xref: /freebsd-13-stable/usr.sbin/bhyve/block_if.c (revision 506890a652aaf19f59da0a84be26e991f99372d9)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
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 
30 #include <sys/cdefs.h>
31 #include <sys/param.h>
32 #ifndef WITHOUT_CAPSICUM
33 #include <sys/capsicum.h>
34 #endif
35 #include <sys/queue.h>
36 #include <sys/errno.h>
37 #include <sys/stat.h>
38 #include <sys/ioctl.h>
39 #include <sys/disk.h>
40 
41 #include <assert.h>
42 #ifndef WITHOUT_CAPSICUM
43 #include <capsicum_helpers.h>
44 #endif
45 #include <err.h>
46 #include <fcntl.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <pthread.h>
51 #include <pthread_np.h>
52 #include <signal.h>
53 #include <sysexits.h>
54 #include <unistd.h>
55 
56 #include <machine/atomic.h>
57 #include <machine/vmm_snapshot.h>
58 
59 #include "bhyverun.h"
60 #include "config.h"
61 #include "debug.h"
62 #include "mevent.h"
63 #include "pci_emul.h"
64 #include "block_if.h"
65 
66 #define BLOCKIF_SIG	0xb109b109
67 
68 #define BLOCKIF_NUMTHR	8
69 #define BLOCKIF_MAXREQ	(BLOCKIF_RING_MAX + BLOCKIF_NUMTHR)
70 
71 enum blockop {
72 	BOP_READ,
73 	BOP_WRITE,
74 	BOP_FLUSH,
75 	BOP_DELETE
76 };
77 
78 enum blockstat {
79 	BST_FREE,
80 	BST_BLOCK,
81 	BST_PEND,
82 	BST_BUSY,
83 	BST_DONE
84 };
85 
86 struct blockif_elem {
87 	TAILQ_ENTRY(blockif_elem) be_link;
88 	struct blockif_req  *be_req;
89 	enum blockop	     be_op;
90 	enum blockstat	     be_status;
91 	pthread_t            be_tid;
92 	off_t		     be_block;
93 };
94 
95 struct blockif_ctxt {
96 	unsigned int		bc_magic;
97 	int			bc_fd;
98 	int			bc_ischr;
99 	int			bc_isgeom;
100 	int			bc_candelete;
101 	int			bc_rdonly;
102 	off_t			bc_size;
103 	int			bc_sectsz;
104 	int			bc_psectsz;
105 	int			bc_psectoff;
106 	int			bc_closing;
107 	int			bc_paused;
108 	pthread_t		bc_btid[BLOCKIF_NUMTHR];
109 	pthread_mutex_t		bc_mtx;
110 	pthread_cond_t		bc_cond;
111 	pthread_cond_t		bc_work_done_cond;
112 	blockif_resize_cb	*bc_resize_cb;
113 	void			*bc_resize_cb_arg;
114 	struct mevent		*bc_resize_event;
115 
116 	/* Request elements and free/pending/busy queues */
117 	TAILQ_HEAD(, blockif_elem) bc_freeq;
118 	TAILQ_HEAD(, blockif_elem) bc_pendq;
119 	TAILQ_HEAD(, blockif_elem) bc_busyq;
120 	struct blockif_elem	bc_reqs[BLOCKIF_MAXREQ];
121 	int			bc_bootindex;
122 };
123 
124 static pthread_once_t blockif_once = PTHREAD_ONCE_INIT;
125 
126 struct blockif_sig_elem {
127 	pthread_mutex_t			bse_mtx;
128 	pthread_cond_t			bse_cond;
129 	int				bse_pending;
130 	struct blockif_sig_elem		*bse_next;
131 };
132 
133 static struct blockif_sig_elem *blockif_bse_head;
134 
135 static int
blockif_enqueue(struct blockif_ctxt * bc,struct blockif_req * breq,enum blockop op)136 blockif_enqueue(struct blockif_ctxt *bc, struct blockif_req *breq,
137 		enum blockop op)
138 {
139 	struct blockif_elem *be, *tbe;
140 	off_t off;
141 	int i;
142 
143 	be = TAILQ_FIRST(&bc->bc_freeq);
144 	assert(be != NULL);
145 	assert(be->be_status == BST_FREE);
146 	TAILQ_REMOVE(&bc->bc_freeq, be, be_link);
147 	be->be_req = breq;
148 	be->be_op = op;
149 	switch (op) {
150 	case BOP_READ:
151 	case BOP_WRITE:
152 	case BOP_DELETE:
153 		off = breq->br_offset;
154 		for (i = 0; i < breq->br_iovcnt; i++)
155 			off += breq->br_iov[i].iov_len;
156 		break;
157 	default:
158 		off = OFF_MAX;
159 	}
160 	be->be_block = off;
161 	TAILQ_FOREACH(tbe, &bc->bc_pendq, be_link) {
162 		if (tbe->be_block == breq->br_offset)
163 			break;
164 	}
165 	if (tbe == NULL) {
166 		TAILQ_FOREACH(tbe, &bc->bc_busyq, be_link) {
167 			if (tbe->be_block == breq->br_offset)
168 				break;
169 		}
170 	}
171 	if (tbe == NULL)
172 		be->be_status = BST_PEND;
173 	else
174 		be->be_status = BST_BLOCK;
175 	TAILQ_INSERT_TAIL(&bc->bc_pendq, be, be_link);
176 	return (be->be_status == BST_PEND);
177 }
178 
179 static int
blockif_dequeue(struct blockif_ctxt * bc,pthread_t t,struct blockif_elem ** bep)180 blockif_dequeue(struct blockif_ctxt *bc, pthread_t t, struct blockif_elem **bep)
181 {
182 	struct blockif_elem *be;
183 
184 	TAILQ_FOREACH(be, &bc->bc_pendq, be_link) {
185 		if (be->be_status == BST_PEND)
186 			break;
187 		assert(be->be_status == BST_BLOCK);
188 	}
189 	if (be == NULL)
190 		return (0);
191 	TAILQ_REMOVE(&bc->bc_pendq, be, be_link);
192 	be->be_status = BST_BUSY;
193 	be->be_tid = t;
194 	TAILQ_INSERT_TAIL(&bc->bc_busyq, be, be_link);
195 	*bep = be;
196 	return (1);
197 }
198 
199 static void
blockif_complete(struct blockif_ctxt * bc,struct blockif_elem * be)200 blockif_complete(struct blockif_ctxt *bc, struct blockif_elem *be)
201 {
202 	struct blockif_elem *tbe;
203 
204 	if (be->be_status == BST_DONE || be->be_status == BST_BUSY)
205 		TAILQ_REMOVE(&bc->bc_busyq, be, be_link);
206 	else
207 		TAILQ_REMOVE(&bc->bc_pendq, be, be_link);
208 	TAILQ_FOREACH(tbe, &bc->bc_pendq, be_link) {
209 		if (tbe->be_req->br_offset == be->be_block)
210 			tbe->be_status = BST_PEND;
211 	}
212 	be->be_tid = 0;
213 	be->be_status = BST_FREE;
214 	be->be_req = NULL;
215 	TAILQ_INSERT_TAIL(&bc->bc_freeq, be, be_link);
216 }
217 
218 static int
blockif_flush_bc(struct blockif_ctxt * bc)219 blockif_flush_bc(struct blockif_ctxt *bc)
220 {
221 	if (bc->bc_ischr) {
222 		if (ioctl(bc->bc_fd, DIOCGFLUSH))
223 			return (errno);
224 	} else if (fsync(bc->bc_fd))
225 		return (errno);
226 
227 	return (0);
228 }
229 
230 static void
blockif_proc(struct blockif_ctxt * bc,struct blockif_elem * be,uint8_t * buf)231 blockif_proc(struct blockif_ctxt *bc, struct blockif_elem *be, uint8_t *buf)
232 {
233 	struct blockif_req *br;
234 	off_t arg[2];
235 	ssize_t n;
236 	size_t clen, len, off, boff, voff;
237 	int i, err;
238 
239 	br = be->be_req;
240 	assert(br->br_resid >= 0);
241 
242 	if (br->br_iovcnt <= 1)
243 		buf = NULL;
244 	err = 0;
245 	switch (be->be_op) {
246 	case BOP_READ:
247 		if (buf == NULL) {
248 			if ((n = preadv(bc->bc_fd, br->br_iov, br->br_iovcnt,
249 			    br->br_offset)) < 0)
250 				err = errno;
251 			else
252 				br->br_resid -= n;
253 			break;
254 		}
255 		i = 0;
256 		off = voff = 0;
257 		while (br->br_resid > 0) {
258 			len = MIN(br->br_resid, MAXPHYS);
259 			n = pread(bc->bc_fd, buf, len, br->br_offset + off);
260 			if (n < 0) {
261 				err = errno;
262 				break;
263 			}
264 			len = (size_t)n;
265 			boff = 0;
266 			do {
267 				clen = MIN(len - boff, br->br_iov[i].iov_len -
268 				    voff);
269 				memcpy((uint8_t *)br->br_iov[i].iov_base + voff,
270 				    buf + boff, clen);
271 				if (clen < br->br_iov[i].iov_len - voff)
272 					voff += clen;
273 				else {
274 					i++;
275 					voff = 0;
276 				}
277 				boff += clen;
278 			} while (boff < len);
279 			off += len;
280 			br->br_resid -= len;
281 		}
282 		break;
283 	case BOP_WRITE:
284 		if (bc->bc_rdonly) {
285 			err = EROFS;
286 			break;
287 		}
288 		if (buf == NULL) {
289 			if ((n = pwritev(bc->bc_fd, br->br_iov, br->br_iovcnt,
290 			    br->br_offset)) < 0)
291 				err = errno;
292 			else
293 				br->br_resid -= n;
294 			break;
295 		}
296 		i = 0;
297 		off = voff = 0;
298 		while (br->br_resid > 0) {
299 			len = MIN(br->br_resid, MAXPHYS);
300 			boff = 0;
301 			do {
302 				clen = MIN(len - boff, br->br_iov[i].iov_len -
303 				    voff);
304 				memcpy(buf + boff,
305 				    (uint8_t *)br->br_iov[i].iov_base + voff,
306 				    clen);
307 				if (clen < br->br_iov[i].iov_len - voff)
308 					voff += clen;
309 				else {
310 					i++;
311 					voff = 0;
312 				}
313 				boff += clen;
314 			} while (boff < len);
315 
316 			n = pwrite(bc->bc_fd, buf, len, br->br_offset + off);
317 			if (n < 0) {
318 				err = errno;
319 				break;
320 			}
321 			off += n;
322 			br->br_resid -= n;
323 		}
324 		break;
325 	case BOP_FLUSH:
326 		err = blockif_flush_bc(bc);
327 		break;
328 	case BOP_DELETE:
329 		if (!bc->bc_candelete)
330 			err = EOPNOTSUPP;
331 		else if (bc->bc_rdonly)
332 			err = EROFS;
333 		else if (bc->bc_ischr) {
334 			arg[0] = br->br_offset;
335 			arg[1] = br->br_resid;
336 			if (ioctl(bc->bc_fd, DIOCGDELETE, arg))
337 				err = errno;
338 			else
339 				br->br_resid = 0;
340 		} else
341 			err = EOPNOTSUPP;
342 		break;
343 	default:
344 		err = EINVAL;
345 		break;
346 	}
347 
348 	be->be_status = BST_DONE;
349 
350 	(*br->br_callback)(br, err);
351 }
352 
353 static inline bool
blockif_empty(const struct blockif_ctxt * bc)354 blockif_empty(const struct blockif_ctxt *bc)
355 {
356 	return (TAILQ_EMPTY(&bc->bc_pendq) && TAILQ_EMPTY(&bc->bc_busyq));
357 }
358 
359 static void *
blockif_thr(void * arg)360 blockif_thr(void *arg)
361 {
362 	struct blockif_ctxt *bc;
363 	struct blockif_elem *be;
364 	pthread_t t;
365 	uint8_t *buf;
366 
367 	bc = arg;
368 	if (bc->bc_isgeom)
369 		buf = malloc(MAXPHYS);
370 	else
371 		buf = NULL;
372 	t = pthread_self();
373 
374 	pthread_mutex_lock(&bc->bc_mtx);
375 	for (;;) {
376 		while (blockif_dequeue(bc, t, &be)) {
377 			pthread_mutex_unlock(&bc->bc_mtx);
378 			blockif_proc(bc, be, buf);
379 			pthread_mutex_lock(&bc->bc_mtx);
380 			blockif_complete(bc, be);
381 		}
382 
383 		/* If none to work, notify the main thread */
384 		if (blockif_empty(bc))
385 			pthread_cond_broadcast(&bc->bc_work_done_cond);
386 
387 		/* Check ctxt status here to see if exit requested */
388 		if (bc->bc_closing)
389 			break;
390 
391 		pthread_cond_wait(&bc->bc_cond, &bc->bc_mtx);
392 	}
393 	pthread_mutex_unlock(&bc->bc_mtx);
394 
395 	if (buf)
396 		free(buf);
397 	pthread_exit(NULL);
398 	return (NULL);
399 }
400 
401 static void
blockif_sigcont_handler(int signal __unused,enum ev_type type __unused,void * arg __unused)402 blockif_sigcont_handler(int signal __unused, enum ev_type type __unused,
403     void *arg __unused)
404 {
405 	struct blockif_sig_elem *bse;
406 
407 	for (;;) {
408 		/*
409 		 * Process the entire list even if not intended for
410 		 * this thread.
411 		 */
412 		do {
413 			bse = blockif_bse_head;
414 			if (bse == NULL)
415 				return;
416 		} while (!atomic_cmpset_ptr((uintptr_t *)&blockif_bse_head,
417 					    (uintptr_t)bse,
418 					    (uintptr_t)bse->bse_next));
419 
420 		pthread_mutex_lock(&bse->bse_mtx);
421 		bse->bse_pending = 0;
422 		pthread_cond_signal(&bse->bse_cond);
423 		pthread_mutex_unlock(&bse->bse_mtx);
424 	}
425 }
426 
427 static void
blockif_init(void)428 blockif_init(void)
429 {
430 	mevent_add(SIGCONT, EVF_SIGNAL, blockif_sigcont_handler, NULL);
431 	(void) signal(SIGCONT, SIG_IGN);
432 }
433 
434 int
blockif_legacy_config(nvlist_t * nvl,const char * opts)435 blockif_legacy_config(nvlist_t *nvl, const char *opts)
436 {
437 	char *cp, *path;
438 
439 	if (opts == NULL)
440 		return (0);
441 
442 	cp = strchr(opts, ',');
443 	if (cp == NULL) {
444 		set_config_value_node(nvl, "path", opts);
445 		return (0);
446 	}
447 	path = strndup(opts, cp - opts);
448 	set_config_value_node(nvl, "path", path);
449 	free(path);
450 	return (pci_parse_legacy_config(nvl, cp + 1));
451 }
452 
453 int
blockif_add_boot_device(struct pci_devinst * const pi,struct blockif_ctxt * const bc)454 blockif_add_boot_device(struct pci_devinst *const pi,
455     struct blockif_ctxt *const bc)
456 {
457 	if (bc->bc_bootindex < 0)
458 		return (0);
459 
460 	return (pci_emul_add_boot_device(pi, bc->bc_bootindex));
461 }
462 
463 struct blockif_ctxt *
blockif_open(nvlist_t * nvl,const char * ident)464 blockif_open(nvlist_t *nvl, const char *ident)
465 {
466 	char tname[MAXCOMLEN + 1];
467 	char name[MAXPATHLEN];
468 	const char *path, *pssval, *ssval, *bootindex_val;
469 	char *cp;
470 	struct blockif_ctxt *bc;
471 	struct stat sbuf;
472 	struct diocgattr_arg arg;
473 	off_t size, psectsz, psectoff;
474 	int extra, fd, i, sectsz;
475 	int ro, candelete, geom, ssopt, pssopt;
476 	int nodelete;
477 	int bootindex;
478 
479 #ifndef WITHOUT_CAPSICUM
480 	cap_rights_t rights;
481 	cap_ioctl_t cmds[] = { DIOCGFLUSH, DIOCGDELETE, DIOCGMEDIASIZE };
482 #endif
483 
484 	pthread_once(&blockif_once, blockif_init);
485 
486 	fd = -1;
487 	extra = 0;
488 	ssopt = 0;
489 	ro = 0;
490 	nodelete = 0;
491 	bootindex = -1;
492 
493 	if (get_config_bool_node_default(nvl, "nocache", false))
494 		extra |= O_DIRECT;
495 	if (get_config_bool_node_default(nvl, "nodelete", false))
496 		nodelete = 1;
497 	if (get_config_bool_node_default(nvl, "sync", false) ||
498 	    get_config_bool_node_default(nvl, "direct", false))
499 		extra |= O_SYNC;
500 	if (get_config_bool_node_default(nvl, "ro", false))
501 		ro = 1;
502 	ssval = get_config_value_node(nvl, "sectorsize");
503 	if (ssval != NULL) {
504 		ssopt = strtol(ssval, &cp, 10);
505 		if (cp == ssval) {
506 			EPRINTLN("Invalid sector size \"%s\"", ssval);
507 			goto err;
508 		}
509 		if (*cp == '\0') {
510 			pssopt = ssopt;
511 		} else if (*cp == '/') {
512 			pssval = cp + 1;
513 			pssopt = strtol(pssval, &cp, 10);
514 			if (cp == pssval || *cp != '\0') {
515 				EPRINTLN("Invalid sector size \"%s\"", ssval);
516 				goto err;
517 			}
518 		} else {
519 			EPRINTLN("Invalid sector size \"%s\"", ssval);
520 			goto err;
521 		}
522 	}
523 
524 	bootindex_val = get_config_value_node(nvl, "bootindex");
525 	if (bootindex_val != NULL) {
526 		bootindex = atoi(bootindex_val);
527 	}
528 
529 	path = get_config_value_node(nvl, "path");
530 	if (path == NULL) {
531 		EPRINTLN("Missing \"path\" for block device.");
532 		goto err;
533 	}
534 
535 	fd = open(path, (ro ? O_RDONLY : O_RDWR) | extra);
536 	if (fd < 0 && !ro) {
537 		/* Attempt a r/w fail with a r/o open */
538 		fd = open(path, O_RDONLY | extra);
539 		ro = 1;
540 	}
541 
542 	if (fd < 0) {
543 		warn("Could not open backing file: %s", path);
544 		goto err;
545 	}
546 
547         if (fstat(fd, &sbuf) < 0) {
548 		warn("Could not stat backing file %s", path);
549 		goto err;
550         }
551 
552 #ifndef WITHOUT_CAPSICUM
553 	cap_rights_init(&rights, CAP_FSYNC, CAP_IOCTL, CAP_READ, CAP_SEEK,
554 	    CAP_WRITE, CAP_FSTAT, CAP_EVENT, CAP_FPATHCONF);
555 	if (ro)
556 		cap_rights_clear(&rights, CAP_FSYNC, CAP_WRITE);
557 
558 	if (caph_rights_limit(fd, &rights) == -1)
559 		errx(EX_OSERR, "Unable to apply rights for sandbox");
560 #endif
561 
562         /*
563 	 * Deal with raw devices
564 	 */
565         size = sbuf.st_size;
566 	sectsz = DEV_BSIZE;
567 	psectsz = psectoff = 0;
568 	candelete = geom = 0;
569 	if (S_ISCHR(sbuf.st_mode)) {
570 		if (ioctl(fd, DIOCGMEDIASIZE, &size) < 0 ||
571 		    ioctl(fd, DIOCGSECTORSIZE, &sectsz)) {
572 			perror("Could not fetch dev blk/sector size");
573 			goto err;
574 		}
575 		assert(size != 0);
576 		assert(sectsz != 0);
577 		if (ioctl(fd, DIOCGSTRIPESIZE, &psectsz) == 0 && psectsz > 0)
578 			ioctl(fd, DIOCGSTRIPEOFFSET, &psectoff);
579 		strlcpy(arg.name, "GEOM::candelete", sizeof(arg.name));
580 		arg.len = sizeof(arg.value.i);
581 		if (nodelete == 0 && ioctl(fd, DIOCGATTR, &arg) == 0)
582 			candelete = arg.value.i;
583 		if (ioctl(fd, DIOCGPROVIDERNAME, name) == 0)
584 			geom = 1;
585 	} else
586 		psectsz = sbuf.st_blksize;
587 
588 #ifndef WITHOUT_CAPSICUM
589 	if (caph_ioctls_limit(fd, cmds, nitems(cmds)) == -1)
590 		errx(EX_OSERR, "Unable to apply rights for sandbox");
591 #endif
592 
593 	if (ssopt != 0) {
594 		if (!powerof2(ssopt) || !powerof2(pssopt) || ssopt < 512 ||
595 		    ssopt > pssopt) {
596 			EPRINTLN("Invalid sector size %d/%d",
597 			    ssopt, pssopt);
598 			goto err;
599 		}
600 
601 		/*
602 		 * Some backend drivers (e.g. cd0, ada0) require that the I/O
603 		 * size be a multiple of the device's sector size.
604 		 *
605 		 * Validate that the emulated sector size complies with this
606 		 * requirement.
607 		 */
608 		if (S_ISCHR(sbuf.st_mode)) {
609 			if (ssopt < sectsz || (ssopt % sectsz) != 0) {
610 				EPRINTLN("Sector size %d incompatible "
611 				    "with underlying device sector size %d",
612 				    ssopt, sectsz);
613 				goto err;
614 			}
615 		}
616 
617 		sectsz = ssopt;
618 		psectsz = pssopt;
619 		psectoff = 0;
620 	}
621 
622 	bc = calloc(1, sizeof(struct blockif_ctxt));
623 	if (bc == NULL) {
624 		perror("calloc");
625 		goto err;
626 	}
627 
628 	bc->bc_magic = BLOCKIF_SIG;
629 	bc->bc_fd = fd;
630 	bc->bc_ischr = S_ISCHR(sbuf.st_mode);
631 	bc->bc_isgeom = geom;
632 	bc->bc_candelete = candelete;
633 	bc->bc_rdonly = ro;
634 	bc->bc_size = size;
635 	bc->bc_sectsz = sectsz;
636 	bc->bc_psectsz = psectsz;
637 	bc->bc_psectoff = psectoff;
638 	pthread_mutex_init(&bc->bc_mtx, NULL);
639 	pthread_cond_init(&bc->bc_cond, NULL);
640 	bc->bc_paused = 0;
641 	pthread_cond_init(&bc->bc_work_done_cond, NULL);
642 	TAILQ_INIT(&bc->bc_freeq);
643 	TAILQ_INIT(&bc->bc_pendq);
644 	TAILQ_INIT(&bc->bc_busyq);
645 	bc->bc_bootindex = bootindex;
646 	for (i = 0; i < BLOCKIF_MAXREQ; i++) {
647 		bc->bc_reqs[i].be_status = BST_FREE;
648 		TAILQ_INSERT_HEAD(&bc->bc_freeq, &bc->bc_reqs[i], be_link);
649 	}
650 
651 	for (i = 0; i < BLOCKIF_NUMTHR; i++) {
652 		pthread_create(&bc->bc_btid[i], NULL, blockif_thr, bc);
653 		snprintf(tname, sizeof(tname), "blk-%s-%d", ident, i);
654 		pthread_set_name_np(bc->bc_btid[i], tname);
655 	}
656 
657 	return (bc);
658 err:
659 	if (fd >= 0)
660 		close(fd);
661 	return (NULL);
662 }
663 
664 static void
blockif_resized(int fd,enum ev_type type __unused,void * arg)665 blockif_resized(int fd, enum ev_type type __unused, void *arg)
666 {
667 	struct blockif_ctxt *bc;
668 	struct stat sb;
669 	off_t mediasize;
670 
671 	if (fstat(fd, &sb) != 0)
672 		return;
673 
674 	if (S_ISCHR(sb.st_mode)) {
675 		if (ioctl(fd, DIOCGMEDIASIZE, &mediasize) < 0) {
676 			EPRINTLN("blockif_resized: get mediasize failed: %s",
677 			    strerror(errno));
678 			return;
679 		}
680 	} else
681 		mediasize = sb.st_size;
682 
683 	bc = arg;
684 	pthread_mutex_lock(&bc->bc_mtx);
685 	if (mediasize != bc->bc_size) {
686 		bc->bc_size = mediasize;
687 		bc->bc_resize_cb(bc, bc->bc_resize_cb_arg, bc->bc_size);
688 	}
689 	pthread_mutex_unlock(&bc->bc_mtx);
690 }
691 
692 int
blockif_register_resize_callback(struct blockif_ctxt * bc,blockif_resize_cb * cb,void * cb_arg)693 blockif_register_resize_callback(struct blockif_ctxt *bc, blockif_resize_cb *cb,
694     void *cb_arg)
695 {
696 	struct stat sb;
697 	int err;
698 
699 	if (cb == NULL)
700 		return (EINVAL);
701 
702 	err = 0;
703 
704 	pthread_mutex_lock(&bc->bc_mtx);
705 	if (bc->bc_resize_cb != NULL) {
706 		err = EBUSY;
707 		goto out;
708 	}
709 
710 	assert(bc->bc_closing == 0);
711 
712 	if (fstat(bc->bc_fd, &sb) != 0) {
713 		err = errno;
714 		goto out;
715 	}
716 
717 	bc->bc_resize_event = mevent_add_flags(bc->bc_fd, EVF_VNODE,
718 	    EVFF_ATTRIB, blockif_resized, bc);
719 	if (bc->bc_resize_event == NULL) {
720 		err = ENXIO;
721 		goto out;
722 	}
723 
724 	bc->bc_resize_cb = cb;
725 	bc->bc_resize_cb_arg = cb_arg;
726 out:
727 	pthread_mutex_unlock(&bc->bc_mtx);
728 
729 	return (err);
730 }
731 
732 static int
blockif_request(struct blockif_ctxt * bc,struct blockif_req * breq,enum blockop op)733 blockif_request(struct blockif_ctxt *bc, struct blockif_req *breq,
734 		enum blockop op)
735 {
736 	int err;
737 
738 	err = 0;
739 
740 	pthread_mutex_lock(&bc->bc_mtx);
741 	assert(!bc->bc_paused);
742 	if (!TAILQ_EMPTY(&bc->bc_freeq)) {
743 		/*
744 		 * Enqueue and inform the block i/o thread
745 		 * that there is work available
746 		 */
747 		if (blockif_enqueue(bc, breq, op))
748 			pthread_cond_signal(&bc->bc_cond);
749 	} else {
750 		/*
751 		 * Callers are not allowed to enqueue more than
752 		 * the specified blockif queue limit. Return an
753 		 * error to indicate that the queue length has been
754 		 * exceeded.
755 		 */
756 		err = E2BIG;
757 	}
758 	pthread_mutex_unlock(&bc->bc_mtx);
759 
760 	return (err);
761 }
762 
763 int
blockif_read(struct blockif_ctxt * bc,struct blockif_req * breq)764 blockif_read(struct blockif_ctxt *bc, struct blockif_req *breq)
765 {
766 	assert(bc->bc_magic == BLOCKIF_SIG);
767 	return (blockif_request(bc, breq, BOP_READ));
768 }
769 
770 int
blockif_write(struct blockif_ctxt * bc,struct blockif_req * breq)771 blockif_write(struct blockif_ctxt *bc, struct blockif_req *breq)
772 {
773 	assert(bc->bc_magic == BLOCKIF_SIG);
774 	return (blockif_request(bc, breq, BOP_WRITE));
775 }
776 
777 int
blockif_flush(struct blockif_ctxt * bc,struct blockif_req * breq)778 blockif_flush(struct blockif_ctxt *bc, struct blockif_req *breq)
779 {
780 	assert(bc->bc_magic == BLOCKIF_SIG);
781 	return (blockif_request(bc, breq, BOP_FLUSH));
782 }
783 
784 int
blockif_delete(struct blockif_ctxt * bc,struct blockif_req * breq)785 blockif_delete(struct blockif_ctxt *bc, struct blockif_req *breq)
786 {
787 	assert(bc->bc_magic == BLOCKIF_SIG);
788 	return (blockif_request(bc, breq, BOP_DELETE));
789 }
790 
791 int
blockif_cancel(struct blockif_ctxt * bc,struct blockif_req * breq)792 blockif_cancel(struct blockif_ctxt *bc, struct blockif_req *breq)
793 {
794 	struct blockif_elem *be;
795 
796 	assert(bc->bc_magic == BLOCKIF_SIG);
797 
798 	pthread_mutex_lock(&bc->bc_mtx);
799 	/* XXX: not waiting while paused */
800 
801 	/*
802 	 * Check pending requests.
803 	 */
804 	TAILQ_FOREACH(be, &bc->bc_pendq, be_link) {
805 		if (be->be_req == breq)
806 			break;
807 	}
808 	if (be != NULL) {
809 		/*
810 		 * Found it.
811 		 */
812 		blockif_complete(bc, be);
813 		pthread_mutex_unlock(&bc->bc_mtx);
814 
815 		return (0);
816 	}
817 
818 	/*
819 	 * Check in-flight requests.
820 	 */
821 	TAILQ_FOREACH(be, &bc->bc_busyq, be_link) {
822 		if (be->be_req == breq)
823 			break;
824 	}
825 	if (be == NULL) {
826 		/*
827 		 * Didn't find it.
828 		 */
829 		pthread_mutex_unlock(&bc->bc_mtx);
830 		return (EINVAL);
831 	}
832 
833 	/*
834 	 * Interrupt the processing thread to force it return
835 	 * prematurely via it's normal callback path.
836 	 */
837 	while (be->be_status == BST_BUSY) {
838 		struct blockif_sig_elem bse, *old_head;
839 
840 		pthread_mutex_init(&bse.bse_mtx, NULL);
841 		pthread_cond_init(&bse.bse_cond, NULL);
842 
843 		bse.bse_pending = 1;
844 
845 		do {
846 			old_head = blockif_bse_head;
847 			bse.bse_next = old_head;
848 		} while (!atomic_cmpset_ptr((uintptr_t *)&blockif_bse_head,
849 					    (uintptr_t)old_head,
850 					    (uintptr_t)&bse));
851 
852 		pthread_kill(be->be_tid, SIGCONT);
853 
854 		pthread_mutex_lock(&bse.bse_mtx);
855 		while (bse.bse_pending)
856 			pthread_cond_wait(&bse.bse_cond, &bse.bse_mtx);
857 		pthread_mutex_unlock(&bse.bse_mtx);
858 	}
859 
860 	pthread_mutex_unlock(&bc->bc_mtx);
861 
862 	/*
863 	 * The processing thread has been interrupted.  Since it's not
864 	 * clear if the callback has been invoked yet, return EBUSY.
865 	 */
866 	return (EBUSY);
867 }
868 
869 int
blockif_close(struct blockif_ctxt * bc)870 blockif_close(struct blockif_ctxt *bc)
871 {
872 	void *jval;
873 	int i;
874 
875 	assert(bc->bc_magic == BLOCKIF_SIG);
876 
877 	/*
878 	 * Stop the block i/o thread
879 	 */
880 	pthread_mutex_lock(&bc->bc_mtx);
881 	bc->bc_closing = 1;
882 	if (bc->bc_resize_event != NULL)
883 		mevent_disable(bc->bc_resize_event);
884 	pthread_mutex_unlock(&bc->bc_mtx);
885 	pthread_cond_broadcast(&bc->bc_cond);
886 	for (i = 0; i < BLOCKIF_NUMTHR; i++)
887 		pthread_join(bc->bc_btid[i], &jval);
888 
889 	/* XXX Cancel queued i/o's ??? */
890 
891 	/*
892 	 * Release resources
893 	 */
894 	bc->bc_magic = 0;
895 	close(bc->bc_fd);
896 	free(bc);
897 
898 	return (0);
899 }
900 
901 /*
902  * Return virtual C/H/S values for a given block. Use the algorithm
903  * outlined in the VHD specification to calculate values.
904  */
905 void
blockif_chs(struct blockif_ctxt * bc,uint16_t * c,uint8_t * h,uint8_t * s)906 blockif_chs(struct blockif_ctxt *bc, uint16_t *c, uint8_t *h, uint8_t *s)
907 {
908 	off_t sectors;		/* total sectors of the block dev */
909 	off_t hcyl;		/* cylinders times heads */
910 	uint16_t secpt;		/* sectors per track */
911 	uint8_t heads;
912 
913 	assert(bc->bc_magic == BLOCKIF_SIG);
914 
915 	sectors = bc->bc_size / bc->bc_sectsz;
916 
917 	/* Clamp the size to the largest possible with CHS */
918 	if (sectors > 65535L * 16 * 255)
919 		sectors = 65535L * 16 * 255;
920 
921 	if (sectors >= 65536L * 16 * 63) {
922 		secpt = 255;
923 		heads = 16;
924 		hcyl = sectors / secpt;
925 	} else {
926 		secpt = 17;
927 		hcyl = sectors / secpt;
928 		heads = (hcyl + 1023) / 1024;
929 
930 		if (heads < 4)
931 			heads = 4;
932 
933 		if (hcyl >= (heads * 1024) || heads > 16) {
934 			secpt = 31;
935 			heads = 16;
936 			hcyl = sectors / secpt;
937 		}
938 		if (hcyl >= (heads * 1024)) {
939 			secpt = 63;
940 			heads = 16;
941 			hcyl = sectors / secpt;
942 		}
943 	}
944 
945 	*c = hcyl / heads;
946 	*h = heads;
947 	*s = secpt;
948 }
949 
950 /*
951  * Accessors
952  */
953 off_t
blockif_size(struct blockif_ctxt * bc)954 blockif_size(struct blockif_ctxt *bc)
955 {
956 	assert(bc->bc_magic == BLOCKIF_SIG);
957 	return (bc->bc_size);
958 }
959 
960 int
blockif_sectsz(struct blockif_ctxt * bc)961 blockif_sectsz(struct blockif_ctxt *bc)
962 {
963 	assert(bc->bc_magic == BLOCKIF_SIG);
964 	return (bc->bc_sectsz);
965 }
966 
967 void
blockif_psectsz(struct blockif_ctxt * bc,int * size,int * off)968 blockif_psectsz(struct blockif_ctxt *bc, int *size, int *off)
969 {
970 	assert(bc->bc_magic == BLOCKIF_SIG);
971 	*size = bc->bc_psectsz;
972 	*off = bc->bc_psectoff;
973 }
974 
975 int
blockif_queuesz(struct blockif_ctxt * bc)976 blockif_queuesz(struct blockif_ctxt *bc)
977 {
978 	assert(bc->bc_magic == BLOCKIF_SIG);
979 	return (BLOCKIF_MAXREQ - 1);
980 }
981 
982 int
blockif_is_ro(struct blockif_ctxt * bc)983 blockif_is_ro(struct blockif_ctxt *bc)
984 {
985 	assert(bc->bc_magic == BLOCKIF_SIG);
986 	return (bc->bc_rdonly);
987 }
988 
989 int
blockif_candelete(struct blockif_ctxt * bc)990 blockif_candelete(struct blockif_ctxt *bc)
991 {
992 	assert(bc->bc_magic == BLOCKIF_SIG);
993 	return (bc->bc_candelete);
994 }
995 
996 #ifdef BHYVE_SNAPSHOT
997 void
blockif_pause(struct blockif_ctxt * bc)998 blockif_pause(struct blockif_ctxt *bc)
999 {
1000 	assert(bc != NULL);
1001 	assert(bc->bc_magic == BLOCKIF_SIG);
1002 
1003 	pthread_mutex_lock(&bc->bc_mtx);
1004 	bc->bc_paused = 1;
1005 
1006 	/* The interface is paused. Wait for workers to finish their work */
1007 	while (!blockif_empty(bc))
1008 		pthread_cond_wait(&bc->bc_work_done_cond, &bc->bc_mtx);
1009 	pthread_mutex_unlock(&bc->bc_mtx);
1010 
1011 	if (!bc->bc_rdonly && blockif_flush_bc(bc))
1012 		EPRINTLN("%s: [WARN] failed to flush backing file.",
1013 			__func__);
1014 }
1015 
1016 void
blockif_resume(struct blockif_ctxt * bc)1017 blockif_resume(struct blockif_ctxt *bc)
1018 {
1019 	assert(bc != NULL);
1020 	assert(bc->bc_magic == BLOCKIF_SIG);
1021 
1022 	pthread_mutex_lock(&bc->bc_mtx);
1023 	bc->bc_paused = 0;
1024 	pthread_mutex_unlock(&bc->bc_mtx);
1025 }
1026 #endif	/* BHYVE_SNAPSHOT */
1027