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