Statistics
| Branch: | Revision:

root / block / sheepdog.c @ bd751f22

History | View | Annotate | Download (54.5 kB)

1
/*
2
 * Copyright (C) 2009-2010 Nippon Telegraph and Telephone Corporation.
3
 *
4
 * This program is free software; you can redistribute it and/or
5
 * modify it under the terms of the GNU General Public License version
6
 * 2 as published by the Free Software Foundation.
7
 *
8
 * You should have received a copy of the GNU General Public License
9
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
10
 *
11
 * Contributions after 2012-01-13 are licensed under the terms of the
12
 * GNU GPL, version 2 or (at your option) any later version.
13
 */
14

    
15
#include "qemu-common.h"
16
#include "qemu/error-report.h"
17
#include "qemu/sockets.h"
18
#include "block/block_int.h"
19
#include "qemu/bitops.h"
20

    
21
#define SD_PROTO_VER 0x01
22

    
23
#define SD_DEFAULT_ADDR "localhost"
24
#define SD_DEFAULT_PORT "7000"
25

    
26
#define SD_OP_CREATE_AND_WRITE_OBJ  0x01
27
#define SD_OP_READ_OBJ       0x02
28
#define SD_OP_WRITE_OBJ      0x03
29

    
30
#define SD_OP_NEW_VDI        0x11
31
#define SD_OP_LOCK_VDI       0x12
32
#define SD_OP_RELEASE_VDI    0x13
33
#define SD_OP_GET_VDI_INFO   0x14
34
#define SD_OP_READ_VDIS      0x15
35
#define SD_OP_FLUSH_VDI      0x16
36

    
37
#define SD_FLAG_CMD_WRITE    0x01
38
#define SD_FLAG_CMD_COW      0x02
39
#define SD_FLAG_CMD_CACHE    0x04
40

    
41
#define SD_RES_SUCCESS       0x00 /* Success */
42
#define SD_RES_UNKNOWN       0x01 /* Unknown error */
43
#define SD_RES_NO_OBJ        0x02 /* No object found */
44
#define SD_RES_EIO           0x03 /* I/O error */
45
#define SD_RES_VDI_EXIST     0x04 /* Vdi exists already */
46
#define SD_RES_INVALID_PARMS 0x05 /* Invalid parameters */
47
#define SD_RES_SYSTEM_ERROR  0x06 /* System error */
48
#define SD_RES_VDI_LOCKED    0x07 /* Vdi is locked */
49
#define SD_RES_NO_VDI        0x08 /* No vdi found */
50
#define SD_RES_NO_BASE_VDI   0x09 /* No base vdi found */
51
#define SD_RES_VDI_READ      0x0A /* Cannot read requested vdi */
52
#define SD_RES_VDI_WRITE     0x0B /* Cannot write requested vdi */
53
#define SD_RES_BASE_VDI_READ 0x0C /* Cannot read base vdi */
54
#define SD_RES_BASE_VDI_WRITE   0x0D /* Cannot write base vdi */
55
#define SD_RES_NO_TAG        0x0E /* Requested tag is not found */
56
#define SD_RES_STARTUP       0x0F /* Sheepdog is on starting up */
57
#define SD_RES_VDI_NOT_LOCKED   0x10 /* Vdi is not locked */
58
#define SD_RES_SHUTDOWN      0x11 /* Sheepdog is shutting down */
59
#define SD_RES_NO_MEM        0x12 /* Cannot allocate memory */
60
#define SD_RES_FULL_VDI      0x13 /* we already have the maximum vdis */
61
#define SD_RES_VER_MISMATCH  0x14 /* Protocol version mismatch */
62
#define SD_RES_NO_SPACE      0x15 /* Server has no room for new objects */
63
#define SD_RES_WAIT_FOR_FORMAT  0x16 /* Waiting for a format operation */
64
#define SD_RES_WAIT_FOR_JOIN    0x17 /* Waiting for other nodes joining */
65
#define SD_RES_JOIN_FAILED   0x18 /* Target node had failed to join sheepdog */
66

    
67
/*
68
 * Object ID rules
69
 *
70
 *  0 - 19 (20 bits): data object space
71
 * 20 - 31 (12 bits): reserved data object space
72
 * 32 - 55 (24 bits): vdi object space
73
 * 56 - 59 ( 4 bits): reserved vdi object space
74
 * 60 - 63 ( 4 bits): object type identifier space
75
 */
76

    
77
#define VDI_SPACE_SHIFT   32
78
#define VDI_BIT (UINT64_C(1) << 63)
79
#define VMSTATE_BIT (UINT64_C(1) << 62)
80
#define MAX_DATA_OBJS (UINT64_C(1) << 20)
81
#define MAX_CHILDREN 1024
82
#define SD_MAX_VDI_LEN 256
83
#define SD_MAX_VDI_TAG_LEN 256
84
#define SD_NR_VDIS   (1U << 24)
85
#define SD_DATA_OBJ_SIZE (UINT64_C(1) << 22)
86
#define SD_MAX_VDI_SIZE (SD_DATA_OBJ_SIZE * MAX_DATA_OBJS)
87
#define SECTOR_SIZE 512
88

    
89
#define SD_INODE_SIZE (sizeof(SheepdogInode))
90
#define CURRENT_VDI_ID 0
91

    
92
typedef struct SheepdogReq {
93
    uint8_t proto_ver;
94
    uint8_t opcode;
95
    uint16_t flags;
96
    uint32_t epoch;
97
    uint32_t id;
98
    uint32_t data_length;
99
    uint32_t opcode_specific[8];
100
} SheepdogReq;
101

    
102
typedef struct SheepdogRsp {
103
    uint8_t proto_ver;
104
    uint8_t opcode;
105
    uint16_t flags;
106
    uint32_t epoch;
107
    uint32_t id;
108
    uint32_t data_length;
109
    uint32_t result;
110
    uint32_t opcode_specific[7];
111
} SheepdogRsp;
112

    
113
typedef struct SheepdogObjReq {
114
    uint8_t proto_ver;
115
    uint8_t opcode;
116
    uint16_t flags;
117
    uint32_t epoch;
118
    uint32_t id;
119
    uint32_t data_length;
120
    uint64_t oid;
121
    uint64_t cow_oid;
122
    uint32_t copies;
123
    uint32_t rsvd;
124
    uint64_t offset;
125
} SheepdogObjReq;
126

    
127
typedef struct SheepdogObjRsp {
128
    uint8_t proto_ver;
129
    uint8_t opcode;
130
    uint16_t flags;
131
    uint32_t epoch;
132
    uint32_t id;
133
    uint32_t data_length;
134
    uint32_t result;
135
    uint32_t copies;
136
    uint32_t pad[6];
137
} SheepdogObjRsp;
138

    
139
typedef struct SheepdogVdiReq {
140
    uint8_t proto_ver;
141
    uint8_t opcode;
142
    uint16_t flags;
143
    uint32_t epoch;
144
    uint32_t id;
145
    uint32_t data_length;
146
    uint64_t vdi_size;
147
    uint32_t base_vdi_id;
148
    uint32_t copies;
149
    uint32_t snapid;
150
    uint32_t pad[3];
151
} SheepdogVdiReq;
152

    
153
typedef struct SheepdogVdiRsp {
154
    uint8_t proto_ver;
155
    uint8_t opcode;
156
    uint16_t flags;
157
    uint32_t epoch;
158
    uint32_t id;
159
    uint32_t data_length;
160
    uint32_t result;
161
    uint32_t rsvd;
162
    uint32_t vdi_id;
163
    uint32_t pad[5];
164
} SheepdogVdiRsp;
165

    
166
typedef struct SheepdogInode {
167
    char name[SD_MAX_VDI_LEN];
168
    char tag[SD_MAX_VDI_TAG_LEN];
169
    uint64_t ctime;
170
    uint64_t snap_ctime;
171
    uint64_t vm_clock_nsec;
172
    uint64_t vdi_size;
173
    uint64_t vm_state_size;
174
    uint16_t copy_policy;
175
    uint8_t nr_copies;
176
    uint8_t block_size_shift;
177
    uint32_t snap_id;
178
    uint32_t vdi_id;
179
    uint32_t parent_vdi_id;
180
    uint32_t child_vdi_id[MAX_CHILDREN];
181
    uint32_t data_vdi_id[MAX_DATA_OBJS];
182
} SheepdogInode;
183

    
184
/*
185
 * 64 bit FNV-1a non-zero initial basis
186
 */
187
#define FNV1A_64_INIT ((uint64_t)0xcbf29ce484222325ULL)
188

    
189
/*
190
 * 64 bit Fowler/Noll/Vo FNV-1a hash code
191
 */
