1 /* switch_root.c - Switch from rootfs/initramfs to another filesystem
3 * Copyright 2005 Rob Landley <rob@landley.net>
5 USE_SWITCH_ROOT(NEWTOY(switch_root, "<2c:h", TOYFLAG_SBIN))
11 usage: switch_root [-c /dev/console] NEW_ROOT NEW_INIT...
13 Use from PID 1 under initramfs to free initramfs, chroot to NEW_ROOT,
16 -c Redirect console to device in NEW_ROOT
17 -h Hang instead of exiting on failure (avoids kernel panic)
20 #define FOR_switch_root
30 static int del_node(struct dirtree *node)
32 if (node->st.st_dev == TT.rootdev && dirtree_notdotdot(node)) {
34 if (S_ISDIR(node->st.st_mode)) {
35 if (!node->again) return DIRTREE_COMEAGAIN;
38 unlinkat(dirtree_parentfd(node), node->name, flag);
44 void switch_root_main(void)
46 char *newroot = *toys.optargs, **cmdline = toys.optargs+1;
49 int console = console; // gcc's "may be used" warnings are broken.
51 if (getpid() != 1) error_exit("not pid 1");
53 // Root filesystem we're leaving must be ramfs or tmpfs
54 if (statfs("/", &stfs) ||
55 (stfs.f_type != 0x858458f6 && stfs.f_type != 0x01021994))
57 error_msg("not ramfs");
61 // New directory must be different filesystem instance
62 if (chdir(newroot) || stat(".", &st1) || stat("/", &st2) ||
63 st1.st_dev == st2.st_dev)
65 error_msg("bad newroot '%s'", newroot);
68 TT.rootdev=st2.st_dev;
70 // init program must exist and be an executable file
71 if (stat("init", &st1) || !S_ISREG(st1.st_mode) || !(st1.st_mode&0100)) {
72 error_msg("bad init");
76 if (TT.console && -1 == (console = open(TT.console, O_RDWR))) {
77 perror_msg("bad console '%s'", TT.console);
81 // Ok, enough safety checks: wipe root partition.
82 dirtree_read("/", del_node);
86 for (i=0; i<3; i++) if (console != i) dup2(console, i);
87 if (console>2) close(console);
89 execv(*cmdline, cmdline);
90 perror_msg("Failed to exec '%s'", *cmdline);
92 if (toys.optflags & FLAG_h) for (;;) wait(NULL);