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
{
90 /* The function of hash table.*/
91 #define LOAD_SIZE 100 /*the size of hash_table */
92 #define FLUSH_TIME 5 /*the flush rate */
93 #define DEPTH_DIR 3 /*the depth of per cgroup */
94 /* The function of calculate loadavg .*/
95 #define FSHIFT 11 /* nr of bits of precision */
96 #define FIXED_1 (1<<FSHIFT) /* 1.0 as fixed-point */
97 #define EXP_1 1884 /* 1/exp(5sec/1min) as fixed-point */
98 #define EXP_5 2014 /* 1/exp(5sec/5min) */
99 #define EXP_15 2037 /* 1/exp(5sec/15min) */
100 #define LOAD_INT(x) ((x) >> FSHIFT)
101 #define LOAD_FRAC(x) LOAD_INT(((x) & (FIXED_1-1)) * 100)
103 * This parameter is used for proc_loadavg_read().
104 * 1 means use loadavg, 0 means not use.
106 static int loadavg
= 0;
107 static volatile sig_atomic_t loadavg_stop
= 0;
108 static int calc_hash(const char *name
)
110 unsigned int hash
= 0;
112 /* ELFHash algorithm. */
114 hash
= (hash
<< 4) + *name
++;
115 x
= hash
& 0xf0000000;
120 return (hash
& 0x7fffffff);
125 unsigned long avenrun
[3]; /* Load averages */
126 unsigned int run_pid
;
127 unsigned int total_pid
;
128 unsigned int last_pid
;
129 int cfd
; /* The file descriptor of the mounted cgroup */
130 struct load_node
*next
;
131 struct load_node
**pre
;
136 * The lock is about insert load_node and refresh load_node.To the first
137 * load_node of each hash bucket, insert and refresh in this hash bucket is
138 * mutually exclusive.
140 pthread_mutex_t lock
;
142 * The rdlock is about read loadavg and delete load_node.To each hash
143 * bucket, read and delete is mutually exclusive. But at the same time, we
144 * allow paratactic read operation. This rdlock is at list level.
146 pthread_rwlock_t rdlock
;
148 * The rilock is about read loadavg and insert load_node.To the first
149 * load_node of each hash bucket, read and insert is mutually exclusive.
150 * But at the same time, we allow paratactic read operation.
152 pthread_rwlock_t rilock
;
153 struct load_node
*next
;
156 static struct load_head load_hash
[LOAD_SIZE
]; /* hash table */
158 * init_load initialize the hash table.
159 * Return 0 on success, return -1 on failure.
161 static int init_load(void)
166 for (i
= 0; i
< LOAD_SIZE
; i
++) {
167 load_hash
[i
].next
= NULL
;
168 ret
= pthread_mutex_init(&load_hash
[i
].lock
, NULL
);
170 lxcfs_error("%s\n", "Failed to initialize lock");
173 ret
= pthread_rwlock_init(&load_hash
[i
].rdlock
, NULL
);
175 lxcfs_error("%s\n", "Failed to initialize rdlock");
178 ret
= pthread_rwlock_init(&load_hash
[i
].rilock
, NULL
);
180 lxcfs_error("%s\n", "Failed to initialize rilock");
186 pthread_rwlock_destroy(&load_hash
[i
].rdlock
);
188 pthread_mutex_destroy(&load_hash
[i
].lock
);
192 pthread_mutex_destroy(&load_hash
[i
].lock
);
193 pthread_rwlock_destroy(&load_hash
[i
].rdlock
);
194 pthread_rwlock_destroy(&load_hash
[i
].rilock
);
199 static void insert_node(struct load_node
**n
, int locate
)
203 pthread_mutex_lock(&load_hash
[locate
].lock
);
204 pthread_rwlock_wrlock(&load_hash
[locate
].rilock
);
205 f
= load_hash
[locate
].next
;
206 load_hash
[locate
].next
= *n
;
208 (*n
)->pre
= &(load_hash
[locate
].next
);
210 f
->pre
= &((*n
)->next
);
212 pthread_mutex_unlock(&load_hash
[locate
].lock
);
213 pthread_rwlock_unlock(&load_hash
[locate
].rilock
);
216 * locate_node() finds special node. Not return NULL means success.
217 * It should be noted that rdlock isn't unlocked at the end of code
218 * because this function is used to read special node. Delete is not
219 * allowed before read has ended.
220 * unlock rdlock only in proc_loadavg_read().
222 static struct load_node
*locate_node(char *cg
, int locate
)
224 struct load_node
*f
= NULL
;
227 pthread_rwlock_rdlock(&load_hash
[locate
].rilock
);
228 pthread_rwlock_rdlock(&load_hash
[locate
].rdlock
);
229 if (load_hash
[locate
].next
== NULL
) {
230 pthread_rwlock_unlock(&load_hash
[locate
].rilock
);
233 f
= load_hash
[locate
].next
;
234 pthread_rwlock_unlock(&load_hash
[locate
].rilock
);
235 while (f
&& ((i
= strcmp(f
->cg
, cg
)) != 0))
239 /* Delete the load_node n and return the next node of it. */
240 static struct load_node
*del_node(struct load_node
*n
, int locate
)
244 pthread_rwlock_wrlock(&load_hash
[locate
].rdlock
);
245 if (n
->next
== NULL
) {
249 n
->next
->pre
= n
->pre
;
254 pthread_rwlock_unlock(&load_hash
[locate
].rdlock
);
258 static void load_free(void)
261 struct load_node
*f
, *p
;
263 for (i
= 0; i
< LOAD_SIZE
; i
++) {
264 pthread_mutex_lock(&load_hash
[i
].lock
);
265 pthread_rwlock_wrlock(&load_hash
[i
].rilock
);
266 pthread_rwlock_wrlock(&load_hash
[i
].rdlock
);
267 if (load_hash
[i
].next
== NULL
) {
268 pthread_mutex_unlock(&load_hash
[i
].lock
);
269 pthread_mutex_destroy(&load_hash
[i
].lock
);
270 pthread_rwlock_unlock(&load_hash
[i
].rilock
);
271 pthread_rwlock_destroy(&load_hash
[i
].rilock
);
272 pthread_rwlock_unlock(&load_hash
[i
].rdlock
);
273 pthread_rwlock_destroy(&load_hash
[i
].rdlock
);
276 for (f
= load_hash
[i
].next
; f
; ) {
282 pthread_mutex_unlock(&load_hash
[i
].lock
);
283 pthread_mutex_destroy(&load_hash
[i
].lock
);
284 pthread_rwlock_unlock(&load_hash
[i
].rilock
);
285 pthread_rwlock_destroy(&load_hash
[i
].rilock
);
286 pthread_rwlock_unlock(&load_hash
[i
].rdlock
);
287 pthread_rwlock_destroy(&load_hash
[i
].rdlock
);
291 /* Data for CPU view */
292 struct cg_proc_stat
{
294 struct cpuacct_usage
*usage
; // Real usage as read from the host's /proc/stat
295 struct cpuacct_usage
*view
; // Usage stats reported to the container
297 pthread_mutex_t lock
; // For node manipulation
298 struct cg_proc_stat
*next
;
301 struct cg_proc_stat_head
{
302 struct cg_proc_stat
*next
;
306 * For access to the list. Reading can be parallel, pruning is exclusive.
308 pthread_rwlock_t lock
;
311 #define CPUVIEW_HASH_SIZE 100
312 static struct cg_proc_stat_head
*proc_stat_history
[CPUVIEW_HASH_SIZE
];
314 static bool cpuview_init_head(struct cg_proc_stat_head
**head
)
316 *head
= malloc(sizeof(struct cg_proc_stat_head
));
318 lxcfs_error("%s\n", strerror(errno
));
322 (*head
)->lastcheck
= time(NULL
);
323 (*head
)->next
= NULL
;
325 if (pthread_rwlock_init(&(*head
)->lock
, NULL
) != 0) {
326 lxcfs_error("%s\n", "Failed to initialize list lock");
334 static bool init_cpuview()
338 for (i
= 0; i
< CPUVIEW_HASH_SIZE
; i
++)
339 proc_stat_history
[i
] = NULL
;
341 for (i
= 0; i
< CPUVIEW_HASH_SIZE
; i
++) {
342 if (!cpuview_init_head(&proc_stat_history
[i
]))
349 for (i
= 0; i
< CPUVIEW_HASH_SIZE
; i
++) {
350 if (proc_stat_history
[i
]) {
351 free(proc_stat_history
[i
]);
352 proc_stat_history
[i
] = NULL
;
359 static void free_proc_stat_node(struct cg_proc_stat
*node
)
361 pthread_mutex_destroy(&node
->lock
);
368 static void cpuview_free_head(struct cg_proc_stat_head
*head
)
370 struct cg_proc_stat
*node
, *tmp
;
378 free_proc_stat_node(tmp
);
385 pthread_rwlock_destroy(&head
->lock
);
389 static void free_cpuview()
393 for (i
= 0; i
< CPUVIEW_HASH_SIZE
; i
++) {
394 if (proc_stat_history
[i
])
395 cpuview_free_head(proc_stat_history
[i
]);
399 /* Reserve buffer size to account for file size changes. */
400 #define BUF_RESERVE_SIZE 512
403 * A table caching which pid is init for a pid namespace.
404 * When looking up which pid is init for $qpid, we first
405 * 1. Stat /proc/$qpid/ns/pid.
406 * 2. Check whether the ino_t is in our store.
407 * a. if not, fork a child in qpid's ns to send us
408 * ucred.pid = 1, and read the initpid. Cache
409 * initpid and creation time for /proc/initpid
410 * in a new store entry.
411 * b. if so, verify that /proc/initpid still matches
412 * what we have saved. If not, clear the store
413 * entry and go back to a. If so, return the
416 struct pidns_init_store
{
417 ino_t ino
; // inode number for /proc/$pid/ns/pid
418 pid_t initpid
; // the pid of nit in that ns
419 long int ctime
; // the time at which /proc/$initpid was created
420 struct pidns_init_store
*next
;
424 /* lol - look at how they are allocated in the kernel */
425 #define PIDNS_HASH_SIZE 4096
426 #define HASH(x) ((x) % PIDNS_HASH_SIZE)
428 static struct pidns_init_store
*pidns_hash_table
[PIDNS_HASH_SIZE
];
429 static pthread_mutex_t pidns_store_mutex
= PTHREAD_MUTEX_INITIALIZER
;
430 static void lock_mutex(pthread_mutex_t
*l
)
434 if ((ret
= pthread_mutex_lock(l
)) != 0) {
435 lxcfs_error("returned:%d %s\n", ret
, strerror(ret
));
440 /* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
441 * Number of hierarchies mounted. */
442 static int num_hierarchies
;
444 /* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
445 * Hierachies mounted {cpuset, blkio, ...}:
446 * Initialized via __constructor__ collect_and_mount_subsystems(). */
447 static char **hierarchies
;
449 /* READ-ONLY after __constructor__ collect_and_mount_subsystems() has run.
450 * Open file descriptors:
451 * @fd_hierarchies[i] refers to cgroup @hierarchies[i]. They are mounted in a
452 * private mount namespace.
453 * Initialized via __constructor__ collect_and_mount_subsystems().
454 * @fd_hierarchies[i] can be used to perform file operations on the cgroup
455 * mounts and respective files in the private namespace even when located in
456 * another namespace using the *at() family of functions
457 * {openat(), fchownat(), ...}. */
458 static int *fd_hierarchies
;
459 static int cgroup_mount_ns_fd
= -1;
461 static void unlock_mutex(pthread_mutex_t
*l
)
465 if ((ret
= pthread_mutex_unlock(l
)) != 0) {
466 lxcfs_error("returned:%d %s\n", ret
, strerror(ret
));
471 static void store_lock(void)
473 lock_mutex(&pidns_store_mutex
);
476 static void store_unlock(void)
478 unlock_mutex(&pidns_store_mutex
);
481 /* Must be called under store_lock */
482 static bool initpid_still_valid(struct pidns_init_store
*e
, struct stat
*nsfdsb
)
487 snprintf(fnam
, 100, "/proc/%d", e
->initpid
);
488 if (stat(fnam
, &initsb
) < 0)
491 lxcfs_debug("Comparing ctime %ld == %ld for pid %d.\n", e
->ctime
,
492 initsb
.st_ctime
, e
->initpid
);
494 if (e
->ctime
!= initsb
.st_ctime
)
499 /* Must be called under store_lock */
500 static void remove_initpid(struct pidns_init_store
*e
)
502 struct pidns_init_store
*tmp
;
505 lxcfs_debug("Remove_initpid: removing entry for %d.\n", e
->initpid
);
508 if (pidns_hash_table
[h
] == e
) {
509 pidns_hash_table
[h
] = e
->next
;
514 tmp
= pidns_hash_table
[h
];
516 if (tmp
->next
== e
) {
526 /* Must be called under store_lock */
527 static void prune_initpid_store(void)
529 static long int last_prune
= 0;
530 struct pidns_init_store
*e
, *prev
, *delme
;
531 long int now
, threshold
;
535 last_prune
= time(NULL
);
539 if (now
< last_prune
+ PURGE_SECS
)
542 lxcfs_debug("%s\n", "Pruning.");
545 threshold
= now
- 2 * PURGE_SECS
;
547 for (i
= 0; i
< PIDNS_HASH_SIZE
; i
++) {
548 for (prev
= NULL
, e
= pidns_hash_table
[i
]; e
; ) {
549 if (e
->lastcheck
< threshold
) {
551 lxcfs_debug("Removing cached entry for %d.\n", e
->initpid
);
555 prev
->next
= e
->next
;
557 pidns_hash_table
[i
] = e
->next
;
568 /* Must be called under store_lock */
569 static void save_initpid(struct stat
*sb
, pid_t pid
)
571 struct pidns_init_store
*e
;
576 lxcfs_debug("Save_initpid: adding entry for %d.\n", pid
);
578 snprintf(fpath
, 100, "/proc/%d", pid
);
579 if (stat(fpath
, &procsb
) < 0)
582 e
= malloc(sizeof(*e
));
586 e
->ctime
= procsb
.st_ctime
;
588 e
->next
= pidns_hash_table
[h
];
589 e
->lastcheck
= time(NULL
);
590 pidns_hash_table
[h
] = e
;
594 * Given the stat(2) info for a nsfd pid inode, lookup the init_pid_store
595 * entry for the inode number and creation time. Verify that the init pid
596 * is still valid. If not, remove it. Return the entry if valid, NULL
598 * Must be called under store_lock
600 static struct pidns_init_store
*lookup_verify_initpid(struct stat
*sb
)
602 int h
= HASH(sb
->st_ino
);
603 struct pidns_init_store
*e
= pidns_hash_table
[h
];
606 if (e
->ino
== sb
->st_ino
) {
607 if (initpid_still_valid(e
, sb
)) {
608 e
->lastcheck
= time(NULL
);
620 static int is_dir(const char *path
, int fd
)
623 int ret
= fstatat(fd
, path
, &statbuf
, fd
);
624 if (ret
== 0 && S_ISDIR(statbuf
.st_mode
))
629 static char *must_copy_string(const char *str
)
641 static inline void drop_trailing_newlines(char *s
)
645 for (l
=strlen(s
); l
>0 && s
[l
-1] == '\n'; l
--)
649 #define BATCH_SIZE 50
650 static void dorealloc(char **mem
, size_t oldlen
, size_t newlen
)
652 int newbatches
= (newlen
/ BATCH_SIZE
) + 1;
653 int oldbatches
= (oldlen
/ BATCH_SIZE
) + 1;
655 if (!*mem
|| newbatches
> oldbatches
) {
658 tmp
= realloc(*mem
, newbatches
* BATCH_SIZE
);
663 static void append_line(char **contents
, size_t *len
, char *line
, ssize_t linelen
)
665 size_t newlen
= *len
+ linelen
;
666 dorealloc(contents
, *len
, newlen
+ 1);
667 memcpy(*contents
+ *len
, line
, linelen
+1);
671 static char *slurp_file(const char *from
, int fd
)
674 char *contents
= NULL
;
675 FILE *f
= fdopen(fd
, "r");
676 size_t len
= 0, fulllen
= 0;
682 while ((linelen
= getline(&line
, &len
, f
)) != -1) {
683 append_line(&contents
, &fulllen
, line
, linelen
);
688 drop_trailing_newlines(contents
);
693 static bool write_string(const char *fnam
, const char *string
, int fd
)
702 len
= strlen(string
);
703 ret
= fwrite(string
, 1, len
, f
);
705 lxcfs_error("%s - Error writing \"%s\" to \"%s\"\n",
706 strerror(errno
), string
, fnam
);
712 lxcfs_error("%s - Failed to close \"%s\"\n", strerror(errno
), fnam
);
726 static bool store_hierarchy(char *stridx
, char *h
)
728 if (num_hierarchies
% ALLOC_NUM
== 0) {
729 size_t n
= (num_hierarchies
/ ALLOC_NUM
) + 1;
731 char **tmp
= realloc(hierarchies
, n
* sizeof(char *));
733 lxcfs_error("%s\n", strerror(errno
));
739 hierarchies
[num_hierarchies
++] = must_copy_string(h
);
743 static void print_subsystems(void)
747 fprintf(stderr
, "mount namespace: %d\n", cgroup_mount_ns_fd
);
748 fprintf(stderr
, "hierarchies:\n");
749 for (i
= 0; i
< num_hierarchies
; i
++) {
751 fprintf(stderr
, " %2d: fd: %3d: %s\n", i
,
752 fd_hierarchies
[i
], hierarchies
[i
]);
756 static bool in_comma_list(const char *needle
, const char *haystack
)
758 const char *s
= haystack
, *e
;
759 size_t nlen
= strlen(needle
);
761 while (*s
&& (e
= strchr(s
, ','))) {
766 if (strncmp(needle
, s
, nlen
) == 0)
770 if (strcmp(needle
, s
) == 0)
775 /* do we need to do any massaging here? I'm not sure... */
776 /* Return the mounted controller and store the corresponding open file descriptor
777 * referring to the controller mountpoint in the private lxcfs namespace in
780 static char *find_mounted_controller(const char *controller
, int *cfd
)
784 for (i
= 0; i
< num_hierarchies
; i
++) {
787 if (strcmp(hierarchies
[i
], controller
) == 0) {
788 *cfd
= fd_hierarchies
[i
];
789 return hierarchies
[i
];
791 if (in_comma_list(controller
, hierarchies
[i
])) {
792 *cfd
= fd_hierarchies
[i
];
793 return hierarchies
[i
];
800 bool cgfs_set_value(const char *controller
, const char *cgroup
, const char *file
,
807 tmpc
= find_mounted_controller(controller
, &cfd
);
811 /* Make sure we pass a relative path to *at() family of functions.
812 * . + /cgroup + / + file + \0
814 len
= strlen(cgroup
) + strlen(file
) + 3;
816 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, file
);
817 if (ret
< 0 || (size_t)ret
>= len
)
820 fd
= openat(cfd
, fnam
, O_WRONLY
);
824 return write_string(fnam
, value
, fd
);
827 // Chown all the files in the cgroup directory. We do this when we create
828 // a cgroup on behalf of a user.
829 static void chown_all_cgroup_files(const char *dirname
, uid_t uid
, gid_t gid
, int fd
)
831 struct dirent
*direntp
;
832 char path
[MAXPATHLEN
];
837 len
= strlen(dirname
);
838 if (len
>= MAXPATHLEN
) {
839 lxcfs_error("Pathname too long: %s\n", dirname
);
843 fd1
= openat(fd
, dirname
, O_DIRECTORY
);
849 lxcfs_error("Failed to open %s\n", dirname
);
853 while ((direntp
= readdir(d
))) {
854 if (!strcmp(direntp
->d_name
, ".") || !strcmp(direntp
->d_name
, ".."))
856 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
857 if (ret
< 0 || ret
>= MAXPATHLEN
) {
858 lxcfs_error("Pathname too long under %s\n", dirname
);
861 if (fchownat(fd
, path
, uid
, gid
, 0) < 0)
862 lxcfs_error("Failed to chown file %s to %u:%u", path
, uid
, gid
);
867 int cgfs_create(const char *controller
, const char *cg
, uid_t uid
, gid_t gid
)
873 tmpc
= find_mounted_controller(controller
, &cfd
);
877 /* Make sure we pass a relative path to *at() family of functions.
880 len
= strlen(cg
) + 2;
881 dirnam
= alloca(len
);
882 snprintf(dirnam
, len
, "%s%s", *cg
== '/' ? "." : "", cg
);
884 if (mkdirat(cfd
, dirnam
, 0755) < 0)
887 if (uid
== 0 && gid
== 0)
890 if (fchownat(cfd
, dirnam
, uid
, gid
, 0) < 0)
893 chown_all_cgroup_files(dirnam
, uid
, gid
, cfd
);
898 static bool recursive_rmdir(const char *dirname
, int fd
, const int cfd
)
900 struct dirent
*direntp
;
903 char pathname
[MAXPATHLEN
];
906 dupfd
= dup(fd
); // fdopendir() does bad things once it uses an fd.
910 dir
= fdopendir(dupfd
);
912 lxcfs_debug("Failed to open %s: %s.\n", dirname
, strerror(errno
));
917 while ((direntp
= readdir(dir
))) {
921 if (!strcmp(direntp
->d_name
, ".") ||
922 !strcmp(direntp
->d_name
, ".."))
925 rc
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
926 if (rc
< 0 || rc
>= MAXPATHLEN
) {
927 lxcfs_error("%s\n", "Pathname too long.");
931 rc
= fstatat(cfd
, pathname
, &mystat
, AT_SYMLINK_NOFOLLOW
);
933 lxcfs_debug("Failed to stat %s: %s.\n", pathname
, strerror(errno
));
936 if (S_ISDIR(mystat
.st_mode
))
937 if (!recursive_rmdir(pathname
, fd
, cfd
))
938 lxcfs_debug("Error removing %s.\n", pathname
);
942 if (closedir(dir
) < 0) {
943 lxcfs_error("Failed to close directory %s: %s\n", dirname
, strerror(errno
));
947 if (unlinkat(cfd
, dirname
, AT_REMOVEDIR
) < 0) {
948 lxcfs_debug("Failed to delete %s: %s.\n", dirname
, strerror(errno
));
957 bool cgfs_remove(const char *controller
, const char *cg
)
964 tmpc
= find_mounted_controller(controller
, &cfd
);
968 /* Make sure we pass a relative path to *at() family of functions.
971 len
= strlen(cg
) + 2;
972 dirnam
= alloca(len
);
973 snprintf(dirnam
, len
, "%s%s", *cg
== '/' ? "." : "", cg
);
975 fd
= openat(cfd
, dirnam
, O_DIRECTORY
);
979 bret
= recursive_rmdir(dirnam
, fd
, cfd
);
984 bool cgfs_chmod_file(const char *controller
, const char *file
, mode_t mode
)
988 char *pathname
, *tmpc
;
990 tmpc
= find_mounted_controller(controller
, &cfd
);
994 /* Make sure we pass a relative path to *at() family of functions.
997 len
= strlen(file
) + 2;
998 pathname
= alloca(len
);
999 snprintf(pathname
, len
, "%s%s", *file
== '/' ? "." : "", file
);
1000 if (fchmodat(cfd
, pathname
, mode
, 0) < 0)
1005 static int chown_tasks_files(const char *dirname
, uid_t uid
, gid_t gid
, int fd
)
1010 len
= strlen(dirname
) + strlen("/cgroup.procs") + 1;
1011 fname
= alloca(len
);
1012 snprintf(fname
, len
, "%s/tasks", dirname
);
1013 if (fchownat(fd
, fname
, uid
, gid
, 0) != 0)
1015 snprintf(fname
, len
, "%s/cgroup.procs", dirname
);
1016 if (fchownat(fd
, fname
, uid
, gid
, 0) != 0)
1021 int cgfs_chown_file(const char *controller
, const char *file
, uid_t uid
, gid_t gid
)
1025 char *pathname
, *tmpc
;
1027 tmpc
= find_mounted_controller(controller
, &cfd
);
1031 /* Make sure we pass a relative path to *at() family of functions.
1034 len
= strlen(file
) + 2;
1035 pathname
= alloca(len
);
1036 snprintf(pathname
, len
, "%s%s", *file
== '/' ? "." : "", file
);
1037 if (fchownat(cfd
, pathname
, uid
, gid
, 0) < 0)
1040 if (is_dir(pathname
, cfd
))
1041 // like cgmanager did, we want to chown the tasks file as well
1042 return chown_tasks_files(pathname
, uid
, gid
, cfd
);
1047 FILE *open_pids_file(const char *controller
, const char *cgroup
)
1051 char *pathname
, *tmpc
;
1053 tmpc
= find_mounted_controller(controller
, &cfd
);
1057 /* Make sure we pass a relative path to *at() family of functions.
1058 * . + /cgroup + / "cgroup.procs" + \0
1060 len
= strlen(cgroup
) + strlen("cgroup.procs") + 3;
1061 pathname
= alloca(len
);
1062 snprintf(pathname
, len
, "%s%s/cgroup.procs", *cgroup
== '/' ? "." : "", cgroup
);
1064 fd
= openat(cfd
, pathname
, O_WRONLY
);
1068 return fdopen(fd
, "w");
1071 static bool cgfs_iterate_cgroup(const char *controller
, const char *cgroup
, bool directories
,
1072 void ***list
, size_t typesize
,
1073 void* (*iterator
)(const char*, const char*, const char*))
1078 char pathname
[MAXPATHLEN
];
1079 size_t sz
= 0, asz
= 0;
1080 struct dirent
*dirent
;
1083 tmpc
= find_mounted_controller(controller
, &cfd
);
1088 /* Make sure we pass a relative path to *at() family of functions. */
1089 len
= strlen(cgroup
) + 1 /* . */ + 1 /* \0 */;
1091 ret
= snprintf(cg
, len
, "%s%s", *cgroup
== '/' ? "." : "", cgroup
);
1092 if (ret
< 0 || (size_t)ret
>= len
) {
1093 lxcfs_error("Pathname too long under %s\n", cgroup
);
1097 fd
= openat(cfd
, cg
, O_DIRECTORY
);
1101 dir
= fdopendir(fd
);
1105 while ((dirent
= readdir(dir
))) {
1108 if (!strcmp(dirent
->d_name
, ".") ||
1109 !strcmp(dirent
->d_name
, ".."))
1112 ret
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", cg
, dirent
->d_name
);
1113 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1114 lxcfs_error("Pathname too long under %s\n", cg
);
1118 ret
= fstatat(cfd
, pathname
, &mystat
, AT_SYMLINK_NOFOLLOW
);
1120 lxcfs_error("Failed to stat %s: %s\n", pathname
, strerror(errno
));
1123 if ((!directories
&& !S_ISREG(mystat
.st_mode
)) ||
1124 (directories
&& !S_ISDIR(mystat
.st_mode
)))
1131 tmp
= realloc(*list
, asz
* typesize
);
1135 (*list
)[sz
] = (*iterator
)(controller
, cg
, dirent
->d_name
);
1136 (*list
)[sz
+1] = NULL
;
1139 if (closedir(dir
) < 0) {
1140 lxcfs_error("Failed closedir for %s: %s\n", cgroup
, strerror(errno
));
1146 static void *make_children_list_entry(const char *controller
, const char *cgroup
, const char *dir_entry
)
1150 dup
= strdup(dir_entry
);
1155 bool cgfs_list_children(const char *controller
, const char *cgroup
, char ***list
)
1157 return cgfs_iterate_cgroup(controller
, cgroup
, true, (void***)list
, sizeof(*list
), &make_children_list_entry
);
1160 void free_key(struct cgfs_files
*k
)
1168 void free_keys(struct cgfs_files
**keys
)
1174 for (i
= 0; keys
[i
]; i
++) {
1180 bool cgfs_get_value(const char *controller
, const char *cgroup
, const char *file
, char **value
)
1186 tmpc
= find_mounted_controller(controller
, &cfd
);
1190 /* Make sure we pass a relative path to *at() family of functions.
1191 * . + /cgroup + / + file + \0
1193 len
= strlen(cgroup
) + strlen(file
) + 3;
1195 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, file
);
1196 if (ret
< 0 || (size_t)ret
>= len
)
1199 fd
= openat(cfd
, fnam
, O_RDONLY
);
1203 *value
= slurp_file(fnam
, fd
);
1204 return *value
!= NULL
;
1207 bool cgfs_param_exist(const char *controller
, const char *cgroup
, const char *file
)
1213 tmpc
= find_mounted_controller(controller
, &cfd
);
1217 /* Make sure we pass a relative path to *at() family of functions.
1218 * . + /cgroup + / + file + \0
1220 len
= strlen(cgroup
) + strlen(file
) + 3;
1222 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, file
);
1223 if (ret
< 0 || (size_t)ret
>= len
)
1226 return (faccessat(cfd
, fnam
, F_OK
, 0) == 0);
1229 struct cgfs_files
*cgfs_get_key(const char *controller
, const char *cgroup
, const char *file
)
1235 struct cgfs_files
*newkey
;
1237 tmpc
= find_mounted_controller(controller
, &cfd
);
1241 if (file
&& *file
== '/')
1244 if (file
&& strchr(file
, '/'))
1247 /* Make sure we pass a relative path to *at() family of functions.
1248 * . + /cgroup + / + file + \0
1250 len
= strlen(cgroup
) + 3;
1252 len
+= strlen(file
) + 1;
1254 snprintf(fnam
, len
, "%s%s%s%s", *cgroup
== '/' ? "." : "", cgroup
,
1255 file
? "/" : "", file
? file
: "");
1257 ret
= fstatat(cfd
, fnam
, &sb
, 0);
1262 newkey
= malloc(sizeof(struct cgfs_files
));
1265 newkey
->name
= must_copy_string(file
);
1266 else if (strrchr(cgroup
, '/'))
1267 newkey
->name
= must_copy_string(strrchr(cgroup
, '/'));
1269 newkey
->name
= must_copy_string(cgroup
);
1270 newkey
->uid
= sb
.st_uid
;
1271 newkey
->gid
= sb
.st_gid
;
1272 newkey
->mode
= sb
.st_mode
;
1277 static void *make_key_list_entry(const char *controller
, const char *cgroup
, const char *dir_entry
)
1279 struct cgfs_files
*entry
= cgfs_get_key(controller
, cgroup
, dir_entry
);
1281 lxcfs_error("Error getting files under %s:%s\n", controller
,
1287 bool cgfs_list_keys(const char *controller
, const char *cgroup
, struct cgfs_files
***keys
)
1289 return cgfs_iterate_cgroup(controller
, cgroup
, false, (void***)keys
, sizeof(*keys
), &make_key_list_entry
);
1292 bool is_child_cgroup(const char *controller
, const char *cgroup
, const char *f
)
1300 tmpc
= find_mounted_controller(controller
, &cfd
);
1304 /* Make sure we pass a relative path to *at() family of functions.
1305 * . + /cgroup + / + f + \0
1307 len
= strlen(cgroup
) + strlen(f
) + 3;
1309 ret
= snprintf(fnam
, len
, "%s%s/%s", *cgroup
== '/' ? "." : "", cgroup
, f
);
1310 if (ret
< 0 || (size_t)ret
>= len
)
1313 ret
= fstatat(cfd
, fnam
, &sb
, 0);
1314 if (ret
< 0 || !S_ISDIR(sb
.st_mode
))
1320 #define SEND_CREDS_OK 0
1321 #define SEND_CREDS_NOTSK 1
1322 #define SEND_CREDS_FAIL 2
1323 static bool recv_creds(int sock
, struct ucred
*cred
, char *v
);
1324 static int wait_for_pid(pid_t pid
);
1325 static int send_creds(int sock
, struct ucred
*cred
, char v
, bool pingfirst
);
1326 static int send_creds_clone_wrapper(void *arg
);
1329 * clone a task which switches to @task's namespace and writes '1'.
1330 * over a unix sock so we can read the task's reaper's pid in our
1333 * Note: glibc's fork() does not respect pidns, which can lead to failed
1334 * assertions inside glibc (and thus failed forks) if the child's pid in
1335 * the pidns and the parent pid outside are identical. Using clone prevents
1338 static void write_task_init_pid_exit(int sock
, pid_t target
)
1343 size_t stack_size
= sysconf(_SC_PAGESIZE
);
1344 void *stack
= alloca(stack_size
);
1346 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", (int)target
);
1347 if (ret
< 0 || ret
>= sizeof(fnam
))
1350 fd
= open(fnam
, O_RDONLY
);
1352 perror("write_task_init_pid_exit open of ns/pid");
1356 perror("write_task_init_pid_exit setns 1");
1360 pid
= clone(send_creds_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &sock
);
1364 if (!wait_for_pid(pid
))
1370 static int send_creds_clone_wrapper(void *arg
) {
1373 int sock
= *(int *)arg
;
1375 /* we are the child */
1380 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
)
1385 static pid_t
get_init_pid_for_task(pid_t task
)
1393 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
1394 perror("socketpair");
1403 write_task_init_pid_exit(sock
[0], task
);
1407 if (!recv_creds(sock
[1], &cred
, &v
))
1419 static pid_t
lookup_initpid_in_store(pid_t qpid
)
1423 struct pidns_init_store
*e
;
1426 snprintf(fnam
, 100, "/proc/%d/ns/pid", qpid
);
1428 if (stat(fnam
, &sb
) < 0)
1430 e
= lookup_verify_initpid(&sb
);
1432 answer
= e
->initpid
;
1435 answer
= get_init_pid_for_task(qpid
);
1437 save_initpid(&sb
, answer
);
1440 /* we prune at end in case we are returning
1441 * the value we were about to return */
1442 prune_initpid_store();
1447 static int wait_for_pid(pid_t pid
)
1455 ret
= waitpid(pid
, &status
, 0);
1463 if (!WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
1470 * append pid to *src.
1471 * src: a pointer to a char* in which ot append the pid.
1472 * sz: the number of characters printed so far, minus trailing \0.
1473 * asz: the allocated size so far
1474 * pid: the pid to append
1476 static void must_strcat_pid(char **src
, size_t *sz
, size_t *asz
, pid_t pid
)
1480 int tmplen
= sprintf(tmp
, "%d\n", (int)pid
);
1482 if (!*src
|| tmplen
+ *sz
+ 1 >= *asz
) {
1485 tmp
= realloc(*src
, *asz
+ BUF_RESERVE_SIZE
);
1488 *asz
+= BUF_RESERVE_SIZE
;
1490 memcpy((*src
) +*sz
, tmp
, tmplen
+1); /* include the \0 */
1495 * Given a open file * to /proc/pid/{u,g}id_map, and an id
1496 * valid in the caller's namespace, return the id mapped into
1498 * Returns the mapped id, or -1 on error.
1501 convert_id_to_ns(FILE *idfile
, unsigned int in_id
)
1503 unsigned int nsuid
, // base id for a range in the idfile's namespace
1504 hostuid
, // base id for a range in the caller's namespace
1505 count
; // number of ids in this range
1509 fseek(idfile
, 0L, SEEK_SET
);
1510 while (fgets(line
, 400, idfile
)) {
1511 ret
= sscanf(line
, "%u %u %u\n", &nsuid
, &hostuid
, &count
);
1514 if (hostuid
+ count
< hostuid
|| nsuid
+ count
< nsuid
) {
1516 * uids wrapped around - unexpected as this is a procfile,
1519 lxcfs_error("pid wrapparound at entry %u %u %u in %s\n",
1520 nsuid
, hostuid
, count
, line
);
1523 if (hostuid
<= in_id
&& hostuid
+count
> in_id
) {
1525 * now since hostuid <= in_id < hostuid+count, and
1526 * hostuid+count and nsuid+count do not wrap around,
1527 * we know that nsuid+(in_id-hostuid) which must be
1528 * less that nsuid+(count) must not wrap around
1530 return (in_id
- hostuid
) + nsuid
;
1539 * for is_privileged_over,
1540 * specify whether we require the calling uid to be root in his
1543 #define NS_ROOT_REQD true
1544 #define NS_ROOT_OPT false
1548 static bool is_privileged_over(pid_t pid
, uid_t uid
, uid_t victim
, bool req_ns_root
)
1550 char fpath
[PROCLEN
];
1552 bool answer
= false;
1555 if (victim
== -1 || uid
== -1)
1559 * If the request is one not requiring root in the namespace,
1560 * then having the same uid suffices. (i.e. uid 1000 has write
1561 * access to files owned by uid 1000
1563 if (!req_ns_root
&& uid
== victim
)
1566 ret
= snprintf(fpath
, PROCLEN
, "/proc/%d/uid_map", pid
);
1567 if (ret
< 0 || ret
>= PROCLEN
)
1569 FILE *f
= fopen(fpath
, "r");
1573 /* if caller's not root in his namespace, reject */
1574 nsuid
= convert_id_to_ns(f
, uid
);
1579 * If victim is not mapped into caller's ns, reject.
1580 * XXX I'm not sure this check is needed given that fuse
1581 * will be sending requests where the vfs has converted
1583 nsuid
= convert_id_to_ns(f
, victim
);
1594 static bool perms_include(int fmode
, mode_t req_mode
)
1598 switch (req_mode
& O_ACCMODE
) {
1606 r
= S_IROTH
| S_IWOTH
;
1611 return ((fmode
& r
) == r
);
1617 * querycg is /a/b/c/d/e
1620 static char *get_next_cgroup_dir(const char *taskcg
, const char *querycg
)
1624 if (strlen(taskcg
) <= strlen(querycg
)) {
1625 lxcfs_error("%s\n", "I was fed bad input.");
1629 if ((strcmp(querycg
, "/") == 0) || (strcmp(querycg
, "./") == 0))
1630 start
= strdup(taskcg
+ 1);
1632 start
= strdup(taskcg
+ strlen(querycg
) + 1);
1635 end
= strchr(start
, '/');
1641 static void stripnewline(char *x
)
1643 size_t l
= strlen(x
);
1644 if (l
&& x
[l
-1] == '\n')
1648 static char *get_pid_cgroup(pid_t pid
, const char *contrl
)
1653 char *answer
= NULL
;
1657 const char *h
= find_mounted_controller(contrl
, &cfd
);
1661 ret
= snprintf(fnam
, PROCLEN
, "/proc/%d/cgroup", pid
);
1662 if (ret
< 0 || ret
>= PROCLEN
)
1664 if (!(f
= fopen(fnam
, "r")))
1667 while (getline(&line
, &len
, f
) != -1) {
1671 c1
= strchr(line
, ':');
1675 c2
= strchr(c1
, ':');
1679 if (strcmp(c1
, h
) != 0)
1684 answer
= strdup(c2
);
1696 * check whether a fuse context may access a cgroup dir or file
1698 * If file is not null, it is a cgroup file to check under cg.
1699 * If file is null, then we are checking perms on cg itself.
1701 * For files we can check the mode of the list_keys result.
1702 * For cgroups, we must make assumptions based on the files under the
1703 * cgroup, because cgmanager doesn't tell us ownership/perms of cgroups
1706 static bool fc_may_access(struct fuse_context
*fc
, const char *contrl
, const char *cg
, const char *file
, mode_t mode
)
1708 struct cgfs_files
*k
= NULL
;
1711 k
= cgfs_get_key(contrl
, cg
, file
);
1715 if (is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
1716 if (perms_include(k
->mode
>> 6, mode
)) {
1721 if (fc
->gid
== k
->gid
) {
1722 if (perms_include(k
->mode
>> 3, mode
)) {
1727 ret
= perms_include(k
->mode
, mode
);
1734 #define INITSCOPE "/init.scope"
1735 static void prune_init_slice(char *cg
)
1738 size_t cg_len
= strlen(cg
), initscope_len
= strlen(INITSCOPE
);
1740 if (cg_len
< initscope_len
)
1743 point
= cg
+ cg_len
- initscope_len
;
1744 if (strcmp(point
, INITSCOPE
) == 0) {
1753 * If pid is in /a/b/c/d, he may only act on things under cg=/a/b/c/d.
1754 * If pid is in /a, he may act on /a/b, but not on /b.
1755 * if the answer is false and nextcg is not NULL, then *nextcg will point
1756 * to a string containing the next cgroup directory under cg, which must be
1757 * freed by the caller.
1759 static bool caller_is_in_ancestor(pid_t pid
, const char *contrl
, const char *cg
, char **nextcg
)
1761 bool answer
= false;
1762 char *c2
= get_pid_cgroup(pid
, contrl
);
1767 prune_init_slice(c2
);
1770 * callers pass in '/' or './' (openat()) for root cgroup, otherwise
1771 * they pass in a cgroup without leading '/'
1773 * The original line here was:
1774 * linecmp = *cg == '/' ? c2 : c2+1;
1775 * TODO: I'm not sure why you'd want to increment when *cg != '/'?
1776 * Serge, do you know?
1778 if (*cg
== '/' || !strncmp(cg
, "./", 2))
1782 if (strncmp(linecmp
, cg
, strlen(linecmp
)) != 0) {
1784 *nextcg
= get_next_cgroup_dir(linecmp
, cg
);
1796 * If pid is in /a/b/c, he may see that /a exists, but not /b or /a/c.
1798 static bool caller_may_see_dir(pid_t pid
, const char *contrl
, const char *cg
)
1800 bool answer
= false;
1802 size_t target_len
, task_len
;
1804 if (strcmp(cg
, "/") == 0 || strcmp(cg
, "./") == 0)
1807 c2
= get_pid_cgroup(pid
, contrl
);
1810 prune_init_slice(c2
);
1813 target_len
= strlen(cg
);
1814 task_len
= strlen(task_cg
);
1815 if (task_len
== 0) {
1816 /* Task is in the root cg, it can see everything. This case is
1817 * not handled by the strmcps below, since they test for the
1818 * last /, but that is the first / that we've chopped off
1824 if (strcmp(cg
, task_cg
) == 0) {
1828 if (target_len
< task_len
) {
1829 /* looking up a parent dir */
1830 if (strncmp(task_cg
, cg
, target_len
) == 0 && task_cg
[target_len
] == '/')
1834 if (target_len
> task_len
) {
1835 /* looking up a child dir */
1836 if (strncmp(task_cg
, cg
, task_len
) == 0 && cg
[task_len
] == '/')
1847 * given /cgroup/freezer/a/b, return "freezer".
1848 * the returned char* should NOT be freed.
1850 static char *pick_controller_from_path(struct fuse_context
*fc
, const char *path
)
1853 char *contr
, *slash
;
1855 if (strlen(path
) < 9) {
1859 if (*(path
+ 7) != '/') {
1864 contr
= strdupa(p1
);
1869 slash
= strstr(contr
, "/");
1874 for (i
= 0; i
< num_hierarchies
; i
++) {
1875 if (hierarchies
[i
] && strcmp(hierarchies
[i
], contr
) == 0)
1876 return hierarchies
[i
];
1883 * Find the start of cgroup in /cgroup/controller/the/cgroup/path
1884 * Note that the returned value may include files (keynames) etc
1886 static const char *find_cgroup_in_path(const char *path
)
1890 if (strlen(path
) < 9) {
1894 p1
= strstr(path
+ 8, "/");
1904 * split the last path element from the path in @cg.
1905 * @dir is newly allocated and should be freed, @last not
1907 static void get_cgdir_and_path(const char *cg
, char **dir
, char **last
)
1914 *last
= strrchr(cg
, '/');
1919 p
= strrchr(*dir
, '/');
1924 * FUSE ops for /cgroup
1927 int cg_getattr(const char *path
, struct stat
*sb
)
1929 struct timespec now
;
1930 struct fuse_context
*fc
= fuse_get_context();
1931 char * cgdir
= NULL
;
1932 char *last
= NULL
, *path1
, *path2
;
1933 struct cgfs_files
*k
= NULL
;
1935 const char *controller
= NULL
;
1942 memset(sb
, 0, sizeof(struct stat
));
1944 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
1947 sb
->st_uid
= sb
->st_gid
= 0;
1948 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
1951 if (strcmp(path
, "/cgroup") == 0) {
1952 sb
->st_mode
= S_IFDIR
| 00755;
1957 controller
= pick_controller_from_path(fc
, path
);
1960 cgroup
= find_cgroup_in_path(path
);
1962 /* this is just /cgroup/controller, return it as a dir */
1963 sb
->st_mode
= S_IFDIR
| 00755;
1968 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
1978 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1981 /* check that cgcopy is either a child cgroup of cgdir, or listed in its keys.
1982 * Then check that caller's cgroup is under path if last is a child
1983 * cgroup, or cgdir if last is a file */
1985 if (is_child_cgroup(controller
, path1
, path2
)) {
1986 if (!caller_may_see_dir(initpid
, controller
, cgroup
)) {
1990 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, NULL
)) {
1991 /* this is just /cgroup/controller, return it as a dir */
1992 sb
->st_mode
= S_IFDIR
| 00555;
1997 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
)) {
2002 // get uid, gid, from '/tasks' file and make up a mode
2003 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
2004 sb
->st_mode
= S_IFDIR
| 00755;
2005 k
= cgfs_get_key(controller
, cgroup
, NULL
);
2007 sb
->st_uid
= sb
->st_gid
= 0;
2009 sb
->st_uid
= k
->uid
;
2010 sb
->st_gid
= k
->gid
;
2018 if ((k
= cgfs_get_key(controller
, path1
, path2
)) != NULL
) {
2019 sb
->st_mode
= S_IFREG
| k
->mode
;
2021 sb
->st_uid
= k
->uid
;
2022 sb
->st_gid
= k
->gid
;
2025 if (!caller_is_in_ancestor(initpid
, controller
, path1
, NULL
)) {
2037 int cg_opendir(const char *path
, struct fuse_file_info
*fi
)
2039 struct fuse_context
*fc
= fuse_get_context();
2041 struct file_info
*dir_info
;
2042 char *controller
= NULL
;
2047 if (strcmp(path
, "/cgroup") == 0) {
2051 // return list of keys for the controller, and list of child cgroups
2052 controller
= pick_controller_from_path(fc
, path
);
2056 cgroup
= find_cgroup_in_path(path
);
2058 /* this is just /cgroup/controller, return its contents */
2063 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2067 if (!caller_may_see_dir(initpid
, controller
, cgroup
))
2069 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
))
2073 /* we'll free this at cg_releasedir */
2074 dir_info
= malloc(sizeof(*dir_info
));
2077 dir_info
->controller
= must_copy_string(controller
);
2078 dir_info
->cgroup
= must_copy_string(cgroup
);
2079 dir_info
->type
= LXC_TYPE_CGDIR
;
2080 dir_info
->buf
= NULL
;
2081 dir_info
->file
= NULL
;
2082 dir_info
->buflen
= 0;
2084 fi
->fh
= (unsigned long)dir_info
;
2088 int cg_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
2089 struct fuse_file_info
*fi
)
2091 struct file_info
*d
= (struct file_info
*)fi
->fh
;
2092 struct cgfs_files
**list
= NULL
;
2094 char *nextcg
= NULL
;
2095 struct fuse_context
*fc
= fuse_get_context();
2096 char **clist
= NULL
;
2098 if (filler(buf
, ".", NULL
, 0) != 0 || filler(buf
, "..", NULL
, 0) != 0)
2101 if (d
->type
!= LXC_TYPE_CGDIR
) {
2102 lxcfs_error("%s\n", "Internal error: file cache info used in readdir.");
2105 if (!d
->cgroup
&& !d
->controller
) {
2106 // ls /var/lib/lxcfs/cgroup - just show list of controllers
2109 for (i
= 0; i
< num_hierarchies
; i
++) {
2110 if (hierarchies
[i
] && filler(buf
, hierarchies
[i
], NULL
, 0) != 0) {
2117 if (!cgfs_list_keys(d
->controller
, d
->cgroup
, &list
)) {
2118 // not a valid cgroup
2123 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2126 if (!caller_is_in_ancestor(initpid
, d
->controller
, d
->cgroup
, &nextcg
)) {
2128 ret
= filler(buf
, nextcg
, NULL
, 0);
2139 for (i
= 0; list
&& list
[i
]; i
++) {
2140 if (filler(buf
, list
[i
]->name
, NULL
, 0) != 0) {
2146 // now get the list of child cgroups
2148 if (!cgfs_list_children(d
->controller
, d
->cgroup
, &clist
)) {
2153 for (i
= 0; clist
[i
]; i
++) {
2154 if (filler(buf
, clist
[i
], NULL
, 0) != 0) {
2165 for (i
= 0; clist
[i
]; i
++)
2172 static void do_release_file_info(struct fuse_file_info
*fi
)
2174 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2181 free(f
->controller
);
2182 f
->controller
= NULL
;
2193 int cg_releasedir(const char *path
, struct fuse_file_info
*fi
)
2195 do_release_file_info(fi
);
2199 int cg_open(const char *path
, struct fuse_file_info
*fi
)
2202 char *last
= NULL
, *path1
, *path2
, * cgdir
= NULL
, *controller
;
2203 struct cgfs_files
*k
= NULL
;
2204 struct file_info
*file_info
;
2205 struct fuse_context
*fc
= fuse_get_context();
2211 controller
= pick_controller_from_path(fc
, path
);
2214 cgroup
= find_cgroup_in_path(path
);
2218 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2227 k
= cgfs_get_key(controller
, path1
, path2
);
2234 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2237 if (!caller_may_see_dir(initpid
, controller
, path1
)) {
2241 if (!fc_may_access(fc
, controller
, path1
, path2
, fi
->flags
)) {
2246 /* we'll free this at cg_release */
2247 file_info
= malloc(sizeof(*file_info
));
2252 file_info
->controller
= must_copy_string(controller
);
2253 file_info
->cgroup
= must_copy_string(path1
);
2254 file_info
->file
= must_copy_string(path2
);
2255 file_info
->type
= LXC_TYPE_CGFILE
;
2256 file_info
->buf
= NULL
;
2257 file_info
->buflen
= 0;
2259 fi
->fh
= (unsigned long)file_info
;
2267 int cg_access(const char *path
, int mode
)
2271 char *path1
, *path2
, *controller
;
2272 char *last
= NULL
, *cgdir
= NULL
;
2273 struct cgfs_files
*k
= NULL
;
2274 struct fuse_context
*fc
= fuse_get_context();
2276 if (strcmp(path
, "/cgroup") == 0)
2282 controller
= pick_controller_from_path(fc
, path
);
2285 cgroup
= find_cgroup_in_path(path
);
2287 // access("/sys/fs/cgroup/systemd", mode) - rx allowed, w not
2288 if ((mode
& W_OK
) == 0)
2293 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2302 k
= cgfs_get_key(controller
, path1
, path2
);
2304 if ((mode
& W_OK
) == 0)
2312 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2315 if (!caller_may_see_dir(initpid
, controller
, path1
)) {
2319 if (!fc_may_access(fc
, controller
, path1
, path2
, mode
)) {
2331 int cg_release(const char *path
, struct fuse_file_info
*fi
)
2333 do_release_file_info(fi
);
2337 #define POLLIN_SET ( EPOLLIN | EPOLLHUP | EPOLLRDHUP )
2339 static bool wait_for_sock(int sock
, int timeout
)
2341 struct epoll_event ev
;
2342 int epfd
, ret
, now
, starttime
, deltatime
, saved_errno
;
2344 if ((starttime
= time(NULL
)) < 0)
2347 if ((epfd
= epoll_create(1)) < 0) {
2348 lxcfs_error("%s\n", "Failed to create epoll socket: %m.");
2352 ev
.events
= POLLIN_SET
;
2354 if (epoll_ctl(epfd
, EPOLL_CTL_ADD
, sock
, &ev
) < 0) {
2355 lxcfs_error("%s\n", "Failed adding socket to epoll: %m.");
2361 if ((now
= time(NULL
)) < 0) {
2366 deltatime
= (starttime
+ timeout
) - now
;
2367 if (deltatime
< 0) { // timeout
2372 ret
= epoll_wait(epfd
, &ev
, 1, 1000*deltatime
+ 1);
2373 if (ret
< 0 && errno
== EINTR
)
2375 saved_errno
= errno
;
2379 errno
= saved_errno
;
2385 static int msgrecv(int sockfd
, void *buf
, size_t len
)
2387 if (!wait_for_sock(sockfd
, 2))
2389 return recv(sockfd
, buf
, len
, MSG_DONTWAIT
);
2392 static int send_creds(int sock
, struct ucred
*cred
, char v
, bool pingfirst
)
2394 struct msghdr msg
= { 0 };
2396 struct cmsghdr
*cmsg
;
2397 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
2402 if (msgrecv(sock
, buf
, 1) != 1) {
2403 lxcfs_error("%s\n", "Error getting reply from server over socketpair.");
2404 return SEND_CREDS_FAIL
;
2408 msg
.msg_control
= cmsgbuf
;
2409 msg
.msg_controllen
= sizeof(cmsgbuf
);
2411 cmsg
= CMSG_FIRSTHDR(&msg
);
2412 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct ucred
));
2413 cmsg
->cmsg_level
= SOL_SOCKET
;
2414 cmsg
->cmsg_type
= SCM_CREDENTIALS
;
2415 memcpy(CMSG_DATA(cmsg
), cred
, sizeof(*cred
));
2417 msg
.msg_name
= NULL
;
2418 msg
.msg_namelen
= 0;
2422 iov
.iov_len
= sizeof(buf
);
2426 if (sendmsg(sock
, &msg
, 0) < 0) {
2427 lxcfs_error("Failed at sendmsg: %s.\n",strerror(errno
));
2429 return SEND_CREDS_NOTSK
;
2430 return SEND_CREDS_FAIL
;
2433 return SEND_CREDS_OK
;
2436 static bool recv_creds(int sock
, struct ucred
*cred
, char *v
)
2438 struct msghdr msg
= { 0 };
2440 struct cmsghdr
*cmsg
;
2441 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
2452 if (setsockopt(sock
, SOL_SOCKET
, SO_PASSCRED
, &optval
, sizeof(optval
)) == -1) {
2453 lxcfs_error("Failed to set passcred: %s\n", strerror(errno
));
2457 if (write(sock
, buf
, 1) != 1) {
2458 lxcfs_error("Failed to start write on scm fd: %s\n", strerror(errno
));
2462 msg
.msg_name
= NULL
;
2463 msg
.msg_namelen
= 0;
2464 msg
.msg_control
= cmsgbuf
;
2465 msg
.msg_controllen
= sizeof(cmsgbuf
);
2468 iov
.iov_len
= sizeof(buf
);
2472 if (!wait_for_sock(sock
, 2)) {
2473 lxcfs_error("Timed out waiting for scm_cred: %s\n", strerror(errno
));
2476 ret
= recvmsg(sock
, &msg
, MSG_DONTWAIT
);
2478 lxcfs_error("Failed to receive scm_cred: %s\n", strerror(errno
));
2482 cmsg
= CMSG_FIRSTHDR(&msg
);
2484 if (cmsg
&& cmsg
->cmsg_len
== CMSG_LEN(sizeof(struct ucred
)) &&
2485 cmsg
->cmsg_level
== SOL_SOCKET
&&
2486 cmsg
->cmsg_type
== SCM_CREDENTIALS
) {
2487 memcpy(cred
, CMSG_DATA(cmsg
), sizeof(*cred
));
2494 struct pid_ns_clone_args
{
2498 int (*wrapped
) (int, pid_t
); // pid_from_ns or pid_to_ns
2502 * pid_ns_clone_wrapper - wraps pid_to_ns or pid_from_ns for usage
2503 * with clone(). This simply writes '1' as ACK back to the parent
2504 * before calling the actual wrapped function.
2506 static int pid_ns_clone_wrapper(void *arg
) {
2507 struct pid_ns_clone_args
* args
= (struct pid_ns_clone_args
*) arg
;
2510 close(args
->cpipe
[0]);
2511 if (write(args
->cpipe
[1], &b
, sizeof(char)) < 0)
2512 lxcfs_error("(child): error on write: %s.\n", strerror(errno
));
2513 close(args
->cpipe
[1]);
2514 return args
->wrapped(args
->sock
, args
->tpid
);
2518 * pid_to_ns - reads pids from a ucred over a socket, then writes the
2519 * int value back over the socket. This shifts the pid from the
2520 * sender's pidns into tpid's pidns.
2522 static int pid_to_ns(int sock
, pid_t tpid
)
2527 while (recv_creds(sock
, &cred
, &v
)) {
2530 if (write(sock
, &cred
.pid
, sizeof(pid_t
)) != sizeof(pid_t
))
2538 * pid_to_ns_wrapper: when you setns into a pidns, you yourself remain
2539 * in your old pidns. Only children which you clone will be in the target
2540 * pidns. So the pid_to_ns_wrapper does the setns, then clones a child to
2541 * actually convert pids.
2543 * Note: glibc's fork() does not respect pidns, which can lead to failed
2544 * assertions inside glibc (and thus failed forks) if the child's pid in
2545 * the pidns and the parent pid outside are identical. Using clone prevents
2548 static void pid_to_ns_wrapper(int sock
, pid_t tpid
)
2550 int newnsfd
= -1, ret
, cpipe
[2];
2555 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
2556 if (ret
< 0 || ret
>= sizeof(fnam
))
2558 newnsfd
= open(fnam
, O_RDONLY
);
2561 if (setns(newnsfd
, 0) < 0)
2565 if (pipe(cpipe
) < 0)
2568 struct pid_ns_clone_args args
= {
2572 .wrapped
= &pid_to_ns
2574 size_t stack_size
= sysconf(_SC_PAGESIZE
);
2575 void *stack
= alloca(stack_size
);
2577 cpid
= clone(pid_ns_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &args
);
2581 // give the child 1 second to be done forking and
2583 if (!wait_for_sock(cpipe
[0], 1))
2585 ret
= read(cpipe
[0], &v
, 1);
2586 if (ret
!= sizeof(char) || v
!= '1')
2589 if (!wait_for_pid(cpid
))
2595 * To read cgroup files with a particular pid, we will setns into the child
2596 * pidns, open a pipe, fork a child - which will be the first to really be in
2597 * the child ns - which does the cgfs_get_value and writes the data to the pipe.
2599 bool do_read_pids(pid_t tpid
, const char *contrl
, const char *cg
, const char *file
, char **d
)
2601 int sock
[2] = {-1, -1};
2602 char *tmpdata
= NULL
;
2604 pid_t qpid
, cpid
= -1;
2605 bool answer
= false;
2608 size_t sz
= 0, asz
= 0;
2610 if (!cgfs_get_value(contrl
, cg
, file
, &tmpdata
))
2614 * Now we read the pids from returned data one by one, pass
2615 * them into a child in the target namespace, read back the
2616 * translated pids, and put them into our to-return data
2619 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
2620 perror("socketpair");
2629 if (!cpid
) // child - exits when done
2630 pid_to_ns_wrapper(sock
[1], tpid
);
2632 char *ptr
= tmpdata
;
2635 while (sscanf(ptr
, "%d\n", &qpid
) == 1) {
2637 ret
= send_creds(sock
[0], &cred
, v
, true);
2639 if (ret
== SEND_CREDS_NOTSK
)
2641 if (ret
== SEND_CREDS_FAIL
)
2644 // read converted results
2645 if (!wait_for_sock(sock
[0], 2)) {
2646 lxcfs_error("Timed out waiting for pid from child: %s.\n", strerror(errno
));
2649 if (read(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
2650 lxcfs_error("Error reading pid from child: %s.\n", strerror(errno
));
2653 must_strcat_pid(d
, &sz
, &asz
, qpid
);
2655 ptr
= strchr(ptr
, '\n');
2661 cred
.pid
= getpid();
2663 if (send_creds(sock
[0], &cred
, v
, true) != SEND_CREDS_OK
) {
2664 // failed to ask child to exit
2665 lxcfs_error("Failed to ask child to exit: %s.\n", strerror(errno
));
2675 if (sock
[0] != -1) {
2682 int cg_read(const char *path
, char *buf
, size_t size
, off_t offset
,
2683 struct fuse_file_info
*fi
)
2685 struct fuse_context
*fc
= fuse_get_context();
2686 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2687 struct cgfs_files
*k
= NULL
;
2692 if (f
->type
!= LXC_TYPE_CGFILE
) {
2693 lxcfs_error("%s\n", "Internal error: directory cache info used in cg_read.");
2706 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
2712 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_RDONLY
)) {
2717 if (strcmp(f
->file
, "tasks") == 0 ||
2718 strcmp(f
->file
, "/tasks") == 0 ||
2719 strcmp(f
->file
, "/cgroup.procs") == 0 ||
2720 strcmp(f
->file
, "cgroup.procs") == 0)
2721 // special case - we have to translate the pids
2722 r
= do_read_pids(fc
->pid
, f
->controller
, f
->cgroup
, f
->file
, &data
);
2724 r
= cgfs_get_value(f
->controller
, f
->cgroup
, f
->file
, &data
);
2738 memcpy(buf
, data
, s
);
2739 if (s
> 0 && s
< size
&& data
[s
-1] != '\n')
2749 static int pid_from_ns(int sock
, pid_t tpid
)
2759 if (!wait_for_sock(sock
, 2)) {
2760 lxcfs_error("%s\n", "Timeout reading from parent.");
2763 if ((ret
= read(sock
, &vpid
, sizeof(pid_t
))) != sizeof(pid_t
)) {
2764 lxcfs_error("Bad read from parent: %s.\n", strerror(errno
));
2767 if (vpid
== -1) // done
2771 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
) {
2773 cred
.pid
= getpid();
2774 if (send_creds(sock
, &cred
, v
, false) != SEND_CREDS_OK
)
2781 static void pid_from_ns_wrapper(int sock
, pid_t tpid
)
2783 int newnsfd
= -1, ret
, cpipe
[2];
2788 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
2789 if (ret
< 0 || ret
>= sizeof(fnam
))
2791 newnsfd
= open(fnam
, O_RDONLY
);
2794 if (setns(newnsfd
, 0) < 0)
2798 if (pipe(cpipe
) < 0)
2801 struct pid_ns_clone_args args
= {
2805 .wrapped
= &pid_from_ns
2807 size_t stack_size
= sysconf(_SC_PAGESIZE
);
2808 void *stack
= alloca(stack_size
);
2810 cpid
= clone(pid_ns_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &args
);
2814 // give the child 1 second to be done forking and
2816 if (!wait_for_sock(cpipe
[0], 1))
2818 ret
= read(cpipe
[0], &v
, 1);
2819 if (ret
!= sizeof(char) || v
!= '1')
2822 if (!wait_for_pid(cpid
))
2828 * Given host @uid, return the uid to which it maps in
2829 * @pid's user namespace, or -1 if none.
2831 bool hostuid_to_ns(uid_t uid
, pid_t pid
, uid_t
*answer
)
2836 sprintf(line
, "/proc/%d/uid_map", pid
);
2837 if ((f
= fopen(line
, "r")) == NULL
) {
2841 *answer
= convert_id_to_ns(f
, uid
);
2850 * get_pid_creds: get the real uid and gid of @pid from
2852 * (XXX should we use euid here?)
2854 void get_pid_creds(pid_t pid
, uid_t
*uid
, gid_t
*gid
)
2863 sprintf(line
, "/proc/%d/status", pid
);
2864 if ((f
= fopen(line
, "r")) == NULL
) {
2865 lxcfs_error("Error opening %s: %s\n", line
, strerror(errno
));
2868 while (fgets(line
, 400, f
)) {
2869 if (strncmp(line
, "Uid:", 4) == 0) {
2870 if (sscanf(line
+4, "%u", &u
) != 1) {
2871 lxcfs_error("bad uid line for pid %u\n", pid
);
2876 } else if (strncmp(line
, "Gid:", 4) == 0) {
2877 if (sscanf(line
+4, "%u", &g
) != 1) {
2878 lxcfs_error("bad gid line for pid %u\n", pid
);
2889 * May the requestor @r move victim @v to a new cgroup?
2890 * This is allowed if
2891 * . they are the same task
2892 * . they are ownedy by the same uid
2893 * . @r is root on the host, or
2894 * . @v's uid is mapped into @r's where @r is root.
2896 bool may_move_pid(pid_t r
, uid_t r_uid
, pid_t v
)
2898 uid_t v_uid
, tmpuid
;
2905 get_pid_creds(v
, &v_uid
, &v_gid
);
2908 if (hostuid_to_ns(r_uid
, r
, &tmpuid
) && tmpuid
== 0
2909 && hostuid_to_ns(v_uid
, r
, &tmpuid
))
2914 static bool do_write_pids(pid_t tpid
, uid_t tuid
, const char *contrl
, const char *cg
,
2915 const char *file
, const char *buf
)
2917 int sock
[2] = {-1, -1};
2918 pid_t qpid
, cpid
= -1;
2919 FILE *pids_file
= NULL
;
2920 bool answer
= false, fail
= false;
2922 pids_file
= open_pids_file(contrl
, cg
);
2927 * write the pids to a socket, have helper in writer's pidns
2928 * call movepid for us
2930 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
2931 perror("socketpair");
2939 if (!cpid
) { // child
2941 pid_from_ns_wrapper(sock
[1], tpid
);
2944 const char *ptr
= buf
;
2945 while (sscanf(ptr
, "%d", &qpid
) == 1) {
2949 if (write(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
2950 lxcfs_error("Error writing pid to child: %s.\n", strerror(errno
));
2954 if (recv_creds(sock
[0], &cred
, &v
)) {
2956 if (!may_move_pid(tpid
, tuid
, cred
.pid
)) {
2960 if (fprintf(pids_file
, "%d", (int) cred
.pid
) < 0)
2965 ptr
= strchr(ptr
, '\n');
2971 /* All good, write the value */
2973 if (write(sock
[0], &qpid
,sizeof(qpid
)) != sizeof(qpid
))
2974 lxcfs_error("%s\n", "Warning: failed to ask child to exit.");
2982 if (sock
[0] != -1) {
2987 if (fclose(pids_file
) != 0)
2993 int cg_write(const char *path
, const char *buf
, size_t size
, off_t offset
,
2994 struct fuse_file_info
*fi
)
2996 struct fuse_context
*fc
= fuse_get_context();
2997 char *localbuf
= NULL
;
2998 struct cgfs_files
*k
= NULL
;
2999 struct file_info
*f
= (struct file_info
*)fi
->fh
;
3002 if (f
->type
!= LXC_TYPE_CGFILE
) {
3003 lxcfs_error("%s\n", "Internal error: directory cache info used in cg_write.");
3013 localbuf
= alloca(size
+1);
3014 localbuf
[size
] = '\0';
3015 memcpy(localbuf
, buf
, size
);
3017 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
3022 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_WRONLY
)) {
3027 if (strcmp(f
->file
, "tasks") == 0 ||
3028 strcmp(f
->file
, "/tasks") == 0 ||
3029 strcmp(f
->file
, "/cgroup.procs") == 0 ||
3030 strcmp(f
->file
, "cgroup.procs") == 0)
3031 // special case - we have to translate the pids
3032 r
= do_write_pids(fc
->pid
, fc
->uid
, f
->controller
, f
->cgroup
, f
->file
, localbuf
);
3034 r
= cgfs_set_value(f
->controller
, f
->cgroup
, f
->file
, localbuf
);
3044 int cg_chown(const char *path
, uid_t uid
, gid_t gid
)
3046 struct fuse_context
*fc
= fuse_get_context();
3047 char *cgdir
= NULL
, *last
= NULL
, *path1
, *path2
, *controller
;
3048 struct cgfs_files
*k
= NULL
;
3055 if (strcmp(path
, "/cgroup") == 0)
3058 controller
= pick_controller_from_path(fc
, path
);
3060 return errno
== ENOENT
? -EPERM
: -errno
;
3062 cgroup
= find_cgroup_in_path(path
);
3064 /* this is just /cgroup/controller */
3067 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
3077 if (is_child_cgroup(controller
, path1
, path2
)) {
3078 // get uid, gid, from '/tasks' file and make up a mode
3079 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
3080 k
= cgfs_get_key(controller
, cgroup
, "tasks");
3083 k
= cgfs_get_key(controller
, path1
, path2
);
3091 * This being a fuse request, the uid and gid must be valid
3092 * in the caller's namespace. So we can just check to make
3093 * sure that the caller is root in his uid, and privileged
3094 * over the file's current owner.
3096 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_REQD
)) {
3101 ret
= cgfs_chown_file(controller
, cgroup
, uid
, gid
);
3110 int cg_chmod(const char *path
, mode_t mode
)
3112 struct fuse_context
*fc
= fuse_get_context();
3113 char * cgdir
= NULL
, *last
= NULL
, *path1
, *path2
, *controller
;
3114 struct cgfs_files
*k
= NULL
;
3121 if (strcmp(path
, "/cgroup") == 0)
3124 controller
= pick_controller_from_path(fc
, path
);
3126 return errno
== ENOENT
? -EPERM
: -errno
;
3128 cgroup
= find_cgroup_in_path(path
);
3130 /* this is just /cgroup/controller */
3133 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
3143 if (is_child_cgroup(controller
, path1
, path2
)) {
3144 // get uid, gid, from '/tasks' file and make up a mode
3145 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
3146 k
= cgfs_get_key(controller
, cgroup
, "tasks");
3149 k
= cgfs_get_key(controller
, path1
, path2
);
3157 * This being a fuse request, the uid and gid must be valid
3158 * in the caller's namespace. So we can just check to make
3159 * sure that the caller is root in his uid, and privileged
3160 * over the file's current owner.
3162 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
3167 if (!cgfs_chmod_file(controller
, cgroup
, mode
)) {
3179 int cg_mkdir(const char *path
, mode_t mode
)
3181 struct fuse_context
*fc
= fuse_get_context();
3182 char *last
= NULL
, *path1
, *cgdir
= NULL
, *controller
, *next
= NULL
;
3189 controller
= pick_controller_from_path(fc
, path
);
3191 return errno
== ENOENT
? -EPERM
: -errno
;
3193 cgroup
= find_cgroup_in_path(path
);
3197 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
3203 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3206 if (!caller_is_in_ancestor(initpid
, controller
, path1
, &next
)) {
3209 else if (last
&& strcmp(next
, last
) == 0)
3216 if (!fc_may_access(fc
, controller
, path1
, NULL
, O_RDWR
)) {
3220 if (!caller_is_in_ancestor(initpid
, controller
, path1
, NULL
)) {
3225 ret
= cgfs_create(controller
, cgroup
, fc
->uid
, fc
->gid
);
3233 int cg_rmdir(const char *path
)
3235 struct fuse_context
*fc
= fuse_get_context();
3236 char *last
= NULL
, *cgdir
= NULL
, *controller
, *next
= NULL
;
3243 controller
= pick_controller_from_path(fc
, path
);
3244 if (!controller
) /* Someone's trying to delete "/cgroup". */
3247 cgroup
= find_cgroup_in_path(path
);
3248 if (!cgroup
) /* Someone's trying to delete a controller e.g. "/blkio". */
3251 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
3253 /* Someone's trying to delete a cgroup on the same level as the
3254 * "/lxc" cgroup e.g. rmdir "/cgroup/blkio/lxc" or
3255 * rmdir "/cgroup/blkio/init.slice".
3261 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3264 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, &next
)) {
3265 if (!last
|| (next
&& (strcmp(next
, last
) == 0)))
3272 if (!fc_may_access(fc
, controller
, cgdir
, NULL
, O_WRONLY
)) {
3276 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, NULL
)) {
3281 if (!cgfs_remove(controller
, cgroup
)) {
3294 static bool startswith(const char *line
, const char *pref
)
3296 if (strncmp(line
, pref
, strlen(pref
)) == 0)
3301 static void parse_memstat(char *memstat
, unsigned long *cached
,
3302 unsigned long *active_anon
, unsigned long *inactive_anon
,
3303 unsigned long *active_file
, unsigned long *inactive_file
,
3304 unsigned long *unevictable
, unsigned long *shmem
)
3309 if (startswith(memstat
, "total_cache")) {
3310 sscanf(memstat
+ 11, "%lu", cached
);
3312 } else if (startswith(memstat
, "total_active_anon")) {
3313 sscanf(memstat
+ 17, "%lu", active_anon
);
3314 *active_anon
/= 1024;
3315 } else if (startswith(memstat
, "total_inactive_anon")) {
3316 sscanf(memstat
+ 19, "%lu", inactive_anon
);
3317 *inactive_anon
/= 1024;
3318 } else if (startswith(memstat
, "total_active_file")) {
3319 sscanf(memstat
+ 17, "%lu", active_file
);
3320 *active_file
/= 1024;
3321 } else if (startswith(memstat
, "total_inactive_file")) {
3322 sscanf(memstat
+ 19, "%lu", inactive_file
);
3323 *inactive_file
/= 1024;
3324 } else if (startswith(memstat
, "total_unevictable")) {
3325 sscanf(memstat
+ 17, "%lu", unevictable
);
3326 *unevictable
/= 1024;
3327 } else if (startswith(memstat
, "total_shmem")) {
3328 sscanf(memstat
+ 11, "%lu", shmem
);
3331 eol
= strchr(memstat
, '\n');
3338 static void get_blkio_io_value(char *str
, unsigned major
, unsigned minor
, char *iotype
, unsigned long *v
)
3344 snprintf(key
, 32, "%u:%u %s", major
, minor
, iotype
);
3346 size_t len
= strlen(key
);
3350 if (startswith(str
, key
)) {
3351 sscanf(str
+ len
, "%lu", v
);
3354 eol
= strchr(str
, '\n');
3361 static int read_file(const char *path
, char *buf
, size_t size
,
3362 struct file_info
*d
)
3364 size_t linelen
= 0, total_len
= 0, rv
= 0;
3366 char *cache
= d
->buf
;
3367 size_t cache_size
= d
->buflen
;
3368 FILE *f
= fopen(path
, "r");
3372 while (getline(&line
, &linelen
, f
) != -1) {
3373 ssize_t l
= snprintf(cache
, cache_size
, "%s", line
);
3375 perror("Error writing to cache");
3379 if (l
>= cache_size
) {
3380 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3389 d
->size
= total_len
;
3390 if (total_len
> size
)
3393 /* read from off 0 */
3394 memcpy(buf
, d
->buf
, total_len
);
3403 * FUSE ops for /proc
3406 static unsigned long get_memlimit(const char *cgroup
, const char *file
)
3408 char *memlimit_str
= NULL
;
3409 unsigned long memlimit
= -1;
3411 if (cgfs_get_value("memory", cgroup
, file
, &memlimit_str
))
3412 memlimit
= strtoul(memlimit_str
, NULL
, 10);
3419 static unsigned long get_min_memlimit(const char *cgroup
, const char *file
)
3421 char *copy
= strdupa(cgroup
);
3422 unsigned long memlimit
= 0, retlimit
;
3424 retlimit
= get_memlimit(copy
, file
);
3426 while (strcmp(copy
, "/") != 0) {
3427 copy
= dirname(copy
);
3428 memlimit
= get_memlimit(copy
, file
);
3429 if (memlimit
!= -1 && memlimit
< retlimit
)
3430 retlimit
= memlimit
;
3436 static int proc_meminfo_read(char *buf
, size_t size
, off_t offset
,
3437 struct fuse_file_info
*fi
)
3439 struct fuse_context
*fc
= fuse_get_context();
3440 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3442 char *memusage_str
= NULL
, *memstat_str
= NULL
,
3443 *memswlimit_str
= NULL
, *memswusage_str
= NULL
;
3444 unsigned long memlimit
= 0, memusage
= 0, memswlimit
= 0, memswusage
= 0,
3445 cached
= 0, hosttotal
= 0, active_anon
= 0, inactive_anon
= 0,
3446 active_file
= 0, inactive_file
= 0, unevictable
= 0, shmem
= 0,
3449 size_t linelen
= 0, total_len
= 0, rv
= 0;
3450 char *cache
= d
->buf
;
3451 size_t cache_size
= d
->buflen
;
3455 if (offset
> d
->size
)
3459 int left
= d
->size
- offset
;
3460 total_len
= left
> size
? size
: left
;
3461 memcpy(buf
, cache
+ offset
, total_len
);
3465 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3468 cg
= get_pid_cgroup(initpid
, "memory");
3470 return read_file("/proc/meminfo", buf
, size
, d
);
3471 prune_init_slice(cg
);
3473 memlimit
= get_min_memlimit(cg
, "memory.limit_in_bytes");
3474 if (!cgfs_get_value("memory", cg
, "memory.usage_in_bytes", &memusage_str
))
3476 if (!cgfs_get_value("memory", cg
, "memory.stat", &memstat_str
))
3479 // Following values are allowed to fail, because swapaccount might be turned
3480 // off for current kernel
3481 if(cgfs_get_value("memory", cg
, "memory.memsw.limit_in_bytes", &memswlimit_str
) &&
3482 cgfs_get_value("memory", cg
, "memory.memsw.usage_in_bytes", &memswusage_str
))
3484 memswlimit
= get_min_memlimit(cg
, "memory.memsw.limit_in_bytes");
3485 memswusage
= strtoul(memswusage_str
, NULL
, 10);
3487 memswlimit
= memswlimit
/ 1024;
3488 memswusage
= memswusage
/ 1024;
3491 memusage
= strtoul(memusage_str
, NULL
, 10);
3495 parse_memstat(memstat_str
, &cached
, &active_anon
,
3496 &inactive_anon
, &active_file
, &inactive_file
,
3497 &unevictable
, &shmem
);
3499 f
= fopen("/proc/meminfo", "r");
3503 while (getline(&line
, &linelen
, f
) != -1) {
3505 char *printme
, lbuf
[100];
3507 memset(lbuf
, 0, 100);
3508 if (startswith(line
, "MemTotal:")) {
3509 sscanf(line
+sizeof("MemTotal:")-1, "%lu", &hosttotal
);
3510 if (hosttotal
< memlimit
)
3511 memlimit
= hosttotal
;
3512 snprintf(lbuf
, 100, "MemTotal: %8lu kB\n", memlimit
);
3514 } else if (startswith(line
, "MemFree:")) {
3515 snprintf(lbuf
, 100, "MemFree: %8lu kB\n", memlimit
- memusage
);
3517 } else if (startswith(line
, "MemAvailable:")) {
3518 snprintf(lbuf
, 100, "MemAvailable: %8lu kB\n", memlimit
- memusage
+ cached
);
3520 } else if (startswith(line
, "SwapTotal:") && memswlimit
> 0) {
3521 sscanf(line
+sizeof("SwapTotal:")-1, "%lu", &hostswtotal
);
3522 if (hostswtotal
< memswlimit
)
3523 memswlimit
= hostswtotal
;
3524 snprintf(lbuf
, 100, "SwapTotal: %8lu kB\n", memswlimit
);
3526 } else if (startswith(line
, "SwapFree:") && memswlimit
> 0 && memswusage
> 0) {
3527 unsigned long swaptotal
= memswlimit
,
3528 swapusage
= memswusage
- memusage
,
3529 swapfree
= swapusage
< swaptotal
? swaptotal
- swapusage
: 0;
3530 snprintf(lbuf
, 100, "SwapFree: %8lu kB\n", swapfree
);
3532 } else if (startswith(line
, "Slab:")) {
3533 snprintf(lbuf
, 100, "Slab: %8lu kB\n", 0UL);
3535 } else if (startswith(line
, "Buffers:")) {
3536 snprintf(lbuf
, 100, "Buffers: %8lu kB\n", 0UL);
3538 } else if (startswith(line
, "Cached:")) {
3539 snprintf(lbuf
, 100, "Cached: %8lu kB\n", cached
);
3541 } else if (startswith(line
, "SwapCached:")) {
3542 snprintf(lbuf
, 100, "SwapCached: %8lu kB\n", 0UL);
3544 } else if (startswith(line
, "Active:")) {
3545 snprintf(lbuf
, 100, "Active: %8lu kB\n",
3546 active_anon
+ active_file
);
3548 } else if (startswith(line
, "Inactive:")) {
3549 snprintf(lbuf
, 100, "Inactive: %8lu kB\n",
3550 inactive_anon
+ inactive_file
);
3552 } else if (startswith(line
, "Active(anon)")) {
3553 snprintf(lbuf
, 100, "Active(anon): %8lu kB\n", active_anon
);
3555 } else if (startswith(line
, "Inactive(anon)")) {
3556 snprintf(lbuf
, 100, "Inactive(anon): %8lu kB\n", inactive_anon
);
3558 } else if (startswith(line
, "Active(file)")) {
3559 snprintf(lbuf
, 100, "Active(file): %8lu kB\n", active_file
);
3561 } else if (startswith(line
, "Inactive(file)")) {
3562 snprintf(lbuf
, 100, "Inactive(file): %8lu kB\n", inactive_file
);
3564 } else if (startswith(line
, "Unevictable")) {
3565 snprintf(lbuf
, 100, "Unevictable: %8lu kB\n", unevictable
);
3567 } else if (startswith(line
, "SReclaimable")) {
3568 snprintf(lbuf
, 100, "SReclaimable: %8lu kB\n", 0UL);
3570 } else if (startswith(line
, "SUnreclaim")) {
3571 snprintf(lbuf
, 100, "SUnreclaim: %8lu kB\n", 0UL);
3573 } else if (startswith(line
, "Shmem:")) {
3574 snprintf(lbuf
, 100, "Shmem: %8lu kB\n", shmem
);
3576 } else if (startswith(line
, "ShmemHugePages")) {
3577 snprintf(lbuf
, 100, "ShmemHugePages: %8lu kB\n", 0UL);
3579 } else if (startswith(line
, "ShmemPmdMapped")) {
3580 snprintf(lbuf
, 100, "ShmemPmdMapped: %8lu kB\n", 0UL);
3585 l
= snprintf(cache
, cache_size
, "%s", printme
);
3587 perror("Error writing to cache");
3592 if (l
>= cache_size
) {
3593 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3604 d
->size
= total_len
;
3605 if (total_len
> size
) total_len
= size
;
3606 memcpy(buf
, d
->buf
, total_len
);
3615 free(memswlimit_str
);
3616 free(memswusage_str
);
3622 * Read the cpuset.cpus for cg
3623 * Return the answer in a newly allocated string which must be freed
3625 static char *get_cpuset(const char *cg
)
3629 if (!cgfs_get_value("cpuset", cg
, "cpuset.cpus", &answer
))
3634 bool cpu_in_cpuset(int cpu
, const char *cpuset
);
3636 static bool cpuline_in_cpuset(const char *line
, const char *cpuset
)
3640 if (sscanf(line
, "processor : %d", &cpu
) != 1)
3642 return cpu_in_cpuset(cpu
, cpuset
);
3646 * Read cgroup CPU quota parameters from `cpu.cfs_quota_us` or `cpu.cfs_period_us`,
3647 * depending on `param`. Parameter value is returned throuh `value`.
3649 static bool read_cpu_cfs_param(const char *cg
, const char *param
, int64_t *value
)
3652 char file
[11 + 6 + 1]; // cpu.cfs__us + quota/period + \0
3655 sprintf(file
, "cpu.cfs_%s_us", param
);
3657 if (!cgfs_get_value("cpu", cg
, file
, &str
))
3660 if (sscanf(str
, "%ld", value
) != 1)
3672 * Return the maximum number of visible CPUs based on CPU quotas.
3673 * If there is no quota set, zero is returned.
3675 int max_cpu_count(const char *cg
)
3678 int64_t cfs_quota
, cfs_period
;
3680 if (!read_cpu_cfs_param(cg
, "quota", &cfs_quota
))
3683 if (!read_cpu_cfs_param(cg
, "period", &cfs_period
))
3686 if (cfs_quota
<= 0 || cfs_period
<= 0)
3689 rv
= cfs_quota
/ cfs_period
;
3691 /* In case quota/period does not yield a whole number, add one CPU for
3694 if ((cfs_quota
% cfs_period
) > 0)
3697 nprocs
= get_nprocs();
3706 * Determine whether CPU views should be used or not.
3708 bool use_cpuview(const char *cg
)
3713 tmpc
= find_mounted_controller("cpu", &cfd
);
3717 tmpc
= find_mounted_controller("cpuacct", &cfd
);
3725 * check whether this is a '^processor" line in /proc/cpuinfo
3727 static bool is_processor_line(const char *line
)
3731 if (sscanf(line
, "processor : %d", &cpu
) == 1)
3736 static int proc_cpuinfo_read(char *buf
, size_t size
, off_t offset
,
3737 struct fuse_file_info
*fi
)
3739 struct fuse_context
*fc
= fuse_get_context();
3740 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3742 char *cpuset
= NULL
;
3744 size_t linelen
= 0, total_len
= 0, rv
= 0;
3745 bool am_printing
= false, firstline
= true, is_s390x
= false;
3746 int curcpu
= -1, cpu
, max_cpus
= 0;
3748 char *cache
= d
->buf
;
3749 size_t cache_size
= d
->buflen
;
3753 if (offset
> d
->size
)
3757 int left
= d
->size
- offset
;
3758 total_len
= left
> size
? size
: left
;
3759 memcpy(buf
, cache
+ offset
, total_len
);
3763 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3766 cg
= get_pid_cgroup(initpid
, "cpuset");
3768 return read_file("proc/cpuinfo", buf
, size
, d
);
3769 prune_init_slice(cg
);
3771 cpuset
= get_cpuset(cg
);
3775 use_view
= use_cpuview(cg
);
3778 max_cpus
= max_cpu_count(cg
);
3780 f
= fopen("/proc/cpuinfo", "r");
3784 while (getline(&line
, &linelen
, f
) != -1) {
3788 if (strstr(line
, "IBM/S390") != NULL
) {
3794 if (strncmp(line
, "# processors:", 12) == 0)
3796 if (is_processor_line(line
)) {
3797 if (use_view
&& max_cpus
> 0 && (curcpu
+1) == max_cpus
)
3799 am_printing
= cpuline_in_cpuset(line
, cpuset
);
3802 l
= snprintf(cache
, cache_size
, "processor : %d\n", curcpu
);
3804 perror("Error writing to cache");
3808 if (l
>= cache_size
) {
3809 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3818 } else if (is_s390x
&& sscanf(line
, "processor %d:", &cpu
) == 1) {
3820 if (use_view
&& max_cpus
> 0 && (curcpu
+1) == max_cpus
)
3822 if (!cpu_in_cpuset(cpu
, cpuset
))
3825 p
= strchr(line
, ':');
3829 l
= snprintf(cache
, cache_size
, "processor %d:%s", curcpu
, p
);
3831 perror("Error writing to cache");
3835 if (l
>= cache_size
) {
3836 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3847 l
= snprintf(cache
, cache_size
, "%s", line
);
3849 perror("Error writing to cache");
3853 if (l
>= cache_size
) {
3854 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3865 char *origcache
= d
->buf
;
3868 d
->buf
= malloc(d
->buflen
);
3871 cache_size
= d
->buflen
;
3873 l
= snprintf(cache
, cache_size
, "vendor_id : IBM/S390\n");
3874 if (l
< 0 || l
>= cache_size
) {
3881 l
= snprintf(cache
, cache_size
, "# processors : %d\n", curcpu
+ 1);
3882 if (l
< 0 || l
>= cache_size
) {
3889 l
= snprintf(cache
, cache_size
, "%s", origcache
);
3891 if (l
< 0 || l
>= cache_size
)
3897 d
->size
= total_len
;
3898 if (total_len
> size
) total_len
= size
;
3900 /* read from off 0 */
3901 memcpy(buf
, d
->buf
, total_len
);
3912 static uint64_t get_reaper_start_time(pid_t pid
)
3917 /* strlen("/proc/") = 6
3921 * strlen("/stat") = 5
3925 #define __PROC_PID_STAT_LEN (6 + LXCFS_NUMSTRLEN64 + 5 + 1)
3926 char path
[__PROC_PID_STAT_LEN
];
3929 qpid
= lookup_initpid_in_store(pid
);
3931 /* Caller can check for EINVAL on 0. */
3936 ret
= snprintf(path
, __PROC_PID_STAT_LEN
, "/proc/%d/stat", qpid
);
3937 if (ret
< 0 || ret
>= __PROC_PID_STAT_LEN
) {
3938 /* Caller can check for EINVAL on 0. */
3943 f
= fopen(path
, "r");
3945 /* Caller can check for EINVAL on 0. */
3950 /* Note that the *scanf() argument supression requires that length
3951 * modifiers such as "l" are omitted. Otherwise some compilers will yell
3952 * at us. It's like telling someone you're not married and then asking
3953 * if you can bring your wife to the party.
3955 ret
= fscanf(f
, "%*d " /* (1) pid %d */
3956 "%*s " /* (2) comm %s */
3957 "%*c " /* (3) state %c */
3958 "%*d " /* (4) ppid %d */
3959 "%*d " /* (5) pgrp %d */
3960 "%*d " /* (6) session %d */
3961 "%*d " /* (7) tty_nr %d */
3962 "%*d " /* (8) tpgid %d */
3963 "%*u " /* (9) flags %u */
3964 "%*u " /* (10) minflt %lu */
3965 "%*u " /* (11) cminflt %lu */
3966 "%*u " /* (12) majflt %lu */
3967 "%*u " /* (13) cmajflt %lu */
3968 "%*u " /* (14) utime %lu */
3969 "%*u " /* (15) stime %lu */
3970 "%*d " /* (16) cutime %ld */
3971 "%*d " /* (17) cstime %ld */
3972 "%*d " /* (18) priority %ld */
3973 "%*d " /* (19) nice %ld */
3974 "%*d " /* (20) num_threads %ld */
3975 "%*d " /* (21) itrealvalue %ld */
3976 "%" PRIu64
, /* (22) starttime %llu */
3980 /* Caller can check for EINVAL on 0. */
3991 static uint64_t get_reaper_start_time_in_sec(pid_t pid
)
3993 uint64_t clockticks
;
3994 int64_t ticks_per_sec
;
3996 clockticks
= get_reaper_start_time(pid
);
3997 if (clockticks
== 0 && errno
== EINVAL
) {
3998 lxcfs_debug("failed to retrieve start time of pid %d\n", pid
);
4002 ticks_per_sec
= sysconf(_SC_CLK_TCK
);
4003 if (ticks_per_sec
< 0 && errno
== EINVAL
) {
4006 "failed to determine number of clock ticks in a second");
4010 return (clockticks
/= ticks_per_sec
);
4013 static uint64_t get_reaper_age(pid_t pid
)
4015 uint64_t procstart
, uptime
, procage
;
4017 /* We need to substract the time the process has started since system
4018 * boot minus the time when the system has started to get the actual
4021 procstart
= get_reaper_start_time_in_sec(pid
);
4022 procage
= procstart
;
4023 if (procstart
> 0) {
4025 struct timespec spec
;
4027 ret
= clock_gettime(CLOCK_BOOTTIME
, &spec
);
4030 /* We could make this more precise here by using the tv_nsec
4031 * field in the timespec struct and convert it to milliseconds
4032 * and then create a double for the seconds and milliseconds but
4033 * that seems more work than it is worth.
4035 uptime
= spec
.tv_sec
;
4036 procage
= uptime
- procstart
;
4043 * Returns 0 on success.
4044 * It is the caller's responsibility to free `return_usage`, unless this
4045 * function returns an error.
4047 static int read_cpuacct_usage_all(char *cg
, char *cpuset
, struct cpuacct_usage
**return_usage
, int *size
)
4049 int cpucount
= get_nprocs_conf();
4050 struct cpuacct_usage
*cpu_usage
;
4051 int rv
= 0, i
, j
, ret
, read_pos
= 0, read_cnt
;
4053 uint64_t cg_user
, cg_system
;
4054 int64_t ticks_per_sec
;
4055 char *usage_str
= NULL
;
4057 ticks_per_sec
= sysconf(_SC_CLK_TCK
);
4059 if (ticks_per_sec
< 0 && errno
== EINVAL
) {
4062 "read_cpuacct_usage_all failed to determine number of clock ticks "
4067 cpu_usage
= malloc(sizeof(struct cpuacct_usage
) * cpucount
);
4071 if (!cgfs_get_value("cpuacct", cg
, "cpuacct.usage_all", &usage_str
)) {
4076 if (sscanf(usage_str
, "cpu user system\n%n", &read_cnt
) != 0) {
4077 lxcfs_error("read_cpuacct_usage_all reading first line from "
4078 "%s/cpuacct.usage_all failed.\n", cg
);
4083 read_pos
+= read_cnt
;
4085 for (i
= 0, j
= 0; i
< cpucount
; i
++) {
4086 ret
= sscanf(usage_str
+ read_pos
, "%d %lu %lu\n%n", &cg_cpu
, &cg_user
,
4087 &cg_system
, &read_cnt
);
4093 lxcfs_error("read_cpuacct_usage_all reading from %s/cpuacct.usage_all "
4099 read_pos
+= read_cnt
;
4101 /* Convert the time from nanoseconds to USER_HZ */
4102 cpu_usage
[j
].user
= cg_user
/ 1000.0 / 1000 / 1000 * ticks_per_sec
;
4103 cpu_usage
[j
].system
= cg_system
/ 1000.0 / 1000 / 1000 * ticks_per_sec
;
4108 *return_usage
= cpu_usage
;
4117 *return_usage
= NULL
;
4123 static unsigned long diff_cpu_usage(struct cpuacct_usage
*older
, struct cpuacct_usage
*newer
, struct cpuacct_usage
*diff
, int cpu_count
)
4126 unsigned long sum
= 0;
4128 for (i
= 0; i
< cpu_count
; i
++) {
4129 if (!newer
[i
].online
)
4132 /* When cpuset is changed on the fly, the CPUs might get reordered.
4133 * We could either reset all counters, or check that the substractions
4134 * below will return expected results.
4136 if (newer
[i
].user
> older
[i
].user
)
4137 diff
[i
].user
= newer
[i
].user
- older
[i
].user
;
4141 if (newer
[i
].system
> older
[i
].system
)
4142 diff
[i
].system
= newer
[i
].system
- older
[i
].system
;
4146 if (newer
[i
].idle
> older
[i
].idle
)
4147 diff
[i
].idle
= newer
[i
].idle
- older
[i
].idle
;
4151 sum
+= diff
[i
].user
;
4152 sum
+= diff
[i
].system
;
4153 sum
+= diff
[i
].idle
;
4159 static void add_cpu_usage(unsigned long *surplus
, struct cpuacct_usage
*usage
, unsigned long *counter
, unsigned long threshold
)
4161 unsigned long free_space
, to_add
;
4163 free_space
= threshold
- usage
->user
- usage
->system
;
4165 if (free_space
> usage
->idle
)
4166 free_space
= usage
->idle
;
4168 to_add
= free_space
> *surplus
? *surplus
: free_space
;
4171 usage
->idle
-= to_add
;
4175 static struct cg_proc_stat
*prune_proc_stat_list(struct cg_proc_stat
*node
)
4177 struct cg_proc_stat
*first
= NULL
, *prev
, *tmp
;
4179 for (prev
= NULL
; node
; ) {
4180 if (!cgfs_param_exist("cpu", node
->cg
, "cpu.shares")) {
4182 lxcfs_debug("Removing stat node for %s\n", node
->cg
);
4185 prev
->next
= node
->next
;
4190 free_proc_stat_node(tmp
);
4202 #define PROC_STAT_PRUNE_INTERVAL 10
4203 static void prune_proc_stat_history(void)
4206 time_t now
= time(NULL
);
4208 for (i
= 0; i
< CPUVIEW_HASH_SIZE
; i
++) {
4209 pthread_rwlock_wrlock(&proc_stat_history
[i
]->lock
);
4211 if ((proc_stat_history
[i
]->lastcheck
+ PROC_STAT_PRUNE_INTERVAL
) > now
) {
4212 pthread_rwlock_unlock(&proc_stat_history
[i
]->lock
);
4216 if (proc_stat_history
[i
]->next
) {
4217 proc_stat_history
[i
]->next
= prune_proc_stat_list(proc_stat_history
[i
]->next
);
4218 proc_stat_history
[i
]->lastcheck
= now
;
4221 pthread_rwlock_unlock(&proc_stat_history
[i
]->lock
);
4225 static struct cg_proc_stat
*find_proc_stat_node(struct cg_proc_stat_head
*head
, const char *cg
)
4227 struct cg_proc_stat
*node
;
4229 pthread_rwlock_rdlock(&head
->lock
);
4232 pthread_rwlock_unlock(&head
->lock
);
4239 if (strcmp(cg
, node
->cg
) == 0)
4241 } while ((node
= node
->next
));
4246 pthread_rwlock_unlock(&head
->lock
);
4247 prune_proc_stat_history();
4251 static struct cg_proc_stat
*new_proc_stat_node(struct cpuacct_usage
*usage
, int cpu_count
, const char *cg
)
4253 struct cg_proc_stat
*node
;
4256 node
= malloc(sizeof(struct cg_proc_stat
));
4264 node
->cg
= malloc(strlen(cg
) + 1);
4268 strcpy(node
->cg
, cg
);
4270 node
->usage
= malloc(sizeof(struct cpuacct_usage
) * cpu_count
);
4274 memcpy(node
->usage
, usage
, sizeof(struct cpuacct_usage
) * cpu_count
);
4276 node
->view
= malloc(sizeof(struct cpuacct_usage
) * cpu_count
);
4280 node
->cpu_count
= cpu_count
;
4283 if (pthread_mutex_init(&node
->lock
, NULL
) != 0) {
4284 lxcfs_error("%s\n", "Failed to initialize node lock");
4288 for (i
= 0; i
< cpu_count
; i
++) {
4289 node
->view
[i
].user
= 0;
4290 node
->view
[i
].system
= 0;
4291 node
->view
[i
].idle
= 0;
4297 if (node
&& node
->cg
)
4299 if (node
&& node
->usage
)
4301 if (node
&& node
->view
)
4309 static struct cg_proc_stat
*add_proc_stat_node(struct cg_proc_stat
*new_node
)
4311 int hash
= calc_hash(new_node
->cg
) % CPUVIEW_HASH_SIZE
;
4312 struct cg_proc_stat_head
*head
= proc_stat_history
[hash
];
4313 struct cg_proc_stat
*node
, *rv
= new_node
;
4315 pthread_rwlock_wrlock(&head
->lock
);
4318 head
->next
= new_node
;
4325 if (strcmp(node
->cg
, new_node
->cg
) == 0) {
4326 /* The node is already present, return it */
4327 free_proc_stat_node(new_node
);
4337 node
->next
= new_node
;
4342 pthread_rwlock_unlock(&head
->lock
);
4346 static bool expand_proc_stat_node(struct cg_proc_stat
*node
, int cpu_count
)
4348 struct cpuacct_usage
*new_usage
, *new_view
;
4351 /* Allocate new memory */
4352 new_usage
= malloc(sizeof(struct cpuacct_usage
) * cpu_count
);
4356 new_view
= malloc(sizeof(struct cpuacct_usage
) * cpu_count
);
4362 /* Copy existing data & initialize new elements */
4363 for (i
= 0; i
< cpu_count
; i
++) {
4364 if (i
< node
->cpu_count
) {
4365 new_usage
[i
].user
= node
->usage
[i
].user
;
4366 new_usage
[i
].system
= node
->usage
[i
].system
;
4367 new_usage
[i
].idle
= node
->usage
[i
].idle
;
4369 new_view
[i
].user
= node
->view
[i
].user
;
4370 new_view
[i
].system
= node
->view
[i
].system
;
4371 new_view
[i
].idle
= node
->view
[i
].idle
;
4373 new_usage
[i
].user
= 0;
4374 new_usage
[i
].system
= 0;
4375 new_usage
[i
].idle
= 0;
4377 new_view
[i
].user
= 0;
4378 new_view
[i
].system
= 0;
4379 new_view
[i
].idle
= 0;
4386 node
->usage
= new_usage
;
4387 node
->view
= new_view
;
4388 node
->cpu_count
= cpu_count
;
4393 static struct cg_proc_stat
*find_or_create_proc_stat_node(struct cpuacct_usage
*usage
, int cpu_count
, const char *cg
)
4395 int hash
= calc_hash(cg
) % CPUVIEW_HASH_SIZE
;
4396 struct cg_proc_stat_head
*head
= proc_stat_history
[hash
];
4397 struct cg_proc_stat
*node
;
4399 node
= find_proc_stat_node(head
, cg
);
4402 node
= new_proc_stat_node(usage
, cpu_count
, cg
);
4406 node
= add_proc_stat_node(node
);
4407 lxcfs_debug("New stat node (%d) for %s\n", cpu_count
, cg
);
4410 pthread_mutex_lock(&node
->lock
);
4412 /* If additional CPUs on the host have been enabled, CPU usage counter
4413 * arrays have to be expanded */
4414 if (node
->cpu_count
< cpu_count
) {
4415 lxcfs_debug("Expanding stat node %d->%d for %s\n",
4416 node
->cpu_count
, cpu_count
, cg
);
4418 if (!expand_proc_stat_node(node
, cpu_count
)) {
4419 pthread_mutex_unlock(&node
->lock
);
4420 lxcfs_debug("Unable to expand stat node %d->%d for %s\n",
4421 node
->cpu_count
, cpu_count
, cg
);
4429 static void reset_proc_stat_node(struct cg_proc_stat
*node
, struct cpuacct_usage
*usage
, int cpu_count
)
4433 lxcfs_debug("Resetting stat node for %s\n", node
->cg
);
4434 memcpy(node
->usage
, usage
, sizeof(struct cpuacct_usage
) * cpu_count
);
4436 for (i
= 0; i
< cpu_count
; i
++) {
4437 node
->view
[i
].user
= 0;
4438 node
->view
[i
].system
= 0;
4439 node
->view
[i
].idle
= 0;
4442 node
->cpu_count
= cpu_count
;
4445 static int cpuview_proc_stat(const char *cg
, const char *cpuset
, struct cpuacct_usage
*cg_cpu_usage
, int cg_cpu_usage_size
, FILE *f
, char *buf
, size_t buf_size
)
4448 size_t linelen
= 0, total_len
= 0, rv
= 0, l
;
4449 int curcpu
= -1; /* cpu numbering starts at 0 */
4451 int max_cpus
= max_cpu_count(cg
), cpu_cnt
= 0;
4452 unsigned long user
= 0, nice
= 0, system
= 0, idle
= 0, iowait
= 0, irq
= 0, softirq
= 0, steal
= 0, guest
= 0, guest_nice
= 0;
4453 unsigned long user_sum
= 0, system_sum
= 0, idle_sum
= 0;
4454 unsigned long user_surplus
= 0, system_surplus
= 0;
4455 unsigned long total_sum
, threshold
;
4456 struct cg_proc_stat
*stat_node
;
4457 struct cpuacct_usage
*diff
= NULL
;
4458 int nprocs
= get_nprocs_conf();
4460 if (cg_cpu_usage_size
< nprocs
)
4461 nprocs
= cg_cpu_usage_size
;
4463 /* Read all CPU stats and stop when we've encountered other lines */
4464 while (getline(&line
, &linelen
, f
) != -1) {
4466 char cpu_char
[10]; /* That's a lot of cores */
4467 uint64_t all_used
, cg_used
;
4469 if (strlen(line
) == 0)
4471 if (sscanf(line
, "cpu%9[^ ]", cpu_char
) != 1) {
4472 /* not a ^cpuN line containing a number N */
4476 if (sscanf(cpu_char
, "%d", &physcpu
) != 1)
4479 if (physcpu
>= cg_cpu_usage_size
)
4485 if (!cpu_in_cpuset(physcpu
, cpuset
)) {
4486 for (i
= curcpu
; i
<= physcpu
; i
++) {
4487 cg_cpu_usage
[i
].online
= false;
4492 if (curcpu
< physcpu
) {
4493 /* Some CPUs may be disabled */
4494 for (i
= curcpu
; i
< physcpu
; i
++)
4495 cg_cpu_usage
[i
].online
= false;
4500 cg_cpu_usage
[curcpu
].online
= true;
4502 ret
= sscanf(line
, "%*s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
4517 all_used
= user
+ nice
+ system
+ iowait
+ irq
+ softirq
+ steal
+ guest
+ guest_nice
;
4518 cg_used
= cg_cpu_usage
[curcpu
].user
+ cg_cpu_usage
[curcpu
].system
;
4520 if (all_used
>= cg_used
) {
4521 cg_cpu_usage
[curcpu
].idle
= idle
+ (all_used
- cg_used
);
4524 lxcfs_error("cpu%d from %s has unexpected cpu time: %lu in /proc/stat, "
4525 "%lu in cpuacct.usage_all; unable to determine idle time\n",
4526 curcpu
, cg
, all_used
, cg_used
);
4527 cg_cpu_usage
[curcpu
].idle
= idle
;
4531 /* Cannot use more CPUs than is available due to cpuset */
4532 if (max_cpus
> cpu_cnt
)
4535 stat_node
= find_or_create_proc_stat_node(cg_cpu_usage
, nprocs
, cg
);
4538 lxcfs_error("unable to find/create stat node for %s\n", cg
);
4543 diff
= malloc(sizeof(struct cpuacct_usage
) * nprocs
);
4550 * If the new values are LOWER than values stored in memory, it means
4551 * the cgroup has been reset/recreated and we should reset too.
4553 for (curcpu
= 0; curcpu
< nprocs
; curcpu
++) {
4554 if (!cg_cpu_usage
[curcpu
].online
)
4557 if (cg_cpu_usage
[curcpu
].user
< stat_node
->usage
[curcpu
].user
)
4558 reset_proc_stat_node(stat_node
, cg_cpu_usage
, nprocs
);
4563 total_sum
= diff_cpu_usage(stat_node
->usage
, cg_cpu_usage
, diff
, nprocs
);
4565 for (curcpu
= 0, i
= -1; curcpu
< nprocs
; curcpu
++) {
4566 stat_node
->usage
[curcpu
].online
= cg_cpu_usage
[curcpu
].online
;
4568 if (!stat_node
->usage
[curcpu
].online
)
4573 stat_node
->usage
[curcpu
].user
+= diff
[curcpu
].user
;
4574 stat_node
->usage
[curcpu
].system
+= diff
[curcpu
].system
;
4575 stat_node
->usage
[curcpu
].idle
+= diff
[curcpu
].idle
;
4577 if (max_cpus
> 0 && i
>= max_cpus
) {
4578 user_surplus
+= diff
[curcpu
].user
;
4579 system_surplus
+= diff
[curcpu
].system
;
4583 /* Calculate usage counters of visible CPUs */
4585 /* threshold = maximum usage per cpu, including idle */
4586 threshold
= total_sum
/ cpu_cnt
* max_cpus
;
4588 for (curcpu
= 0, i
= -1; curcpu
< nprocs
; curcpu
++) {
4592 if (!stat_node
->usage
[curcpu
].online
)
4597 if (diff
[curcpu
].user
+ diff
[curcpu
].system
>= threshold
)
4607 if (diff
[curcpu
].user
+ diff
[curcpu
].system
>= threshold
)
4610 /* If there is still room, add system */
4614 &diff
[curcpu
].system
,
4618 if (user_surplus
> 0)
4619 lxcfs_debug("leftover user: %lu for %s\n", user_surplus
, cg
);
4620 if (system_surplus
> 0)
4621 lxcfs_debug("leftover system: %lu for %s\n", system_surplus
, cg
);
4623 for (curcpu
= 0, i
= -1; curcpu
< nprocs
; curcpu
++) {
4627 if (!stat_node
->usage
[curcpu
].online
)
4632 stat_node
->view
[curcpu
].user
+= diff
[curcpu
].user
;
4633 stat_node
->view
[curcpu
].system
+= diff
[curcpu
].system
;
4634 stat_node
->view
[curcpu
].idle
+= diff
[curcpu
].idle
;
4636 user_sum
+= stat_node
->view
[curcpu
].user
;
4637 system_sum
+= stat_node
->view
[curcpu
].system
;
4638 idle_sum
+= stat_node
->view
[curcpu
].idle
;
4642 for (curcpu
= 0; curcpu
< nprocs
; curcpu
++) {
4643 if (!stat_node
->usage
[curcpu
].online
)
4646 stat_node
->view
[curcpu
].user
= stat_node
->usage
[curcpu
].user
;
4647 stat_node
->view
[curcpu
].system
= stat_node
->usage
[curcpu
].system
;
4648 stat_node
->view
[curcpu
].idle
= stat_node
->usage
[curcpu
].idle
;
4650 user_sum
+= stat_node
->view
[curcpu
].user
;
4651 system_sum
+= stat_node
->view
[curcpu
].system
;
4652 idle_sum
+= stat_node
->view
[curcpu
].idle
;
4656 /* Render the file */
4658 l
= snprintf(buf
, buf_size
, "cpu %lu 0 %lu %lu 0 0 0 0 0 0\n",
4664 perror("Error writing to cache");
4669 if (l
>= buf_size
) {
4670 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4679 /* Render visible CPUs */
4680 for (curcpu
= 0, i
= -1; curcpu
< nprocs
; curcpu
++) {
4681 if (!stat_node
->usage
[curcpu
].online
)
4686 if (max_cpus
> 0 && i
== max_cpus
)
4689 l
= snprintf(buf
, buf_size
, "cpu%d %lu 0 %lu %lu 0 0 0 0 0 0\n",
4691 stat_node
->view
[curcpu
].user
,
4692 stat_node
->view
[curcpu
].system
,
4693 stat_node
->view
[curcpu
].idle
);
4696 perror("Error writing to cache");
4701 if (l
>= buf_size
) {
4702 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4712 /* Pass the rest of /proc/stat, start with the last line read */
4713 l
= snprintf(buf
, buf_size
, "%s", line
);
4716 perror("Error writing to cache");
4721 if (l
>= buf_size
) {
4722 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4731 /* Pass the rest of the host's /proc/stat */
4732 while (getline(&line
, &linelen
, f
) != -1) {
4733 l
= snprintf(buf
, buf_size
, "%s", line
);
4735 perror("Error writing to cache");
4739 if (l
>= buf_size
) {
4740 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4753 pthread_mutex_unlock(&stat_node
->lock
);
4761 #define CPUALL_MAX_SIZE (BUF_RESERVE_SIZE / 2)
4762 static int proc_stat_read(char *buf
, size_t size
, off_t offset
,
4763 struct fuse_file_info
*fi
)
4765 struct fuse_context
*fc
= fuse_get_context();
4766 struct file_info
*d
= (struct file_info
*)fi
->fh
;
4768 char *cpuset
= NULL
;
4770 size_t linelen
= 0, total_len
= 0, rv
= 0;
4771 int curcpu
= -1; /* cpu numbering starts at 0 */
4773 unsigned long user
= 0, nice
= 0, system
= 0, idle
= 0, iowait
= 0, irq
= 0, softirq
= 0, steal
= 0, guest
= 0, guest_nice
= 0;
4774 unsigned long user_sum
= 0, nice_sum
= 0, system_sum
= 0, idle_sum
= 0, iowait_sum
= 0,
4775 irq_sum
= 0, softirq_sum
= 0, steal_sum
= 0, guest_sum
= 0, guest_nice_sum
= 0;
4776 char cpuall
[CPUALL_MAX_SIZE
];
4777 /* reserve for cpu all */
4778 char *cache
= d
->buf
+ CPUALL_MAX_SIZE
;
4779 size_t cache_size
= d
->buflen
- CPUALL_MAX_SIZE
;
4781 struct cpuacct_usage
*cg_cpu_usage
= NULL
;
4782 int cg_cpu_usage_size
= 0;
4785 if (offset
> d
->size
)
4789 int left
= d
->size
- offset
;
4790 total_len
= left
> size
? size
: left
;
4791 memcpy(buf
, d
->buf
+ offset
, total_len
);
4795 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
4798 cg
= get_pid_cgroup(initpid
, "cpuset");
4800 return read_file("/proc/stat", buf
, size
, d
);
4801 prune_init_slice(cg
);
4803 cpuset
= get_cpuset(cg
);
4808 * Read cpuacct.usage_all for all CPUs.
4809 * If the cpuacct cgroup is present, it is used to calculate the container's
4810 * CPU usage. If not, values from the host's /proc/stat are used.
4812 if (read_cpuacct_usage_all(cg
, cpuset
, &cg_cpu_usage
, &cg_cpu_usage_size
) != 0) {
4813 lxcfs_debug("%s\n", "proc_stat_read failed to read from cpuacct, "
4814 "falling back to the host's /proc/stat");
4817 f
= fopen("/proc/stat", "r");
4822 if (getline(&line
, &linelen
, f
) < 0) {
4823 lxcfs_error("%s\n", "proc_stat_read read first line failed.");
4827 if (use_cpuview(cg
) && cg_cpu_usage
) {
4828 total_len
= cpuview_proc_stat(cg
, cpuset
, cg_cpu_usage
, cg_cpu_usage_size
,
4829 f
, d
->buf
, d
->buflen
);
4833 while (getline(&line
, &linelen
, f
) != -1) {
4835 char cpu_char
[10]; /* That's a lot of cores */
4837 uint64_t all_used
, cg_used
, new_idle
;
4840 if (strlen(line
) == 0)
4842 if (sscanf(line
, "cpu%9[^ ]", cpu_char
) != 1) {
4843 /* not a ^cpuN line containing a number N, just print it */
4844 l
= snprintf(cache
, cache_size
, "%s", line
);
4846 perror("Error writing to cache");
4850 if (l
>= cache_size
) {
4851 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4861 if (sscanf(cpu_char
, "%d", &physcpu
) != 1)
4863 if (!cpu_in_cpuset(physcpu
, cpuset
))
4867 ret
= sscanf(line
, "%*s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
4879 if (ret
!= 10 || !cg_cpu_usage
) {
4880 c
= strchr(line
, ' ');
4883 l
= snprintf(cache
, cache_size
, "cpu%d%s", curcpu
, c
);
4885 perror("Error writing to cache");
4890 if (l
>= cache_size
) {
4891 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4905 if (physcpu
>= cg_cpu_usage_size
)
4908 all_used
= user
+ nice
+ system
+ iowait
+ irq
+ softirq
+ steal
+ guest
+ guest_nice
;
4909 cg_used
= cg_cpu_usage
[physcpu
].user
+ cg_cpu_usage
[physcpu
].system
;
4911 if (all_used
>= cg_used
) {
4912 new_idle
= idle
+ (all_used
- cg_used
);
4915 lxcfs_error("cpu%d from %s has unexpected cpu time: %lu in /proc/stat, "
4916 "%lu in cpuacct.usage_all; unable to determine idle time\n",
4917 curcpu
, cg
, all_used
, cg_used
);
4921 l
= snprintf(cache
, cache_size
, "cpu%d %lu 0 %lu %lu 0 0 0 0 0 0\n",
4922 curcpu
, cg_cpu_usage
[physcpu
].user
, cg_cpu_usage
[physcpu
].system
,
4926 perror("Error writing to cache");
4931 if (l
>= cache_size
) {
4932 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4941 user_sum
+= cg_cpu_usage
[physcpu
].user
;
4942 system_sum
+= cg_cpu_usage
[physcpu
].system
;
4943 idle_sum
+= new_idle
;
4948 system_sum
+= system
;
4950 iowait_sum
+= iowait
;
4952 softirq_sum
+= softirq
;
4955 guest_nice_sum
+= guest_nice
;
4961 int cpuall_len
= snprintf(cpuall
, CPUALL_MAX_SIZE
, "cpu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
4972 if (cpuall_len
> 0 && cpuall_len
< CPUALL_MAX_SIZE
) {
4973 memcpy(cache
, cpuall
, cpuall_len
);
4974 cache
+= cpuall_len
;
4976 /* shouldn't happen */
4977 lxcfs_error("proc_stat_read copy cpuall failed, cpuall_len=%d.", cpuall_len
);
4981 memmove(cache
, d
->buf
+ CPUALL_MAX_SIZE
, total_len
);
4982 total_len
+= cpuall_len
;
4986 d
->size
= total_len
;
4987 if (total_len
> size
)
4990 memcpy(buf
, d
->buf
, total_len
);
5004 /* This function retrieves the busy time of a group of tasks by looking at
5005 * cpuacct.usage. Unfortunately, this only makes sense when the container has
5006 * been given it's own cpuacct cgroup. If not, this function will take the busy
5007 * time of all other taks that do not actually belong to the container into
5008 * account as well. If someone has a clever solution for this please send a
5011 static unsigned long get_reaper_busy(pid_t task
)
5013 pid_t initpid
= lookup_initpid_in_store(task
);
5014 char *cgroup
= NULL
, *usage_str
= NULL
;
5015 unsigned long usage
= 0;
5020 cgroup
= get_pid_cgroup(initpid
, "cpuacct");
5023 prune_init_slice(cgroup
);
5024 if (!cgfs_get_value("cpuacct", cgroup
, "cpuacct.usage", &usage_str
))
5026 usage
= strtoul(usage_str
, NULL
, 10);
5027 usage
/= 1000000000;
5040 fd
= creat("/tmp/lxcfs-iwashere", 0644);
5047 * We read /proc/uptime and reuse its second field.
5048 * For the first field, we use the mtime for the reaper for
5049 * the calling pid as returned by getreaperage
5051 static int proc_uptime_read(char *buf
, size_t size
, off_t offset
,
5052 struct fuse_file_info
*fi
)
5054 struct fuse_context
*fc
= fuse_get_context();
5055 struct file_info
*d
= (struct file_info
*)fi
->fh
;
5056 unsigned long int busytime
= get_reaper_busy(fc
->pid
);
5057 char *cache
= d
->buf
;
5058 ssize_t total_len
= 0;
5059 uint64_t idletime
, reaperage
;
5068 if (offset
> d
->size
)
5070 int left
= d
->size
- offset
;
5071 total_len
= left
> size
? size
: left
;
5072 memcpy(buf
, cache
+ offset
, total_len
);
5076 reaperage
= get_reaper_age(fc
->pid
);
5077 /* To understand why this is done, please read the comment to the
5078 * get_reaper_busy() function.
5080 idletime
= reaperage
;
5081 if (reaperage
>= busytime
)
5082 idletime
= reaperage
- busytime
;
5084 total_len
= snprintf(d
->buf
, d
->buflen
, "%"PRIu64
".00 %"PRIu64
".00\n", reaperage
, idletime
);
5085 if (total_len
< 0 || total_len
>= d
->buflen
){
5086 lxcfs_error("%s\n", "failed to write to cache");
5090 d
->size
= (int)total_len
;
5093 if (total_len
> size
) total_len
= size
;
5095 memcpy(buf
, d
->buf
, total_len
);
5099 static int proc_diskstats_read(char *buf
, size_t size
, off_t offset
,
5100 struct fuse_file_info
*fi
)
5103 struct fuse_context
*fc
= fuse_get_context();
5104 struct file_info
*d
= (struct file_info
*)fi
->fh
;
5106 char *io_serviced_str
= NULL
, *io_merged_str
= NULL
, *io_service_bytes_str
= NULL
,
5107 *io_wait_time_str
= NULL
, *io_service_time_str
= NULL
;
5108 unsigned long read
= 0, write
= 0;
5109 unsigned long read_merged
= 0, write_merged
= 0;
5110 unsigned long read_sectors
= 0, write_sectors
= 0;
5111 unsigned long read_ticks
= 0, write_ticks
= 0;
5112 unsigned long ios_pgr
= 0, tot_ticks
= 0, rq_ticks
= 0;
5113 unsigned long rd_svctm
= 0, wr_svctm
= 0, rd_wait
= 0, wr_wait
= 0;
5114 char *cache
= d
->buf
;
5115 size_t cache_size
= d
->buflen
;
5117 size_t linelen
= 0, total_len
= 0, rv
= 0;
5118 unsigned int major
= 0, minor
= 0;
5123 if (offset
> d
->size
)
5127 int left
= d
->size
- offset
;
5128 total_len
= left
> size
? size
: left
;
5129 memcpy(buf
, cache
+ offset
, total_len
);
5133 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
5136 cg
= get_pid_cgroup(initpid
, "blkio");
5138 return read_file("/proc/diskstats", buf
, size
, d
);
5139 prune_init_slice(cg
);
5141 if (!cgfs_get_value("blkio", cg
, "blkio.io_serviced_recursive", &io_serviced_str
))
5143 if (!cgfs_get_value("blkio", cg
, "blkio.io_merged_recursive", &io_merged_str
))
5145 if (!cgfs_get_value("blkio", cg
, "blkio.io_service_bytes_recursive", &io_service_bytes_str
))
5147 if (!cgfs_get_value("blkio", cg
, "blkio.io_wait_time_recursive", &io_wait_time_str
))
5149 if (!cgfs_get_value("blkio", cg
, "blkio.io_service_time_recursive", &io_service_time_str
))
5153 f
= fopen("/proc/diskstats", "r");
5157 while (getline(&line
, &linelen
, f
) != -1) {
5161 i
= sscanf(line
, "%u %u %71s", &major
, &minor
, dev_name
);
5165 get_blkio_io_value(io_serviced_str
, major
, minor
, "Read", &read
);
5166 get_blkio_io_value(io_serviced_str
, major
, minor
, "Write", &write
);
5167 get_blkio_io_value(io_merged_str
, major
, minor
, "Read", &read_merged
);
5168 get_blkio_io_value(io_merged_str
, major
, minor
, "Write", &write_merged
);
5169 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Read", &read_sectors
);
5170 read_sectors
= read_sectors
/512;
5171 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Write", &write_sectors
);
5172 write_sectors
= write_sectors
/512;
5174 get_blkio_io_value(io_service_time_str
, major
, minor
, "Read", &rd_svctm
);
5175 rd_svctm
= rd_svctm
/1000000;
5176 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Read", &rd_wait
);
5177 rd_wait
= rd_wait
/1000000;
5178 read_ticks
= rd_svctm
+ rd_wait
;
5180 get_blkio_io_value(io_service_time_str
, major
, minor
, "Write", &wr_svctm
);
5181 wr_svctm
= wr_svctm
/1000000;
5182 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Write", &wr_wait
);
5183 wr_wait
= wr_wait
/1000000;
5184 write_ticks
= wr_svctm
+ wr_wait
;
5186 get_blkio_io_value(io_service_time_str
, major
, minor
, "Total", &tot_ticks
);
5187 tot_ticks
= tot_ticks
/1000000;
5189 memset(lbuf
, 0, 256);
5190 if (read
|| write
|| read_merged
|| write_merged
|| read_sectors
|| write_sectors
|| read_ticks
|| write_ticks
)
5191 snprintf(lbuf
, 256, "%u %u %s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
5192 major
, minor
, dev_name
, read
, read_merged
, read_sectors
, read_ticks
,
5193 write
, write_merged
, write_sectors
, write_ticks
, ios_pgr
, tot_ticks
, rq_ticks
);
5197 l
= snprintf(cache
, cache_size
, "%s", lbuf
);
5199 perror("Error writing to fuse buf");
5203 if (l
>= cache_size
) {
5204 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
5214 d
->size
= total_len
;
5215 if (total_len
> size
) total_len
= size
;
5216 memcpy(buf
, d
->buf
, total_len
);
5224 free(io_serviced_str
);
5225 free(io_merged_str
);
5226 free(io_service_bytes_str
);
5227 free(io_wait_time_str
);
5228 free(io_service_time_str
);
5232 static int proc_swaps_read(char *buf
, size_t size
, off_t offset
,
5233 struct fuse_file_info
*fi
)
5235 struct fuse_context
*fc
= fuse_get_context();
5236 struct file_info
*d
= (struct file_info
*)fi
->fh
;
5238 char *memswlimit_str
= NULL
, *memlimit_str
= NULL
, *memusage_str
= NULL
, *memswusage_str
= NULL
;
5239 unsigned long memswlimit
= 0, memlimit
= 0, memusage
= 0, memswusage
= 0, swap_total
= 0, swap_free
= 0;
5240 ssize_t total_len
= 0, rv
= 0;
5242 char *cache
= d
->buf
;
5245 if (offset
> d
->size
)
5249 int left
= d
->size
- offset
;
5250 total_len
= left
> size
? size
: left
;
5251 memcpy(buf
, cache
+ offset
, total_len
);
5255 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
5258 cg
= get_pid_cgroup(initpid
, "memory");
5260 return read_file("/proc/swaps", buf
, size
, d
);
5261 prune_init_slice(cg
);
5263 memlimit
= get_min_memlimit(cg
, "memory.limit_in_bytes");
5265 if (!cgfs_get_value("memory", cg
, "memory.usage_in_bytes", &memusage_str
))
5268 memusage
= strtoul(memusage_str
, NULL
, 10);
5270 if (cgfs_get_value("memory", cg
, "memory.memsw.usage_in_bytes", &memswusage_str
) &&
5271 cgfs_get_value("memory", cg
, "memory.memsw.limit_in_bytes", &memswlimit_str
)) {
5273 memswlimit
= get_min_memlimit(cg
, "memory.memsw.limit_in_bytes");
5274 memswusage
= strtoul(memswusage_str
, NULL
, 10);
5276 swap_total
= (memswlimit
- memlimit
) / 1024;
5277 swap_free
= (memswusage
- memusage
) / 1024;
5280 total_len
= snprintf(d
->buf
, d
->size
, "Filename\t\t\t\tType\t\tSize\tUsed\tPriority\n");
5282 /* When no mem + swap limit is specified or swapaccount=0*/
5286 FILE *f
= fopen("/proc/meminfo", "r");
5291 while (getline(&line
, &linelen
, f
) != -1) {
5292 if (startswith(line
, "SwapTotal:")) {
5293 sscanf(line
, "SwapTotal: %8lu kB", &swap_total
);
5294 } else if (startswith(line
, "SwapFree:")) {
5295 sscanf(line
, "SwapFree: %8lu kB", &swap_free
);
5303 if (swap_total
> 0) {
5304 l
= snprintf(d
->buf
+ total_len
, d
->size
- total_len
,
5305 "none%*svirtual\t\t%lu\t%lu\t0\n", 36, " ",
5306 swap_total
, swap_free
);
5310 if (total_len
< 0 || l
< 0) {
5311 perror("Error writing to cache");
5317 d
->size
= (int)total_len
;
5319 if (total_len
> size
) total_len
= size
;
5320 memcpy(buf
, d
->buf
, total_len
);
5325 free(memswlimit_str
);
5328 free(memswusage_str
);
5332 * Find the process pid from cgroup path.
5333 * eg:from /sys/fs/cgroup/cpu/docker/containerid/cgroup.procs to find the process pid.
5334 * @pid_buf : put pid to pid_buf.
5335 * @dpath : the path of cgroup. eg: /docker/containerid or /docker/containerid/child-cgroup ...
5336 * @depth : the depth of cgroup in container.
5337 * @sum : return the number of pid.
5338 * @cfd : the file descriptor of the mounted cgroup. eg: /sys/fs/cgroup/cpu
5340 static int calc_pid(char ***pid_buf
, char *dpath
, int depth
, int sum
, int cfd
)
5344 struct dirent
*file
;
5349 char *path_dir
, *path
;
5352 /* path = dpath + "/cgroup.procs" + /0 */
5354 path
= malloc(strlen(dpath
) + 20);
5357 strcpy(path
, dpath
);
5358 fd
= openat(cfd
, path
, O_RDONLY
);
5362 dir
= fdopendir(fd
);
5368 while (((file
= readdir(dir
)) != NULL
) && depth
> 0) {
5369 if (strncmp(file
->d_name
, ".", 1) == 0)
5371 if (strncmp(file
->d_name
, "..", 1) == 0)
5373 if (file
->d_type
== DT_DIR
) {
5374 /* path + '/' + d_name +/0 */
5376 path_dir
= malloc(strlen(path
) + 2 + sizeof(file
->d_name
));
5377 } while (!path_dir
);
5378 strcpy(path_dir
, path
);
5379 strcat(path_dir
, "/");
5380 strcat(path_dir
, file
->d_name
);
5382 sum
= calc_pid(pid_buf
, path_dir
, pd
, sum
, cfd
);
5388 strcat(path
, "/cgroup.procs");
5389 fd
= openat(cfd
, path
, O_RDONLY
);
5393 f
= fdopen(fd
, "r");
5399 while (getline(&line
, &linelen
, f
) != -1) {
5401 pid
= realloc(*pid_buf
, sizeof(char *) * (sum
+ 1));
5405 *(*pid_buf
+ sum
) = malloc(strlen(line
) + 1);
5406 } while (*(*pid_buf
+ sum
) == NULL
);
5407 strcpy(*(*pid_buf
+ sum
), line
);
5418 * calc_load calculates the load according to the following formula:
5419 * load1 = load0 * exp + active * (1 - exp)
5421 * @load1: the new loadavg.
5422 * @load0: the former loadavg.
5423 * @active: the total number of running pid at this moment.
5424 * @exp: the fixed-point defined in the beginning.
5426 static unsigned long
5427 calc_load(unsigned long load
, unsigned long exp
, unsigned long active
)
5429 unsigned long newload
;
5431 active
= active
> 0 ? active
* FIXED_1
: 0;
5432 newload
= load
* exp
+ active
* (FIXED_1
- exp
);
5434 newload
+= FIXED_1
- 1;
5436 return newload
/ FIXED_1
;
5440 * Return 0 means that container p->cg is closed.
5441 * Return -1 means that error occurred in refresh.
5442 * Positive num equals the total number of pid.
5444 static int refresh_load(struct load_node
*p
, char *path
)
5448 char proc_path
[256];
5449 int i
, ret
, run_pid
= 0, total_pid
= 0, last_pid
= 0;
5454 struct dirent
*file
;
5457 idbuf
= malloc(sizeof(char *));
5459 sum
= calc_pid(&idbuf
, path
, DEPTH_DIR
, 0, p
->cfd
);
5464 for (i
= 0; i
< sum
; i
++) {
5466 length
= strlen(idbuf
[i
])-1;
5467 idbuf
[i
][length
] = '\0';
5468 ret
= snprintf(proc_path
, 256, "/proc/%s/task", idbuf
[i
]);
5469 if (ret
< 0 || ret
> 255) {
5470 lxcfs_error("%s\n", "snprintf() failed in refresh_load.");
5476 dp
= opendir(proc_path
);
5478 lxcfs_error("%s\n", "Open proc_path failed in refresh_load.");
5481 while ((file
= readdir(dp
)) != NULL
) {
5482 if (strncmp(file
->d_name
, ".", 1) == 0)
5484 if (strncmp(file
->d_name
, "..", 1) == 0)
5487 /* We make the biggest pid become last_pid.*/
5488 ret
= atof(file
->d_name
);
5489 last_pid
= (ret
> last_pid
) ? ret
: last_pid
;
5491 ret
= snprintf(proc_path
, 256, "/proc/%s/task/%s/status", idbuf
[i
], file
->d_name
);
5492 if (ret
< 0 || ret
> 255) {
5493 lxcfs_error("%s\n", "snprintf() failed in refresh_load.");
5499 f
= fopen(proc_path
, "r");
5501 while (getline(&line
, &linelen
, f
) != -1) {
5503 if ((line
[0] == 'S') && (line
[1] == 't'))
5506 if ((line
[7] == 'R') || (line
[7] == 'D'))
5513 /*Calculate the loadavg.*/
5514 p
->avenrun
[0] = calc_load(p
->avenrun
[0], EXP_1
, run_pid
);
5515 p
->avenrun
[1] = calc_load(p
->avenrun
[1], EXP_5
, run_pid
);
5516 p
->avenrun
[2] = calc_load(p
->avenrun
[2], EXP_15
, run_pid
);
5517 p
->run_pid
= run_pid
;
5518 p
->total_pid
= total_pid
;
5519 p
->last_pid
= last_pid
;
5530 * Traverse the hash table and update it.
5532 void *load_begin(void *arg
)
5536 int i
, sum
, length
, ret
;
5537 struct load_node
*f
;
5539 clock_t time1
, time2
;
5542 if (loadavg_stop
== 1)
5546 for (i
= 0; i
< LOAD_SIZE
; i
++) {
5547 pthread_mutex_lock(&load_hash
[i
].lock
);
5548 if (load_hash
[i
].next
== NULL
) {
5549 pthread_mutex_unlock(&load_hash
[i
].lock
);
5552 f
= load_hash
[i
].next
;
5555 length
= strlen(f
->cg
) + 2;
5557 /* strlen(f->cg) + '.' or '' + \0 */
5558 path
= malloc(length
);
5561 ret
= snprintf(path
, length
, "%s%s", *(f
->cg
) == '/' ? "." : "", f
->cg
);
5562 if (ret
< 0 || ret
> length
- 1) {
5563 /* snprintf failed, ignore the node.*/
5564 lxcfs_error("Refresh node %s failed for snprintf().\n", f
->cg
);
5567 sum
= refresh_load(f
, path
);
5574 /* load_hash[i].lock locks only on the first node.*/
5575 if (first_node
== 1) {
5577 pthread_mutex_unlock(&load_hash
[i
].lock
);
5582 if (loadavg_stop
== 1)
5586 usleep(FLUSH_TIME
* 1000000 - (int)((time2
- time1
) * 1000000 / CLOCKS_PER_SEC
));
5590 static int proc_loadavg_read(char *buf
, size_t size
, off_t offset
,
5591 struct fuse_file_info
*fi
)
5593 struct fuse_context
*fc
= fuse_get_context();
5594 struct file_info
*d
= (struct file_info
*)fi
->fh
;
5597 size_t total_len
= 0;
5598 char *cache
= d
->buf
;
5599 struct load_node
*n
;
5602 unsigned long a
, b
, c
;
5605 if (offset
> d
->size
)
5609 int left
= d
->size
- offset
;
5610 total_len
= left
> size
? size
: left
;
5611 memcpy(buf
, cache
+ offset
, total_len
);
5615 return read_file("/proc/loadavg", buf
, size
, d
);
5617 initpid
= lookup_initpid_in_store(fc
->pid
);
5620 cg
= get_pid_cgroup(initpid
, "cpu");
5622 return read_file("/proc/loadavg", buf
, size
, d
);
5624 prune_init_slice(cg
);
5625 hash
= calc_hash(cg
) % LOAD_SIZE
;
5626 n
= locate_node(cg
, hash
);
5630 if (!find_mounted_controller("cpu", &cfd
)) {
5632 * In locate_node() above, pthread_rwlock_unlock() isn't used
5633 * because delete is not allowed before read has ended.
5635 pthread_rwlock_unlock(&load_hash
[hash
].rdlock
);
5640 n
= malloc(sizeof(struct load_node
));
5644 n
->cg
= malloc(strlen(cg
)+1);
5652 n
->last_pid
= initpid
;
5654 insert_node(&n
, hash
);
5656 a
= n
->avenrun
[0] + (FIXED_1
/200);
5657 b
= n
->avenrun
[1] + (FIXED_1
/200);
5658 c
= n
->avenrun
[2] + (FIXED_1
/200);
5659 total_len
= snprintf(d
->buf
, d
->buflen
, "%lu.%02lu %lu.%02lu %lu.%02lu %d/%d %d\n",
5660 LOAD_INT(a
), LOAD_FRAC(a
),
5661 LOAD_INT(b
), LOAD_FRAC(b
),
5662 LOAD_INT(c
), LOAD_FRAC(c
),
5663 n
->run_pid
, n
->total_pid
, n
->last_pid
);
5664 pthread_rwlock_unlock(&load_hash
[hash
].rdlock
);
5665 if (total_len
< 0 || total_len
>= d
->buflen
) {
5666 lxcfs_error("%s\n", "Failed to write to cache");
5670 d
->size
= (int)total_len
;
5673 if (total_len
> size
)
5675 memcpy(buf
, d
->buf
, total_len
);
5682 /* Return a positive number on success, return 0 on failure.*/
5683 pthread_t
load_daemon(int load_use
)
5690 lxcfs_error("%s\n", "Initialize hash_table fails in load_daemon!");
5693 ret
= pthread_create(&pid
, NULL
, load_begin
, NULL
);
5695 lxcfs_error("%s\n", "Create pthread fails in load_daemon!");
5699 /* use loadavg, here loadavg = 1*/
5704 /* Returns 0 on success. */
5705 int stop_load_daemon(pthread_t pid
)
5709 /* Signal the thread to gracefully stop */
5712 s
= pthread_join(pid
, NULL
); /* Make sure sub thread has been canceled. */
5714 lxcfs_error("%s\n", "stop_load_daemon error: failed to join");
5724 static off_t
get_procfile_size(const char *which
)
5726 FILE *f
= fopen(which
, "r");
5729 ssize_t sz
, answer
= 0;
5733 while ((sz
= getline(&line
, &len
, f
)) != -1)
5741 int proc_getattr(const char *path
, struct stat
*sb
)
5743 struct timespec now
;
5745 memset(sb
, 0, sizeof(struct stat
));
5746 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
5748 sb
->st_uid
= sb
->st_gid
= 0;
5749 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
5750 if (strcmp(path
, "/proc") == 0) {
5751 sb
->st_mode
= S_IFDIR
| 00555;
5755 if (strcmp(path
, "/proc/meminfo") == 0 ||
5756 strcmp(path
, "/proc/cpuinfo") == 0 ||
5757 strcmp(path
, "/proc/uptime") == 0 ||
5758 strcmp(path
, "/proc/stat") == 0 ||
5759 strcmp(path
, "/proc/diskstats") == 0 ||
5760 strcmp(path
, "/proc/swaps") == 0 ||
5761 strcmp(path
, "/proc/loadavg") == 0) {
5763 sb
->st_mode
= S_IFREG
| 00444;
5771 int proc_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
5772 struct fuse_file_info
*fi
)
5774 if (filler(buf
, ".", NULL
, 0) != 0 ||
5775 filler(buf
, "..", NULL
, 0) != 0 ||
5776 filler(buf
, "cpuinfo", NULL
, 0) != 0 ||
5777 filler(buf
, "meminfo", NULL
, 0) != 0 ||
5778 filler(buf
, "stat", NULL
, 0) != 0 ||
5779 filler(buf
, "uptime", NULL
, 0) != 0 ||
5780 filler(buf
, "diskstats", NULL
, 0) != 0 ||
5781 filler(buf
, "swaps", NULL
, 0) != 0 ||
5782 filler(buf
, "loadavg", NULL
, 0) != 0)
5787 int proc_open(const char *path
, struct fuse_file_info
*fi
)
5790 struct file_info
*info
;
5792 if (strcmp(path
, "/proc/meminfo") == 0)
5793 type
= LXC_TYPE_PROC_MEMINFO
;
5794 else if (strcmp(path
, "/proc/cpuinfo") == 0)
5795 type
= LXC_TYPE_PROC_CPUINFO
;
5796 else if (strcmp(path
, "/proc/uptime") == 0)
5797 type
= LXC_TYPE_PROC_UPTIME
;
5798 else if (strcmp(path
, "/proc/stat") == 0)
5799 type
= LXC_TYPE_PROC_STAT
;
5800 else if (strcmp(path
, "/proc/diskstats") == 0)
5801 type
= LXC_TYPE_PROC_DISKSTATS
;
5802 else if (strcmp(path
, "/proc/swaps") == 0)
5803 type
= LXC_TYPE_PROC_SWAPS
;
5804 else if (strcmp(path
, "/proc/loadavg") == 0)
5805 type
= LXC_TYPE_PROC_LOADAVG
;
5809 info
= malloc(sizeof(*info
));
5813 memset(info
, 0, sizeof(*info
));
5816 info
->buflen
= get_procfile_size(path
) + BUF_RESERVE_SIZE
;
5818 info
->buf
= malloc(info
->buflen
);
5819 } while (!info
->buf
);
5820 memset(info
->buf
, 0, info
->buflen
);
5821 /* set actual size to buffer size */
5822 info
->size
= info
->buflen
;
5824 fi
->fh
= (unsigned long)info
;
5828 int proc_access(const char *path
, int mask
)
5830 if (strcmp(path
, "/proc") == 0 && access(path
, R_OK
) == 0)
5833 /* these are all read-only */
5834 if ((mask
& ~R_OK
) != 0)
5839 int proc_release(const char *path
, struct fuse_file_info
*fi
)
5841 do_release_file_info(fi
);
5845 int proc_read(const char *path
, char *buf
, size_t size
, off_t offset
,
5846 struct fuse_file_info
*fi
)
5848 struct file_info
*f
= (struct file_info
*) fi
->fh
;
5851 case LXC_TYPE_PROC_MEMINFO
:
5852 return proc_meminfo_read(buf
, size
, offset
, fi
);
5853 case LXC_TYPE_PROC_CPUINFO
:
5854 return proc_cpuinfo_read(buf
, size
, offset
, fi
);
5855 case LXC_TYPE_PROC_UPTIME
:
5856 return proc_uptime_read(buf
, size
, offset
, fi
);
5857 case LXC_TYPE_PROC_STAT
:
5858 return proc_stat_read(buf
, size
, offset
, fi
);
5859 case LXC_TYPE_PROC_DISKSTATS
:
5860 return proc_diskstats_read(buf
, size
, offset
, fi
);
5861 case LXC_TYPE_PROC_SWAPS
:
5862 return proc_swaps_read(buf
, size
, offset
, fi
);
5863 case LXC_TYPE_PROC_LOADAVG
:
5864 return proc_loadavg_read(buf
, size
, offset
, fi
);
5871 * Functions needed to setup cgroups in the __constructor__.
5874 static bool mkdir_p(const char *dir
, mode_t mode
)
5876 const char *tmp
= dir
;
5877 const char *orig
= dir
;
5881 dir
= tmp
+ strspn(tmp
, "/");
5882 tmp
= dir
+ strcspn(dir
, "/");
5883 makeme
= strndup(orig
, dir
- orig
);
5886 if (mkdir(makeme
, mode
) && errno
!= EEXIST
) {
5887 lxcfs_error("Failed to create directory '%s': %s.\n",
5888 makeme
, strerror(errno
));
5893 } while(tmp
!= dir
);
5898 static bool umount_if_mounted(void)
5900 if (umount2(BASEDIR
, MNT_DETACH
) < 0 && errno
!= EINVAL
) {
5901 lxcfs_error("Failed to unmount %s: %s.\n", BASEDIR
, strerror(errno
));
5907 /* __typeof__ should be safe to use with all compilers. */
5908 typedef __typeof__(((struct statfs
*)NULL
)->f_type
) fs_type_magic
;
5909 static bool has_fs_type(const struct statfs
*fs
, fs_type_magic magic_val
)
5911 return (fs
->f_type
== (fs_type_magic
)magic_val
);
5915 * looking at fs/proc_namespace.c, it appears we can
5916 * actually expect the rootfs entry to very specifically contain
5917 * " - rootfs rootfs "
5918 * IIUC, so long as we've chrooted so that rootfs is not our root,
5919 * the rootfs entry should always be skipped in mountinfo contents.
5921 static bool is_on_ramfs(void)
5929 f
= fopen("/proc/self/mountinfo", "r");
5933 while (getline(&line
, &len
, f
) != -1) {
5934 for (p
= line
, i
= 0; p
&& i
< 4; i
++)
5935 p
= strchr(p
+ 1, ' ');
5938 p2
= strchr(p
+ 1, ' ');
5942 if (strcmp(p
+ 1, "/") == 0) {
5943 // this is '/'. is it the ramfs?
5944 p
= strchr(p2
+ 1, '-');
5945 if (p
&& strncmp(p
, "- rootfs rootfs ", 16) == 0) {
5957 static int pivot_enter()
5959 int ret
= -1, oldroot
= -1, newroot
= -1;
5961 oldroot
= open("/", O_DIRECTORY
| O_RDONLY
);
5963 lxcfs_error("%s\n", "Failed to open old root for fchdir.");
5967 newroot
= open(ROOTDIR
, O_DIRECTORY
| O_RDONLY
);
5969 lxcfs_error("%s\n", "Failed to open new root for fchdir.");
5973 /* change into new root fs */
5974 if (fchdir(newroot
) < 0) {
5975 lxcfs_error("Failed to change directory to new rootfs: %s.\n", ROOTDIR
);
5979 /* pivot_root into our new root fs */
5980 if (pivot_root(".", ".") < 0) {
5981 lxcfs_error("pivot_root() syscall failed: %s.\n", strerror(errno
));
5986 * At this point the old-root is mounted on top of our new-root.
5987 * To unmounted it we must not be chdir'd into it, so escape back
5990 if (fchdir(oldroot
) < 0) {
5991 lxcfs_error("%s\n", "Failed to enter old root.");
5995 if (umount2(".", MNT_DETACH
) < 0) {
5996 lxcfs_error("%s\n", "Failed to detach old root.");
6000 if (fchdir(newroot
) < 0) {
6001 lxcfs_error("%s\n", "Failed to re-enter new root.");
6016 static int chroot_enter()
6018 if (mount(ROOTDIR
, "/", NULL
, MS_REC
| MS_BIND
, NULL
)) {
6019 lxcfs_error("Failed to recursively bind-mount %s into /.", ROOTDIR
);
6023 if (chroot(".") < 0) {
6024 lxcfs_error("Call to chroot() failed: %s.\n", strerror(errno
));
6028 if (chdir("/") < 0) {
6029 lxcfs_error("Failed to change directory: %s.\n", strerror(errno
));
6036 static int permute_and_enter(void)
6040 if (statfs("/", &sb
) < 0) {
6041 lxcfs_error("%s\n", "Could not stat / mountpoint.");
6045 /* has_fs_type() is not reliable. When the ramfs is a tmpfs it will
6046 * likely report TMPFS_MAGIC. Hence, when it reports no we still check
6047 * /proc/1/mountinfo. */
6048 if (has_fs_type(&sb
, RAMFS_MAGIC
) || is_on_ramfs())
6049 return chroot_enter();
6051 if (pivot_enter() < 0) {
6052 lxcfs_error("%s\n", "Could not perform pivot root.");
6059 /* Prepare our new clean root. */
6060 static int permute_prepare(void)
6062 if (mkdir(ROOTDIR
, 0700) < 0 && errno
!= EEXIST
) {
6063 lxcfs_error("%s\n", "Failed to create directory for new root.");
6067 if (mount("/", ROOTDIR
, NULL
, MS_BIND
, 0) < 0) {
6068 lxcfs_error("Failed to bind-mount / for new root: %s.\n", strerror(errno
));
6072 if (mount(RUNTIME_PATH
, ROOTDIR RUNTIME_PATH
, NULL
, MS_BIND
, 0) < 0) {
6073 lxcfs_error("Failed to bind-mount /run into new root: %s.\n", strerror(errno
));
6077 if (mount(BASEDIR
, ROOTDIR BASEDIR
, NULL
, MS_REC
| MS_MOVE
, 0) < 0) {
6078 printf("Failed to move " BASEDIR
" into new root: %s.\n", strerror(errno
));
6085 /* Calls chroot() on ramfs, pivot_root() in all other cases. */
6086 static bool permute_root(void)
6088 /* Prepare new root. */
6089 if (permute_prepare() < 0)
6092 /* Pivot into new root. */
6093 if (permute_and_enter() < 0)
6099 static int preserve_mnt_ns(int pid
)
6102 size_t len
= sizeof("/proc/") + 21 + sizeof("/ns/mnt");
6105 ret
= snprintf(path
, len
, "/proc/%d/ns/mnt", pid
);
6106 if (ret
< 0 || (size_t)ret
>= len
)
6109 return open(path
, O_RDONLY
| O_CLOEXEC
);
6112 static bool cgfs_prepare_mounts(void)
6114 if (!mkdir_p(BASEDIR
, 0700)) {
6115 lxcfs_error("%s\n", "Failed to create lxcfs cgroup mountpoint.");
6119 if (!umount_if_mounted()) {
6120 lxcfs_error("%s\n", "Failed to clean up old lxcfs cgroup mountpoint.");
6124 if (unshare(CLONE_NEWNS
) < 0) {
6125 lxcfs_error("Failed to unshare mount namespace: %s.\n", strerror(errno
));
6129 cgroup_mount_ns_fd
= preserve_mnt_ns(getpid());
6130 if (cgroup_mount_ns_fd
< 0) {
6131 lxcfs_error("Failed to preserve mount namespace: %s.\n", strerror(errno
));
6135 if (mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, 0) < 0) {
6136 lxcfs_error("Failed to remount / private: %s.\n", strerror(errno
));
6140 if (mount("tmpfs", BASEDIR
, "tmpfs", 0, "size=100000,mode=700") < 0) {
6141 lxcfs_error("%s\n", "Failed to mount tmpfs over lxcfs cgroup mountpoint.");
6148 static bool cgfs_mount_hierarchies(void)
6154 for (i
= 0; i
< num_hierarchies
; i
++) {
6155 char *controller
= hierarchies
[i
];
6157 clen
= strlen(controller
);
6158 len
= strlen(BASEDIR
) + clen
+ 2;
6159 target
= malloc(len
);
6163 ret
= snprintf(target
, len
, "%s/%s", BASEDIR
, controller
);
6164 if (ret
< 0 || ret
>= len
) {
6168 if (mkdir(target
, 0755) < 0 && errno
!= EEXIST
) {
6172 if (!strcmp(controller
, "unified"))
6173 ret
= mount("none", target
, "cgroup2", 0, NULL
);
6175 ret
= mount(controller
, target
, "cgroup", 0, controller
);
6177 lxcfs_error("Failed mounting cgroup %s: %s\n", controller
, strerror(errno
));
6182 fd_hierarchies
[i
] = open(target
, O_DIRECTORY
);
6183 if (fd_hierarchies
[i
] < 0) {
6192 static bool cgfs_setup_controllers(void)
6194 if (!cgfs_prepare_mounts())
6197 if (!cgfs_mount_hierarchies()) {
6198 lxcfs_error("%s\n", "Failed to set up private lxcfs cgroup mounts.");
6202 if (!permute_root())
6208 static void __attribute__((constructor
)) collect_and_mount_subsystems(void)
6211 char *cret
, *line
= NULL
;
6212 char cwd
[MAXPATHLEN
];
6214 int i
, init_ns
= -1;
6215 bool found_unified
= false;
6217 if ((f
= fopen("/proc/self/cgroup", "r")) == NULL
) {
6218 lxcfs_error("Error opening /proc/self/cgroup: %s\n", strerror(errno
));
6222 while (getline(&line
, &len
, f
) != -1) {
6225 p
= strchr(line
, ':');
6231 p2
= strrchr(p
, ':');
6236 /* With cgroupv2 /proc/self/cgroup can contain entries of the
6237 * form: 0::/ This will cause lxcfs to fail the cgroup mounts
6238 * because it parses out the empty string "" and later on passes
6239 * it to mount(). Let's skip such entries.
6241 if (!strcmp(p
, "") && !strcmp(idx
, "0") && !found_unified
) {
6242 found_unified
= true;
6246 if (!store_hierarchy(line
, p
))
6250 /* Preserve initial namespace. */
6251 init_ns
= preserve_mnt_ns(getpid());
6253 lxcfs_error("%s\n", "Failed to preserve initial mount namespace.");
6257 fd_hierarchies
= malloc(sizeof(int) * num_hierarchies
);
6258 if (!fd_hierarchies
) {
6259 lxcfs_error("%s\n", strerror(errno
));
6263 for (i
= 0; i
< num_hierarchies
; i
++)
6264 fd_hierarchies
[i
] = -1;
6266 cret
= getcwd(cwd
, MAXPATHLEN
);
6268 lxcfs_debug("Could not retrieve current working directory: %s.\n", strerror(errno
));
6270 /* This function calls unshare(CLONE_NEWNS) our initial mount namespace
6271 * to privately mount lxcfs cgroups. */
6272 if (!cgfs_setup_controllers()) {
6273 lxcfs_error("%s\n", "Failed to setup private cgroup mounts for lxcfs.");
6277 if (setns(init_ns
, 0) < 0) {
6278 lxcfs_error("Failed to switch back to initial mount namespace: %s.\n", strerror(errno
));
6282 if (!cret
|| chdir(cwd
) < 0)
6283 lxcfs_debug("Could not change back to original working directory: %s.\n", strerror(errno
));
6285 if (!init_cpuview()) {
6286 lxcfs_error("%s\n", "failed to init CPU view");
6299 static void __attribute__((destructor
)) free_subsystems(void)
6303 lxcfs_debug("%s\n", "Running destructor for liblxcfs.");
6305 for (i
= 0; i
< num_hierarchies
; i
++) {
6307 free(hierarchies
[i
]);
6308 if (fd_hierarchies
&& fd_hierarchies
[i
] >= 0)
6309 close(fd_hierarchies
[i
]);
6312 free(fd_hierarchies
);
6315 if (cgroup_mount_ns_fd
>= 0)
6316 close(cgroup_mount_ns_fd
);