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