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