nbd.c 13.7 KB
Newer Older
1 2 3 4
/*
 * QEMU Block driver for  NBD
 *
 * Copyright (C) 2008 Bull S.A.S.
M
malc 已提交
5
 *     Author: Laurent Vivier <Laurent.Vivier@bull.net>
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
 *
 * Some parts:
 *    Copyright (C) 2007 Anthony Liguori <anthony@codemonkey.ws>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

M
Marc-André Lureau 已提交
29
#include "block/nbd-client.h"
30
#include "qemu/uri.h"
31
#include "block/block_int.h"
32 33
#include "qemu/module.h"
#include "qemu/sockets.h"
34
#include "qapi/qmp/qdict.h"
35 36
#include "qapi/qmp/qjson.h"
#include "qapi/qmp/qint.h"
37
#include "qapi/qmp/qstring.h"
38 39 40 41

#include <sys/types.h>
#include <unistd.h>

42 43
#define EN_OPTSTR ":exportname="

44
typedef struct BDRVNBDState {
M
Marc-André Lureau 已提交
45
    NbdClientSession client;
46
    QemuOpts *socket_opts;
47 48
} BDRVNBDState;

49
static int nbd_parse_uri(const char *filename, QDict *options)
P
Paolo Bonzini 已提交
50 51 52 53 54
{
    URI *uri;
    const char *p;
    QueryParams *qp = NULL;
    int ret = 0;
55
    bool is_unix;
P
Paolo Bonzini 已提交
56 57 58 59 60 61 62 63

    uri = uri_parse(filename);
    if (!uri) {
        return -EINVAL;
    }

    /* transport */
    if (!strcmp(uri->scheme, "nbd")) {
64
        is_unix = false;
P
Paolo Bonzini 已提交
65
    } else if (!strcmp(uri->scheme, "nbd+tcp")) {
66
        is_unix = false;
P
Paolo Bonzini 已提交
67
    } else if (!strcmp(uri->scheme, "nbd+unix")) {
68
        is_unix = true;
P
Paolo Bonzini 已提交
69 70 71 72 73 74 75 76
    } else {
        ret = -EINVAL;
        goto out;
    }

    p = uri->path ? uri->path : "/";
    p += strspn(p, "/");
    if (p[0]) {
77
        qdict_put(options, "export", qstring_from_str(p));
P
Paolo Bonzini 已提交
78 79 80
    }

    qp = query_params_parse(uri->query);
81
    if (qp->n > 1 || (is_unix && !qp->n) || (!is_unix && qp->n)) {
P
Paolo Bonzini 已提交
82 83 84 85
        ret = -EINVAL;
        goto out;
    }

86
    if (is_unix) {
P
Paolo Bonzini 已提交
87 88 89 90 91
        /* nbd+unix:///export?socket=path */
        if (uri->server || uri->port || strcmp(qp->p[0].name, "socket")) {
            ret = -EINVAL;
            goto out;
        }
92
        qdict_put(options, "path", qstring_from_str(qp->p[0].value));
P
Paolo Bonzini 已提交
93
    } else {
94
        QString *host;
95
        /* nbd[+tcp]://host[:port]/export */
P
Paolo Bonzini 已提交
96 97 98 99
        if (!uri->server) {
            ret = -EINVAL;
            goto out;
        }
100

101 102 103 104 105 106 107 108 109
        /* strip braces from literal IPv6 address */
        if (uri->server[0] == '[') {
            host = qstring_from_substr(uri->server, 1,
                                       strlen(uri->server) - 2);
        } else {
            host = qstring_from_str(uri->server);
        }

        qdict_put(options, "host", host);
110 111 112 113 114
        if (uri->port) {
            char* port_str = g_strdup_printf("%d", uri->port);
            qdict_put(options, "port", qstring_from_str(port_str));
            g_free(port_str);
        }
P
Paolo Bonzini 已提交
115 116 117 118 119 120 121 122 123 124
    }

out:
    if (qp) {
        query_params_free(qp);
    }
    uri_free(uri);
    return ret;
}

125 126
static void nbd_parse_filename(const char *filename, QDict *options,
                               Error **errp)
