]> git.proxmox.com Git - mirror_qemu.git/blame - nbd.c
nbd: Fix nbd_receive_options()
[mirror_qemu.git] / nbd.c
CommitLineData
75818250 1/*
7a5ca864
FB
2 * Copyright (C) 2005 Anthony Liguori <anthony@codemonkey.ws>
3 *
4 * Network Block Device
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
737e150e 19#include "block/nbd.h"
e140177d 20#include "sysemu/block-backend.h"
7a5ca864 21
737e150e 22#include "block/coroutine.h"
262db388 23
7a5ca864
FB
24#include <errno.h>
25#include <string.h>
03ff3ca3 26#ifndef _WIN32
7a5ca864 27#include <sys/ioctl.h>
03ff3ca3 28#endif
5dc2eec9 29#if defined(__sun__) || defined(__HAIKU__)
7e00eb9b
AL
30#include <sys/ioccom.h>
31#endif
7a5ca864
FB
32#include <ctype.h>
33#include <inttypes.h>
75818250 34
b90fb4b8
PB
35#ifdef __linux__
36#include <linux/fs.h>
37#endif
38
1de7afc9
PB
39#include "qemu/sockets.h"
40#include "qemu/queue.h"
6a1751b7 41#include "qemu/main-loop.h"
03ff3ca3
AL
42
43//#define DEBUG_NBD
44
45#ifdef DEBUG_NBD
75818250 46#define TRACE(msg, ...) do { \
03ff3ca3 47 LOG(msg, ## __VA_ARGS__); \
75818250 48} while(0)
03ff3ca3
AL
49#else
50#define TRACE(msg, ...) \
51 do { } while (0)
52#endif
7a5ca864
FB
53
54#define LOG(msg, ...) do { \
55 fprintf(stderr, "%s:%s():L%d: " msg "\n", \
56 __FILE__, __FUNCTION__, __LINE__, ## __VA_ARGS__); \
57} while(0)
58
f5076b5a
HB
59/* This is all part of the "official" NBD API.
60 *
61 * The most up-to-date documentation is available at:
62 * https://github.com/yoe/nbd/blob/master/doc/proto.txt
63 */
7a5ca864 64
fa26c26b 65#define NBD_REQUEST_SIZE (4 + 4 + 8 + 8 + 4)
b2e3d87f 66#define NBD_REPLY_SIZE (4 + 4 + 8)
7a5ca864
FB
67#define NBD_REQUEST_MAGIC 0x25609513
68#define NBD_REPLY_MAGIC 0x67446698
fa26c26b
PB
69#define NBD_OPTS_MAGIC 0x49484156454F5054LL
70#define NBD_CLIENT_MAGIC 0x0000420281861253LL
f5076b5a 71#define NBD_REP_MAGIC 0x3e889045565a9LL
7a5ca864
FB
72
73#define NBD_SET_SOCK _IO(0xab, 0)
74#define NBD_SET_BLKSIZE _IO(0xab, 1)
75#define NBD_SET_SIZE _IO(0xab, 2)
76#define NBD_DO_IT _IO(0xab, 3)
77#define NBD_CLEAR_SOCK _IO(0xab, 4)
78#define NBD_CLEAR_QUE _IO(0xab, 5)
b2e3d87f
NT
79#define NBD_PRINT_DEBUG _IO(0xab, 6)
80#define NBD_SET_SIZE_BLOCKS _IO(0xab, 7)
7a5ca864 81#define NBD_DISCONNECT _IO(0xab, 8)
bbb74edd
PB
82#define NBD_SET_TIMEOUT _IO(0xab, 9)
83#define NBD_SET_FLAGS _IO(0xab, 10)
7a5ca864 84
f5076b5a
HB
85#define NBD_OPT_EXPORT_NAME (1)
86#define NBD_OPT_ABORT (2)
32d7d2e0 87#define NBD_OPT_LIST (3)
1d45f8b5 88
9a304d29
PB
89/* Definitions for opaque data types */
90
91typedef struct NBDRequest NBDRequest;
92
93struct NBDRequest {
94 QSIMPLEQ_ENTRY(NBDRequest) entry;
95 NBDClient *client;
96 uint8_t *data;
97};
98
99struct NBDExport {
2c8d9f06 100 int refcount;
0ddf08db
PB
101 void (*close)(NBDExport *exp);
102
aadf99a7 103 BlockBackend *blk;
ee0a19ec 104 char *name;
9a304d29
PB
105 off_t dev_offset;
106 off_t size;
107 uint32_t nbdflags;
4b9441f6 108 QTAILQ_HEAD(, NBDClient) clients;
ee0a19ec 109 QTAILQ_ENTRY(NBDExport) next;
958c717d
HR
110
111 AioContext *ctx;
9a304d29
PB
112};
113
ee0a19ec
PB
114static QTAILQ_HEAD(, NBDExport) exports = QTAILQ_HEAD_INITIALIZER(exports);
115
9a304d29
PB
116struct NBDClient {
117 int refcount;
118 void (*close)(NBDClient *client);
119
120 NBDExport *exp;
121 int sock;
122
123 Coroutine *recv_coroutine;
124
125 CoMutex send_lock;
126 Coroutine *send_coroutine;
127
958c717d
HR
128 bool can_read;
129
4b9441f6 130 QTAILQ_ENTRY(NBDClient) next;
9a304d29 131 int nb_requests;
ff2b68aa 132 bool closing;
9a304d29
PB
133};
134
7a5ca864
FB
135/* That's all folks */
136
958c717d
HR
137static void nbd_set_handlers(NBDClient *client);
138static void nbd_unset_handlers(NBDClient *client);
139static void nbd_update_can_read(NBDClient *client);
140
185b4338 141ssize_t nbd_wr_sync(int fd, void *buffer, size_t size, bool do_read)
7a5ca864
FB
142{
143 size_t offset = 0;
185b4338 144 int err;
7a5ca864 145
ae255e52
PB
146 if (qemu_in_coroutine()) {
147 if (do_read) {
148 return qemu_co_recv(fd, buffer, size);
149 } else {
150 return qemu_co_send(fd, buffer, size);
151 }
152 }
153
7a5ca864
FB
154 while (offset < size) {
155 ssize_t len;
156
157 if (do_read) {
00aa0040 158 len = qemu_recv(fd, buffer + offset, size - offset, 0);
7a5ca864 159 } else {
03ff3ca3 160 len = send(fd, buffer + offset, size - offset, 0);
7a5ca864
FB
161 }
162
fc19f8a0 163 if (len < 0) {
185b4338 164 err = socket_error();
03ff3ca3 165
fc19f8a0 166 /* recoverable error */
79d9b656 167 if (err == EINTR || (offset > 0 && (err == EAGAIN || err == EWOULDBLOCK))) {
fc19f8a0
PB
168 continue;
169 }
170
171 /* unrecoverable error */
185b4338 172 return -err;
7a5ca864
FB
173 }
174
175 /* eof */
176 if (len == 0) {
177 break;
178 }
179
7a5ca864
FB
180 offset += len;
181 }
182
183 return offset;
184}
185
7fe7b68b
PB
186static ssize_t read_sync(int fd, void *buffer, size_t size)
187{
188 /* Sockets are kept in blocking mode in the negotiation phase. After
189 * that, a non-readable socket simply means that another thread stole
190 * our request/reply. Synchronization is done with recv_coroutine, so
191 * that this is coroutine-safe.
192 */
193 return nbd_wr_sync(fd, buffer, size, true);
194}
195
196static ssize_t write_sync(int fd, void *buffer, size_t size)
197{
198 int ret;
199 do {
200 /* For writes, we do expect the socket to be writable. */
201 ret = nbd_wr_sync(fd, buffer, size, false);
202 } while (ret == -EAGAIN);
203 return ret;
204}
205
6b8c01e7 206/* Basic flow for negotiation
7a5ca864
FB
207
208 Server Client
7a5ca864 209 Negotiate
6b8c01e7
PB
210
211 or
212
213 Server Client
214 Negotiate #1
215 Option
216 Negotiate #2
217
218 ----
219
220 followed by
221
222 Server Client
7a5ca864
FB
223 Request
224 Response
225 Request
226 Response
227 ...
228 ...
229 Request (type == 2)
6b8c01e7 230
7a5ca864
FB
231*/
232
f5076b5a 233static int nbd_send_rep(int csock, uint32_t type, uint32_t opt)
6b8c01e7 234{
6b8c01e7 235 uint64_t magic;
f5076b5a 236 uint32_t len;
6b8c01e7 237
f5076b5a
HB
238 magic = cpu_to_be64(NBD_REP_MAGIC);
239 if (write_sync(csock, &magic, sizeof(magic)) != sizeof(magic)) {
240 LOG("write failed (rep magic)");
241 return -EINVAL;
6b8c01e7 242 }
f5076b5a
HB
243 opt = cpu_to_be32(opt);
244 if (write_sync(csock, &opt, sizeof(opt)) != sizeof(opt)) {
245 LOG("write failed (rep opt)");
246 return -EINVAL;
6b8c01e7 247 }
f5076b5a
HB
248 type = cpu_to_be32(type);
249 if (write_sync(csock, &type, sizeof(type)) != sizeof(type)) {
250 LOG("write failed (rep type)");
251 return -EINVAL;
6b8c01e7 252 }
f5076b5a
HB
253 len = cpu_to_be32(0);
254 if (write_sync(csock, &len, sizeof(len)) != sizeof(len)) {
255 LOG("write failed (rep data length)");
256 return -EINVAL;
6b8c01e7 257 }
f5076b5a
HB
258 return 0;
259}
6b8c01e7 260
32d7d2e0
HB
261static int nbd_send_rep_list(int csock, NBDExport *exp)
262{
263 uint64_t magic, name_len;
264 uint32_t opt, type, len;
265
266 name_len = strlen(exp->name);
267 magic = cpu_to_be64(NBD_REP_MAGIC);
268 if (write_sync(csock, &magic, sizeof(magic)) != sizeof(magic)) {
269 LOG("write failed (magic)");
270 return -EINVAL;
271 }
272 opt = cpu_to_be32(NBD_OPT_LIST);
273 if (write_sync(csock, &opt, sizeof(opt)) != sizeof(opt)) {
274 LOG("write failed (opt)");
275 return -EINVAL;
276 }
277 type = cpu_to_be32(NBD_REP_SERVER);
278 if (write_sync(csock, &type, sizeof(type)) != sizeof(type)) {
279 LOG("write failed (reply type)");
280 return -EINVAL;
281 }
282 len = cpu_to_be32(name_len + sizeof(len));
283 if (write_sync(csock, &len, sizeof(len)) != sizeof(len)) {
284 LOG("write failed (length)");
285 return -EINVAL;
286 }
287 len = cpu_to_be32(name_len);
288 if (write_sync(csock, &len, sizeof(len)) != sizeof(len)) {
289 LOG("write failed (length)");
290 return -EINVAL;
291 }
292 if (write_sync(csock, exp->name, name_len) != name_len) {
293 LOG("write failed (buffer)");
294 return -EINVAL;
295 }
296 return 0;
297}
298
299static int nbd_handle_list(NBDClient *client, uint32_t length)
300{
301 int csock;
302 NBDExport *exp;
303
304 csock = client->sock;
305 if (length) {
306 return nbd_send_rep(csock, NBD_REP_ERR_INVALID, NBD_OPT_LIST);
307 }
308
309 /* For each export, send a NBD_REP_SERVER reply. */
310 QTAILQ_FOREACH(exp, &exports, next) {
311 if (nbd_send_rep_list(csock, exp)) {
312 return -EINVAL;
313 }
314 }
315 /* Finish with a NBD_REP_ACK. */
316 return nbd_send_rep(csock, NBD_REP_ACK, NBD_OPT_LIST);
317}
318
f5076b5a
HB
319static int nbd_handle_export_name(NBDClient *client, uint32_t length)
320{
321 int rc = -EINVAL, csock = client->sock;
322 char name[256];
6b8c01e7 323
f5076b5a
HB
324 /* Client sends:
325 [20 .. xx] export name (length bytes)
326 */
6b8c01e7 327 TRACE("Checking length");
6b8c01e7
PB
328 if (length > 255) {
329 LOG("Bad length received");
330 goto fail;
331 }
332 if (read_sync(csock, name, length) != length) {
333 LOG("read failed");
334 goto fail;
335 }
336 name[length] = '\0';
337
338 client->exp = nbd_export_find(name);
339 if (!client->exp) {
340 LOG("export not found");
341 goto fail;
342 }
343
344 QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
345 nbd_export_get(client->exp);
6b8c01e7
PB
346 rc = 0;
347fail:
348 return rc;
349}
350
f5076b5a
HB
351static int nbd_receive_options(NBDClient *client)
352{
9c122ada
HR
353 int csock = client->sock;
354 uint32_t flags;
355
356 /* Client sends:
357 [ 0 .. 3] client flags
358
359 [ 0 .. 7] NBD_OPTS_MAGIC
360 [ 8 .. 11] NBD option
361 [12 .. 15] Data length
362 ... Rest of request
363
364 [ 0 .. 7] NBD_OPTS_MAGIC
365 [ 8 .. 11] Second NBD option
366 [12 .. 15] Data length
367 ... Rest of request
368 */
369
370 if (read_sync(csock, &flags, sizeof(flags)) != sizeof(flags)) {
371 LOG("read failed");
372 return -EIO;
373 }
374 TRACE("Checking client flags");
375 be32_to_cpus(&flags);
376 if (flags != 0 && flags != NBD_FLAG_C_FIXED_NEWSTYLE) {
377 LOG("Bad client flags received");
378 return -EIO;
379 }
380
f5076b5a 381 while (1) {
9c122ada 382 int ret;
f5076b5a
HB
383 uint32_t tmp, length;
384 uint64_t magic;
385
f5076b5a
HB
386 if (read_sync(csock, &magic, sizeof(magic)) != sizeof(magic)) {
387 LOG("read failed");
388 return -EINVAL;
389 }
390 TRACE("Checking opts magic");
391 if (magic != be64_to_cpu(NBD_OPTS_MAGIC)) {
392 LOG("Bad magic received");
393 return -EINVAL;
394 }
395
396 if (read_sync(csock, &tmp, sizeof(tmp)) != sizeof(tmp)) {
397 LOG("read failed");
398 return -EINVAL;
399 }
400
401 if (read_sync(csock, &length, sizeof(length)) != sizeof(length)) {
402 LOG("read failed");
403 return -EINVAL;
404 }
405 length = be32_to_cpu(length);
406
407 TRACE("Checking option");
408 switch (be32_to_cpu(tmp)) {
32d7d2e0 409 case NBD_OPT_LIST:
892f5a52
HR
410 ret = nbd_handle_list(client, length);
411 if (ret < 0) {
412 return ret;
32d7d2e0
HB
413 }
414 break;
415
f5076b5a
HB
416 case NBD_OPT_ABORT:
417 return -EINVAL;
418
419 case NBD_OPT_EXPORT_NAME:
420 return nbd_handle_export_name(client, length);
421
422 default:
423 tmp = be32_to_cpu(tmp);
424 LOG("Unsupported option 0x%x", tmp);
425 nbd_send_rep(client->sock, NBD_REP_ERR_UNSUP, tmp);
426 return -EINVAL;
427 }
428 }
429}
430
9a304d29 431static int nbd_send_negotiate(NBDClient *client)
7a5ca864 432{
9a304d29 433 int csock = client->sock;
b2e3d87f 434 char buf[8 + 8 + 8 + 128];
185b4338 435 int rc;
6b8c01e7
PB
436 const int myflags = (NBD_FLAG_HAS_FLAGS | NBD_FLAG_SEND_TRIM |
437 NBD_FLAG_SEND_FLUSH | NBD_FLAG_SEND_FUA);
b2e3d87f 438
6b8c01e7
PB
439 /* Negotiation header without options:
440 [ 0 .. 7] passwd ("NBDMAGIC")
441 [ 8 .. 15] magic (NBD_CLIENT_MAGIC)
b2e3d87f 442 [16 .. 23] size
6b8c01e7 443 [24 .. 25] server flags (0)
5672ee54 444 [26 .. 27] export flags
6b8c01e7
PB
445 [28 .. 151] reserved (0)
446
447 Negotiation header with options, part 1:
448 [ 0 .. 7] passwd ("NBDMAGIC")
449 [ 8 .. 15] magic (NBD_OPTS_MAGIC)
450 [16 .. 17] server flags (0)
451
452 part 2 (after options are sent):
453 [18 .. 25] size
454 [26 .. 27] export flags
455 [28 .. 151] reserved (0)
b2e3d87f
NT
456 */
457
f9e8cacc 458 qemu_set_block(csock);
185b4338
PB
459 rc = -EINVAL;
460
b2e3d87f 461 TRACE("Beginning negotiation.");
8ffaaba0 462 memset(buf, 0, sizeof(buf));
b2e3d87f 463 memcpy(buf, "NBDMAGIC", 8);
6b8c01e7
PB
464 if (client->exp) {
465 assert ((client->exp->nbdflags & ~65535) == 0);
466 cpu_to_be64w((uint64_t*)(buf + 8), NBD_CLIENT_MAGIC);
467 cpu_to_be64w((uint64_t*)(buf + 16), client->exp->size);
468 cpu_to_be16w((uint16_t*)(buf + 26), client->exp->nbdflags | myflags);
469 } else {
470 cpu_to_be64w((uint64_t*)(buf + 8), NBD_OPTS_MAGIC);
f5076b5a 471 cpu_to_be16w((uint16_t *)(buf + 16), NBD_FLAG_FIXED_NEWSTYLE);
6b8c01e7 472 }
b2e3d87f 473
6b8c01e7
PB
474 if (client->exp) {
475 if (write_sync(csock, buf, sizeof(buf)) != sizeof(buf)) {
476 LOG("write failed");
477 goto fail;
478 }
479 } else {
480 if (write_sync(csock, buf, 18) != 18) {
481 LOG("write failed");
482 goto fail;
483 }
484 rc = nbd_receive_options(client);
f5076b5a 485 if (rc != 0) {
6b8c01e7
PB
486 LOG("option negotiation failed");
487 goto fail;
488 }
489
490 assert ((client->exp->nbdflags & ~65535) == 0);
491 cpu_to_be64w((uint64_t*)(buf + 18), client->exp->size);
492 cpu_to_be16w((uint16_t*)(buf + 26), client->exp->nbdflags | myflags);
493 if (write_sync(csock, buf + 18, sizeof(buf) - 18) != sizeof(buf) - 18) {
494 LOG("write failed");
495 goto fail;
496 }
b2e3d87f
NT
497 }
498
07f35073 499 TRACE("Negotiation succeeded.");
185b4338
PB
500 rc = 0;
501fail:
f9e8cacc 502 qemu_set_nonblock(csock);
185b4338 503 return rc;
7a5ca864
FB
504}
505
1d45f8b5 506int nbd_receive_negotiate(int csock, const char *name, uint32_t *flags,
3f472659 507 off_t *size, Error **errp)
7a5ca864 508{
b2e3d87f
NT
509 char buf[256];
510 uint64_t magic, s;
511 uint16_t tmp;
185b4338 512 int rc;
b2e3d87f 513
07f35073 514 TRACE("Receiving negotiation.");
b2e3d87f 515
185b4338
PB
516 rc = -EINVAL;
517
b2e3d87f 518 if (read_sync(csock, buf, 8) != 8) {
1ce52846 519 error_setg(errp, "Failed to read data");
185b4338 520 goto fail;
b2e3d87f
NT
521 }
522
523 buf[8] = '\0';
524 if (strlen(buf) == 0) {
1ce52846 525 error_setg(errp, "Server connection closed unexpectedly");
185b4338 526 goto fail;
b2e3d87f
NT
527 }
528
529 TRACE("Magic is %c%c%c%c%c%c%c%c",
530 qemu_isprint(buf[0]) ? buf[0] : '.',
531 qemu_isprint(buf[1]) ? buf[1] : '.',
532 qemu_isprint(buf[2]) ? buf[2] : '.',
533 qemu_isprint(buf[3]) ? buf[3] : '.',
534 qemu_isprint(buf[4]) ? buf[4] : '.',
535 qemu_isprint(buf[5]) ? buf[5] : '.',
536 qemu_isprint(buf[6]) ? buf[6] : '.',
537 qemu_isprint(buf[7]) ? buf[7] : '.');
538
539 if (memcmp(buf, "NBDMAGIC", 8) != 0) {
1ce52846 540 error_setg(errp, "Invalid magic received");
185b4338 541 goto fail;
b2e3d87f
NT
542 }
543
544 if (read_sync(csock, &magic, sizeof(magic)) != sizeof(magic)) {
1ce52846 545 error_setg(errp, "Failed to read magic");
185b4338 546 goto fail;
b2e3d87f
NT
547 }
548 magic = be64_to_cpu(magic);
549 TRACE("Magic is 0x%" PRIx64, magic);
550
551 if (name) {
552 uint32_t reserved = 0;
553 uint32_t opt;
554 uint32_t namesize;
555
556 TRACE("Checking magic (opts_magic)");
fa26c26b 557 if (magic != NBD_OPTS_MAGIC) {
1ce52846
HR
558 if (magic == NBD_CLIENT_MAGIC) {
559 error_setg(errp, "Server does not support export names");
560 } else {
561 error_setg(errp, "Bad magic received");
562 }
185b4338 563 goto fail;
b2e3d87f
NT
564 }
565 if (read_sync(csock, &tmp, sizeof(tmp)) != sizeof(tmp)) {
1ce52846 566 error_setg(errp, "Failed to read server flags");
185b4338 567 goto fail;
b2e3d87f
NT
568 }
569 *flags = be16_to_cpu(tmp) << 16;
570 /* reserved for future use */
571 if (write_sync(csock, &reserved, sizeof(reserved)) !=
572 sizeof(reserved)) {
1ce52846 573 error_setg(errp, "Failed to read reserved field");
185b4338 574 goto fail;
b2e3d87f
NT
575 }
576 /* write the export name */
577 magic = cpu_to_be64(magic);
578 if (write_sync(csock, &magic, sizeof(magic)) != sizeof(magic)) {
1ce52846 579 error_setg(errp, "Failed to send export name magic");
185b4338 580 goto fail;
b2e3d87f
NT
581 }
582 opt = cpu_to_be32(NBD_OPT_EXPORT_NAME);
583 if (write_sync(csock, &opt, sizeof(opt)) != sizeof(opt)) {
1ce52846 584 error_setg(errp, "Failed to send export name option number");
185b4338 585 goto fail;
b2e3d87f
NT
586 }
587 namesize = cpu_to_be32(strlen(name));
588 if (write_sync(csock, &namesize, sizeof(namesize)) !=
589 sizeof(namesize)) {
1ce52846 590 error_setg(errp, "Failed to send export name length");
185b4338 591 goto fail;
b2e3d87f
NT
592 }
593 if (write_sync(csock, (char*)name, strlen(name)) != strlen(name)) {
1ce52846 594 error_setg(errp, "Failed to send export name");
185b4338 595 goto fail;
b2e3d87f
NT
596 }
597 } else {
598 TRACE("Checking magic (cli_magic)");
599
fa26c26b 600 if (magic != NBD_CLIENT_MAGIC) {
1ce52846
HR
601 if (magic == NBD_OPTS_MAGIC) {
602 error_setg(errp, "Server requires an export name");
603 } else {
604 error_setg(errp, "Bad magic received");
605 }
185b4338 606 goto fail;
b2e3d87f
NT
607 }
608 }
609
610 if (read_sync(csock, &s, sizeof(s)) != sizeof(s)) {
1ce52846 611 error_setg(errp, "Failed to read export length");
185b4338 612 goto fail;
b2e3d87f
NT
613 }
614 *size = be64_to_cpu(s);
b2e3d87f
NT
615 TRACE("Size is %" PRIu64, *size);
616
617 if (!name) {
618 if (read_sync(csock, flags, sizeof(*flags)) != sizeof(*flags)) {
1ce52846 619 error_setg(errp, "Failed to read export flags");
185b4338 620 goto fail;
b2e3d87f
NT
621 }
622 *flags = be32_to_cpup(flags);
623 } else {
624 if (read_sync(csock, &tmp, sizeof(tmp)) != sizeof(tmp)) {
1ce52846 625 error_setg(errp, "Failed to read export flags");
185b4338 626 goto fail;
b2e3d87f
NT
627 }
628 *flags |= be32_to_cpu(tmp);
629 }
630 if (read_sync(csock, &buf, 124) != 124) {
1ce52846 631 error_setg(errp, "Failed to read reserved block");
185b4338 632 goto fail;
b2e3d87f 633 }
185b4338
PB
634 rc = 0;
635
636fail:
637 return rc;
cd831bd7 638}
7a5ca864 639
b90fb4b8 640#ifdef __linux__
3f472659 641int nbd_init(int fd, int csock, uint32_t flags, off_t size)
cd831bd7 642{
3e05c785
CL
643 TRACE("Setting NBD socket");
644
fc19f8a0 645 if (ioctl(fd, NBD_SET_SOCK, csock) < 0) {
3e05c785
CL
646 int serrno = errno;
647 LOG("Failed to set NBD socket");
185b4338 648 return -serrno;
3e05c785
CL
649 }
650
3f472659 651 TRACE("Setting block size to %lu", (unsigned long)BDRV_SECTOR_SIZE);
7a5ca864 652
3f472659 653 if (ioctl(fd, NBD_SET_BLKSIZE, (size_t)BDRV_SECTOR_SIZE) < 0) {
b2e3d87f
NT
654 int serrno = errno;
655 LOG("Failed setting NBD block size");
185b4338 656 return -serrno;
b2e3d87f 657 }
7a5ca864 658
3f472659 659 TRACE("Setting size to %zd block(s)", (size_t)(size / BDRV_SECTOR_SIZE));
7a5ca864 660
3f472659 661 if (ioctl(fd, NBD_SET_SIZE_BLOCKS, size / (size_t)BDRV_SECTOR_SIZE) < 0) {
b2e3d87f
NT
662 int serrno = errno;
663 LOG("Failed setting size (in blocks)");
185b4338 664 return -serrno;
b2e3d87f 665 }
7a5ca864 666
c8969ede
PB
667 if (ioctl(fd, NBD_SET_FLAGS, flags) < 0) {
668 if (errno == ENOTTY) {
669 int read_only = (flags & NBD_FLAG_READ_ONLY) != 0;
670 TRACE("Setting readonly attribute");
671
672 if (ioctl(fd, BLKROSET, (unsigned long) &read_only) < 0) {
673 int serrno = errno;
674 LOG("Failed setting read-only attribute");
675 return -serrno;
676 }
677 } else {
b90fb4b8 678 int serrno = errno;
c8969ede 679 LOG("Failed setting flags");
185b4338 680 return -serrno;
b90fb4b8
PB
681 }
682 }
683
b2e3d87f 684 TRACE("Negotiation ended");
7a5ca864 685
b2e3d87f 686 return 0;
7a5ca864
FB
687}
688
689int nbd_disconnect(int fd)
690{
b2e3d87f
NT
691 ioctl(fd, NBD_CLEAR_QUE);
692 ioctl(fd, NBD_DISCONNECT);
693 ioctl(fd, NBD_CLEAR_SOCK);
694 return 0;
7a5ca864
FB
695}
696
0a4eb864 697int nbd_client(int fd)
7a5ca864 698{
b2e3d87f
NT
699 int ret;
700 int serrno;
7a5ca864 701
b2e3d87f 702 TRACE("Doing NBD loop");
7a5ca864 703
b2e3d87f 704 ret = ioctl(fd, NBD_DO_IT);
fc19f8a0 705 if (ret < 0 && errno == EPIPE) {
74624688
PB
706 /* NBD_DO_IT normally returns EPIPE when someone has disconnected
707 * the socket via NBD_DISCONNECT. We do not want to return 1 in
708 * that case.
709 */
710 ret = 0;
711 }
b2e3d87f 712 serrno = errno;
7a5ca864 713
b2e3d87f 714 TRACE("NBD loop returned %d: %s", ret, strerror(serrno));
7a5ca864 715
b2e3d87f
NT
716 TRACE("Clearing NBD queue");
717 ioctl(fd, NBD_CLEAR_QUE);
7a5ca864 718
b2e3d87f
NT
719 TRACE("Clearing NBD socket");
720 ioctl(fd, NBD_CLEAR_SOCK);
7a5ca864 721
b2e3d87f
NT
722 errno = serrno;
723 return ret;
7a5ca864 724}
03ff3ca3 725#else
3f472659 726int nbd_init(int fd, int csock, uint32_t flags, off_t size)
03ff3ca3 727{
185b4338 728 return -ENOTSUP;
03ff3ca3
AL
729}
730
731int nbd_disconnect(int fd)
732{
185b4338 733 return -ENOTSUP;
03ff3ca3
AL
734}
735
0a4eb864 736int nbd_client(int fd)
03ff3ca3 737{
185b4338 738 return -ENOTSUP;
03ff3ca3
AL
739}
740#endif
7a5ca864 741
94e7340b 742ssize_t nbd_send_request(int csock, struct nbd_request *request)
7a5ca864 743{
fa26c26b 744 uint8_t buf[NBD_REQUEST_SIZE];
185b4338 745 ssize_t ret;
b2e3d87f
NT
746
747 cpu_to_be32w((uint32_t*)buf, NBD_REQUEST_MAGIC);
748 cpu_to_be32w((uint32_t*)(buf + 4), request->type);
749 cpu_to_be64w((uint64_t*)(buf + 8), request->handle);
750 cpu_to_be64w((uint64_t*)(buf + 16), request->from);
751 cpu_to_be32w((uint32_t*)(buf + 24), request->len);
75818250 752
b2e3d87f
NT
753 TRACE("Sending request to client: "
754 "{ .from = %" PRIu64", .len = %u, .handle = %" PRIu64", .type=%i}",
755 request->from, request->len, request->handle, request->type);
756
185b4338
PB
757 ret = write_sync(csock, buf, sizeof(buf));
758 if (ret < 0) {
759 return ret;
760 }
761
762 if (ret != sizeof(buf)) {
b2e3d87f 763 LOG("writing to socket failed");
185b4338 764 return -EINVAL;
b2e3d87f
NT
765 }
766 return 0;
767}
75818250 768
94e7340b 769static ssize_t nbd_receive_request(int csock, struct nbd_request *request)
75818250 770{
fa26c26b 771 uint8_t buf[NBD_REQUEST_SIZE];
b2e3d87f 772 uint32_t magic;
185b4338 773 ssize_t ret;
b2e3d87f 774
185b4338
PB
775 ret = read_sync(csock, buf, sizeof(buf));
776 if (ret < 0) {
777 return ret;
778 }
779
780 if (ret != sizeof(buf)) {
b2e3d87f 781 LOG("read failed");
185b4338 782 return -EINVAL;
b2e3d87f
NT
783 }
784
785 /* Request
786 [ 0 .. 3] magic (NBD_REQUEST_MAGIC)
787 [ 4 .. 7] type (0 == READ, 1 == WRITE)
788 [ 8 .. 15] handle
789 [16 .. 23] from
790 [24 .. 27] len
791 */
792
793 magic = be32_to_cpup((uint32_t*)buf);
794 request->type = be32_to_cpup((uint32_t*)(buf + 4));
795 request->handle = be64_to_cpup((uint64_t*)(buf + 8));
796 request->from = be64_to_cpup((uint64_t*)(buf + 16));
797 request->len = be32_to_cpup((uint32_t*)(buf + 24));
798
799 TRACE("Got request: "
800 "{ magic = 0x%x, .type = %d, from = %" PRIu64" , len = %u }",
801 magic, request->type, request->from, request->len);
802
803 if (magic != NBD_REQUEST_MAGIC) {
804 LOG("invalid magic (got 0x%x)", magic);
185b4338 805 return -EINVAL;
b2e3d87f
NT
806 }
807 return 0;
75818250
TS
808}
809
94e7340b 810ssize_t nbd_receive_reply(int csock, struct nbd_reply *reply)
75818250 811{
b2e3d87f
NT
812 uint8_t buf[NBD_REPLY_SIZE];
813 uint32_t magic;
185b4338 814 ssize_t ret;
b2e3d87f 815
185b4338
PB
816 ret = read_sync(csock, buf, sizeof(buf));
817 if (ret < 0) {
818 return ret;
819 }
820
821 if (ret != sizeof(buf)) {
b2e3d87f 822 LOG("read failed");
185b4338 823 return -EINVAL;
b2e3d87f
NT
824 }
825
826 /* Reply
827 [ 0 .. 3] magic (NBD_REPLY_MAGIC)
828 [ 4 .. 7] error (0 == no error)
829 [ 7 .. 15] handle
830 */
831
832 magic = be32_to_cpup((uint32_t*)buf);
833 reply->error = be32_to_cpup((uint32_t*)(buf + 4));
834 reply->handle = be64_to_cpup((uint64_t*)(buf + 8));
835
836 TRACE("Got reply: "
837 "{ magic = 0x%x, .error = %d, handle = %" PRIu64" }",
838 magic, reply->error, reply->handle);
839
840 if (magic != NBD_REPLY_MAGIC) {
841 LOG("invalid magic (got 0x%x)", magic);
185b4338 842 return -EINVAL;
b2e3d87f
NT
843 }
844 return 0;
75818250
TS
845}
846
94e7340b 847static ssize_t nbd_send_reply(int csock, struct nbd_reply *reply)
75818250 848{
fa26c26b 849 uint8_t buf[NBD_REPLY_SIZE];
185b4338 850 ssize_t ret;
b2e3d87f
NT
851
852 /* Reply
853 [ 0 .. 3] magic (NBD_REPLY_MAGIC)
854 [ 4 .. 7] error (0 == no error)
855 [ 7 .. 15] handle
856 */
857 cpu_to_be32w((uint32_t*)buf, NBD_REPLY_MAGIC);
858 cpu_to_be32w((uint32_t*)(buf + 4), reply->error);
859 cpu_to_be64w((uint64_t*)(buf + 8), reply->handle);
860
861 TRACE("Sending response to client");
862
185b4338
PB
863 ret = write_sync(csock, buf, sizeof(buf));
864 if (ret < 0) {
865 return ret;
866 }
867
868 if (ret != sizeof(buf)) {
b2e3d87f 869 LOG("writing to socket failed");
185b4338 870 return -EINVAL;
b2e3d87f
NT
871 }
872 return 0;
75818250 873}
7a5ca864 874
41996e38
PB
875#define MAX_NBD_REQUESTS 16
876
ce33967a 877void nbd_client_get(NBDClient *client)
1743b515
PB
878{
879 client->refcount++;
880}
881
ce33967a 882void nbd_client_put(NBDClient *client)
1743b515
PB
883{
884 if (--client->refcount == 0) {
ff2b68aa 885 /* The last reference should be dropped by client->close,
f53a829b 886 * which is called by client_close.
ff2b68aa
PB
887 */
888 assert(client->closing);
889
958c717d 890 nbd_unset_handlers(client);
ff2b68aa
PB
891 close(client->sock);
892 client->sock = -1;
6b8c01e7
PB
893 if (client->exp) {
894 QTAILQ_REMOVE(&client->exp->clients, client, next);
895 nbd_export_put(client->exp);
896 }
1743b515
PB
897 g_free(client);
898 }
899}
900
f53a829b 901static void client_close(NBDClient *client)
1743b515 902{
ff2b68aa
PB
903 if (client->closing) {
904 return;
905 }
906
907 client->closing = true;
908
909 /* Force requests to finish. They will drop their own references,
910 * then we'll close the socket and free the NBDClient.
911 */
912 shutdown(client->sock, 2);
913
914 /* Also tell the client, so that they release their reference. */
1743b515
PB
915 if (client->close) {
916 client->close(client);
917 }
1743b515
PB
918}
919
72deddc5 920static NBDRequest *nbd_request_get(NBDClient *client)
d9a73806
PB
921{
922 NBDRequest *req;
72deddc5 923
41996e38
PB
924 assert(client->nb_requests <= MAX_NBD_REQUESTS - 1);
925 client->nb_requests++;
958c717d 926 nbd_update_can_read(client);
41996e38 927
e1adb27a 928 req = g_slice_new0(NBDRequest);
72deddc5
PB
929 nbd_client_get(client);
930 req->client = client;
d9a73806
PB
931 return req;
932}
933
72deddc5 934static void nbd_request_put(NBDRequest *req)
d9a73806 935{
72deddc5 936 NBDClient *client = req->client;
e1adb27a 937
2d821488
SH
938 if (req->data) {
939 qemu_vfree(req->data);
940 }
e1adb27a
SH
941 g_slice_free(NBDRequest, req);
942
958c717d
HR
943 client->nb_requests--;
944 nbd_update_can_read(client);
72deddc5 945 nbd_client_put(client);
d9a73806
PB
946}
947
aadf99a7 948static void blk_aio_attached(AioContext *ctx, void *opaque)
f2149281
HR
949{
950 NBDExport *exp = opaque;
951 NBDClient *client;
952
953 TRACE("Export %s: Attaching clients to AIO context %p\n", exp->name, ctx);
954
955 exp->ctx = ctx;
956
957 QTAILQ_FOREACH(client, &exp->clients, next) {
958 nbd_set_handlers(client);
959 }
960}
961
aadf99a7 962static void blk_aio_detach(void *opaque)
f2149281
HR
963{
964 NBDExport *exp = opaque;
965 NBDClient *client;
966
967 TRACE("Export %s: Detaching clients from AIO context %p\n", exp->name, exp->ctx);
968
969 QTAILQ_FOREACH(client, &exp->clients, next) {
970 nbd_unset_handlers(client);
971 }
972
973 exp->ctx = NULL;
974}
975
e140177d 976NBDExport *nbd_export_new(BlockBackend *blk, off_t dev_offset, off_t size,
98f44bbe
HR
977 uint32_t nbdflags, void (*close)(NBDExport *),
978 Error **errp)
af49bbbe
PB
979{
980 NBDExport *exp = g_malloc0(sizeof(NBDExport));
2c8d9f06 981 exp->refcount = 1;
4b9441f6 982 QTAILQ_INIT(&exp->clients);
aadf99a7 983 exp->blk = blk;
af49bbbe
PB
984 exp->dev_offset = dev_offset;
985 exp->nbdflags = nbdflags;
98f44bbe
HR
986 exp->size = size < 0 ? blk_getlength(blk) : size;
987 if (exp->size < 0) {
988 error_setg_errno(errp, -exp->size,
989 "Failed to determine the NBD export's length");
990 goto fail;
991 }
992 exp->size -= exp->size % BDRV_SECTOR_SIZE;
993
0ddf08db 994 exp->close = close;
aadf99a7
HR
995 exp->ctx = blk_get_aio_context(blk);
996 blk_ref(blk);
997 blk_add_aio_context_notifier(blk, blk_aio_attached, blk_aio_detach, exp);
7ea2d269
AK
998 /*
999 * NBD exports are used for non-shared storage migration. Make sure
1000 * that BDRV_O_INCOMING is cleared and the image is ready for write
1001 * access since the export could be available before migration handover.
1002 */
aadf99a7 1003 blk_invalidate_cache(blk, NULL);
af49bbbe 1004 return exp;
98f44bbe
HR
1005
1006fail:
1007 g_free(exp);
1008 return NULL;
af49bbbe
PB
1009}
1010
ee0a19ec
PB
1011NBDExport *nbd_export_find(const char *name)
1012{
1013 NBDExport *exp;
1014 QTAILQ_FOREACH(exp, &exports, next) {
1015 if (strcmp(name, exp->name) == 0) {
1016 return exp;
1017 }
1018 }
1019
1020 return NULL;
1021}
1022
1023void nbd_export_set_name(NBDExport *exp, const char *name)
1024{
1025 if (exp->name == name) {
1026 return;
1027 }
1028
1029 nbd_export_get(exp);
1030 if (exp->name != NULL) {
1031 g_free(exp->name);
1032 exp->name = NULL;
1033 QTAILQ_REMOVE(&exports, exp, next);
1034 nbd_export_put(exp);
1035 }
1036 if (name != NULL) {
1037 nbd_export_get(exp);
1038 exp->name = g_strdup(name);
1039 QTAILQ_INSERT_TAIL(&exports, exp, next);
1040 }
1041 nbd_export_put(exp);
1042}
1043
af49bbbe
PB
1044void nbd_export_close(NBDExport *exp)
1045{
4b9441f6 1046 NBDClient *client, *next;
2c8d9f06 1047
4b9441f6
PB
1048 nbd_export_get(exp);
1049 QTAILQ_FOREACH_SAFE(client, &exp->clients, next, next) {
f53a829b 1050 client_close(client);
4b9441f6 1051 }
125afda8 1052 nbd_export_set_name(exp, NULL);
4b9441f6 1053 nbd_export_put(exp);
aadf99a7
HR
1054 if (exp->blk) {
1055 blk_remove_aio_context_notifier(exp->blk, blk_aio_attached,
1056 blk_aio_detach, exp);
1057 blk_unref(exp->blk);
1058 exp->blk = NULL;
38b54b6d 1059 }
2c8d9f06
PB
1060}
1061
1062void nbd_export_get(NBDExport *exp)
1063{
1064 assert(exp->refcount > 0);
1065 exp->refcount++;
1066}
1067
1068void nbd_export_put(NBDExport *exp)
1069{
1070 assert(exp->refcount > 0);
1071 if (exp->refcount == 1) {
1072 nbd_export_close(exp);
d9a73806
PB
1073 }
1074
2c8d9f06 1075 if (--exp->refcount == 0) {
ee0a19ec
PB
1076 assert(exp->name == NULL);
1077
0ddf08db
PB
1078 if (exp->close) {
1079 exp->close(exp);
1080 }
1081
2c8d9f06
PB
1082 g_free(exp);
1083 }
af49bbbe
PB
1084}
1085
e140177d 1086BlockBackend *nbd_export_get_blockdev(NBDExport *exp)
125afda8 1087{
aadf99a7 1088 return exp->blk;
125afda8
PB
1089}
1090
ee0a19ec
PB
1091void nbd_export_close_all(void)
1092{
1093 NBDExport *exp, *next;
1094
1095 QTAILQ_FOREACH_SAFE(exp, &exports, next, next) {
1096 nbd_export_close(exp);
ee0a19ec
PB
1097 }
1098}
1099
94e7340b
PB
1100static ssize_t nbd_co_send_reply(NBDRequest *req, struct nbd_reply *reply,
1101 int len)
22045592 1102{
72deddc5
PB
1103 NBDClient *client = req->client;
1104 int csock = client->sock;
94e7340b 1105 ssize_t rc, ret;
22045592 1106
262db388 1107 qemu_co_mutex_lock(&client->send_lock);
262db388 1108 client->send_coroutine = qemu_coroutine_self();
958c717d 1109 nbd_set_handlers(client);
262db388 1110
22045592
PB
1111 if (!len) {
1112 rc = nbd_send_reply(csock, reply);
22045592
PB
1113 } else {
1114 socket_set_cork(csock, 1);
1115 rc = nbd_send_reply(csock, reply);
fc19f8a0 1116 if (rc >= 0) {
262db388 1117 ret = qemu_co_send(csock, req->data, len);
22045592 1118 if (ret != len) {
185b4338 1119 rc = -EIO;
22045592
PB
1120 }
1121 }
22045592
PB
1122 socket_set_cork(csock, 0);
1123 }
262db388
PB
1124
1125 client->send_coroutine = NULL;
958c717d 1126 nbd_set_handlers(client);
262db388 1127 qemu_co_mutex_unlock(&client->send_lock);
22045592
PB
1128 return rc;
1129}
1130
94e7340b 1131static ssize_t nbd_co_receive_request(NBDRequest *req, struct nbd_request *request)
a030b347 1132{
72deddc5
PB
1133 NBDClient *client = req->client;
1134 int csock = client->sock;
2d821488 1135 uint32_t command;
94e7340b 1136 ssize_t rc;
a030b347 1137
262db388 1138 client->recv_coroutine = qemu_coroutine_self();
958c717d
HR
1139 nbd_update_can_read(client);
1140
7fe7b68b
PB
1141 rc = nbd_receive_request(csock, request);
1142 if (rc < 0) {
1143 if (rc != -EAGAIN) {
1144 rc = -EIO;
1145 }
a030b347
PB
1146 goto out;
1147 }
1148
2d821488 1149 if (request->len > NBD_MAX_BUFFER_SIZE) {
a030b347 1150 LOG("len (%u) is larger than max len (%u)",
2d821488 1151 request->len, NBD_MAX_BUFFER_SIZE);
a030b347
PB
1152 rc = -EINVAL;
1153 goto out;
1154 }
1155
1156 if ((request->from + request->len) < request->from) {
1157 LOG("integer overflow detected! "
1158 "you're probably being attacked");
1159 rc = -EINVAL;
1160 goto out;
1161 }
1162
1163 TRACE("Decoding type");
1164
2d821488
SH
1165 command = request->type & NBD_CMD_MASK_COMMAND;
1166 if (command == NBD_CMD_READ || command == NBD_CMD_WRITE) {
aadf99a7 1167 req->data = blk_blockalign(client->exp->blk, request->len);
2d821488
SH
1168 }
1169 if (command == NBD_CMD_WRITE) {
a030b347
PB
1170 TRACE("Reading %u byte(s)", request->len);
1171
262db388 1172 if (qemu_co_recv(csock, req->data, request->len) != request->len) {
a030b347
PB
1173 LOG("reading from socket failed");
1174 rc = -EIO;
1175 goto out;
1176 }
1177 }
1178 rc = 0;
1179
1180out:
262db388 1181 client->recv_coroutine = NULL;
958c717d
HR
1182 nbd_update_can_read(client);
1183
a030b347
PB
1184 return rc;
1185}
1186
262db388 1187static void nbd_trip(void *opaque)
75818250 1188{
262db388 1189 NBDClient *client = opaque;
1743b515 1190 NBDExport *exp = client->exp;
ff2b68aa 1191 NBDRequest *req;
b2e3d87f
NT
1192 struct nbd_request request;
1193 struct nbd_reply reply;
94e7340b 1194 ssize_t ret;
8c5d1abb 1195 uint32_t command;
b2e3d87f
NT
1196
1197 TRACE("Reading request.");
ff2b68aa
PB
1198 if (client->closing) {
1199 return;
1200 }
b2e3d87f 1201
ff2b68aa 1202 req = nbd_request_get(client);
262db388 1203 ret = nbd_co_receive_request(req, &request);
7fe7b68b
PB
1204 if (ret == -EAGAIN) {
1205 goto done;
1206 }
a030b347 1207 if (ret == -EIO) {
d9a73806 1208 goto out;
a030b347 1209 }
b2e3d87f 1210
fae69416
PB
1211 reply.handle = request.handle;
1212 reply.error = 0;
1213
a030b347
PB
1214 if (ret < 0) {
1215 reply.error = -ret;
1216 goto error_reply;
b2e3d87f 1217 }
8c5d1abb
HB
1218 command = request.type & NBD_CMD_MASK_COMMAND;
1219 if (command != NBD_CMD_DISC && (request.from + request.len) > exp->size) {
b2e3d87f
NT
1220 LOG("From: %" PRIu64 ", Len: %u, Size: %" PRIu64
1221 ", Offset: %" PRIu64 "\n",
af49bbbe 1222 request.from, request.len,
0fee8f34 1223 (uint64_t)exp->size, (uint64_t)exp->dev_offset);
b2e3d87f 1224 LOG("requested operation past EOF--bad client?");
fae69416 1225 goto invalid_request;
b2e3d87f
NT
1226 }
1227
8c5d1abb 1228 switch (command) {
b2e3d87f
NT
1229 case NBD_CMD_READ:
1230 TRACE("Request type is READ");
1231
e25ceb76 1232 if (request.type & NBD_CMD_FLAG_FUA) {
aadf99a7 1233 ret = blk_co_flush(exp->blk);
e25ceb76
PB
1234 if (ret < 0) {
1235 LOG("flush failed");
1236 reply.error = -ret;
1237 goto error_reply;
1238 }
1239 }
1240
aadf99a7
HR
1241 ret = blk_read(exp->blk,
1242 (request.from + exp->dev_offset) / BDRV_SECTOR_SIZE,
1243 req->data, request.len / BDRV_SECTOR_SIZE);
adcf6302 1244 if (ret < 0) {
b2e3d87f 1245 LOG("reading from file failed");
adcf6302 1246 reply.error = -ret;
fae69416 1247 goto error_reply;
b2e3d87f 1248 }
b2e3d87f
NT
1249
1250 TRACE("Read %u byte(s)", request.len);
262db388 1251 if (nbd_co_send_reply(req, &reply, request.len) < 0)
d9a73806 1252 goto out;
b2e3d87f
NT
1253 break;
1254 case NBD_CMD_WRITE:
1255 TRACE("Request type is WRITE");
1256
af49bbbe 1257 if (exp->nbdflags & NBD_FLAG_READ_ONLY) {
b2e3d87f 1258 TRACE("Server is read-only, return error");
fae69416
PB
1259 reply.error = EROFS;
1260 goto error_reply;
1261 }
1262
1263 TRACE("Writing to device");
1264
aadf99a7
HR
1265 ret = blk_write(exp->blk,
1266 (request.from + exp->dev_offset) / BDRV_SECTOR_SIZE,
1267 req->data, request.len / BDRV_SECTOR_SIZE);
fae69416
PB
1268 if (ret < 0) {
1269 LOG("writing to file failed");
1270 reply.error = -ret;
1271 goto error_reply;
1272 }
b2e3d87f 1273
fae69416 1274 if (request.type & NBD_CMD_FLAG_FUA) {
aadf99a7 1275 ret = blk_co_flush(exp->blk);
adcf6302 1276 if (ret < 0) {
fae69416 1277 LOG("flush failed");
adcf6302 1278 reply.error = -ret;
fae69416 1279 goto error_reply;
2c7989a9 1280 }
b2e3d87f
NT
1281 }
1282
fc19f8a0 1283 if (nbd_co_send_reply(req, &reply, 0) < 0) {
d9a73806 1284 goto out;
fc19f8a0 1285 }
b2e3d87f
NT
1286 break;
1287 case NBD_CMD_DISC:
1288 TRACE("Request type is DISCONNECT");
1289 errno = 0;
262db388 1290 goto out;
1486d04a
PB
1291 case NBD_CMD_FLUSH:
1292 TRACE("Request type is FLUSH");
1293
aadf99a7 1294 ret = blk_co_flush(exp->blk);
1486d04a
PB
1295 if (ret < 0) {
1296 LOG("flush failed");
1297 reply.error = -ret;
1298 }
fc19f8a0 1299 if (nbd_co_send_reply(req, &reply, 0) < 0) {
d9a73806 1300 goto out;
fc19f8a0 1301 }
7a706633
PB
1302 break;
1303 case NBD_CMD_TRIM:
1304 TRACE("Request type is TRIM");
aadf99a7
HR
1305 ret = blk_co_discard(exp->blk, (request.from + exp->dev_offset)
1306 / BDRV_SECTOR_SIZE,
1307 request.len / BDRV_SECTOR_SIZE);
7a706633
PB
1308 if (ret < 0) {
1309 LOG("discard failed");
1310 reply.error = -ret;
1311 }
fc19f8a0 1312 if (nbd_co_send_reply(req, &reply, 0) < 0) {
d9a73806 1313 goto out;
fc19f8a0 1314 }
1486d04a 1315 break;
b2e3d87f
NT
1316 default:
1317 LOG("invalid request type (%u) received", request.type);
fae69416 1318 invalid_request:
8b2f0abf 1319 reply.error = EINVAL;
fae69416 1320 error_reply:
fc19f8a0 1321 if (nbd_co_send_reply(req, &reply, 0) < 0) {
d9a73806 1322 goto out;
fc19f8a0 1323 }
fae69416 1324 break;
b2e3d87f
NT
1325 }
1326
1327 TRACE("Request/Reply complete");
1328
7fe7b68b 1329done:
262db388
PB
1330 nbd_request_put(req);
1331 return;
1332
d9a73806 1333out:
72deddc5 1334 nbd_request_put(req);
f53a829b 1335 client_close(client);
7a5ca864 1336}
af49bbbe 1337
1743b515
PB
1338static void nbd_read(void *opaque)
1339{
1340 NBDClient *client = opaque;
1341
262db388
PB
1342 if (client->recv_coroutine) {
1343 qemu_coroutine_enter(client->recv_coroutine, NULL);
1344 } else {
1345 qemu_coroutine_enter(qemu_coroutine_create(nbd_trip), client);
1743b515 1346 }
1743b515
PB
1347}
1348
262db388
PB
1349static void nbd_restart_write(void *opaque)
1350{
1351 NBDClient *client = opaque;
1352
1353 qemu_coroutine_enter(client->send_coroutine, NULL);
1354}
1355
958c717d
HR
1356static void nbd_set_handlers(NBDClient *client)
1357{
1358 if (client->exp && client->exp->ctx) {
1359 aio_set_fd_handler(client->exp->ctx, client->sock,
1360 client->can_read ? nbd_read : NULL,
1361 client->send_coroutine ? nbd_restart_write : NULL,
1362 client);
1363 }
1364}
1365
1366static void nbd_unset_handlers(NBDClient *client)
1367{
1368 if (client->exp && client->exp->ctx) {
1369 aio_set_fd_handler(client->exp->ctx, client->sock, NULL, NULL, NULL);
1370 }
1371}
1372
1373static void nbd_update_can_read(NBDClient *client)
1374{
1375 bool can_read = client->recv_coroutine ||
1376 client->nb_requests < MAX_NBD_REQUESTS;
1377
1378 if (can_read != client->can_read) {
1379 client->can_read = can_read;
1380 nbd_set_handlers(client);
1381
1382 /* There is no need to invoke aio_notify(), since aio_set_fd_handler()
1383 * in nbd_set_handlers() will have taken care of that */
1384 }
1385}
1386
1743b515
PB
1387NBDClient *nbd_client_new(NBDExport *exp, int csock,
1388 void (*close)(NBDClient *))
af49bbbe 1389{
1743b515 1390 NBDClient *client;
1743b515
PB
1391 client = g_malloc0(sizeof(NBDClient));
1392 client->refcount = 1;
1393 client->exp = exp;
1394 client->sock = csock;
958c717d 1395 client->can_read = true;
f5076b5a 1396 if (nbd_send_negotiate(client)) {
9a304d29
PB
1397 g_free(client);
1398 return NULL;
1399 }
1743b515 1400 client->close = close;
262db388 1401 qemu_co_mutex_init(&client->send_lock);
958c717d 1402 nbd_set_handlers(client);
2c8d9f06 1403
6b8c01e7
PB
1404 if (exp) {
1405 QTAILQ_INSERT_TAIL(&exp->clients, client, next);
1406 nbd_export_get(exp);
1407 }
1743b515 1408 return client;
af49bbbe 1409}