xref: /freebsd/sys/dev/md/md.c (revision 7660b554bc59a07be0431c17e0e33815818baa69)
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 	u_int		total;
136 	u_int		used;
137 	u_int		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(u_int 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 if(bp->bio_cmd == BIO_WRITE)
494 		auio.uio_rw = UIO_WRITE;
495 	else
496 		panic("wrong BIO_OP in mdstart_vnode");
497 	auio.uio_resid = bp->bio_bcount;
498 	auio.uio_td = curthread;
499 	/*
500 	 * When reading set IO_DIRECT to try to avoid double-caching
501 	 * the data.  When writing IO_DIRECT is not optimal.
502 	 */
503 	if (bp->bio_cmd == BIO_READ) {
504 		vn_lock(sc->vnode, LK_EXCLUSIVE | LK_RETRY, curthread);
505 		error = VOP_READ(sc->vnode, &auio, IO_DIRECT, sc->cred);
506 	} else {
507 		(void) vn_start_write(sc->vnode, &mp, V_WAIT);
508 		vn_lock(sc->vnode, LK_EXCLUSIVE | LK_RETRY, curthread);
509 		error = VOP_WRITE(sc->vnode, &auio, 0, sc->cred);
510 		vn_finished_write(mp);
511 	}
512 	VOP_UNLOCK(sc->vnode, 0, curthread);
513 	bp->bio_resid = auio.uio_resid;
514 	return (error);
515 }
516 
517 #include <vm/vm_extern.h>
518 #include <vm/vm_kern.h>
519 
520 static int
521 mdstart_swap(struct md_s *sc, struct bio *bp)
522 {
523 	{
524 		int i, o, rv;
525 		vm_page_t m;
526 		u_char *p;
527 		vm_offset_t kva;
528 
529 		p = bp->bio_data;
530 		o = bp->bio_offset / sc->secsize;
531 		mtx_lock(&Giant);
532 		kva = kmem_alloc_nofault(kernel_map, sc->secsize);
533 
534 		VM_OBJECT_LOCK(sc->object);
535 		vm_object_pip_add(sc->object, 1);
536 		for (i = 0; i < bp->bio_length / sc->secsize; i++) {
537 			m = vm_page_grab(sc->object, i + o,
538 			    VM_ALLOC_NORMAL|VM_ALLOC_RETRY);
539 			pmap_qenter(kva, &m, 1);
540 			if (bp->bio_cmd == BIO_READ) {
541 				if (m->valid != VM_PAGE_BITS_ALL) {
542 					rv = vm_pager_get_pages(sc->object,
543 					    &m, 1, 0);
544 				}
545 				bcopy((void *)kva, p, sc->secsize);
546 			} else if (bp->bio_cmd == BIO_WRITE) {
547 				bcopy(p, (void *)kva, sc->secsize);
548 				m->valid = VM_PAGE_BITS_ALL;
549 #if 0
550 			} else if (bp->bio_cmd == BIO_DELETE) {
551 				bzero((void *)kva, sc->secsize);
552 				vm_page_dirty(m);
553 				m->valid = VM_PAGE_BITS_ALL;
554 #endif
555 			}
556 			pmap_qremove(kva, 1);
557 			vm_page_lock_queues();
558 			vm_page_wakeup(m);
559 			vm_page_activate(m);
560 			if (bp->bio_cmd == BIO_WRITE) {
561 				vm_page_dirty(m);
562 			}
563 			vm_page_unlock_queues();
564 			p += sc->secsize;
565 #if 0
566 if (bootverbose || o < 17)
567 printf("wire_count %d busy %d flags %x hold_count %d act_count %d queue %d valid %d dirty %d @ %d\n",
568     m->wire_count, m->busy,
569     m->flags, m->hold_count, m->act_count, m->queue, m->valid, m->dirty, o + i);
570 #endif
571 		}
572 		vm_object_pip_subtract(sc->object, 1);
573 		vm_object_set_writeable_dirty(sc->object);
574 		VM_OBJECT_UNLOCK(sc->object);
575 		kmem_free(kernel_map, kva, sc->secsize);
576 		mtx_unlock(&Giant);
577 		return (0);
578 	}
579 }
580 
581 static void
582 md_kthread(void *arg)
583 {
584 	struct md_s *sc;
585 	struct bio *bp;
586 	int error, hasgiant;
587 
588 	sc = arg;
589 	curthread->td_base_pri = PRIBIO;
590 
591 	switch (sc->type) {
592 	case MD_SWAP:
593 	case MD_VNODE:
594 		mtx_lock(&Giant);
595 		hasgiant = 1;
596 		break;
597 	case MD_MALLOC:
598 	case MD_PRELOAD:
599 	default:
600 		hasgiant = 0;
601 		break;
602 	}
603 
604 	for (;;) {
605 		mtx_lock(&sc->queue_mtx);
606 		bp = bioq_first(&sc->bio_queue);
607 		if (bp)
608 			bioq_remove(&sc->bio_queue, bp);
609 		if (!bp) {
610 			if (sc->flags & MD_SHUTDOWN) {
611 				mtx_unlock(&sc->queue_mtx);
612 				sc->procp = NULL;
613 				wakeup(&sc->procp);
614 				if (!hasgiant)
615 					mtx_lock(&Giant);
616 				kthread_exit(0);
617 			}
618 			msleep(sc, &sc->queue_mtx, PRIBIO | PDROP, "mdwait", 0);
619 			continue;
620 		}
621 		mtx_unlock(&sc->queue_mtx);
622 		if (bp->bio_cmd == BIO_GETATTR) {
623 			if (sc->fwsectors && sc->fwheads &&
624 			    (g_handleattr_int(bp, "GEOM::fwsectors",
625 			    sc->fwsectors) ||
626 			    g_handleattr_int(bp, "GEOM::fwheads",
627 			    sc->fwheads)))
628 				error = -1;
629 			else
630 				error = EOPNOTSUPP;
631 		} else {
632 			switch (sc->type) {
633 			case MD_MALLOC:
634 				error = mdstart_malloc(sc, bp);
635 				break;
636 			case MD_PRELOAD:
637 				error = mdstart_preload(sc, bp);
638 				break;
639 			case MD_VNODE:
640 				error = mdstart_vnode(sc, bp);
641 				break;
642 			case MD_SWAP:
643 				error = mdstart_swap(sc, bp);
644 				break;
645 			default:
646 				panic("Impossible md(type)");
647 				break;
648 			}
649 		}
650 
651 		if (error != -1) {
652 			bp->bio_completed = bp->bio_length;
653 			g_io_deliver(bp, error);
654 		}
655 	}
656 }
657 
658 static struct md_s *
659 mdfind(int unit)
660 {
661 	struct md_s *sc;
662 
663 	/* XXX: LOCK(unique unit numbers) */
664 	LIST_FOREACH(sc, &md_softc_list, list) {
665 		if (sc->unit == unit)
666 			break;
667 	}
668 	/* XXX: UNLOCK(unique unit numbers) */
669 	return (sc);
670 }
671 
672 static struct md_s *
673 mdnew(int unit)
674 {
675 	struct md_s *sc;
676 	int error, max = -1;
677 
678 	/* XXX: LOCK(unique unit numbers) */
679 	LIST_FOREACH(sc, &md_softc_list, list) {
680 		if (sc->unit == unit) {
681 			/* XXX: UNLOCK(unique unit numbers) */
682 			return (NULL);
683 		}
684 		if (sc->unit > max)
685 			max = sc->unit;
686 	}
687 	if (unit == -1)
688 		unit = max + 1;
689 	sc = (struct md_s *)malloc(sizeof *sc, M_MD, M_WAITOK | M_ZERO);
690 	sc->unit = unit;
691 	bioq_init(&sc->bio_queue);
692 	mtx_init(&sc->queue_mtx, "md bio queue", NULL, MTX_DEF);
693 	sprintf(sc->name, "md%d", unit);
694 	error = kthread_create(md_kthread, sc, &sc->procp, 0, 0,"%s", sc->name);
695 	if (error) {
696 		free(sc, M_MD);
697 		return (NULL);
698 	}
699 	LIST_INSERT_HEAD(&md_softc_list, sc, list);
700 	/* XXX: UNLOCK(unique unit numbers) */
701 	return (sc);
702 }
703 
704 static void
705 mdinit(struct md_s *sc)
706 {
707 
708 	struct g_geom *gp;
709 	struct g_provider *pp;
710 
711 	DROP_GIANT();
712 	g_topology_lock();
713 	gp = g_new_geomf(&g_md_class, "md%d", sc->unit);
714 	gp->start = g_md_start;
715 	gp->access = g_md_access;
716 	gp->softc = sc;
717 	pp = g_new_providerf(gp, "md%d", sc->unit);
718 	pp->mediasize = (off_t)sc->nsect * sc->secsize;
719 	pp->sectorsize = sc->secsize;
720 	sc->gp = gp;
721 	sc->pp = pp;
722 	g_error_provider(pp, 0);
723 	g_topology_unlock();
724 	PICKUP_GIANT();
725 }
726 
727 /*
728  * XXX: we should check that the range they feed us is mapped.
729  * XXX: we should implement read-only.
730  */
731 
732 static int
733 mdcreate_preload(struct md_ioctl *mdio)
734 {
735 	struct md_s *sc;
736 
737 	if (mdio->md_size == 0)
738 		return (EINVAL);
739 	if (mdio->md_options & ~(MD_AUTOUNIT))
740 		return (EINVAL);
741 	if (mdio->md_options & MD_AUTOUNIT) {
742 		sc = mdnew(-1);
743 		if (sc == NULL)
744 			return (ENOMEM);
745 		mdio->md_unit = sc->unit;
746 	} else {
747 		sc = mdnew(mdio->md_unit);
748 		if (sc == NULL)
749 			return (EBUSY);
750 	}
751 	sc->type = MD_PRELOAD;
752 	sc->secsize = DEV_BSIZE;
753 	sc->nsect = mdio->md_size;
754 	sc->flags = mdio->md_options & MD_FORCE;
755 	/* Cast to pointer size, then to pointer to avoid warning */
756 	sc->pl_ptr = (u_char *)(uintptr_t)mdio->md_base;
757 	sc->pl_len = (mdio->md_size << DEV_BSHIFT);
758 	mdinit(sc);
759 	return (0);
760 }
761 
762 
763 static int
764 mdcreate_malloc(struct md_ioctl *mdio)
765 {
766 	struct md_s *sc;
767 	off_t u;
768 	uintptr_t sp;
769 	int error;
770 
771 	error = 0;
772 	if (mdio->md_size == 0)
773 		return (EINVAL);
774 	if (mdio->md_options & ~(MD_AUTOUNIT | MD_COMPRESS | MD_RESERVE))
775 		return (EINVAL);
776 	if (mdio->md_secsize != 0 && !powerof2(mdio->md_secsize))
777 		return (EINVAL);
778 	/* Compression doesn't make sense if we have reserved space */
779 	if (mdio->md_options & MD_RESERVE)
780 		mdio->md_options &= ~MD_COMPRESS;
781 	if (mdio->md_options & MD_AUTOUNIT) {
782 		sc = mdnew(-1);
783 		if (sc == NULL)
784 			return (ENOMEM);
785 		mdio->md_unit = sc->unit;
786 	} else {
787 		sc = mdnew(mdio->md_unit);
788 		if (sc == NULL)
789 			return (EBUSY);
790 	}
791 	sc->type = MD_MALLOC;
792 	if (mdio->md_secsize != 0)
793 		sc->secsize = mdio->md_secsize;
794 	else
795 		sc->secsize = DEV_BSIZE;
796 	if (mdio->md_fwsectors != 0)
797 		sc->fwsectors = mdio->md_fwsectors;
798 	if (mdio->md_fwheads != 0)
799 		sc->fwheads = mdio->md_fwheads;
800 	sc->nsect = mdio->md_size;
801 	sc->nsect /= (sc->secsize / DEV_BSIZE);
802 	sc->flags = mdio->md_options & (MD_COMPRESS | MD_FORCE);
803 	sc->indir = dimension(sc->nsect);
804 	sc->uma = uma_zcreate(sc->name, sc->secsize,
805 	    NULL, NULL, NULL, NULL, 0x1ff, 0);
806 	if (mdio->md_options & MD_RESERVE) {
807 		for (u = 0; u < sc->nsect; u++) {
808 			sp = (uintptr_t) uma_zalloc(sc->uma, M_NOWAIT | M_ZERO);
809 			if (sp != 0)
810 				error = s_write(sc->indir, u, sp);
811 			else
812 				error = ENOMEM;
813 			if (error)
814 				break;
815 		}
816 	}
817 	if (error)  {
818 		mddestroy(sc, NULL);
819 		return (error);
820 	}
821 	mdinit(sc);
822 	if (!(mdio->md_options & MD_RESERVE))
823 		sc->pp->flags |= G_PF_CANDELETE;
824 	return (0);
825 }
826 
827 
828 static int
829 mdsetcred(struct md_s *sc, struct ucred *cred)
830 {
831 	char *tmpbuf;
832 	int error = 0;
833 
834 	/*
835 	 * Set credits in our softc
836 	 */
837 
838 	if (sc->cred)
839 		crfree(sc->cred);
840 	sc->cred = crhold(cred);
841 
842 	/*
843 	 * Horrible kludge to establish credentials for NFS  XXX.
844 	 */
845 
846 	if (sc->vnode) {
847 		struct uio auio;
848 		struct iovec aiov;
849 
850 		tmpbuf = malloc(sc->secsize, M_TEMP, M_WAITOK);
851 		bzero(&auio, sizeof(auio));
852 
853 		aiov.iov_base = tmpbuf;
854 		aiov.iov_len = sc->secsize;
855 		auio.uio_iov = &aiov;
856 		auio.uio_iovcnt = 1;
857 		auio.uio_offset = 0;
858 		auio.uio_rw = UIO_READ;
859 		auio.uio_segflg = UIO_SYSSPACE;
860 		auio.uio_resid = aiov.iov_len;
861 		vn_lock(sc->vnode, LK_EXCLUSIVE | LK_RETRY, curthread);
862 		error = VOP_READ(sc->vnode, &auio, 0, sc->cred);
863 		VOP_UNLOCK(sc->vnode, 0, curthread);
864 		free(tmpbuf, M_TEMP);
865 	}
866 	return (error);
867 }
868 
869 static int
870 mdcreate_vnode(struct md_ioctl *mdio, struct thread *td)
871 {
872 	struct md_s *sc;
873 	struct vattr vattr;
874 	struct nameidata nd;
875 	int error, flags;
876 
877 	flags = FREAD|FWRITE;
878 	NDINIT(&nd, LOOKUP, FOLLOW, UIO_USERSPACE, mdio->md_file, td);
879 	error = vn_open(&nd, &flags, 0, -1);
880 	if (error) {
881 		if (error != EACCES && error != EPERM && error != EROFS)
882 			return (error);
883 		flags &= ~FWRITE;
884 		NDINIT(&nd, LOOKUP, FOLLOW, UIO_USERSPACE, mdio->md_file, td);
885 		error = vn_open(&nd, &flags, 0, -1);
886 		if (error)
887 			return (error);
888 	}
889 	NDFREE(&nd, NDF_ONLY_PNBUF);
890 	if (nd.ni_vp->v_type != VREG ||
891 	    (error = VOP_GETATTR(nd.ni_vp, &vattr, td->td_ucred, td))) {
892 		VOP_UNLOCK(nd.ni_vp, 0, td);
893 		(void) vn_close(nd.ni_vp, flags, td->td_ucred, td);
894 		return (error ? error : EINVAL);
895 	}
896 	VOP_UNLOCK(nd.ni_vp, 0, td);
897 
898 	if (mdio->md_options & MD_AUTOUNIT) {
899 		sc = mdnew(-1);
900 		mdio->md_unit = sc->unit;
901 	} else {
902 		sc = mdnew(mdio->md_unit);
903 	}
904 	if (sc == NULL) {
905 		(void) vn_close(nd.ni_vp, flags, td->td_ucred, td);
906 		return (EBUSY);
907 	}
908 
909 	sc->type = MD_VNODE;
910 	sc->flags = mdio->md_options & MD_FORCE;
911 	if (!(flags & FWRITE))
912 		sc->flags |= MD_READONLY;
913 	sc->secsize = DEV_BSIZE;
914 	sc->vnode = nd.ni_vp;
915 
916 	/*
917 	 * If the size is specified, override the file attributes.
918 	 */
919 	if (mdio->md_size)
920 		sc->nsect = mdio->md_size;
921 	else
922 		sc->nsect = vattr.va_size / sc->secsize; /* XXX: round up ? */
923 	if (sc->nsect == 0) {
924 		mddestroy(sc, td);
925 		return (EINVAL);
926 	}
927 	error = mdsetcred(sc, td->td_ucred);
928 	if (error) {
929 		mddestroy(sc, td);
930 		return (error);
931 	}
932 	mdinit(sc);
933 	return (0);
934 }
935 
936 static void
937 md_zapit(void *p, int cancel)
938 {
939 	if (cancel)
940 		return;
941 	g_wither_geom(p, ENXIO);
942 }
943 
944 static int
945 mddestroy(struct md_s *sc, struct thread *td)
946 {
947 
948 	GIANT_REQUIRED;
949 
950 	mtx_destroy(&sc->queue_mtx);
951 	if (sc->gp) {
952 		sc->gp->softc = NULL;
953 		g_waitfor_event(md_zapit, sc->gp, M_WAITOK, sc->gp, NULL);
954 		sc->gp = NULL;
955 		sc->pp = NULL;
956 	}
957 	sc->flags |= MD_SHUTDOWN;
958 	wakeup(sc);
959 	while (sc->procp != NULL)
960 		tsleep(&sc->procp, PRIBIO, "mddestroy", hz / 10);
961 	if (sc->vnode != NULL)
962 		(void)vn_close(sc->vnode, sc->flags & MD_READONLY ?
963 		    FREAD : (FREAD|FWRITE), sc->cred, td);
964 	if (sc->cred != NULL)
965 		crfree(sc->cred);
966 	if (sc->object != NULL) {
967 		vm_object_deallocate(sc->object);
968 	}
969 	if (sc->indir)
970 		destroy_indir(sc, sc->indir);
971 	if (sc->uma)
972 		uma_zdestroy(sc->uma);
973 
974 	/* XXX: LOCK(unique unit numbers) */
975 	LIST_REMOVE(sc, list);
976 	/* XXX: UNLOCK(unique unit numbers) */
977 	free(sc, M_MD);
978 	return (0);
979 }
980 
981 static int
982 mdcreate_swap(struct md_ioctl *mdio, struct thread *td)
983 {
984 	int error;
985 	struct md_s *sc;
986 
987 	GIANT_REQUIRED;
988 
989 	if (mdio->md_options & MD_AUTOUNIT) {
990 		sc = mdnew(-1);
991 		mdio->md_unit = sc->unit;
992 	} else {
993 		sc = mdnew(mdio->md_unit);
994 	}
995 	if (sc == NULL)
996 		return (EBUSY);
997 
998 	sc->type = MD_SWAP;
999 
1000 	/*
1001 	 * Range check.  Disallow negative sizes or any size less then the
1002 	 * size of a page.  Then round to a page.
1003 	 */
1004 
1005 	if (mdio->md_size == 0) {
1006 		mddestroy(sc, td);
1007 		return (EDOM);
1008 	}
1009 
1010 	/*
1011 	 * Allocate an OBJT_SWAP object.
1012 	 *
1013 	 * sc_secsize is PAGE_SIZE'd
1014 	 *
1015 	 * mdio->size is in DEV_BSIZE'd chunks.
1016 	 * Note the truncation.
1017 	 */
1018 
1019 	sc->secsize = PAGE_SIZE;
1020 	sc->nsect = mdio->md_size / (PAGE_SIZE / DEV_BSIZE);
1021 	sc->object = vm_pager_allocate(OBJT_SWAP, NULL, sc->secsize * (vm_offset_t)sc->nsect, VM_PROT_DEFAULT, 0);
1022 	sc->flags = mdio->md_options & MD_FORCE;
1023 	if (mdio->md_options & MD_RESERVE) {
1024 		if (swap_pager_reserve(sc->object, 0, sc->nsect) < 0) {
1025 			vm_object_deallocate(sc->object);
1026 			sc->object = NULL;
1027 			mddestroy(sc, td);
1028 			return (EDOM);
1029 		}
1030 	}
1031 	error = mdsetcred(sc, td->td_ucred);
1032 	if (error) {
1033 		mddestroy(sc, td);
1034 		return (error);
1035 	}
1036 	mdinit(sc);
1037 	if (!(mdio->md_options & MD_RESERVE))
1038 		sc->pp->flags |= G_PF_CANDELETE;
1039 	return (0);
1040 }
1041 
1042 static int
1043 mddetach(int unit, struct thread *td)
1044 {
1045 	struct md_s *sc;
1046 
1047 	sc = mdfind(unit);
1048 	if (sc == NULL)
1049 		return (ENOENT);
1050 	if (sc->opencount != 0 && !(sc->flags & MD_FORCE))
1051 		return (EBUSY);
1052 	switch(sc->type) {
1053 	case MD_VNODE:
1054 	case MD_SWAP:
1055 	case MD_MALLOC:
1056 	case MD_PRELOAD:
1057 		return (mddestroy(sc, td));
1058 	default:
1059 		return (EOPNOTSUPP);
1060 	}
1061 }
1062 
1063 static int
1064 mdctlioctl(dev_t dev, u_long cmd, caddr_t addr, int flags, struct thread *td)
1065 {
1066 	struct md_ioctl *mdio;
1067 	struct md_s *sc;
1068 	int i;
1069 
1070 	if (md_debug)
1071 		printf("mdctlioctl(%s %lx %p %x %p)\n",
1072 			devtoname(dev), cmd, addr, flags, td);
1073 
1074 	/*
1075 	 * We assert the version number in the individual ioctl
1076 	 * handlers instead of out here because (a) it is possible we
1077 	 * may add another ioctl in the future which doesn't read an
1078 	 * mdio, and (b) the correct return value for an unknown ioctl
1079 	 * is ENOIOCTL, not EINVAL.
1080 	 */
1081 	mdio = (struct md_ioctl *)addr;
1082 	switch (cmd) {
1083 	case MDIOCATTACH:
1084 		if (mdio->md_version != MDIOVERSION)
1085 			return (EINVAL);
1086 		switch (mdio->md_type) {
1087 		case MD_MALLOC:
1088 			return (mdcreate_malloc(mdio));
1089 		case MD_PRELOAD:
1090 			return (mdcreate_preload(mdio));
1091 		case MD_VNODE:
1092 			return (mdcreate_vnode(mdio, td));
1093 		case MD_SWAP:
1094 			return (mdcreate_swap(mdio, td));
1095 		default:
1096 			return (EINVAL);
1097 		}
1098 	case MDIOCDETACH:
1099 		if (mdio->md_version != MDIOVERSION)
1100 			return (EINVAL);
1101 		if (mdio->md_file != NULL || mdio->md_size != 0 ||
1102 		    mdio->md_options != 0)
1103 			return (EINVAL);
1104 		return (mddetach(mdio->md_unit, td));
1105 	case MDIOCQUERY:
1106 		if (mdio->md_version != MDIOVERSION)
1107 			return (EINVAL);
1108 		sc = mdfind(mdio->md_unit);
1109 		if (sc == NULL)
1110 			return (ENOENT);
1111 		mdio->md_type = sc->type;
1112 		mdio->md_options = sc->flags;
1113 		switch (sc->type) {
1114 		case MD_MALLOC:
1115 			mdio->md_size = sc->nsect;
1116 			break;
1117 		case MD_PRELOAD:
1118 			mdio->md_size = sc->nsect;
1119 			mdio->md_base = (uint64_t)(intptr_t)sc->pl_ptr;
1120 			break;
1121 		case MD_SWAP:
1122 			mdio->md_size = sc->nsect * (PAGE_SIZE / DEV_BSIZE);
1123 			break;
1124 		case MD_VNODE:
1125 			mdio->md_size = sc->nsect;
1126 			/* XXX fill this in */
1127 			mdio->md_file = NULL;
1128 			break;
1129 		}
1130 		return (0);
1131 	case MDIOCLIST:
1132 		i = 1;
1133 		LIST_FOREACH(sc, &md_softc_list, list) {
1134 			if (i == MDNPAD - 1)
1135 				mdio->md_pad[i] = -1;
1136 			else
1137 				mdio->md_pad[i++] = sc->unit;
1138 		}
1139 		mdio->md_pad[0] = i - 1;
1140 		return (0);
1141 	default:
1142 		return (ENOIOCTL);
1143 	};
1144 	return (ENOIOCTL);
1145 }
1146 
1147 static void
1148 md_preloaded(u_char *image, unsigned length)
1149 {
1150 	struct md_s *sc;
1151 
1152 	sc = mdnew(-1);
1153 	if (sc == NULL)
1154 		return;
1155 	sc->type = MD_PRELOAD;
1156 	sc->secsize = DEV_BSIZE;
1157 	sc->nsect = length / DEV_BSIZE;
1158 	sc->pl_ptr = image;
1159 	sc->pl_len = length;
1160 	if (sc->unit == 0)
1161 		mdrootready = 1;
1162 	mdinit(sc);
1163 }
1164 
1165 static void
1166 md_drvinit(void *unused)
1167 {
1168 
1169 	caddr_t mod;
1170 	caddr_t c;
1171 	u_char *ptr, *name, *type;
1172 	unsigned len;
1173 
1174 #ifdef MD_ROOT_SIZE
1175 	md_preloaded(mfs_root, MD_ROOT_SIZE*1024);
1176 #endif
1177 	mod = NULL;
1178 	while ((mod = preload_search_next_name(mod)) != NULL) {
1179 		name = (char *)preload_search_info(mod, MODINFO_NAME);
1180 		type = (char *)preload_search_info(mod, MODINFO_TYPE);
1181 		if (name == NULL)
1182 			continue;
1183 		if (type == NULL)
1184 			continue;
1185 		if (strcmp(type, "md_image") && strcmp(type, "mfs_root"))
1186 			continue;
1187 		c = preload_search_info(mod, MODINFO_ADDR);
1188 		ptr = *(u_char **)c;
1189 		c = preload_search_info(mod, MODINFO_SIZE);
1190 		len = *(size_t *)c;
1191 		printf("%s%d: Preloaded image <%s> %d bytes at %p\n",
1192 		    MD_NAME, mdunits, name, len, ptr);
1193 		md_preloaded(ptr, len);
1194 	}
1195 	status_dev = make_dev(&mdctl_cdevsw, 0xffff00ff, UID_ROOT, GID_WHEEL,
1196 	    0600, MDCTL_NAME);
1197 }
1198 
1199 static int
1200 md_modevent(module_t mod, int type, void *data)
1201 {
1202 	int error;
1203 	struct md_s *sc;
1204 
1205 	switch (type) {
1206 	case MOD_LOAD:
1207 		md_drvinit(NULL);
1208 		break;
1209 	case MOD_UNLOAD:
1210 		LIST_FOREACH(sc, &md_softc_list, list) {
1211 			error = mddetach(sc->unit, curthread);
1212 			if (error != 0)
1213 				return (error);
1214 		}
1215 		if (status_dev)
1216 			destroy_dev(status_dev);
1217 		status_dev = 0;
1218 		break;
1219 	default:
1220 		break;
1221 	}
1222 	return (0);
1223 }
1224 
1225 static moduledata_t md_mod = {
1226 	MD_NAME,
1227 	md_modevent,
1228 	NULL
1229 };
1230 DECLARE_MODULE(md, md_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE+CDEV_MAJOR);
1231 MODULE_VERSION(md, MD_MODVER);
1232 
1233 
1234 #ifdef MD_ROOT
1235 static void
1236 md_takeroot(void *junk)
1237 {
1238 	if (mdrootready)
1239 		rootdevnames[0] = "ufs:/dev/md0";
1240 }
1241 
1242 SYSINIT(md_root, SI_SUB_MOUNT_ROOT, SI_ORDER_FIRST, md_takeroot, NULL);
1243 #endif /* MD_ROOT */
1244