192
static inline uint64_t fnv_64a_buf(void *buf, size_t len, uint64_t hval)
193
{
194
    unsigned char *bp = buf;
195
    unsigned char *be = bp + len;
196
    while (bp < be) {
197
        hval ^= (uint64_t) *bp++;
198
        hval += (hval << 1) + (hval << 4) + (hval << 5) +
199
            (hval << 7) + (hval << 8) + (hval << 40);
200
    }
201
    return hval;
202
}
203

    
204
static inline bool is_data_obj_writable(SheepdogInode *inode, unsigned int idx)
205
{
206
    return inode->vdi_id == inode->data_vdi_id[idx];
207
}
208

    
209
static inline bool is_data_obj(uint64_t oid)
210
{
211
    return !(VDI_BIT & oid);
212
}
213

    
214
static inline uint64_t data_oid_to_idx(uint64_t oid)
215
{
216
    return oid & (MAX_DATA_OBJS - 1);
217
}
218

    
219
static inline uint64_t vid_to_vdi_oid(uint32_t vid)
220
{
221
    return VDI_BIT | ((uint64_t)vid << VDI_SPACE_SHIFT);
222
}
223

    
224
static inline uint64_t vid_to_vmstate_oid(uint32_t vid, uint32_t idx)
225
{
226
    return VMSTATE_BIT | ((uint64_t)vid << VDI_SPACE_SHIFT) | idx;
227
}
228

    
229
static inline uint64_t vid_to_data_oid(uint32_t vid, uint32_t idx)
230
{
231
    return ((uint64_t)vid << VDI_SPACE_SHIFT) | idx;
232
}
233

    
234
static inline bool is_snapshot(struct SheepdogInode *inode)
235
{
236
    return !!inode->snap_ctime;
237
}
238

    
239
#undef dprintf
240
#ifdef DEBUG_SDOG
241
#define dprintf(fmt, args...)                                       \
242
    do {                                                            \
243
        fprintf(stdout, "%s %d: " fmt, __func__, __LINE__, ##args); \
244
    } while (0)
245
#else
246
#define dprintf(fmt, args...)
247
#endif
248

    
249
typedef struct SheepdogAIOCB SheepdogAIOCB;
250

    
251
typedef struct AIOReq {
252
    SheepdogAIOCB *aiocb;
253
    unsigned int iov_offset;
254

    
255
    uint64_t oid;
256
    uint64_t base_oid;
257
    uint64_t offset;
258
    unsigned int data_len;
259
    uint8_t flags;
260
    uint32_t id;
261

    
262
    QLIST_ENTRY(AIOReq) aio_siblings;
263
} AIOReq;
264

    
265
enum AIOCBState {
266
    AIOCB_WRITE_UDATA,
267
    AIOCB_READ_UDATA,
268
};
269

    
270
struct SheepdogAIOCB {
271
    BlockDriverAIOCB common;
272

    
273
    QEMUIOVector *qiov;
274

    
275
    int64_t sector_num;
276
    int nb_sectors;
277

    
278
    int ret;
279
    enum AIOCBState aiocb_type;
280

    
281
    Coroutine *coroutine;
282
    void (*aio_done_func)(SheepdogAIOCB *);
283

    
284
    bool canceled;
285
    int nr_pending;
286
};
287

    
288
typedef struct BDRVSheepdogState {
289
    SheepdogInode inode;
290

    
291
    uint32_t min_dirty_data_idx;
292
    uint32_t max_dirty_data_idx;
293

    
294
    char name[SD_MAX_VDI_LEN];
295
    bool is_snapshot;
296
    bool cache_enabled;
297

    
298
    char *addr;
299
    char *port;
300
    int fd;
301
    int flush_fd;
302

    
303
    CoMutex lock;
304
    Coroutine *co_send;
305
    Coroutine *co_recv;
306

    
307
    uint32_t aioreq_seq_num;
308
    QLIST_HEAD(inflight_aio_head, AIOReq) inflight_aio_head;
309
    QLIST_HEAD(pending_aio_head, AIOReq) pending_aio_head;
310
} BDRVSheepdogState;
311

    
312
static const char * sd_strerror(int err)
313
{
314
    int i;
315

    
316
    static const struct {
317
        int err;
318
        const char *desc;
319
    } errors[] = {
320
        {SD_RES_SUCCESS, "Success"},
321
        {SD_RES_UNKNOWN, "Unknown error"},
322
        {SD_RES_NO_OBJ, "No object found"},
323
        {SD_RES_EIO, "I/O error"},
324
        {SD_RES_VDI_EXIST, "VDI exists already"},
325
        {SD_RES_INVALID_PARMS, "Invalid parameters"},
326
        {SD_RES_SYSTEM_ERROR, "System error"},
327
        {SD_RES_VDI_LOCKED, "VDI is already locked"},
328
        {SD_RES_NO_VDI, "No vdi found"},
329
        {SD_RES_NO_BASE_VDI, "No base VDI found"},
330
        {SD_RES_VDI_READ, "Failed read the requested VDI"},
331
        {SD_RES_VDI_WRITE, "Failed to write the requested VDI"},
332
        {SD_RES_BASE_VDI_READ, "Failed to read the base VDI"},
333
        {SD_RES_BASE_VDI_WRITE, "Failed to write the base VDI"},
334
        {SD_RES_NO_TAG, "Failed to find the requested tag"},
335
        {SD_RES_STARTUP, "The system is still booting"},
336
        {SD_RES_VDI_NOT_LOCKED, "VDI isn't locked"},
337
        {SD_RES_SHUTDOWN, "The system is shutting down"},
338
        {SD_RES_NO_MEM, "Out of memory on the server"},
339
        {SD_RES_FULL_VDI, "We already have the maximum vdis"},
340
        {SD_RES_VER_MISMATCH, "Protocol version mismatch"},
341
        {SD_RES_NO_SPACE, "Server has no space for new objects"},
342
        {SD_RES_WAIT_FOR_FORMAT, "Sheepdog is waiting for a format operation"},
343
        {SD_RES_WAIT_FOR_JOIN, "Sheepdog is waiting for other nodes joining"},
344
        {SD_RES_JOIN_FAILED, "Target node had failed to join sheepdog"},
345
    };
346

    
347
    for (i = 0; i < ARRAY_SIZE(errors); ++i) {
348
        if (errors[i].err == err) {
349
            return errors[i].desc;
350
        }
351
    }
352

    
353
    return "Invalid error code";
354
}
355

    
356
/*
357
 * Sheepdog I/O handling:
358
 *
359
 * 1. In sd_co_rw_vector, we send the I/O requests to the server and
360
 *    link the requests to the inflight_list in the
361
 *    BDRVSheepdogState.  The function exits without waiting for
362
 *    receiving the response.
363
 *
364
 * 2. We receive the response in aio_read_response, the fd handler to
365
 *    the sheepdog connection.  If metadata update is needed, we send
366
 *    the write request to the vdi object in sd_write_done, the write
367
 *    completion function.  We switch back to sd_co_readv/writev after
368
 *    all the requests belonging to the AIOCB are finished.
369
 */
370

    
371
static inline AIOReq *alloc_aio_req(BDRVSheepdogState *s, SheepdogAIOCB *acb,
372
                                    uint64_t oid, unsigned int data_len,
373
                                    uint64_t offset, uint8_t flags,
374
                                    uint64_t base_oid, unsigned int iov_offset)
375
{
376
    AIOReq *aio_req;
377

    
378
    aio_req = g_malloc(sizeof(*aio_req));
379
    aio_req->aiocb = acb;
380
    aio_req->iov_offset = iov_offset;
381
    aio_req->oid = oid;
382
    aio_req->base_oid = base_oid;
383
    aio_req->offset = offset;
384
    aio_req->data_len = data_len;
385
    aio_req->flags = flags;
386
    aio_req->id = s->aioreq_seq_num++;
387

    
388
    acb->nr_pending++;
389
    return aio_req;
390
}
391

    
392
static inline void free_aio_req(BDRVSheepdogState *s, AIOReq *aio_req)
393
{
394
    SheepdogAIOCB *acb = aio_req->aiocb;
395

    
396
    QLIST_REMOVE(aio_req, aio_siblings);
397
    g_free(aio_req);
398

    
399
    acb->nr_pending--;
400
}
401

    
402
static void coroutine_fn sd_finish_aiocb(SheepdogAIOCB *acb)
403
{
404
    if (!acb->canceled) {
405
        qemu_coroutine_enter(acb->coroutine, NULL);
406
    }
407
    qemu_aio_release(acb);
408
}
409

    
410
static void sd_aio_cancel(BlockDriverAIOCB *blockacb)
411
{
412
    SheepdogAIOCB *acb = (SheepdogAIOCB *)blockacb;
413

    
414
    /*
415
     * Sheepdog cannot cancel the requests which are already sent to
416
     * the servers, so we just complete the request with -EIO here.
417
     */
418
    acb->ret = -EIO;
419
    qemu_coroutine_enter(acb->coroutine, NULL);
420
    acb->canceled = true;
421
}
422

    
423
static const AIOCBInfo sd_aiocb_info = {
424
    .aiocb_size = sizeof(SheepdogAIOCB),
425
    .cancel = sd_aio_cancel,
426
};
427

    
428
static SheepdogAIOCB *sd_aio_setup(BlockDriverState *bs, QEMUIOVector *qiov,
429
                                   int64_t sector_num, int nb_sectors,
430
                                   BlockDriverCompletionFunc *cb, void *opaque)
431
{
432
    SheepdogAIOCB *acb;
433

    
434
    acb = qemu_aio_get(&sd_aiocb_info, bs, cb, opaque);
435

    
436
    acb->qiov = qiov;
437

    
438
    acb->sector_num = sector_num;
439
    acb->nb_sectors = nb_sectors;
440

    
441
    acb->aio_done_func = NULL;
442
    acb->canceled = false;
443
    acb->coroutine = qemu_coroutine_self();
444
    acb->ret = 0;
445
    acb->nr_pending = 0;
446
    return acb;
447
}
448

    
449
static int connect_to_sdog(const char *addr, const char *port)
450
{
451
    char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
452
    int fd, ret;
453
    struct addrinfo hints, *res, *res0;
454

    
455
    if (!addr) {
456
        addr = SD_DEFAULT_ADDR;
457
        port = SD_DEFAULT_PORT;
458
    }
459

    
460
    memset(&hints, 0, sizeof(hints));
461
    hints.ai_socktype = SOCK_STREAM;
462

    
463
    ret = getaddrinfo(addr, port, &hints, &res0);
464
    if (ret) {
465
        error_report("unable to get address info %s, %s",
466
                     addr, strerror(errno));
467
        return -errno;
468
    }
469

    
470
    for (res = res0; res; res = res->ai_next) {
471
        ret = getnameinfo(res->ai_addr, res->ai_addrlen, hbuf, sizeof(hbuf),
472
                          sbuf, sizeof(sbuf), NI_NUMERICHOST | NI_NUMERICSERV);
473
        if (ret) {
474
            continue;
475
        }
476

    
477
        fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
478
        if (fd < 0) {
479
            continue;
480
        }
481

    
482
    reconnect:
483
        ret = connect(fd, res->ai_addr, res->ai_addrlen);
484
        if (ret < 0) {
485
            if (errno == EINTR) {
486
                goto reconnect;
487
            }
488
            close(fd);
489
            break;
490
        }
491

    
492
        dprintf("connected to %s:%s\n", addr, port);
493
        goto success;
494
    }
495
    fd = -errno;
496
    error_report("failed connect to %s:%s", addr, port);
497
success:
498
    freeaddrinfo(res0);
499
    return fd;
500
}
501

    
502
static coroutine_fn int send_co_req(int sockfd, SheepdogReq *hdr, void *data,
503
                                    unsigned int *wlen)
504
{
505
    int ret;
506

    
507
    ret = qemu_co_send(sockfd, hdr, sizeof(*hdr));
508
    if (ret < sizeof(*hdr)) {
509
        error_report("failed to send a req, %s", strerror(errno));
510
        return ret;
511
    }
512

    
513
    ret = qemu_co_send(sockfd, data, *wlen);
514
    if (ret < *wlen) {
515
        error_report("failed to send a req, %s", strerror(errno));
516
    }
517

    
518
    return ret;
519
}
520

    
521
static void restart_co_req(void *opaque)
522
{
523
    Coroutine *co = opaque;
524

    
525
    qemu_coroutine_enter(co, NULL);
526
}
527

    
528
typedef struct SheepdogReqCo {
529
    int sockfd;
530
    SheepdogReq *hdr;
531
    void *data;
532
    unsigned int *wlen;
533
    unsigned int *rlen;
534
    int ret;
535
    bool finished;
536
} SheepdogReqCo;
537

    
538
static coroutine_fn void do_co_req(void *opaque)
539
{
540
    int ret;
541
    Coroutine *co;
542
    SheepdogReqCo *srco = opaque;
543
    int sockfd = srco->sockfd;
544
    SheepdogReq *hdr = srco->hdr;
545
    void *data = srco->data;
546
    unsigned int *wlen = srco->wlen;
547
    unsigned int *rlen = srco->rlen;
548

    
549
    co = qemu_coroutine_self();
550
    qemu_aio_set_fd_handler(sockfd, NULL, restart_co_req, NULL, co);
551

    
552
    socket_set_block(sockfd);
553
    ret = send_co_req(sockfd, hdr, data, wlen);
554
    if (ret < 0) {
555
        goto out;
556
    }
557

    
558
    qemu_aio_set_fd_handler(sockfd, restart_co_req, NULL, NULL, co);
559

    
560
    ret = qemu_co_recv(sockfd, hdr, sizeof(*hdr));
561
    if (ret < sizeof(*hdr)) {
562
        error_report("failed to get a rsp, %s", strerror(errno));
563
        ret = -errno;
564
        goto out;
565
    }
566

    
567
    if (*rlen > hdr->data_length) {
568
        *rlen = hdr->data_length;
569
    }
570

    
571
    if (*rlen) {
572
        ret = qemu_co_recv(sockfd, data, *rlen);
573
        if (ret < *rlen) {
574
            error_report("failed to get the data, %s", strerror(errno));
575
            ret = -errno;
576
            goto out;
577
        }
578
    }
579
    ret = 0;
580
out:
581
    qemu_aio_set_fd_handler(sockfd, NULL, NULL, NULL, NULL);
582
    socket_set_nonblock(sockfd);
583

    
584
    srco->ret = ret;
585
    srco->finished = true;
586
}
587

    
588
static int do_req(int sockfd, SheepdogReq *hdr, void *data,
589
                  unsigned int *wlen, unsigned int *rlen)
590
{
591
    Coroutine *co;
592
    SheepdogReqCo srco = {
593
        .sockfd = sockfd,
594
        .hdr = hdr,
595
        .data = data,
596
        .wlen = wlen,
597
        .rlen = rlen,
598
        .ret = 0,
599
        .finished = false,
600
    };
601

    
602
    if (qemu_in_coroutine()) {
603
        do_co_req(&srco);
604
    } else {
605
        co = qemu_coroutine_create(do_co_req);
606
        qemu_coroutine_enter(co, &srco);
607
        while (!srco.finished) {
608
            qemu_aio_wait();
609
        }
610
    }
611

    
612
    return srco.ret;
613
}
614

    
615
static int coroutine_fn add_aio_request(BDRVSheepdogState *s, AIOReq *aio_req,
616
                           struct iovec *iov, int niov, bool create,
617
                           enum AIOCBState aiocb_type);
618

    
619

    
620
static AIOReq *find_pending_req(BDRVSheepdogState *s, uint64_t oid)
621
{
622
    AIOReq *aio_req;
623

    
624
    QLIST_FOREACH(aio_req, &s->pending_aio_head, aio_siblings) {
625
        if (aio_req->oid == oid) {
626
            return aio_req;
627
        }
628
    }
629

    
630
    return NULL;
631
}
632

    
633
/*
634
 * This function searchs pending requests to the object `oid', and
635
 * sends them.
636
 */
637
static void coroutine_fn send_pending_req(BDRVSheepdogState *s, uint64_t oid)
638
{
639
    AIOReq *aio_req;
640
    SheepdogAIOCB *acb;
641
    int ret;
642

    
643
    while ((aio_req = find_pending_req(s, oid)) != NULL) {
644
        acb = aio_req->aiocb;
645
        /* move aio_req from pending list to inflight one */
646
        QLIST_REMOVE(aio_req, aio_siblings);
647
        QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
648
        ret = add_aio_request(s, aio_req, acb->qiov->iov,
649
                              acb->qiov->niov, false, acb->aiocb_type);
650
        if (ret < 0) {
651
            error_report("add_aio_request is failed");
652
            free_aio_req(s, aio_req);
653
            if (!acb->nr_pending) {
654
                sd_finish_aiocb(acb);
655
            }
656
        }
657
    }
658
}
659

    
660
/*
661
 * Receive responses of the I/O requests.
662
 *
663
 * This function is registered as a fd handler, and called from the
664
 * main loop when s->fd is ready for reading responses.
665
 */
666
static void coroutine_fn aio_read_response(void *opaque)
667
{
668
    SheepdogObjRsp rsp;
669
    BDRVSheepdogState *s = opaque;
670
    int fd = s->fd;
671
    int ret;
672
    AIOReq *aio_req = NULL;
673
    SheepdogAIOCB *acb;
674
    unsigned long idx;
675

    
676
    if (QLIST_EMPTY(&s->inflight_aio_head)) {
677
        goto out;
678
    }
679

    
680
    /* read a header */
681
    ret = qemu_co_recv(fd, &rsp, sizeof(rsp));
682
    if (ret < 0) {
683
        error_report("failed to get the header, %s", strerror(errno));
684
        goto out;
685
    }
686

    
687
    /* find the right aio_req from the inflight aio list */
688
    QLIST_FOREACH(aio_req, &s->inflight_aio_head, aio_siblings) {
689
        if (aio_req->id == rsp.id) {
690
            break;
691
        }
692
    }
693
    if (!aio_req) {
694
        error_report("cannot find aio_req %x", rsp.id);
695
        goto out;
696
    }
697

    
698
    acb = aio_req->aiocb;
699

    
700
    switch (acb->aiocb_type) {
701
    case AIOCB_WRITE_UDATA:
702
        /* this coroutine context is no longer suitable for co_recv
703
         * because we may send data to update vdi objects */
704
        s->co_recv = NULL;
705
        if (!is_data_obj(aio_req->oid)) {
706
            break;
707
        }
708
        idx = data_oid_to_idx(aio_req->oid);
709

    
710
        if (s->inode.data_vdi_id[idx] != s->inode.vdi_id) {
711
            /*
712
             * If the object is newly created one, we need to update
713
             * the vdi object (metadata object).  min_dirty_data_idx
714
             * and max_dirty_data_idx are changed to include updated
715
             * index between them.
716
             */
717
            if (rsp.result == SD_RES_SUCCESS) {
718
                s->inode.data_vdi_id[idx] = s->inode.vdi_id;
719
                s->max_dirty_data_idx = MAX(idx, s->max_dirty_data_idx);
720
                s->min_dirty_data_idx = MIN(idx, s->min_dirty_data_idx);
721
            }
722
            /*
723
             * Some requests may be blocked because simultaneous
724
             * create requests are not allowed, so we search the
725
             * pending requests here.
726
             */
727
            send_pending_req(s, vid_to_data_oid(s->inode.vdi_id, idx));
728
        }
729
        break;
730
    case AIOCB_READ_UDATA:
731
        ret = qemu_co_recvv(fd, acb->qiov->iov, acb->qiov->niov,
732
                            aio_req->iov_offset, rsp.data_length);
733
        if (ret < 0) {
734
            error_report("failed to get the data, %s", strerror(errno));
735
            goto out;
736
        }
737
        break;
738
    }
739

    
740
    if (rsp.result != SD_RES_SUCCESS) {
741
        acb->ret = -EIO;
742
        error_report("%s", sd_strerror(rsp.result));
743
    }
744

    
745
    free_aio_req(s, aio_req);
746
    if (!acb->nr_pending) {
747
        /*
748
         * We've finished all requests which belong to the AIOCB, so
749
         * we can switch back to sd_co_readv/writev now.
750
         */
751
        acb->aio_done_func(acb);
752
    }
753
out:
754
    s->co_recv = NULL;
755
}
756

    
757
static void co_read_response(void *opaque)
758
{
759
    BDRVSheepdogState *s = opaque;
760

    
761
    if (!s->co_recv) {
762
        s->co_recv = qemu_coroutine_create(aio_read_response);
763
    }
764

    
765
    qemu_coroutine_enter(s->co_recv, opaque);
766
}
767

    
768
static void co_write_request(void *opaque)
769
{
770
    BDRVSheepdogState *s = opaque;
771

    
772
    qemu_coroutine_enter(s->co_send, NULL);
773
}
774

    
775
static int aio_flush_request(void *opaque)
776
{
777
    BDRVSheepdogState *s = opaque;
778

    
779
    return !QLIST_EMPTY(&s->inflight_aio_head) ||
780
        !QLIST_EMPTY(&s->pending_aio_head);
781
}
782

    
783
static int set_nodelay(int fd)
784
{
785
    int ret, opt;
786

    
787
    opt = 1;
788
    ret = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&opt, sizeof(opt));
789
    return ret;
790
}
791

    
792
/*
793
 * Return a socket discriptor to read/write objects.
794
 *
795
 * We cannot use this discriptor for other operations because
796
 * the block driver may be on waiting response from the server.
797
 */
