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
30 #include <sys/param.h>
31 #ifndef WITHOUT_CAPSICUM
32 #include <sys/capsicum.h>
34 #include <sys/queue.h>
35 #include <sys/errno.h>
37 #include <sys/ioctl.h>
41 #ifndef WITHOUT_CAPSICUM
42 #include <capsicum_helpers.h>
50 #include <pthread_np.h>
55 #include <machine/atomic.h>
56 #include <machine/vmm_snapshot.h>
65 #define BLOCKIF_SIG 0xb109b109
67 #define BLOCKIF_NUMTHR 8
68 #define BLOCKIF_MAXREQ (BLOCKIF_RING_MAX + BLOCKIF_NUMTHR)
86 TAILQ_ENTRY(blockif_elem) be_link;
87 struct blockif_req *be_req;
89 enum blockstat be_status;
95 unsigned int bc_magic;
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;
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];
123 static pthread_once_t blockif_once = PTHREAD_ONCE_INIT;
125 struct blockif_sig_elem {
126 pthread_mutex_t bse_mtx;
127 pthread_cond_t bse_cond;
129 struct blockif_sig_elem *bse_next;
132 static struct blockif_sig_elem *blockif_bse_head;
135 blockif_enqueue(struct blockif_ctxt *bc, struct blockif_req *breq,
138 struct blockif_elem *be, *tbe;
142 be = TAILQ_FIRST(&bc->bc_freeq);
144 assert(be->be_status == BST_FREE);
145 TAILQ_REMOVE(&bc->bc_freeq, be, be_link);
152 off = breq->br_offset;
153 for (i = 0; i < breq->br_iovcnt; i++)
154 off += breq->br_iov[i].iov_len;
160 TAILQ_FOREACH(tbe, &bc->bc_pendq, be_link) {
161 if (tbe->be_block == breq->br_offset)
165 TAILQ_FOREACH(tbe, &bc->bc_busyq, be_link) {
166 if (tbe->be_block == breq->br_offset)
171 be->be_status = BST_PEND;
173 be->be_status = BST_BLOCK;
174 TAILQ_INSERT_TAIL(&bc->bc_pendq, be, be_link);
175 return (be->be_status == BST_PEND);
179 blockif_dequeue(struct blockif_ctxt *bc, pthread_t t, struct blockif_elem **bep)
181 struct blockif_elem *be;
183 TAILQ_FOREACH(be, &bc->bc_pendq, be_link) {
184 if (be->be_status == BST_PEND)
186 assert(be->be_status == BST_BLOCK);
190 TAILQ_REMOVE(&bc->bc_pendq, be, be_link);
191 be->be_status = BST_BUSY;
193 TAILQ_INSERT_TAIL(&bc->bc_busyq, be, be_link);
199 blockif_complete(struct blockif_ctxt *bc, struct blockif_elem *be)
201 struct blockif_elem *tbe;
203 if (be->be_status == BST_DONE || be->be_status == BST_BUSY)
204 TAILQ_REMOVE(&bc->bc_busyq, be, be_link);
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;
212 be->be_status = BST_FREE;
214 TAILQ_INSERT_TAIL(&bc->bc_freeq, be, be_link);
218 blockif_flush_bc(struct blockif_ctxt *bc)
221 if (ioctl(bc->bc_fd, DIOCGFLUSH))
223 } else if (fsync(bc->bc_fd))
230 blockif_proc(struct blockif_ctxt *bc, struct blockif_elem *be, uint8_t *buf)
232 struct spacectl_range range;
233 struct blockif_req *br;
236 size_t clen, len, off, boff, voff;
240 assert(br->br_resid >= 0);
242 if (br->br_iovcnt <= 1)
248 if ((n = preadv(bc->bc_fd, br->br_iov, br->br_iovcnt,
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);
267 clen = MIN(len - boff, br->br_iov[i].iov_len -
269 memcpy((uint8_t *)br->br_iov[i].iov_base + voff,
271 if (clen < br->br_iov[i].iov_len - voff)
278 } while (boff < len);
289 if ((n = 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 (uint8_t *)br->br_iov[i].iov_base + voff,
307 if (clen < br->br_iov[i].iov_len - voff)
314 } while (boff < len);
316 n = pwrite(bc->bc_fd, buf, len, br->br_offset + off);
326 err = blockif_flush_bc(bc);
329 if (!bc->bc_candelete)
331 else if (bc->bc_rdonly)
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))
341 range.r_offset = br->br_offset;
342 range.r_len = br->br_resid;
344 while (range.r_len > 0) {
345 if (fspacectl(bc->bc_fd, SPACECTL_DEALLOC,
346 &range, 0, &range) != 0) {
360 be->be_status = BST_DONE;
362 (*br->br_callback)(br, err);
366 blockif_empty(const struct blockif_ctxt *bc)
368 return (TAILQ_EMPTY(&bc->bc_pendq) && TAILQ_EMPTY(&bc->bc_busyq));
372 blockif_thr(void *arg)
374 struct blockif_ctxt *bc;
375 struct blockif_elem *be;
381 buf = malloc(MAXPHYS);
386 pthread_mutex_lock(&bc->bc_mtx);
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);
395 /* If none to work, notify the main thread */
396 if (blockif_empty(bc))
397 pthread_cond_broadcast(&bc->bc_work_done_cond);
399 /* Check ctxt status here to see if exit requested */
403 pthread_cond_wait(&bc->bc_cond, &bc->bc_mtx);
405 pthread_mutex_unlock(&bc->bc_mtx);
414 blockif_sigcont_handler(int signal __unused, enum ev_type type __unused,
417 struct blockif_sig_elem *bse;
421 * Process the entire list even if not intended for
425 bse = blockif_bse_head;
428 } while (!atomic_cmpset_ptr((uintptr_t *)&blockif_bse_head,
430 (uintptr_t)bse->bse_next));
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);
442 mevent_add(SIGCONT, EVF_SIGNAL, blockif_sigcont_handler, NULL);
443 (void) signal(SIGCONT, SIG_IGN);
447 blockif_legacy_config(nvlist_t *nvl, const char *opts)
454 cp = strchr(opts, ',');
456 set_config_value_node(nvl, "path", opts);
459 path = strndup(opts, cp - opts);
460 set_config_value_node(nvl, "path", path);
462 return (pci_parse_legacy_config(nvl, cp + 1));
466 blockif_add_boot_device(struct pci_devinst *const pi,
467 struct blockif_ctxt *const bc)
469 if (bc->bc_bootindex < 0)
472 return (pci_emul_add_boot_device(pi, bc->bc_bootindex));
475 struct blockif_ctxt *
476 blockif_open(nvlist_t *nvl, const char *ident)
478 char tname[MAXCOMLEN + 1];
479 char name[MAXPATHLEN];
480 const char *path, *pssval, *ssval, *bootindex_val;
482 struct blockif_ctxt *bc;
484 struct diocgattr_arg arg;
485 off_t size, psectsz, psectoff;
486 int extra, fd, i, sectsz;
487 int ro, candelete, geom, ssopt, pssopt;
491 #ifndef WITHOUT_CAPSICUM
493 cap_ioctl_t cmds[] = { DIOCGFLUSH, DIOCGDELETE, DIOCGMEDIASIZE };
496 pthread_once(&blockif_once, blockif_init);
505 if (get_config_bool_node_default(nvl, "nocache", false))
507 if (get_config_bool_node_default(nvl, "nodelete", false))
509 if (get_config_bool_node_default(nvl, "sync", false) ||
510 get_config_bool_node_default(nvl, "direct", false))
512 if (get_config_bool_node_default(nvl, "ro", false))
514 ssval = get_config_value_node(nvl, "sectorsize");
516 ssopt = strtol(ssval, &cp, 10);
518 EPRINTLN("Invalid sector size \"%s\"", ssval);
523 } else if (*cp == '/') {
525 pssopt = strtol(pssval, &cp, 10);
526 if (cp == pssval || *cp != '\0') {
527 EPRINTLN("Invalid sector size \"%s\"", ssval);
531 EPRINTLN("Invalid sector size \"%s\"", ssval);
536 bootindex_val = get_config_value_node(nvl, "bootindex");
537 if (bootindex_val != NULL) {
538 bootindex = atoi(bootindex_val);
541 path = get_config_value_node(nvl, "path");
543 EPRINTLN("Missing \"path\" for block device.");
547 fd = open(path, (ro ? O_RDONLY : O_RDWR) | extra);
549 /* Attempt a r/w fail with a r/o open */
550 fd = open(path, O_RDONLY | extra);
555 warn("Could not open backing file: %s", path);
559 if (fstat(fd, &sbuf) < 0) {
560 warn("Could not stat backing file %s", path);
564 #ifndef WITHOUT_CAPSICUM
565 cap_rights_init(&rights, CAP_FSYNC, CAP_IOCTL, CAP_READ, CAP_SEEK,
566 CAP_WRITE, CAP_FSTAT, CAP_EVENT, CAP_FPATHCONF);
568 cap_rights_clear(&rights, CAP_FSYNC, CAP_WRITE);
570 if (caph_rights_limit(fd, &rights) == -1)
571 errx(EX_OSERR, "Unable to apply rights for sandbox");
575 * Deal with raw devices
579 psectsz = psectoff = 0;
580 candelete = geom = 0;
581 if (S_ISCHR(sbuf.st_mode)) {
582 if (ioctl(fd, DIOCGMEDIASIZE, &size) < 0 ||
583 ioctl(fd, DIOCGSECTORSIZE, §sz)) {
584 perror("Could not fetch dev blk/sector size");
589 if (ioctl(fd, DIOCGSTRIPESIZE, &psectsz) == 0 && psectsz > 0)
590 ioctl(fd, DIOCGSTRIPEOFFSET, &psectoff);
591 strlcpy(arg.name, "GEOM::candelete", sizeof(arg.name));
592 arg.len = sizeof(arg.value.i);
593 if (nodelete == 0 && ioctl(fd, DIOCGATTR, &arg) == 0)
594 candelete = arg.value.i;
595 if (ioctl(fd, DIOCGPROVIDERNAME, name) == 0)
598 psectsz = sbuf.st_blksize;
599 /* Avoid fallback implementation */
600 candelete = fpathconf(fd, _PC_DEALLOC_PRESENT) == 1;
603 #ifndef WITHOUT_CAPSICUM
604 if (caph_ioctls_limit(fd, cmds, nitems(cmds)) == -1)
605 errx(EX_OSERR, "Unable to apply rights for sandbox");
609 if (!powerof2(ssopt) || !powerof2(pssopt) || ssopt < 512 ||
611 EPRINTLN("Invalid sector size %d/%d",
617 * Some backend drivers (e.g. cd0, ada0) require that the I/O
618 * size be a multiple of the device's sector size.
620 * Validate that the emulated sector size complies with this
623 if (S_ISCHR(sbuf.st_mode)) {
624 if (ssopt < sectsz || (ssopt % sectsz) != 0) {
625 EPRINTLN("Sector size %d incompatible "
626 "with underlying device sector size %d",
637 bc = calloc(1, sizeof(struct blockif_ctxt));
643 bc->bc_magic = BLOCKIF_SIG;
645 bc->bc_ischr = S_ISCHR(sbuf.st_mode);
646 bc->bc_isgeom = geom;
647 bc->bc_candelete = candelete;
650 bc->bc_sectsz = sectsz;
651 bc->bc_psectsz = psectsz;
652 bc->bc_psectoff = psectoff;
653 pthread_mutex_init(&bc->bc_mtx, NULL);
654 pthread_cond_init(&bc->bc_cond, NULL);
656 pthread_cond_init(&bc->bc_work_done_cond, NULL);
657 TAILQ_INIT(&bc->bc_freeq);
658 TAILQ_INIT(&bc->bc_pendq);
659 TAILQ_INIT(&bc->bc_busyq);
660 bc->bc_bootindex = bootindex;
661 for (i = 0; i < BLOCKIF_MAXREQ; i++) {
662 bc->bc_reqs[i].be_status = BST_FREE;
663 TAILQ_INSERT_HEAD(&bc->bc_freeq, &bc->bc_reqs[i], be_link);
666 for (i = 0; i < BLOCKIF_NUMTHR; i++) {
667 pthread_create(&bc->bc_btid[i], NULL, blockif_thr, bc);
668 snprintf(tname, sizeof(tname), "blk-%s-%d", ident, i);
669 pthread_set_name_np(bc->bc_btid[i], tname);
680 blockif_resized(int fd, enum ev_type type __unused, void *arg)
682 struct blockif_ctxt *bc;
686 if (fstat(fd, &sb) != 0)
689 if (S_ISCHR(sb.st_mode)) {
690 if (ioctl(fd, DIOCGMEDIASIZE, &mediasize) < 0) {
691 EPRINTLN("blockif_resized: get mediasize failed: %s",
696 mediasize = sb.st_size;
699 pthread_mutex_lock(&bc->bc_mtx);
700 if (mediasize != bc->bc_size) {
701 bc->bc_size = mediasize;
702 bc->bc_resize_cb(bc, bc->bc_resize_cb_arg, bc->bc_size);
704 pthread_mutex_unlock(&bc->bc_mtx);
708 blockif_register_resize_callback(struct blockif_ctxt *bc, blockif_resize_cb *cb,
719 pthread_mutex_lock(&bc->bc_mtx);
720 if (bc->bc_resize_cb != NULL) {
725 assert(bc->bc_closing == 0);
727 if (fstat(bc->bc_fd, &sb) != 0) {
732 bc->bc_resize_event = mevent_add_flags(bc->bc_fd, EVF_VNODE,
733 EVFF_ATTRIB, blockif_resized, bc);
734 if (bc->bc_resize_event == NULL) {
739 bc->bc_resize_cb = cb;
740 bc->bc_resize_cb_arg = cb_arg;
742 pthread_mutex_unlock(&bc->bc_mtx);
748 blockif_request(struct blockif_ctxt *bc, struct blockif_req *breq,
755 pthread_mutex_lock(&bc->bc_mtx);
756 assert(!bc->bc_paused);
757 if (!TAILQ_EMPTY(&bc->bc_freeq)) {
759 * Enqueue and inform the block i/o thread
760 * that there is work available
762 if (blockif_enqueue(bc, breq, op))
763 pthread_cond_signal(&bc->bc_cond);
766 * Callers are not allowed to enqueue more than
767 * the specified blockif queue limit. Return an
768 * error to indicate that the queue length has been
773 pthread_mutex_unlock(&bc->bc_mtx);
779 blockif_read(struct blockif_ctxt *bc, struct blockif_req *breq)
781 assert(bc->bc_magic == BLOCKIF_SIG);
782 return (blockif_request(bc, breq, BOP_READ));
786 blockif_write(struct blockif_ctxt *bc, struct blockif_req *breq)
788 assert(bc->bc_magic == BLOCKIF_SIG);
789 return (blockif_request(bc, breq, BOP_WRITE));
793 blockif_flush(struct blockif_ctxt *bc, struct blockif_req *breq)
795 assert(bc->bc_magic == BLOCKIF_SIG);
796 return (blockif_request(bc, breq, BOP_FLUSH));
800 blockif_delete(struct blockif_ctxt *bc, struct blockif_req *breq)
802 assert(bc->bc_magic == BLOCKIF_SIG);
803 return (blockif_request(bc, breq, BOP_DELETE));
807 blockif_cancel(struct blockif_ctxt *bc, struct blockif_req *breq)
809 struct blockif_elem *be;
811 assert(bc->bc_magic == BLOCKIF_SIG);
813 pthread_mutex_lock(&bc->bc_mtx);
814 /* XXX: not waiting while paused */
817 * Check pending requests.
819 TAILQ_FOREACH(be, &bc->bc_pendq, be_link) {
820 if (be->be_req == breq)
827 blockif_complete(bc, be);
828 pthread_mutex_unlock(&bc->bc_mtx);
834 * Check in-flight requests.
836 TAILQ_FOREACH(be, &bc->bc_busyq, be_link) {
837 if (be->be_req == breq)
844 pthread_mutex_unlock(&bc->bc_mtx);
849 * Interrupt the processing thread to force it return
850 * prematurely via it's normal callback path.
852 while (be->be_status == BST_BUSY) {
853 struct blockif_sig_elem bse, *old_head;
855 pthread_mutex_init(&bse.bse_mtx, NULL);
856 pthread_cond_init(&bse.bse_cond, NULL);
861 old_head = blockif_bse_head;
862 bse.bse_next = old_head;
863 } while (!atomic_cmpset_ptr((uintptr_t *)&blockif_bse_head,
867 pthread_kill(be->be_tid, SIGCONT);
869 pthread_mutex_lock(&bse.bse_mtx);
870 while (bse.bse_pending)
871 pthread_cond_wait(&bse.bse_cond, &bse.bse_mtx);
872 pthread_mutex_unlock(&bse.bse_mtx);
875 pthread_mutex_unlock(&bc->bc_mtx);
878 * The processing thread has been interrupted. Since it's not
879 * clear if the callback has been invoked yet, return EBUSY.
885 blockif_close(struct blockif_ctxt *bc)
890 assert(bc->bc_magic == BLOCKIF_SIG);
893 * Stop the block i/o thread
895 pthread_mutex_lock(&bc->bc_mtx);
897 if (bc->bc_resize_event != NULL)
898 mevent_disable(bc->bc_resize_event);
899 pthread_mutex_unlock(&bc->bc_mtx);
900 pthread_cond_broadcast(&bc->bc_cond);
901 for (i = 0; i < BLOCKIF_NUMTHR; i++)
902 pthread_join(bc->bc_btid[i], &jval);
904 /* XXX Cancel queued i/o's ??? */
917 * Return virtual C/H/S values for a given block. Use the algorithm
918 * outlined in the VHD specification to calculate values.
921 blockif_chs(struct blockif_ctxt *bc, uint16_t *c, uint8_t *h, uint8_t *s)
923 off_t sectors; /* total sectors of the block dev */
924 off_t hcyl; /* cylinders times heads */
925 uint16_t secpt; /* sectors per track */
928 assert(bc->bc_magic == BLOCKIF_SIG);
930 sectors = bc->bc_size / bc->bc_sectsz;
932 /* Clamp the size to the largest possible with CHS */
933 if (sectors > 65535L * 16 * 255)
934 sectors = 65535L * 16 * 255;
936 if (sectors >= 65536L * 16 * 63) {
939 hcyl = sectors / secpt;
942 hcyl = sectors / secpt;
943 heads = (hcyl + 1023) / 1024;
948 if (hcyl >= (heads * 1024) || heads > 16) {
951 hcyl = sectors / secpt;
953 if (hcyl >= (heads * 1024)) {
956 hcyl = sectors / secpt;
969 blockif_size(struct blockif_ctxt *bc)
971 assert(bc->bc_magic == BLOCKIF_SIG);
972 return (bc->bc_size);
976 blockif_sectsz(struct blockif_ctxt *bc)
978 assert(bc->bc_magic == BLOCKIF_SIG);
979 return (bc->bc_sectsz);
983 blockif_psectsz(struct blockif_ctxt *bc, int *size, int *off)
985 assert(bc->bc_magic == BLOCKIF_SIG);
986 *size = bc->bc_psectsz;
987 *off = bc->bc_psectoff;
991 blockif_queuesz(struct blockif_ctxt *bc)
993 assert(bc->bc_magic == BLOCKIF_SIG);
994 return (BLOCKIF_MAXREQ - 1);
998 blockif_is_ro(struct blockif_ctxt *bc)
1000 assert(bc->bc_magic == BLOCKIF_SIG);
1001 return (bc->bc_rdonly);
1005 blockif_candelete(struct blockif_ctxt *bc)
1007 assert(bc->bc_magic == BLOCKIF_SIG);
1008 return (bc->bc_candelete);
1011 #ifdef BHYVE_SNAPSHOT
1013 blockif_pause(struct blockif_ctxt *bc)
1016 assert(bc->bc_magic == BLOCKIF_SIG);
1018 pthread_mutex_lock(&bc->bc_mtx);
1021 /* The interface is paused. Wait for workers to finish their work */
1022 while (!blockif_empty(bc))
1023 pthread_cond_wait(&bc->bc_work_done_cond, &bc->bc_mtx);
1024 pthread_mutex_unlock(&bc->bc_mtx);
1026 if (!bc->bc_rdonly && blockif_flush_bc(bc))
1027 EPRINTLN("%s: [WARN] failed to flush backing file.",
1032 blockif_resume(struct blockif_ctxt *bc)
1035 assert(bc->bc_magic == BLOCKIF_SIG);
1037 pthread_mutex_lock(&bc->bc_mtx);
1039 pthread_mutex_unlock(&bc->bc_mtx);
1041 #endif /* BHYVE_SNAPSHOT */