]> git.proxmox.com Git - qemu.git/blame - block/sheepdog.c
sheepdog: cleanup find_vdi_name
[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
982dcbf4
MK
944static int find_vdi_name(BDRVSheepdogState *s, const char *filename,
945 uint32_t snapid, const char *tag, uint32_t *vid,
946 bool lock)
33b1db1c
MK
947{
948 int ret, fd;
949 SheepdogVdiReq hdr;
950 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
951 unsigned int wlen, rlen = 0;
952 char buf[SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN];
953
25af257d 954 fd = connect_to_sdog(s);
33b1db1c 955 if (fd < 0) {
cb595887 956 return fd;
33b1db1c
MK
957 }
958
3178e275
JM
959 /* This pair of strncpy calls ensures that the buffer is zero-filled,
960 * which is desirable since we'll soon be sending those bytes, and
961 * don't want the send_req to read uninitialized data.
962 */
33b1db1c
MK
963 strncpy(buf, filename, SD_MAX_VDI_LEN);
964 strncpy(buf + SD_MAX_VDI_LEN, tag, SD_MAX_VDI_TAG_LEN);
965
966 memset(&hdr, 0, sizeof(hdr));
982dcbf4 967 if (lock) {
33b1db1c 968 hdr.opcode = SD_OP_LOCK_VDI;
982dcbf4
MK
969 } else {
970 hdr.opcode = SD_OP_GET_VDI_INFO;
33b1db1c
MK
971 }
972 wlen = SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN;
973 hdr.proto_ver = SD_PROTO_VER;
974 hdr.data_length = wlen;
975 hdr.snapid = snapid;
976 hdr.flags = SD_FLAG_CMD_WRITE;
977
978 ret = do_req(fd, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
979 if (ret) {
33b1db1c
MK
980 goto out;
981 }
982
983 if (rsp->result != SD_RES_SUCCESS) {
6daf194d 984 error_report("cannot get vdi info, %s, %s %d %s",
33b1db1c 985 sd_strerror(rsp->result), filename, snapid, tag);
cb595887
MK
986 if (rsp->result == SD_RES_NO_VDI) {
987 ret = -ENOENT;
988 } else {
989 ret = -EIO;
990 }
33b1db1c
MK
991 goto out;
992 }
993 *vid = rsp->vdi_id;
994
995 ret = 0;
996out:
997 closesocket(fd);
998 return ret;
999}
1000
d8716b41 1001static int coroutine_fn add_aio_request(BDRVSheepdogState *s, AIOReq *aio_req,
2f536801 1002 struct iovec *iov, int niov, bool create,
33b1db1c
MK
1003 enum AIOCBState aiocb_type)
1004{
1005 int nr_copies = s->inode.nr_copies;
1006 SheepdogObjReq hdr;
47783072 1007 unsigned int wlen = 0;
33b1db1c
MK
1008 int ret;
1009 uint64_t oid = aio_req->oid;
1010 unsigned int datalen = aio_req->data_len;
1011 uint64_t offset = aio_req->offset;
1012 uint8_t flags = aio_req->flags;
1013 uint64_t old_oid = aio_req->base_oid;
1014
1015 if (!nr_copies) {
6daf194d 1016 error_report("bug");
33b1db1c
MK
1017 }
1018
1019 memset(&hdr, 0, sizeof(hdr));
1020
47783072
LY
1021 switch (aiocb_type) {
1022 case AIOCB_FLUSH_CACHE:
1023 hdr.opcode = SD_OP_FLUSH_VDI;
1024 break;
1025 case AIOCB_READ_UDATA:
33b1db1c
MK
1026 hdr.opcode = SD_OP_READ_OBJ;
1027 hdr.flags = flags;
47783072
LY
1028 break;
1029 case AIOCB_WRITE_UDATA:
1030 if (create) {
1031 hdr.opcode = SD_OP_CREATE_AND_WRITE_OBJ;
1032 } else {
1033 hdr.opcode = SD_OP_WRITE_OBJ;
1034 }
33b1db1c 1035 wlen = datalen;
33b1db1c 1036 hdr.flags = SD_FLAG_CMD_WRITE | flags;
47783072 1037 break;
cac8f4a6
LY
1038 case AIOCB_DISCARD_OBJ:
1039 hdr.opcode = SD_OP_DISCARD_OBJ;
1040 break;
33b1db1c
MK
1041 }
1042
0e7106d8
LY
1043 if (s->cache_flags) {
1044 hdr.flags |= s->cache_flags;
47622c44
LY
1045 }
1046
33b1db1c
MK
1047 hdr.oid = oid;
1048 hdr.cow_oid = old_oid;
1049 hdr.copies = s->inode.nr_copies;
1050
1051 hdr.data_length = datalen;
1052 hdr.offset = offset;
1053
1054 hdr.id = aio_req->id;
1055
2df46246
MK
1056 qemu_co_mutex_lock(&s->lock);
1057 s->co_send = qemu_coroutine_self();
1058 qemu_aio_set_fd_handler(s->fd, co_read_response, co_write_request,
bafbd6a1 1059 aio_flush_request, s);
128aa589 1060 socket_set_cork(s->fd, 1);
33b1db1c
MK
1061
1062 /* send a header */
8c5135f9
PB
1063 ret = qemu_co_send(s->fd, &hdr, sizeof(hdr));
1064 if (ret < 0) {
c3fecea5 1065 qemu_co_mutex_unlock(&s->lock);
6daf194d 1066 error_report("failed to send a req, %s", strerror(errno));
cb595887 1067 return -errno;
33b1db1c
MK
1068 }
1069
1070 if (wlen) {
2fc8ae1d 1071 ret = qemu_co_sendv(s->fd, iov, niov, aio_req->iov_offset, wlen);
8c5135f9 1072 if (ret < 0) {
c3fecea5 1073 qemu_co_mutex_unlock(&s->lock);
6daf194d 1074 error_report("failed to send a data, %s", strerror(errno));
cb595887 1075 return -errno;
33b1db1c
MK
1076 }
1077 }
1078
128aa589 1079 socket_set_cork(s->fd, 0);
2df46246 1080 qemu_aio_set_fd_handler(s->fd, co_read_response, NULL,
bafbd6a1 1081 aio_flush_request, s);
2df46246 1082 qemu_co_mutex_unlock(&s->lock);
33b1db1c
MK
1083
1084 return 0;
1085}
1086
1087static int read_write_object(int fd, char *buf, uint64_t oid, int copies,
1088 unsigned int datalen, uint64_t offset,
0e7106d8 1089 bool write, bool create, uint32_t cache_flags)
33b1db1c
MK
1090{
1091 SheepdogObjReq hdr;
1092 SheepdogObjRsp *rsp = (SheepdogObjRsp *)&hdr;
1093 unsigned int wlen, rlen;
1094 int ret;
1095
1096 memset(&hdr, 0, sizeof(hdr));
1097
1098 if (write) {
1099 wlen = datalen;
1100 rlen = 0;
1101 hdr.flags = SD_FLAG_CMD_WRITE;
1102 if (create) {
1103 hdr.opcode = SD_OP_CREATE_AND_WRITE_OBJ;
1104 } else {
1105 hdr.opcode = SD_OP_WRITE_OBJ;
1106 }
1107 } else {
1108 wlen = 0;
1109 rlen = datalen;
1110 hdr.opcode = SD_OP_READ_OBJ;
1111 }
47622c44 1112
0e7106d8 1113 hdr.flags |= cache_flags;
47622c44 1114
33b1db1c
MK
1115 hdr.oid = oid;
1116 hdr.data_length = datalen;
1117 hdr.offset = offset;
1118 hdr.copies = copies;
1119
1120 ret = do_req(fd, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
1121 if (ret) {
6daf194d 1122 error_report("failed to send a request to the sheep");
cb595887 1123 return ret;
33b1db1c
MK
1124 }
1125
1126 switch (rsp->result) {
1127 case SD_RES_SUCCESS:
1128 return 0;
1129 default:
6daf194d 1130 error_report("%s", sd_strerror(rsp->result));
cb595887 1131 return -EIO;
33b1db1c
MK
1132 }
1133}
1134
1135static int read_object(int fd, char *buf, uint64_t oid, int copies,
0e7106d8
LY
1136 unsigned int datalen, uint64_t offset,
1137 uint32_t cache_flags)
33b1db1c 1138{
2f536801 1139 return read_write_object(fd, buf, oid, copies, datalen, offset, false,
0e7106d8 1140 false, cache_flags);
33b1db1c
MK
1141}
1142
1143static int write_object(int fd, char *buf, uint64_t oid, int copies,
2f536801 1144 unsigned int datalen, uint64_t offset, bool create,
0e7106d8 1145 uint32_t cache_flags)
33b1db1c 1146{
2f536801 1147 return read_write_object(fd, buf, oid, copies, datalen, offset, true,
0e7106d8 1148 create, cache_flags);
33b1db1c
MK
1149}
1150
c8c96350
KW
1151/* TODO Convert to fine grained options */
1152static QemuOptsList runtime_opts = {
1153 .name = "sheepdog",
1154 .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
1155 .desc = {
1156 {
1157 .name = "filename",
1158 .type = QEMU_OPT_STRING,
1159 .help = "URL to the sheepdog image",
1160 },
1161 { /* end of list */ }
1162 },
1163};
1164
56d1b4d2 1165static int sd_open(BlockDriverState *bs, QDict *options, int flags)
33b1db1c
MK
1166{
1167 int ret, fd;
1168 uint32_t vid = 0;
1169 BDRVSheepdogState *s = bs->opaque;
1170 char vdi[SD_MAX_VDI_LEN], tag[SD_MAX_VDI_TAG_LEN];
1171 uint32_t snapid;
1172 char *buf = NULL;
c8c96350
KW
1173 QemuOpts *opts;
1174 Error *local_err = NULL;
1175 const char *filename;
1176
1177 opts = qemu_opts_create_nofail(&runtime_opts);
1178 qemu_opts_absorb_qdict(opts, options, &local_err);
1179 if (error_is_set(&local_err)) {
1180 qerror_report_err(local_err);
1181 error_free(local_err);
1182 ret = -EINVAL;
1183 goto out;
1184 }
1185
1186 filename = qemu_opt_get(opts, "filename");
33b1db1c 1187
c292ee6a
MK
1188 QLIST_INIT(&s->inflight_aio_head);
1189 QLIST_INIT(&s->pending_aio_head);
33b1db1c
MK
1190 s->fd = -1;
1191
1192 memset(vdi, 0, sizeof(vdi));
1193 memset(tag, 0, sizeof(tag));
5d6768e3
MK
1194
1195 if (strstr(filename, "://")) {
1196 ret = sd_parse_uri(s, filename, vdi, &snapid, tag);
1197 } else {
1198 ret = parse_vdiname(s, filename, vdi, &snapid, tag);
1199 }
1200 if (ret < 0) {
33b1db1c
MK
1201 goto out;
1202 }
1203 s->fd = get_sheep_fd(s);
1204 if (s->fd < 0) {
cb595887 1205 ret = s->fd;
33b1db1c
MK
1206 goto out;
1207 }
1208
982dcbf4 1209 ret = find_vdi_name(s, vdi, snapid, tag, &vid, true);
33b1db1c
MK
1210 if (ret) {
1211 goto out;
1212 }
1213
0e7106d8
LY
1214 /*
1215 * QEMU block layer emulates writethrough cache as 'writeback + flush', so
1216 * we always set SD_FLAG_CMD_CACHE (writeback cache) as default.
1217 */
1218 s->cache_flags = SD_FLAG_CMD_CACHE;
1219 if (flags & BDRV_O_NOCACHE) {
1220 s->cache_flags = SD_FLAG_CMD_DIRECT;
1221 }
cac8f4a6 1222 s->discard_supported = true;
0e7106d8 1223
622b6057 1224 if (snapid || tag[0] != '\0') {
33b1db1c 1225 dprintf("%" PRIx32 " snapshot inode was open.\n", vid);
2f536801 1226 s->is_snapshot = true;
33b1db1c
MK
1227 }
1228
25af257d 1229 fd = connect_to_sdog(s);
33b1db1c 1230 if (fd < 0) {
cb595887 1231 ret = fd;
33b1db1c
MK
1232 goto out;
1233 }
1234
7267c094 1235 buf = g_malloc(SD_INODE_SIZE);
47622c44 1236 ret = read_object(fd, buf, vid_to_vdi_oid(vid), 0, SD_INODE_SIZE, 0,
0e7106d8 1237 s->cache_flags);
33b1db1c
MK
1238
1239 closesocket(fd);
1240
1241 if (ret) {
1242 goto out;
1243 }
1244
1245 memcpy(&s->inode, buf, sizeof(s->inode));
1246 s->min_dirty_data_idx = UINT32_MAX;
1247 s->max_dirty_data_idx = 0;
1248
e8bfaa2f 1249 bs->total_sectors = s->inode.vdi_size / BDRV_SECTOR_SIZE;
3178e275 1250 pstrcpy(s->name, sizeof(s->name), vdi);
2df46246 1251 qemu_co_mutex_init(&s->lock);
c8c96350 1252 qemu_opts_del(opts);
7267c094 1253 g_free(buf);
33b1db1c
MK
1254 return 0;
1255out:
bafbd6a1 1256 qemu_aio_set_fd_handler(s->fd, NULL, NULL, NULL, NULL);
33b1db1c
MK
1257 if (s->fd >= 0) {
1258 closesocket(s->fd);
1259 }
c8c96350 1260 qemu_opts_del(opts);
7267c094 1261 g_free(buf);
cb595887 1262 return ret;
33b1db1c
MK
1263}
1264
25af257d
MK
1265static int do_sd_create(BDRVSheepdogState *s, char *filename, int64_t vdi_size,
1266 uint32_t base_vid, uint32_t *vdi_id, int snapshot)
33b1db1c
MK
1267{
1268 SheepdogVdiReq hdr;
1269 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
1270 int fd, ret;
1271 unsigned int wlen, rlen = 0;
1272 char buf[SD_MAX_VDI_LEN];
1273
25af257d 1274 fd = connect_to_sdog(s);
33b1db1c 1275 if (fd < 0) {
cb595887 1276 return fd;
33b1db1c
MK
1277 }
1278
3178e275
JM
1279 /* FIXME: would it be better to fail (e.g., return -EIO) when filename
1280 * does not fit in buf? For now, just truncate and avoid buffer overrun.
1281 */
33b1db1c 1282 memset(buf, 0, sizeof(buf));
3178e275 1283 pstrcpy(buf, sizeof(buf), filename);
33b1db1c
MK
1284
1285 memset(&hdr, 0, sizeof(hdr));
1286 hdr.opcode = SD_OP_NEW_VDI;
6f74c260 1287 hdr.vdi_id = base_vid;
33b1db1c
MK
1288
1289 wlen = SD_MAX_VDI_LEN;
1290
1291 hdr.flags = SD_FLAG_CMD_WRITE;
1292 hdr.snapid = snapshot;
1293
1294 hdr.data_length = wlen;
1295 hdr.vdi_size = vdi_size;
1296
1297 ret = do_req(fd, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
1298
1299 closesocket(fd);
1300
1301 if (ret) {
cb595887 1302 return ret;
33b1db1c
MK
1303 }
1304
1305 if (rsp->result != SD_RES_SUCCESS) {
6daf194d 1306 error_report("%s, %s", sd_strerror(rsp->result), filename);
33b1db1c
MK
1307 return -EIO;
1308 }
1309
1310 if (vdi_id) {
1311 *vdi_id = rsp->vdi_id;
1312 }
1313
1314 return 0;
1315}
1316
a8e0fdd7
MK
1317static int sd_prealloc(const char *filename)
1318{
1319 BlockDriverState *bs = NULL;
1320 uint32_t idx, max_idx;
1321 int64_t vdi_size;
7267c094 1322 void *buf = g_malloc0(SD_DATA_OBJ_SIZE);
a8e0fdd7
MK
1323 int ret;
1324
787e4a85 1325 ret = bdrv_file_open(&bs, filename, NULL, BDRV_O_RDWR);
a8e0fdd7
MK
1326 if (ret < 0) {
1327 goto out;
1328 }
1329
1330 vdi_size = bdrv_getlength(bs);
1331 if (vdi_size < 0) {
1332 ret = vdi_size;
1333 goto out;
1334 }
1335 max_idx = DIV_ROUND_UP(vdi_size, SD_DATA_OBJ_SIZE);
1336
1337 for (idx = 0; idx < max_idx; idx++) {
1338 /*
1339 * The created image can be a cloned image, so we need to read
1340 * a data from the source image.
1341 */
1342 ret = bdrv_pread(bs, idx * SD_DATA_OBJ_SIZE, buf, SD_DATA_OBJ_SIZE);
1343 if (ret < 0) {
1344 goto out;
1345 }
1346 ret = bdrv_pwrite(bs, idx * SD_DATA_OBJ_SIZE, buf, SD_DATA_OBJ_SIZE);
1347 if (ret < 0) {
1348 goto out;
1349 }
1350 }
1351out:
1352 if (bs) {
1353 bdrv_delete(bs);
1354 }
7267c094 1355 g_free(buf);
a8e0fdd7
MK
1356
1357 return ret;
1358}
1359
33b1db1c
MK
1360static int sd_create(const char *filename, QEMUOptionParameter *options)
1361{
b6fc8245 1362 int ret = 0;
b4447363 1363 uint32_t vid = 0, base_vid = 0;
33b1db1c
MK
1364 int64_t vdi_size = 0;
1365 char *backing_file = NULL;
b6fc8245 1366 BDRVSheepdogState *s;
b4447363
MK
1367 char vdi[SD_MAX_VDI_LEN], tag[SD_MAX_VDI_TAG_LEN];
1368 uint32_t snapid;
2f536801 1369 bool prealloc = false;
33b1db1c 1370
b6fc8245
MK
1371 s = g_malloc0(sizeof(BDRVSheepdogState));
1372
b4447363
MK
1373 memset(vdi, 0, sizeof(vdi));
1374 memset(tag, 0, sizeof(tag));
5d6768e3
MK
1375 if (strstr(filename, "://")) {
1376 ret = sd_parse_uri(s, filename, vdi, &snapid, tag);
1377 } else {
1378 ret = parse_vdiname(s, filename, vdi, &snapid, tag);
1379 }
1380 if (ret < 0) {
b6fc8245 1381 goto out;
b4447363
MK
1382 }
1383
33b1db1c
MK
1384 while (options && options->name) {
1385 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
1386 vdi_size = options->value.n;
1387 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
1388 backing_file = options->value.s;
a8e0fdd7
MK
1389 } else if (!strcmp(options->name, BLOCK_OPT_PREALLOC)) {
1390 if (!options->value.s || !strcmp(options->value.s, "off")) {
2f536801 1391 prealloc = false;
a8e0fdd7 1392 } else if (!strcmp(options->value.s, "full")) {
2f536801 1393 prealloc = true;
a8e0fdd7
MK
1394 } else {
1395 error_report("Invalid preallocation mode: '%s'",
1396 options->value.s);
b6fc8245
MK
1397 ret = -EINVAL;
1398 goto out;
a8e0fdd7 1399 }
33b1db1c
MK
1400 }
1401 options++;
1402 }
1403
1404 if (vdi_size > SD_MAX_VDI_SIZE) {
6daf194d 1405 error_report("too big image size");
b6fc8245
MK
1406 ret = -EINVAL;
1407 goto out;
33b1db1c
MK
1408 }
1409
1410 if (backing_file) {
1411 BlockDriverState *bs;
1412 BDRVSheepdogState *s;
1413 BlockDriver *drv;
1414
1415 /* Currently, only Sheepdog backing image is supported. */
1416 drv = bdrv_find_protocol(backing_file);
1417 if (!drv || strcmp(drv->protocol_name, "sheepdog") != 0) {
6daf194d 1418 error_report("backing_file must be a sheepdog image");
b6fc8245
MK
1419 ret = -EINVAL;
1420 goto out;
33b1db1c
MK
1421 }
1422
787e4a85 1423 ret = bdrv_file_open(&bs, backing_file, NULL, 0);
cb595887 1424 if (ret < 0) {
b6fc8245 1425 goto out;
cb595887 1426 }
33b1db1c
MK
1427
1428 s = bs->opaque;
1429
1430 if (!is_snapshot(&s->inode)) {
6daf194d 1431 error_report("cannot clone from a non snapshot vdi");
33b1db1c 1432 bdrv_delete(bs);
b6fc8245
MK
1433 ret = -EINVAL;
1434 goto out;
33b1db1c
MK
1435 }
1436
b4447363 1437 base_vid = s->inode.vdi_id;
33b1db1c
MK
1438 bdrv_delete(bs);
1439 }
1440
25af257d 1441 ret = do_sd_create(s, vdi, vdi_size, base_vid, &vid, 0);
a8e0fdd7 1442 if (!prealloc || ret) {
b6fc8245 1443 goto out;
a8e0fdd7
MK
1444 }
1445
b6fc8245
MK
1446 ret = sd_prealloc(filename);
1447out:
1448 g_free(s);
1449 return ret;
33b1db1c
MK
1450}
1451
1452static void sd_close(BlockDriverState *bs)
1453{
1454 BDRVSheepdogState *s = bs->opaque;
1455 SheepdogVdiReq hdr;
1456 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
1457 unsigned int wlen, rlen = 0;
1458 int fd, ret;
1459
1460 dprintf("%s\n", s->name);
1461
25af257d 1462 fd = connect_to_sdog(s);
33b1db1c
MK
1463 if (fd < 0) {
1464 return;
1465 }
1466
1467 memset(&hdr, 0, sizeof(hdr));
1468
1469 hdr.opcode = SD_OP_RELEASE_VDI;
6f74c260 1470 hdr.vdi_id = s->inode.vdi_id;
33b1db1c
MK
1471 wlen = strlen(s->name) + 1;
1472 hdr.data_length = wlen;
1473 hdr.flags = SD_FLAG_CMD_WRITE;
1474
1475 ret = do_req(fd, (SheepdogReq *)&hdr, s->name, &wlen, &rlen);
1476
1477 closesocket(fd);
1478
1479 if (!ret && rsp->result != SD_RES_SUCCESS &&
1480 rsp->result != SD_RES_VDI_NOT_LOCKED) {
6daf194d 1481 error_report("%s, %s", sd_strerror(rsp->result), s->name);
33b1db1c
MK
1482 }
1483
bafbd6a1 1484 qemu_aio_set_fd_handler(s->fd, NULL, NULL, NULL, NULL);
33b1db1c 1485 closesocket(s->fd);
25af257d 1486 g_free(s->host_spec);
33b1db1c
MK
1487}
1488
1489static int64_t sd_getlength(BlockDriverState *bs)
1490{
1491 BDRVSheepdogState *s = bs->opaque;
1492
1493 return s->inode.vdi_size;
1494}
1495
1496static int sd_truncate(BlockDriverState *bs, int64_t offset)
1497{
1498 BDRVSheepdogState *s = bs->opaque;
1499 int ret, fd;
1500 unsigned int datalen;
1501
1502 if (offset < s->inode.vdi_size) {
6daf194d 1503 error_report("shrinking is not supported");
33b1db1c
MK
1504 return -EINVAL;
1505 } else if (offset > SD_MAX_VDI_SIZE) {
6daf194d 1506 error_report("too big image size");
33b1db1c
MK
1507 return -EINVAL;
1508 }
1509
25af257d 1510 fd = connect_to_sdog(s);
33b1db1c 1511 if (fd < 0) {
cb595887 1512 return fd;
33b1db1c
MK
1513 }
1514
1515 /* we don't need to update entire object */
1516 datalen = SD_INODE_SIZE - sizeof(s->inode.data_vdi_id);
1517 s->inode.vdi_size = offset;
1518 ret = write_object(fd, (char *)&s->inode, vid_to_vdi_oid(s->inode.vdi_id),
0e7106d8 1519 s->inode.nr_copies, datalen, 0, false, s->cache_flags);
33b1db1c
MK
1520 close(fd);
1521
1522 if (ret < 0) {
6daf194d 1523 error_report("failed to update an inode.");
33b1db1c
MK
1524 }
1525
cb595887 1526 return ret;
33b1db1c
MK
1527}
1528
1529/*
1530 * This function is called after writing data objects. If we need to
1531 * update metadata, this sends a write request to the vdi object.
2df46246 1532 * Otherwise, this switches back to sd_co_readv/writev.
33b1db1c 1533 */
d8716b41 1534static void coroutine_fn sd_write_done(SheepdogAIOCB *acb)
33b1db1c
MK
1535{
1536 int ret;
1537 BDRVSheepdogState *s = acb->common.bs->opaque;
1538 struct iovec iov;
1539 AIOReq *aio_req;
1540 uint32_t offset, data_len, mn, mx;
1541
1542 mn = s->min_dirty_data_idx;
1543 mx = s->max_dirty_data_idx;
1544 if (mn <= mx) {
1545 /* we need to update the vdi object. */
1546 offset = sizeof(s->inode) - sizeof(s->inode.data_vdi_id) +
1547 mn * sizeof(s->inode.data_vdi_id[0]);
1548 data_len = (mx - mn + 1) * sizeof(s->inode.data_vdi_id[0]);
1549
1550 s->min_dirty_data_idx = UINT32_MAX;
1551 s->max_dirty_data_idx = 0;
1552
1553 iov.iov_base = &s->inode;
1554 iov.iov_len = sizeof(s->inode);
1555 aio_req = alloc_aio_req(s, acb, vid_to_vdi_oid(s->inode.vdi_id),
1556 data_len, offset, 0, 0, offset);
c292ee6a 1557 QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
2f536801 1558 ret = add_aio_request(s, aio_req, &iov, 1, false, AIOCB_WRITE_UDATA);
33b1db1c
MK
1559 if (ret) {
1560 free_aio_req(s, aio_req);
1561 acb->ret = -EIO;
1562 goto out;
1563 }
1564
1565 acb->aio_done_func = sd_finish_aiocb;
1566 acb->aiocb_type = AIOCB_WRITE_UDATA;
1567 return;
1568 }
1569out:
1570 sd_finish_aiocb(acb);
1571}
1572
1573/*
1574 * Create a writable VDI from a snapshot
1575 */
1576static int sd_create_branch(BDRVSheepdogState *s)
1577{
1578 int ret, fd;
1579 uint32_t vid;
1580 char *buf;
1581
1582 dprintf("%" PRIx32 " is snapshot.\n", s->inode.vdi_id);
1583
7267c094 1584 buf = g_malloc(SD_INODE_SIZE);
33b1db1c 1585
25af257d 1586 ret = do_sd_create(s, s->name, s->inode.vdi_size, s->inode.vdi_id, &vid, 1);
33b1db1c
MK
1587 if (ret) {
1588 goto out;
1589 }
1590
1591 dprintf("%" PRIx32 " is created.\n", vid);
1592
25af257d 1593 fd = connect_to_sdog(s);
33b1db1c 1594 if (fd < 0) {
cb595887 1595 ret = fd;
33b1db1c
MK
1596 goto out;
1597 }
1598
1599 ret = read_object(fd, buf, vid_to_vdi_oid(vid), s->inode.nr_copies,
0e7106d8 1600 SD_INODE_SIZE, 0, s->cache_flags);
33b1db1c
MK
1601
1602 closesocket(fd);
1603
1604 if (ret < 0) {
1605 goto out;
1606 }
1607
1608 memcpy(&s->inode, buf, sizeof(s->inode));
1609
2f536801 1610 s->is_snapshot = false;
33b1db1c
MK
1611 ret = 0;
1612 dprintf("%" PRIx32 " was newly created.\n", s->inode.vdi_id);
1613
1614out:
7267c094 1615 g_free(buf);
33b1db1c
MK
1616
1617 return ret;
1618}
1619
1620/*
1621 * Send I/O requests to the server.
1622 *
1623 * This function sends requests to the server, links the requests to
c292ee6a 1624 * the inflight_list in BDRVSheepdogState, and exits without
33b1db1c
MK
1625 * waiting the response. The responses are received in the
1626 * `aio_read_response' function which is called from the main loop as
1627 * a fd handler.
2df46246
MK
1628 *
1629 * Returns 1 when we need to wait a response, 0 when there is no sent
1630 * request and -errno in error cases.
33b1db1c 1631 */
d8716b41 1632static int coroutine_fn sd_co_rw_vector(void *p)
33b1db1c
MK
1633{
1634 SheepdogAIOCB *acb = p;
1635 int ret = 0;
e8bfaa2f
LY
1636 unsigned long len, done = 0, total = acb->nb_sectors * BDRV_SECTOR_SIZE;
1637 unsigned long idx = acb->sector_num * BDRV_SECTOR_SIZE / SD_DATA_OBJ_SIZE;
33b1db1c 1638 uint64_t oid;
e8bfaa2f 1639 uint64_t offset = (acb->sector_num * BDRV_SECTOR_SIZE) % SD_DATA_OBJ_SIZE;
33b1db1c
MK
1640 BDRVSheepdogState *s = acb->common.bs->opaque;
1641 SheepdogInode *inode = &s->inode;
1642 AIOReq *aio_req;
1643
33b1db1c
MK
1644 if (acb->aiocb_type == AIOCB_WRITE_UDATA && s->is_snapshot) {
1645 /*
1646 * In the case we open the snapshot VDI, Sheepdog creates the
1647 * writable VDI when we do a write operation first.
1648 */
1649 ret = sd_create_branch(s);
1650 if (ret) {
1651 acb->ret = -EIO;
1652 goto out;
1653 }
1654 }
1655
1d732d7d
MK
1656 /*
1657 * Make sure we don't free the aiocb before we are done with all requests.
1658 * This additional reference is dropped at the end of this function.
1659 */
1660 acb->nr_pending++;
1661
33b1db1c
MK
1662 while (done != total) {
1663 uint8_t flags = 0;
1664 uint64_t old_oid = 0;
2f536801 1665 bool create = false;
33b1db1c
MK
1666
1667 oid = vid_to_data_oid(inode->data_vdi_id[idx], idx);
1668
1669 len = MIN(total - done, SD_DATA_OBJ_SIZE - offset);
1670
19db9b90
CH
1671 switch (acb->aiocb_type) {
1672 case AIOCB_READ_UDATA:
1673 if (!inode->data_vdi_id[idx]) {
1674 qemu_iovec_memset(acb->qiov, done, 0, len);
33b1db1c
MK
1675 goto done;
1676 }
19db9b90
CH
1677 break;
1678 case AIOCB_WRITE_UDATA:
1679 if (!inode->data_vdi_id[idx]) {
2f536801 1680 create = true;
19db9b90
CH
1681 } else if (!is_data_obj_writable(inode, idx)) {
1682 /* Copy-On-Write */
2f536801 1683 create = true;
19db9b90
CH
1684 old_oid = oid;
1685 flags = SD_FLAG_CMD_COW;
1686 }
1687 break;
cac8f4a6
LY
1688 case AIOCB_DISCARD_OBJ:
1689 /*
1690 * We discard the object only when the whole object is
1691 * 1) allocated 2) trimmed. Otherwise, simply skip it.
1692 */
1693 if (len != SD_DATA_OBJ_SIZE || inode->data_vdi_id[idx] == 0) {
1694 goto done;
1695 }
1696 break;
19db9b90
CH
1697 default:
1698 break;
33b1db1c
MK
1699 }
1700
1701 if (create) {
1b6ac998
MK
1702 dprintf("update ino (%" PRIu32 ") %" PRIu64 " %" PRIu64 " %ld\n",
1703 inode->vdi_id, oid,
33b1db1c
MK
1704 vid_to_data_oid(inode->data_vdi_id[idx], idx), idx);
1705 oid = vid_to_data_oid(inode->vdi_id, idx);
1b6ac998 1706 dprintf("new oid %" PRIx64 "\n", oid);
33b1db1c
MK
1707 }
1708
1709 aio_req = alloc_aio_req(s, acb, oid, len, offset, flags, old_oid, done);
1710
1711 if (create) {
1712 AIOReq *areq;
c292ee6a 1713 QLIST_FOREACH(areq, &s->inflight_aio_head, aio_siblings) {
33b1db1c
MK
1714 if (areq->oid == oid) {
1715 /*
1716 * Sheepdog cannot handle simultaneous create
1717 * requests to the same object. So we cannot send
1718 * the request until the previous request
1719 * finishes.
1720 */
1721 aio_req->flags = 0;
1722 aio_req->base_oid = 0;
c292ee6a
MK
1723 QLIST_INSERT_HEAD(&s->pending_aio_head, aio_req,
1724 aio_siblings);
33b1db1c
MK
1725 goto done;
1726 }
1727 }
1728 }
1729
c292ee6a 1730 QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
33b1db1c
MK
1731 ret = add_aio_request(s, aio_req, acb->qiov->iov, acb->qiov->niov,
1732 create, acb->aiocb_type);
1733 if (ret < 0) {
6daf194d 1734 error_report("add_aio_request is failed");
33b1db1c
MK
1735 free_aio_req(s, aio_req);
1736 acb->ret = -EIO;
1737 goto out;
1738 }
1739 done:
1740 offset = 0;
1741 idx++;
1742 done += len;
1743 }
1744out:
1d732d7d 1745 if (!--acb->nr_pending) {
2df46246 1746 return acb->ret;
33b1db1c 1747 }
2df46246 1748 return 1;
33b1db1c
MK
1749}
1750
a968168c 1751static coroutine_fn int sd_co_writev(BlockDriverState *bs, int64_t sector_num,
2df46246 1752 int nb_sectors, QEMUIOVector *qiov)
33b1db1c
MK
1753{
1754 SheepdogAIOCB *acb;
2df46246 1755 int ret;
33b1db1c
MK
1756
1757 if (bs->growable && sector_num + nb_sectors > bs->total_sectors) {
e8bfaa2f 1758 ret = sd_truncate(bs, (sector_num + nb_sectors) * BDRV_SECTOR_SIZE);
cb595887
MK
1759 if (ret < 0) {
1760 return ret;
33b1db1c
MK
1761 }
1762 bs->total_sectors = sector_num + nb_sectors;
1763 }
1764
f700f8e3 1765 acb = sd_aio_setup(bs, qiov, sector_num, nb_sectors);
33b1db1c
MK
1766 acb->aio_done_func = sd_write_done;
1767 acb->aiocb_type = AIOCB_WRITE_UDATA;
1768
2df46246
MK
1769 ret = sd_co_rw_vector(acb);
1770 if (ret <= 0) {
1771 qemu_aio_release(acb);
1772 return ret;
1773 }
1774
1775 qemu_coroutine_yield();
1776
1777 return acb->ret;
33b1db1c
MK
1778}
1779
a968168c 1780static coroutine_fn int sd_co_readv(BlockDriverState *bs, int64_t sector_num,
2df46246 1781 int nb_sectors, QEMUIOVector *qiov)
33b1db1c
MK
1782{
1783 SheepdogAIOCB *acb;
19db9b90 1784 int ret;
33b1db1c 1785
f700f8e3 1786 acb = sd_aio_setup(bs, qiov, sector_num, nb_sectors);
33b1db1c
MK
1787 acb->aiocb_type = AIOCB_READ_UDATA;
1788 acb->aio_done_func = sd_finish_aiocb;
1789
2df46246
MK
1790 ret = sd_co_rw_vector(acb);
1791 if (ret <= 0) {
1792 qemu_aio_release(acb);
1793 return ret;
1794 }
1795
1796 qemu_coroutine_yield();
1797
1798 return acb->ret;
33b1db1c
MK
1799}
1800
47622c44
LY
1801static int coroutine_fn sd_co_flush_to_disk(BlockDriverState *bs)
1802{
1803 BDRVSheepdogState *s = bs->opaque;
47783072
LY
1804 SheepdogAIOCB *acb;
1805 AIOReq *aio_req;
47622c44 1806 int ret;
47622c44 1807
0e7106d8 1808 if (s->cache_flags != SD_FLAG_CMD_CACHE) {
47622c44
LY
1809 return 0;
1810 }
1811
f700f8e3 1812 acb = sd_aio_setup(bs, NULL, 0, 0);
47783072
LY
1813 acb->aiocb_type = AIOCB_FLUSH_CACHE;
1814 acb->aio_done_func = sd_finish_aiocb;
47622c44 1815
47783072
LY
1816 aio_req = alloc_aio_req(s, acb, vid_to_vdi_oid(s->inode.vdi_id),
1817 0, 0, 0, 0, 0);
1818 QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
1819 ret = add_aio_request(s, aio_req, NULL, 0, false, acb->aiocb_type);
1820 if (ret < 0) {
1821 error_report("add_aio_request is failed");
1822 free_aio_req(s, aio_req);
1823 qemu_aio_release(acb);
47622c44
LY
1824 return ret;
1825 }
1826
47783072
LY
1827 qemu_coroutine_yield();
1828 return acb->ret;
47622c44
LY
1829}
1830
33b1db1c
MK
1831static int sd_snapshot_create(BlockDriverState *bs, QEMUSnapshotInfo *sn_info)
1832{
1833 BDRVSheepdogState *s = bs->opaque;
1834 int ret, fd;
1835 uint32_t new_vid;
1836 SheepdogInode *inode;
1837 unsigned int datalen;
1838
1b6ac998 1839 dprintf("sn_info: name %s id_str %s s: name %s vm_state_size %" PRId64 " "
33b1db1c
MK
1840 "is_snapshot %d\n", sn_info->name, sn_info->id_str,
1841 s->name, sn_info->vm_state_size, s->is_snapshot);
1842
1843 if (s->is_snapshot) {
1844 error_report("You can't create a snapshot of a snapshot VDI, "
6daf194d 1845 "%s (%" PRIu32 ").", s->name, s->inode.vdi_id);
33b1db1c
MK
1846
1847 return -EINVAL;
1848 }
1849
1850 dprintf("%s %s\n", sn_info->name, sn_info->id_str);
1851
1852 s->inode.vm_state_size = sn_info->vm_state_size;
1853 s->inode.vm_clock_nsec = sn_info->vm_clock_nsec;
3178e275
JM
1854 /* It appears that inode.tag does not require a NUL terminator,
1855 * which means this use of strncpy is ok.
1856 */
33b1db1c
MK
1857 strncpy(s->inode.tag, sn_info->name, sizeof(s->inode.tag));
1858 /* we don't need to update entire object */
1859 datalen = SD_INODE_SIZE - sizeof(s->inode.data_vdi_id);
1860
1861 /* refresh inode. */
25af257d 1862 fd = connect_to_sdog(s);
33b1db1c 1863 if (fd < 0) {
cb595887 1864 ret = fd;
33b1db1c
MK
1865 goto cleanup;
1866 }
1867
1868 ret = write_object(fd, (char *)&s->inode, vid_to_vdi_oid(s->inode.vdi_id),
0e7106d8 1869 s->inode.nr_copies, datalen, 0, false, s->cache_flags);
33b1db1c 1870 if (ret < 0) {
6daf194d 1871 error_report("failed to write snapshot's inode.");
33b1db1c
MK
1872 goto cleanup;
1873 }
1874
25af257d
MK
1875 ret = do_sd_create(s, s->name, s->inode.vdi_size, s->inode.vdi_id, &new_vid,
1876 1);
33b1db1c 1877 if (ret < 0) {
6daf194d 1878 error_report("failed to create inode for snapshot. %s",
33b1db1c 1879 strerror(errno));
33b1db1c
MK
1880 goto cleanup;
1881 }
1882
7267c094 1883 inode = (SheepdogInode *)g_malloc(datalen);
33b1db1c
MK
1884
1885 ret = read_object(fd, (char *)inode, vid_to_vdi_oid(new_vid),
0e7106d8 1886 s->inode.nr_copies, datalen, 0, s->cache_flags);
33b1db1c
MK
1887
1888 if (ret < 0) {
6daf194d 1889 error_report("failed to read new inode info. %s", strerror(errno));
33b1db1c
MK
1890 goto cleanup;
1891 }
1892
1893 memcpy(&s->inode, inode, datalen);
1894 dprintf("s->inode: name %s snap_id %x oid %x\n",
1895 s->inode.name, s->inode.snap_id, s->inode.vdi_id);
1896
1897cleanup:
1898 closesocket(fd);
1899 return ret;
1900}
1901
1902static int sd_snapshot_goto(BlockDriverState *bs, const char *snapshot_id)
1903{
1904 BDRVSheepdogState *s = bs->opaque;
1905 BDRVSheepdogState *old_s;
1906 char vdi[SD_MAX_VDI_LEN], tag[SD_MAX_VDI_TAG_LEN];
1907 char *buf = NULL;
1908 uint32_t vid;
1909 uint32_t snapid = 0;
cb595887 1910 int ret = 0, fd;
33b1db1c 1911
7267c094 1912 old_s = g_malloc(sizeof(BDRVSheepdogState));
33b1db1c
MK
1913
1914 memcpy(old_s, s, sizeof(BDRVSheepdogState));
1915
3178e275 1916 pstrcpy(vdi, sizeof(vdi), s->name);
33b1db1c 1917
33b1db1c 1918 snapid = strtoul(snapshot_id, NULL, 10);
3178e275
JM
1919 if (snapid) {
1920 tag[0] = 0;
1921 } else {
1922 pstrcpy(tag, sizeof(tag), s->name);
33b1db1c
MK
1923 }
1924
982dcbf4 1925 ret = find_vdi_name(s, vdi, snapid, tag, &vid, false);
33b1db1c 1926 if (ret) {
6daf194d 1927 error_report("Failed to find_vdi_name");
33b1db1c
MK
1928 goto out;
1929 }
1930
25af257d 1931 fd = connect_to_sdog(s);
33b1db1c 1932 if (fd < 0) {
cb595887 1933 ret = fd;
33b1db1c
MK
1934 goto out;
1935 }
1936
7267c094 1937 buf = g_malloc(SD_INODE_SIZE);
33b1db1c 1938 ret = read_object(fd, buf, vid_to_vdi_oid(vid), s->inode.nr_copies,
0e7106d8 1939 SD_INODE_SIZE, 0, s->cache_flags);
33b1db1c
MK
1940
1941 closesocket(fd);
1942
1943 if (ret) {
33b1db1c
MK
1944 goto out;
1945 }
1946
1947 memcpy(&s->inode, buf, sizeof(s->inode));
1948
1949 if (!s->inode.vm_state_size) {
6daf194d 1950 error_report("Invalid snapshot");
33b1db1c
MK
1951 ret = -ENOENT;
1952 goto out;
1953 }
1954
2f536801 1955 s->is_snapshot = true;
33b1db1c 1956
7267c094
AL
1957 g_free(buf);
1958 g_free(old_s);
33b1db1c
MK
1959
1960 return 0;
1961out:
1962 /* recover bdrv_sd_state */
1963 memcpy(s, old_s, sizeof(BDRVSheepdogState));
7267c094
AL
1964 g_free(buf);
1965 g_free(old_s);
33b1db1c 1966
6daf194d 1967 error_report("failed to open. recover old bdrv_sd_state.");
33b1db1c
MK
1968
1969 return ret;
1970}
1971
1972static int sd_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
1973{
1974 /* FIXME: Delete specified snapshot id. */
1975 return 0;
1976}
1977
33b1db1c
MK
1978static int sd_snapshot_list(BlockDriverState *bs, QEMUSnapshotInfo **psn_tab)
1979{
1980 BDRVSheepdogState *s = bs->opaque;
1981 SheepdogReq req;
1982 int fd, nr = 1024, ret, max = BITS_TO_LONGS(SD_NR_VDIS) * sizeof(long);
1983 QEMUSnapshotInfo *sn_tab = NULL;
1984 unsigned wlen, rlen;
1985 int found = 0;
1986 static SheepdogInode inode;
1987 unsigned long *vdi_inuse;
1988 unsigned int start_nr;
1989 uint64_t hval;
1990 uint32_t vid;
1991
7267c094 1992 vdi_inuse = g_malloc(max);
33b1db1c 1993
25af257d 1994 fd = connect_to_sdog(s);
33b1db1c 1995 if (fd < 0) {
cb595887 1996 ret = fd;
33b1db1c
MK
1997 goto out;
1998 }
1999
2000 rlen = max;
2001 wlen = 0;
2002
2003 memset(&req, 0, sizeof(req));
2004
2005 req.opcode = SD_OP_READ_VDIS;
2006 req.data_length = max;
2007
2008 ret = do_req(fd, (SheepdogReq *)&req, vdi_inuse, &wlen, &rlen);
2009
2010 closesocket(fd);
2011 if (ret) {
2012 goto out;
2013 }
2014
7267c094 2015 sn_tab = g_malloc0(nr * sizeof(*sn_tab));
33b1db1c
MK
2016
2017 /* calculate a vdi id with hash function */
2018 hval = fnv_64a_buf(s->name, strlen(s->name), FNV1A_64_INIT);
2019 start_nr = hval & (SD_NR_VDIS - 1);
2020
25af257d 2021 fd = connect_to_sdog(s);
33b1db1c 2022 if (fd < 0) {
cb595887 2023 ret = fd;
33b1db1c
MK
2024 goto out;
2025 }
2026
2027 for (vid = start_nr; found < nr; vid = (vid + 1) % SD_NR_VDIS) {
2028 if (!test_bit(vid, vdi_inuse)) {
2029 break;
2030 }
2031
2032 /* we don't need to read entire object */
2033 ret = read_object(fd, (char *)&inode, vid_to_vdi_oid(vid),
47622c44 2034 0, SD_INODE_SIZE - sizeof(inode.data_vdi_id), 0,
0e7106d8 2035 s->cache_flags);
33b1db1c
MK
2036
2037 if (ret) {
2038 continue;
2039 }
2040
2041 if (!strcmp(inode.name, s->name) && is_snapshot(&inode)) {
2042 sn_tab[found].date_sec = inode.snap_ctime >> 32;
2043 sn_tab[found].date_nsec = inode.snap_ctime & 0xffffffff;
2044 sn_tab[found].vm_state_size = inode.vm_state_size;
2045 sn_tab[found].vm_clock_nsec = inode.vm_clock_nsec;
2046
2047 snprintf(sn_tab[found].id_str, sizeof(sn_tab[found].id_str), "%u",
2048 inode.snap_id);
3178e275
JM
2049 pstrcpy(sn_tab[found].name,
2050 MIN(sizeof(sn_tab[found].name), sizeof(inode.tag)),
2051 inode.tag);
33b1db1c
MK
2052 found++;
2053 }
2054 }
2055
2056 closesocket(fd);
2057out:
2058 *psn_tab = sn_tab;
2059
7267c094 2060 g_free(vdi_inuse);
33b1db1c 2061
cb595887
MK
2062 if (ret < 0) {
2063 return ret;
2064 }
2065
33b1db1c
MK
2066 return found;
2067}
2068
2069static int do_load_save_vmstate(BDRVSheepdogState *s, uint8_t *data,
2070 int64_t pos, int size, int load)
2071{
2f536801
MK
2072 bool create;
2073 int fd, ret = 0, remaining = size;
33b1db1c
MK
2074 unsigned int data_len;
2075 uint64_t vmstate_oid;
2076 uint32_t vdi_index;
2077 uint64_t offset;
2078
25af257d 2079 fd = connect_to_sdog(s);
33b1db1c 2080 if (fd < 0) {
cb595887 2081 return fd;
33b1db1c
MK
2082 }
2083
6f3c714e 2084 while (remaining) {
33b1db1c
MK
2085 vdi_index = pos / SD_DATA_OBJ_SIZE;
2086 offset = pos % SD_DATA_OBJ_SIZE;
2087
1f7a48de 2088 data_len = MIN(remaining, SD_DATA_OBJ_SIZE - offset);
33b1db1c
MK
2089
2090 vmstate_oid = vid_to_vmstate_oid(s->inode.vdi_id, vdi_index);
2091
2092 create = (offset == 0);
2093 if (load) {
2094 ret = read_object(fd, (char *)data, vmstate_oid,
47622c44 2095 s->inode.nr_copies, data_len, offset,
0e7106d8 2096 s->cache_flags);
33b1db1c
MK
2097 } else {
2098 ret = write_object(fd, (char *)data, vmstate_oid,
47622c44 2099 s->inode.nr_copies, data_len, offset, create,
0e7106d8 2100 s->cache_flags);
33b1db1c
MK
2101 }
2102
2103 if (ret < 0) {
6daf194d 2104 error_report("failed to save vmstate %s", strerror(errno));
33b1db1c
MK
2105 goto cleanup;
2106 }
2107
2108 pos += data_len;
1f7a48de 2109 data += data_len;
6f3c714e 2110 remaining -= data_len;
33b1db1c 2111 }
6f3c714e 2112 ret = size;
33b1db1c
MK
2113cleanup:
2114 closesocket(fd);
2115 return ret;
2116}
2117
cf8074b3
KW
2118static int sd_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2119 int64_t pos)
33b1db1c
MK
2120{
2121 BDRVSheepdogState *s = bs->opaque;
cf8074b3
KW
2122 void *buf;
2123 int ret;
33b1db1c 2124
cf8074b3
KW
2125 buf = qemu_blockalign(bs, qiov->size);
2126 qemu_iovec_to_buf(qiov, 0, buf, qiov->size);
2127 ret = do_load_save_vmstate(s, (uint8_t *) buf, pos, qiov->size, 0);
2128 qemu_vfree(buf);
2129
2130 return ret;
33b1db1c
MK
2131}
2132
2133static int sd_load_vmstate(BlockDriverState *bs, uint8_t *data,
2134 int64_t pos, int size)
2135{
2136 BDRVSheepdogState *s = bs->opaque;
2137
2138 return do_load_save_vmstate(s, data, pos, size, 1);
2139}
2140
2141
cac8f4a6
LY
2142static coroutine_fn int sd_co_discard(BlockDriverState *bs, int64_t sector_num,
2143 int nb_sectors)
2144{
2145 SheepdogAIOCB *acb;
2146 QEMUIOVector dummy;
2147 BDRVSheepdogState *s = bs->opaque;
2148 int ret;
2149
2150 if (!s->discard_supported) {
2151 return 0;
2152 }
2153
2154 acb = sd_aio_setup(bs, &dummy, sector_num, nb_sectors);
2155 acb->aiocb_type = AIOCB_DISCARD_OBJ;
2156 acb->aio_done_func = sd_finish_aiocb;
2157
2158 ret = sd_co_rw_vector(acb);
2159 if (ret <= 0) {
2160 qemu_aio_release(acb);
2161 return ret;
2162 }
2163
2164 qemu_coroutine_yield();
2165
2166 return acb->ret;
2167}
2168
8d71c631
LY
2169static coroutine_fn int
2170sd_co_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
2171 int *pnum)
2172{
2173 BDRVSheepdogState *s = bs->opaque;
2174 SheepdogInode *inode = &s->inode;
2175 unsigned long start = sector_num * BDRV_SECTOR_SIZE / SD_DATA_OBJ_SIZE,
2176 end = DIV_ROUND_UP((sector_num + nb_sectors) *
2177 BDRV_SECTOR_SIZE, SD_DATA_OBJ_SIZE);
2178 unsigned long idx;
2179 int ret = 1;
2180
2181 for (idx = start; idx < end; idx++) {
2182 if (inode->data_vdi_id[idx] == 0) {
2183 break;
2184 }
2185 }
2186 if (idx == start) {
2187 /* Get the longest length of unallocated sectors */
2188 ret = 0;
2189 for (idx = start + 1; idx < end; idx++) {
2190 if (inode->data_vdi_id[idx] != 0) {
2191 break;
2192 }
2193 }
2194 }
2195
2196 *pnum = (idx - start) * SD_DATA_OBJ_SIZE / BDRV_SECTOR_SIZE;
2197 if (*pnum > nb_sectors) {
2198 *pnum = nb_sectors;
2199 }
2200 return ret;
2201}
2202
33b1db1c
MK
2203static QEMUOptionParameter sd_create_options[] = {
2204 {
2205 .name = BLOCK_OPT_SIZE,
2206 .type = OPT_SIZE,
2207 .help = "Virtual disk size"
2208 },
2209 {
2210 .name = BLOCK_OPT_BACKING_FILE,
2211 .type = OPT_STRING,
2212 .help = "File name of a base image"
2213 },
a8e0fdd7
MK
2214 {
2215 .name = BLOCK_OPT_PREALLOC,
2216 .type = OPT_STRING,
2217 .help = "Preallocation mode (allowed values: off, full)"
2218 },
33b1db1c
MK
2219 { NULL }
2220};
2221
5d6768e3 2222static BlockDriver bdrv_sheepdog = {
33b1db1c
MK
2223 .format_name = "sheepdog",
2224 .protocol_name = "sheepdog",
2225 .instance_size = sizeof(BDRVSheepdogState),
2226 .bdrv_file_open = sd_open,
2227 .bdrv_close = sd_close,
2228 .bdrv_create = sd_create,
2229 .bdrv_getlength = sd_getlength,
2230 .bdrv_truncate = sd_truncate,
2231
2df46246
MK
2232 .bdrv_co_readv = sd_co_readv,
2233 .bdrv_co_writev = sd_co_writev,
47622c44 2234 .bdrv_co_flush_to_disk = sd_co_flush_to_disk,
cac8f4a6 2235 .bdrv_co_discard = sd_co_discard,
8d71c631 2236 .bdrv_co_is_allocated = sd_co_is_allocated,
33b1db1c
MK
2237
2238 .bdrv_snapshot_create = sd_snapshot_create,
2239 .bdrv_snapshot_goto = sd_snapshot_goto,
2240 .bdrv_snapshot_delete = sd_snapshot_delete,
2241 .bdrv_snapshot_list = sd_snapshot_list,
2242
2243 .bdrv_save_vmstate = sd_save_vmstate,
2244 .bdrv_load_vmstate = sd_load_vmstate,
2245
2246 .create_options = sd_create_options,
2247};
2248
5d6768e3
MK
2249static BlockDriver bdrv_sheepdog_tcp = {
2250 .format_name = "sheepdog",
2251 .protocol_name = "sheepdog+tcp",
2252 .instance_size = sizeof(BDRVSheepdogState),
2253 .bdrv_file_open = sd_open,
2254 .bdrv_close = sd_close,
2255 .bdrv_create = sd_create,
2256 .bdrv_getlength = sd_getlength,
2257 .bdrv_truncate = sd_truncate,
2258
2259 .bdrv_co_readv = sd_co_readv,
2260 .bdrv_co_writev = sd_co_writev,
2261 .bdrv_co_flush_to_disk = sd_co_flush_to_disk,
cac8f4a6 2262 .bdrv_co_discard = sd_co_discard,
8d71c631 2263 .bdrv_co_is_allocated = sd_co_is_allocated,
5d6768e3
MK
2264
2265 .bdrv_snapshot_create = sd_snapshot_create,
2266 .bdrv_snapshot_goto = sd_snapshot_goto,
2267 .bdrv_snapshot_delete = sd_snapshot_delete,
2268 .bdrv_snapshot_list = sd_snapshot_list,
2269
2270 .bdrv_save_vmstate = sd_save_vmstate,
2271 .bdrv_load_vmstate = sd_load_vmstate,
2272
2273 .create_options = sd_create_options,
2274};
2275
1b8bbb46
MK
2276static BlockDriver bdrv_sheepdog_unix = {
2277 .format_name = "sheepdog",
2278 .protocol_name = "sheepdog+unix",
2279 .instance_size = sizeof(BDRVSheepdogState),
2280 .bdrv_file_open = sd_open,
2281 .bdrv_close = sd_close,
2282 .bdrv_create = sd_create,
2283 .bdrv_getlength = sd_getlength,
2284 .bdrv_truncate = sd_truncate,
2285
2286 .bdrv_co_readv = sd_co_readv,
2287 .bdrv_co_writev = sd_co_writev,
2288 .bdrv_co_flush_to_disk = sd_co_flush_to_disk,
cac8f4a6 2289 .bdrv_co_discard = sd_co_discard,
8d71c631 2290 .bdrv_co_is_allocated = sd_co_is_allocated,
1b8bbb46
MK
2291
2292 .bdrv_snapshot_create = sd_snapshot_create,
2293 .bdrv_snapshot_goto = sd_snapshot_goto,
2294 .bdrv_snapshot_delete = sd_snapshot_delete,
2295 .bdrv_snapshot_list = sd_snapshot_list,
2296
2297 .bdrv_save_vmstate = sd_save_vmstate,
2298 .bdrv_load_vmstate = sd_load_vmstate,
2299
2300 .create_options = sd_create_options,
2301};
2302
33b1db1c
MK
2303static void bdrv_sheepdog_init(void)
2304{
2305 bdrv_register(&bdrv_sheepdog);
5d6768e3 2306 bdrv_register(&bdrv_sheepdog_tcp);
1b8bbb46 2307 bdrv_register(&bdrv_sheepdog_unix);
33b1db1c
MK
2308}
2309block_init(bdrv_sheepdog_init);