xref: /openbmc/qemu/block/nbd.c (revision 81b07353c5e7ae9ae9360c357b7b4732b1cb03b4)
1  /*
2   * QEMU Block driver for  NBD
3   *
4   * Copyright (C) 2008 Bull S.A.S.
5   *     Author: Laurent Vivier <Laurent.Vivier@bull.net>
6   *
7   * Some parts:
8   *    Copyright (C) 2007 Anthony Liguori <anthony@codemonkey.ws>
9   *
10   * Permission is hereby granted, free of charge, to any person obtaining a copy
11   * of this software and associated documentation files (the "Software"), to deal
12   * in the Software without restriction, including without limitation the rights
13   * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14   * copies of the Software, and to permit persons to whom the Software is
15   * furnished to do so, subject to the following conditions:
16   *
17   * The above copyright notice and this permission notice shall be included in
18   * all copies or substantial portions of the Software.
19   *
20   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
23   * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26   * THE SOFTWARE.
27   */
28  
29  #include "block/nbd-client.h"
30  #include "qemu/uri.h"
31  #include "block/block_int.h"
32  #include "qemu/module.h"
33  #include "qemu/sockets.h"
34  #include "qapi/qmp/qdict.h"
35  #include "qapi/qmp/qjson.h"
36  #include "qapi/qmp/qint.h"
37  #include "qapi/qmp/qstring.h"
38  
39  #include <sys/types.h>
40  #include <unistd.h>
41  
42  #define EN_OPTSTR ":exportname="
43  
44  typedef struct BDRVNBDState {
45      NbdClientSession client;
46      QemuOpts *socket_opts;
47  } BDRVNBDState;
48  
49  static int nbd_parse_uri(const char *filename, QDict *options)
50  {
51      URI *uri;
52      const char *p;
53      QueryParams *qp = NULL;
54      int ret = 0;
55      bool is_unix;
56  
57      uri = uri_parse(filename);
58      if (!uri) {
59          return -EINVAL;
60      }
61  
62      /* transport */
63      if (!strcmp(uri->scheme, "nbd")) {
64          is_unix = false;
65      } else if (!strcmp(uri->scheme, "nbd+tcp")) {
66          is_unix = false;
67      } else if (!strcmp(uri->scheme, "nbd+unix")) {
68          is_unix = true;
69      } else {
70          ret = -EINVAL;
71          goto out;
72      }
73  
74      p = uri->path ? uri->path : "/";
75      p += strspn(p, "/");
76      if (p[0]) {
77          qdict_put(options, "export", qstring_from_str(p));
78      }
79  
80      qp = query_params_parse(uri->query);
81      if (qp->n > 1 || (is_unix && !qp->n) || (!is_unix && qp->n)) {
82          ret = -EINVAL;
83          goto out;
84      }
85  
86      if (is_unix) {
87          /* nbd+unix:///export?socket=path */
88          if (uri->server || uri->port || strcmp(qp->p[0].name, "socket")) {
89              ret = -EINVAL;
90              goto out;
91          }
92          qdict_put(options, "path", qstring_from_str(qp->p[0].value));
93      } else {
94          QString *host;
95          /* nbd[+tcp]://host[:port]/export */
96          if (!uri->server) {
97              ret = -EINVAL;
98              goto out;
99          }
100  
101          /* strip braces from literal IPv6 address */
102          if (uri->server[0] == '[') {
103              host = qstring_from_substr(uri->server, 1,
104                                         strlen(uri->server) - 2);
105          } else {
106              host = qstring_from_str(uri->server);
107          }
108  
109          qdict_put(options, "host", host);
110          if (uri->port) {
111              char* port_str = g_strdup_printf("%d", uri->port);
112              qdict_put(options, "port", qstring_from_str(port_str));
113              g_free(port_str);
114          }
115      }
116  
117  out:
118      if (qp) {
119          query_params_free(qp);
120      }
121      uri_free(uri);
122      return ret;
123  }
124  
125  static void nbd_parse_filename(const char *filename, QDict *options,
126                                 Error **errp)
127  {
128      char *file;
129      char *export_name;
130      const char *host_spec;
131      const char *unixpath;
132  
133      if (qdict_haskey(options, "host")
134          || qdict_haskey(options, "port")
135          || qdict_haskey(options, "path"))
136      {
137          error_setg(errp, "host/port/path and a file name may not be specified "
138                           "at the same time");
139          return;
140      }
141  
142      if (strstr(filename, "://")) {
143          int ret = nbd_parse_uri(filename, options);
144          if (ret < 0) {
145              error_setg(errp, "No valid URL specified");
146          }
147          return;
148      }
149  
150      file = g_strdup(filename);
151  
152      export_name = strstr(file, EN_OPTSTR);
153      if (export_name) {
154          if (export_name[strlen(EN_OPTSTR)] == 0) {
155              goto out;
156          }
157          export_name[0] = 0; /* truncate 'file' */
158          export_name += strlen(EN_OPTSTR);
159  
160          qdict_put(options, "export", qstring_from_str(export_name));
161      }
162  
163      /* extract the host_spec - fail if it's not nbd:... */
164      if (!strstart(file, "nbd:", &host_spec)) {
165          error_setg(errp, "File name string for NBD must start with 'nbd:'");
166          goto out;
167      }
168  
169      if (!*host_spec) {
170          goto out;
171      }
172  
173      /* are we a UNIX or TCP socket? */
174      if (strstart(host_spec, "unix:", &unixpath)) {
175          qdict_put(options, "path", qstring_from_str(unixpath));
176      } else {
177          InetSocketAddress *addr = NULL;
178  
179          addr = inet_parse(host_spec, errp);
180          if (!addr) {
181              goto out;
182          }
183  
184          qdict_put(options, "host", qstring_from_str(addr->host));
185          qdict_put(options, "port", qstring_from_str(addr->port));
186          qapi_free_InetSocketAddress(addr);
187      }
188  
189  out:
190      g_free(file);
191  }
192  
193  static void nbd_config(BDRVNBDState *s, QDict *options, char **export,
194                         Error **errp)
195  {
196      Error *local_err = NULL;
197  
198      if (qdict_haskey(options, "path") == qdict_haskey(options, "host")) {
199          if (qdict_haskey(options, "path")) {
200              error_setg(errp, "path and host may not be used at the same time.");
201          } else {
202              error_setg(errp, "one of path and host must be specified.");
203          }
204          return;
205      }
206  
207      s->client.is_unix = qdict_haskey(options, "path");
208      s->socket_opts = qemu_opts_create(&socket_optslist, NULL, 0,
209                                        &error_abort);
210  
211      qemu_opts_absorb_qdict(s->socket_opts, options, &local_err);
212      if (local_err) {
213          error_propagate(errp, local_err);
214          return;
215      }
216  
217      if (!qemu_opt_get(s->socket_opts, "port")) {
218          qemu_opt_set_number(s->socket_opts, "port", NBD_DEFAULT_PORT,
219                              &error_abort);
220      }
221  
222      *export = g_strdup(qdict_get_try_str(options, "export"));
223      if (*export) {
224          qdict_del(options, "export");
225      }
226  }
227  
228  NbdClientSession *nbd_get_client_session(BlockDriverState *bs)
229  {
230      BDRVNBDState *s = bs->opaque;
231      return &s->client;
232  }
233  
234  static int nbd_establish_connection(BlockDriverState *bs, Error **errp)
235  {
236      BDRVNBDState *s = bs->opaque;
237      int sock;
238  
239      if (s->client.is_unix) {
240          sock = unix_connect_opts(s->socket_opts, errp, NULL, NULL);
241      } else {
242          sock = inet_connect_opts(s->socket_opts, errp, NULL, NULL);
243          if (sock >= 0) {
244              socket_set_nodelay(sock);
245          }
246      }
247  
248      /* Failed to establish connection */
249      if (sock < 0) {
250          logout("Failed to establish connection to NBD server\n");
251          return -errno;
252      }
253  
254      return sock;
255  }
256  
257  static int nbd_open(BlockDriverState *bs, QDict *options, int flags,
258                      Error **errp)
259  {
260      BDRVNBDState *s = bs->opaque;
261      char *export = NULL;
262      int result, sock;
263      Error *local_err = NULL;
264  
265      /* Pop the config into our state object. Exit if invalid. */
266      nbd_config(s, options, &export, &local_err);
267      if (local_err) {
268          error_propagate(errp, local_err);
269          return -EINVAL;
270      }
271  
272      /* establish TCP connection, return error if it fails
273       * TODO: Configurable retry-until-timeout behaviour.
274       */
275      sock = nbd_establish_connection(bs, errp);
276      if (sock < 0) {
277          return sock;
278      }
279  
280      /* NBD handshake */
281      result = nbd_client_init(bs, sock, export, errp);
282      g_free(export);
283      return result;
284  }
285  
286  static int nbd_co_readv(BlockDriverState *bs, int64_t sector_num,
287                          int nb_sectors, QEMUIOVector *qiov)
288  {
289      return nbd_client_co_readv(bs, sector_num, nb_sectors, qiov);
290  }
291  
292  static int nbd_co_writev(BlockDriverState *bs, int64_t sector_num,
293                           int nb_sectors, QEMUIOVector *qiov)
294  {
295      return nbd_client_co_writev(bs, sector_num, nb_sectors, qiov);
296  }
297  
298  static int nbd_co_flush(BlockDriverState *bs)
299  {
300      return nbd_client_co_flush(bs);
301  }
302  
303  static void nbd_refresh_limits(BlockDriverState *bs, Error **errp)
304  {
305      bs->bl.max_discard = UINT32_MAX >> BDRV_SECTOR_BITS;
306      bs->bl.max_transfer_length = UINT32_MAX >> BDRV_SECTOR_BITS;
307  }
308  
309  static int nbd_co_discard(BlockDriverState *bs, int64_t sector_num,
310                            int nb_sectors)
311  {
312      return nbd_client_co_discard(bs, sector_num, nb_sectors);
313  }
314  
315  static void nbd_close(BlockDriverState *bs)
316  {
317      BDRVNBDState *s = bs->opaque;
318  
319      qemu_opts_del(s->socket_opts);
320      nbd_client_close(bs);
321  }
322  
323  static int64_t nbd_getlength(BlockDriverState *bs)
324  {
325      BDRVNBDState *s = bs->opaque;
326  
327      return s->client.size;
328  }
329  
330  static void nbd_detach_aio_context(BlockDriverState *bs)
331  {
332      nbd_client_detach_aio_context(bs);
333  }
334  
335  static void nbd_attach_aio_context(BlockDriverState *bs,
336                                     AioContext *new_context)
337  {
338      nbd_client_attach_aio_context(bs, new_context);
339  }
340  
341  static void nbd_refresh_filename(BlockDriverState *bs)
342  {
343      QDict *opts = qdict_new();
344      const char *path   = qdict_get_try_str(bs->options, "path");
345      const char *host   = qdict_get_try_str(bs->options, "host");
346      const char *port   = qdict_get_try_str(bs->options, "port");
347      const char *export = qdict_get_try_str(bs->options, "export");
348  
349      qdict_put_obj(opts, "driver", QOBJECT(qstring_from_str("nbd")));
350  
351      if (path && export) {
352          snprintf(bs->exact_filename, sizeof(bs->exact_filename),
353                   "nbd+unix:///%s?socket=%s", export, path);
354      } else if (path && !export) {
355          snprintf(bs->exact_filename, sizeof(bs->exact_filename),
356                   "nbd+unix://?socket=%s", path);
357      } else if (!path && export && port) {
358          snprintf(bs->exact_filename, sizeof(bs->exact_filename),
359                   "nbd://%s:%s/%s", host, port, export);
360      } else if (!path && export && !port) {
361          snprintf(bs->exact_filename, sizeof(bs->exact_filename),
362                   "nbd://%s/%s", host, export);
363      } else if (!path && !export && port) {
364          snprintf(bs->exact_filename, sizeof(bs->exact_filename),
365                   "nbd://%s:%s", host, port);
366      } else if (!path && !export && !port) {
367          snprintf(bs->exact_filename, sizeof(bs->exact_filename),
368                   "nbd://%s", host);
369      }
370  
371      if (path) {
372          qdict_put_obj(opts, "path", QOBJECT(qstring_from_str(path)));
373      } else if (port) {
374          qdict_put_obj(opts, "host", QOBJECT(qstring_from_str(host)));
375          qdict_put_obj(opts, "port", QOBJECT(qstring_from_str(port)));
376      } else {
377          qdict_put_obj(opts, "host", QOBJECT(qstring_from_str(host)));
378      }
379      if (export) {
380          qdict_put_obj(opts, "export", QOBJECT(qstring_from_str(export)));
381      }
382  
383      bs->full_open_options = opts;
384  }
385  
386  static BlockDriver bdrv_nbd = {
387      .format_name                = "nbd",
388      .protocol_name              = "nbd",
389      .instance_size              = sizeof(BDRVNBDState),
390      .bdrv_parse_filename        = nbd_parse_filename,
391      .bdrv_file_open             = nbd_open,
392      .bdrv_co_readv              = nbd_co_readv,
393      .bdrv_co_writev             = nbd_co_writev,
394      .bdrv_close                 = nbd_close,
395      .bdrv_co_flush_to_os        = nbd_co_flush,
396      .bdrv_co_discard            = nbd_co_discard,
397      .bdrv_refresh_limits        = nbd_refresh_limits,
398      .bdrv_getlength             = nbd_getlength,
399      .bdrv_detach_aio_context    = nbd_detach_aio_context,
400      .bdrv_attach_aio_context    = nbd_attach_aio_context,
401      .bdrv_refresh_filename      = nbd_refresh_filename,
402  };
403  
404  static BlockDriver bdrv_nbd_tcp = {
405      .format_name                = "nbd",
406      .protocol_name              = "nbd+tcp",
407      .instance_size              = sizeof(BDRVNBDState),
408      .bdrv_parse_filename        = nbd_parse_filename,
409      .bdrv_file_open             = nbd_open,
410      .bdrv_co_readv              = nbd_co_readv,
411      .bdrv_co_writev             = nbd_co_writev,
412      .bdrv_close                 = nbd_close,
413      .bdrv_co_flush_to_os        = nbd_co_flush,
414      .bdrv_co_discard            = nbd_co_discard,
415      .bdrv_refresh_limits        = nbd_refresh_limits,
416      .bdrv_getlength             = nbd_getlength,
417      .bdrv_detach_aio_context    = nbd_detach_aio_context,
418      .bdrv_attach_aio_context    = nbd_attach_aio_context,
419      .bdrv_refresh_filename      = nbd_refresh_filename,
420  };
421  
422  static BlockDriver bdrv_nbd_unix = {
423      .format_name                = "nbd",
424      .protocol_name              = "nbd+unix",
425      .instance_size              = sizeof(BDRVNBDState),
426      .bdrv_parse_filename        = nbd_parse_filename,
427      .bdrv_file_open             = nbd_open,
428      .bdrv_co_readv              = nbd_co_readv,
429      .bdrv_co_writev             = nbd_co_writev,
430      .bdrv_close                 = nbd_close,
431      .bdrv_co_flush_to_os        = nbd_co_flush,
432      .bdrv_co_discard            = nbd_co_discard,
433      .bdrv_refresh_limits        = nbd_refresh_limits,
434      .bdrv_getlength             = nbd_getlength,
435      .bdrv_detach_aio_context    = nbd_detach_aio_context,
436      .bdrv_attach_aio_context    = nbd_attach_aio_context,
437      .bdrv_refresh_filename      = nbd_refresh_filename,
438  };
439  
440  static void bdrv_nbd_init(void)
441  {
442      bdrv_register(&bdrv_nbd);
443      bdrv_register(&bdrv_nbd_tcp);
444      bdrv_register(&bdrv_nbd_unix);
445  }
446  
447  block_init(bdrv_nbd_init);
448