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