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