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 spacectl_range range;
237 struct blockif_req *br;
240 size_t clen, len, off, boff, voff;
244 assert(br->br_resid >= 0);
246 if (br->br_iovcnt <= 1)
252 if ((n = preadv(bc->bc_fd, br->br_iov, br->br_iovcnt,
261 while (br->br_resid > 0) {
262 len = MIN(br->br_resid, MAXPHYS);
263 n = pread(bc->bc_fd, buf, len, br->br_offset + off);
271 clen = MIN(len - boff, br->br_iov[i].iov_len -
273 memcpy((uint8_t *)br->br_iov[i].iov_base + voff,
275 if (clen < br->br_iov[i].iov_len - voff)
282 } while (boff < len);
293 if ((n = pwritev(bc->bc_fd, br->br_iov, br->br_iovcnt,
302 while (br->br_resid > 0) {
303 len = MIN(br->br_resid, MAXPHYS);
306 clen = MIN(len - boff, br->br_iov[i].iov_len -
309 (uint8_t *)br->br_iov[i].iov_base + voff,
311 if (clen < br->br_iov[i].iov_len - voff)
318 } while (boff < len);
320 n = pwrite(bc->bc_fd, buf, len, br->br_offset + off);
330 err = blockif_flush_bc(bc);
333 if (!bc->bc_candelete)
335 else if (bc->bc_rdonly)
337 else if (bc->bc_ischr) {
338 arg[0] = br->br_offset;
339 arg[1] = br->br_resid;
340 if (ioctl(bc->bc_fd, DIOCGDELETE, arg))
345 range.r_offset = br->br_offset;
346 range.r_len = br->br_resid;
348 while (range.r_len > 0) {
349 if (fspacectl(bc->bc_fd, SPACECTL_DEALLOC,
350 &range, 0, &range) != 0) {
364 be->be_status = BST_DONE;
366 (*br->br_callback)(br, err);
370 blockif_empty(const struct blockif_ctxt *bc)
372 return (TAILQ_EMPTY(&bc->bc_pendq) && TAILQ_EMPTY(&bc->bc_busyq));
376 blockif_thr(void *arg)
378 struct blockif_ctxt *bc;
379 struct blockif_elem *be;
385 buf = malloc(MAXPHYS);
390 pthread_mutex_lock(&bc->bc_mtx);
392 while (blockif_dequeue(bc, t, &be)) {
393 pthread_mutex_unlock(&bc->bc_mtx);
394 blockif_proc(bc, be, buf);
395 pthread_mutex_lock(&bc->bc_mtx);
396 blockif_complete(bc, be);
399 /* If none to work, notify the main thread */
400 if (blockif_empty(bc))
401 pthread_cond_broadcast(&bc->bc_work_done_cond);
403 /* Check ctxt status here to see if exit requested */
407 pthread_cond_wait(&bc->bc_cond, &bc->bc_mtx);
409 pthread_mutex_unlock(&bc->bc_mtx);
418 blockif_sigcont_handler(int signal __unused, enum ev_type type __unused,
421 struct blockif_sig_elem *bse;
425 * Process the entire list even if not intended for
429 bse = blockif_bse_head;
432 } while (!atomic_cmpset_ptr((uintptr_t *)&blockif_bse_head,
434 (uintptr_t)bse->bse_next));
436 pthread_mutex_lock(&bse->bse_mtx);
437 bse->bse_pending = 0;
438 pthread_cond_signal(&bse->bse_cond);
439 pthread_mutex_unlock(&bse->bse_mtx);
446 mevent_add(SIGCONT, EVF_SIGNAL, blockif_sigcont_handler, NULL);
447 (void) signal(SIGCONT, SIG_IGN);
451 blockif_legacy_config(nvlist_t *nvl, const char *opts)
458 cp = strchr(opts, ',');
460 set_config_value_node(nvl, "path", opts);
463 path = strndup(opts, cp - opts);
464 set_config_value_node(nvl, "path", path);
466 return (pci_parse_legacy_config(nvl, cp + 1));
469 struct blockif_ctxt *
470 blockif_open(nvlist_t *nvl, const char *ident)
472 char tname[MAXCOMLEN + 1];
473 char name[MAXPATHLEN];
474 const char *path, *pssval, *ssval;
476 struct blockif_ctxt *bc;
478 struct diocgattr_arg arg;
479 off_t size, psectsz, psectoff;
480 int extra, fd, i, sectsz;
481 int ro, candelete, geom, ssopt, pssopt;
484 #ifndef WITHOUT_CAPSICUM
486 cap_ioctl_t cmds[] = { DIOCGFLUSH, DIOCGDELETE, DIOCGMEDIASIZE };
489 pthread_once(&blockif_once, blockif_init);
497 if (get_config_bool_node_default(nvl, "nocache", false))
499 if (get_config_bool_node_default(nvl, "nodelete", false))
501 if (get_config_bool_node_default(nvl, "sync", false) ||
502 get_config_bool_node_default(nvl, "direct", false))
504 if (get_config_bool_node_default(nvl, "ro", false))
506 ssval = get_config_value_node(nvl, "sectorsize");
508 ssopt = strtol(ssval, &cp, 10);
510 EPRINTLN("Invalid sector size \"%s\"", ssval);
515 } else if (*cp == '/') {
517 pssopt = strtol(pssval, &cp, 10);
518 if (cp == pssval || *cp != '\0') {
519 EPRINTLN("Invalid sector size \"%s\"", ssval);
523 EPRINTLN("Invalid sector size \"%s\"", ssval);
528 path = get_config_value_node(nvl, "path");
530 EPRINTLN("Missing \"path\" for block device.");
534 fd = open(path, (ro ? O_RDONLY : O_RDWR) | extra);
536 /* Attempt a r/w fail with a r/o open */
537 fd = open(path, O_RDONLY | extra);
542 warn("Could not open backing file: %s", path);
546 if (fstat(fd, &sbuf) < 0) {
547 warn("Could not stat backing file %s", path);
551 #ifndef WITHOUT_CAPSICUM
552 cap_rights_init(&rights, CAP_FSYNC, CAP_IOCTL, CAP_READ, CAP_SEEK,
553 CAP_WRITE, CAP_FSTAT, CAP_EVENT, CAP_FPATHCONF);
555 cap_rights_clear(&rights, CAP_FSYNC, CAP_WRITE);
557 if (caph_rights_limit(fd, &rights) == -1)
558 errx(EX_OSERR, "Unable to apply rights for sandbox");
562 * Deal with raw devices
566 psectsz = psectoff = 0;
567 candelete = geom = 0;
568 if (S_ISCHR(sbuf.st_mode)) {
569 if (ioctl(fd, DIOCGMEDIASIZE, &size) < 0 ||
570 ioctl(fd, DIOCGSECTORSIZE, §sz)) {
571 perror("Could not fetch dev blk/sector size");
576 if (ioctl(fd, DIOCGSTRIPESIZE, &psectsz) == 0 && psectsz > 0)
577 ioctl(fd, DIOCGSTRIPEOFFSET, &psectoff);
578 strlcpy(arg.name, "GEOM::candelete", sizeof(arg.name));
579 arg.len = sizeof(arg.value.i);
580 if (nodelete == 0 && ioctl(fd, DIOCGATTR, &arg) == 0)
581 candelete = arg.value.i;
582 if (ioctl(fd, DIOCGPROVIDERNAME, name) == 0)
585 psectsz = sbuf.st_blksize;
586 /* Avoid fallback implementation */
587 candelete = fpathconf(fd, _PC_DEALLOC_PRESENT) == 1;
590 #ifndef WITHOUT_CAPSICUM
591 if (caph_ioctls_limit(fd, cmds, nitems(cmds)) == -1)
592 errx(EX_OSERR, "Unable to apply rights for sandbox");
596 if (!powerof2(ssopt) || !powerof2(pssopt) || ssopt < 512 ||
598 EPRINTLN("Invalid sector size %d/%d",
604 * Some backend drivers (e.g. cd0, ada0) require that the I/O
605 * size be a multiple of the device's sector size.
607 * Validate that the emulated sector size complies with this
610 if (S_ISCHR(sbuf.st_mode)) {
611 if (ssopt < sectsz || (ssopt % sectsz) != 0) {
612 EPRINTLN("Sector size %d incompatible "
613 "with underlying device sector size %d",
624 bc = calloc(1, sizeof(struct blockif_ctxt));
630 bc->bc_magic = BLOCKIF_SIG;
632 bc->bc_ischr = S_ISCHR(sbuf.st_mode);
633 bc->bc_isgeom = geom;
634 bc->bc_candelete = candelete;
637 bc->bc_sectsz = sectsz;
638 bc->bc_psectsz = psectsz;
639 bc->bc_psectoff = psectoff;
640 pthread_mutex_init(&bc->bc_mtx, NULL);
641 pthread_cond_init(&bc->bc_cond, NULL);
643 pthread_cond_init(&bc->bc_work_done_cond, NULL);
644 TAILQ_INIT(&bc->bc_freeq);
645 TAILQ_INIT(&bc->bc_pendq);
646 TAILQ_INIT(&bc->bc_busyq);
647 for (i = 0; i < BLOCKIF_MAXREQ; i++) {
648 bc->bc_reqs[i].be_status = BST_FREE;
649 TAILQ_INSERT_HEAD(&bc->bc_freeq, &bc->bc_reqs[i], be_link);
652 for (i = 0; i < BLOCKIF_NUMTHR; i++) {
653 pthread_create(&bc->bc_btid[i], NULL, blockif_thr, bc);
654 snprintf(tname, sizeof(tname), "blk-%s-%d", ident, i);
655 pthread_set_name_np(bc->bc_btid[i], tname);
666 blockif_resized(int fd, enum ev_type type __unused, void *arg)
668 struct blockif_ctxt *bc;
672 if (fstat(fd, &sb) != 0)
675 if (S_ISCHR(sb.st_mode)) {
676 if (ioctl(fd, DIOCGMEDIASIZE, &mediasize) < 0) {
677 EPRINTLN("blockif_resized: get mediasize failed: %s",
682 mediasize = sb.st_size;
685 pthread_mutex_lock(&bc->bc_mtx);
686 if (mediasize != bc->bc_size) {
687 bc->bc_size = mediasize;
688 bc->bc_resize_cb(bc, bc->bc_resize_cb_arg, bc->bc_size);
690 pthread_mutex_unlock(&bc->bc_mtx);
694 blockif_register_resize_callback(struct blockif_ctxt *bc, blockif_resize_cb *cb,
705 pthread_mutex_lock(&bc->bc_mtx);
706 if (bc->bc_resize_cb != NULL) {
711 assert(bc->bc_closing == 0);
713 if (fstat(bc->bc_fd, &sb) != 0) {
718 bc->bc_resize_event = mevent_add_flags(bc->bc_fd, EVF_VNODE,
719 EVFF_ATTRIB, blockif_resized, bc);
720 if (bc->bc_resize_event == NULL) {
725 bc->bc_resize_cb = cb;
726 bc->bc_resize_cb_arg = cb_arg;
728 pthread_mutex_unlock(&bc->bc_mtx);
734 blockif_request(struct blockif_ctxt *bc, struct blockif_req *breq,
741 pthread_mutex_lock(&bc->bc_mtx);
742 assert(!bc->bc_paused);
743 if (!TAILQ_EMPTY(&bc->bc_freeq)) {
745 * Enqueue and inform the block i/o thread
746 * that there is work available
748 if (blockif_enqueue(bc, breq, op))
749 pthread_cond_signal(&bc->bc_cond);
752 * Callers are not allowed to enqueue more than
753 * the specified blockif queue limit. Return an
754 * error to indicate that the queue length has been
759 pthread_mutex_unlock(&bc->bc_mtx);
765 blockif_read(struct blockif_ctxt *bc, struct blockif_req *breq)
767 assert(bc->bc_magic == BLOCKIF_SIG);
768 return (blockif_request(bc, breq, BOP_READ));
772 blockif_write(struct blockif_ctxt *bc, struct blockif_req *breq)
774 assert(bc->bc_magic == BLOCKIF_SIG);
775 return (blockif_request(bc, breq, BOP_WRITE));
779 blockif_flush(struct blockif_ctxt *bc, struct blockif_req *breq)
781 assert(bc->bc_magic == BLOCKIF_SIG);
782 return (blockif_request(bc, breq, BOP_FLUSH));
786 blockif_delete(struct blockif_ctxt *bc, struct blockif_req *breq)
788 assert(bc->bc_magic == BLOCKIF_SIG);
789 return (blockif_request(bc, breq, BOP_DELETE));
793 blockif_cancel(struct blockif_ctxt *bc, struct blockif_req *breq)
795 struct blockif_elem *be;
797 assert(bc->bc_magic == BLOCKIF_SIG);
799 pthread_mutex_lock(&bc->bc_mtx);
800 /* XXX: not waiting while paused */
803 * Check pending requests.
805 TAILQ_FOREACH(be, &bc->bc_pendq, be_link) {
806 if (be->be_req == breq)
813 blockif_complete(bc, be);
814 pthread_mutex_unlock(&bc->bc_mtx);
820 * Check in-flight requests.
822 TAILQ_FOREACH(be, &bc->bc_busyq, be_link) {
823 if (be->be_req == breq)
830 pthread_mutex_unlock(&bc->bc_mtx);
835 * Interrupt the processing thread to force it return
836 * prematurely via it's normal callback path.
838 while (be->be_status == BST_BUSY) {
839 struct blockif_sig_elem bse, *old_head;
841 pthread_mutex_init(&bse.bse_mtx, NULL);
842 pthread_cond_init(&bse.bse_cond, NULL);
847 old_head = blockif_bse_head;
848 bse.bse_next = old_head;
849 } while (!atomic_cmpset_ptr((uintptr_t *)&blockif_bse_head,
853 pthread_kill(be->be_tid, SIGCONT);
855 pthread_mutex_lock(&bse.bse_mtx);
856 while (bse.bse_pending)
857 pthread_cond_wait(&bse.bse_cond, &bse.bse_mtx);
858 pthread_mutex_unlock(&bse.bse_mtx);
861 pthread_mutex_unlock(&bc->bc_mtx);
864 * The processing thread has been interrupted. Since it's not
865 * clear if the callback has been invoked yet, return EBUSY.
871 blockif_close(struct blockif_ctxt *bc)
876 assert(bc->bc_magic == BLOCKIF_SIG);
879 * Stop the block i/o thread
881 pthread_mutex_lock(&bc->bc_mtx);
883 if (bc->bc_resize_event != NULL)
884 mevent_disable(bc->bc_resize_event);
885 pthread_mutex_unlock(&bc->bc_mtx);
886 pthread_cond_broadcast(&bc->bc_cond);
887 for (i = 0; i < BLOCKIF_NUMTHR; i++)
888 pthread_join(bc->bc_btid[i], &jval);
890 /* XXX Cancel queued i/o's ??? */
903 * Return virtual C/H/S values for a given block. Use the algorithm
904 * outlined in the VHD specification to calculate values.
907 blockif_chs(struct blockif_ctxt *bc, uint16_t *c, uint8_t *h, uint8_t *s)
909 off_t sectors; /* total sectors of the block dev */
910 off_t hcyl; /* cylinders times heads */
911 uint16_t secpt; /* sectors per track */
914 assert(bc->bc_magic == BLOCKIF_SIG);
916 sectors = bc->bc_size / bc->bc_sectsz;
918 /* Clamp the size to the largest possible with CHS */
919 if (sectors > 65535L * 16 * 255)
920 sectors = 65535L * 16 * 255;
922 if (sectors >= 65536L * 16 * 63) {
925 hcyl = sectors / secpt;
928 hcyl = sectors / secpt;
929 heads = (hcyl + 1023) / 1024;
934 if (hcyl >= (heads * 1024) || heads > 16) {
937 hcyl = sectors / secpt;
939 if (hcyl >= (heads * 1024)) {
942 hcyl = sectors / secpt;
955 blockif_size(struct blockif_ctxt *bc)
957 assert(bc->bc_magic == BLOCKIF_SIG);
958 return (bc->bc_size);
962 blockif_sectsz(struct blockif_ctxt *bc)
964 assert(bc->bc_magic == BLOCKIF_SIG);
965 return (bc->bc_sectsz);
969 blockif_psectsz(struct blockif_ctxt *bc, int *size, int *off)
971 assert(bc->bc_magic == BLOCKIF_SIG);
972 *size = bc->bc_psectsz;
973 *off = bc->bc_psectoff;
977 blockif_queuesz(struct blockif_ctxt *bc)
979 assert(bc->bc_magic == BLOCKIF_SIG);
980 return (BLOCKIF_MAXREQ - 1);
984 blockif_is_ro(struct blockif_ctxt *bc)
986 assert(bc->bc_magic == BLOCKIF_SIG);
987 return (bc->bc_rdonly);
991 blockif_candelete(struct blockif_ctxt *bc)
993 assert(bc->bc_magic == BLOCKIF_SIG);
994 return (bc->bc_candelete);
997 #ifdef BHYVE_SNAPSHOT
999 blockif_pause(struct blockif_ctxt *bc)
1002 assert(bc->bc_magic == BLOCKIF_SIG);
1004 pthread_mutex_lock(&bc->bc_mtx);
1007 /* The interface is paused. Wait for workers to finish their work */
1008 while (!blockif_empty(bc))
1009 pthread_cond_wait(&bc->bc_work_done_cond, &bc->bc_mtx);
1010 pthread_mutex_unlock(&bc->bc_mtx);
1012 if (blockif_flush_bc(bc))
1013 fprintf(stderr, "%s: [WARN] failed to flush backing file.\r\n",
1018 blockif_resume(struct blockif_ctxt *bc)
1021 assert(bc->bc_magic == BLOCKIF_SIG);
1023 pthread_mutex_lock(&bc->bc_mtx);
1025 pthread_mutex_unlock(&bc->bc_mtx);
1027 #endif /* BHYVE_SNAPSHOT */