xref: /freebsd/sys/dev/md/md.c (revision e17f5b1d)
1 /*-
2  * SPDX-License-Identifier: (Beerware AND BSD-3-Clause)
3  *
4  * ----------------------------------------------------------------------------
5  * "THE BEER-WARE LICENSE" (Revision 42):
6  * <phk@FreeBSD.ORG> wrote this file.  As long as you retain this notice you
7  * can do whatever you want with this stuff. If we meet some day, and you think
8  * this stuff is worth it, you can buy me a beer in return.   Poul-Henning Kamp
9  * ----------------------------------------------------------------------------
10  *
11  * $FreeBSD$
12  *
13  */
14 
15 /*-
16  * The following functions are based in the vn(4) driver: mdstart_swap(),
17  * mdstart_vnode(), mdcreate_swap(), mdcreate_vnode() and mddestroy(),
18  * and as such under the following copyright:
19  *
20  * Copyright (c) 1988 University of Utah.
21  * Copyright (c) 1990, 1993
22  *	The Regents of the University of California.  All rights reserved.
23  * Copyright (c) 2013 The FreeBSD Foundation
24  * All rights reserved.
25  *
26  * This code is derived from software contributed to Berkeley by
27  * the Systems Programming Group of the University of Utah Computer
28  * Science Department.
29  *
30  * Portions of this software were developed by Konstantin Belousov
31  * under sponsorship from the FreeBSD Foundation.
32  *
33  * Redistribution and use in source and binary forms, with or without
34  * modification, are permitted provided that the following conditions
35  * are met:
36  * 1. Redistributions of source code must retain the above copyright
37  *    notice, this list of conditions and the following disclaimer.
38  * 2. Redistributions in binary form must reproduce the above copyright
39  *    notice, this list of conditions and the following disclaimer in the
40  *    documentation and/or other materials provided with the distribution.
41  * 3. Neither the name of the University nor the names of its contributors
42  *    may be used to endorse or promote products derived from this software
43  *    without specific prior written permission.
44  *
45  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
46  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
47  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
48  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
49  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
50  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
51  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
52  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
53  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
54  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
55  * SUCH DAMAGE.
56  *
57  * from: Utah Hdr: vn.c 1.13 94/04/02
58  *
59  *	from: @(#)vn.c	8.6 (Berkeley) 4/1/94
60  * From: src/sys/dev/vn/vn.c,v 1.122 2000/12/16 16:06:03
61  */
62 
63 #include "opt_rootdevname.h"
64 #include "opt_geom.h"
65 #include "opt_md.h"
66 
67 #include <sys/param.h>
68 #include <sys/systm.h>
69 #include <sys/bio.h>
70 #include <sys/buf.h>
71 #include <sys/conf.h>
72 #include <sys/devicestat.h>
73 #include <sys/fcntl.h>
74 #include <sys/kernel.h>
75 #include <sys/kthread.h>
76 #include <sys/limits.h>
77 #include <sys/linker.h>
78 #include <sys/lock.h>
79 #include <sys/malloc.h>
80 #include <sys/mdioctl.h>
81 #include <sys/mount.h>
82 #include <sys/mutex.h>
83 #include <sys/sx.h>
84 #include <sys/namei.h>
85 #include <sys/proc.h>
86 #include <sys/queue.h>
87 #include <sys/rwlock.h>
88 #include <sys/sbuf.h>
89 #include <sys/sched.h>
90 #include <sys/sf_buf.h>
91 #include <sys/sysctl.h>
92 #include <sys/uio.h>
93 #include <sys/vnode.h>
94 #include <sys/disk.h>
95 
96 #include <geom/geom.h>
97 #include <geom/geom_int.h>
98 
99 #include <vm/vm.h>
100 #include <vm/vm_param.h>
101 #include <vm/vm_object.h>
102 #include <vm/vm_page.h>
103 #include <vm/vm_pager.h>
104 #include <vm/swap_pager.h>
105 #include <vm/uma.h>
106 
107 #include <machine/bus.h>
108 
109 #define MD_MODVER 1
110 
111 #define MD_SHUTDOWN	0x10000		/* Tell worker thread to terminate. */
112 #define	MD_EXITING	0x20000		/* Worker thread is exiting. */
113 #define MD_PROVIDERGONE	0x40000		/* Safe to free the softc */
114 
115 #ifndef MD_NSECT
116 #define MD_NSECT (10000 * 2)
117 #endif
118 
119 struct md_req {
120 	unsigned	md_unit;	/* unit number */
121 	enum md_types	md_type;	/* type of disk */
122 	off_t		md_mediasize;	/* size of disk in bytes */
123 	unsigned	md_sectorsize;	/* sectorsize */
124 	unsigned	md_options;	/* options */
125 	int		md_fwheads;	/* firmware heads */
126 	int		md_fwsectors;	/* firmware sectors */
127 	char		*md_file;	/* pathname of file to mount */
128 	enum uio_seg	md_file_seg;	/* location of md_file */
129 	char		*md_label;	/* label of the device (userspace) */
130 	int		*md_units;	/* pointer to units array (kernel) */
131 	size_t		md_units_nitems; /* items in md_units array */
132 };
133 
134 #ifdef COMPAT_FREEBSD32
135 struct md_ioctl32 {
136 	unsigned	md_version;
137 	unsigned	md_unit;
138 	enum md_types	md_type;
139 	uint32_t	md_file;
140 	off_t		md_mediasize;
141 	unsigned	md_sectorsize;
142 	unsigned	md_options;
143 	uint64_t	md_base;
144 	int		md_fwheads;
145 	int		md_fwsectors;
146 	uint32_t	md_label;
147 	int		md_pad[MDNPAD];
148 } __attribute__((__packed__));
149 CTASSERT((sizeof(struct md_ioctl32)) == 436);
150 
151 #define	MDIOCATTACH_32	_IOC_NEWTYPE(MDIOCATTACH, struct md_ioctl32)
152 #define	MDIOCDETACH_32	_IOC_NEWTYPE(MDIOCDETACH, struct md_ioctl32)
153 #define	MDIOCQUERY_32	_IOC_NEWTYPE(MDIOCQUERY, struct md_ioctl32)
154 #define	MDIOCRESIZE_32	_IOC_NEWTYPE(MDIOCRESIZE, struct md_ioctl32)
155 #endif /* COMPAT_FREEBSD32 */
156 
157 static MALLOC_DEFINE(M_MD, "md_disk", "Memory Disk");
158 static MALLOC_DEFINE(M_MDSECT, "md_sectors", "Memory Disk Sectors");
159 
160 static int md_debug;
161 SYSCTL_INT(_debug, OID_AUTO, mddebug, CTLFLAG_RW, &md_debug, 0,
162     "Enable md(4) debug messages");
163 static int md_malloc_wait;
164 SYSCTL_INT(_vm, OID_AUTO, md_malloc_wait, CTLFLAG_RW, &md_malloc_wait, 0,
165     "Allow malloc to wait for memory allocations");
166 
167 #if defined(MD_ROOT) && !defined(MD_ROOT_FSTYPE)
168 #define	MD_ROOT_FSTYPE	"ufs"
169 #endif
170 
171 #if defined(MD_ROOT)
172 /*
173  * Preloaded image gets put here.
174  */
175 #if defined(MD_ROOT_SIZE)
176 /*
177  * We put the mfs_root symbol into the oldmfs section of the kernel object file.
178  * Applications that patch the object with the image can determine
179  * the size looking at the oldmfs section size within the kernel.
180  */
181 u_char mfs_root[MD_ROOT_SIZE*1024] __attribute__ ((section ("oldmfs")));
182 const int mfs_root_size = sizeof(mfs_root);
183 #elif defined(MD_ROOT_MEM)
184 /* MD region already mapped in the memory */
185 u_char *mfs_root;
186 int mfs_root_size;
187 #else
188 extern volatile u_char __weak_symbol mfs_root;
189 extern volatile u_char __weak_symbol mfs_root_end;
190 __GLOBL(mfs_root);
191 __GLOBL(mfs_root_end);
192 #define mfs_root_size ((uintptr_t)(&mfs_root_end - &mfs_root))
193 #endif
194 #endif
195 
196 static g_init_t g_md_init;
197 static g_fini_t g_md_fini;
198 static g_start_t g_md_start;
199 static g_access_t g_md_access;
200 static void g_md_dumpconf(struct sbuf *sb, const char *indent,
201     struct g_geom *gp, struct g_consumer *cp __unused, struct g_provider *pp);
202 static g_provgone_t g_md_providergone;
203 
204 static struct cdev *status_dev = NULL;
205 static struct sx md_sx;
206 static struct unrhdr *md_uh;
207 
208 static d_ioctl_t mdctlioctl;
209 
210 static struct cdevsw mdctl_cdevsw = {
211 	.d_version =	D_VERSION,
212 	.d_ioctl =	mdctlioctl,
213 	.d_name =	MD_NAME,
214 };
215 
216 struct g_class g_md_class = {
217 	.name = "MD",
218 	.version = G_VERSION,
219 	.init = g_md_init,
220 	.fini = g_md_fini,
221 	.start = g_md_start,
222 	.access = g_md_access,
223 	.dumpconf = g_md_dumpconf,
224 	.providergone = g_md_providergone,
225 };
226 
227 DECLARE_GEOM_CLASS(g_md_class, g_md);
228 
229 
230 static LIST_HEAD(, md_s) md_softc_list = LIST_HEAD_INITIALIZER(md_softc_list);
231 
232 #define NINDIR	(PAGE_SIZE / sizeof(uintptr_t))
233 #define NMASK	(NINDIR-1)
234 static int nshift;
235 
236 static uma_zone_t md_pbuf_zone;
237 
238 struct indir {
239 	uintptr_t	*array;
240 	u_int		total;
241 	u_int		used;
242 	u_int		shift;
243 };
244 
245 struct md_s {
246 	int unit;
247 	LIST_ENTRY(md_s) list;
248 	struct bio_queue_head bio_queue;
249 	struct mtx queue_mtx;
250 	struct cdev *dev;
251 	enum md_types type;
252 	off_t mediasize;
253 	unsigned sectorsize;
254 	unsigned opencount;
255 	unsigned fwheads;
256 	unsigned fwsectors;
257 	char ident[32];
258 	unsigned flags;
259 	char name[20];
260 	struct proc *procp;
261 	struct g_geom *gp;
262 	struct g_provider *pp;
263 	int (*start)(struct md_s *sc, struct bio *bp);
264 	struct devstat *devstat;
265 
266 	/* MD_MALLOC related fields */
267 	struct indir *indir;
268 	uma_zone_t uma;
269 
270 	/* MD_PRELOAD related fields */
271 	u_char *pl_ptr;
272 	size_t pl_len;
273 
274 	/* MD_VNODE related fields */
275 	struct vnode *vnode;
276 	char file[PATH_MAX];
277 	char label[PATH_MAX];
278 	struct ucred *cred;
279 
280 	/* MD_SWAP related fields */
281 	vm_object_t object;
282 };
283 
284 static struct indir *
285 new_indir(u_int shift)
286 {
287 	struct indir *ip;
288 
289 	ip = malloc(sizeof *ip, M_MD, (md_malloc_wait ? M_WAITOK : M_NOWAIT)
290 	    | M_ZERO);
291 	if (ip == NULL)
292 		return (NULL);
293 	ip->array = malloc(sizeof(uintptr_t) * NINDIR,
294 	    M_MDSECT, (md_malloc_wait ? M_WAITOK : M_NOWAIT) | M_ZERO);
295 	if (ip->array == NULL) {
296 		free(ip, M_MD);
297 		return (NULL);
298 	}
299 	ip->total = NINDIR;
300 	ip->shift = shift;
301 	return (ip);
302 }
303 
304 static void
305 del_indir(struct indir *ip)
306 {
307 
308 	free(ip->array, M_MDSECT);
309 	free(ip, M_MD);
310 }
311 
312 static void
313 destroy_indir(struct md_s *sc, struct indir *ip)
314 {
315 	int i;
316 
317 	for (i = 0; i < NINDIR; i++) {
318 		if (!ip->array[i])
319 			continue;
320 		if (ip->shift)
321 			destroy_indir(sc, (struct indir*)(ip->array[i]));
322 		else if (ip->array[i] > 255)
323 			uma_zfree(sc->uma, (void *)(ip->array[i]));
324 	}
325 	del_indir(ip);
326 }
327 
328 /*
329  * This function does the math and allocates the top level "indir" structure
330  * for a device of "size" sectors.
331  */
332 
333 static struct indir *
334 dimension(off_t size)
335 {
336 	off_t rcnt;
337 	struct indir *ip;
338 	int layer;
339 
340 	rcnt = size;
341 	layer = 0;
342 	while (rcnt > NINDIR) {
343 		rcnt /= NINDIR;
344 		layer++;
345 	}
346 
347 	/*
348 	 * XXX: the top layer is probably not fully populated, so we allocate
349 	 * too much space for ip->array in here.
350 	 */
351 	ip = malloc(sizeof *ip, M_MD, M_WAITOK | M_ZERO);
352 	ip->array = malloc(sizeof(uintptr_t) * NINDIR,
353 	    M_MDSECT, M_WAITOK | M_ZERO);
354 	ip->total = NINDIR;
355 	ip->shift = layer * nshift;
356 	return (ip);
357 }
358 
359 /*
360  * Read a given sector
361  */
362 
363 static uintptr_t
364 s_read(struct indir *ip, off_t offset)
365 {
366 	struct indir *cip;
367 	int idx;
368 	uintptr_t up;
369 
370 	if (md_debug > 1)
371 		printf("s_read(%jd)\n", (intmax_t)offset);
372 	up = 0;
373 	for (cip = ip; cip != NULL;) {
374 		if (cip->shift) {
375 			idx = (offset >> cip->shift) & NMASK;
376 			up = cip->array[idx];
377 			cip = (struct indir *)up;
378 			continue;
379 		}
380 		idx = offset & NMASK;
381 		return (cip->array[idx]);
382 	}
383 	return (0);
384 }
385 
386 /*
387  * Write a given sector, prune the tree if the value is 0
388  */
389 
390 static int
391 s_write(struct indir *ip, off_t offset, uintptr_t ptr)
392 {
393 	struct indir *cip, *lip[10];
394 	int idx, li;
395 	uintptr_t up;
396 
397 	if (md_debug > 1)
398 		printf("s_write(%jd, %p)\n", (intmax_t)offset, (void *)ptr);
399 	up = 0;
400 	li = 0;
401 	cip = ip;
402 	for (;;) {
403 		lip[li++] = cip;
404 		if (cip->shift) {
405 			idx = (offset >> cip->shift) & NMASK;
406 			up = cip->array[idx];
407 			if (up != 0) {
408 				cip = (struct indir *)up;
409 				continue;
410 			}
411 			/* Allocate branch */
412 			cip->array[idx] =
413 			    (uintptr_t)new_indir(cip->shift - nshift);
414 			if (cip->array[idx] == 0)
415 				return (ENOSPC);
416 			cip->used++;
417 			up = cip->array[idx];
418 			cip = (struct indir *)up;
419 			continue;
420 		}
421 		/* leafnode */
422 		idx = offset & NMASK;
423 		up = cip->array[idx];
424 		if (up != 0)
425 			cip->used--;
426 		cip->array[idx] = ptr;
427 		if (ptr != 0)
428 			cip->used++;
429 		break;
430 	}
431 	if (cip->used != 0 || li == 1)
432 		return (0);
433 	li--;
434 	while (cip->used == 0 && cip != ip) {
435 		li--;
436 		idx = (offset >> lip[li]->shift) & NMASK;
437 		up = lip[li]->array[idx];
438 		KASSERT(up == (uintptr_t)cip, ("md screwed up"));
439 		del_indir(cip);
440 		lip[li]->array[idx] = 0;
441 		lip[li]->used--;
442 		cip = lip[li];
443 	}
444 	return (0);
445 }
446 
447 
448 static int
449 g_md_access(struct g_provider *pp, int r, int w, int e)
450 {
451 	struct md_s *sc;
452 
453 	sc = pp->geom->softc;
454 	if (sc == NULL) {
455 		if (r <= 0 && w <= 0 && e <= 0)
456 			return (0);
457 		return (ENXIO);
458 	}
459 	r += pp->acr;
460 	w += pp->acw;
461 	e += pp->ace;
462 	if ((sc->flags & MD_READONLY) != 0 && w > 0)
463 		return (EROFS);
464 	if ((pp->acr + pp->acw + pp->ace) == 0 && (r + w + e) > 0) {
465 		sc->opencount = 1;
466 	} else if ((pp->acr + pp->acw + pp->ace) > 0 && (r + w + e) == 0) {
467 		sc->opencount = 0;
468 	}
469 	return (0);
470 }
471 
472 static void
473 g_md_start(struct bio *bp)
474 {
475 	struct md_s *sc;
476 
477 	sc = bp->bio_to->geom->softc;
478 	if ((bp->bio_cmd == BIO_READ) || (bp->bio_cmd == BIO_WRITE)) {
479 		devstat_start_transaction_bio(sc->devstat, bp);
480 	}
481 	mtx_lock(&sc->queue_mtx);
482 	bioq_disksort(&sc->bio_queue, bp);
483 	wakeup(sc);
484 	mtx_unlock(&sc->queue_mtx);
485 }
486 
487 #define	MD_MALLOC_MOVE_ZERO	1
488 #define	MD_MALLOC_MOVE_FILL	2
489 #define	MD_MALLOC_MOVE_READ	3
490 #define	MD_MALLOC_MOVE_WRITE	4
491 #define	MD_MALLOC_MOVE_CMP	5
492 
493 static int
494 md_malloc_move_ma(vm_page_t **mp, int *ma_offs, unsigned sectorsize,
495     void *ptr, u_char fill, int op)
496 {
497 	struct sf_buf *sf;
498 	vm_page_t m, *mp1;
499 	char *p, first;
500 	off_t *uc;
501 	unsigned n;
502 	int error, i, ma_offs1, sz, first_read;
503 
504 	m = NULL;
505 	error = 0;
506 	sf = NULL;
507 	/* if (op == MD_MALLOC_MOVE_CMP) { gcc */
508 		first = 0;
509 		first_read = 0;
510 		uc = ptr;
511 		mp1 = *mp;
512 		ma_offs1 = *ma_offs;
513 	/* } */
514 	sched_pin();
515 	for (n = sectorsize; n != 0; n -= sz) {
516 		sz = imin(PAGE_SIZE - *ma_offs, n);
517 		if (m != **mp) {
518 			if (sf != NULL)
519 				sf_buf_free(sf);
520 			m = **mp;
521 			sf = sf_buf_alloc(m, SFB_CPUPRIVATE |
522 			    (md_malloc_wait ? 0 : SFB_NOWAIT));
523 			if (sf == NULL) {
524 				error = ENOMEM;
525 				break;
526 			}
527 		}
528 		p = (char *)sf_buf_kva(sf) + *ma_offs;
529 		switch (op) {
530 		case MD_MALLOC_MOVE_ZERO:
531 			bzero(p, sz);
532 			break;
533 		case MD_MALLOC_MOVE_FILL:
534 			memset(p, fill, sz);
535 			break;
536 		case MD_MALLOC_MOVE_READ:
537 			bcopy(ptr, p, sz);
538 			cpu_flush_dcache(p, sz);
539 			break;
540 		case MD_MALLOC_MOVE_WRITE:
541 			bcopy(p, ptr, sz);
542 			break;
543 		case MD_MALLOC_MOVE_CMP:
544 			for (i = 0; i < sz; i++, p++) {
545 				if (!first_read) {
546 					*uc = (u_char)*p;
547 					first = *p;
548 					first_read = 1;
549 				} else if (*p != first) {
550 					error = EDOOFUS;
551 					break;
552 				}
553 			}
554 			break;
555 		default:
556 			KASSERT(0, ("md_malloc_move_ma unknown op %d\n", op));
557 			break;
558 		}
559 		if (error != 0)
560 			break;
561 		*ma_offs += sz;
562 		*ma_offs %= PAGE_SIZE;
563 		if (*ma_offs == 0)
564 			(*mp)++;
565 		ptr = (char *)ptr + sz;
566 	}
567 
568 	if (sf != NULL)
569 		sf_buf_free(sf);
570 	sched_unpin();
571 	if (op == MD_MALLOC_MOVE_CMP && error != 0) {
572 		*mp = mp1;
573 		*ma_offs = ma_offs1;
574 	}
575 	return (error);
576 }
577 
578 static int
579 md_malloc_move_vlist(bus_dma_segment_t **pvlist, int *pma_offs,
580     unsigned len, void *ptr, u_char fill, int op)
581 {
582 	bus_dma_segment_t *vlist;
583 	uint8_t *p, *end, first;
584 	off_t *uc;
585 	int ma_offs, seg_len;
586 
587 	vlist = *pvlist;
588 	ma_offs = *pma_offs;
589 	uc = ptr;
590 
591 	for (; len != 0; len -= seg_len) {
592 		seg_len = imin(vlist->ds_len - ma_offs, len);
593 		p = (uint8_t *)(uintptr_t)vlist->ds_addr + ma_offs;
594 		switch (op) {
595 		case MD_MALLOC_MOVE_ZERO:
596 			bzero(p, seg_len);
597 			break;
598 		case MD_MALLOC_MOVE_FILL:
599 			memset(p, fill, seg_len);
600 			break;
601 		case MD_MALLOC_MOVE_READ:
602 			bcopy(ptr, p, seg_len);
603 			cpu_flush_dcache(p, seg_len);
604 			break;
605 		case MD_MALLOC_MOVE_WRITE:
606 			bcopy(p, ptr, seg_len);
607 			break;
608 		case MD_MALLOC_MOVE_CMP:
609 			end = p + seg_len;
610 			first = *uc = *p;
611 			/* Confirm all following bytes match the first */
612 			while (++p < end) {
613 				if (*p != first)
614 					return (EDOOFUS);
615 			}
616 			break;
617 		default:
618 			KASSERT(0, ("md_malloc_move_vlist unknown op %d\n", op));
619 			break;
620 		}
621 
622 		ma_offs += seg_len;
623 		if (ma_offs == vlist->ds_len) {
624 			ma_offs = 0;
625 			vlist++;
626 		}
627 		ptr = (uint8_t *)ptr + seg_len;
628 	}
629 	*pvlist = vlist;
630 	*pma_offs = ma_offs;
631 
632 	return (0);
633 }
634 
635 static int
636 mdstart_malloc(struct md_s *sc, struct bio *bp)
637 {
638 	u_char *dst;
639 	vm_page_t *m;
640 	bus_dma_segment_t *vlist;
641 	int i, error, error1, ma_offs, notmapped;
642 	off_t secno, nsec, uc;
643 	uintptr_t sp, osp;
644 
645 	switch (bp->bio_cmd) {
646 	case BIO_READ:
647 	case BIO_WRITE:
648 	case BIO_DELETE:
649 		break;
650 	default:
651 		return (EOPNOTSUPP);
652 	}
653 
654 	notmapped = (bp->bio_flags & BIO_UNMAPPED) != 0;
655 	vlist = (bp->bio_flags & BIO_VLIST) != 0 ?
656 	    (bus_dma_segment_t *)bp->bio_data : NULL;
657 	if (notmapped) {
658 		m = bp->bio_ma;
659 		ma_offs = bp->bio_ma_offset;
660 		dst = NULL;
661 		KASSERT(vlist == NULL, ("vlists cannot be unmapped"));
662 	} else if (vlist != NULL) {
663 		ma_offs = bp->bio_ma_offset;
664 		dst = NULL;
665 	} else {
666 		dst = bp->bio_data;
667 	}
668 
669 	nsec = bp->bio_length / sc->sectorsize;
670 	secno = bp->bio_offset / sc->sectorsize;
671 	error = 0;
672 	while (nsec--) {
673 		osp = s_read(sc->indir, secno);
674 		if (bp->bio_cmd == BIO_DELETE) {
675 			if (osp != 0)
676 				error = s_write(sc->indir, secno, 0);
677 		} else if (bp->bio_cmd == BIO_READ) {
678 			if (osp == 0) {
679 				if (notmapped) {
680 					error = md_malloc_move_ma(&m, &ma_offs,
681 					    sc->sectorsize, NULL, 0,
682 					    MD_MALLOC_MOVE_ZERO);
683 				} else if (vlist != NULL) {
684 					error = md_malloc_move_vlist(&vlist,
685 					    &ma_offs, sc->sectorsize, NULL, 0,
686 					    MD_MALLOC_MOVE_ZERO);
687 				} else
688 					bzero(dst, sc->sectorsize);
689 			} else if (osp <= 255) {
690 				if (notmapped) {
691 					error = md_malloc_move_ma(&m, &ma_offs,
692 					    sc->sectorsize, NULL, osp,
693 					    MD_MALLOC_MOVE_FILL);
694 				} else if (vlist != NULL) {
695 					error = md_malloc_move_vlist(&vlist,
696 					    &ma_offs, sc->sectorsize, NULL, osp,
697 					    MD_MALLOC_MOVE_FILL);
698 				} else
699 					memset(dst, osp, sc->sectorsize);
700 			} else {
701 				if (notmapped) {
702 					error = md_malloc_move_ma(&m, &ma_offs,
703 					    sc->sectorsize, (void *)osp, 0,
704 					    MD_MALLOC_MOVE_READ);
705 				} else if (vlist != NULL) {
706 					error = md_malloc_move_vlist(&vlist,
707 					    &ma_offs, sc->sectorsize,
708 					    (void *)osp, 0,
709 					    MD_MALLOC_MOVE_READ);
710 				} else {
711 					bcopy((void *)osp, dst, sc->sectorsize);
712 					cpu_flush_dcache(dst, sc->sectorsize);
713 				}
714 			}
715 			osp = 0;
716 		} else if (bp->bio_cmd == BIO_WRITE) {
717 			if (sc->flags & MD_COMPRESS) {
718 				if (notmapped) {
719 					error1 = md_malloc_move_ma(&m, &ma_offs,
720 					    sc->sectorsize, &uc, 0,
721 					    MD_MALLOC_MOVE_CMP);
722 					i = error1 == 0 ? sc->sectorsize : 0;
723 				} else if (vlist != NULL) {
724 					error1 = md_malloc_move_vlist(&vlist,
725 					    &ma_offs, sc->sectorsize, &uc, 0,
726 					    MD_MALLOC_MOVE_CMP);
727 					i = error1 == 0 ? sc->sectorsize : 0;
728 				} else {
729 					uc = dst[0];
730 					for (i = 1; i < sc->sectorsize; i++) {
731 						if (dst[i] != uc)
732 							break;
733 					}
734 				}
735 			} else {
736 				i = 0;
737 				uc = 0;
738 			}
739 			if (i == sc->sectorsize) {
740 				if (osp != uc)
741 					error = s_write(sc->indir, secno, uc);
742 			} else {
743 				if (osp <= 255) {
744 					sp = (uintptr_t)uma_zalloc(sc->uma,
745 					    md_malloc_wait ? M_WAITOK :
746 					    M_NOWAIT);
747 					if (sp == 0) {
748 						error = ENOSPC;
749 						break;
750 					}
751 					if (notmapped) {
752 						error = md_malloc_move_ma(&m,
753 						    &ma_offs, sc->sectorsize,
754 						    (void *)sp, 0,
755 						    MD_MALLOC_MOVE_WRITE);
756 					} else if (vlist != NULL) {
757 						error = md_malloc_move_vlist(
758 						    &vlist, &ma_offs,
759 						    sc->sectorsize, (void *)sp,
760 						    0, MD_MALLOC_MOVE_WRITE);
761 					} else {
762 						bcopy(dst, (void *)sp,
763 						    sc->sectorsize);
764 					}
765 					error = s_write(sc->indir, secno, sp);
766 				} else {
767 					if (notmapped) {
768 						error = md_malloc_move_ma(&m,
769 						    &ma_offs, sc->sectorsize,
770 						    (void *)osp, 0,
771 						    MD_MALLOC_MOVE_WRITE);
772 					} else if (vlist != NULL) {
773 						error = md_malloc_move_vlist(
774 						    &vlist, &ma_offs,
775 						    sc->sectorsize, (void *)osp,
776 						    0, MD_MALLOC_MOVE_WRITE);
777 					} else {
778 						bcopy(dst, (void *)osp,
779 						    sc->sectorsize);
780 					}
781 					osp = 0;
782 				}
783 			}
784 		} else {
785 			error = EOPNOTSUPP;
786 		}
787 		if (osp > 255)
788 			uma_zfree(sc->uma, (void*)osp);
789 		if (error != 0)
790 			break;
791 		secno++;
792 		if (!notmapped && vlist == NULL)
793 			dst += sc->sectorsize;
794 	}
795 	bp->bio_resid = 0;
796 	return (error);
797 }
798 
799 static void
800 mdcopyto_vlist(void *src, bus_dma_segment_t *vlist, off_t offset, off_t len)
801 {
802 	off_t seg_len;
803 
804 	while (offset >= vlist->ds_len) {
805 		offset -= vlist->ds_len;
806 		vlist++;
807 	}
808 
809 	while (len != 0) {
810 		seg_len = omin(len, vlist->ds_len - offset);
811 		bcopy(src, (void *)(uintptr_t)(vlist->ds_addr + offset),
812 		    seg_len);
813 		offset = 0;
814 		src = (uint8_t *)src + seg_len;
815 		len -= seg_len;
816 		vlist++;
817 	}
818 }
819 
820 static void
821 mdcopyfrom_vlist(bus_dma_segment_t *vlist, off_t offset, void *dst, off_t len)
822 {
823 	off_t seg_len;
824 
825 	while (offset >= vlist->ds_len) {
826 		offset -= vlist->ds_len;
827 		vlist++;
828 	}
829 
830 	while (len != 0) {
831 		seg_len = omin(len, vlist->ds_len - offset);
832 		bcopy((void *)(uintptr_t)(vlist->ds_addr + offset), dst,
833 		    seg_len);
834 		offset = 0;
835 		dst = (uint8_t *)dst + seg_len;
836 		len -= seg_len;
837 		vlist++;
838 	}
839 }
840 
841 static int
842 mdstart_preload(struct md_s *sc, struct bio *bp)
843 {
844 	uint8_t *p;
845 
846 	p = sc->pl_ptr + bp->bio_offset;
847 	switch (bp->bio_cmd) {
848 	case BIO_READ:
849 		if ((bp->bio_flags & BIO_VLIST) != 0) {
850 			mdcopyto_vlist(p, (bus_dma_segment_t *)bp->bio_data,
851 			    bp->bio_ma_offset, bp->bio_length);
852 		} else {
853 			bcopy(p, bp->bio_data, bp->bio_length);
854 		}
855 		cpu_flush_dcache(bp->bio_data, bp->bio_length);
856 		break;
857 	case BIO_WRITE:
858 		if ((bp->bio_flags & BIO_VLIST) != 0) {
859 			mdcopyfrom_vlist((bus_dma_segment_t *)bp->bio_data,
860 			    bp->bio_ma_offset, p, bp->bio_length);
861 		} else {
862 			bcopy(bp->bio_data, p, bp->bio_length);
863 		}
864 		break;
865 	}
866 	bp->bio_resid = 0;
867 	return (0);
868 }
869 
870 static int
871 mdstart_vnode(struct md_s *sc, struct bio *bp)
872 {
873 	int error;
874 	struct uio auio;
875 	struct iovec aiov;
876 	struct iovec *piov;
877 	struct mount *mp;
878 	struct vnode *vp;
879 	struct buf *pb;
880 	bus_dma_segment_t *vlist;
881 	struct thread *td;
882 	off_t iolen, iostart, len, zerosize;
883 	int ma_offs, npages;
884 
885 	switch (bp->bio_cmd) {
886 	case BIO_READ:
887 		auio.uio_rw = UIO_READ;
888 		break;
889 	case BIO_WRITE:
890 	case BIO_DELETE:
891 		auio.uio_rw = UIO_WRITE;
892 		break;
893 	case BIO_FLUSH:
894 		break;
895 	default:
896 		return (EOPNOTSUPP);
897 	}
898 
899 	td = curthread;
900 	vp = sc->vnode;
901 	pb = NULL;
902 	piov = NULL;
903 	ma_offs = bp->bio_ma_offset;
904 	len = bp->bio_length;
905 
906 	/*
907 	 * VNODE I/O
908 	 *
909 	 * If an error occurs, we set BIO_ERROR but we do not set
910 	 * B_INVAL because (for a write anyway), the buffer is
911 	 * still valid.
912 	 */
913 
914 	if (bp->bio_cmd == BIO_FLUSH) {
915 		(void) vn_start_write(vp, &mp, V_WAIT);
916 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
917 		error = VOP_FSYNC(vp, MNT_WAIT, td);
918 		VOP_UNLOCK(vp);
919 		vn_finished_write(mp);
920 		return (error);
921 	}
922 
923 	auio.uio_offset = (vm_ooffset_t)bp->bio_offset;
924 	auio.uio_resid = bp->bio_length;
925 	auio.uio_segflg = UIO_SYSSPACE;
926 	auio.uio_td = td;
927 
928 	if (bp->bio_cmd == BIO_DELETE) {
929 		/*
930 		 * Emulate BIO_DELETE by writing zeros.
931 		 */
932 		zerosize = ZERO_REGION_SIZE -
933 		    (ZERO_REGION_SIZE % sc->sectorsize);
934 		auio.uio_iovcnt = howmany(bp->bio_length, zerosize);
935 		piov = malloc(sizeof(*piov) * auio.uio_iovcnt, M_MD, M_WAITOK);
936 		auio.uio_iov = piov;
937 		while (len > 0) {
938 			piov->iov_base = __DECONST(void *, zero_region);
939 			piov->iov_len = len;
940 			if (len > zerosize)
941 				piov->iov_len = zerosize;
942 			len -= piov->iov_len;
943 			piov++;
944 		}
945 		piov = auio.uio_iov;
946 	} else if ((bp->bio_flags & BIO_VLIST) != 0) {
947 		piov = malloc(sizeof(*piov) * bp->bio_ma_n, M_MD, M_WAITOK);
948 		auio.uio_iov = piov;
949 		vlist = (bus_dma_segment_t *)bp->bio_data;
950 		while (len > 0) {
951 			piov->iov_base = (void *)(uintptr_t)(vlist->ds_addr +
952 			    ma_offs);
953 			piov->iov_len = vlist->ds_len - ma_offs;
954 			if (piov->iov_len > len)
955 				piov->iov_len = len;
956 			len -= piov->iov_len;
957 			ma_offs = 0;
958 			vlist++;
959 			piov++;
960 		}
961 		auio.uio_iovcnt = piov - auio.uio_iov;
962 		piov = auio.uio_iov;
963 	} else if ((bp->bio_flags & BIO_UNMAPPED) != 0) {
964 		pb = uma_zalloc(md_pbuf_zone, M_WAITOK);
965 		bp->bio_resid = len;
966 unmapped_step:
967 		npages = atop(min(MAXPHYS, round_page(len + (ma_offs &
968 		    PAGE_MASK))));
969 		iolen = min(ptoa(npages) - (ma_offs & PAGE_MASK), len);
970 		KASSERT(iolen > 0, ("zero iolen"));
971 		pmap_qenter((vm_offset_t)pb->b_data,
972 		    &bp->bio_ma[atop(ma_offs)], npages);
973 		aiov.iov_base = (void *)((vm_offset_t)pb->b_data +
974 		    (ma_offs & PAGE_MASK));
975 		aiov.iov_len = iolen;
976 		auio.uio_iov = &aiov;
977 		auio.uio_iovcnt = 1;
978 		auio.uio_resid = iolen;
979 	} else {
980 		aiov.iov_base = bp->bio_data;
981 		aiov.iov_len = bp->bio_length;
982 		auio.uio_iov = &aiov;
983 		auio.uio_iovcnt = 1;
984 	}
985 	iostart = auio.uio_offset;
986 	if (auio.uio_rw == UIO_READ) {
987 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
988 		error = VOP_READ(vp, &auio, 0, sc->cred);
989 		VOP_UNLOCK(vp);
990 	} else {
991 		(void) vn_start_write(vp, &mp, V_WAIT);
992 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
993 		error = VOP_WRITE(vp, &auio, sc->flags & MD_ASYNC ? 0 : IO_SYNC,
994 		    sc->cred);
995 		VOP_UNLOCK(vp);
996 		vn_finished_write(mp);
997 		if (error == 0)
998 			sc->flags &= ~MD_VERIFY;
999 	}
1000 
1001 	/* When MD_CACHE is set, try to avoid double-caching the data. */
1002 	if (error == 0 && (sc->flags & MD_CACHE) == 0)
1003 		VOP_ADVISE(vp, iostart, auio.uio_offset - 1,
1004 		    POSIX_FADV_DONTNEED);
1005 
1006 	if (pb != NULL) {
1007 		pmap_qremove((vm_offset_t)pb->b_data, npages);
1008 		if (error == 0) {
1009 			len -= iolen;
1010 			bp->bio_resid -= iolen;
1011 			ma_offs += iolen;
1012 			if (len > 0)
1013 				goto unmapped_step;
1014 		}
1015 		uma_zfree(md_pbuf_zone, pb);
1016 	}
1017 
1018 	free(piov, M_MD);
1019 	if (pb == NULL)
1020 		bp->bio_resid = auio.uio_resid;
1021 	return (error);
1022 }
1023 
1024 static int
1025 mdstart_swap(struct md_s *sc, struct bio *bp)
1026 {
1027 	vm_page_t m;
1028 	u_char *p;
1029 	vm_pindex_t i, lastp;
1030 	bus_dma_segment_t *vlist;
1031 	int rv, ma_offs, offs, len, lastend;
1032 
1033 	switch (bp->bio_cmd) {
1034 	case BIO_READ:
1035 	case BIO_WRITE:
1036 	case BIO_DELETE:
1037 		break;
1038 	default:
1039 		return (EOPNOTSUPP);
1040 	}
1041 
1042 	p = bp->bio_data;
1043 	ma_offs = (bp->bio_flags & (BIO_UNMAPPED|BIO_VLIST)) != 0 ?
1044 	    bp->bio_ma_offset : 0;
1045 	vlist = (bp->bio_flags & BIO_VLIST) != 0 ?
1046 	    (bus_dma_segment_t *)bp->bio_data : NULL;
1047 
1048 	/*
1049 	 * offs is the offset at which to start operating on the
1050 	 * next (ie, first) page.  lastp is the last page on
1051 	 * which we're going to operate.  lastend is the ending
1052 	 * position within that last page (ie, PAGE_SIZE if
1053 	 * we're operating on complete aligned pages).
1054 	 */
1055 	offs = bp->bio_offset % PAGE_SIZE;
1056 	lastp = (bp->bio_offset + bp->bio_length - 1) / PAGE_SIZE;
1057 	lastend = (bp->bio_offset + bp->bio_length - 1) % PAGE_SIZE + 1;
1058 
1059 	rv = VM_PAGER_OK;
1060 	vm_object_pip_add(sc->object, 1);
1061 	for (i = bp->bio_offset / PAGE_SIZE; i <= lastp; i++) {
1062 		len = ((i == lastp) ? lastend : PAGE_SIZE) - offs;
1063 		m = vm_page_grab_unlocked(sc->object, i, VM_ALLOC_SYSTEM);
1064 		if (bp->bio_cmd == BIO_READ) {
1065 			if (vm_page_all_valid(m))
1066 				rv = VM_PAGER_OK;
1067 			else
1068 				rv = vm_pager_get_pages(sc->object, &m, 1,
1069 				    NULL, NULL);
1070 			if (rv == VM_PAGER_ERROR) {
1071 				VM_OBJECT_WLOCK(sc->object);
1072 				vm_page_free(m);
1073 				VM_OBJECT_WUNLOCK(sc->object);
1074 				break;
1075 			} else if (rv == VM_PAGER_FAIL) {
1076 				/*
1077 				 * Pager does not have the page.  Zero
1078 				 * the allocated page, and mark it as
1079 				 * valid. Do not set dirty, the page
1080 				 * can be recreated if thrown out.
1081 				 */
1082 				pmap_zero_page(m);
1083 				vm_page_valid(m);
1084 			}
1085 			if ((bp->bio_flags & BIO_UNMAPPED) != 0) {
1086 				pmap_copy_pages(&m, offs, bp->bio_ma,
1087 				    ma_offs, len);
1088 			} else if ((bp->bio_flags & BIO_VLIST) != 0) {
1089 				physcopyout_vlist(VM_PAGE_TO_PHYS(m) + offs,
1090 				    vlist, ma_offs, len);
1091 				cpu_flush_dcache(p, len);
1092 			} else {
1093 				physcopyout(VM_PAGE_TO_PHYS(m) + offs, p, len);
1094 				cpu_flush_dcache(p, len);
1095 			}
1096 		} else if (bp->bio_cmd == BIO_WRITE) {
1097 			if (len == PAGE_SIZE || vm_page_all_valid(m))
1098 				rv = VM_PAGER_OK;
1099 			else
1100 				rv = vm_pager_get_pages(sc->object, &m, 1,
1101 				    NULL, NULL);
1102 			if (rv == VM_PAGER_ERROR) {
1103 				VM_OBJECT_WLOCK(sc->object);
1104 				vm_page_free(m);
1105 				VM_OBJECT_WUNLOCK(sc->object);
1106 				break;
1107 			} else if (rv == VM_PAGER_FAIL)
1108 				pmap_zero_page(m);
1109 
1110 			if ((bp->bio_flags & BIO_UNMAPPED) != 0) {
1111 				pmap_copy_pages(bp->bio_ma, ma_offs, &m,
1112 				    offs, len);
1113 			} else if ((bp->bio_flags & BIO_VLIST) != 0) {
1114 				physcopyin_vlist(vlist, ma_offs,
1115 				    VM_PAGE_TO_PHYS(m) + offs, len);
1116 			} else {
1117 				physcopyin(p, VM_PAGE_TO_PHYS(m) + offs, len);
1118 			}
1119 
1120 			vm_page_valid(m);
1121 			vm_page_set_dirty(m);
1122 		} else if (bp->bio_cmd == BIO_DELETE) {
1123 			if (len == PAGE_SIZE || vm_page_all_valid(m))
1124 				rv = VM_PAGER_OK;
1125 			else
1126 				rv = vm_pager_get_pages(sc->object, &m, 1,
1127 				    NULL, NULL);
1128 			VM_OBJECT_WLOCK(sc->object);
1129 			if (rv == VM_PAGER_ERROR) {
1130 				vm_page_free(m);
1131 				VM_OBJECT_WUNLOCK(sc->object);
1132 				break;
1133 			} else if (rv == VM_PAGER_FAIL) {
1134 				vm_page_free(m);
1135 				m = NULL;
1136 			} else {
1137 				/* Page is valid. */
1138 				if (len != PAGE_SIZE) {
1139 					pmap_zero_page_area(m, offs, len);
1140 					vm_page_set_dirty(m);
1141 				} else {
1142 					vm_pager_page_unswapped(m);
1143 					vm_page_free(m);
1144 					m = NULL;
1145 				}
1146 			}
1147 			VM_OBJECT_WUNLOCK(sc->object);
1148 		}
1149 		if (m != NULL) {
1150 			vm_page_xunbusy(m);
1151 
1152 			/*
1153 			 * The page may be deactivated prior to setting
1154 			 * PGA_REFERENCED, but in this case it will be
1155 			 * reactivated by the page daemon.
1156 			 */
1157 			if (vm_page_active(m))
1158 				vm_page_reference(m);
1159 			else
1160 				vm_page_activate(m);
1161 		}
1162 
1163 		/* Actions on further pages start at offset 0 */
1164 		p += PAGE_SIZE - offs;
1165 		offs = 0;
1166 		ma_offs += len;
1167 	}
1168 	vm_object_pip_wakeup(sc->object);
1169 	return (rv != VM_PAGER_ERROR ? 0 : ENOSPC);
1170 }
1171 
1172 static int
1173 mdstart_null(struct md_s *sc, struct bio *bp)
1174 {
1175 
1176 	switch (bp->bio_cmd) {
1177 	case BIO_READ:
1178 		bzero(bp->bio_data, bp->bio_length);
1179 		cpu_flush_dcache(bp->bio_data, bp->bio_length);
1180 		break;
1181 	case BIO_WRITE:
1182 		break;
1183 	}
1184 	bp->bio_resid = 0;
1185 	return (0);
1186 }
1187 
1188 static void
1189 md_kthread(void *arg)
1190 {
1191 	struct md_s *sc;
1192 	struct bio *bp;
1193 	int error;
1194 
1195 	sc = arg;
1196 	thread_lock(curthread);
1197 	sched_prio(curthread, PRIBIO);
1198 	thread_unlock(curthread);
1199 	if (sc->type == MD_VNODE)
1200 		curthread->td_pflags |= TDP_NORUNNINGBUF;
1201 
1202 	for (;;) {
1203 		mtx_lock(&sc->queue_mtx);
1204 		if (sc->flags & MD_SHUTDOWN) {
1205 			sc->flags |= MD_EXITING;
1206 			mtx_unlock(&sc->queue_mtx);
1207 			kproc_exit(0);
1208 		}
1209 		bp = bioq_takefirst(&sc->bio_queue);
1210 		if (!bp) {
1211 			msleep(sc, &sc->queue_mtx, PRIBIO | PDROP, "mdwait", 0);
1212 			continue;
1213 		}
1214 		mtx_unlock(&sc->queue_mtx);
1215 		if (bp->bio_cmd == BIO_GETATTR) {
1216 			int isv = ((sc->flags & MD_VERIFY) != 0);
1217 
1218 			if ((sc->fwsectors && sc->fwheads &&
1219 			    (g_handleattr_int(bp, "GEOM::fwsectors",
1220 			    sc->fwsectors) ||
1221 			    g_handleattr_int(bp, "GEOM::fwheads",
1222 			    sc->fwheads))) ||
1223 			    g_handleattr_int(bp, "GEOM::candelete", 1))
1224 				error = -1;
1225 			else if (sc->ident[0] != '\0' &&
1226 			    g_handleattr_str(bp, "GEOM::ident", sc->ident))
1227 				error = -1;
1228 			else if (g_handleattr_int(bp, "MNT::verified", isv))
1229 				error = -1;
1230 			else
1231 				error = EOPNOTSUPP;
1232 		} else {
1233 			error = sc->start(sc, bp);
1234 		}
1235 
1236 		if (bp->bio_cmd == BIO_READ || bp->bio_cmd == BIO_WRITE) {
1237 			/*
1238 			 * Devstat uses (bio_bcount, bio_resid) for
1239 			 * determining the length of the completed part of
1240 			 * the i/o.  g_io_deliver() will translate from
1241 			 * bio_completed to that, but it also destroys the
1242 			 * bio so we must do our own translation.
1243 			 */
1244 			bp->bio_bcount = bp->bio_length;
1245 			bp->bio_resid = (error == -1 ? bp->bio_bcount : 0);
1246 			devstat_end_transaction_bio(sc->devstat, bp);
1247 		}
1248 		if (error != -1) {
1249 			bp->bio_completed = bp->bio_length;
1250 			g_io_deliver(bp, error);
1251 		}
1252 	}
1253 }
1254 
1255 static struct md_s *
1256 mdfind(int unit)
1257 {
1258 	struct md_s *sc;
1259 
1260 	LIST_FOREACH(sc, &md_softc_list, list) {
1261 		if (sc->unit == unit)
1262 			break;
1263 	}
1264 	return (sc);
1265 }
1266 
1267 static struct md_s *
1268 mdnew(int unit, int *errp, enum md_types type)
1269 {
1270 	struct md_s *sc;
1271 	int error;
1272 
1273 	*errp = 0;
1274 	if (unit == -1)
1275 		unit = alloc_unr(md_uh);
1276 	else
1277 		unit = alloc_unr_specific(md_uh, unit);
1278 
1279 	if (unit == -1) {
1280 		*errp = EBUSY;
1281 		return (NULL);
1282 	}
1283 
1284 	sc = (struct md_s *)malloc(sizeof *sc, M_MD, M_WAITOK | M_ZERO);
1285 	sc->type = type;
1286 	bioq_init(&sc->bio_queue);
1287 	mtx_init(&sc->queue_mtx, "md bio queue", NULL, MTX_DEF);
1288 	sc->unit = unit;
1289 	sprintf(sc->name, "md%d", unit);
1290 	LIST_INSERT_HEAD(&md_softc_list, sc, list);
1291 	error = kproc_create(md_kthread, sc, &sc->procp, 0, 0,"%s", sc->name);
1292 	if (error == 0)
1293 		return (sc);
1294 	LIST_REMOVE(sc, list);
1295 	mtx_destroy(&sc->queue_mtx);
1296 	free_unr(md_uh, sc->unit);
1297 	free(sc, M_MD);
1298 	*errp = error;
1299 	return (NULL);
1300 }
1301 
1302 static void
1303 mdinit(struct md_s *sc)
1304 {
1305 	struct g_geom *gp;
1306 	struct g_provider *pp;
1307 
1308 	g_topology_lock();
1309 	gp = g_new_geomf(&g_md_class, "md%d", sc->unit);
1310 	gp->softc = sc;
1311 	pp = g_new_providerf(gp, "md%d", sc->unit);
1312 	devstat_remove_entry(pp->stat);
1313 	pp->stat = NULL;
1314 	pp->flags |= G_PF_DIRECT_SEND | G_PF_DIRECT_RECEIVE;
1315 	pp->mediasize = sc->mediasize;
1316 	pp->sectorsize = sc->sectorsize;
1317 	switch (sc->type) {
1318 	case MD_MALLOC:
1319 	case MD_VNODE:
1320 	case MD_SWAP:
1321 		pp->flags |= G_PF_ACCEPT_UNMAPPED;
1322 		break;
1323 	case MD_PRELOAD:
1324 	case MD_NULL:
1325 		break;
1326 	}
1327 	sc->gp = gp;
1328 	sc->pp = pp;
1329 	sc->devstat = devstat_new_entry("md", sc->unit, sc->sectorsize,
1330 	    DEVSTAT_ALL_SUPPORTED, DEVSTAT_TYPE_DIRECT, DEVSTAT_PRIORITY_MAX);
1331 	sc->devstat->id = pp;
1332 	g_error_provider(pp, 0);
1333 	g_topology_unlock();
1334 }
1335 
1336 static int
1337 mdcreate_malloc(struct md_s *sc, struct md_req *mdr)
1338 {
1339 	uintptr_t sp;
1340 	int error;
1341 	off_t u;
1342 
1343 	error = 0;
1344 	if (mdr->md_options & ~(MD_AUTOUNIT | MD_COMPRESS | MD_RESERVE))
1345 		return (EINVAL);
1346 	if (mdr->md_sectorsize != 0 && !powerof2(mdr->md_sectorsize))
1347 		return (EINVAL);
1348 	/* Compression doesn't make sense if we have reserved space */
1349 	if (mdr->md_options & MD_RESERVE)
1350 		mdr->md_options &= ~MD_COMPRESS;
1351 	if (mdr->md_fwsectors != 0)
1352 		sc->fwsectors = mdr->md_fwsectors;
1353 	if (mdr->md_fwheads != 0)
1354 		sc->fwheads = mdr->md_fwheads;
1355 	sc->flags = mdr->md_options & (MD_COMPRESS | MD_FORCE);
1356 	sc->indir = dimension(sc->mediasize / sc->sectorsize);
1357 	sc->uma = uma_zcreate(sc->name, sc->sectorsize, NULL, NULL, NULL, NULL,
1358 	    0x1ff, 0);
1359 	if (mdr->md_options & MD_RESERVE) {
1360 		off_t nsectors;
1361 
1362 		nsectors = sc->mediasize / sc->sectorsize;
1363 		for (u = 0; u < nsectors; u++) {
1364 			sp = (uintptr_t)uma_zalloc(sc->uma, (md_malloc_wait ?
1365 			    M_WAITOK : M_NOWAIT) | M_ZERO);
1366 			if (sp != 0)
1367 				error = s_write(sc->indir, u, sp);
1368 			else
1369 				error = ENOMEM;
1370 			if (error != 0)
1371 				break;
1372 		}
1373 	}
1374 	return (error);
1375 }
1376 
1377 
1378 static int
1379 mdsetcred(struct md_s *sc, struct ucred *cred)
1380 {
1381 	char *tmpbuf;
1382 	int error = 0;
1383 
1384 	/*
1385 	 * Set credits in our softc
1386 	 */
1387 
1388 	if (sc->cred)
1389 		crfree(sc->cred);
1390 	sc->cred = crhold(cred);
1391 
1392 	/*
1393 	 * Horrible kludge to establish credentials for NFS  XXX.
1394 	 */
1395 
1396 	if (sc->vnode) {
1397 		struct uio auio;
1398 		struct iovec aiov;
1399 
1400 		tmpbuf = malloc(sc->sectorsize, M_TEMP, M_WAITOK);
1401 		bzero(&auio, sizeof(auio));
1402 
1403 		aiov.iov_base = tmpbuf;
1404 		aiov.iov_len = sc->sectorsize;
1405 		auio.uio_iov = &aiov;
1406 		auio.uio_iovcnt = 1;
1407 		auio.uio_offset = 0;
1408 		auio.uio_rw = UIO_READ;
1409 		auio.uio_segflg = UIO_SYSSPACE;
1410 		auio.uio_resid = aiov.iov_len;
1411 		vn_lock(sc->vnode, LK_EXCLUSIVE | LK_RETRY);
1412 		error = VOP_READ(sc->vnode, &auio, 0, sc->cred);
1413 		VOP_UNLOCK(sc->vnode);
1414 		free(tmpbuf, M_TEMP);
1415 	}
1416 	return (error);
1417 }
1418 
1419 static int
1420 mdcreate_vnode(struct md_s *sc, struct md_req *mdr, struct thread *td)
1421 {
1422 	struct vattr vattr;
1423 	struct nameidata nd;
1424 	char *fname;
1425 	int error, flags;
1426 
1427 	fname = mdr->md_file;
1428 	if (mdr->md_file_seg == UIO_USERSPACE) {
1429 		error = copyinstr(fname, sc->file, sizeof(sc->file), NULL);
1430 		if (error != 0)
1431 			return (error);
1432 	} else if (mdr->md_file_seg == UIO_SYSSPACE)
1433 		strlcpy(sc->file, fname, sizeof(sc->file));
1434 	else
1435 		return (EDOOFUS);
1436 
1437 	/*
1438 	 * If the user specified that this is a read only device, don't
1439 	 * set the FWRITE mask before trying to open the backing store.
1440 	 */
1441 	flags = FREAD | ((mdr->md_options & MD_READONLY) ? 0 : FWRITE) \
1442 	    | ((mdr->md_options & MD_VERIFY) ? O_VERIFY : 0);
1443 	NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, sc->file, td);
1444 	error = vn_open(&nd, &flags, 0, NULL);
1445 	if (error != 0)
1446 		return (error);
1447 	NDFREE(&nd, NDF_ONLY_PNBUF);
1448 	if (nd.ni_vp->v_type != VREG) {
1449 		error = EINVAL;
1450 		goto bad;
1451 	}
1452 	error = VOP_GETATTR(nd.ni_vp, &vattr, td->td_ucred);
1453 	if (error != 0)
1454 		goto bad;
1455 	if (VOP_ISLOCKED(nd.ni_vp) != LK_EXCLUSIVE) {
1456 		vn_lock(nd.ni_vp, LK_UPGRADE | LK_RETRY);
1457 		if (VN_IS_DOOMED(nd.ni_vp)) {
1458 			/* Forced unmount. */
1459 			error = EBADF;
1460 			goto bad;
1461 		}
1462 	}
1463 	nd.ni_vp->v_vflag |= VV_MD;
1464 	VOP_UNLOCK(nd.ni_vp);
1465 
1466 	if (mdr->md_fwsectors != 0)
1467 		sc->fwsectors = mdr->md_fwsectors;
1468 	if (mdr->md_fwheads != 0)
1469 		sc->fwheads = mdr->md_fwheads;
1470 	snprintf(sc->ident, sizeof(sc->ident), "MD-DEV%ju-INO%ju",
1471 	    (uintmax_t)vattr.va_fsid, (uintmax_t)vattr.va_fileid);
1472 	sc->flags = mdr->md_options & (MD_ASYNC | MD_CACHE | MD_FORCE |
1473 	    MD_VERIFY);
1474 	if (!(flags & FWRITE))
1475 		sc->flags |= MD_READONLY;
1476 	sc->vnode = nd.ni_vp;
1477 
1478 	error = mdsetcred(sc, td->td_ucred);
1479 	if (error != 0) {
1480 		sc->vnode = NULL;
1481 		vn_lock(nd.ni_vp, LK_EXCLUSIVE | LK_RETRY);
1482 		nd.ni_vp->v_vflag &= ~VV_MD;
1483 		goto bad;
1484 	}
1485 	return (0);
1486 bad:
1487 	VOP_UNLOCK(nd.ni_vp);
1488 	(void)vn_close(nd.ni_vp, flags, td->td_ucred, td);
1489 	return (error);
1490 }
1491 
1492 static void
1493 g_md_providergone(struct g_provider *pp)
1494 {
1495 	struct md_s *sc = pp->geom->softc;
1496 
1497 	mtx_lock(&sc->queue_mtx);
1498 	sc->flags |= MD_PROVIDERGONE;
1499 	wakeup(&sc->flags);
1500 	mtx_unlock(&sc->queue_mtx);
1501 }
1502 
1503 static int
1504 mddestroy(struct md_s *sc, struct thread *td)
1505 {
1506 
1507 	if (sc->gp) {
1508 		g_topology_lock();
1509 		g_wither_geom(sc->gp, ENXIO);
1510 		g_topology_unlock();
1511 
1512 		mtx_lock(&sc->queue_mtx);
1513 		while (!(sc->flags & MD_PROVIDERGONE))
1514 			msleep(&sc->flags, &sc->queue_mtx, PRIBIO, "mddestroy", 0);
1515 		mtx_unlock(&sc->queue_mtx);
1516 	}
1517 	if (sc->devstat) {
1518 		devstat_remove_entry(sc->devstat);
1519 		sc->devstat = NULL;
1520 	}
1521 	mtx_lock(&sc->queue_mtx);
1522 	sc->flags |= MD_SHUTDOWN;
1523 	wakeup(sc);
1524 	while (!(sc->flags & MD_EXITING))
1525 		msleep(sc->procp, &sc->queue_mtx, PRIBIO, "mddestroy", hz / 10);
1526 	mtx_unlock(&sc->queue_mtx);
1527 	mtx_destroy(&sc->queue_mtx);
1528 	if (sc->vnode != NULL) {
1529 		vn_lock(sc->vnode, LK_EXCLUSIVE | LK_RETRY);
1530 		sc->vnode->v_vflag &= ~VV_MD;
1531 		VOP_UNLOCK(sc->vnode);
1532 		(void)vn_close(sc->vnode, sc->flags & MD_READONLY ?
1533 		    FREAD : (FREAD|FWRITE), sc->cred, td);
1534 	}
1535 	if (sc->cred != NULL)
1536 		crfree(sc->cred);
1537 	if (sc->object != NULL)
1538 		vm_object_deallocate(sc->object);
1539 	if (sc->indir)
1540 		destroy_indir(sc, sc->indir);
1541 	if (sc->uma)
1542 		uma_zdestroy(sc->uma);
1543 
1544 	LIST_REMOVE(sc, list);
1545 	free_unr(md_uh, sc->unit);
1546 	free(sc, M_MD);
1547 	return (0);
1548 }
1549 
1550 static int
1551 mdresize(struct md_s *sc, struct md_req *mdr)
1552 {
1553 	int error, res;
1554 	vm_pindex_t oldpages, newpages;
1555 
1556 	switch (sc->type) {
1557 	case MD_VNODE:
1558 	case MD_NULL:
1559 		break;
1560 	case MD_SWAP:
1561 		if (mdr->md_mediasize <= 0 ||
1562 		    (mdr->md_mediasize % PAGE_SIZE) != 0)
1563 			return (EDOM);
1564 		oldpages = OFF_TO_IDX(sc->mediasize);
1565 		newpages = OFF_TO_IDX(mdr->md_mediasize);
1566 		if (newpages < oldpages) {
1567 			VM_OBJECT_WLOCK(sc->object);
1568 			vm_object_page_remove(sc->object, newpages, 0, 0);
1569 			swap_release_by_cred(IDX_TO_OFF(oldpages -
1570 			    newpages), sc->cred);
1571 			sc->object->charge = IDX_TO_OFF(newpages);
1572 			sc->object->size = newpages;
1573 			VM_OBJECT_WUNLOCK(sc->object);
1574 		} else if (newpages > oldpages) {
1575 			res = swap_reserve_by_cred(IDX_TO_OFF(newpages -
1576 			    oldpages), sc->cred);
1577 			if (!res)
1578 				return (ENOMEM);
1579 			if ((mdr->md_options & MD_RESERVE) ||
1580 			    (sc->flags & MD_RESERVE)) {
1581 				error = swap_pager_reserve(sc->object,
1582 				    oldpages, newpages - oldpages);
1583 				if (error < 0) {
1584 					swap_release_by_cred(
1585 					    IDX_TO_OFF(newpages - oldpages),
1586 					    sc->cred);
1587 					return (EDOM);
1588 				}
1589 			}
1590 			VM_OBJECT_WLOCK(sc->object);
1591 			sc->object->charge = IDX_TO_OFF(newpages);
1592 			sc->object->size = newpages;
1593 			VM_OBJECT_WUNLOCK(sc->object);
1594 		}
1595 		break;
1596 	default:
1597 		return (EOPNOTSUPP);
1598 	}
1599 
1600 	sc->mediasize = mdr->md_mediasize;
1601 	g_topology_lock();
1602 	g_resize_provider(sc->pp, sc->mediasize);
1603 	g_topology_unlock();
1604 	return (0);
1605 }
1606 
1607 static int
1608 mdcreate_swap(struct md_s *sc, struct md_req *mdr, struct thread *td)
1609 {
1610 	vm_ooffset_t npage;
1611 	int error;
1612 
1613 	/*
1614 	 * Range check.  Disallow negative sizes and sizes not being
1615 	 * multiple of page size.
1616 	 */
1617 	if (sc->mediasize <= 0 || (sc->mediasize % PAGE_SIZE) != 0)
1618 		return (EDOM);
1619 
1620 	/*
1621 	 * Allocate an OBJT_SWAP object.
1622 	 *
1623 	 * Note the truncation.
1624 	 */
1625 
1626 	if ((mdr->md_options & MD_VERIFY) != 0)
1627 		return (EINVAL);
1628 	npage = mdr->md_mediasize / PAGE_SIZE;
1629 	if (mdr->md_fwsectors != 0)
1630 		sc->fwsectors = mdr->md_fwsectors;
1631 	if (mdr->md_fwheads != 0)
1632 		sc->fwheads = mdr->md_fwheads;
1633 	sc->object = vm_pager_allocate(OBJT_SWAP, NULL, PAGE_SIZE * npage,
1634 	    VM_PROT_DEFAULT, 0, td->td_ucred);
1635 	if (sc->object == NULL)
1636 		return (ENOMEM);
1637 	sc->flags = mdr->md_options & (MD_FORCE | MD_RESERVE);
1638 	if (mdr->md_options & MD_RESERVE) {
1639 		if (swap_pager_reserve(sc->object, 0, npage) < 0) {
1640 			error = EDOM;
1641 			goto finish;
1642 		}
1643 	}
1644 	error = mdsetcred(sc, td->td_ucred);
1645  finish:
1646 	if (error != 0) {
1647 		vm_object_deallocate(sc->object);
1648 		sc->object = NULL;
1649 	}
1650 	return (error);
1651 }
1652 
1653 static int
1654 mdcreate_null(struct md_s *sc, struct md_req *mdr, struct thread *td)
1655 {
1656 
1657 	/*
1658 	 * Range check.  Disallow negative sizes and sizes not being
1659 	 * multiple of page size.
1660 	 */
1661 	if (sc->mediasize <= 0 || (sc->mediasize % PAGE_SIZE) != 0)
1662 		return (EDOM);
1663 
1664 	return (0);
1665 }
1666 
1667 static int
1668 kern_mdattach_locked(struct thread *td, struct md_req *mdr)
1669 {
1670 	struct md_s *sc;
1671 	unsigned sectsize;
1672 	int error, i;
1673 
1674 	sx_assert(&md_sx, SA_XLOCKED);
1675 
1676 	switch (mdr->md_type) {
1677 	case MD_MALLOC:
1678 	case MD_PRELOAD:
1679 	case MD_VNODE:
1680 	case MD_SWAP:
1681 	case MD_NULL:
1682 		break;
1683 	default:
1684 		return (EINVAL);
1685 	}
1686 	if (mdr->md_sectorsize == 0)
1687 		sectsize = DEV_BSIZE;
1688 	else
1689 		sectsize = mdr->md_sectorsize;
1690 	if (sectsize > MAXPHYS || mdr->md_mediasize < sectsize)
1691 		return (EINVAL);
1692 	if (mdr->md_options & MD_AUTOUNIT)
1693 		sc = mdnew(-1, &error, mdr->md_type);
1694 	else {
1695 		if (mdr->md_unit > INT_MAX)
1696 			return (EINVAL);
1697 		sc = mdnew(mdr->md_unit, &error, mdr->md_type);
1698 	}
1699 	if (sc == NULL)
1700 		return (error);
1701 	if (mdr->md_label != NULL)
1702 		error = copyinstr(mdr->md_label, sc->label,
1703 		    sizeof(sc->label), NULL);
1704 	if (error != 0)
1705 		goto err_after_new;
1706 	if (mdr->md_options & MD_AUTOUNIT)
1707 		mdr->md_unit = sc->unit;
1708 	sc->mediasize = mdr->md_mediasize;
1709 	sc->sectorsize = sectsize;
1710 	error = EDOOFUS;
1711 	switch (sc->type) {
1712 	case MD_MALLOC:
1713 		sc->start = mdstart_malloc;
1714 		error = mdcreate_malloc(sc, mdr);
1715 		break;
1716 	case MD_PRELOAD:
1717 		/*
1718 		 * We disallow attaching preloaded memory disks via
1719 		 * ioctl. Preloaded memory disks are automatically
1720 		 * attached in g_md_init().
1721 		 */
1722 		error = EOPNOTSUPP;
1723 		break;
1724 	case MD_VNODE:
1725 		sc->start = mdstart_vnode;
1726 		error = mdcreate_vnode(sc, mdr, td);
1727 		break;
1728 	case MD_SWAP:
1729 		sc->start = mdstart_swap;
1730 		error = mdcreate_swap(sc, mdr, td);
1731 		break;
1732 	case MD_NULL:
1733 		sc->start = mdstart_null;
1734 		error = mdcreate_null(sc, mdr, td);
1735 		break;
1736 	}
1737 err_after_new:
1738 	if (error != 0) {
1739 		mddestroy(sc, td);
1740 		return (error);
1741 	}
1742 
1743 	/* Prune off any residual fractional sector */
1744 	i = sc->mediasize % sc->sectorsize;
1745 	sc->mediasize -= i;
1746 
1747 	mdinit(sc);
1748 	return (0);
1749 }
1750 
1751 static int
1752 kern_mdattach(struct thread *td, struct md_req *mdr)
1753 {
1754 	int error;
1755 
1756 	sx_xlock(&md_sx);
1757 	error = kern_mdattach_locked(td, mdr);
1758 	sx_xunlock(&md_sx);
1759 	return (error);
1760 }
1761 
1762 static int
1763 kern_mddetach_locked(struct thread *td, struct md_req *mdr)
1764 {
1765 	struct md_s *sc;
1766 
1767 	sx_assert(&md_sx, SA_XLOCKED);
1768 
1769 	if (mdr->md_mediasize != 0 ||
1770 	    (mdr->md_options & ~MD_FORCE) != 0)
1771 		return (EINVAL);
1772 
1773 	sc = mdfind(mdr->md_unit);
1774 	if (sc == NULL)
1775 		return (ENOENT);
1776 	if (sc->opencount != 0 && !(sc->flags & MD_FORCE) &&
1777 	    !(mdr->md_options & MD_FORCE))
1778 		return (EBUSY);
1779 	return (mddestroy(sc, td));
1780 }
1781 
1782 static int
1783 kern_mddetach(struct thread *td, struct md_req *mdr)
1784 {
1785 	int error;
1786 
1787 	sx_xlock(&md_sx);
1788 	error = kern_mddetach_locked(td, mdr);
1789 	sx_xunlock(&md_sx);
1790 	return (error);
1791 }
1792 
1793 static int
1794 kern_mdresize_locked(struct md_req *mdr)
1795 {
1796 	struct md_s *sc;
1797 
1798 	sx_assert(&md_sx, SA_XLOCKED);
1799 
1800 	if ((mdr->md_options & ~(MD_FORCE | MD_RESERVE)) != 0)
1801 		return (EINVAL);
1802 
1803 	sc = mdfind(mdr->md_unit);
1804 	if (sc == NULL)
1805 		return (ENOENT);
1806 	if (mdr->md_mediasize < sc->sectorsize)
1807 		return (EINVAL);
1808 	if (mdr->md_mediasize < sc->mediasize &&
1809 	    !(sc->flags & MD_FORCE) &&
1810 	    !(mdr->md_options & MD_FORCE))
1811 		return (EBUSY);
1812 	return (mdresize(sc, mdr));
1813 }
1814 
1815 static int
1816 kern_mdresize(struct md_req *mdr)
1817 {
1818 	int error;
1819 
1820 	sx_xlock(&md_sx);
1821 	error = kern_mdresize_locked(mdr);
1822 	sx_xunlock(&md_sx);
1823 	return (error);
1824 }
1825 
1826 static int
1827 kern_mdquery_locked(struct md_req *mdr)
1828 {
1829 	struct md_s *sc;
1830 	int error;
1831 
1832 	sx_assert(&md_sx, SA_XLOCKED);
1833 
1834 	sc = mdfind(mdr->md_unit);
1835 	if (sc == NULL)
1836 		return (ENOENT);
1837 	mdr->md_type = sc->type;
1838 	mdr->md_options = sc->flags;
1839 	mdr->md_mediasize = sc->mediasize;
1840 	mdr->md_sectorsize = sc->sectorsize;
1841 	error = 0;
1842 	if (mdr->md_label != NULL) {
1843 		error = copyout(sc->label, mdr->md_label,
1844 		    strlen(sc->label) + 1);
1845 		if (error != 0)
1846 			return (error);
1847 	}
1848 	if (sc->type == MD_VNODE ||
1849 	    (sc->type == MD_PRELOAD && mdr->md_file != NULL))
1850 		error = copyout(sc->file, mdr->md_file,
1851 		    strlen(sc->file) + 1);
1852 	return (error);
1853 }
1854 
1855 static int
1856 kern_mdquery(struct md_req *mdr)
1857 {
1858 	int error;
1859 
1860 	sx_xlock(&md_sx);
1861 	error = kern_mdquery_locked(mdr);
1862 	sx_xunlock(&md_sx);
1863 	return (error);
1864 }
1865 
1866 /* Copy members that are not userspace pointers. */
1867 #define	MD_IOCTL2REQ(mdio, mdr) do {					\
1868 	(mdr)->md_unit = (mdio)->md_unit;				\
1869 	(mdr)->md_type = (mdio)->md_type;				\
1870 	(mdr)->md_mediasize = (mdio)->md_mediasize;			\
1871 	(mdr)->md_sectorsize = (mdio)->md_sectorsize;			\
1872 	(mdr)->md_options = (mdio)->md_options;				\
1873 	(mdr)->md_fwheads = (mdio)->md_fwheads;				\
1874 	(mdr)->md_fwsectors = (mdio)->md_fwsectors;			\
1875 	(mdr)->md_units = &(mdio)->md_pad[0];				\
1876 	(mdr)->md_units_nitems = nitems((mdio)->md_pad);		\
1877 } while(0)
1878 
1879 /* Copy members that might have been updated */
1880 #define MD_REQ2IOCTL(mdr, mdio) do {					\
1881 	(mdio)->md_unit = (mdr)->md_unit;				\
1882 	(mdio)->md_type = (mdr)->md_type;				\
1883 	(mdio)->md_mediasize = (mdr)->md_mediasize;			\
1884 	(mdio)->md_sectorsize = (mdr)->md_sectorsize;			\
1885 	(mdio)->md_options = (mdr)->md_options;				\
1886 	(mdio)->md_fwheads = (mdr)->md_fwheads;				\
1887 	(mdio)->md_fwsectors = (mdr)->md_fwsectors;			\
1888 } while(0)
1889 
1890 static int
1891 mdctlioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flags,
1892     struct thread *td)
1893 {
1894 	struct md_req mdr;
1895 	int error;
1896 
1897 	if (md_debug)
1898 		printf("mdctlioctl(%s %lx %p %x %p)\n",
1899 			devtoname(dev), cmd, addr, flags, td);
1900 
1901 	bzero(&mdr, sizeof(mdr));
1902 	switch (cmd) {
1903 	case MDIOCATTACH:
1904 	case MDIOCDETACH:
1905 	case MDIOCRESIZE:
1906 	case MDIOCQUERY: {
1907 		struct md_ioctl *mdio = (struct md_ioctl *)addr;
1908 		if (mdio->md_version != MDIOVERSION)
1909 			return (EINVAL);
1910 		MD_IOCTL2REQ(mdio, &mdr);
1911 		mdr.md_file = mdio->md_file;
1912 		mdr.md_file_seg = UIO_USERSPACE;
1913 		/* If the file is adjacent to the md_ioctl it's in kernel. */
1914 		if ((void *)mdio->md_file == (void *)(mdio + 1))
1915 			mdr.md_file_seg = UIO_SYSSPACE;
1916 		mdr.md_label = mdio->md_label;
1917 		break;
1918 	}
1919 #ifdef COMPAT_FREEBSD32
1920 	case MDIOCATTACH_32:
1921 	case MDIOCDETACH_32:
1922 	case MDIOCRESIZE_32:
1923 	case MDIOCQUERY_32: {
1924 		struct md_ioctl32 *mdio = (struct md_ioctl32 *)addr;
1925 		if (mdio->md_version != MDIOVERSION)
1926 			return (EINVAL);
1927 		MD_IOCTL2REQ(mdio, &mdr);
1928 		mdr.md_file = (void *)(uintptr_t)mdio->md_file;
1929 		mdr.md_file_seg = UIO_USERSPACE;
1930 		mdr.md_label = (void *)(uintptr_t)mdio->md_label;
1931 		break;
1932 	}
1933 #endif
1934 	default:
1935 		/* Fall through to handler switch. */
1936 		break;
1937 	}
1938 
1939 	error = 0;
1940 	switch (cmd) {
1941 	case MDIOCATTACH:
1942 #ifdef COMPAT_FREEBSD32
1943 	case MDIOCATTACH_32:
1944 #endif
1945 		error = kern_mdattach(td, &mdr);
1946 		break;
1947 	case MDIOCDETACH:
1948 #ifdef COMPAT_FREEBSD32
1949 	case MDIOCDETACH_32:
1950 #endif
1951 		error = kern_mddetach(td, &mdr);
1952 		break;
1953 	case MDIOCRESIZE:
1954 #ifdef COMPAT_FREEBSD32
1955 	case MDIOCRESIZE_32:
1956 #endif
1957 		error = kern_mdresize(&mdr);
1958 		break;
1959 	case MDIOCQUERY:
1960 #ifdef COMPAT_FREEBSD32
1961 	case MDIOCQUERY_32:
1962 #endif
1963 		error = kern_mdquery(&mdr);
1964 		break;
1965 	default:
1966 		error = ENOIOCTL;
1967 	}
1968 
1969 	switch (cmd) {
1970 	case MDIOCATTACH:
1971 	case MDIOCQUERY: {
1972 		struct md_ioctl *mdio = (struct md_ioctl *)addr;
1973 		MD_REQ2IOCTL(&mdr, mdio);
1974 		break;
1975 	}
1976 #ifdef COMPAT_FREEBSD32
1977 	case MDIOCATTACH_32:
1978 	case MDIOCQUERY_32: {
1979 		struct md_ioctl32 *mdio = (struct md_ioctl32 *)addr;
1980 		MD_REQ2IOCTL(&mdr, mdio);
1981 		break;
1982 	}
1983 #endif
1984 	default:
1985 		/* Other commands to not alter mdr. */
1986 		break;
1987 	}
1988 
1989 	return (error);
1990 }
1991 
1992 static void
1993 md_preloaded(u_char *image, size_t length, const char *name)
1994 {
1995 	struct md_s *sc;
1996 	int error;
1997 
1998 	sc = mdnew(-1, &error, MD_PRELOAD);
1999 	if (sc == NULL)
2000 		return;
2001 	sc->mediasize = length;
2002 	sc->sectorsize = DEV_BSIZE;
2003 	sc->pl_ptr = image;
2004 	sc->pl_len = length;
2005 	sc->start = mdstart_preload;
2006 	if (name != NULL)
2007 		strlcpy(sc->file, name, sizeof(sc->file));
2008 #ifdef MD_ROOT
2009 	if (sc->unit == 0) {
2010 #ifndef ROOTDEVNAME
2011 		rootdevnames[0] = MD_ROOT_FSTYPE ":/dev/md0";
2012 #endif
2013 #ifdef MD_ROOT_READONLY
2014 		sc->flags |= MD_READONLY;
2015 #endif
2016 	}
2017 #endif
2018 	mdinit(sc);
2019 	if (name != NULL) {
2020 		printf("%s%d: Preloaded image <%s> %zd bytes at %p\n",
2021 		    MD_NAME, sc->unit, name, length, image);
2022 	} else {
2023 		printf("%s%d: Embedded image %zd bytes at %p\n",
2024 		    MD_NAME, sc->unit, length, image);
2025 	}
2026 }
2027 
2028 static void
2029 g_md_init(struct g_class *mp __unused)
2030 {
2031 	caddr_t mod;
2032 	u_char *ptr, *name, *type;
2033 	unsigned len;
2034 	int i;
2035 
2036 	/* figure out log2(NINDIR) */
2037 	for (i = NINDIR, nshift = -1; i; nshift++)
2038 		i >>= 1;
2039 
2040 	mod = NULL;
2041 	sx_init(&md_sx, "MD config lock");
2042 	g_topology_unlock();
2043 	md_uh = new_unrhdr(0, INT_MAX, NULL);
2044 #ifdef MD_ROOT
2045 	if (mfs_root_size != 0) {
2046 		sx_xlock(&md_sx);
2047 #ifdef MD_ROOT_MEM
2048 		md_preloaded(mfs_root, mfs_root_size, NULL);
2049 #else
2050 		md_preloaded(__DEVOLATILE(u_char *, &mfs_root), mfs_root_size,
2051 		    NULL);
2052 #endif
2053 		sx_xunlock(&md_sx);
2054 	}
2055 #endif
2056 	/* XXX: are preload_* static or do they need Giant ? */
2057 	while ((mod = preload_search_next_name(mod)) != NULL) {
2058 		name = (char *)preload_search_info(mod, MODINFO_NAME);
2059 		if (name == NULL)
2060 			continue;
2061 		type = (char *)preload_search_info(mod, MODINFO_TYPE);
2062 		if (type == NULL)
2063 			continue;
2064 		if (strcmp(type, "md_image") && strcmp(type, "mfs_root"))
2065 			continue;
2066 		ptr = preload_fetch_addr(mod);
2067 		len = preload_fetch_size(mod);
2068 		if (ptr != NULL && len != 0) {
2069 			sx_xlock(&md_sx);
2070 			md_preloaded(ptr, len, name);
2071 			sx_xunlock(&md_sx);
2072 		}
2073 	}
2074 	md_pbuf_zone = pbuf_zsecond_create("mdpbuf", nswbuf / 10);
2075 	status_dev = make_dev(&mdctl_cdevsw, INT_MAX, UID_ROOT, GID_WHEEL,
2076 	    0600, MDCTL_NAME);
2077 	g_topology_lock();
2078 }
2079 
2080 static void
2081 g_md_dumpconf(struct sbuf *sb, const char *indent, struct g_geom *gp,
2082     struct g_consumer *cp __unused, struct g_provider *pp)
2083 {
2084 	struct md_s *mp;
2085 	char *type;
2086 
2087 	mp = gp->softc;
2088 	if (mp == NULL)
2089 		return;
2090 
2091 	switch (mp->type) {
2092 	case MD_MALLOC:
2093 		type = "malloc";
2094 		break;
2095 	case MD_PRELOAD:
2096 		type = "preload";
2097 		break;
2098 	case MD_VNODE:
2099 		type = "vnode";
2100 		break;
2101 	case MD_SWAP:
2102 		type = "swap";
2103 		break;
2104 	case MD_NULL:
2105 		type = "null";
2106 		break;
2107 	default:
2108 		type = "unknown";
2109 		break;
2110 	}
2111 
2112 	if (pp != NULL) {
2113 		if (indent == NULL) {
2114 			sbuf_printf(sb, " u %d", mp->unit);
2115 			sbuf_printf(sb, " s %ju", (uintmax_t) mp->sectorsize);
2116 			sbuf_printf(sb, " f %ju", (uintmax_t) mp->fwheads);
2117 			sbuf_printf(sb, " fs %ju", (uintmax_t) mp->fwsectors);
2118 			sbuf_printf(sb, " l %ju", (uintmax_t) mp->mediasize);
2119 			sbuf_printf(sb, " t %s", type);
2120 			if ((mp->type == MD_VNODE && mp->vnode != NULL) ||
2121 			    (mp->type == MD_PRELOAD && mp->file[0] != '\0'))
2122 				sbuf_printf(sb, " file %s", mp->file);
2123 			sbuf_printf(sb, " label %s", mp->label);
2124 		} else {
2125 			sbuf_printf(sb, "%s<unit>%d</unit>\n", indent,
2126 			    mp->unit);
2127 			sbuf_printf(sb, "%s<sectorsize>%ju</sectorsize>\n",
2128 			    indent, (uintmax_t) mp->sectorsize);
2129 			sbuf_printf(sb, "%s<fwheads>%ju</fwheads>\n",
2130 			    indent, (uintmax_t) mp->fwheads);
2131 			sbuf_printf(sb, "%s<fwsectors>%ju</fwsectors>\n",
2132 			    indent, (uintmax_t) mp->fwsectors);
2133 			if (mp->ident[0] != '\0') {
2134 				sbuf_printf(sb, "%s<ident>", indent);
2135 				g_conf_printf_escaped(sb, "%s", mp->ident);
2136 				sbuf_printf(sb, "</ident>\n");
2137 			}
2138 			sbuf_printf(sb, "%s<length>%ju</length>\n",
2139 			    indent, (uintmax_t) mp->mediasize);
2140 			sbuf_printf(sb, "%s<compression>%s</compression>\n", indent,
2141 			    (mp->flags & MD_COMPRESS) == 0 ? "off": "on");
2142 			sbuf_printf(sb, "%s<access>%s</access>\n", indent,
2143 			    (mp->flags & MD_READONLY) == 0 ? "read-write":
2144 			    "read-only");
2145 			sbuf_printf(sb, "%s<type>%s</type>\n", indent,
2146 			    type);
2147 			if ((mp->type == MD_VNODE && mp->vnode != NULL) ||
2148 			    (mp->type == MD_PRELOAD && mp->file[0] != '\0')) {
2149 				sbuf_printf(sb, "%s<file>", indent);
2150 				g_conf_printf_escaped(sb, "%s", mp->file);
2151 				sbuf_printf(sb, "</file>\n");
2152 			}
2153 			if (mp->type == MD_VNODE)
2154 				sbuf_printf(sb, "%s<cache>%s</cache>\n", indent,
2155 				    (mp->flags & MD_CACHE) == 0 ? "off": "on");
2156 			sbuf_printf(sb, "%s<label>", indent);
2157 			g_conf_printf_escaped(sb, "%s", mp->label);
2158 			sbuf_printf(sb, "</label>\n");
2159 		}
2160 	}
2161 }
2162 
2163 static void
2164 g_md_fini(struct g_class *mp __unused)
2165 {
2166 
2167 	sx_destroy(&md_sx);
2168 	if (status_dev != NULL)
2169 		destroy_dev(status_dev);
2170 	uma_zdestroy(md_pbuf_zone);
2171 	delete_unrhdr(md_uh);
2172 }
2173