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