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