798
static int get_sheep_fd(BDRVSheepdogState *s)
799
{
800
    int ret, fd;
801

    
802
    fd = connect_to_sdog(s->addr, s->port);
803
    if (fd < 0) {
804
        error_report("%s", strerror(errno));
805
        return fd;
806
    }
807

    
808
    socket_set_nonblock(fd);
809

    
810
    ret = set_nodelay(fd);
811
    if (ret) {
812
        error_report("%s", strerror(errno));
813
        closesocket(fd);
814
        return -errno;
815
    }
816

    
817
    qemu_aio_set_fd_handler(fd, co_read_response, NULL, aio_flush_request, s);
818
    return fd;
819
}
820

    
821
/*
822
 * Parse a filename
823
 *
824
 * filename must be one of the following formats:
825
 *   1. [vdiname]
826
 *   2. [vdiname]:[snapid]
827
 *   3. [vdiname]:[tag]
828
 *   4. [hostname]:[port]:[vdiname]
829
 *   5. [hostname]:[port]:[vdiname]:[snapid]
830
 *   6. [hostname]:[port]:[vdiname]:[tag]
831
 *
832
 * You can boot from the snapshot images by specifying `snapid` or
833
 * `tag'.
834
 *
835
 * You can run VMs outside the Sheepdog cluster by specifying
836
 * `hostname' and `port' (experimental).
837
 */
