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