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