2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2013 Peter Grehan <grehan@freebsd.org>
6 * Copyright 2020 Joyent, Inc.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
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.
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
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
35 #include <sys/param.h>
36 #ifndef WITHOUT_CAPSICUM
37 #include <sys/capsicum.h>
39 #include <sys/queue.h>
40 #include <sys/errno.h>
42 #include <sys/ioctl.h>
46 #ifndef WITHOUT_CAPSICUM
47 #include <capsicum_helpers.h>
55 #include <pthread_np.h>
60 #include <machine/atomic.h>
61 #include <machine/vmm_snapshot.h>
70 #define BLOCKIF_SIG 0xb109b109
72 #define BLOCKIF_NUMTHR 8
73 #define BLOCKIF_MAXREQ (BLOCKIF_RING_MAX + BLOCKIF_NUMTHR)
91 TAILQ_ENTRY(blockif_elem) be_link;
92 struct blockif_req *be_req;
94 enum blockstat be_status;
100 unsigned int bc_magic;
112 pthread_t bc_btid[BLOCKIF_NUMTHR];
113 pthread_mutex_t bc_mtx;
114 pthread_cond_t bc_cond;
115 pthread_cond_t bc_work_done_cond;
116 blockif_resize_cb *bc_resize_cb;
117 void *bc_resize_cb_arg;
118 struct mevent *bc_resize_event;
120 /* Request elements and free/pending/busy queues */
121 TAILQ_HEAD(, blockif_elem) bc_freeq;
122 TAILQ_HEAD(, blockif_elem) bc_pendq;
123 TAILQ_HEAD(, blockif_elem) bc_busyq;
124 struct blockif_elem bc_reqs[BLOCKIF_MAXREQ];
127 static pthread_once_t blockif_once = PTHREAD_ONCE_INIT;
129 struct blockif_sig_elem {
130 pthread_mutex_t bse_mtx;
131 pthread_cond_t bse_cond;
133 struct blockif_sig_elem *bse_next;
136 static struct blockif_sig_elem *blockif_bse_head;
139 blockif_enqueue(struct blockif_ctxt *bc, struct blockif_req *breq,
142 struct blockif_elem *be, *tbe;
146 be = TAILQ_FIRST(&bc->bc_freeq);
148 assert(be->be_status == BST_FREE);
149 TAILQ_REMOVE(&bc->bc_freeq, be, be_link);
156 off = breq->br_offset;
157 for (i = 0; i < breq->br_iovcnt; i++)
158 off += breq->br_iov[i].iov_len;
164 TAILQ_FOREACH(tbe, &bc->bc_pendq, be_link) {
165 if (tbe->be_block == breq->br_offset)
169 TAILQ_FOREACH(tbe, &bc->bc_busyq, be_link) {
170 if (tbe->be_block == breq->br_offset)
175 be->be_status = BST_PEND;
177 be->be_status = BST_BLOCK;
178 TAILQ_INSERT_TAIL(&bc->bc_pendq, be, be_link);
179 return (be->be_status == BST_PEND);
183 blockif_dequeue(struct blockif_ctxt *bc, pthread_t t, struct blockif_elem **bep)
185 struct blockif_elem *be;
187 TAILQ_FOREACH(be, &bc->bc_pendq, be_link) {
188 if (be->be_status == BST_PEND)
190 assert(be->be_status == BST_BLOCK);
194 TAILQ_REMOVE(&bc->bc_pendq, be, be_link);
195 be->be_status = BST_BUSY;
197 TAILQ_INSERT_TAIL(&bc->bc_busyq, be, be_link);
203 blockif_complete(struct blockif_ctxt *bc, struct blockif_elem *be)
205 struct blockif_elem *tbe;
207 if (be->be_status == BST_DONE || be->be_status == BST_BUSY)
208 TAILQ_REMOVE(&bc->bc_busyq, be, be_link);
210 TAILQ_REMOVE(&bc->bc_pendq, be, be_link);
211 TAILQ_FOREACH(tbe, &bc->bc_pendq, be_link) {
212 if (tbe->be_req->br_offset == be->be_block)
213 tbe->be_status = BST_PEND;
216 be->be_status = BST_FREE;
218 TAILQ_INSERT_TAIL(&bc->bc_freeq, be, be_link);
222 blockif_flush_bc(struct blockif_ctxt *bc)
225 if (ioctl(bc->bc_fd, DIOCGFLUSH))
227 } else if (fsync(bc->bc_fd))
234 blockif_proc(struct blockif_ctxt *bc, struct blockif_elem *be, uint8_t *buf)
236 struct blockif_req *br;
238 ssize_t clen, len, off, boff, voff;
240 struct spacectl_range range;
243 if (br->br_iovcnt <= 1)
249 if ((len = preadv(bc->bc_fd, br->br_iov, br->br_iovcnt,
258 while (br->br_resid > 0) {
259 len = MIN(br->br_resid, MAXPHYS);
260 if (pread(bc->bc_fd, buf, len, br->br_offset +
267 clen = MIN(len - boff, br->br_iov[i].iov_len -
269 memcpy(br->br_iov[i].iov_base + voff,
271 if (clen < br->br_iov[i].iov_len - voff)
278 } while (boff < len);
289 if ((len = pwritev(bc->bc_fd, br->br_iov, br->br_iovcnt,
298 while (br->br_resid > 0) {
299 len = MIN(br->br_resid, MAXPHYS);
302 clen = MIN(len - boff, br->br_iov[i].iov_len -
305 br->br_iov[i].iov_base + voff, clen);
306 if (clen < br->br_iov[i].iov_len - voff)
313 } while (boff < len);
314 if (pwrite(bc->bc_fd, buf, len, br->br_offset +
324 err = blockif_flush_bc(bc);
327 if (!bc->bc_candelete)
329 else if (bc->bc_rdonly)
331 else if (bc->bc_ischr) {
332 arg[0] = br->br_offset;
333 arg[1] = br->br_resid;
334 if (ioctl(bc->bc_fd, DIOCGDELETE, arg))
339 range.r_offset = br->br_offset;
340 range.r_len = br->br_resid;
342 while (range.r_len > 0) {
343 if (fspacectl(bc->bc_fd, SPACECTL_DEALLOC,
344 &range, 0, &range) != 0) {
358 be->be_status = BST_DONE;
360 (*br->br_callback)(br, err);
364 blockif_empty(const struct blockif_ctxt *bc)
366 return (TAILQ_EMPTY(&bc->bc_pendq) && TAILQ_EMPTY(&bc->bc_busyq));
370 blockif_thr(void *arg)
372 struct blockif_ctxt *bc;
373 struct blockif_elem *be;
379 buf = malloc(MAXPHYS);
384 pthread_mutex_lock(&bc->bc_mtx);
386 while (blockif_dequeue(bc, t, &be)) {
387 pthread_mutex_unlock(&bc->bc_mtx);
388 blockif_proc(bc, be, buf);
389 pthread_mutex_lock(&bc->bc_mtx);
390 blockif_complete(bc, be);
393 /* If none to work, notify the main thread */
394 if (blockif_empty(bc))
395 pthread_cond_broadcast(&bc->bc_work_done_cond);
397 /* Check ctxt status here to see if exit requested */
401 pthread_cond_wait(&bc->bc_cond, &bc->bc_mtx);
403 pthread_mutex_unlock(&bc->bc_mtx);
412 blockif_sigcont_handler(int signal __unused, enum ev_type type __unused,
415 struct blockif_sig_elem *bse;
419 * Process the entire list even if not intended for
423 bse = blockif_bse_head;
426 } while (!atomic_cmpset_ptr((uintptr_t *)&blockif_bse_head,
428 (uintptr_t)bse->bse_next));
430 pthread_mutex_lock(&bse->bse_mtx);
431 bse->bse_pending = 0;
432 pthread_cond_signal(&bse->bse_cond);
433 pthread_mutex_unlock(&bse->bse_mtx);
440 mevent_add(SIGCONT, EVF_SIGNAL, blockif_sigcont_handler, NULL);
441 (void) signal(SIGCONT, SIG_IGN);
445 blockif_legacy_config(nvlist_t *nvl, const char *opts)
452 cp = strchr(opts, ',');
454 set_config_value_node(nvl, "path", opts);
457 path = strndup(opts, cp - opts);
458 set_config_value_node(nvl, "path", path);
460 return (pci_parse_legacy_config(nvl, cp + 1));
463 struct blockif_ctxt *
464 blockif_open(nvlist_t *nvl, const char *ident)
466 char tname[MAXCOMLEN + 1];
467 char name[MAXPATHLEN];
468 const char *path, *pssval, *ssval;
470 struct blockif_ctxt *bc;
472 struct diocgattr_arg arg;
473 off_t size, psectsz, psectoff;
474 int extra, fd, i, sectsz;
475 int ro, candelete, geom, ssopt, pssopt;
478 #ifndef WITHOUT_CAPSICUM
480 cap_ioctl_t cmds[] = { DIOCGFLUSH, DIOCGDELETE, DIOCGMEDIASIZE };
483 pthread_once(&blockif_once, blockif_init);
491 if (get_config_bool_node_default(nvl, "nocache", false))
493 if (get_config_bool_node_default(nvl, "nodelete", false))
495 if (get_config_bool_node_default(nvl, "sync", false) ||
496 get_config_bool_node_default(nvl, "direct", false))
498 if (get_config_bool_node_default(nvl, "ro", false))
500 ssval = get_config_value_node(nvl, "sectorsize");
502 ssopt = strtol(ssval, &cp, 10);
504 EPRINTLN("Invalid sector size \"%s\"", ssval);
509 } else if (*cp == '/') {
511 pssopt = strtol(pssval, &cp, 10);
512 if (cp == pssval || *cp != '\0') {
513 EPRINTLN("Invalid sector size \"%s\"", ssval);
517 EPRINTLN("Invalid sector size \"%s\"", ssval);
522 path = get_config_value_node(nvl, "path");
524 EPRINTLN("Missing \"path\" for block device.");
528 fd = open(path, (ro ? O_RDONLY : O_RDWR) | extra);
530 /* Attempt a r/w fail with a r/o open */
531 fd = open(path, O_RDONLY | extra);
536 warn("Could not open backing file: %s", path);
540 if (fstat(fd, &sbuf) < 0) {
541 warn("Could not stat backing file %s", path);
545 #ifndef WITHOUT_CAPSICUM
546 cap_rights_init(&rights, CAP_FSYNC, CAP_IOCTL, CAP_READ, CAP_SEEK,
547 CAP_WRITE, CAP_FSTAT, CAP_EVENT, CAP_FPATHCONF);
549 cap_rights_clear(&rights, CAP_FSYNC, CAP_WRITE);
551 if (caph_rights_limit(fd, &rights) == -1)
552 errx(EX_OSERR, "Unable to apply rights for sandbox");
556 * Deal with raw devices
560 psectsz = psectoff = 0;
561 candelete = geom = 0;
562 if (S_ISCHR(sbuf.st_mode)) {
563 if (ioctl(fd, DIOCGMEDIASIZE, &size) < 0 ||
564 ioctl(fd, DIOCGSECTORSIZE, §sz)) {
565 perror("Could not fetch dev blk/sector size");
570 if (ioctl(fd, DIOCGSTRIPESIZE, &psectsz) == 0 && psectsz > 0)
571 ioctl(fd, DIOCGSTRIPEOFFSET, &psectoff);
572 strlcpy(arg.name, "GEOM::candelete", sizeof(arg.name));
573 arg.len = sizeof(arg.value.i);
574 if (nodelete == 0 && ioctl(fd, DIOCGATTR, &arg) == 0)
575 candelete = arg.value.i;
576 if (ioctl(fd, DIOCGPROVIDERNAME, name) == 0)
579 psectsz = sbuf.st_blksize;
580 /* Avoid fallback implementation */
581 candelete = fpathconf(fd, _PC_DEALLOC_PRESENT) == 1;
584 #ifndef WITHOUT_CAPSICUM
585 if (caph_ioctls_limit(fd, cmds, nitems(cmds)) == -1)
586 errx(EX_OSERR, "Unable to apply rights for sandbox");
590 if (!powerof2(ssopt) || !powerof2(pssopt) || ssopt < 512 ||
592 EPRINTLN("Invalid sector size %d/%d",
598 * Some backend drivers (e.g. cd0, ada0) require that the I/O
599 * size be a multiple of the device's sector size.
601 * Validate that the emulated sector size complies with this
604 if (S_ISCHR(sbuf.st_mode)) {
605 if (ssopt < sectsz || (ssopt % sectsz) != 0) {
606 EPRINTLN("Sector size %d incompatible "
607 "with underlying device sector size %d",
618 bc = calloc(1, sizeof(struct blockif_ctxt));
624 bc->bc_magic = BLOCKIF_SIG;
626 bc->bc_ischr = S_ISCHR(sbuf.st_mode);
627 bc->bc_isgeom = geom;
628 bc->bc_candelete = candelete;
631 bc->bc_sectsz = sectsz;
632 bc->bc_psectsz = psectsz;
633 bc->bc_psectoff = psectoff;
634 pthread_mutex_init(&bc->bc_mtx, NULL);
635 pthread_cond_init(&bc->bc_cond, NULL);
637 pthread_cond_init(&bc->bc_work_done_cond, NULL);
638 TAILQ_INIT(&bc->bc_freeq);
639 TAILQ_INIT(&bc->bc_pendq);
640 TAILQ_INIT(&bc->bc_busyq);
641 for (i = 0; i < BLOCKIF_MAXREQ; i++) {
642 bc->bc_reqs[i].be_status = BST_FREE;
643 TAILQ_INSERT_HEAD(&bc->bc_freeq, &bc->bc_reqs[i], be_link);
646 for (i = 0; i < BLOCKIF_NUMTHR; i++) {
647 pthread_create(&bc->bc_btid[i], NULL, blockif_thr, bc);
648 snprintf(tname, sizeof(tname), "blk-%s-%d", ident, i);
649 pthread_set_name_np(bc->bc_btid[i], tname);
660 blockif_resized(int fd, enum ev_type type __unused, void *arg)
662 struct blockif_ctxt *bc;
666 if (fstat(fd, &sb) != 0)
669 if (S_ISCHR(sb.st_mode)) {
670 if (ioctl(fd, DIOCGMEDIASIZE, &mediasize) < 0) {
671 EPRINTLN("blockif_resized: get mediasize failed: %s",
676 mediasize = sb.st_size;
679 pthread_mutex_lock(&bc->bc_mtx);
680 if (mediasize != bc->bc_size) {
681 bc->bc_size = mediasize;
682 bc->bc_resize_cb(bc, bc->bc_resize_cb_arg, bc->bc_size);
684 pthread_mutex_unlock(&bc->bc_mtx);
688 blockif_register_resize_callback(struct blockif_ctxt *bc, blockif_resize_cb *cb,
699 pthread_mutex_lock(&bc->bc_mtx);
700 if (bc->bc_resize_cb != NULL) {
705 assert(bc->bc_closing == 0);
707 if (fstat(bc->bc_fd, &sb) != 0) {
712 bc->bc_resize_event = mevent_add_flags(bc->bc_fd, EVF_VNODE,
713 EVFF_ATTRIB, blockif_resized, bc);
714 if (bc->bc_resize_event == NULL) {
719 bc->bc_resize_cb = cb;
720 bc->bc_resize_cb_arg = cb_arg;
722 pthread_mutex_unlock(&bc->bc_mtx);
728 blockif_request(struct blockif_ctxt *bc, struct blockif_req *breq,
735 pthread_mutex_lock(&bc->bc_mtx);
736 assert(!bc->bc_paused);
737 if (!TAILQ_EMPTY(&bc->bc_freeq)) {
739 * Enqueue and inform the block i/o thread
740 * that there is work available
742 if (blockif_enqueue(bc, breq, op))
743 pthread_cond_signal(&bc->bc_cond);
746 * Callers are not allowed to enqueue more than
747 * the specified blockif queue limit. Return an
748 * error to indicate that the queue length has been
753 pthread_mutex_unlock(&bc->bc_mtx);
759 blockif_read(struct blockif_ctxt *bc, struct blockif_req *breq)
761 assert(bc->bc_magic == BLOCKIF_SIG);
762 return (blockif_request(bc, breq, BOP_READ));
766 blockif_write(struct blockif_ctxt *bc, struct blockif_req *breq)
768 assert(bc->bc_magic == BLOCKIF_SIG);
769 return (blockif_request(bc, breq, BOP_WRITE));
773 blockif_flush(struct blockif_ctxt *bc, struct blockif_req *breq)
775 assert(bc->bc_magic == BLOCKIF_SIG);
776 return (blockif_request(bc, breq, BOP_FLUSH));
780 blockif_delete(struct blockif_ctxt *bc, struct blockif_req *breq)
782 assert(bc->bc_magic == BLOCKIF_SIG);
783 return (blockif_request(bc, breq, BOP_DELETE));
787 blockif_cancel(struct blockif_ctxt *bc, struct blockif_req *breq)
789 struct blockif_elem *be;
791 assert(bc->bc_magic == BLOCKIF_SIG);
793 pthread_mutex_lock(&bc->bc_mtx);
794 /* XXX: not waiting while paused */
797 * Check pending requests.
799 TAILQ_FOREACH(be, &bc->bc_pendq, be_link) {
800 if (be->be_req == breq)
807 blockif_complete(bc, be);
808 pthread_mutex_unlock(&bc->bc_mtx);
814 * Check in-flight requests.
816 TAILQ_FOREACH(be, &bc->bc_busyq, be_link) {
817 if (be->be_req == breq)
824 pthread_mutex_unlock(&bc->bc_mtx);
829 * Interrupt the processing thread to force it return
830 * prematurely via it's normal callback path.
832 while (be->be_status == BST_BUSY) {
833 struct blockif_sig_elem bse, *old_head;
835 pthread_mutex_init(&bse.bse_mtx, NULL);
836 pthread_cond_init(&bse.bse_cond, NULL);
841 old_head = blockif_bse_head;
842 bse.bse_next = old_head;
843 } while (!atomic_cmpset_ptr((uintptr_t *)&blockif_bse_head,
847 pthread_kill(be->be_tid, SIGCONT);
849 pthread_mutex_lock(&bse.bse_mtx);
850 while (bse.bse_pending)
851 pthread_cond_wait(&bse.bse_cond, &bse.bse_mtx);
852 pthread_mutex_unlock(&bse.bse_mtx);
855 pthread_mutex_unlock(&bc->bc_mtx);
858 * The processing thread has been interrupted. Since it's not
859 * clear if the callback has been invoked yet, return EBUSY.
865 blockif_close(struct blockif_ctxt *bc)
870 assert(bc->bc_magic == BLOCKIF_SIG);
873 * Stop the block i/o thread
875 pthread_mutex_lock(&bc->bc_mtx);
877 if (bc->bc_resize_event != NULL)
878 mevent_disable(bc->bc_resize_event);
879 pthread_mutex_unlock(&bc->bc_mtx);
880 pthread_cond_broadcast(&bc->bc_cond);
881 for (i = 0; i < BLOCKIF_NUMTHR; i++)
882 pthread_join(bc->bc_btid[i], &jval);
884 /* XXX Cancel queued i/o's ??? */
897 * Return virtual C/H/S values for a given block. Use the algorithm
898 * outlined in the VHD specification to calculate values.
901 blockif_chs(struct blockif_ctxt *bc, uint16_t *c, uint8_t *h, uint8_t *s)
903 off_t sectors; /* total sectors of the block dev */
904 off_t hcyl; /* cylinders times heads */
905 uint16_t secpt; /* sectors per track */
908 assert(bc->bc_magic == BLOCKIF_SIG);
910 sectors = bc->bc_size / bc->bc_sectsz;
912 /* Clamp the size to the largest possible with CHS */
913 if (sectors > 65535UL*16*255)
914 sectors = 65535UL*16*255;
916 if (sectors >= 65536UL*16*63) {
919 hcyl = sectors / secpt;
922 hcyl = sectors / secpt;
923 heads = (hcyl + 1023) / 1024;
928 if (hcyl >= (heads * 1024) || heads > 16) {
931 hcyl = sectors / secpt;
933 if (hcyl >= (heads * 1024)) {
936 hcyl = sectors / secpt;
949 blockif_size(struct blockif_ctxt *bc)
951 assert(bc->bc_magic == BLOCKIF_SIG);
952 return (bc->bc_size);
956 blockif_sectsz(struct blockif_ctxt *bc)
958 assert(bc->bc_magic == BLOCKIF_SIG);
959 return (bc->bc_sectsz);
963 blockif_psectsz(struct blockif_ctxt *bc, int *size, int *off)
965 assert(bc->bc_magic == BLOCKIF_SIG);
966 *size = bc->bc_psectsz;
967 *off = bc->bc_psectoff;
971 blockif_queuesz(struct blockif_ctxt *bc)
973 assert(bc->bc_magic == BLOCKIF_SIG);
974 return (BLOCKIF_MAXREQ - 1);
978 blockif_is_ro(struct blockif_ctxt *bc)
980 assert(bc->bc_magic == BLOCKIF_SIG);
981 return (bc->bc_rdonly);
985 blockif_candelete(struct blockif_ctxt *bc)
987 assert(bc->bc_magic == BLOCKIF_SIG);
988 return (bc->bc_candelete);
991 #ifdef BHYVE_SNAPSHOT
993 blockif_pause(struct blockif_ctxt *bc)
996 assert(bc->bc_magic == BLOCKIF_SIG);
998 pthread_mutex_lock(&bc->bc_mtx);
1001 /* The interface is paused. Wait for workers to finish their work */
1002 while (!blockif_empty(bc))
1003 pthread_cond_wait(&bc->bc_work_done_cond, &bc->bc_mtx);
1004 pthread_mutex_unlock(&bc->bc_mtx);
1006 if (blockif_flush_bc(bc))
1007 fprintf(stderr, "%s: [WARN] failed to flush backing file.\r\n",
1012 blockif_resume(struct blockif_ctxt *bc)
1015 assert(bc->bc_magic == BLOCKIF_SIG);
1017 pthread_mutex_lock(&bc->bc_mtx);
1019 pthread_mutex_unlock(&bc->bc_mtx);
1021 #endif /* BHYVE_SNAPSHOT */