838
static int parse_vdiname(BDRVSheepdogState *s, const char *filename,
839
                         char *vdi, uint32_t *snapid, char *tag)
840
{
841
    char *p, *q;
842
    int nr_sep;
843

    
844
    p = q = g_strdup(filename);
845

    
846
    /* count the number of separators */
847
    nr_sep = 0;
848
    while (*p) {
849
        if (*p == ':') {
850
            nr_sep++;
851
        }
852
        p++;
853
    }
854
    p = q;
855

    
856
    /* use the first two tokens as hostname and port number. */
857
    if (nr_sep >= 2) {
858
        s->addr = p;
859
        p = strchr(p, ':');
860
        *p++ = '\0';
861

    
862
        s->port = p;
863
        p = strchr(p, ':');
864
        *p++ = '\0';
865
    } else {
866
        s->addr = NULL;
867
        s->port = 0;
868
    }
869

    
870
    pstrcpy(vdi, SD_MAX_VDI_LEN, p);
871

    
872
    p = strchr(vdi, ':');
873
    if (p) {
874
        *p++ = '\0';
875
        *snapid = strtoul(p, NULL, 10);
876
        if (*snapid == 0) {
877
            pstrcpy(tag, SD_MAX_VDI_TAG_LEN, p);
878
        }
879
    } else {
880
        *snapid = CURRENT_VDI_ID; /* search current vdi */
881
    }
882

    
883
    if (s->addr == NULL) {
884
        g_free(q);
885
    }
886

    
887
    return 0;
888
}
889

    
890
static int find_vdi_name(BDRVSheepdogState *s, char *filename, uint32_t snapid,
891
                         char *tag, uint32_t *vid, int for_snapshot)
