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