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