892
{
893
    int ret, fd;
894
    SheepdogVdiReq hdr;
895
    SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
896
    unsigned int wlen, rlen = 0;
897
    char buf[SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN];
898

    
899
    fd = connect_to_sdog(s->addr, s->port);
900
    if (fd < 0) {
901
        return fd;
902
    }
903

    
904
    /* This pair of strncpy calls ensures that the buffer is zero-filled,
905
     * which is desirable since we'll soon be sending those bytes, and
906
     * don't want the send_req to read uninitialized data.
907
     */
908
    strncpy(buf, filename, SD_MAX_VDI_LEN);
909
    strncpy(buf + SD_MAX_VDI_LEN, tag, SD_MAX_VDI_TAG_LEN);
910

    
911
    memset(&hdr, 0, sizeof(hdr));
912
    if (for_snapshot) {
913
        hdr.opcode = SD_OP_GET_VDI_INFO;
914
    } else {
915
        hdr.opcode = SD_OP_LOCK_VDI;
916
    }
917
    wlen = SD_MAX_VDI_LEN + SD_MAX_VDI_TAG_LEN;
918
    hdr.proto_ver = SD_PROTO_VER;
919
    hdr.data_length = wlen;
920
    hdr.snapid = snapid;
921
    hdr.flags = SD_FLAG_CMD_WRITE;
922

    
923
    ret = do_req(fd, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
924
    if (ret) {
925
        goto out;
926
    }
927

    
928
    if (rsp->result != SD_RES_SUCCESS) {
929
        error_report("cannot get vdi info, %s, %s %d %s",
930
                     sd_strerror(rsp->result), filename, snapid, tag);
931
        if (rsp->result == SD_RES_NO_VDI) {
932
            ret = -ENOENT;
933
        } else {
934
            ret = -EIO;
935
        }
936
        goto out;
937
    }
938
    *vid = rsp->vdi_id;
939

    
940
    ret = 0;
941
out:
942
    closesocket(fd);
943
    return ret;
944
}
945

    
946
static int coroutine_fn add_aio_request(BDRVSheepdogState *s, AIOReq *aio_req,
947
                           struct iovec *iov, int niov, bool create,
948
                           enum AIOCBState aiocb_type)
949
{
950
    int nr_copies = s->inode.nr_copies;
951
    SheepdogObjReq hdr;
952
    unsigned int wlen;
953
    int ret;
954
    uint64_t oid = aio_req->oid;
955
    unsigned int datalen = aio_req->data_len;
956
    uint64_t offset = aio_req->offset;
957
    uint8_t flags = aio_req->flags;
958
    uint64_t old_oid = aio_req->base_oid;
959

    
960
    if (!nr_copies) {
961
        error_report("bug");
962
    }
963

    
964
    memset(&hdr, 0, sizeof(hdr));
965

    
966
    if (aiocb_type == AIOCB_READ_UDATA) {
967
        wlen = 0;
968
        hdr.opcode = SD_OP_READ_OBJ;
969
        hdr.flags = flags;
970
    } else if (create) {
971
        wlen = datalen;
972
        hdr.opcode = SD_OP_CREATE_AND_WRITE_OBJ;
973
        hdr.flags = SD_FLAG_CMD_WRITE | flags;
974
    } else {
975
        wlen = datalen;
976
        hdr.opcode = SD_OP_WRITE_OBJ;
977
        hdr.flags = SD_FLAG_CMD_WRITE | flags;
978
    }
979

    
980
    if (s->cache_enabled) {
981
        hdr.flags |= SD_FLAG_CMD_CACHE;
982
    }
983

    
984
    hdr.oid = oid;
985
    hdr.cow_oid = old_oid;
986
    hdr.copies = s->inode.nr_copies;
987

    
988
    hdr.data_length = datalen;
989
    hdr.offset = offset;
990

    
991
    hdr.id = aio_req->id;
992

    
993
    qemu_co_mutex_lock(&s->lock);
994
    s->co_send = qemu_coroutine_self();
995
    qemu_aio_set_fd_handler(s->fd, co_read_response, co_write_request,
996
                            aio_flush_request, s);
997
    socket_set_cork(s->fd, 1);
998

    
999
    /* send a header */
1000
    ret = qemu_co_send(s->fd, &hdr, sizeof(hdr));
1001
    if (ret < 0) {
1002
        qemu_co_mutex_unlock(&s->lock);
1003
        error_report("failed to send a req, %s", strerror(errno));
1004
        return -errno;
1005
    }
1006

    
1007
    if (wlen) {
1008
        ret = qemu_co_sendv(s->fd, iov, niov, aio_req->iov_offset, wlen);
1009
        if (ret < 0) {
1010
            qemu_co_mutex_unlock(&s->lock);
1011
            error_report("failed to send a data, %s", strerror(errno));
1012
            return -errno;
1013
        }
1014
    }
1015

    
1016
    socket_set_cork(s->fd, 0);
1017
    qemu_aio_set_fd_handler(s->fd, co_read_response, NULL,
1018
                            aio_flush_request, s);
1019
    qemu_co_mutex_unlock(&s->lock);
1020

    
1021
    return 0;
1022
}
1023

    
1024
static int read_write_object(int fd, char *buf, uint64_t oid, int copies,
1025
                             unsigned int datalen, uint64_t offset,
1026
                             bool write, bool create, bool cache)
1027
{
1028
    SheepdogObjReq hdr;
1029
    SheepdogObjRsp *rsp = (SheepdogObjRsp *)&hdr;
1030
    unsigned int wlen, rlen;
1031
    int ret;
1032

    
1033
    memset(&hdr, 0, sizeof(hdr));
1034

    
1035
    if (write) {
1036
        wlen = datalen;
1037
        rlen = 0;
1038
        hdr.flags = SD_FLAG_CMD_WRITE;
1039
        if (create) {
1040
            hdr.opcode = SD_OP_CREATE_AND_WRITE_OBJ;
1041
        } else {
1042
            hdr.opcode = SD_OP_WRITE_OBJ;
1043
        }
1044
    } else {
1045
        wlen = 0;
1046
        rlen = datalen;
1047
        hdr.opcode = SD_OP_READ_OBJ;
1048
    }
1049

    
1050
    if (cache) {
1051
        hdr.flags |= SD_FLAG_CMD_CACHE;
1052
    }
1053

    
1054
    hdr.oid = oid;
1055
    hdr.data_length = datalen;
1056
    hdr.offset = offset;
1057
    hdr.copies = copies;
1058

    
1059
    ret = do_req(fd, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
1060
    if (ret) {
1061
        error_report("failed to send a request to the sheep");
1062
        return ret;
1063
    }
1064

    
1065
    switch (rsp->result) {
1066
    case SD_RES_SUCCESS:
1067
        return 0;
1068
    default:
1069
        error_report("%s", sd_strerror(rsp->result));
1070
        return -EIO;
1071
    }
1072
}
1073

    
1074
static int read_object(int fd, char *buf, uint64_t oid, int copies,
1075
                       unsigned int datalen, uint64_t offset, bool cache)
1076
{
1077
    return read_write_object(fd, buf, oid, copies, datalen, offset, false,
1078
                             false, cache);
1079
}
1080

    
1081
static int write_object(int fd, char *buf, uint64_t oid, int copies,
1082
                        unsigned int datalen, uint64_t offset, bool create,
1083
                        bool cache)
1084
{
1085
    return read_write_object(fd, buf, oid, copies, datalen, offset, true,
1086
                             create, cache);
1087
}
1088

    
1089
static int sd_open(BlockDriverState *bs, const char *filename, int flags)
1090
{
1091
    int ret, fd;
1092
    uint32_t vid = 0;
1093
    BDRVSheepdogState *s = bs->opaque;
1094
    char vdi[SD_MAX_VDI_LEN], tag[SD_MAX_VDI_TAG_LEN];
1095
    uint32_t snapid;
1096
    char *buf = NULL;
1097

    
1098
    strstart(filename, "sheepdog:", (const char **)&filename);
1099

    
1100
    QLIST_INIT(&s->inflight_aio_head);
1101
    QLIST_INIT(&s->pending_aio_head);
1102
    s->fd = -1;
1103

    
1104
    memset(vdi, 0, sizeof(vdi));
1105
    memset(tag, 0, sizeof(tag));
1106
    if (parse_vdiname(s, filename, vdi, &snapid, tag) < 0) {
1107
        ret = -EINVAL;
1108
        goto out;
1109
    }
1110
    s->fd = get_sheep_fd(s);
1111
    if (s->fd < 0) {
1112
        ret = s->fd;
1113
        goto out;
1114
    }
1115

    
1116
    ret = find_vdi_name(s, vdi, snapid, tag, &vid, 0);
1117
    if (ret) {
1118
        goto out;
1119
    }
1120

    
1121
    s->cache_enabled = true;
1122
    s->flush_fd = connect_to_sdog(s->addr, s->port);
1123
    if (s->flush_fd < 0) {
1124
        error_report("failed to connect");
1125
        ret = s->flush_fd;
1126
        goto out;
1127
    }
1128

    
1129
    if (snapid || tag[0] != '\0') {
1130
        dprintf("%" PRIx32 " snapshot inode was open.\n", vid);
1131
        s->is_snapshot = true;
1132
    }
1133

    
1134
    fd = connect_to_sdog(s->addr, s->port);
1135
    if (fd < 0) {
1136
        error_report("failed to connect");
1137
        ret = fd;
1138
        goto out;
1139
    }
1140

    
1141
    buf = g_malloc(SD_INODE_SIZE);
1142
    ret = read_object(fd, buf, vid_to_vdi_oid(vid), 0, SD_INODE_SIZE, 0,
1143
                      s->cache_enabled);
1144

    
1145
    closesocket(fd);
1146

    
1147
    if (ret) {
1148
        goto out;
1149
    }
1150

    
1151
    memcpy(&s->inode, buf, sizeof(s->inode));
1152
    s->min_dirty_data_idx = UINT32_MAX;
1153
    s->max_dirty_data_idx = 0;
1154

    
1155
    bs->total_sectors = s->inode.vdi_size / SECTOR_SIZE;
1156
    pstrcpy(s->name, sizeof(s->name), vdi);
1157
    qemu_co_mutex_init(&s->lock);
1158
    g_free(buf);
1159
    return 0;
1160
out:
1161
    qemu_aio_set_fd_handler(s->fd, NULL, NULL, NULL, NULL);
1162
    if (s->fd >= 0) {
1163
        closesocket(s->fd);
1164
    }
1165
    g_free(buf);
1166
    return ret;
1167
}
1168

    
1169
static int do_sd_create(char *filename, int64_t vdi_size,
1170
                        uint32_t base_vid, uint32_t *vdi_id, int snapshot,
1171
                        const char *addr, const char *port)
1172
{
1173
    SheepdogVdiReq hdr;
1174
    SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
1175
    int fd, ret;
1176
    unsigned int wlen, rlen = 0;
1177
    char buf[SD_MAX_VDI_LEN];
1178

    
1179
    fd = connect_to_sdog(addr, port);
1180
    if (fd < 0) {
1181
        return fd;
1182
    }
1183

    
1184
    /* FIXME: would it be better to fail (e.g., return -EIO) when filename
1185
     * does not fit in buf?  For now, just truncate and avoid buffer overrun.
1186
     */
1187
    memset(buf, 0, sizeof(buf));
1188
    pstrcpy(buf, sizeof(buf), filename);
1189

    
1190
    memset(&hdr, 0, sizeof(hdr));
1191
    hdr.opcode = SD_OP_NEW_VDI;
1192
    hdr.base_vdi_id = base_vid;
1193

    
1194
    wlen = SD_MAX_VDI_LEN;
1195

    
1196
    hdr.flags = SD_FLAG_CMD_WRITE;
1197
    hdr.snapid = snapshot;
1198

    
1199
    hdr.data_length = wlen;
1200
    hdr.vdi_size = vdi_size;
1201

    
1202
    ret = do_req(fd, (SheepdogReq *)&hdr, buf, &wlen, &rlen);
1203

    
1204
    closesocket(fd);
1205

    
1206
    if (ret) {
1207
        return ret;
1208
    }
1209

    
1210
    if (rsp->result != SD_RES_SUCCESS) {
1211
        error_report("%s, %s", sd_strerror(rsp->result), filename);
1212
        return -EIO;
1213
    }
1214

    
1215
    if (vdi_id) {
1216
        *vdi_id = rsp->vdi_id;
1217
    }
1218

    
1219
    return 0;
1220
}
1221

    
1222
static int sd_prealloc(const char *filename)
1223
{
1224
    BlockDriverState *bs = NULL;
1225
    uint32_t idx, max_idx;
1226
    int64_t vdi_size;
1227
    void *buf = g_malloc0(SD_DATA_OBJ_SIZE);
1228
    int ret;
1229

    
1230
    ret = bdrv_file_open(&bs, filename, BDRV_O_RDWR);
1231
    if (ret < 0) {
1232
        goto out;
1233
    }
1234

    
1235
    vdi_size = bdrv_getlength(bs);
1236
    if (vdi_size < 0) {
1237
        ret = vdi_size;
1238
        goto out;
1239
    }
1240
    max_idx = DIV_ROUND_UP(vdi_size, SD_DATA_OBJ_SIZE);
1241

    
1242
    for (idx = 0; idx < max_idx; idx++) {
1243
        /*
1244
         * The created image can be a cloned image, so we need to read
1245
         * a data from the source image.
1246
         */
1247
        ret = bdrv_pread(bs, idx * SD_DATA_OBJ_SIZE, buf, SD_DATA_OBJ_SIZE);
1248
        if (ret < 0) {
1249
            goto out;
1250
        }
1251
        ret = bdrv_pwrite(bs, idx * SD_DATA_OBJ_SIZE, buf, SD_DATA_OBJ_SIZE);
1252
        if (ret < 0) {
1253
            goto out;
1254
        }
1255
    }
1256
out:
1257
    if (bs) {
1258
        bdrv_delete(bs);
1259
    }
1260
    g_free(buf);
1261

    
1262
    return ret;
1263
}
1264

    
1265
static int sd_create(const char *filename, QEMUOptionParameter *options)
1266
{
1267
    int ret = 0;
1268
    uint32_t vid = 0, base_vid = 0;
1269
    int64_t vdi_size = 0;
1270
    char *backing_file = NULL;
1271
    BDRVSheepdogState *s;
1272
    char vdi[SD_MAX_VDI_LEN], tag[SD_MAX_VDI_TAG_LEN];
1273
    uint32_t snapid;
1274
    bool prealloc = false;
1275
    const char *vdiname;
1276

    
1277
    s = g_malloc0(sizeof(BDRVSheepdogState));
1278

    
1279
    strstart(filename, "sheepdog:", &vdiname);
1280

    
1281
    memset(vdi, 0, sizeof(vdi));
1282
    memset(tag, 0, sizeof(tag));
1283
    if (parse_vdiname(s, vdiname, vdi, &snapid, tag) < 0) {
1284
        error_report("invalid filename");
1285
        ret = -EINVAL;
1286
        goto out;
1287
    }
1288

    
1289
    while (options && options->name) {
1290
        if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
1291
            vdi_size = options->value.n;
1292
        } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
1293
            backing_file = options->value.s;
1294
        } else if (!strcmp(options->name, BLOCK_OPT_PREALLOC)) {
1295
            if (!options->value.s || !strcmp(options->value.s, "off")) {
1296
                prealloc = false;
1297
            } else if (!strcmp(options->value.s, "full")) {
1298
                prealloc = true;
1299
            } else {
1300
                error_report("Invalid preallocation mode: '%s'",
1301
                             options->value.s);
1302
                ret = -EINVAL;
1303
                goto out;
1304
            }
1305
        }
1306
        options++;
1307
    }
1308

    
1309
    if (vdi_size > SD_MAX_VDI_SIZE) {
1310
        error_report("too big image size");
1311
        ret = -EINVAL;
1312
        goto out;
1313
    }
1314

    
1315
    if (backing_file) {
1316
        BlockDriverState *bs;
1317
        BDRVSheepdogState *s;
1318
        BlockDriver *drv;
1319

    
1320
        /* Currently, only Sheepdog backing image is supported. */
1321
        drv = bdrv_find_protocol(backing_file);
1322
        if (!drv || strcmp(drv->protocol_name, "sheepdog") != 0) {
1323
            error_report("backing_file must be a sheepdog image");
1324
            ret = -EINVAL;
1325
            goto out;
1326
        }
1327

    
1328
        ret = bdrv_file_open(&bs, backing_file, 0);
1329
        if (ret < 0) {
1330
            goto out;
1331
        }
1332

    
1333
        s = bs->opaque;
1334

    
1335
        if (!is_snapshot(&s->inode)) {
1336
            error_report("cannot clone from a non snapshot vdi");
1337
            bdrv_delete(bs);
1338
            ret = -EINVAL;
1339
            goto out;
1340
        }
1341

    
1342
        base_vid = s->inode.vdi_id;
1343
        bdrv_delete(bs);
1344
    }
1345

    
1346
    ret = do_sd_create(vdi, vdi_size, base_vid, &vid, 0, s->addr, s->port);
1347
    if (!prealloc || ret) {
1348
        goto out;
1349
    }
1350

    
1351
    ret = sd_prealloc(filename);
1352
out:
1353
    g_free(s);
1354
    return ret;
1355
}
1356

    
1357
static void sd_close(BlockDriverState *bs)
1358
{
1359
    BDRVSheepdogState *s = bs->opaque;
1360
    SheepdogVdiReq hdr;
1361
    SheepdogVdiRsp *rsp = (SheepdogVdiRsp *)&hdr;
1362
    unsigned int wlen, rlen = 0;
1363
    int fd, ret;
1364

    
1365
    dprintf("%s\n", s->name);
1366

    
1367
    fd = connect_to_sdog(s->addr, s->port);
1368
    if (fd < 0) {
1369
        return;
1370
    }
1371

    
1372
    memset(&hdr, 0, sizeof(hdr));
1373

    
1374
    hdr.opcode = SD_OP_RELEASE_VDI;
1375
    wlen = strlen(s->name) + 1;
1376
    hdr.data_length = wlen;
1377
    hdr.flags = SD_FLAG_CMD_WRITE;
1378

    
1379
    ret = do_req(fd, (SheepdogReq *)&hdr, s->name, &wlen, &rlen);
1380

    
1381
    closesocket(fd);
1382

    
1383
    if (!ret && rsp->result != SD_RES_SUCCESS &&
1384
        rsp->result != SD_RES_VDI_NOT_LOCKED) {
1385
        error_report("%s, %s", sd_strerror(rsp->result), s->name);
1386
    }
1387

    
1388
    qemu_aio_set_fd_handler(s->fd, NULL, NULL, NULL, NULL);
1389
    closesocket(s->fd);
1390
    if (s->cache_enabled) {
1391
        closesocket(s->flush_fd);
1392
    }
1393
    g_free(s->addr);
1394
}
1395

    
1396
static int64_t sd_getlength(BlockDriverState *bs)
1397
{
1398
    BDRVSheepdogState *s = bs->opaque;
1399

    
1400
    return s->inode.vdi_size;
1401
}
1402

    
1403
static int sd_truncate(BlockDriverState *bs, int64_t offset)
1404
{
1405
    BDRVSheepdogState *s = bs->opaque;
1406
    int ret, fd;
1407
    unsigned int datalen;
1408

    
1409
    if (offset < s->inode.vdi_size) {
1410
        error_report("shrinking is not supported");
1411
        return -EINVAL;
1412
    } else if (offset > SD_MAX_VDI_SIZE) {
1413
        error_report("too big image size");
1414
        return -EINVAL;
1415
    }
1416

    
1417
    fd = connect_to_sdog(s->addr, s->port);
1418
    if (fd < 0) {
1419
        return fd;
1420
    }
1421

    
1422
    /* we don't need to update entire object */
1423
    datalen = SD_INODE_SIZE - sizeof(s->inode.data_vdi_id);
1424
    s->inode.vdi_size = offset;
1425
    ret = write_object(fd, (char *)&s->inode, vid_to_vdi_oid(s->inode.vdi_id),
1426
                       s->inode.nr_copies, datalen, 0, false, s->cache_enabled);
1427
    close(fd);
1428

    
1429
    if (ret < 0) {
1430
        error_report("failed to update an inode.");
1431
    }
1432

    
1433
    return ret;
1434
}
1435

    
1436
/*
1437
 * This function is called after writing data objects.  If we need to
1438
 * update metadata, this sends a write request to the vdi object.
1439
 * Otherwise, this switches back to sd_co_readv/writev.
1440
 */
