]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.sbin/bhyve/block_if.c
ssh: update to OpenSSH 9.1p1
[FreeBSD/FreeBSD.git] / usr.sbin / bhyve / block_if.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2013  Peter Grehan <grehan@freebsd.org>
5  * All rights reserved.
6  * Copyright 2020 Joyent, Inc.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
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.
16  *
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
27  * SUCH DAMAGE.
28  *
29  * $FreeBSD$
30  */
31
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34
35 #include <sys/param.h>
36 #ifndef WITHOUT_CAPSICUM
37 #include <sys/capsicum.h>
38 #endif
39 #include <sys/queue.h>
40 #include <sys/errno.h>
41 #include <sys/stat.h>
42 #include <sys/ioctl.h>
43 #include <sys/disk.h>
44
45 #include <assert.h>
46 #ifndef WITHOUT_CAPSICUM
47 #include <capsicum_helpers.h>
48 #endif
49 #include <err.h>
50 #include <fcntl.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <pthread.h>
55 #include <pthread_np.h>
56 #include <signal.h>
57 #include <sysexits.h>
58 #include <unistd.h>
59
60 #include <machine/atomic.h>
61 #include <machine/vmm_snapshot.h>
62
63 #include "bhyverun.h"
64 #include "config.h"
65 #include "debug.h"
66 #include "mevent.h"
67 #include "pci_emul.h"
68 #include "block_if.h"
69
70 #define BLOCKIF_SIG     0xb109b109
71
72 #define BLOCKIF_NUMTHR  8
73 #define BLOCKIF_MAXREQ  (BLOCKIF_RING_MAX + BLOCKIF_NUMTHR)
74
75 enum blockop {
76         BOP_READ,
77         BOP_WRITE,
78         BOP_FLUSH,
79         BOP_DELETE
80 };
81
82 enum blockstat {
83         BST_FREE,
84         BST_BLOCK,
85         BST_PEND,
86         BST_BUSY,
87         BST_DONE
88 };
89
90 struct blockif_elem {
91         TAILQ_ENTRY(blockif_elem) be_link;
92         struct blockif_req  *be_req;
93         enum blockop         be_op;
94         enum blockstat       be_status;
95         pthread_t            be_tid;
96         off_t                be_block;
97 };
98
99 struct blockif_ctxt {
100         unsigned int            bc_magic;
101         int                     bc_fd;
102         int                     bc_ischr;
103         int                     bc_isgeom;
104         int                     bc_candelete;
105         int                     bc_rdonly;
106         off_t                   bc_size;
107         int                     bc_sectsz;
108         int                     bc_psectsz;
109         int                     bc_psectoff;
110         int                     bc_closing;
111         int                     bc_paused;
112         pthread_t               bc_btid[BLOCKIF_NUMTHR];
113         pthread_mutex_t         bc_mtx;
114         pthread_cond_t          bc_cond;
115         pthread_cond_t          bc_work_done_cond;
116         blockif_resize_cb       *bc_resize_cb;
117         void                    *bc_resize_cb_arg;
118         struct mevent           *bc_resize_event;
119
120         /* Request elements and free/pending/busy queues */
121         TAILQ_HEAD(, blockif_elem) bc_freeq;
122         TAILQ_HEAD(, blockif_elem) bc_pendq;
123         TAILQ_HEAD(, blockif_elem) bc_busyq;
124         struct blockif_elem     bc_reqs[BLOCKIF_MAXREQ];
125 };
126
127 static pthread_once_t blockif_once = PTHREAD_ONCE_INIT;
128
129 struct blockif_sig_elem {
130         pthread_mutex_t                 bse_mtx;
131         pthread_cond_t                  bse_cond;
132         int                             bse_pending;
133         struct blockif_sig_elem         *bse_next;
134 };
135
136 static struct blockif_sig_elem *blockif_bse_head;
137
138 static int
139 blockif_enqueue(struct blockif_ctxt *bc, struct blockif_req *breq,
140                 enum blockop op)
141 {
142         struct blockif_elem *be, *tbe;
143         off_t off;
144         int i;
145
146         be = TAILQ_FIRST(&bc->bc_freeq);
147         assert(be != NULL);
148         assert(be->be_status == BST_FREE);
149         TAILQ_REMOVE(&bc->bc_freeq, be, be_link);
150         be->be_req = breq;
151         be->be_op = op;
152         switch (op) {
153         case BOP_READ:
154         case BOP_WRITE:
155         case BOP_DELETE:
156                 off = breq->br_offset;
157                 for (i = 0; i < breq->br_iovcnt; i++)
158                         off += breq->br_iov[i].iov_len;
159                 break;
160         default:
161                 off = OFF_MAX;
162         }
163         be->be_block = off;
164         TAILQ_FOREACH(tbe, &bc->bc_pendq, be_link) {
165                 if (tbe->be_block == breq->br_offset)
166                         break;
167         }
168         if (tbe == NULL) {
169                 TAILQ_FOREACH(tbe, &bc->bc_busyq, be_link) {
170                         if (tbe->be_block == breq->br_offset)
171                                 break;
172                 }
173         }
174         if (tbe == NULL)
175                 be->be_status = BST_PEND;
176         else
177                 be->be_status = BST_BLOCK;
178         TAILQ_INSERT_TAIL(&bc->bc_pendq, be, be_link);
179         return (be->be_status == BST_PEND);
180 }
181
182 static int
183 blockif_dequeue(struct blockif_ctxt *bc, pthread_t t, struct blockif_elem **bep)
184 {
185         struct blockif_elem *be;
186
187         TAILQ_FOREACH(be, &bc->bc_pendq, be_link) {
188                 if (be->be_status == BST_PEND)
189                         break;
190                 assert(be->be_status == BST_BLOCK);
191         }
192         if (be == NULL)
193                 return (0);
194         TAILQ_REMOVE(&bc->bc_pendq, be, be_link);
195         be->be_status = BST_BUSY;
196         be->be_tid = t;
197         TAILQ_INSERT_TAIL(&bc->bc_busyq, be, be_link);
198         *bep = be;
199         return (1);
200 }
201
202 static void
203 blockif_complete(struct blockif_ctxt *bc, struct blockif_elem *be)
204 {
205         struct blockif_elem *tbe;
206
207         if (be->be_status == BST_DONE || be->be_status == BST_BUSY)
208                 TAILQ_REMOVE(&bc->bc_busyq, be, be_link);
209         else
210                 TAILQ_REMOVE(&bc->bc_pendq, be, be_link);
211         TAILQ_FOREACH(tbe, &bc->bc_pendq, be_link) {
212                 if (tbe->be_req->br_offset == be->be_block)
213                         tbe->be_status = BST_PEND;
214         }
215         be->be_tid = 0;
216         be->be_status = BST_FREE;
217         be->be_req = NULL;
218         TAILQ_INSERT_TAIL(&bc->bc_freeq, be, be_link);
219 }
220
221 static int
222 blockif_flush_bc(struct blockif_ctxt *bc)
223 {
224         if (bc->bc_ischr) {
225                 if (ioctl(bc->bc_fd, DIOCGFLUSH))
226                         return (errno);
227         } else if (fsync(bc->bc_fd))
228                 return (errno);
229
230         return (0);
231 }
232
233 static void
234 blockif_proc(struct blockif_ctxt *bc, struct blockif_elem *be, uint8_t *buf)
235 {
236         struct blockif_req *br;
237         off_t arg[2];
238         ssize_t clen, len, off, boff, voff;
239         int i, err;
240         struct spacectl_range range;
241
242         br = be->be_req;
243         if (br->br_iovcnt <= 1)
244                 buf = NULL;
245         err = 0;
246         switch (be->be_op) {
247         case BOP_READ:
248                 if (buf == NULL) {
249                         if ((len = preadv(bc->bc_fd, br->br_iov, br->br_iovcnt,
250                                    br->br_offset)) < 0)
251                                 err = errno;
252                         else
253                                 br->br_resid -= len;
254                         break;
255                 }
256                 i = 0;
257                 off = voff = 0;
258                 while (br->br_resid > 0) {
259                         len = MIN(br->br_resid, MAXPHYS);
260                         if (pread(bc->bc_fd, buf, len, br->br_offset +
261                             off) < 0) {
262                                 err = errno;
263                                 break;
264                         }
265                         boff = 0;
266                         do {
267                                 clen = MIN(len - boff, br->br_iov[i].iov_len -
268                                     voff);
269                                 memcpy(br->br_iov[i].iov_base + voff,
270                                     buf + boff, clen);
271                                 if (clen < br->br_iov[i].iov_len - voff)
272                                         voff += clen;
273                                 else {
274                                         i++;
275                                         voff = 0;
276                                 }
277                                 boff += clen;
278                         } while (boff < len);
279                         off += len;
280                         br->br_resid -= len;
281                 }
282                 break;
283         case BOP_WRITE:
284                 if (bc->bc_rdonly) {
285                         err = EROFS;
286                         break;
287                 }
288                 if (buf == NULL) {
289                         if ((len = pwritev(bc->bc_fd, br->br_iov, br->br_iovcnt,
290                                     br->br_offset)) < 0)
291                                 err = errno;
292                         else
293                                 br->br_resid -= len;
294                         break;
295                 }
296                 i = 0;
297                 off = voff = 0;
298                 while (br->br_resid > 0) {
299                         len = MIN(br->br_resid, MAXPHYS);
300                         boff = 0;
301                         do {
302                                 clen = MIN(len - boff, br->br_iov[i].iov_len -
303                                     voff);
304                                 memcpy(buf + boff,
305                                     br->br_iov[i].iov_base + voff, clen);
306                                 if (clen < br->br_iov[i].iov_len - voff)
307                                         voff += clen;
308                                 else {
309                                         i++;
310                                         voff = 0;
311                                 }
312                                 boff += clen;
313                         } while (boff < len);
314                         if (pwrite(bc->bc_fd, buf, len, br->br_offset +
315                             off) < 0) {
316                                 err = errno;
317                                 break;
318                         }
319                         off += len;
320                         br->br_resid -= len;
321                 }
322                 break;
323         case BOP_FLUSH:
324                 err = blockif_flush_bc(bc);
325                 break;
326         case BOP_DELETE:
327                 if (!bc->bc_candelete)
328                         err = EOPNOTSUPP;
329                 else if (bc->bc_rdonly)
330                         err = EROFS;
331                 else if (bc->bc_ischr) {
332                         arg[0] = br->br_offset;
333                         arg[1] = br->br_resid;
334                         if (ioctl(bc->bc_fd, DIOCGDELETE, arg))
335                                 err = errno;
336                         else
337                                 br->br_resid = 0;
338                 } else {
339                         range.r_offset = br->br_offset;
340                         range.r_len = br->br_resid;
341
342                         while (range.r_len > 0) {
343                                 if (fspacectl(bc->bc_fd, SPACECTL_DEALLOC,
344                                     &range, 0, &range) != 0) {
345                                         err = errno;
346                                         break;
347                                 }
348                         }
349                         if (err == 0)
350                                 br->br_resid = 0;
351                 }
352                 break;
353         default:
354                 err = EINVAL;
355                 break;
356         }
357
358         be->be_status = BST_DONE;
359
360         (*br->br_callback)(br, err);
361 }
362
363 static inline bool
364 blockif_empty(const struct blockif_ctxt *bc)
365 {
366         return (TAILQ_EMPTY(&bc->bc_pendq) && TAILQ_EMPTY(&bc->bc_busyq));
367 }
368
369 static void *
370 blockif_thr(void *arg)
371 {
372         struct blockif_ctxt *bc;
373         struct blockif_elem *be;
374         pthread_t t;
375         uint8_t *buf;
376
377         bc = arg;
378         if (bc->bc_isgeom)
379                 buf = malloc(MAXPHYS);
380         else
381                 buf = NULL;
382         t = pthread_self();
383
384         pthread_mutex_lock(&bc->bc_mtx);
385         for (;;) {
386                 while (blockif_dequeue(bc, t, &be)) {
387                         pthread_mutex_unlock(&bc->bc_mtx);
388                         blockif_proc(bc, be, buf);
389                         pthread_mutex_lock(&bc->bc_mtx);
390                         blockif_complete(bc, be);
391                 }
392
393                 /* If none to work, notify the main thread */
394                 if (blockif_empty(bc))
395                         pthread_cond_broadcast(&bc->bc_work_done_cond);
396
397                 /* Check ctxt status here to see if exit requested */
398                 if (bc->bc_closing)
399                         break;
400
401                 pthread_cond_wait(&bc->bc_cond, &bc->bc_mtx);
402         }
403         pthread_mutex_unlock(&bc->bc_mtx);
404
405         if (buf)
406                 free(buf);
407         pthread_exit(NULL);
408         return (NULL);
409 }
410
411 static void
412 blockif_sigcont_handler(int signal __unused, enum ev_type type __unused,
413     void *arg __unused)
414 {
415         struct blockif_sig_elem *bse;
416
417         for (;;) {
418                 /*
419                  * Process the entire list even if not intended for
420                  * this thread.
421                  */
422                 do {
423                         bse = blockif_bse_head;
424                         if (bse == NULL)
425                                 return;
426                 } while (!atomic_cmpset_ptr((uintptr_t *)&blockif_bse_head,
427                                             (uintptr_t)bse,
428                                             (uintptr_t)bse->bse_next));
429
430                 pthread_mutex_lock(&bse->bse_mtx);
431                 bse->bse_pending = 0;
432                 pthread_cond_signal(&bse->bse_cond);
433                 pthread_mutex_unlock(&bse->bse_mtx);
434         }
435 }
436
437 static void
438 blockif_init(void)
439 {
440         mevent_add(SIGCONT, EVF_SIGNAL, blockif_sigcont_handler, NULL);
441         (void) signal(SIGCONT, SIG_IGN);
442 }
443
444 int
445 blockif_legacy_config(nvlist_t *nvl, const char *opts)
446 {
447         char *cp, *path;
448
449         if (opts == NULL)
450                 return (0);
451
452         cp = strchr(opts, ',');
453         if (cp == NULL) {
454                 set_config_value_node(nvl, "path", opts);
455                 return (0);
456         }
457         path = strndup(opts, cp - opts);
458         set_config_value_node(nvl, "path", path);
459         free(path);
460         return (pci_parse_legacy_config(nvl, cp + 1));
461 }
462
463 struct blockif_ctxt *
464 blockif_open(nvlist_t *nvl, const char *ident)
465 {
466         char tname[MAXCOMLEN + 1];
467         char name[MAXPATHLEN];
468         const char *path, *pssval, *ssval;
469         char *cp;
470         struct blockif_ctxt *bc;
471         struct stat sbuf;
472         struct diocgattr_arg arg;
473         off_t size, psectsz, psectoff;
474         int extra, fd, i, sectsz;
475         int ro, candelete, geom, ssopt, pssopt;
476         int nodelete;
477
478 #ifndef WITHOUT_CAPSICUM
479         cap_rights_t rights;
480         cap_ioctl_t cmds[] = { DIOCGFLUSH, DIOCGDELETE, DIOCGMEDIASIZE };
481 #endif
482
483         pthread_once(&blockif_once, blockif_init);
484
485         fd = -1;
486         extra = 0;
487         ssopt = 0;
488         ro = 0;
489         nodelete = 0;
490
491         if (get_config_bool_node_default(nvl, "nocache", false))
492                 extra |= O_DIRECT;
493         if (get_config_bool_node_default(nvl, "nodelete", false))
494                 nodelete = 1;
495         if (get_config_bool_node_default(nvl, "sync", false) ||
496             get_config_bool_node_default(nvl, "direct", false))
497                 extra |= O_SYNC;
498         if (get_config_bool_node_default(nvl, "ro", false))
499                 ro = 1;
500         ssval = get_config_value_node(nvl, "sectorsize");
501         if (ssval != NULL) {
502                 ssopt = strtol(ssval, &cp, 10);
503                 if (cp == ssval) {
504                         EPRINTLN("Invalid sector size \"%s\"", ssval);
505                         goto err;
506                 }
507                 if (*cp == '\0') {
508                         pssopt = ssopt;
509                 } else if (*cp == '/') {
510                         pssval = cp + 1;
511                         pssopt = strtol(pssval, &cp, 10);
512                         if (cp == pssval || *cp != '\0') {
513                                 EPRINTLN("Invalid sector size \"%s\"", ssval);
514                                 goto err;
515                         }
516                 } else {
517                         EPRINTLN("Invalid sector size \"%s\"", ssval);
518                         goto err;
519                 }
520         }
521
522         path = get_config_value_node(nvl, "path");
523         if (path == NULL) {
524                 EPRINTLN("Missing \"path\" for block device.");
525                 goto err;
526         }
527
528         fd = open(path, (ro ? O_RDONLY : O_RDWR) | extra);
529         if (fd < 0 && !ro) {
530                 /* Attempt a r/w fail with a r/o open */
531                 fd = open(path, O_RDONLY | extra);
532                 ro = 1;
533         }
534
535         if (fd < 0) {
536                 warn("Could not open backing file: %s", path);
537                 goto err;
538         }
539
540         if (fstat(fd, &sbuf) < 0) {
541                 warn("Could not stat backing file %s", path);
542                 goto err;
543         }
544
545 #ifndef WITHOUT_CAPSICUM
546         cap_rights_init(&rights, CAP_FSYNC, CAP_IOCTL, CAP_READ, CAP_SEEK,
547             CAP_WRITE, CAP_FSTAT, CAP_EVENT, CAP_FPATHCONF);
548         if (ro)
549                 cap_rights_clear(&rights, CAP_FSYNC, CAP_WRITE);
550
551         if (caph_rights_limit(fd, &rights) == -1)
552                 errx(EX_OSERR, "Unable to apply rights for sandbox");
553 #endif
554
555         /*
556          * Deal with raw devices
557          */
558         size = sbuf.st_size;
559         sectsz = DEV_BSIZE;
560         psectsz = psectoff = 0;
561         candelete = geom = 0;
562         if (S_ISCHR(sbuf.st_mode)) {
563                 if (ioctl(fd, DIOCGMEDIASIZE, &size) < 0 ||
564                     ioctl(fd, DIOCGSECTORSIZE, &sectsz)) {
565                         perror("Could not fetch dev blk/sector size");
566                         goto err;
567                 }
568                 assert(size != 0);
569                 assert(sectsz != 0);
570                 if (ioctl(fd, DIOCGSTRIPESIZE, &psectsz) == 0 && psectsz > 0)
571                         ioctl(fd, DIOCGSTRIPEOFFSET, &psectoff);
572                 strlcpy(arg.name, "GEOM::candelete", sizeof(arg.name));
573                 arg.len = sizeof(arg.value.i);
574                 if (nodelete == 0 && ioctl(fd, DIOCGATTR, &arg) == 0)
575                         candelete = arg.value.i;
576                 if (ioctl(fd, DIOCGPROVIDERNAME, name) == 0)
577                         geom = 1;
578         } else {
579                 psectsz = sbuf.st_blksize;
580                 /* Avoid fallback implementation */
581                 candelete = fpathconf(fd, _PC_DEALLOC_PRESENT) == 1;
582         }
583
584 #ifndef WITHOUT_CAPSICUM
585         if (caph_ioctls_limit(fd, cmds, nitems(cmds)) == -1)
586                 errx(EX_OSERR, "Unable to apply rights for sandbox");
587 #endif
588
589         if (ssopt != 0) {
590                 if (!powerof2(ssopt) || !powerof2(pssopt) || ssopt < 512 ||
591                     ssopt > pssopt) {
592                         EPRINTLN("Invalid sector size %d/%d",
593                             ssopt, pssopt);
594                         goto err;
595                 }
596
597                 /*
598                  * Some backend drivers (e.g. cd0, ada0) require that the I/O
599                  * size be a multiple of the device's sector size.
600                  *
601                  * Validate that the emulated sector size complies with this
602                  * requirement.
603                  */
604                 if (S_ISCHR(sbuf.st_mode)) {
605                         if (ssopt < sectsz || (ssopt % sectsz) != 0) {
606                                 EPRINTLN("Sector size %d incompatible "
607                                     "with underlying device sector size %d",
608                                     ssopt, sectsz);
609                                 goto err;
610                         }
611                 }
612
613                 sectsz = ssopt;
614                 psectsz = pssopt;
615                 psectoff = 0;
616         }
617
618         bc = calloc(1, sizeof(struct blockif_ctxt));
619         if (bc == NULL) {
620                 perror("calloc");
621                 goto err;
622         }
623
624         bc->bc_magic = BLOCKIF_SIG;
625         bc->bc_fd = fd;
626         bc->bc_ischr = S_ISCHR(sbuf.st_mode);
627         bc->bc_isgeom = geom;
628         bc->bc_candelete = candelete;
629         bc->bc_rdonly = ro;
630         bc->bc_size = size;
631         bc->bc_sectsz = sectsz;
632         bc->bc_psectsz = psectsz;
633         bc->bc_psectoff = psectoff;
634         pthread_mutex_init(&bc->bc_mtx, NULL);
635         pthread_cond_init(&bc->bc_cond, NULL);
636         bc->bc_paused = 0;
637         pthread_cond_init(&bc->bc_work_done_cond, NULL);
638         TAILQ_INIT(&bc->bc_freeq);
639         TAILQ_INIT(&bc->bc_pendq);
640         TAILQ_INIT(&bc->bc_busyq);
641         for (i = 0; i < BLOCKIF_MAXREQ; i++) {
642                 bc->bc_reqs[i].be_status = BST_FREE;
643                 TAILQ_INSERT_HEAD(&bc->bc_freeq, &bc->bc_reqs[i], be_link);
644         }
645
646         for (i = 0; i < BLOCKIF_NUMTHR; i++) {
647                 pthread_create(&bc->bc_btid[i], NULL, blockif_thr, bc);
648                 snprintf(tname, sizeof(tname), "blk-%s-%d", ident, i);
649                 pthread_set_name_np(bc->bc_btid[i], tname);
650         }
651
652         return (bc);
653 err:
654         if (fd >= 0)
655                 close(fd);
656         return (NULL);
657 }
658
659 static void
660 blockif_resized(int fd, enum ev_type type __unused, void *arg)
661 {
662         struct blockif_ctxt *bc;
663         struct stat sb;
664         off_t mediasize;
665
666         if (fstat(fd, &sb) != 0)
667                 return;
668
669         if (S_ISCHR(sb.st_mode)) {
670                 if (ioctl(fd, DIOCGMEDIASIZE, &mediasize) < 0) {
671                         EPRINTLN("blockif_resized: get mediasize failed: %s",
672                             strerror(errno));
673                         return;
674                 }
675         } else
676                 mediasize = sb.st_size;
677
678         bc = arg;
679         pthread_mutex_lock(&bc->bc_mtx);
680         if (mediasize != bc->bc_size) {
681                 bc->bc_size = mediasize;
682                 bc->bc_resize_cb(bc, bc->bc_resize_cb_arg, bc->bc_size);
683         }
684         pthread_mutex_unlock(&bc->bc_mtx);
685 }
686
687 int
688 blockif_register_resize_callback(struct blockif_ctxt *bc, blockif_resize_cb *cb,
689     void *cb_arg)
690 {
691         struct stat sb;
692         int err;
693
694         if (cb == NULL)
695                 return (EINVAL);
696
697         err = 0;
698
699         pthread_mutex_lock(&bc->bc_mtx);
700         if (bc->bc_resize_cb != NULL) {
701                 err = EBUSY;
702                 goto out;
703         }
704
705         assert(bc->bc_closing == 0);
706
707         if (fstat(bc->bc_fd, &sb) != 0) {
708                 err = errno;
709                 goto out;
710         }
711
712         bc->bc_resize_event = mevent_add_flags(bc->bc_fd, EVF_VNODE,
713             EVFF_ATTRIB, blockif_resized, bc);
714         if (bc->bc_resize_event == NULL) {
715                 err = ENXIO;
716                 goto out;
717         }
718
719         bc->bc_resize_cb = cb;
720         bc->bc_resize_cb_arg = cb_arg;
721 out:
722         pthread_mutex_unlock(&bc->bc_mtx);
723
724         return (err);
725 }
726
727 static int
728 blockif_request(struct blockif_ctxt *bc, struct blockif_req *breq,
729                 enum blockop op)
730 {
731         int err;
732
733         err = 0;
734
735         pthread_mutex_lock(&bc->bc_mtx);
736         assert(!bc->bc_paused);
737         if (!TAILQ_EMPTY(&bc->bc_freeq)) {
738                 /*
739                  * Enqueue and inform the block i/o thread
740                  * that there is work available
741                  */
742                 if (blockif_enqueue(bc, breq, op))
743                         pthread_cond_signal(&bc->bc_cond);
744         } else {
745                 /*
746                  * Callers are not allowed to enqueue more than
747                  * the specified blockif queue limit. Return an
748                  * error to indicate that the queue length has been
749                  * exceeded.
750                  */
751                 err = E2BIG;
752         }
753         pthread_mutex_unlock(&bc->bc_mtx);
754
755         return (err);
756 }
757
758 int
759 blockif_read(struct blockif_ctxt *bc, struct blockif_req *breq)
760 {
761         assert(bc->bc_magic == BLOCKIF_SIG);
762         return (blockif_request(bc, breq, BOP_READ));
763 }
764
765 int
766 blockif_write(struct blockif_ctxt *bc, struct blockif_req *breq)
767 {
768         assert(bc->bc_magic == BLOCKIF_SIG);
769         return (blockif_request(bc, breq, BOP_WRITE));
770 }
771
772 int
773 blockif_flush(struct blockif_ctxt *bc, struct blockif_req *breq)
774 {
775         assert(bc->bc_magic == BLOCKIF_SIG);
776         return (blockif_request(bc, breq, BOP_FLUSH));
777 }
778
779 int
780 blockif_delete(struct blockif_ctxt *bc, struct blockif_req *breq)
781 {
782         assert(bc->bc_magic == BLOCKIF_SIG);
783         return (blockif_request(bc, breq, BOP_DELETE));
784 }
785
786 int
787 blockif_cancel(struct blockif_ctxt *bc, struct blockif_req *breq)
788 {
789         struct blockif_elem *be;
790
791         assert(bc->bc_magic == BLOCKIF_SIG);
792
793         pthread_mutex_lock(&bc->bc_mtx);
794         /* XXX: not waiting while paused */
795
796         /*
797          * Check pending requests.
798          */
799         TAILQ_FOREACH(be, &bc->bc_pendq, be_link) {
800                 if (be->be_req == breq)
801                         break;
802         }
803         if (be != NULL) {
804                 /*
805                  * Found it.
806                  */
807                 blockif_complete(bc, be);
808                 pthread_mutex_unlock(&bc->bc_mtx);
809
810                 return (0);
811         }
812
813         /*
814          * Check in-flight requests.
815          */
816         TAILQ_FOREACH(be, &bc->bc_busyq, be_link) {
817                 if (be->be_req == breq)
818                         break;
819         }
820         if (be == NULL) {
821                 /*
822                  * Didn't find it.
823                  */
824                 pthread_mutex_unlock(&bc->bc_mtx);
825                 return (EINVAL);
826         }
827
828         /*
829          * Interrupt the processing thread to force it return
830          * prematurely via it's normal callback path.
831          */
832         while (be->be_status == BST_BUSY) {
833                 struct blockif_sig_elem bse, *old_head;
834
835                 pthread_mutex_init(&bse.bse_mtx, NULL);
836                 pthread_cond_init(&bse.bse_cond, NULL);
837
838                 bse.bse_pending = 1;
839
840                 do {
841                         old_head = blockif_bse_head;
842                         bse.bse_next = old_head;
843                 } while (!atomic_cmpset_ptr((uintptr_t *)&blockif_bse_head,
844                                             (uintptr_t)old_head,
845                                             (uintptr_t)&bse));
846
847                 pthread_kill(be->be_tid, SIGCONT);
848
849                 pthread_mutex_lock(&bse.bse_mtx);
850                 while (bse.bse_pending)
851                         pthread_cond_wait(&bse.bse_cond, &bse.bse_mtx);
852                 pthread_mutex_unlock(&bse.bse_mtx);
853         }
854
855         pthread_mutex_unlock(&bc->bc_mtx);
856
857         /*
858          * The processing thread has been interrupted.  Since it's not
859          * clear if the callback has been invoked yet, return EBUSY.
860          */
861         return (EBUSY);
862 }
863
864 int
865 blockif_close(struct blockif_ctxt *bc)
866 {
867         void *jval;
868         int i;
869
870         assert(bc->bc_magic == BLOCKIF_SIG);
871
872         /*
873          * Stop the block i/o thread
874          */
875         pthread_mutex_lock(&bc->bc_mtx);
876         bc->bc_closing = 1;
877         if (bc->bc_resize_event != NULL)
878                 mevent_disable(bc->bc_resize_event);
879         pthread_mutex_unlock(&bc->bc_mtx);
880         pthread_cond_broadcast(&bc->bc_cond);
881         for (i = 0; i < BLOCKIF_NUMTHR; i++)
882                 pthread_join(bc->bc_btid[i], &jval);
883
884         /* XXX Cancel queued i/o's ??? */
885
886         /*
887          * Release resources
888          */
889         bc->bc_magic = 0;
890         close(bc->bc_fd);
891         free(bc);
892
893         return (0);
894 }
895
896 /*
897  * Return virtual C/H/S values for a given block. Use the algorithm
898  * outlined in the VHD specification to calculate values.
899  */
900 void
901 blockif_chs(struct blockif_ctxt *bc, uint16_t *c, uint8_t *h, uint8_t *s)
902 {
903         off_t sectors;          /* total sectors of the block dev */
904         off_t hcyl;             /* cylinders times heads */
905         uint16_t secpt;         /* sectors per track */
906         uint8_t heads;
907
908         assert(bc->bc_magic == BLOCKIF_SIG);
909
910         sectors = bc->bc_size / bc->bc_sectsz;
911
912         /* Clamp the size to the largest possible with CHS */
913         if (sectors > 65535UL*16*255)
914                 sectors = 65535UL*16*255;
915
916         if (sectors >= 65536UL*16*63) {
917                 secpt = 255;
918                 heads = 16;
919                 hcyl = sectors / secpt;
920         } else {
921                 secpt = 17;
922                 hcyl = sectors / secpt;
923                 heads = (hcyl + 1023) / 1024;
924
925                 if (heads < 4)
926                         heads = 4;
927
928                 if (hcyl >= (heads * 1024) || heads > 16) {
929                         secpt = 31;
930                         heads = 16;
931                         hcyl = sectors / secpt;
932                 }
933                 if (hcyl >= (heads * 1024)) {
934                         secpt = 63;
935                         heads = 16;
936                         hcyl = sectors / secpt;
937                 }
938         }
939
940         *c = hcyl / heads;
941         *h = heads;
942         *s = secpt;
943 }
944
945 /*
946  * Accessors
947  */
948 off_t
949 blockif_size(struct blockif_ctxt *bc)
950 {
951         assert(bc->bc_magic == BLOCKIF_SIG);
952         return (bc->bc_size);
953 }
954
955 int
956 blockif_sectsz(struct blockif_ctxt *bc)
957 {
958         assert(bc->bc_magic == BLOCKIF_SIG);
959         return (bc->bc_sectsz);
960 }
961
962 void
963 blockif_psectsz(struct blockif_ctxt *bc, int *size, int *off)
964 {
965         assert(bc->bc_magic == BLOCKIF_SIG);
966         *size = bc->bc_psectsz;
967         *off = bc->bc_psectoff;
968 }
969
970 int
971 blockif_queuesz(struct blockif_ctxt *bc)
972 {
973         assert(bc->bc_magic == BLOCKIF_SIG);
974         return (BLOCKIF_MAXREQ - 1);
975 }
976
977 int
978 blockif_is_ro(struct blockif_ctxt *bc)
979 {
980         assert(bc->bc_magic == BLOCKIF_SIG);
981         return (bc->bc_rdonly);
982 }
983
984 int
985 blockif_candelete(struct blockif_ctxt *bc)
986 {
987         assert(bc->bc_magic == BLOCKIF_SIG);
988         return (bc->bc_candelete);
989 }
990
991 #ifdef BHYVE_SNAPSHOT
992 void
993 blockif_pause(struct blockif_ctxt *bc)
994 {
995         assert(bc != NULL);
996         assert(bc->bc_magic == BLOCKIF_SIG);
997
998         pthread_mutex_lock(&bc->bc_mtx);
999         bc->bc_paused = 1;
1000
1001         /* The interface is paused. Wait for workers to finish their work */
1002         while (!blockif_empty(bc))
1003                 pthread_cond_wait(&bc->bc_work_done_cond, &bc->bc_mtx);
1004         pthread_mutex_unlock(&bc->bc_mtx);
1005
1006         if (blockif_flush_bc(bc))
1007                 fprintf(stderr, "%s: [WARN] failed to flush backing file.\r\n",
1008                         __func__);
1009 }
1010
1011 void
1012 blockif_resume(struct blockif_ctxt *bc)
1013 {
1014         assert(bc != NULL);
1015         assert(bc->bc_magic == BLOCKIF_SIG);
1016
1017         pthread_mutex_lock(&bc->bc_mtx);
1018         bc->bc_paused = 0;
1019         pthread_mutex_unlock(&bc->bc_mtx);
1020 }
1021 #endif  /* BHYVE_SNAPSHOT */