xref: /illumos-gate/usr/src/cmd/bhyve/block_if.c (revision a4955f4fa65e38d70c07d38e657a9aff43fa155f)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2013  Peter Grehan <grehan@freebsd.org>
5  * All rights reserved.
6  * Copyright 2020 Joyent, Inc.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * $FreeBSD$
30  */
31 
32 /*
33  * Copyright 2020 Joyent, Inc.
34  */
35 
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
38 
39 #include <sys/param.h>
40 #ifndef WITHOUT_CAPSICUM
41 #include <sys/capsicum.h>
42 #endif
43 #include <sys/queue.h>
44 #include <sys/errno.h>
45 #include <sys/stat.h>
46 #include <sys/ioctl.h>
47 #include <sys/disk.h>
48 #ifndef __FreeBSD__
49 #include <sys/limits.h>
50 #include <sys/uio.h>
51 #include <sys/dkio.h>
52 #endif
53 
54 #include <assert.h>
55 #ifndef WITHOUT_CAPSICUM
56 #include <capsicum_helpers.h>
57 #endif
58 #include <err.h>
59 #include <fcntl.h>
60 #include <stdio.h>
61 #include <stdlib.h>
62 #include <string.h>
63 #include <pthread.h>
64 #include <pthread_np.h>
65 #include <signal.h>
66 #include <sysexits.h>
67 #include <unistd.h>
68 
69 #include <machine/atomic.h>
70 
71 #include "bhyverun.h"
72 #include "config.h"
73 #include "debug.h"
74 #include "mevent.h"
75 #include "pci_emul.h"
76 #include "block_if.h"
77 
78 #define BLOCKIF_SIG	0xb109b109
79 
80 #ifdef __FreeBSD__
81 #define BLOCKIF_NUMTHR	8
82 #else
83 /* Enlarge to keep pace with the virtio-block ring size */
84 #define BLOCKIF_NUMTHR	16
85 #endif
86 #define BLOCKIF_MAXREQ	(BLOCKIF_RING_MAX + BLOCKIF_NUMTHR)
87 
88 enum blockop {
89 	BOP_READ,
90 	BOP_WRITE,
91 #ifndef __FreeBSD__
92 	BOP_WRITE_SYNC,
93 #endif
94 	BOP_FLUSH,
95 	BOP_DELETE
96 };
97 
98 enum blockstat {
99 	BST_FREE,
100 	BST_BLOCK,
101 	BST_PEND,
102 	BST_BUSY,
103 	BST_DONE
104 };
105 
106 struct blockif_elem {
107 	TAILQ_ENTRY(blockif_elem) be_link;
108 	struct blockif_req  *be_req;
109 	enum blockop	     be_op;
110 	enum blockstat	     be_status;
111 	pthread_t            be_tid;
112 	off_t		     be_block;
113 };
114 
115 #ifndef __FreeBSD__
116 enum blockif_wce {
117 	WCE_NONE = 0,
118 	WCE_IOCTL,
119 	WCE_FCNTL
120 };
121 #endif
122 
123 struct blockif_ctxt {
124 	int			bc_magic;
125 	int			bc_fd;
126 	int			bc_ischr;
127 	int			bc_isgeom;
128 	int			bc_candelete;
129 #ifndef __FreeBSD__
130 	enum blockif_wce	bc_wce;
131 #endif
132 	int			bc_rdonly;
133 	off_t			bc_size;
134 	int			bc_sectsz;
135 	int			bc_psectsz;
136 	int			bc_psectoff;
137 	int			bc_closing;
138 	pthread_t		bc_btid[BLOCKIF_NUMTHR];
139 	pthread_mutex_t		bc_mtx;
140 	pthread_cond_t		bc_cond;
141 	blockif_resize_cb	*bc_resize_cb;
142 	void			*bc_resize_cb_arg;
143 	struct mevent		*bc_resize_event;
144 
145 	/* Request elements and free/pending/busy queues */
146 	TAILQ_HEAD(, blockif_elem) bc_freeq;
147 	TAILQ_HEAD(, blockif_elem) bc_pendq;
148 	TAILQ_HEAD(, blockif_elem) bc_busyq;
149 	struct blockif_elem	bc_reqs[BLOCKIF_MAXREQ];
150 };
151 
152 static pthread_once_t blockif_once = PTHREAD_ONCE_INIT;
153 
154 struct blockif_sig_elem {
155 	pthread_mutex_t			bse_mtx;
156 	pthread_cond_t			bse_cond;
157 	int				bse_pending;
158 	struct blockif_sig_elem		*bse_next;
159 };
160 
161 static struct blockif_sig_elem *blockif_bse_head;
162 
163 static int
164 blockif_enqueue(struct blockif_ctxt *bc, struct blockif_req *breq,
165 		enum blockop op)
166 {
167 	struct blockif_elem *be, *tbe;
168 	off_t off;
169 	int i;
170 
171 	be = TAILQ_FIRST(&bc->bc_freeq);
172 	assert(be != NULL);
173 	assert(be->be_status == BST_FREE);
174 	TAILQ_REMOVE(&bc->bc_freeq, be, be_link);
175 	be->be_req = breq;
176 	be->be_op = op;
177 	switch (op) {
178 	case BOP_READ:
179 	case BOP_WRITE:
180 #ifndef __FreeBSD__
181 	case BOP_WRITE_SYNC:
182 #endif
183 	case BOP_DELETE:
184 		off = breq->br_offset;
185 		for (i = 0; i < breq->br_iovcnt; i++)
186 			off += breq->br_iov[i].iov_len;
187 		break;
188 	default:
189 		off = OFF_MAX;
190 	}
191 	be->be_block = off;
192 	TAILQ_FOREACH(tbe, &bc->bc_pendq, be_link) {
193 		if (tbe->be_block == breq->br_offset)
194 			break;
195 	}
196 	if (tbe == NULL) {
197 		TAILQ_FOREACH(tbe, &bc->bc_busyq, be_link) {
198 			if (tbe->be_block == breq->br_offset)
199 				break;
200 		}
201 	}
202 	if (tbe == NULL)
203 		be->be_status = BST_PEND;
204 	else
205 		be->be_status = BST_BLOCK;
206 	TAILQ_INSERT_TAIL(&bc->bc_pendq, be, be_link);
207 	return (be->be_status == BST_PEND);
208 }
209 
210 static int
211 blockif_dequeue(struct blockif_ctxt *bc, pthread_t t, struct blockif_elem **bep)
212 {
213 	struct blockif_elem *be;
214 
215 	TAILQ_FOREACH(be, &bc->bc_pendq, be_link) {
216 		if (be->be_status == BST_PEND)
217 			break;
218 		assert(be->be_status == BST_BLOCK);
219 	}
220 	if (be == NULL)
221 		return (0);
222 	TAILQ_REMOVE(&bc->bc_pendq, be, be_link);
223 	be->be_status = BST_BUSY;
224 	be->be_tid = t;
225 	TAILQ_INSERT_TAIL(&bc->bc_busyq, be, be_link);
226 	*bep = be;
227 	return (1);
228 }
229 
230 static void
231 blockif_complete(struct blockif_ctxt *bc, struct blockif_elem *be)
232 {
233 	struct blockif_elem *tbe;
234 
235 	if (be->be_status == BST_DONE || be->be_status == BST_BUSY)
236 		TAILQ_REMOVE(&bc->bc_busyq, be, be_link);
237 	else
238 		TAILQ_REMOVE(&bc->bc_pendq, be, be_link);
239 	TAILQ_FOREACH(tbe, &bc->bc_pendq, be_link) {
240 		if (tbe->be_req->br_offset == be->be_block)
241 			tbe->be_status = BST_PEND;
242 	}
243 	be->be_tid = 0;
244 	be->be_status = BST_FREE;
245 	be->be_req = NULL;
246 	TAILQ_INSERT_TAIL(&bc->bc_freeq, be, be_link);
247 }
248 
249 static int
250 blockif_flush_bc(struct blockif_ctxt *bc)
251 {
252 #ifdef	__FreeBSD__
253 	if (bc->bc_ischr) {
254 		if (ioctl(bc->bc_fd, DIOCGFLUSH))
255 			return (errno);
256 	} else if (fsync(bc->bc_fd))
257 		return (errno);
258 #else
259 	/*
260 	 * This fsync() should be adequate to flush the cache of a file
261 	 * or device.  In VFS, the VOP_SYNC operation is converted to
262 	 * the appropriate ioctl in both sdev (for real devices) and
263 	 * zfs (for zvols).
264 	 */
265 	if (fsync(bc->bc_fd))
266 		return (errno);
267 #endif
268 
269 	return (0);
270 }
271 
272 static void
273 blockif_proc(struct blockif_ctxt *bc, struct blockif_elem *be, uint8_t *buf)
274 {
275 	struct blockif_req *br;
276 #ifdef	__FreeBSD__
277 	off_t arg[2];
278 #endif
279 	ssize_t clen, len, off, boff, voff;
280 	int i, err;
281 #ifdef	__FreeBSD__
282 	struct spacectl_range range;
283 #endif
284 
285 	br = be->be_req;
286 	if (br->br_iovcnt <= 1)
287 		buf = NULL;
288 	err = 0;
289 	switch (be->be_op) {
290 	case BOP_READ:
291 		if (buf == NULL) {
292 			if ((len = preadv(bc->bc_fd, br->br_iov, br->br_iovcnt,
293 				   br->br_offset)) < 0)
294 				err = errno;
295 			else
296 				br->br_resid -= len;
297 			break;
298 		}
299 		i = 0;
300 		off = voff = 0;
301 		while (br->br_resid > 0) {
302 			len = MIN(br->br_resid, MAXPHYS);
303 			if (pread(bc->bc_fd, buf, len, br->br_offset +
304 			    off) < 0) {
305 				err = errno;
306 				break;
307 			}
308 			boff = 0;
309 			do {
310 				clen = MIN(len - boff, br->br_iov[i].iov_len -
311 				    voff);
312 				memcpy(br->br_iov[i].iov_base + voff,
313 				    buf + boff, clen);
314 				if (clen < br->br_iov[i].iov_len - voff)
315 					voff += clen;
316 				else {
317 					i++;
318 					voff = 0;
319 				}
320 				boff += clen;
321 			} while (boff < len);
322 			off += len;
323 			br->br_resid -= len;
324 		}
325 		break;
326 	case BOP_WRITE:
327 		if (bc->bc_rdonly) {
328 			err = EROFS;
329 			break;
330 		}
331 		if (buf == NULL) {
332 			if ((len = pwritev(bc->bc_fd, br->br_iov, br->br_iovcnt,
333 				    br->br_offset)) < 0)
334 				err = errno;
335 			else
336 				br->br_resid -= len;
337 			break;
338 		}
339 		i = 0;
340 		off = voff = 0;
341 		while (br->br_resid > 0) {
342 			len = MIN(br->br_resid, MAXPHYS);
343 			boff = 0;
344 			do {
345 				clen = MIN(len - boff, br->br_iov[i].iov_len -
346 				    voff);
347 				memcpy(buf + boff,
348 				    br->br_iov[i].iov_base + voff, clen);
349 				if (clen < br->br_iov[i].iov_len - voff)
350 					voff += clen;
351 				else {
352 					i++;
353 					voff = 0;
354 				}
355 				boff += clen;
356 			} while (boff < len);
357 			if (pwrite(bc->bc_fd, buf, len, br->br_offset +
358 			    off) < 0) {
359 				err = errno;
360 				break;
361 			}
362 			off += len;
363 			br->br_resid -= len;
364 		}
365 		break;
366 	case BOP_FLUSH:
367 		err = blockif_flush_bc(bc);
368 		break;
369 	case BOP_DELETE:
370 		if (!bc->bc_candelete)
371 			err = EOPNOTSUPP;
372 		else if (bc->bc_rdonly)
373 			err = EROFS;
374 #ifdef	__FreeBSD__
375 		else if (bc->bc_ischr) {
376 			arg[0] = br->br_offset;
377 			arg[1] = br->br_resid;
378 			if (ioctl(bc->bc_fd, DIOCGDELETE, arg))
379 				err = errno;
380 			else
381 				br->br_resid = 0;
382 		} else {
383 			range.r_offset = br->br_offset;
384 			range.r_len = br->br_resid;
385 
386 			while (range.r_len > 0) {
387 				if (fspacectl(bc->bc_fd, SPACECTL_DEALLOC,
388 				    &range, 0, &range) != 0) {
389 					err = errno;
390 					break;
391 				}
392 			}
393 			if (err == 0)
394 				br->br_resid = 0;
395 		}
396 #else
397 		else if (bc->bc_ischr) {
398 			dkioc_free_list_t dfl = {
399 				.dfl_num_exts = 1,
400 				.dfl_offset = 0,
401 				.dfl_flags = 0,
402 				.dfl_exts = {
403 					{
404 						.dfle_start = br->br_offset,
405 						.dfle_length = br->br_resid
406 					}
407 				}
408 			};
409 
410 			if (ioctl(bc->bc_fd, DKIOCFREE, &dfl))
411 				err = errno;
412 			else
413 				br->br_resid = 0;
414 		} else {
415 			struct flock fl = {
416 				.l_whence = 0,
417 				.l_type = F_WRLCK,
418 				.l_start = br->br_offset,
419 				.l_len = br->br_resid
420 			};
421 
422 			if (fcntl(bc->bc_fd, F_FREESP, &fl))
423 				err = errno;
424 			else
425 				br->br_resid = 0;
426 		}
427 #endif
428 		break;
429 	default:
430 		err = EINVAL;
431 		break;
432 	}
433 
434 	be->be_status = BST_DONE;
435 
436 	(*br->br_callback)(br, err);
437 }
438 
439 static inline bool
440 blockif_empty(const struct blockif_ctxt *bc)
441 {
442 	return (TAILQ_EMPTY(&bc->bc_pendq) && TAILQ_EMPTY(&bc->bc_busyq));
443 }
444 
445 static void *
446 blockif_thr(void *arg)
447 {
448 	struct blockif_ctxt *bc;
449 	struct blockif_elem *be;
450 	pthread_t t;
451 	uint8_t *buf;
452 
453 	bc = arg;
454 	if (bc->bc_isgeom)
455 		buf = malloc(MAXPHYS);
456 	else
457 		buf = NULL;
458 	t = pthread_self();
459 
460 	pthread_mutex_lock(&bc->bc_mtx);
461 	for (;;) {
462 		while (blockif_dequeue(bc, t, &be)) {
463 			pthread_mutex_unlock(&bc->bc_mtx);
464 			blockif_proc(bc, be, buf);
465 			pthread_mutex_lock(&bc->bc_mtx);
466 			blockif_complete(bc, be);
467 		}
468 		/* Check ctxt status here to see if exit requested */
469 		if (bc->bc_closing)
470 			break;
471 
472 		pthread_cond_wait(&bc->bc_cond, &bc->bc_mtx);
473 	}
474 	pthread_mutex_unlock(&bc->bc_mtx);
475 
476 	if (buf)
477 		free(buf);
478 	pthread_exit(NULL);
479 	return (NULL);
480 }
481 
482 #ifdef	__FreeBSD__
483 static void
484 blockif_sigcont_handler(int signal, enum ev_type type, void *arg)
485 #else
486 static void
487 blockif_sigcont_handler(int signal)
488 #endif
489 {
490 	struct blockif_sig_elem *bse;
491 
492 	for (;;) {
493 		/*
494 		 * Process the entire list even if not intended for
495 		 * this thread.
496 		 */
497 		do {
498 			bse = blockif_bse_head;
499 			if (bse == NULL)
500 				return;
501 		} while (!atomic_cmpset_ptr((uintptr_t *)&blockif_bse_head,
502 					    (uintptr_t)bse,
503 					    (uintptr_t)bse->bse_next));
504 
505 		pthread_mutex_lock(&bse->bse_mtx);
506 		bse->bse_pending = 0;
507 		pthread_cond_signal(&bse->bse_cond);
508 		pthread_mutex_unlock(&bse->bse_mtx);
509 	}
510 }
511 
512 static void
513 blockif_init(void)
514 {
515 #ifdef	__FreeBSD__
516 	mevent_add(SIGCONT, EVF_SIGNAL, blockif_sigcont_handler, NULL);
517 	(void) signal(SIGCONT, SIG_IGN);
518 #else
519 	(void) sigset(SIGCONT, blockif_sigcont_handler);
520 #endif
521 }
522 
523 int
524 blockif_legacy_config(nvlist_t *nvl, const char *opts)
525 {
526 	char *cp, *path;
527 
528 	if (opts == NULL)
529 		return (0);
530 
531 	cp = strchr(opts, ',');
532 	if (cp == NULL) {
533 		set_config_value_node(nvl, "path", opts);
534 		return (0);
535 	}
536 	path = strndup(opts, cp - opts);
537 	set_config_value_node(nvl, "path", path);
538 	free(path);
539 	return (pci_parse_legacy_config(nvl, cp + 1));
540 }
541 
542 struct blockif_ctxt *
543 blockif_open(nvlist_t *nvl, const char *ident)
544 {
545 	char tname[MAXCOMLEN + 1];
546 #ifdef	__FreeBSD__
547 	char name[MAXPATHLEN];
548 #endif
549 	const char *path, *pssval, *ssval;
550 	char *cp;
551 	struct blockif_ctxt *bc;
552 	struct stat sbuf;
553 #ifdef	__FreeBSD__
554 	struct diocgattr_arg arg;
555 #else
556 	enum blockif_wce wce = WCE_NONE;
557 #endif
558 	off_t size, psectsz, psectoff;
559 	int extra, fd, i, sectsz;
560 	int ro, candelete, geom, ssopt, pssopt;
561 	int nodelete;
562 
563 #ifndef WITHOUT_CAPSICUM
564 	cap_rights_t rights;
565 	cap_ioctl_t cmds[] = { DIOCGFLUSH, DIOCGDELETE, DIOCGMEDIASIZE };
566 #endif
567 
568 	pthread_once(&blockif_once, blockif_init);
569 
570 	fd = -1;
571 	extra = 0;
572 	ssopt = 0;
573 #ifndef __FreeBSD__
574 	pssopt = 0;
575 #endif
576 	ro = 0;
577 	nodelete = 0;
578 
579 	if (get_config_bool_node_default(nvl, "nocache", false))
580 		extra |= O_DIRECT;
581 	if (get_config_bool_node_default(nvl, "nodelete", false))
582 		nodelete = 1;
583 	if (get_config_bool_node_default(nvl, "sync", false) ||
584 	    get_config_bool_node_default(nvl, "direct", false))
585 		extra |= O_SYNC;
586 	if (get_config_bool_node_default(nvl, "ro", false))
587 		ro = 1;
588 	ssval = get_config_value_node(nvl, "sectorsize");
589 	if (ssval != NULL) {
590 		ssopt = strtol(ssval, &cp, 10);
591 		if (cp == ssval) {
592 			EPRINTLN("Invalid sector size \"%s\"", ssval);
593 			goto err;
594 		}
595 		if (*cp == '\0') {
596 			pssopt = ssopt;
597 		} else if (*cp == '/') {
598 			pssval = cp + 1;
599 			pssopt = strtol(pssval, &cp, 10);
600 			if (cp == pssval || *cp != '\0') {
601 				EPRINTLN("Invalid sector size \"%s\"", ssval);
602 				goto err;
603 			}
604 		} else {
605 			EPRINTLN("Invalid sector size \"%s\"", ssval);
606 			goto err;
607 		}
608 	}
609 
610 	path = get_config_value_node(nvl, "path");
611 	if (path == NULL) {
612 		EPRINTLN("Missing \"path\" for block device.");
613 		goto err;
614 	}
615 
616 	fd = open(path, (ro ? O_RDONLY : O_RDWR) | extra);
617 	if (fd < 0 && !ro) {
618 		/* Attempt a r/w fail with a r/o open */
619 		fd = open(path, O_RDONLY | extra);
620 		ro = 1;
621 	}
622 
623 	if (fd < 0) {
624 		warn("Could not open backing file: %s", path);
625 		goto err;
626 	}
627 
628         if (fstat(fd, &sbuf) < 0) {
629 		warn("Could not stat backing file %s", path);
630 		goto err;
631         }
632 
633 #ifndef WITHOUT_CAPSICUM
634 	cap_rights_init(&rights, CAP_FSYNC, CAP_IOCTL, CAP_READ, CAP_SEEK,
635 	    CAP_WRITE, CAP_FSTAT, CAP_EVENT, CAP_FPATHCONF);
636 	if (ro)
637 		cap_rights_clear(&rights, CAP_FSYNC, CAP_WRITE);
638 
639 	if (caph_rights_limit(fd, &rights) == -1)
640 		errx(EX_OSERR, "Unable to apply rights for sandbox");
641 #endif
642 
643         /*
644 	 * Deal with raw devices
645 	 */
646         size = sbuf.st_size;
647 	sectsz = DEV_BSIZE;
648 	psectsz = psectoff = 0;
649 	candelete = geom = 0;
650 #ifdef	__FreeBSD__
651 	if (S_ISCHR(sbuf.st_mode)) {
652 		if (ioctl(fd, DIOCGMEDIASIZE, &size) < 0 ||
653 		    ioctl(fd, DIOCGSECTORSIZE, &sectsz)) {
654 			perror("Could not fetch dev blk/sector size");
655 			goto err;
656 		}
657 		assert(size != 0);
658 		assert(sectsz != 0);
659 		if (ioctl(fd, DIOCGSTRIPESIZE, &psectsz) == 0 && psectsz > 0)
660 			ioctl(fd, DIOCGSTRIPEOFFSET, &psectoff);
661 		strlcpy(arg.name, "GEOM::candelete", sizeof(arg.name));
662 		arg.len = sizeof(arg.value.i);
663 		if (nodelete == 0 && ioctl(fd, DIOCGATTR, &arg) == 0)
664 			candelete = arg.value.i;
665 		if (ioctl(fd, DIOCGPROVIDERNAME, name) == 0)
666 			geom = 1;
667 	} else {
668 		psectsz = sbuf.st_blksize;
669 		/* Avoid fallback implementation */
670 		candelete = fpathconf(fd, _PC_DEALLOC_PRESENT) == 1;
671 	}
672 #else
673 	psectsz = sbuf.st_blksize;
674 	if (S_ISCHR(sbuf.st_mode)) {
675 		struct dk_minfo_ext dkmext;
676 		int wce_val;
677 
678 		/* Look for a more accurate physical block/media size */
679 		if (ioctl(fd, DKIOCGMEDIAINFOEXT, &dkmext) == 0) {
680 			psectsz = dkmext.dki_pbsize;
681 			size = dkmext.dki_lbsize * dkmext.dki_capacity;
682 		}
683 		/* See if a configurable write cache is present and working */
684 		if (ioctl(fd, DKIOCGETWCE, &wce_val) == 0) {
685 			/*
686 			 * If WCE is already active, disable it until the
687 			 * specific device driver calls for its return.  If it
688 			 * is not active, toggle it on and off to verify that
689 			 * such actions are possible.
690 			 */
691 			if (wce_val != 0) {
692 				wce_val = 0;
693 				/*
694 				 * Inability to disable the cache is a threat
695 				 * to data durability.
696 				 */
697 				assert(ioctl(fd, DKIOCSETWCE, &wce_val) == 0);
698 				wce = WCE_IOCTL;
699 			} else {
700 				int r1, r2;
701 
702 				wce_val = 1;
703 				r1 = ioctl(fd, DKIOCSETWCE, &wce_val);
704 				wce_val = 0;
705 				r2 = ioctl(fd, DKIOCSETWCE, &wce_val);
706 
707 				if (r1 == 0 && r2 == 0) {
708 					wce = WCE_IOCTL;
709 				} else {
710 					/*
711 					 * If the cache cache toggle was not
712 					 * successful, ensure that the cache
713 					 * was not left enabled.
714 					 */
715 					assert(r1 != 0);
716 				}
717 			}
718 		}
719 
720 		if (nodelete == 0 && ioctl(fd, DKIOC_CANFREE, &candelete))
721 			candelete = 0;
722 
723 	} else {
724 		int flags;
725 
726 		if ((flags = fcntl(fd, F_GETFL)) >= 0) {
727 			flags |= O_DSYNC;
728 			if (fcntl(fd, F_SETFL, flags) != -1) {
729 				wce = WCE_FCNTL;
730 			}
731 		}
732 
733 		/*
734 		 * We don't have a way to discover if a file supports the
735 		 * FREESP fcntl cmd (other than trying it).  However,
736 		 * zfs, ufs, tmpfs, and udfs all support the FREESP fcntl cmd.
737 		 * Nfsv4 and nfsv4 also forward the FREESP request
738 		 * to the server, so we always enable it for file based
739 		 * volumes. Anyone trying to run volumes on an unsupported
740 		 * configuration is on their own, and should be prepared
741 		 * for the requests to fail.
742 		 */
743 		if (nodelete == 0)
744 			candelete = 1;
745 	}
746 #endif
747 
748 #ifndef WITHOUT_CAPSICUM
749 	if (caph_ioctls_limit(fd, cmds, nitems(cmds)) == -1)
750 		errx(EX_OSERR, "Unable to apply rights for sandbox");
751 #endif
752 
753 	if (ssopt != 0) {
754 		if (!powerof2(ssopt) || !powerof2(pssopt) || ssopt < 512 ||
755 		    ssopt > pssopt) {
756 			EPRINTLN("Invalid sector size %d/%d",
757 			    ssopt, pssopt);
758 			goto err;
759 		}
760 
761 		/*
762 		 * Some backend drivers (e.g. cd0, ada0) require that the I/O
763 		 * size be a multiple of the device's sector size.
764 		 *
765 		 * Validate that the emulated sector size complies with this
766 		 * requirement.
767 		 */
768 		if (S_ISCHR(sbuf.st_mode)) {
769 			if (ssopt < sectsz || (ssopt % sectsz) != 0) {
770 				EPRINTLN("Sector size %d incompatible "
771 				    "with underlying device sector size %d",
772 				    ssopt, sectsz);
773 				goto err;
774 			}
775 		}
776 
777 		sectsz = ssopt;
778 		psectsz = pssopt;
779 		psectoff = 0;
780 	}
781 
782 	bc = calloc(1, sizeof(struct blockif_ctxt));
783 	if (bc == NULL) {
784 		perror("calloc");
785 		goto err;
786 	}
787 
788 	bc->bc_magic = BLOCKIF_SIG;
789 	bc->bc_fd = fd;
790 	bc->bc_ischr = S_ISCHR(sbuf.st_mode);
791 	bc->bc_isgeom = geom;
792 	bc->bc_candelete = candelete;
793 #ifndef __FreeBSD__
794 	bc->bc_wce = wce;
795 #endif
796 	bc->bc_rdonly = ro;
797 	bc->bc_size = size;
798 	bc->bc_sectsz = sectsz;
799 	bc->bc_psectsz = psectsz;
800 	bc->bc_psectoff = psectoff;
801 	pthread_mutex_init(&bc->bc_mtx, NULL);
802 	pthread_cond_init(&bc->bc_cond, NULL);
803 	TAILQ_INIT(&bc->bc_freeq);
804 	TAILQ_INIT(&bc->bc_pendq);
805 	TAILQ_INIT(&bc->bc_busyq);
806 	for (i = 0; i < BLOCKIF_MAXREQ; i++) {
807 		bc->bc_reqs[i].be_status = BST_FREE;
808 		TAILQ_INSERT_HEAD(&bc->bc_freeq, &bc->bc_reqs[i], be_link);
809 	}
810 
811 	for (i = 0; i < BLOCKIF_NUMTHR; i++) {
812 		pthread_create(&bc->bc_btid[i], NULL, blockif_thr, bc);
813 		snprintf(tname, sizeof(tname), "blk-%s-%d", ident, i);
814 		pthread_set_name_np(bc->bc_btid[i], tname);
815 	}
816 
817 	return (bc);
818 err:
819 	if (fd >= 0)
820 		close(fd);
821 	return (NULL);
822 }
823 
824 static void
825 blockif_resized(int fd, enum ev_type type, void *arg)
826 {
827 	struct blockif_ctxt *bc;
828 	struct stat sb;
829 	off_t mediasize;
830 
831 	if (fstat(fd, &sb) != 0)
832 		return;
833 
834 #ifdef __FreeBSD__
835 	if (S_ISCHR(sb.st_mode)) {
836 		if (ioctl(fd, DIOCGMEDIASIZE, &mediasize) < 0) {
837 			EPRINTLN("blockif_resized: get mediasize failed: %s",
838 			    strerror(errno));
839 			return;
840 		}
841 	} else
842 		mediasize = sb.st_size;
843 #else
844 	mediasize = sb.st_size;
845 	if (S_ISCHR(sb.st_mode)) {
846 		struct dk_minfo dkm;
847 
848 		if (ioctl(fd, DKIOCGMEDIAINFO, &dkm) == 0)
849 			mediasize = dkm.dki_lbsize * dkm.dki_capacity;
850 	}
851 #endif
852 
853 	bc = arg;
854 	pthread_mutex_lock(&bc->bc_mtx);
855 	if (mediasize != bc->bc_size) {
856 		bc->bc_size = mediasize;
857 		bc->bc_resize_cb(bc, bc->bc_resize_cb_arg, bc->bc_size);
858 	}
859 	pthread_mutex_unlock(&bc->bc_mtx);
860 }
861 
862 int
863 blockif_register_resize_callback(struct blockif_ctxt *bc, blockif_resize_cb *cb,
864     void *cb_arg)
865 {
866 	struct stat sb;
867 	int err;
868 #ifndef __FreeBSD__
869 	err = 0;
870 #endif
871 
872 	if (cb == NULL)
873 		return (EINVAL);
874 
875 	pthread_mutex_lock(&bc->bc_mtx);
876 	if (bc->bc_resize_cb != NULL) {
877 		err = EBUSY;
878 		goto out;
879 	}
880 
881 	assert(bc->bc_closing == 0);
882 
883 	if (fstat(bc->bc_fd, &sb) != 0) {
884 		err = errno;
885 		goto out;
886 	}
887 
888 	bc->bc_resize_event = mevent_add_flags(bc->bc_fd, EVF_VNODE,
889 	    EVFF_ATTRIB, blockif_resized, bc);
890 	if (bc->bc_resize_event == NULL) {
891 		err = ENXIO;
892 		goto out;
893 	}
894 
895 	bc->bc_resize_cb = cb;
896 	bc->bc_resize_cb_arg = cb_arg;
897 out:
898 	pthread_mutex_unlock(&bc->bc_mtx);
899 
900 	return (err);
901 }
902 
903 static int
904 blockif_request(struct blockif_ctxt *bc, struct blockif_req *breq,
905 		enum blockop op)
906 {
907 	int err;
908 
909 	err = 0;
910 
911 	pthread_mutex_lock(&bc->bc_mtx);
912 	if (!TAILQ_EMPTY(&bc->bc_freeq)) {
913 		/*
914 		 * Enqueue and inform the block i/o thread
915 		 * that there is work available
916 		 */
917 		if (blockif_enqueue(bc, breq, op))
918 			pthread_cond_signal(&bc->bc_cond);
919 	} else {
920 		/*
921 		 * Callers are not allowed to enqueue more than
922 		 * the specified blockif queue limit. Return an
923 		 * error to indicate that the queue length has been
924 		 * exceeded.
925 		 */
926 		err = E2BIG;
927 	}
928 	pthread_mutex_unlock(&bc->bc_mtx);
929 
930 	return (err);
931 }
932 
933 int
934 blockif_read(struct blockif_ctxt *bc, struct blockif_req *breq)
935 {
936 	assert(bc->bc_magic == BLOCKIF_SIG);
937 	return (blockif_request(bc, breq, BOP_READ));
938 }
939 
940 int
941 blockif_write(struct blockif_ctxt *bc, struct blockif_req *breq)
942 {
943 	assert(bc->bc_magic == BLOCKIF_SIG);
944 	return (blockif_request(bc, breq, BOP_WRITE));
945 }
946 
947 int
948 blockif_flush(struct blockif_ctxt *bc, struct blockif_req *breq)
949 {
950 	assert(bc->bc_magic == BLOCKIF_SIG);
951 	return (blockif_request(bc, breq, BOP_FLUSH));
952 }
953 
954 int
955 blockif_delete(struct blockif_ctxt *bc, struct blockif_req *breq)
956 {
957 	assert(bc->bc_magic == BLOCKIF_SIG);
958 	return (blockif_request(bc, breq, BOP_DELETE));
959 }
960 
961 int
962 blockif_cancel(struct blockif_ctxt *bc, struct blockif_req *breq)
963 {
964 	struct blockif_elem *be;
965 
966 	assert(bc->bc_magic == BLOCKIF_SIG);
967 
968 	pthread_mutex_lock(&bc->bc_mtx);
969 	/*
970 	 * Check pending requests.
971 	 */
972 	TAILQ_FOREACH(be, &bc->bc_pendq, be_link) {
973 		if (be->be_req == breq)
974 			break;
975 	}
976 	if (be != NULL) {
977 		/*
978 		 * Found it.
979 		 */
980 		blockif_complete(bc, be);
981 		pthread_mutex_unlock(&bc->bc_mtx);
982 
983 		return (0);
984 	}
985 
986 	/*
987 	 * Check in-flight requests.
988 	 */
989 	TAILQ_FOREACH(be, &bc->bc_busyq, be_link) {
990 		if (be->be_req == breq)
991 			break;
992 	}
993 	if (be == NULL) {
994 		/*
995 		 * Didn't find it.
996 		 */
997 		pthread_mutex_unlock(&bc->bc_mtx);
998 		return (EINVAL);
999 	}
1000 
1001 	/*
1002 	 * Interrupt the processing thread to force it return
1003 	 * prematurely via it's normal callback path.
1004 	 */
1005 	while (be->be_status == BST_BUSY) {
1006 		struct blockif_sig_elem bse, *old_head;
1007 
1008 		pthread_mutex_init(&bse.bse_mtx, NULL);
1009 		pthread_cond_init(&bse.bse_cond, NULL);
1010 
1011 		bse.bse_pending = 1;
1012 
1013 		do {
1014 			old_head = blockif_bse_head;
1015 			bse.bse_next = old_head;
1016 		} while (!atomic_cmpset_ptr((uintptr_t *)&blockif_bse_head,
1017 					    (uintptr_t)old_head,
1018 					    (uintptr_t)&bse));
1019 
1020 		pthread_kill(be->be_tid, SIGCONT);
1021 
1022 		pthread_mutex_lock(&bse.bse_mtx);
1023 		while (bse.bse_pending)
1024 			pthread_cond_wait(&bse.bse_cond, &bse.bse_mtx);
1025 		pthread_mutex_unlock(&bse.bse_mtx);
1026 	}
1027 
1028 	pthread_mutex_unlock(&bc->bc_mtx);
1029 
1030 	/*
1031 	 * The processing thread has been interrupted.  Since it's not
1032 	 * clear if the callback has been invoked yet, return EBUSY.
1033 	 */
1034 	return (EBUSY);
1035 }
1036 
1037 int
1038 blockif_close(struct blockif_ctxt *bc)
1039 {
1040 	void *jval;
1041 	int i;
1042 
1043 	assert(bc->bc_magic == BLOCKIF_SIG);
1044 
1045 	/*
1046 	 * Stop the block i/o thread
1047 	 */
1048 	pthread_mutex_lock(&bc->bc_mtx);
1049 	bc->bc_closing = 1;
1050 	if (bc->bc_resize_event != NULL)
1051 		mevent_disable(bc->bc_resize_event);
1052 	pthread_mutex_unlock(&bc->bc_mtx);
1053 	pthread_cond_broadcast(&bc->bc_cond);
1054 	for (i = 0; i < BLOCKIF_NUMTHR; i++)
1055 		pthread_join(bc->bc_btid[i], &jval);
1056 
1057 	/* XXX Cancel queued i/o's ??? */
1058 
1059 	/*
1060 	 * Release resources
1061 	 */
1062 	bc->bc_magic = 0;
1063 	close(bc->bc_fd);
1064 	free(bc);
1065 
1066 	return (0);
1067 }
1068 
1069 /*
1070  * Return virtual C/H/S values for a given block. Use the algorithm
1071  * outlined in the VHD specification to calculate values.
1072  */
1073 void
1074 blockif_chs(struct blockif_ctxt *bc, uint16_t *c, uint8_t *h, uint8_t *s)
1075 {
1076 	off_t sectors;		/* total sectors of the block dev */
1077 	off_t hcyl;		/* cylinders times heads */
1078 	uint16_t secpt;		/* sectors per track */
1079 	uint8_t heads;
1080 
1081 	assert(bc->bc_magic == BLOCKIF_SIG);
1082 
1083 	sectors = bc->bc_size / bc->bc_sectsz;
1084 
1085 	/* Clamp the size to the largest possible with CHS */
1086 	if (sectors > 65535UL*16*255)
1087 		sectors = 65535UL*16*255;
1088 
1089 	if (sectors >= 65536UL*16*63) {
1090 		secpt = 255;
1091 		heads = 16;
1092 		hcyl = sectors / secpt;
1093 	} else {
1094 		secpt = 17;
1095 		hcyl = sectors / secpt;
1096 		heads = (hcyl + 1023) / 1024;
1097 
1098 		if (heads < 4)
1099 			heads = 4;
1100 
1101 		if (hcyl >= (heads * 1024) || heads > 16) {
1102 			secpt = 31;
1103 			heads = 16;
1104 			hcyl = sectors / secpt;
1105 		}
1106 		if (hcyl >= (heads * 1024)) {
1107 			secpt = 63;
1108 			heads = 16;
1109 			hcyl = sectors / secpt;
1110 		}
1111 	}
1112 
1113 	*c = hcyl / heads;
1114 	*h = heads;
1115 	*s = secpt;
1116 }
1117 
1118 /*
1119  * Accessors
1120  */
1121 off_t
1122 blockif_size(struct blockif_ctxt *bc)
1123 {
1124 	assert(bc->bc_magic == BLOCKIF_SIG);
1125 	return (bc->bc_size);
1126 }
1127 
1128 int
1129 blockif_sectsz(struct blockif_ctxt *bc)
1130 {
1131 	assert(bc->bc_magic == BLOCKIF_SIG);
1132 	return (bc->bc_sectsz);
1133 }
1134 
1135 void
1136 blockif_psectsz(struct blockif_ctxt *bc, int *size, int *off)
1137 {
1138 	assert(bc->bc_magic == BLOCKIF_SIG);
1139 	*size = bc->bc_psectsz;
1140 	*off = bc->bc_psectoff;
1141 }
1142 
1143 int
1144 blockif_queuesz(struct blockif_ctxt *bc)
1145 {
1146 	assert(bc->bc_magic == BLOCKIF_SIG);
1147 	return (BLOCKIF_MAXREQ - 1);
1148 }
1149 
1150 int
1151 blockif_is_ro(struct blockif_ctxt *bc)
1152 {
1153 	assert(bc->bc_magic == BLOCKIF_SIG);
1154 	return (bc->bc_rdonly);
1155 }
1156 
1157 int
1158 blockif_candelete(struct blockif_ctxt *bc)
1159 {
1160 	assert(bc->bc_magic == BLOCKIF_SIG);
1161 	return (bc->bc_candelete);
1162 }
1163 
1164 #ifndef __FreeBSD__
1165 int
1166 blockif_set_wce(struct blockif_ctxt *bc, int wc_enable)
1167 {
1168 	int res = 0, flags;
1169 	int clean_val = (wc_enable != 0) ? 1 : 0;
1170 
1171 	(void) pthread_mutex_lock(&bc->bc_mtx);
1172 	switch (bc->bc_wce) {
1173 	case WCE_IOCTL:
1174 		res = ioctl(bc->bc_fd, DKIOCSETWCE, &clean_val);
1175 		break;
1176 	case WCE_FCNTL:
1177 		if ((flags = fcntl(bc->bc_fd, F_GETFL)) >= 0) {
1178 			if (wc_enable == 0) {
1179 				flags |= O_DSYNC;
1180 			} else {
1181 				flags &= ~O_DSYNC;
1182 			}
1183 			if (fcntl(bc->bc_fd, F_SETFL, flags) == -1) {
1184 				res = -1;
1185 			}
1186 		} else {
1187 			res = -1;
1188 		}
1189 		break;
1190 	default:
1191 		break;
1192 	}
1193 
1194 	/*
1195 	 * After a successful disable of the write cache, ensure that any
1196 	 * lingering data in the cache is synced out.
1197 	 */
1198 	if (res == 0 && wc_enable == 0) {
1199 		res = fsync(bc->bc_fd);
1200 	}
1201 	(void) pthread_mutex_unlock(&bc->bc_mtx);
1202 
1203 	return (res);
1204 }
1205 #endif /* __FreeBSD__ */
1206