md.c revision 70595
1/*
2 * ----------------------------------------------------------------------------
3 * "THE BEER-WARE LICENSE" (Revision 42):
4 * <phk@FreeBSD.ORG> wrote this file.  As long as you retain this notice you
5 * can do whatever you want with this stuff. If we meet some day, and you think
6 * this stuff is worth it, you can buy me a beer in return.   Poul-Henning Kamp
7 * ----------------------------------------------------------------------------
8 *
9 * $FreeBSD: head/sys/dev/md/md.c 70595 2001-01-02 09:42:47Z phk $
10 *
11 */
12
13/*
14 * The following functions are based in the vn(4) driver: mdstart_swap(),
15 * mdstart_vnode(), mdcreate_swap(), mdcreate_vnode() and mddestroy(),
16 * and as such under the following copyright:
17 *
18 * Copyright (c) 1988 University of Utah.
19 * Copyright (c) 1990, 1993
20 *	The Regents of the University of California.  All rights reserved.
21 *
22 * This code is derived from software contributed to Berkeley by
23 * the Systems Programming Group of the University of Utah Computer
24 * Science Department.
25 *
26 * Redistribution and use in source and binary forms, with or without
27 * modification, are permitted provided that the following conditions
28 * are met:
29 * 1. Redistributions of source code must retain the above copyright
30 *    notice, this list of conditions and the following disclaimer.
31 * 2. Redistributions in binary form must reproduce the above copyright
32 *    notice, this list of conditions and the following disclaimer in the
33 *    documentation and/or other materials provided with the distribution.
34 * 3. All advertising materials mentioning features or use of this software
35 *    must display the following acknowledgement:
36 *	This product includes software developed by the University of
37 *	California, Berkeley and its contributors.
38 * 4. Neither the name of the University nor the names of its contributors
39 *    may be used to endorse or promote products derived from this software
40 *    without specific prior written permission.
41 *
42 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
43 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
44 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
45 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
46 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
47 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
48 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
49 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
50 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
51 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
52 * SUCH DAMAGE.
53 *
54 * from: Utah Hdr: vn.c 1.13 94/04/02
55 *
56 *	from: @(#)vn.c	8.6 (Berkeley) 4/1/94
57 * From: src/sys/dev/vn/vn.c,v 1.122 2000/12/16 16:06:03
58 */
59
60#include "opt_mfs.h"		/* We have adopted some tasks from MFS */
61#include "opt_md.h"
62
63#include <sys/param.h>
64#include <sys/systm.h>
65#include <sys/bio.h>
66#include <sys/conf.h>
67#include <sys/devicestat.h>
68#include <sys/disk.h>
69#include <sys/kernel.h>
70#include <sys/malloc.h>
71#include <sys/sysctl.h>
72#include <sys/linker.h>
73#include <sys/queue.h>
74#include <sys/mdioctl.h>
75#include <sys/vnode.h>
76#include <sys/namei.h>
77#include <sys/fcntl.h>
78#include <sys/proc.h>
79#include <machine/atomic.h>
80
81#include <vm/vm.h>
82#include <vm/vm_object.h>
83#include <vm/vm_page.h>
84#include <vm/vm_pager.h>
85#include <vm/vm_zone.h>
86#include <vm/swap_pager.h>
87
88#ifndef MD_NSECT
89#define MD_NSECT (10000 * 2)
90#endif
91
92MALLOC_DEFINE(M_MD, "MD disk", "Memory Disk");
93MALLOC_DEFINE(M_MDSECT, "MD sectors", "Memory Disk Sectors");
94
95static int md_debug;
96SYSCTL_INT(_debug, OID_AUTO, mddebug, CTLFLAG_RW, &md_debug, 0, "");
97
98#if defined(MFS_ROOT) && !defined(MD_ROOT)
99#define MD_ROOT MFS_ROOT
100#warning "option MFS_ROOT has been superceeded by MD_ROOT"
101#endif
102
103#if defined(MFS_ROOT_SIZE) && !defined(MD_ROOT_SIZE)
104#define MD_ROOT_SIZE MFS_ROOT_SIZE
105#warning "option MFS_ROOT_SIZE has been superceeded by MD_ROOT_SIZE"
106#endif
107
108#if defined(MD_ROOT) && defined(MD_ROOT_SIZE)
109/* Image gets put here: */
110static u_char mfs_root[MD_ROOT_SIZE*1024] = "MFS Filesystem goes here";
111static u_char end_mfs_root[] __unused = "MFS Filesystem had better STOP here";
112#endif
113
114static int mdrootready;
115static int mdunits;
116
117#define CDEV_MAJOR	95
118
119static d_strategy_t mdstrategy;
120static d_open_t mdopen;
121static d_ioctl_t mdioctl, mdctlioctl;
122
123static struct cdevsw md_cdevsw = {
124        /* open */      mdopen,
125        /* close */     nullclose,
126        /* read */      physread,
127        /* write */     physwrite,
128        /* ioctl */     mdioctl,
129        /* poll */      nopoll,
130        /* mmap */      nommap,
131        /* strategy */  mdstrategy,
132        /* name */      "md",
133        /* maj */       CDEV_MAJOR,
134        /* dump */      nodump,
135        /* psize */     nopsize,
136        /* flags */     D_DISK | D_CANFREE | D_MEMDISK,
137};
138
139static struct cdevsw mdctl_cdevsw = {
140        /* open */      nullopen,
141        /* close */     nullclose,
142        /* read */      noread,
143        /* write */     nowrite,
144        /* ioctl */     mdctlioctl,
145        /* poll */      nopoll,
146        /* mmap */      nommap,
147        /* strategy */  nostrategy,
148        /* name */      "md",
149        /* maj */       CDEV_MAJOR
150};
151
152static struct cdevsw mddisk_cdevsw;
153
154static LIST_HEAD(, md_s) md_softc_list = LIST_HEAD_INITIALIZER(&md_softc_list);
155
156struct md_s {
157	int unit;
158	LIST_ENTRY(md_s) list;
159	struct devstat stats;
160	struct bio_queue_head bio_queue;
161	struct disk disk;
162	dev_t dev;
163	int busy;
164	enum md_types type;
165	unsigned nsect;
166	unsigned secsize;
167	unsigned flags;
168
169	/* MD_MALLOC related fields */
170	unsigned nsecp;
171	u_char **secp;
172
173	/* MD_PRELOAD related fields */
174	u_char *pl_ptr;
175	unsigned pl_len;
176
177	/* MD_VNODE related fields */
178	struct vnode *vnode;
179	struct ucred *cred;
180
181	/* MD_OBJET related fields */
182	vm_object_t object;
183};
184
185static int
186mdopen(dev_t dev, int flag, int fmt, struct proc *p)
187{
188	struct md_s *sc;
189	struct disklabel *dl;
190
191	if (md_debug)
192		printf("mdopen(%s %x %x %p)\n",
193			devtoname(dev), flag, fmt, p);
194
195	sc = dev->si_drv1;
196
197	dl = &sc->disk.d_label;
198	bzero(dl, sizeof(*dl));
199	dl->d_secsize = sc->secsize;
200	dl->d_nsectors = sc->nsect > 1024 ? 1024 : sc->nsect;
201	dl->d_ntracks = 1;
202	dl->d_secpercyl = dl->d_nsectors * dl->d_ntracks;
203	dl->d_secperunit = sc->nsect;
204	dl->d_ncylinders = dl->d_secperunit / dl->d_secpercyl;
205	return (0);
206}
207
208static int
209mdioctl(dev_t dev, u_long cmd, caddr_t addr, int flags, struct proc *p)
210{
211
212	if (md_debug)
213		printf("mdioctl(%s %lx %p %x %p)\n",
214			devtoname(dev), cmd, addr, flags, p);
215
216	return (ENOIOCTL);
217}
218
219static void
220mdstart_malloc(struct md_s *sc)
221{
222	int i;
223	struct bio *bp;
224	devstat_trans_flags dop;
225	u_char *secp, **secpp, *dst;
226	unsigned secno, nsec, secval, uc;
227
228	for (;;) {
229		/* XXX: LOCK(unique unit numbers) */
230		bp = bioq_first(&sc->bio_queue);
231		if (bp)
232			bioq_remove(&sc->bio_queue, bp);
233		/* XXX: UNLOCK(unique unit numbers) */
234		if (!bp)
235			break;
236
237		devstat_start_transaction(&sc->stats);
238
239		if (bp->bio_cmd == BIO_DELETE)
240			dop = DEVSTAT_NO_DATA;
241		else if (bp->bio_cmd == BIO_READ)
242			dop = DEVSTAT_READ;
243		else
244			dop = DEVSTAT_WRITE;
245
246		nsec = bp->bio_bcount / DEV_BSIZE;
247		secno = bp->bio_pblkno;
248		dst = bp->bio_data;
249		while (nsec--) {
250			if (secno < sc->nsecp) {
251				secpp = &sc->secp[secno];
252				if ((uintptr_t)*secpp > 255) {
253					secp = *secpp;
254					secval = 0;
255				} else {
256					secp = 0;
257					secval = (uintptr_t) *secpp;
258				}
259			} else {
260				secpp = 0;
261				secp = 0;
262				secval = 0;
263			}
264			if (md_debug > 2)
265				printf("%x %p %p %d\n",
266				    bp->bio_flags, secpp, secp, secval);
267
268			if (bp->bio_cmd == BIO_DELETE) {
269				if (secpp && !(sc->flags & MD_RESERVE)) {
270					if (secp)
271						FREE(secp, M_MDSECT);
272					*secpp = 0;
273				}
274			} else if (bp->bio_cmd == BIO_READ) {
275				if (secp) {
276					bcopy(secp, dst, DEV_BSIZE);
277				} else if (secval) {
278					for (i = 0; i < DEV_BSIZE; i++)
279						dst[i] = secval;
280				} else {
281					bzero(dst, DEV_BSIZE);
282				}
283			} else {
284				if (sc->flags & MD_COMPRESS) {
285					uc = dst[0];
286					for (i = 1; i < DEV_BSIZE; i++)
287						if (dst[i] != uc)
288							break;
289				} else {
290					i = 0;
291					uc = 0;
292				}
293				if (i == DEV_BSIZE && !uc) {
294					if (secp)
295						FREE(secp, M_MDSECT);
296					if (secpp)
297						*secpp = (u_char *)(uintptr_t)uc;
298				} else {
299					if (!secpp) {
300						MALLOC(secpp, u_char **, (secno + nsec + 1) * sizeof(u_char *), M_MD, M_WAITOK | M_ZERO);
301						bcopy(sc->secp, secpp, sc->nsecp * sizeof(u_char *));
302						FREE(sc->secp, M_MD);
303						sc->secp = secpp;
304						sc->nsecp = secno + nsec + 1;
305						secpp = &sc->secp[secno];
306					}
307					if (i == DEV_BSIZE) {
308						if (secp)
309							FREE(secp, M_MDSECT);
310						*secpp = (u_char *)(uintptr_t)uc;
311					} else {
312						if (!secp)
313							MALLOC(secp, u_char *, DEV_BSIZE, M_MDSECT, M_WAITOK);
314						bcopy(dst, secp, DEV_BSIZE);
315						*secpp = secp;
316					}
317				}
318			}
319			secno++;
320			dst += DEV_BSIZE;
321		}
322		bp->bio_resid = 0;
323		devstat_end_transaction_bio(&sc->stats, bp);
324		biodone(bp);
325	}
326	return;
327}
328
329
330static void
331mdstart_preload(struct md_s *sc)
332{
333	struct bio *bp;
334	devstat_trans_flags dop;
335
336	for (;;) {
337		/* XXX: LOCK(unique unit numbers) */
338		bp = bioq_first(&sc->bio_queue);
339		if (bp)
340			bioq_remove(&sc->bio_queue, bp);
341		/* XXX: UNLOCK(unique unit numbers) */
342		if (!bp)
343			break;
344
345		devstat_start_transaction(&sc->stats);
346
347		if (bp->bio_cmd == BIO_DELETE) {
348			dop = DEVSTAT_NO_DATA;
349		} else if (bp->bio_cmd == BIO_READ) {
350			dop = DEVSTAT_READ;
351			bcopy(sc->pl_ptr + (bp->bio_pblkno << DEV_BSHIFT), bp->bio_data, bp->bio_bcount);
352		} else {
353			dop = DEVSTAT_WRITE;
354			bcopy(bp->bio_data, sc->pl_ptr + (bp->bio_pblkno << DEV_BSHIFT), bp->bio_bcount);
355		}
356		bp->bio_resid = 0;
357		devstat_end_transaction_bio(&sc->stats, bp);
358		biodone(bp);
359	}
360	return;
361}
362
363static void
364mdstart_vnode(struct md_s *sc)
365{
366	int error;
367	struct bio *bp;
368	struct uio auio;
369	struct iovec aiov;
370	struct mount *mp;
371
372	/*
373	 * VNODE I/O
374	 *
375	 * If an error occurs, we set BIO_ERROR but we do not set
376	 * B_INVAL because (for a write anyway), the buffer is
377	 * still valid.
378	 */
379
380	for (;;) {
381		/* XXX: LOCK(unique unit numbers) */
382		bp = bioq_first(&sc->bio_queue);
383		if (bp)
384			bioq_remove(&sc->bio_queue, bp);
385		/* XXX: UNLOCK(unique unit numbers) */
386		if (!bp)
387			break;
388
389		devstat_start_transaction(&sc->stats);
390
391		bzero(&auio, sizeof(auio));
392
393		aiov.iov_base = bp->bio_data;
394		aiov.iov_len = bp->bio_bcount;
395		auio.uio_iov = &aiov;
396		auio.uio_iovcnt = 1;
397		auio.uio_offset = (vm_ooffset_t)bp->bio_pblkno * sc->secsize;
398		auio.uio_segflg = UIO_SYSSPACE;
399		if(bp->bio_cmd == BIO_READ)
400			auio.uio_rw = UIO_READ;
401		else
402			auio.uio_rw = UIO_WRITE;
403		auio.uio_resid = bp->bio_bcount;
404		auio.uio_procp = curproc;
405		if (VOP_ISLOCKED(sc->vnode, NULL))
406			vprint("unexpected vn driver lock", sc->vnode);
407		if (bp->bio_cmd == BIO_READ) {
408			vn_lock(sc->vnode, LK_EXCLUSIVE | LK_RETRY, curproc);
409			error = VOP_READ(sc->vnode, &auio, 0, sc->cred);
410		} else {
411			(void) vn_start_write(sc->vnode, &mp, V_WAIT);
412			vn_lock(sc->vnode, LK_EXCLUSIVE | LK_RETRY, curproc);
413			error = VOP_WRITE(sc->vnode, &auio, 0, sc->cred);
414			vn_finished_write(mp);
415		}
416		VOP_UNLOCK(sc->vnode, 0, curproc);
417		bp->bio_resid = auio.uio_resid;
418
419		if (error) {
420			bp->bio_error = error;
421			bp->bio_flags |= BIO_ERROR;
422		}
423		devstat_end_transaction_bio(&sc->stats, bp);
424		biodone(bp);
425	}
426	return;
427}
428
429static void
430mdstart_swap(struct md_s *sc)
431{
432	struct bio *bp;
433
434	for (;;) {
435		/* XXX: LOCK(unique unit numbers) */
436		bp = bioq_first(&sc->bio_queue);
437		if (bp)
438			bioq_remove(&sc->bio_queue, bp);
439		/* XXX: UNLOCK(unique unit numbers) */
440		if (!bp)
441			break;
442
443#if 0
444		devstat_start_transaction(&sc->stats);
445#endif
446
447		if ((bp->bio_cmd == BIO_DELETE) && (sc->flags & MD_RESERVE))
448			biodone(bp);
449		else
450			vm_pager_strategy(sc->object, bp);
451
452#if 0
453		devstat_end_transaction_bio(&sc->stats, bp);
454#endif
455	}
456	return;
457}
458
459static void
460mdstrategy(struct bio *bp)
461{
462	struct md_s *sc;
463
464	if (md_debug > 1)
465		printf("mdstrategy(%p) %s %x, %d, %ld, %p)\n",
466		    bp, devtoname(bp->bio_dev), bp->bio_flags, bp->bio_blkno,
467		    bp->bio_bcount / DEV_BSIZE, bp->bio_data);
468
469	sc = bp->bio_dev->si_drv1;
470
471	/* XXX: LOCK(sc->lock) */
472	bioqdisksort(&sc->bio_queue, bp);
473	/* XXX: UNLOCK(sc->lock) */
474
475	if (atomic_cmpset_int(&sc->busy, 0, 1) == 0)
476		return;
477
478	switch (sc->type) {
479	case MD_MALLOC:
480		mdstart_malloc(sc);
481		break;
482	case MD_PRELOAD:
483		mdstart_preload(sc);
484		break;
485	case MD_VNODE:
486		mdstart_vnode(sc);
487		break;
488	case MD_SWAP:
489		mdstart_swap(sc);
490		break;
491	default:
492		panic("Impossible md(type)");
493		break;
494	}
495	sc->busy = 0;
496}
497
498static struct md_s *
499mdfind(int unit)
500{
501	struct md_s *sc;
502
503	/* XXX: LOCK(unique unit numbers) */
504	LIST_FOREACH(sc, &md_softc_list, list) {
505		if (sc->unit == unit)
506			break;
507	}
508	/* XXX: UNLOCK(unique unit numbers) */
509	return (sc);
510}
511
512static struct md_s *
513mdnew(int unit)
514{
515	struct md_s *sc;
516	int max = -1;
517
518	/* XXX: LOCK(unique unit numbers) */
519	LIST_FOREACH(sc, &md_softc_list, list) {
520		if (sc->unit == unit) {
521			/* XXX: UNLOCK(unique unit numbers) */
522			return (NULL);
523		}
524		if (sc->unit > max)
525			max = sc->unit;
526	}
527	if (unit == -1)
528		unit = max + 1;
529	if (unit > DKMAXUNIT)
530		return (NULL);
531	MALLOC(sc, struct md_s *,sizeof(*sc), M_MD, M_WAITOK | M_ZERO);
532	sc->unit = unit;
533	LIST_INSERT_HEAD(&md_softc_list, sc, list);
534	/* XXX: UNLOCK(unique unit numbers) */
535	return (sc);
536}
537
538static void
539mddelete(struct md_s *sc)
540{
541
542	/* XXX: LOCK(unique unit numbers) */
543	LIST_REMOVE(sc, list);
544	/* XXX: UNLOCK(unique unit numbers) */
545	FREE(sc, M_MD);
546}
547
548static void
549mdinit(struct md_s *sc)
550{
551
552	bioq_init(&sc->bio_queue);
553	devstat_add_entry(&sc->stats, "md", sc->unit, DEV_BSIZE,
554		DEVSTAT_NO_ORDERED_TAGS,
555		DEVSTAT_TYPE_DIRECT | DEVSTAT_TYPE_IF_OTHER,
556		DEVSTAT_PRIORITY_OTHER);
557	sc->dev = disk_create(sc->unit, &sc->disk, 0, &md_cdevsw, &mddisk_cdevsw);
558	sc->dev->si_drv1 = sc;
559}
560
561static int
562mdcreate_preload(struct md_ioctl *mdio)
563{
564	struct md_s *sc;
565
566	if (mdio->md_size == 0)
567		return(EINVAL);
568	if (mdio->md_options & ~(MD_AUTOUNIT))
569		return(EINVAL);
570	if (mdio->md_options & MD_AUTOUNIT) {
571		sc = mdnew(-1);
572		if (sc == NULL)
573			return (ENOMEM);
574		mdio->md_unit = sc->unit;
575	} else {
576		sc = mdnew(mdio->md_unit);
577		if (sc == NULL)
578			return (EBUSY);
579	}
580	sc->type = MD_PRELOAD;
581	sc->secsize = DEV_BSIZE;
582	sc->nsect = mdio->md_size;
583	sc->pl_ptr = (u_char *)mdio->md_base;
584	sc->pl_len = (mdio->md_size << DEV_BSHIFT);
585	mdinit(sc);
586	return (0);
587}
588
589
590static int
591mdcreate_malloc(struct md_ioctl *mdio)
592{
593	struct md_s *sc;
594	unsigned u;
595
596	if (mdio->md_size == 0)
597		return(EINVAL);
598	if (mdio->md_options & ~(MD_AUTOUNIT | MD_COMPRESS | MD_RESERVE))
599		return(EINVAL);
600	/* Compression doesn't make sense if we have reserved space */
601	if (mdio->md_options & MD_RESERVE)
602		mdio->md_options &= ~MD_COMPRESS;
603	if (mdio->md_options & MD_AUTOUNIT) {
604		sc = mdnew(-1);
605		if (sc == NULL)
606			return (ENOMEM);
607		mdio->md_unit = sc->unit;
608	} else {
609		sc = mdnew(mdio->md_unit);
610		if (sc == NULL)
611			return (EBUSY);
612	}
613	sc->type = MD_MALLOC;
614	sc->secsize = DEV_BSIZE;
615	sc->nsect = mdio->md_size;
616	sc->flags = mdio->md_options & MD_COMPRESS;
617	if (!(mdio->md_options & MD_RESERVE)) {
618		MALLOC(sc->secp, u_char **, sizeof(u_char *), M_MD, M_WAITOK | M_ZERO);
619		sc->nsecp = 1;
620	} else {
621		MALLOC(sc->secp, u_char **, sc->nsect * sizeof(u_char *), M_MD, M_WAITOK | M_ZERO);
622		sc->nsecp = sc->nsect;
623		for (u = 0; u < sc->nsect; u++)
624			MALLOC(sc->secp[u], u_char *, DEV_BSIZE, M_MDSECT, M_WAITOK | M_ZERO);
625	}
626	printf("md%d: Malloc disk\n", sc->unit);
627	mdinit(sc);
628	return (0);
629}
630
631
632static int
633mdsetcred(struct md_s *sc, struct ucred *cred)
634{
635	char *tmpbuf;
636	int error = 0;
637
638	/*
639	 * Set credits in our softc
640	 */
641
642	if (sc->cred)
643		crfree(sc->cred);
644	sc->cred = crdup(cred);
645
646	/*
647	 * Horrible kludge to establish credentials for NFS  XXX.
648	 */
649
650	if (sc->vnode) {
651		struct uio auio;
652		struct iovec aiov;
653
654		tmpbuf = malloc(sc->secsize, M_TEMP, M_WAITOK);
655		bzero(&auio, sizeof(auio));
656
657		aiov.iov_base = tmpbuf;
658		aiov.iov_len = sc->secsize;
659		auio.uio_iov = &aiov;
660		auio.uio_iovcnt = 1;
661		auio.uio_offset = 0;
662		auio.uio_rw = UIO_READ;
663		auio.uio_segflg = UIO_SYSSPACE;
664		auio.uio_resid = aiov.iov_len;
665		vn_lock(sc->vnode, LK_EXCLUSIVE | LK_RETRY, curproc);
666		error = VOP_READ(sc->vnode, &auio, 0, sc->cred);
667		VOP_UNLOCK(sc->vnode, 0, curproc);
668		free(tmpbuf, M_TEMP);
669	}
670	return (error);
671}
672
673static int
674mdcreate_vnode(struct md_ioctl *mdio, struct proc *p)
675{
676	struct md_s *sc;
677	struct vattr vattr;
678	struct nameidata nd;
679	int error, flags;
680
681	if (mdio->md_options & MD_AUTOUNIT) {
682		sc = mdnew(-1);
683		mdio->md_unit = sc->unit;
684	} else {
685		sc = mdnew(mdio->md_unit);
686	}
687	if (sc == NULL)
688		return (EBUSY);
689
690	sc->type = MD_VNODE;
691
692	flags = FREAD|FWRITE;
693	NDINIT(&nd, LOOKUP, FOLLOW, UIO_USERSPACE, mdio->md_file, p);
694	error = vn_open(&nd, &flags, 0);
695	if (error) {
696		if (error != EACCES && error != EPERM && error != EROFS)
697			return (error);
698		flags &= ~FWRITE;
699		sc->flags |= MD_READONLY;
700		NDINIT(&nd, LOOKUP, FOLLOW, UIO_USERSPACE, mdio->md_file, p);
701		error = vn_open(&nd, &flags, 0);
702		if (error)
703			return (error);
704	}
705	NDFREE(&nd, NDF_ONLY_PNBUF);
706	if (nd.ni_vp->v_type != VREG ||
707	    (error = VOP_GETATTR(nd.ni_vp, &vattr, p->p_ucred, p))) {
708		VOP_UNLOCK(nd.ni_vp, 0, p);
709		(void) vn_close(nd.ni_vp, flags, p->p_ucred, p);
710		return (error ? error : EINVAL);
711	}
712	VOP_UNLOCK(nd.ni_vp, 0, p);
713	sc->secsize = DEV_BSIZE;
714	sc->vnode = nd.ni_vp;
715
716	/*
717	 * If the size is specified, override the file attributes.
718	 */
719	if (mdio->md_size)
720		sc->nsect = mdio->md_size;
721	else
722		sc->nsect = vattr.va_size / sc->secsize; /* XXX: round up ? */
723	error = mdsetcred(sc, p->p_ucred);
724	if (error) {
725		(void) vn_close(nd.ni_vp, flags, p->p_ucred, p);
726		return(error);
727	}
728	mdinit(sc);
729	return (0);
730}
731
732static int
733mddestroy(struct md_s *sc, struct md_ioctl *mdio, struct proc *p)
734{
735	unsigned u;
736
737	if (sc->dev != NULL)
738		disk_destroy(sc->dev);
739	if (sc->vnode != NULL)
740		(void)vn_close(sc->vnode, sc->flags & MD_READONLY ?  FREAD : (FREAD|FWRITE), sc->cred, p);
741	if (sc->cred != NULL)
742		crfree(sc->cred);
743	if (sc->object != NULL)
744		vm_pager_deallocate(sc->object);
745	if (sc->secp != NULL) {
746		for (u = 0; u < sc->nsecp; u++)
747			if ((uintptr_t)sc->secp[u] > 255)
748				FREE(sc->secp[u], M_MDSECT);
749		FREE(sc->secp, M_MD);
750	}
751	mddelete(sc);
752	return (0);
753}
754
755static int
756mdcreate_swap(struct md_ioctl *mdio, struct proc *p)
757{
758	int error;
759	struct md_s *sc;
760
761	if (mdio->md_options & MD_AUTOUNIT) {
762		sc = mdnew(-1);
763		mdio->md_unit = sc->unit;
764	} else {
765		sc = mdnew(mdio->md_unit);
766	}
767	if (sc == NULL)
768		return (EBUSY);
769
770	sc->type = MD_SWAP;
771
772	/*
773	 * Range check.  Disallow negative sizes or any size less then the
774	 * size of a page.  Then round to a page.
775	 */
776
777	if (mdio->md_size == 0)
778		return(EDOM);
779
780	/*
781	 * Allocate an OBJT_SWAP object.
782	 *
783	 * sc_secsize is PAGE_SIZE'd
784	 *
785	 * mdio->size is in DEV_BSIZE'd chunks.
786	 * Note the truncation.
787	 */
788
789	sc->secsize = PAGE_SIZE;
790	sc->nsect = mdio->md_size / (PAGE_SIZE / DEV_BSIZE);
791	sc->object = vm_pager_allocate(OBJT_SWAP, NULL, sc->secsize * (vm_offset_t)sc->nsect, VM_PROT_DEFAULT, 0);
792	if (mdio->md_options & MD_RESERVE) {
793		if (swap_pager_reserve(sc->object, 0, sc->nsect) < 0) {
794			vm_pager_deallocate(sc->object);
795			sc->object = NULL;
796			return(EDOM);
797		}
798	}
799	error = mdsetcred(sc, p->p_ucred);
800	if (error)
801		mddestroy(sc, mdio, p);
802	else
803		mdinit(sc);
804	return(error);
805}
806
807static int
808mdctlioctl(dev_t dev, u_long cmd, caddr_t addr, int flags, struct proc *p)
809{
810	struct md_ioctl *mdio;
811	struct md_s *sc;
812
813	if (md_debug)
814		printf("mdctlioctl(%s %lx %p %x %p)\n",
815			devtoname(dev), cmd, addr, flags, p);
816
817	mdio = (struct md_ioctl *)addr;
818	switch (cmd) {
819	case MDIOCATTACH:
820		switch (mdio->md_type) {
821		case MD_MALLOC:
822			return(mdcreate_malloc(mdio));
823		case MD_PRELOAD:
824			return(mdcreate_preload(mdio));
825		case MD_VNODE:
826			return(mdcreate_vnode(mdio, p));
827		case MD_SWAP:
828			return(mdcreate_swap(mdio, p));
829		default:
830			return (EINVAL);
831		}
832	case MDIOCDETACH:
833		if (mdio->md_file != NULL)
834			return(EINVAL);
835		if (mdio->md_size != 0)
836			return(EINVAL);
837		if (mdio->md_options != 0)
838			return(EINVAL);
839		sc = mdfind(mdio->md_unit);
840		if (sc == NULL)
841			return (ENOENT);
842		switch(sc->type) {
843		case MD_VNODE:
844		case MD_SWAP:
845		case MD_MALLOC:
846		case MD_PRELOAD:
847			return(mddestroy(sc, mdio, p));
848		default:
849			return (EOPNOTSUPP);
850		}
851	default:
852		return (ENOIOCTL);
853	};
854	return (ENOIOCTL);
855}
856
857static void
858md_preloaded(u_char *image, unsigned length)
859{
860	struct md_s *sc;
861
862	sc = mdnew(-1);
863	if (sc == NULL)
864		return;
865	sc->type = MD_PRELOAD;
866	sc->secsize = DEV_BSIZE;
867	sc->nsect = length / DEV_BSIZE;
868	sc->pl_ptr = image;
869	sc->pl_len = length;
870	if (sc->unit == 0)
871		mdrootready = 1;
872	mdinit(sc);
873}
874
875static void
876md_drvinit(void *unused)
877{
878
879	caddr_t mod;
880	caddr_t c;
881	u_char *ptr, *name, *type;
882	unsigned len;
883
884#ifdef MD_ROOT_SIZE
885	md_preloaded(mfs_root, MD_ROOT_SIZE*1024);
886#endif
887	mod = NULL;
888	while ((mod = preload_search_next_name(mod)) != NULL) {
889		name = (char *)preload_search_info(mod, MODINFO_NAME);
890		type = (char *)preload_search_info(mod, MODINFO_TYPE);
891		if (name == NULL)
892			continue;
893		if (type == NULL)
894			continue;
895		if (strcmp(type, "md_image") && strcmp(type, "mfs_root"))
896			continue;
897		c = preload_search_info(mod, MODINFO_ADDR);
898		ptr = *(u_char **)c;
899		c = preload_search_info(mod, MODINFO_SIZE);
900		len = *(unsigned *)c;
901		printf("md%d: Preloaded image <%s> %d bytes at %p\n",
902		   mdunits, name, len, ptr);
903		md_preloaded(ptr, len);
904	}
905	make_dev(&mdctl_cdevsw, 0xffff00ff, UID_ROOT, GID_WHEEL, 0600, "mdctl");
906}
907
908SYSINIT(mddev,SI_SUB_DRIVERS,SI_ORDER_MIDDLE+CDEV_MAJOR, md_drvinit,NULL)
909
910#ifdef MD_ROOT
911static void
912md_takeroot(void *junk)
913{
914	if (mdrootready)
915		rootdevnames[0] = "ufs:/dev/md0c";
916}
917
918SYSINIT(md_root, SI_SUB_MOUNT_ROOT, SI_ORDER_FIRST, md_takeroot, NULL);
919#endif
920
921