1441
static void coroutine_fn sd_write_done(SheepdogAIOCB *acb)
1442
{
1443
    int ret;
1444
    BDRVSheepdogState *s = acb->common.bs->opaque;
1445
    struct iovec iov;
1446
    AIOReq *aio_req;
1447
    uint32_t offset, data_len, mn, mx;
1448

    
1449
    mn = s->min_dirty_data_idx;
1450
    mx = s->max_dirty_data_idx;
1451
    if (mn <= mx) {
1452
        /* we need to update the vdi object. */
1453
        offset = sizeof(s->inode) - sizeof(s->inode.data_vdi_id) +
1454
            mn * sizeof(s->inode.data_vdi_id[0]);
1455
        data_len = (mx - mn + 1) * sizeof(s->inode.data_vdi_id[0]);
1456

    
1457
        s->min_dirty_data_idx = UINT32_MAX;
1458
        s->max_dirty_data_idx = 0;
1459

    
1460
        iov.iov_base = &s->inode;
1461
        iov.iov_len = sizeof(s->inode);
1462
        aio_req = alloc_aio_req(s, acb, vid_to_vdi_oid(s->inode.vdi_id),
1463
                                data_len, offset, 0, 0, offset);
1464
        QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
1465
        ret = add_aio_request(s, aio_req, &iov, 1, false, AIOCB_WRITE_UDATA);
1466
        if (ret) {
1467
            free_aio_req(s, aio_req);
1468
            acb->ret = -EIO;
1469
            goto out;
1470
        }
1471

    
1472
        acb->aio_done_func = sd_finish_aiocb;
1473
        acb->aiocb_type = AIOCB_WRITE_UDATA;
1474
        return;
1475
    }
1476
out:
1477
    sd_finish_aiocb(acb);
1478
}
1479

    
1480
/*
1481
 * Create a writable VDI from a snapshot
1482
 */
1483
static int sd_create_branch(BDRVSheepdogState *s)
1484
{
1485
    int ret, fd;
1486
    uint32_t vid;
1487
    char *buf;
1488

    
1489
    dprintf("%" PRIx32 " is snapshot.\n", s->inode.vdi_id);
1490

    
1491
    buf = g_malloc(SD_INODE_SIZE);
1492

    
1493
    ret = do_sd_create(s->name, s->inode.vdi_size, s->inode.vdi_id, &vid, 1,
1494
                       s->addr, s->port);
1495
    if (ret) {
1496
        goto out;
1497
    }
1498

    
1499
    dprintf("%" PRIx32 " is created.\n", vid);
1500

    
1501
    fd = connect_to_sdog(s->addr, s->port);
1502
    if (fd < 0) {
1503
        error_report("failed to connect");
1504
        ret = fd;
1505
        goto out;
1506
    }
1507

    
1508
    ret = read_object(fd, buf, vid_to_vdi_oid(vid), s->inode.nr_copies,
1509
                      SD_INODE_SIZE, 0, s->cache_enabled);
1510

    
1511
    closesocket(fd);
1512

    
1513
    if (ret < 0) {
1514
        goto out;
1515
    }
1516

    
1517
    memcpy(&s->inode, buf, sizeof(s->inode));
1518

    
1519
    s->is_snapshot = false;
1520
    ret = 0;
1521
    dprintf("%" PRIx32 " was newly created.\n", s->inode.vdi_id);
1522

    
1523
out:
1524
    g_free(buf);
1525

    
1526
    return ret;
1527
}
1528

    
1529
/*
1530
 * Send I/O requests to the server.
1531
 *
1532
 * This function sends requests to the server, links the requests to
1533
 * the inflight_list in BDRVSheepdogState, and exits without
1534
 * waiting the response.  The responses are received in the
1535
 * `aio_read_response' function which is called from the main loop as
1536
 * a fd handler.
1537
 *
1538
 * Returns 1 when we need to wait a response, 0 when there is no sent
1539
 * request and -errno in error cases.
1540
 */
