xref: /openbmc/qemu/block/nbd.c (revision 97ebbab0)
1019d6b8fSAnthony Liguori /*
2019d6b8fSAnthony Liguori  * QEMU Block driver for  NBD
3019d6b8fSAnthony Liguori  *
4019d6b8fSAnthony Liguori  * Copyright (C) 2008 Bull S.A.S.
5019d6b8fSAnthony Liguori  *     Author: Laurent Vivier <Laurent.Vivier@bull.net>
6019d6b8fSAnthony Liguori  *
7019d6b8fSAnthony Liguori  * Some parts:
8019d6b8fSAnthony Liguori  *    Copyright (C) 2007 Anthony Liguori <anthony@codemonkey.ws>
9019d6b8fSAnthony Liguori  *
10019d6b8fSAnthony Liguori  * Permission is hereby granted, free of charge, to any person obtaining a copy
11019d6b8fSAnthony Liguori  * of this software and associated documentation files (the "Software"), to deal
12019d6b8fSAnthony Liguori  * in the Software without restriction, including without limitation the rights
13019d6b8fSAnthony Liguori  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14019d6b8fSAnthony Liguori  * copies of the Software, and to permit persons to whom the Software is
15019d6b8fSAnthony Liguori  * furnished to do so, subject to the following conditions:
16019d6b8fSAnthony Liguori  *
17019d6b8fSAnthony Liguori  * The above copyright notice and this permission notice shall be included in
18019d6b8fSAnthony Liguori  * all copies or substantial portions of the Software.
19019d6b8fSAnthony Liguori  *
20019d6b8fSAnthony Liguori  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21019d6b8fSAnthony Liguori  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22019d6b8fSAnthony Liguori  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
23019d6b8fSAnthony Liguori  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24019d6b8fSAnthony Liguori  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25019d6b8fSAnthony Liguori  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26019d6b8fSAnthony Liguori  * THE SOFTWARE.
27019d6b8fSAnthony Liguori  */
28019d6b8fSAnthony Liguori 
29019d6b8fSAnthony Liguori #include "qemu-common.h"
30737e150eSPaolo Bonzini #include "block/nbd.h"
311de7afc9SPaolo Bonzini #include "qemu/uri.h"
32737e150eSPaolo Bonzini #include "block/block_int.h"
331de7afc9SPaolo Bonzini #include "qemu/module.h"
341de7afc9SPaolo Bonzini #include "qemu/sockets.h"
35f53a1febSKevin Wolf #include "qapi/qmp/qjson.h"
36f53a1febSKevin Wolf #include "qapi/qmp/qint.h"
37019d6b8fSAnthony Liguori 
38019d6b8fSAnthony Liguori #include <sys/types.h>
39019d6b8fSAnthony Liguori #include <unistd.h>
40019d6b8fSAnthony Liguori 
411d45f8b5SLaurent Vivier #define EN_OPTSTR ":exportname="
421d45f8b5SLaurent Vivier 
4333897dc7SNick Thomas /* #define DEBUG_NBD */
4433897dc7SNick Thomas 
4533897dc7SNick Thomas #if defined(DEBUG_NBD)
4633897dc7SNick Thomas #define logout(fmt, ...) \
4733897dc7SNick Thomas                 fprintf(stderr, "nbd\t%-24s" fmt, __func__, ##__VA_ARGS__)
4833897dc7SNick Thomas #else
4933897dc7SNick Thomas #define logout(fmt, ...) ((void)0)
5033897dc7SNick Thomas #endif
5133897dc7SNick Thomas 
52ecda3447SPaolo Bonzini #define MAX_NBD_REQUESTS	16
53ecda3447SPaolo Bonzini #define HANDLE_TO_INDEX(bs, handle) ((handle) ^ ((uint64_t)(intptr_t)bs))
54ecda3447SPaolo Bonzini #define INDEX_TO_HANDLE(bs, index)  ((index)  ^ ((uint64_t)(intptr_t)bs))
55ecda3447SPaolo Bonzini 
56019d6b8fSAnthony Liguori typedef struct BDRVNBDState {
57019d6b8fSAnthony Liguori     int sock;
58b90fb4b8SPaolo Bonzini     uint32_t nbdflags;
59019d6b8fSAnthony Liguori     off_t size;
60019d6b8fSAnthony Liguori     size_t blocksize;
6133897dc7SNick Thomas 
62ecda3447SPaolo Bonzini     CoMutex send_mutex;
63ecda3447SPaolo Bonzini     CoMutex free_sema;
64ecda3447SPaolo Bonzini     Coroutine *send_coroutine;
65ecda3447SPaolo Bonzini     int in_flight;
66ae255e52SPaolo Bonzini 
67ecda3447SPaolo Bonzini     Coroutine *recv_coroutine[MAX_NBD_REQUESTS];
68ae255e52SPaolo Bonzini     struct nbd_reply reply;
69ae255e52SPaolo Bonzini 
70f53a1febSKevin Wolf     bool is_unix;
71f53a1febSKevin Wolf     QemuOpts *socket_opts;
72f17c90beSKevin Wolf 
73d04b0bbbSPaolo Bonzini     char *export_name; /* An NBD server may export several devices */
74019d6b8fSAnthony Liguori } BDRVNBDState;
75019d6b8fSAnthony Liguori 
76f53a1febSKevin Wolf static int nbd_parse_uri(const char *filename, QDict *options)
771d7d2a9dSPaolo Bonzini {
781d7d2a9dSPaolo Bonzini     URI *uri;
791d7d2a9dSPaolo Bonzini     const char *p;
801d7d2a9dSPaolo Bonzini     QueryParams *qp = NULL;
811d7d2a9dSPaolo Bonzini     int ret = 0;
82f53a1febSKevin Wolf     bool is_unix;
831d7d2a9dSPaolo Bonzini 
841d7d2a9dSPaolo Bonzini     uri = uri_parse(filename);
851d7d2a9dSPaolo Bonzini     if (!uri) {
861d7d2a9dSPaolo Bonzini         return -EINVAL;
871d7d2a9dSPaolo Bonzini     }
881d7d2a9dSPaolo Bonzini 
891d7d2a9dSPaolo Bonzini     /* transport */
901d7d2a9dSPaolo Bonzini     if (!strcmp(uri->scheme, "nbd")) {
91f53a1febSKevin Wolf         is_unix = false;
921d7d2a9dSPaolo Bonzini     } else if (!strcmp(uri->scheme, "nbd+tcp")) {
93f53a1febSKevin Wolf         is_unix = false;
941d7d2a9dSPaolo Bonzini     } else if (!strcmp(uri->scheme, "nbd+unix")) {
95f53a1febSKevin Wolf         is_unix = true;
961d7d2a9dSPaolo Bonzini     } else {
971d7d2a9dSPaolo Bonzini         ret = -EINVAL;
981d7d2a9dSPaolo Bonzini         goto out;
991d7d2a9dSPaolo Bonzini     }
1001d7d2a9dSPaolo Bonzini 
1011d7d2a9dSPaolo Bonzini     p = uri->path ? uri->path : "/";
1021d7d2a9dSPaolo Bonzini     p += strspn(p, "/");
1031d7d2a9dSPaolo Bonzini     if (p[0]) {
104f53a1febSKevin Wolf         qdict_put(options, "export", qstring_from_str(p));
1051d7d2a9dSPaolo Bonzini     }
1061d7d2a9dSPaolo Bonzini 
1071d7d2a9dSPaolo Bonzini     qp = query_params_parse(uri->query);
108f53a1febSKevin Wolf     if (qp->n > 1 || (is_unix && !qp->n) || (!is_unix && qp->n)) {
1091d7d2a9dSPaolo Bonzini         ret = -EINVAL;
1101d7d2a9dSPaolo Bonzini         goto out;
1111d7d2a9dSPaolo Bonzini     }
1121d7d2a9dSPaolo Bonzini 
113f53a1febSKevin Wolf     if (is_unix) {
1141d7d2a9dSPaolo Bonzini         /* nbd+unix:///export?socket=path */
1151d7d2a9dSPaolo Bonzini         if (uri->server || uri->port || strcmp(qp->p[0].name, "socket")) {
1161d7d2a9dSPaolo Bonzini             ret = -EINVAL;
1171d7d2a9dSPaolo Bonzini             goto out;
1181d7d2a9dSPaolo Bonzini         }
119f53a1febSKevin Wolf         qdict_put(options, "path", qstring_from_str(qp->p[0].value));
1201d7d2a9dSPaolo Bonzini     } else {
121bebbf7faSKevin Wolf         /* nbd[+tcp]://host[:port]/export */
1221d7d2a9dSPaolo Bonzini         if (!uri->server) {
1231d7d2a9dSPaolo Bonzini             ret = -EINVAL;
1241d7d2a9dSPaolo Bonzini             goto out;
1251d7d2a9dSPaolo Bonzini         }
126f17c90beSKevin Wolf 
127f53a1febSKevin Wolf         qdict_put(options, "host", qstring_from_str(uri->server));
128bebbf7faSKevin Wolf         if (uri->port) {
129bebbf7faSKevin Wolf             char* port_str = g_strdup_printf("%d", uri->port);
130f53a1febSKevin Wolf             qdict_put(options, "port", qstring_from_str(port_str));
131f53a1febSKevin Wolf             g_free(port_str);
1321d7d2a9dSPaolo Bonzini         }
133bebbf7faSKevin Wolf     }
1341d7d2a9dSPaolo Bonzini 
1351d7d2a9dSPaolo Bonzini out:
1361d7d2a9dSPaolo Bonzini     if (qp) {
1371d7d2a9dSPaolo Bonzini         query_params_free(qp);
1381d7d2a9dSPaolo Bonzini     }
1391d7d2a9dSPaolo Bonzini     uri_free(uri);
1401d7d2a9dSPaolo Bonzini     return ret;
1411d7d2a9dSPaolo Bonzini }
1421d7d2a9dSPaolo Bonzini 
1436963a30dSKevin Wolf static void nbd_parse_filename(const char *filename, QDict *options,
1446963a30dSKevin Wolf                                Error **errp)
145019d6b8fSAnthony Liguori {
1461d45f8b5SLaurent Vivier     char *file;
14733897dc7SNick Thomas     char *export_name;
14833897dc7SNick Thomas     const char *host_spec;
149019d6b8fSAnthony Liguori     const char *unixpath;
150019d6b8fSAnthony Liguori 
151681e7ad0SKevin Wolf     if (qdict_haskey(options, "host")
152681e7ad0SKevin Wolf         || qdict_haskey(options, "port")
153681e7ad0SKevin Wolf         || qdict_haskey(options, "path"))
154681e7ad0SKevin Wolf     {
155681e7ad0SKevin Wolf         error_setg(errp, "host/port/path and a file name may not be specified "
156681e7ad0SKevin Wolf                          "at the same time");
157681e7ad0SKevin Wolf         return;
158681e7ad0SKevin Wolf     }
159681e7ad0SKevin Wolf 
1601d7d2a9dSPaolo Bonzini     if (strstr(filename, "://")) {
1616963a30dSKevin Wolf         int ret = nbd_parse_uri(filename, options);
1626963a30dSKevin Wolf         if (ret < 0) {
1636963a30dSKevin Wolf             error_setg(errp, "No valid URL specified");
1646963a30dSKevin Wolf         }
1656963a30dSKevin Wolf         return;
1661d7d2a9dSPaolo Bonzini     }
1671d7d2a9dSPaolo Bonzini 
1687267c094SAnthony Liguori     file = g_strdup(filename);
1691d45f8b5SLaurent Vivier 
17033897dc7SNick Thomas     export_name = strstr(file, EN_OPTSTR);
17133897dc7SNick Thomas     if (export_name) {
17233897dc7SNick Thomas         if (export_name[strlen(EN_OPTSTR)] == 0) {
1731d45f8b5SLaurent Vivier             goto out;
1741d45f8b5SLaurent Vivier         }
17533897dc7SNick Thomas         export_name[0] = 0; /* truncate 'file' */
17633897dc7SNick Thomas         export_name += strlen(EN_OPTSTR);
177f53a1febSKevin Wolf 
178f53a1febSKevin Wolf         qdict_put(options, "export", qstring_from_str(export_name));
1791d45f8b5SLaurent Vivier     }
1801d45f8b5SLaurent Vivier 
18133897dc7SNick Thomas     /* extract the host_spec - fail if it's not nbd:... */
18233897dc7SNick Thomas     if (!strstart(file, "nbd:", &host_spec)) {
1836963a30dSKevin Wolf         error_setg(errp, "File name string for NBD must start with 'nbd:'");
1841d45f8b5SLaurent Vivier         goto out;
1851d45f8b5SLaurent Vivier     }
186019d6b8fSAnthony Liguori 
187f53a1febSKevin Wolf     if (!*host_spec) {
188f53a1febSKevin Wolf         goto out;
189f53a1febSKevin Wolf     }
190f53a1febSKevin Wolf 
19133897dc7SNick Thomas     /* are we a UNIX or TCP socket? */
19233897dc7SNick Thomas     if (strstart(host_spec, "unix:", &unixpath)) {
193f53a1febSKevin Wolf         qdict_put(options, "path", qstring_from_str(unixpath));
194019d6b8fSAnthony Liguori     } else {
195f53a1febSKevin Wolf         InetSocketAddress *addr = NULL;
196f53a1febSKevin Wolf 
1976963a30dSKevin Wolf         addr = inet_parse(host_spec, errp);
1986963a30dSKevin Wolf         if (error_is_set(errp)) {
199f17c90beSKevin Wolf             goto out;
200f17c90beSKevin Wolf         }
201f53a1febSKevin Wolf 
202f53a1febSKevin Wolf         qdict_put(options, "host", qstring_from_str(addr->host));
203f53a1febSKevin Wolf         qdict_put(options, "port", qstring_from_str(addr->port));
204f53a1febSKevin Wolf         qapi_free_InetSocketAddress(addr);
2051d45f8b5SLaurent Vivier     }
2061d45f8b5SLaurent Vivier 
2071d45f8b5SLaurent Vivier out:
2087267c094SAnthony Liguori     g_free(file);
20933897dc7SNick Thomas }
210f53a1febSKevin Wolf 
211f53a1febSKevin Wolf static int nbd_config(BDRVNBDState *s, QDict *options)
212f53a1febSKevin Wolf {
213f53a1febSKevin Wolf     Error *local_err = NULL;
214f53a1febSKevin Wolf 
215f53a1febSKevin Wolf     if (qdict_haskey(options, "path")) {
216681e7ad0SKevin Wolf         if (qdict_haskey(options, "host")) {
217681e7ad0SKevin Wolf             qerror_report(ERROR_CLASS_GENERIC_ERROR, "path and host may not "
218681e7ad0SKevin Wolf                           "be used at the same time.");
219681e7ad0SKevin Wolf             return -EINVAL;
220681e7ad0SKevin Wolf         }
221f53a1febSKevin Wolf         s->is_unix = true;
222f53a1febSKevin Wolf     } else if (qdict_haskey(options, "host")) {
223f53a1febSKevin Wolf         s->is_unix = false;
224f53a1febSKevin Wolf     } else {
225f53a1febSKevin Wolf         return -EINVAL;
226019d6b8fSAnthony Liguori     }
227019d6b8fSAnthony Liguori 
228f53a1febSKevin Wolf     s->socket_opts = qemu_opts_create_nofail(&socket_optslist);
229f53a1febSKevin Wolf 
230f53a1febSKevin Wolf     qemu_opts_absorb_qdict(s->socket_opts, options, &local_err);
231f53a1febSKevin Wolf     if (error_is_set(&local_err)) {
232f53a1febSKevin Wolf         qerror_report_err(local_err);
233f53a1febSKevin Wolf         error_free(local_err);
234f53a1febSKevin Wolf         return -EINVAL;
235f53a1febSKevin Wolf     }
236f53a1febSKevin Wolf 
237bebbf7faSKevin Wolf     if (!qemu_opt_get(s->socket_opts, "port")) {
238bebbf7faSKevin Wolf         qemu_opt_set_number(s->socket_opts, "port", NBD_DEFAULT_PORT);
239bebbf7faSKevin Wolf     }
240bebbf7faSKevin Wolf 
241f53a1febSKevin Wolf     s->export_name = g_strdup(qdict_get_try_str(options, "export"));
242f53a1febSKevin Wolf     if (s->export_name) {
243f53a1febSKevin Wolf         qdict_del(options, "export");
244f53a1febSKevin Wolf     }
245f53a1febSKevin Wolf 
246f53a1febSKevin Wolf     return 0;
247f53a1febSKevin Wolf }
248f53a1febSKevin Wolf 
249f53a1febSKevin Wolf 
250ae255e52SPaolo Bonzini static void nbd_coroutine_start(BDRVNBDState *s, struct nbd_request *request)
251ae255e52SPaolo Bonzini {
252ecda3447SPaolo Bonzini     int i;
253ecda3447SPaolo Bonzini 
254ecda3447SPaolo Bonzini     /* Poor man semaphore.  The free_sema is locked when no other request
255ecda3447SPaolo Bonzini      * can be accepted, and unlocked after receiving one reply.  */
256ecda3447SPaolo Bonzini     if (s->in_flight >= MAX_NBD_REQUESTS - 1) {
257ecda3447SPaolo Bonzini         qemu_co_mutex_lock(&s->free_sema);
258ecda3447SPaolo Bonzini         assert(s->in_flight < MAX_NBD_REQUESTS);
259ecda3447SPaolo Bonzini     }
260ecda3447SPaolo Bonzini     s->in_flight++;
261ecda3447SPaolo Bonzini 
262ecda3447SPaolo Bonzini     for (i = 0; i < MAX_NBD_REQUESTS; i++) {
263ecda3447SPaolo Bonzini         if (s->recv_coroutine[i] == NULL) {
264ecda3447SPaolo Bonzini             s->recv_coroutine[i] = qemu_coroutine_self();
265ecda3447SPaolo Bonzini             break;
266ecda3447SPaolo Bonzini         }
267ecda3447SPaolo Bonzini     }
268ecda3447SPaolo Bonzini 
269ecda3447SPaolo Bonzini     assert(i < MAX_NBD_REQUESTS);
270ecda3447SPaolo Bonzini     request->handle = INDEX_TO_HANDLE(s, i);
271ae255e52SPaolo Bonzini }
272ae255e52SPaolo Bonzini 
273ae255e52SPaolo Bonzini static int nbd_have_request(void *opaque)
274ae255e52SPaolo Bonzini {
275ae255e52SPaolo Bonzini     BDRVNBDState *s = opaque;
276ae255e52SPaolo Bonzini 
277ecda3447SPaolo Bonzini     return s->in_flight > 0;
278ae255e52SPaolo Bonzini }
279ae255e52SPaolo Bonzini 
280ae255e52SPaolo Bonzini static void nbd_reply_ready(void *opaque)
281ae255e52SPaolo Bonzini {
282ae255e52SPaolo Bonzini     BDRVNBDState *s = opaque;
283dd3e8ac4SPaolo Bonzini     uint64_t i;
2847fe7b68bSPaolo Bonzini     int ret;
285ae255e52SPaolo Bonzini 
286ae255e52SPaolo Bonzini     if (s->reply.handle == 0) {
2877fe7b68bSPaolo Bonzini         /* No reply already in flight.  Fetch a header.  It is possible
2887fe7b68bSPaolo Bonzini          * that another thread has done the same thing in parallel, so
2897fe7b68bSPaolo Bonzini          * the socket is not readable anymore.
2907fe7b68bSPaolo Bonzini          */
2917fe7b68bSPaolo Bonzini         ret = nbd_receive_reply(s->sock, &s->reply);
2927fe7b68bSPaolo Bonzini         if (ret == -EAGAIN) {
2937fe7b68bSPaolo Bonzini             return;
2947fe7b68bSPaolo Bonzini         }
2957fe7b68bSPaolo Bonzini         if (ret < 0) {
296ae255e52SPaolo Bonzini             s->reply.handle = 0;
297ecda3447SPaolo Bonzini             goto fail;
298ae255e52SPaolo Bonzini         }
299ae255e52SPaolo Bonzini     }
300ae255e52SPaolo Bonzini 
301ae255e52SPaolo Bonzini     /* There's no need for a mutex on the receive side, because the
302ae255e52SPaolo Bonzini      * handler acts as a synchronization point and ensures that only
303ae255e52SPaolo Bonzini      * one coroutine is called until the reply finishes.  */
304ecda3447SPaolo Bonzini     i = HANDLE_TO_INDEX(s, s->reply.handle);
305dd3e8ac4SPaolo Bonzini     if (i >= MAX_NBD_REQUESTS) {
306dd3e8ac4SPaolo Bonzini         goto fail;
307dd3e8ac4SPaolo Bonzini     }
308dd3e8ac4SPaolo Bonzini 
309ecda3447SPaolo Bonzini     if (s->recv_coroutine[i]) {
310ecda3447SPaolo Bonzini         qemu_coroutine_enter(s->recv_coroutine[i], NULL);
311ecda3447SPaolo Bonzini         return;
312ecda3447SPaolo Bonzini     }
313ecda3447SPaolo Bonzini 
314ecda3447SPaolo Bonzini fail:
315ecda3447SPaolo Bonzini     for (i = 0; i < MAX_NBD_REQUESTS; i++) {
316ecda3447SPaolo Bonzini         if (s->recv_coroutine[i]) {
317ecda3447SPaolo Bonzini             qemu_coroutine_enter(s->recv_coroutine[i], NULL);
318ecda3447SPaolo Bonzini         }
319ae255e52SPaolo Bonzini     }
320ae255e52SPaolo Bonzini }
321ae255e52SPaolo Bonzini 
322ae255e52SPaolo Bonzini static void nbd_restart_write(void *opaque)
323ae255e52SPaolo Bonzini {
324ae255e52SPaolo Bonzini     BDRVNBDState *s = opaque;
325ecda3447SPaolo Bonzini     qemu_coroutine_enter(s->send_coroutine, NULL);
326ae255e52SPaolo Bonzini }
327ae255e52SPaolo Bonzini 
328ae255e52SPaolo Bonzini static int nbd_co_send_request(BDRVNBDState *s, struct nbd_request *request,
3292fc8ae1dSMichael Tokarev                                QEMUIOVector *qiov, int offset)
330ae255e52SPaolo Bonzini {
331ae255e52SPaolo Bonzini     int rc, ret;
332ae255e52SPaolo Bonzini 
333ecda3447SPaolo Bonzini     qemu_co_mutex_lock(&s->send_mutex);
334ecda3447SPaolo Bonzini     s->send_coroutine = qemu_coroutine_self();
335ae255e52SPaolo Bonzini     qemu_aio_set_fd_handler(s->sock, nbd_reply_ready, nbd_restart_write,
336bafbd6a1SPaolo Bonzini                             nbd_have_request, s);
3370fcece25SStefan Hajnoczi     if (qiov) {
3380fcece25SStefan Hajnoczi         if (!s->is_unix) {
3390fcece25SStefan Hajnoczi             socket_set_cork(s->sock, 1);
3400fcece25SStefan Hajnoczi         }
341ae255e52SPaolo Bonzini         rc = nbd_send_request(s->sock, request);
3420fcece25SStefan Hajnoczi         if (rc >= 0) {
3432fc8ae1dSMichael Tokarev             ret = qemu_co_sendv(s->sock, qiov->iov, qiov->niov,
3442fc8ae1dSMichael Tokarev                                 offset, request->len);
345ae255e52SPaolo Bonzini             if (ret != request->len) {
3466760c47aSStefan Hajnoczi                 rc = -EIO;
347ae255e52SPaolo Bonzini             }
348ae255e52SPaolo Bonzini         }
3490fcece25SStefan Hajnoczi         if (!s->is_unix) {
3500fcece25SStefan Hajnoczi             socket_set_cork(s->sock, 0);
3510fcece25SStefan Hajnoczi         }
3520fcece25SStefan Hajnoczi     } else {
3530fcece25SStefan Hajnoczi         rc = nbd_send_request(s->sock, request);
3540fcece25SStefan Hajnoczi     }
355ae255e52SPaolo Bonzini     qemu_aio_set_fd_handler(s->sock, nbd_reply_ready, NULL,
356bafbd6a1SPaolo Bonzini                             nbd_have_request, s);
357ecda3447SPaolo Bonzini     s->send_coroutine = NULL;
358ecda3447SPaolo Bonzini     qemu_co_mutex_unlock(&s->send_mutex);
359ae255e52SPaolo Bonzini     return rc;
360ae255e52SPaolo Bonzini }
361ae255e52SPaolo Bonzini 
362ae255e52SPaolo Bonzini static void nbd_co_receive_reply(BDRVNBDState *s, struct nbd_request *request,
363ae255e52SPaolo Bonzini                                  struct nbd_reply *reply,
3642fc8ae1dSMichael Tokarev                                  QEMUIOVector *qiov, int offset)
365ae255e52SPaolo Bonzini {
366ae255e52SPaolo Bonzini     int ret;
367ae255e52SPaolo Bonzini 
368ecda3447SPaolo Bonzini     /* Wait until we're woken up by the read handler.  TODO: perhaps
369ecda3447SPaolo Bonzini      * peek at the next reply and avoid yielding if it's ours?  */
370ae255e52SPaolo Bonzini     qemu_coroutine_yield();
371ae255e52SPaolo Bonzini     *reply = s->reply;
372ae255e52SPaolo Bonzini     if (reply->handle != request->handle) {
373ae255e52SPaolo Bonzini         reply->error = EIO;
374ae255e52SPaolo Bonzini     } else {
3752fc8ae1dSMichael Tokarev         if (qiov && reply->error == 0) {
3762fc8ae1dSMichael Tokarev             ret = qemu_co_recvv(s->sock, qiov->iov, qiov->niov,
3772fc8ae1dSMichael Tokarev                                 offset, request->len);
378ae255e52SPaolo Bonzini             if (ret != request->len) {
379ae255e52SPaolo Bonzini                 reply->error = EIO;
380ae255e52SPaolo Bonzini             }
381ae255e52SPaolo Bonzini         }
382ae255e52SPaolo Bonzini 
383ae255e52SPaolo Bonzini         /* Tell the read handler to read another header.  */
384ae255e52SPaolo Bonzini         s->reply.handle = 0;
385ae255e52SPaolo Bonzini     }
386ae255e52SPaolo Bonzini }
387ae255e52SPaolo Bonzini 
388ae255e52SPaolo Bonzini static void nbd_coroutine_end(BDRVNBDState *s, struct nbd_request *request)
389ae255e52SPaolo Bonzini {
390ecda3447SPaolo Bonzini     int i = HANDLE_TO_INDEX(s, request->handle);
391ecda3447SPaolo Bonzini     s->recv_coroutine[i] = NULL;
392ecda3447SPaolo Bonzini     if (s->in_flight-- == MAX_NBD_REQUESTS) {
393ecda3447SPaolo Bonzini         qemu_co_mutex_unlock(&s->free_sema);
394ecda3447SPaolo Bonzini     }
395ae255e52SPaolo Bonzini }
396ae255e52SPaolo Bonzini 
39733897dc7SNick Thomas static int nbd_establish_connection(BlockDriverState *bs)
39833897dc7SNick Thomas {
39933897dc7SNick Thomas     BDRVNBDState *s = bs->opaque;
40033897dc7SNick Thomas     int sock;
40133897dc7SNick Thomas     int ret;
40233897dc7SNick Thomas     off_t size;
40333897dc7SNick Thomas     size_t blocksize;
40433897dc7SNick Thomas 
405d04b0bbbSPaolo Bonzini     if (s->is_unix) {
406f53a1febSKevin Wolf         sock = unix_socket_outgoing(qemu_opt_get(s->socket_opts, "path"));
40733897dc7SNick Thomas     } else {
408f53a1febSKevin Wolf         sock = tcp_socket_outgoing_opts(s->socket_opts);
409*97ebbab0SStefan Hajnoczi         if (sock >= 0) {
410*97ebbab0SStefan Hajnoczi             socket_set_nodelay(sock);
411*97ebbab0SStefan Hajnoczi         }
41233897dc7SNick Thomas     }
41333897dc7SNick Thomas 
41433897dc7SNick Thomas     /* Failed to establish connection */
415fc19f8a0SPaolo Bonzini     if (sock < 0) {
41633897dc7SNick Thomas         logout("Failed to establish connection to NBD server\n");
41733897dc7SNick Thomas         return -errno;
41833897dc7SNick Thomas     }
41933897dc7SNick Thomas 
42033897dc7SNick Thomas     /* NBD handshake */
421b90fb4b8SPaolo Bonzini     ret = nbd_receive_negotiate(sock, s->export_name, &s->nbdflags, &size,
42233897dc7SNick Thomas                                 &blocksize);
423fc19f8a0SPaolo Bonzini     if (ret < 0) {
42433897dc7SNick Thomas         logout("Failed to negotiate with the NBD server\n");
42533897dc7SNick Thomas         closesocket(sock);
426185b4338SPaolo Bonzini         return ret;
42733897dc7SNick Thomas     }
42833897dc7SNick Thomas 
429ae255e52SPaolo Bonzini     /* Now that we're connected, set the socket to be non-blocking and
430ae255e52SPaolo Bonzini      * kick the reply mechanism.  */
431f9e8caccSStefan Hajnoczi     qemu_set_nonblock(sock);
432b3adf53aSKevin Wolf     qemu_aio_set_fd_handler(sock, nbd_reply_ready, NULL,
433bafbd6a1SPaolo Bonzini                             nbd_have_request, s);
43433897dc7SNick Thomas 
43533897dc7SNick Thomas     s->sock = sock;
43633897dc7SNick Thomas     s->size = size;
43733897dc7SNick Thomas     s->blocksize = blocksize;
43833897dc7SNick Thomas 
43933897dc7SNick Thomas     logout("Established connection with NBD server\n");
44033897dc7SNick Thomas     return 0;
44133897dc7SNick Thomas }
44233897dc7SNick Thomas 
44333897dc7SNick Thomas static void nbd_teardown_connection(BlockDriverState *bs)
44433897dc7SNick Thomas {
44533897dc7SNick Thomas     BDRVNBDState *s = bs->opaque;
44633897dc7SNick Thomas     struct nbd_request request;
44733897dc7SNick Thomas 
44833897dc7SNick Thomas     request.type = NBD_CMD_DISC;
44933897dc7SNick Thomas     request.from = 0;
45033897dc7SNick Thomas     request.len = 0;
45133897dc7SNick Thomas     nbd_send_request(s->sock, &request);
45233897dc7SNick Thomas 
453bafbd6a1SPaolo Bonzini     qemu_aio_set_fd_handler(s->sock, NULL, NULL, NULL, NULL);
45433897dc7SNick Thomas     closesocket(s->sock);
45533897dc7SNick Thomas }
45633897dc7SNick Thomas 
457787e4a85SKevin Wolf static int nbd_open(BlockDriverState *bs, const char* filename,
458787e4a85SKevin Wolf                     QDict *options, int flags)
45933897dc7SNick Thomas {
46033897dc7SNick Thomas     BDRVNBDState *s = bs->opaque;
46133897dc7SNick Thomas     int result;
46233897dc7SNick Thomas 
463ecda3447SPaolo Bonzini     qemu_co_mutex_init(&s->send_mutex);
464ecda3447SPaolo Bonzini     qemu_co_mutex_init(&s->free_sema);
465ae255e52SPaolo Bonzini 
46633897dc7SNick Thomas     /* Pop the config into our state object. Exit if invalid. */
467f53a1febSKevin Wolf     result = nbd_config(s, options);
46833897dc7SNick Thomas     if (result != 0) {
46933897dc7SNick Thomas         return result;
47033897dc7SNick Thomas     }
47133897dc7SNick Thomas 
47233897dc7SNick Thomas     /* establish TCP connection, return error if it fails
47333897dc7SNick Thomas      * TODO: Configurable retry-until-timeout behaviour.
47433897dc7SNick Thomas      */
47533897dc7SNick Thomas     result = nbd_establish_connection(bs);
47633897dc7SNick Thomas 
47733897dc7SNick Thomas     return result;
47833897dc7SNick Thomas }
47933897dc7SNick Thomas 
480d9b09f13SPaolo Bonzini static int nbd_co_readv_1(BlockDriverState *bs, int64_t sector_num,
481d9b09f13SPaolo Bonzini                           int nb_sectors, QEMUIOVector *qiov,
482d9b09f13SPaolo Bonzini                           int offset)
483019d6b8fSAnthony Liguori {
484019d6b8fSAnthony Liguori     BDRVNBDState *s = bs->opaque;
485019d6b8fSAnthony Liguori     struct nbd_request request;
486019d6b8fSAnthony Liguori     struct nbd_reply reply;
487fc19f8a0SPaolo Bonzini     ssize_t ret;
488019d6b8fSAnthony Liguori 
489019d6b8fSAnthony Liguori     request.type = NBD_CMD_READ;
4903a93113aSDong Xu Wang     request.from = sector_num * 512;
491019d6b8fSAnthony Liguori     request.len = nb_sectors * 512;
492019d6b8fSAnthony Liguori 
493ae255e52SPaolo Bonzini     nbd_coroutine_start(s, &request);
494fc19f8a0SPaolo Bonzini     ret = nbd_co_send_request(s, &request, NULL, 0);
495fc19f8a0SPaolo Bonzini     if (ret < 0) {
496185b4338SPaolo Bonzini         reply.error = -ret;
497ae255e52SPaolo Bonzini     } else {
4982fc8ae1dSMichael Tokarev         nbd_co_receive_reply(s, &request, &reply, qiov, offset);
499ae255e52SPaolo Bonzini     }
500ae255e52SPaolo Bonzini     nbd_coroutine_end(s, &request);
501019d6b8fSAnthony Liguori     return -reply.error;
502019d6b8fSAnthony Liguori 
503019d6b8fSAnthony Liguori }
504019d6b8fSAnthony Liguori 
505d9b09f13SPaolo Bonzini static int nbd_co_writev_1(BlockDriverState *bs, int64_t sector_num,
506d9b09f13SPaolo Bonzini                            int nb_sectors, QEMUIOVector *qiov,
507d9b09f13SPaolo Bonzini                            int offset)
508019d6b8fSAnthony Liguori {
509019d6b8fSAnthony Liguori     BDRVNBDState *s = bs->opaque;
510019d6b8fSAnthony Liguori     struct nbd_request request;
511019d6b8fSAnthony Liguori     struct nbd_reply reply;
512fc19f8a0SPaolo Bonzini     ssize_t ret;
513019d6b8fSAnthony Liguori 
514019d6b8fSAnthony Liguori     request.type = NBD_CMD_WRITE;
5152c7989a9SPaolo Bonzini     if (!bdrv_enable_write_cache(bs) && (s->nbdflags & NBD_FLAG_SEND_FUA)) {
5162c7989a9SPaolo Bonzini         request.type |= NBD_CMD_FLAG_FUA;
5172c7989a9SPaolo Bonzini     }
5182c7989a9SPaolo Bonzini 
5193a93113aSDong Xu Wang     request.from = sector_num * 512;
520019d6b8fSAnthony Liguori     request.len = nb_sectors * 512;
521019d6b8fSAnthony Liguori 
522ae255e52SPaolo Bonzini     nbd_coroutine_start(s, &request);
5232fc8ae1dSMichael Tokarev     ret = nbd_co_send_request(s, &request, qiov, offset);
524fc19f8a0SPaolo Bonzini     if (ret < 0) {
525185b4338SPaolo Bonzini         reply.error = -ret;
526ae255e52SPaolo Bonzini     } else {
527ae255e52SPaolo Bonzini         nbd_co_receive_reply(s, &request, &reply, NULL, 0);
528ae255e52SPaolo Bonzini     }
529ae255e52SPaolo Bonzini     nbd_coroutine_end(s, &request);
530019d6b8fSAnthony Liguori     return -reply.error;
531e183ef75SPaolo Bonzini }
532e183ef75SPaolo Bonzini 
533d9b09f13SPaolo Bonzini /* qemu-nbd has a limit of slightly less than 1M per request.  Try to
534d9b09f13SPaolo Bonzini  * remain aligned to 4K. */
535d9b09f13SPaolo Bonzini #define NBD_MAX_SECTORS 2040
536d9b09f13SPaolo Bonzini 
537d9b09f13SPaolo Bonzini static int nbd_co_readv(BlockDriverState *bs, int64_t sector_num,
538d9b09f13SPaolo Bonzini                         int nb_sectors, QEMUIOVector *qiov)
539d9b09f13SPaolo Bonzini {
540d9b09f13SPaolo Bonzini     int offset = 0;
541d9b09f13SPaolo Bonzini     int ret;
542d9b09f13SPaolo Bonzini     while (nb_sectors > NBD_MAX_SECTORS) {
543d9b09f13SPaolo Bonzini         ret = nbd_co_readv_1(bs, sector_num, NBD_MAX_SECTORS, qiov, offset);
544d9b09f13SPaolo Bonzini         if (ret < 0) {
545d9b09f13SPaolo Bonzini             return ret;
546d9b09f13SPaolo Bonzini         }
547d9b09f13SPaolo Bonzini         offset += NBD_MAX_SECTORS * 512;
548d9b09f13SPaolo Bonzini         sector_num += NBD_MAX_SECTORS;
549d9b09f13SPaolo Bonzini         nb_sectors -= NBD_MAX_SECTORS;
550d9b09f13SPaolo Bonzini     }
551d9b09f13SPaolo Bonzini     return nbd_co_readv_1(bs, sector_num, nb_sectors, qiov, offset);
552d9b09f13SPaolo Bonzini }
553d9b09f13SPaolo Bonzini 
554d9b09f13SPaolo Bonzini static int nbd_co_writev(BlockDriverState *bs, int64_t sector_num,
555d9b09f13SPaolo Bonzini                          int nb_sectors, QEMUIOVector *qiov)
556d9b09f13SPaolo Bonzini {
557d9b09f13SPaolo Bonzini     int offset = 0;
558d9b09f13SPaolo Bonzini     int ret;
559d9b09f13SPaolo Bonzini     while (nb_sectors > NBD_MAX_SECTORS) {
560d9b09f13SPaolo Bonzini         ret = nbd_co_writev_1(bs, sector_num, NBD_MAX_SECTORS, qiov, offset);
561d9b09f13SPaolo Bonzini         if (ret < 0) {
562d9b09f13SPaolo Bonzini             return ret;
563d9b09f13SPaolo Bonzini         }
564d9b09f13SPaolo Bonzini         offset += NBD_MAX_SECTORS * 512;
565d9b09f13SPaolo Bonzini         sector_num += NBD_MAX_SECTORS;
566d9b09f13SPaolo Bonzini         nb_sectors -= NBD_MAX_SECTORS;
567d9b09f13SPaolo Bonzini     }
568d9b09f13SPaolo Bonzini     return nbd_co_writev_1(bs, sector_num, nb_sectors, qiov, offset);
569d9b09f13SPaolo Bonzini }
570d9b09f13SPaolo Bonzini 
5711486d04aSPaolo Bonzini static int nbd_co_flush(BlockDriverState *bs)
5721486d04aSPaolo Bonzini {
5731486d04aSPaolo Bonzini     BDRVNBDState *s = bs->opaque;
5741486d04aSPaolo Bonzini     struct nbd_request request;
5751486d04aSPaolo Bonzini     struct nbd_reply reply;
576fc19f8a0SPaolo Bonzini     ssize_t ret;
5771486d04aSPaolo Bonzini 
5781486d04aSPaolo Bonzini     if (!(s->nbdflags & NBD_FLAG_SEND_FLUSH)) {
5791486d04aSPaolo Bonzini         return 0;
5801486d04aSPaolo Bonzini     }
5811486d04aSPaolo Bonzini 
5821486d04aSPaolo Bonzini     request.type = NBD_CMD_FLUSH;
5831486d04aSPaolo Bonzini     if (s->nbdflags & NBD_FLAG_SEND_FUA) {
5841486d04aSPaolo Bonzini         request.type |= NBD_CMD_FLAG_FUA;
5851486d04aSPaolo Bonzini     }
5861486d04aSPaolo Bonzini 
5871486d04aSPaolo Bonzini     request.from = 0;
5881486d04aSPaolo Bonzini     request.len = 0;
5891486d04aSPaolo Bonzini 
5901486d04aSPaolo Bonzini     nbd_coroutine_start(s, &request);
591fc19f8a0SPaolo Bonzini     ret = nbd_co_send_request(s, &request, NULL, 0);
592fc19f8a0SPaolo Bonzini     if (ret < 0) {
593185b4338SPaolo Bonzini         reply.error = -ret;
5941486d04aSPaolo Bonzini     } else {
5951486d04aSPaolo Bonzini         nbd_co_receive_reply(s, &request, &reply, NULL, 0);
5961486d04aSPaolo Bonzini     }
5971486d04aSPaolo Bonzini     nbd_coroutine_end(s, &request);
5981486d04aSPaolo Bonzini     return -reply.error;
5991486d04aSPaolo Bonzini }
6001486d04aSPaolo Bonzini 
6017a706633SPaolo Bonzini static int nbd_co_discard(BlockDriverState *bs, int64_t sector_num,
6027a706633SPaolo Bonzini                           int nb_sectors)
6037a706633SPaolo Bonzini {
6047a706633SPaolo Bonzini     BDRVNBDState *s = bs->opaque;
6057a706633SPaolo Bonzini     struct nbd_request request;
6067a706633SPaolo Bonzini     struct nbd_reply reply;
607fc19f8a0SPaolo Bonzini     ssize_t ret;
6087a706633SPaolo Bonzini 
6097a706633SPaolo Bonzini     if (!(s->nbdflags & NBD_FLAG_SEND_TRIM)) {
6107a706633SPaolo Bonzini         return 0;
6117a706633SPaolo Bonzini     }
6127a706633SPaolo Bonzini     request.type = NBD_CMD_TRIM;
6137a706633SPaolo Bonzini     request.from = sector_num * 512;;
6147a706633SPaolo Bonzini     request.len = nb_sectors * 512;
6157a706633SPaolo Bonzini 
6167a706633SPaolo Bonzini     nbd_coroutine_start(s, &request);
617fc19f8a0SPaolo Bonzini     ret = nbd_co_send_request(s, &request, NULL, 0);
618fc19f8a0SPaolo Bonzini     if (ret < 0) {
619185b4338SPaolo Bonzini         reply.error = -ret;
6207a706633SPaolo Bonzini     } else {
6217a706633SPaolo Bonzini         nbd_co_receive_reply(s, &request, &reply, NULL, 0);
6227a706633SPaolo Bonzini     }
6237a706633SPaolo Bonzini     nbd_coroutine_end(s, &request);
6247a706633SPaolo Bonzini     return -reply.error;
6257a706633SPaolo Bonzini }
6267a706633SPaolo Bonzini 
627019d6b8fSAnthony Liguori static void nbd_close(BlockDriverState *bs)
628019d6b8fSAnthony Liguori {
629d2d979c6SNick Thomas     BDRVNBDState *s = bs->opaque;
6307267c094SAnthony Liguori     g_free(s->export_name);
631f53a1febSKevin Wolf     qemu_opts_del(s->socket_opts);
632d2d979c6SNick Thomas 
63333897dc7SNick Thomas     nbd_teardown_connection(bs);
634019d6b8fSAnthony Liguori }
635019d6b8fSAnthony Liguori 
636019d6b8fSAnthony Liguori static int64_t nbd_getlength(BlockDriverState *bs)
637019d6b8fSAnthony Liguori {
638019d6b8fSAnthony Liguori     BDRVNBDState *s = bs->opaque;
639019d6b8fSAnthony Liguori 
640019d6b8fSAnthony Liguori     return s->size;
641019d6b8fSAnthony Liguori }
642019d6b8fSAnthony Liguori 
643019d6b8fSAnthony Liguori static BlockDriver bdrv_nbd = {
644019d6b8fSAnthony Liguori     .format_name         = "nbd",
6451d7d2a9dSPaolo Bonzini     .protocol_name       = "nbd",
646019d6b8fSAnthony Liguori     .instance_size       = sizeof(BDRVNBDState),
6476963a30dSKevin Wolf     .bdrv_parse_filename = nbd_parse_filename,
64866f82ceeSKevin Wolf     .bdrv_file_open      = nbd_open,
649ae255e52SPaolo Bonzini     .bdrv_co_readv       = nbd_co_readv,
650ae255e52SPaolo Bonzini     .bdrv_co_writev      = nbd_co_writev,
651019d6b8fSAnthony Liguori     .bdrv_close          = nbd_close,
6521486d04aSPaolo Bonzini     .bdrv_co_flush_to_os = nbd_co_flush,
6537a706633SPaolo Bonzini     .bdrv_co_discard     = nbd_co_discard,
654019d6b8fSAnthony Liguori     .bdrv_getlength      = nbd_getlength,
6551d7d2a9dSPaolo Bonzini };
6561d7d2a9dSPaolo Bonzini 
6571d7d2a9dSPaolo Bonzini static BlockDriver bdrv_nbd_tcp = {
6581d7d2a9dSPaolo Bonzini     .format_name         = "nbd",
6591d7d2a9dSPaolo Bonzini     .protocol_name       = "nbd+tcp",
6601d7d2a9dSPaolo Bonzini     .instance_size       = sizeof(BDRVNBDState),
6616963a30dSKevin Wolf     .bdrv_parse_filename = nbd_parse_filename,
6621d7d2a9dSPaolo Bonzini     .bdrv_file_open      = nbd_open,
6631d7d2a9dSPaolo Bonzini     .bdrv_co_readv       = nbd_co_readv,
6641d7d2a9dSPaolo Bonzini     .bdrv_co_writev      = nbd_co_writev,
6651d7d2a9dSPaolo Bonzini     .bdrv_close          = nbd_close,
6661d7d2a9dSPaolo Bonzini     .bdrv_co_flush_to_os = nbd_co_flush,
6671d7d2a9dSPaolo Bonzini     .bdrv_co_discard     = nbd_co_discard,
6681d7d2a9dSPaolo Bonzini     .bdrv_getlength      = nbd_getlength,
6691d7d2a9dSPaolo Bonzini };
6701d7d2a9dSPaolo Bonzini 
6711d7d2a9dSPaolo Bonzini static BlockDriver bdrv_nbd_unix = {
6721d7d2a9dSPaolo Bonzini     .format_name         = "nbd",
6731d7d2a9dSPaolo Bonzini     .protocol_name       = "nbd+unix",
6741d7d2a9dSPaolo Bonzini     .instance_size       = sizeof(BDRVNBDState),
6756963a30dSKevin Wolf     .bdrv_parse_filename = nbd_parse_filename,
6761d7d2a9dSPaolo Bonzini     .bdrv_file_open      = nbd_open,
6771d7d2a9dSPaolo Bonzini     .bdrv_co_readv       = nbd_co_readv,
6781d7d2a9dSPaolo Bonzini     .bdrv_co_writev      = nbd_co_writev,
6791d7d2a9dSPaolo Bonzini     .bdrv_close          = nbd_close,
6801d7d2a9dSPaolo Bonzini     .bdrv_co_flush_to_os = nbd_co_flush,
6811d7d2a9dSPaolo Bonzini     .bdrv_co_discard     = nbd_co_discard,
6821d7d2a9dSPaolo Bonzini     .bdrv_getlength      = nbd_getlength,
683019d6b8fSAnthony Liguori };
684019d6b8fSAnthony Liguori 
685019d6b8fSAnthony Liguori static void bdrv_nbd_init(void)
686019d6b8fSAnthony Liguori {
687019d6b8fSAnthony Liguori     bdrv_register(&bdrv_nbd);
6881d7d2a9dSPaolo Bonzini     bdrv_register(&bdrv_nbd_tcp);
6891d7d2a9dSPaolo Bonzini     bdrv_register(&bdrv_nbd_unix);
690019d6b8fSAnthony Liguori }
691019d6b8fSAnthony Liguori 
692019d6b8fSAnthony Liguori block_init(bdrv_nbd_init);
693