2 * Copyright (C) 2009-2010 Nippon Telegraph and Telephone Corporation.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License version
6 * 2 as published by the Free Software Foundation.
8 * You should have received a copy of the GNU General Public License
9 * along with this program. If not, see <http://www.gnu.org/licenses/>.
11 * Contributions after 2012-01-13 are licensed under the terms of the
12 * GNU GPL, version 2 or (at your option) any later version.
15 #include "qemu/osdep.h"
16 #include "qapi/error.h"
18 #include "qemu/error-report.h"
19 #include "qemu/sockets.h"
20 #include "block/block_int.h"
21 #include "sysemu/block-backend.h"
22 #include "qemu/bitops.h"
23 #include "qemu/cutils.h"
25 #define SD_PROTO_VER 0x01
27 #define SD_DEFAULT_ADDR "localhost"
28 #define SD_DEFAULT_PORT 7000
30 #define SD_OP_CREATE_AND_WRITE_OBJ 0x01
31 #define SD_OP_READ_OBJ 0x02
32 #define SD_OP_WRITE_OBJ 0x03
33 /* 0x04 is used internally by Sheepdog */
35 #define SD_OP_NEW_VDI 0x11
36 #define SD_OP_LOCK_VDI 0x12
37 #define SD_OP_RELEASE_VDI 0x13
38 #define SD_OP_GET_VDI_INFO 0x14
39 #define SD_OP_READ_VDIS 0x15
40 #define SD_OP_FLUSH_VDI 0x16
41 #define SD_OP_DEL_VDI 0x17
42 #define SD_OP_GET_CLUSTER_DEFAULT 0x18
44 #define SD_FLAG_CMD_WRITE 0x01
45 #define SD_FLAG_CMD_COW 0x02
46 #define SD_FLAG_CMD_CACHE 0x04 /* Writeback mode for cache */
47 #define SD_FLAG_CMD_DIRECT 0x08 /* Don't use cache */
49 #define SD_RES_SUCCESS 0x00 /* Success */
50 #define SD_RES_UNKNOWN 0x01 /* Unknown error */
51 #define SD_RES_NO_OBJ 0x02 /* No object found */
52 #define SD_RES_EIO 0x03 /* I/O error */
53 #define SD_RES_VDI_EXIST 0x04 /* Vdi exists already */
54 #define SD_RES_INVALID_PARMS 0x05 /* Invalid parameters */
55 #define SD_RES_SYSTEM_ERROR 0x06 /* System error */
56 #define SD_RES_VDI_LOCKED 0x07 /* Vdi is locked */
57 #define SD_RES_NO_VDI 0x08 /* No vdi found */
58 #define SD_RES_NO_BASE_VDI 0x09 /* No base vdi found */
59 #define SD_RES_VDI_READ 0x0A /* Cannot read requested vdi */
60 #define SD_RES_VDI_WRITE 0x0B /* Cannot write requested vdi */
61 #define SD_RES_BASE_VDI_READ 0x0C /* Cannot read base vdi */
62 #define SD_RES_BASE_VDI_WRITE 0x0D /* Cannot write base vdi */
63 #define SD_RES_NO_TAG 0x0E /* Requested tag is not found */
64 #define SD_RES_STARTUP 0x0F /* Sheepdog is on starting up */
65 #define SD_RES_VDI_NOT_LOCKED 0x10 /* Vdi is not locked */
66 #define SD_RES_SHUTDOWN 0x11 /* Sheepdog is shutting down */
67 #define SD_RES_NO_MEM 0x12 /* Cannot allocate memory */
68 #define SD_RES_FULL_VDI 0x13 /* we already have the maximum vdis */
69 #define SD_RES_VER_MISMATCH 0x14 /* Protocol version mismatch */
70 #define SD_RES_NO_SPACE 0x15 /* Server has no room for new objects */
71 #define SD_RES_WAIT_FOR_FORMAT 0x16 /* Waiting for a format operation */
72 #define SD_RES_WAIT_FOR_JOIN 0x17 /* Waiting for other nodes joining */
73 #define SD_RES_JOIN_FAILED 0x18 /* Target node had failed to join sheepdog */
74 #define SD_RES_HALT 0x19 /* Sheepdog is stopped serving IO request */
75 #define SD_RES_READONLY 0x1A /* Object is read-only */
80 * 0 - 19 (20 bits): data object space
81 * 20 - 31 (12 bits): reserved data object space
82 * 32 - 55 (24 bits): vdi object space
83 * 56 - 59 ( 4 bits): reserved vdi object space
84 * 60 - 63 ( 4 bits): object type identifier space
87 #define VDI_SPACE_SHIFT 32
88 #define VDI_BIT (UINT64_C(1) << 63)
89 #define VMSTATE_BIT (UINT64_C(1) << 62)
90 #define MAX_DATA_OBJS (UINT64_C(1) << 20)
91 #define MAX_CHILDREN 1024
92 #define SD_MAX_VDI_LEN 256
93 #define SD_MAX_VDI_TAG_LEN 256
94 #define SD_NR_VDIS (1U << 24)
95 #define SD_DATA_OBJ_SIZE (UINT64_C(1) << 22)
96 #define SD_MAX_VDI_SIZE (SD_DATA_OBJ_SIZE * MAX_DATA_OBJS)
97 #define SD_DEFAULT_BLOCK_SIZE_SHIFT 22
99 * For erasure coding, we use at most SD_EC_MAX_STRIP for data strips and
100 * (SD_EC_MAX_STRIP - 1) for parity strips
102 * SD_MAX_COPIES is sum of number of data strips and parity strips.
104 #define SD_EC_MAX_STRIP 16
105 #define SD_MAX_COPIES (SD_EC_MAX_STRIP * 2 - 1)
107 #define SD_INODE_SIZE (sizeof(SheepdogInode))
108 #define CURRENT_VDI_ID 0
110 #define LOCK_TYPE_NORMAL 0
111 #define LOCK_TYPE_SHARED 1 /* for iSCSI multipath */
113 typedef struct SheepdogReq {
119 uint32_t data_length;
120 uint32_t opcode_specific[8];
123 typedef struct SheepdogRsp {
129 uint32_t data_length;
131 uint32_t opcode_specific[7];
134 typedef struct SheepdogObjReq {
140 uint32_t data_length;
149 typedef struct SheepdogObjRsp {
155 uint32_t data_length;
163 typedef struct SheepdogVdiReq {
169 uint32_t data_length;
171 uint32_t base_vdi_id;
174 uint8_t store_policy;
175 uint8_t block_size_shift;
181 typedef struct SheepdogVdiRsp {
187 uint32_t data_length;
194 typedef struct SheepdogClusterRsp {
200 uint32_t data_length;
204 uint8_t block_size_shift;
207 } SheepdogClusterRsp;
209 typedef struct SheepdogInode {
210 char name[SD_MAX_VDI_LEN];
211 char tag[SD_MAX_VDI_TAG_LEN];
214 uint64_t vm_clock_nsec;
216 uint64_t vm_state_size;
217 uint16_t copy_policy;
219 uint8_t block_size_shift;
222 uint32_t parent_vdi_id;
223 uint32_t child_vdi_id[MAX_CHILDREN];
224 uint32_t data_vdi_id[MAX_DATA_OBJS];
227 #define SD_INODE_HEADER_SIZE offsetof(SheepdogInode, data_vdi_id)
230 * 64 bit FNV-1a non-zero initial basis
232 #define FNV1A_64_INIT ((uint64_t)0xcbf29ce484222325ULL)
235 * 64 bit Fowler/Noll/Vo FNV-1a hash code
237 static inline uint64_t fnv_64a_buf(void *buf, size_t len, uint64_t hval)
239 unsigned char *bp = buf;
240 unsigned char *be = bp + len;
242 hval ^= (uint64_t) *bp++;
243 hval += (hval << 1) + (hval << 4) + (hval << 5) +
244 (hval << 7) + (hval << 8) + (hval << 40);
249 static inline bool is_data_obj_writable(SheepdogInode *inode, unsigned int idx)
251 return inode->vdi_id == inode->data_vdi_id[idx];
254 static inline bool is_data_obj(uint64_t oid)
256 return !(VDI_BIT & oid);
259 static inline uint64_t data_oid_to_idx(uint64_t oid)
261 return oid & (MAX_DATA_OBJS - 1);
264 static inline uint32_t oid_to_vid(uint64_t oid)
266 return (oid & ~VDI_BIT) >> VDI_SPACE_SHIFT;
269 static inline uint64_t vid_to_vdi_oid(uint32_t vid)
271 return VDI_BIT | ((uint64_t)vid << VDI_SPACE_SHIFT);
274 static inline uint64_t vid_to_vmstate_oid(uint32_t vid, uint32_t idx)
276 return VMSTATE_BIT | ((uint64_t)vid << VDI_SPACE_SHIFT) | idx;
279 static inline uint64_t vid_to_data_oid(uint32_t vid, uint32_t idx)
281 return ((uint64_t)vid << VDI_SPACE_SHIFT) | idx;
284 static inline bool is_snapshot(struct SheepdogInode *inode)
286 return !!inode->snap_ctime;
289 static inline size_t count_data_objs(const struct SheepdogInode *inode)
291 return DIV_ROUND_UP(inode->vdi_size,
292 (1UL << inode->block_size_shift));
297 #define DPRINTF(fmt, args...) \
299 fprintf(stdout, "%s %d: " fmt, __func__, __LINE__, ##args); \
302 #define DPRINTF(fmt, args...)
305 typedef struct SheepdogAIOCB SheepdogAIOCB;
307 typedef struct AIOReq {
308 SheepdogAIOCB *aiocb;
309 unsigned int iov_offset;
314 unsigned int data_len;
319 QLIST_ENTRY(AIOReq) aio_siblings;
329 #define AIOCBOverlapping(x, y) \
330 (!(x->max_affect_data_idx < y->min_affect_data_idx \
331 || y->max_affect_data_idx < x->min_affect_data_idx))
333 struct SheepdogAIOCB {
342 enum AIOCBState aiocb_type;
344 Coroutine *coroutine;
345 void (*aio_done_func)(SheepdogAIOCB *);
350 uint32_t min_affect_data_idx;
351 uint32_t max_affect_data_idx;
354 * The difference between affect_data_idx and dirty_data_idx:
355 * affect_data_idx represents range of index of all request types.
356 * dirty_data_idx represents range of index updated by COW requests.
357 * dirty_data_idx is used for updating an inode object.
359 uint32_t min_dirty_data_idx;
360 uint32_t max_dirty_data_idx;
362 QLIST_ENTRY(SheepdogAIOCB) aiocb_siblings;
365 typedef struct BDRVSheepdogState {
366 BlockDriverState *bs;
367 AioContext *aio_context;
371 char name[SD_MAX_VDI_LEN];
373 uint32_t cache_flags;
374 bool discard_supported;
384 uint32_t aioreq_seq_num;
386 /* Every aio request must be linked to either of these queues. */
387 QLIST_HEAD(inflight_aio_head, AIOReq) inflight_aio_head;
388 QLIST_HEAD(failed_aio_head, AIOReq) failed_aio_head;
390 CoQueue overlapping_queue;
391 QLIST_HEAD(inflight_aiocb_head, SheepdogAIOCB) inflight_aiocb_head;
394 typedef struct BDRVSheepdogReopenState {
397 } BDRVSheepdogReopenState;
399 static const char * sd_strerror(int err)
403 static const struct {
407 {SD_RES_SUCCESS, "Success"},
408 {SD_RES_UNKNOWN, "Unknown error"},
409 {SD_RES_NO_OBJ, "No object found"},
410 {SD_RES_EIO, "I/O error"},
411 {SD_RES_VDI_EXIST, "VDI exists already"},
412 {SD_RES_INVALID_PARMS, "Invalid parameters"},
413 {SD_RES_SYSTEM_ERROR, "System error"},
414 {SD_RES_VDI_LOCKED, "VDI is already locked"},
415 {SD_RES_NO_VDI, "No vdi found"},
416 {SD_RES_NO_BASE_VDI, "No base VDI found"},
417 {SD_RES_VDI_READ, "Failed read the requested VDI"},
418 {SD_RES_VDI_WRITE, "Failed to write the requested VDI"},
419 {SD_RES_BASE_VDI_READ, "Failed to read the base VDI"},
420 {SD_RES_BASE_VDI_WRITE, "Failed to write the base VDI"},
421 {SD_RES_NO_TAG, "Failed to find the requested tag"},
422 {SD_RES_STARTUP, "The system is still booting"},
423 {SD_RES_VDI_NOT_LOCKED, "VDI isn't locked"},
424 {SD_RES_SHUTDOWN, "The system is shutting down"},
425 {SD_RES_NO_MEM, "Out of memory on the server"},
426 {SD_RES_FULL_VDI, "We already have the maximum vdis"},
427 {SD_RES_VER_MISMATCH, "Protocol version mismatch"},
428 {SD_RES_NO_SPACE, "Server has no space for new objects"},
429 {SD_RES_WAIT_FOR_FORMAT, "Sheepdog is waiting for a format operation"},
430 {SD_RES_WAIT_FOR_JOIN, "Sheepdog is waiting for other nodes joining"},
431 {SD_RES_JOIN_FAILED, "Target node had failed to join sheepdog"},
432 {SD_RES_HALT, "Sheepdog is stopped serving IO request"},
433 {SD_RES_READONLY, "Object is read-only"},
436 for (i = 0; i < ARRAY_SIZE(errors); ++i) {
437 if (errors[i].err == err) {
438 return errors[i].desc;
442 return "Invalid error code";
446 * Sheepdog I/O handling:
448 * 1. In sd_co_rw_vector, we send the I/O requests to the server and
449 * link the requests to the inflight_list in the
450 * BDRVSheepdogState. The function exits without waiting for
451 * receiving the response.
453 * 2. We receive the response in aio_read_response, the fd handler to
454 * the sheepdog connection. If metadata update is needed, we send
455 * the write request to the vdi object in sd_write_done, the write
456 * completion function. We switch back to sd_co_readv/writev after
457 * all the requests belonging to the AIOCB are finished.
460 static inline AIOReq *alloc_aio_req(BDRVSheepdogState *s, SheepdogAIOCB *acb,
461 uint64_t oid, unsigned int data_len,
462 uint64_t offset, uint8_t flags, bool create,
463 uint64_t base_oid, unsigned int iov_offset)
467 aio_req = g_malloc(sizeof(*aio_req));
468 aio_req->aiocb = acb;
469 aio_req->iov_offset = iov_offset;
471 aio_req->base_oid = base_oid;
472 aio_req->offset = offset;
473 aio_req->data_len = data_len;
474 aio_req->flags = flags;
475 aio_req->id = s->aioreq_seq_num++;
476 aio_req->create = create;
482 static inline void free_aio_req(BDRVSheepdogState *s, AIOReq *aio_req)
484 SheepdogAIOCB *acb = aio_req->aiocb;
486 acb->cancelable = false;
487 QLIST_REMOVE(aio_req, aio_siblings);
493 static void coroutine_fn sd_finish_aiocb(SheepdogAIOCB *acb)
495 qemu_coroutine_enter(acb->coroutine, NULL);
500 * Check whether the specified acb can be canceled
502 * We can cancel aio when any request belonging to the acb is:
503 * - Not processed by the sheepdog server.
504 * - Not linked to the inflight queue.
506 static bool sd_acb_cancelable(const SheepdogAIOCB *acb)
508 BDRVSheepdogState *s = acb->common.bs->opaque;
511 if (!acb->cancelable) {
515 QLIST_FOREACH(aioreq, &s->inflight_aio_head, aio_siblings) {
516 if (aioreq->aiocb == acb) {
524 static void sd_aio_cancel(BlockAIOCB *blockacb)
526 SheepdogAIOCB *acb = (SheepdogAIOCB *)blockacb;
527 BDRVSheepdogState *s = acb->common.bs->opaque;
528 AIOReq *aioreq, *next;
530 if (sd_acb_cancelable(acb)) {
531 /* Remove outstanding requests from failed queue. */
532 QLIST_FOREACH_SAFE(aioreq, &s->failed_aio_head, aio_siblings,
534 if (aioreq->aiocb == acb) {
535 free_aio_req(s, aioreq);
539 assert(acb->nr_pending == 0);
540 if (acb->common.cb) {
541 acb->common.cb(acb->common.opaque, -ECANCELED);
543 sd_finish_aiocb(acb);
547 static const AIOCBInfo sd_aiocb_info = {
548 .aiocb_size = sizeof(SheepdogAIOCB),
549 .cancel_async = sd_aio_cancel,
552 static SheepdogAIOCB *sd_aio_setup(BlockDriverState *bs, QEMUIOVector *qiov,
553 int64_t sector_num, int nb_sectors)
556 uint32_t object_size;
557 BDRVSheepdogState *s = bs->opaque;
559 object_size = (UINT32_C(1) << s->inode.block_size_shift);
561 acb = qemu_aio_get(&sd_aiocb_info, bs, NULL, NULL);
565 acb->sector_num = sector_num;
566 acb->nb_sectors = nb_sectors;
568 acb->aio_done_func = NULL;
569 acb->cancelable = true;
570 acb->coroutine = qemu_coroutine_self();
574 acb->min_affect_data_idx = acb->sector_num * BDRV_SECTOR_SIZE / object_size;
575 acb->max_affect_data_idx = (acb->sector_num * BDRV_SECTOR_SIZE +
576 acb->nb_sectors * BDRV_SECTOR_SIZE) / object_size;
578 acb->min_dirty_data_idx = UINT32_MAX;
579 acb->max_dirty_data_idx = 0;
584 /* Return -EIO in case of error, file descriptor on success */
585 static int connect_to_sdog(BDRVSheepdogState *s, Error **errp)
590 fd = unix_connect(s->host_spec, errp);
592 fd = inet_connect(s->host_spec, errp);
595 int ret = socket_set_nodelay(fd);
597 error_report("%s", strerror(errno));
603 qemu_set_nonblock(fd);
611 /* Return 0 on success and -errno in case of error */
612 static coroutine_fn int send_co_req(int sockfd, SheepdogReq *hdr, void *data,
617 ret = qemu_co_send(sockfd, hdr, sizeof(*hdr));
618 if (ret != sizeof(*hdr)) {
619 error_report("failed to send a req, %s", strerror(errno));
623 ret = qemu_co_send(sockfd, data, *wlen);
625 error_report("failed to send a req, %s", strerror(errno));
632 static void restart_co_req(void *opaque)
634 Coroutine *co = opaque;
636 qemu_coroutine_enter(co, NULL);
639 typedef struct SheepdogReqCo {
641 AioContext *aio_context;
650 static coroutine_fn void do_co_req(void *opaque)
654 SheepdogReqCo *srco = opaque;
655 int sockfd = srco->sockfd;
656 SheepdogReq *hdr = srco->hdr;
657 void *data = srco->data;
658 unsigned int *wlen = srco->wlen;
659 unsigned int *rlen = srco->rlen;
661 co = qemu_coroutine_self();
662 aio_set_fd_handler(srco->aio_context, sockfd, false,
663 NULL, restart_co_req, co);
665 ret = send_co_req(sockfd, hdr, data, wlen);
670 aio_set_fd_handler(srco->aio_context, sockfd, false,
671 restart_co_req, NULL, co);
673 ret = qemu_co_recv(sockfd, hdr, sizeof(*hdr));
674 if (ret != sizeof(*hdr)) {
675 error_report("failed to get a rsp, %s", strerror(errno));
680 if (*rlen > hdr->data_length) {
681 *rlen = hdr->data_length;
685 ret = qemu_co_recv(sockfd, data, *rlen);
687 error_report("failed to get the data, %s", strerror(errno));
694 /* there is at most one request for this sockfd, so it is safe to
695 * set each handler to NULL. */
696 aio_set_fd_handler(srco->aio_context, sockfd, false,
700 srco->finished = true;
704 * Send the request to the sheep in a synchronous manner.
706 * Return 0 on success, -errno in case of error.
708 static int do_req(int sockfd, AioContext *aio_context, SheepdogReq *hdr,
709 void *data, unsigned int *wlen, unsigned int *rlen)
712 SheepdogReqCo srco = {
714 .aio_context = aio_context,
723 if (qemu_in_coroutine()) {
726 co = qemu_coroutine_create(do_co_req);
727 qemu_coroutine_enter(co, &srco);
728 while (!srco.finished) {
729 aio_poll(aio_context, true);
736 static void coroutine_fn add_aio_request(BDRVSheepdogState *s, AIOReq *aio_req,
737 struct iovec *iov, int niov,
738 enum AIOCBState aiocb_type);
739 static void coroutine_fn resend_aioreq(BDRVSheepdogState *s, AIOReq *aio_req);
740 static int reload_inode(BDRVSheepdogState *s, uint32_t snapid, const char *tag);
741 static int get_sheep_fd(BDRVSheepdogState *s, Error **errp);
742 static void co_write_request(void *opaque);
744 static coroutine_fn void reconnect_to_sdog(void *opaque)
746 BDRVSheepdogState *s = opaque;
747 AIOReq *aio_req, *next;
749 aio_set_fd_handler(s->aio_context, s->fd, false, NULL,
754 /* Wait for outstanding write requests to be completed. */
755 while (s->co_send != NULL) {
756 co_write_request(opaque);
759 /* Try to reconnect the sheepdog server every one second. */
761 Error *local_err = NULL;
762 s->fd = get_sheep_fd(s, &local_err);
764 DPRINTF("Wait for connection to be established\n");
765 error_report_err(local_err);
766 co_aio_sleep_ns(bdrv_get_aio_context(s->bs), QEMU_CLOCK_REALTIME,
772 * Now we have to resend all the request in the inflight queue. However,
773 * resend_aioreq() can yield and newly created requests can be added to the
774 * inflight queue before the coroutine is resumed. To avoid mixing them, we
775 * have to move all the inflight requests to the failed queue before
776 * resend_aioreq() is called.
778 QLIST_FOREACH_SAFE(aio_req, &s->inflight_aio_head, aio_siblings, next) {
779 QLIST_REMOVE(aio_req, aio_siblings);
780 QLIST_INSERT_HEAD(&s->failed_aio_head, aio_req, aio_siblings);
783 /* Resend all the failed aio requests. */
784 while (!QLIST_EMPTY(&s->failed_aio_head)) {
785 aio_req = QLIST_FIRST(&s->failed_aio_head);
786 QLIST_REMOVE(aio_req, aio_siblings);
787 QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
788 resend_aioreq(s, aio_req);
793 * Receive responses of the I/O requests.
795 * This function is registered as a fd handler, and called from the
796 * main loop when s->fd is ready for reading responses.
798 static void coroutine_fn aio_read_response(void *opaque)
801 BDRVSheepdogState *s = opaque;
804 AIOReq *aio_req = NULL;
809 ret = qemu_co_recv(fd, &rsp, sizeof(rsp));
810 if (ret != sizeof(rsp)) {
811 error_report("failed to get the header, %s", strerror(errno));
815 /* find the right aio_req from the inflight aio list */
816 QLIST_FOREACH(aio_req, &s->inflight_aio_head, aio_siblings) {
817 if (aio_req->id == rsp.id) {
822 error_report("cannot find aio_req %x", rsp.id);
826 acb = aio_req->aiocb;
828 switch (acb->aiocb_type) {
829 case AIOCB_WRITE_UDATA:
830 /* this coroutine context is no longer suitable for co_recv
831 * because we may send data to update vdi objects */
833 if (!is_data_obj(aio_req->oid)) {
836 idx = data_oid_to_idx(aio_req->oid);
838 if (aio_req->create) {
840 * If the object is newly created one, we need to update
841 * the vdi object (metadata object). min_dirty_data_idx
842 * and max_dirty_data_idx are changed to include updated
843 * index between them.
845 if (rsp.result == SD_RES_SUCCESS) {
846 s->inode.data_vdi_id[idx] = s->inode.vdi_id;
847 acb->max_dirty_data_idx = MAX(idx, acb->max_dirty_data_idx);
848 acb->min_dirty_data_idx = MIN(idx, acb->min_dirty_data_idx);
852 case AIOCB_READ_UDATA:
853 ret = qemu_co_recvv(fd, acb->qiov->iov, acb->qiov->niov,
854 aio_req->iov_offset, rsp.data_length);
855 if (ret != rsp.data_length) {
856 error_report("failed to get the data, %s", strerror(errno));
860 case AIOCB_FLUSH_CACHE:
861 if (rsp.result == SD_RES_INVALID_PARMS) {
862 DPRINTF("disable cache since the server doesn't support it\n");
863 s->cache_flags = SD_FLAG_CMD_DIRECT;
864 rsp.result = SD_RES_SUCCESS;
867 case AIOCB_DISCARD_OBJ:
868 switch (rsp.result) {
869 case SD_RES_INVALID_PARMS:
870 error_report("sheep(%s) doesn't support discard command",
872 rsp.result = SD_RES_SUCCESS;
873 s->discard_supported = false;
880 switch (rsp.result) {
883 case SD_RES_READONLY:
884 if (s->inode.vdi_id == oid_to_vid(aio_req->oid)) {
885 ret = reload_inode(s, 0, "");
890 if (is_data_obj(aio_req->oid)) {
891 aio_req->oid = vid_to_data_oid(s->inode.vdi_id,
892 data_oid_to_idx(aio_req->oid));
894 aio_req->oid = vid_to_vdi_oid(s->inode.vdi_id);
896 resend_aioreq(s, aio_req);
900 error_report("%s", sd_strerror(rsp.result));
904 free_aio_req(s, aio_req);
905 if (!acb->nr_pending) {
907 * We've finished all requests which belong to the AIOCB, so
908 * we can switch back to sd_co_readv/writev now.
910 acb->aio_done_func(acb);
917 reconnect_to_sdog(opaque);
920 static void co_read_response(void *opaque)
922 BDRVSheepdogState *s = opaque;
925 s->co_recv = qemu_coroutine_create(aio_read_response);
928 qemu_coroutine_enter(s->co_recv, opaque);
931 static void co_write_request(void *opaque)
933 BDRVSheepdogState *s = opaque;
935 qemu_coroutine_enter(s->co_send, NULL);
939 * Return a socket descriptor to read/write objects.
941 * We cannot use this descriptor for other operations because
942 * the block driver may be on waiting response from the server.
944 static int get_sheep_fd(BDRVSheepdogState *s, Error **errp)
948 fd = connect_to_sdog(s, errp);
953 aio_set_fd_handler(s->aio_context, fd, false,
954 co_read_response, NULL, s);
958 static int sd_parse_uri(BDRVSheepdogState *s, const char *filename,
959 char *vdi, uint32_t *snapid, char *tag)
962 QueryParams *qp = NULL;
965 uri = uri_parse(filename);
971 if (!strcmp(uri->scheme, "sheepdog")) {
973 } else if (!strcmp(uri->scheme, "sheepdog+tcp")) {
975 } else if (!strcmp(uri->scheme, "sheepdog+unix")) {
982 if (uri->path == NULL || !strcmp(uri->path, "/")) {
986 pstrcpy(vdi, SD_MAX_VDI_LEN, uri->path + 1);
988 qp = query_params_parse(uri->query);
989 if (qp->n > 1 || (s->is_unix && !qp->n) || (!s->is_unix && qp->n)) {
995 /* sheepdog+unix:///vdiname?socket=path */
996 if (uri->server || uri->port || strcmp(qp->p[0].name, "socket")) {
1000 s->host_spec = g_strdup(qp->p[0].value);
1002 /* sheepdog[+tcp]://[host:port]/vdiname */
1003 s->host_spec = g_strdup_printf("%s:%d", uri->server ?: SD_DEFAULT_ADDR,
1004 uri->port ?: SD_DEFAULT_PORT);
1008 if (uri->fragment) {
1009 *snapid = strtoul(uri->fragment, NULL, 10);
1011 pstrcpy(tag, SD_MAX_VDI_TAG_LEN, uri->fragment);
1014 *snapid = CURRENT_VDI_ID; /* search current vdi */
1019 query_params_free(qp);
1026 * Parse a filename (old syntax)
1028 * filename must be one of the following formats:
1030 * 2. [vdiname]:[snapid]
1031 * 3. [vdiname]:[tag]
1032 * 4. [hostname]:[port]:[vdiname]
1033 * 5. [hostname]:[port]:[vdiname]:[snapid]
1034 * 6. [hostname]:[port]:[vdiname]:[tag]
1036 * You can boot from the snapshot images by specifying `snapid` or
1039 * You can run VMs outside the Sheepdog cluster by specifying
1040 * `hostname' and `port' (experimental).
1042 static int parse_vdiname(BDRVSheepdogState *s, const char *filename,
1043 char *vdi, uint32_t *snapid, char *tag)
1046 const char *host_spec, *vdi_spec;
1049 strstart(filename, "sheepdog:", (const char **)&filename);
1050 p = q = g_strdup(filename);
1052 /* count the number of separators */
1062 /* use the first two tokens as host_spec. */
1075 p = strchr(vdi_spec, ':');
1080 uri = g_strdup_printf("sheepdog://%s/%s", host_spec, vdi_spec);
1082 ret = sd_parse_uri(s, uri, vdi, snapid, tag);
1090 static int find_vdi_name(BDRVSheepdogState *s, const char *filename,
1091 uint32_t snapid, const char *tag, uint32_t *vid,
1092 bool lock, Error **errp)
1096 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
1097 unsigned int wlen, rlen = 0;
1098 char buf[SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN];
1100 fd = connect_to_sdog(s, errp);
1105 /* This pair of strncpy calls ensures that the buffer is zero-filled,
1106 * which is desirable since we'll soon be sending those bytes, and
1107 * don't want the send_req to read uninitialized data.
1109 strncpy(buf, filename, SD_MAX_VDI_LEN);
1110 strncpy(buf + SD_MAX_VDI_LEN, tag, SD_MAX_VDI_TAG_LEN);
1112 memset(&hdr, 0, sizeof(hdr));
1114 hdr.opcode = SD_OP_LOCK_VDI;
1115 hdr.type = LOCK_TYPE_NORMAL;
1117 hdr.opcode = SD_OP_GET_VDI_INFO;
1119 wlen = SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN;
1120 hdr.proto_ver = SD_PROTO_VER;
1121 hdr.data_length = wlen;
1122 hdr.snapid = snapid;
1123 hdr.flags = SD_FLAG_CMD_WRITE;
1125 ret = do_req(fd, s->aio_context, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
1127 error_setg_errno(errp, -ret, "cannot get vdi info");
1131 if (rsp->result != SD_RES_SUCCESS) {
1132 error_setg(errp, "cannot get vdi info, %s, %s %" PRIu32 " %s",
1133 sd_strerror(rsp->result), filename, snapid, tag);
1134 if (rsp->result == SD_RES_NO_VDI) {
1136 } else if (rsp->result == SD_RES_VDI_LOCKED) {
1151 static void coroutine_fn add_aio_request(BDRVSheepdogState *s, AIOReq *aio_req,
1152 struct iovec *iov, int niov,
1153 enum AIOCBState aiocb_type)
1155 int nr_copies = s->inode.nr_copies;
1157 unsigned int wlen = 0;
1159 uint64_t oid = aio_req->oid;
1160 unsigned int datalen = aio_req->data_len;
1161 uint64_t offset = aio_req->offset;
1162 uint8_t flags = aio_req->flags;
1163 uint64_t old_oid = aio_req->base_oid;
1164 bool create = aio_req->create;
1167 error_report("bug");
1170 memset(&hdr, 0, sizeof(hdr));
1172 switch (aiocb_type) {
1173 case AIOCB_FLUSH_CACHE:
1174 hdr.opcode = SD_OP_FLUSH_VDI;
1176 case AIOCB_READ_UDATA:
1177 hdr.opcode = SD_OP_READ_OBJ;
1180 case AIOCB_WRITE_UDATA:
1182 hdr.opcode = SD_OP_CREATE_AND_WRITE_OBJ;
1184 hdr.opcode = SD_OP_WRITE_OBJ;
1187 hdr.flags = SD_FLAG_CMD_WRITE | flags;
1189 case AIOCB_DISCARD_OBJ:
1190 hdr.opcode = SD_OP_WRITE_OBJ;
1191 hdr.flags = SD_FLAG_CMD_WRITE | flags;
1192 s->inode.data_vdi_id[data_oid_to_idx(oid)] = 0;
1193 offset = offsetof(SheepdogInode,
1194 data_vdi_id[data_oid_to_idx(oid)]);
1195 oid = vid_to_vdi_oid(s->inode.vdi_id);
1196 wlen = datalen = sizeof(uint32_t);
1200 if (s->cache_flags) {
1201 hdr.flags |= s->cache_flags;
1205 hdr.cow_oid = old_oid;
1206 hdr.copies = s->inode.nr_copies;
1208 hdr.data_length = datalen;
1209 hdr.offset = offset;
1211 hdr.id = aio_req->id;
1213 qemu_co_mutex_lock(&s->lock);
1214 s->co_send = qemu_coroutine_self();
1215 aio_set_fd_handler(s->aio_context, s->fd, false,
1216 co_read_response, co_write_request, s);
1217 socket_set_cork(s->fd, 1);
1220 ret = qemu_co_send(s->fd, &hdr, sizeof(hdr));
1221 if (ret != sizeof(hdr)) {
1222 error_report("failed to send a req, %s", strerror(errno));
1227 ret = qemu_co_sendv(s->fd, iov, niov, aio_req->iov_offset, wlen);
1229 error_report("failed to send a data, %s", strerror(errno));
1233 socket_set_cork(s->fd, 0);
1234 aio_set_fd_handler(s->aio_context, s->fd, false,
1235 co_read_response, NULL, s);
1237 qemu_co_mutex_unlock(&s->lock);
1240 static int read_write_object(int fd, AioContext *aio_context, char *buf,
1241 uint64_t oid, uint8_t copies,
1242 unsigned int datalen, uint64_t offset,
1243 bool write, bool create, uint32_t cache_flags)
1246 SheepdogObjRsp *rsp = (SheepdogObjRsp *)&hdr;
1247 unsigned int wlen, rlen;
1250 memset(&hdr, 0, sizeof(hdr));
1255 hdr.flags = SD_FLAG_CMD_WRITE;
1257 hdr.opcode = SD_OP_CREATE_AND_WRITE_OBJ;
1259 hdr.opcode = SD_OP_WRITE_OBJ;
1264 hdr.opcode = SD_OP_READ_OBJ;
1267 hdr.flags |= cache_flags;
1270 hdr.data_length = datalen;
1271 hdr.offset = offset;
1272 hdr.copies = copies;
1274 ret = do_req(fd, aio_context, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
1276 error_report("failed to send a request to the sheep");
1280 switch (rsp->result) {
1281 case SD_RES_SUCCESS:
1284 error_report("%s", sd_strerror(rsp->result));
1289 static int read_object(int fd, AioContext *aio_context, char *buf,
1290 uint64_t oid, uint8_t copies,
1291 unsigned int datalen, uint64_t offset,
1292 uint32_t cache_flags)
1294 return read_write_object(fd, aio_context, buf, oid, copies,
1295 datalen, offset, false,
1296 false, cache_flags);
1299 static int write_object(int fd, AioContext *aio_context, char *buf,
1300 uint64_t oid, uint8_t copies,
1301 unsigned int datalen, uint64_t offset, bool create,
1302 uint32_t cache_flags)
1304 return read_write_object(fd, aio_context, buf, oid, copies,
1305 datalen, offset, true,
1306 create, cache_flags);
1309 /* update inode with the latest state */
1310 static int reload_inode(BDRVSheepdogState *s, uint32_t snapid, const char *tag)
1312 Error *local_err = NULL;
1313 SheepdogInode *inode;
1317 fd = connect_to_sdog(s, &local_err);
1319 error_report_err(local_err);
1323 inode = g_malloc(SD_INODE_HEADER_SIZE);
1325 ret = find_vdi_name(s, s->name, snapid, tag, &vid, false, &local_err);
1327 error_report_err(local_err);
1331 ret = read_object(fd, s->aio_context, (char *)inode, vid_to_vdi_oid(vid),
1332 s->inode.nr_copies, SD_INODE_HEADER_SIZE, 0,
1338 if (inode->vdi_id != s->inode.vdi_id) {
1339 memcpy(&s->inode, inode, SD_INODE_HEADER_SIZE);
1349 static void coroutine_fn resend_aioreq(BDRVSheepdogState *s, AIOReq *aio_req)
1351 SheepdogAIOCB *acb = aio_req->aiocb;
1353 aio_req->create = false;
1355 /* check whether this request becomes a CoW one */
1356 if (acb->aiocb_type == AIOCB_WRITE_UDATA && is_data_obj(aio_req->oid)) {
1357 int idx = data_oid_to_idx(aio_req->oid);
1359 if (is_data_obj_writable(&s->inode, idx)) {
1363 if (s->inode.data_vdi_id[idx]) {
1364 aio_req->base_oid = vid_to_data_oid(s->inode.data_vdi_id[idx], idx);
1365 aio_req->flags |= SD_FLAG_CMD_COW;
1367 aio_req->create = true;
1370 if (is_data_obj(aio_req->oid)) {
1371 add_aio_request(s, aio_req, acb->qiov->iov, acb->qiov->niov,
1375 iov.iov_base = &s->inode;
1376 iov.iov_len = sizeof(s->inode);
1377 add_aio_request(s, aio_req, &iov, 1, AIOCB_WRITE_UDATA);
1381 static void sd_detach_aio_context(BlockDriverState *bs)
1383 BDRVSheepdogState *s = bs->opaque;
1385 aio_set_fd_handler(s->aio_context, s->fd, false, NULL,
1389 static void sd_attach_aio_context(BlockDriverState *bs,
1390 AioContext *new_context)
1392 BDRVSheepdogState *s = bs->opaque;
1394 s->aio_context = new_context;
1395 aio_set_fd_handler(new_context, s->fd, false,
1396 co_read_response, NULL, s);
1399 /* TODO Convert to fine grained options */
1400 static QemuOptsList runtime_opts = {
1402 .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
1406 .type = QEMU_OPT_STRING,
1407 .help = "URL to the sheepdog image",
1409 { /* end of list */ }
1413 static int sd_open(BlockDriverState *bs, QDict *options, int flags,
1418 BDRVSheepdogState *s = bs->opaque;
1419 char vdi[SD_MAX_VDI_LEN], tag[SD_MAX_VDI_TAG_LEN];
1423 Error *local_err = NULL;
1424 const char *filename;
1427 s->aio_context = bdrv_get_aio_context(bs);
1429 opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
1430 qemu_opts_absorb_qdict(opts, options, &local_err);
1432 error_propagate(errp, local_err);
1437 filename = qemu_opt_get(opts, "filename");
1439 QLIST_INIT(&s->inflight_aio_head);
1440 QLIST_INIT(&s->failed_aio_head);
1441 QLIST_INIT(&s->inflight_aiocb_head);
1444 memset(vdi, 0, sizeof(vdi));
1445 memset(tag, 0, sizeof(tag));
1447 if (strstr(filename, "://")) {
1448 ret = sd_parse_uri(s, filename, vdi, &snapid, tag);
1450 ret = parse_vdiname(s, filename, vdi, &snapid, tag);
1453 error_setg(errp, "Can't parse filename");
1456 s->fd = get_sheep_fd(s, errp);
1462 ret = find_vdi_name(s, vdi, snapid, tag, &vid, true, errp);
1468 * QEMU block layer emulates writethrough cache as 'writeback + flush', so
1469 * we always set SD_FLAG_CMD_CACHE (writeback cache) as default.
1471 s->cache_flags = SD_FLAG_CMD_CACHE;
1472 if (flags & BDRV_O_NOCACHE) {
1473 s->cache_flags = SD_FLAG_CMD_DIRECT;
1475 s->discard_supported = true;
1477 if (snapid || tag[0] != '\0') {
1478 DPRINTF("%" PRIx32 " snapshot inode was open.\n", vid);
1479 s->is_snapshot = true;
1482 fd = connect_to_sdog(s, errp);
1488 buf = g_malloc(SD_INODE_SIZE);
1489 ret = read_object(fd, s->aio_context, buf, vid_to_vdi_oid(vid),
1490 0, SD_INODE_SIZE, 0, s->cache_flags);
1495 error_setg(errp, "Can't read snapshot inode");
1499 memcpy(&s->inode, buf, sizeof(s->inode));
1501 bs->total_sectors = s->inode.vdi_size / BDRV_SECTOR_SIZE;
1502 pstrcpy(s->name, sizeof(s->name), vdi);
1503 qemu_co_mutex_init(&s->lock);
1504 qemu_co_queue_init(&s->overlapping_queue);
1505 qemu_opts_del(opts);
1509 aio_set_fd_handler(bdrv_get_aio_context(bs), s->fd,
1510 false, NULL, NULL, NULL);
1514 qemu_opts_del(opts);
1519 static int sd_reopen_prepare(BDRVReopenState *state, BlockReopenQueue *queue,
1522 BDRVSheepdogState *s = state->bs->opaque;
1523 BDRVSheepdogReopenState *re_s;
1526 re_s = state->opaque = g_new0(BDRVSheepdogReopenState, 1);
1528 re_s->cache_flags = SD_FLAG_CMD_CACHE;
1529 if (state->flags & BDRV_O_NOCACHE) {
1530 re_s->cache_flags = SD_FLAG_CMD_DIRECT;
1533 re_s->fd = get_sheep_fd(s, errp);
1542 static void sd_reopen_commit(BDRVReopenState *state)
1544 BDRVSheepdogReopenState *re_s = state->opaque;
1545 BDRVSheepdogState *s = state->bs->opaque;
1548 aio_set_fd_handler(s->aio_context, s->fd, false,
1554 s->cache_flags = re_s->cache_flags;
1556 g_free(state->opaque);
1557 state->opaque = NULL;
1562 static void sd_reopen_abort(BDRVReopenState *state)
1564 BDRVSheepdogReopenState *re_s = state->opaque;
1565 BDRVSheepdogState *s = state->bs->opaque;
1572 aio_set_fd_handler(s->aio_context, re_s->fd, false,
1574 closesocket(re_s->fd);
1577 g_free(state->opaque);
1578 state->opaque = NULL;
1583 static int do_sd_create(BDRVSheepdogState *s, uint32_t *vdi_id, int snapshot,
1587 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
1589 unsigned int wlen, rlen = 0;
1590 char buf[SD_MAX_VDI_LEN];
1592 fd = connect_to_sdog(s, errp);
1597 /* FIXME: would it be better to fail (e.g., return -EIO) when filename
1598 * does not fit in buf? For now, just truncate and avoid buffer overrun.
1600 memset(buf, 0, sizeof(buf));
1601 pstrcpy(buf, sizeof(buf), s->name);
1603 memset(&hdr, 0, sizeof(hdr));
1604 hdr.opcode = SD_OP_NEW_VDI;
1605 hdr.base_vdi_id = s->inode.vdi_id;
1607 wlen = SD_MAX_VDI_LEN;
1609 hdr.flags = SD_FLAG_CMD_WRITE;
1610 hdr.snapid = snapshot;
1612 hdr.data_length = wlen;
1613 hdr.vdi_size = s->inode.vdi_size;
1614 hdr.copy_policy = s->inode.copy_policy;
1615 hdr.copies = s->inode.nr_copies;
1616 hdr.block_size_shift = s->inode.block_size_shift;
1618 ret = do_req(fd, s->aio_context, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
1623 error_setg_errno(errp, -ret, "create failed");
1627 if (rsp->result != SD_RES_SUCCESS) {
1628 error_setg(errp, "%s, %s", sd_strerror(rsp->result), s->inode.name);
1633 *vdi_id = rsp->vdi_id;
1639 static int sd_prealloc(const char *filename, Error **errp)
1641 BlockBackend *blk = NULL;
1642 BDRVSheepdogState *base = NULL;
1643 unsigned long buf_size;
1644 uint32_t idx, max_idx;
1645 uint32_t object_size;
1650 blk = blk_new_open(filename, NULL, NULL,
1651 BDRV_O_RDWR | BDRV_O_PROTOCOL, errp);
1654 goto out_with_err_set;
1657 blk_set_allow_write_beyond_eof(blk, true);
1659 vdi_size = blk_getlength(blk);
1665 base = blk_bs(blk)->opaque;
1666 object_size = (UINT32_C(1) << base->inode.block_size_shift);
1667 buf_size = MIN(object_size, SD_DATA_OBJ_SIZE);
1668 buf = g_malloc0(buf_size);
1670 max_idx = DIV_ROUND_UP(vdi_size, buf_size);
1672 for (idx = 0; idx < max_idx; idx++) {
1674 * The created image can be a cloned image, so we need to read
1675 * a data from the source image.
1677 ret = blk_pread(blk, idx * buf_size, buf, buf_size);
1681 ret = blk_pwrite(blk, idx * buf_size, buf, buf_size);
1690 error_setg_errno(errp, -ret, "Can't pre-allocate");
1702 * Sheepdog support two kinds of redundancy, full replication and erasure
1705 * # create a fully replicated vdi with x copies
1706 * -o redundancy=x (1 <= x <= SD_MAX_COPIES)
1708 * # create a erasure coded vdi with x data strips and y parity strips
1709 * -o redundancy=x:y (x must be one of {2,4,8,16} and 1 <= y < SD_EC_MAX_STRIP)
1711 static int parse_redundancy(BDRVSheepdogState *s, const char *opt)
1713 struct SheepdogInode *inode = &s->inode;
1714 const char *n1, *n2;
1718 pstrcpy(p, sizeof(p), opt);
1719 n1 = strtok(p, ":");
1720 n2 = strtok(NULL, ":");
1726 copy = strtol(n1, NULL, 10);
1727 if (copy > SD_MAX_COPIES || copy < 1) {
1731 inode->copy_policy = 0;
1732 inode->nr_copies = copy;
1736 if (copy != 2 && copy != 4 && copy != 8 && copy != 16) {
1740 parity = strtol(n2, NULL, 10);
1741 if (parity >= SD_EC_MAX_STRIP || parity < 1) {
1746 * 4 bits for parity and 4 bits for data.
1747 * We have to compress upper data bits because it can't represent 16
1749 inode->copy_policy = ((copy / 2) << 4) + parity;
1750 inode->nr_copies = copy + parity;
1755 static int parse_block_size_shift(BDRVSheepdogState *s, QemuOpts *opt)
1757 struct SheepdogInode *inode = &s->inode;
1758 uint64_t object_size;
1761 object_size = qemu_opt_get_size_del(opt, BLOCK_OPT_OBJECT_SIZE, 0);
1763 if ((object_size - 1) & object_size) { /* not a power of 2? */
1766 obj_order = ctz32(object_size);
1767 if (obj_order < 20 || obj_order > 31) {
1770 inode->block_size_shift = (uint8_t)obj_order;
1776 static int sd_create(const char *filename, QemuOpts *opts,
1781 char *backing_file = NULL;
1783 BDRVSheepdogState *s;
1784 char tag[SD_MAX_VDI_TAG_LEN];
1786 uint64_t max_vdi_size;
1787 bool prealloc = false;
1789 s = g_new0(BDRVSheepdogState, 1);
1791 memset(tag, 0, sizeof(tag));
1792 if (strstr(filename, "://")) {
1793 ret = sd_parse_uri(s, filename, s->name, &snapid, tag);
1795 ret = parse_vdiname(s, filename, s->name, &snapid, tag);
1798 error_setg(errp, "Can't parse filename");
1802 s->inode.vdi_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
1804 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
1805 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
1806 if (!buf || !strcmp(buf, "off")) {
1808 } else if (!strcmp(buf, "full")) {
1811 error_setg(errp, "Invalid preallocation mode: '%s'", buf);
1817 buf = qemu_opt_get_del(opts, BLOCK_OPT_REDUNDANCY);
1819 ret = parse_redundancy(s, buf);
1821 error_setg(errp, "Invalid redundancy mode: '%s'", buf);
1825 ret = parse_block_size_shift(s, opts);
1827 error_setg(errp, "Invalid object_size."
1828 " obect_size needs to be power of 2"
1829 " and be limited from 2^20 to 2^31");
1835 BDRVSheepdogState *base;
1838 /* Currently, only Sheepdog backing image is supported. */
1839 drv = bdrv_find_protocol(backing_file, true, NULL);
1840 if (!drv || strcmp(drv->protocol_name, "sheepdog") != 0) {
1841 error_setg(errp, "backing_file must be a sheepdog image");
1846 blk = blk_new_open(backing_file, NULL, NULL,
1847 BDRV_O_PROTOCOL, errp);
1853 base = blk_bs(blk)->opaque;
1855 if (!is_snapshot(&base->inode)) {
1856 error_setg(errp, "cannot clone from a non snapshot vdi");
1861 s->inode.vdi_id = base->inode.vdi_id;
1865 s->aio_context = qemu_get_aio_context();
1867 /* if block_size_shift is not specified, get cluster default value */
1868 if (s->inode.block_size_shift == 0) {
1870 SheepdogClusterRsp *rsp = (SheepdogClusterRsp *)&hdr;
1871 Error *local_err = NULL;
1873 unsigned int wlen = 0, rlen = 0;
1875 fd = connect_to_sdog(s, &local_err);
1877 error_report_err(local_err);
1882 memset(&hdr, 0, sizeof(hdr));
1883 hdr.opcode = SD_OP_GET_CLUSTER_DEFAULT;
1884 hdr.proto_ver = SD_PROTO_VER;
1886 ret = do_req(fd, s->aio_context, (SheepdogReq *)&hdr,
1887 NULL, &wlen, &rlen);
1890 error_setg_errno(errp, -ret, "failed to get cluster default");
1893 if (rsp->result == SD_RES_SUCCESS) {
1894 s->inode.block_size_shift = rsp->block_size_shift;
1896 s->inode.block_size_shift = SD_DEFAULT_BLOCK_SIZE_SHIFT;
1900 max_vdi_size = (UINT64_C(1) << s->inode.block_size_shift) * MAX_DATA_OBJS;
1902 if (s->inode.vdi_size > max_vdi_size) {
1903 error_setg(errp, "An image is too large."
1904 " The maximum image size is %"PRIu64 "GB",
1905 max_vdi_size / 1024 / 1024 / 1024);
1910 ret = do_sd_create(s, &vid, 0, errp);
1916 ret = sd_prealloc(filename, errp);
1919 g_free(backing_file);
1925 static void sd_close(BlockDriverState *bs)
1927 Error *local_err = NULL;
1928 BDRVSheepdogState *s = bs->opaque;
1930 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
1931 unsigned int wlen, rlen = 0;
1934 DPRINTF("%s\n", s->name);
1936 fd = connect_to_sdog(s, &local_err);
1938 error_report_err(local_err);
1942 memset(&hdr, 0, sizeof(hdr));
1944 hdr.opcode = SD_OP_RELEASE_VDI;
1945 hdr.type = LOCK_TYPE_NORMAL;
1946 hdr.base_vdi_id = s->inode.vdi_id;
1947 wlen = strlen(s->name) + 1;
1948 hdr.data_length = wlen;
1949 hdr.flags = SD_FLAG_CMD_WRITE;
1951 ret = do_req(fd, s->aio_context, (SheepdogReq *)&hdr,
1952 s->name, &wlen, &rlen);
1956 if (!ret && rsp->result != SD_RES_SUCCESS &&
1957 rsp->result != SD_RES_VDI_NOT_LOCKED) {
1958 error_report("%s, %s", sd_strerror(rsp->result), s->name);
1961 aio_set_fd_handler(bdrv_get_aio_context(bs), s->fd,
1962 false, NULL, NULL, NULL);
1964 g_free(s->host_spec);
1967 static int64_t sd_getlength(BlockDriverState *bs)
1969 BDRVSheepdogState *s = bs->opaque;
1971 return s->inode.vdi_size;
1974 static int sd_truncate(BlockDriverState *bs, int64_t offset)
1976 Error *local_err = NULL;
1977 BDRVSheepdogState *s = bs->opaque;
1979 unsigned int datalen;
1980 uint64_t max_vdi_size;
1982 max_vdi_size = (UINT64_C(1) << s->inode.block_size_shift) * MAX_DATA_OBJS;
1983 if (offset < s->inode.vdi_size) {
1984 error_report("shrinking is not supported");
1986 } else if (offset > max_vdi_size) {
1987 error_report("too big image size");
1991 fd = connect_to_sdog(s, &local_err);
1993 error_report_err(local_err);
1997 /* we don't need to update entire object */
1998 datalen = SD_INODE_SIZE - sizeof(s->inode.data_vdi_id);
1999 s->inode.vdi_size = offset;
2000 ret = write_object(fd, s->aio_context, (char *)&s->inode,
2001 vid_to_vdi_oid(s->inode.vdi_id), s->inode.nr_copies,
2002 datalen, 0, false, s->cache_flags);
2006 error_report("failed to update an inode.");
2013 * This function is called after writing data objects. If we need to
2014 * update metadata, this sends a write request to the vdi object.
2015 * Otherwise, this switches back to sd_co_readv/writev.
2017 static void coroutine_fn sd_write_done(SheepdogAIOCB *acb)
2019 BDRVSheepdogState *s = acb->common.bs->opaque;
2022 uint32_t offset, data_len, mn, mx;
2024 mn = acb->min_dirty_data_idx;
2025 mx = acb->max_dirty_data_idx;
2027 /* we need to update the vdi object. */
2028 offset = sizeof(s->inode) - sizeof(s->inode.data_vdi_id) +
2029 mn * sizeof(s->inode.data_vdi_id[0]);
2030 data_len = (mx - mn + 1) * sizeof(s->inode.data_vdi_id[0]);
2032 acb->min_dirty_data_idx = UINT32_MAX;
2033 acb->max_dirty_data_idx = 0;
2035 iov.iov_base = &s->inode;
2036 iov.iov_len = sizeof(s->inode);
2037 aio_req = alloc_aio_req(s, acb, vid_to_vdi_oid(s->inode.vdi_id),
2038 data_len, offset, 0, false, 0, offset);
2039 QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
2040 add_aio_request(s, aio_req, &iov, 1, AIOCB_WRITE_UDATA);
2042 acb->aio_done_func = sd_finish_aiocb;
2043 acb->aiocb_type = AIOCB_WRITE_UDATA;
2047 sd_finish_aiocb(acb);
2050 /* Delete current working VDI on the snapshot chain */
2051 static bool sd_delete(BDRVSheepdogState *s)
2053 Error *local_err = NULL;
2054 unsigned int wlen = SD_MAX_VDI_LEN, rlen = 0;
2055 SheepdogVdiReq hdr = {
2056 .opcode = SD_OP_DEL_VDI,
2057 .base_vdi_id = s->inode.vdi_id,
2058 .data_length = wlen,
2059 .flags = SD_FLAG_CMD_WRITE,
2061 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
2064 fd = connect_to_sdog(s, &local_err);
2066 error_report_err(local_err);
2070 ret = do_req(fd, s->aio_context, (SheepdogReq *)&hdr,
2071 s->name, &wlen, &rlen);
2076 switch (rsp->result) {
2078 error_report("%s was already deleted", s->name);
2080 case SD_RES_SUCCESS:
2083 error_report("%s, %s", sd_strerror(rsp->result), s->name);
2091 * Create a writable VDI from a snapshot
2093 static int sd_create_branch(BDRVSheepdogState *s)
2095 Error *local_err = NULL;
2101 DPRINTF("%" PRIx32 " is snapshot.\n", s->inode.vdi_id);
2103 buf = g_malloc(SD_INODE_SIZE);
2106 * Even If deletion fails, we will just create extra snapshot based on
2107 * the working VDI which was supposed to be deleted. So no need to
2110 deleted = sd_delete(s);
2111 ret = do_sd_create(s, &vid, !deleted, &local_err);
2113 error_report_err(local_err);
2117 DPRINTF("%" PRIx32 " is created.\n", vid);
2119 fd = connect_to_sdog(s, &local_err);
2121 error_report_err(local_err);
2126 ret = read_object(fd, s->aio_context, buf, vid_to_vdi_oid(vid),
2127 s->inode.nr_copies, SD_INODE_SIZE, 0, s->cache_flags);
2135 memcpy(&s->inode, buf, sizeof(s->inode));
2137 s->is_snapshot = false;
2139 DPRINTF("%" PRIx32 " was newly created.\n", s->inode.vdi_id);
2148 * Send I/O requests to the server.
2150 * This function sends requests to the server, links the requests to
2151 * the inflight_list in BDRVSheepdogState, and exits without
2152 * waiting the response. The responses are received in the
2153 * `aio_read_response' function which is called from the main loop as
2156 * Returns 1 when we need to wait a response, 0 when there is no sent
2157 * request and -errno in error cases.
2159 static int coroutine_fn sd_co_rw_vector(void *p)
2161 SheepdogAIOCB *acb = p;
2163 unsigned long len, done = 0, total = acb->nb_sectors * BDRV_SECTOR_SIZE;
2165 uint32_t object_size;
2168 BDRVSheepdogState *s = acb->common.bs->opaque;
2169 SheepdogInode *inode = &s->inode;
2172 if (acb->aiocb_type == AIOCB_WRITE_UDATA && s->is_snapshot) {
2174 * In the case we open the snapshot VDI, Sheepdog creates the
2175 * writable VDI when we do a write operation first.
2177 ret = sd_create_branch(s);
2184 object_size = (UINT32_C(1) << inode->block_size_shift);
2185 idx = acb->sector_num * BDRV_SECTOR_SIZE / object_size;
2186 offset = (acb->sector_num * BDRV_SECTOR_SIZE) % object_size;
2189 * Make sure we don't free the aiocb before we are done with all requests.
2190 * This additional reference is dropped at the end of this function.
2194 while (done != total) {
2196 uint64_t old_oid = 0;
2197 bool create = false;
2199 oid = vid_to_data_oid(inode->data_vdi_id[idx], idx);
2201 len = MIN(total - done, object_size - offset);
2203 switch (acb->aiocb_type) {
2204 case AIOCB_READ_UDATA:
2205 if (!inode->data_vdi_id[idx]) {
2206 qemu_iovec_memset(acb->qiov, done, 0, len);
2210 case AIOCB_WRITE_UDATA:
2211 if (!inode->data_vdi_id[idx]) {
2213 } else if (!is_data_obj_writable(inode, idx)) {
2217 flags = SD_FLAG_CMD_COW;
2220 case AIOCB_DISCARD_OBJ:
2222 * We discard the object only when the whole object is
2223 * 1) allocated 2) trimmed. Otherwise, simply skip it.
2225 if (len != object_size || inode->data_vdi_id[idx] == 0) {
2234 DPRINTF("update ino (%" PRIu32 ") %" PRIu64 " %" PRIu64 " %ld\n",
2236 vid_to_data_oid(inode->data_vdi_id[idx], idx), idx);
2237 oid = vid_to_data_oid(inode->vdi_id, idx);
2238 DPRINTF("new oid %" PRIx64 "\n", oid);
2241 aio_req = alloc_aio_req(s, acb, oid, len, offset, flags, create,
2243 acb->aiocb_type == AIOCB_DISCARD_OBJ ?
2245 QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
2247 add_aio_request(s, aio_req, acb->qiov->iov, acb->qiov->niov,
2255 if (!--acb->nr_pending) {
2261 static bool check_overlapping_aiocb(BDRVSheepdogState *s, SheepdogAIOCB *aiocb)
2265 QLIST_FOREACH(cb, &s->inflight_aiocb_head, aiocb_siblings) {
2266 if (AIOCBOverlapping(aiocb, cb)) {
2271 QLIST_INSERT_HEAD(&s->inflight_aiocb_head, aiocb, aiocb_siblings);
2275 static coroutine_fn int sd_co_writev(BlockDriverState *bs, int64_t sector_num,
2276 int nb_sectors, QEMUIOVector *qiov)
2280 int64_t offset = (sector_num + nb_sectors) * BDRV_SECTOR_SIZE;
2281 BDRVSheepdogState *s = bs->opaque;
2283 if (offset > s->inode.vdi_size) {
2284 ret = sd_truncate(bs, offset);
2290 acb = sd_aio_setup(bs, qiov, sector_num, nb_sectors);
2291 acb->aio_done_func = sd_write_done;
2292 acb->aiocb_type = AIOCB_WRITE_UDATA;
2295 if (check_overlapping_aiocb(s, acb)) {
2296 qemu_co_queue_wait(&s->overlapping_queue);
2300 ret = sd_co_rw_vector(acb);
2302 QLIST_REMOVE(acb, aiocb_siblings);
2303 qemu_co_queue_restart_all(&s->overlapping_queue);
2304 qemu_aio_unref(acb);
2308 qemu_coroutine_yield();
2310 QLIST_REMOVE(acb, aiocb_siblings);
2311 qemu_co_queue_restart_all(&s->overlapping_queue);
2316 static coroutine_fn int sd_co_readv(BlockDriverState *bs, int64_t sector_num,
2317 int nb_sectors, QEMUIOVector *qiov)
2321 BDRVSheepdogState *s = bs->opaque;
2323 acb = sd_aio_setup(bs, qiov, sector_num, nb_sectors);
2324 acb->aiocb_type = AIOCB_READ_UDATA;
2325 acb->aio_done_func = sd_finish_aiocb;
2328 if (check_overlapping_aiocb(s, acb)) {
2329 qemu_co_queue_wait(&s->overlapping_queue);
2333 ret = sd_co_rw_vector(acb);
2335 QLIST_REMOVE(acb, aiocb_siblings);
2336 qemu_co_queue_restart_all(&s->overlapping_queue);
2337 qemu_aio_unref(acb);
2341 qemu_coroutine_yield();
2343 QLIST_REMOVE(acb, aiocb_siblings);
2344 qemu_co_queue_restart_all(&s->overlapping_queue);
2348 static int coroutine_fn sd_co_flush_to_disk(BlockDriverState *bs)
2350 BDRVSheepdogState *s = bs->opaque;
2354 if (s->cache_flags != SD_FLAG_CMD_CACHE) {
2358 acb = sd_aio_setup(bs, NULL, 0, 0);
2359 acb->aiocb_type = AIOCB_FLUSH_CACHE;
2360 acb->aio_done_func = sd_finish_aiocb;
2362 aio_req = alloc_aio_req(s, acb, vid_to_vdi_oid(s->inode.vdi_id),
2363 0, 0, 0, false, 0, 0);
2364 QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
2365 add_aio_request(s, aio_req, NULL, 0, acb->aiocb_type);
2367 qemu_coroutine_yield();
2371 static int sd_snapshot_create(BlockDriverState *bs, QEMUSnapshotInfo *sn_info)
2373 Error *local_err = NULL;
2374 BDRVSheepdogState *s = bs->opaque;
2377 SheepdogInode *inode;
2378 unsigned int datalen;
2380 DPRINTF("sn_info: name %s id_str %s s: name %s vm_state_size %" PRId64 " "
2381 "is_snapshot %d\n", sn_info->name, sn_info->id_str,
2382 s->name, sn_info->vm_state_size, s->is_snapshot);
2384 if (s->is_snapshot) {
2385 error_report("You can't create a snapshot of a snapshot VDI, "
2386 "%s (%" PRIu32 ").", s->name, s->inode.vdi_id);
2391 DPRINTF("%s %s\n", sn_info->name, sn_info->id_str);
2393 s->inode.vm_state_size = sn_info->vm_state_size;
2394 s->inode.vm_clock_nsec = sn_info->vm_clock_nsec;
2395 /* It appears that inode.tag does not require a NUL terminator,
2396 * which means this use of strncpy is ok.
2398 strncpy(s->inode.tag, sn_info->name, sizeof(s->inode.tag));
2399 /* we don't need to update entire object */
2400 datalen = SD_INODE_SIZE - sizeof(s->inode.data_vdi_id);
2401 inode = g_malloc(datalen);
2403 /* refresh inode. */
2404 fd = connect_to_sdog(s, &local_err);
2406 error_report_err(local_err);
2411 ret = write_object(fd, s->aio_context, (char *)&s->inode,
2412 vid_to_vdi_oid(s->inode.vdi_id), s->inode.nr_copies,
2413 datalen, 0, false, s->cache_flags);
2415 error_report("failed to write snapshot's inode.");
2419 ret = do_sd_create(s, &new_vid, 1, &local_err);
2421 error_reportf_err(local_err,
2422 "failed to create inode for snapshot: ");
2426 ret = read_object(fd, s->aio_context, (char *)inode,
2427 vid_to_vdi_oid(new_vid), s->inode.nr_copies, datalen, 0,
2431 error_report("failed to read new inode info. %s", strerror(errno));
2435 memcpy(&s->inode, inode, datalen);
2436 DPRINTF("s->inode: name %s snap_id %x oid %x\n",
2437 s->inode.name, s->inode.snap_id, s->inode.vdi_id);
2446 * We implement rollback(loadvm) operation to the specified snapshot by
2447 * 1) switch to the snapshot
2448 * 2) rely on sd_create_branch to delete working VDI and
2449 * 3) create a new working VDI based on the specified snapshot
2451 static int sd_snapshot_goto(BlockDriverState *bs, const char *snapshot_id)
2453 BDRVSheepdogState *s = bs->opaque;
2454 BDRVSheepdogState *old_s;
2455 char tag[SD_MAX_VDI_TAG_LEN];
2456 uint32_t snapid = 0;
2459 old_s = g_new(BDRVSheepdogState, 1);
2461 memcpy(old_s, s, sizeof(BDRVSheepdogState));
2463 snapid = strtoul(snapshot_id, NULL, 10);
2467 pstrcpy(tag, sizeof(tag), snapshot_id);
2470 ret = reload_inode(s, snapid, tag);
2475 ret = sd_create_branch(s);
2484 /* recover bdrv_sd_state */
2485 memcpy(s, old_s, sizeof(BDRVSheepdogState));
2488 error_report("failed to open. recover old bdrv_sd_state.");
2493 #define NR_BATCHED_DISCARD 128
2495 static bool remove_objects(BDRVSheepdogState *s)
2497 int fd, i = 0, nr_objs = 0;
2498 Error *local_err = NULL;
2501 SheepdogInode *inode = &s->inode;
2503 fd = connect_to_sdog(s, &local_err);
2505 error_report_err(local_err);
2509 nr_objs = count_data_objs(inode);
2510 while (i < nr_objs) {
2511 int start_idx, nr_filled_idx;
2513 while (i < nr_objs && !inode->data_vdi_id[i]) {
2519 while (i < nr_objs && nr_filled_idx < NR_BATCHED_DISCARD) {
2520 if (inode->data_vdi_id[i]) {
2521 inode->data_vdi_id[i] = 0;
2528 ret = write_object(fd, s->aio_context,
2529 (char *)&inode->data_vdi_id[start_idx],
2530 vid_to_vdi_oid(s->inode.vdi_id), inode->nr_copies,
2531 (i - start_idx) * sizeof(uint32_t),
2532 offsetof(struct SheepdogInode,
2533 data_vdi_id[start_idx]),
2534 false, s->cache_flags);
2536 error_report("failed to discard snapshot inode.");
2547 static int sd_snapshot_delete(BlockDriverState *bs,
2548 const char *snapshot_id,
2552 unsigned long snap_id = 0;
2553 char snap_tag[SD_MAX_VDI_TAG_LEN];
2554 Error *local_err = NULL;
2556 char buf[SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN];
2557 BDRVSheepdogState *s = bs->opaque;
2558 unsigned int wlen = SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN, rlen = 0;
2560 SheepdogVdiReq hdr = {
2561 .opcode = SD_OP_DEL_VDI,
2562 .data_length = wlen,
2563 .flags = SD_FLAG_CMD_WRITE,
2565 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
2567 if (!remove_objects(s)) {
2571 memset(buf, 0, sizeof(buf));
2572 memset(snap_tag, 0, sizeof(snap_tag));
2573 pstrcpy(buf, SD_MAX_VDI_LEN, s->name);
2574 ret = qemu_strtoul(snapshot_id, NULL, 10, &snap_id);
2575 if (ret || snap_id > UINT32_MAX) {
2576 error_setg(errp, "Invalid snapshot ID: %s",
2577 snapshot_id ? snapshot_id : "<null>");
2582 hdr.snapid = (uint32_t) snap_id;
2584 pstrcpy(snap_tag, sizeof(snap_tag), snapshot_id);
2585 pstrcpy(buf + SD_MAX_VDI_LEN, SD_MAX_VDI_TAG_LEN, snap_tag);
2588 ret = find_vdi_name(s, s->name, snap_id, snap_tag, &vid, true,
2594 fd = connect_to_sdog(s, &local_err);
2596 error_report_err(local_err);
2600 ret = do_req(fd, s->aio_context, (SheepdogReq *)&hdr,
2607 switch (rsp->result) {
2609 error_report("%s was already deleted", s->name);
2610 case SD_RES_SUCCESS:
2613 error_report("%s, %s", sd_strerror(rsp->result), s->name);
2620 static int sd_snapshot_list(BlockDriverState *bs, QEMUSnapshotInfo **psn_tab)
2622 Error *local_err = NULL;
2623 BDRVSheepdogState *s = bs->opaque;
2625 int fd, nr = 1024, ret, max = BITS_TO_LONGS(SD_NR_VDIS) * sizeof(long);
2626 QEMUSnapshotInfo *sn_tab = NULL;
2627 unsigned wlen, rlen;
2629 static SheepdogInode inode;
2630 unsigned long *vdi_inuse;
2631 unsigned int start_nr;
2635 vdi_inuse = g_malloc(max);
2637 fd = connect_to_sdog(s, &local_err);
2639 error_report_err(local_err);
2647 memset(&req, 0, sizeof(req));
2649 req.opcode = SD_OP_READ_VDIS;
2650 req.data_length = max;
2652 ret = do_req(fd, s->aio_context, (SheepdogReq *)&req,
2653 vdi_inuse, &wlen, &rlen);
2660 sn_tab = g_new0(QEMUSnapshotInfo, nr);
2662 /* calculate a vdi id with hash function */
2663 hval = fnv_64a_buf(s->name, strlen(s->name), FNV1A_64_INIT);
2664 start_nr = hval & (SD_NR_VDIS - 1);
2666 fd = connect_to_sdog(s, &local_err);
2668 error_report_err(local_err);
2673 for (vid = start_nr; found < nr; vid = (vid + 1) % SD_NR_VDIS) {
2674 if (!test_bit(vid, vdi_inuse)) {
2678 /* we don't need to read entire object */
2679 ret = read_object(fd, s->aio_context, (char *)&inode,
2680 vid_to_vdi_oid(vid),
2681 0, SD_INODE_SIZE - sizeof(inode.data_vdi_id), 0,
2688 if (!strcmp(inode.name, s->name) && is_snapshot(&inode)) {
2689 sn_tab[found].date_sec = inode.snap_ctime >> 32;
2690 sn_tab[found].date_nsec = inode.snap_ctime & 0xffffffff;
2691 sn_tab[found].vm_state_size = inode.vm_state_size;
2692 sn_tab[found].vm_clock_nsec = inode.vm_clock_nsec;
2694 snprintf(sn_tab[found].id_str, sizeof(sn_tab[found].id_str),
2695 "%" PRIu32, inode.snap_id);
2696 pstrcpy(sn_tab[found].name,
2697 MIN(sizeof(sn_tab[found].name), sizeof(inode.tag)),
2716 static int do_load_save_vmstate(BDRVSheepdogState *s, uint8_t *data,
2717 int64_t pos, int size, int load)
2719 Error *local_err = NULL;
2721 int fd, ret = 0, remaining = size;
2722 unsigned int data_len;
2723 uint64_t vmstate_oid;
2726 uint32_t vdi_id = load ? s->inode.parent_vdi_id : s->inode.vdi_id;
2727 uint32_t object_size = (UINT32_C(1) << s->inode.block_size_shift);
2729 fd = connect_to_sdog(s, &local_err);
2731 error_report_err(local_err);
2736 vdi_index = pos / object_size;
2737 offset = pos % object_size;
2739 data_len = MIN(remaining, object_size - offset);
2741 vmstate_oid = vid_to_vmstate_oid(vdi_id, vdi_index);
2743 create = (offset == 0);
2745 ret = read_object(fd, s->aio_context, (char *)data, vmstate_oid,
2746 s->inode.nr_copies, data_len, offset,
2749 ret = write_object(fd, s->aio_context, (char *)data, vmstate_oid,
2750 s->inode.nr_copies, data_len, offset, create,
2755 error_report("failed to save vmstate %s", strerror(errno));
2761 remaining -= data_len;
2769 static int sd_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2772 BDRVSheepdogState *s = bs->opaque;
2776 buf = qemu_blockalign(bs, qiov->size);
2777 qemu_iovec_to_buf(qiov, 0, buf, qiov->size);
2778 ret = do_load_save_vmstate(s, (uint8_t *) buf, pos, qiov->size, 0);
2784 static int sd_load_vmstate(BlockDriverState *bs, uint8_t *data,
2785 int64_t pos, int size)
2787 BDRVSheepdogState *s = bs->opaque;
2789 return do_load_save_vmstate(s, data, pos, size, 1);
2793 static coroutine_fn int sd_co_discard(BlockDriverState *bs, int64_t sector_num,
2797 BDRVSheepdogState *s = bs->opaque;
2799 QEMUIOVector discard_iov;
2803 if (!s->discard_supported) {
2807 memset(&discard_iov, 0, sizeof(discard_iov));
2808 memset(&iov, 0, sizeof(iov));
2809 iov.iov_base = &zero;
2810 iov.iov_len = sizeof(zero);
2811 discard_iov.iov = &iov;
2812 discard_iov.niov = 1;
2813 acb = sd_aio_setup(bs, &discard_iov, sector_num, nb_sectors);
2814 acb->aiocb_type = AIOCB_DISCARD_OBJ;
2815 acb->aio_done_func = sd_finish_aiocb;
2818 if (check_overlapping_aiocb(s, acb)) {
2819 qemu_co_queue_wait(&s->overlapping_queue);
2823 ret = sd_co_rw_vector(acb);
2825 QLIST_REMOVE(acb, aiocb_siblings);
2826 qemu_co_queue_restart_all(&s->overlapping_queue);
2827 qemu_aio_unref(acb);
2831 qemu_coroutine_yield();
2833 QLIST_REMOVE(acb, aiocb_siblings);
2834 qemu_co_queue_restart_all(&s->overlapping_queue);
2839 static coroutine_fn int64_t
2840 sd_co_get_block_status(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
2841 int *pnum, BlockDriverState **file)
2843 BDRVSheepdogState *s = bs->opaque;
2844 SheepdogInode *inode = &s->inode;
2845 uint32_t object_size = (UINT32_C(1) << inode->block_size_shift);
2846 uint64_t offset = sector_num * BDRV_SECTOR_SIZE;
2847 unsigned long start = offset / object_size,
2848 end = DIV_ROUND_UP((sector_num + nb_sectors) *
2849 BDRV_SECTOR_SIZE, object_size);
2851 int64_t ret = BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | offset;
2853 for (idx = start; idx < end; idx++) {
2854 if (inode->data_vdi_id[idx] == 0) {
2859 /* Get the longest length of unallocated sectors */
2861 for (idx = start + 1; idx < end; idx++) {
2862 if (inode->data_vdi_id[idx] != 0) {
2868 *pnum = (idx - start) * object_size / BDRV_SECTOR_SIZE;
2869 if (*pnum > nb_sectors) {
2872 if (ret > 0 && ret & BDRV_BLOCK_OFFSET_VALID) {
2878 static int64_t sd_get_allocated_file_size(BlockDriverState *bs)
2880 BDRVSheepdogState *s = bs->opaque;
2881 SheepdogInode *inode = &s->inode;
2882 uint32_t object_size = (UINT32_C(1) << inode->block_size_shift);
2883 unsigned long i, last = DIV_ROUND_UP(inode->vdi_size, object_size);
2886 for (i = 0; i < last; i++) {
2887 if (inode->data_vdi_id[i] == 0) {
2890 size += object_size;
2895 static QemuOptsList sd_create_opts = {
2896 .name = "sheepdog-create-opts",
2897 .head = QTAILQ_HEAD_INITIALIZER(sd_create_opts.head),
2900 .name = BLOCK_OPT_SIZE,
2901 .type = QEMU_OPT_SIZE,
2902 .help = "Virtual disk size"
2905 .name = BLOCK_OPT_BACKING_FILE,
2906 .type = QEMU_OPT_STRING,
2907 .help = "File name of a base image"
2910 .name = BLOCK_OPT_PREALLOC,
2911 .type = QEMU_OPT_STRING,
2912 .help = "Preallocation mode (allowed values: off, full)"
2915 .name = BLOCK_OPT_REDUNDANCY,
2916 .type = QEMU_OPT_STRING,
2917 .help = "Redundancy of the image"
2920 .name = BLOCK_OPT_OBJECT_SIZE,
2921 .type = QEMU_OPT_SIZE,
2922 .help = "Object size of the image"
2924 { /* end of list */ }
2928 static BlockDriver bdrv_sheepdog = {
2929 .format_name = "sheepdog",
2930 .protocol_name = "sheepdog",
2931 .instance_size = sizeof(BDRVSheepdogState),
2932 .bdrv_needs_filename = true,
2933 .bdrv_file_open = sd_open,
2934 .bdrv_reopen_prepare = sd_reopen_prepare,
2935 .bdrv_reopen_commit = sd_reopen_commit,
2936 .bdrv_reopen_abort = sd_reopen_abort,
2937 .bdrv_close = sd_close,
2938 .bdrv_create = sd_create,
2939 .bdrv_has_zero_init = bdrv_has_zero_init_1,
2940 .bdrv_getlength = sd_getlength,
2941 .bdrv_get_allocated_file_size = sd_get_allocated_file_size,
2942 .bdrv_truncate = sd_truncate,
2944 .bdrv_co_readv = sd_co_readv,
2945 .bdrv_co_writev = sd_co_writev,
2946 .bdrv_co_flush_to_disk = sd_co_flush_to_disk,
2947 .bdrv_co_discard = sd_co_discard,
2948 .bdrv_co_get_block_status = sd_co_get_block_status,
2950 .bdrv_snapshot_create = sd_snapshot_create,
2951 .bdrv_snapshot_goto = sd_snapshot_goto,
2952 .bdrv_snapshot_delete = sd_snapshot_delete,
2953 .bdrv_snapshot_list = sd_snapshot_list,
2955 .bdrv_save_vmstate = sd_save_vmstate,
2956 .bdrv_load_vmstate = sd_load_vmstate,
2958 .bdrv_detach_aio_context = sd_detach_aio_context,
2959 .bdrv_attach_aio_context = sd_attach_aio_context,
2961 .create_opts = &sd_create_opts,
2964 static BlockDriver bdrv_sheepdog_tcp = {
2965 .format_name = "sheepdog",
2966 .protocol_name = "sheepdog+tcp",
2967 .instance_size = sizeof(BDRVSheepdogState),
2968 .bdrv_needs_filename = true,
2969 .bdrv_file_open = sd_open,
2970 .bdrv_reopen_prepare = sd_reopen_prepare,
2971 .bdrv_reopen_commit = sd_reopen_commit,
2972 .bdrv_reopen_abort = sd_reopen_abort,
2973 .bdrv_close = sd_close,
2974 .bdrv_create = sd_create,
2975 .bdrv_has_zero_init = bdrv_has_zero_init_1,
2976 .bdrv_getlength = sd_getlength,
2977 .bdrv_get_allocated_file_size = sd_get_allocated_file_size,
2978 .bdrv_truncate = sd_truncate,
2980 .bdrv_co_readv = sd_co_readv,
2981 .bdrv_co_writev = sd_co_writev,
2982 .bdrv_co_flush_to_disk = sd_co_flush_to_disk,
2983 .bdrv_co_discard = sd_co_discard,
2984 .bdrv_co_get_block_status = sd_co_get_block_status,
2986 .bdrv_snapshot_create = sd_snapshot_create,
2987 .bdrv_snapshot_goto = sd_snapshot_goto,
2988 .bdrv_snapshot_delete = sd_snapshot_delete,
2989 .bdrv_snapshot_list = sd_snapshot_list,
2991 .bdrv_save_vmstate = sd_save_vmstate,
2992 .bdrv_load_vmstate = sd_load_vmstate,
2994 .bdrv_detach_aio_context = sd_detach_aio_context,
2995 .bdrv_attach_aio_context = sd_attach_aio_context,
2997 .create_opts = &sd_create_opts,
3000 static BlockDriver bdrv_sheepdog_unix = {
3001 .format_name = "sheepdog",
3002 .protocol_name = "sheepdog+unix",
3003 .instance_size = sizeof(BDRVSheepdogState),
3004 .bdrv_needs_filename = true,
3005 .bdrv_file_open = sd_open,
3006 .bdrv_reopen_prepare = sd_reopen_prepare,
3007 .bdrv_reopen_commit = sd_reopen_commit,
3008 .bdrv_reopen_abort = sd_reopen_abort,
3009 .bdrv_close = sd_close,
3010 .bdrv_create = sd_create,
3011 .bdrv_has_zero_init = bdrv_has_zero_init_1,
3012 .bdrv_getlength = sd_getlength,
3013 .bdrv_get_allocated_file_size = sd_get_allocated_file_size,
3014 .bdrv_truncate = sd_truncate,
3016 .bdrv_co_readv = sd_co_readv,
3017 .bdrv_co_writev = sd_co_writev,
3018 .bdrv_co_flush_to_disk = sd_co_flush_to_disk,
3019 .bdrv_co_discard = sd_co_discard,
3020 .bdrv_co_get_block_status = sd_co_get_block_status,
3022 .bdrv_snapshot_create = sd_snapshot_create,
3023 .bdrv_snapshot_goto = sd_snapshot_goto,
3024 .bdrv_snapshot_delete = sd_snapshot_delete,
3025 .bdrv_snapshot_list = sd_snapshot_list,
3027 .bdrv_save_vmstate = sd_save_vmstate,
3028 .bdrv_load_vmstate = sd_load_vmstate,
3030 .bdrv_detach_aio_context = sd_detach_aio_context,
3031 .bdrv_attach_aio_context = sd_attach_aio_context,
3033 .create_opts = &sd_create_opts,
3036 static void bdrv_sheepdog_init(void)
3038 bdrv_register(&bdrv_sheepdog);
3039 bdrv_register(&bdrv_sheepdog_tcp);
3040 bdrv_register(&bdrv_sheepdog_unix);
3042 block_init(bdrv_sheepdog_init);