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