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