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