md.c revision 74521
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 74521 2001-03-20 12:31:53Z phk $
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_mfs.h"		/* We have adopted some tasks from MFS */
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/devicestat.h>
68#include <sys/disk.h>
69#include <sys/kernel.h>
70#include <sys/malloc.h>
71#include <sys/sysctl.h>
72#include <sys/linker.h>
73#include <sys/queue.h>
74#include <sys/mdioctl.h>
75#include <sys/vnode.h>
76#include <sys/namei.h>
77#include <sys/fcntl.h>
78#include <sys/proc.h>
79#include <machine/atomic.h>
80
81#include <vm/vm.h>
82#include <vm/vm_object.h>
83#include <vm/vm_page.h>
84#include <vm/vm_pager.h>
85#include <vm/vm_zone.h>
86#include <vm/swap_pager.h>
87
88#define MD_MODVER 1
89
90#ifndef MD_NSECT
91#define MD_NSECT (10000 * 2)
92#endif
93
94MALLOC_DEFINE(M_MD, "MD disk", "Memory Disk");
95MALLOC_DEFINE(M_MDSECT, "MD sectors", "Memory Disk Sectors");
96
97static int md_debug;
98SYSCTL_INT(_debug, OID_AUTO, mddebug, CTLFLAG_RW, &md_debug, 0, "");
99
100#if defined(MFS_ROOT) && !defined(MD_ROOT)
101#define MD_ROOT MFS_ROOT
102#warning "option MFS_ROOT has been superceeded by MD_ROOT"
103#endif
104
105#if defined(MFS_ROOT_SIZE) && !defined(MD_ROOT_SIZE)
106#define MD_ROOT_SIZE MFS_ROOT_SIZE
107#warning "option MFS_ROOT_SIZE has been superceeded by MD_ROOT_SIZE"
108#endif
109
110#if defined(MD_ROOT) && defined(MD_ROOT_SIZE)
111/* Image gets put here: */
112static u_char mfs_root[MD_ROOT_SIZE*1024] = "MFS Filesystem goes here";
113static u_char end_mfs_root[] __unused = "MFS Filesystem had better STOP here";
114#endif
115
116static int	mdrootready;
117static int	mdunits;
118static dev_t	status_dev = 0;
119
120
121#define CDEV_MAJOR	95
122
123static d_strategy_t mdstrategy;
124static d_open_t mdopen;
125static d_ioctl_t mdioctl, mdctlioctl;
126
127static struct cdevsw md_cdevsw = {
128        /* open */      mdopen,
129        /* close */     nullclose,
130        /* read */      physread,
131        /* write */     physwrite,
132        /* ioctl */     mdioctl,
133        /* poll */      nopoll,
134        /* mmap */      nommap,
135        /* strategy */  mdstrategy,
136        /* name */      MD_NAME,
137        /* maj */       CDEV_MAJOR,
138        /* dump */      nodump,
139        /* psize */     nopsize,
140        /* flags */     D_DISK | D_CANFREE | D_MEMDISK,
141};
142
143static struct cdevsw mdctl_cdevsw = {
144        /* open */      nullopen,
145        /* close */     nullclose,
146        /* read */      noread,
147        /* write */     nowrite,
148        /* ioctl */     mdctlioctl,
149        /* poll */      nopoll,
150        /* mmap */      nommap,
151        /* strategy */  nostrategy,
152        /* name */      MD_NAME,
153        /* maj */       CDEV_MAJOR
154};
155
156static struct cdevsw mddisk_cdevsw;
157
158static LIST_HEAD(, md_s) md_softc_list = LIST_HEAD_INITIALIZER(&md_softc_list);
159
160struct md_s {
161	int unit;
162	LIST_ENTRY(md_s) list;
163	struct devstat stats;
164	struct bio_queue_head bio_queue;
165	struct disk disk;
166	dev_t dev;
167	int busy;
168	enum md_types type;
169	unsigned nsect;
170	unsigned secsize;
171	unsigned flags;
172
173	/* MD_MALLOC related fields */
174	u_char **secp;
175
176	/* MD_PRELOAD related fields */
177	u_char *pl_ptr;
178	unsigned pl_len;
179
180	/* MD_VNODE related fields */
181	struct vnode *vnode;
182	struct ucred *cred;
183
184	/* MD_OBJET related fields */
185	vm_object_t object;
186};
187
188static int
189mdopen(dev_t dev, int flag, int fmt, struct proc *p)
190{
191	struct md_s *sc;
192	struct disklabel *dl;
193
194	if (md_debug)
195		printf("mdopen(%s %x %x %p)\n",
196			devtoname(dev), flag, fmt, p);
197
198	sc = dev->si_drv1;
199
200	dl = &sc->disk.d_label;
201	bzero(dl, sizeof(*dl));
202	dl->d_secsize = sc->secsize;
203	dl->d_nsectors = sc->nsect > 63 ? 63 : sc->nsect;
204	dl->d_ntracks = 1;
205	dl->d_secpercyl = dl->d_nsectors * dl->d_ntracks;
206	dl->d_secperunit = sc->nsect;
207	dl->d_ncylinders = dl->d_secperunit / dl->d_secpercyl;
208	return (0);
209}
210
211static int
212mdioctl(dev_t dev, u_long cmd, caddr_t addr, int flags, struct proc *p)
213{
214
215	if (md_debug)
216		printf("mdioctl(%s %lx %p %x %p)\n",
217			devtoname(dev), cmd, addr, flags, p);
218
219	return (ENOIOCTL);
220}
221
222static void
223mdstart_malloc(struct md_s *sc)
224{
225	int i;
226	struct bio *bp;
227	devstat_trans_flags dop;
228	u_char *secp, **secpp, *dst;
229	unsigned secno, nsec, secval, uc;
230
231	for (;;) {
232		/* XXX: LOCK(unique unit numbers) */
233		bp = bioq_first(&sc->bio_queue);
234		if (bp)
235			bioq_remove(&sc->bio_queue, bp);
236		/* XXX: UNLOCK(unique unit numbers) */
237		if (!bp)
238			break;
239
240		devstat_start_transaction(&sc->stats);
241
242		if (bp->bio_cmd == BIO_DELETE)
243			dop = DEVSTAT_NO_DATA;
244		else if (bp->bio_cmd == BIO_READ)
245			dop = DEVSTAT_READ;
246		else
247			dop = DEVSTAT_WRITE;
248
249		nsec = bp->bio_bcount / sc->secsize;
250		secno = bp->bio_pblkno;
251		dst = bp->bio_data;
252		while (nsec--) {
253			secpp = &sc->secp[secno];
254			if ((uintptr_t)*secpp > 255) {
255				secp = *secpp;
256				secval = 0;
257			} else {
258				secp = NULL;
259				secval = (uintptr_t) *secpp;
260			}
261
262			if (md_debug > 2)
263				printf("%x %p %p %d\n",
264				    bp->bio_flags, secpp, secp, secval);
265
266			if (bp->bio_cmd == BIO_DELETE) {
267				if (!(sc->flags & MD_RESERVE) && secp != NULL) {
268					FREE(secp, M_MDSECT);
269					*secpp = 0;
270				}
271			} else if (bp->bio_cmd == BIO_READ) {
272				if (secp != NULL) {
273					bcopy(secp, dst, sc->secsize);
274				} else if (secval) {
275					for (i = 0; i < sc->secsize; i++)
276						dst[i] = secval;
277				} else {
278					bzero(dst, sc->secsize);
279				}
280			} else {
281				if (sc->flags & MD_COMPRESS) {
282					uc = dst[0];
283					for (i = 1; i < sc->secsize; i++)
284						if (dst[i] != uc)
285							break;
286				} else {
287					i = 0;
288					uc = 0;
289				}
290				if (i == sc->secsize) {
291					if (secp)
292						FREE(secp, M_MDSECT);
293					*secpp = (u_char *)(uintptr_t)uc;
294				} else {
295					if (secp == NULL)
296						MALLOC(secp, u_char *, sc->secsize, M_MDSECT, M_WAITOK);
297					bcopy(dst, secp, sc->secsize);
298					*secpp = secp;
299				}
300			}
301			secno++;
302			dst += sc->secsize;
303		}
304		bp->bio_resid = 0;
305		devstat_end_transaction_bio(&sc->stats, bp);
306		biodone(bp);
307	}
308	return;
309}
310
311
312static void
313mdstart_preload(struct md_s *sc)
314{
315	struct bio *bp;
316	devstat_trans_flags dop;
317
318	for (;;) {
319		/* XXX: LOCK(unique unit numbers) */
320		bp = bioq_first(&sc->bio_queue);
321		if (bp)
322			bioq_remove(&sc->bio_queue, bp);
323		/* XXX: UNLOCK(unique unit numbers) */
324		if (!bp)
325			break;
326
327		devstat_start_transaction(&sc->stats);
328
329		if (bp->bio_cmd == BIO_DELETE) {
330			dop = DEVSTAT_NO_DATA;
331		} else if (bp->bio_cmd == BIO_READ) {
332			dop = DEVSTAT_READ;
333			bcopy(sc->pl_ptr + (bp->bio_pblkno << DEV_BSHIFT), bp->bio_data, bp->bio_bcount);
334		} else {
335			dop = DEVSTAT_WRITE;
336			bcopy(bp->bio_data, sc->pl_ptr + (bp->bio_pblkno << DEV_BSHIFT), bp->bio_bcount);
337		}
338		bp->bio_resid = 0;
339		devstat_end_transaction_bio(&sc->stats, bp);
340		biodone(bp);
341	}
342	return;
343}
344
345static void
346mdstart_vnode(struct md_s *sc)
347{
348	int error;
349	struct bio *bp;
350	struct uio auio;
351	struct iovec aiov;
352	struct mount *mp;
353
354	/*
355	 * VNODE I/O
356	 *
357	 * If an error occurs, we set BIO_ERROR but we do not set
358	 * B_INVAL because (for a write anyway), the buffer is
359	 * still valid.
360	 */
361
362	for (;;) {
363		/* XXX: LOCK(unique unit numbers) */
364		bp = bioq_first(&sc->bio_queue);
365		if (bp)
366			bioq_remove(&sc->bio_queue, bp);
367		/* XXX: UNLOCK(unique unit numbers) */
368		if (!bp)
369			break;
370
371		devstat_start_transaction(&sc->stats);
372
373		bzero(&auio, sizeof(auio));
374
375		aiov.iov_base = bp->bio_data;
376		aiov.iov_len = bp->bio_bcount;
377		auio.uio_iov = &aiov;
378		auio.uio_iovcnt = 1;
379		auio.uio_offset = (vm_ooffset_t)bp->bio_pblkno * sc->secsize;
380		auio.uio_segflg = UIO_SYSSPACE;
381		if(bp->bio_cmd == BIO_READ)
382			auio.uio_rw = UIO_READ;
383		else
384			auio.uio_rw = UIO_WRITE;
385		auio.uio_resid = bp->bio_bcount;
386		auio.uio_procp = curproc;
387		if (VOP_ISLOCKED(sc->vnode, NULL))
388			vprint("unexpected md driver lock", sc->vnode);
389		if (bp->bio_cmd == BIO_READ) {
390			vn_lock(sc->vnode, LK_EXCLUSIVE | LK_RETRY, curproc);
391			error = VOP_READ(sc->vnode, &auio, 0, sc->cred);
392		} else {
393			(void) vn_start_write(sc->vnode, &mp, V_WAIT);
394			vn_lock(sc->vnode, LK_EXCLUSIVE | LK_RETRY, curproc);
395			error = VOP_WRITE(sc->vnode, &auio, 0, sc->cred);
396			vn_finished_write(mp);
397		}
398		VOP_UNLOCK(sc->vnode, 0, curproc);
399		bp->bio_resid = auio.uio_resid;
400
401		if (error) {
402			bp->bio_error = error;
403			bp->bio_flags |= BIO_ERROR;
404		}
405		devstat_end_transaction_bio(&sc->stats, bp);
406		biodone(bp);
407	}
408	return;
409}
410
411static void
412mdstart_swap(struct md_s *sc)
413{
414	struct bio *bp;
415
416	for (;;) {
417		/* XXX: LOCK(unique unit numbers) */
418		bp = bioq_first(&sc->bio_queue);
419		if (bp)
420			bioq_remove(&sc->bio_queue, bp);
421		/* XXX: UNLOCK(unique unit numbers) */
422		if (!bp)
423			break;
424
425#if 0
426		devstat_start_transaction(&sc->stats);
427#endif
428
429		if ((bp->bio_cmd == BIO_DELETE) && (sc->flags & MD_RESERVE))
430			biodone(bp);
431		else
432			vm_pager_strategy(sc->object, bp);
433
434#if 0
435		devstat_end_transaction_bio(&sc->stats, bp);
436#endif
437	}
438	return;
439}
440
441static void
442mdstrategy(struct bio *bp)
443{
444	struct md_s *sc;
445
446	if (md_debug > 1)
447		printf("mdstrategy(%p) %s %x, %d, %ld, %p)\n",
448		    bp, devtoname(bp->bio_dev), bp->bio_flags, bp->bio_blkno,
449		    bp->bio_bcount / DEV_BSIZE, bp->bio_data);
450
451	sc = bp->bio_dev->si_drv1;
452
453	/* XXX: LOCK(sc->lock) */
454	bioqdisksort(&sc->bio_queue, bp);
455	/* XXX: UNLOCK(sc->lock) */
456
457	if (atomic_cmpset_int(&sc->busy, 0, 1) == 0)
458		return;
459
460	switch (sc->type) {
461	case MD_MALLOC:
462		mdstart_malloc(sc);
463		break;
464	case MD_PRELOAD:
465		mdstart_preload(sc);
466		break;
467	case MD_VNODE:
468		mdstart_vnode(sc);
469		break;
470	case MD_SWAP:
471		mdstart_swap(sc);
472		break;
473	default:
474		panic("Impossible md(type)");
475		break;
476	}
477	sc->busy = 0;
478}
479
480static struct md_s *
481mdfind(int unit)
482{
483	struct md_s *sc;
484
485	/* XXX: LOCK(unique unit numbers) */
486	LIST_FOREACH(sc, &md_softc_list, list) {
487		if (sc->unit == unit)
488			break;
489	}
490	/* XXX: UNLOCK(unique unit numbers) */
491	return (sc);
492}
493
494static struct md_s *
495mdnew(int unit)
496{
497	struct md_s *sc;
498	int max = -1;
499
500	/* XXX: LOCK(unique unit numbers) */
501	LIST_FOREACH(sc, &md_softc_list, list) {
502		if (sc->unit == unit) {
503			/* XXX: UNLOCK(unique unit numbers) */
504			return (NULL);
505		}
506		if (sc->unit > max)
507			max = sc->unit;
508	}
509	if (unit == -1)
510		unit = max + 1;
511	if (unit > DKMAXUNIT)
512		return (NULL);
513	MALLOC(sc, struct md_s *,sizeof(*sc), M_MD, M_WAITOK | M_ZERO);
514	sc->unit = unit;
515	LIST_INSERT_HEAD(&md_softc_list, sc, list);
516	/* XXX: UNLOCK(unique unit numbers) */
517	return (sc);
518}
519
520static void
521mddelete(struct md_s *sc)
522{
523
524	devstat_remove_entry(&sc->stats);
525	/* XXX: LOCK(unique unit numbers) */
526	LIST_REMOVE(sc, list);
527	/* XXX: UNLOCK(unique unit numbers) */
528	FREE(sc, M_MD);
529}
530
531static void
532mdinit(struct md_s *sc)
533{
534
535	bioq_init(&sc->bio_queue);
536	devstat_add_entry(&sc->stats, MD_NAME, sc->unit, sc->secsize,
537		DEVSTAT_NO_ORDERED_TAGS,
538		DEVSTAT_TYPE_DIRECT | DEVSTAT_TYPE_IF_OTHER,
539		DEVSTAT_PRIORITY_OTHER);
540	sc->dev = disk_create(sc->unit, &sc->disk, 0, &md_cdevsw, &mddisk_cdevsw);
541	sc->dev->si_drv1 = sc;
542}
543
544/*
545 * XXX: we should check that the range they feed us is mapped.
546 * XXX: we should implement read-only.
547 */
548
549static int
550mdcreate_preload(struct md_ioctl *mdio)
551{
552	struct md_s *sc;
553
554	if (mdio->md_size == 0)
555		return(EINVAL);
556	if (mdio->md_options & ~(MD_AUTOUNIT))
557		return(EINVAL);
558	if (mdio->md_options & MD_AUTOUNIT) {
559		sc = mdnew(-1);
560		if (sc == NULL)
561			return (ENOMEM);
562		mdio->md_unit = sc->unit;
563	} else {
564		sc = mdnew(mdio->md_unit);
565		if (sc == NULL)
566			return (EBUSY);
567	}
568	sc->type = MD_PRELOAD;
569	sc->secsize = DEV_BSIZE;
570	sc->nsect = mdio->md_size;
571	/* Cast to pointer size, then to pointer to avoid warning */
572	sc->pl_ptr = (u_char *)(uintptr_t)mdio->md_base;
573	sc->pl_len = (mdio->md_size << DEV_BSHIFT);
574	mdinit(sc);
575	return (0);
576}
577
578
579static int
580mdcreate_malloc(struct md_ioctl *mdio)
581{
582	struct md_s *sc;
583	unsigned u;
584
585	if (mdio->md_size == 0)
586		return(EINVAL);
587	if (mdio->md_options & ~(MD_AUTOUNIT | MD_COMPRESS | MD_RESERVE))
588		return(EINVAL);
589	/* Compression doesn't make sense if we have reserved space */
590	if (mdio->md_options & MD_RESERVE)
591		mdio->md_options &= ~MD_COMPRESS;
592	if (mdio->md_options & MD_AUTOUNIT) {
593		sc = mdnew(-1);
594		if (sc == NULL)
595			return (ENOMEM);
596		mdio->md_unit = sc->unit;
597	} else {
598		sc = mdnew(mdio->md_unit);
599		if (sc == NULL)
600			return (EBUSY);
601	}
602	sc->type = MD_MALLOC;
603	sc->secsize = DEV_BSIZE;
604	sc->nsect = mdio->md_size;
605	sc->flags = mdio->md_options & MD_COMPRESS;
606	MALLOC(sc->secp, u_char **, sc->nsect * sizeof(u_char *), M_MD, M_WAITOK | M_ZERO);
607	if (mdio->md_options & MD_RESERVE) {
608		for (u = 0; u < sc->nsect; u++)
609			MALLOC(sc->secp[u], u_char *, DEV_BSIZE, M_MDSECT, M_WAITOK | M_ZERO);
610	}
611	printf("%s%d: Malloc disk\n", MD_NAME, sc->unit);
612	mdinit(sc);
613	return (0);
614}
615
616
617static int
618mdsetcred(struct md_s *sc, struct ucred *cred)
619{
620	char *tmpbuf;
621	int error = 0;
622
623	/*
624	 * Set credits in our softc
625	 */
626
627	if (sc->cred)
628		crfree(sc->cred);
629	sc->cred = crdup(cred);
630
631	/*
632	 * Horrible kludge to establish credentials for NFS  XXX.
633	 */
634
635	if (sc->vnode) {
636		struct uio auio;
637		struct iovec aiov;
638
639		tmpbuf = malloc(sc->secsize, M_TEMP, M_WAITOK);
640		bzero(&auio, sizeof(auio));
641
642		aiov.iov_base = tmpbuf;
643		aiov.iov_len = sc->secsize;
644		auio.uio_iov = &aiov;
645		auio.uio_iovcnt = 1;
646		auio.uio_offset = 0;
647		auio.uio_rw = UIO_READ;
648		auio.uio_segflg = UIO_SYSSPACE;
649		auio.uio_resid = aiov.iov_len;
650		vn_lock(sc->vnode, LK_EXCLUSIVE | LK_RETRY, curproc);
651		error = VOP_READ(sc->vnode, &auio, 0, sc->cred);
652		VOP_UNLOCK(sc->vnode, 0, curproc);
653		free(tmpbuf, M_TEMP);
654	}
655	return (error);
656}
657
658static int
659mdcreate_vnode(struct md_ioctl *mdio, struct proc *p)
660{
661	struct md_s *sc;
662	struct vattr vattr;
663	struct nameidata nd;
664	int error, flags;
665
666	if (mdio->md_options & MD_AUTOUNIT) {
667		sc = mdnew(-1);
668		mdio->md_unit = sc->unit;
669	} else {
670		sc = mdnew(mdio->md_unit);
671	}
672	if (sc == NULL)
673		return (EBUSY);
674
675	sc->type = MD_VNODE;
676
677	flags = FREAD|FWRITE;
678	NDINIT(&nd, LOOKUP, FOLLOW, UIO_USERSPACE, mdio->md_file, p);
679	error = vn_open(&nd, &flags, 0);
680	if (error) {
681		if (error != EACCES && error != EPERM && error != EROFS)
682			return (error);
683		flags &= ~FWRITE;
684		sc->flags |= MD_READONLY;
685		NDINIT(&nd, LOOKUP, FOLLOW, UIO_USERSPACE, mdio->md_file, p);
686		error = vn_open(&nd, &flags, 0);
687		if (error)
688			return (error);
689	}
690	NDFREE(&nd, NDF_ONLY_PNBUF);
691	if (nd.ni_vp->v_type != VREG ||
692	    (error = VOP_GETATTR(nd.ni_vp, &vattr, p->p_ucred, p))) {
693		VOP_UNLOCK(nd.ni_vp, 0, p);
694		(void) vn_close(nd.ni_vp, flags, p->p_ucred, p);
695		return (error ? error : EINVAL);
696	}
697	VOP_UNLOCK(nd.ni_vp, 0, p);
698	sc->secsize = DEV_BSIZE;
699	sc->vnode = nd.ni_vp;
700
701	/*
702	 * If the size is specified, override the file attributes.
703	 */
704	if (mdio->md_size)
705		sc->nsect = mdio->md_size;
706	else
707		sc->nsect = vattr.va_size / sc->secsize; /* XXX: round up ? */
708	error = mdsetcred(sc, p->p_ucred);
709	if (error) {
710		(void) vn_close(nd.ni_vp, flags, p->p_ucred, p);
711		return(error);
712	}
713	mdinit(sc);
714	return (0);
715}
716
717static int
718mddestroy(struct md_s *sc, struct md_ioctl *mdio, struct proc *p)
719{
720	unsigned u;
721
722	if (sc->dev != NULL)
723		disk_destroy(sc->dev);
724	if (sc->vnode != NULL)
725		(void)vn_close(sc->vnode, sc->flags & MD_READONLY ?  FREAD : (FREAD|FWRITE), sc->cred, p);
726	if (sc->cred != NULL)
727		crfree(sc->cred);
728	if (sc->object != NULL)
729		vm_pager_deallocate(sc->object);
730	if (sc->secp != NULL) {
731		for (u = 0; u < sc->nsect; u++)
732			if ((uintptr_t)sc->secp[u] > 255)
733				FREE(sc->secp[u], M_MDSECT);
734		FREE(sc->secp, M_MD);
735	}
736	mddelete(sc);
737	return (0);
738}
739
740static int
741mdcreate_swap(struct md_ioctl *mdio, struct proc *p)
742{
743	int error;
744	struct md_s *sc;
745
746	if (mdio->md_options & MD_AUTOUNIT) {
747		sc = mdnew(-1);
748		mdio->md_unit = sc->unit;
749	} else {
750		sc = mdnew(mdio->md_unit);
751	}
752	if (sc == NULL)
753		return (EBUSY);
754
755	sc->type = MD_SWAP;
756
757	/*
758	 * Range check.  Disallow negative sizes or any size less then the
759	 * size of a page.  Then round to a page.
760	 */
761
762	if (mdio->md_size == 0)
763		return(EDOM);
764
765	/*
766	 * Allocate an OBJT_SWAP object.
767	 *
768	 * sc_secsize is PAGE_SIZE'd
769	 *
770	 * mdio->size is in DEV_BSIZE'd chunks.
771	 * Note the truncation.
772	 */
773
774	sc->secsize = PAGE_SIZE;
775	sc->nsect = mdio->md_size / (PAGE_SIZE / DEV_BSIZE);
776	sc->object = vm_pager_allocate(OBJT_SWAP, NULL, sc->secsize * (vm_offset_t)sc->nsect, VM_PROT_DEFAULT, 0);
777	if (mdio->md_options & MD_RESERVE) {
778		if (swap_pager_reserve(sc->object, 0, sc->nsect) < 0) {
779			vm_pager_deallocate(sc->object);
780			sc->object = NULL;
781			return(EDOM);
782		}
783	}
784	error = mdsetcred(sc, p->p_ucred);
785	if (error)
786		mddestroy(sc, mdio, p);
787	else
788		mdinit(sc);
789	return(error);
790}
791
792static int
793mdctlioctl(dev_t dev, u_long cmd, caddr_t addr, int flags, struct proc *p)
794{
795	struct md_ioctl *mdio;
796	struct md_s *sc;
797
798	if (md_debug)
799		printf("mdctlioctl(%s %lx %p %x %p)\n",
800			devtoname(dev), cmd, addr, flags, p);
801
802	mdio = (struct md_ioctl *)addr;
803	switch (cmd) {
804	case MDIOCATTACH:
805		switch (mdio->md_type) {
806		case MD_MALLOC:
807			return(mdcreate_malloc(mdio));
808		case MD_PRELOAD:
809			return(mdcreate_preload(mdio));
810		case MD_VNODE:
811			return(mdcreate_vnode(mdio, p));
812		case MD_SWAP:
813			return(mdcreate_swap(mdio, p));
814		default:
815			return (EINVAL);
816		}
817	case MDIOCDETACH:
818		if (mdio->md_file != NULL)
819			return(EINVAL);
820		if (mdio->md_size != 0)
821			return(EINVAL);
822		if (mdio->md_options != 0)
823			return(EINVAL);
824		sc = mdfind(mdio->md_unit);
825		if (sc == NULL)
826			return (ENOENT);
827		switch(sc->type) {
828		case MD_VNODE:
829		case MD_SWAP:
830		case MD_MALLOC:
831		case MD_PRELOAD:
832			return(mddestroy(sc, mdio, p));
833		default:
834			return (EOPNOTSUPP);
835		}
836	case MDIOCQUERY:
837		sc = mdfind(mdio->md_unit);
838		if (sc == NULL)
839			return (ENOENT);
840		mdio->md_type = sc->type;
841		mdio->md_options = sc->flags;
842		switch (sc->type) {
843		case MD_MALLOC:
844			mdio->md_size = sc->nsect;
845			break;
846		case MD_PRELOAD:
847			mdio->md_size = sc->nsect;
848			(u_char *)(uintptr_t)mdio->md_base = sc->pl_ptr;
849			break;
850		case MD_SWAP:
851			mdio->md_size = sc->nsect * (PAGE_SIZE / DEV_BSIZE);
852			break;
853		case MD_VNODE:
854			mdio->md_size = sc->nsect;
855			/* XXX fill this in */
856			mdio->md_file = NULL;
857			break;
858		}
859		return (0);
860	default:
861		return (ENOIOCTL);
862	};
863	return (ENOIOCTL);
864}
865
866static void
867md_preloaded(u_char *image, unsigned length)
868{
869	struct md_s *sc;
870
871	sc = mdnew(-1);
872	if (sc == NULL)
873		return;
874	sc->type = MD_PRELOAD;
875	sc->secsize = DEV_BSIZE;
876	sc->nsect = length / DEV_BSIZE;
877	sc->pl_ptr = image;
878	sc->pl_len = length;
879	if (sc->unit == 0)
880		mdrootready = 1;
881	mdinit(sc);
882}
883
884static void
885md_drvinit(void *unused)
886{
887
888	caddr_t mod;
889	caddr_t c;
890	u_char *ptr, *name, *type;
891	unsigned len;
892
893#ifdef MD_ROOT_SIZE
894	md_preloaded(mfs_root, MD_ROOT_SIZE*1024);
895#endif
896	mod = NULL;
897	while ((mod = preload_search_next_name(mod)) != NULL) {
898		name = (char *)preload_search_info(mod, MODINFO_NAME);
899		type = (char *)preload_search_info(mod, MODINFO_TYPE);
900		if (name == NULL)
901			continue;
902		if (type == NULL)
903			continue;
904		if (strcmp(type, "md_image") && strcmp(type, "mfs_root"))
905			continue;
906		c = preload_search_info(mod, MODINFO_ADDR);
907		ptr = *(u_char **)c;
908		c = preload_search_info(mod, MODINFO_SIZE);
909		len = *(unsigned *)c;
910		printf("md%d: Preloaded image <%s> %d bytes at %p\n",
911		   mdunits, name, len, ptr);
912		md_preloaded(ptr, len);
913	}
914	status_dev = make_dev(&mdctl_cdevsw, 0xffff00ff, UID_ROOT, GID_WHEEL, 0600, "mdctl");
915}
916
917static int
918md_modevent(module_t mod, int type, void *data)
919{
920        switch (type) {
921        case MOD_LOAD:
922		md_drvinit(NULL);
923                break;
924        case MOD_UNLOAD:
925		if (!LIST_EMPTY(&md_softc_list))
926			return EBUSY;
927                if (status_dev)
928                        destroy_dev(status_dev);
929                status_dev = 0;
930                break;
931        default:
932                break;
933        }
934        return 0;
935}
936
937static moduledata_t md_mod = {
938        "md",
939        md_modevent,
940        NULL
941};
942DECLARE_MODULE(md, md_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE+CDEV_MAJOR);
943MODULE_VERSION(md, MD_MODVER);
944
945
946#ifdef MD_ROOT
947static void
948md_takeroot(void *junk)
949{
950	if (mdrootready)
951		rootdevnames[0] = "ufs:/dev/md0c";
952}
953
954SYSINIT(md_root, SI_SUB_MOUNT_ROOT, SI_ORDER_FIRST, md_takeroot, NULL);
955#endif
956
957