]> git.proxmox.com Git - qemu.git/blob - block/sheepdog.c
sheepdog: make add_aio_request and send_aioreq void functions
[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/uri.h"
17 #include "qemu/error-report.h"
18 #include "qemu/sockets.h"
19 #include "block/block_int.h"
20 #include "qemu/bitops.h"
21
22 #define SD_PROTO_VER 0x01
23
24 #define SD_DEFAULT_ADDR "localhost"
25 #define SD_DEFAULT_PORT 7000
26
27 #define SD_OP_CREATE_AND_WRITE_OBJ 0x01
28 #define SD_OP_READ_OBJ 0x02
29 #define SD_OP_WRITE_OBJ 0x03
30 /* 0x04 is used internally by Sheepdog */
31 #define SD_OP_DISCARD_OBJ 0x05
32
33 #define SD_OP_NEW_VDI 0x11
34 #define SD_OP_LOCK_VDI 0x12
35 #define SD_OP_RELEASE_VDI 0x13
36 #define SD_OP_GET_VDI_INFO 0x14
37 #define SD_OP_READ_VDIS 0x15
38 #define SD_OP_FLUSH_VDI 0x16
39 #define SD_OP_DEL_VDI 0x17
40
41 #define SD_FLAG_CMD_WRITE 0x01
42 #define SD_FLAG_CMD_COW 0x02
43 #define SD_FLAG_CMD_CACHE 0x04 /* Writeback mode for cache */
44 #define SD_FLAG_CMD_DIRECT 0x08 /* Don't use cache */
45
46 #define SD_RES_SUCCESS 0x00 /* Success */
47 #define SD_RES_UNKNOWN 0x01 /* Unknown error */
48 #define SD_RES_NO_OBJ 0x02 /* No object found */
49 #define SD_RES_EIO 0x03 /* I/O error */
50 #define SD_RES_VDI_EXIST 0x04 /* Vdi exists already */
51 #define SD_RES_INVALID_PARMS 0x05 /* Invalid parameters */
52 #define SD_RES_SYSTEM_ERROR 0x06 /* System error */
53 #define SD_RES_VDI_LOCKED 0x07 /* Vdi is locked */
54 #define SD_RES_NO_VDI 0x08 /* No vdi found */
55 #define SD_RES_NO_BASE_VDI 0x09 /* No base vdi found */
56 #define SD_RES_VDI_READ 0x0A /* Cannot read requested vdi */
57 #define SD_RES_VDI_WRITE 0x0B /* Cannot write requested vdi */
58 #define SD_RES_BASE_VDI_READ 0x0C /* Cannot read base vdi */
59 #define SD_RES_BASE_VDI_WRITE 0x0D /* Cannot write base vdi */
60 #define SD_RES_NO_TAG 0x0E /* Requested tag is not found */
61 #define SD_RES_STARTUP 0x0F /* Sheepdog is on starting up */
62 #define SD_RES_VDI_NOT_LOCKED 0x10 /* Vdi is not locked */
63 #define SD_RES_SHUTDOWN 0x11 /* Sheepdog is shutting down */
64 #define SD_RES_NO_MEM 0x12 /* Cannot allocate memory */
65 #define SD_RES_FULL_VDI 0x13 /* we already have the maximum vdis */
66 #define SD_RES_VER_MISMATCH 0x14 /* Protocol version mismatch */
67 #define SD_RES_NO_SPACE 0x15 /* Server has no room for new objects */
68 #define SD_RES_WAIT_FOR_FORMAT 0x16 /* Waiting for a format operation */
69 #define SD_RES_WAIT_FOR_JOIN 0x17 /* Waiting for other nodes joining */
70 #define SD_RES_JOIN_FAILED 0x18 /* Target node had failed to join sheepdog */
71 #define SD_RES_HALT 0x19 /* Sheepdog is stopped serving IO request */
72 #define SD_RES_READONLY 0x1A /* Object is read-only */
73
74 /*
75 * Object ID rules
76 *
77 * 0 - 19 (20 bits): data object space
78 * 20 - 31 (12 bits): reserved data object space
79 * 32 - 55 (24 bits): vdi object space
80 * 56 - 59 ( 4 bits): reserved vdi object space
81 * 60 - 63 ( 4 bits): object type identifier space
82 */
83
84 #define VDI_SPACE_SHIFT 32
85 #define VDI_BIT (UINT64_C(1) << 63)
86 #define VMSTATE_BIT (UINT64_C(1) << 62)
87 #define MAX_DATA_OBJS (UINT64_C(1) << 20)
88 #define MAX_CHILDREN 1024
89 #define SD_MAX_VDI_LEN 256
90 #define SD_MAX_VDI_TAG_LEN 256
91 #define SD_NR_VDIS (1U << 24)
92 #define SD_DATA_OBJ_SIZE (UINT64_C(1) << 22)
93 #define SD_MAX_VDI_SIZE (SD_DATA_OBJ_SIZE * MAX_DATA_OBJS)
94
95 #define SD_INODE_SIZE (sizeof(SheepdogInode))
96 #define CURRENT_VDI_ID 0
97
98 typedef struct SheepdogReq {
99 uint8_t proto_ver;
100 uint8_t opcode;
101 uint16_t flags;
102 uint32_t epoch;
103 uint32_t id;
104 uint32_t data_length;
105 uint32_t opcode_specific[8];
106 } SheepdogReq;
107
108 typedef struct SheepdogRsp {
109 uint8_t proto_ver;
110 uint8_t opcode;
111 uint16_t flags;
112 uint32_t epoch;
113 uint32_t id;
114 uint32_t data_length;
115 uint32_t result;
116 uint32_t opcode_specific[7];
117 } SheepdogRsp;
118
119 typedef struct SheepdogObjReq {
120 uint8_t proto_ver;
121 uint8_t opcode;
122 uint16_t flags;
123 uint32_t epoch;
124 uint32_t id;
125 uint32_t data_length;
126 uint64_t oid;
127 uint64_t cow_oid;
128 uint8_t copies;
129 uint8_t copy_policy;
130 uint8_t reserved[6];
131 uint64_t offset;
132 } SheepdogObjReq;
133
134 typedef struct SheepdogObjRsp {
135 uint8_t proto_ver;
136 uint8_t opcode;
137 uint16_t flags;
138 uint32_t epoch;
139 uint32_t id;
140 uint32_t data_length;
141 uint32_t result;
142 uint8_t copies;
143 uint8_t copy_policy;
144 uint8_t reserved[2];
145 uint32_t pad[6];
146 } SheepdogObjRsp;
147
148 typedef struct SheepdogVdiReq {
149 uint8_t proto_ver;
150 uint8_t opcode;
151 uint16_t flags;
152 uint32_t epoch;
153 uint32_t id;
154 uint32_t data_length;
155 uint64_t vdi_size;
156 uint32_t vdi_id;
157 uint8_t copies;
158 uint8_t copy_policy;
159 uint8_t reserved[2];
160 uint32_t snapid;
161 uint32_t pad[3];
162 } SheepdogVdiReq;
163
164 typedef struct SheepdogVdiRsp {
165 uint8_t proto_ver;
166 uint8_t opcode;
167 uint16_t flags;
168 uint32_t epoch;
169 uint32_t id;
170 uint32_t data_length;
171 uint32_t result;
172 uint32_t rsvd;
173 uint32_t vdi_id;
174 uint32_t pad[5];
175 } SheepdogVdiRsp;
176
177 typedef struct SheepdogInode {
178 char name[SD_MAX_VDI_LEN];
179 char tag[SD_MAX_VDI_TAG_LEN];
180 uint64_t ctime;
181 uint64_t snap_ctime;
182 uint64_t vm_clock_nsec;
183 uint64_t vdi_size;
184 uint64_t vm_state_size;
185 uint16_t copy_policy;
186 uint8_t nr_copies;
187 uint8_t block_size_shift;
188 uint32_t snap_id;
189 uint32_t vdi_id;
190 uint32_t parent_vdi_id;
191 uint32_t child_vdi_id[MAX_CHILDREN];
192 uint32_t data_vdi_id[MAX_DATA_OBJS];
193 } SheepdogInode;
194
195 /*
196 * 64 bit FNV-1a non-zero initial basis
197 */
198 #define FNV1A_64_INIT ((uint64_t)0xcbf29ce484222325ULL)
199
200 /*
201 * 64 bit Fowler/Noll/Vo FNV-1a hash code
202 */
203 static inline uint64_t fnv_64a_buf(void *buf, size_t len, uint64_t hval)
204 {
205 unsigned char *bp = buf;
206 unsigned char *be = bp + len;
207 while (bp < be) {
208 hval ^= (uint64_t) *bp++;
209 hval += (hval << 1) + (hval << 4) + (hval << 5) +
210 (hval << 7) + (hval << 8) + (hval << 40);
211 }
212 return hval;
213 }
214
215 static inline bool is_data_obj_writable(SheepdogInode *inode, unsigned int idx)
216 {
217 return inode->vdi_id == inode->data_vdi_id[idx];
218 }
219
220 static inline bool is_data_obj(uint64_t oid)
221 {
222 return !(VDI_BIT & oid);
223 }
224
225 static inline uint64_t data_oid_to_idx(uint64_t oid)
226 {
227 return oid & (MAX_DATA_OBJS - 1);
228 }
229
230 static inline uint32_t oid_to_vid(uint64_t oid)
231 {
232 return (oid & ~VDI_BIT) >> VDI_SPACE_SHIFT;
233 }
234
235 static inline uint64_t vid_to_vdi_oid(uint32_t vid)
236 {
237 return VDI_BIT | ((uint64_t)vid << VDI_SPACE_SHIFT);
238 }
239
240 static inline uint64_t vid_to_vmstate_oid(uint32_t vid, uint32_t idx)
241 {
242 return VMSTATE_BIT | ((uint64_t)vid << VDI_SPACE_SHIFT) | idx;
243 }
244
245 static inline uint64_t vid_to_data_oid(uint32_t vid, uint32_t idx)
246 {
247 return ((uint64_t)vid << VDI_SPACE_SHIFT) | idx;
248 }
249
250 static inline bool is_snapshot(struct SheepdogInode *inode)
251 {
252 return !!inode->snap_ctime;
253 }
254
255 #undef DPRINTF
256 #ifdef DEBUG_SDOG
257 #define DPRINTF(fmt, args...) \
258 do { \
259 fprintf(stdout, "%s %d: " fmt, __func__, __LINE__, ##args); \
260 } while (0)
261 #else
262 #define DPRINTF(fmt, args...)
263 #endif
264
265 typedef struct SheepdogAIOCB SheepdogAIOCB;
266
267 typedef struct AIOReq {
268 SheepdogAIOCB *aiocb;
269 unsigned int iov_offset;
270
271 uint64_t oid;
272 uint64_t base_oid;
273 uint64_t offset;
274 unsigned int data_len;
275 uint8_t flags;
276 uint32_t id;
277
278 QLIST_ENTRY(AIOReq) aio_siblings;
279 } AIOReq;
280
281 enum AIOCBState {
282 AIOCB_WRITE_UDATA,
283 AIOCB_READ_UDATA,
284 AIOCB_FLUSH_CACHE,
285 AIOCB_DISCARD_OBJ,
286 };
287
288 struct SheepdogAIOCB {
289 BlockDriverAIOCB common;
290
291 QEMUIOVector *qiov;
292
293 int64_t sector_num;
294 int nb_sectors;
295
296 int ret;
297 enum AIOCBState aiocb_type;
298
299 Coroutine *coroutine;
300 void (*aio_done_func)(SheepdogAIOCB *);
301
302 bool canceled;
303 int nr_pending;
304 };
305
306 typedef struct BDRVSheepdogState {
307 BlockDriverState *bs;
308
309 SheepdogInode inode;
310
311 uint32_t min_dirty_data_idx;
312 uint32_t max_dirty_data_idx;
313
314 char name[SD_MAX_VDI_LEN];
315 bool is_snapshot;
316 uint32_t cache_flags;
317 bool discard_supported;
318
319 char *host_spec;
320 bool is_unix;
321 int fd;
322
323 CoMutex lock;
324 Coroutine *co_send;
325 Coroutine *co_recv;
326
327 uint32_t aioreq_seq_num;
328
329 /* Every aio request must be linked to either of these queues. */
330 QLIST_HEAD(inflight_aio_head, AIOReq) inflight_aio_head;
331 QLIST_HEAD(pending_aio_head, AIOReq) pending_aio_head;
332 QLIST_HEAD(failed_aio_head, AIOReq) failed_aio_head;
333 } BDRVSheepdogState;
334
335 static const char * sd_strerror(int err)
336 {
337 int i;
338
339 static const struct {
340 int err;
341 const char *desc;
342 } errors[] = {
343 {SD_RES_SUCCESS, "Success"},
344 {SD_RES_UNKNOWN, "Unknown error"},
345 {SD_RES_NO_OBJ, "No object found"},
346 {SD_RES_EIO, "I/O error"},
347 {SD_RES_VDI_EXIST, "VDI exists already"},
348 {SD_RES_INVALID_PARMS, "Invalid parameters"},
349 {SD_RES_SYSTEM_ERROR, "System error"},
350 {SD_RES_VDI_LOCKED, "VDI is already locked"},
351 {SD_RES_NO_VDI, "No vdi found"},
352 {SD_RES_NO_BASE_VDI, "No base VDI found"},
353 {SD_RES_VDI_READ, "Failed read the requested VDI"},
354 {SD_RES_VDI_WRITE, "Failed to write the requested VDI"},
355 {SD_RES_BASE_VDI_READ, "Failed to read the base VDI"},
356 {SD_RES_BASE_VDI_WRITE, "Failed to write the base VDI"},
357 {SD_RES_NO_TAG, "Failed to find the requested tag"},
358 {SD_RES_STARTUP, "The system is still booting"},
359 {SD_RES_VDI_NOT_LOCKED, "VDI isn't locked"},
360 {SD_RES_SHUTDOWN, "The system is shutting down"},
361 {SD_RES_NO_MEM, "Out of memory on the server"},
362 {SD_RES_FULL_VDI, "We already have the maximum vdis"},
363 {SD_RES_VER_MISMATCH, "Protocol version mismatch"},
364 {SD_RES_NO_SPACE, "Server has no space for new objects"},
365 {SD_RES_WAIT_FOR_FORMAT, "Sheepdog is waiting for a format operation"},
366 {SD_RES_WAIT_FOR_JOIN, "Sheepdog is waiting for other nodes joining"},
367 {SD_RES_JOIN_FAILED, "Target node had failed to join sheepdog"},
368 {SD_RES_HALT, "Sheepdog is stopped serving IO request"},
369 {SD_RES_READONLY, "Object is read-only"},
370 };
371
372 for (i = 0; i < ARRAY_SIZE(errors); ++i) {
373 if (errors[i].err == err) {
374 return errors[i].desc;
375 }
376 }
377
378 return "Invalid error code";
379 }
380
381 /*
382 * Sheepdog I/O handling:
383 *
384 * 1. In sd_co_rw_vector, we send the I/O requests to the server and
385 * link the requests to the inflight_list in the
386 * BDRVSheepdogState. The function exits without waiting for
387 * receiving the response.
388 *
389 * 2. We receive the response in aio_read_response, the fd handler to
390 * the sheepdog connection. If metadata update is needed, we send
391 * the write request to the vdi object in sd_write_done, the write
392 * completion function. We switch back to sd_co_readv/writev after
393 * all the requests belonging to the AIOCB are finished.
394 */
395
396 static inline AIOReq *alloc_aio_req(BDRVSheepdogState *s, SheepdogAIOCB *acb,
397 uint64_t oid, unsigned int data_len,
398 uint64_t offset, uint8_t flags,
399 uint64_t base_oid, unsigned int iov_offset)
400 {
401 AIOReq *aio_req;
402
403 aio_req = g_malloc(sizeof(*aio_req));
404 aio_req->aiocb = acb;
405 aio_req->iov_offset = iov_offset;
406 aio_req->oid = oid;
407 aio_req->base_oid = base_oid;
408 aio_req->offset = offset;
409 aio_req->data_len = data_len;
410 aio_req->flags = flags;
411 aio_req->id = s->aioreq_seq_num++;
412
413 acb->nr_pending++;
414 return aio_req;
415 }
416
417 static inline void free_aio_req(BDRVSheepdogState *s, AIOReq *aio_req)
418 {
419 SheepdogAIOCB *acb = aio_req->aiocb;
420
421 QLIST_REMOVE(aio_req, aio_siblings);
422 g_free(aio_req);
423
424 acb->nr_pending--;
425 }
426
427 static void coroutine_fn sd_finish_aiocb(SheepdogAIOCB *acb)
428 {
429 if (!acb->canceled) {
430 qemu_coroutine_enter(acb->coroutine, NULL);
431 }
432 qemu_aio_release(acb);
433 }
434
435 static void sd_aio_cancel(BlockDriverAIOCB *blockacb)
436 {
437 SheepdogAIOCB *acb = (SheepdogAIOCB *)blockacb;
438
439 /*
440 * Sheepdog cannot cancel the requests which are already sent to
441 * the servers, so we just complete the request with -EIO here.
442 */
443 acb->ret = -EIO;
444 qemu_coroutine_enter(acb->coroutine, NULL);
445 acb->canceled = true;
446 }
447
448 static const AIOCBInfo sd_aiocb_info = {
449 .aiocb_size = sizeof(SheepdogAIOCB),
450 .cancel = sd_aio_cancel,
451 };
452
453 static SheepdogAIOCB *sd_aio_setup(BlockDriverState *bs, QEMUIOVector *qiov,
454 int64_t sector_num, int nb_sectors)
455 {
456 SheepdogAIOCB *acb;
457
458 acb = qemu_aio_get(&sd_aiocb_info, bs, NULL, NULL);
459
460 acb->qiov = qiov;
461
462 acb->sector_num = sector_num;
463 acb->nb_sectors = nb_sectors;
464
465 acb->aio_done_func = NULL;
466 acb->canceled = false;
467 acb->coroutine = qemu_coroutine_self();
468 acb->ret = 0;
469 acb->nr_pending = 0;
470 return acb;
471 }
472
473 static int connect_to_sdog(BDRVSheepdogState *s)
474 {
475 int fd;
476 Error *err = NULL;
477
478 if (s->is_unix) {
479 fd = unix_connect(s->host_spec, &err);
480 } else {
481 fd = inet_connect(s->host_spec, &err);
482
483 if (err == NULL) {
484 int ret = socket_set_nodelay(fd);
485 if (ret < 0) {
486 error_report("%s", strerror(errno));
487 }
488 }
489 }
490
491 if (err != NULL) {
492 qerror_report_err(err);
493 error_free(err);
494 } else {
495 qemu_set_nonblock(fd);
496 }
497
498 return fd;
499 }
500
501 static coroutine_fn int send_co_req(int sockfd, SheepdogReq *hdr, void *data,
502 unsigned int *wlen)
503 {
504 int ret;
505
506 ret = qemu_co_send(sockfd, hdr, sizeof(*hdr));
507 if (ret != sizeof(*hdr)) {
508 error_report("failed to send a req, %s", strerror(errno));
509 return ret;
510 }
511
512 ret = qemu_co_send(sockfd, data, *wlen);
513 if (ret != *wlen) {
514 error_report("failed to send a req, %s", strerror(errno));
515 }
516
517 return ret;
518 }
519
520 static void restart_co_req(void *opaque)
521 {
522 Coroutine *co = opaque;
523
524 qemu_coroutine_enter(co, NULL);
525 }
526
527 typedef struct SheepdogReqCo {
528 int sockfd;
529 SheepdogReq *hdr;
530 void *data;
531 unsigned int *wlen;
532 unsigned int *rlen;
533 int ret;
534 bool finished;
535 } SheepdogReqCo;
536
537 static coroutine_fn void do_co_req(void *opaque)
538 {
539 int ret;
540 Coroutine *co;
541 SheepdogReqCo *srco = opaque;
542 int sockfd = srco->sockfd;
543 SheepdogReq *hdr = srco->hdr;
544 void *data = srco->data;
545 unsigned int *wlen = srco->wlen;
546 unsigned int *rlen = srco->rlen;
547
548 co = qemu_coroutine_self();
549 qemu_aio_set_fd_handler(sockfd, NULL, restart_co_req, co);
550
551 ret = send_co_req(sockfd, hdr, data, wlen);
552 if (ret < 0) {
553 goto out;
554 }
555
556 qemu_aio_set_fd_handler(sockfd, restart_co_req, NULL, co);
557
558 ret = qemu_co_recv(sockfd, hdr, sizeof(*hdr));
559 if (ret != sizeof(*hdr)) {
560 error_report("failed to get a rsp, %s", strerror(errno));
561 ret = -errno;
562 goto out;
563 }
564
565 if (*rlen > hdr->data_length) {
566 *rlen = hdr->data_length;
567 }
568
569 if (*rlen) {
570 ret = qemu_co_recv(sockfd, data, *rlen);
571 if (ret != *rlen) {
572 error_report("failed to get the data, %s", strerror(errno));
573 ret = -errno;
574 goto out;
575 }
576 }
577 ret = 0;
578 out:
579 /* there is at most one request for this sockfd, so it is safe to
580 * set each handler to NULL. */
581 qemu_aio_set_fd_handler(sockfd, NULL, NULL, NULL);
582
583 srco->ret = ret;
584 srco->finished = true;
585 }
586
587 static int do_req(int sockfd, SheepdogReq *hdr, void *data,
588 unsigned int *wlen, unsigned int *rlen)
589 {
590 Coroutine *co;
591 SheepdogReqCo srco = {
592 .sockfd = sockfd,
593 .hdr = hdr,
594 .data = data,
595 .wlen = wlen,
596 .rlen = rlen,
597 .ret = 0,
598 .finished = false,
599 };
600
601 if (qemu_in_coroutine()) {
602 do_co_req(&srco);
603 } else {
604 co = qemu_coroutine_create(do_co_req);
605 qemu_coroutine_enter(co, &srco);
606 while (!srco.finished) {
607 qemu_aio_wait();
608 }
609 }
610
611 return srco.ret;
612 }
613
614 static void coroutine_fn add_aio_request(BDRVSheepdogState *s, AIOReq *aio_req,
615 struct iovec *iov, int niov, bool create,
616 enum AIOCBState aiocb_type);
617 static void coroutine_fn resend_aioreq(BDRVSheepdogState *s, AIOReq *aio_req);
618 static int reload_inode(BDRVSheepdogState *s, uint32_t snapid, const char *tag);
619 static int get_sheep_fd(BDRVSheepdogState *s);
620 static void co_write_request(void *opaque);
621
622 static AIOReq *find_pending_req(BDRVSheepdogState *s, uint64_t oid)
623 {
624 AIOReq *aio_req;
625
626 QLIST_FOREACH(aio_req, &s->pending_aio_head, aio_siblings) {
627 if (aio_req->oid == oid) {
628 return aio_req;
629 }
630 }
631
632 return NULL;
633 }
634
635 /*
636 * This function searchs pending requests to the object `oid', and
637 * sends them.
638 */
639 static void coroutine_fn send_pending_req(BDRVSheepdogState *s, uint64_t oid)
640 {
641 AIOReq *aio_req;
642 SheepdogAIOCB *acb;
643
644 while ((aio_req = find_pending_req(s, oid)) != NULL) {
645 acb = aio_req->aiocb;
646 /* move aio_req from pending list to inflight one */
647 QLIST_REMOVE(aio_req, aio_siblings);
648 QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
649 add_aio_request(s, aio_req, acb->qiov->iov, acb->qiov->niov, false,
650 acb->aiocb_type);
651 }
652 }
653
654 static coroutine_fn void reconnect_to_sdog(void *opaque)
655 {
656 BDRVSheepdogState *s = opaque;
657 AIOReq *aio_req, *next;
658
659 qemu_aio_set_fd_handler(s->fd, NULL, NULL, NULL);
660 close(s->fd);
661 s->fd = -1;
662
663 /* Wait for outstanding write requests to be completed. */
664 while (s->co_send != NULL) {
665 co_write_request(opaque);
666 }
667
668 /* Try to reconnect the sheepdog server every one second. */
669 while (s->fd < 0) {
670 s->fd = get_sheep_fd(s);
671 if (s->fd < 0) {
672 DPRINTF("Wait for connection to be established\n");
673 co_aio_sleep_ns(bdrv_get_aio_context(s->bs), QEMU_CLOCK_REALTIME,
674 1000000000ULL);
675 }
676 };
677
678 /*
679 * Now we have to resend all the request in the inflight queue. However,
680 * resend_aioreq() can yield and newly created requests can be added to the
681 * inflight queue before the coroutine is resumed. To avoid mixing them, we
682 * have to move all the inflight requests to the failed queue before
683 * resend_aioreq() is called.
684 */
685 QLIST_FOREACH_SAFE(aio_req, &s->inflight_aio_head, aio_siblings, next) {
686 QLIST_REMOVE(aio_req, aio_siblings);
687 QLIST_INSERT_HEAD(&s->failed_aio_head, aio_req, aio_siblings);
688 }
689
690 /* Resend all the failed aio requests. */
691 while (!QLIST_EMPTY(&s->failed_aio_head)) {
692 aio_req = QLIST_FIRST(&s->failed_aio_head);
693 QLIST_REMOVE(aio_req, aio_siblings);
694 QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
695 resend_aioreq(s, aio_req);
696 }
697 }
698
699 /*
700 * Receive responses of the I/O requests.
701 *
702 * This function is registered as a fd handler, and called from the
703 * main loop when s->fd is ready for reading responses.
704 */
705 static void coroutine_fn aio_read_response(void *opaque)
706 {
707 SheepdogObjRsp rsp;
708 BDRVSheepdogState *s = opaque;
709 int fd = s->fd;
710 int ret;
711 AIOReq *aio_req = NULL;
712 SheepdogAIOCB *acb;
713 uint64_t idx;
714
715 /* read a header */
716 ret = qemu_co_recv(fd, &rsp, sizeof(rsp));
717 if (ret != sizeof(rsp)) {
718 error_report("failed to get the header, %s", strerror(errno));
719 goto err;
720 }
721
722 /* find the right aio_req from the inflight aio list */
723 QLIST_FOREACH(aio_req, &s->inflight_aio_head, aio_siblings) {
724 if (aio_req->id == rsp.id) {
725 break;
726 }
727 }
728 if (!aio_req) {
729 error_report("cannot find aio_req %x", rsp.id);
730 goto err;
731 }
732
733 acb = aio_req->aiocb;
734
735 switch (acb->aiocb_type) {
736 case AIOCB_WRITE_UDATA:
737 /* this coroutine context is no longer suitable for co_recv
738 * because we may send data to update vdi objects */
739 s->co_recv = NULL;
740 if (!is_data_obj(aio_req->oid)) {
741 break;
742 }
743 idx = data_oid_to_idx(aio_req->oid);
744
745 if (s->inode.data_vdi_id[idx] != s->inode.vdi_id) {
746 /*
747 * If the object is newly created one, we need to update
748 * the vdi object (metadata object). min_dirty_data_idx
749 * and max_dirty_data_idx are changed to include updated
750 * index between them.
751 */
752 if (rsp.result == SD_RES_SUCCESS) {
753 s->inode.data_vdi_id[idx] = s->inode.vdi_id;
754 s->max_dirty_data_idx = MAX(idx, s->max_dirty_data_idx);
755 s->min_dirty_data_idx = MIN(idx, s->min_dirty_data_idx);
756 }
757 /*
758 * Some requests may be blocked because simultaneous
759 * create requests are not allowed, so we search the
760 * pending requests here.
761 */
762 send_pending_req(s, aio_req->oid);
763 }
764 break;
765 case AIOCB_READ_UDATA:
766 ret = qemu_co_recvv(fd, acb->qiov->iov, acb->qiov->niov,
767 aio_req->iov_offset, rsp.data_length);
768 if (ret != rsp.data_length) {
769 error_report("failed to get the data, %s", strerror(errno));
770 goto err;
771 }
772 break;
773 case AIOCB_FLUSH_CACHE:
774 if (rsp.result == SD_RES_INVALID_PARMS) {
775 DPRINTF("disable cache since the server doesn't support it\n");
776 s->cache_flags = SD_FLAG_CMD_DIRECT;
777 rsp.result = SD_RES_SUCCESS;
778 }
779 break;
780 case AIOCB_DISCARD_OBJ:
781 switch (rsp.result) {
782 case SD_RES_INVALID_PARMS:
783 error_report("sheep(%s) doesn't support discard command",
784 s->host_spec);
785 rsp.result = SD_RES_SUCCESS;
786 s->discard_supported = false;
787 break;
788 case SD_RES_SUCCESS:
789 idx = data_oid_to_idx(aio_req->oid);
790 s->inode.data_vdi_id[idx] = 0;
791 break;
792 default:
793 break;
794 }
795 }
796
797 switch (rsp.result) {
798 case SD_RES_SUCCESS:
799 break;
800 case SD_RES_READONLY:
801 if (s->inode.vdi_id == oid_to_vid(aio_req->oid)) {
802 ret = reload_inode(s, 0, "");
803 if (ret < 0) {
804 goto err;
805 }
806 }
807 if (is_data_obj(aio_req->oid)) {
808 aio_req->oid = vid_to_data_oid(s->inode.vdi_id,
809 data_oid_to_idx(aio_req->oid));
810 } else {
811 aio_req->oid = vid_to_vdi_oid(s->inode.vdi_id);
812 }
813 resend_aioreq(s, aio_req);
814 goto out;
815 default:
816 acb->ret = -EIO;
817 error_report("%s", sd_strerror(rsp.result));
818 break;
819 }
820
821 free_aio_req(s, aio_req);
822 if (!acb->nr_pending) {
823 /*
824 * We've finished all requests which belong to the AIOCB, so
825 * we can switch back to sd_co_readv/writev now.
826 */
827 acb->aio_done_func(acb);
828 }
829 out:
830 s->co_recv = NULL;
831 return;
832 err:
833 s->co_recv = NULL;
834 reconnect_to_sdog(opaque);
835 }
836
837 static void co_read_response(void *opaque)
838 {
839 BDRVSheepdogState *s = opaque;
840
841 if (!s->co_recv) {
842 s->co_recv = qemu_coroutine_create(aio_read_response);
843 }
844
845 qemu_coroutine_enter(s->co_recv, opaque);
846 }
847
848 static void co_write_request(void *opaque)
849 {
850 BDRVSheepdogState *s = opaque;
851
852 qemu_coroutine_enter(s->co_send, NULL);
853 }
854
855 /*
856 * Return a socket discriptor to read/write objects.
857 *
858 * We cannot use this discriptor for other operations because
859 * the block driver may be on waiting response from the server.
860 */
861 static int get_sheep_fd(BDRVSheepdogState *s)
862 {
863 int fd;
864
865 fd = connect_to_sdog(s);
866 if (fd < 0) {
867 return fd;
868 }
869
870 qemu_aio_set_fd_handler(fd, co_read_response, NULL, s);
871 return fd;
872 }
873
874 static int sd_parse_uri(BDRVSheepdogState *s, const char *filename,
875 char *vdi, uint32_t *snapid, char *tag)
876 {
877 URI *uri;
878 QueryParams *qp = NULL;
879 int ret = 0;
880
881 uri = uri_parse(filename);
882 if (!uri) {
883 return -EINVAL;
884 }
885
886 /* transport */
887 if (!strcmp(uri->scheme, "sheepdog")) {
888 s->is_unix = false;
889 } else if (!strcmp(uri->scheme, "sheepdog+tcp")) {
890 s->is_unix = false;
891 } else if (!strcmp(uri->scheme, "sheepdog+unix")) {
892 s->is_unix = true;
893 } else {
894 ret = -EINVAL;
895 goto out;
896 }
897
898 if (uri->path == NULL || !strcmp(uri->path, "/")) {
899 ret = -EINVAL;
900 goto out;
901 }
902 pstrcpy(vdi, SD_MAX_VDI_LEN, uri->path + 1);
903
904 qp = query_params_parse(uri->query);
905 if (qp->n > 1 || (s->is_unix && !qp->n) || (!s->is_unix && qp->n)) {
906 ret = -EINVAL;
907 goto out;
908 }
909
910 if (s->is_unix) {
911 /* sheepdog+unix:///vdiname?socket=path */
912 if (uri->server || uri->port || strcmp(qp->p[0].name, "socket")) {
913 ret = -EINVAL;
914 goto out;
915 }
916 s->host_spec = g_strdup(qp->p[0].value);
917 } else {
918 /* sheepdog[+tcp]://[host:port]/vdiname */
919 s->host_spec = g_strdup_printf("%s:%d", uri->server ?: SD_DEFAULT_ADDR,
920 uri->port ?: SD_DEFAULT_PORT);
921 }
922
923 /* snapshot tag */
924 if (uri->fragment) {
925 *snapid = strtoul(uri->fragment, NULL, 10);
926 if (*snapid == 0) {
927 pstrcpy(tag, SD_MAX_VDI_TAG_LEN, uri->fragment);
928 }
929 } else {
930 *snapid = CURRENT_VDI_ID; /* search current vdi */
931 }
932
933 out:
934 if (qp) {
935 query_params_free(qp);
936 }
937 uri_free(uri);
938 return ret;
939 }
940
941 /*
942 * Parse a filename (old syntax)
943 *
944 * filename must be one of the following formats:
945 * 1. [vdiname]
946 * 2. [vdiname]:[snapid]
947 * 3. [vdiname]:[tag]
948 * 4. [hostname]:[port]:[vdiname]
949 * 5. [hostname]:[port]:[vdiname]:[snapid]
950 * 6. [hostname]:[port]:[vdiname]:[tag]
951 *
952 * You can boot from the snapshot images by specifying `snapid` or
953 * `tag'.
954 *
955 * You can run VMs outside the Sheepdog cluster by specifying
956 * `hostname' and `port' (experimental).
957 */
958 static int parse_vdiname(BDRVSheepdogState *s, const char *filename,
959 char *vdi, uint32_t *snapid, char *tag)
960 {
961 char *p, *q, *uri;
962 const char *host_spec, *vdi_spec;
963 int nr_sep, ret;
964
965 strstart(filename, "sheepdog:", (const char **)&filename);
966 p = q = g_strdup(filename);
967
968 /* count the number of separators */
969 nr_sep = 0;
970 while (*p) {
971 if (*p == ':') {
972 nr_sep++;
973 }
974 p++;
975 }
976 p = q;
977
978 /* use the first two tokens as host_spec. */
979 if (nr_sep >= 2) {
980 host_spec = p;
981 p = strchr(p, ':');
982 p++;
983 p = strchr(p, ':');
984 *p++ = '\0';
985 } else {
986 host_spec = "";
987 }
988
989 vdi_spec = p;
990
991 p = strchr(vdi_spec, ':');
992 if (p) {
993 *p++ = '#';
994 }
995
996 uri = g_strdup_printf("sheepdog://%s/%s", host_spec, vdi_spec);
997
998 ret = sd_parse_uri(s, uri, vdi, snapid, tag);
999
1000 g_free(q);
1001 g_free(uri);
1002
1003 return ret;
1004 }
1005
1006 static int find_vdi_name(BDRVSheepdogState *s, const char *filename,
1007 uint32_t snapid, const char *tag, uint32_t *vid,
1008 bool lock)
1009 {
1010 int ret, fd;
1011 SheepdogVdiReq hdr;
1012 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
1013 unsigned int wlen, rlen = 0;
1014 char buf[SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN];
1015
1016 fd = connect_to_sdog(s);
1017 if (fd < 0) {
1018 return fd;
1019 }
1020
1021 /* This pair of strncpy calls ensures that the buffer is zero-filled,
1022 * which is desirable since we'll soon be sending those bytes, and
1023 * don't want the send_req to read uninitialized data.
1024 */
1025 strncpy(buf, filename, SD_MAX_VDI_LEN);
1026 strncpy(buf + SD_MAX_VDI_LEN, tag, SD_MAX_VDI_TAG_LEN);
1027
1028 memset(&hdr, 0, sizeof(hdr));
1029 if (lock) {
1030 hdr.opcode = SD_OP_LOCK_VDI;
1031 } else {
1032 hdr.opcode = SD_OP_GET_VDI_INFO;
1033 }
1034 wlen = SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN;
1035 hdr.proto_ver = SD_PROTO_VER;
1036 hdr.data_length = wlen;
1037 hdr.snapid = snapid;
1038 hdr.flags = SD_FLAG_CMD_WRITE;
1039
1040 ret = do_req(fd, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
1041 if (ret) {
1042 goto out;
1043 }
1044
1045 if (rsp->result != SD_RES_SUCCESS) {
1046 error_report("cannot get vdi info, %s, %s %d %s",
1047 sd_strerror(rsp->result), filename, snapid, tag);
1048 if (rsp->result == SD_RES_NO_VDI) {
1049 ret = -ENOENT;
1050 } else {
1051 ret = -EIO;
1052 }
1053 goto out;
1054 }
1055 *vid = rsp->vdi_id;
1056
1057 ret = 0;
1058 out:
1059 closesocket(fd);
1060 return ret;
1061 }
1062
1063 static void coroutine_fn add_aio_request(BDRVSheepdogState *s, AIOReq *aio_req,
1064 struct iovec *iov, int niov, bool create,
1065 enum AIOCBState aiocb_type)
1066 {
1067 int nr_copies = s->inode.nr_copies;
1068 SheepdogObjReq hdr;
1069 unsigned int wlen = 0;
1070 int ret;
1071 uint64_t oid = aio_req->oid;
1072 unsigned int datalen = aio_req->data_len;
1073 uint64_t offset = aio_req->offset;
1074 uint8_t flags = aio_req->flags;
1075 uint64_t old_oid = aio_req->base_oid;
1076
1077 if (!nr_copies) {
1078 error_report("bug");
1079 }
1080
1081 memset(&hdr, 0, sizeof(hdr));
1082
1083 switch (aiocb_type) {
1084 case AIOCB_FLUSH_CACHE:
1085 hdr.opcode = SD_OP_FLUSH_VDI;
1086 break;
1087 case AIOCB_READ_UDATA:
1088 hdr.opcode = SD_OP_READ_OBJ;
1089 hdr.flags = flags;
1090 break;
1091 case AIOCB_WRITE_UDATA:
1092 if (create) {
1093 hdr.opcode = SD_OP_CREATE_AND_WRITE_OBJ;
1094 } else {
1095 hdr.opcode = SD_OP_WRITE_OBJ;
1096 }
1097 wlen = datalen;
1098 hdr.flags = SD_FLAG_CMD_WRITE | flags;
1099 break;
1100 case AIOCB_DISCARD_OBJ:
1101 hdr.opcode = SD_OP_DISCARD_OBJ;
1102 break;
1103 }
1104
1105 if (s->cache_flags) {
1106 hdr.flags |= s->cache_flags;
1107 }
1108
1109 hdr.oid = oid;
1110 hdr.cow_oid = old_oid;
1111 hdr.copies = s->inode.nr_copies;
1112
1113 hdr.data_length = datalen;
1114 hdr.offset = offset;
1115
1116 hdr.id = aio_req->id;
1117
1118 qemu_co_mutex_lock(&s->lock);
1119 s->co_send = qemu_coroutine_self();
1120 qemu_aio_set_fd_handler(s->fd, co_read_response, co_write_request, s);
1121 socket_set_cork(s->fd, 1);
1122
1123 /* send a header */
1124 ret = qemu_co_send(s->fd, &hdr, sizeof(hdr));
1125 if (ret != sizeof(hdr)) {
1126 error_report("failed to send a req, %s", strerror(errno));
1127 goto out;
1128 }
1129
1130 if (wlen) {
1131 ret = qemu_co_sendv(s->fd, iov, niov, aio_req->iov_offset, wlen);
1132 if (ret != wlen) {
1133 error_report("failed to send a data, %s", strerror(errno));
1134 }
1135 }
1136 out:
1137 socket_set_cork(s->fd, 0);
1138 qemu_aio_set_fd_handler(s->fd, co_read_response, NULL, s);
1139 s->co_send = NULL;
1140 qemu_co_mutex_unlock(&s->lock);
1141 }
1142
1143 static int read_write_object(int fd, char *buf, uint64_t oid, uint8_t copies,
1144 unsigned int datalen, uint64_t offset,
1145 bool write, bool create, uint32_t cache_flags)
1146 {
1147 SheepdogObjReq hdr;
1148 SheepdogObjRsp *rsp = (SheepdogObjRsp *)&hdr;
1149 unsigned int wlen, rlen;
1150 int ret;
1151
1152 memset(&hdr, 0, sizeof(hdr));
1153
1154 if (write) {
1155 wlen = datalen;
1156 rlen = 0;
1157 hdr.flags = SD_FLAG_CMD_WRITE;
1158 if (create) {
1159 hdr.opcode = SD_OP_CREATE_AND_WRITE_OBJ;
1160 } else {
1161 hdr.opcode = SD_OP_WRITE_OBJ;
1162 }
1163 } else {
1164 wlen = 0;
1165 rlen = datalen;
1166 hdr.opcode = SD_OP_READ_OBJ;
1167 }
1168
1169 hdr.flags |= cache_flags;
1170
1171 hdr.oid = oid;
1172 hdr.data_length = datalen;
1173 hdr.offset = offset;
1174 hdr.copies = copies;
1175
1176 ret = do_req(fd, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
1177 if (ret) {
1178 error_report("failed to send a request to the sheep");
1179 return ret;
1180 }
1181
1182 switch (rsp->result) {
1183 case SD_RES_SUCCESS:
1184 return 0;
1185 default:
1186 error_report("%s", sd_strerror(rsp->result));
1187 return -EIO;
1188 }
1189 }
1190
1191 static int read_object(int fd, char *buf, uint64_t oid, uint8_t copies,
1192 unsigned int datalen, uint64_t offset,
1193 uint32_t cache_flags)
1194 {
1195 return read_write_object(fd, buf, oid, copies, datalen, offset, false,
1196 false, cache_flags);
1197 }
1198
1199 static int write_object(int fd, char *buf, uint64_t oid, uint8_t copies,
1200 unsigned int datalen, uint64_t offset, bool create,
1201 uint32_t cache_flags)
1202 {
1203 return read_write_object(fd, buf, oid, copies, datalen, offset, true,
1204 create, cache_flags);
1205 }
1206
1207 /* update inode with the latest state */
1208 static int reload_inode(BDRVSheepdogState *s, uint32_t snapid, const char *tag)
1209 {
1210 SheepdogInode *inode;
1211 int ret = 0, fd;
1212 uint32_t vid = 0;
1213
1214 fd = connect_to_sdog(s);
1215 if (fd < 0) {
1216 return -EIO;
1217 }
1218
1219 inode = g_malloc(sizeof(s->inode));
1220
1221 ret = find_vdi_name(s, s->name, snapid, tag, &vid, false);
1222 if (ret) {
1223 goto out;
1224 }
1225
1226 ret = read_object(fd, (char *)inode, vid_to_vdi_oid(vid),
1227 s->inode.nr_copies, sizeof(*inode), 0, s->cache_flags);
1228 if (ret < 0) {
1229 goto out;
1230 }
1231
1232 if (inode->vdi_id != s->inode.vdi_id) {
1233 memcpy(&s->inode, inode, sizeof(s->inode));
1234 }
1235
1236 out:
1237 g_free(inode);
1238 closesocket(fd);
1239
1240 return ret;
1241 }
1242
1243 static void coroutine_fn resend_aioreq(BDRVSheepdogState *s, AIOReq *aio_req)
1244 {
1245 SheepdogAIOCB *acb = aio_req->aiocb;
1246 bool create = false;
1247
1248 /* check whether this request becomes a CoW one */
1249 if (acb->aiocb_type == AIOCB_WRITE_UDATA && is_data_obj(aio_req->oid)) {
1250 int idx = data_oid_to_idx(aio_req->oid);
1251 AIOReq *areq;
1252
1253 if (s->inode.data_vdi_id[idx] == 0) {
1254 create = true;
1255 goto out;
1256 }
1257 if (is_data_obj_writable(&s->inode, idx)) {
1258 goto out;
1259 }
1260
1261 /* link to the pending list if there is another CoW request to
1262 * the same object */
1263 QLIST_FOREACH(areq, &s->inflight_aio_head, aio_siblings) {
1264 if (areq != aio_req && areq->oid == aio_req->oid) {
1265 DPRINTF("simultaneous CoW to %" PRIx64 "\n", aio_req->oid);
1266 QLIST_REMOVE(aio_req, aio_siblings);
1267 QLIST_INSERT_HEAD(&s->pending_aio_head, aio_req, aio_siblings);
1268 return;
1269 }
1270 }
1271
1272 aio_req->base_oid = vid_to_data_oid(s->inode.data_vdi_id[idx], idx);
1273 aio_req->flags |= SD_FLAG_CMD_COW;
1274 create = true;
1275 }
1276 out:
1277 if (is_data_obj(aio_req->oid)) {
1278 add_aio_request(s, aio_req, acb->qiov->iov, acb->qiov->niov, create,
1279 acb->aiocb_type);
1280 } else {
1281 struct iovec iov;
1282 iov.iov_base = &s->inode;
1283 iov.iov_len = sizeof(s->inode);
1284 add_aio_request(s, aio_req, &iov, 1, false, AIOCB_WRITE_UDATA);
1285 }
1286 }
1287
1288 /* TODO Convert to fine grained options */
1289 static QemuOptsList runtime_opts = {
1290 .name = "sheepdog",
1291 .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
1292 .desc = {
1293 {
1294 .name = "filename",
1295 .type = QEMU_OPT_STRING,
1296 .help = "URL to the sheepdog image",
1297 },
1298 { /* end of list */ }
1299 },
1300 };
1301
1302 static int sd_open(BlockDriverState *bs, QDict *options, int flags,
1303 Error **errp)
1304 {
1305 int ret, fd;
1306 uint32_t vid = 0;
1307 BDRVSheepdogState *s = bs->opaque;
1308 char vdi[SD_MAX_VDI_LEN], tag[SD_MAX_VDI_TAG_LEN];
1309 uint32_t snapid;
1310 char *buf = NULL;
1311 QemuOpts *opts;
1312 Error *local_err = NULL;
1313 const char *filename;
1314
1315 s->bs = bs;
1316
1317 opts = qemu_opts_create_nofail(&runtime_opts);
1318 qemu_opts_absorb_qdict(opts, options, &local_err);
1319 if (error_is_set(&local_err)) {
1320 qerror_report_err(local_err);
1321 error_free(local_err);
1322 ret = -EINVAL;
1323 goto out;
1324 }
1325
1326 filename = qemu_opt_get(opts, "filename");
1327
1328 QLIST_INIT(&s->inflight_aio_head);
1329 QLIST_INIT(&s->pending_aio_head);
1330 QLIST_INIT(&s->failed_aio_head);
1331 s->fd = -1;
1332
1333 memset(vdi, 0, sizeof(vdi));
1334 memset(tag, 0, sizeof(tag));
1335
1336 if (strstr(filename, "://")) {
1337 ret = sd_parse_uri(s, filename, vdi, &snapid, tag);
1338 } else {
1339 ret = parse_vdiname(s, filename, vdi, &snapid, tag);
1340 }
1341 if (ret < 0) {
1342 goto out;
1343 }
1344 s->fd = get_sheep_fd(s);
1345 if (s->fd < 0) {
1346 ret = s->fd;
1347 goto out;
1348 }
1349
1350 ret = find_vdi_name(s, vdi, snapid, tag, &vid, true);
1351 if (ret) {
1352 goto out;
1353 }
1354
1355 /*
1356 * QEMU block layer emulates writethrough cache as 'writeback + flush', so
1357 * we always set SD_FLAG_CMD_CACHE (writeback cache) as default.
1358 */
1359 s->cache_flags = SD_FLAG_CMD_CACHE;
1360 if (flags & BDRV_O_NOCACHE) {
1361 s->cache_flags = SD_FLAG_CMD_DIRECT;
1362 }
1363 s->discard_supported = true;
1364
1365 if (snapid || tag[0] != '\0') {
1366 DPRINTF("%" PRIx32 " snapshot inode was open.\n", vid);
1367 s->is_snapshot = true;
1368 }
1369
1370 fd = connect_to_sdog(s);
1371 if (fd < 0) {
1372 ret = fd;
1373 goto out;
1374 }
1375
1376 buf = g_malloc(SD_INODE_SIZE);
1377 ret = read_object(fd, buf, vid_to_vdi_oid(vid), 0, SD_INODE_SIZE, 0,
1378 s->cache_flags);
1379
1380 closesocket(fd);
1381
1382 if (ret) {
1383 goto out;
1384 }
1385
1386 memcpy(&s->inode, buf, sizeof(s->inode));
1387 s->min_dirty_data_idx = UINT32_MAX;
1388 s->max_dirty_data_idx = 0;
1389
1390 bs->total_sectors = s->inode.vdi_size / BDRV_SECTOR_SIZE;
1391 pstrcpy(s->name, sizeof(s->name), vdi);
1392 qemu_co_mutex_init(&s->lock);
1393 qemu_opts_del(opts);
1394 g_free(buf);
1395 return 0;
1396 out:
1397 qemu_aio_set_fd_handler(s->fd, NULL, NULL, NULL);
1398 if (s->fd >= 0) {
1399 closesocket(s->fd);
1400 }
1401 qemu_opts_del(opts);
1402 g_free(buf);
1403 return ret;
1404 }
1405
1406 static int do_sd_create(BDRVSheepdogState *s, char *filename, int64_t vdi_size,
1407 uint32_t base_vid, uint32_t *vdi_id, int snapshot,
1408 uint8_t copy_policy)
1409 {
1410 SheepdogVdiReq hdr;
1411 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
1412 int fd, ret;
1413 unsigned int wlen, rlen = 0;
1414 char buf[SD_MAX_VDI_LEN];
1415
1416 fd = connect_to_sdog(s);
1417 if (fd < 0) {
1418 return fd;
1419 }
1420
1421 /* FIXME: would it be better to fail (e.g., return -EIO) when filename
1422 * does not fit in buf? For now, just truncate and avoid buffer overrun.
1423 */
1424 memset(buf, 0, sizeof(buf));
1425 pstrcpy(buf, sizeof(buf), filename);
1426
1427 memset(&hdr, 0, sizeof(hdr));
1428 hdr.opcode = SD_OP_NEW_VDI;
1429 hdr.vdi_id = base_vid;
1430
1431 wlen = SD_MAX_VDI_LEN;
1432
1433 hdr.flags = SD_FLAG_CMD_WRITE;
1434 hdr.snapid = snapshot;
1435
1436 hdr.data_length = wlen;
1437 hdr.vdi_size = vdi_size;
1438 hdr.copy_policy = copy_policy;
1439
1440 ret = do_req(fd, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
1441
1442 closesocket(fd);
1443
1444 if (ret) {
1445 return ret;
1446 }
1447
1448 if (rsp->result != SD_RES_SUCCESS) {
1449 error_report("%s, %s", sd_strerror(rsp->result), filename);
1450 return -EIO;
1451 }
1452
1453 if (vdi_id) {
1454 *vdi_id = rsp->vdi_id;
1455 }
1456
1457 return 0;
1458 }
1459
1460 static int sd_prealloc(const char *filename)
1461 {
1462 BlockDriverState *bs = NULL;
1463 uint32_t idx, max_idx;
1464 int64_t vdi_size;
1465 void *buf = g_malloc0(SD_DATA_OBJ_SIZE);
1466 Error *local_err = NULL;
1467 int ret;
1468
1469 ret = bdrv_file_open(&bs, filename, NULL, BDRV_O_RDWR, &local_err);
1470 if (ret < 0) {
1471 qerror_report_err(local_err);
1472 error_free(local_err);
1473 goto out;
1474 }
1475
1476 vdi_size = bdrv_getlength(bs);
1477 if (vdi_size < 0) {
1478 ret = vdi_size;
1479 goto out;
1480 }
1481 max_idx = DIV_ROUND_UP(vdi_size, SD_DATA_OBJ_SIZE);
1482
1483 for (idx = 0; idx < max_idx; idx++) {
1484 /*
1485 * The created image can be a cloned image, so we need to read
1486 * a data from the source image.
1487 */
1488 ret = bdrv_pread(bs, idx * SD_DATA_OBJ_SIZE, buf, SD_DATA_OBJ_SIZE);
1489 if (ret < 0) {
1490 goto out;
1491 }
1492 ret = bdrv_pwrite(bs, idx * SD_DATA_OBJ_SIZE, buf, SD_DATA_OBJ_SIZE);
1493 if (ret < 0) {
1494 goto out;
1495 }
1496 }
1497 out:
1498 if (bs) {
1499 bdrv_unref(bs);
1500 }
1501 g_free(buf);
1502
1503 return ret;
1504 }
1505
1506 static int sd_create(const char *filename, QEMUOptionParameter *options,
1507 Error **errp)
1508 {
1509 int ret = 0;
1510 uint32_t vid = 0, base_vid = 0;
1511 int64_t vdi_size = 0;
1512 char *backing_file = NULL;
1513 BDRVSheepdogState *s;
1514 char vdi[SD_MAX_VDI_LEN], tag[SD_MAX_VDI_TAG_LEN];
1515 uint32_t snapid;
1516 bool prealloc = false;
1517 Error *local_err = NULL;
1518
1519 s = g_malloc0(sizeof(BDRVSheepdogState));
1520
1521 memset(vdi, 0, sizeof(vdi));
1522 memset(tag, 0, sizeof(tag));
1523 if (strstr(filename, "://")) {
1524 ret = sd_parse_uri(s, filename, vdi, &snapid, tag);
1525 } else {
1526 ret = parse_vdiname(s, filename, vdi, &snapid, tag);
1527 }
1528 if (ret < 0) {
1529 goto out;
1530 }
1531
1532 while (options && options->name) {
1533 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
1534 vdi_size = options->value.n;
1535 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
1536 backing_file = options->value.s;
1537 } else if (!strcmp(options->name, BLOCK_OPT_PREALLOC)) {
1538 if (!options->value.s || !strcmp(options->value.s, "off")) {
1539 prealloc = false;
1540 } else if (!strcmp(options->value.s, "full")) {
1541 prealloc = true;
1542 } else {
1543 error_report("Invalid preallocation mode: '%s'",
1544 options->value.s);
1545 ret = -EINVAL;
1546 goto out;
1547 }
1548 }
1549 options++;
1550 }
1551
1552 if (vdi_size > SD_MAX_VDI_SIZE) {
1553 error_report("too big image size");
1554 ret = -EINVAL;
1555 goto out;
1556 }
1557
1558 if (backing_file) {
1559 BlockDriverState *bs;
1560 BDRVSheepdogState *s;
1561 BlockDriver *drv;
1562
1563 /* Currently, only Sheepdog backing image is supported. */
1564 drv = bdrv_find_protocol(backing_file, true);
1565 if (!drv || strcmp(drv->protocol_name, "sheepdog") != 0) {
1566 error_report("backing_file must be a sheepdog image");
1567 ret = -EINVAL;
1568 goto out;
1569 }
1570
1571 ret = bdrv_file_open(&bs, backing_file, NULL, 0, &local_err);
1572 if (ret < 0) {
1573 qerror_report_err(local_err);
1574 error_free(local_err);
1575 goto out;
1576 }
1577
1578 s = bs->opaque;
1579
1580 if (!is_snapshot(&s->inode)) {
1581 error_report("cannot clone from a non snapshot vdi");
1582 bdrv_unref(bs);
1583 ret = -EINVAL;
1584 goto out;
1585 }
1586
1587 base_vid = s->inode.vdi_id;
1588 bdrv_unref(bs);
1589 }
1590
1591 /* TODO: allow users to specify copy number */
1592 ret = do_sd_create(s, vdi, vdi_size, base_vid, &vid, 0, 0);
1593 if (!prealloc || ret) {
1594 goto out;
1595 }
1596
1597 ret = sd_prealloc(filename);
1598 out:
1599 g_free(s);
1600 return ret;
1601 }
1602
1603 static void sd_close(BlockDriverState *bs)
1604 {
1605 BDRVSheepdogState *s = bs->opaque;
1606 SheepdogVdiReq hdr;
1607 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
1608 unsigned int wlen, rlen = 0;
1609 int fd, ret;
1610
1611 DPRINTF("%s\n", s->name);
1612
1613 fd = connect_to_sdog(s);
1614 if (fd < 0) {
1615 return;
1616 }
1617
1618 memset(&hdr, 0, sizeof(hdr));
1619
1620 hdr.opcode = SD_OP_RELEASE_VDI;
1621 hdr.vdi_id = s->inode.vdi_id;
1622 wlen = strlen(s->name) + 1;
1623 hdr.data_length = wlen;
1624 hdr.flags = SD_FLAG_CMD_WRITE;
1625
1626 ret = do_req(fd, (SheepdogReq *)&hdr, s->name, &wlen, &rlen);
1627
1628 closesocket(fd);
1629
1630 if (!ret && rsp->result != SD_RES_SUCCESS &&
1631 rsp->result != SD_RES_VDI_NOT_LOCKED) {
1632 error_report("%s, %s", sd_strerror(rsp->result), s->name);
1633 }
1634
1635 qemu_aio_set_fd_handler(s->fd, NULL, NULL, NULL);
1636 closesocket(s->fd);
1637 g_free(s->host_spec);
1638 }
1639
1640 static int64_t sd_getlength(BlockDriverState *bs)
1641 {
1642 BDRVSheepdogState *s = bs->opaque;
1643
1644 return s->inode.vdi_size;
1645 }
1646
1647 static int sd_truncate(BlockDriverState *bs, int64_t offset)
1648 {
1649 BDRVSheepdogState *s = bs->opaque;
1650 int ret, fd;
1651 unsigned int datalen;
1652
1653 if (offset < s->inode.vdi_size) {
1654 error_report("shrinking is not supported");
1655 return -EINVAL;
1656 } else if (offset > SD_MAX_VDI_SIZE) {
1657 error_report("too big image size");
1658 return -EINVAL;
1659 }
1660
1661 fd = connect_to_sdog(s);
1662 if (fd < 0) {
1663 return fd;
1664 }
1665
1666 /* we don't need to update entire object */
1667 datalen = SD_INODE_SIZE - sizeof(s->inode.data_vdi_id);
1668 s->inode.vdi_size = offset;
1669 ret = write_object(fd, (char *)&s->inode, vid_to_vdi_oid(s->inode.vdi_id),
1670 s->inode.nr_copies, datalen, 0, false, s->cache_flags);
1671 close(fd);
1672
1673 if (ret < 0) {
1674 error_report("failed to update an inode.");
1675 }
1676
1677 return ret;
1678 }
1679
1680 /*
1681 * This function is called after writing data objects. If we need to
1682 * update metadata, this sends a write request to the vdi object.
1683 * Otherwise, this switches back to sd_co_readv/writev.
1684 */
1685 static void coroutine_fn sd_write_done(SheepdogAIOCB *acb)
1686 {
1687 BDRVSheepdogState *s = acb->common.bs->opaque;
1688 struct iovec iov;
1689 AIOReq *aio_req;
1690 uint32_t offset, data_len, mn, mx;
1691
1692 mn = s->min_dirty_data_idx;
1693 mx = s->max_dirty_data_idx;
1694 if (mn <= mx) {
1695 /* we need to update the vdi object. */
1696 offset = sizeof(s->inode) - sizeof(s->inode.data_vdi_id) +
1697 mn * sizeof(s->inode.data_vdi_id[0]);
1698 data_len = (mx - mn + 1) * sizeof(s->inode.data_vdi_id[0]);
1699
1700 s->min_dirty_data_idx = UINT32_MAX;
1701 s->max_dirty_data_idx = 0;
1702
1703 iov.iov_base = &s->inode;
1704 iov.iov_len = sizeof(s->inode);
1705 aio_req = alloc_aio_req(s, acb, vid_to_vdi_oid(s->inode.vdi_id),
1706 data_len, offset, 0, 0, offset);
1707 QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
1708 add_aio_request(s, aio_req, &iov, 1, false, AIOCB_WRITE_UDATA);
1709
1710 acb->aio_done_func = sd_finish_aiocb;
1711 acb->aiocb_type = AIOCB_WRITE_UDATA;
1712 return;
1713 }
1714
1715 sd_finish_aiocb(acb);
1716 }
1717
1718 /* Delete current working VDI on the snapshot chain */
1719 static bool sd_delete(BDRVSheepdogState *s)
1720 {
1721 unsigned int wlen = SD_MAX_VDI_LEN, rlen = 0;
1722 SheepdogVdiReq hdr = {
1723 .opcode = SD_OP_DEL_VDI,
1724 .vdi_id = s->inode.vdi_id,
1725 .data_length = wlen,
1726 .flags = SD_FLAG_CMD_WRITE,
1727 };
1728 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
1729 int fd, ret;
1730
1731 fd = connect_to_sdog(s);
1732 if (fd < 0) {
1733 return false;
1734 }
1735
1736 ret = do_req(fd, (SheepdogReq *)&hdr, s->name, &wlen, &rlen);
1737 closesocket(fd);
1738 if (ret) {
1739 return false;
1740 }
1741 switch (rsp->result) {
1742 case SD_RES_NO_VDI:
1743 error_report("%s was already deleted", s->name);
1744 /* fall through */
1745 case SD_RES_SUCCESS:
1746 break;
1747 default:
1748 error_report("%s, %s", sd_strerror(rsp->result), s->name);
1749 return false;
1750 }
1751
1752 return true;
1753 }
1754
1755 /*
1756 * Create a writable VDI from a snapshot
1757 */
1758 static int sd_create_branch(BDRVSheepdogState *s)
1759 {
1760 int ret, fd;
1761 uint32_t vid;
1762 char *buf;
1763 bool deleted;
1764
1765 DPRINTF("%" PRIx32 " is snapshot.\n", s->inode.vdi_id);
1766
1767 buf = g_malloc(SD_INODE_SIZE);
1768
1769 /*
1770 * Even If deletion fails, we will just create extra snapshot based on
1771 * the workding VDI which was supposed to be deleted. So no need to
1772 * false bail out.
1773 */
1774 deleted = sd_delete(s);
1775 ret = do_sd_create(s, s->name, s->inode.vdi_size, s->inode.vdi_id, &vid,
1776 !deleted, s->inode.copy_policy);
1777 if (ret) {
1778 goto out;
1779 }
1780
1781 DPRINTF("%" PRIx32 " is created.\n", vid);
1782
1783 fd = connect_to_sdog(s);
1784 if (fd < 0) {
1785 ret = fd;
1786 goto out;
1787 }
1788
1789 ret = read_object(fd, buf, vid_to_vdi_oid(vid), s->inode.nr_copies,
1790 SD_INODE_SIZE, 0, s->cache_flags);
1791
1792 closesocket(fd);
1793
1794 if (ret < 0) {
1795 goto out;
1796 }
1797
1798 memcpy(&s->inode, buf, sizeof(s->inode));
1799
1800 s->is_snapshot = false;
1801 ret = 0;
1802 DPRINTF("%" PRIx32 " was newly created.\n", s->inode.vdi_id);
1803
1804 out:
1805 g_free(buf);
1806
1807 return ret;
1808 }
1809
1810 /*
1811 * Send I/O requests to the server.
1812 *
1813 * This function sends requests to the server, links the requests to
1814 * the inflight_list in BDRVSheepdogState, and exits without
1815 * waiting the response. The responses are received in the
1816 * `aio_read_response' function which is called from the main loop as
1817 * a fd handler.
1818 *
1819 * Returns 1 when we need to wait a response, 0 when there is no sent
1820 * request and -errno in error cases.
1821 */
1822 static int coroutine_fn sd_co_rw_vector(void *p)
1823 {
1824 SheepdogAIOCB *acb = p;
1825 int ret = 0;
1826 unsigned long len, done = 0, total = acb->nb_sectors * BDRV_SECTOR_SIZE;
1827 unsigned long idx = acb->sector_num * BDRV_SECTOR_SIZE / SD_DATA_OBJ_SIZE;
1828 uint64_t oid;
1829 uint64_t offset = (acb->sector_num * BDRV_SECTOR_SIZE) % SD_DATA_OBJ_SIZE;
1830 BDRVSheepdogState *s = acb->common.bs->opaque;
1831 SheepdogInode *inode = &s->inode;
1832 AIOReq *aio_req;
1833
1834 if (acb->aiocb_type == AIOCB_WRITE_UDATA && s->is_snapshot) {
1835 /*
1836 * In the case we open the snapshot VDI, Sheepdog creates the
1837 * writable VDI when we do a write operation first.
1838 */
1839 ret = sd_create_branch(s);
1840 if (ret) {
1841 acb->ret = -EIO;
1842 goto out;
1843 }
1844 }
1845
1846 /*
1847 * Make sure we don't free the aiocb before we are done with all requests.
1848 * This additional reference is dropped at the end of this function.
1849 */
1850 acb->nr_pending++;
1851
1852 while (done != total) {
1853 uint8_t flags = 0;
1854 uint64_t old_oid = 0;
1855 bool create = false;
1856
1857 oid = vid_to_data_oid(inode->data_vdi_id[idx], idx);
1858
1859 len = MIN(total - done, SD_DATA_OBJ_SIZE - offset);
1860
1861 switch (acb->aiocb_type) {
1862 case AIOCB_READ_UDATA:
1863 if (!inode->data_vdi_id[idx]) {
1864 qemu_iovec_memset(acb->qiov, done, 0, len);
1865 goto done;
1866 }
1867 break;
1868 case AIOCB_WRITE_UDATA:
1869 if (!inode->data_vdi_id[idx]) {
1870 create = true;
1871 } else if (!is_data_obj_writable(inode, idx)) {
1872 /* Copy-On-Write */
1873 create = true;
1874 old_oid = oid;
1875 flags = SD_FLAG_CMD_COW;
1876 }
1877 break;
1878 case AIOCB_DISCARD_OBJ:
1879 /*
1880 * We discard the object only when the whole object is
1881 * 1) allocated 2) trimmed. Otherwise, simply skip it.
1882 */
1883 if (len != SD_DATA_OBJ_SIZE || inode->data_vdi_id[idx] == 0) {
1884 goto done;
1885 }
1886 break;
1887 default:
1888 break;
1889 }
1890
1891 if (create) {
1892 DPRINTF("update ino (%" PRIu32 ") %" PRIu64 " %" PRIu64 " %ld\n",
1893 inode->vdi_id, oid,
1894 vid_to_data_oid(inode->data_vdi_id[idx], idx), idx);
1895 oid = vid_to_data_oid(inode->vdi_id, idx);
1896 DPRINTF("new oid %" PRIx64 "\n", oid);
1897 }
1898
1899 aio_req = alloc_aio_req(s, acb, oid, len, offset, flags, old_oid, done);
1900
1901 if (create) {
1902 AIOReq *areq;
1903 QLIST_FOREACH(areq, &s->inflight_aio_head, aio_siblings) {
1904 if (areq->oid == oid) {
1905 /*
1906 * Sheepdog cannot handle simultaneous create
1907 * requests to the same object. So we cannot send
1908 * the request until the previous request
1909 * finishes.
1910 */
1911 aio_req->flags = 0;
1912 aio_req->base_oid = 0;
1913 QLIST_INSERT_HEAD(&s->pending_aio_head, aio_req,
1914 aio_siblings);
1915 goto done;
1916 }
1917 }
1918 }
1919
1920 QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
1921 add_aio_request(s, aio_req, acb->qiov->iov, acb->qiov->niov, create,
1922 acb->aiocb_type);
1923 done:
1924 offset = 0;
1925 idx++;
1926 done += len;
1927 }
1928 out:
1929 if (!--acb->nr_pending) {
1930 return acb->ret;
1931 }
1932 return 1;
1933 }
1934
1935 static coroutine_fn int sd_co_writev(BlockDriverState *bs, int64_t sector_num,
1936 int nb_sectors, QEMUIOVector *qiov)
1937 {
1938 SheepdogAIOCB *acb;
1939 int ret;
1940
1941 if (bs->growable && sector_num + nb_sectors > bs->total_sectors) {
1942 ret = sd_truncate(bs, (sector_num + nb_sectors) * BDRV_SECTOR_SIZE);
1943 if (ret < 0) {
1944 return ret;
1945 }
1946 bs->total_sectors = sector_num + nb_sectors;
1947 }
1948
1949 acb = sd_aio_setup(bs, qiov, sector_num, nb_sectors);
1950 acb->aio_done_func = sd_write_done;
1951 acb->aiocb_type = AIOCB_WRITE_UDATA;
1952
1953 ret = sd_co_rw_vector(acb);
1954 if (ret <= 0) {
1955 qemu_aio_release(acb);
1956 return ret;
1957 }
1958
1959 qemu_coroutine_yield();
1960
1961 return acb->ret;
1962 }
1963
1964 static coroutine_fn int sd_co_readv(BlockDriverState *bs, int64_t sector_num,
1965 int nb_sectors, QEMUIOVector *qiov)
1966 {
1967 SheepdogAIOCB *acb;
1968 int ret;
1969
1970 acb = sd_aio_setup(bs, qiov, sector_num, nb_sectors);
1971 acb->aiocb_type = AIOCB_READ_UDATA;
1972 acb->aio_done_func = sd_finish_aiocb;
1973
1974 ret = sd_co_rw_vector(acb);
1975 if (ret <= 0) {
1976 qemu_aio_release(acb);
1977 return ret;
1978 }
1979
1980 qemu_coroutine_yield();
1981
1982 return acb->ret;
1983 }
1984
1985 static int coroutine_fn sd_co_flush_to_disk(BlockDriverState *bs)
1986 {
1987 BDRVSheepdogState *s = bs->opaque;
1988 SheepdogAIOCB *acb;
1989 AIOReq *aio_req;
1990
1991 if (s->cache_flags != SD_FLAG_CMD_CACHE) {
1992 return 0;
1993 }
1994
1995 acb = sd_aio_setup(bs, NULL, 0, 0);
1996 acb->aiocb_type = AIOCB_FLUSH_CACHE;
1997 acb->aio_done_func = sd_finish_aiocb;
1998
1999 aio_req = alloc_aio_req(s, acb, vid_to_vdi_oid(s->inode.vdi_id),
2000 0, 0, 0, 0, 0);
2001 QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
2002 add_aio_request(s, aio_req, NULL, 0, false, acb->aiocb_type);
2003
2004 qemu_coroutine_yield();
2005 return acb->ret;
2006 }
2007
2008 static int sd_snapshot_create(BlockDriverState *bs, QEMUSnapshotInfo *sn_info)
2009 {
2010 BDRVSheepdogState *s = bs->opaque;
2011 int ret, fd;
2012 uint32_t new_vid;
2013 SheepdogInode *inode;
2014 unsigned int datalen;
2015
2016 DPRINTF("sn_info: name %s id_str %s s: name %s vm_state_size %" PRId64 " "
2017 "is_snapshot %d\n", sn_info->name, sn_info->id_str,
2018 s->name, sn_info->vm_state_size, s->is_snapshot);
2019
2020 if (s->is_snapshot) {
2021 error_report("You can't create a snapshot of a snapshot VDI, "
2022 "%s (%" PRIu32 ").", s->name, s->inode.vdi_id);
2023
2024 return -EINVAL;
2025 }
2026
2027 DPRINTF("%s %s\n", sn_info->name, sn_info->id_str);
2028
2029 s->inode.vm_state_size = sn_info->vm_state_size;
2030 s->inode.vm_clock_nsec = sn_info->vm_clock_nsec;
2031 /* It appears that inode.tag does not require a NUL terminator,
2032 * which means this use of strncpy is ok.
2033 */
2034 strncpy(s->inode.tag, sn_info->name, sizeof(s->inode.tag));
2035 /* we don't need to update entire object */
2036 datalen = SD_INODE_SIZE - sizeof(s->inode.data_vdi_id);
2037
2038 /* refresh inode. */
2039 fd = connect_to_sdog(s);
2040 if (fd < 0) {
2041 ret = fd;
2042 goto cleanup;
2043 }
2044
2045 ret = write_object(fd, (char *)&s->inode, vid_to_vdi_oid(s->inode.vdi_id),
2046 s->inode.nr_copies, datalen, 0, false, s->cache_flags);
2047 if (ret < 0) {
2048 error_report("failed to write snapshot's inode.");
2049 goto cleanup;
2050 }
2051
2052 ret = do_sd_create(s, s->name, s->inode.vdi_size, s->inode.vdi_id, &new_vid,
2053 1, s->inode.copy_policy);
2054 if (ret < 0) {
2055 error_report("failed to create inode for snapshot. %s",
2056 strerror(errno));
2057 goto cleanup;
2058 }
2059
2060 inode = (SheepdogInode *)g_malloc(datalen);
2061
2062 ret = read_object(fd, (char *)inode, vid_to_vdi_oid(new_vid),
2063 s->inode.nr_copies, datalen, 0, s->cache_flags);
2064
2065 if (ret < 0) {
2066 error_report("failed to read new inode info. %s", strerror(errno));
2067 goto cleanup;
2068 }
2069
2070 memcpy(&s->inode, inode, datalen);
2071 DPRINTF("s->inode: name %s snap_id %x oid %x\n",
2072 s->inode.name, s->inode.snap_id, s->inode.vdi_id);
2073
2074 cleanup:
2075 closesocket(fd);
2076 return ret;
2077 }
2078
2079 /*
2080 * We implement rollback(loadvm) operation to the specified snapshot by
2081 * 1) switch to the snapshot
2082 * 2) rely on sd_create_branch to delete working VDI and
2083 * 3) create a new working VDI based on the speicified snapshot
2084 */
2085 static int sd_snapshot_goto(BlockDriverState *bs, const char *snapshot_id)
2086 {
2087 BDRVSheepdogState *s = bs->opaque;
2088 BDRVSheepdogState *old_s;
2089 char tag[SD_MAX_VDI_TAG_LEN];
2090 uint32_t snapid = 0;
2091 int ret = 0;
2092
2093 old_s = g_malloc(sizeof(BDRVSheepdogState));
2094
2095 memcpy(old_s, s, sizeof(BDRVSheepdogState));
2096
2097 snapid = strtoul(snapshot_id, NULL, 10);
2098 if (snapid) {
2099 tag[0] = 0;
2100 } else {
2101 pstrcpy(tag, sizeof(tag), snapshot_id);
2102 }
2103
2104 ret = reload_inode(s, snapid, tag);
2105 if (ret) {
2106 goto out;
2107 }
2108
2109 ret = sd_create_branch(s);
2110 if (ret) {
2111 goto out;
2112 }
2113
2114 g_free(old_s);
2115
2116 return 0;
2117 out:
2118 /* recover bdrv_sd_state */
2119 memcpy(s, old_s, sizeof(BDRVSheepdogState));
2120 g_free(old_s);
2121
2122 error_report("failed to open. recover old bdrv_sd_state.");
2123
2124 return ret;
2125 }
2126
2127 static int sd_snapshot_delete(BlockDriverState *bs,
2128 const char *snapshot_id,
2129 const char *name,
2130 Error **errp)
2131 {
2132 /* FIXME: Delete specified snapshot id. */
2133 return 0;
2134 }
2135
2136 static int sd_snapshot_list(BlockDriverState *bs, QEMUSnapshotInfo **psn_tab)
2137 {
2138 BDRVSheepdogState *s = bs->opaque;
2139 SheepdogReq req;
2140 int fd, nr = 1024, ret, max = BITS_TO_LONGS(SD_NR_VDIS) * sizeof(long);
2141 QEMUSnapshotInfo *sn_tab = NULL;
2142 unsigned wlen, rlen;
2143 int found = 0;
2144 static SheepdogInode inode;
2145 unsigned long *vdi_inuse;
2146 unsigned int start_nr;
2147 uint64_t hval;
2148 uint32_t vid;
2149
2150 vdi_inuse = g_malloc(max);
2151
2152 fd = connect_to_sdog(s);
2153 if (fd < 0) {
2154 ret = fd;
2155 goto out;
2156 }
2157
2158 rlen = max;
2159 wlen = 0;
2160
2161 memset(&req, 0, sizeof(req));
2162
2163 req.opcode = SD_OP_READ_VDIS;
2164 req.data_length = max;
2165
2166 ret = do_req(fd, (SheepdogReq *)&req, vdi_inuse, &wlen, &rlen);
2167
2168 closesocket(fd);
2169 if (ret) {
2170 goto out;
2171 }
2172
2173 sn_tab = g_malloc0(nr * sizeof(*sn_tab));
2174
2175 /* calculate a vdi id with hash function */
2176 hval = fnv_64a_buf(s->name, strlen(s->name), FNV1A_64_INIT);
2177 start_nr = hval & (SD_NR_VDIS - 1);
2178
2179 fd = connect_to_sdog(s);
2180 if (fd < 0) {
2181 ret = fd;
2182 goto out;
2183 }
2184
2185 for (vid = start_nr; found < nr; vid = (vid + 1) % SD_NR_VDIS) {
2186 if (!test_bit(vid, vdi_inuse)) {
2187 break;
2188 }
2189
2190 /* we don't need to read entire object */
2191 ret = read_object(fd, (char *)&inode, vid_to_vdi_oid(vid),
2192 0, SD_INODE_SIZE - sizeof(inode.data_vdi_id), 0,
2193 s->cache_flags);
2194
2195 if (ret) {
2196 continue;
2197 }
2198
2199 if (!strcmp(inode.name, s->name) && is_snapshot(&inode)) {
2200 sn_tab[found].date_sec = inode.snap_ctime >> 32;
2201 sn_tab[found].date_nsec = inode.snap_ctime & 0xffffffff;
2202 sn_tab[found].vm_state_size = inode.vm_state_size;
2203 sn_tab[found].vm_clock_nsec = inode.vm_clock_nsec;
2204
2205 snprintf(sn_tab[found].id_str, sizeof(sn_tab[found].id_str), "%u",
2206 inode.snap_id);
2207 pstrcpy(sn_tab[found].name,
2208 MIN(sizeof(sn_tab[found].name), sizeof(inode.tag)),
2209 inode.tag);
2210 found++;
2211 }
2212 }
2213
2214 closesocket(fd);
2215 out:
2216 *psn_tab = sn_tab;
2217
2218 g_free(vdi_inuse);
2219
2220 if (ret < 0) {
2221 return ret;
2222 }
2223
2224 return found;
2225 }
2226
2227 static int do_load_save_vmstate(BDRVSheepdogState *s, uint8_t *data,
2228 int64_t pos, int size, int load)
2229 {
2230 bool create;
2231 int fd, ret = 0, remaining = size;
2232 unsigned int data_len;
2233 uint64_t vmstate_oid;
2234 uint64_t offset;
2235 uint32_t vdi_index;
2236 uint32_t vdi_id = load ? s->inode.parent_vdi_id : s->inode.vdi_id;
2237
2238 fd = connect_to_sdog(s);
2239 if (fd < 0) {
2240 return fd;
2241 }
2242
2243 while (remaining) {
2244 vdi_index = pos / SD_DATA_OBJ_SIZE;
2245 offset = pos % SD_DATA_OBJ_SIZE;
2246
2247 data_len = MIN(remaining, SD_DATA_OBJ_SIZE - offset);
2248
2249 vmstate_oid = vid_to_vmstate_oid(vdi_id, vdi_index);
2250
2251 create = (offset == 0);
2252 if (load) {
2253 ret = read_object(fd, (char *)data, vmstate_oid,
2254 s->inode.nr_copies, data_len, offset,
2255 s->cache_flags);
2256 } else {
2257 ret = write_object(fd, (char *)data, vmstate_oid,
2258 s->inode.nr_copies, data_len, offset, create,
2259 s->cache_flags);
2260 }
2261
2262 if (ret < 0) {
2263 error_report("failed to save vmstate %s", strerror(errno));
2264 goto cleanup;
2265 }
2266
2267 pos += data_len;
2268 data += data_len;
2269 remaining -= data_len;
2270 }
2271 ret = size;
2272 cleanup:
2273 closesocket(fd);
2274 return ret;
2275 }
2276
2277 static int sd_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2278 int64_t pos)
2279 {
2280 BDRVSheepdogState *s = bs->opaque;
2281 void *buf;
2282 int ret;
2283
2284 buf = qemu_blockalign(bs, qiov->size);
2285 qemu_iovec_to_buf(qiov, 0, buf, qiov->size);
2286 ret = do_load_save_vmstate(s, (uint8_t *) buf, pos, qiov->size, 0);
2287 qemu_vfree(buf);
2288
2289 return ret;
2290 }
2291
2292 static int sd_load_vmstate(BlockDriverState *bs, uint8_t *data,
2293 int64_t pos, int size)
2294 {
2295 BDRVSheepdogState *s = bs->opaque;
2296
2297 return do_load_save_vmstate(s, data, pos, size, 1);
2298 }
2299
2300
2301 static coroutine_fn int sd_co_discard(BlockDriverState *bs, int64_t sector_num,
2302 int nb_sectors)
2303 {
2304 SheepdogAIOCB *acb;
2305 QEMUIOVector dummy;
2306 BDRVSheepdogState *s = bs->opaque;
2307 int ret;
2308
2309 if (!s->discard_supported) {
2310 return 0;
2311 }
2312
2313 acb = sd_aio_setup(bs, &dummy, sector_num, nb_sectors);
2314 acb->aiocb_type = AIOCB_DISCARD_OBJ;
2315 acb->aio_done_func = sd_finish_aiocb;
2316
2317 ret = sd_co_rw_vector(acb);
2318 if (ret <= 0) {
2319 qemu_aio_release(acb);
2320 return ret;
2321 }
2322
2323 qemu_coroutine_yield();
2324
2325 return acb->ret;
2326 }
2327
2328 static coroutine_fn int64_t
2329 sd_co_get_block_status(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
2330 int *pnum)
2331 {
2332 BDRVSheepdogState *s = bs->opaque;
2333 SheepdogInode *inode = &s->inode;
2334 unsigned long start = sector_num * BDRV_SECTOR_SIZE / SD_DATA_OBJ_SIZE,
2335 end = DIV_ROUND_UP((sector_num + nb_sectors) *
2336 BDRV_SECTOR_SIZE, SD_DATA_OBJ_SIZE);
2337 unsigned long idx;
2338 int64_t ret = BDRV_BLOCK_DATA;
2339
2340 for (idx = start; idx < end; idx++) {
2341 if (inode->data_vdi_id[idx] == 0) {
2342 break;
2343 }
2344 }
2345 if (idx == start) {
2346 /* Get the longest length of unallocated sectors */
2347 ret = 0;
2348 for (idx = start + 1; idx < end; idx++) {
2349 if (inode->data_vdi_id[idx] != 0) {
2350 break;
2351 }
2352 }
2353 }
2354
2355 *pnum = (idx - start) * SD_DATA_OBJ_SIZE / BDRV_SECTOR_SIZE;
2356 if (*pnum > nb_sectors) {
2357 *pnum = nb_sectors;
2358 }
2359 return ret;
2360 }
2361
2362 static QEMUOptionParameter sd_create_options[] = {
2363 {
2364 .name = BLOCK_OPT_SIZE,
2365 .type = OPT_SIZE,
2366 .help = "Virtual disk size"
2367 },
2368 {
2369 .name = BLOCK_OPT_BACKING_FILE,
2370 .type = OPT_STRING,
2371 .help = "File name of a base image"
2372 },
2373 {
2374 .name = BLOCK_OPT_PREALLOC,
2375 .type = OPT_STRING,
2376 .help = "Preallocation mode (allowed values: off, full)"
2377 },
2378 { NULL }
2379 };
2380
2381 static BlockDriver bdrv_sheepdog = {
2382 .format_name = "sheepdog",
2383 .protocol_name = "sheepdog",
2384 .instance_size = sizeof(BDRVSheepdogState),
2385 .bdrv_needs_filename = true,
2386 .bdrv_file_open = sd_open,
2387 .bdrv_close = sd_close,
2388 .bdrv_create = sd_create,
2389 .bdrv_has_zero_init = bdrv_has_zero_init_1,
2390 .bdrv_getlength = sd_getlength,
2391 .bdrv_truncate = sd_truncate,
2392
2393 .bdrv_co_readv = sd_co_readv,
2394 .bdrv_co_writev = sd_co_writev,
2395 .bdrv_co_flush_to_disk = sd_co_flush_to_disk,
2396 .bdrv_co_discard = sd_co_discard,
2397 .bdrv_co_get_block_status = sd_co_get_block_status,
2398
2399 .bdrv_snapshot_create = sd_snapshot_create,
2400 .bdrv_snapshot_goto = sd_snapshot_goto,
2401 .bdrv_snapshot_delete = sd_snapshot_delete,
2402 .bdrv_snapshot_list = sd_snapshot_list,
2403
2404 .bdrv_save_vmstate = sd_save_vmstate,
2405 .bdrv_load_vmstate = sd_load_vmstate,
2406
2407 .create_options = sd_create_options,
2408 };
2409
2410 static BlockDriver bdrv_sheepdog_tcp = {
2411 .format_name = "sheepdog",
2412 .protocol_name = "sheepdog+tcp",
2413 .instance_size = sizeof(BDRVSheepdogState),
2414 .bdrv_needs_filename = true,
2415 .bdrv_file_open = sd_open,
2416 .bdrv_close = sd_close,
2417 .bdrv_create = sd_create,
2418 .bdrv_has_zero_init = bdrv_has_zero_init_1,
2419 .bdrv_getlength = sd_getlength,
2420 .bdrv_truncate = sd_truncate,
2421
2422 .bdrv_co_readv = sd_co_readv,
2423 .bdrv_co_writev = sd_co_writev,
2424 .bdrv_co_flush_to_disk = sd_co_flush_to_disk,
2425 .bdrv_co_discard = sd_co_discard,
2426 .bdrv_co_get_block_status = sd_co_get_block_status,
2427
2428 .bdrv_snapshot_create = sd_snapshot_create,
2429 .bdrv_snapshot_goto = sd_snapshot_goto,
2430 .bdrv_snapshot_delete = sd_snapshot_delete,
2431 .bdrv_snapshot_list = sd_snapshot_list,
2432
2433 .bdrv_save_vmstate = sd_save_vmstate,
2434 .bdrv_load_vmstate = sd_load_vmstate,
2435
2436 .create_options = sd_create_options,
2437 };
2438
2439 static BlockDriver bdrv_sheepdog_unix = {
2440 .format_name = "sheepdog",
2441 .protocol_name = "sheepdog+unix",
2442 .instance_size = sizeof(BDRVSheepdogState),
2443 .bdrv_needs_filename = true,
2444 .bdrv_file_open = sd_open,
2445 .bdrv_close = sd_close,
2446 .bdrv_create = sd_create,
2447 .bdrv_has_zero_init = bdrv_has_zero_init_1,
2448 .bdrv_getlength = sd_getlength,
2449 .bdrv_truncate = sd_truncate,
2450
2451 .bdrv_co_readv = sd_co_readv,
2452 .bdrv_co_writev = sd_co_writev,
2453 .bdrv_co_flush_to_disk = sd_co_flush_to_disk,
2454 .bdrv_co_discard = sd_co_discard,
2455 .bdrv_co_get_block_status = sd_co_get_block_status,
2456
2457 .bdrv_snapshot_create = sd_snapshot_create,
2458 .bdrv_snapshot_goto = sd_snapshot_goto,
2459 .bdrv_snapshot_delete = sd_snapshot_delete,
2460 .bdrv_snapshot_list = sd_snapshot_list,
2461
2462 .bdrv_save_vmstate = sd_save_vmstate,
2463 .bdrv_load_vmstate = sd_load_vmstate,
2464
2465 .create_options = sd_create_options,
2466 };
2467
2468 static void bdrv_sheepdog_init(void)
2469 {
2470 bdrv_register(&bdrv_sheepdog);
2471 bdrv_register(&bdrv_sheepdog_tcp);
2472 bdrv_register(&bdrv_sheepdog_unix);
2473 }
2474 block_init(bdrv_sheepdog_init);