127
{
128
    char *file;
129 130
    char *export_name;
    const char *host_spec;
131 132
    const char *unixpath;

133 134 135 136 137 138 139 140 141
    if (qdict_haskey(options, "host")
        || qdict_haskey(options, "port")
        || qdict_haskey(options, "path"))
    {
        error_setg(errp, "host/port/path and a file name may not be specified "
                         "at the same time");
        return;
    }

P
Paolo Bonzini 已提交
142
    if (strstr(filename, "://")) {
143 144 145 146 147
        int ret = nbd_parse_uri(filename, options);
        if (ret < 0) {
            error_setg(errp, "No valid URL specified");
        }
        return;
P
Paolo Bonzini 已提交
148 149
    }

150
    file = g_strdup(filename);
151

152 153 154
    export_name = strstr(file, EN_OPTSTR);
    if (export_name) {
        if (export_name[strlen(EN_OPTSTR)] == 0) {
155 156
            goto out;
        }
157 158
        export_name[0] = 0; /* truncate 'file' */
        export_name += strlen(EN_OPTSTR);
159 160

        qdict_put(options, "export", qstring_from_str(export_name));
161 162
    }

163 164
    /* extract the host_spec - fail if it's not nbd:... */
    if (!strstart(file, "nbd:", &host_spec)) {
165
        error_setg(errp, "File name string for NBD must start with 'nbd:'");
166 167
        goto out;
    }
168

169 170 171 172
    if (!*host_spec) {
        goto out;
    }

173 174
    /* are we a UNIX or TCP socket? */
    if (strstart(host_spec, "unix:", &unixpath)) {
175
        qdict_put(options, "path", qstring_from_str(unixpath));
176
    } else {
177 178
        InetSocketAddress *addr = NULL;

179
        addr = inet_parse(host_spec, errp);
180
        if (!addr) {
181 182
            goto out;
        }
183

184 185 186 187
        qdict_put(options, "host", qstring_from_str(addr->host));
        qdict_put(options, "port", qstring_from_str(addr->port));
        qapi_free_InetSocketAddress(addr);
    }
188

189
out:
190
    g_free(file);
191 192
}

P
Paolo Bonzini 已提交
193 194
static void nbd_config(BDRVNBDState *s, QDict *options, char **export,
                       Error **errp)
195 196 197
{
    Error *local_err = NULL;

198 199
    if (qdict_haskey(options, "path") == qdict_haskey(options, "host")) {
        if (qdict_haskey(options, "path")) {
P
Paolo Bonzini 已提交
200
            error_setg(errp, "path and host may not be used at the same time.");
201
        } else {
P
Paolo Bonzini 已提交
202
            error_setg(errp, "one of path and host must be specified.");
203
        }
P
Paolo Bonzini 已提交
204
        return;
205
    }
206

207
    s->client.is_unix = qdict_haskey(options, "path");
208 209
    s->socket_opts = qemu_opts_create(&socket_optslist, NULL, 0,
                                      &error_abort);
210 211

    qemu_opts_absorb_qdict(s->socket_opts, options, &local_err);
212
    if (local_err) {
P
Paolo Bonzini 已提交
213 214
        error_propagate(errp, local_err);
        return;
215 216
    }

217 218 219 220
    if (!qemu_opt_get(s->socket_opts, "port")) {
        qemu_opt_set_number(s->socket_opts, "port", NBD_DEFAULT_PORT);
    }

221 222
    *export = g_strdup(qdict_get_try_str(options, "export"));
    if (*export) {
223 224
        qdict_del(options, "export");
    }
225
}
226

P
Paolo Bonzini 已提交
227
static int nbd_establish_connection(BlockDriverState *bs, Error **errp)
228 229 230
{
    BDRVNBDState *s = bs->opaque;
    int sock;
231

M
Marc-André Lureau 已提交
232
    if (s->client.is_unix) {
P
Paolo Bonzini 已提交
233
        sock = unix_connect_opts(s->socket_opts, errp, NULL, NULL);
234
    } else {
P
Paolo Bonzini 已提交
235
        sock = inet_connect_opts(s->socket_opts, errp, NULL, NULL);
S
Stefan Hajnoczi 已提交
236 237 238
        if (sock >= 0) {
            socket_set_nodelay(sock);
        }
239 240
    }

241
    /* Failed to establish connection */
242
    if (sock < 0) {
243 244
        logout("Failed to establish connection to NBD server\n");
        return -errno;
245
    }
246

M
Marc-André Lureau 已提交
247
    return sock;
248 249
}

M
Max Reitz 已提交
250 251
static int nbd_open(BlockDriverState *bs, QDict *options, int flags,
                    Error **errp)