1541
static int coroutine_fn sd_co_rw_vector(void *p)
1542
{
1543
    SheepdogAIOCB *acb = p;
1544
    int ret = 0;
1545
    unsigned long len, done = 0, total = acb->nb_sectors * SECTOR_SIZE;
1546
    unsigned long idx = acb->sector_num * SECTOR_SIZE / SD_DATA_OBJ_SIZE;
1547
    uint64_t oid;
1548
    uint64_t offset = (acb->sector_num * SECTOR_SIZE) % SD_DATA_OBJ_SIZE;
1549
    BDRVSheepdogState *s = acb->common.bs->opaque;
1550
    SheepdogInode *inode = &s->inode;
1551
    AIOReq *aio_req;
1552

    
1553
    if (acb->aiocb_type == AIOCB_WRITE_UDATA && s->is_snapshot) {
1554
        /*
1555
         * In the case we open the snapshot VDI, Sheepdog creates the
1556
         * writable VDI when we do a write operation first.
1557
         */
1558
        ret = sd_create_branch(s);
1559
        if (ret) {
1560
            acb->ret = -EIO;
1561
            goto out;
1562
        }
1563
    }
1564

    
1565
    /*
1566
     * Make sure we don't free the aiocb before we are done with all requests.
1567
     * This additional reference is dropped at the end of this function.
1568
     */
1569
    acb->nr_pending++;
1570

    
1571
    while (done != total) {
1572
        uint8_t flags = 0;
1573
        uint64_t old_oid = 0;
1574
        bool create = false;
1575

    
1576
        oid = vid_to_data_oid(inode->data_vdi_id[idx], idx);
1577

    
1578
        len = MIN(total - done, SD_DATA_OBJ_SIZE - offset);
1579

    
1580
        switch (acb->aiocb_type) {
1581
        case AIOCB_READ_UDATA:
1582
            if (!inode->data_vdi_id[idx]) {
1583
                qemu_iovec_memset(acb->qiov, done, 0, len);
1584
                goto done;
1585
            }
1586
            break;
1587
        case AIOCB_WRITE_UDATA:
1588
            if (!inode->data_vdi_id[idx]) {
1589
                create = true;
1590
            } else if (!is_data_obj_writable(inode, idx)) {
1591
                /* Copy-On-Write */
1592
                create = true;
1593
                old_oid = oid;
1594
                flags = SD_FLAG_CMD_COW;
1595
            }
1596
            break;
1597
        default:
1598
            break;
1599
        }
1600

    
1601
        if (create) {
1602
            dprintf("update ino (%" PRIu32 ") %" PRIu64 " %" PRIu64 " %ld\n",
1603
                    inode->vdi_id, oid,
1604
                    vid_to_data_oid(inode->data_vdi_id[idx], idx), idx);
1605
            oid = vid_to_data_oid(inode->vdi_id, idx);
1606
            dprintf("new oid %" PRIx64 "\n", oid);
1607
        }
1608

    
1609
        aio_req = alloc_aio_req(s, acb, oid, len, offset, flags, old_oid, done);
1610

    
1611
        if (create) {
1612
            AIOReq *areq;
1613
            QLIST_FOREACH(areq, &s->inflight_aio_head, aio_siblings) {
1614
                if (areq->oid == oid) {
1615
                    /*
1616
                     * Sheepdog cannot handle simultaneous create
1617
                     * requests to the same object.  So we cannot send
1618
                     * the request until the previous request
1619
                     * finishes.
1620
                     */
1621
                    aio_req->flags = 0;
1622
                    aio_req->base_oid = 0;
1623
                    QLIST_INSERT_HEAD(&s->pending_aio_head, aio_req,
1624
                                      aio_siblings);
1625
                    goto done;
1626
                }
1627
            }
1628
        }
1629

    
1630
        QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);
1631
        ret = add_aio_request(s, aio_req, acb->qiov->iov, acb->qiov->niov,
1632
                              create, acb->aiocb_type);
1633
        if (ret < 0) {
1634
            error_report("add_aio_request is failed");
1635
            free_aio_req(s, aio_req);
1636
            acb->ret = -EIO;
1637
            goto out;
1638
        }
1639
    done:
1640
        offset = 0;
1641
        idx++;
1642
        done += len;
1643
    }
1644
out:
1645
    if (!--acb->nr_pending) {
1646
        return acb->ret;
1647
    }
1648
    return 1;
1649
}
1650

    
1651
static coroutine_fn int sd_co_writev(BlockDriverState *bs, int64_t sector_num,
1652
                        int nb_sectors, QEMUIOVector *qiov)
1653
{
1654
    SheepdogAIOCB *acb;
1655
    int ret;
1656

    
1657
    if (bs->growable && sector_num + nb_sectors > bs->total_sectors) {
1658
        ret = sd_truncate(bs, (sector_num + nb_sectors) * SECTOR_SIZE);
1659
        if (ret < 0) {
1660
            return ret;
1661
        }
1662
        bs->total_sectors = sector_num + nb_sectors;
1663
    }
1664

    
1665
    acb = sd_aio_setup(bs, qiov, sector_num, nb_sectors, NULL, NULL);
1666
    acb->aio_done_func = sd_write_done;
1667
    acb->aiocb_type = AIOCB_WRITE_UDATA;
1668

    
1669
    ret = sd_co_rw_vector(acb);
1670
    if (ret <= 0) {
1671
        qemu_aio_release(acb);
1672
        return ret;
1673
    }
1674

    
1675
    qemu_coroutine_yield();
1676

    
1677
    return acb->ret;
1678
}
1679

    
1680
static coroutine_fn int sd_co_readv(BlockDriverState *bs, int64_t sector_num,
1681
                       int nb_sectors, QEMUIOVector *qiov)
1682
{
1683
    SheepdogAIOCB *acb;
1684
    int ret;
1685

    
1686
    acb = sd_aio_setup(bs, qiov, sector_num, nb_sectors, NULL, NULL);
1687
    acb->aiocb_type = AIOCB_READ_UDATA;
1688
    acb->aio_done_func = sd_finish_aiocb;
1689

    
1690
    ret = sd_co_rw_vector(acb);
1691
    if (ret <= 0) {
1692
        qemu_aio_release(acb);
1693
        return ret;
1694
    }
1695

    
1696
    qemu_coroutine_yield();
1697

    
1698
    return acb->ret;
1699
}
1700

    
1701
static int coroutine_fn sd_co_flush_to_disk(BlockDriverState *bs)
1702
{
1703
    BDRVSheepdogState *s = bs->opaque;
1704
    SheepdogObjReq hdr = { 0 };
1705
    SheepdogObjRsp *rsp = (SheepdogObjRsp *)&hdr;
1706
    SheepdogInode *inode = &s->inode;
1707
    int ret;
1708
    unsigned int wlen = 0, rlen = 0;
1709

    
1710
    if (!s->cache_enabled) {
1711
        return 0;
1712
    }
1713

    
1714
    hdr.opcode = SD_OP_FLUSH_VDI;
1715
    hdr.oid = vid_to_vdi_oid(inode->vdi_id);
1716

    
1717
    ret = do_req(s->flush_fd, (SheepdogReq *)&hdr, NULL, &wlen, &rlen);
1718
    if (ret) {
1719
        error_report("failed to send a request to the sheep");
1720
        return ret;
1721
    }
1722

    
1723
    if (rsp->result == SD_RES_INVALID_PARMS) {
1724
        dprintf("disable write cache since the server doesn't support it\n");
1725

    
1726
        s->cache_enabled = false;
1727
        closesocket(s->flush_fd);
1728
        return 0;
1729
    }
1730

    
1731
    if (rsp->result != SD_RES_SUCCESS) {
1732
        error_report("%s", sd_strerror(rsp->result));
1733
        return -EIO;
1734
    }
1735

    
1736
    return 0;
1737
}
1738

    
1739
static int sd_snapshot_create(BlockDriverState *bs, QEMUSnapshotInfo *sn_info)
1740
{
1741
    BDRVSheepdogState *s = bs->opaque;
1742
    int ret, fd;
1743
    uint32_t new_vid;
1744
    SheepdogInode *inode;
1745
    unsigned int datalen;
1746

    
1747
    dprintf("sn_info: name %s id_str %s s: name %s vm_state_size %" PRId64 " "
1748
            "is_snapshot %d\n", sn_info->name, sn_info->id_str,
1749
            s->name, sn_info->vm_state_size, s->is_snapshot);
1750

    
1751
    if (s->is_snapshot) {
1752
        error_report("You can't create a snapshot of a snapshot VDI, "
1753
                     "%s (%" PRIu32 ").", s->name, s->inode.vdi_id);
1754

    
1755
        return -EINVAL;
1756
    }
1757

    
1758
    dprintf("%s %s\n", sn_info->name, sn_info->id_str);
1759

    
1760
    s->inode.vm_state_size = sn_info->vm_state_size;
1761
    s->inode.vm_clock_nsec = sn_info->vm_clock_nsec;
1762
    /* It appears that inode.tag does not require a NUL terminator,
1763
     * which means this use of strncpy is ok.
1764
     */
1765
    strncpy(s->inode.tag, sn_info->name, sizeof(s->inode.tag));
1766
    /* we don't need to update entire object */
1767
    datalen = SD_INODE_SIZE - sizeof(s->inode.data_vdi_id);
1768

    
1769
    /* refresh inode. */
1770
    fd = connect_to_sdog(s->addr, s->port);
1771
    if (fd < 0) {
1772
        ret = fd;
1773
        goto cleanup;
1774
    }
1775

    
1776
    ret = write_object(fd, (char *)&s->inode, vid_to_vdi_oid(s->inode.vdi_id),
1777
                       s->inode.nr_copies, datalen, 0, false, s->cache_enabled);
1778
    if (ret < 0) {
1779
        error_report("failed to write snapshot's inode.");
1780
        goto cleanup;
1781
    }
1782

    
1783
    ret = do_sd_create(s->name, s->inode.vdi_size, s->inode.vdi_id, &new_vid, 1,
1784
                       s->addr, s->port);
1785
    if (ret < 0) {
1786
        error_report("failed to create inode for snapshot. %s",
1787
                     strerror(errno));
1788
        goto cleanup;
1789
    }
1790

    
1791
    inode = (SheepdogInode *)g_malloc(datalen);
1792

    
1793
    ret = read_object(fd, (char *)inode, vid_to_vdi_oid(new_vid),
1794
                      s->inode.nr_copies, datalen, 0, s->cache_enabled);
1795

    
1796
    if (ret < 0) {
1797
        error_report("failed to read new inode info. %s", strerror(errno));
1798
        goto cleanup;
1799
    }
1800

    
1801
    memcpy(&s->inode, inode, datalen);
1802
    dprintf("s->inode: name %s snap_id %x oid %x\n",
1803
            s->inode.name, s->inode.snap_id, s->inode.vdi_id);
1804

    
1805
cleanup:
1806
    closesocket(fd);
1807
    return ret;
1808
}
1809

    
1810
static int sd_snapshot_goto(BlockDriverState *bs, const char *snapshot_id)
1811
{
1812
    BDRVSheepdogState *s = bs->opaque;
1813
    BDRVSheepdogState *old_s;
1814
    char vdi[SD_MAX_VDI_LEN], tag[SD_MAX_VDI_TAG_LEN];
1815
    char *buf = NULL;
1816
    uint32_t vid;
1817
    uint32_t snapid = 0;
1818
    int ret = 0, fd;
1819

    
1820
    old_s = g_malloc(sizeof(BDRVSheepdogState));
1821

    
1822
    memcpy(old_s, s, sizeof(BDRVSheepdogState));
1823

    
1824
    pstrcpy(vdi, sizeof(vdi), s->name);
1825

    
1826
    snapid = strtoul(snapshot_id, NULL, 10);
1827
    if (snapid) {
1828
        tag[0] = 0;
1829
    } else {
1830
        pstrcpy(tag, sizeof(tag), s->name);
1831
    }
1832

    
1833
    ret = find_vdi_name(s, vdi, snapid, tag, &vid, 1);
1834
    if (ret) {
1835
        error_report("Failed to find_vdi_name");
1836
        goto out;
1837
    }
1838

    
1839
    fd = connect_to_sdog(s->addr, s->port);
1840
    if (fd < 0) {
1841
        error_report("failed to connect");
1842
        ret = fd;
1843
        goto out;
1844
    }
1845

    
1846
    buf = g_malloc(SD_INODE_SIZE);
1847
    ret = read_object(fd, buf, vid_to_vdi_oid(vid), s->inode.nr_copies,
1848
                      SD_INODE_SIZE, 0, s->cache_enabled);
1849

    
1850
    closesocket(fd);
1851

    
1852
    if (ret) {
1853
        goto out;
1854
    }
1855

    
1856
    memcpy(&s->inode, buf, sizeof(s->inode));
1857

    
1858
    if (!s->inode.vm_state_size) {
1859
        error_report("Invalid snapshot");
1860
        ret = -ENOENT;
1861
        goto out;
1862
    }
1863

    
1864
    s->is_snapshot = true;
1865

    
1866
    g_free(buf);
1867
    g_free(old_s);
1868

    
1869
    return 0;
1870
out:
1871
    /* recover bdrv_sd_state */
1872
    memcpy(s, old_s, sizeof(BDRVSheepdogState));
1873
    g_free(buf);
1874
    g_free(old_s);
1875

    
1876
    error_report("failed to open. recover old bdrv_sd_state.");
1877

    
1878
    return ret;
1879
}
1880

    
1881
static int sd_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
1882
{
1883
    /* FIXME: Delete specified snapshot id.  */
1884
    return 0;
1885
}
1886

    
1887
static int sd_snapshot_list(BlockDriverState *bs, QEMUSnapshotInfo **psn_tab)
1888
{
1889
    BDRVSheepdogState *s = bs->opaque;
1890
    SheepdogReq req;
1891
    int fd, nr = 1024, ret, max = BITS_TO_LONGS(SD_NR_VDIS) * sizeof(long);
1892
    QEMUSnapshotInfo *sn_tab = NULL;
1893
    unsigned wlen, rlen;
1894
    int found = 0;
1895
    static SheepdogInode inode;
1896
    unsigned long *vdi_inuse;
1897
    unsigned int start_nr;
1898
    uint64_t hval;
1899
    uint32_t vid;
1900

    
1901
    vdi_inuse = g_malloc(max);
1902

    
1903
    fd = connect_to_sdog(s->addr, s->port);
1904
    if (fd < 0) {
1905
        ret = fd;
1906
        goto out;
1907
    }
1908

    
1909
    rlen = max;
1910
    wlen = 0;
1911

    
1912
    memset(&req, 0, sizeof(req));
1913

    
1914
    req.opcode = SD_OP_READ_VDIS;
1915
    req.data_length = max;
1916

    
1917
    ret = do_req(fd, (SheepdogReq *)&req, vdi_inuse, &wlen, &rlen);
1918

    
1919
    closesocket(fd);
1920
    if (ret) {
1921
        goto out;
1922
    }
1923

    
1924
    sn_tab = g_malloc0(nr * sizeof(*sn_tab));
1925

    
1926
    /* calculate a vdi id with hash function */
1927
    hval = fnv_64a_buf(s->name, strlen(s->name), FNV1A_64_INIT);
1928
    start_nr = hval & (SD_NR_VDIS - 1);
1929

    
1930
    fd = connect_to_sdog(s->addr, s->port);
1931
    if (fd < 0) {
1932
        error_report("failed to connect");
1933
        ret = fd;
1934
        goto out;
1935
    }
1936

    
1937
    for (vid = start_nr; found < nr; vid = (vid + 1) % SD_NR_VDIS) {
1938
        if (!test_bit(vid, vdi_inuse)) {
1939
            break;
1940
        }
1941

    
1942
        /* we don't need to read entire object */
1943
        ret = read_object(fd, (char *)&inode, vid_to_vdi_oid(vid),
1944
                          0, SD_INODE_SIZE - sizeof(inode.data_vdi_id), 0,
1945
                          s->cache_enabled);
1946

    
1947
        if (ret) {
1948
            continue;
1949
        }
1950

    
1951
        if (!strcmp(inode.name, s->name) && is_snapshot(&inode)) {
1952
            sn_tab[found].date_sec = inode.snap_ctime >> 32;
1953
            sn_tab[found].date_nsec = inode.snap_ctime & 0xffffffff;
1954
            sn_tab[found].vm_state_size = inode.vm_state_size;
1955
            sn_tab[found].vm_clock_nsec = inode.vm_clock_nsec;
1956

    
1957
            snprintf(sn_tab[found].id_str, sizeof(sn_tab[found].id_str), "%u",
1958
                     inode.snap_id);
1959
            pstrcpy(sn_tab[found].name,
1960
                    MIN(sizeof(sn_tab[found].name), sizeof(inode.tag)),
1961
                    inode.tag);
1962
            found++;
1963
        }
1964
    }
1965

    
1966
    closesocket(fd);
1967
out:
1968
    *psn_tab = sn_tab;
1969

    
1970
    g_free(vdi_inuse);
1971

    
1972
    if (ret < 0) {
1973
        return ret;
1974
    }
1975

    
1976
    return found;
1977
}
1978

    
1979
static int do_load_save_vmstate(BDRVSheepdogState *s, uint8_t *data,
1980
                                int64_t pos, int size, int load)
