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