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