2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2013 Peter Grehan <grehan@freebsd.org>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
34 #include <sys/param.h>
35 #ifndef WITHOUT_CAPSICUM
36 #include <sys/capsicum.h>
38 #include <sys/queue.h>
39 #include <sys/errno.h>
41 #include <sys/ioctl.h>
51 #include <pthread_np.h>
56 #include <machine/atomic.h>
62 #define BLOCKIF_SIG 0xb109b109
64 #define BLOCKIF_NUMTHR 8
65 #define BLOCKIF_MAXREQ (64 + BLOCKIF_NUMTHR)
83 TAILQ_ENTRY(blockif_elem) be_link;
84 struct blockif_req *be_req;
86 enum blockstat be_status;
103 pthread_t bc_btid[BLOCKIF_NUMTHR];
104 pthread_mutex_t bc_mtx;
105 pthread_cond_t bc_cond;
107 /* Request elements and free/pending/busy queues */
108 TAILQ_HEAD(, blockif_elem) bc_freeq;
109 TAILQ_HEAD(, blockif_elem) bc_pendq;
110 TAILQ_HEAD(, blockif_elem) bc_busyq;
111 struct blockif_elem bc_reqs[BLOCKIF_MAXREQ];
114 static pthread_once_t blockif_once = PTHREAD_ONCE_INIT;
116 struct blockif_sig_elem {
117 pthread_mutex_t bse_mtx;
118 pthread_cond_t bse_cond;
120 struct blockif_sig_elem *bse_next;
123 static struct blockif_sig_elem *blockif_bse_head;
126 blockif_enqueue(struct blockif_ctxt *bc, struct blockif_req *breq,
129 struct blockif_elem *be, *tbe;
133 be = TAILQ_FIRST(&bc->bc_freeq);
135 assert(be->be_status == BST_FREE);
136 TAILQ_REMOVE(&bc->bc_freeq, be, be_link);
143 off = breq->br_offset;
144 for (i = 0; i < breq->br_iovcnt; i++)
145 off += breq->br_iov[i].iov_len;
151 TAILQ_FOREACH(tbe, &bc->bc_pendq, be_link) {
152 if (tbe->be_block == breq->br_offset)
156 TAILQ_FOREACH(tbe, &bc->bc_busyq, be_link) {
157 if (tbe->be_block == breq->br_offset)
162 be->be_status = BST_PEND;
164 be->be_status = BST_BLOCK;
165 TAILQ_INSERT_TAIL(&bc->bc_pendq, be, be_link);
166 return (be->be_status == BST_PEND);
170 blockif_dequeue(struct blockif_ctxt *bc, pthread_t t, struct blockif_elem **bep)
172 struct blockif_elem *be;
174 TAILQ_FOREACH(be, &bc->bc_pendq, be_link) {
175 if (be->be_status == BST_PEND)
177 assert(be->be_status == BST_BLOCK);
181 TAILQ_REMOVE(&bc->bc_pendq, be, be_link);
182 be->be_status = BST_BUSY;
184 TAILQ_INSERT_TAIL(&bc->bc_busyq, be, be_link);
190 blockif_complete(struct blockif_ctxt *bc, struct blockif_elem *be)
192 struct blockif_elem *tbe;
194 if (be->be_status == BST_DONE || be->be_status == BST_BUSY)
195 TAILQ_REMOVE(&bc->bc_busyq, be, be_link);
197 TAILQ_REMOVE(&bc->bc_pendq, be, be_link);
198 TAILQ_FOREACH(tbe, &bc->bc_pendq, be_link) {
199 if (tbe->be_req->br_offset == be->be_block)
200 tbe->be_status = BST_PEND;
203 be->be_status = BST_FREE;
205 TAILQ_INSERT_TAIL(&bc->bc_freeq, be, be_link);
209 blockif_proc(struct blockif_ctxt *bc, struct blockif_elem *be, uint8_t *buf)
211 struct blockif_req *br;
213 ssize_t clen, len, off, boff, voff;
217 if (br->br_iovcnt <= 1)
223 if ((len = preadv(bc->bc_fd, br->br_iov, br->br_iovcnt,
232 while (br->br_resid > 0) {
233 len = MIN(br->br_resid, MAXPHYS);
234 if (pread(bc->bc_fd, buf, len, br->br_offset +
241 clen = MIN(len - boff, br->br_iov[i].iov_len -
243 memcpy(br->br_iov[i].iov_base + voff,
245 if (clen < br->br_iov[i].iov_len - voff)
252 } while (boff < len);
263 if ((len = pwritev(bc->bc_fd, br->br_iov, br->br_iovcnt,
272 while (br->br_resid > 0) {
273 len = MIN(br->br_resid, MAXPHYS);
276 clen = MIN(len - boff, br->br_iov[i].iov_len -
279 br->br_iov[i].iov_base + voff, clen);
280 if (clen < br->br_iov[i].iov_len - voff)
287 } while (boff < len);
288 if (pwrite(bc->bc_fd, buf, len, br->br_offset +
299 if (ioctl(bc->bc_fd, DIOCGFLUSH))
301 } else if (fsync(bc->bc_fd))
305 if (!bc->bc_candelete)
307 else if (bc->bc_rdonly)
309 else if (bc->bc_ischr) {
310 arg[0] = br->br_offset;
311 arg[1] = br->br_resid;
312 if (ioctl(bc->bc_fd, DIOCGDELETE, arg))
324 be->be_status = BST_DONE;
326 (*br->br_callback)(br, err);
330 blockif_thr(void *arg)
332 struct blockif_ctxt *bc;
333 struct blockif_elem *be;
339 buf = malloc(MAXPHYS);
344 pthread_mutex_lock(&bc->bc_mtx);
346 while (blockif_dequeue(bc, t, &be)) {
347 pthread_mutex_unlock(&bc->bc_mtx);
348 blockif_proc(bc, be, buf);
349 pthread_mutex_lock(&bc->bc_mtx);
350 blockif_complete(bc, be);
352 /* Check ctxt status here to see if exit requested */
355 pthread_cond_wait(&bc->bc_cond, &bc->bc_mtx);
357 pthread_mutex_unlock(&bc->bc_mtx);
366 blockif_sigcont_handler(int signal, enum ev_type type, void *arg)
368 struct blockif_sig_elem *bse;
372 * Process the entire list even if not intended for
376 bse = blockif_bse_head;
379 } while (!atomic_cmpset_ptr((uintptr_t *)&blockif_bse_head,
381 (uintptr_t)bse->bse_next));
383 pthread_mutex_lock(&bse->bse_mtx);
384 bse->bse_pending = 0;
385 pthread_cond_signal(&bse->bse_cond);
386 pthread_mutex_unlock(&bse->bse_mtx);
393 mevent_add(SIGCONT, EVF_SIGNAL, blockif_sigcont_handler, NULL);
394 (void) signal(SIGCONT, SIG_IGN);
397 struct blockif_ctxt *
398 blockif_open(const char *optstr, const char *ident)
400 char tname[MAXCOMLEN + 1];
401 char name[MAXPATHLEN];
402 char *nopt, *xopts, *cp;
403 struct blockif_ctxt *bc;
405 struct diocgattr_arg arg;
406 off_t size, psectsz, psectoff;
407 int extra, fd, i, sectsz;
408 int nocache, sync, ro, candelete, geom, ssopt, pssopt;
409 #ifndef WITHOUT_CAPSICUM
411 cap_ioctl_t cmds[] = { DIOCGFLUSH, DIOCGDELETE };
414 pthread_once(&blockif_once, blockif_init);
423 * The first element in the optstring is always a pathname.
424 * Optional elements follow
426 nopt = xopts = strdup(optstr);
427 while (xopts != NULL) {
428 cp = strsep(&xopts, ",");
429 if (cp == nopt) /* file or device pathname */
431 else if (!strcmp(cp, "nocache"))
433 else if (!strcmp(cp, "sync") || !strcmp(cp, "direct"))
435 else if (!strcmp(cp, "ro"))
437 else if (sscanf(cp, "sectorsize=%d/%d", &ssopt, &pssopt) == 2)
439 else if (sscanf(cp, "sectorsize=%d", &ssopt) == 1)
442 fprintf(stderr, "Invalid device option \"%s\"\n", cp);
453 fd = open(nopt, (ro ? O_RDONLY : O_RDWR) | extra);
455 /* Attempt a r/w fail with a r/o open */
456 fd = open(nopt, O_RDONLY | extra);
461 warn("Could not open backing file: %s", nopt);
465 if (fstat(fd, &sbuf) < 0) {
466 warn("Could not stat backing file %s", nopt);
470 #ifndef WITHOUT_CAPSICUM
471 cap_rights_init(&rights, CAP_FSYNC, CAP_IOCTL, CAP_READ, CAP_SEEK,
474 cap_rights_clear(&rights, CAP_FSYNC, CAP_WRITE);
476 if (cap_rights_limit(fd, &rights) == -1 && errno != ENOSYS)
477 errx(EX_OSERR, "Unable to apply rights for sandbox");
481 * Deal with raw devices
485 psectsz = psectoff = 0;
486 candelete = geom = 0;
487 if (S_ISCHR(sbuf.st_mode)) {
488 if (ioctl(fd, DIOCGMEDIASIZE, &size) < 0 ||
489 ioctl(fd, DIOCGSECTORSIZE, §sz)) {
490 perror("Could not fetch dev blk/sector size");
495 if (ioctl(fd, DIOCGSTRIPESIZE, &psectsz) == 0 && psectsz > 0)
496 ioctl(fd, DIOCGSTRIPEOFFSET, &psectoff);
497 strlcpy(arg.name, "GEOM::candelete", sizeof(arg.name));
498 arg.len = sizeof(arg.value.i);
499 if (ioctl(fd, DIOCGATTR, &arg) == 0)
500 candelete = arg.value.i;
501 if (ioctl(fd, DIOCGPROVIDERNAME, name) == 0)
504 psectsz = sbuf.st_blksize;
506 #ifndef WITHOUT_CAPSICUM
507 if (cap_ioctls_limit(fd, cmds, nitems(cmds)) == -1 && errno != ENOSYS)
508 errx(EX_OSERR, "Unable to apply rights for sandbox");
512 if (!powerof2(ssopt) || !powerof2(pssopt) || ssopt < 512 ||
514 fprintf(stderr, "Invalid sector size %d/%d\n",
520 * Some backend drivers (e.g. cd0, ada0) require that the I/O
521 * size be a multiple of the device's sector size.
523 * Validate that the emulated sector size complies with this
526 if (S_ISCHR(sbuf.st_mode)) {
527 if (ssopt < sectsz || (ssopt % sectsz) != 0) {
528 fprintf(stderr, "Sector size %d incompatible "
529 "with underlying device sector size %d\n",
540 bc = calloc(1, sizeof(struct blockif_ctxt));
546 bc->bc_magic = BLOCKIF_SIG;
548 bc->bc_ischr = S_ISCHR(sbuf.st_mode);
549 bc->bc_isgeom = geom;
550 bc->bc_candelete = candelete;
553 bc->bc_sectsz = sectsz;
554 bc->bc_psectsz = psectsz;
555 bc->bc_psectoff = psectoff;
556 pthread_mutex_init(&bc->bc_mtx, NULL);
557 pthread_cond_init(&bc->bc_cond, NULL);
558 TAILQ_INIT(&bc->bc_freeq);
559 TAILQ_INIT(&bc->bc_pendq);
560 TAILQ_INIT(&bc->bc_busyq);
561 for (i = 0; i < BLOCKIF_MAXREQ; i++) {
562 bc->bc_reqs[i].be_status = BST_FREE;
563 TAILQ_INSERT_HEAD(&bc->bc_freeq, &bc->bc_reqs[i], be_link);
566 for (i = 0; i < BLOCKIF_NUMTHR; i++) {
567 pthread_create(&bc->bc_btid[i], NULL, blockif_thr, bc);
568 snprintf(tname, sizeof(tname), "blk-%s-%d", ident, i);
569 pthread_set_name_np(bc->bc_btid[i], tname);
583 blockif_request(struct blockif_ctxt *bc, struct blockif_req *breq,
590 pthread_mutex_lock(&bc->bc_mtx);
591 if (!TAILQ_EMPTY(&bc->bc_freeq)) {
593 * Enqueue and inform the block i/o thread
594 * that there is work available
596 if (blockif_enqueue(bc, breq, op))
597 pthread_cond_signal(&bc->bc_cond);
600 * Callers are not allowed to enqueue more than
601 * the specified blockif queue limit. Return an
602 * error to indicate that the queue length has been
607 pthread_mutex_unlock(&bc->bc_mtx);
613 blockif_read(struct blockif_ctxt *bc, struct blockif_req *breq)
616 assert(bc->bc_magic == BLOCKIF_SIG);
617 return (blockif_request(bc, breq, BOP_READ));
621 blockif_write(struct blockif_ctxt *bc, struct blockif_req *breq)
624 assert(bc->bc_magic == BLOCKIF_SIG);
625 return (blockif_request(bc, breq, BOP_WRITE));
629 blockif_flush(struct blockif_ctxt *bc, struct blockif_req *breq)
632 assert(bc->bc_magic == BLOCKIF_SIG);
633 return (blockif_request(bc, breq, BOP_FLUSH));
637 blockif_delete(struct blockif_ctxt *bc, struct blockif_req *breq)
640 assert(bc->bc_magic == BLOCKIF_SIG);
641 return (blockif_request(bc, breq, BOP_DELETE));
645 blockif_cancel(struct blockif_ctxt *bc, struct blockif_req *breq)
647 struct blockif_elem *be;
649 assert(bc->bc_magic == BLOCKIF_SIG);
651 pthread_mutex_lock(&bc->bc_mtx);
653 * Check pending requests.
655 TAILQ_FOREACH(be, &bc->bc_pendq, be_link) {
656 if (be->be_req == breq)
663 blockif_complete(bc, be);
664 pthread_mutex_unlock(&bc->bc_mtx);
670 * Check in-flight requests.
672 TAILQ_FOREACH(be, &bc->bc_busyq, be_link) {
673 if (be->be_req == breq)
680 pthread_mutex_unlock(&bc->bc_mtx);
685 * Interrupt the processing thread to force it return
686 * prematurely via it's normal callback path.
688 while (be->be_status == BST_BUSY) {
689 struct blockif_sig_elem bse, *old_head;
691 pthread_mutex_init(&bse.bse_mtx, NULL);
692 pthread_cond_init(&bse.bse_cond, NULL);
697 old_head = blockif_bse_head;
698 bse.bse_next = old_head;
699 } while (!atomic_cmpset_ptr((uintptr_t *)&blockif_bse_head,
703 pthread_kill(be->be_tid, SIGCONT);
705 pthread_mutex_lock(&bse.bse_mtx);
706 while (bse.bse_pending)
707 pthread_cond_wait(&bse.bse_cond, &bse.bse_mtx);
708 pthread_mutex_unlock(&bse.bse_mtx);
711 pthread_mutex_unlock(&bc->bc_mtx);
714 * The processing thread has been interrupted. Since it's not
715 * clear if the callback has been invoked yet, return EBUSY.
721 blockif_close(struct blockif_ctxt *bc)
726 assert(bc->bc_magic == BLOCKIF_SIG);
729 * Stop the block i/o thread
731 pthread_mutex_lock(&bc->bc_mtx);
733 pthread_mutex_unlock(&bc->bc_mtx);
734 pthread_cond_broadcast(&bc->bc_cond);
735 for (i = 0; i < BLOCKIF_NUMTHR; i++)
736 pthread_join(bc->bc_btid[i], &jval);
738 /* XXX Cancel queued i/o's ??? */
751 * Return virtual C/H/S values for a given block. Use the algorithm
752 * outlined in the VHD specification to calculate values.
755 blockif_chs(struct blockif_ctxt *bc, uint16_t *c, uint8_t *h, uint8_t *s)
757 off_t sectors; /* total sectors of the block dev */
758 off_t hcyl; /* cylinders times heads */
759 uint16_t secpt; /* sectors per track */
762 assert(bc->bc_magic == BLOCKIF_SIG);
764 sectors = bc->bc_size / bc->bc_sectsz;
766 /* Clamp the size to the largest possible with CHS */
767 if (sectors > 65535UL*16*255)
768 sectors = 65535UL*16*255;
770 if (sectors >= 65536UL*16*63) {
773 hcyl = sectors / secpt;
776 hcyl = sectors / secpt;
777 heads = (hcyl + 1023) / 1024;
782 if (hcyl >= (heads * 1024) || heads > 16) {
785 hcyl = sectors / secpt;
787 if (hcyl >= (heads * 1024)) {
790 hcyl = sectors / secpt;
803 blockif_size(struct blockif_ctxt *bc)
806 assert(bc->bc_magic == BLOCKIF_SIG);
807 return (bc->bc_size);
811 blockif_sectsz(struct blockif_ctxt *bc)
814 assert(bc->bc_magic == BLOCKIF_SIG);
815 return (bc->bc_sectsz);
819 blockif_psectsz(struct blockif_ctxt *bc, int *size, int *off)
822 assert(bc->bc_magic == BLOCKIF_SIG);
823 *size = bc->bc_psectsz;
824 *off = bc->bc_psectoff;
828 blockif_queuesz(struct blockif_ctxt *bc)
831 assert(bc->bc_magic == BLOCKIF_SIG);
832 return (BLOCKIF_MAXREQ - 1);
836 blockif_is_ro(struct blockif_ctxt *bc)
839 assert(bc->bc_magic == BLOCKIF_SIG);
840 return (bc->bc_rdonly);
844 blockif_candelete(struct blockif_ctxt *bc)
847 assert(bc->bc_magic == BLOCKIF_SIG);
848 return (bc->bc_candelete);