qom: Add object_new_with_props() / object_new_withpropv() helpers
[qemu/cris-port.git] / block / sheepdog.c
blobbd7cbed048de9dee649a17cf3268b7dcc7b5fd1d
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
40 #define SD_OP_GET_CLUSTER_DEFAULT 0x18
42 #define SD_FLAG_CMD_WRITE 0x01
43 #define SD_FLAG_CMD_COW 0x02
44 #define SD_FLAG_CMD_CACHE 0x04 /* Writeback mode for cache */
45 #define SD_FLAG_CMD_DIRECT 0x08 /* Don't use cache */
47 #define SD_RES_SUCCESS 0x00 /* Success */
48 #define SD_RES_UNKNOWN 0x01 /* Unknown error */
49 #define SD_RES_NO_OBJ 0x02 /* No object found */
50 #define SD_RES_EIO 0x03 /* I/O error */
51 #define SD_RES_VDI_EXIST 0x04 /* Vdi exists already */
52 #define SD_RES_INVALID_PARMS 0x05 /* Invalid parameters */
53 #define SD_RES_SYSTEM_ERROR 0x06 /* System error */
54 #define SD_RES_VDI_LOCKED 0x07 /* Vdi is locked */
55 #define SD_RES_NO_VDI 0x08 /* No vdi found */
56 #define SD_RES_NO_BASE_VDI 0x09 /* No base vdi found */
57 #define SD_RES_VDI_READ 0x0A /* Cannot read requested vdi */
58 #define SD_RES_VDI_WRITE 0x0B /* Cannot write requested vdi */
59 #define SD_RES_BASE_VDI_READ 0x0C /* Cannot read base vdi */
60 #define SD_RES_BASE_VDI_WRITE 0x0D /* Cannot write base vdi */
61 #define SD_RES_NO_TAG 0x0E /* Requested tag is not found */
62 #define SD_RES_STARTUP 0x0F /* Sheepdog is on starting up */
63 #define SD_RES_VDI_NOT_LOCKED 0x10 /* Vdi is not locked */
64 #define SD_RES_SHUTDOWN 0x11 /* Sheepdog is shutting down */
65 #define SD_RES_NO_MEM 0x12 /* Cannot allocate memory */
66 #define SD_RES_FULL_VDI 0x13 /* we already have the maximum vdis */
67 #define SD_RES_VER_MISMATCH 0x14 /* Protocol version mismatch */
68 #define SD_RES_NO_SPACE 0x15 /* Server has no room for new objects */
69 #define SD_RES_WAIT_FOR_FORMAT 0x16 /* Waiting for a format operation */
70 #define SD_RES_WAIT_FOR_JOIN 0x17 /* Waiting for other nodes joining */
71 #define SD_RES_JOIN_FAILED 0x18 /* Target node had failed to join sheepdog */
72 #define SD_RES_HALT 0x19 /* Sheepdog is stopped serving IO request */
73 #define SD_RES_READONLY 0x1A /* Object is read-only */
76 * Object ID rules
78 * 0 - 19 (20 bits): data object space
79 * 20 - 31 (12 bits): reserved data object space
80 * 32 - 55 (24 bits): vdi object space
81 * 56 - 59 ( 4 bits): reserved vdi object space
82 * 60 - 63 ( 4 bits): object type identifier space
85 #define VDI_SPACE_SHIFT 32
86 #define VDI_BIT (UINT64_C(1) << 63)
87 #define VMSTATE_BIT (UINT64_C(1) << 62)
88 #define MAX_DATA_OBJS (UINT64_C(1) << 20)
89 #define MAX_CHILDREN 1024
90 #define SD_MAX_VDI_LEN 256
91 #define SD_MAX_VDI_TAG_LEN 256
92 #define SD_NR_VDIS (1U << 24)
93 #define SD_DATA_OBJ_SIZE (UINT64_C(1) << 22)
94 #define SD_MAX_VDI_SIZE (SD_DATA_OBJ_SIZE * MAX_DATA_OBJS)
95 #define SD_DEFAULT_BLOCK_SIZE_SHIFT 22
97 * For erasure coding, we use at most SD_EC_MAX_STRIP for data strips and
98 * (SD_EC_MAX_STRIP - 1) for parity strips
100 * SD_MAX_COPIES is sum of number of data strips and parity strips.
102 #define SD_EC_MAX_STRIP 16
103 #define SD_MAX_COPIES (SD_EC_MAX_STRIP * 2 - 1)
105 #define SD_INODE_SIZE (sizeof(SheepdogInode))
106 #define CURRENT_VDI_ID 0
108 #define LOCK_TYPE_NORMAL 0
109 #define LOCK_TYPE_SHARED 1 /* for iSCSI multipath */
111 typedef struct SheepdogReq {
112 uint8_t proto_ver;
113 uint8_t opcode;
114 uint16_t flags;
115 uint32_t epoch;
116 uint32_t id;
117 uint32_t data_length;
118 uint32_t opcode_specific[8];
119 } SheepdogReq;
121 typedef struct SheepdogRsp {
122 uint8_t proto_ver;
123 uint8_t opcode;
124 uint16_t flags;
125 uint32_t epoch;
126 uint32_t id;
127 uint32_t data_length;
128 uint32_t result;
129 uint32_t opcode_specific[7];
130 } SheepdogRsp;
132 typedef struct SheepdogObjReq {
133 uint8_t proto_ver;
134 uint8_t opcode;
135 uint16_t flags;
136 uint32_t epoch;
137 uint32_t id;
138 uint32_t data_length;
139 uint64_t oid;
140 uint64_t cow_oid;
141 uint8_t copies;
142 uint8_t copy_policy;
143 uint8_t reserved[6];
144 uint64_t offset;
145 } SheepdogObjReq;
147 typedef struct SheepdogObjRsp {
148 uint8_t proto_ver;
149 uint8_t opcode;
150 uint16_t flags;
151 uint32_t epoch;
152 uint32_t id;
153 uint32_t data_length;
154 uint32_t result;
155 uint8_t copies;
156 uint8_t copy_policy;
157 uint8_t reserved[2];
158 uint32_t pad[6];
159 } SheepdogObjRsp;
161 typedef struct SheepdogVdiReq {
162 uint8_t proto_ver;
163 uint8_t opcode;
164 uint16_t flags;
165 uint32_t epoch;
166 uint32_t id;
167 uint32_t data_length;
168 uint64_t vdi_size;
169 uint32_t base_vdi_id;
170 uint8_t copies;
171 uint8_t copy_policy;
172 uint8_t store_policy;
173 uint8_t block_size_shift;
174 uint32_t snapid;
175 uint32_t type;
176 uint32_t pad[2];
177 } SheepdogVdiReq;
179 typedef struct SheepdogVdiRsp {
180 uint8_t proto_ver;
181 uint8_t opcode;
182 uint16_t flags;
183 uint32_t epoch;
184 uint32_t id;
185 uint32_t data_length;
186 uint32_t result;
187 uint32_t rsvd;
188 uint32_t vdi_id;
189 uint32_t pad[5];
190 } SheepdogVdiRsp;
192 typedef struct SheepdogClusterRsp {
193 uint8_t proto_ver;
194 uint8_t opcode;
195 uint16_t flags;
196 uint32_t epoch;
197 uint32_t id;
198 uint32_t data_length;
199 uint32_t result;
200 uint8_t nr_copies;
201 uint8_t copy_policy;
202 uint8_t block_size_shift;
203 uint8_t __pad1;
204 uint32_t __pad2[6];
205 } SheepdogClusterRsp;
207 typedef struct SheepdogInode {
208 char name[SD_MAX_VDI_LEN];
209 char tag[SD_MAX_VDI_TAG_LEN];
210 uint64_t ctime;
211 uint64_t snap_ctime;
212 uint64_t vm_clock_nsec;
213 uint64_t vdi_size;
214 uint64_t vm_state_size;
215 uint16_t copy_policy;
216 uint8_t nr_copies;
217 uint8_t block_size_shift;
218 uint32_t snap_id;
219 uint32_t vdi_id;
220 uint32_t parent_vdi_id;
221 uint32_t child_vdi_id[MAX_CHILDREN];
222 uint32_t data_vdi_id[MAX_DATA_OBJS];
223 } SheepdogInode;
225 #define SD_INODE_HEADER_SIZE offsetof(SheepdogInode, data_vdi_id)
228 * 64 bit FNV-1a non-zero initial basis
230 #define FNV1A_64_INIT ((uint64_t)0xcbf29ce484222325ULL)
233 * 64 bit Fowler/Noll/Vo FNV-1a hash code
235 static inline uint64_t fnv_64a_buf(void *buf, size_t len, uint64_t hval)
237 unsigned char *bp = buf;
238 unsigned char *be = bp + len;
239 while (bp < be) {
240 hval ^= (uint64_t) *bp++;
241 hval += (hval << 1) + (hval << 4) + (hval << 5) +
242 (hval << 7) + (hval << 8) + (hval << 40);
244 return hval;
247 static inline bool is_data_obj_writable(SheepdogInode *inode, unsigned int idx)
249 return inode->vdi_id == inode->data_vdi_id[idx];
252 static inline bool is_data_obj(uint64_t oid)
254 return !(VDI_BIT & oid);
257 static inline uint64_t data_oid_to_idx(uint64_t oid)
259 return oid & (MAX_DATA_OBJS - 1);
262 static inline uint32_t oid_to_vid(uint64_t oid)
264 return (oid & ~VDI_BIT) >> VDI_SPACE_SHIFT;
267 static inline uint64_t vid_to_vdi_oid(uint32_t vid)
269 return VDI_BIT | ((uint64_t)vid << VDI_SPACE_SHIFT);
272 static inline uint64_t vid_to_vmstate_oid(uint32_t vid, uint32_t idx)
274 return VMSTATE_BIT | ((uint64_t)vid << VDI_SPACE_SHIFT) | idx;
277 static inline uint64_t vid_to_data_oid(uint32_t vid, uint32_t idx)
279 return ((uint64_t)vid << VDI_SPACE_SHIFT) | idx;
282 static inline bool is_snapshot(struct SheepdogInode *inode)
284 return !!inode->snap_ctime;
287 #undef DPRINTF
288 #ifdef DEBUG_SDOG
289 #define DPRINTF(fmt, args...) \
290 do { \
291 fprintf(stdout, "%s %d: " fmt, __func__, __LINE__, ##args); \
292 } while (0)
293 #else
294 #define DPRINTF(fmt, args...)
295 #endif
297 typedef struct SheepdogAIOCB SheepdogAIOCB;
299 typedef struct AIOReq {
300 SheepdogAIOCB *aiocb;
301 unsigned int iov_offset;
303 uint64_t oid;
304 uint64_t base_oid;
305 uint64_t offset;
306 unsigned int data_len;
307 uint8_t flags;
308 uint32_t id;
309 bool create;
311 QLIST_ENTRY(AIOReq) aio_siblings;
312 } AIOReq;
314 enum AIOCBState {
315 AIOCB_WRITE_UDATA,
316 AIOCB_READ_UDATA,
317 AIOCB_FLUSH_CACHE,
318 AIOCB_DISCARD_OBJ,
321 struct SheepdogAIOCB {
322 BlockAIOCB common;
324 QEMUIOVector *qiov;
326 int64_t sector_num;
327 int nb_sectors;
329 int ret;
330 enum AIOCBState aiocb_type;
332 Coroutine *coroutine;
333 void (*aio_done_func)(SheepdogAIOCB *);
335 bool cancelable;
336 int nr_pending;
339 typedef struct BDRVSheepdogState {
340 BlockDriverState *bs;
341 AioContext *aio_context;
343 SheepdogInode inode;
345 uint32_t min_dirty_data_idx;
346 uint32_t max_dirty_data_idx;
348 char name[SD_MAX_VDI_LEN];
349 bool is_snapshot;
350 uint32_t cache_flags;
351 bool discard_supported;
353 char *host_spec;
354 bool is_unix;
355 int fd;
357 CoMutex lock;
358 Coroutine *co_send;
359 Coroutine *co_recv;
361 uint32_t aioreq_seq_num;
363 /* Every aio request must be linked to either of these queues. */
364 QLIST_HEAD(inflight_aio_head, AIOReq) inflight_aio_head;
365 QLIST_HEAD(pending_aio_head, AIOReq) pending_aio_head;
366 QLIST_HEAD(failed_aio_head, AIOReq) failed_aio_head;
367 } BDRVSheepdogState;
369 static const char * sd_strerror(int err)
371 int i;
373 static const struct {
374 int err;
375 const char *desc;
376 } errors[] = {
377 {SD_RES_SUCCESS, "Success"},
378 {SD_RES_UNKNOWN, "Unknown error"},
379 {SD_RES_NO_OBJ, "No object found"},
380 {SD_RES_EIO, "I/O error"},
381 {SD_RES_VDI_EXIST, "VDI exists already"},
382 {SD_RES_INVALID_PARMS, "Invalid parameters"},
383 {SD_RES_SYSTEM_ERROR, "System error"},
384 {SD_RES_VDI_LOCKED, "VDI is already locked"},
385 {SD_RES_NO_VDI, "No vdi found"},
386 {SD_RES_NO_BASE_VDI, "No base VDI found"},
387 {SD_RES_VDI_READ, "Failed read the requested VDI"},
388 {SD_RES_VDI_WRITE, "Failed to write the requested VDI"},
389 {SD_RES_BASE_VDI_READ, "Failed to read the base VDI"},
390 {SD_RES_BASE_VDI_WRITE, "Failed to write the base VDI"},
391 {SD_RES_NO_TAG, "Failed to find the requested tag"},
392 {SD_RES_STARTUP, "The system is still booting"},
393 {SD_RES_VDI_NOT_LOCKED, "VDI isn't locked"},
394 {SD_RES_SHUTDOWN, "The system is shutting down"},
395 {SD_RES_NO_MEM, "Out of memory on the server"},
396 {SD_RES_FULL_VDI, "We already have the maximum vdis"},
397 {SD_RES_VER_MISMATCH, "Protocol version mismatch"},
398 {SD_RES_NO_SPACE, "Server has no space for new objects"},
399 {SD_RES_WAIT_FOR_FORMAT, "Sheepdog is waiting for a format operation"},
400 {SD_RES_WAIT_FOR_JOIN, "Sheepdog is waiting for other nodes joining"},
401 {SD_RES_JOIN_FAILED, "Target node had failed to join sheepdog"},
402 {SD_RES_HALT, "Sheepdog is stopped serving IO request"},
403 {SD_RES_READONLY, "Object is read-only"},
406 for (i = 0; i < ARRAY_SIZE(errors); ++i) {
407 if (errors[i].err == err) {
408 return errors[i].desc;
412 return "Invalid error code";
416 * Sheepdog I/O handling:
418 * 1. In sd_co_rw_vector, we send the I/O requests to the server and
419 * link the requests to the inflight_list in the
420 * BDRVSheepdogState. The function exits without waiting for
421 * receiving the response.
423 * 2. We receive the response in aio_read_response, the fd handler to
424 * the sheepdog connection. If metadata update is needed, we send
425 * the write request to the vdi object in sd_write_done, the write
426 * completion function. We switch back to sd_co_readv/writev after
427 * all the requests belonging to the AIOCB are finished.
430 static inline AIOReq *alloc_aio_req(BDRVSheepdogState *s, SheepdogAIOCB *acb,
431 uint64_t oid, unsigned int data_len,
432 uint64_t offset, uint8_t flags, bool create,
433 uint64_t base_oid, unsigned int iov_offset)
435 AIOReq *aio_req;
437 aio_req = g_malloc(sizeof(*aio_req));
438 aio_req->aiocb = acb;
439 aio_req->iov_offset = iov_offset;
440 aio_req->oid = oid;
441 aio_req->base_oid = base_oid;
442 aio_req->offset = offset;
443 aio_req->data_len = data_len;
444 aio_req->flags = flags;
445 aio_req->id = s->aioreq_seq_num++;
446 aio_req->create = create;
448 acb->nr_pending++;
449 return aio_req;
452 static inline void free_aio_req(BDRVSheepdogState *s, AIOReq *aio_req)
454 SheepdogAIOCB *acb = aio_req->aiocb;
456 acb->cancelable = false;
457 QLIST_REMOVE(aio_req, aio_siblings);
458 g_free(aio_req);
460 acb->nr_pending--;
463 static void coroutine_fn sd_finish_aiocb(SheepdogAIOCB *acb)
465 qemu_coroutine_enter(acb->coroutine, NULL);
466 qemu_aio_unref(acb);
470 * Check whether the specified acb can be canceled
472 * We can cancel aio when any request belonging to the acb is:
473 * - Not processed by the sheepdog server.
474 * - Not linked to the inflight queue.
476 static bool sd_acb_cancelable(const SheepdogAIOCB *acb)
478 BDRVSheepdogState *s = acb->common.bs->opaque;
479 AIOReq *aioreq;
481 if (!acb->cancelable) {
482 return false;
485 QLIST_FOREACH(aioreq, &s->inflight_aio_head, aio_siblings) {
486 if (aioreq->aiocb == acb) {
487 return false;
491 return true;
494 static void sd_aio_cancel(BlockAIOCB *blockacb)
496 SheepdogAIOCB *acb = (SheepdogAIOCB *)blockacb;
497 BDRVSheepdogState *s = acb->common.bs->opaque;
498 AIOReq *aioreq, *next;
500 if (sd_acb_cancelable(acb)) {
501 /* Remove outstanding requests from pending and failed queues. */
502 QLIST_FOREACH_SAFE(aioreq, &s->pending_aio_head, aio_siblings,
503 next) {
504 if (aioreq->aiocb == acb) {
505 free_aio_req(s, aioreq);
508 QLIST_FOREACH_SAFE(aioreq, &s->failed_aio_head, aio_siblings,
509 next) {
510 if (aioreq->aiocb == acb) {
511 free_aio_req(s, aioreq);
515 assert(acb->nr_pending == 0);
516 if (acb->common.cb) {
517 acb->common.cb(acb->common.opaque, -ECANCELED);
519 sd_finish_aiocb(acb);
523 static const AIOCBInfo sd_aiocb_info = {
524 .aiocb_size = sizeof(SheepdogAIOCB),
525 .cancel_async = sd_aio_cancel,
528 static SheepdogAIOCB *sd_aio_setup(BlockDriverState *bs, QEMUIOVector *qiov,
529 int64_t sector_num, int nb_sectors)
531 SheepdogAIOCB *acb;
533 acb = qemu_aio_get(&sd_aiocb_info, bs, NULL, NULL);
535 acb->qiov = qiov;
537 acb->sector_num = sector_num;
538 acb->nb_sectors = nb_sectors;
540 acb->aio_done_func = NULL;
541 acb->cancelable = true;
542 acb->coroutine = qemu_coroutine_self();
543 acb->ret = 0;
544 acb->nr_pending = 0;
545 return acb;
548 /* Return -EIO in case of error, file descriptor on success */
549 static int connect_to_sdog(BDRVSheepdogState *s, Error **errp)
551 int fd;
553 if (s->is_unix) {
554 fd = unix_connect(s->host_spec, errp);
555 } else {
556 fd = inet_connect(s->host_spec, errp);
558 if (fd >= 0) {
559 int ret = socket_set_nodelay(fd);
560 if (ret < 0) {
561 error_report("%s", strerror(errno));
566 if (fd >= 0) {
567 qemu_set_nonblock(fd);
568 } else {
569 fd = -EIO;
572 return fd;
575 /* Return 0 on success and -errno in case of error */
576 static coroutine_fn int send_co_req(int sockfd, SheepdogReq *hdr, void *data,
577 unsigned int *wlen)
579 int ret;
581 ret = qemu_co_send(sockfd, hdr, sizeof(*hdr));
582 if (ret != sizeof(*hdr)) {
583 error_report("failed to send a req, %s", strerror(errno));
584 ret = -socket_error();
585 return ret;
588 ret = qemu_co_send(sockfd, data, *wlen);
589 if (ret != *wlen) {
590 ret = -socket_error();
591 error_report("failed to send a req, %s", strerror(errno));
594 return ret;
597 static void restart_co_req(void *opaque)
599 Coroutine *co = opaque;
601 qemu_coroutine_enter(co, NULL);
604 typedef struct SheepdogReqCo {
605 int sockfd;
606 AioContext *aio_context;
607 SheepdogReq *hdr;
608 void *data;
609 unsigned int *wlen;
610 unsigned int *rlen;
611 int ret;
612 bool finished;
613 } SheepdogReqCo;
615 static coroutine_fn void do_co_req(void *opaque)
617 int ret;
618 Coroutine *co;
619 SheepdogReqCo *srco = opaque;
620 int sockfd = srco->sockfd;
621 SheepdogReq *hdr = srco->hdr;
622 void *data = srco->data;
623 unsigned int *wlen = srco->wlen;
624 unsigned int *rlen = srco->rlen;
626 co = qemu_coroutine_self();
627 aio_set_fd_handler(srco->aio_context, sockfd, NULL, restart_co_req, co);
629 ret = send_co_req(sockfd, hdr, data, wlen);
630 if (ret < 0) {
631 goto out;
634 aio_set_fd_handler(srco->aio_context, sockfd, restart_co_req, NULL, co);
636 ret = qemu_co_recv(sockfd, hdr, sizeof(*hdr));
637 if (ret != sizeof(*hdr)) {
638 error_report("failed to get a rsp, %s", strerror(errno));
639 ret = -errno;
640 goto out;
643 if (*rlen > hdr->data_length) {
644 *rlen = hdr->data_length;
647 if (*rlen) {
648 ret = qemu_co_recv(sockfd, data, *rlen);
649 if (ret != *rlen) {
650 error_report("failed to get the data, %s", strerror(errno));
651 ret = -errno;
652 goto out;
655 ret = 0;
656 out:
657 /* there is at most one request for this sockfd, so it is safe to
658 * set each handler to NULL. */
659 aio_set_fd_handler(srco->aio_context, sockfd, NULL, NULL, NULL);
661 srco->ret = ret;
662 srco->finished = true;
666 * Send the request to the sheep in a synchronous manner.
668 * Return 0 on success, -errno in case of error.
670 static int do_req(int sockfd, AioContext *aio_context, SheepdogReq *hdr,
671 void *data, unsigned int *wlen, unsigned int *rlen)
673 Coroutine *co;
674 SheepdogReqCo srco = {
675 .sockfd = sockfd,
676 .aio_context = aio_context,
677 .hdr = hdr,
678 .data = data,
679 .wlen = wlen,
680 .rlen = rlen,
681 .ret = 0,
682 .finished = false,
685 if (qemu_in_coroutine()) {
686 do_co_req(&srco);
687 } else {
688 co = qemu_coroutine_create(do_co_req);
689 qemu_coroutine_enter(co, &srco);
690 while (!srco.finished) {
691 aio_poll(aio_context, true);
695 return srco.ret;
698 static void coroutine_fn add_aio_request(BDRVSheepdogState *s, AIOReq *aio_req,
699 struct iovec *iov, int niov,
700 enum AIOCBState aiocb_type);
701 static void coroutine_fn resend_aioreq(BDRVSheepdogState *s, AIOReq *aio_req);
702 static int reload_inode(BDRVSheepdogState *s, uint32_t snapid, const char *tag);
703 static int get_sheep_fd(BDRVSheepdogState *s, Error **errp);
704 static void co_write_request(void *opaque);
706 static AIOReq *find_pending_req(BDRVSheepdogState *s, uint64_t oid)
708 AIOReq *aio_req;
710 QLIST_FOREACH(aio_req, &s->pending_aio_head, aio_siblings) {
711 if (aio_req->oid == oid) {
712 return aio_req;
716 return NULL;
720 * This function searchs pending requests to the object `oid', and
721 * sends them.
723 static void coroutine_fn send_pending_req(BDRVSheepdogState *s, uint64_t oid)
725 AIOReq *aio_req;
726 SheepdogAIOCB *acb;
728 while ((aio_req = find_pending_req(s, oid)) != NULL) {
729 acb = aio_req->aiocb;
730 /* move aio_req from pending list to inflight one */
731 QLIST_REMOVE(aio_req, aio_siblings);
732 QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
733 add_aio_request(s, aio_req, acb->qiov->iov, acb->qiov->niov,
734 acb->aiocb_type);
738 static coroutine_fn void reconnect_to_sdog(void *opaque)
740 BDRVSheepdogState *s = opaque;
741 AIOReq *aio_req, *next;
743 aio_set_fd_handler(s->aio_context, s->fd, NULL, NULL, NULL);
744 close(s->fd);
745 s->fd = -1;
747 /* Wait for outstanding write requests to be completed. */
748 while (s->co_send != NULL) {
749 co_write_request(opaque);
752 /* Try to reconnect the sheepdog server every one second. */
753 while (s->fd < 0) {
754 Error *local_err = NULL;
755 s->fd = get_sheep_fd(s, &local_err);
756 if (s->fd < 0) {
757 DPRINTF("Wait for connection to be established\n");
758 error_report_err(local_err);
759 co_aio_sleep_ns(bdrv_get_aio_context(s->bs), QEMU_CLOCK_REALTIME,
760 1000000000ULL);
765 * Now we have to resend all the request in the inflight queue. However,
766 * resend_aioreq() can yield and newly created requests can be added to the
767 * inflight queue before the coroutine is resumed. To avoid mixing them, we
768 * have to move all the inflight requests to the failed queue before
769 * resend_aioreq() is called.
771 QLIST_FOREACH_SAFE(aio_req, &s->inflight_aio_head, aio_siblings, next) {
772 QLIST_REMOVE(aio_req, aio_siblings);
773 QLIST_INSERT_HEAD(&s->failed_aio_head, aio_req, aio_siblings);
776 /* Resend all the failed aio requests. */
777 while (!QLIST_EMPTY(&s->failed_aio_head)) {
778 aio_req = QLIST_FIRST(&s->failed_aio_head);
779 QLIST_REMOVE(aio_req, aio_siblings);
780 QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
781 resend_aioreq(s, aio_req);
786 * Receive responses of the I/O requests.
788 * This function is registered as a fd handler, and called from the
789 * main loop when s->fd is ready for reading responses.
791 static void coroutine_fn aio_read_response(void *opaque)
793 SheepdogObjRsp rsp;
794 BDRVSheepdogState *s = opaque;
795 int fd = s->fd;
796 int ret;
797 AIOReq *aio_req = NULL;
798 SheepdogAIOCB *acb;
799 uint64_t idx;
801 /* read a header */
802 ret = qemu_co_recv(fd, &rsp, sizeof(rsp));
803 if (ret != sizeof(rsp)) {
804 error_report("failed to get the header, %s", strerror(errno));
805 goto err;
808 /* find the right aio_req from the inflight aio list */
809 QLIST_FOREACH(aio_req, &s->inflight_aio_head, aio_siblings) {
810 if (aio_req->id == rsp.id) {
811 break;
814 if (!aio_req) {
815 error_report("cannot find aio_req %x", rsp.id);
816 goto err;
819 acb = aio_req->aiocb;
821 switch (acb->aiocb_type) {
822 case AIOCB_WRITE_UDATA:
823 /* this coroutine context is no longer suitable for co_recv
824 * because we may send data to update vdi objects */
825 s->co_recv = NULL;
826 if (!is_data_obj(aio_req->oid)) {
827 break;
829 idx = data_oid_to_idx(aio_req->oid);
831 if (aio_req->create) {
833 * If the object is newly created one, we need to update
834 * the vdi object (metadata object). min_dirty_data_idx
835 * and max_dirty_data_idx are changed to include updated
836 * index between them.
838 if (rsp.result == SD_RES_SUCCESS) {
839 s->inode.data_vdi_id[idx] = s->inode.vdi_id;
840 s->max_dirty_data_idx = MAX(idx, s->max_dirty_data_idx);
841 s->min_dirty_data_idx = MIN(idx, s->min_dirty_data_idx);
844 * Some requests may be blocked because simultaneous
845 * create requests are not allowed, so we search the
846 * pending requests here.
848 send_pending_req(s, aio_req->oid);
850 break;
851 case AIOCB_READ_UDATA:
852 ret = qemu_co_recvv(fd, acb->qiov->iov, acb->qiov->niov,
853 aio_req->iov_offset, rsp.data_length);
854 if (ret != rsp.data_length) {
855 error_report("failed to get the data, %s", strerror(errno));
856 goto err;
858 break;
859 case AIOCB_FLUSH_CACHE:
860 if (rsp.result == SD_RES_INVALID_PARMS) {
861 DPRINTF("disable cache since the server doesn't support it\n");
862 s->cache_flags = SD_FLAG_CMD_DIRECT;
863 rsp.result = SD_RES_SUCCESS;
865 break;
866 case AIOCB_DISCARD_OBJ:
867 switch (rsp.result) {
868 case SD_RES_INVALID_PARMS:
869 error_report("sheep(%s) doesn't support discard command",
870 s->host_spec);
871 rsp.result = SD_RES_SUCCESS;
872 s->discard_supported = false;
873 break;
874 case SD_RES_SUCCESS:
875 idx = data_oid_to_idx(aio_req->oid);
876 s->inode.data_vdi_id[idx] = 0;
877 break;
878 default:
879 break;
883 switch (rsp.result) {
884 case SD_RES_SUCCESS:
885 break;
886 case SD_RES_READONLY:
887 if (s->inode.vdi_id == oid_to_vid(aio_req->oid)) {
888 ret = reload_inode(s, 0, "");
889 if (ret < 0) {
890 goto err;
893 if (is_data_obj(aio_req->oid)) {
894 aio_req->oid = vid_to_data_oid(s->inode.vdi_id,
895 data_oid_to_idx(aio_req->oid));
896 } else {
897 aio_req->oid = vid_to_vdi_oid(s->inode.vdi_id);
899 resend_aioreq(s, aio_req);
900 goto out;
901 default:
902 acb->ret = -EIO;
903 error_report("%s", sd_strerror(rsp.result));
904 break;
907 free_aio_req(s, aio_req);
908 if (!acb->nr_pending) {
910 * We've finished all requests which belong to the AIOCB, so
911 * we can switch back to sd_co_readv/writev now.
913 acb->aio_done_func(acb);
915 out:
916 s->co_recv = NULL;
917 return;
918 err:
919 s->co_recv = NULL;
920 reconnect_to_sdog(opaque);
923 static void co_read_response(void *opaque)
925 BDRVSheepdogState *s = opaque;
927 if (!s->co_recv) {
928 s->co_recv = qemu_coroutine_create(aio_read_response);
931 qemu_coroutine_enter(s->co_recv, opaque);
934 static void co_write_request(void *opaque)
936 BDRVSheepdogState *s = opaque;
938 qemu_coroutine_enter(s->co_send, NULL);
942 * Return a socket descriptor to read/write objects.
944 * We cannot use this descriptor for other operations because
945 * the block driver may be on waiting response from the server.
947 static int get_sheep_fd(BDRVSheepdogState *s, Error **errp)
949 int fd;
951 fd = connect_to_sdog(s, errp);
952 if (fd < 0) {
953 return fd;
956 aio_set_fd_handler(s->aio_context, fd, co_read_response, NULL, s);
957 return fd;
960 static int sd_parse_uri(BDRVSheepdogState *s, const char *filename,
961 char *vdi, uint32_t *snapid, char *tag)
963 URI *uri;
964 QueryParams *qp = NULL;
965 int ret = 0;
967 uri = uri_parse(filename);
968 if (!uri) {
969 return -EINVAL;
972 /* transport */
973 if (!strcmp(uri->scheme, "sheepdog")) {
974 s->is_unix = false;
975 } else if (!strcmp(uri->scheme, "sheepdog+tcp")) {
976 s->is_unix = false;
977 } else if (!strcmp(uri->scheme, "sheepdog+unix")) {
978 s->is_unix = true;
979 } else {
980 ret = -EINVAL;
981 goto out;
984 if (uri->path == NULL || !strcmp(uri->path, "/")) {
985 ret = -EINVAL;
986 goto out;
988 pstrcpy(vdi, SD_MAX_VDI_LEN, uri->path + 1);
990 qp = query_params_parse(uri->query);
991 if (qp->n > 1 || (s->is_unix && !qp->n) || (!s->is_unix && qp->n)) {
992 ret = -EINVAL;
993 goto out;
996 if (s->is_unix) {
997 /* sheepdog+unix:///vdiname?socket=path */
998 if (uri->server || uri->port || strcmp(qp->p[0].name, "socket")) {
999 ret = -EINVAL;
1000 goto out;
1002 s->host_spec = g_strdup(qp->p[0].value);
1003 } else {
1004 /* sheepdog[+tcp]://[host:port]/vdiname */
1005 s->host_spec = g_strdup_printf("%s:%d", uri->server ?: SD_DEFAULT_ADDR,
1006 uri->port ?: SD_DEFAULT_PORT);
1009 /* snapshot tag */
1010 if (uri->fragment) {
1011 *snapid = strtoul(uri->fragment, NULL, 10);
1012 if (*snapid == 0) {
1013 pstrcpy(tag, SD_MAX_VDI_TAG_LEN, uri->fragment);
1015 } else {
1016 *snapid = CURRENT_VDI_ID; /* search current vdi */
1019 out:
1020 if (qp) {
1021 query_params_free(qp);
1023 uri_free(uri);
1024 return ret;
1028 * Parse a filename (old syntax)
1030 * filename must be one of the following formats:
1031 * 1. [vdiname]
1032 * 2. [vdiname]:[snapid]
1033 * 3. [vdiname]:[tag]
1034 * 4. [hostname]:[port]:[vdiname]
1035 * 5. [hostname]:[port]:[vdiname]:[snapid]
1036 * 6. [hostname]:[port]:[vdiname]:[tag]
1038 * You can boot from the snapshot images by specifying `snapid` or
1039 * `tag'.
1041 * You can run VMs outside the Sheepdog cluster by specifying
1042 * `hostname' and `port' (experimental).
1044 static int parse_vdiname(BDRVSheepdogState *s, const char *filename,
1045 char *vdi, uint32_t *snapid, char *tag)
1047 char *p, *q, *uri;
1048 const char *host_spec, *vdi_spec;
1049 int nr_sep, ret;
1051 strstart(filename, "sheepdog:", (const char **)&filename);
1052 p = q = g_strdup(filename);
1054 /* count the number of separators */
1055 nr_sep = 0;
1056 while (*p) {
1057 if (*p == ':') {
1058 nr_sep++;
1060 p++;
1062 p = q;
1064 /* use the first two tokens as host_spec. */
1065 if (nr_sep >= 2) {
1066 host_spec = p;
1067 p = strchr(p, ':');
1068 p++;
1069 p = strchr(p, ':');
1070 *p++ = '\0';
1071 } else {
1072 host_spec = "";
1075 vdi_spec = p;
1077 p = strchr(vdi_spec, ':');
1078 if (p) {
1079 *p++ = '#';
1082 uri = g_strdup_printf("sheepdog://%s/%s", host_spec, vdi_spec);
1084 ret = sd_parse_uri(s, uri, vdi, snapid, tag);
1086 g_free(q);
1087 g_free(uri);
1089 return ret;
1092 static int find_vdi_name(BDRVSheepdogState *s, const char *filename,
1093 uint32_t snapid, const char *tag, uint32_t *vid,
1094 bool lock, Error **errp)
1096 int ret, fd;
1097 SheepdogVdiReq hdr;
1098 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
1099 unsigned int wlen, rlen = 0;
1100 char buf[SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN];
1102 fd = connect_to_sdog(s, errp);
1103 if (fd < 0) {
1104 return fd;
1107 /* This pair of strncpy calls ensures that the buffer is zero-filled,
1108 * which is desirable since we'll soon be sending those bytes, and
1109 * don't want the send_req to read uninitialized data.
1111 strncpy(buf, filename, SD_MAX_VDI_LEN);
1112 strncpy(buf + SD_MAX_VDI_LEN, tag, SD_MAX_VDI_TAG_LEN);
1114 memset(&hdr, 0, sizeof(hdr));
1115 if (lock) {
1116 hdr.opcode = SD_OP_LOCK_VDI;
1117 hdr.type = LOCK_TYPE_NORMAL;
1118 } else {
1119 hdr.opcode = SD_OP_GET_VDI_INFO;
1121 wlen = SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN;
1122 hdr.proto_ver = SD_PROTO_VER;
1123 hdr.data_length = wlen;
1124 hdr.snapid = snapid;
1125 hdr.flags = SD_FLAG_CMD_WRITE;
1127 ret = do_req(fd, s->aio_context, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
1128 if (ret) {
1129 error_setg_errno(errp, -ret, "cannot get vdi info");
1130 goto out;
1133 if (rsp->result != SD_RES_SUCCESS) {
1134 error_setg(errp, "cannot get vdi info, %s, %s %" PRIu32 " %s",
1135 sd_strerror(rsp->result), filename, snapid, tag);
1136 if (rsp->result == SD_RES_NO_VDI) {
1137 ret = -ENOENT;
1138 } else if (rsp->result == SD_RES_VDI_LOCKED) {
1139 ret = -EBUSY;
1140 } else {
1141 ret = -EIO;
1143 goto out;
1145 *vid = rsp->vdi_id;
1147 ret = 0;
1148 out:
1149 closesocket(fd);
1150 return ret;
1153 static void coroutine_fn add_aio_request(BDRVSheepdogState *s, AIOReq *aio_req,
1154 struct iovec *iov, int niov,
1155 enum AIOCBState aiocb_type)
1157 int nr_copies = s->inode.nr_copies;
1158 SheepdogObjReq hdr;
1159 unsigned int wlen = 0;
1160 int ret;
1161 uint64_t oid = aio_req->oid;
1162 unsigned int datalen = aio_req->data_len;
1163 uint64_t offset = aio_req->offset;
1164 uint8_t flags = aio_req->flags;
1165 uint64_t old_oid = aio_req->base_oid;
1166 bool create = aio_req->create;
1168 if (!nr_copies) {
1169 error_report("bug");
1172 memset(&hdr, 0, sizeof(hdr));
1174 switch (aiocb_type) {
1175 case AIOCB_FLUSH_CACHE:
1176 hdr.opcode = SD_OP_FLUSH_VDI;
1177 break;
1178 case AIOCB_READ_UDATA:
1179 hdr.opcode = SD_OP_READ_OBJ;
1180 hdr.flags = flags;
1181 break;
1182 case AIOCB_WRITE_UDATA:
1183 if (create) {
1184 hdr.opcode = SD_OP_CREATE_AND_WRITE_OBJ;
1185 } else {
1186 hdr.opcode = SD_OP_WRITE_OBJ;
1188 wlen = datalen;
1189 hdr.flags = SD_FLAG_CMD_WRITE | flags;
1190 break;
1191 case AIOCB_DISCARD_OBJ:
1192 hdr.opcode = SD_OP_DISCARD_OBJ;
1193 break;
1196 if (s->cache_flags) {
1197 hdr.flags |= s->cache_flags;
1200 hdr.oid = oid;
1201 hdr.cow_oid = old_oid;
1202 hdr.copies = s->inode.nr_copies;
1204 hdr.data_length = datalen;
1205 hdr.offset = offset;
1207 hdr.id = aio_req->id;
1209 qemu_co_mutex_lock(&s->lock);
1210 s->co_send = qemu_coroutine_self();
1211 aio_set_fd_handler(s->aio_context, s->fd,
1212 co_read_response, co_write_request, s);
1213 socket_set_cork(s->fd, 1);
1215 /* send a header */
1216 ret = qemu_co_send(s->fd, &hdr, sizeof(hdr));
1217 if (ret != sizeof(hdr)) {
1218 error_report("failed to send a req, %s", strerror(errno));
1219 goto out;
1222 if (wlen) {
1223 ret = qemu_co_sendv(s->fd, iov, niov, aio_req->iov_offset, wlen);
1224 if (ret != wlen) {
1225 error_report("failed to send a data, %s", strerror(errno));
1228 out:
1229 socket_set_cork(s->fd, 0);
1230 aio_set_fd_handler(s->aio_context, s->fd, co_read_response, NULL, s);
1231 s->co_send = NULL;
1232 qemu_co_mutex_unlock(&s->lock);
1235 static int read_write_object(int fd, AioContext *aio_context, char *buf,
1236 uint64_t oid, uint8_t copies,
1237 unsigned int datalen, uint64_t offset,
1238 bool write, bool create, uint32_t cache_flags)
1240 SheepdogObjReq hdr;
1241 SheepdogObjRsp *rsp = (SheepdogObjRsp *)&hdr;
1242 unsigned int wlen, rlen;
1243 int ret;
1245 memset(&hdr, 0, sizeof(hdr));
1247 if (write) {
1248 wlen = datalen;
1249 rlen = 0;
1250 hdr.flags = SD_FLAG_CMD_WRITE;
1251 if (create) {
1252 hdr.opcode = SD_OP_CREATE_AND_WRITE_OBJ;
1253 } else {
1254 hdr.opcode = SD_OP_WRITE_OBJ;
1256 } else {
1257 wlen = 0;
1258 rlen = datalen;
1259 hdr.opcode = SD_OP_READ_OBJ;
1262 hdr.flags |= cache_flags;
1264 hdr.oid = oid;
1265 hdr.data_length = datalen;
1266 hdr.offset = offset;
1267 hdr.copies = copies;
1269 ret = do_req(fd, aio_context, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
1270 if (ret) {
1271 error_report("failed to send a request to the sheep");
1272 return ret;
1275 switch (rsp->result) {
1276 case SD_RES_SUCCESS:
1277 return 0;
1278 default:
1279 error_report("%s", sd_strerror(rsp->result));
1280 return -EIO;
1284 static int read_object(int fd, AioContext *aio_context, char *buf,
1285 uint64_t oid, uint8_t copies,
1286 unsigned int datalen, uint64_t offset,
1287 uint32_t cache_flags)
1289 return read_write_object(fd, aio_context, buf, oid, copies,
1290 datalen, offset, false,
1291 false, cache_flags);
1294 static int write_object(int fd, AioContext *aio_context, char *buf,
1295 uint64_t oid, uint8_t copies,
1296 unsigned int datalen, uint64_t offset, bool create,
1297 uint32_t cache_flags)
1299 return read_write_object(fd, aio_context, buf, oid, copies,
1300 datalen, offset, true,
1301 create, cache_flags);
1304 /* update inode with the latest state */
1305 static int reload_inode(BDRVSheepdogState *s, uint32_t snapid, const char *tag)
1307 Error *local_err = NULL;
1308 SheepdogInode *inode;
1309 int ret = 0, fd;
1310 uint32_t vid = 0;
1312 fd = connect_to_sdog(s, &local_err);
1313 if (fd < 0) {
1314 error_report_err(local_err);
1315 return -EIO;
1318 inode = g_malloc(SD_INODE_HEADER_SIZE);
1320 ret = find_vdi_name(s, s->name, snapid, tag, &vid, false, &local_err);
1321 if (ret) {
1322 error_report_err(local_err);
1323 goto out;
1326 ret = read_object(fd, s->aio_context, (char *)inode, vid_to_vdi_oid(vid),
1327 s->inode.nr_copies, SD_INODE_HEADER_SIZE, 0,
1328 s->cache_flags);
1329 if (ret < 0) {
1330 goto out;
1333 if (inode->vdi_id != s->inode.vdi_id) {
1334 memcpy(&s->inode, inode, SD_INODE_HEADER_SIZE);
1337 out:
1338 g_free(inode);
1339 closesocket(fd);
1341 return ret;
1344 /* Return true if the specified request is linked to the pending list. */
1345 static bool check_simultaneous_create(BDRVSheepdogState *s, AIOReq *aio_req)
1347 AIOReq *areq;
1348 QLIST_FOREACH(areq, &s->inflight_aio_head, aio_siblings) {
1349 if (areq != aio_req && areq->oid == aio_req->oid) {
1351 * Sheepdog cannot handle simultaneous create requests to the same
1352 * object, so we cannot send the request until the previous request
1353 * finishes.
1355 DPRINTF("simultaneous create to %" PRIx64 "\n", aio_req->oid);
1356 aio_req->flags = 0;
1357 aio_req->base_oid = 0;
1358 aio_req->create = false;
1359 QLIST_REMOVE(aio_req, aio_siblings);
1360 QLIST_INSERT_HEAD(&s->pending_aio_head, aio_req, aio_siblings);
1361 return true;
1365 return false;
1368 static void coroutine_fn resend_aioreq(BDRVSheepdogState *s, AIOReq *aio_req)
1370 SheepdogAIOCB *acb = aio_req->aiocb;
1372 aio_req->create = false;
1374 /* check whether this request becomes a CoW one */
1375 if (acb->aiocb_type == AIOCB_WRITE_UDATA && is_data_obj(aio_req->oid)) {
1376 int idx = data_oid_to_idx(aio_req->oid);
1378 if (is_data_obj_writable(&s->inode, idx)) {
1379 goto out;
1382 if (check_simultaneous_create(s, aio_req)) {
1383 return;
1386 if (s->inode.data_vdi_id[idx]) {
1387 aio_req->base_oid = vid_to_data_oid(s->inode.data_vdi_id[idx], idx);
1388 aio_req->flags |= SD_FLAG_CMD_COW;
1390 aio_req->create = true;
1392 out:
1393 if (is_data_obj(aio_req->oid)) {
1394 add_aio_request(s, aio_req, acb->qiov->iov, acb->qiov->niov,
1395 acb->aiocb_type);
1396 } else {
1397 struct iovec iov;
1398 iov.iov_base = &s->inode;
1399 iov.iov_len = sizeof(s->inode);
1400 add_aio_request(s, aio_req, &iov, 1, AIOCB_WRITE_UDATA);
1404 static void sd_detach_aio_context(BlockDriverState *bs)
1406 BDRVSheepdogState *s = bs->opaque;
1408 aio_set_fd_handler(s->aio_context, s->fd, NULL, NULL, NULL);
1411 static void sd_attach_aio_context(BlockDriverState *bs,
1412 AioContext *new_context)
1414 BDRVSheepdogState *s = bs->opaque;
1416 s->aio_context = new_context;
1417 aio_set_fd_handler(new_context, s->fd, co_read_response, NULL, s);
1420 /* TODO Convert to fine grained options */
1421 static QemuOptsList runtime_opts = {
1422 .name = "sheepdog",
1423 .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
1424 .desc = {
1426 .name = "filename",
1427 .type = QEMU_OPT_STRING,
1428 .help = "URL to the sheepdog image",
1430 { /* end of list */ }
1434 static int sd_open(BlockDriverState *bs, QDict *options, int flags,
1435 Error **errp)
1437 int ret, fd;
1438 uint32_t vid = 0;
1439 BDRVSheepdogState *s = bs->opaque;
1440 char vdi[SD_MAX_VDI_LEN], tag[SD_MAX_VDI_TAG_LEN];
1441 uint32_t snapid;
1442 char *buf = NULL;
1443 QemuOpts *opts;
1444 Error *local_err = NULL;
1445 const char *filename;
1447 s->bs = bs;
1448 s->aio_context = bdrv_get_aio_context(bs);
1450 opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
1451 qemu_opts_absorb_qdict(opts, options, &local_err);
1452 if (local_err) {
1453 error_propagate(errp, local_err);
1454 ret = -EINVAL;
1455 goto out;
1458 filename = qemu_opt_get(opts, "filename");
1460 QLIST_INIT(&s->inflight_aio_head);
1461 QLIST_INIT(&s->pending_aio_head);
1462 QLIST_INIT(&s->failed_aio_head);
1463 s->fd = -1;
1465 memset(vdi, 0, sizeof(vdi));
1466 memset(tag, 0, sizeof(tag));
1468 if (strstr(filename, "://")) {
1469 ret = sd_parse_uri(s, filename, vdi, &snapid, tag);
1470 } else {
1471 ret = parse_vdiname(s, filename, vdi, &snapid, tag);
1473 if (ret < 0) {
1474 error_setg(errp, "Can't parse filename");
1475 goto out;
1477 s->fd = get_sheep_fd(s, errp);
1478 if (s->fd < 0) {
1479 ret = s->fd;
1480 goto out;
1483 ret = find_vdi_name(s, vdi, snapid, tag, &vid, true, errp);
1484 if (ret) {
1485 goto out;
1489 * QEMU block layer emulates writethrough cache as 'writeback + flush', so
1490 * we always set SD_FLAG_CMD_CACHE (writeback cache) as default.
1492 s->cache_flags = SD_FLAG_CMD_CACHE;
1493 if (flags & BDRV_O_NOCACHE) {
1494 s->cache_flags = SD_FLAG_CMD_DIRECT;
1496 s->discard_supported = true;
1498 if (snapid || tag[0] != '\0') {
1499 DPRINTF("%" PRIx32 " snapshot inode was open.\n", vid);
1500 s->is_snapshot = true;
1503 fd = connect_to_sdog(s, errp);
1504 if (fd < 0) {
1505 ret = fd;
1506 goto out;
1509 buf = g_malloc(SD_INODE_SIZE);
1510 ret = read_object(fd, s->aio_context, buf, vid_to_vdi_oid(vid),
1511 0, SD_INODE_SIZE, 0, s->cache_flags);
1513 closesocket(fd);
1515 if (ret) {
1516 error_setg(errp, "Can't read snapshot inode");
1517 goto out;
1520 memcpy(&s->inode, buf, sizeof(s->inode));
1521 s->min_dirty_data_idx = UINT32_MAX;
1522 s->max_dirty_data_idx = 0;
1524 bs->total_sectors = s->inode.vdi_size / BDRV_SECTOR_SIZE;
1525 pstrcpy(s->name, sizeof(s->name), vdi);
1526 qemu_co_mutex_init(&s->lock);
1527 qemu_opts_del(opts);
1528 g_free(buf);
1529 return 0;
1530 out:
1531 aio_set_fd_handler(bdrv_get_aio_context(bs), s->fd, NULL, NULL, NULL);
1532 if (s->fd >= 0) {
1533 closesocket(s->fd);
1535 qemu_opts_del(opts);
1536 g_free(buf);
1537 return ret;
1540 static int do_sd_create(BDRVSheepdogState *s, uint32_t *vdi_id, int snapshot,
1541 Error **errp)
1543 SheepdogVdiReq hdr;
1544 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
1545 int fd, ret;
1546 unsigned int wlen, rlen = 0;
1547 char buf[SD_MAX_VDI_LEN];
1549 fd = connect_to_sdog(s, errp);
1550 if (fd < 0) {
1551 return fd;
1554 /* FIXME: would it be better to fail (e.g., return -EIO) when filename
1555 * does not fit in buf? For now, just truncate and avoid buffer overrun.
1557 memset(buf, 0, sizeof(buf));
1558 pstrcpy(buf, sizeof(buf), s->name);
1560 memset(&hdr, 0, sizeof(hdr));
1561 hdr.opcode = SD_OP_NEW_VDI;
1562 hdr.base_vdi_id = s->inode.vdi_id;
1564 wlen = SD_MAX_VDI_LEN;
1566 hdr.flags = SD_FLAG_CMD_WRITE;
1567 hdr.snapid = snapshot;
1569 hdr.data_length = wlen;
1570 hdr.vdi_size = s->inode.vdi_size;
1571 hdr.copy_policy = s->inode.copy_policy;
1572 hdr.copies = s->inode.nr_copies;
1573 hdr.block_size_shift = s->inode.block_size_shift;
1575 ret = do_req(fd, s->aio_context, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
1577 closesocket(fd);
1579 if (ret) {
1580 error_setg_errno(errp, -ret, "create failed");
1581 return ret;
1584 if (rsp->result != SD_RES_SUCCESS) {
1585 error_setg(errp, "%s, %s", sd_strerror(rsp->result), s->inode.name);
1586 return -EIO;
1589 if (vdi_id) {
1590 *vdi_id = rsp->vdi_id;
1593 return 0;
1596 static int sd_prealloc(const char *filename, Error **errp)
1598 BlockDriverState *bs = NULL;
1599 BDRVSheepdogState *base = NULL;
1600 unsigned long buf_size;
1601 uint32_t idx, max_idx;
1602 uint32_t object_size;
1603 int64_t vdi_size;
1604 void *buf = NULL;
1605 int ret;
1607 ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,
1608 NULL, errp);
1609 if (ret < 0) {
1610 goto out_with_err_set;
1613 vdi_size = bdrv_getlength(bs);
1614 if (vdi_size < 0) {
1615 ret = vdi_size;
1616 goto out;
1619 base = bs->opaque;
1620 object_size = (UINT32_C(1) << base->inode.block_size_shift);
1621 buf_size = MIN(object_size, SD_DATA_OBJ_SIZE);
1622 buf = g_malloc0(buf_size);
1624 max_idx = DIV_ROUND_UP(vdi_size, buf_size);
1626 for (idx = 0; idx < max_idx; idx++) {
1628 * The created image can be a cloned image, so we need to read
1629 * a data from the source image.
1631 ret = bdrv_pread(bs, idx * buf_size, buf, buf_size);
1632 if (ret < 0) {
1633 goto out;
1635 ret = bdrv_pwrite(bs, idx * buf_size, buf, buf_size);
1636 if (ret < 0) {
1637 goto out;
1641 out:
1642 if (ret < 0) {
1643 error_setg_errno(errp, -ret, "Can't pre-allocate");
1645 out_with_err_set:
1646 if (bs) {
1647 bdrv_unref(bs);
1649 g_free(buf);
1651 return ret;
1655 * Sheepdog support two kinds of redundancy, full replication and erasure
1656 * coding.
1658 * # create a fully replicated vdi with x copies
1659 * -o redundancy=x (1 <= x <= SD_MAX_COPIES)
1661 * # create a erasure coded vdi with x data strips and y parity strips
1662 * -o redundancy=x:y (x must be one of {2,4,8,16} and 1 <= y < SD_EC_MAX_STRIP)
1664 static int parse_redundancy(BDRVSheepdogState *s, const char *opt)
1666 struct SheepdogInode *inode = &s->inode;
1667 const char *n1, *n2;
1668 long copy, parity;
1669 char p[10];
1671 pstrcpy(p, sizeof(p), opt);
1672 n1 = strtok(p, ":");
1673 n2 = strtok(NULL, ":");
1675 if (!n1) {
1676 return -EINVAL;
1679 copy = strtol(n1, NULL, 10);
1680 if (copy > SD_MAX_COPIES || copy < 1) {
1681 return -EINVAL;
1683 if (!n2) {
1684 inode->copy_policy = 0;
1685 inode->nr_copies = copy;
1686 return 0;
1689 if (copy != 2 && copy != 4 && copy != 8 && copy != 16) {
1690 return -EINVAL;
1693 parity = strtol(n2, NULL, 10);
1694 if (parity >= SD_EC_MAX_STRIP || parity < 1) {
1695 return -EINVAL;
1699 * 4 bits for parity and 4 bits for data.
1700 * We have to compress upper data bits because it can't represent 16
1702 inode->copy_policy = ((copy / 2) << 4) + parity;
1703 inode->nr_copies = copy + parity;
1705 return 0;
1708 static int parse_block_size_shift(BDRVSheepdogState *s, QemuOpts *opt)
1710 struct SheepdogInode *inode = &s->inode;
1711 uint64_t object_size;
1712 int obj_order;
1714 object_size = qemu_opt_get_size_del(opt, BLOCK_OPT_OBJECT_SIZE, 0);
1715 if (object_size) {
1716 if ((object_size - 1) & object_size) { /* not a power of 2? */
1717 return -EINVAL;
1719 obj_order = ctz32(object_size);
1720 if (obj_order < 20 || obj_order > 31) {
1721 return -EINVAL;
1723 inode->block_size_shift = (uint8_t)obj_order;
1726 return 0;
1729 static int sd_create(const char *filename, QemuOpts *opts,
1730 Error **errp)
1732 int ret = 0;
1733 uint32_t vid = 0;
1734 char *backing_file = NULL;
1735 char *buf = NULL;
1736 BDRVSheepdogState *s;
1737 char tag[SD_MAX_VDI_TAG_LEN];
1738 uint32_t snapid;
1739 uint64_t max_vdi_size;
1740 bool prealloc = false;
1742 s = g_new0(BDRVSheepdogState, 1);
1744 memset(tag, 0, sizeof(tag));
1745 if (strstr(filename, "://")) {
1746 ret = sd_parse_uri(s, filename, s->name, &snapid, tag);
1747 } else {
1748 ret = parse_vdiname(s, filename, s->name, &snapid, tag);
1750 if (ret < 0) {
1751 error_setg(errp, "Can't parse filename");
1752 goto out;
1755 s->inode.vdi_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
1756 BDRV_SECTOR_SIZE);
1757 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
1758 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
1759 if (!buf || !strcmp(buf, "off")) {
1760 prealloc = false;
1761 } else if (!strcmp(buf, "full")) {
1762 prealloc = true;
1763 } else {
1764 error_setg(errp, "Invalid preallocation mode: '%s'", buf);
1765 ret = -EINVAL;
1766 goto out;
1769 g_free(buf);
1770 buf = qemu_opt_get_del(opts, BLOCK_OPT_REDUNDANCY);
1771 if (buf) {
1772 ret = parse_redundancy(s, buf);
1773 if (ret < 0) {
1774 error_setg(errp, "Invalid redundancy mode: '%s'", buf);
1775 goto out;
1778 ret = parse_block_size_shift(s, opts);
1779 if (ret < 0) {
1780 error_setg(errp, "Invalid object_size."
1781 " obect_size needs to be power of 2"
1782 " and be limited from 2^20 to 2^31");
1783 goto out;
1786 if (backing_file) {
1787 BlockDriverState *bs;
1788 BDRVSheepdogState *base;
1789 BlockDriver *drv;
1791 /* Currently, only Sheepdog backing image is supported. */
1792 drv = bdrv_find_protocol(backing_file, true, NULL);
1793 if (!drv || strcmp(drv->protocol_name, "sheepdog") != 0) {
1794 error_setg(errp, "backing_file must be a sheepdog image");
1795 ret = -EINVAL;
1796 goto out;
1799 bs = NULL;
1800 ret = bdrv_open(&bs, backing_file, NULL, NULL, BDRV_O_PROTOCOL, NULL,
1801 errp);
1802 if (ret < 0) {
1803 goto out;
1806 base = bs->opaque;
1808 if (!is_snapshot(&base->inode)) {
1809 error_setg(errp, "cannot clone from a non snapshot vdi");
1810 bdrv_unref(bs);
1811 ret = -EINVAL;
1812 goto out;
1814 s->inode.vdi_id = base->inode.vdi_id;
1815 bdrv_unref(bs);
1818 s->aio_context = qemu_get_aio_context();
1820 /* if block_size_shift is not specified, get cluster default value */
1821 if (s->inode.block_size_shift == 0) {
1822 SheepdogVdiReq hdr;
1823 SheepdogClusterRsp *rsp = (SheepdogClusterRsp *)&hdr;
1824 Error *local_err = NULL;
1825 int fd;
1826 unsigned int wlen = 0, rlen = 0;
1828 fd = connect_to_sdog(s, &local_err);
1829 if (fd < 0) {
1830 error_report("%s", error_get_pretty(local_err));
1831 error_free(local_err);
1832 ret = -EIO;
1833 goto out;
1836 memset(&hdr, 0, sizeof(hdr));
1837 hdr.opcode = SD_OP_GET_CLUSTER_DEFAULT;
1838 hdr.proto_ver = SD_PROTO_VER;
1840 ret = do_req(fd, s->aio_context, (SheepdogReq *)&hdr,
1841 NULL, &wlen, &rlen);
1842 closesocket(fd);
1843 if (ret) {
1844 error_setg_errno(errp, -ret, "failed to get cluster default");
1845 goto out;
1847 if (rsp->result == SD_RES_SUCCESS) {
1848 s->inode.block_size_shift = rsp->block_size_shift;
1849 } else {
1850 s->inode.block_size_shift = SD_DEFAULT_BLOCK_SIZE_SHIFT;
1854 max_vdi_size = (UINT64_C(1) << s->inode.block_size_shift) * MAX_DATA_OBJS;
1856 if (s->inode.vdi_size > max_vdi_size) {
1857 error_setg(errp, "An image is too large."
1858 " The maximum image size is %"PRIu64 "GB",
1859 max_vdi_size / 1024 / 1024 / 1024);
1860 ret = -EINVAL;
1861 goto out;
1864 ret = do_sd_create(s, &vid, 0, errp);
1865 if (ret) {
1866 goto out;
1869 if (prealloc) {
1870 ret = sd_prealloc(filename, errp);
1872 out:
1873 g_free(backing_file);
1874 g_free(buf);
1875 g_free(s);
1876 return ret;
1879 static void sd_close(BlockDriverState *bs)
1881 Error *local_err = NULL;
1882 BDRVSheepdogState *s = bs->opaque;
1883 SheepdogVdiReq hdr;
1884 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
1885 unsigned int wlen, rlen = 0;
1886 int fd, ret;
1888 DPRINTF("%s\n", s->name);
1890 fd = connect_to_sdog(s, &local_err);
1891 if (fd < 0) {
1892 error_report_err(local_err);
1893 return;
1896 memset(&hdr, 0, sizeof(hdr));
1898 hdr.opcode = SD_OP_RELEASE_VDI;
1899 hdr.type = LOCK_TYPE_NORMAL;
1900 hdr.base_vdi_id = s->inode.vdi_id;
1901 wlen = strlen(s->name) + 1;
1902 hdr.data_length = wlen;
1903 hdr.flags = SD_FLAG_CMD_WRITE;
1905 ret = do_req(fd, s->aio_context, (SheepdogReq *)&hdr,
1906 s->name, &wlen, &rlen);
1908 closesocket(fd);
1910 if (!ret && rsp->result != SD_RES_SUCCESS &&
1911 rsp->result != SD_RES_VDI_NOT_LOCKED) {
1912 error_report("%s, %s", sd_strerror(rsp->result), s->name);
1915 aio_set_fd_handler(bdrv_get_aio_context(bs), s->fd, NULL, NULL, NULL);
1916 closesocket(s->fd);
1917 g_free(s->host_spec);
1920 static int64_t sd_getlength(BlockDriverState *bs)
1922 BDRVSheepdogState *s = bs->opaque;
1924 return s->inode.vdi_size;
1927 static int sd_truncate(BlockDriverState *bs, int64_t offset)
1929 Error *local_err = NULL;
1930 BDRVSheepdogState *s = bs->opaque;
1931 int ret, fd;
1932 unsigned int datalen;
1933 uint64_t max_vdi_size;
1935 max_vdi_size = (UINT64_C(1) << s->inode.block_size_shift) * MAX_DATA_OBJS;
1936 if (offset < s->inode.vdi_size) {
1937 error_report("shrinking is not supported");
1938 return -EINVAL;
1939 } else if (offset > max_vdi_size) {
1940 error_report("too big image size");
1941 return -EINVAL;
1944 fd = connect_to_sdog(s, &local_err);
1945 if (fd < 0) {
1946 error_report_err(local_err);
1947 return fd;
1950 /* we don't need to update entire object */
1951 datalen = SD_INODE_SIZE - sizeof(s->inode.data_vdi_id);
1952 s->inode.vdi_size = offset;
1953 ret = write_object(fd, s->aio_context, (char *)&s->inode,
1954 vid_to_vdi_oid(s->inode.vdi_id), s->inode.nr_copies,
1955 datalen, 0, false, s->cache_flags);
1956 close(fd);
1958 if (ret < 0) {
1959 error_report("failed to update an inode.");
1962 return ret;
1966 * This function is called after writing data objects. If we need to
1967 * update metadata, this sends a write request to the vdi object.
1968 * Otherwise, this switches back to sd_co_readv/writev.
1970 static void coroutine_fn sd_write_done(SheepdogAIOCB *acb)
1972 BDRVSheepdogState *s = acb->common.bs->opaque;
1973 struct iovec iov;
1974 AIOReq *aio_req;
1975 uint32_t offset, data_len, mn, mx;
1977 mn = s->min_dirty_data_idx;
1978 mx = s->max_dirty_data_idx;
1979 if (mn <= mx) {
1980 /* we need to update the vdi object. */
1981 offset = sizeof(s->inode) - sizeof(s->inode.data_vdi_id) +
1982 mn * sizeof(s->inode.data_vdi_id[0]);
1983 data_len = (mx - mn + 1) * sizeof(s->inode.data_vdi_id[0]);
1985 s->min_dirty_data_idx = UINT32_MAX;
1986 s->max_dirty_data_idx = 0;
1988 iov.iov_base = &s->inode;
1989 iov.iov_len = sizeof(s->inode);
1990 aio_req = alloc_aio_req(s, acb, vid_to_vdi_oid(s->inode.vdi_id),
1991 data_len, offset, 0, false, 0, offset);
1992 QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
1993 add_aio_request(s, aio_req, &iov, 1, AIOCB_WRITE_UDATA);
1995 acb->aio_done_func = sd_finish_aiocb;
1996 acb->aiocb_type = AIOCB_WRITE_UDATA;
1997 return;
2000 sd_finish_aiocb(acb);
2003 /* Delete current working VDI on the snapshot chain */
2004 static bool sd_delete(BDRVSheepdogState *s)
2006 Error *local_err = NULL;
2007 unsigned int wlen = SD_MAX_VDI_LEN, rlen = 0;
2008 SheepdogVdiReq hdr = {
2009 .opcode = SD_OP_DEL_VDI,
2010 .base_vdi_id = s->inode.vdi_id,
2011 .data_length = wlen,
2012 .flags = SD_FLAG_CMD_WRITE,
2014 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
2015 int fd, ret;
2017 fd = connect_to_sdog(s, &local_err);
2018 if (fd < 0) {
2019 error_report_err(local_err);
2020 return false;
2023 ret = do_req(fd, s->aio_context, (SheepdogReq *)&hdr,
2024 s->name, &wlen, &rlen);
2025 closesocket(fd);
2026 if (ret) {
2027 return false;
2029 switch (rsp->result) {
2030 case SD_RES_NO_VDI:
2031 error_report("%s was already deleted", s->name);
2032 /* fall through */
2033 case SD_RES_SUCCESS:
2034 break;
2035 default:
2036 error_report("%s, %s", sd_strerror(rsp->result), s->name);
2037 return false;
2040 return true;
2044 * Create a writable VDI from a snapshot
2046 static int sd_create_branch(BDRVSheepdogState *s)
2048 Error *local_err = NULL;
2049 int ret, fd;
2050 uint32_t vid;
2051 char *buf;
2052 bool deleted;
2054 DPRINTF("%" PRIx32 " is snapshot.\n", s->inode.vdi_id);
2056 buf = g_malloc(SD_INODE_SIZE);
2059 * Even If deletion fails, we will just create extra snapshot based on
2060 * the working VDI which was supposed to be deleted. So no need to
2061 * false bail out.
2063 deleted = sd_delete(s);
2064 ret = do_sd_create(s, &vid, !deleted, &local_err);
2065 if (ret) {
2066 error_report_err(local_err);
2067 goto out;
2070 DPRINTF("%" PRIx32 " is created.\n", vid);
2072 fd = connect_to_sdog(s, &local_err);
2073 if (fd < 0) {
2074 error_report_err(local_err);
2075 ret = fd;
2076 goto out;
2079 ret = read_object(fd, s->aio_context, buf, vid_to_vdi_oid(vid),
2080 s->inode.nr_copies, SD_INODE_SIZE, 0, s->cache_flags);
2082 closesocket(fd);
2084 if (ret < 0) {
2085 goto out;
2088 memcpy(&s->inode, buf, sizeof(s->inode));
2090 s->is_snapshot = false;
2091 ret = 0;
2092 DPRINTF("%" PRIx32 " was newly created.\n", s->inode.vdi_id);
2094 out:
2095 g_free(buf);
2097 return ret;
2101 * Send I/O requests to the server.
2103 * This function sends requests to the server, links the requests to
2104 * the inflight_list in BDRVSheepdogState, and exits without
2105 * waiting the response. The responses are received in the
2106 * `aio_read_response' function which is called from the main loop as
2107 * a fd handler.
2109 * Returns 1 when we need to wait a response, 0 when there is no sent
2110 * request and -errno in error cases.
2112 static int coroutine_fn sd_co_rw_vector(void *p)
2114 SheepdogAIOCB *acb = p;
2115 int ret = 0;
2116 unsigned long len, done = 0, total = acb->nb_sectors * BDRV_SECTOR_SIZE;
2117 unsigned long idx;
2118 uint32_t object_size;
2119 uint64_t oid;
2120 uint64_t offset;
2121 BDRVSheepdogState *s = acb->common.bs->opaque;
2122 SheepdogInode *inode = &s->inode;
2123 AIOReq *aio_req;
2125 if (acb->aiocb_type == AIOCB_WRITE_UDATA && s->is_snapshot) {
2127 * In the case we open the snapshot VDI, Sheepdog creates the
2128 * writable VDI when we do a write operation first.
2130 ret = sd_create_branch(s);
2131 if (ret) {
2132 acb->ret = -EIO;
2133 goto out;
2137 object_size = (UINT32_C(1) << inode->block_size_shift);
2138 idx = acb->sector_num * BDRV_SECTOR_SIZE / object_size;
2139 offset = (acb->sector_num * BDRV_SECTOR_SIZE) % object_size;
2142 * Make sure we don't free the aiocb before we are done with all requests.
2143 * This additional reference is dropped at the end of this function.
2145 acb->nr_pending++;
2147 while (done != total) {
2148 uint8_t flags = 0;
2149 uint64_t old_oid = 0;
2150 bool create = false;
2152 oid = vid_to_data_oid(inode->data_vdi_id[idx], idx);
2154 len = MIN(total - done, object_size - offset);
2156 switch (acb->aiocb_type) {
2157 case AIOCB_READ_UDATA:
2158 if (!inode->data_vdi_id[idx]) {
2159 qemu_iovec_memset(acb->qiov, done, 0, len);
2160 goto done;
2162 break;
2163 case AIOCB_WRITE_UDATA:
2164 if (!inode->data_vdi_id[idx]) {
2165 create = true;
2166 } else if (!is_data_obj_writable(inode, idx)) {
2167 /* Copy-On-Write */
2168 create = true;
2169 old_oid = oid;
2170 flags = SD_FLAG_CMD_COW;
2172 break;
2173 case AIOCB_DISCARD_OBJ:
2175 * We discard the object only when the whole object is
2176 * 1) allocated 2) trimmed. Otherwise, simply skip it.
2178 if (len != object_size || inode->data_vdi_id[idx] == 0) {
2179 goto done;
2181 break;
2182 default:
2183 break;
2186 if (create) {
2187 DPRINTF("update ino (%" PRIu32 ") %" PRIu64 " %" PRIu64 " %ld\n",
2188 inode->vdi_id, oid,
2189 vid_to_data_oid(inode->data_vdi_id[idx], idx), idx);
2190 oid = vid_to_data_oid(inode->vdi_id, idx);
2191 DPRINTF("new oid %" PRIx64 "\n", oid);
2194 aio_req = alloc_aio_req(s, acb, oid, len, offset, flags, create,
2195 old_oid, done);
2196 QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
2198 if (create) {
2199 if (check_simultaneous_create(s, aio_req)) {
2200 goto done;
2204 add_aio_request(s, aio_req, acb->qiov->iov, acb->qiov->niov,
2205 acb->aiocb_type);
2206 done:
2207 offset = 0;
2208 idx++;
2209 done += len;
2211 out:
2212 if (!--acb->nr_pending) {
2213 return acb->ret;
2215 return 1;
2218 static coroutine_fn int sd_co_writev(BlockDriverState *bs, int64_t sector_num,
2219 int nb_sectors, QEMUIOVector *qiov)
2221 SheepdogAIOCB *acb;
2222 int ret;
2223 int64_t offset = (sector_num + nb_sectors) * BDRV_SECTOR_SIZE;
2224 BDRVSheepdogState *s = bs->opaque;
2226 if (offset > s->inode.vdi_size) {
2227 ret = sd_truncate(bs, offset);
2228 if (ret < 0) {
2229 return ret;
2233 acb = sd_aio_setup(bs, qiov, sector_num, nb_sectors);
2234 acb->aio_done_func = sd_write_done;
2235 acb->aiocb_type = AIOCB_WRITE_UDATA;
2237 ret = sd_co_rw_vector(acb);
2238 if (ret <= 0) {
2239 qemu_aio_unref(acb);
2240 return ret;
2243 qemu_coroutine_yield();
2245 return acb->ret;
2248 static coroutine_fn int sd_co_readv(BlockDriverState *bs, int64_t sector_num,
2249 int nb_sectors, QEMUIOVector *qiov)
2251 SheepdogAIOCB *acb;
2252 int ret;
2254 acb = sd_aio_setup(bs, qiov, sector_num, nb_sectors);
2255 acb->aiocb_type = AIOCB_READ_UDATA;
2256 acb->aio_done_func = sd_finish_aiocb;
2258 ret = sd_co_rw_vector(acb);
2259 if (ret <= 0) {
2260 qemu_aio_unref(acb);
2261 return ret;
2264 qemu_coroutine_yield();
2266 return acb->ret;
2269 static int coroutine_fn sd_co_flush_to_disk(BlockDriverState *bs)
2271 BDRVSheepdogState *s = bs->opaque;
2272 SheepdogAIOCB *acb;
2273 AIOReq *aio_req;
2275 if (s->cache_flags != SD_FLAG_CMD_CACHE) {
2276 return 0;
2279 acb = sd_aio_setup(bs, NULL, 0, 0);
2280 acb->aiocb_type = AIOCB_FLUSH_CACHE;
2281 acb->aio_done_func = sd_finish_aiocb;
2283 aio_req = alloc_aio_req(s, acb, vid_to_vdi_oid(s->inode.vdi_id),
2284 0, 0, 0, false, 0, 0);
2285 QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
2286 add_aio_request(s, aio_req, NULL, 0, acb->aiocb_type);
2288 qemu_coroutine_yield();
2289 return acb->ret;
2292 static int sd_snapshot_create(BlockDriverState *bs, QEMUSnapshotInfo *sn_info)
2294 Error *local_err = NULL;
2295 BDRVSheepdogState *s = bs->opaque;
2296 int ret, fd;
2297 uint32_t new_vid;
2298 SheepdogInode *inode;
2299 unsigned int datalen;
2301 DPRINTF("sn_info: name %s id_str %s s: name %s vm_state_size %" PRId64 " "
2302 "is_snapshot %d\n", sn_info->name, sn_info->id_str,
2303 s->name, sn_info->vm_state_size, s->is_snapshot);
2305 if (s->is_snapshot) {
2306 error_report("You can't create a snapshot of a snapshot VDI, "
2307 "%s (%" PRIu32 ").", s->name, s->inode.vdi_id);
2309 return -EINVAL;
2312 DPRINTF("%s %s\n", sn_info->name, sn_info->id_str);
2314 s->inode.vm_state_size = sn_info->vm_state_size;
2315 s->inode.vm_clock_nsec = sn_info->vm_clock_nsec;
2316 /* It appears that inode.tag does not require a NUL terminator,
2317 * which means this use of strncpy is ok.
2319 strncpy(s->inode.tag, sn_info->name, sizeof(s->inode.tag));
2320 /* we don't need to update entire object */
2321 datalen = SD_INODE_SIZE - sizeof(s->inode.data_vdi_id);
2322 inode = g_malloc(datalen);
2324 /* refresh inode. */
2325 fd = connect_to_sdog(s, &local_err);
2326 if (fd < 0) {
2327 error_report_err(local_err);
2328 ret = fd;
2329 goto cleanup;
2332 ret = write_object(fd, s->aio_context, (char *)&s->inode,
2333 vid_to_vdi_oid(s->inode.vdi_id), s->inode.nr_copies,
2334 datalen, 0, false, s->cache_flags);
2335 if (ret < 0) {
2336 error_report("failed to write snapshot's inode.");
2337 goto cleanup;
2340 ret = do_sd_create(s, &new_vid, 1, &local_err);
2341 if (ret < 0) {
2342 error_report("failed to create inode for snapshot: %s",
2343 error_get_pretty(local_err));
2344 error_free(local_err);
2345 goto cleanup;
2348 ret = read_object(fd, s->aio_context, (char *)inode,
2349 vid_to_vdi_oid(new_vid), s->inode.nr_copies, datalen, 0,
2350 s->cache_flags);
2352 if (ret < 0) {
2353 error_report("failed to read new inode info. %s", strerror(errno));
2354 goto cleanup;
2357 memcpy(&s->inode, inode, datalen);
2358 DPRINTF("s->inode: name %s snap_id %x oid %x\n",
2359 s->inode.name, s->inode.snap_id, s->inode.vdi_id);
2361 cleanup:
2362 g_free(inode);
2363 closesocket(fd);
2364 return ret;
2368 * We implement rollback(loadvm) operation to the specified snapshot by
2369 * 1) switch to the snapshot
2370 * 2) rely on sd_create_branch to delete working VDI and
2371 * 3) create a new working VDI based on the specified snapshot
2373 static int sd_snapshot_goto(BlockDriverState *bs, const char *snapshot_id)
2375 BDRVSheepdogState *s = bs->opaque;
2376 BDRVSheepdogState *old_s;
2377 char tag[SD_MAX_VDI_TAG_LEN];
2378 uint32_t snapid = 0;
2379 int ret = 0;
2381 old_s = g_new(BDRVSheepdogState, 1);
2383 memcpy(old_s, s, sizeof(BDRVSheepdogState));
2385 snapid = strtoul(snapshot_id, NULL, 10);
2386 if (snapid) {
2387 tag[0] = 0;
2388 } else {
2389 pstrcpy(tag, sizeof(tag), snapshot_id);
2392 ret = reload_inode(s, snapid, tag);
2393 if (ret) {
2394 goto out;
2397 ret = sd_create_branch(s);
2398 if (ret) {
2399 goto out;
2402 g_free(old_s);
2404 return 0;
2405 out:
2406 /* recover bdrv_sd_state */
2407 memcpy(s, old_s, sizeof(BDRVSheepdogState));
2408 g_free(old_s);
2410 error_report("failed to open. recover old bdrv_sd_state.");
2412 return ret;
2415 static int sd_snapshot_delete(BlockDriverState *bs,
2416 const char *snapshot_id,
2417 const char *name,
2418 Error **errp)
2420 /* FIXME: Delete specified snapshot id. */
2421 return 0;
2424 static int sd_snapshot_list(BlockDriverState *bs, QEMUSnapshotInfo **psn_tab)
2426 Error *local_err = NULL;
2427 BDRVSheepdogState *s = bs->opaque;
2428 SheepdogReq req;
2429 int fd, nr = 1024, ret, max = BITS_TO_LONGS(SD_NR_VDIS) * sizeof(long);
2430 QEMUSnapshotInfo *sn_tab = NULL;
2431 unsigned wlen, rlen;
2432 int found = 0;
2433 static SheepdogInode inode;
2434 unsigned long *vdi_inuse;
2435 unsigned int start_nr;
2436 uint64_t hval;
2437 uint32_t vid;
2439 vdi_inuse = g_malloc(max);
2441 fd = connect_to_sdog(s, &local_err);
2442 if (fd < 0) {
2443 error_report_err(local_err);
2444 ret = fd;
2445 goto out;
2448 rlen = max;
2449 wlen = 0;
2451 memset(&req, 0, sizeof(req));
2453 req.opcode = SD_OP_READ_VDIS;
2454 req.data_length = max;
2456 ret = do_req(fd, s->aio_context, (SheepdogReq *)&req,
2457 vdi_inuse, &wlen, &rlen);
2459 closesocket(fd);
2460 if (ret) {
2461 goto out;
2464 sn_tab = g_new0(QEMUSnapshotInfo, nr);
2466 /* calculate a vdi id with hash function */
2467 hval = fnv_64a_buf(s->name, strlen(s->name), FNV1A_64_INIT);
2468 start_nr = hval & (SD_NR_VDIS - 1);
2470 fd = connect_to_sdog(s, &local_err);
2471 if (fd < 0) {
2472 error_report_err(local_err);
2473 ret = fd;
2474 goto out;
2477 for (vid = start_nr; found < nr; vid = (vid + 1) % SD_NR_VDIS) {
2478 if (!test_bit(vid, vdi_inuse)) {
2479 break;
2482 /* we don't need to read entire object */
2483 ret = read_object(fd, s->aio_context, (char *)&inode,
2484 vid_to_vdi_oid(vid),
2485 0, SD_INODE_SIZE - sizeof(inode.data_vdi_id), 0,
2486 s->cache_flags);
2488 if (ret) {
2489 continue;
2492 if (!strcmp(inode.name, s->name) && is_snapshot(&inode)) {
2493 sn_tab[found].date_sec = inode.snap_ctime >> 32;
2494 sn_tab[found].date_nsec = inode.snap_ctime & 0xffffffff;
2495 sn_tab[found].vm_state_size = inode.vm_state_size;
2496 sn_tab[found].vm_clock_nsec = inode.vm_clock_nsec;
2498 snprintf(sn_tab[found].id_str, sizeof(sn_tab[found].id_str),
2499 "%" PRIu32, inode.snap_id);
2500 pstrcpy(sn_tab[found].name,
2501 MIN(sizeof(sn_tab[found].name), sizeof(inode.tag)),
2502 inode.tag);
2503 found++;
2507 closesocket(fd);
2508 out:
2509 *psn_tab = sn_tab;
2511 g_free(vdi_inuse);
2513 if (ret < 0) {
2514 return ret;
2517 return found;
2520 static int do_load_save_vmstate(BDRVSheepdogState *s, uint8_t *data,
2521 int64_t pos, int size, int load)
2523 Error *local_err = NULL;
2524 bool create;
2525 int fd, ret = 0, remaining = size;
2526 unsigned int data_len;
2527 uint64_t vmstate_oid;
2528 uint64_t offset;
2529 uint32_t vdi_index;
2530 uint32_t vdi_id = load ? s->inode.parent_vdi_id : s->inode.vdi_id;
2531 uint32_t object_size = (UINT32_C(1) << s->inode.block_size_shift);
2533 fd = connect_to_sdog(s, &local_err);
2534 if (fd < 0) {
2535 error_report_err(local_err);
2536 return fd;
2539 while (remaining) {
2540 vdi_index = pos / object_size;
2541 offset = pos % object_size;
2543 data_len = MIN(remaining, object_size - offset);
2545 vmstate_oid = vid_to_vmstate_oid(vdi_id, vdi_index);
2547 create = (offset == 0);
2548 if (load) {
2549 ret = read_object(fd, s->aio_context, (char *)data, vmstate_oid,
2550 s->inode.nr_copies, data_len, offset,
2551 s->cache_flags);
2552 } else {
2553 ret = write_object(fd, s->aio_context, (char *)data, vmstate_oid,
2554 s->inode.nr_copies, data_len, offset, create,
2555 s->cache_flags);
2558 if (ret < 0) {
2559 error_report("failed to save vmstate %s", strerror(errno));
2560 goto cleanup;
2563 pos += data_len;
2564 data += data_len;
2565 remaining -= data_len;
2567 ret = size;
2568 cleanup:
2569 closesocket(fd);
2570 return ret;
2573 static int sd_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2574 int64_t pos)
2576 BDRVSheepdogState *s = bs->opaque;
2577 void *buf;
2578 int ret;
2580 buf = qemu_blockalign(bs, qiov->size);
2581 qemu_iovec_to_buf(qiov, 0, buf, qiov->size);
2582 ret = do_load_save_vmstate(s, (uint8_t *) buf, pos, qiov->size, 0);
2583 qemu_vfree(buf);
2585 return ret;
2588 static int sd_load_vmstate(BlockDriverState *bs, uint8_t *data,
2589 int64_t pos, int size)
2591 BDRVSheepdogState *s = bs->opaque;
2593 return do_load_save_vmstate(s, data, pos, size, 1);
2597 static coroutine_fn int sd_co_discard(BlockDriverState *bs, int64_t sector_num,
2598 int nb_sectors)
2600 SheepdogAIOCB *acb;
2601 QEMUIOVector dummy;
2602 BDRVSheepdogState *s = bs->opaque;
2603 int ret;
2605 if (!s->discard_supported) {
2606 return 0;
2609 acb = sd_aio_setup(bs, &dummy, sector_num, nb_sectors);
2610 acb->aiocb_type = AIOCB_DISCARD_OBJ;
2611 acb->aio_done_func = sd_finish_aiocb;
2613 ret = sd_co_rw_vector(acb);
2614 if (ret <= 0) {
2615 qemu_aio_unref(acb);
2616 return ret;
2619 qemu_coroutine_yield();
2621 return acb->ret;
2624 static coroutine_fn int64_t
2625 sd_co_get_block_status(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
2626 int *pnum)
2628 BDRVSheepdogState *s = bs->opaque;
2629 SheepdogInode *inode = &s->inode;
2630 uint32_t object_size = (UINT32_C(1) << inode->block_size_shift);
2631 uint64_t offset = sector_num * BDRV_SECTOR_SIZE;
2632 unsigned long start = offset / object_size,
2633 end = DIV_ROUND_UP((sector_num + nb_sectors) *
2634 BDRV_SECTOR_SIZE, object_size);
2635 unsigned long idx;
2636 int64_t ret = BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | offset;
2638 for (idx = start; idx < end; idx++) {
2639 if (inode->data_vdi_id[idx] == 0) {
2640 break;
2643 if (idx == start) {
2644 /* Get the longest length of unallocated sectors */
2645 ret = 0;
2646 for (idx = start + 1; idx < end; idx++) {
2647 if (inode->data_vdi_id[idx] != 0) {
2648 break;
2653 *pnum = (idx - start) * object_size / BDRV_SECTOR_SIZE;
2654 if (*pnum > nb_sectors) {
2655 *pnum = nb_sectors;
2657 return ret;
2660 static int64_t sd_get_allocated_file_size(BlockDriverState *bs)
2662 BDRVSheepdogState *s = bs->opaque;
2663 SheepdogInode *inode = &s->inode;
2664 uint32_t object_size = (UINT32_C(1) << inode->block_size_shift);
2665 unsigned long i, last = DIV_ROUND_UP(inode->vdi_size, object_size);
2666 uint64_t size = 0;
2668 for (i = 0; i < last; i++) {
2669 if (inode->data_vdi_id[i] == 0) {
2670 continue;
2672 size += object_size;
2674 return size;
2677 static QemuOptsList sd_create_opts = {
2678 .name = "sheepdog-create-opts",
2679 .head = QTAILQ_HEAD_INITIALIZER(sd_create_opts.head),
2680 .desc = {
2682 .name = BLOCK_OPT_SIZE,
2683 .type = QEMU_OPT_SIZE,
2684 .help = "Virtual disk size"
2687 .name = BLOCK_OPT_BACKING_FILE,
2688 .type = QEMU_OPT_STRING,
2689 .help = "File name of a base image"
2692 .name = BLOCK_OPT_PREALLOC,
2693 .type = QEMU_OPT_STRING,
2694 .help = "Preallocation mode (allowed values: off, full)"
2697 .name = BLOCK_OPT_REDUNDANCY,
2698 .type = QEMU_OPT_STRING,
2699 .help = "Redundancy of the image"
2702 .name = BLOCK_OPT_OBJECT_SIZE,
2703 .type = QEMU_OPT_SIZE,
2704 .help = "Object size of the image"
2706 { /* end of list */ }
2710 static BlockDriver bdrv_sheepdog = {
2711 .format_name = "sheepdog",
2712 .protocol_name = "sheepdog",
2713 .instance_size = sizeof(BDRVSheepdogState),
2714 .bdrv_needs_filename = true,
2715 .bdrv_file_open = sd_open,
2716 .bdrv_close = sd_close,
2717 .bdrv_create = sd_create,
2718 .bdrv_has_zero_init = bdrv_has_zero_init_1,
2719 .bdrv_getlength = sd_getlength,
2720 .bdrv_get_allocated_file_size = sd_get_allocated_file_size,
2721 .bdrv_truncate = sd_truncate,
2723 .bdrv_co_readv = sd_co_readv,
2724 .bdrv_co_writev = sd_co_writev,
2725 .bdrv_co_flush_to_disk = sd_co_flush_to_disk,
2726 .bdrv_co_discard = sd_co_discard,
2727 .bdrv_co_get_block_status = sd_co_get_block_status,
2729 .bdrv_snapshot_create = sd_snapshot_create,
2730 .bdrv_snapshot_goto = sd_snapshot_goto,
2731 .bdrv_snapshot_delete = sd_snapshot_delete,
2732 .bdrv_snapshot_list = sd_snapshot_list,
2734 .bdrv_save_vmstate = sd_save_vmstate,
2735 .bdrv_load_vmstate = sd_load_vmstate,
2737 .bdrv_detach_aio_context = sd_detach_aio_context,
2738 .bdrv_attach_aio_context = sd_attach_aio_context,
2740 .create_opts = &sd_create_opts,
2743 static BlockDriver bdrv_sheepdog_tcp = {
2744 .format_name = "sheepdog",
2745 .protocol_name = "sheepdog+tcp",
2746 .instance_size = sizeof(BDRVSheepdogState),
2747 .bdrv_needs_filename = true,
2748 .bdrv_file_open = sd_open,
2749 .bdrv_close = sd_close,
2750 .bdrv_create = sd_create,
2751 .bdrv_has_zero_init = bdrv_has_zero_init_1,
2752 .bdrv_getlength = sd_getlength,
2753 .bdrv_get_allocated_file_size = sd_get_allocated_file_size,
2754 .bdrv_truncate = sd_truncate,
2756 .bdrv_co_readv = sd_co_readv,
2757 .bdrv_co_writev = sd_co_writev,
2758 .bdrv_co_flush_to_disk = sd_co_flush_to_disk,
2759 .bdrv_co_discard = sd_co_discard,
2760 .bdrv_co_get_block_status = sd_co_get_block_status,
2762 .bdrv_snapshot_create = sd_snapshot_create,
2763 .bdrv_snapshot_goto = sd_snapshot_goto,
2764 .bdrv_snapshot_delete = sd_snapshot_delete,
2765 .bdrv_snapshot_list = sd_snapshot_list,
2767 .bdrv_save_vmstate = sd_save_vmstate,
2768 .bdrv_load_vmstate = sd_load_vmstate,
2770 .bdrv_detach_aio_context = sd_detach_aio_context,
2771 .bdrv_attach_aio_context = sd_attach_aio_context,
2773 .create_opts = &sd_create_opts,
2776 static BlockDriver bdrv_sheepdog_unix = {
2777 .format_name = "sheepdog",
2778 .protocol_name = "sheepdog+unix",
2779 .instance_size = sizeof(BDRVSheepdogState),
2780 .bdrv_needs_filename = true,
2781 .bdrv_file_open = sd_open,
2782 .bdrv_close = sd_close,
2783 .bdrv_create = sd_create,
2784 .bdrv_has_zero_init = bdrv_has_zero_init_1,
2785 .bdrv_getlength = sd_getlength,
2786 .bdrv_get_allocated_file_size = sd_get_allocated_file_size,
2787 .bdrv_truncate = sd_truncate,
2789 .bdrv_co_readv = sd_co_readv,
2790 .bdrv_co_writev = sd_co_writev,
2791 .bdrv_co_flush_to_disk = sd_co_flush_to_disk,
2792 .bdrv_co_discard = sd_co_discard,
2793 .bdrv_co_get_block_status = sd_co_get_block_status,
2795 .bdrv_snapshot_create = sd_snapshot_create,
2796 .bdrv_snapshot_goto = sd_snapshot_goto,
2797 .bdrv_snapshot_delete = sd_snapshot_delete,
2798 .bdrv_snapshot_list = sd_snapshot_list,
2800 .bdrv_save_vmstate = sd_save_vmstate,
2801 .bdrv_load_vmstate = sd_load_vmstate,
2803 .bdrv_detach_aio_context = sd_detach_aio_context,
2804 .bdrv_attach_aio_context = sd_attach_aio_context,
2806 .create_opts = &sd_create_opts,
2809 static void bdrv_sheepdog_init(void)
2811 bdrv_register(&bdrv_sheepdog);
2812 bdrv_register(&bdrv_sheepdog_tcp);
2813 bdrv_register(&bdrv_sheepdog_unix);
2815 block_init(bdrv_sheepdog_init);