252 253
{
    BDRVNBDState *s = bs->opaque;
254
    char *export = NULL;
M
Marc-André Lureau 已提交
255
    int result, sock;
P
Paolo Bonzini 已提交
256
    Error *local_err = NULL;
257

258
    /* Pop the config into our state object. Exit if invalid. */
P
Paolo Bonzini 已提交
259 260 261 262
    nbd_config(s, options, &export, &local_err);
    if (local_err) {
        error_propagate(errp, local_err);
        return -EINVAL;
263 264 265 266 267
    }

    /* establish TCP connection, return error if it fails
     * TODO: Configurable retry-until-timeout behaviour.
     */
P
Paolo Bonzini 已提交
268
    sock = nbd_establish_connection(bs, errp);
M
Marc-André Lureau 已提交
269 270
    if (sock < 0) {
        return sock;
271 272
    }

M
Marc-André Lureau 已提交
273
    /* NBD handshake */
M
Max Reitz 已提交
274
    result = nbd_client_session_init(&s->client, bs, sock, export, errp);
275 276
    g_free(export);
    return result;
277 278
}

P
Paolo Bonzini 已提交
279 280 281
static int nbd_co_readv(BlockDriverState *bs, int64_t sector_num,
                        int nb_sectors, QEMUIOVector *qiov)
{
M
Marc-André Lureau 已提交
282 283 284 285
    BDRVNBDState *s = bs->opaque;

    return nbd_client_session_co_readv(&s->client, sector_num,
                                       nb_sectors, qiov);
P
Paolo Bonzini 已提交
286 287 288 289 290
}

static int nbd_co_writev(BlockDriverState *bs, int64_t sector_num,
                         int nb_sectors, QEMUIOVector *qiov)
{
M
Marc-André Lureau 已提交
291 292 293 294
    BDRVNBDState *s = bs->opaque;

    return nbd_client_session_co_writev(&s->client, sector_num,
                                        nb_sectors, qiov);
P
Paolo Bonzini 已提交
295 296
}

P
Paolo Bonzini 已提交
297 298 299 300
static int nbd_co_flush(BlockDriverState *bs)
{
    BDRVNBDState *s = bs->opaque;

M
Marc-André Lureau 已提交
301
    return nbd_client_session_co_flush(&s->client);
P
Paolo Bonzini 已提交
302 303
}

304 305 306 307 308 309
static void nbd_refresh_limits(BlockDriverState *bs, Error **errp)
{
    bs->bl.max_discard = UINT32_MAX >> BDRV_SECTOR_BITS;
    bs->bl.max_transfer_length = UINT32_MAX >> BDRV_SECTOR_BITS;
}

P
Paolo Bonzini 已提交
310 311 312 313 314
static int nbd_co_discard(BlockDriverState *bs, int64_t sector_num,
                          int nb_sectors)
{
    BDRVNBDState *s = bs->opaque;

M
Marc-André Lureau 已提交
315 316
    return nbd_client_session_co_discard(&s->client, sector_num,
                                         nb_sectors);
P
Paolo Bonzini 已提交
317 318
}

319 320
static void nbd_close(BlockDriverState *bs)
{
321 322
    BDRVNBDState *s = bs->opaque;

M
Marc-André Lureau 已提交
323 324
    qemu_opts_del(s->socket_opts);
    nbd_client_session_close(&s->client);
325 326 327 328 329 330
}

static int64_t nbd_getlength(BlockDriverState *bs)
{
    BDRVNBDState *s = bs->opaque;

M
Marc-André Lureau 已提交
331
    return s->client.size;
332 333
}

334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
static void nbd_detach_aio_context(BlockDriverState *bs)
{
    BDRVNBDState *s = bs->opaque;

    nbd_client_session_detach_aio_context(&s->client);
}

static void nbd_attach_aio_context(BlockDriverState *bs,
                                   AioContext *new_context)
{
    BDRVNBDState *s = bs->opaque;

    nbd_client_session_attach_aio_context(&s->client, new_context);
}

