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