docker: add --include-files argument to 'build' command
[qemu/kevin.git] / block / sheepdog.c
blob5ebf5d9fbb11985251b4a526a68fc2f3227cfd73
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/qmp/qint.h"
20 #include "qapi/qobject-input-visitor.h"
21 #include "qemu/uri.h"
22 #include "qemu/error-report.h"
23 #include "qemu/sockets.h"
24 #include "block/block_int.h"
25 #include "sysemu/block-backend.h"
26 #include "qemu/bitops.h"
27 #include "qemu/cutils.h"
29 #define SD_PROTO_VER 0x01
31 #define SD_DEFAULT_ADDR "localhost"
32 #define SD_DEFAULT_PORT 7000
34 #define SD_OP_CREATE_AND_WRITE_OBJ 0x01
35 #define SD_OP_READ_OBJ 0x02
36 #define SD_OP_WRITE_OBJ 0x03
37 /* 0x04 is used internally by Sheepdog */
39 #define SD_OP_NEW_VDI 0x11
40 #define SD_OP_LOCK_VDI 0x12
41 #define SD_OP_RELEASE_VDI 0x13
42 #define SD_OP_GET_VDI_INFO 0x14
43 #define SD_OP_READ_VDIS 0x15
44 #define SD_OP_FLUSH_VDI 0x16
45 #define SD_OP_DEL_VDI 0x17
46 #define SD_OP_GET_CLUSTER_DEFAULT 0x18
48 #define SD_FLAG_CMD_WRITE 0x01
49 #define SD_FLAG_CMD_COW 0x02
50 #define SD_FLAG_CMD_CACHE 0x04 /* Writeback mode for cache */
51 #define SD_FLAG_CMD_DIRECT 0x08 /* Don't use cache */
53 #define SD_RES_SUCCESS 0x00 /* Success */
54 #define SD_RES_UNKNOWN 0x01 /* Unknown error */
55 #define SD_RES_NO_OBJ 0x02 /* No object found */
56 #define SD_RES_EIO 0x03 /* I/O error */
57 #define SD_RES_VDI_EXIST 0x04 /* Vdi exists already */
58 #define SD_RES_INVALID_PARMS 0x05 /* Invalid parameters */
59 #define SD_RES_SYSTEM_ERROR 0x06 /* System error */
60 #define SD_RES_VDI_LOCKED 0x07 /* Vdi is locked */
61 #define SD_RES_NO_VDI 0x08 /* No vdi found */
62 #define SD_RES_NO_BASE_VDI 0x09 /* No base vdi found */
63 #define SD_RES_VDI_READ 0x0A /* Cannot read requested vdi */
64 #define SD_RES_VDI_WRITE 0x0B /* Cannot write requested vdi */
65 #define SD_RES_BASE_VDI_READ 0x0C /* Cannot read base vdi */
66 #define SD_RES_BASE_VDI_WRITE 0x0D /* Cannot write base vdi */
67 #define SD_RES_NO_TAG 0x0E /* Requested tag is not found */
68 #define SD_RES_STARTUP 0x0F /* Sheepdog is on starting up */
69 #define SD_RES_VDI_NOT_LOCKED 0x10 /* Vdi is not locked */
70 #define SD_RES_SHUTDOWN 0x11 /* Sheepdog is shutting down */
71 #define SD_RES_NO_MEM 0x12 /* Cannot allocate memory */
72 #define SD_RES_FULL_VDI 0x13 /* we already have the maximum vdis */
73 #define SD_RES_VER_MISMATCH 0x14 /* Protocol version mismatch */
74 #define SD_RES_NO_SPACE 0x15 /* Server has no room for new objects */
75 #define SD_RES_WAIT_FOR_FORMAT 0x16 /* Waiting for a format operation */
76 #define SD_RES_WAIT_FOR_JOIN 0x17 /* Waiting for other nodes joining */
77 #define SD_RES_JOIN_FAILED 0x18 /* Target node had failed to join sheepdog */
78 #define SD_RES_HALT 0x19 /* Sheepdog is stopped serving IO request */
79 #define SD_RES_READONLY 0x1A /* Object is read-only */
82 * Object ID rules
84 * 0 - 19 (20 bits): data object space
85 * 20 - 31 (12 bits): reserved data object space
86 * 32 - 55 (24 bits): vdi object space
87 * 56 - 59 ( 4 bits): reserved vdi object space
88 * 60 - 63 ( 4 bits): object type identifier space
91 #define VDI_SPACE_SHIFT 32
92 #define VDI_BIT (UINT64_C(1) << 63)
93 #define VMSTATE_BIT (UINT64_C(1) << 62)
94 #define MAX_DATA_OBJS (UINT64_C(1) << 20)
95 #define MAX_CHILDREN 1024
96 #define SD_MAX_VDI_LEN 256
97 #define SD_MAX_VDI_TAG_LEN 256
98 #define SD_NR_VDIS (1U << 24)
99 #define SD_DATA_OBJ_SIZE (UINT64_C(1) << 22)
100 #define SD_MAX_VDI_SIZE (SD_DATA_OBJ_SIZE * MAX_DATA_OBJS)
101 #define SD_DEFAULT_BLOCK_SIZE_SHIFT 22
103 * For erasure coding, we use at most SD_EC_MAX_STRIP for data strips and
104 * (SD_EC_MAX_STRIP - 1) for parity strips
106 * SD_MAX_COPIES is sum of number of data strips and parity strips.
108 #define SD_EC_MAX_STRIP 16
109 #define SD_MAX_COPIES (SD_EC_MAX_STRIP * 2 - 1)
111 #define SD_INODE_SIZE (sizeof(SheepdogInode))
112 #define CURRENT_VDI_ID 0
114 #define LOCK_TYPE_NORMAL 0
115 #define LOCK_TYPE_SHARED 1 /* for iSCSI multipath */
117 typedef struct SheepdogReq {
118 uint8_t proto_ver;
119 uint8_t opcode;
120 uint16_t flags;
121 uint32_t epoch;
122 uint32_t id;
123 uint32_t data_length;
124 uint32_t opcode_specific[8];
125 } SheepdogReq;
127 typedef struct SheepdogRsp {
128 uint8_t proto_ver;
129 uint8_t opcode;
130 uint16_t flags;
131 uint32_t epoch;
132 uint32_t id;
133 uint32_t data_length;
134 uint32_t result;
135 uint32_t opcode_specific[7];
136 } SheepdogRsp;
138 typedef struct SheepdogObjReq {
139 uint8_t proto_ver;
140 uint8_t opcode;
141 uint16_t flags;
142 uint32_t epoch;
143 uint32_t id;
144 uint32_t data_length;
145 uint64_t oid;
146 uint64_t cow_oid;
147 uint8_t copies;
148 uint8_t copy_policy;
149 uint8_t reserved[6];
150 uint64_t offset;
151 } SheepdogObjReq;
153 typedef struct SheepdogObjRsp {
154 uint8_t proto_ver;
155 uint8_t opcode;
156 uint16_t flags;
157 uint32_t epoch;
158 uint32_t id;
159 uint32_t data_length;
160 uint32_t result;
161 uint8_t copies;
162 uint8_t copy_policy;
163 uint8_t reserved[2];
164 uint32_t pad[6];
165 } SheepdogObjRsp;
167 typedef struct SheepdogVdiReq {
168 uint8_t proto_ver;
169 uint8_t opcode;
170 uint16_t flags;
171 uint32_t epoch;
172 uint32_t id;
173 uint32_t data_length;
174 uint64_t vdi_size;
175 uint32_t base_vdi_id;
176 uint8_t copies;
177 uint8_t copy_policy;
178 uint8_t store_policy;
179 uint8_t block_size_shift;
180 uint32_t snapid;
181 uint32_t type;
182 uint32_t pad[2];
183 } SheepdogVdiReq;
185 typedef struct SheepdogVdiRsp {
186 uint8_t proto_ver;
187 uint8_t opcode;
188 uint16_t flags;
189 uint32_t epoch;
190 uint32_t id;
191 uint32_t data_length;
192 uint32_t result;
193 uint32_t rsvd;
194 uint32_t vdi_id;
195 uint32_t pad[5];
196 } SheepdogVdiRsp;
198 typedef struct SheepdogClusterRsp {
199 uint8_t proto_ver;
200 uint8_t opcode;
201 uint16_t flags;
202 uint32_t epoch;
203 uint32_t id;
204 uint32_t data_length;
205 uint32_t result;
206 uint8_t nr_copies;
207 uint8_t copy_policy;
208 uint8_t block_size_shift;
209 uint8_t __pad1;
210 uint32_t __pad2[6];
211 } SheepdogClusterRsp;
213 typedef struct SheepdogInode {
214 char name[SD_MAX_VDI_LEN];
215 char tag[SD_MAX_VDI_TAG_LEN];
216 uint64_t ctime;
217 uint64_t snap_ctime;
218 uint64_t vm_clock_nsec;
219 uint64_t vdi_size;
220 uint64_t vm_state_size;
221 uint16_t copy_policy;
222 uint8_t nr_copies;
223 uint8_t block_size_shift;
224 uint32_t snap_id;
225 uint32_t vdi_id;
226 uint32_t parent_vdi_id;
227 uint32_t child_vdi_id[MAX_CHILDREN];
228 uint32_t data_vdi_id[MAX_DATA_OBJS];
229 } SheepdogInode;
231 #define SD_INODE_HEADER_SIZE offsetof(SheepdogInode, data_vdi_id)
234 * 64 bit FNV-1a non-zero initial basis
236 #define FNV1A_64_INIT ((uint64_t)0xcbf29ce484222325ULL)
239 * 64 bit Fowler/Noll/Vo FNV-1a hash code
241 static inline uint64_t fnv_64a_buf(void *buf, size_t len, uint64_t hval)
243 unsigned char *bp = buf;
244 unsigned char *be = bp + len;
245 while (bp < be) {
246 hval ^= (uint64_t) *bp++;
247 hval += (hval << 1) + (hval << 4) + (hval << 5) +
248 (hval << 7) + (hval << 8) + (hval << 40);
250 return hval;
253 static inline bool is_data_obj_writable(SheepdogInode *inode, unsigned int idx)
255 return inode->vdi_id == inode->data_vdi_id[idx];
258 static inline bool is_data_obj(uint64_t oid)
260 return !(VDI_BIT & oid);
263 static inline uint64_t data_oid_to_idx(uint64_t oid)
265 return oid & (MAX_DATA_OBJS - 1);
268 static inline uint32_t oid_to_vid(uint64_t oid)
270 return (oid & ~VDI_BIT) >> VDI_SPACE_SHIFT;
273 static inline uint64_t vid_to_vdi_oid(uint32_t vid)
275 return VDI_BIT | ((uint64_t)vid << VDI_SPACE_SHIFT);
278 static inline uint64_t vid_to_vmstate_oid(uint32_t vid, uint32_t idx)
280 return VMSTATE_BIT | ((uint64_t)vid << VDI_SPACE_SHIFT) | idx;
283 static inline uint64_t vid_to_data_oid(uint32_t vid, uint32_t idx)
285 return ((uint64_t)vid << VDI_SPACE_SHIFT) | idx;
288 static inline bool is_snapshot(struct SheepdogInode *inode)
290 return !!inode->snap_ctime;
293 static inline size_t count_data_objs(const struct SheepdogInode *inode)
295 return DIV_ROUND_UP(inode->vdi_size,
296 (1UL << inode->block_size_shift));
299 #undef DPRINTF
300 #ifdef DEBUG_SDOG
301 #define DEBUG_SDOG_PRINT 1
302 #else
303 #define DEBUG_SDOG_PRINT 0
304 #endif
305 #define DPRINTF(fmt, args...) \
306 do { \
307 if (DEBUG_SDOG_PRINT) { \
308 fprintf(stderr, "%s %d: " fmt, __func__, __LINE__, ##args); \
310 } while (0)
312 typedef struct SheepdogAIOCB SheepdogAIOCB;
313 typedef struct BDRVSheepdogState BDRVSheepdogState;
315 typedef struct AIOReq {
316 SheepdogAIOCB *aiocb;
317 unsigned int iov_offset;
319 uint64_t oid;
320 uint64_t base_oid;
321 uint64_t offset;
322 unsigned int data_len;
323 uint8_t flags;
324 uint32_t id;
325 bool create;
327 QLIST_ENTRY(AIOReq) aio_siblings;
328 } AIOReq;
330 enum AIOCBState {
331 AIOCB_WRITE_UDATA,
332 AIOCB_READ_UDATA,
333 AIOCB_FLUSH_CACHE,
334 AIOCB_DISCARD_OBJ,
337 #define AIOCBOverlapping(x, y) \
338 (!(x->max_affect_data_idx < y->min_affect_data_idx \
339 || y->max_affect_data_idx < x->min_affect_data_idx))
341 struct SheepdogAIOCB {
342 BDRVSheepdogState *s;
344 QEMUIOVector *qiov;
346 int64_t sector_num;
347 int nb_sectors;
349 int ret;
350 enum AIOCBState aiocb_type;
352 Coroutine *coroutine;
353 int nr_pending;
355 uint32_t min_affect_data_idx;
356 uint32_t max_affect_data_idx;
359 * The difference between affect_data_idx and dirty_data_idx:
360 * affect_data_idx represents range of index of all request types.
361 * dirty_data_idx represents range of index updated by COW requests.
362 * dirty_data_idx is used for updating an inode object.
364 uint32_t min_dirty_data_idx;
365 uint32_t max_dirty_data_idx;
367 QLIST_ENTRY(SheepdogAIOCB) aiocb_siblings;
370 struct BDRVSheepdogState {
371 BlockDriverState *bs;
372 AioContext *aio_context;
374 SheepdogInode inode;
376 char name[SD_MAX_VDI_LEN];
377 bool is_snapshot;
378 uint32_t cache_flags;
379 bool discard_supported;
381 SocketAddress *addr;
382 int fd;
384 CoMutex lock;
385 Coroutine *co_send;
386 Coroutine *co_recv;
388 uint32_t aioreq_seq_num;
390 /* Every aio request must be linked to either of these queues. */
391 QLIST_HEAD(inflight_aio_head, AIOReq) inflight_aio_head;
392 QLIST_HEAD(failed_aio_head, AIOReq) failed_aio_head;
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, NULL);
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 wait_for_overlapping_aiocb(s, acb);
530 QLIST_INSERT_HEAD(&s->inflight_aiocb_head, acb, aiocb_siblings);
533 static SocketAddress *sd_socket_address(const char *path,
534 const char *host, const char *port)
536 SocketAddress *addr = g_new0(SocketAddress, 1);
538 if (path) {
539 addr->type = SOCKET_ADDRESS_TYPE_UNIX;
540 addr->u.q_unix.path = g_strdup(path);
541 } else {
542 addr->type = SOCKET_ADDRESS_TYPE_INET;
543 addr->u.inet.host = g_strdup(host ?: SD_DEFAULT_ADDR);
544 addr->u.inet.port = g_strdup(port ?: stringify(SD_DEFAULT_PORT));
547 return addr;
550 static SocketAddress *sd_server_config(QDict *options, Error **errp)
552 QDict *server = NULL;
553 QObject *crumpled_server = NULL;
554 Visitor *iv = NULL;
555 SocketAddress *saddr = NULL;
556 Error *local_err = NULL;
558 qdict_extract_subqdict(options, &server, "server.");
560 crumpled_server = qdict_crumple(server, errp);
561 if (!crumpled_server) {
562 goto done;
566 * FIXME .numeric, .to, .ipv4 or .ipv6 don't work with -drive
567 * server.type=inet. .to doesn't matter, it's ignored anyway.
568 * That's because when @options come from -blockdev or
569 * blockdev_add, members are typed according to the QAPI schema,
570 * but when they come from -drive, they're all QString. The
571 * visitor expects the former.
573 iv = qobject_input_visitor_new(crumpled_server);
574 visit_type_SocketAddress(iv, NULL, &saddr, &local_err);
575 if (local_err) {
576 error_propagate(errp, local_err);
577 goto done;
580 done:
581 visit_free(iv);
582 qobject_decref(crumpled_server);
583 QDECREF(server);
584 return saddr;
587 /* Return -EIO in case of error, file descriptor on success */
588 static int connect_to_sdog(BDRVSheepdogState *s, Error **errp)
590 int fd;
592 fd = socket_connect(s->addr, NULL, NULL, errp);
594 if (s->addr->type == SOCKET_ADDRESS_TYPE_INET && fd >= 0) {
595 int ret = socket_set_nodelay(fd);
596 if (ret < 0) {
597 error_report("%s", strerror(errno));
601 if (fd >= 0) {
602 qemu_set_nonblock(fd);
603 } else {
604 fd = -EIO;
607 return fd;
610 /* Return 0 on success and -errno in case of error */
611 static coroutine_fn int send_co_req(int sockfd, SheepdogReq *hdr, void *data,
612 unsigned int *wlen)
614 int ret;
616 ret = qemu_co_send(sockfd, hdr, sizeof(*hdr));
617 if (ret != sizeof(*hdr)) {
618 error_report("failed to send a req, %s", strerror(errno));
619 return -errno;
622 ret = qemu_co_send(sockfd, data, *wlen);
623 if (ret != *wlen) {
624 error_report("failed to send a req, %s", strerror(errno));
625 return -errno;
628 return ret;
631 typedef struct SheepdogReqCo {
632 int sockfd;
633 BlockDriverState *bs;
634 AioContext *aio_context;
635 SheepdogReq *hdr;
636 void *data;
637 unsigned int *wlen;
638 unsigned int *rlen;
639 int ret;
640 bool finished;
641 Coroutine *co;
642 } SheepdogReqCo;
644 static void restart_co_req(void *opaque)
646 SheepdogReqCo *srco = opaque;
648 aio_co_wake(srco->co);
651 static coroutine_fn void do_co_req(void *opaque)
653 int ret;
654 SheepdogReqCo *srco = opaque;
655 int sockfd = srco->sockfd;
656 SheepdogReq *hdr = srco->hdr;
657 void *data = srco->data;
658 unsigned int *wlen = srco->wlen;
659 unsigned int *rlen = srco->rlen;
661 srco->co = qemu_coroutine_self();
662 aio_set_fd_handler(srco->aio_context, sockfd, false,
663 NULL, restart_co_req, NULL, srco);
665 ret = send_co_req(sockfd, hdr, data, wlen);
666 if (ret < 0) {
667 goto out;
670 aio_set_fd_handler(srco->aio_context, sockfd, false,
671 restart_co_req, NULL, NULL, srco);
673 ret = qemu_co_recv(sockfd, hdr, sizeof(*hdr));
674 if (ret != sizeof(*hdr)) {
675 error_report("failed to get a rsp, %s", strerror(errno));
676 ret = -errno;
677 goto out;
680 if (*rlen > hdr->data_length) {
681 *rlen = hdr->data_length;
684 if (*rlen) {
685 ret = qemu_co_recv(sockfd, data, *rlen);
686 if (ret != *rlen) {
687 error_report("failed to get the data, %s", strerror(errno));
688 ret = -errno;
689 goto out;
692 ret = 0;
693 out:
694 /* there is at most one request for this sockfd, so it is safe to
695 * set each handler to NULL. */
696 aio_set_fd_handler(srco->aio_context, sockfd, false,
697 NULL, NULL, NULL, NULL);
699 srco->co = NULL;
700 srco->ret = ret;
701 /* Set srco->finished before reading bs->wakeup. */
702 atomic_mb_set(&srco->finished, true);
703 if (srco->bs) {
704 bdrv_wakeup(srco->bs);
709 * Send the request to the sheep in a synchronous manner.
711 * Return 0 on success, -errno in case of error.
713 static int do_req(int sockfd, BlockDriverState *bs, SheepdogReq *hdr,
714 void *data, unsigned int *wlen, unsigned int *rlen)
716 Coroutine *co;
717 SheepdogReqCo srco = {
718 .sockfd = sockfd,
719 .aio_context = bs ? bdrv_get_aio_context(bs) : qemu_get_aio_context(),
720 .bs = bs,
721 .hdr = hdr,
722 .data = data,
723 .wlen = wlen,
724 .rlen = rlen,
725 .ret = 0,
726 .finished = false,
729 if (qemu_in_coroutine()) {
730 do_co_req(&srco);
731 } else {
732 co = qemu_coroutine_create(do_co_req, &srco);
733 if (bs) {
734 bdrv_coroutine_enter(bs, co);
735 BDRV_POLL_WHILE(bs, !srco.finished);
736 } else {
737 qemu_coroutine_enter(co);
738 while (!srco.finished) {
739 aio_poll(qemu_get_aio_context(), true);
744 return srco.ret;
747 static void coroutine_fn add_aio_request(BDRVSheepdogState *s, AIOReq *aio_req,
748 struct iovec *iov, int niov,
749 enum AIOCBState aiocb_type);
750 static void coroutine_fn resend_aioreq(BDRVSheepdogState *s, AIOReq *aio_req);
751 static int reload_inode(BDRVSheepdogState *s, uint32_t snapid, const char *tag);
752 static int get_sheep_fd(BDRVSheepdogState *s, Error **errp);
753 static void co_write_request(void *opaque);
755 static coroutine_fn void reconnect_to_sdog(void *opaque)
757 BDRVSheepdogState *s = opaque;
758 AIOReq *aio_req, *next;
760 aio_set_fd_handler(s->aio_context, s->fd, false, NULL,
761 NULL, NULL, NULL);
762 close(s->fd);
763 s->fd = -1;
765 /* Wait for outstanding write requests to be completed. */
766 while (s->co_send != NULL) {
767 co_write_request(opaque);
770 /* Try to reconnect the sheepdog server every one second. */
771 while (s->fd < 0) {
772 Error *local_err = NULL;
773 s->fd = get_sheep_fd(s, &local_err);
774 if (s->fd < 0) {
775 DPRINTF("Wait for connection to be established\n");
776 error_report_err(local_err);
777 co_aio_sleep_ns(bdrv_get_aio_context(s->bs), QEMU_CLOCK_REALTIME,
778 1000000000ULL);
783 * Now we have to resend all the request in the inflight queue. However,
784 * resend_aioreq() can yield and newly created requests can be added to the
785 * inflight queue before the coroutine is resumed. To avoid mixing them, we
786 * have to move all the inflight requests to the failed queue before
787 * resend_aioreq() is called.
789 QLIST_FOREACH_SAFE(aio_req, &s->inflight_aio_head, aio_siblings, next) {
790 QLIST_REMOVE(aio_req, aio_siblings);
791 QLIST_INSERT_HEAD(&s->failed_aio_head, aio_req, aio_siblings);
794 /* Resend all the failed aio requests. */
795 while (!QLIST_EMPTY(&s->failed_aio_head)) {
796 aio_req = QLIST_FIRST(&s->failed_aio_head);
797 QLIST_REMOVE(aio_req, aio_siblings);
798 resend_aioreq(s, aio_req);
803 * Receive responses of the I/O requests.
805 * This function is registered as a fd handler, and called from the
806 * main loop when s->fd is ready for reading responses.
808 static void coroutine_fn aio_read_response(void *opaque)
810 SheepdogObjRsp rsp;
811 BDRVSheepdogState *s = opaque;
812 int fd = s->fd;
813 int ret;
814 AIOReq *aio_req = NULL;
815 SheepdogAIOCB *acb;
816 uint64_t idx;
818 /* read a header */
819 ret = qemu_co_recv(fd, &rsp, sizeof(rsp));
820 if (ret != sizeof(rsp)) {
821 error_report("failed to get the header, %s", strerror(errno));
822 goto err;
825 /* find the right aio_req from the inflight aio list */
826 QLIST_FOREACH(aio_req, &s->inflight_aio_head, aio_siblings) {
827 if (aio_req->id == rsp.id) {
828 break;
831 if (!aio_req) {
832 error_report("cannot find aio_req %x", rsp.id);
833 goto err;
836 acb = aio_req->aiocb;
838 switch (acb->aiocb_type) {
839 case AIOCB_WRITE_UDATA:
840 if (!is_data_obj(aio_req->oid)) {
841 break;
843 idx = data_oid_to_idx(aio_req->oid);
845 if (aio_req->create) {
847 * If the object is newly created one, we need to update
848 * the vdi object (metadata object). min_dirty_data_idx
849 * and max_dirty_data_idx are changed to include updated
850 * index between them.
852 if (rsp.result == SD_RES_SUCCESS) {
853 s->inode.data_vdi_id[idx] = s->inode.vdi_id;
854 acb->max_dirty_data_idx = MAX(idx, acb->max_dirty_data_idx);
855 acb->min_dirty_data_idx = MIN(idx, acb->min_dirty_data_idx);
858 break;
859 case AIOCB_READ_UDATA:
860 ret = qemu_co_recvv(fd, acb->qiov->iov, acb->qiov->niov,
861 aio_req->iov_offset, rsp.data_length);
862 if (ret != rsp.data_length) {
863 error_report("failed to get the data, %s", strerror(errno));
864 goto err;
866 break;
867 case AIOCB_FLUSH_CACHE:
868 if (rsp.result == SD_RES_INVALID_PARMS) {
869 DPRINTF("disable cache since the server doesn't support it\n");
870 s->cache_flags = SD_FLAG_CMD_DIRECT;
871 rsp.result = SD_RES_SUCCESS;
873 break;
874 case AIOCB_DISCARD_OBJ:
875 switch (rsp.result) {
876 case SD_RES_INVALID_PARMS:
877 error_report("server doesn't support discard command");
878 rsp.result = SD_RES_SUCCESS;
879 s->discard_supported = false;
880 break;
881 default:
882 break;
886 /* No more data for this aio_req (reload_inode below uses its own file
887 * descriptor handler which doesn't use co_recv).
889 s->co_recv = NULL;
891 QLIST_REMOVE(aio_req, aio_siblings);
892 switch (rsp.result) {
893 case SD_RES_SUCCESS:
894 break;
895 case SD_RES_READONLY:
896 if (s->inode.vdi_id == oid_to_vid(aio_req->oid)) {
897 ret = reload_inode(s, 0, "");
898 if (ret < 0) {
899 goto err;
902 if (is_data_obj(aio_req->oid)) {
903 aio_req->oid = vid_to_data_oid(s->inode.vdi_id,
904 data_oid_to_idx(aio_req->oid));
905 } else {
906 aio_req->oid = vid_to_vdi_oid(s->inode.vdi_id);
908 resend_aioreq(s, aio_req);
909 return;
910 default:
911 acb->ret = -EIO;
912 error_report("%s", sd_strerror(rsp.result));
913 break;
916 g_free(aio_req);
918 if (!--acb->nr_pending) {
920 * We've finished all requests which belong to the AIOCB, so
921 * we can switch back to sd_co_readv/writev now.
923 aio_co_wake(acb->coroutine);
926 return;
928 err:
929 reconnect_to_sdog(opaque);
932 static void co_read_response(void *opaque)
934 BDRVSheepdogState *s = opaque;
936 if (!s->co_recv) {
937 s->co_recv = qemu_coroutine_create(aio_read_response, opaque);
940 aio_co_enter(s->aio_context, s->co_recv);
943 static void co_write_request(void *opaque)
945 BDRVSheepdogState *s = opaque;
947 aio_co_wake(s->co_send);
951 * Return a socket descriptor to read/write objects.
953 * We cannot use this descriptor for other operations because
954 * the block driver may be on waiting response from the server.
956 static int get_sheep_fd(BDRVSheepdogState *s, Error **errp)
958 int fd;
960 fd = connect_to_sdog(s, errp);
961 if (fd < 0) {
962 return fd;
965 aio_set_fd_handler(s->aio_context, fd, false,
966 co_read_response, NULL, NULL, s);
967 return fd;
971 * Parse numeric snapshot ID in @str
972 * If @str can't be parsed as number, return false.
973 * Else, if the number is zero or too large, set *@snapid to zero and
974 * return true.
975 * Else, set *@snapid to the number and return true.
977 static bool sd_parse_snapid(const char *str, uint32_t *snapid)
979 unsigned long ul;
980 int ret;
982 ret = qemu_strtoul(str, NULL, 10, &ul);
983 if (ret == -ERANGE) {
984 ul = ret = 0;
986 if (ret) {
987 return false;
989 if (ul > UINT32_MAX) {
990 ul = 0;
993 *snapid = ul;
994 return true;
997 static bool sd_parse_snapid_or_tag(const char *str,
998 uint32_t *snapid, char tag[])
1000 if (!sd_parse_snapid(str, snapid)) {
1001 *snapid = 0;
1002 if (g_strlcpy(tag, str, SD_MAX_VDI_TAG_LEN) >= SD_MAX_VDI_TAG_LEN) {
1003 return false;
1005 } else if (!*snapid) {
1006 return false;
1007 } else {
1008 tag[0] = 0;
1010 return true;
1013 typedef struct {
1014 const char *path; /* non-null iff transport is tcp */
1015 const char *host; /* valid when transport is tcp */
1016 int port; /* valid when transport is tcp */
1017 char vdi[SD_MAX_VDI_LEN];
1018 char tag[SD_MAX_VDI_TAG_LEN];
1019 uint32_t snap_id;
1020 /* Remainder is only for sd_config_done() */
1021 URI *uri;
1022 QueryParams *qp;
1023 } SheepdogConfig;
1025 static void sd_config_done(SheepdogConfig *cfg)
1027 if (cfg->qp) {
1028 query_params_free(cfg->qp);
1030 uri_free(cfg->uri);
1033 static void sd_parse_uri(SheepdogConfig *cfg, const char *filename,
1034 Error **errp)
1036 Error *err = NULL;
1037 QueryParams *qp = NULL;
1038 bool is_unix;
1039 URI *uri;
1041 memset(cfg, 0, sizeof(*cfg));
1043 cfg->uri = uri = uri_parse(filename);
1044 if (!uri) {
1045 error_setg(&err, "invalid URI");
1046 goto out;
1049 /* transport */
1050 if (!strcmp(uri->scheme, "sheepdog")) {
1051 is_unix = false;
1052 } else if (!strcmp(uri->scheme, "sheepdog+tcp")) {
1053 is_unix = false;
1054 } else if (!strcmp(uri->scheme, "sheepdog+unix")) {
1055 is_unix = true;
1056 } else {
1057 error_setg(&err, "URI scheme must be 'sheepdog', 'sheepdog+tcp',"
1058 " or 'sheepdog+unix'");
1059 goto out;
1062 if (uri->path == NULL || !strcmp(uri->path, "/")) {
1063 error_setg(&err, "missing file path in URI");
1064 goto out;
1066 if (g_strlcpy(cfg->vdi, uri->path + 1, SD_MAX_VDI_LEN)
1067 >= SD_MAX_VDI_LEN) {
1068 error_setg(&err, "VDI name is too long");
1069 goto out;
1072 cfg->qp = qp = query_params_parse(uri->query);
1074 if (is_unix) {
1075 /* sheepdog+unix:///vdiname?socket=path */
1076 if (uri->server || uri->port) {
1077 error_setg(&err, "URI scheme %s doesn't accept a server address",
1078 uri->scheme);
1079 goto out;
1081 if (!qp->n) {
1082 error_setg(&err,
1083 "URI scheme %s requires query parameter 'socket'",
1084 uri->scheme);
1085 goto out;
1087 if (qp->n != 1 || strcmp(qp->p[0].name, "socket")) {
1088 error_setg(&err, "unexpected query parameters");
1089 goto out;
1091 cfg->path = qp->p[0].value;
1092 } else {
1093 /* sheepdog[+tcp]://[host:port]/vdiname */
1094 if (qp->n) {
1095 error_setg(&err, "unexpected query parameters");
1096 goto out;
1098 cfg->host = uri->server;
1099 cfg->port = uri->port;
1102 /* snapshot tag */
1103 if (uri->fragment) {
1104 if (!sd_parse_snapid_or_tag(uri->fragment,
1105 &cfg->snap_id, cfg->tag)) {
1106 error_setg(&err, "'%s' is not a valid snapshot ID",
1107 uri->fragment);
1108 goto out;
1110 } else {
1111 cfg->snap_id = CURRENT_VDI_ID; /* search current vdi */
1114 out:
1115 if (err) {
1116 error_propagate(errp, err);
1117 sd_config_done(cfg);
1122 * Parse a filename (old syntax)
1124 * filename must be one of the following formats:
1125 * 1. [vdiname]
1126 * 2. [vdiname]:[snapid]
1127 * 3. [vdiname]:[tag]
1128 * 4. [hostname]:[port]:[vdiname]
1129 * 5. [hostname]:[port]:[vdiname]:[snapid]
1130 * 6. [hostname]:[port]:[vdiname]:[tag]
1132 * You can boot from the snapshot images by specifying `snapid` or
1133 * `tag'.
1135 * You can run VMs outside the Sheepdog cluster by specifying
1136 * `hostname' and `port' (experimental).
1138 static void parse_vdiname(SheepdogConfig *cfg, const char *filename,
1139 Error **errp)
1141 Error *err = NULL;
1142 char *p, *q, *uri;
1143 const char *host_spec, *vdi_spec;
1144 int nr_sep;
1146 strstart(filename, "sheepdog:", &filename);
1147 p = q = g_strdup(filename);
1149 /* count the number of separators */
1150 nr_sep = 0;
1151 while (*p) {
1152 if (*p == ':') {
1153 nr_sep++;
1155 p++;
1157 p = q;
1159 /* use the first two tokens as host_spec. */
1160 if (nr_sep >= 2) {
1161 host_spec = p;
1162 p = strchr(p, ':');
1163 p++;
1164 p = strchr(p, ':');
1165 *p++ = '\0';
1166 } else {
1167 host_spec = "";
1170 vdi_spec = p;
1172 p = strchr(vdi_spec, ':');
1173 if (p) {
1174 *p++ = '#';
1177 uri = g_strdup_printf("sheepdog://%s/%s", host_spec, vdi_spec);
1180 * FIXME We to escape URI meta-characters, e.g. "x?y=z"
1181 * produces "sheepdog://x?y=z". Because of that ...
1183 sd_parse_uri(cfg, uri, &err);
1184 if (err) {
1186 * ... this can fail, but the error message is misleading.
1187 * Replace it by the traditional useless one until the
1188 * escaping is fixed.
1190 error_free(err);
1191 error_setg(errp, "Can't parse filename");
1194 g_free(q);
1195 g_free(uri);
1198 static void sd_parse_filename(const char *filename, QDict *options,
1199 Error **errp)
1201 Error *err = NULL;
1202 SheepdogConfig cfg;
1203 char buf[32];
1205 if (strstr(filename, "://")) {
1206 sd_parse_uri(&cfg, filename, &err);
1207 } else {
1208 parse_vdiname(&cfg, filename, &err);
1210 if (err) {
1211 error_propagate(errp, err);
1212 return;
1215 if (cfg.path) {
1216 qdict_set_default_str(options, "server.path", cfg.path);
1217 qdict_set_default_str(options, "server.type", "unix");
1218 } else {
1219 qdict_set_default_str(options, "server.type", "inet");
1220 qdict_set_default_str(options, "server.host",
1221 cfg.host ?: SD_DEFAULT_ADDR);
1222 snprintf(buf, sizeof(buf), "%d", cfg.port ?: SD_DEFAULT_PORT);
1223 qdict_set_default_str(options, "server.port", buf);
1225 qdict_set_default_str(options, "vdi", cfg.vdi);
1226 qdict_set_default_str(options, "tag", cfg.tag);
1227 if (cfg.snap_id) {
1228 snprintf(buf, sizeof(buf), "%d", cfg.snap_id);
1229 qdict_set_default_str(options, "snap-id", buf);
1232 sd_config_done(&cfg);
1235 static int find_vdi_name(BDRVSheepdogState *s, const char *filename,
1236 uint32_t snapid, const char *tag, uint32_t *vid,
1237 bool lock, Error **errp)
1239 int ret, fd;
1240 SheepdogVdiReq hdr;
1241 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
1242 unsigned int wlen, rlen = 0;
1243 char buf[SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN];
1245 fd = connect_to_sdog(s, errp);
1246 if (fd < 0) {
1247 return fd;
1250 /* This pair of strncpy calls ensures that the buffer is zero-filled,
1251 * which is desirable since we'll soon be sending those bytes, and
1252 * don't want the send_req to read uninitialized data.
1254 strncpy(buf, filename, SD_MAX_VDI_LEN);
1255 strncpy(buf + SD_MAX_VDI_LEN, tag, SD_MAX_VDI_TAG_LEN);
1257 memset(&hdr, 0, sizeof(hdr));
1258 if (lock) {
1259 hdr.opcode = SD_OP_LOCK_VDI;
1260 hdr.type = LOCK_TYPE_NORMAL;
1261 } else {
1262 hdr.opcode = SD_OP_GET_VDI_INFO;
1264 wlen = SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN;
1265 hdr.proto_ver = SD_PROTO_VER;
1266 hdr.data_length = wlen;
1267 hdr.snapid = snapid;
1268 hdr.flags = SD_FLAG_CMD_WRITE;
1270 ret = do_req(fd, s->bs, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
1271 if (ret) {
1272 error_setg_errno(errp, -ret, "cannot get vdi info");
1273 goto out;
1276 if (rsp->result != SD_RES_SUCCESS) {
1277 error_setg(errp, "cannot get vdi info, %s, %s %" PRIu32 " %s",
1278 sd_strerror(rsp->result), filename, snapid, tag);
1279 if (rsp->result == SD_RES_NO_VDI) {
1280 ret = -ENOENT;
1281 } else if (rsp->result == SD_RES_VDI_LOCKED) {
1282 ret = -EBUSY;
1283 } else {
1284 ret = -EIO;
1286 goto out;
1288 *vid = rsp->vdi_id;
1290 ret = 0;
1291 out:
1292 closesocket(fd);
1293 return ret;
1296 static void coroutine_fn add_aio_request(BDRVSheepdogState *s, AIOReq *aio_req,
1297 struct iovec *iov, int niov,
1298 enum AIOCBState aiocb_type)
1300 int nr_copies = s->inode.nr_copies;
1301 SheepdogObjReq hdr;
1302 unsigned int wlen = 0;
1303 int ret;
1304 uint64_t oid = aio_req->oid;
1305 unsigned int datalen = aio_req->data_len;
1306 uint64_t offset = aio_req->offset;
1307 uint8_t flags = aio_req->flags;
1308 uint64_t old_oid = aio_req->base_oid;
1309 bool create = aio_req->create;
1311 QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
1313 if (!nr_copies) {
1314 error_report("bug");
1317 memset(&hdr, 0, sizeof(hdr));
1319 switch (aiocb_type) {
1320 case AIOCB_FLUSH_CACHE:
1321 hdr.opcode = SD_OP_FLUSH_VDI;
1322 break;
1323 case AIOCB_READ_UDATA:
1324 hdr.opcode = SD_OP_READ_OBJ;
1325 hdr.flags = flags;
1326 break;
1327 case AIOCB_WRITE_UDATA:
1328 if (create) {
1329 hdr.opcode = SD_OP_CREATE_AND_WRITE_OBJ;
1330 } else {
1331 hdr.opcode = SD_OP_WRITE_OBJ;
1333 wlen = datalen;
1334 hdr.flags = SD_FLAG_CMD_WRITE | flags;
1335 break;
1336 case AIOCB_DISCARD_OBJ:
1337 hdr.opcode = SD_OP_WRITE_OBJ;
1338 hdr.flags = SD_FLAG_CMD_WRITE | flags;
1339 s->inode.data_vdi_id[data_oid_to_idx(oid)] = 0;
1340 offset = offsetof(SheepdogInode,
1341 data_vdi_id[data_oid_to_idx(oid)]);
1342 oid = vid_to_vdi_oid(s->inode.vdi_id);
1343 wlen = datalen = sizeof(uint32_t);
1344 break;
1347 if (s->cache_flags) {
1348 hdr.flags |= s->cache_flags;
1351 hdr.oid = oid;
1352 hdr.cow_oid = old_oid;
1353 hdr.copies = s->inode.nr_copies;
1355 hdr.data_length = datalen;
1356 hdr.offset = offset;
1358 hdr.id = aio_req->id;
1360 qemu_co_mutex_lock(&s->lock);
1361 s->co_send = qemu_coroutine_self();
1362 aio_set_fd_handler(s->aio_context, s->fd, false,
1363 co_read_response, co_write_request, NULL, s);
1364 socket_set_cork(s->fd, 1);
1366 /* send a header */
1367 ret = qemu_co_send(s->fd, &hdr, sizeof(hdr));
1368 if (ret != sizeof(hdr)) {
1369 error_report("failed to send a req, %s", strerror(errno));
1370 goto out;
1373 if (wlen) {
1374 ret = qemu_co_sendv(s->fd, iov, niov, aio_req->iov_offset, wlen);
1375 if (ret != wlen) {
1376 error_report("failed to send a data, %s", strerror(errno));
1379 out:
1380 socket_set_cork(s->fd, 0);
1381 aio_set_fd_handler(s->aio_context, s->fd, false,
1382 co_read_response, NULL, NULL, s);
1383 s->co_send = NULL;
1384 qemu_co_mutex_unlock(&s->lock);
1387 static int read_write_object(int fd, BlockDriverState *bs, char *buf,
1388 uint64_t oid, uint8_t copies,
1389 unsigned int datalen, uint64_t offset,
1390 bool write, bool create, uint32_t cache_flags)
1392 SheepdogObjReq hdr;
1393 SheepdogObjRsp *rsp = (SheepdogObjRsp *)&hdr;
1394 unsigned int wlen, rlen;
1395 int ret;
1397 memset(&hdr, 0, sizeof(hdr));
1399 if (write) {
1400 wlen = datalen;
1401 rlen = 0;
1402 hdr.flags = SD_FLAG_CMD_WRITE;
1403 if (create) {
1404 hdr.opcode = SD_OP_CREATE_AND_WRITE_OBJ;
1405 } else {
1406 hdr.opcode = SD_OP_WRITE_OBJ;
1408 } else {
1409 wlen = 0;
1410 rlen = datalen;
1411 hdr.opcode = SD_OP_READ_OBJ;
1414 hdr.flags |= cache_flags;
1416 hdr.oid = oid;
1417 hdr.data_length = datalen;
1418 hdr.offset = offset;
1419 hdr.copies = copies;
1421 ret = do_req(fd, bs, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
1422 if (ret) {
1423 error_report("failed to send a request to the sheep");
1424 return ret;
1427 switch (rsp->result) {
1428 case SD_RES_SUCCESS:
1429 return 0;
1430 default:
1431 error_report("%s", sd_strerror(rsp->result));
1432 return -EIO;
1436 static int read_object(int fd, BlockDriverState *bs, char *buf,
1437 uint64_t oid, uint8_t copies,
1438 unsigned int datalen, uint64_t offset,
1439 uint32_t cache_flags)
1441 return read_write_object(fd, bs, buf, oid, copies,
1442 datalen, offset, false,
1443 false, cache_flags);
1446 static int write_object(int fd, BlockDriverState *bs, char *buf,
1447 uint64_t oid, uint8_t copies,
1448 unsigned int datalen, uint64_t offset, bool create,
1449 uint32_t cache_flags)
1451 return read_write_object(fd, bs, buf, oid, copies,
1452 datalen, offset, true,
1453 create, cache_flags);
1456 /* update inode with the latest state */
1457 static int reload_inode(BDRVSheepdogState *s, uint32_t snapid, const char *tag)
1459 Error *local_err = NULL;
1460 SheepdogInode *inode;
1461 int ret = 0, fd;
1462 uint32_t vid = 0;
1464 fd = connect_to_sdog(s, &local_err);
1465 if (fd < 0) {
1466 error_report_err(local_err);
1467 return -EIO;
1470 inode = g_malloc(SD_INODE_HEADER_SIZE);
1472 ret = find_vdi_name(s, s->name, snapid, tag, &vid, false, &local_err);
1473 if (ret) {
1474 error_report_err(local_err);
1475 goto out;
1478 ret = read_object(fd, s->bs, (char *)inode, vid_to_vdi_oid(vid),
1479 s->inode.nr_copies, SD_INODE_HEADER_SIZE, 0,
1480 s->cache_flags);
1481 if (ret < 0) {
1482 goto out;
1485 if (inode->vdi_id != s->inode.vdi_id) {
1486 memcpy(&s->inode, inode, SD_INODE_HEADER_SIZE);
1489 out:
1490 g_free(inode);
1491 closesocket(fd);
1493 return ret;
1496 static void coroutine_fn resend_aioreq(BDRVSheepdogState *s, AIOReq *aio_req)
1498 SheepdogAIOCB *acb = aio_req->aiocb;
1500 aio_req->create = false;
1502 /* check whether this request becomes a CoW one */
1503 if (acb->aiocb_type == AIOCB_WRITE_UDATA && is_data_obj(aio_req->oid)) {
1504 int idx = data_oid_to_idx(aio_req->oid);
1506 if (is_data_obj_writable(&s->inode, idx)) {
1507 goto out;
1510 if (s->inode.data_vdi_id[idx]) {
1511 aio_req->base_oid = vid_to_data_oid(s->inode.data_vdi_id[idx], idx);
1512 aio_req->flags |= SD_FLAG_CMD_COW;
1514 aio_req->create = true;
1516 out:
1517 if (is_data_obj(aio_req->oid)) {
1518 add_aio_request(s, aio_req, acb->qiov->iov, acb->qiov->niov,
1519 acb->aiocb_type);
1520 } else {
1521 struct iovec iov;
1522 iov.iov_base = &s->inode;
1523 iov.iov_len = sizeof(s->inode);
1524 add_aio_request(s, aio_req, &iov, 1, AIOCB_WRITE_UDATA);
1528 static void sd_detach_aio_context(BlockDriverState *bs)
1530 BDRVSheepdogState *s = bs->opaque;
1532 aio_set_fd_handler(s->aio_context, s->fd, false, NULL,
1533 NULL, NULL, NULL);
1536 static void sd_attach_aio_context(BlockDriverState *bs,
1537 AioContext *new_context)
1539 BDRVSheepdogState *s = bs->opaque;
1541 s->aio_context = new_context;
1542 aio_set_fd_handler(new_context, s->fd, false,
1543 co_read_response, NULL, NULL, s);
1546 static QemuOptsList runtime_opts = {
1547 .name = "sheepdog",
1548 .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
1549 .desc = {
1551 .name = "vdi",
1552 .type = QEMU_OPT_STRING,
1555 .name = "snap-id",
1556 .type = QEMU_OPT_NUMBER,
1559 .name = "tag",
1560 .type = QEMU_OPT_STRING,
1562 { /* end of list */ }
1566 static int sd_open(BlockDriverState *bs, QDict *options, int flags,
1567 Error **errp)
1569 int ret, fd;
1570 uint32_t vid = 0;
1571 BDRVSheepdogState *s = bs->opaque;
1572 const char *vdi, *snap_id_str, *tag;
1573 uint64_t snap_id;
1574 char *buf = NULL;
1575 QemuOpts *opts;
1576 Error *local_err = NULL;
1578 s->bs = bs;
1579 s->aio_context = bdrv_get_aio_context(bs);
1581 opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
1582 qemu_opts_absorb_qdict(opts, options, &local_err);
1583 if (local_err) {
1584 error_propagate(errp, local_err);
1585 ret = -EINVAL;
1586 goto err_no_fd;
1589 s->addr = sd_server_config(options, errp);
1590 if (!s->addr) {
1591 ret = -EINVAL;
1592 goto err_no_fd;
1595 vdi = qemu_opt_get(opts, "vdi");
1596 snap_id_str = qemu_opt_get(opts, "snap-id");
1597 snap_id = qemu_opt_get_number(opts, "snap-id", CURRENT_VDI_ID);
1598 tag = qemu_opt_get(opts, "tag");
1600 if (!vdi) {
1601 error_setg(errp, "parameter 'vdi' is missing");
1602 ret = -EINVAL;
1603 goto err_no_fd;
1605 if (strlen(vdi) >= SD_MAX_VDI_LEN) {
1606 error_setg(errp, "value of parameter 'vdi' is too long");
1607 ret = -EINVAL;
1608 goto err_no_fd;
1611 if (snap_id > UINT32_MAX) {
1612 snap_id = 0;
1614 if (snap_id_str && !snap_id) {
1615 error_setg(errp, "'snap-id=%s' is not a valid snapshot ID",
1616 snap_id_str);
1617 ret = -EINVAL;
1618 goto err_no_fd;
1621 if (!tag) {
1622 tag = "";
1624 if (tag && strlen(tag) >= SD_MAX_VDI_TAG_LEN) {
1625 error_setg(errp, "value of parameter 'tag' is too long");
1626 ret = -EINVAL;
1627 goto err_no_fd;
1630 QLIST_INIT(&s->inflight_aio_head);
1631 QLIST_INIT(&s->failed_aio_head);
1632 QLIST_INIT(&s->inflight_aiocb_head);
1634 s->fd = get_sheep_fd(s, errp);
1635 if (s->fd < 0) {
1636 ret = s->fd;
1637 goto err_no_fd;
1640 ret = find_vdi_name(s, vdi, (uint32_t)snap_id, tag, &vid, true, errp);
1641 if (ret) {
1642 goto err;
1646 * QEMU block layer emulates writethrough cache as 'writeback + flush', so
1647 * we always set SD_FLAG_CMD_CACHE (writeback cache) as default.
1649 s->cache_flags = SD_FLAG_CMD_CACHE;
1650 if (flags & BDRV_O_NOCACHE) {
1651 s->cache_flags = SD_FLAG_CMD_DIRECT;
1653 s->discard_supported = true;
1655 if (snap_id || tag[0]) {
1656 DPRINTF("%" PRIx32 " snapshot inode was open.\n", vid);
1657 s->is_snapshot = true;
1660 fd = connect_to_sdog(s, errp);
1661 if (fd < 0) {
1662 ret = fd;
1663 goto err;
1666 buf = g_malloc(SD_INODE_SIZE);
1667 ret = read_object(fd, s->bs, buf, vid_to_vdi_oid(vid),
1668 0, SD_INODE_SIZE, 0, s->cache_flags);
1670 closesocket(fd);
1672 if (ret) {
1673 error_setg(errp, "Can't read snapshot inode");
1674 goto err;
1677 memcpy(&s->inode, buf, sizeof(s->inode));
1679 bs->total_sectors = s->inode.vdi_size / BDRV_SECTOR_SIZE;
1680 pstrcpy(s->name, sizeof(s->name), vdi);
1681 qemu_co_mutex_init(&s->lock);
1682 qemu_co_queue_init(&s->overlapping_queue);
1683 qemu_opts_del(opts);
1684 g_free(buf);
1685 return 0;
1687 err:
1688 aio_set_fd_handler(bdrv_get_aio_context(bs), s->fd,
1689 false, NULL, NULL, NULL, NULL);
1690 closesocket(s->fd);
1691 err_no_fd:
1692 qemu_opts_del(opts);
1693 g_free(buf);
1694 return ret;
1697 static int sd_reopen_prepare(BDRVReopenState *state, BlockReopenQueue *queue,
1698 Error **errp)
1700 BDRVSheepdogState *s = state->bs->opaque;
1701 BDRVSheepdogReopenState *re_s;
1702 int ret = 0;
1704 re_s = state->opaque = g_new0(BDRVSheepdogReopenState, 1);
1706 re_s->cache_flags = SD_FLAG_CMD_CACHE;
1707 if (state->flags & BDRV_O_NOCACHE) {
1708 re_s->cache_flags = SD_FLAG_CMD_DIRECT;
1711 re_s->fd = get_sheep_fd(s, errp);
1712 if (re_s->fd < 0) {
1713 ret = re_s->fd;
1714 return ret;
1717 return ret;
1720 static void sd_reopen_commit(BDRVReopenState *state)
1722 BDRVSheepdogReopenState *re_s = state->opaque;
1723 BDRVSheepdogState *s = state->bs->opaque;
1725 if (s->fd) {
1726 aio_set_fd_handler(s->aio_context, s->fd, false,
1727 NULL, NULL, NULL, NULL);
1728 closesocket(s->fd);
1731 s->fd = re_s->fd;
1732 s->cache_flags = re_s->cache_flags;
1734 g_free(state->opaque);
1735 state->opaque = NULL;
1737 return;
1740 static void sd_reopen_abort(BDRVReopenState *state)
1742 BDRVSheepdogReopenState *re_s = state->opaque;
1743 BDRVSheepdogState *s = state->bs->opaque;
1745 if (re_s == NULL) {
1746 return;
1749 if (re_s->fd) {
1750 aio_set_fd_handler(s->aio_context, re_s->fd, false,
1751 NULL, NULL, NULL, NULL);
1752 closesocket(re_s->fd);
1755 g_free(state->opaque);
1756 state->opaque = NULL;
1758 return;
1761 static int do_sd_create(BDRVSheepdogState *s, uint32_t *vdi_id, int snapshot,
1762 Error **errp)
1764 SheepdogVdiReq hdr;
1765 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
1766 int fd, ret;
1767 unsigned int wlen, rlen = 0;
1768 char buf[SD_MAX_VDI_LEN];
1770 fd = connect_to_sdog(s, errp);
1771 if (fd < 0) {
1772 return fd;
1775 /* FIXME: would it be better to fail (e.g., return -EIO) when filename
1776 * does not fit in buf? For now, just truncate and avoid buffer overrun.
1778 memset(buf, 0, sizeof(buf));
1779 pstrcpy(buf, sizeof(buf), s->name);
1781 memset(&hdr, 0, sizeof(hdr));
1782 hdr.opcode = SD_OP_NEW_VDI;
1783 hdr.base_vdi_id = s->inode.vdi_id;
1785 wlen = SD_MAX_VDI_LEN;
1787 hdr.flags = SD_FLAG_CMD_WRITE;
1788 hdr.snapid = snapshot;
1790 hdr.data_length = wlen;
1791 hdr.vdi_size = s->inode.vdi_size;
1792 hdr.copy_policy = s->inode.copy_policy;
1793 hdr.copies = s->inode.nr_copies;
1794 hdr.block_size_shift = s->inode.block_size_shift;
1796 ret = do_req(fd, NULL, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
1798 closesocket(fd);
1800 if (ret) {
1801 error_setg_errno(errp, -ret, "create failed");
1802 return ret;
1805 if (rsp->result != SD_RES_SUCCESS) {
1806 error_setg(errp, "%s, %s", sd_strerror(rsp->result), s->inode.name);
1807 return -EIO;
1810 if (vdi_id) {
1811 *vdi_id = rsp->vdi_id;
1814 return 0;
1817 static int sd_prealloc(const char *filename, Error **errp)
1819 BlockBackend *blk = NULL;
1820 BDRVSheepdogState *base = NULL;
1821 unsigned long buf_size;
1822 uint32_t idx, max_idx;
1823 uint32_t object_size;
1824 int64_t vdi_size;
1825 void *buf = NULL;
1826 int ret;
1828 blk = blk_new_open(filename, NULL, NULL,
1829 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL, errp);
1830 if (blk == NULL) {
1831 ret = -EIO;
1832 goto out_with_err_set;
1835 blk_set_allow_write_beyond_eof(blk, true);
1837 vdi_size = blk_getlength(blk);
1838 if (vdi_size < 0) {
1839 ret = vdi_size;
1840 goto out;
1843 base = blk_bs(blk)->opaque;
1844 object_size = (UINT32_C(1) << base->inode.block_size_shift);
1845 buf_size = MIN(object_size, SD_DATA_OBJ_SIZE);
1846 buf = g_malloc0(buf_size);
1848 max_idx = DIV_ROUND_UP(vdi_size, buf_size);
1850 for (idx = 0; idx < max_idx; idx++) {
1852 * The created image can be a cloned image, so we need to read
1853 * a data from the source image.
1855 ret = blk_pread(blk, idx * buf_size, buf, buf_size);
1856 if (ret < 0) {
1857 goto out;
1859 ret = blk_pwrite(blk, idx * buf_size, buf, buf_size, 0);
1860 if (ret < 0) {
1861 goto out;
1865 ret = 0;
1866 out:
1867 if (ret < 0) {
1868 error_setg_errno(errp, -ret, "Can't pre-allocate");
1870 out_with_err_set:
1871 if (blk) {
1872 blk_unref(blk);
1874 g_free(buf);
1876 return ret;
1880 * Sheepdog support two kinds of redundancy, full replication and erasure
1881 * coding.
1883 * # create a fully replicated vdi with x copies
1884 * -o redundancy=x (1 <= x <= SD_MAX_COPIES)
1886 * # create a erasure coded vdi with x data strips and y parity strips
1887 * -o redundancy=x:y (x must be one of {2,4,8,16} and 1 <= y < SD_EC_MAX_STRIP)
1889 static int parse_redundancy(BDRVSheepdogState *s, const char *opt)
1891 struct SheepdogInode *inode = &s->inode;
1892 const char *n1, *n2;
1893 long copy, parity;
1894 char p[10];
1896 pstrcpy(p, sizeof(p), opt);
1897 n1 = strtok(p, ":");
1898 n2 = strtok(NULL, ":");
1900 if (!n1) {
1901 return -EINVAL;
1904 copy = strtol(n1, NULL, 10);
1905 /* FIXME fix error checking by switching to qemu_strtol() */
1906 if (copy > SD_MAX_COPIES || copy < 1) {
1907 return -EINVAL;
1909 if (!n2) {
1910 inode->copy_policy = 0;
1911 inode->nr_copies = copy;
1912 return 0;
1915 if (copy != 2 && copy != 4 && copy != 8 && copy != 16) {
1916 return -EINVAL;
1919 parity = strtol(n2, NULL, 10);
1920 /* FIXME fix error checking by switching to qemu_strtol() */
1921 if (parity >= SD_EC_MAX_STRIP || parity < 1) {
1922 return -EINVAL;
1926 * 4 bits for parity and 4 bits for data.
1927 * We have to compress upper data bits because it can't represent 16
1929 inode->copy_policy = ((copy / 2) << 4) + parity;
1930 inode->nr_copies = copy + parity;
1932 return 0;
1935 static int parse_block_size_shift(BDRVSheepdogState *s, QemuOpts *opt)
1937 struct SheepdogInode *inode = &s->inode;
1938 uint64_t object_size;
1939 int obj_order;
1941 object_size = qemu_opt_get_size_del(opt, BLOCK_OPT_OBJECT_SIZE, 0);
1942 if (object_size) {
1943 if ((object_size - 1) & object_size) { /* not a power of 2? */
1944 return -EINVAL;
1946 obj_order = ctz32(object_size);
1947 if (obj_order < 20 || obj_order > 31) {
1948 return -EINVAL;
1950 inode->block_size_shift = (uint8_t)obj_order;
1953 return 0;
1956 static int sd_create(const char *filename, QemuOpts *opts,
1957 Error **errp)
1959 Error *err = NULL;
1960 int ret = 0;
1961 uint32_t vid = 0;
1962 char *backing_file = NULL;
1963 char *buf = NULL;
1964 BDRVSheepdogState *s;
1965 SheepdogConfig cfg;
1966 uint64_t max_vdi_size;
1967 bool prealloc = false;
1969 s = g_new0(BDRVSheepdogState, 1);
1971 if (strstr(filename, "://")) {
1972 sd_parse_uri(&cfg, filename, &err);
1973 } else {
1974 parse_vdiname(&cfg, filename, &err);
1976 if (err) {
1977 error_propagate(errp, err);
1978 goto out;
1981 buf = cfg.port ? g_strdup_printf("%d", cfg.port) : NULL;
1982 s->addr = sd_socket_address(cfg.path, cfg.host, buf);
1983 g_free(buf);
1984 strcpy(s->name, cfg.vdi);
1985 sd_config_done(&cfg);
1987 s->inode.vdi_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
1988 BDRV_SECTOR_SIZE);
1989 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
1990 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
1991 if (!buf || !strcmp(buf, "off")) {
1992 prealloc = false;
1993 } else if (!strcmp(buf, "full")) {
1994 prealloc = true;
1995 } else {
1996 error_setg(errp, "Invalid preallocation mode: '%s'", buf);
1997 ret = -EINVAL;
1998 goto out;
2001 g_free(buf);
2002 buf = qemu_opt_get_del(opts, BLOCK_OPT_REDUNDANCY);
2003 if (buf) {
2004 ret = parse_redundancy(s, buf);
2005 if (ret < 0) {
2006 error_setg(errp, "Invalid redundancy mode: '%s'", buf);
2007 goto out;
2010 ret = parse_block_size_shift(s, opts);
2011 if (ret < 0) {
2012 error_setg(errp, "Invalid object_size."
2013 " obect_size needs to be power of 2"
2014 " and be limited from 2^20 to 2^31");
2015 goto out;
2018 if (backing_file) {
2019 BlockBackend *blk;
2020 BDRVSheepdogState *base;
2021 BlockDriver *drv;
2023 /* Currently, only Sheepdog backing image is supported. */
2024 drv = bdrv_find_protocol(backing_file, true, NULL);
2025 if (!drv || strcmp(drv->protocol_name, "sheepdog") != 0) {
2026 error_setg(errp, "backing_file must be a sheepdog image");
2027 ret = -EINVAL;
2028 goto out;
2031 blk = blk_new_open(backing_file, NULL, NULL,
2032 BDRV_O_PROTOCOL, errp);
2033 if (blk == NULL) {
2034 ret = -EIO;
2035 goto out;
2038 base = blk_bs(blk)->opaque;
2040 if (!is_snapshot(&base->inode)) {
2041 error_setg(errp, "cannot clone from a non snapshot vdi");
2042 blk_unref(blk);
2043 ret = -EINVAL;
2044 goto out;
2046 s->inode.vdi_id = base->inode.vdi_id;
2047 blk_unref(blk);
2050 s->aio_context = qemu_get_aio_context();
2052 /* if block_size_shift is not specified, get cluster default value */
2053 if (s->inode.block_size_shift == 0) {
2054 SheepdogVdiReq hdr;
2055 SheepdogClusterRsp *rsp = (SheepdogClusterRsp *)&hdr;
2056 int fd;
2057 unsigned int wlen = 0, rlen = 0;
2059 fd = connect_to_sdog(s, errp);
2060 if (fd < 0) {
2061 ret = fd;
2062 goto out;
2065 memset(&hdr, 0, sizeof(hdr));
2066 hdr.opcode = SD_OP_GET_CLUSTER_DEFAULT;
2067 hdr.proto_ver = SD_PROTO_VER;
2069 ret = do_req(fd, NULL, (SheepdogReq *)&hdr,
2070 NULL, &wlen, &rlen);
2071 closesocket(fd);
2072 if (ret) {
2073 error_setg_errno(errp, -ret, "failed to get cluster default");
2074 goto out;
2076 if (rsp->result == SD_RES_SUCCESS) {
2077 s->inode.block_size_shift = rsp->block_size_shift;
2078 } else {
2079 s->inode.block_size_shift = SD_DEFAULT_BLOCK_SIZE_SHIFT;
2083 max_vdi_size = (UINT64_C(1) << s->inode.block_size_shift) * MAX_DATA_OBJS;
2085 if (s->inode.vdi_size > max_vdi_size) {
2086 error_setg(errp, "An image is too large."
2087 " The maximum image size is %"PRIu64 "GB",
2088 max_vdi_size / 1024 / 1024 / 1024);
2089 ret = -EINVAL;
2090 goto out;
2093 ret = do_sd_create(s, &vid, 0, errp);
2094 if (ret) {
2095 goto out;
2098 if (prealloc) {
2099 ret = sd_prealloc(filename, errp);
2101 out:
2102 g_free(backing_file);
2103 g_free(buf);
2104 g_free(s);
2105 return ret;
2108 static void sd_close(BlockDriverState *bs)
2110 Error *local_err = NULL;
2111 BDRVSheepdogState *s = bs->opaque;
2112 SheepdogVdiReq hdr;
2113 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
2114 unsigned int wlen, rlen = 0;
2115 int fd, ret;
2117 DPRINTF("%s\n", s->name);
2119 fd = connect_to_sdog(s, &local_err);
2120 if (fd < 0) {
2121 error_report_err(local_err);
2122 return;
2125 memset(&hdr, 0, sizeof(hdr));
2127 hdr.opcode = SD_OP_RELEASE_VDI;
2128 hdr.type = LOCK_TYPE_NORMAL;
2129 hdr.base_vdi_id = s->inode.vdi_id;
2130 wlen = strlen(s->name) + 1;
2131 hdr.data_length = wlen;
2132 hdr.flags = SD_FLAG_CMD_WRITE;
2134 ret = do_req(fd, s->bs, (SheepdogReq *)&hdr,
2135 s->name, &wlen, &rlen);
2137 closesocket(fd);
2139 if (!ret && rsp->result != SD_RES_SUCCESS &&
2140 rsp->result != SD_RES_VDI_NOT_LOCKED) {
2141 error_report("%s, %s", sd_strerror(rsp->result), s->name);
2144 aio_set_fd_handler(bdrv_get_aio_context(bs), s->fd,
2145 false, NULL, NULL, NULL, NULL);
2146 closesocket(s->fd);
2147 qapi_free_SocketAddress(s->addr);
2150 static int64_t sd_getlength(BlockDriverState *bs)
2152 BDRVSheepdogState *s = bs->opaque;
2154 return s->inode.vdi_size;
2157 static int sd_truncate(BlockDriverState *bs, int64_t offset, Error **errp)
2159 BDRVSheepdogState *s = bs->opaque;
2160 int ret, fd;
2161 unsigned int datalen;
2162 uint64_t max_vdi_size;
2164 max_vdi_size = (UINT64_C(1) << s->inode.block_size_shift) * MAX_DATA_OBJS;
2165 if (offset < s->inode.vdi_size) {
2166 error_setg(errp, "shrinking is not supported");
2167 return -EINVAL;
2168 } else if (offset > max_vdi_size) {
2169 error_setg(errp, "too big image size");
2170 return -EINVAL;
2173 fd = connect_to_sdog(s, errp);
2174 if (fd < 0) {
2175 return fd;
2178 /* we don't need to update entire object */
2179 datalen = SD_INODE_SIZE - sizeof(s->inode.data_vdi_id);
2180 s->inode.vdi_size = offset;
2181 ret = write_object(fd, s->bs, (char *)&s->inode,
2182 vid_to_vdi_oid(s->inode.vdi_id), s->inode.nr_copies,
2183 datalen, 0, false, s->cache_flags);
2184 close(fd);
2186 if (ret < 0) {
2187 error_setg_errno(errp, -ret, "failed to update an inode");
2190 return ret;
2194 * This function is called after writing data objects. If we need to
2195 * update metadata, this sends a write request to the vdi object.
2197 static void coroutine_fn sd_write_done(SheepdogAIOCB *acb)
2199 BDRVSheepdogState *s = acb->s;
2200 struct iovec iov;
2201 AIOReq *aio_req;
2202 uint32_t offset, data_len, mn, mx;
2204 mn = acb->min_dirty_data_idx;
2205 mx = acb->max_dirty_data_idx;
2206 if (mn <= mx) {
2207 /* we need to update the vdi object. */
2208 ++acb->nr_pending;
2209 offset = sizeof(s->inode) - sizeof(s->inode.data_vdi_id) +
2210 mn * sizeof(s->inode.data_vdi_id[0]);
2211 data_len = (mx - mn + 1) * sizeof(s->inode.data_vdi_id[0]);
2213 acb->min_dirty_data_idx = UINT32_MAX;
2214 acb->max_dirty_data_idx = 0;
2216 iov.iov_base = &s->inode;
2217 iov.iov_len = sizeof(s->inode);
2218 aio_req = alloc_aio_req(s, acb, vid_to_vdi_oid(s->inode.vdi_id),
2219 data_len, offset, 0, false, 0, offset);
2220 add_aio_request(s, aio_req, &iov, 1, AIOCB_WRITE_UDATA);
2221 if (--acb->nr_pending) {
2222 qemu_coroutine_yield();
2227 /* Delete current working VDI on the snapshot chain */
2228 static bool sd_delete(BDRVSheepdogState *s)
2230 Error *local_err = NULL;
2231 unsigned int wlen = SD_MAX_VDI_LEN, rlen = 0;
2232 SheepdogVdiReq hdr = {
2233 .opcode = SD_OP_DEL_VDI,
2234 .base_vdi_id = s->inode.vdi_id,
2235 .data_length = wlen,
2236 .flags = SD_FLAG_CMD_WRITE,
2238 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
2239 int fd, ret;
2241 fd = connect_to_sdog(s, &local_err);
2242 if (fd < 0) {
2243 error_report_err(local_err);
2244 return false;
2247 ret = do_req(fd, s->bs, (SheepdogReq *)&hdr,
2248 s->name, &wlen, &rlen);
2249 closesocket(fd);
2250 if (ret) {
2251 return false;
2253 switch (rsp->result) {
2254 case SD_RES_NO_VDI:
2255 error_report("%s was already deleted", s->name);
2256 /* fall through */
2257 case SD_RES_SUCCESS:
2258 break;
2259 default:
2260 error_report("%s, %s", sd_strerror(rsp->result), s->name);
2261 return false;
2264 return true;
2268 * Create a writable VDI from a snapshot
2270 static int sd_create_branch(BDRVSheepdogState *s)
2272 Error *local_err = NULL;
2273 int ret, fd;
2274 uint32_t vid;
2275 char *buf;
2276 bool deleted;
2278 DPRINTF("%" PRIx32 " is snapshot.\n", s->inode.vdi_id);
2280 buf = g_malloc(SD_INODE_SIZE);
2283 * Even If deletion fails, we will just create extra snapshot based on
2284 * the working VDI which was supposed to be deleted. So no need to
2285 * false bail out.
2287 deleted = sd_delete(s);
2288 ret = do_sd_create(s, &vid, !deleted, &local_err);
2289 if (ret) {
2290 error_report_err(local_err);
2291 goto out;
2294 DPRINTF("%" PRIx32 " is created.\n", vid);
2296 fd = connect_to_sdog(s, &local_err);
2297 if (fd < 0) {
2298 error_report_err(local_err);
2299 ret = fd;
2300 goto out;
2303 ret = read_object(fd, s->bs, buf, vid_to_vdi_oid(vid),
2304 s->inode.nr_copies, SD_INODE_SIZE, 0, s->cache_flags);
2306 closesocket(fd);
2308 if (ret < 0) {
2309 goto out;
2312 memcpy(&s->inode, buf, sizeof(s->inode));
2314 s->is_snapshot = false;
2315 ret = 0;
2316 DPRINTF("%" PRIx32 " was newly created.\n", s->inode.vdi_id);
2318 out:
2319 g_free(buf);
2321 return ret;
2325 * Send I/O requests to the server.
2327 * This function sends requests to the server, links the requests to
2328 * the inflight_list in BDRVSheepdogState, and exits without
2329 * waiting the response. The responses are received in the
2330 * `aio_read_response' function which is called from the main loop as
2331 * a fd handler.
2333 * Returns 1 when we need to wait a response, 0 when there is no sent
2334 * request and -errno in error cases.
2336 static void coroutine_fn sd_co_rw_vector(SheepdogAIOCB *acb)
2338 int ret = 0;
2339 unsigned long len, done = 0, total = acb->nb_sectors * BDRV_SECTOR_SIZE;
2340 unsigned long idx;
2341 uint32_t object_size;
2342 uint64_t oid;
2343 uint64_t offset;
2344 BDRVSheepdogState *s = acb->s;
2345 SheepdogInode *inode = &s->inode;
2346 AIOReq *aio_req;
2348 if (acb->aiocb_type == AIOCB_WRITE_UDATA && s->is_snapshot) {
2350 * In the case we open the snapshot VDI, Sheepdog creates the
2351 * writable VDI when we do a write operation first.
2353 ret = sd_create_branch(s);
2354 if (ret) {
2355 acb->ret = -EIO;
2356 return;
2360 object_size = (UINT32_C(1) << inode->block_size_shift);
2361 idx = acb->sector_num * BDRV_SECTOR_SIZE / object_size;
2362 offset = (acb->sector_num * BDRV_SECTOR_SIZE) % object_size;
2365 * Make sure we don't free the aiocb before we are done with all requests.
2366 * This additional reference is dropped at the end of this function.
2368 acb->nr_pending++;
2370 while (done != total) {
2371 uint8_t flags = 0;
2372 uint64_t old_oid = 0;
2373 bool create = false;
2375 oid = vid_to_data_oid(inode->data_vdi_id[idx], idx);
2377 len = MIN(total - done, object_size - offset);
2379 switch (acb->aiocb_type) {
2380 case AIOCB_READ_UDATA:
2381 if (!inode->data_vdi_id[idx]) {
2382 qemu_iovec_memset(acb->qiov, done, 0, len);
2383 goto done;
2385 break;
2386 case AIOCB_WRITE_UDATA:
2387 if (!inode->data_vdi_id[idx]) {
2388 create = true;
2389 } else if (!is_data_obj_writable(inode, idx)) {
2390 /* Copy-On-Write */
2391 create = true;
2392 old_oid = oid;
2393 flags = SD_FLAG_CMD_COW;
2395 break;
2396 case AIOCB_DISCARD_OBJ:
2398 * We discard the object only when the whole object is
2399 * 1) allocated 2) trimmed. Otherwise, simply skip it.
2401 if (len != object_size || inode->data_vdi_id[idx] == 0) {
2402 goto done;
2404 break;
2405 default:
2406 break;
2409 if (create) {
2410 DPRINTF("update ino (%" PRIu32 ") %" PRIu64 " %" PRIu64 " %ld\n",
2411 inode->vdi_id, oid,
2412 vid_to_data_oid(inode->data_vdi_id[idx], idx), idx);
2413 oid = vid_to_data_oid(inode->vdi_id, idx);
2414 DPRINTF("new oid %" PRIx64 "\n", oid);
2417 aio_req = alloc_aio_req(s, acb, oid, len, offset, flags, create,
2418 old_oid,
2419 acb->aiocb_type == AIOCB_DISCARD_OBJ ?
2420 0 : done);
2421 add_aio_request(s, aio_req, acb->qiov->iov, acb->qiov->niov,
2422 acb->aiocb_type);
2423 done:
2424 offset = 0;
2425 idx++;
2426 done += len;
2428 if (--acb->nr_pending) {
2429 qemu_coroutine_yield();
2433 static void sd_aio_complete(SheepdogAIOCB *acb)
2435 if (acb->aiocb_type == AIOCB_FLUSH_CACHE) {
2436 return;
2439 QLIST_REMOVE(acb, aiocb_siblings);
2440 qemu_co_queue_restart_all(&acb->s->overlapping_queue);
2443 static coroutine_fn int sd_co_writev(BlockDriverState *bs, int64_t sector_num,
2444 int nb_sectors, QEMUIOVector *qiov)
2446 SheepdogAIOCB acb;
2447 int ret;
2448 int64_t offset = (sector_num + nb_sectors) * BDRV_SECTOR_SIZE;
2449 BDRVSheepdogState *s = bs->opaque;
2451 if (offset > s->inode.vdi_size) {
2452 ret = sd_truncate(bs, offset, NULL);
2453 if (ret < 0) {
2454 return ret;
2458 sd_aio_setup(&acb, s, qiov, sector_num, nb_sectors, AIOCB_WRITE_UDATA);
2459 sd_co_rw_vector(&acb);
2460 sd_write_done(&acb);
2461 sd_aio_complete(&acb);
2463 return acb.ret;
2466 static coroutine_fn int sd_co_readv(BlockDriverState *bs, int64_t sector_num,
2467 int nb_sectors, QEMUIOVector *qiov)
2469 SheepdogAIOCB acb;
2470 BDRVSheepdogState *s = bs->opaque;
2472 sd_aio_setup(&acb, s, qiov, sector_num, nb_sectors, AIOCB_READ_UDATA);
2473 sd_co_rw_vector(&acb);
2474 sd_aio_complete(&acb);
2476 return acb.ret;
2479 static int coroutine_fn sd_co_flush_to_disk(BlockDriverState *bs)
2481 BDRVSheepdogState *s = bs->opaque;
2482 SheepdogAIOCB acb;
2483 AIOReq *aio_req;
2485 if (s->cache_flags != SD_FLAG_CMD_CACHE) {
2486 return 0;
2489 sd_aio_setup(&acb, s, NULL, 0, 0, AIOCB_FLUSH_CACHE);
2491 acb.nr_pending++;
2492 aio_req = alloc_aio_req(s, &acb, vid_to_vdi_oid(s->inode.vdi_id),
2493 0, 0, 0, false, 0, 0);
2494 add_aio_request(s, aio_req, NULL, 0, acb.aiocb_type);
2496 if (--acb.nr_pending) {
2497 qemu_coroutine_yield();
2500 sd_aio_complete(&acb);
2501 return acb.ret;
2504 static int sd_snapshot_create(BlockDriverState *bs, QEMUSnapshotInfo *sn_info)
2506 Error *local_err = NULL;
2507 BDRVSheepdogState *s = bs->opaque;
2508 int ret, fd;
2509 uint32_t new_vid;
2510 SheepdogInode *inode;
2511 unsigned int datalen;
2513 DPRINTF("sn_info: name %s id_str %s s: name %s vm_state_size %" PRId64 " "
2514 "is_snapshot %d\n", sn_info->name, sn_info->id_str,
2515 s->name, sn_info->vm_state_size, s->is_snapshot);
2517 if (s->is_snapshot) {
2518 error_report("You can't create a snapshot of a snapshot VDI, "
2519 "%s (%" PRIu32 ").", s->name, s->inode.vdi_id);
2521 return -EINVAL;
2524 DPRINTF("%s %s\n", sn_info->name, sn_info->id_str);
2526 s->inode.vm_state_size = sn_info->vm_state_size;
2527 s->inode.vm_clock_nsec = sn_info->vm_clock_nsec;
2528 /* It appears that inode.tag does not require a NUL terminator,
2529 * which means this use of strncpy is ok.
2531 strncpy(s->inode.tag, sn_info->name, sizeof(s->inode.tag));
2532 /* we don't need to update entire object */
2533 datalen = SD_INODE_SIZE - sizeof(s->inode.data_vdi_id);
2534 inode = g_malloc(datalen);
2536 /* refresh inode. */
2537 fd = connect_to_sdog(s, &local_err);
2538 if (fd < 0) {
2539 error_report_err(local_err);
2540 ret = fd;
2541 goto cleanup;
2544 ret = write_object(fd, s->bs, (char *)&s->inode,
2545 vid_to_vdi_oid(s->inode.vdi_id), s->inode.nr_copies,
2546 datalen, 0, false, s->cache_flags);
2547 if (ret < 0) {
2548 error_report("failed to write snapshot's inode.");
2549 goto cleanup;
2552 ret = do_sd_create(s, &new_vid, 1, &local_err);
2553 if (ret < 0) {
2554 error_reportf_err(local_err,
2555 "failed to create inode for snapshot: ");
2556 goto cleanup;
2559 ret = read_object(fd, s->bs, (char *)inode,
2560 vid_to_vdi_oid(new_vid), s->inode.nr_copies, datalen, 0,
2561 s->cache_flags);
2563 if (ret < 0) {
2564 error_report("failed to read new inode info. %s", strerror(errno));
2565 goto cleanup;
2568 memcpy(&s->inode, inode, datalen);
2569 DPRINTF("s->inode: name %s snap_id %x oid %x\n",
2570 s->inode.name, s->inode.snap_id, s->inode.vdi_id);
2572 cleanup:
2573 g_free(inode);
2574 closesocket(fd);
2575 return ret;
2579 * We implement rollback(loadvm) operation to the specified snapshot by
2580 * 1) switch to the snapshot
2581 * 2) rely on sd_create_branch to delete working VDI and
2582 * 3) create a new working VDI based on the specified snapshot
2584 static int sd_snapshot_goto(BlockDriverState *bs, const char *snapshot_id)
2586 BDRVSheepdogState *s = bs->opaque;
2587 BDRVSheepdogState *old_s;
2588 char tag[SD_MAX_VDI_TAG_LEN];
2589 uint32_t snapid = 0;
2590 int ret;
2592 if (!sd_parse_snapid_or_tag(snapshot_id, &snapid, tag)) {
2593 return -EINVAL;
2596 old_s = g_new(BDRVSheepdogState, 1);
2598 memcpy(old_s, s, sizeof(BDRVSheepdogState));
2600 ret = reload_inode(s, snapid, tag);
2601 if (ret) {
2602 goto out;
2605 ret = sd_create_branch(s);
2606 if (ret) {
2607 goto out;
2610 g_free(old_s);
2612 return 0;
2613 out:
2614 /* recover bdrv_sd_state */
2615 memcpy(s, old_s, sizeof(BDRVSheepdogState));
2616 g_free(old_s);
2618 error_report("failed to open. recover old bdrv_sd_state.");
2620 return ret;
2623 #define NR_BATCHED_DISCARD 128
2625 static int remove_objects(BDRVSheepdogState *s, Error **errp)
2627 int fd, i = 0, nr_objs = 0;
2628 int ret;
2629 SheepdogInode *inode = &s->inode;
2631 fd = connect_to_sdog(s, errp);
2632 if (fd < 0) {
2633 return fd;
2636 nr_objs = count_data_objs(inode);
2637 while (i < nr_objs) {
2638 int start_idx, nr_filled_idx;
2640 while (i < nr_objs && !inode->data_vdi_id[i]) {
2641 i++;
2643 start_idx = i;
2645 nr_filled_idx = 0;
2646 while (i < nr_objs && nr_filled_idx < NR_BATCHED_DISCARD) {
2647 if (inode->data_vdi_id[i]) {
2648 inode->data_vdi_id[i] = 0;
2649 nr_filled_idx++;
2652 i++;
2655 ret = write_object(fd, s->bs,
2656 (char *)&inode->data_vdi_id[start_idx],
2657 vid_to_vdi_oid(s->inode.vdi_id), inode->nr_copies,
2658 (i - start_idx) * sizeof(uint32_t),
2659 offsetof(struct SheepdogInode,
2660 data_vdi_id[start_idx]),
2661 false, s->cache_flags);
2662 if (ret < 0) {
2663 error_setg(errp, "Failed to discard snapshot inode");
2664 goto out;
2668 ret = 0;
2669 out:
2670 closesocket(fd);
2671 return ret;
2674 static int sd_snapshot_delete(BlockDriverState *bs,
2675 const char *snapshot_id,
2676 const char *name,
2677 Error **errp)
2680 * FIXME should delete the snapshot matching both @snapshot_id and
2681 * @name, but @name not used here
2683 unsigned long snap_id = 0;
2684 char snap_tag[SD_MAX_VDI_TAG_LEN];
2685 int fd, ret;
2686 char buf[SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN];
2687 BDRVSheepdogState *s = bs->opaque;
2688 unsigned int wlen = SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN, rlen = 0;
2689 uint32_t vid;
2690 SheepdogVdiReq hdr = {
2691 .opcode = SD_OP_DEL_VDI,
2692 .data_length = wlen,
2693 .flags = SD_FLAG_CMD_WRITE,
2695 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
2697 ret = remove_objects(s, errp);
2698 if (ret) {
2699 return ret;
2702 memset(buf, 0, sizeof(buf));
2703 memset(snap_tag, 0, sizeof(snap_tag));
2704 pstrcpy(buf, SD_MAX_VDI_LEN, s->name);
2705 /* TODO Use sd_parse_snapid() once this mess is cleaned up */
2706 ret = qemu_strtoul(snapshot_id, NULL, 10, &snap_id);
2707 if (ret || snap_id > UINT32_MAX) {
2709 * FIXME Since qemu_strtoul() returns -EINVAL when
2710 * @snapshot_id is null, @snapshot_id is mandatory. Correct
2711 * would be to require at least one of @snapshot_id and @name.
2713 error_setg(errp, "Invalid snapshot ID: %s",
2714 snapshot_id ? snapshot_id : "<null>");
2715 return -EINVAL;
2718 if (snap_id) {
2719 hdr.snapid = (uint32_t) snap_id;
2720 } else {
2721 /* FIXME I suspect we should use @name here */
2722 /* FIXME don't truncate silently */
2723 pstrcpy(snap_tag, sizeof(snap_tag), snapshot_id);
2724 pstrcpy(buf + SD_MAX_VDI_LEN, SD_MAX_VDI_TAG_LEN, snap_tag);
2727 ret = find_vdi_name(s, s->name, snap_id, snap_tag, &vid, true, errp);
2728 if (ret) {
2729 return ret;
2732 fd = connect_to_sdog(s, errp);
2733 if (fd < 0) {
2734 return fd;
2737 ret = do_req(fd, s->bs, (SheepdogReq *)&hdr,
2738 buf, &wlen, &rlen);
2739 closesocket(fd);
2740 if (ret) {
2741 error_setg_errno(errp, -ret, "Couldn't send request to server");
2742 return ret;
2745 switch (rsp->result) {
2746 case SD_RES_NO_VDI:
2747 error_setg(errp, "Can't find the snapshot");
2748 return -ENOENT;
2749 case SD_RES_SUCCESS:
2750 break;
2751 default:
2752 error_setg(errp, "%s", sd_strerror(rsp->result));
2753 return -EIO;
2756 return 0;
2759 static int sd_snapshot_list(BlockDriverState *bs, QEMUSnapshotInfo **psn_tab)
2761 Error *local_err = NULL;
2762 BDRVSheepdogState *s = bs->opaque;
2763 SheepdogReq req;
2764 int fd, nr = 1024, ret, max = BITS_TO_LONGS(SD_NR_VDIS) * sizeof(long);
2765 QEMUSnapshotInfo *sn_tab = NULL;
2766 unsigned wlen, rlen;
2767 int found = 0;
2768 static SheepdogInode inode;
2769 unsigned long *vdi_inuse;
2770 unsigned int start_nr;
2771 uint64_t hval;
2772 uint32_t vid;
2774 vdi_inuse = g_malloc(max);
2776 fd = connect_to_sdog(s, &local_err);
2777 if (fd < 0) {
2778 error_report_err(local_err);
2779 ret = fd;
2780 goto out;
2783 rlen = max;
2784 wlen = 0;
2786 memset(&req, 0, sizeof(req));
2788 req.opcode = SD_OP_READ_VDIS;
2789 req.data_length = max;
2791 ret = do_req(fd, s->bs, &req, vdi_inuse, &wlen, &rlen);
2793 closesocket(fd);
2794 if (ret) {
2795 goto out;
2798 sn_tab = g_new0(QEMUSnapshotInfo, nr);
2800 /* calculate a vdi id with hash function */
2801 hval = fnv_64a_buf(s->name, strlen(s->name), FNV1A_64_INIT);
2802 start_nr = hval & (SD_NR_VDIS - 1);
2804 fd = connect_to_sdog(s, &local_err);
2805 if (fd < 0) {
2806 error_report_err(local_err);
2807 ret = fd;
2808 goto out;
2811 for (vid = start_nr; found < nr; vid = (vid + 1) % SD_NR_VDIS) {
2812 if (!test_bit(vid, vdi_inuse)) {
2813 break;
2816 /* we don't need to read entire object */
2817 ret = read_object(fd, s->bs, (char *)&inode,
2818 vid_to_vdi_oid(vid),
2819 0, SD_INODE_SIZE - sizeof(inode.data_vdi_id), 0,
2820 s->cache_flags);
2822 if (ret) {
2823 continue;
2826 if (!strcmp(inode.name, s->name) && is_snapshot(&inode)) {
2827 sn_tab[found].date_sec = inode.snap_ctime >> 32;
2828 sn_tab[found].date_nsec = inode.snap_ctime & 0xffffffff;
2829 sn_tab[found].vm_state_size = inode.vm_state_size;
2830 sn_tab[found].vm_clock_nsec = inode.vm_clock_nsec;
2832 snprintf(sn_tab[found].id_str, sizeof(sn_tab[found].id_str),
2833 "%" PRIu32, inode.snap_id);
2834 pstrcpy(sn_tab[found].name,
2835 MIN(sizeof(sn_tab[found].name), sizeof(inode.tag)),
2836 inode.tag);
2837 found++;
2841 closesocket(fd);
2842 out:
2843 *psn_tab = sn_tab;
2845 g_free(vdi_inuse);
2847 if (ret < 0) {
2848 return ret;
2851 return found;
2854 static int do_load_save_vmstate(BDRVSheepdogState *s, uint8_t *data,
2855 int64_t pos, int size, int load)
2857 Error *local_err = NULL;
2858 bool create;
2859 int fd, ret = 0, remaining = size;
2860 unsigned int data_len;
2861 uint64_t vmstate_oid;
2862 uint64_t offset;
2863 uint32_t vdi_index;
2864 uint32_t vdi_id = load ? s->inode.parent_vdi_id : s->inode.vdi_id;
2865 uint32_t object_size = (UINT32_C(1) << s->inode.block_size_shift);
2867 fd = connect_to_sdog(s, &local_err);
2868 if (fd < 0) {
2869 error_report_err(local_err);
2870 return fd;
2873 while (remaining) {
2874 vdi_index = pos / object_size;
2875 offset = pos % object_size;
2877 data_len = MIN(remaining, object_size - offset);
2879 vmstate_oid = vid_to_vmstate_oid(vdi_id, vdi_index);
2881 create = (offset == 0);
2882 if (load) {
2883 ret = read_object(fd, s->bs, (char *)data, vmstate_oid,
2884 s->inode.nr_copies, data_len, offset,
2885 s->cache_flags);
2886 } else {
2887 ret = write_object(fd, s->bs, (char *)data, vmstate_oid,
2888 s->inode.nr_copies, data_len, offset, create,
2889 s->cache_flags);
2892 if (ret < 0) {
2893 error_report("failed to save vmstate %s", strerror(errno));
2894 goto cleanup;
2897 pos += data_len;
2898 data += data_len;
2899 remaining -= data_len;
2901 ret = size;
2902 cleanup:
2903 closesocket(fd);
2904 return ret;
2907 static int sd_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2908 int64_t pos)
2910 BDRVSheepdogState *s = bs->opaque;
2911 void *buf;
2912 int ret;
2914 buf = qemu_blockalign(bs, qiov->size);
2915 qemu_iovec_to_buf(qiov, 0, buf, qiov->size);
2916 ret = do_load_save_vmstate(s, (uint8_t *) buf, pos, qiov->size, 0);
2917 qemu_vfree(buf);
2919 return ret;
2922 static int sd_load_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2923 int64_t pos)
2925 BDRVSheepdogState *s = bs->opaque;
2926 void *buf;
2927 int ret;
2929 buf = qemu_blockalign(bs, qiov->size);
2930 ret = do_load_save_vmstate(s, buf, pos, qiov->size, 1);
2931 qemu_iovec_from_buf(qiov, 0, buf, qiov->size);
2932 qemu_vfree(buf);
2934 return ret;
2938 static coroutine_fn int sd_co_pdiscard(BlockDriverState *bs, int64_t offset,
2939 int count)
2941 SheepdogAIOCB acb;
2942 BDRVSheepdogState *s = bs->opaque;
2943 QEMUIOVector discard_iov;
2944 struct iovec iov;
2945 uint32_t zero = 0;
2947 if (!s->discard_supported) {
2948 return 0;
2951 memset(&discard_iov, 0, sizeof(discard_iov));
2952 memset(&iov, 0, sizeof(iov));
2953 iov.iov_base = &zero;
2954 iov.iov_len = sizeof(zero);
2955 discard_iov.iov = &iov;
2956 discard_iov.niov = 1;
2957 if (!QEMU_IS_ALIGNED(offset | count, BDRV_SECTOR_SIZE)) {
2958 return -ENOTSUP;
2960 sd_aio_setup(&acb, s, &discard_iov, offset >> BDRV_SECTOR_BITS,
2961 count >> BDRV_SECTOR_BITS, AIOCB_DISCARD_OBJ);
2962 sd_co_rw_vector(&acb);
2963 sd_aio_complete(&acb);
2965 return acb.ret;
2968 static coroutine_fn int64_t
2969 sd_co_get_block_status(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
2970 int *pnum, BlockDriverState **file)
2972 BDRVSheepdogState *s = bs->opaque;
2973 SheepdogInode *inode = &s->inode;
2974 uint32_t object_size = (UINT32_C(1) << inode->block_size_shift);
2975 uint64_t offset = sector_num * BDRV_SECTOR_SIZE;
2976 unsigned long start = offset / object_size,
2977 end = DIV_ROUND_UP((sector_num + nb_sectors) *
2978 BDRV_SECTOR_SIZE, object_size);
2979 unsigned long idx;
2980 int64_t ret = BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | offset;
2982 for (idx = start; idx < end; idx++) {
2983 if (inode->data_vdi_id[idx] == 0) {
2984 break;
2987 if (idx == start) {
2988 /* Get the longest length of unallocated sectors */
2989 ret = 0;
2990 for (idx = start + 1; idx < end; idx++) {
2991 if (inode->data_vdi_id[idx] != 0) {
2992 break;
2997 *pnum = (idx - start) * object_size / BDRV_SECTOR_SIZE;
2998 if (*pnum > nb_sectors) {
2999 *pnum = nb_sectors;
3001 if (ret > 0 && ret & BDRV_BLOCK_OFFSET_VALID) {
3002 *file = bs;
3004 return ret;
3007 static int64_t sd_get_allocated_file_size(BlockDriverState *bs)
3009 BDRVSheepdogState *s = bs->opaque;
3010 SheepdogInode *inode = &s->inode;
3011 uint32_t object_size = (UINT32_C(1) << inode->block_size_shift);
3012 unsigned long i, last = DIV_ROUND_UP(inode->vdi_size, object_size);
3013 uint64_t size = 0;
3015 for (i = 0; i < last; i++) {
3016 if (inode->data_vdi_id[i] == 0) {
3017 continue;
3019 size += object_size;
3021 return size;
3024 static QemuOptsList sd_create_opts = {
3025 .name = "sheepdog-create-opts",
3026 .head = QTAILQ_HEAD_INITIALIZER(sd_create_opts.head),
3027 .desc = {
3029 .name = BLOCK_OPT_SIZE,
3030 .type = QEMU_OPT_SIZE,
3031 .help = "Virtual disk size"
3034 .name = BLOCK_OPT_BACKING_FILE,
3035 .type = QEMU_OPT_STRING,
3036 .help = "File name of a base image"
3039 .name = BLOCK_OPT_PREALLOC,
3040 .type = QEMU_OPT_STRING,
3041 .help = "Preallocation mode (allowed values: off, full)"
3044 .name = BLOCK_OPT_REDUNDANCY,
3045 .type = QEMU_OPT_STRING,
3046 .help = "Redundancy of the image"
3049 .name = BLOCK_OPT_OBJECT_SIZE,
3050 .type = QEMU_OPT_SIZE,
3051 .help = "Object size of the image"
3053 { /* end of list */ }
3057 static BlockDriver bdrv_sheepdog = {
3058 .format_name = "sheepdog",
3059 .protocol_name = "sheepdog",
3060 .instance_size = sizeof(BDRVSheepdogState),
3061 .bdrv_parse_filename = sd_parse_filename,
3062 .bdrv_file_open = sd_open,
3063 .bdrv_reopen_prepare = sd_reopen_prepare,
3064 .bdrv_reopen_commit = sd_reopen_commit,
3065 .bdrv_reopen_abort = sd_reopen_abort,
3066 .bdrv_close = sd_close,
3067 .bdrv_create = sd_create,
3068 .bdrv_has_zero_init = bdrv_has_zero_init_1,
3069 .bdrv_getlength = sd_getlength,
3070 .bdrv_get_allocated_file_size = sd_get_allocated_file_size,
3071 .bdrv_truncate = sd_truncate,
3073 .bdrv_co_readv = sd_co_readv,
3074 .bdrv_co_writev = sd_co_writev,
3075 .bdrv_co_flush_to_disk = sd_co_flush_to_disk,
3076 .bdrv_co_pdiscard = sd_co_pdiscard,
3077 .bdrv_co_get_block_status = sd_co_get_block_status,
3079 .bdrv_snapshot_create = sd_snapshot_create,
3080 .bdrv_snapshot_goto = sd_snapshot_goto,
3081 .bdrv_snapshot_delete = sd_snapshot_delete,
3082 .bdrv_snapshot_list = sd_snapshot_list,
3084 .bdrv_save_vmstate = sd_save_vmstate,
3085 .bdrv_load_vmstate = sd_load_vmstate,
3087 .bdrv_detach_aio_context = sd_detach_aio_context,
3088 .bdrv_attach_aio_context = sd_attach_aio_context,
3090 .create_opts = &sd_create_opts,
3093 static BlockDriver bdrv_sheepdog_tcp = {
3094 .format_name = "sheepdog",
3095 .protocol_name = "sheepdog+tcp",
3096 .instance_size = sizeof(BDRVSheepdogState),
3097 .bdrv_parse_filename = sd_parse_filename,
3098 .bdrv_file_open = sd_open,
3099 .bdrv_reopen_prepare = sd_reopen_prepare,
3100 .bdrv_reopen_commit = sd_reopen_commit,
3101 .bdrv_reopen_abort = sd_reopen_abort,
3102 .bdrv_close = sd_close,
3103 .bdrv_create = sd_create,
3104 .bdrv_has_zero_init = bdrv_has_zero_init_1,
3105 .bdrv_getlength = sd_getlength,
3106 .bdrv_get_allocated_file_size = sd_get_allocated_file_size,
3107 .bdrv_truncate = sd_truncate,
3109 .bdrv_co_readv = sd_co_readv,
3110 .bdrv_co_writev = sd_co_writev,
3111 .bdrv_co_flush_to_disk = sd_co_flush_to_disk,
3112 .bdrv_co_pdiscard = sd_co_pdiscard,
3113 .bdrv_co_get_block_status = sd_co_get_block_status,
3115 .bdrv_snapshot_create = sd_snapshot_create,
3116 .bdrv_snapshot_goto = sd_snapshot_goto,
3117 .bdrv_snapshot_delete = sd_snapshot_delete,
3118 .bdrv_snapshot_list = sd_snapshot_list,
3120 .bdrv_save_vmstate = sd_save_vmstate,
3121 .bdrv_load_vmstate = sd_load_vmstate,
3123 .bdrv_detach_aio_context = sd_detach_aio_context,
3124 .bdrv_attach_aio_context = sd_attach_aio_context,
3126 .create_opts = &sd_create_opts,
3129 static BlockDriver bdrv_sheepdog_unix = {
3130 .format_name = "sheepdog",
3131 .protocol_name = "sheepdog+unix",
3132 .instance_size = sizeof(BDRVSheepdogState),
3133 .bdrv_parse_filename = sd_parse_filename,
3134 .bdrv_file_open = sd_open,
3135 .bdrv_reopen_prepare = sd_reopen_prepare,
3136 .bdrv_reopen_commit = sd_reopen_commit,
3137 .bdrv_reopen_abort = sd_reopen_abort,
3138 .bdrv_close = sd_close,
3139 .bdrv_create = sd_create,
3140 .bdrv_has_zero_init = bdrv_has_zero_init_1,
3141 .bdrv_getlength = sd_getlength,
3142 .bdrv_get_allocated_file_size = sd_get_allocated_file_size,
3143 .bdrv_truncate = sd_truncate,
3145 .bdrv_co_readv = sd_co_readv,
3146 .bdrv_co_writev = sd_co_writev,
3147 .bdrv_co_flush_to_disk = sd_co_flush_to_disk,
3148 .bdrv_co_pdiscard = sd_co_pdiscard,
3149 .bdrv_co_get_block_status = sd_co_get_block_status,
3151 .bdrv_snapshot_create = sd_snapshot_create,
3152 .bdrv_snapshot_goto = sd_snapshot_goto,
3153 .bdrv_snapshot_delete = sd_snapshot_delete,
3154 .bdrv_snapshot_list = sd_snapshot_list,
3156 .bdrv_save_vmstate = sd_save_vmstate,
3157 .bdrv_load_vmstate = sd_load_vmstate,
3159 .bdrv_detach_aio_context = sd_detach_aio_context,
3160 .bdrv_attach_aio_context = sd_attach_aio_context,
3162 .create_opts = &sd_create_opts,
3165 static void bdrv_sheepdog_init(void)
3167 bdrv_register(&bdrv_sheepdog);
3168 bdrv_register(&bdrv_sheepdog_tcp);
3169 bdrv_register(&bdrv_sheepdog_unix);
3171 block_init(bdrv_sheepdog_init);