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