xref: /freebsd/sys/dev/md/md.c (revision dce6e6518b85561495cff38a3074a69d29d58a55)
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_geom.h"
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/fcntl.h>
68 #include <sys/kernel.h>
69 #include <sys/kthread.h>
70 #include <sys/linker.h>
71 #include <sys/lock.h>
72 #include <sys/malloc.h>
73 #include <sys/mdioctl.h>
74 #include <sys/mutex.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 <geom/geom.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/swap_pager.h>
88 #include <vm/uma.h>
89 
90 #define MD_MODVER 1
91 
92 #define MD_SHUTDOWN 0x10000	/* Tell worker thread to terminate. */
93 
94 #ifndef MD_NSECT
95 #define MD_NSECT (10000 * 2)
96 #endif
97 
98 static MALLOC_DEFINE(M_MD, "MD disk", "Memory Disk");
99 static MALLOC_DEFINE(M_MDSECT, "MD sectors", "Memory Disk Sectors");
100 
101 static int md_debug;
102 SYSCTL_INT(_debug, OID_AUTO, mddebug, CTLFLAG_RW, &md_debug, 0, "");
103 
104 #if defined(MD_ROOT) && defined(MD_ROOT_SIZE)
105 /* Image gets put here: */
106 static u_char mfs_root[MD_ROOT_SIZE*1024] = "MFS Filesystem goes here";
107 static u_char end_mfs_root[] __unused = "MFS Filesystem had better STOP here";
108 #endif
109 
110 static int	mdrootready;
111 static int	mdunits;
112 static dev_t	status_dev = 0;
113 
114 #define CDEV_MAJOR	95
115 
116 static d_ioctl_t mdctlioctl;
117 
118 static struct cdevsw mdctl_cdevsw = {
119 	.d_open =	nullopen,
120 	.d_close =	nullclose,
121 	.d_ioctl =	mdctlioctl,
122 	.d_name =	MD_NAME,
123 	.d_maj =	CDEV_MAJOR
124 };
125 
126 
127 static LIST_HEAD(, md_s) md_softc_list = LIST_HEAD_INITIALIZER(&md_softc_list);
128 
129 #define NINDIR	(PAGE_SIZE / sizeof(uintptr_t))
130 #define NMASK	(NINDIR-1)
131 static int nshift;
132 
133 struct indir {
134 	uintptr_t	*array;
135 	uint		total;
136 	uint		used;
137 	uint		shift;
138 };
139 
140 struct md_s {
141 	int unit;
142 	LIST_ENTRY(md_s) list;
143 	struct bio_queue_head bio_queue;
144 	struct mtx queue_mtx;
145 	dev_t dev;
146 	enum md_types type;
147 	unsigned nsect;
148 	unsigned opencount;
149 	unsigned secsize;
150 	unsigned fwheads;
151 	unsigned fwsectors;
152 	unsigned flags;
153 	char name[20];
154 	struct proc *procp;
155 	struct g_geom *gp;
156 	struct g_provider *pp;
157 
158 	/* MD_MALLOC related fields */
159 	struct indir *indir;
160 	uma_zone_t uma;
161 
162 	/* MD_PRELOAD related fields */
163 	u_char *pl_ptr;
164 	unsigned pl_len;
165 
166 	/* MD_VNODE related fields */
167 	struct vnode *vnode;
168 	struct ucred *cred;
169 
170 	/* MD_SWAP related fields */
171 	vm_object_t object;
172 };
173 
174 static int mddestroy(struct md_s *sc, struct thread *td);
175 
176 static struct indir *
177 new_indir(uint shift)
178 {
179 	struct indir *ip;
180 
181 	ip = malloc(sizeof *ip, M_MD, M_NOWAIT | M_ZERO);
182 	if (ip == NULL)
183 		return (NULL);
184 	ip->array = malloc(sizeof(uintptr_t) * NINDIR,
185 	    M_MDSECT, M_NOWAIT | M_ZERO);
186 	if (ip->array == NULL) {
187 		free(ip, M_MD);
188 		return (NULL);
189 	}
190 	ip->total = NINDIR;
191 	ip->shift = shift;
192 	return (ip);
193 }
194 
195 static void
196 del_indir(struct indir *ip)
197 {
198 
199 	free(ip->array, M_MDSECT);
200 	free(ip, M_MD);
201 }
202 
203 static void
204 destroy_indir(struct md_s *sc, struct indir *ip)
205 {
206 	int i;
207 
208 	for (i = 0; i < NINDIR; i++) {
209 		if (!ip->array[i])
210 			continue;
211 		if (ip->shift)
212 			destroy_indir(sc, (struct indir*)(ip->array[i]));
213 		else if (ip->array[i] > 255)
214 			uma_zfree(sc->uma, (void *)(ip->array[i]));
215 	}
216 	del_indir(ip);
217 }
218 
219 /*
220  * This function does the math and alloctes the top level "indir" structure
221  * for a device of "size" sectors.
222  */
223 
224 static struct indir *
225 dimension(off_t size)
226 {
227 	off_t rcnt;
228 	struct indir *ip;
229 	int i, layer;
230 
231 	rcnt = size;
232 	layer = 0;
233 	while (rcnt > NINDIR) {
234 		rcnt /= NINDIR;
235 		layer++;
236 	}
237 	/* figure out log2(NINDIR) */
238 	for (i = NINDIR, nshift = -1; i; nshift++)
239 		i >>= 1;
240 
241 	/*
242 	 * XXX: the top layer is probably not fully populated, so we allocate
243 	 * too much space for ip->array in here.
244 	 */
245 	ip = malloc(sizeof *ip, M_MD, M_WAITOK | M_ZERO);
246 	ip->array = malloc(sizeof(uintptr_t) * NINDIR,
247 	    M_MDSECT, M_WAITOK | M_ZERO);
248 	ip->total = NINDIR;
249 	ip->shift = layer * nshift;
250 	return (ip);
251 }
252 
253 /*
254  * Read a given sector
255  */
256 
257 static uintptr_t
258 s_read(struct indir *ip, off_t offset)
259 {
260 	struct indir *cip;
261 	int idx;
262 	uintptr_t up;
263 
264 	if (md_debug > 1)
265 		printf("s_read(%jd)\n", (intmax_t)offset);
266 	up = 0;
267 	for (cip = ip; cip != NULL;) {
268 		if (cip->shift) {
269 			idx = (offset >> cip->shift) & NMASK;
270 			up = cip->array[idx];
271 			cip = (struct indir *)up;
272 			continue;
273 		}
274 		idx = offset & NMASK;
275 		return (cip->array[idx]);
276 	}
277 	return (0);
278 }
279 
280 /*
281  * Write a given sector, prune the tree if the value is 0
282  */
283 
284 static int
285 s_write(struct indir *ip, off_t offset, uintptr_t ptr)
286 {
287 	struct indir *cip, *lip[10];
288 	int idx, li;
289 	uintptr_t up;
290 
291 	if (md_debug > 1)
292 		printf("s_write(%jd, %p)\n", (intmax_t)offset, (void *)ptr);
293 	up = 0;
294 	li = 0;
295 	cip = ip;
296 	for (;;) {
297 		lip[li++] = cip;
298 		if (cip->shift) {
299 			idx = (offset >> cip->shift) & NMASK;
300 			up = cip->array[idx];
301 			if (up != 0) {
302 				cip = (struct indir *)up;
303 				continue;
304 			}
305 			/* Allocate branch */
306 			cip->array[idx] =
307 			    (uintptr_t)new_indir(cip->shift - nshift);
308 			if (cip->array[idx] == 0)
309 				return (ENOSPC);
310 			cip->used++;
311 			up = cip->array[idx];
312 			cip = (struct indir *)up;
313 			continue;
314 		}
315 		/* leafnode */
316 		idx = offset & NMASK;
317 		up = cip->array[idx];
318 		if (up != 0)
319 			cip->used--;
320 		cip->array[idx] = ptr;
321 		if (ptr != 0)
322 			cip->used++;
323 		break;
324 	}
325 	if (cip->used != 0 || li == 1)
326 		return (0);
327 	li--;
328 	while (cip->used == 0 && cip != ip) {
329 		li--;
330 		idx = (offset >> lip[li]->shift) & NMASK;
331 		up = lip[li]->array[idx];
332 		KASSERT(up == (uintptr_t)cip, ("md screwed up"));
333 		del_indir(cip);
334 		lip[li]->array[idx] = 0;
335 		lip[li]->used--;
336 		cip = lip[li];
337 	}
338 	return (0);
339 }
340 
341 
342 struct g_class g_md_class = {
343 	.name = "MD",
344 };
345 
346 static int
347 g_md_access(struct g_provider *pp, int r, int w, int e)
348 {
349 	struct md_s *sc;
350 
351 	sc = pp->geom->softc;
352 	if (sc == NULL)
353 		return (ENXIO);
354 	r += pp->acr;
355 	w += pp->acw;
356 	e += pp->ace;
357 	if ((pp->acr + pp->acw + pp->ace) == 0 && (r + w + e) > 0) {
358 		sc->opencount = 1;
359 	} else if ((pp->acr + pp->acw + pp->ace) > 0 && (r + w + e) == 0) {
360 		sc->opencount = 0;
361 	}
362 	return (0);
363 }
364 
365 static void
366 g_md_start(struct bio *bp)
367 {
368 	struct md_s *sc;
369 
370 	sc = bp->bio_to->geom->softc;
371 
372 	bp->bio_blkno = bp->bio_offset >> DEV_BSHIFT;
373 	bp->bio_pblkno = bp->bio_offset / sc->secsize;
374 	bp->bio_bcount = bp->bio_length;
375 	mtx_lock(&sc->queue_mtx);
376 	bioq_disksort(&sc->bio_queue, bp);
377 	mtx_unlock(&sc->queue_mtx);
378 
379 	wakeup(sc);
380 }
381 
382 DECLARE_GEOM_CLASS(g_md_class, g_md);
383 
384 
385 static int
386 mdstart_malloc(struct md_s *sc, struct bio *bp)
387 {
388 	int i, error;
389 	u_char *dst;
390 	unsigned secno, nsec, uc;
391 	uintptr_t sp, osp;
392 
393 	nsec = bp->bio_bcount / sc->secsize;
394 	secno = bp->bio_pblkno;
395 	dst = bp->bio_data;
396 	error = 0;
397 	while (nsec--) {
398 		osp = s_read(sc->indir, secno);
399 		if (bp->bio_cmd == BIO_DELETE) {
400 			if (osp != 0)
401 				error = s_write(sc->indir, secno, 0);
402 		} else if (bp->bio_cmd == BIO_READ) {
403 			if (osp == 0)
404 				bzero(dst, sc->secsize);
405 			else if (osp <= 255)
406 				for (i = 0; i < sc->secsize; i++)
407 					dst[i] = osp;
408 			else
409 				bcopy((void *)osp, dst, sc->secsize);
410 			osp = 0;
411 		} else if (bp->bio_cmd == BIO_WRITE) {
412 			if (sc->flags & MD_COMPRESS) {
413 				uc = dst[0];
414 				for (i = 1; i < sc->secsize; i++)
415 					if (dst[i] != uc)
416 						break;
417 			} else {
418 				i = 0;
419 				uc = 0;
420 			}
421 			if (i == sc->secsize) {
422 				if (osp != uc)
423 					error = s_write(sc->indir, secno, uc);
424 			} else {
425 				if (osp <= 255) {
426 					sp = (uintptr_t) uma_zalloc(
427 					    sc->uma, M_NOWAIT);
428 					if (sp == 0) {
429 						error = ENOSPC;
430 						break;
431 					}
432 					bcopy(dst, (void *)sp, sc->secsize);
433 					error = s_write(sc->indir, secno, sp);
434 				} else {
435 					bcopy(dst, (void *)osp, sc->secsize);
436 					osp = 0;
437 				}
438 			}
439 		} else {
440 			error = EOPNOTSUPP;
441 		}
442 		if (osp > 255)
443 			uma_zfree(sc->uma, (void*)osp);
444 		if (error)
445 			break;
446 		secno++;
447 		dst += sc->secsize;
448 	}
449 	bp->bio_resid = 0;
450 	return (error);
451 }
452 
453 static int
454 mdstart_preload(struct md_s *sc, struct bio *bp)
455 {
456 
457 	if (bp->bio_cmd == BIO_DELETE) {
458 	} else if (bp->bio_cmd == BIO_READ) {
459 		bcopy(sc->pl_ptr + (bp->bio_pblkno << DEV_BSHIFT), bp->bio_data, bp->bio_bcount);
460 	} else {
461 		bcopy(bp->bio_data, sc->pl_ptr + (bp->bio_pblkno << DEV_BSHIFT), bp->bio_bcount);
462 	}
463 	bp->bio_resid = 0;
464 	return (0);
465 }
466 
467 static int
468 mdstart_vnode(struct md_s *sc, struct bio *bp)
469 {
470 	int error;
471 	struct uio auio;
472 	struct iovec aiov;
473 	struct mount *mp;
474 
475 	/*
476 	 * VNODE I/O
477 	 *
478 	 * If an error occurs, we set BIO_ERROR but we do not set
479 	 * B_INVAL because (for a write anyway), the buffer is
480 	 * still valid.
481 	 */
482 
483 	bzero(&auio, sizeof(auio));
484 
485 	aiov.iov_base = bp->bio_data;
486 	aiov.iov_len = bp->bio_bcount;
487 	auio.uio_iov = &aiov;
488 	auio.uio_iovcnt = 1;
489 	auio.uio_offset = (vm_ooffset_t)bp->bio_pblkno * sc->secsize;
490 	auio.uio_segflg = UIO_SYSSPACE;
491 	if(bp->bio_cmd == BIO_READ)
492 		auio.uio_rw = UIO_READ;
493 	else
494 		auio.uio_rw = UIO_WRITE;
495 	auio.uio_resid = bp->bio_bcount;
496 	auio.uio_td = curthread;
497 	/*
498 	 * When reading set IO_DIRECT to try to avoid double-caching
499 	 * the data.  When writing IO_DIRECT is not optimal.
500 	 */
501 	if (bp->bio_cmd == BIO_READ) {
502 		vn_lock(sc->vnode, LK_EXCLUSIVE | LK_RETRY, curthread);
503 		error = VOP_READ(sc->vnode, &auio, IO_DIRECT, sc->cred);
504 	} else {
505 		(void) vn_start_write(sc->vnode, &mp, V_WAIT);
506 		vn_lock(sc->vnode, LK_EXCLUSIVE | LK_RETRY, curthread);
507 		error = VOP_WRITE(sc->vnode, &auio, 0, sc->cred);
508 		vn_finished_write(mp);
509 	}
510 	VOP_UNLOCK(sc->vnode, 0, curthread);
511 	bp->bio_resid = auio.uio_resid;
512 	return (error);
513 }
514 
515 static void
516 mddone_swap(struct bio *bp)
517 {
518 
519 	bp->bio_completed = bp->bio_length - bp->bio_resid;
520 	g_std_done(bp);
521 }
522 
523 static int
524 mdstart_swap(struct md_s *sc, struct bio *bp)
525 {
526 	{
527 	struct bio *bp2;
528 
529 	bp2 = g_clone_bio(bp);
530 	bp2->bio_done = mddone_swap;
531 	bp2->bio_blkno = bp2->bio_offset >> DEV_BSHIFT;
532 	bp2->bio_pblkno = bp2->bio_offset / sc->secsize;
533 	bp2->bio_bcount = bp2->bio_length;
534 	bp = bp2;
535 	}
536 
537 	bp->bio_resid = 0;
538 	if ((bp->bio_cmd == BIO_DELETE) && (sc->flags & MD_RESERVE))
539 		biodone(bp);
540 	else
541 		vm_pager_strategy(sc->object, bp);
542 	return (-1);
543 }
544 
545 static void
546 md_kthread(void *arg)
547 {
548 	struct md_s *sc;
549 	struct bio *bp;
550 	int error, hasgiant;
551 
552 	sc = arg;
553 	curthread->td_base_pri = PRIBIO;
554 
555 	switch (sc->type) {
556 	case MD_SWAP:
557 	case MD_VNODE:
558 		mtx_lock(&Giant);
559 		hasgiant = 1;
560 		break;
561 	case MD_MALLOC:
562 	case MD_PRELOAD:
563 	default:
564 		hasgiant = 0;
565 		break;
566 	}
567 
568 	for (;;) {
569 		mtx_lock(&sc->queue_mtx);
570 		bp = bioq_first(&sc->bio_queue);
571 		if (bp)
572 			bioq_remove(&sc->bio_queue, bp);
573 		if (!bp) {
574 			if (sc->flags & MD_SHUTDOWN) {
575 				mtx_unlock(&sc->queue_mtx);
576 				sc->procp = NULL;
577 				wakeup(&sc->procp);
578 				if (!hasgiant)
579 					mtx_lock(&Giant);
580 				kthread_exit(0);
581 			}
582 			msleep(sc, &sc->queue_mtx, PRIBIO | PDROP, "mdwait", 0);
583 			continue;
584 		}
585 		mtx_unlock(&sc->queue_mtx);
586 		if (bp->bio_cmd == BIO_GETATTR) {
587 			if (sc->fwsectors && sc->fwheads &&
588 			    (g_handleattr_int(bp, "GEOM::fwsectors",
589 			    sc->fwsectors) ||
590 			    g_handleattr_int(bp, "GEOM::fwheads",
591 			    sc->fwheads)))
592 				error = -1;
593 			else
594 				error = EOPNOTSUPP;
595 		} else {
596 			switch (sc->type) {
597 			case MD_MALLOC:
598 				error = mdstart_malloc(sc, bp);
599 				break;
600 			case MD_PRELOAD:
601 				error = mdstart_preload(sc, bp);
602 				break;
603 			case MD_VNODE:
604 				error = mdstart_vnode(sc, bp);
605 				break;
606 			case MD_SWAP:
607 				error = mdstart_swap(sc, bp);
608 				break;
609 			default:
610 				panic("Impossible md(type)");
611 				break;
612 			}
613 		}
614 
615 		if (error != -1) {
616 			bp->bio_completed = bp->bio_length;
617 			g_io_deliver(bp, error);
618 		}
619 	}
620 }
621 
622 static struct md_s *
623 mdfind(int unit)
624 {
625 	struct md_s *sc;
626 
627 	/* XXX: LOCK(unique unit numbers) */
628 	LIST_FOREACH(sc, &md_softc_list, list) {
629 		if (sc->unit == unit)
630 			break;
631 	}
632 	/* XXX: UNLOCK(unique unit numbers) */
633 	return (sc);
634 }
635 
636 static struct md_s *
637 mdnew(int unit)
638 {
639 	struct md_s *sc;
640 	int error, max = -1;
641 
642 	/* XXX: LOCK(unique unit numbers) */
643 	LIST_FOREACH(sc, &md_softc_list, list) {
644 		if (sc->unit == unit) {
645 			/* XXX: UNLOCK(unique unit numbers) */
646 			return (NULL);
647 		}
648 		if (sc->unit > max)
649 			max = sc->unit;
650 	}
651 	if (unit == -1)
652 		unit = max + 1;
653 	sc = (struct md_s *)malloc(sizeof *sc, M_MD, M_WAITOK | M_ZERO);
654 	sc->unit = unit;
655 	bioq_init(&sc->bio_queue);
656 	mtx_init(&sc->queue_mtx, "md bio queue", NULL, MTX_DEF);
657 	sprintf(sc->name, "md%d", unit);
658 	error = kthread_create(md_kthread, sc, &sc->procp, 0, 0,"%s", sc->name);
659 	if (error) {
660 		free(sc, M_MD);
661 		return (NULL);
662 	}
663 	LIST_INSERT_HEAD(&md_softc_list, sc, list);
664 	/* XXX: UNLOCK(unique unit numbers) */
665 	return (sc);
666 }
667 
668 static void
669 mdinit(struct md_s *sc)
670 {
671 
672 	struct g_geom *gp;
673 	struct g_provider *pp;
674 
675 	DROP_GIANT();
676 	g_topology_lock();
677 	gp = g_new_geomf(&g_md_class, "md%d", sc->unit);
678 	gp->start = g_md_start;
679 	gp->access = g_md_access;
680 	gp->softc = sc;
681 	pp = g_new_providerf(gp, "md%d", sc->unit);
682 	pp->mediasize = (off_t)sc->nsect * sc->secsize;
683 	pp->sectorsize = sc->secsize;
684 	sc->gp = gp;
685 	sc->pp = pp;
686 	g_error_provider(pp, 0);
687 	g_topology_unlock();
688 	PICKUP_GIANT();
689 }
690 
691 /*
692  * XXX: we should check that the range they feed us is mapped.
693  * XXX: we should implement read-only.
694  */
695 
696 static int
697 mdcreate_preload(struct md_ioctl *mdio)
698 {
699 	struct md_s *sc;
700 
701 	if (mdio->md_size == 0)
702 		return (EINVAL);
703 	if (mdio->md_options & ~(MD_AUTOUNIT))
704 		return (EINVAL);
705 	if (mdio->md_options & MD_AUTOUNIT) {
706 		sc = mdnew(-1);
707 		if (sc == NULL)
708 			return (ENOMEM);
709 		mdio->md_unit = sc->unit;
710 	} else {
711 		sc = mdnew(mdio->md_unit);
712 		if (sc == NULL)
713 			return (EBUSY);
714 	}
715 	sc->type = MD_PRELOAD;
716 	sc->secsize = DEV_BSIZE;
717 	sc->nsect = mdio->md_size;
718 	sc->flags = mdio->md_options & MD_FORCE;
719 	/* Cast to pointer size, then to pointer to avoid warning */
720 	sc->pl_ptr = (u_char *)(uintptr_t)mdio->md_base;
721 	sc->pl_len = (mdio->md_size << DEV_BSHIFT);
722 	mdinit(sc);
723 	return (0);
724 }
725 
726 
727 static int
728 mdcreate_malloc(struct md_ioctl *mdio)
729 {
730 	struct md_s *sc;
731 	off_t u;
732 	uintptr_t sp;
733 	int error;
734 
735 	error = 0;
736 	if (mdio->md_size == 0)
737 		return (EINVAL);
738 	if (mdio->md_options & ~(MD_AUTOUNIT | MD_COMPRESS | MD_RESERVE))
739 		return (EINVAL);
740 	if (mdio->md_secsize != 0 && !powerof2(mdio->md_secsize))
741 		return (EINVAL);
742 	/* Compression doesn't make sense if we have reserved space */
743 	if (mdio->md_options & MD_RESERVE)
744 		mdio->md_options &= ~MD_COMPRESS;
745 	if (mdio->md_options & MD_AUTOUNIT) {
746 		sc = mdnew(-1);
747 		if (sc == NULL)
748 			return (ENOMEM);
749 		mdio->md_unit = sc->unit;
750 	} else {
751 		sc = mdnew(mdio->md_unit);
752 		if (sc == NULL)
753 			return (EBUSY);
754 	}
755 	sc->type = MD_MALLOC;
756 	if (mdio->md_secsize != 0)
757 		sc->secsize = mdio->md_secsize;
758 	else
759 		sc->secsize = DEV_BSIZE;
760 	if (mdio->md_fwsectors != 0)
761 		sc->fwsectors = mdio->md_fwsectors;
762 	if (mdio->md_fwheads != 0)
763 		sc->fwheads = mdio->md_fwheads;
764 	sc->nsect = mdio->md_size;
765 	sc->nsect /= (sc->secsize / DEV_BSIZE);
766 	sc->flags = mdio->md_options & (MD_COMPRESS | MD_FORCE);
767 	sc->indir = dimension(sc->nsect);
768 	sc->uma = uma_zcreate(sc->name, sc->secsize,
769 	    NULL, NULL, NULL, NULL, 0x1ff, 0);
770 	if (mdio->md_options & MD_RESERVE) {
771 		for (u = 0; u < sc->nsect; u++) {
772 			sp = (uintptr_t) uma_zalloc(sc->uma, M_NOWAIT | M_ZERO);
773 			if (sp != 0)
774 				error = s_write(sc->indir, u, sp);
775 			else
776 				error = ENOMEM;
777 			if (error)
778 				break;
779 		}
780 	}
781 	if (error)  {
782 		mddestroy(sc, NULL);
783 		return (error);
784 	}
785 	mdinit(sc);
786 	if (!(mdio->md_options & MD_RESERVE))
787 		sc->pp->flags |= G_PF_CANDELETE;
788 	return (0);
789 }
790 
791 
792 static int
793 mdsetcred(struct md_s *sc, struct ucred *cred)
794 {
795 	char *tmpbuf;
796 	int error = 0;
797 
798 	/*
799 	 * Set credits in our softc
800 	 */
801 
802 	if (sc->cred)
803 		crfree(sc->cred);
804 	sc->cred = crhold(cred);
805 
806 	/*
807 	 * Horrible kludge to establish credentials for NFS  XXX.
808 	 */
809 
810 	if (sc->vnode) {
811 		struct uio auio;
812 		struct iovec aiov;
813 
814 		tmpbuf = malloc(sc->secsize, M_TEMP, M_WAITOK);
815 		bzero(&auio, sizeof(auio));
816 
817 		aiov.iov_base = tmpbuf;
818 		aiov.iov_len = sc->secsize;
819 		auio.uio_iov = &aiov;
820 		auio.uio_iovcnt = 1;
821 		auio.uio_offset = 0;
822 		auio.uio_rw = UIO_READ;
823 		auio.uio_segflg = UIO_SYSSPACE;
824 		auio.uio_resid = aiov.iov_len;
825 		vn_lock(sc->vnode, LK_EXCLUSIVE | LK_RETRY, curthread);
826 		error = VOP_READ(sc->vnode, &auio, 0, sc->cred);
827 		VOP_UNLOCK(sc->vnode, 0, curthread);
828 		free(tmpbuf, M_TEMP);
829 	}
830 	return (error);
831 }
832 
833 static int
834 mdcreate_vnode(struct md_ioctl *mdio, struct thread *td)
835 {
836 	struct md_s *sc;
837 	struct vattr vattr;
838 	struct nameidata nd;
839 	int error, flags;
840 
841 	flags = FREAD|FWRITE;
842 	NDINIT(&nd, LOOKUP, FOLLOW, UIO_USERSPACE, mdio->md_file, td);
843 	error = vn_open(&nd, &flags, 0);
844 	if (error) {
845 		if (error != EACCES && error != EPERM && error != EROFS)
846 			return (error);
847 		flags &= ~FWRITE;
848 		NDINIT(&nd, LOOKUP, FOLLOW, UIO_USERSPACE, mdio->md_file, td);
849 		error = vn_open(&nd, &flags, 0);
850 		if (error)
851 			return (error);
852 	}
853 	NDFREE(&nd, NDF_ONLY_PNBUF);
854 	if (nd.ni_vp->v_type != VREG ||
855 	    (error = VOP_GETATTR(nd.ni_vp, &vattr, td->td_ucred, td))) {
856 		VOP_UNLOCK(nd.ni_vp, 0, td);
857 		(void) vn_close(nd.ni_vp, flags, td->td_ucred, td);
858 		return (error ? error : EINVAL);
859 	}
860 	VOP_UNLOCK(nd.ni_vp, 0, td);
861 
862 	if (mdio->md_options & MD_AUTOUNIT) {
863 		sc = mdnew(-1);
864 		mdio->md_unit = sc->unit;
865 	} else {
866 		sc = mdnew(mdio->md_unit);
867 	}
868 	if (sc == NULL) {
869 		(void) vn_close(nd.ni_vp, flags, td->td_ucred, td);
870 		return (EBUSY);
871 	}
872 
873 	sc->type = MD_VNODE;
874 	sc->flags = mdio->md_options & MD_FORCE;
875 	if (!(flags & FWRITE))
876 		sc->flags |= MD_READONLY;
877 	sc->secsize = DEV_BSIZE;
878 	sc->vnode = nd.ni_vp;
879 
880 	/*
881 	 * If the size is specified, override the file attributes.
882 	 */
883 	if (mdio->md_size)
884 		sc->nsect = mdio->md_size;
885 	else
886 		sc->nsect = vattr.va_size / sc->secsize; /* XXX: round up ? */
887 	if (sc->nsect == 0) {
888 		mddestroy(sc, td);
889 		return (EINVAL);
890 	}
891 	error = mdsetcred(sc, td->td_ucred);
892 	if (error) {
893 		mddestroy(sc, td);
894 		return (error);
895 	}
896 	mdinit(sc);
897 	return (0);
898 }
899 
900 static void
901 md_zapit(void *p, int cancel)
902 {
903 	if (cancel)
904 		return;
905 	g_wither_geom(p, ENXIO);
906 }
907 
908 static int
909 mddestroy(struct md_s *sc, struct thread *td)
910 {
911 
912 	GIANT_REQUIRED;
913 
914 	mtx_destroy(&sc->queue_mtx);
915 	if (sc->gp) {
916 		sc->gp->softc = NULL;
917 		g_waitfor_event(md_zapit, sc->gp, M_WAITOK, sc->gp, NULL);
918 		sc->gp = NULL;
919 		sc->pp = NULL;
920 	}
921 	sc->flags |= MD_SHUTDOWN;
922 	wakeup(sc);
923 	while (sc->procp != NULL)
924 		tsleep(&sc->procp, PRIBIO, "mddestroy", hz / 10);
925 	if (sc->vnode != NULL)
926 		(void)vn_close(sc->vnode, sc->flags & MD_READONLY ?
927 		    FREAD : (FREAD|FWRITE), sc->cred, td);
928 	if (sc->cred != NULL)
929 		crfree(sc->cred);
930 	if (sc->object != NULL) {
931 		vm_object_deallocate(sc->object);
932 	}
933 	if (sc->indir)
934 		destroy_indir(sc, sc->indir);
935 	if (sc->uma)
936 		uma_zdestroy(sc->uma);
937 
938 	/* XXX: LOCK(unique unit numbers) */
939 	LIST_REMOVE(sc, list);
940 	/* XXX: UNLOCK(unique unit numbers) */
941 	free(sc, M_MD);
942 	return (0);
943 }
944 
945 static int
946 mdcreate_swap(struct md_ioctl *mdio, struct thread *td)
947 {
948 	int error;
949 	struct md_s *sc;
950 
951 	GIANT_REQUIRED;
952 
953 	if (mdio->md_options & MD_AUTOUNIT) {
954 		sc = mdnew(-1);
955 		mdio->md_unit = sc->unit;
956 	} else {
957 		sc = mdnew(mdio->md_unit);
958 	}
959 	if (sc == NULL)
960 		return (EBUSY);
961 
962 	sc->type = MD_SWAP;
963 
964 	/*
965 	 * Range check.  Disallow negative sizes or any size less then the
966 	 * size of a page.  Then round to a page.
967 	 */
968 
969 	if (mdio->md_size == 0) {
970 		mddestroy(sc, td);
971 		return (EDOM);
972 	}
973 
974 	/*
975 	 * Allocate an OBJT_SWAP object.
976 	 *
977 	 * sc_secsize is PAGE_SIZE'd
978 	 *
979 	 * mdio->size is in DEV_BSIZE'd chunks.
980 	 * Note the truncation.
981 	 */
982 
983 	sc->secsize = PAGE_SIZE;
984 	sc->nsect = mdio->md_size / (PAGE_SIZE / DEV_BSIZE);
985 	sc->object = vm_pager_allocate(OBJT_SWAP, NULL, sc->secsize * (vm_offset_t)sc->nsect, VM_PROT_DEFAULT, 0);
986 	sc->flags = mdio->md_options & MD_FORCE;
987 	if (mdio->md_options & MD_RESERVE) {
988 		if (swap_pager_reserve(sc->object, 0, sc->nsect) < 0) {
989 			vm_object_deallocate(sc->object);
990 			sc->object = NULL;
991 			mddestroy(sc, td);
992 			return (EDOM);
993 		}
994 	}
995 	error = mdsetcred(sc, td->td_ucred);
996 	if (error) {
997 		mddestroy(sc, td);
998 		return (error);
999 	}
1000 	mdinit(sc);
1001 	if (!(mdio->md_options & MD_RESERVE))
1002 		sc->pp->flags |= G_PF_CANDELETE;
1003 	return (0);
1004 }
1005 
1006 static int
1007 mddetach(int unit, struct thread *td)
1008 {
1009 	struct md_s *sc;
1010 
1011 	sc = mdfind(unit);
1012 	if (sc == NULL)
1013 		return (ENOENT);
1014 	if (sc->opencount != 0 && !(sc->flags & MD_FORCE))
1015 		return (EBUSY);
1016 	switch(sc->type) {
1017 	case MD_VNODE:
1018 	case MD_SWAP:
1019 	case MD_MALLOC:
1020 	case MD_PRELOAD:
1021 		return (mddestroy(sc, td));
1022 	default:
1023 		return (EOPNOTSUPP);
1024 	}
1025 }
1026 
1027 static int
1028 mdctlioctl(dev_t dev, u_long cmd, caddr_t addr, int flags, struct thread *td)
1029 {
1030 	struct md_ioctl *mdio;
1031 	struct md_s *sc;
1032 	int i;
1033 
1034 	if (md_debug)
1035 		printf("mdctlioctl(%s %lx %p %x %p)\n",
1036 			devtoname(dev), cmd, addr, flags, td);
1037 
1038 	/*
1039 	 * We assert the version number in the individual ioctl
1040 	 * handlers instead of out here because (a) it is possible we
1041 	 * may add another ioctl in the future which doesn't read an
1042 	 * mdio, and (b) the correct return value for an unknown ioctl
1043 	 * is ENOIOCTL, not EINVAL.
1044 	 */
1045 	mdio = (struct md_ioctl *)addr;
1046 	switch (cmd) {
1047 	case MDIOCATTACH:
1048 		if (mdio->md_version != MDIOVERSION)
1049 			return (EINVAL);
1050 		switch (mdio->md_type) {
1051 		case MD_MALLOC:
1052 			return (mdcreate_malloc(mdio));
1053 		case MD_PRELOAD:
1054 			return (mdcreate_preload(mdio));
1055 		case MD_VNODE:
1056 			return (mdcreate_vnode(mdio, td));
1057 		case MD_SWAP:
1058 			return (mdcreate_swap(mdio, td));
1059 		default:
1060 			return (EINVAL);
1061 		}
1062 	case MDIOCDETACH:
1063 		if (mdio->md_version != MDIOVERSION)
1064 			return (EINVAL);
1065 		if (mdio->md_file != NULL || mdio->md_size != 0 ||
1066 		    mdio->md_options != 0)
1067 			return (EINVAL);
1068 		return (mddetach(mdio->md_unit, td));
1069 	case MDIOCQUERY:
1070 		if (mdio->md_version != MDIOVERSION)
1071 			return (EINVAL);
1072 		sc = mdfind(mdio->md_unit);
1073 		if (sc == NULL)
1074 			return (ENOENT);
1075 		mdio->md_type = sc->type;
1076 		mdio->md_options = sc->flags;
1077 		switch (sc->type) {
1078 		case MD_MALLOC:
1079 			mdio->md_size = sc->nsect;
1080 			break;
1081 		case MD_PRELOAD:
1082 			mdio->md_size = sc->nsect;
1083 			mdio->md_base = (uint64_t)(intptr_t)sc->pl_ptr;
1084 			break;
1085 		case MD_SWAP:
1086 			mdio->md_size = sc->nsect * (PAGE_SIZE / DEV_BSIZE);
1087 			break;
1088 		case MD_VNODE:
1089 			mdio->md_size = sc->nsect;
1090 			/* XXX fill this in */
1091 			mdio->md_file = NULL;
1092 			break;
1093 		}
1094 		return (0);
1095 	case MDIOCLIST:
1096 		i = 1;
1097 		LIST_FOREACH(sc, &md_softc_list, list) {
1098 			if (i == MDNPAD - 1)
1099 				mdio->md_pad[i] = -1;
1100 			else
1101 				mdio->md_pad[i++] = sc->unit;
1102 		}
1103 		mdio->md_pad[0] = i - 1;
1104 		return (0);
1105 	default:
1106 		return (ENOIOCTL);
1107 	};
1108 	return (ENOIOCTL);
1109 }
1110 
1111 static void
1112 md_preloaded(u_char *image, unsigned length)
1113 {
1114 	struct md_s *sc;
1115 
1116 	sc = mdnew(-1);
1117 	if (sc == NULL)
1118 		return;
1119 	sc->type = MD_PRELOAD;
1120 	sc->secsize = DEV_BSIZE;
1121 	sc->nsect = length / DEV_BSIZE;
1122 	sc->pl_ptr = image;
1123 	sc->pl_len = length;
1124 	if (sc->unit == 0)
1125 		mdrootready = 1;
1126 	mdinit(sc);
1127 }
1128 
1129 static void
1130 md_drvinit(void *unused)
1131 {
1132 
1133 	caddr_t mod;
1134 	caddr_t c;
1135 	u_char *ptr, *name, *type;
1136 	unsigned len;
1137 
1138 #ifdef MD_ROOT_SIZE
1139 	md_preloaded(mfs_root, MD_ROOT_SIZE*1024);
1140 #endif
1141 	mod = NULL;
1142 	while ((mod = preload_search_next_name(mod)) != NULL) {
1143 		name = (char *)preload_search_info(mod, MODINFO_NAME);
1144 		type = (char *)preload_search_info(mod, MODINFO_TYPE);
1145 		if (name == NULL)
1146 			continue;
1147 		if (type == NULL)
1148 			continue;
1149 		if (strcmp(type, "md_image") && strcmp(type, "mfs_root"))
1150 			continue;
1151 		c = preload_search_info(mod, MODINFO_ADDR);
1152 		ptr = *(u_char **)c;
1153 		c = preload_search_info(mod, MODINFO_SIZE);
1154 		len = *(size_t *)c;
1155 		printf("%s%d: Preloaded image <%s> %d bytes at %p\n",
1156 		    MD_NAME, mdunits, name, len, ptr);
1157 		md_preloaded(ptr, len);
1158 	}
1159 	status_dev = make_dev(&mdctl_cdevsw, 0xffff00ff, UID_ROOT, GID_WHEEL,
1160 	    0600, MDCTL_NAME);
1161 }
1162 
1163 static int
1164 md_modevent(module_t mod, int type, void *data)
1165 {
1166 	int error;
1167 	struct md_s *sc;
1168 
1169 	switch (type) {
1170 	case MOD_LOAD:
1171 		md_drvinit(NULL);
1172 		break;
1173 	case MOD_UNLOAD:
1174 		LIST_FOREACH(sc, &md_softc_list, list) {
1175 			error = mddetach(sc->unit, curthread);
1176 			if (error != 0)
1177 				return (error);
1178 		}
1179 		if (status_dev)
1180 			destroy_dev(status_dev);
1181 		status_dev = 0;
1182 		break;
1183 	default:
1184 		break;
1185 	}
1186 	return (0);
1187 }
1188 
1189 static moduledata_t md_mod = {
1190 	MD_NAME,
1191 	md_modevent,
1192 	NULL
1193 };
1194 DECLARE_MODULE(md, md_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE+CDEV_MAJOR);
1195 MODULE_VERSION(md, MD_MODVER);
1196 
1197 
1198 #ifdef MD_ROOT
1199 static void
1200 md_takeroot(void *junk)
1201 {
1202 	if (mdrootready)
1203 		rootdevnames[0] = "ufs:/dev/md0";
1204 }
1205 
1206 SYSINIT(md_root, SI_SUB_MOUNT_ROOT, SI_ORDER_FIRST, md_takeroot, NULL);
1207 #endif /* MD_ROOT */
1208