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 struct cg_proc_stat
*next
;
299 struct cg_proc_stat_head
{
300 struct cg_proc_stat
*next
;
303 #define CPUVIEW_HASH_SIZE 100
304 static struct cg_proc_stat_head
*proc_stat_history
[CPUVIEW_HASH_SIZE
];
306 static bool cpuview_init_head(struct cg_proc_stat_head
**head
)
308 *head
= malloc(sizeof(struct cg_proc_stat_head
));
310 lxcfs_error("%s\n", strerror(errno
));
314 (*head
)->next
= NULL
;
318 static bool init_cpuview()
322 for (i
= 0; i
< CPUVIEW_HASH_SIZE
; i
++)
323 proc_stat_history
[i
] = NULL
;
325 for (i
= 0; i
< CPUVIEW_HASH_SIZE
; i
++) {
326 if (!cpuview_init_head(&proc_stat_history
[i
]))
333 for (i
= 0; i
< CPUVIEW_HASH_SIZE
; i
++) {
334 if (proc_stat_history
[i
]) {
335 free(proc_stat_history
[i
]);
336 proc_stat_history
[i
] = NULL
;
343 static void cpuview_free_head(struct cg_proc_stat_head
*head
)
345 struct cg_proc_stat
*node
, *tmp
;
367 static void free_cpuview()
371 for (i
= 0; i
< CPUVIEW_HASH_SIZE
; i
++) {
372 if (proc_stat_history
[i
])
373 cpuview_free_head(proc_stat_history
[i
]);
377 /* Reserve buffer size to account for file size changes. */
378 #define BUF_RESERVE_SIZE 512
381 * A table caching which pid is init for a pid namespace.
382 * When looking up which pid is init for $qpid, we first
383 * 1. Stat /proc/$qpid/ns/pid.
384 * 2. Check whether the ino_t is in our store.
385 * a. if not, fork a child in qpid's ns to send us
386 * ucred.pid = 1, and read the initpid. Cache
387 * initpid and creation time for /proc/initpid
388 * in a new store entry.
389 * b. if so, verify that /proc/initpid still matches
390 * what we have saved. If not, clear the store
391 * entry and go back to a. If so, return the
394 struct pidns_init_store
{
395 ino_t ino
; // inode number for /proc/$pid/ns/pid
396 pid_t initpid
; // the pid of nit in that ns
397 long int ctime
; // the time at which /proc/$initpid was created
398 struct pidns_init_store
*next
;
402 /* lol - look at how they are allocated in the kernel */
403 #define PIDNS_HASH_SIZE 4096
404 #define HASH(x) ((x) % PIDNS_HASH_SIZE)
406 static struct pidns_init_store
*pidns_hash_table
[PIDNS_HASH_SIZE
];
407 static pthread_mutex_t pidns_store_mutex
= PTHREAD_MUTEX_INITIALIZER
;
408 static void lock_mutex(pthread_mutex_t
*l
)
412 if ((ret
= pthread_mutex_lock(l
)) != 0) {
413 lxcfs_error("returned:%d %s\n", ret
, strerror(ret
));
418 /* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
419 * Number of hierarchies mounted. */
420 static int num_hierarchies
;
422 /* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
423 * Hierachies mounted {cpuset, blkio, ...}:
424 * Initialized via __constructor__ collect_and_mount_subsystems(). */
425 static char **hierarchies
;
427 /* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
428 * Open file descriptors:
429 * @fd_hierarchies[i] refers to cgroup @hierarchies[i]. They are mounted in a
430 * private mount namespace.
431 * Initialized via __constructor__ collect_and_mount_subsystems().
432 * @fd_hierarchies[i] can be used to perform file operations on the cgroup
433 * mounts and respective files in the private namespace even when located in
434 * another namespace using the *at() family of functions
435 * {openat(), fchownat(), ...}. */
436 static int *fd_hierarchies
;
437 static int cgroup_mount_ns_fd
= -1;
439 static void unlock_mutex(pthread_mutex_t
*l
)
443 if ((ret
= pthread_mutex_unlock(l
)) != 0) {
444 lxcfs_error("returned:%d %s\n", ret
, strerror(ret
));
449 static void store_lock(void)
451 lock_mutex(&pidns_store_mutex
);
454 static void store_unlock(void)
456 unlock_mutex(&pidns_store_mutex
);
459 /* Must be called under store_lock */
460 static bool initpid_still_valid(struct pidns_init_store
*e
, struct stat
*nsfdsb
)
465 snprintf(fnam
, 100, "/proc/%d", e
->initpid
);
466 if (stat(fnam
, &initsb
) < 0)
469 lxcfs_debug("Comparing ctime %ld == %ld for pid %d.\n", e
->ctime
,
470 initsb
.st_ctime
, e
->initpid
);
472 if (e
->ctime
!= initsb
.st_ctime
)
477 /* Must be called under store_lock */
478 static void remove_initpid(struct pidns_init_store
*e
)
480 struct pidns_init_store
*tmp
;
483 lxcfs_debug("Remove_initpid: removing entry for %d.\n", e
->initpid
);
486 if (pidns_hash_table
[h
] == e
) {
487 pidns_hash_table
[h
] = e
->next
;
492 tmp
= pidns_hash_table
[h
];
494 if (tmp
->next
== e
) {
504 /* Must be called under store_lock */
505 static void prune_initpid_store(void)
507 static long int last_prune
= 0;
508 struct pidns_init_store
*e
, *prev
, *delme
;
509 long int now
, threshold
;
513 last_prune
= time(NULL
);
517 if (now
< last_prune
+ PURGE_SECS
)
520 lxcfs_debug("%s\n", "Pruning.");
523 threshold
= now
- 2 * PURGE_SECS
;
525 for (i
= 0; i
< PIDNS_HASH_SIZE
; i
++) {
526 for (prev
= NULL
, e
= pidns_hash_table
[i
]; e
; ) {
527 if (e
->lastcheck
< threshold
) {
529 lxcfs_debug("Removing cached entry for %d.\n", e
->initpid
);
533 prev
->next
= e
->next
;
535 pidns_hash_table
[i
] = e
->next
;
546 /* Must be called under store_lock */
547 static void save_initpid(struct stat
*sb
, pid_t pid
)
549 struct pidns_init_store
*e
;
554 lxcfs_debug("Save_initpid: adding entry for %d.\n", pid
);
556 snprintf(fpath
, 100, "/proc/%d", pid
);
557 if (stat(fpath
, &procsb
) < 0)
560 e
= malloc(sizeof(*e
));
564 e
->ctime
= procsb
.st_ctime
;
566 e
->next
= pidns_hash_table
[h
];
567 e
->lastcheck
= time(NULL
);
568 pidns_hash_table
[h
] = e
;
572 * Given the stat(2) info for a nsfd pid inode, lookup the init_pid_store
573 * entry for the inode number and creation time. Verify that the init pid
574 * is still valid. If not, remove it. Return the entry if valid, NULL
576 * Must be called under store_lock
578 static struct pidns_init_store
*lookup_verify_initpid(struct stat
*sb
)
580 int h
= HASH(sb
->st_ino
);
581 struct pidns_init_store
*e
= pidns_hash_table
[h
];
584 if (e
->ino
== sb
->st_ino
) {
585 if (initpid_still_valid(e
, sb
)) {
586 e
->lastcheck
= time(NULL
);
598 static int is_dir(const char *path
, int fd
)
601 int ret
= fstatat(fd
, path
, &statbuf
, fd
);
602 if (ret
== 0 && S_ISDIR(statbuf
.st_mode
))
607 static char *must_copy_string(const char *str
)
619 static inline void drop_trailing_newlines(char *s
)
623 for (l
=strlen(s
); l
>0 && s
[l
-1] == '\n'; l
--)
627 #define BATCH_SIZE 50
628 static void dorealloc(char **mem
, size_t oldlen
, size_t newlen
)
630 int newbatches
= (newlen
/ BATCH_SIZE
) + 1;
631 int oldbatches
= (oldlen
/ BATCH_SIZE
) + 1;
633 if (!*mem
|| newbatches
> oldbatches
) {
636 tmp
= realloc(*mem
, newbatches
* BATCH_SIZE
);
641 static void append_line(char **contents
, size_t *len
, char *line
, ssize_t linelen
)
643 size_t newlen
= *len
+ linelen
;
644 dorealloc(contents
, *len
, newlen
+ 1);
645 memcpy(*contents
+ *len
, line
, linelen
+1);
649 static char *slurp_file(const char *from
, int fd
)
652 char *contents
= NULL
;
653 FILE *f
= fdopen(fd
, "r");
654 size_t len
= 0, fulllen
= 0;
660 while ((linelen
= getline(&line
, &len
, f
)) != -1) {
661 append_line(&contents
, &fulllen
, line
, linelen
);
666 drop_trailing_newlines(contents
);
671 static bool write_string(const char *fnam
, const char *string
, int fd
)
680 len
= strlen(string
);
681 ret
= fwrite(string
, 1, len
, f
);
683 lxcfs_error("%s - Error writing \"%s\" to \"%s\"\n",
684 strerror(errno
), string
, fnam
);
690 lxcfs_error("%s - Failed to close \"%s\"\n", strerror(errno
), fnam
);
704 static bool store_hierarchy(char *stridx
, char *h
)
706 if (num_hierarchies
% ALLOC_NUM
== 0) {
707 size_t n
= (num_hierarchies
/ ALLOC_NUM
) + 1;
709 char **tmp
= realloc(hierarchies
, n
* sizeof(char *));
711 lxcfs_error("%s\n", strerror(errno
));
717 hierarchies
[num_hierarchies
++] = must_copy_string(h
);
721 static void print_subsystems(void)
725 fprintf(stderr
, "mount namespace: %d\n", cgroup_mount_ns_fd
);
726 fprintf(stderr
, "hierarchies:\n");
727 for (i
= 0; i
< num_hierarchies
; i
++) {
729 fprintf(stderr
, " %2d: fd: %3d: %s\n", i
,
730 fd_hierarchies
[i
], hierarchies
[i
]);
734 static bool in_comma_list(const char *needle
, const char *haystack
)
736 const char *s
= haystack
, *e
;
737 size_t nlen
= strlen(needle
);
739 while (*s
&& (e
= strchr(s
, ','))) {
744 if (strncmp(needle
, s
, nlen
) == 0)
748 if (strcmp(needle
, s
) == 0)
753 /* do we need to do any massaging here? I'm not sure... */
754 /* Return the mounted controller and store the corresponding open file descriptor
755 * referring to the controller mountpoint in the private lxcfs namespace in
758 static char *find_mounted_controller(const char *controller
, int *cfd
)
762 for (i
= 0; i
< num_hierarchies
; i
++) {
765 if (strcmp(hierarchies
[i
], controller
) == 0) {
766 *cfd
= fd_hierarchies
[i
];
767 return hierarchies
[i
];
769 if (in_comma_list(controller
, hierarchies
[i
])) {
770 *cfd
= fd_hierarchies
[i
];
771 return hierarchies
[i
];
778 bool cgfs_set_value(const char *controller
, const char *cgroup
, const char *file
,
785 tmpc
= find_mounted_controller(controller
, &cfd
);
789 /* Make sure we pass a relative path to *at() family of functions.
790 * . + /cgroup + / + file + \0
792 len
= strlen(cgroup
) + strlen(file
) + 3;
794 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, file
);
795 if (ret
< 0 || (size_t)ret
>= len
)
798 fd
= openat(cfd
, fnam
, O_WRONLY
);
802 return write_string(fnam
, value
, fd
);
805 // Chown all the files in the cgroup directory. We do this when we create
806 // a cgroup on behalf of a user.
807 static void chown_all_cgroup_files(const char *dirname
, uid_t uid
, gid_t gid
, int fd
)
809 struct dirent
*direntp
;
810 char path
[MAXPATHLEN
];
815 len
= strlen(dirname
);
816 if (len
>= MAXPATHLEN
) {
817 lxcfs_error("Pathname too long: %s\n", dirname
);
821 fd1
= openat(fd
, dirname
, O_DIRECTORY
);
827 lxcfs_error("Failed to open %s\n", dirname
);
831 while ((direntp
= readdir(d
))) {
832 if (!strcmp(direntp
->d_name
, ".") || !strcmp(direntp
->d_name
, ".."))
834 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
835 if (ret
< 0 || ret
>= MAXPATHLEN
) {
836 lxcfs_error("Pathname too long under %s\n", dirname
);
839 if (fchownat(fd
, path
, uid
, gid
, 0) < 0)
840 lxcfs_error("Failed to chown file %s to %u:%u", path
, uid
, gid
);
845 int cgfs_create(const char *controller
, const char *cg
, uid_t uid
, gid_t gid
)
851 tmpc
= find_mounted_controller(controller
, &cfd
);
855 /* Make sure we pass a relative path to *at() family of functions.
858 len
= strlen(cg
) + 2;
859 dirnam
= alloca(len
);
860 snprintf(dirnam
, len
, "%s%s", *cg
== '/' ? "." : "", cg
);
862 if (mkdirat(cfd
, dirnam
, 0755) < 0)
865 if (uid
== 0 && gid
== 0)
868 if (fchownat(cfd
, dirnam
, uid
, gid
, 0) < 0)
871 chown_all_cgroup_files(dirnam
, uid
, gid
, cfd
);
876 static bool recursive_rmdir(const char *dirname
, int fd
, const int cfd
)
878 struct dirent
*direntp
;
881 char pathname
[MAXPATHLEN
];
884 dupfd
= dup(fd
); // fdopendir() does bad things once it uses an fd.
888 dir
= fdopendir(dupfd
);
890 lxcfs_debug("Failed to open %s: %s.\n", dirname
, strerror(errno
));
895 while ((direntp
= readdir(dir
))) {
899 if (!strcmp(direntp
->d_name
, ".") ||
900 !strcmp(direntp
->d_name
, ".."))
903 rc
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
904 if (rc
< 0 || rc
>= MAXPATHLEN
) {
905 lxcfs_error("%s\n", "Pathname too long.");
909 rc
= fstatat(cfd
, pathname
, &mystat
, AT_SYMLINK_NOFOLLOW
);
911 lxcfs_debug("Failed to stat %s: %s.\n", pathname
, strerror(errno
));
914 if (S_ISDIR(mystat
.st_mode
))
915 if (!recursive_rmdir(pathname
, fd
, cfd
))
916 lxcfs_debug("Error removing %s.\n", pathname
);
920 if (closedir(dir
) < 0) {
921 lxcfs_error("Failed to close directory %s: %s\n", dirname
, strerror(errno
));
925 if (unlinkat(cfd
, dirname
, AT_REMOVEDIR
) < 0) {
926 lxcfs_debug("Failed to delete %s: %s.\n", dirname
, strerror(errno
));
935 bool cgfs_remove(const char *controller
, const char *cg
)
942 tmpc
= find_mounted_controller(controller
, &cfd
);
946 /* Make sure we pass a relative path to *at() family of functions.
949 len
= strlen(cg
) + 2;
950 dirnam
= alloca(len
);
951 snprintf(dirnam
, len
, "%s%s", *cg
== '/' ? "." : "", cg
);
953 fd
= openat(cfd
, dirnam
, O_DIRECTORY
);
957 bret
= recursive_rmdir(dirnam
, fd
, cfd
);
962 bool cgfs_chmod_file(const char *controller
, const char *file
, mode_t mode
)
966 char *pathname
, *tmpc
;
968 tmpc
= find_mounted_controller(controller
, &cfd
);
972 /* Make sure we pass a relative path to *at() family of functions.
975 len
= strlen(file
) + 2;
976 pathname
= alloca(len
);
977 snprintf(pathname
, len
, "%s%s", *file
== '/' ? "." : "", file
);
978 if (fchmodat(cfd
, pathname
, mode
, 0) < 0)
983 static int chown_tasks_files(const char *dirname
, uid_t uid
, gid_t gid
, int fd
)
988 len
= strlen(dirname
) + strlen("/cgroup.procs") + 1;
990 snprintf(fname
, len
, "%s/tasks", dirname
);
991 if (fchownat(fd
, fname
, uid
, gid
, 0) != 0)
993 snprintf(fname
, len
, "%s/cgroup.procs", dirname
);
994 if (fchownat(fd
, fname
, uid
, gid
, 0) != 0)
999 int cgfs_chown_file(const char *controller
, const char *file
, uid_t uid
, gid_t gid
)
1003 char *pathname
, *tmpc
;
1005 tmpc
= find_mounted_controller(controller
, &cfd
);
1009 /* Make sure we pass a relative path to *at() family of functions.
1012 len
= strlen(file
) + 2;
1013 pathname
= alloca(len
);
1014 snprintf(pathname
, len
, "%s%s", *file
== '/' ? "." : "", file
);
1015 if (fchownat(cfd
, pathname
, uid
, gid
, 0) < 0)
1018 if (is_dir(pathname
, cfd
))
1019 // like cgmanager did, we want to chown the tasks file as well
1020 return chown_tasks_files(pathname
, uid
, gid
, cfd
);
1025 FILE *open_pids_file(const char *controller
, const char *cgroup
)
1029 char *pathname
, *tmpc
;
1031 tmpc
= find_mounted_controller(controller
, &cfd
);
1035 /* Make sure we pass a relative path to *at() family of functions.
1036 * . + /cgroup + / "cgroup.procs" + \0
1038 len
= strlen(cgroup
) + strlen("cgroup.procs") + 3;
1039 pathname
= alloca(len
);
1040 snprintf(pathname
, len
, "%s%s/cgroup.procs", *cgroup
== '/' ? "." : "", cgroup
);
1042 fd
= openat(cfd
, pathname
, O_WRONLY
);
1046 return fdopen(fd
, "w");
1049 static bool cgfs_iterate_cgroup(const char *controller
, const char *cgroup
, bool directories
,
1050 void ***list
, size_t typesize
,
1051 void* (*iterator
)(const char*, const char*, const char*))
1056 char pathname
[MAXPATHLEN
];
1057 size_t sz
= 0, asz
= 0;
1058 struct dirent
*dirent
;
1061 tmpc
= find_mounted_controller(controller
, &cfd
);
1066 /* Make sure we pass a relative path to *at() family of functions. */
1067 len
= strlen(cgroup
) + 1 /* . */ + 1 /* \0 */;
1069 ret
= snprintf(cg
, len
, "%s%s", *cgroup
== '/' ? "." : "", cgroup
);
1070 if (ret
< 0 || (size_t)ret
>= len
) {
1071 lxcfs_error("Pathname too long under %s\n", cgroup
);
1075 fd
= openat(cfd
, cg
, O_DIRECTORY
);
1079 dir
= fdopendir(fd
);
1083 while ((dirent
= readdir(dir
))) {
1086 if (!strcmp(dirent
->d_name
, ".") ||
1087 !strcmp(dirent
->d_name
, ".."))
1090 ret
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", cg
, dirent
->d_name
);
1091 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1092 lxcfs_error("Pathname too long under %s\n", cg
);
1096 ret
= fstatat(cfd
, pathname
, &mystat
, AT_SYMLINK_NOFOLLOW
);
1098 lxcfs_error("Failed to stat %s: %s\n", pathname
, strerror(errno
));
1101 if ((!directories
&& !S_ISREG(mystat
.st_mode
)) ||
1102 (directories
&& !S_ISDIR(mystat
.st_mode
)))
1109 tmp
= realloc(*list
, asz
* typesize
);
1113 (*list
)[sz
] = (*iterator
)(controller
, cg
, dirent
->d_name
);
1114 (*list
)[sz
+1] = NULL
;
1117 if (closedir(dir
) < 0) {
1118 lxcfs_error("Failed closedir for %s: %s\n", cgroup
, strerror(errno
));
1124 static void *make_children_list_entry(const char *controller
, const char *cgroup
, const char *dir_entry
)
1128 dup
= strdup(dir_entry
);
1133 bool cgfs_list_children(const char *controller
, const char *cgroup
, char ***list
)
1135 return cgfs_iterate_cgroup(controller
, cgroup
, true, (void***)list
, sizeof(*list
), &make_children_list_entry
);
1138 void free_key(struct cgfs_files
*k
)
1146 void free_keys(struct cgfs_files
**keys
)
1152 for (i
= 0; keys
[i
]; i
++) {
1158 bool cgfs_get_value(const char *controller
, const char *cgroup
, const char *file
, char **value
)
1164 tmpc
= find_mounted_controller(controller
, &cfd
);
1168 /* Make sure we pass a relative path to *at() family of functions.
1169 * . + /cgroup + / + file + \0
1171 len
= strlen(cgroup
) + strlen(file
) + 3;
1173 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, file
);
1174 if (ret
< 0 || (size_t)ret
>= len
)
1177 fd
= openat(cfd
, fnam
, O_RDONLY
);
1181 *value
= slurp_file(fnam
, fd
);
1182 return *value
!= NULL
;
1185 struct cgfs_files
*cgfs_get_key(const char *controller
, const char *cgroup
, const char *file
)
1191 struct cgfs_files
*newkey
;
1193 tmpc
= find_mounted_controller(controller
, &cfd
);
1197 if (file
&& *file
== '/')
1200 if (file
&& strchr(file
, '/'))
1203 /* Make sure we pass a relative path to *at() family of functions.
1204 * . + /cgroup + / + file + \0
1206 len
= strlen(cgroup
) + 3;
1208 len
+= strlen(file
) + 1;
1210 snprintf(fnam
, len
, "%s%s%s%s", *cgroup
== '/' ? "." : "", cgroup
,
1211 file
? "/" : "", file
? file
: "");
1213 ret
= fstatat(cfd
, fnam
, &sb
, 0);
1218 newkey
= malloc(sizeof(struct cgfs_files
));
1221 newkey
->name
= must_copy_string(file
);
1222 else if (strrchr(cgroup
, '/'))
1223 newkey
->name
= must_copy_string(strrchr(cgroup
, '/'));
1225 newkey
->name
= must_copy_string(cgroup
);
1226 newkey
->uid
= sb
.st_uid
;
1227 newkey
->gid
= sb
.st_gid
;
1228 newkey
->mode
= sb
.st_mode
;
1233 static void *make_key_list_entry(const char *controller
, const char *cgroup
, const char *dir_entry
)
1235 struct cgfs_files
*entry
= cgfs_get_key(controller
, cgroup
, dir_entry
);
1237 lxcfs_error("Error getting files under %s:%s\n", controller
,
1243 bool cgfs_list_keys(const char *controller
, const char *cgroup
, struct cgfs_files
***keys
)
1245 return cgfs_iterate_cgroup(controller
, cgroup
, false, (void***)keys
, sizeof(*keys
), &make_key_list_entry
);
1248 bool is_child_cgroup(const char *controller
, const char *cgroup
, const char *f
)
1256 tmpc
= find_mounted_controller(controller
, &cfd
);
1260 /* Make sure we pass a relative path to *at() family of functions.
1261 * . + /cgroup + / + f + \0
1263 len
= strlen(cgroup
) + strlen(f
) + 3;
1265 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, f
);
1266 if (ret
< 0 || (size_t)ret
>= len
)
1269 ret
= fstatat(cfd
, fnam
, &sb
, 0);
1270 if (ret
< 0 || !S_ISDIR(sb
.st_mode
))
1276 #define SEND_CREDS_OK 0
1277 #define SEND_CREDS_NOTSK 1
1278 #define SEND_CREDS_FAIL 2
1279 static bool recv_creds(int sock
, struct ucred
*cred
, char *v
);
1280 static int wait_for_pid(pid_t pid
);
1281 static int send_creds(int sock
, struct ucred
*cred
, char v
, bool pingfirst
);
1282 static int send_creds_clone_wrapper(void *arg
);
1285 * clone a task which switches to @task's namespace and writes '1'.
1286 * over a unix sock so we can read the task's reaper's pid in our
1289 * Note: glibc's fork() does not respect pidns, which can lead to failed
1290 * assertions inside glibc (and thus failed forks) if the child's pid in
1291 * the pidns and the parent pid outside are identical. Using clone prevents
1294 static void write_task_init_pid_exit(int sock
, pid_t target
)
1299 size_t stack_size
= sysconf(_SC_PAGESIZE
);
1300 void *stack
= alloca(stack_size
);
1302 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", (int)target
);
1303 if (ret
< 0 || ret
>= sizeof(fnam
))
1306 fd
= open(fnam
, O_RDONLY
);
1308 perror("write_task_init_pid_exit open of ns/pid");
1312 perror("write_task_init_pid_exit setns 1");
1316 pid
= clone(send_creds_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &sock
);
1320 if (!wait_for_pid(pid
))
1326 static int send_creds_clone_wrapper(void *arg
) {
1329 int sock
= *(int *)arg
;
1331 /* we are the child */
1336 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
)
1341 static pid_t
get_init_pid_for_task(pid_t task
)
1349 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
1350 perror("socketpair");
1359 write_task_init_pid_exit(sock
[0], task
);
1363 if (!recv_creds(sock
[1], &cred
, &v
))
1375 static pid_t
lookup_initpid_in_store(pid_t qpid
)
1379 struct pidns_init_store
*e
;
1382 snprintf(fnam
, 100, "/proc/%d/ns/pid", qpid
);
1384 if (stat(fnam
, &sb
) < 0)
1386 e
= lookup_verify_initpid(&sb
);
1388 answer
= e
->initpid
;
1391 answer
= get_init_pid_for_task(qpid
);
1393 save_initpid(&sb
, answer
);
1396 /* we prune at end in case we are returning
1397 * the value we were about to return */
1398 prune_initpid_store();
1403 static int wait_for_pid(pid_t pid
)
1411 ret
= waitpid(pid
, &status
, 0);
1419 if (!WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
1426 * append pid to *src.
1427 * src: a pointer to a char* in which ot append the pid.
1428 * sz: the number of characters printed so far, minus trailing \0.
1429 * asz: the allocated size so far
1430 * pid: the pid to append
1432 static void must_strcat_pid(char **src
, size_t *sz
, size_t *asz
, pid_t pid
)
1436 int tmplen
= sprintf(tmp
, "%d\n", (int)pid
);
1438 if (!*src
|| tmplen
+ *sz
+ 1 >= *asz
) {
1441 tmp
= realloc(*src
, *asz
+ BUF_RESERVE_SIZE
);
1444 *asz
+= BUF_RESERVE_SIZE
;
1446 memcpy((*src
) +*sz
, tmp
, tmplen
+1); /* include the \0 */
1451 * Given a open file * to /proc/pid/{u,g}id_map, and an id
1452 * valid in the caller's namespace, return the id mapped into
1454 * Returns the mapped id, or -1 on error.
1457 convert_id_to_ns(FILE *idfile
, unsigned int in_id
)
1459 unsigned int nsuid
, // base id for a range in the idfile's namespace
1460 hostuid
, // base id for a range in the caller's namespace
1461 count
; // number of ids in this range
1465 fseek(idfile
, 0L, SEEK_SET
);
1466 while (fgets(line
, 400, idfile
)) {
1467 ret
= sscanf(line
, "%u %u %u\n", &nsuid
, &hostuid
, &count
);
1470 if (hostuid
+ count
< hostuid
|| nsuid
+ count
< nsuid
) {
1472 * uids wrapped around - unexpected as this is a procfile,
1475 lxcfs_error("pid wrapparound at entry %u %u %u in %s\n",
1476 nsuid
, hostuid
, count
, line
);
1479 if (hostuid
<= in_id
&& hostuid
+count
> in_id
) {
1481 * now since hostuid <= in_id < hostuid+count, and
1482 * hostuid+count and nsuid+count do not wrap around,
1483 * we know that nsuid+(in_id-hostuid) which must be
1484 * less that nsuid+(count) must not wrap around
1486 return (in_id
- hostuid
) + nsuid
;
1495 * for is_privileged_over,
1496 * specify whether we require the calling uid to be root in his
1499 #define NS_ROOT_REQD true
1500 #define NS_ROOT_OPT false
1504 static bool is_privileged_over(pid_t pid
, uid_t uid
, uid_t victim
, bool req_ns_root
)
1506 char fpath
[PROCLEN
];
1508 bool answer
= false;
1511 if (victim
== -1 || uid
== -1)
1515 * If the request is one not requiring root in the namespace,
1516 * then having the same uid suffices. (i.e. uid 1000 has write
1517 * access to files owned by uid 1000
1519 if (!req_ns_root
&& uid
== victim
)
1522 ret
= snprintf(fpath
, PROCLEN
, "/proc/%d/uid_map", pid
);
1523 if (ret
< 0 || ret
>= PROCLEN
)
1525 FILE *f
= fopen(fpath
, "r");
1529 /* if caller's not root in his namespace, reject */
1530 nsuid
= convert_id_to_ns(f
, uid
);
1535 * If victim is not mapped into caller's ns, reject.
1536 * XXX I'm not sure this check is needed given that fuse
1537 * will be sending requests where the vfs has converted
1539 nsuid
= convert_id_to_ns(f
, victim
);
1550 static bool perms_include(int fmode
, mode_t req_mode
)
1554 switch (req_mode
& O_ACCMODE
) {
1562 r
= S_IROTH
| S_IWOTH
;
1567 return ((fmode
& r
) == r
);
1573 * querycg is /a/b/c/d/e
1576 static char *get_next_cgroup_dir(const char *taskcg
, const char *querycg
)
1580 if (strlen(taskcg
) <= strlen(querycg
)) {
1581 lxcfs_error("%s\n", "I was fed bad input.");
1585 if ((strcmp(querycg
, "/") == 0) || (strcmp(querycg
, "./") == 0))
1586 start
= strdup(taskcg
+ 1);
1588 start
= strdup(taskcg
+ strlen(querycg
) + 1);
1591 end
= strchr(start
, '/');
1597 static void stripnewline(char *x
)
1599 size_t l
= strlen(x
);
1600 if (l
&& x
[l
-1] == '\n')
1604 static char *get_pid_cgroup(pid_t pid
, const char *contrl
)
1609 char *answer
= NULL
;
1613 const char *h
= find_mounted_controller(contrl
, &cfd
);
1617 ret
= snprintf(fnam
, PROCLEN
, "/proc/%d/cgroup", pid
);
1618 if (ret
< 0 || ret
>= PROCLEN
)
1620 if (!(f
= fopen(fnam
, "r")))
1623 while (getline(&line
, &len
, f
) != -1) {
1627 c1
= strchr(line
, ':');
1631 c2
= strchr(c1
, ':');
1635 if (strcmp(c1
, h
) != 0)
1640 answer
= strdup(c2
);
1652 * check whether a fuse context may access a cgroup dir or file
1654 * If file is not null, it is a cgroup file to check under cg.
1655 * If file is null, then we are checking perms on cg itself.
1657 * For files we can check the mode of the list_keys result.
1658 * For cgroups, we must make assumptions based on the files under the
1659 * cgroup, because cgmanager doesn't tell us ownership/perms of cgroups
1662 static bool fc_may_access(struct fuse_context
*fc
, const char *contrl
, const char *cg
, const char *file
, mode_t mode
)
1664 struct cgfs_files
*k
= NULL
;
1667 k
= cgfs_get_key(contrl
, cg
, file
);
1671 if (is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
1672 if (perms_include(k
->mode
>> 6, mode
)) {
1677 if (fc
->gid
== k
->gid
) {
1678 if (perms_include(k
->mode
>> 3, mode
)) {
1683 ret
= perms_include(k
->mode
, mode
);
1690 #define INITSCOPE "/init.scope"
1691 static void prune_init_slice(char *cg
)
1694 size_t cg_len
= strlen(cg
), initscope_len
= strlen(INITSCOPE
);
1696 if (cg_len
< initscope_len
)
1699 point
= cg
+ cg_len
- initscope_len
;
1700 if (strcmp(point
, INITSCOPE
) == 0) {
1709 * If pid is in /a/b/c/d, he may only act on things under cg=/a/b/c/d.
1710 * If pid is in /a, he may act on /a/b, but not on /b.
1711 * if the answer is false and nextcg is not NULL, then *nextcg will point
1712 * to a string containing the next cgroup directory under cg, which must be
1713 * freed by the caller.
1715 static bool caller_is_in_ancestor(pid_t pid
, const char *contrl
, const char *cg
, char **nextcg
)
1717 bool answer
= false;
1718 char *c2
= get_pid_cgroup(pid
, contrl
);
1723 prune_init_slice(c2
);
1726 * callers pass in '/' or './' (openat()) for root cgroup, otherwise
1727 * they pass in a cgroup without leading '/'
1729 * The original line here was:
1730 * linecmp = *cg == '/' ? c2 : c2+1;
1731 * TODO: I'm not sure why you'd want to increment when *cg != '/'?
1732 * Serge, do you know?
1734 if (*cg
== '/' || !strncmp(cg
, "./", 2))
1738 if (strncmp(linecmp
, cg
, strlen(linecmp
)) != 0) {
1740 *nextcg
= get_next_cgroup_dir(linecmp
, cg
);
1752 * If pid is in /a/b/c, he may see that /a exists, but not /b or /a/c.
1754 static bool caller_may_see_dir(pid_t pid
, const char *contrl
, const char *cg
)
1756 bool answer
= false;
1758 size_t target_len
, task_len
;
1760 if (strcmp(cg
, "/") == 0 || strcmp(cg
, "./") == 0)
1763 c2
= get_pid_cgroup(pid
, contrl
);
1766 prune_init_slice(c2
);
1769 target_len
= strlen(cg
);
1770 task_len
= strlen(task_cg
);
1771 if (task_len
== 0) {
1772 /* Task is in the root cg, it can see everything. This case is
1773 * not handled by the strmcps below, since they test for the
1774 * last /, but that is the first / that we've chopped off
1780 if (strcmp(cg
, task_cg
) == 0) {
1784 if (target_len
< task_len
) {
1785 /* looking up a parent dir */
1786 if (strncmp(task_cg
, cg
, target_len
) == 0 && task_cg
[target_len
] == '/')
1790 if (target_len
> task_len
) {
1791 /* looking up a child dir */
1792 if (strncmp(task_cg
, cg
, task_len
) == 0 && cg
[task_len
] == '/')
1803 * given /cgroup/freezer/a/b, return "freezer".
1804 * the returned char* should NOT be freed.
1806 static char *pick_controller_from_path(struct fuse_context
*fc
, const char *path
)
1809 char *contr
, *slash
;
1811 if (strlen(path
) < 9) {
1815 if (*(path
+ 7) != '/') {
1820 contr
= strdupa(p1
);
1825 slash
= strstr(contr
, "/");
1830 for (i
= 0; i
< num_hierarchies
; i
++) {
1831 if (hierarchies
[i
] && strcmp(hierarchies
[i
], contr
) == 0)
1832 return hierarchies
[i
];
1839 * Find the start of cgroup in /cgroup/controller/the/cgroup/path
1840 * Note that the returned value may include files (keynames) etc
1842 static const char *find_cgroup_in_path(const char *path
)
1846 if (strlen(path
) < 9) {
1850 p1
= strstr(path
+ 8, "/");
1860 * split the last path element from the path in @cg.
1861 * @dir is newly allocated and should be freed, @last not
1863 static void get_cgdir_and_path(const char *cg
, char **dir
, char **last
)
1870 *last
= strrchr(cg
, '/');
1875 p
= strrchr(*dir
, '/');
1880 * FUSE ops for /cgroup
1883 int cg_getattr(const char *path
, struct stat
*sb
)
1885 struct timespec now
;
1886 struct fuse_context
*fc
= fuse_get_context();
1887 char * cgdir
= NULL
;
1888 char *last
= NULL
, *path1
, *path2
;
1889 struct cgfs_files
*k
= NULL
;
1891 const char *controller
= NULL
;
1898 memset(sb
, 0, sizeof(struct stat
));
1900 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
1903 sb
->st_uid
= sb
->st_gid
= 0;
1904 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
1907 if (strcmp(path
, "/cgroup") == 0) {
1908 sb
->st_mode
= S_IFDIR
| 00755;
1913 controller
= pick_controller_from_path(fc
, path
);
1916 cgroup
= find_cgroup_in_path(path
);
1918 /* this is just /cgroup/controller, return it as a dir */
1919 sb
->st_mode
= S_IFDIR
| 00755;
1924 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
1934 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1937 /* check that cgcopy is either a child cgroup of cgdir, or listed in its keys.
1938 * Then check that caller's cgroup is under path if last is a child
1939 * cgroup, or cgdir if last is a file */
1941 if (is_child_cgroup(controller
, path1
, path2
)) {
1942 if (!caller_may_see_dir(initpid
, controller
, cgroup
)) {
1946 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, NULL
)) {
1947 /* this is just /cgroup/controller, return it as a dir */
1948 sb
->st_mode
= S_IFDIR
| 00555;
1953 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
)) {
1958 // get uid, gid, from '/tasks' file and make up a mode
1959 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
1960 sb
->st_mode
= S_IFDIR
| 00755;
1961 k
= cgfs_get_key(controller
, cgroup
, NULL
);
1963 sb
->st_uid
= sb
->st_gid
= 0;
1965 sb
->st_uid
= k
->uid
;
1966 sb
->st_gid
= k
->gid
;
1974 if ((k
= cgfs_get_key(controller
, path1
, path2
)) != NULL
) {
1975 sb
->st_mode
= S_IFREG
| k
->mode
;
1977 sb
->st_uid
= k
->uid
;
1978 sb
->st_gid
= k
->gid
;
1981 if (!caller_is_in_ancestor(initpid
, controller
, path1
, NULL
)) {
1993 int cg_opendir(const char *path
, struct fuse_file_info
*fi
)
1995 struct fuse_context
*fc
= fuse_get_context();
1997 struct file_info
*dir_info
;
1998 char *controller
= NULL
;
2003 if (strcmp(path
, "/cgroup") == 0) {
2007 // return list of keys for the controller, and list of child cgroups
2008 controller
= pick_controller_from_path(fc
, path
);
2012 cgroup
= find_cgroup_in_path(path
);
2014 /* this is just /cgroup/controller, return its contents */
2019 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2023 if (!caller_may_see_dir(initpid
, controller
, cgroup
))
2025 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
))
2029 /* we'll free this at cg_releasedir */
2030 dir_info
= malloc(sizeof(*dir_info
));
2033 dir_info
->controller
= must_copy_string(controller
);
2034 dir_info
->cgroup
= must_copy_string(cgroup
);
2035 dir_info
->type
= LXC_TYPE_CGDIR
;
2036 dir_info
->buf
= NULL
;
2037 dir_info
->file
= NULL
;
2038 dir_info
->buflen
= 0;
2040 fi
->fh
= (unsigned long)dir_info
;
2044 int cg_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
2045 struct fuse_file_info
*fi
)
2047 struct file_info
*d
= (struct file_info
*)fi
->fh
;
2048 struct cgfs_files
**list
= NULL
;
2050 char *nextcg
= NULL
;
2051 struct fuse_context
*fc
= fuse_get_context();
2052 char **clist
= NULL
;
2054 if (filler(buf
, ".", NULL
, 0) != 0 || filler(buf
, "..", NULL
, 0) != 0)
2057 if (d
->type
!= LXC_TYPE_CGDIR
) {
2058 lxcfs_error("%s\n", "Internal error: file cache info used in readdir.");
2061 if (!d
->cgroup
&& !d
->controller
) {
2062 // ls /var/lib/lxcfs/cgroup - just show list of controllers
2065 for (i
= 0; i
< num_hierarchies
; i
++) {
2066 if (hierarchies
[i
] && filler(buf
, hierarchies
[i
], NULL
, 0) != 0) {
2073 if (!cgfs_list_keys(d
->controller
, d
->cgroup
, &list
)) {
2074 // not a valid cgroup
2079 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2082 if (!caller_is_in_ancestor(initpid
, d
->controller
, d
->cgroup
, &nextcg
)) {
2084 ret
= filler(buf
, nextcg
, NULL
, 0);
2095 for (i
= 0; list
[i
]; i
++) {
2096 if (filler(buf
, list
[i
]->name
, NULL
, 0) != 0) {
2102 // now get the list of child cgroups
2104 if (!cgfs_list_children(d
->controller
, d
->cgroup
, &clist
)) {
2109 for (i
= 0; clist
[i
]; i
++) {
2110 if (filler(buf
, clist
[i
], NULL
, 0) != 0) {
2121 for (i
= 0; clist
[i
]; i
++)
2128 static void do_release_file_info(struct fuse_file_info
*fi
)
2130 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2137 free(f
->controller
);
2138 f
->controller
= NULL
;
2149 int cg_releasedir(const char *path
, struct fuse_file_info
*fi
)
2151 do_release_file_info(fi
);
2155 int cg_open(const char *path
, struct fuse_file_info
*fi
)
2158 char *last
= NULL
, *path1
, *path2
, * cgdir
= NULL
, *controller
;
2159 struct cgfs_files
*k
= NULL
;
2160 struct file_info
*file_info
;
2161 struct fuse_context
*fc
= fuse_get_context();
2167 controller
= pick_controller_from_path(fc
, path
);
2170 cgroup
= find_cgroup_in_path(path
);
2174 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2183 k
= cgfs_get_key(controller
, path1
, path2
);
2190 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2193 if (!caller_may_see_dir(initpid
, controller
, path1
)) {
2197 if (!fc_may_access(fc
, controller
, path1
, path2
, fi
->flags
)) {
2202 /* we'll free this at cg_release */
2203 file_info
= malloc(sizeof(*file_info
));
2208 file_info
->controller
= must_copy_string(controller
);
2209 file_info
->cgroup
= must_copy_string(path1
);
2210 file_info
->file
= must_copy_string(path2
);
2211 file_info
->type
= LXC_TYPE_CGFILE
;
2212 file_info
->buf
= NULL
;
2213 file_info
->buflen
= 0;
2215 fi
->fh
= (unsigned long)file_info
;
2223 int cg_access(const char *path
, int mode
)
2227 char *path1
, *path2
, *controller
;
2228 char *last
= NULL
, *cgdir
= NULL
;
2229 struct cgfs_files
*k
= NULL
;
2230 struct fuse_context
*fc
= fuse_get_context();
2232 if (strcmp(path
, "/cgroup") == 0)
2238 controller
= pick_controller_from_path(fc
, path
);
2241 cgroup
= find_cgroup_in_path(path
);
2243 // access("/sys/fs/cgroup/systemd", mode) - rx allowed, w not
2244 if ((mode
& W_OK
) == 0)
2249 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2258 k
= cgfs_get_key(controller
, path1
, path2
);
2260 if ((mode
& W_OK
) == 0)
2268 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2271 if (!caller_may_see_dir(initpid
, controller
, path1
)) {
2275 if (!fc_may_access(fc
, controller
, path1
, path2
, mode
)) {
2287 int cg_release(const char *path
, struct fuse_file_info
*fi
)
2289 do_release_file_info(fi
);
2293 #define POLLIN_SET ( EPOLLIN | EPOLLHUP | EPOLLRDHUP )
2295 static bool wait_for_sock(int sock
, int timeout
)
2297 struct epoll_event ev
;
2298 int epfd
, ret
, now
, starttime
, deltatime
, saved_errno
;
2300 if ((starttime
= time(NULL
)) < 0)
2303 if ((epfd
= epoll_create(1)) < 0) {
2304 lxcfs_error("%s\n", "Failed to create epoll socket: %m.");
2308 ev
.events
= POLLIN_SET
;
2310 if (epoll_ctl(epfd
, EPOLL_CTL_ADD
, sock
, &ev
) < 0) {
2311 lxcfs_error("%s\n", "Failed adding socket to epoll: %m.");
2317 if ((now
= time(NULL
)) < 0) {
2322 deltatime
= (starttime
+ timeout
) - now
;
2323 if (deltatime
< 0) { // timeout
2328 ret
= epoll_wait(epfd
, &ev
, 1, 1000*deltatime
+ 1);
2329 if (ret
< 0 && errno
== EINTR
)
2331 saved_errno
= errno
;
2335 errno
= saved_errno
;
2341 static int msgrecv(int sockfd
, void *buf
, size_t len
)
2343 if (!wait_for_sock(sockfd
, 2))
2345 return recv(sockfd
, buf
, len
, MSG_DONTWAIT
);
2348 static int send_creds(int sock
, struct ucred
*cred
, char v
, bool pingfirst
)
2350 struct msghdr msg
= { 0 };
2352 struct cmsghdr
*cmsg
;
2353 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
2358 if (msgrecv(sock
, buf
, 1) != 1) {
2359 lxcfs_error("%s\n", "Error getting reply from server over socketpair.");
2360 return SEND_CREDS_FAIL
;
2364 msg
.msg_control
= cmsgbuf
;
2365 msg
.msg_controllen
= sizeof(cmsgbuf
);
2367 cmsg
= CMSG_FIRSTHDR(&msg
);
2368 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct ucred
));
2369 cmsg
->cmsg_level
= SOL_SOCKET
;
2370 cmsg
->cmsg_type
= SCM_CREDENTIALS
;
2371 memcpy(CMSG_DATA(cmsg
), cred
, sizeof(*cred
));
2373 msg
.msg_name
= NULL
;
2374 msg
.msg_namelen
= 0;
2378 iov
.iov_len
= sizeof(buf
);
2382 if (sendmsg(sock
, &msg
, 0) < 0) {
2383 lxcfs_error("Failed at sendmsg: %s.\n",strerror(errno
));
2385 return SEND_CREDS_NOTSK
;
2386 return SEND_CREDS_FAIL
;
2389 return SEND_CREDS_OK
;
2392 static bool recv_creds(int sock
, struct ucred
*cred
, char *v
)
2394 struct msghdr msg
= { 0 };
2396 struct cmsghdr
*cmsg
;
2397 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
2408 if (setsockopt(sock
, SOL_SOCKET
, SO_PASSCRED
, &optval
, sizeof(optval
)) == -1) {
2409 lxcfs_error("Failed to set passcred: %s\n", strerror(errno
));
2413 if (write(sock
, buf
, 1) != 1) {
2414 lxcfs_error("Failed to start write on scm fd: %s\n", strerror(errno
));
2418 msg
.msg_name
= NULL
;
2419 msg
.msg_namelen
= 0;
2420 msg
.msg_control
= cmsgbuf
;
2421 msg
.msg_controllen
= sizeof(cmsgbuf
);
2424 iov
.iov_len
= sizeof(buf
);
2428 if (!wait_for_sock(sock
, 2)) {
2429 lxcfs_error("Timed out waiting for scm_cred: %s\n", strerror(errno
));
2432 ret
= recvmsg(sock
, &msg
, MSG_DONTWAIT
);
2434 lxcfs_error("Failed to receive scm_cred: %s\n", strerror(errno
));
2438 cmsg
= CMSG_FIRSTHDR(&msg
);
2440 if (cmsg
&& cmsg
->cmsg_len
== CMSG_LEN(sizeof(struct ucred
)) &&
2441 cmsg
->cmsg_level
== SOL_SOCKET
&&
2442 cmsg
->cmsg_type
== SCM_CREDENTIALS
) {
2443 memcpy(cred
, CMSG_DATA(cmsg
), sizeof(*cred
));
2450 struct pid_ns_clone_args
{
2454 int (*wrapped
) (int, pid_t
); // pid_from_ns or pid_to_ns
2458 * pid_ns_clone_wrapper - wraps pid_to_ns or pid_from_ns for usage
2459 * with clone(). This simply writes '1' as ACK back to the parent
2460 * before calling the actual wrapped function.
2462 static int pid_ns_clone_wrapper(void *arg
) {
2463 struct pid_ns_clone_args
* args
= (struct pid_ns_clone_args
*) arg
;
2466 close(args
->cpipe
[0]);
2467 if (write(args
->cpipe
[1], &b
, sizeof(char)) < 0)
2468 lxcfs_error("(child): error on write: %s.\n", strerror(errno
));
2469 close(args
->cpipe
[1]);
2470 return args
->wrapped(args
->sock
, args
->tpid
);
2474 * pid_to_ns - reads pids from a ucred over a socket, then writes the
2475 * int value back over the socket. This shifts the pid from the
2476 * sender's pidns into tpid's pidns.
2478 static int pid_to_ns(int sock
, pid_t tpid
)
2483 while (recv_creds(sock
, &cred
, &v
)) {
2486 if (write(sock
, &cred
.pid
, sizeof(pid_t
)) != sizeof(pid_t
))
2494 * pid_to_ns_wrapper: when you setns into a pidns, you yourself remain
2495 * in your old pidns. Only children which you clone will be in the target
2496 * pidns. So the pid_to_ns_wrapper does the setns, then clones a child to
2497 * actually convert pids.
2499 * Note: glibc's fork() does not respect pidns, which can lead to failed
2500 * assertions inside glibc (and thus failed forks) if the child's pid in
2501 * the pidns and the parent pid outside are identical. Using clone prevents
2504 static void pid_to_ns_wrapper(int sock
, pid_t tpid
)
2506 int newnsfd
= -1, ret
, cpipe
[2];
2511 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
2512 if (ret
< 0 || ret
>= sizeof(fnam
))
2514 newnsfd
= open(fnam
, O_RDONLY
);
2517 if (setns(newnsfd
, 0) < 0)
2521 if (pipe(cpipe
) < 0)
2524 struct pid_ns_clone_args args
= {
2528 .wrapped
= &pid_to_ns
2530 size_t stack_size
= sysconf(_SC_PAGESIZE
);
2531 void *stack
= alloca(stack_size
);
2533 cpid
= clone(pid_ns_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &args
);
2537 // give the child 1 second to be done forking and
2539 if (!wait_for_sock(cpipe
[0], 1))
2541 ret
= read(cpipe
[0], &v
, 1);
2542 if (ret
!= sizeof(char) || v
!= '1')
2545 if (!wait_for_pid(cpid
))
2551 * To read cgroup files with a particular pid, we will setns into the child
2552 * pidns, open a pipe, fork a child - which will be the first to really be in
2553 * the child ns - which does the cgfs_get_value and writes the data to the pipe.
2555 bool do_read_pids(pid_t tpid
, const char *contrl
, const char *cg
, const char *file
, char **d
)
2557 int sock
[2] = {-1, -1};
2558 char *tmpdata
= NULL
;
2560 pid_t qpid
, cpid
= -1;
2561 bool answer
= false;
2564 size_t sz
= 0, asz
= 0;
2566 if (!cgfs_get_value(contrl
, cg
, file
, &tmpdata
))
2570 * Now we read the pids from returned data one by one, pass
2571 * them into a child in the target namespace, read back the
2572 * translated pids, and put them into our to-return data
2575 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
2576 perror("socketpair");
2585 if (!cpid
) // child - exits when done
2586 pid_to_ns_wrapper(sock
[1], tpid
);
2588 char *ptr
= tmpdata
;
2591 while (sscanf(ptr
, "%d\n", &qpid
) == 1) {
2593 ret
= send_creds(sock
[0], &cred
, v
, true);
2595 if (ret
== SEND_CREDS_NOTSK
)
2597 if (ret
== SEND_CREDS_FAIL
)
2600 // read converted results
2601 if (!wait_for_sock(sock
[0], 2)) {
2602 lxcfs_error("Timed out waiting for pid from child: %s.\n", strerror(errno
));
2605 if (read(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
2606 lxcfs_error("Error reading pid from child: %s.\n", strerror(errno
));
2609 must_strcat_pid(d
, &sz
, &asz
, qpid
);
2611 ptr
= strchr(ptr
, '\n');
2617 cred
.pid
= getpid();
2619 if (send_creds(sock
[0], &cred
, v
, true) != SEND_CREDS_OK
) {
2620 // failed to ask child to exit
2621 lxcfs_error("Failed to ask child to exit: %s.\n", strerror(errno
));
2631 if (sock
[0] != -1) {
2638 int cg_read(const char *path
, char *buf
, size_t size
, off_t offset
,
2639 struct fuse_file_info
*fi
)
2641 struct fuse_context
*fc
= fuse_get_context();
2642 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2643 struct cgfs_files
*k
= NULL
;
2648 if (f
->type
!= LXC_TYPE_CGFILE
) {
2649 lxcfs_error("%s\n", "Internal error: directory cache info used in cg_read.");
2662 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
2668 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_RDONLY
)) {
2673 if (strcmp(f
->file
, "tasks") == 0 ||
2674 strcmp(f
->file
, "/tasks") == 0 ||
2675 strcmp(f
->file
, "/cgroup.procs") == 0 ||
2676 strcmp(f
->file
, "cgroup.procs") == 0)
2677 // special case - we have to translate the pids
2678 r
= do_read_pids(fc
->pid
, f
->controller
, f
->cgroup
, f
->file
, &data
);
2680 r
= cgfs_get_value(f
->controller
, f
->cgroup
, f
->file
, &data
);
2694 memcpy(buf
, data
, s
);
2695 if (s
> 0 && s
< size
&& data
[s
-1] != '\n')
2705 static int pid_from_ns(int sock
, pid_t tpid
)
2715 if (!wait_for_sock(sock
, 2)) {
2716 lxcfs_error("%s\n", "Timeout reading from parent.");
2719 if ((ret
= read(sock
, &vpid
, sizeof(pid_t
))) != sizeof(pid_t
)) {
2720 lxcfs_error("Bad read from parent: %s.\n", strerror(errno
));
2723 if (vpid
== -1) // done
2727 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
) {
2729 cred
.pid
= getpid();
2730 if (send_creds(sock
, &cred
, v
, false) != SEND_CREDS_OK
)
2737 static void pid_from_ns_wrapper(int sock
, pid_t tpid
)
2739 int newnsfd
= -1, ret
, cpipe
[2];
2744 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
2745 if (ret
< 0 || ret
>= sizeof(fnam
))
2747 newnsfd
= open(fnam
, O_RDONLY
);
2750 if (setns(newnsfd
, 0) < 0)
2754 if (pipe(cpipe
) < 0)
2757 struct pid_ns_clone_args args
= {
2761 .wrapped
= &pid_from_ns
2763 size_t stack_size
= sysconf(_SC_PAGESIZE
);
2764 void *stack
= alloca(stack_size
);
2766 cpid
= clone(pid_ns_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &args
);
2770 // give the child 1 second to be done forking and
2772 if (!wait_for_sock(cpipe
[0], 1))
2774 ret
= read(cpipe
[0], &v
, 1);
2775 if (ret
!= sizeof(char) || v
!= '1')
2778 if (!wait_for_pid(cpid
))
2784 * Given host @uid, return the uid to which it maps in
2785 * @pid's user namespace, or -1 if none.
2787 bool hostuid_to_ns(uid_t uid
, pid_t pid
, uid_t
*answer
)
2792 sprintf(line
, "/proc/%d/uid_map", pid
);
2793 if ((f
= fopen(line
, "r")) == NULL
) {
2797 *answer
= convert_id_to_ns(f
, uid
);
2806 * get_pid_creds: get the real uid and gid of @pid from
2808 * (XXX should we use euid here?)
2810 void get_pid_creds(pid_t pid
, uid_t
*uid
, gid_t
*gid
)
2819 sprintf(line
, "/proc/%d/status", pid
);
2820 if ((f
= fopen(line
, "r")) == NULL
) {
2821 lxcfs_error("Error opening %s: %s\n", line
, strerror(errno
));
2824 while (fgets(line
, 400, f
)) {
2825 if (strncmp(line
, "Uid:", 4) == 0) {
2826 if (sscanf(line
+4, "%u", &u
) != 1) {
2827 lxcfs_error("bad uid line for pid %u\n", pid
);
2832 } else if (strncmp(line
, "Gid:", 4) == 0) {
2833 if (sscanf(line
+4, "%u", &g
) != 1) {
2834 lxcfs_error("bad gid line for pid %u\n", pid
);
2845 * May the requestor @r move victim @v to a new cgroup?
2846 * This is allowed if
2847 * . they are the same task
2848 * . they are ownedy by the same uid
2849 * . @r is root on the host, or
2850 * . @v's uid is mapped into @r's where @r is root.
2852 bool may_move_pid(pid_t r
, uid_t r_uid
, pid_t v
)
2854 uid_t v_uid
, tmpuid
;
2861 get_pid_creds(v
, &v_uid
, &v_gid
);
2864 if (hostuid_to_ns(r_uid
, r
, &tmpuid
) && tmpuid
== 0
2865 && hostuid_to_ns(v_uid
, r
, &tmpuid
))
2870 static bool do_write_pids(pid_t tpid
, uid_t tuid
, const char *contrl
, const char *cg
,
2871 const char *file
, const char *buf
)
2873 int sock
[2] = {-1, -1};
2874 pid_t qpid
, cpid
= -1;
2875 FILE *pids_file
= NULL
;
2876 bool answer
= false, fail
= false;
2878 pids_file
= open_pids_file(contrl
, cg
);
2883 * write the pids to a socket, have helper in writer's pidns
2884 * call movepid for us
2886 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
2887 perror("socketpair");
2895 if (!cpid
) { // child
2897 pid_from_ns_wrapper(sock
[1], tpid
);
2900 const char *ptr
= buf
;
2901 while (sscanf(ptr
, "%d", &qpid
) == 1) {
2905 if (write(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
2906 lxcfs_error("Error writing pid to child: %s.\n", strerror(errno
));
2910 if (recv_creds(sock
[0], &cred
, &v
)) {
2912 if (!may_move_pid(tpid
, tuid
, cred
.pid
)) {
2916 if (fprintf(pids_file
, "%d", (int) cred
.pid
) < 0)
2921 ptr
= strchr(ptr
, '\n');
2927 /* All good, write the value */
2929 if (write(sock
[0], &qpid
,sizeof(qpid
)) != sizeof(qpid
))
2930 lxcfs_error("%s\n", "Warning: failed to ask child to exit.");
2938 if (sock
[0] != -1) {
2943 if (fclose(pids_file
) != 0)
2949 int cg_write(const char *path
, const char *buf
, size_t size
, off_t offset
,
2950 struct fuse_file_info
*fi
)
2952 struct fuse_context
*fc
= fuse_get_context();
2953 char *localbuf
= NULL
;
2954 struct cgfs_files
*k
= NULL
;
2955 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2958 if (f
->type
!= LXC_TYPE_CGFILE
) {
2959 lxcfs_error("%s\n", "Internal error: directory cache info used in cg_write.");
2969 localbuf
= alloca(size
+1);
2970 localbuf
[size
] = '\0';
2971 memcpy(localbuf
, buf
, size
);
2973 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
2978 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_WRONLY
)) {
2983 if (strcmp(f
->file
, "tasks") == 0 ||
2984 strcmp(f
->file
, "/tasks") == 0 ||
2985 strcmp(f
->file
, "/cgroup.procs") == 0 ||
2986 strcmp(f
->file
, "cgroup.procs") == 0)
2987 // special case - we have to translate the pids
2988 r
= do_write_pids(fc
->pid
, fc
->uid
, f
->controller
, f
->cgroup
, f
->file
, localbuf
);
2990 r
= cgfs_set_value(f
->controller
, f
->cgroup
, f
->file
, localbuf
);
3000 int cg_chown(const char *path
, uid_t uid
, gid_t gid
)
3002 struct fuse_context
*fc
= fuse_get_context();
3003 char *cgdir
= NULL
, *last
= NULL
, *path1
, *path2
, *controller
;
3004 struct cgfs_files
*k
= NULL
;
3011 if (strcmp(path
, "/cgroup") == 0)
3014 controller
= pick_controller_from_path(fc
, path
);
3016 return errno
== ENOENT
? -EPERM
: -errno
;
3018 cgroup
= find_cgroup_in_path(path
);
3020 /* this is just /cgroup/controller */
3023 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
3033 if (is_child_cgroup(controller
, path1
, path2
)) {
3034 // get uid, gid, from '/tasks' file and make up a mode
3035 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
3036 k
= cgfs_get_key(controller
, cgroup
, "tasks");
3039 k
= cgfs_get_key(controller
, path1
, path2
);
3047 * This being a fuse request, the uid and gid must be valid
3048 * in the caller's namespace. So we can just check to make
3049 * sure that the caller is root in his uid, and privileged
3050 * over the file's current owner.
3052 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_REQD
)) {
3057 ret
= cgfs_chown_file(controller
, cgroup
, uid
, gid
);
3066 int cg_chmod(const char *path
, mode_t mode
)
3068 struct fuse_context
*fc
= fuse_get_context();
3069 char * cgdir
= NULL
, *last
= NULL
, *path1
, *path2
, *controller
;
3070 struct cgfs_files
*k
= NULL
;
3077 if (strcmp(path
, "/cgroup") == 0)
3080 controller
= pick_controller_from_path(fc
, path
);
3082 return errno
== ENOENT
? -EPERM
: -errno
;
3084 cgroup
= find_cgroup_in_path(path
);
3086 /* this is just /cgroup/controller */
3089 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
3099 if (is_child_cgroup(controller
, path1
, path2
)) {
3100 // get uid, gid, from '/tasks' file and make up a mode
3101 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
3102 k
= cgfs_get_key(controller
, cgroup
, "tasks");
3105 k
= cgfs_get_key(controller
, path1
, path2
);
3113 * This being a fuse request, the uid and gid must be valid
3114 * in the caller's namespace. So we can just check to make
3115 * sure that the caller is root in his uid, and privileged
3116 * over the file's current owner.
3118 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
3123 if (!cgfs_chmod_file(controller
, cgroup
, mode
)) {
3135 int cg_mkdir(const char *path
, mode_t mode
)
3137 struct fuse_context
*fc
= fuse_get_context();
3138 char *last
= NULL
, *path1
, *cgdir
= NULL
, *controller
, *next
= NULL
;
3145 controller
= pick_controller_from_path(fc
, path
);
3147 return errno
== ENOENT
? -EPERM
: -errno
;
3149 cgroup
= find_cgroup_in_path(path
);
3153 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
3159 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3162 if (!caller_is_in_ancestor(initpid
, controller
, path1
, &next
)) {
3165 else if (last
&& strcmp(next
, last
) == 0)
3172 if (!fc_may_access(fc
, controller
, path1
, NULL
, O_RDWR
)) {
3176 if (!caller_is_in_ancestor(initpid
, controller
, path1
, NULL
)) {
3181 ret
= cgfs_create(controller
, cgroup
, fc
->uid
, fc
->gid
);
3189 int cg_rmdir(const char *path
)
3191 struct fuse_context
*fc
= fuse_get_context();
3192 char *last
= NULL
, *cgdir
= NULL
, *controller
, *next
= NULL
;
3199 controller
= pick_controller_from_path(fc
, path
);
3200 if (!controller
) /* Someone's trying to delete "/cgroup". */
3203 cgroup
= find_cgroup_in_path(path
);
3204 if (!cgroup
) /* Someone's trying to delete a controller e.g. "/blkio". */
3207 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
3209 /* Someone's trying to delete a cgroup on the same level as the
3210 * "/lxc" cgroup e.g. rmdir "/cgroup/blkio/lxc" or
3211 * rmdir "/cgroup/blkio/init.slice".
3217 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3220 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, &next
)) {
3221 if (!last
|| (next
&& (strcmp(next
, last
) == 0)))
3228 if (!fc_may_access(fc
, controller
, cgdir
, NULL
, O_WRONLY
)) {
3232 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, NULL
)) {
3237 if (!cgfs_remove(controller
, cgroup
)) {
3250 static bool startswith(const char *line
, const char *pref
)
3252 if (strncmp(line
, pref
, strlen(pref
)) == 0)
3257 static void parse_memstat(char *memstat
, unsigned long *cached
,
3258 unsigned long *active_anon
, unsigned long *inactive_anon
,
3259 unsigned long *active_file
, unsigned long *inactive_file
,
3260 unsigned long *unevictable
, unsigned long *shmem
)
3265 if (startswith(memstat
, "total_cache")) {
3266 sscanf(memstat
+ 11, "%lu", cached
);
3268 } else if (startswith(memstat
, "total_active_anon")) {
3269 sscanf(memstat
+ 17, "%lu", active_anon
);
3270 *active_anon
/= 1024;
3271 } else if (startswith(memstat
, "total_inactive_anon")) {
3272 sscanf(memstat
+ 19, "%lu", inactive_anon
);
3273 *inactive_anon
/= 1024;
3274 } else if (startswith(memstat
, "total_active_file")) {
3275 sscanf(memstat
+ 17, "%lu", active_file
);
3276 *active_file
/= 1024;
3277 } else if (startswith(memstat
, "total_inactive_file")) {
3278 sscanf(memstat
+ 19, "%lu", inactive_file
);
3279 *inactive_file
/= 1024;
3280 } else if (startswith(memstat
, "total_unevictable")) {
3281 sscanf(memstat
+ 17, "%lu", unevictable
);
3282 *unevictable
/= 1024;
3283 } else if (startswith(memstat
, "total_shmem")) {
3284 sscanf(memstat
+ 11, "%lu", shmem
);
3287 eol
= strchr(memstat
, '\n');
3294 static void get_blkio_io_value(char *str
, unsigned major
, unsigned minor
, char *iotype
, unsigned long *v
)
3300 snprintf(key
, 32, "%u:%u %s", major
, minor
, iotype
);
3302 size_t len
= strlen(key
);
3306 if (startswith(str
, key
)) {
3307 sscanf(str
+ len
, "%lu", v
);
3310 eol
= strchr(str
, '\n');
3317 static int read_file(const char *path
, char *buf
, size_t size
,
3318 struct file_info
*d
)
3320 size_t linelen
= 0, total_len
= 0, rv
= 0;
3322 char *cache
= d
->buf
;
3323 size_t cache_size
= d
->buflen
;
3324 FILE *f
= fopen(path
, "r");
3328 while (getline(&line
, &linelen
, f
) != -1) {
3329 ssize_t l
= snprintf(cache
, cache_size
, "%s", line
);
3331 perror("Error writing to cache");
3335 if (l
>= cache_size
) {
3336 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3345 d
->size
= total_len
;
3346 if (total_len
> size
)
3349 /* read from off 0 */
3350 memcpy(buf
, d
->buf
, total_len
);
3359 * FUSE ops for /proc
3362 static unsigned long get_memlimit(const char *cgroup
, const char *file
)
3364 char *memlimit_str
= NULL
;
3365 unsigned long memlimit
= -1;
3367 if (cgfs_get_value("memory", cgroup
, file
, &memlimit_str
))
3368 memlimit
= strtoul(memlimit_str
, NULL
, 10);
3375 static unsigned long get_min_memlimit(const char *cgroup
, const char *file
)
3377 char *copy
= strdupa(cgroup
);
3378 unsigned long memlimit
= 0, retlimit
;
3380 retlimit
= get_memlimit(copy
, file
);
3382 while (strcmp(copy
, "/") != 0) {
3383 copy
= dirname(copy
);
3384 memlimit
= get_memlimit(copy
, file
);
3385 if (memlimit
!= -1 && memlimit
< retlimit
)
3386 retlimit
= memlimit
;
3392 static int proc_meminfo_read(char *buf
, size_t size
, off_t offset
,
3393 struct fuse_file_info
*fi
)
3395 struct fuse_context
*fc
= fuse_get_context();
3396 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3398 char *memusage_str
= NULL
, *memstat_str
= NULL
,
3399 *memswlimit_str
= NULL
, *memswusage_str
= NULL
;
3400 unsigned long memlimit
= 0, memusage
= 0, memswlimit
= 0, memswusage
= 0,
3401 cached
= 0, hosttotal
= 0, active_anon
= 0, inactive_anon
= 0,
3402 active_file
= 0, inactive_file
= 0, unevictable
= 0, shmem
= 0,
3405 size_t linelen
= 0, total_len
= 0, rv
= 0;
3406 char *cache
= d
->buf
;
3407 size_t cache_size
= d
->buflen
;
3411 if (offset
> d
->size
)
3415 int left
= d
->size
- offset
;
3416 total_len
= left
> size
? size
: left
;
3417 memcpy(buf
, cache
+ offset
, total_len
);
3421 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3424 cg
= get_pid_cgroup(initpid
, "memory");
3426 return read_file("/proc/meminfo", buf
, size
, d
);
3427 prune_init_slice(cg
);
3429 memlimit
= get_min_memlimit(cg
, "memory.limit_in_bytes");
3430 if (!cgfs_get_value("memory", cg
, "memory.usage_in_bytes", &memusage_str
))
3432 if (!cgfs_get_value("memory", cg
, "memory.stat", &memstat_str
))
3435 // Following values are allowed to fail, because swapaccount might be turned
3436 // off for current kernel
3437 if(cgfs_get_value("memory", cg
, "memory.memsw.limit_in_bytes", &memswlimit_str
) &&
3438 cgfs_get_value("memory", cg
, "memory.memsw.usage_in_bytes", &memswusage_str
))
3440 memswlimit
= get_min_memlimit(cg
, "memory.memsw.limit_in_bytes");
3441 memswusage
= strtoul(memswusage_str
, NULL
, 10);
3443 memswlimit
= memswlimit
/ 1024;
3444 memswusage
= memswusage
/ 1024;
3447 memusage
= strtoul(memusage_str
, NULL
, 10);
3451 parse_memstat(memstat_str
, &cached
, &active_anon
,
3452 &inactive_anon
, &active_file
, &inactive_file
,
3453 &unevictable
, &shmem
);
3455 f
= fopen("/proc/meminfo", "r");
3459 while (getline(&line
, &linelen
, f
) != -1) {
3461 char *printme
, lbuf
[100];
3463 memset(lbuf
, 0, 100);
3464 if (startswith(line
, "MemTotal:")) {
3465 sscanf(line
+sizeof("MemTotal:")-1, "%lu", &hosttotal
);
3466 if (hosttotal
< memlimit
)
3467 memlimit
= hosttotal
;
3468 snprintf(lbuf
, 100, "MemTotal: %8lu kB\n", memlimit
);
3470 } else if (startswith(line
, "MemFree:")) {
3471 snprintf(lbuf
, 100, "MemFree: %8lu kB\n", memlimit
- memusage
);
3473 } else if (startswith(line
, "MemAvailable:")) {
3474 snprintf(lbuf
, 100, "MemAvailable: %8lu kB\n", memlimit
- memusage
+ cached
);
3476 } else if (startswith(line
, "SwapTotal:") && memswlimit
> 0) {
3477 sscanf(line
+sizeof("SwapTotal:")-1, "%lu", &hostswtotal
);
3478 if (hostswtotal
< memswlimit
)
3479 memswlimit
= hostswtotal
;
3480 snprintf(lbuf
, 100, "SwapTotal: %8lu kB\n", memswlimit
);
3482 } else if (startswith(line
, "SwapFree:") && memswlimit
> 0 && memswusage
> 0) {
3483 unsigned long swaptotal
= memswlimit
,
3484 swapusage
= memswusage
- memusage
,
3485 swapfree
= swapusage
< swaptotal
? swaptotal
- swapusage
: 0;
3486 snprintf(lbuf
, 100, "SwapFree: %8lu kB\n", swapfree
);
3488 } else if (startswith(line
, "Slab:")) {
3489 snprintf(lbuf
, 100, "Slab: %8lu kB\n", 0UL);
3491 } else if (startswith(line
, "Buffers:")) {
3492 snprintf(lbuf
, 100, "Buffers: %8lu kB\n", 0UL);
3494 } else if (startswith(line
, "Cached:")) {
3495 snprintf(lbuf
, 100, "Cached: %8lu kB\n", cached
);
3497 } else if (startswith(line
, "SwapCached:")) {
3498 snprintf(lbuf
, 100, "SwapCached: %8lu kB\n", 0UL);
3500 } else if (startswith(line
, "Active:")) {
3501 snprintf(lbuf
, 100, "Active: %8lu kB\n",
3502 active_anon
+ active_file
);
3504 } else if (startswith(line
, "Inactive:")) {
3505 snprintf(lbuf
, 100, "Inactive: %8lu kB\n",
3506 inactive_anon
+ inactive_file
);
3508 } else if (startswith(line
, "Active(anon)")) {
3509 snprintf(lbuf
, 100, "Active(anon): %8lu kB\n", active_anon
);
3511 } else if (startswith(line
, "Inactive(anon)")) {
3512 snprintf(lbuf
, 100, "Inactive(anon): %8lu kB\n", inactive_anon
);
3514 } else if (startswith(line
, "Active(file)")) {
3515 snprintf(lbuf
, 100, "Active(file): %8lu kB\n", active_file
);
3517 } else if (startswith(line
, "Inactive(file)")) {
3518 snprintf(lbuf
, 100, "Inactive(file): %8lu kB\n", inactive_file
);
3520 } else if (startswith(line
, "Unevictable")) {
3521 snprintf(lbuf
, 100, "Unevictable: %8lu kB\n", unevictable
);
3523 } else if (startswith(line
, "SReclaimable")) {
3524 snprintf(lbuf
, 100, "SReclaimable: %8lu kB\n", 0UL);
3526 } else if (startswith(line
, "SUnreclaim")) {
3527 snprintf(lbuf
, 100, "SUnreclaim: %8lu kB\n", 0UL);
3529 } else if (startswith(line
, "Shmem:")) {
3530 snprintf(lbuf
, 100, "Shmem: %8lu kB\n", shmem
);
3532 } else if (startswith(line
, "ShmemHugePages")) {
3533 snprintf(lbuf
, 100, "ShmemHugePages: %8lu kB\n", 0UL);
3535 } else if (startswith(line
, "ShmemPmdMapped")) {
3536 snprintf(lbuf
, 100, "ShmemPmdMapped: %8lu kB\n", 0UL);
3541 l
= snprintf(cache
, cache_size
, "%s", printme
);
3543 perror("Error writing to cache");
3548 if (l
>= cache_size
) {
3549 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3560 d
->size
= total_len
;
3561 if (total_len
> size
) total_len
= size
;
3562 memcpy(buf
, d
->buf
, total_len
);
3571 free(memswlimit_str
);
3572 free(memswusage_str
);
3578 * Read the cpuset.cpus for cg
3579 * Return the answer in a newly allocated string which must be freed
3581 static char *get_cpuset(const char *cg
)
3585 if (!cgfs_get_value("cpuset", cg
, "cpuset.cpus", &answer
))
3590 bool cpu_in_cpuset(int cpu
, const char *cpuset
);
3592 static bool cpuline_in_cpuset(const char *line
, const char *cpuset
)
3596 if (sscanf(line
, "processor : %d", &cpu
) != 1)
3598 return cpu_in_cpuset(cpu
, cpuset
);
3602 * Read cgroup CPU quota parameters from `cpu.cfs_quota_us` or `cpu.cfs_period_us`,
3603 * depending on `param`. Parameter value is returned throuh `value`.
3605 static bool read_cpu_cfs_param(const char *cg
, const char *param
, int64_t *value
)
3608 char file
[11 + 6 + 1]; // cpu.cfs__us + quota/period + \0
3611 sprintf(file
, "cpu.cfs_%s_us", param
);
3613 if (!cgfs_get_value("cpu", cg
, file
, &str
))
3616 if (sscanf(str
, "%ld", value
) != 1)
3628 * Return the maximum number of visible CPUs based on CPU quotas.
3629 * If there is no quota set, zero is returned.
3631 int max_cpu_count(const char *cg
)
3634 int64_t cfs_quota
, cfs_period
;
3636 if (!read_cpu_cfs_param(cg
, "quota", &cfs_quota
))
3639 if (!read_cpu_cfs_param(cg
, "period", &cfs_period
))
3642 if (cfs_quota
<= 0 || cfs_period
<= 0)
3645 rv
= cfs_quota
/ cfs_period
;
3647 /* In case quota/period does not yield a whole number, add one CPU for
3650 if ((cfs_quota
% cfs_period
) > 0)
3653 nprocs
= get_nprocs();
3662 * Determine whether CPU views should be used or not.
3664 bool use_cpuview(const char *cg
)
3669 tmpc
= find_mounted_controller("cpu", &cfd
);
3673 tmpc
= find_mounted_controller("cpuacct", &cfd
);
3681 * check whether this is a '^processor" line in /proc/cpuinfo
3683 static bool is_processor_line(const char *line
)
3687 if (sscanf(line
, "processor : %d", &cpu
) == 1)
3692 static int proc_cpuinfo_read(char *buf
, size_t size
, off_t offset
,
3693 struct fuse_file_info
*fi
)
3695 struct fuse_context
*fc
= fuse_get_context();
3696 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3698 char *cpuset
= NULL
;
3700 size_t linelen
= 0, total_len
= 0, rv
= 0;
3701 bool am_printing
= false, firstline
= true, is_s390x
= false;
3702 int curcpu
= -1, cpu
, max_cpus
= 0;
3704 char *cache
= d
->buf
;
3705 size_t cache_size
= d
->buflen
;
3709 if (offset
> d
->size
)
3713 int left
= d
->size
- offset
;
3714 total_len
= left
> size
? size
: left
;
3715 memcpy(buf
, cache
+ offset
, total_len
);
3719 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3722 cg
= get_pid_cgroup(initpid
, "cpuset");
3724 return read_file("proc/cpuinfo", buf
, size
, d
);
3725 prune_init_slice(cg
);
3727 cpuset
= get_cpuset(cg
);
3731 use_view
= use_cpuview(cg
);
3734 max_cpus
= max_cpu_count(cg
);
3736 f
= fopen("/proc/cpuinfo", "r");
3740 while (getline(&line
, &linelen
, f
) != -1) {
3744 if (strstr(line
, "IBM/S390") != NULL
) {
3750 if (strncmp(line
, "# processors:", 12) == 0)
3752 if (is_processor_line(line
)) {
3753 if (use_view
&& max_cpus
> 0 && (curcpu
+1) == max_cpus
)
3755 am_printing
= cpuline_in_cpuset(line
, cpuset
);
3758 l
= snprintf(cache
, cache_size
, "processor : %d\n", curcpu
);
3760 perror("Error writing to cache");
3764 if (l
>= cache_size
) {
3765 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3774 } else if (is_s390x
&& sscanf(line
, "processor %d:", &cpu
) == 1) {
3776 if (use_view
&& max_cpus
> 0 && (curcpu
+1) == max_cpus
)
3778 if (!cpu_in_cpuset(cpu
, cpuset
))
3781 p
= strchr(line
, ':');
3785 l
= snprintf(cache
, cache_size
, "processor %d:%s", curcpu
, p
);
3787 perror("Error writing to cache");
3791 if (l
>= cache_size
) {
3792 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3803 l
= snprintf(cache
, cache_size
, "%s", line
);
3805 perror("Error writing to cache");
3809 if (l
>= cache_size
) {
3810 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3821 char *origcache
= d
->buf
;
3824 d
->buf
= malloc(d
->buflen
);
3827 cache_size
= d
->buflen
;
3829 l
= snprintf(cache
, cache_size
, "vendor_id : IBM/S390\n");
3830 if (l
< 0 || l
>= cache_size
) {
3837 l
= snprintf(cache
, cache_size
, "# processors : %d\n", curcpu
+ 1);
3838 if (l
< 0 || l
>= cache_size
) {
3845 l
= snprintf(cache
, cache_size
, "%s", origcache
);
3847 if (l
< 0 || l
>= cache_size
)
3853 d
->size
= total_len
;
3854 if (total_len
> size
) total_len
= size
;
3856 /* read from off 0 */
3857 memcpy(buf
, d
->buf
, total_len
);
3868 static uint64_t get_reaper_start_time(pid_t pid
)
3873 /* strlen("/proc/") = 6
3877 * strlen("/stat") = 5
3881 #define __PROC_PID_STAT_LEN (6 + LXCFS_NUMSTRLEN64 + 5 + 1)
3882 char path
[__PROC_PID_STAT_LEN
];
3885 qpid
= lookup_initpid_in_store(pid
);
3887 /* Caller can check for EINVAL on 0. */
3892 ret
= snprintf(path
, __PROC_PID_STAT_LEN
, "/proc/%d/stat", qpid
);
3893 if (ret
< 0 || ret
>= __PROC_PID_STAT_LEN
) {
3894 /* Caller can check for EINVAL on 0. */
3899 f
= fopen(path
, "r");
3901 /* Caller can check for EINVAL on 0. */
3906 /* Note that the *scanf() argument supression requires that length
3907 * modifiers such as "l" are omitted. Otherwise some compilers will yell
3908 * at us. It's like telling someone you're not married and then asking
3909 * if you can bring your wife to the party.
3911 ret
= fscanf(f
, "%*d " /* (1) pid %d */
3912 "%*s " /* (2) comm %s */
3913 "%*c " /* (3) state %c */
3914 "%*d " /* (4) ppid %d */
3915 "%*d " /* (5) pgrp %d */
3916 "%*d " /* (6) session %d */
3917 "%*d " /* (7) tty_nr %d */
3918 "%*d " /* (8) tpgid %d */
3919 "%*u " /* (9) flags %u */
3920 "%*u " /* (10) minflt %lu */
3921 "%*u " /* (11) cminflt %lu */
3922 "%*u " /* (12) majflt %lu */
3923 "%*u " /* (13) cmajflt %lu */
3924 "%*u " /* (14) utime %lu */
3925 "%*u " /* (15) stime %lu */
3926 "%*d " /* (16) cutime %ld */
3927 "%*d " /* (17) cstime %ld */
3928 "%*d " /* (18) priority %ld */
3929 "%*d " /* (19) nice %ld */
3930 "%*d " /* (20) num_threads %ld */
3931 "%*d " /* (21) itrealvalue %ld */
3932 "%" PRIu64
, /* (22) starttime %llu */
3936 /* Caller can check for EINVAL on 0. */
3947 static uint64_t get_reaper_start_time_in_sec(pid_t pid
)
3949 uint64_t clockticks
;
3950 int64_t ticks_per_sec
;
3952 clockticks
= get_reaper_start_time(pid
);
3953 if (clockticks
== 0 && errno
== EINVAL
) {
3954 lxcfs_debug("failed to retrieve start time of pid %d\n", pid
);
3958 ticks_per_sec
= sysconf(_SC_CLK_TCK
);
3959 if (ticks_per_sec
< 0 && errno
== EINVAL
) {
3962 "failed to determine number of clock ticks in a second");
3966 return (clockticks
/= ticks_per_sec
);
3969 static uint64_t get_reaper_age(pid_t pid
)
3971 uint64_t procstart
, uptime
, procage
;
3973 /* We need to substract the time the process has started since system
3974 * boot minus the time when the system has started to get the actual
3977 procstart
= get_reaper_start_time_in_sec(pid
);
3978 procage
= procstart
;
3979 if (procstart
> 0) {
3981 struct timespec spec
;
3983 ret
= clock_gettime(CLOCK_BOOTTIME
, &spec
);
3986 /* We could make this more precise here by using the tv_nsec
3987 * field in the timespec struct and convert it to milliseconds
3988 * and then create a double for the seconds and milliseconds but
3989 * that seems more work than it is worth.
3991 uptime
= spec
.tv_sec
;
3992 procage
= uptime
- procstart
;
3999 * Returns 0 on success.
4000 * It is the caller's responsibility to free `return_usage`, unless this
4001 * function returns an error.
4003 static int read_cpuacct_usage_all(char *cg
, char *cpuset
, struct cpuacct_usage
**return_usage
)
4005 int cpucount
= get_nprocs();
4006 struct cpuacct_usage
*cpu_usage
;
4007 int rv
= 0, i
, j
, ret
, read_pos
= 0, read_cnt
;
4009 uint64_t cg_user
, cg_system
;
4010 int64_t ticks_per_sec
;
4011 char *usage_str
= NULL
;
4013 ticks_per_sec
= sysconf(_SC_CLK_TCK
);
4015 if (ticks_per_sec
< 0 && errno
== EINVAL
) {
4018 "read_cpuacct_usage_all failed to determine number of clock ticks "
4023 cpu_usage
= malloc(sizeof(struct cpuacct_usage
) * cpucount
);
4027 if (!cgfs_get_value("cpuacct", cg
, "cpuacct.usage_all", &usage_str
)) {
4032 if (sscanf(usage_str
, "cpu user system\n%n", &read_cnt
) != 0) {
4033 lxcfs_error("read_cpuacct_usage_all reading first line from "
4034 "%s/cpuacct.usage_all failed.\n", cg
);
4039 read_pos
+= read_cnt
;
4041 for (i
= 0, j
= 0; i
< cpucount
; i
++) {
4042 ret
= sscanf(usage_str
+ read_pos
, "%d %lu %lu\n%n", &cg_cpu
, &cg_user
,
4043 &cg_system
, &read_cnt
);
4049 lxcfs_error("read_cpuacct_usage_all reading from %s/cpuacct.usage_all "
4055 read_pos
+= read_cnt
;
4057 if (!cpu_in_cpuset(i
, cpuset
))
4060 /* Convert the time from nanoseconds to USER_HZ */
4061 cpu_usage
[j
].user
= cg_user
/ 1000.0 / 1000 / 1000 * ticks_per_sec
;
4062 cpu_usage
[j
].system
= cg_system
/ 1000.0 / 1000 / 1000 * ticks_per_sec
;
4067 *return_usage
= cpu_usage
;
4075 *return_usage
= NULL
;
4081 static unsigned long diff_cpu_usage(struct cpuacct_usage
*older
, struct cpuacct_usage
*newer
, struct cpuacct_usage
*diff
, int cpu_count
)
4084 unsigned long sum
= 0;
4086 for (i
= 0; i
< cpu_count
; i
++) {
4087 /* When cpuset is changed on the fly, the CPUs might get reordered.
4088 * We could either reset all counters, or check that the substractions
4089 * below will return expected results.
4091 if (newer
[i
].user
> older
[i
].user
)
4092 diff
[i
].user
= newer
[i
].user
- older
[i
].user
;
4096 if (newer
[i
].system
> older
[i
].system
)
4097 diff
[i
].system
= newer
[i
].system
- older
[i
].system
;
4101 if (newer
[i
].idle
> older
[i
].idle
)
4102 diff
[i
].idle
= newer
[i
].idle
- older
[i
].idle
;
4106 sum
+= diff
[i
].user
;
4107 sum
+= diff
[i
].system
;
4108 sum
+= diff
[i
].idle
;
4114 static void add_cpu_usage(unsigned long *surplus
, struct cpuacct_usage
*usage
, unsigned long *counter
, unsigned long threshold
)
4116 unsigned long free_space
, to_add
;
4118 free_space
= threshold
- usage
->user
- usage
->system
;
4120 if (free_space
> usage
->idle
)
4121 free_space
= usage
->idle
;
4123 to_add
= free_space
> *surplus
? *surplus
: free_space
;
4126 usage
->idle
-= to_add
;
4130 static struct cg_proc_stat
*find_proc_stat_node(const char *cg
)
4132 int hash
= calc_hash(cg
) % CPUVIEW_HASH_SIZE
;
4133 struct cg_proc_stat_head
*head
= proc_stat_history
[hash
];
4134 struct cg_proc_stat
*node
;
4142 if (strcmp(cg
, node
->cg
) == 0)
4144 } while ((node
= node
->next
));
4149 static struct cg_proc_stat
*new_proc_stat_node(struct cpuacct_usage
*usage
, int cpu_count
, const char *cg
)
4151 struct cg_proc_stat
*node
;
4154 node
= malloc(sizeof(struct cg_proc_stat
));
4162 node
->cg
= malloc(strlen(cg
) + 1);
4166 strcpy(node
->cg
, cg
);
4168 node
->usage
= malloc(sizeof(struct cpuacct_usage
) * cpu_count
);
4172 memcpy(node
->usage
, usage
, sizeof(struct cpuacct_usage
) * cpu_count
);
4174 node
->view
= malloc(sizeof(struct cpuacct_usage
) * cpu_count
);
4178 node
->cpu_count
= cpu_count
;
4181 for (i
= 0; i
< cpu_count
; i
++) {
4182 node
->view
[i
].user
= 0;
4183 node
->view
[i
].system
= 0;
4184 node
->view
[i
].idle
= 0;
4190 if (node
&& node
->cg
)
4192 if (node
&& node
->usage
)
4194 if (node
&& node
->view
)
4202 static void add_proc_stat_node(struct cg_proc_stat
*new_node
)
4204 int hash
= calc_hash(new_node
->cg
) % CPUVIEW_HASH_SIZE
;
4205 struct cg_proc_stat_head
*head
= proc_stat_history
[hash
];
4206 struct cg_proc_stat
*node
;
4209 head
->next
= new_node
;
4221 node
->next
= new_node
;
4226 static void reset_proc_stat_node(struct cg_proc_stat
*node
, struct cpuacct_usage
*usage
, int cpu_count
)
4230 lxcfs_debug("Resetting stat node for %s\n", node
->cg
);
4231 memcpy(node
->usage
, usage
, sizeof(struct cpuacct_usage
) * cpu_count
);
4233 for (i
= 0; i
< cpu_count
; i
++) {
4234 node
->view
[i
].user
= 0;
4235 node
->view
[i
].system
= 0;
4236 node
->view
[i
].idle
= 0;
4239 node
->cpu_count
= cpu_count
;
4242 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
)
4245 size_t linelen
= 0, total_len
= 0, rv
= 0, l
;
4246 int curcpu
= -1; /* cpu numbering starts at 0 */
4247 int max_cpus
= max_cpu_count(cg
), cpu_cnt
= 0;
4248 unsigned long user
= 0, nice
= 0, system
= 0, idle
= 0, iowait
= 0, irq
= 0, softirq
= 0, steal
= 0, guest
= 0, guest_nice
= 0;
4249 unsigned long user_sum
= 0, system_sum
= 0, idle_sum
= 0;
4250 unsigned long user_surplus
= 0, system_surplus
= 0;
4251 unsigned long total_sum
, threshold
;
4252 struct cg_proc_stat
*stat_node
;
4253 struct cpuacct_usage
*diff
= NULL
;
4254 int nprocs
= get_nprocs();
4256 /* Read all CPU stats and stop when we've encountered other lines */
4257 while (getline(&line
, &linelen
, f
) != -1) {
4259 char cpu_char
[10]; /* That's a lot of cores */
4260 uint64_t all_used
, cg_used
;
4262 if (strlen(line
) == 0)
4264 if (sscanf(line
, "cpu%9[^ ]", cpu_char
) != 1) {
4265 /* not a ^cpuN line containing a number N */
4269 if (sscanf(cpu_char
, "%d", &cpu
) != 1)
4271 if (!cpu_in_cpuset(cpu
, cpuset
))
4276 ret
= sscanf(line
, "%*s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
4291 all_used
= user
+ nice
+ system
+ iowait
+ irq
+ softirq
+ steal
+ guest
+ guest_nice
;
4292 cg_used
= cg_cpu_usage
[curcpu
].user
+ cg_cpu_usage
[curcpu
].system
;
4294 if (all_used
>= cg_used
) {
4295 cg_cpu_usage
[curcpu
].idle
= idle
+ (all_used
- cg_used
);
4298 lxcfs_error("cpu%d from %s has unexpected cpu time: %lu in /proc/stat, "
4299 "%lu in cpuacct.usage_all; unable to determine idle time\n",
4300 curcpu
, cg
, all_used
, cg_used
);
4301 cg_cpu_usage
[curcpu
].idle
= idle
;
4305 /* Cannot use more CPUs than is available due to cpuset */
4306 if (max_cpus
> cpu_cnt
)
4309 stat_node
= find_proc_stat_node(cg
);
4312 stat_node
= new_proc_stat_node(cg_cpu_usage
, nprocs
, cg
);
4318 add_proc_stat_node(stat_node
);
4321 diff
= malloc(sizeof(struct cpuacct_usage
) * nprocs
);
4328 * If the new values are LOWER than values stored in memory, it means
4329 * the cgroup has been reset/recreated and we should reset too.
4331 if (cg_cpu_usage
[0].user
< stat_node
->usage
[0].user
)
4332 reset_proc_stat_node(stat_node
, cg_cpu_usage
, nprocs
);
4334 total_sum
= diff_cpu_usage(stat_node
->usage
, cg_cpu_usage
, diff
, cpu_cnt
);
4336 for (curcpu
= 0; curcpu
< cpu_cnt
; curcpu
++) {
4337 stat_node
->usage
[curcpu
].user
+= diff
[curcpu
].user
;
4338 stat_node
->usage
[curcpu
].system
+= diff
[curcpu
].system
;
4339 stat_node
->usage
[curcpu
].idle
+= diff
[curcpu
].idle
;
4341 if (max_cpus
> 0 && curcpu
>= max_cpus
) {
4342 user_surplus
+= diff
[curcpu
].user
;
4343 system_surplus
+= diff
[curcpu
].system
;
4347 /* Calculate usage counters of visible CPUs */
4349 /* threshold = maximum usage per cpu, including idle */
4350 threshold
= total_sum
/ cpu_cnt
* max_cpus
;
4352 for (curcpu
= 0; curcpu
< max_cpus
; curcpu
++) {
4353 if (diff
[curcpu
].user
+ diff
[curcpu
].system
>= threshold
)
4363 if (diff
[curcpu
].user
+ diff
[curcpu
].system
>= threshold
)
4366 /* If there is still room, add system */
4370 &diff
[curcpu
].system
,
4374 if (user_surplus
> 0)
4375 lxcfs_debug("leftover user: %lu for %s\n", user_surplus
, cg
);
4376 if (system_surplus
> 0)
4377 lxcfs_debug("leftover system: %lu for %s\n", system_surplus
, cg
);
4379 for (curcpu
= 0; curcpu
< max_cpus
; curcpu
++) {
4380 stat_node
->view
[curcpu
].user
+= diff
[curcpu
].user
;
4381 stat_node
->view
[curcpu
].system
+= diff
[curcpu
].system
;
4382 stat_node
->view
[curcpu
].idle
+= diff
[curcpu
].idle
;
4384 user_sum
+= stat_node
->view
[curcpu
].user
;
4385 system_sum
+= stat_node
->view
[curcpu
].system
;
4386 idle_sum
+= stat_node
->view
[curcpu
].idle
;
4390 for (curcpu
= 0; curcpu
< cpu_cnt
; curcpu
++) {
4391 stat_node
->view
[curcpu
].user
= stat_node
->usage
[curcpu
].user
;
4392 stat_node
->view
[curcpu
].system
= stat_node
->usage
[curcpu
].system
;
4393 stat_node
->view
[curcpu
].idle
= stat_node
->usage
[curcpu
].idle
;
4395 user_sum
+= stat_node
->view
[curcpu
].user
;
4396 system_sum
+= stat_node
->view
[curcpu
].system
;
4397 idle_sum
+= stat_node
->view
[curcpu
].idle
;
4401 /* Render the file */
4403 l
= snprintf(buf
, buf_size
, "cpu %lu 0 %lu %lu 0 0 0 0 0 0\n",
4409 perror("Error writing to cache");
4414 if (l
>= buf_size
) {
4415 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4424 /* Render visible CPUs */
4425 for (curcpu
= 0; curcpu
< cpu_cnt
; curcpu
++) {
4426 if (max_cpus
> 0 && curcpu
== max_cpus
)
4429 l
= snprintf(buf
, buf_size
, "cpu%d %lu 0 %lu %lu 0 0 0 0 0 0\n",
4431 stat_node
->view
[curcpu
].user
,
4432 stat_node
->view
[curcpu
].system
,
4433 stat_node
->view
[curcpu
].idle
);
4436 perror("Error writing to cache");
4441 if (l
>= buf_size
) {
4442 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4452 /* Pass the rest of /proc/stat, start with the last line read */
4453 l
= snprintf(buf
, buf_size
, "%s", line
);
4456 perror("Error writing to cache");
4461 if (l
>= buf_size
) {
4462 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4471 /* Pass the rest of the host's /proc/stat */
4472 while (getline(&line
, &linelen
, f
) != -1) {
4473 l
= snprintf(buf
, buf_size
, "%s", line
);
4475 perror("Error writing to cache");
4479 if (l
>= buf_size
) {
4480 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4499 #define CPUALL_MAX_SIZE (BUF_RESERVE_SIZE / 2)
4500 static int proc_stat_read(char *buf
, size_t size
, off_t offset
,
4501 struct fuse_file_info
*fi
)
4503 struct fuse_context
*fc
= fuse_get_context();
4504 struct file_info
*d
= (struct file_info
*)fi
->fh
;
4506 char *cpuset
= NULL
;
4508 size_t linelen
= 0, total_len
= 0, rv
= 0;
4509 int curcpu
= -1; /* cpu numbering starts at 0 */
4510 unsigned long user
= 0, nice
= 0, system
= 0, idle
= 0, iowait
= 0, irq
= 0, softirq
= 0, steal
= 0, guest
= 0, guest_nice
= 0;
4511 unsigned long user_sum
= 0, nice_sum
= 0, system_sum
= 0, idle_sum
= 0, iowait_sum
= 0,
4512 irq_sum
= 0, softirq_sum
= 0, steal_sum
= 0, guest_sum
= 0, guest_nice_sum
= 0;
4513 char cpuall
[CPUALL_MAX_SIZE
];
4514 /* reserve for cpu all */
4515 char *cache
= d
->buf
+ CPUALL_MAX_SIZE
;
4516 size_t cache_size
= d
->buflen
- CPUALL_MAX_SIZE
;
4518 struct cpuacct_usage
*cg_cpu_usage
= NULL
;
4521 if (offset
> d
->size
)
4525 int left
= d
->size
- offset
;
4526 total_len
= left
> size
? size
: left
;
4527 memcpy(buf
, d
->buf
+ offset
, total_len
);
4531 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
4534 cg
= get_pid_cgroup(initpid
, "cpuset");
4536 return read_file("/proc/stat", buf
, size
, d
);
4537 prune_init_slice(cg
);
4539 cpuset
= get_cpuset(cg
);
4544 * Read cpuacct.usage_all for all CPUs.
4545 * If the cpuacct cgroup is present, it is used to calculate the container's
4546 * CPU usage. If not, values from the host's /proc/stat are used.
4548 if (read_cpuacct_usage_all(cg
, cpuset
, &cg_cpu_usage
) != 0) {
4549 lxcfs_debug("%s\n", "proc_stat_read failed to read from cpuacct, "
4550 "falling back to the host's /proc/stat");
4553 f
= fopen("/proc/stat", "r");
4558 if (getline(&line
, &linelen
, f
) < 0) {
4559 lxcfs_error("%s\n", "proc_stat_read read first line failed.");
4563 if (use_cpuview(cg
) && cg_cpu_usage
) {
4564 total_len
= cpuview_proc_stat(cg
, cpuset
, cg_cpu_usage
, f
, d
->buf
, d
->buflen
);
4568 while (getline(&line
, &linelen
, f
) != -1) {
4571 char cpu_char
[10]; /* That's a lot of cores */
4573 uint64_t all_used
, cg_used
, new_idle
;
4576 if (strlen(line
) == 0)
4578 if (sscanf(line
, "cpu%9[^ ]", cpu_char
) != 1) {
4579 /* not a ^cpuN line containing a number N, just print it */
4580 l
= snprintf(cache
, cache_size
, "%s", line
);
4582 perror("Error writing to cache");
4586 if (l
>= cache_size
) {
4587 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4597 if (sscanf(cpu_char
, "%d", &cpu
) != 1)
4599 if (!cpu_in_cpuset(cpu
, cpuset
))
4603 ret
= sscanf(line
, "%*s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
4615 if (ret
!= 10 || !cg_cpu_usage
) {
4616 c
= strchr(line
, ' ');
4619 l
= snprintf(cache
, cache_size
, "cpu%d%s", curcpu
, c
);
4621 perror("Error writing to cache");
4626 if (l
>= cache_size
) {
4627 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4641 all_used
= user
+ nice
+ system
+ iowait
+ irq
+ softirq
+ steal
+ guest
+ guest_nice
;
4642 cg_used
= cg_cpu_usage
[curcpu
].user
+ cg_cpu_usage
[curcpu
].system
;
4644 if (all_used
>= cg_used
) {
4645 new_idle
= idle
+ (all_used
- cg_used
);
4648 lxcfs_error("cpu%d from %s has unexpected cpu time: %lu in /proc/stat, "
4649 "%lu in cpuacct.usage_all; unable to determine idle time\n",
4650 curcpu
, cg
, all_used
, cg_used
);
4654 l
= snprintf(cache
, cache_size
, "cpu%d %lu 0 %lu %lu 0 0 0 0 0 0\n",
4655 curcpu
, cg_cpu_usage
[curcpu
].user
, cg_cpu_usage
[curcpu
].system
,
4659 perror("Error writing to cache");
4664 if (l
>= cache_size
) {
4665 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4674 user_sum
+= cg_cpu_usage
[curcpu
].user
;
4675 system_sum
+= cg_cpu_usage
[curcpu
].system
;
4676 idle_sum
+= new_idle
;
4681 system_sum
+= system
;
4683 iowait_sum
+= iowait
;
4685 softirq_sum
+= softirq
;
4688 guest_nice_sum
+= guest_nice
;
4694 int cpuall_len
= snprintf(cpuall
, CPUALL_MAX_SIZE
, "cpu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
4705 if (cpuall_len
> 0 && cpuall_len
< CPUALL_MAX_SIZE
) {
4706 memcpy(cache
, cpuall
, cpuall_len
);
4707 cache
+= cpuall_len
;
4709 /* shouldn't happen */
4710 lxcfs_error("proc_stat_read copy cpuall failed, cpuall_len=%d.", cpuall_len
);
4714 memmove(cache
, d
->buf
+ CPUALL_MAX_SIZE
, total_len
);
4715 total_len
+= cpuall_len
;
4719 d
->size
= total_len
;
4720 if (total_len
> size
)
4723 memcpy(buf
, d
->buf
, total_len
);
4737 /* This function retrieves the busy time of a group of tasks by looking at
4738 * cpuacct.usage. Unfortunately, this only makes sense when the container has
4739 * been given it's own cpuacct cgroup. If not, this function will take the busy
4740 * time of all other taks that do not actually belong to the container into
4741 * account as well. If someone has a clever solution for this please send a
4744 static unsigned long get_reaper_busy(pid_t task
)
4746 pid_t initpid
= lookup_initpid_in_store(task
);
4747 char *cgroup
= NULL
, *usage_str
= NULL
;
4748 unsigned long usage
= 0;
4753 cgroup
= get_pid_cgroup(initpid
, "cpuacct");
4756 prune_init_slice(cgroup
);
4757 if (!cgfs_get_value("cpuacct", cgroup
, "cpuacct.usage", &usage_str
))
4759 usage
= strtoul(usage_str
, NULL
, 10);
4760 usage
/= 1000000000;
4773 fd
= creat("/tmp/lxcfs-iwashere", 0644);
4780 * We read /proc/uptime and reuse its second field.
4781 * For the first field, we use the mtime for the reaper for
4782 * the calling pid as returned by getreaperage
4784 static int proc_uptime_read(char *buf
, size_t size
, off_t offset
,
4785 struct fuse_file_info
*fi
)
4787 struct fuse_context
*fc
= fuse_get_context();
4788 struct file_info
*d
= (struct file_info
*)fi
->fh
;
4789 unsigned long int busytime
= get_reaper_busy(fc
->pid
);
4790 char *cache
= d
->buf
;
4791 ssize_t total_len
= 0;
4792 uint64_t idletime
, reaperage
;
4801 if (offset
> d
->size
)
4803 int left
= d
->size
- offset
;
4804 total_len
= left
> size
? size
: left
;
4805 memcpy(buf
, cache
+ offset
, total_len
);
4809 reaperage
= get_reaper_age(fc
->pid
);
4810 /* To understand why this is done, please read the comment to the
4811 * get_reaper_busy() function.
4813 idletime
= reaperage
;
4814 if (reaperage
>= busytime
)
4815 idletime
= reaperage
- busytime
;
4817 total_len
= snprintf(d
->buf
, d
->buflen
, "%"PRIu64
".00 %"PRIu64
".00\n", reaperage
, idletime
);
4818 if (total_len
< 0 || total_len
>= d
->buflen
){
4819 lxcfs_error("%s\n", "failed to write to cache");
4823 d
->size
= (int)total_len
;
4826 if (total_len
> size
) total_len
= size
;
4828 memcpy(buf
, d
->buf
, total_len
);
4832 static int proc_diskstats_read(char *buf
, size_t size
, off_t offset
,
4833 struct fuse_file_info
*fi
)
4836 struct fuse_context
*fc
= fuse_get_context();
4837 struct file_info
*d
= (struct file_info
*)fi
->fh
;
4839 char *io_serviced_str
= NULL
, *io_merged_str
= NULL
, *io_service_bytes_str
= NULL
,
4840 *io_wait_time_str
= NULL
, *io_service_time_str
= NULL
;
4841 unsigned long read
= 0, write
= 0;
4842 unsigned long read_merged
= 0, write_merged
= 0;
4843 unsigned long read_sectors
= 0, write_sectors
= 0;
4844 unsigned long read_ticks
= 0, write_ticks
= 0;
4845 unsigned long ios_pgr
= 0, tot_ticks
= 0, rq_ticks
= 0;
4846 unsigned long rd_svctm
= 0, wr_svctm
= 0, rd_wait
= 0, wr_wait
= 0;
4847 char *cache
= d
->buf
;
4848 size_t cache_size
= d
->buflen
;
4850 size_t linelen
= 0, total_len
= 0, rv
= 0;
4851 unsigned int major
= 0, minor
= 0;
4856 if (offset
> d
->size
)
4860 int left
= d
->size
- offset
;
4861 total_len
= left
> size
? size
: left
;
4862 memcpy(buf
, cache
+ offset
, total_len
);
4866 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
4869 cg
= get_pid_cgroup(initpid
, "blkio");
4871 return read_file("/proc/diskstats", buf
, size
, d
);
4872 prune_init_slice(cg
);
4874 if (!cgfs_get_value("blkio", cg
, "blkio.io_serviced_recursive", &io_serviced_str
))
4876 if (!cgfs_get_value("blkio", cg
, "blkio.io_merged_recursive", &io_merged_str
))
4878 if (!cgfs_get_value("blkio", cg
, "blkio.io_service_bytes_recursive", &io_service_bytes_str
))
4880 if (!cgfs_get_value("blkio", cg
, "blkio.io_wait_time_recursive", &io_wait_time_str
))
4882 if (!cgfs_get_value("blkio", cg
, "blkio.io_service_time_recursive", &io_service_time_str
))
4886 f
= fopen("/proc/diskstats", "r");
4890 while (getline(&line
, &linelen
, f
) != -1) {
4894 i
= sscanf(line
, "%u %u %71s", &major
, &minor
, dev_name
);
4898 get_blkio_io_value(io_serviced_str
, major
, minor
, "Read", &read
);
4899 get_blkio_io_value(io_serviced_str
, major
, minor
, "Write", &write
);
4900 get_blkio_io_value(io_merged_str
, major
, minor
, "Read", &read_merged
);
4901 get_blkio_io_value(io_merged_str
, major
, minor
, "Write", &write_merged
);
4902 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Read", &read_sectors
);
4903 read_sectors
= read_sectors
/512;
4904 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Write", &write_sectors
);
4905 write_sectors
= write_sectors
/512;
4907 get_blkio_io_value(io_service_time_str
, major
, minor
, "Read", &rd_svctm
);
4908 rd_svctm
= rd_svctm
/1000000;
4909 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Read", &rd_wait
);
4910 rd_wait
= rd_wait
/1000000;
4911 read_ticks
= rd_svctm
+ rd_wait
;
4913 get_blkio_io_value(io_service_time_str
, major
, minor
, "Write", &wr_svctm
);
4914 wr_svctm
= wr_svctm
/1000000;
4915 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Write", &wr_wait
);
4916 wr_wait
= wr_wait
/1000000;
4917 write_ticks
= wr_svctm
+ wr_wait
;
4919 get_blkio_io_value(io_service_time_str
, major
, minor
, "Total", &tot_ticks
);
4920 tot_ticks
= tot_ticks
/1000000;
4922 memset(lbuf
, 0, 256);
4923 if (read
|| write
|| read_merged
|| write_merged
|| read_sectors
|| write_sectors
|| read_ticks
|| write_ticks
)
4924 snprintf(lbuf
, 256, "%u %u %s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
4925 major
, minor
, dev_name
, read
, read_merged
, read_sectors
, read_ticks
,
4926 write
, write_merged
, write_sectors
, write_ticks
, ios_pgr
, tot_ticks
, rq_ticks
);
4930 l
= snprintf(cache
, cache_size
, "%s", lbuf
);
4932 perror("Error writing to fuse buf");
4936 if (l
>= cache_size
) {
4937 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4947 d
->size
= total_len
;
4948 if (total_len
> size
) total_len
= size
;
4949 memcpy(buf
, d
->buf
, total_len
);
4957 free(io_serviced_str
);
4958 free(io_merged_str
);
4959 free(io_service_bytes_str
);
4960 free(io_wait_time_str
);
4961 free(io_service_time_str
);
4965 static int proc_swaps_read(char *buf
, size_t size
, off_t offset
,
4966 struct fuse_file_info
*fi
)
4968 struct fuse_context
*fc
= fuse_get_context();
4969 struct file_info
*d
= (struct file_info
*)fi
->fh
;
4971 char *memswlimit_str
= NULL
, *memlimit_str
= NULL
, *memusage_str
= NULL
, *memswusage_str
= NULL
;
4972 unsigned long memswlimit
= 0, memlimit
= 0, memusage
= 0, memswusage
= 0, swap_total
= 0, swap_free
= 0;
4973 ssize_t total_len
= 0, rv
= 0;
4975 char *cache
= d
->buf
;
4978 if (offset
> d
->size
)
4982 int left
= d
->size
- offset
;
4983 total_len
= left
> size
? size
: left
;
4984 memcpy(buf
, cache
+ offset
, total_len
);
4988 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
4991 cg
= get_pid_cgroup(initpid
, "memory");
4993 return read_file("/proc/swaps", buf
, size
, d
);
4994 prune_init_slice(cg
);
4996 memlimit
= get_min_memlimit(cg
, "memory.limit_in_bytes");
4998 if (!cgfs_get_value("memory", cg
, "memory.usage_in_bytes", &memusage_str
))
5001 memusage
= strtoul(memusage_str
, NULL
, 10);
5003 if (cgfs_get_value("memory", cg
, "memory.memsw.usage_in_bytes", &memswusage_str
) &&
5004 cgfs_get_value("memory", cg
, "memory.memsw.limit_in_bytes", &memswlimit_str
)) {
5006 memswlimit
= get_min_memlimit(cg
, "memory.memsw.limit_in_bytes");
5007 memswusage
= strtoul(memswusage_str
, NULL
, 10);
5009 swap_total
= (memswlimit
- memlimit
) / 1024;
5010 swap_free
= (memswusage
- memusage
) / 1024;
5013 total_len
= snprintf(d
->buf
, d
->size
, "Filename\t\t\t\tType\t\tSize\tUsed\tPriority\n");
5015 /* When no mem + swap limit is specified or swapaccount=0*/
5019 FILE *f
= fopen("/proc/meminfo", "r");
5024 while (getline(&line
, &linelen
, f
) != -1) {
5025 if (startswith(line
, "SwapTotal:")) {
5026 sscanf(line
, "SwapTotal: %8lu kB", &swap_total
);
5027 } else if (startswith(line
, "SwapFree:")) {
5028 sscanf(line
, "SwapFree: %8lu kB", &swap_free
);
5036 if (swap_total
> 0) {
5037 l
= snprintf(d
->buf
+ total_len
, d
->size
- total_len
,
5038 "none%*svirtual\t\t%lu\t%lu\t0\n", 36, " ",
5039 swap_total
, swap_free
);
5043 if (total_len
< 0 || l
< 0) {
5044 perror("Error writing to cache");
5050 d
->size
= (int)total_len
;
5052 if (total_len
> size
) total_len
= size
;
5053 memcpy(buf
, d
->buf
, total_len
);
5058 free(memswlimit_str
);
5061 free(memswusage_str
);
5065 * Find the process pid from cgroup path.
5066 * eg:from /sys/fs/cgroup/cpu/docker/containerid/cgroup.procs to find the process pid.
5067 * @pid_buf : put pid to pid_buf.
5068 * @dpath : the path of cgroup. eg: /docker/containerid or /docker/containerid/child-cgroup ...
5069 * @depth : the depth of cgroup in container.
5070 * @sum : return the number of pid.
5071 * @cfd : the file descriptor of the mounted cgroup. eg: /sys/fs/cgroup/cpu
5073 static int calc_pid(char ***pid_buf
, char *dpath
, int depth
, int sum
, int cfd
)
5077 struct dirent
*file
;
5082 char *path_dir
, *path
;
5085 /* path = dpath + "/cgroup.procs" + /0 */
5087 path
= malloc(strlen(dpath
) + 20);
5090 strcpy(path
, dpath
);
5091 fd
= openat(cfd
, path
, O_RDONLY
);
5095 dir
= fdopendir(fd
);
5101 while (((file
= readdir(dir
)) != NULL
) && depth
> 0) {
5102 if (strncmp(file
->d_name
, ".", 1) == 0)
5104 if (strncmp(file
->d_name
, "..", 1) == 0)
5106 if (file
->d_type
== DT_DIR
) {
5107 /* path + '/' + d_name +/0 */
5109 path_dir
= malloc(strlen(path
) + 2 + sizeof(file
->d_name
));
5110 } while (!path_dir
);
5111 strcpy(path_dir
, path
);
5112 strcat(path_dir
, "/");
5113 strcat(path_dir
, file
->d_name
);
5115 sum
= calc_pid(pid_buf
, path_dir
, pd
, sum
, cfd
);
5121 strcat(path
, "/cgroup.procs");
5122 fd
= openat(cfd
, path
, O_RDONLY
);
5126 f
= fdopen(fd
, "r");
5132 while (getline(&line
, &linelen
, f
) != -1) {
5134 pid
= realloc(*pid_buf
, sizeof(char *) * (sum
+ 1));
5138 *(*pid_buf
+ sum
) = malloc(strlen(line
) + 1);
5139 } while (*(*pid_buf
+ sum
) == NULL
);
5140 strcpy(*(*pid_buf
+ sum
), line
);
5151 * calc_load calculates the load according to the following formula:
5152 * load1 = load0 * exp + active * (1 - exp)
5154 * @load1: the new loadavg.
5155 * @load0: the former loadavg.
5156 * @active: the total number of running pid at this moment.
5157 * @exp: the fixed-point defined in the beginning.
5159 static unsigned long
5160 calc_load(unsigned long load
, unsigned long exp
, unsigned long active
)
5162 unsigned long newload
;
5164 active
= active
> 0 ? active
* FIXED_1
: 0;
5165 newload
= load
* exp
+ active
* (FIXED_1
- exp
);
5167 newload
+= FIXED_1
- 1;
5169 return newload
/ FIXED_1
;
5173 * Return 0 means that container p->cg is closed.
5174 * Return -1 means that error occurred in refresh.
5175 * Positive num equals the total number of pid.
5177 static int refresh_load(struct load_node
*p
, char *path
)
5181 char proc_path
[256];
5182 int i
, ret
, run_pid
= 0, total_pid
= 0, last_pid
= 0;
5187 struct dirent
*file
;
5190 idbuf
= malloc(sizeof(char *));
5192 sum
= calc_pid(&idbuf
, path
, DEPTH_DIR
, 0, p
->cfd
);
5197 for (i
= 0; i
< sum
; i
++) {
5199 length
= strlen(idbuf
[i
])-1;
5200 idbuf
[i
][length
] = '\0';
5201 ret
= snprintf(proc_path
, 256, "/proc/%s/task", idbuf
[i
]);
5202 if (ret
< 0 || ret
> 255) {
5203 lxcfs_error("%s\n", "snprintf() failed in refresh_load.");
5209 dp
= opendir(proc_path
);
5211 lxcfs_error("%s\n", "Open proc_path failed in refresh_load.");
5214 while ((file
= readdir(dp
)) != NULL
) {
5215 if (strncmp(file
->d_name
, ".", 1) == 0)
5217 if (strncmp(file
->d_name
, "..", 1) == 0)
5220 /* We make the biggest pid become last_pid.*/
5221 ret
= atof(file
->d_name
);
5222 last_pid
= (ret
> last_pid
) ? ret
: last_pid
;
5224 ret
= snprintf(proc_path
, 256, "/proc/%s/task/%s/status", idbuf
[i
], file
->d_name
);
5225 if (ret
< 0 || ret
> 255) {
5226 lxcfs_error("%s\n", "snprintf() failed in refresh_load.");
5232 f
= fopen(proc_path
, "r");
5234 while (getline(&line
, &linelen
, f
) != -1) {
5236 if ((line
[0] == 'S') && (line
[1] == 't'))
5239 if ((line
[7] == 'R') || (line
[7] == 'D'))
5246 /*Calculate the loadavg.*/
5247 p
->avenrun
[0] = calc_load(p
->avenrun
[0], EXP_1
, run_pid
);
5248 p
->avenrun
[1] = calc_load(p
->avenrun
[1], EXP_5
, run_pid
);
5249 p
->avenrun
[2] = calc_load(p
->avenrun
[2], EXP_15
, run_pid
);
5250 p
->run_pid
= run_pid
;
5251 p
->total_pid
= total_pid
;
5252 p
->last_pid
= last_pid
;
5263 * Traverse the hash table and update it.
5265 void *load_begin(void *arg
)
5269 int i
, sum
, length
, ret
;
5270 struct load_node
*f
;
5272 clock_t time1
, time2
;
5275 if (loadavg_stop
== 1)
5279 for (i
= 0; i
< LOAD_SIZE
; i
++) {
5280 pthread_mutex_lock(&load_hash
[i
].lock
);
5281 if (load_hash
[i
].next
== NULL
) {
5282 pthread_mutex_unlock(&load_hash
[i
].lock
);
5285 f
= load_hash
[i
].next
;
5288 length
= strlen(f
->cg
) + 2;
5290 /* strlen(f->cg) + '.' or '' + \0 */
5291 path
= malloc(length
);
5294 ret
= snprintf(path
, length
, "%s%s", *(f
->cg
) == '/' ? "." : "", f
->cg
);
5295 if (ret
< 0 || ret
> length
- 1) {
5296 /* snprintf failed, ignore the node.*/
5297 lxcfs_error("Refresh node %s failed for snprintf().\n", f
->cg
);
5300 sum
= refresh_load(f
, path
);
5307 /* load_hash[i].lock locks only on the first node.*/
5308 if (first_node
== 1) {
5310 pthread_mutex_unlock(&load_hash
[i
].lock
);
5315 if (loadavg_stop
== 1)
5319 usleep(FLUSH_TIME
* 1000000 - (int)((time2
- time1
) * 1000000 / CLOCKS_PER_SEC
));
5323 static int proc_loadavg_read(char *buf
, size_t size
, off_t offset
,
5324 struct fuse_file_info
*fi
)
5326 struct fuse_context
*fc
= fuse_get_context();
5327 struct file_info
*d
= (struct file_info
*)fi
->fh
;
5330 size_t total_len
= 0;
5331 char *cache
= d
->buf
;
5332 struct load_node
*n
;
5335 unsigned long a
, b
, c
;
5338 if (offset
> d
->size
)
5342 int left
= d
->size
- offset
;
5343 total_len
= left
> size
? size
: left
;
5344 memcpy(buf
, cache
+ offset
, total_len
);
5348 return read_file("/proc/loadavg", buf
, size
, d
);
5350 initpid
= lookup_initpid_in_store(fc
->pid
);
5353 cg
= get_pid_cgroup(initpid
, "cpu");
5355 return read_file("/proc/loadavg", buf
, size
, d
);
5357 prune_init_slice(cg
);
5358 hash
= calc_hash(cg
) % LOAD_SIZE
;
5359 n
= locate_node(cg
, hash
);
5363 if (!find_mounted_controller("cpu", &cfd
)) {
5365 * In locate_node() above, pthread_rwlock_unlock() isn't used
5366 * because delete is not allowed before read has ended.
5368 pthread_rwlock_unlock(&load_hash
[hash
].rdlock
);
5373 n
= malloc(sizeof(struct load_node
));
5377 n
->cg
= malloc(strlen(cg
)+1);
5385 n
->last_pid
= initpid
;
5387 insert_node(&n
, hash
);
5389 a
= n
->avenrun
[0] + (FIXED_1
/200);
5390 b
= n
->avenrun
[1] + (FIXED_1
/200);
5391 c
= n
->avenrun
[2] + (FIXED_1
/200);
5392 total_len
= snprintf(d
->buf
, d
->buflen
, "%lu.%02lu %lu.%02lu %lu.%02lu %d/%d %d\n",
5393 LOAD_INT(a
), LOAD_FRAC(a
),
5394 LOAD_INT(b
), LOAD_FRAC(b
),
5395 LOAD_INT(c
), LOAD_FRAC(c
),
5396 n
->run_pid
, n
->total_pid
, n
->last_pid
);
5397 pthread_rwlock_unlock(&load_hash
[hash
].rdlock
);
5398 if (total_len
< 0 || total_len
>= d
->buflen
) {
5399 lxcfs_error("%s\n", "Failed to write to cache");
5403 d
->size
= (int)total_len
;
5406 if (total_len
> size
)
5408 memcpy(buf
, d
->buf
, total_len
);
5415 /* Return a positive number on success, return 0 on failure.*/
5416 pthread_t
load_daemon(int load_use
)
5423 lxcfs_error("%s\n", "Initialize hash_table fails in load_daemon!");
5426 ret
= pthread_create(&pid
, NULL
, load_begin
, NULL
);
5428 lxcfs_error("%s\n", "Create pthread fails in load_daemon!");
5432 /* use loadavg, here loadavg = 1*/
5437 /* Returns 0 on success. */
5438 int stop_load_daemon(pthread_t pid
)
5442 /* Signal the thread to gracefully stop */
5445 s
= pthread_join(pid
, NULL
); /* Make sure sub thread has been canceled. */
5447 lxcfs_error("%s\n", "stop_load_daemon error: failed to join");
5457 static off_t
get_procfile_size(const char *which
)
5459 FILE *f
= fopen(which
, "r");
5462 ssize_t sz
, answer
= 0;
5466 while ((sz
= getline(&line
, &len
, f
)) != -1)
5474 int proc_getattr(const char *path
, struct stat
*sb
)
5476 struct timespec now
;
5478 memset(sb
, 0, sizeof(struct stat
));
5479 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
5481 sb
->st_uid
= sb
->st_gid
= 0;
5482 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
5483 if (strcmp(path
, "/proc") == 0) {
5484 sb
->st_mode
= S_IFDIR
| 00555;
5488 if (strcmp(path
, "/proc/meminfo") == 0 ||
5489 strcmp(path
, "/proc/cpuinfo") == 0 ||
5490 strcmp(path
, "/proc/uptime") == 0 ||
5491 strcmp(path
, "/proc/stat") == 0 ||
5492 strcmp(path
, "/proc/diskstats") == 0 ||
5493 strcmp(path
, "/proc/swaps") == 0 ||
5494 strcmp(path
, "/proc/loadavg") == 0) {
5496 sb
->st_mode
= S_IFREG
| 00444;
5504 int proc_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
5505 struct fuse_file_info
*fi
)
5507 if (filler(buf
, ".", NULL
, 0) != 0 ||
5508 filler(buf
, "..", NULL
, 0) != 0 ||
5509 filler(buf
, "cpuinfo", NULL
, 0) != 0 ||
5510 filler(buf
, "meminfo", NULL
, 0) != 0 ||
5511 filler(buf
, "stat", NULL
, 0) != 0 ||
5512 filler(buf
, "uptime", NULL
, 0) != 0 ||
5513 filler(buf
, "diskstats", NULL
, 0) != 0 ||
5514 filler(buf
, "swaps", NULL
, 0) != 0 ||
5515 filler(buf
, "loadavg", NULL
, 0) != 0)
5520 int proc_open(const char *path
, struct fuse_file_info
*fi
)
5523 struct file_info
*info
;
5525 if (strcmp(path
, "/proc/meminfo") == 0)
5526 type
= LXC_TYPE_PROC_MEMINFO
;
5527 else if (strcmp(path
, "/proc/cpuinfo") == 0)
5528 type
= LXC_TYPE_PROC_CPUINFO
;
5529 else if (strcmp(path
, "/proc/uptime") == 0)
5530 type
= LXC_TYPE_PROC_UPTIME
;
5531 else if (strcmp(path
, "/proc/stat") == 0)
5532 type
= LXC_TYPE_PROC_STAT
;
5533 else if (strcmp(path
, "/proc/diskstats") == 0)
5534 type
= LXC_TYPE_PROC_DISKSTATS
;
5535 else if (strcmp(path
, "/proc/swaps") == 0)
5536 type
= LXC_TYPE_PROC_SWAPS
;
5537 else if (strcmp(path
, "/proc/loadavg") == 0)
5538 type
= LXC_TYPE_PROC_LOADAVG
;
5542 info
= malloc(sizeof(*info
));
5546 memset(info
, 0, sizeof(*info
));
5549 info
->buflen
= get_procfile_size(path
) + BUF_RESERVE_SIZE
;
5551 info
->buf
= malloc(info
->buflen
);
5552 } while (!info
->buf
);
5553 memset(info
->buf
, 0, info
->buflen
);
5554 /* set actual size to buffer size */
5555 info
->size
= info
->buflen
;
5557 fi
->fh
= (unsigned long)info
;
5561 int proc_access(const char *path
, int mask
)
5563 if (strcmp(path
, "/proc") == 0 && access(path
, R_OK
) == 0)
5566 /* these are all read-only */
5567 if ((mask
& ~R_OK
) != 0)
5572 int proc_release(const char *path
, struct fuse_file_info
*fi
)
5574 do_release_file_info(fi
);
5578 int proc_read(const char *path
, char *buf
, size_t size
, off_t offset
,
5579 struct fuse_file_info
*fi
)
5581 struct file_info
*f
= (struct file_info
*) fi
->fh
;
5584 case LXC_TYPE_PROC_MEMINFO
:
5585 return proc_meminfo_read(buf
, size
, offset
, fi
);
5586 case LXC_TYPE_PROC_CPUINFO
:
5587 return proc_cpuinfo_read(buf
, size
, offset
, fi
);
5588 case LXC_TYPE_PROC_UPTIME
:
5589 return proc_uptime_read(buf
, size
, offset
, fi
);
5590 case LXC_TYPE_PROC_STAT
:
5591 return proc_stat_read(buf
, size
, offset
, fi
);
5592 case LXC_TYPE_PROC_DISKSTATS
:
5593 return proc_diskstats_read(buf
, size
, offset
, fi
);
5594 case LXC_TYPE_PROC_SWAPS
:
5595 return proc_swaps_read(buf
, size
, offset
, fi
);
5596 case LXC_TYPE_PROC_LOADAVG
:
5597 return proc_loadavg_read(buf
, size
, offset
, fi
);
5604 * Functions needed to setup cgroups in the __constructor__.
5607 static bool mkdir_p(const char *dir
, mode_t mode
)
5609 const char *tmp
= dir
;
5610 const char *orig
= dir
;
5614 dir
= tmp
+ strspn(tmp
, "/");
5615 tmp
= dir
+ strcspn(dir
, "/");
5616 makeme
= strndup(orig
, dir
- orig
);
5619 if (mkdir(makeme
, mode
) && errno
!= EEXIST
) {
5620 lxcfs_error("Failed to create directory '%s': %s.\n",
5621 makeme
, strerror(errno
));
5626 } while(tmp
!= dir
);
5631 static bool umount_if_mounted(void)
5633 if (umount2(BASEDIR
, MNT_DETACH
) < 0 && errno
!= EINVAL
) {
5634 lxcfs_error("Failed to unmount %s: %s.\n", BASEDIR
, strerror(errno
));
5640 /* __typeof__ should be safe to use with all compilers. */
5641 typedef __typeof__(((struct statfs
*)NULL
)->f_type
) fs_type_magic
;
5642 static bool has_fs_type(const struct statfs
*fs
, fs_type_magic magic_val
)
5644 return (fs
->f_type
== (fs_type_magic
)magic_val
);
5648 * looking at fs/proc_namespace.c, it appears we can
5649 * actually expect the rootfs entry to very specifically contain
5650 * " - rootfs rootfs "
5651 * IIUC, so long as we've chrooted so that rootfs is not our root,
5652 * the rootfs entry should always be skipped in mountinfo contents.
5654 static bool is_on_ramfs(void)
5662 f
= fopen("/proc/self/mountinfo", "r");
5666 while (getline(&line
, &len
, f
) != -1) {
5667 for (p
= line
, i
= 0; p
&& i
< 4; i
++)
5668 p
= strchr(p
+ 1, ' ');
5671 p2
= strchr(p
+ 1, ' ');
5675 if (strcmp(p
+ 1, "/") == 0) {
5676 // this is '/'. is it the ramfs?
5677 p
= strchr(p2
+ 1, '-');
5678 if (p
&& strncmp(p
, "- rootfs rootfs ", 16) == 0) {
5690 static int pivot_enter()
5692 int ret
= -1, oldroot
= -1, newroot
= -1;
5694 oldroot
= open("/", O_DIRECTORY
| O_RDONLY
);
5696 lxcfs_error("%s\n", "Failed to open old root for fchdir.");
5700 newroot
= open(ROOTDIR
, O_DIRECTORY
| O_RDONLY
);
5702 lxcfs_error("%s\n", "Failed to open new root for fchdir.");
5706 /* change into new root fs */
5707 if (fchdir(newroot
) < 0) {
5708 lxcfs_error("Failed to change directory to new rootfs: %s.\n", ROOTDIR
);
5712 /* pivot_root into our new root fs */
5713 if (pivot_root(".", ".") < 0) {
5714 lxcfs_error("pivot_root() syscall failed: %s.\n", strerror(errno
));
5719 * At this point the old-root is mounted on top of our new-root.
5720 * To unmounted it we must not be chdir'd into it, so escape back
5723 if (fchdir(oldroot
) < 0) {
5724 lxcfs_error("%s\n", "Failed to enter old root.");
5728 if (umount2(".", MNT_DETACH
) < 0) {
5729 lxcfs_error("%s\n", "Failed to detach old root.");
5733 if (fchdir(newroot
) < 0) {
5734 lxcfs_error("%s\n", "Failed to re-enter new root.");
5749 static int chroot_enter()
5751 if (mount(ROOTDIR
, "/", NULL
, MS_REC
| MS_BIND
, NULL
)) {
5752 lxcfs_error("Failed to recursively bind-mount %s into /.", ROOTDIR
);
5756 if (chroot(".") < 0) {
5757 lxcfs_error("Call to chroot() failed: %s.\n", strerror(errno
));
5761 if (chdir("/") < 0) {
5762 lxcfs_error("Failed to change directory: %s.\n", strerror(errno
));
5769 static int permute_and_enter(void)
5773 if (statfs("/", &sb
) < 0) {
5774 lxcfs_error("%s\n", "Could not stat / mountpoint.");
5778 /* has_fs_type() is not reliable. When the ramfs is a tmpfs it will
5779 * likely report TMPFS_MAGIC. Hence, when it reports no we still check
5780 * /proc/1/mountinfo. */
5781 if (has_fs_type(&sb
, RAMFS_MAGIC
) || is_on_ramfs())
5782 return chroot_enter();
5784 if (pivot_enter() < 0) {
5785 lxcfs_error("%s\n", "Could not perform pivot root.");
5792 /* Prepare our new clean root. */
5793 static int permute_prepare(void)
5795 if (mkdir(ROOTDIR
, 0700) < 0 && errno
!= EEXIST
) {
5796 lxcfs_error("%s\n", "Failed to create directory for new root.");
5800 if (mount("/", ROOTDIR
, NULL
, MS_BIND
, 0) < 0) {
5801 lxcfs_error("Failed to bind-mount / for new root: %s.\n", strerror(errno
));
5805 if (mount(RUNTIME_PATH
, ROOTDIR RUNTIME_PATH
, NULL
, MS_BIND
, 0) < 0) {
5806 lxcfs_error("Failed to bind-mount /run into new root: %s.\n", strerror(errno
));
5810 if (mount(BASEDIR
, ROOTDIR BASEDIR
, NULL
, MS_REC
| MS_MOVE
, 0) < 0) {
5811 printf("Failed to move " BASEDIR
" into new root: %s.\n", strerror(errno
));
5818 /* Calls chroot() on ramfs, pivot_root() in all other cases. */
5819 static bool permute_root(void)
5821 /* Prepare new root. */
5822 if (permute_prepare() < 0)
5825 /* Pivot into new root. */
5826 if (permute_and_enter() < 0)
5832 static int preserve_mnt_ns(int pid
)
5835 size_t len
= sizeof("/proc/") + 21 + sizeof("/ns/mnt");
5838 ret
= snprintf(path
, len
, "/proc/%d/ns/mnt", pid
);
5839 if (ret
< 0 || (size_t)ret
>= len
)
5842 return open(path
, O_RDONLY
| O_CLOEXEC
);
5845 static bool cgfs_prepare_mounts(void)
5847 if (!mkdir_p(BASEDIR
, 0700)) {
5848 lxcfs_error("%s\n", "Failed to create lxcfs cgroup mountpoint.");
5852 if (!umount_if_mounted()) {
5853 lxcfs_error("%s\n", "Failed to clean up old lxcfs cgroup mountpoint.");
5857 if (unshare(CLONE_NEWNS
) < 0) {
5858 lxcfs_error("Failed to unshare mount namespace: %s.\n", strerror(errno
));
5862 cgroup_mount_ns_fd
= preserve_mnt_ns(getpid());
5863 if (cgroup_mount_ns_fd
< 0) {
5864 lxcfs_error("Failed to preserve mount namespace: %s.\n", strerror(errno
));
5868 if (mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, 0) < 0) {
5869 lxcfs_error("Failed to remount / private: %s.\n", strerror(errno
));
5873 if (mount("tmpfs", BASEDIR
, "tmpfs", 0, "size=100000,mode=700") < 0) {
5874 lxcfs_error("%s\n", "Failed to mount tmpfs over lxcfs cgroup mountpoint.");
5881 static bool cgfs_mount_hierarchies(void)
5887 for (i
= 0; i
< num_hierarchies
; i
++) {
5888 char *controller
= hierarchies
[i
];
5890 clen
= strlen(controller
);
5891 len
= strlen(BASEDIR
) + clen
+ 2;
5892 target
= malloc(len
);
5896 ret
= snprintf(target
, len
, "%s/%s", BASEDIR
, controller
);
5897 if (ret
< 0 || ret
>= len
) {
5901 if (mkdir(target
, 0755) < 0 && errno
!= EEXIST
) {
5905 if (!strcmp(controller
, "unified"))
5906 ret
= mount("none", target
, "cgroup2", 0, NULL
);
5908 ret
= mount(controller
, target
, "cgroup", 0, controller
);
5910 lxcfs_error("Failed mounting cgroup %s: %s\n", controller
, strerror(errno
));
5915 fd_hierarchies
[i
] = open(target
, O_DIRECTORY
);
5916 if (fd_hierarchies
[i
] < 0) {
5925 static bool cgfs_setup_controllers(void)
5927 if (!cgfs_prepare_mounts())
5930 if (!cgfs_mount_hierarchies()) {
5931 lxcfs_error("%s\n", "Failed to set up private lxcfs cgroup mounts.");
5935 if (!permute_root())
5941 static void __attribute__((constructor
)) collect_and_mount_subsystems(void)
5944 char *cret
, *line
= NULL
;
5945 char cwd
[MAXPATHLEN
];
5947 int i
, init_ns
= -1;
5948 bool found_unified
= false;
5950 if ((f
= fopen("/proc/self/cgroup", "r")) == NULL
) {
5951 lxcfs_error("Error opening /proc/self/cgroup: %s\n", strerror(errno
));
5955 while (getline(&line
, &len
, f
) != -1) {
5958 p
= strchr(line
, ':');
5964 p2
= strrchr(p
, ':');
5969 /* With cgroupv2 /proc/self/cgroup can contain entries of the
5970 * form: 0::/ This will cause lxcfs to fail the cgroup mounts
5971 * because it parses out the empty string "" and later on passes
5972 * it to mount(). Let's skip such entries.
5974 if (!strcmp(p
, "") && !strcmp(idx
, "0") && !found_unified
) {
5975 found_unified
= true;
5979 if (!store_hierarchy(line
, p
))
5983 /* Preserve initial namespace. */
5984 init_ns
= preserve_mnt_ns(getpid());
5986 lxcfs_error("%s\n", "Failed to preserve initial mount namespace.");
5990 fd_hierarchies
= malloc(sizeof(int) * num_hierarchies
);
5991 if (!fd_hierarchies
) {
5992 lxcfs_error("%s\n", strerror(errno
));
5996 for (i
= 0; i
< num_hierarchies
; i
++)
5997 fd_hierarchies
[i
] = -1;
5999 cret
= getcwd(cwd
, MAXPATHLEN
);
6001 lxcfs_debug("Could not retrieve current working directory: %s.\n", strerror(errno
));
6003 /* This function calls unshare(CLONE_NEWNS) our initial mount namespace
6004 * to privately mount lxcfs cgroups. */
6005 if (!cgfs_setup_controllers()) {
6006 lxcfs_error("%s\n", "Failed to setup private cgroup mounts for lxcfs.");
6010 if (setns(init_ns
, 0) < 0) {
6011 lxcfs_error("Failed to switch back to initial mount namespace: %s.\n", strerror(errno
));
6015 if (!cret
|| chdir(cwd
) < 0)
6016 lxcfs_debug("Could not change back to original working directory: %s.\n", strerror(errno
));
6018 if (!init_cpuview()) {
6019 lxcfs_error("%s\n", "failed to init CPU view");
6032 static void __attribute__((destructor
)) free_subsystems(void)
6036 lxcfs_debug("%s\n", "Running destructor for liblxcfs.");
6038 for (i
= 0; i
< num_hierarchies
; i
++) {
6040 free(hierarchies
[i
]);
6041 if (fd_hierarchies
&& fd_hierarchies
[i
] >= 0)
6042 close(fd_hierarchies
[i
]);
6045 free(fd_hierarchies
);
6048 if (cgroup_mount_ns_fd
>= 0)
6049 close(cgroup_mount_ns_fd
);