xref: /freebsd/sys/dev/md/md.c (revision 190cef3d)
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 
114 #ifndef MD_NSECT
115 #define MD_NSECT (10000 * 2)
116 #endif
117 
118 struct md_req {
119 	unsigned	md_unit;	/* unit number */
120 	enum md_types	md_type;	/* type of disk */
121 	off_t		md_mediasize;	/* size of disk in bytes */
122 	unsigned	md_sectorsize;	/* sectorsize */
123 	unsigned	md_options;	/* options */
124 	int		md_fwheads;	/* firmware heads */
125 	int		md_fwsectors;	/* firmware sectors */
126 	char		*md_file;	/* pathname of file to mount */
127 	enum uio_seg	md_file_seg;	/* location of md_file */
128 	char		*md_label;	/* label of the device (userspace) */
129 	int		*md_units;	/* pointer to units array (kernel) */
130 	size_t		md_units_nitems; /* items in md_units array */
131 };
132 
133 #ifdef COMPAT_FREEBSD32
134 struct md_ioctl32 {
135 	unsigned	md_version;
136 	unsigned	md_unit;
137 	enum md_types	md_type;
138 	uint32_t	md_file;
139 	off_t		md_mediasize;
140 	unsigned	md_sectorsize;
141 	unsigned	md_options;
142 	uint64_t	md_base;
143 	int		md_fwheads;
144 	int		md_fwsectors;
145 	uint32_t	md_label;
146 	int		md_pad[MDNPAD];
147 } __attribute__((__packed__));
148 CTASSERT((sizeof(struct md_ioctl32)) == 436);
149 
150 #define	MDIOCATTACH_32	_IOC_NEWTYPE(MDIOCATTACH, struct md_ioctl32)
151 #define	MDIOCDETACH_32	_IOC_NEWTYPE(MDIOCDETACH, struct md_ioctl32)
152 #define	MDIOCQUERY_32	_IOC_NEWTYPE(MDIOCQUERY, struct md_ioctl32)
153 #define	MDIOCLIST_32	_IOC_NEWTYPE(MDIOCLIST, 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 
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 };
224 
225 DECLARE_GEOM_CLASS(g_md_class, g_md);
226 
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 int md_vnode_pbuf_freecnt;
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 mtx stat_mtx;
249 	struct cdev *dev;
250 	enum md_types type;
251 	off_t mediasize;
252 	unsigned sectorsize;
253 	unsigned opencount;
254 	unsigned fwheads;
255 	unsigned fwsectors;
256 	char ident[32];
257 	unsigned flags;
258 	char name[20];
259 	struct proc *procp;
260 	struct g_geom *gp;
261 	struct g_provider *pp;
262 	int (*start)(struct md_s *sc, struct bio *bp);
263 	struct devstat *devstat;
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 
447 static int
448 g_md_access(struct g_provider *pp, int r, int w, int e)
449 {
450 	struct md_s *sc;
451 
452 	sc = pp->geom->softc;
453 	if (sc == NULL) {
454 		if (r <= 0 && w <= 0 && e <= 0)
455 			return (0);
456 		return (ENXIO);
457 	}
458 	r += pp->acr;
459 	w += pp->acw;
460 	e += pp->ace;
461 	if ((sc->flags & MD_READONLY) != 0 && w > 0)
462 		return (EROFS);
463 	if ((pp->acr + pp->acw + pp->ace) == 0 && (r + w + e) > 0) {
464 		sc->opencount = 1;
465 	} else if ((pp->acr + pp->acw + pp->ace) > 0 && (r + w + e) == 0) {
466 		sc->opencount = 0;
467 	}
468 	return (0);
469 }
470 
471 static void
472 g_md_start(struct bio *bp)
473 {
474 	struct md_s *sc;
475 
476 	sc = bp->bio_to->geom->softc;
477 	if ((bp->bio_cmd == BIO_READ) || (bp->bio_cmd == BIO_WRITE)) {
478 		mtx_lock(&sc->stat_mtx);
479 		devstat_start_transaction_bio(sc->devstat, bp);
480 		mtx_unlock(&sc->stat_mtx);
481 	}
482 	mtx_lock(&sc->queue_mtx);
483 	bioq_disksort(&sc->bio_queue, bp);
484 	mtx_unlock(&sc->queue_mtx);
485 	wakeup(sc);
486 }
487 
488 #define	MD_MALLOC_MOVE_ZERO	1
489 #define	MD_MALLOC_MOVE_FILL	2
490 #define	MD_MALLOC_MOVE_READ	3
491 #define	MD_MALLOC_MOVE_WRITE	4
492 #define	MD_MALLOC_MOVE_CMP	5
493 
494 static int
495 md_malloc_move_ma(vm_page_t **mp, int *ma_offs, unsigned sectorsize,
496     void *ptr, u_char fill, int op)
497 {
498 	struct sf_buf *sf;
499 	vm_page_t m, *mp1;
500 	char *p, first;
501 	off_t *uc;
502 	unsigned n;
503 	int error, i, ma_offs1, sz, first_read;
504 
505 	m = NULL;
506 	error = 0;
507 	sf = NULL;
508 	/* if (op == MD_MALLOC_MOVE_CMP) { gcc */
509 		first = 0;
510 		first_read = 0;
511 		uc = ptr;
512 		mp1 = *mp;
513 		ma_offs1 = *ma_offs;
514 	/* } */
515 	sched_pin();
516 	for (n = sectorsize; n != 0; n -= sz) {
517 		sz = imin(PAGE_SIZE - *ma_offs, n);
518 		if (m != **mp) {
519 			if (sf != NULL)
520 				sf_buf_free(sf);
521 			m = **mp;
522 			sf = sf_buf_alloc(m, SFB_CPUPRIVATE |
523 			    (md_malloc_wait ? 0 : SFB_NOWAIT));
524 			if (sf == NULL) {
525 				error = ENOMEM;
526 				break;
527 			}
528 		}
529 		p = (char *)sf_buf_kva(sf) + *ma_offs;
530 		switch (op) {
531 		case MD_MALLOC_MOVE_ZERO:
532 			bzero(p, sz);
533 			break;
534 		case MD_MALLOC_MOVE_FILL:
535 			memset(p, fill, sz);
536 			break;
537 		case MD_MALLOC_MOVE_READ:
538 			bcopy(ptr, p, sz);
539 			cpu_flush_dcache(p, sz);
540 			break;
541 		case MD_MALLOC_MOVE_WRITE:
542 			bcopy(p, ptr, sz);
543 			break;
544 		case MD_MALLOC_MOVE_CMP:
545 			for (i = 0; i < sz; i++, p++) {
546 				if (!first_read) {
547 					*uc = (u_char)*p;
548 					first = *p;
549 					first_read = 1;
550 				} else if (*p != first) {
551 					error = EDOOFUS;
552 					break;
553 				}
554 			}
555 			break;
556 		default:
557 			KASSERT(0, ("md_malloc_move_ma unknown op %d\n", op));
558 			break;
559 		}
560 		if (error != 0)
561 			break;
562 		*ma_offs += sz;
563 		*ma_offs %= PAGE_SIZE;
564 		if (*ma_offs == 0)
565 			(*mp)++;
566 		ptr = (char *)ptr + sz;
567 	}
568 
569 	if (sf != NULL)
570 		sf_buf_free(sf);
571 	sched_unpin();
572 	if (op == MD_MALLOC_MOVE_CMP && error != 0) {
573 		*mp = mp1;
574 		*ma_offs = ma_offs1;
575 	}
576 	return (error);
577 }
578 
579 static int
580 md_malloc_move_vlist(bus_dma_segment_t **pvlist, int *pma_offs,
581     unsigned len, void *ptr, u_char fill, int op)
582 {
583 	bus_dma_segment_t *vlist;
584 	uint8_t *p, *end, first;
585 	off_t *uc;
586 	int ma_offs, seg_len;
587 
588 	vlist = *pvlist;
589 	ma_offs = *pma_offs;
590 	uc = ptr;
591 
592 	for (; len != 0; len -= seg_len) {
593 		seg_len = imin(vlist->ds_len - ma_offs, len);
594 		p = (uint8_t *)(uintptr_t)vlist->ds_addr + ma_offs;
595 		switch (op) {
596 		case MD_MALLOC_MOVE_ZERO:
597 			bzero(p, seg_len);
598 			break;
599 		case MD_MALLOC_MOVE_FILL:
600 			memset(p, fill, seg_len);
601 			break;
602 		case MD_MALLOC_MOVE_READ:
603 			bcopy(ptr, p, seg_len);
604 			cpu_flush_dcache(p, seg_len);
605 			break;
606 		case MD_MALLOC_MOVE_WRITE:
607 			bcopy(p, ptr, seg_len);
608 			break;
609 		case MD_MALLOC_MOVE_CMP:
610 			end = p + seg_len;
611 			first = *uc = *p;
612 			/* Confirm all following bytes match the first */
613 			while (++p < end) {
614 				if (*p != first)
615 					return (EDOOFUS);
616 			}
617 			break;
618 		default:
619 			KASSERT(0, ("md_malloc_move_vlist unknown op %d\n", op));
620 			break;
621 		}
622 
623 		ma_offs += seg_len;
624 		if (ma_offs == vlist->ds_len) {
625 			ma_offs = 0;
626 			vlist++;
627 		}
628 		ptr = (uint8_t *)ptr + seg_len;
629 	}
630 	*pvlist = vlist;
631 	*pma_offs = ma_offs;
632 
633 	return (0);
634 }
635 
636 static int
637 mdstart_malloc(struct md_s *sc, struct bio *bp)
638 {
639 	u_char *dst;
640 	vm_page_t *m;
641 	bus_dma_segment_t *vlist;
642 	int i, error, error1, ma_offs, notmapped;
643 	off_t secno, nsec, uc;
644 	uintptr_t sp, osp;
645 
646 	switch (bp->bio_cmd) {
647 	case BIO_READ:
648 	case BIO_WRITE:
649 	case BIO_DELETE:
650 		break;
651 	default:
652 		return (EOPNOTSUPP);
653 	}
654 
655 	notmapped = (bp->bio_flags & BIO_UNMAPPED) != 0;
656 	vlist = (bp->bio_flags & BIO_VLIST) != 0 ?
657 	    (bus_dma_segment_t *)bp->bio_data : NULL;
658 	if (notmapped) {
659 		m = bp->bio_ma;
660 		ma_offs = bp->bio_ma_offset;
661 		dst = NULL;
662 		KASSERT(vlist == NULL, ("vlists cannot be unmapped"));
663 	} else if (vlist != NULL) {
664 		ma_offs = bp->bio_ma_offset;
665 		dst = NULL;
666 	} else {
667 		dst = bp->bio_data;
668 	}
669 
670 	nsec = bp->bio_length / sc->sectorsize;
671 	secno = bp->bio_offset / sc->sectorsize;
672 	error = 0;
673 	while (nsec--) {
674 		osp = s_read(sc->indir, secno);
675 		if (bp->bio_cmd == BIO_DELETE) {
676 			if (osp != 0)
677 				error = s_write(sc->indir, secno, 0);
678 		} else if (bp->bio_cmd == BIO_READ) {
679 			if (osp == 0) {
680 				if (notmapped) {
681 					error = md_malloc_move_ma(&m, &ma_offs,
682 					    sc->sectorsize, NULL, 0,
683 					    MD_MALLOC_MOVE_ZERO);
684 				} else if (vlist != NULL) {
685 					error = md_malloc_move_vlist(&vlist,
686 					    &ma_offs, sc->sectorsize, NULL, 0,
687 					    MD_MALLOC_MOVE_ZERO);
688 				} else
689 					bzero(dst, sc->sectorsize);
690 			} else if (osp <= 255) {
691 				if (notmapped) {
692 					error = md_malloc_move_ma(&m, &ma_offs,
693 					    sc->sectorsize, NULL, osp,
694 					    MD_MALLOC_MOVE_FILL);
695 				} else if (vlist != NULL) {
696 					error = md_malloc_move_vlist(&vlist,
697 					    &ma_offs, sc->sectorsize, NULL, osp,
698 					    MD_MALLOC_MOVE_FILL);
699 				} else
700 					memset(dst, osp, sc->sectorsize);
701 			} else {
702 				if (notmapped) {
703 					error = md_malloc_move_ma(&m, &ma_offs,
704 					    sc->sectorsize, (void *)osp, 0,
705 					    MD_MALLOC_MOVE_READ);
706 				} else if (vlist != NULL) {
707 					error = md_malloc_move_vlist(&vlist,
708 					    &ma_offs, sc->sectorsize,
709 					    (void *)osp, 0,
710 					    MD_MALLOC_MOVE_READ);
711 				} else {
712 					bcopy((void *)osp, dst, sc->sectorsize);
713 					cpu_flush_dcache(dst, sc->sectorsize);
714 				}
715 			}
716 			osp = 0;
717 		} else if (bp->bio_cmd == BIO_WRITE) {
718 			if (sc->flags & MD_COMPRESS) {
719 				if (notmapped) {
720 					error1 = md_malloc_move_ma(&m, &ma_offs,
721 					    sc->sectorsize, &uc, 0,
722 					    MD_MALLOC_MOVE_CMP);
723 					i = error1 == 0 ? sc->sectorsize : 0;
724 				} else if (vlist != NULL) {
725 					error1 = md_malloc_move_vlist(&vlist,
726 					    &ma_offs, sc->sectorsize, &uc, 0,
727 					    MD_MALLOC_MOVE_CMP);
728 					i = error1 == 0 ? sc->sectorsize : 0;
729 				} else {
730 					uc = dst[0];
731 					for (i = 1; i < sc->sectorsize; i++) {
732 						if (dst[i] != uc)
733 							break;
734 					}
735 				}
736 			} else {
737 				i = 0;
738 				uc = 0;
739 			}
740 			if (i == sc->sectorsize) {
741 				if (osp != uc)
742 					error = s_write(sc->indir, secno, uc);
743 			} else {
744 				if (osp <= 255) {
745 					sp = (uintptr_t)uma_zalloc(sc->uma,
746 					    md_malloc_wait ? M_WAITOK :
747 					    M_NOWAIT);
748 					if (sp == 0) {
749 						error = ENOSPC;
750 						break;
751 					}
752 					if (notmapped) {
753 						error = md_malloc_move_ma(&m,
754 						    &ma_offs, sc->sectorsize,
755 						    (void *)sp, 0,
756 						    MD_MALLOC_MOVE_WRITE);
757 					} else if (vlist != NULL) {
758 						error = md_malloc_move_vlist(
759 						    &vlist, &ma_offs,
760 						    sc->sectorsize, (void *)sp,
761 						    0, MD_MALLOC_MOVE_WRITE);
762 					} else {
763 						bcopy(dst, (void *)sp,
764 						    sc->sectorsize);
765 					}
766 					error = s_write(sc->indir, secno, sp);
767 				} else {
768 					if (notmapped) {
769 						error = md_malloc_move_ma(&m,
770 						    &ma_offs, sc->sectorsize,
771 						    (void *)osp, 0,
772 						    MD_MALLOC_MOVE_WRITE);
773 					} else if (vlist != NULL) {
774 						error = md_malloc_move_vlist(
775 						    &vlist, &ma_offs,
776 						    sc->sectorsize, (void *)osp,
777 						    0, MD_MALLOC_MOVE_WRITE);
778 					} else {
779 						bcopy(dst, (void *)osp,
780 						    sc->sectorsize);
781 					}
782 					osp = 0;
783 				}
784 			}
785 		} else {
786 			error = EOPNOTSUPP;
787 		}
788 		if (osp > 255)
789 			uma_zfree(sc->uma, (void*)osp);
790 		if (error != 0)
791 			break;
792 		secno++;
793 		if (!notmapped && vlist == NULL)
794 			dst += sc->sectorsize;
795 	}
796 	bp->bio_resid = 0;
797 	return (error);
798 }
799 
800 static void
801 mdcopyto_vlist(void *src, bus_dma_segment_t *vlist, off_t offset, off_t len)
802 {
803 	off_t seg_len;
804 
805 	while (offset >= vlist->ds_len) {
806 		offset -= vlist->ds_len;
807 		vlist++;
808 	}
809 
810 	while (len != 0) {
811 		seg_len = omin(len, vlist->ds_len - offset);
812 		bcopy(src, (void *)(uintptr_t)(vlist->ds_addr + offset),
813 		    seg_len);
814 		offset = 0;
815 		src = (uint8_t *)src + seg_len;
816 		len -= seg_len;
817 		vlist++;
818 	}
819 }
820 
821 static void
822 mdcopyfrom_vlist(bus_dma_segment_t *vlist, off_t offset, void *dst, off_t len)
823 {
824 	off_t seg_len;
825 
826 	while (offset >= vlist->ds_len) {
827 		offset -= vlist->ds_len;
828 		vlist++;
829 	}
830 
831 	while (len != 0) {
832 		seg_len = omin(len, vlist->ds_len - offset);
833 		bcopy((void *)(uintptr_t)(vlist->ds_addr + offset), dst,
834 		    seg_len);
835 		offset = 0;
836 		dst = (uint8_t *)dst + seg_len;
837 		len -= seg_len;
838 		vlist++;
839 	}
840 }
841 
842 static int
843 mdstart_preload(struct md_s *sc, struct bio *bp)
844 {
845 	uint8_t *p;
846 
847 	p = sc->pl_ptr + bp->bio_offset;
848 	switch (bp->bio_cmd) {
849 	case BIO_READ:
850 		if ((bp->bio_flags & BIO_VLIST) != 0) {
851 			mdcopyto_vlist(p, (bus_dma_segment_t *)bp->bio_data,
852 			    bp->bio_ma_offset, bp->bio_length);
853 		} else {
854 			bcopy(p, bp->bio_data, bp->bio_length);
855 		}
856 		cpu_flush_dcache(bp->bio_data, bp->bio_length);
857 		break;
858 	case BIO_WRITE:
859 		if ((bp->bio_flags & BIO_VLIST) != 0) {
860 			mdcopyfrom_vlist((bus_dma_segment_t *)bp->bio_data,
861 			    bp->bio_ma_offset, p, bp->bio_length);
862 		} else {
863 			bcopy(bp->bio_data, p, bp->bio_length);
864 		}
865 		break;
866 	}
867 	bp->bio_resid = 0;
868 	return (0);
869 }
870 
871 static int
872 mdstart_vnode(struct md_s *sc, struct bio *bp)
873 {
874 	int error;
875 	struct uio auio;
876 	struct iovec aiov;
877 	struct iovec *piov;
878 	struct mount *mp;
879 	struct vnode *vp;
880 	struct buf *pb;
881 	bus_dma_segment_t *vlist;
882 	struct thread *td;
883 	off_t iolen, len, zerosize;
884 	int ma_offs, npages;
885 
886 	switch (bp->bio_cmd) {
887 	case BIO_READ:
888 		auio.uio_rw = UIO_READ;
889 		break;
890 	case BIO_WRITE:
891 	case BIO_DELETE:
892 		auio.uio_rw = UIO_WRITE;
893 		break;
894 	case BIO_FLUSH:
895 		break;
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 	len = bp->bio_length;
906 
907 	/*
908 	 * VNODE I/O
909 	 *
910 	 * If an error occurs, we set BIO_ERROR but we do not set
911 	 * B_INVAL because (for a write anyway), the buffer is
912 	 * still valid.
913 	 */
914 
915 	if (bp->bio_cmd == BIO_FLUSH) {
916 		(void) vn_start_write(vp, &mp, V_WAIT);
917 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
918 		error = VOP_FSYNC(vp, MNT_WAIT, td);
919 		VOP_UNLOCK(vp, 0);
920 		vn_finished_write(mp);
921 		return (error);
922 	}
923 
924 	auio.uio_offset = (vm_ooffset_t)bp->bio_offset;
925 	auio.uio_resid = bp->bio_length;
926 	auio.uio_segflg = UIO_SYSSPACE;
927 	auio.uio_td = td;
928 
929 	if (bp->bio_cmd == BIO_DELETE) {
930 		/*
931 		 * Emulate BIO_DELETE by writing zeros.
932 		 */
933 		zerosize = ZERO_REGION_SIZE -
934 		    (ZERO_REGION_SIZE % sc->sectorsize);
935 		auio.uio_iovcnt = howmany(bp->bio_length, zerosize);
936 		piov = malloc(sizeof(*piov) * auio.uio_iovcnt, M_MD, M_WAITOK);
937 		auio.uio_iov = piov;
938 		while (len > 0) {
939 			piov->iov_base = __DECONST(void *, zero_region);
940 			piov->iov_len = len;
941 			if (len > zerosize)
942 				piov->iov_len = zerosize;
943 			len -= piov->iov_len;
944 			piov++;
945 		}
946 		piov = auio.uio_iov;
947 	} else if ((bp->bio_flags & BIO_VLIST) != 0) {
948 		piov = malloc(sizeof(*piov) * bp->bio_ma_n, M_MD, M_WAITOK);
949 		auio.uio_iov = piov;
950 		vlist = (bus_dma_segment_t *)bp->bio_data;
951 		while (len > 0) {
952 			piov->iov_base = (void *)(uintptr_t)(vlist->ds_addr +
953 			    ma_offs);
954 			piov->iov_len = vlist->ds_len - ma_offs;
955 			if (piov->iov_len > len)
956 				piov->iov_len = len;
957 			len -= piov->iov_len;
958 			ma_offs = 0;
959 			vlist++;
960 			piov++;
961 		}
962 		auio.uio_iovcnt = piov - auio.uio_iov;
963 		piov = auio.uio_iov;
964 	} else if ((bp->bio_flags & BIO_UNMAPPED) != 0) {
965 		pb = getpbuf(&md_vnode_pbuf_freecnt);
966 		bp->bio_resid = len;
967 unmapped_step:
968 		npages = atop(min(MAXPHYS, round_page(len + (ma_offs &
969 		    PAGE_MASK))));
970 		iolen = min(ptoa(npages) - (ma_offs & PAGE_MASK), len);
971 		KASSERT(iolen > 0, ("zero iolen"));
972 		pmap_qenter((vm_offset_t)pb->b_data,
973 		    &bp->bio_ma[atop(ma_offs)], npages);
974 		aiov.iov_base = (void *)((vm_offset_t)pb->b_data +
975 		    (ma_offs & PAGE_MASK));
976 		aiov.iov_len = iolen;
977 		auio.uio_iov = &aiov;
978 		auio.uio_iovcnt = 1;
979 		auio.uio_resid = iolen;
980 	} else {
981 		aiov.iov_base = bp->bio_data;
982 		aiov.iov_len = bp->bio_length;
983 		auio.uio_iov = &aiov;
984 		auio.uio_iovcnt = 1;
985 	}
986 	/*
987 	 * When reading set IO_DIRECT to try to avoid double-caching
988 	 * the data.  When writing IO_DIRECT is not optimal.
989 	 */
990 	if (auio.uio_rw == UIO_READ) {
991 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
992 		error = VOP_READ(vp, &auio, IO_DIRECT, sc->cred);
993 		VOP_UNLOCK(vp, 0);
994 	} else {
995 		(void) vn_start_write(vp, &mp, V_WAIT);
996 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
997 		error = VOP_WRITE(vp, &auio, sc->flags & MD_ASYNC ? 0 : IO_SYNC,
998 		    sc->cred);
999 		VOP_UNLOCK(vp, 0);
1000 		vn_finished_write(mp);
1001 		if (error == 0)
1002 			sc->flags &= ~MD_VERIFY;
1003 	}
1004 
1005 	if (pb != NULL) {
1006 		pmap_qremove((vm_offset_t)pb->b_data, npages);
1007 		if (error == 0) {
1008 			len -= iolen;
1009 			bp->bio_resid -= iolen;
1010 			ma_offs += iolen;
1011 			if (len > 0)
1012 				goto unmapped_step;
1013 		}
1014 		relpbuf(pb, &md_vnode_pbuf_freecnt);
1015 	}
1016 
1017 	free(piov, M_MD);
1018 	if (pb == NULL)
1019 		bp->bio_resid = auio.uio_resid;
1020 	return (error);
1021 }
1022 
1023 static void
1024 md_swap_page_free(vm_page_t m)
1025 {
1026 
1027 	vm_page_xunbusy(m);
1028 	vm_page_lock(m);
1029 	vm_page_free(m);
1030 	vm_page_unlock(m);
1031 }
1032 
1033 static int
1034 mdstart_swap(struct md_s *sc, struct bio *bp)
1035 {
1036 	vm_page_t m;
1037 	u_char *p;
1038 	vm_pindex_t i, lastp;
1039 	bus_dma_segment_t *vlist;
1040 	int rv, ma_offs, offs, len, lastend;
1041 
1042 	switch (bp->bio_cmd) {
1043 	case BIO_READ:
1044 	case BIO_WRITE:
1045 	case BIO_DELETE:
1046 		break;
1047 	default:
1048 		return (EOPNOTSUPP);
1049 	}
1050 
1051 	p = bp->bio_data;
1052 	ma_offs = (bp->bio_flags & (BIO_UNMAPPED|BIO_VLIST)) != 0 ?
1053 	    bp->bio_ma_offset : 0;
1054 	vlist = (bp->bio_flags & BIO_VLIST) != 0 ?
1055 	    (bus_dma_segment_t *)bp->bio_data : NULL;
1056 
1057 	/*
1058 	 * offs is the offset at which to start operating on the
1059 	 * next (ie, first) page.  lastp is the last page on
1060 	 * which we're going to operate.  lastend is the ending
1061 	 * position within that last page (ie, PAGE_SIZE if
1062 	 * we're operating on complete aligned pages).
1063 	 */
1064 	offs = bp->bio_offset % PAGE_SIZE;
1065 	lastp = (bp->bio_offset + bp->bio_length - 1) / PAGE_SIZE;
1066 	lastend = (bp->bio_offset + bp->bio_length - 1) % PAGE_SIZE + 1;
1067 
1068 	rv = VM_PAGER_OK;
1069 	VM_OBJECT_WLOCK(sc->object);
1070 	vm_object_pip_add(sc->object, 1);
1071 	for (i = bp->bio_offset / PAGE_SIZE; i <= lastp; i++) {
1072 		len = ((i == lastp) ? lastend : PAGE_SIZE) - offs;
1073 		m = vm_page_grab(sc->object, i, VM_ALLOC_SYSTEM);
1074 		if (bp->bio_cmd == BIO_READ) {
1075 			if (m->valid == VM_PAGE_BITS_ALL)
1076 				rv = VM_PAGER_OK;
1077 			else
1078 				rv = vm_pager_get_pages(sc->object, &m, 1,
1079 				    NULL, NULL);
1080 			if (rv == VM_PAGER_ERROR) {
1081 				md_swap_page_free(m);
1082 				break;
1083 			} else if (rv == VM_PAGER_FAIL) {
1084 				/*
1085 				 * Pager does not have the page.  Zero
1086 				 * the allocated page, and mark it as
1087 				 * valid. Do not set dirty, the page
1088 				 * can be recreated if thrown out.
1089 				 */
1090 				pmap_zero_page(m);
1091 				m->valid = VM_PAGE_BITS_ALL;
1092 			}
1093 			if ((bp->bio_flags & BIO_UNMAPPED) != 0) {
1094 				pmap_copy_pages(&m, offs, bp->bio_ma,
1095 				    ma_offs, len);
1096 			} else if ((bp->bio_flags & BIO_VLIST) != 0) {
1097 				physcopyout_vlist(VM_PAGE_TO_PHYS(m) + offs,
1098 				    vlist, ma_offs, len);
1099 				cpu_flush_dcache(p, len);
1100 			} else {
1101 				physcopyout(VM_PAGE_TO_PHYS(m) + offs, p, len);
1102 				cpu_flush_dcache(p, len);
1103 			}
1104 		} else if (bp->bio_cmd == BIO_WRITE) {
1105 			if (len == PAGE_SIZE || m->valid == VM_PAGE_BITS_ALL)
1106 				rv = VM_PAGER_OK;
1107 			else
1108 				rv = vm_pager_get_pages(sc->object, &m, 1,
1109 				    NULL, NULL);
1110 			if (rv == VM_PAGER_ERROR) {
1111 				md_swap_page_free(m);
1112 				break;
1113 			} else if (rv == VM_PAGER_FAIL)
1114 				pmap_zero_page(m);
1115 
1116 			if ((bp->bio_flags & BIO_UNMAPPED) != 0) {
1117 				pmap_copy_pages(bp->bio_ma, ma_offs, &m,
1118 				    offs, len);
1119 			} else if ((bp->bio_flags & BIO_VLIST) != 0) {
1120 				physcopyin_vlist(vlist, ma_offs,
1121 				    VM_PAGE_TO_PHYS(m) + offs, len);
1122 			} else {
1123 				physcopyin(p, VM_PAGE_TO_PHYS(m) + offs, len);
1124 			}
1125 
1126 			m->valid = VM_PAGE_BITS_ALL;
1127 			if (m->dirty != VM_PAGE_BITS_ALL) {
1128 				vm_page_dirty(m);
1129 				vm_pager_page_unswapped(m);
1130 			}
1131 		} else if (bp->bio_cmd == BIO_DELETE) {
1132 			if (len == PAGE_SIZE || m->valid == VM_PAGE_BITS_ALL)
1133 				rv = VM_PAGER_OK;
1134 			else
1135 				rv = vm_pager_get_pages(sc->object, &m, 1,
1136 				    NULL, NULL);
1137 			if (rv == VM_PAGER_ERROR) {
1138 				md_swap_page_free(m);
1139 				break;
1140 			} else if (rv == VM_PAGER_FAIL) {
1141 				md_swap_page_free(m);
1142 				m = NULL;
1143 			} else {
1144 				/* Page is valid. */
1145 				if (len != PAGE_SIZE) {
1146 					pmap_zero_page_area(m, offs, len);
1147 					if (m->dirty != VM_PAGE_BITS_ALL) {
1148 						vm_page_dirty(m);
1149 						vm_pager_page_unswapped(m);
1150 					}
1151 				} else {
1152 					vm_pager_page_unswapped(m);
1153 					md_swap_page_free(m);
1154 					m = NULL;
1155 				}
1156 			}
1157 		}
1158 		if (m != NULL) {
1159 			vm_page_xunbusy(m);
1160 			vm_page_lock(m);
1161 			if (vm_page_active(m))
1162 				vm_page_reference(m);
1163 			else
1164 				vm_page_activate(m);
1165 			vm_page_unlock(m);
1166 		}
1167 
1168 		/* Actions on further pages start at offset 0 */
1169 		p += PAGE_SIZE - offs;
1170 		offs = 0;
1171 		ma_offs += len;
1172 	}
1173 	vm_object_pip_wakeup(sc->object);
1174 	VM_OBJECT_WUNLOCK(sc->object);
1175 	return (rv != VM_PAGER_ERROR ? 0 : ENOSPC);
1176 }
1177 
1178 static int
1179 mdstart_null(struct md_s *sc, struct bio *bp)
1180 {
1181 
1182 	switch (bp->bio_cmd) {
1183 	case BIO_READ:
1184 		bzero(bp->bio_data, bp->bio_length);
1185 		cpu_flush_dcache(bp->bio_data, bp->bio_length);
1186 		break;
1187 	case BIO_WRITE:
1188 		break;
1189 	}
1190 	bp->bio_resid = 0;
1191 	return (0);
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 			int isv = ((sc->flags & MD_VERIFY) != 0);
1223 
1224 			if ((sc->fwsectors && sc->fwheads &&
1225 			    (g_handleattr_int(bp, "GEOM::fwsectors",
1226 			    sc->fwsectors) ||
1227 			    g_handleattr_int(bp, "GEOM::fwheads",
1228 			    sc->fwheads))) ||
1229 			    g_handleattr_int(bp, "GEOM::candelete", 1))
1230 				error = -1;
1231 			else if (sc->ident[0] != '\0' &&
1232 			    g_handleattr_str(bp, "GEOM::ident", sc->ident))
1233 				error = -1;
1234 			else if (g_handleattr_int(bp, "MNT::verified", isv))
1235 				error = -1;
1236 			else
1237 				error = EOPNOTSUPP;
1238 		} else {
1239 			error = sc->start(sc, bp);
1240 		}
1241 
1242 		if (error != -1) {
1243 			bp->bio_completed = bp->bio_length;
1244 			if ((bp->bio_cmd == BIO_READ) || (bp->bio_cmd == BIO_WRITE))
1245 				devstat_end_transaction_bio(sc->devstat, bp);
1246 			g_io_deliver(bp, error);
1247 		}
1248 	}
1249 }
1250 
1251 static struct md_s *
1252 mdfind(int unit)
1253 {
1254 	struct md_s *sc;
1255 
1256 	LIST_FOREACH(sc, &md_softc_list, list) {
1257 		if (sc->unit == unit)
1258 			break;
1259 	}
1260 	return (sc);
1261 }
1262 
1263 static struct md_s *
1264 mdnew(int unit, int *errp, enum md_types type)
1265 {
1266 	struct md_s *sc;
1267 	int error;
1268 
1269 	*errp = 0;
1270 	if (unit == -1)
1271 		unit = alloc_unr(md_uh);
1272 	else
1273 		unit = alloc_unr_specific(md_uh, unit);
1274 
1275 	if (unit == -1) {
1276 		*errp = EBUSY;
1277 		return (NULL);
1278 	}
1279 
1280 	sc = (struct md_s *)malloc(sizeof *sc, M_MD, M_WAITOK | M_ZERO);
1281 	sc->type = type;
1282 	bioq_init(&sc->bio_queue);
1283 	mtx_init(&sc->queue_mtx, "md bio queue", NULL, MTX_DEF);
1284 	mtx_init(&sc->stat_mtx, "md stat", NULL, MTX_DEF);
1285 	sc->unit = unit;
1286 	sprintf(sc->name, "md%d", unit);
1287 	LIST_INSERT_HEAD(&md_softc_list, sc, list);
1288 	error = kproc_create(md_kthread, sc, &sc->procp, 0, 0,"%s", sc->name);
1289 	if (error == 0)
1290 		return (sc);
1291 	LIST_REMOVE(sc, list);
1292 	mtx_destroy(&sc->stat_mtx);
1293 	mtx_destroy(&sc->queue_mtx);
1294 	free_unr(md_uh, sc->unit);
1295 	free(sc, M_MD);
1296 	*errp = error;
1297 	return (NULL);
1298 }
1299 
1300 static void
1301 mdinit(struct md_s *sc)
1302 {
1303 	struct g_geom *gp;
1304 	struct g_provider *pp;
1305 
1306 	g_topology_lock();
1307 	gp = g_new_geomf(&g_md_class, "md%d", sc->unit);
1308 	gp->softc = sc;
1309 	pp = g_new_providerf(gp, "md%d", sc->unit);
1310 	pp->flags |= G_PF_DIRECT_SEND | G_PF_DIRECT_RECEIVE;
1311 	pp->mediasize = sc->mediasize;
1312 	pp->sectorsize = sc->sectorsize;
1313 	switch (sc->type) {
1314 	case MD_MALLOC:
1315 	case MD_VNODE:
1316 	case MD_SWAP:
1317 		pp->flags |= G_PF_ACCEPT_UNMAPPED;
1318 		break;
1319 	case MD_PRELOAD:
1320 	case MD_NULL:
1321 		break;
1322 	}
1323 	sc->gp = gp;
1324 	sc->pp = pp;
1325 	g_error_provider(pp, 0);
1326 	g_topology_unlock();
1327 	sc->devstat = devstat_new_entry("md", sc->unit, sc->sectorsize,
1328 	    DEVSTAT_ALL_SUPPORTED, DEVSTAT_TYPE_DIRECT, DEVSTAT_PRIORITY_MAX);
1329 }
1330 
1331 static int
1332 mdcreate_malloc(struct md_s *sc, struct md_req *mdr)
1333 {
1334 	uintptr_t sp;
1335 	int error;
1336 	off_t u;
1337 
1338 	error = 0;
1339 	if (mdr->md_options & ~(MD_AUTOUNIT | MD_COMPRESS | MD_RESERVE))
1340 		return (EINVAL);
1341 	if (mdr->md_sectorsize != 0 && !powerof2(mdr->md_sectorsize))
1342 		return (EINVAL);
1343 	/* Compression doesn't make sense if we have reserved space */
1344 	if (mdr->md_options & MD_RESERVE)
1345 		mdr->md_options &= ~MD_COMPRESS;
1346 	if (mdr->md_fwsectors != 0)
1347 		sc->fwsectors = mdr->md_fwsectors;
1348 	if (mdr->md_fwheads != 0)
1349 		sc->fwheads = mdr->md_fwheads;
1350 	sc->flags = mdr->md_options & (MD_COMPRESS | MD_FORCE);
1351 	sc->indir = dimension(sc->mediasize / sc->sectorsize);
1352 	sc->uma = uma_zcreate(sc->name, sc->sectorsize, NULL, NULL, NULL, NULL,
1353 	    0x1ff, 0);
1354 	if (mdr->md_options & MD_RESERVE) {
1355 		off_t nsectors;
1356 
1357 		nsectors = sc->mediasize / sc->sectorsize;
1358 		for (u = 0; u < nsectors; u++) {
1359 			sp = (uintptr_t)uma_zalloc(sc->uma, (md_malloc_wait ?
1360 			    M_WAITOK : M_NOWAIT) | M_ZERO);
1361 			if (sp != 0)
1362 				error = s_write(sc->indir, u, sp);
1363 			else
1364 				error = ENOMEM;
1365 			if (error != 0)
1366 				break;
1367 		}
1368 	}
1369 	return (error);
1370 }
1371 
1372 
1373 static int
1374 mdsetcred(struct md_s *sc, struct ucred *cred)
1375 {
1376 	char *tmpbuf;
1377 	int error = 0;
1378 
1379 	/*
1380 	 * Set credits in our softc
1381 	 */
1382 
1383 	if (sc->cred)
1384 		crfree(sc->cred);
1385 	sc->cred = crhold(cred);
1386 
1387 	/*
1388 	 * Horrible kludge to establish credentials for NFS  XXX.
1389 	 */
1390 
1391 	if (sc->vnode) {
1392 		struct uio auio;
1393 		struct iovec aiov;
1394 
1395 		tmpbuf = malloc(sc->sectorsize, M_TEMP, M_WAITOK);
1396 		bzero(&auio, sizeof(auio));
1397 
1398 		aiov.iov_base = tmpbuf;
1399 		aiov.iov_len = sc->sectorsize;
1400 		auio.uio_iov = &aiov;
1401 		auio.uio_iovcnt = 1;
1402 		auio.uio_offset = 0;
1403 		auio.uio_rw = UIO_READ;
1404 		auio.uio_segflg = UIO_SYSSPACE;
1405 		auio.uio_resid = aiov.iov_len;
1406 		vn_lock(sc->vnode, LK_EXCLUSIVE | LK_RETRY);
1407 		error = VOP_READ(sc->vnode, &auio, 0, sc->cred);
1408 		VOP_UNLOCK(sc->vnode, 0);
1409 		free(tmpbuf, M_TEMP);
1410 	}
1411 	return (error);
1412 }
1413 
1414 static int
1415 mdcreate_vnode(struct md_s *sc, struct md_req *mdr, struct thread *td)
1416 {
1417 	struct vattr vattr;
1418 	struct nameidata nd;
1419 	char *fname;
1420 	int error, flags;
1421 
1422 	fname = mdr->md_file;
1423 	if (mdr->md_file_seg == UIO_USERSPACE) {
1424 		error = copyinstr(fname, sc->file, sizeof(sc->file), NULL);
1425 		if (error != 0)
1426 			return (error);
1427 	} else if (mdr->md_file_seg == UIO_SYSSPACE)
1428 		strlcpy(sc->file, fname, sizeof(sc->file));
1429 	else
1430 		return (EDOOFUS);
1431 
1432 	/*
1433 	 * If the user specified that this is a read only device, don't
1434 	 * set the FWRITE mask before trying to open the backing store.
1435 	 */
1436 	flags = FREAD | ((mdr->md_options & MD_READONLY) ? 0 : FWRITE) \
1437 	    | ((mdr->md_options & MD_VERIFY) ? O_VERIFY : 0);
1438 	NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, sc->file, td);
1439 	error = vn_open(&nd, &flags, 0, NULL);
1440 	if (error != 0)
1441 		return (error);
1442 	NDFREE(&nd, NDF_ONLY_PNBUF);
1443 	if (nd.ni_vp->v_type != VREG) {
1444 		error = EINVAL;
1445 		goto bad;
1446 	}
1447 	error = VOP_GETATTR(nd.ni_vp, &vattr, td->td_ucred);
1448 	if (error != 0)
1449 		goto bad;
1450 	if (VOP_ISLOCKED(nd.ni_vp) != LK_EXCLUSIVE) {
1451 		vn_lock(nd.ni_vp, LK_UPGRADE | LK_RETRY);
1452 		if (nd.ni_vp->v_iflag & VI_DOOMED) {
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, 0);
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_FORCE | MD_ASYNC | MD_VERIFY);
1468 	if (!(flags & FWRITE))
1469 		sc->flags |= MD_READONLY;
1470 	sc->vnode = nd.ni_vp;
1471 
1472 	error = mdsetcred(sc, td->td_ucred);
1473 	if (error != 0) {
1474 		sc->vnode = NULL;
1475 		vn_lock(nd.ni_vp, LK_EXCLUSIVE | LK_RETRY);
1476 		nd.ni_vp->v_vflag &= ~VV_MD;
1477 		goto bad;
1478 	}
1479 	return (0);
1480 bad:
1481 	VOP_UNLOCK(nd.ni_vp, 0);
1482 	(void)vn_close(nd.ni_vp, flags, td->td_ucred, td);
1483 	return (error);
1484 }
1485 
1486 static int
1487 mddestroy(struct md_s *sc, struct thread *td)
1488 {
1489 
1490 	if (sc->gp) {
1491 		sc->gp->softc = NULL;
1492 		g_topology_lock();
1493 		g_wither_geom(sc->gp, ENXIO);
1494 		g_topology_unlock();
1495 		sc->gp = NULL;
1496 		sc->pp = NULL;
1497 	}
1498 	if (sc->devstat) {
1499 		devstat_remove_entry(sc->devstat);
1500 		sc->devstat = NULL;
1501 	}
1502 	mtx_lock(&sc->queue_mtx);
1503 	sc->flags |= MD_SHUTDOWN;
1504 	wakeup(sc);
1505 	while (!(sc->flags & MD_EXITING))
1506 		msleep(sc->procp, &sc->queue_mtx, PRIBIO, "mddestroy", hz / 10);
1507 	mtx_unlock(&sc->queue_mtx);
1508 	mtx_destroy(&sc->stat_mtx);
1509 	mtx_destroy(&sc->queue_mtx);
1510 	if (sc->vnode != NULL) {
1511 		vn_lock(sc->vnode, LK_EXCLUSIVE | LK_RETRY);
1512 		sc->vnode->v_vflag &= ~VV_MD;
1513 		VOP_UNLOCK(sc->vnode, 0);
1514 		(void)vn_close(sc->vnode, sc->flags & MD_READONLY ?
1515 		    FREAD : (FREAD|FWRITE), sc->cred, td);
1516 	}
1517 	if (sc->cred != NULL)
1518 		crfree(sc->cred);
1519 	if (sc->object != NULL)
1520 		vm_object_deallocate(sc->object);
1521 	if (sc->indir)
1522 		destroy_indir(sc, sc->indir);
1523 	if (sc->uma)
1524 		uma_zdestroy(sc->uma);
1525 
1526 	LIST_REMOVE(sc, list);
1527 	free_unr(md_uh, sc->unit);
1528 	free(sc, M_MD);
1529 	return (0);
1530 }
1531 
1532 static int
1533 mdresize(struct md_s *sc, struct md_req *mdr)
1534 {
1535 	int error, res;
1536 	vm_pindex_t oldpages, newpages;
1537 
1538 	switch (sc->type) {
1539 	case MD_VNODE:
1540 	case MD_NULL:
1541 		break;
1542 	case MD_SWAP:
1543 		if (mdr->md_mediasize <= 0 ||
1544 		    (mdr->md_mediasize % PAGE_SIZE) != 0)
1545 			return (EDOM);
1546 		oldpages = OFF_TO_IDX(round_page(sc->mediasize));
1547 		newpages = OFF_TO_IDX(round_page(mdr->md_mediasize));
1548 		if (newpages < oldpages) {
1549 			VM_OBJECT_WLOCK(sc->object);
1550 			vm_object_page_remove(sc->object, newpages, 0, 0);
1551 			swap_pager_freespace(sc->object, newpages,
1552 			    oldpages - newpages);
1553 			swap_release_by_cred(IDX_TO_OFF(oldpages -
1554 			    newpages), sc->cred);
1555 			sc->object->charge = IDX_TO_OFF(newpages);
1556 			sc->object->size = newpages;
1557 			VM_OBJECT_WUNLOCK(sc->object);
1558 		} else if (newpages > oldpages) {
1559 			res = swap_reserve_by_cred(IDX_TO_OFF(newpages -
1560 			    oldpages), sc->cred);
1561 			if (!res)
1562 				return (ENOMEM);
1563 			if ((mdr->md_options & MD_RESERVE) ||
1564 			    (sc->flags & MD_RESERVE)) {
1565 				error = swap_pager_reserve(sc->object,
1566 				    oldpages, newpages - oldpages);
1567 				if (error < 0) {
1568 					swap_release_by_cred(
1569 					    IDX_TO_OFF(newpages - oldpages),
1570 					    sc->cred);
1571 					return (EDOM);
1572 				}
1573 			}
1574 			VM_OBJECT_WLOCK(sc->object);
1575 			sc->object->charge = IDX_TO_OFF(newpages);
1576 			sc->object->size = newpages;
1577 			VM_OBJECT_WUNLOCK(sc->object);
1578 		}
1579 		break;
1580 	default:
1581 		return (EOPNOTSUPP);
1582 	}
1583 
1584 	sc->mediasize = mdr->md_mediasize;
1585 	g_topology_lock();
1586 	g_resize_provider(sc->pp, sc->mediasize);
1587 	g_topology_unlock();
1588 	return (0);
1589 }
1590 
1591 static int
1592 mdcreate_swap(struct md_s *sc, struct md_req *mdr, struct thread *td)
1593 {
1594 	vm_ooffset_t npage;
1595 	int error;
1596 
1597 	/*
1598 	 * Range check.  Disallow negative sizes and sizes not being
1599 	 * multiple of page size.
1600 	 */
1601 	if (sc->mediasize <= 0 || (sc->mediasize % PAGE_SIZE) != 0)
1602 		return (EDOM);
1603 
1604 	/*
1605 	 * Allocate an OBJT_SWAP object.
1606 	 *
1607 	 * Note the truncation.
1608 	 */
1609 
1610 	if ((mdr->md_options & MD_VERIFY) != 0)
1611 		return (EINVAL);
1612 	npage = mdr->md_mediasize / PAGE_SIZE;
1613 	if (mdr->md_fwsectors != 0)
1614 		sc->fwsectors = mdr->md_fwsectors;
1615 	if (mdr->md_fwheads != 0)
1616 		sc->fwheads = mdr->md_fwheads;
1617 	sc->object = vm_pager_allocate(OBJT_SWAP, NULL, PAGE_SIZE * npage,
1618 	    VM_PROT_DEFAULT, 0, td->td_ucred);
1619 	if (sc->object == NULL)
1620 		return (ENOMEM);
1621 	sc->flags = mdr->md_options & (MD_FORCE | MD_RESERVE);
1622 	if (mdr->md_options & MD_RESERVE) {
1623 		if (swap_pager_reserve(sc->object, 0, npage) < 0) {
1624 			error = EDOM;
1625 			goto finish;
1626 		}
1627 	}
1628 	error = mdsetcred(sc, td->td_ucred);
1629  finish:
1630 	if (error != 0) {
1631 		vm_object_deallocate(sc->object);
1632 		sc->object = NULL;
1633 	}
1634 	return (error);
1635 }
1636 
1637 static int
1638 mdcreate_null(struct md_s *sc, struct md_req *mdr, struct thread *td)
1639 {
1640 
1641 	/*
1642 	 * Range check.  Disallow negative sizes and sizes not being
1643 	 * multiple of page size.
1644 	 */
1645 	if (sc->mediasize <= 0 || (sc->mediasize % PAGE_SIZE) != 0)
1646 		return (EDOM);
1647 
1648 	return (0);
1649 }
1650 
1651 static int
1652 kern_mdattach_locked(struct thread *td, struct md_req *mdr)
1653 {
1654 	struct md_s *sc;
1655 	unsigned sectsize;
1656 	int error, i;
1657 
1658 	sx_assert(&md_sx, SA_XLOCKED);
1659 
1660 	switch (mdr->md_type) {
1661 	case MD_MALLOC:
1662 	case MD_PRELOAD:
1663 	case MD_VNODE:
1664 	case MD_SWAP:
1665 	case MD_NULL:
1666 		break;
1667 	default:
1668 		return (EINVAL);
1669 	}
1670 	if (mdr->md_sectorsize == 0)
1671 		sectsize = DEV_BSIZE;
1672 	else
1673 		sectsize = mdr->md_sectorsize;
1674 	if (sectsize > MAXPHYS || mdr->md_mediasize < sectsize)
1675 		return (EINVAL);
1676 	if (mdr->md_options & MD_AUTOUNIT)
1677 		sc = mdnew(-1, &error, mdr->md_type);
1678 	else {
1679 		if (mdr->md_unit > INT_MAX)
1680 			return (EINVAL);
1681 		sc = mdnew(mdr->md_unit, &error, mdr->md_type);
1682 	}
1683 	if (sc == NULL)
1684 		return (error);
1685 	if (mdr->md_label != NULL)
1686 		error = copyinstr(mdr->md_label, sc->label,
1687 		    sizeof(sc->label), NULL);
1688 	if (error != 0)
1689 		goto err_after_new;
1690 	if (mdr->md_options & MD_AUTOUNIT)
1691 		mdr->md_unit = sc->unit;
1692 	sc->mediasize = mdr->md_mediasize;
1693 	sc->sectorsize = sectsize;
1694 	error = EDOOFUS;
1695 	switch (sc->type) {
1696 	case MD_MALLOC:
1697 		sc->start = mdstart_malloc;
1698 		error = mdcreate_malloc(sc, mdr);
1699 		break;
1700 	case MD_PRELOAD:
1701 		/*
1702 		 * We disallow attaching preloaded memory disks via
1703 		 * ioctl. Preloaded memory disks are automatically
1704 		 * attached in g_md_init().
1705 		 */
1706 		error = EOPNOTSUPP;
1707 		break;
1708 	case MD_VNODE:
1709 		sc->start = mdstart_vnode;
1710 		error = mdcreate_vnode(sc, mdr, td);
1711 		break;
1712 	case MD_SWAP:
1713 		sc->start = mdstart_swap;
1714 		error = mdcreate_swap(sc, mdr, td);
1715 		break;
1716 	case MD_NULL:
1717 		sc->start = mdstart_null;
1718 		error = mdcreate_null(sc, mdr, td);
1719 		break;
1720 	}
1721 err_after_new:
1722 	if (error != 0) {
1723 		mddestroy(sc, td);
1724 		return (error);
1725 	}
1726 
1727 	/* Prune off any residual fractional sector */
1728 	i = sc->mediasize % sc->sectorsize;
1729 	sc->mediasize -= i;
1730 
1731 	mdinit(sc);
1732 	return (0);
1733 }
1734 
1735 static int
1736 kern_mdattach(struct thread *td, struct md_req *mdr)
1737 {
1738 	int error;
1739 
1740 	sx_xlock(&md_sx);
1741 	error = kern_mdattach_locked(td, mdr);
1742 	sx_xunlock(&md_sx);
1743 	return (error);
1744 }
1745 
1746 static int
1747 kern_mddetach_locked(struct thread *td, struct md_req *mdr)
1748 {
1749 	struct md_s *sc;
1750 
1751 	sx_assert(&md_sx, SA_XLOCKED);
1752 
1753 	if (mdr->md_mediasize != 0 ||
1754 	    (mdr->md_options & ~MD_FORCE) != 0)
1755 		return (EINVAL);
1756 
1757 	sc = mdfind(mdr->md_unit);
1758 	if (sc == NULL)
1759 		return (ENOENT);
1760 	if (sc->opencount != 0 && !(sc->flags & MD_FORCE) &&
1761 	    !(mdr->md_options & MD_FORCE))
1762 		return (EBUSY);
1763 	return (mddestroy(sc, td));
1764 }
1765 
1766 static int
1767 kern_mddetach(struct thread *td, struct md_req *mdr)
1768 {
1769 	int error;
1770 
1771 	sx_xlock(&md_sx);
1772 	error = kern_mddetach_locked(td, mdr);
1773 	sx_xunlock(&md_sx);
1774 	return (error);
1775 }
1776 
1777 static int
1778 kern_mdresize_locked(struct md_req *mdr)
1779 {
1780 	struct md_s *sc;
1781 
1782 	sx_assert(&md_sx, SA_XLOCKED);
1783 
1784 	if ((mdr->md_options & ~(MD_FORCE | MD_RESERVE)) != 0)
1785 		return (EINVAL);
1786 
1787 	sc = mdfind(mdr->md_unit);
1788 	if (sc == NULL)
1789 		return (ENOENT);
1790 	if (mdr->md_mediasize < sc->sectorsize)
1791 		return (EINVAL);
1792 	if (mdr->md_mediasize < sc->mediasize &&
1793 	    !(sc->flags & MD_FORCE) &&
1794 	    !(mdr->md_options & MD_FORCE))
1795 		return (EBUSY);
1796 	return (mdresize(sc, mdr));
1797 }
1798 
1799 static int
1800 kern_mdresize(struct md_req *mdr)
1801 {
1802 	int error;
1803 
1804 	sx_xlock(&md_sx);
1805 	error = kern_mdresize_locked(mdr);
1806 	sx_xunlock(&md_sx);
1807 	return (error);
1808 }
1809 
1810 static int
1811 kern_mdquery_locked(struct md_req *mdr)
1812 {
1813 	struct md_s *sc;
1814 	int error;
1815 
1816 	sx_assert(&md_sx, SA_XLOCKED);
1817 
1818 	sc = mdfind(mdr->md_unit);
1819 	if (sc == NULL)
1820 		return (ENOENT);
1821 	mdr->md_type = sc->type;
1822 	mdr->md_options = sc->flags;
1823 	mdr->md_mediasize = sc->mediasize;
1824 	mdr->md_sectorsize = sc->sectorsize;
1825 	error = 0;
1826 	if (mdr->md_label != NULL) {
1827 		error = copyout(sc->label, mdr->md_label,
1828 		    strlen(sc->label) + 1);
1829 		if (error != 0)
1830 			return (error);
1831 	}
1832 	if (sc->type == MD_VNODE ||
1833 	    (sc->type == MD_PRELOAD && mdr->md_file != NULL))
1834 		error = copyout(sc->file, mdr->md_file,
1835 		    strlen(sc->file) + 1);
1836 	return (error);
1837 }
1838 
1839 static int
1840 kern_mdquery(struct md_req *mdr)
1841 {
1842 	int error;
1843 
1844 	sx_xlock(&md_sx);
1845 	error = kern_mdquery_locked(mdr);
1846 	sx_xunlock(&md_sx);
1847 	return (error);
1848 }
1849 
1850 static int
1851 kern_mdlist_locked(struct md_req *mdr)
1852 {
1853 	struct md_s *sc;
1854 	int i;
1855 
1856 	sx_assert(&md_sx, SA_XLOCKED);
1857 
1858 	/*
1859 	 * Write the number of md devices to mdr->md_units[0].
1860 	 * Write the unit number of the first (mdr->md_units_nitems - 2)
1861 	 * units to mdr->md_units[1::(mdr->md_units - 2)] and terminate the
1862 	 * list with -1.
1863 	 *
1864 	 * XXX: There is currently no mechanism to retrieve unit
1865 	 * numbers for more than (MDNPAD - 2) units.
1866 	 *
1867 	 * XXX: Due to the use of LIST_INSERT_HEAD in mdnew(), the
1868 	 * list of visible unit numbers not stable.
1869 	 */
1870 	i = 1;
1871 	LIST_FOREACH(sc, &md_softc_list, list) {
1872 		if (i < mdr->md_units_nitems - 1)
1873 			mdr->md_units[i] = sc->unit;
1874 		i++;
1875 	}
1876 	mdr->md_units[MIN(i, mdr->md_units_nitems - 1)] = -1;
1877 	mdr->md_units[0] = i - 1;
1878 	return (0);
1879 }
1880 
1881 static int
1882 kern_mdlist(struct md_req *mdr)
1883 {
1884 	int error;
1885 
1886 	sx_xlock(&md_sx);
1887 	error = kern_mdlist_locked(mdr);
1888 	sx_xunlock(&md_sx);
1889 	return (error);
1890 }
1891 
1892 /* Copy members that are not userspace pointers. */
1893 #define	MD_IOCTL2REQ(mdio, mdr) do {					\
1894 	(mdr)->md_unit = (mdio)->md_unit;				\
1895 	(mdr)->md_type = (mdio)->md_type;				\
1896 	(mdr)->md_mediasize = (mdio)->md_mediasize;			\
1897 	(mdr)->md_sectorsize = (mdio)->md_sectorsize;			\
1898 	(mdr)->md_options = (mdio)->md_options;				\
1899 	(mdr)->md_fwheads = (mdio)->md_fwheads;				\
1900 	(mdr)->md_fwsectors = (mdio)->md_fwsectors;			\
1901 	(mdr)->md_units = &(mdio)->md_pad[0];				\
1902 	(mdr)->md_units_nitems = nitems((mdio)->md_pad);		\
1903 } while(0)
1904 
1905 /* Copy members that might have been updated */
1906 #define MD_REQ2IOCTL(mdr, mdio) do {					\
1907 	(mdio)->md_unit = (mdr)->md_unit;				\
1908 	(mdio)->md_type = (mdr)->md_type;				\
1909 	(mdio)->md_mediasize = (mdr)->md_mediasize;			\
1910 	(mdio)->md_sectorsize = (mdr)->md_sectorsize;			\
1911 	(mdio)->md_options = (mdr)->md_options;				\
1912 	(mdio)->md_fwheads = (mdr)->md_fwheads;				\
1913 	(mdio)->md_fwsectors = (mdr)->md_fwsectors;			\
1914 } while(0)
1915 
1916 static int
1917 mdctlioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flags,
1918     struct thread *td)
1919 {
1920 	struct md_req mdr;
1921 	int error;
1922 
1923 	if (md_debug)
1924 		printf("mdctlioctl(%s %lx %p %x %p)\n",
1925 			devtoname(dev), cmd, addr, flags, td);
1926 
1927 	bzero(&mdr, sizeof(mdr));
1928 	switch (cmd) {
1929 	case MDIOCATTACH:
1930 	case MDIOCDETACH:
1931 	case MDIOCRESIZE:
1932 	case MDIOCQUERY:
1933 	case MDIOCLIST: {
1934 		struct md_ioctl *mdio = (struct md_ioctl *)addr;
1935 		if (mdio->md_version != MDIOVERSION)
1936 			return (EINVAL);
1937 		MD_IOCTL2REQ(mdio, &mdr);
1938 		mdr.md_file = mdio->md_file;
1939 		mdr.md_file_seg = UIO_USERSPACE;
1940 		/* If the file is adjacent to the md_ioctl it's in kernel. */
1941 		if ((void *)mdio->md_file == (void *)(mdio + 1))
1942 			mdr.md_file_seg = UIO_SYSSPACE;
1943 		mdr.md_label = mdio->md_label;
1944 		break;
1945 	}
1946 #ifdef COMPAT_FREEBSD32
1947 	case MDIOCATTACH_32:
1948 	case MDIOCDETACH_32:
1949 	case MDIOCRESIZE_32:
1950 	case MDIOCQUERY_32:
1951 	case MDIOCLIST_32: {
1952 		struct md_ioctl32 *mdio = (struct md_ioctl32 *)addr;
1953 		if (mdio->md_version != MDIOVERSION)
1954 			return (EINVAL);
1955 		MD_IOCTL2REQ(mdio, &mdr);
1956 		mdr.md_file = (void *)(uintptr_t)mdio->md_file;
1957 		mdr.md_file_seg = UIO_USERSPACE;
1958 		mdr.md_label = (void *)(uintptr_t)mdio->md_label;
1959 		break;
1960 	}
1961 #endif
1962 	default:
1963 		/* Fall through to handler switch. */
1964 		break;
1965 	}
1966 
1967 	error = 0;
1968 	switch (cmd) {
1969 	case MDIOCATTACH:
1970 #ifdef COMPAT_FREEBSD32
1971 	case MDIOCATTACH_32:
1972 #endif
1973 		error = kern_mdattach(td, &mdr);
1974 		break;
1975 	case MDIOCDETACH:
1976 #ifdef COMPAT_FREEBSD32
1977 	case MDIOCDETACH_32:
1978 #endif
1979 		error = kern_mddetach(td, &mdr);
1980 		break;
1981 	case MDIOCRESIZE:
1982 #ifdef COMPAT_FREEBSD32
1983 	case MDIOCRESIZE_32:
1984 #endif
1985 		error = kern_mdresize(&mdr);
1986 		break;
1987 	case MDIOCQUERY:
1988 #ifdef COMPAT_FREEBSD32
1989 	case MDIOCQUERY_32:
1990 #endif
1991 		error = kern_mdquery(&mdr);
1992 		break;
1993 	case MDIOCLIST:
1994 #ifdef COMPAT_FREEBSD32
1995 	case MDIOCLIST_32:
1996 #endif
1997 		error = kern_mdlist(&mdr);
1998 		break;
1999 	default:
2000 		error = ENOIOCTL;
2001 	}
2002 
2003 	switch (cmd) {
2004 	case MDIOCATTACH:
2005 	case MDIOCQUERY: {
2006 		struct md_ioctl *mdio = (struct md_ioctl *)addr;
2007 		MD_REQ2IOCTL(&mdr, mdio);
2008 		break;
2009 	}
2010 #ifdef COMPAT_FREEBSD32
2011 	case MDIOCATTACH_32:
2012 	case MDIOCQUERY_32: {
2013 		struct md_ioctl32 *mdio = (struct md_ioctl32 *)addr;
2014 		MD_REQ2IOCTL(&mdr, mdio);
2015 		break;
2016 	}
2017 #endif
2018 	default:
2019 		/* Other commands to not alter mdr. */
2020 		break;
2021 	}
2022 
2023 	return (error);
2024 }
2025 
2026 static void
2027 md_preloaded(u_char *image, size_t length, const char *name)
2028 {
2029 	struct md_s *sc;
2030 	int error;
2031 
2032 	sc = mdnew(-1, &error, MD_PRELOAD);
2033 	if (sc == NULL)
2034 		return;
2035 	sc->mediasize = length;
2036 	sc->sectorsize = DEV_BSIZE;
2037 	sc->pl_ptr = image;
2038 	sc->pl_len = length;
2039 	sc->start = mdstart_preload;
2040 	if (name != NULL)
2041 		strlcpy(sc->file, name, sizeof(sc->file));
2042 #ifdef MD_ROOT
2043 	if (sc->unit == 0) {
2044 #ifndef ROOTDEVNAME
2045 		rootdevnames[0] = MD_ROOT_FSTYPE ":/dev/md0";
2046 #endif
2047 #ifdef MD_ROOT_READONLY
2048 		sc->flags |= MD_READONLY;
2049 #endif
2050 	}
2051 #endif
2052 	mdinit(sc);
2053 	if (name != NULL) {
2054 		printf("%s%d: Preloaded image <%s> %zd bytes at %p\n",
2055 		    MD_NAME, sc->unit, name, length, image);
2056 	} else {
2057 		printf("%s%d: Embedded image %zd bytes at %p\n",
2058 		    MD_NAME, sc->unit, length, image);
2059 	}
2060 }
2061 
2062 static void
2063 g_md_init(struct g_class *mp __unused)
2064 {
2065 	caddr_t mod;
2066 	u_char *ptr, *name, *type;
2067 	unsigned len;
2068 	int i;
2069 
2070 	/* figure out log2(NINDIR) */
2071 	for (i = NINDIR, nshift = -1; i; nshift++)
2072 		i >>= 1;
2073 
2074 	mod = NULL;
2075 	sx_init(&md_sx, "MD config lock");
2076 	g_topology_unlock();
2077 	md_uh = new_unrhdr(0, INT_MAX, NULL);
2078 #ifdef MD_ROOT
2079 	if (mfs_root_size != 0) {
2080 		sx_xlock(&md_sx);
2081 #ifdef MD_ROOT_MEM
2082 		md_preloaded(mfs_root, mfs_root_size, NULL);
2083 #else
2084 		md_preloaded(__DEVOLATILE(u_char *, &mfs_root), mfs_root_size,
2085 		    NULL);
2086 #endif
2087 		sx_xunlock(&md_sx);
2088 	}
2089 #endif
2090 	/* XXX: are preload_* static or do they need Giant ? */
2091 	while ((mod = preload_search_next_name(mod)) != NULL) {
2092 		name = (char *)preload_search_info(mod, MODINFO_NAME);
2093 		if (name == NULL)
2094 			continue;
2095 		type = (char *)preload_search_info(mod, MODINFO_TYPE);
2096 		if (type == NULL)
2097 			continue;
2098 		if (strcmp(type, "md_image") && strcmp(type, "mfs_root"))
2099 			continue;
2100 		ptr = preload_fetch_addr(mod);
2101 		len = preload_fetch_size(mod);
2102 		if (ptr != NULL && len != 0) {
2103 			sx_xlock(&md_sx);
2104 			md_preloaded(ptr, len, name);
2105 			sx_xunlock(&md_sx);
2106 		}
2107 	}
2108 	md_vnode_pbuf_freecnt = nswbuf / 10;
2109 	status_dev = make_dev(&mdctl_cdevsw, INT_MAX, UID_ROOT, GID_WHEEL,
2110 	    0600, MDCTL_NAME);
2111 	g_topology_lock();
2112 }
2113 
2114 static void
2115 g_md_dumpconf(struct sbuf *sb, const char *indent, struct g_geom *gp,
2116     struct g_consumer *cp __unused, struct g_provider *pp)
2117 {
2118 	struct md_s *mp;
2119 	char *type;
2120 
2121 	mp = gp->softc;
2122 	if (mp == NULL)
2123 		return;
2124 
2125 	switch (mp->type) {
2126 	case MD_MALLOC:
2127 		type = "malloc";
2128 		break;
2129 	case MD_PRELOAD:
2130 		type = "preload";
2131 		break;
2132 	case MD_VNODE:
2133 		type = "vnode";
2134 		break;
2135 	case MD_SWAP:
2136 		type = "swap";
2137 		break;
2138 	case MD_NULL:
2139 		type = "null";
2140 		break;
2141 	default:
2142 		type = "unknown";
2143 		break;
2144 	}
2145 
2146 	if (pp != NULL) {
2147 		if (indent == NULL) {
2148 			sbuf_printf(sb, " u %d", mp->unit);
2149 			sbuf_printf(sb, " s %ju", (uintmax_t) mp->sectorsize);
2150 			sbuf_printf(sb, " f %ju", (uintmax_t) mp->fwheads);
2151 			sbuf_printf(sb, " fs %ju", (uintmax_t) mp->fwsectors);
2152 			sbuf_printf(sb, " l %ju", (uintmax_t) mp->mediasize);
2153 			sbuf_printf(sb, " t %s", type);
2154 			if ((mp->type == MD_VNODE && mp->vnode != NULL) ||
2155 			    (mp->type == MD_PRELOAD && mp->file[0] != '\0'))
2156 				sbuf_printf(sb, " file %s", mp->file);
2157 			sbuf_printf(sb, " label %s", mp->label);
2158 		} else {
2159 			sbuf_printf(sb, "%s<unit>%d</unit>\n", indent,
2160 			    mp->unit);
2161 			sbuf_printf(sb, "%s<sectorsize>%ju</sectorsize>\n",
2162 			    indent, (uintmax_t) mp->sectorsize);
2163 			sbuf_printf(sb, "%s<fwheads>%ju</fwheads>\n",
2164 			    indent, (uintmax_t) mp->fwheads);
2165 			sbuf_printf(sb, "%s<fwsectors>%ju</fwsectors>\n",
2166 			    indent, (uintmax_t) mp->fwsectors);
2167 			if (mp->ident[0] != '\0') {
2168 				sbuf_printf(sb, "%s<ident>", indent);
2169 				g_conf_printf_escaped(sb, "%s", mp->ident);
2170 				sbuf_printf(sb, "</ident>\n");
2171 			}
2172 			sbuf_printf(sb, "%s<length>%ju</length>\n",
2173 			    indent, (uintmax_t) mp->mediasize);
2174 			sbuf_printf(sb, "%s<compression>%s</compression>\n", indent,
2175 			    (mp->flags & MD_COMPRESS) == 0 ? "off": "on");
2176 			sbuf_printf(sb, "%s<access>%s</access>\n", indent,
2177 			    (mp->flags & MD_READONLY) == 0 ? "read-write":
2178 			    "read-only");
2179 			sbuf_printf(sb, "%s<type>%s</type>\n", indent,
2180 			    type);
2181 			if ((mp->type == MD_VNODE && mp->vnode != NULL) ||
2182 			    (mp->type == MD_PRELOAD && mp->file[0] != '\0')) {
2183 				sbuf_printf(sb, "%s<file>", indent);
2184 				g_conf_printf_escaped(sb, "%s", mp->file);
2185 				sbuf_printf(sb, "</file>\n");
2186 			}
2187 			sbuf_printf(sb, "%s<label>", indent);
2188 			g_conf_printf_escaped(sb, "%s", mp->label);
2189 			sbuf_printf(sb, "</label>\n");
2190 		}
2191 	}
2192 }
2193 
2194 static void
2195 g_md_fini(struct g_class *mp __unused)
2196 {
2197 
2198 	sx_destroy(&md_sx);
2199 	if (status_dev != NULL)
2200 		destroy_dev(status_dev);
2201 	delete_unrhdr(md_uh);
2202 }
2203