master
c 2,235 lines 68 KB
Raw
1 /*
2 * QEMU Block driver for NBD
3 *
4 * Copyright (c) 2019 Virtuozzo International GmbH.
5 * Copyright Red Hat
6 * Copyright (C) 2008 Bull S.A.S.
7 * Author: Laurent Vivier <Laurent.Vivier@bull.net>
8 *
9 * Some parts:
10 * Copyright (C) 2007 Anthony Liguori <anthony@codemonkey.ws>
11 *
12 * Permission is hereby granted, free of charge, to any person obtaining a copy
13 * of this software and associated documentation files (the "Software"), to deal
14 * in the Software without restriction, including without limitation the rights
15 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 * copies of the Software, and to permit persons to whom the Software is
17 * furnished to do so, subject to the following conditions:
18 *
19 * The above copyright notice and this permission notice shall be included in
20 * all copies or substantial portions of the Software.
21 *
22 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
25 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
28 * THE SOFTWARE.
29 */
30
31 #include "qemu/osdep.h"
32
33 #include "trace.h"
34 #include "qemu/option.h"
35 #include "qemu/cutils.h"
36 #include "qemu/main-loop.h"
37
38 #include "qapi/qapi-visit-sockets.h"
39 #include "qobject/qstring.h"
40 #include "qapi/clone-visitor.h"
41
42 #include "block/qdict.h"
43 #include "block/nbd.h"
44 #include "block/block_int.h"
45 #include "block/coroutines.h"
46
47 #include "qemu/yank.h"
48
49 #define EN_OPTSTR ":exportname="
50 #define MAX_NBD_REQUESTS 16
51
52 #define COOKIE_TO_INDEX(cookie) ((cookie) - 1)
53 #define INDEX_TO_COOKIE(index) ((index) + 1)
54
55 typedef struct {
56 Coroutine *coroutine;
57 uint64_t offset; /* original offset of the request */
58 bool receiving; /* sleeping in the yield in nbd_receive_replies */
59 } NBDClientRequest;
60
61 typedef enum NBDClientState {
62 NBD_CLIENT_CONNECTING_WAIT,
63 NBD_CLIENT_CONNECTING_NOWAIT,
64 NBD_CLIENT_CONNECTED,
65 NBD_CLIENT_QUIT
66 } NBDClientState;
67
68 typedef struct BDRVNBDState {
69 QIOChannel *ioc; /* The current I/O channel */
70 NBDExportInfo info;
71
72 /*
73 * Protects state, free_sema, in_flight, requests[].coroutine,
74 * reconnect_delay_timer.
75 */
76 QemuMutex requests_lock;
77 NBDClientState state;
78 CoQueue free_sema;
79 unsigned in_flight;
80 NBDClientRequest requests[MAX_NBD_REQUESTS];
81 QEMUTimer *reconnect_delay_timer;
82
83 /* Protects sending data on the socket. */
84 CoMutex send_mutex;
85
86 /*
87 * Protects receiving reply headers from the socket, as well as the
88 * fields reply and requests[].receiving
89 */
90 CoMutex receive_mutex;
91 NBDReply reply;
92
93 QEMUTimer *open_timer;
94
95 BlockDriverState *bs;
96
97 /* Connection parameters */
98 uint32_t reconnect_delay;
99 uint32_t open_timeout;
100 SocketAddress *saddr;
101 char *export;
102 char *tlscredsid;
103 QCryptoTLSCreds *tlscreds;
104 char *tlshostname;
105 char *x_dirty_bitmap;
106 bool alloc_depth;
107
108 NBDClientConnection *conn;
109 } BDRVNBDState;
110
111 static void nbd_yank(void *opaque);
112
113 static void nbd_clear_bdrvstate(BlockDriverState *bs)
114 {
115 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
116
117 nbd_client_connection_release(s->conn);
118 s->conn = NULL;
119
120 yank_unregister_instance(BLOCKDEV_YANK_INSTANCE(bs->node_name));
121
122 /* Must not leave timers behind that would access freed data */
123 assert(!s->reconnect_delay_timer);
124 assert(!s->open_timer);
125
126 object_unref(OBJECT(s->tlscreds));
127 qapi_free_SocketAddress(s->saddr);
128 s->saddr = NULL;
129 g_free(s->export);
130 s->export = NULL;
131 g_free(s->tlscredsid);
132 s->tlscredsid = NULL;
133 g_free(s->tlshostname);
134 s->tlshostname = NULL;
135 g_free(s->x_dirty_bitmap);
136 s->x_dirty_bitmap = NULL;
137 }
138
139 /* Called with s->receive_mutex taken. */
140 static bool coroutine_fn nbd_recv_coroutine_wake_one(NBDClientRequest *req)
141 {
142 if (req->receiving) {
143 req->receiving = false;
144 aio_co_wake(req->coroutine);
145 return true;
146 }
147
148 return false;
149 }
150
151 static void coroutine_fn nbd_recv_coroutines_wake(BDRVNBDState *s)
152 {
153 int i;
154
155 QEMU_LOCK_GUARD(&s->receive_mutex);
156 for (i = 0; i < MAX_NBD_REQUESTS; i++) {
157 if (nbd_recv_coroutine_wake_one(&s->requests[i])) {
158 return;
159 }
160 }
161 }
162
163 /* Called with s->requests_lock held. */
164 static void coroutine_fn nbd_channel_error_locked(BDRVNBDState *s, int ret)
165 {
166 if (s->state == NBD_CLIENT_CONNECTED) {
167 qio_channel_shutdown(s->ioc, QIO_CHANNEL_SHUTDOWN_BOTH, NULL);
168 }
169
170 if (ret == -EIO) {
171 if (s->state == NBD_CLIENT_CONNECTED) {
172 s->state = s->reconnect_delay ? NBD_CLIENT_CONNECTING_WAIT :
173 NBD_CLIENT_CONNECTING_NOWAIT;
174 }
175 } else {
176 s->state = NBD_CLIENT_QUIT;
177 }
178 }
179
180 static void coroutine_fn nbd_channel_error(BDRVNBDState *s, int ret)
181 {
182 QEMU_LOCK_GUARD(&s->requests_lock);
183 nbd_channel_error_locked(s, ret);
184 }
185
186 static void reconnect_delay_timer_del(BDRVNBDState *s)
187 {
188 if (s->reconnect_delay_timer) {
189 timer_free(s->reconnect_delay_timer);
190 s->reconnect_delay_timer = NULL;
191 }
192 }
193
194 static void reconnect_delay_timer_cb(void *opaque)
195 {
196 BDRVNBDState *s = opaque;
197
198 reconnect_delay_timer_del(s);
199 WITH_QEMU_LOCK_GUARD(&s->requests_lock) {
200 if (s->state != NBD_CLIENT_CONNECTING_WAIT) {
201 return;
202 }
203 s->state = NBD_CLIENT_CONNECTING_NOWAIT;
204 }
205 nbd_co_establish_connection_cancel(s->conn);
206 }
207
208 static void reconnect_delay_timer_init(BDRVNBDState *s, uint64_t expire_time_ns)
209 {
210 assert(!s->reconnect_delay_timer);
211 s->reconnect_delay_timer = aio_timer_new(bdrv_get_aio_context(s->bs),
212 QEMU_CLOCK_REALTIME,
213 SCALE_NS,
214 reconnect_delay_timer_cb, s);
215 timer_mod(s->reconnect_delay_timer, expire_time_ns);
216 }
217
218 static void nbd_teardown_connection(BlockDriverState *bs)
219 {
220 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
221
222 assert(!s->in_flight);
223
224 if (s->ioc) {
225 qio_channel_shutdown(s->ioc, QIO_CHANNEL_SHUTDOWN_BOTH, NULL);
226 yank_unregister_function(BLOCKDEV_YANK_INSTANCE(s->bs->node_name),
227 nbd_yank, s->bs);
228 object_unref(OBJECT(s->ioc));
229 s->ioc = NULL;
230 }
231
232 WITH_QEMU_LOCK_GUARD(&s->requests_lock) {
233 s->state = NBD_CLIENT_QUIT;
234 }
235 }
236
237 static void open_timer_del(BDRVNBDState *s)
238 {
239 if (s->open_timer) {
240 timer_free(s->open_timer);
241 s->open_timer = NULL;
242 }
243 }
244
245 static void open_timer_cb(void *opaque)
246 {
247 BDRVNBDState *s = opaque;
248
249 nbd_co_establish_connection_cancel(s->conn);
250 open_timer_del(s);
251 }
252
253 static void open_timer_init(BDRVNBDState *s, uint64_t expire_time_ns)
254 {
255 assert(!s->open_timer);
256 s->open_timer = aio_timer_new(bdrv_get_aio_context(s->bs),
257 QEMU_CLOCK_REALTIME,
258 SCALE_NS,
259 open_timer_cb, s);
260 timer_mod(s->open_timer, expire_time_ns);
261 }
262
263 static bool nbd_client_will_reconnect(BDRVNBDState *s)
264 {
265 /*
266 * Called only after a socket error, so this is not performance sensitive.
267 */
268 QEMU_LOCK_GUARD(&s->requests_lock);
269 return s->state == NBD_CLIENT_CONNECTING_WAIT;
270 }
271
272 /*
273 * Update @bs with information learned during a completed negotiation process.
274 * Return failure if the server's advertised options are incompatible with the
275 * client's needs.
276 */
277 static int coroutine_fn GRAPH_RDLOCK
278 nbd_handle_updated_info(BlockDriverState *bs, Error **errp)
279 {
280 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
281 int ret;
282
283 if (s->x_dirty_bitmap) {
284 if (!s->info.base_allocation) {
285 error_setg(errp, "requested x-dirty-bitmap %s not found",
286 s->x_dirty_bitmap);
287 return -EINVAL;
288 }
289 if (strcmp(s->x_dirty_bitmap, "qemu:allocation-depth") == 0) {
290 s->alloc_depth = true;
291 }
292 }
293
294 if (s->info.flags & NBD_FLAG_READ_ONLY) {
295 ret = bdrv_apply_auto_read_only(bs, "NBD export is read-only", errp);
296 if (ret < 0) {
297 return ret;
298 }
299 }
300
301 if (s->info.flags & NBD_FLAG_SEND_FUA) {
302 bs->supported_write_flags = BDRV_REQ_FUA;
303 bs->supported_zero_flags |= BDRV_REQ_FUA;
304 }
305
306 if (s->info.flags & NBD_FLAG_SEND_WRITE_ZEROES) {
307 bs->supported_zero_flags |= BDRV_REQ_MAY_UNMAP;
308 if (s->info.flags & NBD_FLAG_SEND_FAST_ZERO) {
309 bs->supported_zero_flags |= BDRV_REQ_NO_FALLBACK;
310 }
311 }
312
313 trace_nbd_client_handshake_success(s->export);
314
315 return 0;
316 }
317
318 int coroutine_fn nbd_co_do_establish_connection(BlockDriverState *bs,
319 bool blocking, Error **errp)
320 {
321 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
322 int ret;
323 IO_CODE();
324
325 assert_bdrv_graph_readable();
326 assert(!s->ioc);
327
328 s->ioc = nbd_co_establish_connection(s->conn, &s->info, blocking, errp);
329 if (!s->ioc) {
330 return -ECONNREFUSED;
331 }
332
333 yank_register_function(BLOCKDEV_YANK_INSTANCE(s->bs->node_name), nbd_yank,
334 bs);
335
336 ret = nbd_handle_updated_info(s->bs, NULL);
337 if (ret < 0) {
338 /*
339 * We have connected, but must fail for other reasons.
340 * Send NBD_CMD_DISC as a courtesy to the server.
341 */
342 NBDRequest request = { .type = NBD_CMD_DISC, .mode = s->info.mode };
343
344 nbd_send_request(s->ioc, &request);
345
346 yank_unregister_function(BLOCKDEV_YANK_INSTANCE(s->bs->node_name),
347 nbd_yank, bs);
348 object_unref(OBJECT(s->ioc));
349 s->ioc = NULL;
350
351 return ret;
352 }
353
354 if (!qio_channel_set_blocking(s->ioc, false, errp)) {
355 return -EINVAL;
356 }
357 qio_channel_set_follow_coroutine_ctx(s->ioc, true);
358
359 /* successfully connected */
360 WITH_QEMU_LOCK_GUARD(&s->requests_lock) {
361 s->state = NBD_CLIENT_CONNECTED;
362 }
363
364 return 0;
365 }
366
367 /* Called with s->requests_lock held. */
368 static bool nbd_client_connecting(BDRVNBDState *s)
369 {
370 return s->state == NBD_CLIENT_CONNECTING_WAIT ||
371 s->state == NBD_CLIENT_CONNECTING_NOWAIT;
372 }
373
374 /* Called with s->requests_lock taken. */
375 static void coroutine_fn GRAPH_RDLOCK nbd_reconnect_attempt(BDRVNBDState *s)
376 {
377 int ret;
378 bool blocking = s->state == NBD_CLIENT_CONNECTING_WAIT;
379
380 /*
381 * Now we are sure that nobody is accessing the channel, and no one will
382 * try until we set the state to CONNECTED.
383 */
384 assert(nbd_client_connecting(s));
385 assert(s->in_flight == 1);
386
387 trace_nbd_reconnect_attempt(s->bs->in_flight);
388
389 if (blocking && !s->reconnect_delay_timer) {
390 /*
391 * It's the first reconnect attempt after switching to
392 * NBD_CLIENT_CONNECTING_WAIT
393 */
394 g_assert(s->reconnect_delay);
395 reconnect_delay_timer_init(s,
396 qemu_clock_get_ns(QEMU_CLOCK_REALTIME) +
397 s->reconnect_delay * NANOSECONDS_PER_SECOND);
398 }
399
400 /* Finalize previous connection if any */
401 if (s->ioc) {
402 yank_unregister_function(BLOCKDEV_YANK_INSTANCE(s->bs->node_name),
403 nbd_yank, s->bs);
404 object_unref(OBJECT(s->ioc));
405 s->ioc = NULL;
406 }
407
408 qemu_mutex_unlock(&s->requests_lock);
409 ret = nbd_co_do_establish_connection(s->bs, blocking, NULL);
410 trace_nbd_reconnect_attempt_result(ret, s->bs->in_flight);
411 qemu_mutex_lock(&s->requests_lock);
412
413 /*
414 * The reconnect attempt is done (maybe successfully, maybe not), so
415 * we no longer need this timer. Delete it so it will not outlive
416 * this I/O request (so draining removes all timers).
417 */
418 reconnect_delay_timer_del(s);
419 }
420
421 static coroutine_fn int nbd_receive_replies(BDRVNBDState *s, uint64_t cookie,
422 Error **errp)
423 {
424 int ret;
425 uint64_t ind = COOKIE_TO_INDEX(cookie), ind2;
426 QEMU_LOCK_GUARD(&s->receive_mutex);
427
428 while (true) {
429 if (s->reply.cookie == cookie) {
430 /* We are done */
431 return 0;
432 }
433
434 if (s->reply.cookie != 0) {
435 /*
436 * Some other request is being handled now. It should already be
437 * woken by whoever set s->reply.cookie (or never wait in this
438 * yield). So, we should not wake it here.
439 */
440 ind2 = COOKIE_TO_INDEX(s->reply.cookie);
441 assert(!s->requests[ind2].receiving);
442
443 s->requests[ind].receiving = true;
444 qemu_co_mutex_unlock(&s->receive_mutex);
445
446 qemu_coroutine_yield();
447 /*
448 * We may be woken for 2 reasons:
449 * 1. From this function, executing in parallel coroutine, when our
450 * cookie is received.
451 * 2. From nbd_co_receive_one_chunk(), when previous request is
452 * finished and s->reply.cookie set to 0.
453 * Anyway, it's OK to lock the mutex and go to the next iteration.
454 */
455
456 qemu_co_mutex_lock(&s->receive_mutex);
457 assert(!s->requests[ind].receiving);
458 continue;
459 }
460
461 /* We are under mutex and cookie is 0. We have to do the dirty work. */
462 assert(s->reply.cookie == 0);
463 ret = nbd_receive_reply(s->bs, s->ioc, &s->reply, s->info.mode, errp);
464 if (ret == 0) {
465 ret = -EIO;
466 error_setg(errp, "server dropped connection");
467 }
468 if (ret < 0) {
469 nbd_channel_error(s, ret);
470 return ret;
471 }
472 if (nbd_reply_is_structured(&s->reply) &&
473 s->info.mode < NBD_MODE_STRUCTURED) {
474 nbd_channel_error(s, -EINVAL);
475 error_setg(errp, "unexpected structured reply");
476 return -EINVAL;
477 }
478 ind2 = COOKIE_TO_INDEX(s->reply.cookie);
479 if (ind2 >= MAX_NBD_REQUESTS || !s->requests[ind2].coroutine) {
480 nbd_channel_error(s, -EINVAL);
481 error_setg(errp, "unexpected cookie value");
482 return -EINVAL;
483 }
484 if (s->reply.cookie == cookie) {
485 /* We are done */
486 return 0;
487 }
488 nbd_recv_coroutine_wake_one(&s->requests[ind2]);
489 }
490 }
491
492 static int coroutine_fn GRAPH_RDLOCK
493 nbd_co_send_request(BlockDriverState *bs, NBDRequest *request,
494 QEMUIOVector *qiov)
495 {
496 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
497 int rc, i = -1;
498
499 qemu_mutex_lock(&s->requests_lock);
500 while (s->in_flight == MAX_NBD_REQUESTS ||
501 (s->state != NBD_CLIENT_CONNECTED && s->in_flight > 0)) {
502 qemu_co_queue_wait(&s->free_sema, &s->requests_lock);
503 }
504
505 s->in_flight++;
506 if (s->state != NBD_CLIENT_CONNECTED) {
507 if (nbd_client_connecting(s)) {
508 nbd_reconnect_attempt(s);
509 qemu_co_queue_restart_all(&s->free_sema);
510 }
511 if (s->state != NBD_CLIENT_CONNECTED) {
512 rc = -EIO;
513 goto err;
514 }
515 }
516
517 for (i = 0; i < MAX_NBD_REQUESTS; i++) {
518 if (s->requests[i].coroutine == NULL) {
519 break;
520 }
521 }
522
523 assert(i < MAX_NBD_REQUESTS);
524 s->requests[i].coroutine = qemu_coroutine_self();
525 s->requests[i].offset = request->from;
526 s->requests[i].receiving = false;
527 qemu_mutex_unlock(&s->requests_lock);
528
529 qemu_co_mutex_lock(&s->send_mutex);
530 request->cookie = INDEX_TO_COOKIE(i);
531 request->mode = s->info.mode;
532
533 assert(s->ioc);
534
535 if (qiov) {
536 qio_channel_set_cork(s->ioc, true);
537 rc = nbd_send_request(s->ioc, request);
538 if (rc >= 0 && qio_channel_writev_all(s->ioc, qiov->iov, qiov->niov,
539 NULL) < 0) {
540 rc = -EIO;
541 }
542 qio_channel_set_cork(s->ioc, false);
543 } else {
544 rc = nbd_send_request(s->ioc, request);
545 }
546 qemu_co_mutex_unlock(&s->send_mutex);
547
548 if (rc < 0) {
549 qemu_mutex_lock(&s->requests_lock);
550 err:
551 nbd_channel_error_locked(s, rc);
552 if (i != -1) {
553 s->requests[i].coroutine = NULL;
554 }
555 s->in_flight--;
556 qemu_co_queue_next(&s->free_sema);
557 qemu_mutex_unlock(&s->requests_lock);
558 }
559 return rc;
560 }
561
562 static inline uint16_t payload_advance16(uint8_t **payload)
563 {
564 *payload += 2;
565 return lduw_be_p(*payload - 2);
566 }
567
568 static inline uint32_t payload_advance32(uint8_t **payload)
569 {
570 *payload += 4;
571 return ldl_be_p(*payload - 4);
572 }
573
574 static inline uint64_t payload_advance64(uint8_t **payload)
575 {
576 *payload += 8;
577 return ldq_be_p(*payload - 8);
578 }
579
580 static int nbd_parse_offset_hole_payload(BDRVNBDState *s,
581 NBDStructuredReplyChunk *chunk,
582 uint8_t *payload, uint64_t orig_offset,
583 QEMUIOVector *qiov, Error **errp)
584 {
585 uint64_t offset;
586 uint32_t hole_size;
587
588 if (chunk->length != sizeof(offset) + sizeof(hole_size)) {
589 error_setg(errp, "Protocol error: invalid payload for "
590 "NBD_REPLY_TYPE_OFFSET_HOLE");
591 return -EINVAL;
592 }
593
594 offset = payload_advance64(&payload);
595 hole_size = payload_advance32(&payload);
596
597 if (!hole_size || offset < orig_offset || hole_size > qiov->size ||
598 offset > orig_offset + qiov->size - hole_size) {
599 error_setg(errp, "Protocol error: server sent chunk exceeding requested"
600 " region");
601 return -EINVAL;
602 }
603 if (s->info.min_block &&
604 !QEMU_IS_ALIGNED(hole_size, s->info.min_block)) {
605 trace_nbd_structured_read_compliance("hole");
606 }
607
608 qemu_iovec_memset(qiov, offset - orig_offset, 0, hole_size);
609
610 return 0;
611 }
612
613 /*
614 * nbd_parse_blockstatus_payload
615 * Based on our request, we expect only one extent in reply, for the
616 * base:allocation context.
617 */
618 static int nbd_parse_blockstatus_payload(BDRVNBDState *s,
619 NBDStructuredReplyChunk *chunk,
620 uint8_t *payload, bool wide,
621 uint64_t orig_length,
622 NBDExtent64 *extent, Error **errp)
623 {
624 uint32_t context_id;
625 uint32_t count;
626 size_t ext_len = wide ? sizeof(*extent) : sizeof(NBDExtent32);
627 size_t pay_len = sizeof(context_id) + wide * sizeof(count) + ext_len;
628
629 /* The server succeeded, so it must have sent [at least] one extent */
630 if (chunk->length < pay_len) {
631 error_setg(errp, "Protocol error: invalid payload for "
632 "NBD_REPLY_TYPE_BLOCK_STATUS");
633 return -EINVAL;
634 }
635
636 context_id = payload_advance32(&payload);
637 if (s->info.context_id != context_id) {
638 error_setg(errp, "Protocol error: unexpected context id %d for "
639 "NBD_REPLY_TYPE_BLOCK_STATUS, when negotiated context "
640 "id is %d", context_id,
641 s->info.context_id);
642 return -EINVAL;
643 }
644
645 if (wide) {
646 count = payload_advance32(&payload);
647 extent->length = payload_advance64(&payload);
648 extent->flags = payload_advance64(&payload);
649 } else {
650 count = 0;
651 extent->length = payload_advance32(&payload);
652 extent->flags = payload_advance32(&payload);
653 }
654
655 if (extent->length == 0) {
656 error_setg(errp, "Protocol error: server sent status chunk with "
657 "zero length");
658 return -EINVAL;
659 }
660
661 /*
662 * A server sending unaligned block status is in violation of the
663 * protocol, but as qemu-nbd 3.1 is such a server (at least for
664 * POSIX files that are not a multiple of 512 bytes, since qemu
665 * rounds files up to 512-byte multiples but lseek(SEEK_HOLE)
666 * still sees an implicit hole beyond the real EOF), it's nicer to
667 * work around the misbehaving server. If the request included
668 * more than the final unaligned block, truncate it back to an
669 * aligned result; if the request was only the final block, round
670 * up to the full block and change the status to fully-allocated
671 * (always a safe status, even if it loses information).
672 */
673 if (s->info.min_block && !QEMU_IS_ALIGNED(extent->length,
674 s->info.min_block)) {
675 trace_nbd_parse_blockstatus_compliance("extent length is unaligned");
676 if (extent->length > s->info.min_block) {
677 extent->length = QEMU_ALIGN_DOWN(extent->length,
678 s->info.min_block);
679 } else {
680 extent->length = s->info.min_block;
681 extent->flags = 0;
682 }
683 }
684
685 /*
686 * We used NBD_CMD_FLAG_REQ_ONE, so the server should not have
687 * sent us any more than one extent, nor should it have included
688 * status beyond our request in that extent. Furthermore, a wide
689 * server should have replied with an accurate count (we left
690 * count at 0 for a narrow server). However, it's easy enough to
691 * ignore the server's noncompliance without killing the
692 * connection; just ignore trailing extents, and clamp things to
693 * the length of our request.
694 */
695 if (count != wide || chunk->length > pay_len) {
696 trace_nbd_parse_blockstatus_compliance("unexpected extent count");
697 }
698 if (extent->length > orig_length) {
699 extent->length = orig_length;
700 trace_nbd_parse_blockstatus_compliance("extent length too large");
701 }
702
703 /*
704 * HACK: if we are using x-dirty-bitmaps to access
705 * qemu:allocation-depth, treat all depths > 2 the same as 2,
706 * since nbd_client_co_block_status is only expecting the low two
707 * bits to be set.
708 */
709 if (s->alloc_depth && extent->flags > 2) {
710 extent->flags = 2;
711 }
712
713 return 0;
714 }
715
716 /*
717 * nbd_parse_error_payload
718 * on success @errp contains message describing nbd error reply
719 */
720 static int nbd_parse_error_payload(NBDStructuredReplyChunk *chunk,
721 uint8_t *payload, int *request_ret,
722 Error **errp)
723 {
724 uint32_t error;
725 uint16_t message_size;
726
727 assert(chunk->type & (1 << 15));
728
729 if (chunk->length < sizeof(error) + sizeof(message_size)) {
730 error_setg(errp,
731 "Protocol error: invalid payload for structured error");
732 return -EINVAL;
733 }
734
735 error = nbd_errno_to_system_errno(payload_advance32(&payload));
736 if (error == 0) {
737 error_setg(errp, "Protocol error: server sent structured error chunk "
738 "with error = 0");
739 return -EINVAL;
740 }
741
742 *request_ret = -error;
743 message_size = payload_advance16(&payload);
744
745 if (message_size > chunk->length - sizeof(error) - sizeof(message_size)) {
746 error_setg(errp, "Protocol error: server sent structured error chunk "
747 "with incorrect message size");
748 return -EINVAL;
749 }
750
751 /* TODO: Add a trace point to mention the server complaint */
752
753 /* TODO handle ERROR_OFFSET */
754
755 return 0;
756 }
757
758 static int coroutine_fn
759 nbd_co_receive_offset_data_payload(BDRVNBDState *s, uint64_t orig_offset,
760 QEMUIOVector *qiov, Error **errp)
761 {
762 QEMUIOVector sub_qiov;
763 uint64_t offset;
764 size_t data_size;
765 int ret;
766 NBDStructuredReplyChunk *chunk = &s->reply.structured;
767
768 assert(nbd_reply_is_structured(&s->reply));
769
770 /* The NBD spec requires at least one byte of payload */
771 if (chunk->length <= sizeof(offset)) {
772 error_setg(errp, "Protocol error: invalid payload for "
773 "NBD_REPLY_TYPE_OFFSET_DATA");
774 return -EINVAL;
775 }
776
777 if (nbd_read64(s->ioc, &offset, "OFFSET_DATA offset", errp) < 0) {
778 return -EIO;
779 }
780
781 data_size = chunk->length - sizeof(offset);
782 assert(data_size);
783 if (offset < orig_offset || data_size > qiov->size ||
784 offset > orig_offset + qiov->size - data_size) {
785 error_setg(errp, "Protocol error: server sent chunk exceeding requested"
786 " region");
787 return -EINVAL;
788 }
789 if (s->info.min_block && !QEMU_IS_ALIGNED(data_size, s->info.min_block)) {
790 trace_nbd_structured_read_compliance("data");
791 }
792
793 qemu_iovec_init(&sub_qiov, qiov->niov);
794 qemu_iovec_concat(&sub_qiov, qiov, offset - orig_offset, data_size);
795 ret = qio_channel_readv_all(s->ioc, sub_qiov.iov, sub_qiov.niov, errp);
796 qemu_iovec_destroy(&sub_qiov);
797
798 return ret < 0 ? -EIO : 0;
799 }
800
801 #define NBD_MAX_MALLOC_PAYLOAD 1000
802 static coroutine_fn int nbd_co_receive_structured_payload(
803 BDRVNBDState *s, void **payload, Error **errp)
804 {
805 int ret;
806 uint32_t len;
807
808 assert(nbd_reply_is_structured(&s->reply));
809
810 len = s->reply.structured.length;
811
812 if (len == 0) {
813 return 0;
814 }
815
816 if (payload == NULL) {
817 error_setg(errp, "Unexpected structured payload");
818 return -EINVAL;
819 }
820
821 if (len > NBD_MAX_MALLOC_PAYLOAD) {
822 error_setg(errp, "Payload too large");
823 return -EINVAL;
824 }
825
826 *payload = g_new(char, len);
827 ret = nbd_read(s->ioc, *payload, len, "structured payload", errp);
828 if (ret < 0) {
829 g_free(*payload);
830 *payload = NULL;
831 return ret;
832 }
833
834 return 0;
835 }
836
837 /*
838 * nbd_co_do_receive_one_chunk
839 * for simple reply:
840 * set request_ret to received reply error
841 * if qiov is not NULL: read payload to @qiov
842 * for structured reply chunk:
843 * if error chunk: read payload, set @request_ret, do not set @payload
844 * else if offset_data chunk: read payload data to @qiov, do not set @payload
845 * else: read payload to @payload
846 *
847 * If function fails, @errp contains corresponding error message, and the
848 * connection with the server is suspect. If it returns 0, then the
849 * transaction succeeded (although @request_ret may be a negative errno
850 * corresponding to the server's error reply), and errp is unchanged.
851 */
852 static coroutine_fn int nbd_co_do_receive_one_chunk(
853 BDRVNBDState *s, uint64_t cookie, bool only_structured,
854 int *request_ret, QEMUIOVector *qiov, void **payload, Error **errp)
855 {
856 ERRP_GUARD();
857 int ret;
858 int i = COOKIE_TO_INDEX(cookie);
859 void *local_payload = NULL;
860 NBDStructuredReplyChunk *chunk;
861
862 if (payload) {
863 *payload = NULL;
864 }
865 *request_ret = 0;
866
867 ret = nbd_receive_replies(s, cookie, errp);
868 if (ret < 0) {
869 error_prepend(errp, "Connection closed: ");
870 return -EIO;
871 }
872 assert(s->ioc);
873
874 assert(s->reply.cookie == cookie);
875
876 if (nbd_reply_is_simple(&s->reply)) {
877 if (only_structured) {
878 error_setg(errp, "Protocol error: simple reply when structured "
879 "reply chunk was expected");
880 return -EINVAL;
881 }
882
883 *request_ret = -nbd_errno_to_system_errno(s->reply.simple.error);
884 if (*request_ret < 0 || !qiov) {
885 return 0;
886 }
887
888 return qio_channel_readv_all(s->ioc, qiov->iov, qiov->niov,
889 errp) < 0 ? -EIO : 0;
890 }
891
892 /* handle structured reply chunk */
893 assert(s->info.mode >= NBD_MODE_STRUCTURED);
894 chunk = &s->reply.structured;
895
896 if (chunk->type == NBD_REPLY_TYPE_NONE) {
897 if (!(chunk->flags & NBD_REPLY_FLAG_DONE)) {
898 error_setg(errp, "Protocol error: NBD_REPLY_TYPE_NONE chunk without"
899 " NBD_REPLY_FLAG_DONE flag set");
900 return -EINVAL;
901 }
902 if (chunk->length) {
903 error_setg(errp, "Protocol error: NBD_REPLY_TYPE_NONE chunk with"
904 " nonzero length");
905 return -EINVAL;
906 }
907 return 0;
908 }
909
910 if (chunk->type == NBD_REPLY_TYPE_OFFSET_DATA) {
911 if (!qiov) {
912 error_setg(errp, "Unexpected NBD_REPLY_TYPE_OFFSET_DATA chunk");
913 return -EINVAL;
914 }
915
916 return nbd_co_receive_offset_data_payload(s, s->requests[i].offset,
917 qiov, errp);
918 }
919
920 if (nbd_reply_type_is_error(chunk->type)) {
921 payload = &local_payload;
922 }
923
924 ret = nbd_co_receive_structured_payload(s, payload, errp);
925 if (ret < 0) {
926 return ret;
927 }
928
929 if (nbd_reply_type_is_error(chunk->type)) {
930 ret = nbd_parse_error_payload(chunk, local_payload, request_ret, errp);
931 g_free(local_payload);
932 return ret;
933 }
934
935 return 0;
936 }
937
938 /*
939 * nbd_co_receive_one_chunk
940 * Read reply, wake up connection_co and set s->quit if needed.
941 * Return value is a fatal error code or normal nbd reply error code
942 */
943 static coroutine_fn int nbd_co_receive_one_chunk(
944 BDRVNBDState *s, uint64_t cookie, bool only_structured,
945 int *request_ret, QEMUIOVector *qiov, NBDReply *reply, void **payload,
946 Error **errp)
947 {
948 int ret = nbd_co_do_receive_one_chunk(s, cookie, only_structured,
949 request_ret, qiov, payload, errp);
950
951 if (ret < 0) {
952 memset(reply, 0, sizeof(*reply));
953 nbd_channel_error(s, ret);
954 } else {
955 /* For assert at loop start in nbd_connection_entry */
956 *reply = s->reply;
957 }
958 s->reply.cookie = 0;
959
960 nbd_recv_coroutines_wake(s);
961
962 return ret;
963 }
964
965 typedef struct NBDReplyChunkIter {
966 int ret;
967 int request_ret;
968 Error *err;
969 bool done, only_structured;
970 } NBDReplyChunkIter;
971
972 static void nbd_iter_channel_error(NBDReplyChunkIter *iter,
973 int ret, Error **local_err)
974 {
975 assert(local_err && *local_err);
976 assert(ret < 0);
977
978 if (!iter->ret) {
979 iter->ret = ret;
980 error_propagate(&iter->err, *local_err);
981 } else {
982 error_free(*local_err);
983 }
984
985 *local_err = NULL;
986 }
987
988 static void nbd_iter_request_error(NBDReplyChunkIter *iter, int ret)
989 {
990 assert(ret < 0);
991
992 if (!iter->request_ret) {
993 iter->request_ret = ret;
994 }
995 }
996
997 /*
998 * NBD_FOREACH_REPLY_CHUNK
999 * The pointer stored in @payload requires g_free() to free it.
1000 */
1001 #define NBD_FOREACH_REPLY_CHUNK(s, iter, cookie, structured, \
1002 qiov, reply, payload) \
1003 for (iter = (NBDReplyChunkIter) { .only_structured = structured }; \
1004 nbd_reply_chunk_iter_receive(s, &iter, cookie, qiov, reply, payload);)
1005
1006 /*
1007 * nbd_reply_chunk_iter_receive
1008 * The pointer stored in @payload requires g_free() to free it.
1009 */
1010 static bool coroutine_fn nbd_reply_chunk_iter_receive(BDRVNBDState *s,
1011 NBDReplyChunkIter *iter,
1012 uint64_t cookie,
1013 QEMUIOVector *qiov,
1014 NBDReply *reply,
1015 void **payload)
1016 {
1017 int ret, request_ret;
1018 NBDReply local_reply;
1019 NBDStructuredReplyChunk *chunk;
1020 Error *local_err = NULL;
1021
1022 if (iter->done) {
1023 /* Previous iteration was last. */
1024 goto break_loop;
1025 }
1026
1027 if (reply == NULL) {
1028 reply = &local_reply;
1029 }
1030
1031 ret = nbd_co_receive_one_chunk(s, cookie, iter->only_structured,
1032 &request_ret, qiov, reply, payload,
1033 &local_err);
1034 if (ret < 0) {
1035 nbd_iter_channel_error(iter, ret, &local_err);
1036 } else if (request_ret < 0) {
1037 nbd_iter_request_error(iter, request_ret);
1038 }
1039
1040 /* Do not execute the body of NBD_FOREACH_REPLY_CHUNK for simple reply. */
1041 if (nbd_reply_is_simple(reply) || iter->ret < 0) {
1042 goto break_loop;
1043 }
1044
1045 chunk = &reply->structured;
1046 iter->only_structured = true;
1047
1048 if (chunk->type == NBD_REPLY_TYPE_NONE) {
1049 /* NBD_REPLY_FLAG_DONE is already checked in nbd_co_receive_one_chunk */
1050 assert(chunk->flags & NBD_REPLY_FLAG_DONE);
1051 goto break_loop;
1052 }
1053
1054 if (chunk->flags & NBD_REPLY_FLAG_DONE) {
1055 /* This iteration is last. */
1056 iter->done = true;
1057 }
1058
1059 /* Execute the loop body */
1060 return true;
1061
1062 break_loop:
1063 qemu_mutex_lock(&s->requests_lock);
1064 s->requests[COOKIE_TO_INDEX(cookie)].coroutine = NULL;
1065 s->in_flight--;
1066 qemu_co_queue_next(&s->free_sema);
1067 qemu_mutex_unlock(&s->requests_lock);
1068
1069 return false;
1070 }
1071
1072 static int coroutine_fn
1073 nbd_co_receive_return_code(BDRVNBDState *s, uint64_t cookie,
1074 int *request_ret, Error **errp)
1075 {
1076 NBDReplyChunkIter iter;
1077
1078 NBD_FOREACH_REPLY_CHUNK(s, iter, cookie, false, NULL, NULL, NULL) {
1079 /* nbd_reply_chunk_iter_receive does all the work */
1080 }
1081
1082 error_propagate(errp, iter.err);
1083 *request_ret = iter.request_ret;
1084 return iter.ret;
1085 }
1086
1087 static int coroutine_fn
1088 nbd_co_receive_cmdread_reply(BDRVNBDState *s, uint64_t cookie,
1089 uint64_t offset, QEMUIOVector *qiov,
1090 int *request_ret, Error **errp)
1091 {
1092 NBDReplyChunkIter iter;
1093 NBDReply reply;
1094 void *payload = NULL;
1095 Error *local_err = NULL;
1096
1097 NBD_FOREACH_REPLY_CHUNK(s, iter, cookie,
1098 s->info.mode >= NBD_MODE_STRUCTURED,
1099 qiov, &reply, &payload)
1100 {
1101 int ret;
1102 NBDStructuredReplyChunk *chunk = &reply.structured;
1103
1104 assert(nbd_reply_is_structured(&reply));
1105
1106 switch (chunk->type) {
1107 case NBD_REPLY_TYPE_OFFSET_DATA:
1108 /*
1109 * special cased in nbd_co_receive_one_chunk, data is already
1110 * in qiov
1111 */
1112 break;
1113 case NBD_REPLY_TYPE_OFFSET_HOLE:
1114 ret = nbd_parse_offset_hole_payload(s, &reply.structured, payload,
1115 offset, qiov, &local_err);
1116 if (ret < 0) {
1117 nbd_channel_error(s, ret);
1118 nbd_iter_channel_error(&iter, ret, &local_err);
1119 }
1120 break;
1121 default:
1122 if (!nbd_reply_type_is_error(chunk->type)) {
1123 /* not allowed reply type */
1124 nbd_channel_error(s, -EINVAL);
1125 error_setg(&local_err,
1126 "Unexpected reply type: %d (%s) for CMD_READ",
1127 chunk->type, nbd_reply_type_lookup(chunk->type));
1128 nbd_iter_channel_error(&iter, -EINVAL, &local_err);
1129 }
1130 }
1131
1132 g_free(payload);
1133 payload = NULL;
1134 }
1135
1136 error_propagate(errp, iter.err);
1137 *request_ret = iter.request_ret;
1138 return iter.ret;
1139 }
1140
1141 static int coroutine_fn
1142 nbd_co_receive_blockstatus_reply(BDRVNBDState *s, uint64_t cookie,
1143 uint64_t length, NBDExtent64 *extent,
1144 int *request_ret, Error **errp)
1145 {
1146 NBDReplyChunkIter iter;
1147 NBDReply reply;
1148 void *payload = NULL;
1149 Error *local_err = NULL;
1150 bool received = false;
1151
1152 assert(!extent->length);
1153 NBD_FOREACH_REPLY_CHUNK(s, iter, cookie, false, NULL, &reply, &payload) {
1154 int ret;
1155 NBDStructuredReplyChunk *chunk = &reply.structured;
1156 bool wide;
1157
1158 assert(nbd_reply_is_structured(&reply));
1159
1160 switch (chunk->type) {
1161 case NBD_REPLY_TYPE_BLOCK_STATUS_EXT:
1162 case NBD_REPLY_TYPE_BLOCK_STATUS:
1163 wide = chunk->type == NBD_REPLY_TYPE_BLOCK_STATUS_EXT;
1164 if ((s->info.mode >= NBD_MODE_EXTENDED) != wide) {
1165 trace_nbd_extended_headers_compliance("block_status");
1166 }
1167 if (received) {
1168 nbd_channel_error(s, -EINVAL);
1169 error_setg(&local_err, "Several BLOCK_STATUS chunks in reply");
1170 nbd_iter_channel_error(&iter, -EINVAL, &local_err);
1171 }
1172 received = true;
1173
1174 ret = nbd_parse_blockstatus_payload(
1175 s, &reply.structured, payload, wide,
1176 length, extent, &local_err);
1177 if (ret < 0) {
1178 nbd_channel_error(s, ret);
1179 nbd_iter_channel_error(&iter, ret, &local_err);
1180 }
1181 break;
1182 default:
1183 if (!nbd_reply_type_is_error(chunk->type)) {
1184 nbd_channel_error(s, -EINVAL);
1185 error_setg(&local_err,
1186 "Unexpected reply type: %d (%s) "
1187 "for CMD_BLOCK_STATUS",
1188 chunk->type, nbd_reply_type_lookup(chunk->type));
1189 nbd_iter_channel_error(&iter, -EINVAL, &local_err);
1190 }
1191 }
1192
1193 g_free(payload);
1194 payload = NULL;
1195 }
1196
1197 if (!extent->length && !iter.request_ret) {
1198 error_setg(&local_err, "Server did not reply with any status extents");
1199 nbd_iter_channel_error(&iter, -EIO, &local_err);
1200 }
1201
1202 error_propagate(errp, iter.err);
1203 *request_ret = iter.request_ret;
1204 return iter.ret;
1205 }
1206
1207 static int coroutine_fn GRAPH_RDLOCK
1208 nbd_co_request(BlockDriverState *bs, NBDRequest *request,
1209 QEMUIOVector *write_qiov)
1210 {
1211 int ret, request_ret;
1212 Error *local_err = NULL;
1213 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1214
1215 assert(request->type != NBD_CMD_READ);
1216 if (write_qiov) {
1217 assert(request->type == NBD_CMD_WRITE);
1218 assert(request->len == iov_size(write_qiov->iov, write_qiov->niov));
1219 } else {
1220 assert(request->type != NBD_CMD_WRITE);
1221 }
1222
1223 do {
1224 ret = nbd_co_send_request(bs, request, write_qiov);
1225 if (ret < 0) {
1226 continue;
1227 }
1228
1229 ret = nbd_co_receive_return_code(s, request->cookie,
1230 &request_ret, &local_err);
1231 if (local_err) {
1232 trace_nbd_co_request_fail(request->from, request->len,
1233 request->cookie, request->flags,
1234 request->type,
1235 nbd_cmd_lookup(request->type),
1236 ret, error_get_pretty(local_err));
1237 error_free(local_err);
1238 local_err = NULL;
1239 }
1240 } while (ret < 0 && nbd_client_will_reconnect(s));
1241
1242 return ret ? ret : request_ret;
1243 }
1244
1245 static int coroutine_fn GRAPH_RDLOCK
1246 nbd_client_co_preadv(BlockDriverState *bs, int64_t offset, int64_t bytes,
1247 QEMUIOVector *qiov, BdrvRequestFlags flags)
1248 {
1249 int ret, request_ret;
1250 Error *local_err = NULL;
1251 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1252 NBDRequest request = {
1253 .type = NBD_CMD_READ,
1254 .from = offset,
1255 .len = bytes,
1256 };
1257
1258 assert(bytes <= NBD_MAX_BUFFER_SIZE);
1259
1260 if (!bytes) {
1261 return 0;
1262 }
1263 /*
1264 * Work around the fact that the block layer doesn't do
1265 * byte-accurate sizing yet - if the read exceeds the server's
1266 * advertised size because the block layer rounded size up, then
1267 * truncate the request to the server and tail-pad with zero.
1268 */
1269 if (offset >= s->info.size) {
1270 assert(bytes < BDRV_SECTOR_SIZE);
1271 qemu_iovec_memset(qiov, 0, 0, bytes);
1272 return 0;
1273 }
1274 if (offset + bytes > s->info.size) {
1275 uint64_t slop = offset + bytes - s->info.size;
1276
1277 assert(slop < BDRV_SECTOR_SIZE);
1278 qemu_iovec_memset(qiov, bytes - slop, 0, slop);
1279 request.len -= slop;
1280 }
1281
1282 do {
1283 ret = nbd_co_send_request(bs, &request, NULL);
1284 if (ret < 0) {
1285 continue;
1286 }
1287
1288 ret = nbd_co_receive_cmdread_reply(s, request.cookie, offset, qiov,
1289 &request_ret, &local_err);
1290 if (local_err) {
1291 trace_nbd_co_request_fail(request.from, request.len, request.cookie,
1292 request.flags, request.type,
1293 nbd_cmd_lookup(request.type),
1294 ret, error_get_pretty(local_err));
1295 error_free(local_err);
1296 local_err = NULL;
1297 }
1298 } while (ret < 0 && nbd_client_will_reconnect(s));
1299
1300 return ret ? ret : request_ret;
1301 }
1302
1303 static int coroutine_fn GRAPH_RDLOCK
1304 nbd_client_co_pwritev(BlockDriverState *bs, int64_t offset, int64_t bytes,
1305 QEMUIOVector *qiov, BdrvRequestFlags flags)
1306 {
1307 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1308 NBDRequest request = {
1309 .type = NBD_CMD_WRITE,
1310 .from = offset,
1311 .len = bytes,
1312 };
1313
1314 assert(!(s->info.flags & NBD_FLAG_READ_ONLY));
1315 if (flags & BDRV_REQ_FUA) {
1316 assert(s->info.flags & NBD_FLAG_SEND_FUA);
1317 request.flags |= NBD_CMD_FLAG_FUA;
1318 }
1319
1320 assert(bytes <= NBD_MAX_BUFFER_SIZE);
1321
1322 if (!bytes) {
1323 return 0;
1324 }
1325 return nbd_co_request(bs, &request, qiov);
1326 }
1327
1328 static int coroutine_fn GRAPH_RDLOCK
1329 nbd_client_co_pwrite_zeroes(BlockDriverState *bs, int64_t offset, int64_t bytes,
1330 BdrvRequestFlags flags)
1331 {
1332 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1333 NBDRequest request = {
1334 .type = NBD_CMD_WRITE_ZEROES,
1335 .from = offset,
1336 .len = bytes,
1337 };
1338
1339 /* rely on max_pwrite_zeroes */
1340 assert(bytes <= UINT32_MAX || s->info.mode >= NBD_MODE_EXTENDED);
1341
1342 assert(!(s->info.flags & NBD_FLAG_READ_ONLY));
1343 if (!(s->info.flags & NBD_FLAG_SEND_WRITE_ZEROES)) {
1344 return -ENOTSUP;
1345 }
1346
1347 if (flags & BDRV_REQ_FUA) {
1348 assert(s->info.flags & NBD_FLAG_SEND_FUA);
1349 request.flags |= NBD_CMD_FLAG_FUA;
1350 }
1351 if (!(flags & BDRV_REQ_MAY_UNMAP)) {
1352 request.flags |= NBD_CMD_FLAG_NO_HOLE;
1353 }
1354 if (flags & BDRV_REQ_NO_FALLBACK) {
1355 assert(s->info.flags & NBD_FLAG_SEND_FAST_ZERO);
1356 request.flags |= NBD_CMD_FLAG_FAST_ZERO;
1357 }
1358
1359 if (!bytes) {
1360 return 0;
1361 }
1362 return nbd_co_request(bs, &request, NULL);
1363 }
1364
1365 static int coroutine_fn GRAPH_RDLOCK nbd_client_co_flush(BlockDriverState *bs)
1366 {
1367 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1368 NBDRequest request = { .type = NBD_CMD_FLUSH };
1369
1370 if (!(s->info.flags & NBD_FLAG_SEND_FLUSH)) {
1371 return 0;
1372 }
1373
1374 request.from = 0;
1375 request.len = 0;
1376
1377 return nbd_co_request(bs, &request, NULL);
1378 }
1379
1380 static int coroutine_fn GRAPH_RDLOCK
1381 nbd_client_co_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes)
1382 {
1383 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1384 NBDRequest request = {
1385 .type = NBD_CMD_TRIM,
1386 .from = offset,
1387 .len = bytes,
1388 };
1389
1390 /* rely on max_pdiscard */
1391 assert(bytes <= UINT32_MAX || s->info.mode >= NBD_MODE_EXTENDED);
1392
1393 assert(!(s->info.flags & NBD_FLAG_READ_ONLY));
1394 if (!(s->info.flags & NBD_FLAG_SEND_TRIM) || !bytes) {
1395 return 0;
1396 }
1397
1398 return nbd_co_request(bs, &request, NULL);
1399 }
1400
1401 static int coroutine_fn GRAPH_RDLOCK nbd_client_co_block_status(
1402 BlockDriverState *bs, unsigned int mode, int64_t offset,
1403 int64_t bytes, int64_t *pnum, int64_t *map, BlockDriverState **file)
1404 {
1405 int ret, request_ret;
1406 NBDExtent64 extent = { 0 };
1407 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1408 Error *local_err = NULL;
1409
1410 NBDRequest request = {
1411 .type = NBD_CMD_BLOCK_STATUS,
1412 .from = offset,
1413 .len = MIN(bytes, s->info.size - offset),
1414 .flags = NBD_CMD_FLAG_REQ_ONE,
1415 };
1416
1417 if (!s->info.base_allocation) {
1418 *pnum = bytes;
1419 *map = offset;
1420 *file = bs;
1421 return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
1422 }
1423 if (s->info.mode < NBD_MODE_EXTENDED) {
1424 request.len = MIN(QEMU_ALIGN_DOWN(INT_MAX, bs->bl.request_alignment),
1425 request.len);
1426 }
1427
1428 /*
1429 * Work around the fact that the block layer doesn't do
1430 * byte-accurate sizing yet - if the status request exceeds the
1431 * server's advertised size because the block layer rounded size
1432 * up, we truncated the request to the server (above), or are
1433 * called on just the hole.
1434 */
1435 if (offset >= s->info.size) {
1436 *pnum = bytes;
1437 assert(bytes < BDRV_SECTOR_SIZE);
1438 /* Intentionally don't report offset_valid for the hole */
1439 return BDRV_BLOCK_ZERO;
1440 }
1441
1442 if (s->info.min_block) {
1443 assert(QEMU_IS_ALIGNED(request.len, s->info.min_block));
1444 }
1445 do {
1446 ret = nbd_co_send_request(bs, &request, NULL);
1447 if (ret < 0) {
1448 continue;
1449 }
1450
1451 ret = nbd_co_receive_blockstatus_reply(s, request.cookie, bytes,
1452 &extent, &request_ret,
1453 &local_err);
1454 if (local_err) {
1455 trace_nbd_co_request_fail(request.from, request.len, request.cookie,
1456 request.flags, request.type,
1457 nbd_cmd_lookup(request.type),
1458 ret, error_get_pretty(local_err));
1459 error_free(local_err);
1460 local_err = NULL;
1461 }
1462 } while (ret < 0 && nbd_client_will_reconnect(s));
1463
1464 if (ret < 0 || request_ret < 0) {
1465 return ret ? ret : request_ret;
1466 }
1467
1468 assert(extent.length);
1469 *pnum = extent.length;
1470 *map = offset;
1471 *file = bs;
1472 return (extent.flags & NBD_STATE_HOLE ? 0 : BDRV_BLOCK_DATA) |
1473 (extent.flags & NBD_STATE_ZERO ? BDRV_BLOCK_ZERO : 0) |
1474 BDRV_BLOCK_OFFSET_VALID;
1475 }
1476
1477 static int nbd_client_reopen_prepare(BDRVReopenState *state,
1478 BlockReopenQueue *queue, Error **errp)
1479 {
1480 BDRVNBDState *s = (BDRVNBDState *)state->bs->opaque;
1481
1482 if ((state->flags & BDRV_O_RDWR) && (s->info.flags & NBD_FLAG_READ_ONLY)) {
1483 error_setg(errp, "Can't reopen read-only NBD mount as read/write");
1484 return -EACCES;
1485 }
1486 return 0;
1487 }
1488
1489 static void nbd_yank(void *opaque)
1490 {
1491 BlockDriverState *bs = opaque;
1492 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1493
1494 QEMU_LOCK_GUARD(&s->requests_lock);
1495 qio_channel_shutdown(s->ioc, QIO_CHANNEL_SHUTDOWN_BOTH, NULL);
1496 s->state = NBD_CLIENT_QUIT;
1497 }
1498
1499 static void nbd_client_close(BlockDriverState *bs)
1500 {
1501 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1502 NBDRequest request = { .type = NBD_CMD_DISC, .mode = s->info.mode };
1503
1504 if (s->ioc) {
1505 nbd_send_request(s->ioc, &request);
1506 }
1507
1508 nbd_teardown_connection(bs);
1509 }
1510
1511
1512 /*
1513 * Parse nbd_open options
1514 */
1515
1516 static int nbd_parse_uri(const char *filename, QDict *options)
1517 {
1518 g_autoptr(GUri) uri = g_uri_parse(filename, G_URI_FLAGS_NONE, NULL);
1519 g_autoptr(GHashTable) qp = NULL;
1520 const char *p;
1521 int qp_n;
1522 bool is_unix;
1523 const char *uri_scheme, *uri_query, *uri_server;
1524 int uri_port;
1525
1526 if (!uri) {
1527 return -EINVAL;
1528 }
1529
1530 /* transport */
1531 uri_scheme = g_uri_get_scheme(uri);
1532 if (!g_strcmp0(uri_scheme, "nbd")) {
1533 is_unix = false;
1534 } else if (!g_strcmp0(uri_scheme, "nbd+tcp")) {
1535 is_unix = false;
1536 } else if (!g_strcmp0(uri_scheme, "nbd+unix")) {
1537 is_unix = true;
1538 } else {
1539 return -EINVAL;
1540 }
1541
1542 p = g_uri_get_path(uri) ?: "";
1543 if (p[0] == '/') {
1544 p++;
1545 }
1546 if (p[0]) {
1547 qdict_put_str(options, "export", p);
1548 }
1549
1550 uri_query = g_uri_get_query(uri);
1551 if (uri_query) {
1552 qp = g_uri_parse_params(uri_query, -1, "&", G_URI_PARAMS_NONE, NULL);
1553 if (!qp) {
1554 return -EINVAL;
1555 }
1556 qp_n = g_hash_table_size(qp);
1557 if (qp_n > 1 || (is_unix && !qp_n) || (!is_unix && qp_n)) {
1558 return -EINVAL;
1559 }
1560 }
1561
1562 uri_server = g_uri_get_host(uri);
1563 if (uri_server && !uri_server[0]) {
1564 uri_server = NULL;
1565 }
1566 uri_port = g_uri_get_port(uri);
1567
1568 if (is_unix) {
1569 /* nbd+unix:///export?socket=path */
1570 const char *uri_socket = g_hash_table_lookup(qp, "socket");
1571 if (uri_server || uri_port != -1 || !uri_socket) {
1572 return -EINVAL;
1573 }
1574 qdict_put_str(options, "server.type", "unix");
1575 qdict_put_str(options, "server.path", uri_socket);
1576 } else {
1577 char *port_str;
1578
1579 /* nbd[+tcp]://host[:port]/export */
1580 if (!uri_server) {
1581 return -EINVAL;
1582 }
1583
1584 qdict_put_str(options, "server.type", "inet");
1585 qdict_put_str(options, "server.host", uri_server);
1586
1587 port_str = g_strdup_printf("%d", uri_port > 0 ? uri_port
1588 : NBD_DEFAULT_PORT);
1589 qdict_put_str(options, "server.port", port_str);
1590 g_free(port_str);
1591 }
1592
1593 return 0;
1594 }
1595
1596 static bool nbd_has_filename_options_conflict(QDict *options, Error **errp)
1597 {
1598 const QDictEntry *e;
1599
1600 for (e = qdict_first(options); e; e = qdict_next(options, e)) {
1601 if (!strcmp(e->key, "host") ||
1602 !strcmp(e->key, "port") ||
1603 !strcmp(e->key, "path") ||
1604 !strcmp(e->key, "export") ||
1605 strstart(e->key, "server.", NULL))
1606 {
1607 error_setg(errp, "Option '%s' cannot be used with a file name",
1608 e->key);
1609 return true;
1610 }
1611 }
1612
1613 return false;
1614 }
1615
1616 static void nbd_parse_filename(const char *filename, QDict *options,
1617 Error **errp)
1618 {
1619 g_autofree char *file = NULL;
1620 char *export_name;
1621 const char *host_spec;
1622 const char *unixpath;
1623
1624 if (nbd_has_filename_options_conflict(options, errp)) {
1625 return;
1626 }
1627
1628 if (strstr(filename, "://")) {
1629 int ret = nbd_parse_uri(filename, options);
1630 if (ret < 0) {
1631 error_setg(errp, "No valid URL specified");
1632 }
1633 return;
1634 }
1635
1636 file = g_strdup(filename);
1637
1638 export_name = strstr(file, EN_OPTSTR);
1639 if (export_name) {
1640 if (export_name[strlen(EN_OPTSTR)] == 0) {
1641 return;
1642 }
1643 export_name[0] = 0; /* truncate 'file' */
1644 export_name += strlen(EN_OPTSTR);
1645
1646 qdict_put_str(options, "export", export_name);
1647 }
1648
1649 /* extract the host_spec - fail if it's not nbd:... */
1650 if (!strstart(file, "nbd:", &host_spec)) {
1651 error_setg(errp, "File name string for NBD must start with 'nbd:'");
1652 return;
1653 }
1654
1655 if (!*host_spec) {
1656 return;
1657 }
1658
1659 /* are we a UNIX or TCP socket? */
1660 if (strstart(host_spec, "unix:", &unixpath)) {
1661 qdict_put_str(options, "server.type", "unix");
1662 qdict_put_str(options, "server.path", unixpath);
1663 } else {
1664 InetSocketAddress *addr = g_new(InetSocketAddress, 1);
1665
1666 if (inet_parse(addr, host_spec, errp)) {
1667 goto out_inet;
1668 }
1669
1670 qdict_put_str(options, "server.type", "inet");
1671 qdict_put_str(options, "server.host", addr->host);
1672 qdict_put_str(options, "server.port", addr->port);
1673 out_inet:
1674 qapi_free_InetSocketAddress(addr);
1675 }
1676 }
1677
1678 static bool nbd_process_legacy_socket_options(QDict *output_options,
1679 QemuOpts *legacy_opts,
1680 Error **errp)
1681 {
1682 const char *path = qemu_opt_get(legacy_opts, "path");
1683 const char *host = qemu_opt_get(legacy_opts, "host");
1684 const char *port = qemu_opt_get(legacy_opts, "port");
1685 const QDictEntry *e;
1686
1687 if (!path && !host && !port) {
1688 return true;
1689 }
1690
1691 for (e = qdict_first(output_options); e; e = qdict_next(output_options, e))
1692 {
1693 if (strstart(e->key, "server.", NULL)) {
1694 error_setg(errp, "Cannot use 'server' and path/host/port at the "
1695 "same time");
1696 return false;
1697 }
1698 }
1699
1700 if (path && host) {
1701 error_setg(errp, "path and host may not be used at the same time");
1702 return false;
1703 } else if (path) {
1704 if (port) {
1705 error_setg(errp, "port may not be used without host");
1706 return false;
1707 }
1708
1709 qdict_put_str(output_options, "server.type", "unix");
1710 qdict_put_str(output_options, "server.path", path);
1711 } else if (host) {
1712 qdict_put_str(output_options, "server.type", "inet");
1713 qdict_put_str(output_options, "server.host", host);
1714 qdict_put_str(output_options, "server.port",
1715 port ?: stringify(NBD_DEFAULT_PORT));
1716 }
1717
1718 return true;
1719 }
1720
1721 static SocketAddress *nbd_config(BDRVNBDState *s, QDict *options,
1722 Error **errp)
1723 {
1724 SocketAddress *saddr = NULL;
1725 QDict *addr = NULL;
1726 Visitor *iv = NULL;
1727
1728 qdict_extract_subqdict(options, &addr, "server.");
1729 if (!qdict_size(addr)) {
1730 error_setg(errp, "NBD server address missing");
1731 goto done;
1732 }
1733
1734 iv = qobject_input_visitor_new_flat_confused(addr, errp);
1735 if (!iv) {
1736 goto done;
1737 }
1738
1739 if (!visit_type_SocketAddress(iv, NULL, &saddr, errp)) {
1740 goto done;
1741 }
1742
1743 if (socket_address_parse_named_fd(saddr, errp) < 0) {
1744 qapi_free_SocketAddress(saddr);
1745 saddr = NULL;
1746 goto done;
1747 }
1748
1749 done:
1750 qobject_unref(addr);
1751 visit_free(iv);
1752 return saddr;
1753 }
1754
1755 static QCryptoTLSCreds *nbd_get_tls_creds(const char *id, Error **errp)
1756 {
1757 Object *obj;
1758 QCryptoTLSCreds *creds;
1759
1760 obj = object_resolve_path_component(
1761 object_get_objects_root(), id);
1762 if (!obj) {
1763 error_setg(errp, "No TLS credentials with id '%s'",
1764 id);
1765 return NULL;
1766 }
1767 creds = (QCryptoTLSCreds *)
1768 object_dynamic_cast(obj, TYPE_QCRYPTO_TLS_CREDS);
1769 if (!creds) {
1770 error_setg(errp, "Object with id '%s' is not TLS credentials",
1771 id);
1772 return NULL;
1773 }
1774
1775 if (!qcrypto_tls_creds_check_endpoint(creds,
1776 QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT,
1777 errp)) {
1778 return NULL;
1779 }
1780 object_ref(obj);
1781 return creds;
1782 }
1783
1784
1785 static QemuOptsList nbd_runtime_opts = {
1786 .name = "nbd",
1787 .head = QTAILQ_HEAD_INITIALIZER(nbd_runtime_opts.head),
1788 .desc = {
1789 {
1790 .name = "host",
1791 .type = QEMU_OPT_STRING,
1792 .help = "TCP host to connect to",
1793 },
1794 {
1795 .name = "port",
1796 .type = QEMU_OPT_STRING,
1797 .help = "TCP port to connect to",
1798 },
1799 {
1800 .name = "path",
1801 .type = QEMU_OPT_STRING,
1802 .help = "Unix socket path to connect to",
1803 },
1804 {
1805 .name = "export",
1806 .type = QEMU_OPT_STRING,
1807 .help = "Name of the NBD export to open",
1808 },
1809 {
1810 .name = "tls-creds",
1811 .type = QEMU_OPT_STRING,
1812 .help = "ID of the TLS credentials to use",
1813 },
1814 {
1815 .name = "tls-hostname",
1816 .type = QEMU_OPT_STRING,
1817 .help = "Override hostname for validating TLS x509 certificate",
1818 },
1819 {
1820 .name = "x-dirty-bitmap",
1821 .type = QEMU_OPT_STRING,
1822 .help = "experimental: expose named dirty bitmap in place of "
1823 "block status",
1824 },
1825 {
1826 .name = "reconnect-delay",
1827 .type = QEMU_OPT_NUMBER,
1828 .help = "On an unexpected disconnect, the nbd client tries to "
1829 "connect again until succeeding or encountering a serious "
1830 "error. During the first @reconnect-delay seconds, all "
1831 "requests are paused and will be rerun on a successful "
1832 "reconnect. After that time, any delayed requests and all "
1833 "future requests before a successful reconnect will "
1834 "immediately fail. Default 0",
1835 },
1836 {
1837 .name = "open-timeout",
1838 .type = QEMU_OPT_NUMBER,
1839 .help = "In seconds. If zero, the nbd driver tries the connection "
1840 "only once, and fails to open if the connection fails. "
1841 "If non-zero, the nbd driver will repeat connection "
1842 "attempts until successful or until @open-timeout seconds "
1843 "have elapsed. Default 0",
1844 },
1845 { /* end of list */ }
1846 },
1847 };
1848
1849 static int nbd_process_options(BlockDriverState *bs, QDict *options,
1850 Error **errp)
1851 {
1852 BDRVNBDState *s = bs->opaque;
1853 QemuOpts *opts;
1854 int ret = -EINVAL;
1855
1856 opts = qemu_opts_create(&nbd_runtime_opts, NULL, 0, &error_abort);
1857 if (!qemu_opts_absorb_qdict(opts, options, errp)) {
1858 goto error;
1859 }
1860
1861 /* Translate @host, @port, and @path to a SocketAddress */
1862 if (!nbd_process_legacy_socket_options(options, opts, errp)) {
1863 goto error;
1864 }
1865
1866 /* Pop the config into our state object. Exit if invalid. */
1867 s->saddr = nbd_config(s, options, errp);
1868 if (!s->saddr) {
1869 goto error;
1870 }
1871
1872 s->export = g_strdup(qemu_opt_get(opts, "export"));
1873 if (s->export && strlen(s->export) > NBD_MAX_STRING_SIZE) {
1874 error_setg(errp, "export name too long to send to server");
1875 goto error;
1876 }
1877
1878 s->tlscredsid = g_strdup(qemu_opt_get(opts, "tls-creds"));
1879 if (s->tlscredsid) {
1880 s->tlscreds = nbd_get_tls_creds(s->tlscredsid, errp);
1881 if (!s->tlscreds) {
1882 goto error;
1883 }
1884
1885 s->tlshostname = g_strdup(qemu_opt_get(opts, "tls-hostname"));
1886 if (!s->tlshostname &&
1887 s->saddr->type == SOCKET_ADDRESS_TYPE_INET) {
1888 s->tlshostname = g_strdup(s->saddr->u.inet.host);
1889 }
1890 }
1891
1892 s->x_dirty_bitmap = g_strdup(qemu_opt_get(opts, "x-dirty-bitmap"));
1893 if (s->x_dirty_bitmap && strlen(s->x_dirty_bitmap) > NBD_MAX_STRING_SIZE) {
1894 error_setg(errp, "x-dirty-bitmap query too long to send to server");
1895 goto error;
1896 }
1897
1898 s->reconnect_delay = qemu_opt_get_number(opts, "reconnect-delay", 0);
1899 s->open_timeout = qemu_opt_get_number(opts, "open-timeout", 0);
1900
1901 ret = 0;
1902
1903 error:
1904 qemu_opts_del(opts);
1905 return ret;
1906 }
1907
1908 static int nbd_open(BlockDriverState *bs, QDict *options, int flags,
1909 Error **errp)
1910 {
1911 int ret;
1912 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1913
1914 s->bs = bs;
1915 qemu_mutex_init(&s->requests_lock);
1916 qemu_co_queue_init(&s->free_sema);
1917 qemu_co_mutex_init(&s->send_mutex);
1918 qemu_co_mutex_init(&s->receive_mutex);
1919
1920 if (!yank_register_instance(BLOCKDEV_YANK_INSTANCE(bs->node_name), errp)) {
1921 return -EEXIST;
1922 }
1923
1924 ret = nbd_process_options(bs, options, errp);
1925 if (ret < 0) {
1926 goto fail;
1927 }
1928
1929 s->conn = nbd_client_connection_new(s->saddr, true, s->export,
1930 s->x_dirty_bitmap, s->tlscreds,
1931 s->tlshostname);
1932
1933 if (s->open_timeout) {
1934 nbd_client_connection_enable_retry(s->conn);
1935 open_timer_init(s, qemu_clock_get_ns(QEMU_CLOCK_REALTIME) +
1936 s->open_timeout * NANOSECONDS_PER_SECOND);
1937 }
1938
1939 s->state = NBD_CLIENT_CONNECTING_WAIT;
1940 ret = nbd_do_establish_connection(bs, true, errp);
1941 if (ret < 0) {
1942 goto fail;
1943 }
1944
1945 /*
1946 * The connect attempt is done, so we no longer need this timer.
1947 * Delete it, because we do not want it to be around when this node
1948 * is drained or closed.
1949 */
1950 open_timer_del(s);
1951
1952 nbd_client_connection_enable_retry(s->conn);
1953
1954 return 0;
1955
1956 fail:
1957 open_timer_del(s);
1958 nbd_clear_bdrvstate(bs);
1959 return ret;
1960 }
1961
1962 static void nbd_refresh_limits(BlockDriverState *bs, Error **errp)
1963 {
1964 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1965 uint32_t min = s->info.min_block;
1966 uint32_t max = MIN_NON_ZERO(NBD_MAX_BUFFER_SIZE, s->info.max_block);
1967
1968 /*
1969 * If the server did not advertise an alignment:
1970 * - a size that is not sector-aligned implies that an alignment
1971 * of 1 can be used to access those tail bytes
1972 * - advertisement of block status requires an alignment of 1, so
1973 * that we don't violate block layer constraints that block
1974 * status is always aligned (as we can't control whether the
1975 * server will report sub-sector extents, such as a hole at EOF
1976 * on an unaligned POSIX file)
1977 * - otherwise, assume the server is so old that we are safer avoiding
1978 * sub-sector requests
1979 */
1980 if (!min) {
1981 min = (!QEMU_IS_ALIGNED(s->info.size, BDRV_SECTOR_SIZE) ||
1982 s->info.base_allocation) ? 1 : BDRV_SECTOR_SIZE;
1983 }
1984
1985 bs->bl.request_alignment = min;
1986 bs->bl.max_pdiscard = QEMU_ALIGN_DOWN(INT_MAX, min);
1987 bs->bl.max_pwrite_zeroes = max;
1988 bs->bl.max_transfer = max;
1989
1990 /*
1991 * Assume that if the server supports extended headers, it also
1992 * supports unlimited size zero and trim commands.
1993 */
1994 if (s->info.mode >= NBD_MODE_EXTENDED) {
1995 bs->bl.max_pdiscard = bs->bl.max_pwrite_zeroes = 0;
1996 }
1997
1998 if (s->info.opt_block &&
1999 s->info.opt_block > bs->bl.opt_transfer) {
2000 bs->bl.opt_transfer = s->info.opt_block;
2001 }
2002 }
2003
2004 static void nbd_close(BlockDriverState *bs)
2005 {
2006 nbd_client_close(bs);
2007 nbd_clear_bdrvstate(bs);
2008 }
2009
2010 /*
2011 * NBD cannot truncate, but if the caller asks to truncate to the same size, or
2012 * to a smaller size with exact=false, there is no reason to fail the
2013 * operation.
2014 *
2015 * Preallocation mode is ignored since it does not seems useful to fail when
2016 * we never change anything.
2017 */
2018 static int coroutine_fn nbd_co_truncate(BlockDriverState *bs, int64_t offset,
2019 bool exact, PreallocMode prealloc,
2020 BdrvRequestFlags flags, Error **errp)
2021 {
2022 BDRVNBDState *s = bs->opaque;
2023
2024 if (offset != s->info.size && exact) {
2025 error_setg(errp, "Cannot resize NBD nodes");
2026 return -ENOTSUP;
2027 }
2028
2029 if (offset > s->info.size) {
2030 error_setg(errp, "Cannot grow NBD nodes");
2031 return -EINVAL;
2032 }
2033
2034 return 0;
2035 }
2036
2037 static int64_t coroutine_fn nbd_co_getlength(BlockDriverState *bs)
2038 {
2039 BDRVNBDState *s = bs->opaque;
2040
2041 return s->info.size;
2042 }
2043
2044 static void nbd_refresh_filename(BlockDriverState *bs)
2045 {
2046 BDRVNBDState *s = bs->opaque;
2047 const char *host = NULL, *port = NULL, *path = NULL;
2048 size_t len = 0;
2049
2050 if (s->saddr->type == SOCKET_ADDRESS_TYPE_INET) {
2051 const InetSocketAddress *inet = &s->saddr->u.inet;
2052 if (!inet->has_ipv4 && !inet->has_ipv6 && !inet->has_to) {
2053 host = inet->host;
2054 port = inet->port;
2055 }
2056 } else if (s->saddr->type == SOCKET_ADDRESS_TYPE_UNIX) {
2057 path = s->saddr->u.q_unix.path;
2058 } /* else can't represent as pseudo-filename */
2059
2060 if (path && s->export) {
2061 len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
2062 "nbd+unix:///%s?socket=%s", s->export, path);
2063 } else if (path && !s->export) {
2064 len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
2065 "nbd+unix://?socket=%s", path);
2066 } else if (host && s->export) {
2067 len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
2068 "nbd://%s:%s/%s", host, port, s->export);
2069 } else if (host && !s->export) {
2070 len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
2071 "nbd://%s:%s", host, port);
2072 }
2073 if (len >= sizeof(bs->exact_filename)) {
2074 /* Name is too long to represent exactly, so leave it empty. */
2075 bs->exact_filename[0] = '\0';
2076 }
2077 }
2078
2079 static char *nbd_dirname(BlockDriverState *bs, Error **errp)
2080 {
2081 /* The generic bdrv_dirname() implementation is able to work out some
2082 * directory name for NBD nodes, but that would be wrong. So far there is no
2083 * specification for how "export paths" would work, so NBD does not have
2084 * directory names. */
2085 error_setg(errp, "Cannot generate a base directory for NBD nodes");
2086 return NULL;
2087 }
2088
2089 static const char *const nbd_strong_runtime_opts[] = {
2090 "path",
2091 "host",
2092 "port",
2093 "export",
2094 "tls-creds",
2095 "tls-hostname",
2096 "server.",
2097
2098 NULL
2099 };
2100
2101 static void nbd_cancel_in_flight(BlockDriverState *bs)
2102 {
2103 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
2104
2105 reconnect_delay_timer_del(s);
2106
2107 qemu_mutex_lock(&s->requests_lock);
2108 if (s->state == NBD_CLIENT_CONNECTING_WAIT) {
2109 s->state = NBD_CLIENT_CONNECTING_NOWAIT;
2110 }
2111 qemu_mutex_unlock(&s->requests_lock);
2112
2113 nbd_co_establish_connection_cancel(s->conn);
2114 }
2115
2116 static void nbd_attach_aio_context(BlockDriverState *bs,
2117 AioContext *new_context)
2118 {
2119 BDRVNBDState *s = bs->opaque;
2120
2121 /* The open_timer is used only during nbd_open() */
2122 assert(!s->open_timer);
2123
2124 /*
2125 * The reconnect_delay_timer is scheduled in I/O paths when the
2126 * connection is lost, to cancel the reconnection attempt after a
2127 * given time. Once this attempt is done (successfully or not),
2128 * nbd_reconnect_attempt() ensures the timer is deleted before the
2129 * respective I/O request is resumed.
2130 * Since the AioContext can only be changed when a node is drained,
2131 * the reconnect_delay_timer cannot be active here.
2132 */
2133 assert(!s->reconnect_delay_timer);
2134 }
2135
2136 static void nbd_detach_aio_context(BlockDriverState *bs)
2137 {
2138 BDRVNBDState *s = bs->opaque;
2139
2140 assert(!s->open_timer);
2141 assert(!s->reconnect_delay_timer);
2142 }
2143
2144 static BlockDriver bdrv_nbd = {
2145 .format_name = "nbd",
2146 .protocol_name = "nbd",
2147 .instance_size = sizeof(BDRVNBDState),
2148 .bdrv_parse_filename = nbd_parse_filename,
2149 .bdrv_co_create_opts = bdrv_co_create_opts_simple,
2150 .create_opts = &bdrv_create_opts_simple,
2151 .bdrv_open = nbd_open,
2152 .bdrv_reopen_prepare = nbd_client_reopen_prepare,
2153 .bdrv_co_preadv = nbd_client_co_preadv,
2154 .bdrv_co_pwritev = nbd_client_co_pwritev,
2155 .bdrv_co_pwrite_zeroes = nbd_client_co_pwrite_zeroes,
2156 .bdrv_close = nbd_close,
2157 .bdrv_co_flush_to_os = nbd_client_co_flush,
2158 .bdrv_co_pdiscard = nbd_client_co_pdiscard,
2159 .bdrv_refresh_limits = nbd_refresh_limits,
2160 .bdrv_co_truncate = nbd_co_truncate,
2161 .bdrv_co_getlength = nbd_co_getlength,
2162 .bdrv_refresh_filename = nbd_refresh_filename,
2163 .bdrv_co_block_status = nbd_client_co_block_status,
2164 .bdrv_dirname = nbd_dirname,
2165 .strong_runtime_opts = nbd_strong_runtime_opts,
2166 .bdrv_cancel_in_flight = nbd_cancel_in_flight,
2167
2168 .bdrv_attach_aio_context = nbd_attach_aio_context,
2169 .bdrv_detach_aio_context = nbd_detach_aio_context,
2170 };
2171
2172 static BlockDriver bdrv_nbd_tcp = {
2173 .format_name = "nbd",
2174 .protocol_name = "nbd+tcp",
2175 .instance_size = sizeof(BDRVNBDState),
2176 .bdrv_parse_filename = nbd_parse_filename,
2177 .bdrv_co_create_opts = bdrv_co_create_opts_simple,
2178 .create_opts = &bdrv_create_opts_simple,
2179 .bdrv_open = nbd_open,
2180 .bdrv_reopen_prepare = nbd_client_reopen_prepare,
2181 .bdrv_co_preadv = nbd_client_co_preadv,
2182 .bdrv_co_pwritev = nbd_client_co_pwritev,
2183 .bdrv_co_pwrite_zeroes = nbd_client_co_pwrite_zeroes,
2184 .bdrv_close = nbd_close,
2185 .bdrv_co_flush_to_os = nbd_client_co_flush,
2186 .bdrv_co_pdiscard = nbd_client_co_pdiscard,
2187 .bdrv_refresh_limits = nbd_refresh_limits,
2188 .bdrv_co_truncate = nbd_co_truncate,
2189 .bdrv_co_getlength = nbd_co_getlength,
2190 .bdrv_refresh_filename = nbd_refresh_filename,
2191 .bdrv_co_block_status = nbd_client_co_block_status,
2192 .bdrv_dirname = nbd_dirname,
2193 .strong_runtime_opts = nbd_strong_runtime_opts,
2194 .bdrv_cancel_in_flight = nbd_cancel_in_flight,
2195
2196 .bdrv_attach_aio_context = nbd_attach_aio_context,
2197 .bdrv_detach_aio_context = nbd_detach_aio_context,
2198 };
2199
2200 static BlockDriver bdrv_nbd_unix = {
2201 .format_name = "nbd",
2202 .protocol_name = "nbd+unix",
2203 .instance_size = sizeof(BDRVNBDState),
2204 .bdrv_parse_filename = nbd_parse_filename,
2205 .bdrv_co_create_opts = bdrv_co_create_opts_simple,
2206 .create_opts = &bdrv_create_opts_simple,
2207 .bdrv_open = nbd_open,
2208 .bdrv_reopen_prepare = nbd_client_reopen_prepare,
2209 .bdrv_co_preadv = nbd_client_co_preadv,
2210 .bdrv_co_pwritev = nbd_client_co_pwritev,
2211 .bdrv_co_pwrite_zeroes = nbd_client_co_pwrite_zeroes,
2212 .bdrv_close = nbd_close,
2213 .bdrv_co_flush_to_os = nbd_client_co_flush,
2214 .bdrv_co_pdiscard = nbd_client_co_pdiscard,
2215 .bdrv_refresh_limits = nbd_refresh_limits,
2216 .bdrv_co_truncate = nbd_co_truncate,
2217 .bdrv_co_getlength = nbd_co_getlength,
2218 .bdrv_refresh_filename = nbd_refresh_filename,
2219 .bdrv_co_block_status = nbd_client_co_block_status,
2220 .bdrv_dirname = nbd_dirname,
2221 .strong_runtime_opts = nbd_strong_runtime_opts,
2222 .bdrv_cancel_in_flight = nbd_cancel_in_flight,
2223
2224 .bdrv_attach_aio_context = nbd_attach_aio_context,
2225 .bdrv_detach_aio_context = nbd_detach_aio_context,
2226 };
2227
2228 static void bdrv_nbd_init(void)
2229 {
2230 bdrv_register(&bdrv_nbd);
2231 bdrv_register(&bdrv_nbd_tcp);
2232 bdrv_register(&bdrv_nbd_unix);
2233 }
2234
2235 block_init(bdrv_nbd_init);