2 * Copyright (C) 2009-2010 Nippon Telegraph and Telephone Corporation.
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.
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/>.
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.
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"
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"
28 #define SD_PROTO_VER 0x01
30 #define SD_DEFAULT_ADDR "localhost"
31 #define SD_DEFAULT_PORT 7000
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 */
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
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 */
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 */
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
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
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
105 * SD_MAX_COPIES is sum of number of data strips and parity strips.
107 #define SD_EC_MAX_STRIP 16
108 #define SD_MAX_COPIES (SD_EC_MAX_STRIP * 2 - 1)
110 #define SD_INODE_SIZE (sizeof(SheepdogInode))
111 #define CURRENT_VDI_ID 0
113 #define LOCK_TYPE_NORMAL 0
114 #define LOCK_TYPE_SHARED 1 /* for iSCSI multipath */
116 typedef struct SheepdogReq
{
122 uint32_t data_length
;
123 uint32_t opcode_specific
[8];
126 typedef struct SheepdogRsp
{
132 uint32_t data_length
;
134 uint32_t opcode_specific
[7];
137 typedef struct SheepdogObjReq
{
143 uint32_t data_length
;
152 typedef struct SheepdogObjRsp
{
158 uint32_t data_length
;
166 typedef struct SheepdogVdiReq
{
172 uint32_t data_length
;
174 uint32_t base_vdi_id
;
177 uint8_t store_policy
;
178 uint8_t block_size_shift
;
184 typedef struct SheepdogVdiRsp
{
190 uint32_t data_length
;
197 typedef struct SheepdogClusterRsp
{
203 uint32_t data_length
;
207 uint8_t block_size_shift
;
210 } SheepdogClusterRsp
;
212 typedef struct SheepdogInode
{
213 char name
[SD_MAX_VDI_LEN
];
214 char tag
[SD_MAX_VDI_TAG_LEN
];
217 uint64_t vm_clock_nsec
;
219 uint64_t vm_state_size
;
220 uint16_t copy_policy
;
222 uint8_t block_size_shift
;
225 uint32_t parent_vdi_id
;
226 uint32_t child_vdi_id
[MAX_CHILDREN
];
227 uint32_t data_vdi_id
[MAX_DATA_OBJS
];
230 #define SD_INODE_HEADER_SIZE offsetof(SheepdogInode, data_vdi_id)
233 * 64 bit FNV-1a non-zero initial basis
235 #define FNV1A_64_INIT ((uint64_t)0xcbf29ce484222325ULL)
238 * 64 bit Fowler/Noll/Vo FNV-1a hash code
240 static inline uint64_t fnv_64a_buf(void *buf
, size_t len
, uint64_t hval
)
242 unsigned char *bp
= buf
;
243 unsigned char *be
= bp
+ len
;
245 hval
^= (uint64_t) *bp
++;
246 hval
+= (hval
<< 1) + (hval
<< 4) + (hval
<< 5) +
247 (hval
<< 7) + (hval
<< 8) + (hval
<< 40);
252 static inline bool is_data_obj_writable(SheepdogInode
*inode
, unsigned int idx
)
254 return inode
->vdi_id
== inode
->data_vdi_id
[idx
];
257 static inline bool is_data_obj(uint64_t oid
)
259 return !(VDI_BIT
& oid
);
262 static inline uint64_t data_oid_to_idx(uint64_t oid
)
264 return oid
& (MAX_DATA_OBJS
- 1);
267 static inline uint32_t oid_to_vid(uint64_t oid
)
269 return (oid
& ~VDI_BIT
) >> VDI_SPACE_SHIFT
;
272 static inline uint64_t vid_to_vdi_oid(uint32_t vid
)
274 return VDI_BIT
| ((uint64_t)vid
<< VDI_SPACE_SHIFT
);
277 static inline uint64_t vid_to_vmstate_oid(uint32_t vid
, uint32_t idx
)
279 return VMSTATE_BIT
| ((uint64_t)vid
<< VDI_SPACE_SHIFT
) | idx
;
282 static inline uint64_t vid_to_data_oid(uint32_t vid
, uint32_t idx
)
284 return ((uint64_t)vid
<< VDI_SPACE_SHIFT
) | idx
;
287 static inline bool is_snapshot(struct SheepdogInode
*inode
)
289 return !!inode
->snap_ctime
;
292 static inline size_t count_data_objs(const struct SheepdogInode
*inode
)
294 return DIV_ROUND_UP(inode
->vdi_size
,
295 (1UL << inode
->block_size_shift
));
300 #define DEBUG_SDOG_PRINT 1
302 #define DEBUG_SDOG_PRINT 0
304 #define DPRINTF(fmt, args...) \
306 if (DEBUG_SDOG_PRINT) { \
307 fprintf(stderr, "%s %d: " fmt, __func__, __LINE__, ##args); \
311 typedef struct SheepdogAIOCB SheepdogAIOCB
;
312 typedef struct BDRVSheepdogState BDRVSheepdogState
;
314 typedef struct AIOReq
{
315 SheepdogAIOCB
*aiocb
;
316 unsigned int iov_offset
;
321 unsigned int data_len
;
326 QLIST_ENTRY(AIOReq
) aio_siblings
;
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))
340 struct SheepdogAIOCB
{
341 BDRVSheepdogState
*s
;
349 enum AIOCBState aiocb_type
;
351 Coroutine
*coroutine
;
354 uint32_t min_affect_data_idx
;
355 uint32_t max_affect_data_idx
;
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.
363 uint32_t min_dirty_data_idx
;
364 uint32_t max_dirty_data_idx
;
366 QLIST_ENTRY(SheepdogAIOCB
) aiocb_siblings
;
369 struct BDRVSheepdogState
{
370 BlockDriverState
*bs
;
371 AioContext
*aio_context
;
375 char name
[SD_MAX_VDI_LEN
];
377 uint32_t cache_flags
;
378 bool discard_supported
;
387 uint32_t aioreq_seq_num
;
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
;
393 CoQueue overlapping_queue
;
394 QLIST_HEAD(inflight_aiocb_head
, SheepdogAIOCB
) inflight_aiocb_head
;
397 typedef struct BDRVSheepdogReopenState
{
400 } BDRVSheepdogReopenState
;
402 static const char * sd_strerror(int err
)
406 static const struct {
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"},
439 for (i
= 0; i
< ARRAY_SIZE(errors
); ++i
) {
440 if (errors
[i
].err
== err
) {
441 return errors
[i
].desc
;
445 return "Invalid error code";
449 * Sheepdog I/O handling:
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.
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.
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
)
469 aio_req
= g_malloc(sizeof(*aio_req
));
470 aio_req
->aiocb
= acb
;
471 aio_req
->iov_offset
= iov_offset
;
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
;
484 static void wait_for_overlapping_aiocb(BDRVSheepdogState
*s
, SheepdogAIOCB
*acb
)
489 QLIST_FOREACH(cb
, &s
->inflight_aiocb_head
, aiocb_siblings
) {
490 if (AIOCBOverlapping(acb
, cb
)) {
491 qemu_co_queue_wait(&s
->overlapping_queue
, NULL
);
497 static void sd_aio_setup(SheepdogAIOCB
*acb
, BDRVSheepdogState
*s
,
498 QEMUIOVector
*qiov
, int64_t sector_num
, int nb_sectors
,
501 uint32_t object_size
;
503 object_size
= (UINT32_C(1) << s
->inode
.block_size_shift
);
509 acb
->sector_num
= sector_num
;
510 acb
->nb_sectors
= nb_sectors
;
512 acb
->coroutine
= qemu_coroutine_self();
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
;
520 acb
->min_dirty_data_idx
= UINT32_MAX
;
521 acb
->max_dirty_data_idx
= 0;
522 acb
->aiocb_type
= type
;
524 if (type
== AIOCB_FLUSH_CACHE
) {
528 wait_for_overlapping_aiocb(s
, acb
);
529 QLIST_INSERT_HEAD(&s
->inflight_aiocb_head
, acb
, aiocb_siblings
);
532 static SocketAddress
*sd_socket_address(const char *path
,
533 const char *host
, const char *port
)
535 SocketAddress
*addr
= g_new0(SocketAddress
, 1);
538 addr
->type
= SOCKET_ADDRESS_TYPE_UNIX
;
539 addr
->u
.q_unix
.path
= g_strdup(path
);
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
));
549 static SocketAddress
*sd_server_config(QDict
*options
, Error
**errp
)
551 QDict
*server
= NULL
;
552 QObject
*crumpled_server
= NULL
;
554 SocketAddress
*saddr
= NULL
;
555 Error
*local_err
= NULL
;
557 qdict_extract_subqdict(options
, &server
, "server.");
559 crumpled_server
= qdict_crumple(server
, errp
);
560 if (!crumpled_server
) {
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.
572 iv
= qobject_input_visitor_new(crumpled_server
);
573 visit_type_SocketAddress(iv
, NULL
, &saddr
, &local_err
);
575 error_propagate(errp
, local_err
);
581 qobject_decref(crumpled_server
);
586 /* Return -EIO in case of error, file descriptor on success */
587 static int connect_to_sdog(BDRVSheepdogState
*s
, Error
**errp
)
591 fd
= socket_connect(s
->addr
, NULL
, NULL
, errp
);
593 if (s
->addr
->type
== SOCKET_ADDRESS_TYPE_INET
&& fd
>= 0) {
594 int ret
= socket_set_nodelay(fd
);
596 error_report("%s", strerror(errno
));
601 qemu_set_nonblock(fd
);
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
,
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
));
621 ret
= qemu_co_send(sockfd
, data
, *wlen
);
623 error_report("failed to send a req, %s", strerror(errno
));
630 typedef struct SheepdogReqCo
{
632 BlockDriverState
*bs
;
633 AioContext
*aio_context
;
643 static void restart_co_req(void *opaque
)
645 SheepdogReqCo
*srco
= opaque
;
647 aio_co_wake(srco
->co
);
650 static coroutine_fn
void do_co_req(void *opaque
)
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
;
660 srco
->co
= qemu_coroutine_self();
661 aio_set_fd_handler(srco
->aio_context
, sockfd
, false,
662 NULL
, restart_co_req
, NULL
, srco
);
664 ret
= send_co_req(sockfd
, hdr
, data
, wlen
);
669 aio_set_fd_handler(srco
->aio_context
, sockfd
, false,
670 restart_co_req
, NULL
, NULL
, srco
);
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
));
679 if (*rlen
> hdr
->data_length
) {
680 *rlen
= hdr
->data_length
;
684 ret
= qemu_co_recv(sockfd
, data
, *rlen
);
686 error_report("failed to get the data, %s", strerror(errno
));
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
);
700 /* Set srco->finished before reading bs->wakeup. */
701 atomic_mb_set(&srco
->finished
, true);
703 bdrv_wakeup(srco
->bs
);
708 * Send the request to the sheep in a synchronous manner.
710 * Return 0 on success, -errno in case of error.
712 static int do_req(int sockfd
, BlockDriverState
*bs
, SheepdogReq
*hdr
,
713 void *data
, unsigned int *wlen
, unsigned int *rlen
)
716 SheepdogReqCo srco
= {
718 .aio_context
= bs
? bdrv_get_aio_context(bs
) : qemu_get_aio_context(),
728 if (qemu_in_coroutine()) {
731 co
= qemu_coroutine_create(do_co_req
, &srco
);
733 bdrv_coroutine_enter(bs
, co
);
734 BDRV_POLL_WHILE(bs
, !srco
.finished
);
736 qemu_coroutine_enter(co
);
737 while (!srco
.finished
) {
738 aio_poll(qemu_get_aio_context(), true);
746 static void coroutine_fn
add_aio_request(BDRVSheepdogState
*s
, AIOReq
*aio_req
,
747 struct iovec
*iov
, int niov
,
748 enum AIOCBState aiocb_type
);
749 static void coroutine_fn
resend_aioreq(BDRVSheepdogState
*s
, AIOReq
*aio_req
);
750 static int reload_inode(BDRVSheepdogState
*s
, uint32_t snapid
, const char *tag
);
751 static int get_sheep_fd(BDRVSheepdogState
*s
, Error
**errp
);
752 static void co_write_request(void *opaque
);
754 static coroutine_fn
void reconnect_to_sdog(void *opaque
)
756 BDRVSheepdogState
*s
= opaque
;
757 AIOReq
*aio_req
, *next
;
759 aio_set_fd_handler(s
->aio_context
, s
->fd
, false, NULL
,
764 /* Wait for outstanding write requests to be completed. */
765 while (s
->co_send
!= NULL
) {
766 co_write_request(opaque
);
769 /* Try to reconnect the sheepdog server every one second. */
771 Error
*local_err
= NULL
;
772 s
->fd
= get_sheep_fd(s
, &local_err
);
774 DPRINTF("Wait for connection to be established\n");
775 error_report_err(local_err
);
776 co_aio_sleep_ns(bdrv_get_aio_context(s
->bs
), QEMU_CLOCK_REALTIME
,
782 * Now we have to resend all the request in the inflight queue. However,
783 * resend_aioreq() can yield and newly created requests can be added to the
784 * inflight queue before the coroutine is resumed. To avoid mixing them, we
785 * have to move all the inflight requests to the failed queue before
786 * resend_aioreq() is called.
788 QLIST_FOREACH_SAFE(aio_req
, &s
->inflight_aio_head
, aio_siblings
, next
) {
789 QLIST_REMOVE(aio_req
, aio_siblings
);
790 QLIST_INSERT_HEAD(&s
->failed_aio_head
, aio_req
, aio_siblings
);
793 /* Resend all the failed aio requests. */
794 while (!QLIST_EMPTY(&s
->failed_aio_head
)) {
795 aio_req
= QLIST_FIRST(&s
->failed_aio_head
);
796 QLIST_REMOVE(aio_req
, aio_siblings
);
797 resend_aioreq(s
, aio_req
);
802 * Receive responses of the I/O requests.
804 * This function is registered as a fd handler, and called from the
805 * main loop when s->fd is ready for reading responses.
807 static void coroutine_fn
aio_read_response(void *opaque
)
810 BDRVSheepdogState
*s
= opaque
;
813 AIOReq
*aio_req
= NULL
;
818 ret
= qemu_co_recv(fd
, &rsp
, sizeof(rsp
));
819 if (ret
!= sizeof(rsp
)) {
820 error_report("failed to get the header, %s", strerror(errno
));
824 /* find the right aio_req from the inflight aio list */
825 QLIST_FOREACH(aio_req
, &s
->inflight_aio_head
, aio_siblings
) {
826 if (aio_req
->id
== rsp
.id
) {
831 error_report("cannot find aio_req %x", rsp
.id
);
835 acb
= aio_req
->aiocb
;
837 switch (acb
->aiocb_type
) {
838 case AIOCB_WRITE_UDATA
:
839 if (!is_data_obj(aio_req
->oid
)) {
842 idx
= data_oid_to_idx(aio_req
->oid
);
844 if (aio_req
->create
) {
846 * If the object is newly created one, we need to update
847 * the vdi object (metadata object). min_dirty_data_idx
848 * and max_dirty_data_idx are changed to include updated
849 * index between them.
851 if (rsp
.result
== SD_RES_SUCCESS
) {
852 s
->inode
.data_vdi_id
[idx
] = s
->inode
.vdi_id
;
853 acb
->max_dirty_data_idx
= MAX(idx
, acb
->max_dirty_data_idx
);
854 acb
->min_dirty_data_idx
= MIN(idx
, acb
->min_dirty_data_idx
);
858 case AIOCB_READ_UDATA
:
859 ret
= qemu_co_recvv(fd
, acb
->qiov
->iov
, acb
->qiov
->niov
,
860 aio_req
->iov_offset
, rsp
.data_length
);
861 if (ret
!= rsp
.data_length
) {
862 error_report("failed to get the data, %s", strerror(errno
));
866 case AIOCB_FLUSH_CACHE
:
867 if (rsp
.result
== SD_RES_INVALID_PARMS
) {
868 DPRINTF("disable cache since the server doesn't support it\n");
869 s
->cache_flags
= SD_FLAG_CMD_DIRECT
;
870 rsp
.result
= SD_RES_SUCCESS
;
873 case AIOCB_DISCARD_OBJ
:
874 switch (rsp
.result
) {
875 case SD_RES_INVALID_PARMS
:
876 error_report("server doesn't support discard command");
877 rsp
.result
= SD_RES_SUCCESS
;
878 s
->discard_supported
= false;
885 /* No more data for this aio_req (reload_inode below uses its own file
886 * descriptor handler which doesn't use co_recv).
890 QLIST_REMOVE(aio_req
, aio_siblings
);
891 switch (rsp
.result
) {
894 case SD_RES_READONLY
:
895 if (s
->inode
.vdi_id
== oid_to_vid(aio_req
->oid
)) {
896 ret
= reload_inode(s
, 0, "");
901 if (is_data_obj(aio_req
->oid
)) {
902 aio_req
->oid
= vid_to_data_oid(s
->inode
.vdi_id
,
903 data_oid_to_idx(aio_req
->oid
));
905 aio_req
->oid
= vid_to_vdi_oid(s
->inode
.vdi_id
);
907 resend_aioreq(s
, aio_req
);
911 error_report("%s", sd_strerror(rsp
.result
));
917 if (!--acb
->nr_pending
) {
919 * We've finished all requests which belong to the AIOCB, so
920 * we can switch back to sd_co_readv/writev now.
922 aio_co_wake(acb
->coroutine
);
928 reconnect_to_sdog(opaque
);
931 static void co_read_response(void *opaque
)
933 BDRVSheepdogState
*s
= opaque
;
936 s
->co_recv
= qemu_coroutine_create(aio_read_response
, opaque
);
939 aio_co_enter(s
->aio_context
, s
->co_recv
);
942 static void co_write_request(void *opaque
)
944 BDRVSheepdogState
*s
= opaque
;
946 aio_co_wake(s
->co_send
);
950 * Return a socket descriptor to read/write objects.
952 * We cannot use this descriptor for other operations because
953 * the block driver may be on waiting response from the server.
955 static int get_sheep_fd(BDRVSheepdogState
*s
, Error
**errp
)
959 fd
= connect_to_sdog(s
, errp
);
964 aio_set_fd_handler(s
->aio_context
, fd
, false,
965 co_read_response
, NULL
, NULL
, s
);
970 * Parse numeric snapshot ID in @str
971 * If @str can't be parsed as number, return false.
972 * Else, if the number is zero or too large, set *@snapid to zero and
974 * Else, set *@snapid to the number and return true.
976 static bool sd_parse_snapid(const char *str
, uint32_t *snapid
)
981 ret
= qemu_strtoul(str
, NULL
, 10, &ul
);
982 if (ret
== -ERANGE
) {
988 if (ul
> UINT32_MAX
) {
996 static bool sd_parse_snapid_or_tag(const char *str
,
997 uint32_t *snapid
, char tag
[])
999 if (!sd_parse_snapid(str
, snapid
)) {
1001 if (g_strlcpy(tag
, str
, SD_MAX_VDI_TAG_LEN
) >= SD_MAX_VDI_TAG_LEN
) {
1004 } else if (!*snapid
) {
1013 const char *path
; /* non-null iff transport is tcp */
1014 const char *host
; /* valid when transport is tcp */
1015 int port
; /* valid when transport is tcp */
1016 char vdi
[SD_MAX_VDI_LEN
];
1017 char tag
[SD_MAX_VDI_TAG_LEN
];
1019 /* Remainder is only for sd_config_done() */
1024 static void sd_config_done(SheepdogConfig
*cfg
)
1027 query_params_free(cfg
->qp
);
1032 static void sd_parse_uri(SheepdogConfig
*cfg
, const char *filename
,
1036 QueryParams
*qp
= NULL
;
1040 memset(cfg
, 0, sizeof(*cfg
));
1042 cfg
->uri
= uri
= uri_parse(filename
);
1044 error_setg(&err
, "invalid URI");
1049 if (!g_strcmp0(uri
->scheme
, "sheepdog")) {
1051 } else if (!g_strcmp0(uri
->scheme
, "sheepdog+tcp")) {
1053 } else if (!g_strcmp0(uri
->scheme
, "sheepdog+unix")) {
1056 error_setg(&err
, "URI scheme must be 'sheepdog', 'sheepdog+tcp',"
1057 " or 'sheepdog+unix'");
1061 if (uri
->path
== NULL
|| !strcmp(uri
->path
, "/")) {
1062 error_setg(&err
, "missing file path in URI");
1065 if (g_strlcpy(cfg
->vdi
, uri
->path
+ 1, SD_MAX_VDI_LEN
)
1066 >= SD_MAX_VDI_LEN
) {
1067 error_setg(&err
, "VDI name is too long");
1071 cfg
->qp
= qp
= query_params_parse(uri
->query
);
1074 /* sheepdog+unix:///vdiname?socket=path */
1075 if (uri
->server
|| uri
->port
) {
1076 error_setg(&err
, "URI scheme %s doesn't accept a server address",
1082 "URI scheme %s requires query parameter 'socket'",
1086 if (qp
->n
!= 1 || strcmp(qp
->p
[0].name
, "socket")) {
1087 error_setg(&err
, "unexpected query parameters");
1090 cfg
->path
= qp
->p
[0].value
;
1092 /* sheepdog[+tcp]://[host:port]/vdiname */
1094 error_setg(&err
, "unexpected query parameters");
1097 cfg
->host
= uri
->server
;
1098 cfg
->port
= uri
->port
;
1102 if (uri
->fragment
) {
1103 if (!sd_parse_snapid_or_tag(uri
->fragment
,
1104 &cfg
->snap_id
, cfg
->tag
)) {
1105 error_setg(&err
, "'%s' is not a valid snapshot ID",
1110 cfg
->snap_id
= CURRENT_VDI_ID
; /* search current vdi */
1115 error_propagate(errp
, err
);
1116 sd_config_done(cfg
);
1121 * Parse a filename (old syntax)
1123 * filename must be one of the following formats:
1125 * 2. [vdiname]:[snapid]
1126 * 3. [vdiname]:[tag]
1127 * 4. [hostname]:[port]:[vdiname]
1128 * 5. [hostname]:[port]:[vdiname]:[snapid]
1129 * 6. [hostname]:[port]:[vdiname]:[tag]
1131 * You can boot from the snapshot images by specifying `snapid` or
1134 * You can run VMs outside the Sheepdog cluster by specifying
1135 * `hostname' and `port' (experimental).
1137 static void parse_vdiname(SheepdogConfig
*cfg
, const char *filename
,
1142 const char *host_spec
, *vdi_spec
;
1145 strstart(filename
, "sheepdog:", &filename
);
1146 p
= q
= g_strdup(filename
);
1148 /* count the number of separators */
1158 /* use the first two tokens as host_spec. */
1171 p
= strchr(vdi_spec
, ':');
1176 uri
= g_strdup_printf("sheepdog://%s/%s", host_spec
, vdi_spec
);
1179 * FIXME We to escape URI meta-characters, e.g. "x?y=z"
1180 * produces "sheepdog://x?y=z". Because of that ...
1182 sd_parse_uri(cfg
, uri
, &err
);
1185 * ... this can fail, but the error message is misleading.
1186 * Replace it by the traditional useless one until the
1187 * escaping is fixed.
1190 error_setg(errp
, "Can't parse filename");
1197 static void sd_parse_filename(const char *filename
, QDict
*options
,
1204 if (strstr(filename
, "://")) {
1205 sd_parse_uri(&cfg
, filename
, &err
);
1207 parse_vdiname(&cfg
, filename
, &err
);
1210 error_propagate(errp
, err
);
1215 qdict_set_default_str(options
, "server.path", cfg
.path
);
1216 qdict_set_default_str(options
, "server.type", "unix");
1218 qdict_set_default_str(options
, "server.type", "inet");
1219 qdict_set_default_str(options
, "server.host",
1220 cfg
.host
?: SD_DEFAULT_ADDR
);
1221 snprintf(buf
, sizeof(buf
), "%d", cfg
.port
?: SD_DEFAULT_PORT
);
1222 qdict_set_default_str(options
, "server.port", buf
);
1224 qdict_set_default_str(options
, "vdi", cfg
.vdi
);
1225 qdict_set_default_str(options
, "tag", cfg
.tag
);
1227 snprintf(buf
, sizeof(buf
), "%d", cfg
.snap_id
);
1228 qdict_set_default_str(options
, "snap-id", buf
);
1231 sd_config_done(&cfg
);
1234 static int find_vdi_name(BDRVSheepdogState
*s
, const char *filename
,
1235 uint32_t snapid
, const char *tag
, uint32_t *vid
,
1236 bool lock
, Error
**errp
)
1240 SheepdogVdiRsp
*rsp
= (SheepdogVdiRsp
*)&hdr
;
1241 unsigned int wlen
, rlen
= 0;
1242 char buf
[SD_MAX_VDI_LEN
+ SD_MAX_VDI_TAG_LEN
];
1244 fd
= connect_to_sdog(s
, errp
);
1249 /* This pair of strncpy calls ensures that the buffer is zero-filled,
1250 * which is desirable since we'll soon be sending those bytes, and
1251 * don't want the send_req to read uninitialized data.
1253 strncpy(buf
, filename
, SD_MAX_VDI_LEN
);
1254 strncpy(buf
+ SD_MAX_VDI_LEN
, tag
, SD_MAX_VDI_TAG_LEN
);
1256 memset(&hdr
, 0, sizeof(hdr
));
1258 hdr
.opcode
= SD_OP_LOCK_VDI
;
1259 hdr
.type
= LOCK_TYPE_NORMAL
;
1261 hdr
.opcode
= SD_OP_GET_VDI_INFO
;
1263 wlen
= SD_MAX_VDI_LEN
+ SD_MAX_VDI_TAG_LEN
;
1264 hdr
.proto_ver
= SD_PROTO_VER
;
1265 hdr
.data_length
= wlen
;
1266 hdr
.snapid
= snapid
;
1267 hdr
.flags
= SD_FLAG_CMD_WRITE
;
1269 ret
= do_req(fd
, s
->bs
, (SheepdogReq
*)&hdr
, buf
, &wlen
, &rlen
);
1271 error_setg_errno(errp
, -ret
, "cannot get vdi info");
1275 if (rsp
->result
!= SD_RES_SUCCESS
) {
1276 error_setg(errp
, "cannot get vdi info, %s, %s %" PRIu32
" %s",
1277 sd_strerror(rsp
->result
), filename
, snapid
, tag
);
1278 if (rsp
->result
== SD_RES_NO_VDI
) {
1280 } else if (rsp
->result
== SD_RES_VDI_LOCKED
) {
1295 static void coroutine_fn
add_aio_request(BDRVSheepdogState
*s
, AIOReq
*aio_req
,
1296 struct iovec
*iov
, int niov
,
1297 enum AIOCBState aiocb_type
)
1299 int nr_copies
= s
->inode
.nr_copies
;
1301 unsigned int wlen
= 0;
1303 uint64_t oid
= aio_req
->oid
;
1304 unsigned int datalen
= aio_req
->data_len
;
1305 uint64_t offset
= aio_req
->offset
;
1306 uint8_t flags
= aio_req
->flags
;
1307 uint64_t old_oid
= aio_req
->base_oid
;
1308 bool create
= aio_req
->create
;
1310 QLIST_INSERT_HEAD(&s
->inflight_aio_head
, aio_req
, aio_siblings
);
1313 error_report("bug");
1316 memset(&hdr
, 0, sizeof(hdr
));
1318 switch (aiocb_type
) {
1319 case AIOCB_FLUSH_CACHE
:
1320 hdr
.opcode
= SD_OP_FLUSH_VDI
;
1322 case AIOCB_READ_UDATA
:
1323 hdr
.opcode
= SD_OP_READ_OBJ
;
1326 case AIOCB_WRITE_UDATA
:
1328 hdr
.opcode
= SD_OP_CREATE_AND_WRITE_OBJ
;
1330 hdr
.opcode
= SD_OP_WRITE_OBJ
;
1333 hdr
.flags
= SD_FLAG_CMD_WRITE
| flags
;
1335 case AIOCB_DISCARD_OBJ
:
1336 hdr
.opcode
= SD_OP_WRITE_OBJ
;
1337 hdr
.flags
= SD_FLAG_CMD_WRITE
| flags
;
1338 s
->inode
.data_vdi_id
[data_oid_to_idx(oid
)] = 0;
1339 offset
= offsetof(SheepdogInode
,
1340 data_vdi_id
[data_oid_to_idx(oid
)]);
1341 oid
= vid_to_vdi_oid(s
->inode
.vdi_id
);
1342 wlen
= datalen
= sizeof(uint32_t);
1346 if (s
->cache_flags
) {
1347 hdr
.flags
|= s
->cache_flags
;
1351 hdr
.cow_oid
= old_oid
;
1352 hdr
.copies
= s
->inode
.nr_copies
;
1354 hdr
.data_length
= datalen
;
1355 hdr
.offset
= offset
;
1357 hdr
.id
= aio_req
->id
;
1359 qemu_co_mutex_lock(&s
->lock
);
1360 s
->co_send
= qemu_coroutine_self();
1361 aio_set_fd_handler(s
->aio_context
, s
->fd
, false,
1362 co_read_response
, co_write_request
, NULL
, s
);
1363 socket_set_cork(s
->fd
, 1);
1366 ret
= qemu_co_send(s
->fd
, &hdr
, sizeof(hdr
));
1367 if (ret
!= sizeof(hdr
)) {
1368 error_report("failed to send a req, %s", strerror(errno
));
1373 ret
= qemu_co_sendv(s
->fd
, iov
, niov
, aio_req
->iov_offset
, wlen
);
1375 error_report("failed to send a data, %s", strerror(errno
));
1379 socket_set_cork(s
->fd
, 0);
1380 aio_set_fd_handler(s
->aio_context
, s
->fd
, false,
1381 co_read_response
, NULL
, NULL
, s
);
1383 qemu_co_mutex_unlock(&s
->lock
);
1386 static int read_write_object(int fd
, BlockDriverState
*bs
, char *buf
,
1387 uint64_t oid
, uint8_t copies
,
1388 unsigned int datalen
, uint64_t offset
,
1389 bool write
, bool create
, uint32_t cache_flags
)
1392 SheepdogObjRsp
*rsp
= (SheepdogObjRsp
*)&hdr
;
1393 unsigned int wlen
, rlen
;
1396 memset(&hdr
, 0, sizeof(hdr
));
1401 hdr
.flags
= SD_FLAG_CMD_WRITE
;
1403 hdr
.opcode
= SD_OP_CREATE_AND_WRITE_OBJ
;
1405 hdr
.opcode
= SD_OP_WRITE_OBJ
;
1410 hdr
.opcode
= SD_OP_READ_OBJ
;
1413 hdr
.flags
|= cache_flags
;
1416 hdr
.data_length
= datalen
;
1417 hdr
.offset
= offset
;
1418 hdr
.copies
= copies
;
1420 ret
= do_req(fd
, bs
, (SheepdogReq
*)&hdr
, buf
, &wlen
, &rlen
);
1422 error_report("failed to send a request to the sheep");
1426 switch (rsp
->result
) {
1427 case SD_RES_SUCCESS
:
1430 error_report("%s", sd_strerror(rsp
->result
));
1435 static int read_object(int fd
, BlockDriverState
*bs
, char *buf
,
1436 uint64_t oid
, uint8_t copies
,
1437 unsigned int datalen
, uint64_t offset
,
1438 uint32_t cache_flags
)
1440 return read_write_object(fd
, bs
, buf
, oid
, copies
,
1441 datalen
, offset
, false,
1442 false, cache_flags
);
1445 static int write_object(int fd
, BlockDriverState
*bs
, char *buf
,
1446 uint64_t oid
, uint8_t copies
,
1447 unsigned int datalen
, uint64_t offset
, bool create
,
1448 uint32_t cache_flags
)
1450 return read_write_object(fd
, bs
, buf
, oid
, copies
,
1451 datalen
, offset
, true,
1452 create
, cache_flags
);
1455 /* update inode with the latest state */
1456 static int reload_inode(BDRVSheepdogState
*s
, uint32_t snapid
, const char *tag
)
1458 Error
*local_err
= NULL
;
1459 SheepdogInode
*inode
;
1463 fd
= connect_to_sdog(s
, &local_err
);
1465 error_report_err(local_err
);
1469 inode
= g_malloc(SD_INODE_HEADER_SIZE
);
1471 ret
= find_vdi_name(s
, s
->name
, snapid
, tag
, &vid
, false, &local_err
);
1473 error_report_err(local_err
);
1477 ret
= read_object(fd
, s
->bs
, (char *)inode
, vid_to_vdi_oid(vid
),
1478 s
->inode
.nr_copies
, SD_INODE_HEADER_SIZE
, 0,
1484 if (inode
->vdi_id
!= s
->inode
.vdi_id
) {
1485 memcpy(&s
->inode
, inode
, SD_INODE_HEADER_SIZE
);
1495 static void coroutine_fn
resend_aioreq(BDRVSheepdogState
*s
, AIOReq
*aio_req
)
1497 SheepdogAIOCB
*acb
= aio_req
->aiocb
;
1499 aio_req
->create
= false;
1501 /* check whether this request becomes a CoW one */
1502 if (acb
->aiocb_type
== AIOCB_WRITE_UDATA
&& is_data_obj(aio_req
->oid
)) {
1503 int idx
= data_oid_to_idx(aio_req
->oid
);
1505 if (is_data_obj_writable(&s
->inode
, idx
)) {
1509 if (s
->inode
.data_vdi_id
[idx
]) {
1510 aio_req
->base_oid
= vid_to_data_oid(s
->inode
.data_vdi_id
[idx
], idx
);
1511 aio_req
->flags
|= SD_FLAG_CMD_COW
;
1513 aio_req
->create
= true;
1516 if (is_data_obj(aio_req
->oid
)) {
1517 add_aio_request(s
, aio_req
, acb
->qiov
->iov
, acb
->qiov
->niov
,
1521 iov
.iov_base
= &s
->inode
;
1522 iov
.iov_len
= sizeof(s
->inode
);
1523 add_aio_request(s
, aio_req
, &iov
, 1, AIOCB_WRITE_UDATA
);
1527 static void sd_detach_aio_context(BlockDriverState
*bs
)
1529 BDRVSheepdogState
*s
= bs
->opaque
;
1531 aio_set_fd_handler(s
->aio_context
, s
->fd
, false, NULL
,
1535 static void sd_attach_aio_context(BlockDriverState
*bs
,
1536 AioContext
*new_context
)
1538 BDRVSheepdogState
*s
= bs
->opaque
;
1540 s
->aio_context
= new_context
;
1541 aio_set_fd_handler(new_context
, s
->fd
, false,
1542 co_read_response
, NULL
, NULL
, s
);
1545 static QemuOptsList runtime_opts
= {
1547 .head
= QTAILQ_HEAD_INITIALIZER(runtime_opts
.head
),
1551 .type
= QEMU_OPT_STRING
,
1555 .type
= QEMU_OPT_NUMBER
,
1559 .type
= QEMU_OPT_STRING
,
1561 { /* end of list */ }
1565 static int sd_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
1570 BDRVSheepdogState
*s
= bs
->opaque
;
1571 const char *vdi
, *snap_id_str
, *tag
;
1575 Error
*local_err
= NULL
;
1578 s
->aio_context
= bdrv_get_aio_context(bs
);
1580 opts
= qemu_opts_create(&runtime_opts
, NULL
, 0, &error_abort
);
1581 qemu_opts_absorb_qdict(opts
, options
, &local_err
);
1583 error_propagate(errp
, local_err
);
1588 s
->addr
= sd_server_config(options
, errp
);
1594 vdi
= qemu_opt_get(opts
, "vdi");
1595 snap_id_str
= qemu_opt_get(opts
, "snap-id");
1596 snap_id
= qemu_opt_get_number(opts
, "snap-id", CURRENT_VDI_ID
);
1597 tag
= qemu_opt_get(opts
, "tag");
1600 error_setg(errp
, "parameter 'vdi' is missing");
1604 if (strlen(vdi
) >= SD_MAX_VDI_LEN
) {
1605 error_setg(errp
, "value of parameter 'vdi' is too long");
1610 if (snap_id
> UINT32_MAX
) {
1613 if (snap_id_str
&& !snap_id
) {
1614 error_setg(errp
, "'snap-id=%s' is not a valid snapshot ID",
1623 if (tag
&& strlen(tag
) >= SD_MAX_VDI_TAG_LEN
) {
1624 error_setg(errp
, "value of parameter 'tag' is too long");
1629 QLIST_INIT(&s
->inflight_aio_head
);
1630 QLIST_INIT(&s
->failed_aio_head
);
1631 QLIST_INIT(&s
->inflight_aiocb_head
);
1633 s
->fd
= get_sheep_fd(s
, errp
);
1639 ret
= find_vdi_name(s
, vdi
, (uint32_t)snap_id
, tag
, &vid
, true, errp
);
1645 * QEMU block layer emulates writethrough cache as 'writeback + flush', so
1646 * we always set SD_FLAG_CMD_CACHE (writeback cache) as default.
1648 s
->cache_flags
= SD_FLAG_CMD_CACHE
;
1649 if (flags
& BDRV_O_NOCACHE
) {
1650 s
->cache_flags
= SD_FLAG_CMD_DIRECT
;
1652 s
->discard_supported
= true;
1654 if (snap_id
|| tag
[0]) {
1655 DPRINTF("%" PRIx32
" snapshot inode was open.\n", vid
);
1656 s
->is_snapshot
= true;
1659 fd
= connect_to_sdog(s
, errp
);
1665 buf
= g_malloc(SD_INODE_SIZE
);
1666 ret
= read_object(fd
, s
->bs
, buf
, vid_to_vdi_oid(vid
),
1667 0, SD_INODE_SIZE
, 0, s
->cache_flags
);
1672 error_setg(errp
, "Can't read snapshot inode");
1676 memcpy(&s
->inode
, buf
, sizeof(s
->inode
));
1678 bs
->total_sectors
= s
->inode
.vdi_size
/ BDRV_SECTOR_SIZE
;
1679 pstrcpy(s
->name
, sizeof(s
->name
), vdi
);
1680 qemu_co_mutex_init(&s
->lock
);
1681 qemu_co_queue_init(&s
->overlapping_queue
);
1682 qemu_opts_del(opts
);
1687 aio_set_fd_handler(bdrv_get_aio_context(bs
), s
->fd
,
1688 false, NULL
, NULL
, NULL
, NULL
);
1691 qemu_opts_del(opts
);
1696 static int sd_reopen_prepare(BDRVReopenState
*state
, BlockReopenQueue
*queue
,
1699 BDRVSheepdogState
*s
= state
->bs
->opaque
;
1700 BDRVSheepdogReopenState
*re_s
;
1703 re_s
= state
->opaque
= g_new0(BDRVSheepdogReopenState
, 1);
1705 re_s
->cache_flags
= SD_FLAG_CMD_CACHE
;
1706 if (state
->flags
& BDRV_O_NOCACHE
) {
1707 re_s
->cache_flags
= SD_FLAG_CMD_DIRECT
;
1710 re_s
->fd
= get_sheep_fd(s
, errp
);
1719 static void sd_reopen_commit(BDRVReopenState
*state
)
1721 BDRVSheepdogReopenState
*re_s
= state
->opaque
;
1722 BDRVSheepdogState
*s
= state
->bs
->opaque
;
1725 aio_set_fd_handler(s
->aio_context
, s
->fd
, false,
1726 NULL
, NULL
, NULL
, NULL
);
1731 s
->cache_flags
= re_s
->cache_flags
;
1733 g_free(state
->opaque
);
1734 state
->opaque
= NULL
;
1739 static void sd_reopen_abort(BDRVReopenState
*state
)
1741 BDRVSheepdogReopenState
*re_s
= state
->opaque
;
1742 BDRVSheepdogState
*s
= state
->bs
->opaque
;
1749 aio_set_fd_handler(s
->aio_context
, re_s
->fd
, false,
1750 NULL
, NULL
, NULL
, NULL
);
1751 closesocket(re_s
->fd
);
1754 g_free(state
->opaque
);
1755 state
->opaque
= NULL
;
1760 static int do_sd_create(BDRVSheepdogState
*s
, uint32_t *vdi_id
, int snapshot
,
1764 SheepdogVdiRsp
*rsp
= (SheepdogVdiRsp
*)&hdr
;
1766 unsigned int wlen
, rlen
= 0;
1767 char buf
[SD_MAX_VDI_LEN
];
1769 fd
= connect_to_sdog(s
, errp
);
1774 /* FIXME: would it be better to fail (e.g., return -EIO) when filename
1775 * does not fit in buf? For now, just truncate and avoid buffer overrun.
1777 memset(buf
, 0, sizeof(buf
));
1778 pstrcpy(buf
, sizeof(buf
), s
->name
);
1780 memset(&hdr
, 0, sizeof(hdr
));
1781 hdr
.opcode
= SD_OP_NEW_VDI
;
1782 hdr
.base_vdi_id
= s
->inode
.vdi_id
;
1784 wlen
= SD_MAX_VDI_LEN
;
1786 hdr
.flags
= SD_FLAG_CMD_WRITE
;
1787 hdr
.snapid
= snapshot
;
1789 hdr
.data_length
= wlen
;
1790 hdr
.vdi_size
= s
->inode
.vdi_size
;
1791 hdr
.copy_policy
= s
->inode
.copy_policy
;
1792 hdr
.copies
= s
->inode
.nr_copies
;
1793 hdr
.block_size_shift
= s
->inode
.block_size_shift
;
1795 ret
= do_req(fd
, NULL
, (SheepdogReq
*)&hdr
, buf
, &wlen
, &rlen
);
1800 error_setg_errno(errp
, -ret
, "create failed");
1804 if (rsp
->result
!= SD_RES_SUCCESS
) {
1805 error_setg(errp
, "%s, %s", sd_strerror(rsp
->result
), s
->inode
.name
);
1810 *vdi_id
= rsp
->vdi_id
;
1816 static int sd_prealloc(const char *filename
, Error
**errp
)
1818 BlockBackend
*blk
= NULL
;
1819 BDRVSheepdogState
*base
= NULL
;
1820 unsigned long buf_size
;
1821 uint32_t idx
, max_idx
;
1822 uint32_t object_size
;
1827 blk
= blk_new_open(filename
, NULL
, NULL
,
1828 BDRV_O_RDWR
| BDRV_O_RESIZE
| BDRV_O_PROTOCOL
, errp
);
1831 goto out_with_err_set
;
1834 blk_set_allow_write_beyond_eof(blk
, true);
1836 vdi_size
= blk_getlength(blk
);
1842 base
= blk_bs(blk
)->opaque
;
1843 object_size
= (UINT32_C(1) << base
->inode
.block_size_shift
);
1844 buf_size
= MIN(object_size
, SD_DATA_OBJ_SIZE
);
1845 buf
= g_malloc0(buf_size
);
1847 max_idx
= DIV_ROUND_UP(vdi_size
, buf_size
);
1849 for (idx
= 0; idx
< max_idx
; idx
++) {
1851 * The created image can be a cloned image, so we need to read
1852 * a data from the source image.
1854 ret
= blk_pread(blk
, idx
* buf_size
, buf
, buf_size
);
1858 ret
= blk_pwrite(blk
, idx
* buf_size
, buf
, buf_size
, 0);
1867 error_setg_errno(errp
, -ret
, "Can't pre-allocate");
1879 * Sheepdog support two kinds of redundancy, full replication and erasure
1882 * # create a fully replicated vdi with x copies
1883 * -o redundancy=x (1 <= x <= SD_MAX_COPIES)
1885 * # create a erasure coded vdi with x data strips and y parity strips
1886 * -o redundancy=x:y (x must be one of {2,4,8,16} and 1 <= y < SD_EC_MAX_STRIP)
1888 static int parse_redundancy(BDRVSheepdogState
*s
, const char *opt
)
1890 struct SheepdogInode
*inode
= &s
->inode
;
1891 const char *n1
, *n2
;
1895 pstrcpy(p
, sizeof(p
), opt
);
1896 n1
= strtok(p
, ":");
1897 n2
= strtok(NULL
, ":");
1903 copy
= strtol(n1
, NULL
, 10);
1904 /* FIXME fix error checking by switching to qemu_strtol() */
1905 if (copy
> SD_MAX_COPIES
|| copy
< 1) {
1909 inode
->copy_policy
= 0;
1910 inode
->nr_copies
= copy
;
1914 if (copy
!= 2 && copy
!= 4 && copy
!= 8 && copy
!= 16) {
1918 parity
= strtol(n2
, NULL
, 10);
1919 /* FIXME fix error checking by switching to qemu_strtol() */
1920 if (parity
>= SD_EC_MAX_STRIP
|| parity
< 1) {
1925 * 4 bits for parity and 4 bits for data.
1926 * We have to compress upper data bits because it can't represent 16
1928 inode
->copy_policy
= ((copy
/ 2) << 4) + parity
;
1929 inode
->nr_copies
= copy
+ parity
;
1934 static int parse_block_size_shift(BDRVSheepdogState
*s
, QemuOpts
*opt
)
1936 struct SheepdogInode
*inode
= &s
->inode
;
1937 uint64_t object_size
;
1940 object_size
= qemu_opt_get_size_del(opt
, BLOCK_OPT_OBJECT_SIZE
, 0);
1942 if ((object_size
- 1) & object_size
) { /* not a power of 2? */
1945 obj_order
= ctz32(object_size
);
1946 if (obj_order
< 20 || obj_order
> 31) {
1949 inode
->block_size_shift
= (uint8_t)obj_order
;
1955 static int sd_create(const char *filename
, QemuOpts
*opts
,
1961 char *backing_file
= NULL
;
1963 BDRVSheepdogState
*s
;
1965 uint64_t max_vdi_size
;
1966 bool prealloc
= false;
1968 s
= g_new0(BDRVSheepdogState
, 1);
1970 if (strstr(filename
, "://")) {
1971 sd_parse_uri(&cfg
, filename
, &err
);
1973 parse_vdiname(&cfg
, filename
, &err
);
1976 error_propagate(errp
, err
);
1980 buf
= cfg
.port
? g_strdup_printf("%d", cfg
.port
) : NULL
;
1981 s
->addr
= sd_socket_address(cfg
.path
, cfg
.host
, buf
);
1983 strcpy(s
->name
, cfg
.vdi
);
1984 sd_config_done(&cfg
);
1986 s
->inode
.vdi_size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
1988 backing_file
= qemu_opt_get_del(opts
, BLOCK_OPT_BACKING_FILE
);
1989 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_PREALLOC
);
1990 if (!buf
|| !strcmp(buf
, "off")) {
1992 } else if (!strcmp(buf
, "full")) {
1995 error_setg(errp
, "Invalid preallocation mode: '%s'", buf
);
2001 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_REDUNDANCY
);
2003 ret
= parse_redundancy(s
, buf
);
2005 error_setg(errp
, "Invalid redundancy mode: '%s'", buf
);
2009 ret
= parse_block_size_shift(s
, opts
);
2011 error_setg(errp
, "Invalid object_size."
2012 " obect_size needs to be power of 2"
2013 " and be limited from 2^20 to 2^31");
2019 BDRVSheepdogState
*base
;
2022 /* Currently, only Sheepdog backing image is supported. */
2023 drv
= bdrv_find_protocol(backing_file
, true, NULL
);
2024 if (!drv
|| strcmp(drv
->protocol_name
, "sheepdog") != 0) {
2025 error_setg(errp
, "backing_file must be a sheepdog image");
2030 blk
= blk_new_open(backing_file
, NULL
, NULL
,
2031 BDRV_O_PROTOCOL
, errp
);
2037 base
= blk_bs(blk
)->opaque
;
2039 if (!is_snapshot(&base
->inode
)) {
2040 error_setg(errp
, "cannot clone from a non snapshot vdi");
2045 s
->inode
.vdi_id
= base
->inode
.vdi_id
;
2049 s
->aio_context
= qemu_get_aio_context();
2051 /* if block_size_shift is not specified, get cluster default value */
2052 if (s
->inode
.block_size_shift
== 0) {
2054 SheepdogClusterRsp
*rsp
= (SheepdogClusterRsp
*)&hdr
;
2056 unsigned int wlen
= 0, rlen
= 0;
2058 fd
= connect_to_sdog(s
, errp
);
2064 memset(&hdr
, 0, sizeof(hdr
));
2065 hdr
.opcode
= SD_OP_GET_CLUSTER_DEFAULT
;
2066 hdr
.proto_ver
= SD_PROTO_VER
;
2068 ret
= do_req(fd
, NULL
, (SheepdogReq
*)&hdr
,
2069 NULL
, &wlen
, &rlen
);
2072 error_setg_errno(errp
, -ret
, "failed to get cluster default");
2075 if (rsp
->result
== SD_RES_SUCCESS
) {
2076 s
->inode
.block_size_shift
= rsp
->block_size_shift
;
2078 s
->inode
.block_size_shift
= SD_DEFAULT_BLOCK_SIZE_SHIFT
;
2082 max_vdi_size
= (UINT64_C(1) << s
->inode
.block_size_shift
) * MAX_DATA_OBJS
;
2084 if (s
->inode
.vdi_size
> max_vdi_size
) {
2085 error_setg(errp
, "An image is too large."
2086 " The maximum image size is %"PRIu64
"GB",
2087 max_vdi_size
/ 1024 / 1024 / 1024);
2092 ret
= do_sd_create(s
, &vid
, 0, errp
);
2098 ret
= sd_prealloc(filename
, errp
);
2101 g_free(backing_file
);
2107 static void sd_close(BlockDriverState
*bs
)
2109 Error
*local_err
= NULL
;
2110 BDRVSheepdogState
*s
= bs
->opaque
;
2112 SheepdogVdiRsp
*rsp
= (SheepdogVdiRsp
*)&hdr
;
2113 unsigned int wlen
, rlen
= 0;
2116 DPRINTF("%s\n", s
->name
);
2118 fd
= connect_to_sdog(s
, &local_err
);
2120 error_report_err(local_err
);
2124 memset(&hdr
, 0, sizeof(hdr
));
2126 hdr
.opcode
= SD_OP_RELEASE_VDI
;
2127 hdr
.type
= LOCK_TYPE_NORMAL
;
2128 hdr
.base_vdi_id
= s
->inode
.vdi_id
;
2129 wlen
= strlen(s
->name
) + 1;
2130 hdr
.data_length
= wlen
;
2131 hdr
.flags
= SD_FLAG_CMD_WRITE
;
2133 ret
= do_req(fd
, s
->bs
, (SheepdogReq
*)&hdr
,
2134 s
->name
, &wlen
, &rlen
);
2138 if (!ret
&& rsp
->result
!= SD_RES_SUCCESS
&&
2139 rsp
->result
!= SD_RES_VDI_NOT_LOCKED
) {
2140 error_report("%s, %s", sd_strerror(rsp
->result
), s
->name
);
2143 aio_set_fd_handler(bdrv_get_aio_context(bs
), s
->fd
,
2144 false, NULL
, NULL
, NULL
, NULL
);
2146 qapi_free_SocketAddress(s
->addr
);
2149 static int64_t sd_getlength(BlockDriverState
*bs
)
2151 BDRVSheepdogState
*s
= bs
->opaque
;
2153 return s
->inode
.vdi_size
;
2156 static int sd_truncate(BlockDriverState
*bs
, int64_t offset
,
2157 PreallocMode prealloc
, Error
**errp
)
2159 BDRVSheepdogState
*s
= bs
->opaque
;
2161 unsigned int datalen
;
2162 uint64_t max_vdi_size
;
2164 if (prealloc
!= PREALLOC_MODE_OFF
) {
2165 error_setg(errp
, "Unsupported preallocation mode '%s'",
2166 PreallocMode_lookup
[prealloc
]);
2170 max_vdi_size
= (UINT64_C(1) << s
->inode
.block_size_shift
) * MAX_DATA_OBJS
;
2171 if (offset
< s
->inode
.vdi_size
) {
2172 error_setg(errp
, "shrinking is not supported");
2174 } else if (offset
> max_vdi_size
) {
2175 error_setg(errp
, "too big image size");
2179 fd
= connect_to_sdog(s
, errp
);
2184 /* we don't need to update entire object */
2185 datalen
= SD_INODE_SIZE
- sizeof(s
->inode
.data_vdi_id
);
2186 s
->inode
.vdi_size
= offset
;
2187 ret
= write_object(fd
, s
->bs
, (char *)&s
->inode
,
2188 vid_to_vdi_oid(s
->inode
.vdi_id
), s
->inode
.nr_copies
,
2189 datalen
, 0, false, s
->cache_flags
);
2193 error_setg_errno(errp
, -ret
, "failed to update an inode");
2200 * This function is called after writing data objects. If we need to
2201 * update metadata, this sends a write request to the vdi object.
2203 static void coroutine_fn
sd_write_done(SheepdogAIOCB
*acb
)
2205 BDRVSheepdogState
*s
= acb
->s
;
2208 uint32_t offset
, data_len
, mn
, mx
;
2210 mn
= acb
->min_dirty_data_idx
;
2211 mx
= acb
->max_dirty_data_idx
;
2213 /* we need to update the vdi object. */
2215 offset
= sizeof(s
->inode
) - sizeof(s
->inode
.data_vdi_id
) +
2216 mn
* sizeof(s
->inode
.data_vdi_id
[0]);
2217 data_len
= (mx
- mn
+ 1) * sizeof(s
->inode
.data_vdi_id
[0]);
2219 acb
->min_dirty_data_idx
= UINT32_MAX
;
2220 acb
->max_dirty_data_idx
= 0;
2222 iov
.iov_base
= &s
->inode
;
2223 iov
.iov_len
= sizeof(s
->inode
);
2224 aio_req
= alloc_aio_req(s
, acb
, vid_to_vdi_oid(s
->inode
.vdi_id
),
2225 data_len
, offset
, 0, false, 0, offset
);
2226 add_aio_request(s
, aio_req
, &iov
, 1, AIOCB_WRITE_UDATA
);
2227 if (--acb
->nr_pending
) {
2228 qemu_coroutine_yield();
2233 /* Delete current working VDI on the snapshot chain */
2234 static bool sd_delete(BDRVSheepdogState
*s
)
2236 Error
*local_err
= NULL
;
2237 unsigned int wlen
= SD_MAX_VDI_LEN
, rlen
= 0;
2238 SheepdogVdiReq hdr
= {
2239 .opcode
= SD_OP_DEL_VDI
,
2240 .base_vdi_id
= s
->inode
.vdi_id
,
2241 .data_length
= wlen
,
2242 .flags
= SD_FLAG_CMD_WRITE
,
2244 SheepdogVdiRsp
*rsp
= (SheepdogVdiRsp
*)&hdr
;
2247 fd
= connect_to_sdog(s
, &local_err
);
2249 error_report_err(local_err
);
2253 ret
= do_req(fd
, s
->bs
, (SheepdogReq
*)&hdr
,
2254 s
->name
, &wlen
, &rlen
);
2259 switch (rsp
->result
) {
2261 error_report("%s was already deleted", s
->name
);
2263 case SD_RES_SUCCESS
:
2266 error_report("%s, %s", sd_strerror(rsp
->result
), s
->name
);
2274 * Create a writable VDI from a snapshot
2276 static int sd_create_branch(BDRVSheepdogState
*s
)
2278 Error
*local_err
= NULL
;
2284 DPRINTF("%" PRIx32
" is snapshot.\n", s
->inode
.vdi_id
);
2286 buf
= g_malloc(SD_INODE_SIZE
);
2289 * Even If deletion fails, we will just create extra snapshot based on
2290 * the working VDI which was supposed to be deleted. So no need to
2293 deleted
= sd_delete(s
);
2294 ret
= do_sd_create(s
, &vid
, !deleted
, &local_err
);
2296 error_report_err(local_err
);
2300 DPRINTF("%" PRIx32
" is created.\n", vid
);
2302 fd
= connect_to_sdog(s
, &local_err
);
2304 error_report_err(local_err
);
2309 ret
= read_object(fd
, s
->bs
, buf
, vid_to_vdi_oid(vid
),
2310 s
->inode
.nr_copies
, SD_INODE_SIZE
, 0, s
->cache_flags
);
2318 memcpy(&s
->inode
, buf
, sizeof(s
->inode
));
2320 s
->is_snapshot
= false;
2322 DPRINTF("%" PRIx32
" was newly created.\n", s
->inode
.vdi_id
);
2331 * Send I/O requests to the server.
2333 * This function sends requests to the server, links the requests to
2334 * the inflight_list in BDRVSheepdogState, and exits without
2335 * waiting the response. The responses are received in the
2336 * `aio_read_response' function which is called from the main loop as
2339 * Returns 1 when we need to wait a response, 0 when there is no sent
2340 * request and -errno in error cases.
2342 static void coroutine_fn
sd_co_rw_vector(SheepdogAIOCB
*acb
)
2345 unsigned long len
, done
= 0, total
= acb
->nb_sectors
* BDRV_SECTOR_SIZE
;
2347 uint32_t object_size
;
2350 BDRVSheepdogState
*s
= acb
->s
;
2351 SheepdogInode
*inode
= &s
->inode
;
2354 if (acb
->aiocb_type
== AIOCB_WRITE_UDATA
&& s
->is_snapshot
) {
2356 * In the case we open the snapshot VDI, Sheepdog creates the
2357 * writable VDI when we do a write operation first.
2359 ret
= sd_create_branch(s
);
2366 object_size
= (UINT32_C(1) << inode
->block_size_shift
);
2367 idx
= acb
->sector_num
* BDRV_SECTOR_SIZE
/ object_size
;
2368 offset
= (acb
->sector_num
* BDRV_SECTOR_SIZE
) % object_size
;
2371 * Make sure we don't free the aiocb before we are done with all requests.
2372 * This additional reference is dropped at the end of this function.
2376 while (done
!= total
) {
2378 uint64_t old_oid
= 0;
2379 bool create
= false;
2381 oid
= vid_to_data_oid(inode
->data_vdi_id
[idx
], idx
);
2383 len
= MIN(total
- done
, object_size
- offset
);
2385 switch (acb
->aiocb_type
) {
2386 case AIOCB_READ_UDATA
:
2387 if (!inode
->data_vdi_id
[idx
]) {
2388 qemu_iovec_memset(acb
->qiov
, done
, 0, len
);
2392 case AIOCB_WRITE_UDATA
:
2393 if (!inode
->data_vdi_id
[idx
]) {
2395 } else if (!is_data_obj_writable(inode
, idx
)) {
2399 flags
= SD_FLAG_CMD_COW
;
2402 case AIOCB_DISCARD_OBJ
:
2404 * We discard the object only when the whole object is
2405 * 1) allocated 2) trimmed. Otherwise, simply skip it.
2407 if (len
!= object_size
|| inode
->data_vdi_id
[idx
] == 0) {
2416 DPRINTF("update ino (%" PRIu32
") %" PRIu64
" %" PRIu64
" %ld\n",
2418 vid_to_data_oid(inode
->data_vdi_id
[idx
], idx
), idx
);
2419 oid
= vid_to_data_oid(inode
->vdi_id
, idx
);
2420 DPRINTF("new oid %" PRIx64
"\n", oid
);
2423 aio_req
= alloc_aio_req(s
, acb
, oid
, len
, offset
, flags
, create
,
2425 acb
->aiocb_type
== AIOCB_DISCARD_OBJ
?
2427 add_aio_request(s
, aio_req
, acb
->qiov
->iov
, acb
->qiov
->niov
,
2434 if (--acb
->nr_pending
) {
2435 qemu_coroutine_yield();
2439 static void sd_aio_complete(SheepdogAIOCB
*acb
)
2441 if (acb
->aiocb_type
== AIOCB_FLUSH_CACHE
) {
2445 QLIST_REMOVE(acb
, aiocb_siblings
);
2446 qemu_co_queue_restart_all(&acb
->s
->overlapping_queue
);
2449 static coroutine_fn
int sd_co_writev(BlockDriverState
*bs
, int64_t sector_num
,
2450 int nb_sectors
, QEMUIOVector
*qiov
)
2454 int64_t offset
= (sector_num
+ nb_sectors
) * BDRV_SECTOR_SIZE
;
2455 BDRVSheepdogState
*s
= bs
->opaque
;
2457 if (offset
> s
->inode
.vdi_size
) {
2458 ret
= sd_truncate(bs
, offset
, PREALLOC_MODE_OFF
, NULL
);
2464 sd_aio_setup(&acb
, s
, qiov
, sector_num
, nb_sectors
, AIOCB_WRITE_UDATA
);
2465 sd_co_rw_vector(&acb
);
2466 sd_write_done(&acb
);
2467 sd_aio_complete(&acb
);
2472 static coroutine_fn
int sd_co_readv(BlockDriverState
*bs
, int64_t sector_num
,
2473 int nb_sectors
, QEMUIOVector
*qiov
)
2476 BDRVSheepdogState
*s
= bs
->opaque
;
2478 sd_aio_setup(&acb
, s
, qiov
, sector_num
, nb_sectors
, AIOCB_READ_UDATA
);
2479 sd_co_rw_vector(&acb
);
2480 sd_aio_complete(&acb
);
2485 static int coroutine_fn
sd_co_flush_to_disk(BlockDriverState
*bs
)
2487 BDRVSheepdogState
*s
= bs
->opaque
;
2491 if (s
->cache_flags
!= SD_FLAG_CMD_CACHE
) {
2495 sd_aio_setup(&acb
, s
, NULL
, 0, 0, AIOCB_FLUSH_CACHE
);
2498 aio_req
= alloc_aio_req(s
, &acb
, vid_to_vdi_oid(s
->inode
.vdi_id
),
2499 0, 0, 0, false, 0, 0);
2500 add_aio_request(s
, aio_req
, NULL
, 0, acb
.aiocb_type
);
2502 if (--acb
.nr_pending
) {
2503 qemu_coroutine_yield();
2506 sd_aio_complete(&acb
);
2510 static int sd_snapshot_create(BlockDriverState
*bs
, QEMUSnapshotInfo
*sn_info
)
2512 Error
*local_err
= NULL
;
2513 BDRVSheepdogState
*s
= bs
->opaque
;
2516 SheepdogInode
*inode
;
2517 unsigned int datalen
;
2519 DPRINTF("sn_info: name %s id_str %s s: name %s vm_state_size %" PRId64
" "
2520 "is_snapshot %d\n", sn_info
->name
, sn_info
->id_str
,
2521 s
->name
, sn_info
->vm_state_size
, s
->is_snapshot
);
2523 if (s
->is_snapshot
) {
2524 error_report("You can't create a snapshot of a snapshot VDI, "
2525 "%s (%" PRIu32
").", s
->name
, s
->inode
.vdi_id
);
2530 DPRINTF("%s %s\n", sn_info
->name
, sn_info
->id_str
);
2532 s
->inode
.vm_state_size
= sn_info
->vm_state_size
;
2533 s
->inode
.vm_clock_nsec
= sn_info
->vm_clock_nsec
;
2534 /* It appears that inode.tag does not require a NUL terminator,
2535 * which means this use of strncpy is ok.
2537 strncpy(s
->inode
.tag
, sn_info
->name
, sizeof(s
->inode
.tag
));
2538 /* we don't need to update entire object */
2539 datalen
= SD_INODE_SIZE
- sizeof(s
->inode
.data_vdi_id
);
2540 inode
= g_malloc(datalen
);
2542 /* refresh inode. */
2543 fd
= connect_to_sdog(s
, &local_err
);
2545 error_report_err(local_err
);
2550 ret
= write_object(fd
, s
->bs
, (char *)&s
->inode
,
2551 vid_to_vdi_oid(s
->inode
.vdi_id
), s
->inode
.nr_copies
,
2552 datalen
, 0, false, s
->cache_flags
);
2554 error_report("failed to write snapshot's inode.");
2558 ret
= do_sd_create(s
, &new_vid
, 1, &local_err
);
2560 error_reportf_err(local_err
,
2561 "failed to create inode for snapshot: ");
2565 ret
= read_object(fd
, s
->bs
, (char *)inode
,
2566 vid_to_vdi_oid(new_vid
), s
->inode
.nr_copies
, datalen
, 0,
2570 error_report("failed to read new inode info. %s", strerror(errno
));
2574 memcpy(&s
->inode
, inode
, datalen
);
2575 DPRINTF("s->inode: name %s snap_id %x oid %x\n",
2576 s
->inode
.name
, s
->inode
.snap_id
, s
->inode
.vdi_id
);
2585 * We implement rollback(loadvm) operation to the specified snapshot by
2586 * 1) switch to the snapshot
2587 * 2) rely on sd_create_branch to delete working VDI and
2588 * 3) create a new working VDI based on the specified snapshot
2590 static int sd_snapshot_goto(BlockDriverState
*bs
, const char *snapshot_id
)
2592 BDRVSheepdogState
*s
= bs
->opaque
;
2593 BDRVSheepdogState
*old_s
;
2594 char tag
[SD_MAX_VDI_TAG_LEN
];
2595 uint32_t snapid
= 0;
2598 if (!sd_parse_snapid_or_tag(snapshot_id
, &snapid
, tag
)) {
2602 old_s
= g_new(BDRVSheepdogState
, 1);
2604 memcpy(old_s
, s
, sizeof(BDRVSheepdogState
));
2606 ret
= reload_inode(s
, snapid
, tag
);
2611 ret
= sd_create_branch(s
);
2620 /* recover bdrv_sd_state */
2621 memcpy(s
, old_s
, sizeof(BDRVSheepdogState
));
2624 error_report("failed to open. recover old bdrv_sd_state.");
2629 #define NR_BATCHED_DISCARD 128
2631 static int remove_objects(BDRVSheepdogState
*s
, Error
**errp
)
2633 int fd
, i
= 0, nr_objs
= 0;
2635 SheepdogInode
*inode
= &s
->inode
;
2637 fd
= connect_to_sdog(s
, errp
);
2642 nr_objs
= count_data_objs(inode
);
2643 while (i
< nr_objs
) {
2644 int start_idx
, nr_filled_idx
;
2646 while (i
< nr_objs
&& !inode
->data_vdi_id
[i
]) {
2652 while (i
< nr_objs
&& nr_filled_idx
< NR_BATCHED_DISCARD
) {
2653 if (inode
->data_vdi_id
[i
]) {
2654 inode
->data_vdi_id
[i
] = 0;
2661 ret
= write_object(fd
, s
->bs
,
2662 (char *)&inode
->data_vdi_id
[start_idx
],
2663 vid_to_vdi_oid(s
->inode
.vdi_id
), inode
->nr_copies
,
2664 (i
- start_idx
) * sizeof(uint32_t),
2665 offsetof(struct SheepdogInode
,
2666 data_vdi_id
[start_idx
]),
2667 false, s
->cache_flags
);
2669 error_setg(errp
, "Failed to discard snapshot inode");
2680 static int sd_snapshot_delete(BlockDriverState
*bs
,
2681 const char *snapshot_id
,
2686 * FIXME should delete the snapshot matching both @snapshot_id and
2687 * @name, but @name not used here
2689 unsigned long snap_id
= 0;
2690 char snap_tag
[SD_MAX_VDI_TAG_LEN
];
2692 char buf
[SD_MAX_VDI_LEN
+ SD_MAX_VDI_TAG_LEN
];
2693 BDRVSheepdogState
*s
= bs
->opaque
;
2694 unsigned int wlen
= SD_MAX_VDI_LEN
+ SD_MAX_VDI_TAG_LEN
, rlen
= 0;
2696 SheepdogVdiReq hdr
= {
2697 .opcode
= SD_OP_DEL_VDI
,
2698 .data_length
= wlen
,
2699 .flags
= SD_FLAG_CMD_WRITE
,
2701 SheepdogVdiRsp
*rsp
= (SheepdogVdiRsp
*)&hdr
;
2703 ret
= remove_objects(s
, errp
);
2708 memset(buf
, 0, sizeof(buf
));
2709 memset(snap_tag
, 0, sizeof(snap_tag
));
2710 pstrcpy(buf
, SD_MAX_VDI_LEN
, s
->name
);
2711 /* TODO Use sd_parse_snapid() once this mess is cleaned up */
2712 ret
= qemu_strtoul(snapshot_id
, NULL
, 10, &snap_id
);
2713 if (ret
|| snap_id
> UINT32_MAX
) {
2715 * FIXME Since qemu_strtoul() returns -EINVAL when
2716 * @snapshot_id is null, @snapshot_id is mandatory. Correct
2717 * would be to require at least one of @snapshot_id and @name.
2719 error_setg(errp
, "Invalid snapshot ID: %s",
2720 snapshot_id
? snapshot_id
: "<null>");
2725 hdr
.snapid
= (uint32_t) snap_id
;
2727 /* FIXME I suspect we should use @name here */
2728 /* FIXME don't truncate silently */
2729 pstrcpy(snap_tag
, sizeof(snap_tag
), snapshot_id
);
2730 pstrcpy(buf
+ SD_MAX_VDI_LEN
, SD_MAX_VDI_TAG_LEN
, snap_tag
);
2733 ret
= find_vdi_name(s
, s
->name
, snap_id
, snap_tag
, &vid
, true, errp
);
2738 fd
= connect_to_sdog(s
, errp
);
2743 ret
= do_req(fd
, s
->bs
, (SheepdogReq
*)&hdr
,
2747 error_setg_errno(errp
, -ret
, "Couldn't send request to server");
2751 switch (rsp
->result
) {
2753 error_setg(errp
, "Can't find the snapshot");
2755 case SD_RES_SUCCESS
:
2758 error_setg(errp
, "%s", sd_strerror(rsp
->result
));
2765 static int sd_snapshot_list(BlockDriverState
*bs
, QEMUSnapshotInfo
**psn_tab
)
2767 Error
*local_err
= NULL
;
2768 BDRVSheepdogState
*s
= bs
->opaque
;
2770 int fd
, nr
= 1024, ret
, max
= BITS_TO_LONGS(SD_NR_VDIS
) * sizeof(long);
2771 QEMUSnapshotInfo
*sn_tab
= NULL
;
2772 unsigned wlen
, rlen
;
2774 static SheepdogInode inode
;
2775 unsigned long *vdi_inuse
;
2776 unsigned int start_nr
;
2780 vdi_inuse
= g_malloc(max
);
2782 fd
= connect_to_sdog(s
, &local_err
);
2784 error_report_err(local_err
);
2792 memset(&req
, 0, sizeof(req
));
2794 req
.opcode
= SD_OP_READ_VDIS
;
2795 req
.data_length
= max
;
2797 ret
= do_req(fd
, s
->bs
, &req
, vdi_inuse
, &wlen
, &rlen
);
2804 sn_tab
= g_new0(QEMUSnapshotInfo
, nr
);
2806 /* calculate a vdi id with hash function */
2807 hval
= fnv_64a_buf(s
->name
, strlen(s
->name
), FNV1A_64_INIT
);
2808 start_nr
= hval
& (SD_NR_VDIS
- 1);
2810 fd
= connect_to_sdog(s
, &local_err
);
2812 error_report_err(local_err
);
2817 for (vid
= start_nr
; found
< nr
; vid
= (vid
+ 1) % SD_NR_VDIS
) {
2818 if (!test_bit(vid
, vdi_inuse
)) {
2822 /* we don't need to read entire object */
2823 ret
= read_object(fd
, s
->bs
, (char *)&inode
,
2824 vid_to_vdi_oid(vid
),
2825 0, SD_INODE_SIZE
- sizeof(inode
.data_vdi_id
), 0,
2832 if (!strcmp(inode
.name
, s
->name
) && is_snapshot(&inode
)) {
2833 sn_tab
[found
].date_sec
= inode
.snap_ctime
>> 32;
2834 sn_tab
[found
].date_nsec
= inode
.snap_ctime
& 0xffffffff;
2835 sn_tab
[found
].vm_state_size
= inode
.vm_state_size
;
2836 sn_tab
[found
].vm_clock_nsec
= inode
.vm_clock_nsec
;
2838 snprintf(sn_tab
[found
].id_str
, sizeof(sn_tab
[found
].id_str
),
2839 "%" PRIu32
, inode
.snap_id
);
2840 pstrcpy(sn_tab
[found
].name
,
2841 MIN(sizeof(sn_tab
[found
].name
), sizeof(inode
.tag
)),
2860 static int do_load_save_vmstate(BDRVSheepdogState
*s
, uint8_t *data
,
2861 int64_t pos
, int size
, int load
)
2863 Error
*local_err
= NULL
;
2865 int fd
, ret
= 0, remaining
= size
;
2866 unsigned int data_len
;
2867 uint64_t vmstate_oid
;
2870 uint32_t vdi_id
= load
? s
->inode
.parent_vdi_id
: s
->inode
.vdi_id
;
2871 uint32_t object_size
= (UINT32_C(1) << s
->inode
.block_size_shift
);
2873 fd
= connect_to_sdog(s
, &local_err
);
2875 error_report_err(local_err
);
2880 vdi_index
= pos
/ object_size
;
2881 offset
= pos
% object_size
;
2883 data_len
= MIN(remaining
, object_size
- offset
);
2885 vmstate_oid
= vid_to_vmstate_oid(vdi_id
, vdi_index
);
2887 create
= (offset
== 0);
2889 ret
= read_object(fd
, s
->bs
, (char *)data
, vmstate_oid
,
2890 s
->inode
.nr_copies
, data_len
, offset
,
2893 ret
= write_object(fd
, s
->bs
, (char *)data
, vmstate_oid
,
2894 s
->inode
.nr_copies
, data_len
, offset
, create
,
2899 error_report("failed to save vmstate %s", strerror(errno
));
2905 remaining
-= data_len
;
2913 static int sd_save_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
,
2916 BDRVSheepdogState
*s
= bs
->opaque
;
2920 buf
= qemu_blockalign(bs
, qiov
->size
);
2921 qemu_iovec_to_buf(qiov
, 0, buf
, qiov
->size
);
2922 ret
= do_load_save_vmstate(s
, (uint8_t *) buf
, pos
, qiov
->size
, 0);
2928 static int sd_load_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
,
2931 BDRVSheepdogState
*s
= bs
->opaque
;
2935 buf
= qemu_blockalign(bs
, qiov
->size
);
2936 ret
= do_load_save_vmstate(s
, buf
, pos
, qiov
->size
, 1);
2937 qemu_iovec_from_buf(qiov
, 0, buf
, qiov
->size
);
2944 static coroutine_fn
int sd_co_pdiscard(BlockDriverState
*bs
, int64_t offset
,
2948 BDRVSheepdogState
*s
= bs
->opaque
;
2949 QEMUIOVector discard_iov
;
2953 if (!s
->discard_supported
) {
2957 memset(&discard_iov
, 0, sizeof(discard_iov
));
2958 memset(&iov
, 0, sizeof(iov
));
2959 iov
.iov_base
= &zero
;
2960 iov
.iov_len
= sizeof(zero
);
2961 discard_iov
.iov
= &iov
;
2962 discard_iov
.niov
= 1;
2963 if (!QEMU_IS_ALIGNED(offset
| bytes
, BDRV_SECTOR_SIZE
)) {
2966 sd_aio_setup(&acb
, s
, &discard_iov
, offset
>> BDRV_SECTOR_BITS
,
2967 bytes
>> BDRV_SECTOR_BITS
, AIOCB_DISCARD_OBJ
);
2968 sd_co_rw_vector(&acb
);
2969 sd_aio_complete(&acb
);
2974 static coroutine_fn
int64_t
2975 sd_co_get_block_status(BlockDriverState
*bs
, int64_t sector_num
, int nb_sectors
,
2976 int *pnum
, BlockDriverState
**file
)
2978 BDRVSheepdogState
*s
= bs
->opaque
;
2979 SheepdogInode
*inode
= &s
->inode
;
2980 uint32_t object_size
= (UINT32_C(1) << inode
->block_size_shift
);
2981 uint64_t offset
= sector_num
* BDRV_SECTOR_SIZE
;
2982 unsigned long start
= offset
/ object_size
,
2983 end
= DIV_ROUND_UP((sector_num
+ nb_sectors
) *
2984 BDRV_SECTOR_SIZE
, object_size
);
2986 int64_t ret
= BDRV_BLOCK_DATA
| BDRV_BLOCK_OFFSET_VALID
| offset
;
2988 for (idx
= start
; idx
< end
; idx
++) {
2989 if (inode
->data_vdi_id
[idx
] == 0) {
2994 /* Get the longest length of unallocated sectors */
2996 for (idx
= start
+ 1; idx
< end
; idx
++) {
2997 if (inode
->data_vdi_id
[idx
] != 0) {
3003 *pnum
= (idx
- start
) * object_size
/ BDRV_SECTOR_SIZE
;
3004 if (*pnum
> nb_sectors
) {
3007 if (ret
> 0 && ret
& BDRV_BLOCK_OFFSET_VALID
) {
3013 static int64_t sd_get_allocated_file_size(BlockDriverState
*bs
)
3015 BDRVSheepdogState
*s
= bs
->opaque
;
3016 SheepdogInode
*inode
= &s
->inode
;
3017 uint32_t object_size
= (UINT32_C(1) << inode
->block_size_shift
);
3018 unsigned long i
, last
= DIV_ROUND_UP(inode
->vdi_size
, object_size
);
3021 for (i
= 0; i
< last
; i
++) {
3022 if (inode
->data_vdi_id
[i
] == 0) {
3025 size
+= object_size
;
3030 static QemuOptsList sd_create_opts
= {
3031 .name
= "sheepdog-create-opts",
3032 .head
= QTAILQ_HEAD_INITIALIZER(sd_create_opts
.head
),
3035 .name
= BLOCK_OPT_SIZE
,
3036 .type
= QEMU_OPT_SIZE
,
3037 .help
= "Virtual disk size"
3040 .name
= BLOCK_OPT_BACKING_FILE
,
3041 .type
= QEMU_OPT_STRING
,
3042 .help
= "File name of a base image"
3045 .name
= BLOCK_OPT_PREALLOC
,
3046 .type
= QEMU_OPT_STRING
,
3047 .help
= "Preallocation mode (allowed values: off, full)"
3050 .name
= BLOCK_OPT_REDUNDANCY
,
3051 .type
= QEMU_OPT_STRING
,
3052 .help
= "Redundancy of the image"
3055 .name
= BLOCK_OPT_OBJECT_SIZE
,
3056 .type
= QEMU_OPT_SIZE
,
3057 .help
= "Object size of the image"
3059 { /* end of list */ }
3063 static BlockDriver bdrv_sheepdog
= {
3064 .format_name
= "sheepdog",
3065 .protocol_name
= "sheepdog",
3066 .instance_size
= sizeof(BDRVSheepdogState
),
3067 .bdrv_parse_filename
= sd_parse_filename
,
3068 .bdrv_file_open
= sd_open
,
3069 .bdrv_reopen_prepare
= sd_reopen_prepare
,
3070 .bdrv_reopen_commit
= sd_reopen_commit
,
3071 .bdrv_reopen_abort
= sd_reopen_abort
,
3072 .bdrv_close
= sd_close
,
3073 .bdrv_create
= sd_create
,
3074 .bdrv_has_zero_init
= bdrv_has_zero_init_1
,
3075 .bdrv_getlength
= sd_getlength
,
3076 .bdrv_get_allocated_file_size
= sd_get_allocated_file_size
,
3077 .bdrv_truncate
= sd_truncate
,
3079 .bdrv_co_readv
= sd_co_readv
,
3080 .bdrv_co_writev
= sd_co_writev
,
3081 .bdrv_co_flush_to_disk
= sd_co_flush_to_disk
,
3082 .bdrv_co_pdiscard
= sd_co_pdiscard
,
3083 .bdrv_co_get_block_status
= sd_co_get_block_status
,
3085 .bdrv_snapshot_create
= sd_snapshot_create
,
3086 .bdrv_snapshot_goto
= sd_snapshot_goto
,
3087 .bdrv_snapshot_delete
= sd_snapshot_delete
,
3088 .bdrv_snapshot_list
= sd_snapshot_list
,
3090 .bdrv_save_vmstate
= sd_save_vmstate
,
3091 .bdrv_load_vmstate
= sd_load_vmstate
,
3093 .bdrv_detach_aio_context
= sd_detach_aio_context
,
3094 .bdrv_attach_aio_context
= sd_attach_aio_context
,
3096 .create_opts
= &sd_create_opts
,
3099 static BlockDriver bdrv_sheepdog_tcp
= {
3100 .format_name
= "sheepdog",
3101 .protocol_name
= "sheepdog+tcp",
3102 .instance_size
= sizeof(BDRVSheepdogState
),
3103 .bdrv_parse_filename
= sd_parse_filename
,
3104 .bdrv_file_open
= sd_open
,
3105 .bdrv_reopen_prepare
= sd_reopen_prepare
,
3106 .bdrv_reopen_commit
= sd_reopen_commit
,
3107 .bdrv_reopen_abort
= sd_reopen_abort
,
3108 .bdrv_close
= sd_close
,
3109 .bdrv_create
= sd_create
,
3110 .bdrv_has_zero_init
= bdrv_has_zero_init_1
,
3111 .bdrv_getlength
= sd_getlength
,
3112 .bdrv_get_allocated_file_size
= sd_get_allocated_file_size
,
3113 .bdrv_truncate
= sd_truncate
,
3115 .bdrv_co_readv
= sd_co_readv
,
3116 .bdrv_co_writev
= sd_co_writev
,
3117 .bdrv_co_flush_to_disk
= sd_co_flush_to_disk
,
3118 .bdrv_co_pdiscard
= sd_co_pdiscard
,
3119 .bdrv_co_get_block_status
= sd_co_get_block_status
,
3121 .bdrv_snapshot_create
= sd_snapshot_create
,
3122 .bdrv_snapshot_goto
= sd_snapshot_goto
,
3123 .bdrv_snapshot_delete
= sd_snapshot_delete
,
3124 .bdrv_snapshot_list
= sd_snapshot_list
,
3126 .bdrv_save_vmstate
= sd_save_vmstate
,
3127 .bdrv_load_vmstate
= sd_load_vmstate
,
3129 .bdrv_detach_aio_context
= sd_detach_aio_context
,
3130 .bdrv_attach_aio_context
= sd_attach_aio_context
,
3132 .create_opts
= &sd_create_opts
,
3135 static BlockDriver bdrv_sheepdog_unix
= {
3136 .format_name
= "sheepdog",
3137 .protocol_name
= "sheepdog+unix",
3138 .instance_size
= sizeof(BDRVSheepdogState
),
3139 .bdrv_parse_filename
= sd_parse_filename
,
3140 .bdrv_file_open
= sd_open
,
3141 .bdrv_reopen_prepare
= sd_reopen_prepare
,
3142 .bdrv_reopen_commit
= sd_reopen_commit
,
3143 .bdrv_reopen_abort
= sd_reopen_abort
,
3144 .bdrv_close
= sd_close
,
3145 .bdrv_create
= sd_create
,
3146 .bdrv_has_zero_init
= bdrv_has_zero_init_1
,
3147 .bdrv_getlength
= sd_getlength
,
3148 .bdrv_get_allocated_file_size
= sd_get_allocated_file_size
,
3149 .bdrv_truncate
= sd_truncate
,
3151 .bdrv_co_readv
= sd_co_readv
,
3152 .bdrv_co_writev
= sd_co_writev
,
3153 .bdrv_co_flush_to_disk
= sd_co_flush_to_disk
,
3154 .bdrv_co_pdiscard
= sd_co_pdiscard
,
3155 .bdrv_co_get_block_status
= sd_co_get_block_status
,
3157 .bdrv_snapshot_create
= sd_snapshot_create
,
3158 .bdrv_snapshot_goto
= sd_snapshot_goto
,
3159 .bdrv_snapshot_delete
= sd_snapshot_delete
,
3160 .bdrv_snapshot_list
= sd_snapshot_list
,
3162 .bdrv_save_vmstate
= sd_save_vmstate
,
3163 .bdrv_load_vmstate
= sd_load_vmstate
,
3165 .bdrv_detach_aio_context
= sd_detach_aio_context
,
3166 .bdrv_attach_aio_context
= sd_attach_aio_context
,
3168 .create_opts
= &sd_create_opts
,
3171 static void bdrv_sheepdog_init(void)
3173 bdrv_register(&bdrv_sheepdog
);
3174 bdrv_register(&bdrv_sheepdog_tcp
);
3175 bdrv_register(&bdrv_sheepdog_unix
);
3177 block_init(bdrv_sheepdog_init
);