xref: /freebsd/sys/dev/md/md.c (revision d086ded32300bc0f33fb1574d0bcfccfbc60881d)
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 };
345 
346 static int
347 g_md_access(struct g_provider *pp, int r, int w, int e)
348 {
349 	struct md_s *sc;
350 
351 	sc = pp->geom->softc;
352 	if (sc == NULL)
353 		return (ENXIO);
354 	r += pp->acr;
355 	w += pp->acw;
356 	e += pp->ace;
357 	if ((pp->acr + pp->acw + pp->ace) == 0 && (r + w + e) > 0) {
358 		sc->opencount = 1;
359 	} else if ((pp->acr + pp->acw + pp->ace) > 0 && (r + w + e) == 0) {
360 		sc->opencount = 0;
361 	}
362 	return (0);
363 }
364 
365 static void
366 g_md_start(struct bio *bp)
367 {
368 	struct md_s *sc;
369 
370 	sc = bp->bio_to->geom->softc;
371 
372 	bp->bio_blkno = bp->bio_offset >> DEV_BSHIFT;
373 	bp->bio_pblkno = bp->bio_offset / sc->secsize;
374 	bp->bio_bcount = bp->bio_length;
375 	mtx_lock(&sc->queue_mtx);
376 	bioq_disksort(&sc->bio_queue, bp);
377 	mtx_unlock(&sc->queue_mtx);
378 
379 	wakeup(sc);
380 }
381 
382 DECLARE_GEOM_CLASS(g_md_class, g_md);
383 
384 
385 static int
386 mdstart_malloc(struct md_s *sc, struct bio *bp)
387 {
388 	int i, error;
389 	u_char *dst;
390 	unsigned secno, nsec, uc;
391 	uintptr_t sp, osp;
392 
393 	nsec = bp->bio_bcount / sc->secsize;
394 	secno = bp->bio_pblkno;
395 	dst = bp->bio_data;
396 	error = 0;
397 	while (nsec--) {
398 		osp = s_read(sc->indir, secno);
399 		if (bp->bio_cmd == BIO_DELETE) {
400 			if (osp != 0)
401 				error = s_write(sc->indir, secno, 0);
402 		} else if (bp->bio_cmd == BIO_READ) {
403 			if (osp == 0)
404 				bzero(dst, sc->secsize);
405 			else if (osp <= 255)
406 				for (i = 0; i < sc->secsize; i++)
407 					dst[i] = osp;
408 			else
409 				bcopy((void *)osp, dst, sc->secsize);
410 			osp = 0;
411 		} else if (bp->bio_cmd == BIO_WRITE) {
412 			if (sc->flags & MD_COMPRESS) {
413 				uc = dst[0];
414 				for (i = 1; i < sc->secsize; i++)
415 					if (dst[i] != uc)
416 						break;
417 			} else {
418 				i = 0;
419 				uc = 0;
420 			}
421 			if (i == sc->secsize) {
422 				if (osp != uc)
423 					error = s_write(sc->indir, secno, uc);
424 			} else {
425 				if (osp <= 255) {
426 					sp = (uintptr_t) uma_zalloc(
427 					    sc->uma, M_NOWAIT);
428 					if (sp == 0) {
429 						error = ENOSPC;
430 						break;
431 					}
432 					bcopy(dst, (void *)sp, sc->secsize);
433 					error = s_write(sc->indir, secno, sp);
434 				} else {
435 					bcopy(dst, (void *)osp, sc->secsize);
436 					osp = 0;
437 				}
438 			}
439 		} else {
440 			error = EOPNOTSUPP;
441 		}
442 		if (osp > 255)
443 			uma_zfree(sc->uma, (void*)osp);
444 		if (error)
445 			break;
446 		secno++;
447 		dst += sc->secsize;
448 	}
449 	bp->bio_resid = 0;
450 	return (error);
451 }
452 
453 static int
454 mdstart_preload(struct md_s *sc, struct bio *bp)
455 {
456 
457 	if (bp->bio_cmd == BIO_DELETE) {
458 	} else if (bp->bio_cmd == BIO_READ) {
459 		bcopy(sc->pl_ptr + (bp->bio_pblkno << DEV_BSHIFT), bp->bio_data, bp->bio_bcount);
460 	} else {
461 		bcopy(bp->bio_data, sc->pl_ptr + (bp->bio_pblkno << DEV_BSHIFT), bp->bio_bcount);
462 	}
463 	bp->bio_resid = 0;
464 	return (0);
465 }
466 
467 static int
468 mdstart_vnode(struct md_s *sc, struct bio *bp)
469 {
470 	int error;
471 	struct uio auio;
472 	struct iovec aiov;
473 	struct mount *mp;
474 
475 	/*
476 	 * VNODE I/O
477 	 *
478 	 * If an error occurs, we set BIO_ERROR but we do not set
479 	 * B_INVAL because (for a write anyway), the buffer is
480 	 * still valid.
481 	 */
482 
483 	bzero(&auio, sizeof(auio));
484 
485 	aiov.iov_base = bp->bio_data;
486 	aiov.iov_len = bp->bio_bcount;
487 	auio.uio_iov = &aiov;
488 	auio.uio_iovcnt = 1;
489 	auio.uio_offset = (vm_ooffset_t)bp->bio_pblkno * sc->secsize;
490 	auio.uio_segflg = UIO_SYSSPACE;
491 	if(bp->bio_cmd == BIO_READ)
492 		auio.uio_rw = UIO_READ;
493 	else
494 		auio.uio_rw = UIO_WRITE;
495 	auio.uio_resid = bp->bio_bcount;
496 	auio.uio_td = curthread;
497 	/*
498 	 * When reading set IO_DIRECT to try to avoid double-caching
499 	 * the data.  When writing IO_DIRECT is not optimal.
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, 0, 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 void
903 md_zapit(void *p, int cancel)
904 {
905 	if (cancel)
906 		return;
907 	g_wither_geom(p, ENXIO);
908 }
909 
910 static int
911 mddestroy(struct md_s *sc, struct thread *td)
912 {
913 
914 	GIANT_REQUIRED;
915 
916 	mtx_destroy(&sc->queue_mtx);
917 	if (sc->gp) {
918 		sc->gp->softc = NULL;
919 		g_waitfor_event(md_zapit, sc->gp, M_WAITOK, sc->gp, NULL);
920 		sc->gp = NULL;
921 		sc->pp = NULL;
922 	}
923 	sc->flags |= MD_SHUTDOWN;
924 	wakeup(sc);
925 	while (sc->procp != NULL)
926 		tsleep(&sc->procp, PRIBIO, "mddestroy", hz / 10);
927 	if (sc->vnode != NULL)
928 		(void)vn_close(sc->vnode, sc->flags & MD_READONLY ?
929 		    FREAD : (FREAD|FWRITE), sc->cred, td);
930 	if (sc->cred != NULL)
931 		crfree(sc->cred);
932 	if (sc->object != NULL) {
933 		vm_object_deallocate(sc->object);
934 	}
935 	if (sc->indir)
936 		destroy_indir(sc, sc->indir);
937 	if (sc->uma)
938 		uma_zdestroy(sc->uma);
939 
940 	/* XXX: LOCK(unique unit numbers) */
941 	LIST_REMOVE(sc, list);
942 	/* XXX: UNLOCK(unique unit numbers) */
943 	free(sc, M_MD);
944 	return (0);
945 }
946 
947 static int
948 mdcreate_swap(struct md_ioctl *mdio, struct thread *td)
949 {
950 	int error;
951 	struct md_s *sc;
952 
953 	GIANT_REQUIRED;
954 
955 	if (mdio->md_options & MD_AUTOUNIT) {
956 		sc = mdnew(-1);
957 		mdio->md_unit = sc->unit;
958 	} else {
959 		sc = mdnew(mdio->md_unit);
960 	}
961 	if (sc == NULL)
962 		return (EBUSY);
963 
964 	sc->type = MD_SWAP;
965 
966 	/*
967 	 * Range check.  Disallow negative sizes or any size less then the
968 	 * size of a page.  Then round to a page.
969 	 */
970 
971 	if (mdio->md_size == 0) {
972 		mddestroy(sc, td);
973 		return (EDOM);
974 	}
975 
976 	/*
977 	 * Allocate an OBJT_SWAP object.
978 	 *
979 	 * sc_secsize is PAGE_SIZE'd
980 	 *
981 	 * mdio->size is in DEV_BSIZE'd chunks.
982 	 * Note the truncation.
983 	 */
984 
985 	sc->secsize = PAGE_SIZE;
986 	sc->nsect = mdio->md_size / (PAGE_SIZE / DEV_BSIZE);
987 	sc->object = vm_pager_allocate(OBJT_SWAP, NULL, sc->secsize * (vm_offset_t)sc->nsect, VM_PROT_DEFAULT, 0);
988 	sc->flags = mdio->md_options & MD_FORCE;
989 	if (mdio->md_options & MD_RESERVE) {
990 		if (swap_pager_reserve(sc->object, 0, sc->nsect) < 0) {
991 			vm_object_deallocate(sc->object);
992 			sc->object = NULL;
993 			mddestroy(sc, td);
994 			return (EDOM);
995 		}
996 	}
997 	error = mdsetcred(sc, td->td_ucred);
998 	if (error) {
999 		mddestroy(sc, td);
1000 		return (error);
1001 	}
1002 	mdinit(sc);
1003 	if (!(mdio->md_options & MD_RESERVE))
1004 		sc->pp->flags |= G_PF_CANDELETE;
1005 	return (0);
1006 }
1007 
1008 static int
1009 mddetach(int unit, struct thread *td)
1010 {
1011 	struct md_s *sc;
1012 
1013 	sc = mdfind(unit);
1014 	if (sc == NULL)
1015 		return (ENOENT);
1016 	if (sc->opencount != 0 && !(sc->flags & MD_FORCE))
1017 		return (EBUSY);
1018 	switch(sc->type) {
1019 	case MD_VNODE:
1020 	case MD_SWAP:
1021 	case MD_MALLOC:
1022 	case MD_PRELOAD:
1023 		return (mddestroy(sc, td));
1024 	default:
1025 		return (EOPNOTSUPP);
1026 	}
1027 }
1028 
1029 static int
1030 mdctlioctl(dev_t dev, u_long cmd, caddr_t addr, int flags, struct thread *td)
1031 {
1032 	struct md_ioctl *mdio;
1033 	struct md_s *sc;
1034 	int i;
1035 
1036 	if (md_debug)
1037 		printf("mdctlioctl(%s %lx %p %x %p)\n",
1038 			devtoname(dev), cmd, addr, flags, td);
1039 
1040 	/*
1041 	 * We assert the version number in the individual ioctl
1042 	 * handlers instead of out here because (a) it is possible we
1043 	 * may add another ioctl in the future which doesn't read an
1044 	 * mdio, and (b) the correct return value for an unknown ioctl
1045 	 * is ENOIOCTL, not EINVAL.
1046 	 */
1047 	mdio = (struct md_ioctl *)addr;
1048 	switch (cmd) {
1049 	case MDIOCATTACH:
1050 		if (mdio->md_version != MDIOVERSION)
1051 			return (EINVAL);
1052 		switch (mdio->md_type) {
1053 		case MD_MALLOC:
1054 			return (mdcreate_malloc(mdio));
1055 		case MD_PRELOAD:
1056 			return (mdcreate_preload(mdio));
1057 		case MD_VNODE:
1058 			return (mdcreate_vnode(mdio, td));
1059 		case MD_SWAP:
1060 			return (mdcreate_swap(mdio, td));
1061 		default:
1062 			return (EINVAL);
1063 		}
1064 	case MDIOCDETACH:
1065 		if (mdio->md_version != MDIOVERSION)
1066 			return (EINVAL);
1067 		if (mdio->md_file != NULL || mdio->md_size != 0 ||
1068 		    mdio->md_options != 0)
1069 			return (EINVAL);
1070 		return (mddetach(mdio->md_unit, td));
1071 	case MDIOCQUERY:
1072 		if (mdio->md_version != MDIOVERSION)
1073 			return (EINVAL);
1074 		sc = mdfind(mdio->md_unit);
1075 		if (sc == NULL)
1076 			return (ENOENT);
1077 		mdio->md_type = sc->type;
1078 		mdio->md_options = sc->flags;
1079 		switch (sc->type) {
1080 		case MD_MALLOC:
1081 			mdio->md_size = sc->nsect;
1082 			break;
1083 		case MD_PRELOAD:
1084 			mdio->md_size = sc->nsect;
1085 			mdio->md_base = (uint64_t)(intptr_t)sc->pl_ptr;
1086 			break;
1087 		case MD_SWAP:
1088 			mdio->md_size = sc->nsect * (PAGE_SIZE / DEV_BSIZE);
1089 			break;
1090 		case MD_VNODE:
1091 			mdio->md_size = sc->nsect;
1092 			/* XXX fill this in */
1093 			mdio->md_file = NULL;
1094 			break;
1095 		}
1096 		return (0);
1097 	case MDIOCLIST:
1098 		i = 1;
1099 		LIST_FOREACH(sc, &md_softc_list, list) {
1100 			if (i == MDNPAD - 1)
1101 				mdio->md_pad[i] = -1;
1102 			else
1103 				mdio->md_pad[i++] = sc->unit;
1104 		}
1105 		mdio->md_pad[0] = i - 1;
1106 		return (0);
1107 	default:
1108 		return (ENOIOCTL);
1109 	};
1110 	return (ENOIOCTL);
1111 }
1112 
1113 static void
1114 md_preloaded(u_char *image, unsigned length)
1115 {
1116 	struct md_s *sc;
1117 
1118 	sc = mdnew(-1);
1119 	if (sc == NULL)
1120 		return;
1121 	sc->type = MD_PRELOAD;
1122 	sc->secsize = DEV_BSIZE;
1123 	sc->nsect = length / DEV_BSIZE;
1124 	sc->pl_ptr = image;
1125 	sc->pl_len = length;
1126 	if (sc->unit == 0)
1127 		mdrootready = 1;
1128 	mdinit(sc);
1129 }
1130 
1131 static void
1132 md_drvinit(void *unused)
1133 {
1134 
1135 	caddr_t mod;
1136 	caddr_t c;
1137 	u_char *ptr, *name, *type;
1138 	unsigned len;
1139 
1140 #ifdef MD_ROOT_SIZE
1141 	md_preloaded(mfs_root, MD_ROOT_SIZE*1024);
1142 #endif
1143 	mod = NULL;
1144 	while ((mod = preload_search_next_name(mod)) != NULL) {
1145 		name = (char *)preload_search_info(mod, MODINFO_NAME);
1146 		type = (char *)preload_search_info(mod, MODINFO_TYPE);
1147 		if (name == NULL)
1148 			continue;
1149 		if (type == NULL)
1150 			continue;
1151 		if (strcmp(type, "md_image") && strcmp(type, "mfs_root"))
1152 			continue;
1153 		c = preload_search_info(mod, MODINFO_ADDR);
1154 		ptr = *(u_char **)c;
1155 		c = preload_search_info(mod, MODINFO_SIZE);
1156 		len = *(size_t *)c;
1157 		printf("%s%d: Preloaded image <%s> %d bytes at %p\n",
1158 		    MD_NAME, mdunits, name, len, ptr);
1159 		md_preloaded(ptr, len);
1160 	}
1161 	status_dev = make_dev(&mdctl_cdevsw, 0xffff00ff, UID_ROOT, GID_WHEEL,
1162 	    0600, MDCTL_NAME);
1163 }
1164 
1165 static int
1166 md_modevent(module_t mod, int type, void *data)
1167 {
1168 	int error;
1169 	struct md_s *sc;
1170 
1171 	switch (type) {
1172 	case MOD_LOAD:
1173 		md_drvinit(NULL);
1174 		break;
1175 	case MOD_UNLOAD:
1176 		LIST_FOREACH(sc, &md_softc_list, list) {
1177 			error = mddetach(sc->unit, curthread);
1178 			if (error != 0)
1179 				return (error);
1180 		}
1181 		if (status_dev)
1182 			destroy_dev(status_dev);
1183 		status_dev = 0;
1184 		break;
1185 	default:
1186 		break;
1187 	}
1188 	return (0);
1189 }
1190 
1191 static moduledata_t md_mod = {
1192 	MD_NAME,
1193 	md_modevent,
1194 	NULL
1195 };
1196 DECLARE_MODULE(md, md_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE+CDEV_MAJOR);
1197 MODULE_VERSION(md, MD_MODVER);
1198 
1199 
1200 #ifdef MD_ROOT
1201 static void
1202 md_takeroot(void *junk)
1203 {
1204 	if (mdrootready)
1205 		rootdevnames[0] = "ufs:/dev/md0";
1206 }
1207 
1208 SYSINIT(md_root, SI_SUB_MOUNT_ROOT, SI_ORDER_FIRST, md_takeroot, NULL);
1209 #endif /* MD_ROOT */
1210