2 * Copyright (c) 2013 Peter Grehan <grehan@freebsd.org>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
32 #include <sys/param.h>
33 #include <sys/queue.h>
34 #include <sys/errno.h>
36 #include <sys/ioctl.h>
45 #include <pthread_np.h>
49 #include <machine/atomic.h>
55 #define BLOCKIF_SIG 0xb109b109
57 #define BLOCKIF_NUMTHR 8
58 #define BLOCKIF_MAXREQ (64 + BLOCKIF_NUMTHR)
76 TAILQ_ENTRY(blockif_elem) be_link;
77 struct blockif_req *be_req;
79 enum blockstat be_status;
96 pthread_t bc_btid[BLOCKIF_NUMTHR];
97 pthread_mutex_t bc_mtx;
98 pthread_cond_t bc_cond;
100 /* Request elements and free/pending/busy queues */
101 TAILQ_HEAD(, blockif_elem) bc_freeq;
102 TAILQ_HEAD(, blockif_elem) bc_pendq;
103 TAILQ_HEAD(, blockif_elem) bc_busyq;
104 struct blockif_elem bc_reqs[BLOCKIF_MAXREQ];
107 static pthread_once_t blockif_once = PTHREAD_ONCE_INIT;
109 struct blockif_sig_elem {
110 pthread_mutex_t bse_mtx;
111 pthread_cond_t bse_cond;
113 struct blockif_sig_elem *bse_next;
116 static struct blockif_sig_elem *blockif_bse_head;
119 blockif_enqueue(struct blockif_ctxt *bc, struct blockif_req *breq,
122 struct blockif_elem *be, *tbe;
126 be = TAILQ_FIRST(&bc->bc_freeq);
128 assert(be->be_status == BST_FREE);
129 TAILQ_REMOVE(&bc->bc_freeq, be, be_link);
136 off = breq->br_offset;
137 for (i = 0; i < breq->br_iovcnt; i++)
138 off += breq->br_iov[i].iov_len;
144 TAILQ_FOREACH(tbe, &bc->bc_pendq, be_link) {
145 if (tbe->be_block == breq->br_offset)
149 TAILQ_FOREACH(tbe, &bc->bc_busyq, be_link) {
150 if (tbe->be_block == breq->br_offset)
155 be->be_status = BST_PEND;
157 be->be_status = BST_BLOCK;
158 TAILQ_INSERT_TAIL(&bc->bc_pendq, be, be_link);
159 return (be->be_status == BST_PEND);
163 blockif_dequeue(struct blockif_ctxt *bc, pthread_t t, struct blockif_elem **bep)
165 struct blockif_elem *be;
167 TAILQ_FOREACH(be, &bc->bc_pendq, be_link) {
168 if (be->be_status == BST_PEND)
170 assert(be->be_status == BST_BLOCK);
174 TAILQ_REMOVE(&bc->bc_pendq, be, be_link);
175 be->be_status = BST_BUSY;
177 TAILQ_INSERT_TAIL(&bc->bc_busyq, be, be_link);
183 blockif_complete(struct blockif_ctxt *bc, struct blockif_elem *be)
185 struct blockif_elem *tbe;
187 if (be->be_status == BST_DONE || be->be_status == BST_BUSY)
188 TAILQ_REMOVE(&bc->bc_busyq, be, be_link);
190 TAILQ_REMOVE(&bc->bc_pendq, be, be_link);
191 TAILQ_FOREACH(tbe, &bc->bc_pendq, be_link) {
192 if (tbe->be_req->br_offset == be->be_block)
193 tbe->be_status = BST_PEND;
196 be->be_status = BST_FREE;
198 TAILQ_INSERT_TAIL(&bc->bc_freeq, be, be_link);
202 blockif_proc(struct blockif_ctxt *bc, struct blockif_elem *be, uint8_t *buf)
204 struct blockif_req *br;
206 ssize_t clen, len, off, boff, voff;
210 if (br->br_iovcnt <= 1)
216 if ((len = preadv(bc->bc_fd, br->br_iov, br->br_iovcnt,
225 while (br->br_resid > 0) {
226 len = MIN(br->br_resid, MAXPHYS);
227 if (pread(bc->bc_fd, buf, len, br->br_offset +
234 clen = MIN(len - boff, br->br_iov[i].iov_len -
236 memcpy(br->br_iov[i].iov_base + voff,
238 if (clen < br->br_iov[i].iov_len - voff)
245 } while (boff < len);
256 if ((len = pwritev(bc->bc_fd, br->br_iov, br->br_iovcnt,
265 while (br->br_resid > 0) {
266 len = MIN(br->br_resid, MAXPHYS);
269 clen = MIN(len - boff, br->br_iov[i].iov_len -
272 br->br_iov[i].iov_base + voff, clen);
273 if (clen < br->br_iov[i].iov_len - voff)
280 } while (boff < len);
281 if (pwrite(bc->bc_fd, buf, len, br->br_offset +
292 if (ioctl(bc->bc_fd, DIOCGFLUSH))
294 } else if (fsync(bc->bc_fd))
298 if (!bc->bc_candelete)
300 else if (bc->bc_rdonly)
302 else if (bc->bc_ischr) {
303 arg[0] = br->br_offset;
304 arg[1] = br->br_resid;
305 if (ioctl(bc->bc_fd, DIOCGDELETE, arg))
317 be->be_status = BST_DONE;
319 (*br->br_callback)(br, err);
323 blockif_thr(void *arg)
325 struct blockif_ctxt *bc;
326 struct blockif_elem *be;
332 buf = malloc(MAXPHYS);
337 pthread_mutex_lock(&bc->bc_mtx);
339 while (blockif_dequeue(bc, t, &be)) {
340 pthread_mutex_unlock(&bc->bc_mtx);
341 blockif_proc(bc, be, buf);
342 pthread_mutex_lock(&bc->bc_mtx);
343 blockif_complete(bc, be);
345 /* Check ctxt status here to see if exit requested */
348 pthread_cond_wait(&bc->bc_cond, &bc->bc_mtx);
350 pthread_mutex_unlock(&bc->bc_mtx);
359 blockif_sigcont_handler(int signal, enum ev_type type, void *arg)
361 struct blockif_sig_elem *bse;
365 * Process the entire list even if not intended for
369 bse = blockif_bse_head;
372 } while (!atomic_cmpset_ptr((uintptr_t *)&blockif_bse_head,
374 (uintptr_t)bse->bse_next));
376 pthread_mutex_lock(&bse->bse_mtx);
377 bse->bse_pending = 0;
378 pthread_cond_signal(&bse->bse_cond);
379 pthread_mutex_unlock(&bse->bse_mtx);
386 mevent_add(SIGCONT, EVF_SIGNAL, blockif_sigcont_handler, NULL);
387 (void) signal(SIGCONT, SIG_IGN);
390 struct blockif_ctxt *
391 blockif_open(const char *optstr, const char *ident)
393 char tname[MAXCOMLEN + 1];
394 char name[MAXPATHLEN];
395 char *nopt, *xopts, *cp;
396 struct blockif_ctxt *bc;
398 struct diocgattr_arg arg;
399 off_t size, psectsz, psectoff;
400 int extra, fd, i, sectsz;
401 int nocache, sync, ro, candelete, geom, ssopt, pssopt;
403 pthread_once(&blockif_once, blockif_init);
412 * The first element in the optstring is always a pathname.
413 * Optional elements follow
415 nopt = xopts = strdup(optstr);
416 while (xopts != NULL) {
417 cp = strsep(&xopts, ",");
418 if (cp == nopt) /* file or device pathname */
420 else if (!strcmp(cp, "nocache"))
422 else if (!strcmp(cp, "sync") || !strcmp(cp, "direct"))
424 else if (!strcmp(cp, "ro"))
426 else if (sscanf(cp, "sectorsize=%d/%d", &ssopt, &pssopt) == 2)
428 else if (sscanf(cp, "sectorsize=%d", &ssopt) == 1)
431 fprintf(stderr, "Invalid device option \"%s\"\n", cp);
442 fd = open(nopt, (ro ? O_RDONLY : O_RDWR) | extra);
444 /* Attempt a r/w fail with a r/o open */
445 fd = open(nopt, O_RDONLY | extra);
450 perror("Could not open backing file");
454 if (fstat(fd, &sbuf) < 0) {
455 perror("Could not stat backing file");
460 * Deal with raw devices
464 psectsz = psectoff = 0;
465 candelete = geom = 0;
466 if (S_ISCHR(sbuf.st_mode)) {
467 if (ioctl(fd, DIOCGMEDIASIZE, &size) < 0 ||
468 ioctl(fd, DIOCGSECTORSIZE, §sz)) {
469 perror("Could not fetch dev blk/sector size");
474 if (ioctl(fd, DIOCGSTRIPESIZE, &psectsz) == 0 && psectsz > 0)
475 ioctl(fd, DIOCGSTRIPEOFFSET, &psectoff);
476 strlcpy(arg.name, "GEOM::candelete", sizeof(arg.name));
477 arg.len = sizeof(arg.value.i);
478 if (ioctl(fd, DIOCGATTR, &arg) == 0)
479 candelete = arg.value.i;
480 if (ioctl(fd, DIOCGPROVIDERNAME, name) == 0)
483 psectsz = sbuf.st_blksize;
486 if (!powerof2(ssopt) || !powerof2(pssopt) || ssopt < 512 ||
488 fprintf(stderr, "Invalid sector size %d/%d\n",
494 * Some backend drivers (e.g. cd0, ada0) require that the I/O
495 * size be a multiple of the device's sector size.
497 * Validate that the emulated sector size complies with this
500 if (S_ISCHR(sbuf.st_mode)) {
501 if (ssopt < sectsz || (ssopt % sectsz) != 0) {
502 fprintf(stderr, "Sector size %d incompatible "
503 "with underlying device sector size %d\n",
514 bc = calloc(1, sizeof(struct blockif_ctxt));
520 bc->bc_magic = BLOCKIF_SIG;
522 bc->bc_ischr = S_ISCHR(sbuf.st_mode);
523 bc->bc_isgeom = geom;
524 bc->bc_candelete = candelete;
527 bc->bc_sectsz = sectsz;
528 bc->bc_psectsz = psectsz;
529 bc->bc_psectoff = psectoff;
530 pthread_mutex_init(&bc->bc_mtx, NULL);
531 pthread_cond_init(&bc->bc_cond, NULL);
532 TAILQ_INIT(&bc->bc_freeq);
533 TAILQ_INIT(&bc->bc_pendq);
534 TAILQ_INIT(&bc->bc_busyq);
535 for (i = 0; i < BLOCKIF_MAXREQ; i++) {
536 bc->bc_reqs[i].be_status = BST_FREE;
537 TAILQ_INSERT_HEAD(&bc->bc_freeq, &bc->bc_reqs[i], be_link);
540 for (i = 0; i < BLOCKIF_NUMTHR; i++) {
541 pthread_create(&bc->bc_btid[i], NULL, blockif_thr, bc);
542 snprintf(tname, sizeof(tname), "blk-%s-%d", ident, i);
543 pthread_set_name_np(bc->bc_btid[i], tname);
554 blockif_request(struct blockif_ctxt *bc, struct blockif_req *breq,
561 pthread_mutex_lock(&bc->bc_mtx);
562 if (!TAILQ_EMPTY(&bc->bc_freeq)) {
564 * Enqueue and inform the block i/o thread
565 * that there is work available
567 if (blockif_enqueue(bc, breq, op))
568 pthread_cond_signal(&bc->bc_cond);
571 * Callers are not allowed to enqueue more than
572 * the specified blockif queue limit. Return an
573 * error to indicate that the queue length has been
578 pthread_mutex_unlock(&bc->bc_mtx);
584 blockif_read(struct blockif_ctxt *bc, struct blockif_req *breq)
587 assert(bc->bc_magic == BLOCKIF_SIG);
588 return (blockif_request(bc, breq, BOP_READ));
592 blockif_write(struct blockif_ctxt *bc, struct blockif_req *breq)
595 assert(bc->bc_magic == BLOCKIF_SIG);
596 return (blockif_request(bc, breq, BOP_WRITE));
600 blockif_flush(struct blockif_ctxt *bc, struct blockif_req *breq)
603 assert(bc->bc_magic == BLOCKIF_SIG);
604 return (blockif_request(bc, breq, BOP_FLUSH));
608 blockif_delete(struct blockif_ctxt *bc, struct blockif_req *breq)
611 assert(bc->bc_magic == BLOCKIF_SIG);
612 return (blockif_request(bc, breq, BOP_DELETE));
616 blockif_cancel(struct blockif_ctxt *bc, struct blockif_req *breq)
618 struct blockif_elem *be;
620 assert(bc->bc_magic == BLOCKIF_SIG);
622 pthread_mutex_lock(&bc->bc_mtx);
624 * Check pending requests.
626 TAILQ_FOREACH(be, &bc->bc_pendq, be_link) {
627 if (be->be_req == breq)
634 blockif_complete(bc, be);
635 pthread_mutex_unlock(&bc->bc_mtx);
641 * Check in-flight requests.
643 TAILQ_FOREACH(be, &bc->bc_busyq, be_link) {
644 if (be->be_req == breq)
651 pthread_mutex_unlock(&bc->bc_mtx);
656 * Interrupt the processing thread to force it return
657 * prematurely via it's normal callback path.
659 while (be->be_status == BST_BUSY) {
660 struct blockif_sig_elem bse, *old_head;
662 pthread_mutex_init(&bse.bse_mtx, NULL);
663 pthread_cond_init(&bse.bse_cond, NULL);
668 old_head = blockif_bse_head;
669 bse.bse_next = old_head;
670 } while (!atomic_cmpset_ptr((uintptr_t *)&blockif_bse_head,
674 pthread_kill(be->be_tid, SIGCONT);
676 pthread_mutex_lock(&bse.bse_mtx);
677 while (bse.bse_pending)
678 pthread_cond_wait(&bse.bse_cond, &bse.bse_mtx);
679 pthread_mutex_unlock(&bse.bse_mtx);
682 pthread_mutex_unlock(&bc->bc_mtx);
685 * The processing thread has been interrupted. Since it's not
686 * clear if the callback has been invoked yet, return EBUSY.
692 blockif_close(struct blockif_ctxt *bc)
699 assert(bc->bc_magic == BLOCKIF_SIG);
702 * Stop the block i/o thread
704 pthread_mutex_lock(&bc->bc_mtx);
706 pthread_mutex_unlock(&bc->bc_mtx);
707 pthread_cond_broadcast(&bc->bc_cond);
708 for (i = 0; i < BLOCKIF_NUMTHR; i++)
709 pthread_join(bc->bc_btid[i], &jval);
711 /* XXX Cancel queued i/o's ??? */
724 * Return virtual C/H/S values for a given block. Use the algorithm
725 * outlined in the VHD specification to calculate values.
728 blockif_chs(struct blockif_ctxt *bc, uint16_t *c, uint8_t *h, uint8_t *s)
730 off_t sectors; /* total sectors of the block dev */
731 off_t hcyl; /* cylinders times heads */
732 uint16_t secpt; /* sectors per track */
735 assert(bc->bc_magic == BLOCKIF_SIG);
737 sectors = bc->bc_size / bc->bc_sectsz;
739 /* Clamp the size to the largest possible with CHS */
740 if (sectors > 65535UL*16*255)
741 sectors = 65535UL*16*255;
743 if (sectors >= 65536UL*16*63) {
746 hcyl = sectors / secpt;
749 hcyl = sectors / secpt;
750 heads = (hcyl + 1023) / 1024;
755 if (hcyl >= (heads * 1024) || heads > 16) {
758 hcyl = sectors / secpt;
760 if (hcyl >= (heads * 1024)) {
763 hcyl = sectors / secpt;
776 blockif_size(struct blockif_ctxt *bc)
779 assert(bc->bc_magic == BLOCKIF_SIG);
780 return (bc->bc_size);
784 blockif_sectsz(struct blockif_ctxt *bc)
787 assert(bc->bc_magic == BLOCKIF_SIG);
788 return (bc->bc_sectsz);
792 blockif_psectsz(struct blockif_ctxt *bc, int *size, int *off)
795 assert(bc->bc_magic == BLOCKIF_SIG);
796 *size = bc->bc_psectsz;
797 *off = bc->bc_psectoff;
801 blockif_queuesz(struct blockif_ctxt *bc)
804 assert(bc->bc_magic == BLOCKIF_SIG);
805 return (BLOCKIF_MAXREQ - 1);
809 blockif_is_ro(struct blockif_ctxt *bc)
812 assert(bc->bc_magic == BLOCKIF_SIG);
813 return (bc->bc_rdonly);
817 blockif_candelete(struct blockif_ctxt *bc)
820 assert(bc->bc_magic == BLOCKIF_SIG);
821 return (bc->bc_candelete);