349 350 351
static void nbd_refresh_filename(BlockDriverState *bs)
{
    QDict *opts = qdict_new();
M
Max Reitz 已提交
352 353 354 355
    const char *path   = qdict_get_try_str(bs->options, "path");
    const char *host   = qdict_get_try_str(bs->options, "host");
    const char *port   = qdict_get_try_str(bs->options, "port");
    const char *export = qdict_get_try_str(bs->options, "export");
356 357 358

    qdict_put_obj(opts, "driver", QOBJECT(qstring_from_str("nbd")));

M
Max Reitz 已提交
359
    if (path && export) {
360
        snprintf(bs->exact_filename, sizeof(bs->exact_filename),
M
Max Reitz 已提交
361 362
                 "nbd+unix:///%s?socket=%s", export, path);
    } else if (path && !export) {
363
        snprintf(bs->exact_filename, sizeof(bs->exact_filename),
M
Max Reitz 已提交
364 365 366 367 368 369 370 371 372 373 374
                 "nbd+unix://?socket=%s", path);
    } else if (!path && export && port) {
        snprintf(bs->exact_filename, sizeof(bs->exact_filename),
                 "nbd://%s:%s/%s", host, port, export);
    } else if (!path && export && !port) {
        snprintf(bs->exact_filename, sizeof(bs->exact_filename),
                 "nbd://%s/%s", host, export);
    } else if (!path && !export && port) {
        snprintf(bs->exact_filename, sizeof(bs->exact_filename),
                 "nbd://%s:%s", host, port);
    } else if (!path && !export && !port) {
375
        snprintf(bs->exact_filename, sizeof(bs->exact_filename),
M
Max Reitz 已提交
376 377 378 379 380 381
                 "nbd://%s", host);
    }

    if (path) {
        qdict_put_obj(opts, "path", QOBJECT(qstring_from_str(path)));
    } else if (port) {
382 383
        qdict_put_obj(opts, "host", QOBJECT(qstring_from_str(host)));
        qdict_put_obj(opts, "port", QOBJECT(qstring_from_str(port)));
M
Max Reitz 已提交
384 385 386 387 388
    } else {
        qdict_put_obj(opts, "host", QOBJECT(qstring_from_str(host)));
    }
    if (export) {
        qdict_put_obj(opts, "export", QOBJECT(qstring_from_str(export)));
389 390 391 392 393
    }

    bs->full_open_options = opts;
}

394
static BlockDriver bdrv_nbd = {
395 396 397 398 399 400 401 402 403 404
    .format_name                = "nbd",
    .protocol_name              = "nbd",
    .instance_size              = sizeof(BDRVNBDState),
    .bdrv_parse_filename        = nbd_parse_filename,
    .bdrv_file_open             = nbd_open,
    .bdrv_co_readv              = nbd_co_readv,
    .bdrv_co_writev             = nbd_co_writev,
    .bdrv_close                 = nbd_close,
    .bdrv_co_flush_to_os        = nbd_co_flush,
    .bdrv_co_discard            = nbd_co_discard,
405
    .bdrv_refresh_limits        = nbd_refresh_limits,
406 407 408
    .bdrv_getlength             = nbd_getlength,
    .bdrv_detach_aio_context    = nbd_detach_aio_context,
    .bdrv_attach_aio_context    = nbd_attach_aio_context,
409
    .bdrv_refresh_filename      = nbd_refresh_filename,
P
Paolo Bonzini 已提交
410 411 412
};

static BlockDriver bdrv_nbd_tcp = {
413 414 415 416 417 418 419 420 421 422
    .format_name                = "nbd",
    .protocol_name              = "nbd+tcp",
    .instance_size              = sizeof(BDRVNBDState),
    .bdrv_parse_filename        = nbd_parse_filename,
    .bdrv_file_open             = nbd_open,
    .bdrv_co_readv              = nbd_co_readv,
    .bdrv_co_writev             = nbd_co_writev,
    .bdrv_close                 = nbd_close,
    .bdrv_co_flush_to_os        = nbd_co_flush,
    .bdrv_co_discard            = nbd_co_discard,
423
    .bdrv_refresh_limits        = nbd_refresh_limits,
424 425 426
    .bdrv_getlength             = nbd_getlength,
    .bdrv_detach_aio_context    = nbd_detach_aio_context,
    .bdrv_attach_aio_context    = nbd_attach_aio_context,
427
    .bdrv_refresh_filename      = nbd_refresh_filename,
P
Paolo Bonzini 已提交
428 429 430
};

static BlockDriver bdrv_nbd_unix = {
431 432 433 434 435 436 437 438 439 440
    .format_name                = "nbd",
    .protocol_name              = "nbd+unix",
    .instance_size              = sizeof(BDRVNBDState),
    .bdrv_parse_filename        = nbd_parse_filename,
    .bdrv_file_open             = nbd_open,
    .bdrv_co_readv              = nbd_co_readv,
    .bdrv_co_writev             = nbd_co_writev,
    .bdrv_close                 = nbd_close,
    .bdrv_co_flush_to_os        = nbd_co_flush,
    .bdrv_co_discard            = nbd_co_discard,
441
    .bdrv_refresh_limits        = nbd_refresh_limits,
442 443 444
    .bdrv_getlength             = nbd_getlength,
    .bdrv_detach_aio_context    = nbd_detach_aio_context,
    .bdrv_attach_aio_context    = nbd_attach_aio_context,
445
    .bdrv_refresh_filename      = nbd_refresh_filename,
446
};
447 448 449 450

static void bdrv_nbd_init(void)
{
    bdrv_register(&bdrv_nbd);
P
Paolo Bonzini 已提交
451 452
    bdrv_register(&bdrv_nbd_tcp);
    bdrv_register(&bdrv_nbd_unix);
453 454 455
}

block_init(bdrv_nbd_init);