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>
45 #ifndef WITHOUT_CAPSICUM
46 #include <capsicum_helpers.h>
54 #include <pthread_np.h>
59 #include <machine/atomic.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;
106 pthread_t bc_btid[BLOCKIF_NUMTHR];
107 pthread_mutex_t bc_mtx;
108 pthread_cond_t bc_cond;
110 /* Request elements and free/pending/busy queues */
111 TAILQ_HEAD(, blockif_elem) bc_freeq;
112 TAILQ_HEAD(, blockif_elem) bc_pendq;
113 TAILQ_HEAD(, blockif_elem) bc_busyq;
114 struct blockif_elem bc_reqs[BLOCKIF_MAXREQ];
117 static pthread_once_t blockif_once = PTHREAD_ONCE_INIT;
119 struct blockif_sig_elem {
120 pthread_mutex_t bse_mtx;
121 pthread_cond_t bse_cond;
123 struct blockif_sig_elem *bse_next;
126 static struct blockif_sig_elem *blockif_bse_head;
129 blockif_enqueue(struct blockif_ctxt *bc, struct blockif_req *breq,
132 struct blockif_elem *be, *tbe;
136 be = TAILQ_FIRST(&bc->bc_freeq);
138 assert(be->be_status == BST_FREE);
139 TAILQ_REMOVE(&bc->bc_freeq, be, be_link);
146 off = breq->br_offset;
147 for (i = 0; i < breq->br_iovcnt; i++)
148 off += breq->br_iov[i].iov_len;
154 TAILQ_FOREACH(tbe, &bc->bc_pendq, be_link) {
155 if (tbe->be_block == breq->br_offset)
159 TAILQ_FOREACH(tbe, &bc->bc_busyq, be_link) {
160 if (tbe->be_block == breq->br_offset)
165 be->be_status = BST_PEND;
167 be->be_status = BST_BLOCK;
168 TAILQ_INSERT_TAIL(&bc->bc_pendq, be, be_link);
169 return (be->be_status == BST_PEND);
173 blockif_dequeue(struct blockif_ctxt *bc, pthread_t t, struct blockif_elem **bep)
175 struct blockif_elem *be;
177 TAILQ_FOREACH(be, &bc->bc_pendq, be_link) {
178 if (be->be_status == BST_PEND)
180 assert(be->be_status == BST_BLOCK);
184 TAILQ_REMOVE(&bc->bc_pendq, be, be_link);
185 be->be_status = BST_BUSY;
187 TAILQ_INSERT_TAIL(&bc->bc_busyq, be, be_link);
193 blockif_complete(struct blockif_ctxt *bc, struct blockif_elem *be)
195 struct blockif_elem *tbe;
197 if (be->be_status == BST_DONE || be->be_status == BST_BUSY)
198 TAILQ_REMOVE(&bc->bc_busyq, be, be_link);
200 TAILQ_REMOVE(&bc->bc_pendq, be, be_link);
201 TAILQ_FOREACH(tbe, &bc->bc_pendq, be_link) {
202 if (tbe->be_req->br_offset == be->be_block)
203 tbe->be_status = BST_PEND;
206 be->be_status = BST_FREE;
208 TAILQ_INSERT_TAIL(&bc->bc_freeq, be, be_link);
212 blockif_proc(struct blockif_ctxt *bc, struct blockif_elem *be, uint8_t *buf)
214 struct blockif_req *br;
216 ssize_t clen, len, off, boff, voff;
220 if (br->br_iovcnt <= 1)
226 if ((len = preadv(bc->bc_fd, br->br_iov, br->br_iovcnt,
235 while (br->br_resid > 0) {
236 len = MIN(br->br_resid, MAXPHYS);
237 if (pread(bc->bc_fd, buf, len, br->br_offset +
244 clen = MIN(len - boff, br->br_iov[i].iov_len -
246 memcpy(br->br_iov[i].iov_base + voff,
248 if (clen < br->br_iov[i].iov_len - voff)
255 } while (boff < len);
266 if ((len = pwritev(bc->bc_fd, br->br_iov, br->br_iovcnt,
275 while (br->br_resid > 0) {
276 len = MIN(br->br_resid, MAXPHYS);
279 clen = MIN(len - boff, br->br_iov[i].iov_len -
282 br->br_iov[i].iov_base + voff, clen);
283 if (clen < br->br_iov[i].iov_len - voff)
290 } while (boff < len);
291 if (pwrite(bc->bc_fd, buf, len, br->br_offset +
302 if (ioctl(bc->bc_fd, DIOCGFLUSH))
304 } else if (fsync(bc->bc_fd))
308 if (!bc->bc_candelete)
310 else if (bc->bc_rdonly)
312 else if (bc->bc_ischr) {
313 arg[0] = br->br_offset;
314 arg[1] = br->br_resid;
315 if (ioctl(bc->bc_fd, DIOCGDELETE, arg))
327 be->be_status = BST_DONE;
329 (*br->br_callback)(br, err);
333 blockif_thr(void *arg)
335 struct blockif_ctxt *bc;
336 struct blockif_elem *be;
342 buf = malloc(MAXPHYS);
347 pthread_mutex_lock(&bc->bc_mtx);
349 while (blockif_dequeue(bc, t, &be)) {
350 pthread_mutex_unlock(&bc->bc_mtx);
351 blockif_proc(bc, be, buf);
352 pthread_mutex_lock(&bc->bc_mtx);
353 blockif_complete(bc, be);
355 /* Check ctxt status here to see if exit requested */
358 pthread_cond_wait(&bc->bc_cond, &bc->bc_mtx);
360 pthread_mutex_unlock(&bc->bc_mtx);
369 blockif_sigcont_handler(int signal, enum ev_type type, void *arg)
371 struct blockif_sig_elem *bse;
375 * Process the entire list even if not intended for
379 bse = blockif_bse_head;
382 } while (!atomic_cmpset_ptr((uintptr_t *)&blockif_bse_head,
384 (uintptr_t)bse->bse_next));
386 pthread_mutex_lock(&bse->bse_mtx);
387 bse->bse_pending = 0;
388 pthread_cond_signal(&bse->bse_cond);
389 pthread_mutex_unlock(&bse->bse_mtx);
396 mevent_add(SIGCONT, EVF_SIGNAL, blockif_sigcont_handler, NULL);
397 (void) signal(SIGCONT, SIG_IGN);
400 struct blockif_ctxt *
401 blockif_open(const char *optstr, const char *ident)
403 char tname[MAXCOMLEN + 1];
404 char name[MAXPATHLEN];
405 char *nopt, *xopts, *cp;
406 struct blockif_ctxt *bc;
408 struct diocgattr_arg arg;
409 off_t size, psectsz, psectoff;
410 int extra, fd, i, sectsz;
411 int nocache, sync, ro, candelete, geom, ssopt, pssopt;
412 #ifndef WITHOUT_CAPSICUM
414 cap_ioctl_t cmds[] = { DIOCGFLUSH, DIOCGDELETE };
417 pthread_once(&blockif_once, blockif_init);
426 * The first element in the optstring is always a pathname.
427 * Optional elements follow
429 nopt = xopts = strdup(optstr);
430 while (xopts != NULL) {
431 cp = strsep(&xopts, ",");
432 if (cp == nopt) /* file or device pathname */
434 else if (!strcmp(cp, "nocache"))
436 else if (!strcmp(cp, "sync") || !strcmp(cp, "direct"))
438 else if (!strcmp(cp, "ro"))
440 else if (sscanf(cp, "sectorsize=%d/%d", &ssopt, &pssopt) == 2)
442 else if (sscanf(cp, "sectorsize=%d", &ssopt) == 1)
445 fprintf(stderr, "Invalid device option \"%s\"\n", cp);
456 fd = open(nopt, (ro ? O_RDONLY : O_RDWR) | extra);
458 /* Attempt a r/w fail with a r/o open */
459 fd = open(nopt, O_RDONLY | extra);
464 warn("Could not open backing file: %s", nopt);
468 if (fstat(fd, &sbuf) < 0) {
469 warn("Could not stat backing file %s", nopt);
473 #ifndef WITHOUT_CAPSICUM
474 cap_rights_init(&rights, CAP_FSYNC, CAP_IOCTL, CAP_READ, CAP_SEEK,
477 cap_rights_clear(&rights, CAP_FSYNC, CAP_WRITE);
479 if (caph_rights_limit(fd, &rights) == -1)
480 errx(EX_OSERR, "Unable to apply rights for sandbox");
484 * Deal with raw devices
488 psectsz = psectoff = 0;
489 candelete = geom = 0;
490 if (S_ISCHR(sbuf.st_mode)) {
491 if (ioctl(fd, DIOCGMEDIASIZE, &size) < 0 ||
492 ioctl(fd, DIOCGSECTORSIZE, §sz)) {
493 perror("Could not fetch dev blk/sector size");
498 if (ioctl(fd, DIOCGSTRIPESIZE, &psectsz) == 0 && psectsz > 0)
499 ioctl(fd, DIOCGSTRIPEOFFSET, &psectoff);
500 strlcpy(arg.name, "GEOM::candelete", sizeof(arg.name));
501 arg.len = sizeof(arg.value.i);
502 if (ioctl(fd, DIOCGATTR, &arg) == 0)
503 candelete = arg.value.i;
504 if (ioctl(fd, DIOCGPROVIDERNAME, name) == 0)
507 psectsz = sbuf.st_blksize;
509 #ifndef WITHOUT_CAPSICUM
510 if (caph_ioctls_limit(fd, cmds, nitems(cmds)) == -1)
511 errx(EX_OSERR, "Unable to apply rights for sandbox");
515 if (!powerof2(ssopt) || !powerof2(pssopt) || ssopt < 512 ||
517 fprintf(stderr, "Invalid sector size %d/%d\n",
523 * Some backend drivers (e.g. cd0, ada0) require that the I/O
524 * size be a multiple of the device's sector size.
526 * Validate that the emulated sector size complies with this
529 if (S_ISCHR(sbuf.st_mode)) {
530 if (ssopt < sectsz || (ssopt % sectsz) != 0) {
531 fprintf(stderr, "Sector size %d incompatible "
532 "with underlying device sector size %d\n",
543 bc = calloc(1, sizeof(struct blockif_ctxt));
549 bc->bc_magic = BLOCKIF_SIG;
551 bc->bc_ischr = S_ISCHR(sbuf.st_mode);
552 bc->bc_isgeom = geom;
553 bc->bc_candelete = candelete;
556 bc->bc_sectsz = sectsz;
557 bc->bc_psectsz = psectsz;
558 bc->bc_psectoff = psectoff;
559 pthread_mutex_init(&bc->bc_mtx, NULL);
560 pthread_cond_init(&bc->bc_cond, NULL);
561 TAILQ_INIT(&bc->bc_freeq);
562 TAILQ_INIT(&bc->bc_pendq);
563 TAILQ_INIT(&bc->bc_busyq);
564 for (i = 0; i < BLOCKIF_MAXREQ; i++) {
565 bc->bc_reqs[i].be_status = BST_FREE;
566 TAILQ_INSERT_HEAD(&bc->bc_freeq, &bc->bc_reqs[i], be_link);
569 for (i = 0; i < BLOCKIF_NUMTHR; i++) {
570 pthread_create(&bc->bc_btid[i], NULL, blockif_thr, bc);
571 snprintf(tname, sizeof(tname), "blk-%s-%d", ident, i);
572 pthread_set_name_np(bc->bc_btid[i], tname);
584 blockif_request(struct blockif_ctxt *bc, struct blockif_req *breq,
591 pthread_mutex_lock(&bc->bc_mtx);
592 if (!TAILQ_EMPTY(&bc->bc_freeq)) {
594 * Enqueue and inform the block i/o thread
595 * that there is work available
597 if (blockif_enqueue(bc, breq, op))
598 pthread_cond_signal(&bc->bc_cond);
601 * Callers are not allowed to enqueue more than
602 * the specified blockif queue limit. Return an
603 * error to indicate that the queue length has been
608 pthread_mutex_unlock(&bc->bc_mtx);
614 blockif_read(struct blockif_ctxt *bc, struct blockif_req *breq)
617 assert(bc->bc_magic == BLOCKIF_SIG);
618 return (blockif_request(bc, breq, BOP_READ));
622 blockif_write(struct blockif_ctxt *bc, struct blockif_req *breq)
625 assert(bc->bc_magic == BLOCKIF_SIG);
626 return (blockif_request(bc, breq, BOP_WRITE));
630 blockif_flush(struct blockif_ctxt *bc, struct blockif_req *breq)
633 assert(bc->bc_magic == BLOCKIF_SIG);
634 return (blockif_request(bc, breq, BOP_FLUSH));
638 blockif_delete(struct blockif_ctxt *bc, struct blockif_req *breq)
641 assert(bc->bc_magic == BLOCKIF_SIG);
642 return (blockif_request(bc, breq, BOP_DELETE));
646 blockif_cancel(struct blockif_ctxt *bc, struct blockif_req *breq)
648 struct blockif_elem *be;
650 assert(bc->bc_magic == BLOCKIF_SIG);
652 pthread_mutex_lock(&bc->bc_mtx);
654 * Check pending requests.
656 TAILQ_FOREACH(be, &bc->bc_pendq, be_link) {
657 if (be->be_req == breq)
664 blockif_complete(bc, be);
665 pthread_mutex_unlock(&bc->bc_mtx);
671 * Check in-flight requests.
673 TAILQ_FOREACH(be, &bc->bc_busyq, be_link) {
674 if (be->be_req == breq)
681 pthread_mutex_unlock(&bc->bc_mtx);
686 * Interrupt the processing thread to force it return
687 * prematurely via it's normal callback path.
689 while (be->be_status == BST_BUSY) {
690 struct blockif_sig_elem bse, *old_head;
692 pthread_mutex_init(&bse.bse_mtx, NULL);
693 pthread_cond_init(&bse.bse_cond, NULL);
698 old_head = blockif_bse_head;
699 bse.bse_next = old_head;
700 } while (!atomic_cmpset_ptr((uintptr_t *)&blockif_bse_head,
704 pthread_kill(be->be_tid, SIGCONT);
706 pthread_mutex_lock(&bse.bse_mtx);
707 while (bse.bse_pending)
708 pthread_cond_wait(&bse.bse_cond, &bse.bse_mtx);
709 pthread_mutex_unlock(&bse.bse_mtx);
712 pthread_mutex_unlock(&bc->bc_mtx);
715 * The processing thread has been interrupted. Since it's not
716 * clear if the callback has been invoked yet, return EBUSY.
722 blockif_close(struct blockif_ctxt *bc)
727 assert(bc->bc_magic == BLOCKIF_SIG);
730 * Stop the block i/o thread
732 pthread_mutex_lock(&bc->bc_mtx);
734 pthread_mutex_unlock(&bc->bc_mtx);
735 pthread_cond_broadcast(&bc->bc_cond);
736 for (i = 0; i < BLOCKIF_NUMTHR; i++)
737 pthread_join(bc->bc_btid[i], &jval);
739 /* XXX Cancel queued i/o's ??? */
752 * Return virtual C/H/S values for a given block. Use the algorithm
753 * outlined in the VHD specification to calculate values.
756 blockif_chs(struct blockif_ctxt *bc, uint16_t *c, uint8_t *h, uint8_t *s)
758 off_t sectors; /* total sectors of the block dev */
759 off_t hcyl; /* cylinders times heads */
760 uint16_t secpt; /* sectors per track */
763 assert(bc->bc_magic == BLOCKIF_SIG);
765 sectors = bc->bc_size / bc->bc_sectsz;
767 /* Clamp the size to the largest possible with CHS */
768 if (sectors > 65535UL*16*255)
769 sectors = 65535UL*16*255;
771 if (sectors >= 65536UL*16*63) {
774 hcyl = sectors / secpt;
777 hcyl = sectors / secpt;
778 heads = (hcyl + 1023) / 1024;
783 if (hcyl >= (heads * 1024) || heads > 16) {
786 hcyl = sectors / secpt;
788 if (hcyl >= (heads * 1024)) {
791 hcyl = sectors / secpt;
804 blockif_size(struct blockif_ctxt *bc)
807 assert(bc->bc_magic == BLOCKIF_SIG);
808 return (bc->bc_size);
812 blockif_sectsz(struct blockif_ctxt *bc)
815 assert(bc->bc_magic == BLOCKIF_SIG);
816 return (bc->bc_sectsz);
820 blockif_psectsz(struct blockif_ctxt *bc, int *size, int *off)
823 assert(bc->bc_magic == BLOCKIF_SIG);
824 *size = bc->bc_psectsz;
825 *off = bc->bc_psectoff;
829 blockif_queuesz(struct blockif_ctxt *bc)
832 assert(bc->bc_magic == BLOCKIF_SIG);
833 return (BLOCKIF_MAXREQ - 1);
837 blockif_is_ro(struct blockif_ctxt *bc)
840 assert(bc->bc_magic == BLOCKIF_SIG);
841 return (bc->bc_rdonly);
845 blockif_candelete(struct blockif_ctxt *bc)
848 assert(bc->bc_magic == BLOCKIF_SIG);
849 return (bc->bc_candelete);