2 * SPDX-License-Identifier: BSD-2-Clause
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];
128 static pthread_once_t blockif_once = PTHREAD_ONCE_INIT;
130 struct blockif_sig_elem {
131 pthread_mutex_t bse_mtx;
132 pthread_cond_t bse_cond;
134 struct blockif_sig_elem *bse_next;
137 static struct blockif_sig_elem *blockif_bse_head;
140 blockif_enqueue(struct blockif_ctxt *bc, struct blockif_req *breq,
143 struct blockif_elem *be, *tbe;
147 be = TAILQ_FIRST(&bc->bc_freeq);
149 assert(be->be_status == BST_FREE);
150 TAILQ_REMOVE(&bc->bc_freeq, be, be_link);
157 off = breq->br_offset;
158 for (i = 0; i < breq->br_iovcnt; i++)
159 off += breq->br_iov[i].iov_len;
165 TAILQ_FOREACH(tbe, &bc->bc_pendq, be_link) {
166 if (tbe->be_block == breq->br_offset)
170 TAILQ_FOREACH(tbe, &bc->bc_busyq, be_link) {
171 if (tbe->be_block == breq->br_offset)
176 be->be_status = BST_PEND;
178 be->be_status = BST_BLOCK;
179 TAILQ_INSERT_TAIL(&bc->bc_pendq, be, be_link);
180 return (be->be_status == BST_PEND);
184 blockif_dequeue(struct blockif_ctxt *bc, pthread_t t, struct blockif_elem **bep)
186 struct blockif_elem *be;
188 TAILQ_FOREACH(be, &bc->bc_pendq, be_link) {
189 if (be->be_status == BST_PEND)
191 assert(be->be_status == BST_BLOCK);
195 TAILQ_REMOVE(&bc->bc_pendq, be, be_link);
196 be->be_status = BST_BUSY;
198 TAILQ_INSERT_TAIL(&bc->bc_busyq, be, be_link);
204 blockif_complete(struct blockif_ctxt *bc, struct blockif_elem *be)
206 struct blockif_elem *tbe;
208 if (be->be_status == BST_DONE || be->be_status == BST_BUSY)
209 TAILQ_REMOVE(&bc->bc_busyq, be, be_link);
211 TAILQ_REMOVE(&bc->bc_pendq, be, be_link);
212 TAILQ_FOREACH(tbe, &bc->bc_pendq, be_link) {
213 if (tbe->be_req->br_offset == be->be_block)
214 tbe->be_status = BST_PEND;
217 be->be_status = BST_FREE;
219 TAILQ_INSERT_TAIL(&bc->bc_freeq, be, be_link);
223 blockif_flush_bc(struct blockif_ctxt *bc)
226 if (ioctl(bc->bc_fd, DIOCGFLUSH))
228 } else if (fsync(bc->bc_fd))
235 blockif_proc(struct blockif_ctxt *bc, struct blockif_elem *be, uint8_t *buf)
237 struct spacectl_range range;
238 struct blockif_req *br;
241 size_t clen, len, off, boff, voff;
245 assert(br->br_resid >= 0);
247 if (br->br_iovcnt <= 1)
253 if ((n = preadv(bc->bc_fd, br->br_iov, br->br_iovcnt,
262 while (br->br_resid > 0) {
263 len = MIN(br->br_resid, MAXPHYS);
264 n = pread(bc->bc_fd, buf, len, br->br_offset + off);
272 clen = MIN(len - boff, br->br_iov[i].iov_len -
274 memcpy((uint8_t *)br->br_iov[i].iov_base + voff,
276 if (clen < br->br_iov[i].iov_len - voff)
283 } while (boff < len);
294 if ((n = pwritev(bc->bc_fd, br->br_iov, br->br_iovcnt,
303 while (br->br_resid > 0) {
304 len = MIN(br->br_resid, MAXPHYS);
307 clen = MIN(len - boff, br->br_iov[i].iov_len -
310 (uint8_t *)br->br_iov[i].iov_base + voff,
312 if (clen < br->br_iov[i].iov_len - voff)
319 } while (boff < len);
321 n = pwrite(bc->bc_fd, buf, len, br->br_offset + off);
331 err = blockif_flush_bc(bc);
334 if (!bc->bc_candelete)
336 else if (bc->bc_rdonly)
338 else if (bc->bc_ischr) {
339 arg[0] = br->br_offset;
340 arg[1] = br->br_resid;
341 if (ioctl(bc->bc_fd, DIOCGDELETE, arg))
346 range.r_offset = br->br_offset;
347 range.r_len = br->br_resid;
349 while (range.r_len > 0) {
350 if (fspacectl(bc->bc_fd, SPACECTL_DEALLOC,
351 &range, 0, &range) != 0) {
365 be->be_status = BST_DONE;
367 (*br->br_callback)(br, err);
371 blockif_empty(const struct blockif_ctxt *bc)
373 return (TAILQ_EMPTY(&bc->bc_pendq) && TAILQ_EMPTY(&bc->bc_busyq));
377 blockif_thr(void *arg)
379 struct blockif_ctxt *bc;
380 struct blockif_elem *be;
386 buf = malloc(MAXPHYS);
391 pthread_mutex_lock(&bc->bc_mtx);
393 while (blockif_dequeue(bc, t, &be)) {
394 pthread_mutex_unlock(&bc->bc_mtx);
395 blockif_proc(bc, be, buf);
396 pthread_mutex_lock(&bc->bc_mtx);
397 blockif_complete(bc, be);
400 /* If none to work, notify the main thread */
401 if (blockif_empty(bc))
402 pthread_cond_broadcast(&bc->bc_work_done_cond);
404 /* Check ctxt status here to see if exit requested */
408 pthread_cond_wait(&bc->bc_cond, &bc->bc_mtx);
410 pthread_mutex_unlock(&bc->bc_mtx);
419 blockif_sigcont_handler(int signal __unused, enum ev_type type __unused,
422 struct blockif_sig_elem *bse;
426 * Process the entire list even if not intended for
430 bse = blockif_bse_head;
433 } while (!atomic_cmpset_ptr((uintptr_t *)&blockif_bse_head,
435 (uintptr_t)bse->bse_next));
437 pthread_mutex_lock(&bse->bse_mtx);
438 bse->bse_pending = 0;
439 pthread_cond_signal(&bse->bse_cond);
440 pthread_mutex_unlock(&bse->bse_mtx);
447 mevent_add(SIGCONT, EVF_SIGNAL, blockif_sigcont_handler, NULL);
448 (void) signal(SIGCONT, SIG_IGN);
452 blockif_legacy_config(nvlist_t *nvl, const char *opts)
459 cp = strchr(opts, ',');
461 set_config_value_node(nvl, "path", opts);
464 path = strndup(opts, cp - opts);
465 set_config_value_node(nvl, "path", path);
467 return (pci_parse_legacy_config(nvl, cp + 1));
471 blockif_add_boot_device(struct pci_devinst *const pi,
472 struct blockif_ctxt *const bc)
474 if (bc->bc_bootindex < 0)
477 return (pci_emul_add_boot_device(pi, bc->bc_bootindex));
480 struct blockif_ctxt *
481 blockif_open(nvlist_t *nvl, const char *ident)
483 char tname[MAXCOMLEN + 1];
484 char name[MAXPATHLEN];
485 const char *path, *pssval, *ssval, *bootindex_val;
487 struct blockif_ctxt *bc;
489 struct diocgattr_arg arg;
490 off_t size, psectsz, psectoff;
491 int extra, fd, i, sectsz;
492 int ro, candelete, geom, ssopt, pssopt;
496 #ifndef WITHOUT_CAPSICUM
498 cap_ioctl_t cmds[] = { DIOCGFLUSH, DIOCGDELETE, DIOCGMEDIASIZE };
501 pthread_once(&blockif_once, blockif_init);
510 if (get_config_bool_node_default(nvl, "nocache", false))
512 if (get_config_bool_node_default(nvl, "nodelete", false))
514 if (get_config_bool_node_default(nvl, "sync", false) ||
515 get_config_bool_node_default(nvl, "direct", false))
517 if (get_config_bool_node_default(nvl, "ro", false))
519 ssval = get_config_value_node(nvl, "sectorsize");
521 ssopt = strtol(ssval, &cp, 10);
523 EPRINTLN("Invalid sector size \"%s\"", ssval);
528 } else if (*cp == '/') {
530 pssopt = strtol(pssval, &cp, 10);
531 if (cp == pssval || *cp != '\0') {
532 EPRINTLN("Invalid sector size \"%s\"", ssval);
536 EPRINTLN("Invalid sector size \"%s\"", ssval);
541 bootindex_val = get_config_value_node(nvl, "bootindex");
542 if (bootindex_val != NULL) {
543 bootindex = atoi(bootindex_val);
546 path = get_config_value_node(nvl, "path");
548 EPRINTLN("Missing \"path\" for block device.");
552 fd = open(path, (ro ? O_RDONLY : O_RDWR) | extra);
554 /* Attempt a r/w fail with a r/o open */
555 fd = open(path, O_RDONLY | extra);
560 warn("Could not open backing file: %s", path);
564 if (fstat(fd, &sbuf) < 0) {
565 warn("Could not stat backing file %s", path);
569 #ifndef WITHOUT_CAPSICUM
570 cap_rights_init(&rights, CAP_FSYNC, CAP_IOCTL, CAP_READ, CAP_SEEK,
571 CAP_WRITE, CAP_FSTAT, CAP_EVENT, CAP_FPATHCONF);
573 cap_rights_clear(&rights, CAP_FSYNC, CAP_WRITE);
575 if (caph_rights_limit(fd, &rights) == -1)
576 errx(EX_OSERR, "Unable to apply rights for sandbox");
580 * Deal with raw devices
584 psectsz = psectoff = 0;
585 candelete = geom = 0;
586 if (S_ISCHR(sbuf.st_mode)) {
587 if (ioctl(fd, DIOCGMEDIASIZE, &size) < 0 ||
588 ioctl(fd, DIOCGSECTORSIZE, §sz)) {
589 perror("Could not fetch dev blk/sector size");
594 if (ioctl(fd, DIOCGSTRIPESIZE, &psectsz) == 0 && psectsz > 0)
595 ioctl(fd, DIOCGSTRIPEOFFSET, &psectoff);
596 strlcpy(arg.name, "GEOM::candelete", sizeof(arg.name));
597 arg.len = sizeof(arg.value.i);
598 if (nodelete == 0 && ioctl(fd, DIOCGATTR, &arg) == 0)
599 candelete = arg.value.i;
600 if (ioctl(fd, DIOCGPROVIDERNAME, name) == 0)
603 psectsz = sbuf.st_blksize;
604 /* Avoid fallback implementation */
605 candelete = fpathconf(fd, _PC_DEALLOC_PRESENT) == 1;
608 #ifndef WITHOUT_CAPSICUM
609 if (caph_ioctls_limit(fd, cmds, nitems(cmds)) == -1)
610 errx(EX_OSERR, "Unable to apply rights for sandbox");
614 if (!powerof2(ssopt) || !powerof2(pssopt) || ssopt < 512 ||
616 EPRINTLN("Invalid sector size %d/%d",
622 * Some backend drivers (e.g. cd0, ada0) require that the I/O
623 * size be a multiple of the device's sector size.
625 * Validate that the emulated sector size complies with this
628 if (S_ISCHR(sbuf.st_mode)) {
629 if (ssopt < sectsz || (ssopt % sectsz) != 0) {
630 EPRINTLN("Sector size %d incompatible "
631 "with underlying device sector size %d",
642 bc = calloc(1, sizeof(struct blockif_ctxt));
648 bc->bc_magic = BLOCKIF_SIG;
650 bc->bc_ischr = S_ISCHR(sbuf.st_mode);
651 bc->bc_isgeom = geom;
652 bc->bc_candelete = candelete;
655 bc->bc_sectsz = sectsz;
656 bc->bc_psectsz = psectsz;
657 bc->bc_psectoff = psectoff;
658 pthread_mutex_init(&bc->bc_mtx, NULL);
659 pthread_cond_init(&bc->bc_cond, NULL);
661 pthread_cond_init(&bc->bc_work_done_cond, NULL);
662 TAILQ_INIT(&bc->bc_freeq);
663 TAILQ_INIT(&bc->bc_pendq);
664 TAILQ_INIT(&bc->bc_busyq);
665 bc->bc_bootindex = bootindex;
666 for (i = 0; i < BLOCKIF_MAXREQ; i++) {
667 bc->bc_reqs[i].be_status = BST_FREE;
668 TAILQ_INSERT_HEAD(&bc->bc_freeq, &bc->bc_reqs[i], be_link);
671 for (i = 0; i < BLOCKIF_NUMTHR; i++) {
672 pthread_create(&bc->bc_btid[i], NULL, blockif_thr, bc);
673 snprintf(tname, sizeof(tname), "blk-%s-%d", ident, i);
674 pthread_set_name_np(bc->bc_btid[i], tname);
685 blockif_resized(int fd, enum ev_type type __unused, void *arg)
687 struct blockif_ctxt *bc;
691 if (fstat(fd, &sb) != 0)
694 if (S_ISCHR(sb.st_mode)) {
695 if (ioctl(fd, DIOCGMEDIASIZE, &mediasize) < 0) {
696 EPRINTLN("blockif_resized: get mediasize failed: %s",
701 mediasize = sb.st_size;
704 pthread_mutex_lock(&bc->bc_mtx);
705 if (mediasize != bc->bc_size) {
706 bc->bc_size = mediasize;
707 bc->bc_resize_cb(bc, bc->bc_resize_cb_arg, bc->bc_size);
709 pthread_mutex_unlock(&bc->bc_mtx);
713 blockif_register_resize_callback(struct blockif_ctxt *bc, blockif_resize_cb *cb,
724 pthread_mutex_lock(&bc->bc_mtx);
725 if (bc->bc_resize_cb != NULL) {
730 assert(bc->bc_closing == 0);
732 if (fstat(bc->bc_fd, &sb) != 0) {
737 bc->bc_resize_event = mevent_add_flags(bc->bc_fd, EVF_VNODE,
738 EVFF_ATTRIB, blockif_resized, bc);
739 if (bc->bc_resize_event == NULL) {
744 bc->bc_resize_cb = cb;
745 bc->bc_resize_cb_arg = cb_arg;
747 pthread_mutex_unlock(&bc->bc_mtx);
753 blockif_request(struct blockif_ctxt *bc, struct blockif_req *breq,
760 pthread_mutex_lock(&bc->bc_mtx);
761 assert(!bc->bc_paused);
762 if (!TAILQ_EMPTY(&bc->bc_freeq)) {
764 * Enqueue and inform the block i/o thread
765 * that there is work available
767 if (blockif_enqueue(bc, breq, op))
768 pthread_cond_signal(&bc->bc_cond);
771 * Callers are not allowed to enqueue more than
772 * the specified blockif queue limit. Return an
773 * error to indicate that the queue length has been
778 pthread_mutex_unlock(&bc->bc_mtx);
784 blockif_read(struct blockif_ctxt *bc, struct blockif_req *breq)
786 assert(bc->bc_magic == BLOCKIF_SIG);
787 return (blockif_request(bc, breq, BOP_READ));
791 blockif_write(struct blockif_ctxt *bc, struct blockif_req *breq)
793 assert(bc->bc_magic == BLOCKIF_SIG);
794 return (blockif_request(bc, breq, BOP_WRITE));
798 blockif_flush(struct blockif_ctxt *bc, struct blockif_req *breq)
800 assert(bc->bc_magic == BLOCKIF_SIG);
801 return (blockif_request(bc, breq, BOP_FLUSH));
805 blockif_delete(struct blockif_ctxt *bc, struct blockif_req *breq)
807 assert(bc->bc_magic == BLOCKIF_SIG);
808 return (blockif_request(bc, breq, BOP_DELETE));
812 blockif_cancel(struct blockif_ctxt *bc, struct blockif_req *breq)
814 struct blockif_elem *be;
816 assert(bc->bc_magic == BLOCKIF_SIG);
818 pthread_mutex_lock(&bc->bc_mtx);
819 /* XXX: not waiting while paused */
822 * Check pending requests.
824 TAILQ_FOREACH(be, &bc->bc_pendq, be_link) {
825 if (be->be_req == breq)
832 blockif_complete(bc, be);
833 pthread_mutex_unlock(&bc->bc_mtx);
839 * Check in-flight requests.
841 TAILQ_FOREACH(be, &bc->bc_busyq, be_link) {
842 if (be->be_req == breq)
849 pthread_mutex_unlock(&bc->bc_mtx);
854 * Interrupt the processing thread to force it return
855 * prematurely via it's normal callback path.
857 while (be->be_status == BST_BUSY) {
858 struct blockif_sig_elem bse, *old_head;
860 pthread_mutex_init(&bse.bse_mtx, NULL);
861 pthread_cond_init(&bse.bse_cond, NULL);
866 old_head = blockif_bse_head;
867 bse.bse_next = old_head;
868 } while (!atomic_cmpset_ptr((uintptr_t *)&blockif_bse_head,
872 pthread_kill(be->be_tid, SIGCONT);
874 pthread_mutex_lock(&bse.bse_mtx);
875 while (bse.bse_pending)
876 pthread_cond_wait(&bse.bse_cond, &bse.bse_mtx);
877 pthread_mutex_unlock(&bse.bse_mtx);
880 pthread_mutex_unlock(&bc->bc_mtx);
883 * The processing thread has been interrupted. Since it's not
884 * clear if the callback has been invoked yet, return EBUSY.
890 blockif_close(struct blockif_ctxt *bc)
895 assert(bc->bc_magic == BLOCKIF_SIG);
898 * Stop the block i/o thread
900 pthread_mutex_lock(&bc->bc_mtx);
902 if (bc->bc_resize_event != NULL)
903 mevent_disable(bc->bc_resize_event);
904 pthread_mutex_unlock(&bc->bc_mtx);
905 pthread_cond_broadcast(&bc->bc_cond);
906 for (i = 0; i < BLOCKIF_NUMTHR; i++)
907 pthread_join(bc->bc_btid[i], &jval);
909 /* XXX Cancel queued i/o's ??? */
922 * Return virtual C/H/S values for a given block. Use the algorithm
923 * outlined in the VHD specification to calculate values.
926 blockif_chs(struct blockif_ctxt *bc, uint16_t *c, uint8_t *h, uint8_t *s)
928 off_t sectors; /* total sectors of the block dev */
929 off_t hcyl; /* cylinders times heads */
930 uint16_t secpt; /* sectors per track */
933 assert(bc->bc_magic == BLOCKIF_SIG);
935 sectors = bc->bc_size / bc->bc_sectsz;
937 /* Clamp the size to the largest possible with CHS */
938 if (sectors > 65535L * 16 * 255)
939 sectors = 65535L * 16 * 255;
941 if (sectors >= 65536L * 16 * 63) {
944 hcyl = sectors / secpt;
947 hcyl = sectors / secpt;
948 heads = (hcyl + 1023) / 1024;
953 if (hcyl >= (heads * 1024) || heads > 16) {
956 hcyl = sectors / secpt;
958 if (hcyl >= (heads * 1024)) {
961 hcyl = sectors / secpt;
974 blockif_size(struct blockif_ctxt *bc)
976 assert(bc->bc_magic == BLOCKIF_SIG);
977 return (bc->bc_size);
981 blockif_sectsz(struct blockif_ctxt *bc)
983 assert(bc->bc_magic == BLOCKIF_SIG);
984 return (bc->bc_sectsz);
988 blockif_psectsz(struct blockif_ctxt *bc, int *size, int *off)
990 assert(bc->bc_magic == BLOCKIF_SIG);
991 *size = bc->bc_psectsz;
992 *off = bc->bc_psectoff;
996 blockif_queuesz(struct blockif_ctxt *bc)
998 assert(bc->bc_magic == BLOCKIF_SIG);
999 return (BLOCKIF_MAXREQ - 1);
1003 blockif_is_ro(struct blockif_ctxt *bc)
1005 assert(bc->bc_magic == BLOCKIF_SIG);
1006 return (bc->bc_rdonly);
1010 blockif_candelete(struct blockif_ctxt *bc)
1012 assert(bc->bc_magic == BLOCKIF_SIG);
1013 return (bc->bc_candelete);
1016 #ifdef BHYVE_SNAPSHOT
1018 blockif_pause(struct blockif_ctxt *bc)
1021 assert(bc->bc_magic == BLOCKIF_SIG);
1023 pthread_mutex_lock(&bc->bc_mtx);
1026 /* The interface is paused. Wait for workers to finish their work */
1027 while (!blockif_empty(bc))
1028 pthread_cond_wait(&bc->bc_work_done_cond, &bc->bc_mtx);
1029 pthread_mutex_unlock(&bc->bc_mtx);
1031 if (!bc->bc_rdonly && blockif_flush_bc(bc))
1032 fprintf(stderr, "%s: [WARN] failed to flush backing file.\r\n",
1037 blockif_resume(struct blockif_ctxt *bc)
1040 assert(bc->bc_magic == BLOCKIF_SIG);
1042 pthread_mutex_lock(&bc->bc_mtx);
1044 pthread_mutex_unlock(&bc->bc_mtx);
1046 #endif /* BHYVE_SNAPSHOT */