ui: fix VNC client throttling when audio capture is active
[qemu/ar7.git] / block / sheepdog.c
blobf684477328a8adf51dda023fec21f3cb5094c6b5
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/osdep.h"
16 #include "qapi-visit.h"
17 #include "qapi/error.h"
18 #include "qapi/qmp/qdict.h"
19 #include "qapi/qobject-input-visitor.h"
20 #include "qemu/uri.h"
21 #include "qemu/error-report.h"
22 #include "qemu/sockets.h"
23 #include "block/block_int.h"
24 #include "sysemu/block-backend.h"
25 #include "qemu/bitops.h"
26 #include "qemu/cutils.h"
28 #define SD_PROTO_VER 0x01
30 #define SD_DEFAULT_ADDR "localhost"
31 #define SD_DEFAULT_PORT 7000
33 #define SD_OP_CREATE_AND_WRITE_OBJ 0x01
34 #define SD_OP_READ_OBJ 0x02
35 #define SD_OP_WRITE_OBJ 0x03
36 /* 0x04 is used internally by Sheepdog */
38 #define SD_OP_NEW_VDI 0x11
39 #define SD_OP_LOCK_VDI 0x12
40 #define SD_OP_RELEASE_VDI 0x13
41 #define SD_OP_GET_VDI_INFO 0x14
42 #define SD_OP_READ_VDIS 0x15
43 #define SD_OP_FLUSH_VDI 0x16
44 #define SD_OP_DEL_VDI 0x17
45 #define SD_OP_GET_CLUSTER_DEFAULT 0x18
47 #define SD_FLAG_CMD_WRITE 0x01
48 #define SD_FLAG_CMD_COW 0x02
49 #define SD_FLAG_CMD_CACHE 0x04 /* Writeback mode for cache */
50 #define SD_FLAG_CMD_DIRECT 0x08 /* Don't use cache */
52 #define SD_RES_SUCCESS 0x00 /* Success */
53 #define SD_RES_UNKNOWN 0x01 /* Unknown error */
54 #define SD_RES_NO_OBJ 0x02 /* No object found */
55 #define SD_RES_EIO 0x03 /* I/O error */
56 #define SD_RES_VDI_EXIST 0x04 /* Vdi exists already */
57 #define SD_RES_INVALID_PARMS 0x05 /* Invalid parameters */
58 #define SD_RES_SYSTEM_ERROR 0x06 /* System error */
59 #define SD_RES_VDI_LOCKED 0x07 /* Vdi is locked */
60 #define SD_RES_NO_VDI 0x08 /* No vdi found */
61 #define SD_RES_NO_BASE_VDI 0x09 /* No base vdi found */
62 #define SD_RES_VDI_READ 0x0A /* Cannot read requested vdi */
63 #define SD_RES_VDI_WRITE 0x0B /* Cannot write requested vdi */
64 #define SD_RES_BASE_VDI_READ 0x0C /* Cannot read base vdi */
65 #define SD_RES_BASE_VDI_WRITE 0x0D /* Cannot write base vdi */
66 #define SD_RES_NO_TAG 0x0E /* Requested tag is not found */
67 #define SD_RES_STARTUP 0x0F /* Sheepdog is on starting up */
68 #define SD_RES_VDI_NOT_LOCKED 0x10 /* Vdi is not locked */
69 #define SD_RES_SHUTDOWN 0x11 /* Sheepdog is shutting down */
70 #define SD_RES_NO_MEM 0x12 /* Cannot allocate memory */
71 #define SD_RES_FULL_VDI 0x13 /* we already have the maximum vdis */
72 #define SD_RES_VER_MISMATCH 0x14 /* Protocol version mismatch */
73 #define SD_RES_NO_SPACE 0x15 /* Server has no room for new objects */
74 #define SD_RES_WAIT_FOR_FORMAT 0x16 /* Waiting for a format operation */
75 #define SD_RES_WAIT_FOR_JOIN 0x17 /* Waiting for other nodes joining */
76 #define SD_RES_JOIN_FAILED 0x18 /* Target node had failed to join sheepdog */
77 #define SD_RES_HALT 0x19 /* Sheepdog is stopped serving IO request */
78 #define SD_RES_READONLY 0x1A /* Object is read-only */
81 * Object ID rules
83 * 0 - 19 (20 bits): data object space
84 * 20 - 31 (12 bits): reserved data object space
85 * 32 - 55 (24 bits): vdi object space
86 * 56 - 59 ( 4 bits): reserved vdi object space
87 * 60 - 63 ( 4 bits): object type identifier space
90 #define VDI_SPACE_SHIFT 32
91 #define VDI_BIT (UINT64_C(1) << 63)
92 #define VMSTATE_BIT (UINT64_C(1) << 62)
93 #define MAX_DATA_OBJS (UINT64_C(1) << 20)
94 #define MAX_CHILDREN 1024
95 #define SD_MAX_VDI_LEN 256
96 #define SD_MAX_VDI_TAG_LEN 256
97 #define SD_NR_VDIS (1U << 24)
98 #define SD_DATA_OBJ_SIZE (UINT64_C(1) << 22)
99 #define SD_MAX_VDI_SIZE (SD_DATA_OBJ_SIZE * MAX_DATA_OBJS)
100 #define SD_DEFAULT_BLOCK_SIZE_SHIFT 22
102 * For erasure coding, we use at most SD_EC_MAX_STRIP for data strips and
103 * (SD_EC_MAX_STRIP - 1) for parity strips
105 * SD_MAX_COPIES is sum of number of data strips and parity strips.
107 #define SD_EC_MAX_STRIP 16
108 #define SD_MAX_COPIES (SD_EC_MAX_STRIP * 2 - 1)
110 #define SD_INODE_SIZE (sizeof(SheepdogInode))
111 #define CURRENT_VDI_ID 0
113 #define LOCK_TYPE_NORMAL 0
114 #define LOCK_TYPE_SHARED 1 /* for iSCSI multipath */
116 typedef struct SheepdogReq {
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 opcode_specific[8];
124 } SheepdogReq;
126 typedef struct SheepdogRsp {
127 uint8_t proto_ver;
128 uint8_t opcode;
129 uint16_t flags;
130 uint32_t epoch;
131 uint32_t id;
132 uint32_t data_length;
133 uint32_t result;
134 uint32_t opcode_specific[7];
135 } SheepdogRsp;
137 typedef struct SheepdogObjReq {
138 uint8_t proto_ver;
139 uint8_t opcode;
140 uint16_t flags;
141 uint32_t epoch;
142 uint32_t id;
143 uint32_t data_length;
144 uint64_t oid;
145 uint64_t cow_oid;
146 uint8_t copies;
147 uint8_t copy_policy;
148 uint8_t reserved[6];
149 uint64_t offset;
150 } SheepdogObjReq;
152 typedef struct SheepdogObjRsp {
153 uint8_t proto_ver;
154 uint8_t opcode;
155 uint16_t flags;
156 uint32_t epoch;
157 uint32_t id;
158 uint32_t data_length;
159 uint32_t result;
160 uint8_t copies;
161 uint8_t copy_policy;
162 uint8_t reserved[2];
163 uint32_t pad[6];
164 } SheepdogObjRsp;
166 typedef struct SheepdogVdiReq {
167 uint8_t proto_ver;
168 uint8_t opcode;
169 uint16_t flags;
170 uint32_t epoch;
171 uint32_t id;
172 uint32_t data_length;
173 uint64_t vdi_size;
174 uint32_t base_vdi_id;
175 uint8_t copies;
176 uint8_t copy_policy;
177 uint8_t store_policy;
178 uint8_t block_size_shift;
179 uint32_t snapid;
180 uint32_t type;
181 uint32_t pad[2];
182 } SheepdogVdiReq;
184 typedef struct SheepdogVdiRsp {
185 uint8_t proto_ver;
186 uint8_t opcode;
187 uint16_t flags;
188 uint32_t epoch;
189 uint32_t id;
190 uint32_t data_length;
191 uint32_t result;
192 uint32_t rsvd;
193 uint32_t vdi_id;
194 uint32_t pad[5];
195 } SheepdogVdiRsp;
197 typedef struct SheepdogClusterRsp {
198 uint8_t proto_ver;
199 uint8_t opcode;
200 uint16_t flags;
201 uint32_t epoch;
202 uint32_t id;
203 uint32_t data_length;
204 uint32_t result;
205 uint8_t nr_copies;
206 uint8_t copy_policy;
207 uint8_t block_size_shift;
208 uint8_t __pad1;
209 uint32_t __pad2[6];
210 } SheepdogClusterRsp;
212 typedef struct SheepdogInode {
213 char name[SD_MAX_VDI_LEN];
214 char tag[SD_MAX_VDI_TAG_LEN];
215 uint64_t ctime;
216 uint64_t snap_ctime;
217 uint64_t vm_clock_nsec;
218 uint64_t vdi_size;
219 uint64_t vm_state_size;
220 uint16_t copy_policy;
221 uint8_t nr_copies;
222 uint8_t block_size_shift;
223 uint32_t snap_id;
224 uint32_t vdi_id;
225 uint32_t parent_vdi_id;
226 uint32_t child_vdi_id[MAX_CHILDREN];
227 uint32_t data_vdi_id[MAX_DATA_OBJS];
228 } SheepdogInode;
230 #define SD_INODE_HEADER_SIZE offsetof(SheepdogInode, data_vdi_id)
233 * 64 bit FNV-1a non-zero initial basis
235 #define FNV1A_64_INIT ((uint64_t)0xcbf29ce484222325ULL)
238 * 64 bit Fowler/Noll/Vo FNV-1a hash code
240 static inline uint64_t fnv_64a_buf(void *buf, size_t len, uint64_t hval)
242 unsigned char *bp = buf;
243 unsigned char *be = bp + len;
244 while (bp < be) {
245 hval ^= (uint64_t) *bp++;
246 hval += (hval << 1) + (hval << 4) + (hval << 5) +
247 (hval << 7) + (hval << 8) + (hval << 40);
249 return hval;
252 static inline bool is_data_obj_writable(SheepdogInode *inode, unsigned int idx)
254 return inode->vdi_id == inode->data_vdi_id[idx];
257 static inline bool is_data_obj(uint64_t oid)
259 return !(VDI_BIT & oid);
262 static inline uint64_t data_oid_to_idx(uint64_t oid)
264 return oid & (MAX_DATA_OBJS - 1);
267 static inline uint32_t oid_to_vid(uint64_t oid)
269 return (oid & ~VDI_BIT) >> VDI_SPACE_SHIFT;
272 static inline uint64_t vid_to_vdi_oid(uint32_t vid)
274 return VDI_BIT | ((uint64_t)vid << VDI_SPACE_SHIFT);
277 static inline uint64_t vid_to_vmstate_oid(uint32_t vid, uint32_t idx)
279 return VMSTATE_BIT | ((uint64_t)vid << VDI_SPACE_SHIFT) | idx;
282 static inline uint64_t vid_to_data_oid(uint32_t vid, uint32_t idx)
284 return ((uint64_t)vid << VDI_SPACE_SHIFT) | idx;
287 static inline bool is_snapshot(struct SheepdogInode *inode)
289 return !!inode->snap_ctime;
292 static inline size_t count_data_objs(const struct SheepdogInode *inode)
294 return DIV_ROUND_UP(inode->vdi_size,
295 (1UL << inode->block_size_shift));
298 #undef DPRINTF
299 #ifdef DEBUG_SDOG
300 #define DEBUG_SDOG_PRINT 1
301 #else
302 #define DEBUG_SDOG_PRINT 0
303 #endif
304 #define DPRINTF(fmt, args...) \
305 do { \
306 if (DEBUG_SDOG_PRINT) { \
307 fprintf(stderr, "%s %d: " fmt, __func__, __LINE__, ##args); \
309 } while (0)
311 typedef struct SheepdogAIOCB SheepdogAIOCB;
312 typedef struct BDRVSheepdogState BDRVSheepdogState;
314 typedef struct AIOReq {
315 SheepdogAIOCB *aiocb;
316 unsigned int iov_offset;
318 uint64_t oid;
319 uint64_t base_oid;
320 uint64_t offset;
321 unsigned int data_len;
322 uint8_t flags;
323 uint32_t id;
324 bool create;
326 QLIST_ENTRY(AIOReq) aio_siblings;
327 } AIOReq;
329 enum AIOCBState {
330 AIOCB_WRITE_UDATA,
331 AIOCB_READ_UDATA,
332 AIOCB_FLUSH_CACHE,
333 AIOCB_DISCARD_OBJ,
336 #define AIOCBOverlapping(x, y) \
337 (!(x->max_affect_data_idx < y->min_affect_data_idx \
338 || y->max_affect_data_idx < x->min_affect_data_idx))
340 struct SheepdogAIOCB {
341 BDRVSheepdogState *s;
343 QEMUIOVector *qiov;
345 int64_t sector_num;
346 int nb_sectors;
348 int ret;
349 enum AIOCBState aiocb_type;
351 Coroutine *coroutine;
352 int nr_pending;
354 uint32_t min_affect_data_idx;
355 uint32_t max_affect_data_idx;
358 * The difference between affect_data_idx and dirty_data_idx:
359 * affect_data_idx represents range of index of all request types.
360 * dirty_data_idx represents range of index updated by COW requests.
361 * dirty_data_idx is used for updating an inode object.
363 uint32_t min_dirty_data_idx;
364 uint32_t max_dirty_data_idx;
366 QLIST_ENTRY(SheepdogAIOCB) aiocb_siblings;
369 struct BDRVSheepdogState {
370 BlockDriverState *bs;
371 AioContext *aio_context;
373 SheepdogInode inode;
375 char name[SD_MAX_VDI_LEN];
376 bool is_snapshot;
377 uint32_t cache_flags;
378 bool discard_supported;
380 SocketAddress *addr;
381 int fd;
383 CoMutex lock;
384 Coroutine *co_send;
385 Coroutine *co_recv;
387 uint32_t aioreq_seq_num;
389 /* Every aio request must be linked to either of these queues. */
390 QLIST_HEAD(inflight_aio_head, AIOReq) inflight_aio_head;
391 QLIST_HEAD(failed_aio_head, AIOReq) failed_aio_head;
393 CoMutex queue_lock;
394 CoQueue overlapping_queue;
395 QLIST_HEAD(inflight_aiocb_head, SheepdogAIOCB) inflight_aiocb_head;
398 typedef struct BDRVSheepdogReopenState {
399 int fd;
400 int cache_flags;
401 } BDRVSheepdogReopenState;
403 static const char *sd_strerror(int err)
405 int i;
407 static const struct {
408 int err;
409 const char *desc;
410 } errors[] = {
411 {SD_RES_SUCCESS, "Success"},
412 {SD_RES_UNKNOWN, "Unknown error"},
413 {SD_RES_NO_OBJ, "No object found"},
414 {SD_RES_EIO, "I/O error"},
415 {SD_RES_VDI_EXIST, "VDI exists already"},
416 {SD_RES_INVALID_PARMS, "Invalid parameters"},
417 {SD_RES_SYSTEM_ERROR, "System error"},
418 {SD_RES_VDI_LOCKED, "VDI is already locked"},
419 {SD_RES_NO_VDI, "No vdi found"},
420 {SD_RES_NO_BASE_VDI, "No base VDI found"},
421 {SD_RES_VDI_READ, "Failed read the requested VDI"},
422 {SD_RES_VDI_WRITE, "Failed to write the requested VDI"},
423 {SD_RES_BASE_VDI_READ, "Failed to read the base VDI"},
424 {SD_RES_BASE_VDI_WRITE, "Failed to write the base VDI"},
425 {SD_RES_NO_TAG, "Failed to find the requested tag"},
426 {SD_RES_STARTUP, "The system is still booting"},
427 {SD_RES_VDI_NOT_LOCKED, "VDI isn't locked"},
428 {SD_RES_SHUTDOWN, "The system is shutting down"},
429 {SD_RES_NO_MEM, "Out of memory on the server"},
430 {SD_RES_FULL_VDI, "We already have the maximum vdis"},
431 {SD_RES_VER_MISMATCH, "Protocol version mismatch"},
432 {SD_RES_NO_SPACE, "Server has no space for new objects"},
433 {SD_RES_WAIT_FOR_FORMAT, "Sheepdog is waiting for a format operation"},
434 {SD_RES_WAIT_FOR_JOIN, "Sheepdog is waiting for other nodes joining"},
435 {SD_RES_JOIN_FAILED, "Target node had failed to join sheepdog"},
436 {SD_RES_HALT, "Sheepdog is stopped serving IO request"},
437 {SD_RES_READONLY, "Object is read-only"},
440 for (i = 0; i < ARRAY_SIZE(errors); ++i) {
441 if (errors[i].err == err) {
442 return errors[i].desc;
446 return "Invalid error code";
450 * Sheepdog I/O handling:
452 * 1. In sd_co_rw_vector, we send the I/O requests to the server and
453 * link the requests to the inflight_list in the
454 * BDRVSheepdogState. The function yields while waiting for
455 * receiving the response.
457 * 2. We receive the response in aio_read_response, the fd handler to
458 * the sheepdog connection. We switch back to sd_co_readv/sd_writev
459 * after all the requests belonging to the AIOCB are finished. If
460 * needed, sd_co_writev will send another requests for the vdi object.
463 static inline AIOReq *alloc_aio_req(BDRVSheepdogState *s, SheepdogAIOCB *acb,
464 uint64_t oid, unsigned int data_len,
465 uint64_t offset, uint8_t flags, bool create,
466 uint64_t base_oid, unsigned int iov_offset)
468 AIOReq *aio_req;
470 aio_req = g_malloc(sizeof(*aio_req));
471 aio_req->aiocb = acb;
472 aio_req->iov_offset = iov_offset;
473 aio_req->oid = oid;
474 aio_req->base_oid = base_oid;
475 aio_req->offset = offset;
476 aio_req->data_len = data_len;
477 aio_req->flags = flags;
478 aio_req->id = s->aioreq_seq_num++;
479 aio_req->create = create;
481 acb->nr_pending++;
482 return aio_req;
485 static void wait_for_overlapping_aiocb(BDRVSheepdogState *s, SheepdogAIOCB *acb)
487 SheepdogAIOCB *cb;
489 retry:
490 QLIST_FOREACH(cb, &s->inflight_aiocb_head, aiocb_siblings) {
491 if (AIOCBOverlapping(acb, cb)) {
492 qemu_co_queue_wait(&s->overlapping_queue, &s->queue_lock);
493 goto retry;
498 static void sd_aio_setup(SheepdogAIOCB *acb, BDRVSheepdogState *s,
499 QEMUIOVector *qiov, int64_t sector_num, int nb_sectors,
500 int type)
502 uint32_t object_size;
504 object_size = (UINT32_C(1) << s->inode.block_size_shift);
506 acb->s = s;
508 acb->qiov = qiov;
510 acb->sector_num = sector_num;
511 acb->nb_sectors = nb_sectors;
513 acb->coroutine = qemu_coroutine_self();
514 acb->ret = 0;
515 acb->nr_pending = 0;
517 acb->min_affect_data_idx = acb->sector_num * BDRV_SECTOR_SIZE / object_size;
518 acb->max_affect_data_idx = (acb->sector_num * BDRV_SECTOR_SIZE +
519 acb->nb_sectors * BDRV_SECTOR_SIZE) / object_size;
521 acb->min_dirty_data_idx = UINT32_MAX;
522 acb->max_dirty_data_idx = 0;
523 acb->aiocb_type = type;
525 if (type == AIOCB_FLUSH_CACHE) {
526 return;
529 qemu_co_mutex_lock(&s->queue_lock);
530 wait_for_overlapping_aiocb(s, acb);
531 QLIST_INSERT_HEAD(&s->inflight_aiocb_head, acb, aiocb_siblings);
532 qemu_co_mutex_unlock(&s->queue_lock);
535 static SocketAddress *sd_socket_address(const char *path,
536 const char *host, const char *port)
538 SocketAddress *addr = g_new0(SocketAddress, 1);
540 if (path) {
541 addr->type = SOCKET_ADDRESS_TYPE_UNIX;
542 addr->u.q_unix.path = g_strdup(path);
543 } else {
544 addr->type = SOCKET_ADDRESS_TYPE_INET;
545 addr->u.inet.host = g_strdup(host ?: SD_DEFAULT_ADDR);
546 addr->u.inet.port = g_strdup(port ?: stringify(SD_DEFAULT_PORT));
549 return addr;
552 static SocketAddress *sd_server_config(QDict *options, Error **errp)
554 QDict *server = NULL;
555 QObject *crumpled_server = NULL;
556 Visitor *iv = NULL;
557 SocketAddress *saddr = NULL;
558 Error *local_err = NULL;
560 qdict_extract_subqdict(options, &server, "server.");
562 crumpled_server = qdict_crumple(server, errp);
563 if (!crumpled_server) {
564 goto done;
568 * FIXME .numeric, .to, .ipv4 or .ipv6 don't work with -drive
569 * server.type=inet. .to doesn't matter, it's ignored anyway.
570 * That's because when @options come from -blockdev or
571 * blockdev_add, members are typed according to the QAPI schema,
572 * but when they come from -drive, they're all QString. The
573 * visitor expects the former.
575 iv = qobject_input_visitor_new(crumpled_server);
576 visit_type_SocketAddress(iv, NULL, &saddr, &local_err);
577 if (local_err) {
578 error_propagate(errp, local_err);
579 goto done;
582 done:
583 visit_free(iv);
584 qobject_decref(crumpled_server);
585 QDECREF(server);
586 return saddr;
589 /* Return -EIO in case of error, file descriptor on success */
590 static int connect_to_sdog(BDRVSheepdogState *s, Error **errp)
592 int fd;
594 fd = socket_connect(s->addr, errp);
596 if (s->addr->type == SOCKET_ADDRESS_TYPE_INET && fd >= 0) {
597 int ret = socket_set_nodelay(fd);
598 if (ret < 0) {
599 error_report("%s", strerror(errno));
603 if (fd >= 0) {
604 qemu_set_nonblock(fd);
605 } else {
606 fd = -EIO;
609 return fd;
612 /* Return 0 on success and -errno in case of error */
613 static coroutine_fn int send_co_req(int sockfd, SheepdogReq *hdr, void *data,
614 unsigned int *wlen)
616 int ret;
618 ret = qemu_co_send(sockfd, hdr, sizeof(*hdr));
619 if (ret != sizeof(*hdr)) {
620 error_report("failed to send a req, %s", strerror(errno));
621 return -errno;
624 ret = qemu_co_send(sockfd, data, *wlen);
625 if (ret != *wlen) {
626 error_report("failed to send a req, %s", strerror(errno));
627 return -errno;
630 return ret;
633 typedef struct SheepdogReqCo {
634 int sockfd;
635 BlockDriverState *bs;
636 AioContext *aio_context;
637 SheepdogReq *hdr;
638 void *data;
639 unsigned int *wlen;
640 unsigned int *rlen;
641 int ret;
642 bool finished;
643 Coroutine *co;
644 } SheepdogReqCo;
646 static void restart_co_req(void *opaque)
648 SheepdogReqCo *srco = opaque;
650 aio_co_wake(srco->co);
653 static coroutine_fn void do_co_req(void *opaque)
655 int ret;
656 SheepdogReqCo *srco = opaque;
657 int sockfd = srco->sockfd;
658 SheepdogReq *hdr = srco->hdr;
659 void *data = srco->data;
660 unsigned int *wlen = srco->wlen;
661 unsigned int *rlen = srco->rlen;
663 srco->co = qemu_coroutine_self();
664 aio_set_fd_handler(srco->aio_context, sockfd, false,
665 NULL, restart_co_req, NULL, srco);
667 ret = send_co_req(sockfd, hdr, data, wlen);
668 if (ret < 0) {
669 goto out;
672 aio_set_fd_handler(srco->aio_context, sockfd, false,
673 restart_co_req, NULL, NULL, srco);
675 ret = qemu_co_recv(sockfd, hdr, sizeof(*hdr));
676 if (ret != sizeof(*hdr)) {
677 error_report("failed to get a rsp, %s", strerror(errno));
678 ret = -errno;
679 goto out;
682 if (*rlen > hdr->data_length) {
683 *rlen = hdr->data_length;
686 if (*rlen) {
687 ret = qemu_co_recv(sockfd, data, *rlen);
688 if (ret != *rlen) {
689 error_report("failed to get the data, %s", strerror(errno));
690 ret = -errno;
691 goto out;
694 ret = 0;
695 out:
696 /* there is at most one request for this sockfd, so it is safe to
697 * set each handler to NULL. */
698 aio_set_fd_handler(srco->aio_context, sockfd, false,
699 NULL, NULL, NULL, NULL);
701 srco->co = NULL;
702 srco->ret = ret;
703 /* Set srco->finished before reading bs->wakeup. */
704 atomic_mb_set(&srco->finished, true);
705 if (srco->bs) {
706 bdrv_wakeup(srco->bs);
711 * Send the request to the sheep in a synchronous manner.
713 * Return 0 on success, -errno in case of error.
715 static int do_req(int sockfd, BlockDriverState *bs, SheepdogReq *hdr,
716 void *data, unsigned int *wlen, unsigned int *rlen)
718 Coroutine *co;
719 SheepdogReqCo srco = {
720 .sockfd = sockfd,
721 .aio_context = bs ? bdrv_get_aio_context(bs) : qemu_get_aio_context(),
722 .bs = bs,
723 .hdr = hdr,
724 .data = data,
725 .wlen = wlen,
726 .rlen = rlen,
727 .ret = 0,
728 .finished = false,
731 if (qemu_in_coroutine()) {
732 do_co_req(&srco);
733 } else {
734 co = qemu_coroutine_create(do_co_req, &srco);
735 if (bs) {
736 bdrv_coroutine_enter(bs, co);
737 BDRV_POLL_WHILE(bs, !srco.finished);
738 } else {
739 qemu_coroutine_enter(co);
740 while (!srco.finished) {
741 aio_poll(qemu_get_aio_context(), true);
746 return srco.ret;
749 static void coroutine_fn add_aio_request(BDRVSheepdogState *s, AIOReq *aio_req,
750 struct iovec *iov, int niov,
751 enum AIOCBState aiocb_type);
752 static void coroutine_fn resend_aioreq(BDRVSheepdogState *s, AIOReq *aio_req);
753 static int reload_inode(BDRVSheepdogState *s, uint32_t snapid, const char *tag);
754 static int get_sheep_fd(BDRVSheepdogState *s, Error **errp);
755 static void co_write_request(void *opaque);
757 static coroutine_fn void reconnect_to_sdog(void *opaque)
759 BDRVSheepdogState *s = opaque;
760 AIOReq *aio_req, *next;
762 aio_set_fd_handler(s->aio_context, s->fd, false, NULL,
763 NULL, NULL, NULL);
764 close(s->fd);
765 s->fd = -1;
767 /* Wait for outstanding write requests to be completed. */
768 while (s->co_send != NULL) {
769 co_write_request(opaque);
772 /* Try to reconnect the sheepdog server every one second. */
773 while (s->fd < 0) {
774 Error *local_err = NULL;
775 s->fd = get_sheep_fd(s, &local_err);
776 if (s->fd < 0) {
777 DPRINTF("Wait for connection to be established\n");
778 error_report_err(local_err);
779 qemu_co_sleep_ns(QEMU_CLOCK_REALTIME, 1000000000ULL);
784 * Now we have to resend all the request in the inflight queue. However,
785 * resend_aioreq() can yield and newly created requests can be added to the
786 * inflight queue before the coroutine is resumed. To avoid mixing them, we
787 * have to move all the inflight requests to the failed queue before
788 * resend_aioreq() is called.
790 qemu_co_mutex_lock(&s->queue_lock);
791 QLIST_FOREACH_SAFE(aio_req, &s->inflight_aio_head, aio_siblings, next) {
792 QLIST_REMOVE(aio_req, aio_siblings);
793 QLIST_INSERT_HEAD(&s->failed_aio_head, aio_req, aio_siblings);
796 /* Resend all the failed aio requests. */
797 while (!QLIST_EMPTY(&s->failed_aio_head)) {
798 aio_req = QLIST_FIRST(&s->failed_aio_head);
799 QLIST_REMOVE(aio_req, aio_siblings);
800 qemu_co_mutex_unlock(&s->queue_lock);
801 resend_aioreq(s, aio_req);
802 qemu_co_mutex_lock(&s->queue_lock);
804 qemu_co_mutex_unlock(&s->queue_lock);
808 * Receive responses of the I/O requests.
810 * This function is registered as a fd handler, and called from the
811 * main loop when s->fd is ready for reading responses.
813 static void coroutine_fn aio_read_response(void *opaque)
815 SheepdogObjRsp rsp;
816 BDRVSheepdogState *s = opaque;
817 int fd = s->fd;
818 int ret;
819 AIOReq *aio_req = NULL;
820 SheepdogAIOCB *acb;
821 uint64_t idx;
823 /* read a header */
824 ret = qemu_co_recv(fd, &rsp, sizeof(rsp));
825 if (ret != sizeof(rsp)) {
826 error_report("failed to get the header, %s", strerror(errno));
827 goto err;
830 /* find the right aio_req from the inflight aio list */
831 QLIST_FOREACH(aio_req, &s->inflight_aio_head, aio_siblings) {
832 if (aio_req->id == rsp.id) {
833 break;
836 if (!aio_req) {
837 error_report("cannot find aio_req %x", rsp.id);
838 goto err;
841 acb = aio_req->aiocb;
843 switch (acb->aiocb_type) {
844 case AIOCB_WRITE_UDATA:
845 if (!is_data_obj(aio_req->oid)) {
846 break;
848 idx = data_oid_to_idx(aio_req->oid);
850 if (aio_req->create) {
852 * If the object is newly created one, we need to update
853 * the vdi object (metadata object). min_dirty_data_idx
854 * and max_dirty_data_idx are changed to include updated
855 * index between them.
857 if (rsp.result == SD_RES_SUCCESS) {
858 s->inode.data_vdi_id[idx] = s->inode.vdi_id;
859 acb->max_dirty_data_idx = MAX(idx, acb->max_dirty_data_idx);
860 acb->min_dirty_data_idx = MIN(idx, acb->min_dirty_data_idx);
863 break;
864 case AIOCB_READ_UDATA:
865 ret = qemu_co_recvv(fd, acb->qiov->iov, acb->qiov->niov,
866 aio_req->iov_offset, rsp.data_length);
867 if (ret != rsp.data_length) {
868 error_report("failed to get the data, %s", strerror(errno));
869 goto err;
871 break;
872 case AIOCB_FLUSH_CACHE:
873 if (rsp.result == SD_RES_INVALID_PARMS) {
874 DPRINTF("disable cache since the server doesn't support it\n");
875 s->cache_flags = SD_FLAG_CMD_DIRECT;
876 rsp.result = SD_RES_SUCCESS;
878 break;
879 case AIOCB_DISCARD_OBJ:
880 switch (rsp.result) {
881 case SD_RES_INVALID_PARMS:
882 error_report("server doesn't support discard command");
883 rsp.result = SD_RES_SUCCESS;
884 s->discard_supported = false;
885 break;
886 default:
887 break;
891 /* No more data for this aio_req (reload_inode below uses its own file
892 * descriptor handler which doesn't use co_recv).
894 s->co_recv = NULL;
896 qemu_co_mutex_lock(&s->queue_lock);
897 QLIST_REMOVE(aio_req, aio_siblings);
898 qemu_co_mutex_unlock(&s->queue_lock);
900 switch (rsp.result) {
901 case SD_RES_SUCCESS:
902 break;
903 case SD_RES_READONLY:
904 if (s->inode.vdi_id == oid_to_vid(aio_req->oid)) {
905 ret = reload_inode(s, 0, "");
906 if (ret < 0) {
907 goto err;
910 if (is_data_obj(aio_req->oid)) {
911 aio_req->oid = vid_to_data_oid(s->inode.vdi_id,
912 data_oid_to_idx(aio_req->oid));
913 } else {
914 aio_req->oid = vid_to_vdi_oid(s->inode.vdi_id);
916 resend_aioreq(s, aio_req);
917 return;
918 default:
919 acb->ret = -EIO;
920 error_report("%s", sd_strerror(rsp.result));
921 break;
924 g_free(aio_req);
926 if (!--acb->nr_pending) {
928 * We've finished all requests which belong to the AIOCB, so
929 * we can switch back to sd_co_readv/writev now.
931 aio_co_wake(acb->coroutine);
934 return;
936 err:
937 reconnect_to_sdog(opaque);
940 static void co_read_response(void *opaque)
942 BDRVSheepdogState *s = opaque;
944 if (!s->co_recv) {
945 s->co_recv = qemu_coroutine_create(aio_read_response, opaque);
948 aio_co_enter(s->aio_context, s->co_recv);
951 static void co_write_request(void *opaque)
953 BDRVSheepdogState *s = opaque;
955 aio_co_wake(s->co_send);
959 * Return a socket descriptor to read/write objects.
961 * We cannot use this descriptor for other operations because
962 * the block driver may be on waiting response from the server.
964 static int get_sheep_fd(BDRVSheepdogState *s, Error **errp)
966 int fd;
968 fd = connect_to_sdog(s, errp);
969 if (fd < 0) {
970 return fd;
973 aio_set_fd_handler(s->aio_context, fd, false,
974 co_read_response, NULL, NULL, s);
975 return fd;
979 * Parse numeric snapshot ID in @str
980 * If @str can't be parsed as number, return false.
981 * Else, if the number is zero or too large, set *@snapid to zero and
982 * return true.
983 * Else, set *@snapid to the number and return true.
985 static bool sd_parse_snapid(const char *str, uint32_t *snapid)
987 unsigned long ul;
988 int ret;
990 ret = qemu_strtoul(str, NULL, 10, &ul);
991 if (ret == -ERANGE) {
992 ul = ret = 0;
994 if (ret) {
995 return false;
997 if (ul > UINT32_MAX) {
998 ul = 0;
1001 *snapid = ul;
1002 return true;
1005 static bool sd_parse_snapid_or_tag(const char *str,
1006 uint32_t *snapid, char tag[])
1008 if (!sd_parse_snapid(str, snapid)) {
1009 *snapid = 0;
1010 if (g_strlcpy(tag, str, SD_MAX_VDI_TAG_LEN) >= SD_MAX_VDI_TAG_LEN) {
1011 return false;
1013 } else if (!*snapid) {
1014 return false;
1015 } else {
1016 tag[0] = 0;
1018 return true;
1021 typedef struct {
1022 const char *path; /* non-null iff transport is tcp */
1023 const char *host; /* valid when transport is tcp */
1024 int port; /* valid when transport is tcp */
1025 char vdi[SD_MAX_VDI_LEN];
1026 char tag[SD_MAX_VDI_TAG_LEN];
1027 uint32_t snap_id;
1028 /* Remainder is only for sd_config_done() */
1029 URI *uri;
1030 QueryParams *qp;
1031 } SheepdogConfig;
1033 static void sd_config_done(SheepdogConfig *cfg)
1035 if (cfg->qp) {
1036 query_params_free(cfg->qp);
1038 uri_free(cfg->uri);
1041 static void sd_parse_uri(SheepdogConfig *cfg, const char *filename,
1042 Error **errp)
1044 Error *err = NULL;
1045 QueryParams *qp = NULL;
1046 bool is_unix;
1047 URI *uri;
1049 memset(cfg, 0, sizeof(*cfg));
1051 cfg->uri = uri = uri_parse(filename);
1052 if (!uri) {
1053 error_setg(&err, "invalid URI");
1054 goto out;
1057 /* transport */
1058 if (!g_strcmp0(uri->scheme, "sheepdog")) {
1059 is_unix = false;
1060 } else if (!g_strcmp0(uri->scheme, "sheepdog+tcp")) {
1061 is_unix = false;
1062 } else if (!g_strcmp0(uri->scheme, "sheepdog+unix")) {
1063 is_unix = true;
1064 } else {
1065 error_setg(&err, "URI scheme must be 'sheepdog', 'sheepdog+tcp',"
1066 " or 'sheepdog+unix'");
1067 goto out;
1070 if (uri->path == NULL || !strcmp(uri->path, "/")) {
1071 error_setg(&err, "missing file path in URI");
1072 goto out;
1074 if (g_strlcpy(cfg->vdi, uri->path + 1, SD_MAX_VDI_LEN)
1075 >= SD_MAX_VDI_LEN) {
1076 error_setg(&err, "VDI name is too long");
1077 goto out;
1080 cfg->qp = qp = query_params_parse(uri->query);
1082 if (is_unix) {
1083 /* sheepdog+unix:///vdiname?socket=path */
1084 if (uri->server || uri->port) {
1085 error_setg(&err, "URI scheme %s doesn't accept a server address",
1086 uri->scheme);
1087 goto out;
1089 if (!qp->n) {
1090 error_setg(&err,
1091 "URI scheme %s requires query parameter 'socket'",
1092 uri->scheme);
1093 goto out;
1095 if (qp->n != 1 || strcmp(qp->p[0].name, "socket")) {
1096 error_setg(&err, "unexpected query parameters");
1097 goto out;
1099 cfg->path = qp->p[0].value;
1100 } else {
1101 /* sheepdog[+tcp]://[host:port]/vdiname */
1102 if (qp->n) {
1103 error_setg(&err, "unexpected query parameters");
1104 goto out;
1106 cfg->host = uri->server;
1107 cfg->port = uri->port;
1110 /* snapshot tag */
1111 if (uri->fragment) {
1112 if (!sd_parse_snapid_or_tag(uri->fragment,
1113 &cfg->snap_id, cfg->tag)) {
1114 error_setg(&err, "'%s' is not a valid snapshot ID",
1115 uri->fragment);
1116 goto out;
1118 } else {
1119 cfg->snap_id = CURRENT_VDI_ID; /* search current vdi */
1122 out:
1123 if (err) {
1124 error_propagate(errp, err);
1125 sd_config_done(cfg);
1130 * Parse a filename (old syntax)
1132 * filename must be one of the following formats:
1133 * 1. [vdiname]
1134 * 2. [vdiname]:[snapid]
1135 * 3. [vdiname]:[tag]
1136 * 4. [hostname]:[port]:[vdiname]
1137 * 5. [hostname]:[port]:[vdiname]:[snapid]
1138 * 6. [hostname]:[port]:[vdiname]:[tag]
1140 * You can boot from the snapshot images by specifying `snapid` or
1141 * `tag'.
1143 * You can run VMs outside the Sheepdog cluster by specifying
1144 * `hostname' and `port' (experimental).
1146 static void parse_vdiname(SheepdogConfig *cfg, const char *filename,
1147 Error **errp)
1149 Error *err = NULL;
1150 char *p, *q, *uri;
1151 const char *host_spec, *vdi_spec;
1152 int nr_sep;
1154 strstart(filename, "sheepdog:", &filename);
1155 p = q = g_strdup(filename);
1157 /* count the number of separators */
1158 nr_sep = 0;
1159 while (*p) {
1160 if (*p == ':') {
1161 nr_sep++;
1163 p++;
1165 p = q;
1167 /* use the first two tokens as host_spec. */
1168 if (nr_sep >= 2) {
1169 host_spec = p;
1170 p = strchr(p, ':');
1171 p++;
1172 p = strchr(p, ':');
1173 *p++ = '\0';
1174 } else {
1175 host_spec = "";
1178 vdi_spec = p;
1180 p = strchr(vdi_spec, ':');
1181 if (p) {
1182 *p++ = '#';
1185 uri = g_strdup_printf("sheepdog://%s/%s", host_spec, vdi_spec);
1188 * FIXME We to escape URI meta-characters, e.g. "x?y=z"
1189 * produces "sheepdog://x?y=z". Because of that ...
1191 sd_parse_uri(cfg, uri, &err);
1192 if (err) {
1194 * ... this can fail, but the error message is misleading.
1195 * Replace it by the traditional useless one until the
1196 * escaping is fixed.
1198 error_free(err);
1199 error_setg(errp, "Can't parse filename");
1202 g_free(q);
1203 g_free(uri);
1206 static void sd_parse_filename(const char *filename, QDict *options,
1207 Error **errp)
1209 Error *err = NULL;
1210 SheepdogConfig cfg;
1211 char buf[32];
1213 if (strstr(filename, "://")) {
1214 sd_parse_uri(&cfg, filename, &err);
1215 } else {
1216 parse_vdiname(&cfg, filename, &err);
1218 if (err) {
1219 error_propagate(errp, err);
1220 return;
1223 if (cfg.path) {
1224 qdict_set_default_str(options, "server.path", cfg.path);
1225 qdict_set_default_str(options, "server.type", "unix");
1226 } else {
1227 qdict_set_default_str(options, "server.type", "inet");
1228 qdict_set_default_str(options, "server.host",
1229 cfg.host ?: SD_DEFAULT_ADDR);
1230 snprintf(buf, sizeof(buf), "%d", cfg.port ?: SD_DEFAULT_PORT);
1231 qdict_set_default_str(options, "server.port", buf);
1233 qdict_set_default_str(options, "vdi", cfg.vdi);
1234 qdict_set_default_str(options, "tag", cfg.tag);
1235 if (cfg.snap_id) {
1236 snprintf(buf, sizeof(buf), "%d", cfg.snap_id);
1237 qdict_set_default_str(options, "snap-id", buf);
1240 sd_config_done(&cfg);
1243 static int find_vdi_name(BDRVSheepdogState *s, const char *filename,
1244 uint32_t snapid, const char *tag, uint32_t *vid,
1245 bool lock, Error **errp)
1247 int ret, fd;
1248 SheepdogVdiReq hdr;
1249 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
1250 unsigned int wlen, rlen = 0;
1251 char buf[SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN];
1253 fd = connect_to_sdog(s, errp);
1254 if (fd < 0) {
1255 return fd;
1258 /* This pair of strncpy calls ensures that the buffer is zero-filled,
1259 * which is desirable since we'll soon be sending those bytes, and
1260 * don't want the send_req to read uninitialized data.
1262 strncpy(buf, filename, SD_MAX_VDI_LEN);
1263 strncpy(buf + SD_MAX_VDI_LEN, tag, SD_MAX_VDI_TAG_LEN);
1265 memset(&hdr, 0, sizeof(hdr));
1266 if (lock) {
1267 hdr.opcode = SD_OP_LOCK_VDI;
1268 hdr.type = LOCK_TYPE_NORMAL;
1269 } else {
1270 hdr.opcode = SD_OP_GET_VDI_INFO;
1272 wlen = SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN;
1273 hdr.proto_ver = SD_PROTO_VER;
1274 hdr.data_length = wlen;
1275 hdr.snapid = snapid;
1276 hdr.flags = SD_FLAG_CMD_WRITE;
1278 ret = do_req(fd, s->bs, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
1279 if (ret) {
1280 error_setg_errno(errp, -ret, "cannot get vdi info");
1281 goto out;
1284 if (rsp->result != SD_RES_SUCCESS) {
1285 error_setg(errp, "cannot get vdi info, %s, %s %" PRIu32 " %s",
1286 sd_strerror(rsp->result), filename, snapid, tag);
1287 if (rsp->result == SD_RES_NO_VDI) {
1288 ret = -ENOENT;
1289 } else if (rsp->result == SD_RES_VDI_LOCKED) {
1290 ret = -EBUSY;
1291 } else {
1292 ret = -EIO;
1294 goto out;
1296 *vid = rsp->vdi_id;
1298 ret = 0;
1299 out:
1300 closesocket(fd);
1301 return ret;
1304 static void coroutine_fn add_aio_request(BDRVSheepdogState *s, AIOReq *aio_req,
1305 struct iovec *iov, int niov,
1306 enum AIOCBState aiocb_type)
1308 int nr_copies = s->inode.nr_copies;
1309 SheepdogObjReq hdr;
1310 unsigned int wlen = 0;
1311 int ret;
1312 uint64_t oid = aio_req->oid;
1313 unsigned int datalen = aio_req->data_len;
1314 uint64_t offset = aio_req->offset;
1315 uint8_t flags = aio_req->flags;
1316 uint64_t old_oid = aio_req->base_oid;
1317 bool create = aio_req->create;
1319 qemu_co_mutex_lock(&s->queue_lock);
1320 QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
1321 qemu_co_mutex_unlock(&s->queue_lock);
1323 if (!nr_copies) {
1324 error_report("bug");
1327 memset(&hdr, 0, sizeof(hdr));
1329 switch (aiocb_type) {
1330 case AIOCB_FLUSH_CACHE:
1331 hdr.opcode = SD_OP_FLUSH_VDI;
1332 break;
1333 case AIOCB_READ_UDATA:
1334 hdr.opcode = SD_OP_READ_OBJ;
1335 hdr.flags = flags;
1336 break;
1337 case AIOCB_WRITE_UDATA:
1338 if (create) {
1339 hdr.opcode = SD_OP_CREATE_AND_WRITE_OBJ;
1340 } else {
1341 hdr.opcode = SD_OP_WRITE_OBJ;
1343 wlen = datalen;
1344 hdr.flags = SD_FLAG_CMD_WRITE | flags;
1345 break;
1346 case AIOCB_DISCARD_OBJ:
1347 hdr.opcode = SD_OP_WRITE_OBJ;
1348 hdr.flags = SD_FLAG_CMD_WRITE | flags;
1349 s->inode.data_vdi_id[data_oid_to_idx(oid)] = 0;
1350 offset = offsetof(SheepdogInode,
1351 data_vdi_id[data_oid_to_idx(oid)]);
1352 oid = vid_to_vdi_oid(s->inode.vdi_id);
1353 wlen = datalen = sizeof(uint32_t);
1354 break;
1357 if (s->cache_flags) {
1358 hdr.flags |= s->cache_flags;
1361 hdr.oid = oid;
1362 hdr.cow_oid = old_oid;
1363 hdr.copies = s->inode.nr_copies;
1365 hdr.data_length = datalen;
1366 hdr.offset = offset;
1368 hdr.id = aio_req->id;
1370 qemu_co_mutex_lock(&s->lock);
1371 s->co_send = qemu_coroutine_self();
1372 aio_set_fd_handler(s->aio_context, s->fd, false,
1373 co_read_response, co_write_request, NULL, s);
1374 socket_set_cork(s->fd, 1);
1376 /* send a header */
1377 ret = qemu_co_send(s->fd, &hdr, sizeof(hdr));
1378 if (ret != sizeof(hdr)) {
1379 error_report("failed to send a req, %s", strerror(errno));
1380 goto out;
1383 if (wlen) {
1384 ret = qemu_co_sendv(s->fd, iov, niov, aio_req->iov_offset, wlen);
1385 if (ret != wlen) {
1386 error_report("failed to send a data, %s", strerror(errno));
1389 out:
1390 socket_set_cork(s->fd, 0);
1391 aio_set_fd_handler(s->aio_context, s->fd, false,
1392 co_read_response, NULL, NULL, s);
1393 s->co_send = NULL;
1394 qemu_co_mutex_unlock(&s->lock);
1397 static int read_write_object(int fd, BlockDriverState *bs, char *buf,
1398 uint64_t oid, uint8_t copies,
1399 unsigned int datalen, uint64_t offset,
1400 bool write, bool create, uint32_t cache_flags)
1402 SheepdogObjReq hdr;
1403 SheepdogObjRsp *rsp = (SheepdogObjRsp *)&hdr;
1404 unsigned int wlen, rlen;
1405 int ret;
1407 memset(&hdr, 0, sizeof(hdr));
1409 if (write) {
1410 wlen = datalen;
1411 rlen = 0;
1412 hdr.flags = SD_FLAG_CMD_WRITE;
1413 if (create) {
1414 hdr.opcode = SD_OP_CREATE_AND_WRITE_OBJ;
1415 } else {
1416 hdr.opcode = SD_OP_WRITE_OBJ;
1418 } else {
1419 wlen = 0;
1420 rlen = datalen;
1421 hdr.opcode = SD_OP_READ_OBJ;
1424 hdr.flags |= cache_flags;
1426 hdr.oid = oid;
1427 hdr.data_length = datalen;
1428 hdr.offset = offset;
1429 hdr.copies = copies;
1431 ret = do_req(fd, bs, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
1432 if (ret) {
1433 error_report("failed to send a request to the sheep");
1434 return ret;
1437 switch (rsp->result) {
1438 case SD_RES_SUCCESS:
1439 return 0;
1440 default:
1441 error_report("%s", sd_strerror(rsp->result));
1442 return -EIO;
1446 static int read_object(int fd, BlockDriverState *bs, char *buf,
1447 uint64_t oid, uint8_t copies,
1448 unsigned int datalen, uint64_t offset,
1449 uint32_t cache_flags)
1451 return read_write_object(fd, bs, buf, oid, copies,
1452 datalen, offset, false,
1453 false, cache_flags);
1456 static int write_object(int fd, BlockDriverState *bs, char *buf,
1457 uint64_t oid, uint8_t copies,
1458 unsigned int datalen, uint64_t offset, bool create,
1459 uint32_t cache_flags)
1461 return read_write_object(fd, bs, buf, oid, copies,
1462 datalen, offset, true,
1463 create, cache_flags);
1466 /* update inode with the latest state */
1467 static int reload_inode(BDRVSheepdogState *s, uint32_t snapid, const char *tag)
1469 Error *local_err = NULL;
1470 SheepdogInode *inode;
1471 int ret = 0, fd;
1472 uint32_t vid = 0;
1474 fd = connect_to_sdog(s, &local_err);
1475 if (fd < 0) {
1476 error_report_err(local_err);
1477 return -EIO;
1480 inode = g_malloc(SD_INODE_HEADER_SIZE);
1482 ret = find_vdi_name(s, s->name, snapid, tag, &vid, false, &local_err);
1483 if (ret) {
1484 error_report_err(local_err);
1485 goto out;
1488 ret = read_object(fd, s->bs, (char *)inode, vid_to_vdi_oid(vid),
1489 s->inode.nr_copies, SD_INODE_HEADER_SIZE, 0,
1490 s->cache_flags);
1491 if (ret < 0) {
1492 goto out;
1495 if (inode->vdi_id != s->inode.vdi_id) {
1496 memcpy(&s->inode, inode, SD_INODE_HEADER_SIZE);
1499 out:
1500 g_free(inode);
1501 closesocket(fd);
1503 return ret;
1506 static void coroutine_fn resend_aioreq(BDRVSheepdogState *s, AIOReq *aio_req)
1508 SheepdogAIOCB *acb = aio_req->aiocb;
1510 aio_req->create = false;
1512 /* check whether this request becomes a CoW one */
1513 if (acb->aiocb_type == AIOCB_WRITE_UDATA && is_data_obj(aio_req->oid)) {
1514 int idx = data_oid_to_idx(aio_req->oid);
1516 if (is_data_obj_writable(&s->inode, idx)) {
1517 goto out;
1520 if (s->inode.data_vdi_id[idx]) {
1521 aio_req->base_oid = vid_to_data_oid(s->inode.data_vdi_id[idx], idx);
1522 aio_req->flags |= SD_FLAG_CMD_COW;
1524 aio_req->create = true;
1526 out:
1527 if (is_data_obj(aio_req->oid)) {
1528 add_aio_request(s, aio_req, acb->qiov->iov, acb->qiov->niov,
1529 acb->aiocb_type);
1530 } else {
1531 struct iovec iov;
1532 iov.iov_base = &s->inode;
1533 iov.iov_len = sizeof(s->inode);
1534 add_aio_request(s, aio_req, &iov, 1, AIOCB_WRITE_UDATA);
1538 static void sd_detach_aio_context(BlockDriverState *bs)
1540 BDRVSheepdogState *s = bs->opaque;
1542 aio_set_fd_handler(s->aio_context, s->fd, false, NULL,
1543 NULL, NULL, NULL);
1546 static void sd_attach_aio_context(BlockDriverState *bs,
1547 AioContext *new_context)
1549 BDRVSheepdogState *s = bs->opaque;
1551 s->aio_context = new_context;
1552 aio_set_fd_handler(new_context, s->fd, false,
1553 co_read_response, NULL, NULL, s);
1556 static QemuOptsList runtime_opts = {
1557 .name = "sheepdog",
1558 .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
1559 .desc = {
1561 .name = "vdi",
1562 .type = QEMU_OPT_STRING,
1565 .name = "snap-id",
1566 .type = QEMU_OPT_NUMBER,
1569 .name = "tag",
1570 .type = QEMU_OPT_STRING,
1572 { /* end of list */ }
1576 static int sd_open(BlockDriverState *bs, QDict *options, int flags,
1577 Error **errp)
1579 int ret, fd;
1580 uint32_t vid = 0;
1581 BDRVSheepdogState *s = bs->opaque;
1582 const char *vdi, *snap_id_str, *tag;
1583 uint64_t snap_id;
1584 char *buf = NULL;
1585 QemuOpts *opts;
1586 Error *local_err = NULL;
1588 s->bs = bs;
1589 s->aio_context = bdrv_get_aio_context(bs);
1591 opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
1592 qemu_opts_absorb_qdict(opts, options, &local_err);
1593 if (local_err) {
1594 error_propagate(errp, local_err);
1595 ret = -EINVAL;
1596 goto err_no_fd;
1599 s->addr = sd_server_config(options, errp);
1600 if (!s->addr) {
1601 ret = -EINVAL;
1602 goto err_no_fd;
1605 vdi = qemu_opt_get(opts, "vdi");
1606 snap_id_str = qemu_opt_get(opts, "snap-id");
1607 snap_id = qemu_opt_get_number(opts, "snap-id", CURRENT_VDI_ID);
1608 tag = qemu_opt_get(opts, "tag");
1610 if (!vdi) {
1611 error_setg(errp, "parameter 'vdi' is missing");
1612 ret = -EINVAL;
1613 goto err_no_fd;
1615 if (strlen(vdi) >= SD_MAX_VDI_LEN) {
1616 error_setg(errp, "value of parameter 'vdi' is too long");
1617 ret = -EINVAL;
1618 goto err_no_fd;
1621 if (snap_id > UINT32_MAX) {
1622 snap_id = 0;
1624 if (snap_id_str && !snap_id) {
1625 error_setg(errp, "'snap-id=%s' is not a valid snapshot ID",
1626 snap_id_str);
1627 ret = -EINVAL;
1628 goto err_no_fd;
1631 if (!tag) {
1632 tag = "";
1634 if (strlen(tag) >= SD_MAX_VDI_TAG_LEN) {
1635 error_setg(errp, "value of parameter 'tag' is too long");
1636 ret = -EINVAL;
1637 goto err_no_fd;
1640 QLIST_INIT(&s->inflight_aio_head);
1641 QLIST_INIT(&s->failed_aio_head);
1642 QLIST_INIT(&s->inflight_aiocb_head);
1644 s->fd = get_sheep_fd(s, errp);
1645 if (s->fd < 0) {
1646 ret = s->fd;
1647 goto err_no_fd;
1650 ret = find_vdi_name(s, vdi, (uint32_t)snap_id, tag, &vid, true, errp);
1651 if (ret) {
1652 goto err;
1656 * QEMU block layer emulates writethrough cache as 'writeback + flush', so
1657 * we always set SD_FLAG_CMD_CACHE (writeback cache) as default.
1659 s->cache_flags = SD_FLAG_CMD_CACHE;
1660 if (flags & BDRV_O_NOCACHE) {
1661 s->cache_flags = SD_FLAG_CMD_DIRECT;
1663 s->discard_supported = true;
1665 if (snap_id || tag[0]) {
1666 DPRINTF("%" PRIx32 " snapshot inode was open.\n", vid);
1667 s->is_snapshot = true;
1670 fd = connect_to_sdog(s, errp);
1671 if (fd < 0) {
1672 ret = fd;
1673 goto err;
1676 buf = g_malloc(SD_INODE_SIZE);
1677 ret = read_object(fd, s->bs, buf, vid_to_vdi_oid(vid),
1678 0, SD_INODE_SIZE, 0, s->cache_flags);
1680 closesocket(fd);
1682 if (ret) {
1683 error_setg(errp, "Can't read snapshot inode");
1684 goto err;
1687 memcpy(&s->inode, buf, sizeof(s->inode));
1689 bs->total_sectors = s->inode.vdi_size / BDRV_SECTOR_SIZE;
1690 pstrcpy(s->name, sizeof(s->name), vdi);
1691 qemu_co_mutex_init(&s->lock);
1692 qemu_co_mutex_init(&s->queue_lock);
1693 qemu_co_queue_init(&s->overlapping_queue);
1694 qemu_opts_del(opts);
1695 g_free(buf);
1696 return 0;
1698 err:
1699 aio_set_fd_handler(bdrv_get_aio_context(bs), s->fd,
1700 false, NULL, NULL, NULL, NULL);
1701 closesocket(s->fd);
1702 err_no_fd:
1703 qemu_opts_del(opts);
1704 g_free(buf);
1705 return ret;
1708 static int sd_reopen_prepare(BDRVReopenState *state, BlockReopenQueue *queue,
1709 Error **errp)
1711 BDRVSheepdogState *s = state->bs->opaque;
1712 BDRVSheepdogReopenState *re_s;
1713 int ret = 0;
1715 re_s = state->opaque = g_new0(BDRVSheepdogReopenState, 1);
1717 re_s->cache_flags = SD_FLAG_CMD_CACHE;
1718 if (state->flags & BDRV_O_NOCACHE) {
1719 re_s->cache_flags = SD_FLAG_CMD_DIRECT;
1722 re_s->fd = get_sheep_fd(s, errp);
1723 if (re_s->fd < 0) {
1724 ret = re_s->fd;
1725 return ret;
1728 return ret;
1731 static void sd_reopen_commit(BDRVReopenState *state)
1733 BDRVSheepdogReopenState *re_s = state->opaque;
1734 BDRVSheepdogState *s = state->bs->opaque;
1736 if (s->fd) {
1737 aio_set_fd_handler(s->aio_context, s->fd, false,
1738 NULL, NULL, NULL, NULL);
1739 closesocket(s->fd);
1742 s->fd = re_s->fd;
1743 s->cache_flags = re_s->cache_flags;
1745 g_free(state->opaque);
1746 state->opaque = NULL;
1748 return;
1751 static void sd_reopen_abort(BDRVReopenState *state)
1753 BDRVSheepdogReopenState *re_s = state->opaque;
1754 BDRVSheepdogState *s = state->bs->opaque;
1756 if (re_s == NULL) {
1757 return;
1760 if (re_s->fd) {
1761 aio_set_fd_handler(s->aio_context, re_s->fd, false,
1762 NULL, NULL, NULL, NULL);
1763 closesocket(re_s->fd);
1766 g_free(state->opaque);
1767 state->opaque = NULL;
1769 return;
1772 static int do_sd_create(BDRVSheepdogState *s, uint32_t *vdi_id, int snapshot,
1773 Error **errp)
1775 SheepdogVdiReq hdr;
1776 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
1777 int fd, ret;
1778 unsigned int wlen, rlen = 0;
1779 char buf[SD_MAX_VDI_LEN];
1781 fd = connect_to_sdog(s, errp);
1782 if (fd < 0) {
1783 return fd;
1786 /* FIXME: would it be better to fail (e.g., return -EIO) when filename
1787 * does not fit in buf? For now, just truncate and avoid buffer overrun.
1789 memset(buf, 0, sizeof(buf));
1790 pstrcpy(buf, sizeof(buf), s->name);
1792 memset(&hdr, 0, sizeof(hdr));
1793 hdr.opcode = SD_OP_NEW_VDI;
1794 hdr.base_vdi_id = s->inode.vdi_id;
1796 wlen = SD_MAX_VDI_LEN;
1798 hdr.flags = SD_FLAG_CMD_WRITE;
1799 hdr.snapid = snapshot;
1801 hdr.data_length = wlen;
1802 hdr.vdi_size = s->inode.vdi_size;
1803 hdr.copy_policy = s->inode.copy_policy;
1804 hdr.copies = s->inode.nr_copies;
1805 hdr.block_size_shift = s->inode.block_size_shift;
1807 ret = do_req(fd, NULL, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
1809 closesocket(fd);
1811 if (ret) {
1812 error_setg_errno(errp, -ret, "create failed");
1813 return ret;
1816 if (rsp->result != SD_RES_SUCCESS) {
1817 error_setg(errp, "%s, %s", sd_strerror(rsp->result), s->inode.name);
1818 return -EIO;
1821 if (vdi_id) {
1822 *vdi_id = rsp->vdi_id;
1825 return 0;
1828 static int sd_prealloc(const char *filename, Error **errp)
1830 BlockBackend *blk = NULL;
1831 BDRVSheepdogState *base = NULL;
1832 unsigned long buf_size;
1833 uint32_t idx, max_idx;
1834 uint32_t object_size;
1835 int64_t vdi_size;
1836 void *buf = NULL;
1837 int ret;
1839 blk = blk_new_open(filename, NULL, NULL,
1840 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL, errp);
1841 if (blk == NULL) {
1842 ret = -EIO;
1843 goto out_with_err_set;
1846 blk_set_allow_write_beyond_eof(blk, true);
1848 vdi_size = blk_getlength(blk);
1849 if (vdi_size < 0) {
1850 ret = vdi_size;
1851 goto out;
1854 base = blk_bs(blk)->opaque;
1855 object_size = (UINT32_C(1) << base->inode.block_size_shift);
1856 buf_size = MIN(object_size, SD_DATA_OBJ_SIZE);
1857 buf = g_malloc0(buf_size);
1859 max_idx = DIV_ROUND_UP(vdi_size, buf_size);
1861 for (idx = 0; idx < max_idx; idx++) {
1863 * The created image can be a cloned image, so we need to read
1864 * a data from the source image.
1866 ret = blk_pread(blk, idx * buf_size, buf, buf_size);
1867 if (ret < 0) {
1868 goto out;
1870 ret = blk_pwrite(blk, idx * buf_size, buf, buf_size, 0);
1871 if (ret < 0) {
1872 goto out;
1876 ret = 0;
1877 out:
1878 if (ret < 0) {
1879 error_setg_errno(errp, -ret, "Can't pre-allocate");
1881 out_with_err_set:
1882 if (blk) {
1883 blk_unref(blk);
1885 g_free(buf);
1887 return ret;
1891 * Sheepdog support two kinds of redundancy, full replication and erasure
1892 * coding.
1894 * # create a fully replicated vdi with x copies
1895 * -o redundancy=x (1 <= x <= SD_MAX_COPIES)
1897 * # create a erasure coded vdi with x data strips and y parity strips
1898 * -o redundancy=x:y (x must be one of {2,4,8,16} and 1 <= y < SD_EC_MAX_STRIP)
1900 static int parse_redundancy(BDRVSheepdogState *s, const char *opt)
1902 struct SheepdogInode *inode = &s->inode;
1903 const char *n1, *n2;
1904 long copy, parity;
1905 char p[10];
1907 pstrcpy(p, sizeof(p), opt);
1908 n1 = strtok(p, ":");
1909 n2 = strtok(NULL, ":");
1911 if (!n1) {
1912 return -EINVAL;
1915 copy = strtol(n1, NULL, 10);
1916 /* FIXME fix error checking by switching to qemu_strtol() */
1917 if (copy > SD_MAX_COPIES || copy < 1) {
1918 return -EINVAL;
1920 if (!n2) {
1921 inode->copy_policy = 0;
1922 inode->nr_copies = copy;
1923 return 0;
1926 if (copy != 2 && copy != 4 && copy != 8 && copy != 16) {
1927 return -EINVAL;
1930 parity = strtol(n2, NULL, 10);
1931 /* FIXME fix error checking by switching to qemu_strtol() */
1932 if (parity >= SD_EC_MAX_STRIP || parity < 1) {
1933 return -EINVAL;
1937 * 4 bits for parity and 4 bits for data.
1938 * We have to compress upper data bits because it can't represent 16
1940 inode->copy_policy = ((copy / 2) << 4) + parity;
1941 inode->nr_copies = copy + parity;
1943 return 0;
1946 static int parse_block_size_shift(BDRVSheepdogState *s, QemuOpts *opt)
1948 struct SheepdogInode *inode = &s->inode;
1949 uint64_t object_size;
1950 int obj_order;
1952 object_size = qemu_opt_get_size_del(opt, BLOCK_OPT_OBJECT_SIZE, 0);
1953 if (object_size) {
1954 if ((object_size - 1) & object_size) { /* not a power of 2? */
1955 return -EINVAL;
1957 obj_order = ctz32(object_size);
1958 if (obj_order < 20 || obj_order > 31) {
1959 return -EINVAL;
1961 inode->block_size_shift = (uint8_t)obj_order;
1964 return 0;
1967 static int sd_create(const char *filename, QemuOpts *opts,
1968 Error **errp)
1970 Error *err = NULL;
1971 int ret = 0;
1972 uint32_t vid = 0;
1973 char *backing_file = NULL;
1974 char *buf = NULL;
1975 BDRVSheepdogState *s;
1976 SheepdogConfig cfg;
1977 uint64_t max_vdi_size;
1978 bool prealloc = false;
1980 s = g_new0(BDRVSheepdogState, 1);
1982 if (strstr(filename, "://")) {
1983 sd_parse_uri(&cfg, filename, &err);
1984 } else {
1985 parse_vdiname(&cfg, filename, &err);
1987 if (err) {
1988 error_propagate(errp, err);
1989 goto out;
1992 buf = cfg.port ? g_strdup_printf("%d", cfg.port) : NULL;
1993 s->addr = sd_socket_address(cfg.path, cfg.host, buf);
1994 g_free(buf);
1995 strcpy(s->name, cfg.vdi);
1996 sd_config_done(&cfg);
1998 s->inode.vdi_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
1999 BDRV_SECTOR_SIZE);
2000 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
2001 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
2002 if (!buf || !strcmp(buf, "off")) {
2003 prealloc = false;
2004 } else if (!strcmp(buf, "full")) {
2005 prealloc = true;
2006 } else {
2007 error_setg(errp, "Invalid preallocation mode: '%s'", buf);
2008 ret = -EINVAL;
2009 goto out;
2012 g_free(buf);
2013 buf = qemu_opt_get_del(opts, BLOCK_OPT_REDUNDANCY);
2014 if (buf) {
2015 ret = parse_redundancy(s, buf);
2016 if (ret < 0) {
2017 error_setg(errp, "Invalid redundancy mode: '%s'", buf);
2018 goto out;
2021 ret = parse_block_size_shift(s, opts);
2022 if (ret < 0) {
2023 error_setg(errp, "Invalid object_size."
2024 " obect_size needs to be power of 2"
2025 " and be limited from 2^20 to 2^31");
2026 goto out;
2029 if (backing_file) {
2030 BlockBackend *blk;
2031 BDRVSheepdogState *base;
2032 BlockDriver *drv;
2034 /* Currently, only Sheepdog backing image is supported. */
2035 drv = bdrv_find_protocol(backing_file, true, NULL);
2036 if (!drv || strcmp(drv->protocol_name, "sheepdog") != 0) {
2037 error_setg(errp, "backing_file must be a sheepdog image");
2038 ret = -EINVAL;
2039 goto out;
2042 blk = blk_new_open(backing_file, NULL, NULL,
2043 BDRV_O_PROTOCOL, errp);
2044 if (blk == NULL) {
2045 ret = -EIO;
2046 goto out;
2049 base = blk_bs(blk)->opaque;
2051 if (!is_snapshot(&base->inode)) {
2052 error_setg(errp, "cannot clone from a non snapshot vdi");
2053 blk_unref(blk);
2054 ret = -EINVAL;
2055 goto out;
2057 s->inode.vdi_id = base->inode.vdi_id;
2058 blk_unref(blk);
2061 s->aio_context = qemu_get_aio_context();
2063 /* if block_size_shift is not specified, get cluster default value */
2064 if (s->inode.block_size_shift == 0) {
2065 SheepdogVdiReq hdr;
2066 SheepdogClusterRsp *rsp = (SheepdogClusterRsp *)&hdr;
2067 int fd;
2068 unsigned int wlen = 0, rlen = 0;
2070 fd = connect_to_sdog(s, errp);
2071 if (fd < 0) {
2072 ret = fd;
2073 goto out;
2076 memset(&hdr, 0, sizeof(hdr));
2077 hdr.opcode = SD_OP_GET_CLUSTER_DEFAULT;
2078 hdr.proto_ver = SD_PROTO_VER;
2080 ret = do_req(fd, NULL, (SheepdogReq *)&hdr,
2081 NULL, &wlen, &rlen);
2082 closesocket(fd);
2083 if (ret) {
2084 error_setg_errno(errp, -ret, "failed to get cluster default");
2085 goto out;
2087 if (rsp->result == SD_RES_SUCCESS) {
2088 s->inode.block_size_shift = rsp->block_size_shift;
2089 } else {
2090 s->inode.block_size_shift = SD_DEFAULT_BLOCK_SIZE_SHIFT;
2094 max_vdi_size = (UINT64_C(1) << s->inode.block_size_shift) * MAX_DATA_OBJS;
2096 if (s->inode.vdi_size > max_vdi_size) {
2097 error_setg(errp, "An image is too large."
2098 " The maximum image size is %"PRIu64 "GB",
2099 max_vdi_size / 1024 / 1024 / 1024);
2100 ret = -EINVAL;
2101 goto out;
2104 ret = do_sd_create(s, &vid, 0, errp);
2105 if (ret) {
2106 goto out;
2109 if (prealloc) {
2110 ret = sd_prealloc(filename, errp);
2112 out:
2113 g_free(backing_file);
2114 g_free(buf);
2115 g_free(s);
2116 return ret;
2119 static void sd_close(BlockDriverState *bs)
2121 Error *local_err = NULL;
2122 BDRVSheepdogState *s = bs->opaque;
2123 SheepdogVdiReq hdr;
2124 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
2125 unsigned int wlen, rlen = 0;
2126 int fd, ret;
2128 DPRINTF("%s\n", s->name);
2130 fd = connect_to_sdog(s, &local_err);
2131 if (fd < 0) {
2132 error_report_err(local_err);
2133 return;
2136 memset(&hdr, 0, sizeof(hdr));
2138 hdr.opcode = SD_OP_RELEASE_VDI;
2139 hdr.type = LOCK_TYPE_NORMAL;
2140 hdr.base_vdi_id = s->inode.vdi_id;
2141 wlen = strlen(s->name) + 1;
2142 hdr.data_length = wlen;
2143 hdr.flags = SD_FLAG_CMD_WRITE;
2145 ret = do_req(fd, s->bs, (SheepdogReq *)&hdr,
2146 s->name, &wlen, &rlen);
2148 closesocket(fd);
2150 if (!ret && rsp->result != SD_RES_SUCCESS &&
2151 rsp->result != SD_RES_VDI_NOT_LOCKED) {
2152 error_report("%s, %s", sd_strerror(rsp->result), s->name);
2155 aio_set_fd_handler(bdrv_get_aio_context(bs), s->fd,
2156 false, NULL, NULL, NULL, NULL);
2157 closesocket(s->fd);
2158 qapi_free_SocketAddress(s->addr);
2161 static int64_t sd_getlength(BlockDriverState *bs)
2163 BDRVSheepdogState *s = bs->opaque;
2165 return s->inode.vdi_size;
2168 static int sd_truncate(BlockDriverState *bs, int64_t offset,
2169 PreallocMode prealloc, Error **errp)
2171 BDRVSheepdogState *s = bs->opaque;
2172 int ret, fd;
2173 unsigned int datalen;
2174 uint64_t max_vdi_size;
2176 if (prealloc != PREALLOC_MODE_OFF) {
2177 error_setg(errp, "Unsupported preallocation mode '%s'",
2178 PreallocMode_str(prealloc));
2179 return -ENOTSUP;
2182 max_vdi_size = (UINT64_C(1) << s->inode.block_size_shift) * MAX_DATA_OBJS;
2183 if (offset < s->inode.vdi_size) {
2184 error_setg(errp, "shrinking is not supported");
2185 return -EINVAL;
2186 } else if (offset > max_vdi_size) {
2187 error_setg(errp, "too big image size");
2188 return -EINVAL;
2191 fd = connect_to_sdog(s, errp);
2192 if (fd < 0) {
2193 return fd;
2196 /* we don't need to update entire object */
2197 datalen = SD_INODE_SIZE - sizeof(s->inode.data_vdi_id);
2198 s->inode.vdi_size = offset;
2199 ret = write_object(fd, s->bs, (char *)&s->inode,
2200 vid_to_vdi_oid(s->inode.vdi_id), s->inode.nr_copies,
2201 datalen, 0, false, s->cache_flags);
2202 close(fd);
2204 if (ret < 0) {
2205 error_setg_errno(errp, -ret, "failed to update an inode");
2208 return ret;
2212 * This function is called after writing data objects. If we need to
2213 * update metadata, this sends a write request to the vdi object.
2215 static void coroutine_fn sd_write_done(SheepdogAIOCB *acb)
2217 BDRVSheepdogState *s = acb->s;
2218 struct iovec iov;
2219 AIOReq *aio_req;
2220 uint32_t offset, data_len, mn, mx;
2222 mn = acb->min_dirty_data_idx;
2223 mx = acb->max_dirty_data_idx;
2224 if (mn <= mx) {
2225 /* we need to update the vdi object. */
2226 ++acb->nr_pending;
2227 offset = sizeof(s->inode) - sizeof(s->inode.data_vdi_id) +
2228 mn * sizeof(s->inode.data_vdi_id[0]);
2229 data_len = (mx - mn + 1) * sizeof(s->inode.data_vdi_id[0]);
2231 acb->min_dirty_data_idx = UINT32_MAX;
2232 acb->max_dirty_data_idx = 0;
2234 iov.iov_base = &s->inode;
2235 iov.iov_len = sizeof(s->inode);
2236 aio_req = alloc_aio_req(s, acb, vid_to_vdi_oid(s->inode.vdi_id),
2237 data_len, offset, 0, false, 0, offset);
2238 add_aio_request(s, aio_req, &iov, 1, AIOCB_WRITE_UDATA);
2239 if (--acb->nr_pending) {
2240 qemu_coroutine_yield();
2245 /* Delete current working VDI on the snapshot chain */
2246 static bool sd_delete(BDRVSheepdogState *s)
2248 Error *local_err = NULL;
2249 unsigned int wlen = SD_MAX_VDI_LEN, rlen = 0;
2250 SheepdogVdiReq hdr = {
2251 .opcode = SD_OP_DEL_VDI,
2252 .base_vdi_id = s->inode.vdi_id,
2253 .data_length = wlen,
2254 .flags = SD_FLAG_CMD_WRITE,
2256 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
2257 int fd, ret;
2259 fd = connect_to_sdog(s, &local_err);
2260 if (fd < 0) {
2261 error_report_err(local_err);
2262 return false;
2265 ret = do_req(fd, s->bs, (SheepdogReq *)&hdr,
2266 s->name, &wlen, &rlen);
2267 closesocket(fd);
2268 if (ret) {
2269 return false;
2271 switch (rsp->result) {
2272 case SD_RES_NO_VDI:
2273 error_report("%s was already deleted", s->name);
2274 /* fall through */
2275 case SD_RES_SUCCESS:
2276 break;
2277 default:
2278 error_report("%s, %s", sd_strerror(rsp->result), s->name);
2279 return false;
2282 return true;
2286 * Create a writable VDI from a snapshot
2288 static int sd_create_branch(BDRVSheepdogState *s)
2290 Error *local_err = NULL;
2291 int ret, fd;
2292 uint32_t vid;
2293 char *buf;
2294 bool deleted;
2296 DPRINTF("%" PRIx32 " is snapshot.\n", s->inode.vdi_id);
2298 buf = g_malloc(SD_INODE_SIZE);
2301 * Even If deletion fails, we will just create extra snapshot based on
2302 * the working VDI which was supposed to be deleted. So no need to
2303 * false bail out.
2305 deleted = sd_delete(s);
2306 ret = do_sd_create(s, &vid, !deleted, &local_err);
2307 if (ret) {
2308 error_report_err(local_err);
2309 goto out;
2312 DPRINTF("%" PRIx32 " is created.\n", vid);
2314 fd = connect_to_sdog(s, &local_err);
2315 if (fd < 0) {
2316 error_report_err(local_err);
2317 ret = fd;
2318 goto out;
2321 ret = read_object(fd, s->bs, buf, vid_to_vdi_oid(vid),
2322 s->inode.nr_copies, SD_INODE_SIZE, 0, s->cache_flags);
2324 closesocket(fd);
2326 if (ret < 0) {
2327 goto out;
2330 memcpy(&s->inode, buf, sizeof(s->inode));
2332 s->is_snapshot = false;
2333 ret = 0;
2334 DPRINTF("%" PRIx32 " was newly created.\n", s->inode.vdi_id);
2336 out:
2337 g_free(buf);
2339 return ret;
2343 * Send I/O requests to the server.
2345 * This function sends requests to the server, links the requests to
2346 * the inflight_list in BDRVSheepdogState, and exits without
2347 * waiting the response. The responses are received in the
2348 * `aio_read_response' function which is called from the main loop as
2349 * a fd handler.
2351 * Returns 1 when we need to wait a response, 0 when there is no sent
2352 * request and -errno in error cases.
2354 static void coroutine_fn sd_co_rw_vector(SheepdogAIOCB *acb)
2356 int ret = 0;
2357 unsigned long len, done = 0, total = acb->nb_sectors * BDRV_SECTOR_SIZE;
2358 unsigned long idx;
2359 uint32_t object_size;
2360 uint64_t oid;
2361 uint64_t offset;
2362 BDRVSheepdogState *s = acb->s;
2363 SheepdogInode *inode = &s->inode;
2364 AIOReq *aio_req;
2366 if (acb->aiocb_type == AIOCB_WRITE_UDATA && s->is_snapshot) {
2368 * In the case we open the snapshot VDI, Sheepdog creates the
2369 * writable VDI when we do a write operation first.
2371 ret = sd_create_branch(s);
2372 if (ret) {
2373 acb->ret = -EIO;
2374 return;
2378 object_size = (UINT32_C(1) << inode->block_size_shift);
2379 idx = acb->sector_num * BDRV_SECTOR_SIZE / object_size;
2380 offset = (acb->sector_num * BDRV_SECTOR_SIZE) % object_size;
2383 * Make sure we don't free the aiocb before we are done with all requests.
2384 * This additional reference is dropped at the end of this function.
2386 acb->nr_pending++;
2388 while (done != total) {
2389 uint8_t flags = 0;
2390 uint64_t old_oid = 0;
2391 bool create = false;
2393 oid = vid_to_data_oid(inode->data_vdi_id[idx], idx);
2395 len = MIN(total - done, object_size - offset);
2397 switch (acb->aiocb_type) {
2398 case AIOCB_READ_UDATA:
2399 if (!inode->data_vdi_id[idx]) {
2400 qemu_iovec_memset(acb->qiov, done, 0, len);
2401 goto done;
2403 break;
2404 case AIOCB_WRITE_UDATA:
2405 if (!inode->data_vdi_id[idx]) {
2406 create = true;
2407 } else if (!is_data_obj_writable(inode, idx)) {
2408 /* Copy-On-Write */
2409 create = true;
2410 old_oid = oid;
2411 flags = SD_FLAG_CMD_COW;
2413 break;
2414 case AIOCB_DISCARD_OBJ:
2416 * We discard the object only when the whole object is
2417 * 1) allocated 2) trimmed. Otherwise, simply skip it.
2419 if (len != object_size || inode->data_vdi_id[idx] == 0) {
2420 goto done;
2422 break;
2423 default:
2424 break;
2427 if (create) {
2428 DPRINTF("update ino (%" PRIu32 ") %" PRIu64 " %" PRIu64 " %ld\n",
2429 inode->vdi_id, oid,
2430 vid_to_data_oid(inode->data_vdi_id[idx], idx), idx);
2431 oid = vid_to_data_oid(inode->vdi_id, idx);
2432 DPRINTF("new oid %" PRIx64 "\n", oid);
2435 aio_req = alloc_aio_req(s, acb, oid, len, offset, flags, create,
2436 old_oid,
2437 acb->aiocb_type == AIOCB_DISCARD_OBJ ?
2438 0 : done);
2439 add_aio_request(s, aio_req, acb->qiov->iov, acb->qiov->niov,
2440 acb->aiocb_type);
2441 done:
2442 offset = 0;
2443 idx++;
2444 done += len;
2446 if (--acb->nr_pending) {
2447 qemu_coroutine_yield();
2451 static void sd_aio_complete(SheepdogAIOCB *acb)
2453 BDRVSheepdogState *s;
2454 if (acb->aiocb_type == AIOCB_FLUSH_CACHE) {
2455 return;
2458 s = acb->s;
2459 qemu_co_mutex_lock(&s->queue_lock);
2460 QLIST_REMOVE(acb, aiocb_siblings);
2461 qemu_co_queue_restart_all(&s->overlapping_queue);
2462 qemu_co_mutex_unlock(&s->queue_lock);
2465 static coroutine_fn int sd_co_writev(BlockDriverState *bs, int64_t sector_num,
2466 int nb_sectors, QEMUIOVector *qiov)
2468 SheepdogAIOCB acb;
2469 int ret;
2470 int64_t offset = (sector_num + nb_sectors) * BDRV_SECTOR_SIZE;
2471 BDRVSheepdogState *s = bs->opaque;
2473 if (offset > s->inode.vdi_size) {
2474 ret = sd_truncate(bs, offset, PREALLOC_MODE_OFF, NULL);
2475 if (ret < 0) {
2476 return ret;
2480 sd_aio_setup(&acb, s, qiov, sector_num, nb_sectors, AIOCB_WRITE_UDATA);
2481 sd_co_rw_vector(&acb);
2482 sd_write_done(&acb);
2483 sd_aio_complete(&acb);
2485 return acb.ret;
2488 static coroutine_fn int sd_co_readv(BlockDriverState *bs, int64_t sector_num,
2489 int nb_sectors, QEMUIOVector *qiov)
2491 SheepdogAIOCB acb;
2492 BDRVSheepdogState *s = bs->opaque;
2494 sd_aio_setup(&acb, s, qiov, sector_num, nb_sectors, AIOCB_READ_UDATA);
2495 sd_co_rw_vector(&acb);
2496 sd_aio_complete(&acb);
2498 return acb.ret;
2501 static int coroutine_fn sd_co_flush_to_disk(BlockDriverState *bs)
2503 BDRVSheepdogState *s = bs->opaque;
2504 SheepdogAIOCB acb;
2505 AIOReq *aio_req;
2507 if (s->cache_flags != SD_FLAG_CMD_CACHE) {
2508 return 0;
2511 sd_aio_setup(&acb, s, NULL, 0, 0, AIOCB_FLUSH_CACHE);
2513 acb.nr_pending++;
2514 aio_req = alloc_aio_req(s, &acb, vid_to_vdi_oid(s->inode.vdi_id),
2515 0, 0, 0, false, 0, 0);
2516 add_aio_request(s, aio_req, NULL, 0, acb.aiocb_type);
2518 if (--acb.nr_pending) {
2519 qemu_coroutine_yield();
2522 sd_aio_complete(&acb);
2523 return acb.ret;
2526 static int sd_snapshot_create(BlockDriverState *bs, QEMUSnapshotInfo *sn_info)
2528 Error *local_err = NULL;
2529 BDRVSheepdogState *s = bs->opaque;
2530 int ret, fd;
2531 uint32_t new_vid;
2532 SheepdogInode *inode;
2533 unsigned int datalen;
2535 DPRINTF("sn_info: name %s id_str %s s: name %s vm_state_size %" PRId64 " "
2536 "is_snapshot %d\n", sn_info->name, sn_info->id_str,
2537 s->name, sn_info->vm_state_size, s->is_snapshot);
2539 if (s->is_snapshot) {
2540 error_report("You can't create a snapshot of a snapshot VDI, "
2541 "%s (%" PRIu32 ").", s->name, s->inode.vdi_id);
2543 return -EINVAL;
2546 DPRINTF("%s %s\n", sn_info->name, sn_info->id_str);
2548 s->inode.vm_state_size = sn_info->vm_state_size;
2549 s->inode.vm_clock_nsec = sn_info->vm_clock_nsec;
2550 /* It appears that inode.tag does not require a NUL terminator,
2551 * which means this use of strncpy is ok.
2553 strncpy(s->inode.tag, sn_info->name, sizeof(s->inode.tag));
2554 /* we don't need to update entire object */
2555 datalen = SD_INODE_SIZE - sizeof(s->inode.data_vdi_id);
2556 inode = g_malloc(datalen);
2558 /* refresh inode. */
2559 fd = connect_to_sdog(s, &local_err);
2560 if (fd < 0) {
2561 error_report_err(local_err);
2562 ret = fd;
2563 goto cleanup;
2566 ret = write_object(fd, s->bs, (char *)&s->inode,
2567 vid_to_vdi_oid(s->inode.vdi_id), s->inode.nr_copies,
2568 datalen, 0, false, s->cache_flags);
2569 if (ret < 0) {
2570 error_report("failed to write snapshot's inode.");
2571 goto cleanup;
2574 ret = do_sd_create(s, &new_vid, 1, &local_err);
2575 if (ret < 0) {
2576 error_reportf_err(local_err,
2577 "failed to create inode for snapshot: ");
2578 goto cleanup;
2581 ret = read_object(fd, s->bs, (char *)inode,
2582 vid_to_vdi_oid(new_vid), s->inode.nr_copies, datalen, 0,
2583 s->cache_flags);
2585 if (ret < 0) {
2586 error_report("failed to read new inode info. %s", strerror(errno));
2587 goto cleanup;
2590 memcpy(&s->inode, inode, datalen);
2591 DPRINTF("s->inode: name %s snap_id %x oid %x\n",
2592 s->inode.name, s->inode.snap_id, s->inode.vdi_id);
2594 cleanup:
2595 g_free(inode);
2596 closesocket(fd);
2597 return ret;
2601 * We implement rollback(loadvm) operation to the specified snapshot by
2602 * 1) switch to the snapshot
2603 * 2) rely on sd_create_branch to delete working VDI and
2604 * 3) create a new working VDI based on the specified snapshot
2606 static int sd_snapshot_goto(BlockDriverState *bs, const char *snapshot_id)
2608 BDRVSheepdogState *s = bs->opaque;
2609 BDRVSheepdogState *old_s;
2610 char tag[SD_MAX_VDI_TAG_LEN];
2611 uint32_t snapid = 0;
2612 int ret;
2614 if (!sd_parse_snapid_or_tag(snapshot_id, &snapid, tag)) {
2615 return -EINVAL;
2618 old_s = g_new(BDRVSheepdogState, 1);
2620 memcpy(old_s, s, sizeof(BDRVSheepdogState));
2622 ret = reload_inode(s, snapid, tag);
2623 if (ret) {
2624 goto out;
2627 ret = sd_create_branch(s);
2628 if (ret) {
2629 goto out;
2632 g_free(old_s);
2634 return 0;
2635 out:
2636 /* recover bdrv_sd_state */
2637 memcpy(s, old_s, sizeof(BDRVSheepdogState));
2638 g_free(old_s);
2640 error_report("failed to open. recover old bdrv_sd_state.");
2642 return ret;
2645 #define NR_BATCHED_DISCARD 128
2647 static int remove_objects(BDRVSheepdogState *s, Error **errp)
2649 int fd, i = 0, nr_objs = 0;
2650 int ret;
2651 SheepdogInode *inode = &s->inode;
2653 fd = connect_to_sdog(s, errp);
2654 if (fd < 0) {
2655 return fd;
2658 nr_objs = count_data_objs(inode);
2659 while (i < nr_objs) {
2660 int start_idx, nr_filled_idx;
2662 while (i < nr_objs && !inode->data_vdi_id[i]) {
2663 i++;
2665 start_idx = i;
2667 nr_filled_idx = 0;
2668 while (i < nr_objs && nr_filled_idx < NR_BATCHED_DISCARD) {
2669 if (inode->data_vdi_id[i]) {
2670 inode->data_vdi_id[i] = 0;
2671 nr_filled_idx++;
2674 i++;
2677 ret = write_object(fd, s->bs,
2678 (char *)&inode->data_vdi_id[start_idx],
2679 vid_to_vdi_oid(s->inode.vdi_id), inode->nr_copies,
2680 (i - start_idx) * sizeof(uint32_t),
2681 offsetof(struct SheepdogInode,
2682 data_vdi_id[start_idx]),
2683 false, s->cache_flags);
2684 if (ret < 0) {
2685 error_setg(errp, "Failed to discard snapshot inode");
2686 goto out;
2690 ret = 0;
2691 out:
2692 closesocket(fd);
2693 return ret;
2696 static int sd_snapshot_delete(BlockDriverState *bs,
2697 const char *snapshot_id,
2698 const char *name,
2699 Error **errp)
2702 * FIXME should delete the snapshot matching both @snapshot_id and
2703 * @name, but @name not used here
2705 unsigned long snap_id = 0;
2706 char snap_tag[SD_MAX_VDI_TAG_LEN];
2707 int fd, ret;
2708 char buf[SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN];
2709 BDRVSheepdogState *s = bs->opaque;
2710 unsigned int wlen = SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN, rlen = 0;
2711 uint32_t vid;
2712 SheepdogVdiReq hdr = {
2713 .opcode = SD_OP_DEL_VDI,
2714 .data_length = wlen,
2715 .flags = SD_FLAG_CMD_WRITE,
2717 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
2719 ret = remove_objects(s, errp);
2720 if (ret) {
2721 return ret;
2724 memset(buf, 0, sizeof(buf));
2725 memset(snap_tag, 0, sizeof(snap_tag));
2726 pstrcpy(buf, SD_MAX_VDI_LEN, s->name);
2727 /* TODO Use sd_parse_snapid() once this mess is cleaned up */
2728 ret = qemu_strtoul(snapshot_id, NULL, 10, &snap_id);
2729 if (ret || snap_id > UINT32_MAX) {
2731 * FIXME Since qemu_strtoul() returns -EINVAL when
2732 * @snapshot_id is null, @snapshot_id is mandatory. Correct
2733 * would be to require at least one of @snapshot_id and @name.
2735 error_setg(errp, "Invalid snapshot ID: %s",
2736 snapshot_id ? snapshot_id : "<null>");
2737 return -EINVAL;
2740 if (snap_id) {
2741 hdr.snapid = (uint32_t) snap_id;
2742 } else {
2743 /* FIXME I suspect we should use @name here */
2744 /* FIXME don't truncate silently */
2745 pstrcpy(snap_tag, sizeof(snap_tag), snapshot_id);
2746 pstrcpy(buf + SD_MAX_VDI_LEN, SD_MAX_VDI_TAG_LEN, snap_tag);
2749 ret = find_vdi_name(s, s->name, snap_id, snap_tag, &vid, true, errp);
2750 if (ret) {
2751 return ret;
2754 fd = connect_to_sdog(s, errp);
2755 if (fd < 0) {
2756 return fd;
2759 ret = do_req(fd, s->bs, (SheepdogReq *)&hdr,
2760 buf, &wlen, &rlen);
2761 closesocket(fd);
2762 if (ret) {
2763 error_setg_errno(errp, -ret, "Couldn't send request to server");
2764 return ret;
2767 switch (rsp->result) {
2768 case SD_RES_NO_VDI:
2769 error_setg(errp, "Can't find the snapshot");
2770 return -ENOENT;
2771 case SD_RES_SUCCESS:
2772 break;
2773 default:
2774 error_setg(errp, "%s", sd_strerror(rsp->result));
2775 return -EIO;
2778 return 0;
2781 static int sd_snapshot_list(BlockDriverState *bs, QEMUSnapshotInfo **psn_tab)
2783 Error *local_err = NULL;
2784 BDRVSheepdogState *s = bs->opaque;
2785 SheepdogReq req;
2786 int fd, nr = 1024, ret, max = BITS_TO_LONGS(SD_NR_VDIS) * sizeof(long);
2787 QEMUSnapshotInfo *sn_tab = NULL;
2788 unsigned wlen, rlen;
2789 int found = 0;
2790 static SheepdogInode inode;
2791 unsigned long *vdi_inuse;
2792 unsigned int start_nr;
2793 uint64_t hval;
2794 uint32_t vid;
2796 vdi_inuse = g_malloc(max);
2798 fd = connect_to_sdog(s, &local_err);
2799 if (fd < 0) {
2800 error_report_err(local_err);
2801 ret = fd;
2802 goto out;
2805 rlen = max;
2806 wlen = 0;
2808 memset(&req, 0, sizeof(req));
2810 req.opcode = SD_OP_READ_VDIS;
2811 req.data_length = max;
2813 ret = do_req(fd, s->bs, &req, vdi_inuse, &wlen, &rlen);
2815 closesocket(fd);
2816 if (ret) {
2817 goto out;
2820 sn_tab = g_new0(QEMUSnapshotInfo, nr);
2822 /* calculate a vdi id with hash function */
2823 hval = fnv_64a_buf(s->name, strlen(s->name), FNV1A_64_INIT);
2824 start_nr = hval & (SD_NR_VDIS - 1);
2826 fd = connect_to_sdog(s, &local_err);
2827 if (fd < 0) {
2828 error_report_err(local_err);
2829 ret = fd;
2830 goto out;
2833 for (vid = start_nr; found < nr; vid = (vid + 1) % SD_NR_VDIS) {
2834 if (!test_bit(vid, vdi_inuse)) {
2835 break;
2838 /* we don't need to read entire object */
2839 ret = read_object(fd, s->bs, (char *)&inode,
2840 vid_to_vdi_oid(vid),
2841 0, SD_INODE_SIZE - sizeof(inode.data_vdi_id), 0,
2842 s->cache_flags);
2844 if (ret) {
2845 continue;
2848 if (!strcmp(inode.name, s->name) && is_snapshot(&inode)) {
2849 sn_tab[found].date_sec = inode.snap_ctime >> 32;
2850 sn_tab[found].date_nsec = inode.snap_ctime & 0xffffffff;
2851 sn_tab[found].vm_state_size = inode.vm_state_size;
2852 sn_tab[found].vm_clock_nsec = inode.vm_clock_nsec;
2854 snprintf(sn_tab[found].id_str, sizeof(sn_tab[found].id_str),
2855 "%" PRIu32, inode.snap_id);
2856 pstrcpy(sn_tab[found].name,
2857 MIN(sizeof(sn_tab[found].name), sizeof(inode.tag)),
2858 inode.tag);
2859 found++;
2863 closesocket(fd);
2864 out:
2865 *psn_tab = sn_tab;
2867 g_free(vdi_inuse);
2869 if (ret < 0) {
2870 return ret;
2873 return found;
2876 static int do_load_save_vmstate(BDRVSheepdogState *s, uint8_t *data,
2877 int64_t pos, int size, int load)
2879 Error *local_err = NULL;
2880 bool create;
2881 int fd, ret = 0, remaining = size;
2882 unsigned int data_len;
2883 uint64_t vmstate_oid;
2884 uint64_t offset;
2885 uint32_t vdi_index;
2886 uint32_t vdi_id = load ? s->inode.parent_vdi_id : s->inode.vdi_id;
2887 uint32_t object_size = (UINT32_C(1) << s->inode.block_size_shift);
2889 fd = connect_to_sdog(s, &local_err);
2890 if (fd < 0) {
2891 error_report_err(local_err);
2892 return fd;
2895 while (remaining) {
2896 vdi_index = pos / object_size;
2897 offset = pos % object_size;
2899 data_len = MIN(remaining, object_size - offset);
2901 vmstate_oid = vid_to_vmstate_oid(vdi_id, vdi_index);
2903 create = (offset == 0);
2904 if (load) {
2905 ret = read_object(fd, s->bs, (char *)data, vmstate_oid,
2906 s->inode.nr_copies, data_len, offset,
2907 s->cache_flags);
2908 } else {
2909 ret = write_object(fd, s->bs, (char *)data, vmstate_oid,
2910 s->inode.nr_copies, data_len, offset, create,
2911 s->cache_flags);
2914 if (ret < 0) {
2915 error_report("failed to save vmstate %s", strerror(errno));
2916 goto cleanup;
2919 pos += data_len;
2920 data += data_len;
2921 remaining -= data_len;
2923 ret = size;
2924 cleanup:
2925 closesocket(fd);
2926 return ret;
2929 static int sd_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2930 int64_t pos)
2932 BDRVSheepdogState *s = bs->opaque;
2933 void *buf;
2934 int ret;
2936 buf = qemu_blockalign(bs, qiov->size);
2937 qemu_iovec_to_buf(qiov, 0, buf, qiov->size);
2938 ret = do_load_save_vmstate(s, (uint8_t *) buf, pos, qiov->size, 0);
2939 qemu_vfree(buf);
2941 return ret;
2944 static int sd_load_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2945 int64_t pos)
2947 BDRVSheepdogState *s = bs->opaque;
2948 void *buf;
2949 int ret;
2951 buf = qemu_blockalign(bs, qiov->size);
2952 ret = do_load_save_vmstate(s, buf, pos, qiov->size, 1);
2953 qemu_iovec_from_buf(qiov, 0, buf, qiov->size);
2954 qemu_vfree(buf);
2956 return ret;
2960 static coroutine_fn int sd_co_pdiscard(BlockDriverState *bs, int64_t offset,
2961 int bytes)
2963 SheepdogAIOCB acb;
2964 BDRVSheepdogState *s = bs->opaque;
2965 QEMUIOVector discard_iov;
2966 struct iovec iov;
2967 uint32_t zero = 0;
2969 if (!s->discard_supported) {
2970 return 0;
2973 memset(&discard_iov, 0, sizeof(discard_iov));
2974 memset(&iov, 0, sizeof(iov));
2975 iov.iov_base = &zero;
2976 iov.iov_len = sizeof(zero);
2977 discard_iov.iov = &iov;
2978 discard_iov.niov = 1;
2979 if (!QEMU_IS_ALIGNED(offset | bytes, BDRV_SECTOR_SIZE)) {
2980 return -ENOTSUP;
2982 sd_aio_setup(&acb, s, &discard_iov, offset >> BDRV_SECTOR_BITS,
2983 bytes >> BDRV_SECTOR_BITS, AIOCB_DISCARD_OBJ);
2984 sd_co_rw_vector(&acb);
2985 sd_aio_complete(&acb);
2987 return acb.ret;
2990 static coroutine_fn int64_t
2991 sd_co_get_block_status(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
2992 int *pnum, BlockDriverState **file)
2994 BDRVSheepdogState *s = bs->opaque;
2995 SheepdogInode *inode = &s->inode;
2996 uint32_t object_size = (UINT32_C(1) << inode->block_size_shift);
2997 uint64_t offset = sector_num * BDRV_SECTOR_SIZE;
2998 unsigned long start = offset / object_size,
2999 end = DIV_ROUND_UP((sector_num + nb_sectors) *
3000 BDRV_SECTOR_SIZE, object_size);
3001 unsigned long idx;
3002 int64_t ret = BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | offset;
3004 for (idx = start; idx < end; idx++) {
3005 if (inode->data_vdi_id[idx] == 0) {
3006 break;
3009 if (idx == start) {
3010 /* Get the longest length of unallocated sectors */
3011 ret = 0;
3012 for (idx = start + 1; idx < end; idx++) {
3013 if (inode->data_vdi_id[idx] != 0) {
3014 break;
3019 *pnum = (idx - start) * object_size / BDRV_SECTOR_SIZE;
3020 if (*pnum > nb_sectors) {
3021 *pnum = nb_sectors;
3023 if (ret > 0 && ret & BDRV_BLOCK_OFFSET_VALID) {
3024 *file = bs;
3026 return ret;
3029 static int64_t sd_get_allocated_file_size(BlockDriverState *bs)
3031 BDRVSheepdogState *s = bs->opaque;
3032 SheepdogInode *inode = &s->inode;
3033 uint32_t object_size = (UINT32_C(1) << inode->block_size_shift);
3034 unsigned long i, last = DIV_ROUND_UP(inode->vdi_size, object_size);
3035 uint64_t size = 0;
3037 for (i = 0; i < last; i++) {
3038 if (inode->data_vdi_id[i] == 0) {
3039 continue;
3041 size += object_size;
3043 return size;
3046 static QemuOptsList sd_create_opts = {
3047 .name = "sheepdog-create-opts",
3048 .head = QTAILQ_HEAD_INITIALIZER(sd_create_opts.head),
3049 .desc = {
3051 .name = BLOCK_OPT_SIZE,
3052 .type = QEMU_OPT_SIZE,
3053 .help = "Virtual disk size"
3056 .name = BLOCK_OPT_BACKING_FILE,
3057 .type = QEMU_OPT_STRING,
3058 .help = "File name of a base image"
3061 .name = BLOCK_OPT_PREALLOC,
3062 .type = QEMU_OPT_STRING,
3063 .help = "Preallocation mode (allowed values: off, full)"
3066 .name = BLOCK_OPT_REDUNDANCY,
3067 .type = QEMU_OPT_STRING,
3068 .help = "Redundancy of the image"
3071 .name = BLOCK_OPT_OBJECT_SIZE,
3072 .type = QEMU_OPT_SIZE,
3073 .help = "Object size of the image"
3075 { /* end of list */ }
3079 static BlockDriver bdrv_sheepdog = {
3080 .format_name = "sheepdog",
3081 .protocol_name = "sheepdog",
3082 .instance_size = sizeof(BDRVSheepdogState),
3083 .bdrv_parse_filename = sd_parse_filename,
3084 .bdrv_file_open = sd_open,
3085 .bdrv_reopen_prepare = sd_reopen_prepare,
3086 .bdrv_reopen_commit = sd_reopen_commit,
3087 .bdrv_reopen_abort = sd_reopen_abort,
3088 .bdrv_close = sd_close,
3089 .bdrv_create = sd_create,
3090 .bdrv_has_zero_init = bdrv_has_zero_init_1,
3091 .bdrv_getlength = sd_getlength,
3092 .bdrv_get_allocated_file_size = sd_get_allocated_file_size,
3093 .bdrv_truncate = sd_truncate,
3095 .bdrv_co_readv = sd_co_readv,
3096 .bdrv_co_writev = sd_co_writev,
3097 .bdrv_co_flush_to_disk = sd_co_flush_to_disk,
3098 .bdrv_co_pdiscard = sd_co_pdiscard,
3099 .bdrv_co_get_block_status = sd_co_get_block_status,
3101 .bdrv_snapshot_create = sd_snapshot_create,
3102 .bdrv_snapshot_goto = sd_snapshot_goto,
3103 .bdrv_snapshot_delete = sd_snapshot_delete,
3104 .bdrv_snapshot_list = sd_snapshot_list,
3106 .bdrv_save_vmstate = sd_save_vmstate,
3107 .bdrv_load_vmstate = sd_load_vmstate,
3109 .bdrv_detach_aio_context = sd_detach_aio_context,
3110 .bdrv_attach_aio_context = sd_attach_aio_context,
3112 .create_opts = &sd_create_opts,
3115 static BlockDriver bdrv_sheepdog_tcp = {
3116 .format_name = "sheepdog",
3117 .protocol_name = "sheepdog+tcp",
3118 .instance_size = sizeof(BDRVSheepdogState),
3119 .bdrv_parse_filename = sd_parse_filename,
3120 .bdrv_file_open = sd_open,
3121 .bdrv_reopen_prepare = sd_reopen_prepare,
3122 .bdrv_reopen_commit = sd_reopen_commit,
3123 .bdrv_reopen_abort = sd_reopen_abort,
3124 .bdrv_close = sd_close,
3125 .bdrv_create = sd_create,
3126 .bdrv_has_zero_init = bdrv_has_zero_init_1,
3127 .bdrv_getlength = sd_getlength,
3128 .bdrv_get_allocated_file_size = sd_get_allocated_file_size,
3129 .bdrv_truncate = sd_truncate,
3131 .bdrv_co_readv = sd_co_readv,
3132 .bdrv_co_writev = sd_co_writev,
3133 .bdrv_co_flush_to_disk = sd_co_flush_to_disk,
3134 .bdrv_co_pdiscard = sd_co_pdiscard,
3135 .bdrv_co_get_block_status = sd_co_get_block_status,
3137 .bdrv_snapshot_create = sd_snapshot_create,
3138 .bdrv_snapshot_goto = sd_snapshot_goto,
3139 .bdrv_snapshot_delete = sd_snapshot_delete,
3140 .bdrv_snapshot_list = sd_snapshot_list,
3142 .bdrv_save_vmstate = sd_save_vmstate,
3143 .bdrv_load_vmstate = sd_load_vmstate,
3145 .bdrv_detach_aio_context = sd_detach_aio_context,
3146 .bdrv_attach_aio_context = sd_attach_aio_context,
3148 .create_opts = &sd_create_opts,
3151 static BlockDriver bdrv_sheepdog_unix = {
3152 .format_name = "sheepdog",
3153 .protocol_name = "sheepdog+unix",
3154 .instance_size = sizeof(BDRVSheepdogState),
3155 .bdrv_parse_filename = sd_parse_filename,
3156 .bdrv_file_open = sd_open,
3157 .bdrv_reopen_prepare = sd_reopen_prepare,
3158 .bdrv_reopen_commit = sd_reopen_commit,
3159 .bdrv_reopen_abort = sd_reopen_abort,
3160 .bdrv_close = sd_close,
3161 .bdrv_create = sd_create,
3162 .bdrv_has_zero_init = bdrv_has_zero_init_1,
3163 .bdrv_getlength = sd_getlength,
3164 .bdrv_get_allocated_file_size = sd_get_allocated_file_size,
3165 .bdrv_truncate = sd_truncate,
3167 .bdrv_co_readv = sd_co_readv,
3168 .bdrv_co_writev = sd_co_writev,
3169 .bdrv_co_flush_to_disk = sd_co_flush_to_disk,
3170 .bdrv_co_pdiscard = sd_co_pdiscard,
3171 .bdrv_co_get_block_status = sd_co_get_block_status,
3173 .bdrv_snapshot_create = sd_snapshot_create,
3174 .bdrv_snapshot_goto = sd_snapshot_goto,
3175 .bdrv_snapshot_delete = sd_snapshot_delete,
3176 .bdrv_snapshot_list = sd_snapshot_list,
3178 .bdrv_save_vmstate = sd_save_vmstate,
3179 .bdrv_load_vmstate = sd_load_vmstate,
3181 .bdrv_detach_aio_context = sd_detach_aio_context,
3182 .bdrv_attach_aio_context = sd_attach_aio_context,
3184 .create_opts = &sd_create_opts,
3187 static void bdrv_sheepdog_init(void)
3189 bdrv_register(&bdrv_sheepdog);
3190 bdrv_register(&bdrv_sheepdog_tcp);
3191 bdrv_register(&bdrv_sheepdog_unix);
3193 block_init(bdrv_sheepdog_init);