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