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