]> git.proxmox.com Git - mirror_qemu.git/blame - nbd/server.c
nbd: Add qemu-nbd -D for human-readable description
[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
d38ea87a 19#include "qemu/osdep.h"
da34e65c 20#include "qapi/error.h"
798bfe00 21#include "nbd-internal.h"
ca441480
PB
22
23static int system_errno_to_nbd_errno(int err)
24{
25 switch (err) {
26 case 0:
27 return NBD_SUCCESS;
28 case EPERM:
c0301fcc 29 case EROFS:
ca441480
PB
30 return NBD_EPERM;
31 case EIO:
32 return NBD_EIO;
33 case ENOMEM:
34 return NBD_ENOMEM;
35#ifdef EDQUOT
36 case EDQUOT:
37#endif
38 case EFBIG:
39 case ENOSPC:
40 return NBD_ENOSPC;
41 case EINVAL:
42 default:
43 return NBD_EINVAL;
44 }
45}
46
9a304d29
PB
47/* Definitions for opaque data types */
48
49typedef struct NBDRequest NBDRequest;
50
51struct NBDRequest {
52 QSIMPLEQ_ENTRY(NBDRequest) entry;
53 NBDClient *client;
54 uint8_t *data;
29b6c3b3 55 bool complete;
9a304d29
PB
56};
57
58struct NBDExport {
2c8d9f06 59 int refcount;
0ddf08db
PB
60 void (*close)(NBDExport *exp);
61
aadf99a7 62 BlockBackend *blk;
ee0a19ec 63 char *name;
b1a75b33 64 char *description;
9a304d29
PB
65 off_t dev_offset;
66 off_t size;
7423f417 67 uint16_t nbdflags;
4b9441f6 68 QTAILQ_HEAD(, NBDClient) clients;
ee0a19ec 69 QTAILQ_ENTRY(NBDExport) next;
958c717d
HR
70
71 AioContext *ctx;
741cc431 72
cd7fca95 73 BlockBackend *eject_notifier_blk;
741cc431 74 Notifier eject_notifier;
9a304d29
PB
75};
76
ee0a19ec
PB
77static QTAILQ_HEAD(, NBDExport) exports = QTAILQ_HEAD_INITIALIZER(exports);
78
9a304d29
PB
79struct NBDClient {
80 int refcount;
81 void (*close)(NBDClient *client);
82
83 NBDExport *exp;
f95910fe
DB
84 QCryptoTLSCreds *tlscreds;
85 char *tlsaclname;
1c778ef7
DB
86 QIOChannelSocket *sioc; /* The underlying data channel */
87 QIOChannel *ioc; /* The current I/O channel which may differ (eg TLS) */
9a304d29
PB
88
89 Coroutine *recv_coroutine;
90
91 CoMutex send_lock;
92 Coroutine *send_coroutine;
93
958c717d
HR
94 bool can_read;
95
4b9441f6 96 QTAILQ_ENTRY(NBDClient) next;
9a304d29 97 int nb_requests;
ff2b68aa 98 bool closing;
9a304d29
PB
99};
100
7a5ca864
FB
101/* That's all folks */
102
958c717d
HR
103static void nbd_set_handlers(NBDClient *client);
104static void nbd_unset_handlers(NBDClient *client);
105static void nbd_update_can_read(NBDClient *client);
106
1c778ef7
DB
107static gboolean nbd_negotiate_continue(QIOChannel *ioc,
108 GIOCondition condition,
109 void *opaque)
1a6245a5 110{
0b8b8753 111 qemu_coroutine_enter(opaque);
1c778ef7 112 return TRUE;
1a6245a5
FZ
113}
114
1c778ef7 115static ssize_t nbd_negotiate_read(QIOChannel *ioc, void *buffer, size_t size)
1a6245a5
FZ
116{
117 ssize_t ret;
1c778ef7 118 guint watch;
1a6245a5
FZ
119
120 assert(qemu_in_coroutine());
121 /* Negotiation are always in main loop. */
1c778ef7
DB
122 watch = qio_channel_add_watch(ioc,
123 G_IO_IN,
124 nbd_negotiate_continue,
125 qemu_coroutine_self(),
126 NULL);
127 ret = read_sync(ioc, buffer, size);
128 g_source_remove(watch);
1a6245a5
FZ
129 return ret;
130
131}
132
b1a75b33
EB
133static ssize_t nbd_negotiate_write(QIOChannel *ioc, const void *buffer,
134 size_t size)
1a6245a5
FZ
135{
136 ssize_t ret;
1c778ef7 137 guint watch;
1a6245a5
FZ
138
139 assert(qemu_in_coroutine());
140 /* Negotiation are always in main loop. */
1c778ef7
DB
141 watch = qio_channel_add_watch(ioc,
142 G_IO_OUT,
143 nbd_negotiate_continue,
144 qemu_coroutine_self(),
145 NULL);
146 ret = write_sync(ioc, buffer, size);
147 g_source_remove(watch);
1a6245a5
FZ
148 return ret;
149}
150
1c778ef7 151static ssize_t nbd_negotiate_drop_sync(QIOChannel *ioc, size_t size)
0379f474
HR
152{
153 ssize_t ret, dropped = size;
154 uint8_t *buffer = g_malloc(MIN(65536, size));
155
156 while (size > 0) {
1c778ef7 157 ret = nbd_negotiate_read(ioc, buffer, MIN(65536, size));
0379f474
HR
158 if (ret < 0) {
159 g_free(buffer);
160 return ret;
161 }
162
163 assert(ret <= size);
164 size -= ret;
165 }
166
167 g_free(buffer);
168 return dropped;
169}
170
6b8c01e7 171/* Basic flow for negotiation
7a5ca864
FB
172
173 Server Client
7a5ca864 174 Negotiate
6b8c01e7
PB
175
176 or
177
178 Server Client
179 Negotiate #1
180 Option
181 Negotiate #2
182
183 ----
184
185 followed by
186
187 Server Client
7a5ca864
FB
188 Request
189 Response
190 Request
191 Response
192 ...
193 ...
194 Request (type == 2)
6b8c01e7 195
7a5ca864
FB
196*/
197
1c778ef7 198static int nbd_negotiate_send_rep(QIOChannel *ioc, uint32_t type, uint32_t opt)
6b8c01e7 199{
6b8c01e7 200 uint64_t magic;
f5076b5a 201 uint32_t len;
6b8c01e7 202
2cb34749 203 TRACE("Reply opt=%" PRIx32 " type=%" PRIx32, type, opt);
f95910fe 204
f5076b5a 205 magic = cpu_to_be64(NBD_REP_MAGIC);
1c778ef7 206 if (nbd_negotiate_write(ioc, &magic, sizeof(magic)) != sizeof(magic)) {
f5076b5a
HB
207 LOG("write failed (rep magic)");
208 return -EINVAL;
6b8c01e7 209 }
f5076b5a 210 opt = cpu_to_be32(opt);
1c778ef7 211 if (nbd_negotiate_write(ioc, &opt, sizeof(opt)) != sizeof(opt)) {
f5076b5a
HB
212 LOG("write failed (rep opt)");
213 return -EINVAL;
6b8c01e7 214 }
f5076b5a 215 type = cpu_to_be32(type);
1c778ef7 216 if (nbd_negotiate_write(ioc, &type, sizeof(type)) != sizeof(type)) {
f5076b5a
HB
217 LOG("write failed (rep type)");
218 return -EINVAL;
6b8c01e7 219 }
f5076b5a 220 len = cpu_to_be32(0);
1c778ef7 221 if (nbd_negotiate_write(ioc, &len, sizeof(len)) != sizeof(len)) {
f5076b5a
HB
222 LOG("write failed (rep data length)");
223 return -EINVAL;
6b8c01e7 224 }
f5076b5a
HB
225 return 0;
226}
6b8c01e7 227
1c778ef7 228static int nbd_negotiate_send_rep_list(QIOChannel *ioc, NBDExport *exp)
32d7d2e0 229{
b1a75b33
EB
230 uint64_t magic;
231 size_t name_len, desc_len;
32d7d2e0 232 uint32_t opt, type, len;
b1a75b33
EB
233 const char *name = exp->name ? exp->name : "";
234 const char *desc = exp->description ? exp->description : "";
32d7d2e0 235
b1a75b33
EB
236 TRACE("Advertising export name '%s' description '%s'", name, desc);
237 name_len = strlen(name);
238 desc_len = strlen(desc);
32d7d2e0 239 magic = cpu_to_be64(NBD_REP_MAGIC);
1c778ef7 240 if (nbd_negotiate_write(ioc, &magic, sizeof(magic)) != sizeof(magic)) {
32d7d2e0
HB
241 LOG("write failed (magic)");
242 return -EINVAL;
243 }
244 opt = cpu_to_be32(NBD_OPT_LIST);
1c778ef7 245 if (nbd_negotiate_write(ioc, &opt, sizeof(opt)) != sizeof(opt)) {
32d7d2e0
HB
246 LOG("write failed (opt)");
247 return -EINVAL;
248 }
249 type = cpu_to_be32(NBD_REP_SERVER);
1c778ef7 250 if (nbd_negotiate_write(ioc, &type, sizeof(type)) != sizeof(type)) {
32d7d2e0
HB
251 LOG("write failed (reply type)");
252 return -EINVAL;
253 }
b1a75b33 254 len = cpu_to_be32(name_len + desc_len + sizeof(len));
1c778ef7 255 if (nbd_negotiate_write(ioc, &len, sizeof(len)) != sizeof(len)) {
32d7d2e0
HB
256 LOG("write failed (length)");
257 return -EINVAL;
258 }
259 len = cpu_to_be32(name_len);
1c778ef7 260 if (nbd_negotiate_write(ioc, &len, sizeof(len)) != sizeof(len)) {
b1a75b33
EB
261 LOG("write failed (name length)");
262 return -EINVAL;
263 }
264 if (nbd_negotiate_write(ioc, name, name_len) != name_len) {
265 LOG("write failed (name buffer)");
32d7d2e0
HB
266 return -EINVAL;
267 }
b1a75b33
EB
268 if (nbd_negotiate_write(ioc, desc, desc_len) != desc_len) {
269 LOG("write failed (description buffer)");
32d7d2e0
HB
270 return -EINVAL;
271 }
272 return 0;
273}
274
1a6245a5 275static int nbd_negotiate_handle_list(NBDClient *client, uint32_t length)
32d7d2e0 276{
32d7d2e0
HB
277 NBDExport *exp;
278
32d7d2e0 279 if (length) {
1c778ef7 280 if (nbd_negotiate_drop_sync(client->ioc, length) != length) {
0379f474
HR
281 return -EIO;
282 }
1c778ef7
DB
283 return nbd_negotiate_send_rep(client->ioc,
284 NBD_REP_ERR_INVALID, NBD_OPT_LIST);
32d7d2e0
HB
285 }
286
287 /* For each export, send a NBD_REP_SERVER reply. */
288 QTAILQ_FOREACH(exp, &exports, next) {
1c778ef7 289 if (nbd_negotiate_send_rep_list(client->ioc, exp)) {
32d7d2e0
HB
290 return -EINVAL;
291 }
292 }
293 /* Finish with a NBD_REP_ACK. */
1c778ef7 294 return nbd_negotiate_send_rep(client->ioc, NBD_REP_ACK, NBD_OPT_LIST);
32d7d2e0
HB
295}
296
1a6245a5 297static int nbd_negotiate_handle_export_name(NBDClient *client, uint32_t length)
f5076b5a 298{
1c778ef7 299 int rc = -EINVAL;
943cec86 300 char name[NBD_MAX_NAME_SIZE + 1];
6b8c01e7 301
f5076b5a
HB
302 /* Client sends:
303 [20 .. xx] export name (length bytes)
304 */
6b8c01e7 305 TRACE("Checking length");
943cec86 306 if (length >= sizeof(name)) {
6b8c01e7
PB
307 LOG("Bad length received");
308 goto fail;
309 }
1c778ef7 310 if (nbd_negotiate_read(client->ioc, name, length) != length) {
6b8c01e7
PB
311 LOG("read failed");
312 goto fail;
313 }
314 name[length] = '\0';
315
9344e5f5
DB
316 TRACE("Client requested export '%s'", name);
317
6b8c01e7
PB
318 client->exp = nbd_export_find(name);
319 if (!client->exp) {
320 LOG("export not found");
321 goto fail;
322 }
323
324 QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
325 nbd_export_get(client->exp);
6b8c01e7
PB
326 rc = 0;
327fail:
328 return rc;
329}
330
f95910fe
DB
331
332static QIOChannel *nbd_negotiate_handle_starttls(NBDClient *client,
333 uint32_t length)
334{
335 QIOChannel *ioc;
336 QIOChannelTLS *tioc;
337 struct NBDTLSHandshakeData data = { 0 };
338
339 TRACE("Setting up TLS");
340 ioc = client->ioc;
341 if (length) {
342 if (nbd_negotiate_drop_sync(ioc, length) != length) {
343 return NULL;
344 }
345 nbd_negotiate_send_rep(ioc, NBD_REP_ERR_INVALID, NBD_OPT_STARTTLS);
346 return NULL;
347 }
348
63d5ef86
EB
349 if (nbd_negotiate_send_rep(client->ioc, NBD_REP_ACK,
350 NBD_OPT_STARTTLS) < 0) {
351 return NULL;
352 }
f95910fe
DB
353
354 tioc = qio_channel_tls_new_server(ioc,
355 client->tlscreds,
356 client->tlsaclname,
357 NULL);
358 if (!tioc) {
359 return NULL;
360 }
361
0d73f725 362 qio_channel_set_name(QIO_CHANNEL(tioc), "nbd-server-tls");
f95910fe
DB
363 TRACE("Starting TLS handshake");
364 data.loop = g_main_loop_new(g_main_context_default(), FALSE);
365 qio_channel_tls_handshake(tioc,
366 nbd_tls_handshake,
367 &data,
368 NULL);
369
370 if (!data.complete) {
371 g_main_loop_run(data.loop);
372 }
373 g_main_loop_unref(data.loop);
374 if (data.error) {
375 object_unref(OBJECT(tioc));
376 error_free(data.error);
377 return NULL;
378 }
379
380 return QIO_CHANNEL(tioc);
381}
382
383
1a6245a5 384static int nbd_negotiate_options(NBDClient *client)
f5076b5a 385{
9c122ada 386 uint32_t flags;
26afa868 387 bool fixedNewstyle = false;
9c122ada
HR
388
389 /* Client sends:
390 [ 0 .. 3] client flags
391
392 [ 0 .. 7] NBD_OPTS_MAGIC
393 [ 8 .. 11] NBD option
394 [12 .. 15] Data length
395 ... Rest of request
396
397 [ 0 .. 7] NBD_OPTS_MAGIC
398 [ 8 .. 11] Second NBD option
399 [12 .. 15] Data length
400 ... Rest of request
401 */
402
1c778ef7
DB
403 if (nbd_negotiate_read(client->ioc, &flags, sizeof(flags)) !=
404 sizeof(flags)) {
9c122ada
HR
405 LOG("read failed");
406 return -EIO;
407 }
408 TRACE("Checking client flags");
409 be32_to_cpus(&flags);
26afa868 410 if (flags & NBD_FLAG_C_FIXED_NEWSTYLE) {
2cb34749 411 TRACE("Client supports fixed newstyle handshake");
26afa868
DB
412 fixedNewstyle = true;
413 flags &= ~NBD_FLAG_C_FIXED_NEWSTYLE;
414 }
415 if (flags != 0) {
2cb34749 416 TRACE("Unknown client flags 0x%" PRIx32 " received", flags);
9c122ada
HR
417 return -EIO;
418 }
419
f5076b5a 420 while (1) {
9c122ada 421 int ret;
26afa868 422 uint32_t clientflags, length;
f5076b5a
HB
423 uint64_t magic;
424
1c778ef7
DB
425 if (nbd_negotiate_read(client->ioc, &magic, sizeof(magic)) !=
426 sizeof(magic)) {
f5076b5a
HB
427 LOG("read failed");
428 return -EINVAL;
429 }
430 TRACE("Checking opts magic");
431 if (magic != be64_to_cpu(NBD_OPTS_MAGIC)) {
432 LOG("Bad magic received");
433 return -EINVAL;
434 }
435
26afa868
DB
436 if (nbd_negotiate_read(client->ioc, &clientflags,
437 sizeof(clientflags)) != sizeof(clientflags)) {
f5076b5a
HB
438 LOG("read failed");
439 return -EINVAL;
440 }
26afa868 441 clientflags = be32_to_cpu(clientflags);
f5076b5a 442
1c778ef7
DB
443 if (nbd_negotiate_read(client->ioc, &length, sizeof(length)) !=
444 sizeof(length)) {
f5076b5a
HB
445 LOG("read failed");
446 return -EINVAL;
447 }
448 length = be32_to_cpu(length);
449
2cb34749 450 TRACE("Checking option 0x%" PRIx32, clientflags);
f95910fe
DB
451 if (client->tlscreds &&
452 client->ioc == (QIOChannel *)client->sioc) {
453 QIOChannel *tioc;
454 if (!fixedNewstyle) {
2cb34749 455 TRACE("Unsupported option 0x%" PRIx32, clientflags);
f95910fe
DB
456 return -EINVAL;
457 }
458 switch (clientflags) {
459 case NBD_OPT_STARTTLS:
460 tioc = nbd_negotiate_handle_starttls(client, length);
461 if (!tioc) {
462 return -EIO;
463 }
464 object_unref(OBJECT(client->ioc));
465 client->ioc = QIO_CHANNEL(tioc);
466 break;
467
d1129a8a
EB
468 case NBD_OPT_EXPORT_NAME:
469 /* No way to return an error to client, so drop connection */
470 TRACE("Option 0x%x not permitted before TLS", clientflags);
471 return -EINVAL;
472
f95910fe 473 default:
2cb34749
EB
474 TRACE("Option 0x%" PRIx32 " not permitted before TLS",
475 clientflags);
d1129a8a
EB
476 if (nbd_negotiate_drop_sync(client->ioc, length) != length) {
477 return -EIO;
478 }
63d5ef86
EB
479 ret = nbd_negotiate_send_rep(client->ioc, NBD_REP_ERR_TLS_REQD,
480 clientflags);
481 if (ret < 0) {
482 return ret;
483 }
d1129a8a 484 break;
f95910fe
DB
485 }
486 } else if (fixedNewstyle) {
26afa868
DB
487 switch (clientflags) {
488 case NBD_OPT_LIST:
489 ret = nbd_negotiate_handle_list(client, length);
490 if (ret < 0) {
491 return ret;
492 }
493 break;
494
495 case NBD_OPT_ABORT:
496 return -EINVAL;
497
498 case NBD_OPT_EXPORT_NAME:
499 return nbd_negotiate_handle_export_name(client, length);
500
f95910fe 501 case NBD_OPT_STARTTLS:
d1129a8a
EB
502 if (nbd_negotiate_drop_sync(client->ioc, length) != length) {
503 return -EIO;
504 }
f95910fe
DB
505 if (client->tlscreds) {
506 TRACE("TLS already enabled");
63d5ef86
EB
507 ret = nbd_negotiate_send_rep(client->ioc,
508 NBD_REP_ERR_INVALID,
509 clientflags);
f95910fe
DB
510 } else {
511 TRACE("TLS not configured");
63d5ef86
EB
512 ret = nbd_negotiate_send_rep(client->ioc,
513 NBD_REP_ERR_POLICY,
514 clientflags);
515 }
516 if (ret < 0) {
517 return ret;
f95910fe 518 }
d1129a8a 519 break;
26afa868 520 default:
2cb34749 521 TRACE("Unsupported option 0x%" PRIx32, clientflags);
156f6a10
EB
522 if (nbd_negotiate_drop_sync(client->ioc, length) != length) {
523 return -EIO;
524 }
63d5ef86
EB
525 ret = nbd_negotiate_send_rep(client->ioc, NBD_REP_ERR_UNSUP,
526 clientflags);
527 if (ret < 0) {
528 return ret;
529 }
156f6a10 530 break;
26afa868
DB
531 }
532 } else {
533 /*
534 * If broken new-style we should drop the connection
535 * for anything except NBD_OPT_EXPORT_NAME
536 */
537 switch (clientflags) {
538 case NBD_OPT_EXPORT_NAME:
539 return nbd_negotiate_handle_export_name(client, length);
540
541 default:
2cb34749 542 TRACE("Unsupported option 0x%" PRIx32, clientflags);
26afa868 543 return -EINVAL;
32d7d2e0 544 }
f5076b5a
HB
545 }
546 }
547}
548
1a6245a5
FZ
549typedef struct {
550 NBDClient *client;
551 Coroutine *co;
552} NBDClientNewData;
553
554static coroutine_fn int nbd_negotiate(NBDClientNewData *data)
7a5ca864 555{
1a6245a5 556 NBDClient *client = data->client;
b2e3d87f 557 char buf[8 + 8 + 8 + 128];
185b4338 558 int rc;
7423f417
EB
559 const uint16_t myflags = (NBD_FLAG_HAS_FLAGS | NBD_FLAG_SEND_TRIM |
560 NBD_FLAG_SEND_FLUSH | NBD_FLAG_SEND_FUA);
f95910fe 561 bool oldStyle;
b2e3d87f 562
f95910fe 563 /* Old style negotiation header without options
6b8c01e7
PB
564 [ 0 .. 7] passwd ("NBDMAGIC")
565 [ 8 .. 15] magic (NBD_CLIENT_MAGIC)
b2e3d87f 566 [16 .. 23] size
6b8c01e7 567 [24 .. 25] server flags (0)
5672ee54 568 [26 .. 27] export flags
6b8c01e7
PB
569 [28 .. 151] reserved (0)
570
f95910fe 571 New style negotiation header with options
6b8c01e7
PB
572 [ 0 .. 7] passwd ("NBDMAGIC")
573 [ 8 .. 15] magic (NBD_OPTS_MAGIC)
574 [16 .. 17] server flags (0)
f95910fe 575 ....options sent....
6b8c01e7
PB
576 [18 .. 25] size
577 [26 .. 27] export flags
578 [28 .. 151] reserved (0)
b2e3d87f
NT
579 */
580
1c778ef7 581 qio_channel_set_blocking(client->ioc, false, NULL);
185b4338
PB
582 rc = -EINVAL;
583
b2e3d87f 584 TRACE("Beginning negotiation.");
8ffaaba0 585 memset(buf, 0, sizeof(buf));
b2e3d87f 586 memcpy(buf, "NBDMAGIC", 8);
f95910fe
DB
587
588 oldStyle = client->exp != NULL && !client->tlscreds;
589 if (oldStyle) {
2cb34749
EB
590 TRACE("advertising size %" PRIu64 " and flags %x",
591 client->exp->size, client->exp->nbdflags | myflags);
667ad26f
JS
592 stq_be_p(buf + 8, NBD_CLIENT_MAGIC);
593 stq_be_p(buf + 16, client->exp->size);
594 stw_be_p(buf + 26, client->exp->nbdflags | myflags);
6b8c01e7 595 } else {
667ad26f
JS
596 stq_be_p(buf + 8, NBD_OPTS_MAGIC);
597 stw_be_p(buf + 16, NBD_FLAG_FIXED_NEWSTYLE);
6b8c01e7 598 }
b2e3d87f 599
f95910fe
DB
600 if (oldStyle) {
601 if (client->tlscreds) {
602 TRACE("TLS cannot be enabled with oldstyle protocol");
603 goto fail;
604 }
1c778ef7 605 if (nbd_negotiate_write(client->ioc, buf, sizeof(buf)) != sizeof(buf)) {
6b8c01e7
PB
606 LOG("write failed");
607 goto fail;
608 }
609 } else {
1c778ef7 610 if (nbd_negotiate_write(client->ioc, buf, 18) != 18) {
6b8c01e7
PB
611 LOG("write failed");
612 goto fail;
613 }
1a6245a5 614 rc = nbd_negotiate_options(client);
f5076b5a 615 if (rc != 0) {
6b8c01e7
PB
616 LOG("option negotiation failed");
617 goto fail;
618 }
619
2cb34749
EB
620 TRACE("advertising size %" PRIu64 " and flags %x",
621 client->exp->size, client->exp->nbdflags | myflags);
667ad26f
JS
622 stq_be_p(buf + 18, client->exp->size);
623 stw_be_p(buf + 26, client->exp->nbdflags | myflags);
1c778ef7
DB
624 if (nbd_negotiate_write(client->ioc, buf + 18, sizeof(buf) - 18) !=
625 sizeof(buf) - 18) {
6b8c01e7
PB
626 LOG("write failed");
627 goto fail;
628 }
b2e3d87f
NT
629 }
630
07f35073 631 TRACE("Negotiation succeeded.");
185b4338
PB
632 rc = 0;
633fail:
634 return rc;
7a5ca864
FB
635}
636
1c778ef7 637static ssize_t nbd_receive_request(QIOChannel *ioc, struct nbd_request *request)
75818250 638{
fa26c26b 639 uint8_t buf[NBD_REQUEST_SIZE];
b2e3d87f 640 uint32_t magic;
185b4338 641 ssize_t ret;
b2e3d87f 642
1c778ef7 643 ret = read_sync(ioc, buf, sizeof(buf));
185b4338
PB
644 if (ret < 0) {
645 return ret;
646 }
647
648 if (ret != sizeof(buf)) {
b2e3d87f 649 LOG("read failed");
185b4338 650 return -EINVAL;
b2e3d87f
NT
651 }
652
653 /* Request
654 [ 0 .. 3] magic (NBD_REQUEST_MAGIC)
655 [ 4 .. 7] type (0 == READ, 1 == WRITE)
656 [ 8 .. 15] handle
657 [16 .. 23] from
658 [24 .. 27] len
659 */
660
773dce3c
PM
661 magic = ldl_be_p(buf);
662 request->type = ldl_be_p(buf + 4);
663 request->handle = ldq_be_p(buf + 8);
664 request->from = ldq_be_p(buf + 16);
665 request->len = ldl_be_p(buf + 24);
b2e3d87f 666
2cb34749
EB
667 TRACE("Got request: { magic = 0x%" PRIx32 ", .type = %" PRIx32
668 ", from = %" PRIu64 " , len = %" PRIu32 " }",
b2e3d87f
NT
669 magic, request->type, request->from, request->len);
670
671 if (magic != NBD_REQUEST_MAGIC) {
2cb34749 672 LOG("invalid magic (got 0x%" PRIx32 ")", magic);
185b4338 673 return -EINVAL;
b2e3d87f
NT
674 }
675 return 0;
75818250
TS
676}
677
1c778ef7 678static ssize_t nbd_send_reply(QIOChannel *ioc, struct nbd_reply *reply)
75818250 679{
fa26c26b 680 uint8_t buf[NBD_REPLY_SIZE];
185b4338 681 ssize_t ret;
b2e3d87f 682
ca441480
PB
683 reply->error = system_errno_to_nbd_errno(reply->error);
684
2cb34749
EB
685 TRACE("Sending response to client: { .error = %" PRId32
686 ", handle = %" PRIu64 " }",
7548fe31
EB
687 reply->error, reply->handle);
688
b2e3d87f
NT
689 /* Reply
690 [ 0 .. 3] magic (NBD_REPLY_MAGIC)
691 [ 4 .. 7] error (0 == no error)
692 [ 7 .. 15] handle
693 */
667ad26f
JS
694 stl_be_p(buf, NBD_REPLY_MAGIC);
695 stl_be_p(buf + 4, reply->error);
696 stq_be_p(buf + 8, reply->handle);
b2e3d87f 697
1c778ef7 698 ret = write_sync(ioc, buf, sizeof(buf));
185b4338
PB
699 if (ret < 0) {
700 return ret;
701 }
702
703 if (ret != sizeof(buf)) {
b2e3d87f 704 LOG("writing to socket failed");
185b4338 705 return -EINVAL;
b2e3d87f
NT
706 }
707 return 0;
75818250 708}
7a5ca864 709
41996e38
PB
710#define MAX_NBD_REQUESTS 16
711
ce33967a 712void nbd_client_get(NBDClient *client)
1743b515
PB
713{
714 client->refcount++;
715}
716
ce33967a 717void nbd_client_put(NBDClient *client)
1743b515
PB
718{
719 if (--client->refcount == 0) {
ff2b68aa 720 /* The last reference should be dropped by client->close,
f53a829b 721 * which is called by client_close.
ff2b68aa
PB
722 */
723 assert(client->closing);
724
958c717d 725 nbd_unset_handlers(client);
1c778ef7
DB
726 object_unref(OBJECT(client->sioc));
727 object_unref(OBJECT(client->ioc));
f95910fe
DB
728 if (client->tlscreds) {
729 object_unref(OBJECT(client->tlscreds));
730 }
731 g_free(client->tlsaclname);
6b8c01e7
PB
732 if (client->exp) {
733 QTAILQ_REMOVE(&client->exp->clients, client, next);
734 nbd_export_put(client->exp);
735 }
1743b515
PB
736 g_free(client);
737 }
738}
739
f53a829b 740static void client_close(NBDClient *client)
1743b515 741{
ff2b68aa
PB
742 if (client->closing) {
743 return;
744 }
745
746 client->closing = true;
747
748 /* Force requests to finish. They will drop their own references,
749 * then we'll close the socket and free the NBDClient.
750 */
1c778ef7
DB
751 qio_channel_shutdown(client->ioc, QIO_CHANNEL_SHUTDOWN_BOTH,
752 NULL);
ff2b68aa
PB
753
754 /* Also tell the client, so that they release their reference. */
1743b515
PB
755 if (client->close) {
756 client->close(client);
757 }
1743b515
PB
758}
759
72deddc5 760static NBDRequest *nbd_request_get(NBDClient *client)
d9a73806
PB
761{
762 NBDRequest *req;
72deddc5 763
41996e38
PB
764 assert(client->nb_requests <= MAX_NBD_REQUESTS - 1);
765 client->nb_requests++;
958c717d 766 nbd_update_can_read(client);
41996e38 767
1729404c 768 req = g_new0(NBDRequest, 1);
72deddc5
PB
769 nbd_client_get(client);
770 req->client = client;
d9a73806
PB
771 return req;
772}
773
72deddc5 774static void nbd_request_put(NBDRequest *req)
d9a73806 775{
72deddc5 776 NBDClient *client = req->client;
e1adb27a 777
2d821488
SH
778 if (req->data) {
779 qemu_vfree(req->data);
780 }
1729404c 781 g_free(req);
e1adb27a 782
958c717d
HR
783 client->nb_requests--;
784 nbd_update_can_read(client);
72deddc5 785 nbd_client_put(client);
d9a73806
PB
786}
787
aadf99a7 788static void blk_aio_attached(AioContext *ctx, void *opaque)
f2149281
HR
789{
790 NBDExport *exp = opaque;
791 NBDClient *client;
792
793 TRACE("Export %s: Attaching clients to AIO context %p\n", exp->name, ctx);
794
795 exp->ctx = ctx;
796
797 QTAILQ_FOREACH(client, &exp->clients, next) {
798 nbd_set_handlers(client);
799 }
800}
801
aadf99a7 802static void blk_aio_detach(void *opaque)
f2149281
HR
803{
804 NBDExport *exp = opaque;
805 NBDClient *client;
806
807 TRACE("Export %s: Detaching clients from AIO context %p\n", exp->name, exp->ctx);
808
809 QTAILQ_FOREACH(client, &exp->clients, next) {
810 nbd_unset_handlers(client);
811 }
812
813 exp->ctx = NULL;
814}
815
741cc431
HR
816static void nbd_eject_notifier(Notifier *n, void *data)
817{
818 NBDExport *exp = container_of(n, NBDExport, eject_notifier);
819 nbd_export_close(exp);
820}
821
cd7fca95 822NBDExport *nbd_export_new(BlockDriverState *bs, off_t dev_offset, off_t size,
7423f417 823 uint16_t nbdflags, void (*close)(NBDExport *),
cd7fca95 824 bool writethrough, BlockBackend *on_eject_blk,
98f44bbe 825 Error **errp)
af49bbbe 826{
cd7fca95 827 BlockBackend *blk;
af49bbbe 828 NBDExport *exp = g_malloc0(sizeof(NBDExport));
cd7fca95
KW
829
830 blk = blk_new();
831 blk_insert_bs(blk, bs);
832 blk_set_enable_write_cache(blk, !writethrough);
833
2c8d9f06 834 exp->refcount = 1;
4b9441f6 835 QTAILQ_INIT(&exp->clients);
aadf99a7 836 exp->blk = blk;
af49bbbe
PB
837 exp->dev_offset = dev_offset;
838 exp->nbdflags = nbdflags;
98f44bbe
HR
839 exp->size = size < 0 ? blk_getlength(blk) : size;
840 if (exp->size < 0) {
841 error_setg_errno(errp, -exp->size,
842 "Failed to determine the NBD export's length");
843 goto fail;
844 }
845 exp->size -= exp->size % BDRV_SECTOR_SIZE;
846
0ddf08db 847 exp->close = close;
aadf99a7 848 exp->ctx = blk_get_aio_context(blk);
aadf99a7 849 blk_add_aio_context_notifier(blk, blk_aio_attached, blk_aio_detach, exp);
741cc431 850
cd7fca95
KW
851 if (on_eject_blk) {
852 blk_ref(on_eject_blk);
853 exp->eject_notifier_blk = on_eject_blk;
854 exp->eject_notifier.notify = nbd_eject_notifier;
855 blk_add_remove_bs_notifier(on_eject_blk, &exp->eject_notifier);
856 }
741cc431 857
7ea2d269
AK
858 /*
859 * NBD exports are used for non-shared storage migration. Make sure
04c01a5c 860 * that BDRV_O_INACTIVE is cleared and the image is ready for write
7ea2d269
AK
861 * access since the export could be available before migration handover.
862 */
e5f3e12e 863 aio_context_acquire(exp->ctx);
aadf99a7 864 blk_invalidate_cache(blk, NULL);
e5f3e12e 865 aio_context_release(exp->ctx);
af49bbbe 866 return exp;
98f44bbe
HR
867
868fail:
cd7fca95 869 blk_unref(blk);
98f44bbe
HR
870 g_free(exp);
871 return NULL;
af49bbbe
PB
872}
873
ee0a19ec
PB
874NBDExport *nbd_export_find(const char *name)
875{
876 NBDExport *exp;
877 QTAILQ_FOREACH(exp, &exports, next) {
878 if (strcmp(name, exp->name) == 0) {
879 return exp;
880 }
881 }
882
883 return NULL;
884}
885
886void nbd_export_set_name(NBDExport *exp, const char *name)
887{
888 if (exp->name == name) {
889 return;
890 }
891
892 nbd_export_get(exp);
893 if (exp->name != NULL) {
894 g_free(exp->name);
895 exp->name = NULL;
896 QTAILQ_REMOVE(&exports, exp, next);
897 nbd_export_put(exp);
898 }
899 if (name != NULL) {
900 nbd_export_get(exp);
901 exp->name = g_strdup(name);
902 QTAILQ_INSERT_TAIL(&exports, exp, next);
903 }
904 nbd_export_put(exp);
905}
906
b1a75b33
EB
907void nbd_export_set_description(NBDExport *exp, const char *description)
908{
909 g_free(exp->description);
910 exp->description = g_strdup(description);
911}
912
af49bbbe
PB
913void nbd_export_close(NBDExport *exp)
914{
4b9441f6 915 NBDClient *client, *next;
2c8d9f06 916
4b9441f6
PB
917 nbd_export_get(exp);
918 QTAILQ_FOREACH_SAFE(client, &exp->clients, next, next) {
f53a829b 919 client_close(client);
4b9441f6 920 }
125afda8 921 nbd_export_set_name(exp, NULL);
b1a75b33 922 nbd_export_set_description(exp, NULL);
4b9441f6 923 nbd_export_put(exp);
2c8d9f06
PB
924}
925
926void nbd_export_get(NBDExport *exp)
927{
928 assert(exp->refcount > 0);
929 exp->refcount++;
930}
931
932void nbd_export_put(NBDExport *exp)
933{
934 assert(exp->refcount > 0);
935 if (exp->refcount == 1) {
936 nbd_export_close(exp);
d9a73806
PB
937 }
938
2c8d9f06 939 if (--exp->refcount == 0) {
ee0a19ec 940 assert(exp->name == NULL);
b1a75b33 941 assert(exp->description == NULL);
ee0a19ec 942
0ddf08db
PB
943 if (exp->close) {
944 exp->close(exp);
945 }
946
d6268348 947 if (exp->blk) {
cd7fca95
KW
948 if (exp->eject_notifier_blk) {
949 notifier_remove(&exp->eject_notifier);
950 blk_unref(exp->eject_notifier_blk);
951 }
d6268348
WC
952 blk_remove_aio_context_notifier(exp->blk, blk_aio_attached,
953 blk_aio_detach, exp);
954 blk_unref(exp->blk);
955 exp->blk = NULL;
956 }
957
2c8d9f06
PB
958 g_free(exp);
959 }
af49bbbe
PB
960}
961
e140177d 962BlockBackend *nbd_export_get_blockdev(NBDExport *exp)
125afda8 963{
aadf99a7 964 return exp->blk;
125afda8
PB
965}
966
ee0a19ec
PB
967void nbd_export_close_all(void)
968{
969 NBDExport *exp, *next;
970
971 QTAILQ_FOREACH_SAFE(exp, &exports, next, next) {
972 nbd_export_close(exp);
ee0a19ec
PB
973 }
974}
975
94e7340b
PB
976static ssize_t nbd_co_send_reply(NBDRequest *req, struct nbd_reply *reply,
977 int len)
22045592 978{
72deddc5 979 NBDClient *client = req->client;
94e7340b 980 ssize_t rc, ret;
22045592 981
1c778ef7 982 g_assert(qemu_in_coroutine());
262db388 983 qemu_co_mutex_lock(&client->send_lock);
262db388 984 client->send_coroutine = qemu_coroutine_self();
958c717d 985 nbd_set_handlers(client);
262db388 986
22045592 987 if (!len) {
1c778ef7 988 rc = nbd_send_reply(client->ioc, reply);
22045592 989 } else {
1c778ef7
DB
990 qio_channel_set_cork(client->ioc, true);
991 rc = nbd_send_reply(client->ioc, reply);
fc19f8a0 992 if (rc >= 0) {
1c778ef7 993 ret = write_sync(client->ioc, req->data, len);
22045592 994 if (ret != len) {
185b4338 995 rc = -EIO;
22045592
PB
996 }
997 }
1c778ef7 998 qio_channel_set_cork(client->ioc, false);
22045592 999 }
262db388
PB
1000
1001 client->send_coroutine = NULL;
958c717d 1002 nbd_set_handlers(client);
262db388 1003 qemu_co_mutex_unlock(&client->send_lock);
22045592
PB
1004 return rc;
1005}
1006
29b6c3b3
EB
1007/* Collect a client request. Return 0 if request looks valid, -EAGAIN
1008 * to keep trying the collection, -EIO to drop connection right away,
1009 * and any other negative value to report an error to the client
1010 * (although the caller may still need to disconnect after reporting
1011 * the error). */
1012static ssize_t nbd_co_receive_request(NBDRequest *req,
1013 struct nbd_request *request)
a030b347 1014{
72deddc5 1015 NBDClient *client = req->client;
2d821488 1016 uint32_t command;
94e7340b 1017 ssize_t rc;
a030b347 1018
1c778ef7 1019 g_assert(qemu_in_coroutine());
262db388 1020 client->recv_coroutine = qemu_coroutine_self();
958c717d
HR
1021 nbd_update_can_read(client);
1022
1c778ef7 1023 rc = nbd_receive_request(client->ioc, request);
7fe7b68b
PB
1024 if (rc < 0) {
1025 if (rc != -EAGAIN) {
1026 rc = -EIO;
1027 }
a030b347
PB
1028 goto out;
1029 }
1030
29b6c3b3
EB
1031 TRACE("Decoding type");
1032
1033 command = request->type & NBD_CMD_MASK_COMMAND;
1034 if (command != NBD_CMD_WRITE) {
1035 /* No payload, we are ready to read the next request. */
1036 req->complete = true;
1037 }
1038
1039 if (command == NBD_CMD_DISC) {
1040 /* Special case: we're going to disconnect without a reply,
1041 * whether or not flags, from, or len are bogus */
1042 TRACE("Request type is DISCONNECT");
1043 rc = -EIO;
1044 goto out;
1045 }
1046
1047 /* Check for sanity in the parameters, part 1. Defer as many
1048 * checks as possible until after reading any NBD_CMD_WRITE
1049 * payload, so we can try and keep the connection alive. */
a030b347 1050 if ((request->from + request->len) < request->from) {
29b6c3b3 1051 LOG("integer overflow detected, you're probably being attacked");
a030b347
PB
1052 rc = -EINVAL;
1053 goto out;
1054 }
1055
2d821488 1056 if (command == NBD_CMD_READ || command == NBD_CMD_WRITE) {
eb38c3b6 1057 if (request->len > NBD_MAX_BUFFER_SIZE) {
2cb34749 1058 LOG("len (%" PRIu32" ) is larger than max len (%u)",
eb38c3b6
PB
1059 request->len, NBD_MAX_BUFFER_SIZE);
1060 rc = -EINVAL;
1061 goto out;
1062 }
1063
f1c17521
PB
1064 req->data = blk_try_blockalign(client->exp->blk, request->len);
1065 if (req->data == NULL) {
1066 rc = -ENOMEM;
1067 goto out;
1068 }
2d821488
SH
1069 }
1070 if (command == NBD_CMD_WRITE) {
2cb34749 1071 TRACE("Reading %" PRIu32 " byte(s)", request->len);
a030b347 1072
1c778ef7 1073 if (read_sync(client->ioc, req->data, request->len) != request->len) {
a030b347
PB
1074 LOG("reading from socket failed");
1075 rc = -EIO;
1076 goto out;
1077 }
29b6c3b3 1078 req->complete = true;
a030b347 1079 }
29b6c3b3
EB
1080
1081 /* Sanity checks, part 2. */
1082 if (request->from + request->len > client->exp->size) {
1083 LOG("operation past EOF; From: %" PRIu64 ", Len: %" PRIu32
1084 ", Size: %" PRIu64, request->from, request->len,
1085 (uint64_t)client->exp->size);
1086 rc = command == NBD_CMD_WRITE ? -ENOSPC : -EINVAL;
1087 goto out;
1088 }
ab7c548e
EB
1089 if (request->type & ~NBD_CMD_MASK_COMMAND & ~NBD_CMD_FLAG_FUA) {
1090 LOG("unsupported flags (got 0x%x)",
1091 request->type & ~NBD_CMD_MASK_COMMAND);
5bee0f47
EB
1092 rc = -EINVAL;
1093 goto out;
ab7c548e 1094 }
29b6c3b3 1095
a030b347
PB
1096 rc = 0;
1097
1098out:
262db388 1099 client->recv_coroutine = NULL;
958c717d
HR
1100 nbd_update_can_read(client);
1101
a030b347
PB
1102 return rc;
1103}
1104
262db388 1105static void nbd_trip(void *opaque)
75818250 1106{
262db388 1107 NBDClient *client = opaque;
1743b515 1108 NBDExport *exp = client->exp;
ff2b68aa 1109 NBDRequest *req;
b2e3d87f
NT
1110 struct nbd_request request;
1111 struct nbd_reply reply;
94e7340b 1112 ssize_t ret;
8c5d1abb 1113 uint32_t command;
a0c30369 1114 int flags;
b2e3d87f
NT
1115
1116 TRACE("Reading request.");
ff2b68aa
PB
1117 if (client->closing) {
1118 return;
1119 }
b2e3d87f 1120
ff2b68aa 1121 req = nbd_request_get(client);
262db388 1122 ret = nbd_co_receive_request(req, &request);
7fe7b68b
PB
1123 if (ret == -EAGAIN) {
1124 goto done;
1125 }
a030b347 1126 if (ret == -EIO) {
d9a73806 1127 goto out;
a030b347 1128 }
b2e3d87f 1129
fae69416
PB
1130 reply.handle = request.handle;
1131 reply.error = 0;
1132
a030b347
PB
1133 if (ret < 0) {
1134 reply.error = -ret;
1135 goto error_reply;
b2e3d87f 1136 }
8c5d1abb 1137 command = request.type & NBD_CMD_MASK_COMMAND;
b2e3d87f 1138
d6268348
WC
1139 if (client->closing) {
1140 /*
1141 * The client may be closed when we are blocked in
1142 * nbd_co_receive_request()
1143 */
1144 goto done;
1145 }
1146
8c5d1abb 1147 switch (command) {
b2e3d87f
NT
1148 case NBD_CMD_READ:
1149 TRACE("Request type is READ");
1150
e25ceb76 1151 if (request.type & NBD_CMD_FLAG_FUA) {
aadf99a7 1152 ret = blk_co_flush(exp->blk);
e25ceb76
PB
1153 if (ret < 0) {
1154 LOG("flush failed");
1155 reply.error = -ret;
1156 goto error_reply;
1157 }
1158 }
1159
df7b97ff
EB
1160 ret = blk_pread(exp->blk, request.from + exp->dev_offset,
1161 req->data, request.len);
adcf6302 1162 if (ret < 0) {
b2e3d87f 1163 LOG("reading from file failed");
adcf6302 1164 reply.error = -ret;
fae69416 1165 goto error_reply;
b2e3d87f 1166 }
b2e3d87f 1167
2cb34749 1168 TRACE("Read %" PRIu32" byte(s)", request.len);
262db388 1169 if (nbd_co_send_reply(req, &reply, request.len) < 0)
d9a73806 1170 goto out;
b2e3d87f
NT
1171 break;
1172 case NBD_CMD_WRITE:
1173 TRACE("Request type is WRITE");
1174
af49bbbe 1175 if (exp->nbdflags & NBD_FLAG_READ_ONLY) {
b2e3d87f 1176 TRACE("Server is read-only, return error");
fae69416
PB
1177 reply.error = EROFS;
1178 goto error_reply;
1179 }
1180
1181 TRACE("Writing to device");
1182
a0c30369
EB
1183 flags = 0;
1184 if (request.type & NBD_CMD_FLAG_FUA) {
1185 flags |= BDRV_REQ_FUA;
1186 }
df7b97ff 1187 ret = blk_pwrite(exp->blk, request.from + exp->dev_offset,
a0c30369 1188 req->data, request.len, flags);
fae69416
PB
1189 if (ret < 0) {
1190 LOG("writing to file failed");
1191 reply.error = -ret;
1192 goto error_reply;
1193 }
b2e3d87f 1194
fc19f8a0 1195 if (nbd_co_send_reply(req, &reply, 0) < 0) {
d9a73806 1196 goto out;
fc19f8a0 1197 }
b2e3d87f 1198 break;
29b6c3b3 1199
b2e3d87f 1200 case NBD_CMD_DISC:
29b6c3b3
EB
1201 /* unreachable, thanks to special case in nbd_co_receive_request() */
1202 abort();
1203
1486d04a
PB
1204 case NBD_CMD_FLUSH:
1205 TRACE("Request type is FLUSH");
1206
aadf99a7 1207 ret = blk_co_flush(exp->blk);
1486d04a
PB
1208 if (ret < 0) {
1209 LOG("flush failed");
1210 reply.error = -ret;
1211 }
fc19f8a0 1212 if (nbd_co_send_reply(req, &reply, 0) < 0) {
d9a73806 1213 goto out;
fc19f8a0 1214 }
7a706633
PB
1215 break;
1216 case NBD_CMD_TRIM:
1217 TRACE("Request type is TRIM");
1c6c4bb7
EB
1218 ret = blk_co_pdiscard(exp->blk, request.from + exp->dev_offset,
1219 request.len);
1220 if (ret < 0) {
1221 LOG("discard failed");
1222 reply.error = -ret;
7a706633 1223 }
fc19f8a0 1224 if (nbd_co_send_reply(req, &reply, 0) < 0) {
d9a73806 1225 goto out;
fc19f8a0 1226 }
1486d04a 1227 break;
b2e3d87f 1228 default:
2cb34749 1229 LOG("invalid request type (%" PRIu32 ") received", request.type);
8b2f0abf 1230 reply.error = EINVAL;
fae69416 1231 error_reply:
29b6c3b3
EB
1232 /* We must disconnect after NBD_CMD_WRITE if we did not
1233 * read the payload.
1234 */
1235 if (nbd_co_send_reply(req, &reply, 0) < 0 || !req->complete) {
d9a73806 1236 goto out;
fc19f8a0 1237 }
fae69416 1238 break;
b2e3d87f
NT
1239 }
1240
1241 TRACE("Request/Reply complete");
1242
7fe7b68b 1243done:
262db388
PB
1244 nbd_request_put(req);
1245 return;
1246
d9a73806 1247out:
72deddc5 1248 nbd_request_put(req);
f53a829b 1249 client_close(client);
7a5ca864 1250}
af49bbbe 1251
1743b515
PB
1252static void nbd_read(void *opaque)
1253{
1254 NBDClient *client = opaque;
1255
262db388 1256 if (client->recv_coroutine) {
0b8b8753 1257 qemu_coroutine_enter(client->recv_coroutine);
262db388 1258 } else {
0b8b8753 1259 qemu_coroutine_enter(qemu_coroutine_create(nbd_trip, client));
1743b515 1260 }
1743b515
PB
1261}
1262
262db388
PB
1263static void nbd_restart_write(void *opaque)
1264{
1265 NBDClient *client = opaque;
1266
0b8b8753 1267 qemu_coroutine_enter(client->send_coroutine);
262db388
PB
1268}
1269
958c717d
HR
1270static void nbd_set_handlers(NBDClient *client)
1271{
1272 if (client->exp && client->exp->ctx) {
1c778ef7 1273 aio_set_fd_handler(client->exp->ctx, client->sioc->fd,
172cc129 1274 true,
958c717d
HR
1275 client->can_read ? nbd_read : NULL,
1276 client->send_coroutine ? nbd_restart_write : NULL,
1277 client);
1278 }
1279}
1280
1281static void nbd_unset_handlers(NBDClient *client)
1282{
1283 if (client->exp && client->exp->ctx) {
1c778ef7 1284 aio_set_fd_handler(client->exp->ctx, client->sioc->fd,
172cc129 1285 true, NULL, NULL, NULL);
958c717d
HR
1286 }
1287}
1288
1289static void nbd_update_can_read(NBDClient *client)
1290{
1291 bool can_read = client->recv_coroutine ||
1292 client->nb_requests < MAX_NBD_REQUESTS;
1293
1294 if (can_read != client->can_read) {
1295 client->can_read = can_read;
1296 nbd_set_handlers(client);
1297
1298 /* There is no need to invoke aio_notify(), since aio_set_fd_handler()
1299 * in nbd_set_handlers() will have taken care of that */
1300 }
1301}
1302
1a6245a5
FZ
1303static coroutine_fn void nbd_co_client_start(void *opaque)
1304{
1305 NBDClientNewData *data = opaque;
1306 NBDClient *client = data->client;
1307 NBDExport *exp = client->exp;
1308
1309 if (exp) {
1310 nbd_export_get(exp);
1311 }
1312 if (nbd_negotiate(data)) {
d3780c2d 1313 client_close(client);
1a6245a5
FZ
1314 goto out;
1315 }
1316 qemu_co_mutex_init(&client->send_lock);
1317 nbd_set_handlers(client);
1318
1319 if (exp) {
1320 QTAILQ_INSERT_TAIL(&exp->clients, client, next);
1321 }
1322out:
1323 g_free(data);
1324}
1325
1c778ef7
DB
1326void nbd_client_new(NBDExport *exp,
1327 QIOChannelSocket *sioc,
f95910fe
DB
1328 QCryptoTLSCreds *tlscreds,
1329 const char *tlsaclname,
1c778ef7 1330 void (*close_fn)(NBDClient *))
af49bbbe 1331{
1743b515 1332 NBDClient *client;
1a6245a5
FZ
1333 NBDClientNewData *data = g_new(NBDClientNewData, 1);
1334
1743b515
PB
1335 client = g_malloc0(sizeof(NBDClient));
1336 client->refcount = 1;
1337 client->exp = exp;
f95910fe
DB
1338 client->tlscreds = tlscreds;
1339 if (tlscreds) {
1340 object_ref(OBJECT(client->tlscreds));
1341 }
1342 client->tlsaclname = g_strdup(tlsaclname);
1c778ef7
DB
1343 client->sioc = sioc;
1344 object_ref(OBJECT(client->sioc));
1345 client->ioc = QIO_CHANNEL(sioc);
1346 object_ref(OBJECT(client->ioc));
958c717d 1347 client->can_read = true;
ee7d7aab 1348 client->close = close_fn;
2c8d9f06 1349
1a6245a5 1350 data->client = client;
0b8b8753
PB
1351 data->co = qemu_coroutine_create(nbd_co_client_start, data);
1352 qemu_coroutine_enter(data->co);
af49bbbe 1353}