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