1981
{
1982
    bool create;
1983
    int fd, ret = 0, remaining = size;
1984
    unsigned int data_len;
1985
    uint64_t vmstate_oid;
1986
    uint32_t vdi_index;
1987
    uint64_t offset;
1988

    
1989
    fd = connect_to_sdog(s->addr, s->port);
1990
    if (fd < 0) {
1991
        return fd;
1992
    }
1993

    
1994
    while (remaining) {
1995
        vdi_index = pos / SD_DATA_OBJ_SIZE;
1996
        offset = pos % SD_DATA_OBJ_SIZE;
1997

    
1998
        data_len = MIN(remaining, SD_DATA_OBJ_SIZE - offset);
1999

    
2000
        vmstate_oid = vid_to_vmstate_oid(s->inode.vdi_id, vdi_index);
2001

    
2002
        create = (offset == 0);
2003
        if (load) {
2004
            ret = read_object(fd, (char *)data, vmstate_oid,
2005
                              s->inode.nr_copies, data_len, offset,
2006
                              s->cache_enabled);
2007
        } else {
2008
            ret = write_object(fd, (char *)data, vmstate_oid,
2009
                               s->inode.nr_copies, data_len, offset, create,
2010
                               s->cache_enabled);
2011
        }
2012

    
2013
        if (ret < 0) {
2014
            error_report("failed to save vmstate %s", strerror(errno));
2015
            goto cleanup;
2016
        }
2017

    
2018
        pos += data_len;
2019
        data += data_len;
2020
        remaining -= data_len;
2021
    }
2022
    ret = size;
2023
cleanup:
2024
    closesocket(fd);
2025
    return ret;
2026
}
2027

    
2028
static int sd_save_vmstate(BlockDriverState *bs, const uint8_t *data,
2029
                           int64_t pos, int size)
2030
{
2031
    BDRVSheepdogState *s = bs->opaque;
2032

    
2033
    return do_load_save_vmstate(s, (uint8_t *)data, pos, size, 0);
2034
}
2035

    
2036
static int sd_load_vmstate(BlockDriverState *bs, uint8_t *data,
2037
                           int64_t pos, int size)
2038
{
2039
    BDRVSheepdogState *s = bs->opaque;
2040

    
2041
    return do_load_save_vmstate(s, data, pos, size, 1);
2042
}
2043

    
2044

    
2045
static QEMUOptionParameter sd_create_options[] = {
2046
    {
2047
        .name = BLOCK_OPT_SIZE,
2048
        .type = OPT_SIZE,
2049
        .help = "Virtual disk size"
2050
    },
2051
    {
2052
        .name = BLOCK_OPT_BACKING_FILE,
2053
        .type = OPT_STRING,
2054
        .help = "File name of a base image"
2055
    },
2056
    {
2057
        .name = BLOCK_OPT_PREALLOC,
2058
        .type = OPT_STRING,
2059
        .help = "Preallocation mode (allowed values: off, full)"
2060
    },
2061
    { NULL }
2062
};
2063

    
2064
BlockDriver bdrv_sheepdog = {
2065
    .format_name    = "sheepdog",
2066
    .protocol_name  = "sheepdog",
2067
    .instance_size  = sizeof(BDRVSheepdogState),
2068
    .bdrv_file_open = sd_open,
2069
    .bdrv_close     = sd_close,
2070
    .bdrv_create    = sd_create,
2071
    .bdrv_getlength = sd_getlength,
2072
    .bdrv_truncate  = sd_truncate,
2073

    
2074
    .bdrv_co_readv  = sd_co_readv,
2075
    .bdrv_co_writev = sd_co_writev,
2076
    .bdrv_co_flush_to_disk  = sd_co_flush_to_disk,
2077

    
2078
    .bdrv_snapshot_create   = sd_snapshot_create,
2079
    .bdrv_snapshot_goto     = sd_snapshot_goto,
2080
    .bdrv_snapshot_delete   = sd_snapshot_delete,
2081
    .bdrv_snapshot_list     = sd_snapshot_list,
2082

    
2083
    .bdrv_save_vmstate  = sd_save_vmstate,
2084
    .bdrv_load_vmstate  = sd_load_vmstate,
2085

    
2086
    .create_options = sd_create_options,
2087
};
2088

    
2089
static void bdrv_sheepdog_init(void)
2090
{
2091
    bdrv_register(&bdrv_sheepdog);
2092
}
2093
block_init(bdrv_sheepdog_init);