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