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>
46 #include <pthread_np.h>
50 #include <machine/atomic.h>
56 #define BLOCKIF_SIG 0xb109b109
58 #define BLOCKIF_NUMTHR 8
59 #define BLOCKIF_MAXREQ (64 + BLOCKIF_NUMTHR)
77 TAILQ_ENTRY(blockif_elem) be_link;
78 struct blockif_req *be_req;
80 enum blockstat be_status;
97 pthread_t bc_btid[BLOCKIF_NUMTHR];
98 pthread_mutex_t bc_mtx;
99 pthread_cond_t bc_cond;
101 /* Request elements and free/pending/busy queues */
102 TAILQ_HEAD(, blockif_elem) bc_freeq;
103 TAILQ_HEAD(, blockif_elem) bc_pendq;
104 TAILQ_HEAD(, blockif_elem) bc_busyq;
105 struct blockif_elem bc_reqs[BLOCKIF_MAXREQ];
108 static pthread_once_t blockif_once = PTHREAD_ONCE_INIT;
110 struct blockif_sig_elem {
111 pthread_mutex_t bse_mtx;
112 pthread_cond_t bse_cond;
114 struct blockif_sig_elem *bse_next;
117 static struct blockif_sig_elem *blockif_bse_head;
120 blockif_enqueue(struct blockif_ctxt *bc, struct blockif_req *breq,
123 struct blockif_elem *be, *tbe;
127 be = TAILQ_FIRST(&bc->bc_freeq);
129 assert(be->be_status == BST_FREE);
130 TAILQ_REMOVE(&bc->bc_freeq, be, be_link);
137 off = breq->br_offset;
138 for (i = 0; i < breq->br_iovcnt; i++)
139 off += breq->br_iov[i].iov_len;
145 TAILQ_FOREACH(tbe, &bc->bc_pendq, be_link) {
146 if (tbe->be_block == breq->br_offset)
150 TAILQ_FOREACH(tbe, &bc->bc_busyq, be_link) {
151 if (tbe->be_block == breq->br_offset)
156 be->be_status = BST_PEND;
158 be->be_status = BST_BLOCK;
159 TAILQ_INSERT_TAIL(&bc->bc_pendq, be, be_link);
160 return (be->be_status == BST_PEND);
164 blockif_dequeue(struct blockif_ctxt *bc, pthread_t t, struct blockif_elem **bep)
166 struct blockif_elem *be;
168 TAILQ_FOREACH(be, &bc->bc_pendq, be_link) {
169 if (be->be_status == BST_PEND)
171 assert(be->be_status == BST_BLOCK);
175 TAILQ_REMOVE(&bc->bc_pendq, be, be_link);
176 be->be_status = BST_BUSY;
178 TAILQ_INSERT_TAIL(&bc->bc_busyq, be, be_link);
184 blockif_complete(struct blockif_ctxt *bc, struct blockif_elem *be)
186 struct blockif_elem *tbe;
188 if (be->be_status == BST_DONE || be->be_status == BST_BUSY)
189 TAILQ_REMOVE(&bc->bc_busyq, be, be_link);
191 TAILQ_REMOVE(&bc->bc_pendq, be, be_link);
192 TAILQ_FOREACH(tbe, &bc->bc_pendq, be_link) {
193 if (tbe->be_req->br_offset == be->be_block)
194 tbe->be_status = BST_PEND;
197 be->be_status = BST_FREE;
199 TAILQ_INSERT_TAIL(&bc->bc_freeq, be, be_link);
203 blockif_proc(struct blockif_ctxt *bc, struct blockif_elem *be, uint8_t *buf)
205 struct blockif_req *br;
207 ssize_t clen, len, off, boff, voff;
211 if (br->br_iovcnt <= 1)
217 if ((len = preadv(bc->bc_fd, br->br_iov, br->br_iovcnt,
226 while (br->br_resid > 0) {
227 len = MIN(br->br_resid, MAXPHYS);
228 if (pread(bc->bc_fd, buf, len, br->br_offset +
235 clen = MIN(len - boff, br->br_iov[i].iov_len -
237 memcpy(br->br_iov[i].iov_base + voff,
239 if (clen < br->br_iov[i].iov_len - voff)
246 } while (boff < len);
257 if ((len = pwritev(bc->bc_fd, br->br_iov, br->br_iovcnt,
266 while (br->br_resid > 0) {
267 len = MIN(br->br_resid, MAXPHYS);
270 clen = MIN(len - boff, br->br_iov[i].iov_len -
273 br->br_iov[i].iov_base + voff, clen);
274 if (clen < br->br_iov[i].iov_len - voff)
281 } while (boff < len);
282 if (pwrite(bc->bc_fd, buf, len, br->br_offset +
293 if (ioctl(bc->bc_fd, DIOCGFLUSH))
295 } else if (fsync(bc->bc_fd))
299 if (!bc->bc_candelete)
301 else if (bc->bc_rdonly)
303 else if (bc->bc_ischr) {
304 arg[0] = br->br_offset;
305 arg[1] = br->br_resid;
306 if (ioctl(bc->bc_fd, DIOCGDELETE, arg))
318 be->be_status = BST_DONE;
320 (*br->br_callback)(br, err);
324 blockif_thr(void *arg)
326 struct blockif_ctxt *bc;
327 struct blockif_elem *be;
333 buf = malloc(MAXPHYS);
338 pthread_mutex_lock(&bc->bc_mtx);
340 while (blockif_dequeue(bc, t, &be)) {
341 pthread_mutex_unlock(&bc->bc_mtx);
342 blockif_proc(bc, be, buf);
343 pthread_mutex_lock(&bc->bc_mtx);
344 blockif_complete(bc, be);
346 /* Check ctxt status here to see if exit requested */
349 pthread_cond_wait(&bc->bc_cond, &bc->bc_mtx);
351 pthread_mutex_unlock(&bc->bc_mtx);
360 blockif_sigcont_handler(int signal, enum ev_type type, void *arg)
362 struct blockif_sig_elem *bse;
366 * Process the entire list even if not intended for
370 bse = blockif_bse_head;
373 } while (!atomic_cmpset_ptr((uintptr_t *)&blockif_bse_head,
375 (uintptr_t)bse->bse_next));
377 pthread_mutex_lock(&bse->bse_mtx);
378 bse->bse_pending = 0;
379 pthread_cond_signal(&bse->bse_cond);
380 pthread_mutex_unlock(&bse->bse_mtx);
387 mevent_add(SIGCONT, EVF_SIGNAL, blockif_sigcont_handler, NULL);
388 (void) signal(SIGCONT, SIG_IGN);
391 struct blockif_ctxt *
392 blockif_open(const char *optstr, const char *ident)
394 char tname[MAXCOMLEN + 1];
395 char name[MAXPATHLEN];
396 char *nopt, *xopts, *cp;
397 struct blockif_ctxt *bc;
399 struct diocgattr_arg arg;
400 off_t size, psectsz, psectoff;
401 int extra, fd, i, sectsz;
402 int nocache, sync, ro, candelete, geom, ssopt, pssopt;
404 pthread_once(&blockif_once, blockif_init);
413 * The first element in the optstring is always a pathname.
414 * Optional elements follow
416 nopt = xopts = strdup(optstr);
417 while (xopts != NULL) {
418 cp = strsep(&xopts, ",");
419 if (cp == nopt) /* file or device pathname */
421 else if (!strcmp(cp, "nocache"))
423 else if (!strcmp(cp, "sync") || !strcmp(cp, "direct"))
425 else if (!strcmp(cp, "ro"))
427 else if (sscanf(cp, "sectorsize=%d/%d", &ssopt, &pssopt) == 2)
429 else if (sscanf(cp, "sectorsize=%d", &ssopt) == 1)
432 fprintf(stderr, "Invalid device option \"%s\"\n", cp);
443 fd = open(nopt, (ro ? O_RDONLY : O_RDWR) | extra);
445 /* Attempt a r/w fail with a r/o open */
446 fd = open(nopt, O_RDONLY | extra);
451 warn("Could not open backing file: %s", nopt);
455 if (fstat(fd, &sbuf) < 0) {
456 warn("Could not stat backing file %s", nopt);
461 * Deal with raw devices
465 psectsz = psectoff = 0;
466 candelete = geom = 0;
467 if (S_ISCHR(sbuf.st_mode)) {
468 if (ioctl(fd, DIOCGMEDIASIZE, &size) < 0 ||
469 ioctl(fd, DIOCGSECTORSIZE, §sz)) {
470 perror("Could not fetch dev blk/sector size");
475 if (ioctl(fd, DIOCGSTRIPESIZE, &psectsz) == 0 && psectsz > 0)
476 ioctl(fd, DIOCGSTRIPEOFFSET, &psectoff);
477 strlcpy(arg.name, "GEOM::candelete", sizeof(arg.name));
478 arg.len = sizeof(arg.value.i);
479 if (ioctl(fd, DIOCGATTR, &arg) == 0)
480 candelete = arg.value.i;
481 if (ioctl(fd, DIOCGPROVIDERNAME, name) == 0)
484 psectsz = sbuf.st_blksize;
487 if (!powerof2(ssopt) || !powerof2(pssopt) || ssopt < 512 ||
489 fprintf(stderr, "Invalid sector size %d/%d\n",
495 * Some backend drivers (e.g. cd0, ada0) require that the I/O
496 * size be a multiple of the device's sector size.
498 * Validate that the emulated sector size complies with this
501 if (S_ISCHR(sbuf.st_mode)) {
502 if (ssopt < sectsz || (ssopt % sectsz) != 0) {
503 fprintf(stderr, "Sector size %d incompatible "
504 "with underlying device sector size %d\n",
515 bc = calloc(1, sizeof(struct blockif_ctxt));
521 bc->bc_magic = BLOCKIF_SIG;
523 bc->bc_ischr = S_ISCHR(sbuf.st_mode);
524 bc->bc_isgeom = geom;
525 bc->bc_candelete = candelete;
528 bc->bc_sectsz = sectsz;
529 bc->bc_psectsz = psectsz;
530 bc->bc_psectoff = psectoff;
531 pthread_mutex_init(&bc->bc_mtx, NULL);
532 pthread_cond_init(&bc->bc_cond, NULL);
533 TAILQ_INIT(&bc->bc_freeq);
534 TAILQ_INIT(&bc->bc_pendq);
535 TAILQ_INIT(&bc->bc_busyq);
536 for (i = 0; i < BLOCKIF_MAXREQ; i++) {
537 bc->bc_reqs[i].be_status = BST_FREE;
538 TAILQ_INSERT_HEAD(&bc->bc_freeq, &bc->bc_reqs[i], be_link);
541 for (i = 0; i < BLOCKIF_NUMTHR; i++) {
542 pthread_create(&bc->bc_btid[i], NULL, blockif_thr, bc);
543 snprintf(tname, sizeof(tname), "blk-%s-%d", ident, i);
544 pthread_set_name_np(bc->bc_btid[i], tname);
555 blockif_request(struct blockif_ctxt *bc, struct blockif_req *breq,
562 pthread_mutex_lock(&bc->bc_mtx);
563 if (!TAILQ_EMPTY(&bc->bc_freeq)) {
565 * Enqueue and inform the block i/o thread
566 * that there is work available
568 if (blockif_enqueue(bc, breq, op))
569 pthread_cond_signal(&bc->bc_cond);
572 * Callers are not allowed to enqueue more than
573 * the specified blockif queue limit. Return an
574 * error to indicate that the queue length has been
579 pthread_mutex_unlock(&bc->bc_mtx);
585 blockif_read(struct blockif_ctxt *bc, struct blockif_req *breq)
588 assert(bc->bc_magic == BLOCKIF_SIG);
589 return (blockif_request(bc, breq, BOP_READ));
593 blockif_write(struct blockif_ctxt *bc, struct blockif_req *breq)
596 assert(bc->bc_magic == BLOCKIF_SIG);
597 return (blockif_request(bc, breq, BOP_WRITE));
601 blockif_flush(struct blockif_ctxt *bc, struct blockif_req *breq)
604 assert(bc->bc_magic == BLOCKIF_SIG);
605 return (blockif_request(bc, breq, BOP_FLUSH));
609 blockif_delete(struct blockif_ctxt *bc, struct blockif_req *breq)
612 assert(bc->bc_magic == BLOCKIF_SIG);
613 return (blockif_request(bc, breq, BOP_DELETE));
617 blockif_cancel(struct blockif_ctxt *bc, struct blockif_req *breq)
619 struct blockif_elem *be;
621 assert(bc->bc_magic == BLOCKIF_SIG);
623 pthread_mutex_lock(&bc->bc_mtx);
625 * Check pending requests.
627 TAILQ_FOREACH(be, &bc->bc_pendq, be_link) {
628 if (be->be_req == breq)
635 blockif_complete(bc, be);
636 pthread_mutex_unlock(&bc->bc_mtx);
642 * Check in-flight requests.
644 TAILQ_FOREACH(be, &bc->bc_busyq, be_link) {
645 if (be->be_req == breq)
652 pthread_mutex_unlock(&bc->bc_mtx);
657 * Interrupt the processing thread to force it return
658 * prematurely via it's normal callback path.
660 while (be->be_status == BST_BUSY) {
661 struct blockif_sig_elem bse, *old_head;
663 pthread_mutex_init(&bse.bse_mtx, NULL);
664 pthread_cond_init(&bse.bse_cond, NULL);
669 old_head = blockif_bse_head;
670 bse.bse_next = old_head;
671 } while (!atomic_cmpset_ptr((uintptr_t *)&blockif_bse_head,
675 pthread_kill(be->be_tid, SIGCONT);
677 pthread_mutex_lock(&bse.bse_mtx);
678 while (bse.bse_pending)
679 pthread_cond_wait(&bse.bse_cond, &bse.bse_mtx);
680 pthread_mutex_unlock(&bse.bse_mtx);
683 pthread_mutex_unlock(&bc->bc_mtx);
686 * The processing thread has been interrupted. Since it's not
687 * clear if the callback has been invoked yet, return EBUSY.
693 blockif_close(struct blockif_ctxt *bc)
698 assert(bc->bc_magic == BLOCKIF_SIG);
701 * Stop the block i/o thread
703 pthread_mutex_lock(&bc->bc_mtx);
705 pthread_mutex_unlock(&bc->bc_mtx);
706 pthread_cond_broadcast(&bc->bc_cond);
707 for (i = 0; i < BLOCKIF_NUMTHR; i++)
708 pthread_join(bc->bc_btid[i], &jval);
710 /* XXX Cancel queued i/o's ??? */
723 * Return virtual C/H/S values for a given block. Use the algorithm
724 * outlined in the VHD specification to calculate values.
727 blockif_chs(struct blockif_ctxt *bc, uint16_t *c, uint8_t *h, uint8_t *s)
729 off_t sectors; /* total sectors of the block dev */
730 off_t hcyl; /* cylinders times heads */
731 uint16_t secpt; /* sectors per track */
734 assert(bc->bc_magic == BLOCKIF_SIG);
736 sectors = bc->bc_size / bc->bc_sectsz;
738 /* Clamp the size to the largest possible with CHS */
739 if (sectors > 65535UL*16*255)
740 sectors = 65535UL*16*255;
742 if (sectors >= 65536UL*16*63) {
745 hcyl = sectors / secpt;
748 hcyl = sectors / secpt;
749 heads = (hcyl + 1023) / 1024;
754 if (hcyl >= (heads * 1024) || heads > 16) {
757 hcyl = sectors / secpt;
759 if (hcyl >= (heads * 1024)) {
762 hcyl = sectors / secpt;
775 blockif_size(struct blockif_ctxt *bc)
778 assert(bc->bc_magic == BLOCKIF_SIG);
779 return (bc->bc_size);
783 blockif_sectsz(struct blockif_ctxt *bc)
786 assert(bc->bc_magic == BLOCKIF_SIG);
787 return (bc->bc_sectsz);
791 blockif_psectsz(struct blockif_ctxt *bc, int *size, int *off)
794 assert(bc->bc_magic == BLOCKIF_SIG);
795 *size = bc->bc_psectsz;
796 *off = bc->bc_psectoff;
800 blockif_queuesz(struct blockif_ctxt *bc)
803 assert(bc->bc_magic == BLOCKIF_SIG);
804 return (BLOCKIF_MAXREQ - 1);
808 blockif_is_ro(struct blockif_ctxt *bc)
811 assert(bc->bc_magic == BLOCKIF_SIG);
812 return (bc->bc_rdonly);
816 blockif_candelete(struct blockif_ctxt *bc)
819 assert(bc->bc_magic == BLOCKIF_SIG);
820 return (bc->bc_candelete);