xref: /freebsd/sys/dev/md/md.c (revision 4cbff7a3dcdc5b5838d3c3ca5644ab4815c52a58)
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  * 4. Neither the name of the University nor the names of its contributors
35  *    may be used to endorse or promote products derived from this software
36  *    without specific prior written permission.
37  *
38  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
39  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
40  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
41  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
42  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
43  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
44  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
45  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
46  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
47  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
48  * SUCH DAMAGE.
49  *
50  * from: Utah Hdr: vn.c 1.13 94/04/02
51  *
52  *	from: @(#)vn.c	8.6 (Berkeley) 4/1/94
53  * From: src/sys/dev/vn/vn.c,v 1.122 2000/12/16 16:06:03
54  */
55 
56 #include "opt_geom.h"
57 #include "opt_md.h"
58 
59 #include <sys/param.h>
60 #include <sys/systm.h>
61 #include <sys/bio.h>
62 #include <sys/conf.h>
63 #include <sys/devicestat.h>
64 #include <sys/fcntl.h>
65 #include <sys/kernel.h>
66 #include <sys/kthread.h>
67 #include <sys/limits.h>
68 #include <sys/linker.h>
69 #include <sys/lock.h>
70 #include <sys/malloc.h>
71 #include <sys/mdioctl.h>
72 #include <sys/mount.h>
73 #include <sys/mutex.h>
74 #include <sys/sx.h>
75 #include <sys/namei.h>
76 #include <sys/proc.h>
77 #include <sys/queue.h>
78 #include <sys/sbuf.h>
79 #include <sys/sched.h>
80 #include <sys/sf_buf.h>
81 #include <sys/sysctl.h>
82 #include <sys/vnode.h>
83 
84 #include <geom/geom.h>
85 
86 #include <vm/vm.h>
87 #include <vm/vm_param.h>
88 #include <vm/vm_object.h>
89 #include <vm/vm_page.h>
90 #include <vm/vm_pager.h>
91 #include <vm/swap_pager.h>
92 #include <vm/uma.h>
93 
94 #define MD_MODVER 1
95 
96 #define MD_SHUTDOWN	0x10000		/* Tell worker thread to terminate. */
97 #define	MD_EXITING	0x20000		/* Worker thread is exiting. */
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     "Enable md(4) debug messages");
109 static int md_malloc_wait;
110 SYSCTL_INT(_vm, OID_AUTO, md_malloc_wait, CTLFLAG_RW, &md_malloc_wait, 0,
111     "Allow malloc to wait for memory allocations");
112 
113 #if defined(MD_ROOT) && !defined(MD_ROOT_FSTYPE)
114 #define	MD_ROOT_FSTYPE	"ufs"
115 #endif
116 
117 #if defined(MD_ROOT) && defined(MD_ROOT_SIZE)
118 /*
119  * Preloaded image gets put here.
120  * Applications that patch the object with the image can determine
121  * the size looking at the start and end markers (strings),
122  * so we want them contiguous.
123  */
124 static struct {
125 	u_char start[MD_ROOT_SIZE*1024];
126 	u_char end[128];
127 } mfs_root = {
128 	.start = "MFS Filesystem goes here",
129 	.end = "MFS Filesystem had better STOP here",
130 };
131 #endif
132 
133 static g_init_t g_md_init;
134 static g_fini_t g_md_fini;
135 static g_start_t g_md_start;
136 static g_access_t g_md_access;
137 static void g_md_dumpconf(struct sbuf *sb, const char *indent,
138     struct g_geom *gp, struct g_consumer *cp __unused, struct g_provider *pp);
139 
140 static int mdunits;
141 static struct cdev *status_dev = 0;
142 static struct sx md_sx;
143 static struct unrhdr *md_uh;
144 
145 static d_ioctl_t mdctlioctl;
146 
147 static struct cdevsw mdctl_cdevsw = {
148 	.d_version =	D_VERSION,
149 	.d_ioctl =	mdctlioctl,
150 	.d_name =	MD_NAME,
151 };
152 
153 struct g_class g_md_class = {
154 	.name = "MD",
155 	.version = G_VERSION,
156 	.init = g_md_init,
157 	.fini = g_md_fini,
158 	.start = g_md_start,
159 	.access = g_md_access,
160 	.dumpconf = g_md_dumpconf,
161 };
162 
163 DECLARE_GEOM_CLASS(g_md_class, g_md);
164 
165 
166 static LIST_HEAD(, md_s) md_softc_list = LIST_HEAD_INITIALIZER(md_softc_list);
167 
168 #define NINDIR	(PAGE_SIZE / sizeof(uintptr_t))
169 #define NMASK	(NINDIR-1)
170 static int nshift;
171 
172 struct indir {
173 	uintptr_t	*array;
174 	u_int		total;
175 	u_int		used;
176 	u_int		shift;
177 };
178 
179 struct md_s {
180 	int unit;
181 	LIST_ENTRY(md_s) list;
182 	struct bio_queue_head bio_queue;
183 	struct mtx queue_mtx;
184 	struct cdev *dev;
185 	enum md_types type;
186 	off_t mediasize;
187 	unsigned sectorsize;
188 	unsigned opencount;
189 	unsigned fwheads;
190 	unsigned fwsectors;
191 	unsigned flags;
192 	char name[20];
193 	struct proc *procp;
194 	struct g_geom *gp;
195 	struct g_provider *pp;
196 	int (*start)(struct md_s *sc, struct bio *bp);
197 	struct devstat *devstat;
198 
199 	/* MD_MALLOC related fields */
200 	struct indir *indir;
201 	uma_zone_t uma;
202 
203 	/* MD_PRELOAD related fields */
204 	u_char *pl_ptr;
205 	size_t pl_len;
206 
207 	/* MD_VNODE related fields */
208 	struct vnode *vnode;
209 	char file[PATH_MAX];
210 	struct ucred *cred;
211 
212 	/* MD_SWAP related fields */
213 	vm_object_t object;
214 };
215 
216 static struct indir *
217 new_indir(u_int shift)
218 {
219 	struct indir *ip;
220 
221 	ip = malloc(sizeof *ip, M_MD, (md_malloc_wait ? M_WAITOK : M_NOWAIT)
222 	    | M_ZERO);
223 	if (ip == NULL)
224 		return (NULL);
225 	ip->array = malloc(sizeof(uintptr_t) * NINDIR,
226 	    M_MDSECT, (md_malloc_wait ? M_WAITOK : M_NOWAIT) | M_ZERO);
227 	if (ip->array == NULL) {
228 		free(ip, M_MD);
229 		return (NULL);
230 	}
231 	ip->total = NINDIR;
232 	ip->shift = shift;
233 	return (ip);
234 }
235 
236 static void
237 del_indir(struct indir *ip)
238 {
239 
240 	free(ip->array, M_MDSECT);
241 	free(ip, M_MD);
242 }
243 
244 static void
245 destroy_indir(struct md_s *sc, struct indir *ip)
246 {
247 	int i;
248 
249 	for (i = 0; i < NINDIR; i++) {
250 		if (!ip->array[i])
251 			continue;
252 		if (ip->shift)
253 			destroy_indir(sc, (struct indir*)(ip->array[i]));
254 		else if (ip->array[i] > 255)
255 			uma_zfree(sc->uma, (void *)(ip->array[i]));
256 	}
257 	del_indir(ip);
258 }
259 
260 /*
261  * This function does the math and allocates the top level "indir" structure
262  * for a device of "size" sectors.
263  */
264 
265 static struct indir *
266 dimension(off_t size)
267 {
268 	off_t rcnt;
269 	struct indir *ip;
270 	int layer;
271 
272 	rcnt = size;
273 	layer = 0;
274 	while (rcnt > NINDIR) {
275 		rcnt /= NINDIR;
276 		layer++;
277 	}
278 
279 	/*
280 	 * XXX: the top layer is probably not fully populated, so we allocate
281 	 * too much space for ip->array in here.
282 	 */
283 	ip = malloc(sizeof *ip, M_MD, M_WAITOK | M_ZERO);
284 	ip->array = malloc(sizeof(uintptr_t) * NINDIR,
285 	    M_MDSECT, M_WAITOK | M_ZERO);
286 	ip->total = NINDIR;
287 	ip->shift = layer * nshift;
288 	return (ip);
289 }
290 
291 /*
292  * Read a given sector
293  */
294 
295 static uintptr_t
296 s_read(struct indir *ip, off_t offset)
297 {
298 	struct indir *cip;
299 	int idx;
300 	uintptr_t up;
301 
302 	if (md_debug > 1)
303 		printf("s_read(%jd)\n", (intmax_t)offset);
304 	up = 0;
305 	for (cip = ip; cip != NULL;) {
306 		if (cip->shift) {
307 			idx = (offset >> cip->shift) & NMASK;
308 			up = cip->array[idx];
309 			cip = (struct indir *)up;
310 			continue;
311 		}
312 		idx = offset & NMASK;
313 		return (cip->array[idx]);
314 	}
315 	return (0);
316 }
317 
318 /*
319  * Write a given sector, prune the tree if the value is 0
320  */
321 
322 static int
323 s_write(struct indir *ip, off_t offset, uintptr_t ptr)
324 {
325 	struct indir *cip, *lip[10];
326 	int idx, li;
327 	uintptr_t up;
328 
329 	if (md_debug > 1)
330 		printf("s_write(%jd, %p)\n", (intmax_t)offset, (void *)ptr);
331 	up = 0;
332 	li = 0;
333 	cip = ip;
334 	for (;;) {
335 		lip[li++] = cip;
336 		if (cip->shift) {
337 			idx = (offset >> cip->shift) & NMASK;
338 			up = cip->array[idx];
339 			if (up != 0) {
340 				cip = (struct indir *)up;
341 				continue;
342 			}
343 			/* Allocate branch */
344 			cip->array[idx] =
345 			    (uintptr_t)new_indir(cip->shift - nshift);
346 			if (cip->array[idx] == 0)
347 				return (ENOSPC);
348 			cip->used++;
349 			up = cip->array[idx];
350 			cip = (struct indir *)up;
351 			continue;
352 		}
353 		/* leafnode */
354 		idx = offset & NMASK;
355 		up = cip->array[idx];
356 		if (up != 0)
357 			cip->used--;
358 		cip->array[idx] = ptr;
359 		if (ptr != 0)
360 			cip->used++;
361 		break;
362 	}
363 	if (cip->used != 0 || li == 1)
364 		return (0);
365 	li--;
366 	while (cip->used == 0 && cip != ip) {
367 		li--;
368 		idx = (offset >> lip[li]->shift) & NMASK;
369 		up = lip[li]->array[idx];
370 		KASSERT(up == (uintptr_t)cip, ("md screwed up"));
371 		del_indir(cip);
372 		lip[li]->array[idx] = 0;
373 		lip[li]->used--;
374 		cip = lip[li];
375 	}
376 	return (0);
377 }
378 
379 
380 static int
381 g_md_access(struct g_provider *pp, int r, int w, int e)
382 {
383 	struct md_s *sc;
384 
385 	sc = pp->geom->softc;
386 	if (sc == NULL) {
387 		if (r <= 0 && w <= 0 && e <= 0)
388 			return (0);
389 		return (ENXIO);
390 	}
391 	r += pp->acr;
392 	w += pp->acw;
393 	e += pp->ace;
394 	if ((sc->flags & MD_READONLY) != 0 && w > 0)
395 		return (EROFS);
396 	if ((pp->acr + pp->acw + pp->ace) == 0 && (r + w + e) > 0) {
397 		sc->opencount = 1;
398 	} else if ((pp->acr + pp->acw + pp->ace) > 0 && (r + w + e) == 0) {
399 		sc->opencount = 0;
400 	}
401 	return (0);
402 }
403 
404 static void
405 g_md_start(struct bio *bp)
406 {
407 	struct md_s *sc;
408 
409 	sc = bp->bio_to->geom->softc;
410 	if ((bp->bio_cmd == BIO_READ) || (bp->bio_cmd == BIO_WRITE))
411 		devstat_start_transaction_bio(sc->devstat, bp);
412 	mtx_lock(&sc->queue_mtx);
413 	bioq_disksort(&sc->bio_queue, bp);
414 	mtx_unlock(&sc->queue_mtx);
415 	wakeup(sc);
416 }
417 
418 static int
419 mdstart_malloc(struct md_s *sc, struct bio *bp)
420 {
421 	int i, error;
422 	u_char *dst;
423 	off_t secno, nsec, uc;
424 	uintptr_t sp, osp;
425 
426 	switch (bp->bio_cmd) {
427 	case BIO_READ:
428 	case BIO_WRITE:
429 	case BIO_DELETE:
430 		break;
431 	default:
432 		return (EOPNOTSUPP);
433 	}
434 
435 	nsec = bp->bio_length / sc->sectorsize;
436 	secno = bp->bio_offset / sc->sectorsize;
437 	dst = bp->bio_data;
438 	error = 0;
439 	while (nsec--) {
440 		osp = s_read(sc->indir, secno);
441 		if (bp->bio_cmd == BIO_DELETE) {
442 			if (osp != 0)
443 				error = s_write(sc->indir, secno, 0);
444 		} else if (bp->bio_cmd == BIO_READ) {
445 			if (osp == 0)
446 				bzero(dst, sc->sectorsize);
447 			else if (osp <= 255)
448 				memset(dst, osp, sc->sectorsize);
449 			else {
450 				bcopy((void *)osp, dst, sc->sectorsize);
451 				cpu_flush_dcache(dst, sc->sectorsize);
452 			}
453 			osp = 0;
454 		} else if (bp->bio_cmd == BIO_WRITE) {
455 			if (sc->flags & MD_COMPRESS) {
456 				uc = dst[0];
457 				for (i = 1; i < sc->sectorsize; i++)
458 					if (dst[i] != uc)
459 						break;
460 			} else {
461 				i = 0;
462 				uc = 0;
463 			}
464 			if (i == sc->sectorsize) {
465 				if (osp != uc)
466 					error = s_write(sc->indir, secno, uc);
467 			} else {
468 				if (osp <= 255) {
469 					sp = (uintptr_t)uma_zalloc(sc->uma,
470 					    md_malloc_wait ? M_WAITOK :
471 					    M_NOWAIT);
472 					if (sp == 0) {
473 						error = ENOSPC;
474 						break;
475 					}
476 					bcopy(dst, (void *)sp, sc->sectorsize);
477 					error = s_write(sc->indir, secno, sp);
478 				} else {
479 					bcopy(dst, (void *)osp, sc->sectorsize);
480 					osp = 0;
481 				}
482 			}
483 		} else {
484 			error = EOPNOTSUPP;
485 		}
486 		if (osp > 255)
487 			uma_zfree(sc->uma, (void*)osp);
488 		if (error != 0)
489 			break;
490 		secno++;
491 		dst += sc->sectorsize;
492 	}
493 	bp->bio_resid = 0;
494 	return (error);
495 }
496 
497 static int
498 mdstart_preload(struct md_s *sc, struct bio *bp)
499 {
500 
501 	switch (bp->bio_cmd) {
502 	case BIO_READ:
503 		bcopy(sc->pl_ptr + bp->bio_offset, bp->bio_data,
504 		    bp->bio_length);
505 		cpu_flush_dcache(bp->bio_data, bp->bio_length);
506 		break;
507 	case BIO_WRITE:
508 		bcopy(bp->bio_data, sc->pl_ptr + bp->bio_offset,
509 		    bp->bio_length);
510 		break;
511 	}
512 	bp->bio_resid = 0;
513 	return (0);
514 }
515 
516 static int
517 mdstart_vnode(struct md_s *sc, struct bio *bp)
518 {
519 	int error;
520 	struct uio auio;
521 	struct iovec aiov;
522 	struct mount *mp;
523 	struct vnode *vp;
524 	struct thread *td;
525 	off_t end, zerosize;
526 
527 	switch (bp->bio_cmd) {
528 	case BIO_READ:
529 	case BIO_WRITE:
530 	case BIO_DELETE:
531 	case BIO_FLUSH:
532 		break;
533 	default:
534 		return (EOPNOTSUPP);
535 	}
536 
537 	td = curthread;
538 	vp = sc->vnode;
539 
540 	/*
541 	 * VNODE I/O
542 	 *
543 	 * If an error occurs, we set BIO_ERROR but we do not set
544 	 * B_INVAL because (for a write anyway), the buffer is
545 	 * still valid.
546 	 */
547 
548 	if (bp->bio_cmd == BIO_FLUSH) {
549 		(void) vn_start_write(vp, &mp, V_WAIT);
550 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
551 		error = VOP_FSYNC(vp, MNT_WAIT, td);
552 		VOP_UNLOCK(vp, 0);
553 		vn_finished_write(mp);
554 		return (error);
555 	}
556 
557 	bzero(&auio, sizeof(auio));
558 
559 	/*
560 	 * Special case for BIO_DELETE.  On the surface, this is very
561 	 * similar to BIO_WRITE, except that we write from our own
562 	 * fixed-length buffer, so we have to loop.  The net result is
563 	 * that the two cases end up having very little in common.
564 	 */
565 	if (bp->bio_cmd == BIO_DELETE) {
566 		zerosize = ZERO_REGION_SIZE -
567 		    (ZERO_REGION_SIZE % sc->sectorsize);
568 		auio.uio_iov = &aiov;
569 		auio.uio_iovcnt = 1;
570 		auio.uio_offset = (vm_ooffset_t)bp->bio_offset;
571 		auio.uio_segflg = UIO_SYSSPACE;
572 		auio.uio_rw = UIO_WRITE;
573 		auio.uio_td = td;
574 		end = bp->bio_offset + bp->bio_length;
575 		(void) vn_start_write(vp, &mp, V_WAIT);
576 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
577 		error = 0;
578 		while (auio.uio_offset < end) {
579 			aiov.iov_base = __DECONST(void *, zero_region);
580 			aiov.iov_len = end - auio.uio_offset;
581 			if (aiov.iov_len > zerosize)
582 				aiov.iov_len = zerosize;
583 			auio.uio_resid = aiov.iov_len;
584 			error = VOP_WRITE(vp, &auio,
585 			    sc->flags & MD_ASYNC ? 0 : IO_SYNC, sc->cred);
586 			if (error != 0)
587 				break;
588 		}
589 		VOP_UNLOCK(vp, 0);
590 		vn_finished_write(mp);
591 		bp->bio_resid = end - auio.uio_offset;
592 		return (error);
593 	}
594 
595 	aiov.iov_base = bp->bio_data;
596 	aiov.iov_len = bp->bio_length;
597 	auio.uio_iov = &aiov;
598 	auio.uio_iovcnt = 1;
599 	auio.uio_offset = (vm_ooffset_t)bp->bio_offset;
600 	auio.uio_segflg = UIO_SYSSPACE;
601 	if (bp->bio_cmd == BIO_READ)
602 		auio.uio_rw = UIO_READ;
603 	else if (bp->bio_cmd == BIO_WRITE)
604 		auio.uio_rw = UIO_WRITE;
605 	else
606 		panic("wrong BIO_OP in mdstart_vnode");
607 	auio.uio_resid = bp->bio_length;
608 	auio.uio_td = td;
609 	/*
610 	 * When reading set IO_DIRECT to try to avoid double-caching
611 	 * the data.  When writing IO_DIRECT is not optimal.
612 	 */
613 	if (bp->bio_cmd == BIO_READ) {
614 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
615 		error = VOP_READ(vp, &auio, IO_DIRECT, sc->cred);
616 		VOP_UNLOCK(vp, 0);
617 	} else {
618 		(void) vn_start_write(vp, &mp, V_WAIT);
619 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
620 		error = VOP_WRITE(vp, &auio, sc->flags & MD_ASYNC ? 0 : IO_SYNC,
621 		    sc->cred);
622 		VOP_UNLOCK(vp, 0);
623 		vn_finished_write(mp);
624 	}
625 	bp->bio_resid = auio.uio_resid;
626 	return (error);
627 }
628 
629 static int
630 mdstart_swap(struct md_s *sc, struct bio *bp)
631 {
632 	struct sf_buf *sf;
633 	int rv, offs, len, lastend;
634 	vm_pindex_t i, lastp;
635 	vm_page_t m;
636 	u_char *p;
637 
638 	switch (bp->bio_cmd) {
639 	case BIO_READ:
640 	case BIO_WRITE:
641 	case BIO_DELETE:
642 		break;
643 	default:
644 		return (EOPNOTSUPP);
645 	}
646 
647 	p = bp->bio_data;
648 
649 	/*
650 	 * offs is the offset at which to start operating on the
651 	 * next (ie, first) page.  lastp is the last page on
652 	 * which we're going to operate.  lastend is the ending
653 	 * position within that last page (ie, PAGE_SIZE if
654 	 * we're operating on complete aligned pages).
655 	 */
656 	offs = bp->bio_offset % PAGE_SIZE;
657 	lastp = (bp->bio_offset + bp->bio_length - 1) / PAGE_SIZE;
658 	lastend = (bp->bio_offset + bp->bio_length - 1) % PAGE_SIZE + 1;
659 
660 	rv = VM_PAGER_OK;
661 	VM_OBJECT_LOCK(sc->object);
662 	vm_object_pip_add(sc->object, 1);
663 	for (i = bp->bio_offset / PAGE_SIZE; i <= lastp; i++) {
664 		len = ((i == lastp) ? lastend : PAGE_SIZE) - offs;
665 
666 		m = vm_page_grab(sc->object, i,
667 		    VM_ALLOC_NORMAL|VM_ALLOC_RETRY);
668 		VM_OBJECT_UNLOCK(sc->object);
669 		sched_pin();
670 		sf = sf_buf_alloc(m, SFB_CPUPRIVATE);
671 		VM_OBJECT_LOCK(sc->object);
672 		if (bp->bio_cmd == BIO_READ) {
673 			if (m->valid != VM_PAGE_BITS_ALL)
674 				rv = vm_pager_get_pages(sc->object, &m, 1, 0);
675 			if (rv == VM_PAGER_ERROR) {
676 				sf_buf_free(sf);
677 				sched_unpin();
678 				vm_page_wakeup(m);
679 				break;
680 			}
681 			bcopy((void *)(sf_buf_kva(sf) + offs), p, len);
682 			cpu_flush_dcache(p, len);
683 		} else if (bp->bio_cmd == BIO_WRITE) {
684 			if (len != PAGE_SIZE && m->valid != VM_PAGE_BITS_ALL)
685 				rv = vm_pager_get_pages(sc->object, &m, 1, 0);
686 			if (rv == VM_PAGER_ERROR) {
687 				sf_buf_free(sf);
688 				sched_unpin();
689 				vm_page_wakeup(m);
690 				break;
691 			}
692 			bcopy(p, (void *)(sf_buf_kva(sf) + offs), len);
693 			m->valid = VM_PAGE_BITS_ALL;
694 		} else if (bp->bio_cmd == BIO_DELETE) {
695 			if (len != PAGE_SIZE && m->valid != VM_PAGE_BITS_ALL)
696 				rv = vm_pager_get_pages(sc->object, &m, 1, 0);
697 			if (rv == VM_PAGER_ERROR) {
698 				sf_buf_free(sf);
699 				sched_unpin();
700 				vm_page_wakeup(m);
701 				break;
702 			}
703 			if (len != PAGE_SIZE) {
704 				bzero((void *)(sf_buf_kva(sf) + offs), len);
705 				vm_page_clear_dirty(m, offs, len);
706 				m->valid = VM_PAGE_BITS_ALL;
707 			} else
708 				vm_pager_page_unswapped(m);
709 		}
710 		sf_buf_free(sf);
711 		sched_unpin();
712 		vm_page_wakeup(m);
713 		vm_page_lock(m);
714 		if (bp->bio_cmd == BIO_DELETE && len == PAGE_SIZE)
715 			vm_page_free(m);
716 		else
717 			vm_page_activate(m);
718 		vm_page_unlock(m);
719 		if (bp->bio_cmd == BIO_WRITE)
720 			vm_page_dirty(m);
721 
722 		/* Actions on further pages start at offset 0 */
723 		p += PAGE_SIZE - offs;
724 		offs = 0;
725 	}
726 	vm_object_pip_subtract(sc->object, 1);
727 	VM_OBJECT_UNLOCK(sc->object);
728 	return (rv != VM_PAGER_ERROR ? 0 : ENOSPC);
729 }
730 
731 static void
732 md_kthread(void *arg)
733 {
734 	struct md_s *sc;
735 	struct bio *bp;
736 	int error;
737 
738 	sc = arg;
739 	thread_lock(curthread);
740 	sched_prio(curthread, PRIBIO);
741 	thread_unlock(curthread);
742 	if (sc->type == MD_VNODE)
743 		curthread->td_pflags |= TDP_NORUNNINGBUF;
744 
745 	for (;;) {
746 		mtx_lock(&sc->queue_mtx);
747 		if (sc->flags & MD_SHUTDOWN) {
748 			sc->flags |= MD_EXITING;
749 			mtx_unlock(&sc->queue_mtx);
750 			kproc_exit(0);
751 		}
752 		bp = bioq_takefirst(&sc->bio_queue);
753 		if (!bp) {
754 			msleep(sc, &sc->queue_mtx, PRIBIO | PDROP, "mdwait", 0);
755 			continue;
756 		}
757 		mtx_unlock(&sc->queue_mtx);
758 		if (bp->bio_cmd == BIO_GETATTR) {
759 			if ((sc->fwsectors && sc->fwheads &&
760 			    (g_handleattr_int(bp, "GEOM::fwsectors",
761 			    sc->fwsectors) ||
762 			    g_handleattr_int(bp, "GEOM::fwheads",
763 			    sc->fwheads))) ||
764 			    g_handleattr_int(bp, "GEOM::candelete", 1))
765 				error = -1;
766 			else
767 				error = EOPNOTSUPP;
768 		} else {
769 			error = sc->start(sc, bp);
770 		}
771 
772 		if (error != -1) {
773 			bp->bio_completed = bp->bio_length;
774 			if ((bp->bio_cmd == BIO_READ) || (bp->bio_cmd == BIO_WRITE))
775 				devstat_end_transaction_bio(sc->devstat, bp);
776 			g_io_deliver(bp, error);
777 		}
778 	}
779 }
780 
781 static struct md_s *
782 mdfind(int unit)
783 {
784 	struct md_s *sc;
785 
786 	LIST_FOREACH(sc, &md_softc_list, list) {
787 		if (sc->unit == unit)
788 			break;
789 	}
790 	return (sc);
791 }
792 
793 static struct md_s *
794 mdnew(int unit, int *errp, enum md_types type)
795 {
796 	struct md_s *sc;
797 	int error;
798 
799 	*errp = 0;
800 	if (unit == -1)
801 		unit = alloc_unr(md_uh);
802 	else
803 		unit = alloc_unr_specific(md_uh, unit);
804 
805 	if (unit == -1) {
806 		*errp = EBUSY;
807 		return (NULL);
808 	}
809 
810 	sc = (struct md_s *)malloc(sizeof *sc, M_MD, M_WAITOK | M_ZERO);
811 	sc->type = type;
812 	bioq_init(&sc->bio_queue);
813 	mtx_init(&sc->queue_mtx, "md bio queue", NULL, MTX_DEF);
814 	sc->unit = unit;
815 	sprintf(sc->name, "md%d", unit);
816 	LIST_INSERT_HEAD(&md_softc_list, sc, list);
817 	error = kproc_create(md_kthread, sc, &sc->procp, 0, 0,"%s", sc->name);
818 	if (error == 0)
819 		return (sc);
820 	LIST_REMOVE(sc, list);
821 	mtx_destroy(&sc->queue_mtx);
822 	free_unr(md_uh, sc->unit);
823 	free(sc, M_MD);
824 	*errp = error;
825 	return (NULL);
826 }
827 
828 static void
829 mdinit(struct md_s *sc)
830 {
831 	struct g_geom *gp;
832 	struct g_provider *pp;
833 
834 	g_topology_lock();
835 	gp = g_new_geomf(&g_md_class, "md%d", sc->unit);
836 	gp->softc = sc;
837 	pp = g_new_providerf(gp, "md%d", sc->unit);
838 	pp->mediasize = sc->mediasize;
839 	pp->sectorsize = sc->sectorsize;
840 	sc->gp = gp;
841 	sc->pp = pp;
842 	g_error_provider(pp, 0);
843 	g_topology_unlock();
844 	sc->devstat = devstat_new_entry("md", sc->unit, sc->sectorsize,
845 	    DEVSTAT_ALL_SUPPORTED, DEVSTAT_TYPE_DIRECT, DEVSTAT_PRIORITY_MAX);
846 }
847 
848 /*
849  * XXX: we should check that the range they feed us is mapped.
850  * XXX: we should implement read-only.
851  */
852 
853 static int
854 mdcreate_preload(struct md_s *sc, struct md_ioctl *mdio)
855 {
856 
857 	if (mdio->md_options & ~(MD_AUTOUNIT | MD_FORCE))
858 		return (EINVAL);
859 	if (mdio->md_base == 0)
860 		return (EINVAL);
861 	sc->flags = mdio->md_options & MD_FORCE;
862 	/* Cast to pointer size, then to pointer to avoid warning */
863 	sc->pl_ptr = (u_char *)(uintptr_t)mdio->md_base;
864 	sc->pl_len = (size_t)sc->mediasize;
865 	return (0);
866 }
867 
868 
869 static int
870 mdcreate_malloc(struct md_s *sc, struct md_ioctl *mdio)
871 {
872 	uintptr_t sp;
873 	int error;
874 	off_t u;
875 
876 	error = 0;
877 	if (mdio->md_options & ~(MD_AUTOUNIT | MD_COMPRESS | MD_RESERVE))
878 		return (EINVAL);
879 	if (mdio->md_sectorsize != 0 && !powerof2(mdio->md_sectorsize))
880 		return (EINVAL);
881 	/* Compression doesn't make sense if we have reserved space */
882 	if (mdio->md_options & MD_RESERVE)
883 		mdio->md_options &= ~MD_COMPRESS;
884 	if (mdio->md_fwsectors != 0)
885 		sc->fwsectors = mdio->md_fwsectors;
886 	if (mdio->md_fwheads != 0)
887 		sc->fwheads = mdio->md_fwheads;
888 	sc->flags = mdio->md_options & (MD_COMPRESS | MD_FORCE);
889 	sc->indir = dimension(sc->mediasize / sc->sectorsize);
890 	sc->uma = uma_zcreate(sc->name, sc->sectorsize, NULL, NULL, NULL, NULL,
891 	    0x1ff, 0);
892 	if (mdio->md_options & MD_RESERVE) {
893 		off_t nsectors;
894 
895 		nsectors = sc->mediasize / sc->sectorsize;
896 		for (u = 0; u < nsectors; u++) {
897 			sp = (uintptr_t)uma_zalloc(sc->uma, (md_malloc_wait ?
898 			    M_WAITOK : M_NOWAIT) | M_ZERO);
899 			if (sp != 0)
900 				error = s_write(sc->indir, u, sp);
901 			else
902 				error = ENOMEM;
903 			if (error != 0)
904 				break;
905 		}
906 	}
907 	return (error);
908 }
909 
910 
911 static int
912 mdsetcred(struct md_s *sc, struct ucred *cred)
913 {
914 	char *tmpbuf;
915 	int error = 0;
916 
917 	/*
918 	 * Set credits in our softc
919 	 */
920 
921 	if (sc->cred)
922 		crfree(sc->cred);
923 	sc->cred = crhold(cred);
924 
925 	/*
926 	 * Horrible kludge to establish credentials for NFS  XXX.
927 	 */
928 
929 	if (sc->vnode) {
930 		struct uio auio;
931 		struct iovec aiov;
932 
933 		tmpbuf = malloc(sc->sectorsize, M_TEMP, M_WAITOK);
934 		bzero(&auio, sizeof(auio));
935 
936 		aiov.iov_base = tmpbuf;
937 		aiov.iov_len = sc->sectorsize;
938 		auio.uio_iov = &aiov;
939 		auio.uio_iovcnt = 1;
940 		auio.uio_offset = 0;
941 		auio.uio_rw = UIO_READ;
942 		auio.uio_segflg = UIO_SYSSPACE;
943 		auio.uio_resid = aiov.iov_len;
944 		vn_lock(sc->vnode, LK_EXCLUSIVE | LK_RETRY);
945 		error = VOP_READ(sc->vnode, &auio, 0, sc->cred);
946 		VOP_UNLOCK(sc->vnode, 0);
947 		free(tmpbuf, M_TEMP);
948 	}
949 	return (error);
950 }
951 
952 static int
953 mdcreate_vnode(struct md_s *sc, struct md_ioctl *mdio, struct thread *td)
954 {
955 	struct vattr vattr;
956 	struct nameidata nd;
957 	char *fname;
958 	int error, flags;
959 
960 	/*
961 	 * Kernel-originated requests must have the filename appended
962 	 * to the mdio structure to protect against malicious software.
963 	 */
964 	fname = mdio->md_file;
965 	if ((void *)fname != (void *)(mdio + 1)) {
966 		error = copyinstr(fname, sc->file, sizeof(sc->file), NULL);
967 		if (error != 0)
968 			return (error);
969 	} else
970 		strlcpy(sc->file, fname, sizeof(sc->file));
971 
972 	/*
973 	 * If the user specified that this is a read only device, don't
974 	 * set the FWRITE mask before trying to open the backing store.
975 	 */
976 	flags = FREAD | ((mdio->md_options & MD_READONLY) ? 0 : FWRITE);
977 	NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, sc->file, td);
978 	error = vn_open(&nd, &flags, 0, NULL);
979 	if (error != 0)
980 		return (error);
981 	NDFREE(&nd, NDF_ONLY_PNBUF);
982 	if (nd.ni_vp->v_type != VREG) {
983 		error = EINVAL;
984 		goto bad;
985 	}
986 	error = VOP_GETATTR(nd.ni_vp, &vattr, td->td_ucred);
987 	if (error != 0)
988 		goto bad;
989 	if (VOP_ISLOCKED(nd.ni_vp) != LK_EXCLUSIVE) {
990 		vn_lock(nd.ni_vp, LK_UPGRADE | LK_RETRY);
991 		if (nd.ni_vp->v_iflag & VI_DOOMED) {
992 			/* Forced unmount. */
993 			error = EBADF;
994 			goto bad;
995 		}
996 	}
997 	nd.ni_vp->v_vflag |= VV_MD;
998 	VOP_UNLOCK(nd.ni_vp, 0);
999 
1000 	if (mdio->md_fwsectors != 0)
1001 		sc->fwsectors = mdio->md_fwsectors;
1002 	if (mdio->md_fwheads != 0)
1003 		sc->fwheads = mdio->md_fwheads;
1004 	sc->flags = mdio->md_options & (MD_FORCE | MD_ASYNC);
1005 	if (!(flags & FWRITE))
1006 		sc->flags |= MD_READONLY;
1007 	sc->vnode = nd.ni_vp;
1008 
1009 	error = mdsetcred(sc, td->td_ucred);
1010 	if (error != 0) {
1011 		sc->vnode = NULL;
1012 		vn_lock(nd.ni_vp, LK_EXCLUSIVE | LK_RETRY);
1013 		nd.ni_vp->v_vflag &= ~VV_MD;
1014 		goto bad;
1015 	}
1016 	return (0);
1017 bad:
1018 	VOP_UNLOCK(nd.ni_vp, 0);
1019 	(void)vn_close(nd.ni_vp, flags, td->td_ucred, td);
1020 	return (error);
1021 }
1022 
1023 static int
1024 mddestroy(struct md_s *sc, struct thread *td)
1025 {
1026 
1027 	if (sc->gp) {
1028 		sc->gp->softc = NULL;
1029 		g_topology_lock();
1030 		g_wither_geom(sc->gp, ENXIO);
1031 		g_topology_unlock();
1032 		sc->gp = NULL;
1033 		sc->pp = NULL;
1034 	}
1035 	if (sc->devstat) {
1036 		devstat_remove_entry(sc->devstat);
1037 		sc->devstat = NULL;
1038 	}
1039 	mtx_lock(&sc->queue_mtx);
1040 	sc->flags |= MD_SHUTDOWN;
1041 	wakeup(sc);
1042 	while (!(sc->flags & MD_EXITING))
1043 		msleep(sc->procp, &sc->queue_mtx, PRIBIO, "mddestroy", hz / 10);
1044 	mtx_unlock(&sc->queue_mtx);
1045 	mtx_destroy(&sc->queue_mtx);
1046 	if (sc->vnode != NULL) {
1047 		vn_lock(sc->vnode, LK_EXCLUSIVE | LK_RETRY);
1048 		sc->vnode->v_vflag &= ~VV_MD;
1049 		VOP_UNLOCK(sc->vnode, 0);
1050 		(void)vn_close(sc->vnode, sc->flags & MD_READONLY ?
1051 		    FREAD : (FREAD|FWRITE), sc->cred, td);
1052 	}
1053 	if (sc->cred != NULL)
1054 		crfree(sc->cred);
1055 	if (sc->object != NULL)
1056 		vm_object_deallocate(sc->object);
1057 	if (sc->indir)
1058 		destroy_indir(sc, sc->indir);
1059 	if (sc->uma)
1060 		uma_zdestroy(sc->uma);
1061 
1062 	LIST_REMOVE(sc, list);
1063 	free_unr(md_uh, sc->unit);
1064 	free(sc, M_MD);
1065 	return (0);
1066 }
1067 
1068 static int
1069 mdresize(struct md_s *sc, struct md_ioctl *mdio)
1070 {
1071 	int error, res;
1072 	vm_pindex_t oldpages, newpages;
1073 
1074 	switch (sc->type) {
1075 	case MD_VNODE:
1076 		break;
1077 	case MD_SWAP:
1078 		if (mdio->md_mediasize <= 0 ||
1079 		    (mdio->md_mediasize % PAGE_SIZE) != 0)
1080 			return (EDOM);
1081 		oldpages = OFF_TO_IDX(round_page(sc->mediasize));
1082 		newpages = OFF_TO_IDX(round_page(mdio->md_mediasize));
1083 		if (newpages < oldpages) {
1084 			VM_OBJECT_LOCK(sc->object);
1085 			vm_object_page_remove(sc->object, newpages, 0, 0);
1086 			swap_pager_freespace(sc->object, newpages,
1087 			    oldpages - newpages);
1088 			swap_release_by_cred(IDX_TO_OFF(oldpages -
1089 			    newpages), sc->cred);
1090 			sc->object->charge = IDX_TO_OFF(newpages);
1091 			sc->object->size = newpages;
1092 			VM_OBJECT_UNLOCK(sc->object);
1093 		} else if (newpages > oldpages) {
1094 			res = swap_reserve_by_cred(IDX_TO_OFF(newpages -
1095 			    oldpages), sc->cred);
1096 			if (!res)
1097 				return (ENOMEM);
1098 			if ((mdio->md_options & MD_RESERVE) ||
1099 			    (sc->flags & MD_RESERVE)) {
1100 				error = swap_pager_reserve(sc->object,
1101 				    oldpages, newpages - oldpages);
1102 				if (error < 0) {
1103 					swap_release_by_cred(
1104 					    IDX_TO_OFF(newpages - oldpages),
1105 					    sc->cred);
1106 					return (EDOM);
1107 				}
1108 			}
1109 			VM_OBJECT_LOCK(sc->object);
1110 			sc->object->charge = IDX_TO_OFF(newpages);
1111 			sc->object->size = newpages;
1112 			VM_OBJECT_UNLOCK(sc->object);
1113 		}
1114 		break;
1115 	default:
1116 		return (EOPNOTSUPP);
1117 	}
1118 
1119 	sc->mediasize = mdio->md_mediasize;
1120 	g_topology_lock();
1121 	g_resize_provider(sc->pp, sc->mediasize);
1122 	g_topology_unlock();
1123 	return (0);
1124 }
1125 
1126 static int
1127 mdcreate_swap(struct md_s *sc, struct md_ioctl *mdio, struct thread *td)
1128 {
1129 	vm_ooffset_t npage;
1130 	int error;
1131 
1132 	/*
1133 	 * Range check.  Disallow negative sizes or any size less then the
1134 	 * size of a page.  Then round to a page.
1135 	 */
1136 	if (sc->mediasize <= 0 || (sc->mediasize % PAGE_SIZE) != 0)
1137 		return (EDOM);
1138 
1139 	/*
1140 	 * Allocate an OBJT_SWAP object.
1141 	 *
1142 	 * Note the truncation.
1143 	 */
1144 
1145 	npage = mdio->md_mediasize / PAGE_SIZE;
1146 	if (mdio->md_fwsectors != 0)
1147 		sc->fwsectors = mdio->md_fwsectors;
1148 	if (mdio->md_fwheads != 0)
1149 		sc->fwheads = mdio->md_fwheads;
1150 	sc->object = vm_pager_allocate(OBJT_SWAP, NULL, PAGE_SIZE * npage,
1151 	    VM_PROT_DEFAULT, 0, td->td_ucred);
1152 	if (sc->object == NULL)
1153 		return (ENOMEM);
1154 	sc->flags = mdio->md_options & (MD_FORCE | MD_RESERVE);
1155 	if (mdio->md_options & MD_RESERVE) {
1156 		if (swap_pager_reserve(sc->object, 0, npage) < 0) {
1157 			error = EDOM;
1158 			goto finish;
1159 		}
1160 	}
1161 	error = mdsetcred(sc, td->td_ucred);
1162  finish:
1163 	if (error != 0) {
1164 		vm_object_deallocate(sc->object);
1165 		sc->object = NULL;
1166 	}
1167 	return (error);
1168 }
1169 
1170 
1171 static int
1172 xmdctlioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flags, struct thread *td)
1173 {
1174 	struct md_ioctl *mdio;
1175 	struct md_s *sc;
1176 	int error, i;
1177 	unsigned sectsize;
1178 
1179 	if (md_debug)
1180 		printf("mdctlioctl(%s %lx %p %x %p)\n",
1181 			devtoname(dev), cmd, addr, flags, td);
1182 
1183 	mdio = (struct md_ioctl *)addr;
1184 	if (mdio->md_version != MDIOVERSION)
1185 		return (EINVAL);
1186 
1187 	/*
1188 	 * We assert the version number in the individual ioctl
1189 	 * handlers instead of out here because (a) it is possible we
1190 	 * may add another ioctl in the future which doesn't read an
1191 	 * mdio, and (b) the correct return value for an unknown ioctl
1192 	 * is ENOIOCTL, not EINVAL.
1193 	 */
1194 	error = 0;
1195 	switch (cmd) {
1196 	case MDIOCATTACH:
1197 		switch (mdio->md_type) {
1198 		case MD_MALLOC:
1199 		case MD_PRELOAD:
1200 		case MD_VNODE:
1201 		case MD_SWAP:
1202 			break;
1203 		default:
1204 			return (EINVAL);
1205 		}
1206 		if (mdio->md_sectorsize == 0)
1207 			sectsize = DEV_BSIZE;
1208 		else
1209 			sectsize = mdio->md_sectorsize;
1210 		if (sectsize > MAXPHYS || mdio->md_mediasize < sectsize)
1211 			return (EINVAL);
1212 		if (mdio->md_options & MD_AUTOUNIT)
1213 			sc = mdnew(-1, &error, mdio->md_type);
1214 		else {
1215 			if (mdio->md_unit > INT_MAX)
1216 				return (EINVAL);
1217 			sc = mdnew(mdio->md_unit, &error, mdio->md_type);
1218 		}
1219 		if (sc == NULL)
1220 			return (error);
1221 		if (mdio->md_options & MD_AUTOUNIT)
1222 			mdio->md_unit = sc->unit;
1223 		sc->mediasize = mdio->md_mediasize;
1224 		sc->sectorsize = sectsize;
1225 		error = EDOOFUS;
1226 		switch (sc->type) {
1227 		case MD_MALLOC:
1228 			sc->start = mdstart_malloc;
1229 			error = mdcreate_malloc(sc, mdio);
1230 			break;
1231 		case MD_PRELOAD:
1232 			sc->start = mdstart_preload;
1233 			error = mdcreate_preload(sc, mdio);
1234 			break;
1235 		case MD_VNODE:
1236 			sc->start = mdstart_vnode;
1237 			error = mdcreate_vnode(sc, mdio, td);
1238 			break;
1239 		case MD_SWAP:
1240 			sc->start = mdstart_swap;
1241 			error = mdcreate_swap(sc, mdio, td);
1242 			break;
1243 		}
1244 		if (error != 0) {
1245 			mddestroy(sc, td);
1246 			return (error);
1247 		}
1248 
1249 		/* Prune off any residual fractional sector */
1250 		i = sc->mediasize % sc->sectorsize;
1251 		sc->mediasize -= i;
1252 
1253 		mdinit(sc);
1254 		return (0);
1255 	case MDIOCDETACH:
1256 		if (mdio->md_mediasize != 0 ||
1257 		    (mdio->md_options & ~MD_FORCE) != 0)
1258 			return (EINVAL);
1259 
1260 		sc = mdfind(mdio->md_unit);
1261 		if (sc == NULL)
1262 			return (ENOENT);
1263 		if (sc->opencount != 0 && !(sc->flags & MD_FORCE) &&
1264 		    !(mdio->md_options & MD_FORCE))
1265 			return (EBUSY);
1266 		return (mddestroy(sc, td));
1267 	case MDIOCRESIZE:
1268 		if ((mdio->md_options & ~(MD_FORCE | MD_RESERVE)) != 0)
1269 			return (EINVAL);
1270 
1271 		sc = mdfind(mdio->md_unit);
1272 		if (sc == NULL)
1273 			return (ENOENT);
1274 		if (mdio->md_mediasize < sc->sectorsize)
1275 			return (EINVAL);
1276 		if (mdio->md_mediasize < sc->mediasize &&
1277 		    !(sc->flags & MD_FORCE) &&
1278 		    !(mdio->md_options & MD_FORCE))
1279 			return (EBUSY);
1280 		return (mdresize(sc, mdio));
1281 	case MDIOCQUERY:
1282 		sc = mdfind(mdio->md_unit);
1283 		if (sc == NULL)
1284 			return (ENOENT);
1285 		mdio->md_type = sc->type;
1286 		mdio->md_options = sc->flags;
1287 		mdio->md_mediasize = sc->mediasize;
1288 		mdio->md_sectorsize = sc->sectorsize;
1289 		if (sc->type == MD_VNODE)
1290 			error = copyout(sc->file, mdio->md_file,
1291 			    strlen(sc->file) + 1);
1292 		return (error);
1293 	case MDIOCLIST:
1294 		i = 1;
1295 		LIST_FOREACH(sc, &md_softc_list, list) {
1296 			if (i == MDNPAD - 1)
1297 				mdio->md_pad[i] = -1;
1298 			else
1299 				mdio->md_pad[i++] = sc->unit;
1300 		}
1301 		mdio->md_pad[0] = i - 1;
1302 		return (0);
1303 	default:
1304 		return (ENOIOCTL);
1305 	};
1306 }
1307 
1308 static int
1309 mdctlioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flags, struct thread *td)
1310 {
1311 	int error;
1312 
1313 	sx_xlock(&md_sx);
1314 	error = xmdctlioctl(dev, cmd, addr, flags, td);
1315 	sx_xunlock(&md_sx);
1316 	return (error);
1317 }
1318 
1319 static void
1320 md_preloaded(u_char *image, size_t length)
1321 {
1322 	struct md_s *sc;
1323 	int error;
1324 
1325 	sc = mdnew(-1, &error, MD_PRELOAD);
1326 	if (sc == NULL)
1327 		return;
1328 	sc->mediasize = length;
1329 	sc->sectorsize = DEV_BSIZE;
1330 	sc->pl_ptr = image;
1331 	sc->pl_len = length;
1332 	sc->start = mdstart_preload;
1333 #ifdef MD_ROOT
1334 	if (sc->unit == 0)
1335 		rootdevnames[0] = MD_ROOT_FSTYPE ":/dev/md0";
1336 #endif
1337 	mdinit(sc);
1338 }
1339 
1340 static void
1341 g_md_init(struct g_class *mp __unused)
1342 {
1343 	caddr_t mod;
1344 	u_char *ptr, *name, *type;
1345 	unsigned len;
1346 	int i;
1347 
1348 	/* figure out log2(NINDIR) */
1349 	for (i = NINDIR, nshift = -1; i; nshift++)
1350 		i >>= 1;
1351 
1352 	mod = NULL;
1353 	sx_init(&md_sx, "MD config lock");
1354 	g_topology_unlock();
1355 	md_uh = new_unrhdr(0, INT_MAX, NULL);
1356 #ifdef MD_ROOT_SIZE
1357 	sx_xlock(&md_sx);
1358 	md_preloaded(mfs_root.start, sizeof(mfs_root.start));
1359 	sx_xunlock(&md_sx);
1360 #endif
1361 	/* XXX: are preload_* static or do they need Giant ? */
1362 	while ((mod = preload_search_next_name(mod)) != NULL) {
1363 		name = (char *)preload_search_info(mod, MODINFO_NAME);
1364 		if (name == NULL)
1365 			continue;
1366 		type = (char *)preload_search_info(mod, MODINFO_TYPE);
1367 		if (type == NULL)
1368 			continue;
1369 		if (strcmp(type, "md_image") && strcmp(type, "mfs_root"))
1370 			continue;
1371 		ptr = preload_fetch_addr(mod);
1372 		len = preload_fetch_size(mod);
1373 		if (ptr != NULL && len != 0) {
1374 			printf("%s%d: Preloaded image <%s> %d bytes at %p\n",
1375 			    MD_NAME, mdunits, name, len, ptr);
1376 			sx_xlock(&md_sx);
1377 			md_preloaded(ptr, len);
1378 			sx_xunlock(&md_sx);
1379 		}
1380 	}
1381 	status_dev = make_dev(&mdctl_cdevsw, INT_MAX, UID_ROOT, GID_WHEEL,
1382 	    0600, MDCTL_NAME);
1383 	g_topology_lock();
1384 }
1385 
1386 static void
1387 g_md_dumpconf(struct sbuf *sb, const char *indent, struct g_geom *gp,
1388     struct g_consumer *cp __unused, struct g_provider *pp)
1389 {
1390 	struct md_s *mp;
1391 	char *type;
1392 
1393 	mp = gp->softc;
1394 	if (mp == NULL)
1395 		return;
1396 
1397 	switch (mp->type) {
1398 	case MD_MALLOC:
1399 		type = "malloc";
1400 		break;
1401 	case MD_PRELOAD:
1402 		type = "preload";
1403 		break;
1404 	case MD_VNODE:
1405 		type = "vnode";
1406 		break;
1407 	case MD_SWAP:
1408 		type = "swap";
1409 		break;
1410 	default:
1411 		type = "unknown";
1412 		break;
1413 	}
1414 
1415 	if (pp != NULL) {
1416 		if (indent == NULL) {
1417 			sbuf_printf(sb, " u %d", mp->unit);
1418 			sbuf_printf(sb, " s %ju", (uintmax_t) mp->sectorsize);
1419 			sbuf_printf(sb, " f %ju", (uintmax_t) mp->fwheads);
1420 			sbuf_printf(sb, " fs %ju", (uintmax_t) mp->fwsectors);
1421 			sbuf_printf(sb, " l %ju", (uintmax_t) mp->mediasize);
1422 			sbuf_printf(sb, " t %s", type);
1423 			if (mp->type == MD_VNODE && mp->vnode != NULL)
1424 				sbuf_printf(sb, " file %s", mp->file);
1425 		} else {
1426 			sbuf_printf(sb, "%s<unit>%d</unit>\n", indent,
1427 			    mp->unit);
1428 			sbuf_printf(sb, "%s<sectorsize>%ju</sectorsize>\n",
1429 			    indent, (uintmax_t) mp->sectorsize);
1430 			sbuf_printf(sb, "%s<fwheads>%ju</fwheads>\n",
1431 			    indent, (uintmax_t) mp->fwheads);
1432 			sbuf_printf(sb, "%s<fwsectors>%ju</fwsectors>\n",
1433 			    indent, (uintmax_t) mp->fwsectors);
1434 			sbuf_printf(sb, "%s<length>%ju</length>\n",
1435 			    indent, (uintmax_t) mp->mediasize);
1436 			sbuf_printf(sb, "%s<compression>%s</compression>\n", indent,
1437 			    (mp->flags & MD_COMPRESS) == 0 ? "off": "on");
1438 			sbuf_printf(sb, "%s<access>%s</access>\n", indent,
1439 			    (mp->flags & MD_READONLY) == 0 ? "read-write":
1440 			    "read-only");
1441 			sbuf_printf(sb, "%s<type>%s</type>\n", indent,
1442 			    type);
1443 			if (mp->type == MD_VNODE && mp->vnode != NULL)
1444 				sbuf_printf(sb, "%s<file>%s</file>\n",
1445 				    indent, mp->file);
1446 		}
1447 	}
1448 }
1449 
1450 static void
1451 g_md_fini(struct g_class *mp __unused)
1452 {
1453 
1454 	sx_destroy(&md_sx);
1455 	if (status_dev != NULL)
1456 		destroy_dev(status_dev);
1457 	delete_unrhdr(md_uh);
1458 }
1459