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