block/sheepdog: Propagate errors through find_vdi_name()
[qemu/kevin.git] / block / sheepdog.c
blobb72c31828eefdd23103742141466301a54e16aeb
1 /*
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"
16 #include "qemu/uri.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 */
75 * Object ID rules
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 {
107 uint8_t proto_ver;
108 uint8_t opcode;
109 uint16_t flags;
110 uint32_t epoch;
111 uint32_t id;
112 uint32_t data_length;
113 uint32_t opcode_specific[8];
114 } SheepdogReq;
116 typedef struct SheepdogRsp {
117 uint8_t proto_ver;
118 uint8_t opcode;
119 uint16_t flags;
120 uint32_t epoch;
121 uint32_t id;
122 uint32_t data_length;
123 uint32_t result;
124 uint32_t opcode_specific[7];
125 } SheepdogRsp;
127 typedef struct SheepdogObjReq {
128 uint8_t proto_ver;
129 uint8_t opcode;
130 uint16_t flags;
131 uint32_t epoch;
132 uint32_t id;
133 uint32_t data_length;
134 uint64_t oid;
135 uint64_t cow_oid;
136 uint8_t copies;
137 uint8_t copy_policy;
138 uint8_t reserved[6];
139 uint64_t offset;
140 } SheepdogObjReq;
142 typedef struct SheepdogObjRsp {
143 uint8_t proto_ver;
144 uint8_t opcode;
145 uint16_t flags;
146 uint32_t epoch;
147 uint32_t id;
148 uint32_t data_length;
149 uint32_t result;
150 uint8_t copies;
151 uint8_t copy_policy;
152 uint8_t reserved[2];
153 uint32_t pad[6];
154 } SheepdogObjRsp;
156 typedef struct SheepdogVdiReq {
157 uint8_t proto_ver;
158 uint8_t opcode;
159 uint16_t flags;
160 uint32_t epoch;
161 uint32_t id;
162 uint32_t data_length;
163 uint64_t vdi_size;
164 uint32_t base_vdi_id;
165 uint8_t copies;
166 uint8_t copy_policy;
167 uint8_t reserved[2];
168 uint32_t snapid;
169 uint32_t pad[3];
170 } SheepdogVdiReq;
172 typedef struct SheepdogVdiRsp {
173 uint8_t proto_ver;
174 uint8_t opcode;
175 uint16_t flags;
176 uint32_t epoch;
177 uint32_t id;
178 uint32_t data_length;
179 uint32_t result;
180 uint32_t rsvd;
181 uint32_t vdi_id;
182 uint32_t pad[5];
183 } SheepdogVdiRsp;
185 typedef struct SheepdogInode {
186 char name[SD_MAX_VDI_LEN];
187 char tag[SD_MAX_VDI_TAG_LEN];
188 uint64_t ctime;
189 uint64_t snap_ctime;
190 uint64_t vm_clock_nsec;
191 uint64_t vdi_size;
192 uint64_t vm_state_size;
193 uint16_t copy_policy;
194 uint8_t nr_copies;
195 uint8_t block_size_shift;
196 uint32_t snap_id;
197 uint32_t vdi_id;
198 uint32_t parent_vdi_id;
199 uint32_t child_vdi_id[MAX_CHILDREN];
200 uint32_t data_vdi_id[MAX_DATA_OBJS];
201 } SheepdogInode;
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;
215 while (bp < be) {
216 hval ^= (uint64_t) *bp++;
217 hval += (hval << 1) + (hval << 4) + (hval << 5) +
218 (hval << 7) + (hval << 8) + (hval << 40);
220 return hval;
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;
263 #undef DPRINTF
264 #ifdef DEBUG_SDOG
265 #define DPRINTF(fmt, args...) \
266 do { \
267 fprintf(stdout, "%s %d: " fmt, __func__, __LINE__, ##args); \
268 } while (0)
269 #else
270 #define DPRINTF(fmt, args...)
271 #endif
273 typedef struct SheepdogAIOCB SheepdogAIOCB;
275 typedef struct AIOReq {
276 SheepdogAIOCB *aiocb;
277 unsigned int iov_offset;
279 uint64_t oid;
280 uint64_t base_oid;
281 uint64_t offset;
282 unsigned int data_len;
283 uint8_t flags;
284 uint32_t id;
286 QLIST_ENTRY(AIOReq) aio_siblings;
287 } AIOReq;
289 enum AIOCBState {
290 AIOCB_WRITE_UDATA,
291 AIOCB_READ_UDATA,
292 AIOCB_FLUSH_CACHE,
293 AIOCB_DISCARD_OBJ,
296 struct SheepdogAIOCB {
297 BlockDriverAIOCB common;
299 QEMUIOVector *qiov;
301 int64_t sector_num;
302 int nb_sectors;
304 int ret;
305 enum AIOCBState aiocb_type;
307 Coroutine *coroutine;
308 void (*aio_done_func)(SheepdogAIOCB *);
310 bool cancelable;
311 bool *finished;
312 int nr_pending;
315 typedef struct BDRVSheepdogState {
316 BlockDriverState *bs;
318 SheepdogInode inode;
320 uint32_t min_dirty_data_idx;
321 uint32_t max_dirty_data_idx;
323 char name[SD_MAX_VDI_LEN];
324 bool is_snapshot;
325 uint32_t cache_flags;
326 bool discard_supported;
328 char *host_spec;
329 bool is_unix;
330 int fd;
332 CoMutex lock;
333 Coroutine *co_send;
334 Coroutine *co_recv;
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;
342 } BDRVSheepdogState;
344 static const char * sd_strerror(int err)
346 int i;
348 static const struct {
349 int err;
350 const char *desc;
351 } errors[] = {
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)
410 AIOReq *aio_req;
412 aio_req = g_malloc(sizeof(*aio_req));
413 aio_req->aiocb = acb;
414 aio_req->iov_offset = iov_offset;
415 aio_req->oid = oid;
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++;
422 acb->nr_pending++;
423 return aio_req;
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);
432 g_free(aio_req);
434 acb->nr_pending--;
437 static void coroutine_fn sd_finish_aiocb(SheepdogAIOCB *acb)
439 qemu_coroutine_enter(acb->coroutine, NULL);
440 if (acb->finished) {
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;
456 AIOReq *aioreq;
458 if (!acb->cancelable) {
459 return false;
462 QLIST_FOREACH(aioreq, &s->inflight_aio_head, aio_siblings) {
463 if (aioreq->aiocb == acb) {
464 return false;
468 return true;
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;
479 while (!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,
483 next) {
484 if (aioreq->aiocb == acb) {
485 free_aio_req(s, aioreq);
488 QLIST_FOREACH_SAFE(aioreq, &s->failed_aio_head, aio_siblings,
489 next) {
490 if (aioreq->aiocb == acb) {
491 free_aio_req(s, aioreq);
495 assert(acb->nr_pending == 0);
496 sd_finish_aiocb(acb);
497 return;
499 qemu_aio_wait();
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)
511 SheepdogAIOCB *acb;
513 acb = qemu_aio_get(&sd_aiocb_info, bs, NULL, NULL);
515 acb->qiov = qiov;
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();
524 acb->ret = 0;
525 acb->nr_pending = 0;
526 return acb;
529 static int connect_to_sdog(BDRVSheepdogState *s, Error **errp)
531 int fd;
533 if (s->is_unix) {
534 fd = unix_connect(s->host_spec, errp);
535 } else {
536 fd = inet_connect(s->host_spec, errp);
538 if (fd >= 0) {
539 int ret = socket_set_nodelay(fd);
540 if (ret < 0) {
541 error_report("%s", strerror(errno));
546 if (fd >= 0) {
547 qemu_set_nonblock(fd);
550 return fd;
553 static coroutine_fn int send_co_req(int sockfd, SheepdogReq *hdr, void *data,
554 unsigned int *wlen)
556 int ret;
558 ret = qemu_co_send(sockfd, hdr, sizeof(*hdr));
559 if (ret != sizeof(*hdr)) {
560 error_report("failed to send a req, %s", strerror(errno));
561 return ret;
564 ret = qemu_co_send(sockfd, data, *wlen);
565 if (ret != *wlen) {
566 error_report("failed to send a req, %s", strerror(errno));
569 return ret;
572 static void restart_co_req(void *opaque)
574 Coroutine *co = opaque;
576 qemu_coroutine_enter(co, NULL);
579 typedef struct SheepdogReqCo {
580 int sockfd;
581 SheepdogReq *hdr;
582 void *data;
583 unsigned int *wlen;
584 unsigned int *rlen;
585 int ret;
586 bool finished;
587 } SheepdogReqCo;
589 static coroutine_fn void do_co_req(void *opaque)
591 int ret;
592 Coroutine *co;
593 SheepdogReqCo *srco = opaque;
594 int sockfd = srco->sockfd;
595 SheepdogReq *hdr = srco->hdr;
596 void *data = srco->data;
597 unsigned int *wlen = srco->wlen;
598 unsigned int *rlen = srco->rlen;
600 co = qemu_coroutine_self();
601 qemu_aio_set_fd_handler(sockfd, NULL, restart_co_req, co);
603 ret = send_co_req(sockfd, hdr, data, wlen);
604 if (ret < 0) {
605 goto out;
608 qemu_aio_set_fd_handler(sockfd, restart_co_req, NULL, co);
610 ret = qemu_co_recv(sockfd, hdr, sizeof(*hdr));
611 if (ret != sizeof(*hdr)) {
612 error_report("failed to get a rsp, %s", strerror(errno));
613 ret = -errno;
614 goto out;
617 if (*rlen > hdr->data_length) {
618 *rlen = hdr->data_length;
621 if (*rlen) {
622 ret = qemu_co_recv(sockfd, data, *rlen);
623 if (ret != *rlen) {
624 error_report("failed to get the data, %s", strerror(errno));
625 ret = -errno;
626 goto out;
629 ret = 0;
630 out:
631 /* there is at most one request for this sockfd, so it is safe to
632 * set each handler to NULL. */
633 qemu_aio_set_fd_handler(sockfd, NULL, NULL, NULL);
635 srco->ret = ret;
636 srco->finished = true;
639 static int do_req(int sockfd, SheepdogReq *hdr, void *data,
640 unsigned int *wlen, unsigned int *rlen)
642 Coroutine *co;
643 SheepdogReqCo srco = {
644 .sockfd = sockfd,
645 .hdr = hdr,
646 .data = data,
647 .wlen = wlen,
648 .rlen = rlen,
649 .ret = 0,
650 .finished = false,
653 if (qemu_in_coroutine()) {
654 do_co_req(&srco);
655 } else {
656 co = qemu_coroutine_create(do_co_req);
657 qemu_coroutine_enter(co, &srco);
658 while (!srco.finished) {
659 qemu_aio_wait();
663 return srco.ret;
666 static void coroutine_fn add_aio_request(BDRVSheepdogState *s, AIOReq *aio_req,
667 struct iovec *iov, int niov, bool create,
668 enum AIOCBState aiocb_type);
669 static void coroutine_fn resend_aioreq(BDRVSheepdogState *s, AIOReq *aio_req);
670 static int reload_inode(BDRVSheepdogState *s, uint32_t snapid, const char *tag);
671 static int get_sheep_fd(BDRVSheepdogState *s, Error **errp);
672 static void co_write_request(void *opaque);
674 static AIOReq *find_pending_req(BDRVSheepdogState *s, uint64_t oid)
676 AIOReq *aio_req;
678 QLIST_FOREACH(aio_req, &s->pending_aio_head, aio_siblings) {
679 if (aio_req->oid == oid) {
680 return aio_req;
684 return NULL;
688 * This function searchs pending requests to the object `oid', and
689 * sends them.
691 static void coroutine_fn send_pending_req(BDRVSheepdogState *s, uint64_t oid)
693 AIOReq *aio_req;
694 SheepdogAIOCB *acb;
696 while ((aio_req = find_pending_req(s, oid)) != NULL) {
697 acb = aio_req->aiocb;
698 /* move aio_req from pending list to inflight one */
699 QLIST_REMOVE(aio_req, aio_siblings);
700 QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
701 add_aio_request(s, aio_req, acb->qiov->iov, acb->qiov->niov, false,
702 acb->aiocb_type);
706 static coroutine_fn void reconnect_to_sdog(void *opaque)
708 Error *local_err = NULL;
709 BDRVSheepdogState *s = opaque;
710 AIOReq *aio_req, *next;
712 qemu_aio_set_fd_handler(s->fd, NULL, NULL, NULL);
713 close(s->fd);
714 s->fd = -1;
716 /* Wait for outstanding write requests to be completed. */
717 while (s->co_send != NULL) {
718 co_write_request(opaque);
721 /* Try to reconnect the sheepdog server every one second. */
722 while (s->fd < 0) {
723 s->fd = get_sheep_fd(s, &local_err);
724 if (s->fd < 0) {
725 DPRINTF("Wait for connection to be established\n");
726 qerror_report_err(local_err);
727 error_free(local_err);
728 co_aio_sleep_ns(bdrv_get_aio_context(s->bs), QEMU_CLOCK_REALTIME,
729 1000000000ULL);
734 * Now we have to resend all the request in the inflight queue. However,
735 * resend_aioreq() can yield and newly created requests can be added to the
736 * inflight queue before the coroutine is resumed. To avoid mixing them, we
737 * have to move all the inflight requests to the failed queue before
738 * resend_aioreq() is called.
740 QLIST_FOREACH_SAFE(aio_req, &s->inflight_aio_head, aio_siblings, next) {
741 QLIST_REMOVE(aio_req, aio_siblings);
742 QLIST_INSERT_HEAD(&s->failed_aio_head, aio_req, aio_siblings);
745 /* Resend all the failed aio requests. */
746 while (!QLIST_EMPTY(&s->failed_aio_head)) {
747 aio_req = QLIST_FIRST(&s->failed_aio_head);
748 QLIST_REMOVE(aio_req, aio_siblings);
749 QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
750 resend_aioreq(s, aio_req);
755 * Receive responses of the I/O requests.
757 * This function is registered as a fd handler, and called from the
758 * main loop when s->fd is ready for reading responses.
760 static void coroutine_fn aio_read_response(void *opaque)
762 SheepdogObjRsp rsp;
763 BDRVSheepdogState *s = opaque;
764 int fd = s->fd;
765 int ret;
766 AIOReq *aio_req = NULL;
767 SheepdogAIOCB *acb;
768 uint64_t idx;
770 /* read a header */
771 ret = qemu_co_recv(fd, &rsp, sizeof(rsp));
772 if (ret != sizeof(rsp)) {
773 error_report("failed to get the header, %s", strerror(errno));
774 goto err;
777 /* find the right aio_req from the inflight aio list */
778 QLIST_FOREACH(aio_req, &s->inflight_aio_head, aio_siblings) {
779 if (aio_req->id == rsp.id) {
780 break;
783 if (!aio_req) {
784 error_report("cannot find aio_req %x", rsp.id);
785 goto err;
788 acb = aio_req->aiocb;
790 switch (acb->aiocb_type) {
791 case AIOCB_WRITE_UDATA:
792 /* this coroutine context is no longer suitable for co_recv
793 * because we may send data to update vdi objects */
794 s->co_recv = NULL;
795 if (!is_data_obj(aio_req->oid)) {
796 break;
798 idx = data_oid_to_idx(aio_req->oid);
800 if (s->inode.data_vdi_id[idx] != s->inode.vdi_id) {
802 * If the object is newly created one, we need to update
803 * the vdi object (metadata object). min_dirty_data_idx
804 * and max_dirty_data_idx are changed to include updated
805 * index between them.
807 if (rsp.result == SD_RES_SUCCESS) {
808 s->inode.data_vdi_id[idx] = s->inode.vdi_id;
809 s->max_dirty_data_idx = MAX(idx, s->max_dirty_data_idx);
810 s->min_dirty_data_idx = MIN(idx, s->min_dirty_data_idx);
813 * Some requests may be blocked because simultaneous
814 * create requests are not allowed, so we search the
815 * pending requests here.
817 send_pending_req(s, aio_req->oid);
819 break;
820 case AIOCB_READ_UDATA:
821 ret = qemu_co_recvv(fd, acb->qiov->iov, acb->qiov->niov,
822 aio_req->iov_offset, rsp.data_length);
823 if (ret != rsp.data_length) {
824 error_report("failed to get the data, %s", strerror(errno));
825 goto err;
827 break;
828 case AIOCB_FLUSH_CACHE:
829 if (rsp.result == SD_RES_INVALID_PARMS) {
830 DPRINTF("disable cache since the server doesn't support it\n");
831 s->cache_flags = SD_FLAG_CMD_DIRECT;
832 rsp.result = SD_RES_SUCCESS;
834 break;
835 case AIOCB_DISCARD_OBJ:
836 switch (rsp.result) {
837 case SD_RES_INVALID_PARMS:
838 error_report("sheep(%s) doesn't support discard command",
839 s->host_spec);
840 rsp.result = SD_RES_SUCCESS;
841 s->discard_supported = false;
842 break;
843 case SD_RES_SUCCESS:
844 idx = data_oid_to_idx(aio_req->oid);
845 s->inode.data_vdi_id[idx] = 0;
846 break;
847 default:
848 break;
852 switch (rsp.result) {
853 case SD_RES_SUCCESS:
854 break;
855 case SD_RES_READONLY:
856 if (s->inode.vdi_id == oid_to_vid(aio_req->oid)) {
857 ret = reload_inode(s, 0, "");
858 if (ret < 0) {
859 goto err;
862 if (is_data_obj(aio_req->oid)) {
863 aio_req->oid = vid_to_data_oid(s->inode.vdi_id,
864 data_oid_to_idx(aio_req->oid));
865 } else {
866 aio_req->oid = vid_to_vdi_oid(s->inode.vdi_id);
868 resend_aioreq(s, aio_req);
869 goto out;
870 default:
871 acb->ret = -EIO;
872 error_report("%s", sd_strerror(rsp.result));
873 break;
876 free_aio_req(s, aio_req);
877 if (!acb->nr_pending) {
879 * We've finished all requests which belong to the AIOCB, so
880 * we can switch back to sd_co_readv/writev now.
882 acb->aio_done_func(acb);
884 out:
885 s->co_recv = NULL;
886 return;
887 err:
888 s->co_recv = NULL;
889 reconnect_to_sdog(opaque);
892 static void co_read_response(void *opaque)
894 BDRVSheepdogState *s = opaque;
896 if (!s->co_recv) {
897 s->co_recv = qemu_coroutine_create(aio_read_response);
900 qemu_coroutine_enter(s->co_recv, opaque);
903 static void co_write_request(void *opaque)
905 BDRVSheepdogState *s = opaque;
907 qemu_coroutine_enter(s->co_send, NULL);
911 * Return a socket descriptor to read/write objects.
913 * We cannot use this descriptor for other operations because
914 * the block driver may be on waiting response from the server.
916 static int get_sheep_fd(BDRVSheepdogState *s, Error **errp)
918 int fd;
920 fd = connect_to_sdog(s, errp);
921 if (fd < 0) {
922 return fd;
925 qemu_aio_set_fd_handler(fd, co_read_response, NULL, s);
926 return fd;
929 static int sd_parse_uri(BDRVSheepdogState *s, const char *filename,
930 char *vdi, uint32_t *snapid, char *tag)
932 URI *uri;
933 QueryParams *qp = NULL;
934 int ret = 0;
936 uri = uri_parse(filename);
937 if (!uri) {
938 return -EINVAL;
941 /* transport */
942 if (!strcmp(uri->scheme, "sheepdog")) {
943 s->is_unix = false;
944 } else if (!strcmp(uri->scheme, "sheepdog+tcp")) {
945 s->is_unix = false;
946 } else if (!strcmp(uri->scheme, "sheepdog+unix")) {
947 s->is_unix = true;
948 } else {
949 ret = -EINVAL;
950 goto out;
953 if (uri->path == NULL || !strcmp(uri->path, "/")) {
954 ret = -EINVAL;
955 goto out;
957 pstrcpy(vdi, SD_MAX_VDI_LEN, uri->path + 1);
959 qp = query_params_parse(uri->query);
960 if (qp->n > 1 || (s->is_unix && !qp->n) || (!s->is_unix && qp->n)) {
961 ret = -EINVAL;
962 goto out;
965 if (s->is_unix) {
966 /* sheepdog+unix:///vdiname?socket=path */
967 if (uri->server || uri->port || strcmp(qp->p[0].name, "socket")) {
968 ret = -EINVAL;
969 goto out;
971 s->host_spec = g_strdup(qp->p[0].value);
972 } else {
973 /* sheepdog[+tcp]://[host:port]/vdiname */
974 s->host_spec = g_strdup_printf("%s:%d", uri->server ?: SD_DEFAULT_ADDR,
975 uri->port ?: SD_DEFAULT_PORT);
978 /* snapshot tag */
979 if (uri->fragment) {
980 *snapid = strtoul(uri->fragment, NULL, 10);
981 if (*snapid == 0) {
982 pstrcpy(tag, SD_MAX_VDI_TAG_LEN, uri->fragment);
984 } else {
985 *snapid = CURRENT_VDI_ID; /* search current vdi */
988 out:
989 if (qp) {
990 query_params_free(qp);
992 uri_free(uri);
993 return ret;
997 * Parse a filename (old syntax)
999 * filename must be one of the following formats:
1000 * 1. [vdiname]
1001 * 2. [vdiname]:[snapid]
1002 * 3. [vdiname]:[tag]
1003 * 4. [hostname]:[port]:[vdiname]
1004 * 5. [hostname]:[port]:[vdiname]:[snapid]
1005 * 6. [hostname]:[port]:[vdiname]:[tag]
1007 * You can boot from the snapshot images by specifying `snapid` or
1008 * `tag'.
1010 * You can run VMs outside the Sheepdog cluster by specifying
1011 * `hostname' and `port' (experimental).
1013 static int parse_vdiname(BDRVSheepdogState *s, const char *filename,
1014 char *vdi, uint32_t *snapid, char *tag)
1016 char *p, *q, *uri;
1017 const char *host_spec, *vdi_spec;
1018 int nr_sep, ret;
1020 strstart(filename, "sheepdog:", (const char **)&filename);
1021 p = q = g_strdup(filename);
1023 /* count the number of separators */
1024 nr_sep = 0;
1025 while (*p) {
1026 if (*p == ':') {
1027 nr_sep++;
1029 p++;
1031 p = q;
1033 /* use the first two tokens as host_spec. */
1034 if (nr_sep >= 2) {
1035 host_spec = p;
1036 p = strchr(p, ':');
1037 p++;
1038 p = strchr(p, ':');
1039 *p++ = '\0';
1040 } else {
1041 host_spec = "";
1044 vdi_spec = p;
1046 p = strchr(vdi_spec, ':');
1047 if (p) {
1048 *p++ = '#';
1051 uri = g_strdup_printf("sheepdog://%s/%s", host_spec, vdi_spec);
1053 ret = sd_parse_uri(s, uri, vdi, snapid, tag);
1055 g_free(q);
1056 g_free(uri);
1058 return ret;
1061 static int find_vdi_name(BDRVSheepdogState *s, const char *filename,
1062 uint32_t snapid, const char *tag, uint32_t *vid,
1063 bool lock, Error **errp)
1065 int ret, fd;
1066 SheepdogVdiReq hdr;
1067 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
1068 unsigned int wlen, rlen = 0;
1069 char buf[SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN];
1071 fd = connect_to_sdog(s, errp);
1072 if (fd < 0) {
1073 return fd;
1076 /* This pair of strncpy calls ensures that the buffer is zero-filled,
1077 * which is desirable since we'll soon be sending those bytes, and
1078 * don't want the send_req to read uninitialized data.
1080 strncpy(buf, filename, SD_MAX_VDI_LEN);
1081 strncpy(buf + SD_MAX_VDI_LEN, tag, SD_MAX_VDI_TAG_LEN);
1083 memset(&hdr, 0, sizeof(hdr));
1084 if (lock) {
1085 hdr.opcode = SD_OP_LOCK_VDI;
1086 } else {
1087 hdr.opcode = SD_OP_GET_VDI_INFO;
1089 wlen = SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN;
1090 hdr.proto_ver = SD_PROTO_VER;
1091 hdr.data_length = wlen;
1092 hdr.snapid = snapid;
1093 hdr.flags = SD_FLAG_CMD_WRITE;
1095 ret = do_req(fd, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
1096 if (ret) {
1097 error_setg_errno(errp, -ret, "cannot get vdi info");
1098 goto out;
1101 if (rsp->result != SD_RES_SUCCESS) {
1102 error_setg(errp, "cannot get vdi info, %s, %s %" PRIu32 " %s",
1103 sd_strerror(rsp->result), filename, snapid, tag);
1104 if (rsp->result == SD_RES_NO_VDI) {
1105 ret = -ENOENT;
1106 } else {
1107 ret = -EIO;
1109 goto out;
1111 *vid = rsp->vdi_id;
1113 ret = 0;
1114 out:
1115 closesocket(fd);
1116 return ret;
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;
1124 SheepdogObjReq hdr;
1125 unsigned int wlen = 0;
1126 int ret;
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;
1133 if (!nr_copies) {
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;
1142 break;
1143 case AIOCB_READ_UDATA:
1144 hdr.opcode = SD_OP_READ_OBJ;
1145 hdr.flags = flags;
1146 break;
1147 case AIOCB_WRITE_UDATA:
1148 if (create) {
1149 hdr.opcode = SD_OP_CREATE_AND_WRITE_OBJ;
1150 } else {
1151 hdr.opcode = SD_OP_WRITE_OBJ;
1153 wlen = datalen;
1154 hdr.flags = SD_FLAG_CMD_WRITE | flags;
1155 break;
1156 case AIOCB_DISCARD_OBJ:
1157 hdr.opcode = SD_OP_DISCARD_OBJ;
1158 break;
1161 if (s->cache_flags) {
1162 hdr.flags |= s->cache_flags;
1165 hdr.oid = oid;
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);
1179 /* send a header */
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));
1183 goto out;
1186 if (wlen) {
1187 ret = qemu_co_sendv(s->fd, iov, niov, aio_req->iov_offset, wlen);
1188 if (ret != wlen) {
1189 error_report("failed to send a data, %s", strerror(errno));
1192 out:
1193 socket_set_cork(s->fd, 0);
1194 qemu_aio_set_fd_handler(s->fd, co_read_response, NULL, s);
1195 s->co_send = NULL;
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)
1203 SheepdogObjReq hdr;
1204 SheepdogObjRsp *rsp = (SheepdogObjRsp *)&hdr;
1205 unsigned int wlen, rlen;
1206 int ret;
1208 memset(&hdr, 0, sizeof(hdr));
1210 if (write) {
1211 wlen = datalen;
1212 rlen = 0;
1213 hdr.flags = SD_FLAG_CMD_WRITE;
1214 if (create) {
1215 hdr.opcode = SD_OP_CREATE_AND_WRITE_OBJ;
1216 } else {
1217 hdr.opcode = SD_OP_WRITE_OBJ;
1219 } else {
1220 wlen = 0;
1221 rlen = datalen;
1222 hdr.opcode = SD_OP_READ_OBJ;
1225 hdr.flags |= cache_flags;
1227 hdr.oid = oid;
1228 hdr.data_length = datalen;
1229 hdr.offset = offset;
1230 hdr.copies = copies;
1232 ret = do_req(fd, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
1233 if (ret) {
1234 error_report("failed to send a request to the sheep");
1235 return ret;
1238 switch (rsp->result) {
1239 case SD_RES_SUCCESS:
1240 return 0;
1241 default:
1242 error_report("%s", sd_strerror(rsp->result));
1243 return -EIO;
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 Error *local_err = NULL;
1267 SheepdogInode *inode;
1268 int ret = 0, fd;
1269 uint32_t vid = 0;
1271 fd = connect_to_sdog(s, &local_err);
1272 if (fd < 0) {
1273 qerror_report_err(local_err);
1274 error_free(local_err);
1275 return -EIO;
1278 inode = g_malloc(sizeof(s->inode));
1280 ret = find_vdi_name(s, s->name, snapid, tag, &vid, false, &local_err);
1281 if (ret) {
1282 qerror_report_err(local_err);
1283 error_free(local_err);
1284 goto out;
1287 ret = read_object(fd, (char *)inode, vid_to_vdi_oid(vid),
1288 s->inode.nr_copies, sizeof(*inode), 0, s->cache_flags);
1289 if (ret < 0) {
1290 goto out;
1293 if (inode->vdi_id != s->inode.vdi_id) {
1294 memcpy(&s->inode, inode, sizeof(s->inode));
1297 out:
1298 g_free(inode);
1299 closesocket(fd);
1301 return ret;
1304 /* Return true if the specified request is linked to the pending list. */
1305 static bool check_simultaneous_create(BDRVSheepdogState *s, AIOReq *aio_req)
1307 AIOReq *areq;
1308 QLIST_FOREACH(areq, &s->inflight_aio_head, aio_siblings) {
1309 if (areq != aio_req && areq->oid == aio_req->oid) {
1311 * Sheepdog cannot handle simultaneous create requests to the same
1312 * object, so we cannot send the request until the previous request
1313 * finishes.
1315 DPRINTF("simultaneous create to %" PRIx64 "\n", aio_req->oid);
1316 aio_req->flags = 0;
1317 aio_req->base_oid = 0;
1318 QLIST_REMOVE(aio_req, aio_siblings);
1319 QLIST_INSERT_HEAD(&s->pending_aio_head, aio_req, aio_siblings);
1320 return true;
1324 return false;
1327 static void coroutine_fn resend_aioreq(BDRVSheepdogState *s, AIOReq *aio_req)
1329 SheepdogAIOCB *acb = aio_req->aiocb;
1330 bool create = false;
1332 /* check whether this request becomes a CoW one */
1333 if (acb->aiocb_type == AIOCB_WRITE_UDATA && is_data_obj(aio_req->oid)) {
1334 int idx = data_oid_to_idx(aio_req->oid);
1336 if (is_data_obj_writable(&s->inode, idx)) {
1337 goto out;
1340 if (check_simultaneous_create(s, aio_req)) {
1341 return;
1344 if (s->inode.data_vdi_id[idx]) {
1345 aio_req->base_oid = vid_to_data_oid(s->inode.data_vdi_id[idx], idx);
1346 aio_req->flags |= SD_FLAG_CMD_COW;
1348 create = true;
1350 out:
1351 if (is_data_obj(aio_req->oid)) {
1352 add_aio_request(s, aio_req, acb->qiov->iov, acb->qiov->niov, create,
1353 acb->aiocb_type);
1354 } else {
1355 struct iovec iov;
1356 iov.iov_base = &s->inode;
1357 iov.iov_len = sizeof(s->inode);
1358 add_aio_request(s, aio_req, &iov, 1, false, AIOCB_WRITE_UDATA);
1362 /* TODO Convert to fine grained options */
1363 static QemuOptsList runtime_opts = {
1364 .name = "sheepdog",
1365 .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
1366 .desc = {
1368 .name = "filename",
1369 .type = QEMU_OPT_STRING,
1370 .help = "URL to the sheepdog image",
1372 { /* end of list */ }
1376 static int sd_open(BlockDriverState *bs, QDict *options, int flags,
1377 Error **errp)
1379 int ret, fd;
1380 uint32_t vid = 0;
1381 BDRVSheepdogState *s = bs->opaque;
1382 char vdi[SD_MAX_VDI_LEN], tag[SD_MAX_VDI_TAG_LEN];
1383 uint32_t snapid;
1384 char *buf = NULL;
1385 QemuOpts *opts;
1386 Error *local_err = NULL;
1387 const char *filename;
1389 s->bs = bs;
1391 opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
1392 qemu_opts_absorb_qdict(opts, options, &local_err);
1393 if (local_err) {
1394 qerror_report_err(local_err);
1395 error_free(local_err);
1396 ret = -EINVAL;
1397 goto out;
1400 filename = qemu_opt_get(opts, "filename");
1402 QLIST_INIT(&s->inflight_aio_head);
1403 QLIST_INIT(&s->pending_aio_head);
1404 QLIST_INIT(&s->failed_aio_head);
1405 s->fd = -1;
1407 memset(vdi, 0, sizeof(vdi));
1408 memset(tag, 0, sizeof(tag));
1410 if (strstr(filename, "://")) {
1411 ret = sd_parse_uri(s, filename, vdi, &snapid, tag);
1412 } else {
1413 ret = parse_vdiname(s, filename, vdi, &snapid, tag);
1415 if (ret < 0) {
1416 goto out;
1418 s->fd = get_sheep_fd(s, &local_err);
1419 if (s->fd < 0) {
1420 qerror_report_err(local_err);
1421 error_free(local_err);
1422 ret = s->fd;
1423 goto out;
1426 ret = find_vdi_name(s, vdi, snapid, tag, &vid, true, &local_err);
1427 if (ret) {
1428 qerror_report_err(local_err);
1429 error_free(local_err);
1430 goto out;
1434 * QEMU block layer emulates writethrough cache as 'writeback + flush', so
1435 * we always set SD_FLAG_CMD_CACHE (writeback cache) as default.
1437 s->cache_flags = SD_FLAG_CMD_CACHE;
1438 if (flags & BDRV_O_NOCACHE) {
1439 s->cache_flags = SD_FLAG_CMD_DIRECT;
1441 s->discard_supported = true;
1443 if (snapid || tag[0] != '\0') {
1444 DPRINTF("%" PRIx32 " snapshot inode was open.\n", vid);
1445 s->is_snapshot = true;
1448 fd = connect_to_sdog(s, &local_err);
1449 if (fd < 0) {
1450 qerror_report_err(local_err);
1451 error_free(local_err);
1452 ret = fd;
1453 goto out;
1456 buf = g_malloc(SD_INODE_SIZE);
1457 ret = read_object(fd, buf, vid_to_vdi_oid(vid), 0, SD_INODE_SIZE, 0,
1458 s->cache_flags);
1460 closesocket(fd);
1462 if (ret) {
1463 goto out;
1466 memcpy(&s->inode, buf, sizeof(s->inode));
1467 s->min_dirty_data_idx = UINT32_MAX;
1468 s->max_dirty_data_idx = 0;
1470 bs->total_sectors = s->inode.vdi_size / BDRV_SECTOR_SIZE;
1471 pstrcpy(s->name, sizeof(s->name), vdi);
1472 qemu_co_mutex_init(&s->lock);
1473 qemu_opts_del(opts);
1474 g_free(buf);
1475 return 0;
1476 out:
1477 qemu_aio_set_fd_handler(s->fd, NULL, NULL, NULL);
1478 if (s->fd >= 0) {
1479 closesocket(s->fd);
1481 qemu_opts_del(opts);
1482 g_free(buf);
1483 return ret;
1486 static int do_sd_create(BDRVSheepdogState *s, uint32_t *vdi_id, int snapshot,
1487 Error **errp)
1489 SheepdogVdiReq hdr;
1490 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
1491 int fd, ret;
1492 unsigned int wlen, rlen = 0;
1493 char buf[SD_MAX_VDI_LEN];
1495 fd = connect_to_sdog(s, errp);
1496 if (fd < 0) {
1497 return fd;
1500 /* FIXME: would it be better to fail (e.g., return -EIO) when filename
1501 * does not fit in buf? For now, just truncate and avoid buffer overrun.
1503 memset(buf, 0, sizeof(buf));
1504 pstrcpy(buf, sizeof(buf), s->name);
1506 memset(&hdr, 0, sizeof(hdr));
1507 hdr.opcode = SD_OP_NEW_VDI;
1508 hdr.base_vdi_id = s->inode.vdi_id;
1510 wlen = SD_MAX_VDI_LEN;
1512 hdr.flags = SD_FLAG_CMD_WRITE;
1513 hdr.snapid = snapshot;
1515 hdr.data_length = wlen;
1516 hdr.vdi_size = s->inode.vdi_size;
1517 hdr.copy_policy = s->inode.copy_policy;
1518 hdr.copies = s->inode.nr_copies;
1520 ret = do_req(fd, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
1522 closesocket(fd);
1524 if (ret) {
1525 error_setg_errno(errp, -ret, "create failed");
1526 return ret;
1529 if (rsp->result != SD_RES_SUCCESS) {
1530 error_setg(errp, "%s, %s", sd_strerror(rsp->result), s->inode.name);
1531 return -EIO;
1534 if (vdi_id) {
1535 *vdi_id = rsp->vdi_id;
1538 return 0;
1541 static int sd_prealloc(const char *filename, Error **errp)
1543 BlockDriverState *bs = NULL;
1544 uint32_t idx, max_idx;
1545 int64_t vdi_size;
1546 void *buf = g_malloc0(SD_DATA_OBJ_SIZE);
1547 int ret;
1549 ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,
1550 NULL, errp);
1551 if (ret < 0) {
1552 goto out_with_err_set;
1555 vdi_size = bdrv_getlength(bs);
1556 if (vdi_size < 0) {
1557 ret = vdi_size;
1558 goto out;
1560 max_idx = DIV_ROUND_UP(vdi_size, SD_DATA_OBJ_SIZE);
1562 for (idx = 0; idx < max_idx; idx++) {
1564 * The created image can be a cloned image, so we need to read
1565 * a data from the source image.
1567 ret = bdrv_pread(bs, idx * SD_DATA_OBJ_SIZE, buf, SD_DATA_OBJ_SIZE);
1568 if (ret < 0) {
1569 goto out;
1571 ret = bdrv_pwrite(bs, idx * SD_DATA_OBJ_SIZE, buf, SD_DATA_OBJ_SIZE);
1572 if (ret < 0) {
1573 goto out;
1577 out:
1578 if (ret < 0) {
1579 error_setg_errno(errp, -ret, "Can't pre-allocate");
1581 out_with_err_set:
1582 if (bs) {
1583 bdrv_unref(bs);
1585 g_free(buf);
1587 return ret;
1591 * Sheepdog support two kinds of redundancy, full replication and erasure
1592 * coding.
1594 * # create a fully replicated vdi with x copies
1595 * -o redundancy=x (1 <= x <= SD_MAX_COPIES)
1597 * # create a erasure coded vdi with x data strips and y parity strips
1598 * -o redundancy=x:y (x must be one of {2,4,8,16} and 1 <= y < SD_EC_MAX_STRIP)
1600 static int parse_redundancy(BDRVSheepdogState *s, const char *opt)
1602 struct SheepdogInode *inode = &s->inode;
1603 const char *n1, *n2;
1604 long copy, parity;
1605 char p[10];
1607 pstrcpy(p, sizeof(p), opt);
1608 n1 = strtok(p, ":");
1609 n2 = strtok(NULL, ":");
1611 if (!n1) {
1612 return -EINVAL;
1615 copy = strtol(n1, NULL, 10);
1616 if (copy > SD_MAX_COPIES || copy < 1) {
1617 return -EINVAL;
1619 if (!n2) {
1620 inode->copy_policy = 0;
1621 inode->nr_copies = copy;
1622 return 0;
1625 if (copy != 2 && copy != 4 && copy != 8 && copy != 16) {
1626 return -EINVAL;
1629 parity = strtol(n2, NULL, 10);
1630 if (parity >= SD_EC_MAX_STRIP || parity < 1) {
1631 return -EINVAL;
1635 * 4 bits for parity and 4 bits for data.
1636 * We have to compress upper data bits because it can't represent 16
1638 inode->copy_policy = ((copy / 2) << 4) + parity;
1639 inode->nr_copies = copy + parity;
1641 return 0;
1644 static int sd_create(const char *filename, QEMUOptionParameter *options,
1645 Error **errp)
1647 int ret = 0;
1648 uint32_t vid = 0;
1649 char *backing_file = NULL;
1650 BDRVSheepdogState *s;
1651 char tag[SD_MAX_VDI_TAG_LEN];
1652 uint32_t snapid;
1653 bool prealloc = false;
1654 Error *local_err = NULL;
1656 s = g_malloc0(sizeof(BDRVSheepdogState));
1658 memset(tag, 0, sizeof(tag));
1659 if (strstr(filename, "://")) {
1660 ret = sd_parse_uri(s, filename, s->name, &snapid, tag);
1661 } else {
1662 ret = parse_vdiname(s, filename, s->name, &snapid, tag);
1664 if (ret < 0) {
1665 goto out;
1668 while (options && options->name) {
1669 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
1670 s->inode.vdi_size = options->value.n;
1671 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
1672 backing_file = options->value.s;
1673 } else if (!strcmp(options->name, BLOCK_OPT_PREALLOC)) {
1674 if (!options->value.s || !strcmp(options->value.s, "off")) {
1675 prealloc = false;
1676 } else if (!strcmp(options->value.s, "full")) {
1677 prealloc = true;
1678 } else {
1679 error_report("Invalid preallocation mode: '%s'",
1680 options->value.s);
1681 ret = -EINVAL;
1682 goto out;
1684 } else if (!strcmp(options->name, BLOCK_OPT_REDUNDANCY)) {
1685 if (options->value.s) {
1686 ret = parse_redundancy(s, options->value.s);
1687 if (ret < 0) {
1688 goto out;
1692 options++;
1695 if (s->inode.vdi_size > SD_MAX_VDI_SIZE) {
1696 error_report("too big image size");
1697 ret = -EINVAL;
1698 goto out;
1701 if (backing_file) {
1702 BlockDriverState *bs;
1703 BDRVSheepdogState *base;
1704 BlockDriver *drv;
1706 /* Currently, only Sheepdog backing image is supported. */
1707 drv = bdrv_find_protocol(backing_file, true);
1708 if (!drv || strcmp(drv->protocol_name, "sheepdog") != 0) {
1709 error_report("backing_file must be a sheepdog image");
1710 ret = -EINVAL;
1711 goto out;
1714 bs = NULL;
1715 ret = bdrv_open(&bs, backing_file, NULL, NULL, BDRV_O_PROTOCOL, NULL,
1716 &local_err);
1717 if (ret < 0) {
1718 qerror_report_err(local_err);
1719 error_free(local_err);
1720 goto out;
1723 base = bs->opaque;
1725 if (!is_snapshot(&base->inode)) {
1726 error_report("cannot clone from a non snapshot vdi");
1727 bdrv_unref(bs);
1728 ret = -EINVAL;
1729 goto out;
1731 s->inode.vdi_id = base->inode.vdi_id;
1732 bdrv_unref(bs);
1735 ret = do_sd_create(s, &vid, 0, &local_err);
1736 if (ret) {
1737 qerror_report_err(local_err);
1738 error_free(local_err);
1739 goto out;
1742 if (prealloc) {
1743 ret = sd_prealloc(filename, &local_err);
1744 if (ret < 0) {
1745 qerror_report_err(local_err);
1746 error_free(local_err);
1749 out:
1750 g_free(s);
1751 return ret;
1754 static void sd_close(BlockDriverState *bs)
1756 Error *local_err = NULL;
1757 BDRVSheepdogState *s = bs->opaque;
1758 SheepdogVdiReq hdr;
1759 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
1760 unsigned int wlen, rlen = 0;
1761 int fd, ret;
1763 DPRINTF("%s\n", s->name);
1765 fd = connect_to_sdog(s, &local_err);
1766 if (fd < 0) {
1767 qerror_report_err(local_err);
1768 error_free(local_err);
1769 return;
1772 memset(&hdr, 0, sizeof(hdr));
1774 hdr.opcode = SD_OP_RELEASE_VDI;
1775 hdr.base_vdi_id = s->inode.vdi_id;
1776 wlen = strlen(s->name) + 1;
1777 hdr.data_length = wlen;
1778 hdr.flags = SD_FLAG_CMD_WRITE;
1780 ret = do_req(fd, (SheepdogReq *)&hdr, s->name, &wlen, &rlen);
1782 closesocket(fd);
1784 if (!ret && rsp->result != SD_RES_SUCCESS &&
1785 rsp->result != SD_RES_VDI_NOT_LOCKED) {
1786 error_report("%s, %s", sd_strerror(rsp->result), s->name);
1789 qemu_aio_set_fd_handler(s->fd, NULL, NULL, NULL);
1790 closesocket(s->fd);
1791 g_free(s->host_spec);
1794 static int64_t sd_getlength(BlockDriverState *bs)
1796 BDRVSheepdogState *s = bs->opaque;
1798 return s->inode.vdi_size;
1801 static int sd_truncate(BlockDriverState *bs, int64_t offset)
1803 Error *local_err = NULL;
1804 BDRVSheepdogState *s = bs->opaque;
1805 int ret, fd;
1806 unsigned int datalen;
1808 if (offset < s->inode.vdi_size) {
1809 error_report("shrinking is not supported");
1810 return -EINVAL;
1811 } else if (offset > SD_MAX_VDI_SIZE) {
1812 error_report("too big image size");
1813 return -EINVAL;
1816 fd = connect_to_sdog(s, &local_err);
1817 if (fd < 0) {
1818 qerror_report_err(local_err);
1819 error_free(local_err);
1820 return fd;
1823 /* we don't need to update entire object */
1824 datalen = SD_INODE_SIZE - sizeof(s->inode.data_vdi_id);
1825 s->inode.vdi_size = offset;
1826 ret = write_object(fd, (char *)&s->inode, vid_to_vdi_oid(s->inode.vdi_id),
1827 s->inode.nr_copies, datalen, 0, false, s->cache_flags);
1828 close(fd);
1830 if (ret < 0) {
1831 error_report("failed to update an inode.");
1834 return ret;
1838 * This function is called after writing data objects. If we need to
1839 * update metadata, this sends a write request to the vdi object.
1840 * Otherwise, this switches back to sd_co_readv/writev.
1842 static void coroutine_fn sd_write_done(SheepdogAIOCB *acb)
1844 BDRVSheepdogState *s = acb->common.bs->opaque;
1845 struct iovec iov;
1846 AIOReq *aio_req;
1847 uint32_t offset, data_len, mn, mx;
1849 mn = s->min_dirty_data_idx;
1850 mx = s->max_dirty_data_idx;
1851 if (mn <= mx) {
1852 /* we need to update the vdi object. */
1853 offset = sizeof(s->inode) - sizeof(s->inode.data_vdi_id) +
1854 mn * sizeof(s->inode.data_vdi_id[0]);
1855 data_len = (mx - mn + 1) * sizeof(s->inode.data_vdi_id[0]);
1857 s->min_dirty_data_idx = UINT32_MAX;
1858 s->max_dirty_data_idx = 0;
1860 iov.iov_base = &s->inode;
1861 iov.iov_len = sizeof(s->inode);
1862 aio_req = alloc_aio_req(s, acb, vid_to_vdi_oid(s->inode.vdi_id),
1863 data_len, offset, 0, 0, offset);
1864 QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
1865 add_aio_request(s, aio_req, &iov, 1, false, AIOCB_WRITE_UDATA);
1867 acb->aio_done_func = sd_finish_aiocb;
1868 acb->aiocb_type = AIOCB_WRITE_UDATA;
1869 return;
1872 sd_finish_aiocb(acb);
1875 /* Delete current working VDI on the snapshot chain */
1876 static bool sd_delete(BDRVSheepdogState *s)
1878 Error *local_err = NULL;
1879 unsigned int wlen = SD_MAX_VDI_LEN, rlen = 0;
1880 SheepdogVdiReq hdr = {
1881 .opcode = SD_OP_DEL_VDI,
1882 .base_vdi_id = s->inode.vdi_id,
1883 .data_length = wlen,
1884 .flags = SD_FLAG_CMD_WRITE,
1886 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
1887 int fd, ret;
1889 fd = connect_to_sdog(s, &local_err);
1890 if (fd < 0) {
1891 qerror_report_err(local_err);
1892 error_free(local_err);
1893 return false;
1896 ret = do_req(fd, (SheepdogReq *)&hdr, s->name, &wlen, &rlen);
1897 closesocket(fd);
1898 if (ret) {
1899 return false;
1901 switch (rsp->result) {
1902 case SD_RES_NO_VDI:
1903 error_report("%s was already deleted", s->name);
1904 /* fall through */
1905 case SD_RES_SUCCESS:
1906 break;
1907 default:
1908 error_report("%s, %s", sd_strerror(rsp->result), s->name);
1909 return false;
1912 return true;
1916 * Create a writable VDI from a snapshot
1918 static int sd_create_branch(BDRVSheepdogState *s)
1920 Error *local_err = NULL;
1921 int ret, fd;
1922 uint32_t vid;
1923 char *buf;
1924 bool deleted;
1926 DPRINTF("%" PRIx32 " is snapshot.\n", s->inode.vdi_id);
1928 buf = g_malloc(SD_INODE_SIZE);
1931 * Even If deletion fails, we will just create extra snapshot based on
1932 * the working VDI which was supposed to be deleted. So no need to
1933 * false bail out.
1935 deleted = sd_delete(s);
1936 ret = do_sd_create(s, &vid, !deleted, &local_err);
1937 if (ret) {
1938 qerror_report_err(local_err);
1939 error_free(local_err);
1940 goto out;
1943 DPRINTF("%" PRIx32 " is created.\n", vid);
1945 fd = connect_to_sdog(s, &local_err);
1946 if (fd < 0) {
1947 qerror_report_err(local_err);
1948 error_free(local_err);
1949 ret = fd;
1950 goto out;
1953 ret = read_object(fd, buf, vid_to_vdi_oid(vid), s->inode.nr_copies,
1954 SD_INODE_SIZE, 0, s->cache_flags);
1956 closesocket(fd);
1958 if (ret < 0) {
1959 goto out;
1962 memcpy(&s->inode, buf, sizeof(s->inode));
1964 s->is_snapshot = false;
1965 ret = 0;
1966 DPRINTF("%" PRIx32 " was newly created.\n", s->inode.vdi_id);
1968 out:
1969 g_free(buf);
1971 return ret;
1975 * Send I/O requests to the server.
1977 * This function sends requests to the server, links the requests to
1978 * the inflight_list in BDRVSheepdogState, and exits without
1979 * waiting the response. The responses are received in the
1980 * `aio_read_response' function which is called from the main loop as
1981 * a fd handler.
1983 * Returns 1 when we need to wait a response, 0 when there is no sent
1984 * request and -errno in error cases.
1986 static int coroutine_fn sd_co_rw_vector(void *p)
1988 SheepdogAIOCB *acb = p;
1989 int ret = 0;
1990 unsigned long len, done = 0, total = acb->nb_sectors * BDRV_SECTOR_SIZE;
1991 unsigned long idx = acb->sector_num * BDRV_SECTOR_SIZE / SD_DATA_OBJ_SIZE;
1992 uint64_t oid;
1993 uint64_t offset = (acb->sector_num * BDRV_SECTOR_SIZE) % SD_DATA_OBJ_SIZE;
1994 BDRVSheepdogState *s = acb->common.bs->opaque;
1995 SheepdogInode *inode = &s->inode;
1996 AIOReq *aio_req;
1998 if (acb->aiocb_type == AIOCB_WRITE_UDATA && s->is_snapshot) {
2000 * In the case we open the snapshot VDI, Sheepdog creates the
2001 * writable VDI when we do a write operation first.
2003 ret = sd_create_branch(s);
2004 if (ret) {
2005 acb->ret = -EIO;
2006 goto out;
2011 * Make sure we don't free the aiocb before we are done with all requests.
2012 * This additional reference is dropped at the end of this function.
2014 acb->nr_pending++;
2016 while (done != total) {
2017 uint8_t flags = 0;
2018 uint64_t old_oid = 0;
2019 bool create = false;
2021 oid = vid_to_data_oid(inode->data_vdi_id[idx], idx);
2023 len = MIN(total - done, SD_DATA_OBJ_SIZE - offset);
2025 switch (acb->aiocb_type) {
2026 case AIOCB_READ_UDATA:
2027 if (!inode->data_vdi_id[idx]) {
2028 qemu_iovec_memset(acb->qiov, done, 0, len);
2029 goto done;
2031 break;
2032 case AIOCB_WRITE_UDATA:
2033 if (!inode->data_vdi_id[idx]) {
2034 create = true;
2035 } else if (!is_data_obj_writable(inode, idx)) {
2036 /* Copy-On-Write */
2037 create = true;
2038 old_oid = oid;
2039 flags = SD_FLAG_CMD_COW;
2041 break;
2042 case AIOCB_DISCARD_OBJ:
2044 * We discard the object only when the whole object is
2045 * 1) allocated 2) trimmed. Otherwise, simply skip it.
2047 if (len != SD_DATA_OBJ_SIZE || inode->data_vdi_id[idx] == 0) {
2048 goto done;
2050 break;
2051 default:
2052 break;
2055 if (create) {
2056 DPRINTF("update ino (%" PRIu32 ") %" PRIu64 " %" PRIu64 " %ld\n",
2057 inode->vdi_id, oid,
2058 vid_to_data_oid(inode->data_vdi_id[idx], idx), idx);
2059 oid = vid_to_data_oid(inode->vdi_id, idx);
2060 DPRINTF("new oid %" PRIx64 "\n", oid);
2063 aio_req = alloc_aio_req(s, acb, oid, len, offset, flags, old_oid, done);
2064 QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
2066 if (create) {
2067 if (check_simultaneous_create(s, aio_req)) {
2068 goto done;
2072 add_aio_request(s, aio_req, acb->qiov->iov, acb->qiov->niov, create,
2073 acb->aiocb_type);
2074 done:
2075 offset = 0;
2076 idx++;
2077 done += len;
2079 out:
2080 if (!--acb->nr_pending) {
2081 return acb->ret;
2083 return 1;
2086 static coroutine_fn int sd_co_writev(BlockDriverState *bs, int64_t sector_num,
2087 int nb_sectors, QEMUIOVector *qiov)
2089 SheepdogAIOCB *acb;
2090 int ret;
2091 int64_t offset = (sector_num + nb_sectors) * BDRV_SECTOR_SIZE;
2092 BDRVSheepdogState *s = bs->opaque;
2094 if (bs->growable && offset > s->inode.vdi_size) {
2095 ret = sd_truncate(bs, offset);
2096 if (ret < 0) {
2097 return ret;
2101 acb = sd_aio_setup(bs, qiov, sector_num, nb_sectors);
2102 acb->aio_done_func = sd_write_done;
2103 acb->aiocb_type = AIOCB_WRITE_UDATA;
2105 ret = sd_co_rw_vector(acb);
2106 if (ret <= 0) {
2107 qemu_aio_release(acb);
2108 return ret;
2111 qemu_coroutine_yield();
2113 return acb->ret;
2116 static coroutine_fn int sd_co_readv(BlockDriverState *bs, int64_t sector_num,
2117 int nb_sectors, QEMUIOVector *qiov)
2119 SheepdogAIOCB *acb;
2120 int ret;
2122 acb = sd_aio_setup(bs, qiov, sector_num, nb_sectors);
2123 acb->aiocb_type = AIOCB_READ_UDATA;
2124 acb->aio_done_func = sd_finish_aiocb;
2126 ret = sd_co_rw_vector(acb);
2127 if (ret <= 0) {
2128 qemu_aio_release(acb);
2129 return ret;
2132 qemu_coroutine_yield();
2134 return acb->ret;
2137 static int coroutine_fn sd_co_flush_to_disk(BlockDriverState *bs)
2139 BDRVSheepdogState *s = bs->opaque;
2140 SheepdogAIOCB *acb;
2141 AIOReq *aio_req;
2143 if (s->cache_flags != SD_FLAG_CMD_CACHE) {
2144 return 0;
2147 acb = sd_aio_setup(bs, NULL, 0, 0);
2148 acb->aiocb_type = AIOCB_FLUSH_CACHE;
2149 acb->aio_done_func = sd_finish_aiocb;
2151 aio_req = alloc_aio_req(s, acb, vid_to_vdi_oid(s->inode.vdi_id),
2152 0, 0, 0, 0, 0);
2153 QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
2154 add_aio_request(s, aio_req, NULL, 0, false, acb->aiocb_type);
2156 qemu_coroutine_yield();
2157 return acb->ret;
2160 static int sd_snapshot_create(BlockDriverState *bs, QEMUSnapshotInfo *sn_info)
2162 Error *local_err = NULL;
2163 BDRVSheepdogState *s = bs->opaque;
2164 int ret, fd;
2165 uint32_t new_vid;
2166 SheepdogInode *inode;
2167 unsigned int datalen;
2169 DPRINTF("sn_info: name %s id_str %s s: name %s vm_state_size %" PRId64 " "
2170 "is_snapshot %d\n", sn_info->name, sn_info->id_str,
2171 s->name, sn_info->vm_state_size, s->is_snapshot);
2173 if (s->is_snapshot) {
2174 error_report("You can't create a snapshot of a snapshot VDI, "
2175 "%s (%" PRIu32 ").", s->name, s->inode.vdi_id);
2177 return -EINVAL;
2180 DPRINTF("%s %s\n", sn_info->name, sn_info->id_str);
2182 s->inode.vm_state_size = sn_info->vm_state_size;
2183 s->inode.vm_clock_nsec = sn_info->vm_clock_nsec;
2184 /* It appears that inode.tag does not require a NUL terminator,
2185 * which means this use of strncpy is ok.
2187 strncpy(s->inode.tag, sn_info->name, sizeof(s->inode.tag));
2188 /* we don't need to update entire object */
2189 datalen = SD_INODE_SIZE - sizeof(s->inode.data_vdi_id);
2191 /* refresh inode. */
2192 fd = connect_to_sdog(s, &local_err);
2193 if (fd < 0) {
2194 qerror_report_err(local_err);
2195 error_free(local_err);
2196 ret = fd;
2197 goto cleanup;
2200 ret = write_object(fd, (char *)&s->inode, vid_to_vdi_oid(s->inode.vdi_id),
2201 s->inode.nr_copies, datalen, 0, false, s->cache_flags);
2202 if (ret < 0) {
2203 error_report("failed to write snapshot's inode.");
2204 goto cleanup;
2207 ret = do_sd_create(s, &new_vid, 1, &local_err);
2208 if (ret < 0) {
2209 qerror_report_err(local_err);
2210 error_free(local_err);
2211 error_report("failed to create inode for snapshot. %s",
2212 strerror(errno));
2213 goto cleanup;
2216 inode = (SheepdogInode *)g_malloc(datalen);
2218 ret = read_object(fd, (char *)inode, vid_to_vdi_oid(new_vid),
2219 s->inode.nr_copies, datalen, 0, s->cache_flags);
2221 if (ret < 0) {
2222 error_report("failed to read new inode info. %s", strerror(errno));
2223 goto cleanup;
2226 memcpy(&s->inode, inode, datalen);
2227 DPRINTF("s->inode: name %s snap_id %x oid %x\n",
2228 s->inode.name, s->inode.snap_id, s->inode.vdi_id);
2230 cleanup:
2231 closesocket(fd);
2232 return ret;
2236 * We implement rollback(loadvm) operation to the specified snapshot by
2237 * 1) switch to the snapshot
2238 * 2) rely on sd_create_branch to delete working VDI and
2239 * 3) create a new working VDI based on the specified snapshot
2241 static int sd_snapshot_goto(BlockDriverState *bs, const char *snapshot_id)
2243 BDRVSheepdogState *s = bs->opaque;
2244 BDRVSheepdogState *old_s;
2245 char tag[SD_MAX_VDI_TAG_LEN];
2246 uint32_t snapid = 0;
2247 int ret = 0;
2249 old_s = g_malloc(sizeof(BDRVSheepdogState));
2251 memcpy(old_s, s, sizeof(BDRVSheepdogState));
2253 snapid = strtoul(snapshot_id, NULL, 10);
2254 if (snapid) {
2255 tag[0] = 0;
2256 } else {
2257 pstrcpy(tag, sizeof(tag), snapshot_id);
2260 ret = reload_inode(s, snapid, tag);
2261 if (ret) {
2262 goto out;
2265 ret = sd_create_branch(s);
2266 if (ret) {
2267 goto out;
2270 g_free(old_s);
2272 return 0;
2273 out:
2274 /* recover bdrv_sd_state */
2275 memcpy(s, old_s, sizeof(BDRVSheepdogState));
2276 g_free(old_s);
2278 error_report("failed to open. recover old bdrv_sd_state.");
2280 return ret;
2283 static int sd_snapshot_delete(BlockDriverState *bs,
2284 const char *snapshot_id,
2285 const char *name,
2286 Error **errp)
2288 /* FIXME: Delete specified snapshot id. */
2289 return 0;
2292 static int sd_snapshot_list(BlockDriverState *bs, QEMUSnapshotInfo **psn_tab)
2294 Error *local_err = NULL;
2295 BDRVSheepdogState *s = bs->opaque;
2296 SheepdogReq req;
2297 int fd, nr = 1024, ret, max = BITS_TO_LONGS(SD_NR_VDIS) * sizeof(long);
2298 QEMUSnapshotInfo *sn_tab = NULL;
2299 unsigned wlen, rlen;
2300 int found = 0;
2301 static SheepdogInode inode;
2302 unsigned long *vdi_inuse;
2303 unsigned int start_nr;
2304 uint64_t hval;
2305 uint32_t vid;
2307 vdi_inuse = g_malloc(max);
2309 fd = connect_to_sdog(s, &local_err);
2310 if (fd < 0) {
2311 qerror_report_err(local_err);
2312 error_free(local_err);
2313 ret = fd;
2314 goto out;
2317 rlen = max;
2318 wlen = 0;
2320 memset(&req, 0, sizeof(req));
2322 req.opcode = SD_OP_READ_VDIS;
2323 req.data_length = max;
2325 ret = do_req(fd, (SheepdogReq *)&req, vdi_inuse, &wlen, &rlen);
2327 closesocket(fd);
2328 if (ret) {
2329 goto out;
2332 sn_tab = g_malloc0(nr * sizeof(*sn_tab));
2334 /* calculate a vdi id with hash function */
2335 hval = fnv_64a_buf(s->name, strlen(s->name), FNV1A_64_INIT);
2336 start_nr = hval & (SD_NR_VDIS - 1);
2338 fd = connect_to_sdog(s, &local_err);
2339 if (fd < 0) {
2340 qerror_report_err(local_err);
2341 error_free(local_err);
2342 ret = fd;
2343 goto out;
2346 for (vid = start_nr; found < nr; vid = (vid + 1) % SD_NR_VDIS) {
2347 if (!test_bit(vid, vdi_inuse)) {
2348 break;
2351 /* we don't need to read entire object */
2352 ret = read_object(fd, (char *)&inode, vid_to_vdi_oid(vid),
2353 0, SD_INODE_SIZE - sizeof(inode.data_vdi_id), 0,
2354 s->cache_flags);
2356 if (ret) {
2357 continue;
2360 if (!strcmp(inode.name, s->name) && is_snapshot(&inode)) {
2361 sn_tab[found].date_sec = inode.snap_ctime >> 32;
2362 sn_tab[found].date_nsec = inode.snap_ctime & 0xffffffff;
2363 sn_tab[found].vm_state_size = inode.vm_state_size;
2364 sn_tab[found].vm_clock_nsec = inode.vm_clock_nsec;
2366 snprintf(sn_tab[found].id_str, sizeof(sn_tab[found].id_str),
2367 "%" PRIu32, inode.snap_id);
2368 pstrcpy(sn_tab[found].name,
2369 MIN(sizeof(sn_tab[found].name), sizeof(inode.tag)),
2370 inode.tag);
2371 found++;
2375 closesocket(fd);
2376 out:
2377 *psn_tab = sn_tab;
2379 g_free(vdi_inuse);
2381 if (ret < 0) {
2382 return ret;
2385 return found;
2388 static int do_load_save_vmstate(BDRVSheepdogState *s, uint8_t *data,
2389 int64_t pos, int size, int load)
2391 Error *local_err = NULL;
2392 bool create;
2393 int fd, ret = 0, remaining = size;
2394 unsigned int data_len;
2395 uint64_t vmstate_oid;
2396 uint64_t offset;
2397 uint32_t vdi_index;
2398 uint32_t vdi_id = load ? s->inode.parent_vdi_id : s->inode.vdi_id;
2400 fd = connect_to_sdog(s, &local_err);
2401 if (fd < 0) {
2402 qerror_report_err(local_err);
2403 error_free(local_err);
2404 return fd;
2407 while (remaining) {
2408 vdi_index = pos / SD_DATA_OBJ_SIZE;
2409 offset = pos % SD_DATA_OBJ_SIZE;
2411 data_len = MIN(remaining, SD_DATA_OBJ_SIZE - offset);
2413 vmstate_oid = vid_to_vmstate_oid(vdi_id, vdi_index);
2415 create = (offset == 0);
2416 if (load) {
2417 ret = read_object(fd, (char *)data, vmstate_oid,
2418 s->inode.nr_copies, data_len, offset,
2419 s->cache_flags);
2420 } else {
2421 ret = write_object(fd, (char *)data, vmstate_oid,
2422 s->inode.nr_copies, data_len, offset, create,
2423 s->cache_flags);
2426 if (ret < 0) {
2427 error_report("failed to save vmstate %s", strerror(errno));
2428 goto cleanup;
2431 pos += data_len;
2432 data += data_len;
2433 remaining -= data_len;
2435 ret = size;
2436 cleanup:
2437 closesocket(fd);
2438 return ret;
2441 static int sd_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2442 int64_t pos)
2444 BDRVSheepdogState *s = bs->opaque;
2445 void *buf;
2446 int ret;
2448 buf = qemu_blockalign(bs, qiov->size);
2449 qemu_iovec_to_buf(qiov, 0, buf, qiov->size);
2450 ret = do_load_save_vmstate(s, (uint8_t *) buf, pos, qiov->size, 0);
2451 qemu_vfree(buf);
2453 return ret;
2456 static int sd_load_vmstate(BlockDriverState *bs, uint8_t *data,
2457 int64_t pos, int size)
2459 BDRVSheepdogState *s = bs->opaque;
2461 return do_load_save_vmstate(s, data, pos, size, 1);
2465 static coroutine_fn int sd_co_discard(BlockDriverState *bs, int64_t sector_num,
2466 int nb_sectors)
2468 SheepdogAIOCB *acb;
2469 QEMUIOVector dummy;
2470 BDRVSheepdogState *s = bs->opaque;
2471 int ret;
2473 if (!s->discard_supported) {
2474 return 0;
2477 acb = sd_aio_setup(bs, &dummy, sector_num, nb_sectors);
2478 acb->aiocb_type = AIOCB_DISCARD_OBJ;
2479 acb->aio_done_func = sd_finish_aiocb;
2481 ret = sd_co_rw_vector(acb);
2482 if (ret <= 0) {
2483 qemu_aio_release(acb);
2484 return ret;
2487 qemu_coroutine_yield();
2489 return acb->ret;
2492 static coroutine_fn int64_t
2493 sd_co_get_block_status(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
2494 int *pnum)
2496 BDRVSheepdogState *s = bs->opaque;
2497 SheepdogInode *inode = &s->inode;
2498 uint64_t offset = sector_num * BDRV_SECTOR_SIZE;
2499 unsigned long start = offset / SD_DATA_OBJ_SIZE,
2500 end = DIV_ROUND_UP((sector_num + nb_sectors) *
2501 BDRV_SECTOR_SIZE, SD_DATA_OBJ_SIZE);
2502 unsigned long idx;
2503 int64_t ret = BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | offset;
2505 for (idx = start; idx < end; idx++) {
2506 if (inode->data_vdi_id[idx] == 0) {
2507 break;
2510 if (idx == start) {
2511 /* Get the longest length of unallocated sectors */
2512 ret = 0;
2513 for (idx = start + 1; idx < end; idx++) {
2514 if (inode->data_vdi_id[idx] != 0) {
2515 break;
2520 *pnum = (idx - start) * SD_DATA_OBJ_SIZE / BDRV_SECTOR_SIZE;
2521 if (*pnum > nb_sectors) {
2522 *pnum = nb_sectors;
2524 return ret;
2527 static int64_t sd_get_allocated_file_size(BlockDriverState *bs)
2529 BDRVSheepdogState *s = bs->opaque;
2530 SheepdogInode *inode = &s->inode;
2531 unsigned long i, last = DIV_ROUND_UP(inode->vdi_size, SD_DATA_OBJ_SIZE);
2532 uint64_t size = 0;
2534 for (i = 0; i < last; i++) {
2535 if (inode->data_vdi_id[i] == 0) {
2536 continue;
2538 size += SD_DATA_OBJ_SIZE;
2540 return size;
2543 static QEMUOptionParameter sd_create_options[] = {
2545 .name = BLOCK_OPT_SIZE,
2546 .type = OPT_SIZE,
2547 .help = "Virtual disk size"
2550 .name = BLOCK_OPT_BACKING_FILE,
2551 .type = OPT_STRING,
2552 .help = "File name of a base image"
2555 .name = BLOCK_OPT_PREALLOC,
2556 .type = OPT_STRING,
2557 .help = "Preallocation mode (allowed values: off, full)"
2560 .name = BLOCK_OPT_REDUNDANCY,
2561 .type = OPT_STRING,
2562 .help = "Redundancy of the image"
2564 { NULL }
2567 static BlockDriver bdrv_sheepdog = {
2568 .format_name = "sheepdog",
2569 .protocol_name = "sheepdog",
2570 .instance_size = sizeof(BDRVSheepdogState),
2571 .bdrv_needs_filename = true,
2572 .bdrv_file_open = sd_open,
2573 .bdrv_close = sd_close,
2574 .bdrv_create = sd_create,
2575 .bdrv_has_zero_init = bdrv_has_zero_init_1,
2576 .bdrv_getlength = sd_getlength,
2577 .bdrv_get_allocated_file_size = sd_get_allocated_file_size,
2578 .bdrv_truncate = sd_truncate,
2580 .bdrv_co_readv = sd_co_readv,
2581 .bdrv_co_writev = sd_co_writev,
2582 .bdrv_co_flush_to_disk = sd_co_flush_to_disk,
2583 .bdrv_co_discard = sd_co_discard,
2584 .bdrv_co_get_block_status = sd_co_get_block_status,
2586 .bdrv_snapshot_create = sd_snapshot_create,
2587 .bdrv_snapshot_goto = sd_snapshot_goto,
2588 .bdrv_snapshot_delete = sd_snapshot_delete,
2589 .bdrv_snapshot_list = sd_snapshot_list,
2591 .bdrv_save_vmstate = sd_save_vmstate,
2592 .bdrv_load_vmstate = sd_load_vmstate,
2594 .create_options = sd_create_options,
2597 static BlockDriver bdrv_sheepdog_tcp = {
2598 .format_name = "sheepdog",
2599 .protocol_name = "sheepdog+tcp",
2600 .instance_size = sizeof(BDRVSheepdogState),
2601 .bdrv_needs_filename = true,
2602 .bdrv_file_open = sd_open,
2603 .bdrv_close = sd_close,
2604 .bdrv_create = sd_create,
2605 .bdrv_has_zero_init = bdrv_has_zero_init_1,
2606 .bdrv_getlength = sd_getlength,
2607 .bdrv_get_allocated_file_size = sd_get_allocated_file_size,
2608 .bdrv_truncate = sd_truncate,
2610 .bdrv_co_readv = sd_co_readv,
2611 .bdrv_co_writev = sd_co_writev,
2612 .bdrv_co_flush_to_disk = sd_co_flush_to_disk,
2613 .bdrv_co_discard = sd_co_discard,
2614 .bdrv_co_get_block_status = sd_co_get_block_status,
2616 .bdrv_snapshot_create = sd_snapshot_create,
2617 .bdrv_snapshot_goto = sd_snapshot_goto,
2618 .bdrv_snapshot_delete = sd_snapshot_delete,
2619 .bdrv_snapshot_list = sd_snapshot_list,
2621 .bdrv_save_vmstate = sd_save_vmstate,
2622 .bdrv_load_vmstate = sd_load_vmstate,
2624 .create_options = sd_create_options,
2627 static BlockDriver bdrv_sheepdog_unix = {
2628 .format_name = "sheepdog",
2629 .protocol_name = "sheepdog+unix",
2630 .instance_size = sizeof(BDRVSheepdogState),
2631 .bdrv_needs_filename = true,
2632 .bdrv_file_open = sd_open,
2633 .bdrv_close = sd_close,
2634 .bdrv_create = sd_create,
2635 .bdrv_has_zero_init = bdrv_has_zero_init_1,
2636 .bdrv_getlength = sd_getlength,
2637 .bdrv_get_allocated_file_size = sd_get_allocated_file_size,
2638 .bdrv_truncate = sd_truncate,
2640 .bdrv_co_readv = sd_co_readv,
2641 .bdrv_co_writev = sd_co_writev,
2642 .bdrv_co_flush_to_disk = sd_co_flush_to_disk,
2643 .bdrv_co_discard = sd_co_discard,
2644 .bdrv_co_get_block_status = sd_co_get_block_status,
2646 .bdrv_snapshot_create = sd_snapshot_create,
2647 .bdrv_snapshot_goto = sd_snapshot_goto,
2648 .bdrv_snapshot_delete = sd_snapshot_delete,
2649 .bdrv_snapshot_list = sd_snapshot_list,
2651 .bdrv_save_vmstate = sd_save_vmstate,
2652 .bdrv_load_vmstate = sd_load_vmstate,
2654 .create_options = sd_create_options,
2657 static void bdrv_sheepdog_init(void)
2659 bdrv_register(&bdrv_sheepdog);
2660 bdrv_register(&bdrv_sheepdog_tcp);
2661 bdrv_register(&bdrv_sheepdog_unix);
2663 block_init(bdrv_sheepdog_init);