]> Git Repo - qemu.git/blob - block/sheepdog.c
block: Add BdrvChildRole.get_parent_desc()
[qemu.git] / block / sheepdog.c
1 /*
2  * Copyright (C) 2009-2010 Nippon Telegraph and Telephone Corporation.
3  *
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.
7  *
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/>.
10  *
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.
13  */
14
15 #include "qemu/osdep.h"
16 #include "qapi/error.h"
17 #include "qemu/uri.h"
18 #include "qemu/error-report.h"
19 #include "qemu/sockets.h"
20 #include "block/block_int.h"
21 #include "sysemu/block-backend.h"
22 #include "qemu/bitops.h"
23 #include "qemu/cutils.h"
24
25 #define SD_PROTO_VER 0x01
26
27 #define SD_DEFAULT_ADDR "localhost"
28 #define SD_DEFAULT_PORT 7000
29
30 #define SD_OP_CREATE_AND_WRITE_OBJ  0x01
31 #define SD_OP_READ_OBJ       0x02
32 #define SD_OP_WRITE_OBJ      0x03
33 /* 0x04 is used internally by Sheepdog */
34
35 #define SD_OP_NEW_VDI        0x11
36 #define SD_OP_LOCK_VDI       0x12
37 #define SD_OP_RELEASE_VDI    0x13
38 #define SD_OP_GET_VDI_INFO   0x14
39 #define SD_OP_READ_VDIS      0x15
40 #define SD_OP_FLUSH_VDI      0x16
41 #define SD_OP_DEL_VDI        0x17
42 #define SD_OP_GET_CLUSTER_DEFAULT   0x18
43
44 #define SD_FLAG_CMD_WRITE    0x01
45 #define SD_FLAG_CMD_COW      0x02
46 #define SD_FLAG_CMD_CACHE    0x04 /* Writeback mode for cache */
47 #define SD_FLAG_CMD_DIRECT   0x08 /* Don't use cache */
48
49 #define SD_RES_SUCCESS       0x00 /* Success */
50 #define SD_RES_UNKNOWN       0x01 /* Unknown error */
51 #define SD_RES_NO_OBJ        0x02 /* No object found */
52 #define SD_RES_EIO           0x03 /* I/O error */
53 #define SD_RES_VDI_EXIST     0x04 /* Vdi exists already */
54 #define SD_RES_INVALID_PARMS 0x05 /* Invalid parameters */
55 #define SD_RES_SYSTEM_ERROR  0x06 /* System error */
56 #define SD_RES_VDI_LOCKED    0x07 /* Vdi is locked */
57 #define SD_RES_NO_VDI        0x08 /* No vdi found */
58 #define SD_RES_NO_BASE_VDI   0x09 /* No base vdi found */
59 #define SD_RES_VDI_READ      0x0A /* Cannot read requested vdi */
60 #define SD_RES_VDI_WRITE     0x0B /* Cannot write requested vdi */
61 #define SD_RES_BASE_VDI_READ 0x0C /* Cannot read base vdi */
62 #define SD_RES_BASE_VDI_WRITE   0x0D /* Cannot write base vdi */
63 #define SD_RES_NO_TAG        0x0E /* Requested tag is not found */
64 #define SD_RES_STARTUP       0x0F /* Sheepdog is on starting up */
65 #define SD_RES_VDI_NOT_LOCKED   0x10 /* Vdi is not locked */
66 #define SD_RES_SHUTDOWN      0x11 /* Sheepdog is shutting down */
67 #define SD_RES_NO_MEM        0x12 /* Cannot allocate memory */
68 #define SD_RES_FULL_VDI      0x13 /* we already have the maximum vdis */
69 #define SD_RES_VER_MISMATCH  0x14 /* Protocol version mismatch */
70 #define SD_RES_NO_SPACE      0x15 /* Server has no room for new objects */
71 #define SD_RES_WAIT_FOR_FORMAT  0x16 /* Waiting for a format operation */
72 #define SD_RES_WAIT_FOR_JOIN    0x17 /* Waiting for other nodes joining */
73 #define SD_RES_JOIN_FAILED   0x18 /* Target node had failed to join sheepdog */
74 #define SD_RES_HALT          0x19 /* Sheepdog is stopped serving IO request */
75 #define SD_RES_READONLY      0x1A /* Object is read-only */
76
77 /*
78  * Object ID rules
79  *
80  *  0 - 19 (20 bits): data object space
81  * 20 - 31 (12 bits): reserved data object space
82  * 32 - 55 (24 bits): vdi object space
83  * 56 - 59 ( 4 bits): reserved vdi object space
84  * 60 - 63 ( 4 bits): object type identifier space
85  */
86
87 #define VDI_SPACE_SHIFT   32
88 #define VDI_BIT (UINT64_C(1) << 63)
89 #define VMSTATE_BIT (UINT64_C(1) << 62)
90 #define MAX_DATA_OBJS (UINT64_C(1) << 20)
91 #define MAX_CHILDREN 1024
92 #define SD_MAX_VDI_LEN 256
93 #define SD_MAX_VDI_TAG_LEN 256
94 #define SD_NR_VDIS   (1U << 24)
95 #define SD_DATA_OBJ_SIZE (UINT64_C(1) << 22)
96 #define SD_MAX_VDI_SIZE (SD_DATA_OBJ_SIZE * MAX_DATA_OBJS)
97 #define SD_DEFAULT_BLOCK_SIZE_SHIFT 22
98 /*
99  * For erasure coding, we use at most SD_EC_MAX_STRIP for data strips and
100  * (SD_EC_MAX_STRIP - 1) for parity strips
101  *
102  * SD_MAX_COPIES is sum of number of data strips and parity strips.
103  */
104 #define SD_EC_MAX_STRIP 16
105 #define SD_MAX_COPIES (SD_EC_MAX_STRIP * 2 - 1)
106
107 #define SD_INODE_SIZE (sizeof(SheepdogInode))
108 #define CURRENT_VDI_ID 0
109
110 #define LOCK_TYPE_NORMAL 0
111 #define LOCK_TYPE_SHARED 1      /* for iSCSI multipath */
112
113 typedef struct SheepdogReq {
114     uint8_t proto_ver;
115     uint8_t opcode;
116     uint16_t flags;
117     uint32_t epoch;
118     uint32_t id;
119     uint32_t data_length;
120     uint32_t opcode_specific[8];
121 } SheepdogReq;
122
123 typedef struct SheepdogRsp {
124     uint8_t proto_ver;
125     uint8_t opcode;
126     uint16_t flags;
127     uint32_t epoch;
128     uint32_t id;
129     uint32_t data_length;
130     uint32_t result;
131     uint32_t opcode_specific[7];
132 } SheepdogRsp;
133
134 typedef struct SheepdogObjReq {
135     uint8_t proto_ver;
136     uint8_t opcode;
137     uint16_t flags;
138     uint32_t epoch;
139     uint32_t id;
140     uint32_t data_length;
141     uint64_t oid;
142     uint64_t cow_oid;
143     uint8_t copies;
144     uint8_t copy_policy;
145     uint8_t reserved[6];
146     uint64_t offset;
147 } SheepdogObjReq;
148
149 typedef struct SheepdogObjRsp {
150     uint8_t proto_ver;
151     uint8_t opcode;
152     uint16_t flags;
153     uint32_t epoch;
154     uint32_t id;
155     uint32_t data_length;
156     uint32_t result;
157     uint8_t copies;
158     uint8_t copy_policy;
159     uint8_t reserved[2];
160     uint32_t pad[6];
161 } SheepdogObjRsp;
162
163 typedef struct SheepdogVdiReq {
164     uint8_t proto_ver;
165     uint8_t opcode;
166     uint16_t flags;
167     uint32_t epoch;
168     uint32_t id;
169     uint32_t data_length;
170     uint64_t vdi_size;
171     uint32_t base_vdi_id;
172     uint8_t copies;
173     uint8_t copy_policy;
174     uint8_t store_policy;
175     uint8_t block_size_shift;
176     uint32_t snapid;
177     uint32_t type;
178     uint32_t pad[2];
179 } SheepdogVdiReq;
180
181 typedef struct SheepdogVdiRsp {
182     uint8_t proto_ver;
183     uint8_t opcode;
184     uint16_t flags;
185     uint32_t epoch;
186     uint32_t id;
187     uint32_t data_length;
188     uint32_t result;
189     uint32_t rsvd;
190     uint32_t vdi_id;
191     uint32_t pad[5];
192 } SheepdogVdiRsp;
193
194 typedef struct SheepdogClusterRsp {
195     uint8_t proto_ver;
196     uint8_t opcode;
197     uint16_t flags;
198     uint32_t epoch;
199     uint32_t id;
200     uint32_t data_length;
201     uint32_t result;
202     uint8_t nr_copies;
203     uint8_t copy_policy;
204     uint8_t block_size_shift;
205     uint8_t __pad1;
206     uint32_t __pad2[6];
207 } SheepdogClusterRsp;
208
209 typedef struct SheepdogInode {
210     char name[SD_MAX_VDI_LEN];
211     char tag[SD_MAX_VDI_TAG_LEN];
212     uint64_t ctime;
213     uint64_t snap_ctime;
214     uint64_t vm_clock_nsec;
215     uint64_t vdi_size;
216     uint64_t vm_state_size;
217     uint16_t copy_policy;
218     uint8_t nr_copies;
219     uint8_t block_size_shift;
220     uint32_t snap_id;
221     uint32_t vdi_id;
222     uint32_t parent_vdi_id;
223     uint32_t child_vdi_id[MAX_CHILDREN];
224     uint32_t data_vdi_id[MAX_DATA_OBJS];
225 } SheepdogInode;
226
227 #define SD_INODE_HEADER_SIZE offsetof(SheepdogInode, data_vdi_id)
228
229 /*
230  * 64 bit FNV-1a non-zero initial basis
231  */
232 #define FNV1A_64_INIT ((uint64_t)0xcbf29ce484222325ULL)
233
234 /*
235  * 64 bit Fowler/Noll/Vo FNV-1a hash code
236  */
237 static inline uint64_t fnv_64a_buf(void *buf, size_t len, uint64_t hval)
238 {
239     unsigned char *bp = buf;
240     unsigned char *be = bp + len;
241     while (bp < be) {
242         hval ^= (uint64_t) *bp++;
243         hval += (hval << 1) + (hval << 4) + (hval << 5) +
244             (hval << 7) + (hval << 8) + (hval << 40);
245     }
246     return hval;
247 }
248
249 static inline bool is_data_obj_writable(SheepdogInode *inode, unsigned int idx)
250 {
251     return inode->vdi_id == inode->data_vdi_id[idx];
252 }
253
254 static inline bool is_data_obj(uint64_t oid)
255 {
256     return !(VDI_BIT & oid);
257 }
258
259 static inline uint64_t data_oid_to_idx(uint64_t oid)
260 {
261     return oid & (MAX_DATA_OBJS - 1);
262 }
263
264 static inline uint32_t oid_to_vid(uint64_t oid)
265 {
266     return (oid & ~VDI_BIT) >> VDI_SPACE_SHIFT;
267 }
268
269 static inline uint64_t vid_to_vdi_oid(uint32_t vid)
270 {
271     return VDI_BIT | ((uint64_t)vid << VDI_SPACE_SHIFT);
272 }
273
274 static inline uint64_t vid_to_vmstate_oid(uint32_t vid, uint32_t idx)
275 {
276     return VMSTATE_BIT | ((uint64_t)vid << VDI_SPACE_SHIFT) | idx;
277 }
278
279 static inline uint64_t vid_to_data_oid(uint32_t vid, uint32_t idx)
280 {
281     return ((uint64_t)vid << VDI_SPACE_SHIFT) | idx;
282 }
283
284 static inline bool is_snapshot(struct SheepdogInode *inode)
285 {
286     return !!inode->snap_ctime;
287 }
288
289 static inline size_t count_data_objs(const struct SheepdogInode *inode)
290 {
291     return DIV_ROUND_UP(inode->vdi_size,
292                         (1UL << inode->block_size_shift));
293 }
294
295 #undef DPRINTF
296 #ifdef DEBUG_SDOG
297 #define DEBUG_SDOG_PRINT 1
298 #else
299 #define DEBUG_SDOG_PRINT 0
300 #endif
301 #define DPRINTF(fmt, args...)                                           \
302     do {                                                                \
303         if (DEBUG_SDOG_PRINT) {                                         \
304             fprintf(stderr, "%s %d: " fmt, __func__, __LINE__, ##args); \
305         }                                                               \
306     } while (0)
307
308 typedef struct SheepdogAIOCB SheepdogAIOCB;
309 typedef struct BDRVSheepdogState BDRVSheepdogState;
310
311 typedef struct AIOReq {
312     SheepdogAIOCB *aiocb;
313     unsigned int iov_offset;
314
315     uint64_t oid;
316     uint64_t base_oid;
317     uint64_t offset;
318     unsigned int data_len;
319     uint8_t flags;
320     uint32_t id;
321     bool create;
322
323     QLIST_ENTRY(AIOReq) aio_siblings;
324 } AIOReq;
325
326 enum AIOCBState {
327     AIOCB_WRITE_UDATA,
328     AIOCB_READ_UDATA,
329     AIOCB_FLUSH_CACHE,
330     AIOCB_DISCARD_OBJ,
331 };
332
333 #define AIOCBOverlapping(x, y)                                 \
334     (!(x->max_affect_data_idx < y->min_affect_data_idx          \
335        || y->max_affect_data_idx < x->min_affect_data_idx))
336
337 struct SheepdogAIOCB {
338     BDRVSheepdogState *s;
339
340     QEMUIOVector *qiov;
341
342     int64_t sector_num;
343     int nb_sectors;
344
345     int ret;
346     enum AIOCBState aiocb_type;
347
348     Coroutine *coroutine;
349     int nr_pending;
350
351     uint32_t min_affect_data_idx;
352     uint32_t max_affect_data_idx;
353
354     /*
355      * The difference between affect_data_idx and dirty_data_idx:
356      * affect_data_idx represents range of index of all request types.
357      * dirty_data_idx represents range of index updated by COW requests.
358      * dirty_data_idx is used for updating an inode object.
359      */
360     uint32_t min_dirty_data_idx;
361     uint32_t max_dirty_data_idx;
362
363     QLIST_ENTRY(SheepdogAIOCB) aiocb_siblings;
364 };
365
366 struct BDRVSheepdogState {
367     BlockDriverState *bs;
368     AioContext *aio_context;
369
370     SheepdogInode inode;
371
372     char name[SD_MAX_VDI_LEN];
373     bool is_snapshot;
374     uint32_t cache_flags;
375     bool discard_supported;
376
377     char *host_spec;
378     bool is_unix;
379     int fd;
380
381     CoMutex lock;
382     Coroutine *co_send;
383     Coroutine *co_recv;
384
385     uint32_t aioreq_seq_num;
386
387     /* Every aio request must be linked to either of these queues. */
388     QLIST_HEAD(inflight_aio_head, AIOReq) inflight_aio_head;
389     QLIST_HEAD(failed_aio_head, AIOReq) failed_aio_head;
390
391     CoQueue overlapping_queue;
392     QLIST_HEAD(inflight_aiocb_head, SheepdogAIOCB) inflight_aiocb_head;
393 };
394
395 typedef struct BDRVSheepdogReopenState {
396     int fd;
397     int cache_flags;
398 } BDRVSheepdogReopenState;
399
400 static const char * sd_strerror(int err)
401 {
402     int i;
403
404     static const struct {
405         int err;
406         const char *desc;
407     } errors[] = {
408         {SD_RES_SUCCESS, "Success"},
409         {SD_RES_UNKNOWN, "Unknown error"},
410         {SD_RES_NO_OBJ, "No object found"},
411         {SD_RES_EIO, "I/O error"},
412         {SD_RES_VDI_EXIST, "VDI exists already"},
413         {SD_RES_INVALID_PARMS, "Invalid parameters"},
414         {SD_RES_SYSTEM_ERROR, "System error"},
415         {SD_RES_VDI_LOCKED, "VDI is already locked"},
416         {SD_RES_NO_VDI, "No vdi found"},
417         {SD_RES_NO_BASE_VDI, "No base VDI found"},
418         {SD_RES_VDI_READ, "Failed read the requested VDI"},
419         {SD_RES_VDI_WRITE, "Failed to write the requested VDI"},
420         {SD_RES_BASE_VDI_READ, "Failed to read the base VDI"},
421         {SD_RES_BASE_VDI_WRITE, "Failed to write the base VDI"},
422         {SD_RES_NO_TAG, "Failed to find the requested tag"},
423         {SD_RES_STARTUP, "The system is still booting"},
424         {SD_RES_VDI_NOT_LOCKED, "VDI isn't locked"},
425         {SD_RES_SHUTDOWN, "The system is shutting down"},
426         {SD_RES_NO_MEM, "Out of memory on the server"},
427         {SD_RES_FULL_VDI, "We already have the maximum vdis"},
428         {SD_RES_VER_MISMATCH, "Protocol version mismatch"},
429         {SD_RES_NO_SPACE, "Server has no space for new objects"},
430         {SD_RES_WAIT_FOR_FORMAT, "Sheepdog is waiting for a format operation"},
431         {SD_RES_WAIT_FOR_JOIN, "Sheepdog is waiting for other nodes joining"},
432         {SD_RES_JOIN_FAILED, "Target node had failed to join sheepdog"},
433         {SD_RES_HALT, "Sheepdog is stopped serving IO request"},
434         {SD_RES_READONLY, "Object is read-only"},
435     };
436
437     for (i = 0; i < ARRAY_SIZE(errors); ++i) {
438         if (errors[i].err == err) {
439             return errors[i].desc;
440         }
441     }
442
443     return "Invalid error code";
444 }
445
446 /*
447  * Sheepdog I/O handling:
448  *
449  * 1. In sd_co_rw_vector, we send the I/O requests to the server and
450  *    link the requests to the inflight_list in the
451  *    BDRVSheepdogState.  The function yields while waiting for
452  *    receiving the response.
453  *
454  * 2. We receive the response in aio_read_response, the fd handler to
455  *    the sheepdog connection.  We switch back to sd_co_readv/sd_writev
456  *    after all the requests belonging to the AIOCB are finished.  If
457  *    needed, sd_co_writev will send another requests for the vdi object.
458  */
459
460 static inline AIOReq *alloc_aio_req(BDRVSheepdogState *s, SheepdogAIOCB *acb,
461                                     uint64_t oid, unsigned int data_len,
462                                     uint64_t offset, uint8_t flags, bool create,
463                                     uint64_t base_oid, unsigned int iov_offset)
464 {
465     AIOReq *aio_req;
466
467     aio_req = g_malloc(sizeof(*aio_req));
468     aio_req->aiocb = acb;
469     aio_req->iov_offset = iov_offset;
470     aio_req->oid = oid;
471     aio_req->base_oid = base_oid;
472     aio_req->offset = offset;
473     aio_req->data_len = data_len;
474     aio_req->flags = flags;
475     aio_req->id = s->aioreq_seq_num++;
476     aio_req->create = create;
477
478     acb->nr_pending++;
479     return aio_req;
480 }
481
482 static void wait_for_overlapping_aiocb(BDRVSheepdogState *s, SheepdogAIOCB *acb)
483 {
484     SheepdogAIOCB *cb;
485
486 retry:
487     QLIST_FOREACH(cb, &s->inflight_aiocb_head, aiocb_siblings) {
488         if (AIOCBOverlapping(acb, cb)) {
489             qemu_co_queue_wait(&s->overlapping_queue, NULL);
490             goto retry;
491         }
492     }
493 }
494
495 static void sd_aio_setup(SheepdogAIOCB *acb, BDRVSheepdogState *s,
496                          QEMUIOVector *qiov, int64_t sector_num, int nb_sectors,
497                          int type)
498 {
499     uint32_t object_size;
500
501     object_size = (UINT32_C(1) << s->inode.block_size_shift);
502
503     acb->s = s;
504
505     acb->qiov = qiov;
506
507     acb->sector_num = sector_num;
508     acb->nb_sectors = nb_sectors;
509
510     acb->coroutine = qemu_coroutine_self();
511     acb->ret = 0;
512     acb->nr_pending = 0;
513
514     acb->min_affect_data_idx = acb->sector_num * BDRV_SECTOR_SIZE / object_size;
515     acb->max_affect_data_idx = (acb->sector_num * BDRV_SECTOR_SIZE +
516                               acb->nb_sectors * BDRV_SECTOR_SIZE) / object_size;
517
518     acb->min_dirty_data_idx = UINT32_MAX;
519     acb->max_dirty_data_idx = 0;
520     acb->aiocb_type = type;
521
522     if (type == AIOCB_FLUSH_CACHE) {
523         return;
524     }
525
526     wait_for_overlapping_aiocb(s, acb);
527     QLIST_INSERT_HEAD(&s->inflight_aiocb_head, acb, aiocb_siblings);
528 }
529
530 /* Return -EIO in case of error, file descriptor on success */
531 static int connect_to_sdog(BDRVSheepdogState *s, Error **errp)
532 {
533     int fd;
534
535     if (s->is_unix) {
536         fd = unix_connect(s->host_spec, errp);
537     } else {
538         fd = inet_connect(s->host_spec, errp);
539
540         if (fd >= 0) {
541             int ret = socket_set_nodelay(fd);
542             if (ret < 0) {
543                 error_report("%s", strerror(errno));
544             }
545         }
546     }
547
548     if (fd >= 0) {
549         qemu_set_nonblock(fd);
550     } else {
551         fd = -EIO;
552     }
553
554     return fd;
555 }
556
557 /* Return 0 on success and -errno in case of error */
558 static coroutine_fn int send_co_req(int sockfd, SheepdogReq *hdr, void *data,
559                                     unsigned int *wlen)
560 {
561     int ret;
562
563     ret = qemu_co_send(sockfd, hdr, sizeof(*hdr));
564     if (ret != sizeof(*hdr)) {
565         error_report("failed to send a req, %s", strerror(errno));
566         return -errno;
567     }
568
569     ret = qemu_co_send(sockfd, data, *wlen);
570     if (ret != *wlen) {
571         error_report("failed to send a req, %s", strerror(errno));
572         return -errno;
573     }
574
575     return ret;
576 }
577
578 typedef struct SheepdogReqCo {
579     int sockfd;
580     BlockDriverState *bs;
581     AioContext *aio_context;
582     SheepdogReq *hdr;
583     void *data;
584     unsigned int *wlen;
585     unsigned int *rlen;
586     int ret;
587     bool finished;
588     Coroutine *co;
589 } SheepdogReqCo;
590
591 static void restart_co_req(void *opaque)
592 {
593     SheepdogReqCo *srco = opaque;
594
595     aio_co_wake(srco->co);
596 }
597
598 static coroutine_fn void do_co_req(void *opaque)
599 {
600     int ret;
601     SheepdogReqCo *srco = opaque;
602     int sockfd = srco->sockfd;
603     SheepdogReq *hdr = srco->hdr;
604     void *data = srco->data;
605     unsigned int *wlen = srco->wlen;
606     unsigned int *rlen = srco->rlen;
607
608     srco->co = qemu_coroutine_self();
609     aio_set_fd_handler(srco->aio_context, sockfd, false,
610                        NULL, restart_co_req, NULL, srco);
611
612     ret = send_co_req(sockfd, hdr, data, wlen);
613     if (ret < 0) {
614         goto out;
615     }
616
617     aio_set_fd_handler(srco->aio_context, sockfd, false,
618                        restart_co_req, NULL, NULL, srco);
619
620     ret = qemu_co_recv(sockfd, hdr, sizeof(*hdr));
621     if (ret != sizeof(*hdr)) {
622         error_report("failed to get a rsp, %s", strerror(errno));
623         ret = -errno;
624         goto out;
625     }
626
627     if (*rlen > hdr->data_length) {
628         *rlen = hdr->data_length;
629     }
630
631     if (*rlen) {
632         ret = qemu_co_recv(sockfd, data, *rlen);
633         if (ret != *rlen) {
634             error_report("failed to get the data, %s", strerror(errno));
635             ret = -errno;
636             goto out;
637         }
638     }
639     ret = 0;
640 out:
641     /* there is at most one request for this sockfd, so it is safe to
642      * set each handler to NULL. */
643     aio_set_fd_handler(srco->aio_context, sockfd, false,
644                        NULL, NULL, NULL, NULL);
645
646     srco->co = NULL;
647     srco->ret = ret;
648     srco->finished = true;
649     if (srco->bs) {
650         bdrv_wakeup(srco->bs);
651     }
652 }
653
654 /*
655  * Send the request to the sheep in a synchronous manner.
656  *
657  * Return 0 on success, -errno in case of error.
658  */
659 static int do_req(int sockfd, BlockDriverState *bs, SheepdogReq *hdr,
660                   void *data, unsigned int *wlen, unsigned int *rlen)
661 {
662     Coroutine *co;
663     SheepdogReqCo srco = {
664         .sockfd = sockfd,
665         .aio_context = bs ? bdrv_get_aio_context(bs) : qemu_get_aio_context(),
666         .bs = bs,
667         .hdr = hdr,
668         .data = data,
669         .wlen = wlen,
670         .rlen = rlen,
671         .ret = 0,
672         .finished = false,
673     };
674
675     if (qemu_in_coroutine()) {
676         do_co_req(&srco);
677     } else {
678         co = qemu_coroutine_create(do_co_req, &srco);
679         if (bs) {
680             qemu_coroutine_enter(co);
681             BDRV_POLL_WHILE(bs, !srco.finished);
682         } else {
683             qemu_coroutine_enter(co);
684             while (!srco.finished) {
685                 aio_poll(qemu_get_aio_context(), true);
686             }
687         }
688     }
689
690     return srco.ret;
691 }
692
693 static void coroutine_fn add_aio_request(BDRVSheepdogState *s, AIOReq *aio_req,
694                                          struct iovec *iov, int niov,
695                                          enum AIOCBState aiocb_type);
696 static void coroutine_fn resend_aioreq(BDRVSheepdogState *s, AIOReq *aio_req);
697 static int reload_inode(BDRVSheepdogState *s, uint32_t snapid, const char *tag);
698 static int get_sheep_fd(BDRVSheepdogState *s, Error **errp);
699 static void co_write_request(void *opaque);
700
701 static coroutine_fn void reconnect_to_sdog(void *opaque)
702 {
703     BDRVSheepdogState *s = opaque;
704     AIOReq *aio_req, *next;
705
706     aio_set_fd_handler(s->aio_context, s->fd, false, NULL,
707                        NULL, NULL, NULL);
708     close(s->fd);
709     s->fd = -1;
710
711     /* Wait for outstanding write requests to be completed. */
712     while (s->co_send != NULL) {
713         co_write_request(opaque);
714     }
715
716     /* Try to reconnect the sheepdog server every one second. */
717     while (s->fd < 0) {
718         Error *local_err = NULL;
719         s->fd = get_sheep_fd(s, &local_err);
720         if (s->fd < 0) {
721             DPRINTF("Wait for connection to be established\n");
722             error_report_err(local_err);
723             co_aio_sleep_ns(bdrv_get_aio_context(s->bs), QEMU_CLOCK_REALTIME,
724                             1000000000ULL);
725         }
726     };
727
728     /*
729      * Now we have to resend all the request in the inflight queue.  However,
730      * resend_aioreq() can yield and newly created requests can be added to the
731      * inflight queue before the coroutine is resumed.  To avoid mixing them, we
732      * have to move all the inflight requests to the failed queue before
733      * resend_aioreq() is called.
734      */
735     QLIST_FOREACH_SAFE(aio_req, &s->inflight_aio_head, aio_siblings, next) {
736         QLIST_REMOVE(aio_req, aio_siblings);
737         QLIST_INSERT_HEAD(&s->failed_aio_head, aio_req, aio_siblings);
738     }
739
740     /* Resend all the failed aio requests. */
741     while (!QLIST_EMPTY(&s->failed_aio_head)) {
742         aio_req = QLIST_FIRST(&s->failed_aio_head);
743         QLIST_REMOVE(aio_req, aio_siblings);
744         resend_aioreq(s, aio_req);
745     }
746 }
747
748 /*
749  * Receive responses of the I/O requests.
750  *
751  * This function is registered as a fd handler, and called from the
752  * main loop when s->fd is ready for reading responses.
753  */
754 static void coroutine_fn aio_read_response(void *opaque)
755 {
756     SheepdogObjRsp rsp;
757     BDRVSheepdogState *s = opaque;
758     int fd = s->fd;
759     int ret;
760     AIOReq *aio_req = NULL;
761     SheepdogAIOCB *acb;
762     uint64_t idx;
763
764     /* read a header */
765     ret = qemu_co_recv(fd, &rsp, sizeof(rsp));
766     if (ret != sizeof(rsp)) {
767         error_report("failed to get the header, %s", strerror(errno));
768         goto err;
769     }
770
771     /* find the right aio_req from the inflight aio list */
772     QLIST_FOREACH(aio_req, &s->inflight_aio_head, aio_siblings) {
773         if (aio_req->id == rsp.id) {
774             break;
775         }
776     }
777     if (!aio_req) {
778         error_report("cannot find aio_req %x", rsp.id);
779         goto err;
780     }
781
782     acb = aio_req->aiocb;
783
784     switch (acb->aiocb_type) {
785     case AIOCB_WRITE_UDATA:
786         if (!is_data_obj(aio_req->oid)) {
787             break;
788         }
789         idx = data_oid_to_idx(aio_req->oid);
790
791         if (aio_req->create) {
792             /*
793              * If the object is newly created one, we need to update
794              * the vdi object (metadata object).  min_dirty_data_idx
795              * and max_dirty_data_idx are changed to include updated
796              * index between them.
797              */
798             if (rsp.result == SD_RES_SUCCESS) {
799                 s->inode.data_vdi_id[idx] = s->inode.vdi_id;
800                 acb->max_dirty_data_idx = MAX(idx, acb->max_dirty_data_idx);
801                 acb->min_dirty_data_idx = MIN(idx, acb->min_dirty_data_idx);
802             }
803         }
804         break;
805     case AIOCB_READ_UDATA:
806         ret = qemu_co_recvv(fd, acb->qiov->iov, acb->qiov->niov,
807                             aio_req->iov_offset, rsp.data_length);
808         if (ret != rsp.data_length) {
809             error_report("failed to get the data, %s", strerror(errno));
810             goto err;
811         }
812         break;
813     case AIOCB_FLUSH_CACHE:
814         if (rsp.result == SD_RES_INVALID_PARMS) {
815             DPRINTF("disable cache since the server doesn't support it\n");
816             s->cache_flags = SD_FLAG_CMD_DIRECT;
817             rsp.result = SD_RES_SUCCESS;
818         }
819         break;
820     case AIOCB_DISCARD_OBJ:
821         switch (rsp.result) {
822         case SD_RES_INVALID_PARMS:
823             error_report("sheep(%s) doesn't support discard command",
824                          s->host_spec);
825             rsp.result = SD_RES_SUCCESS;
826             s->discard_supported = false;
827             break;
828         default:
829             break;
830         }
831     }
832
833     /* No more data for this aio_req (reload_inode below uses its own file
834      * descriptor handler which doesn't use co_recv).
835     */
836     s->co_recv = NULL;
837
838     QLIST_REMOVE(aio_req, aio_siblings);
839     switch (rsp.result) {
840     case SD_RES_SUCCESS:
841         break;
842     case SD_RES_READONLY:
843         if (s->inode.vdi_id == oid_to_vid(aio_req->oid)) {
844             ret = reload_inode(s, 0, "");
845             if (ret < 0) {
846                 goto err;
847             }
848         }
849         if (is_data_obj(aio_req->oid)) {
850             aio_req->oid = vid_to_data_oid(s->inode.vdi_id,
851                                            data_oid_to_idx(aio_req->oid));
852         } else {
853             aio_req->oid = vid_to_vdi_oid(s->inode.vdi_id);
854         }
855         resend_aioreq(s, aio_req);
856         return;
857     default:
858         acb->ret = -EIO;
859         error_report("%s", sd_strerror(rsp.result));
860         break;
861     }
862
863     g_free(aio_req);
864
865     if (!--acb->nr_pending) {
866         /*
867          * We've finished all requests which belong to the AIOCB, so
868          * we can switch back to sd_co_readv/writev now.
869          */
870         aio_co_wake(acb->coroutine);
871     }
872
873     return;
874
875 err:
876     reconnect_to_sdog(opaque);
877 }
878
879 static void co_read_response(void *opaque)
880 {
881     BDRVSheepdogState *s = opaque;
882
883     if (!s->co_recv) {
884         s->co_recv = qemu_coroutine_create(aio_read_response, opaque);
885     }
886
887     aio_co_wake(s->co_recv);
888 }
889
890 static void co_write_request(void *opaque)
891 {
892     BDRVSheepdogState *s = opaque;
893
894     aio_co_wake(s->co_send);
895 }
896
897 /*
898  * Return a socket descriptor to read/write objects.
899  *
900  * We cannot use this descriptor for other operations because
901  * the block driver may be on waiting response from the server.
902  */
903 static int get_sheep_fd(BDRVSheepdogState *s, Error **errp)
904 {
905     int fd;
906
907     fd = connect_to_sdog(s, errp);
908     if (fd < 0) {
909         return fd;
910     }
911
912     aio_set_fd_handler(s->aio_context, fd, false,
913                        co_read_response, NULL, NULL, s);
914     return fd;
915 }
916
917 static int sd_parse_uri(BDRVSheepdogState *s, const char *filename,
918                         char *vdi, uint32_t *snapid, char *tag)
919 {
920     URI *uri;
921     QueryParams *qp = NULL;
922     int ret = 0;
923
924     uri = uri_parse(filename);
925     if (!uri) {
926         return -EINVAL;
927     }
928
929     /* transport */
930     if (!strcmp(uri->scheme, "sheepdog")) {
931         s->is_unix = false;
932     } else if (!strcmp(uri->scheme, "sheepdog+tcp")) {
933         s->is_unix = false;
934     } else if (!strcmp(uri->scheme, "sheepdog+unix")) {
935         s->is_unix = true;
936     } else {
937         ret = -EINVAL;
938         goto out;
939     }
940
941     if (uri->path == NULL || !strcmp(uri->path, "/")) {
942         ret = -EINVAL;
943         goto out;
944     }
945     pstrcpy(vdi, SD_MAX_VDI_LEN, uri->path + 1);
946
947     qp = query_params_parse(uri->query);
948     if (qp->n > 1 || (s->is_unix && !qp->n) || (!s->is_unix && qp->n)) {
949         ret = -EINVAL;
950         goto out;
951     }
952
953     if (s->is_unix) {
954         /* sheepdog+unix:///vdiname?socket=path */
955         if (uri->server || uri->port || strcmp(qp->p[0].name, "socket")) {
956             ret = -EINVAL;
957             goto out;
958         }
959         s->host_spec = g_strdup(qp->p[0].value);
960     } else {
961         /* sheepdog[+tcp]://[host:port]/vdiname */
962         s->host_spec = g_strdup_printf("%s:%d", uri->server ?: SD_DEFAULT_ADDR,
963                                        uri->port ?: SD_DEFAULT_PORT);
964     }
965
966     /* snapshot tag */
967     if (uri->fragment) {
968         *snapid = strtoul(uri->fragment, NULL, 10);
969         if (*snapid == 0) {
970             pstrcpy(tag, SD_MAX_VDI_TAG_LEN, uri->fragment);
971         }
972     } else {
973         *snapid = CURRENT_VDI_ID; /* search current vdi */
974     }
975
976 out:
977     if (qp) {
978         query_params_free(qp);
979     }
980     uri_free(uri);
981     return ret;
982 }
983
984 /*
985  * Parse a filename (old syntax)
986  *
987  * filename must be one of the following formats:
988  *   1. [vdiname]
989  *   2. [vdiname]:[snapid]
990  *   3. [vdiname]:[tag]
991  *   4. [hostname]:[port]:[vdiname]
992  *   5. [hostname]:[port]:[vdiname]:[snapid]
993  *   6. [hostname]:[port]:[vdiname]:[tag]
994  *
995  * You can boot from the snapshot images by specifying `snapid` or
996  * `tag'.
997  *
998  * You can run VMs outside the Sheepdog cluster by specifying
999  * `hostname' and `port' (experimental).
1000  */
1001 static int parse_vdiname(BDRVSheepdogState *s, const char *filename,
1002                          char *vdi, uint32_t *snapid, char *tag)
1003 {
1004     char *p, *q, *uri;
1005     const char *host_spec, *vdi_spec;
1006     int nr_sep, ret;
1007
1008     strstart(filename, "sheepdog:", &filename);
1009     p = q = g_strdup(filename);
1010
1011     /* count the number of separators */
1012     nr_sep = 0;
1013     while (*p) {
1014         if (*p == ':') {
1015             nr_sep++;
1016         }
1017         p++;
1018     }
1019     p = q;
1020
1021     /* use the first two tokens as host_spec. */
1022     if (nr_sep >= 2) {
1023         host_spec = p;
1024         p = strchr(p, ':');
1025         p++;
1026         p = strchr(p, ':');
1027         *p++ = '\0';
1028     } else {
1029         host_spec = "";
1030     }
1031
1032     vdi_spec = p;
1033
1034     p = strchr(vdi_spec, ':');
1035     if (p) {
1036         *p++ = '#';
1037     }
1038
1039     uri = g_strdup_printf("sheepdog://%s/%s", host_spec, vdi_spec);
1040
1041     ret = sd_parse_uri(s, uri, vdi, snapid, tag);
1042
1043     g_free(q);
1044     g_free(uri);
1045
1046     return ret;
1047 }
1048
1049 static int find_vdi_name(BDRVSheepdogState *s, const char *filename,
1050                          uint32_t snapid, const char *tag, uint32_t *vid,
1051                          bool lock, Error **errp)
1052 {
1053     int ret, fd;
1054     SheepdogVdiReq hdr;
1055     SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
1056     unsigned int wlen, rlen = 0;
1057     char buf[SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN];
1058
1059     fd = connect_to_sdog(s, errp);
1060     if (fd < 0) {
1061         return fd;
1062     }
1063
1064     /* This pair of strncpy calls ensures that the buffer is zero-filled,
1065      * which is desirable since we'll soon be sending those bytes, and
1066      * don't want the send_req to read uninitialized data.
1067      */
1068     strncpy(buf, filename, SD_MAX_VDI_LEN);
1069     strncpy(buf + SD_MAX_VDI_LEN, tag, SD_MAX_VDI_TAG_LEN);
1070
1071     memset(&hdr, 0, sizeof(hdr));
1072     if (lock) {
1073         hdr.opcode = SD_OP_LOCK_VDI;
1074         hdr.type = LOCK_TYPE_NORMAL;
1075     } else {
1076         hdr.opcode = SD_OP_GET_VDI_INFO;
1077     }
1078     wlen = SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN;
1079     hdr.proto_ver = SD_PROTO_VER;
1080     hdr.data_length = wlen;
1081     hdr.snapid = snapid;
1082     hdr.flags = SD_FLAG_CMD_WRITE;
1083
1084     ret = do_req(fd, s->bs, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
1085     if (ret) {
1086         error_setg_errno(errp, -ret, "cannot get vdi info");
1087         goto out;
1088     }
1089
1090     if (rsp->result != SD_RES_SUCCESS) {
1091         error_setg(errp, "cannot get vdi info, %s, %s %" PRIu32 " %s",
1092                    sd_strerror(rsp->result), filename, snapid, tag);
1093         if (rsp->result == SD_RES_NO_VDI) {
1094             ret = -ENOENT;
1095         } else if (rsp->result == SD_RES_VDI_LOCKED) {
1096             ret = -EBUSY;
1097         } else {
1098             ret = -EIO;
1099         }
1100         goto out;
1101     }
1102     *vid = rsp->vdi_id;
1103
1104     ret = 0;
1105 out:
1106     closesocket(fd);
1107     return ret;
1108 }
1109
1110 static void coroutine_fn add_aio_request(BDRVSheepdogState *s, AIOReq *aio_req,
1111                                          struct iovec *iov, int niov,
1112                                          enum AIOCBState aiocb_type)
1113 {
1114     int nr_copies = s->inode.nr_copies;
1115     SheepdogObjReq hdr;
1116     unsigned int wlen = 0;
1117     int ret;
1118     uint64_t oid = aio_req->oid;
1119     unsigned int datalen = aio_req->data_len;
1120     uint64_t offset = aio_req->offset;
1121     uint8_t flags = aio_req->flags;
1122     uint64_t old_oid = aio_req->base_oid;
1123     bool create = aio_req->create;
1124
1125     QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
1126
1127     if (!nr_copies) {
1128         error_report("bug");
1129     }
1130
1131     memset(&hdr, 0, sizeof(hdr));
1132
1133     switch (aiocb_type) {
1134     case AIOCB_FLUSH_CACHE:
1135         hdr.opcode = SD_OP_FLUSH_VDI;
1136         break;
1137     case AIOCB_READ_UDATA:
1138         hdr.opcode = SD_OP_READ_OBJ;
1139         hdr.flags = flags;
1140         break;
1141     case AIOCB_WRITE_UDATA:
1142         if (create) {
1143             hdr.opcode = SD_OP_CREATE_AND_WRITE_OBJ;
1144         } else {
1145             hdr.opcode = SD_OP_WRITE_OBJ;
1146         }
1147         wlen = datalen;
1148         hdr.flags = SD_FLAG_CMD_WRITE | flags;
1149         break;
1150     case AIOCB_DISCARD_OBJ:
1151         hdr.opcode = SD_OP_WRITE_OBJ;
1152         hdr.flags = SD_FLAG_CMD_WRITE | flags;
1153         s->inode.data_vdi_id[data_oid_to_idx(oid)] = 0;
1154         offset = offsetof(SheepdogInode,
1155                           data_vdi_id[data_oid_to_idx(oid)]);
1156         oid = vid_to_vdi_oid(s->inode.vdi_id);
1157         wlen = datalen = sizeof(uint32_t);
1158         break;
1159     }
1160
1161     if (s->cache_flags) {
1162         hdr.flags |= s->cache_flags;
1163     }
1164
1165     hdr.oid = oid;
1166     hdr.cow_oid = old_oid;
1167     hdr.copies = s->inode.nr_copies;
1168
1169     hdr.data_length = datalen;
1170     hdr.offset = offset;
1171
1172     hdr.id = aio_req->id;
1173
1174     qemu_co_mutex_lock(&s->lock);
1175     s->co_send = qemu_coroutine_self();
1176     aio_set_fd_handler(s->aio_context, s->fd, false,
1177                        co_read_response, co_write_request, NULL, s);
1178     socket_set_cork(s->fd, 1);
1179
1180     /* send a header */
1181     ret = qemu_co_send(s->fd, &hdr, sizeof(hdr));
1182     if (ret != sizeof(hdr)) {
1183         error_report("failed to send a req, %s", strerror(errno));
1184         goto out;
1185     }
1186
1187     if (wlen) {
1188         ret = qemu_co_sendv(s->fd, iov, niov, aio_req->iov_offset, wlen);
1189         if (ret != wlen) {
1190             error_report("failed to send a data, %s", strerror(errno));
1191         }
1192     }
1193 out:
1194     socket_set_cork(s->fd, 0);
1195     aio_set_fd_handler(s->aio_context, s->fd, false,
1196                        co_read_response, NULL, NULL, s);
1197     s->co_send = NULL;
1198     qemu_co_mutex_unlock(&s->lock);
1199 }
1200
1201 static int read_write_object(int fd, BlockDriverState *bs, char *buf,
1202                              uint64_t oid, uint8_t copies,
1203                              unsigned int datalen, uint64_t offset,
1204                              bool write, bool create, uint32_t cache_flags)
1205 {
1206     SheepdogObjReq hdr;
1207     SheepdogObjRsp *rsp = (SheepdogObjRsp *)&hdr;
1208     unsigned int wlen, rlen;
1209     int ret;
1210
1211     memset(&hdr, 0, sizeof(hdr));
1212
1213     if (write) {
1214         wlen = datalen;
1215         rlen = 0;
1216         hdr.flags = SD_FLAG_CMD_WRITE;
1217         if (create) {
1218             hdr.opcode = SD_OP_CREATE_AND_WRITE_OBJ;
1219         } else {
1220             hdr.opcode = SD_OP_WRITE_OBJ;
1221         }
1222     } else {
1223         wlen = 0;
1224         rlen = datalen;
1225         hdr.opcode = SD_OP_READ_OBJ;
1226     }
1227
1228     hdr.flags |= cache_flags;
1229
1230     hdr.oid = oid;
1231     hdr.data_length = datalen;
1232     hdr.offset = offset;
1233     hdr.copies = copies;
1234
1235     ret = do_req(fd, bs, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
1236     if (ret) {
1237         error_report("failed to send a request to the sheep");
1238         return ret;
1239     }
1240
1241     switch (rsp->result) {
1242     case SD_RES_SUCCESS:
1243         return 0;
1244     default:
1245         error_report("%s", sd_strerror(rsp->result));
1246         return -EIO;
1247     }
1248 }
1249
1250 static int read_object(int fd, BlockDriverState *bs, char *buf,
1251                        uint64_t oid, uint8_t copies,
1252                        unsigned int datalen, uint64_t offset,
1253                        uint32_t cache_flags)
1254 {
1255     return read_write_object(fd, bs, buf, oid, copies,
1256                              datalen, offset, false,
1257                              false, cache_flags);
1258 }
1259
1260 static int write_object(int fd, BlockDriverState *bs, char *buf,
1261                         uint64_t oid, uint8_t copies,
1262                         unsigned int datalen, uint64_t offset, bool create,
1263                         uint32_t cache_flags)
1264 {
1265     return read_write_object(fd, bs, buf, oid, copies,
1266                              datalen, offset, true,
1267                              create, cache_flags);
1268 }
1269
1270 /* update inode with the latest state */
1271 static int reload_inode(BDRVSheepdogState *s, uint32_t snapid, const char *tag)
1272 {
1273     Error *local_err = NULL;
1274     SheepdogInode *inode;
1275     int ret = 0, fd;
1276     uint32_t vid = 0;
1277
1278     fd = connect_to_sdog(s, &local_err);
1279     if (fd < 0) {
1280         error_report_err(local_err);
1281         return -EIO;
1282     }
1283
1284     inode = g_malloc(SD_INODE_HEADER_SIZE);
1285
1286     ret = find_vdi_name(s, s->name, snapid, tag, &vid, false, &local_err);
1287     if (ret) {
1288         error_report_err(local_err);
1289         goto out;
1290     }
1291
1292     ret = read_object(fd, s->bs, (char *)inode, vid_to_vdi_oid(vid),
1293                       s->inode.nr_copies, SD_INODE_HEADER_SIZE, 0,
1294                       s->cache_flags);
1295     if (ret < 0) {
1296         goto out;
1297     }
1298
1299     if (inode->vdi_id != s->inode.vdi_id) {
1300         memcpy(&s->inode, inode, SD_INODE_HEADER_SIZE);
1301     }
1302
1303 out:
1304     g_free(inode);
1305     closesocket(fd);
1306
1307     return ret;
1308 }
1309
1310 static void coroutine_fn resend_aioreq(BDRVSheepdogState *s, AIOReq *aio_req)
1311 {
1312     SheepdogAIOCB *acb = aio_req->aiocb;
1313
1314     aio_req->create = false;
1315
1316     /* check whether this request becomes a CoW one */
1317     if (acb->aiocb_type == AIOCB_WRITE_UDATA && is_data_obj(aio_req->oid)) {
1318         int idx = data_oid_to_idx(aio_req->oid);
1319
1320         if (is_data_obj_writable(&s->inode, idx)) {
1321             goto out;
1322         }
1323
1324         if (s->inode.data_vdi_id[idx]) {
1325             aio_req->base_oid = vid_to_data_oid(s->inode.data_vdi_id[idx], idx);
1326             aio_req->flags |= SD_FLAG_CMD_COW;
1327         }
1328         aio_req->create = true;
1329     }
1330 out:
1331     if (is_data_obj(aio_req->oid)) {
1332         add_aio_request(s, aio_req, acb->qiov->iov, acb->qiov->niov,
1333                         acb->aiocb_type);
1334     } else {
1335         struct iovec iov;
1336         iov.iov_base = &s->inode;
1337         iov.iov_len = sizeof(s->inode);
1338         add_aio_request(s, aio_req, &iov, 1, AIOCB_WRITE_UDATA);
1339     }
1340 }
1341
1342 static void sd_detach_aio_context(BlockDriverState *bs)
1343 {
1344     BDRVSheepdogState *s = bs->opaque;
1345
1346     aio_set_fd_handler(s->aio_context, s->fd, false, NULL,
1347                        NULL, NULL, NULL);
1348 }
1349
1350 static void sd_attach_aio_context(BlockDriverState *bs,
1351                                   AioContext *new_context)
1352 {
1353     BDRVSheepdogState *s = bs->opaque;
1354
1355     s->aio_context = new_context;
1356     aio_set_fd_handler(new_context, s->fd, false,
1357                        co_read_response, NULL, NULL, s);
1358 }
1359
1360 /* TODO Convert to fine grained options */
1361 static QemuOptsList runtime_opts = {
1362     .name = "sheepdog",
1363     .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
1364     .desc = {
1365         {
1366             .name = "filename",
1367             .type = QEMU_OPT_STRING,
1368             .help = "URL to the sheepdog image",
1369         },
1370         { /* end of list */ }
1371     },
1372 };
1373
1374 static int sd_open(BlockDriverState *bs, QDict *options, int flags,
1375                    Error **errp)
1376 {
1377     int ret, fd;
1378     uint32_t vid = 0;
1379     BDRVSheepdogState *s = bs->opaque;
1380     char vdi[SD_MAX_VDI_LEN], tag[SD_MAX_VDI_TAG_LEN];
1381     uint32_t snapid;
1382     char *buf = NULL;
1383     QemuOpts *opts;
1384     Error *local_err = NULL;
1385     const char *filename;
1386
1387     s->bs = bs;
1388     s->aio_context = bdrv_get_aio_context(bs);
1389
1390     opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
1391     qemu_opts_absorb_qdict(opts, options, &local_err);
1392     if (local_err) {
1393         error_propagate(errp, local_err);
1394         ret = -EINVAL;
1395         goto out;
1396     }
1397
1398     filename = qemu_opt_get(opts, "filename");
1399
1400     QLIST_INIT(&s->inflight_aio_head);
1401     QLIST_INIT(&s->failed_aio_head);
1402     QLIST_INIT(&s->inflight_aiocb_head);
1403     s->fd = -1;
1404
1405     memset(vdi, 0, sizeof(vdi));
1406     memset(tag, 0, sizeof(tag));
1407
1408     if (strstr(filename, "://")) {
1409         ret = sd_parse_uri(s, filename, vdi, &snapid, tag);
1410     } else {
1411         ret = parse_vdiname(s, filename, vdi, &snapid, tag);
1412     }
1413     if (ret < 0) {
1414         error_setg(errp, "Can't parse filename");
1415         goto out;
1416     }
1417     s->fd = get_sheep_fd(s, errp);
1418     if (s->fd < 0) {
1419         ret = s->fd;
1420         goto out;
1421     }
1422
1423     ret = find_vdi_name(s, vdi, snapid, tag, &vid, true, errp);
1424     if (ret) {
1425         goto out;
1426     }
1427
1428     /*
1429      * QEMU block layer emulates writethrough cache as 'writeback + flush', so
1430      * we always set SD_FLAG_CMD_CACHE (writeback cache) as default.
1431      */
1432     s->cache_flags = SD_FLAG_CMD_CACHE;
1433     if (flags & BDRV_O_NOCACHE) {
1434         s->cache_flags = SD_FLAG_CMD_DIRECT;
1435     }
1436     s->discard_supported = true;
1437
1438     if (snapid || tag[0] != '\0') {
1439         DPRINTF("%" PRIx32 " snapshot inode was open.\n", vid);
1440         s->is_snapshot = true;
1441     }
1442
1443     fd = connect_to_sdog(s, errp);
1444     if (fd < 0) {
1445         ret = fd;
1446         goto out;
1447     }
1448
1449     buf = g_malloc(SD_INODE_SIZE);
1450     ret = read_object(fd, s->bs, buf, vid_to_vdi_oid(vid),
1451                       0, SD_INODE_SIZE, 0, s->cache_flags);
1452
1453     closesocket(fd);
1454
1455     if (ret) {
1456         error_setg(errp, "Can't read snapshot inode");
1457         goto out;
1458     }
1459
1460     memcpy(&s->inode, buf, sizeof(s->inode));
1461
1462     bs->total_sectors = s->inode.vdi_size / BDRV_SECTOR_SIZE;
1463     pstrcpy(s->name, sizeof(s->name), vdi);
1464     qemu_co_mutex_init(&s->lock);
1465     qemu_co_queue_init(&s->overlapping_queue);
1466     qemu_opts_del(opts);
1467     g_free(buf);
1468     return 0;
1469 out:
1470     aio_set_fd_handler(bdrv_get_aio_context(bs), s->fd,
1471                        false, NULL, NULL, NULL, NULL);
1472     if (s->fd >= 0) {
1473         closesocket(s->fd);
1474     }
1475     qemu_opts_del(opts);
1476     g_free(buf);
1477     return ret;
1478 }
1479
1480 static int sd_reopen_prepare(BDRVReopenState *state, BlockReopenQueue *queue,
1481                              Error **errp)
1482 {
1483     BDRVSheepdogState *s = state->bs->opaque;
1484     BDRVSheepdogReopenState *re_s;
1485     int ret = 0;
1486
1487     re_s = state->opaque = g_new0(BDRVSheepdogReopenState, 1);
1488
1489     re_s->cache_flags = SD_FLAG_CMD_CACHE;
1490     if (state->flags & BDRV_O_NOCACHE) {
1491         re_s->cache_flags = SD_FLAG_CMD_DIRECT;
1492     }
1493
1494     re_s->fd = get_sheep_fd(s, errp);
1495     if (re_s->fd < 0) {
1496         ret = re_s->fd;
1497         return ret;
1498     }
1499
1500     return ret;
1501 }
1502
1503 static void sd_reopen_commit(BDRVReopenState *state)
1504 {
1505     BDRVSheepdogReopenState *re_s = state->opaque;
1506     BDRVSheepdogState *s = state->bs->opaque;
1507
1508     if (s->fd) {
1509         aio_set_fd_handler(s->aio_context, s->fd, false,
1510                            NULL, NULL, NULL, NULL);
1511         closesocket(s->fd);
1512     }
1513
1514     s->fd = re_s->fd;
1515     s->cache_flags = re_s->cache_flags;
1516
1517     g_free(state->opaque);
1518     state->opaque = NULL;
1519
1520     return;
1521 }
1522
1523 static void sd_reopen_abort(BDRVReopenState *state)
1524 {
1525     BDRVSheepdogReopenState *re_s = state->opaque;
1526     BDRVSheepdogState *s = state->bs->opaque;
1527
1528     if (re_s == NULL) {
1529         return;
1530     }
1531
1532     if (re_s->fd) {
1533         aio_set_fd_handler(s->aio_context, re_s->fd, false,
1534                            NULL, NULL, NULL, NULL);
1535         closesocket(re_s->fd);
1536     }
1537
1538     g_free(state->opaque);
1539     state->opaque = NULL;
1540
1541     return;
1542 }
1543
1544 static int do_sd_create(BDRVSheepdogState *s, uint32_t *vdi_id, int snapshot,
1545                         Error **errp)
1546 {
1547     SheepdogVdiReq hdr;
1548     SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
1549     int fd, ret;
1550     unsigned int wlen, rlen = 0;
1551     char buf[SD_MAX_VDI_LEN];
1552
1553     fd = connect_to_sdog(s, errp);
1554     if (fd < 0) {
1555         return fd;
1556     }
1557
1558     /* FIXME: would it be better to fail (e.g., return -EIO) when filename
1559      * does not fit in buf?  For now, just truncate and avoid buffer overrun.
1560      */
1561     memset(buf, 0, sizeof(buf));
1562     pstrcpy(buf, sizeof(buf), s->name);
1563
1564     memset(&hdr, 0, sizeof(hdr));
1565     hdr.opcode = SD_OP_NEW_VDI;
1566     hdr.base_vdi_id = s->inode.vdi_id;
1567
1568     wlen = SD_MAX_VDI_LEN;
1569
1570     hdr.flags = SD_FLAG_CMD_WRITE;
1571     hdr.snapid = snapshot;
1572
1573     hdr.data_length = wlen;
1574     hdr.vdi_size = s->inode.vdi_size;
1575     hdr.copy_policy = s->inode.copy_policy;
1576     hdr.copies = s->inode.nr_copies;
1577     hdr.block_size_shift = s->inode.block_size_shift;
1578
1579     ret = do_req(fd, NULL, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
1580
1581     closesocket(fd);
1582
1583     if (ret) {
1584         error_setg_errno(errp, -ret, "create failed");
1585         return ret;
1586     }
1587
1588     if (rsp->result != SD_RES_SUCCESS) {
1589         error_setg(errp, "%s, %s", sd_strerror(rsp->result), s->inode.name);
1590         return -EIO;
1591     }
1592
1593     if (vdi_id) {
1594         *vdi_id = rsp->vdi_id;
1595     }
1596
1597     return 0;
1598 }
1599
1600 static int sd_prealloc(const char *filename, Error **errp)
1601 {
1602     BlockBackend *blk = NULL;
1603     BDRVSheepdogState *base = NULL;
1604     unsigned long buf_size;
1605     uint32_t idx, max_idx;
1606     uint32_t object_size;
1607     int64_t vdi_size;
1608     void *buf = NULL;
1609     int ret;
1610
1611     blk = blk_new_open(filename, NULL, NULL,
1612                        BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL, errp);
1613     if (blk == NULL) {
1614         ret = -EIO;
1615         goto out_with_err_set;
1616     }
1617
1618     blk_set_allow_write_beyond_eof(blk, true);
1619
1620     vdi_size = blk_getlength(blk);
1621     if (vdi_size < 0) {
1622         ret = vdi_size;
1623         goto out;
1624     }
1625
1626     base = blk_bs(blk)->opaque;
1627     object_size = (UINT32_C(1) << base->inode.block_size_shift);
1628     buf_size = MIN(object_size, SD_DATA_OBJ_SIZE);
1629     buf = g_malloc0(buf_size);
1630
1631     max_idx = DIV_ROUND_UP(vdi_size, buf_size);
1632
1633     for (idx = 0; idx < max_idx; idx++) {
1634         /*
1635          * The created image can be a cloned image, so we need to read
1636          * a data from the source image.
1637          */
1638         ret = blk_pread(blk, idx * buf_size, buf, buf_size);
1639         if (ret < 0) {
1640             goto out;
1641         }
1642         ret = blk_pwrite(blk, idx * buf_size, buf, buf_size, 0);
1643         if (ret < 0) {
1644             goto out;
1645         }
1646     }
1647
1648     ret = 0;
1649 out:
1650     if (ret < 0) {
1651         error_setg_errno(errp, -ret, "Can't pre-allocate");
1652     }
1653 out_with_err_set:
1654     if (blk) {
1655         blk_unref(blk);
1656     }
1657     g_free(buf);
1658
1659     return ret;
1660 }
1661
1662 /*
1663  * Sheepdog support two kinds of redundancy, full replication and erasure
1664  * coding.
1665  *
1666  * # create a fully replicated vdi with x copies
1667  * -o redundancy=x (1 <= x <= SD_MAX_COPIES)
1668  *
1669  * # create a erasure coded vdi with x data strips and y parity strips
1670  * -o redundancy=x:y (x must be one of {2,4,8,16} and 1 <= y < SD_EC_MAX_STRIP)
1671  */
1672 static int parse_redundancy(BDRVSheepdogState *s, const char *opt)
1673 {
1674     struct SheepdogInode *inode = &s->inode;
1675     const char *n1, *n2;
1676     long copy, parity;
1677     char p[10];
1678
1679     pstrcpy(p, sizeof(p), opt);
1680     n1 = strtok(p, ":");
1681     n2 = strtok(NULL, ":");
1682
1683     if (!n1) {
1684         return -EINVAL;
1685     }
1686
1687     copy = strtol(n1, NULL, 10);
1688     if (copy > SD_MAX_COPIES || copy < 1) {
1689         return -EINVAL;
1690     }
1691     if (!n2) {
1692         inode->copy_policy = 0;
1693         inode->nr_copies = copy;
1694         return 0;
1695     }
1696
1697     if (copy != 2 && copy != 4 && copy != 8 && copy != 16) {
1698         return -EINVAL;
1699     }
1700
1701     parity = strtol(n2, NULL, 10);
1702     if (parity >= SD_EC_MAX_STRIP || parity < 1) {
1703         return -EINVAL;
1704     }
1705
1706     /*
1707      * 4 bits for parity and 4 bits for data.
1708      * We have to compress upper data bits because it can't represent 16
1709      */
1710     inode->copy_policy = ((copy / 2) << 4) + parity;
1711     inode->nr_copies = copy + parity;
1712
1713     return 0;
1714 }
1715
1716 static int parse_block_size_shift(BDRVSheepdogState *s, QemuOpts *opt)
1717 {
1718     struct SheepdogInode *inode = &s->inode;
1719     uint64_t object_size;
1720     int obj_order;
1721
1722     object_size = qemu_opt_get_size_del(opt, BLOCK_OPT_OBJECT_SIZE, 0);
1723     if (object_size) {
1724         if ((object_size - 1) & object_size) {    /* not a power of 2? */
1725             return -EINVAL;
1726         }
1727         obj_order = ctz32(object_size);
1728         if (obj_order < 20 || obj_order > 31) {
1729             return -EINVAL;
1730         }
1731         inode->block_size_shift = (uint8_t)obj_order;
1732     }
1733
1734     return 0;
1735 }
1736
1737 static int sd_create(const char *filename, QemuOpts *opts,
1738                      Error **errp)
1739 {
1740     int ret = 0;
1741     uint32_t vid = 0;
1742     char *backing_file = NULL;
1743     char *buf = NULL;
1744     BDRVSheepdogState *s;
1745     char tag[SD_MAX_VDI_TAG_LEN];
1746     uint32_t snapid;
1747     uint64_t max_vdi_size;
1748     bool prealloc = false;
1749
1750     s = g_new0(BDRVSheepdogState, 1);
1751
1752     memset(tag, 0, sizeof(tag));
1753     if (strstr(filename, "://")) {
1754         ret = sd_parse_uri(s, filename, s->name, &snapid, tag);
1755     } else {
1756         ret = parse_vdiname(s, filename, s->name, &snapid, tag);
1757     }
1758     if (ret < 0) {
1759         error_setg(errp, "Can't parse filename");
1760         goto out;
1761     }
1762
1763     s->inode.vdi_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
1764                                  BDRV_SECTOR_SIZE);
1765     backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
1766     buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
1767     if (!buf || !strcmp(buf, "off")) {
1768         prealloc = false;
1769     } else if (!strcmp(buf, "full")) {
1770         prealloc = true;
1771     } else {
1772         error_setg(errp, "Invalid preallocation mode: '%s'", buf);
1773         ret = -EINVAL;
1774         goto out;
1775     }
1776
1777     g_free(buf);
1778     buf = qemu_opt_get_del(opts, BLOCK_OPT_REDUNDANCY);
1779     if (buf) {
1780         ret = parse_redundancy(s, buf);
1781         if (ret < 0) {
1782             error_setg(errp, "Invalid redundancy mode: '%s'", buf);
1783             goto out;
1784         }
1785     }
1786     ret = parse_block_size_shift(s, opts);
1787     if (ret < 0) {
1788         error_setg(errp, "Invalid object_size."
1789                          " obect_size needs to be power of 2"
1790                          " and be limited from 2^20 to 2^31");
1791         goto out;
1792     }
1793
1794     if (backing_file) {
1795         BlockBackend *blk;
1796         BDRVSheepdogState *base;
1797         BlockDriver *drv;
1798
1799         /* Currently, only Sheepdog backing image is supported. */
1800         drv = bdrv_find_protocol(backing_file, true, NULL);
1801         if (!drv || strcmp(drv->protocol_name, "sheepdog") != 0) {
1802             error_setg(errp, "backing_file must be a sheepdog image");
1803             ret = -EINVAL;
1804             goto out;
1805         }
1806
1807         blk = blk_new_open(backing_file, NULL, NULL,
1808                            BDRV_O_PROTOCOL, errp);
1809         if (blk == NULL) {
1810             ret = -EIO;
1811             goto out;
1812         }
1813
1814         base = blk_bs(blk)->opaque;
1815
1816         if (!is_snapshot(&base->inode)) {
1817             error_setg(errp, "cannot clone from a non snapshot vdi");
1818             blk_unref(blk);
1819             ret = -EINVAL;
1820             goto out;
1821         }
1822         s->inode.vdi_id = base->inode.vdi_id;
1823         blk_unref(blk);
1824     }
1825
1826     s->aio_context = qemu_get_aio_context();
1827
1828     /* if block_size_shift is not specified, get cluster default value */
1829     if (s->inode.block_size_shift == 0) {
1830         SheepdogVdiReq hdr;
1831         SheepdogClusterRsp *rsp = (SheepdogClusterRsp *)&hdr;
1832         Error *local_err = NULL;
1833         int fd;
1834         unsigned int wlen = 0, rlen = 0;
1835
1836         fd = connect_to_sdog(s, &local_err);
1837         if (fd < 0) {
1838             error_report_err(local_err);
1839             ret = -EIO;
1840             goto out;
1841         }
1842
1843         memset(&hdr, 0, sizeof(hdr));
1844         hdr.opcode = SD_OP_GET_CLUSTER_DEFAULT;
1845         hdr.proto_ver = SD_PROTO_VER;
1846
1847         ret = do_req(fd, NULL, (SheepdogReq *)&hdr,
1848                      NULL, &wlen, &rlen);
1849         closesocket(fd);
1850         if (ret) {
1851             error_setg_errno(errp, -ret, "failed to get cluster default");
1852             goto out;
1853         }
1854         if (rsp->result == SD_RES_SUCCESS) {
1855             s->inode.block_size_shift = rsp->block_size_shift;
1856         } else {
1857             s->inode.block_size_shift = SD_DEFAULT_BLOCK_SIZE_SHIFT;
1858         }
1859     }
1860
1861     max_vdi_size = (UINT64_C(1) << s->inode.block_size_shift) * MAX_DATA_OBJS;
1862
1863     if (s->inode.vdi_size > max_vdi_size) {
1864         error_setg(errp, "An image is too large."
1865                          " The maximum image size is %"PRIu64 "GB",
1866                          max_vdi_size / 1024 / 1024 / 1024);
1867         ret = -EINVAL;
1868         goto out;
1869     }
1870
1871     ret = do_sd_create(s, &vid, 0, errp);
1872     if (ret) {
1873         goto out;
1874     }
1875
1876     if (prealloc) {
1877         ret = sd_prealloc(filename, errp);
1878     }
1879 out:
1880     g_free(backing_file);
1881     g_free(buf);
1882     g_free(s);
1883     return ret;
1884 }
1885
1886 static void sd_close(BlockDriverState *bs)
1887 {
1888     Error *local_err = NULL;
1889     BDRVSheepdogState *s = bs->opaque;
1890     SheepdogVdiReq hdr;
1891     SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
1892     unsigned int wlen, rlen = 0;
1893     int fd, ret;
1894
1895     DPRINTF("%s\n", s->name);
1896
1897     fd = connect_to_sdog(s, &local_err);
1898     if (fd < 0) {
1899         error_report_err(local_err);
1900         return;
1901     }
1902
1903     memset(&hdr, 0, sizeof(hdr));
1904
1905     hdr.opcode = SD_OP_RELEASE_VDI;
1906     hdr.type = LOCK_TYPE_NORMAL;
1907     hdr.base_vdi_id = s->inode.vdi_id;
1908     wlen = strlen(s->name) + 1;
1909     hdr.data_length = wlen;
1910     hdr.flags = SD_FLAG_CMD_WRITE;
1911
1912     ret = do_req(fd, s->bs, (SheepdogReq *)&hdr,
1913                  s->name, &wlen, &rlen);
1914
1915     closesocket(fd);
1916
1917     if (!ret && rsp->result != SD_RES_SUCCESS &&
1918         rsp->result != SD_RES_VDI_NOT_LOCKED) {
1919         error_report("%s, %s", sd_strerror(rsp->result), s->name);
1920     }
1921
1922     aio_set_fd_handler(bdrv_get_aio_context(bs), s->fd,
1923                        false, NULL, NULL, NULL, NULL);
1924     closesocket(s->fd);
1925     g_free(s->host_spec);
1926 }
1927
1928 static int64_t sd_getlength(BlockDriverState *bs)
1929 {
1930     BDRVSheepdogState *s = bs->opaque;
1931
1932     return s->inode.vdi_size;
1933 }
1934
1935 static int sd_truncate(BlockDriverState *bs, int64_t offset)
1936 {
1937     Error *local_err = NULL;
1938     BDRVSheepdogState *s = bs->opaque;
1939     int ret, fd;
1940     unsigned int datalen;
1941     uint64_t max_vdi_size;
1942
1943     max_vdi_size = (UINT64_C(1) << s->inode.block_size_shift) * MAX_DATA_OBJS;
1944     if (offset < s->inode.vdi_size) {
1945         error_report("shrinking is not supported");
1946         return -EINVAL;
1947     } else if (offset > max_vdi_size) {
1948         error_report("too big image size");
1949         return -EINVAL;
1950     }
1951
1952     fd = connect_to_sdog(s, &local_err);
1953     if (fd < 0) {
1954         error_report_err(local_err);
1955         return fd;
1956     }
1957
1958     /* we don't need to update entire object */
1959     datalen = SD_INODE_SIZE - sizeof(s->inode.data_vdi_id);
1960     s->inode.vdi_size = offset;
1961     ret = write_object(fd, s->bs, (char *)&s->inode,
1962                        vid_to_vdi_oid(s->inode.vdi_id), s->inode.nr_copies,
1963                        datalen, 0, false, s->cache_flags);
1964     close(fd);
1965
1966     if (ret < 0) {
1967         error_report("failed to update an inode.");
1968     }
1969
1970     return ret;
1971 }
1972
1973 /*
1974  * This function is called after writing data objects.  If we need to
1975  * update metadata, this sends a write request to the vdi object.
1976  */
1977 static void coroutine_fn sd_write_done(SheepdogAIOCB *acb)
1978 {
1979     BDRVSheepdogState *s = acb->s;
1980     struct iovec iov;
1981     AIOReq *aio_req;
1982     uint32_t offset, data_len, mn, mx;
1983
1984     mn = acb->min_dirty_data_idx;
1985     mx = acb->max_dirty_data_idx;
1986     if (mn <= mx) {
1987         /* we need to update the vdi object. */
1988         ++acb->nr_pending;
1989         offset = sizeof(s->inode) - sizeof(s->inode.data_vdi_id) +
1990             mn * sizeof(s->inode.data_vdi_id[0]);
1991         data_len = (mx - mn + 1) * sizeof(s->inode.data_vdi_id[0]);
1992
1993         acb->min_dirty_data_idx = UINT32_MAX;
1994         acb->max_dirty_data_idx = 0;
1995
1996         iov.iov_base = &s->inode;
1997         iov.iov_len = sizeof(s->inode);
1998         aio_req = alloc_aio_req(s, acb, vid_to_vdi_oid(s->inode.vdi_id),
1999                                 data_len, offset, 0, false, 0, offset);
2000         add_aio_request(s, aio_req, &iov, 1, AIOCB_WRITE_UDATA);
2001         if (--acb->nr_pending) {
2002             qemu_coroutine_yield();
2003         }
2004     }
2005 }
2006
2007 /* Delete current working VDI on the snapshot chain */
2008 static bool sd_delete(BDRVSheepdogState *s)
2009 {
2010     Error *local_err = NULL;
2011     unsigned int wlen = SD_MAX_VDI_LEN, rlen = 0;
2012     SheepdogVdiReq hdr = {
2013         .opcode = SD_OP_DEL_VDI,
2014         .base_vdi_id = s->inode.vdi_id,
2015         .data_length = wlen,
2016         .flags = SD_FLAG_CMD_WRITE,
2017     };
2018     SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
2019     int fd, ret;
2020
2021     fd = connect_to_sdog(s, &local_err);
2022     if (fd < 0) {
2023         error_report_err(local_err);
2024         return false;
2025     }
2026
2027     ret = do_req(fd, s->bs, (SheepdogReq *)&hdr,
2028                  s->name, &wlen, &rlen);
2029     closesocket(fd);
2030     if (ret) {
2031         return false;
2032     }
2033     switch (rsp->result) {
2034     case SD_RES_NO_VDI:
2035         error_report("%s was already deleted", s->name);
2036         /* fall through */
2037     case SD_RES_SUCCESS:
2038         break;
2039     default:
2040         error_report("%s, %s", sd_strerror(rsp->result), s->name);
2041         return false;
2042     }
2043
2044     return true;
2045 }
2046
2047 /*
2048  * Create a writable VDI from a snapshot
2049  */
2050 static int sd_create_branch(BDRVSheepdogState *s)
2051 {
2052     Error *local_err = NULL;
2053     int ret, fd;
2054     uint32_t vid;
2055     char *buf;
2056     bool deleted;
2057
2058     DPRINTF("%" PRIx32 " is snapshot.\n", s->inode.vdi_id);
2059
2060     buf = g_malloc(SD_INODE_SIZE);
2061
2062     /*
2063      * Even If deletion fails, we will just create extra snapshot based on
2064      * the working VDI which was supposed to be deleted. So no need to
2065      * false bail out.
2066      */
2067     deleted = sd_delete(s);
2068     ret = do_sd_create(s, &vid, !deleted, &local_err);
2069     if (ret) {
2070         error_report_err(local_err);
2071         goto out;
2072     }
2073
2074     DPRINTF("%" PRIx32 " is created.\n", vid);
2075
2076     fd = connect_to_sdog(s, &local_err);
2077     if (fd < 0) {
2078         error_report_err(local_err);
2079         ret = fd;
2080         goto out;
2081     }
2082
2083     ret = read_object(fd, s->bs, buf, vid_to_vdi_oid(vid),
2084                       s->inode.nr_copies, SD_INODE_SIZE, 0, s->cache_flags);
2085
2086     closesocket(fd);
2087
2088     if (ret < 0) {
2089         goto out;
2090     }
2091
2092     memcpy(&s->inode, buf, sizeof(s->inode));
2093
2094     s->is_snapshot = false;
2095     ret = 0;
2096     DPRINTF("%" PRIx32 " was newly created.\n", s->inode.vdi_id);
2097
2098 out:
2099     g_free(buf);
2100
2101     return ret;
2102 }
2103
2104 /*
2105  * Send I/O requests to the server.
2106  *
2107  * This function sends requests to the server, links the requests to
2108  * the inflight_list in BDRVSheepdogState, and exits without
2109  * waiting the response.  The responses are received in the
2110  * `aio_read_response' function which is called from the main loop as
2111  * a fd handler.
2112  *
2113  * Returns 1 when we need to wait a response, 0 when there is no sent
2114  * request and -errno in error cases.
2115  */
2116 static void coroutine_fn sd_co_rw_vector(SheepdogAIOCB *acb)
2117 {
2118     int ret = 0;
2119     unsigned long len, done = 0, total = acb->nb_sectors * BDRV_SECTOR_SIZE;
2120     unsigned long idx;
2121     uint32_t object_size;
2122     uint64_t oid;
2123     uint64_t offset;
2124     BDRVSheepdogState *s = acb->s;
2125     SheepdogInode *inode = &s->inode;
2126     AIOReq *aio_req;
2127
2128     if (acb->aiocb_type == AIOCB_WRITE_UDATA && s->is_snapshot) {
2129         /*
2130          * In the case we open the snapshot VDI, Sheepdog creates the
2131          * writable VDI when we do a write operation first.
2132          */
2133         ret = sd_create_branch(s);
2134         if (ret) {
2135             acb->ret = -EIO;
2136             return;
2137         }
2138     }
2139
2140     object_size = (UINT32_C(1) << inode->block_size_shift);
2141     idx = acb->sector_num * BDRV_SECTOR_SIZE / object_size;
2142     offset = (acb->sector_num * BDRV_SECTOR_SIZE) % object_size;
2143
2144     /*
2145      * Make sure we don't free the aiocb before we are done with all requests.
2146      * This additional reference is dropped at the end of this function.
2147      */
2148     acb->nr_pending++;
2149
2150     while (done != total) {
2151         uint8_t flags = 0;
2152         uint64_t old_oid = 0;
2153         bool create = false;
2154
2155         oid = vid_to_data_oid(inode->data_vdi_id[idx], idx);
2156
2157         len = MIN(total - done, object_size - offset);
2158
2159         switch (acb->aiocb_type) {
2160         case AIOCB_READ_UDATA:
2161             if (!inode->data_vdi_id[idx]) {
2162                 qemu_iovec_memset(acb->qiov, done, 0, len);
2163                 goto done;
2164             }
2165             break;
2166         case AIOCB_WRITE_UDATA:
2167             if (!inode->data_vdi_id[idx]) {
2168                 create = true;
2169             } else if (!is_data_obj_writable(inode, idx)) {
2170                 /* Copy-On-Write */
2171                 create = true;
2172                 old_oid = oid;
2173                 flags = SD_FLAG_CMD_COW;
2174             }
2175             break;
2176         case AIOCB_DISCARD_OBJ:
2177             /*
2178              * We discard the object only when the whole object is
2179              * 1) allocated 2) trimmed. Otherwise, simply skip it.
2180              */
2181             if (len != object_size || inode->data_vdi_id[idx] == 0) {
2182                 goto done;
2183             }
2184             break;
2185         default:
2186             break;
2187         }
2188
2189         if (create) {
2190             DPRINTF("update ino (%" PRIu32 ") %" PRIu64 " %" PRIu64 " %ld\n",
2191                     inode->vdi_id, oid,
2192                     vid_to_data_oid(inode->data_vdi_id[idx], idx), idx);
2193             oid = vid_to_data_oid(inode->vdi_id, idx);
2194             DPRINTF("new oid %" PRIx64 "\n", oid);
2195         }
2196
2197         aio_req = alloc_aio_req(s, acb, oid, len, offset, flags, create,
2198                                 old_oid,
2199                                 acb->aiocb_type == AIOCB_DISCARD_OBJ ?
2200                                 0 : done);
2201         add_aio_request(s, aio_req, acb->qiov->iov, acb->qiov->niov,
2202                         acb->aiocb_type);
2203     done:
2204         offset = 0;
2205         idx++;
2206         done += len;
2207     }
2208     if (--acb->nr_pending) {
2209         qemu_coroutine_yield();
2210     }
2211 }
2212
2213 static void sd_aio_complete(SheepdogAIOCB *acb)
2214 {
2215     if (acb->aiocb_type == AIOCB_FLUSH_CACHE) {
2216         return;
2217     }
2218
2219     QLIST_REMOVE(acb, aiocb_siblings);
2220     qemu_co_queue_restart_all(&acb->s->overlapping_queue);
2221 }
2222
2223 static coroutine_fn int sd_co_writev(BlockDriverState *bs, int64_t sector_num,
2224                         int nb_sectors, QEMUIOVector *qiov)
2225 {
2226     SheepdogAIOCB acb;
2227     int ret;
2228     int64_t offset = (sector_num + nb_sectors) * BDRV_SECTOR_SIZE;
2229     BDRVSheepdogState *s = bs->opaque;
2230
2231     if (offset > s->inode.vdi_size) {
2232         ret = sd_truncate(bs, offset);
2233         if (ret < 0) {
2234             return ret;
2235         }
2236     }
2237
2238     sd_aio_setup(&acb, s, qiov, sector_num, nb_sectors, AIOCB_WRITE_UDATA);
2239     sd_co_rw_vector(&acb);
2240     sd_write_done(&acb);
2241     sd_aio_complete(&acb);
2242
2243     return acb.ret;
2244 }
2245
2246 static coroutine_fn int sd_co_readv(BlockDriverState *bs, int64_t sector_num,
2247                        int nb_sectors, QEMUIOVector *qiov)
2248 {
2249     SheepdogAIOCB acb;
2250     BDRVSheepdogState *s = bs->opaque;
2251
2252     sd_aio_setup(&acb, s, qiov, sector_num, nb_sectors, AIOCB_READ_UDATA);
2253     sd_co_rw_vector(&acb);
2254     sd_aio_complete(&acb);
2255
2256     return acb.ret;
2257 }
2258
2259 static int coroutine_fn sd_co_flush_to_disk(BlockDriverState *bs)
2260 {
2261     BDRVSheepdogState *s = bs->opaque;
2262     SheepdogAIOCB acb;
2263     AIOReq *aio_req;
2264
2265     if (s->cache_flags != SD_FLAG_CMD_CACHE) {
2266         return 0;
2267     }
2268
2269     sd_aio_setup(&acb, s, NULL, 0, 0, AIOCB_FLUSH_CACHE);
2270
2271     acb.nr_pending++;
2272     aio_req = alloc_aio_req(s, &acb, vid_to_vdi_oid(s->inode.vdi_id),
2273                             0, 0, 0, false, 0, 0);
2274     add_aio_request(s, aio_req, NULL, 0, acb.aiocb_type);
2275
2276     if (--acb.nr_pending) {
2277         qemu_coroutine_yield();
2278     }
2279
2280     sd_aio_complete(&acb);
2281     return acb.ret;
2282 }
2283
2284 static int sd_snapshot_create(BlockDriverState *bs, QEMUSnapshotInfo *sn_info)
2285 {
2286     Error *local_err = NULL;
2287     BDRVSheepdogState *s = bs->opaque;
2288     int ret, fd;
2289     uint32_t new_vid;
2290     SheepdogInode *inode;
2291     unsigned int datalen;
2292
2293     DPRINTF("sn_info: name %s id_str %s s: name %s vm_state_size %" PRId64 " "
2294             "is_snapshot %d\n", sn_info->name, sn_info->id_str,
2295             s->name, sn_info->vm_state_size, s->is_snapshot);
2296
2297     if (s->is_snapshot) {
2298         error_report("You can't create a snapshot of a snapshot VDI, "
2299                      "%s (%" PRIu32 ").", s->name, s->inode.vdi_id);
2300
2301         return -EINVAL;
2302     }
2303
2304     DPRINTF("%s %s\n", sn_info->name, sn_info->id_str);
2305
2306     s->inode.vm_state_size = sn_info->vm_state_size;
2307     s->inode.vm_clock_nsec = sn_info->vm_clock_nsec;
2308     /* It appears that inode.tag does not require a NUL terminator,
2309      * which means this use of strncpy is ok.
2310      */
2311     strncpy(s->inode.tag, sn_info->name, sizeof(s->inode.tag));
2312     /* we don't need to update entire object */
2313     datalen = SD_INODE_SIZE - sizeof(s->inode.data_vdi_id);
2314     inode = g_malloc(datalen);
2315
2316     /* refresh inode. */
2317     fd = connect_to_sdog(s, &local_err);
2318     if (fd < 0) {
2319         error_report_err(local_err);
2320         ret = fd;
2321         goto cleanup;
2322     }
2323
2324     ret = write_object(fd, s->bs, (char *)&s->inode,
2325                        vid_to_vdi_oid(s->inode.vdi_id), s->inode.nr_copies,
2326                        datalen, 0, false, s->cache_flags);
2327     if (ret < 0) {
2328         error_report("failed to write snapshot's inode.");
2329         goto cleanup;
2330     }
2331
2332     ret = do_sd_create(s, &new_vid, 1, &local_err);
2333     if (ret < 0) {
2334         error_reportf_err(local_err,
2335                           "failed to create inode for snapshot: ");
2336         goto cleanup;
2337     }
2338
2339     ret = read_object(fd, s->bs, (char *)inode,
2340                       vid_to_vdi_oid(new_vid), s->inode.nr_copies, datalen, 0,
2341                       s->cache_flags);
2342
2343     if (ret < 0) {
2344         error_report("failed to read new inode info. %s", strerror(errno));
2345         goto cleanup;
2346     }
2347
2348     memcpy(&s->inode, inode, datalen);
2349     DPRINTF("s->inode: name %s snap_id %x oid %x\n",
2350             s->inode.name, s->inode.snap_id, s->inode.vdi_id);
2351
2352 cleanup:
2353     g_free(inode);
2354     closesocket(fd);
2355     return ret;
2356 }
2357
2358 /*
2359  * We implement rollback(loadvm) operation to the specified snapshot by
2360  * 1) switch to the snapshot
2361  * 2) rely on sd_create_branch to delete working VDI and
2362  * 3) create a new working VDI based on the specified snapshot
2363  */
2364 static int sd_snapshot_goto(BlockDriverState *bs, const char *snapshot_id)
2365 {
2366     BDRVSheepdogState *s = bs->opaque;
2367     BDRVSheepdogState *old_s;
2368     char tag[SD_MAX_VDI_TAG_LEN];
2369     uint32_t snapid = 0;
2370     int ret = 0;
2371
2372     old_s = g_new(BDRVSheepdogState, 1);
2373
2374     memcpy(old_s, s, sizeof(BDRVSheepdogState));
2375
2376     snapid = strtoul(snapshot_id, NULL, 10);
2377     if (snapid) {
2378         tag[0] = 0;
2379     } else {
2380         pstrcpy(tag, sizeof(tag), snapshot_id);
2381     }
2382
2383     ret = reload_inode(s, snapid, tag);
2384     if (ret) {
2385         goto out;
2386     }
2387
2388     ret = sd_create_branch(s);
2389     if (ret) {
2390         goto out;
2391     }
2392
2393     g_free(old_s);
2394
2395     return 0;
2396 out:
2397     /* recover bdrv_sd_state */
2398     memcpy(s, old_s, sizeof(BDRVSheepdogState));
2399     g_free(old_s);
2400
2401     error_report("failed to open. recover old bdrv_sd_state.");
2402
2403     return ret;
2404 }
2405
2406 #define NR_BATCHED_DISCARD 128
2407
2408 static bool remove_objects(BDRVSheepdogState *s)
2409 {
2410     int fd, i = 0, nr_objs = 0;
2411     Error *local_err = NULL;
2412     int ret = 0;
2413     bool result = true;
2414     SheepdogInode *inode = &s->inode;
2415
2416     fd = connect_to_sdog(s, &local_err);
2417     if (fd < 0) {
2418         error_report_err(local_err);
2419         return false;
2420     }
2421
2422     nr_objs = count_data_objs(inode);
2423     while (i < nr_objs) {
2424         int start_idx, nr_filled_idx;
2425
2426         while (i < nr_objs && !inode->data_vdi_id[i]) {
2427             i++;
2428         }
2429         start_idx = i;
2430
2431         nr_filled_idx = 0;
2432         while (i < nr_objs && nr_filled_idx < NR_BATCHED_DISCARD) {
2433             if (inode->data_vdi_id[i]) {
2434                 inode->data_vdi_id[i] = 0;
2435                 nr_filled_idx++;
2436             }
2437
2438             i++;
2439         }
2440
2441         ret = write_object(fd, s->bs,
2442                            (char *)&inode->data_vdi_id[start_idx],
2443                            vid_to_vdi_oid(s->inode.vdi_id), inode->nr_copies,
2444                            (i - start_idx) * sizeof(uint32_t),
2445                            offsetof(struct SheepdogInode,
2446                                     data_vdi_id[start_idx]),
2447                            false, s->cache_flags);
2448         if (ret < 0) {
2449             error_report("failed to discard snapshot inode.");
2450             result = false;
2451             goto out;
2452         }
2453     }
2454
2455 out:
2456     closesocket(fd);
2457     return result;
2458 }
2459
2460 static int sd_snapshot_delete(BlockDriverState *bs,
2461                               const char *snapshot_id,
2462                               const char *name,
2463                               Error **errp)
2464 {
2465     unsigned long snap_id = 0;
2466     char snap_tag[SD_MAX_VDI_TAG_LEN];
2467     Error *local_err = NULL;
2468     int fd, ret;
2469     char buf[SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN];
2470     BDRVSheepdogState *s = bs->opaque;
2471     unsigned int wlen = SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN, rlen = 0;
2472     uint32_t vid;
2473     SheepdogVdiReq hdr = {
2474         .opcode = SD_OP_DEL_VDI,
2475         .data_length = wlen,
2476         .flags = SD_FLAG_CMD_WRITE,
2477     };
2478     SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
2479
2480     if (!remove_objects(s)) {
2481         return -1;
2482     }
2483
2484     memset(buf, 0, sizeof(buf));
2485     memset(snap_tag, 0, sizeof(snap_tag));
2486     pstrcpy(buf, SD_MAX_VDI_LEN, s->name);
2487     ret = qemu_strtoul(snapshot_id, NULL, 10, &snap_id);
2488     if (ret || snap_id > UINT32_MAX) {
2489         error_setg(errp, "Invalid snapshot ID: %s",
2490                          snapshot_id ? snapshot_id : "<null>");
2491         return -EINVAL;
2492     }
2493
2494     if (snap_id) {
2495         hdr.snapid = (uint32_t) snap_id;
2496     } else {
2497         pstrcpy(snap_tag, sizeof(snap_tag), snapshot_id);
2498         pstrcpy(buf + SD_MAX_VDI_LEN, SD_MAX_VDI_TAG_LEN, snap_tag);
2499     }
2500
2501     ret = find_vdi_name(s, s->name, snap_id, snap_tag, &vid, true,
2502                         &local_err);
2503     if (ret) {
2504         return ret;
2505     }
2506
2507     fd = connect_to_sdog(s, &local_err);
2508     if (fd < 0) {
2509         error_report_err(local_err);
2510         return -1;
2511     }
2512
2513     ret = do_req(fd, s->bs, (SheepdogReq *)&hdr,
2514                  buf, &wlen, &rlen);
2515     closesocket(fd);
2516     if (ret) {
2517         return ret;
2518     }
2519
2520     switch (rsp->result) {
2521     case SD_RES_NO_VDI:
2522         error_report("%s was already deleted", s->name);
2523     case SD_RES_SUCCESS:
2524         break;
2525     default:
2526         error_report("%s, %s", sd_strerror(rsp->result), s->name);
2527         return -1;
2528     }
2529
2530     return ret;
2531 }
2532
2533 static int sd_snapshot_list(BlockDriverState *bs, QEMUSnapshotInfo **psn_tab)
2534 {
2535     Error *local_err = NULL;
2536     BDRVSheepdogState *s = bs->opaque;
2537     SheepdogReq req;
2538     int fd, nr = 1024, ret, max = BITS_TO_LONGS(SD_NR_VDIS) * sizeof(long);
2539     QEMUSnapshotInfo *sn_tab = NULL;
2540     unsigned wlen, rlen;
2541     int found = 0;
2542     static SheepdogInode inode;
2543     unsigned long *vdi_inuse;
2544     unsigned int start_nr;
2545     uint64_t hval;
2546     uint32_t vid;
2547
2548     vdi_inuse = g_malloc(max);
2549
2550     fd = connect_to_sdog(s, &local_err);
2551     if (fd < 0) {
2552         error_report_err(local_err);
2553         ret = fd;
2554         goto out;
2555     }
2556
2557     rlen = max;
2558     wlen = 0;
2559
2560     memset(&req, 0, sizeof(req));
2561
2562     req.opcode = SD_OP_READ_VDIS;
2563     req.data_length = max;
2564
2565     ret = do_req(fd, s->bs, &req, vdi_inuse, &wlen, &rlen);
2566
2567     closesocket(fd);
2568     if (ret) {
2569         goto out;
2570     }
2571
2572     sn_tab = g_new0(QEMUSnapshotInfo, nr);
2573
2574     /* calculate a vdi id with hash function */
2575     hval = fnv_64a_buf(s->name, strlen(s->name), FNV1A_64_INIT);
2576     start_nr = hval & (SD_NR_VDIS - 1);
2577
2578     fd = connect_to_sdog(s, &local_err);
2579     if (fd < 0) {
2580         error_report_err(local_err);
2581         ret = fd;
2582         goto out;
2583     }
2584
2585     for (vid = start_nr; found < nr; vid = (vid + 1) % SD_NR_VDIS) {
2586         if (!test_bit(vid, vdi_inuse)) {
2587             break;
2588         }
2589
2590         /* we don't need to read entire object */
2591         ret = read_object(fd, s->bs, (char *)&inode,
2592                           vid_to_vdi_oid(vid),
2593                           0, SD_INODE_SIZE - sizeof(inode.data_vdi_id), 0,
2594                           s->cache_flags);
2595
2596         if (ret) {
2597             continue;
2598         }
2599
2600         if (!strcmp(inode.name, s->name) && is_snapshot(&inode)) {
2601             sn_tab[found].date_sec = inode.snap_ctime >> 32;
2602             sn_tab[found].date_nsec = inode.snap_ctime & 0xffffffff;
2603             sn_tab[found].vm_state_size = inode.vm_state_size;
2604             sn_tab[found].vm_clock_nsec = inode.vm_clock_nsec;
2605
2606             snprintf(sn_tab[found].id_str, sizeof(sn_tab[found].id_str),
2607                      "%" PRIu32, inode.snap_id);
2608             pstrcpy(sn_tab[found].name,
2609                     MIN(sizeof(sn_tab[found].name), sizeof(inode.tag)),
2610                     inode.tag);
2611             found++;
2612         }
2613     }
2614
2615     closesocket(fd);
2616 out:
2617     *psn_tab = sn_tab;
2618
2619     g_free(vdi_inuse);
2620
2621     if (ret < 0) {
2622         return ret;
2623     }
2624
2625     return found;
2626 }
2627
2628 static int do_load_save_vmstate(BDRVSheepdogState *s, uint8_t *data,
2629                                 int64_t pos, int size, int load)
2630 {
2631     Error *local_err = NULL;
2632     bool create;
2633     int fd, ret = 0, remaining = size;
2634     unsigned int data_len;
2635     uint64_t vmstate_oid;
2636     uint64_t offset;
2637     uint32_t vdi_index;
2638     uint32_t vdi_id = load ? s->inode.parent_vdi_id : s->inode.vdi_id;
2639     uint32_t object_size = (UINT32_C(1) << s->inode.block_size_shift);
2640
2641     fd = connect_to_sdog(s, &local_err);
2642     if (fd < 0) {
2643         error_report_err(local_err);
2644         return fd;
2645     }
2646
2647     while (remaining) {
2648         vdi_index = pos / object_size;
2649         offset = pos % object_size;
2650
2651         data_len = MIN(remaining, object_size - offset);
2652
2653         vmstate_oid = vid_to_vmstate_oid(vdi_id, vdi_index);
2654
2655         create = (offset == 0);
2656         if (load) {
2657             ret = read_object(fd, s->bs, (char *)data, vmstate_oid,
2658                               s->inode.nr_copies, data_len, offset,
2659                               s->cache_flags);
2660         } else {
2661             ret = write_object(fd, s->bs, (char *)data, vmstate_oid,
2662                                s->inode.nr_copies, data_len, offset, create,
2663                                s->cache_flags);
2664         }
2665
2666         if (ret < 0) {
2667             error_report("failed to save vmstate %s", strerror(errno));
2668             goto cleanup;
2669         }
2670
2671         pos += data_len;
2672         data += data_len;
2673         remaining -= data_len;
2674     }
2675     ret = size;
2676 cleanup:
2677     closesocket(fd);
2678     return ret;
2679 }
2680
2681 static int sd_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2682                            int64_t pos)
2683 {
2684     BDRVSheepdogState *s = bs->opaque;
2685     void *buf;
2686     int ret;
2687
2688     buf = qemu_blockalign(bs, qiov->size);
2689     qemu_iovec_to_buf(qiov, 0, buf, qiov->size);
2690     ret = do_load_save_vmstate(s, (uint8_t *) buf, pos, qiov->size, 0);
2691     qemu_vfree(buf);
2692
2693     return ret;
2694 }
2695
2696 static int sd_load_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2697                            int64_t pos)
2698 {
2699     BDRVSheepdogState *s = bs->opaque;
2700     void *buf;
2701     int ret;
2702
2703     buf = qemu_blockalign(bs, qiov->size);
2704     ret = do_load_save_vmstate(s, buf, pos, qiov->size, 1);
2705     qemu_iovec_from_buf(qiov, 0, buf, qiov->size);
2706     qemu_vfree(buf);
2707
2708     return ret;
2709 }
2710
2711
2712 static coroutine_fn int sd_co_pdiscard(BlockDriverState *bs, int64_t offset,
2713                                       int count)
2714 {
2715     SheepdogAIOCB acb;
2716     BDRVSheepdogState *s = bs->opaque;
2717     QEMUIOVector discard_iov;
2718     struct iovec iov;
2719     uint32_t zero = 0;
2720
2721     if (!s->discard_supported) {
2722         return 0;
2723     }
2724
2725     memset(&discard_iov, 0, sizeof(discard_iov));
2726     memset(&iov, 0, sizeof(iov));
2727     iov.iov_base = &zero;
2728     iov.iov_len = sizeof(zero);
2729     discard_iov.iov = &iov;
2730     discard_iov.niov = 1;
2731     if (!QEMU_IS_ALIGNED(offset | count, BDRV_SECTOR_SIZE)) {
2732         return -ENOTSUP;
2733     }
2734     sd_aio_setup(&acb, s, &discard_iov, offset >> BDRV_SECTOR_BITS,
2735                  count >> BDRV_SECTOR_BITS, AIOCB_DISCARD_OBJ);
2736     sd_co_rw_vector(&acb);
2737     sd_aio_complete(&acb);
2738
2739     return acb.ret;
2740 }
2741
2742 static coroutine_fn int64_t
2743 sd_co_get_block_status(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
2744                        int *pnum, BlockDriverState **file)
2745 {
2746     BDRVSheepdogState *s = bs->opaque;
2747     SheepdogInode *inode = &s->inode;
2748     uint32_t object_size = (UINT32_C(1) << inode->block_size_shift);
2749     uint64_t offset = sector_num * BDRV_SECTOR_SIZE;
2750     unsigned long start = offset / object_size,
2751                   end = DIV_ROUND_UP((sector_num + nb_sectors) *
2752                                      BDRV_SECTOR_SIZE, object_size);
2753     unsigned long idx;
2754     int64_t ret = BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | offset;
2755
2756     for (idx = start; idx < end; idx++) {
2757         if (inode->data_vdi_id[idx] == 0) {
2758             break;
2759         }
2760     }
2761     if (idx == start) {
2762         /* Get the longest length of unallocated sectors */
2763         ret = 0;
2764         for (idx = start + 1; idx < end; idx++) {
2765             if (inode->data_vdi_id[idx] != 0) {
2766                 break;
2767             }
2768         }
2769     }
2770
2771     *pnum = (idx - start) * object_size / BDRV_SECTOR_SIZE;
2772     if (*pnum > nb_sectors) {
2773         *pnum = nb_sectors;
2774     }
2775     if (ret > 0 && ret & BDRV_BLOCK_OFFSET_VALID) {
2776         *file = bs;
2777     }
2778     return ret;
2779 }
2780
2781 static int64_t sd_get_allocated_file_size(BlockDriverState *bs)
2782 {
2783     BDRVSheepdogState *s = bs->opaque;
2784     SheepdogInode *inode = &s->inode;
2785     uint32_t object_size = (UINT32_C(1) << inode->block_size_shift);
2786     unsigned long i, last = DIV_ROUND_UP(inode->vdi_size, object_size);
2787     uint64_t size = 0;
2788
2789     for (i = 0; i < last; i++) {
2790         if (inode->data_vdi_id[i] == 0) {
2791             continue;
2792         }
2793         size += object_size;
2794     }
2795     return size;
2796 }
2797
2798 static QemuOptsList sd_create_opts = {
2799     .name = "sheepdog-create-opts",
2800     .head = QTAILQ_HEAD_INITIALIZER(sd_create_opts.head),
2801     .desc = {
2802         {
2803             .name = BLOCK_OPT_SIZE,
2804             .type = QEMU_OPT_SIZE,
2805             .help = "Virtual disk size"
2806         },
2807         {
2808             .name = BLOCK_OPT_BACKING_FILE,
2809             .type = QEMU_OPT_STRING,
2810             .help = "File name of a base image"
2811         },
2812         {
2813             .name = BLOCK_OPT_PREALLOC,
2814             .type = QEMU_OPT_STRING,
2815             .help = "Preallocation mode (allowed values: off, full)"
2816         },
2817         {
2818             .name = BLOCK_OPT_REDUNDANCY,
2819             .type = QEMU_OPT_STRING,
2820             .help = "Redundancy of the image"
2821         },
2822         {
2823             .name = BLOCK_OPT_OBJECT_SIZE,
2824             .type = QEMU_OPT_SIZE,
2825             .help = "Object size of the image"
2826         },
2827         { /* end of list */ }
2828     }
2829 };
2830
2831 static BlockDriver bdrv_sheepdog = {
2832     .format_name    = "sheepdog",
2833     .protocol_name  = "sheepdog",
2834     .instance_size  = sizeof(BDRVSheepdogState),
2835     .bdrv_needs_filename = true,
2836     .bdrv_file_open = sd_open,
2837     .bdrv_reopen_prepare    = sd_reopen_prepare,
2838     .bdrv_reopen_commit     = sd_reopen_commit,
2839     .bdrv_reopen_abort      = sd_reopen_abort,
2840     .bdrv_close     = sd_close,
2841     .bdrv_create    = sd_create,
2842     .bdrv_has_zero_init = bdrv_has_zero_init_1,
2843     .bdrv_getlength = sd_getlength,
2844     .bdrv_get_allocated_file_size = sd_get_allocated_file_size,
2845     .bdrv_truncate  = sd_truncate,
2846
2847     .bdrv_co_readv  = sd_co_readv,
2848     .bdrv_co_writev = sd_co_writev,
2849     .bdrv_co_flush_to_disk  = sd_co_flush_to_disk,
2850     .bdrv_co_pdiscard = sd_co_pdiscard,
2851     .bdrv_co_get_block_status = sd_co_get_block_status,
2852
2853     .bdrv_snapshot_create   = sd_snapshot_create,
2854     .bdrv_snapshot_goto     = sd_snapshot_goto,
2855     .bdrv_snapshot_delete   = sd_snapshot_delete,
2856     .bdrv_snapshot_list     = sd_snapshot_list,
2857
2858     .bdrv_save_vmstate  = sd_save_vmstate,
2859     .bdrv_load_vmstate  = sd_load_vmstate,
2860
2861     .bdrv_detach_aio_context = sd_detach_aio_context,
2862     .bdrv_attach_aio_context = sd_attach_aio_context,
2863
2864     .create_opts    = &sd_create_opts,
2865 };
2866
2867 static BlockDriver bdrv_sheepdog_tcp = {
2868     .format_name    = "sheepdog",
2869     .protocol_name  = "sheepdog+tcp",
2870     .instance_size  = sizeof(BDRVSheepdogState),
2871     .bdrv_needs_filename = true,
2872     .bdrv_file_open = sd_open,
2873     .bdrv_reopen_prepare    = sd_reopen_prepare,
2874     .bdrv_reopen_commit     = sd_reopen_commit,
2875     .bdrv_reopen_abort      = sd_reopen_abort,
2876     .bdrv_close     = sd_close,
2877     .bdrv_create    = sd_create,
2878     .bdrv_has_zero_init = bdrv_has_zero_init_1,
2879     .bdrv_getlength = sd_getlength,
2880     .bdrv_get_allocated_file_size = sd_get_allocated_file_size,
2881     .bdrv_truncate  = sd_truncate,
2882
2883     .bdrv_co_readv  = sd_co_readv,
2884     .bdrv_co_writev = sd_co_writev,
2885     .bdrv_co_flush_to_disk  = sd_co_flush_to_disk,
2886     .bdrv_co_pdiscard = sd_co_pdiscard,
2887     .bdrv_co_get_block_status = sd_co_get_block_status,
2888
2889     .bdrv_snapshot_create   = sd_snapshot_create,
2890     .bdrv_snapshot_goto     = sd_snapshot_goto,
2891     .bdrv_snapshot_delete   = sd_snapshot_delete,
2892     .bdrv_snapshot_list     = sd_snapshot_list,
2893
2894     .bdrv_save_vmstate  = sd_save_vmstate,
2895     .bdrv_load_vmstate  = sd_load_vmstate,
2896
2897     .bdrv_detach_aio_context = sd_detach_aio_context,
2898     .bdrv_attach_aio_context = sd_attach_aio_context,
2899
2900     .create_opts    = &sd_create_opts,
2901 };
2902
2903 static BlockDriver bdrv_sheepdog_unix = {
2904     .format_name    = "sheepdog",
2905     .protocol_name  = "sheepdog+unix",
2906     .instance_size  = sizeof(BDRVSheepdogState),
2907     .bdrv_needs_filename = true,
2908     .bdrv_file_open = sd_open,
2909     .bdrv_reopen_prepare    = sd_reopen_prepare,
2910     .bdrv_reopen_commit     = sd_reopen_commit,
2911     .bdrv_reopen_abort      = sd_reopen_abort,
2912     .bdrv_close     = sd_close,
2913     .bdrv_create    = sd_create,
2914     .bdrv_has_zero_init = bdrv_has_zero_init_1,
2915     .bdrv_getlength = sd_getlength,
2916     .bdrv_get_allocated_file_size = sd_get_allocated_file_size,
2917     .bdrv_truncate  = sd_truncate,
2918
2919     .bdrv_co_readv  = sd_co_readv,
2920     .bdrv_co_writev = sd_co_writev,
2921     .bdrv_co_flush_to_disk  = sd_co_flush_to_disk,
2922     .bdrv_co_pdiscard = sd_co_pdiscard,
2923     .bdrv_co_get_block_status = sd_co_get_block_status,
2924
2925     .bdrv_snapshot_create   = sd_snapshot_create,
2926     .bdrv_snapshot_goto     = sd_snapshot_goto,
2927     .bdrv_snapshot_delete   = sd_snapshot_delete,
2928     .bdrv_snapshot_list     = sd_snapshot_list,
2929
2930     .bdrv_save_vmstate  = sd_save_vmstate,
2931     .bdrv_load_vmstate  = sd_load_vmstate,
2932
2933     .bdrv_detach_aio_context = sd_detach_aio_context,
2934     .bdrv_attach_aio_context = sd_attach_aio_context,
2935
2936     .create_opts    = &sd_create_opts,
2937 };
2938
2939 static void bdrv_sheepdog_init(void)
2940 {
2941     bdrv_register(&bdrv_sheepdog);
2942     bdrv_register(&bdrv_sheepdog_tcp);
2943     bdrv_register(&bdrv_sheepdog_unix);
2944 }
2945 block_init(bdrv_sheepdog_init);
This page took 0.181981 seconds and 4 git commands to generate.