]> git.proxmox.com Git - mirror_qemu.git/blame - nbd/server.c
nbd-server: Coroutine based negotiation
[mirror_qemu.git] / nbd / server.c
CommitLineData
75818250 1/*
7a5ca864
FB
2 * Copyright (C) 2005 Anthony Liguori <anthony@codemonkey.ws>
3 *
798bfe00 4 * Network Block Device Server Side
7a5ca864
FB
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; under version 2 of the License.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
8167ee88 16 * along with this program; if not, see <http://www.gnu.org/licenses/>.
75818250 17 */
7a5ca864 18
798bfe00 19#include "nbd-internal.h"
ca441480
PB
20
21static int system_errno_to_nbd_errno(int err)
22{
23 switch (err) {
24 case 0:
25 return NBD_SUCCESS;
26 case EPERM:
27 return NBD_EPERM;
28 case EIO:
29 return NBD_EIO;
30 case ENOMEM:
31 return NBD_ENOMEM;
32#ifdef EDQUOT
33 case EDQUOT:
34#endif
35 case EFBIG:
36 case ENOSPC:
37 return NBD_ENOSPC;
38 case EINVAL:
39 default:
40 return NBD_EINVAL;
41 }
42}
43
9a304d29
PB
44/* Definitions for opaque data types */
45
46typedef struct NBDRequest NBDRequest;
47
48struct NBDRequest {
49 QSIMPLEQ_ENTRY(NBDRequest) entry;
50 NBDClient *client;
51 uint8_t *data;
52};
53
54struct NBDExport {
2c8d9f06 55 int refcount;
0ddf08db
PB
56 void (*close)(NBDExport *exp);
57
aadf99a7 58 BlockBackend *blk;
ee0a19ec 59 char *name;
9a304d29
PB
60 off_t dev_offset;
61 off_t size;
62 uint32_t nbdflags;
4b9441f6 63 QTAILQ_HEAD(, NBDClient) clients;
ee0a19ec 64 QTAILQ_ENTRY(NBDExport) next;
958c717d
HR
65
66 AioContext *ctx;
9a304d29
PB
67};
68
ee0a19ec
PB
69static QTAILQ_HEAD(, NBDExport) exports = QTAILQ_HEAD_INITIALIZER(exports);
70
9a304d29
PB
71struct NBDClient {
72 int refcount;
73 void (*close)(NBDClient *client);
74
75 NBDExport *exp;
76 int sock;
77
78 Coroutine *recv_coroutine;
79
80 CoMutex send_lock;
81 Coroutine *send_coroutine;
82
958c717d
HR
83 bool can_read;
84
4b9441f6 85 QTAILQ_ENTRY(NBDClient) next;
9a304d29 86 int nb_requests;
ff2b68aa 87 bool closing;
9a304d29
PB
88};
89
7a5ca864
FB
90/* That's all folks */
91
958c717d
HR
92static void nbd_set_handlers(NBDClient *client);
93static void nbd_unset_handlers(NBDClient *client);
94static void nbd_update_can_read(NBDClient *client);
95
1a6245a5
FZ
96static void nbd_negotiate_continue(void *opaque)
97{
98 qemu_coroutine_enter(opaque, NULL);
99}
100
101static ssize_t nbd_negotiate_read(int fd, void *buffer, size_t size)
102{
103 ssize_t ret;
104
105 assert(qemu_in_coroutine());
106 /* Negotiation are always in main loop. */
107 qemu_set_fd_handler(fd, nbd_negotiate_continue, NULL,
108 qemu_coroutine_self());
109 ret = read_sync(fd, buffer, size);
110 qemu_set_fd_handler(fd, NULL, NULL, NULL);
111 return ret;
112
113}
114
115static ssize_t nbd_negotiate_write(int fd, void *buffer, size_t size)
116{
117 ssize_t ret;
118
119 assert(qemu_in_coroutine());
120 /* Negotiation are always in main loop. */
121 qemu_set_fd_handler(fd, NULL, nbd_negotiate_continue,
122 qemu_coroutine_self());
123 ret = write_sync(fd, buffer, size);
124 qemu_set_fd_handler(fd, NULL, NULL, NULL);
125 return ret;
126}
127
128static ssize_t nbd_negotiate_drop_sync(int fd, size_t size)
0379f474
HR
129{
130 ssize_t ret, dropped = size;
131 uint8_t *buffer = g_malloc(MIN(65536, size));
132
133 while (size > 0) {
1a6245a5 134 ret = nbd_negotiate_read(fd, buffer, MIN(65536, size));
0379f474
HR
135 if (ret < 0) {
136 g_free(buffer);
137 return ret;
138 }
139
140 assert(ret <= size);
141 size -= ret;
142 }
143
144 g_free(buffer);
145 return dropped;
146}
147
6b8c01e7 148/* Basic flow for negotiation
7a5ca864
FB
149
150 Server Client
7a5ca864 151 Negotiate
6b8c01e7
PB
152
153 or
154
155 Server Client
156 Negotiate #1
157 Option
158 Negotiate #2
159
160 ----
161
162 followed by
163
164 Server Client
7a5ca864
FB
165 Request
166 Response
167 Request
168 Response
169 ...
170 ...
171 Request (type == 2)
6b8c01e7 172
7a5ca864
FB
173*/
174
1a6245a5 175static int nbd_negotiate_send_rep(int csock, uint32_t type, uint32_t opt)
6b8c01e7 176{
6b8c01e7 177 uint64_t magic;
f5076b5a 178 uint32_t len;
6b8c01e7 179
f5076b5a 180 magic = cpu_to_be64(NBD_REP_MAGIC);
1a6245a5 181 if (nbd_negotiate_write(csock, &magic, sizeof(magic)) != sizeof(magic)) {
f5076b5a
HB
182 LOG("write failed (rep magic)");
183 return -EINVAL;
6b8c01e7 184 }
f5076b5a 185 opt = cpu_to_be32(opt);
1a6245a5 186 if (nbd_negotiate_write(csock, &opt, sizeof(opt)) != sizeof(opt)) {
f5076b5a
HB
187 LOG("write failed (rep opt)");
188 return -EINVAL;
6b8c01e7 189 }
f5076b5a 190 type = cpu_to_be32(type);
1a6245a5 191 if (nbd_negotiate_write(csock, &type, sizeof(type)) != sizeof(type)) {
f5076b5a
HB
192 LOG("write failed (rep type)");
193 return -EINVAL;
6b8c01e7 194 }
f5076b5a 195 len = cpu_to_be32(0);
1a6245a5 196 if (nbd_negotiate_write(csock, &len, sizeof(len)) != sizeof(len)) {
f5076b5a
HB
197 LOG("write failed (rep data length)");
198 return -EINVAL;
6b8c01e7 199 }
f5076b5a
HB
200 return 0;
201}
6b8c01e7 202
1a6245a5 203static int nbd_negotiate_send_rep_list(int csock, NBDExport *exp)
32d7d2e0
HB
204{
205 uint64_t magic, name_len;
206 uint32_t opt, type, len;
207
208 name_len = strlen(exp->name);
209 magic = cpu_to_be64(NBD_REP_MAGIC);
1a6245a5 210 if (nbd_negotiate_write(csock, &magic, sizeof(magic)) != sizeof(magic)) {
32d7d2e0
HB
211 LOG("write failed (magic)");
212 return -EINVAL;
213 }
214 opt = cpu_to_be32(NBD_OPT_LIST);
1a6245a5 215 if (nbd_negotiate_write(csock, &opt, sizeof(opt)) != sizeof(opt)) {
32d7d2e0
HB
216 LOG("write failed (opt)");
217 return -EINVAL;
218 }
219 type = cpu_to_be32(NBD_REP_SERVER);
1a6245a5 220 if (nbd_negotiate_write(csock, &type, sizeof(type)) != sizeof(type)) {
32d7d2e0
HB
221 LOG("write failed (reply type)");
222 return -EINVAL;
223 }
224 len = cpu_to_be32(name_len + sizeof(len));
1a6245a5 225 if (nbd_negotiate_write(csock, &len, sizeof(len)) != sizeof(len)) {
32d7d2e0
HB
226 LOG("write failed (length)");
227 return -EINVAL;
228 }
229 len = cpu_to_be32(name_len);
1a6245a5 230 if (nbd_negotiate_write(csock, &len, sizeof(len)) != sizeof(len)) {
32d7d2e0
HB
231 LOG("write failed (length)");
232 return -EINVAL;
233 }
1a6245a5 234 if (nbd_negotiate_write(csock, exp->name, name_len) != name_len) {
32d7d2e0
HB
235 LOG("write failed (buffer)");
236 return -EINVAL;
237 }
238 return 0;
239}
240
1a6245a5 241static int nbd_negotiate_handle_list(NBDClient *client, uint32_t length)
32d7d2e0
HB
242{
243 int csock;
244 NBDExport *exp;
245
246 csock = client->sock;
247 if (length) {
1a6245a5 248 if (nbd_negotiate_drop_sync(csock, length) != length) {
0379f474
HR
249 return -EIO;
250 }
1a6245a5 251 return nbd_negotiate_send_rep(csock, NBD_REP_ERR_INVALID, NBD_OPT_LIST);
32d7d2e0
HB
252 }
253
254 /* For each export, send a NBD_REP_SERVER reply. */
255 QTAILQ_FOREACH(exp, &exports, next) {
1a6245a5 256 if (nbd_negotiate_send_rep_list(csock, exp)) {
32d7d2e0
HB
257 return -EINVAL;
258 }
259 }
260 /* Finish with a NBD_REP_ACK. */
1a6245a5 261 return nbd_negotiate_send_rep(csock, NBD_REP_ACK, NBD_OPT_LIST);
32d7d2e0
HB
262}
263
1a6245a5 264static int nbd_negotiate_handle_export_name(NBDClient *client, uint32_t length)
f5076b5a
HB
265{
266 int rc = -EINVAL, csock = client->sock;
267 char name[256];
6b8c01e7 268
f5076b5a
HB
269 /* Client sends:
270 [20 .. xx] export name (length bytes)
271 */
6b8c01e7 272 TRACE("Checking length");
6b8c01e7
PB
273 if (length > 255) {
274 LOG("Bad length received");
275 goto fail;
276 }
1a6245a5 277 if (nbd_negotiate_read(csock, name, length) != length) {
6b8c01e7
PB
278 LOG("read failed");
279 goto fail;
280 }
281 name[length] = '\0';
282
283 client->exp = nbd_export_find(name);
284 if (!client->exp) {
285 LOG("export not found");
286 goto fail;
287 }
288
289 QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
290 nbd_export_get(client->exp);
6b8c01e7
PB
291 rc = 0;
292fail:
293 return rc;
294}
295
1a6245a5 296static int nbd_negotiate_options(NBDClient *client)
f5076b5a 297{
9c122ada
HR
298 int csock = client->sock;
299 uint32_t flags;
300
301 /* Client sends:
302 [ 0 .. 3] client flags
303
304 [ 0 .. 7] NBD_OPTS_MAGIC
305 [ 8 .. 11] NBD option
306 [12 .. 15] Data length
307 ... Rest of request
308
309 [ 0 .. 7] NBD_OPTS_MAGIC
310 [ 8 .. 11] Second NBD option
311 [12 .. 15] Data length
312 ... Rest of request
313 */
314
1a6245a5 315 if (nbd_negotiate_read(csock, &flags, sizeof(flags)) != sizeof(flags)) {
9c122ada
HR
316 LOG("read failed");
317 return -EIO;
318 }
319 TRACE("Checking client flags");
320 be32_to_cpus(&flags);
321 if (flags != 0 && flags != NBD_FLAG_C_FIXED_NEWSTYLE) {
322 LOG("Bad client flags received");
323 return -EIO;
324 }
325
f5076b5a 326 while (1) {
9c122ada 327 int ret;
f5076b5a
HB
328 uint32_t tmp, length;
329 uint64_t magic;
330
1a6245a5 331 if (nbd_negotiate_read(csock, &magic, sizeof(magic)) != sizeof(magic)) {
f5076b5a
HB
332 LOG("read failed");
333 return -EINVAL;
334 }
335 TRACE("Checking opts magic");
336 if (magic != be64_to_cpu(NBD_OPTS_MAGIC)) {
337 LOG("Bad magic received");
338 return -EINVAL;
339 }
340
1a6245a5 341 if (nbd_negotiate_read(csock, &tmp, sizeof(tmp)) != sizeof(tmp)) {
f5076b5a
HB
342 LOG("read failed");
343 return -EINVAL;
344 }
345
1a6245a5
FZ
346 if (nbd_negotiate_read(csock, &length,
347 sizeof(length)) != sizeof(length)) {
f5076b5a
HB
348 LOG("read failed");
349 return -EINVAL;
350 }
351 length = be32_to_cpu(length);
352
353 TRACE("Checking option");
354 switch (be32_to_cpu(tmp)) {
32d7d2e0 355 case NBD_OPT_LIST:
1a6245a5 356 ret = nbd_negotiate_handle_list(client, length);
892f5a52
HR
357 if (ret < 0) {
358 return ret;
32d7d2e0
HB
359 }
360 break;
361
f5076b5a
HB
362 case NBD_OPT_ABORT:
363 return -EINVAL;
364
365 case NBD_OPT_EXPORT_NAME:
1a6245a5 366 return nbd_negotiate_handle_export_name(client, length);
f5076b5a
HB
367
368 default:
369 tmp = be32_to_cpu(tmp);
370 LOG("Unsupported option 0x%x", tmp);
1a6245a5 371 nbd_negotiate_send_rep(client->sock, NBD_REP_ERR_UNSUP, tmp);
f5076b5a
HB
372 return -EINVAL;
373 }
374 }
375}
376
1a6245a5
FZ
377typedef struct {
378 NBDClient *client;
379 Coroutine *co;
380} NBDClientNewData;
381
382static coroutine_fn int nbd_negotiate(NBDClientNewData *data)
7a5ca864 383{
1a6245a5 384 NBDClient *client = data->client;
9a304d29 385 int csock = client->sock;
b2e3d87f 386 char buf[8 + 8 + 8 + 128];
185b4338 387 int rc;
6b8c01e7
PB
388 const int myflags = (NBD_FLAG_HAS_FLAGS | NBD_FLAG_SEND_TRIM |
389 NBD_FLAG_SEND_FLUSH | NBD_FLAG_SEND_FUA);
b2e3d87f 390
6b8c01e7
PB
391 /* Negotiation header without options:
392 [ 0 .. 7] passwd ("NBDMAGIC")
393 [ 8 .. 15] magic (NBD_CLIENT_MAGIC)
b2e3d87f 394 [16 .. 23] size
6b8c01e7 395 [24 .. 25] server flags (0)
5672ee54 396 [26 .. 27] export flags
6b8c01e7
PB
397 [28 .. 151] reserved (0)
398
399 Negotiation header with options, part 1:
400 [ 0 .. 7] passwd ("NBDMAGIC")
401 [ 8 .. 15] magic (NBD_OPTS_MAGIC)
402 [16 .. 17] server flags (0)
403
404 part 2 (after options are sent):
405 [18 .. 25] size
406 [26 .. 27] export flags
407 [28 .. 151] reserved (0)
b2e3d87f
NT
408 */
409
185b4338
PB
410 rc = -EINVAL;
411
b2e3d87f 412 TRACE("Beginning negotiation.");
8ffaaba0 413 memset(buf, 0, sizeof(buf));
b2e3d87f 414 memcpy(buf, "NBDMAGIC", 8);
6b8c01e7
PB
415 if (client->exp) {
416 assert ((client->exp->nbdflags & ~65535) == 0);
417 cpu_to_be64w((uint64_t*)(buf + 8), NBD_CLIENT_MAGIC);
418 cpu_to_be64w((uint64_t*)(buf + 16), client->exp->size);
419 cpu_to_be16w((uint16_t*)(buf + 26), client->exp->nbdflags | myflags);
420 } else {
421 cpu_to_be64w((uint64_t*)(buf + 8), NBD_OPTS_MAGIC);
f5076b5a 422 cpu_to_be16w((uint16_t *)(buf + 16), NBD_FLAG_FIXED_NEWSTYLE);
6b8c01e7 423 }
b2e3d87f 424
6b8c01e7 425 if (client->exp) {
1a6245a5 426 if (nbd_negotiate_write(csock, buf, sizeof(buf)) != sizeof(buf)) {
6b8c01e7
PB
427 LOG("write failed");
428 goto fail;
429 }
430 } else {
1a6245a5 431 if (nbd_negotiate_write(csock, buf, 18) != 18) {
6b8c01e7
PB
432 LOG("write failed");
433 goto fail;
434 }
1a6245a5 435 rc = nbd_negotiate_options(client);
f5076b5a 436 if (rc != 0) {
6b8c01e7
PB
437 LOG("option negotiation failed");
438 goto fail;
439 }
440
441 assert ((client->exp->nbdflags & ~65535) == 0);
442 cpu_to_be64w((uint64_t*)(buf + 18), client->exp->size);
443 cpu_to_be16w((uint16_t*)(buf + 26), client->exp->nbdflags | myflags);
1a6245a5
FZ
444 if (nbd_negotiate_write(csock, buf + 18,
445 sizeof(buf) - 18) != sizeof(buf) - 18) {
6b8c01e7
PB
446 LOG("write failed");
447 goto fail;
448 }
b2e3d87f
NT
449 }
450
07f35073 451 TRACE("Negotiation succeeded.");
185b4338
PB
452 rc = 0;
453fail:
454 return rc;
7a5ca864
FB
455}
456
b90fb4b8 457#ifdef __linux__
7a5ca864
FB
458
459int nbd_disconnect(int fd)
460{
b2e3d87f
NT
461 ioctl(fd, NBD_CLEAR_QUE);
462 ioctl(fd, NBD_DISCONNECT);
463 ioctl(fd, NBD_CLEAR_SOCK);
464 return 0;
7a5ca864
FB
465}
466
03ff3ca3 467#else
03ff3ca3
AL
468
469int nbd_disconnect(int fd)
470{
185b4338 471 return -ENOTSUP;
03ff3ca3 472}
03ff3ca3 473#endif
7a5ca864 474
94e7340b 475static ssize_t nbd_receive_request(int csock, struct nbd_request *request)
75818250 476{
fa26c26b 477 uint8_t buf[NBD_REQUEST_SIZE];
b2e3d87f 478 uint32_t magic;
185b4338 479 ssize_t ret;
b2e3d87f 480
185b4338
PB
481 ret = read_sync(csock, buf, sizeof(buf));
482 if (ret < 0) {
483 return ret;
484 }
485
486 if (ret != sizeof(buf)) {
b2e3d87f 487 LOG("read failed");
185b4338 488 return -EINVAL;
b2e3d87f
NT
489 }
490
491 /* Request
492 [ 0 .. 3] magic (NBD_REQUEST_MAGIC)
493 [ 4 .. 7] type (0 == READ, 1 == WRITE)
494 [ 8 .. 15] handle
495 [16 .. 23] from
496 [24 .. 27] len
497 */
498
499 magic = be32_to_cpup((uint32_t*)buf);
500 request->type = be32_to_cpup((uint32_t*)(buf + 4));
501 request->handle = be64_to_cpup((uint64_t*)(buf + 8));
502 request->from = be64_to_cpup((uint64_t*)(buf + 16));
503 request->len = be32_to_cpup((uint32_t*)(buf + 24));
504
505 TRACE("Got request: "
506 "{ magic = 0x%x, .type = %d, from = %" PRIu64" , len = %u }",
507 magic, request->type, request->from, request->len);
508
509 if (magic != NBD_REQUEST_MAGIC) {
510 LOG("invalid magic (got 0x%x)", magic);
185b4338 511 return -EINVAL;
b2e3d87f
NT
512 }
513 return 0;
75818250
TS
514}
515
94e7340b 516static ssize_t nbd_send_reply(int csock, struct nbd_reply *reply)
75818250 517{
fa26c26b 518 uint8_t buf[NBD_REPLY_SIZE];
185b4338 519 ssize_t ret;
b2e3d87f 520
ca441480
PB
521 reply->error = system_errno_to_nbd_errno(reply->error);
522
b2e3d87f
NT
523 /* Reply
524 [ 0 .. 3] magic (NBD_REPLY_MAGIC)
525 [ 4 .. 7] error (0 == no error)
526 [ 7 .. 15] handle
527 */
528 cpu_to_be32w((uint32_t*)buf, NBD_REPLY_MAGIC);
529 cpu_to_be32w((uint32_t*)(buf + 4), reply->error);
530 cpu_to_be64w((uint64_t*)(buf + 8), reply->handle);
531
532 TRACE("Sending response to client");
533
185b4338
PB
534 ret = write_sync(csock, buf, sizeof(buf));
535 if (ret < 0) {
536 return ret;
537 }
538
539 if (ret != sizeof(buf)) {
b2e3d87f 540 LOG("writing to socket failed");
185b4338 541 return -EINVAL;
b2e3d87f
NT
542 }
543 return 0;
75818250 544}
7a5ca864 545
41996e38
PB
546#define MAX_NBD_REQUESTS 16
547
ce33967a 548void nbd_client_get(NBDClient *client)
1743b515
PB
549{
550 client->refcount++;
551}
552
ce33967a 553void nbd_client_put(NBDClient *client)
1743b515
PB
554{
555 if (--client->refcount == 0) {
ff2b68aa 556 /* The last reference should be dropped by client->close,
f53a829b 557 * which is called by client_close.
ff2b68aa
PB
558 */
559 assert(client->closing);
560
958c717d 561 nbd_unset_handlers(client);
ff2b68aa
PB
562 close(client->sock);
563 client->sock = -1;
6b8c01e7
PB
564 if (client->exp) {
565 QTAILQ_REMOVE(&client->exp->clients, client, next);
566 nbd_export_put(client->exp);
567 }
1743b515
PB
568 g_free(client);
569 }
570}
571
f53a829b 572static void client_close(NBDClient *client)
1743b515 573{
ff2b68aa
PB
574 if (client->closing) {
575 return;
576 }
577
578 client->closing = true;
579
580 /* Force requests to finish. They will drop their own references,
581 * then we'll close the socket and free the NBDClient.
582 */
583 shutdown(client->sock, 2);
584
585 /* Also tell the client, so that they release their reference. */
1743b515
PB
586 if (client->close) {
587 client->close(client);
588 }
1743b515
PB
589}
590
72deddc5 591static NBDRequest *nbd_request_get(NBDClient *client)
d9a73806
PB
592{
593 NBDRequest *req;
72deddc5 594
41996e38
PB
595 assert(client->nb_requests <= MAX_NBD_REQUESTS - 1);
596 client->nb_requests++;
958c717d 597 nbd_update_can_read(client);
41996e38 598
1729404c 599 req = g_new0(NBDRequest, 1);
72deddc5
PB
600 nbd_client_get(client);
601 req->client = client;
d9a73806
PB
602 return req;
603}
604
72deddc5 605static void nbd_request_put(NBDRequest *req)
d9a73806 606{
72deddc5 607 NBDClient *client = req->client;
e1adb27a 608
2d821488
SH
609 if (req->data) {
610 qemu_vfree(req->data);
611 }
1729404c 612 g_free(req);
e1adb27a 613
958c717d
HR
614 client->nb_requests--;
615 nbd_update_can_read(client);
72deddc5 616 nbd_client_put(client);
d9a73806
PB
617}
618
aadf99a7 619static void blk_aio_attached(AioContext *ctx, void *opaque)
f2149281
HR
620{
621 NBDExport *exp = opaque;
622 NBDClient *client;
623
624 TRACE("Export %s: Attaching clients to AIO context %p\n", exp->name, ctx);
625
626 exp->ctx = ctx;
627
628 QTAILQ_FOREACH(client, &exp->clients, next) {
629 nbd_set_handlers(client);
630 }
631}
632
aadf99a7 633static void blk_aio_detach(void *opaque)
f2149281
HR
634{
635 NBDExport *exp = opaque;
636 NBDClient *client;
637
638 TRACE("Export %s: Detaching clients from AIO context %p\n", exp->name, exp->ctx);
639
640 QTAILQ_FOREACH(client, &exp->clients, next) {
641 nbd_unset_handlers(client);
642 }
643
644 exp->ctx = NULL;
645}
646
e140177d 647NBDExport *nbd_export_new(BlockBackend *blk, off_t dev_offset, off_t size,
98f44bbe
HR
648 uint32_t nbdflags, void (*close)(NBDExport *),
649 Error **errp)
af49bbbe
PB
650{
651 NBDExport *exp = g_malloc0(sizeof(NBDExport));
2c8d9f06 652 exp->refcount = 1;
4b9441f6 653 QTAILQ_INIT(&exp->clients);
aadf99a7 654 exp->blk = blk;
af49bbbe
PB
655 exp->dev_offset = dev_offset;
656 exp->nbdflags = nbdflags;
98f44bbe
HR
657 exp->size = size < 0 ? blk_getlength(blk) : size;
658 if (exp->size < 0) {
659 error_setg_errno(errp, -exp->size,
660 "Failed to determine the NBD export's length");
661 goto fail;
662 }
663 exp->size -= exp->size % BDRV_SECTOR_SIZE;
664
0ddf08db 665 exp->close = close;
aadf99a7
HR
666 exp->ctx = blk_get_aio_context(blk);
667 blk_ref(blk);
668 blk_add_aio_context_notifier(blk, blk_aio_attached, blk_aio_detach, exp);
7ea2d269
AK
669 /*
670 * NBD exports are used for non-shared storage migration. Make sure
671 * that BDRV_O_INCOMING is cleared and the image is ready for write
672 * access since the export could be available before migration handover.
673 */
aadf99a7 674 blk_invalidate_cache(blk, NULL);
af49bbbe 675 return exp;
98f44bbe
HR
676
677fail:
678 g_free(exp);
679 return NULL;
af49bbbe
PB
680}
681
ee0a19ec
PB
682NBDExport *nbd_export_find(const char *name)
683{
684 NBDExport *exp;
685 QTAILQ_FOREACH(exp, &exports, next) {
686 if (strcmp(name, exp->name) == 0) {
687 return exp;
688 }
689 }
690
691 return NULL;
692}
693
694void nbd_export_set_name(NBDExport *exp, const char *name)
695{
696 if (exp->name == name) {
697 return;
698 }
699
700 nbd_export_get(exp);
701 if (exp->name != NULL) {
702 g_free(exp->name);
703 exp->name = NULL;
704 QTAILQ_REMOVE(&exports, exp, next);
705 nbd_export_put(exp);
706 }
707 if (name != NULL) {
708 nbd_export_get(exp);
709 exp->name = g_strdup(name);
710 QTAILQ_INSERT_TAIL(&exports, exp, next);
711 }
712 nbd_export_put(exp);
713}
714
af49bbbe
PB
715void nbd_export_close(NBDExport *exp)
716{
4b9441f6 717 NBDClient *client, *next;
2c8d9f06 718
4b9441f6
PB
719 nbd_export_get(exp);
720 QTAILQ_FOREACH_SAFE(client, &exp->clients, next, next) {
f53a829b 721 client_close(client);
4b9441f6 722 }
125afda8 723 nbd_export_set_name(exp, NULL);
4b9441f6 724 nbd_export_put(exp);
2c8d9f06
PB
725}
726
727void nbd_export_get(NBDExport *exp)
728{
729 assert(exp->refcount > 0);
730 exp->refcount++;
731}
732
733void nbd_export_put(NBDExport *exp)
734{
735 assert(exp->refcount > 0);
736 if (exp->refcount == 1) {
737 nbd_export_close(exp);
d9a73806
PB
738 }
739
2c8d9f06 740 if (--exp->refcount == 0) {
ee0a19ec
PB
741 assert(exp->name == NULL);
742
0ddf08db
PB
743 if (exp->close) {
744 exp->close(exp);
745 }
746
d6268348
WC
747 if (exp->blk) {
748 blk_remove_aio_context_notifier(exp->blk, blk_aio_attached,
749 blk_aio_detach, exp);
750 blk_unref(exp->blk);
751 exp->blk = NULL;
752 }
753
2c8d9f06
PB
754 g_free(exp);
755 }
af49bbbe
PB
756}
757
e140177d 758BlockBackend *nbd_export_get_blockdev(NBDExport *exp)
125afda8 759{
aadf99a7 760 return exp->blk;
125afda8
PB
761}
762
ee0a19ec
PB
763void nbd_export_close_all(void)
764{
765 NBDExport *exp, *next;
766
767 QTAILQ_FOREACH_SAFE(exp, &exports, next, next) {
768 nbd_export_close(exp);
ee0a19ec
PB
769 }
770}
771
94e7340b
PB
772static ssize_t nbd_co_send_reply(NBDRequest *req, struct nbd_reply *reply,
773 int len)
22045592 774{
72deddc5
PB
775 NBDClient *client = req->client;
776 int csock = client->sock;
94e7340b 777 ssize_t rc, ret;
22045592 778
262db388 779 qemu_co_mutex_lock(&client->send_lock);
262db388 780 client->send_coroutine = qemu_coroutine_self();
958c717d 781 nbd_set_handlers(client);
262db388 782
22045592
PB
783 if (!len) {
784 rc = nbd_send_reply(csock, reply);
22045592
PB
785 } else {
786 socket_set_cork(csock, 1);
787 rc = nbd_send_reply(csock, reply);
fc19f8a0 788 if (rc >= 0) {
262db388 789 ret = qemu_co_send(csock, req->data, len);
22045592 790 if (ret != len) {
185b4338 791 rc = -EIO;
22045592
PB
792 }
793 }
22045592
PB
794 socket_set_cork(csock, 0);
795 }
262db388
PB
796
797 client->send_coroutine = NULL;
958c717d 798 nbd_set_handlers(client);
262db388 799 qemu_co_mutex_unlock(&client->send_lock);
22045592
PB
800 return rc;
801}
802
94e7340b 803static ssize_t nbd_co_receive_request(NBDRequest *req, struct nbd_request *request)
a030b347 804{
72deddc5
PB
805 NBDClient *client = req->client;
806 int csock = client->sock;
2d821488 807 uint32_t command;
94e7340b 808 ssize_t rc;
a030b347 809
262db388 810 client->recv_coroutine = qemu_coroutine_self();
958c717d
HR
811 nbd_update_can_read(client);
812
7fe7b68b
PB
813 rc = nbd_receive_request(csock, request);
814 if (rc < 0) {
815 if (rc != -EAGAIN) {
816 rc = -EIO;
817 }
a030b347
PB
818 goto out;
819 }
820
2d821488 821 if (request->len > NBD_MAX_BUFFER_SIZE) {
a030b347 822 LOG("len (%u) is larger than max len (%u)",
2d821488 823 request->len, NBD_MAX_BUFFER_SIZE);
a030b347
PB
824 rc = -EINVAL;
825 goto out;
826 }
827
828 if ((request->from + request->len) < request->from) {
829 LOG("integer overflow detected! "
830 "you're probably being attacked");
831 rc = -EINVAL;
832 goto out;
833 }
834
835 TRACE("Decoding type");
836
2d821488
SH
837 command = request->type & NBD_CMD_MASK_COMMAND;
838 if (command == NBD_CMD_READ || command == NBD_CMD_WRITE) {
aadf99a7 839 req->data = blk_blockalign(client->exp->blk, request->len);
2d821488
SH
840 }
841 if (command == NBD_CMD_WRITE) {
a030b347
PB
842 TRACE("Reading %u byte(s)", request->len);
843
262db388 844 if (qemu_co_recv(csock, req->data, request->len) != request->len) {
a030b347
PB
845 LOG("reading from socket failed");
846 rc = -EIO;
847 goto out;
848 }
849 }
850 rc = 0;
851
852out:
262db388 853 client->recv_coroutine = NULL;
958c717d
HR
854 nbd_update_can_read(client);
855
a030b347
PB
856 return rc;
857}
858
262db388 859static void nbd_trip(void *opaque)
75818250 860{
262db388 861 NBDClient *client = opaque;
1743b515 862 NBDExport *exp = client->exp;
ff2b68aa 863 NBDRequest *req;
b2e3d87f
NT
864 struct nbd_request request;
865 struct nbd_reply reply;
94e7340b 866 ssize_t ret;
8c5d1abb 867 uint32_t command;
b2e3d87f
NT
868
869 TRACE("Reading request.");
ff2b68aa
PB
870 if (client->closing) {
871 return;
872 }
b2e3d87f 873
ff2b68aa 874 req = nbd_request_get(client);
262db388 875 ret = nbd_co_receive_request(req, &request);
7fe7b68b
PB
876 if (ret == -EAGAIN) {
877 goto done;
878 }
a030b347 879 if (ret == -EIO) {
d9a73806 880 goto out;
a030b347 881 }
b2e3d87f 882
fae69416
PB
883 reply.handle = request.handle;
884 reply.error = 0;
885
a030b347
PB
886 if (ret < 0) {
887 reply.error = -ret;
888 goto error_reply;
b2e3d87f 889 }
8c5d1abb
HB
890 command = request.type & NBD_CMD_MASK_COMMAND;
891 if (command != NBD_CMD_DISC && (request.from + request.len) > exp->size) {
b2e3d87f
NT
892 LOG("From: %" PRIu64 ", Len: %u, Size: %" PRIu64
893 ", Offset: %" PRIu64 "\n",
af49bbbe 894 request.from, request.len,
0fee8f34 895 (uint64_t)exp->size, (uint64_t)exp->dev_offset);
b2e3d87f 896 LOG("requested operation past EOF--bad client?");
fae69416 897 goto invalid_request;
b2e3d87f
NT
898 }
899
d6268348
WC
900 if (client->closing) {
901 /*
902 * The client may be closed when we are blocked in
903 * nbd_co_receive_request()
904 */
905 goto done;
906 }
907
8c5d1abb 908 switch (command) {
b2e3d87f
NT
909 case NBD_CMD_READ:
910 TRACE("Request type is READ");
911
e25ceb76 912 if (request.type & NBD_CMD_FLAG_FUA) {
aadf99a7 913 ret = blk_co_flush(exp->blk);
e25ceb76
PB
914 if (ret < 0) {
915 LOG("flush failed");
916 reply.error = -ret;
917 goto error_reply;
918 }
919 }
920
aadf99a7
HR
921 ret = blk_read(exp->blk,
922 (request.from + exp->dev_offset) / BDRV_SECTOR_SIZE,
923 req->data, request.len / BDRV_SECTOR_SIZE);
adcf6302 924 if (ret < 0) {
b2e3d87f 925 LOG("reading from file failed");
adcf6302 926 reply.error = -ret;
fae69416 927 goto error_reply;
b2e3d87f 928 }
b2e3d87f
NT
929
930 TRACE("Read %u byte(s)", request.len);
262db388 931 if (nbd_co_send_reply(req, &reply, request.len) < 0)
d9a73806 932 goto out;
b2e3d87f
NT
933 break;
934 case NBD_CMD_WRITE:
935 TRACE("Request type is WRITE");
936
af49bbbe 937 if (exp->nbdflags & NBD_FLAG_READ_ONLY) {
b2e3d87f 938 TRACE("Server is read-only, return error");
fae69416
PB
939 reply.error = EROFS;
940 goto error_reply;
941 }
942
943 TRACE("Writing to device");
944
aadf99a7
HR
945 ret = blk_write(exp->blk,
946 (request.from + exp->dev_offset) / BDRV_SECTOR_SIZE,
947 req->data, request.len / BDRV_SECTOR_SIZE);
fae69416
PB
948 if (ret < 0) {
949 LOG("writing to file failed");
950 reply.error = -ret;
951 goto error_reply;
952 }
b2e3d87f 953
fae69416 954 if (request.type & NBD_CMD_FLAG_FUA) {
aadf99a7 955 ret = blk_co_flush(exp->blk);
adcf6302 956 if (ret < 0) {
fae69416 957 LOG("flush failed");
adcf6302 958 reply.error = -ret;
fae69416 959 goto error_reply;
2c7989a9 960 }
b2e3d87f
NT
961 }
962
fc19f8a0 963 if (nbd_co_send_reply(req, &reply, 0) < 0) {
d9a73806 964 goto out;
fc19f8a0 965 }
b2e3d87f
NT
966 break;
967 case NBD_CMD_DISC:
968 TRACE("Request type is DISCONNECT");
969 errno = 0;
262db388 970 goto out;
1486d04a
PB
971 case NBD_CMD_FLUSH:
972 TRACE("Request type is FLUSH");
973
aadf99a7 974 ret = blk_co_flush(exp->blk);
1486d04a
PB
975 if (ret < 0) {
976 LOG("flush failed");
977 reply.error = -ret;
978 }
fc19f8a0 979 if (nbd_co_send_reply(req, &reply, 0) < 0) {
d9a73806 980 goto out;
fc19f8a0 981 }
7a706633
PB
982 break;
983 case NBD_CMD_TRIM:
984 TRACE("Request type is TRIM");
aadf99a7
HR
985 ret = blk_co_discard(exp->blk, (request.from + exp->dev_offset)
986 / BDRV_SECTOR_SIZE,
987 request.len / BDRV_SECTOR_SIZE);
7a706633
PB
988 if (ret < 0) {
989 LOG("discard failed");
990 reply.error = -ret;
991 }
fc19f8a0 992 if (nbd_co_send_reply(req, &reply, 0) < 0) {
d9a73806 993 goto out;
fc19f8a0 994 }
1486d04a 995 break;
b2e3d87f
NT
996 default:
997 LOG("invalid request type (%u) received", request.type);
fae69416 998 invalid_request:
8b2f0abf 999 reply.error = EINVAL;
fae69416 1000 error_reply:
fc19f8a0 1001 if (nbd_co_send_reply(req, &reply, 0) < 0) {
d9a73806 1002 goto out;
fc19f8a0 1003 }
fae69416 1004 break;
b2e3d87f
NT
1005 }
1006
1007 TRACE("Request/Reply complete");
1008
7fe7b68b 1009done:
262db388
PB
1010 nbd_request_put(req);
1011 return;
1012
d9a73806 1013out:
72deddc5 1014 nbd_request_put(req);
f53a829b 1015 client_close(client);
7a5ca864 1016}
af49bbbe 1017
1743b515
PB
1018static void nbd_read(void *opaque)
1019{
1020 NBDClient *client = opaque;
1021
262db388
PB
1022 if (client->recv_coroutine) {
1023 qemu_coroutine_enter(client->recv_coroutine, NULL);
1024 } else {
1025 qemu_coroutine_enter(qemu_coroutine_create(nbd_trip), client);
1743b515 1026 }
1743b515
PB
1027}
1028
262db388
PB
1029static void nbd_restart_write(void *opaque)
1030{
1031 NBDClient *client = opaque;
1032
1033 qemu_coroutine_enter(client->send_coroutine, NULL);
1034}
1035
958c717d
HR
1036static void nbd_set_handlers(NBDClient *client)
1037{
1038 if (client->exp && client->exp->ctx) {
1039 aio_set_fd_handler(client->exp->ctx, client->sock,
172cc129 1040 true,
958c717d
HR
1041 client->can_read ? nbd_read : NULL,
1042 client->send_coroutine ? nbd_restart_write : NULL,
1043 client);
1044 }
1045}
1046
1047static void nbd_unset_handlers(NBDClient *client)
1048{
1049 if (client->exp && client->exp->ctx) {
dca21ef2 1050 aio_set_fd_handler(client->exp->ctx, client->sock,
172cc129 1051 true, NULL, NULL, NULL);
958c717d
HR
1052 }
1053}
1054
1055static void nbd_update_can_read(NBDClient *client)
1056{
1057 bool can_read = client->recv_coroutine ||
1058 client->nb_requests < MAX_NBD_REQUESTS;
1059
1060 if (can_read != client->can_read) {
1061 client->can_read = can_read;
1062 nbd_set_handlers(client);
1063
1064 /* There is no need to invoke aio_notify(), since aio_set_fd_handler()
1065 * in nbd_set_handlers() will have taken care of that */
1066 }
1067}
1068
1a6245a5
FZ
1069static coroutine_fn void nbd_co_client_start(void *opaque)
1070{
1071 NBDClientNewData *data = opaque;
1072 NBDClient *client = data->client;
1073 NBDExport *exp = client->exp;
1074
1075 if (exp) {
1076 nbd_export_get(exp);
1077 }
1078 if (nbd_negotiate(data)) {
1079 shutdown(client->sock, 2);
1080 client->close(client);
1081 goto out;
1082 }
1083 qemu_co_mutex_init(&client->send_lock);
1084 nbd_set_handlers(client);
1085
1086 if (exp) {
1087 QTAILQ_INSERT_TAIL(&exp->clients, client, next);
1088 }
1089out:
1090 g_free(data);
1091}
1092
ee7d7aab 1093void nbd_client_new(NBDExport *exp, int csock, void (*close_fn)(NBDClient *))
af49bbbe 1094{
1743b515 1095 NBDClient *client;
1a6245a5
FZ
1096 NBDClientNewData *data = g_new(NBDClientNewData, 1);
1097
1743b515
PB
1098 client = g_malloc0(sizeof(NBDClient));
1099 client->refcount = 1;
1100 client->exp = exp;
1101 client->sock = csock;
958c717d 1102 client->can_read = true;
ee7d7aab 1103 client->close = close_fn;
2c8d9f06 1104
1a6245a5
FZ
1105 data->client = client;
1106 data->co = qemu_coroutine_create(nbd_co_client_start);
1107 qemu_coroutine_enter(data->co, data);
af49bbbe 1108}