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