xref: /freebsd/sys/dev/md/md.c (revision cec50dea12481dc578c0805c887ab2097e1c06c5)
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 	unsigned nsect;
157 	unsigned opencount;
158 	unsigned secsize;
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 	unsigned 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 	unsigned npage;
182 };
183 
184 static int mddestroy(struct md_s *sc, struct thread *td);
185 
186 static struct indir *
187 new_indir(u_int shift)
188 {
189 	struct indir *ip;
190 
191 	ip = malloc(sizeof *ip, M_MD, M_NOWAIT | M_ZERO);
192 	if (ip == NULL)
193 		return (NULL);
194 	ip->array = malloc(sizeof(uintptr_t) * NINDIR,
195 	    M_MDSECT, M_NOWAIT | M_ZERO);
196 	if (ip->array == NULL) {
197 		free(ip, M_MD);
198 		return (NULL);
199 	}
200 	ip->total = NINDIR;
201 	ip->shift = shift;
202 	return (ip);
203 }
204 
205 static void
206 del_indir(struct indir *ip)
207 {
208 
209 	free(ip->array, M_MDSECT);
210 	free(ip, M_MD);
211 }
212 
213 static void
214 destroy_indir(struct md_s *sc, struct indir *ip)
215 {
216 	int i;
217 
218 	for (i = 0; i < NINDIR; i++) {
219 		if (!ip->array[i])
220 			continue;
221 		if (ip->shift)
222 			destroy_indir(sc, (struct indir*)(ip->array[i]));
223 		else if (ip->array[i] > 255)
224 			uma_zfree(sc->uma, (void *)(ip->array[i]));
225 	}
226 	del_indir(ip);
227 }
228 
229 /*
230  * This function does the math and alloctes the top level "indir" structure
231  * for a device of "size" sectors.
232  */
233 
234 static struct indir *
235 dimension(off_t size)
236 {
237 	off_t rcnt;
238 	struct indir *ip;
239 	int i, layer;
240 
241 	rcnt = size;
242 	layer = 0;
243 	while (rcnt > NINDIR) {
244 		rcnt /= NINDIR;
245 		layer++;
246 	}
247 	/* figure out log2(NINDIR) */
248 	for (i = NINDIR, nshift = -1; i; nshift++)
249 		i >>= 1;
250 
251 	/*
252 	 * XXX: the top layer is probably not fully populated, so we allocate
253 	 * too much space for ip->array in here.
254 	 */
255 	ip = malloc(sizeof *ip, M_MD, M_WAITOK | M_ZERO);
256 	ip->array = malloc(sizeof(uintptr_t) * NINDIR,
257 	    M_MDSECT, M_WAITOK | M_ZERO);
258 	ip->total = NINDIR;
259 	ip->shift = layer * nshift;
260 	return (ip);
261 }
262 
263 /*
264  * Read a given sector
265  */
266 
267 static uintptr_t
268 s_read(struct indir *ip, off_t offset)
269 {
270 	struct indir *cip;
271 	int idx;
272 	uintptr_t up;
273 
274 	if (md_debug > 1)
275 		printf("s_read(%jd)\n", (intmax_t)offset);
276 	up = 0;
277 	for (cip = ip; cip != NULL;) {
278 		if (cip->shift) {
279 			idx = (offset >> cip->shift) & NMASK;
280 			up = cip->array[idx];
281 			cip = (struct indir *)up;
282 			continue;
283 		}
284 		idx = offset & NMASK;
285 		return (cip->array[idx]);
286 	}
287 	return (0);
288 }
289 
290 /*
291  * Write a given sector, prune the tree if the value is 0
292  */
293 
294 static int
295 s_write(struct indir *ip, off_t offset, uintptr_t ptr)
296 {
297 	struct indir *cip, *lip[10];
298 	int idx, li;
299 	uintptr_t up;
300 
301 	if (md_debug > 1)
302 		printf("s_write(%jd, %p)\n", (intmax_t)offset, (void *)ptr);
303 	up = 0;
304 	li = 0;
305 	cip = ip;
306 	for (;;) {
307 		lip[li++] = cip;
308 		if (cip->shift) {
309 			idx = (offset >> cip->shift) & NMASK;
310 			up = cip->array[idx];
311 			if (up != 0) {
312 				cip = (struct indir *)up;
313 				continue;
314 			}
315 			/* Allocate branch */
316 			cip->array[idx] =
317 			    (uintptr_t)new_indir(cip->shift - nshift);
318 			if (cip->array[idx] == 0)
319 				return (ENOSPC);
320 			cip->used++;
321 			up = cip->array[idx];
322 			cip = (struct indir *)up;
323 			continue;
324 		}
325 		/* leafnode */
326 		idx = offset & NMASK;
327 		up = cip->array[idx];
328 		if (up != 0)
329 			cip->used--;
330 		cip->array[idx] = ptr;
331 		if (ptr != 0)
332 			cip->used++;
333 		break;
334 	}
335 	if (cip->used != 0 || li == 1)
336 		return (0);
337 	li--;
338 	while (cip->used == 0 && cip != ip) {
339 		li--;
340 		idx = (offset >> lip[li]->shift) & NMASK;
341 		up = lip[li]->array[idx];
342 		KASSERT(up == (uintptr_t)cip, ("md screwed up"));
343 		del_indir(cip);
344 		lip[li]->array[idx] = 0;
345 		lip[li]->used--;
346 		cip = lip[li];
347 	}
348 	return (0);
349 }
350 
351 
352 static int
353 g_md_access(struct g_provider *pp, int r, int w, int e)
354 {
355 	struct md_s *sc;
356 
357 	sc = pp->geom->softc;
358 	if (sc == NULL)
359 		return (ENXIO);
360 	r += pp->acr;
361 	w += pp->acw;
362 	e += pp->ace;
363 	if ((pp->acr + pp->acw + pp->ace) == 0 && (r + w + e) > 0) {
364 		sc->opencount = 1;
365 	} else if ((pp->acr + pp->acw + pp->ace) > 0 && (r + w + e) == 0) {
366 		sc->opencount = 0;
367 	}
368 	return (0);
369 }
370 
371 static void
372 g_md_start(struct bio *bp)
373 {
374 	struct md_s *sc;
375 
376 	sc = bp->bio_to->geom->softc;
377 	mtx_lock(&sc->queue_mtx);
378 	bioq_disksort(&sc->bio_queue, bp);
379 	wakeup(sc);
380 	mtx_unlock(&sc->queue_mtx);
381 }
382 
383 
384 
385 static int
386 mdstart_malloc(struct md_s *sc, struct bio *bp)
387 {
388 	int i, error;
389 	u_char *dst;
390 	unsigned secno, nsec, uc;
391 	uintptr_t sp, osp;
392 
393 	nsec = bp->bio_length / sc->secsize;
394 	secno = bp->bio_offset / sc->secsize;
395 	dst = bp->bio_data;
396 	error = 0;
397 	while (nsec--) {
398 		osp = s_read(sc->indir, secno);
399 		if (bp->bio_cmd == BIO_DELETE) {
400 			if (osp != 0)
401 				error = s_write(sc->indir, secno, 0);
402 		} else if (bp->bio_cmd == BIO_READ) {
403 			if (osp == 0)
404 				bzero(dst, sc->secsize);
405 			else if (osp <= 255)
406 				for (i = 0; i < sc->secsize; i++)
407 					dst[i] = osp;
408 			else
409 				bcopy((void *)osp, dst, sc->secsize);
410 			osp = 0;
411 		} else if (bp->bio_cmd == BIO_WRITE) {
412 			if (sc->flags & MD_COMPRESS) {
413 				uc = dst[0];
414 				for (i = 1; i < sc->secsize; i++)
415 					if (dst[i] != uc)
416 						break;
417 			} else {
418 				i = 0;
419 				uc = 0;
420 			}
421 			if (i == sc->secsize) {
422 				if (osp != uc)
423 					error = s_write(sc->indir, secno, uc);
424 			} else {
425 				if (osp <= 255) {
426 					sp = (uintptr_t) uma_zalloc(
427 					    sc->uma, M_NOWAIT);
428 					if (sp == 0) {
429 						error = ENOSPC;
430 						break;
431 					}
432 					bcopy(dst, (void *)sp, sc->secsize);
433 					error = s_write(sc->indir, secno, sp);
434 				} else {
435 					bcopy(dst, (void *)osp, sc->secsize);
436 					osp = 0;
437 				}
438 			}
439 		} else {
440 			error = EOPNOTSUPP;
441 		}
442 		if (osp > 255)
443 			uma_zfree(sc->uma, (void*)osp);
444 		if (error)
445 			break;
446 		secno++;
447 		dst += sc->secsize;
448 	}
449 	bp->bio_resid = 0;
450 	return (error);
451 }
452 
453 static int
454 mdstart_preload(struct md_s *sc, struct bio *bp)
455 {
456 
457 	switch (bp->bio_cmd) {
458 	case BIO_READ:
459 		bcopy(sc->pl_ptr + bp->bio_offset, bp->bio_data,
460 		    bp->bio_length);
461 		break;
462 	case BIO_WRITE:
463 		bcopy(bp->bio_data, sc->pl_ptr + bp->bio_offset,
464 		    bp->bio_length);
465 		break;
466 	}
467 	bp->bio_resid = 0;
468 	return (0);
469 }
470 
471 static int
472 mdstart_vnode(struct md_s *sc, struct bio *bp)
473 {
474 	int error;
475 	struct uio auio;
476 	struct iovec aiov;
477 	struct mount *mp;
478 
479 	/*
480 	 * VNODE I/O
481 	 *
482 	 * If an error occurs, we set BIO_ERROR but we do not set
483 	 * B_INVAL because (for a write anyway), the buffer is
484 	 * still valid.
485 	 */
486 
487 	bzero(&auio, sizeof(auio));
488 
489 	aiov.iov_base = bp->bio_data;
490 	aiov.iov_len = bp->bio_length;
491 	auio.uio_iov = &aiov;
492 	auio.uio_iovcnt = 1;
493 	auio.uio_offset = (vm_ooffset_t)bp->bio_offset;
494 	auio.uio_segflg = UIO_SYSSPACE;
495 	if(bp->bio_cmd == BIO_READ)
496 		auio.uio_rw = UIO_READ;
497 	else if(bp->bio_cmd == BIO_WRITE)
498 		auio.uio_rw = UIO_WRITE;
499 	else
500 		panic("wrong BIO_OP in mdstart_vnode");
501 	auio.uio_resid = bp->bio_length;
502 	auio.uio_td = curthread;
503 	/*
504 	 * When reading set IO_DIRECT to try to avoid double-caching
505 	 * the data.  When writing IO_DIRECT is not optimal.
506 	 */
507 	if (bp->bio_cmd == BIO_READ) {
508 		vn_lock(sc->vnode, LK_EXCLUSIVE | LK_RETRY, curthread);
509 		error = VOP_READ(sc->vnode, &auio, IO_DIRECT, sc->cred);
510 		VOP_UNLOCK(sc->vnode, 0, curthread);
511 	} else {
512 		(void) vn_start_write(sc->vnode, &mp, V_WAIT);
513 		vn_lock(sc->vnode, LK_EXCLUSIVE | LK_RETRY, curthread);
514 		error = VOP_WRITE(sc->vnode, &auio,
515 		    sc->flags & MD_ASYNC ? 0 : IO_SYNC, sc->cred);
516 		VOP_UNLOCK(sc->vnode, 0, curthread);
517 		vn_finished_write(mp);
518 	}
519 	bp->bio_resid = auio.uio_resid;
520 	return (error);
521 }
522 
523 static int
524 mdstart_swap(struct md_s *sc, struct bio *bp)
525 {
526 	struct sf_buf *sf;
527 	int rv, offs, len, lastend;
528 	vm_pindex_t i, lastp;
529 	vm_page_t m;
530 	u_char *p;
531 
532 	p = bp->bio_data;
533 
534 	/*
535 	 * offs is the ofset at whih to start operating on the
536 	 * next (ie, first) page.  lastp is the last page on
537 	 * which we're going to operate.  lastend is the ending
538 	 * position within that last page (ie, PAGE_SIZE if
539 	 * we're operating on complete aligned pages).
540 	 */
541 	offs = bp->bio_offset % PAGE_SIZE;
542 	lastp = (bp->bio_offset + bp->bio_length - 1) / PAGE_SIZE;
543 	lastend = (bp->bio_offset + bp->bio_length - 1) % PAGE_SIZE + 1;
544 
545 	VM_OBJECT_LOCK(sc->object);
546 	vm_object_pip_add(sc->object, 1);
547 	for (i = bp->bio_offset / PAGE_SIZE; i <= lastp; i++) {
548 		len = ((i == lastp) ? lastend : PAGE_SIZE) - offs;
549 
550 		m = vm_page_grab(sc->object, i,
551 		    VM_ALLOC_NORMAL|VM_ALLOC_RETRY);
552 		VM_OBJECT_UNLOCK(sc->object);
553 		sf = sf_buf_alloc(m, 0);
554 		VM_OBJECT_LOCK(sc->object);
555 		if (bp->bio_cmd == BIO_READ) {
556 			if (m->valid != VM_PAGE_BITS_ALL)
557 				rv = vm_pager_get_pages(sc->object, &m, 1, 0);
558 			bcopy((void *)(sf_buf_kva(sf) + offs), p, len);
559 		} else if (bp->bio_cmd == BIO_WRITE) {
560 			if (len != PAGE_SIZE && m->valid != VM_PAGE_BITS_ALL)
561 				rv = vm_pager_get_pages(sc->object, &m, 1, 0);
562 			bcopy(p, (void *)(sf_buf_kva(sf) + offs), len);
563 			m->valid = VM_PAGE_BITS_ALL;
564 #if 0
565 		} else if (bp->bio_cmd == BIO_DELETE) {
566 			if (len != PAGE_SIZE && m->valid != VM_PAGE_BITS_ALL)
567 				rv = vm_pager_get_pages(sc->object, &m, 1, 0);
568 			bzero((void *)(sf_buf_kva(sf) + offs), len);
569 			vm_page_dirty(m);
570 			m->valid = VM_PAGE_BITS_ALL;
571 #endif
572 		}
573 		sf_buf_free(sf);
574 		vm_page_lock_queues();
575 		vm_page_wakeup(m);
576 		vm_page_activate(m);
577 		if (bp->bio_cmd == BIO_WRITE)
578 			vm_page_dirty(m);
579 		vm_page_unlock_queues();
580 
581 		/* Actions on further pages start at offset 0 */
582 		p += PAGE_SIZE - offs;
583 		offs = 0;
584 #if 0
585 if (bootverbose || bp->bio_offset / PAGE_SIZE < 17)
586 printf("wire_count %d busy %d flags %x hold_count %d act_count %d queue %d valid %d dirty %d @ %d\n",
587     m->wire_count, m->busy,
588     m->flags, m->hold_count, m->act_count, m->queue, m->valid, m->dirty, i);
589 #endif
590 	}
591 	vm_object_pip_subtract(sc->object, 1);
592 	vm_object_set_writeable_dirty(sc->object);
593 	VM_OBJECT_UNLOCK(sc->object);
594 	return (0);
595 }
596 
597 static void
598 md_kthread(void *arg)
599 {
600 	struct md_s *sc;
601 	struct bio *bp;
602 	int error, hasgiant;
603 
604 	sc = arg;
605 	curthread->td_base_pri = PRIBIO;
606 
607 	switch (sc->type) {
608 	case MD_VNODE:
609 		mtx_lock(&Giant);
610 		hasgiant = 1;
611 		break;
612 	case MD_MALLOC:
613 	case MD_PRELOAD:
614 	case MD_SWAP:
615 	default:
616 		hasgiant = 0;
617 		break;
618 	}
619 
620 	for (;;) {
621 		mtx_lock(&sc->queue_mtx);
622 		bp = bioq_takefirst(&sc->bio_queue);
623 		if (!bp) {
624 			if (sc->flags & MD_SHUTDOWN) {
625 				mtx_unlock(&sc->queue_mtx);
626 				sc->procp = NULL;
627 				wakeup(&sc->procp);
628 				if (hasgiant)
629 					mtx_unlock(&Giant);
630 				kthread_exit(0);
631 			}
632 			msleep(sc, &sc->queue_mtx, PRIBIO | PDROP, "mdwait", 0);
633 			continue;
634 		}
635 		mtx_unlock(&sc->queue_mtx);
636 		if (bp->bio_cmd == BIO_GETATTR) {
637 			if (sc->fwsectors && sc->fwheads &&
638 			    (g_handleattr_int(bp, "GEOM::fwsectors",
639 			    sc->fwsectors) ||
640 			    g_handleattr_int(bp, "GEOM::fwheads",
641 			    sc->fwheads)))
642 				error = -1;
643 			else
644 				error = EOPNOTSUPP;
645 		} else {
646 			switch (sc->type) {
647 			case MD_MALLOC:
648 				error = mdstart_malloc(sc, bp);
649 				break;
650 			case MD_PRELOAD:
651 				error = mdstart_preload(sc, bp);
652 				break;
653 			case MD_VNODE:
654 				error = mdstart_vnode(sc, bp);
655 				break;
656 			case MD_SWAP:
657 				error = mdstart_swap(sc, bp);
658 				break;
659 			default:
660 				panic("Impossible md(type)");
661 				break;
662 			}
663 		}
664 
665 		if (error != -1) {
666 			bp->bio_completed = bp->bio_length;
667 			g_io_deliver(bp, error);
668 		}
669 	}
670 }
671 
672 static struct md_s *
673 mdfind(int unit)
674 {
675 	struct md_s *sc;
676 
677 	/* XXX: LOCK(unique unit numbers) */
678 	LIST_FOREACH(sc, &md_softc_list, list) {
679 		if (sc->unit == unit)
680 			break;
681 	}
682 	/* XXX: UNLOCK(unique unit numbers) */
683 	return (sc);
684 }
685 
686 static struct md_s *
687 mdnew(int unit)
688 {
689 	struct md_s *sc;
690 	int error, max = -1;
691 
692 	/* XXX: LOCK(unique unit numbers) */
693 	LIST_FOREACH(sc, &md_softc_list, list) {
694 		if (sc->unit == unit) {
695 			/* XXX: UNLOCK(unique unit numbers) */
696 			return (NULL);
697 		}
698 		if (sc->unit > max)
699 			max = sc->unit;
700 	}
701 	if (unit == -1)
702 		unit = max + 1;
703 	sc = (struct md_s *)malloc(sizeof *sc, M_MD, M_WAITOK | M_ZERO);
704 	sc->unit = unit;
705 	bioq_init(&sc->bio_queue);
706 	mtx_init(&sc->queue_mtx, "md bio queue", NULL, MTX_DEF);
707 	sprintf(sc->name, "md%d", unit);
708 	error = kthread_create(md_kthread, sc, &sc->procp, 0, 0,"%s", sc->name);
709 	if (error) {
710 		free(sc, M_MD);
711 		return (NULL);
712 	}
713 	LIST_INSERT_HEAD(&md_softc_list, sc, list);
714 	/* XXX: UNLOCK(unique unit numbers) */
715 	return (sc);
716 }
717 
718 static void
719 mdinit(struct md_s *sc)
720 {
721 
722 	struct g_geom *gp;
723 	struct g_provider *pp;
724 
725 	DROP_GIANT();
726 	g_topology_lock();
727 	gp = g_new_geomf(&g_md_class, "md%d", sc->unit);
728 	gp->softc = sc;
729 	pp = g_new_providerf(gp, "md%d", sc->unit);
730 	pp->mediasize = (off_t)sc->nsect * sc->secsize;
731 	pp->sectorsize = sc->secsize;
732 	sc->gp = gp;
733 	sc->pp = pp;
734 	g_error_provider(pp, 0);
735 	g_topology_unlock();
736 	if (sc->type != MD_PRELOAD)
737 		g_waitidle();
738 	PICKUP_GIANT();
739 }
740 
741 /*
742  * XXX: we should check that the range they feed us is mapped.
743  * XXX: we should implement read-only.
744  */
745 
746 static int
747 mdcreate_preload(struct md_ioctl *mdio)
748 {
749 	struct md_s *sc;
750 
751 	if (mdio->md_size == 0)
752 		return (EINVAL);
753 	if (mdio->md_options & ~(MD_AUTOUNIT))
754 		return (EINVAL);
755 	if (mdio->md_options & MD_AUTOUNIT) {
756 		sc = mdnew(-1);
757 		if (sc == NULL)
758 			return (ENOMEM);
759 		mdio->md_unit = sc->unit;
760 	} else {
761 		sc = mdnew(mdio->md_unit);
762 		if (sc == NULL)
763 			return (EBUSY);
764 	}
765 	sc->type = MD_PRELOAD;
766 	sc->secsize = DEV_BSIZE;
767 	sc->nsect = mdio->md_size;
768 	sc->flags = mdio->md_options & MD_FORCE;
769 	/* Cast to pointer size, then to pointer to avoid warning */
770 	sc->pl_ptr = (u_char *)(uintptr_t)mdio->md_base;
771 	sc->pl_len = (mdio->md_size << DEV_BSHIFT);
772 	mdinit(sc);
773 	return (0);
774 }
775 
776 
777 static int
778 mdcreate_malloc(struct md_ioctl *mdio)
779 {
780 	struct md_s *sc;
781 	off_t u;
782 	uintptr_t sp;
783 	int error;
784 
785 	error = 0;
786 	if (mdio->md_size == 0)
787 		return (EINVAL);
788 	if (mdio->md_options & ~(MD_AUTOUNIT | MD_COMPRESS | MD_RESERVE))
789 		return (EINVAL);
790 	if (mdio->md_secsize != 0 && !powerof2(mdio->md_secsize))
791 		return (EINVAL);
792 	/* Compression doesn't make sense if we have reserved space */
793 	if (mdio->md_options & MD_RESERVE)
794 		mdio->md_options &= ~MD_COMPRESS;
795 	if (mdio->md_options & MD_AUTOUNIT) {
796 		sc = mdnew(-1);
797 		if (sc == NULL)
798 			return (ENOMEM);
799 		mdio->md_unit = sc->unit;
800 	} else {
801 		sc = mdnew(mdio->md_unit);
802 		if (sc == NULL)
803 			return (EBUSY);
804 	}
805 	sc->type = MD_MALLOC;
806 	if (mdio->md_secsize != 0)
807 		sc->secsize = mdio->md_secsize;
808 	else
809 		sc->secsize = DEV_BSIZE;
810 	if (mdio->md_fwsectors != 0)
811 		sc->fwsectors = mdio->md_fwsectors;
812 	if (mdio->md_fwheads != 0)
813 		sc->fwheads = mdio->md_fwheads;
814 	sc->nsect = (mdio->md_size * DEV_BSIZE) / sc->secsize;
815 	sc->flags = mdio->md_options & (MD_COMPRESS | MD_FORCE);
816 	sc->indir = dimension(sc->nsect);
817 	sc->uma = uma_zcreate(sc->name, sc->secsize,
818 	    NULL, NULL, NULL, NULL, 0x1ff, 0);
819 	if (mdio->md_options & MD_RESERVE) {
820 		for (u = 0; u < sc->nsect; u++) {
821 			sp = (uintptr_t) uma_zalloc(sc->uma, M_NOWAIT | M_ZERO);
822 			if (sp != 0)
823 				error = s_write(sc->indir, u, sp);
824 			else
825 				error = ENOMEM;
826 			if (error)
827 				break;
828 		}
829 	}
830 	if (error)  {
831 		uma_zdestroy(sc->uma);
832 		mddestroy(sc, NULL);
833 		return (error);
834 	}
835 	mdinit(sc);
836 	if (!(mdio->md_options & MD_RESERVE))
837 		sc->pp->flags |= G_PF_CANDELETE;
838 	return (0);
839 }
840 
841 
842 static int
843 mdsetcred(struct md_s *sc, struct ucred *cred)
844 {
845 	char *tmpbuf;
846 	int error = 0;
847 
848 	/*
849 	 * Set credits in our softc
850 	 */
851 
852 	if (sc->cred)
853 		crfree(sc->cred);
854 	sc->cred = crhold(cred);
855 
856 	/*
857 	 * Horrible kludge to establish credentials for NFS  XXX.
858 	 */
859 
860 	if (sc->vnode) {
861 		struct uio auio;
862 		struct iovec aiov;
863 
864 		tmpbuf = malloc(sc->secsize, M_TEMP, M_WAITOK);
865 		bzero(&auio, sizeof(auio));
866 
867 		aiov.iov_base = tmpbuf;
868 		aiov.iov_len = sc->secsize;
869 		auio.uio_iov = &aiov;
870 		auio.uio_iovcnt = 1;
871 		auio.uio_offset = 0;
872 		auio.uio_rw = UIO_READ;
873 		auio.uio_segflg = UIO_SYSSPACE;
874 		auio.uio_resid = aiov.iov_len;
875 		vn_lock(sc->vnode, LK_EXCLUSIVE | LK_RETRY, curthread);
876 		error = VOP_READ(sc->vnode, &auio, 0, sc->cred);
877 		VOP_UNLOCK(sc->vnode, 0, curthread);
878 		free(tmpbuf, M_TEMP);
879 	}
880 	return (error);
881 }
882 
883 static int
884 mdcreate_vnode(struct md_ioctl *mdio, struct thread *td)
885 {
886 	struct md_s *sc;
887 	struct vattr vattr;
888 	struct nameidata nd;
889 	int error, flags;
890 
891 	flags = FREAD|FWRITE;
892 	NDINIT(&nd, LOOKUP, FOLLOW, UIO_USERSPACE, mdio->md_file, td);
893 	error = vn_open(&nd, &flags, 0, -1);
894 	if (error) {
895 		NDFREE(&nd, NDF_ONLY_PNBUF);
896 		if (error != EACCES && error != EPERM && error != EROFS)
897 			return (error);
898 		flags &= ~FWRITE;
899 		NDINIT(&nd, LOOKUP, FOLLOW, UIO_USERSPACE, mdio->md_file, td);
900 		error = vn_open(&nd, &flags, 0, -1);
901 	}
902 	NDFREE(&nd, NDF_ONLY_PNBUF);
903 	if (error)
904 		return (error);
905 	if (nd.ni_vp->v_type != VREG ||
906 	    (error = VOP_GETATTR(nd.ni_vp, &vattr, td->td_ucred, td))) {
907 		VOP_UNLOCK(nd.ni_vp, 0, td);
908 		(void) vn_close(nd.ni_vp, flags, td->td_ucred, td);
909 		return (error ? error : EINVAL);
910 	}
911 	VOP_UNLOCK(nd.ni_vp, 0, td);
912 
913 	if (mdio->md_options & MD_AUTOUNIT) {
914 		sc = mdnew(-1);
915 		mdio->md_unit = sc->unit;
916 	} else {
917 		sc = mdnew(mdio->md_unit);
918 	}
919 	if (sc == NULL) {
920 		(void) vn_close(nd.ni_vp, flags, td->td_ucred, td);
921 		return (EBUSY);
922 	}
923 
924 	if (mdio->md_fwsectors != 0)
925 		sc->fwsectors = mdio->md_fwsectors;
926 	if (mdio->md_fwheads != 0)
927 		sc->fwheads = mdio->md_fwheads;
928 	sc->type = MD_VNODE;
929 	sc->flags = mdio->md_options & (MD_FORCE | MD_ASYNC);
930 	if (!(flags & FWRITE))
931 		sc->flags |= MD_READONLY;
932 	sc->secsize = DEV_BSIZE;
933 	sc->vnode = nd.ni_vp;
934 
935 	/*
936 	 * If the size is specified, override the file attributes.
937 	 */
938 	if (mdio->md_size)
939 		sc->nsect = mdio->md_size;
940 	else
941 		sc->nsect = vattr.va_size / sc->secsize; /* XXX: round up ? */
942 	if (sc->nsect == 0) {
943 		(void) vn_close(nd.ni_vp, flags, td->td_ucred, td);
944 		mddestroy(sc, td);
945 		return (EINVAL);
946 	}
947 	error = mdsetcred(sc, td->td_ucred);
948 	if (error) {
949 		(void) vn_close(nd.ni_vp, flags, td->td_ucred, td);
950 		mddestroy(sc, td);
951 		return (error);
952 	}
953 	mdinit(sc);
954 	return (0);
955 }
956 
957 static void
958 md_zapit(void *p, int cancel)
959 {
960 	if (cancel)
961 		return;
962 	g_wither_geom(p, ENXIO);
963 }
964 
965 static int
966 mddestroy(struct md_s *sc, struct thread *td)
967 {
968 
969 	GIANT_REQUIRED;
970 
971 	mtx_destroy(&sc->queue_mtx);
972 	if (sc->gp) {
973 		sc->gp->softc = NULL;
974 		g_waitfor_event(md_zapit, sc->gp, M_WAITOK, sc->gp, NULL);
975 		sc->gp = NULL;
976 		sc->pp = NULL;
977 	}
978 	sc->flags |= MD_SHUTDOWN;
979 	wakeup(sc);
980 	while (sc->procp != NULL)
981 		tsleep(&sc->procp, PRIBIO, "mddestroy", hz / 10);
982 	if (sc->vnode != NULL)
983 		(void)vn_close(sc->vnode, sc->flags & MD_READONLY ?
984 		    FREAD : (FREAD|FWRITE), sc->cred, td);
985 	if (sc->cred != NULL)
986 		crfree(sc->cred);
987 	if (sc->object != NULL) {
988 		vm_object_deallocate(sc->object);
989 	}
990 	if (sc->indir)
991 		destroy_indir(sc, sc->indir);
992 	if (sc->uma)
993 		uma_zdestroy(sc->uma);
994 
995 	/* XXX: LOCK(unique unit numbers) */
996 	LIST_REMOVE(sc, list);
997 	/* XXX: UNLOCK(unique unit numbers) */
998 	free(sc, M_MD);
999 	return (0);
1000 }
1001 
1002 static int
1003 mdcreate_swap(struct md_ioctl *mdio, struct thread *td)
1004 {
1005 	int error;
1006 	struct md_s *sc;
1007 
1008 	GIANT_REQUIRED;
1009 
1010 	if (mdio->md_options & MD_AUTOUNIT) {
1011 		sc = mdnew(-1);
1012 		mdio->md_unit = sc->unit;
1013 	} else {
1014 		sc = mdnew(mdio->md_unit);
1015 	}
1016 	if (sc == NULL)
1017 		return (EBUSY);
1018 
1019 	sc->type = MD_SWAP;
1020 
1021 	/*
1022 	 * Range check.  Disallow negative sizes or any size less then the
1023 	 * size of a page.  Then round to a page.
1024 	 */
1025 
1026 	if (mdio->md_size == 0) {
1027 		mddestroy(sc, td);
1028 		return (EDOM);
1029 	}
1030 
1031 	/*
1032 	 * Allocate an OBJT_SWAP object.
1033 	 *
1034 	 * sc_nsect is in units of DEV_BSIZE.
1035 	 * sc_npage is in units of PAGE_SIZE.
1036 	 *
1037 	 * Note the truncation.
1038 	 */
1039 
1040 	sc->secsize = DEV_BSIZE;
1041 	sc->npage = mdio->md_size / (PAGE_SIZE / DEV_BSIZE);
1042 	sc->nsect = sc->npage * (PAGE_SIZE / DEV_BSIZE);
1043 	if (mdio->md_fwsectors != 0)
1044 		sc->fwsectors = mdio->md_fwsectors;
1045 	if (mdio->md_fwheads != 0)
1046 		sc->fwheads = mdio->md_fwheads;
1047 	sc->object = vm_pager_allocate(OBJT_SWAP, NULL, PAGE_SIZE *
1048 	    (vm_offset_t)sc->npage, VM_PROT_DEFAULT, 0);
1049 	sc->flags = mdio->md_options & MD_FORCE;
1050 	if (mdio->md_options & MD_RESERVE) {
1051 		if (swap_pager_reserve(sc->object, 0, sc->npage) < 0) {
1052 			vm_object_deallocate(sc->object);
1053 			sc->object = NULL;
1054 			mddestroy(sc, td);
1055 			return (EDOM);
1056 		}
1057 	}
1058 	error = mdsetcred(sc, td->td_ucred);
1059 	if (error) {
1060 		vm_object_deallocate(sc->object);
1061 		sc->object = NULL;
1062 		mddestroy(sc, td);
1063 		return (error);
1064 	}
1065 	mdinit(sc);
1066 	if (!(mdio->md_options & MD_RESERVE))
1067 		sc->pp->flags |= G_PF_CANDELETE;
1068 	return (0);
1069 }
1070 
1071 static int
1072 mddetach(int unit, struct thread *td)
1073 {
1074 	struct md_s *sc;
1075 
1076 	sc = mdfind(unit);
1077 	if (sc == NULL)
1078 		return (ENOENT);
1079 	if (sc->opencount != 0 && !(sc->flags & MD_FORCE))
1080 		return (EBUSY);
1081 	switch(sc->type) {
1082 	case MD_VNODE:
1083 	case MD_SWAP:
1084 	case MD_MALLOC:
1085 	case MD_PRELOAD:
1086 		return (mddestroy(sc, td));
1087 	default:
1088 		return (EOPNOTSUPP);
1089 	}
1090 }
1091 
1092 static int
1093 mdctlioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flags, struct thread *td)
1094 {
1095 	struct md_ioctl *mdio;
1096 	struct md_s *sc;
1097 	int i;
1098 
1099 	if (md_debug)
1100 		printf("mdctlioctl(%s %lx %p %x %p)\n",
1101 			devtoname(dev), cmd, addr, flags, td);
1102 
1103 	/*
1104 	 * We assert the version number in the individual ioctl
1105 	 * handlers instead of out here because (a) it is possible we
1106 	 * may add another ioctl in the future which doesn't read an
1107 	 * mdio, and (b) the correct return value for an unknown ioctl
1108 	 * is ENOIOCTL, not EINVAL.
1109 	 */
1110 	mdio = (struct md_ioctl *)addr;
1111 	switch (cmd) {
1112 	case MDIOCATTACH:
1113 		if (mdio->md_version != MDIOVERSION)
1114 			return (EINVAL);
1115 		switch (mdio->md_type) {
1116 		case MD_MALLOC:
1117 			return (mdcreate_malloc(mdio));
1118 		case MD_PRELOAD:
1119 			return (mdcreate_preload(mdio));
1120 		case MD_VNODE:
1121 			return (mdcreate_vnode(mdio, td));
1122 		case MD_SWAP:
1123 			return (mdcreate_swap(mdio, td));
1124 		default:
1125 			return (EINVAL);
1126 		}
1127 	case MDIOCDETACH:
1128 		if (mdio->md_version != MDIOVERSION)
1129 			return (EINVAL);
1130 		if (mdio->md_file != NULL || mdio->md_size != 0 ||
1131 		    mdio->md_options != 0)
1132 			return (EINVAL);
1133 		return (mddetach(mdio->md_unit, td));
1134 	case MDIOCQUERY:
1135 		if (mdio->md_version != MDIOVERSION)
1136 			return (EINVAL);
1137 		sc = mdfind(mdio->md_unit);
1138 		if (sc == NULL)
1139 			return (ENOENT);
1140 		mdio->md_type = sc->type;
1141 		mdio->md_options = sc->flags;
1142 		switch (sc->type) {
1143 		case MD_MALLOC:
1144 			mdio->md_size = sc->nsect;
1145 			break;
1146 		case MD_PRELOAD:
1147 			mdio->md_size = sc->nsect;
1148 			mdio->md_base = (uint64_t)(intptr_t)sc->pl_ptr;
1149 			break;
1150 		case MD_SWAP:
1151 			mdio->md_size = sc->nsect;
1152 			break;
1153 		case MD_VNODE:
1154 			mdio->md_size = sc->nsect;
1155 			/* XXX fill this in */
1156 			mdio->md_file = NULL;
1157 			break;
1158 		}
1159 		return (0);
1160 	case MDIOCLIST:
1161 		i = 1;
1162 		LIST_FOREACH(sc, &md_softc_list, list) {
1163 			if (i == MDNPAD - 1)
1164 				mdio->md_pad[i] = -1;
1165 			else
1166 				mdio->md_pad[i++] = sc->unit;
1167 		}
1168 		mdio->md_pad[0] = i - 1;
1169 		return (0);
1170 	default:
1171 		return (ENOIOCTL);
1172 	};
1173 	return (ENOIOCTL);
1174 }
1175 
1176 static void
1177 md_preloaded(u_char *image, unsigned length)
1178 {
1179 	struct md_s *sc;
1180 
1181 	sc = mdnew(-1);
1182 	if (sc == NULL)
1183 		return;
1184 	sc->type = MD_PRELOAD;
1185 	sc->secsize = DEV_BSIZE;
1186 	sc->nsect = length / DEV_BSIZE;
1187 	sc->pl_ptr = image;
1188 	sc->pl_len = length;
1189 #ifdef MD_ROOT
1190 	if (sc->unit == 0)
1191 		rootdevnames[0] = "ufs:/dev/md0";
1192 #endif
1193 	mdinit(sc);
1194 }
1195 
1196 static void
1197 g_md_init(struct g_class *mp __unused)
1198 {
1199 
1200 	caddr_t mod;
1201 	caddr_t c;
1202 	u_char *ptr, *name, *type;
1203 	unsigned len;
1204 
1205 	mod = NULL;
1206 	g_topology_unlock();
1207 #ifdef MD_ROOT_SIZE
1208 	md_preloaded(mfs_root, MD_ROOT_SIZE*1024);
1209 #endif
1210 	while ((mod = preload_search_next_name(mod)) != NULL) {
1211 		name = (char *)preload_search_info(mod, MODINFO_NAME);
1212 		type = (char *)preload_search_info(mod, MODINFO_TYPE);
1213 		if (name == NULL)
1214 			continue;
1215 		if (type == NULL)
1216 			continue;
1217 		if (strcmp(type, "md_image") && strcmp(type, "mfs_root"))
1218 			continue;
1219 		c = preload_search_info(mod, MODINFO_ADDR);
1220 		ptr = *(u_char **)c;
1221 		c = preload_search_info(mod, MODINFO_SIZE);
1222 		len = *(size_t *)c;
1223 		printf("%s%d: Preloaded image <%s> %d bytes at %p\n",
1224 		    MD_NAME, mdunits, name, len, ptr);
1225 		md_preloaded(ptr, len);
1226 	}
1227 	status_dev = make_dev(&mdctl_cdevsw, 0xffff00ff, UID_ROOT, GID_WHEEL,
1228 	    0600, MDCTL_NAME);
1229 	g_topology_lock();
1230 }
1231 
1232 static void
1233 g_md_fini(struct g_class *mp __unused)
1234 {
1235 
1236 	if (status_dev != NULL)
1237 		destroy_dev(status_dev);
1238 }
1239