xref: /freebsd/sys/dev/md/md.c (revision ec09ef4ff8d0a377fd86c0c2e96a807a538fce4b)
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$
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/fcntl.h>
70 #include <sys/kernel.h>
71 #include <sys/linker.h>
72 #include <sys/lock.h>
73 #include <sys/malloc.h>
74 #include <sys/mdioctl.h>
75 #include <sys/namei.h>
76 #include <sys/proc.h>
77 #include <sys/queue.h>
78 #include <sys/sysctl.h>
79 #include <sys/vnode.h>
80 
81 #include <machine/atomic.h>
82 
83 #include <vm/vm.h>
84 #include <vm/vm_object.h>
85 #include <vm/vm_page.h>
86 #include <vm/vm_pager.h>
87 #include <vm/vm_zone.h>
88 #include <vm/swap_pager.h>
89 
90 #define MD_MODVER 1
91 
92 #ifndef MD_NSECT
93 #define MD_NSECT (10000 * 2)
94 #endif
95 
96 MALLOC_DEFINE(M_MD, "MD disk", "Memory Disk");
97 MALLOC_DEFINE(M_MDSECT, "MD sectors", "Memory Disk Sectors");
98 
99 static int md_debug;
100 SYSCTL_INT(_debug, OID_AUTO, mddebug, CTLFLAG_RW, &md_debug, 0, "");
101 
102 #if defined(MFS_ROOT) && !defined(MD_ROOT)
103 #define MD_ROOT MFS_ROOT
104 #warning "option MFS_ROOT has been superceeded by MD_ROOT"
105 #endif
106 
107 #if defined(MFS_ROOT_SIZE) && !defined(MD_ROOT_SIZE)
108 #define MD_ROOT_SIZE MFS_ROOT_SIZE
109 #warning "option MFS_ROOT_SIZE has been superceeded by MD_ROOT_SIZE"
110 #endif
111 
112 #if defined(MD_ROOT) && defined(MD_ROOT_SIZE)
113 /* Image gets put here: */
114 static u_char mfs_root[MD_ROOT_SIZE*1024] = "MFS Filesystem goes here";
115 static u_char end_mfs_root[] __unused = "MFS Filesystem had better STOP here";
116 #endif
117 
118 static int	mdrootready;
119 static int	mdunits;
120 static dev_t	status_dev = 0;
121 
122 
123 #define CDEV_MAJOR	95
124 
125 static d_strategy_t mdstrategy;
126 static d_open_t mdopen;
127 static d_ioctl_t mdioctl, mdctlioctl;
128 
129 static struct cdevsw md_cdevsw = {
130         /* open */      mdopen,
131         /* close */     nullclose,
132         /* read */      physread,
133         /* write */     physwrite,
134         /* ioctl */     mdioctl,
135         /* poll */      nopoll,
136         /* mmap */      nommap,
137         /* strategy */  mdstrategy,
138         /* name */      MD_NAME,
139         /* maj */       CDEV_MAJOR,
140         /* dump */      nodump,
141         /* psize */     nopsize,
142         /* flags */     D_DISK | D_CANFREE | D_MEMDISK,
143 };
144 
145 static struct cdevsw mdctl_cdevsw = {
146         /* open */      nullopen,
147         /* close */     nullclose,
148         /* read */      noread,
149         /* write */     nowrite,
150         /* ioctl */     mdctlioctl,
151         /* poll */      nopoll,
152         /* mmap */      nommap,
153         /* strategy */  nostrategy,
154         /* name */      MD_NAME,
155         /* maj */       CDEV_MAJOR
156 };
157 
158 static struct cdevsw mddisk_cdevsw;
159 
160 static LIST_HEAD(, md_s) md_softc_list = LIST_HEAD_INITIALIZER(&md_softc_list);
161 
162 struct md_s {
163 	int unit;
164 	LIST_ENTRY(md_s) list;
165 	struct devstat stats;
166 	struct bio_queue_head bio_queue;
167 	struct disk disk;
168 	dev_t dev;
169 	int busy;
170 	enum md_types type;
171 	unsigned nsect;
172 	unsigned secsize;
173 	unsigned flags;
174 
175 	/* MD_MALLOC related fields */
176 	u_char **secp;
177 
178 	/* MD_PRELOAD related fields */
179 	u_char *pl_ptr;
180 	unsigned pl_len;
181 
182 	/* MD_VNODE related fields */
183 	struct vnode *vnode;
184 	struct ucred *cred;
185 
186 	/* MD_OBJET related fields */
187 	vm_object_t object;
188 };
189 
190 static int
191 mdopen(dev_t dev, int flag, int fmt, struct proc *p)
192 {
193 	struct md_s *sc;
194 	struct disklabel *dl;
195 
196 	if (md_debug)
197 		printf("mdopen(%s %x %x %p)\n",
198 			devtoname(dev), flag, fmt, p);
199 
200 	sc = dev->si_drv1;
201 
202 	dl = &sc->disk.d_label;
203 	bzero(dl, sizeof(*dl));
204 	dl->d_secsize = sc->secsize;
205 	dl->d_nsectors = sc->nsect > 63 ? 63 : sc->nsect;
206 	dl->d_ntracks = 1;
207 	dl->d_secpercyl = dl->d_nsectors * dl->d_ntracks;
208 	dl->d_secperunit = sc->nsect;
209 	dl->d_ncylinders = dl->d_secperunit / dl->d_secpercyl;
210 	return (0);
211 }
212 
213 static int
214 mdioctl(dev_t dev, u_long cmd, caddr_t addr, int flags, struct proc *p)
215 {
216 
217 	if (md_debug)
218 		printf("mdioctl(%s %lx %p %x %p)\n",
219 			devtoname(dev), cmd, addr, flags, p);
220 
221 	return (ENOIOCTL);
222 }
223 
224 static void
225 mdstart_malloc(struct md_s *sc)
226 {
227 	int i;
228 	struct bio *bp;
229 	devstat_trans_flags dop;
230 	u_char *secp, **secpp, *dst;
231 	unsigned secno, nsec, secval, uc;
232 
233 	for (;;) {
234 		/* XXX: LOCK(unique unit numbers) */
235 		bp = bioq_first(&sc->bio_queue);
236 		if (bp)
237 			bioq_remove(&sc->bio_queue, bp);
238 		/* XXX: UNLOCK(unique unit numbers) */
239 		if (!bp)
240 			break;
241 
242 		devstat_start_transaction(&sc->stats);
243 
244 		if (bp->bio_cmd == BIO_DELETE)
245 			dop = DEVSTAT_NO_DATA;
246 		else if (bp->bio_cmd == BIO_READ)
247 			dop = DEVSTAT_READ;
248 		else
249 			dop = DEVSTAT_WRITE;
250 
251 		nsec = bp->bio_bcount / sc->secsize;
252 		secno = bp->bio_pblkno;
253 		dst = bp->bio_data;
254 		while (nsec--) {
255 			secpp = &sc->secp[secno];
256 			if ((uintptr_t)*secpp > 255) {
257 				secp = *secpp;
258 				secval = 0;
259 			} else {
260 				secp = NULL;
261 				secval = (uintptr_t) *secpp;
262 			}
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 (!(sc->flags & MD_RESERVE) && secp != NULL) {
270 					FREE(secp, M_MDSECT);
271 					*secpp = 0;
272 				}
273 			} else if (bp->bio_cmd == BIO_READ) {
274 				if (secp != NULL) {
275 					bcopy(secp, dst, sc->secsize);
276 				} else if (secval) {
277 					for (i = 0; i < sc->secsize; i++)
278 						dst[i] = secval;
279 				} else {
280 					bzero(dst, sc->secsize);
281 				}
282 			} else {
283 				if (sc->flags & MD_COMPRESS) {
284 					uc = dst[0];
285 					for (i = 1; i < sc->secsize; i++)
286 						if (dst[i] != uc)
287 							break;
288 				} else {
289 					i = 0;
290 					uc = 0;
291 				}
292 				if (i == sc->secsize) {
293 					if (secp)
294 						FREE(secp, M_MDSECT);
295 					*secpp = (u_char *)(uintptr_t)uc;
296 				} else {
297 					if (secp == NULL)
298 						MALLOC(secp, u_char *, sc->secsize, M_MDSECT, M_WAITOK);
299 					bcopy(dst, secp, sc->secsize);
300 					*secpp = secp;
301 				}
302 			}
303 			secno++;
304 			dst += sc->secsize;
305 		}
306 		bp->bio_resid = 0;
307 		devstat_end_transaction_bio(&sc->stats, bp);
308 		biodone(bp);
309 	}
310 	return;
311 }
312 
313 
314 static void
315 mdstart_preload(struct md_s *sc)
316 {
317 	struct bio *bp;
318 	devstat_trans_flags dop;
319 
320 	for (;;) {
321 		/* XXX: LOCK(unique unit numbers) */
322 		bp = bioq_first(&sc->bio_queue);
323 		if (bp)
324 			bioq_remove(&sc->bio_queue, bp);
325 		/* XXX: UNLOCK(unique unit numbers) */
326 		if (!bp)
327 			break;
328 
329 		devstat_start_transaction(&sc->stats);
330 
331 		if (bp->bio_cmd == BIO_DELETE) {
332 			dop = DEVSTAT_NO_DATA;
333 		} else if (bp->bio_cmd == BIO_READ) {
334 			dop = DEVSTAT_READ;
335 			bcopy(sc->pl_ptr + (bp->bio_pblkno << DEV_BSHIFT), bp->bio_data, bp->bio_bcount);
336 		} else {
337 			dop = DEVSTAT_WRITE;
338 			bcopy(bp->bio_data, sc->pl_ptr + (bp->bio_pblkno << DEV_BSHIFT), bp->bio_bcount);
339 		}
340 		bp->bio_resid = 0;
341 		devstat_end_transaction_bio(&sc->stats, bp);
342 		biodone(bp);
343 	}
344 	return;
345 }
346 
347 static void
348 mdstart_vnode(struct md_s *sc)
349 {
350 	int error;
351 	struct bio *bp;
352 	struct uio auio;
353 	struct iovec aiov;
354 	struct mount *mp;
355 
356 	/*
357 	 * VNODE I/O
358 	 *
359 	 * If an error occurs, we set BIO_ERROR but we do not set
360 	 * B_INVAL because (for a write anyway), the buffer is
361 	 * still valid.
362 	 */
363 
364 	for (;;) {
365 		/* XXX: LOCK(unique unit numbers) */
366 		bp = bioq_first(&sc->bio_queue);
367 		if (bp)
368 			bioq_remove(&sc->bio_queue, bp);
369 		/* XXX: UNLOCK(unique unit numbers) */
370 		if (!bp)
371 			break;
372 
373 		devstat_start_transaction(&sc->stats);
374 
375 		bzero(&auio, sizeof(auio));
376 
377 		aiov.iov_base = bp->bio_data;
378 		aiov.iov_len = bp->bio_bcount;
379 		auio.uio_iov = &aiov;
380 		auio.uio_iovcnt = 1;
381 		auio.uio_offset = (vm_ooffset_t)bp->bio_pblkno * sc->secsize;
382 		auio.uio_segflg = UIO_SYSSPACE;
383 		if(bp->bio_cmd == BIO_READ)
384 			auio.uio_rw = UIO_READ;
385 		else
386 			auio.uio_rw = UIO_WRITE;
387 		auio.uio_resid = bp->bio_bcount;
388 		auio.uio_procp = curproc;
389 		if (VOP_ISLOCKED(sc->vnode, NULL))
390 			vprint("unexpected md driver lock", sc->vnode);
391 		if (bp->bio_cmd == BIO_READ) {
392 			vn_lock(sc->vnode, LK_EXCLUSIVE | LK_RETRY, curproc);
393 			error = VOP_READ(sc->vnode, &auio, 0, sc->cred);
394 		} else {
395 			(void) vn_start_write(sc->vnode, &mp, V_WAIT);
396 			vn_lock(sc->vnode, LK_EXCLUSIVE | LK_RETRY, curproc);
397 			error = VOP_WRITE(sc->vnode, &auio, 0, sc->cred);
398 			vn_finished_write(mp);
399 		}
400 		VOP_UNLOCK(sc->vnode, 0, curproc);
401 		bp->bio_resid = auio.uio_resid;
402 
403 		if (error) {
404 			bp->bio_error = error;
405 			bp->bio_flags |= BIO_ERROR;
406 		}
407 		devstat_end_transaction_bio(&sc->stats, bp);
408 		biodone(bp);
409 	}
410 	return;
411 }
412 
413 static void
414 mdstart_swap(struct md_s *sc)
415 {
416 	struct bio *bp;
417 
418 	for (;;) {
419 		/* XXX: LOCK(unique unit numbers) */
420 		bp = bioq_first(&sc->bio_queue);
421 		if (bp)
422 			bioq_remove(&sc->bio_queue, bp);
423 		/* XXX: UNLOCK(unique unit numbers) */
424 		if (!bp)
425 			break;
426 
427 #if 0
428 		devstat_start_transaction(&sc->stats);
429 #endif
430 
431 		if ((bp->bio_cmd == BIO_DELETE) && (sc->flags & MD_RESERVE))
432 			biodone(bp);
433 		else
434 			vm_pager_strategy(sc->object, bp);
435 
436 #if 0
437 		devstat_end_transaction_bio(&sc->stats, bp);
438 #endif
439 	}
440 	return;
441 }
442 
443 static void
444 mdstrategy(struct bio *bp)
445 {
446 	struct md_s *sc;
447 
448 	if (md_debug > 1)
449 		printf("mdstrategy(%p) %s %x, %d, %ld, %p)\n",
450 		    bp, devtoname(bp->bio_dev), bp->bio_flags, bp->bio_blkno,
451 		    bp->bio_bcount / DEV_BSIZE, bp->bio_data);
452 
453 	sc = bp->bio_dev->si_drv1;
454 
455 	/* XXX: LOCK(sc->lock) */
456 	bioqdisksort(&sc->bio_queue, bp);
457 	/* XXX: UNLOCK(sc->lock) */
458 
459 	if (atomic_cmpset_int(&sc->busy, 0, 1) == 0)
460 		return;
461 
462 	switch (sc->type) {
463 	case MD_MALLOC:
464 		mdstart_malloc(sc);
465 		break;
466 	case MD_PRELOAD:
467 		mdstart_preload(sc);
468 		break;
469 	case MD_VNODE:
470 		mdstart_vnode(sc);
471 		break;
472 	case MD_SWAP:
473 		mdstart_swap(sc);
474 		break;
475 	default:
476 		panic("Impossible md(type)");
477 		break;
478 	}
479 	sc->busy = 0;
480 }
481 
482 static struct md_s *
483 mdfind(int unit)
484 {
485 	struct md_s *sc;
486 
487 	/* XXX: LOCK(unique unit numbers) */
488 	LIST_FOREACH(sc, &md_softc_list, list) {
489 		if (sc->unit == unit)
490 			break;
491 	}
492 	/* XXX: UNLOCK(unique unit numbers) */
493 	return (sc);
494 }
495 
496 static struct md_s *
497 mdnew(int unit)
498 {
499 	struct md_s *sc;
500 	int max = -1;
501 
502 	/* XXX: LOCK(unique unit numbers) */
503 	LIST_FOREACH(sc, &md_softc_list, list) {
504 		if (sc->unit == unit) {
505 			/* XXX: UNLOCK(unique unit numbers) */
506 			return (NULL);
507 		}
508 		if (sc->unit > max)
509 			max = sc->unit;
510 	}
511 	if (unit == -1)
512 		unit = max + 1;
513 	if (unit > DKMAXUNIT)
514 		return (NULL);
515 	MALLOC(sc, struct md_s *,sizeof(*sc), M_MD, M_WAITOK | M_ZERO);
516 	sc->unit = unit;
517 	LIST_INSERT_HEAD(&md_softc_list, sc, list);
518 	/* XXX: UNLOCK(unique unit numbers) */
519 	return (sc);
520 }
521 
522 static void
523 mddelete(struct md_s *sc)
524 {
525 
526 	devstat_remove_entry(&sc->stats);
527 	/* XXX: LOCK(unique unit numbers) */
528 	LIST_REMOVE(sc, list);
529 	/* XXX: UNLOCK(unique unit numbers) */
530 	FREE(sc, M_MD);
531 }
532 
533 static void
534 mdinit(struct md_s *sc)
535 {
536 
537 	bioq_init(&sc->bio_queue);
538 	devstat_add_entry(&sc->stats, MD_NAME, sc->unit, sc->secsize,
539 		DEVSTAT_NO_ORDERED_TAGS,
540 		DEVSTAT_TYPE_DIRECT | DEVSTAT_TYPE_IF_OTHER,
541 		DEVSTAT_PRIORITY_OTHER);
542 	sc->dev = disk_create(sc->unit, &sc->disk, 0, &md_cdevsw, &mddisk_cdevsw);
543 	sc->dev->si_drv1 = sc;
544 }
545 
546 /*
547  * XXX: we should check that the range they feed us is mapped.
548  * XXX: we should implement read-only.
549  */
550 
551 static int
552 mdcreate_preload(struct md_ioctl *mdio)
553 {
554 	struct md_s *sc;
555 
556 	if (mdio->md_size == 0)
557 		return(EINVAL);
558 	if (mdio->md_options & ~(MD_AUTOUNIT))
559 		return(EINVAL);
560 	if (mdio->md_options & MD_AUTOUNIT) {
561 		sc = mdnew(-1);
562 		if (sc == NULL)
563 			return (ENOMEM);
564 		mdio->md_unit = sc->unit;
565 	} else {
566 		sc = mdnew(mdio->md_unit);
567 		if (sc == NULL)
568 			return (EBUSY);
569 	}
570 	sc->type = MD_PRELOAD;
571 	sc->secsize = DEV_BSIZE;
572 	sc->nsect = mdio->md_size;
573 	/* Cast to pointer size, then to pointer to avoid warning */
574 	sc->pl_ptr = (u_char *)(uintptr_t)mdio->md_base;
575 	sc->pl_len = (mdio->md_size << DEV_BSHIFT);
576 	mdinit(sc);
577 	return (0);
578 }
579 
580 
581 static int
582 mdcreate_malloc(struct md_ioctl *mdio)
583 {
584 	struct md_s *sc;
585 	unsigned u;
586 
587 	if (mdio->md_size == 0)
588 		return(EINVAL);
589 	if (mdio->md_options & ~(MD_AUTOUNIT | MD_COMPRESS | MD_RESERVE))
590 		return(EINVAL);
591 	/* Compression doesn't make sense if we have reserved space */
592 	if (mdio->md_options & MD_RESERVE)
593 		mdio->md_options &= ~MD_COMPRESS;
594 	if (mdio->md_options & MD_AUTOUNIT) {
595 		sc = mdnew(-1);
596 		if (sc == NULL)
597 			return (ENOMEM);
598 		mdio->md_unit = sc->unit;
599 	} else {
600 		sc = mdnew(mdio->md_unit);
601 		if (sc == NULL)
602 			return (EBUSY);
603 	}
604 	sc->type = MD_MALLOC;
605 	sc->secsize = DEV_BSIZE;
606 	sc->nsect = mdio->md_size;
607 	sc->flags = mdio->md_options & MD_COMPRESS;
608 	MALLOC(sc->secp, u_char **, sc->nsect * sizeof(u_char *), M_MD, M_WAITOK | M_ZERO);
609 	if (mdio->md_options & MD_RESERVE) {
610 		for (u = 0; u < sc->nsect; u++)
611 			MALLOC(sc->secp[u], u_char *, DEV_BSIZE, M_MDSECT, M_WAITOK | M_ZERO);
612 	}
613 	printf("%s%d: Malloc disk\n", MD_NAME, sc->unit);
614 	mdinit(sc);
615 	return (0);
616 }
617 
618 
619 static int
620 mdsetcred(struct md_s *sc, struct ucred *cred)
621 {
622 	char *tmpbuf;
623 	int error = 0;
624 
625 	/*
626 	 * Set credits in our softc
627 	 */
628 
629 	if (sc->cred)
630 		crfree(sc->cred);
631 	sc->cred = crdup(cred);
632 
633 	/*
634 	 * Horrible kludge to establish credentials for NFS  XXX.
635 	 */
636 
637 	if (sc->vnode) {
638 		struct uio auio;
639 		struct iovec aiov;
640 
641 		tmpbuf = malloc(sc->secsize, M_TEMP, M_WAITOK);
642 		bzero(&auio, sizeof(auio));
643 
644 		aiov.iov_base = tmpbuf;
645 		aiov.iov_len = sc->secsize;
646 		auio.uio_iov = &aiov;
647 		auio.uio_iovcnt = 1;
648 		auio.uio_offset = 0;
649 		auio.uio_rw = UIO_READ;
650 		auio.uio_segflg = UIO_SYSSPACE;
651 		auio.uio_resid = aiov.iov_len;
652 		vn_lock(sc->vnode, LK_EXCLUSIVE | LK_RETRY, curproc);
653 		error = VOP_READ(sc->vnode, &auio, 0, sc->cred);
654 		VOP_UNLOCK(sc->vnode, 0, curproc);
655 		free(tmpbuf, M_TEMP);
656 	}
657 	return (error);
658 }
659 
660 static int
661 mdcreate_vnode(struct md_ioctl *mdio, struct proc *p)
662 {
663 	struct md_s *sc;
664 	struct vattr vattr;
665 	struct nameidata nd;
666 	int error, flags;
667 
668 	if (mdio->md_options & MD_AUTOUNIT) {
669 		sc = mdnew(-1);
670 		mdio->md_unit = sc->unit;
671 	} else {
672 		sc = mdnew(mdio->md_unit);
673 	}
674 	if (sc == NULL)
675 		return (EBUSY);
676 
677 	sc->type = MD_VNODE;
678 
679 	flags = FREAD|FWRITE;
680 	NDINIT(&nd, LOOKUP, FOLLOW, UIO_USERSPACE, mdio->md_file, p);
681 	error = vn_open(&nd, &flags, 0);
682 	if (error) {
683 		if (error != EACCES && error != EPERM && error != EROFS)
684 			return (error);
685 		flags &= ~FWRITE;
686 		sc->flags |= MD_READONLY;
687 		NDINIT(&nd, LOOKUP, FOLLOW, UIO_USERSPACE, mdio->md_file, p);
688 		error = vn_open(&nd, &flags, 0);
689 		if (error)
690 			return (error);
691 	}
692 	NDFREE(&nd, NDF_ONLY_PNBUF);
693 	if (nd.ni_vp->v_type != VREG ||
694 	    (error = VOP_GETATTR(nd.ni_vp, &vattr, p->p_ucred, p))) {
695 		VOP_UNLOCK(nd.ni_vp, 0, p);
696 		(void) vn_close(nd.ni_vp, flags, p->p_ucred, p);
697 		return (error ? error : EINVAL);
698 	}
699 	VOP_UNLOCK(nd.ni_vp, 0, p);
700 	sc->secsize = DEV_BSIZE;
701 	sc->vnode = nd.ni_vp;
702 
703 	/*
704 	 * If the size is specified, override the file attributes.
705 	 */
706 	if (mdio->md_size)
707 		sc->nsect = mdio->md_size;
708 	else
709 		sc->nsect = vattr.va_size / sc->secsize; /* XXX: round up ? */
710 	error = mdsetcred(sc, p->p_ucred);
711 	if (error) {
712 		(void) vn_close(nd.ni_vp, flags, p->p_ucred, p);
713 		return(error);
714 	}
715 	mdinit(sc);
716 	return (0);
717 }
718 
719 static int
720 mddestroy(struct md_s *sc, struct md_ioctl *mdio, struct proc *p)
721 {
722 	unsigned u;
723 
724 	if (sc->dev != NULL)
725 		disk_destroy(sc->dev);
726 	if (sc->vnode != NULL)
727 		(void)vn_close(sc->vnode, sc->flags & MD_READONLY ?  FREAD : (FREAD|FWRITE), sc->cred, p);
728 	if (sc->cred != NULL)
729 		crfree(sc->cred);
730 	if (sc->object != NULL)
731 		vm_pager_deallocate(sc->object);
732 	if (sc->secp != NULL) {
733 		for (u = 0; u < sc->nsect; u++)
734 			if ((uintptr_t)sc->secp[u] > 255)
735 				FREE(sc->secp[u], M_MDSECT);
736 		FREE(sc->secp, M_MD);
737 	}
738 	mddelete(sc);
739 	return (0);
740 }
741 
742 static int
743 mdcreate_swap(struct md_ioctl *mdio, struct proc *p)
744 {
745 	int error;
746 	struct md_s *sc;
747 
748 	if (mdio->md_options & MD_AUTOUNIT) {
749 		sc = mdnew(-1);
750 		mdio->md_unit = sc->unit;
751 	} else {
752 		sc = mdnew(mdio->md_unit);
753 	}
754 	if (sc == NULL)
755 		return (EBUSY);
756 
757 	sc->type = MD_SWAP;
758 
759 	/*
760 	 * Range check.  Disallow negative sizes or any size less then the
761 	 * size of a page.  Then round to a page.
762 	 */
763 
764 	if (mdio->md_size == 0)
765 		return(EDOM);
766 
767 	/*
768 	 * Allocate an OBJT_SWAP object.
769 	 *
770 	 * sc_secsize is PAGE_SIZE'd
771 	 *
772 	 * mdio->size is in DEV_BSIZE'd chunks.
773 	 * Note the truncation.
774 	 */
775 
776 	sc->secsize = PAGE_SIZE;
777 	sc->nsect = mdio->md_size / (PAGE_SIZE / DEV_BSIZE);
778 	sc->object = vm_pager_allocate(OBJT_SWAP, NULL, sc->secsize * (vm_offset_t)sc->nsect, VM_PROT_DEFAULT, 0);
779 	if (mdio->md_options & MD_RESERVE) {
780 		if (swap_pager_reserve(sc->object, 0, sc->nsect) < 0) {
781 			vm_pager_deallocate(sc->object);
782 			sc->object = NULL;
783 			return(EDOM);
784 		}
785 	}
786 	error = mdsetcred(sc, p->p_ucred);
787 	if (error)
788 		mddestroy(sc, mdio, p);
789 	else
790 		mdinit(sc);
791 	return(error);
792 }
793 
794 static int
795 mdctlioctl(dev_t dev, u_long cmd, caddr_t addr, int flags, struct proc *p)
796 {
797 	struct md_ioctl *mdio;
798 	struct md_s *sc;
799 
800 	if (md_debug)
801 		printf("mdctlioctl(%s %lx %p %x %p)\n",
802 			devtoname(dev), cmd, addr, flags, p);
803 
804 	mdio = (struct md_ioctl *)addr;
805 	switch (cmd) {
806 	case MDIOCATTACH:
807 		switch (mdio->md_type) {
808 		case MD_MALLOC:
809 			return(mdcreate_malloc(mdio));
810 		case MD_PRELOAD:
811 			return(mdcreate_preload(mdio));
812 		case MD_VNODE:
813 			return(mdcreate_vnode(mdio, p));
814 		case MD_SWAP:
815 			return(mdcreate_swap(mdio, p));
816 		default:
817 			return (EINVAL);
818 		}
819 	case MDIOCDETACH:
820 		if (mdio->md_file != NULL)
821 			return(EINVAL);
822 		if (mdio->md_size != 0)
823 			return(EINVAL);
824 		if (mdio->md_options != 0)
825 			return(EINVAL);
826 		sc = mdfind(mdio->md_unit);
827 		if (sc == NULL)
828 			return (ENOENT);
829 		switch(sc->type) {
830 		case MD_VNODE:
831 		case MD_SWAP:
832 		case MD_MALLOC:
833 		case MD_PRELOAD:
834 			return(mddestroy(sc, mdio, p));
835 		default:
836 			return (EOPNOTSUPP);
837 		}
838 	case MDIOCQUERY:
839 		sc = mdfind(mdio->md_unit);
840 		if (sc == NULL)
841 			return (ENOENT);
842 		mdio->md_type = sc->type;
843 		mdio->md_options = sc->flags;
844 		switch (sc->type) {
845 		case MD_MALLOC:
846 			mdio->md_size = sc->nsect;
847 			break;
848 		case MD_PRELOAD:
849 			mdio->md_size = sc->nsect;
850 			(u_char *)(uintptr_t)mdio->md_base = sc->pl_ptr;
851 			break;
852 		case MD_SWAP:
853 			mdio->md_size = sc->nsect * (PAGE_SIZE / DEV_BSIZE);
854 			break;
855 		case MD_VNODE:
856 			mdio->md_size = sc->nsect;
857 			/* XXX fill this in */
858 			mdio->md_file = NULL;
859 			break;
860 		}
861 		return (0);
862 	default:
863 		return (ENOIOCTL);
864 	};
865 	return (ENOIOCTL);
866 }
867 
868 static void
869 md_preloaded(u_char *image, unsigned length)
870 {
871 	struct md_s *sc;
872 
873 	sc = mdnew(-1);
874 	if (sc == NULL)
875 		return;
876 	sc->type = MD_PRELOAD;
877 	sc->secsize = DEV_BSIZE;
878 	sc->nsect = length / DEV_BSIZE;
879 	sc->pl_ptr = image;
880 	sc->pl_len = length;
881 	if (sc->unit == 0)
882 		mdrootready = 1;
883 	mdinit(sc);
884 }
885 
886 static void
887 md_drvinit(void *unused)
888 {
889 
890 	caddr_t mod;
891 	caddr_t c;
892 	u_char *ptr, *name, *type;
893 	unsigned len;
894 
895 #ifdef MD_ROOT_SIZE
896 	md_preloaded(mfs_root, MD_ROOT_SIZE*1024);
897 #endif
898 	mod = NULL;
899 	while ((mod = preload_search_next_name(mod)) != NULL) {
900 		name = (char *)preload_search_info(mod, MODINFO_NAME);
901 		type = (char *)preload_search_info(mod, MODINFO_TYPE);
902 		if (name == NULL)
903 			continue;
904 		if (type == NULL)
905 			continue;
906 		if (strcmp(type, "md_image") && strcmp(type, "mfs_root"))
907 			continue;
908 		c = preload_search_info(mod, MODINFO_ADDR);
909 		ptr = *(u_char **)c;
910 		c = preload_search_info(mod, MODINFO_SIZE);
911 		len = *(unsigned *)c;
912 		printf("md%d: Preloaded image <%s> %d bytes at %p\n",
913 		   mdunits, name, len, ptr);
914 		md_preloaded(ptr, len);
915 	}
916 	status_dev = make_dev(&mdctl_cdevsw, 0xffff00ff, UID_ROOT, GID_WHEEL, 0600, "mdctl");
917 }
918 
919 static int
920 md_modevent(module_t mod, int type, void *data)
921 {
922         switch (type) {
923         case MOD_LOAD:
924 		md_drvinit(NULL);
925                 break;
926         case MOD_UNLOAD:
927 		if (!LIST_EMPTY(&md_softc_list))
928 			return EBUSY;
929                 if (status_dev)
930                         destroy_dev(status_dev);
931                 status_dev = 0;
932                 break;
933         default:
934                 break;
935         }
936         return 0;
937 }
938 
939 static moduledata_t md_mod = {
940         "md",
941         md_modevent,
942         NULL
943 };
944 DECLARE_MODULE(md, md_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE+CDEV_MAJOR);
945 MODULE_VERSION(md, MD_MODVER);
946 
947 
948 #ifdef MD_ROOT
949 static void
950 md_takeroot(void *junk)
951 {
952 	if (mdrootready)
953 		rootdevnames[0] = "ufs:/dev/md0c";
954 }
955 
956 SYSINIT(md_root, SI_SUB_MOUNT_ROOT, SI_ORDER_FIRST, md_takeroot, NULL);
957 #endif
958 
959