kernel - adjust devfs mount point according to init_chroot loader variable
[dragonfly.git] / sys / kern / vfs_conf.c
1 /*-
2  * Copyright (c) 1999 Michael Smith
3  * All rights reserved.
4  * Copyright (c) 1999 Poul-Henning Kamp
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  *      $FreeBSD: src/sys/kern/vfs_conf.c,v 1.49.2.5 2003/01/07 11:56:53 joerg Exp $
29  *      $DragonFly: src/sys/kern/vfs_conf.c,v 1.34 2008/05/24 19:08:28 dillon Exp $
30  */
31
32 /*
33  * Locate and mount the root filesystem.
34  *
35  * The root filesystem is detailed in the kernel environment variable
36  * vfs.root.mountfrom, which is expected to be in the general format
37  *
38  * <vfsname>:[<path>]
39  * vfsname   := the name of a VFS known to the kernel and capable
40  *              of being mounted as root
41  * path      := disk device name or other data used by the filesystem
42  *              to locate its physical store
43  *
44  */
45
46 #include "opt_rootdevname.h"
47
48 #include <sys/param.h>
49 #include <sys/kernel.h>
50 #include <sys/systm.h>
51 #include <sys/proc.h>
52 #include <sys/vnode.h>
53 #include <sys/mount.h>
54 #include <sys/malloc.h>
55 #include <sys/reboot.h>
56 #include <sys/diskslice.h>
57 #include <sys/conf.h>
58 #include <sys/cons.h>
59 #include <sys/device.h>
60 #include <sys/disk.h>
61 #include <sys/namecache.h>
62 #include <sys/paths.h>
63 #include <sys/thread2.h>
64 #include <sys/nlookup.h>
65 #include <sys/devfs.h>
66 #include <sys/sysctl.h>
67
68 #include "opt_ddb.h"
69 #ifdef DDB
70 #include <ddb/ddb.h>
71 #endif
72
73 MALLOC_DEFINE(M_MOUNT, "mount", "vfs mount structure");
74
75 #define ROOTNAME        "root_device"
76
77 struct vnode    *rootvnode;
78 struct nchandle rootnch;
79
80 /* 
81  * The root specifiers we will try if RB_CDROM is specified.  Note that
82  * with DEVFS we do not use the compatibility slice's whole-disk 'c'
83  * partition.  Instead we just use the whole disk, e.g. cd0 or cd0s0.
84  */
85 static char *cdrom_rootdevnames[] = {
86         "cd9660:cd0",   /* SCSI (including AHCI and SILI) */
87         "cd9660:acd0",  /* NATA */
88         "cd9660:cd1",   /* SCSI (including AHCI and SILI) */
89         "cd9660:acd1",  /* NATA */
90         "cd9660:cd8",   /* USB */
91         "cd9660:cd9",   /* USB */
92         NULL
93 };
94
95 int vfs_mountroot_devfs(void);
96 static void     vfs_mountroot(void *junk);
97 static int      vfs_mountroot_try(const char *mountfrom);
98 static int      vfs_mountroot_ask(void);
99 static int      getline(char *cp, int limit);
100
101 /* legacy find-root code */
102 char            *rootdevnames[2] = {NULL, NULL};
103 static int      setrootbyname(char *name);
104
105 SYSINIT(mountroot, SI_SUB_MOUNT_ROOT, SI_ORDER_SECOND, vfs_mountroot, NULL);
106         
107 /*
108  * Find and mount the root filesystem
109  */
110 static void
111 vfs_mountroot(void *junk)
112 {
113         cdev_t  save_rootdev = rootdev;
114         int     i;
115         int     dummy;
116         
117         /*
118          * Make sure all disk devices created so far have also been probed,
119          * and also make sure that the newly created device nodes for
120          * probed disks are ready, too.
121          *
122          * Messages can fly around here so get good synchronization
123          * coverage.
124          *
125          * XXX - Delay an additional 2 seconds to help drivers which pickup
126          *       devices asynchronously and are not caught by CAM's initial
127          *       probe.
128          */
129         sync_devs();
130         tsleep(&dummy, 0, "syncer", hz*2);
131
132
133         /* 
134          * The root filesystem information is compiled in, and we are
135          * booted with instructions to use it.
136          */
137 #ifdef ROOTDEVNAME
138         if ((boothowto & RB_DFLTROOT) && 
139             !vfs_mountroot_try(ROOTDEVNAME))
140                 return;
141 #endif
142         /* 
143          * We are booted with instructions to prompt for the root filesystem,
144          * or to use the compiled-in default when it doesn't exist.
145          */
146         if (boothowto & (RB_DFLTROOT | RB_ASKNAME)) {
147                 if (!vfs_mountroot_ask())
148                         return;
149         }
150
151         /*
152          * We've been given the generic "use CDROM as root" flag.  This is
153          * necessary because one media may be used in many different
154          * devices, so we need to search for them.
155          */
156         if (boothowto & RB_CDROM) {
157                 for (i = 0; cdrom_rootdevnames[i] != NULL; i++) {
158                         if (!vfs_mountroot_try(cdrom_rootdevnames[i]))
159                                 return;
160                 }
161         }
162
163         /*
164          * Try to use the value read by the loader from /etc/fstab, or
165          * supplied via some other means.  This is the preferred 
166          * mechanism.
167          */
168         if (!vfs_mountroot_try(kgetenv("vfs.root.mountfrom")))
169                 return;
170
171         /*
172          * If a vfs set rootdev, try it (XXX VINUM HACK!)
173          */
174         if (save_rootdev != NULL) {
175                 rootdev = save_rootdev;
176                 if (!vfs_mountroot_try(""))
177                         return;
178         }
179
180         /* 
181          * Try values that may have been computed by the machine-dependant
182          * legacy code.
183          */
184         if (rootdevnames[0] && !vfs_mountroot_try(rootdevnames[0]))
185                 return;
186         if (rootdevnames[1] && !vfs_mountroot_try(rootdevnames[1]))
187                 return;
188
189         /*
190          * If we have a compiled-in default, and haven't already tried it, try
191          * it now.
192          */
193 #ifdef ROOTDEVNAME
194         if (!(boothowto & RB_DFLTROOT))
195                 if (!vfs_mountroot_try(ROOTDEVNAME))
196                         return;
197 #endif
198
199         /* 
200          * Everything so far has failed, prompt on the console if we haven't
201          * already tried that.
202          */
203         if (!(boothowto & (RB_DFLTROOT | RB_ASKNAME)) && !vfs_mountroot_ask())
204                 return;
205         panic("Root mount failed, startup aborted.");
206 }
207
208
209 int
210 vfs_mountroot_devfs(void)
211 {
212         struct vnode *vp;
213         struct nchandle nch;
214         struct nlookupdata nd;
215         struct mount *mp;
216         struct vfsconf *vfsp;
217         int error;
218         struct ucred *cred = proc0.p_ucred;
219         const char *devfs_path, *init_chroot;
220         char *dev_malloced = NULL;
221
222         if ((init_chroot = kgetenv("init_chroot")) != NULL) {
223                 size_t l;
224
225                 l = strlen(init_chroot) + sizeof("/dev");
226                 dev_malloced = kmalloc(l, M_MOUNT, M_WAITOK);
227                 ksnprintf(dev_malloced, l, "%s/dev", init_chroot);
228                 devfs_path = dev_malloced;
229         } else {
230                 devfs_path = "/dev";
231         }
232         /*
233          * Lookup the requested path and extract the nch and vnode.
234          */
235         error = nlookup_init_raw(&nd,
236              devfs_path, UIO_SYSSPACE, NLC_FOLLOW,
237              cred, &rootnch);
238
239         if (error == 0) {
240                 devfs_debug(DEVFS_DEBUG_DEBUG, "vfs_mountroot_devfs: nlookup_init is ok...\n");
241                 if ((error = nlookup(&nd)) == 0) {
242                         devfs_debug(DEVFS_DEBUG_DEBUG, "vfs_mountroot_devfs: nlookup is ok...\n");
243                         if (nd.nl_nch.ncp->nc_vp == NULL) {
244                                 devfs_debug(DEVFS_DEBUG_SHOW, "vfs_mountroot_devfs: nlookup: simply not found\n");
245                                 error = ENOENT;
246                         }
247                 }
248         }
249         if (dev_malloced != NULL)
250                 kfree(dev_malloced, M_MOUNT), dev_malloced = NULL;
251         devfs_path = NULL;
252         if (error) {
253                 nlookup_done(&nd);
254                 devfs_debug(DEVFS_DEBUG_SHOW, "vfs_mountroot_devfs: nlookup failed, error: %d\n", error);
255                 return (error);
256         }
257
258         /*
259          * Extract the locked+refd ncp and cleanup the nd structure
260          */
261         nch = nd.nl_nch;
262         cache_zero(&nd.nl_nch);
263         nlookup_done(&nd);
264
265         /*
266          * now we have the locked ref'd nch and unreferenced vnode.
267          */
268         vp = nch.ncp->nc_vp;
269         if ((error = vget(vp, LK_EXCLUSIVE)) != 0) {
270                 cache_put(&nch);
271                 devfs_debug(DEVFS_DEBUG_SHOW, "vfs_mountroot_devfs: vget failed\n");
272                 return (error);
273         }
274         cache_unlock(&nch);
275
276         if ((error = vinvalbuf(vp, V_SAVE, 0, 0)) != 0) {
277                 cache_drop(&nch);
278                 vput(vp);
279                 devfs_debug(DEVFS_DEBUG_SHOW, "vfs_mountroot_devfs: vinvalbuf failed\n");
280                 return (error);
281         }
282         if (vp->v_type != VDIR) {
283                 cache_drop(&nch);
284                 vput(vp);
285                 devfs_debug(DEVFS_DEBUG_SHOW, "vfs_mountroot_devfs: vp is not VDIR\n");
286                 return (ENOTDIR);
287         }
288
289         vfsp = vfsconf_find_by_name("devfs");
290         vsetflags(vp, VMOUNT);
291
292         /*
293          * Allocate and initialize the filesystem.
294          */
295         mp = kmalloc(sizeof(struct mount), M_MOUNT, M_ZERO|M_WAITOK);
296         mount_init(mp);
297         vfs_busy(mp, LK_NOWAIT);
298         mp->mnt_op = vfsp->vfc_vfsops;
299         mp->mnt_vfc = vfsp;
300         vfsp->vfc_refcount++;
301         mp->mnt_stat.f_type = vfsp->vfc_typenum;
302         mp->mnt_flag |= vfsp->vfc_flags & MNT_VISFLAGMASK;
303         strncpy(mp->mnt_stat.f_fstypename, vfsp->vfc_name, MFSNAMELEN);
304         mp->mnt_stat.f_owner = cred->cr_uid;
305         vn_unlock(vp);
306
307         /*
308          * Mount the filesystem.
309          */
310         error = VFS_MOUNT(mp, "/dev", NULL, cred);
311
312         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
313
314         /*
315          * Put the new filesystem on the mount list after root.  The mount
316          * point gets its own mnt_ncmountpt (unless the VFS already set one
317          * up) which represents the root of the mount.  The lookup code
318          * detects the mount point going forward and checks the root of
319          * the mount going backwards.
320          *
321          * It is not necessary to invalidate or purge the vnode underneath
322          * because elements under the mount will be given their own glue
323          * namecache record.
324          */
325         if (!error) {
326                 if (mp->mnt_ncmountpt.ncp == NULL) {
327                         /*
328                          * allocate, then unlock, but leave the ref intact
329                          */
330                         cache_allocroot(&mp->mnt_ncmountpt, mp, NULL);
331                         cache_unlock(&mp->mnt_ncmountpt);
332                 }
333                 mp->mnt_ncmounton = nch;                /* inherits ref */
334                 nch.ncp->nc_flag |= NCF_ISMOUNTPT;
335
336                 /* XXX get the root of the fs and cache_setvp(mnt_ncmountpt...) */
337                 vclrflags(vp, VMOUNT);
338                 mountlist_insert(mp, MNTINS_LAST);
339                 vn_unlock(vp);
340                 //checkdirs(&mp->mnt_ncmounton, &mp->mnt_ncmountpt);
341                 error = vfs_allocate_syncvnode(mp);
342                 if (error) {
343                         devfs_debug(DEVFS_DEBUG_SHOW, "vfs_mountroot_devfs: vfs_allocate_syncvnode failed\n");
344                 }
345                 vfs_unbusy(mp);
346                 error = VFS_START(mp, 0);
347                 vrele(vp);
348         } else {
349                 vfs_rm_vnodeops(mp, NULL, &mp->mnt_vn_coherency_ops);
350                 vfs_rm_vnodeops(mp, NULL, &mp->mnt_vn_journal_ops);
351                 vfs_rm_vnodeops(mp, NULL, &mp->mnt_vn_norm_ops);
352                 vfs_rm_vnodeops(mp, NULL, &mp->mnt_vn_spec_ops);
353                 vfs_rm_vnodeops(mp, NULL, &mp->mnt_vn_fifo_ops);
354                 vclrflags(vp, VMOUNT);
355                 mp->mnt_vfc->vfc_refcount--;
356                 vfs_unbusy(mp);
357                 kfree(mp, M_MOUNT);
358                 cache_drop(&nch);
359                 vput(vp);
360                 devfs_debug(DEVFS_DEBUG_SHOW, "vfs_mountroot_devfs: mount failed\n");
361         }
362
363         devfs_debug(DEVFS_DEBUG_DEBUG, "rootmount_devfs done with error: %d\n", error);
364         return (error);
365 }
366
367
368 /*
369  * Mount (mountfrom) as the root filesystem.
370  */
371 static int
372 vfs_mountroot_try(const char *mountfrom)
373 {
374         struct mount    *mp, *mp2;
375         char            *vfsname, *devname;
376         int             error;
377         char            patt[32];
378         int             mountfromlen, len;
379         const char      *cp, *ep;
380         char            *mf;
381
382         vfsname = NULL;
383         devname = NULL;
384         mp      = NULL;
385         mp2             = NULL;
386         error   = EINVAL;
387
388         if (mountfrom == NULL)
389                 return(error);          /* don't complain */
390
391         crit_enter();
392         kprintf("Mounting root from %s\n", mountfrom);
393         crit_exit();
394
395         mountfromlen = strlen(mountfrom);
396         cp = mountfrom;
397         /* parse vfs name and devname */
398         vfsname = kmalloc(MFSNAMELEN, M_MOUNT, M_WAITOK);
399         devname = kmalloc(MNAMELEN, M_MOUNT, M_WAITOK);
400         mf = kmalloc(MFSNAMELEN+MNAMELEN, M_MOUNT, M_WAITOK);
401         for(;;) {
402                 for (ep = cp; (*ep != 0) && (*ep != ';'); ep++);
403                 len = ep - cp;
404                 bzero(vfsname, MFSNAMELEN);
405                 bzero(devname, MNAMELEN);
406                 bzero(mf, MFSNAMELEN+MNAMELEN);
407                 strncpy(mf, cp, MFSNAMELEN+MNAMELEN);
408
409                 vfsname[0] = devname[0] = 0;
410                 ksprintf(patt, "%%%d[a-z0-9]:%%%ds", MFSNAMELEN, MNAMELEN);
411                 if (ksscanf(mf, patt, vfsname, devname) < 1)
412                         goto end;
413
414                 /* allocate a root mount */
415                 error = vfs_rootmountalloc(vfsname,
416                                 devname[0] != 0 ? devname : ROOTNAME, &mp);
417                 if (error != 0) {
418                         kprintf("Can't allocate root mount for filesystem '%s': %d\n",
419                                vfsname, error);
420                         goto end;
421                 }
422                 mp->mnt_flag |= MNT_ROOTFS;
423
424                 /* do our best to set rootdev */
425                 if ((strcmp(vfsname, "hammer") != 0) && (devname[0] != 0) &&
426                     setrootbyname(devname))
427                         kprintf("setrootbyname failed\n");
428
429                 /* If the root device is a type "memory disk", mount RW */
430                 if (rootdev != NULL && dev_is_good(rootdev) &&
431                     (dev_dflags(rootdev) & D_MEMDISK)) {
432                         mp->mnt_flag &= ~MNT_RDONLY;
433                 }
434
435                 error = VFS_MOUNT(mp, NULL, NULL, proc0.p_ucred);
436
437                 if (!error)
438                         break;
439 end:
440                 if(*ep == 0)
441                         break;
442                 cp = ep + 1;
443         }
444
445         if (vfsname != NULL)
446                 kfree(vfsname, M_MOUNT);
447         if (devname != NULL)
448                 kfree(devname, M_MOUNT);
449         if (mf != NULL)
450                 kfree(mf, M_MOUNT);
451         if (error == 0) {
452                 /* register with list of mounted filesystems */
453                 mountlist_insert(mp, MNTINS_FIRST);
454
455                 /* sanity check system clock against root fs timestamp */
456                 inittodr(mp->mnt_time);
457                 vfs_unbusy(mp);
458                 if (mp->mnt_syncer == NULL) {
459                         error = vfs_allocate_syncvnode(mp);
460                         if (error)
461                                 kprintf("Warning: no syncer vp for root!\n");
462                         error = 0;
463                 }
464         } else {
465                 if (mp != NULL) {
466                         vfs_unbusy(mp);
467                         kfree(mp, M_MOUNT);
468                 }
469                 kprintf("Root mount failed: %d\n", error);
470         }
471         return(error);
472 }
473
474
475 static void
476 vfs_mountroot_ask_callback(cdev_t dev, void *arg __unused)
477 {
478         if (dev_is_good(dev) && (dev_dflags(dev) & D_DISK))
479                 kprintf(" \"%s\" ", dev->si_name);
480 }
481
482
483 /*
484  * Spin prompting on the console for a suitable root filesystem
485  */
486 static int
487 vfs_mountroot_ask(void)
488 {
489         char name[128];
490         int llimit = 100;
491
492         kprintf("\nManual root filesystem specification:\n");
493         kprintf("  <fstype>:<device>  Specify root (e.g. ufs:da0s1a)\n");
494         kprintf("  ?                  List valid disk boot devices\n");
495         kprintf("  panic              Just panic\n");
496         kprintf("  abort              Abort manual input\n");
497         while (llimit--) {
498                 kprintf("\nmountroot> ");
499
500                 if (getline(name, 128) < 0)
501                         break;
502                 if (name[0] == 0) {
503                         ;
504                 } else if (name[0] == '?') {
505                         kprintf("Possibly valid devices for root FS:\n");
506                         //enumerate all disk devices
507                         devfs_scan_callback(vfs_mountroot_ask_callback, NULL);
508                         kprintf("\n");
509                         continue;
510                 } else if (strcmp(name, "panic") == 0) {
511                         panic("panic from console");
512                 } else if (strcmp(name, "abort") == 0) {
513                         break;
514                 } else if (vfs_mountroot_try(name) == 0) {
515                         return(0);
516                 }
517         }
518         return(1);
519 }
520
521
522 static int
523 getline(char *cp, int limit)
524 {
525         char *lp;
526         int c;
527
528         lp = cp;
529         for (;;) {
530                 c = cngetc();
531
532                 switch (c) {
533                 case -1:
534                         return(-1);
535                 case '\n':
536                 case '\r':
537                         kprintf("\n");
538                         *lp++ = '\0';
539                         return(0);
540                 case '\b':
541                 case '\177':
542                         if (lp > cp) {
543                                 kprintf("\b \b");
544                                 lp--;
545                         } else {
546                                 kprintf("%c", 7);
547                         }
548                         continue;
549                 case '#':
550                         kprintf("#");
551                         lp--;
552                         if (lp < cp)
553                                 lp = cp;
554                         continue;
555                 case '@':
556                 case 'u' & 037:
557                         lp = cp;
558                         kprintf("%c", '\n');
559                         continue;
560                 default:
561                         if (lp - cp >= limit - 1) {
562                                 kprintf("%c", 7);
563                         } else {
564                                 kprintf("%c", c);
565                                 *lp++ = c;
566                         }
567                         continue;
568                 }
569         }
570 }
571
572 /*
573  * Convert a given name to the cdev_t of the disk-like device
574  * it refers to.
575  */
576 struct kdbn_info {
577         const char *name;
578         int nlen;
579         int minor;
580         cdev_t dev;
581 };
582
583
584 cdev_t
585 kgetdiskbyname(const char *name) 
586 {
587         char *cp;
588         cdev_t rdev;
589
590         /*
591          * Get the base name of the device
592          */
593         if (strncmp(name, __SYS_PATH_DEV, sizeof(__SYS_PATH_DEV) - 1) == 0)
594                 name += sizeof(__SYS_PATH_DEV) - 1;
595         cp = __DECONST(char *, name);
596
597         /*
598          * Locate the device
599          */
600         kprintf("tryroot %s\n", name);
601         rdev = devfs_find_device_by_name(name);
602         if (rdev == NULL) {
603                 kprintf("no disk named '%s'\n", name);
604         }
605         /*
606          * FOUND DEVICE
607          */
608         return(rdev);
609 }
610
611 /*
612  * Set rootdev to match (name), given that we expect it to
613  * refer to a disk-like device.
614  */
615 static int
616 setrootbyname(char *name)
617 {
618         cdev_t diskdev;
619
620         diskdev = kgetdiskbyname(name);
621         if (diskdev != NULL) {
622                 rootdev = diskdev;
623                 return (0);
624         }
625         /* set to NULL if kgetdiskbyname() fails so that if the first rootdev is
626          * found by fails to mount and the second one isn't found, mountroot_try
627          * doesn't try again with the first one
628          */
629         rootdev = NULL;
630         return (1);
631 }
632
633 #ifdef DDB
634 DB_SHOW_COMMAND(disk, db_getdiskbyname)
635 {
636         cdev_t dev;
637
638         if (modif[0] == '\0') {
639                 db_error("usage: show disk/devicename");
640                 return;
641         }
642         dev = kgetdiskbyname(modif);
643         if (dev != NULL)
644                 db_printf("cdev_t = %p\n", dev);
645         else
646                 db_printf("No disk device matched.\n");
647 }
648 #endif
649
650 static int
651 vfs_sysctl_real_root(SYSCTL_HANDLER_ARGS)
652 {
653         char *real_root;
654         size_t len;
655         int error;
656
657         real_root = kgetenv("vfs.root.realroot");
658
659         if (real_root == NULL)
660                 real_root = "";
661
662         len = strlen(real_root) + 1;
663
664         error = sysctl_handle_string(oidp, real_root, len, req);
665
666         return error;
667 }
668
669 SYSCTL_PROC(_vfs, OID_AUTO, real_root,
670             CTLTYPE_STRING | CTLFLAG_RD, 0, 0, vfs_sysctl_real_root,
671             "A", "Real root mount string");