xref: /freebsd/sys/dev/md/md.c (revision bacb482d94518367b83ecea533ae07cc1b15da34)
1 /*
2  * ----------------------------------------------------------------------------
3  * "THE BEER-WARE LICENSE" (Revision 42):
4  * <phk@FreeBSD.ORG> wrote this file.  As long as you retain this notice you
5  * can do whatever you want with this stuff. If we meet some day, and you think
6  * this stuff is worth it, you can buy me a beer in return.   Poul-Henning Kamp
7  * ----------------------------------------------------------------------------
8  *
9  * $FreeBSD$
10  *
11  */
12 
13 /*
14  * The following functions are based in the vn(4) driver: mdstart_swap(),
15  * mdstart_vnode(), mdcreate_swap(), mdcreate_vnode() and mddestroy(),
16  * and as such under the following copyright:
17  *
18  * Copyright (c) 1988 University of Utah.
19  * Copyright (c) 1990, 1993
20  *	The Regents of the University of California.  All rights reserved.
21  *
22  * This code is derived from software contributed to Berkeley by
23  * the Systems Programming Group of the University of Utah Computer
24  * Science Department.
25  *
26  * Redistribution and use in source and binary forms, with or without
27  * modification, are permitted provided that the following conditions
28  * are met:
29  * 1. Redistributions of source code must retain the above copyright
30  *    notice, this list of conditions and the following disclaimer.
31  * 2. Redistributions in binary form must reproduce the above copyright
32  *    notice, this list of conditions and the following disclaimer in the
33  *    documentation and/or other materials provided with the distribution.
34  * 4. Neither the name of the University nor the names of its contributors
35  *    may be used to endorse or promote products derived from this software
36  *    without specific prior written permission.
37  *
38  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
39  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
40  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
41  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
42  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
43  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
44  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
45  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
46  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
47  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
48  * SUCH DAMAGE.
49  *
50  * from: Utah Hdr: vn.c 1.13 94/04/02
51  *
52  *	from: @(#)vn.c	8.6 (Berkeley) 4/1/94
53  * From: src/sys/dev/vn/vn.c,v 1.122 2000/12/16 16:06:03
54  */
55 
56 #include "opt_geom.h"
57 #include "opt_md.h"
58 
59 #include <sys/param.h>
60 #include <sys/systm.h>
61 #include <sys/bio.h>
62 #include <sys/conf.h>
63 #include <sys/fcntl.h>
64 #include <sys/kernel.h>
65 #include <sys/kthread.h>
66 #include <sys/linker.h>
67 #include <sys/lock.h>
68 #include <sys/malloc.h>
69 #include <sys/mdioctl.h>
70 #include <sys/mutex.h>
71 #include <sys/namei.h>
72 #include <sys/proc.h>
73 #include <sys/queue.h>
74 #include <sys/sf_buf.h>
75 #include <sys/sysctl.h>
76 #include <sys/vnode.h>
77 
78 #include <geom/geom.h>
79 
80 #include <vm/vm.h>
81 #include <vm/vm_object.h>
82 #include <vm/vm_page.h>
83 #include <vm/vm_pager.h>
84 #include <vm/swap_pager.h>
85 #include <vm/uma.h>
86 
87 #define MD_MODVER 1
88 
89 #define MD_SHUTDOWN 0x10000	/* Tell worker thread to terminate. */
90 
91 #ifndef MD_NSECT
92 #define MD_NSECT (10000 * 2)
93 #endif
94 
95 static MALLOC_DEFINE(M_MD, "MD disk", "Memory Disk");
96 static MALLOC_DEFINE(M_MDSECT, "MD sectors", "Memory Disk Sectors");
97 
98 static int md_debug;
99 SYSCTL_INT(_debug, OID_AUTO, mddebug, CTLFLAG_RW, &md_debug, 0, "");
100 
101 #if defined(MD_ROOT) && defined(MD_ROOT_SIZE)
102 /* Image gets put here: */
103 static u_char mfs_root[MD_ROOT_SIZE*1024] = "MFS Filesystem goes here";
104 static u_char end_mfs_root[] __unused = "MFS Filesystem had better STOP here";
105 #endif
106 
107 static g_init_t g_md_init;
108 static g_fini_t g_md_fini;
109 static g_start_t g_md_start;
110 static g_access_t g_md_access;
111 
112 static int	mdunits;
113 static struct cdev *status_dev = 0;
114 
115 static d_ioctl_t mdctlioctl;
116 
117 static struct cdevsw mdctl_cdevsw = {
118 	.d_version =	D_VERSION,
119 	.d_flags =	D_NEEDGIANT,
120 	.d_ioctl =	mdctlioctl,
121 	.d_name =	MD_NAME,
122 };
123 
124 struct g_class g_md_class = {
125 	.name = "MD",
126 	.version = G_VERSION,
127 	.init = g_md_init,
128 	.fini = g_md_fini,
129 	.start = g_md_start,
130 	.access = g_md_access,
131 };
132 
133 DECLARE_GEOM_CLASS(g_md_class, g_md);
134 
135 
136 static LIST_HEAD(, md_s) md_softc_list = LIST_HEAD_INITIALIZER(&md_softc_list);
137 
138 #define NINDIR	(PAGE_SIZE / sizeof(uintptr_t))
139 #define NMASK	(NINDIR-1)
140 static int nshift;
141 
142 struct indir {
143 	uintptr_t	*array;
144 	u_int		total;
145 	u_int		used;
146 	u_int		shift;
147 };
148 
149 struct md_s {
150 	int unit;
151 	LIST_ENTRY(md_s) list;
152 	struct bio_queue_head bio_queue;
153 	struct mtx queue_mtx;
154 	struct cdev *dev;
155 	enum md_types type;
156 	off_t mediasize;
157 	unsigned sectorsize;
158 	unsigned opencount;
159 	unsigned fwheads;
160 	unsigned fwsectors;
161 	unsigned flags;
162 	char name[20];
163 	struct proc *procp;
164 	struct g_geom *gp;
165 	struct g_provider *pp;
166 
167 	/* MD_MALLOC related fields */
168 	struct indir *indir;
169 	uma_zone_t uma;
170 
171 	/* MD_PRELOAD related fields */
172 	u_char *pl_ptr;
173 	size_t pl_len;
174 
175 	/* MD_VNODE related fields */
176 	struct vnode *vnode;
177 	struct ucred *cred;
178 
179 	/* MD_SWAP related fields */
180 	vm_object_t object;
181 };
182 
183 static int mddestroy(struct md_s *sc, struct thread *td);
184 
185 static struct indir *
186 new_indir(u_int shift)
187 {
188 	struct indir *ip;
189 
190 	ip = malloc(sizeof *ip, M_MD, M_NOWAIT | M_ZERO);
191 	if (ip == NULL)
192 		return (NULL);
193 	ip->array = malloc(sizeof(uintptr_t) * NINDIR,
194 	    M_MDSECT, M_NOWAIT | M_ZERO);
195 	if (ip->array == NULL) {
196 		free(ip, M_MD);
197 		return (NULL);
198 	}
199 	ip->total = NINDIR;
200 	ip->shift = shift;
201 	return (ip);
202 }
203 
204 static void
205 del_indir(struct indir *ip)
206 {
207 
208 	free(ip->array, M_MDSECT);
209 	free(ip, M_MD);
210 }
211 
212 static void
213 destroy_indir(struct md_s *sc, struct indir *ip)
214 {
215 	int i;
216 
217 	for (i = 0; i < NINDIR; i++) {
218 		if (!ip->array[i])
219 			continue;
220 		if (ip->shift)
221 			destroy_indir(sc, (struct indir*)(ip->array[i]));
222 		else if (ip->array[i] > 255)
223 			uma_zfree(sc->uma, (void *)(ip->array[i]));
224 	}
225 	del_indir(ip);
226 }
227 
228 /*
229  * This function does the math and alloctes the top level "indir" structure
230  * for a device of "size" sectors.
231  */
232 
233 static struct indir *
234 dimension(off_t size)
235 {
236 	off_t rcnt;
237 	struct indir *ip;
238 	int i, layer;
239 
240 	rcnt = size;
241 	layer = 0;
242 	while (rcnt > NINDIR) {
243 		rcnt /= NINDIR;
244 		layer++;
245 	}
246 	/* figure out log2(NINDIR) */
247 	for (i = NINDIR, nshift = -1; i; nshift++)
248 		i >>= 1;
249 
250 	/*
251 	 * XXX: the top layer is probably not fully populated, so we allocate
252 	 * too much space for ip->array in here.
253 	 */
254 	ip = malloc(sizeof *ip, M_MD, M_WAITOK | M_ZERO);
255 	ip->array = malloc(sizeof(uintptr_t) * NINDIR,
256 	    M_MDSECT, M_WAITOK | M_ZERO);
257 	ip->total = NINDIR;
258 	ip->shift = layer * nshift;
259 	return (ip);
260 }
261 
262 /*
263  * Read a given sector
264  */
265 
266 static uintptr_t
267 s_read(struct indir *ip, off_t offset)
268 {
269 	struct indir *cip;
270 	int idx;
271 	uintptr_t up;
272 
273 	if (md_debug > 1)
274 		printf("s_read(%jd)\n", (intmax_t)offset);
275 	up = 0;
276 	for (cip = ip; cip != NULL;) {
277 		if (cip->shift) {
278 			idx = (offset >> cip->shift) & NMASK;
279 			up = cip->array[idx];
280 			cip = (struct indir *)up;
281 			continue;
282 		}
283 		idx = offset & NMASK;
284 		return (cip->array[idx]);
285 	}
286 	return (0);
287 }
288 
289 /*
290  * Write a given sector, prune the tree if the value is 0
291  */
292 
293 static int
294 s_write(struct indir *ip, off_t offset, uintptr_t ptr)
295 {
296 	struct indir *cip, *lip[10];
297 	int idx, li;
298 	uintptr_t up;
299 
300 	if (md_debug > 1)
301 		printf("s_write(%jd, %p)\n", (intmax_t)offset, (void *)ptr);
302 	up = 0;
303 	li = 0;
304 	cip = ip;
305 	for (;;) {
306 		lip[li++] = cip;
307 		if (cip->shift) {
308 			idx = (offset >> cip->shift) & NMASK;
309 			up = cip->array[idx];
310 			if (up != 0) {
311 				cip = (struct indir *)up;
312 				continue;
313 			}
314 			/* Allocate branch */
315 			cip->array[idx] =
316 			    (uintptr_t)new_indir(cip->shift - nshift);
317 			if (cip->array[idx] == 0)
318 				return (ENOSPC);
319 			cip->used++;
320 			up = cip->array[idx];
321 			cip = (struct indir *)up;
322 			continue;
323 		}
324 		/* leafnode */
325 		idx = offset & NMASK;
326 		up = cip->array[idx];
327 		if (up != 0)
328 			cip->used--;
329 		cip->array[idx] = ptr;
330 		if (ptr != 0)
331 			cip->used++;
332 		break;
333 	}
334 	if (cip->used != 0 || li == 1)
335 		return (0);
336 	li--;
337 	while (cip->used == 0 && cip != ip) {
338 		li--;
339 		idx = (offset >> lip[li]->shift) & NMASK;
340 		up = lip[li]->array[idx];
341 		KASSERT(up == (uintptr_t)cip, ("md screwed up"));
342 		del_indir(cip);
343 		lip[li]->array[idx] = 0;
344 		lip[li]->used--;
345 		cip = lip[li];
346 	}
347 	return (0);
348 }
349 
350 
351 static int
352 g_md_access(struct g_provider *pp, int r, int w, int e)
353 {
354 	struct md_s *sc;
355 
356 	sc = pp->geom->softc;
357 	if (sc == NULL)
358 		return (ENXIO);
359 	r += pp->acr;
360 	w += pp->acw;
361 	e += pp->ace;
362 	if ((pp->acr + pp->acw + pp->ace) == 0 && (r + w + e) > 0) {
363 		sc->opencount = 1;
364 	} else if ((pp->acr + pp->acw + pp->ace) > 0 && (r + w + e) == 0) {
365 		sc->opencount = 0;
366 	}
367 	return (0);
368 }
369 
370 static void
371 g_md_start(struct bio *bp)
372 {
373 	struct md_s *sc;
374 
375 	sc = bp->bio_to->geom->softc;
376 	mtx_lock(&sc->queue_mtx);
377 	bioq_disksort(&sc->bio_queue, bp);
378 	mtx_unlock(&sc->queue_mtx);
379 	wakeup(sc);
380 }
381 
382 
383 
384 static int
385 mdstart_malloc(struct md_s *sc, struct bio *bp)
386 {
387 	int i, error;
388 	u_char *dst;
389 	off_t secno, nsec, uc;
390 	uintptr_t sp, osp;
391 
392 	nsec = bp->bio_length / sc->sectorsize;
393 	secno = bp->bio_offset / sc->sectorsize;
394 	dst = bp->bio_data;
395 	error = 0;
396 	while (nsec--) {
397 		osp = s_read(sc->indir, secno);
398 		if (bp->bio_cmd == BIO_DELETE) {
399 			if (osp != 0)
400 				error = s_write(sc->indir, secno, 0);
401 		} else if (bp->bio_cmd == BIO_READ) {
402 			if (osp == 0)
403 				bzero(dst, sc->sectorsize);
404 			else if (osp <= 255)
405 				for (i = 0; i < sc->sectorsize; i++)
406 					dst[i] = osp;
407 			else
408 				bcopy((void *)osp, dst, sc->sectorsize);
409 			osp = 0;
410 		} else if (bp->bio_cmd == BIO_WRITE) {
411 			if (sc->flags & MD_COMPRESS) {
412 				uc = dst[0];
413 				for (i = 1; i < sc->sectorsize; i++)
414 					if (dst[i] != uc)
415 						break;
416 			} else {
417 				i = 0;
418 				uc = 0;
419 			}
420 			if (i == sc->sectorsize) {
421 				if (osp != uc)
422 					error = s_write(sc->indir, secno, uc);
423 			} else {
424 				if (osp <= 255) {
425 					sp = (uintptr_t)uma_zalloc(sc->uma,
426 					    M_NOWAIT);
427 					if (sp == 0) {
428 						error = ENOSPC;
429 						break;
430 					}
431 					bcopy(dst, (void *)sp, sc->sectorsize);
432 					error = s_write(sc->indir, secno, sp);
433 				} else {
434 					bcopy(dst, (void *)osp, sc->sectorsize);
435 					osp = 0;
436 				}
437 			}
438 		} else {
439 			error = EOPNOTSUPP;
440 		}
441 		if (osp > 255)
442 			uma_zfree(sc->uma, (void*)osp);
443 		if (error)
444 			break;
445 		secno++;
446 		dst += sc->sectorsize;
447 	}
448 	bp->bio_resid = 0;
449 	return (error);
450 }
451 
452 static int
453 mdstart_preload(struct md_s *sc, struct bio *bp)
454 {
455 
456 	switch (bp->bio_cmd) {
457 	case BIO_READ:
458 		bcopy(sc->pl_ptr + bp->bio_offset, bp->bio_data,
459 		    bp->bio_length);
460 		break;
461 	case BIO_WRITE:
462 		bcopy(bp->bio_data, sc->pl_ptr + bp->bio_offset,
463 		    bp->bio_length);
464 		break;
465 	}
466 	bp->bio_resid = 0;
467 	return (0);
468 }
469 
470 static int
471 mdstart_vnode(struct md_s *sc, struct bio *bp)
472 {
473 	int error;
474 	struct uio auio;
475 	struct iovec aiov;
476 	struct mount *mp;
477 
478 	/*
479 	 * VNODE I/O
480 	 *
481 	 * If an error occurs, we set BIO_ERROR but we do not set
482 	 * B_INVAL because (for a write anyway), the buffer is
483 	 * still valid.
484 	 */
485 
486 	bzero(&auio, sizeof(auio));
487 
488 	aiov.iov_base = bp->bio_data;
489 	aiov.iov_len = bp->bio_length;
490 	auio.uio_iov = &aiov;
491 	auio.uio_iovcnt = 1;
492 	auio.uio_offset = (vm_ooffset_t)bp->bio_offset;
493 	auio.uio_segflg = UIO_SYSSPACE;
494 	if(bp->bio_cmd == BIO_READ)
495 		auio.uio_rw = UIO_READ;
496 	else if(bp->bio_cmd == BIO_WRITE)
497 		auio.uio_rw = UIO_WRITE;
498 	else
499 		panic("wrong BIO_OP in mdstart_vnode");
500 	auio.uio_resid = bp->bio_length;
501 	auio.uio_td = curthread;
502 	/*
503 	 * When reading set IO_DIRECT to try to avoid double-caching
504 	 * the data.  When writing IO_DIRECT is not optimal.
505 	 */
506 	if (bp->bio_cmd == BIO_READ) {
507 		vn_lock(sc->vnode, LK_EXCLUSIVE | LK_RETRY, curthread);
508 		error = VOP_READ(sc->vnode, &auio, IO_DIRECT, sc->cred);
509 		VOP_UNLOCK(sc->vnode, 0, curthread);
510 	} else {
511 		(void) vn_start_write(sc->vnode, &mp, V_WAIT);
512 		vn_lock(sc->vnode, LK_EXCLUSIVE | LK_RETRY, curthread);
513 		error = VOP_WRITE(sc->vnode, &auio,
514 		    sc->flags & MD_ASYNC ? 0 : IO_SYNC, sc->cred);
515 		VOP_UNLOCK(sc->vnode, 0, curthread);
516 		vn_finished_write(mp);
517 	}
518 	bp->bio_resid = auio.uio_resid;
519 	return (error);
520 }
521 
522 static int
523 mdstart_swap(struct md_s *sc, struct bio *bp)
524 {
525 	struct sf_buf *sf;
526 	int rv, offs, len, lastend;
527 	vm_pindex_t i, lastp;
528 	vm_page_t m;
529 	u_char *p;
530 
531 	p = bp->bio_data;
532 
533 	/*
534 	 * offs is the ofset at whih to start operating on the
535 	 * next (ie, first) page.  lastp is the last page on
536 	 * which we're going to operate.  lastend is the ending
537 	 * position within that last page (ie, PAGE_SIZE if
538 	 * we're operating on complete aligned pages).
539 	 */
540 	offs = bp->bio_offset % PAGE_SIZE;
541 	lastp = (bp->bio_offset + bp->bio_length - 1) / PAGE_SIZE;
542 	lastend = (bp->bio_offset + bp->bio_length - 1) % PAGE_SIZE + 1;
543 
544 	VM_OBJECT_LOCK(sc->object);
545 	vm_object_pip_add(sc->object, 1);
546 	for (i = bp->bio_offset / PAGE_SIZE; i <= lastp; i++) {
547 		len = ((i == lastp) ? lastend : PAGE_SIZE) - offs;
548 
549 		m = vm_page_grab(sc->object, i,
550 		    VM_ALLOC_NORMAL|VM_ALLOC_RETRY);
551 		VM_OBJECT_UNLOCK(sc->object);
552 		sf = sf_buf_alloc(m, 0);
553 		VM_OBJECT_LOCK(sc->object);
554 		if (bp->bio_cmd == BIO_READ) {
555 			if (m->valid != VM_PAGE_BITS_ALL)
556 				rv = vm_pager_get_pages(sc->object, &m, 1, 0);
557 			bcopy((void *)(sf_buf_kva(sf) + offs), p, len);
558 		} else if (bp->bio_cmd == BIO_WRITE) {
559 			if (len != PAGE_SIZE && m->valid != VM_PAGE_BITS_ALL)
560 				rv = vm_pager_get_pages(sc->object, &m, 1, 0);
561 			bcopy(p, (void *)(sf_buf_kva(sf) + offs), len);
562 			m->valid = VM_PAGE_BITS_ALL;
563 #if 0
564 		} else if (bp->bio_cmd == BIO_DELETE) {
565 			if (len != PAGE_SIZE && m->valid != VM_PAGE_BITS_ALL)
566 				rv = vm_pager_get_pages(sc->object, &m, 1, 0);
567 			bzero((void *)(sf_buf_kva(sf) + offs), len);
568 			vm_page_dirty(m);
569 			m->valid = VM_PAGE_BITS_ALL;
570 #endif
571 		}
572 		sf_buf_free(sf);
573 		vm_page_lock_queues();
574 		vm_page_wakeup(m);
575 		vm_page_activate(m);
576 		if (bp->bio_cmd == BIO_WRITE)
577 			vm_page_dirty(m);
578 		vm_page_unlock_queues();
579 
580 		/* Actions on further pages start at offset 0 */
581 		p += PAGE_SIZE - offs;
582 		offs = 0;
583 #if 0
584 if (bootverbose || bp->bio_offset / PAGE_SIZE < 17)
585 printf("wire_count %d busy %d flags %x hold_count %d act_count %d queue %d valid %d dirty %d @ %d\n",
586     m->wire_count, m->busy,
587     m->flags, m->hold_count, m->act_count, m->queue, m->valid, m->dirty, i);
588 #endif
589 	}
590 	vm_object_pip_subtract(sc->object, 1);
591 	vm_object_set_writeable_dirty(sc->object);
592 	VM_OBJECT_UNLOCK(sc->object);
593 	return (0);
594 }
595 
596 static void
597 md_kthread(void *arg)
598 {
599 	struct md_s *sc;
600 	struct bio *bp;
601 	int error, hasgiant;
602 
603 	sc = arg;
604 	curthread->td_base_pri = PRIBIO;
605 
606 	switch (sc->type) {
607 	case MD_VNODE:
608 		mtx_lock(&Giant);
609 		hasgiant = 1;
610 		break;
611 	case MD_MALLOC:
612 	case MD_PRELOAD:
613 	case MD_SWAP:
614 	default:
615 		hasgiant = 0;
616 		break;
617 	}
618 
619 	for (;;) {
620 		mtx_lock(&sc->queue_mtx);
621 		bp = bioq_takefirst(&sc->bio_queue);
622 		if (!bp) {
623 			if (sc->flags & MD_SHUTDOWN) {
624 				mtx_unlock(&sc->queue_mtx);
625 				sc->procp = NULL;
626 				wakeup(&sc->procp);
627 				if (hasgiant)
628 					mtx_unlock(&Giant);
629 				kthread_exit(0);
630 			}
631 			msleep(sc, &sc->queue_mtx, PRIBIO | PDROP, "mdwait", 0);
632 			continue;
633 		}
634 		mtx_unlock(&sc->queue_mtx);
635 		if (bp->bio_cmd == BIO_GETATTR) {
636 			if (sc->fwsectors && sc->fwheads &&
637 			    (g_handleattr_int(bp, "GEOM::fwsectors",
638 			    sc->fwsectors) ||
639 			    g_handleattr_int(bp, "GEOM::fwheads",
640 			    sc->fwheads)))
641 				error = -1;
642 			else
643 				error = EOPNOTSUPP;
644 		} else {
645 			switch (sc->type) {
646 			case MD_MALLOC:
647 				error = mdstart_malloc(sc, bp);
648 				break;
649 			case MD_PRELOAD:
650 				error = mdstart_preload(sc, bp);
651 				break;
652 			case MD_VNODE:
653 				error = mdstart_vnode(sc, bp);
654 				break;
655 			case MD_SWAP:
656 				error = mdstart_swap(sc, bp);
657 				break;
658 			default:
659 				panic("Impossible md(type)");
660 				break;
661 			}
662 		}
663 
664 		if (error != -1) {
665 			bp->bio_completed = bp->bio_length;
666 			g_io_deliver(bp, error);
667 		}
668 	}
669 }
670 
671 static struct md_s *
672 mdfind(int unit)
673 {
674 	struct md_s *sc;
675 
676 	/* XXX: LOCK(unique unit numbers) */
677 	LIST_FOREACH(sc, &md_softc_list, list) {
678 		if (sc->unit == unit)
679 			break;
680 	}
681 	/* XXX: UNLOCK(unique unit numbers) */
682 	return (sc);
683 }
684 
685 static struct md_s *
686 mdnew(int unit)
687 {
688 	struct md_s *sc;
689 	int error, max = -1;
690 
691 	/* XXX: LOCK(unique unit numbers) */
692 	LIST_FOREACH(sc, &md_softc_list, list) {
693 		if (sc->unit == unit) {
694 			/* XXX: UNLOCK(unique unit numbers) */
695 			return (NULL);
696 		}
697 		if (sc->unit > max)
698 			max = sc->unit;
699 	}
700 	if (unit == -1)
701 		unit = max + 1;
702 	sc = (struct md_s *)malloc(sizeof *sc, M_MD, M_WAITOK | M_ZERO);
703 	sc->unit = unit;
704 	bioq_init(&sc->bio_queue);
705 	mtx_init(&sc->queue_mtx, "md bio queue", NULL, MTX_DEF);
706 	sprintf(sc->name, "md%d", unit);
707 	error = kthread_create(md_kthread, sc, &sc->procp, 0, 0,"%s", sc->name);
708 	if (error) {
709 		free(sc, M_MD);
710 		return (NULL);
711 	}
712 	LIST_INSERT_HEAD(&md_softc_list, sc, list);
713 	/* XXX: UNLOCK(unique unit numbers) */
714 	return (sc);
715 }
716 
717 static void
718 mdinit(struct md_s *sc)
719 {
720 
721 	struct g_geom *gp;
722 	struct g_provider *pp;
723 
724 	DROP_GIANT();
725 	g_topology_lock();
726 	gp = g_new_geomf(&g_md_class, "md%d", sc->unit);
727 	gp->softc = sc;
728 	pp = g_new_providerf(gp, "md%d", sc->unit);
729 	pp->mediasize = sc->mediasize;
730 	pp->sectorsize = sc->sectorsize;
731 	sc->gp = gp;
732 	sc->pp = pp;
733 	g_error_provider(pp, 0);
734 	g_topology_unlock();
735 	if (sc->type != MD_PRELOAD)
736 		g_waitidle();
737 	PICKUP_GIANT();
738 }
739 
740 /*
741  * XXX: we should check that the range they feed us is mapped.
742  * XXX: we should implement read-only.
743  */
744 
745 static int
746 mdcreate_preload(struct md_s *sc, struct md_ioctl *mdio)
747 {
748 
749 	if (mdio->md_options & ~(MD_AUTOUNIT | MD_FORCE))
750 		return (EINVAL);
751 	sc->flags = mdio->md_options & MD_FORCE;
752 	/* Cast to pointer size, then to pointer to avoid warning */
753 	sc->pl_ptr = (u_char *)(uintptr_t)mdio->md_base;
754 	sc->pl_len = (size_t)sc->mediasize;
755 	return (0);
756 }
757 
758 
759 static int
760 mdcreate_malloc(struct md_s *sc, struct md_ioctl *mdio)
761 {
762 	uintptr_t sp;
763 	int error;
764 	off_t u;
765 
766 	error = 0;
767 	if (mdio->md_options & ~(MD_AUTOUNIT | MD_COMPRESS | MD_RESERVE))
768 		return (EINVAL);
769 	if (mdio->md_sectorsize != 0 && !powerof2(mdio->md_sectorsize))
770 		return (EINVAL);
771 	/* Compression doesn't make sense if we have reserved space */
772 	if (mdio->md_options & MD_RESERVE)
773 		mdio->md_options &= ~MD_COMPRESS;
774 	if (mdio->md_fwsectors != 0)
775 		sc->fwsectors = mdio->md_fwsectors;
776 	if (mdio->md_fwheads != 0)
777 		sc->fwheads = mdio->md_fwheads;
778 	sc->flags = mdio->md_options & (MD_COMPRESS | MD_FORCE);
779 	sc->indir = dimension(sc->mediasize / sc->sectorsize);
780 	sc->uma = uma_zcreate(sc->name, sc->sectorsize, NULL, NULL, NULL, NULL,
781 	    0x1ff, 0);
782 	if (mdio->md_options & MD_RESERVE) {
783 		off_t nsectors;
784 
785 		nsectors = sc->mediasize / sc->sectorsize;
786 		for (u = 0; u < nsectors; u++) {
787 			sp = (uintptr_t)uma_zalloc(sc->uma, M_NOWAIT | M_ZERO);
788 			if (sp != 0)
789 				error = s_write(sc->indir, u, sp);
790 			else
791 				error = ENOMEM;
792 			if (error != 0)
793 				break;
794 		}
795 	}
796 	if (error != 0)
797 		uma_zdestroy(sc->uma);
798 	return (error);
799 }
800 
801 
802 static int
803 mdsetcred(struct md_s *sc, struct ucred *cred)
804 {
805 	char *tmpbuf;
806 	int error = 0;
807 
808 	/*
809 	 * Set credits in our softc
810 	 */
811 
812 	if (sc->cred)
813 		crfree(sc->cred);
814 	sc->cred = crhold(cred);
815 
816 	/*
817 	 * Horrible kludge to establish credentials for NFS  XXX.
818 	 */
819 
820 	if (sc->vnode) {
821 		struct uio auio;
822 		struct iovec aiov;
823 
824 		tmpbuf = malloc(sc->sectorsize, M_TEMP, M_WAITOK);
825 		bzero(&auio, sizeof(auio));
826 
827 		aiov.iov_base = tmpbuf;
828 		aiov.iov_len = sc->sectorsize;
829 		auio.uio_iov = &aiov;
830 		auio.uio_iovcnt = 1;
831 		auio.uio_offset = 0;
832 		auio.uio_rw = UIO_READ;
833 		auio.uio_segflg = UIO_SYSSPACE;
834 		auio.uio_resid = aiov.iov_len;
835 		vn_lock(sc->vnode, LK_EXCLUSIVE | LK_RETRY, curthread);
836 		error = VOP_READ(sc->vnode, &auio, 0, sc->cred);
837 		VOP_UNLOCK(sc->vnode, 0, curthread);
838 		free(tmpbuf, M_TEMP);
839 	}
840 	return (error);
841 }
842 
843 static int
844 mdcreate_vnode(struct md_s *sc, struct md_ioctl *mdio, struct thread *td)
845 {
846 	struct vattr vattr;
847 	struct nameidata nd;
848 	int error, flags;
849 
850 	flags = FREAD|FWRITE;
851 	NDINIT(&nd, LOOKUP, FOLLOW, UIO_USERSPACE, mdio->md_file, td);
852 	error = vn_open(&nd, &flags, 0, -1);
853 	if (error) {
854 		NDFREE(&nd, NDF_ONLY_PNBUF);
855 		if (error != EACCES && error != EPERM && error != EROFS)
856 			return (error);
857 		flags &= ~FWRITE;
858 		NDINIT(&nd, LOOKUP, FOLLOW, UIO_USERSPACE, mdio->md_file, td);
859 		error = vn_open(&nd, &flags, 0, -1);
860 	}
861 	NDFREE(&nd, NDF_ONLY_PNBUF);
862 	if (error)
863 		return (error);
864 	if (nd.ni_vp->v_type != VREG ||
865 	    (error = VOP_GETATTR(nd.ni_vp, &vattr, td->td_ucred, td))) {
866 		VOP_UNLOCK(nd.ni_vp, 0, td);
867 		(void)vn_close(nd.ni_vp, flags, td->td_ucred, td);
868 		return (error ? error : EINVAL);
869 	}
870 	VOP_UNLOCK(nd.ni_vp, 0, td);
871 
872 	if (mdio->md_fwsectors != 0)
873 		sc->fwsectors = mdio->md_fwsectors;
874 	if (mdio->md_fwheads != 0)
875 		sc->fwheads = mdio->md_fwheads;
876 	sc->flags = mdio->md_options & (MD_FORCE | MD_ASYNC);
877 	if (!(flags & FWRITE))
878 		sc->flags |= MD_READONLY;
879 	sc->vnode = nd.ni_vp;
880 
881 	error = mdsetcred(sc, td->td_ucred);
882 	if (error != 0) {
883 		(void)vn_close(nd.ni_vp, flags, td->td_ucred, td);
884 		return (error);
885 	}
886 	return (0);
887 }
888 
889 static void
890 md_zapit(void *p, int cancel)
891 {
892 	if (cancel)
893 		return;
894 	g_wither_geom(p, ENXIO);
895 }
896 
897 static int
898 mddestroy(struct md_s *sc, struct thread *td)
899 {
900 
901 	GIANT_REQUIRED;
902 
903 	mtx_destroy(&sc->queue_mtx);
904 	if (sc->gp) {
905 		sc->gp->softc = NULL;
906 		g_waitfor_event(md_zapit, sc->gp, M_WAITOK, sc->gp, NULL);
907 		sc->gp = NULL;
908 		sc->pp = NULL;
909 	}
910 	sc->flags |= MD_SHUTDOWN;
911 	wakeup(sc);
912 	while (sc->procp != NULL)
913 		tsleep(&sc->procp, PRIBIO, "mddestroy", hz / 10);
914 	if (sc->vnode != NULL)
915 		(void)vn_close(sc->vnode, sc->flags & MD_READONLY ?
916 		    FREAD : (FREAD|FWRITE), sc->cred, td);
917 	if (sc->cred != NULL)
918 		crfree(sc->cred);
919 	if (sc->object != NULL) {
920 		vm_object_deallocate(sc->object);
921 	}
922 	if (sc->indir)
923 		destroy_indir(sc, sc->indir);
924 	if (sc->uma)
925 		uma_zdestroy(sc->uma);
926 
927 	/* XXX: LOCK(unique unit numbers) */
928 	LIST_REMOVE(sc, list);
929 	/* XXX: UNLOCK(unique unit numbers) */
930 	free(sc, M_MD);
931 	return (0);
932 }
933 
934 static int
935 mdcreate_swap(struct md_s *sc, struct md_ioctl *mdio, struct thread *td)
936 {
937 	vm_ooffset_t npage;
938 	int error;
939 
940 	GIANT_REQUIRED;
941 
942 	/*
943 	 * Range check.  Disallow negative sizes or any size less then the
944 	 * size of a page.  Then round to a page.
945 	 */
946 	if (sc->mediasize == 0 || (sc->mediasize % PAGE_SIZE) != 0)
947 		return (EDOM);
948 
949 	/*
950 	 * Allocate an OBJT_SWAP object.
951 	 *
952 	 * Note the truncation.
953 	 */
954 
955 	npage = mdio->md_mediasize / PAGE_SIZE;
956 	if (mdio->md_fwsectors != 0)
957 		sc->fwsectors = mdio->md_fwsectors;
958 	if (mdio->md_fwheads != 0)
959 		sc->fwheads = mdio->md_fwheads;
960 	sc->object = vm_pager_allocate(OBJT_SWAP, NULL, PAGE_SIZE * npage,
961 	    VM_PROT_DEFAULT, 0);
962 	sc->flags = mdio->md_options & MD_FORCE;
963 	if (mdio->md_options & MD_RESERVE) {
964 		if (swap_pager_reserve(sc->object, 0, npage) < 0) {
965 			vm_object_deallocate(sc->object);
966 			sc->object = NULL;
967 			return (EDOM);
968 		}
969 	}
970 	error = mdsetcred(sc, td->td_ucred);
971 	if (error) {
972 		vm_object_deallocate(sc->object);
973 		sc->object = NULL;
974 	}
975 	return (error);
976 }
977 
978 static int
979 mddetach(int unit, struct thread *td)
980 {
981 	struct md_s *sc;
982 
983 	sc = mdfind(unit);
984 	if (sc == NULL)
985 		return (ENOENT);
986 	if (sc->opencount != 0 && !(sc->flags & MD_FORCE))
987 		return (EBUSY);
988 	switch(sc->type) {
989 	case MD_VNODE:
990 	case MD_SWAP:
991 	case MD_MALLOC:
992 	case MD_PRELOAD:
993 		return (mddestroy(sc, td));
994 	default:
995 		return (EOPNOTSUPP);
996 	}
997 }
998 
999 static int
1000 mdctlioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flags, struct thread *td)
1001 {
1002 	struct md_ioctl *mdio;
1003 	struct md_s *sc;
1004 	int error, i;
1005 
1006 	if (md_debug)
1007 		printf("mdctlioctl(%s %lx %p %x %p)\n",
1008 			devtoname(dev), cmd, addr, flags, td);
1009 
1010 	/*
1011 	 * We assert the version number in the individual ioctl
1012 	 * handlers instead of out here because (a) it is possible we
1013 	 * may add another ioctl in the future which doesn't read an
1014 	 * mdio, and (b) the correct return value for an unknown ioctl
1015 	 * is ENOIOCTL, not EINVAL.
1016 	 */
1017 	mdio = (struct md_ioctl *)addr;
1018 	switch (cmd) {
1019 	case MDIOCATTACH:
1020 		if (mdio->md_version != MDIOVERSION)
1021 			return (EINVAL);
1022 		switch (mdio->md_type) {
1023 		case MD_MALLOC:
1024 		case MD_PRELOAD:
1025 		case MD_VNODE:
1026 		case MD_SWAP:
1027 			break;
1028 		default:
1029 			return (EINVAL);
1030 		}
1031 		if (mdio->md_options & MD_AUTOUNIT) {
1032 			sc = mdnew(-1);
1033 			mdio->md_unit = sc->unit;
1034 		} else {
1035 			sc = mdnew(mdio->md_unit);
1036 			if (sc == NULL)
1037 				return (EBUSY);
1038 		}
1039 		sc->type = mdio->md_type;
1040 		sc->mediasize = mdio->md_mediasize;
1041 		if (mdio->md_sectorsize == 0)
1042 			sc->sectorsize = DEV_BSIZE;
1043 		else
1044 			sc->sectorsize = mdio->md_sectorsize;
1045 		error = EDOOFUS;
1046 		switch (sc->type) {
1047 		case MD_MALLOC:
1048 			error = mdcreate_malloc(sc, mdio);
1049 			break;
1050 		case MD_PRELOAD:
1051 			error = mdcreate_preload(sc, mdio);
1052 			break;
1053 		case MD_VNODE:
1054 			error = mdcreate_vnode(sc, mdio, td);
1055 			break;
1056 		case MD_SWAP:
1057 			error = mdcreate_swap(sc, mdio, td);
1058 			break;
1059 		}
1060 		if (error != 0) {
1061 			mddestroy(sc, td);
1062 			return (error);
1063 		}
1064 		mdinit(sc);
1065 		return (0);
1066 	case MDIOCDETACH:
1067 		if (mdio->md_version != MDIOVERSION)
1068 			return (EINVAL);
1069 		if (mdio->md_file != NULL || mdio->md_mediasize != 0 ||
1070 		    mdio->md_options != 0)
1071 			return (EINVAL);
1072 		return (mddetach(mdio->md_unit, td));
1073 	case MDIOCQUERY:
1074 		if (mdio->md_version != MDIOVERSION)
1075 			return (EINVAL);
1076 		sc = mdfind(mdio->md_unit);
1077 		if (sc == NULL)
1078 			return (ENOENT);
1079 		mdio->md_type = sc->type;
1080 		mdio->md_options = sc->flags;
1081 		mdio->md_mediasize = sc->mediasize;
1082 		mdio->md_sectorsize = sc->sectorsize;
1083 		if (sc->type == MD_VNODE) {
1084 			/* XXX fill this in */
1085 			mdio->md_file = NULL;
1086 		}
1087 		return (0);
1088 	case MDIOCLIST:
1089 		i = 1;
1090 		LIST_FOREACH(sc, &md_softc_list, list) {
1091 			if (i == MDNPAD - 1)
1092 				mdio->md_pad[i] = -1;
1093 			else
1094 				mdio->md_pad[i++] = sc->unit;
1095 		}
1096 		mdio->md_pad[0] = i - 1;
1097 		return (0);
1098 	default:
1099 		return (ENOIOCTL);
1100 	};
1101 	return (ENOIOCTL);
1102 }
1103 
1104 static void
1105 md_preloaded(u_char *image, size_t length)
1106 {
1107 	struct md_s *sc;
1108 
1109 	sc = mdnew(-1);
1110 	if (sc == NULL)
1111 		return;
1112 	sc->type = MD_PRELOAD;
1113 	sc->mediasize = length;
1114 	sc->sectorsize = DEV_BSIZE;
1115 	sc->pl_ptr = image;
1116 	sc->pl_len = length;
1117 #ifdef MD_ROOT
1118 	if (sc->unit == 0)
1119 		rootdevnames[0] = "ufs:/dev/md0";
1120 #endif
1121 	mdinit(sc);
1122 }
1123 
1124 static void
1125 g_md_init(struct g_class *mp __unused)
1126 {
1127 
1128 	caddr_t mod;
1129 	caddr_t c;
1130 	u_char *ptr, *name, *type;
1131 	unsigned len;
1132 
1133 	mod = NULL;
1134 	g_topology_unlock();
1135 #ifdef MD_ROOT_SIZE
1136 	md_preloaded(mfs_root, MD_ROOT_SIZE*1024);
1137 #endif
1138 	while ((mod = preload_search_next_name(mod)) != NULL) {
1139 		name = (char *)preload_search_info(mod, MODINFO_NAME);
1140 		type = (char *)preload_search_info(mod, MODINFO_TYPE);
1141 		if (name == NULL)
1142 			continue;
1143 		if (type == NULL)
1144 			continue;
1145 		if (strcmp(type, "md_image") && strcmp(type, "mfs_root"))
1146 			continue;
1147 		c = preload_search_info(mod, MODINFO_ADDR);
1148 		ptr = *(u_char **)c;
1149 		c = preload_search_info(mod, MODINFO_SIZE);
1150 		len = *(size_t *)c;
1151 		printf("%s%d: Preloaded image <%s> %d bytes at %p\n",
1152 		    MD_NAME, mdunits, name, len, ptr);
1153 		md_preloaded(ptr, len);
1154 	}
1155 	status_dev = make_dev(&mdctl_cdevsw, 0xffff00ff, UID_ROOT, GID_WHEEL,
1156 	    0600, MDCTL_NAME);
1157 	g_topology_lock();
1158 }
1159 
1160 static void
1161 g_md_fini(struct g_class *mp __unused)
1162 {
1163 
1164 	if (status_dev != NULL)
1165 		destroy_dev(status_dev);
1166 }
1167