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