virtio-ccw: Wire up virtio-rng.
[qemu.git] / block / sheepdog.c
blobc711c286139c6a2d70b51f7746b2b4112e9c7088
1 /*
2 * Copyright (C) 2009-2010 Nippon Telegraph and Telephone Corporation.
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.
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/>.
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.
15 #include "qemu-common.h"
16 #include "qemu/uri.h"
17 #include "qemu/error-report.h"
18 #include "qemu/sockets.h"
19 #include "block/block_int.h"
20 #include "qemu/bitops.h"
22 #define SD_PROTO_VER 0x01
24 #define SD_DEFAULT_ADDR "localhost"
25 #define SD_DEFAULT_PORT 7000
27 #define SD_OP_CREATE_AND_WRITE_OBJ 0x01
28 #define SD_OP_READ_OBJ 0x02
29 #define SD_OP_WRITE_OBJ 0x03
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
36 #define SD_OP_FLUSH_VDI 0x16
38 #define SD_FLAG_CMD_WRITE 0x01
39 #define SD_FLAG_CMD_COW 0x02
40 #define SD_FLAG_CMD_CACHE 0x04 /* Writeback mode for cache */
41 #define SD_FLAG_CMD_DIRECT 0x08 /* Don't use cache */
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 */
70 * Object ID rules
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
76 * 60 - 63 ( 4 bits): object type identifier space
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
91 #define SD_INODE_SIZE (sizeof(SheepdogInode))
92 #define CURRENT_VDI_ID 0
94 typedef 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;
104 typedef 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;
115 typedef 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;
129 typedef 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;
141 typedef 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;
149 uint32_t vdi_id;
150 uint32_t copies;
151 uint32_t snapid;
152 uint32_t pad[3];
153 } SheepdogVdiReq;
155 typedef 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;
168 typedef 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;
187 * 64 bit FNV-1a non-zero initial basis
189 #define FNV1A_64_INIT ((uint64_t)0xcbf29ce484222325ULL)
192 * 64 bit Fowler/Noll/Vo FNV-1a hash code
194 static inline uint64_t fnv_64a_buf(void *buf, size_t len, uint64_t hval)
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);
203 return hval;
206 static inline bool is_data_obj_writable(SheepdogInode *inode, unsigned int idx)
208 return inode->vdi_id == inode->data_vdi_id[idx];
211 static inline bool is_data_obj(uint64_t oid)
213 return !(VDI_BIT & oid);
216 static inline uint64_t data_oid_to_idx(uint64_t oid)
218 return oid & (MAX_DATA_OBJS - 1);
221 static inline uint64_t vid_to_vdi_oid(uint32_t vid)
223 return VDI_BIT | ((uint64_t)vid << VDI_SPACE_SHIFT);
226 static inline uint64_t vid_to_vmstate_oid(uint32_t vid, uint32_t idx)
228 return VMSTATE_BIT | ((uint64_t)vid << VDI_SPACE_SHIFT) | idx;
231 static inline uint64_t vid_to_data_oid(uint32_t vid, uint32_t idx)
233 return ((uint64_t)vid << VDI_SPACE_SHIFT) | idx;
236 static inline bool is_snapshot(struct SheepdogInode *inode)
238 return !!inode->snap_ctime;
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
251 typedef struct SheepdogAIOCB SheepdogAIOCB;
253 typedef struct AIOReq {
254 SheepdogAIOCB *aiocb;
255 unsigned int iov_offset;
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;
264 QLIST_ENTRY(AIOReq) aio_siblings;
265 } AIOReq;
267 enum AIOCBState {
268 AIOCB_WRITE_UDATA,
269 AIOCB_READ_UDATA,
270 AIOCB_FLUSH_CACHE,
273 struct SheepdogAIOCB {
274 BlockDriverAIOCB common;
276 QEMUIOVector *qiov;
278 int64_t sector_num;
279 int nb_sectors;
281 int ret;
282 enum AIOCBState aiocb_type;
284 Coroutine *coroutine;
285 void (*aio_done_func)(SheepdogAIOCB *);
287 bool canceled;
288 int nr_pending;
291 typedef struct BDRVSheepdogState {
292 SheepdogInode inode;
294 uint32_t min_dirty_data_idx;
295 uint32_t max_dirty_data_idx;
297 char name[SD_MAX_VDI_LEN];
298 bool is_snapshot;
299 uint32_t cache_flags;
301 char *host_spec;
302 bool is_unix;
303 int fd;
305 CoMutex lock;
306 Coroutine *co_send;
307 Coroutine *co_recv;
309 uint32_t aioreq_seq_num;
310 QLIST_HEAD(inflight_aio_head, AIOReq) inflight_aio_head;
311 QLIST_HEAD(pending_aio_head, AIOReq) pending_aio_head;
312 } BDRVSheepdogState;
314 static const char * sd_strerror(int err)
316 int i;
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"},
349 for (i = 0; i < ARRAY_SIZE(errors); ++i) {
350 if (errors[i].err == err) {
351 return errors[i].desc;
355 return "Invalid error code";
359 * Sheepdog I/O handling:
361 * 1. In sd_co_rw_vector, we send the I/O requests to the server and
362 * link the requests to the inflight_list in the
363 * BDRVSheepdogState. The function exits without waiting for
364 * receiving the response.
366 * 2. We receive the response in aio_read_response, the fd handler to
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
369 * completion function. We switch back to sd_co_readv/writev after
370 * all the requests belonging to the AIOCB are finished.
373 static 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)
378 AIOReq *aio_req;
380 aio_req = g_malloc(sizeof(*aio_req));
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++;
390 acb->nr_pending++;
391 return aio_req;
394 static inline void free_aio_req(BDRVSheepdogState *s, AIOReq *aio_req)
396 SheepdogAIOCB *acb = aio_req->aiocb;
398 QLIST_REMOVE(aio_req, aio_siblings);
399 g_free(aio_req);
401 acb->nr_pending--;
404 static void coroutine_fn sd_finish_aiocb(SheepdogAIOCB *acb)
406 if (!acb->canceled) {
407 qemu_coroutine_enter(acb->coroutine, NULL);
409 qemu_aio_release(acb);
412 static void sd_aio_cancel(BlockDriverAIOCB *blockacb)
414 SheepdogAIOCB *acb = (SheepdogAIOCB *)blockacb;
417 * Sheepdog cannot cancel the requests which are already sent to
418 * the servers, so we just complete the request with -EIO here.
420 acb->ret = -EIO;
421 qemu_coroutine_enter(acb->coroutine, NULL);
422 acb->canceled = true;
425 static const AIOCBInfo sd_aiocb_info = {
426 .aiocb_size = sizeof(SheepdogAIOCB),
427 .cancel = sd_aio_cancel,
430 static SheepdogAIOCB *sd_aio_setup(BlockDriverState *bs, QEMUIOVector *qiov,
431 int64_t sector_num, int nb_sectors)
433 SheepdogAIOCB *acb;
435 acb = qemu_aio_get(&sd_aiocb_info, bs, NULL, NULL);
437 acb->qiov = qiov;
439 acb->sector_num = sector_num;
440 acb->nb_sectors = nb_sectors;
442 acb->aio_done_func = NULL;
443 acb->canceled = false;
444 acb->coroutine = qemu_coroutine_self();
445 acb->ret = 0;
446 acb->nr_pending = 0;
447 return acb;
450 static int connect_to_sdog(BDRVSheepdogState *s)
452 int fd;
453 Error *err = NULL;
455 if (s->is_unix) {
456 fd = unix_connect(s->host_spec, &err);
457 } else {
458 fd = inet_connect(s->host_spec, &err);
460 if (err == NULL) {
461 int ret = socket_set_nodelay(fd);
462 if (ret < 0) {
463 error_report("%s", strerror(errno));
468 if (err != NULL) {
469 qerror_report_err(err);
470 error_free(err);
473 return fd;
476 static coroutine_fn int send_co_req(int sockfd, SheepdogReq *hdr, void *data,
477 unsigned int *wlen)
479 int ret;
481 ret = qemu_co_send(sockfd, hdr, sizeof(*hdr));
482 if (ret < sizeof(*hdr)) {
483 error_report("failed to send a req, %s", strerror(errno));
484 return ret;
487 ret = qemu_co_send(sockfd, data, *wlen);
488 if (ret < *wlen) {
489 error_report("failed to send a req, %s", strerror(errno));
492 return ret;
495 static void restart_co_req(void *opaque)
497 Coroutine *co = opaque;
499 qemu_coroutine_enter(co, NULL);
502 typedef struct SheepdogReqCo {
503 int sockfd;
504 SheepdogReq *hdr;
505 void *data;
506 unsigned int *wlen;
507 unsigned int *rlen;
508 int ret;
509 bool finished;
510 } SheepdogReqCo;
512 static coroutine_fn void do_co_req(void *opaque)
514 int ret;
515 Coroutine *co;
516 SheepdogReqCo *srco = opaque;
517 int sockfd = srco->sockfd;
518 SheepdogReq *hdr = srco->hdr;
519 void *data = srco->data;
520 unsigned int *wlen = srco->wlen;
521 unsigned int *rlen = srco->rlen;
523 co = qemu_coroutine_self();
524 qemu_aio_set_fd_handler(sockfd, NULL, restart_co_req, NULL, co);
526 socket_set_block(sockfd);
527 ret = send_co_req(sockfd, hdr, data, wlen);
528 if (ret < 0) {
529 goto out;
532 qemu_aio_set_fd_handler(sockfd, restart_co_req, NULL, NULL, co);
534 ret = qemu_co_recv(sockfd, hdr, sizeof(*hdr));
535 if (ret < sizeof(*hdr)) {
536 error_report("failed to get a rsp, %s", strerror(errno));
537 ret = -errno;
538 goto out;
541 if (*rlen > hdr->data_length) {
542 *rlen = hdr->data_length;
545 if (*rlen) {
546 ret = qemu_co_recv(sockfd, data, *rlen);
547 if (ret < *rlen) {
548 error_report("failed to get the data, %s", strerror(errno));
549 ret = -errno;
550 goto out;
553 ret = 0;
554 out:
555 qemu_aio_set_fd_handler(sockfd, NULL, NULL, NULL, NULL);
556 socket_set_nonblock(sockfd);
558 srco->ret = ret;
559 srco->finished = true;
562 static int do_req(int sockfd, SheepdogReq *hdr, void *data,
563 unsigned int *wlen, unsigned int *rlen)
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,
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();
586 return srco.ret;
589 static int coroutine_fn add_aio_request(BDRVSheepdogState *s, AIOReq *aio_req,
590 struct iovec *iov, int niov, bool create,
591 enum AIOCBState aiocb_type);
594 static AIOReq *find_pending_req(BDRVSheepdogState *s, uint64_t oid)
596 AIOReq *aio_req;
598 QLIST_FOREACH(aio_req, &s->pending_aio_head, aio_siblings) {
599 if (aio_req->oid == oid) {
600 return aio_req;
604 return NULL;
608 * This function searchs pending requests to the object `oid', and
609 * sends them.
611 static void coroutine_fn send_pending_req(BDRVSheepdogState *s, uint64_t oid)
613 AIOReq *aio_req;
614 SheepdogAIOCB *acb;
615 int ret;
617 while ((aio_req = find_pending_req(s, oid)) != NULL) {
618 acb = aio_req->aiocb;
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);
622 ret = add_aio_request(s, aio_req, acb->qiov->iov,
623 acb->qiov->niov, false, acb->aiocb_type);
624 if (ret < 0) {
625 error_report("add_aio_request is failed");
626 free_aio_req(s, aio_req);
627 if (!acb->nr_pending) {
628 sd_finish_aiocb(acb);
635 * Receive responses of the I/O requests.
637 * This function is registered as a fd handler, and called from the
638 * main loop when s->fd is ready for reading responses.
640 static void coroutine_fn aio_read_response(void *opaque)
642 SheepdogObjRsp rsp;
643 BDRVSheepdogState *s = opaque;
644 int fd = s->fd;
645 int ret;
646 AIOReq *aio_req = NULL;
647 SheepdogAIOCB *acb;
648 unsigned long idx;
650 if (QLIST_EMPTY(&s->inflight_aio_head)) {
651 goto out;
654 /* read a header */
655 ret = qemu_co_recv(fd, &rsp, sizeof(rsp));
656 if (ret < 0) {
657 error_report("failed to get the header, %s", strerror(errno));
658 goto out;
661 /* find the right aio_req from the inflight aio list */
662 QLIST_FOREACH(aio_req, &s->inflight_aio_head, aio_siblings) {
663 if (aio_req->id == rsp.id) {
664 break;
667 if (!aio_req) {
668 error_report("cannot find aio_req %x", rsp.id);
669 goto out;
672 acb = aio_req->aiocb;
674 switch (acb->aiocb_type) {
675 case AIOCB_WRITE_UDATA:
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;
679 if (!is_data_obj(aio_req->oid)) {
680 break;
682 idx = data_oid_to_idx(aio_req->oid);
684 if (s->inode.data_vdi_id[idx] != s->inode.vdi_id) {
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.
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);
697 * Some requests may be blocked because simultaneous
698 * create requests are not allowed, so we search the
699 * pending requests here.
701 send_pending_req(s, aio_req->oid);
703 break;
704 case AIOCB_READ_UDATA:
705 ret = qemu_co_recvv(fd, acb->qiov->iov, acb->qiov->niov,
706 aio_req->iov_offset, rsp.data_length);
707 if (ret < 0) {
708 error_report("failed to get the data, %s", strerror(errno));
709 goto out;
711 break;
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;
718 break;
721 if (rsp.result != SD_RES_SUCCESS) {
722 acb->ret = -EIO;
723 error_report("%s", sd_strerror(rsp.result));
726 free_aio_req(s, aio_req);
727 if (!acb->nr_pending) {
729 * We've finished all requests which belong to the AIOCB, so
730 * we can switch back to sd_co_readv/writev now.
732 acb->aio_done_func(acb);
734 out:
735 s->co_recv = NULL;
738 static void co_read_response(void *opaque)
740 BDRVSheepdogState *s = opaque;
742 if (!s->co_recv) {
743 s->co_recv = qemu_coroutine_create(aio_read_response);
746 qemu_coroutine_enter(s->co_recv, opaque);
749 static void co_write_request(void *opaque)
751 BDRVSheepdogState *s = opaque;
753 qemu_coroutine_enter(s->co_send, NULL);
756 static int aio_flush_request(void *opaque)
758 BDRVSheepdogState *s = opaque;
760 return !QLIST_EMPTY(&s->inflight_aio_head) ||
761 !QLIST_EMPTY(&s->pending_aio_head);
765 * Return a socket discriptor to read/write objects.
767 * We cannot use this discriptor for other operations because
768 * the block driver may be on waiting response from the server.
770 static int get_sheep_fd(BDRVSheepdogState *s)
772 int fd;
774 fd = connect_to_sdog(s);
775 if (fd < 0) {
776 return fd;
779 socket_set_nonblock(fd);
781 qemu_aio_set_fd_handler(fd, co_read_response, NULL, aio_flush_request, s);
782 return fd;
785 static int sd_parse_uri(BDRVSheepdogState *s, const char *filename,
786 char *vdi, uint32_t *snapid, char *tag)
788 URI *uri;
789 QueryParams *qp = NULL;
790 int ret = 0;
792 uri = uri_parse(filename);
793 if (!uri) {
794 return -EINVAL;
797 /* transport */
798 if (!strcmp(uri->scheme, "sheepdog")) {
799 s->is_unix = false;
800 } else if (!strcmp(uri->scheme, "sheepdog+tcp")) {
801 s->is_unix = false;
802 } else if (!strcmp(uri->scheme, "sheepdog+unix")) {
803 s->is_unix = true;
804 } else {
805 ret = -EINVAL;
806 goto out;
809 if (uri->path == NULL || !strcmp(uri->path, "/")) {
810 ret = -EINVAL;
811 goto out;
813 pstrcpy(vdi, SD_MAX_VDI_LEN, uri->path + 1);
815 qp = query_params_parse(uri->query);
816 if (qp->n > 1 || (s->is_unix && !qp->n) || (!s->is_unix && qp->n)) {
817 ret = -EINVAL;
818 goto out;
821 if (s->is_unix) {
822 /* sheepdog+unix:///vdiname?socket=path */
823 if (uri->server || uri->port || strcmp(qp->p[0].name, "socket")) {
824 ret = -EINVAL;
825 goto out;
827 s->host_spec = g_strdup(qp->p[0].value);
828 } else {
829 /* sheepdog[+tcp]://[host:port]/vdiname */
830 s->host_spec = g_strdup_printf("%s:%d", uri->server ?: SD_DEFAULT_ADDR,
831 uri->port ?: SD_DEFAULT_PORT);
834 /* snapshot tag */
835 if (uri->fragment) {
836 *snapid = strtoul(uri->fragment, NULL, 10);
837 if (*snapid == 0) {
838 pstrcpy(tag, SD_MAX_VDI_TAG_LEN, uri->fragment);
840 } else {
841 *snapid = CURRENT_VDI_ID; /* search current vdi */
844 out:
845 if (qp) {
846 query_params_free(qp);
848 uri_free(uri);
849 return ret;
853 * Parse a filename (old syntax)
855 * filename must be one of the following formats:
856 * 1. [vdiname]
857 * 2. [vdiname]:[snapid]
858 * 3. [vdiname]:[tag]
859 * 4. [hostname]:[port]:[vdiname]
860 * 5. [hostname]:[port]:[vdiname]:[snapid]
861 * 6. [hostname]:[port]:[vdiname]:[tag]
863 * You can boot from the snapshot images by specifying `snapid` or
864 * `tag'.
866 * You can run VMs outside the Sheepdog cluster by specifying
867 * `hostname' and `port' (experimental).
869 static int parse_vdiname(BDRVSheepdogState *s, const char *filename,
870 char *vdi, uint32_t *snapid, char *tag)
872 char *p, *q, *uri;
873 const char *host_spec, *vdi_spec;
874 int nr_sep, ret;
876 strstart(filename, "sheepdog:", (const char **)&filename);
877 p = q = g_strdup(filename);
879 /* count the number of separators */
880 nr_sep = 0;
881 while (*p) {
882 if (*p == ':') {
883 nr_sep++;
885 p++;
887 p = q;
889 /* use the first two tokens as host_spec. */
890 if (nr_sep >= 2) {
891 host_spec = p;
892 p = strchr(p, ':');
893 p++;
894 p = strchr(p, ':');
895 *p++ = '\0';
896 } else {
897 host_spec = "";
900 vdi_spec = p;
902 p = strchr(vdi_spec, ':');
903 if (p) {
904 *p++ = '#';
907 uri = g_strdup_printf("sheepdog://%s/%s", host_spec, vdi_spec);
909 ret = sd_parse_uri(s, uri, vdi, snapid, tag);
911 g_free(q);
912 g_free(uri);
914 return ret;
917 static int find_vdi_name(BDRVSheepdogState *s, char *filename, uint32_t snapid,
918 char *tag, uint32_t *vid, int for_snapshot)
920 int ret, fd;
921 SheepdogVdiReq hdr;
922 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
923 unsigned int wlen, rlen = 0;
924 char buf[SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN];
926 fd = connect_to_sdog(s);
927 if (fd < 0) {
928 return fd;
931 /* This pair of strncpy calls ensures that the buffer is zero-filled,
932 * which is desirable since we'll soon be sending those bytes, and
933 * don't want the send_req to read uninitialized data.
935 strncpy(buf, filename, SD_MAX_VDI_LEN);
936 strncpy(buf + SD_MAX_VDI_LEN, tag, SD_MAX_VDI_TAG_LEN);
938 memset(&hdr, 0, sizeof(hdr));
939 if (for_snapshot) {
940 hdr.opcode = SD_OP_GET_VDI_INFO;
941 } else {
942 hdr.opcode = SD_OP_LOCK_VDI;
944 wlen = SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN;
945 hdr.proto_ver = SD_PROTO_VER;
946 hdr.data_length = wlen;
947 hdr.snapid = snapid;
948 hdr.flags = SD_FLAG_CMD_WRITE;
950 ret = do_req(fd, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
951 if (ret) {
952 goto out;
955 if (rsp->result != SD_RES_SUCCESS) {
956 error_report("cannot get vdi info, %s, %s %d %s",
957 sd_strerror(rsp->result), filename, snapid, tag);
958 if (rsp->result == SD_RES_NO_VDI) {
959 ret = -ENOENT;
960 } else {
961 ret = -EIO;
963 goto out;
965 *vid = rsp->vdi_id;
967 ret = 0;
968 out:
969 closesocket(fd);
970 return ret;
973 static int coroutine_fn add_aio_request(BDRVSheepdogState *s, AIOReq *aio_req,
974 struct iovec *iov, int niov, bool create,
975 enum AIOCBState aiocb_type)
977 int nr_copies = s->inode.nr_copies;
978 SheepdogObjReq hdr;
979 unsigned int wlen = 0;
980 int ret;
981 uint64_t oid = aio_req->oid;
982 unsigned int datalen = aio_req->data_len;
983 uint64_t offset = aio_req->offset;
984 uint8_t flags = aio_req->flags;
985 uint64_t old_oid = aio_req->base_oid;
987 if (!nr_copies) {
988 error_report("bug");
991 memset(&hdr, 0, sizeof(hdr));
993 switch (aiocb_type) {
994 case AIOCB_FLUSH_CACHE:
995 hdr.opcode = SD_OP_FLUSH_VDI;
996 break;
997 case AIOCB_READ_UDATA:
998 hdr.opcode = SD_OP_READ_OBJ;
999 hdr.flags = flags;
1000 break;
1001 case AIOCB_WRITE_UDATA:
1002 if (create) {
1003 hdr.opcode = SD_OP_CREATE_AND_WRITE_OBJ;
1004 } else {
1005 hdr.opcode = SD_OP_WRITE_OBJ;
1007 wlen = datalen;
1008 hdr.flags = SD_FLAG_CMD_WRITE | flags;
1009 break;
1012 if (s->cache_flags) {
1013 hdr.flags |= s->cache_flags;
1016 hdr.oid = oid;
1017 hdr.cow_oid = old_oid;
1018 hdr.copies = s->inode.nr_copies;
1020 hdr.data_length = datalen;
1021 hdr.offset = offset;
1023 hdr.id = aio_req->id;
1025 qemu_co_mutex_lock(&s->lock);
1026 s->co_send = qemu_coroutine_self();
1027 qemu_aio_set_fd_handler(s->fd, co_read_response, co_write_request,
1028 aio_flush_request, s);
1029 socket_set_cork(s->fd, 1);
1031 /* send a header */
1032 ret = qemu_co_send(s->fd, &hdr, sizeof(hdr));
1033 if (ret < 0) {
1034 qemu_co_mutex_unlock(&s->lock);
1035 error_report("failed to send a req, %s", strerror(errno));
1036 return -errno;
1039 if (wlen) {
1040 ret = qemu_co_sendv(s->fd, iov, niov, aio_req->iov_offset, wlen);
1041 if (ret < 0) {
1042 qemu_co_mutex_unlock(&s->lock);
1043 error_report("failed to send a data, %s", strerror(errno));
1044 return -errno;
1048 socket_set_cork(s->fd, 0);
1049 qemu_aio_set_fd_handler(s->fd, co_read_response, NULL,
1050 aio_flush_request, s);
1051 qemu_co_mutex_unlock(&s->lock);
1053 return 0;
1056 static int read_write_object(int fd, char *buf, uint64_t oid, int copies,
1057 unsigned int datalen, uint64_t offset,
1058 bool write, bool create, uint32_t cache_flags)
1060 SheepdogObjReq hdr;
1061 SheepdogObjRsp *rsp = (SheepdogObjRsp *)&hdr;
1062 unsigned int wlen, rlen;
1063 int ret;
1065 memset(&hdr, 0, sizeof(hdr));
1067 if (write) {
1068 wlen = datalen;
1069 rlen = 0;
1070 hdr.flags = SD_FLAG_CMD_WRITE;
1071 if (create) {
1072 hdr.opcode = SD_OP_CREATE_AND_WRITE_OBJ;
1073 } else {
1074 hdr.opcode = SD_OP_WRITE_OBJ;
1076 } else {
1077 wlen = 0;
1078 rlen = datalen;
1079 hdr.opcode = SD_OP_READ_OBJ;
1082 hdr.flags |= cache_flags;
1084 hdr.oid = oid;
1085 hdr.data_length = datalen;
1086 hdr.offset = offset;
1087 hdr.copies = copies;
1089 ret = do_req(fd, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
1090 if (ret) {
1091 error_report("failed to send a request to the sheep");
1092 return ret;
1095 switch (rsp->result) {
1096 case SD_RES_SUCCESS:
1097 return 0;
1098 default:
1099 error_report("%s", sd_strerror(rsp->result));
1100 return -EIO;
1104 static int read_object(int fd, char *buf, uint64_t oid, int copies,
1105 unsigned int datalen, uint64_t offset,
1106 uint32_t cache_flags)
1108 return read_write_object(fd, buf, oid, copies, datalen, offset, false,
1109 false, cache_flags);
1112 static int write_object(int fd, char *buf, uint64_t oid, int copies,
1113 unsigned int datalen, uint64_t offset, bool create,
1114 uint32_t cache_flags)
1116 return read_write_object(fd, buf, oid, copies, datalen, offset, true,
1117 create, cache_flags);
1120 static int sd_open(BlockDriverState *bs, const char *filename, int flags)
1122 int ret, fd;
1123 uint32_t vid = 0;
1124 BDRVSheepdogState *s = bs->opaque;
1125 char vdi[SD_MAX_VDI_LEN], tag[SD_MAX_VDI_TAG_LEN];
1126 uint32_t snapid;
1127 char *buf = NULL;
1129 QLIST_INIT(&s->inflight_aio_head);
1130 QLIST_INIT(&s->pending_aio_head);
1131 s->fd = -1;
1133 memset(vdi, 0, sizeof(vdi));
1134 memset(tag, 0, sizeof(tag));
1136 if (strstr(filename, "://")) {
1137 ret = sd_parse_uri(s, filename, vdi, &snapid, tag);
1138 } else {
1139 ret = parse_vdiname(s, filename, vdi, &snapid, tag);
1141 if (ret < 0) {
1142 goto out;
1144 s->fd = get_sheep_fd(s);
1145 if (s->fd < 0) {
1146 ret = s->fd;
1147 goto out;
1150 ret = find_vdi_name(s, vdi, snapid, tag, &vid, 0);
1151 if (ret) {
1152 goto out;
1156 * QEMU block layer emulates writethrough cache as 'writeback + flush', so
1157 * we always set SD_FLAG_CMD_CACHE (writeback cache) as default.
1159 s->cache_flags = SD_FLAG_CMD_CACHE;
1160 if (flags & BDRV_O_NOCACHE) {
1161 s->cache_flags = SD_FLAG_CMD_DIRECT;
1164 if (snapid || tag[0] != '\0') {
1165 dprintf("%" PRIx32 " snapshot inode was open.\n", vid);
1166 s->is_snapshot = true;
1169 fd = connect_to_sdog(s);
1170 if (fd < 0) {
1171 ret = fd;
1172 goto out;
1175 buf = g_malloc(SD_INODE_SIZE);
1176 ret = read_object(fd, buf, vid_to_vdi_oid(vid), 0, SD_INODE_SIZE, 0,
1177 s->cache_flags);
1179 closesocket(fd);
1181 if (ret) {
1182 goto out;
1185 memcpy(&s->inode, buf, sizeof(s->inode));
1186 s->min_dirty_data_idx = UINT32_MAX;
1187 s->max_dirty_data_idx = 0;
1189 bs->total_sectors = s->inode.vdi_size / SECTOR_SIZE;
1190 pstrcpy(s->name, sizeof(s->name), vdi);
1191 qemu_co_mutex_init(&s->lock);
1192 g_free(buf);
1193 return 0;
1194 out:
1195 qemu_aio_set_fd_handler(s->fd, NULL, NULL, NULL, NULL);
1196 if (s->fd >= 0) {
1197 closesocket(s->fd);
1199 g_free(buf);
1200 return ret;
1203 static int do_sd_create(BDRVSheepdogState *s, char *filename, int64_t vdi_size,
1204 uint32_t base_vid, uint32_t *vdi_id, int snapshot)
1206 SheepdogVdiReq hdr;
1207 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
1208 int fd, ret;
1209 unsigned int wlen, rlen = 0;
1210 char buf[SD_MAX_VDI_LEN];
1212 fd = connect_to_sdog(s);
1213 if (fd < 0) {
1214 return fd;
1217 /* FIXME: would it be better to fail (e.g., return -EIO) when filename
1218 * does not fit in buf? For now, just truncate and avoid buffer overrun.
1220 memset(buf, 0, sizeof(buf));
1221 pstrcpy(buf, sizeof(buf), filename);
1223 memset(&hdr, 0, sizeof(hdr));
1224 hdr.opcode = SD_OP_NEW_VDI;
1225 hdr.vdi_id = base_vid;
1227 wlen = SD_MAX_VDI_LEN;
1229 hdr.flags = SD_FLAG_CMD_WRITE;
1230 hdr.snapid = snapshot;
1232 hdr.data_length = wlen;
1233 hdr.vdi_size = vdi_size;
1235 ret = do_req(fd, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
1237 closesocket(fd);
1239 if (ret) {
1240 return ret;
1243 if (rsp->result != SD_RES_SUCCESS) {
1244 error_report("%s, %s", sd_strerror(rsp->result), filename);
1245 return -EIO;
1248 if (vdi_id) {
1249 *vdi_id = rsp->vdi_id;
1252 return 0;
1255 static int sd_prealloc(const char *filename)
1257 BlockDriverState *bs = NULL;
1258 uint32_t idx, max_idx;
1259 int64_t vdi_size;
1260 void *buf = g_malloc0(SD_DATA_OBJ_SIZE);
1261 int ret;
1263 ret = bdrv_file_open(&bs, filename, BDRV_O_RDWR);
1264 if (ret < 0) {
1265 goto out;
1268 vdi_size = bdrv_getlength(bs);
1269 if (vdi_size < 0) {
1270 ret = vdi_size;
1271 goto out;
1273 max_idx = DIV_ROUND_UP(vdi_size, SD_DATA_OBJ_SIZE);
1275 for (idx = 0; idx < max_idx; idx++) {
1277 * The created image can be a cloned image, so we need to read
1278 * a data from the source image.
1280 ret = bdrv_pread(bs, idx * SD_DATA_OBJ_SIZE, buf, SD_DATA_OBJ_SIZE);
1281 if (ret < 0) {
1282 goto out;
1284 ret = bdrv_pwrite(bs, idx * SD_DATA_OBJ_SIZE, buf, SD_DATA_OBJ_SIZE);
1285 if (ret < 0) {
1286 goto out;
1289 out:
1290 if (bs) {
1291 bdrv_delete(bs);
1293 g_free(buf);
1295 return ret;
1298 static int sd_create(const char *filename, QEMUOptionParameter *options)
1300 int ret = 0;
1301 uint32_t vid = 0, base_vid = 0;
1302 int64_t vdi_size = 0;
1303 char *backing_file = NULL;
1304 BDRVSheepdogState *s;
1305 char vdi[SD_MAX_VDI_LEN], tag[SD_MAX_VDI_TAG_LEN];
1306 uint32_t snapid;
1307 bool prealloc = false;
1309 s = g_malloc0(sizeof(BDRVSheepdogState));
1311 memset(vdi, 0, sizeof(vdi));
1312 memset(tag, 0, sizeof(tag));
1313 if (strstr(filename, "://")) {
1314 ret = sd_parse_uri(s, filename, vdi, &snapid, tag);
1315 } else {
1316 ret = parse_vdiname(s, filename, vdi, &snapid, tag);
1318 if (ret < 0) {
1319 goto out;
1322 while (options && options->name) {
1323 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
1324 vdi_size = options->value.n;
1325 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
1326 backing_file = options->value.s;
1327 } else if (!strcmp(options->name, BLOCK_OPT_PREALLOC)) {
1328 if (!options->value.s || !strcmp(options->value.s, "off")) {
1329 prealloc = false;
1330 } else if (!strcmp(options->value.s, "full")) {
1331 prealloc = true;
1332 } else {
1333 error_report("Invalid preallocation mode: '%s'",
1334 options->value.s);
1335 ret = -EINVAL;
1336 goto out;
1339 options++;
1342 if (vdi_size > SD_MAX_VDI_SIZE) {
1343 error_report("too big image size");
1344 ret = -EINVAL;
1345 goto out;
1348 if (backing_file) {
1349 BlockDriverState *bs;
1350 BDRVSheepdogState *s;
1351 BlockDriver *drv;
1353 /* Currently, only Sheepdog backing image is supported. */
1354 drv = bdrv_find_protocol(backing_file);
1355 if (!drv || strcmp(drv->protocol_name, "sheepdog") != 0) {
1356 error_report("backing_file must be a sheepdog image");
1357 ret = -EINVAL;
1358 goto out;
1361 ret = bdrv_file_open(&bs, backing_file, 0);
1362 if (ret < 0) {
1363 goto out;
1366 s = bs->opaque;
1368 if (!is_snapshot(&s->inode)) {
1369 error_report("cannot clone from a non snapshot vdi");
1370 bdrv_delete(bs);
1371 ret = -EINVAL;
1372 goto out;
1375 base_vid = s->inode.vdi_id;
1376 bdrv_delete(bs);
1379 ret = do_sd_create(s, vdi, vdi_size, base_vid, &vid, 0);
1380 if (!prealloc || ret) {
1381 goto out;
1384 ret = sd_prealloc(filename);
1385 out:
1386 g_free(s);
1387 return ret;
1390 static void sd_close(BlockDriverState *bs)
1392 BDRVSheepdogState *s = bs->opaque;
1393 SheepdogVdiReq hdr;
1394 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
1395 unsigned int wlen, rlen = 0;
1396 int fd, ret;
1398 dprintf("%s\n", s->name);
1400 fd = connect_to_sdog(s);
1401 if (fd < 0) {
1402 return;
1405 memset(&hdr, 0, sizeof(hdr));
1407 hdr.opcode = SD_OP_RELEASE_VDI;
1408 hdr.vdi_id = s->inode.vdi_id;
1409 wlen = strlen(s->name) + 1;
1410 hdr.data_length = wlen;
1411 hdr.flags = SD_FLAG_CMD_WRITE;
1413 ret = do_req(fd, (SheepdogReq *)&hdr, s->name, &wlen, &rlen);
1415 closesocket(fd);
1417 if (!ret && rsp->result != SD_RES_SUCCESS &&
1418 rsp->result != SD_RES_VDI_NOT_LOCKED) {
1419 error_report("%s, %s", sd_strerror(rsp->result), s->name);
1422 qemu_aio_set_fd_handler(s->fd, NULL, NULL, NULL, NULL);
1423 closesocket(s->fd);
1424 g_free(s->host_spec);
1427 static int64_t sd_getlength(BlockDriverState *bs)
1429 BDRVSheepdogState *s = bs->opaque;
1431 return s->inode.vdi_size;
1434 static int sd_truncate(BlockDriverState *bs, int64_t offset)
1436 BDRVSheepdogState *s = bs->opaque;
1437 int ret, fd;
1438 unsigned int datalen;
1440 if (offset < s->inode.vdi_size) {
1441 error_report("shrinking is not supported");
1442 return -EINVAL;
1443 } else if (offset > SD_MAX_VDI_SIZE) {
1444 error_report("too big image size");
1445 return -EINVAL;
1448 fd = connect_to_sdog(s);
1449 if (fd < 0) {
1450 return fd;
1453 /* we don't need to update entire object */
1454 datalen = SD_INODE_SIZE - sizeof(s->inode.data_vdi_id);
1455 s->inode.vdi_size = offset;
1456 ret = write_object(fd, (char *)&s->inode, vid_to_vdi_oid(s->inode.vdi_id),
1457 s->inode.nr_copies, datalen, 0, false, s->cache_flags);
1458 close(fd);
1460 if (ret < 0) {
1461 error_report("failed to update an inode.");
1464 return ret;
1468 * This function is called after writing data objects. If we need to
1469 * update metadata, this sends a write request to the vdi object.
1470 * Otherwise, this switches back to sd_co_readv/writev.
1472 static void coroutine_fn sd_write_done(SheepdogAIOCB *acb)
1474 int ret;
1475 BDRVSheepdogState *s = acb->common.bs->opaque;
1476 struct iovec iov;
1477 AIOReq *aio_req;
1478 uint32_t offset, data_len, mn, mx;
1480 mn = s->min_dirty_data_idx;
1481 mx = s->max_dirty_data_idx;
1482 if (mn <= mx) {
1483 /* we need to update the vdi object. */
1484 offset = sizeof(s->inode) - sizeof(s->inode.data_vdi_id) +
1485 mn * sizeof(s->inode.data_vdi_id[0]);
1486 data_len = (mx - mn + 1) * sizeof(s->inode.data_vdi_id[0]);
1488 s->min_dirty_data_idx = UINT32_MAX;
1489 s->max_dirty_data_idx = 0;
1491 iov.iov_base = &s->inode;
1492 iov.iov_len = sizeof(s->inode);
1493 aio_req = alloc_aio_req(s, acb, vid_to_vdi_oid(s->inode.vdi_id),
1494 data_len, offset, 0, 0, offset);
1495 QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
1496 ret = add_aio_request(s, aio_req, &iov, 1, false, AIOCB_WRITE_UDATA);
1497 if (ret) {
1498 free_aio_req(s, aio_req);
1499 acb->ret = -EIO;
1500 goto out;
1503 acb->aio_done_func = sd_finish_aiocb;
1504 acb->aiocb_type = AIOCB_WRITE_UDATA;
1505 return;
1507 out:
1508 sd_finish_aiocb(acb);
1512 * Create a writable VDI from a snapshot
1514 static int sd_create_branch(BDRVSheepdogState *s)
1516 int ret, fd;
1517 uint32_t vid;
1518 char *buf;
1520 dprintf("%" PRIx32 " is snapshot.\n", s->inode.vdi_id);
1522 buf = g_malloc(SD_INODE_SIZE);
1524 ret = do_sd_create(s, s->name, s->inode.vdi_size, s->inode.vdi_id, &vid, 1);
1525 if (ret) {
1526 goto out;
1529 dprintf("%" PRIx32 " is created.\n", vid);
1531 fd = connect_to_sdog(s);
1532 if (fd < 0) {
1533 ret = fd;
1534 goto out;
1537 ret = read_object(fd, buf, vid_to_vdi_oid(vid), s->inode.nr_copies,
1538 SD_INODE_SIZE, 0, s->cache_flags);
1540 closesocket(fd);
1542 if (ret < 0) {
1543 goto out;
1546 memcpy(&s->inode, buf, sizeof(s->inode));
1548 s->is_snapshot = false;
1549 ret = 0;
1550 dprintf("%" PRIx32 " was newly created.\n", s->inode.vdi_id);
1552 out:
1553 g_free(buf);
1555 return ret;
1559 * Send I/O requests to the server.
1561 * This function sends requests to the server, links the requests to
1562 * the inflight_list in BDRVSheepdogState, and exits without
1563 * waiting the response. The responses are received in the
1564 * `aio_read_response' function which is called from the main loop as
1565 * a fd handler.
1567 * Returns 1 when we need to wait a response, 0 when there is no sent
1568 * request and -errno in error cases.
1570 static int coroutine_fn sd_co_rw_vector(void *p)
1572 SheepdogAIOCB *acb = p;
1573 int ret = 0;
1574 unsigned long len, done = 0, total = acb->nb_sectors * SECTOR_SIZE;
1575 unsigned long idx = acb->sector_num * SECTOR_SIZE / SD_DATA_OBJ_SIZE;
1576 uint64_t oid;
1577 uint64_t offset = (acb->sector_num * SECTOR_SIZE) % SD_DATA_OBJ_SIZE;
1578 BDRVSheepdogState *s = acb->common.bs->opaque;
1579 SheepdogInode *inode = &s->inode;
1580 AIOReq *aio_req;
1582 if (acb->aiocb_type == AIOCB_WRITE_UDATA && s->is_snapshot) {
1584 * In the case we open the snapshot VDI, Sheepdog creates the
1585 * writable VDI when we do a write operation first.
1587 ret = sd_create_branch(s);
1588 if (ret) {
1589 acb->ret = -EIO;
1590 goto out;
1595 * Make sure we don't free the aiocb before we are done with all requests.
1596 * This additional reference is dropped at the end of this function.
1598 acb->nr_pending++;
1600 while (done != total) {
1601 uint8_t flags = 0;
1602 uint64_t old_oid = 0;
1603 bool create = false;
1605 oid = vid_to_data_oid(inode->data_vdi_id[idx], idx);
1607 len = MIN(total - done, SD_DATA_OBJ_SIZE - offset);
1609 switch (acb->aiocb_type) {
1610 case AIOCB_READ_UDATA:
1611 if (!inode->data_vdi_id[idx]) {
1612 qemu_iovec_memset(acb->qiov, done, 0, len);
1613 goto done;
1615 break;
1616 case AIOCB_WRITE_UDATA:
1617 if (!inode->data_vdi_id[idx]) {
1618 create = true;
1619 } else if (!is_data_obj_writable(inode, idx)) {
1620 /* Copy-On-Write */
1621 create = true;
1622 old_oid = oid;
1623 flags = SD_FLAG_CMD_COW;
1625 break;
1626 default:
1627 break;
1630 if (create) {
1631 dprintf("update ino (%" PRIu32 ") %" PRIu64 " %" PRIu64 " %ld\n",
1632 inode->vdi_id, oid,
1633 vid_to_data_oid(inode->data_vdi_id[idx], idx), idx);
1634 oid = vid_to_data_oid(inode->vdi_id, idx);
1635 dprintf("new oid %" PRIx64 "\n", oid);
1638 aio_req = alloc_aio_req(s, acb, oid, len, offset, flags, old_oid, done);
1640 if (create) {
1641 AIOReq *areq;
1642 QLIST_FOREACH(areq, &s->inflight_aio_head, aio_siblings) {
1643 if (areq->oid == oid) {
1645 * Sheepdog cannot handle simultaneous create
1646 * requests to the same object. So we cannot send
1647 * the request until the previous request
1648 * finishes.
1650 aio_req->flags = 0;
1651 aio_req->base_oid = 0;
1652 QLIST_INSERT_HEAD(&s->pending_aio_head, aio_req,
1653 aio_siblings);
1654 goto done;
1659 QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
1660 ret = add_aio_request(s, aio_req, acb->qiov->iov, acb->qiov->niov,
1661 create, acb->aiocb_type);
1662 if (ret < 0) {
1663 error_report("add_aio_request is failed");
1664 free_aio_req(s, aio_req);
1665 acb->ret = -EIO;
1666 goto out;
1668 done:
1669 offset = 0;
1670 idx++;
1671 done += len;
1673 out:
1674 if (!--acb->nr_pending) {
1675 return acb->ret;
1677 return 1;
1680 static coroutine_fn int sd_co_writev(BlockDriverState *bs, int64_t sector_num,
1681 int nb_sectors, QEMUIOVector *qiov)
1683 SheepdogAIOCB *acb;
1684 int ret;
1686 if (bs->growable && sector_num + nb_sectors > bs->total_sectors) {
1687 ret = sd_truncate(bs, (sector_num + nb_sectors) * SECTOR_SIZE);
1688 if (ret < 0) {
1689 return ret;
1691 bs->total_sectors = sector_num + nb_sectors;
1694 acb = sd_aio_setup(bs, qiov, sector_num, nb_sectors);
1695 acb->aio_done_func = sd_write_done;
1696 acb->aiocb_type = AIOCB_WRITE_UDATA;
1698 ret = sd_co_rw_vector(acb);
1699 if (ret <= 0) {
1700 qemu_aio_release(acb);
1701 return ret;
1704 qemu_coroutine_yield();
1706 return acb->ret;
1709 static coroutine_fn int sd_co_readv(BlockDriverState *bs, int64_t sector_num,
1710 int nb_sectors, QEMUIOVector *qiov)
1712 SheepdogAIOCB *acb;
1713 int ret;
1715 acb = sd_aio_setup(bs, qiov, sector_num, nb_sectors);
1716 acb->aiocb_type = AIOCB_READ_UDATA;
1717 acb->aio_done_func = sd_finish_aiocb;
1719 ret = sd_co_rw_vector(acb);
1720 if (ret <= 0) {
1721 qemu_aio_release(acb);
1722 return ret;
1725 qemu_coroutine_yield();
1727 return acb->ret;
1730 static int coroutine_fn sd_co_flush_to_disk(BlockDriverState *bs)
1732 BDRVSheepdogState *s = bs->opaque;
1733 SheepdogAIOCB *acb;
1734 AIOReq *aio_req;
1735 int ret;
1737 if (s->cache_flags != SD_FLAG_CMD_CACHE) {
1738 return 0;
1741 acb = sd_aio_setup(bs, NULL, 0, 0);
1742 acb->aiocb_type = AIOCB_FLUSH_CACHE;
1743 acb->aio_done_func = sd_finish_aiocb;
1745 aio_req = alloc_aio_req(s, acb, vid_to_vdi_oid(s->inode.vdi_id),
1746 0, 0, 0, 0, 0);
1747 QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
1748 ret = add_aio_request(s, aio_req, NULL, 0, false, acb->aiocb_type);
1749 if (ret < 0) {
1750 error_report("add_aio_request is failed");
1751 free_aio_req(s, aio_req);
1752 qemu_aio_release(acb);
1753 return ret;
1756 qemu_coroutine_yield();
1757 return acb->ret;
1760 static int sd_snapshot_create(BlockDriverState *bs, QEMUSnapshotInfo *sn_info)
1762 BDRVSheepdogState *s = bs->opaque;
1763 int ret, fd;
1764 uint32_t new_vid;
1765 SheepdogInode *inode;
1766 unsigned int datalen;
1768 dprintf("sn_info: name %s id_str %s s: name %s vm_state_size %" PRId64 " "
1769 "is_snapshot %d\n", sn_info->name, sn_info->id_str,
1770 s->name, sn_info->vm_state_size, s->is_snapshot);
1772 if (s->is_snapshot) {
1773 error_report("You can't create a snapshot of a snapshot VDI, "
1774 "%s (%" PRIu32 ").", s->name, s->inode.vdi_id);
1776 return -EINVAL;
1779 dprintf("%s %s\n", sn_info->name, sn_info->id_str);
1781 s->inode.vm_state_size = sn_info->vm_state_size;
1782 s->inode.vm_clock_nsec = sn_info->vm_clock_nsec;
1783 /* It appears that inode.tag does not require a NUL terminator,
1784 * which means this use of strncpy is ok.
1786 strncpy(s->inode.tag, sn_info->name, sizeof(s->inode.tag));
1787 /* we don't need to update entire object */
1788 datalen = SD_INODE_SIZE - sizeof(s->inode.data_vdi_id);
1790 /* refresh inode. */
1791 fd = connect_to_sdog(s);
1792 if (fd < 0) {
1793 ret = fd;
1794 goto cleanup;
1797 ret = write_object(fd, (char *)&s->inode, vid_to_vdi_oid(s->inode.vdi_id),
1798 s->inode.nr_copies, datalen, 0, false, s->cache_flags);
1799 if (ret < 0) {
1800 error_report("failed to write snapshot's inode.");
1801 goto cleanup;
1804 ret = do_sd_create(s, s->name, s->inode.vdi_size, s->inode.vdi_id, &new_vid,
1806 if (ret < 0) {
1807 error_report("failed to create inode for snapshot. %s",
1808 strerror(errno));
1809 goto cleanup;
1812 inode = (SheepdogInode *)g_malloc(datalen);
1814 ret = read_object(fd, (char *)inode, vid_to_vdi_oid(new_vid),
1815 s->inode.nr_copies, datalen, 0, s->cache_flags);
1817 if (ret < 0) {
1818 error_report("failed to read new inode info. %s", strerror(errno));
1819 goto cleanup;
1822 memcpy(&s->inode, inode, datalen);
1823 dprintf("s->inode: name %s snap_id %x oid %x\n",
1824 s->inode.name, s->inode.snap_id, s->inode.vdi_id);
1826 cleanup:
1827 closesocket(fd);
1828 return ret;
1831 static int sd_snapshot_goto(BlockDriverState *bs, const char *snapshot_id)
1833 BDRVSheepdogState *s = bs->opaque;
1834 BDRVSheepdogState *old_s;
1835 char vdi[SD_MAX_VDI_LEN], tag[SD_MAX_VDI_TAG_LEN];
1836 char *buf = NULL;
1837 uint32_t vid;
1838 uint32_t snapid = 0;
1839 int ret = 0, fd;
1841 old_s = g_malloc(sizeof(BDRVSheepdogState));
1843 memcpy(old_s, s, sizeof(BDRVSheepdogState));
1845 pstrcpy(vdi, sizeof(vdi), s->name);
1847 snapid = strtoul(snapshot_id, NULL, 10);
1848 if (snapid) {
1849 tag[0] = 0;
1850 } else {
1851 pstrcpy(tag, sizeof(tag), s->name);
1854 ret = find_vdi_name(s, vdi, snapid, tag, &vid, 1);
1855 if (ret) {
1856 error_report("Failed to find_vdi_name");
1857 goto out;
1860 fd = connect_to_sdog(s);
1861 if (fd < 0) {
1862 ret = fd;
1863 goto out;
1866 buf = g_malloc(SD_INODE_SIZE);
1867 ret = read_object(fd, buf, vid_to_vdi_oid(vid), s->inode.nr_copies,
1868 SD_INODE_SIZE, 0, s->cache_flags);
1870 closesocket(fd);
1872 if (ret) {
1873 goto out;
1876 memcpy(&s->inode, buf, sizeof(s->inode));
1878 if (!s->inode.vm_state_size) {
1879 error_report("Invalid snapshot");
1880 ret = -ENOENT;
1881 goto out;
1884 s->is_snapshot = true;
1886 g_free(buf);
1887 g_free(old_s);
1889 return 0;
1890 out:
1891 /* recover bdrv_sd_state */
1892 memcpy(s, old_s, sizeof(BDRVSheepdogState));
1893 g_free(buf);
1894 g_free(old_s);
1896 error_report("failed to open. recover old bdrv_sd_state.");
1898 return ret;
1901 static int sd_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
1903 /* FIXME: Delete specified snapshot id. */
1904 return 0;
1907 static int sd_snapshot_list(BlockDriverState *bs, QEMUSnapshotInfo **psn_tab)
1909 BDRVSheepdogState *s = bs->opaque;
1910 SheepdogReq req;
1911 int fd, nr = 1024, ret, max = BITS_TO_LONGS(SD_NR_VDIS) * sizeof(long);
1912 QEMUSnapshotInfo *sn_tab = NULL;
1913 unsigned wlen, rlen;
1914 int found = 0;
1915 static SheepdogInode inode;
1916 unsigned long *vdi_inuse;
1917 unsigned int start_nr;
1918 uint64_t hval;
1919 uint32_t vid;
1921 vdi_inuse = g_malloc(max);
1923 fd = connect_to_sdog(s);
1924 if (fd < 0) {
1925 ret = fd;
1926 goto out;
1929 rlen = max;
1930 wlen = 0;
1932 memset(&req, 0, sizeof(req));
1934 req.opcode = SD_OP_READ_VDIS;
1935 req.data_length = max;
1937 ret = do_req(fd, (SheepdogReq *)&req, vdi_inuse, &wlen, &rlen);
1939 closesocket(fd);
1940 if (ret) {
1941 goto out;
1944 sn_tab = g_malloc0(nr * sizeof(*sn_tab));
1946 /* calculate a vdi id with hash function */
1947 hval = fnv_64a_buf(s->name, strlen(s->name), FNV1A_64_INIT);
1948 start_nr = hval & (SD_NR_VDIS - 1);
1950 fd = connect_to_sdog(s);
1951 if (fd < 0) {
1952 ret = fd;
1953 goto out;
1956 for (vid = start_nr; found < nr; vid = (vid + 1) % SD_NR_VDIS) {
1957 if (!test_bit(vid, vdi_inuse)) {
1958 break;
1961 /* we don't need to read entire object */
1962 ret = read_object(fd, (char *)&inode, vid_to_vdi_oid(vid),
1963 0, SD_INODE_SIZE - sizeof(inode.data_vdi_id), 0,
1964 s->cache_flags);
1966 if (ret) {
1967 continue;
1970 if (!strcmp(inode.name, s->name) && is_snapshot(&inode)) {
1971 sn_tab[found].date_sec = inode.snap_ctime >> 32;
1972 sn_tab[found].date_nsec = inode.snap_ctime & 0xffffffff;
1973 sn_tab[found].vm_state_size = inode.vm_state_size;
1974 sn_tab[found].vm_clock_nsec = inode.vm_clock_nsec;
1976 snprintf(sn_tab[found].id_str, sizeof(sn_tab[found].id_str), "%u",
1977 inode.snap_id);
1978 pstrcpy(sn_tab[found].name,
1979 MIN(sizeof(sn_tab[found].name), sizeof(inode.tag)),
1980 inode.tag);
1981 found++;
1985 closesocket(fd);
1986 out:
1987 *psn_tab = sn_tab;
1989 g_free(vdi_inuse);
1991 if (ret < 0) {
1992 return ret;
1995 return found;
1998 static int do_load_save_vmstate(BDRVSheepdogState *s, uint8_t *data,
1999 int64_t pos, int size, int load)
2001 bool create;
2002 int fd, ret = 0, remaining = size;
2003 unsigned int data_len;
2004 uint64_t vmstate_oid;
2005 uint32_t vdi_index;
2006 uint64_t offset;
2008 fd = connect_to_sdog(s);
2009 if (fd < 0) {
2010 return fd;
2013 while (remaining) {
2014 vdi_index = pos / SD_DATA_OBJ_SIZE;
2015 offset = pos % SD_DATA_OBJ_SIZE;
2017 data_len = MIN(remaining, SD_DATA_OBJ_SIZE - offset);
2019 vmstate_oid = vid_to_vmstate_oid(s->inode.vdi_id, vdi_index);
2021 create = (offset == 0);
2022 if (load) {
2023 ret = read_object(fd, (char *)data, vmstate_oid,
2024 s->inode.nr_copies, data_len, offset,
2025 s->cache_flags);
2026 } else {
2027 ret = write_object(fd, (char *)data, vmstate_oid,
2028 s->inode.nr_copies, data_len, offset, create,
2029 s->cache_flags);
2032 if (ret < 0) {
2033 error_report("failed to save vmstate %s", strerror(errno));
2034 goto cleanup;
2037 pos += data_len;
2038 data += data_len;
2039 remaining -= data_len;
2041 ret = size;
2042 cleanup:
2043 closesocket(fd);
2044 return ret;
2047 static int sd_save_vmstate(BlockDriverState *bs, const uint8_t *data,
2048 int64_t pos, int size)
2050 BDRVSheepdogState *s = bs->opaque;
2052 return do_load_save_vmstate(s, (uint8_t *)data, pos, size, 0);
2055 static int sd_load_vmstate(BlockDriverState *bs, uint8_t *data,
2056 int64_t pos, int size)
2058 BDRVSheepdogState *s = bs->opaque;
2060 return do_load_save_vmstate(s, data, pos, size, 1);
2064 static QEMUOptionParameter sd_create_options[] = {
2066 .name = BLOCK_OPT_SIZE,
2067 .type = OPT_SIZE,
2068 .help = "Virtual disk size"
2071 .name = BLOCK_OPT_BACKING_FILE,
2072 .type = OPT_STRING,
2073 .help = "File name of a base image"
2076 .name = BLOCK_OPT_PREALLOC,
2077 .type = OPT_STRING,
2078 .help = "Preallocation mode (allowed values: off, full)"
2080 { NULL }
2083 static BlockDriver bdrv_sheepdog = {
2084 .format_name = "sheepdog",
2085 .protocol_name = "sheepdog",
2086 .instance_size = sizeof(BDRVSheepdogState),
2087 .bdrv_file_open = sd_open,
2088 .bdrv_close = sd_close,
2089 .bdrv_create = sd_create,
2090 .bdrv_getlength = sd_getlength,
2091 .bdrv_truncate = sd_truncate,
2093 .bdrv_co_readv = sd_co_readv,
2094 .bdrv_co_writev = sd_co_writev,
2095 .bdrv_co_flush_to_disk = sd_co_flush_to_disk,
2097 .bdrv_snapshot_create = sd_snapshot_create,
2098 .bdrv_snapshot_goto = sd_snapshot_goto,
2099 .bdrv_snapshot_delete = sd_snapshot_delete,
2100 .bdrv_snapshot_list = sd_snapshot_list,
2102 .bdrv_save_vmstate = sd_save_vmstate,
2103 .bdrv_load_vmstate = sd_load_vmstate,
2105 .create_options = sd_create_options,
2108 static BlockDriver bdrv_sheepdog_tcp = {
2109 .format_name = "sheepdog",
2110 .protocol_name = "sheepdog+tcp",
2111 .instance_size = sizeof(BDRVSheepdogState),
2112 .bdrv_file_open = sd_open,
2113 .bdrv_close = sd_close,
2114 .bdrv_create = sd_create,
2115 .bdrv_getlength = sd_getlength,
2116 .bdrv_truncate = sd_truncate,
2118 .bdrv_co_readv = sd_co_readv,
2119 .bdrv_co_writev = sd_co_writev,
2120 .bdrv_co_flush_to_disk = sd_co_flush_to_disk,
2122 .bdrv_snapshot_create = sd_snapshot_create,
2123 .bdrv_snapshot_goto = sd_snapshot_goto,
2124 .bdrv_snapshot_delete = sd_snapshot_delete,
2125 .bdrv_snapshot_list = sd_snapshot_list,
2127 .bdrv_save_vmstate = sd_save_vmstate,
2128 .bdrv_load_vmstate = sd_load_vmstate,
2130 .create_options = sd_create_options,
2133 static BlockDriver bdrv_sheepdog_unix = {
2134 .format_name = "sheepdog",
2135 .protocol_name = "sheepdog+unix",
2136 .instance_size = sizeof(BDRVSheepdogState),
2137 .bdrv_file_open = sd_open,
2138 .bdrv_close = sd_close,
2139 .bdrv_create = sd_create,
2140 .bdrv_getlength = sd_getlength,
2141 .bdrv_truncate = sd_truncate,
2143 .bdrv_co_readv = sd_co_readv,
2144 .bdrv_co_writev = sd_co_writev,
2145 .bdrv_co_flush_to_disk = sd_co_flush_to_disk,
2147 .bdrv_snapshot_create = sd_snapshot_create,
2148 .bdrv_snapshot_goto = sd_snapshot_goto,
2149 .bdrv_snapshot_delete = sd_snapshot_delete,
2150 .bdrv_snapshot_list = sd_snapshot_list,
2152 .bdrv_save_vmstate = sd_save_vmstate,
2153 .bdrv_load_vmstate = sd_load_vmstate,
2155 .create_options = sd_create_options,
2158 static void bdrv_sheepdog_init(void)
2160 bdrv_register(&bdrv_sheepdog);
2161 bdrv_register(&bdrv_sheepdog_tcp);
2162 bdrv_register(&bdrv_sheepdog_unix);
2164 block_init(bdrv_sheepdog_init);