]> git.proxmox.com Git - qemu.git/blob - block/sheepdog.c
sheepdog: use coroutine based socket functions in coroutine context
[qemu.git] / block / sheepdog.c
1 /*
2 * Copyright (C) 2009-2010 Nippon Telegraph and Telephone Corporation.
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License version
6 * 2 as published by the Free Software Foundation.
7 *
8 * You should have received a copy of the GNU General Public License
9 * along with this program. If not, see <http://www.gnu.org/licenses/>.
10 *
11 * Contributions after 2012-01-13 are licensed under the terms of the
12 * GNU GPL, version 2 or (at your option) any later version.
13 */
14
15 #include "qemu-common.h"
16 #include "qemu-error.h"
17 #include "qemu_socket.h"
18 #include "block_int.h"
19 #include "bitops.h"
20
21 #define SD_PROTO_VER 0x01
22
23 #define SD_DEFAULT_ADDR "localhost"
24 #define SD_DEFAULT_PORT "7000"
25
26 #define SD_OP_CREATE_AND_WRITE_OBJ 0x01
27 #define SD_OP_READ_OBJ 0x02
28 #define SD_OP_WRITE_OBJ 0x03
29
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
36
37 #define SD_FLAG_CMD_WRITE 0x01
38 #define SD_FLAG_CMD_COW 0x02
39 #define SD_FLAG_CMD_CACHE 0x04
40
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 */
66
67 /*
68 * Object ID rules
69 *
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
75 */
76
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
88
89 #define SD_INODE_SIZE (sizeof(SheepdogInode))
90 #define CURRENT_VDI_ID 0
91
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;
101
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;
112
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;
126
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;
138
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;
152
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;
165
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;
183
184 /*
185 * 64 bit FNV-1a non-zero initial basis
186 */
187 #define FNV1A_64_INIT ((uint64_t)0xcbf29ce484222325ULL)
188
189 /*
190 * 64 bit Fowler/Noll/Vo FNV-1a hash code
191 */
192 static inline uint64_t fnv_64a_buf(void *buf, size_t len, uint64_t hval)
193 {
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);
200 }
201 return hval;
202 }
203
204 static inline int is_data_obj_writable(SheepdogInode *inode, unsigned int idx)
205 {
206 return inode->vdi_id == inode->data_vdi_id[idx];
207 }
208
209 static inline int is_data_obj(uint64_t oid)
210 {
211 return !(VDI_BIT & oid);
212 }
213
214 static inline uint64_t data_oid_to_idx(uint64_t oid)
215 {
216 return oid & (MAX_DATA_OBJS - 1);
217 }
218
219 static inline uint64_t vid_to_vdi_oid(uint32_t vid)
220 {
221 return VDI_BIT | ((uint64_t)vid << VDI_SPACE_SHIFT);
222 }
223
224 static inline uint64_t vid_to_vmstate_oid(uint32_t vid, uint32_t idx)
225 {
226 return VMSTATE_BIT | ((uint64_t)vid << VDI_SPACE_SHIFT) | idx;
227 }
228
229 static inline uint64_t vid_to_data_oid(uint32_t vid, uint32_t idx)
230 {
231 return ((uint64_t)vid << VDI_SPACE_SHIFT) | idx;
232 }
233
234 static inline int is_snapshot(struct SheepdogInode *inode)
235 {
236 return !!inode->snap_ctime;
237 }
238
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
248
249 typedef struct SheepdogAIOCB SheepdogAIOCB;
250
251 typedef struct AIOReq {
252 SheepdogAIOCB *aiocb;
253 unsigned int iov_offset;
254
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;
261
262 QLIST_ENTRY(AIOReq) outstanding_aio_siblings;
263 QLIST_ENTRY(AIOReq) aioreq_siblings;
264 } AIOReq;
265
266 enum AIOCBState {
267 AIOCB_WRITE_UDATA,
268 AIOCB_READ_UDATA,
269 };
270
271 struct SheepdogAIOCB {
272 BlockDriverAIOCB common;
273
274 QEMUIOVector *qiov;
275
276 int64_t sector_num;
277 int nb_sectors;
278
279 int ret;
280 enum AIOCBState aiocb_type;
281
282 Coroutine *coroutine;
283 void (*aio_done_func)(SheepdogAIOCB *);
284
285 int canceled;
286
287 QLIST_HEAD(aioreq_head, AIOReq) aioreq_head;
288 };
289
290 typedef struct BDRVSheepdogState {
291 SheepdogInode inode;
292
293 uint32_t min_dirty_data_idx;
294 uint32_t max_dirty_data_idx;
295
296 char name[SD_MAX_VDI_LEN];
297 int is_snapshot;
298 uint8_t cache_enabled;
299
300 char *addr;
301 char *port;
302 int fd;
303 int flush_fd;
304
305 CoMutex lock;
306 Coroutine *co_send;
307 Coroutine *co_recv;
308
309 uint32_t aioreq_seq_num;
310 QLIST_HEAD(outstanding_aio_head, AIOReq) outstanding_aio_head;
311 } BDRVSheepdogState;
312
313 static const char * sd_strerror(int err)
314 {
315 int i;
316
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"},
346 };
347
348 for (i = 0; i < ARRAY_SIZE(errors); ++i) {
349 if (errors[i].err == err) {
350 return errors[i].desc;
351 }
352 }
353
354 return "Invalid error code";
355 }
356
357 /*
358 * Sheepdog I/O handling:
359 *
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.
364 *
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.
370 */
371
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)
376 {
377 AIOReq *aio_req;
378
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++;
388
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);
392
393 return aio_req;
394 }
395
396 static inline int free_aio_req(BDRVSheepdogState *s, AIOReq *aio_req)
397 {
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);
402
403 return !QLIST_EMPTY(&acb->aioreq_head);
404 }
405
406 static void coroutine_fn sd_finish_aiocb(SheepdogAIOCB *acb)
407 {
408 if (!acb->canceled) {
409 qemu_coroutine_enter(acb->coroutine, NULL);
410 }
411 qemu_aio_release(acb);
412 }
413
414 static void sd_aio_cancel(BlockDriverAIOCB *blockacb)
415 {
416 SheepdogAIOCB *acb = (SheepdogAIOCB *)blockacb;
417
418 /*
419 * Sheepdog cannot cancel the requests which are already sent to
420 * the servers, so we just complete the request with -EIO here.
421 */
422 acb->ret = -EIO;
423 qemu_coroutine_enter(acb->coroutine, NULL);
424 acb->canceled = 1;
425 }
426
427 static AIOPool sd_aio_pool = {
428 .aiocb_size = sizeof(SheepdogAIOCB),
429 .cancel = sd_aio_cancel,
430 };
431
432 static SheepdogAIOCB *sd_aio_setup(BlockDriverState *bs, QEMUIOVector *qiov,
433 int64_t sector_num, int nb_sectors,
434 BlockDriverCompletionFunc *cb, void *opaque)
435 {
436 SheepdogAIOCB *acb;
437
438 acb = qemu_aio_get(&sd_aio_pool, bs, cb, opaque);
439
440 acb->qiov = qiov;
441
442 acb->sector_num = sector_num;
443 acb->nb_sectors = nb_sectors;
444
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;
451 }
452
453 static int connect_to_sdog(const char *addr, const char *port)
454 {
455 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
456 int fd, ret;
457 struct addrinfo hints, *res, *res0;
458
459 if (!addr) {
460 addr = SD_DEFAULT_ADDR;
461 port = SD_DEFAULT_PORT;
462 }
463
464 memset(&hints, 0, sizeof(hints));
465 hints.ai_socktype = SOCK_STREAM;
466
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 -errno;
472 }
473
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;
479 }
480
481 fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
482 if (fd < 0) {
483 continue;
484 }
485
486 reconnect:
487 ret = connect(fd, res->ai_addr, res->ai_addrlen);
488 if (ret < 0) {
489 if (errno == EINTR) {
490 goto reconnect;
491 }
492 break;
493 }
494
495 dprintf("connected to %s:%s\n", addr, port);
496 goto success;
497 }
498 fd = -errno;
499 error_report("failed connect to %s:%s", addr, port);
500 success:
501 freeaddrinfo(res0);
502 return fd;
503 }
504
505 static int send_req(int sockfd, SheepdogReq *hdr, void *data,
506 unsigned int *wlen)
507 {
508 int ret;
509
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 -errno;
514 }
515
516 ret = qemu_send_full(sockfd, data, *wlen, 0);
517 if (ret < *wlen) {
518 error_report("failed to send a req, %s", strerror(errno));
519 ret = -errno;
520 }
521
522 return ret;
523 }
524
525 static coroutine_fn int send_co_req(int sockfd, SheepdogReq *hdr, void *data,
526 unsigned int *wlen)
527 {
528 int ret;
529
530 ret = qemu_co_send(sockfd, hdr, sizeof(*hdr));
531 if (ret < sizeof(*hdr)) {
532 error_report("failed to send a req, %s", strerror(errno));
533 return ret;
534 }
535
536 ret = qemu_co_send(sockfd, data, *wlen);
537 if (ret < *wlen) {
538 error_report("failed to send a req, %s", strerror(errno));
539 }
540
541 return ret;
542 }
543
544 static coroutine_fn int do_co_req(int sockfd, SheepdogReq *hdr, void *data,
545 unsigned int *wlen, unsigned int *rlen);
546
547 static int do_req(int sockfd, SheepdogReq *hdr, void *data,
548 unsigned int *wlen, unsigned int *rlen)
549 {
550 int ret;
551
552 if (qemu_in_coroutine()) {
553 return do_co_req(sockfd, hdr, data, wlen, rlen);
554 }
555
556 socket_set_block(sockfd);
557 ret = send_req(sockfd, hdr, data, wlen);
558 if (ret < 0) {
559 goto out;
560 }
561
562 ret = qemu_recv_full(sockfd, hdr, sizeof(*hdr), 0);
563 if (ret < sizeof(*hdr)) {
564 error_report("failed to get a rsp, %s", strerror(errno));
565 ret = -errno;
566 goto out;
567 }
568
569 if (*rlen > hdr->data_length) {
570 *rlen = hdr->data_length;
571 }
572
573 if (*rlen) {
574 ret = qemu_recv_full(sockfd, data, *rlen, 0);
575 if (ret < *rlen) {
576 error_report("failed to get the data, %s", strerror(errno));
577 ret = -errno;
578 goto out;
579 }
580 }
581 ret = 0;
582 out:
583 socket_set_nonblock(sockfd);
584 return ret;
585 }
586
587 static void restart_co_req(void *opaque)
588 {
589 Coroutine *co = opaque;
590
591 qemu_coroutine_enter(co, NULL);
592 }
593
594 static coroutine_fn int do_co_req(int sockfd, SheepdogReq *hdr, void *data,
595 unsigned int *wlen, unsigned int *rlen)
596 {
597 int ret;
598 Coroutine *co;
599
600 co = qemu_coroutine_self();
601 qemu_aio_set_fd_handler(sockfd, NULL, restart_co_req, NULL, co);
602
603 socket_set_block(sockfd);
604 ret = send_co_req(sockfd, hdr, data, wlen);
605 if (ret < 0) {
606 goto out;
607 }
608
609 qemu_aio_set_fd_handler(sockfd, restart_co_req, NULL, NULL, co);
610
611 ret = qemu_co_recv(sockfd, hdr, sizeof(*hdr));
612 if (ret < sizeof(*hdr)) {
613 error_report("failed to get a rsp, %s", strerror(errno));
614 ret = -errno;
615 goto out;
616 }
617
618 if (*rlen > hdr->data_length) {
619 *rlen = hdr->data_length;
620 }
621
622 if (*rlen) {
623 ret = qemu_co_recv(sockfd, data, *rlen);
624 if (ret < *rlen) {
625 error_report("failed to get the data, %s", strerror(errno));
626 ret = -errno;
627 goto out;
628 }
629 }
630 ret = 0;
631 out:
632 qemu_aio_set_fd_handler(sockfd, NULL, NULL, NULL, NULL);
633 socket_set_nonblock(sockfd);
634 return ret;
635 }
636
637 static int coroutine_fn add_aio_request(BDRVSheepdogState *s, AIOReq *aio_req,
638 struct iovec *iov, int niov, int create,
639 enum AIOCBState aiocb_type);
640
641 /*
642 * This function searchs pending requests to the object `oid', and
643 * sends them.
644 */
645 static void coroutine_fn send_pending_req(BDRVSheepdogState *s, uint64_t oid, uint32_t id)
646 {
647 AIOReq *aio_req, *next;
648 SheepdogAIOCB *acb;
649 int ret;
650
651 QLIST_FOREACH_SAFE(aio_req, &s->outstanding_aio_head,
652 outstanding_aio_siblings, next) {
653 if (id == aio_req->id) {
654 continue;
655 }
656 if (aio_req->oid != oid) {
657 continue;
658 }
659
660 acb = aio_req->aiocb;
661 ret = add_aio_request(s, aio_req, acb->qiov->iov,
662 acb->qiov->niov, 0, acb->aiocb_type);
663 if (ret < 0) {
664 error_report("add_aio_request is failed");
665 free_aio_req(s, aio_req);
666 if (QLIST_EMPTY(&acb->aioreq_head)) {
667 sd_finish_aiocb(acb);
668 }
669 }
670 }
671 }
672
673 /*
674 * Receive responses of the I/O requests.
675 *
676 * This function is registered as a fd handler, and called from the
677 * main loop when s->fd is ready for reading responses.
678 */
679 static void coroutine_fn aio_read_response(void *opaque)
680 {
681 SheepdogObjRsp rsp;
682 BDRVSheepdogState *s = opaque;
683 int fd = s->fd;
684 int ret;
685 AIOReq *aio_req = NULL;
686 SheepdogAIOCB *acb;
687 int rest;
688 unsigned long idx;
689
690 if (QLIST_EMPTY(&s->outstanding_aio_head)) {
691 goto out;
692 }
693
694 /* read a header */
695 ret = qemu_co_recv(fd, &rsp, sizeof(rsp));
696 if (ret < 0) {
697 error_report("failed to get the header, %s", strerror(errno));
698 goto out;
699 }
700
701 /* find the right aio_req from the outstanding_aio list */
702 QLIST_FOREACH(aio_req, &s->outstanding_aio_head, outstanding_aio_siblings) {
703 if (aio_req->id == rsp.id) {
704 break;
705 }
706 }
707 if (!aio_req) {
708 error_report("cannot find aio_req %x", rsp.id);
709 goto out;
710 }
711
712 acb = aio_req->aiocb;
713
714 switch (acb->aiocb_type) {
715 case AIOCB_WRITE_UDATA:
716 /* this coroutine context is no longer suitable for co_recv
717 * because we may send data to update vdi objects */
718 s->co_recv = NULL;
719 if (!is_data_obj(aio_req->oid)) {
720 break;
721 }
722 idx = data_oid_to_idx(aio_req->oid);
723
724 if (s->inode.data_vdi_id[idx] != s->inode.vdi_id) {
725 /*
726 * If the object is newly created one, we need to update
727 * the vdi object (metadata object). min_dirty_data_idx
728 * and max_dirty_data_idx are changed to include updated
729 * index between them.
730 */
731 s->inode.data_vdi_id[idx] = s->inode.vdi_id;
732 s->max_dirty_data_idx = MAX(idx, s->max_dirty_data_idx);
733 s->min_dirty_data_idx = MIN(idx, s->min_dirty_data_idx);
734
735 /*
736 * Some requests may be blocked because simultaneous
737 * create requests are not allowed, so we search the
738 * pending requests here.
739 */
740 send_pending_req(s, vid_to_data_oid(s->inode.vdi_id, idx), rsp.id);
741 }
742 break;
743 case AIOCB_READ_UDATA:
744 ret = qemu_co_recvv(fd, acb->qiov->iov, rsp.data_length,
745 aio_req->iov_offset);
746 if (ret < 0) {
747 error_report("failed to get the data, %s", strerror(errno));
748 goto out;
749 }
750 break;
751 }
752
753 if (rsp.result != SD_RES_SUCCESS) {
754 acb->ret = -EIO;
755 error_report("%s", sd_strerror(rsp.result));
756 }
757
758 rest = free_aio_req(s, aio_req);
759 if (!rest) {
760 /*
761 * We've finished all requests which belong to the AIOCB, so
762 * we can switch back to sd_co_readv/writev now.
763 */
764 acb->aio_done_func(acb);
765 }
766 out:
767 s->co_recv = NULL;
768 }
769
770 static void co_read_response(void *opaque)
771 {
772 BDRVSheepdogState *s = opaque;
773
774 if (!s->co_recv) {
775 s->co_recv = qemu_coroutine_create(aio_read_response);
776 }
777
778 qemu_coroutine_enter(s->co_recv, opaque);
779 }
780
781 static void co_write_request(void *opaque)
782 {
783 BDRVSheepdogState *s = opaque;
784
785 qemu_coroutine_enter(s->co_send, NULL);
786 }
787
788 static int aio_flush_request(void *opaque)
789 {
790 BDRVSheepdogState *s = opaque;
791
792 return !QLIST_EMPTY(&s->outstanding_aio_head);
793 }
794
795 static int set_nodelay(int fd)
796 {
797 int ret, opt;
798
799 opt = 1;
800 ret = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&opt, sizeof(opt));
801 return ret;
802 }
803
804 /*
805 * Return a socket discriptor to read/write objects.
806 *
807 * We cannot use this discriptor for other operations because
808 * the block driver may be on waiting response from the server.
809 */
810 static int get_sheep_fd(BDRVSheepdogState *s)
811 {
812 int ret, fd;
813
814 fd = connect_to_sdog(s->addr, s->port);
815 if (fd < 0) {
816 error_report("%s", strerror(errno));
817 return fd;
818 }
819
820 socket_set_nonblock(fd);
821
822 ret = set_nodelay(fd);
823 if (ret) {
824 error_report("%s", strerror(errno));
825 closesocket(fd);
826 return -errno;
827 }
828
829 qemu_aio_set_fd_handler(fd, co_read_response, NULL, aio_flush_request, s);
830 return fd;
831 }
832
833 /*
834 * Parse a filename
835 *
836 * filename must be one of the following formats:
837 * 1. [vdiname]
838 * 2. [vdiname]:[snapid]
839 * 3. [vdiname]:[tag]
840 * 4. [hostname]:[port]:[vdiname]
841 * 5. [hostname]:[port]:[vdiname]:[snapid]
842 * 6. [hostname]:[port]:[vdiname]:[tag]
843 *
844 * You can boot from the snapshot images by specifying `snapid` or
845 * `tag'.
846 *
847 * You can run VMs outside the Sheepdog cluster by specifying
848 * `hostname' and `port' (experimental).
849 */
850 static int parse_vdiname(BDRVSheepdogState *s, const char *filename,
851 char *vdi, uint32_t *snapid, char *tag)
852 {
853 char *p, *q;
854 int nr_sep;
855
856 p = q = g_strdup(filename);
857
858 /* count the number of separators */
859 nr_sep = 0;
860 while (*p) {
861 if (*p == ':') {
862 nr_sep++;
863 }
864 p++;
865 }
866 p = q;
867
868 /* use the first two tokens as hostname and port number. */
869 if (nr_sep >= 2) {
870 s->addr = p;
871 p = strchr(p, ':');
872 *p++ = '\0';
873
874 s->port = p;
875 p = strchr(p, ':');
876 *p++ = '\0';
877 } else {
878 s->addr = NULL;
879 s->port = 0;
880 }
881
882 strncpy(vdi, p, SD_MAX_VDI_LEN);
883
884 p = strchr(vdi, ':');
885 if (p) {
886 *p++ = '\0';
887 *snapid = strtoul(p, NULL, 10);
888 if (*snapid == 0) {
889 strncpy(tag, p, SD_MAX_VDI_TAG_LEN);
890 }
891 } else {
892 *snapid = CURRENT_VDI_ID; /* search current vdi */
893 }
894
895 if (s->addr == NULL) {
896 g_free(q);
897 }
898
899 return 0;
900 }
901
902 static int find_vdi_name(BDRVSheepdogState *s, char *filename, uint32_t snapid,
903 char *tag, uint32_t *vid, int for_snapshot)
904 {
905 int ret, fd;
906 SheepdogVdiReq hdr;
907 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
908 unsigned int wlen, rlen = 0;
909 char buf[SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN];
910
911 fd = connect_to_sdog(s->addr, s->port);
912 if (fd < 0) {
913 return fd;
914 }
915
916 memset(buf, 0, sizeof(buf));
917 strncpy(buf, filename, SD_MAX_VDI_LEN);
918 strncpy(buf + SD_MAX_VDI_LEN, tag, SD_MAX_VDI_TAG_LEN);
919
920 memset(&hdr, 0, sizeof(hdr));
921 if (for_snapshot) {
922 hdr.opcode = SD_OP_GET_VDI_INFO;
923 } else {
924 hdr.opcode = SD_OP_LOCK_VDI;
925 }
926 wlen = SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN;
927 hdr.proto_ver = SD_PROTO_VER;
928 hdr.data_length = wlen;
929 hdr.snapid = snapid;
930 hdr.flags = SD_FLAG_CMD_WRITE;
931
932 ret = do_req(fd, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
933 if (ret) {
934 goto out;
935 }
936
937 if (rsp->result != SD_RES_SUCCESS) {
938 error_report("cannot get vdi info, %s, %s %d %s",
939 sd_strerror(rsp->result), filename, snapid, tag);
940 if (rsp->result == SD_RES_NO_VDI) {
941 ret = -ENOENT;
942 } else {
943 ret = -EIO;
944 }
945 goto out;
946 }
947 *vid = rsp->vdi_id;
948
949 ret = 0;
950 out:
951 closesocket(fd);
952 return ret;
953 }
954
955 static int coroutine_fn add_aio_request(BDRVSheepdogState *s, AIOReq *aio_req,
956 struct iovec *iov, int niov, int create,
957 enum AIOCBState aiocb_type)
958 {
959 int nr_copies = s->inode.nr_copies;
960 SheepdogObjReq hdr;
961 unsigned int wlen;
962 int ret;
963 uint64_t oid = aio_req->oid;
964 unsigned int datalen = aio_req->data_len;
965 uint64_t offset = aio_req->offset;
966 uint8_t flags = aio_req->flags;
967 uint64_t old_oid = aio_req->base_oid;
968
969 if (!nr_copies) {
970 error_report("bug");
971 }
972
973 memset(&hdr, 0, sizeof(hdr));
974
975 if (aiocb_type == AIOCB_READ_UDATA) {
976 wlen = 0;
977 hdr.opcode = SD_OP_READ_OBJ;
978 hdr.flags = flags;
979 } else if (create) {
980 wlen = datalen;
981 hdr.opcode = SD_OP_CREATE_AND_WRITE_OBJ;
982 hdr.flags = SD_FLAG_CMD_WRITE | flags;
983 } else {
984 wlen = datalen;
985 hdr.opcode = SD_OP_WRITE_OBJ;
986 hdr.flags = SD_FLAG_CMD_WRITE | flags;
987 }
988
989 if (s->cache_enabled) {
990 hdr.flags |= SD_FLAG_CMD_CACHE;
991 }
992
993 hdr.oid = oid;
994 hdr.cow_oid = old_oid;
995 hdr.copies = s->inode.nr_copies;
996
997 hdr.data_length = datalen;
998 hdr.offset = offset;
999
1000 hdr.id = aio_req->id;
1001
1002 qemu_co_mutex_lock(&s->lock);
1003 s->co_send = qemu_coroutine_self();
1004 qemu_aio_set_fd_handler(s->fd, co_read_response, co_write_request,
1005 aio_flush_request, s);
1006 socket_set_cork(s->fd, 1);
1007
1008 /* send a header */
1009 ret = qemu_co_send(s->fd, &hdr, sizeof(hdr));
1010 if (ret < 0) {
1011 qemu_co_mutex_unlock(&s->lock);
1012 error_report("failed to send a req, %s", strerror(errno));
1013 return -errno;
1014 }
1015
1016 if (wlen) {
1017 ret = qemu_co_sendv(s->fd, iov, wlen, aio_req->iov_offset);
1018 if (ret < 0) {
1019 qemu_co_mutex_unlock(&s->lock);
1020 error_report("failed to send a data, %s", strerror(errno));
1021 return -errno;
1022 }
1023 }
1024
1025 socket_set_cork(s->fd, 0);
1026 qemu_aio_set_fd_handler(s->fd, co_read_response, NULL,
1027 aio_flush_request, s);
1028 qemu_co_mutex_unlock(&s->lock);
1029
1030 return 0;
1031 }
1032
1033 static int read_write_object(int fd, char *buf, uint64_t oid, int copies,
1034 unsigned int datalen, uint64_t offset,
1035 int write, int create, uint8_t cache)
1036 {
1037 SheepdogObjReq hdr;
1038 SheepdogObjRsp *rsp = (SheepdogObjRsp *)&hdr;
1039 unsigned int wlen, rlen;
1040 int ret;
1041
1042 memset(&hdr, 0, sizeof(hdr));
1043
1044 if (write) {
1045 wlen = datalen;
1046 rlen = 0;
1047 hdr.flags = SD_FLAG_CMD_WRITE;
1048 if (create) {
1049 hdr.opcode = SD_OP_CREATE_AND_WRITE_OBJ;
1050 } else {
1051 hdr.opcode = SD_OP_WRITE_OBJ;
1052 }
1053 } else {
1054 wlen = 0;
1055 rlen = datalen;
1056 hdr.opcode = SD_OP_READ_OBJ;
1057 }
1058
1059 if (cache) {
1060 hdr.flags |= SD_FLAG_CMD_CACHE;
1061 }
1062
1063 hdr.oid = oid;
1064 hdr.data_length = datalen;
1065 hdr.offset = offset;
1066 hdr.copies = copies;
1067
1068 ret = do_req(fd, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
1069 if (ret) {
1070 error_report("failed to send a request to the sheep");
1071 return ret;
1072 }
1073
1074 switch (rsp->result) {
1075 case SD_RES_SUCCESS:
1076 return 0;
1077 default:
1078 error_report("%s", sd_strerror(rsp->result));
1079 return -EIO;
1080 }
1081 }
1082
1083 static int read_object(int fd, char *buf, uint64_t oid, int copies,
1084 unsigned int datalen, uint64_t offset, uint8_t cache)
1085 {
1086 return read_write_object(fd, buf, oid, copies, datalen, offset, 0, 0,
1087 cache);
1088 }
1089
1090 static int write_object(int fd, char *buf, uint64_t oid, int copies,
1091 unsigned int datalen, uint64_t offset, int create,
1092 uint8_t cache)
1093 {
1094 return read_write_object(fd, buf, oid, copies, datalen, offset, 1, create,
1095 cache);
1096 }
1097
1098 static int sd_open(BlockDriverState *bs, const char *filename, int flags)
1099 {
1100 int ret, fd;
1101 uint32_t vid = 0;
1102 BDRVSheepdogState *s = bs->opaque;
1103 char vdi[SD_MAX_VDI_LEN], tag[SD_MAX_VDI_TAG_LEN];
1104 uint32_t snapid;
1105 char *buf = NULL;
1106
1107 strstart(filename, "sheepdog:", (const char **)&filename);
1108
1109 QLIST_INIT(&s->outstanding_aio_head);
1110 s->fd = -1;
1111
1112 memset(vdi, 0, sizeof(vdi));
1113 memset(tag, 0, sizeof(tag));
1114 if (parse_vdiname(s, filename, vdi, &snapid, tag) < 0) {
1115 ret = -EINVAL;
1116 goto out;
1117 }
1118 s->fd = get_sheep_fd(s);
1119 if (s->fd < 0) {
1120 ret = s->fd;
1121 goto out;
1122 }
1123
1124 ret = find_vdi_name(s, vdi, snapid, tag, &vid, 0);
1125 if (ret) {
1126 goto out;
1127 }
1128
1129 if (flags & BDRV_O_CACHE_WB) {
1130 s->cache_enabled = 1;
1131 s->flush_fd = connect_to_sdog(s->addr, s->port);
1132 if (s->flush_fd < 0) {
1133 error_report("failed to connect");
1134 ret = s->flush_fd;
1135 goto out;
1136 }
1137 }
1138
1139 if (snapid || tag[0] != '\0') {
1140 dprintf("%" PRIx32 " snapshot inode was open.\n", vid);
1141 s->is_snapshot = 1;
1142 }
1143
1144 fd = connect_to_sdog(s->addr, s->port);
1145 if (fd < 0) {
1146 error_report("failed to connect");
1147 ret = fd;
1148 goto out;
1149 }
1150
1151 buf = g_malloc(SD_INODE_SIZE);
1152 ret = read_object(fd, buf, vid_to_vdi_oid(vid), 0, SD_INODE_SIZE, 0,
1153 s->cache_enabled);
1154
1155 closesocket(fd);
1156
1157 if (ret) {
1158 goto out;
1159 }
1160
1161 memcpy(&s->inode, buf, sizeof(s->inode));
1162 s->min_dirty_data_idx = UINT32_MAX;
1163 s->max_dirty_data_idx = 0;
1164
1165 bs->total_sectors = s->inode.vdi_size / SECTOR_SIZE;
1166 strncpy(s->name, vdi, sizeof(s->name));
1167 qemu_co_mutex_init(&s->lock);
1168 g_free(buf);
1169 return 0;
1170 out:
1171 qemu_aio_set_fd_handler(s->fd, NULL, NULL, NULL, NULL);
1172 if (s->fd >= 0) {
1173 closesocket(s->fd);
1174 }
1175 g_free(buf);
1176 return ret;
1177 }
1178
1179 static int do_sd_create(char *filename, int64_t vdi_size,
1180 uint32_t base_vid, uint32_t *vdi_id, int snapshot,
1181 const char *addr, const char *port)
1182 {
1183 SheepdogVdiReq hdr;
1184 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
1185 int fd, ret;
1186 unsigned int wlen, rlen = 0;
1187 char buf[SD_MAX_VDI_LEN];
1188
1189 fd = connect_to_sdog(addr, port);
1190 if (fd < 0) {
1191 return fd;
1192 }
1193
1194 memset(buf, 0, sizeof(buf));
1195 strncpy(buf, filename, SD_MAX_VDI_LEN);
1196
1197 memset(&hdr, 0, sizeof(hdr));
1198 hdr.opcode = SD_OP_NEW_VDI;
1199 hdr.base_vdi_id = base_vid;
1200
1201 wlen = SD_MAX_VDI_LEN;
1202
1203 hdr.flags = SD_FLAG_CMD_WRITE;
1204 hdr.snapid = snapshot;
1205
1206 hdr.data_length = wlen;
1207 hdr.vdi_size = vdi_size;
1208
1209 ret = do_req(fd, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
1210
1211 closesocket(fd);
1212
1213 if (ret) {
1214 return ret;
1215 }
1216
1217 if (rsp->result != SD_RES_SUCCESS) {
1218 error_report("%s, %s", sd_strerror(rsp->result), filename);
1219 return -EIO;
1220 }
1221
1222 if (vdi_id) {
1223 *vdi_id = rsp->vdi_id;
1224 }
1225
1226 return 0;
1227 }
1228
1229 static int sd_prealloc(const char *filename)
1230 {
1231 BlockDriverState *bs = NULL;
1232 uint32_t idx, max_idx;
1233 int64_t vdi_size;
1234 void *buf = g_malloc0(SD_DATA_OBJ_SIZE);
1235 int ret;
1236
1237 ret = bdrv_file_open(&bs, filename, BDRV_O_RDWR);
1238 if (ret < 0) {
1239 goto out;
1240 }
1241
1242 vdi_size = bdrv_getlength(bs);
1243 if (vdi_size < 0) {
1244 ret = vdi_size;
1245 goto out;
1246 }
1247 max_idx = DIV_ROUND_UP(vdi_size, SD_DATA_OBJ_SIZE);
1248
1249 for (idx = 0; idx < max_idx; idx++) {
1250 /*
1251 * The created image can be a cloned image, so we need to read
1252 * a data from the source image.
1253 */
1254 ret = bdrv_pread(bs, idx * SD_DATA_OBJ_SIZE, buf, SD_DATA_OBJ_SIZE);
1255 if (ret < 0) {
1256 goto out;
1257 }
1258 ret = bdrv_pwrite(bs, idx * SD_DATA_OBJ_SIZE, buf, SD_DATA_OBJ_SIZE);
1259 if (ret < 0) {
1260 goto out;
1261 }
1262 }
1263 out:
1264 if (bs) {
1265 bdrv_delete(bs);
1266 }
1267 g_free(buf);
1268
1269 return ret;
1270 }
1271
1272 static int sd_create(const char *filename, QEMUOptionParameter *options)
1273 {
1274 int ret = 0;
1275 uint32_t vid = 0, base_vid = 0;
1276 int64_t vdi_size = 0;
1277 char *backing_file = NULL;
1278 BDRVSheepdogState *s;
1279 char vdi[SD_MAX_VDI_LEN], tag[SD_MAX_VDI_TAG_LEN];
1280 uint32_t snapid;
1281 int prealloc = 0;
1282 const char *vdiname;
1283
1284 s = g_malloc0(sizeof(BDRVSheepdogState));
1285
1286 strstart(filename, "sheepdog:", &vdiname);
1287
1288 memset(vdi, 0, sizeof(vdi));
1289 memset(tag, 0, sizeof(tag));
1290 if (parse_vdiname(s, vdiname, vdi, &snapid, tag) < 0) {
1291 error_report("invalid filename");
1292 ret = -EINVAL;
1293 goto out;
1294 }
1295
1296 while (options && options->name) {
1297 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
1298 vdi_size = options->value.n;
1299 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
1300 backing_file = options->value.s;
1301 } else if (!strcmp(options->name, BLOCK_OPT_PREALLOC)) {
1302 if (!options->value.s || !strcmp(options->value.s, "off")) {
1303 prealloc = 0;
1304 } else if (!strcmp(options->value.s, "full")) {
1305 prealloc = 1;
1306 } else {
1307 error_report("Invalid preallocation mode: '%s'",
1308 options->value.s);
1309 ret = -EINVAL;
1310 goto out;
1311 }
1312 }
1313 options++;
1314 }
1315
1316 if (vdi_size > SD_MAX_VDI_SIZE) {
1317 error_report("too big image size");
1318 ret = -EINVAL;
1319 goto out;
1320 }
1321
1322 if (backing_file) {
1323 BlockDriverState *bs;
1324 BDRVSheepdogState *s;
1325 BlockDriver *drv;
1326
1327 /* Currently, only Sheepdog backing image is supported. */
1328 drv = bdrv_find_protocol(backing_file);
1329 if (!drv || strcmp(drv->protocol_name, "sheepdog") != 0) {
1330 error_report("backing_file must be a sheepdog image");
1331 ret = -EINVAL;
1332 goto out;
1333 }
1334
1335 ret = bdrv_file_open(&bs, backing_file, 0);
1336 if (ret < 0) {
1337 goto out;
1338 }
1339
1340 s = bs->opaque;
1341
1342 if (!is_snapshot(&s->inode)) {
1343 error_report("cannot clone from a non snapshot vdi");
1344 bdrv_delete(bs);
1345 ret = -EINVAL;
1346 goto out;
1347 }
1348
1349 base_vid = s->inode.vdi_id;
1350 bdrv_delete(bs);
1351 }
1352
1353 ret = do_sd_create(vdi, vdi_size, base_vid, &vid, 0, s->addr, s->port);
1354 if (!prealloc || ret) {
1355 goto out;
1356 }
1357
1358 ret = sd_prealloc(filename);
1359 out:
1360 g_free(s);
1361 return ret;
1362 }
1363
1364 static void sd_close(BlockDriverState *bs)
1365 {
1366 BDRVSheepdogState *s = bs->opaque;
1367 SheepdogVdiReq hdr;
1368 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
1369 unsigned int wlen, rlen = 0;
1370 int fd, ret;
1371
1372 dprintf("%s\n", s->name);
1373
1374 fd = connect_to_sdog(s->addr, s->port);
1375 if (fd < 0) {
1376 return;
1377 }
1378
1379 memset(&hdr, 0, sizeof(hdr));
1380
1381 hdr.opcode = SD_OP_RELEASE_VDI;
1382 wlen = strlen(s->name) + 1;
1383 hdr.data_length = wlen;
1384 hdr.flags = SD_FLAG_CMD_WRITE;
1385
1386 ret = do_req(fd, (SheepdogReq *)&hdr, s->name, &wlen, &rlen);
1387
1388 closesocket(fd);
1389
1390 if (!ret && rsp->result != SD_RES_SUCCESS &&
1391 rsp->result != SD_RES_VDI_NOT_LOCKED) {
1392 error_report("%s, %s", sd_strerror(rsp->result), s->name);
1393 }
1394
1395 qemu_aio_set_fd_handler(s->fd, NULL, NULL, NULL, NULL);
1396 closesocket(s->fd);
1397 if (s->cache_enabled) {
1398 closesocket(s->flush_fd);
1399 }
1400 g_free(s->addr);
1401 }
1402
1403 static int64_t sd_getlength(BlockDriverState *bs)
1404 {
1405 BDRVSheepdogState *s = bs->opaque;
1406
1407 return s->inode.vdi_size;
1408 }
1409
1410 static int sd_truncate(BlockDriverState *bs, int64_t offset)
1411 {
1412 BDRVSheepdogState *s = bs->opaque;
1413 int ret, fd;
1414 unsigned int datalen;
1415
1416 if (offset < s->inode.vdi_size) {
1417 error_report("shrinking is not supported");
1418 return -EINVAL;
1419 } else if (offset > SD_MAX_VDI_SIZE) {
1420 error_report("too big image size");
1421 return -EINVAL;
1422 }
1423
1424 fd = connect_to_sdog(s->addr, s->port);
1425 if (fd < 0) {
1426 return fd;
1427 }
1428
1429 /* we don't need to update entire object */
1430 datalen = SD_INODE_SIZE - sizeof(s->inode.data_vdi_id);
1431 s->inode.vdi_size = offset;
1432 ret = write_object(fd, (char *)&s->inode, vid_to_vdi_oid(s->inode.vdi_id),
1433 s->inode.nr_copies, datalen, 0, 0, s->cache_enabled);
1434 close(fd);
1435
1436 if (ret < 0) {
1437 error_report("failed to update an inode.");
1438 }
1439
1440 return ret;
1441 }
1442
1443 /*
1444 * This function is called after writing data objects. If we need to
1445 * update metadata, this sends a write request to the vdi object.
1446 * Otherwise, this switches back to sd_co_readv/writev.
1447 */
1448 static void coroutine_fn sd_write_done(SheepdogAIOCB *acb)
1449 {
1450 int ret;
1451 BDRVSheepdogState *s = acb->common.bs->opaque;
1452 struct iovec iov;
1453 AIOReq *aio_req;
1454 uint32_t offset, data_len, mn, mx;
1455
1456 mn = s->min_dirty_data_idx;
1457 mx = s->max_dirty_data_idx;
1458 if (mn <= mx) {
1459 /* we need to update the vdi object. */
1460 offset = sizeof(s->inode) - sizeof(s->inode.data_vdi_id) +
1461 mn * sizeof(s->inode.data_vdi_id[0]);
1462 data_len = (mx - mn + 1) * sizeof(s->inode.data_vdi_id[0]);
1463
1464 s->min_dirty_data_idx = UINT32_MAX;
1465 s->max_dirty_data_idx = 0;
1466
1467 iov.iov_base = &s->inode;
1468 iov.iov_len = sizeof(s->inode);
1469 aio_req = alloc_aio_req(s, acb, vid_to_vdi_oid(s->inode.vdi_id),
1470 data_len, offset, 0, 0, offset);
1471 ret = add_aio_request(s, aio_req, &iov, 1, 0, AIOCB_WRITE_UDATA);
1472 if (ret) {
1473 free_aio_req(s, aio_req);
1474 acb->ret = -EIO;
1475 goto out;
1476 }
1477
1478 acb->aio_done_func = sd_finish_aiocb;
1479 acb->aiocb_type = AIOCB_WRITE_UDATA;
1480 return;
1481 }
1482 out:
1483 sd_finish_aiocb(acb);
1484 }
1485
1486 /*
1487 * Create a writable VDI from a snapshot
1488 */
1489 static int sd_create_branch(BDRVSheepdogState *s)
1490 {
1491 int ret, fd;
1492 uint32_t vid;
1493 char *buf;
1494
1495 dprintf("%" PRIx32 " is snapshot.\n", s->inode.vdi_id);
1496
1497 buf = g_malloc(SD_INODE_SIZE);
1498
1499 ret = do_sd_create(s->name, s->inode.vdi_size, s->inode.vdi_id, &vid, 1,
1500 s->addr, s->port);
1501 if (ret) {
1502 goto out;
1503 }
1504
1505 dprintf("%" PRIx32 " is created.\n", vid);
1506
1507 fd = connect_to_sdog(s->addr, s->port);
1508 if (fd < 0) {
1509 error_report("failed to connect");
1510 ret = fd;
1511 goto out;
1512 }
1513
1514 ret = read_object(fd, buf, vid_to_vdi_oid(vid), s->inode.nr_copies,
1515 SD_INODE_SIZE, 0, s->cache_enabled);
1516
1517 closesocket(fd);
1518
1519 if (ret < 0) {
1520 goto out;
1521 }
1522
1523 memcpy(&s->inode, buf, sizeof(s->inode));
1524
1525 s->is_snapshot = 0;
1526 ret = 0;
1527 dprintf("%" PRIx32 " was newly created.\n", s->inode.vdi_id);
1528
1529 out:
1530 g_free(buf);
1531
1532 return ret;
1533 }
1534
1535 /*
1536 * Send I/O requests to the server.
1537 *
1538 * This function sends requests to the server, links the requests to
1539 * the outstanding_list in BDRVSheepdogState, and exits without
1540 * waiting the response. The responses are received in the
1541 * `aio_read_response' function which is called from the main loop as
1542 * a fd handler.
1543 *
1544 * Returns 1 when we need to wait a response, 0 when there is no sent
1545 * request and -errno in error cases.
1546 */
1547 static int coroutine_fn sd_co_rw_vector(void *p)
1548 {
1549 SheepdogAIOCB *acb = p;
1550 int ret = 0;
1551 unsigned long len, done = 0, total = acb->nb_sectors * SECTOR_SIZE;
1552 unsigned long idx = acb->sector_num * SECTOR_SIZE / SD_DATA_OBJ_SIZE;
1553 uint64_t oid;
1554 uint64_t offset = (acb->sector_num * SECTOR_SIZE) % SD_DATA_OBJ_SIZE;
1555 BDRVSheepdogState *s = acb->common.bs->opaque;
1556 SheepdogInode *inode = &s->inode;
1557 AIOReq *aio_req;
1558
1559 if (acb->aiocb_type == AIOCB_WRITE_UDATA && s->is_snapshot) {
1560 /*
1561 * In the case we open the snapshot VDI, Sheepdog creates the
1562 * writable VDI when we do a write operation first.
1563 */
1564 ret = sd_create_branch(s);
1565 if (ret) {
1566 acb->ret = -EIO;
1567 goto out;
1568 }
1569 }
1570
1571 while (done != total) {
1572 uint8_t flags = 0;
1573 uint64_t old_oid = 0;
1574 int create = 0;
1575
1576 oid = vid_to_data_oid(inode->data_vdi_id[idx], idx);
1577
1578 len = MIN(total - done, SD_DATA_OBJ_SIZE - offset);
1579
1580 if (!inode->data_vdi_id[idx]) {
1581 if (acb->aiocb_type == AIOCB_READ_UDATA) {
1582 goto done;
1583 }
1584
1585 create = 1;
1586 } else if (acb->aiocb_type == AIOCB_WRITE_UDATA
1587 && !is_data_obj_writable(inode, idx)) {
1588 /* Copy-On-Write */
1589 create = 1;
1590 old_oid = oid;
1591 flags = SD_FLAG_CMD_COW;
1592 }
1593
1594 if (create) {
1595 dprintf("update ino (%" PRIu32 ") %" PRIu64 " %" PRIu64 " %ld\n",
1596 inode->vdi_id, oid,
1597 vid_to_data_oid(inode->data_vdi_id[idx], idx), idx);
1598 oid = vid_to_data_oid(inode->vdi_id, idx);
1599 dprintf("new oid %" PRIx64 "\n", oid);
1600 }
1601
1602 aio_req = alloc_aio_req(s, acb, oid, len, offset, flags, old_oid, done);
1603
1604 if (create) {
1605 AIOReq *areq;
1606 QLIST_FOREACH(areq, &s->outstanding_aio_head,
1607 outstanding_aio_siblings) {
1608 if (areq == aio_req) {
1609 continue;
1610 }
1611 if (areq->oid == oid) {
1612 /*
1613 * Sheepdog cannot handle simultaneous create
1614 * requests to the same object. So we cannot send
1615 * the request until the previous request
1616 * finishes.
1617 */
1618 aio_req->flags = 0;
1619 aio_req->base_oid = 0;
1620 goto done;
1621 }
1622 }
1623 }
1624
1625 ret = add_aio_request(s, aio_req, acb->qiov->iov, acb->qiov->niov,
1626 create, acb->aiocb_type);
1627 if (ret < 0) {
1628 error_report("add_aio_request is failed");
1629 free_aio_req(s, aio_req);
1630 acb->ret = -EIO;
1631 goto out;
1632 }
1633 done:
1634 offset = 0;
1635 idx++;
1636 done += len;
1637 }
1638 out:
1639 if (QLIST_EMPTY(&acb->aioreq_head)) {
1640 return acb->ret;
1641 }
1642 return 1;
1643 }
1644
1645 static coroutine_fn int sd_co_writev(BlockDriverState *bs, int64_t sector_num,
1646 int nb_sectors, QEMUIOVector *qiov)
1647 {
1648 SheepdogAIOCB *acb;
1649 int ret;
1650
1651 if (bs->growable && sector_num + nb_sectors > bs->total_sectors) {
1652 ret = sd_truncate(bs, (sector_num + nb_sectors) * SECTOR_SIZE);
1653 if (ret < 0) {
1654 return ret;
1655 }
1656 bs->total_sectors = sector_num + nb_sectors;
1657 }
1658
1659 acb = sd_aio_setup(bs, qiov, sector_num, nb_sectors, NULL, NULL);
1660 acb->aio_done_func = sd_write_done;
1661 acb->aiocb_type = AIOCB_WRITE_UDATA;
1662
1663 ret = sd_co_rw_vector(acb);
1664 if (ret <= 0) {
1665 qemu_aio_release(acb);
1666 return ret;
1667 }
1668
1669 qemu_coroutine_yield();
1670
1671 return acb->ret;
1672 }
1673
1674 static coroutine_fn int sd_co_readv(BlockDriverState *bs, int64_t sector_num,
1675 int nb_sectors, QEMUIOVector *qiov)
1676 {
1677 SheepdogAIOCB *acb;
1678 int i, ret;
1679
1680 acb = sd_aio_setup(bs, qiov, sector_num, nb_sectors, NULL, NULL);
1681 acb->aiocb_type = AIOCB_READ_UDATA;
1682 acb->aio_done_func = sd_finish_aiocb;
1683
1684 /*
1685 * TODO: we can do better; we don't need to initialize
1686 * blindly.
1687 */
1688 for (i = 0; i < qiov->niov; i++) {
1689 memset(qiov->iov[i].iov_base, 0, qiov->iov[i].iov_len);
1690 }
1691
1692 ret = sd_co_rw_vector(acb);
1693 if (ret <= 0) {
1694 qemu_aio_release(acb);
1695 return ret;
1696 }
1697
1698 qemu_coroutine_yield();
1699
1700 return acb->ret;
1701 }
1702
1703 static int coroutine_fn sd_co_flush_to_disk(BlockDriverState *bs)
1704 {
1705 BDRVSheepdogState *s = bs->opaque;
1706 SheepdogObjReq hdr = { 0 };
1707 SheepdogObjRsp *rsp = (SheepdogObjRsp *)&hdr;
1708 SheepdogInode *inode = &s->inode;
1709 int ret;
1710 unsigned int wlen = 0, rlen = 0;
1711
1712 if (!s->cache_enabled) {
1713 return 0;
1714 }
1715
1716 hdr.opcode = SD_OP_FLUSH_VDI;
1717 hdr.oid = vid_to_vdi_oid(inode->vdi_id);
1718
1719 ret = do_req(s->flush_fd, (SheepdogReq *)&hdr, NULL, &wlen, &rlen);
1720 if (ret) {
1721 error_report("failed to send a request to the sheep");
1722 return ret;
1723 }
1724
1725 if (rsp->result == SD_RES_INVALID_PARMS) {
1726 dprintf("disable write cache since the server doesn't support it\n");
1727
1728 s->cache_enabled = 0;
1729 closesocket(s->flush_fd);
1730 return 0;
1731 }
1732
1733 if (rsp->result != SD_RES_SUCCESS) {
1734 error_report("%s", sd_strerror(rsp->result));
1735 return -EIO;
1736 }
1737
1738 return 0;
1739 }
1740
1741 static int sd_snapshot_create(BlockDriverState *bs, QEMUSnapshotInfo *sn_info)
1742 {
1743 BDRVSheepdogState *s = bs->opaque;
1744 int ret, fd;
1745 uint32_t new_vid;
1746 SheepdogInode *inode;
1747 unsigned int datalen;
1748
1749 dprintf("sn_info: name %s id_str %s s: name %s vm_state_size %" PRId64 " "
1750 "is_snapshot %d\n", sn_info->name, sn_info->id_str,
1751 s->name, sn_info->vm_state_size, s->is_snapshot);
1752
1753 if (s->is_snapshot) {
1754 error_report("You can't create a snapshot of a snapshot VDI, "
1755 "%s (%" PRIu32 ").", s->name, s->inode.vdi_id);
1756
1757 return -EINVAL;
1758 }
1759
1760 dprintf("%s %s\n", sn_info->name, sn_info->id_str);
1761
1762 s->inode.vm_state_size = sn_info->vm_state_size;
1763 s->inode.vm_clock_nsec = sn_info->vm_clock_nsec;
1764 strncpy(s->inode.tag, sn_info->name, sizeof(s->inode.tag));
1765 /* we don't need to update entire object */
1766 datalen = SD_INODE_SIZE - sizeof(s->inode.data_vdi_id);
1767
1768 /* refresh inode. */
1769 fd = connect_to_sdog(s->addr, s->port);
1770 if (fd < 0) {
1771 ret = fd;
1772 goto cleanup;
1773 }
1774
1775 ret = write_object(fd, (char *)&s->inode, vid_to_vdi_oid(s->inode.vdi_id),
1776 s->inode.nr_copies, datalen, 0, 0, s->cache_enabled);
1777 if (ret < 0) {
1778 error_report("failed to write snapshot's inode.");
1779 goto cleanup;
1780 }
1781
1782 ret = do_sd_create(s->name, s->inode.vdi_size, s->inode.vdi_id, &new_vid, 1,
1783 s->addr, s->port);
1784 if (ret < 0) {
1785 error_report("failed to create inode for snapshot. %s",
1786 strerror(errno));
1787 goto cleanup;
1788 }
1789
1790 inode = (SheepdogInode *)g_malloc(datalen);
1791
1792 ret = read_object(fd, (char *)inode, vid_to_vdi_oid(new_vid),
1793 s->inode.nr_copies, datalen, 0, s->cache_enabled);
1794
1795 if (ret < 0) {
1796 error_report("failed to read new inode info. %s", strerror(errno));
1797 goto cleanup;
1798 }
1799
1800 memcpy(&s->inode, inode, datalen);
1801 dprintf("s->inode: name %s snap_id %x oid %x\n",
1802 s->inode.name, s->inode.snap_id, s->inode.vdi_id);
1803
1804 cleanup:
1805 closesocket(fd);
1806 return ret;
1807 }
1808
1809 static int sd_snapshot_goto(BlockDriverState *bs, const char *snapshot_id)
1810 {
1811 BDRVSheepdogState *s = bs->opaque;
1812 BDRVSheepdogState *old_s;
1813 char vdi[SD_MAX_VDI_LEN], tag[SD_MAX_VDI_TAG_LEN];
1814 char *buf = NULL;
1815 uint32_t vid;
1816 uint32_t snapid = 0;
1817 int ret = 0, fd;
1818
1819 old_s = g_malloc(sizeof(BDRVSheepdogState));
1820
1821 memcpy(old_s, s, sizeof(BDRVSheepdogState));
1822
1823 memset(vdi, 0, sizeof(vdi));
1824 strncpy(vdi, s->name, sizeof(vdi));
1825
1826 memset(tag, 0, sizeof(tag));
1827 snapid = strtoul(snapshot_id, NULL, 10);
1828 if (!snapid) {
1829 strncpy(tag, s->name, sizeof(tag));
1830 }
1831
1832 ret = find_vdi_name(s, vdi, snapid, tag, &vid, 1);
1833 if (ret) {
1834 error_report("Failed to find_vdi_name");
1835 goto out;
1836 }
1837
1838 fd = connect_to_sdog(s->addr, s->port);
1839 if (fd < 0) {
1840 error_report("failed to connect");
1841 ret = fd;
1842 goto out;
1843 }
1844
1845 buf = g_malloc(SD_INODE_SIZE);
1846 ret = read_object(fd, buf, vid_to_vdi_oid(vid), s->inode.nr_copies,
1847 SD_INODE_SIZE, 0, s->cache_enabled);
1848
1849 closesocket(fd);
1850
1851 if (ret) {
1852 goto out;
1853 }
1854
1855 memcpy(&s->inode, buf, sizeof(s->inode));
1856
1857 if (!s->inode.vm_state_size) {
1858 error_report("Invalid snapshot");
1859 ret = -ENOENT;
1860 goto out;
1861 }
1862
1863 s->is_snapshot = 1;
1864
1865 g_free(buf);
1866 g_free(old_s);
1867
1868 return 0;
1869 out:
1870 /* recover bdrv_sd_state */
1871 memcpy(s, old_s, sizeof(BDRVSheepdogState));
1872 g_free(buf);
1873 g_free(old_s);
1874
1875 error_report("failed to open. recover old bdrv_sd_state.");
1876
1877 return ret;
1878 }
1879
1880 static int sd_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
1881 {
1882 /* FIXME: Delete specified snapshot id. */
1883 return 0;
1884 }
1885
1886 static int sd_snapshot_list(BlockDriverState *bs, QEMUSnapshotInfo **psn_tab)
1887 {
1888 BDRVSheepdogState *s = bs->opaque;
1889 SheepdogReq req;
1890 int fd, nr = 1024, ret, max = BITS_TO_LONGS(SD_NR_VDIS) * sizeof(long);
1891 QEMUSnapshotInfo *sn_tab = NULL;
1892 unsigned wlen, rlen;
1893 int found = 0;
1894 static SheepdogInode inode;
1895 unsigned long *vdi_inuse;
1896 unsigned int start_nr;
1897 uint64_t hval;
1898 uint32_t vid;
1899
1900 vdi_inuse = g_malloc(max);
1901
1902 fd = connect_to_sdog(s->addr, s->port);
1903 if (fd < 0) {
1904 ret = fd;
1905 goto out;
1906 }
1907
1908 rlen = max;
1909 wlen = 0;
1910
1911 memset(&req, 0, sizeof(req));
1912
1913 req.opcode = SD_OP_READ_VDIS;
1914 req.data_length = max;
1915
1916 ret = do_req(fd, (SheepdogReq *)&req, vdi_inuse, &wlen, &rlen);
1917
1918 closesocket(fd);
1919 if (ret) {
1920 goto out;
1921 }
1922
1923 sn_tab = g_malloc0(nr * sizeof(*sn_tab));
1924
1925 /* calculate a vdi id with hash function */
1926 hval = fnv_64a_buf(s->name, strlen(s->name), FNV1A_64_INIT);
1927 start_nr = hval & (SD_NR_VDIS - 1);
1928
1929 fd = connect_to_sdog(s->addr, s->port);
1930 if (fd < 0) {
1931 error_report("failed to connect");
1932 ret = fd;
1933 goto out;
1934 }
1935
1936 for (vid = start_nr; found < nr; vid = (vid + 1) % SD_NR_VDIS) {
1937 if (!test_bit(vid, vdi_inuse)) {
1938 break;
1939 }
1940
1941 /* we don't need to read entire object */
1942 ret = read_object(fd, (char *)&inode, vid_to_vdi_oid(vid),
1943 0, SD_INODE_SIZE - sizeof(inode.data_vdi_id), 0,
1944 s->cache_enabled);
1945
1946 if (ret) {
1947 continue;
1948 }
1949
1950 if (!strcmp(inode.name, s->name) && is_snapshot(&inode)) {
1951 sn_tab[found].date_sec = inode.snap_ctime >> 32;
1952 sn_tab[found].date_nsec = inode.snap_ctime & 0xffffffff;
1953 sn_tab[found].vm_state_size = inode.vm_state_size;
1954 sn_tab[found].vm_clock_nsec = inode.vm_clock_nsec;
1955
1956 snprintf(sn_tab[found].id_str, sizeof(sn_tab[found].id_str), "%u",
1957 inode.snap_id);
1958 strncpy(sn_tab[found].name, inode.tag,
1959 MIN(sizeof(sn_tab[found].name), sizeof(inode.tag)));
1960 found++;
1961 }
1962 }
1963
1964 closesocket(fd);
1965 out:
1966 *psn_tab = sn_tab;
1967
1968 g_free(vdi_inuse);
1969
1970 if (ret < 0) {
1971 return ret;
1972 }
1973
1974 return found;
1975 }
1976
1977 static int do_load_save_vmstate(BDRVSheepdogState *s, uint8_t *data,
1978 int64_t pos, int size, int load)
1979 {
1980 int fd, create;
1981 int ret = 0, remaining = size;
1982 unsigned int data_len;
1983 uint64_t vmstate_oid;
1984 uint32_t vdi_index;
1985 uint64_t offset;
1986
1987 fd = connect_to_sdog(s->addr, s->port);
1988 if (fd < 0) {
1989 return fd;
1990 }
1991
1992 while (remaining) {
1993 vdi_index = pos / SD_DATA_OBJ_SIZE;
1994 offset = pos % SD_DATA_OBJ_SIZE;
1995
1996 data_len = MIN(remaining, SD_DATA_OBJ_SIZE);
1997
1998 vmstate_oid = vid_to_vmstate_oid(s->inode.vdi_id, vdi_index);
1999
2000 create = (offset == 0);
2001 if (load) {
2002 ret = read_object(fd, (char *)data, vmstate_oid,
2003 s->inode.nr_copies, data_len, offset,
2004 s->cache_enabled);
2005 } else {
2006 ret = write_object(fd, (char *)data, vmstate_oid,
2007 s->inode.nr_copies, data_len, offset, create,
2008 s->cache_enabled);
2009 }
2010
2011 if (ret < 0) {
2012 error_report("failed to save vmstate %s", strerror(errno));
2013 goto cleanup;
2014 }
2015
2016 pos += data_len;
2017 remaining -= data_len;
2018 }
2019 ret = size;
2020 cleanup:
2021 closesocket(fd);
2022 return ret;
2023 }
2024
2025 static int sd_save_vmstate(BlockDriverState *bs, const uint8_t *data,
2026 int64_t pos, int size)
2027 {
2028 BDRVSheepdogState *s = bs->opaque;
2029
2030 return do_load_save_vmstate(s, (uint8_t *)data, pos, size, 0);
2031 }
2032
2033 static int sd_load_vmstate(BlockDriverState *bs, uint8_t *data,
2034 int64_t pos, int size)
2035 {
2036 BDRVSheepdogState *s = bs->opaque;
2037
2038 return do_load_save_vmstate(s, data, pos, size, 1);
2039 }
2040
2041
2042 static QEMUOptionParameter sd_create_options[] = {
2043 {
2044 .name = BLOCK_OPT_SIZE,
2045 .type = OPT_SIZE,
2046 .help = "Virtual disk size"
2047 },
2048 {
2049 .name = BLOCK_OPT_BACKING_FILE,
2050 .type = OPT_STRING,
2051 .help = "File name of a base image"
2052 },
2053 {
2054 .name = BLOCK_OPT_PREALLOC,
2055 .type = OPT_STRING,
2056 .help = "Preallocation mode (allowed values: off, full)"
2057 },
2058 { NULL }
2059 };
2060
2061 BlockDriver bdrv_sheepdog = {
2062 .format_name = "sheepdog",
2063 .protocol_name = "sheepdog",
2064 .instance_size = sizeof(BDRVSheepdogState),
2065 .bdrv_file_open = sd_open,
2066 .bdrv_close = sd_close,
2067 .bdrv_create = sd_create,
2068 .bdrv_getlength = sd_getlength,
2069 .bdrv_truncate = sd_truncate,
2070
2071 .bdrv_co_readv = sd_co_readv,
2072 .bdrv_co_writev = sd_co_writev,
2073 .bdrv_co_flush_to_disk = sd_co_flush_to_disk,
2074
2075 .bdrv_snapshot_create = sd_snapshot_create,
2076 .bdrv_snapshot_goto = sd_snapshot_goto,
2077 .bdrv_snapshot_delete = sd_snapshot_delete,
2078 .bdrv_snapshot_list = sd_snapshot_list,
2079
2080 .bdrv_save_vmstate = sd_save_vmstate,
2081 .bdrv_load_vmstate = sd_load_vmstate,
2082
2083 .create_options = sd_create_options,
2084 };
2085
2086 static void bdrv_sheepdog_init(void)
2087 {
2088 bdrv_register(&bdrv_sheepdog);
2089 }
2090 block_init(bdrv_sheepdog_init);