qemu-log: fix x86 and user logging
[qemu/ar7.git] / block / sheepdog.c
blob809df39d9e7dd22010c82e71d3ba9c68ae616ceb
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) aio_siblings;
263 } AIOReq;
265 enum AIOCBState {
266 AIOCB_WRITE_UDATA,
267 AIOCB_READ_UDATA,
270 struct SheepdogAIOCB {
271 BlockDriverAIOCB common;
273 QEMUIOVector *qiov;
275 int64_t sector_num;
276 int nb_sectors;
278 int ret;
279 enum AIOCBState aiocb_type;
281 Coroutine *coroutine;
282 void (*aio_done_func)(SheepdogAIOCB *);
284 int canceled;
285 int nr_pending;
288 typedef struct BDRVSheepdogState {
289 SheepdogInode inode;
291 uint32_t min_dirty_data_idx;
292 uint32_t max_dirty_data_idx;
294 char name[SD_MAX_VDI_LEN];
295 int is_snapshot;
296 uint8_t cache_enabled;
298 char *addr;
299 char *port;
300 int fd;
301 int flush_fd;
303 CoMutex lock;
304 Coroutine *co_send;
305 Coroutine *co_recv;
307 uint32_t aioreq_seq_num;
308 QLIST_HEAD(inflight_aio_head, AIOReq) inflight_aio_head;
309 QLIST_HEAD(pending_aio_head, AIOReq) pending_aio_head;
310 } BDRVSheepdogState;
312 static const char * sd_strerror(int err)
314 int i;
316 static const struct {
317 int err;
318 const char *desc;
319 } errors[] = {
320 {SD_RES_SUCCESS, "Success"},
321 {SD_RES_UNKNOWN, "Unknown error"},
322 {SD_RES_NO_OBJ, "No object found"},
323 {SD_RES_EIO, "I/O error"},
324 {SD_RES_VDI_EXIST, "VDI exists already"},
325 {SD_RES_INVALID_PARMS, "Invalid parameters"},
326 {SD_RES_SYSTEM_ERROR, "System error"},
327 {SD_RES_VDI_LOCKED, "VDI is already locked"},
328 {SD_RES_NO_VDI, "No vdi found"},
329 {SD_RES_NO_BASE_VDI, "No base VDI found"},
330 {SD_RES_VDI_READ, "Failed read the requested VDI"},
331 {SD_RES_VDI_WRITE, "Failed to write the requested VDI"},
332 {SD_RES_BASE_VDI_READ, "Failed to read the base VDI"},
333 {SD_RES_BASE_VDI_WRITE, "Failed to write the base VDI"},
334 {SD_RES_NO_TAG, "Failed to find the requested tag"},
335 {SD_RES_STARTUP, "The system is still booting"},
336 {SD_RES_VDI_NOT_LOCKED, "VDI isn't locked"},
337 {SD_RES_SHUTDOWN, "The system is shutting down"},
338 {SD_RES_NO_MEM, "Out of memory on the server"},
339 {SD_RES_FULL_VDI, "We already have the maximum vdis"},
340 {SD_RES_VER_MISMATCH, "Protocol version mismatch"},
341 {SD_RES_NO_SPACE, "Server has no space for new objects"},
342 {SD_RES_WAIT_FOR_FORMAT, "Sheepdog is waiting for a format operation"},
343 {SD_RES_WAIT_FOR_JOIN, "Sheepdog is waiting for other nodes joining"},
344 {SD_RES_JOIN_FAILED, "Target node had failed to join sheepdog"},
347 for (i = 0; i < ARRAY_SIZE(errors); ++i) {
348 if (errors[i].err == err) {
349 return errors[i].desc;
353 return "Invalid error code";
357 * Sheepdog I/O handling:
359 * 1. In sd_co_rw_vector, we send the I/O requests to the server and
360 * link the requests to the inflight_list in the
361 * BDRVSheepdogState. The function exits without waiting for
362 * receiving the response.
364 * 2. We receive the response in aio_read_response, the fd handler to
365 * the sheepdog connection. If metadata update is needed, we send
366 * the write request to the vdi object in sd_write_done, the write
367 * completion function. We switch back to sd_co_readv/writev after
368 * all the requests belonging to the AIOCB are finished.
371 static inline AIOReq *alloc_aio_req(BDRVSheepdogState *s, SheepdogAIOCB *acb,
372 uint64_t oid, unsigned int data_len,
373 uint64_t offset, uint8_t flags,
374 uint64_t base_oid, unsigned int iov_offset)
376 AIOReq *aio_req;
378 aio_req = g_malloc(sizeof(*aio_req));
379 aio_req->aiocb = acb;
380 aio_req->iov_offset = iov_offset;
381 aio_req->oid = oid;
382 aio_req->base_oid = base_oid;
383 aio_req->offset = offset;
384 aio_req->data_len = data_len;
385 aio_req->flags = flags;
386 aio_req->id = s->aioreq_seq_num++;
388 acb->nr_pending++;
389 return aio_req;
392 static inline void free_aio_req(BDRVSheepdogState *s, AIOReq *aio_req)
394 SheepdogAIOCB *acb = aio_req->aiocb;
396 QLIST_REMOVE(aio_req, aio_siblings);
397 g_free(aio_req);
399 acb->nr_pending--;
402 static void coroutine_fn sd_finish_aiocb(SheepdogAIOCB *acb)
404 if (!acb->canceled) {
405 qemu_coroutine_enter(acb->coroutine, NULL);
407 qemu_aio_release(acb);
410 static void sd_aio_cancel(BlockDriverAIOCB *blockacb)
412 SheepdogAIOCB *acb = (SheepdogAIOCB *)blockacb;
415 * Sheepdog cannot cancel the requests which are already sent to
416 * the servers, so we just complete the request with -EIO here.
418 acb->ret = -EIO;
419 qemu_coroutine_enter(acb->coroutine, NULL);
420 acb->canceled = 1;
423 static AIOPool sd_aio_pool = {
424 .aiocb_size = sizeof(SheepdogAIOCB),
425 .cancel = sd_aio_cancel,
428 static SheepdogAIOCB *sd_aio_setup(BlockDriverState *bs, QEMUIOVector *qiov,
429 int64_t sector_num, int nb_sectors,
430 BlockDriverCompletionFunc *cb, void *opaque)
432 SheepdogAIOCB *acb;
434 acb = qemu_aio_get(&sd_aio_pool, bs, cb, opaque);
436 acb->qiov = qiov;
438 acb->sector_num = sector_num;
439 acb->nb_sectors = nb_sectors;
441 acb->aio_done_func = NULL;
442 acb->canceled = 0;
443 acb->coroutine = qemu_coroutine_self();
444 acb->ret = 0;
445 acb->nr_pending = 0;
446 return acb;
449 static int connect_to_sdog(const char *addr, const char *port)
451 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
452 int fd, ret;
453 struct addrinfo hints, *res, *res0;
455 if (!addr) {
456 addr = SD_DEFAULT_ADDR;
457 port = SD_DEFAULT_PORT;
460 memset(&hints, 0, sizeof(hints));
461 hints.ai_socktype = SOCK_STREAM;
463 ret = getaddrinfo(addr, port, &hints, &res0);
464 if (ret) {
465 error_report("unable to get address info %s, %s",
466 addr, strerror(errno));
467 return -errno;
470 for (res = res0; res; res = res->ai_next) {
471 ret = getnameinfo(res->ai_addr, res->ai_addrlen, hbuf, sizeof(hbuf),
472 sbuf, sizeof(sbuf), NI_NUMERICHOST | NI_NUMERICSERV);
473 if (ret) {
474 continue;
477 fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
478 if (fd < 0) {
479 continue;
482 reconnect:
483 ret = connect(fd, res->ai_addr, res->ai_addrlen);
484 if (ret < 0) {
485 if (errno == EINTR) {
486 goto reconnect;
488 break;
491 dprintf("connected to %s:%s\n", addr, port);
492 goto success;
494 fd = -errno;
495 error_report("failed connect to %s:%s", addr, port);
496 success:
497 freeaddrinfo(res0);
498 return fd;
501 static int send_req(int sockfd, SheepdogReq *hdr, void *data,
502 unsigned int *wlen)
504 int ret;
506 ret = qemu_send_full(sockfd, hdr, sizeof(*hdr), 0);
507 if (ret < sizeof(*hdr)) {
508 error_report("failed to send a req, %s", strerror(errno));
509 return -errno;
512 ret = qemu_send_full(sockfd, data, *wlen, 0);
513 if (ret < *wlen) {
514 error_report("failed to send a req, %s", strerror(errno));
515 ret = -errno;
518 return ret;
521 static coroutine_fn int send_co_req(int sockfd, SheepdogReq *hdr, void *data,
522 unsigned int *wlen)
524 int ret;
526 ret = qemu_co_send(sockfd, hdr, sizeof(*hdr));
527 if (ret < sizeof(*hdr)) {
528 error_report("failed to send a req, %s", strerror(errno));
529 return ret;
532 ret = qemu_co_send(sockfd, data, *wlen);
533 if (ret < *wlen) {
534 error_report("failed to send a req, %s", strerror(errno));
537 return ret;
540 static coroutine_fn int do_co_req(int sockfd, SheepdogReq *hdr, void *data,
541 unsigned int *wlen, unsigned int *rlen);
543 static int do_req(int sockfd, SheepdogReq *hdr, void *data,
544 unsigned int *wlen, unsigned int *rlen)
546 int ret;
548 if (qemu_in_coroutine()) {
549 return do_co_req(sockfd, hdr, data, wlen, rlen);
552 socket_set_block(sockfd);
553 ret = send_req(sockfd, hdr, data, wlen);
554 if (ret < 0) {
555 goto out;
558 ret = qemu_recv_full(sockfd, hdr, sizeof(*hdr), 0);
559 if (ret < sizeof(*hdr)) {
560 error_report("failed to get a rsp, %s", strerror(errno));
561 ret = -errno;
562 goto out;
565 if (*rlen > hdr->data_length) {
566 *rlen = hdr->data_length;
569 if (*rlen) {
570 ret = qemu_recv_full(sockfd, data, *rlen, 0);
571 if (ret < *rlen) {
572 error_report("failed to get the data, %s", strerror(errno));
573 ret = -errno;
574 goto out;
577 ret = 0;
578 out:
579 socket_set_nonblock(sockfd);
580 return ret;
583 static void restart_co_req(void *opaque)
585 Coroutine *co = opaque;
587 qemu_coroutine_enter(co, NULL);
590 static coroutine_fn int do_co_req(int sockfd, SheepdogReq *hdr, void *data,
591 unsigned int *wlen, unsigned int *rlen)
593 int ret;
594 Coroutine *co;
596 co = qemu_coroutine_self();
597 qemu_aio_set_fd_handler(sockfd, NULL, restart_co_req, NULL, co);
599 socket_set_block(sockfd);
600 ret = send_co_req(sockfd, hdr, data, wlen);
601 if (ret < 0) {
602 goto out;
605 qemu_aio_set_fd_handler(sockfd, restart_co_req, NULL, NULL, co);
607 ret = qemu_co_recv(sockfd, hdr, sizeof(*hdr));
608 if (ret < sizeof(*hdr)) {
609 error_report("failed to get a rsp, %s", strerror(errno));
610 ret = -errno;
611 goto out;
614 if (*rlen > hdr->data_length) {
615 *rlen = hdr->data_length;
618 if (*rlen) {
619 ret = qemu_co_recv(sockfd, data, *rlen);
620 if (ret < *rlen) {
621 error_report("failed to get the data, %s", strerror(errno));
622 ret = -errno;
623 goto out;
626 ret = 0;
627 out:
628 qemu_aio_set_fd_handler(sockfd, NULL, NULL, NULL, NULL);
629 socket_set_nonblock(sockfd);
630 return ret;
633 static int coroutine_fn add_aio_request(BDRVSheepdogState *s, AIOReq *aio_req,
634 struct iovec *iov, int niov, int create,
635 enum AIOCBState aiocb_type);
638 static AIOReq *find_pending_req(BDRVSheepdogState *s, uint64_t oid)
640 AIOReq *aio_req;
642 QLIST_FOREACH(aio_req, &s->pending_aio_head, aio_siblings) {
643 if (aio_req->oid == oid) {
644 return aio_req;
648 return NULL;
652 * This function searchs pending requests to the object `oid', and
653 * sends them.
655 static void coroutine_fn send_pending_req(BDRVSheepdogState *s, uint64_t oid)
657 AIOReq *aio_req;
658 SheepdogAIOCB *acb;
659 int ret;
661 while ((aio_req = find_pending_req(s, oid)) != NULL) {
662 acb = aio_req->aiocb;
663 /* move aio_req from pending list to inflight one */
664 QLIST_REMOVE(aio_req, aio_siblings);
665 QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
666 ret = add_aio_request(s, aio_req, acb->qiov->iov,
667 acb->qiov->niov, 0, acb->aiocb_type);
668 if (ret < 0) {
669 error_report("add_aio_request is failed");
670 free_aio_req(s, aio_req);
671 if (!acb->nr_pending) {
672 sd_finish_aiocb(acb);
679 * Receive responses of the I/O requests.
681 * This function is registered as a fd handler, and called from the
682 * main loop when s->fd is ready for reading responses.
684 static void coroutine_fn aio_read_response(void *opaque)
686 SheepdogObjRsp rsp;
687 BDRVSheepdogState *s = opaque;
688 int fd = s->fd;
689 int ret;
690 AIOReq *aio_req = NULL;
691 SheepdogAIOCB *acb;
692 unsigned long idx;
694 if (QLIST_EMPTY(&s->inflight_aio_head)) {
695 goto out;
698 /* read a header */
699 ret = qemu_co_recv(fd, &rsp, sizeof(rsp));
700 if (ret < 0) {
701 error_report("failed to get the header, %s", strerror(errno));
702 goto out;
705 /* find the right aio_req from the inflight aio list */
706 QLIST_FOREACH(aio_req, &s->inflight_aio_head, aio_siblings) {
707 if (aio_req->id == rsp.id) {
708 break;
711 if (!aio_req) {
712 error_report("cannot find aio_req %x", rsp.id);
713 goto out;
716 acb = aio_req->aiocb;
718 switch (acb->aiocb_type) {
719 case AIOCB_WRITE_UDATA:
720 /* this coroutine context is no longer suitable for co_recv
721 * because we may send data to update vdi objects */
722 s->co_recv = NULL;
723 if (!is_data_obj(aio_req->oid)) {
724 break;
726 idx = data_oid_to_idx(aio_req->oid);
728 if (s->inode.data_vdi_id[idx] != s->inode.vdi_id) {
730 * If the object is newly created one, we need to update
731 * the vdi object (metadata object). min_dirty_data_idx
732 * and max_dirty_data_idx are changed to include updated
733 * index between them.
735 s->inode.data_vdi_id[idx] = s->inode.vdi_id;
736 s->max_dirty_data_idx = MAX(idx, s->max_dirty_data_idx);
737 s->min_dirty_data_idx = MIN(idx, s->min_dirty_data_idx);
740 * Some requests may be blocked because simultaneous
741 * create requests are not allowed, so we search the
742 * pending requests here.
744 send_pending_req(s, vid_to_data_oid(s->inode.vdi_id, idx));
746 break;
747 case AIOCB_READ_UDATA:
748 ret = qemu_co_recvv(fd, acb->qiov->iov, acb->qiov->niov,
749 aio_req->iov_offset, rsp.data_length);
750 if (ret < 0) {
751 error_report("failed to get the data, %s", strerror(errno));
752 goto out;
754 break;
757 if (rsp.result != SD_RES_SUCCESS) {
758 acb->ret = -EIO;
759 error_report("%s", sd_strerror(rsp.result));
762 free_aio_req(s, aio_req);
763 if (!acb->nr_pending) {
765 * We've finished all requests which belong to the AIOCB, so
766 * we can switch back to sd_co_readv/writev now.
768 acb->aio_done_func(acb);
770 out:
771 s->co_recv = NULL;
774 static void co_read_response(void *opaque)
776 BDRVSheepdogState *s = opaque;
778 if (!s->co_recv) {
779 s->co_recv = qemu_coroutine_create(aio_read_response);
782 qemu_coroutine_enter(s->co_recv, opaque);
785 static void co_write_request(void *opaque)
787 BDRVSheepdogState *s = opaque;
789 qemu_coroutine_enter(s->co_send, NULL);
792 static int aio_flush_request(void *opaque)
794 BDRVSheepdogState *s = opaque;
796 return !QLIST_EMPTY(&s->inflight_aio_head) ||
797 !QLIST_EMPTY(&s->pending_aio_head);
800 static int set_nodelay(int fd)
802 int ret, opt;
804 opt = 1;
805 ret = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&opt, sizeof(opt));
806 return ret;
810 * Return a socket discriptor to read/write objects.
812 * We cannot use this discriptor for other operations because
813 * the block driver may be on waiting response from the server.
815 static int get_sheep_fd(BDRVSheepdogState *s)
817 int ret, fd;
819 fd = connect_to_sdog(s->addr, s->port);
820 if (fd < 0) {
821 error_report("%s", strerror(errno));
822 return fd;
825 socket_set_nonblock(fd);
827 ret = set_nodelay(fd);
828 if (ret) {
829 error_report("%s", strerror(errno));
830 closesocket(fd);
831 return -errno;
834 qemu_aio_set_fd_handler(fd, co_read_response, NULL, aio_flush_request, s);
835 return fd;
839 * Parse a filename
841 * filename must be one of the following formats:
842 * 1. [vdiname]
843 * 2. [vdiname]:[snapid]
844 * 3. [vdiname]:[tag]
845 * 4. [hostname]:[port]:[vdiname]
846 * 5. [hostname]:[port]:[vdiname]:[snapid]
847 * 6. [hostname]:[port]:[vdiname]:[tag]
849 * You can boot from the snapshot images by specifying `snapid` or
850 * `tag'.
852 * You can run VMs outside the Sheepdog cluster by specifying
853 * `hostname' and `port' (experimental).
855 static int parse_vdiname(BDRVSheepdogState *s, const char *filename,
856 char *vdi, uint32_t *snapid, char *tag)
858 char *p, *q;
859 int nr_sep;
861 p = q = g_strdup(filename);
863 /* count the number of separators */
864 nr_sep = 0;
865 while (*p) {
866 if (*p == ':') {
867 nr_sep++;
869 p++;
871 p = q;
873 /* use the first two tokens as hostname and port number. */
874 if (nr_sep >= 2) {
875 s->addr = p;
876 p = strchr(p, ':');
877 *p++ = '\0';
879 s->port = p;
880 p = strchr(p, ':');
881 *p++ = '\0';
882 } else {
883 s->addr = NULL;
884 s->port = 0;
887 strncpy(vdi, p, SD_MAX_VDI_LEN);
889 p = strchr(vdi, ':');
890 if (p) {
891 *p++ = '\0';
892 *snapid = strtoul(p, NULL, 10);
893 if (*snapid == 0) {
894 strncpy(tag, p, SD_MAX_VDI_TAG_LEN);
896 } else {
897 *snapid = CURRENT_VDI_ID; /* search current vdi */
900 if (s->addr == NULL) {
901 g_free(q);
904 return 0;
907 static int find_vdi_name(BDRVSheepdogState *s, char *filename, uint32_t snapid,
908 char *tag, uint32_t *vid, int for_snapshot)
910 int ret, fd;
911 SheepdogVdiReq hdr;
912 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
913 unsigned int wlen, rlen = 0;
914 char buf[SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN];
916 fd = connect_to_sdog(s->addr, s->port);
917 if (fd < 0) {
918 return fd;
921 memset(buf, 0, sizeof(buf));
922 strncpy(buf, filename, SD_MAX_VDI_LEN);
923 strncpy(buf + SD_MAX_VDI_LEN, tag, SD_MAX_VDI_TAG_LEN);
925 memset(&hdr, 0, sizeof(hdr));
926 if (for_snapshot) {
927 hdr.opcode = SD_OP_GET_VDI_INFO;
928 } else {
929 hdr.opcode = SD_OP_LOCK_VDI;
931 wlen = SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN;
932 hdr.proto_ver = SD_PROTO_VER;
933 hdr.data_length = wlen;
934 hdr.snapid = snapid;
935 hdr.flags = SD_FLAG_CMD_WRITE;
937 ret = do_req(fd, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
938 if (ret) {
939 goto out;
942 if (rsp->result != SD_RES_SUCCESS) {
943 error_report("cannot get vdi info, %s, %s %d %s",
944 sd_strerror(rsp->result), filename, snapid, tag);
945 if (rsp->result == SD_RES_NO_VDI) {
946 ret = -ENOENT;
947 } else {
948 ret = -EIO;
950 goto out;
952 *vid = rsp->vdi_id;
954 ret = 0;
955 out:
956 closesocket(fd);
957 return ret;
960 static int coroutine_fn add_aio_request(BDRVSheepdogState *s, AIOReq *aio_req,
961 struct iovec *iov, int niov, int create,
962 enum AIOCBState aiocb_type)
964 int nr_copies = s->inode.nr_copies;
965 SheepdogObjReq hdr;
966 unsigned int wlen;
967 int ret;
968 uint64_t oid = aio_req->oid;
969 unsigned int datalen = aio_req->data_len;
970 uint64_t offset = aio_req->offset;
971 uint8_t flags = aio_req->flags;
972 uint64_t old_oid = aio_req->base_oid;
974 if (!nr_copies) {
975 error_report("bug");
978 memset(&hdr, 0, sizeof(hdr));
980 if (aiocb_type == AIOCB_READ_UDATA) {
981 wlen = 0;
982 hdr.opcode = SD_OP_READ_OBJ;
983 hdr.flags = flags;
984 } else if (create) {
985 wlen = datalen;
986 hdr.opcode = SD_OP_CREATE_AND_WRITE_OBJ;
987 hdr.flags = SD_FLAG_CMD_WRITE | flags;
988 } else {
989 wlen = datalen;
990 hdr.opcode = SD_OP_WRITE_OBJ;
991 hdr.flags = SD_FLAG_CMD_WRITE | flags;
994 if (s->cache_enabled) {
995 hdr.flags |= SD_FLAG_CMD_CACHE;
998 hdr.oid = oid;
999 hdr.cow_oid = old_oid;
1000 hdr.copies = s->inode.nr_copies;
1002 hdr.data_length = datalen;
1003 hdr.offset = offset;
1005 hdr.id = aio_req->id;
1007 qemu_co_mutex_lock(&s->lock);
1008 s->co_send = qemu_coroutine_self();
1009 qemu_aio_set_fd_handler(s->fd, co_read_response, co_write_request,
1010 aio_flush_request, s);
1011 socket_set_cork(s->fd, 1);
1013 /* send a header */
1014 ret = qemu_co_send(s->fd, &hdr, sizeof(hdr));
1015 if (ret < 0) {
1016 qemu_co_mutex_unlock(&s->lock);
1017 error_report("failed to send a req, %s", strerror(errno));
1018 return -errno;
1021 if (wlen) {
1022 ret = qemu_co_sendv(s->fd, iov, niov, aio_req->iov_offset, wlen);
1023 if (ret < 0) {
1024 qemu_co_mutex_unlock(&s->lock);
1025 error_report("failed to send a data, %s", strerror(errno));
1026 return -errno;
1030 socket_set_cork(s->fd, 0);
1031 qemu_aio_set_fd_handler(s->fd, co_read_response, NULL,
1032 aio_flush_request, s);
1033 qemu_co_mutex_unlock(&s->lock);
1035 return 0;
1038 static int read_write_object(int fd, char *buf, uint64_t oid, int copies,
1039 unsigned int datalen, uint64_t offset,
1040 int write, int create, uint8_t cache)
1042 SheepdogObjReq hdr;
1043 SheepdogObjRsp *rsp = (SheepdogObjRsp *)&hdr;
1044 unsigned int wlen, rlen;
1045 int ret;
1047 memset(&hdr, 0, sizeof(hdr));
1049 if (write) {
1050 wlen = datalen;
1051 rlen = 0;
1052 hdr.flags = SD_FLAG_CMD_WRITE;
1053 if (create) {
1054 hdr.opcode = SD_OP_CREATE_AND_WRITE_OBJ;
1055 } else {
1056 hdr.opcode = SD_OP_WRITE_OBJ;
1058 } else {
1059 wlen = 0;
1060 rlen = datalen;
1061 hdr.opcode = SD_OP_READ_OBJ;
1064 if (cache) {
1065 hdr.flags |= SD_FLAG_CMD_CACHE;
1068 hdr.oid = oid;
1069 hdr.data_length = datalen;
1070 hdr.offset = offset;
1071 hdr.copies = copies;
1073 ret = do_req(fd, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
1074 if (ret) {
1075 error_report("failed to send a request to the sheep");
1076 return ret;
1079 switch (rsp->result) {
1080 case SD_RES_SUCCESS:
1081 return 0;
1082 default:
1083 error_report("%s", sd_strerror(rsp->result));
1084 return -EIO;
1088 static int read_object(int fd, char *buf, uint64_t oid, int copies,
1089 unsigned int datalen, uint64_t offset, uint8_t cache)
1091 return read_write_object(fd, buf, oid, copies, datalen, offset, 0, 0,
1092 cache);
1095 static int write_object(int fd, char *buf, uint64_t oid, int copies,
1096 unsigned int datalen, uint64_t offset, int create,
1097 uint8_t cache)
1099 return read_write_object(fd, buf, oid, copies, datalen, offset, 1, create,
1100 cache);
1103 static int sd_open(BlockDriverState *bs, const char *filename, int flags)
1105 int ret, fd;
1106 uint32_t vid = 0;
1107 BDRVSheepdogState *s = bs->opaque;
1108 char vdi[SD_MAX_VDI_LEN], tag[SD_MAX_VDI_TAG_LEN];
1109 uint32_t snapid;
1110 char *buf = NULL;
1112 strstart(filename, "sheepdog:", (const char **)&filename);
1114 QLIST_INIT(&s->inflight_aio_head);
1115 QLIST_INIT(&s->pending_aio_head);
1116 s->fd = -1;
1118 memset(vdi, 0, sizeof(vdi));
1119 memset(tag, 0, sizeof(tag));
1120 if (parse_vdiname(s, filename, vdi, &snapid, tag) < 0) {
1121 ret = -EINVAL;
1122 goto out;
1124 s->fd = get_sheep_fd(s);
1125 if (s->fd < 0) {
1126 ret = s->fd;
1127 goto out;
1130 ret = find_vdi_name(s, vdi, snapid, tag, &vid, 0);
1131 if (ret) {
1132 goto out;
1135 if (flags & BDRV_O_CACHE_WB) {
1136 s->cache_enabled = 1;
1137 s->flush_fd = connect_to_sdog(s->addr, s->port);
1138 if (s->flush_fd < 0) {
1139 error_report("failed to connect");
1140 ret = s->flush_fd;
1141 goto out;
1145 if (snapid || tag[0] != '\0') {
1146 dprintf("%" PRIx32 " snapshot inode was open.\n", vid);
1147 s->is_snapshot = 1;
1150 fd = connect_to_sdog(s->addr, s->port);
1151 if (fd < 0) {
1152 error_report("failed to connect");
1153 ret = fd;
1154 goto out;
1157 buf = g_malloc(SD_INODE_SIZE);
1158 ret = read_object(fd, buf, vid_to_vdi_oid(vid), 0, SD_INODE_SIZE, 0,
1159 s->cache_enabled);
1161 closesocket(fd);
1163 if (ret) {
1164 goto out;
1167 memcpy(&s->inode, buf, sizeof(s->inode));
1168 s->min_dirty_data_idx = UINT32_MAX;
1169 s->max_dirty_data_idx = 0;
1171 bs->total_sectors = s->inode.vdi_size / SECTOR_SIZE;
1172 strncpy(s->name, vdi, sizeof(s->name));
1173 qemu_co_mutex_init(&s->lock);
1174 g_free(buf);
1175 return 0;
1176 out:
1177 qemu_aio_set_fd_handler(s->fd, NULL, NULL, NULL, NULL);
1178 if (s->fd >= 0) {
1179 closesocket(s->fd);
1181 g_free(buf);
1182 return ret;
1185 static int do_sd_create(char *filename, int64_t vdi_size,
1186 uint32_t base_vid, uint32_t *vdi_id, int snapshot,
1187 const char *addr, const char *port)
1189 SheepdogVdiReq hdr;
1190 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
1191 int fd, ret;
1192 unsigned int wlen, rlen = 0;
1193 char buf[SD_MAX_VDI_LEN];
1195 fd = connect_to_sdog(addr, port);
1196 if (fd < 0) {
1197 return fd;
1200 memset(buf, 0, sizeof(buf));
1201 strncpy(buf, filename, SD_MAX_VDI_LEN);
1203 memset(&hdr, 0, sizeof(hdr));
1204 hdr.opcode = SD_OP_NEW_VDI;
1205 hdr.base_vdi_id = base_vid;
1207 wlen = SD_MAX_VDI_LEN;
1209 hdr.flags = SD_FLAG_CMD_WRITE;
1210 hdr.snapid = snapshot;
1212 hdr.data_length = wlen;
1213 hdr.vdi_size = vdi_size;
1215 ret = do_req(fd, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
1217 closesocket(fd);
1219 if (ret) {
1220 return ret;
1223 if (rsp->result != SD_RES_SUCCESS) {
1224 error_report("%s, %s", sd_strerror(rsp->result), filename);
1225 return -EIO;
1228 if (vdi_id) {
1229 *vdi_id = rsp->vdi_id;
1232 return 0;
1235 static int sd_prealloc(const char *filename)
1237 BlockDriverState *bs = NULL;
1238 uint32_t idx, max_idx;
1239 int64_t vdi_size;
1240 void *buf = g_malloc0(SD_DATA_OBJ_SIZE);
1241 int ret;
1243 ret = bdrv_file_open(&bs, filename, BDRV_O_RDWR);
1244 if (ret < 0) {
1245 goto out;
1248 vdi_size = bdrv_getlength(bs);
1249 if (vdi_size < 0) {
1250 ret = vdi_size;
1251 goto out;
1253 max_idx = DIV_ROUND_UP(vdi_size, SD_DATA_OBJ_SIZE);
1255 for (idx = 0; idx < max_idx; idx++) {
1257 * The created image can be a cloned image, so we need to read
1258 * a data from the source image.
1260 ret = bdrv_pread(bs, idx * SD_DATA_OBJ_SIZE, buf, SD_DATA_OBJ_SIZE);
1261 if (ret < 0) {
1262 goto out;
1264 ret = bdrv_pwrite(bs, idx * SD_DATA_OBJ_SIZE, buf, SD_DATA_OBJ_SIZE);
1265 if (ret < 0) {
1266 goto out;
1269 out:
1270 if (bs) {
1271 bdrv_delete(bs);
1273 g_free(buf);
1275 return ret;
1278 static int sd_create(const char *filename, QEMUOptionParameter *options)
1280 int ret = 0;
1281 uint32_t vid = 0, base_vid = 0;
1282 int64_t vdi_size = 0;
1283 char *backing_file = NULL;
1284 BDRVSheepdogState *s;
1285 char vdi[SD_MAX_VDI_LEN], tag[SD_MAX_VDI_TAG_LEN];
1286 uint32_t snapid;
1287 int prealloc = 0;
1288 const char *vdiname;
1290 s = g_malloc0(sizeof(BDRVSheepdogState));
1292 strstart(filename, "sheepdog:", &vdiname);
1294 memset(vdi, 0, sizeof(vdi));
1295 memset(tag, 0, sizeof(tag));
1296 if (parse_vdiname(s, vdiname, vdi, &snapid, tag) < 0) {
1297 error_report("invalid filename");
1298 ret = -EINVAL;
1299 goto out;
1302 while (options && options->name) {
1303 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
1304 vdi_size = options->value.n;
1305 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
1306 backing_file = options->value.s;
1307 } else if (!strcmp(options->name, BLOCK_OPT_PREALLOC)) {
1308 if (!options->value.s || !strcmp(options->value.s, "off")) {
1309 prealloc = 0;
1310 } else if (!strcmp(options->value.s, "full")) {
1311 prealloc = 1;
1312 } else {
1313 error_report("Invalid preallocation mode: '%s'",
1314 options->value.s);
1315 ret = -EINVAL;
1316 goto out;
1319 options++;
1322 if (vdi_size > SD_MAX_VDI_SIZE) {
1323 error_report("too big image size");
1324 ret = -EINVAL;
1325 goto out;
1328 if (backing_file) {
1329 BlockDriverState *bs;
1330 BDRVSheepdogState *s;
1331 BlockDriver *drv;
1333 /* Currently, only Sheepdog backing image is supported. */
1334 drv = bdrv_find_protocol(backing_file);
1335 if (!drv || strcmp(drv->protocol_name, "sheepdog") != 0) {
1336 error_report("backing_file must be a sheepdog image");
1337 ret = -EINVAL;
1338 goto out;
1341 ret = bdrv_file_open(&bs, backing_file, 0);
1342 if (ret < 0) {
1343 goto out;
1346 s = bs->opaque;
1348 if (!is_snapshot(&s->inode)) {
1349 error_report("cannot clone from a non snapshot vdi");
1350 bdrv_delete(bs);
1351 ret = -EINVAL;
1352 goto out;
1355 base_vid = s->inode.vdi_id;
1356 bdrv_delete(bs);
1359 ret = do_sd_create(vdi, vdi_size, base_vid, &vid, 0, s->addr, s->port);
1360 if (!prealloc || ret) {
1361 goto out;
1364 ret = sd_prealloc(filename);
1365 out:
1366 g_free(s);
1367 return ret;
1370 static void sd_close(BlockDriverState *bs)
1372 BDRVSheepdogState *s = bs->opaque;
1373 SheepdogVdiReq hdr;
1374 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
1375 unsigned int wlen, rlen = 0;
1376 int fd, ret;
1378 dprintf("%s\n", s->name);
1380 fd = connect_to_sdog(s->addr, s->port);
1381 if (fd < 0) {
1382 return;
1385 memset(&hdr, 0, sizeof(hdr));
1387 hdr.opcode = SD_OP_RELEASE_VDI;
1388 wlen = strlen(s->name) + 1;
1389 hdr.data_length = wlen;
1390 hdr.flags = SD_FLAG_CMD_WRITE;
1392 ret = do_req(fd, (SheepdogReq *)&hdr, s->name, &wlen, &rlen);
1394 closesocket(fd);
1396 if (!ret && rsp->result != SD_RES_SUCCESS &&
1397 rsp->result != SD_RES_VDI_NOT_LOCKED) {
1398 error_report("%s, %s", sd_strerror(rsp->result), s->name);
1401 qemu_aio_set_fd_handler(s->fd, NULL, NULL, NULL, NULL);
1402 closesocket(s->fd);
1403 if (s->cache_enabled) {
1404 closesocket(s->flush_fd);
1406 g_free(s->addr);
1409 static int64_t sd_getlength(BlockDriverState *bs)
1411 BDRVSheepdogState *s = bs->opaque;
1413 return s->inode.vdi_size;
1416 static int sd_truncate(BlockDriverState *bs, int64_t offset)
1418 BDRVSheepdogState *s = bs->opaque;
1419 int ret, fd;
1420 unsigned int datalen;
1422 if (offset < s->inode.vdi_size) {
1423 error_report("shrinking is not supported");
1424 return -EINVAL;
1425 } else if (offset > SD_MAX_VDI_SIZE) {
1426 error_report("too big image size");
1427 return -EINVAL;
1430 fd = connect_to_sdog(s->addr, s->port);
1431 if (fd < 0) {
1432 return fd;
1435 /* we don't need to update entire object */
1436 datalen = SD_INODE_SIZE - sizeof(s->inode.data_vdi_id);
1437 s->inode.vdi_size = offset;
1438 ret = write_object(fd, (char *)&s->inode, vid_to_vdi_oid(s->inode.vdi_id),
1439 s->inode.nr_copies, datalen, 0, 0, s->cache_enabled);
1440 close(fd);
1442 if (ret < 0) {
1443 error_report("failed to update an inode.");
1446 return ret;
1450 * This function is called after writing data objects. If we need to
1451 * update metadata, this sends a write request to the vdi object.
1452 * Otherwise, this switches back to sd_co_readv/writev.
1454 static void coroutine_fn sd_write_done(SheepdogAIOCB *acb)
1456 int ret;
1457 BDRVSheepdogState *s = acb->common.bs->opaque;
1458 struct iovec iov;
1459 AIOReq *aio_req;
1460 uint32_t offset, data_len, mn, mx;
1462 mn = s->min_dirty_data_idx;
1463 mx = s->max_dirty_data_idx;
1464 if (mn <= mx) {
1465 /* we need to update the vdi object. */
1466 offset = sizeof(s->inode) - sizeof(s->inode.data_vdi_id) +
1467 mn * sizeof(s->inode.data_vdi_id[0]);
1468 data_len = (mx - mn + 1) * sizeof(s->inode.data_vdi_id[0]);
1470 s->min_dirty_data_idx = UINT32_MAX;
1471 s->max_dirty_data_idx = 0;
1473 iov.iov_base = &s->inode;
1474 iov.iov_len = sizeof(s->inode);
1475 aio_req = alloc_aio_req(s, acb, vid_to_vdi_oid(s->inode.vdi_id),
1476 data_len, offset, 0, 0, offset);
1477 QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
1478 ret = add_aio_request(s, aio_req, &iov, 1, 0, AIOCB_WRITE_UDATA);
1479 if (ret) {
1480 free_aio_req(s, aio_req);
1481 acb->ret = -EIO;
1482 goto out;
1485 acb->aio_done_func = sd_finish_aiocb;
1486 acb->aiocb_type = AIOCB_WRITE_UDATA;
1487 return;
1489 out:
1490 sd_finish_aiocb(acb);
1494 * Create a writable VDI from a snapshot
1496 static int sd_create_branch(BDRVSheepdogState *s)
1498 int ret, fd;
1499 uint32_t vid;
1500 char *buf;
1502 dprintf("%" PRIx32 " is snapshot.\n", s->inode.vdi_id);
1504 buf = g_malloc(SD_INODE_SIZE);
1506 ret = do_sd_create(s->name, s->inode.vdi_size, s->inode.vdi_id, &vid, 1,
1507 s->addr, s->port);
1508 if (ret) {
1509 goto out;
1512 dprintf("%" PRIx32 " is created.\n", vid);
1514 fd = connect_to_sdog(s->addr, s->port);
1515 if (fd < 0) {
1516 error_report("failed to connect");
1517 ret = fd;
1518 goto out;
1521 ret = read_object(fd, buf, vid_to_vdi_oid(vid), s->inode.nr_copies,
1522 SD_INODE_SIZE, 0, s->cache_enabled);
1524 closesocket(fd);
1526 if (ret < 0) {
1527 goto out;
1530 memcpy(&s->inode, buf, sizeof(s->inode));
1532 s->is_snapshot = 0;
1533 ret = 0;
1534 dprintf("%" PRIx32 " was newly created.\n", s->inode.vdi_id);
1536 out:
1537 g_free(buf);
1539 return ret;
1543 * Send I/O requests to the server.
1545 * This function sends requests to the server, links the requests to
1546 * the inflight_list in BDRVSheepdogState, and exits without
1547 * waiting the response. The responses are received in the
1548 * `aio_read_response' function which is called from the main loop as
1549 * a fd handler.
1551 * Returns 1 when we need to wait a response, 0 when there is no sent
1552 * request and -errno in error cases.
1554 static int coroutine_fn sd_co_rw_vector(void *p)
1556 SheepdogAIOCB *acb = p;
1557 int ret = 0;
1558 unsigned long len, done = 0, total = acb->nb_sectors * SECTOR_SIZE;
1559 unsigned long idx = acb->sector_num * SECTOR_SIZE / SD_DATA_OBJ_SIZE;
1560 uint64_t oid;
1561 uint64_t offset = (acb->sector_num * SECTOR_SIZE) % SD_DATA_OBJ_SIZE;
1562 BDRVSheepdogState *s = acb->common.bs->opaque;
1563 SheepdogInode *inode = &s->inode;
1564 AIOReq *aio_req;
1566 if (acb->aiocb_type == AIOCB_WRITE_UDATA && s->is_snapshot) {
1568 * In the case we open the snapshot VDI, Sheepdog creates the
1569 * writable VDI when we do a write operation first.
1571 ret = sd_create_branch(s);
1572 if (ret) {
1573 acb->ret = -EIO;
1574 goto out;
1579 * Make sure we don't free the aiocb before we are done with all requests.
1580 * This additional reference is dropped at the end of this function.
1582 acb->nr_pending++;
1584 while (done != total) {
1585 uint8_t flags = 0;
1586 uint64_t old_oid = 0;
1587 int create = 0;
1589 oid = vid_to_data_oid(inode->data_vdi_id[idx], idx);
1591 len = MIN(total - done, SD_DATA_OBJ_SIZE - offset);
1593 if (!inode->data_vdi_id[idx]) {
1594 if (acb->aiocb_type == AIOCB_READ_UDATA) {
1595 goto done;
1598 create = 1;
1599 } else if (acb->aiocb_type == AIOCB_WRITE_UDATA
1600 && !is_data_obj_writable(inode, idx)) {
1601 /* Copy-On-Write */
1602 create = 1;
1603 old_oid = oid;
1604 flags = SD_FLAG_CMD_COW;
1607 if (create) {
1608 dprintf("update ino (%" PRIu32 ") %" PRIu64 " %" PRIu64 " %ld\n",
1609 inode->vdi_id, oid,
1610 vid_to_data_oid(inode->data_vdi_id[idx], idx), idx);
1611 oid = vid_to_data_oid(inode->vdi_id, idx);
1612 dprintf("new oid %" PRIx64 "\n", oid);
1615 aio_req = alloc_aio_req(s, acb, oid, len, offset, flags, old_oid, done);
1617 if (create) {
1618 AIOReq *areq;
1619 QLIST_FOREACH(areq, &s->inflight_aio_head, aio_siblings) {
1620 if (areq->oid == oid) {
1622 * Sheepdog cannot handle simultaneous create
1623 * requests to the same object. So we cannot send
1624 * the request until the previous request
1625 * finishes.
1627 aio_req->flags = 0;
1628 aio_req->base_oid = 0;
1629 QLIST_INSERT_HEAD(&s->pending_aio_head, aio_req,
1630 aio_siblings);
1631 goto done;
1636 QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
1637 ret = add_aio_request(s, aio_req, acb->qiov->iov, acb->qiov->niov,
1638 create, acb->aiocb_type);
1639 if (ret < 0) {
1640 error_report("add_aio_request is failed");
1641 free_aio_req(s, aio_req);
1642 acb->ret = -EIO;
1643 goto out;
1645 done:
1646 offset = 0;
1647 idx++;
1648 done += len;
1650 out:
1651 if (!--acb->nr_pending) {
1652 return acb->ret;
1654 return 1;
1657 static coroutine_fn int sd_co_writev(BlockDriverState *bs, int64_t sector_num,
1658 int nb_sectors, QEMUIOVector *qiov)
1660 SheepdogAIOCB *acb;
1661 int ret;
1663 if (bs->growable && sector_num + nb_sectors > bs->total_sectors) {
1664 ret = sd_truncate(bs, (sector_num + nb_sectors) * SECTOR_SIZE);
1665 if (ret < 0) {
1666 return ret;
1668 bs->total_sectors = sector_num + nb_sectors;
1671 acb = sd_aio_setup(bs, qiov, sector_num, nb_sectors, NULL, NULL);
1672 acb->aio_done_func = sd_write_done;
1673 acb->aiocb_type = AIOCB_WRITE_UDATA;
1675 ret = sd_co_rw_vector(acb);
1676 if (ret <= 0) {
1677 qemu_aio_release(acb);
1678 return ret;
1681 qemu_coroutine_yield();
1683 return acb->ret;
1686 static coroutine_fn int sd_co_readv(BlockDriverState *bs, int64_t sector_num,
1687 int nb_sectors, QEMUIOVector *qiov)
1689 SheepdogAIOCB *acb;
1690 int i, ret;
1692 acb = sd_aio_setup(bs, qiov, sector_num, nb_sectors, NULL, NULL);
1693 acb->aiocb_type = AIOCB_READ_UDATA;
1694 acb->aio_done_func = sd_finish_aiocb;
1697 * TODO: we can do better; we don't need to initialize
1698 * blindly.
1700 for (i = 0; i < qiov->niov; i++) {
1701 memset(qiov->iov[i].iov_base, 0, qiov->iov[i].iov_len);
1704 ret = sd_co_rw_vector(acb);
1705 if (ret <= 0) {
1706 qemu_aio_release(acb);
1707 return ret;
1710 qemu_coroutine_yield();
1712 return acb->ret;
1715 static int coroutine_fn sd_co_flush_to_disk(BlockDriverState *bs)
1717 BDRVSheepdogState *s = bs->opaque;
1718 SheepdogObjReq hdr = { 0 };
1719 SheepdogObjRsp *rsp = (SheepdogObjRsp *)&hdr;
1720 SheepdogInode *inode = &s->inode;
1721 int ret;
1722 unsigned int wlen = 0, rlen = 0;
1724 if (!s->cache_enabled) {
1725 return 0;
1728 hdr.opcode = SD_OP_FLUSH_VDI;
1729 hdr.oid = vid_to_vdi_oid(inode->vdi_id);
1731 ret = do_req(s->flush_fd, (SheepdogReq *)&hdr, NULL, &wlen, &rlen);
1732 if (ret) {
1733 error_report("failed to send a request to the sheep");
1734 return ret;
1737 if (rsp->result == SD_RES_INVALID_PARMS) {
1738 dprintf("disable write cache since the server doesn't support it\n");
1740 s->cache_enabled = 0;
1741 closesocket(s->flush_fd);
1742 return 0;
1745 if (rsp->result != SD_RES_SUCCESS) {
1746 error_report("%s", sd_strerror(rsp->result));
1747 return -EIO;
1750 return 0;
1753 static int sd_snapshot_create(BlockDriverState *bs, QEMUSnapshotInfo *sn_info)
1755 BDRVSheepdogState *s = bs->opaque;
1756 int ret, fd;
1757 uint32_t new_vid;
1758 SheepdogInode *inode;
1759 unsigned int datalen;
1761 dprintf("sn_info: name %s id_str %s s: name %s vm_state_size %" PRId64 " "
1762 "is_snapshot %d\n", sn_info->name, sn_info->id_str,
1763 s->name, sn_info->vm_state_size, s->is_snapshot);
1765 if (s->is_snapshot) {
1766 error_report("You can't create a snapshot of a snapshot VDI, "
1767 "%s (%" PRIu32 ").", s->name, s->inode.vdi_id);
1769 return -EINVAL;
1772 dprintf("%s %s\n", sn_info->name, sn_info->id_str);
1774 s->inode.vm_state_size = sn_info->vm_state_size;
1775 s->inode.vm_clock_nsec = sn_info->vm_clock_nsec;
1776 strncpy(s->inode.tag, sn_info->name, sizeof(s->inode.tag));
1777 /* we don't need to update entire object */
1778 datalen = SD_INODE_SIZE - sizeof(s->inode.data_vdi_id);
1780 /* refresh inode. */
1781 fd = connect_to_sdog(s->addr, s->port);
1782 if (fd < 0) {
1783 ret = fd;
1784 goto cleanup;
1787 ret = write_object(fd, (char *)&s->inode, vid_to_vdi_oid(s->inode.vdi_id),
1788 s->inode.nr_copies, datalen, 0, 0, s->cache_enabled);
1789 if (ret < 0) {
1790 error_report("failed to write snapshot's inode.");
1791 goto cleanup;
1794 ret = do_sd_create(s->name, s->inode.vdi_size, s->inode.vdi_id, &new_vid, 1,
1795 s->addr, s->port);
1796 if (ret < 0) {
1797 error_report("failed to create inode for snapshot. %s",
1798 strerror(errno));
1799 goto cleanup;
1802 inode = (SheepdogInode *)g_malloc(datalen);
1804 ret = read_object(fd, (char *)inode, vid_to_vdi_oid(new_vid),
1805 s->inode.nr_copies, datalen, 0, s->cache_enabled);
1807 if (ret < 0) {
1808 error_report("failed to read new inode info. %s", strerror(errno));
1809 goto cleanup;
1812 memcpy(&s->inode, inode, datalen);
1813 dprintf("s->inode: name %s snap_id %x oid %x\n",
1814 s->inode.name, s->inode.snap_id, s->inode.vdi_id);
1816 cleanup:
1817 closesocket(fd);
1818 return ret;
1821 static int sd_snapshot_goto(BlockDriverState *bs, const char *snapshot_id)
1823 BDRVSheepdogState *s = bs->opaque;
1824 BDRVSheepdogState *old_s;
1825 char vdi[SD_MAX_VDI_LEN], tag[SD_MAX_VDI_TAG_LEN];
1826 char *buf = NULL;
1827 uint32_t vid;
1828 uint32_t snapid = 0;
1829 int ret = 0, fd;
1831 old_s = g_malloc(sizeof(BDRVSheepdogState));
1833 memcpy(old_s, s, sizeof(BDRVSheepdogState));
1835 memset(vdi, 0, sizeof(vdi));
1836 strncpy(vdi, s->name, sizeof(vdi));
1838 memset(tag, 0, sizeof(tag));
1839 snapid = strtoul(snapshot_id, NULL, 10);
1840 if (!snapid) {
1841 strncpy(tag, s->name, sizeof(tag));
1844 ret = find_vdi_name(s, vdi, snapid, tag, &vid, 1);
1845 if (ret) {
1846 error_report("Failed to find_vdi_name");
1847 goto out;
1850 fd = connect_to_sdog(s->addr, s->port);
1851 if (fd < 0) {
1852 error_report("failed to connect");
1853 ret = fd;
1854 goto out;
1857 buf = g_malloc(SD_INODE_SIZE);
1858 ret = read_object(fd, buf, vid_to_vdi_oid(vid), s->inode.nr_copies,
1859 SD_INODE_SIZE, 0, s->cache_enabled);
1861 closesocket(fd);
1863 if (ret) {
1864 goto out;
1867 memcpy(&s->inode, buf, sizeof(s->inode));
1869 if (!s->inode.vm_state_size) {
1870 error_report("Invalid snapshot");
1871 ret = -ENOENT;
1872 goto out;
1875 s->is_snapshot = 1;
1877 g_free(buf);
1878 g_free(old_s);
1880 return 0;
1881 out:
1882 /* recover bdrv_sd_state */
1883 memcpy(s, old_s, sizeof(BDRVSheepdogState));
1884 g_free(buf);
1885 g_free(old_s);
1887 error_report("failed to open. recover old bdrv_sd_state.");
1889 return ret;
1892 static int sd_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
1894 /* FIXME: Delete specified snapshot id. */
1895 return 0;
1898 static int sd_snapshot_list(BlockDriverState *bs, QEMUSnapshotInfo **psn_tab)
1900 BDRVSheepdogState *s = bs->opaque;
1901 SheepdogReq req;
1902 int fd, nr = 1024, ret, max = BITS_TO_LONGS(SD_NR_VDIS) * sizeof(long);
1903 QEMUSnapshotInfo *sn_tab = NULL;
1904 unsigned wlen, rlen;
1905 int found = 0;
1906 static SheepdogInode inode;
1907 unsigned long *vdi_inuse;
1908 unsigned int start_nr;
1909 uint64_t hval;
1910 uint32_t vid;
1912 vdi_inuse = g_malloc(max);
1914 fd = connect_to_sdog(s->addr, s->port);
1915 if (fd < 0) {
1916 ret = fd;
1917 goto out;
1920 rlen = max;
1921 wlen = 0;
1923 memset(&req, 0, sizeof(req));
1925 req.opcode = SD_OP_READ_VDIS;
1926 req.data_length = max;
1928 ret = do_req(fd, (SheepdogReq *)&req, vdi_inuse, &wlen, &rlen);
1930 closesocket(fd);
1931 if (ret) {
1932 goto out;
1935 sn_tab = g_malloc0(nr * sizeof(*sn_tab));
1937 /* calculate a vdi id with hash function */
1938 hval = fnv_64a_buf(s->name, strlen(s->name), FNV1A_64_INIT);
1939 start_nr = hval & (SD_NR_VDIS - 1);
1941 fd = connect_to_sdog(s->addr, s->port);
1942 if (fd < 0) {
1943 error_report("failed to connect");
1944 ret = fd;
1945 goto out;
1948 for (vid = start_nr; found < nr; vid = (vid + 1) % SD_NR_VDIS) {
1949 if (!test_bit(vid, vdi_inuse)) {
1950 break;
1953 /* we don't need to read entire object */
1954 ret = read_object(fd, (char *)&inode, vid_to_vdi_oid(vid),
1955 0, SD_INODE_SIZE - sizeof(inode.data_vdi_id), 0,
1956 s->cache_enabled);
1958 if (ret) {
1959 continue;
1962 if (!strcmp(inode.name, s->name) && is_snapshot(&inode)) {
1963 sn_tab[found].date_sec = inode.snap_ctime >> 32;
1964 sn_tab[found].date_nsec = inode.snap_ctime & 0xffffffff;
1965 sn_tab[found].vm_state_size = inode.vm_state_size;
1966 sn_tab[found].vm_clock_nsec = inode.vm_clock_nsec;
1968 snprintf(sn_tab[found].id_str, sizeof(sn_tab[found].id_str), "%u",
1969 inode.snap_id);
1970 strncpy(sn_tab[found].name, inode.tag,
1971 MIN(sizeof(sn_tab[found].name), sizeof(inode.tag)));
1972 found++;
1976 closesocket(fd);
1977 out:
1978 *psn_tab = sn_tab;
1980 g_free(vdi_inuse);
1982 if (ret < 0) {
1983 return ret;
1986 return found;
1989 static int do_load_save_vmstate(BDRVSheepdogState *s, uint8_t *data,
1990 int64_t pos, int size, int load)
1992 int fd, create;
1993 int ret = 0, remaining = size;
1994 unsigned int data_len;
1995 uint64_t vmstate_oid;
1996 uint32_t vdi_index;
1997 uint64_t offset;
1999 fd = connect_to_sdog(s->addr, s->port);
2000 if (fd < 0) {
2001 return fd;
2004 while (remaining) {
2005 vdi_index = pos / SD_DATA_OBJ_SIZE;
2006 offset = pos % SD_DATA_OBJ_SIZE;
2008 data_len = MIN(remaining, SD_DATA_OBJ_SIZE);
2010 vmstate_oid = vid_to_vmstate_oid(s->inode.vdi_id, vdi_index);
2012 create = (offset == 0);
2013 if (load) {
2014 ret = read_object(fd, (char *)data, vmstate_oid,
2015 s->inode.nr_copies, data_len, offset,
2016 s->cache_enabled);
2017 } else {
2018 ret = write_object(fd, (char *)data, vmstate_oid,
2019 s->inode.nr_copies, data_len, offset, create,
2020 s->cache_enabled);
2023 if (ret < 0) {
2024 error_report("failed to save vmstate %s", strerror(errno));
2025 goto cleanup;
2028 pos += data_len;
2029 remaining -= data_len;
2031 ret = size;
2032 cleanup:
2033 closesocket(fd);
2034 return ret;
2037 static int sd_save_vmstate(BlockDriverState *bs, const uint8_t *data,
2038 int64_t pos, int size)
2040 BDRVSheepdogState *s = bs->opaque;
2042 return do_load_save_vmstate(s, (uint8_t *)data, pos, size, 0);
2045 static int sd_load_vmstate(BlockDriverState *bs, uint8_t *data,
2046 int64_t pos, int size)
2048 BDRVSheepdogState *s = bs->opaque;
2050 return do_load_save_vmstate(s, data, pos, size, 1);
2054 static QEMUOptionParameter sd_create_options[] = {
2056 .name = BLOCK_OPT_SIZE,
2057 .type = OPT_SIZE,
2058 .help = "Virtual disk size"
2061 .name = BLOCK_OPT_BACKING_FILE,
2062 .type = OPT_STRING,
2063 .help = "File name of a base image"
2066 .name = BLOCK_OPT_PREALLOC,
2067 .type = OPT_STRING,
2068 .help = "Preallocation mode (allowed values: off, full)"
2070 { NULL }
2073 BlockDriver bdrv_sheepdog = {
2074 .format_name = "sheepdog",
2075 .protocol_name = "sheepdog",
2076 .instance_size = sizeof(BDRVSheepdogState),
2077 .bdrv_file_open = sd_open,
2078 .bdrv_close = sd_close,
2079 .bdrv_create = sd_create,
2080 .bdrv_getlength = sd_getlength,
2081 .bdrv_truncate = sd_truncate,
2083 .bdrv_co_readv = sd_co_readv,
2084 .bdrv_co_writev = sd_co_writev,
2085 .bdrv_co_flush_to_disk = sd_co_flush_to_disk,
2087 .bdrv_snapshot_create = sd_snapshot_create,
2088 .bdrv_snapshot_goto = sd_snapshot_goto,
2089 .bdrv_snapshot_delete = sd_snapshot_delete,
2090 .bdrv_snapshot_list = sd_snapshot_list,
2092 .bdrv_save_vmstate = sd_save_vmstate,
2093 .bdrv_load_vmstate = sd_load_vmstate,
2095 .create_options = sd_create_options,
2098 static void bdrv_sheepdog_init(void)
2100 bdrv_register(&bdrv_sheepdog);
2102 block_init(bdrv_sheepdog_init);