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