]> git.proxmox.com Git - mirror_qemu.git/blob - block/sheepdog.c
qapi: merge QInt and QFloat in QNum
[mirror_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/osdep.h"
16 #include "qapi-visit.h"
17 #include "qapi/error.h"
18 #include "qapi/qmp/qdict.h"
19 #include "qapi/qobject-input-visitor.h"
20 #include "qemu/uri.h"
21 #include "qemu/error-report.h"
22 #include "qemu/sockets.h"
23 #include "block/block_int.h"
24 #include "sysemu/block-backend.h"
25 #include "qemu/bitops.h"
26 #include "qemu/cutils.h"
27
28 #define SD_PROTO_VER 0x01
29
30 #define SD_DEFAULT_ADDR "localhost"
31 #define SD_DEFAULT_PORT 7000
32
33 #define SD_OP_CREATE_AND_WRITE_OBJ 0x01
34 #define SD_OP_READ_OBJ 0x02
35 #define SD_OP_WRITE_OBJ 0x03
36 /* 0x04 is used internally by Sheepdog */
37
38 #define SD_OP_NEW_VDI 0x11
39 #define SD_OP_LOCK_VDI 0x12
40 #define SD_OP_RELEASE_VDI 0x13
41 #define SD_OP_GET_VDI_INFO 0x14
42 #define SD_OP_READ_VDIS 0x15
43 #define SD_OP_FLUSH_VDI 0x16
44 #define SD_OP_DEL_VDI 0x17
45 #define SD_OP_GET_CLUSTER_DEFAULT 0x18
46
47 #define SD_FLAG_CMD_WRITE 0x01
48 #define SD_FLAG_CMD_COW 0x02
49 #define SD_FLAG_CMD_CACHE 0x04 /* Writeback mode for cache */
50 #define SD_FLAG_CMD_DIRECT 0x08 /* Don't use cache */
51
52 #define SD_RES_SUCCESS 0x00 /* Success */
53 #define SD_RES_UNKNOWN 0x01 /* Unknown error */
54 #define SD_RES_NO_OBJ 0x02 /* No object found */
55 #define SD_RES_EIO 0x03 /* I/O error */
56 #define SD_RES_VDI_EXIST 0x04 /* Vdi exists already */
57 #define SD_RES_INVALID_PARMS 0x05 /* Invalid parameters */
58 #define SD_RES_SYSTEM_ERROR 0x06 /* System error */
59 #define SD_RES_VDI_LOCKED 0x07 /* Vdi is locked */
60 #define SD_RES_NO_VDI 0x08 /* No vdi found */
61 #define SD_RES_NO_BASE_VDI 0x09 /* No base vdi found */
62 #define SD_RES_VDI_READ 0x0A /* Cannot read requested vdi */
63 #define SD_RES_VDI_WRITE 0x0B /* Cannot write requested vdi */
64 #define SD_RES_BASE_VDI_READ 0x0C /* Cannot read base vdi */
65 #define SD_RES_BASE_VDI_WRITE 0x0D /* Cannot write base vdi */
66 #define SD_RES_NO_TAG 0x0E /* Requested tag is not found */
67 #define SD_RES_STARTUP 0x0F /* Sheepdog is on starting up */
68 #define SD_RES_VDI_NOT_LOCKED 0x10 /* Vdi is not locked */
69 #define SD_RES_SHUTDOWN 0x11 /* Sheepdog is shutting down */
70 #define SD_RES_NO_MEM 0x12 /* Cannot allocate memory */
71 #define SD_RES_FULL_VDI 0x13 /* we already have the maximum vdis */
72 #define SD_RES_VER_MISMATCH 0x14 /* Protocol version mismatch */
73 #define SD_RES_NO_SPACE 0x15 /* Server has no room for new objects */
74 #define SD_RES_WAIT_FOR_FORMAT 0x16 /* Waiting for a format operation */
75 #define SD_RES_WAIT_FOR_JOIN 0x17 /* Waiting for other nodes joining */
76 #define SD_RES_JOIN_FAILED 0x18 /* Target node had failed to join sheepdog */
77 #define SD_RES_HALT 0x19 /* Sheepdog is stopped serving IO request */
78 #define SD_RES_READONLY 0x1A /* Object is read-only */
79
80 /*
81 * Object ID rules
82 *
83 * 0 - 19 (20 bits): data object space
84 * 20 - 31 (12 bits): reserved data object space
85 * 32 - 55 (24 bits): vdi object space
86 * 56 - 59 ( 4 bits): reserved vdi object space
87 * 60 - 63 ( 4 bits): object type identifier space
88 */
89
90 #define VDI_SPACE_SHIFT 32
91 #define VDI_BIT (UINT64_C(1) << 63)
92 #define VMSTATE_BIT (UINT64_C(1) << 62)
93 #define MAX_DATA_OBJS (UINT64_C(1) << 20)
94 #define MAX_CHILDREN 1024
95 #define SD_MAX_VDI_LEN 256
96 #define SD_MAX_VDI_TAG_LEN 256
97 #define SD_NR_VDIS (1U << 24)
98 #define SD_DATA_OBJ_SIZE (UINT64_C(1) << 22)
99 #define SD_MAX_VDI_SIZE (SD_DATA_OBJ_SIZE * MAX_DATA_OBJS)
100 #define SD_DEFAULT_BLOCK_SIZE_SHIFT 22
101 /*
102 * For erasure coding, we use at most SD_EC_MAX_STRIP for data strips and
103 * (SD_EC_MAX_STRIP - 1) for parity strips
104 *
105 * SD_MAX_COPIES is sum of number of data strips and parity strips.
106 */
107 #define SD_EC_MAX_STRIP 16
108 #define SD_MAX_COPIES (SD_EC_MAX_STRIP * 2 - 1)
109
110 #define SD_INODE_SIZE (sizeof(SheepdogInode))
111 #define CURRENT_VDI_ID 0
112
113 #define LOCK_TYPE_NORMAL 0
114 #define LOCK_TYPE_SHARED 1 /* for iSCSI multipath */
115
116 typedef struct SheepdogReq {
117 uint8_t proto_ver;
118 uint8_t opcode;
119 uint16_t flags;
120 uint32_t epoch;
121 uint32_t id;
122 uint32_t data_length;
123 uint32_t opcode_specific[8];
124 } SheepdogReq;
125
126 typedef struct SheepdogRsp {
127 uint8_t proto_ver;
128 uint8_t opcode;
129 uint16_t flags;
130 uint32_t epoch;
131 uint32_t id;
132 uint32_t data_length;
133 uint32_t result;
134 uint32_t opcode_specific[7];
135 } SheepdogRsp;
136
137 typedef struct SheepdogObjReq {
138 uint8_t proto_ver;
139 uint8_t opcode;
140 uint16_t flags;
141 uint32_t epoch;
142 uint32_t id;
143 uint32_t data_length;
144 uint64_t oid;
145 uint64_t cow_oid;
146 uint8_t copies;
147 uint8_t copy_policy;
148 uint8_t reserved[6];
149 uint64_t offset;
150 } SheepdogObjReq;
151
152 typedef struct SheepdogObjRsp {
153 uint8_t proto_ver;
154 uint8_t opcode;
155 uint16_t flags;
156 uint32_t epoch;
157 uint32_t id;
158 uint32_t data_length;
159 uint32_t result;
160 uint8_t copies;
161 uint8_t copy_policy;
162 uint8_t reserved[2];
163 uint32_t pad[6];
164 } SheepdogObjRsp;
165
166 typedef struct SheepdogVdiReq {
167 uint8_t proto_ver;
168 uint8_t opcode;
169 uint16_t flags;
170 uint32_t epoch;
171 uint32_t id;
172 uint32_t data_length;
173 uint64_t vdi_size;
174 uint32_t base_vdi_id;
175 uint8_t copies;
176 uint8_t copy_policy;
177 uint8_t store_policy;
178 uint8_t block_size_shift;
179 uint32_t snapid;
180 uint32_t type;
181 uint32_t pad[2];
182 } SheepdogVdiReq;
183
184 typedef struct SheepdogVdiRsp {
185 uint8_t proto_ver;
186 uint8_t opcode;
187 uint16_t flags;
188 uint32_t epoch;
189 uint32_t id;
190 uint32_t data_length;
191 uint32_t result;
192 uint32_t rsvd;
193 uint32_t vdi_id;
194 uint32_t pad[5];
195 } SheepdogVdiRsp;
196
197 typedef struct SheepdogClusterRsp {
198 uint8_t proto_ver;
199 uint8_t opcode;
200 uint16_t flags;
201 uint32_t epoch;
202 uint32_t id;
203 uint32_t data_length;
204 uint32_t result;
205 uint8_t nr_copies;
206 uint8_t copy_policy;
207 uint8_t block_size_shift;
208 uint8_t __pad1;
209 uint32_t __pad2[6];
210 } SheepdogClusterRsp;
211
212 typedef struct SheepdogInode {
213 char name[SD_MAX_VDI_LEN];
214 char tag[SD_MAX_VDI_TAG_LEN];
215 uint64_t ctime;
216 uint64_t snap_ctime;
217 uint64_t vm_clock_nsec;
218 uint64_t vdi_size;
219 uint64_t vm_state_size;
220 uint16_t copy_policy;
221 uint8_t nr_copies;
222 uint8_t block_size_shift;
223 uint32_t snap_id;
224 uint32_t vdi_id;
225 uint32_t parent_vdi_id;
226 uint32_t child_vdi_id[MAX_CHILDREN];
227 uint32_t data_vdi_id[MAX_DATA_OBJS];
228 } SheepdogInode;
229
230 #define SD_INODE_HEADER_SIZE offsetof(SheepdogInode, data_vdi_id)
231
232 /*
233 * 64 bit FNV-1a non-zero initial basis
234 */
235 #define FNV1A_64_INIT ((uint64_t)0xcbf29ce484222325ULL)
236
237 /*
238 * 64 bit Fowler/Noll/Vo FNV-1a hash code
239 */
240 static inline uint64_t fnv_64a_buf(void *buf, size_t len, uint64_t hval)
241 {
242 unsigned char *bp = buf;
243 unsigned char *be = bp + len;
244 while (bp < be) {
245 hval ^= (uint64_t) *bp++;
246 hval += (hval << 1) + (hval << 4) + (hval << 5) +
247 (hval << 7) + (hval << 8) + (hval << 40);
248 }
249 return hval;
250 }
251
252 static inline bool is_data_obj_writable(SheepdogInode *inode, unsigned int idx)
253 {
254 return inode->vdi_id == inode->data_vdi_id[idx];
255 }
256
257 static inline bool is_data_obj(uint64_t oid)
258 {
259 return !(VDI_BIT & oid);
260 }
261
262 static inline uint64_t data_oid_to_idx(uint64_t oid)
263 {
264 return oid & (MAX_DATA_OBJS - 1);
265 }
266
267 static inline uint32_t oid_to_vid(uint64_t oid)
268 {
269 return (oid & ~VDI_BIT) >> VDI_SPACE_SHIFT;
270 }
271
272 static inline uint64_t vid_to_vdi_oid(uint32_t vid)
273 {
274 return VDI_BIT | ((uint64_t)vid << VDI_SPACE_SHIFT);
275 }
276
277 static inline uint64_t vid_to_vmstate_oid(uint32_t vid, uint32_t idx)
278 {
279 return VMSTATE_BIT | ((uint64_t)vid << VDI_SPACE_SHIFT) | idx;
280 }
281
282 static inline uint64_t vid_to_data_oid(uint32_t vid, uint32_t idx)
283 {
284 return ((uint64_t)vid << VDI_SPACE_SHIFT) | idx;
285 }
286
287 static inline bool is_snapshot(struct SheepdogInode *inode)
288 {
289 return !!inode->snap_ctime;
290 }
291
292 static inline size_t count_data_objs(const struct SheepdogInode *inode)
293 {
294 return DIV_ROUND_UP(inode->vdi_size,
295 (1UL << inode->block_size_shift));
296 }
297
298 #undef DPRINTF
299 #ifdef DEBUG_SDOG
300 #define DEBUG_SDOG_PRINT 1
301 #else
302 #define DEBUG_SDOG_PRINT 0
303 #endif
304 #define DPRINTF(fmt, args...) \
305 do { \
306 if (DEBUG_SDOG_PRINT) { \
307 fprintf(stderr, "%s %d: " fmt, __func__, __LINE__, ##args); \
308 } \
309 } while (0)
310
311 typedef struct SheepdogAIOCB SheepdogAIOCB;
312 typedef struct BDRVSheepdogState BDRVSheepdogState;
313
314 typedef struct AIOReq {
315 SheepdogAIOCB *aiocb;
316 unsigned int iov_offset;
317
318 uint64_t oid;
319 uint64_t base_oid;
320 uint64_t offset;
321 unsigned int data_len;
322 uint8_t flags;
323 uint32_t id;
324 bool create;
325
326 QLIST_ENTRY(AIOReq) aio_siblings;
327 } AIOReq;
328
329 enum AIOCBState {
330 AIOCB_WRITE_UDATA,
331 AIOCB_READ_UDATA,
332 AIOCB_FLUSH_CACHE,
333 AIOCB_DISCARD_OBJ,
334 };
335
336 #define AIOCBOverlapping(x, y) \
337 (!(x->max_affect_data_idx < y->min_affect_data_idx \
338 || y->max_affect_data_idx < x->min_affect_data_idx))
339
340 struct SheepdogAIOCB {
341 BDRVSheepdogState *s;
342
343 QEMUIOVector *qiov;
344
345 int64_t sector_num;
346 int nb_sectors;
347
348 int ret;
349 enum AIOCBState aiocb_type;
350
351 Coroutine *coroutine;
352 int nr_pending;
353
354 uint32_t min_affect_data_idx;
355 uint32_t max_affect_data_idx;
356
357 /*
358 * The difference between affect_data_idx and dirty_data_idx:
359 * affect_data_idx represents range of index of all request types.
360 * dirty_data_idx represents range of index updated by COW requests.
361 * dirty_data_idx is used for updating an inode object.
362 */
363 uint32_t min_dirty_data_idx;
364 uint32_t max_dirty_data_idx;
365
366 QLIST_ENTRY(SheepdogAIOCB) aiocb_siblings;
367 };
368
369 struct BDRVSheepdogState {
370 BlockDriverState *bs;
371 AioContext *aio_context;
372
373 SheepdogInode inode;
374
375 char name[SD_MAX_VDI_LEN];
376 bool is_snapshot;
377 uint32_t cache_flags;
378 bool discard_supported;
379
380 SocketAddress *addr;
381 int fd;
382
383 CoMutex lock;
384 Coroutine *co_send;
385 Coroutine *co_recv;
386
387 uint32_t aioreq_seq_num;
388
389 /* Every aio request must be linked to either of these queues. */
390 QLIST_HEAD(inflight_aio_head, AIOReq) inflight_aio_head;
391 QLIST_HEAD(failed_aio_head, AIOReq) failed_aio_head;
392
393 CoQueue overlapping_queue;
394 QLIST_HEAD(inflight_aiocb_head, SheepdogAIOCB) inflight_aiocb_head;
395 };
396
397 typedef struct BDRVSheepdogReopenState {
398 int fd;
399 int cache_flags;
400 } BDRVSheepdogReopenState;
401
402 static const char * sd_strerror(int err)
403 {
404 int i;
405
406 static const struct {
407 int err;
408 const char *desc;
409 } errors[] = {
410 {SD_RES_SUCCESS, "Success"},
411 {SD_RES_UNKNOWN, "Unknown error"},
412 {SD_RES_NO_OBJ, "No object found"},
413 {SD_RES_EIO, "I/O error"},
414 {SD_RES_VDI_EXIST, "VDI exists already"},
415 {SD_RES_INVALID_PARMS, "Invalid parameters"},
416 {SD_RES_SYSTEM_ERROR, "System error"},
417 {SD_RES_VDI_LOCKED, "VDI is already locked"},
418 {SD_RES_NO_VDI, "No vdi found"},
419 {SD_RES_NO_BASE_VDI, "No base VDI found"},
420 {SD_RES_VDI_READ, "Failed read the requested VDI"},
421 {SD_RES_VDI_WRITE, "Failed to write the requested VDI"},
422 {SD_RES_BASE_VDI_READ, "Failed to read the base VDI"},
423 {SD_RES_BASE_VDI_WRITE, "Failed to write the base VDI"},
424 {SD_RES_NO_TAG, "Failed to find the requested tag"},
425 {SD_RES_STARTUP, "The system is still booting"},
426 {SD_RES_VDI_NOT_LOCKED, "VDI isn't locked"},
427 {SD_RES_SHUTDOWN, "The system is shutting down"},
428 {SD_RES_NO_MEM, "Out of memory on the server"},
429 {SD_RES_FULL_VDI, "We already have the maximum vdis"},
430 {SD_RES_VER_MISMATCH, "Protocol version mismatch"},
431 {SD_RES_NO_SPACE, "Server has no space for new objects"},
432 {SD_RES_WAIT_FOR_FORMAT, "Sheepdog is waiting for a format operation"},
433 {SD_RES_WAIT_FOR_JOIN, "Sheepdog is waiting for other nodes joining"},
434 {SD_RES_JOIN_FAILED, "Target node had failed to join sheepdog"},
435 {SD_RES_HALT, "Sheepdog is stopped serving IO request"},
436 {SD_RES_READONLY, "Object is read-only"},
437 };
438
439 for (i = 0; i < ARRAY_SIZE(errors); ++i) {
440 if (errors[i].err == err) {
441 return errors[i].desc;
442 }
443 }
444
445 return "Invalid error code";
446 }
447
448 /*
449 * Sheepdog I/O handling:
450 *
451 * 1. In sd_co_rw_vector, we send the I/O requests to the server and
452 * link the requests to the inflight_list in the
453 * BDRVSheepdogState. The function yields while waiting for
454 * receiving the response.
455 *
456 * 2. We receive the response in aio_read_response, the fd handler to
457 * the sheepdog connection. We switch back to sd_co_readv/sd_writev
458 * after all the requests belonging to the AIOCB are finished. If
459 * needed, sd_co_writev will send another requests for the vdi object.
460 */
461
462 static inline AIOReq *alloc_aio_req(BDRVSheepdogState *s, SheepdogAIOCB *acb,
463 uint64_t oid, unsigned int data_len,
464 uint64_t offset, uint8_t flags, bool create,
465 uint64_t base_oid, unsigned int iov_offset)
466 {
467 AIOReq *aio_req;
468
469 aio_req = g_malloc(sizeof(*aio_req));
470 aio_req->aiocb = acb;
471 aio_req->iov_offset = iov_offset;
472 aio_req->oid = oid;
473 aio_req->base_oid = base_oid;
474 aio_req->offset = offset;
475 aio_req->data_len = data_len;
476 aio_req->flags = flags;
477 aio_req->id = s->aioreq_seq_num++;
478 aio_req->create = create;
479
480 acb->nr_pending++;
481 return aio_req;
482 }
483
484 static void wait_for_overlapping_aiocb(BDRVSheepdogState *s, SheepdogAIOCB *acb)
485 {
486 SheepdogAIOCB *cb;
487
488 retry:
489 QLIST_FOREACH(cb, &s->inflight_aiocb_head, aiocb_siblings) {
490 if (AIOCBOverlapping(acb, cb)) {
491 qemu_co_queue_wait(&s->overlapping_queue, NULL);
492 goto retry;
493 }
494 }
495 }
496
497 static void sd_aio_setup(SheepdogAIOCB *acb, BDRVSheepdogState *s,
498 QEMUIOVector *qiov, int64_t sector_num, int nb_sectors,
499 int type)
500 {
501 uint32_t object_size;
502
503 object_size = (UINT32_C(1) << s->inode.block_size_shift);
504
505 acb->s = s;
506
507 acb->qiov = qiov;
508
509 acb->sector_num = sector_num;
510 acb->nb_sectors = nb_sectors;
511
512 acb->coroutine = qemu_coroutine_self();
513 acb->ret = 0;
514 acb->nr_pending = 0;
515
516 acb->min_affect_data_idx = acb->sector_num * BDRV_SECTOR_SIZE / object_size;
517 acb->max_affect_data_idx = (acb->sector_num * BDRV_SECTOR_SIZE +
518 acb->nb_sectors * BDRV_SECTOR_SIZE) / object_size;
519
520 acb->min_dirty_data_idx = UINT32_MAX;
521 acb->max_dirty_data_idx = 0;
522 acb->aiocb_type = type;
523
524 if (type == AIOCB_FLUSH_CACHE) {
525 return;
526 }
527
528 wait_for_overlapping_aiocb(s, acb);
529 QLIST_INSERT_HEAD(&s->inflight_aiocb_head, acb, aiocb_siblings);
530 }
531
532 static SocketAddress *sd_socket_address(const char *path,
533 const char *host, const char *port)
534 {
535 SocketAddress *addr = g_new0(SocketAddress, 1);
536
537 if (path) {
538 addr->type = SOCKET_ADDRESS_TYPE_UNIX;
539 addr->u.q_unix.path = g_strdup(path);
540 } else {
541 addr->type = SOCKET_ADDRESS_TYPE_INET;
542 addr->u.inet.host = g_strdup(host ?: SD_DEFAULT_ADDR);
543 addr->u.inet.port = g_strdup(port ?: stringify(SD_DEFAULT_PORT));
544 }
545
546 return addr;
547 }
548
549 static SocketAddress *sd_server_config(QDict *options, Error **errp)
550 {
551 QDict *server = NULL;
552 QObject *crumpled_server = NULL;
553 Visitor *iv = NULL;
554 SocketAddress *saddr = NULL;
555 Error *local_err = NULL;
556
557 qdict_extract_subqdict(options, &server, "server.");
558
559 crumpled_server = qdict_crumple(server, errp);
560 if (!crumpled_server) {
561 goto done;
562 }
563
564 /*
565 * FIXME .numeric, .to, .ipv4 or .ipv6 don't work with -drive
566 * server.type=inet. .to doesn't matter, it's ignored anyway.
567 * That's because when @options come from -blockdev or
568 * blockdev_add, members are typed according to the QAPI schema,
569 * but when they come from -drive, they're all QString. The
570 * visitor expects the former.
571 */
572 iv = qobject_input_visitor_new(crumpled_server);
573 visit_type_SocketAddress(iv, NULL, &saddr, &local_err);
574 if (local_err) {
575 error_propagate(errp, local_err);
576 goto done;
577 }
578
579 done:
580 visit_free(iv);
581 qobject_decref(crumpled_server);
582 QDECREF(server);
583 return saddr;
584 }
585
586 /* Return -EIO in case of error, file descriptor on success */
587 static int connect_to_sdog(BDRVSheepdogState *s, Error **errp)
588 {
589 int fd;
590
591 fd = socket_connect(s->addr, NULL, NULL, errp);
592
593 if (s->addr->type == SOCKET_ADDRESS_TYPE_INET && fd >= 0) {
594 int ret = socket_set_nodelay(fd);
595 if (ret < 0) {
596 error_report("%s", strerror(errno));
597 }
598 }
599
600 if (fd >= 0) {
601 qemu_set_nonblock(fd);
602 } else {
603 fd = -EIO;
604 }
605
606 return fd;
607 }
608
609 /* Return 0 on success and -errno in case of error */
610 static coroutine_fn int send_co_req(int sockfd, SheepdogReq *hdr, void *data,
611 unsigned int *wlen)
612 {
613 int ret;
614
615 ret = qemu_co_send(sockfd, hdr, sizeof(*hdr));
616 if (ret != sizeof(*hdr)) {
617 error_report("failed to send a req, %s", strerror(errno));
618 return -errno;
619 }
620
621 ret = qemu_co_send(sockfd, data, *wlen);
622 if (ret != *wlen) {
623 error_report("failed to send a req, %s", strerror(errno));
624 return -errno;
625 }
626
627 return ret;
628 }
629
630 typedef struct SheepdogReqCo {
631 int sockfd;
632 BlockDriverState *bs;
633 AioContext *aio_context;
634 SheepdogReq *hdr;
635 void *data;
636 unsigned int *wlen;
637 unsigned int *rlen;
638 int ret;
639 bool finished;
640 Coroutine *co;
641 } SheepdogReqCo;
642
643 static void restart_co_req(void *opaque)
644 {
645 SheepdogReqCo *srco = opaque;
646
647 aio_co_wake(srco->co);
648 }
649
650 static coroutine_fn void do_co_req(void *opaque)
651 {
652 int ret;
653 SheepdogReqCo *srco = opaque;
654 int sockfd = srco->sockfd;
655 SheepdogReq *hdr = srco->hdr;
656 void *data = srco->data;
657 unsigned int *wlen = srco->wlen;
658 unsigned int *rlen = srco->rlen;
659
660 srco->co = qemu_coroutine_self();
661 aio_set_fd_handler(srco->aio_context, sockfd, false,
662 NULL, restart_co_req, NULL, srco);
663
664 ret = send_co_req(sockfd, hdr, data, wlen);
665 if (ret < 0) {
666 goto out;
667 }
668
669 aio_set_fd_handler(srco->aio_context, sockfd, false,
670 restart_co_req, NULL, NULL, srco);
671
672 ret = qemu_co_recv(sockfd, hdr, sizeof(*hdr));
673 if (ret != sizeof(*hdr)) {
674 error_report("failed to get a rsp, %s", strerror(errno));
675 ret = -errno;
676 goto out;
677 }
678
679 if (*rlen > hdr->data_length) {
680 *rlen = hdr->data_length;
681 }
682
683 if (*rlen) {
684 ret = qemu_co_recv(sockfd, data, *rlen);
685 if (ret != *rlen) {
686 error_report("failed to get the data, %s", strerror(errno));
687 ret = -errno;
688 goto out;
689 }
690 }
691 ret = 0;
692 out:
693 /* there is at most one request for this sockfd, so it is safe to
694 * set each handler to NULL. */
695 aio_set_fd_handler(srco->aio_context, sockfd, false,
696 NULL, NULL, NULL, NULL);
697
698 srco->co = NULL;
699 srco->ret = ret;
700 srco->finished = true;
701 if (srco->bs) {
702 bdrv_wakeup(srco->bs);
703 }
704 }
705
706 /*
707 * Send the request to the sheep in a synchronous manner.
708 *
709 * Return 0 on success, -errno in case of error.
710 */
711 static int do_req(int sockfd, BlockDriverState *bs, SheepdogReq *hdr,
712 void *data, unsigned int *wlen, unsigned int *rlen)
713 {
714 Coroutine *co;
715 SheepdogReqCo srco = {
716 .sockfd = sockfd,
717 .aio_context = bs ? bdrv_get_aio_context(bs) : qemu_get_aio_context(),
718 .bs = bs,
719 .hdr = hdr,
720 .data = data,
721 .wlen = wlen,
722 .rlen = rlen,
723 .ret = 0,
724 .finished = false,
725 };
726
727 if (qemu_in_coroutine()) {
728 do_co_req(&srco);
729 } else {
730 co = qemu_coroutine_create(do_co_req, &srco);
731 if (bs) {
732 bdrv_coroutine_enter(bs, co);
733 BDRV_POLL_WHILE(bs, !srco.finished);
734 } else {
735 qemu_coroutine_enter(co);
736 while (!srco.finished) {
737 aio_poll(qemu_get_aio_context(), true);
738 }
739 }
740 }
741
742 return srco.ret;
743 }
744
745 static void coroutine_fn add_aio_request(BDRVSheepdogState *s, AIOReq *aio_req,
746 struct iovec *iov, int niov,
747 enum AIOCBState aiocb_type);
748 static void coroutine_fn resend_aioreq(BDRVSheepdogState *s, AIOReq *aio_req);
749 static int reload_inode(BDRVSheepdogState *s, uint32_t snapid, const char *tag);
750 static int get_sheep_fd(BDRVSheepdogState *s, Error **errp);
751 static void co_write_request(void *opaque);
752
753 static coroutine_fn void reconnect_to_sdog(void *opaque)
754 {
755 BDRVSheepdogState *s = opaque;
756 AIOReq *aio_req, *next;
757
758 aio_set_fd_handler(s->aio_context, s->fd, false, NULL,
759 NULL, NULL, NULL);
760 close(s->fd);
761 s->fd = -1;
762
763 /* Wait for outstanding write requests to be completed. */
764 while (s->co_send != NULL) {
765 co_write_request(opaque);
766 }
767
768 /* Try to reconnect the sheepdog server every one second. */
769 while (s->fd < 0) {
770 Error *local_err = NULL;
771 s->fd = get_sheep_fd(s, &local_err);
772 if (s->fd < 0) {
773 DPRINTF("Wait for connection to be established\n");
774 error_report_err(local_err);
775 co_aio_sleep_ns(bdrv_get_aio_context(s->bs), QEMU_CLOCK_REALTIME,
776 1000000000ULL);
777 }
778 };
779
780 /*
781 * Now we have to resend all the request in the inflight queue. However,
782 * resend_aioreq() can yield and newly created requests can be added to the
783 * inflight queue before the coroutine is resumed. To avoid mixing them, we
784 * have to move all the inflight requests to the failed queue before
785 * resend_aioreq() is called.
786 */
787 QLIST_FOREACH_SAFE(aio_req, &s->inflight_aio_head, aio_siblings, next) {
788 QLIST_REMOVE(aio_req, aio_siblings);
789 QLIST_INSERT_HEAD(&s->failed_aio_head, aio_req, aio_siblings);
790 }
791
792 /* Resend all the failed aio requests. */
793 while (!QLIST_EMPTY(&s->failed_aio_head)) {
794 aio_req = QLIST_FIRST(&s->failed_aio_head);
795 QLIST_REMOVE(aio_req, aio_siblings);
796 resend_aioreq(s, aio_req);
797 }
798 }
799
800 /*
801 * Receive responses of the I/O requests.
802 *
803 * This function is registered as a fd handler, and called from the
804 * main loop when s->fd is ready for reading responses.
805 */
806 static void coroutine_fn aio_read_response(void *opaque)
807 {
808 SheepdogObjRsp rsp;
809 BDRVSheepdogState *s = opaque;
810 int fd = s->fd;
811 int ret;
812 AIOReq *aio_req = NULL;
813 SheepdogAIOCB *acb;
814 uint64_t idx;
815
816 /* read a header */
817 ret = qemu_co_recv(fd, &rsp, sizeof(rsp));
818 if (ret != sizeof(rsp)) {
819 error_report("failed to get the header, %s", strerror(errno));
820 goto err;
821 }
822
823 /* find the right aio_req from the inflight aio list */
824 QLIST_FOREACH(aio_req, &s->inflight_aio_head, aio_siblings) {
825 if (aio_req->id == rsp.id) {
826 break;
827 }
828 }
829 if (!aio_req) {
830 error_report("cannot find aio_req %x", rsp.id);
831 goto err;
832 }
833
834 acb = aio_req->aiocb;
835
836 switch (acb->aiocb_type) {
837 case AIOCB_WRITE_UDATA:
838 if (!is_data_obj(aio_req->oid)) {
839 break;
840 }
841 idx = data_oid_to_idx(aio_req->oid);
842
843 if (aio_req->create) {
844 /*
845 * If the object is newly created one, we need to update
846 * the vdi object (metadata object). min_dirty_data_idx
847 * and max_dirty_data_idx are changed to include updated
848 * index between them.
849 */
850 if (rsp.result == SD_RES_SUCCESS) {
851 s->inode.data_vdi_id[idx] = s->inode.vdi_id;
852 acb->max_dirty_data_idx = MAX(idx, acb->max_dirty_data_idx);
853 acb->min_dirty_data_idx = MIN(idx, acb->min_dirty_data_idx);
854 }
855 }
856 break;
857 case AIOCB_READ_UDATA:
858 ret = qemu_co_recvv(fd, acb->qiov->iov, acb->qiov->niov,
859 aio_req->iov_offset, rsp.data_length);
860 if (ret != rsp.data_length) {
861 error_report("failed to get the data, %s", strerror(errno));
862 goto err;
863 }
864 break;
865 case AIOCB_FLUSH_CACHE:
866 if (rsp.result == SD_RES_INVALID_PARMS) {
867 DPRINTF("disable cache since the server doesn't support it\n");
868 s->cache_flags = SD_FLAG_CMD_DIRECT;
869 rsp.result = SD_RES_SUCCESS;
870 }
871 break;
872 case AIOCB_DISCARD_OBJ:
873 switch (rsp.result) {
874 case SD_RES_INVALID_PARMS:
875 error_report("server doesn't support discard command");
876 rsp.result = SD_RES_SUCCESS;
877 s->discard_supported = false;
878 break;
879 default:
880 break;
881 }
882 }
883
884 /* No more data for this aio_req (reload_inode below uses its own file
885 * descriptor handler which doesn't use co_recv).
886 */
887 s->co_recv = NULL;
888
889 QLIST_REMOVE(aio_req, aio_siblings);
890 switch (rsp.result) {
891 case SD_RES_SUCCESS:
892 break;
893 case SD_RES_READONLY:
894 if (s->inode.vdi_id == oid_to_vid(aio_req->oid)) {
895 ret = reload_inode(s, 0, "");
896 if (ret < 0) {
897 goto err;
898 }
899 }
900 if (is_data_obj(aio_req->oid)) {
901 aio_req->oid = vid_to_data_oid(s->inode.vdi_id,
902 data_oid_to_idx(aio_req->oid));
903 } else {
904 aio_req->oid = vid_to_vdi_oid(s->inode.vdi_id);
905 }
906 resend_aioreq(s, aio_req);
907 return;
908 default:
909 acb->ret = -EIO;
910 error_report("%s", sd_strerror(rsp.result));
911 break;
912 }
913
914 g_free(aio_req);
915
916 if (!--acb->nr_pending) {
917 /*
918 * We've finished all requests which belong to the AIOCB, so
919 * we can switch back to sd_co_readv/writev now.
920 */
921 aio_co_wake(acb->coroutine);
922 }
923
924 return;
925
926 err:
927 reconnect_to_sdog(opaque);
928 }
929
930 static void co_read_response(void *opaque)
931 {
932 BDRVSheepdogState *s = opaque;
933
934 if (!s->co_recv) {
935 s->co_recv = qemu_coroutine_create(aio_read_response, opaque);
936 }
937
938 aio_co_enter(s->aio_context, s->co_recv);
939 }
940
941 static void co_write_request(void *opaque)
942 {
943 BDRVSheepdogState *s = opaque;
944
945 aio_co_wake(s->co_send);
946 }
947
948 /*
949 * Return a socket descriptor to read/write objects.
950 *
951 * We cannot use this descriptor for other operations because
952 * the block driver may be on waiting response from the server.
953 */
954 static int get_sheep_fd(BDRVSheepdogState *s, Error **errp)
955 {
956 int fd;
957
958 fd = connect_to_sdog(s, errp);
959 if (fd < 0) {
960 return fd;
961 }
962
963 aio_set_fd_handler(s->aio_context, fd, false,
964 co_read_response, NULL, NULL, s);
965 return fd;
966 }
967
968 /*
969 * Parse numeric snapshot ID in @str
970 * If @str can't be parsed as number, return false.
971 * Else, if the number is zero or too large, set *@snapid to zero and
972 * return true.
973 * Else, set *@snapid to the number and return true.
974 */
975 static bool sd_parse_snapid(const char *str, uint32_t *snapid)
976 {
977 unsigned long ul;
978 int ret;
979
980 ret = qemu_strtoul(str, NULL, 10, &ul);
981 if (ret == -ERANGE) {
982 ul = ret = 0;
983 }
984 if (ret) {
985 return false;
986 }
987 if (ul > UINT32_MAX) {
988 ul = 0;
989 }
990
991 *snapid = ul;
992 return true;
993 }
994
995 static bool sd_parse_snapid_or_tag(const char *str,
996 uint32_t *snapid, char tag[])
997 {
998 if (!sd_parse_snapid(str, snapid)) {
999 *snapid = 0;
1000 if (g_strlcpy(tag, str, SD_MAX_VDI_TAG_LEN) >= SD_MAX_VDI_TAG_LEN) {
1001 return false;
1002 }
1003 } else if (!*snapid) {
1004 return false;
1005 } else {
1006 tag[0] = 0;
1007 }
1008 return true;
1009 }
1010
1011 typedef struct {
1012 const char *path; /* non-null iff transport is tcp */
1013 const char *host; /* valid when transport is tcp */
1014 int port; /* valid when transport is tcp */
1015 char vdi[SD_MAX_VDI_LEN];
1016 char tag[SD_MAX_VDI_TAG_LEN];
1017 uint32_t snap_id;
1018 /* Remainder is only for sd_config_done() */
1019 URI *uri;
1020 QueryParams *qp;
1021 } SheepdogConfig;
1022
1023 static void sd_config_done(SheepdogConfig *cfg)
1024 {
1025 if (cfg->qp) {
1026 query_params_free(cfg->qp);
1027 }
1028 uri_free(cfg->uri);
1029 }
1030
1031 static void sd_parse_uri(SheepdogConfig *cfg, const char *filename,
1032 Error **errp)
1033 {
1034 Error *err = NULL;
1035 QueryParams *qp = NULL;
1036 bool is_unix;
1037 URI *uri;
1038
1039 memset(cfg, 0, sizeof(*cfg));
1040
1041 cfg->uri = uri = uri_parse(filename);
1042 if (!uri) {
1043 error_setg(&err, "invalid URI");
1044 goto out;
1045 }
1046
1047 /* transport */
1048 if (!strcmp(uri->scheme, "sheepdog")) {
1049 is_unix = false;
1050 } else if (!strcmp(uri->scheme, "sheepdog+tcp")) {
1051 is_unix = false;
1052 } else if (!strcmp(uri->scheme, "sheepdog+unix")) {
1053 is_unix = true;
1054 } else {
1055 error_setg(&err, "URI scheme must be 'sheepdog', 'sheepdog+tcp',"
1056 " or 'sheepdog+unix'");
1057 goto out;
1058 }
1059
1060 if (uri->path == NULL || !strcmp(uri->path, "/")) {
1061 error_setg(&err, "missing file path in URI");
1062 goto out;
1063 }
1064 if (g_strlcpy(cfg->vdi, uri->path + 1, SD_MAX_VDI_LEN)
1065 >= SD_MAX_VDI_LEN) {
1066 error_setg(&err, "VDI name is too long");
1067 goto out;
1068 }
1069
1070 cfg->qp = qp = query_params_parse(uri->query);
1071
1072 if (is_unix) {
1073 /* sheepdog+unix:///vdiname?socket=path */
1074 if (uri->server || uri->port) {
1075 error_setg(&err, "URI scheme %s doesn't accept a server address",
1076 uri->scheme);
1077 goto out;
1078 }
1079 if (!qp->n) {
1080 error_setg(&err,
1081 "URI scheme %s requires query parameter 'socket'",
1082 uri->scheme);
1083 goto out;
1084 }
1085 if (qp->n != 1 || strcmp(qp->p[0].name, "socket")) {
1086 error_setg(&err, "unexpected query parameters");
1087 goto out;
1088 }
1089 cfg->path = qp->p[0].value;
1090 } else {
1091 /* sheepdog[+tcp]://[host:port]/vdiname */
1092 if (qp->n) {
1093 error_setg(&err, "unexpected query parameters");
1094 goto out;
1095 }
1096 cfg->host = uri->server;
1097 cfg->port = uri->port;
1098 }
1099
1100 /* snapshot tag */
1101 if (uri->fragment) {
1102 if (!sd_parse_snapid_or_tag(uri->fragment,
1103 &cfg->snap_id, cfg->tag)) {
1104 error_setg(&err, "'%s' is not a valid snapshot ID",
1105 uri->fragment);
1106 goto out;
1107 }
1108 } else {
1109 cfg->snap_id = CURRENT_VDI_ID; /* search current vdi */
1110 }
1111
1112 out:
1113 if (err) {
1114 error_propagate(errp, err);
1115 sd_config_done(cfg);
1116 }
1117 }
1118
1119 /*
1120 * Parse a filename (old syntax)
1121 *
1122 * filename must be one of the following formats:
1123 * 1. [vdiname]
1124 * 2. [vdiname]:[snapid]
1125 * 3. [vdiname]:[tag]
1126 * 4. [hostname]:[port]:[vdiname]
1127 * 5. [hostname]:[port]:[vdiname]:[snapid]
1128 * 6. [hostname]:[port]:[vdiname]:[tag]
1129 *
1130 * You can boot from the snapshot images by specifying `snapid` or
1131 * `tag'.
1132 *
1133 * You can run VMs outside the Sheepdog cluster by specifying
1134 * `hostname' and `port' (experimental).
1135 */
1136 static void parse_vdiname(SheepdogConfig *cfg, const char *filename,
1137 Error **errp)
1138 {
1139 Error *err = NULL;
1140 char *p, *q, *uri;
1141 const char *host_spec, *vdi_spec;
1142 int nr_sep;
1143
1144 strstart(filename, "sheepdog:", &filename);
1145 p = q = g_strdup(filename);
1146
1147 /* count the number of separators */
1148 nr_sep = 0;
1149 while (*p) {
1150 if (*p == ':') {
1151 nr_sep++;
1152 }
1153 p++;
1154 }
1155 p = q;
1156
1157 /* use the first two tokens as host_spec. */
1158 if (nr_sep >= 2) {
1159 host_spec = p;
1160 p = strchr(p, ':');
1161 p++;
1162 p = strchr(p, ':');
1163 *p++ = '\0';
1164 } else {
1165 host_spec = "";
1166 }
1167
1168 vdi_spec = p;
1169
1170 p = strchr(vdi_spec, ':');
1171 if (p) {
1172 *p++ = '#';
1173 }
1174
1175 uri = g_strdup_printf("sheepdog://%s/%s", host_spec, vdi_spec);
1176
1177 /*
1178 * FIXME We to escape URI meta-characters, e.g. "x?y=z"
1179 * produces "sheepdog://x?y=z". Because of that ...
1180 */
1181 sd_parse_uri(cfg, uri, &err);
1182 if (err) {
1183 /*
1184 * ... this can fail, but the error message is misleading.
1185 * Replace it by the traditional useless one until the
1186 * escaping is fixed.
1187 */
1188 error_free(err);
1189 error_setg(errp, "Can't parse filename");
1190 }
1191
1192 g_free(q);
1193 g_free(uri);
1194 }
1195
1196 static void sd_parse_filename(const char *filename, QDict *options,
1197 Error **errp)
1198 {
1199 Error *err = NULL;
1200 SheepdogConfig cfg;
1201 char buf[32];
1202
1203 if (strstr(filename, "://")) {
1204 sd_parse_uri(&cfg, filename, &err);
1205 } else {
1206 parse_vdiname(&cfg, filename, &err);
1207 }
1208 if (err) {
1209 error_propagate(errp, err);
1210 return;
1211 }
1212
1213 if (cfg.path) {
1214 qdict_set_default_str(options, "server.path", cfg.path);
1215 qdict_set_default_str(options, "server.type", "unix");
1216 } else {
1217 qdict_set_default_str(options, "server.type", "inet");
1218 qdict_set_default_str(options, "server.host",
1219 cfg.host ?: SD_DEFAULT_ADDR);
1220 snprintf(buf, sizeof(buf), "%d", cfg.port ?: SD_DEFAULT_PORT);
1221 qdict_set_default_str(options, "server.port", buf);
1222 }
1223 qdict_set_default_str(options, "vdi", cfg.vdi);
1224 qdict_set_default_str(options, "tag", cfg.tag);
1225 if (cfg.snap_id) {
1226 snprintf(buf, sizeof(buf), "%d", cfg.snap_id);
1227 qdict_set_default_str(options, "snap-id", buf);
1228 }
1229
1230 sd_config_done(&cfg);
1231 }
1232
1233 static int find_vdi_name(BDRVSheepdogState *s, const char *filename,
1234 uint32_t snapid, const char *tag, uint32_t *vid,
1235 bool lock, Error **errp)
1236 {
1237 int ret, fd;
1238 SheepdogVdiReq hdr;
1239 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
1240 unsigned int wlen, rlen = 0;
1241 char buf[SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN];
1242
1243 fd = connect_to_sdog(s, errp);
1244 if (fd < 0) {
1245 return fd;
1246 }
1247
1248 /* This pair of strncpy calls ensures that the buffer is zero-filled,
1249 * which is desirable since we'll soon be sending those bytes, and
1250 * don't want the send_req to read uninitialized data.
1251 */
1252 strncpy(buf, filename, SD_MAX_VDI_LEN);
1253 strncpy(buf + SD_MAX_VDI_LEN, tag, SD_MAX_VDI_TAG_LEN);
1254
1255 memset(&hdr, 0, sizeof(hdr));
1256 if (lock) {
1257 hdr.opcode = SD_OP_LOCK_VDI;
1258 hdr.type = LOCK_TYPE_NORMAL;
1259 } else {
1260 hdr.opcode = SD_OP_GET_VDI_INFO;
1261 }
1262 wlen = SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN;
1263 hdr.proto_ver = SD_PROTO_VER;
1264 hdr.data_length = wlen;
1265 hdr.snapid = snapid;
1266 hdr.flags = SD_FLAG_CMD_WRITE;
1267
1268 ret = do_req(fd, s->bs, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
1269 if (ret) {
1270 error_setg_errno(errp, -ret, "cannot get vdi info");
1271 goto out;
1272 }
1273
1274 if (rsp->result != SD_RES_SUCCESS) {
1275 error_setg(errp, "cannot get vdi info, %s, %s %" PRIu32 " %s",
1276 sd_strerror(rsp->result), filename, snapid, tag);
1277 if (rsp->result == SD_RES_NO_VDI) {
1278 ret = -ENOENT;
1279 } else if (rsp->result == SD_RES_VDI_LOCKED) {
1280 ret = -EBUSY;
1281 } else {
1282 ret = -EIO;
1283 }
1284 goto out;
1285 }
1286 *vid = rsp->vdi_id;
1287
1288 ret = 0;
1289 out:
1290 closesocket(fd);
1291 return ret;
1292 }
1293
1294 static void coroutine_fn add_aio_request(BDRVSheepdogState *s, AIOReq *aio_req,
1295 struct iovec *iov, int niov,
1296 enum AIOCBState aiocb_type)
1297 {
1298 int nr_copies = s->inode.nr_copies;
1299 SheepdogObjReq hdr;
1300 unsigned int wlen = 0;
1301 int ret;
1302 uint64_t oid = aio_req->oid;
1303 unsigned int datalen = aio_req->data_len;
1304 uint64_t offset = aio_req->offset;
1305 uint8_t flags = aio_req->flags;
1306 uint64_t old_oid = aio_req->base_oid;
1307 bool create = aio_req->create;
1308
1309 QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
1310
1311 if (!nr_copies) {
1312 error_report("bug");
1313 }
1314
1315 memset(&hdr, 0, sizeof(hdr));
1316
1317 switch (aiocb_type) {
1318 case AIOCB_FLUSH_CACHE:
1319 hdr.opcode = SD_OP_FLUSH_VDI;
1320 break;
1321 case AIOCB_READ_UDATA:
1322 hdr.opcode = SD_OP_READ_OBJ;
1323 hdr.flags = flags;
1324 break;
1325 case AIOCB_WRITE_UDATA:
1326 if (create) {
1327 hdr.opcode = SD_OP_CREATE_AND_WRITE_OBJ;
1328 } else {
1329 hdr.opcode = SD_OP_WRITE_OBJ;
1330 }
1331 wlen = datalen;
1332 hdr.flags = SD_FLAG_CMD_WRITE | flags;
1333 break;
1334 case AIOCB_DISCARD_OBJ:
1335 hdr.opcode = SD_OP_WRITE_OBJ;
1336 hdr.flags = SD_FLAG_CMD_WRITE | flags;
1337 s->inode.data_vdi_id[data_oid_to_idx(oid)] = 0;
1338 offset = offsetof(SheepdogInode,
1339 data_vdi_id[data_oid_to_idx(oid)]);
1340 oid = vid_to_vdi_oid(s->inode.vdi_id);
1341 wlen = datalen = sizeof(uint32_t);
1342 break;
1343 }
1344
1345 if (s->cache_flags) {
1346 hdr.flags |= s->cache_flags;
1347 }
1348
1349 hdr.oid = oid;
1350 hdr.cow_oid = old_oid;
1351 hdr.copies = s->inode.nr_copies;
1352
1353 hdr.data_length = datalen;
1354 hdr.offset = offset;
1355
1356 hdr.id = aio_req->id;
1357
1358 qemu_co_mutex_lock(&s->lock);
1359 s->co_send = qemu_coroutine_self();
1360 aio_set_fd_handler(s->aio_context, s->fd, false,
1361 co_read_response, co_write_request, NULL, s);
1362 socket_set_cork(s->fd, 1);
1363
1364 /* send a header */
1365 ret = qemu_co_send(s->fd, &hdr, sizeof(hdr));
1366 if (ret != sizeof(hdr)) {
1367 error_report("failed to send a req, %s", strerror(errno));
1368 goto out;
1369 }
1370
1371 if (wlen) {
1372 ret = qemu_co_sendv(s->fd, iov, niov, aio_req->iov_offset, wlen);
1373 if (ret != wlen) {
1374 error_report("failed to send a data, %s", strerror(errno));
1375 }
1376 }
1377 out:
1378 socket_set_cork(s->fd, 0);
1379 aio_set_fd_handler(s->aio_context, s->fd, false,
1380 co_read_response, NULL, NULL, s);
1381 s->co_send = NULL;
1382 qemu_co_mutex_unlock(&s->lock);
1383 }
1384
1385 static int read_write_object(int fd, BlockDriverState *bs, char *buf,
1386 uint64_t oid, uint8_t copies,
1387 unsigned int datalen, uint64_t offset,
1388 bool write, bool create, uint32_t cache_flags)
1389 {
1390 SheepdogObjReq hdr;
1391 SheepdogObjRsp *rsp = (SheepdogObjRsp *)&hdr;
1392 unsigned int wlen, rlen;
1393 int ret;
1394
1395 memset(&hdr, 0, sizeof(hdr));
1396
1397 if (write) {
1398 wlen = datalen;
1399 rlen = 0;
1400 hdr.flags = SD_FLAG_CMD_WRITE;
1401 if (create) {
1402 hdr.opcode = SD_OP_CREATE_AND_WRITE_OBJ;
1403 } else {
1404 hdr.opcode = SD_OP_WRITE_OBJ;
1405 }
1406 } else {
1407 wlen = 0;
1408 rlen = datalen;
1409 hdr.opcode = SD_OP_READ_OBJ;
1410 }
1411
1412 hdr.flags |= cache_flags;
1413
1414 hdr.oid = oid;
1415 hdr.data_length = datalen;
1416 hdr.offset = offset;
1417 hdr.copies = copies;
1418
1419 ret = do_req(fd, bs, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
1420 if (ret) {
1421 error_report("failed to send a request to the sheep");
1422 return ret;
1423 }
1424
1425 switch (rsp->result) {
1426 case SD_RES_SUCCESS:
1427 return 0;
1428 default:
1429 error_report("%s", sd_strerror(rsp->result));
1430 return -EIO;
1431 }
1432 }
1433
1434 static int read_object(int fd, BlockDriverState *bs, char *buf,
1435 uint64_t oid, uint8_t copies,
1436 unsigned int datalen, uint64_t offset,
1437 uint32_t cache_flags)
1438 {
1439 return read_write_object(fd, bs, buf, oid, copies,
1440 datalen, offset, false,
1441 false, cache_flags);
1442 }
1443
1444 static int write_object(int fd, BlockDriverState *bs, char *buf,
1445 uint64_t oid, uint8_t copies,
1446 unsigned int datalen, uint64_t offset, bool create,
1447 uint32_t cache_flags)
1448 {
1449 return read_write_object(fd, bs, buf, oid, copies,
1450 datalen, offset, true,
1451 create, cache_flags);
1452 }
1453
1454 /* update inode with the latest state */
1455 static int reload_inode(BDRVSheepdogState *s, uint32_t snapid, const char *tag)
1456 {
1457 Error *local_err = NULL;
1458 SheepdogInode *inode;
1459 int ret = 0, fd;
1460 uint32_t vid = 0;
1461
1462 fd = connect_to_sdog(s, &local_err);
1463 if (fd < 0) {
1464 error_report_err(local_err);
1465 return -EIO;
1466 }
1467
1468 inode = g_malloc(SD_INODE_HEADER_SIZE);
1469
1470 ret = find_vdi_name(s, s->name, snapid, tag, &vid, false, &local_err);
1471 if (ret) {
1472 error_report_err(local_err);
1473 goto out;
1474 }
1475
1476 ret = read_object(fd, s->bs, (char *)inode, vid_to_vdi_oid(vid),
1477 s->inode.nr_copies, SD_INODE_HEADER_SIZE, 0,
1478 s->cache_flags);
1479 if (ret < 0) {
1480 goto out;
1481 }
1482
1483 if (inode->vdi_id != s->inode.vdi_id) {
1484 memcpy(&s->inode, inode, SD_INODE_HEADER_SIZE);
1485 }
1486
1487 out:
1488 g_free(inode);
1489 closesocket(fd);
1490
1491 return ret;
1492 }
1493
1494 static void coroutine_fn resend_aioreq(BDRVSheepdogState *s, AIOReq *aio_req)
1495 {
1496 SheepdogAIOCB *acb = aio_req->aiocb;
1497
1498 aio_req->create = false;
1499
1500 /* check whether this request becomes a CoW one */
1501 if (acb->aiocb_type == AIOCB_WRITE_UDATA && is_data_obj(aio_req->oid)) {
1502 int idx = data_oid_to_idx(aio_req->oid);
1503
1504 if (is_data_obj_writable(&s->inode, idx)) {
1505 goto out;
1506 }
1507
1508 if (s->inode.data_vdi_id[idx]) {
1509 aio_req->base_oid = vid_to_data_oid(s->inode.data_vdi_id[idx], idx);
1510 aio_req->flags |= SD_FLAG_CMD_COW;
1511 }
1512 aio_req->create = true;
1513 }
1514 out:
1515 if (is_data_obj(aio_req->oid)) {
1516 add_aio_request(s, aio_req, acb->qiov->iov, acb->qiov->niov,
1517 acb->aiocb_type);
1518 } else {
1519 struct iovec iov;
1520 iov.iov_base = &s->inode;
1521 iov.iov_len = sizeof(s->inode);
1522 add_aio_request(s, aio_req, &iov, 1, AIOCB_WRITE_UDATA);
1523 }
1524 }
1525
1526 static void sd_detach_aio_context(BlockDriverState *bs)
1527 {
1528 BDRVSheepdogState *s = bs->opaque;
1529
1530 aio_set_fd_handler(s->aio_context, s->fd, false, NULL,
1531 NULL, NULL, NULL);
1532 }
1533
1534 static void sd_attach_aio_context(BlockDriverState *bs,
1535 AioContext *new_context)
1536 {
1537 BDRVSheepdogState *s = bs->opaque;
1538
1539 s->aio_context = new_context;
1540 aio_set_fd_handler(new_context, s->fd, false,
1541 co_read_response, NULL, NULL, s);
1542 }
1543
1544 static QemuOptsList runtime_opts = {
1545 .name = "sheepdog",
1546 .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
1547 .desc = {
1548 {
1549 .name = "vdi",
1550 .type = QEMU_OPT_STRING,
1551 },
1552 {
1553 .name = "snap-id",
1554 .type = QEMU_OPT_NUMBER,
1555 },
1556 {
1557 .name = "tag",
1558 .type = QEMU_OPT_STRING,
1559 },
1560 { /* end of list */ }
1561 },
1562 };
1563
1564 static int sd_open(BlockDriverState *bs, QDict *options, int flags,
1565 Error **errp)
1566 {
1567 int ret, fd;
1568 uint32_t vid = 0;
1569 BDRVSheepdogState *s = bs->opaque;
1570 const char *vdi, *snap_id_str, *tag;
1571 uint64_t snap_id;
1572 char *buf = NULL;
1573 QemuOpts *opts;
1574 Error *local_err = NULL;
1575
1576 s->bs = bs;
1577 s->aio_context = bdrv_get_aio_context(bs);
1578
1579 opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
1580 qemu_opts_absorb_qdict(opts, options, &local_err);
1581 if (local_err) {
1582 error_propagate(errp, local_err);
1583 ret = -EINVAL;
1584 goto err_no_fd;
1585 }
1586
1587 s->addr = sd_server_config(options, errp);
1588 if (!s->addr) {
1589 ret = -EINVAL;
1590 goto err_no_fd;
1591 }
1592
1593 vdi = qemu_opt_get(opts, "vdi");
1594 snap_id_str = qemu_opt_get(opts, "snap-id");
1595 snap_id = qemu_opt_get_number(opts, "snap-id", CURRENT_VDI_ID);
1596 tag = qemu_opt_get(opts, "tag");
1597
1598 if (!vdi) {
1599 error_setg(errp, "parameter 'vdi' is missing");
1600 ret = -EINVAL;
1601 goto err_no_fd;
1602 }
1603 if (strlen(vdi) >= SD_MAX_VDI_LEN) {
1604 error_setg(errp, "value of parameter 'vdi' is too long");
1605 ret = -EINVAL;
1606 goto err_no_fd;
1607 }
1608
1609 if (snap_id > UINT32_MAX) {
1610 snap_id = 0;
1611 }
1612 if (snap_id_str && !snap_id) {
1613 error_setg(errp, "'snap-id=%s' is not a valid snapshot ID",
1614 snap_id_str);
1615 ret = -EINVAL;
1616 goto err_no_fd;
1617 }
1618
1619 if (!tag) {
1620 tag = "";
1621 }
1622 if (tag && strlen(tag) >= SD_MAX_VDI_TAG_LEN) {
1623 error_setg(errp, "value of parameter 'tag' is too long");
1624 ret = -EINVAL;
1625 goto err_no_fd;
1626 }
1627
1628 QLIST_INIT(&s->inflight_aio_head);
1629 QLIST_INIT(&s->failed_aio_head);
1630 QLIST_INIT(&s->inflight_aiocb_head);
1631
1632 s->fd = get_sheep_fd(s, errp);
1633 if (s->fd < 0) {
1634 ret = s->fd;
1635 goto err_no_fd;
1636 }
1637
1638 ret = find_vdi_name(s, vdi, (uint32_t)snap_id, tag, &vid, true, errp);
1639 if (ret) {
1640 goto err;
1641 }
1642
1643 /*
1644 * QEMU block layer emulates writethrough cache as 'writeback + flush', so
1645 * we always set SD_FLAG_CMD_CACHE (writeback cache) as default.
1646 */
1647 s->cache_flags = SD_FLAG_CMD_CACHE;
1648 if (flags & BDRV_O_NOCACHE) {
1649 s->cache_flags = SD_FLAG_CMD_DIRECT;
1650 }
1651 s->discard_supported = true;
1652
1653 if (snap_id || tag[0]) {
1654 DPRINTF("%" PRIx32 " snapshot inode was open.\n", vid);
1655 s->is_snapshot = true;
1656 }
1657
1658 fd = connect_to_sdog(s, errp);
1659 if (fd < 0) {
1660 ret = fd;
1661 goto err;
1662 }
1663
1664 buf = g_malloc(SD_INODE_SIZE);
1665 ret = read_object(fd, s->bs, buf, vid_to_vdi_oid(vid),
1666 0, SD_INODE_SIZE, 0, s->cache_flags);
1667
1668 closesocket(fd);
1669
1670 if (ret) {
1671 error_setg(errp, "Can't read snapshot inode");
1672 goto err;
1673 }
1674
1675 memcpy(&s->inode, buf, sizeof(s->inode));
1676
1677 bs->total_sectors = s->inode.vdi_size / BDRV_SECTOR_SIZE;
1678 pstrcpy(s->name, sizeof(s->name), vdi);
1679 qemu_co_mutex_init(&s->lock);
1680 qemu_co_queue_init(&s->overlapping_queue);
1681 qemu_opts_del(opts);
1682 g_free(buf);
1683 return 0;
1684
1685 err:
1686 aio_set_fd_handler(bdrv_get_aio_context(bs), s->fd,
1687 false, NULL, NULL, NULL, NULL);
1688 closesocket(s->fd);
1689 err_no_fd:
1690 qemu_opts_del(opts);
1691 g_free(buf);
1692 return ret;
1693 }
1694
1695 static int sd_reopen_prepare(BDRVReopenState *state, BlockReopenQueue *queue,
1696 Error **errp)
1697 {
1698 BDRVSheepdogState *s = state->bs->opaque;
1699 BDRVSheepdogReopenState *re_s;
1700 int ret = 0;
1701
1702 re_s = state->opaque = g_new0(BDRVSheepdogReopenState, 1);
1703
1704 re_s->cache_flags = SD_FLAG_CMD_CACHE;
1705 if (state->flags & BDRV_O_NOCACHE) {
1706 re_s->cache_flags = SD_FLAG_CMD_DIRECT;
1707 }
1708
1709 re_s->fd = get_sheep_fd(s, errp);
1710 if (re_s->fd < 0) {
1711 ret = re_s->fd;
1712 return ret;
1713 }
1714
1715 return ret;
1716 }
1717
1718 static void sd_reopen_commit(BDRVReopenState *state)
1719 {
1720 BDRVSheepdogReopenState *re_s = state->opaque;
1721 BDRVSheepdogState *s = state->bs->opaque;
1722
1723 if (s->fd) {
1724 aio_set_fd_handler(s->aio_context, s->fd, false,
1725 NULL, NULL, NULL, NULL);
1726 closesocket(s->fd);
1727 }
1728
1729 s->fd = re_s->fd;
1730 s->cache_flags = re_s->cache_flags;
1731
1732 g_free(state->opaque);
1733 state->opaque = NULL;
1734
1735 return;
1736 }
1737
1738 static void sd_reopen_abort(BDRVReopenState *state)
1739 {
1740 BDRVSheepdogReopenState *re_s = state->opaque;
1741 BDRVSheepdogState *s = state->bs->opaque;
1742
1743 if (re_s == NULL) {
1744 return;
1745 }
1746
1747 if (re_s->fd) {
1748 aio_set_fd_handler(s->aio_context, re_s->fd, false,
1749 NULL, NULL, NULL, NULL);
1750 closesocket(re_s->fd);
1751 }
1752
1753 g_free(state->opaque);
1754 state->opaque = NULL;
1755
1756 return;
1757 }
1758
1759 static int do_sd_create(BDRVSheepdogState *s, uint32_t *vdi_id, int snapshot,
1760 Error **errp)
1761 {
1762 SheepdogVdiReq hdr;
1763 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
1764 int fd, ret;
1765 unsigned int wlen, rlen = 0;
1766 char buf[SD_MAX_VDI_LEN];
1767
1768 fd = connect_to_sdog(s, errp);
1769 if (fd < 0) {
1770 return fd;
1771 }
1772
1773 /* FIXME: would it be better to fail (e.g., return -EIO) when filename
1774 * does not fit in buf? For now, just truncate and avoid buffer overrun.
1775 */
1776 memset(buf, 0, sizeof(buf));
1777 pstrcpy(buf, sizeof(buf), s->name);
1778
1779 memset(&hdr, 0, sizeof(hdr));
1780 hdr.opcode = SD_OP_NEW_VDI;
1781 hdr.base_vdi_id = s->inode.vdi_id;
1782
1783 wlen = SD_MAX_VDI_LEN;
1784
1785 hdr.flags = SD_FLAG_CMD_WRITE;
1786 hdr.snapid = snapshot;
1787
1788 hdr.data_length = wlen;
1789 hdr.vdi_size = s->inode.vdi_size;
1790 hdr.copy_policy = s->inode.copy_policy;
1791 hdr.copies = s->inode.nr_copies;
1792 hdr.block_size_shift = s->inode.block_size_shift;
1793
1794 ret = do_req(fd, NULL, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
1795
1796 closesocket(fd);
1797
1798 if (ret) {
1799 error_setg_errno(errp, -ret, "create failed");
1800 return ret;
1801 }
1802
1803 if (rsp->result != SD_RES_SUCCESS) {
1804 error_setg(errp, "%s, %s", sd_strerror(rsp->result), s->inode.name);
1805 return -EIO;
1806 }
1807
1808 if (vdi_id) {
1809 *vdi_id = rsp->vdi_id;
1810 }
1811
1812 return 0;
1813 }
1814
1815 static int sd_prealloc(const char *filename, Error **errp)
1816 {
1817 BlockBackend *blk = NULL;
1818 BDRVSheepdogState *base = NULL;
1819 unsigned long buf_size;
1820 uint32_t idx, max_idx;
1821 uint32_t object_size;
1822 int64_t vdi_size;
1823 void *buf = NULL;
1824 int ret;
1825
1826 blk = blk_new_open(filename, NULL, NULL,
1827 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL, errp);
1828 if (blk == NULL) {
1829 ret = -EIO;
1830 goto out_with_err_set;
1831 }
1832
1833 blk_set_allow_write_beyond_eof(blk, true);
1834
1835 vdi_size = blk_getlength(blk);
1836 if (vdi_size < 0) {
1837 ret = vdi_size;
1838 goto out;
1839 }
1840
1841 base = blk_bs(blk)->opaque;
1842 object_size = (UINT32_C(1) << base->inode.block_size_shift);
1843 buf_size = MIN(object_size, SD_DATA_OBJ_SIZE);
1844 buf = g_malloc0(buf_size);
1845
1846 max_idx = DIV_ROUND_UP(vdi_size, buf_size);
1847
1848 for (idx = 0; idx < max_idx; idx++) {
1849 /*
1850 * The created image can be a cloned image, so we need to read
1851 * a data from the source image.
1852 */
1853 ret = blk_pread(blk, idx * buf_size, buf, buf_size);
1854 if (ret < 0) {
1855 goto out;
1856 }
1857 ret = blk_pwrite(blk, idx * buf_size, buf, buf_size, 0);
1858 if (ret < 0) {
1859 goto out;
1860 }
1861 }
1862
1863 ret = 0;
1864 out:
1865 if (ret < 0) {
1866 error_setg_errno(errp, -ret, "Can't pre-allocate");
1867 }
1868 out_with_err_set:
1869 if (blk) {
1870 blk_unref(blk);
1871 }
1872 g_free(buf);
1873
1874 return ret;
1875 }
1876
1877 /*
1878 * Sheepdog support two kinds of redundancy, full replication and erasure
1879 * coding.
1880 *
1881 * # create a fully replicated vdi with x copies
1882 * -o redundancy=x (1 <= x <= SD_MAX_COPIES)
1883 *
1884 * # create a erasure coded vdi with x data strips and y parity strips
1885 * -o redundancy=x:y (x must be one of {2,4,8,16} and 1 <= y < SD_EC_MAX_STRIP)
1886 */
1887 static int parse_redundancy(BDRVSheepdogState *s, const char *opt)
1888 {
1889 struct SheepdogInode *inode = &s->inode;
1890 const char *n1, *n2;
1891 long copy, parity;
1892 char p[10];
1893
1894 pstrcpy(p, sizeof(p), opt);
1895 n1 = strtok(p, ":");
1896 n2 = strtok(NULL, ":");
1897
1898 if (!n1) {
1899 return -EINVAL;
1900 }
1901
1902 copy = strtol(n1, NULL, 10);
1903 /* FIXME fix error checking by switching to qemu_strtol() */
1904 if (copy > SD_MAX_COPIES || copy < 1) {
1905 return -EINVAL;
1906 }
1907 if (!n2) {
1908 inode->copy_policy = 0;
1909 inode->nr_copies = copy;
1910 return 0;
1911 }
1912
1913 if (copy != 2 && copy != 4 && copy != 8 && copy != 16) {
1914 return -EINVAL;
1915 }
1916
1917 parity = strtol(n2, NULL, 10);
1918 /* FIXME fix error checking by switching to qemu_strtol() */
1919 if (parity >= SD_EC_MAX_STRIP || parity < 1) {
1920 return -EINVAL;
1921 }
1922
1923 /*
1924 * 4 bits for parity and 4 bits for data.
1925 * We have to compress upper data bits because it can't represent 16
1926 */
1927 inode->copy_policy = ((copy / 2) << 4) + parity;
1928 inode->nr_copies = copy + parity;
1929
1930 return 0;
1931 }
1932
1933 static int parse_block_size_shift(BDRVSheepdogState *s, QemuOpts *opt)
1934 {
1935 struct SheepdogInode *inode = &s->inode;
1936 uint64_t object_size;
1937 int obj_order;
1938
1939 object_size = qemu_opt_get_size_del(opt, BLOCK_OPT_OBJECT_SIZE, 0);
1940 if (object_size) {
1941 if ((object_size - 1) & object_size) { /* not a power of 2? */
1942 return -EINVAL;
1943 }
1944 obj_order = ctz32(object_size);
1945 if (obj_order < 20 || obj_order > 31) {
1946 return -EINVAL;
1947 }
1948 inode->block_size_shift = (uint8_t)obj_order;
1949 }
1950
1951 return 0;
1952 }
1953
1954 static int sd_create(const char *filename, QemuOpts *opts,
1955 Error **errp)
1956 {
1957 Error *err = NULL;
1958 int ret = 0;
1959 uint32_t vid = 0;
1960 char *backing_file = NULL;
1961 char *buf = NULL;
1962 BDRVSheepdogState *s;
1963 SheepdogConfig cfg;
1964 uint64_t max_vdi_size;
1965 bool prealloc = false;
1966
1967 s = g_new0(BDRVSheepdogState, 1);
1968
1969 if (strstr(filename, "://")) {
1970 sd_parse_uri(&cfg, filename, &err);
1971 } else {
1972 parse_vdiname(&cfg, filename, &err);
1973 }
1974 if (err) {
1975 error_propagate(errp, err);
1976 goto out;
1977 }
1978
1979 buf = cfg.port ? g_strdup_printf("%d", cfg.port) : NULL;
1980 s->addr = sd_socket_address(cfg.path, cfg.host, buf);
1981 g_free(buf);
1982 strcpy(s->name, cfg.vdi);
1983 sd_config_done(&cfg);
1984
1985 s->inode.vdi_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
1986 BDRV_SECTOR_SIZE);
1987 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
1988 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
1989 if (!buf || !strcmp(buf, "off")) {
1990 prealloc = false;
1991 } else if (!strcmp(buf, "full")) {
1992 prealloc = true;
1993 } else {
1994 error_setg(errp, "Invalid preallocation mode: '%s'", buf);
1995 ret = -EINVAL;
1996 goto out;
1997 }
1998
1999 g_free(buf);
2000 buf = qemu_opt_get_del(opts, BLOCK_OPT_REDUNDANCY);
2001 if (buf) {
2002 ret = parse_redundancy(s, buf);
2003 if (ret < 0) {
2004 error_setg(errp, "Invalid redundancy mode: '%s'", buf);
2005 goto out;
2006 }
2007 }
2008 ret = parse_block_size_shift(s, opts);
2009 if (ret < 0) {
2010 error_setg(errp, "Invalid object_size."
2011 " obect_size needs to be power of 2"
2012 " and be limited from 2^20 to 2^31");
2013 goto out;
2014 }
2015
2016 if (backing_file) {
2017 BlockBackend *blk;
2018 BDRVSheepdogState *base;
2019 BlockDriver *drv;
2020
2021 /* Currently, only Sheepdog backing image is supported. */
2022 drv = bdrv_find_protocol(backing_file, true, NULL);
2023 if (!drv || strcmp(drv->protocol_name, "sheepdog") != 0) {
2024 error_setg(errp, "backing_file must be a sheepdog image");
2025 ret = -EINVAL;
2026 goto out;
2027 }
2028
2029 blk = blk_new_open(backing_file, NULL, NULL,
2030 BDRV_O_PROTOCOL, errp);
2031 if (blk == NULL) {
2032 ret = -EIO;
2033 goto out;
2034 }
2035
2036 base = blk_bs(blk)->opaque;
2037
2038 if (!is_snapshot(&base->inode)) {
2039 error_setg(errp, "cannot clone from a non snapshot vdi");
2040 blk_unref(blk);
2041 ret = -EINVAL;
2042 goto out;
2043 }
2044 s->inode.vdi_id = base->inode.vdi_id;
2045 blk_unref(blk);
2046 }
2047
2048 s->aio_context = qemu_get_aio_context();
2049
2050 /* if block_size_shift is not specified, get cluster default value */
2051 if (s->inode.block_size_shift == 0) {
2052 SheepdogVdiReq hdr;
2053 SheepdogClusterRsp *rsp = (SheepdogClusterRsp *)&hdr;
2054 int fd;
2055 unsigned int wlen = 0, rlen = 0;
2056
2057 fd = connect_to_sdog(s, errp);
2058 if (fd < 0) {
2059 ret = fd;
2060 goto out;
2061 }
2062
2063 memset(&hdr, 0, sizeof(hdr));
2064 hdr.opcode = SD_OP_GET_CLUSTER_DEFAULT;
2065 hdr.proto_ver = SD_PROTO_VER;
2066
2067 ret = do_req(fd, NULL, (SheepdogReq *)&hdr,
2068 NULL, &wlen, &rlen);
2069 closesocket(fd);
2070 if (ret) {
2071 error_setg_errno(errp, -ret, "failed to get cluster default");
2072 goto out;
2073 }
2074 if (rsp->result == SD_RES_SUCCESS) {
2075 s->inode.block_size_shift = rsp->block_size_shift;
2076 } else {
2077 s->inode.block_size_shift = SD_DEFAULT_BLOCK_SIZE_SHIFT;
2078 }
2079 }
2080
2081 max_vdi_size = (UINT64_C(1) << s->inode.block_size_shift) * MAX_DATA_OBJS;
2082
2083 if (s->inode.vdi_size > max_vdi_size) {
2084 error_setg(errp, "An image is too large."
2085 " The maximum image size is %"PRIu64 "GB",
2086 max_vdi_size / 1024 / 1024 / 1024);
2087 ret = -EINVAL;
2088 goto out;
2089 }
2090
2091 ret = do_sd_create(s, &vid, 0, errp);
2092 if (ret) {
2093 goto out;
2094 }
2095
2096 if (prealloc) {
2097 ret = sd_prealloc(filename, errp);
2098 }
2099 out:
2100 g_free(backing_file);
2101 g_free(buf);
2102 g_free(s);
2103 return ret;
2104 }
2105
2106 static void sd_close(BlockDriverState *bs)
2107 {
2108 Error *local_err = NULL;
2109 BDRVSheepdogState *s = bs->opaque;
2110 SheepdogVdiReq hdr;
2111 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
2112 unsigned int wlen, rlen = 0;
2113 int fd, ret;
2114
2115 DPRINTF("%s\n", s->name);
2116
2117 fd = connect_to_sdog(s, &local_err);
2118 if (fd < 0) {
2119 error_report_err(local_err);
2120 return;
2121 }
2122
2123 memset(&hdr, 0, sizeof(hdr));
2124
2125 hdr.opcode = SD_OP_RELEASE_VDI;
2126 hdr.type = LOCK_TYPE_NORMAL;
2127 hdr.base_vdi_id = s->inode.vdi_id;
2128 wlen = strlen(s->name) + 1;
2129 hdr.data_length = wlen;
2130 hdr.flags = SD_FLAG_CMD_WRITE;
2131
2132 ret = do_req(fd, s->bs, (SheepdogReq *)&hdr,
2133 s->name, &wlen, &rlen);
2134
2135 closesocket(fd);
2136
2137 if (!ret && rsp->result != SD_RES_SUCCESS &&
2138 rsp->result != SD_RES_VDI_NOT_LOCKED) {
2139 error_report("%s, %s", sd_strerror(rsp->result), s->name);
2140 }
2141
2142 aio_set_fd_handler(bdrv_get_aio_context(bs), s->fd,
2143 false, NULL, NULL, NULL, NULL);
2144 closesocket(s->fd);
2145 qapi_free_SocketAddress(s->addr);
2146 }
2147
2148 static int64_t sd_getlength(BlockDriverState *bs)
2149 {
2150 BDRVSheepdogState *s = bs->opaque;
2151
2152 return s->inode.vdi_size;
2153 }
2154
2155 static int sd_truncate(BlockDriverState *bs, int64_t offset, Error **errp)
2156 {
2157 BDRVSheepdogState *s = bs->opaque;
2158 int ret, fd;
2159 unsigned int datalen;
2160 uint64_t max_vdi_size;
2161
2162 max_vdi_size = (UINT64_C(1) << s->inode.block_size_shift) * MAX_DATA_OBJS;
2163 if (offset < s->inode.vdi_size) {
2164 error_setg(errp, "shrinking is not supported");
2165 return -EINVAL;
2166 } else if (offset > max_vdi_size) {
2167 error_setg(errp, "too big image size");
2168 return -EINVAL;
2169 }
2170
2171 fd = connect_to_sdog(s, errp);
2172 if (fd < 0) {
2173 return fd;
2174 }
2175
2176 /* we don't need to update entire object */
2177 datalen = SD_INODE_SIZE - sizeof(s->inode.data_vdi_id);
2178 s->inode.vdi_size = offset;
2179 ret = write_object(fd, s->bs, (char *)&s->inode,
2180 vid_to_vdi_oid(s->inode.vdi_id), s->inode.nr_copies,
2181 datalen, 0, false, s->cache_flags);
2182 close(fd);
2183
2184 if (ret < 0) {
2185 error_setg_errno(errp, -ret, "failed to update an inode");
2186 }
2187
2188 return ret;
2189 }
2190
2191 /*
2192 * This function is called after writing data objects. If we need to
2193 * update metadata, this sends a write request to the vdi object.
2194 */
2195 static void coroutine_fn sd_write_done(SheepdogAIOCB *acb)
2196 {
2197 BDRVSheepdogState *s = acb->s;
2198 struct iovec iov;
2199 AIOReq *aio_req;
2200 uint32_t offset, data_len, mn, mx;
2201
2202 mn = acb->min_dirty_data_idx;
2203 mx = acb->max_dirty_data_idx;
2204 if (mn <= mx) {
2205 /* we need to update the vdi object. */
2206 ++acb->nr_pending;
2207 offset = sizeof(s->inode) - sizeof(s->inode.data_vdi_id) +
2208 mn * sizeof(s->inode.data_vdi_id[0]);
2209 data_len = (mx - mn + 1) * sizeof(s->inode.data_vdi_id[0]);
2210
2211 acb->min_dirty_data_idx = UINT32_MAX;
2212 acb->max_dirty_data_idx = 0;
2213
2214 iov.iov_base = &s->inode;
2215 iov.iov_len = sizeof(s->inode);
2216 aio_req = alloc_aio_req(s, acb, vid_to_vdi_oid(s->inode.vdi_id),
2217 data_len, offset, 0, false, 0, offset);
2218 add_aio_request(s, aio_req, &iov, 1, AIOCB_WRITE_UDATA);
2219 if (--acb->nr_pending) {
2220 qemu_coroutine_yield();
2221 }
2222 }
2223 }
2224
2225 /* Delete current working VDI on the snapshot chain */
2226 static bool sd_delete(BDRVSheepdogState *s)
2227 {
2228 Error *local_err = NULL;
2229 unsigned int wlen = SD_MAX_VDI_LEN, rlen = 0;
2230 SheepdogVdiReq hdr = {
2231 .opcode = SD_OP_DEL_VDI,
2232 .base_vdi_id = s->inode.vdi_id,
2233 .data_length = wlen,
2234 .flags = SD_FLAG_CMD_WRITE,
2235 };
2236 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
2237 int fd, ret;
2238
2239 fd = connect_to_sdog(s, &local_err);
2240 if (fd < 0) {
2241 error_report_err(local_err);
2242 return false;
2243 }
2244
2245 ret = do_req(fd, s->bs, (SheepdogReq *)&hdr,
2246 s->name, &wlen, &rlen);
2247 closesocket(fd);
2248 if (ret) {
2249 return false;
2250 }
2251 switch (rsp->result) {
2252 case SD_RES_NO_VDI:
2253 error_report("%s was already deleted", s->name);
2254 /* fall through */
2255 case SD_RES_SUCCESS:
2256 break;
2257 default:
2258 error_report("%s, %s", sd_strerror(rsp->result), s->name);
2259 return false;
2260 }
2261
2262 return true;
2263 }
2264
2265 /*
2266 * Create a writable VDI from a snapshot
2267 */
2268 static int sd_create_branch(BDRVSheepdogState *s)
2269 {
2270 Error *local_err = NULL;
2271 int ret, fd;
2272 uint32_t vid;
2273 char *buf;
2274 bool deleted;
2275
2276 DPRINTF("%" PRIx32 " is snapshot.\n", s->inode.vdi_id);
2277
2278 buf = g_malloc(SD_INODE_SIZE);
2279
2280 /*
2281 * Even If deletion fails, we will just create extra snapshot based on
2282 * the working VDI which was supposed to be deleted. So no need to
2283 * false bail out.
2284 */
2285 deleted = sd_delete(s);
2286 ret = do_sd_create(s, &vid, !deleted, &local_err);
2287 if (ret) {
2288 error_report_err(local_err);
2289 goto out;
2290 }
2291
2292 DPRINTF("%" PRIx32 " is created.\n", vid);
2293
2294 fd = connect_to_sdog(s, &local_err);
2295 if (fd < 0) {
2296 error_report_err(local_err);
2297 ret = fd;
2298 goto out;
2299 }
2300
2301 ret = read_object(fd, s->bs, buf, vid_to_vdi_oid(vid),
2302 s->inode.nr_copies, SD_INODE_SIZE, 0, s->cache_flags);
2303
2304 closesocket(fd);
2305
2306 if (ret < 0) {
2307 goto out;
2308 }
2309
2310 memcpy(&s->inode, buf, sizeof(s->inode));
2311
2312 s->is_snapshot = false;
2313 ret = 0;
2314 DPRINTF("%" PRIx32 " was newly created.\n", s->inode.vdi_id);
2315
2316 out:
2317 g_free(buf);
2318
2319 return ret;
2320 }
2321
2322 /*
2323 * Send I/O requests to the server.
2324 *
2325 * This function sends requests to the server, links the requests to
2326 * the inflight_list in BDRVSheepdogState, and exits without
2327 * waiting the response. The responses are received in the
2328 * `aio_read_response' function which is called from the main loop as
2329 * a fd handler.
2330 *
2331 * Returns 1 when we need to wait a response, 0 when there is no sent
2332 * request and -errno in error cases.
2333 */
2334 static void coroutine_fn sd_co_rw_vector(SheepdogAIOCB *acb)
2335 {
2336 int ret = 0;
2337 unsigned long len, done = 0, total = acb->nb_sectors * BDRV_SECTOR_SIZE;
2338 unsigned long idx;
2339 uint32_t object_size;
2340 uint64_t oid;
2341 uint64_t offset;
2342 BDRVSheepdogState *s = acb->s;
2343 SheepdogInode *inode = &s->inode;
2344 AIOReq *aio_req;
2345
2346 if (acb->aiocb_type == AIOCB_WRITE_UDATA && s->is_snapshot) {
2347 /*
2348 * In the case we open the snapshot VDI, Sheepdog creates the
2349 * writable VDI when we do a write operation first.
2350 */
2351 ret = sd_create_branch(s);
2352 if (ret) {
2353 acb->ret = -EIO;
2354 return;
2355 }
2356 }
2357
2358 object_size = (UINT32_C(1) << inode->block_size_shift);
2359 idx = acb->sector_num * BDRV_SECTOR_SIZE / object_size;
2360 offset = (acb->sector_num * BDRV_SECTOR_SIZE) % object_size;
2361
2362 /*
2363 * Make sure we don't free the aiocb before we are done with all requests.
2364 * This additional reference is dropped at the end of this function.
2365 */
2366 acb->nr_pending++;
2367
2368 while (done != total) {
2369 uint8_t flags = 0;
2370 uint64_t old_oid = 0;
2371 bool create = false;
2372
2373 oid = vid_to_data_oid(inode->data_vdi_id[idx], idx);
2374
2375 len = MIN(total - done, object_size - offset);
2376
2377 switch (acb->aiocb_type) {
2378 case AIOCB_READ_UDATA:
2379 if (!inode->data_vdi_id[idx]) {
2380 qemu_iovec_memset(acb->qiov, done, 0, len);
2381 goto done;
2382 }
2383 break;
2384 case AIOCB_WRITE_UDATA:
2385 if (!inode->data_vdi_id[idx]) {
2386 create = true;
2387 } else if (!is_data_obj_writable(inode, idx)) {
2388 /* Copy-On-Write */
2389 create = true;
2390 old_oid = oid;
2391 flags = SD_FLAG_CMD_COW;
2392 }
2393 break;
2394 case AIOCB_DISCARD_OBJ:
2395 /*
2396 * We discard the object only when the whole object is
2397 * 1) allocated 2) trimmed. Otherwise, simply skip it.
2398 */
2399 if (len != object_size || inode->data_vdi_id[idx] == 0) {
2400 goto done;
2401 }
2402 break;
2403 default:
2404 break;
2405 }
2406
2407 if (create) {
2408 DPRINTF("update ino (%" PRIu32 ") %" PRIu64 " %" PRIu64 " %ld\n",
2409 inode->vdi_id, oid,
2410 vid_to_data_oid(inode->data_vdi_id[idx], idx), idx);
2411 oid = vid_to_data_oid(inode->vdi_id, idx);
2412 DPRINTF("new oid %" PRIx64 "\n", oid);
2413 }
2414
2415 aio_req = alloc_aio_req(s, acb, oid, len, offset, flags, create,
2416 old_oid,
2417 acb->aiocb_type == AIOCB_DISCARD_OBJ ?
2418 0 : done);
2419 add_aio_request(s, aio_req, acb->qiov->iov, acb->qiov->niov,
2420 acb->aiocb_type);
2421 done:
2422 offset = 0;
2423 idx++;
2424 done += len;
2425 }
2426 if (--acb->nr_pending) {
2427 qemu_coroutine_yield();
2428 }
2429 }
2430
2431 static void sd_aio_complete(SheepdogAIOCB *acb)
2432 {
2433 if (acb->aiocb_type == AIOCB_FLUSH_CACHE) {
2434 return;
2435 }
2436
2437 QLIST_REMOVE(acb, aiocb_siblings);
2438 qemu_co_queue_restart_all(&acb->s->overlapping_queue);
2439 }
2440
2441 static coroutine_fn int sd_co_writev(BlockDriverState *bs, int64_t sector_num,
2442 int nb_sectors, QEMUIOVector *qiov)
2443 {
2444 SheepdogAIOCB acb;
2445 int ret;
2446 int64_t offset = (sector_num + nb_sectors) * BDRV_SECTOR_SIZE;
2447 BDRVSheepdogState *s = bs->opaque;
2448
2449 if (offset > s->inode.vdi_size) {
2450 ret = sd_truncate(bs, offset, NULL);
2451 if (ret < 0) {
2452 return ret;
2453 }
2454 }
2455
2456 sd_aio_setup(&acb, s, qiov, sector_num, nb_sectors, AIOCB_WRITE_UDATA);
2457 sd_co_rw_vector(&acb);
2458 sd_write_done(&acb);
2459 sd_aio_complete(&acb);
2460
2461 return acb.ret;
2462 }
2463
2464 static coroutine_fn int sd_co_readv(BlockDriverState *bs, int64_t sector_num,
2465 int nb_sectors, QEMUIOVector *qiov)
2466 {
2467 SheepdogAIOCB acb;
2468 BDRVSheepdogState *s = bs->opaque;
2469
2470 sd_aio_setup(&acb, s, qiov, sector_num, nb_sectors, AIOCB_READ_UDATA);
2471 sd_co_rw_vector(&acb);
2472 sd_aio_complete(&acb);
2473
2474 return acb.ret;
2475 }
2476
2477 static int coroutine_fn sd_co_flush_to_disk(BlockDriverState *bs)
2478 {
2479 BDRVSheepdogState *s = bs->opaque;
2480 SheepdogAIOCB acb;
2481 AIOReq *aio_req;
2482
2483 if (s->cache_flags != SD_FLAG_CMD_CACHE) {
2484 return 0;
2485 }
2486
2487 sd_aio_setup(&acb, s, NULL, 0, 0, AIOCB_FLUSH_CACHE);
2488
2489 acb.nr_pending++;
2490 aio_req = alloc_aio_req(s, &acb, vid_to_vdi_oid(s->inode.vdi_id),
2491 0, 0, 0, false, 0, 0);
2492 add_aio_request(s, aio_req, NULL, 0, acb.aiocb_type);
2493
2494 if (--acb.nr_pending) {
2495 qemu_coroutine_yield();
2496 }
2497
2498 sd_aio_complete(&acb);
2499 return acb.ret;
2500 }
2501
2502 static int sd_snapshot_create(BlockDriverState *bs, QEMUSnapshotInfo *sn_info)
2503 {
2504 Error *local_err = NULL;
2505 BDRVSheepdogState *s = bs->opaque;
2506 int ret, fd;
2507 uint32_t new_vid;
2508 SheepdogInode *inode;
2509 unsigned int datalen;
2510
2511 DPRINTF("sn_info: name %s id_str %s s: name %s vm_state_size %" PRId64 " "
2512 "is_snapshot %d\n", sn_info->name, sn_info->id_str,
2513 s->name, sn_info->vm_state_size, s->is_snapshot);
2514
2515 if (s->is_snapshot) {
2516 error_report("You can't create a snapshot of a snapshot VDI, "
2517 "%s (%" PRIu32 ").", s->name, s->inode.vdi_id);
2518
2519 return -EINVAL;
2520 }
2521
2522 DPRINTF("%s %s\n", sn_info->name, sn_info->id_str);
2523
2524 s->inode.vm_state_size = sn_info->vm_state_size;
2525 s->inode.vm_clock_nsec = sn_info->vm_clock_nsec;
2526 /* It appears that inode.tag does not require a NUL terminator,
2527 * which means this use of strncpy is ok.
2528 */
2529 strncpy(s->inode.tag, sn_info->name, sizeof(s->inode.tag));
2530 /* we don't need to update entire object */
2531 datalen = SD_INODE_SIZE - sizeof(s->inode.data_vdi_id);
2532 inode = g_malloc(datalen);
2533
2534 /* refresh inode. */
2535 fd = connect_to_sdog(s, &local_err);
2536 if (fd < 0) {
2537 error_report_err(local_err);
2538 ret = fd;
2539 goto cleanup;
2540 }
2541
2542 ret = write_object(fd, s->bs, (char *)&s->inode,
2543 vid_to_vdi_oid(s->inode.vdi_id), s->inode.nr_copies,
2544 datalen, 0, false, s->cache_flags);
2545 if (ret < 0) {
2546 error_report("failed to write snapshot's inode.");
2547 goto cleanup;
2548 }
2549
2550 ret = do_sd_create(s, &new_vid, 1, &local_err);
2551 if (ret < 0) {
2552 error_reportf_err(local_err,
2553 "failed to create inode for snapshot: ");
2554 goto cleanup;
2555 }
2556
2557 ret = read_object(fd, s->bs, (char *)inode,
2558 vid_to_vdi_oid(new_vid), s->inode.nr_copies, datalen, 0,
2559 s->cache_flags);
2560
2561 if (ret < 0) {
2562 error_report("failed to read new inode info. %s", strerror(errno));
2563 goto cleanup;
2564 }
2565
2566 memcpy(&s->inode, inode, datalen);
2567 DPRINTF("s->inode: name %s snap_id %x oid %x\n",
2568 s->inode.name, s->inode.snap_id, s->inode.vdi_id);
2569
2570 cleanup:
2571 g_free(inode);
2572 closesocket(fd);
2573 return ret;
2574 }
2575
2576 /*
2577 * We implement rollback(loadvm) operation to the specified snapshot by
2578 * 1) switch to the snapshot
2579 * 2) rely on sd_create_branch to delete working VDI and
2580 * 3) create a new working VDI based on the specified snapshot
2581 */
2582 static int sd_snapshot_goto(BlockDriverState *bs, const char *snapshot_id)
2583 {
2584 BDRVSheepdogState *s = bs->opaque;
2585 BDRVSheepdogState *old_s;
2586 char tag[SD_MAX_VDI_TAG_LEN];
2587 uint32_t snapid = 0;
2588 int ret;
2589
2590 if (!sd_parse_snapid_or_tag(snapshot_id, &snapid, tag)) {
2591 return -EINVAL;
2592 }
2593
2594 old_s = g_new(BDRVSheepdogState, 1);
2595
2596 memcpy(old_s, s, sizeof(BDRVSheepdogState));
2597
2598 ret = reload_inode(s, snapid, tag);
2599 if (ret) {
2600 goto out;
2601 }
2602
2603 ret = sd_create_branch(s);
2604 if (ret) {
2605 goto out;
2606 }
2607
2608 g_free(old_s);
2609
2610 return 0;
2611 out:
2612 /* recover bdrv_sd_state */
2613 memcpy(s, old_s, sizeof(BDRVSheepdogState));
2614 g_free(old_s);
2615
2616 error_report("failed to open. recover old bdrv_sd_state.");
2617
2618 return ret;
2619 }
2620
2621 #define NR_BATCHED_DISCARD 128
2622
2623 static int remove_objects(BDRVSheepdogState *s, Error **errp)
2624 {
2625 int fd, i = 0, nr_objs = 0;
2626 int ret;
2627 SheepdogInode *inode = &s->inode;
2628
2629 fd = connect_to_sdog(s, errp);
2630 if (fd < 0) {
2631 return fd;
2632 }
2633
2634 nr_objs = count_data_objs(inode);
2635 while (i < nr_objs) {
2636 int start_idx, nr_filled_idx;
2637
2638 while (i < nr_objs && !inode->data_vdi_id[i]) {
2639 i++;
2640 }
2641 start_idx = i;
2642
2643 nr_filled_idx = 0;
2644 while (i < nr_objs && nr_filled_idx < NR_BATCHED_DISCARD) {
2645 if (inode->data_vdi_id[i]) {
2646 inode->data_vdi_id[i] = 0;
2647 nr_filled_idx++;
2648 }
2649
2650 i++;
2651 }
2652
2653 ret = write_object(fd, s->bs,
2654 (char *)&inode->data_vdi_id[start_idx],
2655 vid_to_vdi_oid(s->inode.vdi_id), inode->nr_copies,
2656 (i - start_idx) * sizeof(uint32_t),
2657 offsetof(struct SheepdogInode,
2658 data_vdi_id[start_idx]),
2659 false, s->cache_flags);
2660 if (ret < 0) {
2661 error_setg(errp, "Failed to discard snapshot inode");
2662 goto out;
2663 }
2664 }
2665
2666 ret = 0;
2667 out:
2668 closesocket(fd);
2669 return ret;
2670 }
2671
2672 static int sd_snapshot_delete(BlockDriverState *bs,
2673 const char *snapshot_id,
2674 const char *name,
2675 Error **errp)
2676 {
2677 /*
2678 * FIXME should delete the snapshot matching both @snapshot_id and
2679 * @name, but @name not used here
2680 */
2681 unsigned long snap_id = 0;
2682 char snap_tag[SD_MAX_VDI_TAG_LEN];
2683 int fd, ret;
2684 char buf[SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN];
2685 BDRVSheepdogState *s = bs->opaque;
2686 unsigned int wlen = SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN, rlen = 0;
2687 uint32_t vid;
2688 SheepdogVdiReq hdr = {
2689 .opcode = SD_OP_DEL_VDI,
2690 .data_length = wlen,
2691 .flags = SD_FLAG_CMD_WRITE,
2692 };
2693 SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
2694
2695 ret = remove_objects(s, errp);
2696 if (ret) {
2697 return ret;
2698 }
2699
2700 memset(buf, 0, sizeof(buf));
2701 memset(snap_tag, 0, sizeof(snap_tag));
2702 pstrcpy(buf, SD_MAX_VDI_LEN, s->name);
2703 /* TODO Use sd_parse_snapid() once this mess is cleaned up */
2704 ret = qemu_strtoul(snapshot_id, NULL, 10, &snap_id);
2705 if (ret || snap_id > UINT32_MAX) {
2706 /*
2707 * FIXME Since qemu_strtoul() returns -EINVAL when
2708 * @snapshot_id is null, @snapshot_id is mandatory. Correct
2709 * would be to require at least one of @snapshot_id and @name.
2710 */
2711 error_setg(errp, "Invalid snapshot ID: %s",
2712 snapshot_id ? snapshot_id : "<null>");
2713 return -EINVAL;
2714 }
2715
2716 if (snap_id) {
2717 hdr.snapid = (uint32_t) snap_id;
2718 } else {
2719 /* FIXME I suspect we should use @name here */
2720 /* FIXME don't truncate silently */
2721 pstrcpy(snap_tag, sizeof(snap_tag), snapshot_id);
2722 pstrcpy(buf + SD_MAX_VDI_LEN, SD_MAX_VDI_TAG_LEN, snap_tag);
2723 }
2724
2725 ret = find_vdi_name(s, s->name, snap_id, snap_tag, &vid, true, errp);
2726 if (ret) {
2727 return ret;
2728 }
2729
2730 fd = connect_to_sdog(s, errp);
2731 if (fd < 0) {
2732 return fd;
2733 }
2734
2735 ret = do_req(fd, s->bs, (SheepdogReq *)&hdr,
2736 buf, &wlen, &rlen);
2737 closesocket(fd);
2738 if (ret) {
2739 error_setg_errno(errp, -ret, "Couldn't send request to server");
2740 return ret;
2741 }
2742
2743 switch (rsp->result) {
2744 case SD_RES_NO_VDI:
2745 error_setg(errp, "Can't find the snapshot");
2746 return -ENOENT;
2747 case SD_RES_SUCCESS:
2748 break;
2749 default:
2750 error_setg(errp, "%s", sd_strerror(rsp->result));
2751 return -EIO;
2752 }
2753
2754 return 0;
2755 }
2756
2757 static int sd_snapshot_list(BlockDriverState *bs, QEMUSnapshotInfo **psn_tab)
2758 {
2759 Error *local_err = NULL;
2760 BDRVSheepdogState *s = bs->opaque;
2761 SheepdogReq req;
2762 int fd, nr = 1024, ret, max = BITS_TO_LONGS(SD_NR_VDIS) * sizeof(long);
2763 QEMUSnapshotInfo *sn_tab = NULL;
2764 unsigned wlen, rlen;
2765 int found = 0;
2766 static SheepdogInode inode;
2767 unsigned long *vdi_inuse;
2768 unsigned int start_nr;
2769 uint64_t hval;
2770 uint32_t vid;
2771
2772 vdi_inuse = g_malloc(max);
2773
2774 fd = connect_to_sdog(s, &local_err);
2775 if (fd < 0) {
2776 error_report_err(local_err);
2777 ret = fd;
2778 goto out;
2779 }
2780
2781 rlen = max;
2782 wlen = 0;
2783
2784 memset(&req, 0, sizeof(req));
2785
2786 req.opcode = SD_OP_READ_VDIS;
2787 req.data_length = max;
2788
2789 ret = do_req(fd, s->bs, &req, vdi_inuse, &wlen, &rlen);
2790
2791 closesocket(fd);
2792 if (ret) {
2793 goto out;
2794 }
2795
2796 sn_tab = g_new0(QEMUSnapshotInfo, nr);
2797
2798 /* calculate a vdi id with hash function */
2799 hval = fnv_64a_buf(s->name, strlen(s->name), FNV1A_64_INIT);
2800 start_nr = hval & (SD_NR_VDIS - 1);
2801
2802 fd = connect_to_sdog(s, &local_err);
2803 if (fd < 0) {
2804 error_report_err(local_err);
2805 ret = fd;
2806 goto out;
2807 }
2808
2809 for (vid = start_nr; found < nr; vid = (vid + 1) % SD_NR_VDIS) {
2810 if (!test_bit(vid, vdi_inuse)) {
2811 break;
2812 }
2813
2814 /* we don't need to read entire object */
2815 ret = read_object(fd, s->bs, (char *)&inode,
2816 vid_to_vdi_oid(vid),
2817 0, SD_INODE_SIZE - sizeof(inode.data_vdi_id), 0,
2818 s->cache_flags);
2819
2820 if (ret) {
2821 continue;
2822 }
2823
2824 if (!strcmp(inode.name, s->name) && is_snapshot(&inode)) {
2825 sn_tab[found].date_sec = inode.snap_ctime >> 32;
2826 sn_tab[found].date_nsec = inode.snap_ctime & 0xffffffff;
2827 sn_tab[found].vm_state_size = inode.vm_state_size;
2828 sn_tab[found].vm_clock_nsec = inode.vm_clock_nsec;
2829
2830 snprintf(sn_tab[found].id_str, sizeof(sn_tab[found].id_str),
2831 "%" PRIu32, inode.snap_id);
2832 pstrcpy(sn_tab[found].name,
2833 MIN(sizeof(sn_tab[found].name), sizeof(inode.tag)),
2834 inode.tag);
2835 found++;
2836 }
2837 }
2838
2839 closesocket(fd);
2840 out:
2841 *psn_tab = sn_tab;
2842
2843 g_free(vdi_inuse);
2844
2845 if (ret < 0) {
2846 return ret;
2847 }
2848
2849 return found;
2850 }
2851
2852 static int do_load_save_vmstate(BDRVSheepdogState *s, uint8_t *data,
2853 int64_t pos, int size, int load)
2854 {
2855 Error *local_err = NULL;
2856 bool create;
2857 int fd, ret = 0, remaining = size;
2858 unsigned int data_len;
2859 uint64_t vmstate_oid;
2860 uint64_t offset;
2861 uint32_t vdi_index;
2862 uint32_t vdi_id = load ? s->inode.parent_vdi_id : s->inode.vdi_id;
2863 uint32_t object_size = (UINT32_C(1) << s->inode.block_size_shift);
2864
2865 fd = connect_to_sdog(s, &local_err);
2866 if (fd < 0) {
2867 error_report_err(local_err);
2868 return fd;
2869 }
2870
2871 while (remaining) {
2872 vdi_index = pos / object_size;
2873 offset = pos % object_size;
2874
2875 data_len = MIN(remaining, object_size - offset);
2876
2877 vmstate_oid = vid_to_vmstate_oid(vdi_id, vdi_index);
2878
2879 create = (offset == 0);
2880 if (load) {
2881 ret = read_object(fd, s->bs, (char *)data, vmstate_oid,
2882 s->inode.nr_copies, data_len, offset,
2883 s->cache_flags);
2884 } else {
2885 ret = write_object(fd, s->bs, (char *)data, vmstate_oid,
2886 s->inode.nr_copies, data_len, offset, create,
2887 s->cache_flags);
2888 }
2889
2890 if (ret < 0) {
2891 error_report("failed to save vmstate %s", strerror(errno));
2892 goto cleanup;
2893 }
2894
2895 pos += data_len;
2896 data += data_len;
2897 remaining -= data_len;
2898 }
2899 ret = size;
2900 cleanup:
2901 closesocket(fd);
2902 return ret;
2903 }
2904
2905 static int sd_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2906 int64_t pos)
2907 {
2908 BDRVSheepdogState *s = bs->opaque;
2909 void *buf;
2910 int ret;
2911
2912 buf = qemu_blockalign(bs, qiov->size);
2913 qemu_iovec_to_buf(qiov, 0, buf, qiov->size);
2914 ret = do_load_save_vmstate(s, (uint8_t *) buf, pos, qiov->size, 0);
2915 qemu_vfree(buf);
2916
2917 return ret;
2918 }
2919
2920 static int sd_load_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2921 int64_t pos)
2922 {
2923 BDRVSheepdogState *s = bs->opaque;
2924 void *buf;
2925 int ret;
2926
2927 buf = qemu_blockalign(bs, qiov->size);
2928 ret = do_load_save_vmstate(s, buf, pos, qiov->size, 1);
2929 qemu_iovec_from_buf(qiov, 0, buf, qiov->size);
2930 qemu_vfree(buf);
2931
2932 return ret;
2933 }
2934
2935
2936 static coroutine_fn int sd_co_pdiscard(BlockDriverState *bs, int64_t offset,
2937 int count)
2938 {
2939 SheepdogAIOCB acb;
2940 BDRVSheepdogState *s = bs->opaque;
2941 QEMUIOVector discard_iov;
2942 struct iovec iov;
2943 uint32_t zero = 0;
2944
2945 if (!s->discard_supported) {
2946 return 0;
2947 }
2948
2949 memset(&discard_iov, 0, sizeof(discard_iov));
2950 memset(&iov, 0, sizeof(iov));
2951 iov.iov_base = &zero;
2952 iov.iov_len = sizeof(zero);
2953 discard_iov.iov = &iov;
2954 discard_iov.niov = 1;
2955 if (!QEMU_IS_ALIGNED(offset | count, BDRV_SECTOR_SIZE)) {
2956 return -ENOTSUP;
2957 }
2958 sd_aio_setup(&acb, s, &discard_iov, offset >> BDRV_SECTOR_BITS,
2959 count >> BDRV_SECTOR_BITS, AIOCB_DISCARD_OBJ);
2960 sd_co_rw_vector(&acb);
2961 sd_aio_complete(&acb);
2962
2963 return acb.ret;
2964 }
2965
2966 static coroutine_fn int64_t
2967 sd_co_get_block_status(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
2968 int *pnum, BlockDriverState **file)
2969 {
2970 BDRVSheepdogState *s = bs->opaque;
2971 SheepdogInode *inode = &s->inode;
2972 uint32_t object_size = (UINT32_C(1) << inode->block_size_shift);
2973 uint64_t offset = sector_num * BDRV_SECTOR_SIZE;
2974 unsigned long start = offset / object_size,
2975 end = DIV_ROUND_UP((sector_num + nb_sectors) *
2976 BDRV_SECTOR_SIZE, object_size);
2977 unsigned long idx;
2978 int64_t ret = BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | offset;
2979
2980 for (idx = start; idx < end; idx++) {
2981 if (inode->data_vdi_id[idx] == 0) {
2982 break;
2983 }
2984 }
2985 if (idx == start) {
2986 /* Get the longest length of unallocated sectors */
2987 ret = 0;
2988 for (idx = start + 1; idx < end; idx++) {
2989 if (inode->data_vdi_id[idx] != 0) {
2990 break;
2991 }
2992 }
2993 }
2994
2995 *pnum = (idx - start) * object_size / BDRV_SECTOR_SIZE;
2996 if (*pnum > nb_sectors) {
2997 *pnum = nb_sectors;
2998 }
2999 if (ret > 0 && ret & BDRV_BLOCK_OFFSET_VALID) {
3000 *file = bs;
3001 }
3002 return ret;
3003 }
3004
3005 static int64_t sd_get_allocated_file_size(BlockDriverState *bs)
3006 {
3007 BDRVSheepdogState *s = bs->opaque;
3008 SheepdogInode *inode = &s->inode;
3009 uint32_t object_size = (UINT32_C(1) << inode->block_size_shift);
3010 unsigned long i, last = DIV_ROUND_UP(inode->vdi_size, object_size);
3011 uint64_t size = 0;
3012
3013 for (i = 0; i < last; i++) {
3014 if (inode->data_vdi_id[i] == 0) {
3015 continue;
3016 }
3017 size += object_size;
3018 }
3019 return size;
3020 }
3021
3022 static QemuOptsList sd_create_opts = {
3023 .name = "sheepdog-create-opts",
3024 .head = QTAILQ_HEAD_INITIALIZER(sd_create_opts.head),
3025 .desc = {
3026 {
3027 .name = BLOCK_OPT_SIZE,
3028 .type = QEMU_OPT_SIZE,
3029 .help = "Virtual disk size"
3030 },
3031 {
3032 .name = BLOCK_OPT_BACKING_FILE,
3033 .type = QEMU_OPT_STRING,
3034 .help = "File name of a base image"
3035 },
3036 {
3037 .name = BLOCK_OPT_PREALLOC,
3038 .type = QEMU_OPT_STRING,
3039 .help = "Preallocation mode (allowed values: off, full)"
3040 },
3041 {
3042 .name = BLOCK_OPT_REDUNDANCY,
3043 .type = QEMU_OPT_STRING,
3044 .help = "Redundancy of the image"
3045 },
3046 {
3047 .name = BLOCK_OPT_OBJECT_SIZE,
3048 .type = QEMU_OPT_SIZE,
3049 .help = "Object size of the image"
3050 },
3051 { /* end of list */ }
3052 }
3053 };
3054
3055 static BlockDriver bdrv_sheepdog = {
3056 .format_name = "sheepdog",
3057 .protocol_name = "sheepdog",
3058 .instance_size = sizeof(BDRVSheepdogState),
3059 .bdrv_parse_filename = sd_parse_filename,
3060 .bdrv_file_open = sd_open,
3061 .bdrv_reopen_prepare = sd_reopen_prepare,
3062 .bdrv_reopen_commit = sd_reopen_commit,
3063 .bdrv_reopen_abort = sd_reopen_abort,
3064 .bdrv_close = sd_close,
3065 .bdrv_create = sd_create,
3066 .bdrv_has_zero_init = bdrv_has_zero_init_1,
3067 .bdrv_getlength = sd_getlength,
3068 .bdrv_get_allocated_file_size = sd_get_allocated_file_size,
3069 .bdrv_truncate = sd_truncate,
3070
3071 .bdrv_co_readv = sd_co_readv,
3072 .bdrv_co_writev = sd_co_writev,
3073 .bdrv_co_flush_to_disk = sd_co_flush_to_disk,
3074 .bdrv_co_pdiscard = sd_co_pdiscard,
3075 .bdrv_co_get_block_status = sd_co_get_block_status,
3076
3077 .bdrv_snapshot_create = sd_snapshot_create,
3078 .bdrv_snapshot_goto = sd_snapshot_goto,
3079 .bdrv_snapshot_delete = sd_snapshot_delete,
3080 .bdrv_snapshot_list = sd_snapshot_list,
3081
3082 .bdrv_save_vmstate = sd_save_vmstate,
3083 .bdrv_load_vmstate = sd_load_vmstate,
3084
3085 .bdrv_detach_aio_context = sd_detach_aio_context,
3086 .bdrv_attach_aio_context = sd_attach_aio_context,
3087
3088 .create_opts = &sd_create_opts,
3089 };
3090
3091 static BlockDriver bdrv_sheepdog_tcp = {
3092 .format_name = "sheepdog",
3093 .protocol_name = "sheepdog+tcp",
3094 .instance_size = sizeof(BDRVSheepdogState),
3095 .bdrv_parse_filename = sd_parse_filename,
3096 .bdrv_file_open = sd_open,
3097 .bdrv_reopen_prepare = sd_reopen_prepare,
3098 .bdrv_reopen_commit = sd_reopen_commit,
3099 .bdrv_reopen_abort = sd_reopen_abort,
3100 .bdrv_close = sd_close,
3101 .bdrv_create = sd_create,
3102 .bdrv_has_zero_init = bdrv_has_zero_init_1,
3103 .bdrv_getlength = sd_getlength,
3104 .bdrv_get_allocated_file_size = sd_get_allocated_file_size,
3105 .bdrv_truncate = sd_truncate,
3106
3107 .bdrv_co_readv = sd_co_readv,
3108 .bdrv_co_writev = sd_co_writev,
3109 .bdrv_co_flush_to_disk = sd_co_flush_to_disk,
3110 .bdrv_co_pdiscard = sd_co_pdiscard,
3111 .bdrv_co_get_block_status = sd_co_get_block_status,
3112
3113 .bdrv_snapshot_create = sd_snapshot_create,
3114 .bdrv_snapshot_goto = sd_snapshot_goto,
3115 .bdrv_snapshot_delete = sd_snapshot_delete,
3116 .bdrv_snapshot_list = sd_snapshot_list,
3117
3118 .bdrv_save_vmstate = sd_save_vmstate,
3119 .bdrv_load_vmstate = sd_load_vmstate,
3120
3121 .bdrv_detach_aio_context = sd_detach_aio_context,
3122 .bdrv_attach_aio_context = sd_attach_aio_context,
3123
3124 .create_opts = &sd_create_opts,
3125 };
3126
3127 static BlockDriver bdrv_sheepdog_unix = {
3128 .format_name = "sheepdog",
3129 .protocol_name = "sheepdog+unix",
3130 .instance_size = sizeof(BDRVSheepdogState),
3131 .bdrv_parse_filename = sd_parse_filename,
3132 .bdrv_file_open = sd_open,
3133 .bdrv_reopen_prepare = sd_reopen_prepare,
3134 .bdrv_reopen_commit = sd_reopen_commit,
3135 .bdrv_reopen_abort = sd_reopen_abort,
3136 .bdrv_close = sd_close,
3137 .bdrv_create = sd_create,
3138 .bdrv_has_zero_init = bdrv_has_zero_init_1,
3139 .bdrv_getlength = sd_getlength,
3140 .bdrv_get_allocated_file_size = sd_get_allocated_file_size,
3141 .bdrv_truncate = sd_truncate,
3142
3143 .bdrv_co_readv = sd_co_readv,
3144 .bdrv_co_writev = sd_co_writev,
3145 .bdrv_co_flush_to_disk = sd_co_flush_to_disk,
3146 .bdrv_co_pdiscard = sd_co_pdiscard,
3147 .bdrv_co_get_block_status = sd_co_get_block_status,
3148
3149 .bdrv_snapshot_create = sd_snapshot_create,
3150 .bdrv_snapshot_goto = sd_snapshot_goto,
3151 .bdrv_snapshot_delete = sd_snapshot_delete,
3152 .bdrv_snapshot_list = sd_snapshot_list,
3153
3154 .bdrv_save_vmstate = sd_save_vmstate,
3155 .bdrv_load_vmstate = sd_load_vmstate,
3156
3157 .bdrv_detach_aio_context = sd_detach_aio_context,
3158 .bdrv_attach_aio_context = sd_attach_aio_context,
3159
3160 .create_opts = &sd_create_opts,
3161 };
3162
3163 static void bdrv_sheepdog_init(void)
3164 {
3165 bdrv_register(&bdrv_sheepdog);
3166 bdrv_register(&bdrv_sheepdog_tcp);
3167 bdrv_register(&bdrv_sheepdog_unix);
3168 }
3169 block_init(bdrv_sheepdog_init);