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