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