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.
 */

P
Peter Maydell 已提交
29
#include "qemu/osdep.h"
M
Marc-André Lureau 已提交
30
#include "block/nbd-client.h"
31
#include "qemu/uri.h"
32
#include "block/block_int.h"
33
#include "qemu/module.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
#define EN_OPTSTR ":exportname="

42
typedef struct BDRVNBDState {
M
Marc-André Lureau 已提交
43
    NbdClientSession client;
44 45
} BDRVNBDState;

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

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

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

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

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

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

98 99 100 101 102 103 104 105 106
        /* 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);
107 108 109 110 111
        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 已提交
112 113 114 115 116 117 118 119 120 121
    }

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

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

130 131 132 133 134 135 136 137 138
    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 已提交
139
    if (strstr(filename, "://")) {
140 141 142 143 144
        int ret = nbd_parse_uri(filename, options);
        if (ret < 0) {
            error_setg(errp, "No valid URL specified");
        }
        return;
P
Paolo Bonzini 已提交
145 146
    }

147
    file = g_strdup(filename);
148

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

        qdict_put(options, "export", qstring_from_str(export_name));
158 159
    }

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

166 167 168 169
    if (!*host_spec) {
        goto out;
    }

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

176
        addr = inet_parse(host_spec, errp);
177
        if (!addr) {
178 179
            goto out;
        }
180

181 182 183 184
        qdict_put(options, "host", qstring_from_str(addr->host));
        qdict_put(options, "port", qstring_from_str(addr->port));
        qapi_free_InetSocketAddress(addr);
    }
185

186
out:
187
    g_free(file);
188 189
}

190 191
static SocketAddress *nbd_config(BDRVNBDState *s, QDict *options, char **export,
                                 Error **errp)
192
{
193
    SocketAddress *saddr;
194

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

204
    saddr = g_new0(SocketAddress, 1);
205

206
    if (qdict_haskey(options, "path")) {
207 208 209
        saddr->type = SOCKET_ADDRESS_KIND_UNIX;
        saddr->u.q_unix = g_new0(UnixSocketAddress, 1);
        saddr->u.q_unix->path = g_strdup(qdict_get_str(options, "path"));
210 211
        qdict_del(options, "path");
    } else {
212 213 214
        saddr->type = SOCKET_ADDRESS_KIND_INET;
        saddr->u.inet = g_new0(InetSocketAddress, 1);
        saddr->u.inet->host = g_strdup(qdict_get_str(options, "host"));
215
        if (!qdict_get_try_str(options, "port")) {
216
            saddr->u.inet->port = g_strdup_printf("%d", NBD_DEFAULT_PORT);
217
        } else {
218
            saddr->u.inet->port = g_strdup(qdict_get_str(options, "port"));
219 220 221
        }
        qdict_del(options, "host");
        qdict_del(options, "port");
222 223
    }

224
    s->client.is_unix = saddr->type == SOCKET_ADDRESS_KIND_UNIX;
225

226 227
    *export = g_strdup(qdict_get_try_str(options, "export"));
    if (*export) {
228 229
        qdict_del(options, "export");
    }
230 231

    return saddr;
232
}
233

M
Max Reitz 已提交
234 235 236 237 238 239
NbdClientSession *nbd_get_client_session(BlockDriverState *bs)
{
    BDRVNBDState *s = bs->opaque;
    return &s->client;
}

240 241
static QIOChannelSocket *nbd_establish_connection(SocketAddress *saddr,
                                                  Error **errp)
242
{
243 244
    QIOChannelSocket *sioc;
    Error *local_err = NULL;
245

246
    sioc = qio_channel_socket_new();
247

248 249 250 251 252 253
    qio_channel_socket_connect_sync(sioc,
                                    saddr,
                                    &local_err);
    if (local_err) {
        error_propagate(errp, local_err);
        return NULL;
254
    }
255

256
    qio_channel_set_delay(QIO_CHANNEL(sioc), false);
257

258
    return sioc;
259 260
}

M
Max Reitz 已提交
261 262
static int nbd_open(BlockDriverState *bs, QDict *options, int flags,
                    Error **errp)
263 264
{
    BDRVNBDState *s = bs->opaque;
265
    char *export = NULL;
266 267
    int result;
    QIOChannelSocket *sioc;
268
    SocketAddress *saddr;
269

270
    /* Pop the config into our state object. Exit if invalid. */
271 272
    saddr = nbd_config(s, options, &export, errp);
    if (!saddr) {
P
Paolo Bonzini 已提交
273
        return -EINVAL;
274 275 276 277 278
    }

    /* establish TCP connection, return error if it fails
     * TODO: Configurable retry-until-timeout behaviour.
     */
279
    sioc = nbd_establish_connection(saddr, errp);
280
    qapi_free_SocketAddress(saddr);
281
    if (!sioc) {
G
Gonglei 已提交
282
        g_free(export);
283
        return -ECONNREFUSED;
284 285
    }

M
Marc-André Lureau 已提交
286
    /* NBD handshake */
287 288
    result = nbd_client_init(bs, sioc, export, errp);
    object_unref(OBJECT(sioc));
289 290
    g_free(export);
    return result;
291 292
}

