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