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;
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, enum ev_type type, void *arg)
414 struct blockif_sig_elem *bse;
418 * Process the entire list even if not intended for
422 bse = blockif_bse_head;
425 } while (!atomic_cmpset_ptr((uintptr_t *)&blockif_bse_head,
427 (uintptr_t)bse->bse_next));
429 pthread_mutex_lock(&bse->bse_mtx);
430 bse->bse_pending = 0;
431 pthread_cond_signal(&bse->bse_cond);
432 pthread_mutex_unlock(&bse->bse_mtx);
439 mevent_add(SIGCONT, EVF_SIGNAL, blockif_sigcont_handler, NULL);
440 (void) signal(SIGCONT, SIG_IGN);
444 blockif_legacy_config(nvlist_t *nvl, const char *opts)
451 cp = strchr(opts, ',');
453 set_config_value_node(nvl, "path", opts);
456 path = strndup(opts, cp - opts);
457 set_config_value_node(nvl, "path", path);
459 return (pci_parse_legacy_config(nvl, cp + 1));
462 struct blockif_ctxt *
463 blockif_open(nvlist_t *nvl, const char *ident)
465 char tname[MAXCOMLEN + 1];
466 char name[MAXPATHLEN];
467 const char *path, *pssval, *ssval;
469 struct blockif_ctxt *bc;
471 struct diocgattr_arg arg;
472 off_t size, psectsz, psectoff;
473 int extra, fd, i, sectsz;
474 int ro, candelete, geom, ssopt, pssopt;
477 #ifndef WITHOUT_CAPSICUM
479 cap_ioctl_t cmds[] = { DIOCGFLUSH, DIOCGDELETE, DIOCGMEDIASIZE };
482 pthread_once(&blockif_once, blockif_init);
490 if (get_config_bool_node_default(nvl, "nocache", false))
492 if (get_config_bool_node_default(nvl, "nodelete", false))
494 if (get_config_bool_node_default(nvl, "sync", false) ||
495 get_config_bool_node_default(nvl, "direct", false))
497 if (get_config_bool_node_default(nvl, "ro", false))
499 ssval = get_config_value_node(nvl, "sectorsize");
501 ssopt = strtol(ssval, &cp, 10);
503 EPRINTLN("Invalid sector size \"%s\"", ssval);
508 } else if (*cp == '/') {
510 pssopt = strtol(pssval, &cp, 10);
511 if (cp == pssval || *cp != '\0') {
512 EPRINTLN("Invalid sector size \"%s\"", ssval);
516 EPRINTLN("Invalid sector size \"%s\"", ssval);
521 path = get_config_value_node(nvl, "path");
523 EPRINTLN("Missing \"path\" for block device.");
527 fd = open(path, (ro ? O_RDONLY : O_RDWR) | extra);
529 /* Attempt a r/w fail with a r/o open */
530 fd = open(path, O_RDONLY | extra);
535 warn("Could not open backing file: %s", path);
539 if (fstat(fd, &sbuf) < 0) {
540 warn("Could not stat backing file %s", path);
544 #ifndef WITHOUT_CAPSICUM
545 cap_rights_init(&rights, CAP_FSYNC, CAP_IOCTL, CAP_READ, CAP_SEEK,
546 CAP_WRITE, CAP_FSTAT, CAP_EVENT, CAP_FPATHCONF);
548 cap_rights_clear(&rights, CAP_FSYNC, CAP_WRITE);
550 if (caph_rights_limit(fd, &rights) == -1)
551 errx(EX_OSERR, "Unable to apply rights for sandbox");
555 * Deal with raw devices
559 psectsz = psectoff = 0;
560 candelete = geom = 0;
561 if (S_ISCHR(sbuf.st_mode)) {
562 if (ioctl(fd, DIOCGMEDIASIZE, &size) < 0 ||
563 ioctl(fd, DIOCGSECTORSIZE, §sz)) {
564 perror("Could not fetch dev blk/sector size");
569 if (ioctl(fd, DIOCGSTRIPESIZE, &psectsz) == 0 && psectsz > 0)
570 ioctl(fd, DIOCGSTRIPEOFFSET, &psectoff);
571 strlcpy(arg.name, "GEOM::candelete", sizeof(arg.name));
572 arg.len = sizeof(arg.value.i);
573 if (nodelete == 0 && ioctl(fd, DIOCGATTR, &arg) == 0)
574 candelete = arg.value.i;
575 if (ioctl(fd, DIOCGPROVIDERNAME, name) == 0)
578 psectsz = sbuf.st_blksize;
579 /* Avoid fallback implementation */
580 candelete = fpathconf(fd, _PC_DEALLOC_PRESENT) == 1;
583 #ifndef WITHOUT_CAPSICUM
584 if (caph_ioctls_limit(fd, cmds, nitems(cmds)) == -1)
585 errx(EX_OSERR, "Unable to apply rights for sandbox");
589 if (!powerof2(ssopt) || !powerof2(pssopt) || ssopt < 512 ||
591 EPRINTLN("Invalid sector size %d/%d",
597 * Some backend drivers (e.g. cd0, ada0) require that the I/O
598 * size be a multiple of the device's sector size.
600 * Validate that the emulated sector size complies with this
603 if (S_ISCHR(sbuf.st_mode)) {
604 if (ssopt < sectsz || (ssopt % sectsz) != 0) {
605 EPRINTLN("Sector size %d incompatible "
606 "with underlying device sector size %d",
617 bc = calloc(1, sizeof(struct blockif_ctxt));
623 bc->bc_magic = BLOCKIF_SIG;
625 bc->bc_ischr = S_ISCHR(sbuf.st_mode);
626 bc->bc_isgeom = geom;
627 bc->bc_candelete = candelete;
630 bc->bc_sectsz = sectsz;
631 bc->bc_psectsz = psectsz;
632 bc->bc_psectoff = psectoff;
633 pthread_mutex_init(&bc->bc_mtx, NULL);
634 pthread_cond_init(&bc->bc_cond, NULL);
636 pthread_cond_init(&bc->bc_work_done_cond, NULL);
637 TAILQ_INIT(&bc->bc_freeq);
638 TAILQ_INIT(&bc->bc_pendq);
639 TAILQ_INIT(&bc->bc_busyq);
640 for (i = 0; i < BLOCKIF_MAXREQ; i++) {
641 bc->bc_reqs[i].be_status = BST_FREE;
642 TAILQ_INSERT_HEAD(&bc->bc_freeq, &bc->bc_reqs[i], be_link);
645 for (i = 0; i < BLOCKIF_NUMTHR; i++) {
646 pthread_create(&bc->bc_btid[i], NULL, blockif_thr, bc);
647 snprintf(tname, sizeof(tname), "blk-%s-%d", ident, i);
648 pthread_set_name_np(bc->bc_btid[i], tname);
659 blockif_resized(int fd, enum ev_type type, void *arg)
661 struct blockif_ctxt *bc;
665 if (fstat(fd, &sb) != 0)
668 if (S_ISCHR(sb.st_mode)) {
669 if (ioctl(fd, DIOCGMEDIASIZE, &mediasize) < 0) {
670 EPRINTLN("blockif_resized: get mediasize failed: %s",
675 mediasize = sb.st_size;
678 pthread_mutex_lock(&bc->bc_mtx);
679 if (mediasize != bc->bc_size) {
680 bc->bc_size = mediasize;
681 bc->bc_resize_cb(bc, bc->bc_resize_cb_arg, bc->bc_size);
683 pthread_mutex_unlock(&bc->bc_mtx);
687 blockif_register_resize_callback(struct blockif_ctxt *bc, blockif_resize_cb *cb,
696 pthread_mutex_lock(&bc->bc_mtx);
697 if (bc->bc_resize_cb != NULL) {
702 assert(bc->bc_closing == 0);
704 if (fstat(bc->bc_fd, &sb) != 0) {
709 bc->bc_resize_event = mevent_add_flags(bc->bc_fd, EVF_VNODE,
710 EVFF_ATTRIB, blockif_resized, bc);
711 if (bc->bc_resize_event == NULL) {
716 bc->bc_resize_cb = cb;
717 bc->bc_resize_cb_arg = cb_arg;
719 pthread_mutex_unlock(&bc->bc_mtx);
725 blockif_request(struct blockif_ctxt *bc, struct blockif_req *breq,
732 pthread_mutex_lock(&bc->bc_mtx);
733 assert(!bc->bc_paused);
734 if (!TAILQ_EMPTY(&bc->bc_freeq)) {
736 * Enqueue and inform the block i/o thread
737 * that there is work available
739 if (blockif_enqueue(bc, breq, op))
740 pthread_cond_signal(&bc->bc_cond);
743 * Callers are not allowed to enqueue more than
744 * the specified blockif queue limit. Return an
745 * error to indicate that the queue length has been
750 pthread_mutex_unlock(&bc->bc_mtx);
756 blockif_read(struct blockif_ctxt *bc, struct blockif_req *breq)
758 assert(bc->bc_magic == BLOCKIF_SIG);
759 return (blockif_request(bc, breq, BOP_READ));
763 blockif_write(struct blockif_ctxt *bc, struct blockif_req *breq)
765 assert(bc->bc_magic == BLOCKIF_SIG);
766 return (blockif_request(bc, breq, BOP_WRITE));
770 blockif_flush(struct blockif_ctxt *bc, struct blockif_req *breq)
772 assert(bc->bc_magic == BLOCKIF_SIG);
773 return (blockif_request(bc, breq, BOP_FLUSH));
777 blockif_delete(struct blockif_ctxt *bc, struct blockif_req *breq)
779 assert(bc->bc_magic == BLOCKIF_SIG);
780 return (blockif_request(bc, breq, BOP_DELETE));
784 blockif_cancel(struct blockif_ctxt *bc, struct blockif_req *breq)
786 struct blockif_elem *be;
788 assert(bc->bc_magic == BLOCKIF_SIG);
790 pthread_mutex_lock(&bc->bc_mtx);
791 /* XXX: not waiting while paused */
794 * Check pending requests.
796 TAILQ_FOREACH(be, &bc->bc_pendq, be_link) {
797 if (be->be_req == breq)
804 blockif_complete(bc, be);
805 pthread_mutex_unlock(&bc->bc_mtx);
811 * Check in-flight requests.
813 TAILQ_FOREACH(be, &bc->bc_busyq, be_link) {
814 if (be->be_req == breq)
821 pthread_mutex_unlock(&bc->bc_mtx);
826 * Interrupt the processing thread to force it return
827 * prematurely via it's normal callback path.
829 while (be->be_status == BST_BUSY) {
830 struct blockif_sig_elem bse, *old_head;
832 pthread_mutex_init(&bse.bse_mtx, NULL);
833 pthread_cond_init(&bse.bse_cond, NULL);
838 old_head = blockif_bse_head;
839 bse.bse_next = old_head;
840 } while (!atomic_cmpset_ptr((uintptr_t *)&blockif_bse_head,
844 pthread_kill(be->be_tid, SIGCONT);
846 pthread_mutex_lock(&bse.bse_mtx);
847 while (bse.bse_pending)
848 pthread_cond_wait(&bse.bse_cond, &bse.bse_mtx);
849 pthread_mutex_unlock(&bse.bse_mtx);
852 pthread_mutex_unlock(&bc->bc_mtx);
855 * The processing thread has been interrupted. Since it's not
856 * clear if the callback has been invoked yet, return EBUSY.
862 blockif_close(struct blockif_ctxt *bc)
867 assert(bc->bc_magic == BLOCKIF_SIG);
870 * Stop the block i/o thread
872 pthread_mutex_lock(&bc->bc_mtx);
874 if (bc->bc_resize_event != NULL)
875 mevent_disable(bc->bc_resize_event);
876 pthread_mutex_unlock(&bc->bc_mtx);
877 pthread_cond_broadcast(&bc->bc_cond);
878 for (i = 0; i < BLOCKIF_NUMTHR; i++)
879 pthread_join(bc->bc_btid[i], &jval);
881 /* XXX Cancel queued i/o's ??? */
894 * Return virtual C/H/S values for a given block. Use the algorithm
895 * outlined in the VHD specification to calculate values.
898 blockif_chs(struct blockif_ctxt *bc, uint16_t *c, uint8_t *h, uint8_t *s)
900 off_t sectors; /* total sectors of the block dev */
901 off_t hcyl; /* cylinders times heads */
902 uint16_t secpt; /* sectors per track */
905 assert(bc->bc_magic == BLOCKIF_SIG);
907 sectors = bc->bc_size / bc->bc_sectsz;
909 /* Clamp the size to the largest possible with CHS */
910 if (sectors > 65535UL*16*255)
911 sectors = 65535UL*16*255;
913 if (sectors >= 65536UL*16*63) {
916 hcyl = sectors / secpt;
919 hcyl = sectors / secpt;
920 heads = (hcyl + 1023) / 1024;
925 if (hcyl >= (heads * 1024) || heads > 16) {
928 hcyl = sectors / secpt;
930 if (hcyl >= (heads * 1024)) {
933 hcyl = sectors / secpt;
946 blockif_size(struct blockif_ctxt *bc)
948 assert(bc->bc_magic == BLOCKIF_SIG);
949 return (bc->bc_size);
953 blockif_sectsz(struct blockif_ctxt *bc)
955 assert(bc->bc_magic == BLOCKIF_SIG);
956 return (bc->bc_sectsz);
960 blockif_psectsz(struct blockif_ctxt *bc, int *size, int *off)
962 assert(bc->bc_magic == BLOCKIF_SIG);
963 *size = bc->bc_psectsz;
964 *off = bc->bc_psectoff;
968 blockif_queuesz(struct blockif_ctxt *bc)
970 assert(bc->bc_magic == BLOCKIF_SIG);
971 return (BLOCKIF_MAXREQ - 1);
975 blockif_is_ro(struct blockif_ctxt *bc)
977 assert(bc->bc_magic == BLOCKIF_SIG);
978 return (bc->bc_rdonly);
982 blockif_candelete(struct blockif_ctxt *bc)
984 assert(bc->bc_magic == BLOCKIF_SIG);
985 return (bc->bc_candelete);
988 #ifdef BHYVE_SNAPSHOT
990 blockif_pause(struct blockif_ctxt *bc)
993 assert(bc->bc_magic == BLOCKIF_SIG);
995 pthread_mutex_lock(&bc->bc_mtx);
998 /* The interface is paused. Wait for workers to finish their work */
999 while (!blockif_empty(bc))
1000 pthread_cond_wait(&bc->bc_work_done_cond, &bc->bc_mtx);
1001 pthread_mutex_unlock(&bc->bc_mtx);
1003 if (blockif_flush_bc(bc))
1004 fprintf(stderr, "%s: [WARN] failed to flush backing file.\r\n",
1009 blockif_resume(struct blockif_ctxt *bc)
1012 assert(bc->bc_magic == BLOCKIF_SIG);
1014 pthread_mutex_lock(&bc->bc_mtx);
1016 pthread_mutex_unlock(&bc->bc_mtx);
1018 #endif /* BHYVE_SNAPSHOT */