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>
41 #include "cgroups/cgroup.h"
42 #include "cgroups/cgroup_utils.h"
43 #include "memory_utils.h"
46 /* Define pivot_root() if missing from the C library */
47 #ifndef HAVE_PIVOT_ROOT
48 static int pivot_root(const char * new_root
, const char * put_old
)
50 #ifdef __NR_pivot_root
51 return syscall(__NR_pivot_root
, new_root
, put_old
);
58 extern int pivot_root(const char * new_root
, const char * put_old
);
61 struct cpuacct_usage
{
68 /* The function of hash table.*/
69 #define LOAD_SIZE 100 /*the size of hash_table */
70 #define FLUSH_TIME 5 /*the flush rate */
71 #define DEPTH_DIR 3 /*the depth of per cgroup */
72 /* The function of calculate loadavg .*/
73 #define FSHIFT 11 /* nr of bits of precision */
74 #define FIXED_1 (1<<FSHIFT) /* 1.0 as fixed-point */
75 #define EXP_1 1884 /* 1/exp(5sec/1min) as fixed-point */
76 #define EXP_5 2014 /* 1/exp(5sec/5min) */
77 #define EXP_15 2037 /* 1/exp(5sec/15min) */
78 #define LOAD_INT(x) ((x) >> FSHIFT)
79 #define LOAD_FRAC(x) LOAD_INT(((x) & (FIXED_1-1)) * 100)
81 * This parameter is used for proc_loadavg_read().
82 * 1 means use loadavg, 0 means not use.
84 static int loadavg
= 0;
85 static volatile sig_atomic_t loadavg_stop
= 0;
86 static int calc_hash(const char *name
)
88 unsigned int hash
= 0;
90 /* ELFHash algorithm. */
92 hash
= (hash
<< 4) + *name
++;
93 x
= hash
& 0xf0000000;
98 return (hash
& 0x7fffffff);
103 unsigned long avenrun
[3]; /* Load averages */
104 unsigned int run_pid
;
105 unsigned int total_pid
;
106 unsigned int last_pid
;
107 int cfd
; /* The file descriptor of the mounted cgroup */
108 struct load_node
*next
;
109 struct load_node
**pre
;
114 * The lock is about insert load_node and refresh load_node.To the first
115 * load_node of each hash bucket, insert and refresh in this hash bucket is
116 * mutually exclusive.
118 pthread_mutex_t lock
;
120 * The rdlock is about read loadavg and delete load_node.To each hash
121 * bucket, read and delete is mutually exclusive. But at the same time, we
122 * allow paratactic read operation. This rdlock is at list level.
124 pthread_rwlock_t rdlock
;
126 * The rilock is about read loadavg and insert load_node.To the first
127 * load_node of each hash bucket, read and insert is mutually exclusive.
128 * But at the same time, we allow paratactic read operation.
130 pthread_rwlock_t rilock
;
131 struct load_node
*next
;
134 static struct load_head load_hash
[LOAD_SIZE
]; /* hash table */
136 * init_load initialize the hash table.
137 * Return 0 on success, return -1 on failure.
139 static int init_load(void)
144 for (i
= 0; i
< LOAD_SIZE
; i
++) {
145 load_hash
[i
].next
= NULL
;
146 ret
= pthread_mutex_init(&load_hash
[i
].lock
, NULL
);
148 lxcfs_error("%s\n", "Failed to initialize lock");
151 ret
= pthread_rwlock_init(&load_hash
[i
].rdlock
, NULL
);
153 lxcfs_error("%s\n", "Failed to initialize rdlock");
156 ret
= pthread_rwlock_init(&load_hash
[i
].rilock
, NULL
);
158 lxcfs_error("%s\n", "Failed to initialize rilock");
164 pthread_rwlock_destroy(&load_hash
[i
].rdlock
);
166 pthread_mutex_destroy(&load_hash
[i
].lock
);
170 pthread_mutex_destroy(&load_hash
[i
].lock
);
171 pthread_rwlock_destroy(&load_hash
[i
].rdlock
);
172 pthread_rwlock_destroy(&load_hash
[i
].rilock
);
177 static void insert_node(struct load_node
**n
, int locate
)
181 pthread_mutex_lock(&load_hash
[locate
].lock
);
182 pthread_rwlock_wrlock(&load_hash
[locate
].rilock
);
183 f
= load_hash
[locate
].next
;
184 load_hash
[locate
].next
= *n
;
186 (*n
)->pre
= &(load_hash
[locate
].next
);
188 f
->pre
= &((*n
)->next
);
190 pthread_mutex_unlock(&load_hash
[locate
].lock
);
191 pthread_rwlock_unlock(&load_hash
[locate
].rilock
);
194 * locate_node() finds special node. Not return NULL means success.
195 * It should be noted that rdlock isn't unlocked at the end of code
196 * because this function is used to read special node. Delete is not
197 * allowed before read has ended.
198 * unlock rdlock only in proc_loadavg_read().
200 static struct load_node
*locate_node(char *cg
, int locate
)
202 struct load_node
*f
= NULL
;
205 pthread_rwlock_rdlock(&load_hash
[locate
].rilock
);
206 pthread_rwlock_rdlock(&load_hash
[locate
].rdlock
);
207 if (load_hash
[locate
].next
== NULL
) {
208 pthread_rwlock_unlock(&load_hash
[locate
].rilock
);
211 f
= load_hash
[locate
].next
;
212 pthread_rwlock_unlock(&load_hash
[locate
].rilock
);
213 while (f
&& ((i
= strcmp(f
->cg
, cg
)) != 0))
218 /* Delete the load_node n and return the next node of it. */
219 static struct load_node
*del_node(struct load_node
*n
, int locate
)
223 pthread_rwlock_wrlock(&load_hash
[locate
].rdlock
);
224 if (n
->next
== NULL
) {
228 n
->next
->pre
= n
->pre
;
233 pthread_rwlock_unlock(&load_hash
[locate
].rdlock
);
237 static void load_free(void)
239 struct load_node
*f
, *p
;
241 for (int i
= 0; i
< LOAD_SIZE
; i
++) {
242 pthread_mutex_lock(&load_hash
[i
].lock
);
243 pthread_rwlock_wrlock(&load_hash
[i
].rilock
);
244 pthread_rwlock_wrlock(&load_hash
[i
].rdlock
);
245 if (load_hash
[i
].next
== NULL
) {
246 pthread_mutex_unlock(&load_hash
[i
].lock
);
247 pthread_mutex_destroy(&load_hash
[i
].lock
);
248 pthread_rwlock_unlock(&load_hash
[i
].rilock
);
249 pthread_rwlock_destroy(&load_hash
[i
].rilock
);
250 pthread_rwlock_unlock(&load_hash
[i
].rdlock
);
251 pthread_rwlock_destroy(&load_hash
[i
].rdlock
);
255 for (f
= load_hash
[i
].next
; f
;) {
262 pthread_mutex_unlock(&load_hash
[i
].lock
);
263 pthread_mutex_destroy(&load_hash
[i
].lock
);
264 pthread_rwlock_unlock(&load_hash
[i
].rilock
);
265 pthread_rwlock_destroy(&load_hash
[i
].rilock
);
266 pthread_rwlock_unlock(&load_hash
[i
].rdlock
);
267 pthread_rwlock_destroy(&load_hash
[i
].rdlock
);
271 /* Data for CPU view */
272 struct cg_proc_stat
{
274 struct cpuacct_usage
*usage
; // Real usage as read from the host's /proc/stat
275 struct cpuacct_usage
*view
; // Usage stats reported to the container
277 pthread_mutex_t lock
; // For node manipulation
278 struct cg_proc_stat
*next
;
281 struct cg_proc_stat_head
{
282 struct cg_proc_stat
*next
;
286 * For access to the list. Reading can be parallel, pruning is exclusive.
288 pthread_rwlock_t lock
;
291 #define CPUVIEW_HASH_SIZE 100
292 static struct cg_proc_stat_head
*proc_stat_history
[CPUVIEW_HASH_SIZE
];
294 static bool cpuview_init_head(struct cg_proc_stat_head
**head
)
296 *head
= malloc(sizeof(struct cg_proc_stat_head
));
298 lxcfs_error("%s\n", strerror(errno
));
302 (*head
)->lastcheck
= time(NULL
);
303 (*head
)->next
= NULL
;
305 if (pthread_rwlock_init(&(*head
)->lock
, NULL
) != 0) {
306 lxcfs_error("%s\n", "Failed to initialize list lock");
314 static bool init_cpuview()
318 for (i
= 0; i
< CPUVIEW_HASH_SIZE
; i
++)
319 proc_stat_history
[i
] = NULL
;
321 for (i
= 0; i
< CPUVIEW_HASH_SIZE
; i
++) {
322 if (!cpuview_init_head(&proc_stat_history
[i
]))
329 for (i
= 0; i
< CPUVIEW_HASH_SIZE
; i
++) {
330 if (proc_stat_history
[i
])
331 free_disarm(proc_stat_history
[i
]);
337 static void free_proc_stat_node(struct cg_proc_stat
*node
)
339 pthread_mutex_destroy(&node
->lock
);
340 free_disarm(node
->cg
);
341 free_disarm(node
->usage
);
342 free_disarm(node
->view
);
346 static void cpuview_free_head(struct cg_proc_stat_head
*head
)
348 struct cg_proc_stat
*node
, *tmp
;
356 free_proc_stat_node(tmp
);
363 pthread_rwlock_destroy(&head
->lock
);
367 static void free_cpuview()
371 for (i
= 0; i
< CPUVIEW_HASH_SIZE
; i
++) {
372 if (proc_stat_history
[i
])
373 cpuview_free_head(proc_stat_history
[i
]);
378 * A table caching which pid is init for a pid namespace.
379 * When looking up which pid is init for $qpid, we first
380 * 1. Stat /proc/$qpid/ns/pid.
381 * 2. Check whether the ino_t is in our store.
382 * a. if not, fork a child in qpid's ns to send us
383 * ucred.pid = 1, and read the initpid. Cache
384 * initpid and creation time for /proc/initpid
385 * in a new store entry.
386 * b. if so, verify that /proc/initpid still matches
387 * what we have saved. If not, clear the store
388 * entry and go back to a. If so, return the
391 struct pidns_init_store
{
392 ino_t ino
; // inode number for /proc/$pid/ns/pid
393 pid_t initpid
; // the pid of nit in that ns
394 long int ctime
; // the time at which /proc/$initpid was created
395 struct pidns_init_store
*next
;
399 /* lol - look at how they are allocated in the kernel */
400 #define PIDNS_HASH_SIZE 4096
401 #define HASH(x) ((x) % PIDNS_HASH_SIZE)
403 static struct pidns_init_store
*pidns_hash_table
[PIDNS_HASH_SIZE
];
404 static pthread_mutex_t pidns_store_mutex
= PTHREAD_MUTEX_INITIALIZER
;
405 static void lock_mutex(pthread_mutex_t
*l
)
409 if ((ret
= pthread_mutex_lock(l
)) != 0) {
410 lxcfs_error("returned:%d %s\n", ret
, strerror(ret
));
415 struct cgroup_ops
*cgroup_ops
;
417 static void unlock_mutex(pthread_mutex_t
*l
)
421 if ((ret
= pthread_mutex_unlock(l
)) != 0) {
422 lxcfs_error("returned:%d %s\n", ret
, strerror(ret
));
427 static void store_lock(void)
429 lock_mutex(&pidns_store_mutex
);
432 static void store_unlock(void)
434 unlock_mutex(&pidns_store_mutex
);
437 /* Must be called under store_lock */
438 static bool initpid_still_valid(struct pidns_init_store
*e
, struct stat
*nsfdsb
)
443 snprintf(fnam
, 100, "/proc/%d", e
->initpid
);
444 if (stat(fnam
, &initsb
) < 0)
447 lxcfs_debug("Comparing ctime %ld == %ld for pid %d.\n", e
->ctime
,
448 initsb
.st_ctime
, e
->initpid
);
450 if (e
->ctime
!= initsb
.st_ctime
)
455 /* Must be called under store_lock */
456 static void remove_initpid(struct pidns_init_store
*e
)
458 struct pidns_init_store
*tmp
;
461 lxcfs_debug("Remove_initpid: removing entry for %d.\n", e
->initpid
);
464 if (pidns_hash_table
[h
] == e
) {
465 pidns_hash_table
[h
] = e
->next
;
470 tmp
= pidns_hash_table
[h
];
472 if (tmp
->next
== e
) {
482 /* Must be called under store_lock */
483 static void prune_initpid_store(void)
485 static long int last_prune
= 0;
486 struct pidns_init_store
*e
, *prev
, *delme
;
487 long int now
, threshold
;
491 last_prune
= time(NULL
);
495 if (now
< last_prune
+ PURGE_SECS
)
498 lxcfs_debug("%s\n", "Pruning.");
501 threshold
= now
- 2 * PURGE_SECS
;
503 for (i
= 0; i
< PIDNS_HASH_SIZE
; i
++) {
504 for (prev
= NULL
, e
= pidns_hash_table
[i
]; e
; ) {
505 if (e
->lastcheck
< threshold
) {
507 lxcfs_debug("Removing cached entry for %d.\n", e
->initpid
);
511 prev
->next
= e
->next
;
513 pidns_hash_table
[i
] = e
->next
;
524 /* Must be called under store_lock */
525 static void save_initpid(struct stat
*sb
, pid_t pid
)
527 struct pidns_init_store
*e
;
532 lxcfs_debug("Save_initpid: adding entry for %d.\n", pid
);
534 snprintf(fpath
, 100, "/proc/%d", pid
);
535 if (stat(fpath
, &procsb
) < 0)
538 e
= malloc(sizeof(*e
));
542 e
->ctime
= procsb
.st_ctime
;
544 e
->next
= pidns_hash_table
[h
];
545 e
->lastcheck
= time(NULL
);
546 pidns_hash_table
[h
] = e
;
550 * Given the stat(2) info for a nsfd pid inode, lookup the init_pid_store
551 * entry for the inode number and creation time. Verify that the init pid
552 * is still valid. If not, remove it. Return the entry if valid, NULL
554 * Must be called under store_lock
556 static struct pidns_init_store
*lookup_verify_initpid(struct stat
*sb
)
558 int h
= HASH(sb
->st_ino
);
559 struct pidns_init_store
*e
= pidns_hash_table
[h
];
562 if (e
->ino
== sb
->st_ino
) {
563 if (initpid_still_valid(e
, sb
)) {
564 e
->lastcheck
= time(NULL
);
576 static int is_dir(const char *path
, int fd
)
579 int ret
= fstatat(fd
, path
, &statbuf
, fd
);
580 if (ret
== 0 && S_ISDIR(statbuf
.st_mode
))
585 static int preserve_ns(const int pid
, const char *ns
)
588 /* 5 /proc + 21 /int_as_str + 3 /ns + 20 /NS_NAME + 1 \0 */
589 #define __NS_PATH_LEN 50
590 char path
[__NS_PATH_LEN
];
592 /* This way we can use this function to also check whether namespaces
593 * are supported by the kernel by passing in the NULL or the empty
596 ret
= snprintf(path
, __NS_PATH_LEN
, "/proc/%d/ns%s%s", pid
,
597 !ns
|| strcmp(ns
, "") == 0 ? "" : "/",
598 !ns
|| strcmp(ns
, "") == 0 ? "" : ns
);
599 if (ret
< 0 || (size_t)ret
>= __NS_PATH_LEN
) {
604 return open(path
, O_RDONLY
| O_CLOEXEC
);
608 * in_same_namespace - Check whether two processes are in the same namespace.
609 * @pid1 - PID of the first process.
610 * @pid2 - PID of the second process.
611 * @ns - Name of the namespace to check. Must correspond to one of the names
612 * for the namespaces as shown in /proc/<pid/ns/
614 * If the two processes are not in the same namespace returns an fd to the
615 * namespace of the second process identified by @pid2. If the two processes are
616 * in the same namespace returns -EINVAL, -1 if an error occurred.
618 static int in_same_namespace(pid_t pid1
, pid_t pid2
, const char *ns
)
620 __do_close_prot_errno
int ns_fd1
= -1, ns_fd2
= -1;
622 struct stat ns_st1
, ns_st2
;
624 ns_fd1
= preserve_ns(pid1
, ns
);
626 /* The kernel does not support this namespace. This is not an
635 ns_fd2
= preserve_ns(pid2
, ns
);
639 ret
= fstat(ns_fd1
, &ns_st1
);
643 ret
= fstat(ns_fd2
, &ns_st2
);
647 /* processes are in the same namespace */
648 if ((ns_st1
.st_dev
== ns_st2
.st_dev
) && (ns_st1
.st_ino
== ns_st2
.st_ino
))
651 /* processes are in different namespaces */
652 return move_fd(ns_fd2
);
655 static bool is_shared_pidns(pid_t pid
)
660 if (in_same_namespace(pid
, getpid(), "pid") == -EINVAL
)
666 static bool write_string(const char *fnam
, const char *string
, int fd
)
675 len
= strlen(string
);
676 ret
= fwrite(string
, 1, len
, f
);
678 lxcfs_error("%s - Error writing \"%s\" to \"%s\"\n",
679 strerror(errno
), string
, fnam
);
685 lxcfs_error("%s - Failed to close \"%s\"\n", strerror(errno
), fnam
);
698 static void print_subsystems(void)
702 fprintf(stderr
, "mount namespace: %d\n", cgroup_ops
->mntns_fd
);
703 fprintf(stderr
, "hierarchies:\n");
704 for (struct hierarchy
**h
= cgroup_ops
->hierarchies
; h
&& *h
; h
++, i
++) {
705 __do_free
char *controllers
= lxc_string_join(",", (const char **)(*h
)->controllers
, false);
706 fprintf(stderr
, " %2d: fd: %3d: %s\n", i
, (*h
)->fd
, controllers
?: "");
710 bool cgfs_set_value(const char *controller
, const char *cgroup
, const char *file
,
717 cfd
= get_cgroup_fd(controller
);
721 /* Make sure we pass a relative path to *at() family of functions.
722 * . + /cgroup + / + file + \0
724 len
= strlen(cgroup
) + strlen(file
) + 3;
726 ret
= snprintf(fnam
, len
, "%s%s/%s", dot_or_empty(cgroup
), cgroup
, file
);
727 if (ret
< 0 || (size_t)ret
>= len
)
730 fd
= openat(cfd
, fnam
, O_WRONLY
);
734 return write_string(fnam
, value
, fd
);
737 // Chown all the files in the cgroup directory. We do this when we create
738 // a cgroup on behalf of a user.
739 static void chown_all_cgroup_files(const char *dirname
, uid_t uid
, gid_t gid
, int fd
)
741 struct dirent
*direntp
;
742 char path
[MAXPATHLEN
];
747 len
= strlen(dirname
);
748 if (len
>= MAXPATHLEN
) {
749 lxcfs_error("Pathname too long: %s\n", dirname
);
753 fd1
= openat(fd
, dirname
, O_DIRECTORY
);
759 lxcfs_error("Failed to open %s\n", dirname
);
763 while ((direntp
= readdir(d
))) {
764 if (!strcmp(direntp
->d_name
, ".") || !strcmp(direntp
->d_name
, ".."))
766 ret
= snprintf(path
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
767 if (ret
< 0 || ret
>= MAXPATHLEN
) {
768 lxcfs_error("Pathname too long under %s\n", dirname
);
771 if (fchownat(fd
, path
, uid
, gid
, 0) < 0)
772 lxcfs_error("Failed to chown file %s to %u:%u", path
, uid
, gid
);
777 int cgfs_create(const char *controller
, const char *cg
, uid_t uid
, gid_t gid
)
783 cfd
= get_cgroup_fd(controller
);
787 /* Make sure we pass a relative path to *at() family of functions.
790 len
= strlen(cg
) + 2;
791 dirnam
= alloca(len
);
792 snprintf(dirnam
, len
, "%s%s", dot_or_empty(cg
), cg
);
794 if (mkdirat(cfd
, dirnam
, 0755) < 0)
797 if (uid
== 0 && gid
== 0)
800 if (fchownat(cfd
, dirnam
, uid
, gid
, 0) < 0)
803 chown_all_cgroup_files(dirnam
, uid
, gid
, cfd
);
808 static bool recursive_rmdir(const char *dirname
, int fd
, const int cfd
)
810 struct dirent
*direntp
;
813 char pathname
[MAXPATHLEN
];
816 dupfd
= dup(fd
); // fdopendir() does bad things once it uses an fd.
820 dir
= fdopendir(dupfd
);
822 lxcfs_debug("Failed to open %s: %s.\n", dirname
, strerror(errno
));
827 while ((direntp
= readdir(dir
))) {
831 if (!strcmp(direntp
->d_name
, ".") ||
832 !strcmp(direntp
->d_name
, ".."))
835 rc
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", dirname
, direntp
->d_name
);
836 if (rc
< 0 || rc
>= MAXPATHLEN
) {
837 lxcfs_error("%s\n", "Pathname too long.");
841 rc
= fstatat(cfd
, pathname
, &mystat
, AT_SYMLINK_NOFOLLOW
);
843 lxcfs_debug("Failed to stat %s: %s.\n", pathname
, strerror(errno
));
846 if (S_ISDIR(mystat
.st_mode
))
847 if (!recursive_rmdir(pathname
, fd
, cfd
))
848 lxcfs_debug("Error removing %s.\n", pathname
);
852 if (closedir(dir
) < 0) {
853 lxcfs_error("Failed to close directory %s: %s\n", dirname
, strerror(errno
));
857 if (unlinkat(cfd
, dirname
, AT_REMOVEDIR
) < 0) {
858 lxcfs_debug("Failed to delete %s: %s.\n", dirname
, strerror(errno
));
867 bool cgfs_remove(const char *controller
, const char *cg
)
874 cfd
= get_cgroup_fd(controller
);
878 /* Make sure we pass a relative path to *at() family of functions.
881 len
= strlen(cg
) + 2;
882 dirnam
= alloca(len
);
883 snprintf(dirnam
, len
, "%s%s", dot_or_empty(cg
), cg
);
885 fd
= openat(cfd
, dirnam
, O_DIRECTORY
);
889 bret
= recursive_rmdir(dirnam
, fd
, cfd
);
894 bool cgfs_chmod_file(const char *controller
, const char *file
, mode_t mode
)
900 cfd
= get_cgroup_fd(controller
);
904 /* Make sure we pass a relative path to *at() family of functions.
907 len
= strlen(file
) + 2;
908 pathname
= alloca(len
);
909 snprintf(pathname
, len
, "%s%s", dot_or_empty(file
), file
);
910 if (fchmodat(cfd
, pathname
, mode
, 0) < 0)
915 static int chown_tasks_files(const char *dirname
, uid_t uid
, gid_t gid
, int fd
)
920 len
= strlen(dirname
) + strlen("/cgroup.procs") + 1;
922 snprintf(fname
, len
, "%s/tasks", dirname
);
923 if (fchownat(fd
, fname
, uid
, gid
, 0) != 0)
925 snprintf(fname
, len
, "%s/cgroup.procs", dirname
);
926 if (fchownat(fd
, fname
, uid
, gid
, 0) != 0)
931 int cgfs_chown_file(const char *controller
, const char *file
, uid_t uid
, gid_t gid
)
937 cfd
= get_cgroup_fd(controller
);
941 /* Make sure we pass a relative path to *at() family of functions.
944 len
= strlen(file
) + 2;
945 pathname
= alloca(len
);
946 snprintf(pathname
, len
, "%s%s", dot_or_empty(file
), file
);
947 if (fchownat(cfd
, pathname
, uid
, gid
, 0) < 0)
950 if (is_dir(pathname
, cfd
))
951 // like cgmanager did, we want to chown the tasks file as well
952 return chown_tasks_files(pathname
, uid
, gid
, cfd
);
957 FILE *open_pids_file(const char *controller
, const char *cgroup
)
963 cfd
= get_cgroup_fd(controller
);
967 /* Make sure we pass a relative path to *at() family of functions.
968 * . + /cgroup + / "cgroup.procs" + \0
970 len
= strlen(cgroup
) + strlen("cgroup.procs") + 3;
971 pathname
= alloca(len
);
972 snprintf(pathname
, len
, "%s%s/cgroup.procs", dot_or_empty(cgroup
), cgroup
);
974 fd
= openat(cfd
, pathname
, O_WRONLY
);
978 return fdopen(fd
, "w");
981 static bool cgfs_iterate_cgroup(const char *controller
, const char *cgroup
, bool directories
,
982 void ***list
, size_t typesize
,
983 void* (*iterator
)(const char*, const char*, const char*))
988 char pathname
[MAXPATHLEN
];
989 size_t sz
= 0, asz
= 0;
990 struct dirent
*dirent
;
993 cfd
= get_cgroup_fd(controller
);
998 /* Make sure we pass a relative path to *at() family of functions. */
999 len
= strlen(cgroup
) + 1 /* . */ + 1 /* \0 */;
1001 ret
= snprintf(cg
, len
, "%s%s", dot_or_empty(cgroup
), cgroup
);
1002 if (ret
< 0 || (size_t)ret
>= len
) {
1003 lxcfs_error("Pathname too long under %s\n", cgroup
);
1007 fd
= openat(cfd
, cg
, O_DIRECTORY
);
1011 dir
= fdopendir(fd
);
1015 while ((dirent
= readdir(dir
))) {
1018 if (!strcmp(dirent
->d_name
, ".") ||
1019 !strcmp(dirent
->d_name
, ".."))
1022 ret
= snprintf(pathname
, MAXPATHLEN
, "%s/%s", cg
, dirent
->d_name
);
1023 if (ret
< 0 || ret
>= MAXPATHLEN
) {
1024 lxcfs_error("Pathname too long under %s\n", cg
);
1028 ret
= fstatat(cfd
, pathname
, &mystat
, AT_SYMLINK_NOFOLLOW
);
1030 lxcfs_error("Failed to stat %s: %s\n", pathname
, strerror(errno
));
1033 if ((!directories
&& !S_ISREG(mystat
.st_mode
)) ||
1034 (directories
&& !S_ISDIR(mystat
.st_mode
)))
1041 tmp
= realloc(*list
, asz
* typesize
);
1045 (*list
)[sz
] = (*iterator
)(controller
, cg
, dirent
->d_name
);
1046 (*list
)[sz
+1] = NULL
;
1049 if (closedir(dir
) < 0) {
1050 lxcfs_error("Failed closedir for %s: %s\n", cgroup
, strerror(errno
));
1056 static void *make_children_list_entry(const char *controller
, const char *cgroup
, const char *dir_entry
)
1060 dup
= strdup(dir_entry
);
1065 bool cgfs_list_children(const char *controller
, const char *cgroup
, char ***list
)
1067 return cgfs_iterate_cgroup(controller
, cgroup
, true, (void***)list
, sizeof(*list
), &make_children_list_entry
);
1070 void free_key(struct cgfs_files
*k
)
1074 free_disarm(k
->name
);
1078 void free_keys(struct cgfs_files
**keys
)
1084 for (i
= 0; keys
[i
]; i
++) {
1090 bool cgfs_param_exist(const char *controller
, const char *cgroup
, const char *file
)
1096 cfd
= get_cgroup_fd(controller
);
1100 /* Make sure we pass a relative path to *at() family of functions.
1101 * . + /cgroup + / + file + \0
1103 len
= strlen(cgroup
) + strlen(file
) + 3;
1105 ret
= snprintf(fnam
, len
, "%s%s/%s", dot_or_empty(cgroup
), cgroup
, file
);
1106 if (ret
< 0 || (size_t)ret
>= len
)
1109 return (faccessat(cfd
, fnam
, F_OK
, 0) == 0);
1112 struct cgfs_files
*cgfs_get_key(const char *controller
, const char *cgroup
, const char *file
)
1118 struct cgfs_files
*newkey
;
1120 cfd
= get_cgroup_fd(controller
);
1124 if (file
&& *file
== '/')
1127 if (file
&& strchr(file
, '/'))
1130 /* Make sure we pass a relative path to *at() family of functions.
1131 * . + /cgroup + / + file + \0
1133 len
= strlen(cgroup
) + 3;
1135 len
+= strlen(file
) + 1;
1137 snprintf(fnam
, len
, "%s%s%s%s", dot_or_empty(cgroup
), cgroup
,
1138 file
? "/" : "", file
? file
: "");
1140 ret
= fstatat(cfd
, fnam
, &sb
, 0);
1145 newkey
= malloc(sizeof(struct cgfs_files
));
1148 newkey
->name
= must_copy_string(file
);
1149 else if (strrchr(cgroup
, '/'))
1150 newkey
->name
= must_copy_string(strrchr(cgroup
, '/'));
1152 newkey
->name
= must_copy_string(cgroup
);
1153 newkey
->uid
= sb
.st_uid
;
1154 newkey
->gid
= sb
.st_gid
;
1155 newkey
->mode
= sb
.st_mode
;
1160 static void *make_key_list_entry(const char *controller
, const char *cgroup
, const char *dir_entry
)
1162 struct cgfs_files
*entry
= cgfs_get_key(controller
, cgroup
, dir_entry
);
1164 lxcfs_error("Error getting files under %s:%s\n", controller
,
1170 bool cgfs_list_keys(const char *controller
, const char *cgroup
, struct cgfs_files
***keys
)
1172 return cgfs_iterate_cgroup(controller
, cgroup
, false, (void***)keys
, sizeof(*keys
), &make_key_list_entry
);
1175 bool is_child_cgroup(const char *controller
, const char *cgroup
, const char *f
)
1183 cfd
= get_cgroup_fd(controller
);
1187 /* Make sure we pass a relative path to *at() family of functions.
1188 * . + /cgroup + / + f + \0
1190 len
= strlen(cgroup
) + strlen(f
) + 3;
1192 ret
= snprintf(fnam
, len
, "%s%s/%s", dot_or_empty(cgroup
), cgroup
, f
);
1193 if (ret
< 0 || (size_t)ret
>= len
)
1196 ret
= fstatat(cfd
, fnam
, &sb
, 0);
1197 if (ret
< 0 || !S_ISDIR(sb
.st_mode
))
1203 #define SEND_CREDS_OK 0
1204 #define SEND_CREDS_NOTSK 1
1205 #define SEND_CREDS_FAIL 2
1206 static bool recv_creds(int sock
, struct ucred
*cred
, char *v
);
1207 static int wait_for_pid(pid_t pid
);
1208 static int send_creds(int sock
, struct ucred
*cred
, char v
, bool pingfirst
);
1209 static int send_creds_clone_wrapper(void *arg
);
1212 * clone a task which switches to @task's namespace and writes '1'.
1213 * over a unix sock so we can read the task's reaper's pid in our
1216 * Note: glibc's fork() does not respect pidns, which can lead to failed
1217 * assertions inside glibc (and thus failed forks) if the child's pid in
1218 * the pidns and the parent pid outside are identical. Using clone prevents
1221 static void write_task_init_pid_exit(int sock
, pid_t target
)
1226 size_t stack_size
= sysconf(_SC_PAGESIZE
);
1227 void *stack
= alloca(stack_size
);
1229 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", (int)target
);
1230 if (ret
< 0 || ret
>= sizeof(fnam
))
1233 fd
= open(fnam
, O_RDONLY
);
1235 perror("write_task_init_pid_exit open of ns/pid");
1239 perror("write_task_init_pid_exit setns 1");
1243 pid
= clone(send_creds_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &sock
);
1247 if (!wait_for_pid(pid
))
1253 static int send_creds_clone_wrapper(void *arg
) {
1256 int sock
= *(int *)arg
;
1258 /* we are the child */
1263 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
)
1268 static pid_t
get_init_pid_for_task(pid_t task
)
1276 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
1277 perror("socketpair");
1286 write_task_init_pid_exit(sock
[0], task
);
1290 if (!recv_creds(sock
[1], &cred
, &v
))
1302 pid_t
lookup_initpid_in_store(pid_t qpid
)
1306 struct pidns_init_store
*e
;
1309 snprintf(fnam
, 100, "/proc/%d/ns/pid", qpid
);
1311 if (stat(fnam
, &sb
) < 0)
1313 e
= lookup_verify_initpid(&sb
);
1315 answer
= e
->initpid
;
1318 answer
= get_init_pid_for_task(qpid
);
1320 save_initpid(&sb
, answer
);
1323 /* we prune at end in case we are returning
1324 * the value we were about to return */
1325 prune_initpid_store();
1330 static int wait_for_pid(pid_t pid
)
1338 ret
= waitpid(pid
, &status
, 0);
1346 if (!WIFEXITED(status
) || WEXITSTATUS(status
) != 0)
1352 * append the given formatted string to *src.
1353 * src: a pointer to a char* in which to append the formatted string.
1354 * sz: the number of characters printed so far, minus trailing \0.
1355 * asz: the allocated size so far
1356 * format: string format. See printf for details.
1357 * ...: varargs. See printf for details.
1359 static void must_strcat(char **src
, size_t *sz
, size_t *asz
, const char *format
, ...)
1361 char tmp
[BUF_RESERVE_SIZE
];
1364 va_start (args
, format
);
1365 int tmplen
= vsnprintf(tmp
, BUF_RESERVE_SIZE
, format
, args
);
1368 if (!*src
|| tmplen
+ *sz
+ 1 >= *asz
) {
1371 tmp
= realloc(*src
, *asz
+ BUF_RESERVE_SIZE
);
1374 *asz
+= BUF_RESERVE_SIZE
;
1376 memcpy((*src
) +*sz
, tmp
, tmplen
+1); /* include the \0 */
1381 * append pid to *src.
1382 * src: a pointer to a char* in which ot append the pid.
1383 * sz: the number of characters printed so far, minus trailing \0.
1384 * asz: the allocated size so far
1385 * pid: the pid to append
1387 static void must_strcat_pid(char **src
, size_t *sz
, size_t *asz
, pid_t pid
)
1389 must_strcat(src
, sz
, asz
, "%d\n", (int)pid
);
1393 * Given a open file * to /proc/pid/{u,g}id_map, and an id
1394 * valid in the caller's namespace, return the id mapped into
1396 * Returns the mapped id, or -1 on error.
1399 convert_id_to_ns(FILE *idfile
, unsigned int in_id
)
1401 unsigned int nsuid
, // base id for a range in the idfile's namespace
1402 hostuid
, // base id for a range in the caller's namespace
1403 count
; // number of ids in this range
1407 fseek(idfile
, 0L, SEEK_SET
);
1408 while (fgets(line
, 400, idfile
)) {
1409 ret
= sscanf(line
, "%u %u %u\n", &nsuid
, &hostuid
, &count
);
1412 if (hostuid
+ count
< hostuid
|| nsuid
+ count
< nsuid
) {
1414 * uids wrapped around - unexpected as this is a procfile,
1417 lxcfs_error("pid wrapparound at entry %u %u %u in %s\n",
1418 nsuid
, hostuid
, count
, line
);
1421 if (hostuid
<= in_id
&& hostuid
+count
> in_id
) {
1423 * now since hostuid <= in_id < hostuid+count, and
1424 * hostuid+count and nsuid+count do not wrap around,
1425 * we know that nsuid+(in_id-hostuid) which must be
1426 * less that nsuid+(count) must not wrap around
1428 return (in_id
- hostuid
) + nsuid
;
1437 * for is_privileged_over,
1438 * specify whether we require the calling uid to be root in his
1441 #define NS_ROOT_REQD true
1442 #define NS_ROOT_OPT false
1446 static bool is_privileged_over(pid_t pid
, uid_t uid
, uid_t victim
, bool req_ns_root
)
1448 char fpath
[PROCLEN
];
1450 bool answer
= false;
1453 if (victim
== -1 || uid
== -1)
1457 * If the request is one not requiring root in the namespace,
1458 * then having the same uid suffices. (i.e. uid 1000 has write
1459 * access to files owned by uid 1000
1461 if (!req_ns_root
&& uid
== victim
)
1464 ret
= snprintf(fpath
, PROCLEN
, "/proc/%d/uid_map", pid
);
1465 if (ret
< 0 || ret
>= PROCLEN
)
1467 FILE *f
= fopen(fpath
, "r");
1471 /* if caller's not root in his namespace, reject */
1472 nsuid
= convert_id_to_ns(f
, uid
);
1477 * If victim is not mapped into caller's ns, reject.
1478 * XXX I'm not sure this check is needed given that fuse
1479 * will be sending requests where the vfs has converted
1481 nsuid
= convert_id_to_ns(f
, victim
);
1492 static bool perms_include(int fmode
, mode_t req_mode
)
1496 switch (req_mode
& O_ACCMODE
) {
1504 r
= S_IROTH
| S_IWOTH
;
1509 return ((fmode
& r
) == r
);
1515 * querycg is /a/b/c/d/e
1518 static char *get_next_cgroup_dir(const char *taskcg
, const char *querycg
)
1522 if (strlen(taskcg
) <= strlen(querycg
)) {
1523 lxcfs_error("%s\n", "I was fed bad input.");
1527 if ((strcmp(querycg
, "/") == 0) || (strcmp(querycg
, "./") == 0))
1528 start
= strdup(taskcg
+ 1);
1530 start
= strdup(taskcg
+ strlen(querycg
) + 1);
1533 end
= strchr(start
, '/');
1539 char *get_pid_cgroup(pid_t pid
, const char *contrl
)
1543 cfd
= get_cgroup_fd(contrl
);
1547 if (pure_unified_layout(cgroup_ops
))
1548 return cg_unified_get_current_cgroup(pid
);
1550 return cg_legacy_get_current_cgroup(pid
, contrl
);
1554 * check whether a fuse context may access a cgroup dir or file
1556 * If file is not null, it is a cgroup file to check under cg.
1557 * If file is null, then we are checking perms on cg itself.
1559 * For files we can check the mode of the list_keys result.
1560 * For cgroups, we must make assumptions based on the files under the
1561 * cgroup, because cgmanager doesn't tell us ownership/perms of cgroups
1564 static bool fc_may_access(struct fuse_context
*fc
, const char *contrl
, const char *cg
, const char *file
, mode_t mode
)
1566 struct cgfs_files
*k
= NULL
;
1569 k
= cgfs_get_key(contrl
, cg
, file
);
1573 if (is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
1574 if (perms_include(k
->mode
>> 6, mode
)) {
1579 if (fc
->gid
== k
->gid
) {
1580 if (perms_include(k
->mode
>> 3, mode
)) {
1585 ret
= perms_include(k
->mode
, mode
);
1592 #define INITSCOPE "/init.scope"
1593 void prune_init_slice(char *cg
)
1596 size_t cg_len
= strlen(cg
), initscope_len
= strlen(INITSCOPE
);
1598 if (cg_len
< initscope_len
)
1601 point
= cg
+ cg_len
- initscope_len
;
1602 if (strcmp(point
, INITSCOPE
) == 0) {
1611 * If pid is in /a/b/c/d, he may only act on things under cg=/a/b/c/d.
1612 * If pid is in /a, he may act on /a/b, but not on /b.
1613 * if the answer is false and nextcg is not NULL, then *nextcg will point
1614 * to a string containing the next cgroup directory under cg, which must be
1615 * freed by the caller.
1617 static bool caller_is_in_ancestor(pid_t pid
, const char *contrl
, const char *cg
, char **nextcg
)
1619 bool answer
= false;
1620 char *c2
= get_pid_cgroup(pid
, contrl
);
1625 prune_init_slice(c2
);
1628 * callers pass in '/' or './' (openat()) for root cgroup, otherwise
1629 * they pass in a cgroup without leading '/'
1631 * The original line here was:
1632 * linecmp = *cg == '/' ? c2 : c2+1;
1633 * TODO: I'm not sure why you'd want to increment when *cg != '/'?
1634 * Serge, do you know?
1636 if (*cg
== '/' || !strncmp(cg
, "./", 2))
1640 if (strncmp(linecmp
, cg
, strlen(linecmp
)) != 0) {
1642 *nextcg
= get_next_cgroup_dir(linecmp
, cg
);
1654 * If pid is in /a/b/c, he may see that /a exists, but not /b or /a/c.
1656 static bool caller_may_see_dir(pid_t pid
, const char *contrl
, const char *cg
)
1658 bool answer
= false;
1660 size_t target_len
, task_len
;
1662 if (strcmp(cg
, "/") == 0 || strcmp(cg
, "./") == 0)
1665 c2
= get_pid_cgroup(pid
, contrl
);
1668 prune_init_slice(c2
);
1671 target_len
= strlen(cg
);
1672 task_len
= strlen(task_cg
);
1673 if (task_len
== 0) {
1674 /* Task is in the root cg, it can see everything. This case is
1675 * not handled by the strmcps below, since they test for the
1676 * last /, but that is the first / that we've chopped off
1682 if (strcmp(cg
, task_cg
) == 0) {
1686 if (target_len
< task_len
) {
1687 /* looking up a parent dir */
1688 if (strncmp(task_cg
, cg
, target_len
) == 0 && task_cg
[target_len
] == '/')
1692 if (target_len
> task_len
) {
1693 /* looking up a child dir */
1694 if (strncmp(task_cg
, cg
, task_len
) == 0 && cg
[task_len
] == '/')
1705 * given /cgroup/freezer/a/b, return "freezer".
1706 * the returned char* should NOT be freed.
1708 static char *pick_controller_from_path(struct fuse_context
*fc
, const char *path
)
1711 char *contr
, *slash
;
1713 if (strlen(path
) < 9) {
1717 if (*(path
+ 7) != '/') {
1722 contr
= strdupa(p1
);
1727 slash
= strstr(contr
, "/");
1731 for (struct hierarchy
**h
= cgroup_ops
->hierarchies
; h
&& *h
; h
++) {
1732 if ((*h
)->__controllers
&& strcmp((*h
)->__controllers
, contr
) == 0)
1733 return (*h
)->__controllers
;
1740 * Find the start of cgroup in /cgroup/controller/the/cgroup/path
1741 * Note that the returned value may include files (keynames) etc
1743 static const char *find_cgroup_in_path(const char *path
)
1747 if (strlen(path
) < 9) {
1751 p1
= strstr(path
+ 8, "/");
1761 * split the last path element from the path in @cg.
1762 * @dir is newly allocated and should be freed, @last not
1764 static void get_cgdir_and_path(const char *cg
, char **dir
, char **last
)
1771 *last
= strrchr(cg
, '/');
1776 p
= strrchr(*dir
, '/');
1781 * FUSE ops for /cgroup
1784 int cg_getattr(const char *path
, struct stat
*sb
)
1786 struct timespec now
;
1787 struct fuse_context
*fc
= fuse_get_context();
1788 char * cgdir
= NULL
;
1789 char *last
= NULL
, *path1
, *path2
;
1790 struct cgfs_files
*k
= NULL
;
1792 const char *controller
= NULL
;
1796 if (!fc
|| !cgroup_ops
|| pure_unified_layout(cgroup_ops
))
1799 memset(sb
, 0, sizeof(struct stat
));
1801 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
1804 sb
->st_uid
= sb
->st_gid
= 0;
1805 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
1808 if (strcmp(path
, "/cgroup") == 0) {
1809 sb
->st_mode
= S_IFDIR
| 00755;
1814 controller
= pick_controller_from_path(fc
, path
);
1817 cgroup
= find_cgroup_in_path(path
);
1819 /* this is just /cgroup/controller, return it as a dir */
1820 sb
->st_mode
= S_IFDIR
| 00755;
1825 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
1835 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1836 if (initpid
<= 1 || is_shared_pidns(initpid
))
1838 /* check that cgcopy is either a child cgroup of cgdir, or listed in its keys.
1839 * Then check that caller's cgroup is under path if last is a child
1840 * cgroup, or cgdir if last is a file */
1842 if (is_child_cgroup(controller
, path1
, path2
)) {
1843 if (!caller_may_see_dir(initpid
, controller
, cgroup
)) {
1847 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, NULL
)) {
1848 /* this is just /cgroup/controller, return it as a dir */
1849 sb
->st_mode
= S_IFDIR
| 00555;
1854 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
)) {
1859 // get uid, gid, from '/tasks' file and make up a mode
1860 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
1861 sb
->st_mode
= S_IFDIR
| 00755;
1862 k
= cgfs_get_key(controller
, cgroup
, NULL
);
1864 sb
->st_uid
= sb
->st_gid
= 0;
1866 sb
->st_uid
= k
->uid
;
1867 sb
->st_gid
= k
->gid
;
1875 if ((k
= cgfs_get_key(controller
, path1
, path2
)) != NULL
) {
1876 sb
->st_mode
= S_IFREG
| k
->mode
;
1878 sb
->st_uid
= k
->uid
;
1879 sb
->st_gid
= k
->gid
;
1882 if (!caller_is_in_ancestor(initpid
, controller
, path1
, NULL
)) {
1894 int cg_opendir(const char *path
, struct fuse_file_info
*fi
)
1896 struct fuse_context
*fc
= fuse_get_context();
1898 struct file_info
*dir_info
;
1899 char *controller
= NULL
;
1901 if (!fc
|| !cgroup_ops
|| pure_unified_layout(cgroup_ops
))
1904 if (strcmp(path
, "/cgroup") == 0) {
1908 // return list of keys for the controller, and list of child cgroups
1909 controller
= pick_controller_from_path(fc
, path
);
1913 cgroup
= find_cgroup_in_path(path
);
1915 /* this is just /cgroup/controller, return its contents */
1920 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1921 if (initpid
<= 1 || is_shared_pidns(initpid
))
1924 if (!caller_may_see_dir(initpid
, controller
, cgroup
))
1926 if (!fc_may_access(fc
, controller
, cgroup
, NULL
, O_RDONLY
))
1930 /* we'll free this at cg_releasedir */
1931 dir_info
= malloc(sizeof(*dir_info
));
1934 dir_info
->controller
= must_copy_string(controller
);
1935 dir_info
->cgroup
= must_copy_string(cgroup
);
1936 dir_info
->type
= LXC_TYPE_CGDIR
;
1937 dir_info
->buf
= NULL
;
1938 dir_info
->file
= NULL
;
1939 dir_info
->buflen
= 0;
1941 fi
->fh
= (unsigned long)dir_info
;
1945 int cg_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
1946 struct fuse_file_info
*fi
)
1948 struct file_info
*d
= (struct file_info
*)fi
->fh
;
1949 struct cgfs_files
**list
= NULL
;
1951 char *nextcg
= NULL
;
1952 struct fuse_context
*fc
= fuse_get_context();
1953 char **clist
= NULL
;
1955 if (!fc
|| !cgroup_ops
|| pure_unified_layout(cgroup_ops
))
1958 if (filler(buf
, ".", NULL
, 0) != 0 || filler(buf
, "..", NULL
, 0) != 0)
1961 if (d
->type
!= LXC_TYPE_CGDIR
) {
1962 lxcfs_error("%s\n", "Internal error: file cache info used in readdir.");
1965 if (!d
->cgroup
&& !d
->controller
) {
1967 * ls /var/lib/lxcfs/cgroup - just show list of controllers.
1968 * This only works with the legacy hierarchy.
1970 for (struct hierarchy
**h
= cgroup_ops
->hierarchies
; h
&& *h
; h
++) {
1971 if (is_unified_hierarchy(*h
))
1974 if ((*h
)->__controllers
&& filler(buf
, (*h
)->__controllers
, NULL
, 0))
1981 if (!cgfs_list_keys(d
->controller
, d
->cgroup
, &list
)) {
1982 // not a valid cgroup
1987 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
1988 if (initpid
<= 1 || is_shared_pidns(initpid
))
1990 if (!caller_is_in_ancestor(initpid
, d
->controller
, d
->cgroup
, &nextcg
)) {
1992 ret
= filler(buf
, nextcg
, NULL
, 0);
2003 for (i
= 0; list
&& list
[i
]; i
++) {
2004 if (filler(buf
, list
[i
]->name
, NULL
, 0) != 0) {
2010 // now get the list of child cgroups
2012 if (!cgfs_list_children(d
->controller
, d
->cgroup
, &clist
)) {
2017 for (i
= 0; clist
[i
]; i
++) {
2018 if (filler(buf
, clist
[i
], NULL
, 0) != 0) {
2029 for (i
= 0; clist
[i
]; i
++)
2036 void do_release_file_info(struct fuse_file_info
*fi
)
2038 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2045 free_disarm(f
->controller
);
2046 free_disarm(f
->cgroup
);
2047 free_disarm(f
->file
);
2048 free_disarm(f
->buf
);
2052 int cg_releasedir(const char *path
, struct fuse_file_info
*fi
)
2054 do_release_file_info(fi
);
2058 int cg_open(const char *path
, struct fuse_file_info
*fi
)
2061 char *last
= NULL
, *path1
, *path2
, * cgdir
= NULL
, *controller
;
2062 struct cgfs_files
*k
= NULL
;
2063 struct file_info
*file_info
;
2064 struct fuse_context
*fc
= fuse_get_context();
2067 if (!fc
|| !cgroup_ops
|| pure_unified_layout(cgroup_ops
))
2070 controller
= pick_controller_from_path(fc
, path
);
2073 cgroup
= find_cgroup_in_path(path
);
2077 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2086 k
= cgfs_get_key(controller
, path1
, path2
);
2093 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2094 if (initpid
<= 1 || is_shared_pidns(initpid
))
2096 if (!caller_may_see_dir(initpid
, controller
, path1
)) {
2100 if (!fc_may_access(fc
, controller
, path1
, path2
, fi
->flags
)) {
2105 /* we'll free this at cg_release */
2106 file_info
= malloc(sizeof(*file_info
));
2111 file_info
->controller
= must_copy_string(controller
);
2112 file_info
->cgroup
= must_copy_string(path1
);
2113 file_info
->file
= must_copy_string(path2
);
2114 file_info
->type
= LXC_TYPE_CGFILE
;
2115 file_info
->buf
= NULL
;
2116 file_info
->buflen
= 0;
2118 fi
->fh
= (unsigned long)file_info
;
2126 int cg_access(const char *path
, int mode
)
2130 char *path1
, *path2
, *controller
;
2131 char *last
= NULL
, *cgdir
= NULL
;
2132 struct cgfs_files
*k
= NULL
;
2133 struct fuse_context
*fc
= fuse_get_context();
2135 if (!fc
|| !cgroup_ops
|| pure_unified_layout(cgroup_ops
))
2138 if (strcmp(path
, "/cgroup") == 0)
2141 controller
= pick_controller_from_path(fc
, path
);
2144 cgroup
= find_cgroup_in_path(path
);
2146 // access("/sys/fs/cgroup/systemd", mode) - rx allowed, w not
2147 if ((mode
& W_OK
) == 0)
2152 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2161 k
= cgfs_get_key(controller
, path1
, path2
);
2163 if ((mode
& W_OK
) == 0)
2171 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
2172 if (initpid
<= 1 || is_shared_pidns(initpid
))
2174 if (!caller_may_see_dir(initpid
, controller
, path1
)) {
2178 if (!fc_may_access(fc
, controller
, path1
, path2
, mode
)) {
2190 int cg_release(const char *path
, struct fuse_file_info
*fi
)
2192 do_release_file_info(fi
);
2196 #define POLLIN_SET ( EPOLLIN | EPOLLHUP | EPOLLRDHUP )
2198 static bool wait_for_sock(int sock
, int timeout
)
2200 struct epoll_event ev
;
2201 int epfd
, ret
, now
, starttime
, deltatime
, saved_errno
;
2203 if ((starttime
= time(NULL
)) < 0)
2206 if ((epfd
= epoll_create(1)) < 0) {
2207 lxcfs_error("%s\n", "Failed to create epoll socket: %m.");
2211 ev
.events
= POLLIN_SET
;
2213 if (epoll_ctl(epfd
, EPOLL_CTL_ADD
, sock
, &ev
) < 0) {
2214 lxcfs_error("%s\n", "Failed adding socket to epoll: %m.");
2220 if ((now
= time(NULL
)) < 0) {
2225 deltatime
= (starttime
+ timeout
) - now
;
2226 if (deltatime
< 0) { // timeout
2231 ret
= epoll_wait(epfd
, &ev
, 1, 1000*deltatime
+ 1);
2232 if (ret
< 0 && errno
== EINTR
)
2234 saved_errno
= errno
;
2238 errno
= saved_errno
;
2244 static int msgrecv(int sockfd
, void *buf
, size_t len
)
2246 if (!wait_for_sock(sockfd
, 2))
2248 return recv(sockfd
, buf
, len
, MSG_DONTWAIT
);
2251 static int send_creds(int sock
, struct ucred
*cred
, char v
, bool pingfirst
)
2253 struct msghdr msg
= { 0 };
2255 struct cmsghdr
*cmsg
;
2256 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
2261 if (msgrecv(sock
, buf
, 1) != 1) {
2262 lxcfs_error("%s\n", "Error getting reply from server over socketpair.");
2263 return SEND_CREDS_FAIL
;
2267 msg
.msg_control
= cmsgbuf
;
2268 msg
.msg_controllen
= sizeof(cmsgbuf
);
2270 cmsg
= CMSG_FIRSTHDR(&msg
);
2271 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct ucred
));
2272 cmsg
->cmsg_level
= SOL_SOCKET
;
2273 cmsg
->cmsg_type
= SCM_CREDENTIALS
;
2274 memcpy(CMSG_DATA(cmsg
), cred
, sizeof(*cred
));
2276 msg
.msg_name
= NULL
;
2277 msg
.msg_namelen
= 0;
2281 iov
.iov_len
= sizeof(buf
);
2285 if (sendmsg(sock
, &msg
, 0) < 0) {
2286 lxcfs_error("Failed at sendmsg: %s.\n",strerror(errno
));
2288 return SEND_CREDS_NOTSK
;
2289 return SEND_CREDS_FAIL
;
2292 return SEND_CREDS_OK
;
2295 static bool recv_creds(int sock
, struct ucred
*cred
, char *v
)
2297 struct msghdr msg
= { 0 };
2299 struct cmsghdr
*cmsg
;
2300 char cmsgbuf
[CMSG_SPACE(sizeof(*cred
))];
2311 if (setsockopt(sock
, SOL_SOCKET
, SO_PASSCRED
, &optval
, sizeof(optval
)) == -1) {
2312 lxcfs_error("Failed to set passcred: %s\n", strerror(errno
));
2316 if (write(sock
, buf
, 1) != 1) {
2317 lxcfs_error("Failed to start write on scm fd: %s\n", strerror(errno
));
2321 msg
.msg_name
= NULL
;
2322 msg
.msg_namelen
= 0;
2323 msg
.msg_control
= cmsgbuf
;
2324 msg
.msg_controllen
= sizeof(cmsgbuf
);
2327 iov
.iov_len
= sizeof(buf
);
2331 if (!wait_for_sock(sock
, 2)) {
2332 lxcfs_error("Timed out waiting for scm_cred: %s\n", strerror(errno
));
2335 ret
= recvmsg(sock
, &msg
, MSG_DONTWAIT
);
2337 lxcfs_error("Failed to receive scm_cred: %s\n", strerror(errno
));
2341 cmsg
= CMSG_FIRSTHDR(&msg
);
2343 if (cmsg
&& cmsg
->cmsg_len
== CMSG_LEN(sizeof(struct ucred
)) &&
2344 cmsg
->cmsg_level
== SOL_SOCKET
&&
2345 cmsg
->cmsg_type
== SCM_CREDENTIALS
) {
2346 memcpy(cred
, CMSG_DATA(cmsg
), sizeof(*cred
));
2353 struct pid_ns_clone_args
{
2357 int (*wrapped
) (int, pid_t
); // pid_from_ns or pid_to_ns
2361 * pid_ns_clone_wrapper - wraps pid_to_ns or pid_from_ns for usage
2362 * with clone(). This simply writes '1' as ACK back to the parent
2363 * before calling the actual wrapped function.
2365 static int pid_ns_clone_wrapper(void *arg
) {
2366 struct pid_ns_clone_args
* args
= (struct pid_ns_clone_args
*) arg
;
2369 close(args
->cpipe
[0]);
2370 if (write(args
->cpipe
[1], &b
, sizeof(char)) < 0)
2371 lxcfs_error("(child): error on write: %s.\n", strerror(errno
));
2372 close(args
->cpipe
[1]);
2373 return args
->wrapped(args
->sock
, args
->tpid
);
2377 * pid_to_ns - reads pids from a ucred over a socket, then writes the
2378 * int value back over the socket. This shifts the pid from the
2379 * sender's pidns into tpid's pidns.
2381 static int pid_to_ns(int sock
, pid_t tpid
)
2386 while (recv_creds(sock
, &cred
, &v
)) {
2389 if (write(sock
, &cred
.pid
, sizeof(pid_t
)) != sizeof(pid_t
))
2397 * pid_to_ns_wrapper: when you setns into a pidns, you yourself remain
2398 * in your old pidns. Only children which you clone will be in the target
2399 * pidns. So the pid_to_ns_wrapper does the setns, then clones a child to
2400 * actually convert pids.
2402 * Note: glibc's fork() does not respect pidns, which can lead to failed
2403 * assertions inside glibc (and thus failed forks) if the child's pid in
2404 * the pidns and the parent pid outside are identical. Using clone prevents
2407 static void pid_to_ns_wrapper(int sock
, pid_t tpid
)
2409 int newnsfd
= -1, ret
, cpipe
[2];
2414 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
2415 if (ret
< 0 || ret
>= sizeof(fnam
))
2417 newnsfd
= open(fnam
, O_RDONLY
);
2420 if (setns(newnsfd
, 0) < 0)
2424 if (pipe(cpipe
) < 0)
2427 struct pid_ns_clone_args args
= {
2431 .wrapped
= &pid_to_ns
2433 size_t stack_size
= sysconf(_SC_PAGESIZE
);
2434 void *stack
= alloca(stack_size
);
2436 cpid
= clone(pid_ns_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &args
);
2440 // give the child 1 second to be done forking and
2442 if (!wait_for_sock(cpipe
[0], 1))
2444 ret
= read(cpipe
[0], &v
, 1);
2445 if (ret
!= sizeof(char) || v
!= '1')
2448 if (!wait_for_pid(cpid
))
2454 * To read cgroup files with a particular pid, we will setns into the child
2455 * pidns, open a pipe, fork a child - which will be the first to really be in
2456 * the child ns - which does the cgfs_get_value and writes the data to the pipe.
2458 bool do_read_pids(pid_t tpid
, const char *contrl
, const char *cg
, const char *file
, char **d
)
2460 int sock
[2] = {-1, -1};
2461 char *tmpdata
= NULL
;
2463 pid_t qpid
, cpid
= -1;
2464 bool answer
= false;
2467 size_t sz
= 0, asz
= 0;
2469 if (!cgroup_ops
->get(cgroup_ops
, contrl
, cg
, file
, &tmpdata
))
2473 * Now we read the pids from returned data one by one, pass
2474 * them into a child in the target namespace, read back the
2475 * translated pids, and put them into our to-return data
2478 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
2479 perror("socketpair");
2488 if (!cpid
) // child - exits when done
2489 pid_to_ns_wrapper(sock
[1], tpid
);
2491 char *ptr
= tmpdata
;
2494 while (sscanf(ptr
, "%d\n", &qpid
) == 1) {
2496 ret
= send_creds(sock
[0], &cred
, v
, true);
2498 if (ret
== SEND_CREDS_NOTSK
)
2500 if (ret
== SEND_CREDS_FAIL
)
2503 // read converted results
2504 if (!wait_for_sock(sock
[0], 2)) {
2505 lxcfs_error("Timed out waiting for pid from child: %s.\n", strerror(errno
));
2508 if (read(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
2509 lxcfs_error("Error reading pid from child: %s.\n", strerror(errno
));
2512 must_strcat_pid(d
, &sz
, &asz
, qpid
);
2514 ptr
= strchr(ptr
, '\n');
2520 cred
.pid
= getpid();
2522 if (send_creds(sock
[0], &cred
, v
, true) != SEND_CREDS_OK
) {
2523 // failed to ask child to exit
2524 lxcfs_error("Failed to ask child to exit: %s.\n", strerror(errno
));
2534 if (sock
[0] != -1) {
2541 int cg_read(const char *path
, char *buf
, size_t size
, off_t offset
,
2542 struct fuse_file_info
*fi
)
2544 struct fuse_context
*fc
= fuse_get_context();
2545 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2546 struct cgfs_files
*k
= NULL
;
2551 if (!fc
|| !cgroup_ops
|| pure_unified_layout(cgroup_ops
))
2554 if (f
->type
!= LXC_TYPE_CGFILE
) {
2555 lxcfs_error("%s\n", "Internal error: directory cache info used in cg_read.");
2565 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
2571 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_RDONLY
)) {
2576 if (strcmp(f
->file
, "tasks") == 0 ||
2577 strcmp(f
->file
, "/tasks") == 0 ||
2578 strcmp(f
->file
, "/cgroup.procs") == 0 ||
2579 strcmp(f
->file
, "cgroup.procs") == 0)
2580 // special case - we have to translate the pids
2581 r
= do_read_pids(fc
->pid
, f
->controller
, f
->cgroup
, f
->file
, &data
);
2583 r
= cgroup_ops
->get(cgroup_ops
, f
->controller
, f
->cgroup
, f
->file
, &data
);
2597 memcpy(buf
, data
, s
);
2598 if (s
> 0 && s
< size
&& data
[s
-1] != '\n')
2608 static int pid_from_ns(int sock
, pid_t tpid
)
2618 if (!wait_for_sock(sock
, 2)) {
2619 lxcfs_error("%s\n", "Timeout reading from parent.");
2622 if ((ret
= read(sock
, &vpid
, sizeof(pid_t
))) != sizeof(pid_t
)) {
2623 lxcfs_error("Bad read from parent: %s.\n", strerror(errno
));
2626 if (vpid
== -1) // done
2630 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
) {
2632 cred
.pid
= getpid();
2633 if (send_creds(sock
, &cred
, v
, false) != SEND_CREDS_OK
)
2640 static void pid_from_ns_wrapper(int sock
, pid_t tpid
)
2642 int newnsfd
= -1, ret
, cpipe
[2];
2647 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", tpid
);
2648 if (ret
< 0 || ret
>= sizeof(fnam
))
2650 newnsfd
= open(fnam
, O_RDONLY
);
2653 if (setns(newnsfd
, 0) < 0)
2657 if (pipe(cpipe
) < 0)
2660 struct pid_ns_clone_args args
= {
2664 .wrapped
= &pid_from_ns
2666 size_t stack_size
= sysconf(_SC_PAGESIZE
);
2667 void *stack
= alloca(stack_size
);
2669 cpid
= clone(pid_ns_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &args
);
2673 // give the child 1 second to be done forking and
2675 if (!wait_for_sock(cpipe
[0], 1))
2677 ret
= read(cpipe
[0], &v
, 1);
2678 if (ret
!= sizeof(char) || v
!= '1')
2681 if (!wait_for_pid(cpid
))
2687 * Given host @uid, return the uid to which it maps in
2688 * @pid's user namespace, or -1 if none.
2690 bool hostuid_to_ns(uid_t uid
, pid_t pid
, uid_t
*answer
)
2695 sprintf(line
, "/proc/%d/uid_map", pid
);
2696 if ((f
= fopen(line
, "r")) == NULL
) {
2700 *answer
= convert_id_to_ns(f
, uid
);
2709 * get_pid_creds: get the real uid and gid of @pid from
2711 * (XXX should we use euid here?)
2713 void get_pid_creds(pid_t pid
, uid_t
*uid
, gid_t
*gid
)
2722 sprintf(line
, "/proc/%d/status", pid
);
2723 if ((f
= fopen(line
, "r")) == NULL
) {
2724 lxcfs_error("Error opening %s: %s\n", line
, strerror(errno
));
2727 while (fgets(line
, 400, f
)) {
2728 if (strncmp(line
, "Uid:", 4) == 0) {
2729 if (sscanf(line
+4, "%u", &u
) != 1) {
2730 lxcfs_error("bad uid line for pid %u\n", pid
);
2735 } else if (strncmp(line
, "Gid:", 4) == 0) {
2736 if (sscanf(line
+4, "%u", &g
) != 1) {
2737 lxcfs_error("bad gid line for pid %u\n", pid
);
2748 * May the requestor @r move victim @v to a new cgroup?
2749 * This is allowed if
2750 * . they are the same task
2751 * . they are ownedy by the same uid
2752 * . @r is root on the host, or
2753 * . @v's uid is mapped into @r's where @r is root.
2755 bool may_move_pid(pid_t r
, uid_t r_uid
, pid_t v
)
2757 uid_t v_uid
, tmpuid
;
2764 get_pid_creds(v
, &v_uid
, &v_gid
);
2767 if (hostuid_to_ns(r_uid
, r
, &tmpuid
) && tmpuid
== 0
2768 && hostuid_to_ns(v_uid
, r
, &tmpuid
))
2773 static bool do_write_pids(pid_t tpid
, uid_t tuid
, const char *contrl
, const char *cg
,
2774 const char *file
, const char *buf
)
2776 int sock
[2] = {-1, -1};
2777 pid_t qpid
, cpid
= -1;
2778 FILE *pids_file
= NULL
;
2779 bool answer
= false, fail
= false;
2781 pids_file
= open_pids_file(contrl
, cg
);
2786 * write the pids to a socket, have helper in writer's pidns
2787 * call movepid for us
2789 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
2790 perror("socketpair");
2798 if (!cpid
) { // child
2800 pid_from_ns_wrapper(sock
[1], tpid
);
2803 const char *ptr
= buf
;
2804 while (sscanf(ptr
, "%d", &qpid
) == 1) {
2808 if (write(sock
[0], &qpid
, sizeof(qpid
)) != sizeof(qpid
)) {
2809 lxcfs_error("Error writing pid to child: %s.\n", strerror(errno
));
2813 if (recv_creds(sock
[0], &cred
, &v
)) {
2815 if (!may_move_pid(tpid
, tuid
, cred
.pid
)) {
2819 if (fprintf(pids_file
, "%d", (int) cred
.pid
) < 0)
2824 ptr
= strchr(ptr
, '\n');
2830 /* All good, write the value */
2832 if (write(sock
[0], &qpid
,sizeof(qpid
)) != sizeof(qpid
))
2833 lxcfs_error("%s\n", "Warning: failed to ask child to exit.");
2841 if (sock
[0] != -1) {
2846 if (fclose(pids_file
) != 0)
2852 int cg_write(const char *path
, const char *buf
, size_t size
, off_t offset
,
2853 struct fuse_file_info
*fi
)
2855 struct fuse_context
*fc
= fuse_get_context();
2856 char *localbuf
= NULL
;
2857 struct cgfs_files
*k
= NULL
;
2858 struct file_info
*f
= (struct file_info
*)fi
->fh
;
2861 if (!fc
|| !cgroup_ops
|| pure_unified_layout(cgroup_ops
))
2864 if (f
->type
!= LXC_TYPE_CGFILE
) {
2865 lxcfs_error("%s\n", "Internal error: directory cache info used in cg_write.");
2872 localbuf
= alloca(size
+1);
2873 localbuf
[size
] = '\0';
2874 memcpy(localbuf
, buf
, size
);
2876 if ((k
= cgfs_get_key(f
->controller
, f
->cgroup
, f
->file
)) == NULL
) {
2881 if (!fc_may_access(fc
, f
->controller
, f
->cgroup
, f
->file
, O_WRONLY
)) {
2886 if (strcmp(f
->file
, "tasks") == 0 ||
2887 strcmp(f
->file
, "/tasks") == 0 ||
2888 strcmp(f
->file
, "/cgroup.procs") == 0 ||
2889 strcmp(f
->file
, "cgroup.procs") == 0)
2890 // special case - we have to translate the pids
2891 r
= do_write_pids(fc
->pid
, fc
->uid
, f
->controller
, f
->cgroup
, f
->file
, localbuf
);
2893 r
= cgfs_set_value(f
->controller
, f
->cgroup
, f
->file
, localbuf
);
2903 int cg_chown(const char *path
, uid_t uid
, gid_t gid
)
2905 struct fuse_context
*fc
= fuse_get_context();
2906 char *cgdir
= NULL
, *last
= NULL
, *path1
, *path2
, *controller
;
2907 struct cgfs_files
*k
= NULL
;
2911 if (!fc
|| !cgroup_ops
|| pure_unified_layout(cgroup_ops
))
2914 if (strcmp(path
, "/cgroup") == 0)
2917 controller
= pick_controller_from_path(fc
, path
);
2919 return errno
== ENOENT
? -EPERM
: -errno
;
2921 cgroup
= find_cgroup_in_path(path
);
2923 /* this is just /cgroup/controller */
2926 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
2936 if (is_child_cgroup(controller
, path1
, path2
)) {
2937 // get uid, gid, from '/tasks' file and make up a mode
2938 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
2939 k
= cgfs_get_key(controller
, cgroup
, "tasks");
2942 k
= cgfs_get_key(controller
, path1
, path2
);
2950 * This being a fuse request, the uid and gid must be valid
2951 * in the caller's namespace. So we can just check to make
2952 * sure that the caller is root in his uid, and privileged
2953 * over the file's current owner.
2955 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_REQD
)) {
2960 ret
= cgfs_chown_file(controller
, cgroup
, uid
, gid
);
2969 int cg_chmod(const char *path
, mode_t mode
)
2971 struct fuse_context
*fc
= fuse_get_context();
2972 char * cgdir
= NULL
, *last
= NULL
, *path1
, *path2
, *controller
;
2973 struct cgfs_files
*k
= NULL
;
2977 if (!fc
|| !cgroup_ops
|| pure_unified_layout(cgroup_ops
))
2980 if (strcmp(path
, "/cgroup") == 0)
2983 controller
= pick_controller_from_path(fc
, path
);
2985 return errno
== ENOENT
? -EPERM
: -errno
;
2987 cgroup
= find_cgroup_in_path(path
);
2989 /* this is just /cgroup/controller */
2992 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
3002 if (is_child_cgroup(controller
, path1
, path2
)) {
3003 // get uid, gid, from '/tasks' file and make up a mode
3004 // That is a hack, until cgmanager gains a GetCgroupPerms fn.
3005 k
= cgfs_get_key(controller
, cgroup
, "tasks");
3008 k
= cgfs_get_key(controller
, path1
, path2
);
3016 * This being a fuse request, the uid and gid must be valid
3017 * in the caller's namespace. So we can just check to make
3018 * sure that the caller is root in his uid, and privileged
3019 * over the file's current owner.
3021 if (!is_privileged_over(fc
->pid
, fc
->uid
, k
->uid
, NS_ROOT_OPT
)) {
3026 if (!cgfs_chmod_file(controller
, cgroup
, mode
)) {
3038 int cg_mkdir(const char *path
, mode_t mode
)
3040 struct fuse_context
*fc
= fuse_get_context();
3041 char *last
= NULL
, *path1
, *cgdir
= NULL
, *controller
, *next
= NULL
;
3045 if (!fc
|| !cgroup_ops
|| pure_unified_layout(cgroup_ops
))
3048 controller
= pick_controller_from_path(fc
, path
);
3050 return errno
== ENOENT
? -EPERM
: -errno
;
3052 cgroup
= find_cgroup_in_path(path
);
3056 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
3062 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3063 if (initpid
<= 1 || is_shared_pidns(initpid
))
3065 if (!caller_is_in_ancestor(initpid
, controller
, path1
, &next
)) {
3068 else if (last
&& strcmp(next
, last
) == 0)
3075 if (!fc_may_access(fc
, controller
, path1
, NULL
, O_RDWR
)) {
3079 if (!caller_is_in_ancestor(initpid
, controller
, path1
, NULL
)) {
3084 ret
= cgfs_create(controller
, cgroup
, fc
->uid
, fc
->gid
);
3092 int cg_rmdir(const char *path
)
3094 struct fuse_context
*fc
= fuse_get_context();
3095 char *last
= NULL
, *cgdir
= NULL
, *controller
, *next
= NULL
;
3099 if (!fc
|| !cgroup_ops
|| pure_unified_layout(cgroup_ops
))
3102 controller
= pick_controller_from_path(fc
, path
);
3103 if (!controller
) /* Someone's trying to delete "/cgroup". */
3106 cgroup
= find_cgroup_in_path(path
);
3107 if (!cgroup
) /* Someone's trying to delete a controller e.g. "/blkio". */
3110 get_cgdir_and_path(cgroup
, &cgdir
, &last
);
3112 /* Someone's trying to delete a cgroup on the same level as the
3113 * "/lxc" cgroup e.g. rmdir "/cgroup/blkio/lxc" or
3114 * rmdir "/cgroup/blkio/init.slice".
3120 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3121 if (initpid
<= 1 || is_shared_pidns(initpid
))
3123 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, &next
)) {
3124 if (!last
|| (next
&& (strcmp(next
, last
) == 0)))
3131 if (!fc_may_access(fc
, controller
, cgdir
, NULL
, O_WRONLY
)) {
3135 if (!caller_is_in_ancestor(initpid
, controller
, cgroup
, NULL
)) {
3140 if (!cgfs_remove(controller
, cgroup
)) {
3153 static bool startswith(const char *line
, const char *pref
)
3155 if (strncmp(line
, pref
, strlen(pref
)) == 0)
3160 /* Note that "memory.stat" in cgroup2 is hierarchical by default. */
3161 static void parse_memstat(int version
,
3163 unsigned long *cached
,
3164 unsigned long *active_anon
,
3165 unsigned long *inactive_anon
,
3166 unsigned long *active_file
,
3167 unsigned long *inactive_file
,
3168 unsigned long *unevictable
,
3169 unsigned long *shmem
)
3174 if (startswith(memstat
, is_unified_controller(version
)
3177 sscanf(memstat
+ 11, "%lu", cached
);
3179 } else if (startswith(memstat
, is_unified_controller(version
)
3181 : "total_active_anon")) {
3182 sscanf(memstat
+ 17, "%lu", active_anon
);
3183 *active_anon
/= 1024;
3184 } else if (startswith(memstat
, is_unified_controller(version
)
3186 : "total_inactive_anon")) {
3187 sscanf(memstat
+ 19, "%lu", inactive_anon
);
3188 *inactive_anon
/= 1024;
3189 } else if (startswith(memstat
, is_unified_controller(version
)
3191 : "total_active_file")) {
3192 sscanf(memstat
+ 17, "%lu", active_file
);
3193 *active_file
/= 1024;
3194 } else if (startswith(memstat
, is_unified_controller(version
)
3196 : "total_inactive_file")) {
3197 sscanf(memstat
+ 19, "%lu", inactive_file
);
3198 *inactive_file
/= 1024;
3199 } else if (startswith(memstat
, is_unified_controller(version
)
3201 : "total_unevictable")) {
3202 sscanf(memstat
+ 17, "%lu", unevictable
);
3203 *unevictable
/= 1024;
3204 } else if (startswith(memstat
, is_unified_controller(version
)
3207 sscanf(memstat
+ 11, "%lu", shmem
);
3210 eol
= strchr(memstat
, '\n');
3217 static void get_blkio_io_value(char *str
, unsigned major
, unsigned minor
, char *iotype
, unsigned long *v
)
3223 snprintf(key
, 32, "%u:%u %s", major
, minor
, iotype
);
3225 size_t len
= strlen(key
);
3229 if (startswith(str
, key
)) {
3230 sscanf(str
+ len
, "%lu", v
);
3233 eol
= strchr(str
, '\n');
3240 int read_file_fuse(const char *path
, char *buf
, size_t size
, struct file_info
*d
)
3242 __do_free
char *line
= NULL
;
3243 __do_fclose
FILE *f
= NULL
;
3244 size_t linelen
= 0, total_len
= 0;
3245 char *cache
= d
->buf
;
3246 size_t cache_size
= d
->buflen
;
3248 f
= fopen(path
, "r");
3252 while (getline(&line
, &linelen
, f
) != -1) {
3253 ssize_t l
= snprintf(cache
, cache_size
, "%s", line
);
3255 perror("Error writing to cache");
3258 if (l
>= cache_size
) {
3259 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3267 d
->size
= total_len
;
3268 if (total_len
> size
)
3271 /* read from off 0 */
3272 memcpy(buf
, d
->buf
, total_len
);
3274 if (d
->size
> total_len
)
3275 d
->cached
= d
->size
- total_len
;
3280 * FUSE ops for /proc
3283 static unsigned long get_memlimit(const char *cgroup
, bool swap
)
3286 __do_free
char *memlimit_str
= NULL
;
3287 unsigned long memlimit
= -1;
3290 ret
= cgroup_ops
->get_memory_swap_max(cgroup_ops
, cgroup
, &memlimit_str
);
3292 ret
= cgroup_ops
->get_memory_max(cgroup_ops
, cgroup
, &memlimit_str
);
3294 memlimit
= strtoul(memlimit_str
, NULL
, 10);
3299 static unsigned long get_min_memlimit(const char *cgroup
, bool swap
)
3301 __do_free
char *copy
= NULL
;
3302 unsigned long memlimit
= 0;
3303 unsigned long retlimit
;
3305 copy
= strdup(cgroup
);
3306 retlimit
= get_memlimit(copy
, swap
);
3308 while (strcmp(copy
, "/") != 0) {
3312 memlimit
= get_memlimit(it
, swap
);
3313 if (memlimit
!= -1 && memlimit
< retlimit
)
3314 retlimit
= memlimit
;
3320 static int proc_meminfo_read(char *buf
, size_t size
, off_t offset
,
3321 struct fuse_file_info
*fi
)
3323 __do_free
char *cgroup
= NULL
, *line
= NULL
,
3324 *memusage_str
= NULL
, *memstat_str
= NULL
,
3325 *memswlimit_str
= NULL
, *memswusage_str
= NULL
;
3326 __do_fclose
FILE *f
= NULL
;
3327 struct fuse_context
*fc
= fuse_get_context();
3328 struct lxcfs_opts
*opts
= (struct lxcfs_opts
*) fuse_get_context()->private_data
;
3329 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3330 unsigned long memlimit
= 0, memusage
= 0, memswlimit
= 0,
3331 memswusage
= 0, cached
= 0, hosttotal
= 0, active_anon
= 0,
3332 inactive_anon
= 0, active_file
= 0, inactive_file
= 0,
3333 unevictable
= 0, shmem
= 0, hostswtotal
= 0;
3334 size_t linelen
= 0, total_len
= 0;
3335 char *cache
= d
->buf
;
3336 size_t cache_size
= d
->buflen
;
3342 if (offset
> d
->size
)
3348 left
= d
->size
- offset
;
3349 total_len
= left
> size
? size
: left
;
3350 memcpy(buf
, cache
+ offset
, total_len
);
3355 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3356 if (initpid
<= 1 || is_shared_pidns(initpid
))
3359 cgroup
= get_pid_cgroup(initpid
, "memory");
3361 return read_file_fuse("/proc/meminfo", buf
, size
, d
);
3363 prune_init_slice(cgroup
);
3365 memlimit
= get_min_memlimit(cgroup
, false);
3367 ret
= cgroup_ops
->get_memory_current(cgroup_ops
, cgroup
, &memusage_str
);
3371 ret
= cgroup_ops
->get_memory_stats(cgroup_ops
, cgroup
, &memstat_str
);
3374 parse_memstat(ret
, memstat_str
, &cached
, &active_anon
, &inactive_anon
,
3375 &active_file
, &inactive_file
, &unevictable
, &shmem
);
3378 * Following values are allowed to fail, because swapaccount might be
3379 * turned off for current kernel.
3381 ret
= cgroup_ops
->get_memory_swap_max(cgroup_ops
, cgroup
, &memswlimit_str
);
3383 ret
= cgroup_ops
->get_memory_swap_current(cgroup_ops
, cgroup
, &memswusage_str
);
3385 memswlimit
= get_min_memlimit(cgroup
, true);
3386 memswusage
= strtoul(memswusage_str
, NULL
, 10);
3387 memswlimit
= memswlimit
/ 1024;
3388 memswusage
= memswusage
/ 1024;
3391 memusage
= strtoul(memusage_str
, NULL
, 10);
3395 f
= fopen("/proc/meminfo", "r");
3399 while (getline(&line
, &linelen
, f
) != -1) {
3401 char *printme
, lbuf
[100];
3403 memset(lbuf
, 0, 100);
3404 if (startswith(line
, "MemTotal:")) {
3405 sscanf(line
+sizeof("MemTotal:")-1, "%lu", &hosttotal
);
3406 if (hosttotal
< memlimit
)
3407 memlimit
= hosttotal
;
3408 snprintf(lbuf
, 100, "MemTotal: %8lu kB\n", memlimit
);
3410 } else if (startswith(line
, "MemFree:")) {
3411 snprintf(lbuf
, 100, "MemFree: %8lu kB\n", memlimit
- memusage
);
3413 } else if (startswith(line
, "MemAvailable:")) {
3414 snprintf(lbuf
, 100, "MemAvailable: %8lu kB\n", memlimit
- memusage
+ cached
);
3416 } else if (startswith(line
, "SwapTotal:") && memswlimit
> 0 &&
3417 opts
&& opts
->swap_off
== false) {
3418 sscanf(line
+sizeof("SwapTotal:")-1, "%lu", &hostswtotal
);
3419 if (hostswtotal
< memswlimit
)
3420 memswlimit
= hostswtotal
;
3421 snprintf(lbuf
, 100, "SwapTotal: %8lu kB\n", memswlimit
);
3423 } else if (startswith(line
, "SwapTotal:") && opts
&& opts
->swap_off
== true) {
3424 snprintf(lbuf
, 100, "SwapTotal: %8lu kB\n", 0UL);
3426 } else if (startswith(line
, "SwapFree:") && memswlimit
> 0 &&
3427 memswusage
> 0 && opts
&& opts
->swap_off
== false) {
3428 unsigned long swaptotal
= memswlimit
,
3429 swapusage
= memusage
> memswusage
3431 : memswusage
- memusage
,
3432 swapfree
= swapusage
< swaptotal
3433 ? swaptotal
- swapusage
3435 snprintf(lbuf
, 100, "SwapFree: %8lu kB\n", swapfree
);
3437 } else if (startswith(line
, "SwapFree:") && opts
&& opts
->swap_off
== true) {
3438 snprintf(lbuf
, 100, "SwapFree: %8lu kB\n", 0UL);
3440 } else if (startswith(line
, "Slab:")) {
3441 snprintf(lbuf
, 100, "Slab: %8lu kB\n", 0UL);
3443 } else if (startswith(line
, "Buffers:")) {
3444 snprintf(lbuf
, 100, "Buffers: %8lu kB\n", 0UL);
3446 } else if (startswith(line
, "Cached:")) {
3447 snprintf(lbuf
, 100, "Cached: %8lu kB\n", cached
);
3449 } else if (startswith(line
, "SwapCached:")) {
3450 snprintf(lbuf
, 100, "SwapCached: %8lu kB\n", 0UL);
3452 } else if (startswith(line
, "Active:")) {
3453 snprintf(lbuf
, 100, "Active: %8lu kB\n",
3454 active_anon
+ active_file
);
3456 } else if (startswith(line
, "Inactive:")) {
3457 snprintf(lbuf
, 100, "Inactive: %8lu kB\n",
3458 inactive_anon
+ inactive_file
);
3460 } else if (startswith(line
, "Active(anon)")) {
3461 snprintf(lbuf
, 100, "Active(anon): %8lu kB\n", active_anon
);
3463 } else if (startswith(line
, "Inactive(anon)")) {
3464 snprintf(lbuf
, 100, "Inactive(anon): %8lu kB\n", inactive_anon
);
3466 } else if (startswith(line
, "Active(file)")) {
3467 snprintf(lbuf
, 100, "Active(file): %8lu kB\n", active_file
);
3469 } else if (startswith(line
, "Inactive(file)")) {
3470 snprintf(lbuf
, 100, "Inactive(file): %8lu kB\n", inactive_file
);
3472 } else if (startswith(line
, "Unevictable")) {
3473 snprintf(lbuf
, 100, "Unevictable: %8lu kB\n", unevictable
);
3475 } else if (startswith(line
, "SReclaimable")) {
3476 snprintf(lbuf
, 100, "SReclaimable: %8lu kB\n", 0UL);
3478 } else if (startswith(line
, "SUnreclaim")) {
3479 snprintf(lbuf
, 100, "SUnreclaim: %8lu kB\n", 0UL);
3481 } else if (startswith(line
, "Shmem:")) {
3482 snprintf(lbuf
, 100, "Shmem: %8lu kB\n", shmem
);
3484 } else if (startswith(line
, "ShmemHugePages")) {
3485 snprintf(lbuf
, 100, "ShmemHugePages: %8lu kB\n", 0UL);
3487 } else if (startswith(line
, "ShmemPmdMapped")) {
3488 snprintf(lbuf
, 100, "ShmemPmdMapped: %8lu kB\n", 0UL);
3493 l
= snprintf(cache
, cache_size
, "%s", printme
);
3495 perror("Error writing to cache");
3499 if (l
>= cache_size
) {
3500 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3510 d
->size
= total_len
;
3511 if (total_len
> size
) total_len
= size
;
3512 memcpy(buf
, d
->buf
, total_len
);
3518 * Read the cpuset.cpus for cg
3519 * Return the answer in a newly allocated string which must be freed
3521 char *get_cpuset(const char *cg
)
3526 ret
= cgroup_ops
->get_cpuset_cpus(cgroup_ops
, cg
, &value
);
3533 bool cpu_in_cpuset(int cpu
, const char *cpuset
);
3535 static bool cpuline_in_cpuset(const char *line
, const char *cpuset
)
3539 if (sscanf(line
, "processor : %d", &cpu
) != 1)
3541 return cpu_in_cpuset(cpu
, cpuset
);
3545 * Read cgroup CPU quota parameters from `cpu.cfs_quota_us` or `cpu.cfs_period_us`,
3546 * depending on `param`. Parameter value is returned throuh `value`.
3548 static bool read_cpu_cfs_param(const char *cg
, const char *param
, int64_t *value
)
3550 __do_free
char *str
= NULL
;
3551 char file
[11 + 6 + 1]; /* cpu.cfs__us + quota/period + \0 */
3553 snprintf(file
, sizeof(file
), "cpu.cfs_%s_us", param
);
3555 if (!cgroup_ops
->get(cgroup_ops
, "cpu", cg
, file
, &str
))
3558 if (sscanf(str
, "%ld", value
) != 1)
3565 * Return the maximum number of visible CPUs based on CPU quotas.
3566 * If there is no quota set, zero is returned.
3568 int max_cpu_count(const char *cg
)
3571 int64_t cfs_quota
, cfs_period
;
3572 int nr_cpus_in_cpuset
= 0;
3573 char *cpuset
= NULL
;
3575 if (!read_cpu_cfs_param(cg
, "quota", &cfs_quota
))
3578 if (!read_cpu_cfs_param(cg
, "period", &cfs_period
))
3581 cpuset
= get_cpuset(cg
);
3583 nr_cpus_in_cpuset
= cpu_number_in_cpuset(cpuset
);
3585 if (cfs_quota
<= 0 || cfs_period
<= 0){
3586 if (nr_cpus_in_cpuset
> 0)
3587 return nr_cpus_in_cpuset
;
3592 rv
= cfs_quota
/ cfs_period
;
3594 /* In case quota/period does not yield a whole number, add one CPU for
3597 if ((cfs_quota
% cfs_period
) > 0)
3600 nprocs
= get_nprocs();
3605 /* use min value in cpu quota and cpuset */
3606 if (nr_cpus_in_cpuset
> 0 && nr_cpus_in_cpuset
< rv
)
3607 rv
= nr_cpus_in_cpuset
;
3613 * Return the exact number of visible CPUs based on CPU quotas.
3614 * If there is no quota set, zero is returned.
3616 static double exact_cpu_count(const char *cg
)
3620 int64_t cfs_quota
, cfs_period
;
3622 if (!read_cpu_cfs_param(cg
, "quota", &cfs_quota
))
3625 if (!read_cpu_cfs_param(cg
, "period", &cfs_period
))
3628 if (cfs_quota
<= 0 || cfs_period
<= 0)
3631 rv
= (double)cfs_quota
/ (double)cfs_period
;
3633 nprocs
= get_nprocs();
3642 * check whether this is a '^processor" line in /proc/cpuinfo
3644 static bool is_processor_line(const char *line
)
3648 if (sscanf(line
, "processor : %d", &cpu
) == 1)
3653 static int proc_cpuinfo_read(char *buf
, size_t size
, off_t offset
,
3654 struct fuse_file_info
*fi
)
3656 __do_free
char *cg
= NULL
, *cpuset
= NULL
, *line
= NULL
;
3657 __do_fclose
FILE *f
= NULL
;
3658 struct fuse_context
*fc
= fuse_get_context();
3659 struct file_info
*d
= (struct file_info
*)fi
->fh
;
3660 size_t linelen
= 0, total_len
= 0;
3661 bool am_printing
= false, firstline
= true, is_s390x
= false;
3662 int curcpu
= -1, cpu
, max_cpus
= 0;
3664 char *cache
= d
->buf
;
3665 size_t cache_size
= d
->buflen
;
3670 if (offset
> d
->size
)
3676 left
= d
->size
- offset
;
3677 total_len
= left
> size
? size
: left
;
3678 memcpy(buf
, cache
+ offset
, total_len
);
3683 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
3684 if (initpid
<= 1 || is_shared_pidns(initpid
))
3686 cg
= get_pid_cgroup(initpid
, "cpuset");
3688 return read_file_fuse("proc/cpuinfo", buf
, size
, d
);
3689 prune_init_slice(cg
);
3691 cpuset
= get_cpuset(cg
);
3695 use_view
= cgroup_ops
->can_use_cpuview(cgroup_ops
);
3697 max_cpus
= max_cpu_count(cg
);
3699 f
= fopen("/proc/cpuinfo", "r");
3703 while (getline(&line
, &linelen
, f
) != -1) {
3707 if (strstr(line
, "IBM/S390") != NULL
) {
3713 if (strncmp(line
, "# processors:", 12) == 0)
3715 if (is_processor_line(line
)) {
3716 if (use_view
&& max_cpus
> 0 && (curcpu
+1) == max_cpus
)
3718 am_printing
= cpuline_in_cpuset(line
, cpuset
);
3721 l
= snprintf(cache
, cache_size
, "processor : %d\n", curcpu
);
3723 perror("Error writing to cache");
3726 if (l
>= cache_size
) {
3727 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3735 } else if (is_s390x
&& sscanf(line
, "processor %d:", &cpu
) == 1) {
3737 if (use_view
&& max_cpus
> 0 && (curcpu
+1) == max_cpus
)
3739 if (!cpu_in_cpuset(cpu
, cpuset
))
3742 p
= strchr(line
, ':');
3746 l
= snprintf(cache
, cache_size
, "processor %d:%s", curcpu
, p
);
3748 perror("Error writing to cache");
3751 if (l
>= cache_size
) {
3752 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3762 l
= snprintf(cache
, cache_size
, "%s", line
);
3764 perror("Error writing to cache");
3767 if (l
>= cache_size
) {
3768 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
3778 __do_free
char *origcache
= d
->buf
;
3781 d
->buf
= malloc(d
->buflen
);
3783 d
->buf
= move_ptr(origcache
);
3788 cache_size
= d
->buflen
;
3790 l
= snprintf(cache
, cache_size
, "vendor_id : IBM/S390\n");
3791 if (l
< 0 || l
>= cache_size
)
3797 l
= snprintf(cache
, cache_size
, "# processors : %d\n", curcpu
+ 1);
3798 if (l
< 0 || l
>= cache_size
)
3804 l
= snprintf(cache
, cache_size
, "%s", origcache
);
3805 if (l
< 0 || l
>= cache_size
)
3811 d
->size
= total_len
;
3812 if (total_len
> size
) total_len
= size
;
3814 /* read from off 0 */
3815 memcpy(buf
, d
->buf
, total_len
);
3819 static uint64_t get_reaper_start_time(pid_t pid
)
3824 /* strlen("/proc/") = 6
3828 * strlen("/stat") = 5
3832 #define __PROC_PID_STAT_LEN (6 + LXCFS_NUMSTRLEN64 + 5 + 1)
3833 char path
[__PROC_PID_STAT_LEN
];
3836 qpid
= lookup_initpid_in_store(pid
);
3838 /* Caller can check for EINVAL on 0. */
3843 ret
= snprintf(path
, __PROC_PID_STAT_LEN
, "/proc/%d/stat", qpid
);
3844 if (ret
< 0 || ret
>= __PROC_PID_STAT_LEN
) {
3845 /* Caller can check for EINVAL on 0. */
3850 f
= fopen(path
, "r");
3852 /* Caller can check for EINVAL on 0. */
3857 /* Note that the *scanf() argument supression requires that length
3858 * modifiers such as "l" are omitted. Otherwise some compilers will yell
3859 * at us. It's like telling someone you're not married and then asking
3860 * if you can bring your wife to the party.
3862 ret
= fscanf(f
, "%*d " /* (1) pid %d */
3863 "%*s " /* (2) comm %s */
3864 "%*c " /* (3) state %c */
3865 "%*d " /* (4) ppid %d */
3866 "%*d " /* (5) pgrp %d */
3867 "%*d " /* (6) session %d */
3868 "%*d " /* (7) tty_nr %d */
3869 "%*d " /* (8) tpgid %d */
3870 "%*u " /* (9) flags %u */
3871 "%*u " /* (10) minflt %lu */
3872 "%*u " /* (11) cminflt %lu */
3873 "%*u " /* (12) majflt %lu */
3874 "%*u " /* (13) cmajflt %lu */
3875 "%*u " /* (14) utime %lu */
3876 "%*u " /* (15) stime %lu */
3877 "%*d " /* (16) cutime %ld */
3878 "%*d " /* (17) cstime %ld */
3879 "%*d " /* (18) priority %ld */
3880 "%*d " /* (19) nice %ld */
3881 "%*d " /* (20) num_threads %ld */
3882 "%*d " /* (21) itrealvalue %ld */
3883 "%" PRIu64
, /* (22) starttime %llu */
3887 /* Caller can check for EINVAL on 0. */
3898 static double get_reaper_start_time_in_sec(pid_t pid
)
3900 uint64_t clockticks
, ticks_per_sec
;
3904 clockticks
= get_reaper_start_time(pid
);
3905 if (clockticks
== 0 && errno
== EINVAL
) {
3906 lxcfs_debug("failed to retrieve start time of pid %d\n", pid
);
3910 ret
= sysconf(_SC_CLK_TCK
);
3911 if (ret
< 0 && errno
== EINVAL
) {
3914 "failed to determine number of clock ticks in a second");
3918 ticks_per_sec
= (uint64_t)ret
;
3919 res
= (double)clockticks
/ ticks_per_sec
;
3923 static double get_reaper_age(pid_t pid
)
3926 double procstart
, procage
;
3928 /* We need to substract the time the process has started since system
3929 * boot minus the time when the system has started to get the actual
3932 procstart
= get_reaper_start_time_in_sec(pid
);
3933 procage
= procstart
;
3934 if (procstart
> 0) {
3936 struct timespec spec
;
3938 ret
= clock_gettime(CLOCK_BOOTTIME
, &spec
);
3942 /* We could make this more precise here by using the tv_nsec
3943 * field in the timespec struct and convert it to milliseconds
3944 * and then create a double for the seconds and milliseconds but
3945 * that seems more work than it is worth.
3947 uptime_ms
= (spec
.tv_sec
* 1000) + (spec
.tv_nsec
* 1e-6);
3948 procage
= (uptime_ms
- (procstart
* 1000)) / 1000;
3955 * Returns 0 on success.
3956 * It is the caller's responsibility to free `return_usage`, unless this
3957 * function returns an error.
3959 static int read_cpuacct_usage_all(char *cg
, char *cpuset
, struct cpuacct_usage
**return_usage
, int *size
)
3961 __do_free
char *usage_str
= NULL
;
3962 __do_free
struct cpuacct_usage
*cpu_usage
= NULL
;
3963 int cpucount
= get_nprocs_conf();
3964 int read_pos
= 0, read_cnt
=0;
3967 uint64_t cg_user
, cg_system
;
3968 int64_t ticks_per_sec
;
3970 ticks_per_sec
= sysconf(_SC_CLK_TCK
);
3972 if (ticks_per_sec
< 0 && errno
== EINVAL
) {
3975 "read_cpuacct_usage_all failed to determine number of clock ticks "
3980 cpu_usage
= malloc(sizeof(struct cpuacct_usage
) * cpucount
);
3984 memset(cpu_usage
, 0, sizeof(struct cpuacct_usage
) * cpucount
);
3985 if (!cgroup_ops
->get(cgroup_ops
, "cpuacct", cg
, "cpuacct.usage_all", &usage_str
)) {
3987 int i
= 0, read_pos
= 0, read_cnt
=0;
3988 size_t sz
= 0, asz
= 0;
3990 /* read cpuacct.usage_percpu instead. */
3991 lxcfs_v("failed to read cpuacct.usage_all. reading cpuacct.usage_percpu instead\n%s", "");
3992 if (!cgroup_ops
->get(cgroup_ops
, "cpuacct", cg
, "cpuacct.usage_percpu", &usage_str
))
3994 lxcfs_v("usage_str: %s\n", usage_str
);
3996 /* convert cpuacct.usage_percpu into cpuacct.usage_all. */
3997 lxcfs_v("converting cpuacct.usage_percpu into cpuacct.usage_all\n%s", "");
3999 must_strcat(&data
, &sz
, &asz
, "cpu user system\n");
4001 while (sscanf(usage_str
+ read_pos
, "%lu %n", &cg_user
, &read_cnt
) > 0) {
4002 lxcfs_debug("i: %d, cg_user: %lu, read_pos: %d, read_cnt: %d\n", i
, cg_user
, read_pos
, read_cnt
);
4003 must_strcat(&data
, &sz
, &asz
, "%d %lu 0\n", i
, cg_user
);
4005 read_pos
+= read_cnt
;
4010 lxcfs_v("usage_str: %s\n", usage_str
);
4013 if (sscanf(usage_str
, "cpu user system\n%n", &read_cnt
) != 0) {
4014 lxcfs_error("read_cpuacct_usage_all reading first line from "
4015 "%s/cpuacct.usage_all failed.\n", cg
);
4019 read_pos
+= read_cnt
;
4021 for (i
= 0, j
= 0; i
< cpucount
; i
++) {
4022 ret
= sscanf(usage_str
+ read_pos
, "%d %lu %lu\n%n", &cg_cpu
, &cg_user
,
4023 &cg_system
, &read_cnt
);
4029 lxcfs_error("read_cpuacct_usage_all reading from %s/cpuacct.usage_all "
4034 read_pos
+= read_cnt
;
4036 /* Convert the time from nanoseconds to USER_HZ */
4037 cpu_usage
[j
].user
= cg_user
/ 1000.0 / 1000 / 1000 * ticks_per_sec
;
4038 cpu_usage
[j
].system
= cg_system
/ 1000.0 / 1000 / 1000 * ticks_per_sec
;
4042 *return_usage
= move_ptr(cpu_usage
);
4047 static unsigned long diff_cpu_usage(struct cpuacct_usage
*older
, struct cpuacct_usage
*newer
, struct cpuacct_usage
*diff
, int cpu_count
)
4050 unsigned long sum
= 0;
4052 for (i
= 0; i
< cpu_count
; i
++) {
4053 if (!newer
[i
].online
)
4056 /* When cpuset is changed on the fly, the CPUs might get reordered.
4057 * We could either reset all counters, or check that the substractions
4058 * below will return expected results.
4060 if (newer
[i
].user
> older
[i
].user
)
4061 diff
[i
].user
= newer
[i
].user
- older
[i
].user
;
4065 if (newer
[i
].system
> older
[i
].system
)
4066 diff
[i
].system
= newer
[i
].system
- older
[i
].system
;
4070 if (newer
[i
].idle
> older
[i
].idle
)
4071 diff
[i
].idle
= newer
[i
].idle
- older
[i
].idle
;
4075 sum
+= diff
[i
].user
;
4076 sum
+= diff
[i
].system
;
4077 sum
+= diff
[i
].idle
;
4083 static void add_cpu_usage(unsigned long *surplus
, struct cpuacct_usage
*usage
, unsigned long *counter
, unsigned long threshold
)
4085 unsigned long free_space
, to_add
;
4087 free_space
= threshold
- usage
->user
- usage
->system
;
4089 if (free_space
> usage
->idle
)
4090 free_space
= usage
->idle
;
4092 to_add
= free_space
> *surplus
? *surplus
: free_space
;
4095 usage
->idle
-= to_add
;
4099 static struct cg_proc_stat
*prune_proc_stat_list(struct cg_proc_stat
*node
)
4101 struct cg_proc_stat
*first
= NULL
, *prev
, *tmp
;
4103 for (prev
= NULL
; node
; ) {
4104 if (!cgfs_param_exist("cpu", node
->cg
, "cpu.shares")) {
4106 lxcfs_debug("Removing stat node for %s\n", node
->cg
);
4109 prev
->next
= node
->next
;
4114 free_proc_stat_node(tmp
);
4126 #define PROC_STAT_PRUNE_INTERVAL 10
4127 static void prune_proc_stat_history(void)
4130 time_t now
= time(NULL
);
4132 for (i
= 0; i
< CPUVIEW_HASH_SIZE
; i
++) {
4133 pthread_rwlock_wrlock(&proc_stat_history
[i
]->lock
);
4135 if ((proc_stat_history
[i
]->lastcheck
+ PROC_STAT_PRUNE_INTERVAL
) > now
) {
4136 pthread_rwlock_unlock(&proc_stat_history
[i
]->lock
);
4140 if (proc_stat_history
[i
]->next
) {
4141 proc_stat_history
[i
]->next
= prune_proc_stat_list(proc_stat_history
[i
]->next
);
4142 proc_stat_history
[i
]->lastcheck
= now
;
4145 pthread_rwlock_unlock(&proc_stat_history
[i
]->lock
);
4149 static struct cg_proc_stat
*find_proc_stat_node(struct cg_proc_stat_head
*head
, const char *cg
)
4151 struct cg_proc_stat
*node
;
4153 pthread_rwlock_rdlock(&head
->lock
);
4156 pthread_rwlock_unlock(&head
->lock
);
4163 if (strcmp(cg
, node
->cg
) == 0)
4165 } while ((node
= node
->next
));
4170 pthread_rwlock_unlock(&head
->lock
);
4171 prune_proc_stat_history();
4175 static struct cg_proc_stat
*new_proc_stat_node(struct cpuacct_usage
*usage
, int cpu_count
, const char *cg
)
4177 struct cg_proc_stat
*node
;
4180 node
= malloc(sizeof(struct cg_proc_stat
));
4188 node
->cg
= malloc(strlen(cg
) + 1);
4192 strcpy(node
->cg
, cg
);
4194 node
->usage
= malloc(sizeof(struct cpuacct_usage
) * cpu_count
);
4198 memcpy(node
->usage
, usage
, sizeof(struct cpuacct_usage
) * cpu_count
);
4200 node
->view
= malloc(sizeof(struct cpuacct_usage
) * cpu_count
);
4204 node
->cpu_count
= cpu_count
;
4207 if (pthread_mutex_init(&node
->lock
, NULL
) != 0) {
4208 lxcfs_error("%s\n", "Failed to initialize node lock");
4212 for (i
= 0; i
< cpu_count
; i
++) {
4213 node
->view
[i
].user
= 0;
4214 node
->view
[i
].system
= 0;
4215 node
->view
[i
].idle
= 0;
4221 if (node
&& node
->cg
)
4223 if (node
&& node
->usage
)
4225 if (node
&& node
->view
)
4233 static struct cg_proc_stat
*add_proc_stat_node(struct cg_proc_stat
*new_node
)
4235 int hash
= calc_hash(new_node
->cg
) % CPUVIEW_HASH_SIZE
;
4236 struct cg_proc_stat_head
*head
= proc_stat_history
[hash
];
4237 struct cg_proc_stat
*node
, *rv
= new_node
;
4239 pthread_rwlock_wrlock(&head
->lock
);
4242 head
->next
= new_node
;
4249 if (strcmp(node
->cg
, new_node
->cg
) == 0) {
4250 /* The node is already present, return it */
4251 free_proc_stat_node(new_node
);
4261 node
->next
= new_node
;
4266 pthread_rwlock_unlock(&head
->lock
);
4270 static bool expand_proc_stat_node(struct cg_proc_stat
*node
, int cpu_count
)
4272 __do_free
struct cpuacct_usage
*new_usage
= NULL
, *new_view
= NULL
;
4274 /* Allocate new memory */
4275 new_usage
= malloc(sizeof(struct cpuacct_usage
) * cpu_count
);
4279 new_view
= malloc(sizeof(struct cpuacct_usage
) * cpu_count
);
4283 /* Copy existing data & initialize new elements */
4284 for (int i
= 0; i
< cpu_count
; i
++) {
4285 if (i
< node
->cpu_count
) {
4286 new_usage
[i
].user
= node
->usage
[i
].user
;
4287 new_usage
[i
].system
= node
->usage
[i
].system
;
4288 new_usage
[i
].idle
= node
->usage
[i
].idle
;
4290 new_view
[i
].user
= node
->view
[i
].user
;
4291 new_view
[i
].system
= node
->view
[i
].system
;
4292 new_view
[i
].idle
= node
->view
[i
].idle
;
4294 new_usage
[i
].user
= 0;
4295 new_usage
[i
].system
= 0;
4296 new_usage
[i
].idle
= 0;
4298 new_view
[i
].user
= 0;
4299 new_view
[i
].system
= 0;
4300 new_view
[i
].idle
= 0;
4305 node
->usage
= move_ptr(new_usage
);
4308 node
->view
= move_ptr(new_view
);
4309 node
->cpu_count
= cpu_count
;
4314 static struct cg_proc_stat
*find_or_create_proc_stat_node(struct cpuacct_usage
*usage
, int cpu_count
, const char *cg
)
4316 int hash
= calc_hash(cg
) % CPUVIEW_HASH_SIZE
;
4317 struct cg_proc_stat_head
*head
= proc_stat_history
[hash
];
4318 struct cg_proc_stat
*node
;
4320 node
= find_proc_stat_node(head
, cg
);
4323 node
= new_proc_stat_node(usage
, cpu_count
, cg
);
4327 node
= add_proc_stat_node(node
);
4328 lxcfs_debug("New stat node (%d) for %s\n", cpu_count
, cg
);
4331 pthread_mutex_lock(&node
->lock
);
4333 /* If additional CPUs on the host have been enabled, CPU usage counter
4334 * arrays have to be expanded */
4335 if (node
->cpu_count
< cpu_count
) {
4336 lxcfs_debug("Expanding stat node %d->%d for %s\n",
4337 node
->cpu_count
, cpu_count
, cg
);
4339 if (!expand_proc_stat_node(node
, cpu_count
)) {
4340 pthread_mutex_unlock(&node
->lock
);
4341 lxcfs_debug("Unable to expand stat node %d->%d for %s\n",
4342 node
->cpu_count
, cpu_count
, cg
);
4350 static void reset_proc_stat_node(struct cg_proc_stat
*node
, struct cpuacct_usage
*usage
, int cpu_count
)
4354 lxcfs_debug("Resetting stat node for %s\n", node
->cg
);
4355 memcpy(node
->usage
, usage
, sizeof(struct cpuacct_usage
) * cpu_count
);
4357 for (i
= 0; i
< cpu_count
; i
++) {
4358 node
->view
[i
].user
= 0;
4359 node
->view
[i
].system
= 0;
4360 node
->view
[i
].idle
= 0;
4363 node
->cpu_count
= cpu_count
;
4366 static int cpuview_proc_stat(const char *cg
, const char *cpuset
,
4367 struct cpuacct_usage
*cg_cpu_usage
,
4368 int cg_cpu_usage_size
, FILE *f
, char *buf
,
4371 __do_free
char *line
= NULL
;
4372 __do_free
struct cpuacct_usage
*diff
= NULL
;
4373 size_t linelen
= 0, total_len
= 0, l
;
4374 int curcpu
= -1; /* cpu numbering starts at 0 */
4376 int max_cpus
= max_cpu_count(cg
), cpu_cnt
= 0;
4377 unsigned long user
= 0, nice
= 0, system
= 0, idle
= 0, iowait
= 0,
4378 irq
= 0, softirq
= 0, steal
= 0, guest
= 0, guest_nice
= 0;
4379 unsigned long user_sum
= 0, system_sum
= 0, idle_sum
= 0;
4380 unsigned long user_surplus
= 0, system_surplus
= 0;
4381 unsigned long total_sum
, threshold
;
4382 struct cg_proc_stat
*stat_node
;
4383 int nprocs
= get_nprocs_conf();
4385 if (cg_cpu_usage_size
< nprocs
)
4386 nprocs
= cg_cpu_usage_size
;
4388 /* Read all CPU stats and stop when we've encountered other lines */
4389 while (getline(&line
, &linelen
, f
) != -1) {
4391 char cpu_char
[10]; /* That's a lot of cores */
4392 uint64_t all_used
, cg_used
;
4394 if (strlen(line
) == 0)
4397 /* not a ^cpuN line containing a number N */
4398 if (sscanf(line
, "cpu%9[^ ]", cpu_char
) != 1)
4401 if (sscanf(cpu_char
, "%d", &physcpu
) != 1)
4404 if (physcpu
>= cg_cpu_usage_size
)
4410 if (!cpu_in_cpuset(physcpu
, cpuset
)) {
4411 for (i
= curcpu
; i
<= physcpu
; i
++)
4412 cg_cpu_usage
[i
].online
= false;
4416 if (curcpu
< physcpu
) {
4417 /* Some CPUs may be disabled */
4418 for (i
= curcpu
; i
< physcpu
; i
++)
4419 cg_cpu_usage
[i
].online
= false;
4424 cg_cpu_usage
[curcpu
].online
= true;
4426 ret
= sscanf(line
, "%*s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
4441 all_used
= user
+ nice
+ system
+ iowait
+ irq
+ softirq
+ steal
+ guest
+ guest_nice
;
4442 cg_used
= cg_cpu_usage
[curcpu
].user
+ cg_cpu_usage
[curcpu
].system
;
4444 if (all_used
>= cg_used
) {
4445 cg_cpu_usage
[curcpu
].idle
= idle
+ (all_used
- cg_used
);
4448 lxcfs_error("cpu%d from %s has unexpected cpu time: %lu in /proc/stat, "
4449 "%lu in cpuacct.usage_all; unable to determine idle time\n",
4450 curcpu
, cg
, all_used
, cg_used
);
4451 cg_cpu_usage
[curcpu
].idle
= idle
;
4455 /* Cannot use more CPUs than is available due to cpuset */
4456 if (max_cpus
> cpu_cnt
)
4459 stat_node
= find_or_create_proc_stat_node(cg_cpu_usage
, nprocs
, cg
);
4462 lxcfs_error("unable to find/create stat node for %s\n", cg
);
4466 diff
= malloc(sizeof(struct cpuacct_usage
) * nprocs
);
4472 * If the new values are LOWER than values stored in memory, it means
4473 * the cgroup has been reset/recreated and we should reset too.
4475 for (curcpu
= 0; curcpu
< nprocs
; curcpu
++) {
4476 if (!cg_cpu_usage
[curcpu
].online
)
4479 if (cg_cpu_usage
[curcpu
].user
< stat_node
->usage
[curcpu
].user
)
4480 reset_proc_stat_node(stat_node
, cg_cpu_usage
, nprocs
);
4485 total_sum
= diff_cpu_usage(stat_node
->usage
, cg_cpu_usage
, diff
, nprocs
);
4487 for (curcpu
= 0, i
= -1; curcpu
< nprocs
; curcpu
++) {
4488 stat_node
->usage
[curcpu
].online
= cg_cpu_usage
[curcpu
].online
;
4490 if (!stat_node
->usage
[curcpu
].online
)
4495 stat_node
->usage
[curcpu
].user
+= diff
[curcpu
].user
;
4496 stat_node
->usage
[curcpu
].system
+= diff
[curcpu
].system
;
4497 stat_node
->usage
[curcpu
].idle
+= diff
[curcpu
].idle
;
4499 if (max_cpus
> 0 && i
>= max_cpus
) {
4500 user_surplus
+= diff
[curcpu
].user
;
4501 system_surplus
+= diff
[curcpu
].system
;
4505 /* Calculate usage counters of visible CPUs */
4507 unsigned long diff_user
= 0;
4508 unsigned long diff_system
= 0;
4509 unsigned long diff_idle
= 0;
4510 unsigned long max_diff_idle
= 0;
4511 unsigned long max_diff_idle_index
= 0;
4514 /* threshold = maximum usage per cpu, including idle */
4515 threshold
= total_sum
/ cpu_cnt
* max_cpus
;
4517 for (curcpu
= 0, i
= -1; curcpu
< nprocs
; curcpu
++) {
4518 if (!stat_node
->usage
[curcpu
].online
)
4526 if (diff
[curcpu
].user
+ diff
[curcpu
].system
>= threshold
)
4530 add_cpu_usage(&user_surplus
, &diff
[curcpu
],
4531 &diff
[curcpu
].user
, threshold
);
4533 if (diff
[curcpu
].user
+ diff
[curcpu
].system
>= threshold
)
4536 /* If there is still room, add system */
4537 add_cpu_usage(&system_surplus
, &diff
[curcpu
],
4538 &diff
[curcpu
].system
, threshold
);
4541 if (user_surplus
> 0)
4542 lxcfs_debug("leftover user: %lu for %s\n", user_surplus
, cg
);
4543 if (system_surplus
> 0)
4544 lxcfs_debug("leftover system: %lu for %s\n", system_surplus
, cg
);
4546 for (curcpu
= 0, i
= -1; curcpu
< nprocs
; curcpu
++) {
4547 if (!stat_node
->usage
[curcpu
].online
)
4555 stat_node
->view
[curcpu
].user
+= diff
[curcpu
].user
;
4556 stat_node
->view
[curcpu
].system
+= diff
[curcpu
].system
;
4557 stat_node
->view
[curcpu
].idle
+= diff
[curcpu
].idle
;
4559 user_sum
+= stat_node
->view
[curcpu
].user
;
4560 system_sum
+= stat_node
->view
[curcpu
].system
;
4561 idle_sum
+= stat_node
->view
[curcpu
].idle
;
4563 diff_user
+= diff
[curcpu
].user
;
4564 diff_system
+= diff
[curcpu
].system
;
4565 diff_idle
+= diff
[curcpu
].idle
;
4566 if (diff
[curcpu
].idle
> max_diff_idle
) {
4567 max_diff_idle
= diff
[curcpu
].idle
;
4568 max_diff_idle_index
= curcpu
;
4571 lxcfs_v("curcpu: %d, diff_user: %lu, diff_system: %lu, diff_idle: %lu\n", curcpu
, diff
[curcpu
].user
, diff
[curcpu
].system
, diff
[curcpu
].idle
);
4573 lxcfs_v("total. diff_user: %lu, diff_system: %lu, diff_idle: %lu\n", diff_user
, diff_system
, diff_idle
);
4575 /* revise cpu usage view to support partial cpu case. */
4576 exact_cpus
= exact_cpu_count(cg
);
4577 if (exact_cpus
< (double)max_cpus
){
4578 unsigned long delta
= (unsigned long)((double)(diff_user
+ diff_system
+ diff_idle
) * (1 - exact_cpus
/ (double)max_cpus
));
4580 lxcfs_v("revising cpu usage view to match the exact cpu count [%f]\n", exact_cpus
);
4581 lxcfs_v("delta: %lu\n", delta
);
4582 lxcfs_v("idle_sum before: %lu\n", idle_sum
);
4583 idle_sum
= idle_sum
> delta
? idle_sum
- delta
: 0;
4584 lxcfs_v("idle_sum after: %lu\n", idle_sum
);
4586 curcpu
= max_diff_idle_index
;
4587 lxcfs_v("curcpu: %d, idle before: %lu\n", curcpu
, stat_node
->view
[curcpu
].idle
);
4588 stat_node
->view
[curcpu
].idle
= stat_node
->view
[curcpu
].idle
> delta
? stat_node
->view
[curcpu
].idle
- delta
: 0;
4589 lxcfs_v("curcpu: %d, idle after: %lu\n", curcpu
, stat_node
->view
[curcpu
].idle
);
4592 for (curcpu
= 0; curcpu
< nprocs
; curcpu
++) {
4593 if (!stat_node
->usage
[curcpu
].online
)
4596 stat_node
->view
[curcpu
].user
= stat_node
->usage
[curcpu
].user
;
4597 stat_node
->view
[curcpu
].system
= stat_node
->usage
[curcpu
].system
;
4598 stat_node
->view
[curcpu
].idle
= stat_node
->usage
[curcpu
].idle
;
4600 user_sum
+= stat_node
->view
[curcpu
].user
;
4601 system_sum
+= stat_node
->view
[curcpu
].system
;
4602 idle_sum
+= stat_node
->view
[curcpu
].idle
;
4606 /* Render the file */
4608 l
= snprintf(buf
, buf_size
, "cpu %lu 0 %lu %lu 0 0 0 0 0 0\n",
4612 lxcfs_v("cpu-all: %s\n", buf
);
4615 perror("Error writing to cache");
4618 if (l
>= buf_size
) {
4619 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4627 /* Render visible CPUs */
4628 for (curcpu
= 0, i
= -1; curcpu
< nprocs
; curcpu
++) {
4629 if (!stat_node
->usage
[curcpu
].online
)
4634 if (max_cpus
> 0 && i
== max_cpus
)
4637 l
= snprintf(buf
, buf_size
, "cpu%d %lu 0 %lu %lu 0 0 0 0 0 0\n",
4639 stat_node
->view
[curcpu
].user
,
4640 stat_node
->view
[curcpu
].system
,
4641 stat_node
->view
[curcpu
].idle
);
4642 lxcfs_v("cpu: %s\n", buf
);
4645 perror("Error writing to cache");
4649 if (l
>= buf_size
) {
4650 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4659 /* Pass the rest of /proc/stat, start with the last line read */
4660 l
= snprintf(buf
, buf_size
, "%s", line
);
4663 perror("Error writing to cache");
4667 if (l
>= buf_size
) {
4668 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4676 /* Pass the rest of the host's /proc/stat */
4677 while (getline(&line
, &linelen
, f
) != -1) {
4678 l
= snprintf(buf
, buf_size
, "%s", line
);
4680 perror("Error writing to cache");
4683 if (l
>= buf_size
) {
4684 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4693 pthread_mutex_unlock(&stat_node
->lock
);
4697 #define CPUALL_MAX_SIZE (BUF_RESERVE_SIZE / 2)
4698 static int proc_stat_read(char *buf
, size_t size
, off_t offset
,
4699 struct fuse_file_info
*fi
)
4701 __do_free
char *cg
= NULL
, *cpuset
= NULL
, *line
= NULL
;
4702 __do_free
struct cpuacct_usage
*cg_cpu_usage
= NULL
;
4703 __do_fclose
FILE *f
= NULL
;
4704 struct fuse_context
*fc
= fuse_get_context();
4705 struct file_info
*d
= (struct file_info
*)fi
->fh
;
4706 size_t linelen
= 0, total_len
= 0;
4707 int curcpu
= -1; /* cpu numbering starts at 0 */
4709 unsigned long user
= 0, nice
= 0, system
= 0, idle
= 0, iowait
= 0,
4710 irq
= 0, softirq
= 0, steal
= 0, guest
= 0, guest_nice
= 0;
4711 unsigned long user_sum
= 0, nice_sum
= 0, system_sum
= 0, idle_sum
= 0,
4712 iowait_sum
= 0, irq_sum
= 0, softirq_sum
= 0,
4713 steal_sum
= 0, guest_sum
= 0, guest_nice_sum
= 0;
4714 char cpuall
[CPUALL_MAX_SIZE
];
4715 /* reserve for cpu all */
4716 char *cache
= d
->buf
+ CPUALL_MAX_SIZE
;
4717 size_t cache_size
= d
->buflen
- CPUALL_MAX_SIZE
;
4718 int cg_cpu_usage_size
= 0;
4721 if (offset
> d
->size
)
4725 int left
= d
->size
- offset
;
4726 total_len
= left
> size
? size
: left
;
4727 memcpy(buf
, d
->buf
+ offset
, total_len
);
4731 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
4732 lxcfs_v("initpid: %d\n", initpid
);
4737 * when container run with host pid namespace initpid == 1, cgroup will "/"
4738 * we should return host os's /proc contents.
4739 * in some case cpuacct_usage.all in "/" will larger then /proc/stat
4742 return read_file_fuse("/proc/stat", buf
, size
, d
);
4745 cg
= get_pid_cgroup(initpid
, "cpuset");
4746 lxcfs_v("cg: %s\n", cg
);
4748 return read_file_fuse("/proc/stat", buf
, size
, d
);
4749 prune_init_slice(cg
);
4751 cpuset
= get_cpuset(cg
);
4756 * Read cpuacct.usage_all for all CPUs.
4757 * If the cpuacct cgroup is present, it is used to calculate the container's
4758 * CPU usage. If not, values from the host's /proc/stat are used.
4760 if (read_cpuacct_usage_all(cg
, cpuset
, &cg_cpu_usage
, &cg_cpu_usage_size
) != 0) {
4761 lxcfs_v("%s\n", "proc_stat_read failed to read from cpuacct, "
4762 "falling back to the host's /proc/stat");
4765 f
= fopen("/proc/stat", "r");
4770 if (getline(&line
, &linelen
, f
) < 0) {
4771 lxcfs_error("%s\n", "proc_stat_read read first line failed.");
4775 if (cgroup_ops
->can_use_cpuview(cgroup_ops
) && cg_cpu_usage
) {
4776 total_len
= cpuview_proc_stat(cg
, cpuset
, cg_cpu_usage
, cg_cpu_usage_size
,
4777 f
, d
->buf
, d
->buflen
);
4781 while (getline(&line
, &linelen
, f
) != -1) {
4783 char cpu_char
[10]; /* That's a lot of cores */
4785 uint64_t all_used
, cg_used
, new_idle
;
4788 if (strlen(line
) == 0)
4790 if (sscanf(line
, "cpu%9[^ ]", cpu_char
) != 1) {
4791 /* not a ^cpuN line containing a number N, just print it */
4792 l
= snprintf(cache
, cache_size
, "%s", line
);
4794 perror("Error writing to cache");
4797 if (l
>= cache_size
) {
4798 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4807 if (sscanf(cpu_char
, "%d", &physcpu
) != 1)
4809 if (!cpu_in_cpuset(physcpu
, cpuset
))
4813 ret
= sscanf(line
, "%*s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
4825 if (ret
!= 10 || !cg_cpu_usage
) {
4826 c
= strchr(line
, ' ');
4829 l
= snprintf(cache
, cache_size
, "cpu%d%s", curcpu
, c
);
4831 perror("Error writing to cache");
4835 if (l
>= cache_size
) {
4836 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4849 if (physcpu
>= cg_cpu_usage_size
)
4852 all_used
= user
+ nice
+ system
+ iowait
+ irq
+ softirq
+ steal
+ guest
+ guest_nice
;
4853 cg_used
= cg_cpu_usage
[physcpu
].user
+ cg_cpu_usage
[physcpu
].system
;
4855 if (all_used
>= cg_used
) {
4856 new_idle
= idle
+ (all_used
- cg_used
);
4859 lxcfs_error("cpu%d from %s has unexpected cpu time: %lu in /proc/stat, "
4860 "%lu in cpuacct.usage_all; unable to determine idle time\n",
4861 curcpu
, cg
, all_used
, cg_used
);
4865 l
= snprintf(cache
, cache_size
, "cpu%d %lu 0 %lu %lu 0 0 0 0 0 0\n",
4866 curcpu
, cg_cpu_usage
[physcpu
].user
, cg_cpu_usage
[physcpu
].system
,
4870 perror("Error writing to cache");
4874 if (l
>= cache_size
) {
4875 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
4883 user_sum
+= cg_cpu_usage
[physcpu
].user
;
4884 system_sum
+= cg_cpu_usage
[physcpu
].system
;
4885 idle_sum
+= new_idle
;
4890 system_sum
+= system
;
4892 iowait_sum
+= iowait
;
4894 softirq_sum
+= softirq
;
4897 guest_nice_sum
+= guest_nice
;
4903 int cpuall_len
= snprintf(cpuall
, CPUALL_MAX_SIZE
, "cpu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
4914 if (cpuall_len
> 0 && cpuall_len
< CPUALL_MAX_SIZE
) {
4915 memcpy(cache
, cpuall
, cpuall_len
);
4916 cache
+= cpuall_len
;
4918 /* shouldn't happen */
4919 lxcfs_error("proc_stat_read copy cpuall failed, cpuall_len=%d.", cpuall_len
);
4923 memmove(cache
, d
->buf
+ CPUALL_MAX_SIZE
, total_len
);
4924 total_len
+= cpuall_len
;
4928 d
->size
= total_len
;
4929 if (total_len
> size
)
4932 memcpy(buf
, d
->buf
, total_len
);
4936 /* This function retrieves the busy time of a group of tasks by looking at
4937 * cpuacct.usage. Unfortunately, this only makes sense when the container has
4938 * been given it's own cpuacct cgroup. If not, this function will take the busy
4939 * time of all other taks that do not actually belong to the container into
4940 * account as well. If someone has a clever solution for this please send a
4943 static double get_reaper_busy(pid_t task
)
4945 __do_free
char *cgroup
= NULL
, *usage_str
= NULL
;
4946 unsigned long usage
= 0;
4949 initpid
= lookup_initpid_in_store(task
);
4953 cgroup
= get_pid_cgroup(initpid
, "cpuacct");
4956 prune_init_slice(cgroup
);
4957 if (!cgroup_ops
->get(cgroup_ops
, "cpuacct", cgroup
, "cpuacct.usage",
4961 usage
= strtoul(usage_str
, NULL
, 10);
4962 return ((double)usage
/ 1000000000);
4970 fd
= creat("/tmp/lxcfs-iwashere", 0644);
4977 * We read /proc/uptime and reuse its second field.
4978 * For the first field, we use the mtime for the reaper for
4979 * the calling pid as returned by getreaperage
4981 static int proc_uptime_read(char *buf
, size_t size
, off_t offset
,
4982 struct fuse_file_info
*fi
)
4984 struct fuse_context
*fc
= fuse_get_context();
4985 struct file_info
*d
= (struct file_info
*)fi
->fh
;
4986 double busytime
= get_reaper_busy(fc
->pid
);
4987 char *cache
= d
->buf
;
4988 ssize_t total_len
= 0;
4989 double idletime
, reaperage
;
4998 if (offset
> d
->size
)
5000 int left
= d
->size
- offset
;
5001 total_len
= left
> size
? size
: left
;
5002 memcpy(buf
, cache
+ offset
, total_len
);
5006 reaperage
= get_reaper_age(fc
->pid
);
5007 /* To understand why this is done, please read the comment to the
5008 * get_reaper_busy() function.
5010 idletime
= reaperage
;
5011 if (reaperage
>= busytime
)
5012 idletime
= reaperage
- busytime
;
5014 total_len
= snprintf(d
->buf
, d
->buflen
, "%.2lf %.2lf\n", reaperage
, idletime
);
5015 if (total_len
< 0 || total_len
>= d
->buflen
){
5016 lxcfs_error("%s\n", "failed to write to cache");
5020 d
->size
= (int)total_len
;
5023 if (total_len
> size
) total_len
= size
;
5025 memcpy(buf
, d
->buf
, total_len
);
5029 static int proc_diskstats_read(char *buf
, size_t size
, off_t offset
,
5030 struct fuse_file_info
*fi
)
5032 __do_free
char *cg
= NULL
, *io_serviced_str
= NULL
,
5033 *io_merged_str
= NULL
, *io_service_bytes_str
= NULL
,
5034 *io_wait_time_str
= NULL
, *io_service_time_str
= NULL
,
5036 __do_fclose
FILE *f
= NULL
;
5037 struct fuse_context
*fc
= fuse_get_context();
5038 struct file_info
*d
= (struct file_info
*)fi
->fh
;
5039 unsigned long read
= 0, write
= 0;
5040 unsigned long read_merged
= 0, write_merged
= 0;
5041 unsigned long read_sectors
= 0, write_sectors
= 0;
5042 unsigned long read_ticks
= 0, write_ticks
= 0;
5043 unsigned long ios_pgr
= 0, tot_ticks
= 0, rq_ticks
= 0;
5044 unsigned long rd_svctm
= 0, wr_svctm
= 0, rd_wait
= 0, wr_wait
= 0;
5045 char *cache
= d
->buf
;
5046 size_t cache_size
= d
->buflen
;
5047 size_t linelen
= 0, total_len
= 0;
5048 unsigned int major
= 0, minor
= 0;
5056 if (offset
> d
->size
)
5062 left
= d
->size
- offset
;
5063 total_len
= left
> size
? size
: left
;
5064 memcpy(buf
, cache
+ offset
, total_len
);
5069 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
5070 if (initpid
<= 1 || is_shared_pidns(initpid
))
5072 cg
= get_pid_cgroup(initpid
, "blkio");
5074 return read_file_fuse("/proc/diskstats", buf
, size
, d
);
5075 prune_init_slice(cg
);
5077 ret
= cgroup_ops
->get_io_serviced(cgroup_ops
, cg
, &io_serviced_str
);
5079 if (ret
== -EOPNOTSUPP
)
5080 return read_file_fuse("/proc/diskstats", buf
, size
, d
);
5083 ret
= cgroup_ops
->get_io_merged(cgroup_ops
, cg
, &io_merged_str
);
5085 if (ret
== -EOPNOTSUPP
)
5086 return read_file_fuse("/proc/diskstats", buf
, size
, d
);
5089 ret
= cgroup_ops
->get_io_service_bytes(cgroup_ops
, cg
, &io_service_bytes_str
);
5091 if (ret
== -EOPNOTSUPP
)
5092 return read_file_fuse("/proc/diskstats", buf
, size
, d
);
5095 ret
= cgroup_ops
->get_io_wait_time(cgroup_ops
, cg
, &io_wait_time_str
);
5097 if (ret
== -EOPNOTSUPP
)
5098 return read_file_fuse("/proc/diskstats", buf
, size
, d
);
5101 ret
= cgroup_ops
->get_io_service_time(cgroup_ops
, cg
, &io_service_time_str
);
5103 if (ret
== -EOPNOTSUPP
)
5104 return read_file_fuse("/proc/diskstats", buf
, size
, d
);
5107 f
= fopen("/proc/diskstats", "r");
5111 while (getline(&line
, &linelen
, f
) != -1) {
5115 i
= sscanf(line
, "%u %u %71s", &major
, &minor
, dev_name
);
5119 get_blkio_io_value(io_serviced_str
, major
, minor
, "Read", &read
);
5120 get_blkio_io_value(io_serviced_str
, major
, minor
, "Write", &write
);
5121 get_blkio_io_value(io_merged_str
, major
, minor
, "Read", &read_merged
);
5122 get_blkio_io_value(io_merged_str
, major
, minor
, "Write", &write_merged
);
5123 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Read", &read_sectors
);
5124 read_sectors
= read_sectors
/512;
5125 get_blkio_io_value(io_service_bytes_str
, major
, minor
, "Write", &write_sectors
);
5126 write_sectors
= write_sectors
/512;
5128 get_blkio_io_value(io_service_time_str
, major
, minor
, "Read", &rd_svctm
);
5129 rd_svctm
= rd_svctm
/1000000;
5130 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Read", &rd_wait
);
5131 rd_wait
= rd_wait
/1000000;
5132 read_ticks
= rd_svctm
+ rd_wait
;
5134 get_blkio_io_value(io_service_time_str
, major
, minor
, "Write", &wr_svctm
);
5135 wr_svctm
= wr_svctm
/1000000;
5136 get_blkio_io_value(io_wait_time_str
, major
, minor
, "Write", &wr_wait
);
5137 wr_wait
= wr_wait
/1000000;
5138 write_ticks
= wr_svctm
+ wr_wait
;
5140 get_blkio_io_value(io_service_time_str
, major
, minor
, "Total", &tot_ticks
);
5141 tot_ticks
= tot_ticks
/1000000;
5143 memset(lbuf
, 0, 256);
5144 if (read
|| write
|| read_merged
|| write_merged
|| read_sectors
|| write_sectors
|| read_ticks
|| write_ticks
)
5145 snprintf(lbuf
, 256, "%u %u %s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
5146 major
, minor
, dev_name
, read
, read_merged
, read_sectors
, read_ticks
,
5147 write
, write_merged
, write_sectors
, write_ticks
, ios_pgr
, tot_ticks
, rq_ticks
);
5151 l
= snprintf(cache
, cache_size
, "%s", lbuf
);
5153 perror("Error writing to fuse buf");
5156 if (l
>= cache_size
) {
5157 lxcfs_error("%s\n", "Internal error: truncated write to cache.");
5166 d
->size
= total_len
;
5167 if (total_len
> size
) total_len
= size
;
5168 memcpy(buf
, d
->buf
, total_len
);
5173 static int proc_swaps_read(char *buf
, size_t size
, off_t offset
,
5174 struct fuse_file_info
*fi
)
5176 __do_free
char *cg
= NULL
, *memswlimit_str
= NULL
, *memusage_str
= NULL
,
5177 *memswusage_str
= NULL
;
5178 struct fuse_context
*fc
= fuse_get_context();
5179 struct file_info
*d
= (struct file_info
*)fi
->fh
;
5180 unsigned long memswlimit
= 0, memlimit
= 0, memusage
= 0,
5181 memswusage
= 0, swap_total
= 0, swap_free
= 0;
5182 ssize_t total_len
= 0;
5184 char *cache
= d
->buf
;
5190 if (offset
> d
->size
)
5196 left
= d
->size
- offset
;
5197 total_len
= left
> size
? size
: left
;
5198 memcpy(buf
, cache
+ offset
, total_len
);
5203 pid_t initpid
= lookup_initpid_in_store(fc
->pid
);
5204 if (initpid
<= 1 || is_shared_pidns(initpid
))
5206 cg
= get_pid_cgroup(initpid
, "memory");
5208 return read_file_fuse("/proc/swaps", buf
, size
, d
);
5209 prune_init_slice(cg
);
5211 memlimit
= get_min_memlimit(cg
, false);
5213 ret
= cgroup_ops
->get_memory_current(cgroup_ops
, cg
, &memusage_str
);
5217 memusage
= strtoul(memusage_str
, NULL
, 10);
5219 ret
= cgroup_ops
->get_memory_swap_max(cgroup_ops
, cg
, &memswlimit_str
);
5221 ret
= cgroup_ops
->get_memory_swap_current(cgroup_ops
, cg
, &memswusage_str
);
5223 memswlimit
= get_min_memlimit(cg
, true);
5224 memswusage
= strtoul(memswusage_str
, NULL
, 10);
5225 swap_total
= (memswlimit
- memlimit
) / 1024;
5226 swap_free
= (memswusage
- memusage
) / 1024;
5229 total_len
= snprintf(d
->buf
, d
->size
, "Filename\t\t\t\tType\t\tSize\tUsed\tPriority\n");
5231 /* When no mem + swap limit is specified or swapaccount=0*/
5233 __do_free
char *line
= NULL
;
5234 __do_fclose
FILE *f
= NULL
;
5237 f
= fopen("/proc/meminfo", "r");
5241 while (getline(&line
, &linelen
, f
) != -1) {
5242 if (startswith(line
, "SwapTotal:"))
5243 sscanf(line
, "SwapTotal: %8lu kB", &swap_total
);
5244 else if (startswith(line
, "SwapFree:"))
5245 sscanf(line
, "SwapFree: %8lu kB", &swap_free
);
5249 if (swap_total
> 0) {
5250 l
= snprintf(d
->buf
+ total_len
, d
->size
- total_len
,
5251 "none%*svirtual\t\t%lu\t%lu\t0\n", 36, " ",
5252 swap_total
, swap_free
);
5256 if (total_len
< 0 || l
< 0) {
5257 perror("Error writing to cache");
5262 d
->size
= (int)total_len
;
5264 if (total_len
> size
) total_len
= size
;
5265 memcpy(buf
, d
->buf
, total_len
);
5270 * Find the process pid from cgroup path.
5271 * eg:from /sys/fs/cgroup/cpu/docker/containerid/cgroup.procs to find the process pid.
5272 * @pid_buf : put pid to pid_buf.
5273 * @dpath : the path of cgroup. eg: /docker/containerid or /docker/containerid/child-cgroup ...
5274 * @depth : the depth of cgroup in container.
5275 * @sum : return the number of pid.
5276 * @cfd : the file descriptor of the mounted cgroup. eg: /sys/fs/cgroup/cpu
5278 static int calc_pid(char ***pid_buf
, char *dpath
, int depth
, int sum
, int cfd
)
5280 __do_free
char *path
= NULL
;
5281 __do_close_prot_errno
int fd
= -EBADF
;
5282 __do_fclose
FILE *f
= NULL
;
5283 __do_closedir
DIR *dir
= NULL
;
5284 struct dirent
*file
;
5290 /* path = dpath + "/cgroup.procs" + /0 */
5291 path
= malloc(strlen(dpath
) + 20);
5295 strcpy(path
, dpath
);
5296 fd
= openat(cfd
, path
, O_RDONLY
| O_CLOEXEC
| O_NOFOLLOW
);
5300 dir
= fdopendir(move_fd(fd
));
5304 while (((file
= readdir(dir
)) != NULL
) && depth
> 0) {
5305 if (strcmp(file
->d_name
, ".") == 0)
5308 if (strcmp(file
->d_name
, "..") == 0)
5311 if (file
->d_type
== DT_DIR
) {
5312 __do_free
char *path_dir
= NULL
;
5314 /* path + '/' + d_name +/0 */
5315 path_dir
= malloc(strlen(path
) + 2 + sizeof(file
->d_name
));
5319 strcpy(path_dir
, path
);
5320 strcat(path_dir
, "/");
5321 strcat(path_dir
, file
->d_name
);
5323 sum
= calc_pid(pid_buf
, path_dir
, pd
, sum
, cfd
);
5327 strcat(path
, "/cgroup.procs");
5328 fd
= openat(cfd
, path
, O_RDONLY
);
5332 f
= fdopen(move_fd(fd
), "r");
5336 while (getline(&line
, &linelen
, f
) != -1) {
5337 pid
= realloc(*pid_buf
, sizeof(char *) * (sum
+ 1));
5342 *(*pid_buf
+ sum
) = malloc(strlen(line
) + 1);
5343 if (!*(*pid_buf
+ sum
))
5346 strcpy(*(*pid_buf
+ sum
), line
);
5354 * calc_load calculates the load according to the following formula:
5355 * load1 = load0 * exp + active * (1 - exp)
5357 * @load1: the new loadavg.
5358 * @load0: the former loadavg.
5359 * @active: the total number of running pid at this moment.
5360 * @exp: the fixed-point defined in the beginning.
5362 static unsigned long
5363 calc_load(unsigned long load
, unsigned long exp
, unsigned long active
)
5365 unsigned long newload
;
5367 active
= active
> 0 ? active
* FIXED_1
: 0;
5368 newload
= load
* exp
+ active
* (FIXED_1
- exp
);
5370 newload
+= FIXED_1
- 1;
5372 return newload
/ FIXED_1
;
5376 * Return 0 means that container p->cg is closed.
5377 * Return -1 means that error occurred in refresh.
5378 * Positive num equals the total number of pid.
5380 static int refresh_load(struct load_node
*p
, char *path
)
5382 __do_free
char *line
= NULL
;
5384 char proc_path
[256];
5385 int i
, ret
, run_pid
= 0, total_pid
= 0, last_pid
= 0;
5388 struct dirent
*file
;
5390 idbuf
= malloc(sizeof(char *));
5394 sum
= calc_pid(&idbuf
, path
, DEPTH_DIR
, 0, p
->cfd
);
5399 for (i
= 0; i
< sum
; i
++) {
5400 __do_closedir
DIR *dp
= NULL
;
5403 length
= strlen(idbuf
[i
])-1;
5404 idbuf
[i
][length
] = '\0';
5405 ret
= snprintf(proc_path
, 256, "/proc/%s/task", idbuf
[i
]);
5406 if (ret
< 0 || ret
> 255) {
5407 lxcfs_error("%s\n", "snprintf() failed in refresh_load.");
5413 dp
= opendir(proc_path
);
5415 lxcfs_error("%s\n", "Open proc_path failed in refresh_load.");
5418 while ((file
= readdir(dp
)) != NULL
) {
5419 __do_fclose
FILE *f
= NULL
;
5421 if (strncmp(file
->d_name
, ".", 1) == 0)
5423 if (strncmp(file
->d_name
, "..", 1) == 0)
5426 /* We make the biggest pid become last_pid.*/
5427 ret
= atof(file
->d_name
);
5428 last_pid
= (ret
> last_pid
) ? ret
: last_pid
;
5430 ret
= snprintf(proc_path
, 256, "/proc/%s/task/%s/status", idbuf
[i
], file
->d_name
);
5431 if (ret
< 0 || ret
> 255) {
5432 lxcfs_error("%s\n", "snprintf() failed in refresh_load.");
5438 f
= fopen(proc_path
, "r");
5440 while (getline(&line
, &linelen
, f
) != -1) {
5442 if ((line
[0] == 'S') && (line
[1] == 't'))
5446 if ((line
[7] == 'R') || (line
[7] == 'D'))
5451 /*Calculate the loadavg.*/
5452 p
->avenrun
[0] = calc_load(p
->avenrun
[0], EXP_1
, run_pid
);
5453 p
->avenrun
[1] = calc_load(p
->avenrun
[1], EXP_5
, run_pid
);
5454 p
->avenrun
[2] = calc_load(p
->avenrun
[2], EXP_15
, run_pid
);
5455 p
->run_pid
= run_pid
;
5456 p
->total_pid
= total_pid
;
5457 p
->last_pid
= last_pid
;
5468 * Traverse the hash table and update it.
5470 void *load_begin(void *arg
)
5473 int i
, sum
, length
, ret
;
5474 struct load_node
*f
;
5476 clock_t time1
, time2
;
5479 if (loadavg_stop
== 1)
5483 for (i
= 0; i
< LOAD_SIZE
; i
++) {
5484 pthread_mutex_lock(&load_hash
[i
].lock
);
5485 if (load_hash
[i
].next
== NULL
) {
5486 pthread_mutex_unlock(&load_hash
[i
].lock
);
5489 f
= load_hash
[i
].next
;
5492 __do_free
char *path
= NULL
;
5494 length
= strlen(f
->cg
) + 2;
5495 /* strlen(f->cg) + '.' or '' + \0 */
5496 path
= malloc(length
);
5500 ret
= snprintf(path
, length
, "%s%s", dot_or_empty(f
->cg
), f
->cg
);
5501 if (ret
< 0 || ret
> length
- 1) {
5502 /* snprintf failed, ignore the node.*/
5503 lxcfs_error("Refresh node %s failed for snprintf().\n", f
->cg
);
5507 sum
= refresh_load(f
, path
);
5512 /* load_hash[i].lock locks only on the first node.*/
5513 if (first_node
== 1) {
5515 pthread_mutex_unlock(&load_hash
[i
].lock
);
5520 if (loadavg_stop
== 1)
5524 usleep(FLUSH_TIME
* 1000000 - (int)((time2
- time1
) * 1000000 / CLOCKS_PER_SEC
));
5528 static int proc_loadavg_read(char *buf
, size_t size
, off_t offset
,
5529 struct fuse_file_info
*fi
)
5531 struct fuse_context
*fc
= fuse_get_context();
5532 struct file_info
*d
= (struct file_info
*)fi
->fh
;
5535 size_t total_len
= 0;
5536 char *cache
= d
->buf
;
5537 struct load_node
*n
;
5540 unsigned long a
, b
, c
;
5543 if (offset
> d
->size
)
5547 int left
= d
->size
- offset
;
5548 total_len
= left
> size
? size
: left
;
5549 memcpy(buf
, cache
+ offset
, total_len
);
5553 return read_file_fuse("/proc/loadavg", buf
, size
, d
);
5555 initpid
= lookup_initpid_in_store(fc
->pid
);
5556 if (initpid
<= 1 || is_shared_pidns(initpid
))
5558 cg
= get_pid_cgroup(initpid
, "cpu");
5560 return read_file_fuse("/proc/loadavg", buf
, size
, d
);
5562 prune_init_slice(cg
);
5563 hash
= calc_hash(cg
) % LOAD_SIZE
;
5564 n
= locate_node(cg
, hash
);
5568 cfd
= get_cgroup_fd("cpu");
5571 * In locate_node() above, pthread_rwlock_unlock() isn't used
5572 * because delete is not allowed before read has ended.
5574 pthread_rwlock_unlock(&load_hash
[hash
].rdlock
);
5579 n
= malloc(sizeof(struct load_node
));
5583 n
->cg
= malloc(strlen(cg
)+1);
5591 n
->last_pid
= initpid
;
5593 insert_node(&n
, hash
);
5595 a
= n
->avenrun
[0] + (FIXED_1
/200);
5596 b
= n
->avenrun
[1] + (FIXED_1
/200);
5597 c
= n
->avenrun
[2] + (FIXED_1
/200);
5598 total_len
= snprintf(d
->buf
, d
->buflen
, "%lu.%02lu %lu.%02lu %lu.%02lu %d/%d %d\n",
5599 LOAD_INT(a
), LOAD_FRAC(a
),
5600 LOAD_INT(b
), LOAD_FRAC(b
),
5601 LOAD_INT(c
), LOAD_FRAC(c
),
5602 n
->run_pid
, n
->total_pid
, n
->last_pid
);
5603 pthread_rwlock_unlock(&load_hash
[hash
].rdlock
);
5604 if (total_len
< 0 || total_len
>= d
->buflen
) {
5605 lxcfs_error("%s\n", "Failed to write to cache");
5609 d
->size
= (int)total_len
;
5612 if (total_len
> size
)
5614 memcpy(buf
, d
->buf
, total_len
);
5621 /* Return a positive number on success, return 0 on failure.*/
5622 pthread_t
load_daemon(int load_use
)
5629 lxcfs_error("%s\n", "Initialize hash_table fails in load_daemon!");
5632 ret
= pthread_create(&pid
, NULL
, load_begin
, NULL
);
5634 lxcfs_error("%s\n", "Create pthread fails in load_daemon!");
5638 /* use loadavg, here loadavg = 1*/
5643 /* Returns 0 on success. */
5644 int stop_load_daemon(pthread_t pid
)
5648 /* Signal the thread to gracefully stop */
5651 s
= pthread_join(pid
, NULL
); /* Make sure sub thread has been canceled. */
5653 lxcfs_error("%s\n", "stop_load_daemon error: failed to join");
5663 static off_t
get_procfile_size(const char *which
)
5665 FILE *f
= fopen(which
, "r");
5668 ssize_t sz
, answer
= 0;
5672 while ((sz
= getline(&line
, &len
, f
)) != -1)
5680 int proc_getattr(const char *path
, struct stat
*sb
)
5682 struct timespec now
;
5684 memset(sb
, 0, sizeof(struct stat
));
5685 if (clock_gettime(CLOCK_REALTIME
, &now
) < 0)
5687 sb
->st_uid
= sb
->st_gid
= 0;
5688 sb
->st_atim
= sb
->st_mtim
= sb
->st_ctim
= now
;
5689 if (strcmp(path
, "/proc") == 0) {
5690 sb
->st_mode
= S_IFDIR
| 00555;
5694 if (strcmp(path
, "/proc/meminfo") == 0 ||
5695 strcmp(path
, "/proc/cpuinfo") == 0 ||
5696 strcmp(path
, "/proc/uptime") == 0 ||
5697 strcmp(path
, "/proc/stat") == 0 ||
5698 strcmp(path
, "/proc/diskstats") == 0 ||
5699 strcmp(path
, "/proc/swaps") == 0 ||
5700 strcmp(path
, "/proc/loadavg") == 0) {
5702 sb
->st_mode
= S_IFREG
| 00444;
5710 int proc_readdir(const char *path
, void *buf
, fuse_fill_dir_t filler
, off_t offset
,
5711 struct fuse_file_info
*fi
)
5713 if (filler(buf
, ".", NULL
, 0) != 0 ||
5714 filler(buf
, "..", NULL
, 0) != 0 ||
5715 filler(buf
, "cpuinfo", NULL
, 0) != 0 ||
5716 filler(buf
, "meminfo", NULL
, 0) != 0 ||
5717 filler(buf
, "stat", NULL
, 0) != 0 ||
5718 filler(buf
, "uptime", NULL
, 0) != 0 ||
5719 filler(buf
, "diskstats", NULL
, 0) != 0 ||
5720 filler(buf
, "swaps", NULL
, 0) != 0 ||
5721 filler(buf
, "loadavg", NULL
, 0) != 0)
5726 int proc_open(const char *path
, struct fuse_file_info
*fi
)
5729 struct file_info
*info
;
5731 if (strcmp(path
, "/proc/meminfo") == 0)
5732 type
= LXC_TYPE_PROC_MEMINFO
;
5733 else if (strcmp(path
, "/proc/cpuinfo") == 0)
5734 type
= LXC_TYPE_PROC_CPUINFO
;
5735 else if (strcmp(path
, "/proc/uptime") == 0)
5736 type
= LXC_TYPE_PROC_UPTIME
;
5737 else if (strcmp(path
, "/proc/stat") == 0)
5738 type
= LXC_TYPE_PROC_STAT
;
5739 else if (strcmp(path
, "/proc/diskstats") == 0)
5740 type
= LXC_TYPE_PROC_DISKSTATS
;
5741 else if (strcmp(path
, "/proc/swaps") == 0)
5742 type
= LXC_TYPE_PROC_SWAPS
;
5743 else if (strcmp(path
, "/proc/loadavg") == 0)
5744 type
= LXC_TYPE_PROC_LOADAVG
;
5748 info
= malloc(sizeof(*info
));
5752 memset(info
, 0, sizeof(*info
));
5755 info
->buflen
= get_procfile_size(path
) + BUF_RESERVE_SIZE
;
5757 info
->buf
= malloc(info
->buflen
);
5758 } while (!info
->buf
);
5759 memset(info
->buf
, 0, info
->buflen
);
5760 /* set actual size to buffer size */
5761 info
->size
= info
->buflen
;
5763 fi
->fh
= (unsigned long)info
;
5767 int proc_access(const char *path
, int mask
)
5769 if (strcmp(path
, "/proc") == 0 && access(path
, R_OK
) == 0)
5772 /* these are all read-only */
5773 if ((mask
& ~R_OK
) != 0)
5778 int proc_release(const char *path
, struct fuse_file_info
*fi
)
5780 do_release_file_info(fi
);
5784 int proc_read(const char *path
, char *buf
, size_t size
, off_t offset
,
5785 struct fuse_file_info
*fi
)
5787 struct file_info
*f
= (struct file_info
*) fi
->fh
;
5790 case LXC_TYPE_PROC_MEMINFO
:
5791 return proc_meminfo_read(buf
, size
, offset
, fi
);
5792 case LXC_TYPE_PROC_CPUINFO
:
5793 return proc_cpuinfo_read(buf
, size
, offset
, fi
);
5794 case LXC_TYPE_PROC_UPTIME
:
5795 return proc_uptime_read(buf
, size
, offset
, fi
);
5796 case LXC_TYPE_PROC_STAT
:
5797 return proc_stat_read(buf
, size
, offset
, fi
);
5798 case LXC_TYPE_PROC_DISKSTATS
:
5799 return proc_diskstats_read(buf
, size
, offset
, fi
);
5800 case LXC_TYPE_PROC_SWAPS
:
5801 return proc_swaps_read(buf
, size
, offset
, fi
);
5802 case LXC_TYPE_PROC_LOADAVG
:
5803 return proc_loadavg_read(buf
, size
, offset
, fi
);
5810 * Functions needed to setup cgroups in the __constructor__.
5813 static bool umount_if_mounted(void)
5815 if (umount2(BASEDIR
, MNT_DETACH
) < 0 && errno
!= EINVAL
) {
5816 lxcfs_error("Failed to unmount %s: %s.\n", BASEDIR
, strerror(errno
));
5822 /* __typeof__ should be safe to use with all compilers. */
5823 typedef __typeof__(((struct statfs
*)NULL
)->f_type
) fs_type_magic
;
5824 static bool has_fs_type(const struct statfs
*fs
, fs_type_magic magic_val
)
5826 return (fs
->f_type
== (fs_type_magic
)magic_val
);
5830 * looking at fs/proc_namespace.c, it appears we can
5831 * actually expect the rootfs entry to very specifically contain
5832 * " - rootfs rootfs "
5833 * IIUC, so long as we've chrooted so that rootfs is not our root,
5834 * the rootfs entry should always be skipped in mountinfo contents.
5836 static bool is_on_ramfs(void)
5844 f
= fopen("/proc/self/mountinfo", "r");
5848 while (getline(&line
, &len
, f
) != -1) {
5849 for (p
= line
, i
= 0; p
&& i
< 4; i
++)
5850 p
= strchr(p
+ 1, ' ');
5853 p2
= strchr(p
+ 1, ' ');
5857 if (strcmp(p
+ 1, "/") == 0) {
5858 // this is '/'. is it the ramfs?
5859 p
= strchr(p2
+ 1, '-');
5860 if (p
&& strncmp(p
, "- rootfs rootfs ", 16) == 0) {
5872 static int pivot_enter()
5874 int ret
= -1, oldroot
= -1, newroot
= -1;
5876 oldroot
= open("/", O_DIRECTORY
| O_RDONLY
);
5878 lxcfs_error("%s\n", "Failed to open old root for fchdir.");
5882 newroot
= open(ROOTDIR
, O_DIRECTORY
| O_RDONLY
);
5884 lxcfs_error("%s\n", "Failed to open new root for fchdir.");
5888 /* change into new root fs */
5889 if (fchdir(newroot
) < 0) {
5890 lxcfs_error("Failed to change directory to new rootfs: %s.\n", ROOTDIR
);
5894 /* pivot_root into our new root fs */
5895 if (pivot_root(".", ".") < 0) {
5896 lxcfs_error("pivot_root() syscall failed: %s.\n", strerror(errno
));
5901 * At this point the old-root is mounted on top of our new-root.
5902 * To unmounted it we must not be chdir'd into it, so escape back
5905 if (fchdir(oldroot
) < 0) {
5906 lxcfs_error("%s\n", "Failed to enter old root.");
5910 if (umount2(".", MNT_DETACH
) < 0) {
5911 lxcfs_error("%s\n", "Failed to detach old root.");
5915 if (fchdir(newroot
) < 0) {
5916 lxcfs_error("%s\n", "Failed to re-enter new root.");
5931 static int chroot_enter()
5933 if (mount(ROOTDIR
, "/", NULL
, MS_REC
| MS_BIND
, NULL
)) {
5934 lxcfs_error("Failed to recursively bind-mount %s into /.", ROOTDIR
);
5938 if (chroot(".") < 0) {
5939 lxcfs_error("Call to chroot() failed: %s.\n", strerror(errno
));
5943 if (chdir("/") < 0) {
5944 lxcfs_error("Failed to change directory: %s.\n", strerror(errno
));
5951 static int permute_and_enter(void)
5955 if (statfs("/", &sb
) < 0) {
5956 lxcfs_error("%s\n", "Could not stat / mountpoint.");
5960 /* has_fs_type() is not reliable. When the ramfs is a tmpfs it will
5961 * likely report TMPFS_MAGIC. Hence, when it reports no we still check
5962 * /proc/1/mountinfo. */
5963 if (has_fs_type(&sb
, RAMFS_MAGIC
) || is_on_ramfs())
5964 return chroot_enter();
5966 if (pivot_enter() < 0) {
5967 lxcfs_error("%s\n", "Could not perform pivot root.");
5974 /* Prepare our new clean root. */
5975 static int permute_prepare(void)
5977 if (mkdir(ROOTDIR
, 0700) < 0 && errno
!= EEXIST
) {
5978 lxcfs_error("%s\n", "Failed to create directory for new root.");
5982 if (mount("/", ROOTDIR
, NULL
, MS_BIND
, 0) < 0) {
5983 lxcfs_error("Failed to bind-mount / for new root: %s.\n", strerror(errno
));
5987 if (mount(RUNTIME_PATH
, ROOTDIR RUNTIME_PATH
, NULL
, MS_BIND
, 0) < 0) {
5988 lxcfs_error("Failed to bind-mount /run into new root: %s.\n", strerror(errno
));
5992 if (mount(BASEDIR
, ROOTDIR BASEDIR
, NULL
, MS_REC
| MS_MOVE
, 0) < 0) {
5993 printf("Failed to move " BASEDIR
" into new root: %s.\n", strerror(errno
));
6000 /* Calls chroot() on ramfs, pivot_root() in all other cases. */
6001 static bool permute_root(void)
6003 /* Prepare new root. */
6004 if (permute_prepare() < 0)
6007 /* Pivot into new root. */
6008 if (permute_and_enter() < 0)
6014 static int preserve_mnt_ns(int pid
)
6017 size_t len
= sizeof("/proc/") + 21 + sizeof("/ns/mnt");
6020 ret
= snprintf(path
, len
, "/proc/%d/ns/mnt", pid
);
6021 if (ret
< 0 || (size_t)ret
>= len
)
6024 return open(path
, O_RDONLY
| O_CLOEXEC
);
6027 static bool cgfs_prepare_mounts(void)
6029 if (!mkdir_p(BASEDIR
, 0700)) {
6030 lxcfs_error("%s\n", "Failed to create lxcfs cgroup mountpoint.");
6034 if (!umount_if_mounted()) {
6035 lxcfs_error("%s\n", "Failed to clean up old lxcfs cgroup mountpoint.");
6039 if (unshare(CLONE_NEWNS
) < 0) {
6040 lxcfs_error("Failed to unshare mount namespace: %s.\n", strerror(errno
));
6044 cgroup_ops
->mntns_fd
= preserve_mnt_ns(getpid());
6045 if (cgroup_ops
->mntns_fd
< 0) {
6046 lxcfs_error("Failed to preserve mount namespace: %s.\n", strerror(errno
));
6050 if (mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, 0) < 0) {
6051 lxcfs_error("Failed to remount / private: %s.\n", strerror(errno
));
6055 if (mount("tmpfs", BASEDIR
, "tmpfs", 0, "size=100000,mode=700") < 0) {
6056 lxcfs_error("%s\n", "Failed to mount tmpfs over lxcfs cgroup mountpoint.");
6063 static bool cgfs_mount_hierarchies(void)
6065 if (!mkdir_p(BASEDIR DEFAULT_CGROUP_MOUNTPOINT
, 0755))
6068 if (!cgroup_ops
->mount(cgroup_ops
, BASEDIR
))
6071 for (struct hierarchy
**h
= cgroup_ops
->hierarchies
; h
&& *h
; h
++) {
6072 __do_free
char *path
= must_make_path(BASEDIR
, (*h
)->mountpoint
, NULL
);
6073 (*h
)->fd
= open(path
, O_DIRECTORY
| O_CLOEXEC
| O_NOFOLLOW
);
6081 static bool cgfs_setup_controllers(void)
6083 if (!cgfs_prepare_mounts())
6086 if (!cgfs_mount_hierarchies()) {
6087 lxcfs_error("%s\n", "Failed to set up private lxcfs cgroup mounts.");
6091 if (!permute_root())
6097 static void __attribute__((constructor
)) lxcfs_init(void)
6099 __do_close_prot_errno
int init_ns
= -EBADF
;
6101 char cwd
[MAXPATHLEN
];
6103 cgroup_ops
= cgroup_init();
6105 log_exit("Failed to initialize cgroup support");
6107 /* Preserve initial namespace. */
6108 init_ns
= preserve_mnt_ns(getpid());
6110 log_exit("Failed to preserve initial mount namespace");
6112 cret
= getcwd(cwd
, MAXPATHLEN
);
6113 log_exit("%s - Could not retrieve current working directory", strerror(errno
));
6115 /* This function calls unshare(CLONE_NEWNS) our initial mount namespace
6116 * to privately mount lxcfs cgroups. */
6117 if (!cgfs_setup_controllers())
6118 log_exit("Failed to setup private cgroup mounts for lxcfs");
6120 if (setns(init_ns
, 0) < 0)
6121 log_exit("%s - Failed to switch back to initial mount namespace", strerror(errno
));
6123 if (!cret
|| chdir(cwd
) < 0)
6124 log_exit("%s - Could not change back to original working directory", strerror(errno
));
6126 if (!init_cpuview())
6127 log_exit("Failed to init CPU view");
6132 static void __attribute__((destructor
)) lxcfs_exit(void)
6134 lxcfs_debug("%s\n", "Running destructor for liblxcfs");
6136 cgroup_exit(cgroup_ops
);