P
Paolo Bonzini 已提交
293 294 295
static int nbd_co_readv(BlockDriverState *bs, int64_t sector_num,
                        int nb_sectors, QEMUIOVector *qiov)
{
M
Max Reitz 已提交
296
    return nbd_client_co_readv(bs, sector_num, nb_sectors, qiov);
P
Paolo Bonzini 已提交
297 298 299 300 301
}

static int nbd_co_writev(BlockDriverState *bs, int64_t sector_num,
                         int nb_sectors, QEMUIOVector *qiov)
{
M
Max Reitz 已提交
302
    return nbd_client_co_writev(bs, sector_num, nb_sectors, qiov);
P
Paolo Bonzini 已提交
303 304
}

P
Paolo Bonzini 已提交
305 306
static int nbd_co_flush(BlockDriverState *bs)
{
M
Max Reitz 已提交
307
    return nbd_client_co_flush(bs);
P
Paolo Bonzini 已提交
308 309
}

310 311 312 313 314 315
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 已提交
316 317 318
static int nbd_co_discard(BlockDriverState *bs, int64_t sector_num,
                          int nb_sectors)
{
M
Max Reitz 已提交
319
    return nbd_client_co_discard(bs, sector_num, nb_sectors);
P
Paolo Bonzini 已提交
320 321
}

322 323
static void nbd_close(BlockDriverState *bs)
{
M
Max Reitz 已提交
324
    nbd_client_close(bs);
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
static void nbd_detach_aio_context(BlockDriverState *bs)
{
M
Max Reitz 已提交
336
    nbd_client_detach_aio_context(bs);
337 338 339 340 341
}

static void nbd_attach_aio_context(BlockDriverState *bs,
                                   AioContext *new_context)
{
M
Max Reitz 已提交
342
    nbd_client_attach_aio_context(bs, new_context);
343 344
}

345
static void nbd_refresh_filename(BlockDriverState *bs, QDict *options)
346 347
{
    QDict *opts = qdict_new();
348 349 350 351
    const char *path   = qdict_get_try_str(options, "path");
    const char *host   = qdict_get_try_str(options, "host");
    const char *port   = qdict_get_try_str(options, "port");
    const char *export = qdict_get_try_str(options, "export");
352 353 354

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

M
Max Reitz 已提交
355
    if (path && export) {
356
        snprintf(bs->exact_filename, sizeof(bs->exact_filename),
M
Max Reitz 已提交
357 358
                 "nbd+unix:///%s?socket=%s", export, path);
    } else if (path && !export) {
359
        snprintf(bs->exact_filename, sizeof(bs->exact_filename),
M
Max Reitz 已提交
360 361 362 363 364 365 366 367 368 369 370
                 "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) {
371
        snprintf(bs->exact_filename, sizeof(bs->exact_filename),
M
Max Reitz 已提交
372 373 374 375 376 377
                 "nbd://%s", host);
    }

    if (path) {
        qdict_put_obj(opts, "path", QOBJECT(qstring_from_str(path)));
    } else if (port) {
378 379
        qdict_put_obj(opts, "host", QOBJECT(qstring_from_str(host)));
        qdict_put_obj(opts, "port", QOBJECT(qstring_from_str(port)));
M
Max Reitz 已提交
380 381 382 383 384
    } else {
        qdict_put_obj(opts, "host", QOBJECT(qstring_from_str(host)));
    }
    if (export) {
        qdict_put_obj(opts, "export", QOBJECT(qstring_from_str(export)));
385 386 387 388 389
    }

    bs->full_open_options = opts;
}

390
static BlockDriver bdrv_nbd = {
391 392 393 394 395 396 397 398 399 400
    .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,
401
    .bdrv_refresh_limits        = nbd_refresh_limits,
402 403 404
    .bdrv_getlength             = nbd_getlength,
    .bdrv_detach_aio_context    = nbd_detach_aio_context,
    .bdrv_attach_aio_context    = nbd_attach_aio_context,
405
    .bdrv_refresh_filename      = nbd_refresh_filename,
P
Paolo Bonzini 已提交
406 407 408
};

static BlockDriver bdrv_nbd_tcp = {
409 410 411 412 413 414 415 416 417 418
    .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,
419
    .bdrv_refresh_limits        = nbd_refresh_limits,
420 421 422
    .bdrv_getlength             = nbd_getlength,
    .bdrv_detach_aio_context    = nbd_detach_aio_context,
    .bdrv_attach_aio_context    = nbd_attach_aio_context,
423
    .bdrv_refresh_filename      = nbd_refresh_filename,
P
Paolo Bonzini 已提交
424 425 426
};

static BlockDriver bdrv_nbd_unix = {
427 428 429 430 431 432 433 434 435 436
    .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,
437
    .bdrv_refresh_limits        = nbd_refresh_limits,
438 439 440
    .bdrv_getlength             = nbd_getlength,
    .bdrv_detach_aio_context    = nbd_detach_aio_context,
    .bdrv_attach_aio_context    = nbd_attach_aio_context,
441
    .bdrv_refresh_filename      = nbd_refresh_filename,
442
};
443 444 445 446

static void bdrv_nbd_init(void)
{
    bdrv_register(&bdrv_nbd);
P
Paolo Bonzini 已提交
447 448
    bdrv_register(&bdrv_nbd_tcp);
    bdrv_register(&bdrv_nbd_unix);
449 450 451
}

block_init(bdrv_nbd_init);