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>
67 #define BLOCKIF_SIG 0xb109b109
69 #define BLOCKIF_NUMTHR 8
70 #define BLOCKIF_MAXREQ (BLOCKIF_RING_MAX + BLOCKIF_NUMTHR)
88 TAILQ_ENTRY(blockif_elem) be_link;
89 struct blockif_req *be_req;
91 enum blockstat be_status;
108 pthread_t bc_btid[BLOCKIF_NUMTHR];
109 pthread_mutex_t bc_mtx;
110 pthread_cond_t bc_cond;
112 /* Request elements and free/pending/busy queues */
113 TAILQ_HEAD(, blockif_elem) bc_freeq;
114 TAILQ_HEAD(, blockif_elem) bc_pendq;
115 TAILQ_HEAD(, blockif_elem) bc_busyq;
116 struct blockif_elem bc_reqs[BLOCKIF_MAXREQ];
119 static pthread_once_t blockif_once = PTHREAD_ONCE_INIT;
121 struct blockif_sig_elem {
122 pthread_mutex_t bse_mtx;
123 pthread_cond_t bse_cond;
125 struct blockif_sig_elem *bse_next;
128 static struct blockif_sig_elem *blockif_bse_head;
131 blockif_enqueue(struct blockif_ctxt *bc, struct blockif_req *breq,
134 struct blockif_elem *be, *tbe;
138 be = TAILQ_FIRST(&bc->bc_freeq);
140 assert(be->be_status == BST_FREE);
141 TAILQ_REMOVE(&bc->bc_freeq, be, be_link);
148 off = breq->br_offset;
149 for (i = 0; i < breq->br_iovcnt; i++)
150 off += breq->br_iov[i].iov_len;
156 TAILQ_FOREACH(tbe, &bc->bc_pendq, be_link) {
157 if (tbe->be_block == breq->br_offset)
161 TAILQ_FOREACH(tbe, &bc->bc_busyq, be_link) {
162 if (tbe->be_block == breq->br_offset)
167 be->be_status = BST_PEND;
169 be->be_status = BST_BLOCK;
170 TAILQ_INSERT_TAIL(&bc->bc_pendq, be, be_link);
171 return (be->be_status == BST_PEND);
175 blockif_dequeue(struct blockif_ctxt *bc, pthread_t t, struct blockif_elem **bep)
177 struct blockif_elem *be;
179 TAILQ_FOREACH(be, &bc->bc_pendq, be_link) {
180 if (be->be_status == BST_PEND)
182 assert(be->be_status == BST_BLOCK);
186 TAILQ_REMOVE(&bc->bc_pendq, be, be_link);
187 be->be_status = BST_BUSY;
189 TAILQ_INSERT_TAIL(&bc->bc_busyq, be, be_link);
195 blockif_complete(struct blockif_ctxt *bc, struct blockif_elem *be)
197 struct blockif_elem *tbe;
199 if (be->be_status == BST_DONE || be->be_status == BST_BUSY)
200 TAILQ_REMOVE(&bc->bc_busyq, be, be_link);
202 TAILQ_REMOVE(&bc->bc_pendq, be, be_link);
203 TAILQ_FOREACH(tbe, &bc->bc_pendq, be_link) {
204 if (tbe->be_req->br_offset == be->be_block)
205 tbe->be_status = BST_PEND;
208 be->be_status = BST_FREE;
210 TAILQ_INSERT_TAIL(&bc->bc_freeq, be, be_link);
214 blockif_proc(struct blockif_ctxt *bc, struct blockif_elem *be, uint8_t *buf)
216 struct blockif_req *br;
218 ssize_t clen, len, off, boff, voff;
222 if (br->br_iovcnt <= 1)
228 if ((len = preadv(bc->bc_fd, br->br_iov, br->br_iovcnt,
237 while (br->br_resid > 0) {
238 len = MIN(br->br_resid, MAXPHYS);
239 if (pread(bc->bc_fd, buf, len, br->br_offset +
246 clen = MIN(len - boff, br->br_iov[i].iov_len -
248 memcpy(br->br_iov[i].iov_base + voff,
250 if (clen < br->br_iov[i].iov_len - voff)
257 } while (boff < len);
268 if ((len = pwritev(bc->bc_fd, br->br_iov, br->br_iovcnt,
277 while (br->br_resid > 0) {
278 len = MIN(br->br_resid, MAXPHYS);
281 clen = MIN(len - boff, br->br_iov[i].iov_len -
284 br->br_iov[i].iov_base + voff, clen);
285 if (clen < br->br_iov[i].iov_len - voff)
292 } while (boff < len);
293 if (pwrite(bc->bc_fd, buf, len, br->br_offset +
304 if (ioctl(bc->bc_fd, DIOCGFLUSH))
306 } else if (fsync(bc->bc_fd))
310 if (!bc->bc_candelete)
312 else if (bc->bc_rdonly)
314 else if (bc->bc_ischr) {
315 arg[0] = br->br_offset;
316 arg[1] = br->br_resid;
317 if (ioctl(bc->bc_fd, DIOCGDELETE, arg))
329 be->be_status = BST_DONE;
331 (*br->br_callback)(br, err);
335 blockif_thr(void *arg)
337 struct blockif_ctxt *bc;
338 struct blockif_elem *be;
344 buf = malloc(MAXPHYS);
349 pthread_mutex_lock(&bc->bc_mtx);
351 while (blockif_dequeue(bc, t, &be)) {
352 pthread_mutex_unlock(&bc->bc_mtx);
353 blockif_proc(bc, be, buf);
354 pthread_mutex_lock(&bc->bc_mtx);
355 blockif_complete(bc, be);
357 /* Check ctxt status here to see if exit requested */
360 pthread_cond_wait(&bc->bc_cond, &bc->bc_mtx);
362 pthread_mutex_unlock(&bc->bc_mtx);
371 blockif_sigcont_handler(int signal, enum ev_type type, void *arg)
373 struct blockif_sig_elem *bse;
377 * Process the entire list even if not intended for
381 bse = blockif_bse_head;
384 } while (!atomic_cmpset_ptr((uintptr_t *)&blockif_bse_head,
386 (uintptr_t)bse->bse_next));
388 pthread_mutex_lock(&bse->bse_mtx);
389 bse->bse_pending = 0;
390 pthread_cond_signal(&bse->bse_cond);
391 pthread_mutex_unlock(&bse->bse_mtx);
398 mevent_add(SIGCONT, EVF_SIGNAL, blockif_sigcont_handler, NULL);
399 (void) signal(SIGCONT, SIG_IGN);
402 struct blockif_ctxt *
403 blockif_open(const char *optstr, const char *ident)
405 char tname[MAXCOMLEN + 1];
406 char name[MAXPATHLEN];
407 char *nopt, *xopts, *cp;
408 struct blockif_ctxt *bc;
410 struct diocgattr_arg arg;
411 off_t size, psectsz, psectoff;
412 int extra, fd, i, sectsz;
413 int nocache, sync, ro, candelete, geom, ssopt, pssopt;
416 #ifndef WITHOUT_CAPSICUM
418 cap_ioctl_t cmds[] = { DIOCGFLUSH, DIOCGDELETE };
421 pthread_once(&blockif_once, blockif_init);
431 * The first element in the optstring is always a pathname.
432 * Optional elements follow
434 nopt = xopts = strdup(optstr);
435 while (xopts != NULL) {
436 cp = strsep(&xopts, ",");
437 if (cp == nopt) /* file or device pathname */
439 else if (!strcmp(cp, "nocache"))
441 else if (!strcmp(cp, "nodelete"))
443 else if (!strcmp(cp, "sync") || !strcmp(cp, "direct"))
445 else if (!strcmp(cp, "ro"))
447 else if (sscanf(cp, "sectorsize=%d/%d", &ssopt, &pssopt) == 2)
449 else if (sscanf(cp, "sectorsize=%d", &ssopt) == 1)
452 EPRINTLN("Invalid device option \"%s\"", cp);
463 fd = open(nopt, (ro ? O_RDONLY : O_RDWR) | extra);
465 /* Attempt a r/w fail with a r/o open */
466 fd = open(nopt, O_RDONLY | extra);
471 warn("Could not open backing file: %s", nopt);
475 if (fstat(fd, &sbuf) < 0) {
476 warn("Could not stat backing file %s", nopt);
480 #ifndef WITHOUT_CAPSICUM
481 cap_rights_init(&rights, CAP_FSYNC, CAP_IOCTL, CAP_READ, CAP_SEEK,
484 cap_rights_clear(&rights, CAP_FSYNC, CAP_WRITE);
486 if (caph_rights_limit(fd, &rights) == -1)
487 errx(EX_OSERR, "Unable to apply rights for sandbox");
491 * Deal with raw devices
495 psectsz = psectoff = 0;
496 candelete = geom = 0;
497 if (S_ISCHR(sbuf.st_mode)) {
498 if (ioctl(fd, DIOCGMEDIASIZE, &size) < 0 ||
499 ioctl(fd, DIOCGSECTORSIZE, §sz)) {
500 perror("Could not fetch dev blk/sector size");
505 if (ioctl(fd, DIOCGSTRIPESIZE, &psectsz) == 0 && psectsz > 0)
506 ioctl(fd, DIOCGSTRIPEOFFSET, &psectoff);
507 strlcpy(arg.name, "GEOM::candelete", sizeof(arg.name));
508 arg.len = sizeof(arg.value.i);
509 if (nodelete == 0 && ioctl(fd, DIOCGATTR, &arg) == 0)
510 candelete = arg.value.i;
511 if (ioctl(fd, DIOCGPROVIDERNAME, name) == 0)
514 psectsz = sbuf.st_blksize;
516 #ifndef WITHOUT_CAPSICUM
517 if (caph_ioctls_limit(fd, cmds, nitems(cmds)) == -1)
518 errx(EX_OSERR, "Unable to apply rights for sandbox");
522 if (!powerof2(ssopt) || !powerof2(pssopt) || ssopt < 512 ||
524 EPRINTLN("Invalid sector size %d/%d",
530 * Some backend drivers (e.g. cd0, ada0) require that the I/O
531 * size be a multiple of the device's sector size.
533 * Validate that the emulated sector size complies with this
536 if (S_ISCHR(sbuf.st_mode)) {
537 if (ssopt < sectsz || (ssopt % sectsz) != 0) {
538 EPRINTLN("Sector size %d incompatible "
539 "with underlying device sector size %d",
550 bc = calloc(1, sizeof(struct blockif_ctxt));
556 bc->bc_magic = BLOCKIF_SIG;
558 bc->bc_ischr = S_ISCHR(sbuf.st_mode);
559 bc->bc_isgeom = geom;
560 bc->bc_candelete = candelete;
563 bc->bc_sectsz = sectsz;
564 bc->bc_psectsz = psectsz;
565 bc->bc_psectoff = psectoff;
566 pthread_mutex_init(&bc->bc_mtx, NULL);
567 pthread_cond_init(&bc->bc_cond, NULL);
568 TAILQ_INIT(&bc->bc_freeq);
569 TAILQ_INIT(&bc->bc_pendq);
570 TAILQ_INIT(&bc->bc_busyq);
571 for (i = 0; i < BLOCKIF_MAXREQ; i++) {
572 bc->bc_reqs[i].be_status = BST_FREE;
573 TAILQ_INSERT_HEAD(&bc->bc_freeq, &bc->bc_reqs[i], be_link);
576 for (i = 0; i < BLOCKIF_NUMTHR; i++) {
577 pthread_create(&bc->bc_btid[i], NULL, blockif_thr, bc);
578 snprintf(tname, sizeof(tname), "blk-%s-%d", ident, i);
579 pthread_set_name_np(bc->bc_btid[i], tname);
590 blockif_request(struct blockif_ctxt *bc, struct blockif_req *breq,
597 pthread_mutex_lock(&bc->bc_mtx);
598 if (!TAILQ_EMPTY(&bc->bc_freeq)) {
600 * Enqueue and inform the block i/o thread
601 * that there is work available
603 if (blockif_enqueue(bc, breq, op))
604 pthread_cond_signal(&bc->bc_cond);
607 * Callers are not allowed to enqueue more than
608 * the specified blockif queue limit. Return an
609 * error to indicate that the queue length has been
614 pthread_mutex_unlock(&bc->bc_mtx);
620 blockif_read(struct blockif_ctxt *bc, struct blockif_req *breq)
623 assert(bc->bc_magic == BLOCKIF_SIG);
624 return (blockif_request(bc, breq, BOP_READ));
628 blockif_write(struct blockif_ctxt *bc, struct blockif_req *breq)
631 assert(bc->bc_magic == BLOCKIF_SIG);
632 return (blockif_request(bc, breq, BOP_WRITE));
636 blockif_flush(struct blockif_ctxt *bc, struct blockif_req *breq)
639 assert(bc->bc_magic == BLOCKIF_SIG);
640 return (blockif_request(bc, breq, BOP_FLUSH));
644 blockif_delete(struct blockif_ctxt *bc, struct blockif_req *breq)
647 assert(bc->bc_magic == BLOCKIF_SIG);
648 return (blockif_request(bc, breq, BOP_DELETE));
652 blockif_cancel(struct blockif_ctxt *bc, struct blockif_req *breq)
654 struct blockif_elem *be;
656 assert(bc->bc_magic == BLOCKIF_SIG);
658 pthread_mutex_lock(&bc->bc_mtx);
660 * Check pending requests.
662 TAILQ_FOREACH(be, &bc->bc_pendq, be_link) {
663 if (be->be_req == breq)
670 blockif_complete(bc, be);
671 pthread_mutex_unlock(&bc->bc_mtx);
677 * Check in-flight requests.
679 TAILQ_FOREACH(be, &bc->bc_busyq, be_link) {
680 if (be->be_req == breq)
687 pthread_mutex_unlock(&bc->bc_mtx);
692 * Interrupt the processing thread to force it return
693 * prematurely via it's normal callback path.
695 while (be->be_status == BST_BUSY) {
696 struct blockif_sig_elem bse, *old_head;
698 pthread_mutex_init(&bse.bse_mtx, NULL);
699 pthread_cond_init(&bse.bse_cond, NULL);
704 old_head = blockif_bse_head;
705 bse.bse_next = old_head;
706 } while (!atomic_cmpset_ptr((uintptr_t *)&blockif_bse_head,
710 pthread_kill(be->be_tid, SIGCONT);
712 pthread_mutex_lock(&bse.bse_mtx);
713 while (bse.bse_pending)
714 pthread_cond_wait(&bse.bse_cond, &bse.bse_mtx);
715 pthread_mutex_unlock(&bse.bse_mtx);
718 pthread_mutex_unlock(&bc->bc_mtx);
721 * The processing thread has been interrupted. Since it's not
722 * clear if the callback has been invoked yet, return EBUSY.
728 blockif_close(struct blockif_ctxt *bc)
733 assert(bc->bc_magic == BLOCKIF_SIG);
736 * Stop the block i/o thread
738 pthread_mutex_lock(&bc->bc_mtx);
740 pthread_mutex_unlock(&bc->bc_mtx);
741 pthread_cond_broadcast(&bc->bc_cond);
742 for (i = 0; i < BLOCKIF_NUMTHR; i++)
743 pthread_join(bc->bc_btid[i], &jval);
745 /* XXX Cancel queued i/o's ??? */
758 * Return virtual C/H/S values for a given block. Use the algorithm
759 * outlined in the VHD specification to calculate values.
762 blockif_chs(struct blockif_ctxt *bc, uint16_t *c, uint8_t *h, uint8_t *s)
764 off_t sectors; /* total sectors of the block dev */
765 off_t hcyl; /* cylinders times heads */
766 uint16_t secpt; /* sectors per track */
769 assert(bc->bc_magic == BLOCKIF_SIG);
771 sectors = bc->bc_size / bc->bc_sectsz;
773 /* Clamp the size to the largest possible with CHS */
774 if (sectors > 65535UL*16*255)
775 sectors = 65535UL*16*255;
777 if (sectors >= 65536UL*16*63) {
780 hcyl = sectors / secpt;
783 hcyl = sectors / secpt;
784 heads = (hcyl + 1023) / 1024;
789 if (hcyl >= (heads * 1024) || heads > 16) {
792 hcyl = sectors / secpt;
794 if (hcyl >= (heads * 1024)) {
797 hcyl = sectors / secpt;
810 blockif_size(struct blockif_ctxt *bc)
813 assert(bc->bc_magic == BLOCKIF_SIG);
814 return (bc->bc_size);
818 blockif_sectsz(struct blockif_ctxt *bc)
821 assert(bc->bc_magic == BLOCKIF_SIG);
822 return (bc->bc_sectsz);
826 blockif_psectsz(struct blockif_ctxt *bc, int *size, int *off)
829 assert(bc->bc_magic == BLOCKIF_SIG);
830 *size = bc->bc_psectsz;
831 *off = bc->bc_psectoff;
835 blockif_queuesz(struct blockif_ctxt *bc)
838 assert(bc->bc_magic == BLOCKIF_SIG);
839 return (BLOCKIF_MAXREQ - 1);
843 blockif_is_ro(struct blockif_ctxt *bc)
846 assert(bc->bc_magic == BLOCKIF_SIG);
847 return (bc->bc_rdonly);
851 blockif_candelete(struct blockif_ctxt *bc)
854 assert(bc->bc_magic == BLOCKIF_SIG);
855 return (bc->bc_candelete);