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