]> Git Repo - qemu.git/blob - nbd.c
nbd: inline tcp_socket_incoming_spec into sole caller
[qemu.git] / nbd.c
1 /*
2  *  Copyright (C) 2005  Anthony Liguori <[email protected]>
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
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 #define NBD_REQUEST_SIZE        (4 + 4 + 8 + 8 + 4)
62 #define NBD_REPLY_SIZE          (4 + 4 + 8)
63 #define NBD_REQUEST_MAGIC       0x25609513
64 #define NBD_REPLY_MAGIC         0x67446698
65 #define NBD_OPTS_MAGIC          0x49484156454F5054LL
66 #define NBD_CLIENT_MAGIC        0x0000420281861253LL
67
68 #define NBD_SET_SOCK            _IO(0xab, 0)
69 #define NBD_SET_BLKSIZE         _IO(0xab, 1)
70 #define NBD_SET_SIZE            _IO(0xab, 2)
71 #define NBD_DO_IT               _IO(0xab, 3)
72 #define NBD_CLEAR_SOCK          _IO(0xab, 4)
73 #define NBD_CLEAR_QUE           _IO(0xab, 5)
74 #define NBD_PRINT_DEBUG         _IO(0xab, 6)
75 #define NBD_SET_SIZE_BLOCKS     _IO(0xab, 7)
76 #define NBD_DISCONNECT          _IO(0xab, 8)
77 #define NBD_SET_TIMEOUT         _IO(0xab, 9)
78 #define NBD_SET_FLAGS           _IO(0xab, 10)
79
80 #define NBD_OPT_EXPORT_NAME     (1 << 0)
81
82 /* Definitions for opaque data types */
83
84 typedef struct NBDRequest NBDRequest;
85
86 struct NBDRequest {
87     QSIMPLEQ_ENTRY(NBDRequest) entry;
88     NBDClient *client;
89     uint8_t *data;
90 };
91
92 struct NBDExport {
93     int refcount;
94     void (*close)(NBDExport *exp);
95
96     BlockDriverState *bs;
97     char *name;
98     off_t dev_offset;
99     off_t size;
100     uint32_t nbdflags;
101     QTAILQ_HEAD(, NBDClient) clients;
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_incoming(const char *address, uint16_t port)
203 {
204     char address_and_port[128];
205     Error *local_err = NULL;
206
207     combine_addr(address_and_port, 128, address, port);
208     int fd = inet_listen(address_and_port, NULL, 0, SOCK_STREAM, 0, &local_err);
209
210     if (local_err != NULL) {
211         qerror_report_err(local_err);
212         error_free(local_err);
213     }
214     return fd;
215 }
216
217 int unix_socket_incoming(const char *path)
218 {
219     Error *local_err = NULL;
220     int fd = unix_listen(path, NULL, 0, &local_err);
221
222     if (local_err != NULL) {
223         qerror_report_err(local_err);
224         error_free(local_err);
225     }
226     return fd;
227 }
228
229 int unix_socket_outgoing(const char *path)
230 {
231     Error *local_err = NULL;
232     int fd = unix_connect(path, &local_err);
233
234     if (local_err != NULL) {
235         qerror_report_err(local_err);
236         error_free(local_err);
237     }
238     return fd;
239 }
240
241 /* Basic flow for negotiation
242
243    Server         Client
244    Negotiate
245
246    or
247
248    Server         Client
249    Negotiate #1
250                   Option
251    Negotiate #2
252
253    ----
254
255    followed by
256
257    Server         Client
258                   Request
259    Response
260                   Request
261    Response
262                   ...
263    ...
264                   Request (type == 2)
265
266 */
267
268 static int nbd_receive_options(NBDClient *client)
269 {
270     int csock = client->sock;
271     char name[256];
272     uint32_t tmp, length;
273     uint64_t magic;
274     int rc;
275
276     /* Client sends:
277         [ 0 ..   3]   reserved (0)
278         [ 4 ..  11]   NBD_OPTS_MAGIC
279         [12 ..  15]   NBD_OPT_EXPORT_NAME
280         [16 ..  19]   length
281         [20 ..  xx]   export name (length bytes)
282      */
283
284     rc = -EINVAL;
285     if (read_sync(csock, &tmp, sizeof(tmp)) != sizeof(tmp)) {
286         LOG("read failed");
287         goto fail;
288     }
289     TRACE("Checking reserved");
290     if (tmp != 0) {
291         LOG("Bad reserved received");
292         goto fail;
293     }
294
295     if (read_sync(csock, &magic, sizeof(magic)) != sizeof(magic)) {
296         LOG("read failed");
297         goto fail;
298     }
299     TRACE("Checking reserved");
300     if (magic != be64_to_cpu(NBD_OPTS_MAGIC)) {
301         LOG("Bad magic received");
302         goto fail;
303     }
304
305     if (read_sync(csock, &tmp, sizeof(tmp)) != sizeof(tmp)) {
306         LOG("read failed");
307         goto fail;
308     }
309     TRACE("Checking option");
310     if (tmp != be32_to_cpu(NBD_OPT_EXPORT_NAME)) {
311         LOG("Bad option received");
312         goto fail;
313     }
314
315     if (read_sync(csock, &length, sizeof(length)) != sizeof(length)) {
316         LOG("read failed");
317         goto fail;
318     }
319     TRACE("Checking length");
320     length = be32_to_cpu(length);
321     if (length > 255) {
322         LOG("Bad length received");
323         goto fail;
324     }
325     if (read_sync(csock, name, length) != length) {
326         LOG("read failed");
327         goto fail;
328     }
329     name[length] = '\0';
330
331     client->exp = nbd_export_find(name);
332     if (!client->exp) {
333         LOG("export not found");
334         goto fail;
335     }
336
337     QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
338     nbd_export_get(client->exp);
339
340     TRACE("Option negotiation succeeded.");
341     rc = 0;
342 fail:
343     return rc;
344 }
345
346 static int nbd_send_negotiate(NBDClient *client)
347 {
348     int csock = client->sock;
349     char buf[8 + 8 + 8 + 128];
350     int rc;
351     const int myflags = (NBD_FLAG_HAS_FLAGS | NBD_FLAG_SEND_TRIM |
352                          NBD_FLAG_SEND_FLUSH | NBD_FLAG_SEND_FUA);
353
354     /* Negotiation header without options:
355         [ 0 ..   7]   passwd       ("NBDMAGIC")
356         [ 8 ..  15]   magic        (NBD_CLIENT_MAGIC)
357         [16 ..  23]   size
358         [24 ..  25]   server flags (0)
359         [24 ..  27]   export flags
360         [28 .. 151]   reserved     (0)
361
362        Negotiation header with options, part 1:
363         [ 0 ..   7]   passwd       ("NBDMAGIC")
364         [ 8 ..  15]   magic        (NBD_OPTS_MAGIC)
365         [16 ..  17]   server flags (0)
366
367        part 2 (after options are sent):
368         [18 ..  25]   size
369         [26 ..  27]   export flags
370         [28 .. 151]   reserved     (0)
371      */
372
373     qemu_set_block(csock);
374     rc = -EINVAL;
375
376     TRACE("Beginning negotiation.");
377     memset(buf, 0, sizeof(buf));
378     memcpy(buf, "NBDMAGIC", 8);
379     if (client->exp) {
380         assert ((client->exp->nbdflags & ~65535) == 0);
381         cpu_to_be64w((uint64_t*)(buf + 8), NBD_CLIENT_MAGIC);
382         cpu_to_be64w((uint64_t*)(buf + 16), client->exp->size);
383         cpu_to_be16w((uint16_t*)(buf + 26), client->exp->nbdflags | myflags);
384     } else {
385         cpu_to_be64w((uint64_t*)(buf + 8), NBD_OPTS_MAGIC);
386     }
387
388     if (client->exp) {
389         if (write_sync(csock, buf, sizeof(buf)) != sizeof(buf)) {
390             LOG("write failed");
391             goto fail;
392         }
393     } else {
394         if (write_sync(csock, buf, 18) != 18) {
395             LOG("write failed");
396             goto fail;
397         }
398         rc = nbd_receive_options(client);
399         if (rc < 0) {
400             LOG("option negotiation failed");
401             goto fail;
402         }
403
404         assert ((client->exp->nbdflags & ~65535) == 0);
405         cpu_to_be64w((uint64_t*)(buf + 18), client->exp->size);
406         cpu_to_be16w((uint16_t*)(buf + 26), client->exp->nbdflags | myflags);
407         if (write_sync(csock, buf + 18, sizeof(buf) - 18) != sizeof(buf) - 18) {
408             LOG("write failed");
409             goto fail;
410         }
411     }
412
413     TRACE("Negotiation succeeded.");
414     rc = 0;
415 fail:
416     qemu_set_nonblock(csock);
417     return rc;
418 }
419
420 int nbd_receive_negotiate(int csock, const char *name, uint32_t *flags,
421                           off_t *size, size_t *blocksize)
422 {
423     char buf[256];
424     uint64_t magic, s;
425     uint16_t tmp;
426     int rc;
427
428     TRACE("Receiving negotiation.");
429
430     rc = -EINVAL;
431
432     if (read_sync(csock, buf, 8) != 8) {
433         LOG("read failed");
434         goto fail;
435     }
436
437     buf[8] = '\0';
438     if (strlen(buf) == 0) {
439         LOG("server connection closed");
440         goto fail;
441     }
442
443     TRACE("Magic is %c%c%c%c%c%c%c%c",
444           qemu_isprint(buf[0]) ? buf[0] : '.',
445           qemu_isprint(buf[1]) ? buf[1] : '.',
446           qemu_isprint(buf[2]) ? buf[2] : '.',
447           qemu_isprint(buf[3]) ? buf[3] : '.',
448           qemu_isprint(buf[4]) ? buf[4] : '.',
449           qemu_isprint(buf[5]) ? buf[5] : '.',
450           qemu_isprint(buf[6]) ? buf[6] : '.',
451           qemu_isprint(buf[7]) ? buf[7] : '.');
452
453     if (memcmp(buf, "NBDMAGIC", 8) != 0) {
454         LOG("Invalid magic received");
455         goto fail;
456     }
457
458     if (read_sync(csock, &magic, sizeof(magic)) != sizeof(magic)) {
459         LOG("read failed");
460         goto fail;
461     }
462     magic = be64_to_cpu(magic);
463     TRACE("Magic is 0x%" PRIx64, magic);
464
465     if (name) {
466         uint32_t reserved = 0;
467         uint32_t opt;
468         uint32_t namesize;
469
470         TRACE("Checking magic (opts_magic)");
471         if (magic != NBD_OPTS_MAGIC) {
472             LOG("Bad magic received");
473             goto fail;
474         }
475         if (read_sync(csock, &tmp, sizeof(tmp)) != sizeof(tmp)) {
476             LOG("flags read failed");
477             goto fail;
478         }
479         *flags = be16_to_cpu(tmp) << 16;
480         /* reserved for future use */
481         if (write_sync(csock, &reserved, sizeof(reserved)) !=
482             sizeof(reserved)) {
483             LOG("write failed (reserved)");
484             goto fail;
485         }
486         /* write the export name */
487         magic = cpu_to_be64(magic);
488         if (write_sync(csock, &magic, sizeof(magic)) != sizeof(magic)) {
489             LOG("write failed (magic)");
490             goto fail;
491         }
492         opt = cpu_to_be32(NBD_OPT_EXPORT_NAME);
493         if (write_sync(csock, &opt, sizeof(opt)) != sizeof(opt)) {
494             LOG("write failed (opt)");
495             goto fail;
496         }
497         namesize = cpu_to_be32(strlen(name));
498         if (write_sync(csock, &namesize, sizeof(namesize)) !=
499             sizeof(namesize)) {
500             LOG("write failed (namesize)");
501             goto fail;
502         }
503         if (write_sync(csock, (char*)name, strlen(name)) != strlen(name)) {
504             LOG("write failed (name)");
505             goto fail;
506         }
507     } else {
508         TRACE("Checking magic (cli_magic)");
509
510         if (magic != NBD_CLIENT_MAGIC) {
511             LOG("Bad magic received");
512             goto fail;
513         }
514     }
515
516     if (read_sync(csock, &s, sizeof(s)) != sizeof(s)) {
517         LOG("read failed");
518         goto fail;
519     }
520     *size = be64_to_cpu(s);
521     *blocksize = 1024;
522     TRACE("Size is %" PRIu64, *size);
523
524     if (!name) {
525         if (read_sync(csock, flags, sizeof(*flags)) != sizeof(*flags)) {
526             LOG("read failed (flags)");
527             goto fail;
528         }
529         *flags = be32_to_cpup(flags);
530     } else {
531         if (read_sync(csock, &tmp, sizeof(tmp)) != sizeof(tmp)) {
532             LOG("read failed (tmp)");
533             goto fail;
534         }
535         *flags |= be32_to_cpu(tmp);
536     }
537     if (read_sync(csock, &buf, 124) != 124) {
538         LOG("read failed (buf)");
539         goto fail;
540     }
541     rc = 0;
542
543 fail:
544     return rc;
545 }
546
547 #ifdef __linux__
548 int nbd_init(int fd, int csock, uint32_t flags, off_t size, size_t blocksize)
549 {
550     TRACE("Setting NBD socket");
551
552     if (ioctl(fd, NBD_SET_SOCK, csock) < 0) {
553         int serrno = errno;
554         LOG("Failed to set NBD socket");
555         return -serrno;
556     }
557
558     TRACE("Setting block size to %lu", (unsigned long)blocksize);
559
560     if (ioctl(fd, NBD_SET_BLKSIZE, blocksize) < 0) {
561         int serrno = errno;
562         LOG("Failed setting NBD block size");
563         return -serrno;
564     }
565
566         TRACE("Setting size to %zd block(s)", (size_t)(size / blocksize));
567
568     if (ioctl(fd, NBD_SET_SIZE_BLOCKS, size / blocksize) < 0) {
569         int serrno = errno;
570         LOG("Failed setting size (in blocks)");
571         return -serrno;
572     }
573
574     if (ioctl(fd, NBD_SET_FLAGS, flags) < 0) {
575         if (errno == ENOTTY) {
576             int read_only = (flags & NBD_FLAG_READ_ONLY) != 0;
577             TRACE("Setting readonly attribute");
578
579             if (ioctl(fd, BLKROSET, (unsigned long) &read_only) < 0) {
580                 int serrno = errno;
581                 LOG("Failed setting read-only attribute");
582                 return -serrno;
583             }
584         } else {
585             int serrno = errno;
586             LOG("Failed setting flags");
587             return -serrno;
588         }
589     }
590
591     TRACE("Negotiation ended");
592
593     return 0;
594 }
595
596 int nbd_disconnect(int fd)
597 {
598     ioctl(fd, NBD_CLEAR_QUE);
599     ioctl(fd, NBD_DISCONNECT);
600     ioctl(fd, NBD_CLEAR_SOCK);
601     return 0;
602 }
603
604 int nbd_client(int fd)
605 {
606     int ret;
607     int serrno;
608
609     TRACE("Doing NBD loop");
610
611     ret = ioctl(fd, NBD_DO_IT);
612     if (ret < 0 && errno == EPIPE) {
613         /* NBD_DO_IT normally returns EPIPE when someone has disconnected
614          * the socket via NBD_DISCONNECT.  We do not want to return 1 in
615          * that case.
616          */
617         ret = 0;
618     }
619     serrno = errno;
620
621     TRACE("NBD loop returned %d: %s", ret, strerror(serrno));
622
623     TRACE("Clearing NBD queue");
624     ioctl(fd, NBD_CLEAR_QUE);
625
626     TRACE("Clearing NBD socket");
627     ioctl(fd, NBD_CLEAR_SOCK);
628
629     errno = serrno;
630     return ret;
631 }
632 #else
633 int nbd_init(int fd, int csock, uint32_t flags, off_t size, size_t blocksize)
634 {
635     return -ENOTSUP;
636 }
637
638 int nbd_disconnect(int fd)
639 {
640     return -ENOTSUP;
641 }
642
643 int nbd_client(int fd)
644 {
645     return -ENOTSUP;
646 }
647 #endif
648
649 ssize_t nbd_send_request(int csock, struct nbd_request *request)
650 {
651     uint8_t buf[NBD_REQUEST_SIZE];
652     ssize_t ret;
653
654     cpu_to_be32w((uint32_t*)buf, NBD_REQUEST_MAGIC);
655     cpu_to_be32w((uint32_t*)(buf + 4), request->type);
656     cpu_to_be64w((uint64_t*)(buf + 8), request->handle);
657     cpu_to_be64w((uint64_t*)(buf + 16), request->from);
658     cpu_to_be32w((uint32_t*)(buf + 24), request->len);
659
660     TRACE("Sending request to client: "
661           "{ .from = %" PRIu64", .len = %u, .handle = %" PRIu64", .type=%i}",
662           request->from, request->len, request->handle, request->type);
663
664     ret = write_sync(csock, buf, sizeof(buf));
665     if (ret < 0) {
666         return ret;
667     }
668
669     if (ret != sizeof(buf)) {
670         LOG("writing to socket failed");
671         return -EINVAL;
672     }
673     return 0;
674 }
675
676 static ssize_t nbd_receive_request(int csock, struct nbd_request *request)
677 {
678     uint8_t buf[NBD_REQUEST_SIZE];
679     uint32_t magic;
680     ssize_t ret;
681
682     ret = read_sync(csock, buf, sizeof(buf));
683     if (ret < 0) {
684         return ret;
685     }
686
687     if (ret != sizeof(buf)) {
688         LOG("read failed");
689         return -EINVAL;
690     }
691
692     /* Request
693        [ 0 ..  3]   magic   (NBD_REQUEST_MAGIC)
694        [ 4 ..  7]   type    (0 == READ, 1 == WRITE)
695        [ 8 .. 15]   handle
696        [16 .. 23]   from
697        [24 .. 27]   len
698      */
699
700     magic = be32_to_cpup((uint32_t*)buf);
701     request->type  = be32_to_cpup((uint32_t*)(buf + 4));
702     request->handle = be64_to_cpup((uint64_t*)(buf + 8));
703     request->from  = be64_to_cpup((uint64_t*)(buf + 16));
704     request->len   = be32_to_cpup((uint32_t*)(buf + 24));
705
706     TRACE("Got request: "
707           "{ magic = 0x%x, .type = %d, from = %" PRIu64" , len = %u }",
708           magic, request->type, request->from, request->len);
709
710     if (magic != NBD_REQUEST_MAGIC) {
711         LOG("invalid magic (got 0x%x)", magic);
712         return -EINVAL;
713     }
714     return 0;
715 }
716
717 ssize_t nbd_receive_reply(int csock, struct nbd_reply *reply)
718 {
719     uint8_t buf[NBD_REPLY_SIZE];
720     uint32_t magic;
721     ssize_t ret;
722
723     ret = read_sync(csock, buf, sizeof(buf));
724     if (ret < 0) {
725         return ret;
726     }
727
728     if (ret != sizeof(buf)) {
729         LOG("read failed");
730         return -EINVAL;
731     }
732
733     /* Reply
734        [ 0 ..  3]    magic   (NBD_REPLY_MAGIC)
735        [ 4 ..  7]    error   (0 == no error)
736        [ 7 .. 15]    handle
737      */
738
739     magic = be32_to_cpup((uint32_t*)buf);
740     reply->error  = be32_to_cpup((uint32_t*)(buf + 4));
741     reply->handle = be64_to_cpup((uint64_t*)(buf + 8));
742
743     TRACE("Got reply: "
744           "{ magic = 0x%x, .error = %d, handle = %" PRIu64" }",
745           magic, reply->error, reply->handle);
746
747     if (magic != NBD_REPLY_MAGIC) {
748         LOG("invalid magic (got 0x%x)", magic);
749         return -EINVAL;
750     }
751     return 0;
752 }
753
754 static ssize_t nbd_send_reply(int csock, struct nbd_reply *reply)
755 {
756     uint8_t buf[NBD_REPLY_SIZE];
757     ssize_t ret;
758
759     /* Reply
760        [ 0 ..  3]    magic   (NBD_REPLY_MAGIC)
761        [ 4 ..  7]    error   (0 == no error)
762        [ 7 .. 15]    handle
763      */
764     cpu_to_be32w((uint32_t*)buf, NBD_REPLY_MAGIC);
765     cpu_to_be32w((uint32_t*)(buf + 4), reply->error);
766     cpu_to_be64w((uint64_t*)(buf + 8), reply->handle);
767
768     TRACE("Sending response to client");
769
770     ret = write_sync(csock, buf, sizeof(buf));
771     if (ret < 0) {
772         return ret;
773     }
774
775     if (ret != sizeof(buf)) {
776         LOG("writing to socket failed");
777         return -EINVAL;
778     }
779     return 0;
780 }
781
782 #define MAX_NBD_REQUESTS 16
783
784 void nbd_client_get(NBDClient *client)
785 {
786     client->refcount++;
787 }
788
789 void nbd_client_put(NBDClient *client)
790 {
791     if (--client->refcount == 0) {
792         /* The last reference should be dropped by client->close,
793          * which is called by nbd_client_close.
794          */
795         assert(client->closing);
796
797         qemu_set_fd_handler2(client->sock, NULL, NULL, NULL, NULL);
798         close(client->sock);
799         client->sock = -1;
800         if (client->exp) {
801             QTAILQ_REMOVE(&client->exp->clients, client, next);
802             nbd_export_put(client->exp);
803         }
804         g_free(client);
805     }
806 }
807
808 void nbd_client_close(NBDClient *client)
809 {
810     if (client->closing) {
811         return;
812     }
813
814     client->closing = true;
815
816     /* Force requests to finish.  They will drop their own references,
817      * then we'll close the socket and free the NBDClient.
818      */
819     shutdown(client->sock, 2);
820
821     /* Also tell the client, so that they release their reference.  */
822     if (client->close) {
823         client->close(client);
824     }
825 }
826
827 static NBDRequest *nbd_request_get(NBDClient *client)
828 {
829     NBDRequest *req;
830
831     assert(client->nb_requests <= MAX_NBD_REQUESTS - 1);
832     client->nb_requests++;
833
834     req = g_slice_new0(NBDRequest);
835     nbd_client_get(client);
836     req->client = client;
837     return req;
838 }
839
840 static void nbd_request_put(NBDRequest *req)
841 {
842     NBDClient *client = req->client;
843
844     if (req->data) {
845         qemu_vfree(req->data);
846     }
847     g_slice_free(NBDRequest, req);
848
849     if (client->nb_requests-- == MAX_NBD_REQUESTS) {
850         qemu_notify_event();
851     }
852     nbd_client_put(client);
853 }
854
855 NBDExport *nbd_export_new(BlockDriverState *bs, off_t dev_offset,
856                           off_t size, uint32_t nbdflags,
857                           void (*close)(NBDExport *))
858 {
859     NBDExport *exp = g_malloc0(sizeof(NBDExport));
860     exp->refcount = 1;
861     QTAILQ_INIT(&exp->clients);
862     exp->bs = bs;
863     exp->dev_offset = dev_offset;
864     exp->nbdflags = nbdflags;
865     exp->size = size == -1 ? bdrv_getlength(bs) : size;
866     exp->close = close;
867     bdrv_ref(bs);
868     return exp;
869 }
870
871 NBDExport *nbd_export_find(const char *name)
872 {
873     NBDExport *exp;
874     QTAILQ_FOREACH(exp, &exports, next) {
875         if (strcmp(name, exp->name) == 0) {
876             return exp;
877         }
878     }
879
880     return NULL;
881 }
882
883 void nbd_export_set_name(NBDExport *exp, const char *name)
884 {
885     if (exp->name == name) {
886         return;
887     }
888
889     nbd_export_get(exp);
890     if (exp->name != NULL) {
891         g_free(exp->name);
892         exp->name = NULL;
893         QTAILQ_REMOVE(&exports, exp, next);
894         nbd_export_put(exp);
895     }
896     if (name != NULL) {
897         nbd_export_get(exp);
898         exp->name = g_strdup(name);
899         QTAILQ_INSERT_TAIL(&exports, exp, next);
900     }
901     nbd_export_put(exp);
902 }
903
904 void nbd_export_close(NBDExport *exp)
905 {
906     NBDClient *client, *next;
907
908     nbd_export_get(exp);
909     QTAILQ_FOREACH_SAFE(client, &exp->clients, next, next) {
910         nbd_client_close(client);
911     }
912     nbd_export_set_name(exp, NULL);
913     nbd_export_put(exp);
914     if (exp->bs) {
915         bdrv_unref(exp->bs);
916         exp->bs = NULL;
917     }
918 }
919
920 void nbd_export_get(NBDExport *exp)
921 {
922     assert(exp->refcount > 0);
923     exp->refcount++;
924 }
925
926 void nbd_export_put(NBDExport *exp)
927 {
928     assert(exp->refcount > 0);
929     if (exp->refcount == 1) {
930         nbd_export_close(exp);
931     }
932
933     if (--exp->refcount == 0) {
934         assert(exp->name == NULL);
935
936         if (exp->close) {
937             exp->close(exp);
938         }
939
940         g_free(exp);
941     }
942 }
943
944 BlockDriverState *nbd_export_get_blockdev(NBDExport *exp)
945 {
946     return exp->bs;
947 }
948
949 void nbd_export_close_all(void)
950 {
951     NBDExport *exp, *next;
952
953     QTAILQ_FOREACH_SAFE(exp, &exports, next, next) {
954         nbd_export_close(exp);
955     }
956 }
957
958 static int nbd_can_read(void *opaque);
959 static void nbd_read(void *opaque);
960 static void nbd_restart_write(void *opaque);
961
962 static ssize_t nbd_co_send_reply(NBDRequest *req, struct nbd_reply *reply,
963                                  int len)
964 {
965     NBDClient *client = req->client;
966     int csock = client->sock;
967     ssize_t rc, ret;
968
969     qemu_co_mutex_lock(&client->send_lock);
970     qemu_set_fd_handler2(csock, nbd_can_read, nbd_read,
971                          nbd_restart_write, client);
972     client->send_coroutine = qemu_coroutine_self();
973
974     if (!len) {
975         rc = nbd_send_reply(csock, reply);
976     } else {
977         socket_set_cork(csock, 1);
978         rc = nbd_send_reply(csock, reply);
979         if (rc >= 0) {
980             ret = qemu_co_send(csock, req->data, len);
981             if (ret != len) {
982                 rc = -EIO;
983             }
984         }
985         socket_set_cork(csock, 0);
986     }
987
988     client->send_coroutine = NULL;
989     qemu_set_fd_handler2(csock, nbd_can_read, nbd_read, NULL, client);
990     qemu_co_mutex_unlock(&client->send_lock);
991     return rc;
992 }
993
994 static ssize_t nbd_co_receive_request(NBDRequest *req, struct nbd_request *request)
995 {
996     NBDClient *client = req->client;
997     int csock = client->sock;
998     uint32_t command;
999     ssize_t rc;
1000
1001     client->recv_coroutine = qemu_coroutine_self();
1002     rc = nbd_receive_request(csock, request);
1003     if (rc < 0) {
1004         if (rc != -EAGAIN) {
1005             rc = -EIO;
1006         }
1007         goto out;
1008     }
1009
1010     if (request->len > NBD_MAX_BUFFER_SIZE) {
1011         LOG("len (%u) is larger than max len (%u)",
1012             request->len, NBD_MAX_BUFFER_SIZE);
1013         rc = -EINVAL;
1014         goto out;
1015     }
1016
1017     if ((request->from + request->len) < request->from) {
1018         LOG("integer overflow detected! "
1019             "you're probably being attacked");
1020         rc = -EINVAL;
1021         goto out;
1022     }
1023
1024     TRACE("Decoding type");
1025
1026     command = request->type & NBD_CMD_MASK_COMMAND;
1027     if (command == NBD_CMD_READ || command == NBD_CMD_WRITE) {
1028         req->data = qemu_blockalign(client->exp->bs, request->len);
1029     }
1030     if (command == NBD_CMD_WRITE) {
1031         TRACE("Reading %u byte(s)", request->len);
1032
1033         if (qemu_co_recv(csock, req->data, request->len) != request->len) {
1034             LOG("reading from socket failed");
1035             rc = -EIO;
1036             goto out;
1037         }
1038     }
1039     rc = 0;
1040
1041 out:
1042     client->recv_coroutine = NULL;
1043     return rc;
1044 }
1045
1046 static void nbd_trip(void *opaque)
1047 {
1048     NBDClient *client = opaque;
1049     NBDExport *exp = client->exp;
1050     NBDRequest *req;
1051     struct nbd_request request;
1052     struct nbd_reply reply;
1053     ssize_t ret;
1054
1055     TRACE("Reading request.");
1056     if (client->closing) {
1057         return;
1058     }
1059
1060     req = nbd_request_get(client);
1061     ret = nbd_co_receive_request(req, &request);
1062     if (ret == -EAGAIN) {
1063         goto done;
1064     }
1065     if (ret == -EIO) {
1066         goto out;
1067     }
1068
1069     reply.handle = request.handle;
1070     reply.error = 0;
1071
1072     if (ret < 0) {
1073         reply.error = -ret;
1074         goto error_reply;
1075     }
1076
1077     if ((request.from + request.len) > exp->size) {
1078             LOG("From: %" PRIu64 ", Len: %u, Size: %" PRIu64
1079             ", Offset: %" PRIu64 "\n",
1080                     request.from, request.len,
1081                     (uint64_t)exp->size, (uint64_t)exp->dev_offset);
1082         LOG("requested operation past EOF--bad client?");
1083         goto invalid_request;
1084     }
1085
1086     switch (request.type & NBD_CMD_MASK_COMMAND) {
1087     case NBD_CMD_READ:
1088         TRACE("Request type is READ");
1089
1090         if (request.type & NBD_CMD_FLAG_FUA) {
1091             ret = bdrv_co_flush(exp->bs);
1092             if (ret < 0) {
1093                 LOG("flush failed");
1094                 reply.error = -ret;
1095                 goto error_reply;
1096             }
1097         }
1098
1099         ret = bdrv_read(exp->bs, (request.from + exp->dev_offset) / 512,
1100                         req->data, request.len / 512);
1101         if (ret < 0) {
1102             LOG("reading from file failed");
1103             reply.error = -ret;
1104             goto error_reply;
1105         }
1106
1107         TRACE("Read %u byte(s)", request.len);
1108         if (nbd_co_send_reply(req, &reply, request.len) < 0)
1109             goto out;
1110         break;
1111     case NBD_CMD_WRITE:
1112         TRACE("Request type is WRITE");
1113
1114         if (exp->nbdflags & NBD_FLAG_READ_ONLY) {
1115             TRACE("Server is read-only, return error");
1116             reply.error = EROFS;
1117             goto error_reply;
1118         }
1119
1120         TRACE("Writing to device");
1121
1122         ret = bdrv_write(exp->bs, (request.from + exp->dev_offset) / 512,
1123                          req->data, request.len / 512);
1124         if (ret < 0) {
1125             LOG("writing to file failed");
1126             reply.error = -ret;
1127             goto error_reply;
1128         }
1129
1130         if (request.type & NBD_CMD_FLAG_FUA) {
1131             ret = bdrv_co_flush(exp->bs);
1132             if (ret < 0) {
1133                 LOG("flush failed");
1134                 reply.error = -ret;
1135                 goto error_reply;
1136             }
1137         }
1138
1139         if (nbd_co_send_reply(req, &reply, 0) < 0) {
1140             goto out;
1141         }
1142         break;
1143     case NBD_CMD_DISC:
1144         TRACE("Request type is DISCONNECT");
1145         errno = 0;
1146         goto out;
1147     case NBD_CMD_FLUSH:
1148         TRACE("Request type is FLUSH");
1149
1150         ret = bdrv_co_flush(exp->bs);
1151         if (ret < 0) {
1152             LOG("flush failed");
1153             reply.error = -ret;
1154         }
1155         if (nbd_co_send_reply(req, &reply, 0) < 0) {
1156             goto out;
1157         }
1158         break;
1159     case NBD_CMD_TRIM:
1160         TRACE("Request type is TRIM");
1161         ret = bdrv_co_discard(exp->bs, (request.from + exp->dev_offset) / 512,
1162                               request.len / 512);
1163         if (ret < 0) {
1164             LOG("discard failed");
1165             reply.error = -ret;
1166         }
1167         if (nbd_co_send_reply(req, &reply, 0) < 0) {
1168             goto out;
1169         }
1170         break;
1171     default:
1172         LOG("invalid request type (%u) received", request.type);
1173     invalid_request:
1174         reply.error = -EINVAL;
1175     error_reply:
1176         if (nbd_co_send_reply(req, &reply, 0) < 0) {
1177             goto out;
1178         }
1179         break;
1180     }
1181
1182     TRACE("Request/Reply complete");
1183
1184 done:
1185     nbd_request_put(req);
1186     return;
1187
1188 out:
1189     nbd_request_put(req);
1190     nbd_client_close(client);
1191 }
1192
1193 static int nbd_can_read(void *opaque)
1194 {
1195     NBDClient *client = opaque;
1196
1197     return client->recv_coroutine || client->nb_requests < MAX_NBD_REQUESTS;
1198 }
1199
1200 static void nbd_read(void *opaque)
1201 {
1202     NBDClient *client = opaque;
1203
1204     if (client->recv_coroutine) {
1205         qemu_coroutine_enter(client->recv_coroutine, NULL);
1206     } else {
1207         qemu_coroutine_enter(qemu_coroutine_create(nbd_trip), client);
1208     }
1209 }
1210
1211 static void nbd_restart_write(void *opaque)
1212 {
1213     NBDClient *client = opaque;
1214
1215     qemu_coroutine_enter(client->send_coroutine, NULL);
1216 }
1217
1218 NBDClient *nbd_client_new(NBDExport *exp, int csock,
1219                           void (*close)(NBDClient *))
1220 {
1221     NBDClient *client;
1222     client = g_malloc0(sizeof(NBDClient));
1223     client->refcount = 1;
1224     client->exp = exp;
1225     client->sock = csock;
1226     if (nbd_send_negotiate(client) < 0) {
1227         g_free(client);
1228         return NULL;
1229     }
1230     client->close = close;
1231     qemu_co_mutex_init(&client->send_lock);
1232     qemu_set_fd_handler2(csock, nbd_can_read, nbd_read, NULL, client);
1233
1234     if (exp) {
1235         QTAILQ_INSERT_TAIL(&exp->clients, client, next);
1236         nbd_export_get(exp);
1237     }
1238     return client;
1239 }
This page took 0.132437 seconds and 4 git commands to generate.