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
29 #include <linux/magic.h>
30 #include <linux/sched.h>
31 #include <sys/epoll.h>
33 #include <sys/mount.h>
34 #include <sys/param.h>
35 #include <sys/socket.h>
36 #include <sys/syscall.h>
37 #include <sys/sysinfo.h>
42 #include "cgroups/cgroup.h"
43 #include "cgroups/cgroup_utils.h"
44 #include "memory_utils.h"
47 /* Define pivot_root() if missing from the C library */
48 #ifndef HAVE_PIVOT_ROOT
49 static int pivot_root(const char * new_root
, const char * put_old
)
51 #ifdef __NR_pivot_root
52 return syscall(__NR_pivot_root
, new_root
, put_old
);
59 extern int pivot_root(const char * new_root
, const char * put_old
);
62 struct cpuacct_usage
{
69 /* The function of hash table.*/
70 #define LOAD_SIZE 100 /*the size of hash_table */
71 #define FLUSH_TIME 5 /*the flush rate */
72 #define DEPTH_DIR 3 /*the depth of per cgroup */
73 /* The function of calculate loadavg .*/
74 #define FSHIFT 11 /* nr of bits of precision */
75 #define FIXED_1 (1<<FSHIFT) /* 1.0 as fixed-point */
76 #define EXP_1 1884 /* 1/exp(5sec/1min) as fixed-point */
77 #define EXP_5 2014 /* 1/exp(5sec/5min) */
78 #define EXP_15 2037 /* 1/exp(5sec/15min) */
79 #define LOAD_INT(x) ((x) >> FSHIFT)
80 #define LOAD_FRAC(x) LOAD_INT(((x) & (FIXED_1-1)) * 100)
82 * This parameter is used for proc_loadavg_read().
83 * 1 means use loadavg, 0 means not use.
85 static int loadavg
= 0;
86 static volatile sig_atomic_t loadavg_stop
= 0;
87 static int calc_hash(const char *name
)
89 unsigned int hash
= 0;
91 /* ELFHash algorithm. */
93 hash
= (hash
<< 4) + *name
++;
94 x
= hash
& 0xf0000000;
99 return (hash
& 0x7fffffff);
104 unsigned long avenrun
[3]; /* Load averages */
105 unsigned int run_pid
;
106 unsigned int total_pid
;
107 unsigned int last_pid
;
108 int cfd
; /* The file descriptor of the mounted cgroup */
109 struct load_node
*next
;
110 struct load_node
**pre
;
115 * The lock is about insert load_node and refresh load_node.To the first
116 * load_node of each hash bucket, insert and refresh in this hash bucket is
117 * mutually exclusive.
119 pthread_mutex_t lock
;
121 * The rdlock is about read loadavg and delete load_node.To each hash
122 * bucket, read and delete is mutually exclusive. But at the same time, we
123 * allow paratactic read operation. This rdlock is at list level.
125 pthread_rwlock_t rdlock
;
127 * The rilock is about read loadavg and insert load_node.To the first
128 * load_node of each hash bucket, read and insert is mutually exclusive.
129 * But at the same time, we allow paratactic read operation.
131 pthread_rwlock_t rilock
;
132 struct load_node
*next
;
135 static struct load_head load_hash
[LOAD_SIZE
]; /* hash table */
137 * init_load initialize the hash table.
138 * Return 0 on success, return -1 on failure.
140 static int init_load(void)
145 for (i
= 0; i
< LOAD_SIZE
; i
++) {
146 load_hash
[i
].next
= NULL
;
147 ret
= pthread_mutex_init(&load_hash
[i
].lock
, NULL
);
149 lxcfs_error("%s\n", "Failed to initialize lock");
152 ret
= pthread_rwlock_init(&load_hash
[i
].rdlock
, NULL
);
154 lxcfs_error("%s\n", "Failed to initialize rdlock");
157 ret
= pthread_rwlock_init(&load_hash
[i
].rilock
, NULL
);
159 lxcfs_error("%s\n", "Failed to initialize rilock");
165 pthread_rwlock_destroy(&load_hash
[i
].rdlock
);
167 pthread_mutex_destroy(&load_hash
[i
].lock
);
171 pthread_mutex_destroy(&load_hash
[i
].lock
);
172 pthread_rwlock_destroy(&load_hash
[i
].rdlock
);
173 pthread_rwlock_destroy(&load_hash
[i
].rilock
);
178 static void insert_node(struct load_node
**n
, int locate
)
182 pthread_mutex_lock(&load_hash
[locate
].lock
);
183 pthread_rwlock_wrlock(&load_hash
[locate
].rilock
);
184 f
= load_hash
[locate
].next
;
185 load_hash
[locate
].next
= *n
;
187 (*n
)->pre
= &(load_hash
[locate
].next
);
189 f
->pre
= &((*n
)->next
);
191 pthread_mutex_unlock(&load_hash
[locate
].lock
);
192 pthread_rwlock_unlock(&load_hash
[locate
].rilock
);
195 * locate_node() finds special node. Not return NULL means success.
196 * It should be noted that rdlock isn't unlocked at the end of code
197 * because this function is used to read special node. Delete is not
198 * allowed before read has ended.
199 * unlock rdlock only in proc_loadavg_read().
201 static struct load_node
*locate_node(char *cg
, int locate
)
203 struct load_node
*f
= NULL
;
206 pthread_rwlock_rdlock(&load_hash
[locate
].rilock
);
207 pthread_rwlock_rdlock(&load_hash
[locate
].rdlock
);
208 if (load_hash
[locate
].next
== NULL
) {
209 pthread_rwlock_unlock(&load_hash
[locate
].rilock
);
212 f
= load_hash
[locate
].next
;
213 pthread_rwlock_unlock(&load_hash
[locate
].rilock
);
214 while (f
&& ((i
= strcmp(f
->cg
, cg
)) != 0))
219 /* Delete the load_node n and return the next node of it. */
220 static struct load_node
*del_node(struct load_node
*n
, int locate
)
224 pthread_rwlock_wrlock(&load_hash
[locate
].rdlock
);
225 if (n
->next
== NULL
) {
229 n
->next
->pre
= n
->pre
;
234 pthread_rwlock_unlock(&load_hash
[locate
].rdlock
);
238 static void load_free(void)
240 struct load_node
*f
, *p
;
242 for (int i
= 0; i
< LOAD_SIZE
; i
++) {
243 pthread_mutex_lock(&load_hash
[i
].lock
);
244 pthread_rwlock_wrlock(&load_hash
[i
].rilock
);
245 pthread_rwlock_wrlock(&load_hash
[i
].rdlock
);
246 if (load_hash
[i
].next
== NULL
) {
247 pthread_mutex_unlock(&load_hash
[i
].lock
);
248 pthread_mutex_destroy(&load_hash
[i
].lock
);
249 pthread_rwlock_unlock(&load_hash
[i
].rilock
);
250 pthread_rwlock_destroy(&load_hash
[i
].rilock
);
251 pthread_rwlock_unlock(&load_hash
[i
].rdlock
);
252 pthread_rwlock_destroy(&load_hash
[i
].rdlock
);
256 for (f
= load_hash
[i
].next
; f
;) {
263 pthread_mutex_unlock(&load_hash
[i
].lock
);
264 pthread_mutex_destroy(&load_hash
[i
].lock
);
265 pthread_rwlock_unlock(&load_hash
[i
].rilock
);
266 pthread_rwlock_destroy(&load_hash
[i
].rilock
);
267 pthread_rwlock_unlock(&load_hash
[i
].rdlock
);
268 pthread_rwlock_destroy(&load_hash
[i
].rdlock
);
272 /* Data for CPU view */
273 struct cg_proc_stat
{
275 struct cpuacct_usage
*usage
; // Real usage as read from the host's /proc/stat
276 struct cpuacct_usage
*view
; // Usage stats reported to the container
278 pthread_mutex_t lock
; // For node manipulation
279 struct cg_proc_stat
*next
;
282 struct cg_proc_stat_head
{
283 struct cg_proc_stat
*next
;
287 * For access to the list. Reading can be parallel, pruning is exclusive.
289 pthread_rwlock_t lock
;
292 #define CPUVIEW_HASH_SIZE 100
293 static struct cg_proc_stat_head
*proc_stat_history
[CPUVIEW_HASH_SIZE
];
295 static bool cpuview_init_head(struct cg_proc_stat_head
**head
)
297 *head
= malloc(sizeof(struct cg_proc_stat_head
));
299 lxcfs_error("%s\n", strerror(errno
));
303 (*head
)->lastcheck
= time(NULL
);
304 (*head
)->next
= NULL
;
306 if (pthread_rwlock_init(&(*head
)->lock
, NULL
) != 0) {
307 lxcfs_error("%s\n", "Failed to initialize list lock");
315 static bool init_cpuview()
319 for (i
= 0; i
< CPUVIEW_HASH_SIZE
; i
++)
320 proc_stat_history
[i
] = NULL
;
322 for (i
= 0; i
< CPUVIEW_HASH_SIZE
; i
++) {
323 if (!cpuview_init_head(&proc_stat_history
[i
]))
330 for (i
= 0; i
< CPUVIEW_HASH_SIZE
; i
++) {
331 if (proc_stat_history
[i
])
332 free_disarm(proc_stat_history
[i
]);
338 static void free_proc_stat_node(struct cg_proc_stat
*node
)
340 pthread_mutex_destroy(&node
->lock
);
341 free_disarm(node
->cg
);
342 free_disarm(node
->usage
);
343 free_disarm(node
->view
);
347 static void cpuview_free_head(struct cg_proc_stat_head
*head
)
349 struct cg_proc_stat
*node
, *tmp
;
357 free_proc_stat_node(tmp
);
364 pthread_rwlock_destroy(&head
->lock
);
368 static void free_cpuview()
372 for (i
= 0; i
< CPUVIEW_HASH_SIZE
; i
++) {
373 if (proc_stat_history
[i
])
374 cpuview_free_head(proc_stat_history
[i
]);
379 * A table caching which pid is init for a pid namespace.
380 * When looking up which pid is init for $qpid, we first
381 * 1. Stat /proc/$qpid/ns/pid.
382 * 2. Check whether the ino_t is in our store.
383 * a. if not, fork a child in qpid's ns to send us
384 * ucred.pid = 1, and read the initpid. Cache
385 * initpid and creation time for /proc/initpid
386 * in a new store entry.
387 * b. if so, verify that /proc/initpid still matches
388 * what we have saved. If not, clear the store
389 * entry and go back to a. If so, return the
392 struct pidns_init_store
{
393 ino_t ino
; // inode number for /proc/$pid/ns/pid
394 pid_t initpid
; // the pid of nit in that ns
395 long int ctime
; // the time at which /proc/$initpid was created
396 struct pidns_init_store
*next
;
400 /* lol - look at how they are allocated in the kernel */
401 #define PIDNS_HASH_SIZE 4096
402 #define HASH(x) ((x) % PIDNS_HASH_SIZE)
404 static struct pidns_init_store
*pidns_hash_table
[PIDNS_HASH_SIZE
];
405 static pthread_mutex_t pidns_store_mutex
= PTHREAD_MUTEX_INITIALIZER
;
406 static void lock_mutex(pthread_mutex_t
*l
)
410 if ((ret
= pthread_mutex_lock(l
)) != 0) {
411 lxcfs_error("returned:%d %s\n", ret
, strerror(ret
));
416 struct cgroup_ops
*cgroup_ops
;
418 static void unlock_mutex(pthread_mutex_t
*l
)
422 if ((ret
= pthread_mutex_unlock(l
)) != 0) {
423 lxcfs_error("returned:%d %s\n", ret
, strerror(ret
));
428 static void store_lock(void)
430 lock_mutex(&pidns_store_mutex
);
433 static void store_unlock(void)
435 unlock_mutex(&pidns_store_mutex
);
438 /* Must be called under store_lock */
439 static bool initpid_still_valid(struct pidns_init_store
*e
, struct stat
*nsfdsb
)
444 snprintf(fnam
, 100, "/proc/%d", e
->initpid
);
445 if (stat(fnam
, &initsb
) < 0)
448 lxcfs_debug("Comparing ctime %ld == %ld for pid %d.\n", e
->ctime
,
449 initsb
.st_ctime
, e
->initpid
);
451 if (e
->ctime
!= initsb
.st_ctime
)
456 /* Must be called under store_lock */
457 static void remove_initpid(struct pidns_init_store
*e
)
459 struct pidns_init_store
*tmp
;
462 lxcfs_debug("Remove_initpid: removing entry for %d.\n", e
->initpid
);
465 if (pidns_hash_table
[h
] == e
) {
466 pidns_hash_table
[h
] = e
->next
;
471 tmp
= pidns_hash_table
[h
];
473 if (tmp
->next
== e
) {
483 /* Must be called under store_lock */
484 static void prune_initpid_store(void)
486 static long int last_prune
= 0;
487 struct pidns_init_store
*e
, *prev
, *delme
;
488 long int now
, threshold
;
492 last_prune
= time(NULL
);
496 if (now
< last_prune
+ PURGE_SECS
)
499 lxcfs_debug("%s\n", "Pruning.");
502 threshold
= now
- 2 * PURGE_SECS
;
504 for (i
= 0; i
< PIDNS_HASH_SIZE
; i
++) {
505 for (prev
= NULL
, e
= pidns_hash_table
[i
]; e
; ) {
506 if (e
->lastcheck
< threshold
) {
508 lxcfs_debug("Removing cached entry for %d.\n", e
->initpid
);
512 prev
->next
= e
->next
;
514 pidns_hash_table
[i
] = e
->next
;
525 /* Must be called under store_lock */
526 static void save_initpid(struct stat
*sb
, pid_t pid
)
528 struct pidns_init_store
*e
;
533 lxcfs_debug("Save_initpid: adding entry for %d.\n", pid
);
535 snprintf(fpath
, 100, "/proc/%d", pid
);
536 if (stat(fpath
, &procsb
) < 0)
539 e
= malloc(sizeof(*e
));
543 e
->ctime
= procsb
.st_ctime
;
545 e
->next
= pidns_hash_table
[h
];
546 e
->lastcheck
= time(NULL
);
547 pidns_hash_table
[h
] = e
;
551 * Given the stat(2) info for a nsfd pid inode, lookup the init_pid_store
552 * entry for the inode number and creation time. Verify that the init pid
553 * is still valid. If not, remove it. Return the entry if valid, NULL
555 * Must be called under store_lock
557 static struct pidns_init_store
*lookup_verify_initpid(struct stat
*sb
)
559 int h
= HASH(sb
->st_ino
);
560 struct pidns_init_store
*e
= pidns_hash_table
[h
];
563 if (e
->ino
== sb
->st_ino
) {
564 if (initpid_still_valid(e
, sb
)) {
565 e
->lastcheck
= time(NULL
);
577 static int is_dir(const char *path
, int fd
)
580 int ret
= fstatat(fd
, path
, &statbuf
, fd
);
581 if (ret
== 0 && S_ISDIR(statbuf
.st_mode
))
586 static bool write_string(const char *fnam
, const char *string
, int fd
)
595 len
= strlen(string
);
596 ret
= fwrite(string
, 1, len
, f
);
598 lxcfs_error("%s - Error writing \"%s\" to \"%s\"\n",
599 strerror(errno
), string
, fnam
);
605 lxcfs_error("%s - Failed to close \"%s\"\n", strerror(errno
), fnam
);
618 static void print_subsystems(void)
622 fprintf(stderr
, "mount namespace: %d\n", cgroup_ops
->mntns_fd
);
623 fprintf(stderr
, "hierarchies:\n");
624 for (struct hierarchy
**h
= cgroup_ops
->hierarchies
; h
&& *h
; h
++, i
++) {
625 __do_free
char *controllers
= lxc_string_join(",", (const char **)(*h
)->controllers
, false);
626 fprintf(stderr
, " %2d: fd: %3d: %s\n", i
, (*h
)->fd
, controllers
?: "");
630 bool cgfs_set_value(const char *controller
, const char *cgroup
, const char *file
,
637 cfd
= get_cgroup_fd(controller
);
641 /* Make sure we pass a relative path to *at() family of functions.
642 * . + /cgroup + / + file + \0
644 len
= strlen(cgroup
) + strlen(file
) + 3;
646 ret
= snprintf(fnam
, len
, "%s%s/%s", dot_or_empty(cgroup
), cgroup
, file
);
647 if (ret
< 0 || (size_t)ret
>= len
)
650 fd
= openat(cfd
, fnam
, O_WRONLY
);
654 return write_string(fnam
, value
, fd
);
657 // Chown all the files in the cgroup directory. We do this when we create
658 // a cgroup on behalf of a user.
659 static void chown_all_cgroup_files(const char *dirname
, uid_t uid
, gid_t gid
, int fd
)
661 struct dirent
*direntp
;
662 char path
[MAXPATHLEN
];
667 len
= strlen(dirname
);
668 if (len
>= MAXPATHLEN
) {
669 lxcfs_error("Pathname too long: %s\n", dirname
);
673 fd1
= openat(fd
, dirname
, O_DIRECTORY
);
679 lxcfs_error("Failed to open %s\n", dirname
);
683 while ((direntp
= readdir(d
))) {
684 if (!strcmp(direntp
->d_name
, ".") || !strcmp(direntp
->d_name
, ".."))
686 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
687 if (ret
< 0 || ret
>= MAXPATHLEN
) {
688 lxcfs_error("Pathname too long under %s\n", dirname
);
691 if (fchownat(fd
, path
, uid
, gid
, 0) < 0)
692 lxcfs_error("Failed to chown file %s to %u:%u", path
, uid
, gid
);
697 int cgfs_create(const char *controller
, const char *cg
, uid_t uid
, gid_t gid
)
703 cfd
= get_cgroup_fd(controller
);
707 /* Make sure we pass a relative path to *at() family of functions.
710 len
= strlen(cg
) + 2;
711 dirnam
= alloca(len
);
712 snprintf(dirnam
, len
, "%s%s", dot_or_empty(cg
), cg
);
714 if (mkdirat(cfd
, dirnam
, 0755) < 0)
717 if (uid
== 0 && gid
== 0)
720 if (fchownat(cfd
, dirnam
, uid
, gid
, 0) < 0)
723 chown_all_cgroup_files(dirnam
, uid
, gid
, cfd
);
728 static bool recursive_rmdir(const char *dirname
, int fd
, const int cfd
)
730 struct dirent
*direntp
;
733 char pathname
[MAXPATHLEN
];
736 dupfd
= dup(fd
); // fdopendir() does bad things once it uses an fd.
740 dir
= fdopendir(dupfd
);
742 lxcfs_debug("Failed to open %s: %s.\n", dirname
, strerror(errno
));
747 while ((direntp
= readdir(dir
))) {
751 if (!strcmp(direntp
->d_name
, ".") ||
752 !strcmp(direntp
->d_name
, ".."))
755 rc
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
756 if (rc
< 0 || rc
>= MAXPATHLEN
) {
757 lxcfs_error("%s\n", "Pathname too long.");
761 rc
= fstatat(cfd
, pathname
, &mystat
, AT_SYMLINK_NOFOLLOW
);
763 lxcfs_debug("Failed to stat %s: %s.\n", pathname
, strerror(errno
));
766 if (S_ISDIR(mystat
.st_mode
))
767 if (!recursive_rmdir(pathname
, fd
, cfd
))
768 lxcfs_debug("Error removing %s.\n", pathname
);
772 if (closedir(dir
) < 0) {
773 lxcfs_error("Failed to close directory %s: %s\n", dirname
, strerror(errno
));
777 if (unlinkat(cfd
, dirname
, AT_REMOVEDIR
) < 0) {
778 lxcfs_debug("Failed to delete %s: %s.\n", dirname
, strerror(errno
));
787 bool cgfs_remove(const char *controller
, const char *cg
)
794 cfd
= get_cgroup_fd(controller
);
798 /* Make sure we pass a relative path to *at() family of functions.
801 len
= strlen(cg
) + 2;
802 dirnam
= alloca(len
);
803 snprintf(dirnam
, len
, "%s%s", dot_or_empty(cg
), cg
);
805 fd
= openat(cfd
, dirnam
, O_DIRECTORY
);
809 bret
= recursive_rmdir(dirnam
, fd
, cfd
);
814 bool cgfs_chmod_file(const char *controller
, const char *file
, mode_t mode
)
820 cfd
= get_cgroup_fd(controller
);
824 /* Make sure we pass a relative path to *at() family of functions.
827 len
= strlen(file
) + 2;
828 pathname
= alloca(len
);
829 snprintf(pathname
, len
, "%s%s", dot_or_empty(file
), file
);
830 if (fchmodat(cfd
, pathname
, mode
, 0) < 0)
835 static int chown_tasks_files(const char *dirname
, uid_t uid
, gid_t gid
, int fd
)
840 len
= strlen(dirname
) + strlen("/cgroup.procs") + 1;
842 snprintf(fname
, len
, "%s/tasks", dirname
);
843 if (fchownat(fd
, fname
, uid
, gid
, 0) != 0)
845 snprintf(fname
, len
, "%s/cgroup.procs", dirname
);
846 if (fchownat(fd
, fname
, uid
, gid
, 0) != 0)
851 int cgfs_chown_file(const char *controller
, const char *file
, uid_t uid
, gid_t gid
)
857 cfd
= get_cgroup_fd(controller
);
861 /* Make sure we pass a relative path to *at() family of functions.
864 len
= strlen(file
) + 2;
865 pathname
= alloca(len
);
866 snprintf(pathname
, len
, "%s%s", dot_or_empty(file
), file
);
867 if (fchownat(cfd
, pathname
, uid
, gid
, 0) < 0)
870 if (is_dir(pathname
, cfd
))
871 // like cgmanager did, we want to chown the tasks file as well
872 return chown_tasks_files(pathname
, uid
, gid
, cfd
);
877 FILE *open_pids_file(const char *controller
, const char *cgroup
)
883 cfd
= get_cgroup_fd(controller
);
887 /* Make sure we pass a relative path to *at() family of functions.
888 * . + /cgroup + / "cgroup.procs" + \0
890 len
= strlen(cgroup
) + strlen("cgroup.procs") + 3;
891 pathname
= alloca(len
);
892 snprintf(pathname
, len
, "%s%s/cgroup.procs", dot_or_empty(cgroup
), cgroup
);
894 fd
= openat(cfd
, pathname
, O_WRONLY
);
898 return fdopen(fd
, "w");
901 static bool cgfs_iterate_cgroup(const char *controller
, const char *cgroup
, bool directories
,
902 void ***list
, size_t typesize
,
903 void* (*iterator
)(const char*, const char*, const char*))
908 char pathname
[MAXPATHLEN
];
909 size_t sz
= 0, asz
= 0;
910 struct dirent
*dirent
;
913 cfd
= get_cgroup_fd(controller
);
918 /* Make sure we pass a relative path to *at() family of functions. */
919 len
= strlen(cgroup
) + 1 /* . */ + 1 /* \0 */;
921 ret
= snprintf(cg
, len
, "%s%s", dot_or_empty(cgroup
), cgroup
);
922 if (ret
< 0 || (size_t)ret
>= len
) {
923 lxcfs_error("Pathname too long under %s\n", cgroup
);
927 fd
= openat(cfd
, cg
, O_DIRECTORY
);
935 while ((dirent
= readdir(dir
))) {
938 if (!strcmp(dirent
->d_name
, ".") ||
939 !strcmp(dirent
->d_name
, ".."))
942 ret
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", cg
, dirent
->d_name
);
943 if (ret
< 0 || ret
>= MAXPATHLEN
) {
944 lxcfs_error("Pathname too long under %s\n", cg
);
948 ret
= fstatat(cfd
, pathname
, &mystat
, AT_SYMLINK_NOFOLLOW
);
950 lxcfs_error("Failed to stat %s: %s\n", pathname
, strerror(errno
));
953 if ((!directories
&& !S_ISREG(mystat
.st_mode
)) ||
954 (directories
&& !S_ISDIR(mystat
.st_mode
)))
961 tmp
= realloc(*list
, asz
* typesize
);
965 (*list
)[sz
] = (*iterator
)(controller
, cg
, dirent
->d_name
);
966 (*list
)[sz
+1] = NULL
;
969 if (closedir(dir
) < 0) {
970 lxcfs_error("Failed closedir for %s: %s\n", cgroup
, strerror(errno
));
976 static void *make_children_list_entry(const char *controller
, const char *cgroup
, const char *dir_entry
)
980 dup
= strdup(dir_entry
);
985 bool cgfs_list_children(const char *controller
, const char *cgroup
, char ***list
)
987 return cgfs_iterate_cgroup(controller
, cgroup
, true, (void***)list
, sizeof(*list
), &make_children_list_entry
);
990 void free_key(struct cgfs_files
*k
)
994 free_disarm(k
->name
);
998 void free_keys(struct cgfs_files
**keys
)
1004 for (i
= 0; keys
[i
]; i
++) {
1010 bool cgfs_param_exist(const char *controller
, const char *cgroup
, const char *file
)
1016 cfd
= get_cgroup_fd(controller
);
1020 /* Make sure we pass a relative path to *at() family of functions.
1021 * . + /cgroup + / + file + \0
1023 len
= strlen(cgroup
) + strlen(file
) + 3;
1025 ret
= snprintf(fnam
, len
, "%s%s/%s", dot_or_empty(cgroup
), cgroup
, file
);
1026 if (ret
< 0 || (size_t)ret
>= len
)
1029 return (faccessat(cfd
, fnam
, F_OK
, 0) == 0);
1032 struct cgfs_files
*cgfs_get_key(const char *controller
, const char *cgroup
, const char *file
)
1038 struct cgfs_files
*newkey
;
1040 cfd
= get_cgroup_fd(controller
);
1044 if (file
&& *file
== '/')
1047 if (file
&& strchr(file
, '/'))
1050 /* Make sure we pass a relative path to *at() family of functions.
1051 * . + /cgroup + / + file + \0
1053 len
= strlen(cgroup
) + 3;
1055 len
+= strlen(file
) + 1;
1057 snprintf(fnam
, len
, "%s%s%s%s", dot_or_empty(cgroup
), cgroup
,
1058 file
? "/" : "", file
? file
: "");
1060 ret
= fstatat(cfd
, fnam
, &sb
, 0);
1065 newkey
= malloc(sizeof(struct cgfs_files
));
1068 newkey
->name
= must_copy_string(file
);
1069 else if (strrchr(cgroup
, '/'))
1070 newkey
->name
= must_copy_string(strrchr(cgroup
, '/'));
1072 newkey
->name
= must_copy_string(cgroup
);
1073 newkey
->uid
= sb
.st_uid
;
1074 newkey
->gid
= sb
.st_gid
;
1075 newkey
->mode
= sb
.st_mode
;
1080 static void *make_key_list_entry(const char *controller
, const char *cgroup
, const char *dir_entry
)
1082 struct cgfs_files
*entry
= cgfs_get_key(controller
, cgroup
, dir_entry
);
1084 lxcfs_error("Error getting files under %s:%s\n", controller
,
1090 bool cgfs_list_keys(const char *controller
, const char *cgroup
, struct cgfs_files
***keys
)
1092 return cgfs_iterate_cgroup(controller
, cgroup
, false, (void***)keys
, sizeof(*keys
), &make_key_list_entry
);
1095 bool is_child_cgroup(const char *controller
, const char *cgroup
, const char *f
)
1103 cfd
= get_cgroup_fd(controller
);
1107 /* Make sure we pass a relative path to *at() family of functions.
1108 * . + /cgroup + / + f + \0
1110 len
= strlen(cgroup
) + strlen(f
) + 3;
1112 ret
= snprintf(fnam
, len
, "%s%s/%s", dot_or_empty(cgroup
), cgroup
, f
);
1113 if (ret
< 0 || (size_t)ret
>= len
)
1116 ret
= fstatat(cfd
, fnam
, &sb
, 0);
1117 if (ret
< 0 || !S_ISDIR(sb
.st_mode
))
1123 #define SEND_CREDS_OK 0
1124 #define SEND_CREDS_NOTSK 1
1125 #define SEND_CREDS_FAIL 2
1126 static bool recv_creds(int sock
, struct ucred
*cred
, char *v
);
1127 static int wait_for_pid(pid_t pid
);
1128 static int send_creds(int sock
, struct ucred
*cred
, char v
, bool pingfirst
);
1129 static int send_creds_clone_wrapper(void *arg
);
1132 * clone a task which switches to @task's namespace and writes '1'.
1133 * over a unix sock so we can read the task's reaper's pid in our
1136 * Note: glibc's fork() does not respect pidns, which can lead to failed
1137 * assertions inside glibc (and thus failed forks) if the child's pid in
1138 * the pidns and the parent pid outside are identical. Using clone prevents
1141 static void write_task_init_pid_exit(int sock
, pid_t target
)
1146 size_t stack_size
= sysconf(_SC_PAGESIZE
);
1147 void *stack
= alloca(stack_size
);
1149 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", (int)target
);
1150 if (ret
< 0 || ret
>= sizeof(fnam
))
1153 fd
= open(fnam
, O_RDONLY
);
1155 perror("write_task_init_pid_exit open of ns/pid");
1159 perror("write_task_init_pid_exit setns 1");
1163 pid
= clone(send_creds_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &sock
);
1167 if (!wait_for_pid(pid
))
1173 static int send_creds_clone_wrapper(void *arg
) {
1176 int sock
= *(int *)arg
;
1178 /* we are the child */
1183 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
)
1188 static pid_t
get_init_pid_for_task(pid_t task
)
1196 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
1197 perror("socketpair");
1206 write_task_init_pid_exit(sock
[0], task
);
1210 if (!recv_creds(sock
[1], &cred
, &v
))
1222 pid_t
lookup_initpid_in_store(pid_t qpid
)
1226 struct pidns_init_store
*e
;
1229 snprintf(fnam
, 100, "/proc/%d/ns/pid", qpid
);
1231 if (stat(fnam
, &sb
) < 0)
1233 e
= lookup_verify_initpid(&sb
);
1235 answer
= e
->initpid
;
1238 answer
= get_init_pid_for_task(qpid
);
1240 save_initpid(&sb
, answer
);
1243 /* we prune at end in case we are returning
1244 * the value we were about to return */
1245 prune_initpid_store();
1250 static int wait_for_pid(pid_t pid
)
1258 ret
= waitpid(pid
, &status
, 0);
1266 if (!WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
1273 * append pid to *src.
1274 * src: a pointer to a char* in which ot append the pid.
1275 * sz: the number of characters printed so far, minus trailing \0.
1276 * asz: the allocated size so far
1277 * pid: the pid to append
1279 static void must_strcat_pid(char **src
, size_t *sz
, size_t *asz
, pid_t pid
)
1281 must_strcat(src
, sz
, asz
, "%d\n", (int)pid
);
1285 * Given a open file * to /proc/pid/{u,g}id_map, and an id
1286 * valid in the caller's namespace, return the id mapped into
1288 * Returns the mapped id, or -1 on error.
1291 convert_id_to_ns(FILE *idfile
, unsigned int in_id
)
1293 unsigned int nsuid
, // base id for a range in the idfile's namespace
1294 hostuid
, // base id for a range in the caller's namespace
1295 count
; // number of ids in this range
1299 fseek(idfile
, 0L, SEEK_SET
);
1300 while (fgets(line
, 400, idfile
)) {
1301 ret
= sscanf(line
, "%u %u %u\n", &nsuid
, &hostuid
, &count
);
1304 if (hostuid
+ count
< hostuid
|| nsuid
+ count
< nsuid
) {
1306 * uids wrapped around - unexpected as this is a procfile,
1309 lxcfs_error("pid wrapparound at entry %u %u %u in %s\n",
1310 nsuid
, hostuid
, count
, line
);
1313 if (hostuid
<= in_id
&& hostuid
+count
> in_id
) {
1315 * now since hostuid <= in_id < hostuid+count, and
1316 * hostuid+count and nsuid+count do not wrap around,
1317 * we know that nsuid+(in_id-hostuid) which must be
1318 * less that nsuid+(count) must not wrap around
1320 return (in_id
- hostuid
) + nsuid
;
1329 * for is_privileged_over,
1330 * specify whether we require the calling uid to be root in his
1333 #define NS_ROOT_REQD true
1334 #define NS_ROOT_OPT false
1338 static bool is_privileged_over(pid_t pid
, uid_t uid
, uid_t victim
, bool req_ns_root
)
1340 char fpath
[PROCLEN
];
1342 bool answer
= false;
1345 if (victim
== -1 || uid
== -1)
1349 * If the request is one not requiring root in the namespace,
1350 * then having the same uid suffices. (i.e. uid 1000 has write
1351 * access to files owned by uid 1000
1353 if (!req_ns_root
&& uid
== victim
)
1356 ret
= snprintf(fpath
, PROCLEN
, "/proc/%d/uid_map", pid
);
1357 if (ret
< 0 || ret
>= PROCLEN
)
1359 FILE *f
= fopen(fpath
, "r");
1363 /* if caller's not root in his namespace, reject */
1364 nsuid
= convert_id_to_ns(f
, uid
);
1369 * If victim is not mapped into caller's ns, reject.
1370 * XXX I'm not sure this check is needed given that fuse
1371 * will be sending requests where the vfs has converted
1373 nsuid
= convert_id_to_ns(f
, victim
);
1384 static bool perms_include(int fmode
, mode_t req_mode
)
1388 switch (req_mode
& O_ACCMODE
) {
1396 r
= S_IROTH
| S_IWOTH
;
1401 return ((fmode
& r
) == r
);
1407 * querycg is /a/b/c/d/e
1410 static char *get_next_cgroup_dir(const char *taskcg
, const char *querycg
)
1414 if (strlen(taskcg
) <= strlen(querycg
)) {
1415 lxcfs_error("%s\n", "I was fed bad input.");
1419 if ((strcmp(querycg
, "/") == 0) || (strcmp(querycg
, "./") == 0))
1420 start
= strdup(taskcg
+ 1);
1422 start
= strdup(taskcg
+ strlen(querycg
) + 1);
1425 end
= strchr(start
, '/');
1431 char *get_pid_cgroup(pid_t pid
, const char *contrl
)
1435 cfd
= get_cgroup_fd(contrl
);
1439 if (pure_unified_layout(cgroup_ops
))
1440 return cg_unified_get_current_cgroup(pid
);
1442 return cg_legacy_get_current_cgroup(pid
, contrl
);
1446 * check whether a fuse context may access a cgroup dir or file
1448 * If file is not null, it is a cgroup file to check under cg.
1449 * If file is null, then we are checking perms on cg itself.
1451 * For files we can check the mode of the list_keys result.
1452 * For cgroups, we must make assumptions based on the files under the
1453 * cgroup, because cgmanager doesn't tell us ownership/perms of cgroups
1456 static bool fc_may_access(struct fuse_context
*fc
, const char *contrl
, const char *cg
, const char *file
, mode_t mode
)
1458 struct cgfs_files
*k
= NULL
;
1461 k
= cgfs_get_key(contrl
, cg
, file
);
1465 if (is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
1466 if (perms_include(k
->mode
>> 6, mode
)) {
1471 if (fc
->gid
== k
->gid
) {
1472 if (perms_include(k
->mode
>> 3, mode
)) {
1477 ret
= perms_include(k
->mode
, mode
);
1484 #define INITSCOPE "/init.scope"
1485 void prune_init_slice(char *cg
)
1488 size_t cg_len
= strlen(cg
), initscope_len
= strlen(INITSCOPE
);
1490 if (cg_len
< initscope_len
)
1493 point
= cg
+ cg_len
- initscope_len
;
1494 if (strcmp(point
, INITSCOPE
) == 0) {
1503 * If pid is in /a/b/c/d, he may only act on things under cg=/a/b/c/d.
1504 * If pid is in /a, he may act on /a/b, but not on /b.
1505 * if the answer is false and nextcg is not NULL, then *nextcg will point
1506 * to a string containing the next cgroup directory under cg, which must be
1507 * freed by the caller.
1509 static bool caller_is_in_ancestor(pid_t pid
, const char *contrl
, const char *cg
, char **nextcg
)
1511 bool answer
= false;
1512 char *c2
= get_pid_cgroup(pid
, contrl
);
1517 prune_init_slice(c2
);
1520 * callers pass in '/' or './' (openat()) for root cgroup, otherwise
1521 * they pass in a cgroup without leading '/'
1523 * The original line here was:
1524 * linecmp = *cg == '/' ? c2 : c2+1;
1525 * TODO: I'm not sure why you'd want to increment when *cg != '/'?
1526 * Serge, do you know?
1528 if (*cg
== '/' || !strncmp(cg
, "./", 2))
1532 if (strncmp(linecmp
, cg
, strlen(linecmp
)) != 0) {
1534 *nextcg
= get_next_cgroup_dir(linecmp
, cg
);
1546 * If pid is in /a/b/c, he may see that /a exists, but not /b or /a/c.
1548 static bool caller_may_see_dir(pid_t pid
, const char *contrl
, const char *cg
)
1550 bool answer
= false;
1552 size_t target_len
, task_len
;
1554 if (strcmp(cg
, "/") == 0 || strcmp(cg
, "./") == 0)
1557 c2
= get_pid_cgroup(pid
, contrl
);
1560 prune_init_slice(c2
);
1563 target_len
= strlen(cg
);
1564 task_len
= strlen(task_cg
);
1565 if (task_len
== 0) {
1566 /* Task is in the root cg, it can see everything. This case is
1567 * not handled by the strmcps below, since they test for the
1568 * last /, but that is the first / that we've chopped off
1574 if (strcmp(cg
, task_cg
) == 0) {
1578 if (target_len
< task_len
) {
1579 /* looking up a parent dir */
1580 if (strncmp(task_cg
, cg
, target_len
) == 0 && task_cg
[target_len
] == '/')
1584 if (target_len
> task_len
) {
1585 /* looking up a child dir */
1586 if (strncmp(task_cg
, cg
, task_len
) == 0 && cg
[task_len
] == '/')
1597 * given /cgroup/freezer/a/b, return "freezer".
1598 * the returned char* should NOT be freed.
1600 static char *pick_controller_from_path(struct fuse_context
*fc
, const char *path
)
1603 char *contr
, *slash
;
1605 if (strlen(path
) < 9) {
1609 if (*(path
+ 7) != '/') {
1614 contr
= strdupa(p1
);
1619 slash
= strstr(contr
, "/");
1623 for (struct hierarchy
**h
= cgroup_ops
->hierarchies
; h
&& *h
; h
++) {
1624 if ((*h
)->__controllers
&& strcmp((*h
)->__controllers
, contr
) == 0)
1625 return (*h
)->__controllers
;
1632 * Find the start of cgroup in /cgroup/controller/the/cgroup/path
1633 * Note that the returned value may include files (keynames) etc
1635 static const char *find_cgroup_in_path(const char *path
)
1639 if (strlen(path
) < 9) {
1643 p1
= strstr(path
+ 8, "/");
1653 * split the last path element from the path in @cg.
1654 * @dir is newly allocated and should be freed, @last not
1656 static void get_cgdir_and_path(const char *cg
, char **dir
, char **last
)
1663 *last
= strrchr(cg
, '/');
1668 p
= strrchr(*dir
, '/');
1673 * FUSE ops for /cgroup
1676 int cg_getattr(const char *path
, struct stat
*sb
)
1678 struct timespec now
;
1679 struct fuse_context
*fc
= fuse_get_context();
1680 char * cgdir
= NULL
;
1681 char *last
= NULL
, *path1
, *path2
;
1682 struct cgfs_files
*k
= NULL
;
1684 const char *controller
= NULL
;
1688 if (!fc
|| !cgroup_ops
|| pure_unified_layout(cgroup_ops
))
1691 memset(sb
, 0, sizeof(struct stat
));
1693 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
1696 sb
->st_uid
= sb
->st_gid
= 0;
1697 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
1700 if (strcmp(path
, "/cgroup") == 0) {
1701 sb
->st_mode
= S_IFDIR
| 00755;
1706 controller
= pick_controller_from_path(fc
, path
);
1709 cgroup
= find_cgroup_in_path(path
);
1711 /* this is just /cgroup/controller, return it as a dir */
1712 sb
->st_mode
= S_IFDIR
| 00755;
1717 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
1727 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1728 if (initpid
<= 1 || is_shared_pidns(initpid
))
1730 /* check that cgcopy is either a child cgroup of cgdir, or listed in its keys.
1731 * Then check that caller's cgroup is under path if last is a child
1732 * cgroup, or cgdir if last is a file */
1734 if (is_child_cgroup(controller
, path1
, path2
)) {
1735 if (!caller_may_see_dir(initpid
, controller
, cgroup
)) {
1739 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, NULL
)) {
1740 /* this is just /cgroup/controller, return it as a dir */
1741 sb
->st_mode
= S_IFDIR
| 00555;
1746 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
)) {
1751 // get uid, gid, from '/tasks' file and make up a mode
1752 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
1753 sb
->st_mode
= S_IFDIR
| 00755;
1754 k
= cgfs_get_key(controller
, cgroup
, NULL
);
1756 sb
->st_uid
= sb
->st_gid
= 0;
1758 sb
->st_uid
= k
->uid
;
1759 sb
->st_gid
= k
->gid
;
1767 if ((k
= cgfs_get_key(controller
, path1
, path2
)) != NULL
) {
1768 sb
->st_mode
= S_IFREG
| k
->mode
;
1770 sb
->st_uid
= k
->uid
;
1771 sb
->st_gid
= k
->gid
;
1774 if (!caller_is_in_ancestor(initpid
, controller
, path1
, NULL
)) {
1786 int cg_opendir(const char *path
, struct fuse_file_info
*fi
)
1788 struct fuse_context
*fc
= fuse_get_context();
1790 struct file_info
*dir_info
;
1791 char *controller
= NULL
;
1793 if (!fc
|| !cgroup_ops
|| pure_unified_layout(cgroup_ops
))
1796 if (strcmp(path
, "/cgroup") == 0) {
1800 // return list of keys for the controller, and list of child cgroups
1801 controller
= pick_controller_from_path(fc
, path
);
1805 cgroup
= find_cgroup_in_path(path
);
1807 /* this is just /cgroup/controller, return its contents */
1812 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1813 if (initpid
<= 1 || is_shared_pidns(initpid
))
1816 if (!caller_may_see_dir(initpid
, controller
, cgroup
))
1818 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
))
1822 /* we'll free this at cg_releasedir */
1823 dir_info
= malloc(sizeof(*dir_info
));
1826 dir_info
->controller
= must_copy_string(controller
);
1827 dir_info
->cgroup
= must_copy_string(cgroup
);
1828 dir_info
->type
= LXC_TYPE_CGDIR
;
1829 dir_info
->buf
= NULL
;
1830 dir_info
->file
= NULL
;
1831 dir_info
->buflen
= 0;
1833 fi
->fh
= (unsigned long)dir_info
;
1837 int cg_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
1838 struct fuse_file_info
*fi
)
1840 struct file_info
*d
= (struct file_info
*)fi
->fh
;
1841 struct cgfs_files
**list
= NULL
;
1843 char *nextcg
= NULL
;
1844 struct fuse_context
*fc
= fuse_get_context();
1845 char **clist
= NULL
;
1847 if (!fc
|| !cgroup_ops
|| pure_unified_layout(cgroup_ops
))
1850 if (filler(buf
, ".", NULL
, 0) != 0 || filler(buf
, "..", NULL
, 0) != 0)
1853 if (d
->type
!= LXC_TYPE_CGDIR
) {
1854 lxcfs_error("%s\n", "Internal error: file cache info used in readdir.");
1857 if (!d
->cgroup
&& !d
->controller
) {
1859 * ls /var/lib/lxcfs/cgroup - just show list of controllers.
1860 * This only works with the legacy hierarchy.
1862 for (struct hierarchy
**h
= cgroup_ops
->hierarchies
; h
&& *h
; h
++) {
1863 if (is_unified_hierarchy(*h
))
1866 if ((*h
)->__controllers
&& filler(buf
, (*h
)->__controllers
, NULL
, 0))
1873 if (!cgfs_list_keys(d
->controller
, d
->cgroup
, &list
)) {
1874 // not a valid cgroup
1879 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1880 if (initpid
<= 1 || is_shared_pidns(initpid
))
1882 if (!caller_is_in_ancestor(initpid
, d
->controller
, d
->cgroup
, &nextcg
)) {
1884 ret
= filler(buf
, nextcg
, NULL
, 0);
1895 for (i
= 0; list
&& list
[i
]; i
++) {
1896 if (filler(buf
, list
[i
]->name
, NULL
, 0) != 0) {
1902 // now get the list of child cgroups
1904 if (!cgfs_list_children(d
->controller
, d
->cgroup
, &clist
)) {
1909 for (i
= 0; clist
[i
]; i
++) {
1910 if (filler(buf
, clist
[i
], NULL
, 0) != 0) {
1921 for (i
= 0; clist
[i
]; i
++)
1928 void do_release_file_info(struct fuse_file_info
*fi
)
1930 struct file_info
*f
= (struct file_info
*)fi
->fh
;
1937 free_disarm(f
->controller
);
1938 free_disarm(f
->cgroup
);
1939 free_disarm(f
->file
);
1940 free_disarm(f
->buf
);
1944 int cg_releasedir(const char *path
, struct fuse_file_info
*fi
)
1946 do_release_file_info(fi
);
1950 int cg_open(const char *path
, struct fuse_file_info
*fi
)
1953 char *last
= NULL
, *path1
, *path2
, * cgdir
= NULL
, *controller
;
1954 struct cgfs_files
*k
= NULL
;
1955 struct file_info
*file_info
;
1956 struct fuse_context
*fc
= fuse_get_context();
1959 if (!fc
|| !cgroup_ops
|| pure_unified_layout(cgroup_ops
))
1962 controller
= pick_controller_from_path(fc
, path
);
1965 cgroup
= find_cgroup_in_path(path
);
1969 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
1978 k
= cgfs_get_key(controller
, path1
, path2
);
1985 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1986 if (initpid
<= 1 || is_shared_pidns(initpid
))
1988 if (!caller_may_see_dir(initpid
, controller
, path1
)) {
1992 if (!fc_may_access(fc
, controller
, path1
, path2
, fi
->flags
)) {
1997 /* we'll free this at cg_release */
1998 file_info
= malloc(sizeof(*file_info
));
2003 file_info
->controller
= must_copy_string(controller
);
2004 file_info
->cgroup
= must_copy_string(path1
);
2005 file_info
->file
= must_copy_string(path2
);
2006 file_info
->type
= LXC_TYPE_CGFILE
;
2007 file_info
->buf
= NULL
;
2008 file_info
->buflen
= 0;
2010 fi
->fh
= (unsigned long)file_info
;
2018 int cg_access(const char *path
, int mode
)
2022 char *path1
, *path2
, *controller
;
2023 char *last
= NULL
, *cgdir
= NULL
;
2024 struct cgfs_files
*k
= NULL
;
2025 struct fuse_context
*fc
= fuse_get_context();
2027 if (!fc
|| !cgroup_ops
|| pure_unified_layout(cgroup_ops
))
2030 if (strcmp(path
, "/cgroup") == 0)
2033 controller
= pick_controller_from_path(fc
, path
);
2036 cgroup
= find_cgroup_in_path(path
);
2038 // access("/sys/fs/cgroup/systemd", mode) - rx allowed, w not
2039 if ((mode
& W_OK
) == 0)
2044 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2053 k
= cgfs_get_key(controller
, path1
, path2
);
2055 if ((mode
& W_OK
) == 0)
2063 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2064 if (initpid
<= 1 || is_shared_pidns(initpid
))
2066 if (!caller_may_see_dir(initpid
, controller
, path1
)) {
2070 if (!fc_may_access(fc
, controller
, path1
, path2
, mode
)) {
2082 int cg_release(const char *path
, struct fuse_file_info
*fi
)
2084 do_release_file_info(fi
);
2088 #define POLLIN_SET ( EPOLLIN | EPOLLHUP | EPOLLRDHUP )
2090 static bool wait_for_sock(int sock
, int timeout
)
2092 struct epoll_event ev
;
2093 int epfd
, ret
, now
, starttime
, deltatime
, saved_errno
;
2095 if ((starttime
= time(NULL
)) < 0)
2098 if ((epfd
= epoll_create(1)) < 0) {
2099 lxcfs_error("%s\n", "Failed to create epoll socket: %m.");
2103 ev
.events
= POLLIN_SET
;
2105 if (epoll_ctl(epfd
, EPOLL_CTL_ADD
, sock
, &ev
) < 0) {
2106 lxcfs_error("%s\n", "Failed adding socket to epoll: %m.");
2112 if ((now
= time(NULL
)) < 0) {
2117 deltatime
= (starttime
+ timeout
) - now
;
2118 if (deltatime
< 0) { // timeout
2123 ret
= epoll_wait(epfd
, &ev
, 1, 1000*deltatime
+ 1);
2124 if (ret
< 0 && errno
== EINTR
)
2126 saved_errno
= errno
;
2130 errno
= saved_errno
;
2136 static int msgrecv(int sockfd
, void *buf
, size_t len
)
2138 if (!wait_for_sock(sockfd
, 2))
2140 return recv(sockfd
, buf
, len
, MSG_DONTWAIT
);
2143 static int send_creds(int sock
, struct ucred
*cred
, char v
, bool pingfirst
)
2145 struct msghdr msg
= { 0 };
2147 struct cmsghdr
*cmsg
;
2148 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
2153 if (msgrecv(sock
, buf
, 1) != 1) {
2154 lxcfs_error("%s\n", "Error getting reply from server over socketpair.");
2155 return SEND_CREDS_FAIL
;
2159 msg
.msg_control
= cmsgbuf
;
2160 msg
.msg_controllen
= sizeof(cmsgbuf
);
2162 cmsg
= CMSG_FIRSTHDR(&msg
);
2163 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct ucred
));
2164 cmsg
->cmsg_level
= SOL_SOCKET
;
2165 cmsg
->cmsg_type
= SCM_CREDENTIALS
;
2166 memcpy(CMSG_DATA(cmsg
), cred
, sizeof(*cred
));
2168 msg
.msg_name
= NULL
;
2169 msg
.msg_namelen
= 0;
2173 iov
.iov_len
= sizeof(buf
);
2177 if (sendmsg(sock
, &msg
, 0) < 0) {
2178 lxcfs_error("Failed at sendmsg: %s.\n",strerror(errno
));
2180 return SEND_CREDS_NOTSK
;
2181 return SEND_CREDS_FAIL
;
2184 return SEND_CREDS_OK
;
2187 static bool recv_creds(int sock
, struct ucred
*cred
, char *v
)
2189 struct msghdr msg
= { 0 };
2191 struct cmsghdr
*cmsg
;
2192 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
2203 if (setsockopt(sock
, SOL_SOCKET
, SO_PASSCRED
, &optval
, sizeof(optval
)) == -1) {
2204 lxcfs_error("Failed to set passcred: %s\n", strerror(errno
));
2208 if (write(sock
, buf
, 1) != 1) {
2209 lxcfs_error("Failed to start write on scm fd: %s\n", strerror(errno
));
2213 msg
.msg_name
= NULL
;
2214 msg
.msg_namelen
= 0;
2215 msg
.msg_control
= cmsgbuf
;
2216 msg
.msg_controllen
= sizeof(cmsgbuf
);
2219 iov
.iov_len
= sizeof(buf
);
2223 if (!wait_for_sock(sock
, 2)) {
2224 lxcfs_error("Timed out waiting for scm_cred: %s\n", strerror(errno
));
2227 ret
= recvmsg(sock
, &msg
, MSG_DONTWAIT
);
2229 lxcfs_error("Failed to receive scm_cred: %s\n", strerror(errno
));
2233 cmsg
= CMSG_FIRSTHDR(&msg
);
2235 if (cmsg
&& cmsg
->cmsg_len
== CMSG_LEN(sizeof(struct ucred
)) &&
2236 cmsg
->cmsg_level
== SOL_SOCKET
&&
2237 cmsg
->cmsg_type
== SCM_CREDENTIALS
) {
2238 memcpy(cred
, CMSG_DATA(cmsg
), sizeof(*cred
));
2245 struct pid_ns_clone_args
{
2249 int (*wrapped
) (int, pid_t
); // pid_from_ns or pid_to_ns
2253 * pid_ns_clone_wrapper - wraps pid_to_ns or pid_from_ns for usage
2254 * with clone(). This simply writes '1' as ACK back to the parent
2255 * before calling the actual wrapped function.
2257 static int pid_ns_clone_wrapper(void *arg
) {
2258 struct pid_ns_clone_args
* args
= (struct pid_ns_clone_args
*) arg
;
2261 close(args
->cpipe
[0]);
2262 if (write(args
->cpipe
[1], &b
, sizeof(char)) < 0)
2263 lxcfs_error("(child): error on write: %s.\n", strerror(errno
));
2264 close(args
->cpipe
[1]);
2265 return args
->wrapped(args
->sock
, args
->tpid
);
2269 * pid_to_ns - reads pids from a ucred over a socket, then writes the
2270 * int value back over the socket. This shifts the pid from the
2271 * sender's pidns into tpid's pidns.
2273 static int pid_to_ns(int sock
, pid_t tpid
)
2278 while (recv_creds(sock
, &cred
, &v
)) {
2281 if (write(sock
, &cred
.pid
, sizeof(pid_t
)) != sizeof(pid_t
))
2289 * pid_to_ns_wrapper: when you setns into a pidns, you yourself remain
2290 * in your old pidns. Only children which you clone will be in the target
2291 * pidns. So the pid_to_ns_wrapper does the setns, then clones a child to
2292 * actually convert pids.
2294 * Note: glibc's fork() does not respect pidns, which can lead to failed
2295 * assertions inside glibc (and thus failed forks) if the child's pid in
2296 * the pidns and the parent pid outside are identical. Using clone prevents
2299 static void pid_to_ns_wrapper(int sock
, pid_t tpid
)
2301 int newnsfd
= -1, ret
, cpipe
[2];
2306 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
2307 if (ret
< 0 || ret
>= sizeof(fnam
))
2309 newnsfd
= open(fnam
, O_RDONLY
);
2312 if (setns(newnsfd
, 0) < 0)
2316 if (pipe(cpipe
) < 0)
2319 struct pid_ns_clone_args args
= {
2323 .wrapped
= &pid_to_ns
2325 size_t stack_size
= sysconf(_SC_PAGESIZE
);
2326 void *stack
= alloca(stack_size
);
2328 cpid
= clone(pid_ns_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &args
);
2332 // give the child 1 second to be done forking and
2334 if (!wait_for_sock(cpipe
[0], 1))
2336 ret
= read(cpipe
[0], &v
, 1);
2337 if (ret
!= sizeof(char) || v
!= '1')
2340 if (!wait_for_pid(cpid
))
2346 * To read cgroup files with a particular pid, we will setns into the child
2347 * pidns, open a pipe, fork a child - which will be the first to really be in
2348 * the child ns - which does the cgfs_get_value and writes the data to the pipe.
2350 bool do_read_pids(pid_t tpid
, const char *contrl
, const char *cg
, const char *file
, char **d
)
2352 int sock
[2] = {-1, -1};
2353 char *tmpdata
= NULL
;
2355 pid_t qpid
, cpid
= -1;
2356 bool answer
= false;
2359 size_t sz
= 0, asz
= 0;
2361 if (!cgroup_ops
->get(cgroup_ops
, contrl
, cg
, file
, &tmpdata
))
2365 * Now we read the pids from returned data one by one, pass
2366 * them into a child in the target namespace, read back the
2367 * translated pids, and put them into our to-return data
2370 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
2371 perror("socketpair");
2380 if (!cpid
) // child - exits when done
2381 pid_to_ns_wrapper(sock
[1], tpid
);
2383 char *ptr
= tmpdata
;
2386 while (sscanf(ptr
, "%d\n", &qpid
) == 1) {
2388 ret
= send_creds(sock
[0], &cred
, v
, true);
2390 if (ret
== SEND_CREDS_NOTSK
)
2392 if (ret
== SEND_CREDS_FAIL
)
2395 // read converted results
2396 if (!wait_for_sock(sock
[0], 2)) {
2397 lxcfs_error("Timed out waiting for pid from child: %s.\n", strerror(errno
));
2400 if (read(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
2401 lxcfs_error("Error reading pid from child: %s.\n", strerror(errno
));
2404 must_strcat_pid(d
, &sz
, &asz
, qpid
);
2406 ptr
= strchr(ptr
, '\n');
2412 cred
.pid
= getpid();
2414 if (send_creds(sock
[0], &cred
, v
, true) != SEND_CREDS_OK
) {
2415 // failed to ask child to exit
2416 lxcfs_error("Failed to ask child to exit: %s.\n", strerror(errno
));
2426 if (sock
[0] != -1) {
2433 int cg_read(const char *path
, char *buf
, size_t size
, off_t offset
,
2434 struct fuse_file_info
*fi
)
2436 struct fuse_context
*fc
= fuse_get_context();
2437 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2438 struct cgfs_files
*k
= NULL
;
2443 if (!fc
|| !cgroup_ops
|| pure_unified_layout(cgroup_ops
))
2446 if (f
->type
!= LXC_TYPE_CGFILE
) {
2447 lxcfs_error("%s\n", "Internal error: directory cache info used in cg_read.");
2457 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
2463 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_RDONLY
)) {
2468 if (strcmp(f
->file
, "tasks") == 0 ||
2469 strcmp(f
->file
, "/tasks") == 0 ||
2470 strcmp(f
->file
, "/cgroup.procs") == 0 ||
2471 strcmp(f
->file
, "cgroup.procs") == 0)
2472 // special case - we have to translate the pids
2473 r
= do_read_pids(fc
->pid
, f
->controller
, f
->cgroup
, f
->file
, &data
);
2475 r
= cgroup_ops
->get(cgroup_ops
, f
->controller
, f
->cgroup
, f
->file
, &data
);
2489 memcpy(buf
, data
, s
);
2490 if (s
> 0 && s
< size
&& data
[s
-1] != '\n')
2500 static int pid_from_ns(int sock
, pid_t tpid
)
2510 if (!wait_for_sock(sock
, 2)) {
2511 lxcfs_error("%s\n", "Timeout reading from parent.");
2514 if ((ret
= read(sock
, &vpid
, sizeof(pid_t
))) != sizeof(pid_t
)) {
2515 lxcfs_error("Bad read from parent: %s.\n", strerror(errno
));
2518 if (vpid
== -1) // done
2522 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
) {
2524 cred
.pid
= getpid();
2525 if (send_creds(sock
, &cred
, v
, false) != SEND_CREDS_OK
)
2532 static void pid_from_ns_wrapper(int sock
, pid_t tpid
)
2534 int newnsfd
= -1, ret
, cpipe
[2];
2539 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
2540 if (ret
< 0 || ret
>= sizeof(fnam
))
2542 newnsfd
= open(fnam
, O_RDONLY
);
2545 if (setns(newnsfd
, 0) < 0)
2549 if (pipe(cpipe
) < 0)
2552 struct pid_ns_clone_args args
= {
2556 .wrapped
= &pid_from_ns
2558 size_t stack_size
= sysconf(_SC_PAGESIZE
);
2559 void *stack
= alloca(stack_size
);
2561 cpid
= clone(pid_ns_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &args
);
2565 // give the child 1 second to be done forking and
2567 if (!wait_for_sock(cpipe
[0], 1))
2569 ret
= read(cpipe
[0], &v
, 1);
2570 if (ret
!= sizeof(char) || v
!= '1')
2573 if (!wait_for_pid(cpid
))
2579 * Given host @uid, return the uid to which it maps in
2580 * @pid's user namespace, or -1 if none.
2582 bool hostuid_to_ns(uid_t uid
, pid_t pid
, uid_t
*answer
)
2587 sprintf(line
, "/proc/%d/uid_map", pid
);
2588 if ((f
= fopen(line
, "r")) == NULL
) {
2592 *answer
= convert_id_to_ns(f
, uid
);
2601 * get_pid_creds: get the real uid and gid of @pid from
2603 * (XXX should we use euid here?)
2605 void get_pid_creds(pid_t pid
, uid_t
*uid
, gid_t
*gid
)
2614 sprintf(line
, "/proc/%d/status", pid
);
2615 if ((f
= fopen(line
, "r")) == NULL
) {
2616 lxcfs_error("Error opening %s: %s\n", line
, strerror(errno
));
2619 while (fgets(line
, 400, f
)) {
2620 if (strncmp(line
, "Uid:", 4) == 0) {
2621 if (sscanf(line
+4, "%u", &u
) != 1) {
2622 lxcfs_error("bad uid line for pid %u\n", pid
);
2627 } else if (strncmp(line
, "Gid:", 4) == 0) {
2628 if (sscanf(line
+4, "%u", &g
) != 1) {
2629 lxcfs_error("bad gid line for pid %u\n", pid
);
2640 * May the requestor @r move victim @v to a new cgroup?
2641 * This is allowed if
2642 * . they are the same task
2643 * . they are ownedy by the same uid
2644 * . @r is root on the host, or
2645 * . @v's uid is mapped into @r's where @r is root.
2647 bool may_move_pid(pid_t r
, uid_t r_uid
, pid_t v
)
2649 uid_t v_uid
, tmpuid
;
2656 get_pid_creds(v
, &v_uid
, &v_gid
);
2659 if (hostuid_to_ns(r_uid
, r
, &tmpuid
) && tmpuid
== 0
2660 && hostuid_to_ns(v_uid
, r
, &tmpuid
))
2665 static bool do_write_pids(pid_t tpid
, uid_t tuid
, const char *contrl
, const char *cg
,
2666 const char *file
, const char *buf
)
2668 int sock
[2] = {-1, -1};
2669 pid_t qpid
, cpid
= -1;
2670 FILE *pids_file
= NULL
;
2671 bool answer
= false, fail
= false;
2673 pids_file
= open_pids_file(contrl
, cg
);
2678 * write the pids to a socket, have helper in writer's pidns
2679 * call movepid for us
2681 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
2682 perror("socketpair");
2690 if (!cpid
) { // child
2692 pid_from_ns_wrapper(sock
[1], tpid
);
2695 const char *ptr
= buf
;
2696 while (sscanf(ptr
, "%d", &qpid
) == 1) {
2700 if (write(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
2701 lxcfs_error("Error writing pid to child: %s.\n", strerror(errno
));
2705 if (recv_creds(sock
[0], &cred
, &v
)) {
2707 if (!may_move_pid(tpid
, tuid
, cred
.pid
)) {
2711 if (fprintf(pids_file
, "%d", (int) cred
.pid
) < 0)
2716 ptr
= strchr(ptr
, '\n');
2722 /* All good, write the value */
2724 if (write(sock
[0], &qpid
,sizeof(qpid
)) != sizeof(qpid
))
2725 lxcfs_error("%s\n", "Warning: failed to ask child to exit.");
2733 if (sock
[0] != -1) {
2738 if (fclose(pids_file
) != 0)
2744 int cg_write(const char *path
, const char *buf
, size_t size
, off_t offset
,
2745 struct fuse_file_info
*fi
)
2747 struct fuse_context
*fc
= fuse_get_context();
2748 char *localbuf
= NULL
;
2749 struct cgfs_files
*k
= NULL
;
2750 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2753 if (!fc
|| !cgroup_ops
|| pure_unified_layout(cgroup_ops
))
2756 if (f
->type
!= LXC_TYPE_CGFILE
) {
2757 lxcfs_error("%s\n", "Internal error: directory cache info used in cg_write.");
2764 localbuf
= alloca(size
+1);
2765 localbuf
[size
] = '\0';
2766 memcpy(localbuf
, buf
, size
);
2768 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
2773 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_WRONLY
)) {
2778 if (strcmp(f
->file
, "tasks") == 0 ||
2779 strcmp(f
->file
, "/tasks") == 0 ||
2780 strcmp(f
->file
, "/cgroup.procs") == 0 ||
2781 strcmp(f
->file
, "cgroup.procs") == 0)
2782 // special case - we have to translate the pids
2783 r
= do_write_pids(fc
->pid
, fc
->uid
, f
->controller
, f
->cgroup
, f
->file
, localbuf
);
2785 r
= cgfs_set_value(f
->controller
, f
->cgroup
, f
->file
, localbuf
);
2795 int cg_chown(const char *path
, uid_t uid
, gid_t gid
)
2797 struct fuse_context
*fc
= fuse_get_context();
2798 char *cgdir
= NULL
, *last
= NULL
, *path1
, *path2
, *controller
;
2799 struct cgfs_files
*k
= NULL
;
2803 if (!fc
|| !cgroup_ops
|| pure_unified_layout(cgroup_ops
))
2806 if (strcmp(path
, "/cgroup") == 0)
2809 controller
= pick_controller_from_path(fc
, path
);
2811 return errno
== ENOENT
? -EPERM
: -errno
;
2813 cgroup
= find_cgroup_in_path(path
);
2815 /* this is just /cgroup/controller */
2818 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2828 if (is_child_cgroup(controller
, path1
, path2
)) {
2829 // get uid, gid, from '/tasks' file and make up a mode
2830 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
2831 k
= cgfs_get_key(controller
, cgroup
, "tasks");
2834 k
= cgfs_get_key(controller
, path1
, path2
);
2842 * This being a fuse request, the uid and gid must be valid
2843 * in the caller's namespace. So we can just check to make
2844 * sure that the caller is root in his uid, and privileged
2845 * over the file's current owner.
2847 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_REQD
)) {
2852 ret
= cgfs_chown_file(controller
, cgroup
, uid
, gid
);
2861 int cg_chmod(const char *path
, mode_t mode
)
2863 struct fuse_context
*fc
= fuse_get_context();
2864 char * cgdir
= NULL
, *last
= NULL
, *path1
, *path2
, *controller
;
2865 struct cgfs_files
*k
= NULL
;
2869 if (!fc
|| !cgroup_ops
|| pure_unified_layout(cgroup_ops
))
2872 if (strcmp(path
, "/cgroup") == 0)
2875 controller
= pick_controller_from_path(fc
, path
);
2877 return errno
== ENOENT
? -EPERM
: -errno
;
2879 cgroup
= find_cgroup_in_path(path
);
2881 /* this is just /cgroup/controller */
2884 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2894 if (is_child_cgroup(controller
, path1
, path2
)) {
2895 // get uid, gid, from '/tasks' file and make up a mode
2896 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
2897 k
= cgfs_get_key(controller
, cgroup
, "tasks");
2900 k
= cgfs_get_key(controller
, path1
, path2
);
2908 * This being a fuse request, the uid and gid must be valid
2909 * in the caller's namespace. So we can just check to make
2910 * sure that the caller is root in his uid, and privileged
2911 * over the file's current owner.
2913 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
2918 if (!cgfs_chmod_file(controller
, cgroup
, mode
)) {
2930 int cg_mkdir(const char *path
, mode_t mode
)
2932 struct fuse_context
*fc
= fuse_get_context();
2933 char *last
= NULL
, *path1
, *cgdir
= NULL
, *controller
, *next
= NULL
;
2937 if (!fc
|| !cgroup_ops
|| pure_unified_layout(cgroup_ops
))
2940 controller
= pick_controller_from_path(fc
, path
);
2942 return errno
== ENOENT
? -EPERM
: -errno
;
2944 cgroup
= find_cgroup_in_path(path
);
2948 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2954 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2955 if (initpid
<= 1 || is_shared_pidns(initpid
))
2957 if (!caller_is_in_ancestor(initpid
, controller
, path1
, &next
)) {
2960 else if (last
&& strcmp(next
, last
) == 0)
2967 if (!fc_may_access(fc
, controller
, path1
, NULL
, O_RDWR
)) {
2971 if (!caller_is_in_ancestor(initpid
, controller
, path1
, NULL
)) {
2976 ret
= cgfs_create(controller
, cgroup
, fc
->uid
, fc
->gid
);
2984 int cg_rmdir(const char *path
)
2986 struct fuse_context
*fc
= fuse_get_context();
2987 char *last
= NULL
, *cgdir
= NULL
, *controller
, *next
= NULL
;
2991 if (!fc
|| !cgroup_ops
|| pure_unified_layout(cgroup_ops
))
2994 controller
= pick_controller_from_path(fc
, path
);
2995 if (!controller
) /* Someone's trying to delete "/cgroup". */
2998 cgroup
= find_cgroup_in_path(path
);
2999 if (!cgroup
) /* Someone's trying to delete a controller e.g. "/blkio". */
3002 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
3004 /* Someone's trying to delete a cgroup on the same level as the
3005 * "/lxc" cgroup e.g. rmdir "/cgroup/blkio/lxc" or
3006 * rmdir "/cgroup/blkio/init.slice".
3012 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3013 if (initpid
<= 1 || is_shared_pidns(initpid
))
3015 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, &next
)) {
3016 if (!last
|| (next
&& (strcmp(next
, last
) == 0)))
3023 if (!fc_may_access(fc
, controller
, cgdir
, NULL
, O_WRONLY
)) {
3027 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, NULL
)) {
3032 if (!cgfs_remove(controller
, cgroup
)) {
3045 static bool startswith(const char *line
, const char *pref
)
3047 if (strncmp(line
, pref
, strlen(pref
)) == 0)
3052 /* Note that "memory.stat" in cgroup2 is hierarchical by default. */
3053 static void parse_memstat(int version
,
3055 unsigned long *cached
,
3056 unsigned long *active_anon
,
3057 unsigned long *inactive_anon
,
3058 unsigned long *active_file
,
3059 unsigned long *inactive_file
,
3060 unsigned long *unevictable
,
3061 unsigned long *shmem
)
3066 if (startswith(memstat
, is_unified_controller(version
)
3069 sscanf(memstat
+ 11, "%lu", cached
);
3071 } else if (startswith(memstat
, is_unified_controller(version
)
3073 : "total_active_anon")) {
3074 sscanf(memstat
+ 17, "%lu", active_anon
);
3075 *active_anon
/= 1024;
3076 } else if (startswith(memstat
, is_unified_controller(version
)
3078 : "total_inactive_anon")) {
3079 sscanf(memstat
+ 19, "%lu", inactive_anon
);
3080 *inactive_anon
/= 1024;
3081 } else if (startswith(memstat
, is_unified_controller(version
)
3083 : "total_active_file")) {
3084 sscanf(memstat
+ 17, "%lu", active_file
);
3085 *active_file
/= 1024;
3086 } else if (startswith(memstat
, is_unified_controller(version
)
3088 : "total_inactive_file")) {
3089 sscanf(memstat
+ 19, "%lu", inactive_file
);
3090 *inactive_file
/= 1024;
3091 } else if (startswith(memstat
, is_unified_controller(version
)
3093 : "total_unevictable")) {
3094 sscanf(memstat
+ 17, "%lu", unevictable
);
3095 *unevictable
/= 1024;
3096 } else if (startswith(memstat
, is_unified_controller(version
)
3099 sscanf(memstat
+ 11, "%lu", shmem
);
3102 eol
= strchr(memstat
, '\n');
3109 static void get_blkio_io_value(char *str
, unsigned major
, unsigned minor
, char *iotype
, unsigned long *v
)
3115 snprintf(key
, 32, "%u:%u %s", major
, minor
, iotype
);
3117 size_t len
= strlen(key
);
3121 if (startswith(str
, key
)) {
3122 sscanf(str
+ len
, "%lu", v
);
3125 eol
= strchr(str
, '\n');
3132 int read_file_fuse(const char *path
, char *buf
, size_t size
, struct file_info
*d
)
3134 __do_free
char *line
= NULL
;
3135 __do_fclose
FILE *f
= NULL
;
3136 size_t linelen
= 0, total_len
= 0;
3137 char *cache
= d
->buf
;
3138 size_t cache_size
= d
->buflen
;
3140 f
= fopen(path
, "r");
3144 while (getline(&line
, &linelen
, f
) != -1) {
3145 ssize_t l
= snprintf(cache
, cache_size
, "%s", line
);
3147 perror("Error writing to cache");
3150 if (l
>= cache_size
) {
3151 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3159 d
->size
= total_len
;
3160 if (total_len
> size
)
3163 /* read from off 0 */
3164 memcpy(buf
, d
->buf
, total_len
);
3166 if (d
->size
> total_len
)
3167 d
->cached
= d
->size
- total_len
;
3172 * FUSE ops for /proc
3175 static unsigned long get_memlimit(const char *cgroup
, bool swap
)
3178 __do_free
char *memlimit_str
= NULL
;
3179 unsigned long memlimit
= -1;
3182 ret
= cgroup_ops
->get_memory_swap_max(cgroup_ops
, cgroup
, &memlimit_str
);
3184 ret
= cgroup_ops
->get_memory_max(cgroup_ops
, cgroup
, &memlimit_str
);
3186 memlimit
= strtoul(memlimit_str
, NULL
, 10);
3191 static unsigned long get_min_memlimit(const char *cgroup
, bool swap
)
3193 __do_free
char *copy
= NULL
;
3194 unsigned long memlimit
= 0;
3195 unsigned long retlimit
;
3197 copy
= strdup(cgroup
);
3198 retlimit
= get_memlimit(copy
, swap
);
3200 while (strcmp(copy
, "/") != 0) {
3204 memlimit
= get_memlimit(it
, swap
);
3205 if (memlimit
!= -1 && memlimit
< retlimit
)
3206 retlimit
= memlimit
;
3212 static int proc_meminfo_read(char *buf
, size_t size
, off_t offset
,
3213 struct fuse_file_info
*fi
)
3215 __do_free
char *cgroup
= NULL
, *line
= NULL
,
3216 *memusage_str
= NULL
, *memstat_str
= NULL
,
3217 *memswlimit_str
= NULL
, *memswusage_str
= NULL
;
3218 __do_fclose
FILE *f
= NULL
;
3219 struct fuse_context
*fc
= fuse_get_context();
3220 struct lxcfs_opts
*opts
= (struct lxcfs_opts
*) fuse_get_context()->private_data
;
3221 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3222 unsigned long memlimit
= 0, memusage
= 0, memswlimit
= 0,
3223 memswusage
= 0, cached
= 0, hosttotal
= 0, active_anon
= 0,
3224 inactive_anon
= 0, active_file
= 0, inactive_file
= 0,
3225 unevictable
= 0, shmem
= 0, hostswtotal
= 0;
3226 size_t linelen
= 0, total_len
= 0;
3227 char *cache
= d
->buf
;
3228 size_t cache_size
= d
->buflen
;
3234 if (offset
> d
->size
)
3240 left
= d
->size
- offset
;
3241 total_len
= left
> size
? size
: left
;
3242 memcpy(buf
, cache
+ offset
, total_len
);
3247 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3248 if (initpid
<= 1 || is_shared_pidns(initpid
))
3251 cgroup
= get_pid_cgroup(initpid
, "memory");
3253 return read_file_fuse("/proc/meminfo", buf
, size
, d
);
3255 prune_init_slice(cgroup
);
3257 memlimit
= get_min_memlimit(cgroup
, false);
3259 ret
= cgroup_ops
->get_memory_current(cgroup_ops
, cgroup
, &memusage_str
);
3263 ret
= cgroup_ops
->get_memory_stats(cgroup_ops
, cgroup
, &memstat_str
);
3266 parse_memstat(ret
, memstat_str
, &cached
, &active_anon
, &inactive_anon
,
3267 &active_file
, &inactive_file
, &unevictable
, &shmem
);
3270 * Following values are allowed to fail, because swapaccount might be
3271 * turned off for current kernel.
3273 ret
= cgroup_ops
->get_memory_swap_max(cgroup_ops
, cgroup
, &memswlimit_str
);
3275 ret
= cgroup_ops
->get_memory_swap_current(cgroup_ops
, cgroup
, &memswusage_str
);
3277 memswlimit
= get_min_memlimit(cgroup
, true);
3278 memswusage
= strtoul(memswusage_str
, NULL
, 10);
3279 memswlimit
= memswlimit
/ 1024;
3280 memswusage
= memswusage
/ 1024;
3283 memusage
= strtoul(memusage_str
, NULL
, 10);
3287 f
= fopen("/proc/meminfo", "r");
3291 while (getline(&line
, &linelen
, f
) != -1) {
3293 char *printme
, lbuf
[100];
3295 memset(lbuf
, 0, 100);
3296 if (startswith(line
, "MemTotal:")) {
3297 sscanf(line
+sizeof("MemTotal:")-1, "%lu", &hosttotal
);
3298 if (hosttotal
< memlimit
)
3299 memlimit
= hosttotal
;
3300 snprintf(lbuf
, 100, "MemTotal: %8lu kB\n", memlimit
);
3302 } else if (startswith(line
, "MemFree:")) {
3303 snprintf(lbuf
, 100, "MemFree: %8lu kB\n", memlimit
- memusage
);
3305 } else if (startswith(line
, "MemAvailable:")) {
3306 snprintf(lbuf
, 100, "MemAvailable: %8lu kB\n", memlimit
- memusage
+ cached
);
3308 } else if (startswith(line
, "SwapTotal:") && memswlimit
> 0 &&
3309 opts
&& opts
->swap_off
== false) {
3310 sscanf(line
+sizeof("SwapTotal:")-1, "%lu", &hostswtotal
);
3311 if (hostswtotal
< memswlimit
)
3312 memswlimit
= hostswtotal
;
3313 snprintf(lbuf
, 100, "SwapTotal: %8lu kB\n", memswlimit
);
3315 } else if (startswith(line
, "SwapTotal:") && opts
&& opts
->swap_off
== true) {
3316 snprintf(lbuf
, 100, "SwapTotal: %8lu kB\n", 0UL);
3318 } else if (startswith(line
, "SwapFree:") && memswlimit
> 0 &&
3319 memswusage
> 0 && opts
&& opts
->swap_off
== false) {
3320 unsigned long swaptotal
= memswlimit
,
3321 swapusage
= memusage
> memswusage
3323 : memswusage
- memusage
,
3324 swapfree
= swapusage
< swaptotal
3325 ? swaptotal
- swapusage
3327 snprintf(lbuf
, 100, "SwapFree: %8lu kB\n", swapfree
);
3329 } else if (startswith(line
, "SwapFree:") && opts
&& opts
->swap_off
== true) {
3330 snprintf(lbuf
, 100, "SwapFree: %8lu kB\n", 0UL);
3332 } else if (startswith(line
, "Slab:")) {
3333 snprintf(lbuf
, 100, "Slab: %8lu kB\n", 0UL);
3335 } else if (startswith(line
, "Buffers:")) {
3336 snprintf(lbuf
, 100, "Buffers: %8lu kB\n", 0UL);
3338 } else if (startswith(line
, "Cached:")) {
3339 snprintf(lbuf
, 100, "Cached: %8lu kB\n", cached
);
3341 } else if (startswith(line
, "SwapCached:")) {
3342 snprintf(lbuf
, 100, "SwapCached: %8lu kB\n", 0UL);
3344 } else if (startswith(line
, "Active:")) {
3345 snprintf(lbuf
, 100, "Active: %8lu kB\n",
3346 active_anon
+ active_file
);
3348 } else if (startswith(line
, "Inactive:")) {
3349 snprintf(lbuf
, 100, "Inactive: %8lu kB\n",
3350 inactive_anon
+ inactive_file
);
3352 } else if (startswith(line
, "Active(anon)")) {
3353 snprintf(lbuf
, 100, "Active(anon): %8lu kB\n", active_anon
);
3355 } else if (startswith(line
, "Inactive(anon)")) {
3356 snprintf(lbuf
, 100, "Inactive(anon): %8lu kB\n", inactive_anon
);
3358 } else if (startswith(line
, "Active(file)")) {
3359 snprintf(lbuf
, 100, "Active(file): %8lu kB\n", active_file
);
3361 } else if (startswith(line
, "Inactive(file)")) {
3362 snprintf(lbuf
, 100, "Inactive(file): %8lu kB\n", inactive_file
);
3364 } else if (startswith(line
, "Unevictable")) {
3365 snprintf(lbuf
, 100, "Unevictable: %8lu kB\n", unevictable
);
3367 } else if (startswith(line
, "SReclaimable")) {
3368 snprintf(lbuf
, 100, "SReclaimable: %8lu kB\n", 0UL);
3370 } else if (startswith(line
, "SUnreclaim")) {
3371 snprintf(lbuf
, 100, "SUnreclaim: %8lu kB\n", 0UL);
3373 } else if (startswith(line
, "Shmem:")) {
3374 snprintf(lbuf
, 100, "Shmem: %8lu kB\n", shmem
);
3376 } else if (startswith(line
, "ShmemHugePages")) {
3377 snprintf(lbuf
, 100, "ShmemHugePages: %8lu kB\n", 0UL);
3379 } else if (startswith(line
, "ShmemPmdMapped")) {
3380 snprintf(lbuf
, 100, "ShmemPmdMapped: %8lu kB\n", 0UL);
3385 l
= snprintf(cache
, cache_size
, "%s", printme
);
3387 perror("Error writing to cache");
3391 if (l
>= cache_size
) {
3392 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3402 d
->size
= total_len
;
3403 if (total_len
> size
) total_len
= size
;
3404 memcpy(buf
, d
->buf
, total_len
);
3410 * Read the cpuset.cpus for cg
3411 * Return the answer in a newly allocated string which must be freed
3413 char *get_cpuset(const char *cg
)
3418 ret
= cgroup_ops
->get_cpuset_cpus(cgroup_ops
, cg
, &value
);
3425 bool cpu_in_cpuset(int cpu
, const char *cpuset
);
3427 static bool cpuline_in_cpuset(const char *line
, const char *cpuset
)
3431 if (sscanf(line
, "processor : %d", &cpu
) != 1)
3433 return cpu_in_cpuset(cpu
, cpuset
);
3437 * Read cgroup CPU quota parameters from `cpu.cfs_quota_us` or `cpu.cfs_period_us`,
3438 * depending on `param`. Parameter value is returned throuh `value`.
3440 static bool read_cpu_cfs_param(const char *cg
, const char *param
, int64_t *value
)
3442 __do_free
char *str
= NULL
;
3443 char file
[11 + 6 + 1]; /* cpu.cfs__us + quota/period + \0 */
3445 snprintf(file
, sizeof(file
), "cpu.cfs_%s_us", param
);
3447 if (!cgroup_ops
->get(cgroup_ops
, "cpu", cg
, file
, &str
))
3450 if (sscanf(str
, "%ld", value
) != 1)
3457 * Return the maximum number of visible CPUs based on CPU quotas.
3458 * If there is no quota set, zero is returned.
3460 int max_cpu_count(const char *cg
)
3463 int64_t cfs_quota
, cfs_period
;
3464 int nr_cpus_in_cpuset
= 0;
3465 char *cpuset
= NULL
;
3467 if (!read_cpu_cfs_param(cg
, "quota", &cfs_quota
))
3470 if (!read_cpu_cfs_param(cg
, "period", &cfs_period
))
3473 cpuset
= get_cpuset(cg
);
3475 nr_cpus_in_cpuset
= cpu_number_in_cpuset(cpuset
);
3477 if (cfs_quota
<= 0 || cfs_period
<= 0){
3478 if (nr_cpus_in_cpuset
> 0)
3479 return nr_cpus_in_cpuset
;
3484 rv
= cfs_quota
/ cfs_period
;
3486 /* In case quota/period does not yield a whole number, add one CPU for
3489 if ((cfs_quota
% cfs_period
) > 0)
3492 nprocs
= get_nprocs();
3497 /* use min value in cpu quota and cpuset */
3498 if (nr_cpus_in_cpuset
> 0 && nr_cpus_in_cpuset
< rv
)
3499 rv
= nr_cpus_in_cpuset
;
3505 * Return the exact number of visible CPUs based on CPU quotas.
3506 * If there is no quota set, zero is returned.
3508 static double exact_cpu_count(const char *cg
)
3512 int64_t cfs_quota
, cfs_period
;
3514 if (!read_cpu_cfs_param(cg
, "quota", &cfs_quota
))
3517 if (!read_cpu_cfs_param(cg
, "period", &cfs_period
))
3520 if (cfs_quota
<= 0 || cfs_period
<= 0)
3523 rv
= (double)cfs_quota
/ (double)cfs_period
;
3525 nprocs
= get_nprocs();
3534 * check whether this is a '^processor" line in /proc/cpuinfo
3536 static bool is_processor_line(const char *line
)
3540 if (sscanf(line
, "processor : %d", &cpu
) == 1)
3545 static int proc_cpuinfo_read(char *buf
, size_t size
, off_t offset
,
3546 struct fuse_file_info
*fi
)
3548 __do_free
char *cg
= NULL
, *cpuset
= NULL
, *line
= NULL
;
3549 __do_fclose
FILE *f
= NULL
;
3550 struct fuse_context
*fc
= fuse_get_context();
3551 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3552 size_t linelen
= 0, total_len
= 0;
3553 bool am_printing
= false, firstline
= true, is_s390x
= false;
3554 int curcpu
= -1, cpu
, max_cpus
= 0;
3556 char *cache
= d
->buf
;
3557 size_t cache_size
= d
->buflen
;
3562 if (offset
> d
->size
)
3568 left
= d
->size
- offset
;
3569 total_len
= left
> size
? size
: left
;
3570 memcpy(buf
, cache
+ offset
, total_len
);
3575 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3576 if (initpid
<= 1 || is_shared_pidns(initpid
))
3578 cg
= get_pid_cgroup(initpid
, "cpuset");
3580 return read_file_fuse("proc/cpuinfo", buf
, size
, d
);
3581 prune_init_slice(cg
);
3583 cpuset
= get_cpuset(cg
);
3587 use_view
= cgroup_ops
->can_use_cpuview(cgroup_ops
);
3589 max_cpus
= max_cpu_count(cg
);
3591 f
= fopen("/proc/cpuinfo", "r");
3595 while (getline(&line
, &linelen
, f
) != -1) {
3599 if (strstr(line
, "IBM/S390") != NULL
) {
3605 if (strncmp(line
, "# processors:", 12) == 0)
3607 if (is_processor_line(line
)) {
3608 if (use_view
&& max_cpus
> 0 && (curcpu
+1) == max_cpus
)
3610 am_printing
= cpuline_in_cpuset(line
, cpuset
);
3613 l
= snprintf(cache
, cache_size
, "processor : %d\n", curcpu
);
3615 perror("Error writing to cache");
3618 if (l
>= cache_size
) {
3619 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3627 } else if (is_s390x
&& sscanf(line
, "processor %d:", &cpu
) == 1) {
3629 if (use_view
&& max_cpus
> 0 && (curcpu
+1) == max_cpus
)
3631 if (!cpu_in_cpuset(cpu
, cpuset
))
3634 p
= strchr(line
, ':');
3638 l
= snprintf(cache
, cache_size
, "processor %d:%s", curcpu
, p
);
3640 perror("Error writing to cache");
3643 if (l
>= cache_size
) {
3644 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3654 l
= snprintf(cache
, cache_size
, "%s", line
);
3656 perror("Error writing to cache");
3659 if (l
>= cache_size
) {
3660 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3670 __do_free
char *origcache
= d
->buf
;
3673 d
->buf
= malloc(d
->buflen
);
3675 d
->buf
= move_ptr(origcache
);
3680 cache_size
= d
->buflen
;
3682 l
= snprintf(cache
, cache_size
, "vendor_id : IBM/S390\n");
3683 if (l
< 0 || l
>= cache_size
)
3689 l
= snprintf(cache
, cache_size
, "# processors : %d\n", curcpu
+ 1);
3690 if (l
< 0 || l
>= cache_size
)
3696 l
= snprintf(cache
, cache_size
, "%s", origcache
);
3697 if (l
< 0 || l
>= cache_size
)
3703 d
->size
= total_len
;
3704 if (total_len
> size
) total_len
= size
;
3706 /* read from off 0 */
3707 memcpy(buf
, d
->buf
, total_len
);
3711 static uint64_t get_reaper_start_time(pid_t pid
)
3716 /* strlen("/proc/") = 6
3720 * strlen("/stat") = 5
3724 #define __PROC_PID_STAT_LEN (6 + LXCFS_NUMSTRLEN64 + 5 + 1)
3725 char path
[__PROC_PID_STAT_LEN
];
3728 qpid
= lookup_initpid_in_store(pid
);
3730 /* Caller can check for EINVAL on 0. */
3735 ret
= snprintf(path
, __PROC_PID_STAT_LEN
, "/proc/%d/stat", qpid
);
3736 if (ret
< 0 || ret
>= __PROC_PID_STAT_LEN
) {
3737 /* Caller can check for EINVAL on 0. */
3742 f
= fopen(path
, "r");
3744 /* Caller can check for EINVAL on 0. */
3749 /* Note that the *scanf() argument supression requires that length
3750 * modifiers such as "l" are omitted. Otherwise some compilers will yell
3751 * at us. It's like telling someone you're not married and then asking
3752 * if you can bring your wife to the party.
3754 ret
= fscanf(f
, "%*d " /* (1) pid %d */
3755 "%*s " /* (2) comm %s */
3756 "%*c " /* (3) state %c */
3757 "%*d " /* (4) ppid %d */
3758 "%*d " /* (5) pgrp %d */
3759 "%*d " /* (6) session %d */
3760 "%*d " /* (7) tty_nr %d */
3761 "%*d " /* (8) tpgid %d */
3762 "%*u " /* (9) flags %u */
3763 "%*u " /* (10) minflt %lu */
3764 "%*u " /* (11) cminflt %lu */
3765 "%*u " /* (12) majflt %lu */
3766 "%*u " /* (13) cmajflt %lu */
3767 "%*u " /* (14) utime %lu */
3768 "%*u " /* (15) stime %lu */
3769 "%*d " /* (16) cutime %ld */
3770 "%*d " /* (17) cstime %ld */
3771 "%*d " /* (18) priority %ld */
3772 "%*d " /* (19) nice %ld */
3773 "%*d " /* (20) num_threads %ld */
3774 "%*d " /* (21) itrealvalue %ld */
3775 "%" PRIu64
, /* (22) starttime %llu */
3779 /* Caller can check for EINVAL on 0. */
3790 static double get_reaper_start_time_in_sec(pid_t pid
)
3792 uint64_t clockticks
, ticks_per_sec
;
3796 clockticks
= get_reaper_start_time(pid
);
3797 if (clockticks
== 0 && errno
== EINVAL
) {
3798 lxcfs_debug("failed to retrieve start time of pid %d\n", pid
);
3802 ret
= sysconf(_SC_CLK_TCK
);
3803 if (ret
< 0 && errno
== EINVAL
) {
3806 "failed to determine number of clock ticks in a second");
3810 ticks_per_sec
= (uint64_t)ret
;
3811 res
= (double)clockticks
/ ticks_per_sec
;
3815 static double get_reaper_age(pid_t pid
)
3818 double procstart
, procage
;
3820 /* We need to substract the time the process has started since system
3821 * boot minus the time when the system has started to get the actual
3824 procstart
= get_reaper_start_time_in_sec(pid
);
3825 procage
= procstart
;
3826 if (procstart
> 0) {
3828 struct timespec spec
;
3830 ret
= clock_gettime(CLOCK_BOOTTIME
, &spec
);
3834 /* We could make this more precise here by using the tv_nsec
3835 * field in the timespec struct and convert it to milliseconds
3836 * and then create a double for the seconds and milliseconds but
3837 * that seems more work than it is worth.
3839 uptime_ms
= (spec
.tv_sec
* 1000) + (spec
.tv_nsec
* 1e-6);
3840 procage
= (uptime_ms
- (procstart
* 1000)) / 1000;
3847 * Returns 0 on success.
3848 * It is the caller's responsibility to free `return_usage`, unless this
3849 * function returns an error.
3851 static int read_cpuacct_usage_all(char *cg
, char *cpuset
, struct cpuacct_usage
**return_usage
, int *size
)
3853 __do_free
char *usage_str
= NULL
;
3854 __do_free
struct cpuacct_usage
*cpu_usage
= NULL
;
3855 int cpucount
= get_nprocs_conf();
3856 int read_pos
= 0, read_cnt
=0;
3859 uint64_t cg_user
, cg_system
;
3860 int64_t ticks_per_sec
;
3862 ticks_per_sec
= sysconf(_SC_CLK_TCK
);
3864 if (ticks_per_sec
< 0 && errno
== EINVAL
) {
3867 "read_cpuacct_usage_all failed to determine number of clock ticks "
3872 cpu_usage
= malloc(sizeof(struct cpuacct_usage
) * cpucount
);
3876 memset(cpu_usage
, 0, sizeof(struct cpuacct_usage
) * cpucount
);
3877 if (!cgroup_ops
->get(cgroup_ops
, "cpuacct", cg
, "cpuacct.usage_all", &usage_str
)) {
3879 int i
= 0, read_pos
= 0, read_cnt
=0;
3880 size_t sz
= 0, asz
= 0;
3882 /* read cpuacct.usage_percpu instead. */
3883 lxcfs_v("failed to read cpuacct.usage_all. reading cpuacct.usage_percpu instead\n%s", "");
3884 if (!cgroup_ops
->get(cgroup_ops
, "cpuacct", cg
, "cpuacct.usage_percpu", &usage_str
))
3886 lxcfs_v("usage_str: %s\n", usage_str
);
3888 /* convert cpuacct.usage_percpu into cpuacct.usage_all. */
3889 lxcfs_v("converting cpuacct.usage_percpu into cpuacct.usage_all\n%s", "");
3891 must_strcat(&data
, &sz
, &asz
, "cpu user system\n");
3893 while (sscanf(usage_str
+ read_pos
, "%lu %n", &cg_user
, &read_cnt
) > 0) {
3894 lxcfs_debug("i: %d, cg_user: %lu, read_pos: %d, read_cnt: %d\n", i
, cg_user
, read_pos
, read_cnt
);
3895 must_strcat(&data
, &sz
, &asz
, "%d %lu 0\n", i
, cg_user
);
3897 read_pos
+= read_cnt
;
3902 lxcfs_v("usage_str: %s\n", usage_str
);
3905 if (sscanf(usage_str
, "cpu user system\n%n", &read_cnt
) != 0) {
3906 lxcfs_error("read_cpuacct_usage_all reading first line from "
3907 "%s/cpuacct.usage_all failed.\n", cg
);
3911 read_pos
+= read_cnt
;
3913 for (i
= 0, j
= 0; i
< cpucount
; i
++) {
3914 ret
= sscanf(usage_str
+ read_pos
, "%d %lu %lu\n%n", &cg_cpu
, &cg_user
,
3915 &cg_system
, &read_cnt
);
3921 lxcfs_error("read_cpuacct_usage_all reading from %s/cpuacct.usage_all "
3926 read_pos
+= read_cnt
;
3928 /* Convert the time from nanoseconds to USER_HZ */
3929 cpu_usage
[j
].user
= cg_user
/ 1000.0 / 1000 / 1000 * ticks_per_sec
;
3930 cpu_usage
[j
].system
= cg_system
/ 1000.0 / 1000 / 1000 * ticks_per_sec
;
3934 *return_usage
= move_ptr(cpu_usage
);
3939 static unsigned long diff_cpu_usage(struct cpuacct_usage
*older
, struct cpuacct_usage
*newer
, struct cpuacct_usage
*diff
, int cpu_count
)
3942 unsigned long sum
= 0;
3944 for (i
= 0; i
< cpu_count
; i
++) {
3945 if (!newer
[i
].online
)
3948 /* When cpuset is changed on the fly, the CPUs might get reordered.
3949 * We could either reset all counters, or check that the substractions
3950 * below will return expected results.
3952 if (newer
[i
].user
> older
[i
].user
)
3953 diff
[i
].user
= newer
[i
].user
- older
[i
].user
;
3957 if (newer
[i
].system
> older
[i
].system
)
3958 diff
[i
].system
= newer
[i
].system
- older
[i
].system
;
3962 if (newer
[i
].idle
> older
[i
].idle
)
3963 diff
[i
].idle
= newer
[i
].idle
- older
[i
].idle
;
3967 sum
+= diff
[i
].user
;
3968 sum
+= diff
[i
].system
;
3969 sum
+= diff
[i
].idle
;
3975 static void add_cpu_usage(unsigned long *surplus
, struct cpuacct_usage
*usage
, unsigned long *counter
, unsigned long threshold
)
3977 unsigned long free_space
, to_add
;
3979 free_space
= threshold
- usage
->user
- usage
->system
;
3981 if (free_space
> usage
->idle
)
3982 free_space
= usage
->idle
;
3984 to_add
= free_space
> *surplus
? *surplus
: free_space
;
3987 usage
->idle
-= to_add
;
3991 static struct cg_proc_stat
*prune_proc_stat_list(struct cg_proc_stat
*node
)
3993 struct cg_proc_stat
*first
= NULL
, *prev
, *tmp
;
3995 for (prev
= NULL
; node
; ) {
3996 if (!cgfs_param_exist("cpu", node
->cg
, "cpu.shares")) {
3998 lxcfs_debug("Removing stat node for %s\n", node
->cg
);
4001 prev
->next
= node
->next
;
4006 free_proc_stat_node(tmp
);
4018 #define PROC_STAT_PRUNE_INTERVAL 10
4019 static void prune_proc_stat_history(void)
4022 time_t now
= time(NULL
);
4024 for (i
= 0; i
< CPUVIEW_HASH_SIZE
; i
++) {
4025 pthread_rwlock_wrlock(&proc_stat_history
[i
]->lock
);
4027 if ((proc_stat_history
[i
]->lastcheck
+ PROC_STAT_PRUNE_INTERVAL
) > now
) {
4028 pthread_rwlock_unlock(&proc_stat_history
[i
]->lock
);
4032 if (proc_stat_history
[i
]->next
) {
4033 proc_stat_history
[i
]->next
= prune_proc_stat_list(proc_stat_history
[i
]->next
);
4034 proc_stat_history
[i
]->lastcheck
= now
;
4037 pthread_rwlock_unlock(&proc_stat_history
[i
]->lock
);
4041 static struct cg_proc_stat
*find_proc_stat_node(struct cg_proc_stat_head
*head
, const char *cg
)
4043 struct cg_proc_stat
*node
;
4045 pthread_rwlock_rdlock(&head
->lock
);
4048 pthread_rwlock_unlock(&head
->lock
);
4055 if (strcmp(cg
, node
->cg
) == 0)
4057 } while ((node
= node
->next
));
4062 pthread_rwlock_unlock(&head
->lock
);
4063 prune_proc_stat_history();
4067 static struct cg_proc_stat
*new_proc_stat_node(struct cpuacct_usage
*usage
, int cpu_count
, const char *cg
)
4069 struct cg_proc_stat
*node
;
4072 node
= malloc(sizeof(struct cg_proc_stat
));
4080 node
->cg
= malloc(strlen(cg
) + 1);
4084 strcpy(node
->cg
, cg
);
4086 node
->usage
= malloc(sizeof(struct cpuacct_usage
) * cpu_count
);
4090 memcpy(node
->usage
, usage
, sizeof(struct cpuacct_usage
) * cpu_count
);
4092 node
->view
= malloc(sizeof(struct cpuacct_usage
) * cpu_count
);
4096 node
->cpu_count
= cpu_count
;
4099 if (pthread_mutex_init(&node
->lock
, NULL
) != 0) {
4100 lxcfs_error("%s\n", "Failed to initialize node lock");
4104 for (i
= 0; i
< cpu_count
; i
++) {
4105 node
->view
[i
].user
= 0;
4106 node
->view
[i
].system
= 0;
4107 node
->view
[i
].idle
= 0;
4113 if (node
&& node
->cg
)
4115 if (node
&& node
->usage
)
4117 if (node
&& node
->view
)
4125 static struct cg_proc_stat
*add_proc_stat_node(struct cg_proc_stat
*new_node
)
4127 int hash
= calc_hash(new_node
->cg
) % CPUVIEW_HASH_SIZE
;
4128 struct cg_proc_stat_head
*head
= proc_stat_history
[hash
];
4129 struct cg_proc_stat
*node
, *rv
= new_node
;
4131 pthread_rwlock_wrlock(&head
->lock
);
4134 head
->next
= new_node
;
4141 if (strcmp(node
->cg
, new_node
->cg
) == 0) {
4142 /* The node is already present, return it */
4143 free_proc_stat_node(new_node
);
4153 node
->next
= new_node
;
4158 pthread_rwlock_unlock(&head
->lock
);
4162 static bool expand_proc_stat_node(struct cg_proc_stat
*node
, int cpu_count
)
4164 __do_free
struct cpuacct_usage
*new_usage
= NULL
, *new_view
= NULL
;
4166 /* Allocate new memory */
4167 new_usage
= malloc(sizeof(struct cpuacct_usage
) * cpu_count
);
4171 new_view
= malloc(sizeof(struct cpuacct_usage
) * cpu_count
);
4175 /* Copy existing data & initialize new elements */
4176 for (int i
= 0; i
< cpu_count
; i
++) {
4177 if (i
< node
->cpu_count
) {
4178 new_usage
[i
].user
= node
->usage
[i
].user
;
4179 new_usage
[i
].system
= node
->usage
[i
].system
;
4180 new_usage
[i
].idle
= node
->usage
[i
].idle
;
4182 new_view
[i
].user
= node
->view
[i
].user
;
4183 new_view
[i
].system
= node
->view
[i
].system
;
4184 new_view
[i
].idle
= node
->view
[i
].idle
;
4186 new_usage
[i
].user
= 0;
4187 new_usage
[i
].system
= 0;
4188 new_usage
[i
].idle
= 0;
4190 new_view
[i
].user
= 0;
4191 new_view
[i
].system
= 0;
4192 new_view
[i
].idle
= 0;
4197 node
->usage
= move_ptr(new_usage
);
4200 node
->view
= move_ptr(new_view
);
4201 node
->cpu_count
= cpu_count
;
4206 static struct cg_proc_stat
*find_or_create_proc_stat_node(struct cpuacct_usage
*usage
, int cpu_count
, const char *cg
)
4208 int hash
= calc_hash(cg
) % CPUVIEW_HASH_SIZE
;
4209 struct cg_proc_stat_head
*head
= proc_stat_history
[hash
];
4210 struct cg_proc_stat
*node
;
4212 node
= find_proc_stat_node(head
, cg
);
4215 node
= new_proc_stat_node(usage
, cpu_count
, cg
);
4219 node
= add_proc_stat_node(node
);
4220 lxcfs_debug("New stat node (%d) for %s\n", cpu_count
, cg
);
4223 pthread_mutex_lock(&node
->lock
);
4225 /* If additional CPUs on the host have been enabled, CPU usage counter
4226 * arrays have to be expanded */
4227 if (node
->cpu_count
< cpu_count
) {
4228 lxcfs_debug("Expanding stat node %d->%d for %s\n",
4229 node
->cpu_count
, cpu_count
, cg
);
4231 if (!expand_proc_stat_node(node
, cpu_count
)) {
4232 pthread_mutex_unlock(&node
->lock
);
4233 lxcfs_debug("Unable to expand stat node %d->%d for %s\n",
4234 node
->cpu_count
, cpu_count
, cg
);
4242 static void reset_proc_stat_node(struct cg_proc_stat
*node
, struct cpuacct_usage
*usage
, int cpu_count
)
4246 lxcfs_debug("Resetting stat node for %s\n", node
->cg
);
4247 memcpy(node
->usage
, usage
, sizeof(struct cpuacct_usage
) * cpu_count
);
4249 for (i
= 0; i
< cpu_count
; i
++) {
4250 node
->view
[i
].user
= 0;
4251 node
->view
[i
].system
= 0;
4252 node
->view
[i
].idle
= 0;
4255 node
->cpu_count
= cpu_count
;
4258 static int cpuview_proc_stat(const char *cg
, const char *cpuset
,
4259 struct cpuacct_usage
*cg_cpu_usage
,
4260 int cg_cpu_usage_size
, FILE *f
, char *buf
,
4263 __do_free
char *line
= NULL
;
4264 __do_free
struct cpuacct_usage
*diff
= NULL
;
4265 size_t linelen
= 0, total_len
= 0, l
;
4266 int curcpu
= -1; /* cpu numbering starts at 0 */
4268 int max_cpus
= max_cpu_count(cg
), cpu_cnt
= 0;
4269 unsigned long user
= 0, nice
= 0, system
= 0, idle
= 0, iowait
= 0,
4270 irq
= 0, softirq
= 0, steal
= 0, guest
= 0, guest_nice
= 0;
4271 unsigned long user_sum
= 0, system_sum
= 0, idle_sum
= 0;
4272 unsigned long user_surplus
= 0, system_surplus
= 0;
4273 unsigned long total_sum
, threshold
;
4274 struct cg_proc_stat
*stat_node
;
4275 int nprocs
= get_nprocs_conf();
4277 if (cg_cpu_usage_size
< nprocs
)
4278 nprocs
= cg_cpu_usage_size
;
4280 /* Read all CPU stats and stop when we've encountered other lines */
4281 while (getline(&line
, &linelen
, f
) != -1) {
4283 char cpu_char
[10]; /* That's a lot of cores */
4284 uint64_t all_used
, cg_used
;
4286 if (strlen(line
) == 0)
4289 /* not a ^cpuN line containing a number N */
4290 if (sscanf(line
, "cpu%9[^ ]", cpu_char
) != 1)
4293 if (sscanf(cpu_char
, "%d", &physcpu
) != 1)
4296 if (physcpu
>= cg_cpu_usage_size
)
4302 if (!cpu_in_cpuset(physcpu
, cpuset
)) {
4303 for (i
= curcpu
; i
<= physcpu
; i
++)
4304 cg_cpu_usage
[i
].online
= false;
4308 if (curcpu
< physcpu
) {
4309 /* Some CPUs may be disabled */
4310 for (i
= curcpu
; i
< physcpu
; i
++)
4311 cg_cpu_usage
[i
].online
= false;
4316 cg_cpu_usage
[curcpu
].online
= true;
4318 ret
= sscanf(line
, "%*s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
4333 all_used
= user
+ nice
+ system
+ iowait
+ irq
+ softirq
+ steal
+ guest
+ guest_nice
;
4334 cg_used
= cg_cpu_usage
[curcpu
].user
+ cg_cpu_usage
[curcpu
].system
;
4336 if (all_used
>= cg_used
) {
4337 cg_cpu_usage
[curcpu
].idle
= idle
+ (all_used
- cg_used
);
4340 lxcfs_error("cpu%d from %s has unexpected cpu time: %lu in /proc/stat, "
4341 "%lu in cpuacct.usage_all; unable to determine idle time\n",
4342 curcpu
, cg
, all_used
, cg_used
);
4343 cg_cpu_usage
[curcpu
].idle
= idle
;
4347 /* Cannot use more CPUs than is available due to cpuset */
4348 if (max_cpus
> cpu_cnt
)
4351 stat_node
= find_or_create_proc_stat_node(cg_cpu_usage
, nprocs
, cg
);
4354 lxcfs_error("unable to find/create stat node for %s\n", cg
);
4358 diff
= malloc(sizeof(struct cpuacct_usage
) * nprocs
);
4364 * If the new values are LOWER than values stored in memory, it means
4365 * the cgroup has been reset/recreated and we should reset too.
4367 for (curcpu
= 0; curcpu
< nprocs
; curcpu
++) {
4368 if (!cg_cpu_usage
[curcpu
].online
)
4371 if (cg_cpu_usage
[curcpu
].user
< stat_node
->usage
[curcpu
].user
)
4372 reset_proc_stat_node(stat_node
, cg_cpu_usage
, nprocs
);
4377 total_sum
= diff_cpu_usage(stat_node
->usage
, cg_cpu_usage
, diff
, nprocs
);
4379 for (curcpu
= 0, i
= -1; curcpu
< nprocs
; curcpu
++) {
4380 stat_node
->usage
[curcpu
].online
= cg_cpu_usage
[curcpu
].online
;
4382 if (!stat_node
->usage
[curcpu
].online
)
4387 stat_node
->usage
[curcpu
].user
+= diff
[curcpu
].user
;
4388 stat_node
->usage
[curcpu
].system
+= diff
[curcpu
].system
;
4389 stat_node
->usage
[curcpu
].idle
+= diff
[curcpu
].idle
;
4391 if (max_cpus
> 0 && i
>= max_cpus
) {
4392 user_surplus
+= diff
[curcpu
].user
;
4393 system_surplus
+= diff
[curcpu
].system
;
4397 /* Calculate usage counters of visible CPUs */
4399 unsigned long diff_user
= 0;
4400 unsigned long diff_system
= 0;
4401 unsigned long diff_idle
= 0;
4402 unsigned long max_diff_idle
= 0;
4403 unsigned long max_diff_idle_index
= 0;
4406 /* threshold = maximum usage per cpu, including idle */
4407 threshold
= total_sum
/ cpu_cnt
* max_cpus
;
4409 for (curcpu
= 0, i
= -1; curcpu
< nprocs
; curcpu
++) {
4410 if (!stat_node
->usage
[curcpu
].online
)
4418 if (diff
[curcpu
].user
+ diff
[curcpu
].system
>= threshold
)
4422 add_cpu_usage(&user_surplus
, &diff
[curcpu
],
4423 &diff
[curcpu
].user
, threshold
);
4425 if (diff
[curcpu
].user
+ diff
[curcpu
].system
>= threshold
)
4428 /* If there is still room, add system */
4429 add_cpu_usage(&system_surplus
, &diff
[curcpu
],
4430 &diff
[curcpu
].system
, threshold
);
4433 if (user_surplus
> 0)
4434 lxcfs_debug("leftover user: %lu for %s\n", user_surplus
, cg
);
4435 if (system_surplus
> 0)
4436 lxcfs_debug("leftover system: %lu for %s\n", system_surplus
, cg
);
4438 for (curcpu
= 0, i
= -1; curcpu
< nprocs
; curcpu
++) {
4439 if (!stat_node
->usage
[curcpu
].online
)
4447 stat_node
->view
[curcpu
].user
+= diff
[curcpu
].user
;
4448 stat_node
->view
[curcpu
].system
+= diff
[curcpu
].system
;
4449 stat_node
->view
[curcpu
].idle
+= diff
[curcpu
].idle
;
4451 user_sum
+= stat_node
->view
[curcpu
].user
;
4452 system_sum
+= stat_node
->view
[curcpu
].system
;
4453 idle_sum
+= stat_node
->view
[curcpu
].idle
;
4455 diff_user
+= diff
[curcpu
].user
;
4456 diff_system
+= diff
[curcpu
].system
;
4457 diff_idle
+= diff
[curcpu
].idle
;
4458 if (diff
[curcpu
].idle
> max_diff_idle
) {
4459 max_diff_idle
= diff
[curcpu
].idle
;
4460 max_diff_idle_index
= curcpu
;
4463 lxcfs_v("curcpu: %d, diff_user: %lu, diff_system: %lu, diff_idle: %lu\n", curcpu
, diff
[curcpu
].user
, diff
[curcpu
].system
, diff
[curcpu
].idle
);
4465 lxcfs_v("total. diff_user: %lu, diff_system: %lu, diff_idle: %lu\n", diff_user
, diff_system
, diff_idle
);
4467 /* revise cpu usage view to support partial cpu case. */
4468 exact_cpus
= exact_cpu_count(cg
);
4469 if (exact_cpus
< (double)max_cpus
){
4470 unsigned long delta
= (unsigned long)((double)(diff_user
+ diff_system
+ diff_idle
) * (1 - exact_cpus
/ (double)max_cpus
));
4472 lxcfs_v("revising cpu usage view to match the exact cpu count [%f]\n", exact_cpus
);
4473 lxcfs_v("delta: %lu\n", delta
);
4474 lxcfs_v("idle_sum before: %lu\n", idle_sum
);
4475 idle_sum
= idle_sum
> delta
? idle_sum
- delta
: 0;
4476 lxcfs_v("idle_sum after: %lu\n", idle_sum
);
4478 curcpu
= max_diff_idle_index
;
4479 lxcfs_v("curcpu: %d, idle before: %lu\n", curcpu
, stat_node
->view
[curcpu
].idle
);
4480 stat_node
->view
[curcpu
].idle
= stat_node
->view
[curcpu
].idle
> delta
? stat_node
->view
[curcpu
].idle
- delta
: 0;
4481 lxcfs_v("curcpu: %d, idle after: %lu\n", curcpu
, stat_node
->view
[curcpu
].idle
);
4484 for (curcpu
= 0; curcpu
< nprocs
; curcpu
++) {
4485 if (!stat_node
->usage
[curcpu
].online
)
4488 stat_node
->view
[curcpu
].user
= stat_node
->usage
[curcpu
].user
;
4489 stat_node
->view
[curcpu
].system
= stat_node
->usage
[curcpu
].system
;
4490 stat_node
->view
[curcpu
].idle
= stat_node
->usage
[curcpu
].idle
;
4492 user_sum
+= stat_node
->view
[curcpu
].user
;
4493 system_sum
+= stat_node
->view
[curcpu
].system
;
4494 idle_sum
+= stat_node
->view
[curcpu
].idle
;
4498 /* Render the file */
4500 l
= snprintf(buf
, buf_size
, "cpu %lu 0 %lu %lu 0 0 0 0 0 0\n",
4504 lxcfs_v("cpu-all: %s\n", buf
);
4507 perror("Error writing to cache");
4510 if (l
>= buf_size
) {
4511 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4519 /* Render visible CPUs */
4520 for (curcpu
= 0, i
= -1; curcpu
< nprocs
; curcpu
++) {
4521 if (!stat_node
->usage
[curcpu
].online
)
4526 if (max_cpus
> 0 && i
== max_cpus
)
4529 l
= snprintf(buf
, buf_size
, "cpu%d %lu 0 %lu %lu 0 0 0 0 0 0\n",
4531 stat_node
->view
[curcpu
].user
,
4532 stat_node
->view
[curcpu
].system
,
4533 stat_node
->view
[curcpu
].idle
);
4534 lxcfs_v("cpu: %s\n", buf
);
4537 perror("Error writing to cache");
4541 if (l
>= buf_size
) {
4542 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4551 /* Pass the rest of /proc/stat, start with the last line read */
4552 l
= snprintf(buf
, buf_size
, "%s", line
);
4555 perror("Error writing to cache");
4559 if (l
>= buf_size
) {
4560 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4568 /* Pass the rest of the host's /proc/stat */
4569 while (getline(&line
, &linelen
, f
) != -1) {
4570 l
= snprintf(buf
, buf_size
, "%s", line
);
4572 perror("Error writing to cache");
4575 if (l
>= buf_size
) {
4576 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4585 pthread_mutex_unlock(&stat_node
->lock
);
4589 #define CPUALL_MAX_SIZE (BUF_RESERVE_SIZE / 2)
4590 static int proc_stat_read(char *buf
, size_t size
, off_t offset
,
4591 struct fuse_file_info
*fi
)
4593 __do_free
char *cg
= NULL
, *cpuset
= NULL
, *line
= NULL
;
4594 __do_free
struct cpuacct_usage
*cg_cpu_usage
= NULL
;
4595 __do_fclose
FILE *f
= NULL
;
4596 struct fuse_context
*fc
= fuse_get_context();
4597 struct file_info
*d
= (struct file_info
*)fi
->fh
;
4598 size_t linelen
= 0, total_len
= 0;
4599 int curcpu
= -1; /* cpu numbering starts at 0 */
4601 unsigned long user
= 0, nice
= 0, system
= 0, idle
= 0, iowait
= 0,
4602 irq
= 0, softirq
= 0, steal
= 0, guest
= 0, guest_nice
= 0;
4603 unsigned long user_sum
= 0, nice_sum
= 0, system_sum
= 0, idle_sum
= 0,
4604 iowait_sum
= 0, irq_sum
= 0, softirq_sum
= 0,
4605 steal_sum
= 0, guest_sum
= 0, guest_nice_sum
= 0;
4606 char cpuall
[CPUALL_MAX_SIZE
];
4607 /* reserve for cpu all */
4608 char *cache
= d
->buf
+ CPUALL_MAX_SIZE
;
4609 size_t cache_size
= d
->buflen
- CPUALL_MAX_SIZE
;
4610 int cg_cpu_usage_size
= 0;
4613 if (offset
> d
->size
)
4617 int left
= d
->size
- offset
;
4618 total_len
= left
> size
? size
: left
;
4619 memcpy(buf
, d
->buf
+ offset
, total_len
);
4623 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
4624 lxcfs_v("initpid: %d\n", initpid
);
4629 * when container run with host pid namespace initpid == 1, cgroup will "/"
4630 * we should return host os's /proc contents.
4631 * in some case cpuacct_usage.all in "/" will larger then /proc/stat
4634 return read_file_fuse("/proc/stat", buf
, size
, d
);
4637 cg
= get_pid_cgroup(initpid
, "cpuset");
4638 lxcfs_v("cg: %s\n", cg
);
4640 return read_file_fuse("/proc/stat", buf
, size
, d
);
4641 prune_init_slice(cg
);
4643 cpuset
= get_cpuset(cg
);
4648 * Read cpuacct.usage_all for all CPUs.
4649 * If the cpuacct cgroup is present, it is used to calculate the container's
4650 * CPU usage. If not, values from the host's /proc/stat are used.
4652 if (read_cpuacct_usage_all(cg
, cpuset
, &cg_cpu_usage
, &cg_cpu_usage_size
) != 0) {
4653 lxcfs_v("%s\n", "proc_stat_read failed to read from cpuacct, "
4654 "falling back to the host's /proc/stat");
4657 f
= fopen("/proc/stat", "r");
4662 if (getline(&line
, &linelen
, f
) < 0) {
4663 lxcfs_error("%s\n", "proc_stat_read read first line failed.");
4667 if (cgroup_ops
->can_use_cpuview(cgroup_ops
) && cg_cpu_usage
) {
4668 total_len
= cpuview_proc_stat(cg
, cpuset
, cg_cpu_usage
, cg_cpu_usage_size
,
4669 f
, d
->buf
, d
->buflen
);
4673 while (getline(&line
, &linelen
, f
) != -1) {
4675 char cpu_char
[10]; /* That's a lot of cores */
4677 uint64_t all_used
, cg_used
, new_idle
;
4680 if (strlen(line
) == 0)
4682 if (sscanf(line
, "cpu%9[^ ]", cpu_char
) != 1) {
4683 /* not a ^cpuN line containing a number N, just print it */
4684 l
= snprintf(cache
, cache_size
, "%s", line
);
4686 perror("Error writing to cache");
4689 if (l
>= cache_size
) {
4690 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4699 if (sscanf(cpu_char
, "%d", &physcpu
) != 1)
4701 if (!cpu_in_cpuset(physcpu
, cpuset
))
4705 ret
= sscanf(line
, "%*s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
4717 if (ret
!= 10 || !cg_cpu_usage
) {
4718 c
= strchr(line
, ' ');
4721 l
= snprintf(cache
, cache_size
, "cpu%d%s", curcpu
, c
);
4723 perror("Error writing to cache");
4727 if (l
>= cache_size
) {
4728 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4741 if (physcpu
>= cg_cpu_usage_size
)
4744 all_used
= user
+ nice
+ system
+ iowait
+ irq
+ softirq
+ steal
+ guest
+ guest_nice
;
4745 cg_used
= cg_cpu_usage
[physcpu
].user
+ cg_cpu_usage
[physcpu
].system
;
4747 if (all_used
>= cg_used
) {
4748 new_idle
= idle
+ (all_used
- cg_used
);
4751 lxcfs_error("cpu%d from %s has unexpected cpu time: %lu in /proc/stat, "
4752 "%lu in cpuacct.usage_all; unable to determine idle time\n",
4753 curcpu
, cg
, all_used
, cg_used
);
4757 l
= snprintf(cache
, cache_size
, "cpu%d %lu 0 %lu %lu 0 0 0 0 0 0\n",
4758 curcpu
, cg_cpu_usage
[physcpu
].user
, cg_cpu_usage
[physcpu
].system
,
4762 perror("Error writing to cache");
4766 if (l
>= cache_size
) {
4767 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4775 user_sum
+= cg_cpu_usage
[physcpu
].user
;
4776 system_sum
+= cg_cpu_usage
[physcpu
].system
;
4777 idle_sum
+= new_idle
;
4782 system_sum
+= system
;
4784 iowait_sum
+= iowait
;
4786 softirq_sum
+= softirq
;
4789 guest_nice_sum
+= guest_nice
;
4795 int cpuall_len
= snprintf(cpuall
, CPUALL_MAX_SIZE
, "cpu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
4806 if (cpuall_len
> 0 && cpuall_len
< CPUALL_MAX_SIZE
) {
4807 memcpy(cache
, cpuall
, cpuall_len
);
4808 cache
+= cpuall_len
;
4810 /* shouldn't happen */
4811 lxcfs_error("proc_stat_read copy cpuall failed, cpuall_len=%d.", cpuall_len
);
4815 memmove(cache
, d
->buf
+ CPUALL_MAX_SIZE
, total_len
);
4816 total_len
+= cpuall_len
;
4820 d
->size
= total_len
;
4821 if (total_len
> size
)
4824 memcpy(buf
, d
->buf
, total_len
);
4828 /* This function retrieves the busy time of a group of tasks by looking at
4829 * cpuacct.usage. Unfortunately, this only makes sense when the container has
4830 * been given it's own cpuacct cgroup. If not, this function will take the busy
4831 * time of all other taks that do not actually belong to the container into
4832 * account as well. If someone has a clever solution for this please send a
4835 static double get_reaper_busy(pid_t task
)
4837 __do_free
char *cgroup
= NULL
, *usage_str
= NULL
;
4838 unsigned long usage
= 0;
4841 initpid
= lookup_initpid_in_store(task
);
4845 cgroup
= get_pid_cgroup(initpid
, "cpuacct");
4848 prune_init_slice(cgroup
);
4849 if (!cgroup_ops
->get(cgroup_ops
, "cpuacct", cgroup
, "cpuacct.usage",
4853 usage
= strtoul(usage_str
, NULL
, 10);
4854 return ((double)usage
/ 1000000000);
4862 fd
= creat("/tmp/lxcfs-iwashere", 0644);
4869 * We read /proc/uptime and reuse its second field.
4870 * For the first field, we use the mtime for the reaper for
4871 * the calling pid as returned by getreaperage
4873 static int proc_uptime_read(char *buf
, size_t size
, off_t offset
,
4874 struct fuse_file_info
*fi
)
4876 struct fuse_context
*fc
= fuse_get_context();
4877 struct file_info
*d
= (struct file_info
*)fi
->fh
;
4878 double busytime
= get_reaper_busy(fc
->pid
);
4879 char *cache
= d
->buf
;
4880 ssize_t total_len
= 0;
4881 double idletime
, reaperage
;
4890 if (offset
> d
->size
)
4892 int left
= d
->size
- offset
;
4893 total_len
= left
> size
? size
: left
;
4894 memcpy(buf
, cache
+ offset
, total_len
);
4898 reaperage
= get_reaper_age(fc
->pid
);
4899 /* To understand why this is done, please read the comment to the
4900 * get_reaper_busy() function.
4902 idletime
= reaperage
;
4903 if (reaperage
>= busytime
)
4904 idletime
= reaperage
- busytime
;
4906 total_len
= snprintf(d
->buf
, d
->buflen
, "%.2lf %.2lf\n", reaperage
, idletime
);
4907 if (total_len
< 0 || total_len
>= d
->buflen
){
4908 lxcfs_error("%s\n", "failed to write to cache");
4912 d
->size
= (int)total_len
;
4915 if (total_len
> size
) total_len
= size
;
4917 memcpy(buf
, d
->buf
, total_len
);
4921 static int proc_diskstats_read(char *buf
, size_t size
, off_t offset
,
4922 struct fuse_file_info
*fi
)
4924 __do_free
char *cg
= NULL
, *io_serviced_str
= NULL
,
4925 *io_merged_str
= NULL
, *io_service_bytes_str
= NULL
,
4926 *io_wait_time_str
= NULL
, *io_service_time_str
= NULL
,
4928 __do_fclose
FILE *f
= NULL
;
4929 struct fuse_context
*fc
= fuse_get_context();
4930 struct file_info
*d
= (struct file_info
*)fi
->fh
;
4931 unsigned long read
= 0, write
= 0;
4932 unsigned long read_merged
= 0, write_merged
= 0;
4933 unsigned long read_sectors
= 0, write_sectors
= 0;
4934 unsigned long read_ticks
= 0, write_ticks
= 0;
4935 unsigned long ios_pgr
= 0, tot_ticks
= 0, rq_ticks
= 0;
4936 unsigned long rd_svctm
= 0, wr_svctm
= 0, rd_wait
= 0, wr_wait
= 0;
4937 char *cache
= d
->buf
;
4938 size_t cache_size
= d
->buflen
;
4939 size_t linelen
= 0, total_len
= 0;
4940 unsigned int major
= 0, minor
= 0;
4948 if (offset
> d
->size
)
4954 left
= d
->size
- offset
;
4955 total_len
= left
> size
? size
: left
;
4956 memcpy(buf
, cache
+ offset
, total_len
);
4961 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
4962 if (initpid
<= 1 || is_shared_pidns(initpid
))
4964 cg
= get_pid_cgroup(initpid
, "blkio");
4966 return read_file_fuse("/proc/diskstats", buf
, size
, d
);
4967 prune_init_slice(cg
);
4969 ret
= cgroup_ops
->get_io_serviced(cgroup_ops
, cg
, &io_serviced_str
);
4971 if (ret
== -EOPNOTSUPP
)
4972 return read_file_fuse("/proc/diskstats", buf
, size
, d
);
4975 ret
= cgroup_ops
->get_io_merged(cgroup_ops
, cg
, &io_merged_str
);
4977 if (ret
== -EOPNOTSUPP
)
4978 return read_file_fuse("/proc/diskstats", buf
, size
, d
);
4981 ret
= cgroup_ops
->get_io_service_bytes(cgroup_ops
, cg
, &io_service_bytes_str
);
4983 if (ret
== -EOPNOTSUPP
)
4984 return read_file_fuse("/proc/diskstats", buf
, size
, d
);
4987 ret
= cgroup_ops
->get_io_wait_time(cgroup_ops
, cg
, &io_wait_time_str
);
4989 if (ret
== -EOPNOTSUPP
)
4990 return read_file_fuse("/proc/diskstats", buf
, size
, d
);
4993 ret
= cgroup_ops
->get_io_service_time(cgroup_ops
, cg
, &io_service_time_str
);
4995 if (ret
== -EOPNOTSUPP
)
4996 return read_file_fuse("/proc/diskstats", buf
, size
, d
);
4999 f
= fopen("/proc/diskstats", "r");
5003 while (getline(&line
, &linelen
, f
) != -1) {
5007 i
= sscanf(line
, "%u %u %71s", &major
, &minor
, dev_name
);
5011 get_blkio_io_value(io_serviced_str
, major
, minor
, "Read", &read
);
5012 get_blkio_io_value(io_serviced_str
, major
, minor
, "Write", &write
);
5013 get_blkio_io_value(io_merged_str
, major
, minor
, "Read", &read_merged
);
5014 get_blkio_io_value(io_merged_str
, major
, minor
, "Write", &write_merged
);
5015 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Read", &read_sectors
);
5016 read_sectors
= read_sectors
/512;
5017 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Write", &write_sectors
);
5018 write_sectors
= write_sectors
/512;
5020 get_blkio_io_value(io_service_time_str
, major
, minor
, "Read", &rd_svctm
);
5021 rd_svctm
= rd_svctm
/1000000;
5022 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Read", &rd_wait
);
5023 rd_wait
= rd_wait
/1000000;
5024 read_ticks
= rd_svctm
+ rd_wait
;
5026 get_blkio_io_value(io_service_time_str
, major
, minor
, "Write", &wr_svctm
);
5027 wr_svctm
= wr_svctm
/1000000;
5028 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Write", &wr_wait
);
5029 wr_wait
= wr_wait
/1000000;
5030 write_ticks
= wr_svctm
+ wr_wait
;
5032 get_blkio_io_value(io_service_time_str
, major
, minor
, "Total", &tot_ticks
);
5033 tot_ticks
= tot_ticks
/1000000;
5035 memset(lbuf
, 0, 256);
5036 if (read
|| write
|| read_merged
|| write_merged
|| read_sectors
|| write_sectors
|| read_ticks
|| write_ticks
)
5037 snprintf(lbuf
, 256, "%u %u %s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
5038 major
, minor
, dev_name
, read
, read_merged
, read_sectors
, read_ticks
,
5039 write
, write_merged
, write_sectors
, write_ticks
, ios_pgr
, tot_ticks
, rq_ticks
);
5043 l
= snprintf(cache
, cache_size
, "%s", lbuf
);
5045 perror("Error writing to fuse buf");
5048 if (l
>= cache_size
) {
5049 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
5058 d
->size
= total_len
;
5059 if (total_len
> size
) total_len
= size
;
5060 memcpy(buf
, d
->buf
, total_len
);
5065 static int proc_swaps_read(char *buf
, size_t size
, off_t offset
,
5066 struct fuse_file_info
*fi
)
5068 __do_free
char *cg
= NULL
, *memswlimit_str
= NULL
, *memusage_str
= NULL
,
5069 *memswusage_str
= NULL
;
5070 struct fuse_context
*fc
= fuse_get_context();
5071 struct file_info
*d
= (struct file_info
*)fi
->fh
;
5072 unsigned long memswlimit
= 0, memlimit
= 0, memusage
= 0,
5073 memswusage
= 0, swap_total
= 0, swap_free
= 0;
5074 ssize_t total_len
= 0;
5076 char *cache
= d
->buf
;
5082 if (offset
> d
->size
)
5088 left
= d
->size
- offset
;
5089 total_len
= left
> size
? size
: left
;
5090 memcpy(buf
, cache
+ offset
, total_len
);
5095 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
5096 if (initpid
<= 1 || is_shared_pidns(initpid
))
5098 cg
= get_pid_cgroup(initpid
, "memory");
5100 return read_file_fuse("/proc/swaps", buf
, size
, d
);
5101 prune_init_slice(cg
);
5103 memlimit
= get_min_memlimit(cg
, false);
5105 ret
= cgroup_ops
->get_memory_current(cgroup_ops
, cg
, &memusage_str
);
5109 memusage
= strtoul(memusage_str
, NULL
, 10);
5111 ret
= cgroup_ops
->get_memory_swap_max(cgroup_ops
, cg
, &memswlimit_str
);
5113 ret
= cgroup_ops
->get_memory_swap_current(cgroup_ops
, cg
, &memswusage_str
);
5115 memswlimit
= get_min_memlimit(cg
, true);
5116 memswusage
= strtoul(memswusage_str
, NULL
, 10);
5117 swap_total
= (memswlimit
- memlimit
) / 1024;
5118 swap_free
= (memswusage
- memusage
) / 1024;
5121 total_len
= snprintf(d
->buf
, d
->size
, "Filename\t\t\t\tType\t\tSize\tUsed\tPriority\n");
5123 /* When no mem + swap limit is specified or swapaccount=0*/
5125 __do_free
char *line
= NULL
;
5126 __do_fclose
FILE *f
= NULL
;
5129 f
= fopen("/proc/meminfo", "r");
5133 while (getline(&line
, &linelen
, f
) != -1) {
5134 if (startswith(line
, "SwapTotal:"))
5135 sscanf(line
, "SwapTotal: %8lu kB", &swap_total
);
5136 else if (startswith(line
, "SwapFree:"))
5137 sscanf(line
, "SwapFree: %8lu kB", &swap_free
);
5141 if (swap_total
> 0) {
5142 l
= snprintf(d
->buf
+ total_len
, d
->size
- total_len
,
5143 "none%*svirtual\t\t%lu\t%lu\t0\n", 36, " ",
5144 swap_total
, swap_free
);
5148 if (total_len
< 0 || l
< 0) {
5149 perror("Error writing to cache");
5154 d
->size
= (int)total_len
;
5156 if (total_len
> size
) total_len
= size
;
5157 memcpy(buf
, d
->buf
, total_len
);
5162 * Find the process pid from cgroup path.
5163 * eg:from /sys/fs/cgroup/cpu/docker/containerid/cgroup.procs to find the process pid.
5164 * @pid_buf : put pid to pid_buf.
5165 * @dpath : the path of cgroup. eg: /docker/containerid or /docker/containerid/child-cgroup ...
5166 * @depth : the depth of cgroup in container.
5167 * @sum : return the number of pid.
5168 * @cfd : the file descriptor of the mounted cgroup. eg: /sys/fs/cgroup/cpu
5170 static int calc_pid(char ***pid_buf
, char *dpath
, int depth
, int sum
, int cfd
)
5172 __do_free
char *path
= NULL
;
5173 __do_close_prot_errno
int fd
= -EBADF
;
5174 __do_fclose
FILE *f
= NULL
;
5175 __do_closedir
DIR *dir
= NULL
;
5176 struct dirent
*file
;
5182 /* path = dpath + "/cgroup.procs" + /0 */
5183 path
= malloc(strlen(dpath
) + 20);
5187 strcpy(path
, dpath
);
5188 fd
= openat(cfd
, path
, O_RDONLY
| O_CLOEXEC
| O_NOFOLLOW
);
5192 dir
= fdopendir(move_fd(fd
));
5196 while (((file
= readdir(dir
)) != NULL
) && depth
> 0) {
5197 if (strcmp(file
->d_name
, ".") == 0)
5200 if (strcmp(file
->d_name
, "..") == 0)
5203 if (file
->d_type
== DT_DIR
) {
5204 __do_free
char *path_dir
= NULL
;
5206 /* path + '/' + d_name +/0 */
5207 path_dir
= malloc(strlen(path
) + 2 + sizeof(file
->d_name
));
5211 strcpy(path_dir
, path
);
5212 strcat(path_dir
, "/");
5213 strcat(path_dir
, file
->d_name
);
5215 sum
= calc_pid(pid_buf
, path_dir
, pd
, sum
, cfd
);
5219 strcat(path
, "/cgroup.procs");
5220 fd
= openat(cfd
, path
, O_RDONLY
);
5224 f
= fdopen(move_fd(fd
), "r");
5228 while (getline(&line
, &linelen
, f
) != -1) {
5229 pid
= realloc(*pid_buf
, sizeof(char *) * (sum
+ 1));
5234 *(*pid_buf
+ sum
) = malloc(strlen(line
) + 1);
5235 if (!*(*pid_buf
+ sum
))
5238 strcpy(*(*pid_buf
+ sum
), line
);
5246 * calc_load calculates the load according to the following formula:
5247 * load1 = load0 * exp + active * (1 - exp)
5249 * @load1: the new loadavg.
5250 * @load0: the former loadavg.
5251 * @active: the total number of running pid at this moment.
5252 * @exp: the fixed-point defined in the beginning.
5254 static unsigned long
5255 calc_load(unsigned long load
, unsigned long exp
, unsigned long active
)
5257 unsigned long newload
;
5259 active
= active
> 0 ? active
* FIXED_1
: 0;
5260 newload
= load
* exp
+ active
* (FIXED_1
- exp
);
5262 newload
+= FIXED_1
- 1;
5264 return newload
/ FIXED_1
;
5268 * Return 0 means that container p->cg is closed.
5269 * Return -1 means that error occurred in refresh.
5270 * Positive num equals the total number of pid.
5272 static int refresh_load(struct load_node
*p
, char *path
)
5274 __do_free
char *line
= NULL
;
5276 char proc_path
[256];
5277 int i
, ret
, run_pid
= 0, total_pid
= 0, last_pid
= 0;
5280 struct dirent
*file
;
5282 idbuf
= malloc(sizeof(char *));
5286 sum
= calc_pid(&idbuf
, path
, DEPTH_DIR
, 0, p
->cfd
);
5291 for (i
= 0; i
< sum
; i
++) {
5292 __do_closedir
DIR *dp
= NULL
;
5295 length
= strlen(idbuf
[i
])-1;
5296 idbuf
[i
][length
] = '\0';
5297 ret
= snprintf(proc_path
, 256, "/proc/%s/task", idbuf
[i
]);
5298 if (ret
< 0 || ret
> 255) {
5299 lxcfs_error("%s\n", "snprintf() failed in refresh_load.");
5305 dp
= opendir(proc_path
);
5307 lxcfs_error("%s\n", "Open proc_path failed in refresh_load.");
5310 while ((file
= readdir(dp
)) != NULL
) {
5311 __do_fclose
FILE *f
= NULL
;
5313 if (strncmp(file
->d_name
, ".", 1) == 0)
5315 if (strncmp(file
->d_name
, "..", 1) == 0)
5318 /* We make the biggest pid become last_pid.*/
5319 ret
= atof(file
->d_name
);
5320 last_pid
= (ret
> last_pid
) ? ret
: last_pid
;
5322 ret
= snprintf(proc_path
, 256, "/proc/%s/task/%s/status", idbuf
[i
], file
->d_name
);
5323 if (ret
< 0 || ret
> 255) {
5324 lxcfs_error("%s\n", "snprintf() failed in refresh_load.");
5330 f
= fopen(proc_path
, "r");
5332 while (getline(&line
, &linelen
, f
) != -1) {
5334 if ((line
[0] == 'S') && (line
[1] == 't'))
5338 if ((line
[7] == 'R') || (line
[7] == 'D'))
5343 /*Calculate the loadavg.*/
5344 p
->avenrun
[0] = calc_load(p
->avenrun
[0], EXP_1
, run_pid
);
5345 p
->avenrun
[1] = calc_load(p
->avenrun
[1], EXP_5
, run_pid
);
5346 p
->avenrun
[2] = calc_load(p
->avenrun
[2], EXP_15
, run_pid
);
5347 p
->run_pid
= run_pid
;
5348 p
->total_pid
= total_pid
;
5349 p
->last_pid
= last_pid
;
5360 * Traverse the hash table and update it.
5362 void *load_begin(void *arg
)
5365 int i
, sum
, length
, ret
;
5366 struct load_node
*f
;
5368 clock_t time1
, time2
;
5371 if (loadavg_stop
== 1)
5375 for (i
= 0; i
< LOAD_SIZE
; i
++) {
5376 pthread_mutex_lock(&load_hash
[i
].lock
);
5377 if (load_hash
[i
].next
== NULL
) {
5378 pthread_mutex_unlock(&load_hash
[i
].lock
);
5381 f
= load_hash
[i
].next
;
5384 __do_free
char *path
= NULL
;
5386 length
= strlen(f
->cg
) + 2;
5387 /* strlen(f->cg) + '.' or '' + \0 */
5388 path
= malloc(length
);
5392 ret
= snprintf(path
, length
, "%s%s", dot_or_empty(f
->cg
), f
->cg
);
5393 if (ret
< 0 || ret
> length
- 1) {
5394 /* snprintf failed, ignore the node.*/
5395 lxcfs_error("Refresh node %s failed for snprintf().\n", f
->cg
);
5399 sum
= refresh_load(f
, path
);
5404 /* load_hash[i].lock locks only on the first node.*/
5405 if (first_node
== 1) {
5407 pthread_mutex_unlock(&load_hash
[i
].lock
);
5412 if (loadavg_stop
== 1)
5416 usleep(FLUSH_TIME
* 1000000 - (int)((time2
- time1
) * 1000000 / CLOCKS_PER_SEC
));
5420 static int proc_loadavg_read(char *buf
, size_t size
, off_t offset
,
5421 struct fuse_file_info
*fi
)
5423 struct fuse_context
*fc
= fuse_get_context();
5424 struct file_info
*d
= (struct file_info
*)fi
->fh
;
5427 size_t total_len
= 0;
5428 char *cache
= d
->buf
;
5429 struct load_node
*n
;
5432 unsigned long a
, b
, c
;
5435 if (offset
> d
->size
)
5439 int left
= d
->size
- offset
;
5440 total_len
= left
> size
? size
: left
;
5441 memcpy(buf
, cache
+ offset
, total_len
);
5445 return read_file_fuse("/proc/loadavg", buf
, size
, d
);
5447 initpid
= lookup_initpid_in_store(fc
->pid
);
5448 if (initpid
<= 1 || is_shared_pidns(initpid
))
5450 cg
= get_pid_cgroup(initpid
, "cpu");
5452 return read_file_fuse("/proc/loadavg", buf
, size
, d
);
5454 prune_init_slice(cg
);
5455 hash
= calc_hash(cg
) % LOAD_SIZE
;
5456 n
= locate_node(cg
, hash
);
5460 cfd
= get_cgroup_fd("cpu");
5463 * In locate_node() above, pthread_rwlock_unlock() isn't used
5464 * because delete is not allowed before read has ended.
5466 pthread_rwlock_unlock(&load_hash
[hash
].rdlock
);
5471 n
= malloc(sizeof(struct load_node
));
5475 n
->cg
= malloc(strlen(cg
)+1);
5483 n
->last_pid
= initpid
;
5485 insert_node(&n
, hash
);
5487 a
= n
->avenrun
[0] + (FIXED_1
/200);
5488 b
= n
->avenrun
[1] + (FIXED_1
/200);
5489 c
= n
->avenrun
[2] + (FIXED_1
/200);
5490 total_len
= snprintf(d
->buf
, d
->buflen
, "%lu.%02lu %lu.%02lu %lu.%02lu %d/%d %d\n",
5491 LOAD_INT(a
), LOAD_FRAC(a
),
5492 LOAD_INT(b
), LOAD_FRAC(b
),
5493 LOAD_INT(c
), LOAD_FRAC(c
),
5494 n
->run_pid
, n
->total_pid
, n
->last_pid
);
5495 pthread_rwlock_unlock(&load_hash
[hash
].rdlock
);
5496 if (total_len
< 0 || total_len
>= d
->buflen
) {
5497 lxcfs_error("%s\n", "Failed to write to cache");
5501 d
->size
= (int)total_len
;
5504 if (total_len
> size
)
5506 memcpy(buf
, d
->buf
, total_len
);
5513 /* Return a positive number on success, return 0 on failure.*/
5514 pthread_t
load_daemon(int load_use
)
5521 lxcfs_error("%s\n", "Initialize hash_table fails in load_daemon!");
5524 ret
= pthread_create(&pid
, NULL
, load_begin
, NULL
);
5526 lxcfs_error("%s\n", "Create pthread fails in load_daemon!");
5530 /* use loadavg, here loadavg = 1*/
5535 /* Returns 0 on success. */
5536 int stop_load_daemon(pthread_t pid
)
5540 /* Signal the thread to gracefully stop */
5543 s
= pthread_join(pid
, NULL
); /* Make sure sub thread has been canceled. */
5545 lxcfs_error("%s\n", "stop_load_daemon error: failed to join");
5555 static off_t
get_procfile_size(const char *which
)
5557 FILE *f
= fopen(which
, "r");
5560 ssize_t sz
, answer
= 0;
5564 while ((sz
= getline(&line
, &len
, f
)) != -1)
5572 int proc_getattr(const char *path
, struct stat
*sb
)
5574 struct timespec now
;
5576 memset(sb
, 0, sizeof(struct stat
));
5577 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
5579 sb
->st_uid
= sb
->st_gid
= 0;
5580 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
5581 if (strcmp(path
, "/proc") == 0) {
5582 sb
->st_mode
= S_IFDIR
| 00555;
5586 if (strcmp(path
, "/proc/meminfo") == 0 ||
5587 strcmp(path
, "/proc/cpuinfo") == 0 ||
5588 strcmp(path
, "/proc/uptime") == 0 ||
5589 strcmp(path
, "/proc/stat") == 0 ||
5590 strcmp(path
, "/proc/diskstats") == 0 ||
5591 strcmp(path
, "/proc/swaps") == 0 ||
5592 strcmp(path
, "/proc/loadavg") == 0) {
5594 sb
->st_mode
= S_IFREG
| 00444;
5602 int proc_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
5603 struct fuse_file_info
*fi
)
5605 if (filler(buf
, ".", NULL
, 0) != 0 ||
5606 filler(buf
, "..", NULL
, 0) != 0 ||
5607 filler(buf
, "cpuinfo", NULL
, 0) != 0 ||
5608 filler(buf
, "meminfo", NULL
, 0) != 0 ||
5609 filler(buf
, "stat", NULL
, 0) != 0 ||
5610 filler(buf
, "uptime", NULL
, 0) != 0 ||
5611 filler(buf
, "diskstats", NULL
, 0) != 0 ||
5612 filler(buf
, "swaps", NULL
, 0) != 0 ||
5613 filler(buf
, "loadavg", NULL
, 0) != 0)
5618 int proc_open(const char *path
, struct fuse_file_info
*fi
)
5621 struct file_info
*info
;
5623 if (strcmp(path
, "/proc/meminfo") == 0)
5624 type
= LXC_TYPE_PROC_MEMINFO
;
5625 else if (strcmp(path
, "/proc/cpuinfo") == 0)
5626 type
= LXC_TYPE_PROC_CPUINFO
;
5627 else if (strcmp(path
, "/proc/uptime") == 0)
5628 type
= LXC_TYPE_PROC_UPTIME
;
5629 else if (strcmp(path
, "/proc/stat") == 0)
5630 type
= LXC_TYPE_PROC_STAT
;
5631 else if (strcmp(path
, "/proc/diskstats") == 0)
5632 type
= LXC_TYPE_PROC_DISKSTATS
;
5633 else if (strcmp(path
, "/proc/swaps") == 0)
5634 type
= LXC_TYPE_PROC_SWAPS
;
5635 else if (strcmp(path
, "/proc/loadavg") == 0)
5636 type
= LXC_TYPE_PROC_LOADAVG
;
5640 info
= malloc(sizeof(*info
));
5644 memset(info
, 0, sizeof(*info
));
5647 info
->buflen
= get_procfile_size(path
) + BUF_RESERVE_SIZE
;
5649 info
->buf
= malloc(info
->buflen
);
5650 } while (!info
->buf
);
5651 memset(info
->buf
, 0, info
->buflen
);
5652 /* set actual size to buffer size */
5653 info
->size
= info
->buflen
;
5655 fi
->fh
= (unsigned long)info
;
5659 int proc_access(const char *path
, int mask
)
5661 if (strcmp(path
, "/proc") == 0 && access(path
, R_OK
) == 0)
5664 /* these are all read-only */
5665 if ((mask
& ~R_OK
) != 0)
5670 int proc_release(const char *path
, struct fuse_file_info
*fi
)
5672 do_release_file_info(fi
);
5676 int proc_read(const char *path
, char *buf
, size_t size
, off_t offset
,
5677 struct fuse_file_info
*fi
)
5679 struct file_info
*f
= (struct file_info
*) fi
->fh
;
5682 case LXC_TYPE_PROC_MEMINFO
:
5683 return proc_meminfo_read(buf
, size
, offset
, fi
);
5684 case LXC_TYPE_PROC_CPUINFO
:
5685 return proc_cpuinfo_read(buf
, size
, offset
, fi
);
5686 case LXC_TYPE_PROC_UPTIME
:
5687 return proc_uptime_read(buf
, size
, offset
, fi
);
5688 case LXC_TYPE_PROC_STAT
:
5689 return proc_stat_read(buf
, size
, offset
, fi
);
5690 case LXC_TYPE_PROC_DISKSTATS
:
5691 return proc_diskstats_read(buf
, size
, offset
, fi
);
5692 case LXC_TYPE_PROC_SWAPS
:
5693 return proc_swaps_read(buf
, size
, offset
, fi
);
5694 case LXC_TYPE_PROC_LOADAVG
:
5695 return proc_loadavg_read(buf
, size
, offset
, fi
);
5702 * Functions needed to setup cgroups in the __constructor__.
5705 static bool umount_if_mounted(void)
5707 if (umount2(BASEDIR
, MNT_DETACH
) < 0 && errno
!= EINVAL
) {
5708 lxcfs_error("Failed to unmount %s: %s.\n", BASEDIR
, strerror(errno
));
5714 /* __typeof__ should be safe to use with all compilers. */
5715 typedef __typeof__(((struct statfs
*)NULL
)->f_type
) fs_type_magic
;
5716 static bool has_fs_type(const struct statfs
*fs
, fs_type_magic magic_val
)
5718 return (fs
->f_type
== (fs_type_magic
)magic_val
);
5722 * looking at fs/proc_namespace.c, it appears we can
5723 * actually expect the rootfs entry to very specifically contain
5724 * " - rootfs rootfs "
5725 * IIUC, so long as we've chrooted so that rootfs is not our root,
5726 * the rootfs entry should always be skipped in mountinfo contents.
5728 static bool is_on_ramfs(void)
5736 f
= fopen("/proc/self/mountinfo", "r");
5740 while (getline(&line
, &len
, f
) != -1) {
5741 for (p
= line
, i
= 0; p
&& i
< 4; i
++)
5742 p
= strchr(p
+ 1, ' ');
5745 p2
= strchr(p
+ 1, ' ');
5749 if (strcmp(p
+ 1, "/") == 0) {
5750 // this is '/'. is it the ramfs?
5751 p
= strchr(p2
+ 1, '-');
5752 if (p
&& strncmp(p
, "- rootfs rootfs ", 16) == 0) {
5764 static int pivot_enter()
5766 int ret
= -1, oldroot
= -1, newroot
= -1;
5768 oldroot
= open("/", O_DIRECTORY
| O_RDONLY
);
5770 lxcfs_error("%s\n", "Failed to open old root for fchdir.");
5774 newroot
= open(ROOTDIR
, O_DIRECTORY
| O_RDONLY
);
5776 lxcfs_error("%s\n", "Failed to open new root for fchdir.");
5780 /* change into new root fs */
5781 if (fchdir(newroot
) < 0) {
5782 lxcfs_error("Failed to change directory to new rootfs: %s.\n", ROOTDIR
);
5786 /* pivot_root into our new root fs */
5787 if (pivot_root(".", ".") < 0) {
5788 lxcfs_error("pivot_root() syscall failed: %s.\n", strerror(errno
));
5793 * At this point the old-root is mounted on top of our new-root.
5794 * To unmounted it we must not be chdir'd into it, so escape back
5797 if (fchdir(oldroot
) < 0) {
5798 lxcfs_error("%s\n", "Failed to enter old root.");
5802 if (umount2(".", MNT_DETACH
) < 0) {
5803 lxcfs_error("%s\n", "Failed to detach old root.");
5807 if (fchdir(newroot
) < 0) {
5808 lxcfs_error("%s\n", "Failed to re-enter new root.");
5823 static int chroot_enter()
5825 if (mount(ROOTDIR
, "/", NULL
, MS_REC
| MS_BIND
, NULL
)) {
5826 lxcfs_error("Failed to recursively bind-mount %s into /.", ROOTDIR
);
5830 if (chroot(".") < 0) {
5831 lxcfs_error("Call to chroot() failed: %s.\n", strerror(errno
));
5835 if (chdir("/") < 0) {
5836 lxcfs_error("Failed to change directory: %s.\n", strerror(errno
));
5843 static int permute_and_enter(void)
5847 if (statfs("/", &sb
) < 0) {
5848 lxcfs_error("%s\n", "Could not stat / mountpoint.");
5852 /* has_fs_type() is not reliable. When the ramfs is a tmpfs it will
5853 * likely report TMPFS_MAGIC. Hence, when it reports no we still check
5854 * /proc/1/mountinfo. */
5855 if (has_fs_type(&sb
, RAMFS_MAGIC
) || is_on_ramfs())
5856 return chroot_enter();
5858 if (pivot_enter() < 0) {
5859 lxcfs_error("%s\n", "Could not perform pivot root.");
5866 /* Prepare our new clean root. */
5867 static int permute_prepare(void)
5869 if (mkdir(ROOTDIR
, 0700) < 0 && errno
!= EEXIST
) {
5870 lxcfs_error("%s\n", "Failed to create directory for new root.");
5874 if (mount("/", ROOTDIR
, NULL
, MS_BIND
, 0) < 0) {
5875 lxcfs_error("Failed to bind-mount / for new root: %s.\n", strerror(errno
));
5879 if (mount(RUNTIME_PATH
, ROOTDIR RUNTIME_PATH
, NULL
, MS_BIND
, 0) < 0) {
5880 lxcfs_error("Failed to bind-mount /run into new root: %s.\n", strerror(errno
));
5884 if (mount(BASEDIR
, ROOTDIR BASEDIR
, NULL
, MS_REC
| MS_MOVE
, 0) < 0) {
5885 printf("Failed to move " BASEDIR
" into new root: %s.\n", strerror(errno
));
5892 /* Calls chroot() on ramfs, pivot_root() in all other cases. */
5893 static bool permute_root(void)
5895 /* Prepare new root. */
5896 if (permute_prepare() < 0)
5899 /* Pivot into new root. */
5900 if (permute_and_enter() < 0)
5906 static bool cgfs_prepare_mounts(void)
5908 if (!mkdir_p(BASEDIR
, 0700)) {
5909 lxcfs_error("%s\n", "Failed to create lxcfs cgroup mountpoint.");
5913 if (!umount_if_mounted()) {
5914 lxcfs_error("%s\n", "Failed to clean up old lxcfs cgroup mountpoint.");
5918 if (unshare(CLONE_NEWNS
) < 0) {
5919 lxcfs_error("Failed to unshare mount namespace: %s.\n", strerror(errno
));
5923 cgroup_ops
->mntns_fd
= preserve_ns(getpid(), "mnt");
5924 if (cgroup_ops
->mntns_fd
< 0) {
5925 lxcfs_error("Failed to preserve mount namespace: %s.\n", strerror(errno
));
5929 if (mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, 0) < 0) {
5930 lxcfs_error("Failed to remount / private: %s.\n", strerror(errno
));
5934 if (mount("tmpfs", BASEDIR
, "tmpfs", 0, "size=100000,mode=700") < 0) {
5935 lxcfs_error("%s\n", "Failed to mount tmpfs over lxcfs cgroup mountpoint.");
5942 static bool cgfs_mount_hierarchies(void)
5944 if (!mkdir_p(BASEDIR DEFAULT_CGROUP_MOUNTPOINT
, 0755))
5947 if (!cgroup_ops
->mount(cgroup_ops
, BASEDIR
))
5950 for (struct hierarchy
**h
= cgroup_ops
->hierarchies
; h
&& *h
; h
++) {
5951 __do_free
char *path
= must_make_path(BASEDIR
, (*h
)->mountpoint
, NULL
);
5952 (*h
)->fd
= open(path
, O_DIRECTORY
| O_CLOEXEC
| O_NOFOLLOW
);
5960 static bool cgfs_setup_controllers(void)
5962 if (!cgfs_prepare_mounts())
5965 if (!cgfs_mount_hierarchies()) {
5966 lxcfs_error("%s\n", "Failed to set up private lxcfs cgroup mounts.");
5970 if (!permute_root())
5976 static void __attribute__((constructor
)) lxcfs_init(void)
5978 __do_close_prot_errno
int init_ns
= -EBADF
;
5980 char cwd
[MAXPATHLEN
];
5982 cgroup_ops
= cgroup_init();
5984 log_exit("Failed to initialize cgroup support");
5986 /* Preserve initial namespace. */
5987 init_ns
= preserve_ns(getpid(), "mnt");
5989 log_exit("Failed to preserve initial mount namespace");
5991 cret
= getcwd(cwd
, MAXPATHLEN
);
5992 log_exit("%s - Could not retrieve current working directory", strerror(errno
));
5994 /* This function calls unshare(CLONE_NEWNS) our initial mount namespace
5995 * to privately mount lxcfs cgroups. */
5996 if (!cgfs_setup_controllers())
5997 log_exit("Failed to setup private cgroup mounts for lxcfs");
5999 if (setns(init_ns
, 0) < 0)
6000 log_exit("%s - Failed to switch back to initial mount namespace", strerror(errno
));
6002 if (!cret
|| chdir(cwd
) < 0)
6003 log_exit("%s - Could not change back to original working directory", strerror(errno
));
6005 if (!init_cpuview())
6006 log_exit("Failed to init CPU view");
6011 static void __attribute__((destructor
)) lxcfs_exit(void)
6013 lxcfs_debug("%s\n", "Running destructor for liblxcfs");
6015 cgroup_exit(cgroup_ops
);