3 * Copyright © 2014-2016 Canonical, Inc
4 * Author: Serge Hallyn <serge.hallyn@ubuntu.com>
6 * See COPYING file for details.
9 #define FUSE_USE_VERSION 26
11 #define __STDC_FORMAT_MACROS
28 #include <linux/magic.h>
29 #include <linux/sched.h>
30 #include <sys/epoll.h>
32 #include <sys/mount.h>
33 #include <sys/param.h>
34 #include <sys/socket.h>
35 #include <sys/syscall.h>
36 #include <sys/sysinfo.h>
40 #include "config.h" // for VERSION
42 /* Maximum number for 64 bit integer is a string with 21 digits: 2^64 - 1 = 21 */
43 #define LXCFS_NUMSTRLEN64 21
45 /* Define pivot_root() if missing from the C library */
46 #ifndef HAVE_PIVOT_ROOT
47 static int pivot_root(const char * new_root
, const char * put_old
)
49 #ifdef __NR_pivot_root
50 return syscall(__NR_pivot_root
, new_root
, put_old
);
57 extern int pivot_root(const char * new_root
, const char * put_old
);
63 LXC_TYPE_PROC_MEMINFO
,
64 LXC_TYPE_PROC_CPUINFO
,
67 LXC_TYPE_PROC_DISKSTATS
,
69 LXC_TYPE_PROC_LOADAVG
,
77 char *buf
; // unused as of yet
79 int size
; //actual data size
83 struct cpuacct_usage
{
89 /* The function of hash table.*/
90 #define LOAD_SIZE 100 /*the size of hash_table */
91 #define FLUSH_TIME 5 /*the flush rate */
92 #define DEPTH_DIR 3 /*the depth of per cgroup */
93 /* The function of calculate loadavg .*/
94 #define FSHIFT 11 /* nr of bits of precision */
95 #define FIXED_1 (1<<FSHIFT) /* 1.0 as fixed-point */
96 #define EXP_1 1884 /* 1/exp(5sec/1min) as fixed-point */
97 #define EXP_5 2014 /* 1/exp(5sec/5min) */
98 #define EXP_15 2037 /* 1/exp(5sec/15min) */
99 #define LOAD_INT(x) ((x) >> FSHIFT)
100 #define LOAD_FRAC(x) LOAD_INT(((x) & (FIXED_1-1)) * 100)
102 * This parameter is used for proc_loadavg_read().
103 * 1 means use loadavg, 0 means not use.
105 static int loadavg
= 0;
106 static volatile sig_atomic_t loadavg_stop
= 0;
107 static int calc_hash(const char *name
)
109 unsigned int hash
= 0;
111 /* ELFHash algorithm. */
113 hash
= (hash
<< 4) + *name
++;
114 x
= hash
& 0xf0000000;
119 return (hash
& 0x7fffffff);
124 unsigned long avenrun
[3]; /* Load averages */
125 unsigned int run_pid
;
126 unsigned int total_pid
;
127 unsigned int last_pid
;
128 int cfd
; /* The file descriptor of the mounted cgroup */
129 struct load_node
*next
;
130 struct load_node
**pre
;
135 * The lock is about insert load_node and refresh load_node.To the first
136 * load_node of each hash bucket, insert and refresh in this hash bucket is
137 * mutually exclusive.
139 pthread_mutex_t lock
;
141 * The rdlock is about read loadavg and delete load_node.To each hash
142 * bucket, read and delete is mutually exclusive. But at the same time, we
143 * allow paratactic read operation. This rdlock is at list level.
145 pthread_rwlock_t rdlock
;
147 * The rilock is about read loadavg and insert load_node.To the first
148 * load_node of each hash bucket, read and insert is mutually exclusive.
149 * But at the same time, we allow paratactic read operation.
151 pthread_rwlock_t rilock
;
152 struct load_node
*next
;
155 static struct load_head load_hash
[LOAD_SIZE
]; /* hash table */
157 * init_load initialize the hash table.
158 * Return 0 on success, return -1 on failure.
160 static int init_load(void)
165 for (i
= 0; i
< LOAD_SIZE
; i
++) {
166 load_hash
[i
].next
= NULL
;
167 ret
= pthread_mutex_init(&load_hash
[i
].lock
, NULL
);
169 lxcfs_error("%s\n", "Failed to initialize lock");
172 ret
= pthread_rwlock_init(&load_hash
[i
].rdlock
, NULL
);
174 lxcfs_error("%s\n", "Failed to initialize rdlock");
177 ret
= pthread_rwlock_init(&load_hash
[i
].rilock
, NULL
);
179 lxcfs_error("%s\n", "Failed to initialize rilock");
185 pthread_rwlock_destroy(&load_hash
[i
].rdlock
);
187 pthread_mutex_destroy(&load_hash
[i
].lock
);
191 pthread_mutex_destroy(&load_hash
[i
].lock
);
192 pthread_rwlock_destroy(&load_hash
[i
].rdlock
);
193 pthread_rwlock_destroy(&load_hash
[i
].rilock
);
198 static void insert_node(struct load_node
**n
, int locate
)
202 pthread_mutex_lock(&load_hash
[locate
].lock
);
203 pthread_rwlock_wrlock(&load_hash
[locate
].rilock
);
204 f
= load_hash
[locate
].next
;
205 load_hash
[locate
].next
= *n
;
207 (*n
)->pre
= &(load_hash
[locate
].next
);
209 f
->pre
= &((*n
)->next
);
211 pthread_mutex_unlock(&load_hash
[locate
].lock
);
212 pthread_rwlock_unlock(&load_hash
[locate
].rilock
);
215 * locate_node() finds special node. Not return NULL means success.
216 * It should be noted that rdlock isn't unlocked at the end of code
217 * because this function is used to read special node. Delete is not
218 * allowed before read has ended.
219 * unlock rdlock only in proc_loadavg_read().
221 static struct load_node
*locate_node(char *cg
, int locate
)
223 struct load_node
*f
= NULL
;
226 pthread_rwlock_rdlock(&load_hash
[locate
].rilock
);
227 pthread_rwlock_rdlock(&load_hash
[locate
].rdlock
);
228 if (load_hash
[locate
].next
== NULL
) {
229 pthread_rwlock_unlock(&load_hash
[locate
].rilock
);
232 f
= load_hash
[locate
].next
;
233 pthread_rwlock_unlock(&load_hash
[locate
].rilock
);
234 while (f
&& ((i
= strcmp(f
->cg
, cg
)) != 0))
238 /* Delete the load_node n and return the next node of it. */
239 static struct load_node
*del_node(struct load_node
*n
, int locate
)
243 pthread_rwlock_wrlock(&load_hash
[locate
].rdlock
);
244 if (n
->next
== NULL
) {
248 n
->next
->pre
= n
->pre
;
253 pthread_rwlock_unlock(&load_hash
[locate
].rdlock
);
257 static void load_free(void)
260 struct load_node
*f
, *p
;
262 for (i
= 0; i
< LOAD_SIZE
; i
++) {
263 pthread_mutex_lock(&load_hash
[i
].lock
);
264 pthread_rwlock_wrlock(&load_hash
[i
].rilock
);
265 pthread_rwlock_wrlock(&load_hash
[i
].rdlock
);
266 if (load_hash
[i
].next
== NULL
) {
267 pthread_mutex_unlock(&load_hash
[i
].lock
);
268 pthread_mutex_destroy(&load_hash
[i
].lock
);
269 pthread_rwlock_unlock(&load_hash
[i
].rilock
);
270 pthread_rwlock_destroy(&load_hash
[i
].rilock
);
271 pthread_rwlock_unlock(&load_hash
[i
].rdlock
);
272 pthread_rwlock_destroy(&load_hash
[i
].rdlock
);
275 for (f
= load_hash
[i
].next
; f
; ) {
281 pthread_mutex_unlock(&load_hash
[i
].lock
);
282 pthread_mutex_destroy(&load_hash
[i
].lock
);
283 pthread_rwlock_unlock(&load_hash
[i
].rilock
);
284 pthread_rwlock_destroy(&load_hash
[i
].rilock
);
285 pthread_rwlock_unlock(&load_hash
[i
].rdlock
);
286 pthread_rwlock_destroy(&load_hash
[i
].rdlock
);
290 /* Data for CPU view */
291 struct cg_proc_stat
{
293 struct cpuacct_usage
*usage
; // Real usage as read from the host's /proc/stat
294 struct cpuacct_usage
*view
; // Usage stats reported to the container
296 pthread_mutex_t lock
; // For node manipulation
297 struct cg_proc_stat
*next
;
300 struct cg_proc_stat_head
{
301 struct cg_proc_stat
*next
;
305 * For access to the list. Reading can be parallel, pruning is exclusive.
307 pthread_rwlock_t lock
;
310 #define CPUVIEW_HASH_SIZE 100
311 static struct cg_proc_stat_head
*proc_stat_history
[CPUVIEW_HASH_SIZE
];
313 static bool cpuview_init_head(struct cg_proc_stat_head
**head
)
315 *head
= malloc(sizeof(struct cg_proc_stat_head
));
317 lxcfs_error("%s\n", strerror(errno
));
321 (*head
)->lastcheck
= time(NULL
);
322 (*head
)->next
= NULL
;
324 if (pthread_rwlock_init(&(*head
)->lock
, NULL
) != 0) {
325 lxcfs_error("%s\n", "Failed to initialize list lock");
333 static bool init_cpuview()
337 for (i
= 0; i
< CPUVIEW_HASH_SIZE
; i
++)
338 proc_stat_history
[i
] = NULL
;
340 for (i
= 0; i
< CPUVIEW_HASH_SIZE
; i
++) {
341 if (!cpuview_init_head(&proc_stat_history
[i
]))
348 for (i
= 0; i
< CPUVIEW_HASH_SIZE
; i
++) {
349 if (proc_stat_history
[i
]) {
350 free(proc_stat_history
[i
]);
351 proc_stat_history
[i
] = NULL
;
358 static void free_proc_stat_node(struct cg_proc_stat
*node
)
360 pthread_mutex_destroy(&node
->lock
);
367 static void cpuview_free_head(struct cg_proc_stat_head
*head
)
369 struct cg_proc_stat
*node
, *tmp
;
377 free_proc_stat_node(tmp
);
384 pthread_rwlock_destroy(&head
->lock
);
388 static void free_cpuview()
392 for (i
= 0; i
< CPUVIEW_HASH_SIZE
; i
++) {
393 if (proc_stat_history
[i
])
394 cpuview_free_head(proc_stat_history
[i
]);
398 /* Reserve buffer size to account for file size changes. */
399 #define BUF_RESERVE_SIZE 512
402 * A table caching which pid is init for a pid namespace.
403 * When looking up which pid is init for $qpid, we first
404 * 1. Stat /proc/$qpid/ns/pid.
405 * 2. Check whether the ino_t is in our store.
406 * a. if not, fork a child in qpid's ns to send us
407 * ucred.pid = 1, and read the initpid. Cache
408 * initpid and creation time for /proc/initpid
409 * in a new store entry.
410 * b. if so, verify that /proc/initpid still matches
411 * what we have saved. If not, clear the store
412 * entry and go back to a. If so, return the
415 struct pidns_init_store
{
416 ino_t ino
; // inode number for /proc/$pid/ns/pid
417 pid_t initpid
; // the pid of nit in that ns
418 long int ctime
; // the time at which /proc/$initpid was created
419 struct pidns_init_store
*next
;
423 /* lol - look at how they are allocated in the kernel */
424 #define PIDNS_HASH_SIZE 4096
425 #define HASH(x) ((x) % PIDNS_HASH_SIZE)
427 static struct pidns_init_store
*pidns_hash_table
[PIDNS_HASH_SIZE
];
428 static pthread_mutex_t pidns_store_mutex
= PTHREAD_MUTEX_INITIALIZER
;
429 static void lock_mutex(pthread_mutex_t
*l
)
433 if ((ret
= pthread_mutex_lock(l
)) != 0) {
434 lxcfs_error("returned:%d %s\n", ret
, strerror(ret
));
439 /* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
440 * Number of hierarchies mounted. */
441 static int num_hierarchies
;
443 /* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
444 * Hierachies mounted {cpuset, blkio, ...}:
445 * Initialized via __constructor__ collect_and_mount_subsystems(). */
446 static char **hierarchies
;
448 /* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
449 * Open file descriptors:
450 * @fd_hierarchies[i] refers to cgroup @hierarchies[i]. They are mounted in a
451 * private mount namespace.
452 * Initialized via __constructor__ collect_and_mount_subsystems().
453 * @fd_hierarchies[i] can be used to perform file operations on the cgroup
454 * mounts and respective files in the private namespace even when located in
455 * another namespace using the *at() family of functions
456 * {openat(), fchownat(), ...}. */
457 static int *fd_hierarchies
;
458 static int cgroup_mount_ns_fd
= -1;
460 static void unlock_mutex(pthread_mutex_t
*l
)
464 if ((ret
= pthread_mutex_unlock(l
)) != 0) {
465 lxcfs_error("returned:%d %s\n", ret
, strerror(ret
));
470 static void store_lock(void)
472 lock_mutex(&pidns_store_mutex
);
475 static void store_unlock(void)
477 unlock_mutex(&pidns_store_mutex
);
480 /* Must be called under store_lock */
481 static bool initpid_still_valid(struct pidns_init_store
*e
, struct stat
*nsfdsb
)
486 snprintf(fnam
, 100, "/proc/%d", e
->initpid
);
487 if (stat(fnam
, &initsb
) < 0)
490 lxcfs_debug("Comparing ctime %ld == %ld for pid %d.\n", e
->ctime
,
491 initsb
.st_ctime
, e
->initpid
);
493 if (e
->ctime
!= initsb
.st_ctime
)
498 /* Must be called under store_lock */
499 static void remove_initpid(struct pidns_init_store
*e
)
501 struct pidns_init_store
*tmp
;
504 lxcfs_debug("Remove_initpid: removing entry for %d.\n", e
->initpid
);
507 if (pidns_hash_table
[h
] == e
) {
508 pidns_hash_table
[h
] = e
->next
;
513 tmp
= pidns_hash_table
[h
];
515 if (tmp
->next
== e
) {
525 /* Must be called under store_lock */
526 static void prune_initpid_store(void)
528 static long int last_prune
= 0;
529 struct pidns_init_store
*e
, *prev
, *delme
;
530 long int now
, threshold
;
534 last_prune
= time(NULL
);
538 if (now
< last_prune
+ PURGE_SECS
)
541 lxcfs_debug("%s\n", "Pruning.");
544 threshold
= now
- 2 * PURGE_SECS
;
546 for (i
= 0; i
< PIDNS_HASH_SIZE
; i
++) {
547 for (prev
= NULL
, e
= pidns_hash_table
[i
]; e
; ) {
548 if (e
->lastcheck
< threshold
) {
550 lxcfs_debug("Removing cached entry for %d.\n", e
->initpid
);
554 prev
->next
= e
->next
;
556 pidns_hash_table
[i
] = e
->next
;
567 /* Must be called under store_lock */
568 static void save_initpid(struct stat
*sb
, pid_t pid
)
570 struct pidns_init_store
*e
;
575 lxcfs_debug("Save_initpid: adding entry for %d.\n", pid
);
577 snprintf(fpath
, 100, "/proc/%d", pid
);
578 if (stat(fpath
, &procsb
) < 0)
581 e
= malloc(sizeof(*e
));
585 e
->ctime
= procsb
.st_ctime
;
587 e
->next
= pidns_hash_table
[h
];
588 e
->lastcheck
= time(NULL
);
589 pidns_hash_table
[h
] = e
;
593 * Given the stat(2) info for a nsfd pid inode, lookup the init_pid_store
594 * entry for the inode number and creation time. Verify that the init pid
595 * is still valid. If not, remove it. Return the entry if valid, NULL
597 * Must be called under store_lock
599 static struct pidns_init_store
*lookup_verify_initpid(struct stat
*sb
)
601 int h
= HASH(sb
->st_ino
);
602 struct pidns_init_store
*e
= pidns_hash_table
[h
];
605 if (e
->ino
== sb
->st_ino
) {
606 if (initpid_still_valid(e
, sb
)) {
607 e
->lastcheck
= time(NULL
);
619 static int is_dir(const char *path
, int fd
)
622 int ret
= fstatat(fd
, path
, &statbuf
, fd
);
623 if (ret
== 0 && S_ISDIR(statbuf
.st_mode
))
628 static char *must_copy_string(const char *str
)
640 static inline void drop_trailing_newlines(char *s
)
644 for (l
=strlen(s
); l
>0 && s
[l
-1] == '\n'; l
--)
648 #define BATCH_SIZE 50
649 static void dorealloc(char **mem
, size_t oldlen
, size_t newlen
)
651 int newbatches
= (newlen
/ BATCH_SIZE
) + 1;
652 int oldbatches
= (oldlen
/ BATCH_SIZE
) + 1;
654 if (!*mem
|| newbatches
> oldbatches
) {
657 tmp
= realloc(*mem
, newbatches
* BATCH_SIZE
);
662 static void append_line(char **contents
, size_t *len
, char *line
, ssize_t linelen
)
664 size_t newlen
= *len
+ linelen
;
665 dorealloc(contents
, *len
, newlen
+ 1);
666 memcpy(*contents
+ *len
, line
, linelen
+1);
670 static char *slurp_file(const char *from
, int fd
)
673 char *contents
= NULL
;
674 FILE *f
= fdopen(fd
, "r");
675 size_t len
= 0, fulllen
= 0;
681 while ((linelen
= getline(&line
, &len
, f
)) != -1) {
682 append_line(&contents
, &fulllen
, line
, linelen
);
687 drop_trailing_newlines(contents
);
692 static bool write_string(const char *fnam
, const char *string
, int fd
)
701 len
= strlen(string
);
702 ret
= fwrite(string
, 1, len
, f
);
704 lxcfs_error("%s - Error writing \"%s\" to \"%s\"\n",
705 strerror(errno
), string
, fnam
);
711 lxcfs_error("%s - Failed to close \"%s\"\n", strerror(errno
), fnam
);
725 static bool store_hierarchy(char *stridx
, char *h
)
727 if (num_hierarchies
% ALLOC_NUM
== 0) {
728 size_t n
= (num_hierarchies
/ ALLOC_NUM
) + 1;
730 char **tmp
= realloc(hierarchies
, n
* sizeof(char *));
732 lxcfs_error("%s\n", strerror(errno
));
738 hierarchies
[num_hierarchies
++] = must_copy_string(h
);
742 static void print_subsystems(void)
746 fprintf(stderr
, "mount namespace: %d\n", cgroup_mount_ns_fd
);
747 fprintf(stderr
, "hierarchies:\n");
748 for (i
= 0; i
< num_hierarchies
; i
++) {
750 fprintf(stderr
, " %2d: fd: %3d: %s\n", i
,
751 fd_hierarchies
[i
], hierarchies
[i
]);
755 static bool in_comma_list(const char *needle
, const char *haystack
)
757 const char *s
= haystack
, *e
;
758 size_t nlen
= strlen(needle
);
760 while (*s
&& (e
= strchr(s
, ','))) {
765 if (strncmp(needle
, s
, nlen
) == 0)
769 if (strcmp(needle
, s
) == 0)
774 /* do we need to do any massaging here? I'm not sure... */
775 /* Return the mounted controller and store the corresponding open file descriptor
776 * referring to the controller mountpoint in the private lxcfs namespace in
779 static char *find_mounted_controller(const char *controller
, int *cfd
)
783 for (i
= 0; i
< num_hierarchies
; i
++) {
786 if (strcmp(hierarchies
[i
], controller
) == 0) {
787 *cfd
= fd_hierarchies
[i
];
788 return hierarchies
[i
];
790 if (in_comma_list(controller
, hierarchies
[i
])) {
791 *cfd
= fd_hierarchies
[i
];
792 return hierarchies
[i
];
799 bool cgfs_set_value(const char *controller
, const char *cgroup
, const char *file
,
806 tmpc
= find_mounted_controller(controller
, &cfd
);
810 /* Make sure we pass a relative path to *at() family of functions.
811 * . + /cgroup + / + file + \0
813 len
= strlen(cgroup
) + strlen(file
) + 3;
815 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, file
);
816 if (ret
< 0 || (size_t)ret
>= len
)
819 fd
= openat(cfd
, fnam
, O_WRONLY
);
823 return write_string(fnam
, value
, fd
);
826 // Chown all the files in the cgroup directory. We do this when we create
827 // a cgroup on behalf of a user.
828 static void chown_all_cgroup_files(const char *dirname
, uid_t uid
, gid_t gid
, int fd
)
830 struct dirent
*direntp
;
831 char path
[MAXPATHLEN
];
836 len
= strlen(dirname
);
837 if (len
>= MAXPATHLEN
) {
838 lxcfs_error("Pathname too long: %s\n", dirname
);
842 fd1
= openat(fd
, dirname
, O_DIRECTORY
);
848 lxcfs_error("Failed to open %s\n", dirname
);
852 while ((direntp
= readdir(d
))) {
853 if (!strcmp(direntp
->d_name
, ".") || !strcmp(direntp
->d_name
, ".."))
855 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
856 if (ret
< 0 || ret
>= MAXPATHLEN
) {
857 lxcfs_error("Pathname too long under %s\n", dirname
);
860 if (fchownat(fd
, path
, uid
, gid
, 0) < 0)
861 lxcfs_error("Failed to chown file %s to %u:%u", path
, uid
, gid
);
866 int cgfs_create(const char *controller
, const char *cg
, uid_t uid
, gid_t gid
)
872 tmpc
= find_mounted_controller(controller
, &cfd
);
876 /* Make sure we pass a relative path to *at() family of functions.
879 len
= strlen(cg
) + 2;
880 dirnam
= alloca(len
);
881 snprintf(dirnam
, len
, "%s%s", *cg
== '/' ? "." : "", cg
);
883 if (mkdirat(cfd
, dirnam
, 0755) < 0)
886 if (uid
== 0 && gid
== 0)
889 if (fchownat(cfd
, dirnam
, uid
, gid
, 0) < 0)
892 chown_all_cgroup_files(dirnam
, uid
, gid
, cfd
);
897 static bool recursive_rmdir(const char *dirname
, int fd
, const int cfd
)
899 struct dirent
*direntp
;
902 char pathname
[MAXPATHLEN
];
905 dupfd
= dup(fd
); // fdopendir() does bad things once it uses an fd.
909 dir
= fdopendir(dupfd
);
911 lxcfs_debug("Failed to open %s: %s.\n", dirname
, strerror(errno
));
916 while ((direntp
= readdir(dir
))) {
920 if (!strcmp(direntp
->d_name
, ".") ||
921 !strcmp(direntp
->d_name
, ".."))
924 rc
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
925 if (rc
< 0 || rc
>= MAXPATHLEN
) {
926 lxcfs_error("%s\n", "Pathname too long.");
930 rc
= fstatat(cfd
, pathname
, &mystat
, AT_SYMLINK_NOFOLLOW
);
932 lxcfs_debug("Failed to stat %s: %s.\n", pathname
, strerror(errno
));
935 if (S_ISDIR(mystat
.st_mode
))
936 if (!recursive_rmdir(pathname
, fd
, cfd
))
937 lxcfs_debug("Error removing %s.\n", pathname
);
941 if (closedir(dir
) < 0) {
942 lxcfs_error("Failed to close directory %s: %s\n", dirname
, strerror(errno
));
946 if (unlinkat(cfd
, dirname
, AT_REMOVEDIR
) < 0) {
947 lxcfs_debug("Failed to delete %s: %s.\n", dirname
, strerror(errno
));
956 bool cgfs_remove(const char *controller
, const char *cg
)
963 tmpc
= find_mounted_controller(controller
, &cfd
);
967 /* Make sure we pass a relative path to *at() family of functions.
970 len
= strlen(cg
) + 2;
971 dirnam
= alloca(len
);
972 snprintf(dirnam
, len
, "%s%s", *cg
== '/' ? "." : "", cg
);
974 fd
= openat(cfd
, dirnam
, O_DIRECTORY
);
978 bret
= recursive_rmdir(dirnam
, fd
, cfd
);
983 bool cgfs_chmod_file(const char *controller
, const char *file
, mode_t mode
)
987 char *pathname
, *tmpc
;
989 tmpc
= find_mounted_controller(controller
, &cfd
);
993 /* Make sure we pass a relative path to *at() family of functions.
996 len
= strlen(file
) + 2;
997 pathname
= alloca(len
);
998 snprintf(pathname
, len
, "%s%s", *file
== '/' ? "." : "", file
);
999 if (fchmodat(cfd
, pathname
, mode
, 0) < 0)
1004 static int chown_tasks_files(const char *dirname
, uid_t uid
, gid_t gid
, int fd
)
1009 len
= strlen(dirname
) + strlen("/cgroup.procs") + 1;
1010 fname
= alloca(len
);
1011 snprintf(fname
, len
, "%s/tasks", dirname
);
1012 if (fchownat(fd
, fname
, uid
, gid
, 0) != 0)
1014 snprintf(fname
, len
, "%s/cgroup.procs", dirname
);
1015 if (fchownat(fd
, fname
, uid
, gid
, 0) != 0)
1020 int cgfs_chown_file(const char *controller
, const char *file
, uid_t uid
, gid_t gid
)
1024 char *pathname
, *tmpc
;
1026 tmpc
= find_mounted_controller(controller
, &cfd
);
1030 /* Make sure we pass a relative path to *at() family of functions.
1033 len
= strlen(file
) + 2;
1034 pathname
= alloca(len
);
1035 snprintf(pathname
, len
, "%s%s", *file
== '/' ? "." : "", file
);
1036 if (fchownat(cfd
, pathname
, uid
, gid
, 0) < 0)
1039 if (is_dir(pathname
, cfd
))
1040 // like cgmanager did, we want to chown the tasks file as well
1041 return chown_tasks_files(pathname
, uid
, gid
, cfd
);
1046 FILE *open_pids_file(const char *controller
, const char *cgroup
)
1050 char *pathname
, *tmpc
;
1052 tmpc
= find_mounted_controller(controller
, &cfd
);
1056 /* Make sure we pass a relative path to *at() family of functions.
1057 * . + /cgroup + / "cgroup.procs" + \0
1059 len
= strlen(cgroup
) + strlen("cgroup.procs") + 3;
1060 pathname
= alloca(len
);
1061 snprintf(pathname
, len
, "%s%s/cgroup.procs", *cgroup
== '/' ? "." : "", cgroup
);
1063 fd
= openat(cfd
, pathname
, O_WRONLY
);
1067 return fdopen(fd
, "w");
1070 static bool cgfs_iterate_cgroup(const char *controller
, const char *cgroup
, bool directories
,
1071 void ***list
, size_t typesize
,
1072 void* (*iterator
)(const char*, const char*, const char*))
1077 char pathname
[MAXPATHLEN
];
1078 size_t sz
= 0, asz
= 0;
1079 struct dirent
*dirent
;
1082 tmpc
= find_mounted_controller(controller
, &cfd
);
1087 /* Make sure we pass a relative path to *at() family of functions. */
1088 len
= strlen(cgroup
) + 1 /* . */ + 1 /* \0 */;
1090 ret
= snprintf(cg
, len
, "%s%s", *cgroup
== '/' ? "." : "", cgroup
);
1091 if (ret
< 0 || (size_t)ret
>= len
) {
1092 lxcfs_error("Pathname too long under %s\n", cgroup
);
1096 fd
= openat(cfd
, cg
, O_DIRECTORY
);
1100 dir
= fdopendir(fd
);
1104 while ((dirent
= readdir(dir
))) {
1107 if (!strcmp(dirent
->d_name
, ".") ||
1108 !strcmp(dirent
->d_name
, ".."))
1111 ret
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", cg
, dirent
->d_name
);
1112 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1113 lxcfs_error("Pathname too long under %s\n", cg
);
1117 ret
= fstatat(cfd
, pathname
, &mystat
, AT_SYMLINK_NOFOLLOW
);
1119 lxcfs_error("Failed to stat %s: %s\n", pathname
, strerror(errno
));
1122 if ((!directories
&& !S_ISREG(mystat
.st_mode
)) ||
1123 (directories
&& !S_ISDIR(mystat
.st_mode
)))
1130 tmp
= realloc(*list
, asz
* typesize
);
1134 (*list
)[sz
] = (*iterator
)(controller
, cg
, dirent
->d_name
);
1135 (*list
)[sz
+1] = NULL
;
1138 if (closedir(dir
) < 0) {
1139 lxcfs_error("Failed closedir for %s: %s\n", cgroup
, strerror(errno
));
1145 static void *make_children_list_entry(const char *controller
, const char *cgroup
, const char *dir_entry
)
1149 dup
= strdup(dir_entry
);
1154 bool cgfs_list_children(const char *controller
, const char *cgroup
, char ***list
)
1156 return cgfs_iterate_cgroup(controller
, cgroup
, true, (void***)list
, sizeof(*list
), &make_children_list_entry
);
1159 void free_key(struct cgfs_files
*k
)
1167 void free_keys(struct cgfs_files
**keys
)
1173 for (i
= 0; keys
[i
]; i
++) {
1179 bool cgfs_get_value(const char *controller
, const char *cgroup
, const char *file
, char **value
)
1185 tmpc
= find_mounted_controller(controller
, &cfd
);
1189 /* Make sure we pass a relative path to *at() family of functions.
1190 * . + /cgroup + / + file + \0
1192 len
= strlen(cgroup
) + strlen(file
) + 3;
1194 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, file
);
1195 if (ret
< 0 || (size_t)ret
>= len
)
1198 fd
= openat(cfd
, fnam
, O_RDONLY
);
1202 *value
= slurp_file(fnam
, fd
);
1203 return *value
!= NULL
;
1206 bool cgfs_param_exist(const char *controller
, const char *cgroup
, const char *file
)
1212 tmpc
= find_mounted_controller(controller
, &cfd
);
1216 /* Make sure we pass a relative path to *at() family of functions.
1217 * . + /cgroup + / + file + \0
1219 len
= strlen(cgroup
) + strlen(file
) + 3;
1221 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, file
);
1222 if (ret
< 0 || (size_t)ret
>= len
)
1225 return (faccessat(cfd
, fnam
, F_OK
, 0) == 0);
1228 struct cgfs_files
*cgfs_get_key(const char *controller
, const char *cgroup
, const char *file
)
1234 struct cgfs_files
*newkey
;
1236 tmpc
= find_mounted_controller(controller
, &cfd
);
1240 if (file
&& *file
== '/')
1243 if (file
&& strchr(file
, '/'))
1246 /* Make sure we pass a relative path to *at() family of functions.
1247 * . + /cgroup + / + file + \0
1249 len
= strlen(cgroup
) + 3;
1251 len
+= strlen(file
) + 1;
1253 snprintf(fnam
, len
, "%s%s%s%s", *cgroup
== '/' ? "." : "", cgroup
,
1254 file
? "/" : "", file
? file
: "");
1256 ret
= fstatat(cfd
, fnam
, &sb
, 0);
1261 newkey
= malloc(sizeof(struct cgfs_files
));
1264 newkey
->name
= must_copy_string(file
);
1265 else if (strrchr(cgroup
, '/'))
1266 newkey
->name
= must_copy_string(strrchr(cgroup
, '/'));
1268 newkey
->name
= must_copy_string(cgroup
);
1269 newkey
->uid
= sb
.st_uid
;
1270 newkey
->gid
= sb
.st_gid
;
1271 newkey
->mode
= sb
.st_mode
;
1276 static void *make_key_list_entry(const char *controller
, const char *cgroup
, const char *dir_entry
)
1278 struct cgfs_files
*entry
= cgfs_get_key(controller
, cgroup
, dir_entry
);
1280 lxcfs_error("Error getting files under %s:%s\n", controller
,
1286 bool cgfs_list_keys(const char *controller
, const char *cgroup
, struct cgfs_files
***keys
)
1288 return cgfs_iterate_cgroup(controller
, cgroup
, false, (void***)keys
, sizeof(*keys
), &make_key_list_entry
);
1291 bool is_child_cgroup(const char *controller
, const char *cgroup
, const char *f
)
1299 tmpc
= find_mounted_controller(controller
, &cfd
);
1303 /* Make sure we pass a relative path to *at() family of functions.
1304 * . + /cgroup + / + f + \0
1306 len
= strlen(cgroup
) + strlen(f
) + 3;
1308 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, f
);
1309 if (ret
< 0 || (size_t)ret
>= len
)
1312 ret
= fstatat(cfd
, fnam
, &sb
, 0);
1313 if (ret
< 0 || !S_ISDIR(sb
.st_mode
))
1319 #define SEND_CREDS_OK 0
1320 #define SEND_CREDS_NOTSK 1
1321 #define SEND_CREDS_FAIL 2
1322 static bool recv_creds(int sock
, struct ucred
*cred
, char *v
);
1323 static int wait_for_pid(pid_t pid
);
1324 static int send_creds(int sock
, struct ucred
*cred
, char v
, bool pingfirst
);
1325 static int send_creds_clone_wrapper(void *arg
);
1328 * clone a task which switches to @task's namespace and writes '1'.
1329 * over a unix sock so we can read the task's reaper's pid in our
1332 * Note: glibc's fork() does not respect pidns, which can lead to failed
1333 * assertions inside glibc (and thus failed forks) if the child's pid in
1334 * the pidns and the parent pid outside are identical. Using clone prevents
1337 static void write_task_init_pid_exit(int sock
, pid_t target
)
1342 size_t stack_size
= sysconf(_SC_PAGESIZE
);
1343 void *stack
= alloca(stack_size
);
1345 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", (int)target
);
1346 if (ret
< 0 || ret
>= sizeof(fnam
))
1349 fd
= open(fnam
, O_RDONLY
);
1351 perror("write_task_init_pid_exit open of ns/pid");
1355 perror("write_task_init_pid_exit setns 1");
1359 pid
= clone(send_creds_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &sock
);
1363 if (!wait_for_pid(pid
))
1369 static int send_creds_clone_wrapper(void *arg
) {
1372 int sock
= *(int *)arg
;
1374 /* we are the child */
1379 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
)
1384 static pid_t
get_init_pid_for_task(pid_t task
)
1392 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
1393 perror("socketpair");
1402 write_task_init_pid_exit(sock
[0], task
);
1406 if (!recv_creds(sock
[1], &cred
, &v
))
1418 static pid_t
lookup_initpid_in_store(pid_t qpid
)
1422 struct pidns_init_store
*e
;
1425 snprintf(fnam
, 100, "/proc/%d/ns/pid", qpid
);
1427 if (stat(fnam
, &sb
) < 0)
1429 e
= lookup_verify_initpid(&sb
);
1431 answer
= e
->initpid
;
1434 answer
= get_init_pid_for_task(qpid
);
1436 save_initpid(&sb
, answer
);
1439 /* we prune at end in case we are returning
1440 * the value we were about to return */
1441 prune_initpid_store();
1446 static int wait_for_pid(pid_t pid
)
1454 ret
= waitpid(pid
, &status
, 0);
1462 if (!WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
1469 * append pid to *src.
1470 * src: a pointer to a char* in which ot append the pid.
1471 * sz: the number of characters printed so far, minus trailing \0.
1472 * asz: the allocated size so far
1473 * pid: the pid to append
1475 static void must_strcat_pid(char **src
, size_t *sz
, size_t *asz
, pid_t pid
)
1479 int tmplen
= sprintf(tmp
, "%d\n", (int)pid
);
1481 if (!*src
|| tmplen
+ *sz
+ 1 >= *asz
) {
1484 tmp
= realloc(*src
, *asz
+ BUF_RESERVE_SIZE
);
1487 *asz
+= BUF_RESERVE_SIZE
;
1489 memcpy((*src
) +*sz
, tmp
, tmplen
+1); /* include the \0 */
1494 * Given a open file * to /proc/pid/{u,g}id_map, and an id
1495 * valid in the caller's namespace, return the id mapped into
1497 * Returns the mapped id, or -1 on error.
1500 convert_id_to_ns(FILE *idfile
, unsigned int in_id
)
1502 unsigned int nsuid
, // base id for a range in the idfile's namespace
1503 hostuid
, // base id for a range in the caller's namespace
1504 count
; // number of ids in this range
1508 fseek(idfile
, 0L, SEEK_SET
);
1509 while (fgets(line
, 400, idfile
)) {
1510 ret
= sscanf(line
, "%u %u %u\n", &nsuid
, &hostuid
, &count
);
1513 if (hostuid
+ count
< hostuid
|| nsuid
+ count
< nsuid
) {
1515 * uids wrapped around - unexpected as this is a procfile,
1518 lxcfs_error("pid wrapparound at entry %u %u %u in %s\n",
1519 nsuid
, hostuid
, count
, line
);
1522 if (hostuid
<= in_id
&& hostuid
+count
> in_id
) {
1524 * now since hostuid <= in_id < hostuid+count, and
1525 * hostuid+count and nsuid+count do not wrap around,
1526 * we know that nsuid+(in_id-hostuid) which must be
1527 * less that nsuid+(count) must not wrap around
1529 return (in_id
- hostuid
) + nsuid
;
1538 * for is_privileged_over,
1539 * specify whether we require the calling uid to be root in his
1542 #define NS_ROOT_REQD true
1543 #define NS_ROOT_OPT false
1547 static bool is_privileged_over(pid_t pid
, uid_t uid
, uid_t victim
, bool req_ns_root
)
1549 char fpath
[PROCLEN
];
1551 bool answer
= false;
1554 if (victim
== -1 || uid
== -1)
1558 * If the request is one not requiring root in the namespace,
1559 * then having the same uid suffices. (i.e. uid 1000 has write
1560 * access to files owned by uid 1000
1562 if (!req_ns_root
&& uid
== victim
)
1565 ret
= snprintf(fpath
, PROCLEN
, "/proc/%d/uid_map", pid
);
1566 if (ret
< 0 || ret
>= PROCLEN
)
1568 FILE *f
= fopen(fpath
, "r");
1572 /* if caller's not root in his namespace, reject */
1573 nsuid
= convert_id_to_ns(f
, uid
);
1578 * If victim is not mapped into caller's ns, reject.
1579 * XXX I'm not sure this check is needed given that fuse
1580 * will be sending requests where the vfs has converted
1582 nsuid
= convert_id_to_ns(f
, victim
);
1593 static bool perms_include(int fmode
, mode_t req_mode
)
1597 switch (req_mode
& O_ACCMODE
) {
1605 r
= S_IROTH
| S_IWOTH
;
1610 return ((fmode
& r
) == r
);
1616 * querycg is /a/b/c/d/e
1619 static char *get_next_cgroup_dir(const char *taskcg
, const char *querycg
)
1623 if (strlen(taskcg
) <= strlen(querycg
)) {
1624 lxcfs_error("%s\n", "I was fed bad input.");
1628 if ((strcmp(querycg
, "/") == 0) || (strcmp(querycg
, "./") == 0))
1629 start
= strdup(taskcg
+ 1);
1631 start
= strdup(taskcg
+ strlen(querycg
) + 1);
1634 end
= strchr(start
, '/');
1640 static void stripnewline(char *x
)
1642 size_t l
= strlen(x
);
1643 if (l
&& x
[l
-1] == '\n')
1647 static char *get_pid_cgroup(pid_t pid
, const char *contrl
)
1652 char *answer
= NULL
;
1656 const char *h
= find_mounted_controller(contrl
, &cfd
);
1660 ret
= snprintf(fnam
, PROCLEN
, "/proc/%d/cgroup", pid
);
1661 if (ret
< 0 || ret
>= PROCLEN
)
1663 if (!(f
= fopen(fnam
, "r")))
1666 while (getline(&line
, &len
, f
) != -1) {
1670 c1
= strchr(line
, ':');
1674 c2
= strchr(c1
, ':');
1678 if (strcmp(c1
, h
) != 0)
1683 answer
= strdup(c2
);
1695 * check whether a fuse context may access a cgroup dir or file
1697 * If file is not null, it is a cgroup file to check under cg.
1698 * If file is null, then we are checking perms on cg itself.
1700 * For files we can check the mode of the list_keys result.
1701 * For cgroups, we must make assumptions based on the files under the
1702 * cgroup, because cgmanager doesn't tell us ownership/perms of cgroups
1705 static bool fc_may_access(struct fuse_context
*fc
, const char *contrl
, const char *cg
, const char *file
, mode_t mode
)
1707 struct cgfs_files
*k
= NULL
;
1710 k
= cgfs_get_key(contrl
, cg
, file
);
1714 if (is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
1715 if (perms_include(k
->mode
>> 6, mode
)) {
1720 if (fc
->gid
== k
->gid
) {
1721 if (perms_include(k
->mode
>> 3, mode
)) {
1726 ret
= perms_include(k
->mode
, mode
);
1733 #define INITSCOPE "/init.scope"
1734 static void prune_init_slice(char *cg
)
1737 size_t cg_len
= strlen(cg
), initscope_len
= strlen(INITSCOPE
);
1739 if (cg_len
< initscope_len
)
1742 point
= cg
+ cg_len
- initscope_len
;
1743 if (strcmp(point
, INITSCOPE
) == 0) {
1752 * If pid is in /a/b/c/d, he may only act on things under cg=/a/b/c/d.
1753 * If pid is in /a, he may act on /a/b, but not on /b.
1754 * if the answer is false and nextcg is not NULL, then *nextcg will point
1755 * to a string containing the next cgroup directory under cg, which must be
1756 * freed by the caller.
1758 static bool caller_is_in_ancestor(pid_t pid
, const char *contrl
, const char *cg
, char **nextcg
)
1760 bool answer
= false;
1761 char *c2
= get_pid_cgroup(pid
, contrl
);
1766 prune_init_slice(c2
);
1769 * callers pass in '/' or './' (openat()) for root cgroup, otherwise
1770 * they pass in a cgroup without leading '/'
1772 * The original line here was:
1773 * linecmp = *cg == '/' ? c2 : c2+1;
1774 * TODO: I'm not sure why you'd want to increment when *cg != '/'?
1775 * Serge, do you know?
1777 if (*cg
== '/' || !strncmp(cg
, "./", 2))
1781 if (strncmp(linecmp
, cg
, strlen(linecmp
)) != 0) {
1783 *nextcg
= get_next_cgroup_dir(linecmp
, cg
);
1795 * If pid is in /a/b/c, he may see that /a exists, but not /b or /a/c.
1797 static bool caller_may_see_dir(pid_t pid
, const char *contrl
, const char *cg
)
1799 bool answer
= false;
1801 size_t target_len
, task_len
;
1803 if (strcmp(cg
, "/") == 0 || strcmp(cg
, "./") == 0)
1806 c2
= get_pid_cgroup(pid
, contrl
);
1809 prune_init_slice(c2
);
1812 target_len
= strlen(cg
);
1813 task_len
= strlen(task_cg
);
1814 if (task_len
== 0) {
1815 /* Task is in the root cg, it can see everything. This case is
1816 * not handled by the strmcps below, since they test for the
1817 * last /, but that is the first / that we've chopped off
1823 if (strcmp(cg
, task_cg
) == 0) {
1827 if (target_len
< task_len
) {
1828 /* looking up a parent dir */
1829 if (strncmp(task_cg
, cg
, target_len
) == 0 && task_cg
[target_len
] == '/')
1833 if (target_len
> task_len
) {
1834 /* looking up a child dir */
1835 if (strncmp(task_cg
, cg
, task_len
) == 0 && cg
[task_len
] == '/')
1846 * given /cgroup/freezer/a/b, return "freezer".
1847 * the returned char* should NOT be freed.
1849 static char *pick_controller_from_path(struct fuse_context
*fc
, const char *path
)
1852 char *contr
, *slash
;
1854 if (strlen(path
) < 9) {
1858 if (*(path
+ 7) != '/') {
1863 contr
= strdupa(p1
);
1868 slash
= strstr(contr
, "/");
1873 for (i
= 0; i
< num_hierarchies
; i
++) {
1874 if (hierarchies
[i
] && strcmp(hierarchies
[i
], contr
) == 0)
1875 return hierarchies
[i
];
1882 * Find the start of cgroup in /cgroup/controller/the/cgroup/path
1883 * Note that the returned value may include files (keynames) etc
1885 static const char *find_cgroup_in_path(const char *path
)
1889 if (strlen(path
) < 9) {
1893 p1
= strstr(path
+ 8, "/");
1903 * split the last path element from the path in @cg.
1904 * @dir is newly allocated and should be freed, @last not
1906 static void get_cgdir_and_path(const char *cg
, char **dir
, char **last
)
1913 *last
= strrchr(cg
, '/');
1918 p
= strrchr(*dir
, '/');
1923 * FUSE ops for /cgroup
1926 int cg_getattr(const char *path
, struct stat
*sb
)
1928 struct timespec now
;
1929 struct fuse_context
*fc
= fuse_get_context();
1930 char * cgdir
= NULL
;
1931 char *last
= NULL
, *path1
, *path2
;
1932 struct cgfs_files
*k
= NULL
;
1934 const char *controller
= NULL
;
1941 memset(sb
, 0, sizeof(struct stat
));
1943 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
1946 sb
->st_uid
= sb
->st_gid
= 0;
1947 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
1950 if (strcmp(path
, "/cgroup") == 0) {
1951 sb
->st_mode
= S_IFDIR
| 00755;
1956 controller
= pick_controller_from_path(fc
, path
);
1959 cgroup
= find_cgroup_in_path(path
);
1961 /* this is just /cgroup/controller, return it as a dir */
1962 sb
->st_mode
= S_IFDIR
| 00755;
1967 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
1977 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1980 /* check that cgcopy is either a child cgroup of cgdir, or listed in its keys.
1981 * Then check that caller's cgroup is under path if last is a child
1982 * cgroup, or cgdir if last is a file */
1984 if (is_child_cgroup(controller
, path1
, path2
)) {
1985 if (!caller_may_see_dir(initpid
, controller
, cgroup
)) {
1989 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, NULL
)) {
1990 /* this is just /cgroup/controller, return it as a dir */
1991 sb
->st_mode
= S_IFDIR
| 00555;
1996 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
)) {
2001 // get uid, gid, from '/tasks' file and make up a mode
2002 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
2003 sb
->st_mode
= S_IFDIR
| 00755;
2004 k
= cgfs_get_key(controller
, cgroup
, NULL
);
2006 sb
->st_uid
= sb
->st_gid
= 0;
2008 sb
->st_uid
= k
->uid
;
2009 sb
->st_gid
= k
->gid
;
2017 if ((k
= cgfs_get_key(controller
, path1
, path2
)) != NULL
) {
2018 sb
->st_mode
= S_IFREG
| k
->mode
;
2020 sb
->st_uid
= k
->uid
;
2021 sb
->st_gid
= k
->gid
;
2024 if (!caller_is_in_ancestor(initpid
, controller
, path1
, NULL
)) {
2036 int cg_opendir(const char *path
, struct fuse_file_info
*fi
)
2038 struct fuse_context
*fc
= fuse_get_context();
2040 struct file_info
*dir_info
;
2041 char *controller
= NULL
;
2046 if (strcmp(path
, "/cgroup") == 0) {
2050 // return list of keys for the controller, and list of child cgroups
2051 controller
= pick_controller_from_path(fc
, path
);
2055 cgroup
= find_cgroup_in_path(path
);
2057 /* this is just /cgroup/controller, return its contents */
2062 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2066 if (!caller_may_see_dir(initpid
, controller
, cgroup
))
2068 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
))
2072 /* we'll free this at cg_releasedir */
2073 dir_info
= malloc(sizeof(*dir_info
));
2076 dir_info
->controller
= must_copy_string(controller
);
2077 dir_info
->cgroup
= must_copy_string(cgroup
);
2078 dir_info
->type
= LXC_TYPE_CGDIR
;
2079 dir_info
->buf
= NULL
;
2080 dir_info
->file
= NULL
;
2081 dir_info
->buflen
= 0;
2083 fi
->fh
= (unsigned long)dir_info
;
2087 int cg_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
2088 struct fuse_file_info
*fi
)
2090 struct file_info
*d
= (struct file_info
*)fi
->fh
;
2091 struct cgfs_files
**list
= NULL
;
2093 char *nextcg
= NULL
;
2094 struct fuse_context
*fc
= fuse_get_context();
2095 char **clist
= NULL
;
2097 if (filler(buf
, ".", NULL
, 0) != 0 || filler(buf
, "..", NULL
, 0) != 0)
2100 if (d
->type
!= LXC_TYPE_CGDIR
) {
2101 lxcfs_error("%s\n", "Internal error: file cache info used in readdir.");
2104 if (!d
->cgroup
&& !d
->controller
) {
2105 // ls /var/lib/lxcfs/cgroup - just show list of controllers
2108 for (i
= 0; i
< num_hierarchies
; i
++) {
2109 if (hierarchies
[i
] && filler(buf
, hierarchies
[i
], NULL
, 0) != 0) {
2116 if (!cgfs_list_keys(d
->controller
, d
->cgroup
, &list
)) {
2117 // not a valid cgroup
2122 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2125 if (!caller_is_in_ancestor(initpid
, d
->controller
, d
->cgroup
, &nextcg
)) {
2127 ret
= filler(buf
, nextcg
, NULL
, 0);
2138 for (i
= 0; list
[i
]; i
++) {
2139 if (filler(buf
, list
[i
]->name
, NULL
, 0) != 0) {
2145 // now get the list of child cgroups
2147 if (!cgfs_list_children(d
->controller
, d
->cgroup
, &clist
)) {
2152 for (i
= 0; clist
[i
]; i
++) {
2153 if (filler(buf
, clist
[i
], NULL
, 0) != 0) {
2164 for (i
= 0; clist
[i
]; i
++)
2171 static void do_release_file_info(struct fuse_file_info
*fi
)
2173 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2180 free(f
->controller
);
2181 f
->controller
= NULL
;
2192 int cg_releasedir(const char *path
, struct fuse_file_info
*fi
)
2194 do_release_file_info(fi
);
2198 int cg_open(const char *path
, struct fuse_file_info
*fi
)
2201 char *last
= NULL
, *path1
, *path2
, * cgdir
= NULL
, *controller
;
2202 struct cgfs_files
*k
= NULL
;
2203 struct file_info
*file_info
;
2204 struct fuse_context
*fc
= fuse_get_context();
2210 controller
= pick_controller_from_path(fc
, path
);
2213 cgroup
= find_cgroup_in_path(path
);
2217 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2226 k
= cgfs_get_key(controller
, path1
, path2
);
2233 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2236 if (!caller_may_see_dir(initpid
, controller
, path1
)) {
2240 if (!fc_may_access(fc
, controller
, path1
, path2
, fi
->flags
)) {
2245 /* we'll free this at cg_release */
2246 file_info
= malloc(sizeof(*file_info
));
2251 file_info
->controller
= must_copy_string(controller
);
2252 file_info
->cgroup
= must_copy_string(path1
);
2253 file_info
->file
= must_copy_string(path2
);
2254 file_info
->type
= LXC_TYPE_CGFILE
;
2255 file_info
->buf
= NULL
;
2256 file_info
->buflen
= 0;
2258 fi
->fh
= (unsigned long)file_info
;
2266 int cg_access(const char *path
, int mode
)
2270 char *path1
, *path2
, *controller
;
2271 char *last
= NULL
, *cgdir
= NULL
;
2272 struct cgfs_files
*k
= NULL
;
2273 struct fuse_context
*fc
= fuse_get_context();
2275 if (strcmp(path
, "/cgroup") == 0)
2281 controller
= pick_controller_from_path(fc
, path
);
2284 cgroup
= find_cgroup_in_path(path
);
2286 // access("/sys/fs/cgroup/systemd", mode) - rx allowed, w not
2287 if ((mode
& W_OK
) == 0)
2292 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2301 k
= cgfs_get_key(controller
, path1
, path2
);
2303 if ((mode
& W_OK
) == 0)
2311 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2314 if (!caller_may_see_dir(initpid
, controller
, path1
)) {
2318 if (!fc_may_access(fc
, controller
, path1
, path2
, mode
)) {
2330 int cg_release(const char *path
, struct fuse_file_info
*fi
)
2332 do_release_file_info(fi
);
2336 #define POLLIN_SET ( EPOLLIN | EPOLLHUP | EPOLLRDHUP )
2338 static bool wait_for_sock(int sock
, int timeout
)
2340 struct epoll_event ev
;
2341 int epfd
, ret
, now
, starttime
, deltatime
, saved_errno
;
2343 if ((starttime
= time(NULL
)) < 0)
2346 if ((epfd
= epoll_create(1)) < 0) {
2347 lxcfs_error("%s\n", "Failed to create epoll socket: %m.");
2351 ev
.events
= POLLIN_SET
;
2353 if (epoll_ctl(epfd
, EPOLL_CTL_ADD
, sock
, &ev
) < 0) {
2354 lxcfs_error("%s\n", "Failed adding socket to epoll: %m.");
2360 if ((now
= time(NULL
)) < 0) {
2365 deltatime
= (starttime
+ timeout
) - now
;
2366 if (deltatime
< 0) { // timeout
2371 ret
= epoll_wait(epfd
, &ev
, 1, 1000*deltatime
+ 1);
2372 if (ret
< 0 && errno
== EINTR
)
2374 saved_errno
= errno
;
2378 errno
= saved_errno
;
2384 static int msgrecv(int sockfd
, void *buf
, size_t len
)
2386 if (!wait_for_sock(sockfd
, 2))
2388 return recv(sockfd
, buf
, len
, MSG_DONTWAIT
);
2391 static int send_creds(int sock
, struct ucred
*cred
, char v
, bool pingfirst
)
2393 struct msghdr msg
= { 0 };
2395 struct cmsghdr
*cmsg
;
2396 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
2401 if (msgrecv(sock
, buf
, 1) != 1) {
2402 lxcfs_error("%s\n", "Error getting reply from server over socketpair.");
2403 return SEND_CREDS_FAIL
;
2407 msg
.msg_control
= cmsgbuf
;
2408 msg
.msg_controllen
= sizeof(cmsgbuf
);
2410 cmsg
= CMSG_FIRSTHDR(&msg
);
2411 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct ucred
));
2412 cmsg
->cmsg_level
= SOL_SOCKET
;
2413 cmsg
->cmsg_type
= SCM_CREDENTIALS
;
2414 memcpy(CMSG_DATA(cmsg
), cred
, sizeof(*cred
));
2416 msg
.msg_name
= NULL
;
2417 msg
.msg_namelen
= 0;
2421 iov
.iov_len
= sizeof(buf
);
2425 if (sendmsg(sock
, &msg
, 0) < 0) {
2426 lxcfs_error("Failed at sendmsg: %s.\n",strerror(errno
));
2428 return SEND_CREDS_NOTSK
;
2429 return SEND_CREDS_FAIL
;
2432 return SEND_CREDS_OK
;
2435 static bool recv_creds(int sock
, struct ucred
*cred
, char *v
)
2437 struct msghdr msg
= { 0 };
2439 struct cmsghdr
*cmsg
;
2440 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
2451 if (setsockopt(sock
, SOL_SOCKET
, SO_PASSCRED
, &optval
, sizeof(optval
)) == -1) {
2452 lxcfs_error("Failed to set passcred: %s\n", strerror(errno
));
2456 if (write(sock
, buf
, 1) != 1) {
2457 lxcfs_error("Failed to start write on scm fd: %s\n", strerror(errno
));
2461 msg
.msg_name
= NULL
;
2462 msg
.msg_namelen
= 0;
2463 msg
.msg_control
= cmsgbuf
;
2464 msg
.msg_controllen
= sizeof(cmsgbuf
);
2467 iov
.iov_len
= sizeof(buf
);
2471 if (!wait_for_sock(sock
, 2)) {
2472 lxcfs_error("Timed out waiting for scm_cred: %s\n", strerror(errno
));
2475 ret
= recvmsg(sock
, &msg
, MSG_DONTWAIT
);
2477 lxcfs_error("Failed to receive scm_cred: %s\n", strerror(errno
));
2481 cmsg
= CMSG_FIRSTHDR(&msg
);
2483 if (cmsg
&& cmsg
->cmsg_len
== CMSG_LEN(sizeof(struct ucred
)) &&
2484 cmsg
->cmsg_level
== SOL_SOCKET
&&
2485 cmsg
->cmsg_type
== SCM_CREDENTIALS
) {
2486 memcpy(cred
, CMSG_DATA(cmsg
), sizeof(*cred
));
2493 struct pid_ns_clone_args
{
2497 int (*wrapped
) (int, pid_t
); // pid_from_ns or pid_to_ns
2501 * pid_ns_clone_wrapper - wraps pid_to_ns or pid_from_ns for usage
2502 * with clone(). This simply writes '1' as ACK back to the parent
2503 * before calling the actual wrapped function.
2505 static int pid_ns_clone_wrapper(void *arg
) {
2506 struct pid_ns_clone_args
* args
= (struct pid_ns_clone_args
*) arg
;
2509 close(args
->cpipe
[0]);
2510 if (write(args
->cpipe
[1], &b
, sizeof(char)) < 0)
2511 lxcfs_error("(child): error on write: %s.\n", strerror(errno
));
2512 close(args
->cpipe
[1]);
2513 return args
->wrapped(args
->sock
, args
->tpid
);
2517 * pid_to_ns - reads pids from a ucred over a socket, then writes the
2518 * int value back over the socket. This shifts the pid from the
2519 * sender's pidns into tpid's pidns.
2521 static int pid_to_ns(int sock
, pid_t tpid
)
2526 while (recv_creds(sock
, &cred
, &v
)) {
2529 if (write(sock
, &cred
.pid
, sizeof(pid_t
)) != sizeof(pid_t
))
2537 * pid_to_ns_wrapper: when you setns into a pidns, you yourself remain
2538 * in your old pidns. Only children which you clone will be in the target
2539 * pidns. So the pid_to_ns_wrapper does the setns, then clones a child to
2540 * actually convert pids.
2542 * Note: glibc's fork() does not respect pidns, which can lead to failed
2543 * assertions inside glibc (and thus failed forks) if the child's pid in
2544 * the pidns and the parent pid outside are identical. Using clone prevents
2547 static void pid_to_ns_wrapper(int sock
, pid_t tpid
)
2549 int newnsfd
= -1, ret
, cpipe
[2];
2554 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
2555 if (ret
< 0 || ret
>= sizeof(fnam
))
2557 newnsfd
= open(fnam
, O_RDONLY
);
2560 if (setns(newnsfd
, 0) < 0)
2564 if (pipe(cpipe
) < 0)
2567 struct pid_ns_clone_args args
= {
2571 .wrapped
= &pid_to_ns
2573 size_t stack_size
= sysconf(_SC_PAGESIZE
);
2574 void *stack
= alloca(stack_size
);
2576 cpid
= clone(pid_ns_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &args
);
2580 // give the child 1 second to be done forking and
2582 if (!wait_for_sock(cpipe
[0], 1))
2584 ret
= read(cpipe
[0], &v
, 1);
2585 if (ret
!= sizeof(char) || v
!= '1')
2588 if (!wait_for_pid(cpid
))
2594 * To read cgroup files with a particular pid, we will setns into the child
2595 * pidns, open a pipe, fork a child - which will be the first to really be in
2596 * the child ns - which does the cgfs_get_value and writes the data to the pipe.
2598 bool do_read_pids(pid_t tpid
, const char *contrl
, const char *cg
, const char *file
, char **d
)
2600 int sock
[2] = {-1, -1};
2601 char *tmpdata
= NULL
;
2603 pid_t qpid
, cpid
= -1;
2604 bool answer
= false;
2607 size_t sz
= 0, asz
= 0;
2609 if (!cgfs_get_value(contrl
, cg
, file
, &tmpdata
))
2613 * Now we read the pids from returned data one by one, pass
2614 * them into a child in the target namespace, read back the
2615 * translated pids, and put them into our to-return data
2618 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
2619 perror("socketpair");
2628 if (!cpid
) // child - exits when done
2629 pid_to_ns_wrapper(sock
[1], tpid
);
2631 char *ptr
= tmpdata
;
2634 while (sscanf(ptr
, "%d\n", &qpid
) == 1) {
2636 ret
= send_creds(sock
[0], &cred
, v
, true);
2638 if (ret
== SEND_CREDS_NOTSK
)
2640 if (ret
== SEND_CREDS_FAIL
)
2643 // read converted results
2644 if (!wait_for_sock(sock
[0], 2)) {
2645 lxcfs_error("Timed out waiting for pid from child: %s.\n", strerror(errno
));
2648 if (read(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
2649 lxcfs_error("Error reading pid from child: %s.\n", strerror(errno
));
2652 must_strcat_pid(d
, &sz
, &asz
, qpid
);
2654 ptr
= strchr(ptr
, '\n');
2660 cred
.pid
= getpid();
2662 if (send_creds(sock
[0], &cred
, v
, true) != SEND_CREDS_OK
) {
2663 // failed to ask child to exit
2664 lxcfs_error("Failed to ask child to exit: %s.\n", strerror(errno
));
2674 if (sock
[0] != -1) {
2681 int cg_read(const char *path
, char *buf
, size_t size
, off_t offset
,
2682 struct fuse_file_info
*fi
)
2684 struct fuse_context
*fc
= fuse_get_context();
2685 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2686 struct cgfs_files
*k
= NULL
;
2691 if (f
->type
!= LXC_TYPE_CGFILE
) {
2692 lxcfs_error("%s\n", "Internal error: directory cache info used in cg_read.");
2705 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
2711 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_RDONLY
)) {
2716 if (strcmp(f
->file
, "tasks") == 0 ||
2717 strcmp(f
->file
, "/tasks") == 0 ||
2718 strcmp(f
->file
, "/cgroup.procs") == 0 ||
2719 strcmp(f
->file
, "cgroup.procs") == 0)
2720 // special case - we have to translate the pids
2721 r
= do_read_pids(fc
->pid
, f
->controller
, f
->cgroup
, f
->file
, &data
);
2723 r
= cgfs_get_value(f
->controller
, f
->cgroup
, f
->file
, &data
);
2737 memcpy(buf
, data
, s
);
2738 if (s
> 0 && s
< size
&& data
[s
-1] != '\n')
2748 static int pid_from_ns(int sock
, pid_t tpid
)
2758 if (!wait_for_sock(sock
, 2)) {
2759 lxcfs_error("%s\n", "Timeout reading from parent.");
2762 if ((ret
= read(sock
, &vpid
, sizeof(pid_t
))) != sizeof(pid_t
)) {
2763 lxcfs_error("Bad read from parent: %s.\n", strerror(errno
));
2766 if (vpid
== -1) // done
2770 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
) {
2772 cred
.pid
= getpid();
2773 if (send_creds(sock
, &cred
, v
, false) != SEND_CREDS_OK
)
2780 static void pid_from_ns_wrapper(int sock
, pid_t tpid
)
2782 int newnsfd
= -1, ret
, cpipe
[2];
2787 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
2788 if (ret
< 0 || ret
>= sizeof(fnam
))
2790 newnsfd
= open(fnam
, O_RDONLY
);
2793 if (setns(newnsfd
, 0) < 0)
2797 if (pipe(cpipe
) < 0)
2800 struct pid_ns_clone_args args
= {
2804 .wrapped
= &pid_from_ns
2806 size_t stack_size
= sysconf(_SC_PAGESIZE
);
2807 void *stack
= alloca(stack_size
);
2809 cpid
= clone(pid_ns_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &args
);
2813 // give the child 1 second to be done forking and
2815 if (!wait_for_sock(cpipe
[0], 1))
2817 ret
= read(cpipe
[0], &v
, 1);
2818 if (ret
!= sizeof(char) || v
!= '1')
2821 if (!wait_for_pid(cpid
))
2827 * Given host @uid, return the uid to which it maps in
2828 * @pid's user namespace, or -1 if none.
2830 bool hostuid_to_ns(uid_t uid
, pid_t pid
, uid_t
*answer
)
2835 sprintf(line
, "/proc/%d/uid_map", pid
);
2836 if ((f
= fopen(line
, "r")) == NULL
) {
2840 *answer
= convert_id_to_ns(f
, uid
);
2849 * get_pid_creds: get the real uid and gid of @pid from
2851 * (XXX should we use euid here?)
2853 void get_pid_creds(pid_t pid
, uid_t
*uid
, gid_t
*gid
)
2862 sprintf(line
, "/proc/%d/status", pid
);
2863 if ((f
= fopen(line
, "r")) == NULL
) {
2864 lxcfs_error("Error opening %s: %s\n", line
, strerror(errno
));
2867 while (fgets(line
, 400, f
)) {
2868 if (strncmp(line
, "Uid:", 4) == 0) {
2869 if (sscanf(line
+4, "%u", &u
) != 1) {
2870 lxcfs_error("bad uid line for pid %u\n", pid
);
2875 } else if (strncmp(line
, "Gid:", 4) == 0) {
2876 if (sscanf(line
+4, "%u", &g
) != 1) {
2877 lxcfs_error("bad gid line for pid %u\n", pid
);
2888 * May the requestor @r move victim @v to a new cgroup?
2889 * This is allowed if
2890 * . they are the same task
2891 * . they are ownedy by the same uid
2892 * . @r is root on the host, or
2893 * . @v's uid is mapped into @r's where @r is root.
2895 bool may_move_pid(pid_t r
, uid_t r_uid
, pid_t v
)
2897 uid_t v_uid
, tmpuid
;
2904 get_pid_creds(v
, &v_uid
, &v_gid
);
2907 if (hostuid_to_ns(r_uid
, r
, &tmpuid
) && tmpuid
== 0
2908 && hostuid_to_ns(v_uid
, r
, &tmpuid
))
2913 static bool do_write_pids(pid_t tpid
, uid_t tuid
, const char *contrl
, const char *cg
,
2914 const char *file
, const char *buf
)
2916 int sock
[2] = {-1, -1};
2917 pid_t qpid
, cpid
= -1;
2918 FILE *pids_file
= NULL
;
2919 bool answer
= false, fail
= false;
2921 pids_file
= open_pids_file(contrl
, cg
);
2926 * write the pids to a socket, have helper in writer's pidns
2927 * call movepid for us
2929 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
2930 perror("socketpair");
2938 if (!cpid
) { // child
2940 pid_from_ns_wrapper(sock
[1], tpid
);
2943 const char *ptr
= buf
;
2944 while (sscanf(ptr
, "%d", &qpid
) == 1) {
2948 if (write(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
2949 lxcfs_error("Error writing pid to child: %s.\n", strerror(errno
));
2953 if (recv_creds(sock
[0], &cred
, &v
)) {
2955 if (!may_move_pid(tpid
, tuid
, cred
.pid
)) {
2959 if (fprintf(pids_file
, "%d", (int) cred
.pid
) < 0)
2964 ptr
= strchr(ptr
, '\n');
2970 /* All good, write the value */
2972 if (write(sock
[0], &qpid
,sizeof(qpid
)) != sizeof(qpid
))
2973 lxcfs_error("%s\n", "Warning: failed to ask child to exit.");
2981 if (sock
[0] != -1) {
2986 if (fclose(pids_file
) != 0)
2992 int cg_write(const char *path
, const char *buf
, size_t size
, off_t offset
,
2993 struct fuse_file_info
*fi
)
2995 struct fuse_context
*fc
= fuse_get_context();
2996 char *localbuf
= NULL
;
2997 struct cgfs_files
*k
= NULL
;
2998 struct file_info
*f
= (struct file_info
*)fi
->fh
;
3001 if (f
->type
!= LXC_TYPE_CGFILE
) {
3002 lxcfs_error("%s\n", "Internal error: directory cache info used in cg_write.");
3012 localbuf
= alloca(size
+1);
3013 localbuf
[size
] = '\0';
3014 memcpy(localbuf
, buf
, size
);
3016 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
3021 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_WRONLY
)) {
3026 if (strcmp(f
->file
, "tasks") == 0 ||
3027 strcmp(f
->file
, "/tasks") == 0 ||
3028 strcmp(f
->file
, "/cgroup.procs") == 0 ||
3029 strcmp(f
->file
, "cgroup.procs") == 0)
3030 // special case - we have to translate the pids
3031 r
= do_write_pids(fc
->pid
, fc
->uid
, f
->controller
, f
->cgroup
, f
->file
, localbuf
);
3033 r
= cgfs_set_value(f
->controller
, f
->cgroup
, f
->file
, localbuf
);
3043 int cg_chown(const char *path
, uid_t uid
, gid_t gid
)
3045 struct fuse_context
*fc
= fuse_get_context();
3046 char *cgdir
= NULL
, *last
= NULL
, *path1
, *path2
, *controller
;
3047 struct cgfs_files
*k
= NULL
;
3054 if (strcmp(path
, "/cgroup") == 0)
3057 controller
= pick_controller_from_path(fc
, path
);
3059 return errno
== ENOENT
? -EPERM
: -errno
;
3061 cgroup
= find_cgroup_in_path(path
);
3063 /* this is just /cgroup/controller */
3066 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
3076 if (is_child_cgroup(controller
, path1
, path2
)) {
3077 // get uid, gid, from '/tasks' file and make up a mode
3078 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
3079 k
= cgfs_get_key(controller
, cgroup
, "tasks");
3082 k
= cgfs_get_key(controller
, path1
, path2
);
3090 * This being a fuse request, the uid and gid must be valid
3091 * in the caller's namespace. So we can just check to make
3092 * sure that the caller is root in his uid, and privileged
3093 * over the file's current owner.
3095 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_REQD
)) {
3100 ret
= cgfs_chown_file(controller
, cgroup
, uid
, gid
);
3109 int cg_chmod(const char *path
, mode_t mode
)
3111 struct fuse_context
*fc
= fuse_get_context();
3112 char * cgdir
= NULL
, *last
= NULL
, *path1
, *path2
, *controller
;
3113 struct cgfs_files
*k
= NULL
;
3120 if (strcmp(path
, "/cgroup") == 0)
3123 controller
= pick_controller_from_path(fc
, path
);
3125 return errno
== ENOENT
? -EPERM
: -errno
;
3127 cgroup
= find_cgroup_in_path(path
);
3129 /* this is just /cgroup/controller */
3132 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
3142 if (is_child_cgroup(controller
, path1
, path2
)) {
3143 // get uid, gid, from '/tasks' file and make up a mode
3144 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
3145 k
= cgfs_get_key(controller
, cgroup
, "tasks");
3148 k
= cgfs_get_key(controller
, path1
, path2
);
3156 * This being a fuse request, the uid and gid must be valid
3157 * in the caller's namespace. So we can just check to make
3158 * sure that the caller is root in his uid, and privileged
3159 * over the file's current owner.
3161 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
3166 if (!cgfs_chmod_file(controller
, cgroup
, mode
)) {
3178 int cg_mkdir(const char *path
, mode_t mode
)
3180 struct fuse_context
*fc
= fuse_get_context();
3181 char *last
= NULL
, *path1
, *cgdir
= NULL
, *controller
, *next
= NULL
;
3188 controller
= pick_controller_from_path(fc
, path
);
3190 return errno
== ENOENT
? -EPERM
: -errno
;
3192 cgroup
= find_cgroup_in_path(path
);
3196 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
3202 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3205 if (!caller_is_in_ancestor(initpid
, controller
, path1
, &next
)) {
3208 else if (last
&& strcmp(next
, last
) == 0)
3215 if (!fc_may_access(fc
, controller
, path1
, NULL
, O_RDWR
)) {
3219 if (!caller_is_in_ancestor(initpid
, controller
, path1
, NULL
)) {
3224 ret
= cgfs_create(controller
, cgroup
, fc
->uid
, fc
->gid
);
3232 int cg_rmdir(const char *path
)
3234 struct fuse_context
*fc
= fuse_get_context();
3235 char *last
= NULL
, *cgdir
= NULL
, *controller
, *next
= NULL
;
3242 controller
= pick_controller_from_path(fc
, path
);
3243 if (!controller
) /* Someone's trying to delete "/cgroup". */
3246 cgroup
= find_cgroup_in_path(path
);
3247 if (!cgroup
) /* Someone's trying to delete a controller e.g. "/blkio". */
3250 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
3252 /* Someone's trying to delete a cgroup on the same level as the
3253 * "/lxc" cgroup e.g. rmdir "/cgroup/blkio/lxc" or
3254 * rmdir "/cgroup/blkio/init.slice".
3260 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3263 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, &next
)) {
3264 if (!last
|| (next
&& (strcmp(next
, last
) == 0)))
3271 if (!fc_may_access(fc
, controller
, cgdir
, NULL
, O_WRONLY
)) {
3275 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, NULL
)) {
3280 if (!cgfs_remove(controller
, cgroup
)) {
3293 static bool startswith(const char *line
, const char *pref
)
3295 if (strncmp(line
, pref
, strlen(pref
)) == 0)
3300 static void parse_memstat(char *memstat
, unsigned long *cached
,
3301 unsigned long *active_anon
, unsigned long *inactive_anon
,
3302 unsigned long *active_file
, unsigned long *inactive_file
,
3303 unsigned long *unevictable
, unsigned long *shmem
)
3308 if (startswith(memstat
, "total_cache")) {
3309 sscanf(memstat
+ 11, "%lu", cached
);
3311 } else if (startswith(memstat
, "total_active_anon")) {
3312 sscanf(memstat
+ 17, "%lu", active_anon
);
3313 *active_anon
/= 1024;
3314 } else if (startswith(memstat
, "total_inactive_anon")) {
3315 sscanf(memstat
+ 19, "%lu", inactive_anon
);
3316 *inactive_anon
/= 1024;
3317 } else if (startswith(memstat
, "total_active_file")) {
3318 sscanf(memstat
+ 17, "%lu", active_file
);
3319 *active_file
/= 1024;
3320 } else if (startswith(memstat
, "total_inactive_file")) {
3321 sscanf(memstat
+ 19, "%lu", inactive_file
);
3322 *inactive_file
/= 1024;
3323 } else if (startswith(memstat
, "total_unevictable")) {
3324 sscanf(memstat
+ 17, "%lu", unevictable
);
3325 *unevictable
/= 1024;
3326 } else if (startswith(memstat
, "total_shmem")) {
3327 sscanf(memstat
+ 11, "%lu", shmem
);
3330 eol
= strchr(memstat
, '\n');
3337 static void get_blkio_io_value(char *str
, unsigned major
, unsigned minor
, char *iotype
, unsigned long *v
)
3343 snprintf(key
, 32, "%u:%u %s", major
, minor
, iotype
);
3345 size_t len
= strlen(key
);
3349 if (startswith(str
, key
)) {
3350 sscanf(str
+ len
, "%lu", v
);
3353 eol
= strchr(str
, '\n');
3360 static int read_file(const char *path
, char *buf
, size_t size
,
3361 struct file_info
*d
)
3363 size_t linelen
= 0, total_len
= 0, rv
= 0;
3365 char *cache
= d
->buf
;
3366 size_t cache_size
= d
->buflen
;
3367 FILE *f
= fopen(path
, "r");
3371 while (getline(&line
, &linelen
, f
) != -1) {
3372 ssize_t l
= snprintf(cache
, cache_size
, "%s", line
);
3374 perror("Error writing to cache");
3378 if (l
>= cache_size
) {
3379 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3388 d
->size
= total_len
;
3389 if (total_len
> size
)
3392 /* read from off 0 */
3393 memcpy(buf
, d
->buf
, total_len
);
3402 * FUSE ops for /proc
3405 static unsigned long get_memlimit(const char *cgroup
, const char *file
)
3407 char *memlimit_str
= NULL
;
3408 unsigned long memlimit
= -1;
3410 if (cgfs_get_value("memory", cgroup
, file
, &memlimit_str
))
3411 memlimit
= strtoul(memlimit_str
, NULL
, 10);
3418 static unsigned long get_min_memlimit(const char *cgroup
, const char *file
)
3420 char *copy
= strdupa(cgroup
);
3421 unsigned long memlimit
= 0, retlimit
;
3423 retlimit
= get_memlimit(copy
, file
);
3425 while (strcmp(copy
, "/") != 0) {
3426 copy
= dirname(copy
);
3427 memlimit
= get_memlimit(copy
, file
);
3428 if (memlimit
!= -1 && memlimit
< retlimit
)
3429 retlimit
= memlimit
;
3435 static int proc_meminfo_read(char *buf
, size_t size
, off_t offset
,
3436 struct fuse_file_info
*fi
)
3438 struct fuse_context
*fc
= fuse_get_context();
3439 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3441 char *memusage_str
= NULL
, *memstat_str
= NULL
,
3442 *memswlimit_str
= NULL
, *memswusage_str
= NULL
;
3443 unsigned long memlimit
= 0, memusage
= 0, memswlimit
= 0, memswusage
= 0,
3444 cached
= 0, hosttotal
= 0, active_anon
= 0, inactive_anon
= 0,
3445 active_file
= 0, inactive_file
= 0, unevictable
= 0, shmem
= 0,
3448 size_t linelen
= 0, total_len
= 0, rv
= 0;
3449 char *cache
= d
->buf
;
3450 size_t cache_size
= d
->buflen
;
3454 if (offset
> d
->size
)
3458 int left
= d
->size
- offset
;
3459 total_len
= left
> size
? size
: left
;
3460 memcpy(buf
, cache
+ offset
, total_len
);
3464 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3467 cg
= get_pid_cgroup(initpid
, "memory");
3469 return read_file("/proc/meminfo", buf
, size
, d
);
3470 prune_init_slice(cg
);
3472 memlimit
= get_min_memlimit(cg
, "memory.limit_in_bytes");
3473 if (!cgfs_get_value("memory", cg
, "memory.usage_in_bytes", &memusage_str
))
3475 if (!cgfs_get_value("memory", cg
, "memory.stat", &memstat_str
))
3478 // Following values are allowed to fail, because swapaccount might be turned
3479 // off for current kernel
3480 if(cgfs_get_value("memory", cg
, "memory.memsw.limit_in_bytes", &memswlimit_str
) &&
3481 cgfs_get_value("memory", cg
, "memory.memsw.usage_in_bytes", &memswusage_str
))
3483 memswlimit
= get_min_memlimit(cg
, "memory.memsw.limit_in_bytes");
3484 memswusage
= strtoul(memswusage_str
, NULL
, 10);
3486 memswlimit
= memswlimit
/ 1024;
3487 memswusage
= memswusage
/ 1024;
3490 memusage
= strtoul(memusage_str
, NULL
, 10);
3494 parse_memstat(memstat_str
, &cached
, &active_anon
,
3495 &inactive_anon
, &active_file
, &inactive_file
,
3496 &unevictable
, &shmem
);
3498 f
= fopen("/proc/meminfo", "r");
3502 while (getline(&line
, &linelen
, f
) != -1) {
3504 char *printme
, lbuf
[100];
3506 memset(lbuf
, 0, 100);
3507 if (startswith(line
, "MemTotal:")) {
3508 sscanf(line
+sizeof("MemTotal:")-1, "%lu", &hosttotal
);
3509 if (hosttotal
< memlimit
)
3510 memlimit
= hosttotal
;
3511 snprintf(lbuf
, 100, "MemTotal: %8lu kB\n", memlimit
);
3513 } else if (startswith(line
, "MemFree:")) {
3514 snprintf(lbuf
, 100, "MemFree: %8lu kB\n", memlimit
- memusage
);
3516 } else if (startswith(line
, "MemAvailable:")) {
3517 snprintf(lbuf
, 100, "MemAvailable: %8lu kB\n", memlimit
- memusage
+ cached
);
3519 } else if (startswith(line
, "SwapTotal:") && memswlimit
> 0) {
3520 sscanf(line
+sizeof("SwapTotal:")-1, "%lu", &hostswtotal
);
3521 if (hostswtotal
< memswlimit
)
3522 memswlimit
= hostswtotal
;
3523 snprintf(lbuf
, 100, "SwapTotal: %8lu kB\n", memswlimit
);
3525 } else if (startswith(line
, "SwapFree:") && memswlimit
> 0 && memswusage
> 0) {
3526 unsigned long swaptotal
= memswlimit
,
3527 swapusage
= memswusage
- memusage
,
3528 swapfree
= swapusage
< swaptotal
? swaptotal
- swapusage
: 0;
3529 snprintf(lbuf
, 100, "SwapFree: %8lu kB\n", swapfree
);
3531 } else if (startswith(line
, "Slab:")) {
3532 snprintf(lbuf
, 100, "Slab: %8lu kB\n", 0UL);
3534 } else if (startswith(line
, "Buffers:")) {
3535 snprintf(lbuf
, 100, "Buffers: %8lu kB\n", 0UL);
3537 } else if (startswith(line
, "Cached:")) {
3538 snprintf(lbuf
, 100, "Cached: %8lu kB\n", cached
);
3540 } else if (startswith(line
, "SwapCached:")) {
3541 snprintf(lbuf
, 100, "SwapCached: %8lu kB\n", 0UL);
3543 } else if (startswith(line
, "Active:")) {
3544 snprintf(lbuf
, 100, "Active: %8lu kB\n",
3545 active_anon
+ active_file
);
3547 } else if (startswith(line
, "Inactive:")) {
3548 snprintf(lbuf
, 100, "Inactive: %8lu kB\n",
3549 inactive_anon
+ inactive_file
);
3551 } else if (startswith(line
, "Active(anon)")) {
3552 snprintf(lbuf
, 100, "Active(anon): %8lu kB\n", active_anon
);
3554 } else if (startswith(line
, "Inactive(anon)")) {
3555 snprintf(lbuf
, 100, "Inactive(anon): %8lu kB\n", inactive_anon
);
3557 } else if (startswith(line
, "Active(file)")) {
3558 snprintf(lbuf
, 100, "Active(file): %8lu kB\n", active_file
);
3560 } else if (startswith(line
, "Inactive(file)")) {
3561 snprintf(lbuf
, 100, "Inactive(file): %8lu kB\n", inactive_file
);
3563 } else if (startswith(line
, "Unevictable")) {
3564 snprintf(lbuf
, 100, "Unevictable: %8lu kB\n", unevictable
);
3566 } else if (startswith(line
, "SReclaimable")) {
3567 snprintf(lbuf
, 100, "SReclaimable: %8lu kB\n", 0UL);
3569 } else if (startswith(line
, "SUnreclaim")) {
3570 snprintf(lbuf
, 100, "SUnreclaim: %8lu kB\n", 0UL);
3572 } else if (startswith(line
, "Shmem:")) {
3573 snprintf(lbuf
, 100, "Shmem: %8lu kB\n", shmem
);
3575 } else if (startswith(line
, "ShmemHugePages")) {
3576 snprintf(lbuf
, 100, "ShmemHugePages: %8lu kB\n", 0UL);
3578 } else if (startswith(line
, "ShmemPmdMapped")) {
3579 snprintf(lbuf
, 100, "ShmemPmdMapped: %8lu kB\n", 0UL);
3584 l
= snprintf(cache
, cache_size
, "%s", printme
);
3586 perror("Error writing to cache");
3591 if (l
>= cache_size
) {
3592 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3603 d
->size
= total_len
;
3604 if (total_len
> size
) total_len
= size
;
3605 memcpy(buf
, d
->buf
, total_len
);
3614 free(memswlimit_str
);
3615 free(memswusage_str
);
3621 * Read the cpuset.cpus for cg
3622 * Return the answer in a newly allocated string which must be freed
3624 static char *get_cpuset(const char *cg
)
3628 if (!cgfs_get_value("cpuset", cg
, "cpuset.cpus", &answer
))
3633 bool cpu_in_cpuset(int cpu
, const char *cpuset
);
3635 static bool cpuline_in_cpuset(const char *line
, const char *cpuset
)
3639 if (sscanf(line
, "processor : %d", &cpu
) != 1)
3641 return cpu_in_cpuset(cpu
, cpuset
);
3645 * Read cgroup CPU quota parameters from `cpu.cfs_quota_us` or `cpu.cfs_period_us`,
3646 * depending on `param`. Parameter value is returned throuh `value`.
3648 static bool read_cpu_cfs_param(const char *cg
, const char *param
, int64_t *value
)
3651 char file
[11 + 6 + 1]; // cpu.cfs__us + quota/period + \0
3654 sprintf(file
, "cpu.cfs_%s_us", param
);
3656 if (!cgfs_get_value("cpu", cg
, file
, &str
))
3659 if (sscanf(str
, "%ld", value
) != 1)
3671 * Return the maximum number of visible CPUs based on CPU quotas.
3672 * If there is no quota set, zero is returned.
3674 int max_cpu_count(const char *cg
)
3677 int64_t cfs_quota
, cfs_period
;
3679 if (!read_cpu_cfs_param(cg
, "quota", &cfs_quota
))
3682 if (!read_cpu_cfs_param(cg
, "period", &cfs_period
))
3685 if (cfs_quota
<= 0 || cfs_period
<= 0)
3688 rv
= cfs_quota
/ cfs_period
;
3690 /* In case quota/period does not yield a whole number, add one CPU for
3693 if ((cfs_quota
% cfs_period
) > 0)
3696 nprocs
= get_nprocs();
3705 * Determine whether CPU views should be used or not.
3707 bool use_cpuview(const char *cg
)
3712 tmpc
= find_mounted_controller("cpu", &cfd
);
3716 tmpc
= find_mounted_controller("cpuacct", &cfd
);
3724 * check whether this is a '^processor" line in /proc/cpuinfo
3726 static bool is_processor_line(const char *line
)
3730 if (sscanf(line
, "processor : %d", &cpu
) == 1)
3735 static int proc_cpuinfo_read(char *buf
, size_t size
, off_t offset
,
3736 struct fuse_file_info
*fi
)
3738 struct fuse_context
*fc
= fuse_get_context();
3739 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3741 char *cpuset
= NULL
;
3743 size_t linelen
= 0, total_len
= 0, rv
= 0;
3744 bool am_printing
= false, firstline
= true, is_s390x
= false;
3745 int curcpu
= -1, cpu
, max_cpus
= 0;
3747 char *cache
= d
->buf
;
3748 size_t cache_size
= d
->buflen
;
3752 if (offset
> d
->size
)
3756 int left
= d
->size
- offset
;
3757 total_len
= left
> size
? size
: left
;
3758 memcpy(buf
, cache
+ offset
, total_len
);
3762 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3765 cg
= get_pid_cgroup(initpid
, "cpuset");
3767 return read_file("proc/cpuinfo", buf
, size
, d
);
3768 prune_init_slice(cg
);
3770 cpuset
= get_cpuset(cg
);
3774 use_view
= use_cpuview(cg
);
3777 max_cpus
= max_cpu_count(cg
);
3779 f
= fopen("/proc/cpuinfo", "r");
3783 while (getline(&line
, &linelen
, f
) != -1) {
3787 if (strstr(line
, "IBM/S390") != NULL
) {
3793 if (strncmp(line
, "# processors:", 12) == 0)
3795 if (is_processor_line(line
)) {
3796 if (use_view
&& max_cpus
> 0 && (curcpu
+1) == max_cpus
)
3798 am_printing
= cpuline_in_cpuset(line
, cpuset
);
3801 l
= snprintf(cache
, cache_size
, "processor : %d\n", curcpu
);
3803 perror("Error writing to cache");
3807 if (l
>= cache_size
) {
3808 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3817 } else if (is_s390x
&& sscanf(line
, "processor %d:", &cpu
) == 1) {
3819 if (use_view
&& max_cpus
> 0 && (curcpu
+1) == max_cpus
)
3821 if (!cpu_in_cpuset(cpu
, cpuset
))
3824 p
= strchr(line
, ':');
3828 l
= snprintf(cache
, cache_size
, "processor %d:%s", curcpu
, p
);
3830 perror("Error writing to cache");
3834 if (l
>= cache_size
) {
3835 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3846 l
= snprintf(cache
, cache_size
, "%s", line
);
3848 perror("Error writing to cache");
3852 if (l
>= cache_size
) {
3853 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3864 char *origcache
= d
->buf
;
3867 d
->buf
= malloc(d
->buflen
);
3870 cache_size
= d
->buflen
;
3872 l
= snprintf(cache
, cache_size
, "vendor_id : IBM/S390\n");
3873 if (l
< 0 || l
>= cache_size
) {
3880 l
= snprintf(cache
, cache_size
, "# processors : %d\n", curcpu
+ 1);
3881 if (l
< 0 || l
>= cache_size
) {
3888 l
= snprintf(cache
, cache_size
, "%s", origcache
);
3890 if (l
< 0 || l
>= cache_size
)
3896 d
->size
= total_len
;
3897 if (total_len
> size
) total_len
= size
;
3899 /* read from off 0 */
3900 memcpy(buf
, d
->buf
, total_len
);
3911 static uint64_t get_reaper_start_time(pid_t pid
)
3916 /* strlen("/proc/") = 6
3920 * strlen("/stat") = 5
3924 #define __PROC_PID_STAT_LEN (6 + LXCFS_NUMSTRLEN64 + 5 + 1)
3925 char path
[__PROC_PID_STAT_LEN
];
3928 qpid
= lookup_initpid_in_store(pid
);
3930 /* Caller can check for EINVAL on 0. */
3935 ret
= snprintf(path
, __PROC_PID_STAT_LEN
, "/proc/%d/stat", qpid
);
3936 if (ret
< 0 || ret
>= __PROC_PID_STAT_LEN
) {
3937 /* Caller can check for EINVAL on 0. */
3942 f
= fopen(path
, "r");
3944 /* Caller can check for EINVAL on 0. */
3949 /* Note that the *scanf() argument supression requires that length
3950 * modifiers such as "l" are omitted. Otherwise some compilers will yell
3951 * at us. It's like telling someone you're not married and then asking
3952 * if you can bring your wife to the party.
3954 ret
= fscanf(f
, "%*d " /* (1) pid %d */
3955 "%*s " /* (2) comm %s */
3956 "%*c " /* (3) state %c */
3957 "%*d " /* (4) ppid %d */
3958 "%*d " /* (5) pgrp %d */
3959 "%*d " /* (6) session %d */
3960 "%*d " /* (7) tty_nr %d */
3961 "%*d " /* (8) tpgid %d */
3962 "%*u " /* (9) flags %u */
3963 "%*u " /* (10) minflt %lu */
3964 "%*u " /* (11) cminflt %lu */
3965 "%*u " /* (12) majflt %lu */
3966 "%*u " /* (13) cmajflt %lu */
3967 "%*u " /* (14) utime %lu */
3968 "%*u " /* (15) stime %lu */
3969 "%*d " /* (16) cutime %ld */
3970 "%*d " /* (17) cstime %ld */
3971 "%*d " /* (18) priority %ld */
3972 "%*d " /* (19) nice %ld */
3973 "%*d " /* (20) num_threads %ld */
3974 "%*d " /* (21) itrealvalue %ld */
3975 "%" PRIu64
, /* (22) starttime %llu */
3979 /* Caller can check for EINVAL on 0. */
3990 static uint64_t get_reaper_start_time_in_sec(pid_t pid
)
3992 uint64_t clockticks
;
3993 int64_t ticks_per_sec
;
3995 clockticks
= get_reaper_start_time(pid
);
3996 if (clockticks
== 0 && errno
== EINVAL
) {
3997 lxcfs_debug("failed to retrieve start time of pid %d\n", pid
);
4001 ticks_per_sec
= sysconf(_SC_CLK_TCK
);
4002 if (ticks_per_sec
< 0 && errno
== EINVAL
) {
4005 "failed to determine number of clock ticks in a second");
4009 return (clockticks
/= ticks_per_sec
);
4012 static uint64_t get_reaper_age(pid_t pid
)
4014 uint64_t procstart
, uptime
, procage
;
4016 /* We need to substract the time the process has started since system
4017 * boot minus the time when the system has started to get the actual
4020 procstart
= get_reaper_start_time_in_sec(pid
);
4021 procage
= procstart
;
4022 if (procstart
> 0) {
4024 struct timespec spec
;
4026 ret
= clock_gettime(CLOCK_BOOTTIME
, &spec
);
4029 /* We could make this more precise here by using the tv_nsec
4030 * field in the timespec struct and convert it to milliseconds
4031 * and then create a double for the seconds and milliseconds but
4032 * that seems more work than it is worth.
4034 uptime
= spec
.tv_sec
;
4035 procage
= uptime
- procstart
;
4042 * Returns 0 on success.
4043 * It is the caller's responsibility to free `return_usage`, unless this
4044 * function returns an error.
4046 static int read_cpuacct_usage_all(char *cg
, char *cpuset
, struct cpuacct_usage
**return_usage
)
4048 int cpucount
= get_nprocs();
4049 struct cpuacct_usage
*cpu_usage
;
4050 int rv
= 0, i
, j
, ret
, read_pos
= 0, read_cnt
;
4052 uint64_t cg_user
, cg_system
;
4053 int64_t ticks_per_sec
;
4054 char *usage_str
= NULL
;
4056 ticks_per_sec
= sysconf(_SC_CLK_TCK
);
4058 if (ticks_per_sec
< 0 && errno
== EINVAL
) {
4061 "read_cpuacct_usage_all failed to determine number of clock ticks "
4066 cpu_usage
= malloc(sizeof(struct cpuacct_usage
) * cpucount
);
4070 if (!cgfs_get_value("cpuacct", cg
, "cpuacct.usage_all", &usage_str
)) {
4075 if (sscanf(usage_str
, "cpu user system\n%n", &read_cnt
) != 0) {
4076 lxcfs_error("read_cpuacct_usage_all reading first line from "
4077 "%s/cpuacct.usage_all failed.\n", cg
);
4082 read_pos
+= read_cnt
;
4084 for (i
= 0, j
= 0; i
< cpucount
; i
++) {
4085 ret
= sscanf(usage_str
+ read_pos
, "%d %lu %lu\n%n", &cg_cpu
, &cg_user
,
4086 &cg_system
, &read_cnt
);
4092 lxcfs_error("read_cpuacct_usage_all reading from %s/cpuacct.usage_all "
4098 read_pos
+= read_cnt
;
4100 if (!cpu_in_cpuset(i
, cpuset
))
4103 /* Convert the time from nanoseconds to USER_HZ */
4104 cpu_usage
[j
].user
= cg_user
/ 1000.0 / 1000 / 1000 * ticks_per_sec
;
4105 cpu_usage
[j
].system
= cg_system
/ 1000.0 / 1000 / 1000 * ticks_per_sec
;
4110 *return_usage
= cpu_usage
;
4118 *return_usage
= NULL
;
4124 static unsigned long diff_cpu_usage(struct cpuacct_usage
*older
, struct cpuacct_usage
*newer
, struct cpuacct_usage
*diff
, int cpu_count
)
4127 unsigned long sum
= 0;
4129 for (i
= 0; i
< cpu_count
; i
++) {
4130 /* When cpuset is changed on the fly, the CPUs might get reordered.
4131 * We could either reset all counters, or check that the substractions
4132 * below will return expected results.
4134 if (newer
[i
].user
> older
[i
].user
)
4135 diff
[i
].user
= newer
[i
].user
- older
[i
].user
;
4139 if (newer
[i
].system
> older
[i
].system
)
4140 diff
[i
].system
= newer
[i
].system
- older
[i
].system
;
4144 if (newer
[i
].idle
> older
[i
].idle
)
4145 diff
[i
].idle
= newer
[i
].idle
- older
[i
].idle
;
4149 sum
+= diff
[i
].user
;
4150 sum
+= diff
[i
].system
;
4151 sum
+= diff
[i
].idle
;
4157 static void add_cpu_usage(unsigned long *surplus
, struct cpuacct_usage
*usage
, unsigned long *counter
, unsigned long threshold
)
4159 unsigned long free_space
, to_add
;
4161 free_space
= threshold
- usage
->user
- usage
->system
;
4163 if (free_space
> usage
->idle
)
4164 free_space
= usage
->idle
;
4166 to_add
= free_space
> *surplus
? *surplus
: free_space
;
4169 usage
->idle
-= to_add
;
4173 static struct cg_proc_stat
*prune_proc_stat_list(struct cg_proc_stat
*node
)
4175 struct cg_proc_stat
*first
= NULL
, *prev
, *tmp
;
4177 for (prev
= NULL
; node
; ) {
4178 if (!cgfs_param_exist("cpu", node
->cg
, "cpu.shares")) {
4180 lxcfs_debug("Removing stat node for %s\n", node
->cg
);
4183 prev
->next
= node
->next
;
4188 free_proc_stat_node(tmp
);
4200 #define PROC_STAT_PRUNE_INTERVAL 10
4201 static void prune_proc_stat_history(void)
4204 time_t now
= time(NULL
);
4206 for (i
= 0; i
< CPUVIEW_HASH_SIZE
; i
++) {
4207 pthread_rwlock_wrlock(&proc_stat_history
[i
]->lock
);
4209 if ((proc_stat_history
[i
]->lastcheck
+ PROC_STAT_PRUNE_INTERVAL
) > now
) {
4210 pthread_rwlock_unlock(&proc_stat_history
[i
]->lock
);
4214 if (proc_stat_history
[i
]->next
) {
4215 proc_stat_history
[i
]->next
= prune_proc_stat_list(proc_stat_history
[i
]->next
);
4216 proc_stat_history
[i
]->lastcheck
= now
;
4219 pthread_rwlock_unlock(&proc_stat_history
[i
]->lock
);
4223 static struct cg_proc_stat
*find_proc_stat_node(struct cg_proc_stat_head
*head
, const char *cg
)
4225 struct cg_proc_stat
*node
;
4227 pthread_rwlock_rdlock(&head
->lock
);
4230 pthread_rwlock_unlock(&head
->lock
);
4237 if (strcmp(cg
, node
->cg
) == 0)
4239 } while ((node
= node
->next
));
4244 pthread_rwlock_unlock(&head
->lock
);
4245 prune_proc_stat_history();
4249 static struct cg_proc_stat
*new_proc_stat_node(struct cpuacct_usage
*usage
, int cpu_count
, const char *cg
)
4251 struct cg_proc_stat
*node
;
4254 node
= malloc(sizeof(struct cg_proc_stat
));
4262 node
->cg
= malloc(strlen(cg
) + 1);
4266 strcpy(node
->cg
, cg
);
4268 node
->usage
= malloc(sizeof(struct cpuacct_usage
) * cpu_count
);
4272 memcpy(node
->usage
, usage
, sizeof(struct cpuacct_usage
) * cpu_count
);
4274 node
->view
= malloc(sizeof(struct cpuacct_usage
) * cpu_count
);
4278 node
->cpu_count
= cpu_count
;
4281 if (pthread_mutex_init(&node
->lock
, NULL
) != 0) {
4282 lxcfs_error("%s\n", "Failed to initialize node lock");
4286 for (i
= 0; i
< cpu_count
; i
++) {
4287 node
->view
[i
].user
= 0;
4288 node
->view
[i
].system
= 0;
4289 node
->view
[i
].idle
= 0;
4295 if (node
&& node
->cg
)
4297 if (node
&& node
->usage
)
4299 if (node
&& node
->view
)
4307 static struct cg_proc_stat
*add_proc_stat_node(struct cg_proc_stat
*new_node
)
4309 int hash
= calc_hash(new_node
->cg
) % CPUVIEW_HASH_SIZE
;
4310 struct cg_proc_stat_head
*head
= proc_stat_history
[hash
];
4311 struct cg_proc_stat
*node
, *rv
= new_node
;
4313 pthread_rwlock_wrlock(&head
->lock
);
4316 head
->next
= new_node
;
4323 if (strcmp(node
->cg
, new_node
->cg
) == 0) {
4324 /* The node is already present, return it */
4325 free_proc_stat_node(new_node
);
4335 node
->next
= new_node
;
4340 pthread_rwlock_unlock(&head
->lock
);
4344 static bool expand_proc_stat_node(struct cg_proc_stat
*node
, int cpu_count
)
4346 struct cpuacct_usage
*new_usage
, *new_view
;
4349 /* Allocate new memory */
4350 new_usage
= malloc(sizeof(struct cpuacct_usage
) * cpu_count
);
4354 new_view
= malloc(sizeof(struct cpuacct_usage
) * cpu_count
);
4360 /* Copy existing data & initialize new elements */
4361 for (i
= 0; i
< cpu_count
; i
++) {
4362 if (i
< node
->cpu_count
) {
4363 new_usage
[i
].user
= node
->usage
[i
].user
;
4364 new_usage
[i
].system
= node
->usage
[i
].system
;
4365 new_usage
[i
].idle
= node
->usage
[i
].idle
;
4367 new_view
[i
].user
= node
->view
[i
].user
;
4368 new_view
[i
].system
= node
->view
[i
].system
;
4369 new_view
[i
].idle
= node
->view
[i
].idle
;
4371 new_usage
[i
].user
= 0;
4372 new_usage
[i
].system
= 0;
4373 new_usage
[i
].idle
= 0;
4375 new_view
[i
].user
= 0;
4376 new_view
[i
].system
= 0;
4377 new_view
[i
].idle
= 0;
4384 node
->usage
= new_usage
;
4385 node
->view
= new_view
;
4386 node
->cpu_count
= cpu_count
;
4391 static struct cg_proc_stat
*find_or_create_proc_stat_node(struct cpuacct_usage
*usage
, int cpu_count
, const char *cg
)
4393 int hash
= calc_hash(cg
) % CPUVIEW_HASH_SIZE
;
4394 struct cg_proc_stat_head
*head
= proc_stat_history
[hash
];
4395 struct cg_proc_stat
*node
;
4397 node
= find_proc_stat_node(head
, cg
);
4400 node
= new_proc_stat_node(usage
, cpu_count
, cg
);
4404 node
= add_proc_stat_node(node
);
4405 lxcfs_debug("New stat node (%d) for %s\n", cpu_count
, cg
);
4408 pthread_mutex_lock(&node
->lock
);
4410 /* If additional CPUs on the host have been enabled, CPU usage counter
4411 * arrays have to be expanded */
4412 if (node
->cpu_count
< cpu_count
) {
4413 lxcfs_debug("Expanding stat node %d->%d for %s\n",
4414 node
->cpu_count
, cpu_count
, cg
);
4416 if (!expand_proc_stat_node(node
, cpu_count
)) {
4417 pthread_mutex_unlock(&node
->lock
);
4418 lxcfs_debug("Unable to expand stat node %d->%d for %s\n",
4419 node
->cpu_count
, cpu_count
, cg
);
4427 static void reset_proc_stat_node(struct cg_proc_stat
*node
, struct cpuacct_usage
*usage
, int cpu_count
)
4431 lxcfs_debug("Resetting stat node for %s\n", node
->cg
);
4432 memcpy(node
->usage
, usage
, sizeof(struct cpuacct_usage
) * cpu_count
);
4434 for (i
= 0; i
< cpu_count
; i
++) {
4435 node
->view
[i
].user
= 0;
4436 node
->view
[i
].system
= 0;
4437 node
->view
[i
].idle
= 0;
4440 node
->cpu_count
= cpu_count
;
4443 static int cpuview_proc_stat(const char *cg
, const char *cpuset
, struct cpuacct_usage
*cg_cpu_usage
, FILE *f
, char *buf
, size_t buf_size
)
4446 size_t linelen
= 0, total_len
= 0, rv
= 0, l
;
4447 int curcpu
= -1; /* cpu numbering starts at 0 */
4448 int max_cpus
= max_cpu_count(cg
), cpu_cnt
= 0;
4449 unsigned long user
= 0, nice
= 0, system
= 0, idle
= 0, iowait
= 0, irq
= 0, softirq
= 0, steal
= 0, guest
= 0, guest_nice
= 0;
4450 unsigned long user_sum
= 0, system_sum
= 0, idle_sum
= 0;
4451 unsigned long user_surplus
= 0, system_surplus
= 0;
4452 unsigned long total_sum
, threshold
;
4453 struct cg_proc_stat
*stat_node
;
4454 struct cpuacct_usage
*diff
= NULL
;
4455 int nprocs
= get_nprocs();
4457 /* Read all CPU stats and stop when we've encountered other lines */
4458 while (getline(&line
, &linelen
, f
) != -1) {
4460 char cpu_char
[10]; /* That's a lot of cores */
4461 uint64_t all_used
, cg_used
;
4463 if (strlen(line
) == 0)
4465 if (sscanf(line
, "cpu%9[^ ]", cpu_char
) != 1) {
4466 /* not a ^cpuN line containing a number N */
4470 if (sscanf(cpu_char
, "%d", &cpu
) != 1)
4472 if (!cpu_in_cpuset(cpu
, cpuset
))
4477 ret
= sscanf(line
, "%*s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
4492 all_used
= user
+ nice
+ system
+ iowait
+ irq
+ softirq
+ steal
+ guest
+ guest_nice
;
4493 cg_used
= cg_cpu_usage
[curcpu
].user
+ cg_cpu_usage
[curcpu
].system
;
4495 if (all_used
>= cg_used
) {
4496 cg_cpu_usage
[curcpu
].idle
= idle
+ (all_used
- cg_used
);
4499 lxcfs_error("cpu%d from %s has unexpected cpu time: %lu in /proc/stat, "
4500 "%lu in cpuacct.usage_all; unable to determine idle time\n",
4501 curcpu
, cg
, all_used
, cg_used
);
4502 cg_cpu_usage
[curcpu
].idle
= idle
;
4506 /* Cannot use more CPUs than is available due to cpuset */
4507 if (max_cpus
> cpu_cnt
)
4510 stat_node
= find_or_create_proc_stat_node(cg_cpu_usage
, nprocs
, cg
);
4513 lxcfs_error("unable to find/create stat node for %s\n", cg
);
4518 diff
= malloc(sizeof(struct cpuacct_usage
) * nprocs
);
4525 * If the new values are LOWER than values stored in memory, it means
4526 * the cgroup has been reset/recreated and we should reset too.
4528 if (cg_cpu_usage
[0].user
< stat_node
->usage
[0].user
)
4529 reset_proc_stat_node(stat_node
, cg_cpu_usage
, nprocs
);
4531 total_sum
= diff_cpu_usage(stat_node
->usage
, cg_cpu_usage
, diff
, cpu_cnt
);
4533 for (curcpu
= 0; curcpu
< cpu_cnt
; curcpu
++) {
4534 stat_node
->usage
[curcpu
].user
+= diff
[curcpu
].user
;
4535 stat_node
->usage
[curcpu
].system
+= diff
[curcpu
].system
;
4536 stat_node
->usage
[curcpu
].idle
+= diff
[curcpu
].idle
;
4538 if (max_cpus
> 0 && curcpu
>= max_cpus
) {
4539 user_surplus
+= diff
[curcpu
].user
;
4540 system_surplus
+= diff
[curcpu
].system
;
4544 /* Calculate usage counters of visible CPUs */
4546 /* threshold = maximum usage per cpu, including idle */
4547 threshold
= total_sum
/ cpu_cnt
* max_cpus
;
4549 for (curcpu
= 0; curcpu
< max_cpus
; curcpu
++) {
4550 if (diff
[curcpu
].user
+ diff
[curcpu
].system
>= threshold
)
4560 if (diff
[curcpu
].user
+ diff
[curcpu
].system
>= threshold
)
4563 /* If there is still room, add system */
4567 &diff
[curcpu
].system
,
4571 if (user_surplus
> 0)
4572 lxcfs_debug("leftover user: %lu for %s\n", user_surplus
, cg
);
4573 if (system_surplus
> 0)
4574 lxcfs_debug("leftover system: %lu for %s\n", system_surplus
, cg
);
4576 for (curcpu
= 0; curcpu
< max_cpus
; curcpu
++) {
4577 stat_node
->view
[curcpu
].user
+= diff
[curcpu
].user
;
4578 stat_node
->view
[curcpu
].system
+= diff
[curcpu
].system
;
4579 stat_node
->view
[curcpu
].idle
+= diff
[curcpu
].idle
;
4581 user_sum
+= stat_node
->view
[curcpu
].user
;
4582 system_sum
+= stat_node
->view
[curcpu
].system
;
4583 idle_sum
+= stat_node
->view
[curcpu
].idle
;
4587 for (curcpu
= 0; curcpu
< cpu_cnt
; curcpu
++) {
4588 stat_node
->view
[curcpu
].user
= stat_node
->usage
[curcpu
].user
;
4589 stat_node
->view
[curcpu
].system
= stat_node
->usage
[curcpu
].system
;
4590 stat_node
->view
[curcpu
].idle
= stat_node
->usage
[curcpu
].idle
;
4592 user_sum
+= stat_node
->view
[curcpu
].user
;
4593 system_sum
+= stat_node
->view
[curcpu
].system
;
4594 idle_sum
+= stat_node
->view
[curcpu
].idle
;
4598 /* Render the file */
4600 l
= snprintf(buf
, buf_size
, "cpu %lu 0 %lu %lu 0 0 0 0 0 0\n",
4606 perror("Error writing to cache");
4611 if (l
>= buf_size
) {
4612 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4621 /* Render visible CPUs */
4622 for (curcpu
= 0; curcpu
< cpu_cnt
; curcpu
++) {
4623 if (max_cpus
> 0 && curcpu
== max_cpus
)
4626 l
= snprintf(buf
, buf_size
, "cpu%d %lu 0 %lu %lu 0 0 0 0 0 0\n",
4628 stat_node
->view
[curcpu
].user
,
4629 stat_node
->view
[curcpu
].system
,
4630 stat_node
->view
[curcpu
].idle
);
4633 perror("Error writing to cache");
4638 if (l
>= buf_size
) {
4639 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4649 /* Pass the rest of /proc/stat, start with the last line read */
4650 l
= snprintf(buf
, buf_size
, "%s", line
);
4653 perror("Error writing to cache");
4658 if (l
>= buf_size
) {
4659 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4668 /* Pass the rest of the host's /proc/stat */
4669 while (getline(&line
, &linelen
, f
) != -1) {
4670 l
= snprintf(buf
, buf_size
, "%s", line
);
4672 perror("Error writing to cache");
4676 if (l
>= buf_size
) {
4677 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4690 pthread_mutex_unlock(&stat_node
->lock
);
4698 #define CPUALL_MAX_SIZE (BUF_RESERVE_SIZE / 2)
4699 static int proc_stat_read(char *buf
, size_t size
, off_t offset
,
4700 struct fuse_file_info
*fi
)
4702 struct fuse_context
*fc
= fuse_get_context();
4703 struct file_info
*d
= (struct file_info
*)fi
->fh
;
4705 char *cpuset
= NULL
;
4707 size_t linelen
= 0, total_len
= 0, rv
= 0;
4708 int curcpu
= -1; /* cpu numbering starts at 0 */
4709 unsigned long user
= 0, nice
= 0, system
= 0, idle
= 0, iowait
= 0, irq
= 0, softirq
= 0, steal
= 0, guest
= 0, guest_nice
= 0;
4710 unsigned long user_sum
= 0, nice_sum
= 0, system_sum
= 0, idle_sum
= 0, iowait_sum
= 0,
4711 irq_sum
= 0, softirq_sum
= 0, steal_sum
= 0, guest_sum
= 0, guest_nice_sum
= 0;
4712 char cpuall
[CPUALL_MAX_SIZE
];
4713 /* reserve for cpu all */
4714 char *cache
= d
->buf
+ CPUALL_MAX_SIZE
;
4715 size_t cache_size
= d
->buflen
- CPUALL_MAX_SIZE
;
4717 struct cpuacct_usage
*cg_cpu_usage
= NULL
;
4720 if (offset
> d
->size
)
4724 int left
= d
->size
- offset
;
4725 total_len
= left
> size
? size
: left
;
4726 memcpy(buf
, d
->buf
+ offset
, total_len
);
4730 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
4733 cg
= get_pid_cgroup(initpid
, "cpuset");
4735 return read_file("/proc/stat", buf
, size
, d
);
4736 prune_init_slice(cg
);
4738 cpuset
= get_cpuset(cg
);
4743 * Read cpuacct.usage_all for all CPUs.
4744 * If the cpuacct cgroup is present, it is used to calculate the container's
4745 * CPU usage. If not, values from the host's /proc/stat are used.
4747 if (read_cpuacct_usage_all(cg
, cpuset
, &cg_cpu_usage
) != 0) {
4748 lxcfs_debug("%s\n", "proc_stat_read failed to read from cpuacct, "
4749 "falling back to the host's /proc/stat");
4752 f
= fopen("/proc/stat", "r");
4757 if (getline(&line
, &linelen
, f
) < 0) {
4758 lxcfs_error("%s\n", "proc_stat_read read first line failed.");
4762 if (use_cpuview(cg
) && cg_cpu_usage
) {
4763 total_len
= cpuview_proc_stat(cg
, cpuset
, cg_cpu_usage
, f
, d
->buf
, d
->buflen
);
4767 while (getline(&line
, &linelen
, f
) != -1) {
4770 char cpu_char
[10]; /* That's a lot of cores */
4772 uint64_t all_used
, cg_used
, new_idle
;
4775 if (strlen(line
) == 0)
4777 if (sscanf(line
, "cpu%9[^ ]", cpu_char
) != 1) {
4778 /* not a ^cpuN line containing a number N, just print it */
4779 l
= snprintf(cache
, cache_size
, "%s", line
);
4781 perror("Error writing to cache");
4785 if (l
>= cache_size
) {
4786 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4796 if (sscanf(cpu_char
, "%d", &cpu
) != 1)
4798 if (!cpu_in_cpuset(cpu
, cpuset
))
4802 ret
= sscanf(line
, "%*s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
4814 if (ret
!= 10 || !cg_cpu_usage
) {
4815 c
= strchr(line
, ' ');
4818 l
= snprintf(cache
, cache_size
, "cpu%d%s", curcpu
, c
);
4820 perror("Error writing to cache");
4825 if (l
>= cache_size
) {
4826 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4840 all_used
= user
+ nice
+ system
+ iowait
+ irq
+ softirq
+ steal
+ guest
+ guest_nice
;
4841 cg_used
= cg_cpu_usage
[curcpu
].user
+ cg_cpu_usage
[curcpu
].system
;
4843 if (all_used
>= cg_used
) {
4844 new_idle
= idle
+ (all_used
- cg_used
);
4847 lxcfs_error("cpu%d from %s has unexpected cpu time: %lu in /proc/stat, "
4848 "%lu in cpuacct.usage_all; unable to determine idle time\n",
4849 curcpu
, cg
, all_used
, cg_used
);
4853 l
= snprintf(cache
, cache_size
, "cpu%d %lu 0 %lu %lu 0 0 0 0 0 0\n",
4854 curcpu
, cg_cpu_usage
[curcpu
].user
, cg_cpu_usage
[curcpu
].system
,
4858 perror("Error writing to cache");
4863 if (l
>= cache_size
) {
4864 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4873 user_sum
+= cg_cpu_usage
[curcpu
].user
;
4874 system_sum
+= cg_cpu_usage
[curcpu
].system
;
4875 idle_sum
+= new_idle
;
4880 system_sum
+= system
;
4882 iowait_sum
+= iowait
;
4884 softirq_sum
+= softirq
;
4887 guest_nice_sum
+= guest_nice
;
4893 int cpuall_len
= snprintf(cpuall
, CPUALL_MAX_SIZE
, "cpu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
4904 if (cpuall_len
> 0 && cpuall_len
< CPUALL_MAX_SIZE
) {
4905 memcpy(cache
, cpuall
, cpuall_len
);
4906 cache
+= cpuall_len
;
4908 /* shouldn't happen */
4909 lxcfs_error("proc_stat_read copy cpuall failed, cpuall_len=%d.", cpuall_len
);
4913 memmove(cache
, d
->buf
+ CPUALL_MAX_SIZE
, total_len
);
4914 total_len
+= cpuall_len
;
4918 d
->size
= total_len
;
4919 if (total_len
> size
)
4922 memcpy(buf
, d
->buf
, total_len
);
4936 /* This function retrieves the busy time of a group of tasks by looking at
4937 * cpuacct.usage. Unfortunately, this only makes sense when the container has
4938 * been given it's own cpuacct cgroup. If not, this function will take the busy
4939 * time of all other taks that do not actually belong to the container into
4940 * account as well. If someone has a clever solution for this please send a
4943 static unsigned long get_reaper_busy(pid_t task
)
4945 pid_t initpid
= lookup_initpid_in_store(task
);
4946 char *cgroup
= NULL
, *usage_str
= NULL
;
4947 unsigned long usage
= 0;
4952 cgroup
= get_pid_cgroup(initpid
, "cpuacct");
4955 prune_init_slice(cgroup
);
4956 if (!cgfs_get_value("cpuacct", cgroup
, "cpuacct.usage", &usage_str
))
4958 usage
= strtoul(usage_str
, NULL
, 10);
4959 usage
/= 1000000000;
4972 fd
= creat("/tmp/lxcfs-iwashere", 0644);
4979 * We read /proc/uptime and reuse its second field.
4980 * For the first field, we use the mtime for the reaper for
4981 * the calling pid as returned by getreaperage
4983 static int proc_uptime_read(char *buf
, size_t size
, off_t offset
,
4984 struct fuse_file_info
*fi
)
4986 struct fuse_context
*fc
= fuse_get_context();
4987 struct file_info
*d
= (struct file_info
*)fi
->fh
;
4988 unsigned long int busytime
= get_reaper_busy(fc
->pid
);
4989 char *cache
= d
->buf
;
4990 ssize_t total_len
= 0;
4991 uint64_t idletime
, reaperage
;
5000 if (offset
> d
->size
)
5002 int left
= d
->size
- offset
;
5003 total_len
= left
> size
? size
: left
;
5004 memcpy(buf
, cache
+ offset
, total_len
);
5008 reaperage
= get_reaper_age(fc
->pid
);
5009 /* To understand why this is done, please read the comment to the
5010 * get_reaper_busy() function.
5012 idletime
= reaperage
;
5013 if (reaperage
>= busytime
)
5014 idletime
= reaperage
- busytime
;
5016 total_len
= snprintf(d
->buf
, d
->buflen
, "%"PRIu64
".00 %"PRIu64
".00\n", reaperage
, idletime
);
5017 if (total_len
< 0 || total_len
>= d
->buflen
){
5018 lxcfs_error("%s\n", "failed to write to cache");
5022 d
->size
= (int)total_len
;
5025 if (total_len
> size
) total_len
= size
;
5027 memcpy(buf
, d
->buf
, total_len
);
5031 static int proc_diskstats_read(char *buf
, size_t size
, off_t offset
,
5032 struct fuse_file_info
*fi
)
5035 struct fuse_context
*fc
= fuse_get_context();
5036 struct file_info
*d
= (struct file_info
*)fi
->fh
;
5038 char *io_serviced_str
= NULL
, *io_merged_str
= NULL
, *io_service_bytes_str
= NULL
,
5039 *io_wait_time_str
= NULL
, *io_service_time_str
= NULL
;
5040 unsigned long read
= 0, write
= 0;
5041 unsigned long read_merged
= 0, write_merged
= 0;
5042 unsigned long read_sectors
= 0, write_sectors
= 0;
5043 unsigned long read_ticks
= 0, write_ticks
= 0;
5044 unsigned long ios_pgr
= 0, tot_ticks
= 0, rq_ticks
= 0;
5045 unsigned long rd_svctm
= 0, wr_svctm
= 0, rd_wait
= 0, wr_wait
= 0;
5046 char *cache
= d
->buf
;
5047 size_t cache_size
= d
->buflen
;
5049 size_t linelen
= 0, total_len
= 0, rv
= 0;
5050 unsigned int major
= 0, minor
= 0;
5055 if (offset
> d
->size
)
5059 int left
= d
->size
- offset
;
5060 total_len
= left
> size
? size
: left
;
5061 memcpy(buf
, cache
+ offset
, total_len
);
5065 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
5068 cg
= get_pid_cgroup(initpid
, "blkio");
5070 return read_file("/proc/diskstats", buf
, size
, d
);
5071 prune_init_slice(cg
);
5073 if (!cgfs_get_value("blkio", cg
, "blkio.io_serviced_recursive", &io_serviced_str
))
5075 if (!cgfs_get_value("blkio", cg
, "blkio.io_merged_recursive", &io_merged_str
))
5077 if (!cgfs_get_value("blkio", cg
, "blkio.io_service_bytes_recursive", &io_service_bytes_str
))
5079 if (!cgfs_get_value("blkio", cg
, "blkio.io_wait_time_recursive", &io_wait_time_str
))
5081 if (!cgfs_get_value("blkio", cg
, "blkio.io_service_time_recursive", &io_service_time_str
))
5085 f
= fopen("/proc/diskstats", "r");
5089 while (getline(&line
, &linelen
, f
) != -1) {
5093 i
= sscanf(line
, "%u %u %71s", &major
, &minor
, dev_name
);
5097 get_blkio_io_value(io_serviced_str
, major
, minor
, "Read", &read
);
5098 get_blkio_io_value(io_serviced_str
, major
, minor
, "Write", &write
);
5099 get_blkio_io_value(io_merged_str
, major
, minor
, "Read", &read_merged
);
5100 get_blkio_io_value(io_merged_str
, major
, minor
, "Write", &write_merged
);
5101 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Read", &read_sectors
);
5102 read_sectors
= read_sectors
/512;
5103 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Write", &write_sectors
);
5104 write_sectors
= write_sectors
/512;
5106 get_blkio_io_value(io_service_time_str
, major
, minor
, "Read", &rd_svctm
);
5107 rd_svctm
= rd_svctm
/1000000;
5108 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Read", &rd_wait
);
5109 rd_wait
= rd_wait
/1000000;
5110 read_ticks
= rd_svctm
+ rd_wait
;
5112 get_blkio_io_value(io_service_time_str
, major
, minor
, "Write", &wr_svctm
);
5113 wr_svctm
= wr_svctm
/1000000;
5114 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Write", &wr_wait
);
5115 wr_wait
= wr_wait
/1000000;
5116 write_ticks
= wr_svctm
+ wr_wait
;
5118 get_blkio_io_value(io_service_time_str
, major
, minor
, "Total", &tot_ticks
);
5119 tot_ticks
= tot_ticks
/1000000;
5121 memset(lbuf
, 0, 256);
5122 if (read
|| write
|| read_merged
|| write_merged
|| read_sectors
|| write_sectors
|| read_ticks
|| write_ticks
)
5123 snprintf(lbuf
, 256, "%u %u %s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
5124 major
, minor
, dev_name
, read
, read_merged
, read_sectors
, read_ticks
,
5125 write
, write_merged
, write_sectors
, write_ticks
, ios_pgr
, tot_ticks
, rq_ticks
);
5129 l
= snprintf(cache
, cache_size
, "%s", lbuf
);
5131 perror("Error writing to fuse buf");
5135 if (l
>= cache_size
) {
5136 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
5146 d
->size
= total_len
;
5147 if (total_len
> size
) total_len
= size
;
5148 memcpy(buf
, d
->buf
, total_len
);
5156 free(io_serviced_str
);
5157 free(io_merged_str
);
5158 free(io_service_bytes_str
);
5159 free(io_wait_time_str
);
5160 free(io_service_time_str
);
5164 static int proc_swaps_read(char *buf
, size_t size
, off_t offset
,
5165 struct fuse_file_info
*fi
)
5167 struct fuse_context
*fc
= fuse_get_context();
5168 struct file_info
*d
= (struct file_info
*)fi
->fh
;
5170 char *memswlimit_str
= NULL
, *memlimit_str
= NULL
, *memusage_str
= NULL
, *memswusage_str
= NULL
;
5171 unsigned long memswlimit
= 0, memlimit
= 0, memusage
= 0, memswusage
= 0, swap_total
= 0, swap_free
= 0;
5172 ssize_t total_len
= 0, rv
= 0;
5174 char *cache
= d
->buf
;
5177 if (offset
> d
->size
)
5181 int left
= d
->size
- offset
;
5182 total_len
= left
> size
? size
: left
;
5183 memcpy(buf
, cache
+ offset
, total_len
);
5187 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
5190 cg
= get_pid_cgroup(initpid
, "memory");
5192 return read_file("/proc/swaps", buf
, size
, d
);
5193 prune_init_slice(cg
);
5195 memlimit
= get_min_memlimit(cg
, "memory.limit_in_bytes");
5197 if (!cgfs_get_value("memory", cg
, "memory.usage_in_bytes", &memusage_str
))
5200 memusage
= strtoul(memusage_str
, NULL
, 10);
5202 if (cgfs_get_value("memory", cg
, "memory.memsw.usage_in_bytes", &memswusage_str
) &&
5203 cgfs_get_value("memory", cg
, "memory.memsw.limit_in_bytes", &memswlimit_str
)) {
5205 memswlimit
= get_min_memlimit(cg
, "memory.memsw.limit_in_bytes");
5206 memswusage
= strtoul(memswusage_str
, NULL
, 10);
5208 swap_total
= (memswlimit
- memlimit
) / 1024;
5209 swap_free
= (memswusage
- memusage
) / 1024;
5212 total_len
= snprintf(d
->buf
, d
->size
, "Filename\t\t\t\tType\t\tSize\tUsed\tPriority\n");
5214 /* When no mem + swap limit is specified or swapaccount=0*/
5218 FILE *f
= fopen("/proc/meminfo", "r");
5223 while (getline(&line
, &linelen
, f
) != -1) {
5224 if (startswith(line
, "SwapTotal:")) {
5225 sscanf(line
, "SwapTotal: %8lu kB", &swap_total
);
5226 } else if (startswith(line
, "SwapFree:")) {
5227 sscanf(line
, "SwapFree: %8lu kB", &swap_free
);
5235 if (swap_total
> 0) {
5236 l
= snprintf(d
->buf
+ total_len
, d
->size
- total_len
,
5237 "none%*svirtual\t\t%lu\t%lu\t0\n", 36, " ",
5238 swap_total
, swap_free
);
5242 if (total_len
< 0 || l
< 0) {
5243 perror("Error writing to cache");
5249 d
->size
= (int)total_len
;
5251 if (total_len
> size
) total_len
= size
;
5252 memcpy(buf
, d
->buf
, total_len
);
5257 free(memswlimit_str
);
5260 free(memswusage_str
);
5264 * Find the process pid from cgroup path.
5265 * eg:from /sys/fs/cgroup/cpu/docker/containerid/cgroup.procs to find the process pid.
5266 * @pid_buf : put pid to pid_buf.
5267 * @dpath : the path of cgroup. eg: /docker/containerid or /docker/containerid/child-cgroup ...
5268 * @depth : the depth of cgroup in container.
5269 * @sum : return the number of pid.
5270 * @cfd : the file descriptor of the mounted cgroup. eg: /sys/fs/cgroup/cpu
5272 static int calc_pid(char ***pid_buf
, char *dpath
, int depth
, int sum
, int cfd
)
5276 struct dirent
*file
;
5281 char *path_dir
, *path
;
5284 /* path = dpath + "/cgroup.procs" + /0 */
5286 path
= malloc(strlen(dpath
) + 20);
5289 strcpy(path
, dpath
);
5290 fd
= openat(cfd
, path
, O_RDONLY
);
5294 dir
= fdopendir(fd
);
5300 while (((file
= readdir(dir
)) != NULL
) && depth
> 0) {
5301 if (strncmp(file
->d_name
, ".", 1) == 0)
5303 if (strncmp(file
->d_name
, "..", 1) == 0)
5305 if (file
->d_type
== DT_DIR
) {
5306 /* path + '/' + d_name +/0 */
5308 path_dir
= malloc(strlen(path
) + 2 + sizeof(file
->d_name
));
5309 } while (!path_dir
);
5310 strcpy(path_dir
, path
);
5311 strcat(path_dir
, "/");
5312 strcat(path_dir
, file
->d_name
);
5314 sum
= calc_pid(pid_buf
, path_dir
, pd
, sum
, cfd
);
5320 strcat(path
, "/cgroup.procs");
5321 fd
= openat(cfd
, path
, O_RDONLY
);
5325 f
= fdopen(fd
, "r");
5331 while (getline(&line
, &linelen
, f
) != -1) {
5333 pid
= realloc(*pid_buf
, sizeof(char *) * (sum
+ 1));
5337 *(*pid_buf
+ sum
) = malloc(strlen(line
) + 1);
5338 } while (*(*pid_buf
+ sum
) == NULL
);
5339 strcpy(*(*pid_buf
+ sum
), line
);
5350 * calc_load calculates the load according to the following formula:
5351 * load1 = load0 * exp + active * (1 - exp)
5353 * @load1: the new loadavg.
5354 * @load0: the former loadavg.
5355 * @active: the total number of running pid at this moment.
5356 * @exp: the fixed-point defined in the beginning.
5358 static unsigned long
5359 calc_load(unsigned long load
, unsigned long exp
, unsigned long active
)
5361 unsigned long newload
;
5363 active
= active
> 0 ? active
* FIXED_1
: 0;
5364 newload
= load
* exp
+ active
* (FIXED_1
- exp
);
5366 newload
+= FIXED_1
- 1;
5368 return newload
/ FIXED_1
;
5372 * Return 0 means that container p->cg is closed.
5373 * Return -1 means that error occurred in refresh.
5374 * Positive num equals the total number of pid.
5376 static int refresh_load(struct load_node
*p
, char *path
)
5380 char proc_path
[256];
5381 int i
, ret
, run_pid
= 0, total_pid
= 0, last_pid
= 0;
5386 struct dirent
*file
;
5389 idbuf
= malloc(sizeof(char *));
5391 sum
= calc_pid(&idbuf
, path
, DEPTH_DIR
, 0, p
->cfd
);
5396 for (i
= 0; i
< sum
; i
++) {
5398 length
= strlen(idbuf
[i
])-1;
5399 idbuf
[i
][length
] = '\0';
5400 ret
= snprintf(proc_path
, 256, "/proc/%s/task", idbuf
[i
]);
5401 if (ret
< 0 || ret
> 255) {
5402 lxcfs_error("%s\n", "snprintf() failed in refresh_load.");
5408 dp
= opendir(proc_path
);
5410 lxcfs_error("%s\n", "Open proc_path failed in refresh_load.");
5413 while ((file
= readdir(dp
)) != NULL
) {
5414 if (strncmp(file
->d_name
, ".", 1) == 0)
5416 if (strncmp(file
->d_name
, "..", 1) == 0)
5419 /* We make the biggest pid become last_pid.*/
5420 ret
= atof(file
->d_name
);
5421 last_pid
= (ret
> last_pid
) ? ret
: last_pid
;
5423 ret
= snprintf(proc_path
, 256, "/proc/%s/task/%s/status", idbuf
[i
], file
->d_name
);
5424 if (ret
< 0 || ret
> 255) {
5425 lxcfs_error("%s\n", "snprintf() failed in refresh_load.");
5431 f
= fopen(proc_path
, "r");
5433 while (getline(&line
, &linelen
, f
) != -1) {
5435 if ((line
[0] == 'S') && (line
[1] == 't'))
5438 if ((line
[7] == 'R') || (line
[7] == 'D'))
5445 /*Calculate the loadavg.*/
5446 p
->avenrun
[0] = calc_load(p
->avenrun
[0], EXP_1
, run_pid
);
5447 p
->avenrun
[1] = calc_load(p
->avenrun
[1], EXP_5
, run_pid
);
5448 p
->avenrun
[2] = calc_load(p
->avenrun
[2], EXP_15
, run_pid
);
5449 p
->run_pid
= run_pid
;
5450 p
->total_pid
= total_pid
;
5451 p
->last_pid
= last_pid
;
5462 * Traverse the hash table and update it.
5464 void *load_begin(void *arg
)
5468 int i
, sum
, length
, ret
;
5469 struct load_node
*f
;
5471 clock_t time1
, time2
;
5474 if (loadavg_stop
== 1)
5478 for (i
= 0; i
< LOAD_SIZE
; i
++) {
5479 pthread_mutex_lock(&load_hash
[i
].lock
);
5480 if (load_hash
[i
].next
== NULL
) {
5481 pthread_mutex_unlock(&load_hash
[i
].lock
);
5484 f
= load_hash
[i
].next
;
5487 length
= strlen(f
->cg
) + 2;
5489 /* strlen(f->cg) + '.' or '' + \0 */
5490 path
= malloc(length
);
5493 ret
= snprintf(path
, length
, "%s%s", *(f
->cg
) == '/' ? "." : "", f
->cg
);
5494 if (ret
< 0 || ret
> length
- 1) {
5495 /* snprintf failed, ignore the node.*/
5496 lxcfs_error("Refresh node %s failed for snprintf().\n", f
->cg
);
5499 sum
= refresh_load(f
, path
);
5506 /* load_hash[i].lock locks only on the first node.*/
5507 if (first_node
== 1) {
5509 pthread_mutex_unlock(&load_hash
[i
].lock
);
5514 if (loadavg_stop
== 1)
5518 usleep(FLUSH_TIME
* 1000000 - (int)((time2
- time1
) * 1000000 / CLOCKS_PER_SEC
));
5522 static int proc_loadavg_read(char *buf
, size_t size
, off_t offset
,
5523 struct fuse_file_info
*fi
)
5525 struct fuse_context
*fc
= fuse_get_context();
5526 struct file_info
*d
= (struct file_info
*)fi
->fh
;
5529 size_t total_len
= 0;
5530 char *cache
= d
->buf
;
5531 struct load_node
*n
;
5534 unsigned long a
, b
, c
;
5537 if (offset
> d
->size
)
5541 int left
= d
->size
- offset
;
5542 total_len
= left
> size
? size
: left
;
5543 memcpy(buf
, cache
+ offset
, total_len
);
5547 return read_file("/proc/loadavg", buf
, size
, d
);
5549 initpid
= lookup_initpid_in_store(fc
->pid
);
5552 cg
= get_pid_cgroup(initpid
, "cpu");
5554 return read_file("/proc/loadavg", buf
, size
, d
);
5556 prune_init_slice(cg
);
5557 hash
= calc_hash(cg
) % LOAD_SIZE
;
5558 n
= locate_node(cg
, hash
);
5562 if (!find_mounted_controller("cpu", &cfd
)) {
5564 * In locate_node() above, pthread_rwlock_unlock() isn't used
5565 * because delete is not allowed before read has ended.
5567 pthread_rwlock_unlock(&load_hash
[hash
].rdlock
);
5572 n
= malloc(sizeof(struct load_node
));
5576 n
->cg
= malloc(strlen(cg
)+1);
5584 n
->last_pid
= initpid
;
5586 insert_node(&n
, hash
);
5588 a
= n
->avenrun
[0] + (FIXED_1
/200);
5589 b
= n
->avenrun
[1] + (FIXED_1
/200);
5590 c
= n
->avenrun
[2] + (FIXED_1
/200);
5591 total_len
= snprintf(d
->buf
, d
->buflen
, "%lu.%02lu %lu.%02lu %lu.%02lu %d/%d %d\n",
5592 LOAD_INT(a
), LOAD_FRAC(a
),
5593 LOAD_INT(b
), LOAD_FRAC(b
),
5594 LOAD_INT(c
), LOAD_FRAC(c
),
5595 n
->run_pid
, n
->total_pid
, n
->last_pid
);
5596 pthread_rwlock_unlock(&load_hash
[hash
].rdlock
);
5597 if (total_len
< 0 || total_len
>= d
->buflen
) {
5598 lxcfs_error("%s\n", "Failed to write to cache");
5602 d
->size
= (int)total_len
;
5605 if (total_len
> size
)
5607 memcpy(buf
, d
->buf
, total_len
);
5614 /* Return a positive number on success, return 0 on failure.*/
5615 pthread_t
load_daemon(int load_use
)
5622 lxcfs_error("%s\n", "Initialize hash_table fails in load_daemon!");
5625 ret
= pthread_create(&pid
, NULL
, load_begin
, NULL
);
5627 lxcfs_error("%s\n", "Create pthread fails in load_daemon!");
5631 /* use loadavg, here loadavg = 1*/
5636 /* Returns 0 on success. */
5637 int stop_load_daemon(pthread_t pid
)
5641 /* Signal the thread to gracefully stop */
5644 s
= pthread_join(pid
, NULL
); /* Make sure sub thread has been canceled. */
5646 lxcfs_error("%s\n", "stop_load_daemon error: failed to join");
5656 static off_t
get_procfile_size(const char *which
)
5658 FILE *f
= fopen(which
, "r");
5661 ssize_t sz
, answer
= 0;
5665 while ((sz
= getline(&line
, &len
, f
)) != -1)
5673 int proc_getattr(const char *path
, struct stat
*sb
)
5675 struct timespec now
;
5677 memset(sb
, 0, sizeof(struct stat
));
5678 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
5680 sb
->st_uid
= sb
->st_gid
= 0;
5681 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
5682 if (strcmp(path
, "/proc") == 0) {
5683 sb
->st_mode
= S_IFDIR
| 00555;
5687 if (strcmp(path
, "/proc/meminfo") == 0 ||
5688 strcmp(path
, "/proc/cpuinfo") == 0 ||
5689 strcmp(path
, "/proc/uptime") == 0 ||
5690 strcmp(path
, "/proc/stat") == 0 ||
5691 strcmp(path
, "/proc/diskstats") == 0 ||
5692 strcmp(path
, "/proc/swaps") == 0 ||
5693 strcmp(path
, "/proc/loadavg") == 0) {
5695 sb
->st_mode
= S_IFREG
| 00444;
5703 int proc_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
5704 struct fuse_file_info
*fi
)
5706 if (filler(buf
, ".", NULL
, 0) != 0 ||
5707 filler(buf
, "..", NULL
, 0) != 0 ||
5708 filler(buf
, "cpuinfo", NULL
, 0) != 0 ||
5709 filler(buf
, "meminfo", NULL
, 0) != 0 ||
5710 filler(buf
, "stat", NULL
, 0) != 0 ||
5711 filler(buf
, "uptime", NULL
, 0) != 0 ||
5712 filler(buf
, "diskstats", NULL
, 0) != 0 ||
5713 filler(buf
, "swaps", NULL
, 0) != 0 ||
5714 filler(buf
, "loadavg", NULL
, 0) != 0)
5719 int proc_open(const char *path
, struct fuse_file_info
*fi
)
5722 struct file_info
*info
;
5724 if (strcmp(path
, "/proc/meminfo") == 0)
5725 type
= LXC_TYPE_PROC_MEMINFO
;
5726 else if (strcmp(path
, "/proc/cpuinfo") == 0)
5727 type
= LXC_TYPE_PROC_CPUINFO
;
5728 else if (strcmp(path
, "/proc/uptime") == 0)
5729 type
= LXC_TYPE_PROC_UPTIME
;
5730 else if (strcmp(path
, "/proc/stat") == 0)
5731 type
= LXC_TYPE_PROC_STAT
;
5732 else if (strcmp(path
, "/proc/diskstats") == 0)
5733 type
= LXC_TYPE_PROC_DISKSTATS
;
5734 else if (strcmp(path
, "/proc/swaps") == 0)
5735 type
= LXC_TYPE_PROC_SWAPS
;
5736 else if (strcmp(path
, "/proc/loadavg") == 0)
5737 type
= LXC_TYPE_PROC_LOADAVG
;
5741 info
= malloc(sizeof(*info
));
5745 memset(info
, 0, sizeof(*info
));
5748 info
->buflen
= get_procfile_size(path
) + BUF_RESERVE_SIZE
;
5750 info
->buf
= malloc(info
->buflen
);
5751 } while (!info
->buf
);
5752 memset(info
->buf
, 0, info
->buflen
);
5753 /* set actual size to buffer size */
5754 info
->size
= info
->buflen
;
5756 fi
->fh
= (unsigned long)info
;
5760 int proc_access(const char *path
, int mask
)
5762 if (strcmp(path
, "/proc") == 0 && access(path
, R_OK
) == 0)
5765 /* these are all read-only */
5766 if ((mask
& ~R_OK
) != 0)
5771 int proc_release(const char *path
, struct fuse_file_info
*fi
)
5773 do_release_file_info(fi
);
5777 int proc_read(const char *path
, char *buf
, size_t size
, off_t offset
,
5778 struct fuse_file_info
*fi
)
5780 struct file_info
*f
= (struct file_info
*) fi
->fh
;
5783 case LXC_TYPE_PROC_MEMINFO
:
5784 return proc_meminfo_read(buf
, size
, offset
, fi
);
5785 case LXC_TYPE_PROC_CPUINFO
:
5786 return proc_cpuinfo_read(buf
, size
, offset
, fi
);
5787 case LXC_TYPE_PROC_UPTIME
:
5788 return proc_uptime_read(buf
, size
, offset
, fi
);
5789 case LXC_TYPE_PROC_STAT
:
5790 return proc_stat_read(buf
, size
, offset
, fi
);
5791 case LXC_TYPE_PROC_DISKSTATS
:
5792 return proc_diskstats_read(buf
, size
, offset
, fi
);
5793 case LXC_TYPE_PROC_SWAPS
:
5794 return proc_swaps_read(buf
, size
, offset
, fi
);
5795 case LXC_TYPE_PROC_LOADAVG
:
5796 return proc_loadavg_read(buf
, size
, offset
, fi
);
5803 * Functions needed to setup cgroups in the __constructor__.
5806 static bool mkdir_p(const char *dir
, mode_t mode
)
5808 const char *tmp
= dir
;
5809 const char *orig
= dir
;
5813 dir
= tmp
+ strspn(tmp
, "/");
5814 tmp
= dir
+ strcspn(dir
, "/");
5815 makeme
= strndup(orig
, dir
- orig
);
5818 if (mkdir(makeme
, mode
) && errno
!= EEXIST
) {
5819 lxcfs_error("Failed to create directory '%s': %s.\n",
5820 makeme
, strerror(errno
));
5825 } while(tmp
!= dir
);
5830 static bool umount_if_mounted(void)
5832 if (umount2(BASEDIR
, MNT_DETACH
) < 0 && errno
!= EINVAL
) {
5833 lxcfs_error("Failed to unmount %s: %s.\n", BASEDIR
, strerror(errno
));
5839 /* __typeof__ should be safe to use with all compilers. */
5840 typedef __typeof__(((struct statfs
*)NULL
)->f_type
) fs_type_magic
;
5841 static bool has_fs_type(const struct statfs
*fs
, fs_type_magic magic_val
)
5843 return (fs
->f_type
== (fs_type_magic
)magic_val
);
5847 * looking at fs/proc_namespace.c, it appears we can
5848 * actually expect the rootfs entry to very specifically contain
5849 * " - rootfs rootfs "
5850 * IIUC, so long as we've chrooted so that rootfs is not our root,
5851 * the rootfs entry should always be skipped in mountinfo contents.
5853 static bool is_on_ramfs(void)
5861 f
= fopen("/proc/self/mountinfo", "r");
5865 while (getline(&line
, &len
, f
) != -1) {
5866 for (p
= line
, i
= 0; p
&& i
< 4; i
++)
5867 p
= strchr(p
+ 1, ' ');
5870 p2
= strchr(p
+ 1, ' ');
5874 if (strcmp(p
+ 1, "/") == 0) {
5875 // this is '/'. is it the ramfs?
5876 p
= strchr(p2
+ 1, '-');
5877 if (p
&& strncmp(p
, "- rootfs rootfs ", 16) == 0) {
5889 static int pivot_enter()
5891 int ret
= -1, oldroot
= -1, newroot
= -1;
5893 oldroot
= open("/", O_DIRECTORY
| O_RDONLY
);
5895 lxcfs_error("%s\n", "Failed to open old root for fchdir.");
5899 newroot
= open(ROOTDIR
, O_DIRECTORY
| O_RDONLY
);
5901 lxcfs_error("%s\n", "Failed to open new root for fchdir.");
5905 /* change into new root fs */
5906 if (fchdir(newroot
) < 0) {
5907 lxcfs_error("Failed to change directory to new rootfs: %s.\n", ROOTDIR
);
5911 /* pivot_root into our new root fs */
5912 if (pivot_root(".", ".") < 0) {
5913 lxcfs_error("pivot_root() syscall failed: %s.\n", strerror(errno
));
5918 * At this point the old-root is mounted on top of our new-root.
5919 * To unmounted it we must not be chdir'd into it, so escape back
5922 if (fchdir(oldroot
) < 0) {
5923 lxcfs_error("%s\n", "Failed to enter old root.");
5927 if (umount2(".", MNT_DETACH
) < 0) {
5928 lxcfs_error("%s\n", "Failed to detach old root.");
5932 if (fchdir(newroot
) < 0) {
5933 lxcfs_error("%s\n", "Failed to re-enter new root.");
5948 static int chroot_enter()
5950 if (mount(ROOTDIR
, "/", NULL
, MS_REC
| MS_BIND
, NULL
)) {
5951 lxcfs_error("Failed to recursively bind-mount %s into /.", ROOTDIR
);
5955 if (chroot(".") < 0) {
5956 lxcfs_error("Call to chroot() failed: %s.\n", strerror(errno
));
5960 if (chdir("/") < 0) {
5961 lxcfs_error("Failed to change directory: %s.\n", strerror(errno
));
5968 static int permute_and_enter(void)
5972 if (statfs("/", &sb
) < 0) {
5973 lxcfs_error("%s\n", "Could not stat / mountpoint.");
5977 /* has_fs_type() is not reliable. When the ramfs is a tmpfs it will
5978 * likely report TMPFS_MAGIC. Hence, when it reports no we still check
5979 * /proc/1/mountinfo. */
5980 if (has_fs_type(&sb
, RAMFS_MAGIC
) || is_on_ramfs())
5981 return chroot_enter();
5983 if (pivot_enter() < 0) {
5984 lxcfs_error("%s\n", "Could not perform pivot root.");
5991 /* Prepare our new clean root. */
5992 static int permute_prepare(void)
5994 if (mkdir(ROOTDIR
, 0700) < 0 && errno
!= EEXIST
) {
5995 lxcfs_error("%s\n", "Failed to create directory for new root.");
5999 if (mount("/", ROOTDIR
, NULL
, MS_BIND
, 0) < 0) {
6000 lxcfs_error("Failed to bind-mount / for new root: %s.\n", strerror(errno
));
6004 if (mount(RUNTIME_PATH
, ROOTDIR RUNTIME_PATH
, NULL
, MS_BIND
, 0) < 0) {
6005 lxcfs_error("Failed to bind-mount /run into new root: %s.\n", strerror(errno
));
6009 if (mount(BASEDIR
, ROOTDIR BASEDIR
, NULL
, MS_REC
| MS_MOVE
, 0) < 0) {
6010 printf("Failed to move " BASEDIR
" into new root: %s.\n", strerror(errno
));
6017 /* Calls chroot() on ramfs, pivot_root() in all other cases. */
6018 static bool permute_root(void)
6020 /* Prepare new root. */
6021 if (permute_prepare() < 0)
6024 /* Pivot into new root. */
6025 if (permute_and_enter() < 0)
6031 static int preserve_mnt_ns(int pid
)
6034 size_t len
= sizeof("/proc/") + 21 + sizeof("/ns/mnt");
6037 ret
= snprintf(path
, len
, "/proc/%d/ns/mnt", pid
);
6038 if (ret
< 0 || (size_t)ret
>= len
)
6041 return open(path
, O_RDONLY
| O_CLOEXEC
);
6044 static bool cgfs_prepare_mounts(void)
6046 if (!mkdir_p(BASEDIR
, 0700)) {
6047 lxcfs_error("%s\n", "Failed to create lxcfs cgroup mountpoint.");
6051 if (!umount_if_mounted()) {
6052 lxcfs_error("%s\n", "Failed to clean up old lxcfs cgroup mountpoint.");
6056 if (unshare(CLONE_NEWNS
) < 0) {
6057 lxcfs_error("Failed to unshare mount namespace: %s.\n", strerror(errno
));
6061 cgroup_mount_ns_fd
= preserve_mnt_ns(getpid());
6062 if (cgroup_mount_ns_fd
< 0) {
6063 lxcfs_error("Failed to preserve mount namespace: %s.\n", strerror(errno
));
6067 if (mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, 0) < 0) {
6068 lxcfs_error("Failed to remount / private: %s.\n", strerror(errno
));
6072 if (mount("tmpfs", BASEDIR
, "tmpfs", 0, "size=100000,mode=700") < 0) {
6073 lxcfs_error("%s\n", "Failed to mount tmpfs over lxcfs cgroup mountpoint.");
6080 static bool cgfs_mount_hierarchies(void)
6086 for (i
= 0; i
< num_hierarchies
; i
++) {
6087 char *controller
= hierarchies
[i
];
6089 clen
= strlen(controller
);
6090 len
= strlen(BASEDIR
) + clen
+ 2;
6091 target
= malloc(len
);
6095 ret
= snprintf(target
, len
, "%s/%s", BASEDIR
, controller
);
6096 if (ret
< 0 || ret
>= len
) {
6100 if (mkdir(target
, 0755) < 0 && errno
!= EEXIST
) {
6104 if (!strcmp(controller
, "unified"))
6105 ret
= mount("none", target
, "cgroup2", 0, NULL
);
6107 ret
= mount(controller
, target
, "cgroup", 0, controller
);
6109 lxcfs_error("Failed mounting cgroup %s: %s\n", controller
, strerror(errno
));
6114 fd_hierarchies
[i
] = open(target
, O_DIRECTORY
);
6115 if (fd_hierarchies
[i
] < 0) {
6124 static bool cgfs_setup_controllers(void)
6126 if (!cgfs_prepare_mounts())
6129 if (!cgfs_mount_hierarchies()) {
6130 lxcfs_error("%s\n", "Failed to set up private lxcfs cgroup mounts.");
6134 if (!permute_root())
6140 static void __attribute__((constructor
)) collect_and_mount_subsystems(void)
6143 char *cret
, *line
= NULL
;
6144 char cwd
[MAXPATHLEN
];
6146 int i
, init_ns
= -1;
6147 bool found_unified
= false;
6149 if ((f
= fopen("/proc/self/cgroup", "r")) == NULL
) {
6150 lxcfs_error("Error opening /proc/self/cgroup: %s\n", strerror(errno
));
6154 while (getline(&line
, &len
, f
) != -1) {
6157 p
= strchr(line
, ':');
6163 p2
= strrchr(p
, ':');
6168 /* With cgroupv2 /proc/self/cgroup can contain entries of the
6169 * form: 0::/ This will cause lxcfs to fail the cgroup mounts
6170 * because it parses out the empty string "" and later on passes
6171 * it to mount(). Let's skip such entries.
6173 if (!strcmp(p
, "") && !strcmp(idx
, "0") && !found_unified
) {
6174 found_unified
= true;
6178 if (!store_hierarchy(line
, p
))
6182 /* Preserve initial namespace. */
6183 init_ns
= preserve_mnt_ns(getpid());
6185 lxcfs_error("%s\n", "Failed to preserve initial mount namespace.");
6189 fd_hierarchies
= malloc(sizeof(int) * num_hierarchies
);
6190 if (!fd_hierarchies
) {
6191 lxcfs_error("%s\n", strerror(errno
));
6195 for (i
= 0; i
< num_hierarchies
; i
++)
6196 fd_hierarchies
[i
] = -1;
6198 cret
= getcwd(cwd
, MAXPATHLEN
);
6200 lxcfs_debug("Could not retrieve current working directory: %s.\n", strerror(errno
));
6202 /* This function calls unshare(CLONE_NEWNS) our initial mount namespace
6203 * to privately mount lxcfs cgroups. */
6204 if (!cgfs_setup_controllers()) {
6205 lxcfs_error("%s\n", "Failed to setup private cgroup mounts for lxcfs.");
6209 if (setns(init_ns
, 0) < 0) {
6210 lxcfs_error("Failed to switch back to initial mount namespace: %s.\n", strerror(errno
));
6214 if (!cret
|| chdir(cwd
) < 0)
6215 lxcfs_debug("Could not change back to original working directory: %s.\n", strerror(errno
));
6217 if (!init_cpuview()) {
6218 lxcfs_error("%s\n", "failed to init CPU view");
6231 static void __attribute__((destructor
)) free_subsystems(void)
6235 lxcfs_debug("%s\n", "Running destructor for liblxcfs.");
6237 for (i
= 0; i
< num_hierarchies
; i
++) {
6239 free(hierarchies
[i
]);
6240 if (fd_hierarchies
&& fd_hierarchies
[i
] >= 0)
6241 close(fd_hierarchies
[i
]);
6244 free(fd_hierarchies
);
6247 if (cgroup_mount_ns_fd
>= 0)
6248 close(cgroup_mount_ns_fd
);