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