]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/vfs_mountroot.c
zfs: merge openzfs/zfs@eb62221ff (zfs-2.1-release) into stable/13
[FreeBSD/FreeBSD.git] / sys / kern / vfs_mountroot.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 2010 Marcel Moolenaar
5  * Copyright (c) 1999-2004 Poul-Henning Kamp
6  * Copyright (c) 1999 Michael Smith
7  * Copyright (c) 1989, 1993
8  *      The Regents of the University of California.  All rights reserved.
9  * (c) UNIX System Laboratories, Inc.
10  * All or some portions of this file are derived from material licensed
11  * to the University of California by American Telephone and Telegraph
12  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
13  * the permission of UNIX System Laboratories, Inc.
14  *
15  * Redistribution and use in source and binary forms, with or without
16  * modification, are permitted provided that the following conditions
17  * are met:
18  * 1. Redistributions of source code must retain the above copyright
19  *    notice, this list of conditions and the following disclaimer.
20  * 2. Redistributions in binary form must reproduce the above copyright
21  *    notice, this list of conditions and the following disclaimer in the
22  *    documentation and/or other materials provided with the distribution.
23  * 3. Neither the name of the University nor the names of its contributors
24  *    may be used to endorse or promote products derived from this software
25  *    without specific prior written permission.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
28  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
31  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37  * SUCH DAMAGE.
38  */
39
40 #include "opt_rootdevname.h"
41
42 #include <sys/cdefs.h>
43 #include <sys/param.h>
44 #include <sys/conf.h>
45 #include <sys/cons.h>
46 #include <sys/eventhandler.h>
47 #include <sys/fcntl.h>
48 #include <sys/jail.h>
49 #include <sys/kernel.h>
50 #include <sys/malloc.h>
51 #include <sys/mdioctl.h>
52 #include <sys/mount.h>
53 #include <sys/mutex.h>
54 #include <sys/namei.h>
55 #include <sys/priv.h>
56 #include <sys/proc.h>
57 #include <sys/filedesc.h>
58 #include <sys/reboot.h>
59 #include <sys/sbuf.h>
60 #include <sys/stat.h>
61 #include <sys/syscallsubr.h>
62 #include <sys/sysproto.h>
63 #include <sys/sx.h>
64 #include <sys/sysctl.h>
65 #include <sys/systm.h>
66 #include <sys/vnode.h>
67
68 #include <geom/geom.h>
69
70 /*
71  * The root filesystem is detailed in the kernel environment variable
72  * vfs.root.mountfrom, which is expected to be in the general format
73  *
74  * <vfsname>:[<path>][  <vfsname>:[<path>] ...]
75  * vfsname   := the name of a VFS known to the kernel and capable
76  *              of being mounted as root
77  * path      := disk device name or other data used by the filesystem
78  *              to locate its physical store
79  *
80  * If the environment variable vfs.root.mountfrom is a space separated list,
81  * each list element is tried in turn and the root filesystem will be mounted
82  * from the first one that succeeds.
83  *
84  * The environment variable vfs.root.mountfrom.options is a comma delimited
85  * set of string mount options.  These mount options must be parseable
86  * by nmount() in the kernel.
87  */
88
89 static int parse_mount(char **);
90 static struct mntarg *parse_mountroot_options(struct mntarg *, const char *);
91 static int sysctl_vfs_root_mount_hold(SYSCTL_HANDLER_ARGS);
92 static void vfs_mountroot_wait(void);
93 static int vfs_mountroot_wait_if_neccessary(const char *fs, const char *dev);
94
95 /*
96  * The vnode of the system's root (/ in the filesystem, without chroot
97  * active.)
98  */
99 struct vnode *rootvnode;
100
101 /*
102  * Mount of the system's /dev.
103  */
104 struct mount *rootdevmp;
105
106 char *rootdevnames[2] = {NULL, NULL};
107
108 struct mtx root_holds_mtx;
109 MTX_SYSINIT(root_holds, &root_holds_mtx, "root_holds", MTX_DEF);
110
111 static TAILQ_HEAD(, root_hold_token)    root_holds =
112     TAILQ_HEAD_INITIALIZER(root_holds);
113
114 enum action {
115         A_CONTINUE,
116         A_PANIC,
117         A_REBOOT,
118         A_RETRY
119 };
120
121 enum rh_flags {
122         RH_FREE,
123         RH_ALLOC,
124         RH_ARG,
125 };
126
127 static enum action root_mount_onfail = A_CONTINUE;
128
129 static int root_mount_mddev;
130 static int root_mount_complete;
131
132 /* By default wait up to 3 seconds for devices to appear. */
133 static int root_mount_timeout = 3;
134 TUNABLE_INT("vfs.mountroot.timeout", &root_mount_timeout);
135
136 static int root_mount_always_wait = 0;
137 SYSCTL_INT(_vfs, OID_AUTO, root_mount_always_wait, CTLFLAG_RDTUN,
138     &root_mount_always_wait, 0,
139     "Wait for root mount holds even if the root device already exists");
140
141 SYSCTL_PROC(_vfs, OID_AUTO, root_mount_hold,
142     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
143     NULL, 0, sysctl_vfs_root_mount_hold, "A",
144     "List of root mount hold tokens");
145
146 static int
147 sysctl_vfs_root_mount_hold(SYSCTL_HANDLER_ARGS)
148 {
149         struct sbuf sb;
150         struct root_hold_token *h;
151         int error;
152
153         sbuf_new(&sb, NULL, 256, SBUF_AUTOEXTEND | SBUF_INCLUDENUL);
154
155         mtx_lock(&root_holds_mtx);
156         TAILQ_FOREACH(h, &root_holds, list) {
157                 if (h != TAILQ_FIRST(&root_holds))
158                         sbuf_putc(&sb, ' ');
159                 sbuf_printf(&sb, "%s", h->who);
160         }
161         mtx_unlock(&root_holds_mtx);
162
163         error = sbuf_finish(&sb);
164         if (error == 0)
165                 error = SYSCTL_OUT(req, sbuf_data(&sb), sbuf_len(&sb));
166         sbuf_delete(&sb);
167         return (error);
168 }
169
170 struct root_hold_token *
171 root_mount_hold(const char *identifier)
172 {
173         struct root_hold_token *h;
174
175         h = malloc(sizeof *h, M_DEVBUF, M_ZERO | M_WAITOK);
176         h->flags = RH_ALLOC;
177         h->who = identifier;
178         mtx_lock(&root_holds_mtx);
179         TSHOLD("root mount");
180         TAILQ_INSERT_TAIL(&root_holds, h, list);
181         mtx_unlock(&root_holds_mtx);
182         return (h);
183 }
184
185 void
186 root_mount_hold_token(const char *identifier, struct root_hold_token *h)
187 {
188 #ifdef INVARIANTS
189         struct root_hold_token *t;
190 #endif
191
192         h->flags = RH_ARG;
193         h->who = identifier;
194         mtx_lock(&root_holds_mtx);
195 #ifdef INVARIANTS
196         TAILQ_FOREACH(t, &root_holds, list) {
197                 if (t == h) {
198                         panic("Duplicate mount hold by '%s' on %p",
199                             identifier, h);
200                 }
201         }
202 #endif
203         TSHOLD("root mount");
204         TAILQ_INSERT_TAIL(&root_holds, h, list);
205         mtx_unlock(&root_holds_mtx);
206 }
207
208 void
209 root_mount_rel(struct root_hold_token *h)
210 {
211
212         if (h == NULL || h->flags == RH_FREE)
213                 return;
214
215         mtx_lock(&root_holds_mtx);
216         TAILQ_REMOVE(&root_holds, h, list);
217         TSRELEASE("root mount");
218         wakeup(&root_holds);
219         mtx_unlock(&root_holds_mtx);
220         if (h->flags == RH_ALLOC) {
221                 free(h, M_DEVBUF);
222         } else
223                 h->flags = RH_FREE;
224 }
225
226 int
227 root_mounted(void)
228 {
229
230         /* No mutex is acquired here because int stores are atomic. */
231         return (root_mount_complete);
232 }
233
234 static void
235 set_rootvnode(void)
236 {
237
238         if (VFS_ROOT(TAILQ_FIRST(&mountlist), LK_EXCLUSIVE, &rootvnode))
239                 panic("set_rootvnode: Cannot find root vnode");
240
241         VOP_UNLOCK(rootvnode);
242
243         pwd_set_rootvnode();
244 }
245
246 static int
247 vfs_mountroot_devfs(struct thread *td, struct mount **mpp)
248 {
249         struct vfsoptlist *opts;
250         struct vfsconf *vfsp;
251         struct mount *mp;
252         int error;
253
254         *mpp = NULL;
255
256         if (rootdevmp != NULL) {
257                 /*
258                  * Already have /dev; this happens during rerooting.
259                  */
260                 error = vfs_busy(rootdevmp, 0);
261                 if (error != 0)
262                         return (error);
263                 *mpp = rootdevmp;
264         } else {
265                 vfsp = vfs_byname("devfs");
266                 KASSERT(vfsp != NULL, ("Could not find devfs by name"));
267                 if (vfsp == NULL)
268                         return (ENOENT);
269
270                 mp = vfs_mount_alloc(NULLVP, vfsp, "/dev", td->td_ucred);
271
272                 error = VFS_MOUNT(mp);
273                 KASSERT(error == 0, ("VFS_MOUNT(devfs) failed %d", error));
274                 if (error)
275                         return (error);
276
277                 error = VFS_STATFS(mp, &mp->mnt_stat);
278                 KASSERT(error == 0, ("VFS_STATFS(devfs) failed %d", error));
279                 if (error)
280                         return (error);
281
282                 opts = malloc(sizeof(struct vfsoptlist), M_MOUNT, M_WAITOK);
283                 TAILQ_INIT(opts);
284                 mp->mnt_opt = opts;
285
286                 mtx_lock(&mountlist_mtx);
287                 TAILQ_INSERT_HEAD(&mountlist, mp, mnt_list);
288                 mtx_unlock(&mountlist_mtx);
289
290                 *mpp = mp;
291                 rootdevmp = mp;
292                 vfs_op_exit(mp);
293         }
294
295         set_rootvnode();
296
297         error = kern_symlinkat(td, "/", AT_FDCWD, "dev", UIO_SYSSPACE);
298         if (error)
299                 printf("kern_symlink /dev -> / returns %d\n", error);
300
301         return (error);
302 }
303
304 static void
305 vfs_mountroot_shuffle(struct thread *td, struct mount *mpdevfs)
306 {
307         struct nameidata nd;
308         struct mount *mporoot, *mpnroot;
309         struct vnode *vp, *vporoot, *vpdevfs;
310         char *fspath;
311         int error;
312
313         mpnroot = TAILQ_NEXT(mpdevfs, mnt_list);
314
315         /* Shuffle the mountlist. */
316         mtx_lock(&mountlist_mtx);
317         mporoot = TAILQ_FIRST(&mountlist);
318         TAILQ_REMOVE(&mountlist, mpdevfs, mnt_list);
319         if (mporoot != mpdevfs) {
320                 TAILQ_REMOVE(&mountlist, mpnroot, mnt_list);
321                 TAILQ_INSERT_HEAD(&mountlist, mpnroot, mnt_list);
322         }
323         TAILQ_INSERT_TAIL(&mountlist, mpdevfs, mnt_list);
324         mtx_unlock(&mountlist_mtx);
325
326         cache_purgevfs(mporoot);
327         if (mporoot != mpdevfs)
328                 cache_purgevfs(mpdevfs);
329
330         if (VFS_ROOT(mporoot, LK_EXCLUSIVE, &vporoot))
331                 panic("vfs_mountroot_shuffle: Cannot find root vnode");
332
333         VI_LOCK(vporoot);
334         vporoot->v_iflag &= ~VI_MOUNT;
335         vn_irflag_unset_locked(vporoot, VIRF_MOUNTPOINT);
336         vporoot->v_mountedhere = NULL;
337         VI_UNLOCK(vporoot);
338         mporoot->mnt_flag &= ~MNT_ROOTFS;
339         mporoot->mnt_vnodecovered = NULL;
340         vput(vporoot);
341
342         /* Set up the new rootvnode, and purge the cache */
343         mpnroot->mnt_vnodecovered = NULL;
344         set_rootvnode();
345         cache_purgevfs(rootvnode->v_mount);
346
347         if (mporoot != mpdevfs) {
348                 /* Remount old root under /.mount or /mnt */
349                 fspath = "/.mount";
350                 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE,
351                     fspath, td);
352                 error = namei(&nd);
353                 if (error) {
354                         NDFREE(&nd, NDF_ONLY_PNBUF);
355                         fspath = "/mnt";
356                         NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE,
357                             fspath, td);
358                         error = namei(&nd);
359                 }
360                 if (!error) {
361                         vp = nd.ni_vp;
362                         error = (vp->v_type == VDIR) ? 0 : ENOTDIR;
363                         if (!error)
364                                 error = vinvalbuf(vp, V_SAVE, 0, 0);
365                         if (!error) {
366                                 cache_purge(vp);
367                                 VI_LOCK(vp);
368                                 mporoot->mnt_vnodecovered = vp;
369                                 vn_irflag_set_locked(vp, VIRF_MOUNTPOINT);
370                                 vp->v_mountedhere = mporoot;
371                                 strlcpy(mporoot->mnt_stat.f_mntonname,
372                                     fspath, MNAMELEN);
373                                 VI_UNLOCK(vp);
374                                 VOP_UNLOCK(vp);
375                         } else
376                                 vput(vp);
377                 }
378                 NDFREE(&nd, NDF_ONLY_PNBUF);
379
380                 if (error)
381                         printf("mountroot: unable to remount previous root "
382                             "under /.mount or /mnt (error %d)\n", error);
383         }
384
385         /* Remount devfs under /dev */
386         NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE, "/dev", td);
387         error = namei(&nd);
388         if (!error) {
389                 vp = nd.ni_vp;
390                 error = (vp->v_type == VDIR) ? 0 : ENOTDIR;
391                 if (!error)
392                         error = vinvalbuf(vp, V_SAVE, 0, 0);
393                 if (!error) {
394                         vpdevfs = mpdevfs->mnt_vnodecovered;
395                         if (vpdevfs != NULL) {
396                                 cache_purge(vpdevfs);
397                                 VI_LOCK(vpdevfs);
398                                 vn_irflag_unset_locked(vpdevfs, VIRF_MOUNTPOINT);
399                                 vpdevfs->v_mountedhere = NULL;
400                                 VI_UNLOCK(vpdevfs);
401                                 vrele(vpdevfs);
402                         }
403                         VI_LOCK(vp);
404                         mpdevfs->mnt_vnodecovered = vp;
405                         vn_irflag_set_locked(vp, VIRF_MOUNTPOINT);
406                         vp->v_mountedhere = mpdevfs;
407                         VI_UNLOCK(vp);
408                         VOP_UNLOCK(vp);
409                 } else
410                         vput(vp);
411         }
412         if (error)
413                 printf("mountroot: unable to remount devfs under /dev "
414                     "(error %d)\n", error);
415         NDFREE(&nd, NDF_ONLY_PNBUF);
416
417         if (mporoot == mpdevfs) {
418                 vfs_unbusy(mpdevfs);
419                 /* Unlink the no longer needed /dev/dev -> / symlink */
420                 error = kern_funlinkat(td, AT_FDCWD, "/dev/dev", FD_NONE,
421                     UIO_SYSSPACE, 0, 0);
422                 if (error)
423                         printf("mountroot: unable to unlink /dev/dev "
424                             "(error %d)\n", error);
425         }
426 }
427
428 /*
429  * Configuration parser.
430  */
431
432 /* Parser character classes. */
433 #define CC_WHITESPACE           -1
434 #define CC_NONWHITESPACE        -2
435
436 /* Parse errors. */
437 #define PE_EOF                  -1
438 #define PE_EOL                  -2
439
440 static __inline int
441 parse_peek(char **conf)
442 {
443
444         return (**conf);
445 }
446
447 static __inline void
448 parse_poke(char **conf, int c)
449 {
450
451         **conf = c;
452 }
453
454 static __inline void
455 parse_advance(char **conf)
456 {
457
458         (*conf)++;
459 }
460
461 static int
462 parse_skipto(char **conf, int mc)
463 {
464         int c, match;
465
466         while (1) {
467                 c = parse_peek(conf);
468                 if (c == 0)
469                         return (PE_EOF);
470                 switch (mc) {
471                 case CC_WHITESPACE:
472                         match = (c == ' ' || c == '\t' || c == '\n') ? 1 : 0;
473                         break;
474                 case CC_NONWHITESPACE:
475                         if (c == '\n')
476                                 return (PE_EOL);
477                         match = (c != ' ' && c != '\t') ? 1 : 0;
478                         break;
479                 default:
480                         match = (c == mc) ? 1 : 0;
481                         break;
482                 }
483                 if (match)
484                         break;
485                 parse_advance(conf);
486         }
487         return (0);
488 }
489
490 static int
491 parse_token(char **conf, char **tok)
492 {
493         char *p;
494         size_t len;
495         int error;
496
497         *tok = NULL;
498         error = parse_skipto(conf, CC_NONWHITESPACE);
499         if (error)
500                 return (error);
501         p = *conf;
502         error = parse_skipto(conf, CC_WHITESPACE);
503         len = *conf - p;
504         *tok = malloc(len + 1, M_TEMP, M_WAITOK | M_ZERO);
505         bcopy(p, *tok, len);
506         return (0);
507 }
508
509 static void
510 parse_dir_ask_printenv(const char *var)
511 {
512         char *val;
513
514         val = kern_getenv(var);
515         if (val != NULL) {
516                 printf("  %s=%s\n", var, val);
517                 freeenv(val);
518         }
519 }
520
521 static int
522 parse_dir_ask(char **conf)
523 {
524         char name[80];
525         char *mnt;
526         int error;
527
528         vfs_mountroot_wait();
529
530         printf("\nLoader variables:\n");
531         parse_dir_ask_printenv("vfs.root.mountfrom");
532         parse_dir_ask_printenv("vfs.root.mountfrom.options");
533
534         printf("\nManual root filesystem specification:\n");
535         printf("  <fstype>:<device> [options]\n");
536         printf("      Mount <device> using filesystem <fstype>\n");
537         printf("      and with the specified (optional) option list.\n");
538         printf("\n");
539         printf("    eg. ufs:/dev/da0s1a\n");
540         printf("        zfs:zroot/ROOT/default\n");
541         printf("        cd9660:/dev/cd0 ro\n");
542         printf("          (which is equivalent to: ");
543         printf("mount -t cd9660 -o ro /dev/cd0 /)\n");
544         printf("\n");
545         printf("  ?               List valid disk boot devices\n");
546         printf("  .               Yield 1 second (for background tasks)\n");
547         printf("  <empty line>    Abort manual input\n");
548
549         do {
550                 error = EINVAL;
551                 printf("\nmountroot> ");
552                 cngets(name, sizeof(name), GETS_ECHO);
553                 if (name[0] == '\0')
554                         break;
555                 if (name[0] == '?' && name[1] == '\0') {
556                         printf("\nList of GEOM managed disk devices:\n  ");
557                         g_dev_print();
558                         continue;
559                 }
560                 if (name[0] == '.' && name[1] == '\0') {
561                         pause("rmask", hz);
562                         continue;
563                 }
564                 mnt = name;
565                 error = parse_mount(&mnt);
566                 if (error == -1)
567                         printf("Invalid file system specification.\n");
568         } while (error != 0);
569
570         return (error);
571 }
572
573 static int
574 parse_dir_md(char **conf)
575 {
576         struct stat sb;
577         struct thread *td;
578         struct md_ioctl *mdio;
579         char *path, *tok;
580         int error, fd, len;
581
582         td = curthread;
583         fd = -1;
584
585         error = parse_token(conf, &tok);
586         if (error)
587                 return (error);
588
589         len = strlen(tok);
590         mdio = malloc(sizeof(*mdio) + len + 1, M_TEMP, M_WAITOK | M_ZERO);
591         path = (void *)(mdio + 1);
592         bcopy(tok, path, len);
593         free(tok, M_TEMP);
594
595         /* Get file status. */
596         error = kern_statat(td, 0, AT_FDCWD, path, UIO_SYSSPACE, &sb);
597         if (error)
598                 goto out;
599
600         /* Open /dev/mdctl so that we can attach/detach. */
601         error = kern_openat(td, AT_FDCWD, "/dev/" MDCTL_NAME, UIO_SYSSPACE,
602             O_RDWR, 0);
603         if (error)
604                 goto out;
605
606         fd = td->td_retval[0];
607         mdio->md_version = MDIOVERSION;
608         mdio->md_type = MD_VNODE;
609
610         if (root_mount_mddev != -1) {
611                 mdio->md_unit = root_mount_mddev;
612                 (void)kern_ioctl(td, fd, MDIOCDETACH, (void *)mdio);
613                 /* Ignore errors. We don't care. */
614                 root_mount_mddev = -1;
615         }
616
617         mdio->md_file = (void *)(mdio + 1);
618         mdio->md_options = MD_AUTOUNIT | MD_READONLY;
619         mdio->md_mediasize = sb.st_size;
620         mdio->md_unit = 0;
621         error = kern_ioctl(td, fd, MDIOCATTACH, (void *)mdio);
622         if (error)
623                 goto out;
624
625         if (mdio->md_unit > 9) {
626                 printf("rootmount: too many md units\n");
627                 mdio->md_file = NULL;
628                 mdio->md_options = 0;
629                 mdio->md_mediasize = 0;
630                 error = kern_ioctl(td, fd, MDIOCDETACH, (void *)mdio);
631                 /* Ignore errors. We don't care. */
632                 error = ERANGE;
633                 goto out;
634         }
635
636         root_mount_mddev = mdio->md_unit;
637         printf(MD_NAME "%u attached to %s\n", root_mount_mddev, mdio->md_file);
638
639  out:
640         if (fd >= 0)
641                 (void)kern_close(td, fd);
642         free(mdio, M_TEMP);
643         return (error);
644 }
645
646 static int
647 parse_dir_onfail(char **conf)
648 {
649         char *action;
650         int error;
651
652         error = parse_token(conf, &action);
653         if (error)
654                 return (error);
655
656         if (!strcmp(action, "continue"))
657                 root_mount_onfail = A_CONTINUE;
658         else if (!strcmp(action, "panic"))
659                 root_mount_onfail = A_PANIC;
660         else if (!strcmp(action, "reboot"))
661                 root_mount_onfail = A_REBOOT;
662         else if (!strcmp(action, "retry"))
663                 root_mount_onfail = A_RETRY;
664         else {
665                 printf("rootmount: %s: unknown action\n", action);
666                 error = EINVAL;
667         }
668
669         free(action, M_TEMP);
670         return (0);
671 }
672
673 static int
674 parse_dir_timeout(char **conf)
675 {
676         char *tok, *endtok;
677         long secs;
678         int error;
679
680         error = parse_token(conf, &tok);
681         if (error)
682                 return (error);
683
684         secs = strtol(tok, &endtok, 0);
685         error = (secs < 0 || *endtok != '\0') ? EINVAL : 0;
686         if (!error)
687                 root_mount_timeout = secs;
688         free(tok, M_TEMP);
689         return (error);
690 }
691
692 static int
693 parse_directive(char **conf)
694 {
695         char *dir;
696         int error;
697
698         error = parse_token(conf, &dir);
699         if (error)
700                 return (error);
701
702         if (strcmp(dir, ".ask") == 0)
703                 error = parse_dir_ask(conf);
704         else if (strcmp(dir, ".md") == 0)
705                 error = parse_dir_md(conf);
706         else if (strcmp(dir, ".onfail") == 0)
707                 error = parse_dir_onfail(conf);
708         else if (strcmp(dir, ".timeout") == 0)
709                 error = parse_dir_timeout(conf);
710         else {
711                 printf("mountroot: invalid directive `%s'\n", dir);
712                 /* Ignore the rest of the line. */
713                 (void)parse_skipto(conf, '\n');
714                 error = EINVAL;
715         }
716         free(dir, M_TEMP);
717         return (error);
718 }
719
720 static int
721 parse_mount_dev_present(const char *dev)
722 {
723         struct nameidata nd;
724         int error;
725
726         NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE, dev, curthread);
727         error = namei(&nd);
728         if (!error)
729                 vput(nd.ni_vp);
730         NDFREE(&nd, NDF_ONLY_PNBUF);
731         return (error != 0) ? 0 : 1;
732 }
733
734 #define ERRMSGL 255
735 static int
736 parse_mount(char **conf)
737 {
738         char *errmsg;
739         struct mntarg *ma;
740         char *dev, *fs, *opts, *tok;
741         int delay, error, timeout;
742
743         error = parse_token(conf, &tok);
744         if (error)
745                 return (error);
746         fs = tok;
747         error = parse_skipto(&tok, ':');
748         if (error) {
749                 free(fs, M_TEMP);
750                 return (error);
751         }
752         parse_poke(&tok, '\0');
753         parse_advance(&tok);
754         dev = tok;
755
756         if (root_mount_mddev != -1) {
757                 /* Handle substitution for the md unit number. */
758                 tok = strstr(dev, "md#");
759                 if (tok != NULL)
760                         tok[2] = '0' + root_mount_mddev;
761         }
762
763         /* Parse options. */
764         error = parse_token(conf, &tok);
765         opts = (error == 0) ? tok : NULL;
766
767         printf("Trying to mount root from %s:%s [%s]...\n", fs, dev,
768             (opts != NULL) ? opts : "");
769
770         errmsg = malloc(ERRMSGL, M_TEMP, M_WAITOK | M_ZERO);
771
772         if (vfs_byname(fs) == NULL) {
773                 strlcpy(errmsg, "unknown file system", ERRMSGL);
774                 error = ENOENT;
775                 goto out;
776         }
777
778         error = vfs_mountroot_wait_if_neccessary(fs, dev);
779         if (error != 0)
780                 goto out;
781
782         delay = hz / 10;
783         timeout = root_mount_timeout * hz;
784
785         for (;;) {
786                 ma = NULL;
787                 ma = mount_arg(ma, "fstype", fs, -1);
788                 ma = mount_arg(ma, "fspath", "/", -1);
789                 ma = mount_arg(ma, "from", dev, -1);
790                 ma = mount_arg(ma, "errmsg", errmsg, ERRMSGL);
791                 ma = mount_arg(ma, "ro", NULL, 0);
792                 ma = parse_mountroot_options(ma, opts);
793
794                 error = kernel_mount(ma, MNT_ROOTFS);
795                 if (error == 0 || timeout <= 0)
796                         break;
797
798                 if (root_mount_timeout * hz == timeout ||
799                     (bootverbose && timeout % hz == 0)) {
800                         printf("Mounting from %s:%s failed with error %d; "
801                             "retrying for %d more second%s\n", fs, dev, error,
802                             timeout / hz, (timeout / hz > 1) ? "s" : "");
803                 }
804                 pause("rmretry", delay);
805                 timeout -= delay;
806         }
807  out:
808         if (error) {
809                 printf("Mounting from %s:%s failed with error %d",
810                     fs, dev, error);
811                 if (errmsg[0] != '\0')
812                         printf(": %s", errmsg);
813                 printf(".\n");
814         }
815         free(fs, M_TEMP);
816         free(errmsg, M_TEMP);
817         if (opts != NULL)
818                 free(opts, M_TEMP);
819         /* kernel_mount can return -1 on error. */
820         return ((error < 0) ? EDOOFUS : error);
821 }
822 #undef ERRMSGL
823
824 static int
825 vfs_mountroot_parse(struct sbuf *sb, struct mount *mpdevfs)
826 {
827         struct mount *mp;
828         char *conf;
829         int error;
830
831         root_mount_mddev = -1;
832
833 retry:
834         conf = sbuf_data(sb);
835         mp = TAILQ_NEXT(mpdevfs, mnt_list);
836         error = (mp == NULL) ? 0 : EDOOFUS;
837         root_mount_onfail = A_CONTINUE;
838         while (mp == NULL) {
839                 error = parse_skipto(&conf, CC_NONWHITESPACE);
840                 if (error == PE_EOL) {
841                         parse_advance(&conf);
842                         continue;
843                 }
844                 if (error < 0)
845                         break;
846                 switch (parse_peek(&conf)) {
847                 case '#':
848                         error = parse_skipto(&conf, '\n');
849                         break;
850                 case '.':
851                         error = parse_directive(&conf);
852                         break;
853                 default:
854                         error = parse_mount(&conf);
855                         if (error == -1) {
856                                 printf("mountroot: invalid file system "
857                                     "specification.\n");
858                                 error = 0;
859                         }
860                         break;
861                 }
862                 if (error < 0)
863                         break;
864                 /* Ignore any trailing garbage on the line. */
865                 if (parse_peek(&conf) != '\n') {
866                         printf("mountroot: advancing to next directive...\n");
867                         (void)parse_skipto(&conf, '\n');
868                 }
869                 mp = TAILQ_NEXT(mpdevfs, mnt_list);
870         }
871         if (mp != NULL)
872                 return (0);
873
874         /*
875          * We failed to mount (a new) root.
876          */
877         switch (root_mount_onfail) {
878         case A_CONTINUE:
879                 break;
880         case A_PANIC:
881                 panic("mountroot: unable to (re-)mount root.");
882                 /* NOTREACHED */
883         case A_RETRY:
884                 goto retry;
885         case A_REBOOT:
886                 kern_reboot(RB_NOSYNC);
887                 /* NOTREACHED */
888         }
889
890         return (error);
891 }
892
893 static void
894 vfs_mountroot_conf0(struct sbuf *sb)
895 {
896         char *s, *tok, *mnt, *opt;
897         int error;
898
899         sbuf_printf(sb, ".onfail panic\n");
900         sbuf_printf(sb, ".timeout %d\n", root_mount_timeout);
901         if (boothowto & RB_ASKNAME)
902                 sbuf_printf(sb, ".ask\n");
903 #ifdef ROOTDEVNAME
904         if (boothowto & RB_DFLTROOT)
905                 sbuf_printf(sb, "%s\n", ROOTDEVNAME);
906 #endif
907         if (boothowto & RB_CDROM) {
908                 sbuf_printf(sb, "cd9660:/dev/cd0 ro\n");
909                 sbuf_printf(sb, ".timeout 0\n");
910                 sbuf_printf(sb, "cd9660:/dev/cd1 ro\n");
911                 sbuf_printf(sb, ".timeout %d\n", root_mount_timeout);
912         }
913         s = kern_getenv("vfs.root.mountfrom");
914         if (s != NULL) {
915                 opt = kern_getenv("vfs.root.mountfrom.options");
916                 tok = s;
917                 error = parse_token(&tok, &mnt);
918                 while (!error) {
919                         sbuf_printf(sb, "%s %s\n", mnt,
920                             (opt != NULL) ? opt : "");
921                         free(mnt, M_TEMP);
922                         error = parse_token(&tok, &mnt);
923                 }
924                 if (opt != NULL)
925                         freeenv(opt);
926                 freeenv(s);
927         }
928         if (rootdevnames[0] != NULL)
929                 sbuf_printf(sb, "%s\n", rootdevnames[0]);
930         if (rootdevnames[1] != NULL)
931                 sbuf_printf(sb, "%s\n", rootdevnames[1]);
932 #ifdef ROOTDEVNAME
933         if (!(boothowto & RB_DFLTROOT))
934                 sbuf_printf(sb, "%s\n", ROOTDEVNAME);
935 #endif
936         if (!(boothowto & RB_ASKNAME))
937                 sbuf_printf(sb, ".ask\n");
938 }
939
940 static int
941 vfs_mountroot_readconf(struct thread *td, struct sbuf *sb)
942 {
943         static char buf[128];
944         struct nameidata nd;
945         off_t ofs;
946         ssize_t resid;
947         int error, flags, len;
948
949         NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, "/.mount.conf", td);
950         flags = FREAD;
951         error = vn_open(&nd, &flags, 0, NULL);
952         if (error)
953                 return (error);
954
955         NDFREE(&nd, NDF_ONLY_PNBUF);
956         ofs = 0;
957         len = sizeof(buf) - 1;
958         while (1) {
959                 error = vn_rdwr(UIO_READ, nd.ni_vp, buf, len, ofs,
960                     UIO_SYSSPACE, IO_NODELOCKED, td->td_ucred,
961                     NOCRED, &resid, td);
962                 if (error)
963                         break;
964                 if (resid == len)
965                         break;
966                 buf[len - resid] = 0;
967                 sbuf_printf(sb, "%s", buf);
968                 ofs += len - resid;
969         }
970
971         VOP_UNLOCK(nd.ni_vp);
972         vn_close(nd.ni_vp, FREAD, td->td_ucred, td);
973         return (error);
974 }
975
976 static void
977 vfs_mountroot_wait(void)
978 {
979         struct root_hold_token *h;
980         struct timeval lastfail;
981         int curfail;
982
983         TSENTER();
984
985         curfail = 0;
986         lastfail.tv_sec = 0;
987         ppsratecheck(&lastfail, &curfail, 1);
988         while (1) {
989                 g_waitidle();
990                 mtx_lock(&root_holds_mtx);
991                 if (TAILQ_EMPTY(&root_holds)) {
992                         mtx_unlock(&root_holds_mtx);
993                         break;
994                 }
995                 if (ppsratecheck(&lastfail, &curfail, 1)) {
996                         printf("Root mount waiting for:");
997                         TAILQ_FOREACH(h, &root_holds, list)
998                                 printf(" %s", h->who);
999                         printf("\n");
1000                 }
1001                 TSWAIT("root mount");
1002                 msleep(&root_holds, &root_holds_mtx, PZERO | PDROP, "roothold",
1003                     hz);
1004                 TSUNWAIT("root mount");
1005         }
1006         g_waitidle();
1007
1008         TSEXIT();
1009 }
1010
1011 static int
1012 vfs_mountroot_wait_if_neccessary(const char *fs, const char *dev)
1013 {
1014         int delay, timeout;
1015
1016         /*
1017          * In case of ZFS and NFS we don't have a way to wait for
1018          * specific device.  Also do the wait if the user forced that
1019          * behaviour by setting vfs.root_mount_always_wait=1.
1020          */
1021         if (strcmp(fs, "zfs") == 0 || strstr(fs, "nfs") != NULL ||
1022             dev[0] == '\0' || root_mount_always_wait != 0) {
1023                 vfs_mountroot_wait();
1024                 return (0);
1025         }
1026
1027         /*
1028          * Otherwise, no point in waiting if the device is already there.
1029          * Note that we must wait for GEOM to finish reconfiguring itself,
1030          * eg for geom_part(4) to finish tasting.
1031          */
1032         g_waitidle();
1033         if (parse_mount_dev_present(dev))
1034                 return (0);
1035
1036         /*
1037          * No luck.  Let's wait.  This code looks weird, but it's that way
1038          * to behave exactly as it used to work before.
1039          */
1040         vfs_mountroot_wait();
1041         if (parse_mount_dev_present(dev))
1042                 return (0);
1043         printf("mountroot: waiting for device %s...\n", dev);
1044         delay = hz / 10;
1045         timeout = root_mount_timeout * hz;
1046         do {
1047                 pause("rmdev", delay);
1048                 timeout -= delay;
1049         } while (timeout > 0 && !parse_mount_dev_present(dev));
1050
1051         if (timeout <= 0)
1052                 return (ENODEV);
1053
1054         return (0);
1055 }
1056
1057 void
1058 vfs_mountroot(void)
1059 {
1060         struct mount *mp;
1061         struct sbuf *sb;
1062         struct thread *td;
1063         time_t timebase;
1064         int error;
1065
1066         mtx_assert(&Giant, MA_NOTOWNED);
1067
1068         TSENTER();
1069
1070         td = curthread;
1071
1072         sb = sbuf_new_auto();
1073         vfs_mountroot_conf0(sb);
1074         sbuf_finish(sb);
1075
1076         error = vfs_mountroot_devfs(td, &mp);
1077         while (!error) {
1078                 error = vfs_mountroot_parse(sb, mp);
1079                 if (!error) {
1080                         vfs_mountroot_shuffle(td, mp);
1081                         sbuf_clear(sb);
1082                         error = vfs_mountroot_readconf(td, sb);
1083                         sbuf_finish(sb);
1084                 }
1085         }
1086
1087         sbuf_delete(sb);
1088
1089         /*
1090          * Iterate over all currently mounted file systems and use
1091          * the time stamp found to check and/or initialize the RTC.
1092          * Call inittodr() only once and pass it the largest of the
1093          * timestamps we encounter.
1094          */
1095         timebase = 0;
1096         mtx_lock(&mountlist_mtx);
1097         mp = TAILQ_FIRST(&mountlist);
1098         while (mp != NULL) {
1099                 if (mp->mnt_time > timebase)
1100                         timebase = mp->mnt_time;
1101                 mp = TAILQ_NEXT(mp, mnt_list);
1102         }
1103         mtx_unlock(&mountlist_mtx);
1104         inittodr(timebase);
1105
1106         /* Keep prison0's root in sync with the global rootvnode. */
1107         mtx_lock(&prison0.pr_mtx);
1108         prison0.pr_root = rootvnode;
1109         vref(prison0.pr_root);
1110         mtx_unlock(&prison0.pr_mtx);
1111
1112         mtx_lock(&root_holds_mtx);
1113         atomic_store_rel_int(&root_mount_complete, 1);
1114         wakeup(&root_mount_complete);
1115         mtx_unlock(&root_holds_mtx);
1116
1117         EVENTHANDLER_INVOKE(mountroot);
1118
1119         TSEXIT();
1120 }
1121
1122 static struct mntarg *
1123 parse_mountroot_options(struct mntarg *ma, const char *options)
1124 {
1125         char *p;
1126         char *name, *name_arg;
1127         char *val, *val_arg;
1128         char *opts;
1129
1130         if (options == NULL || options[0] == '\0')
1131                 return (ma);
1132
1133         p = opts = strdup(options, M_MOUNT);
1134         if (opts == NULL) {
1135                 return (ma);
1136         }
1137
1138         while((name = strsep(&p, ",")) != NULL) {
1139                 if (name[0] == '\0')
1140                         break;
1141
1142                 val = strchr(name, '=');
1143                 if (val != NULL) {
1144                         *val = '\0';
1145                         ++val;
1146                 }
1147                 if( strcmp(name, "rw") == 0 ||
1148                     strcmp(name, "noro") == 0) {
1149                         /*
1150                          * The first time we mount the root file system,
1151                          * we need to mount 'ro', so We need to ignore
1152                          * 'rw' and 'noro' mount options.
1153                          */
1154                         continue;
1155                 }
1156                 name_arg = strdup(name, M_MOUNT);
1157                 val_arg = NULL;
1158                 if (val != NULL)
1159                         val_arg = strdup(val, M_MOUNT);
1160
1161                 ma = mount_arg(ma, name_arg, val_arg,
1162                     (val_arg != NULL ? -1 : 0));
1163         }
1164         free(opts, M_MOUNT);
1165         return (ma);
1166 }