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