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