nbd.c 10.4 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 178
        addr = inet_parse(host_spec, errp);
        if (error_is_set(errp)) {
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
}

191
static int nbd_config(BDRVNBDState *s, QDict *options, char **export)
192 193 194 195
{
    Error *local_err = NULL;

    if (qdict_haskey(options, "path")) {
196 197 198 199 200
        if (qdict_haskey(options, "host")) {
            qerror_report(ERROR_CLASS_GENERIC_ERROR, "path and host may not "
                          "be used at the same time.");
            return -EINVAL;
        }
M
Marc-André Lureau 已提交
201
        s->client.is_unix = true;
202
    } else if (qdict_haskey(options, "host")) {
M
Marc-André Lureau 已提交
203
        s->client.is_unix = false;
204 205
    } else {
        return -EINVAL;
206
    }
207

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) {
213 214 215 216 217
        qerror_report_err(local_err);
        error_free(local_err);
        return -EINVAL;
    }

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

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

    return 0;
228
}
229

230 231 232 233
static int nbd_establish_connection(BlockDriverState *bs)
{
    BDRVNBDState *s = bs->opaque;
    int sock;
234

M
Marc-André Lureau 已提交
235
    if (s->client.is_unix) {
236
        sock = unix_socket_outgoing(qemu_opt_get(s->socket_opts, "path"));
237
    } else {
238
        sock = tcp_socket_outgoing_opts(s->socket_opts);
S
Stefan Hajnoczi 已提交
239 240 241
        if (sock >= 0) {
            socket_set_nodelay(sock);
        }
242 243
    }

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

M
Marc-André Lureau 已提交
250
    return sock;
251 252
}

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

260
    /* Pop the config into our state object. Exit if invalid. */
261
    result = nbd_config(s, options, &export);
262 263 264 265 266 267 268
    if (result != 0) {
        return result;
    }

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

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

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

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

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

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

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

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

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

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

314 315
static void nbd_close(BlockDriverState *bs)
{
316 317
    BDRVNBDState *s = bs->opaque;

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

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

M
Marc-André Lureau 已提交
326
    return s->client.size;
327 328
}

329
static BlockDriver bdrv_nbd = {
P
Paolo Bonzini 已提交
330
    .format_name         = "nbd",
P
Paolo Bonzini 已提交
331 332
    .protocol_name       = "nbd",
    .instance_size       = sizeof(BDRVNBDState),
333
    .bdrv_parse_filename = nbd_parse_filename,
P
Paolo Bonzini 已提交
334 335 336 337 338 339 340 341 342 343 344 345 346
    .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,
};

static BlockDriver bdrv_nbd_tcp = {
    .format_name         = "nbd",
    .protocol_name       = "nbd+tcp",
    .instance_size       = sizeof(BDRVNBDState),
347
    .bdrv_parse_filename = nbd_parse_filename,
P
Paolo Bonzini 已提交
348 349 350 351 352 353 354 355 356 357 358 359
    .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,
};

static BlockDriver bdrv_nbd_unix = {
    .format_name         = "nbd",
    .protocol_name       = "nbd+unix",
P
Paolo Bonzini 已提交
360
    .instance_size       = sizeof(BDRVNBDState),
361
    .bdrv_parse_filename = nbd_parse_filename,
P
Paolo Bonzini 已提交
362 363 364 365 366
    .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,
P
Paolo Bonzini 已提交
367
    .bdrv_co_discard     = nbd_co_discard,
P
Paolo Bonzini 已提交
368
    .bdrv_getlength      = nbd_getlength,
369
};
370 371 372 373

static void bdrv_nbd_init(void)
{
    bdrv_register(&bdrv_nbd);
P
Paolo Bonzini 已提交
374 375
    bdrv_register(&bdrv_nbd_tcp);
    bdrv_register(&bdrv_nbd_unix);
376 377 378
}

block_init(bdrv_nbd_init);