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