nbd.c 11.3 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 35
#include "qapi/qmp/qjson.h"
#include "qapi/qmp/qint.h"
36 37 38 39

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

40 41
#define EN_OPTSTR ":exportname="

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

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

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

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

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

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

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

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

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

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

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

148
    file = g_strdup(filename);
149

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

M
Marc-André Lureau 已提交
245
    return sock;
246 247
}

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

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

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

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

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

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

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

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

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

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

P
Paolo Bonzini 已提交
302 303 304 305 306
static int nbd_co_discard(BlockDriverState *bs, int64_t sector_num,
                          int nb_sectors)
{
    BDRVNBDState *s = bs->opaque;

M
Marc-André Lureau 已提交
307 308
    return nbd_client_session_co_discard(&s->client, sector_num,
                                         nb_sectors);
P
Paolo Bonzini 已提交
309 310
}

311 312
static void nbd_close(BlockDriverState *bs)
{
313 314
    BDRVNBDState *s = bs->opaque;

M
Marc-André Lureau 已提交
315 316
    qemu_opts_del(s->socket_opts);
    nbd_client_session_close(&s->client);
317 318 319 320 321 322
}

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

M
Marc-André Lureau 已提交
323
    return s->client.size;
324 325
}

326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
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);
}

341
static BlockDriver bdrv_nbd = {
342 343 344 345 346 347 348 349 350 351 352 353 354
    .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,
    .bdrv_getlength             = nbd_getlength,
    .bdrv_detach_aio_context    = nbd_detach_aio_context,
    .bdrv_attach_aio_context    = nbd_attach_aio_context,
P
Paolo Bonzini 已提交
355 356 357
};

static BlockDriver bdrv_nbd_tcp = {
358 359 360 361 362 363 364 365 366 367 368 369 370
    .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,
    .bdrv_getlength             = nbd_getlength,
    .bdrv_detach_aio_context    = nbd_detach_aio_context,
    .bdrv_attach_aio_context    = nbd_attach_aio_context,
P
Paolo Bonzini 已提交
371 372 373
};

static BlockDriver bdrv_nbd_unix = {
374 375 376 377 378 379 380 381 382 383 384 385 386
    .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,
    .bdrv_getlength             = nbd_getlength,
    .bdrv_detach_aio_context    = nbd_detach_aio_context,
    .bdrv_attach_aio_context    = nbd_attach_aio_context,
387
};
388 389 390 391

static void bdrv_nbd_init(void)
{
    bdrv_register(&bdrv_nbd);
P
Paolo Bonzini 已提交
392 393
    bdrv_register(&bdrv_nbd_tcp);
    bdrv_register(&bdrv_nbd_unix);
394 395 396
}

block_init(bdrv_nbd_init);