usb-host: add usb packet to request tracepoints
[qemu/wangdongxu.git] / block / sheepdog.c
blob3eaf625e98b633a0505715a040a6a455f5da9ce4
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-error.h"
17 #include "qemu_socket.h"
18 #include "block_int.h"
19 #include "bitops.h"
21 #define SD_PROTO_VER 0x01
23 #define SD_DEFAULT_ADDR "localhost"
24 #define SD_DEFAULT_PORT "7000"
26 #define SD_OP_CREATE_AND_WRITE_OBJ 0x01
27 #define SD_OP_READ_OBJ 0x02
28 #define SD_OP_WRITE_OBJ 0x03
30 #define SD_OP_NEW_VDI 0x11
31 #define SD_OP_LOCK_VDI 0x12
32 #define SD_OP_RELEASE_VDI 0x13
33 #define SD_OP_GET_VDI_INFO 0x14
34 #define SD_OP_READ_VDIS 0x15
35 #define SD_OP_FLUSH_VDI 0x16
37 #define SD_FLAG_CMD_WRITE 0x01
38 #define SD_FLAG_CMD_COW 0x02
39 #define SD_FLAG_CMD_CACHE 0x04
41 #define SD_RES_SUCCESS 0x00 /* Success */
42 #define SD_RES_UNKNOWN 0x01 /* Unknown error */
43 #define SD_RES_NO_OBJ 0x02 /* No object found */
44 #define SD_RES_EIO 0x03 /* I/O error */
45 #define SD_RES_VDI_EXIST 0x04 /* Vdi exists already */
46 #define SD_RES_INVALID_PARMS 0x05 /* Invalid parameters */
47 #define SD_RES_SYSTEM_ERROR 0x06 /* System error */
48 #define SD_RES_VDI_LOCKED 0x07 /* Vdi is locked */
49 #define SD_RES_NO_VDI 0x08 /* No vdi found */
50 #define SD_RES_NO_BASE_VDI 0x09 /* No base vdi found */
51 #define SD_RES_VDI_READ 0x0A /* Cannot read requested vdi */
52 #define SD_RES_VDI_WRITE 0x0B /* Cannot write requested vdi */
53 #define SD_RES_BASE_VDI_READ 0x0C /* Cannot read base vdi */
54 #define SD_RES_BASE_VDI_WRITE 0x0D /* Cannot write base vdi */
55 #define SD_RES_NO_TAG 0x0E /* Requested tag is not found */
56 #define SD_RES_STARTUP 0x0F /* Sheepdog is on starting up */
57 #define SD_RES_VDI_NOT_LOCKED 0x10 /* Vdi is not locked */
58 #define SD_RES_SHUTDOWN 0x11 /* Sheepdog is shutting down */
59 #define SD_RES_NO_MEM 0x12 /* Cannot allocate memory */
60 #define SD_RES_FULL_VDI 0x13 /* we already have the maximum vdis */
61 #define SD_RES_VER_MISMATCH 0x14 /* Protocol version mismatch */
62 #define SD_RES_NO_SPACE 0x15 /* Server has no room for new objects */
63 #define SD_RES_WAIT_FOR_FORMAT 0x16 /* Waiting for a format operation */
64 #define SD_RES_WAIT_FOR_JOIN 0x17 /* Waiting for other nodes joining */
65 #define SD_RES_JOIN_FAILED 0x18 /* Target node had failed to join sheepdog */
68 * Object ID rules
70 * 0 - 19 (20 bits): data object space
71 * 20 - 31 (12 bits): reserved data object space
72 * 32 - 55 (24 bits): vdi object space
73 * 56 - 59 ( 4 bits): reserved vdi object space
74 * 60 - 63 ( 4 bits): object type identifier space
77 #define VDI_SPACE_SHIFT 32
78 #define VDI_BIT (UINT64_C(1) << 63)
79 #define VMSTATE_BIT (UINT64_C(1) << 62)
80 #define MAX_DATA_OBJS (UINT64_C(1) << 20)
81 #define MAX_CHILDREN 1024
82 #define SD_MAX_VDI_LEN 256
83 #define SD_MAX_VDI_TAG_LEN 256
84 #define SD_NR_VDIS (1U << 24)
85 #define SD_DATA_OBJ_SIZE (UINT64_C(1) << 22)
86 #define SD_MAX_VDI_SIZE (SD_DATA_OBJ_SIZE * MAX_DATA_OBJS)
87 #define SECTOR_SIZE 512
89 #define SD_INODE_SIZE (sizeof(SheepdogInode))
90 #define CURRENT_VDI_ID 0
92 typedef struct SheepdogReq {
93 uint8_t proto_ver;
94 uint8_t opcode;
95 uint16_t flags;
96 uint32_t epoch;
97 uint32_t id;
98 uint32_t data_length;
99 uint32_t opcode_specific[8];
100 } SheepdogReq;
102 typedef struct SheepdogRsp {
103 uint8_t proto_ver;
104 uint8_t opcode;
105 uint16_t flags;
106 uint32_t epoch;
107 uint32_t id;
108 uint32_t data_length;
109 uint32_t result;
110 uint32_t opcode_specific[7];
111 } SheepdogRsp;
113 typedef struct SheepdogObjReq {
114 uint8_t proto_ver;
115 uint8_t opcode;
116 uint16_t flags;
117 uint32_t epoch;
118 uint32_t id;
119 uint32_t data_length;
120 uint64_t oid;
121 uint64_t cow_oid;
122 uint32_t copies;
123 uint32_t rsvd;
124 uint64_t offset;
125 } SheepdogObjReq;
127 typedef struct SheepdogObjRsp {
128 uint8_t proto_ver;
129 uint8_t opcode;
130 uint16_t flags;
131 uint32_t epoch;
132 uint32_t id;
133 uint32_t data_length;
134 uint32_t result;
135 uint32_t copies;
136 uint32_t pad[6];
137 } SheepdogObjRsp;
139 typedef struct SheepdogVdiReq {
140 uint8_t proto_ver;
141 uint8_t opcode;
142 uint16_t flags;
143 uint32_t epoch;
144 uint32_t id;
145 uint32_t data_length;
146 uint64_t vdi_size;
147 uint32_t base_vdi_id;
148 uint32_t copies;
149 uint32_t snapid;
150 uint32_t pad[3];
151 } SheepdogVdiReq;
153 typedef struct SheepdogVdiRsp {
154 uint8_t proto_ver;
155 uint8_t opcode;
156 uint16_t flags;
157 uint32_t epoch;
158 uint32_t id;
159 uint32_t data_length;
160 uint32_t result;
161 uint32_t rsvd;
162 uint32_t vdi_id;
163 uint32_t pad[5];
164 } SheepdogVdiRsp;
166 typedef struct SheepdogInode {
167 char name[SD_MAX_VDI_LEN];
168 char tag[SD_MAX_VDI_TAG_LEN];
169 uint64_t ctime;
170 uint64_t snap_ctime;
171 uint64_t vm_clock_nsec;
172 uint64_t vdi_size;
173 uint64_t vm_state_size;
174 uint16_t copy_policy;
175 uint8_t nr_copies;
176 uint8_t block_size_shift;
177 uint32_t snap_id;
178 uint32_t vdi_id;
179 uint32_t parent_vdi_id;
180 uint32_t child_vdi_id[MAX_CHILDREN];
181 uint32_t data_vdi_id[MAX_DATA_OBJS];
182 } SheepdogInode;
185 * 64 bit FNV-1a non-zero initial basis
187 #define FNV1A_64_INIT ((uint64_t)0xcbf29ce484222325ULL)
190 * 64 bit Fowler/Noll/Vo FNV-1a hash code
192 static inline uint64_t fnv_64a_buf(void *buf, size_t len, uint64_t hval)
194 unsigned char *bp = buf;
195 unsigned char *be = bp + len;
196 while (bp < be) {
197 hval ^= (uint64_t) *bp++;
198 hval += (hval << 1) + (hval << 4) + (hval << 5) +
199 (hval << 7) + (hval << 8) + (hval << 40);
201 return hval;
204 static inline int is_data_obj_writable(SheepdogInode *inode, unsigned int idx)
206 return inode->vdi_id == inode->data_vdi_id[idx];
209 static inline int is_data_obj(uint64_t oid)
211 return !(VDI_BIT & oid);
214 static inline uint64_t data_oid_to_idx(uint64_t oid)
216 return oid & (MAX_DATA_OBJS - 1);
219 static inline uint64_t vid_to_vdi_oid(uint32_t vid)
221 return VDI_BIT | ((uint64_t)vid << VDI_SPACE_SHIFT);
224 static inline uint64_t vid_to_vmstate_oid(uint32_t vid, uint32_t idx)
226 return VMSTATE_BIT | ((uint64_t)vid << VDI_SPACE_SHIFT) | idx;
229 static inline uint64_t vid_to_data_oid(uint32_t vid, uint32_t idx)
231 return ((uint64_t)vid << VDI_SPACE_SHIFT) | idx;
234 static inline int is_snapshot(struct SheepdogInode *inode)
236 return !!inode->snap_ctime;
239 #undef dprintf
240 #ifdef DEBUG_SDOG
241 #define dprintf(fmt, args...) \
242 do { \
243 fprintf(stdout, "%s %d: " fmt, __func__, __LINE__, ##args); \
244 } while (0)
245 #else
246 #define dprintf(fmt, args...)
247 #endif
249 typedef struct SheepdogAIOCB SheepdogAIOCB;
251 typedef struct AIOReq {
252 SheepdogAIOCB *aiocb;
253 unsigned int iov_offset;
255 uint64_t oid;
256 uint64_t base_oid;
257 uint64_t offset;
258 unsigned int data_len;
259 uint8_t flags;
260 uint32_t id;
262 QLIST_ENTRY(AIOReq) outstanding_aio_siblings;
263 QLIST_ENTRY(AIOReq) aioreq_siblings;
264 } AIOReq;
266 enum AIOCBState {
267 AIOCB_WRITE_UDATA,
268 AIOCB_READ_UDATA,
271 struct SheepdogAIOCB {
272 BlockDriverAIOCB common;
274 QEMUIOVector *qiov;
276 int64_t sector_num;
277 int nb_sectors;
279 int ret;
280 enum AIOCBState aiocb_type;
282 Coroutine *coroutine;
283 void (*aio_done_func)(SheepdogAIOCB *);
285 int canceled;
287 QLIST_HEAD(aioreq_head, AIOReq) aioreq_head;
290 typedef struct BDRVSheepdogState {
291 SheepdogInode inode;
293 uint32_t min_dirty_data_idx;
294 uint32_t max_dirty_data_idx;
296 char name[SD_MAX_VDI_LEN];
297 int is_snapshot;
298 uint8_t cache_enabled;
300 char *addr;
301 char *port;
302 int fd;
303 int flush_fd;
305 CoMutex lock;
306 Coroutine *co_send;
307 Coroutine *co_recv;
309 uint32_t aioreq_seq_num;
310 QLIST_HEAD(outstanding_aio_head, AIOReq) outstanding_aio_head;
311 } BDRVSheepdogState;
313 static const char * sd_strerror(int err)
315 int i;
317 static const struct {
318 int err;
319 const char *desc;
320 } errors[] = {
321 {SD_RES_SUCCESS, "Success"},
322 {SD_RES_UNKNOWN, "Unknown error"},
323 {SD_RES_NO_OBJ, "No object found"},
324 {SD_RES_EIO, "I/O error"},
325 {SD_RES_VDI_EXIST, "VDI exists already"},
326 {SD_RES_INVALID_PARMS, "Invalid parameters"},
327 {SD_RES_SYSTEM_ERROR, "System error"},
328 {SD_RES_VDI_LOCKED, "VDI is already locked"},
329 {SD_RES_NO_VDI, "No vdi found"},
330 {SD_RES_NO_BASE_VDI, "No base VDI found"},
331 {SD_RES_VDI_READ, "Failed read the requested VDI"},
332 {SD_RES_VDI_WRITE, "Failed to write the requested VDI"},
333 {SD_RES_BASE_VDI_READ, "Failed to read the base VDI"},
334 {SD_RES_BASE_VDI_WRITE, "Failed to write the base VDI"},
335 {SD_RES_NO_TAG, "Failed to find the requested tag"},
336 {SD_RES_STARTUP, "The system is still booting"},
337 {SD_RES_VDI_NOT_LOCKED, "VDI isn't locked"},
338 {SD_RES_SHUTDOWN, "The system is shutting down"},
339 {SD_RES_NO_MEM, "Out of memory on the server"},
340 {SD_RES_FULL_VDI, "We already have the maximum vdis"},
341 {SD_RES_VER_MISMATCH, "Protocol version mismatch"},
342 {SD_RES_NO_SPACE, "Server has no space for new objects"},
343 {SD_RES_WAIT_FOR_FORMAT, "Sheepdog is waiting for a format operation"},
344 {SD_RES_WAIT_FOR_JOIN, "Sheepdog is waiting for other nodes joining"},
345 {SD_RES_JOIN_FAILED, "Target node had failed to join sheepdog"},
348 for (i = 0; i < ARRAY_SIZE(errors); ++i) {
349 if (errors[i].err == err) {
350 return errors[i].desc;
354 return "Invalid error code";
358 * Sheepdog I/O handling:
360 * 1. In sd_co_rw_vector, we send the I/O requests to the server and
361 * link the requests to the outstanding_list in the
362 * BDRVSheepdogState. The function exits without waiting for
363 * receiving the response.
365 * 2. We receive the response in aio_read_response, the fd handler to
366 * the sheepdog connection. If metadata update is needed, we send
367 * the write request to the vdi object in sd_write_done, the write
368 * completion function. We switch back to sd_co_readv/writev after
369 * all the requests belonging to the AIOCB are finished.
372 static inline AIOReq *alloc_aio_req(BDRVSheepdogState *s, SheepdogAIOCB *acb,
373 uint64_t oid, unsigned int data_len,
374 uint64_t offset, uint8_t flags,
375 uint64_t base_oid, unsigned int iov_offset)
377 AIOReq *aio_req;
379 aio_req = g_malloc(sizeof(*aio_req));
380 aio_req->aiocb = acb;
381 aio_req->iov_offset = iov_offset;
382 aio_req->oid = oid;
383 aio_req->base_oid = base_oid;
384 aio_req->offset = offset;
385 aio_req->data_len = data_len;
386 aio_req->flags = flags;
387 aio_req->id = s->aioreq_seq_num++;
389 QLIST_INSERT_HEAD(&s->outstanding_aio_head, aio_req,
390 outstanding_aio_siblings);
391 QLIST_INSERT_HEAD(&acb->aioreq_head, aio_req, aioreq_siblings);
393 return aio_req;
396 static inline int free_aio_req(BDRVSheepdogState *s, AIOReq *aio_req)
398 SheepdogAIOCB *acb = aio_req->aiocb;
399 QLIST_REMOVE(aio_req, outstanding_aio_siblings);
400 QLIST_REMOVE(aio_req, aioreq_siblings);
401 g_free(aio_req);
403 return !QLIST_EMPTY(&acb->aioreq_head);
406 static void coroutine_fn sd_finish_aiocb(SheepdogAIOCB *acb)
408 if (!acb->canceled) {
409 qemu_coroutine_enter(acb->coroutine, NULL);
411 qemu_aio_release(acb);
414 static void sd_aio_cancel(BlockDriverAIOCB *blockacb)
416 SheepdogAIOCB *acb = (SheepdogAIOCB *)blockacb;
419 * Sheepdog cannot cancel the requests which are already sent to
420 * the servers, so we just complete the request with -EIO here.
422 acb->ret = -EIO;
423 qemu_coroutine_enter(acb->coroutine, NULL);
424 acb->canceled = 1;
427 static AIOPool sd_aio_pool = {
428 .aiocb_size = sizeof(SheepdogAIOCB),
429 .cancel = sd_aio_cancel,
432 static SheepdogAIOCB *sd_aio_setup(BlockDriverState *bs, QEMUIOVector *qiov,
433 int64_t sector_num, int nb_sectors,
434 BlockDriverCompletionFunc *cb, void *opaque)
436 SheepdogAIOCB *acb;
438 acb = qemu_aio_get(&sd_aio_pool, bs, cb, opaque);
440 acb->qiov = qiov;
442 acb->sector_num = sector_num;
443 acb->nb_sectors = nb_sectors;
445 acb->aio_done_func = NULL;
446 acb->canceled = 0;
447 acb->coroutine = qemu_coroutine_self();
448 acb->ret = 0;
449 QLIST_INIT(&acb->aioreq_head);
450 return acb;
453 static int connect_to_sdog(const char *addr, const char *port)
455 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
456 int fd, ret;
457 struct addrinfo hints, *res, *res0;
459 if (!addr) {
460 addr = SD_DEFAULT_ADDR;
461 port = SD_DEFAULT_PORT;
464 memset(&hints, 0, sizeof(hints));
465 hints.ai_socktype = SOCK_STREAM;
467 ret = getaddrinfo(addr, port, &hints, &res0);
468 if (ret) {
469 error_report("unable to get address info %s, %s",
470 addr, strerror(errno));
471 return -1;
474 for (res = res0; res; res = res->ai_next) {
475 ret = getnameinfo(res->ai_addr, res->ai_addrlen, hbuf, sizeof(hbuf),
476 sbuf, sizeof(sbuf), NI_NUMERICHOST | NI_NUMERICSERV);
477 if (ret) {
478 continue;
481 fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
482 if (fd < 0) {
483 continue;
486 reconnect:
487 ret = connect(fd, res->ai_addr, res->ai_addrlen);
488 if (ret < 0) {
489 if (errno == EINTR) {
490 goto reconnect;
492 break;
495 dprintf("connected to %s:%s\n", addr, port);
496 goto success;
498 fd = -1;
499 error_report("failed connect to %s:%s", addr, port);
500 success:
501 freeaddrinfo(res0);
502 return fd;
505 static int send_req(int sockfd, SheepdogReq *hdr, void *data,
506 unsigned int *wlen)
508 int ret;
510 ret = qemu_send_full(sockfd, hdr, sizeof(*hdr), 0);
511 if (ret < sizeof(*hdr)) {
512 error_report("failed to send a req, %s", strerror(errno));
513 return ret;
516 ret = qemu_send_full(sockfd, data, *wlen, 0);
517 if (ret < *wlen) {
518 error_report("failed to send a req, %s", strerror(errno));
521 return ret;
524 static int send_co_req(int sockfd, SheepdogReq *hdr, void *data,
525 unsigned int *wlen)
527 int ret;
529 ret = qemu_co_send(sockfd, hdr, sizeof(*hdr));
530 if (ret < sizeof(*hdr)) {
531 error_report("failed to send a req, %s", strerror(errno));
532 return ret;
535 ret = qemu_co_send(sockfd, data, *wlen);
536 if (ret < *wlen) {
537 error_report("failed to send a req, %s", strerror(errno));
540 return ret;
542 static int do_req(int sockfd, SheepdogReq *hdr, void *data,
543 unsigned int *wlen, unsigned int *rlen)
545 int ret;
547 socket_set_block(sockfd);
548 ret = send_req(sockfd, hdr, data, wlen);
549 if (ret < 0) {
550 goto out;
553 ret = qemu_recv_full(sockfd, hdr, sizeof(*hdr), 0);
554 if (ret < sizeof(*hdr)) {
555 error_report("failed to get a rsp, %s", strerror(errno));
556 goto out;
559 if (*rlen > hdr->data_length) {
560 *rlen = hdr->data_length;
563 if (*rlen) {
564 ret = qemu_recv_full(sockfd, data, *rlen, 0);
565 if (ret < *rlen) {
566 error_report("failed to get the data, %s", strerror(errno));
567 goto out;
570 ret = 0;
571 out:
572 socket_set_nonblock(sockfd);
573 return ret;
576 static int do_co_req(int sockfd, SheepdogReq *hdr, void *data,
577 unsigned int *wlen, unsigned int *rlen)
579 int ret;
581 socket_set_block(sockfd);
582 ret = send_co_req(sockfd, hdr, data, wlen);
583 if (ret < 0) {
584 goto out;
587 ret = qemu_co_recv(sockfd, hdr, sizeof(*hdr));
588 if (ret < sizeof(*hdr)) {
589 error_report("failed to get a rsp, %s", strerror(errno));
590 goto out;
593 if (*rlen > hdr->data_length) {
594 *rlen = hdr->data_length;
597 if (*rlen) {
598 ret = qemu_co_recv(sockfd, data, *rlen);
599 if (ret < *rlen) {
600 error_report("failed to get the data, %s", strerror(errno));
601 goto out;
604 ret = 0;
605 out:
606 socket_set_nonblock(sockfd);
607 return ret;
610 static int coroutine_fn add_aio_request(BDRVSheepdogState *s, AIOReq *aio_req,
611 struct iovec *iov, int niov, int create,
612 enum AIOCBState aiocb_type);
615 * This function searchs pending requests to the object `oid', and
616 * sends them.
618 static void coroutine_fn send_pending_req(BDRVSheepdogState *s, uint64_t oid, uint32_t id)
620 AIOReq *aio_req, *next;
621 SheepdogAIOCB *acb;
622 int ret;
624 QLIST_FOREACH_SAFE(aio_req, &s->outstanding_aio_head,
625 outstanding_aio_siblings, next) {
626 if (id == aio_req->id) {
627 continue;
629 if (aio_req->oid != oid) {
630 continue;
633 acb = aio_req->aiocb;
634 ret = add_aio_request(s, aio_req, acb->qiov->iov,
635 acb->qiov->niov, 0, acb->aiocb_type);
636 if (ret < 0) {
637 error_report("add_aio_request is failed");
638 free_aio_req(s, aio_req);
639 if (QLIST_EMPTY(&acb->aioreq_head)) {
640 sd_finish_aiocb(acb);
647 * Receive responses of the I/O requests.
649 * This function is registered as a fd handler, and called from the
650 * main loop when s->fd is ready for reading responses.
652 static void coroutine_fn aio_read_response(void *opaque)
654 SheepdogObjRsp rsp;
655 BDRVSheepdogState *s = opaque;
656 int fd = s->fd;
657 int ret;
658 AIOReq *aio_req = NULL;
659 SheepdogAIOCB *acb;
660 int rest;
661 unsigned long idx;
663 if (QLIST_EMPTY(&s->outstanding_aio_head)) {
664 goto out;
667 /* read a header */
668 ret = qemu_co_recv(fd, &rsp, sizeof(rsp));
669 if (ret < 0) {
670 error_report("failed to get the header, %s", strerror(errno));
671 goto out;
674 /* find the right aio_req from the outstanding_aio list */
675 QLIST_FOREACH(aio_req, &s->outstanding_aio_head, outstanding_aio_siblings) {
676 if (aio_req->id == rsp.id) {
677 break;
680 if (!aio_req) {
681 error_report("cannot find aio_req %x", rsp.id);
682 goto out;
685 acb = aio_req->aiocb;
687 switch (acb->aiocb_type) {
688 case AIOCB_WRITE_UDATA:
689 /* this coroutine context is no longer suitable for co_recv
690 * because we may send data to update vdi objects */
691 s->co_recv = NULL;
692 if (!is_data_obj(aio_req->oid)) {
693 break;
695 idx = data_oid_to_idx(aio_req->oid);
697 if (s->inode.data_vdi_id[idx] != s->inode.vdi_id) {
699 * If the object is newly created one, we need to update
700 * the vdi object (metadata object). min_dirty_data_idx
701 * and max_dirty_data_idx are changed to include updated
702 * index between them.
704 s->inode.data_vdi_id[idx] = s->inode.vdi_id;
705 s->max_dirty_data_idx = MAX(idx, s->max_dirty_data_idx);
706 s->min_dirty_data_idx = MIN(idx, s->min_dirty_data_idx);
709 * Some requests may be blocked because simultaneous
710 * create requests are not allowed, so we search the
711 * pending requests here.
713 send_pending_req(s, vid_to_data_oid(s->inode.vdi_id, idx), rsp.id);
715 break;
716 case AIOCB_READ_UDATA:
717 ret = qemu_co_recvv(fd, acb->qiov->iov, rsp.data_length,
718 aio_req->iov_offset);
719 if (ret < 0) {
720 error_report("failed to get the data, %s", strerror(errno));
721 goto out;
723 break;
726 if (rsp.result != SD_RES_SUCCESS) {
727 acb->ret = -EIO;
728 error_report("%s", sd_strerror(rsp.result));
731 rest = free_aio_req(s, aio_req);
732 if (!rest) {
734 * We've finished all requests which belong to the AIOCB, so
735 * we can switch back to sd_co_readv/writev now.
737 acb->aio_done_func(acb);
739 out:
740 s->co_recv = NULL;
743 static void co_read_response(void *opaque)
745 BDRVSheepdogState *s = opaque;
747 if (!s->co_recv) {
748 s->co_recv = qemu_coroutine_create(aio_read_response);
751 qemu_coroutine_enter(s->co_recv, opaque);
754 static void co_write_request(void *opaque)
756 BDRVSheepdogState *s = opaque;
758 qemu_coroutine_enter(s->co_send, NULL);
761 static int aio_flush_request(void *opaque)
763 BDRVSheepdogState *s = opaque;
765 return !QLIST_EMPTY(&s->outstanding_aio_head);
768 static int set_nodelay(int fd)
770 int ret, opt;
772 opt = 1;
773 ret = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&opt, sizeof(opt));
774 return ret;
778 * Return a socket discriptor to read/write objects.
780 * We cannot use this discriptor for other operations because
781 * the block driver may be on waiting response from the server.
783 static int get_sheep_fd(BDRVSheepdogState *s)
785 int ret, fd;
787 fd = connect_to_sdog(s->addr, s->port);
788 if (fd < 0) {
789 error_report("%s", strerror(errno));
790 return -1;
793 socket_set_nonblock(fd);
795 ret = set_nodelay(fd);
796 if (ret) {
797 error_report("%s", strerror(errno));
798 closesocket(fd);
799 return -1;
802 qemu_aio_set_fd_handler(fd, co_read_response, NULL, aio_flush_request,
803 NULL, s);
804 return fd;
808 * Parse a filename
810 * filename must be one of the following formats:
811 * 1. [vdiname]
812 * 2. [vdiname]:[snapid]
813 * 3. [vdiname]:[tag]
814 * 4. [hostname]:[port]:[vdiname]
815 * 5. [hostname]:[port]:[vdiname]:[snapid]
816 * 6. [hostname]:[port]:[vdiname]:[tag]
818 * You can boot from the snapshot images by specifying `snapid` or
819 * `tag'.
821 * You can run VMs outside the Sheepdog cluster by specifying
822 * `hostname' and `port' (experimental).
824 static int parse_vdiname(BDRVSheepdogState *s, const char *filename,
825 char *vdi, uint32_t *snapid, char *tag)
827 char *p, *q;
828 int nr_sep;
830 p = q = g_strdup(filename);
832 /* count the number of separators */
833 nr_sep = 0;
834 while (*p) {
835 if (*p == ':') {
836 nr_sep++;
838 p++;
840 p = q;
842 /* use the first two tokens as hostname and port number. */
843 if (nr_sep >= 2) {
844 s->addr = p;
845 p = strchr(p, ':');
846 *p++ = '\0';
848 s->port = p;
849 p = strchr(p, ':');
850 *p++ = '\0';
851 } else {
852 s->addr = NULL;
853 s->port = 0;
856 strncpy(vdi, p, SD_MAX_VDI_LEN);
858 p = strchr(vdi, ':');
859 if (p) {
860 *p++ = '\0';
861 *snapid = strtoul(p, NULL, 10);
862 if (*snapid == 0) {
863 strncpy(tag, p, SD_MAX_VDI_TAG_LEN);
865 } else {
866 *snapid = CURRENT_VDI_ID; /* search current vdi */
869 if (s->addr == NULL) {
870 g_free(q);
873 return 0;
876 static int find_vdi_name(BDRVSheepdogState *s, char *filename, uint32_t snapid,
877 char *tag, uint32_t *vid, int for_snapshot)
879 int ret, fd;
880 SheepdogVdiReq hdr;
881 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
882 unsigned int wlen, rlen = 0;
883 char buf[SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN];
885 fd = connect_to_sdog(s->addr, s->port);
886 if (fd < 0) {
887 return -1;
890 memset(buf, 0, sizeof(buf));
891 strncpy(buf, filename, SD_MAX_VDI_LEN);
892 strncpy(buf + SD_MAX_VDI_LEN, tag, SD_MAX_VDI_TAG_LEN);
894 memset(&hdr, 0, sizeof(hdr));
895 if (for_snapshot) {
896 hdr.opcode = SD_OP_GET_VDI_INFO;
897 } else {
898 hdr.opcode = SD_OP_LOCK_VDI;
900 wlen = SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN;
901 hdr.proto_ver = SD_PROTO_VER;
902 hdr.data_length = wlen;
903 hdr.snapid = snapid;
904 hdr.flags = SD_FLAG_CMD_WRITE;
906 ret = do_req(fd, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
907 if (ret) {
908 ret = -1;
909 goto out;
912 if (rsp->result != SD_RES_SUCCESS) {
913 error_report("cannot get vdi info, %s, %s %d %s",
914 sd_strerror(rsp->result), filename, snapid, tag);
915 ret = -1;
916 goto out;
918 *vid = rsp->vdi_id;
920 ret = 0;
921 out:
922 closesocket(fd);
923 return ret;
926 static int coroutine_fn add_aio_request(BDRVSheepdogState *s, AIOReq *aio_req,
927 struct iovec *iov, int niov, int create,
928 enum AIOCBState aiocb_type)
930 int nr_copies = s->inode.nr_copies;
931 SheepdogObjReq hdr;
932 unsigned int wlen;
933 int ret;
934 uint64_t oid = aio_req->oid;
935 unsigned int datalen = aio_req->data_len;
936 uint64_t offset = aio_req->offset;
937 uint8_t flags = aio_req->flags;
938 uint64_t old_oid = aio_req->base_oid;
940 if (!nr_copies) {
941 error_report("bug");
944 memset(&hdr, 0, sizeof(hdr));
946 if (aiocb_type == AIOCB_READ_UDATA) {
947 wlen = 0;
948 hdr.opcode = SD_OP_READ_OBJ;
949 hdr.flags = flags;
950 } else if (create) {
951 wlen = datalen;
952 hdr.opcode = SD_OP_CREATE_AND_WRITE_OBJ;
953 hdr.flags = SD_FLAG_CMD_WRITE | flags;
954 } else {
955 wlen = datalen;
956 hdr.opcode = SD_OP_WRITE_OBJ;
957 hdr.flags = SD_FLAG_CMD_WRITE | flags;
960 if (s->cache_enabled) {
961 hdr.flags |= SD_FLAG_CMD_CACHE;
964 hdr.oid = oid;
965 hdr.cow_oid = old_oid;
966 hdr.copies = s->inode.nr_copies;
968 hdr.data_length = datalen;
969 hdr.offset = offset;
971 hdr.id = aio_req->id;
973 qemu_co_mutex_lock(&s->lock);
974 s->co_send = qemu_coroutine_self();
975 qemu_aio_set_fd_handler(s->fd, co_read_response, co_write_request,
976 aio_flush_request, NULL, s);
977 socket_set_cork(s->fd, 1);
979 /* send a header */
980 ret = qemu_co_send(s->fd, &hdr, sizeof(hdr));
981 if (ret < 0) {
982 qemu_co_mutex_unlock(&s->lock);
983 error_report("failed to send a req, %s", strerror(errno));
984 return -EIO;
987 if (wlen) {
988 ret = qemu_co_sendv(s->fd, iov, wlen, aio_req->iov_offset);
989 if (ret < 0) {
990 qemu_co_mutex_unlock(&s->lock);
991 error_report("failed to send a data, %s", strerror(errno));
992 return -EIO;
996 socket_set_cork(s->fd, 0);
997 qemu_aio_set_fd_handler(s->fd, co_read_response, NULL,
998 aio_flush_request, NULL, s);
999 qemu_co_mutex_unlock(&s->lock);
1001 return 0;
1004 static int read_write_object(int fd, char *buf, uint64_t oid, int copies,
1005 unsigned int datalen, uint64_t offset,
1006 int write, int create, uint8_t cache)
1008 SheepdogObjReq hdr;
1009 SheepdogObjRsp *rsp = (SheepdogObjRsp *)&hdr;
1010 unsigned int wlen, rlen;
1011 int ret;
1013 memset(&hdr, 0, sizeof(hdr));
1015 if (write) {
1016 wlen = datalen;
1017 rlen = 0;
1018 hdr.flags = SD_FLAG_CMD_WRITE;
1019 if (create) {
1020 hdr.opcode = SD_OP_CREATE_AND_WRITE_OBJ;
1021 } else {
1022 hdr.opcode = SD_OP_WRITE_OBJ;
1024 } else {
1025 wlen = 0;
1026 rlen = datalen;
1027 hdr.opcode = SD_OP_READ_OBJ;
1030 if (cache) {
1031 hdr.flags |= SD_FLAG_CMD_CACHE;
1034 hdr.oid = oid;
1035 hdr.data_length = datalen;
1036 hdr.offset = offset;
1037 hdr.copies = copies;
1039 ret = do_req(fd, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
1040 if (ret) {
1041 error_report("failed to send a request to the sheep");
1042 return -1;
1045 switch (rsp->result) {
1046 case SD_RES_SUCCESS:
1047 return 0;
1048 default:
1049 error_report("%s", sd_strerror(rsp->result));
1050 return -1;
1054 static int read_object(int fd, char *buf, uint64_t oid, int copies,
1055 unsigned int datalen, uint64_t offset, uint8_t cache)
1057 return read_write_object(fd, buf, oid, copies, datalen, offset, 0, 0,
1058 cache);
1061 static int write_object(int fd, char *buf, uint64_t oid, int copies,
1062 unsigned int datalen, uint64_t offset, int create,
1063 uint8_t cache)
1065 return read_write_object(fd, buf, oid, copies, datalen, offset, 1, create,
1066 cache);
1069 static int sd_open(BlockDriverState *bs, const char *filename, int flags)
1071 int ret, fd;
1072 uint32_t vid = 0;
1073 BDRVSheepdogState *s = bs->opaque;
1074 char vdi[SD_MAX_VDI_LEN], tag[SD_MAX_VDI_TAG_LEN];
1075 uint32_t snapid;
1076 char *buf = NULL;
1078 strstart(filename, "sheepdog:", (const char **)&filename);
1080 QLIST_INIT(&s->outstanding_aio_head);
1081 s->fd = -1;
1083 memset(vdi, 0, sizeof(vdi));
1084 memset(tag, 0, sizeof(tag));
1085 if (parse_vdiname(s, filename, vdi, &snapid, tag) < 0) {
1086 goto out;
1088 s->fd = get_sheep_fd(s);
1089 if (s->fd < 0) {
1090 goto out;
1093 ret = find_vdi_name(s, vdi, snapid, tag, &vid, 0);
1094 if (ret) {
1095 goto out;
1098 if (flags & BDRV_O_CACHE_WB) {
1099 s->cache_enabled = 1;
1100 s->flush_fd = connect_to_sdog(s->addr, s->port);
1101 if (s->flush_fd < 0) {
1102 error_report("failed to connect");
1103 goto out;
1107 if (snapid) {
1108 dprintf("%" PRIx32 " snapshot inode was open.\n", vid);
1109 s->is_snapshot = 1;
1112 fd = connect_to_sdog(s->addr, s->port);
1113 if (fd < 0) {
1114 error_report("failed to connect");
1115 goto out;
1118 buf = g_malloc(SD_INODE_SIZE);
1119 ret = read_object(fd, buf, vid_to_vdi_oid(vid), 0, SD_INODE_SIZE, 0,
1120 s->cache_enabled);
1122 closesocket(fd);
1124 if (ret) {
1125 goto out;
1128 memcpy(&s->inode, buf, sizeof(s->inode));
1129 s->min_dirty_data_idx = UINT32_MAX;
1130 s->max_dirty_data_idx = 0;
1132 bs->total_sectors = s->inode.vdi_size / SECTOR_SIZE;
1133 strncpy(s->name, vdi, sizeof(s->name));
1134 qemu_co_mutex_init(&s->lock);
1135 g_free(buf);
1136 return 0;
1137 out:
1138 qemu_aio_set_fd_handler(s->fd, NULL, NULL, NULL, NULL, NULL);
1139 if (s->fd >= 0) {
1140 closesocket(s->fd);
1142 g_free(buf);
1143 return -1;
1146 static int do_sd_create(char *filename, int64_t vdi_size,
1147 uint32_t base_vid, uint32_t *vdi_id, int snapshot,
1148 const char *addr, const char *port)
1150 SheepdogVdiReq hdr;
1151 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
1152 int fd, ret;
1153 unsigned int wlen, rlen = 0;
1154 char buf[SD_MAX_VDI_LEN];
1156 fd = connect_to_sdog(addr, port);
1157 if (fd < 0) {
1158 return -EIO;
1161 memset(buf, 0, sizeof(buf));
1162 strncpy(buf, filename, SD_MAX_VDI_LEN);
1164 memset(&hdr, 0, sizeof(hdr));
1165 hdr.opcode = SD_OP_NEW_VDI;
1166 hdr.base_vdi_id = base_vid;
1168 wlen = SD_MAX_VDI_LEN;
1170 hdr.flags = SD_FLAG_CMD_WRITE;
1171 hdr.snapid = snapshot;
1173 hdr.data_length = wlen;
1174 hdr.vdi_size = vdi_size;
1176 ret = do_req(fd, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
1178 closesocket(fd);
1180 if (ret) {
1181 return -EIO;
1184 if (rsp->result != SD_RES_SUCCESS) {
1185 error_report("%s, %s", sd_strerror(rsp->result), filename);
1186 return -EIO;
1189 if (vdi_id) {
1190 *vdi_id = rsp->vdi_id;
1193 return 0;
1196 static int sd_prealloc(const char *filename)
1198 BlockDriverState *bs = NULL;
1199 uint32_t idx, max_idx;
1200 int64_t vdi_size;
1201 void *buf = g_malloc0(SD_DATA_OBJ_SIZE);
1202 int ret;
1204 ret = bdrv_file_open(&bs, filename, BDRV_O_RDWR);
1205 if (ret < 0) {
1206 goto out;
1209 vdi_size = bdrv_getlength(bs);
1210 if (vdi_size < 0) {
1211 ret = vdi_size;
1212 goto out;
1214 max_idx = DIV_ROUND_UP(vdi_size, SD_DATA_OBJ_SIZE);
1216 for (idx = 0; idx < max_idx; idx++) {
1218 * The created image can be a cloned image, so we need to read
1219 * a data from the source image.
1221 ret = bdrv_pread(bs, idx * SD_DATA_OBJ_SIZE, buf, SD_DATA_OBJ_SIZE);
1222 if (ret < 0) {
1223 goto out;
1225 ret = bdrv_pwrite(bs, idx * SD_DATA_OBJ_SIZE, buf, SD_DATA_OBJ_SIZE);
1226 if (ret < 0) {
1227 goto out;
1230 out:
1231 if (bs) {
1232 bdrv_delete(bs);
1234 g_free(buf);
1236 return ret;
1239 static int sd_create(const char *filename, QEMUOptionParameter *options)
1241 int ret;
1242 uint32_t vid = 0, base_vid = 0;
1243 int64_t vdi_size = 0;
1244 char *backing_file = NULL;
1245 BDRVSheepdogState s;
1246 char vdi[SD_MAX_VDI_LEN], tag[SD_MAX_VDI_TAG_LEN];
1247 uint32_t snapid;
1248 int prealloc = 0;
1249 const char *vdiname;
1251 strstart(filename, "sheepdog:", &vdiname);
1253 memset(&s, 0, sizeof(s));
1254 memset(vdi, 0, sizeof(vdi));
1255 memset(tag, 0, sizeof(tag));
1256 if (parse_vdiname(&s, vdiname, vdi, &snapid, tag) < 0) {
1257 error_report("invalid filename");
1258 return -EINVAL;
1261 while (options && options->name) {
1262 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
1263 vdi_size = options->value.n;
1264 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
1265 backing_file = options->value.s;
1266 } else if (!strcmp(options->name, BLOCK_OPT_PREALLOC)) {
1267 if (!options->value.s || !strcmp(options->value.s, "off")) {
1268 prealloc = 0;
1269 } else if (!strcmp(options->value.s, "full")) {
1270 prealloc = 1;
1271 } else {
1272 error_report("Invalid preallocation mode: '%s'",
1273 options->value.s);
1274 return -EINVAL;
1277 options++;
1280 if (vdi_size > SD_MAX_VDI_SIZE) {
1281 error_report("too big image size");
1282 return -EINVAL;
1285 if (backing_file) {
1286 BlockDriverState *bs;
1287 BDRVSheepdogState *s;
1288 BlockDriver *drv;
1290 /* Currently, only Sheepdog backing image is supported. */
1291 drv = bdrv_find_protocol(backing_file);
1292 if (!drv || strcmp(drv->protocol_name, "sheepdog") != 0) {
1293 error_report("backing_file must be a sheepdog image");
1294 return -EINVAL;
1297 ret = bdrv_file_open(&bs, backing_file, 0);
1298 if (ret < 0)
1299 return -EIO;
1301 s = bs->opaque;
1303 if (!is_snapshot(&s->inode)) {
1304 error_report("cannot clone from a non snapshot vdi");
1305 bdrv_delete(bs);
1306 return -EINVAL;
1309 base_vid = s->inode.vdi_id;
1310 bdrv_delete(bs);
1313 ret = do_sd_create(vdi, vdi_size, base_vid, &vid, 0, s.addr, s.port);
1314 if (!prealloc || ret) {
1315 return ret;
1318 return sd_prealloc(filename);
1321 static void sd_close(BlockDriverState *bs)
1323 BDRVSheepdogState *s = bs->opaque;
1324 SheepdogVdiReq hdr;
1325 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
1326 unsigned int wlen, rlen = 0;
1327 int fd, ret;
1329 dprintf("%s\n", s->name);
1331 fd = connect_to_sdog(s->addr, s->port);
1332 if (fd < 0) {
1333 return;
1336 memset(&hdr, 0, sizeof(hdr));
1338 hdr.opcode = SD_OP_RELEASE_VDI;
1339 wlen = strlen(s->name) + 1;
1340 hdr.data_length = wlen;
1341 hdr.flags = SD_FLAG_CMD_WRITE;
1343 ret = do_req(fd, (SheepdogReq *)&hdr, s->name, &wlen, &rlen);
1345 closesocket(fd);
1347 if (!ret && rsp->result != SD_RES_SUCCESS &&
1348 rsp->result != SD_RES_VDI_NOT_LOCKED) {
1349 error_report("%s, %s", sd_strerror(rsp->result), s->name);
1352 qemu_aio_set_fd_handler(s->fd, NULL, NULL, NULL, NULL, NULL);
1353 closesocket(s->fd);
1354 if (s->cache_enabled) {
1355 closesocket(s->flush_fd);
1357 g_free(s->addr);
1360 static int64_t sd_getlength(BlockDriverState *bs)
1362 BDRVSheepdogState *s = bs->opaque;
1364 return s->inode.vdi_size;
1367 static int sd_truncate(BlockDriverState *bs, int64_t offset)
1369 BDRVSheepdogState *s = bs->opaque;
1370 int ret, fd;
1371 unsigned int datalen;
1373 if (offset < s->inode.vdi_size) {
1374 error_report("shrinking is not supported");
1375 return -EINVAL;
1376 } else if (offset > SD_MAX_VDI_SIZE) {
1377 error_report("too big image size");
1378 return -EINVAL;
1381 fd = connect_to_sdog(s->addr, s->port);
1382 if (fd < 0) {
1383 return -EIO;
1386 /* we don't need to update entire object */
1387 datalen = SD_INODE_SIZE - sizeof(s->inode.data_vdi_id);
1388 s->inode.vdi_size = offset;
1389 ret = write_object(fd, (char *)&s->inode, vid_to_vdi_oid(s->inode.vdi_id),
1390 s->inode.nr_copies, datalen, 0, 0, s->cache_enabled);
1391 close(fd);
1393 if (ret < 0) {
1394 error_report("failed to update an inode.");
1395 return -EIO;
1398 return 0;
1402 * This function is called after writing data objects. If we need to
1403 * update metadata, this sends a write request to the vdi object.
1404 * Otherwise, this switches back to sd_co_readv/writev.
1406 static void coroutine_fn sd_write_done(SheepdogAIOCB *acb)
1408 int ret;
1409 BDRVSheepdogState *s = acb->common.bs->opaque;
1410 struct iovec iov;
1411 AIOReq *aio_req;
1412 uint32_t offset, data_len, mn, mx;
1414 mn = s->min_dirty_data_idx;
1415 mx = s->max_dirty_data_idx;
1416 if (mn <= mx) {
1417 /* we need to update the vdi object. */
1418 offset = sizeof(s->inode) - sizeof(s->inode.data_vdi_id) +
1419 mn * sizeof(s->inode.data_vdi_id[0]);
1420 data_len = (mx - mn + 1) * sizeof(s->inode.data_vdi_id[0]);
1422 s->min_dirty_data_idx = UINT32_MAX;
1423 s->max_dirty_data_idx = 0;
1425 iov.iov_base = &s->inode;
1426 iov.iov_len = sizeof(s->inode);
1427 aio_req = alloc_aio_req(s, acb, vid_to_vdi_oid(s->inode.vdi_id),
1428 data_len, offset, 0, 0, offset);
1429 ret = add_aio_request(s, aio_req, &iov, 1, 0, AIOCB_WRITE_UDATA);
1430 if (ret) {
1431 free_aio_req(s, aio_req);
1432 acb->ret = -EIO;
1433 goto out;
1436 acb->aio_done_func = sd_finish_aiocb;
1437 acb->aiocb_type = AIOCB_WRITE_UDATA;
1438 return;
1440 out:
1441 sd_finish_aiocb(acb);
1445 * Create a writable VDI from a snapshot
1447 static int sd_create_branch(BDRVSheepdogState *s)
1449 int ret, fd;
1450 uint32_t vid;
1451 char *buf;
1453 dprintf("%" PRIx32 " is snapshot.\n", s->inode.vdi_id);
1455 buf = g_malloc(SD_INODE_SIZE);
1457 ret = do_sd_create(s->name, s->inode.vdi_size, s->inode.vdi_id, &vid, 1,
1458 s->addr, s->port);
1459 if (ret) {
1460 goto out;
1463 dprintf("%" PRIx32 " is created.\n", vid);
1465 fd = connect_to_sdog(s->addr, s->port);
1466 if (fd < 0) {
1467 error_report("failed to connect");
1468 goto out;
1471 ret = read_object(fd, buf, vid_to_vdi_oid(vid), s->inode.nr_copies,
1472 SD_INODE_SIZE, 0, s->cache_enabled);
1474 closesocket(fd);
1476 if (ret < 0) {
1477 goto out;
1480 memcpy(&s->inode, buf, sizeof(s->inode));
1482 s->is_snapshot = 0;
1483 ret = 0;
1484 dprintf("%" PRIx32 " was newly created.\n", s->inode.vdi_id);
1486 out:
1487 g_free(buf);
1489 return ret;
1493 * Send I/O requests to the server.
1495 * This function sends requests to the server, links the requests to
1496 * the outstanding_list in BDRVSheepdogState, and exits without
1497 * waiting the response. The responses are received in the
1498 * `aio_read_response' function which is called from the main loop as
1499 * a fd handler.
1501 * Returns 1 when we need to wait a response, 0 when there is no sent
1502 * request and -errno in error cases.
1504 static int coroutine_fn sd_co_rw_vector(void *p)
1506 SheepdogAIOCB *acb = p;
1507 int ret = 0;
1508 unsigned long len, done = 0, total = acb->nb_sectors * SECTOR_SIZE;
1509 unsigned long idx = acb->sector_num * SECTOR_SIZE / SD_DATA_OBJ_SIZE;
1510 uint64_t oid;
1511 uint64_t offset = (acb->sector_num * SECTOR_SIZE) % SD_DATA_OBJ_SIZE;
1512 BDRVSheepdogState *s = acb->common.bs->opaque;
1513 SheepdogInode *inode = &s->inode;
1514 AIOReq *aio_req;
1516 if (acb->aiocb_type == AIOCB_WRITE_UDATA && s->is_snapshot) {
1518 * In the case we open the snapshot VDI, Sheepdog creates the
1519 * writable VDI when we do a write operation first.
1521 ret = sd_create_branch(s);
1522 if (ret) {
1523 acb->ret = -EIO;
1524 goto out;
1528 while (done != total) {
1529 uint8_t flags = 0;
1530 uint64_t old_oid = 0;
1531 int create = 0;
1533 oid = vid_to_data_oid(inode->data_vdi_id[idx], idx);
1535 len = MIN(total - done, SD_DATA_OBJ_SIZE - offset);
1537 if (!inode->data_vdi_id[idx]) {
1538 if (acb->aiocb_type == AIOCB_READ_UDATA) {
1539 goto done;
1542 create = 1;
1543 } else if (acb->aiocb_type == AIOCB_WRITE_UDATA
1544 && !is_data_obj_writable(inode, idx)) {
1545 /* Copy-On-Write */
1546 create = 1;
1547 old_oid = oid;
1548 flags = SD_FLAG_CMD_COW;
1551 if (create) {
1552 dprintf("update ino (%" PRIu32") %" PRIu64 " %" PRIu64
1553 " %" PRIu64 "\n", inode->vdi_id, oid,
1554 vid_to_data_oid(inode->data_vdi_id[idx], idx), idx);
1555 oid = vid_to_data_oid(inode->vdi_id, idx);
1556 dprintf("new oid %lx\n", oid);
1559 aio_req = alloc_aio_req(s, acb, oid, len, offset, flags, old_oid, done);
1561 if (create) {
1562 AIOReq *areq;
1563 QLIST_FOREACH(areq, &s->outstanding_aio_head,
1564 outstanding_aio_siblings) {
1565 if (areq == aio_req) {
1566 continue;
1568 if (areq->oid == oid) {
1570 * Sheepdog cannot handle simultaneous create
1571 * requests to the same object. So we cannot send
1572 * the request until the previous request
1573 * finishes.
1575 aio_req->flags = 0;
1576 aio_req->base_oid = 0;
1577 goto done;
1582 ret = add_aio_request(s, aio_req, acb->qiov->iov, acb->qiov->niov,
1583 create, acb->aiocb_type);
1584 if (ret < 0) {
1585 error_report("add_aio_request is failed");
1586 free_aio_req(s, aio_req);
1587 acb->ret = -EIO;
1588 goto out;
1590 done:
1591 offset = 0;
1592 idx++;
1593 done += len;
1595 out:
1596 if (QLIST_EMPTY(&acb->aioreq_head)) {
1597 return acb->ret;
1599 return 1;
1602 static coroutine_fn int sd_co_writev(BlockDriverState *bs, int64_t sector_num,
1603 int nb_sectors, QEMUIOVector *qiov)
1605 SheepdogAIOCB *acb;
1606 int ret;
1608 if (bs->growable && sector_num + nb_sectors > bs->total_sectors) {
1609 /* TODO: shouldn't block here */
1610 if (sd_truncate(bs, (sector_num + nb_sectors) * SECTOR_SIZE) < 0) {
1611 return -EIO;
1613 bs->total_sectors = sector_num + nb_sectors;
1616 acb = sd_aio_setup(bs, qiov, sector_num, nb_sectors, NULL, NULL);
1617 acb->aio_done_func = sd_write_done;
1618 acb->aiocb_type = AIOCB_WRITE_UDATA;
1620 ret = sd_co_rw_vector(acb);
1621 if (ret <= 0) {
1622 qemu_aio_release(acb);
1623 return ret;
1626 qemu_coroutine_yield();
1628 return acb->ret;
1631 static coroutine_fn int sd_co_readv(BlockDriverState *bs, int64_t sector_num,
1632 int nb_sectors, QEMUIOVector *qiov)
1634 SheepdogAIOCB *acb;
1635 int i, ret;
1637 acb = sd_aio_setup(bs, qiov, sector_num, nb_sectors, NULL, NULL);
1638 acb->aiocb_type = AIOCB_READ_UDATA;
1639 acb->aio_done_func = sd_finish_aiocb;
1642 * TODO: we can do better; we don't need to initialize
1643 * blindly.
1645 for (i = 0; i < qiov->niov; i++) {
1646 memset(qiov->iov[i].iov_base, 0, qiov->iov[i].iov_len);
1649 ret = sd_co_rw_vector(acb);
1650 if (ret <= 0) {
1651 qemu_aio_release(acb);
1652 return ret;
1655 qemu_coroutine_yield();
1657 return acb->ret;
1660 static int coroutine_fn sd_co_flush_to_disk(BlockDriverState *bs)
1662 BDRVSheepdogState *s = bs->opaque;
1663 SheepdogObjReq hdr = { 0 };
1664 SheepdogObjRsp *rsp = (SheepdogObjRsp *)&hdr;
1665 SheepdogInode *inode = &s->inode;
1666 int ret;
1667 unsigned int wlen = 0, rlen = 0;
1669 if (!s->cache_enabled) {
1670 return 0;
1673 hdr.opcode = SD_OP_FLUSH_VDI;
1674 hdr.oid = vid_to_vdi_oid(inode->vdi_id);
1676 ret = do_co_req(s->flush_fd, (SheepdogReq *)&hdr, NULL, &wlen, &rlen);
1677 if (ret) {
1678 error_report("failed to send a request to the sheep");
1679 return ret;
1682 if (rsp->result != SD_RES_SUCCESS) {
1683 error_report("%s", sd_strerror(rsp->result));
1684 return -EIO;
1687 return 0;
1690 static int sd_snapshot_create(BlockDriverState *bs, QEMUSnapshotInfo *sn_info)
1692 BDRVSheepdogState *s = bs->opaque;
1693 int ret, fd;
1694 uint32_t new_vid;
1695 SheepdogInode *inode;
1696 unsigned int datalen;
1698 dprintf("sn_info: name %s id_str %s s: name %s vm_state_size %d "
1699 "is_snapshot %d\n", sn_info->name, sn_info->id_str,
1700 s->name, sn_info->vm_state_size, s->is_snapshot);
1702 if (s->is_snapshot) {
1703 error_report("You can't create a snapshot of a snapshot VDI, "
1704 "%s (%" PRIu32 ").", s->name, s->inode.vdi_id);
1706 return -EINVAL;
1709 dprintf("%s %s\n", sn_info->name, sn_info->id_str);
1711 s->inode.vm_state_size = sn_info->vm_state_size;
1712 s->inode.vm_clock_nsec = sn_info->vm_clock_nsec;
1713 strncpy(s->inode.tag, sn_info->name, sizeof(s->inode.tag));
1714 /* we don't need to update entire object */
1715 datalen = SD_INODE_SIZE - sizeof(s->inode.data_vdi_id);
1717 /* refresh inode. */
1718 fd = connect_to_sdog(s->addr, s->port);
1719 if (fd < 0) {
1720 ret = -EIO;
1721 goto cleanup;
1724 ret = write_object(fd, (char *)&s->inode, vid_to_vdi_oid(s->inode.vdi_id),
1725 s->inode.nr_copies, datalen, 0, 0, s->cache_enabled);
1726 if (ret < 0) {
1727 error_report("failed to write snapshot's inode.");
1728 ret = -EIO;
1729 goto cleanup;
1732 ret = do_sd_create(s->name, s->inode.vdi_size, s->inode.vdi_id, &new_vid, 1,
1733 s->addr, s->port);
1734 if (ret < 0) {
1735 error_report("failed to create inode for snapshot. %s",
1736 strerror(errno));
1737 ret = -EIO;
1738 goto cleanup;
1741 inode = (SheepdogInode *)g_malloc(datalen);
1743 ret = read_object(fd, (char *)inode, vid_to_vdi_oid(new_vid),
1744 s->inode.nr_copies, datalen, 0, s->cache_enabled);
1746 if (ret < 0) {
1747 error_report("failed to read new inode info. %s", strerror(errno));
1748 ret = -EIO;
1749 goto cleanup;
1752 memcpy(&s->inode, inode, datalen);
1753 dprintf("s->inode: name %s snap_id %x oid %x\n",
1754 s->inode.name, s->inode.snap_id, s->inode.vdi_id);
1756 cleanup:
1757 closesocket(fd);
1758 return ret;
1761 static int sd_snapshot_goto(BlockDriverState *bs, const char *snapshot_id)
1763 BDRVSheepdogState *s = bs->opaque;
1764 BDRVSheepdogState *old_s;
1765 char vdi[SD_MAX_VDI_LEN], tag[SD_MAX_VDI_TAG_LEN];
1766 char *buf = NULL;
1767 uint32_t vid;
1768 uint32_t snapid = 0;
1769 int ret = -ENOENT, fd;
1771 old_s = g_malloc(sizeof(BDRVSheepdogState));
1773 memcpy(old_s, s, sizeof(BDRVSheepdogState));
1775 memset(vdi, 0, sizeof(vdi));
1776 strncpy(vdi, s->name, sizeof(vdi));
1778 memset(tag, 0, sizeof(tag));
1779 snapid = strtoul(snapshot_id, NULL, 10);
1780 if (!snapid) {
1781 strncpy(tag, s->name, sizeof(tag));
1784 ret = find_vdi_name(s, vdi, snapid, tag, &vid, 1);
1785 if (ret) {
1786 error_report("Failed to find_vdi_name");
1787 ret = -ENOENT;
1788 goto out;
1791 fd = connect_to_sdog(s->addr, s->port);
1792 if (fd < 0) {
1793 error_report("failed to connect");
1794 goto out;
1797 buf = g_malloc(SD_INODE_SIZE);
1798 ret = read_object(fd, buf, vid_to_vdi_oid(vid), s->inode.nr_copies,
1799 SD_INODE_SIZE, 0, s->cache_enabled);
1801 closesocket(fd);
1803 if (ret) {
1804 ret = -ENOENT;
1805 goto out;
1808 memcpy(&s->inode, buf, sizeof(s->inode));
1810 if (!s->inode.vm_state_size) {
1811 error_report("Invalid snapshot");
1812 ret = -ENOENT;
1813 goto out;
1816 s->is_snapshot = 1;
1818 g_free(buf);
1819 g_free(old_s);
1821 return 0;
1822 out:
1823 /* recover bdrv_sd_state */
1824 memcpy(s, old_s, sizeof(BDRVSheepdogState));
1825 g_free(buf);
1826 g_free(old_s);
1828 error_report("failed to open. recover old bdrv_sd_state.");
1830 return ret;
1833 static int sd_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
1835 /* FIXME: Delete specified snapshot id. */
1836 return 0;
1839 static int sd_snapshot_list(BlockDriverState *bs, QEMUSnapshotInfo **psn_tab)
1841 BDRVSheepdogState *s = bs->opaque;
1842 SheepdogReq req;
1843 int fd, nr = 1024, ret, max = BITS_TO_LONGS(SD_NR_VDIS) * sizeof(long);
1844 QEMUSnapshotInfo *sn_tab = NULL;
1845 unsigned wlen, rlen;
1846 int found = 0;
1847 static SheepdogInode inode;
1848 unsigned long *vdi_inuse;
1849 unsigned int start_nr;
1850 uint64_t hval;
1851 uint32_t vid;
1853 vdi_inuse = g_malloc(max);
1855 fd = connect_to_sdog(s->addr, s->port);
1856 if (fd < 0) {
1857 goto out;
1860 rlen = max;
1861 wlen = 0;
1863 memset(&req, 0, sizeof(req));
1865 req.opcode = SD_OP_READ_VDIS;
1866 req.data_length = max;
1868 ret = do_req(fd, (SheepdogReq *)&req, vdi_inuse, &wlen, &rlen);
1870 closesocket(fd);
1871 if (ret) {
1872 goto out;
1875 sn_tab = g_malloc0(nr * sizeof(*sn_tab));
1877 /* calculate a vdi id with hash function */
1878 hval = fnv_64a_buf(s->name, strlen(s->name), FNV1A_64_INIT);
1879 start_nr = hval & (SD_NR_VDIS - 1);
1881 fd = connect_to_sdog(s->addr, s->port);
1882 if (fd < 0) {
1883 error_report("failed to connect");
1884 goto out;
1887 for (vid = start_nr; found < nr; vid = (vid + 1) % SD_NR_VDIS) {
1888 if (!test_bit(vid, vdi_inuse)) {
1889 break;
1892 /* we don't need to read entire object */
1893 ret = read_object(fd, (char *)&inode, vid_to_vdi_oid(vid),
1894 0, SD_INODE_SIZE - sizeof(inode.data_vdi_id), 0,
1895 s->cache_enabled);
1897 if (ret) {
1898 continue;
1901 if (!strcmp(inode.name, s->name) && is_snapshot(&inode)) {
1902 sn_tab[found].date_sec = inode.snap_ctime >> 32;
1903 sn_tab[found].date_nsec = inode.snap_ctime & 0xffffffff;
1904 sn_tab[found].vm_state_size = inode.vm_state_size;
1905 sn_tab[found].vm_clock_nsec = inode.vm_clock_nsec;
1907 snprintf(sn_tab[found].id_str, sizeof(sn_tab[found].id_str), "%u",
1908 inode.snap_id);
1909 strncpy(sn_tab[found].name, inode.tag,
1910 MIN(sizeof(sn_tab[found].name), sizeof(inode.tag)));
1911 found++;
1915 closesocket(fd);
1916 out:
1917 *psn_tab = sn_tab;
1919 g_free(vdi_inuse);
1921 return found;
1924 static int do_load_save_vmstate(BDRVSheepdogState *s, uint8_t *data,
1925 int64_t pos, int size, int load)
1927 int fd, create;
1928 int ret = 0;
1929 unsigned int data_len;
1930 uint64_t vmstate_oid;
1931 uint32_t vdi_index;
1932 uint64_t offset;
1934 fd = connect_to_sdog(s->addr, s->port);
1935 if (fd < 0) {
1936 ret = -EIO;
1937 goto cleanup;
1940 while (size) {
1941 vdi_index = pos / SD_DATA_OBJ_SIZE;
1942 offset = pos % SD_DATA_OBJ_SIZE;
1944 data_len = MIN(size, SD_DATA_OBJ_SIZE);
1946 vmstate_oid = vid_to_vmstate_oid(s->inode.vdi_id, vdi_index);
1948 create = (offset == 0);
1949 if (load) {
1950 ret = read_object(fd, (char *)data, vmstate_oid,
1951 s->inode.nr_copies, data_len, offset,
1952 s->cache_enabled);
1953 } else {
1954 ret = write_object(fd, (char *)data, vmstate_oid,
1955 s->inode.nr_copies, data_len, offset, create,
1956 s->cache_enabled);
1959 if (ret < 0) {
1960 error_report("failed to save vmstate %s", strerror(errno));
1961 ret = -EIO;
1962 goto cleanup;
1965 pos += data_len;
1966 size -= data_len;
1967 ret += data_len;
1969 cleanup:
1970 closesocket(fd);
1971 return ret;
1974 static int sd_save_vmstate(BlockDriverState *bs, const uint8_t *data,
1975 int64_t pos, int size)
1977 BDRVSheepdogState *s = bs->opaque;
1979 return do_load_save_vmstate(s, (uint8_t *)data, pos, size, 0);
1982 static int sd_load_vmstate(BlockDriverState *bs, uint8_t *data,
1983 int64_t pos, int size)
1985 BDRVSheepdogState *s = bs->opaque;
1987 return do_load_save_vmstate(s, data, pos, size, 1);
1991 static QEMUOptionParameter sd_create_options[] = {
1993 .name = BLOCK_OPT_SIZE,
1994 .type = OPT_SIZE,
1995 .help = "Virtual disk size"
1998 .name = BLOCK_OPT_BACKING_FILE,
1999 .type = OPT_STRING,
2000 .help = "File name of a base image"
2003 .name = BLOCK_OPT_PREALLOC,
2004 .type = OPT_STRING,
2005 .help = "Preallocation mode (allowed values: off, full)"
2007 { NULL }
2010 BlockDriver bdrv_sheepdog = {
2011 .format_name = "sheepdog",
2012 .protocol_name = "sheepdog",
2013 .instance_size = sizeof(BDRVSheepdogState),
2014 .bdrv_file_open = sd_open,
2015 .bdrv_close = sd_close,
2016 .bdrv_create = sd_create,
2017 .bdrv_getlength = sd_getlength,
2018 .bdrv_truncate = sd_truncate,
2020 .bdrv_co_readv = sd_co_readv,
2021 .bdrv_co_writev = sd_co_writev,
2022 .bdrv_co_flush_to_disk = sd_co_flush_to_disk,
2024 .bdrv_snapshot_create = sd_snapshot_create,
2025 .bdrv_snapshot_goto = sd_snapshot_goto,
2026 .bdrv_snapshot_delete = sd_snapshot_delete,
2027 .bdrv_snapshot_list = sd_snapshot_list,
2029 .bdrv_save_vmstate = sd_save_vmstate,
2030 .bdrv_load_vmstate = sd_load_vmstate,
2032 .create_options = sd_create_options,
2035 static void bdrv_sheepdog_init(void)
2037 bdrv_register(&bdrv_sheepdog);
2039 block_init(bdrv_sheepdog_init);