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-common.h"
17 #include "qemu/error-report.h"
18 #include "qemu/sockets.h"
19 #include "block/block_int.h"
20 #include "qemu/bitops.h"
22 #define SD_PROTO_VER 0x01
24 #define SD_DEFAULT_ADDR "localhost"
25 #define SD_DEFAULT_PORT 7000
27 #define SD_OP_CREATE_AND_WRITE_OBJ 0x01
28 #define SD_OP_READ_OBJ 0x02
29 #define SD_OP_WRITE_OBJ 0x03
30 /* 0x04 is used internally by Sheepdog */
31 #define SD_OP_DISCARD_OBJ 0x05
33 #define SD_OP_NEW_VDI 0x11
34 #define SD_OP_LOCK_VDI 0x12
35 #define SD_OP_RELEASE_VDI 0x13
36 #define SD_OP_GET_VDI_INFO 0x14
37 #define SD_OP_READ_VDIS 0x15
38 #define SD_OP_FLUSH_VDI 0x16
39 #define SD_OP_DEL_VDI 0x17
41 #define SD_FLAG_CMD_WRITE 0x01
42 #define SD_FLAG_CMD_COW 0x02
43 #define SD_FLAG_CMD_CACHE 0x04 /* Writeback mode for cache */
44 #define SD_FLAG_CMD_DIRECT 0x08 /* Don't use cache */
46 #define SD_RES_SUCCESS 0x00 /* Success */
47 #define SD_RES_UNKNOWN 0x01 /* Unknown error */
48 #define SD_RES_NO_OBJ 0x02 /* No object found */
49 #define SD_RES_EIO 0x03 /* I/O error */
50 #define SD_RES_VDI_EXIST 0x04 /* Vdi exists already */
51 #define SD_RES_INVALID_PARMS 0x05 /* Invalid parameters */
52 #define SD_RES_SYSTEM_ERROR 0x06 /* System error */
53 #define SD_RES_VDI_LOCKED 0x07 /* Vdi is locked */
54 #define SD_RES_NO_VDI 0x08 /* No vdi found */
55 #define SD_RES_NO_BASE_VDI 0x09 /* No base vdi found */
56 #define SD_RES_VDI_READ 0x0A /* Cannot read requested vdi */
57 #define SD_RES_VDI_WRITE 0x0B /* Cannot write requested vdi */
58 #define SD_RES_BASE_VDI_READ 0x0C /* Cannot read base vdi */
59 #define SD_RES_BASE_VDI_WRITE 0x0D /* Cannot write base vdi */
60 #define SD_RES_NO_TAG 0x0E /* Requested tag is not found */
61 #define SD_RES_STARTUP 0x0F /* Sheepdog is on starting up */
62 #define SD_RES_VDI_NOT_LOCKED 0x10 /* Vdi is not locked */
63 #define SD_RES_SHUTDOWN 0x11 /* Sheepdog is shutting down */
64 #define SD_RES_NO_MEM 0x12 /* Cannot allocate memory */
65 #define SD_RES_FULL_VDI 0x13 /* we already have the maximum vdis */
66 #define SD_RES_VER_MISMATCH 0x14 /* Protocol version mismatch */
67 #define SD_RES_NO_SPACE 0x15 /* Server has no room for new objects */
68 #define SD_RES_WAIT_FOR_FORMAT 0x16 /* Waiting for a format operation */
69 #define SD_RES_WAIT_FOR_JOIN 0x17 /* Waiting for other nodes joining */
70 #define SD_RES_JOIN_FAILED 0x18 /* Target node had failed to join sheepdog */
71 #define SD_RES_HALT 0x19 /* Sheepdog is stopped serving IO request */
72 #define SD_RES_READONLY 0x1A /* Object is read-only */
77 * 0 - 19 (20 bits): data object space
78 * 20 - 31 (12 bits): reserved data object space
79 * 32 - 55 (24 bits): vdi object space
80 * 56 - 59 ( 4 bits): reserved vdi object space
81 * 60 - 63 ( 4 bits): object type identifier space
84 #define VDI_SPACE_SHIFT 32
85 #define VDI_BIT (UINT64_C(1) << 63)
86 #define VMSTATE_BIT (UINT64_C(1) << 62)
87 #define MAX_DATA_OBJS (UINT64_C(1) << 20)
88 #define MAX_CHILDREN 1024
89 #define SD_MAX_VDI_LEN 256
90 #define SD_MAX_VDI_TAG_LEN 256
91 #define SD_NR_VDIS (1U << 24)
92 #define SD_DATA_OBJ_SIZE (UINT64_C(1) << 22)
93 #define SD_MAX_VDI_SIZE (SD_DATA_OBJ_SIZE * MAX_DATA_OBJS)
95 * For erasure coding, we use at most SD_EC_MAX_STRIP for data strips and
96 * (SD_EC_MAX_STRIP - 1) for parity strips
98 * SD_MAX_COPIES is sum of number of data strips and parity strips.
100 #define SD_EC_MAX_STRIP 16
101 #define SD_MAX_COPIES (SD_EC_MAX_STRIP * 2 - 1)
103 #define SD_INODE_SIZE (sizeof(SheepdogInode))
104 #define CURRENT_VDI_ID 0
106 typedef struct SheepdogReq {
112 uint32_t data_length;
113 uint32_t opcode_specific[8];
116 typedef struct SheepdogRsp {
122 uint32_t data_length;
124 uint32_t opcode_specific[7];
127 typedef struct SheepdogObjReq {
133 uint32_t data_length;
142 typedef struct SheepdogObjRsp {
148 uint32_t data_length;
156 typedef struct SheepdogVdiReq {
162 uint32_t data_length;
172 typedef struct SheepdogVdiRsp {
178 uint32_t data_length;
185 typedef struct SheepdogInode {
186 char name[SD_MAX_VDI_LEN];
187 char tag[SD_MAX_VDI_TAG_LEN];
190 uint64_t vm_clock_nsec;
192 uint64_t vm_state_size;
193 uint16_t copy_policy;
195 uint8_t block_size_shift;
198 uint32_t parent_vdi_id;
199 uint32_t child_vdi_id[MAX_CHILDREN];
200 uint32_t data_vdi_id[MAX_DATA_OBJS];
204 * 64 bit FNV-1a non-zero initial basis
206 #define FNV1A_64_INIT ((uint64_t)0xcbf29ce484222325ULL)
209 * 64 bit Fowler/Noll/Vo FNV-1a hash code
211 static inline uint64_t fnv_64a_buf(void *buf, size_t len, uint64_t hval)
213 unsigned char *bp = buf;
214 unsigned char *be = bp + len;
216 hval ^= (uint64_t) *bp++;
217 hval += (hval << 1) + (hval << 4) + (hval << 5) +
218 (hval << 7) + (hval << 8) + (hval << 40);
223 static inline bool is_data_obj_writable(SheepdogInode *inode, unsigned int idx)
225 return inode->vdi_id == inode->data_vdi_id[idx];
228 static inline bool is_data_obj(uint64_t oid)
230 return !(VDI_BIT & oid);
233 static inline uint64_t data_oid_to_idx(uint64_t oid)
235 return oid & (MAX_DATA_OBJS - 1);
238 static inline uint32_t oid_to_vid(uint64_t oid)
240 return (oid & ~VDI_BIT) >> VDI_SPACE_SHIFT;
243 static inline uint64_t vid_to_vdi_oid(uint32_t vid)
245 return VDI_BIT | ((uint64_t)vid << VDI_SPACE_SHIFT);
248 static inline uint64_t vid_to_vmstate_oid(uint32_t vid, uint32_t idx)
250 return VMSTATE_BIT | ((uint64_t)vid << VDI_SPACE_SHIFT) | idx;
253 static inline uint64_t vid_to_data_oid(uint32_t vid, uint32_t idx)
255 return ((uint64_t)vid << VDI_SPACE_SHIFT) | idx;
258 static inline bool is_snapshot(struct SheepdogInode *inode)
260 return !!inode->snap_ctime;
265 #define DPRINTF(fmt, args...) \
267 fprintf(stdout, "%s %d: " fmt, __func__, __LINE__, ##args); \
270 #define DPRINTF(fmt, args...)
273 typedef struct SheepdogAIOCB SheepdogAIOCB;
275 typedef struct AIOReq {
276 SheepdogAIOCB *aiocb;
277 unsigned int iov_offset;
282 unsigned int data_len;
286 QLIST_ENTRY(AIOReq) aio_siblings;
296 struct SheepdogAIOCB {
297 BlockDriverAIOCB common;
305 enum AIOCBState aiocb_type;
307 Coroutine *coroutine;
308 void (*aio_done_func)(SheepdogAIOCB *);
315 typedef struct BDRVSheepdogState {
316 BlockDriverState *bs;
320 uint32_t min_dirty_data_idx;
321 uint32_t max_dirty_data_idx;
323 char name[SD_MAX_VDI_LEN];
325 uint32_t cache_flags;
326 bool discard_supported;
336 uint32_t aioreq_seq_num;
338 /* Every aio request must be linked to either of these queues. */
339 QLIST_HEAD(inflight_aio_head, AIOReq) inflight_aio_head;
340 QLIST_HEAD(pending_aio_head, AIOReq) pending_aio_head;
341 QLIST_HEAD(failed_aio_head, AIOReq) failed_aio_head;
344 static const char * sd_strerror(int err)
348 static const struct {
352 {SD_RES_SUCCESS, "Success"},
353 {SD_RES_UNKNOWN, "Unknown error"},
354 {SD_RES_NO_OBJ, "No object found"},
355 {SD_RES_EIO, "I/O error"},
356 {SD_RES_VDI_EXIST, "VDI exists already"},
357 {SD_RES_INVALID_PARMS, "Invalid parameters"},
358 {SD_RES_SYSTEM_ERROR, "System error"},
359 {SD_RES_VDI_LOCKED, "VDI is already locked"},
360 {SD_RES_NO_VDI, "No vdi found"},
361 {SD_RES_NO_BASE_VDI, "No base VDI found"},
362 {SD_RES_VDI_READ, "Failed read the requested VDI"},
363 {SD_RES_VDI_WRITE, "Failed to write the requested VDI"},
364 {SD_RES_BASE_VDI_READ, "Failed to read the base VDI"},
365 {SD_RES_BASE_VDI_WRITE, "Failed to write the base VDI"},
366 {SD_RES_NO_TAG, "Failed to find the requested tag"},
367 {SD_RES_STARTUP, "The system is still booting"},
368 {SD_RES_VDI_NOT_LOCKED, "VDI isn't locked"},
369 {SD_RES_SHUTDOWN, "The system is shutting down"},
370 {SD_RES_NO_MEM, "Out of memory on the server"},
371 {SD_RES_FULL_VDI, "We already have the maximum vdis"},
372 {SD_RES_VER_MISMATCH, "Protocol version mismatch"},
373 {SD_RES_NO_SPACE, "Server has no space for new objects"},
374 {SD_RES_WAIT_FOR_FORMAT, "Sheepdog is waiting for a format operation"},
375 {SD_RES_WAIT_FOR_JOIN, "Sheepdog is waiting for other nodes joining"},
376 {SD_RES_JOIN_FAILED, "Target node had failed to join sheepdog"},
377 {SD_RES_HALT, "Sheepdog is stopped serving IO request"},
378 {SD_RES_READONLY, "Object is read-only"},
381 for (i = 0; i < ARRAY_SIZE(errors); ++i) {
382 if (errors[i].err == err) {
383 return errors[i].desc;
387 return "Invalid error code";
391 * Sheepdog I/O handling:
393 * 1. In sd_co_rw_vector, we send the I/O requests to the server and
394 * link the requests to the inflight_list in the
395 * BDRVSheepdogState. The function exits without waiting for
396 * receiving the response.
398 * 2. We receive the response in aio_read_response, the fd handler to
399 * the sheepdog connection. If metadata update is needed, we send
400 * the write request to the vdi object in sd_write_done, the write
401 * completion function. We switch back to sd_co_readv/writev after
402 * all the requests belonging to the AIOCB are finished.
405 static inline AIOReq *alloc_aio_req(BDRVSheepdogState *s, SheepdogAIOCB *acb,
406 uint64_t oid, unsigned int data_len,
407 uint64_t offset, uint8_t flags,
408 uint64_t base_oid, unsigned int iov_offset)
412 aio_req = g_malloc(sizeof(*aio_req));
413 aio_req->aiocb = acb;
414 aio_req->iov_offset = iov_offset;
416 aio_req->base_oid = base_oid;
417 aio_req->offset = offset;
418 aio_req->data_len = data_len;
419 aio_req->flags = flags;
420 aio_req->id = s->aioreq_seq_num++;
426 static inline void free_aio_req(BDRVSheepdogState *s, AIOReq *aio_req)
428 SheepdogAIOCB *acb = aio_req->aiocb;
430 acb->cancelable = false;
431 QLIST_REMOVE(aio_req, aio_siblings);
437 static void coroutine_fn sd_finish_aiocb(SheepdogAIOCB *acb)
439 qemu_coroutine_enter(acb->coroutine, NULL);
441 *acb->finished = true;
443 qemu_aio_release(acb);
447 * Check whether the specified acb can be canceled
449 * We can cancel aio when any request belonging to the acb is:
450 * - Not processed by the sheepdog server.
451 * - Not linked to the inflight queue.
453 static bool sd_acb_cancelable(const SheepdogAIOCB *acb)
455 BDRVSheepdogState *s = acb->common.bs->opaque;
458 if (!acb->cancelable) {
462 QLIST_FOREACH(aioreq, &s->inflight_aio_head, aio_siblings) {
463 if (aioreq->aiocb == acb) {
471 static void sd_aio_cancel(BlockDriverAIOCB *blockacb)
473 SheepdogAIOCB *acb = (SheepdogAIOCB *)blockacb;
474 BDRVSheepdogState *s = acb->common.bs->opaque;
475 AIOReq *aioreq, *next;
476 bool finished = false;
478 acb->finished = &finished;
480 if (sd_acb_cancelable(acb)) {
481 /* Remove outstanding requests from pending and failed queues. */
482 QLIST_FOREACH_SAFE(aioreq, &s->pending_aio_head, aio_siblings,
484 if (aioreq->aiocb == acb) {
485 free_aio_req(s, aioreq);
488 QLIST_FOREACH_SAFE(aioreq, &s->failed_aio_head, aio_siblings,
490 if (aioreq->aiocb == acb) {
491 free_aio_req(s, aioreq);
495 assert(acb->nr_pending == 0);
496 sd_finish_aiocb(acb);
503 static const AIOCBInfo sd_aiocb_info = {
504 .aiocb_size = sizeof(SheepdogAIOCB),
505 .cancel = sd_aio_cancel,
508 static SheepdogAIOCB *sd_aio_setup(BlockDriverState *bs, QEMUIOVector *qiov,
509 int64_t sector_num, int nb_sectors)
513 acb = qemu_aio_get(&sd_aiocb_info, bs, NULL, NULL);
517 acb->sector_num = sector_num;
518 acb->nb_sectors = nb_sectors;
520 acb->aio_done_func = NULL;
521 acb->cancelable = true;
522 acb->finished = NULL;
523 acb->coroutine = qemu_coroutine_self();
529 static int connect_to_sdog(BDRVSheepdogState *s)
535 fd = unix_connect(s->host_spec, &err);
537 fd = inet_connect(s->host_spec, &err);
540 int ret = socket_set_nodelay(fd);
542 error_report("%s", strerror(errno));
548 qerror_report_err(err);
551 qemu_set_nonblock(fd);
557 static coroutine_fn int send_co_req(int sockfd, SheepdogReq *hdr, void *data,
562 ret = qemu_co_send(sockfd, hdr, sizeof(*hdr));
563 if (ret != sizeof(*hdr)) {
564 error_report("failed to send a req, %s", strerror(errno));
568 ret = qemu_co_send(sockfd, data, *wlen);
570 error_report("failed to send a req, %s", strerror(errno));
576 static void restart_co_req(void *opaque)
578 Coroutine *co = opaque;
580 qemu_coroutine_enter(co, NULL);
583 typedef struct SheepdogReqCo {
593 static coroutine_fn void do_co_req(void *opaque)
597 SheepdogReqCo *srco = opaque;
598 int sockfd = srco->sockfd;
599 SheepdogReq *hdr = srco->hdr;
600 void *data = srco->data;
601 unsigned int *wlen = srco->wlen;
602 unsigned int *rlen = srco->rlen;
604 co = qemu_coroutine_self();
605 qemu_aio_set_fd_handler(sockfd, NULL, restart_co_req, co);
607 ret = send_co_req(sockfd, hdr, data, wlen);
612 qemu_aio_set_fd_handler(sockfd, restart_co_req, NULL, co);
614 ret = qemu_co_recv(sockfd, hdr, sizeof(*hdr));
615 if (ret != sizeof(*hdr)) {
616 error_report("failed to get a rsp, %s", strerror(errno));
621 if (*rlen > hdr->data_length) {
622 *rlen = hdr->data_length;
626 ret = qemu_co_recv(sockfd, data, *rlen);
628 error_report("failed to get the data, %s", strerror(errno));
635 /* there is at most one request for this sockfd, so it is safe to
636 * set each handler to NULL. */
637 qemu_aio_set_fd_handler(sockfd, NULL, NULL, NULL);
640 srco->finished = true;
643 static int do_req(int sockfd, SheepdogReq *hdr, void *data,
644 unsigned int *wlen, unsigned int *rlen)
647 SheepdogReqCo srco = {
657 if (qemu_in_coroutine()) {
660 co = qemu_coroutine_create(do_co_req);
661 qemu_coroutine_enter(co, &srco);
662 while (!srco.finished) {
670 static void coroutine_fn add_aio_request(BDRVSheepdogState *s, AIOReq *aio_req,
671 struct iovec *iov, int niov, bool create,
672 enum AIOCBState aiocb_type);
673 static void coroutine_fn resend_aioreq(BDRVSheepdogState *s, AIOReq *aio_req);
674 static int reload_inode(BDRVSheepdogState *s, uint32_t snapid, const char *tag);
675 static int get_sheep_fd(BDRVSheepdogState *s);
676 static void co_write_request(void *opaque);
678 static AIOReq *find_pending_req(BDRVSheepdogState *s, uint64_t oid)
682 QLIST_FOREACH(aio_req, &s->pending_aio_head, aio_siblings) {
683 if (aio_req->oid == oid) {
692 * This function searchs pending requests to the object `oid', and
695 static void coroutine_fn send_pending_req(BDRVSheepdogState *s, uint64_t oid)
700 while ((aio_req = find_pending_req(s, oid)) != NULL) {
701 acb = aio_req->aiocb;
702 /* move aio_req from pending list to inflight one */
703 QLIST_REMOVE(aio_req, aio_siblings);
704 QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
705 add_aio_request(s, aio_req, acb->qiov->iov, acb->qiov->niov, false,
710 static coroutine_fn void reconnect_to_sdog(void *opaque)
712 BDRVSheepdogState *s = opaque;
713 AIOReq *aio_req, *next;
715 qemu_aio_set_fd_handler(s->fd, NULL, NULL, NULL);
719 /* Wait for outstanding write requests to be completed. */
720 while (s->co_send != NULL) {
721 co_write_request(opaque);
724 /* Try to reconnect the sheepdog server every one second. */
726 s->fd = get_sheep_fd(s);
728 DPRINTF("Wait for connection to be established\n");
729 co_aio_sleep_ns(bdrv_get_aio_context(s->bs), QEMU_CLOCK_REALTIME,
735 * Now we have to resend all the request in the inflight queue. However,
736 * resend_aioreq() can yield and newly created requests can be added to the
737 * inflight queue before the coroutine is resumed. To avoid mixing them, we
738 * have to move all the inflight requests to the failed queue before
739 * resend_aioreq() is called.
741 QLIST_FOREACH_SAFE(aio_req, &s->inflight_aio_head, aio_siblings, next) {
742 QLIST_REMOVE(aio_req, aio_siblings);
743 QLIST_INSERT_HEAD(&s->failed_aio_head, aio_req, aio_siblings);
746 /* Resend all the failed aio requests. */
747 while (!QLIST_EMPTY(&s->failed_aio_head)) {
748 aio_req = QLIST_FIRST(&s->failed_aio_head);
749 QLIST_REMOVE(aio_req, aio_siblings);
750 QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
751 resend_aioreq(s, aio_req);
756 * Receive responses of the I/O requests.
758 * This function is registered as a fd handler, and called from the
759 * main loop when s->fd is ready for reading responses.
761 static void coroutine_fn aio_read_response(void *opaque)
764 BDRVSheepdogState *s = opaque;
767 AIOReq *aio_req = NULL;
772 ret = qemu_co_recv(fd, &rsp, sizeof(rsp));
773 if (ret != sizeof(rsp)) {
774 error_report("failed to get the header, %s", strerror(errno));
778 /* find the right aio_req from the inflight aio list */
779 QLIST_FOREACH(aio_req, &s->inflight_aio_head, aio_siblings) {
780 if (aio_req->id == rsp.id) {
785 error_report("cannot find aio_req %x", rsp.id);
789 acb = aio_req->aiocb;
791 switch (acb->aiocb_type) {
792 case AIOCB_WRITE_UDATA:
793 /* this coroutine context is no longer suitable for co_recv
794 * because we may send data to update vdi objects */
796 if (!is_data_obj(aio_req->oid)) {
799 idx = data_oid_to_idx(aio_req->oid);
801 if (s->inode.data_vdi_id[idx] != s->inode.vdi_id) {
803 * If the object is newly created one, we need to update
804 * the vdi object (metadata object). min_dirty_data_idx
805 * and max_dirty_data_idx are changed to include updated
806 * index between them.
808 if (rsp.result == SD_RES_SUCCESS) {
809 s->inode.data_vdi_id[idx] = s->inode.vdi_id;
810 s->max_dirty_data_idx = MAX(idx, s->max_dirty_data_idx);
811 s->min_dirty_data_idx = MIN(idx, s->min_dirty_data_idx);
814 * Some requests may be blocked because simultaneous
815 * create requests are not allowed, so we search the
816 * pending requests here.
818 send_pending_req(s, aio_req->oid);
821 case AIOCB_READ_UDATA:
822 ret = qemu_co_recvv(fd, acb->qiov->iov, acb->qiov->niov,
823 aio_req->iov_offset, rsp.data_length);
824 if (ret != rsp.data_length) {
825 error_report("failed to get the data, %s", strerror(errno));
829 case AIOCB_FLUSH_CACHE:
830 if (rsp.result == SD_RES_INVALID_PARMS) {
831 DPRINTF("disable cache since the server doesn't support it\n");
832 s->cache_flags = SD_FLAG_CMD_DIRECT;
833 rsp.result = SD_RES_SUCCESS;
836 case AIOCB_DISCARD_OBJ:
837 switch (rsp.result) {
838 case SD_RES_INVALID_PARMS:
839 error_report("sheep(%s) doesn't support discard command",
841 rsp.result = SD_RES_SUCCESS;
842 s->discard_supported = false;
845 idx = data_oid_to_idx(aio_req->oid);
846 s->inode.data_vdi_id[idx] = 0;
853 switch (rsp.result) {
856 case SD_RES_READONLY:
857 if (s->inode.vdi_id == oid_to_vid(aio_req->oid)) {
858 ret = reload_inode(s, 0, "");
863 if (is_data_obj(aio_req->oid)) {
864 aio_req->oid = vid_to_data_oid(s->inode.vdi_id,
865 data_oid_to_idx(aio_req->oid));
867 aio_req->oid = vid_to_vdi_oid(s->inode.vdi_id);
869 resend_aioreq(s, aio_req);
873 error_report("%s", sd_strerror(rsp.result));
877 free_aio_req(s, aio_req);
878 if (!acb->nr_pending) {
880 * We've finished all requests which belong to the AIOCB, so
881 * we can switch back to sd_co_readv/writev now.
883 acb->aio_done_func(acb);
890 reconnect_to_sdog(opaque);
893 static void co_read_response(void *opaque)
895 BDRVSheepdogState *s = opaque;
898 s->co_recv = qemu_coroutine_create(aio_read_response);
901 qemu_coroutine_enter(s->co_recv, opaque);
904 static void co_write_request(void *opaque)
906 BDRVSheepdogState *s = opaque;
908 qemu_coroutine_enter(s->co_send, NULL);
912 * Return a socket discriptor to read/write objects.
914 * We cannot use this discriptor for other operations because
915 * the block driver may be on waiting response from the server.
917 static int get_sheep_fd(BDRVSheepdogState *s)
921 fd = connect_to_sdog(s);
926 qemu_aio_set_fd_handler(fd, co_read_response, NULL, s);
930 static int sd_parse_uri(BDRVSheepdogState *s, const char *filename,
931 char *vdi, uint32_t *snapid, char *tag)
934 QueryParams *qp = NULL;
937 uri = uri_parse(filename);
943 if (!strcmp(uri->scheme, "sheepdog")) {
945 } else if (!strcmp(uri->scheme, "sheepdog+tcp")) {
947 } else if (!strcmp(uri->scheme, "sheepdog+unix")) {
954 if (uri->path == NULL || !strcmp(uri->path, "/")) {
958 pstrcpy(vdi, SD_MAX_VDI_LEN, uri->path + 1);
960 qp = query_params_parse(uri->query);
961 if (qp->n > 1 || (s->is_unix && !qp->n) || (!s->is_unix && qp->n)) {
967 /* sheepdog+unix:///vdiname?socket=path */
968 if (uri->server || uri->port || strcmp(qp->p[0].name, "socket")) {
972 s->host_spec = g_strdup(qp->p[0].value);
974 /* sheepdog[+tcp]://[host:port]/vdiname */
975 s->host_spec = g_strdup_printf("%s:%d", uri->server ?: SD_DEFAULT_ADDR,
976 uri->port ?: SD_DEFAULT_PORT);
981 *snapid = strtoul(uri->fragment, NULL, 10);
983 pstrcpy(tag, SD_MAX_VDI_TAG_LEN, uri->fragment);
986 *snapid = CURRENT_VDI_ID; /* search current vdi */
991 query_params_free(qp);
998 * Parse a filename (old syntax)
1000 * filename must be one of the following formats:
1002 * 2. [vdiname]:[snapid]
1003 * 3. [vdiname]:[tag]
1004 * 4. [hostname]:[port]:[vdiname]
1005 * 5. [hostname]:[port]:[vdiname]:[snapid]
1006 * 6. [hostname]:[port]:[vdiname]:[tag]
1008 * You can boot from the snapshot images by specifying `snapid` or
1011 * You can run VMs outside the Sheepdog cluster by specifying
1012 * `hostname' and `port' (experimental).
1014 static int parse_vdiname(BDRVSheepdogState *s, const char *filename,
1015 char *vdi, uint32_t *snapid, char *tag)
1018 const char *host_spec, *vdi_spec;
1021 strstart(filename, "sheepdog:", (const char **)&filename);
1022 p = q = g_strdup(filename);
1024 /* count the number of separators */
1034 /* use the first two tokens as host_spec. */
1047 p = strchr(vdi_spec, ':');
1052 uri = g_strdup_printf("sheepdog://%s/%s", host_spec, vdi_spec);
1054 ret = sd_parse_uri(s, uri, vdi, snapid, tag);
1062 static int find_vdi_name(BDRVSheepdogState *s, const char *filename,
1063 uint32_t snapid, const char *tag, uint32_t *vid,
1068 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
1069 unsigned int wlen, rlen = 0;
1070 char buf[SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN];
1072 fd = connect_to_sdog(s);
1077 /* This pair of strncpy calls ensures that the buffer is zero-filled,
1078 * which is desirable since we'll soon be sending those bytes, and
1079 * don't want the send_req to read uninitialized data.
1081 strncpy(buf, filename, SD_MAX_VDI_LEN);
1082 strncpy(buf + SD_MAX_VDI_LEN, tag, SD_MAX_VDI_TAG_LEN);
1084 memset(&hdr, 0, sizeof(hdr));
1086 hdr.opcode = SD_OP_LOCK_VDI;
1088 hdr.opcode = SD_OP_GET_VDI_INFO;
1090 wlen = SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN;
1091 hdr.proto_ver = SD_PROTO_VER;
1092 hdr.data_length = wlen;
1093 hdr.snapid = snapid;
1094 hdr.flags = SD_FLAG_CMD_WRITE;
1096 ret = do_req(fd, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
1101 if (rsp->result != SD_RES_SUCCESS) {
1102 error_report("cannot get vdi info, %s, %s %d %s",
1103 sd_strerror(rsp->result), filename, snapid, tag);
1104 if (rsp->result == SD_RES_NO_VDI) {
1119 static void coroutine_fn add_aio_request(BDRVSheepdogState *s, AIOReq *aio_req,
1120 struct iovec *iov, int niov, bool create,
1121 enum AIOCBState aiocb_type)
1123 int nr_copies = s->inode.nr_copies;
1125 unsigned int wlen = 0;
1127 uint64_t oid = aio_req->oid;
1128 unsigned int datalen = aio_req->data_len;
1129 uint64_t offset = aio_req->offset;
1130 uint8_t flags = aio_req->flags;
1131 uint64_t old_oid = aio_req->base_oid;
1134 error_report("bug");
1137 memset(&hdr, 0, sizeof(hdr));
1139 switch (aiocb_type) {
1140 case AIOCB_FLUSH_CACHE:
1141 hdr.opcode = SD_OP_FLUSH_VDI;
1143 case AIOCB_READ_UDATA:
1144 hdr.opcode = SD_OP_READ_OBJ;
1147 case AIOCB_WRITE_UDATA:
1149 hdr.opcode = SD_OP_CREATE_AND_WRITE_OBJ;
1151 hdr.opcode = SD_OP_WRITE_OBJ;
1154 hdr.flags = SD_FLAG_CMD_WRITE | flags;
1156 case AIOCB_DISCARD_OBJ:
1157 hdr.opcode = SD_OP_DISCARD_OBJ;
1161 if (s->cache_flags) {
1162 hdr.flags |= s->cache_flags;
1166 hdr.cow_oid = old_oid;
1167 hdr.copies = s->inode.nr_copies;
1169 hdr.data_length = datalen;
1170 hdr.offset = offset;
1172 hdr.id = aio_req->id;
1174 qemu_co_mutex_lock(&s->lock);
1175 s->co_send = qemu_coroutine_self();
1176 qemu_aio_set_fd_handler(s->fd, co_read_response, co_write_request, s);
1177 socket_set_cork(s->fd, 1);
1180 ret = qemu_co_send(s->fd, &hdr, sizeof(hdr));
1181 if (ret != sizeof(hdr)) {
1182 error_report("failed to send a req, %s", strerror(errno));
1187 ret = qemu_co_sendv(s->fd, iov, niov, aio_req->iov_offset, wlen);
1189 error_report("failed to send a data, %s", strerror(errno));
1193 socket_set_cork(s->fd, 0);
1194 qemu_aio_set_fd_handler(s->fd, co_read_response, NULL, s);
1196 qemu_co_mutex_unlock(&s->lock);
1199 static int read_write_object(int fd, char *buf, uint64_t oid, uint8_t copies,
1200 unsigned int datalen, uint64_t offset,
1201 bool write, bool create, uint32_t cache_flags)
1204 SheepdogObjRsp *rsp = (SheepdogObjRsp *)&hdr;
1205 unsigned int wlen, rlen;
1208 memset(&hdr, 0, sizeof(hdr));
1213 hdr.flags = SD_FLAG_CMD_WRITE;
1215 hdr.opcode = SD_OP_CREATE_AND_WRITE_OBJ;
1217 hdr.opcode = SD_OP_WRITE_OBJ;
1222 hdr.opcode = SD_OP_READ_OBJ;
1225 hdr.flags |= cache_flags;
1228 hdr.data_length = datalen;
1229 hdr.offset = offset;
1230 hdr.copies = copies;
1232 ret = do_req(fd, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
1234 error_report("failed to send a request to the sheep");
1238 switch (rsp->result) {
1239 case SD_RES_SUCCESS:
1242 error_report("%s", sd_strerror(rsp->result));
1247 static int read_object(int fd, char *buf, uint64_t oid, uint8_t copies,
1248 unsigned int datalen, uint64_t offset,
1249 uint32_t cache_flags)
1251 return read_write_object(fd, buf, oid, copies, datalen, offset, false,
1252 false, cache_flags);
1255 static int write_object(int fd, char *buf, uint64_t oid, uint8_t copies,
1256 unsigned int datalen, uint64_t offset, bool create,
1257 uint32_t cache_flags)
1259 return read_write_object(fd, buf, oid, copies, datalen, offset, true,
1260 create, cache_flags);
1263 /* update inode with the latest state */
1264 static int reload_inode(BDRVSheepdogState *s, uint32_t snapid, const char *tag)
1266 SheepdogInode *inode;
1270 fd = connect_to_sdog(s);
1275 inode = g_malloc(sizeof(s->inode));
1277 ret = find_vdi_name(s, s->name, snapid, tag, &vid, false);
1282 ret = read_object(fd, (char *)inode, vid_to_vdi_oid(vid),
1283 s->inode.nr_copies, sizeof(*inode), 0, s->cache_flags);
1288 if (inode->vdi_id != s->inode.vdi_id) {
1289 memcpy(&s->inode, inode, sizeof(s->inode));
1299 /* Return true if the specified request is linked to the pending list. */
1300 static bool check_simultaneous_create(BDRVSheepdogState *s, AIOReq *aio_req)
1303 QLIST_FOREACH(areq, &s->inflight_aio_head, aio_siblings) {
1304 if (areq != aio_req && areq->oid == aio_req->oid) {
1306 * Sheepdog cannot handle simultaneous create requests to the same
1307 * object, so we cannot send the request until the previous request
1310 DPRINTF("simultaneous create to %" PRIx64 "\n", aio_req->oid);
1312 aio_req->base_oid = 0;
1313 QLIST_REMOVE(aio_req, aio_siblings);
1314 QLIST_INSERT_HEAD(&s->pending_aio_head, aio_req, aio_siblings);
1322 static void coroutine_fn resend_aioreq(BDRVSheepdogState *s, AIOReq *aio_req)
1324 SheepdogAIOCB *acb = aio_req->aiocb;
1325 bool create = false;
1327 /* check whether this request becomes a CoW one */
1328 if (acb->aiocb_type == AIOCB_WRITE_UDATA && is_data_obj(aio_req->oid)) {
1329 int idx = data_oid_to_idx(aio_req->oid);
1331 if (is_data_obj_writable(&s->inode, idx)) {
1335 if (check_simultaneous_create(s, aio_req)) {
1339 if (s->inode.data_vdi_id[idx]) {
1340 aio_req->base_oid = vid_to_data_oid(s->inode.data_vdi_id[idx], idx);
1341 aio_req->flags |= SD_FLAG_CMD_COW;
1346 if (is_data_obj(aio_req->oid)) {
1347 add_aio_request(s, aio_req, acb->qiov->iov, acb->qiov->niov, create,
1351 iov.iov_base = &s->inode;
1352 iov.iov_len = sizeof(s->inode);
1353 add_aio_request(s, aio_req, &iov, 1, false, AIOCB_WRITE_UDATA);
1357 /* TODO Convert to fine grained options */
1358 static QemuOptsList runtime_opts = {
1360 .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
1364 .type = QEMU_OPT_STRING,
1365 .help = "URL to the sheepdog image",
1367 { /* end of list */ }
1371 static int sd_open(BlockDriverState *bs, QDict *options, int flags,
1376 BDRVSheepdogState *s = bs->opaque;
1377 char vdi[SD_MAX_VDI_LEN], tag[SD_MAX_VDI_TAG_LEN];
1381 Error *local_err = NULL;
1382 const char *filename;
1386 opts = qemu_opts_create_nofail(&runtime_opts);
1387 qemu_opts_absorb_qdict(opts, options, &local_err);
1388 if (error_is_set(&local_err)) {
1389 qerror_report_err(local_err);
1390 error_free(local_err);
1395 filename = qemu_opt_get(opts, "filename");
1397 QLIST_INIT(&s->inflight_aio_head);
1398 QLIST_INIT(&s->pending_aio_head);
1399 QLIST_INIT(&s->failed_aio_head);
1402 memset(vdi, 0, sizeof(vdi));
1403 memset(tag, 0, sizeof(tag));
1405 if (strstr(filename, "://")) {
1406 ret = sd_parse_uri(s, filename, vdi, &snapid, tag);
1408 ret = parse_vdiname(s, filename, vdi, &snapid, tag);
1413 s->fd = get_sheep_fd(s);
1419 ret = find_vdi_name(s, vdi, snapid, tag, &vid, true);
1425 * QEMU block layer emulates writethrough cache as 'writeback + flush', so
1426 * we always set SD_FLAG_CMD_CACHE (writeback cache) as default.
1428 s->cache_flags = SD_FLAG_CMD_CACHE;
1429 if (flags & BDRV_O_NOCACHE) {
1430 s->cache_flags = SD_FLAG_CMD_DIRECT;
1432 s->discard_supported = true;
1434 if (snapid || tag[0] != '\0') {
1435 DPRINTF("%" PRIx32 " snapshot inode was open.\n", vid);
1436 s->is_snapshot = true;
1439 fd = connect_to_sdog(s);
1445 buf = g_malloc(SD_INODE_SIZE);
1446 ret = read_object(fd, buf, vid_to_vdi_oid(vid), 0, SD_INODE_SIZE, 0,
1455 memcpy(&s->inode, buf, sizeof(s->inode));
1456 s->min_dirty_data_idx = UINT32_MAX;
1457 s->max_dirty_data_idx = 0;
1459 bs->total_sectors = s->inode.vdi_size / BDRV_SECTOR_SIZE;
1460 pstrcpy(s->name, sizeof(s->name), vdi);
1461 qemu_co_mutex_init(&s->lock);
1462 qemu_opts_del(opts);
1466 qemu_aio_set_fd_handler(s->fd, NULL, NULL, NULL);
1470 qemu_opts_del(opts);
1475 static int do_sd_create(BDRVSheepdogState *s, uint32_t *vdi_id, int snapshot)
1478 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
1480 unsigned int wlen, rlen = 0;
1481 char buf[SD_MAX_VDI_LEN];
1483 fd = connect_to_sdog(s);
1488 /* FIXME: would it be better to fail (e.g., return -EIO) when filename
1489 * does not fit in buf? For now, just truncate and avoid buffer overrun.
1491 memset(buf, 0, sizeof(buf));
1492 pstrcpy(buf, sizeof(buf), s->name);
1494 memset(&hdr, 0, sizeof(hdr));
1495 hdr.opcode = SD_OP_NEW_VDI;
1496 hdr.vdi_id = s->inode.vdi_id;
1498 wlen = SD_MAX_VDI_LEN;
1500 hdr.flags = SD_FLAG_CMD_WRITE;
1501 hdr.snapid = snapshot;
1503 hdr.data_length = wlen;
1504 hdr.vdi_size = s->inode.vdi_size;
1505 hdr.copy_policy = s->inode.copy_policy;
1506 hdr.copies = s->inode.nr_copies;
1508 ret = do_req(fd, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
1516 if (rsp->result != SD_RES_SUCCESS) {
1517 error_report("%s, %s", sd_strerror(rsp->result), s->inode.name);
1522 *vdi_id = rsp->vdi_id;
1528 static int sd_prealloc(const char *filename)
1530 BlockDriverState *bs = NULL;
1531 uint32_t idx, max_idx;
1533 void *buf = g_malloc0(SD_DATA_OBJ_SIZE);
1534 Error *local_err = NULL;
1537 ret = bdrv_file_open(&bs, filename, NULL, BDRV_O_RDWR, &local_err);
1539 qerror_report_err(local_err);
1540 error_free(local_err);
1544 vdi_size = bdrv_getlength(bs);
1549 max_idx = DIV_ROUND_UP(vdi_size, SD_DATA_OBJ_SIZE);
1551 for (idx = 0; idx < max_idx; idx++) {
1553 * The created image can be a cloned image, so we need to read
1554 * a data from the source image.
1556 ret = bdrv_pread(bs, idx * SD_DATA_OBJ_SIZE, buf, SD_DATA_OBJ_SIZE);
1560 ret = bdrv_pwrite(bs, idx * SD_DATA_OBJ_SIZE, buf, SD_DATA_OBJ_SIZE);
1575 * Sheepdog support two kinds of redundancy, full replication and erasure
1578 * # create a fully replicated vdi with x copies
1579 * -o redundancy=x (1 <= x <= SD_MAX_COPIES)
1581 * # create a erasure coded vdi with x data strips and y parity strips
1582 * -o redundancy=x:y (x must be one of {2,4,8,16} and 1 <= y < SD_EC_MAX_STRIP)
1584 static int parse_redundancy(BDRVSheepdogState *s, const char *opt)
1586 struct SheepdogInode *inode = &s->inode;
1587 const char *n1, *n2;
1591 pstrcpy(p, sizeof(p), opt);
1592 n1 = strtok(p, ":");
1593 n2 = strtok(NULL, ":");
1599 copy = strtol(n1, NULL, 10);
1600 if (copy > SD_MAX_COPIES || copy < 1) {
1604 inode->copy_policy = 0;
1605 inode->nr_copies = copy;
1609 if (copy != 2 && copy != 4 && copy != 8 && copy != 16) {
1613 parity = strtol(n2, NULL, 10);
1614 if (parity >= SD_EC_MAX_STRIP || parity < 1) {
1619 * 4 bits for parity and 4 bits for data.
1620 * We have to compress upper data bits because it can't represent 16
1622 inode->copy_policy = ((copy / 2) << 4) + parity;
1623 inode->nr_copies = copy + parity;
1628 static int sd_create(const char *filename, QEMUOptionParameter *options,
1633 char *backing_file = NULL;
1634 BDRVSheepdogState *s;
1635 char tag[SD_MAX_VDI_TAG_LEN];
1637 bool prealloc = false;
1638 Error *local_err = NULL;
1640 s = g_malloc0(sizeof(BDRVSheepdogState));
1642 memset(tag, 0, sizeof(tag));
1643 if (strstr(filename, "://")) {
1644 ret = sd_parse_uri(s, filename, s->name, &snapid, tag);
1646 ret = parse_vdiname(s, filename, s->name, &snapid, tag);
1652 while (options && options->name) {
1653 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
1654 s->inode.vdi_size = options->value.n;
1655 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
1656 backing_file = options->value.s;
1657 } else if (!strcmp(options->name, BLOCK_OPT_PREALLOC)) {
1658 if (!options->value.s || !strcmp(options->value.s, "off")) {
1660 } else if (!strcmp(options->value.s, "full")) {
1663 error_report("Invalid preallocation mode: '%s'",
1668 } else if (!strcmp(options->name, BLOCK_OPT_REDUNDANCY)) {
1669 ret = parse_redundancy(s, options->value.s);
1677 if (s->inode.vdi_size > SD_MAX_VDI_SIZE) {
1678 error_report("too big image size");
1684 BlockDriverState *bs;
1685 BDRVSheepdogState *s;
1688 /* Currently, only Sheepdog backing image is supported. */
1689 drv = bdrv_find_protocol(backing_file, true);
1690 if (!drv || strcmp(drv->protocol_name, "sheepdog") != 0) {
1691 error_report("backing_file must be a sheepdog image");
1696 ret = bdrv_file_open(&bs, backing_file, NULL, 0, &local_err);
1698 qerror_report_err(local_err);
1699 error_free(local_err);
1705 if (!is_snapshot(&s->inode)) {
1706 error_report("cannot clone from a non snapshot vdi");
1715 ret = do_sd_create(s, &vid, 0);
1716 if (!prealloc || ret) {
1720 ret = sd_prealloc(filename);
1726 static void sd_close(BlockDriverState *bs)
1728 BDRVSheepdogState *s = bs->opaque;
1730 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
1731 unsigned int wlen, rlen = 0;
1734 DPRINTF("%s\n", s->name);
1736 fd = connect_to_sdog(s);
1741 memset(&hdr, 0, sizeof(hdr));
1743 hdr.opcode = SD_OP_RELEASE_VDI;
1744 hdr.vdi_id = s->inode.vdi_id;
1745 wlen = strlen(s->name) + 1;
1746 hdr.data_length = wlen;
1747 hdr.flags = SD_FLAG_CMD_WRITE;
1749 ret = do_req(fd, (SheepdogReq *)&hdr, s->name, &wlen, &rlen);
1753 if (!ret && rsp->result != SD_RES_SUCCESS &&
1754 rsp->result != SD_RES_VDI_NOT_LOCKED) {
1755 error_report("%s, %s", sd_strerror(rsp->result), s->name);
1758 qemu_aio_set_fd_handler(s->fd, NULL, NULL, NULL);
1760 g_free(s->host_spec);
1763 static int64_t sd_getlength(BlockDriverState *bs)
1765 BDRVSheepdogState *s = bs->opaque;
1767 return s->inode.vdi_size;
1770 static int sd_truncate(BlockDriverState *bs, int64_t offset)
1772 BDRVSheepdogState *s = bs->opaque;
1774 unsigned int datalen;
1776 if (offset < s->inode.vdi_size) {
1777 error_report("shrinking is not supported");
1779 } else if (offset > SD_MAX_VDI_SIZE) {
1780 error_report("too big image size");
1784 fd = connect_to_sdog(s);
1789 /* we don't need to update entire object */
1790 datalen = SD_INODE_SIZE - sizeof(s->inode.data_vdi_id);
1791 s->inode.vdi_size = offset;
1792 ret = write_object(fd, (char *)&s->inode, vid_to_vdi_oid(s->inode.vdi_id),
1793 s->inode.nr_copies, datalen, 0, false, s->cache_flags);
1797 error_report("failed to update an inode.");
1804 * This function is called after writing data objects. If we need to
1805 * update metadata, this sends a write request to the vdi object.
1806 * Otherwise, this switches back to sd_co_readv/writev.
1808 static void coroutine_fn sd_write_done(SheepdogAIOCB *acb)
1810 BDRVSheepdogState *s = acb->common.bs->opaque;
1813 uint32_t offset, data_len, mn, mx;
1815 mn = s->min_dirty_data_idx;
1816 mx = s->max_dirty_data_idx;
1818 /* we need to update the vdi object. */
1819 offset = sizeof(s->inode) - sizeof(s->inode.data_vdi_id) +
1820 mn * sizeof(s->inode.data_vdi_id[0]);
1821 data_len = (mx - mn + 1) * sizeof(s->inode.data_vdi_id[0]);
1823 s->min_dirty_data_idx = UINT32_MAX;
1824 s->max_dirty_data_idx = 0;
1826 iov.iov_base = &s->inode;
1827 iov.iov_len = sizeof(s->inode);
1828 aio_req = alloc_aio_req(s, acb, vid_to_vdi_oid(s->inode.vdi_id),
1829 data_len, offset, 0, 0, offset);
1830 QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
1831 add_aio_request(s, aio_req, &iov, 1, false, AIOCB_WRITE_UDATA);
1833 acb->aio_done_func = sd_finish_aiocb;
1834 acb->aiocb_type = AIOCB_WRITE_UDATA;
1838 sd_finish_aiocb(acb);
1841 /* Delete current working VDI on the snapshot chain */
1842 static bool sd_delete(BDRVSheepdogState *s)
1844 unsigned int wlen = SD_MAX_VDI_LEN, rlen = 0;
1845 SheepdogVdiReq hdr = {
1846 .opcode = SD_OP_DEL_VDI,
1847 .vdi_id = s->inode.vdi_id,
1848 .data_length = wlen,
1849 .flags = SD_FLAG_CMD_WRITE,
1851 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
1854 fd = connect_to_sdog(s);
1859 ret = do_req(fd, (SheepdogReq *)&hdr, s->name, &wlen, &rlen);
1864 switch (rsp->result) {
1866 error_report("%s was already deleted", s->name);
1868 case SD_RES_SUCCESS:
1871 error_report("%s, %s", sd_strerror(rsp->result), s->name);
1879 * Create a writable VDI from a snapshot
1881 static int sd_create_branch(BDRVSheepdogState *s)
1888 DPRINTF("%" PRIx32 " is snapshot.\n", s->inode.vdi_id);
1890 buf = g_malloc(SD_INODE_SIZE);
1893 * Even If deletion fails, we will just create extra snapshot based on
1894 * the workding VDI which was supposed to be deleted. So no need to
1897 deleted = sd_delete(s);
1898 ret = do_sd_create(s, &vid, !deleted);
1903 DPRINTF("%" PRIx32 " is created.\n", vid);
1905 fd = connect_to_sdog(s);
1911 ret = read_object(fd, buf, vid_to_vdi_oid(vid), s->inode.nr_copies,
1912 SD_INODE_SIZE, 0, s->cache_flags);
1920 memcpy(&s->inode, buf, sizeof(s->inode));
1922 s->is_snapshot = false;
1924 DPRINTF("%" PRIx32 " was newly created.\n", s->inode.vdi_id);
1933 * Send I/O requests to the server.
1935 * This function sends requests to the server, links the requests to
1936 * the inflight_list in BDRVSheepdogState, and exits without
1937 * waiting the response. The responses are received in the
1938 * `aio_read_response' function which is called from the main loop as
1941 * Returns 1 when we need to wait a response, 0 when there is no sent
1942 * request and -errno in error cases.
1944 static int coroutine_fn sd_co_rw_vector(void *p)
1946 SheepdogAIOCB *acb = p;
1948 unsigned long len, done = 0, total = acb->nb_sectors * BDRV_SECTOR_SIZE;
1949 unsigned long idx = acb->sector_num * BDRV_SECTOR_SIZE / SD_DATA_OBJ_SIZE;
1951 uint64_t offset = (acb->sector_num * BDRV_SECTOR_SIZE) % SD_DATA_OBJ_SIZE;
1952 BDRVSheepdogState *s = acb->common.bs->opaque;
1953 SheepdogInode *inode = &s->inode;
1956 if (acb->aiocb_type == AIOCB_WRITE_UDATA && s->is_snapshot) {
1958 * In the case we open the snapshot VDI, Sheepdog creates the
1959 * writable VDI when we do a write operation first.
1961 ret = sd_create_branch(s);
1969 * Make sure we don't free the aiocb before we are done with all requests.
1970 * This additional reference is dropped at the end of this function.
1974 while (done != total) {
1976 uint64_t old_oid = 0;
1977 bool create = false;
1979 oid = vid_to_data_oid(inode->data_vdi_id[idx], idx);
1981 len = MIN(total - done, SD_DATA_OBJ_SIZE - offset);
1983 switch (acb->aiocb_type) {
1984 case AIOCB_READ_UDATA:
1985 if (!inode->data_vdi_id[idx]) {
1986 qemu_iovec_memset(acb->qiov, done, 0, len);
1990 case AIOCB_WRITE_UDATA:
1991 if (!inode->data_vdi_id[idx]) {
1993 } else if (!is_data_obj_writable(inode, idx)) {
1997 flags = SD_FLAG_CMD_COW;
2000 case AIOCB_DISCARD_OBJ:
2002 * We discard the object only when the whole object is
2003 * 1) allocated 2) trimmed. Otherwise, simply skip it.
2005 if (len != SD_DATA_OBJ_SIZE || inode->data_vdi_id[idx] == 0) {
2014 DPRINTF("update ino (%" PRIu32 ") %" PRIu64 " %" PRIu64 " %ld\n",
2016 vid_to_data_oid(inode->data_vdi_id[idx], idx), idx);
2017 oid = vid_to_data_oid(inode->vdi_id, idx);
2018 DPRINTF("new oid %" PRIx64 "\n", oid);
2021 aio_req = alloc_aio_req(s, acb, oid, len, offset, flags, old_oid, done);
2022 QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
2025 if (check_simultaneous_create(s, aio_req)) {
2030 add_aio_request(s, aio_req, acb->qiov->iov, acb->qiov->niov, create,
2038 if (!--acb->nr_pending) {
2044 static coroutine_fn int sd_co_writev(BlockDriverState *bs, int64_t sector_num,
2045 int nb_sectors, QEMUIOVector *qiov)
2050 if (bs->growable && sector_num + nb_sectors > bs->total_sectors) {
2051 ret = sd_truncate(bs, (sector_num + nb_sectors) * BDRV_SECTOR_SIZE);
2055 bs->total_sectors = sector_num + nb_sectors;
2058 acb = sd_aio_setup(bs, qiov, sector_num, nb_sectors);
2059 acb->aio_done_func = sd_write_done;
2060 acb->aiocb_type = AIOCB_WRITE_UDATA;
2062 ret = sd_co_rw_vector(acb);
2064 qemu_aio_release(acb);
2068 qemu_coroutine_yield();
2073 static coroutine_fn int sd_co_readv(BlockDriverState *bs, int64_t sector_num,
2074 int nb_sectors, QEMUIOVector *qiov)
2079 acb = sd_aio_setup(bs, qiov, sector_num, nb_sectors);
2080 acb->aiocb_type = AIOCB_READ_UDATA;
2081 acb->aio_done_func = sd_finish_aiocb;
2083 ret = sd_co_rw_vector(acb);
2085 qemu_aio_release(acb);
2089 qemu_coroutine_yield();
2094 static int coroutine_fn sd_co_flush_to_disk(BlockDriverState *bs)
2096 BDRVSheepdogState *s = bs->opaque;
2100 if (s->cache_flags != SD_FLAG_CMD_CACHE) {
2104 acb = sd_aio_setup(bs, NULL, 0, 0);
2105 acb->aiocb_type = AIOCB_FLUSH_CACHE;
2106 acb->aio_done_func = sd_finish_aiocb;
2108 aio_req = alloc_aio_req(s, acb, vid_to_vdi_oid(s->inode.vdi_id),
2110 QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
2111 add_aio_request(s, aio_req, NULL, 0, false, acb->aiocb_type);
2113 qemu_coroutine_yield();
2117 static int sd_snapshot_create(BlockDriverState *bs, QEMUSnapshotInfo *sn_info)
2119 BDRVSheepdogState *s = bs->opaque;
2122 SheepdogInode *inode;
2123 unsigned int datalen;
2125 DPRINTF("sn_info: name %s id_str %s s: name %s vm_state_size %" PRId64 " "
2126 "is_snapshot %d\n", sn_info->name, sn_info->id_str,
2127 s->name, sn_info->vm_state_size, s->is_snapshot);
2129 if (s->is_snapshot) {
2130 error_report("You can't create a snapshot of a snapshot VDI, "
2131 "%s (%" PRIu32 ").", s->name, s->inode.vdi_id);
2136 DPRINTF("%s %s\n", sn_info->name, sn_info->id_str);
2138 s->inode.vm_state_size = sn_info->vm_state_size;
2139 s->inode.vm_clock_nsec = sn_info->vm_clock_nsec;
2140 /* It appears that inode.tag does not require a NUL terminator,
2141 * which means this use of strncpy is ok.
2143 strncpy(s->inode.tag, sn_info->name, sizeof(s->inode.tag));
2144 /* we don't need to update entire object */
2145 datalen = SD_INODE_SIZE - sizeof(s->inode.data_vdi_id);
2147 /* refresh inode. */
2148 fd = connect_to_sdog(s);
2154 ret = write_object(fd, (char *)&s->inode, vid_to_vdi_oid(s->inode.vdi_id),
2155 s->inode.nr_copies, datalen, 0, false, s->cache_flags);
2157 error_report("failed to write snapshot's inode.");
2161 ret = do_sd_create(s, &new_vid, 1);
2163 error_report("failed to create inode for snapshot. %s",
2168 inode = (SheepdogInode *)g_malloc(datalen);
2170 ret = read_object(fd, (char *)inode, vid_to_vdi_oid(new_vid),
2171 s->inode.nr_copies, datalen, 0, s->cache_flags);
2174 error_report("failed to read new inode info. %s", strerror(errno));
2178 memcpy(&s->inode, inode, datalen);
2179 DPRINTF("s->inode: name %s snap_id %x oid %x\n",
2180 s->inode.name, s->inode.snap_id, s->inode.vdi_id);
2188 * We implement rollback(loadvm) operation to the specified snapshot by
2189 * 1) switch to the snapshot
2190 * 2) rely on sd_create_branch to delete working VDI and
2191 * 3) create a new working VDI based on the speicified snapshot
2193 static int sd_snapshot_goto(BlockDriverState *bs, const char *snapshot_id)
2195 BDRVSheepdogState *s = bs->opaque;
2196 BDRVSheepdogState *old_s;
2197 char tag[SD_MAX_VDI_TAG_LEN];
2198 uint32_t snapid = 0;
2201 old_s = g_malloc(sizeof(BDRVSheepdogState));
2203 memcpy(old_s, s, sizeof(BDRVSheepdogState));
2205 snapid = strtoul(snapshot_id, NULL, 10);
2209 pstrcpy(tag, sizeof(tag), snapshot_id);
2212 ret = reload_inode(s, snapid, tag);
2217 ret = sd_create_branch(s);
2226 /* recover bdrv_sd_state */
2227 memcpy(s, old_s, sizeof(BDRVSheepdogState));
2230 error_report("failed to open. recover old bdrv_sd_state.");
2235 static int sd_snapshot_delete(BlockDriverState *bs,
2236 const char *snapshot_id,
2240 /* FIXME: Delete specified snapshot id. */
2244 static int sd_snapshot_list(BlockDriverState *bs, QEMUSnapshotInfo **psn_tab)
2246 BDRVSheepdogState *s = bs->opaque;
2248 int fd, nr = 1024, ret, max = BITS_TO_LONGS(SD_NR_VDIS) * sizeof(long);
2249 QEMUSnapshotInfo *sn_tab = NULL;
2250 unsigned wlen, rlen;
2252 static SheepdogInode inode;
2253 unsigned long *vdi_inuse;
2254 unsigned int start_nr;
2258 vdi_inuse = g_malloc(max);
2260 fd = connect_to_sdog(s);
2269 memset(&req, 0, sizeof(req));
2271 req.opcode = SD_OP_READ_VDIS;
2272 req.data_length = max;
2274 ret = do_req(fd, (SheepdogReq *)&req, vdi_inuse, &wlen, &rlen);
2281 sn_tab = g_malloc0(nr * sizeof(*sn_tab));
2283 /* calculate a vdi id with hash function */
2284 hval = fnv_64a_buf(s->name, strlen(s->name), FNV1A_64_INIT);
2285 start_nr = hval & (SD_NR_VDIS - 1);
2287 fd = connect_to_sdog(s);
2293 for (vid = start_nr; found < nr; vid = (vid + 1) % SD_NR_VDIS) {
2294 if (!test_bit(vid, vdi_inuse)) {
2298 /* we don't need to read entire object */
2299 ret = read_object(fd, (char *)&inode, vid_to_vdi_oid(vid),
2300 0, SD_INODE_SIZE - sizeof(inode.data_vdi_id), 0,
2307 if (!strcmp(inode.name, s->name) && is_snapshot(&inode)) {
2308 sn_tab[found].date_sec = inode.snap_ctime >> 32;
2309 sn_tab[found].date_nsec = inode.snap_ctime & 0xffffffff;
2310 sn_tab[found].vm_state_size = inode.vm_state_size;
2311 sn_tab[found].vm_clock_nsec = inode.vm_clock_nsec;
2313 snprintf(sn_tab[found].id_str, sizeof(sn_tab[found].id_str), "%u",
2315 pstrcpy(sn_tab[found].name,
2316 MIN(sizeof(sn_tab[found].name), sizeof(inode.tag)),
2335 static int do_load_save_vmstate(BDRVSheepdogState *s, uint8_t *data,
2336 int64_t pos, int size, int load)
2339 int fd, ret = 0, remaining = size;
2340 unsigned int data_len;
2341 uint64_t vmstate_oid;
2344 uint32_t vdi_id = load ? s->inode.parent_vdi_id : s->inode.vdi_id;
2346 fd = connect_to_sdog(s);
2352 vdi_index = pos / SD_DATA_OBJ_SIZE;
2353 offset = pos % SD_DATA_OBJ_SIZE;
2355 data_len = MIN(remaining, SD_DATA_OBJ_SIZE - offset);
2357 vmstate_oid = vid_to_vmstate_oid(vdi_id, vdi_index);
2359 create = (offset == 0);
2361 ret = read_object(fd, (char *)data, vmstate_oid,
2362 s->inode.nr_copies, data_len, offset,
2365 ret = write_object(fd, (char *)data, vmstate_oid,
2366 s->inode.nr_copies, data_len, offset, create,
2371 error_report("failed to save vmstate %s", strerror(errno));
2377 remaining -= data_len;
2385 static int sd_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2388 BDRVSheepdogState *s = bs->opaque;
2392 buf = qemu_blockalign(bs, qiov->size);
2393 qemu_iovec_to_buf(qiov, 0, buf, qiov->size);
2394 ret = do_load_save_vmstate(s, (uint8_t *) buf, pos, qiov->size, 0);
2400 static int sd_load_vmstate(BlockDriverState *bs, uint8_t *data,
2401 int64_t pos, int size)
2403 BDRVSheepdogState *s = bs->opaque;
2405 return do_load_save_vmstate(s, data, pos, size, 1);
2409 static coroutine_fn int sd_co_discard(BlockDriverState *bs, int64_t sector_num,
2414 BDRVSheepdogState *s = bs->opaque;
2417 if (!s->discard_supported) {
2421 acb = sd_aio_setup(bs, &dummy, sector_num, nb_sectors);
2422 acb->aiocb_type = AIOCB_DISCARD_OBJ;
2423 acb->aio_done_func = sd_finish_aiocb;
2425 ret = sd_co_rw_vector(acb);
2427 qemu_aio_release(acb);
2431 qemu_coroutine_yield();
2436 static coroutine_fn int64_t
2437 sd_co_get_block_status(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
2440 BDRVSheepdogState *s = bs->opaque;
2441 SheepdogInode *inode = &s->inode;
2442 unsigned long start = sector_num * BDRV_SECTOR_SIZE / SD_DATA_OBJ_SIZE,
2443 end = DIV_ROUND_UP((sector_num + nb_sectors) *
2444 BDRV_SECTOR_SIZE, SD_DATA_OBJ_SIZE);
2446 int64_t ret = BDRV_BLOCK_DATA;
2448 for (idx = start; idx < end; idx++) {
2449 if (inode->data_vdi_id[idx] == 0) {
2454 /* Get the longest length of unallocated sectors */
2456 for (idx = start + 1; idx < end; idx++) {
2457 if (inode->data_vdi_id[idx] != 0) {
2463 *pnum = (idx - start) * SD_DATA_OBJ_SIZE / BDRV_SECTOR_SIZE;
2464 if (*pnum > nb_sectors) {
2470 static int64_t sd_get_allocated_file_size(BlockDriverState *bs)
2472 BDRVSheepdogState *s = bs->opaque;
2473 SheepdogInode *inode = &s->inode;
2474 unsigned long i, last = DIV_ROUND_UP(inode->vdi_size, SD_DATA_OBJ_SIZE);
2477 for (i = 0; i < last; i++) {
2478 if (inode->data_vdi_id[i] == 0) {
2481 size += SD_DATA_OBJ_SIZE;
2486 static QEMUOptionParameter sd_create_options[] = {
2488 .name = BLOCK_OPT_SIZE,
2490 .help = "Virtual disk size"
2493 .name = BLOCK_OPT_BACKING_FILE,
2495 .help = "File name of a base image"
2498 .name = BLOCK_OPT_PREALLOC,
2500 .help = "Preallocation mode (allowed values: off, full)"
2503 .name = BLOCK_OPT_REDUNDANCY,
2505 .help = "Redundancy of the image"
2510 static BlockDriver bdrv_sheepdog = {
2511 .format_name = "sheepdog",
2512 .protocol_name = "sheepdog",
2513 .instance_size = sizeof(BDRVSheepdogState),
2514 .bdrv_needs_filename = true,
2515 .bdrv_file_open = sd_open,
2516 .bdrv_close = sd_close,
2517 .bdrv_create = sd_create,
2518 .bdrv_has_zero_init = bdrv_has_zero_init_1,
2519 .bdrv_getlength = sd_getlength,
2520 .bdrv_get_allocated_file_size = sd_get_allocated_file_size,
2521 .bdrv_truncate = sd_truncate,
2523 .bdrv_co_readv = sd_co_readv,
2524 .bdrv_co_writev = sd_co_writev,
2525 .bdrv_co_flush_to_disk = sd_co_flush_to_disk,
2526 .bdrv_co_discard = sd_co_discard,
2527 .bdrv_co_get_block_status = sd_co_get_block_status,
2529 .bdrv_snapshot_create = sd_snapshot_create,
2530 .bdrv_snapshot_goto = sd_snapshot_goto,
2531 .bdrv_snapshot_delete = sd_snapshot_delete,
2532 .bdrv_snapshot_list = sd_snapshot_list,
2534 .bdrv_save_vmstate = sd_save_vmstate,
2535 .bdrv_load_vmstate = sd_load_vmstate,
2537 .create_options = sd_create_options,
2540 static BlockDriver bdrv_sheepdog_tcp = {
2541 .format_name = "sheepdog",
2542 .protocol_name = "sheepdog+tcp",
2543 .instance_size = sizeof(BDRVSheepdogState),
2544 .bdrv_needs_filename = true,
2545 .bdrv_file_open = sd_open,
2546 .bdrv_close = sd_close,
2547 .bdrv_create = sd_create,
2548 .bdrv_has_zero_init = bdrv_has_zero_init_1,
2549 .bdrv_getlength = sd_getlength,
2550 .bdrv_get_allocated_file_size = sd_get_allocated_file_size,
2551 .bdrv_truncate = sd_truncate,
2553 .bdrv_co_readv = sd_co_readv,
2554 .bdrv_co_writev = sd_co_writev,
2555 .bdrv_co_flush_to_disk = sd_co_flush_to_disk,
2556 .bdrv_co_discard = sd_co_discard,
2557 .bdrv_co_get_block_status = sd_co_get_block_status,
2559 .bdrv_snapshot_create = sd_snapshot_create,
2560 .bdrv_snapshot_goto = sd_snapshot_goto,
2561 .bdrv_snapshot_delete = sd_snapshot_delete,
2562 .bdrv_snapshot_list = sd_snapshot_list,
2564 .bdrv_save_vmstate = sd_save_vmstate,
2565 .bdrv_load_vmstate = sd_load_vmstate,
2567 .create_options = sd_create_options,
2570 static BlockDriver bdrv_sheepdog_unix = {
2571 .format_name = "sheepdog",
2572 .protocol_name = "sheepdog+unix",
2573 .instance_size = sizeof(BDRVSheepdogState),
2574 .bdrv_needs_filename = true,
2575 .bdrv_file_open = sd_open,
2576 .bdrv_close = sd_close,
2577 .bdrv_create = sd_create,
2578 .bdrv_has_zero_init = bdrv_has_zero_init_1,
2579 .bdrv_getlength = sd_getlength,
2580 .bdrv_get_allocated_file_size = sd_get_allocated_file_size,
2581 .bdrv_truncate = sd_truncate,
2583 .bdrv_co_readv = sd_co_readv,
2584 .bdrv_co_writev = sd_co_writev,
2585 .bdrv_co_flush_to_disk = sd_co_flush_to_disk,
2586 .bdrv_co_discard = sd_co_discard,
2587 .bdrv_co_get_block_status = sd_co_get_block_status,
2589 .bdrv_snapshot_create = sd_snapshot_create,
2590 .bdrv_snapshot_goto = sd_snapshot_goto,
2591 .bdrv_snapshot_delete = sd_snapshot_delete,
2592 .bdrv_snapshot_list = sd_snapshot_list,
2594 .bdrv_save_vmstate = sd_save_vmstate,
2595 .bdrv_load_vmstate = sd_load_vmstate,
2597 .create_options = sd_create_options,
2600 static void bdrv_sheepdog_init(void)
2602 bdrv_register(&bdrv_sheepdog);
2603 bdrv_register(&bdrv_sheepdog_tcp);
2604 bdrv_register(&bdrv_sheepdog_unix);
2606 block_init(bdrv_sheepdog_init);