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