17 #define STR(x) _STR(x)
20 #define SYSFS_MAGIC 0x62656572
23 #ifndef PROC_SUPER_MAGIC
24 #define PROC_SUPER_MAGIC 0x9fa0
28 #define DEBUGFS_MAGIC 0x64626720
31 static const char * const sysfs__fs_known_mountpoints[] = {
36 static const char * const procfs__known_mountpoints[] = {
41 #ifndef DEBUGFS_DEFAULT_PATH
42 #define DEBUGFS_DEFAULT_PATH "/sys/kernel/debug"
45 static const char * const debugfs__known_mountpoints[] = {
53 const char * const *mounts;
54 char path[PATH_MAX + 1];
65 static struct fs fs__entries[] = {
68 .mounts = sysfs__fs_known_mountpoints,
73 .mounts = procfs__known_mountpoints,
74 .magic = PROC_SUPER_MAGIC,
78 .mounts = debugfs__known_mountpoints,
79 .magic = DEBUGFS_MAGIC,
83 static bool fs__read_mounts(struct fs *fs)
89 fp = fopen("/proc/mounts", "r");
94 fscanf(fp, "%*s %" STR(PATH_MAX) "s %99s %*s %*d %*d\n",
95 fs->path, type) == 2) {
97 if (strcmp(type, fs->name) == 0)
102 return fs->found = found;
105 static int fs__valid_mount(const char *fs, long magic)
109 if (statfs(fs, &st_fs) < 0)
111 else if ((long)st_fs.f_type != magic)
117 static bool fs__check_mounts(struct fs *fs)
119 const char * const *ptr;
123 if (fs__valid_mount(*ptr, fs->magic) == 0) {
125 strcpy(fs->path, *ptr);
134 static void mem_toupper(char *f, size_t len)
144 * Check for "NAME_PATH" environment variable to override fs location (for
145 * testing). This matches the recommendation in Documentation/sysfs-rules.txt
148 static bool fs__env_override(struct fs *fs)
151 size_t name_len = strlen(fs->name);
152 /* name + "_PATH" + '\0' */
153 char upper_name[name_len + 5 + 1];
154 memcpy(upper_name, fs->name, name_len);
155 mem_toupper(upper_name, name_len);
156 strcpy(&upper_name[name_len], "_PATH");
158 override_path = getenv(upper_name);
163 strncpy(fs->path, override_path, sizeof(fs->path));
167 static const char *fs__get_mountpoint(struct fs *fs)
169 if (fs__env_override(fs))
172 if (fs__check_mounts(fs))
175 if (fs__read_mounts(fs))
181 static const char *fs__mountpoint(int idx)
183 struct fs *fs = &fs__entries[idx];
186 return (const char *)fs->path;
188 return fs__get_mountpoint(fs);
191 #define FS__MOUNTPOINT(name, idx) \
192 const char *name##__mountpoint(void) \
194 return fs__mountpoint(idx); \
197 FS__MOUNTPOINT(sysfs, FS__SYSFS);
198 FS__MOUNTPOINT(procfs, FS__PROCFS);
199 FS__MOUNTPOINT(debugfs, FS__DEBUGFS);
201 int filename__read_int(const char *filename, int *value)
204 int fd = open(filename, O_RDONLY), err = -1;
209 if (read(fd, line, sizeof(line)) > 0) {
218 int sysctl__read_int(const char *sysctl, int *value)
221 const char *procfs = procfs__mountpoint();
226 snprintf(path, sizeof(path), "%s/sys/%s", procfs, sysctl);
228 return filename__read_int(path, value);