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