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