1 /*-
2  * SPDX-License-Identifier: (Beerware AND BSD-3-Clause)
3  *
4  * ----------------------------------------------------------------------------
5  * "THE BEER-WARE LICENSE" (Revision 42):
6  * <phk@FreeBSD.ORG> wrote this file.  As long as you retain this notice you
7  * can do whatever you want with this stuff. If we meet some day, and you think
8  * this stuff is worth it, you can buy me a beer in return.   Poul-Henning Kamp
9  * ----------------------------------------------------------------------------
10  *
11  * $FreeBSD: stable/12/sys/dev/md/md.c 373173 2023-08-18 12:42:09Z karels $
12  *
13  */
14 
15 /*-
16  * The following functions are based in the vn(4) driver: mdstart_swap(),
17  * mdstart_vnode(), mdcreate_swap(), mdcreate_vnode() and mddestroy(),
18  * and as such under the following copyright:
19  *
20  * Copyright (c) 1988 University of Utah.
21  * Copyright (c) 1990, 1993
22  *	The Regents of the University of California.  All rights reserved.
23  * Copyright (c) 2013 The FreeBSD Foundation
24  * All rights reserved.
25  *
26  * This code is derived from software contributed to Berkeley by
27  * the Systems Programming Group of the University of Utah Computer
28  * Science Department.
29  *
30  * Portions of this software were developed by Konstantin Belousov
31  * under sponsorship from the FreeBSD Foundation.
32  *
33  * Redistribution and use in source and binary forms, with or without
34  * modification, are permitted provided that the following conditions
35  * are met:
36  * 1. Redistributions of source code must retain the above copyright
37  *    notice, this list of conditions and the following disclaimer.
38  * 2. Redistributions in binary form must reproduce the above copyright
39  *    notice, this list of conditions and the following disclaimer in the
40  *    documentation and/or other materials provided with the distribution.
41  * 3. Neither the name of the University nor the names of its contributors
42  *    may be used to endorse or promote products derived from this software
43  *    without specific prior written permission.
44  *
45  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
46  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
47  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
48  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
49  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
50  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
51  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
52  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
53  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
54  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
55  * SUCH DAMAGE.
56  *
57  * from: Utah Hdr: vn.c 1.13 94/04/02
58  *
59  *	from: @(#)vn.c	8.6 (Berkeley) 4/1/94
60  * From: src/sys/dev/vn/vn.c,v 1.122 2000/12/16 16:06:03
61  */
62 
63 #include "opt_rootdevname.h"
64 #include "opt_geom.h"
65 #include "opt_md.h"
66 
67 #include <sys/param.h>
68 #include <sys/systm.h>
69 #include <sys/bio.h>
70 #include <sys/buf.h>
71 #include <sys/conf.h>
72 #include <sys/devicestat.h>
73 #include <sys/fcntl.h>
74 #include <sys/kernel.h>
75 #include <sys/kthread.h>
76 #include <sys/limits.h>
77 #include <sys/linker.h>
78 #include <sys/lock.h>
79 #include <sys/malloc.h>
80 #include <sys/mdioctl.h>
81 #include <sys/mount.h>
82 #include <sys/mutex.h>
83 #include <sys/sx.h>
84 #include <sys/namei.h>
85 #include <sys/proc.h>
86 #include <sys/queue.h>
87 #include <sys/rwlock.h>
88 #include <sys/sbuf.h>
89 #include <sys/sched.h>
90 #include <sys/sf_buf.h>
91 #include <sys/sysctl.h>
92 #include <sys/uio.h>
93 #include <sys/vnode.h>
94 #include <sys/disk.h>
95 
96 #include <geom/geom.h>
97 #include <geom/geom_int.h>
98 
99 #include <vm/vm.h>
100 #include <vm/vm_param.h>
101 #include <vm/vm_object.h>
102 #include <vm/vm_page.h>
103 #include <vm/vm_pager.h>
104 #include <vm/swap_pager.h>
105 #include <vm/uma.h>
106 
107 #include <machine/bus.h>
108 
109 #define MD_MODVER 1
110 
111 #define MD_SHUTDOWN	0x10000		/* Tell worker thread to terminate. */
112 #define	MD_EXITING	0x20000		/* Worker thread is exiting. */
113 #define	MD_PROVIDERGONE	0x40000		/* Safe to free the softc */
114 
115 #ifndef MD_NSECT
116 #define MD_NSECT (10000 * 2)
117 #endif
118 
119 struct md_req {
120 	unsigned	md_unit;	/* unit number */
121 	enum md_types	md_type;	/* type of disk */
122 	off_t		md_mediasize;	/* size of disk in bytes */
123 	unsigned	md_sectorsize;	/* sectorsize */
124 	unsigned	md_options;	/* options */
125 	int		md_fwheads;	/* firmware heads */
126 	int		md_fwsectors;	/* firmware sectors */
127 	char		*md_file;	/* pathname of file to mount */
128 	enum uio_seg	md_file_seg;	/* location of md_file */
129 	char		*md_label;	/* label of the device (userspace) */
130 	int		*md_units;	/* pointer to units array (kernel) */
131 	size_t		md_units_nitems; /* items in md_units array */
132 };
133 
134 #ifdef COMPAT_FREEBSD32
135 struct md_ioctl32 {
136 	unsigned	md_version;
137 	unsigned	md_unit;
138 	enum md_types	md_type;
139 	uint32_t	md_file;
140 	off_t		md_mediasize;
141 	unsigned	md_sectorsize;
142 	unsigned	md_options;
143 	uint64_t	md_base;
144 	int		md_fwheads;
145 	int		md_fwsectors;
146 	uint32_t	md_label;
147 	int		md_pad[MDNPAD];
148 }
149 #ifdef __amd64__
150 __attribute__((__packed__))
151 #endif
152 ;
153 #ifndef __amd64__
154 CTASSERT((sizeof(struct md_ioctl32)) == 440);
155 #else
156 CTASSERT((sizeof(struct md_ioctl32)) == 436);
157 #endif
158 
159 #define	MDIOCATTACH_32	_IOC_NEWTYPE(MDIOCATTACH, struct md_ioctl32)
160 #define	MDIOCDETACH_32	_IOC_NEWTYPE(MDIOCDETACH, struct md_ioctl32)
161 #define	MDIOCQUERY_32	_IOC_NEWTYPE(MDIOCQUERY, struct md_ioctl32)
162 #define	MDIOCLIST_32	_IOC_NEWTYPE(MDIOCLIST, struct md_ioctl32)
163 #define	MDIOCRESIZE_32	_IOC_NEWTYPE(MDIOCRESIZE, struct md_ioctl32)
164 #endif /* COMPAT_FREEBSD32 */
165 
166 static MALLOC_DEFINE(M_MD, "md_disk", "Memory Disk");
167 static MALLOC_DEFINE(M_MDSECT, "md_sectors", "Memory Disk Sectors");
168 
169 static int md_debug;
170 SYSCTL_INT(_debug, OID_AUTO, mddebug, CTLFLAG_RW, &md_debug, 0,
171     "Enable md(4) debug messages");
172 static int md_malloc_wait;
173 SYSCTL_INT(_vm, OID_AUTO, md_malloc_wait, CTLFLAG_RW, &md_malloc_wait, 0,
174     "Allow malloc to wait for memory allocations");
175 
176 #if defined(MD_ROOT) && !defined(MD_ROOT_FSTYPE)
177 #define	MD_ROOT_FSTYPE	"ufs"
178 #endif
179 
180 #if defined(MD_ROOT)
181 /*
182  * Preloaded image gets put here.
183  */
184 #if defined(MD_ROOT_SIZE)
185 /*
186  * We put the mfs_root symbol into the oldmfs section of the kernel object file.
187  * Applications that patch the object with the image can determine
188  * the size looking at the oldmfs section size within the kernel.
189  */
190 u_char mfs_root[MD_ROOT_SIZE*1024] __attribute__ ((section ("oldmfs")));
191 const int mfs_root_size = sizeof(mfs_root);
192 #elif defined(MD_ROOT_MEM)
193 /* MD region already mapped in the memory */
194 u_char *mfs_root;
195 int mfs_root_size;
196 #else
197 extern volatile u_char __weak_symbol mfs_root;
198 extern volatile u_char __weak_symbol mfs_root_end;
199 #define mfs_root_size ((uintptr_t)(&mfs_root_end - &mfs_root))
200 #endif
201 #endif
202 
203 static g_init_t g_md_init;
204 static g_fini_t g_md_fini;
205 static g_start_t g_md_start;
206 static g_access_t g_md_access;
207 static void g_md_dumpconf(struct sbuf *sb, const char *indent,
208     struct g_geom *gp, struct g_consumer *cp __unused, struct g_provider *pp);
209 static g_provgone_t g_md_providergone;
210 
211 static struct cdev *status_dev = NULL;
212 static struct sx md_sx;
213 static struct unrhdr *md_uh;
214 
215 static d_ioctl_t mdctlioctl;
216 
217 static struct cdevsw mdctl_cdevsw = {
218 	.d_version =	D_VERSION,
219 	.d_ioctl =	mdctlioctl,
220 	.d_name =	MD_NAME,
221 };
222 
223 struct g_class g_md_class = {
224 	.name = "MD",
225 	.version = G_VERSION,
226 	.init = g_md_init,
227 	.fini = g_md_fini,
228 	.start = g_md_start,
229 	.access = g_md_access,
230 	.dumpconf = g_md_dumpconf,
231 	.providergone = g_md_providergone,
232 };
233 
234 DECLARE_GEOM_CLASS(g_md_class, g_md);
235 MODULE_VERSION(geom_md, 0);
236 
237 
238 static LIST_HEAD(, md_s) md_softc_list = LIST_HEAD_INITIALIZER(md_softc_list);
239 
240 #define NINDIR	(PAGE_SIZE / sizeof(uintptr_t))
241 #define NMASK	(NINDIR-1)
242 static int nshift;
243 
244 static int md_vnode_pbuf_freecnt;
245 
246 struct indir {
247 	uintptr_t	*array;
248 	u_int		total;
249 	u_int		used;
250 	u_int		shift;
251 };
252 
253 struct md_s {
254 	int unit;
255 	LIST_ENTRY(md_s) list;
256 	struct bio_queue_head bio_queue;
257 	struct mtx queue_mtx;
258 	struct mtx stat_mtx;
259 	struct cdev *dev;
260 	enum md_types type;
261 	off_t mediasize;
262 	unsigned sectorsize;
263 	unsigned opencount;
264 	unsigned fwheads;
265 	unsigned fwsectors;
266 	char ident[32];
267 	unsigned flags;
268 	char name[20];
269 	struct proc *procp;
270 	struct g_geom *gp;
271 	struct g_provider *pp;
272 	int (*start)(struct md_s *sc, struct bio *bp);
273 	struct devstat *devstat;
274 
275 	/* MD_MALLOC related fields */
276 	struct indir *indir;
277 	uma_zone_t uma;
278 
279 	/* MD_PRELOAD related fields */
280 	u_char *pl_ptr;
281 	size_t pl_len;
282 
283 	/* MD_VNODE related fields */
284 	struct vnode *vnode;
285 	char file[PATH_MAX];
286 	char label[PATH_MAX];
287 	struct ucred *cred;
288 
289 	/* MD_SWAP related fields */
290 	vm_object_t object;
291 };
292 
293 static struct indir *
new_indir(u_int shift)294 new_indir(u_int shift)
295 {
296 	struct indir *ip;
297 
298 	ip = malloc(sizeof *ip, M_MD, (md_malloc_wait ? M_WAITOK : M_NOWAIT)
299 	    | M_ZERO);
300 	if (ip == NULL)
301 		return (NULL);
302 	ip->array = malloc(sizeof(uintptr_t) * NINDIR,
303 	    M_MDSECT, (md_malloc_wait ? M_WAITOK : M_NOWAIT) | M_ZERO);
304 	if (ip->array == NULL) {
305 		free(ip, M_MD);
306 		return (NULL);
307 	}
308 	ip->total = NINDIR;
309 	ip->shift = shift;
310 	return (ip);
311 }
312 
313 static void
del_indir(struct indir * ip)314 del_indir(struct indir *ip)
315 {
316 
317 	free(ip->array, M_MDSECT);
318 	free(ip, M_MD);
319 }
320 
321 static void
destroy_indir(struct md_s * sc,struct indir * ip)322 destroy_indir(struct md_s *sc, struct indir *ip)
323 {
324 	int i;
325 
326 	for (i = 0; i < NINDIR; i++) {
327 		if (!ip->array[i])
328 			continue;
329 		if (ip->shift)
330 			destroy_indir(sc, (struct indir*)(ip->array[i]));
331 		else if (ip->array[i] > 255)
332 			uma_zfree(sc->uma, (void *)(ip->array[i]));
333 	}
334 	del_indir(ip);
335 }
336 
337 /*
338  * This function does the math and allocates the top level "indir" structure
339  * for a device of "size" sectors.
340  */
341 
342 static struct indir *
dimension(off_t size)343 dimension(off_t size)
344 {
345 	off_t rcnt;
346 	struct indir *ip;
347 	int layer;
348 
349 	rcnt = size;
350 	layer = 0;
351 	while (rcnt > NINDIR) {
352 		rcnt /= NINDIR;
353 		layer++;
354 	}
355 
356 	/*
357 	 * XXX: the top layer is probably not fully populated, so we allocate
358 	 * too much space for ip->array in here.
359 	 */
360 	ip = malloc(sizeof *ip, M_MD, M_WAITOK | M_ZERO);
361 	ip->array = malloc(sizeof(uintptr_t) * NINDIR,
362 	    M_MDSECT, M_WAITOK | M_ZERO);
363 	ip->total = NINDIR;
364 	ip->shift = layer * nshift;
365 	return (ip);
366 }
367 
368 /*
369  * Read a given sector
370  */
371 
372 static uintptr_t
s_read(struct indir * ip,off_t offset)373 s_read(struct indir *ip, off_t offset)
374 {
375 	struct indir *cip;
376 	int idx;
377 	uintptr_t up;
378 
379 	if (md_debug > 1)
380 		printf("s_read(%jd)\n", (intmax_t)offset);
381 	up = 0;
382 	for (cip = ip; cip != NULL;) {
383 		if (cip->shift) {
384 			idx = (offset >> cip->shift) & NMASK;
385 			up = cip->array[idx];
386 			cip = (struct indir *)up;
387 			continue;
388 		}
389 		idx = offset & NMASK;
390 		return (cip->array[idx]);
391 	}
392 	return (0);
393 }
394 
395 /*
396  * Write a given sector, prune the tree if the value is 0
397  */
398 
399 static int
s_write(struct indir * ip,off_t offset,uintptr_t ptr)400 s_write(struct indir *ip, off_t offset, uintptr_t ptr)
401 {
402 	struct indir *cip, *lip[10];
403 	int idx, li;
404 	uintptr_t up;
405 
406 	if (md_debug > 1)
407 		printf("s_write(%jd, %p)\n", (intmax_t)offset, (void *)ptr);
408 	up = 0;
409 	li = 0;
410 	cip = ip;
411 	for (;;) {
412 		lip[li++] = cip;
413 		if (cip->shift) {
414 			idx = (offset >> cip->shift) & NMASK;
415 			up = cip->array[idx];
416 			if (up != 0) {
417 				cip = (struct indir *)up;
418 				continue;
419 			}
420 			/* Allocate branch */
421 			cip->array[idx] =
422 			    (uintptr_t)new_indir(cip->shift - nshift);
423 			if (cip->array[idx] == 0)
424 				return (ENOSPC);
425 			cip->used++;
426 			up = cip->array[idx];
427 			cip = (struct indir *)up;
428 			continue;
429 		}
430 		/* leafnode */
431 		idx = offset & NMASK;
432 		up = cip->array[idx];
433 		if (up != 0)
434 			cip->used--;
435 		cip->array[idx] = ptr;
436 		if (ptr != 0)
437 			cip->used++;
438 		break;
439 	}
440 	if (cip->used != 0 || li == 1)
441 		return (0);
442 	li--;
443 	while (cip->used == 0 && cip != ip) {
444 		li--;
445 		idx = (offset >> lip[li]->shift) & NMASK;
446 		up = lip[li]->array[idx];
447 		KASSERT(up == (uintptr_t)cip, ("md screwed up"));
448 		del_indir(cip);
449 		lip[li]->array[idx] = 0;
450 		lip[li]->used--;
451 		cip = lip[li];
452 	}
453 	return (0);
454 }
455 
456 
457 static int
g_md_access(struct g_provider * pp,int r,int w,int e)458 g_md_access(struct g_provider *pp, int r, int w, int e)
459 {
460 	struct md_s *sc;
461 
462 	sc = pp->geom->softc;
463 	if (sc == NULL) {
464 		if (r <= 0 && w <= 0 && e <= 0)
465 			return (0);
466 		return (ENXIO);
467 	}
468 	r += pp->acr;
469 	w += pp->acw;
470 	e += pp->ace;
471 	if ((sc->flags & MD_READONLY) != 0 && w > 0)
472 		return (EROFS);
473 	if ((pp->acr + pp->acw + pp->ace) == 0 && (r + w + e) > 0) {
474 		sc->opencount = 1;
475 	} else if ((pp->acr + pp->acw + pp->ace) > 0 && (r + w + e) == 0) {
476 		sc->opencount = 0;
477 	}
478 	return (0);
479 }
480 
481 static void
g_md_start(struct bio * bp)482 g_md_start(struct bio *bp)
483 {
484 	struct md_s *sc;
485 
486 	sc = bp->bio_to->geom->softc;
487 	if ((bp->bio_cmd == BIO_READ) || (bp->bio_cmd == BIO_WRITE)) {
488 		mtx_lock(&sc->stat_mtx);
489 		devstat_start_transaction_bio(sc->devstat, bp);
490 		mtx_unlock(&sc->stat_mtx);
491 	}
492 	mtx_lock(&sc->queue_mtx);
493 	bioq_disksort(&sc->bio_queue, bp);
494 	wakeup(sc);
495 	mtx_unlock(&sc->queue_mtx);
496 }
497 
498 #define	MD_MALLOC_MOVE_ZERO	1
499 #define	MD_MALLOC_MOVE_FILL	2
500 #define	MD_MALLOC_MOVE_READ	3
501 #define	MD_MALLOC_MOVE_WRITE	4
502 #define	MD_MALLOC_MOVE_CMP	5
503 
504 static int
md_malloc_move_ma(vm_page_t ** mp,int * ma_offs,unsigned sectorsize,void * ptr,u_char fill,int op)505 md_malloc_move_ma(vm_page_t **mp, int *ma_offs, unsigned sectorsize,
506     void *ptr, u_char fill, int op)
507 {
508 	struct sf_buf *sf;
509 	vm_page_t m, *mp1;
510 	char *p, first;
511 	off_t *uc;
512 	unsigned n;
513 	int error, i, ma_offs1, sz, first_read;
514 
515 	m = NULL;
516 	error = 0;
517 	sf = NULL;
518 	/* if (op == MD_MALLOC_MOVE_CMP) { gcc */
519 		first = 0;
520 		first_read = 0;
521 		uc = ptr;
522 		mp1 = *mp;
523 		ma_offs1 = *ma_offs;
524 	/* } */
525 	sched_pin();
526 	for (n = sectorsize; n != 0; n -= sz) {
527 		sz = imin(PAGE_SIZE - *ma_offs, n);
528 		if (m != **mp) {
529 			if (sf != NULL)
530 				sf_buf_free(sf);
531 			m = **mp;
532 			sf = sf_buf_alloc(m, SFB_CPUPRIVATE |
533 			    (md_malloc_wait ? 0 : SFB_NOWAIT));
534 			if (sf == NULL) {
535 				error = ENOMEM;
536 				break;
537 			}
538 		}
539 		p = (char *)sf_buf_kva(sf) + *ma_offs;
540 		switch (op) {
541 		case MD_MALLOC_MOVE_ZERO:
542 			bzero(p, sz);
543 			break;
544 		case MD_MALLOC_MOVE_FILL:
545 			memset(p, fill, sz);
546 			break;
547 		case MD_MALLOC_MOVE_READ:
548 			bcopy(ptr, p, sz);
549 			cpu_flush_dcache(p, sz);
550 			break;
551 		case MD_MALLOC_MOVE_WRITE:
552 			bcopy(p, ptr, sz);
553 			break;
554 		case MD_MALLOC_MOVE_CMP:
555 			for (i = 0; i < sz; i++, p++) {
556 				if (!first_read) {
557 					*uc = (u_char)*p;
558 					first = *p;
559 					first_read = 1;
560 				} else if (*p != first) {
561 					error = EDOOFUS;
562 					break;
563 				}
564 			}
565 			break;
566 		default:
567 			KASSERT(0, ("md_malloc_move_ma unknown op %d\n", op));
568 			break;
569 		}
570 		if (error != 0)
571 			break;
572 		*ma_offs += sz;
573 		*ma_offs %= PAGE_SIZE;
574 		if (*ma_offs == 0)
575 			(*mp)++;
576 		ptr = (char *)ptr + sz;
577 	}
578 
579 	if (sf != NULL)
580 		sf_buf_free(sf);
581 	sched_unpin();
582 	if (op == MD_MALLOC_MOVE_CMP && error != 0) {
583 		*mp = mp1;
584 		*ma_offs = ma_offs1;
585 	}
586 	return (error);
587 }
588 
589 static int
md_malloc_move_vlist(bus_dma_segment_t ** pvlist,int * pma_offs,unsigned len,void * ptr,u_char fill,int op)590 md_malloc_move_vlist(bus_dma_segment_t **pvlist, int *pma_offs,
591     unsigned len, void *ptr, u_char fill, int op)
592 {
593 	bus_dma_segment_t *vlist;
594 	uint8_t *p, *end, first;
595 	off_t *uc;
596 	int ma_offs, seg_len;
597 
598 	vlist = *pvlist;
599 	ma_offs = *pma_offs;
600 	uc = ptr;
601 
602 	for (; len != 0; len -= seg_len) {
603 		seg_len = imin(vlist->ds_len - ma_offs, len);
604 		p = (uint8_t *)(uintptr_t)vlist->ds_addr + ma_offs;
605 		switch (op) {
606 		case MD_MALLOC_MOVE_ZERO:
607 			bzero(p, seg_len);
608 			break;
609 		case MD_MALLOC_MOVE_FILL:
610 			memset(p, fill, seg_len);
611 			break;
612 		case MD_MALLOC_MOVE_READ:
613 			bcopy(ptr, p, seg_len);
614 			cpu_flush_dcache(p, seg_len);
615 			break;
616 		case MD_MALLOC_MOVE_WRITE:
617 			bcopy(p, ptr, seg_len);
618 			break;
619 		case MD_MALLOC_MOVE_CMP:
620 			end = p + seg_len;
621 			first = *uc = *p;
622 			/* Confirm all following bytes match the first */
623 			while (++p < end) {
624 				if (*p != first)
625 					return (EDOOFUS);
626 			}
627 			break;
628 		default:
629 			KASSERT(0, ("md_malloc_move_vlist unknown op %d\n", op));
630 			break;
631 		}
632 
633 		ma_offs += seg_len;
634 		if (ma_offs == vlist->ds_len) {
635 			ma_offs = 0;
636 			vlist++;
637 		}
638 		ptr = (uint8_t *)ptr + seg_len;
639 	}
640 	*pvlist = vlist;
641 	*pma_offs = ma_offs;
642 
643 	return (0);
644 }
645 
646 static int
mdstart_malloc(struct md_s * sc,struct bio * bp)647 mdstart_malloc(struct md_s *sc, struct bio *bp)
648 {
649 	u_char *dst;
650 	vm_page_t *m;
651 	bus_dma_segment_t *vlist;
652 	int i, error, error1, ma_offs, notmapped;
653 	off_t secno, nsec, uc;
654 	uintptr_t sp, osp;
655 
656 	switch (bp->bio_cmd) {
657 	case BIO_READ:
658 	case BIO_WRITE:
659 	case BIO_DELETE:
660 		break;
661 	default:
662 		return (EOPNOTSUPP);
663 	}
664 
665 	notmapped = (bp->bio_flags & BIO_UNMAPPED) != 0;
666 	vlist = (bp->bio_flags & BIO_VLIST) != 0 ?
667 	    (bus_dma_segment_t *)bp->bio_data : NULL;
668 	if (notmapped) {
669 		m = bp->bio_ma;
670 		ma_offs = bp->bio_ma_offset;
671 		dst = NULL;
672 		KASSERT(vlist == NULL, ("vlists cannot be unmapped"));
673 	} else if (vlist != NULL) {
674 		ma_offs = bp->bio_ma_offset;
675 		dst = NULL;
676 	} else {
677 		dst = bp->bio_data;
678 	}
679 
680 	nsec = bp->bio_length / sc->sectorsize;
681 	secno = bp->bio_offset / sc->sectorsize;
682 	error = 0;
683 	while (nsec--) {
684 		osp = s_read(sc->indir, secno);
685 		if (bp->bio_cmd == BIO_DELETE) {
686 			if (osp != 0)
687 				error = s_write(sc->indir, secno, 0);
688 		} else if (bp->bio_cmd == BIO_READ) {
689 			if (osp == 0) {
690 				if (notmapped) {
691 					error = md_malloc_move_ma(&m, &ma_offs,
692 					    sc->sectorsize, NULL, 0,
693 					    MD_MALLOC_MOVE_ZERO);
694 				} else if (vlist != NULL) {
695 					error = md_malloc_move_vlist(&vlist,
696 					    &ma_offs, sc->sectorsize, NULL, 0,
697 					    MD_MALLOC_MOVE_ZERO);
698 				} else
699 					bzero(dst, sc->sectorsize);
700 			} else if (osp <= 255) {
701 				if (notmapped) {
702 					error = md_malloc_move_ma(&m, &ma_offs,
703 					    sc->sectorsize, NULL, osp,
704 					    MD_MALLOC_MOVE_FILL);
705 				} else if (vlist != NULL) {
706 					error = md_malloc_move_vlist(&vlist,
707 					    &ma_offs, sc->sectorsize, NULL, osp,
708 					    MD_MALLOC_MOVE_FILL);
709 				} else
710 					memset(dst, osp, sc->sectorsize);
711 			} else {
712 				if (notmapped) {
713 					error = md_malloc_move_ma(&m, &ma_offs,
714 					    sc->sectorsize, (void *)osp, 0,
715 					    MD_MALLOC_MOVE_READ);
716 				} else if (vlist != NULL) {
717 					error = md_malloc_move_vlist(&vlist,
718 					    &ma_offs, sc->sectorsize,
719 					    (void *)osp, 0,
720 					    MD_MALLOC_MOVE_READ);
721 				} else {
722 					bcopy((void *)osp, dst, sc->sectorsize);
723 					cpu_flush_dcache(dst, sc->sectorsize);
724 				}
725 			}
726 			osp = 0;
727 		} else if (bp->bio_cmd == BIO_WRITE) {
728 			if (sc->flags & MD_COMPRESS) {
729 				if (notmapped) {
730 					error1 = md_malloc_move_ma(&m, &ma_offs,
731 					    sc->sectorsize, &uc, 0,
732 					    MD_MALLOC_MOVE_CMP);
733 					i = error1 == 0 ? sc->sectorsize : 0;
734 				} else if (vlist != NULL) {
735 					error1 = md_malloc_move_vlist(&vlist,
736 					    &ma_offs, sc->sectorsize, &uc, 0,
737 					    MD_MALLOC_MOVE_CMP);
738 					i = error1 == 0 ? sc->sectorsize : 0;
739 				} else {
740 					uc = dst[0];
741 					for (i = 1; i < sc->sectorsize; i++) {
742 						if (dst[i] != uc)
743 							break;
744 					}
745 				}
746 			} else {
747 				i = 0;
748 				uc = 0;
749 			}
750 			if (i == sc->sectorsize) {
751 				if (osp != uc)
752 					error = s_write(sc->indir, secno, uc);
753 			} else {
754 				if (osp <= 255) {
755 					sp = (uintptr_t)uma_zalloc(sc->uma,
756 					    md_malloc_wait ? M_WAITOK :
757 					    M_NOWAIT);
758 					if (sp == 0) {
759 						error = ENOSPC;
760 						break;
761 					}
762 					if (notmapped) {
763 						error = md_malloc_move_ma(&m,
764 						    &ma_offs, sc->sectorsize,
765 						    (void *)sp, 0,
766 						    MD_MALLOC_MOVE_WRITE);
767 					} else if (vlist != NULL) {
768 						error = md_malloc_move_vlist(
769 						    &vlist, &ma_offs,
770 						    sc->sectorsize, (void *)sp,
771 						    0, MD_MALLOC_MOVE_WRITE);
772 					} else {
773 						bcopy(dst, (void *)sp,
774 						    sc->sectorsize);
775 					}
776 					error = s_write(sc->indir, secno, sp);
777 				} else {
778 					if (notmapped) {
779 						error = md_malloc_move_ma(&m,
780 						    &ma_offs, sc->sectorsize,
781 						    (void *)osp, 0,
782 						    MD_MALLOC_MOVE_WRITE);
783 					} else if (vlist != NULL) {
784 						error = md_malloc_move_vlist(
785 						    &vlist, &ma_offs,
786 						    sc->sectorsize, (void *)osp,
787 						    0, MD_MALLOC_MOVE_WRITE);
788 					} else {
789 						bcopy(dst, (void *)osp,
790 						    sc->sectorsize);
791 					}
792 					osp = 0;
793 				}
794 			}
795 		} else {
796 			error = EOPNOTSUPP;
797 		}
798 		if (osp > 255)
799 			uma_zfree(sc->uma, (void*)osp);
800 		if (error != 0)
801 			break;
802 		secno++;
803 		if (!notmapped && vlist == NULL)
804 			dst += sc->sectorsize;
805 	}
806 	bp->bio_resid = 0;
807 	return (error);
808 }
809 
810 static void
mdcopyto_vlist(void * src,bus_dma_segment_t * vlist,off_t offset,off_t len)811 mdcopyto_vlist(void *src, bus_dma_segment_t *vlist, off_t offset, off_t len)
812 {
813 	off_t seg_len;
814 
815 	while (offset >= vlist->ds_len) {
816 		offset -= vlist->ds_len;
817 		vlist++;
818 	}
819 
820 	while (len != 0) {
821 		seg_len = omin(len, vlist->ds_len - offset);
822 		bcopy(src, (void *)(uintptr_t)(vlist->ds_addr + offset),
823 		    seg_len);
824 		offset = 0;
825 		src = (uint8_t *)src + seg_len;
826 		len -= seg_len;
827 		vlist++;
828 	}
829 }
830 
831 static void
mdcopyfrom_vlist(bus_dma_segment_t * vlist,off_t offset,void * dst,off_t len)832 mdcopyfrom_vlist(bus_dma_segment_t *vlist, off_t offset, void *dst, off_t len)
833 {
834 	off_t seg_len;
835 
836 	while (offset >= vlist->ds_len) {
837 		offset -= vlist->ds_len;
838 		vlist++;
839 	}
840 
841 	while (len != 0) {
842 		seg_len = omin(len, vlist->ds_len - offset);
843 		bcopy((void *)(uintptr_t)(vlist->ds_addr + offset), dst,
844 		    seg_len);
845 		offset = 0;
846 		dst = (uint8_t *)dst + seg_len;
847 		len -= seg_len;
848 		vlist++;
849 	}
850 }
851 
852 static int
mdstart_preload(struct md_s * sc,struct bio * bp)853 mdstart_preload(struct md_s *sc, struct bio *bp)
854 {
855 	uint8_t *p;
856 
857 	p = sc->pl_ptr + bp->bio_offset;
858 	switch (bp->bio_cmd) {
859 	case BIO_READ:
860 		if ((bp->bio_flags & BIO_VLIST) != 0) {
861 			mdcopyto_vlist(p, (bus_dma_segment_t *)bp->bio_data,
862 			    bp->bio_ma_offset, bp->bio_length);
863 		} else {
864 			bcopy(p, bp->bio_data, bp->bio_length);
865 		}
866 		cpu_flush_dcache(bp->bio_data, bp->bio_length);
867 		break;
868 	case BIO_WRITE:
869 		if ((bp->bio_flags & BIO_VLIST) != 0) {
870 			mdcopyfrom_vlist((bus_dma_segment_t *)bp->bio_data,
871 			    bp->bio_ma_offset, p, bp->bio_length);
872 		} else {
873 			bcopy(bp->bio_data, p, bp->bio_length);
874 		}
875 		break;
876 	}
877 	bp->bio_resid = 0;
878 	return (0);
879 }
880 
881 static int
mdstart_vnode(struct md_s * sc,struct bio * bp)882 mdstart_vnode(struct md_s *sc, struct bio *bp)
883 {
884 	int error;
885 	struct uio auio;
886 	struct iovec aiov;
887 	struct iovec *piov;
888 	struct mount *mp;
889 	struct vnode *vp;
890 	struct buf *pb;
891 	bus_dma_segment_t *vlist;
892 	struct thread *td;
893 	off_t iolen, len, zerosize;
894 	int ma_offs, npages;
895 
896 	switch (bp->bio_cmd) {
897 	case BIO_READ:
898 		auio.uio_rw = UIO_READ;
899 		break;
900 	case BIO_WRITE:
901 	case BIO_DELETE:
902 		auio.uio_rw = UIO_WRITE;
903 		break;
904 	case BIO_FLUSH:
905 		break;
906 	default:
907 		return (EOPNOTSUPP);
908 	}
909 
910 	td = curthread;
911 	vp = sc->vnode;
912 	pb = NULL;
913 	piov = NULL;
914 	ma_offs = bp->bio_ma_offset;
915 	len = bp->bio_length;
916 
917 	/*
918 	 * VNODE I/O
919 	 *
920 	 * If an error occurs, we set BIO_ERROR but we do not set
921 	 * B_INVAL because (for a write anyway), the buffer is
922 	 * still valid.
923 	 */
924 
925 	if (bp->bio_cmd == BIO_FLUSH) {
926 		(void) vn_start_write(vp, &mp, V_WAIT);
927 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
928 		error = VOP_FSYNC(vp, MNT_WAIT, td);
929 		VOP_UNLOCK(vp, 0);
930 		vn_finished_write(mp);
931 		return (error);
932 	}
933 
934 	auio.uio_offset = (vm_ooffset_t)bp->bio_offset;
935 	auio.uio_resid = bp->bio_length;
936 	auio.uio_segflg = UIO_SYSSPACE;
937 	auio.uio_td = td;
938 
939 	if (bp->bio_cmd == BIO_DELETE) {
940 		/*
941 		 * Emulate BIO_DELETE by writing zeros.
942 		 */
943 		zerosize = ZERO_REGION_SIZE -
944 		    (ZERO_REGION_SIZE % sc->sectorsize);
945 		auio.uio_iovcnt = howmany(bp->bio_length, zerosize);
946 		piov = malloc(sizeof(*piov) * auio.uio_iovcnt, M_MD, M_WAITOK);
947 		auio.uio_iov = piov;
948 		while (len > 0) {
949 			piov->iov_base = __DECONST(void *, zero_region);
950 			piov->iov_len = len;
951 			if (len > zerosize)
952 				piov->iov_len = zerosize;
953 			len -= piov->iov_len;
954 			piov++;
955 		}
956 		piov = auio.uio_iov;
957 	} else if ((bp->bio_flags & BIO_VLIST) != 0) {
958 		piov = malloc(sizeof(*piov) * bp->bio_ma_n, M_MD, M_WAITOK);
959 		auio.uio_iov = piov;
960 		vlist = (bus_dma_segment_t *)bp->bio_data;
961 		while (len > 0) {
962 			piov->iov_base = (void *)(uintptr_t)(vlist->ds_addr +
963 			    ma_offs);
964 			piov->iov_len = vlist->ds_len - ma_offs;
965 			if (piov->iov_len > len)
966 				piov->iov_len = len;
967 			len -= piov->iov_len;
968 			ma_offs = 0;
969 			vlist++;
970 			piov++;
971 		}
972 		auio.uio_iovcnt = piov - auio.uio_iov;
973 		piov = auio.uio_iov;
974 	} else if ((bp->bio_flags & BIO_UNMAPPED) != 0) {
975 		pb = getpbuf(&md_vnode_pbuf_freecnt);
976 		bp->bio_resid = len;
977 unmapped_step:
978 		npages = atop(min(MAXPHYS, round_page(len + (ma_offs &
979 		    PAGE_MASK))));
980 		iolen = min(ptoa(npages) - (ma_offs & PAGE_MASK), len);
981 		KASSERT(iolen > 0, ("zero iolen"));
982 		pmap_qenter((vm_offset_t)pb->b_data,
983 		    &bp->bio_ma[atop(ma_offs)], npages);
984 		aiov.iov_base = (void *)((vm_offset_t)pb->b_data +
985 		    (ma_offs & PAGE_MASK));
986 		aiov.iov_len = iolen;
987 		auio.uio_iov = &aiov;
988 		auio.uio_iovcnt = 1;
989 		auio.uio_resid = iolen;
990 	} else {
991 		aiov.iov_base = bp->bio_data;
992 		aiov.iov_len = bp->bio_length;
993 		auio.uio_iov = &aiov;
994 		auio.uio_iovcnt = 1;
995 	}
996 	/*
997 	 * When reading set IO_DIRECT to try to avoid double-caching
998 	 * the data.  When writing IO_DIRECT is not optimal.
999 	 */
1000 	if (auio.uio_rw == UIO_READ) {
1001 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1002 		error = VOP_READ(vp, &auio, IO_DIRECT, sc->cred);
1003 		VOP_UNLOCK(vp, 0);
1004 	} else {
1005 		(void) vn_start_write(vp, &mp, V_WAIT);
1006 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1007 		error = VOP_WRITE(vp, &auio, sc->flags & MD_ASYNC ? 0 : IO_SYNC,
1008 		    sc->cred);
1009 		VOP_UNLOCK(vp, 0);
1010 		vn_finished_write(mp);
1011 		if (error == 0)
1012 			sc->flags &= ~MD_VERIFY;
1013 	}
1014 
1015 	if (pb != NULL) {
1016 		pmap_qremove((vm_offset_t)pb->b_data, npages);
1017 		if (error == 0) {
1018 			len -= iolen;
1019 			bp->bio_resid -= iolen;
1020 			ma_offs += iolen;
1021 			if (len > 0)
1022 				goto unmapped_step;
1023 		}
1024 		relpbuf(pb, &md_vnode_pbuf_freecnt);
1025 	}
1026 
1027 	free(piov, M_MD);
1028 	if (pb == NULL)
1029 		bp->bio_resid = auio.uio_resid;
1030 	return (error);
1031 }
1032 
1033 static void
md_swap_page_free(vm_page_t m)1034 md_swap_page_free(vm_page_t m)
1035 {
1036 
1037 	vm_page_xunbusy(m);
1038 	vm_page_lock(m);
1039 	vm_page_free(m);
1040 	vm_page_unlock(m);
1041 }
1042 
1043 static int
mdstart_swap(struct md_s * sc,struct bio * bp)1044 mdstart_swap(struct md_s *sc, struct bio *bp)
1045 {
1046 	vm_page_t m;
1047 	u_char *p;
1048 	vm_pindex_t i, lastp;
1049 	bus_dma_segment_t *vlist;
1050 	int rv, ma_offs, offs, len, lastend;
1051 
1052 	switch (bp->bio_cmd) {
1053 	case BIO_READ:
1054 	case BIO_WRITE:
1055 	case BIO_DELETE:
1056 		break;
1057 	default:
1058 		return (EOPNOTSUPP);
1059 	}
1060 
1061 	p = bp->bio_data;
1062 	ma_offs = (bp->bio_flags & (BIO_UNMAPPED|BIO_VLIST)) != 0 ?
1063 	    bp->bio_ma_offset : 0;
1064 	vlist = (bp->bio_flags & BIO_VLIST) != 0 ?
1065 	    (bus_dma_segment_t *)bp->bio_data : NULL;
1066 
1067 	/*
1068 	 * offs is the offset at which to start operating on the
1069 	 * next (ie, first) page.  lastp is the last page on
1070 	 * which we're going to operate.  lastend is the ending
1071 	 * position within that last page (ie, PAGE_SIZE if
1072 	 * we're operating on complete aligned pages).
1073 	 */
1074 	offs = bp->bio_offset % PAGE_SIZE;
1075 	lastp = (bp->bio_offset + bp->bio_length - 1) / PAGE_SIZE;
1076 	lastend = (bp->bio_offset + bp->bio_length - 1) % PAGE_SIZE + 1;
1077 
1078 	rv = VM_PAGER_OK;
1079 	VM_OBJECT_WLOCK(sc->object);
1080 	vm_object_pip_add(sc->object, 1);
1081 	for (i = bp->bio_offset / PAGE_SIZE; i <= lastp; i++) {
1082 		len = ((i == lastp) ? lastend : PAGE_SIZE) - offs;
1083 		m = vm_page_grab(sc->object, i, VM_ALLOC_SYSTEM);
1084 		if (bp->bio_cmd == BIO_READ) {
1085 			if (m->valid == VM_PAGE_BITS_ALL)
1086 				rv = VM_PAGER_OK;
1087 			else
1088 				rv = vm_pager_get_pages(sc->object, &m, 1,
1089 				    NULL, NULL);
1090 			if (rv == VM_PAGER_ERROR) {
1091 				md_swap_page_free(m);
1092 				break;
1093 			} else if (rv == VM_PAGER_FAIL) {
1094 				/*
1095 				 * Pager does not have the page.  Zero
1096 				 * the allocated page, and mark it as
1097 				 * valid. Do not set dirty, the page
1098 				 * can be recreated if thrown out.
1099 				 */
1100 				pmap_zero_page(m);
1101 				m->valid = VM_PAGE_BITS_ALL;
1102 			}
1103 			if ((bp->bio_flags & BIO_UNMAPPED) != 0) {
1104 				pmap_copy_pages(&m, offs, bp->bio_ma,
1105 				    ma_offs, len);
1106 			} else if ((bp->bio_flags & BIO_VLIST) != 0) {
1107 				physcopyout_vlist(VM_PAGE_TO_PHYS(m) + offs,
1108 				    vlist, ma_offs, len);
1109 				cpu_flush_dcache(p, len);
1110 			} else {
1111 				physcopyout(VM_PAGE_TO_PHYS(m) + offs, p, len);
1112 				cpu_flush_dcache(p, len);
1113 			}
1114 		} else if (bp->bio_cmd == BIO_WRITE) {
1115 			if (len == PAGE_SIZE || m->valid == VM_PAGE_BITS_ALL)
1116 				rv = VM_PAGER_OK;
1117 			else
1118 				rv = vm_pager_get_pages(sc->object, &m, 1,
1119 				    NULL, NULL);
1120 			if (rv == VM_PAGER_ERROR) {
1121 				md_swap_page_free(m);
1122 				break;
1123 			} else if (rv == VM_PAGER_FAIL)
1124 				pmap_zero_page(m);
1125 
1126 			if ((bp->bio_flags & BIO_UNMAPPED) != 0) {
1127 				pmap_copy_pages(bp->bio_ma, ma_offs, &m,
1128 				    offs, len);
1129 			} else if ((bp->bio_flags & BIO_VLIST) != 0) {
1130 				physcopyin_vlist(vlist, ma_offs,
1131 				    VM_PAGE_TO_PHYS(m) + offs, len);
1132 			} else {
1133 				physcopyin(p, VM_PAGE_TO_PHYS(m) + offs, len);
1134 			}
1135 
1136 			m->valid = VM_PAGE_BITS_ALL;
1137 			if (m->dirty != VM_PAGE_BITS_ALL) {
1138 				vm_page_dirty(m);
1139 				vm_pager_page_unswapped(m);
1140 			}
1141 		} else if (bp->bio_cmd == BIO_DELETE) {
1142 			if (len == PAGE_SIZE || m->valid == VM_PAGE_BITS_ALL)
1143 				rv = VM_PAGER_OK;
1144 			else
1145 				rv = vm_pager_get_pages(sc->object, &m, 1,
1146 				    NULL, NULL);
1147 			if (rv == VM_PAGER_ERROR) {
1148 				md_swap_page_free(m);
1149 				break;
1150 			} else if (rv == VM_PAGER_FAIL) {
1151 				md_swap_page_free(m);
1152 				m = NULL;
1153 			} else {
1154 				/* Page is valid. */
1155 				if (len != PAGE_SIZE) {
1156 					pmap_zero_page_area(m, offs, len);
1157 					if (m->dirty != VM_PAGE_BITS_ALL) {
1158 						vm_page_dirty(m);
1159 						vm_pager_page_unswapped(m);
1160 					}
1161 				} else {
1162 					vm_pager_page_unswapped(m);
1163 					md_swap_page_free(m);
1164 					m = NULL;
1165 				}
1166 			}
1167 		}
1168 		if (m != NULL) {
1169 			vm_page_xunbusy(m);
1170 			vm_page_lock(m);
1171 			if (vm_page_active(m))
1172 				vm_page_reference(m);
1173 			else
1174 				vm_page_activate(m);
1175 			vm_page_unlock(m);
1176 		}
1177 
1178 		/* Actions on further pages start at offset 0 */
1179 		p += PAGE_SIZE - offs;
1180 		offs = 0;
1181 		ma_offs += len;
1182 	}
1183 	vm_object_pip_wakeup(sc->object);
1184 	VM_OBJECT_WUNLOCK(sc->object);
1185 	return (rv != VM_PAGER_ERROR ? 0 : ENOSPC);
1186 }
1187 
1188 static int
mdstart_null(struct md_s * sc,struct bio * bp)1189 mdstart_null(struct md_s *sc, struct bio *bp)
1190 {
1191 
1192 	switch (bp->bio_cmd) {
1193 	case BIO_READ:
1194 		bzero(bp->bio_data, bp->bio_length);
1195 		cpu_flush_dcache(bp->bio_data, bp->bio_length);
1196 		break;
1197 	case BIO_WRITE:
1198 		break;
1199 	}
1200 	bp->bio_resid = 0;
1201 	return (0);
1202 }
1203 
1204 static void
md_kthread(void * arg)1205 md_kthread(void *arg)
1206 {
1207 	struct md_s *sc;
1208 	struct bio *bp;
1209 	int error;
1210 
1211 	sc = arg;
1212 	thread_lock(curthread);
1213 	sched_prio(curthread, PRIBIO);
1214 	thread_unlock(curthread);
1215 	if (sc->type == MD_VNODE)
1216 		curthread->td_pflags |= TDP_NORUNNINGBUF;
1217 
1218 	for (;;) {
1219 		mtx_lock(&sc->queue_mtx);
1220 		if (sc->flags & MD_SHUTDOWN) {
1221 			sc->flags |= MD_EXITING;
1222 			mtx_unlock(&sc->queue_mtx);
1223 			kproc_exit(0);
1224 		}
1225 		bp = bioq_takefirst(&sc->bio_queue);
1226 		if (!bp) {
1227 			msleep(sc, &sc->queue_mtx, PRIBIO | PDROP, "mdwait", 0);
1228 			continue;
1229 		}
1230 		mtx_unlock(&sc->queue_mtx);
1231 		if (bp->bio_cmd == BIO_GETATTR) {
1232 			int isv = ((sc->flags & MD_VERIFY) != 0);
1233 
1234 			if ((sc->fwsectors && sc->fwheads &&
1235 			    (g_handleattr_int(bp, "GEOM::fwsectors",
1236 			    sc->fwsectors) ||
1237 			    g_handleattr_int(bp, "GEOM::fwheads",
1238 			    sc->fwheads))) ||
1239 			    g_handleattr_int(bp, "GEOM::candelete", 1))
1240 				error = -1;
1241 			else if (sc->ident[0] != '\0' &&
1242 			    g_handleattr_str(bp, "GEOM::ident", sc->ident))
1243 				error = -1;
1244 			else if (g_handleattr_int(bp, "MNT::verified", isv))
1245 				error = -1;
1246 			else
1247 				error = EOPNOTSUPP;
1248 		} else {
1249 			error = sc->start(sc, bp);
1250 		}
1251 
1252 		if (error != -1) {
1253 			bp->bio_completed = bp->bio_length;
1254 			if ((bp->bio_cmd == BIO_READ) || (bp->bio_cmd == BIO_WRITE))
1255 				devstat_end_transaction_bio(sc->devstat, bp);
1256 			g_io_deliver(bp, error);
1257 		}
1258 	}
1259 }
1260 
1261 static struct md_s *
mdfind(int unit)1262 mdfind(int unit)
1263 {
1264 	struct md_s *sc;
1265 
1266 	LIST_FOREACH(sc, &md_softc_list, list) {
1267 		if (sc->unit == unit)
1268 			break;
1269 	}
1270 	return (sc);
1271 }
1272 
1273 static struct md_s *
mdnew(int unit,int * errp,enum md_types type)1274 mdnew(int unit, int *errp, enum md_types type)
1275 {
1276 	struct md_s *sc;
1277 	int error;
1278 
1279 	*errp = 0;
1280 	if (unit == -1)
1281 		unit = alloc_unr(md_uh);
1282 	else
1283 		unit = alloc_unr_specific(md_uh, unit);
1284 
1285 	if (unit == -1) {
1286 		*errp = EBUSY;
1287 		return (NULL);
1288 	}
1289 
1290 	sc = (struct md_s *)malloc(sizeof *sc, M_MD, M_WAITOK | M_ZERO);
1291 	sc->type = type;
1292 	bioq_init(&sc->bio_queue);
1293 	mtx_init(&sc->queue_mtx, "md bio queue", NULL, MTX_DEF);
1294 	mtx_init(&sc->stat_mtx, "md stat", NULL, MTX_DEF);
1295 	sc->unit = unit;
1296 	sprintf(sc->name, "md%d", unit);
1297 	LIST_INSERT_HEAD(&md_softc_list, sc, list);
1298 	error = kproc_create(md_kthread, sc, &sc->procp, 0, 0,"%s", sc->name);
1299 	if (error == 0)
1300 		return (sc);
1301 	LIST_REMOVE(sc, list);
1302 	mtx_destroy(&sc->stat_mtx);
1303 	mtx_destroy(&sc->queue_mtx);
1304 	free_unr(md_uh, sc->unit);
1305 	free(sc, M_MD);
1306 	*errp = error;
1307 	return (NULL);
1308 }
1309 
1310 static void
mdinit(struct md_s * sc)1311 mdinit(struct md_s *sc)
1312 {
1313 	struct g_geom *gp;
1314 	struct g_provider *pp;
1315 
1316 	g_topology_lock();
1317 	gp = g_new_geomf(&g_md_class, "md%d", sc->unit);
1318 	gp->softc = sc;
1319 	pp = g_new_providerf(gp, "md%d", sc->unit);
1320 	devstat_remove_entry(pp->stat);
1321 	pp->stat = NULL;
1322 	pp->flags |= G_PF_DIRECT_SEND | G_PF_DIRECT_RECEIVE;
1323 	pp->mediasize = sc->mediasize;
1324 	pp->sectorsize = sc->sectorsize;
1325 	switch (sc->type) {
1326 	case MD_MALLOC:
1327 	case MD_VNODE:
1328 	case MD_SWAP:
1329 		pp->flags |= G_PF_ACCEPT_UNMAPPED;
1330 		break;
1331 	case MD_PRELOAD:
1332 	case MD_NULL:
1333 		break;
1334 	}
1335 	sc->gp = gp;
1336 	sc->pp = pp;
1337 	sc->devstat = devstat_new_entry("md", sc->unit, sc->sectorsize,
1338 	    DEVSTAT_ALL_SUPPORTED, DEVSTAT_TYPE_DIRECT, DEVSTAT_PRIORITY_MAX);
1339 	sc->devstat->id = pp;
1340 	g_error_provider(pp, 0);
1341 	g_topology_unlock();
1342 }
1343 
1344 static int
mdcreate_malloc(struct md_s * sc,struct md_req * mdr)1345 mdcreate_malloc(struct md_s *sc, struct md_req *mdr)
1346 {
1347 	uintptr_t sp;
1348 	int error;
1349 	off_t u;
1350 
1351 	error = 0;
1352 	if (mdr->md_options & ~(MD_AUTOUNIT | MD_COMPRESS | MD_RESERVE))
1353 		return (EINVAL);
1354 	if (mdr->md_sectorsize != 0 && !powerof2(mdr->md_sectorsize))
1355 		return (EINVAL);
1356 	/* Compression doesn't make sense if we have reserved space */
1357 	if (mdr->md_options & MD_RESERVE)
1358 		mdr->md_options &= ~MD_COMPRESS;
1359 	if (mdr->md_fwsectors != 0)
1360 		sc->fwsectors = mdr->md_fwsectors;
1361 	if (mdr->md_fwheads != 0)
1362 		sc->fwheads = mdr->md_fwheads;
1363 	sc->flags = mdr->md_options & (MD_COMPRESS | MD_FORCE);
1364 	sc->indir = dimension(sc->mediasize / sc->sectorsize);
1365 	sc->uma = uma_zcreate(sc->name, sc->sectorsize, NULL, NULL, NULL, NULL,
1366 	    0x1ff, 0);
1367 	if (mdr->md_options & MD_RESERVE) {
1368 		off_t nsectors;
1369 
1370 		nsectors = sc->mediasize / sc->sectorsize;
1371 		for (u = 0; u < nsectors; u++) {
1372 			sp = (uintptr_t)uma_zalloc(sc->uma, (md_malloc_wait ?
1373 			    M_WAITOK : M_NOWAIT) | M_ZERO);
1374 			if (sp != 0)
1375 				error = s_write(sc->indir, u, sp);
1376 			else
1377 				error = ENOMEM;
1378 			if (error != 0)
1379 				break;
1380 		}
1381 	}
1382 	return (error);
1383 }
1384 
1385 
1386 static int
mdsetcred(struct md_s * sc,struct ucred * cred)1387 mdsetcred(struct md_s *sc, struct ucred *cred)
1388 {
1389 	char *tmpbuf;
1390 	int error = 0;
1391 
1392 	/*
1393 	 * Set credits in our softc
1394 	 */
1395 
1396 	if (sc->cred)
1397 		crfree(sc->cred);
1398 	sc->cred = crhold(cred);
1399 
1400 	/*
1401 	 * Horrible kludge to establish credentials for NFS  XXX.
1402 	 */
1403 
1404 	if (sc->vnode) {
1405 		struct uio auio;
1406 		struct iovec aiov;
1407 
1408 		tmpbuf = malloc(sc->sectorsize, M_TEMP, M_WAITOK);
1409 		bzero(&auio, sizeof(auio));
1410 
1411 		aiov.iov_base = tmpbuf;
1412 		aiov.iov_len = sc->sectorsize;
1413 		auio.uio_iov = &aiov;
1414 		auio.uio_iovcnt = 1;
1415 		auio.uio_offset = 0;
1416 		auio.uio_rw = UIO_READ;
1417 		auio.uio_segflg = UIO_SYSSPACE;
1418 		auio.uio_resid = aiov.iov_len;
1419 		vn_lock(sc->vnode, LK_EXCLUSIVE | LK_RETRY);
1420 		error = VOP_READ(sc->vnode, &auio, 0, sc->cred);
1421 		VOP_UNLOCK(sc->vnode, 0);
1422 		free(tmpbuf, M_TEMP);
1423 	}
1424 	return (error);
1425 }
1426 
1427 static int
mdcreate_vnode(struct md_s * sc,struct md_req * mdr,struct thread * td)1428 mdcreate_vnode(struct md_s *sc, struct md_req *mdr, struct thread *td)
1429 {
1430 	struct vattr vattr;
1431 	struct nameidata nd;
1432 	char *fname;
1433 	int error, flags;
1434 
1435 	fname = mdr->md_file;
1436 	if (mdr->md_file_seg == UIO_USERSPACE) {
1437 		error = copyinstr(fname, sc->file, sizeof(sc->file), NULL);
1438 		if (error != 0)
1439 			return (error);
1440 	} else if (mdr->md_file_seg == UIO_SYSSPACE)
1441 		strlcpy(sc->file, fname, sizeof(sc->file));
1442 	else
1443 		return (EDOOFUS);
1444 
1445 	/*
1446 	 * If the user specified that this is a read only device, don't
1447 	 * set the FWRITE mask before trying to open the backing store.
1448 	 */
1449 	flags = FREAD | ((mdr->md_options & MD_READONLY) ? 0 : FWRITE) \
1450 	    | ((mdr->md_options & MD_VERIFY) ? O_VERIFY : 0);
1451 	NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, sc->file, td);
1452 	error = vn_open(&nd, &flags, 0, NULL);
1453 	if (error != 0)
1454 		return (error);
1455 	NDFREE(&nd, NDF_ONLY_PNBUF);
1456 	if (nd.ni_vp->v_type != VREG) {
1457 		error = EINVAL;
1458 		goto bad;
1459 	}
1460 	error = VOP_GETATTR(nd.ni_vp, &vattr, td->td_ucred);
1461 	if (error != 0)
1462 		goto bad;
1463 	if (VOP_ISLOCKED(nd.ni_vp) != LK_EXCLUSIVE) {
1464 		vn_lock(nd.ni_vp, LK_UPGRADE | LK_RETRY);
1465 		if (nd.ni_vp->v_iflag & VI_DOOMED) {
1466 			/* Forced unmount. */
1467 			error = EBADF;
1468 			goto bad;
1469 		}
1470 	}
1471 	nd.ni_vp->v_vflag |= VV_MD;
1472 	VOP_UNLOCK(nd.ni_vp, 0);
1473 
1474 	if (mdr->md_fwsectors != 0)
1475 		sc->fwsectors = mdr->md_fwsectors;
1476 	if (mdr->md_fwheads != 0)
1477 		sc->fwheads = mdr->md_fwheads;
1478 	snprintf(sc->ident, sizeof(sc->ident), "MD-DEV%ju-INO%ju",
1479 	    (uintmax_t)vattr.va_fsid, (uintmax_t)vattr.va_fileid);
1480 	sc->flags = mdr->md_options & (MD_FORCE | MD_ASYNC | MD_VERIFY);
1481 	if (!(flags & FWRITE))
1482 		sc->flags |= MD_READONLY;
1483 	sc->vnode = nd.ni_vp;
1484 
1485 	error = mdsetcred(sc, td->td_ucred);
1486 	if (error != 0) {
1487 		sc->vnode = NULL;
1488 		vn_lock(nd.ni_vp, LK_EXCLUSIVE | LK_RETRY);
1489 		nd.ni_vp->v_vflag &= ~VV_MD;
1490 		goto bad;
1491 	}
1492 	return (0);
1493 bad:
1494 	VOP_UNLOCK(nd.ni_vp, 0);
1495 	(void)vn_close(nd.ni_vp, flags, td->td_ucred, td);
1496 	return (error);
1497 }
1498 
1499 static void
g_md_providergone(struct g_provider * pp)1500 g_md_providergone(struct g_provider *pp)
1501 {
1502 	struct md_s *sc = pp->geom->softc;
1503 
1504 	mtx_lock(&sc->queue_mtx);
1505 	sc->flags |= MD_PROVIDERGONE;
1506 	wakeup(&sc->flags);
1507 	mtx_unlock(&sc->queue_mtx);
1508 }
1509 
1510 static int
mddestroy(struct md_s * sc,struct thread * td)1511 mddestroy(struct md_s *sc, struct thread *td)
1512 {
1513 
1514 	if (sc->gp) {
1515 		g_topology_lock();
1516 		g_wither_geom(sc->gp, ENXIO);
1517 		g_topology_unlock();
1518 
1519 		mtx_lock(&sc->queue_mtx);
1520 		while (!(sc->flags & MD_PROVIDERGONE))
1521 			msleep(&sc->flags, &sc->queue_mtx, PRIBIO, "mddestroy", 0);
1522 		mtx_unlock(&sc->queue_mtx);
1523 	}
1524 	if (sc->devstat) {
1525 		devstat_remove_entry(sc->devstat);
1526 		sc->devstat = NULL;
1527 	}
1528 	mtx_lock(&sc->queue_mtx);
1529 	sc->flags |= MD_SHUTDOWN;
1530 	wakeup(sc);
1531 	while (!(sc->flags & MD_EXITING))
1532 		msleep(sc->procp, &sc->queue_mtx, PRIBIO, "mddestroy", hz / 10);
1533 	mtx_unlock(&sc->queue_mtx);
1534 	mtx_destroy(&sc->stat_mtx);
1535 	mtx_destroy(&sc->queue_mtx);
1536 	if (sc->vnode != NULL) {
1537 		vn_lock(sc->vnode, LK_EXCLUSIVE | LK_RETRY);
1538 		sc->vnode->v_vflag &= ~VV_MD;
1539 		VOP_UNLOCK(sc->vnode, 0);
1540 		(void)vn_close(sc->vnode, sc->flags & MD_READONLY ?
1541 		    FREAD : (FREAD|FWRITE), sc->cred, td);
1542 	}
1543 	if (sc->cred != NULL)
1544 		crfree(sc->cred);
1545 	if (sc->object != NULL)
1546 		vm_object_deallocate(sc->object);
1547 	if (sc->indir)
1548 		destroy_indir(sc, sc->indir);
1549 	if (sc->uma)
1550 		uma_zdestroy(sc->uma);
1551 
1552 	LIST_REMOVE(sc, list);
1553 	free_unr(md_uh, sc->unit);
1554 	free(sc, M_MD);
1555 	return (0);
1556 }
1557 
1558 static int
mdresize(struct md_s * sc,struct md_req * mdr)1559 mdresize(struct md_s *sc, struct md_req *mdr)
1560 {
1561 	int error, res;
1562 	vm_pindex_t oldpages, newpages;
1563 
1564 	switch (sc->type) {
1565 	case MD_VNODE:
1566 	case MD_NULL:
1567 		break;
1568 	case MD_SWAP:
1569 		if (mdr->md_mediasize <= 0 ||
1570 		    (mdr->md_mediasize % PAGE_SIZE) != 0)
1571 			return (EDOM);
1572 		oldpages = OFF_TO_IDX(sc->mediasize);
1573 		newpages = OFF_TO_IDX(mdr->md_mediasize);
1574 		if (newpages < oldpages) {
1575 			VM_OBJECT_WLOCK(sc->object);
1576 			vm_object_page_remove(sc->object, newpages, 0, 0);
1577 			swap_pager_freespace(sc->object, newpages,
1578 			    oldpages - newpages);
1579 			swap_release_by_cred(IDX_TO_OFF(oldpages -
1580 			    newpages), sc->cred);
1581 			sc->object->charge = IDX_TO_OFF(newpages);
1582 			sc->object->size = newpages;
1583 			VM_OBJECT_WUNLOCK(sc->object);
1584 		} else if (newpages > oldpages) {
1585 			res = swap_reserve_by_cred(IDX_TO_OFF(newpages -
1586 			    oldpages), sc->cred);
1587 			if (!res)
1588 				return (ENOMEM);
1589 			if ((mdr->md_options & MD_RESERVE) ||
1590 			    (sc->flags & MD_RESERVE)) {
1591 				error = swap_pager_reserve(sc->object,
1592 				    oldpages, newpages - oldpages);
1593 				if (error < 0) {
1594 					swap_release_by_cred(
1595 					    IDX_TO_OFF(newpages - oldpages),
1596 					    sc->cred);
1597 					return (EDOM);
1598 				}
1599 			}
1600 			VM_OBJECT_WLOCK(sc->object);
1601 			sc->object->charge = IDX_TO_OFF(newpages);
1602 			sc->object->size = newpages;
1603 			VM_OBJECT_WUNLOCK(sc->object);
1604 		}
1605 		break;
1606 	default:
1607 		return (EOPNOTSUPP);
1608 	}
1609 
1610 	sc->mediasize = mdr->md_mediasize;
1611 	g_topology_lock();
1612 	g_resize_provider(sc->pp, sc->mediasize);
1613 	g_topology_unlock();
1614 	return (0);
1615 }
1616 
1617 static int
mdcreate_swap(struct md_s * sc,struct md_req * mdr,struct thread * td)1618 mdcreate_swap(struct md_s *sc, struct md_req *mdr, struct thread *td)
1619 {
1620 	vm_ooffset_t npage;
1621 	int error;
1622 
1623 	/*
1624 	 * Range check.  Disallow negative sizes and sizes not being
1625 	 * multiple of page size.
1626 	 */
1627 	if (sc->mediasize <= 0 || (sc->mediasize % PAGE_SIZE) != 0)
1628 		return (EDOM);
1629 
1630 	/*
1631 	 * Allocate an OBJT_SWAP object.
1632 	 *
1633 	 * Note the truncation.
1634 	 */
1635 
1636 	if ((mdr->md_options & MD_VERIFY) != 0)
1637 		return (EINVAL);
1638 	npage = mdr->md_mediasize / PAGE_SIZE;
1639 	if (mdr->md_fwsectors != 0)
1640 		sc->fwsectors = mdr->md_fwsectors;
1641 	if (mdr->md_fwheads != 0)
1642 		sc->fwheads = mdr->md_fwheads;
1643 	sc->object = vm_pager_allocate(OBJT_SWAP, NULL, PAGE_SIZE * npage,
1644 	    VM_PROT_DEFAULT, 0, td->td_ucred);
1645 	if (sc->object == NULL)
1646 		return (ENOMEM);
1647 	sc->flags = mdr->md_options & (MD_FORCE | MD_RESERVE);
1648 	if (mdr->md_options & MD_RESERVE) {
1649 		if (swap_pager_reserve(sc->object, 0, npage) < 0) {
1650 			error = EDOM;
1651 			goto finish;
1652 		}
1653 	}
1654 	error = mdsetcred(sc, td->td_ucred);
1655  finish:
1656 	if (error != 0) {
1657 		vm_object_deallocate(sc->object);
1658 		sc->object = NULL;
1659 	}
1660 	return (error);
1661 }
1662 
1663 static int
mdcreate_null(struct md_s * sc,struct md_req * mdr,struct thread * td)1664 mdcreate_null(struct md_s *sc, struct md_req *mdr, struct thread *td)
1665 {
1666 
1667 	/*
1668 	 * Range check.  Disallow negative sizes and sizes not being
1669 	 * multiple of page size.
1670 	 */
1671 	if (sc->mediasize <= 0 || (sc->mediasize % PAGE_SIZE) != 0)
1672 		return (EDOM);
1673 
1674 	return (0);
1675 }
1676 
1677 static int
kern_mdattach_locked(struct thread * td,struct md_req * mdr)1678 kern_mdattach_locked(struct thread *td, struct md_req *mdr)
1679 {
1680 	struct md_s *sc;
1681 	unsigned sectsize;
1682 	int error, i;
1683 
1684 	sx_assert(&md_sx, SA_XLOCKED);
1685 
1686 	switch (mdr->md_type) {
1687 	case MD_MALLOC:
1688 	case MD_PRELOAD:
1689 	case MD_VNODE:
1690 	case MD_SWAP:
1691 	case MD_NULL:
1692 		break;
1693 	default:
1694 		return (EINVAL);
1695 	}
1696 	if (mdr->md_sectorsize == 0)
1697 		sectsize = DEV_BSIZE;
1698 	else
1699 		sectsize = mdr->md_sectorsize;
1700 	if (sectsize > MAXPHYS || mdr->md_mediasize < sectsize)
1701 		return (EINVAL);
1702 	if (mdr->md_options & MD_AUTOUNIT)
1703 		sc = mdnew(-1, &error, mdr->md_type);
1704 	else {
1705 		if (mdr->md_unit > INT_MAX)
1706 			return (EINVAL);
1707 		sc = mdnew(mdr->md_unit, &error, mdr->md_type);
1708 	}
1709 	if (sc == NULL)
1710 		return (error);
1711 	if (mdr->md_label != NULL)
1712 		error = copyinstr(mdr->md_label, sc->label,
1713 		    sizeof(sc->label), NULL);
1714 	if (error != 0)
1715 		goto err_after_new;
1716 	if (mdr->md_options & MD_AUTOUNIT)
1717 		mdr->md_unit = sc->unit;
1718 	sc->mediasize = mdr->md_mediasize;
1719 	sc->sectorsize = sectsize;
1720 	error = EDOOFUS;
1721 	switch (sc->type) {
1722 	case MD_MALLOC:
1723 		sc->start = mdstart_malloc;
1724 		error = mdcreate_malloc(sc, mdr);
1725 		break;
1726 	case MD_PRELOAD:
1727 		/*
1728 		 * We disallow attaching preloaded memory disks via
1729 		 * ioctl. Preloaded memory disks are automatically
1730 		 * attached in g_md_init().
1731 		 */
1732 		error = EOPNOTSUPP;
1733 		break;
1734 	case MD_VNODE:
1735 		sc->start = mdstart_vnode;
1736 		error = mdcreate_vnode(sc, mdr, td);
1737 		break;
1738 	case MD_SWAP:
1739 		sc->start = mdstart_swap;
1740 		error = mdcreate_swap(sc, mdr, td);
1741 		break;
1742 	case MD_NULL:
1743 		sc->start = mdstart_null;
1744 		error = mdcreate_null(sc, mdr, td);
1745 		break;
1746 	}
1747 err_after_new:
1748 	if (error != 0) {
1749 		mddestroy(sc, td);
1750 		return (error);
1751 	}
1752 
1753 	/* Prune off any residual fractional sector */
1754 	i = sc->mediasize % sc->sectorsize;
1755 	sc->mediasize -= i;
1756 
1757 	mdinit(sc);
1758 	return (0);
1759 }
1760 
1761 static int
kern_mdattach(struct thread * td,struct md_req * mdr)1762 kern_mdattach(struct thread *td, struct md_req *mdr)
1763 {
1764 	int error;
1765 
1766 	sx_xlock(&md_sx);
1767 	error = kern_mdattach_locked(td, mdr);
1768 	sx_xunlock(&md_sx);
1769 	return (error);
1770 }
1771 
1772 static int
kern_mddetach_locked(struct thread * td,struct md_req * mdr)1773 kern_mddetach_locked(struct thread *td, struct md_req *mdr)
1774 {
1775 	struct md_s *sc;
1776 
1777 	sx_assert(&md_sx, SA_XLOCKED);
1778 
1779 	if (mdr->md_mediasize != 0 ||
1780 	    (mdr->md_options & ~MD_FORCE) != 0)
1781 		return (EINVAL);
1782 
1783 	sc = mdfind(mdr->md_unit);
1784 	if (sc == NULL)
1785 		return (ENOENT);
1786 	if (sc->opencount != 0 && !(sc->flags & MD_FORCE) &&
1787 	    !(mdr->md_options & MD_FORCE))
1788 		return (EBUSY);
1789 	return (mddestroy(sc, td));
1790 }
1791 
1792 static int
kern_mddetach(struct thread * td,struct md_req * mdr)1793 kern_mddetach(struct thread *td, struct md_req *mdr)
1794 {
1795 	int error;
1796 
1797 	sx_xlock(&md_sx);
1798 	error = kern_mddetach_locked(td, mdr);
1799 	sx_xunlock(&md_sx);
1800 	return (error);
1801 }
1802 
1803 static int
kern_mdresize_locked(struct md_req * mdr)1804 kern_mdresize_locked(struct md_req *mdr)
1805 {
1806 	struct md_s *sc;
1807 
1808 	sx_assert(&md_sx, SA_XLOCKED);
1809 
1810 	if ((mdr->md_options & ~(MD_FORCE | MD_RESERVE)) != 0)
1811 		return (EINVAL);
1812 
1813 	sc = mdfind(mdr->md_unit);
1814 	if (sc == NULL)
1815 		return (ENOENT);
1816 	if (mdr->md_mediasize < sc->sectorsize)
1817 		return (EINVAL);
1818 	if (mdr->md_mediasize < sc->mediasize &&
1819 	    !(sc->flags & MD_FORCE) &&
1820 	    !(mdr->md_options & MD_FORCE))
1821 		return (EBUSY);
1822 	return (mdresize(sc, mdr));
1823 }
1824 
1825 static int
kern_mdresize(struct md_req * mdr)1826 kern_mdresize(struct md_req *mdr)
1827 {
1828 	int error;
1829 
1830 	sx_xlock(&md_sx);
1831 	error = kern_mdresize_locked(mdr);
1832 	sx_xunlock(&md_sx);
1833 	return (error);
1834 }
1835 
1836 static int
kern_mdquery_locked(struct md_req * mdr)1837 kern_mdquery_locked(struct md_req *mdr)
1838 {
1839 	struct md_s *sc;
1840 	int error;
1841 
1842 	sx_assert(&md_sx, SA_XLOCKED);
1843 
1844 	sc = mdfind(mdr->md_unit);
1845 	if (sc == NULL)
1846 		return (ENOENT);
1847 	mdr->md_type = sc->type;
1848 	mdr->md_options = sc->flags;
1849 	mdr->md_mediasize = sc->mediasize;
1850 	mdr->md_sectorsize = sc->sectorsize;
1851 	error = 0;
1852 	if (mdr->md_label != NULL) {
1853 		error = copyout(sc->label, mdr->md_label,
1854 		    strlen(sc->label) + 1);
1855 		if (error != 0)
1856 			return (error);
1857 	}
1858 	if (sc->type == MD_VNODE ||
1859 	    (sc->type == MD_PRELOAD && mdr->md_file != NULL))
1860 		error = copyout(sc->file, mdr->md_file,
1861 		    strlen(sc->file) + 1);
1862 	return (error);
1863 }
1864 
1865 static int
kern_mdquery(struct md_req * mdr)1866 kern_mdquery(struct md_req *mdr)
1867 {
1868 	int error;
1869 
1870 	sx_xlock(&md_sx);
1871 	error = kern_mdquery_locked(mdr);
1872 	sx_xunlock(&md_sx);
1873 	return (error);
1874 }
1875 
1876 static int
kern_mdlist_locked(struct md_req * mdr)1877 kern_mdlist_locked(struct md_req *mdr)
1878 {
1879 	struct md_s *sc;
1880 	int i;
1881 
1882 	sx_assert(&md_sx, SA_XLOCKED);
1883 
1884 	/*
1885 	 * Write the number of md devices to mdr->md_units[0].
1886 	 * Write the unit number of the first (mdr->md_units_nitems - 2)
1887 	 * units to mdr->md_units[1::(mdr->md_units - 2)] and terminate the
1888 	 * list with -1.
1889 	 *
1890 	 * XXX: There is currently no mechanism to retrieve unit
1891 	 * numbers for more than (MDNPAD - 2) units.
1892 	 *
1893 	 * XXX: Due to the use of LIST_INSERT_HEAD in mdnew(), the
1894 	 * list of visible unit numbers not stable.
1895 	 */
1896 	i = 1;
1897 	LIST_FOREACH(sc, &md_softc_list, list) {
1898 		if (i < mdr->md_units_nitems - 1)
1899 			mdr->md_units[i] = sc->unit;
1900 		i++;
1901 	}
1902 	mdr->md_units[MIN(i, mdr->md_units_nitems - 1)] = -1;
1903 	mdr->md_units[0] = i - 1;
1904 	return (0);
1905 }
1906 
1907 static int
kern_mdlist(struct md_req * mdr)1908 kern_mdlist(struct md_req *mdr)
1909 {
1910 	int error;
1911 
1912 	sx_xlock(&md_sx);
1913 	error = kern_mdlist_locked(mdr);
1914 	sx_xunlock(&md_sx);
1915 	return (error);
1916 }
1917 
1918 /* Copy members that are not userspace pointers. */
1919 #define	MD_IOCTL2REQ(mdio, mdr) do {					\
1920 	(mdr)->md_unit = (mdio)->md_unit;				\
1921 	(mdr)->md_type = (mdio)->md_type;				\
1922 	(mdr)->md_mediasize = (mdio)->md_mediasize;			\
1923 	(mdr)->md_sectorsize = (mdio)->md_sectorsize;			\
1924 	(mdr)->md_options = (mdio)->md_options;				\
1925 	(mdr)->md_fwheads = (mdio)->md_fwheads;				\
1926 	(mdr)->md_fwsectors = (mdio)->md_fwsectors;			\
1927 	(mdr)->md_units = &(mdio)->md_pad[0];				\
1928 	(mdr)->md_units_nitems = nitems((mdio)->md_pad);		\
1929 } while(0)
1930 
1931 /* Copy members that might have been updated */
1932 #define MD_REQ2IOCTL(mdr, mdio) do {					\
1933 	(mdio)->md_unit = (mdr)->md_unit;				\
1934 	(mdio)->md_type = (mdr)->md_type;				\
1935 	(mdio)->md_mediasize = (mdr)->md_mediasize;			\
1936 	(mdio)->md_sectorsize = (mdr)->md_sectorsize;			\
1937 	(mdio)->md_options = (mdr)->md_options;				\
1938 	(mdio)->md_fwheads = (mdr)->md_fwheads;				\
1939 	(mdio)->md_fwsectors = (mdr)->md_fwsectors;			\
1940 } while(0)
1941 
1942 static int
mdctlioctl(struct cdev * dev,u_long cmd,caddr_t addr,int flags,struct thread * td)1943 mdctlioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flags,
1944     struct thread *td)
1945 {
1946 	struct md_req mdr;
1947 	int error;
1948 
1949 	if (md_debug)
1950 		printf("mdctlioctl(%s %lx %p %x %p)\n",
1951 			devtoname(dev), cmd, addr, flags, td);
1952 
1953 	bzero(&mdr, sizeof(mdr));
1954 	switch (cmd) {
1955 	case MDIOCATTACH:
1956 	case MDIOCDETACH:
1957 	case MDIOCRESIZE:
1958 	case MDIOCQUERY:
1959 	case MDIOCLIST: {
1960 		struct md_ioctl *mdio = (struct md_ioctl *)addr;
1961 		if (mdio->md_version != MDIOVERSION)
1962 			return (EINVAL);
1963 		MD_IOCTL2REQ(mdio, &mdr);
1964 		mdr.md_file = mdio->md_file;
1965 		mdr.md_file_seg = UIO_USERSPACE;
1966 		/* If the file is adjacent to the md_ioctl it's in kernel. */
1967 		if ((void *)mdio->md_file == (void *)(mdio + 1))
1968 			mdr.md_file_seg = UIO_SYSSPACE;
1969 		mdr.md_label = mdio->md_label;
1970 		break;
1971 	}
1972 #ifdef COMPAT_FREEBSD32
1973 	case MDIOCATTACH_32:
1974 	case MDIOCDETACH_32:
1975 	case MDIOCRESIZE_32:
1976 	case MDIOCQUERY_32:
1977 	case MDIOCLIST_32: {
1978 		struct md_ioctl32 *mdio = (struct md_ioctl32 *)addr;
1979 		if (mdio->md_version != MDIOVERSION)
1980 			return (EINVAL);
1981 		MD_IOCTL2REQ(mdio, &mdr);
1982 		mdr.md_file = (void *)(uintptr_t)mdio->md_file;
1983 		mdr.md_file_seg = UIO_USERSPACE;
1984 		mdr.md_label = (void *)(uintptr_t)mdio->md_label;
1985 		break;
1986 	}
1987 #endif
1988 	default:
1989 		/* Fall through to handler switch. */
1990 		break;
1991 	}
1992 
1993 	error = 0;
1994 	switch (cmd) {
1995 	case MDIOCATTACH:
1996 #ifdef COMPAT_FREEBSD32
1997 	case MDIOCATTACH_32:
1998 #endif
1999 		error = kern_mdattach(td, &mdr);
2000 		break;
2001 	case MDIOCDETACH:
2002 #ifdef COMPAT_FREEBSD32
2003 	case MDIOCDETACH_32:
2004 #endif
2005 		error = kern_mddetach(td, &mdr);
2006 		break;
2007 	case MDIOCRESIZE:
2008 #ifdef COMPAT_FREEBSD32
2009 	case MDIOCRESIZE_32:
2010 #endif
2011 		error = kern_mdresize(&mdr);
2012 		break;
2013 	case MDIOCQUERY:
2014 #ifdef COMPAT_FREEBSD32
2015 	case MDIOCQUERY_32:
2016 #endif
2017 		error = kern_mdquery(&mdr);
2018 		break;
2019 	case MDIOCLIST:
2020 #ifdef COMPAT_FREEBSD32
2021 	case MDIOCLIST_32:
2022 #endif
2023 		error = kern_mdlist(&mdr);
2024 		break;
2025 	default:
2026 		error = ENOIOCTL;
2027 	}
2028 
2029 	switch (cmd) {
2030 	case MDIOCATTACH:
2031 	case MDIOCQUERY: {
2032 		struct md_ioctl *mdio = (struct md_ioctl *)addr;
2033 		MD_REQ2IOCTL(&mdr, mdio);
2034 		break;
2035 	}
2036 #ifdef COMPAT_FREEBSD32
2037 	case MDIOCATTACH_32:
2038 	case MDIOCQUERY_32: {
2039 		struct md_ioctl32 *mdio = (struct md_ioctl32 *)addr;
2040 		MD_REQ2IOCTL(&mdr, mdio);
2041 		break;
2042 	}
2043 #endif
2044 	default:
2045 		/* Other commands to not alter mdr. */
2046 		break;
2047 	}
2048 
2049 	return (error);
2050 }
2051 
2052 static void
md_preloaded(u_char * image,size_t length,const char * name)2053 md_preloaded(u_char *image, size_t length, const char *name)
2054 {
2055 	struct md_s *sc;
2056 	int error;
2057 
2058 	sc = mdnew(-1, &error, MD_PRELOAD);
2059 	if (sc == NULL)
2060 		return;
2061 	sc->mediasize = length;
2062 	sc->sectorsize = DEV_BSIZE;
2063 	sc->pl_ptr = image;
2064 	sc->pl_len = length;
2065 	sc->start = mdstart_preload;
2066 	if (name != NULL)
2067 		strlcpy(sc->file, name, sizeof(sc->file));
2068 #ifdef MD_ROOT
2069 	if (sc->unit == 0) {
2070 #ifndef ROOTDEVNAME
2071 		rootdevnames[0] = MD_ROOT_FSTYPE ":/dev/md0";
2072 #endif
2073 #ifdef MD_ROOT_READONLY
2074 		sc->flags |= MD_READONLY;
2075 #endif
2076 	}
2077 #endif
2078 	mdinit(sc);
2079 	if (name != NULL) {
2080 		printf("%s%d: Preloaded image <%s> %zd bytes at %p\n",
2081 		    MD_NAME, sc->unit, name, length, image);
2082 	} else {
2083 		printf("%s%d: Embedded image %zd bytes at %p\n",
2084 		    MD_NAME, sc->unit, length, image);
2085 	}
2086 }
2087 
2088 static void
g_md_init(struct g_class * mp __unused)2089 g_md_init(struct g_class *mp __unused)
2090 {
2091 	caddr_t mod;
2092 	u_char *ptr, *name, *type;
2093 	unsigned len;
2094 	int i;
2095 
2096 	/* figure out log2(NINDIR) */
2097 	for (i = NINDIR, nshift = -1; i; nshift++)
2098 		i >>= 1;
2099 
2100 	mod = NULL;
2101 	sx_init(&md_sx, "MD config lock");
2102 	g_topology_unlock();
2103 	md_uh = new_unrhdr(0, INT_MAX, NULL);
2104 #ifdef MD_ROOT
2105 	if (mfs_root_size != 0) {
2106 		sx_xlock(&md_sx);
2107 #ifdef MD_ROOT_MEM
2108 		md_preloaded(mfs_root, mfs_root_size, NULL);
2109 #else
2110 		md_preloaded(__DEVOLATILE(u_char *, &mfs_root), mfs_root_size,
2111 		    NULL);
2112 #endif
2113 		sx_xunlock(&md_sx);
2114 	}
2115 #endif
2116 	/* XXX: are preload_* static or do they need Giant ? */
2117 	while ((mod = preload_search_next_name(mod)) != NULL) {
2118 		name = (char *)preload_search_info(mod, MODINFO_NAME);
2119 		if (name == NULL)
2120 			continue;
2121 		type = (char *)preload_search_info(mod, MODINFO_TYPE);
2122 		if (type == NULL)
2123 			continue;
2124 		if (strcmp(type, "md_image") && strcmp(type, "mfs_root"))
2125 			continue;
2126 		ptr = preload_fetch_addr(mod);
2127 		len = preload_fetch_size(mod);
2128 		if (ptr != NULL && len != 0) {
2129 			sx_xlock(&md_sx);
2130 			md_preloaded(ptr, len, name);
2131 			sx_xunlock(&md_sx);
2132 		}
2133 	}
2134 	md_vnode_pbuf_freecnt = nswbuf / 10;
2135 	status_dev = make_dev(&mdctl_cdevsw, INT_MAX, UID_ROOT, GID_WHEEL,
2136 	    0600, MDCTL_NAME);
2137 	g_topology_lock();
2138 }
2139 
2140 static void
g_md_dumpconf(struct sbuf * sb,const char * indent,struct g_geom * gp,struct g_consumer * cp __unused,struct g_provider * pp)2141 g_md_dumpconf(struct sbuf *sb, const char *indent, struct g_geom *gp,
2142     struct g_consumer *cp __unused, struct g_provider *pp)
2143 {
2144 	struct md_s *mp;
2145 	char *type;
2146 
2147 	mp = gp->softc;
2148 	if (mp == NULL)
2149 		return;
2150 
2151 	switch (mp->type) {
2152 	case MD_MALLOC:
2153 		type = "malloc";
2154 		break;
2155 	case MD_PRELOAD:
2156 		type = "preload";
2157 		break;
2158 	case MD_VNODE:
2159 		type = "vnode";
2160 		break;
2161 	case MD_SWAP:
2162 		type = "swap";
2163 		break;
2164 	case MD_NULL:
2165 		type = "null";
2166 		break;
2167 	default:
2168 		type = "unknown";
2169 		break;
2170 	}
2171 
2172 	if (pp != NULL) {
2173 		if (indent == NULL) {
2174 			sbuf_printf(sb, " u %d", mp->unit);
2175 			sbuf_printf(sb, " s %ju", (uintmax_t) mp->sectorsize);
2176 			sbuf_printf(sb, " f %ju", (uintmax_t) mp->fwheads);
2177 			sbuf_printf(sb, " fs %ju", (uintmax_t) mp->fwsectors);
2178 			sbuf_printf(sb, " l %ju", (uintmax_t) mp->mediasize);
2179 			sbuf_printf(sb, " t %s", type);
2180 			if ((mp->type == MD_VNODE && mp->vnode != NULL) ||
2181 			    (mp->type == MD_PRELOAD && mp->file[0] != '\0'))
2182 				sbuf_printf(sb, " file %s", mp->file);
2183 			sbuf_printf(sb, " label %s", mp->label);
2184 		} else {
2185 			sbuf_printf(sb, "%s<unit>%d</unit>\n", indent,
2186 			    mp->unit);
2187 			sbuf_printf(sb, "%s<sectorsize>%ju</sectorsize>\n",
2188 			    indent, (uintmax_t) mp->sectorsize);
2189 			sbuf_printf(sb, "%s<fwheads>%ju</fwheads>\n",
2190 			    indent, (uintmax_t) mp->fwheads);
2191 			sbuf_printf(sb, "%s<fwsectors>%ju</fwsectors>\n",
2192 			    indent, (uintmax_t) mp->fwsectors);
2193 			if (mp->ident[0] != '\0') {
2194 				sbuf_printf(sb, "%s<ident>", indent);
2195 				g_conf_printf_escaped(sb, "%s", mp->ident);
2196 				sbuf_printf(sb, "</ident>\n");
2197 			}
2198 			sbuf_printf(sb, "%s<length>%ju</length>\n",
2199 			    indent, (uintmax_t) mp->mediasize);
2200 			sbuf_printf(sb, "%s<compression>%s</compression>\n", indent,
2201 			    (mp->flags & MD_COMPRESS) == 0 ? "off": "on");
2202 			sbuf_printf(sb, "%s<access>%s</access>\n", indent,
2203 			    (mp->flags & MD_READONLY) == 0 ? "read-write":
2204 			    "read-only");
2205 			sbuf_printf(sb, "%s<type>%s</type>\n", indent,
2206 			    type);
2207 			if ((mp->type == MD_VNODE && mp->vnode != NULL) ||
2208 			    (mp->type == MD_PRELOAD && mp->file[0] != '\0')) {
2209 				sbuf_printf(sb, "%s<file>", indent);
2210 				g_conf_printf_escaped(sb, "%s", mp->file);
2211 				sbuf_printf(sb, "</file>\n");
2212 			}
2213 			sbuf_printf(sb, "%s<label>", indent);
2214 			g_conf_printf_escaped(sb, "%s", mp->label);
2215 			sbuf_printf(sb, "</label>\n");
2216 		}
2217 	}
2218 }
2219 
2220 static void
g_md_fini(struct g_class * mp __unused)2221 g_md_fini(struct g_class *mp __unused)
2222 {
2223 
2224 	sx_destroy(&md_sx);
2225 	if (status_dev != NULL)
2226 		destroy_dev(status_dev);
2227 	delete_unrhdr(md_uh);
2228 }
2229