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