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