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