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