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