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