md.c revision 248518
1287020Sdelphij/*-
2267460Sedwin * ----------------------------------------------------------------------------
3287020Sdelphij * "THE BEER-WARE LICENSE" (Revision 42):
42742Swollman * <phk@FreeBSD.ORG> wrote this file.  As long as you retain this notice you
5287020Sdelphij * can do whatever you want with this stuff. If we meet some day, and you think
6352354Sphilip * this stuff is worth it, you can buy me a beer in return.   Poul-Henning Kamp
7339630Sphilip * ----------------------------------------------------------------------------
8352354Sphilip *
9368822Sphilip * $FreeBSD: head/sys/dev/md/md.c 248518 2013-03-19 14:53:23Z kib $
10368822Sphilip *
11368822Sphilip */
12368822Sphilip
13287020Sdelphij/*-
14287020Sdelphij * The following functions are based in the vn(4) driver: mdstart_swap(),
15339630Sphilip * mdstart_vnode(), mdcreate_swap(), mdcreate_vnode() and mddestroy(),
16287020Sdelphij * and as such under the following copyright:
17352354Sphilip *
18352354Sphilip * Copyright (c) 1988 University of Utah.
19352354Sphilip * Copyright (c) 1990, 1993
20352354Sphilip *	The Regents of the University of California.  All rights reserved.
21352354Sphilip * Copyright (c) 2013 The FreeBSD Foundation
22352354Sphilip * All rights reserved.
23287020Sdelphij *
24352354Sphilip * This code is derived from software contributed to Berkeley by
25339630Sphilip * the Systems Programming Group of the University of Utah Computer
26339630Sphilip * Science Department.
27339630Sphilip *
28325159Sphilip * Portions of this software were developed by Konstantin Belousov
29339630Sphilip * under sponsorship from the FreeBSD Foundation.
30342668Sphilip *
31352354Sphilip * Redistribution and use in source and binary forms, with or without
32352354Sphilip * modification, are permitted provided that the following conditions
33352354Sphilip * are met:
34342668Sphilip * 1. Redistributions of source code must retain the above copyright
35342668Sphilip *    notice, this list of conditions and the following disclaimer.
362742Swollman * 2. Redistributions in binary form must reproduce the above copyright
37352354Sphilip *    notice, this list of conditions and the following disclaimer in the
38352354Sphilip *    documentation and/or other materials provided with the distribution.
39352354Sphilip * 4. Neither the name of the University nor the names of its contributors
40352354Sphilip *    may be used to endorse or promote products derived from this software
41352354Sphilip *    without specific prior written permission.
42352354Sphilip *
432742Swollman * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
442742Swollman * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
452742Swollman * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
462742Swollman * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
472742Swollman * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
482742Swollman * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
492742Swollman * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
502742Swollman * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
512742Swollman * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
522742Swollman * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
532742Swollman * SUCH DAMAGE.
542742Swollman *
552742Swollman * from: Utah Hdr: vn.c 1.13 94/04/02
562742Swollman *
572742Swollman *	from: @(#)vn.c	8.6 (Berkeley) 4/1/94
582742Swollman * From: src/sys/dev/vn/vn.c,v 1.122 2000/12/16 16:06:03
592742Swollman */
602742Swollman
612742Swollman#include "opt_geom.h"
6239871Sphk#include "opt_md.h"
6339871Sphk
6439898Sphk#include <sys/param.h>
65147771Sphk#include <sys/systm.h>
66181424Sedwin#include <sys/bio.h>
67233445Sedwin#include <sys/buf.h>
68287020Sdelphij#include <sys/conf.h>
69307361Sbapt#include <sys/devicestat.h>
70267460Sedwin#include <sys/fcntl.h>
71360362Sphilip#include <sys/kernel.h>
72360362Sphilip#include <sys/kthread.h>
73360362Sphilip#include <sys/limits.h>
74360362Sphilip#include <sys/linker.h>
75369144Sgit2svn#include <sys/lock.h>
76360362Sphilip#include <sys/malloc.h>
77339630Sphilip#include <sys/mdioctl.h>
78352354Sphilip#include <sys/mount.h>
79369144Sgit2svn#include <sys/mutex.h>
80339630Sphilip#include <sys/sx.h>
81369144Sgit2svn#include <sys/namei.h>
82369144Sgit2svn#include <sys/proc.h>
83#include <sys/queue.h>
84#include <sys/rwlock.h>
85#include <sys/sbuf.h>
86#include <sys/sched.h>
87#include <sys/sf_buf.h>
88#include <sys/sysctl.h>
89#include <sys/vnode.h>
90
91#include <geom/geom.h>
92
93#include <vm/vm.h>
94#include <vm/vm_param.h>
95#include <vm/vm_object.h>
96#include <vm/vm_page.h>
97#include <vm/vm_pager.h>
98#include <vm/swap_pager.h>
99#include <vm/uma.h>
100
101#define MD_MODVER 1
102
103#define MD_SHUTDOWN	0x10000		/* Tell worker thread to terminate. */
104#define	MD_EXITING	0x20000		/* Worker thread is exiting. */
105
106#ifndef MD_NSECT
107#define MD_NSECT (10000 * 2)
108#endif
109
110static MALLOC_DEFINE(M_MD, "md_disk", "Memory Disk");
111static MALLOC_DEFINE(M_MDSECT, "md_sectors", "Memory Disk Sectors");
112
113static int md_debug;
114SYSCTL_INT(_debug, OID_AUTO, mddebug, CTLFLAG_RW, &md_debug, 0,
115    "Enable md(4) debug messages");
116static int md_malloc_wait;
117SYSCTL_INT(_vm, OID_AUTO, md_malloc_wait, CTLFLAG_RW, &md_malloc_wait, 0,
118    "Allow malloc to wait for memory allocations");
119
120#if defined(MD_ROOT) && !defined(MD_ROOT_FSTYPE)
121#define	MD_ROOT_FSTYPE	"ufs"
122#endif
123
124#if defined(MD_ROOT) && defined(MD_ROOT_SIZE)
125/*
126 * Preloaded image gets put here.
127 * Applications that patch the object with the image can determine
128 * the size looking at the start and end markers (strings),
129 * so we want them contiguous.
130 */
131static struct {
132	u_char start[MD_ROOT_SIZE*1024];
133	u_char end[128];
134} mfs_root = {
135	.start = "MFS Filesystem goes here",
136	.end = "MFS Filesystem had better STOP here",
137};
138#endif
139
140static g_init_t g_md_init;
141static g_fini_t g_md_fini;
142static g_start_t g_md_start;
143static g_access_t g_md_access;
144static void g_md_dumpconf(struct sbuf *sb, const char *indent,
145    struct g_geom *gp, struct g_consumer *cp __unused, struct g_provider *pp);
146
147static struct cdev *status_dev = 0;
148static struct sx md_sx;
149static struct unrhdr *md_uh;
150
151static d_ioctl_t mdctlioctl;
152
153static struct cdevsw mdctl_cdevsw = {
154	.d_version =	D_VERSION,
155	.d_ioctl =	mdctlioctl,
156	.d_name =	MD_NAME,
157};
158
159struct g_class g_md_class = {
160	.name = "MD",
161	.version = G_VERSION,
162	.init = g_md_init,
163	.fini = g_md_fini,
164	.start = g_md_start,
165	.access = g_md_access,
166	.dumpconf = g_md_dumpconf,
167};
168
169DECLARE_GEOM_CLASS(g_md_class, g_md);
170
171
172static LIST_HEAD(, md_s) md_softc_list = LIST_HEAD_INITIALIZER(md_softc_list);
173
174#define NINDIR	(PAGE_SIZE / sizeof(uintptr_t))
175#define NMASK	(NINDIR-1)
176static int nshift;
177
178static int md_vnode_pbuf_freecnt;
179
180struct indir {
181	uintptr_t	*array;
182	u_int		total;
183	u_int		used;
184	u_int		shift;
185};
186
187struct md_s {
188	int unit;
189	LIST_ENTRY(md_s) list;
190	struct bio_queue_head bio_queue;
191	struct mtx queue_mtx;
192	struct cdev *dev;
193	enum md_types type;
194	off_t mediasize;
195	unsigned sectorsize;
196	unsigned opencount;
197	unsigned fwheads;
198	unsigned fwsectors;
199	unsigned flags;
200	char name[20];
201	struct proc *procp;
202	struct g_geom *gp;
203	struct g_provider *pp;
204	int (*start)(struct md_s *sc, struct bio *bp);
205	struct devstat *devstat;
206
207	/* MD_MALLOC related fields */
208	struct indir *indir;
209	uma_zone_t uma;
210
211	/* MD_PRELOAD related fields */
212	u_char *pl_ptr;
213	size_t pl_len;
214
215	/* MD_VNODE related fields */
216	struct vnode *vnode;
217	char file[PATH_MAX];
218	struct ucred *cred;
219
220	/* MD_SWAP related fields */
221	vm_object_t object;
222};
223
224static struct indir *
225new_indir(u_int shift)
226{
227	struct indir *ip;
228
229	ip = malloc(sizeof *ip, M_MD, (md_malloc_wait ? M_WAITOK : M_NOWAIT)
230	    | M_ZERO);
231	if (ip == NULL)
232		return (NULL);
233	ip->array = malloc(sizeof(uintptr_t) * NINDIR,
234	    M_MDSECT, (md_malloc_wait ? M_WAITOK : M_NOWAIT) | M_ZERO);
235	if (ip->array == NULL) {
236		free(ip, M_MD);
237		return (NULL);
238	}
239	ip->total = NINDIR;
240	ip->shift = shift;
241	return (ip);
242}
243
244static void
245del_indir(struct indir *ip)
246{
247
248	free(ip->array, M_MDSECT);
249	free(ip, M_MD);
250}
251
252static void
253destroy_indir(struct md_s *sc, struct indir *ip)
254{
255	int i;
256
257	for (i = 0; i < NINDIR; i++) {
258		if (!ip->array[i])
259			continue;
260		if (ip->shift)
261			destroy_indir(sc, (struct indir*)(ip->array[i]));
262		else if (ip->array[i] > 255)
263			uma_zfree(sc->uma, (void *)(ip->array[i]));
264	}
265	del_indir(ip);
266}
267
268/*
269 * This function does the math and allocates the top level "indir" structure
270 * for a device of "size" sectors.
271 */
272
273static struct indir *
274dimension(off_t size)
275{
276	off_t rcnt;
277	struct indir *ip;
278	int layer;
279
280	rcnt = size;
281	layer = 0;
282	while (rcnt > NINDIR) {
283		rcnt /= NINDIR;
284		layer++;
285	}
286
287	/*
288	 * XXX: the top layer is probably not fully populated, so we allocate
289	 * too much space for ip->array in here.
290	 */
291	ip = malloc(sizeof *ip, M_MD, M_WAITOK | M_ZERO);
292	ip->array = malloc(sizeof(uintptr_t) * NINDIR,
293	    M_MDSECT, M_WAITOK | M_ZERO);
294	ip->total = NINDIR;
295	ip->shift = layer * nshift;
296	return (ip);
297}
298
299/*
300 * Read a given sector
301 */
302
303static uintptr_t
304s_read(struct indir *ip, off_t offset)
305{
306	struct indir *cip;
307	int idx;
308	uintptr_t up;
309
310	if (md_debug > 1)
311		printf("s_read(%jd)\n", (intmax_t)offset);
312	up = 0;
313	for (cip = ip; cip != NULL;) {
314		if (cip->shift) {
315			idx = (offset >> cip->shift) & NMASK;
316			up = cip->array[idx];
317			cip = (struct indir *)up;
318			continue;
319		}
320		idx = offset & NMASK;
321		return (cip->array[idx]);
322	}
323	return (0);
324}
325
326/*
327 * Write a given sector, prune the tree if the value is 0
328 */
329
330static int
331s_write(struct indir *ip, off_t offset, uintptr_t ptr)
332{
333	struct indir *cip, *lip[10];
334	int idx, li;
335	uintptr_t up;
336
337	if (md_debug > 1)
338		printf("s_write(%jd, %p)\n", (intmax_t)offset, (void *)ptr);
339	up = 0;
340	li = 0;
341	cip = ip;
342	for (;;) {
343		lip[li++] = cip;
344		if (cip->shift) {
345			idx = (offset >> cip->shift) & NMASK;
346			up = cip->array[idx];
347			if (up != 0) {
348				cip = (struct indir *)up;
349				continue;
350			}
351			/* Allocate branch */
352			cip->array[idx] =
353			    (uintptr_t)new_indir(cip->shift - nshift);
354			if (cip->array[idx] == 0)
355				return (ENOSPC);
356			cip->used++;
357			up = cip->array[idx];
358			cip = (struct indir *)up;
359			continue;
360		}
361		/* leafnode */
362		idx = offset & NMASK;
363		up = cip->array[idx];
364		if (up != 0)
365			cip->used--;
366		cip->array[idx] = ptr;
367		if (ptr != 0)
368			cip->used++;
369		break;
370	}
371	if (cip->used != 0 || li == 1)
372		return (0);
373	li--;
374	while (cip->used == 0 && cip != ip) {
375		li--;
376		idx = (offset >> lip[li]->shift) & NMASK;
377		up = lip[li]->array[idx];
378		KASSERT(up == (uintptr_t)cip, ("md screwed up"));
379		del_indir(cip);
380		lip[li]->array[idx] = 0;
381		lip[li]->used--;
382		cip = lip[li];
383	}
384	return (0);
385}
386
387
388static int
389g_md_access(struct g_provider *pp, int r, int w, int e)
390{
391	struct md_s *sc;
392
393	sc = pp->geom->softc;
394	if (sc == NULL) {
395		if (r <= 0 && w <= 0 && e <= 0)
396			return (0);
397		return (ENXIO);
398	}
399	r += pp->acr;
400	w += pp->acw;
401	e += pp->ace;
402	if ((sc->flags & MD_READONLY) != 0 && w > 0)
403		return (EROFS);
404	if ((pp->acr + pp->acw + pp->ace) == 0 && (r + w + e) > 0) {
405		sc->opencount = 1;
406	} else if ((pp->acr + pp->acw + pp->ace) > 0 && (r + w + e) == 0) {
407		sc->opencount = 0;
408	}
409	return (0);
410}
411
412static void
413g_md_start(struct bio *bp)
414{
415	struct md_s *sc;
416
417	sc = bp->bio_to->geom->softc;
418	if ((bp->bio_cmd == BIO_READ) || (bp->bio_cmd == BIO_WRITE))
419		devstat_start_transaction_bio(sc->devstat, bp);
420	mtx_lock(&sc->queue_mtx);
421	bioq_disksort(&sc->bio_queue, bp);
422	mtx_unlock(&sc->queue_mtx);
423	wakeup(sc);
424}
425
426#define	MD_MALLOC_MOVE_ZERO	1
427#define	MD_MALLOC_MOVE_FILL	2
428#define	MD_MALLOC_MOVE_READ	3
429#define	MD_MALLOC_MOVE_WRITE	4
430#define	MD_MALLOC_MOVE_CMP	5
431
432static int
433md_malloc_move(vm_page_t **mp, int *ma_offs, unsigned sectorsize,
434    void *ptr, u_char fill, int op)
435{
436	struct sf_buf *sf;
437	vm_page_t m, *mp1;
438	char *p, first;
439	off_t *uc;
440	unsigned n;
441	int error, i, ma_offs1, sz, first_read;
442
443	m = NULL;
444	error = 0;
445	sf = NULL;
446	/* if (op == MD_MALLOC_MOVE_CMP) { gcc */
447		first = 0;
448		first_read = 0;
449		uc = ptr;
450		mp1 = *mp;
451		ma_offs1 = *ma_offs;
452	/* } */
453	sched_pin();
454	for (n = sectorsize; n != 0; n -= sz) {
455		sz = imin(PAGE_SIZE - *ma_offs, n);
456		if (m != **mp) {
457			if (sf != NULL)
458				sf_buf_free(sf);
459			m = **mp;
460			sf = sf_buf_alloc(m, SFB_CPUPRIVATE |
461			    (md_malloc_wait ? 0 : SFB_NOWAIT));
462			if (sf == NULL) {
463				error = ENOMEM;
464				break;
465			}
466		}
467		p = (char *)sf_buf_kva(sf) + *ma_offs;
468		switch (op) {
469		case MD_MALLOC_MOVE_ZERO:
470			bzero(p, sz);
471			break;
472		case MD_MALLOC_MOVE_FILL:
473			memset(p, fill, sz);
474			break;
475		case MD_MALLOC_MOVE_READ:
476			bcopy(ptr, p, sz);
477			cpu_flush_dcache(p, sz);
478			break;
479		case MD_MALLOC_MOVE_WRITE:
480			bcopy(p, ptr, sz);
481			break;
482		case MD_MALLOC_MOVE_CMP:
483			for (i = 0; i < sz; i++, p++) {
484				if (!first_read) {
485					*uc = (u_char)*p;
486					first = *p;
487					first_read = 1;
488				} else if (*p != first) {
489					error = EDOOFUS;
490					break;
491				}
492			}
493			break;
494		default:
495			KASSERT(0, ("md_malloc_move unknown op %d\n", op));
496			break;
497		}
498		if (error != 0)
499			break;
500		*ma_offs += sz;
501		*ma_offs %= PAGE_SIZE;
502		if (*ma_offs == 0)
503			(*mp)++;
504		ptr = (char *)ptr + sz;
505	}
506
507	if (sf != NULL)
508		sf_buf_free(sf);
509	sched_unpin();
510	if (op == MD_MALLOC_MOVE_CMP && error != 0) {
511		*mp = mp1;
512		*ma_offs = ma_offs1;
513	}
514	return (error);
515}
516
517static int
518mdstart_malloc(struct md_s *sc, struct bio *bp)
519{
520	u_char *dst;
521	vm_page_t *m;
522	int i, error, error1, ma_offs, notmapped;
523	off_t secno, nsec, uc;
524	uintptr_t sp, osp;
525
526	switch (bp->bio_cmd) {
527	case BIO_READ:
528	case BIO_WRITE:
529	case BIO_DELETE:
530		break;
531	default:
532		return (EOPNOTSUPP);
533	}
534
535	notmapped = (bp->bio_flags & BIO_UNMAPPED) != 0;
536	if (notmapped) {
537		m = bp->bio_ma;
538		ma_offs = bp->bio_ma_offset;
539		dst = NULL;
540	} else {
541		dst = bp->bio_data;
542	}
543
544	nsec = bp->bio_length / sc->sectorsize;
545	secno = bp->bio_offset / sc->sectorsize;
546	error = 0;
547	while (nsec--) {
548		osp = s_read(sc->indir, secno);
549		if (bp->bio_cmd == BIO_DELETE) {
550			if (osp != 0)
551				error = s_write(sc->indir, secno, 0);
552		} else if (bp->bio_cmd == BIO_READ) {
553			if (osp == 0) {
554				if (notmapped) {
555					error = md_malloc_move(&m, &ma_offs,
556					    sc->sectorsize, NULL, 0,
557					    MD_MALLOC_MOVE_ZERO);
558				} else
559					bzero(dst, sc->sectorsize);
560			} else if (osp <= 255) {
561				if (notmapped) {
562					error = md_malloc_move(&m, &ma_offs,
563					    sc->sectorsize, NULL, osp,
564					    MD_MALLOC_MOVE_FILL);
565				} else
566					memset(dst, osp, sc->sectorsize);
567			} else {
568				if (notmapped) {
569					error = md_malloc_move(&m, &ma_offs,
570					    sc->sectorsize, (void *)osp, 0,
571					    MD_MALLOC_MOVE_READ);
572				} else {
573					bcopy((void *)osp, dst, sc->sectorsize);
574					cpu_flush_dcache(dst, sc->sectorsize);
575				}
576			}
577			osp = 0;
578		} else if (bp->bio_cmd == BIO_WRITE) {
579			if (sc->flags & MD_COMPRESS) {
580				if (notmapped) {
581					error1 = md_malloc_move(&m, &ma_offs,
582					    sc->sectorsize, &uc, 0,
583					    MD_MALLOC_MOVE_CMP);
584					i = error1 == 0 ? sc->sectorsize : 0;
585				} else {
586					uc = dst[0];
587					for (i = 1; i < sc->sectorsize; i++) {
588						if (dst[i] != uc)
589							break;
590					}
591				}
592			} else {
593				i = 0;
594				uc = 0;
595			}
596			if (i == sc->sectorsize) {
597				if (osp != uc)
598					error = s_write(sc->indir, secno, uc);
599			} else {
600				if (osp <= 255) {
601					sp = (uintptr_t)uma_zalloc(sc->uma,
602					    md_malloc_wait ? M_WAITOK :
603					    M_NOWAIT);
604					if (sp == 0) {
605						error = ENOSPC;
606						break;
607					}
608					if (notmapped) {
609						error = md_malloc_move(&m,
610						    &ma_offs, sc->sectorsize,
611						    (void *)sp, 0,
612						    MD_MALLOC_MOVE_WRITE);
613					} else {
614						bcopy(dst, (void *)sp,
615						    sc->sectorsize);
616					}
617					error = s_write(sc->indir, secno, sp);
618				} else {
619					if (notmapped) {
620						error = md_malloc_move(&m,
621						    &ma_offs, sc->sectorsize,
622						    (void *)osp, 0,
623						    MD_MALLOC_MOVE_WRITE);
624					} else {
625						bcopy(dst, (void *)osp,
626						    sc->sectorsize);
627					}
628					osp = 0;
629				}
630			}
631		} else {
632			error = EOPNOTSUPP;
633		}
634		if (osp > 255)
635			uma_zfree(sc->uma, (void*)osp);
636		if (error != 0)
637			break;
638		secno++;
639		if (!notmapped)
640			dst += sc->sectorsize;
641	}
642	bp->bio_resid = 0;
643	return (error);
644}
645
646static int
647mdstart_preload(struct md_s *sc, struct bio *bp)
648{
649
650	switch (bp->bio_cmd) {
651	case BIO_READ:
652		bcopy(sc->pl_ptr + bp->bio_offset, bp->bio_data,
653		    bp->bio_length);
654		cpu_flush_dcache(bp->bio_data, bp->bio_length);
655		break;
656	case BIO_WRITE:
657		bcopy(bp->bio_data, sc->pl_ptr + bp->bio_offset,
658		    bp->bio_length);
659		break;
660	}
661	bp->bio_resid = 0;
662	return (0);
663}
664
665static int
666mdstart_vnode(struct md_s *sc, struct bio *bp)
667{
668	int error;
669	struct uio auio;
670	struct iovec aiov;
671	struct mount *mp;
672	struct vnode *vp;
673	struct buf *pb;
674	struct thread *td;
675	off_t end, zerosize;
676
677	switch (bp->bio_cmd) {
678	case BIO_READ:
679	case BIO_WRITE:
680	case BIO_DELETE:
681	case BIO_FLUSH:
682		break;
683	default:
684		return (EOPNOTSUPP);
685	}
686
687	td = curthread;
688	vp = sc->vnode;
689
690	/*
691	 * VNODE I/O
692	 *
693	 * If an error occurs, we set BIO_ERROR but we do not set
694	 * B_INVAL because (for a write anyway), the buffer is
695	 * still valid.
696	 */
697
698	if (bp->bio_cmd == BIO_FLUSH) {
699		(void) vn_start_write(vp, &mp, V_WAIT);
700		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
701		error = VOP_FSYNC(vp, MNT_WAIT, td);
702		VOP_UNLOCK(vp, 0);
703		vn_finished_write(mp);
704		return (error);
705	}
706
707	bzero(&auio, sizeof(auio));
708
709	/*
710	 * Special case for BIO_DELETE.  On the surface, this is very
711	 * similar to BIO_WRITE, except that we write from our own
712	 * fixed-length buffer, so we have to loop.  The net result is
713	 * that the two cases end up having very little in common.
714	 */
715	if (bp->bio_cmd == BIO_DELETE) {
716		zerosize = ZERO_REGION_SIZE -
717		    (ZERO_REGION_SIZE % sc->sectorsize);
718		auio.uio_iov = &aiov;
719		auio.uio_iovcnt = 1;
720		auio.uio_offset = (vm_ooffset_t)bp->bio_offset;
721		auio.uio_segflg = UIO_SYSSPACE;
722		auio.uio_rw = UIO_WRITE;
723		auio.uio_td = td;
724		end = bp->bio_offset + bp->bio_length;
725		(void) vn_start_write(vp, &mp, V_WAIT);
726		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
727		error = 0;
728		while (auio.uio_offset < end) {
729			aiov.iov_base = __DECONST(void *, zero_region);
730			aiov.iov_len = end - auio.uio_offset;
731			if (aiov.iov_len > zerosize)
732				aiov.iov_len = zerosize;
733			auio.uio_resid = aiov.iov_len;
734			error = VOP_WRITE(vp, &auio,
735			    sc->flags & MD_ASYNC ? 0 : IO_SYNC, sc->cred);
736			if (error != 0)
737				break;
738		}
739		VOP_UNLOCK(vp, 0);
740		vn_finished_write(mp);
741		bp->bio_resid = end - auio.uio_offset;
742		return (error);
743	}
744
745	KASSERT(bp->bio_length <= MAXPHYS, ("bio_length %jd",
746	    (uintmax_t)bp->bio_length));
747	if ((bp->bio_flags & BIO_UNMAPPED) == 0) {
748		pb = NULL;
749		aiov.iov_base = bp->bio_data;
750	} else {
751		pb = getpbuf(&md_vnode_pbuf_freecnt);
752		pmap_qenter((vm_offset_t)pb->b_data, bp->bio_ma, bp->bio_ma_n);
753		aiov.iov_base = (void *)((vm_offset_t)pb->b_data +
754		    bp->bio_ma_offset);
755	}
756	aiov.iov_len = bp->bio_length;
757	auio.uio_iov = &aiov;
758	auio.uio_iovcnt = 1;
759	auio.uio_offset = (vm_ooffset_t)bp->bio_offset;
760	auio.uio_segflg = UIO_SYSSPACE;
761	if (bp->bio_cmd == BIO_READ)
762		auio.uio_rw = UIO_READ;
763	else if (bp->bio_cmd == BIO_WRITE)
764		auio.uio_rw = UIO_WRITE;
765	else
766		panic("wrong BIO_OP in mdstart_vnode");
767	auio.uio_resid = bp->bio_length;
768	auio.uio_td = td;
769	/*
770	 * When reading set IO_DIRECT to try to avoid double-caching
771	 * the data.  When writing IO_DIRECT is not optimal.
772	 */
773	if (bp->bio_cmd == BIO_READ) {
774		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
775		error = VOP_READ(vp, &auio, IO_DIRECT, sc->cred);
776		VOP_UNLOCK(vp, 0);
777	} else {
778		(void) vn_start_write(vp, &mp, V_WAIT);
779		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
780		error = VOP_WRITE(vp, &auio, sc->flags & MD_ASYNC ? 0 : IO_SYNC,
781		    sc->cred);
782		VOP_UNLOCK(vp, 0);
783		vn_finished_write(mp);
784	}
785	if ((bp->bio_flags & BIO_UNMAPPED) != 0) {
786		pmap_qremove((vm_offset_t)pb->b_data, bp->bio_ma_n);
787		relpbuf(pb, &md_vnode_pbuf_freecnt);
788	}
789	bp->bio_resid = auio.uio_resid;
790	return (error);
791}
792
793static int
794mdstart_swap(struct md_s *sc, struct bio *bp)
795{
796	vm_page_t m;
797	u_char *p;
798	vm_pindex_t i, lastp;
799	int rv, ma_offs, offs, len, lastend;
800
801	switch (bp->bio_cmd) {
802	case BIO_READ:
803	case BIO_WRITE:
804	case BIO_DELETE:
805		break;
806	default:
807		return (EOPNOTSUPP);
808	}
809
810	p = bp->bio_data;
811	ma_offs = (bp->bio_flags & BIO_UNMAPPED) == 0 ? 0 : bp->bio_ma_offset;
812
813	/*
814	 * offs is the offset at which to start operating on the
815	 * next (ie, first) page.  lastp is the last page on
816	 * which we're going to operate.  lastend is the ending
817	 * position within that last page (ie, PAGE_SIZE if
818	 * we're operating on complete aligned pages).
819	 */
820	offs = bp->bio_offset % PAGE_SIZE;
821	lastp = (bp->bio_offset + bp->bio_length - 1) / PAGE_SIZE;
822	lastend = (bp->bio_offset + bp->bio_length - 1) % PAGE_SIZE + 1;
823
824	rv = VM_PAGER_OK;
825	VM_OBJECT_WLOCK(sc->object);
826	vm_object_pip_add(sc->object, 1);
827	for (i = bp->bio_offset / PAGE_SIZE; i <= lastp; i++) {
828		len = ((i == lastp) ? lastend : PAGE_SIZE) - offs;
829		m = vm_page_grab(sc->object, i, VM_ALLOC_NORMAL |
830		    VM_ALLOC_RETRY);
831		if (bp->bio_cmd == BIO_READ) {
832			if (m->valid != VM_PAGE_BITS_ALL)
833				rv = vm_pager_get_pages(sc->object, &m, 1, 0);
834			if (rv == VM_PAGER_ERROR) {
835				vm_page_wakeup(m);
836				break;
837			} else if (rv == VM_PAGER_FAIL) {
838				/*
839				 * Pager does not have the page.  Zero
840				 * the allocated page, and mark it as
841				 * valid. Do not set dirty, the page
842				 * can be recreated if thrown out.
843				 */
844				pmap_zero_page(m);
845				m->valid = VM_PAGE_BITS_ALL;
846			}
847			if ((bp->bio_flags & BIO_UNMAPPED) != 0) {
848				pmap_copy_pages(&m, offs, bp->bio_ma,
849				    ma_offs, len);
850			} else {
851				physcopyout(VM_PAGE_TO_PHYS(m) + offs, p, len);
852				cpu_flush_dcache(p, len);
853			}
854		} else if (bp->bio_cmd == BIO_WRITE) {
855			if (len != PAGE_SIZE && m->valid != VM_PAGE_BITS_ALL)
856				rv = vm_pager_get_pages(sc->object, &m, 1, 0);
857			if (rv == VM_PAGER_ERROR) {
858				vm_page_wakeup(m);
859				break;
860			}
861			if ((bp->bio_flags & BIO_UNMAPPED) != 0) {
862				pmap_copy_pages(bp->bio_ma, ma_offs, &m,
863				    offs, len);
864			} else {
865				physcopyin(p, VM_PAGE_TO_PHYS(m) + offs, len);
866			}
867			m->valid = VM_PAGE_BITS_ALL;
868		} else if (bp->bio_cmd == BIO_DELETE) {
869			if (len != PAGE_SIZE && m->valid != VM_PAGE_BITS_ALL)
870				rv = vm_pager_get_pages(sc->object, &m, 1, 0);
871			if (rv == VM_PAGER_ERROR) {
872				vm_page_wakeup(m);
873				break;
874			}
875			if (len != PAGE_SIZE) {
876				pmap_zero_page_area(m, offs, len);
877				vm_page_clear_dirty(m, offs, len);
878				m->valid = VM_PAGE_BITS_ALL;
879			} else
880				vm_pager_page_unswapped(m);
881		}
882		vm_page_wakeup(m);
883		vm_page_lock(m);
884		if (bp->bio_cmd == BIO_DELETE && len == PAGE_SIZE)
885			vm_page_free(m);
886		else
887			vm_page_activate(m);
888		vm_page_unlock(m);
889		if (bp->bio_cmd == BIO_WRITE)
890			vm_page_dirty(m);
891
892		/* Actions on further pages start at offset 0 */
893		p += PAGE_SIZE - offs;
894		offs = 0;
895		ma_offs += len;
896	}
897	vm_object_pip_subtract(sc->object, 1);
898	VM_OBJECT_WUNLOCK(sc->object);
899	return (rv != VM_PAGER_ERROR ? 0 : ENOSPC);
900}
901
902static void
903md_kthread(void *arg)
904{
905	struct md_s *sc;
906	struct bio *bp;
907	int error;
908
909	sc = arg;
910	thread_lock(curthread);
911	sched_prio(curthread, PRIBIO);
912	thread_unlock(curthread);
913	if (sc->type == MD_VNODE)
914		curthread->td_pflags |= TDP_NORUNNINGBUF;
915
916	for (;;) {
917		mtx_lock(&sc->queue_mtx);
918		if (sc->flags & MD_SHUTDOWN) {
919			sc->flags |= MD_EXITING;
920			mtx_unlock(&sc->queue_mtx);
921			kproc_exit(0);
922		}
923		bp = bioq_takefirst(&sc->bio_queue);
924		if (!bp) {
925			msleep(sc, &sc->queue_mtx, PRIBIO | PDROP, "mdwait", 0);
926			continue;
927		}
928		mtx_unlock(&sc->queue_mtx);
929		if (bp->bio_cmd == BIO_GETATTR) {
930			if ((sc->fwsectors && sc->fwheads &&
931			    (g_handleattr_int(bp, "GEOM::fwsectors",
932			    sc->fwsectors) ||
933			    g_handleattr_int(bp, "GEOM::fwheads",
934			    sc->fwheads))) ||
935			    g_handleattr_int(bp, "GEOM::candelete", 1))
936				error = -1;
937			else
938				error = EOPNOTSUPP;
939		} else {
940			error = sc->start(sc, bp);
941		}
942
943		if (error != -1) {
944			bp->bio_completed = bp->bio_length;
945			if ((bp->bio_cmd == BIO_READ) || (bp->bio_cmd == BIO_WRITE))
946				devstat_end_transaction_bio(sc->devstat, bp);
947			g_io_deliver(bp, error);
948		}
949	}
950}
951
952static struct md_s *
953mdfind(int unit)
954{
955	struct md_s *sc;
956
957	LIST_FOREACH(sc, &md_softc_list, list) {
958		if (sc->unit == unit)
959			break;
960	}
961	return (sc);
962}
963
964static struct md_s *
965mdnew(int unit, int *errp, enum md_types type)
966{
967	struct md_s *sc;
968	int error;
969
970	*errp = 0;
971	if (unit == -1)
972		unit = alloc_unr(md_uh);
973	else
974		unit = alloc_unr_specific(md_uh, unit);
975
976	if (unit == -1) {
977		*errp = EBUSY;
978		return (NULL);
979	}
980
981	sc = (struct md_s *)malloc(sizeof *sc, M_MD, M_WAITOK | M_ZERO);
982	sc->type = type;
983	bioq_init(&sc->bio_queue);
984	mtx_init(&sc->queue_mtx, "md bio queue", NULL, MTX_DEF);
985	sc->unit = unit;
986	sprintf(sc->name, "md%d", unit);
987	LIST_INSERT_HEAD(&md_softc_list, sc, list);
988	error = kproc_create(md_kthread, sc, &sc->procp, 0, 0,"%s", sc->name);
989	if (error == 0)
990		return (sc);
991	LIST_REMOVE(sc, list);
992	mtx_destroy(&sc->queue_mtx);
993	free_unr(md_uh, sc->unit);
994	free(sc, M_MD);
995	*errp = error;
996	return (NULL);
997}
998
999static void
1000mdinit(struct md_s *sc)
1001{
1002	struct g_geom *gp;
1003	struct g_provider *pp;
1004
1005	g_topology_lock();
1006	gp = g_new_geomf(&g_md_class, "md%d", sc->unit);
1007	gp->softc = sc;
1008	pp = g_new_providerf(gp, "md%d", sc->unit);
1009	pp->mediasize = sc->mediasize;
1010	pp->sectorsize = sc->sectorsize;
1011	pp->flags |= G_PF_ACCEPT_UNMAPPED;
1012	sc->gp = gp;
1013	sc->pp = pp;
1014	g_error_provider(pp, 0);
1015	g_topology_unlock();
1016	sc->devstat = devstat_new_entry("md", sc->unit, sc->sectorsize,
1017	    DEVSTAT_ALL_SUPPORTED, DEVSTAT_TYPE_DIRECT, DEVSTAT_PRIORITY_MAX);
1018}
1019
1020static int
1021mdcreate_malloc(struct md_s *sc, struct md_ioctl *mdio)
1022{
1023	uintptr_t sp;
1024	int error;
1025	off_t u;
1026
1027	error = 0;
1028	if (mdio->md_options & ~(MD_AUTOUNIT | MD_COMPRESS | MD_RESERVE))
1029		return (EINVAL);
1030	if (mdio->md_sectorsize != 0 && !powerof2(mdio->md_sectorsize))
1031		return (EINVAL);
1032	/* Compression doesn't make sense if we have reserved space */
1033	if (mdio->md_options & MD_RESERVE)
1034		mdio->md_options &= ~MD_COMPRESS;
1035	if (mdio->md_fwsectors != 0)
1036		sc->fwsectors = mdio->md_fwsectors;
1037	if (mdio->md_fwheads != 0)
1038		sc->fwheads = mdio->md_fwheads;
1039	sc->flags = mdio->md_options & (MD_COMPRESS | MD_FORCE);
1040	sc->indir = dimension(sc->mediasize / sc->sectorsize);
1041	sc->uma = uma_zcreate(sc->name, sc->sectorsize, NULL, NULL, NULL, NULL,
1042	    0x1ff, 0);
1043	if (mdio->md_options & MD_RESERVE) {
1044		off_t nsectors;
1045
1046		nsectors = sc->mediasize / sc->sectorsize;
1047		for (u = 0; u < nsectors; u++) {
1048			sp = (uintptr_t)uma_zalloc(sc->uma, (md_malloc_wait ?
1049			    M_WAITOK : M_NOWAIT) | M_ZERO);
1050			if (sp != 0)
1051				error = s_write(sc->indir, u, sp);
1052			else
1053				error = ENOMEM;
1054			if (error != 0)
1055				break;
1056		}
1057	}
1058	return (error);
1059}
1060
1061
1062static int
1063mdsetcred(struct md_s *sc, struct ucred *cred)
1064{
1065	char *tmpbuf;
1066	int error = 0;
1067
1068	/*
1069	 * Set credits in our softc
1070	 */
1071
1072	if (sc->cred)
1073		crfree(sc->cred);
1074	sc->cred = crhold(cred);
1075
1076	/*
1077	 * Horrible kludge to establish credentials for NFS  XXX.
1078	 */
1079
1080	if (sc->vnode) {
1081		struct uio auio;
1082		struct iovec aiov;
1083
1084		tmpbuf = malloc(sc->sectorsize, M_TEMP, M_WAITOK);
1085		bzero(&auio, sizeof(auio));
1086
1087		aiov.iov_base = tmpbuf;
1088		aiov.iov_len = sc->sectorsize;
1089		auio.uio_iov = &aiov;
1090		auio.uio_iovcnt = 1;
1091		auio.uio_offset = 0;
1092		auio.uio_rw = UIO_READ;
1093		auio.uio_segflg = UIO_SYSSPACE;
1094		auio.uio_resid = aiov.iov_len;
1095		vn_lock(sc->vnode, LK_EXCLUSIVE | LK_RETRY);
1096		error = VOP_READ(sc->vnode, &auio, 0, sc->cred);
1097		VOP_UNLOCK(sc->vnode, 0);
1098		free(tmpbuf, M_TEMP);
1099	}
1100	return (error);
1101}
1102
1103static int
1104mdcreate_vnode(struct md_s *sc, struct md_ioctl *mdio, struct thread *td)
1105{
1106	struct vattr vattr;
1107	struct nameidata nd;
1108	char *fname;
1109	int error, flags;
1110
1111	/*
1112	 * Kernel-originated requests must have the filename appended
1113	 * to the mdio structure to protect against malicious software.
1114	 */
1115	fname = mdio->md_file;
1116	if ((void *)fname != (void *)(mdio + 1)) {
1117		error = copyinstr(fname, sc->file, sizeof(sc->file), NULL);
1118		if (error != 0)
1119			return (error);
1120	} else
1121		strlcpy(sc->file, fname, sizeof(sc->file));
1122
1123	/*
1124	 * If the user specified that this is a read only device, don't
1125	 * set the FWRITE mask before trying to open the backing store.
1126	 */
1127	flags = FREAD | ((mdio->md_options & MD_READONLY) ? 0 : FWRITE);
1128	NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, sc->file, td);
1129	error = vn_open(&nd, &flags, 0, NULL);
1130	if (error != 0)
1131		return (error);
1132	NDFREE(&nd, NDF_ONLY_PNBUF);
1133	if (nd.ni_vp->v_type != VREG) {
1134		error = EINVAL;
1135		goto bad;
1136	}
1137	error = VOP_GETATTR(nd.ni_vp, &vattr, td->td_ucred);
1138	if (error != 0)
1139		goto bad;
1140	if (VOP_ISLOCKED(nd.ni_vp) != LK_EXCLUSIVE) {
1141		vn_lock(nd.ni_vp, LK_UPGRADE | LK_RETRY);
1142		if (nd.ni_vp->v_iflag & VI_DOOMED) {
1143			/* Forced unmount. */
1144			error = EBADF;
1145			goto bad;
1146		}
1147	}
1148	nd.ni_vp->v_vflag |= VV_MD;
1149	VOP_UNLOCK(nd.ni_vp, 0);
1150
1151	if (mdio->md_fwsectors != 0)
1152		sc->fwsectors = mdio->md_fwsectors;
1153	if (mdio->md_fwheads != 0)
1154		sc->fwheads = mdio->md_fwheads;
1155	sc->flags = mdio->md_options & (MD_FORCE | MD_ASYNC);
1156	if (!(flags & FWRITE))
1157		sc->flags |= MD_READONLY;
1158	sc->vnode = nd.ni_vp;
1159
1160	error = mdsetcred(sc, td->td_ucred);
1161	if (error != 0) {
1162		sc->vnode = NULL;
1163		vn_lock(nd.ni_vp, LK_EXCLUSIVE | LK_RETRY);
1164		nd.ni_vp->v_vflag &= ~VV_MD;
1165		goto bad;
1166	}
1167	return (0);
1168bad:
1169	VOP_UNLOCK(nd.ni_vp, 0);
1170	(void)vn_close(nd.ni_vp, flags, td->td_ucred, td);
1171	return (error);
1172}
1173
1174static int
1175mddestroy(struct md_s *sc, struct thread *td)
1176{
1177
1178	if (sc->gp) {
1179		sc->gp->softc = NULL;
1180		g_topology_lock();
1181		g_wither_geom(sc->gp, ENXIO);
1182		g_topology_unlock();
1183		sc->gp = NULL;
1184		sc->pp = NULL;
1185	}
1186	if (sc->devstat) {
1187		devstat_remove_entry(sc->devstat);
1188		sc->devstat = NULL;
1189	}
1190	mtx_lock(&sc->queue_mtx);
1191	sc->flags |= MD_SHUTDOWN;
1192	wakeup(sc);
1193	while (!(sc->flags & MD_EXITING))
1194		msleep(sc->procp, &sc->queue_mtx, PRIBIO, "mddestroy", hz / 10);
1195	mtx_unlock(&sc->queue_mtx);
1196	mtx_destroy(&sc->queue_mtx);
1197	if (sc->vnode != NULL) {
1198		vn_lock(sc->vnode, LK_EXCLUSIVE | LK_RETRY);
1199		sc->vnode->v_vflag &= ~VV_MD;
1200		VOP_UNLOCK(sc->vnode, 0);
1201		(void)vn_close(sc->vnode, sc->flags & MD_READONLY ?
1202		    FREAD : (FREAD|FWRITE), sc->cred, td);
1203	}
1204	if (sc->cred != NULL)
1205		crfree(sc->cred);
1206	if (sc->object != NULL)
1207		vm_object_deallocate(sc->object);
1208	if (sc->indir)
1209		destroy_indir(sc, sc->indir);
1210	if (sc->uma)
1211		uma_zdestroy(sc->uma);
1212
1213	LIST_REMOVE(sc, list);
1214	free_unr(md_uh, sc->unit);
1215	free(sc, M_MD);
1216	return (0);
1217}
1218
1219static int
1220mdresize(struct md_s *sc, struct md_ioctl *mdio)
1221{
1222	int error, res;
1223	vm_pindex_t oldpages, newpages;
1224
1225	switch (sc->type) {
1226	case MD_VNODE:
1227		break;
1228	case MD_SWAP:
1229		if (mdio->md_mediasize <= 0 ||
1230		    (mdio->md_mediasize % PAGE_SIZE) != 0)
1231			return (EDOM);
1232		oldpages = OFF_TO_IDX(round_page(sc->mediasize));
1233		newpages = OFF_TO_IDX(round_page(mdio->md_mediasize));
1234		if (newpages < oldpages) {
1235			VM_OBJECT_WLOCK(sc->object);
1236			vm_object_page_remove(sc->object, newpages, 0, 0);
1237			swap_pager_freespace(sc->object, newpages,
1238			    oldpages - newpages);
1239			swap_release_by_cred(IDX_TO_OFF(oldpages -
1240			    newpages), sc->cred);
1241			sc->object->charge = IDX_TO_OFF(newpages);
1242			sc->object->size = newpages;
1243			VM_OBJECT_WUNLOCK(sc->object);
1244		} else if (newpages > oldpages) {
1245			res = swap_reserve_by_cred(IDX_TO_OFF(newpages -
1246			    oldpages), sc->cred);
1247			if (!res)
1248				return (ENOMEM);
1249			if ((mdio->md_options & MD_RESERVE) ||
1250			    (sc->flags & MD_RESERVE)) {
1251				error = swap_pager_reserve(sc->object,
1252				    oldpages, newpages - oldpages);
1253				if (error < 0) {
1254					swap_release_by_cred(
1255					    IDX_TO_OFF(newpages - oldpages),
1256					    sc->cred);
1257					return (EDOM);
1258				}
1259			}
1260			VM_OBJECT_WLOCK(sc->object);
1261			sc->object->charge = IDX_TO_OFF(newpages);
1262			sc->object->size = newpages;
1263			VM_OBJECT_WUNLOCK(sc->object);
1264		}
1265		break;
1266	default:
1267		return (EOPNOTSUPP);
1268	}
1269
1270	sc->mediasize = mdio->md_mediasize;
1271	g_topology_lock();
1272	g_resize_provider(sc->pp, sc->mediasize);
1273	g_topology_unlock();
1274	return (0);
1275}
1276
1277static int
1278mdcreate_swap(struct md_s *sc, struct md_ioctl *mdio, struct thread *td)
1279{
1280	vm_ooffset_t npage;
1281	int error;
1282
1283	/*
1284	 * Range check.  Disallow negative sizes or any size less then the
1285	 * size of a page.  Then round to a page.
1286	 */
1287	if (sc->mediasize <= 0 || (sc->mediasize % PAGE_SIZE) != 0)
1288		return (EDOM);
1289
1290	/*
1291	 * Allocate an OBJT_SWAP object.
1292	 *
1293	 * Note the truncation.
1294	 */
1295
1296	npage = mdio->md_mediasize / PAGE_SIZE;
1297	if (mdio->md_fwsectors != 0)
1298		sc->fwsectors = mdio->md_fwsectors;
1299	if (mdio->md_fwheads != 0)
1300		sc->fwheads = mdio->md_fwheads;
1301	sc->object = vm_pager_allocate(OBJT_SWAP, NULL, PAGE_SIZE * npage,
1302	    VM_PROT_DEFAULT, 0, td->td_ucred);
1303	if (sc->object == NULL)
1304		return (ENOMEM);
1305	sc->flags = mdio->md_options & (MD_FORCE | MD_RESERVE);
1306	if (mdio->md_options & MD_RESERVE) {
1307		if (swap_pager_reserve(sc->object, 0, npage) < 0) {
1308			error = EDOM;
1309			goto finish;
1310		}
1311	}
1312	error = mdsetcred(sc, td->td_ucred);
1313 finish:
1314	if (error != 0) {
1315		vm_object_deallocate(sc->object);
1316		sc->object = NULL;
1317	}
1318	return (error);
1319}
1320
1321
1322static int
1323xmdctlioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flags, struct thread *td)
1324{
1325	struct md_ioctl *mdio;
1326	struct md_s *sc;
1327	int error, i;
1328	unsigned sectsize;
1329
1330	if (md_debug)
1331		printf("mdctlioctl(%s %lx %p %x %p)\n",
1332			devtoname(dev), cmd, addr, flags, td);
1333
1334	mdio = (struct md_ioctl *)addr;
1335	if (mdio->md_version != MDIOVERSION)
1336		return (EINVAL);
1337
1338	/*
1339	 * We assert the version number in the individual ioctl
1340	 * handlers instead of out here because (a) it is possible we
1341	 * may add another ioctl in the future which doesn't read an
1342	 * mdio, and (b) the correct return value for an unknown ioctl
1343	 * is ENOIOCTL, not EINVAL.
1344	 */
1345	error = 0;
1346	switch (cmd) {
1347	case MDIOCATTACH:
1348		switch (mdio->md_type) {
1349		case MD_MALLOC:
1350		case MD_PRELOAD:
1351		case MD_VNODE:
1352		case MD_SWAP:
1353			break;
1354		default:
1355			return (EINVAL);
1356		}
1357		if (mdio->md_sectorsize == 0)
1358			sectsize = DEV_BSIZE;
1359		else
1360			sectsize = mdio->md_sectorsize;
1361		if (sectsize > MAXPHYS || mdio->md_mediasize < sectsize)
1362			return (EINVAL);
1363		if (mdio->md_options & MD_AUTOUNIT)
1364			sc = mdnew(-1, &error, mdio->md_type);
1365		else {
1366			if (mdio->md_unit > INT_MAX)
1367				return (EINVAL);
1368			sc = mdnew(mdio->md_unit, &error, mdio->md_type);
1369		}
1370		if (sc == NULL)
1371			return (error);
1372		if (mdio->md_options & MD_AUTOUNIT)
1373			mdio->md_unit = sc->unit;
1374		sc->mediasize = mdio->md_mediasize;
1375		sc->sectorsize = sectsize;
1376		error = EDOOFUS;
1377		switch (sc->type) {
1378		case MD_MALLOC:
1379			sc->start = mdstart_malloc;
1380			error = mdcreate_malloc(sc, mdio);
1381			break;
1382		case MD_PRELOAD:
1383			/*
1384			 * We disallow attaching preloaded memory disks via
1385			 * ioctl. Preloaded memory disks are automatically
1386			 * attached in g_md_init().
1387			 */
1388			error = EOPNOTSUPP;
1389			break;
1390		case MD_VNODE:
1391			sc->start = mdstart_vnode;
1392			error = mdcreate_vnode(sc, mdio, td);
1393			break;
1394		case MD_SWAP:
1395			sc->start = mdstart_swap;
1396			error = mdcreate_swap(sc, mdio, td);
1397			break;
1398		}
1399		if (error != 0) {
1400			mddestroy(sc, td);
1401			return (error);
1402		}
1403
1404		/* Prune off any residual fractional sector */
1405		i = sc->mediasize % sc->sectorsize;
1406		sc->mediasize -= i;
1407
1408		mdinit(sc);
1409		return (0);
1410	case MDIOCDETACH:
1411		if (mdio->md_mediasize != 0 ||
1412		    (mdio->md_options & ~MD_FORCE) != 0)
1413			return (EINVAL);
1414
1415		sc = mdfind(mdio->md_unit);
1416		if (sc == NULL)
1417			return (ENOENT);
1418		if (sc->opencount != 0 && !(sc->flags & MD_FORCE) &&
1419		    !(mdio->md_options & MD_FORCE))
1420			return (EBUSY);
1421		return (mddestroy(sc, td));
1422	case MDIOCRESIZE:
1423		if ((mdio->md_options & ~(MD_FORCE | MD_RESERVE)) != 0)
1424			return (EINVAL);
1425
1426		sc = mdfind(mdio->md_unit);
1427		if (sc == NULL)
1428			return (ENOENT);
1429		if (mdio->md_mediasize < sc->sectorsize)
1430			return (EINVAL);
1431		if (mdio->md_mediasize < sc->mediasize &&
1432		    !(sc->flags & MD_FORCE) &&
1433		    !(mdio->md_options & MD_FORCE))
1434			return (EBUSY);
1435		return (mdresize(sc, mdio));
1436	case MDIOCQUERY:
1437		sc = mdfind(mdio->md_unit);
1438		if (sc == NULL)
1439			return (ENOENT);
1440		mdio->md_type = sc->type;
1441		mdio->md_options = sc->flags;
1442		mdio->md_mediasize = sc->mediasize;
1443		mdio->md_sectorsize = sc->sectorsize;
1444		if (sc->type == MD_VNODE)
1445			error = copyout(sc->file, mdio->md_file,
1446			    strlen(sc->file) + 1);
1447		return (error);
1448	case MDIOCLIST:
1449		i = 1;
1450		LIST_FOREACH(sc, &md_softc_list, list) {
1451			if (i == MDNPAD - 1)
1452				mdio->md_pad[i] = -1;
1453			else
1454				mdio->md_pad[i++] = sc->unit;
1455		}
1456		mdio->md_pad[0] = i - 1;
1457		return (0);
1458	default:
1459		return (ENOIOCTL);
1460	};
1461}
1462
1463static int
1464mdctlioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flags, struct thread *td)
1465{
1466	int error;
1467
1468	sx_xlock(&md_sx);
1469	error = xmdctlioctl(dev, cmd, addr, flags, td);
1470	sx_xunlock(&md_sx);
1471	return (error);
1472}
1473
1474static void
1475md_preloaded(u_char *image, size_t length, const char *name)
1476{
1477	struct md_s *sc;
1478	int error;
1479
1480	sc = mdnew(-1, &error, MD_PRELOAD);
1481	if (sc == NULL)
1482		return;
1483	sc->mediasize = length;
1484	sc->sectorsize = DEV_BSIZE;
1485	sc->pl_ptr = image;
1486	sc->pl_len = length;
1487	sc->start = mdstart_preload;
1488#ifdef MD_ROOT
1489	if (sc->unit == 0)
1490		rootdevnames[0] = MD_ROOT_FSTYPE ":/dev/md0";
1491#endif
1492	mdinit(sc);
1493	if (name != NULL) {
1494		printf("%s%d: Preloaded image <%s> %zd bytes at %p\n",
1495		    MD_NAME, sc->unit, name, length, image);
1496	}
1497}
1498
1499static void
1500g_md_init(struct g_class *mp __unused)
1501{
1502	caddr_t mod;
1503	u_char *ptr, *name, *type;
1504	unsigned len;
1505	int i;
1506
1507	/* figure out log2(NINDIR) */
1508	for (i = NINDIR, nshift = -1; i; nshift++)
1509		i >>= 1;
1510
1511	mod = NULL;
1512	sx_init(&md_sx, "MD config lock");
1513	g_topology_unlock();
1514	md_uh = new_unrhdr(0, INT_MAX, NULL);
1515#ifdef MD_ROOT_SIZE
1516	sx_xlock(&md_sx);
1517	md_preloaded(mfs_root.start, sizeof(mfs_root.start), NULL);
1518	sx_xunlock(&md_sx);
1519#endif
1520	/* XXX: are preload_* static or do they need Giant ? */
1521	while ((mod = preload_search_next_name(mod)) != NULL) {
1522		name = (char *)preload_search_info(mod, MODINFO_NAME);
1523		if (name == NULL)
1524			continue;
1525		type = (char *)preload_search_info(mod, MODINFO_TYPE);
1526		if (type == NULL)
1527			continue;
1528		if (strcmp(type, "md_image") && strcmp(type, "mfs_root"))
1529			continue;
1530		ptr = preload_fetch_addr(mod);
1531		len = preload_fetch_size(mod);
1532		if (ptr != NULL && len != 0) {
1533			sx_xlock(&md_sx);
1534			md_preloaded(ptr, len, name);
1535			sx_xunlock(&md_sx);
1536		}
1537	}
1538	md_vnode_pbuf_freecnt = nswbuf / 10;
1539	status_dev = make_dev(&mdctl_cdevsw, INT_MAX, UID_ROOT, GID_WHEEL,
1540	    0600, MDCTL_NAME);
1541	g_topology_lock();
1542}
1543
1544static void
1545g_md_dumpconf(struct sbuf *sb, const char *indent, struct g_geom *gp,
1546    struct g_consumer *cp __unused, struct g_provider *pp)
1547{
1548	struct md_s *mp;
1549	char *type;
1550
1551	mp = gp->softc;
1552	if (mp == NULL)
1553		return;
1554
1555	switch (mp->type) {
1556	case MD_MALLOC:
1557		type = "malloc";
1558		break;
1559	case MD_PRELOAD:
1560		type = "preload";
1561		break;
1562	case MD_VNODE:
1563		type = "vnode";
1564		break;
1565	case MD_SWAP:
1566		type = "swap";
1567		break;
1568	default:
1569		type = "unknown";
1570		break;
1571	}
1572
1573	if (pp != NULL) {
1574		if (indent == NULL) {
1575			sbuf_printf(sb, " u %d", mp->unit);
1576			sbuf_printf(sb, " s %ju", (uintmax_t) mp->sectorsize);
1577			sbuf_printf(sb, " f %ju", (uintmax_t) mp->fwheads);
1578			sbuf_printf(sb, " fs %ju", (uintmax_t) mp->fwsectors);
1579			sbuf_printf(sb, " l %ju", (uintmax_t) mp->mediasize);
1580			sbuf_printf(sb, " t %s", type);
1581			if (mp->type == MD_VNODE && mp->vnode != NULL)
1582				sbuf_printf(sb, " file %s", mp->file);
1583		} else {
1584			sbuf_printf(sb, "%s<unit>%d</unit>\n", indent,
1585			    mp->unit);
1586			sbuf_printf(sb, "%s<sectorsize>%ju</sectorsize>\n",
1587			    indent, (uintmax_t) mp->sectorsize);
1588			sbuf_printf(sb, "%s<fwheads>%ju</fwheads>\n",
1589			    indent, (uintmax_t) mp->fwheads);
1590			sbuf_printf(sb, "%s<fwsectors>%ju</fwsectors>\n",
1591			    indent, (uintmax_t) mp->fwsectors);
1592			sbuf_printf(sb, "%s<length>%ju</length>\n",
1593			    indent, (uintmax_t) mp->mediasize);
1594			sbuf_printf(sb, "%s<compression>%s</compression>\n", indent,
1595			    (mp->flags & MD_COMPRESS) == 0 ? "off": "on");
1596			sbuf_printf(sb, "%s<access>%s</access>\n", indent,
1597			    (mp->flags & MD_READONLY) == 0 ? "read-write":
1598			    "read-only");
1599			sbuf_printf(sb, "%s<type>%s</type>\n", indent,
1600			    type);
1601			if (mp->type == MD_VNODE && mp->vnode != NULL)
1602				sbuf_printf(sb, "%s<file>%s</file>\n",
1603				    indent, mp->file);
1604		}
1605	}
1606}
1607
1608static void
1609g_md_fini(struct g_class *mp __unused)
1610{
1611
1612	sx_destroy(&md_sx);
1613	if (status_dev != NULL)
1614		destroy_dev(status_dev);
1615	delete_unrhdr(md_uh);
1616}
1617