3 * Copyright © 2014-2016 Canonical, Inc
4 * Author: Serge Hallyn <serge.hallyn@ubuntu.com>
6 * See COPYING file for details.
13 #ifndef FUSE_USE_VERSION
14 #define FUSE_USE_VERSION 26
17 #define _FILE_OFFSET_BITS 64
36 #include <linux/magic.h>
37 #include <linux/sched.h>
38 #include <sys/epoll.h>
40 #include <sys/mount.h>
41 #include <sys/param.h>
42 #include <sys/socket.h>
43 #include <sys/syscall.h>
44 #include <sys/sysinfo.h>
49 #include "cgroup_fuse.h"
50 #include "cgroups/cgroup.h"
51 #include "cgroups/cgroup_utils.h"
52 #include "memory_utils.h"
53 #include "proc_cpuview.h"
56 static bool can_use_pidfd
;
58 /* Define pivot_root() if missing from the C library */
59 #ifndef HAVE_PIVOT_ROOT
60 static int pivot_root(const char *new_root
, const char *put_old
)
62 #ifdef __NR_pivot_root
63 return syscall(__NR_pivot_root
, new_root
, put_old
);
70 extern int pivot_root(const char *new_root
, const char *put_old
);
74 * A table caching which pid is init for a pid namespace.
75 * When looking up which pid is init for $qpid, we first
76 * 1. Stat /proc/$qpid/ns/pid.
77 * 2. Check whether the ino_t is in our store.
78 * a. if not, fork a child in qpid's ns to send us
79 * ucred.pid = 1, and read the initpid. Cache
80 * initpid and creation time for /proc/initpid
81 * in a new store entry.
82 * b. if so, verify that /proc/initpid still matches
83 * what we have saved. If not, clear the store
84 * entry and go back to a. If so, return the
87 struct pidns_init_store
{
88 ino_t ino
; /* inode number for /proc/$pid/ns/pid */
89 pid_t initpid
; /* the pid of nit in that ns */
91 long int ctime
; /* the time at which /proc/$initpid was created */
92 struct pidns_init_store
*next
;
96 /* lol - look at how they are allocated in the kernel */
97 #define PIDNS_HASH_SIZE 4096
98 #define HASH(x) ((x) % PIDNS_HASH_SIZE)
100 static struct pidns_init_store
*pidns_hash_table
[PIDNS_HASH_SIZE
];
101 static pthread_mutex_t pidns_store_mutex
= PTHREAD_MUTEX_INITIALIZER
;
103 static void lock_mutex(pthread_mutex_t
*l
)
107 ret
= pthread_mutex_lock(l
);
109 log_exit("%s - returned %d\n", strerror(ret
), ret
);
112 struct cgroup_ops
*cgroup_ops
;
114 static void unlock_mutex(pthread_mutex_t
*l
)
118 ret
= pthread_mutex_unlock(l
);
120 log_exit("%s - returned %d\n", strerror(ret
), ret
);
123 static void store_lock(void)
125 lock_mutex(&pidns_store_mutex
);
128 static void store_unlock(void)
130 unlock_mutex(&pidns_store_mutex
);
135 * <pid-as-str> = INTTYPE_TO_STRLEN(pid_t)
139 #define LXCFS_PROC_PID_LEN \
140 (STRLITERALLEN("/proc/") + INTTYPE_TO_STRLEN(uint64_t) + +1)
142 /* Must be called under store_lock */
143 static bool initpid_still_valid(struct pidns_init_store
*entry
)
147 if (entry
->init_pidfd
>= 0) {
148 if (pidfd_send_signal(entry
->init_pidfd
, 0, NULL
, 0))
152 char path
[LXCFS_PROC_PID_LEN
];
154 snprintf(path
, sizeof(path
), "/proc/%d", entry
->initpid
);
156 if (stat(path
, &st
) || entry
->ctime
!= st
.st_ctime
)
163 /* Must be called under store_lock */
164 static void remove_initpid(struct pidns_init_store
*entry
)
166 struct pidns_init_store
*it
;
169 lxcfs_debug("Removing cached entry for pid %d from init pid cache",
172 ino_hash
= HASH(entry
->ino
);
173 if (pidns_hash_table
[ino_hash
] == entry
) {
174 pidns_hash_table
[ino_hash
] = entry
->next
;
175 close_prot_errno_disarm(entry
->init_pidfd
);
180 it
= pidns_hash_table
[ino_hash
];
182 if (it
->next
== entry
) {
183 it
->next
= entry
->next
;
184 close_prot_errno_disarm(entry
->init_pidfd
);
193 /* Must be called under store_lock */
194 static void prune_initpid_store(void)
196 static long int last_prune
= 0;
197 long int now
, threshold
;
200 last_prune
= time(NULL
);
205 if (now
< last_prune
+ PURGE_SECS
)
208 lxcfs_debug("Pruning init pid cache");
211 threshold
= now
- 2 * PURGE_SECS
;
213 for (int i
= 0; i
< PIDNS_HASH_SIZE
; i
++) {
214 for (struct pidns_init_store
*entry
= pidns_hash_table
[i
], *prev
= NULL
; entry
;) {
215 if (entry
->lastcheck
< threshold
) {
216 struct pidns_init_store
*cur
= entry
;
218 lxcfs_debug("Removed cache entry for pid %d to init pid cache", cur
->initpid
);
221 prev
->next
= entry
->next
;
223 pidns_hash_table
[i
] = entry
->next
;
225 close_prot_errno_disarm(cur
->init_pidfd
);
235 /* Must be called under store_lock */
236 static void save_initpid(struct stat
*sb
, pid_t pid
)
238 __do_free
struct pidns_init_store
*e
= NULL
;
239 __do_close_prot_errno
int pidfd
= -EBADF
;
240 char path
[LXCFS_PROC_PID_LEN
];
241 struct lxcfs_opts
*opts
= fuse_get_context()->private_data
;
245 if (opts
->use_pidfd
&& can_use_pidfd
) {
246 pidfd
= pidfd_open(pid
, 0);
251 snprintf(path
, sizeof(path
), "/proc/%d", pid
);
255 e
= malloc(sizeof(*e
));
261 e
->ctime
= st
.st_ctime
;
262 ino_hash
= HASH(e
->ino
);
263 e
->next
= pidns_hash_table
[ino_hash
];
264 e
->lastcheck
= time(NULL
);
265 e
->init_pidfd
= move_fd(pidfd
);
266 pidns_hash_table
[ino_hash
] = move_ptr(e
);
268 lxcfs_debug("Added cache entry %d for pid %d to init pid cache", ino_hash
, pid
);
272 * Given the stat(2) info for a nsfd pid inode, lookup the init_pid_store
273 * entry for the inode number and creation time. Verify that the init pid
274 * is still valid. If not, remove it. Return the entry if valid, NULL
276 * Must be called under store_lock
278 static struct pidns_init_store
*lookup_verify_initpid(struct stat
*sb
)
280 struct pidns_init_store
*entry
= pidns_hash_table
[HASH(sb
->st_ino
)];
283 if (entry
->ino
== sb
->st_ino
) {
284 if (initpid_still_valid(entry
)) {
285 entry
->lastcheck
= time(NULL
);
289 remove_initpid(entry
);
298 static int send_creds_clone_wrapper(void *arg
)
302 int sock
= *(int *)arg
;
304 /* we are the child */
309 if (send_creds(sock
, &cred
, v
, true) != SEND_CREDS_OK
)
315 * clone a task which switches to @task's namespace and writes '1'.
316 * over a unix sock so we can read the task's reaper's pid in our
319 * Note: glibc's fork() does not respect pidns, which can lead to failed
320 * assertions inside glibc (and thus failed forks) if the child's pid in
321 * the pidns and the parent pid outside are identical. Using clone prevents
324 static void write_task_init_pid_exit(int sock
, pid_t target
)
329 size_t stack_size
= sysconf(_SC_PAGESIZE
);
330 void *stack
= alloca(stack_size
);
332 ret
= snprintf(fnam
, sizeof(fnam
), "/proc/%d/ns/pid", (int)target
);
333 if (ret
< 0 || ret
>= sizeof(fnam
))
336 fd
= open(fnam
, O_RDONLY
);
338 perror("write_task_init_pid_exit open of ns/pid");
342 perror("write_task_init_pid_exit setns 1");
346 pid
= clone(send_creds_clone_wrapper
, stack
+ stack_size
, SIGCHLD
, &sock
);
350 if (!wait_for_pid(pid
))
356 static pid_t
get_init_pid_for_task(pid_t task
)
364 if (socketpair(AF_UNIX
, SOCK_DGRAM
, 0, sock
) < 0) {
365 perror("socketpair");
374 write_task_init_pid_exit(sock
[0], task
);
378 if (!recv_creds(sock
[1], &cred
, &v
))
390 #define LXCFS_PROC_PID_NS_LEN \
391 (STRLITERALLEN("/proc/") + INTTYPE_TO_STRLEN(uint64_t) + \
392 STRLITERALLEN("/ns/pid") + 1)
394 pid_t
lookup_initpid_in_store(pid_t pid
)
397 char path
[LXCFS_PROC_PID_NS_LEN
];
399 struct pidns_init_store
*entry
;
401 snprintf(path
, sizeof(path
), "/proc/%d/ns/pid", pid
);
407 entry
= lookup_verify_initpid(&st
);
409 answer
= entry
->initpid
;
413 answer
= get_init_pid_for_task(pid
);
415 save_initpid(&st
, answer
);
419 * Prune at the end in case we're returning the value we were about to
422 prune_initpid_store();
430 * Functions needed to setup cgroups in the __constructor__.
433 static bool umount_if_mounted(void)
435 if (umount2(BASEDIR
, MNT_DETACH
) < 0 && errno
!= EINVAL
) {
436 lxcfs_error("Failed to unmount %s: %s.\n", BASEDIR
, strerror(errno
));
442 /* __typeof__ should be safe to use with all compilers. */
443 typedef __typeof__(((struct statfs
*)NULL
)->f_type
) fs_type_magic
;
444 static bool has_fs_type(const struct statfs
*fs
, fs_type_magic magic_val
)
446 return (fs
->f_type
== (fs_type_magic
)magic_val
);
450 * looking at fs/proc_namespace.c, it appears we can
451 * actually expect the rootfs entry to very specifically contain
452 * " - rootfs rootfs "
453 * IIUC, so long as we've chrooted so that rootfs is not our root,
454 * the rootfs entry should always be skipped in mountinfo contents.
456 static bool is_on_ramfs(void)
464 f
= fopen("/proc/self/mountinfo", "r");
468 while (getline(&line
, &len
, f
) != -1) {
469 for (p
= line
, i
= 0; p
&& i
< 4; i
++)
470 p
= strchr(p
+ 1, ' ');
473 p2
= strchr(p
+ 1, ' ');
477 if (strcmp(p
+ 1, "/") == 0) {
478 // this is '/'. is it the ramfs?
479 p
= strchr(p2
+ 1, '-');
480 if (p
&& strncmp(p
, "- rootfs rootfs ", 16) == 0) {
492 static int pivot_enter()
494 int ret
= -1, oldroot
= -1, newroot
= -1;
496 oldroot
= open("/", O_DIRECTORY
| O_RDONLY
);
498 lxcfs_error("%s\n", "Failed to open old root for fchdir.");
502 newroot
= open(ROOTDIR
, O_DIRECTORY
| O_RDONLY
);
504 lxcfs_error("%s\n", "Failed to open new root for fchdir.");
508 /* change into new root fs */
509 if (fchdir(newroot
) < 0) {
510 lxcfs_error("Failed to change directory to new rootfs: %s.\n", ROOTDIR
);
514 /* pivot_root into our new root fs */
515 if (pivot_root(".", ".") < 0) {
516 lxcfs_error("pivot_root() syscall failed: %s.\n", strerror(errno
));
521 * At this point the old-root is mounted on top of our new-root.
522 * To unmounted it we must not be chdir'd into it, so escape back
525 if (fchdir(oldroot
) < 0) {
526 lxcfs_error("%s\n", "Failed to enter old root.");
530 if (umount2(".", MNT_DETACH
) < 0) {
531 lxcfs_error("%s\n", "Failed to detach old root.");
535 if (fchdir(newroot
) < 0) {
536 lxcfs_error("%s\n", "Failed to re-enter new root.");
551 static int chroot_enter()
553 if (mount(ROOTDIR
, "/", NULL
, MS_REC
| MS_BIND
, NULL
)) {
554 lxcfs_error("Failed to recursively bind-mount %s into /.", ROOTDIR
);
558 if (chroot(".") < 0) {
559 lxcfs_error("Call to chroot() failed: %s.\n", strerror(errno
));
563 if (chdir("/") < 0) {
564 lxcfs_error("Failed to change directory: %s.\n", strerror(errno
));
571 static int permute_and_enter(void)
575 if (statfs("/", &sb
) < 0) {
576 lxcfs_error("%s\n", "Could not stat / mountpoint.");
580 /* has_fs_type() is not reliable. When the ramfs is a tmpfs it will
581 * likely report TMPFS_MAGIC. Hence, when it reports no we still check
582 * /proc/1/mountinfo. */
583 if (has_fs_type(&sb
, RAMFS_MAGIC
) || is_on_ramfs())
584 return chroot_enter();
586 if (pivot_enter() < 0) {
587 lxcfs_error("%s\n", "Could not perform pivot root.");
594 /* Prepare our new clean root. */
595 static int permute_prepare(void)
597 if (mkdir(ROOTDIR
, 0700) < 0 && errno
!= EEXIST
) {
598 lxcfs_error("%s\n", "Failed to create directory for new root.");
602 if (mount("/", ROOTDIR
, NULL
, MS_BIND
, 0) < 0) {
603 lxcfs_error("Failed to bind-mount / for new root: %s.\n", strerror(errno
));
607 if (mount(RUNTIME_PATH
, ROOTDIR RUNTIME_PATH
, NULL
, MS_BIND
, 0) < 0) {
608 lxcfs_error("Failed to bind-mount /run into new root: %s.\n", strerror(errno
));
612 if (mount(BASEDIR
, ROOTDIR BASEDIR
, NULL
, MS_REC
| MS_MOVE
, 0) < 0) {
613 printf("Failed to move " BASEDIR
" into new root: %s.\n", strerror(errno
));
620 /* Calls chroot() on ramfs, pivot_root() in all other cases. */
621 static bool permute_root(void)
623 /* Prepare new root. */
624 if (permute_prepare() < 0)
627 /* Pivot into new root. */
628 if (permute_and_enter() < 0)
634 static bool cgfs_prepare_mounts(void)
636 if (!mkdir_p(BASEDIR
, 0700)) {
637 lxcfs_error("%s\n", "Failed to create lxcfs cgroup mountpoint.");
641 if (!umount_if_mounted()) {
642 lxcfs_error("%s\n", "Failed to clean up old lxcfs cgroup mountpoint.");
646 if (unshare(CLONE_NEWNS
) < 0) {
647 lxcfs_error("Failed to unshare mount namespace: %s.\n", strerror(errno
));
651 cgroup_ops
->mntns_fd
= preserve_ns(getpid(), "mnt");
652 if (cgroup_ops
->mntns_fd
< 0) {
653 lxcfs_error("Failed to preserve mount namespace: %s.\n", strerror(errno
));
657 if (mount(NULL
, "/", NULL
, MS_REC
| MS_PRIVATE
, 0) < 0) {
658 lxcfs_error("Failed to remount / private: %s.\n", strerror(errno
));
662 if (mount("tmpfs", BASEDIR
, "tmpfs", 0, "size=100000,mode=700") < 0) {
663 lxcfs_error("%s\n", "Failed to mount tmpfs over lxcfs cgroup mountpoint.");
670 static bool cgfs_mount_hierarchies(void)
672 if (!mkdir_p(BASEDIR DEFAULT_CGROUP_MOUNTPOINT
, 0755))
675 if (!cgroup_ops
->mount(cgroup_ops
, BASEDIR
))
678 for (struct hierarchy
**h
= cgroup_ops
->hierarchies
; h
&& *h
; h
++) {
679 __do_free
char *path
= must_make_path(BASEDIR
, (*h
)->mountpoint
, NULL
);
680 (*h
)->fd
= open(path
, O_DIRECTORY
| O_CLOEXEC
| O_NOFOLLOW
);
688 static bool cgfs_setup_controllers(void)
690 if (!cgfs_prepare_mounts())
693 if (!cgfs_mount_hierarchies()) {
694 lxcfs_error("%s\n", "Failed to set up private lxcfs cgroup mounts.");
704 static void __attribute__((constructor
)) lxcfs_init(void)
706 __do_close_prot_errno
int init_ns
= -EBADF
, pidfd
= -EBADF
;
710 char cwd
[MAXPATHLEN
];
712 cgroup_ops
= cgroup_init();
714 log_exit("Failed to initialize cgroup support");
716 /* Preserve initial namespace. */
718 init_ns
= preserve_ns(pid
, "mnt");
720 log_exit("Failed to preserve initial mount namespace");
722 cret
= getcwd(cwd
, MAXPATHLEN
);
724 log_exit("%s - Could not retrieve current working directory", strerror(errno
));
726 /* This function calls unshare(CLONE_NEWNS) our initial mount namespace
727 * to privately mount lxcfs cgroups. */
728 if (!cgfs_setup_controllers())
729 log_exit("Failed to setup private cgroup mounts for lxcfs");
731 if (setns(init_ns
, 0) < 0)
732 log_exit("%s - Failed to switch back to initial mount namespace", strerror(errno
));
734 if (!cret
|| chdir(cwd
) < 0)
735 log_exit("%s - Could not change back to original working directory", strerror(errno
));
738 log_exit("Failed to init CPU view");
740 fprintf(stderr
, "mount namespace: %d\n", cgroup_ops
->mntns_fd
);
741 fprintf(stderr
, "hierarchies:\n");
743 for (struct hierarchy
**h
= cgroup_ops
->hierarchies
; h
&& *h
; h
++, i
++) {
744 __do_free
char *controllers
= lxc_string_join(",", (const char **)(*h
)->controllers
, false);
745 fprintf(stderr
, " %2d: fd: %3d: %s\n", i
, (*h
)->fd
, controllers
?: "");
748 pidfd
= pidfd_open(pid
, 0);
749 if (pidfd
>= 0 && pidfd_send_signal(pidfd
, 0, NULL
, 0) == 0) {
750 can_use_pidfd
= true;
751 lxcfs_error("Kernel supports pidfds");
755 static void __attribute__((destructor
)) lxcfs_exit(void)
757 lxcfs_debug("%s\n", "Running destructor for liblxcfs");
759 cgroup_exit(cgroup_ops
);