xref: /openbmc/qemu/include/block/nbd.h (revision ab4c1361)
1 /*
2  *  Copyright (C) 2016-2022 Red Hat, Inc.
3  *  Copyright (C) 2005  Anthony Liguori <anthony@codemonkey.ws>
4  *
5  *  Network Block Device
6  *
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License as published by
9  *  the Free Software Foundation; under version 2 of the License.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, see <http://www.gnu.org/licenses/>.
18  */
19 
20 #ifndef NBD_H
21 #define NBD_H
22 
23 #include "block/export.h"
24 #include "io/channel-socket.h"
25 #include "crypto/tlscreds.h"
26 #include "qapi/error.h"
27 #include "qemu/bswap.h"
28 
29 extern const BlockExportDriver blk_exp_nbd;
30 
31 /* Handshake phase structs - this struct is passed on the wire */
32 
33 struct NBDOption {
34     uint64_t magic; /* NBD_OPTS_MAGIC */
35     uint32_t option; /* NBD_OPT_* */
36     uint32_t length;
37 } QEMU_PACKED;
38 typedef struct NBDOption NBDOption;
39 
40 struct NBDOptionReply {
41     uint64_t magic; /* NBD_REP_MAGIC */
42     uint32_t option; /* NBD_OPT_* */
43     uint32_t type; /* NBD_REP_* */
44     uint32_t length;
45 } QEMU_PACKED;
46 typedef struct NBDOptionReply NBDOptionReply;
47 
48 typedef struct NBDOptionReplyMetaContext {
49     NBDOptionReply h; /* h.type = NBD_REP_META_CONTEXT, h.length > 4 */
50     uint32_t context_id;
51     /* metadata context name follows */
52 } QEMU_PACKED NBDOptionReplyMetaContext;
53 
54 /* Transmission phase structs
55  *
56  * Note: these are _NOT_ the same as the network representation of an NBD
57  * request and reply!
58  */
59 struct NBDRequest {
60     uint64_t handle;
61     uint64_t from;
62     uint32_t len;
63     uint16_t flags; /* NBD_CMD_FLAG_* */
64     uint16_t type; /* NBD_CMD_* */
65 };
66 typedef struct NBDRequest NBDRequest;
67 
68 typedef struct NBDSimpleReply {
69     uint32_t magic;  /* NBD_SIMPLE_REPLY_MAGIC */
70     uint32_t error;
71     uint64_t handle;
72 } QEMU_PACKED NBDSimpleReply;
73 
74 /* Header of all structured replies */
75 typedef struct NBDStructuredReplyChunk {
76     uint32_t magic;  /* NBD_STRUCTURED_REPLY_MAGIC */
77     uint16_t flags;  /* combination of NBD_REPLY_FLAG_* */
78     uint16_t type;   /* NBD_REPLY_TYPE_* */
79     uint64_t handle; /* request handle */
80     uint32_t length; /* length of payload */
81 } QEMU_PACKED NBDStructuredReplyChunk;
82 
83 typedef union NBDReply {
84     NBDSimpleReply simple;
85     NBDStructuredReplyChunk structured;
86     struct {
87         /* @magic and @handle fields have the same offset and size both in
88          * simple reply and structured reply chunk, so let them be accessible
89          * without ".simple." or ".structured." specification
90          */
91         uint32_t magic;
92         uint32_t _skip;
93         uint64_t handle;
94     } QEMU_PACKED;
95 } NBDReply;
96 
97 /* Header of chunk for NBD_REPLY_TYPE_OFFSET_DATA */
98 typedef struct NBDStructuredReadData {
99     NBDStructuredReplyChunk h; /* h.length >= 9 */
100     uint64_t offset;
101     /* At least one byte of data payload follows, calculated from h.length */
102 } QEMU_PACKED NBDStructuredReadData;
103 
104 /* Complete chunk for NBD_REPLY_TYPE_OFFSET_HOLE */
105 typedef struct NBDStructuredReadHole {
106     NBDStructuredReplyChunk h; /* h.length == 12 */
107     uint64_t offset;
108     uint32_t length;
109 } QEMU_PACKED NBDStructuredReadHole;
110 
111 /* Header of all NBD_REPLY_TYPE_ERROR* errors */
112 typedef struct NBDStructuredError {
113     NBDStructuredReplyChunk h; /* h.length >= 6 */
114     uint32_t error;
115     uint16_t message_length;
116 } QEMU_PACKED NBDStructuredError;
117 
118 /* Header of NBD_REPLY_TYPE_BLOCK_STATUS */
119 typedef struct NBDStructuredMeta {
120     NBDStructuredReplyChunk h; /* h.length >= 12 (at least one extent) */
121     uint32_t context_id;
122     /* extents follows */
123 } QEMU_PACKED NBDStructuredMeta;
124 
125 /* Extent chunk for NBD_REPLY_TYPE_BLOCK_STATUS */
126 typedef struct NBDExtent {
127     uint32_t length;
128     uint32_t flags; /* NBD_STATE_* */
129 } QEMU_PACKED NBDExtent;
130 
131 /* Transmission (export) flags: sent from server to client during handshake,
132    but describe what will happen during transmission */
133 enum {
134     NBD_FLAG_HAS_FLAGS_BIT          =  0, /* Flags are there */
135     NBD_FLAG_READ_ONLY_BIT          =  1, /* Device is read-only */
136     NBD_FLAG_SEND_FLUSH_BIT         =  2, /* Send FLUSH */
137     NBD_FLAG_SEND_FUA_BIT           =  3, /* Send FUA (Force Unit Access) */
138     NBD_FLAG_ROTATIONAL_BIT         =  4, /* Use elevator algorithm -
139                                              rotational media */
140     NBD_FLAG_SEND_TRIM_BIT          =  5, /* Send TRIM (discard) */
141     NBD_FLAG_SEND_WRITE_ZEROES_BIT  =  6, /* Send WRITE_ZEROES */
142     NBD_FLAG_SEND_DF_BIT            =  7, /* Send DF (Do not Fragment) */
143     NBD_FLAG_CAN_MULTI_CONN_BIT     =  8, /* Multi-client cache consistent */
144     NBD_FLAG_SEND_RESIZE_BIT        =  9, /* Send resize */
145     NBD_FLAG_SEND_CACHE_BIT         = 10, /* Send CACHE (prefetch) */
146     NBD_FLAG_SEND_FAST_ZERO_BIT     = 11, /* FAST_ZERO flag for WRITE_ZEROES */
147 };
148 
149 #define NBD_FLAG_HAS_FLAGS         (1 << NBD_FLAG_HAS_FLAGS_BIT)
150 #define NBD_FLAG_READ_ONLY         (1 << NBD_FLAG_READ_ONLY_BIT)
151 #define NBD_FLAG_SEND_FLUSH        (1 << NBD_FLAG_SEND_FLUSH_BIT)
152 #define NBD_FLAG_SEND_FUA          (1 << NBD_FLAG_SEND_FUA_BIT)
153 #define NBD_FLAG_ROTATIONAL        (1 << NBD_FLAG_ROTATIONAL_BIT)
154 #define NBD_FLAG_SEND_TRIM         (1 << NBD_FLAG_SEND_TRIM_BIT)
155 #define NBD_FLAG_SEND_WRITE_ZEROES (1 << NBD_FLAG_SEND_WRITE_ZEROES_BIT)
156 #define NBD_FLAG_SEND_DF           (1 << NBD_FLAG_SEND_DF_BIT)
157 #define NBD_FLAG_CAN_MULTI_CONN    (1 << NBD_FLAG_CAN_MULTI_CONN_BIT)
158 #define NBD_FLAG_SEND_RESIZE       (1 << NBD_FLAG_SEND_RESIZE_BIT)
159 #define NBD_FLAG_SEND_CACHE        (1 << NBD_FLAG_SEND_CACHE_BIT)
160 #define NBD_FLAG_SEND_FAST_ZERO    (1 << NBD_FLAG_SEND_FAST_ZERO_BIT)
161 
162 /* New-style handshake (global) flags, sent from server to client, and
163    control what will happen during handshake phase. */
164 #define NBD_FLAG_FIXED_NEWSTYLE   (1 << 0) /* Fixed newstyle protocol. */
165 #define NBD_FLAG_NO_ZEROES        (1 << 1) /* End handshake without zeroes. */
166 
167 /* New-style client flags, sent from client to server to control what happens
168    during handshake phase. */
169 #define NBD_FLAG_C_FIXED_NEWSTYLE (1 << 0) /* Fixed newstyle protocol. */
170 #define NBD_FLAG_C_NO_ZEROES      (1 << 1) /* End handshake without zeroes. */
171 
172 /* Option requests. */
173 #define NBD_OPT_EXPORT_NAME       (1)
174 #define NBD_OPT_ABORT             (2)
175 #define NBD_OPT_LIST              (3)
176 /* #define NBD_OPT_PEEK_EXPORT    (4) not in use */
177 #define NBD_OPT_STARTTLS          (5)
178 #define NBD_OPT_INFO              (6)
179 #define NBD_OPT_GO                (7)
180 #define NBD_OPT_STRUCTURED_REPLY  (8)
181 #define NBD_OPT_LIST_META_CONTEXT (9)
182 #define NBD_OPT_SET_META_CONTEXT  (10)
183 
184 /* Option reply types. */
185 #define NBD_REP_ERR(value) ((UINT32_C(1) << 31) | (value))
186 
187 #define NBD_REP_ACK             (1)    /* Data sending finished. */
188 #define NBD_REP_SERVER          (2)    /* Export description. */
189 #define NBD_REP_INFO            (3)    /* NBD_OPT_INFO/GO. */
190 #define NBD_REP_META_CONTEXT    (4)    /* NBD_OPT_{LIST,SET}_META_CONTEXT */
191 
192 #define NBD_REP_ERR_UNSUP           NBD_REP_ERR(1)  /* Unknown option */
193 #define NBD_REP_ERR_POLICY          NBD_REP_ERR(2)  /* Server denied */
194 #define NBD_REP_ERR_INVALID         NBD_REP_ERR(3)  /* Invalid length */
195 #define NBD_REP_ERR_PLATFORM        NBD_REP_ERR(4)  /* Not compiled in */
196 #define NBD_REP_ERR_TLS_REQD        NBD_REP_ERR(5)  /* TLS required */
197 #define NBD_REP_ERR_UNKNOWN         NBD_REP_ERR(6)  /* Export unknown */
198 #define NBD_REP_ERR_SHUTDOWN        NBD_REP_ERR(7)  /* Server shutting down */
199 #define NBD_REP_ERR_BLOCK_SIZE_REQD NBD_REP_ERR(8)  /* Need INFO_BLOCK_SIZE */
200 
201 /* Info types, used during NBD_REP_INFO */
202 #define NBD_INFO_EXPORT         0
203 #define NBD_INFO_NAME           1
204 #define NBD_INFO_DESCRIPTION    2
205 #define NBD_INFO_BLOCK_SIZE     3
206 
207 /* Request flags, sent from client to server during transmission phase */
208 #define NBD_CMD_FLAG_FUA        (1 << 0) /* 'force unit access' during write */
209 #define NBD_CMD_FLAG_NO_HOLE    (1 << 1) /* don't punch hole on zero run */
210 #define NBD_CMD_FLAG_DF         (1 << 2) /* don't fragment structured read */
211 #define NBD_CMD_FLAG_REQ_ONE    (1 << 3) /* only one extent in BLOCK_STATUS
212                                           * reply chunk */
213 #define NBD_CMD_FLAG_FAST_ZERO  (1 << 4) /* fail if WRITE_ZEROES is not fast */
214 
215 /* Supported request types */
216 enum {
217     NBD_CMD_READ = 0,
218     NBD_CMD_WRITE = 1,
219     NBD_CMD_DISC = 2,
220     NBD_CMD_FLUSH = 3,
221     NBD_CMD_TRIM = 4,
222     NBD_CMD_CACHE = 5,
223     NBD_CMD_WRITE_ZEROES = 6,
224     NBD_CMD_BLOCK_STATUS = 7,
225 };
226 
227 #define NBD_DEFAULT_PORT	10809
228 
229 /* Maximum size of a single READ/WRITE data buffer */
230 #define NBD_MAX_BUFFER_SIZE (32 * 1024 * 1024)
231 
232 /*
233  * Maximum size of a protocol string (export name, metadata context name,
234  * etc.).  Use malloc rather than stack allocation for storage of a
235  * string.
236  */
237 #define NBD_MAX_STRING_SIZE 4096
238 
239 /* Two types of reply structures */
240 #define NBD_SIMPLE_REPLY_MAGIC      0x67446698
241 #define NBD_STRUCTURED_REPLY_MAGIC  0x668e33ef
242 
243 /* Structured reply flags */
244 #define NBD_REPLY_FLAG_DONE          (1 << 0) /* This reply-chunk is last */
245 
246 /* Structured reply types */
247 #define NBD_REPLY_ERR(value)         ((1 << 15) | (value))
248 
249 #define NBD_REPLY_TYPE_NONE          0
250 #define NBD_REPLY_TYPE_OFFSET_DATA   1
251 #define NBD_REPLY_TYPE_OFFSET_HOLE   2
252 #define NBD_REPLY_TYPE_BLOCK_STATUS  5
253 #define NBD_REPLY_TYPE_ERROR         NBD_REPLY_ERR(1)
254 #define NBD_REPLY_TYPE_ERROR_OFFSET  NBD_REPLY_ERR(2)
255 
256 /* Extent flags for base:allocation in NBD_REPLY_TYPE_BLOCK_STATUS */
257 #define NBD_STATE_HOLE (1 << 0)
258 #define NBD_STATE_ZERO (1 << 1)
259 
260 /* Extent flags for qemu:dirty-bitmap in NBD_REPLY_TYPE_BLOCK_STATUS */
261 #define NBD_STATE_DIRTY (1 << 0)
262 
263 /* No flags needed for qemu:allocation-depth in NBD_REPLY_TYPE_BLOCK_STATUS */
264 
265 static inline bool nbd_reply_type_is_error(int type)
266 {
267     return type & (1 << 15);
268 }
269 
270 /* NBD errors are based on errno numbers, so there is a 1:1 mapping,
271  * but only a limited set of errno values is specified in the protocol.
272  * Everything else is squashed to EINVAL.
273  */
274 #define NBD_SUCCESS    0
275 #define NBD_EPERM      1
276 #define NBD_EIO        5
277 #define NBD_ENOMEM     12
278 #define NBD_EINVAL     22
279 #define NBD_ENOSPC     28
280 #define NBD_EOVERFLOW  75
281 #define NBD_ENOTSUP    95
282 #define NBD_ESHUTDOWN  108
283 
284 /* Details collected by NBD_OPT_EXPORT_NAME and NBD_OPT_GO */
285 struct NBDExportInfo {
286     /* Set by client before nbd_receive_negotiate() */
287     bool request_sizes;
288     char *x_dirty_bitmap;
289 
290     /* Set by client before nbd_receive_negotiate(), or by server results
291      * during nbd_receive_export_list() */
292     char *name; /* must be non-NULL */
293 
294     /* In-out fields, set by client before nbd_receive_negotiate() and
295      * updated by server results during nbd_receive_negotiate() */
296     bool structured_reply;
297     bool base_allocation; /* base:allocation context for NBD_CMD_BLOCK_STATUS */
298 
299     /* Set by server results during nbd_receive_negotiate() and
300      * nbd_receive_export_list() */
301     uint64_t size;
302     uint16_t flags;
303     uint32_t min_block;
304     uint32_t opt_block;
305     uint32_t max_block;
306 
307     uint32_t context_id;
308 
309     /* Set by server results during nbd_receive_export_list() */
310     char *description;
311     int n_contexts;
312     char **contexts;
313 };
314 typedef struct NBDExportInfo NBDExportInfo;
315 
316 int nbd_receive_negotiate(AioContext *aio_context, QIOChannel *ioc,
317                           QCryptoTLSCreds *tlscreds,
318                           const char *hostname, QIOChannel **outioc,
319                           NBDExportInfo *info, Error **errp);
320 void nbd_free_export_list(NBDExportInfo *info, int count);
321 int nbd_receive_export_list(QIOChannel *ioc, QCryptoTLSCreds *tlscreds,
322                             const char *hostname, NBDExportInfo **info,
323                             Error **errp);
324 int nbd_init(int fd, QIOChannelSocket *sioc, NBDExportInfo *info,
325              Error **errp);
326 int nbd_send_request(QIOChannel *ioc, NBDRequest *request);
327 int coroutine_fn nbd_receive_reply(BlockDriverState *bs, QIOChannel *ioc,
328                                    NBDReply *reply, Error **errp);
329 int nbd_client(int fd);
330 int nbd_disconnect(int fd);
331 int nbd_errno_to_system_errno(int err);
332 
333 typedef struct NBDExport NBDExport;
334 typedef struct NBDClient NBDClient;
335 
336 void nbd_export_set_on_eject_blk(BlockExport *exp, BlockBackend *blk);
337 
338 AioContext *nbd_export_aio_context(NBDExport *exp);
339 NBDExport *nbd_export_find(const char *name);
340 
341 void nbd_client_new(QIOChannelSocket *sioc,
342                     QCryptoTLSCreds *tlscreds,
343                     const char *tlsauthz,
344                     void (*close_fn)(NBDClient *, bool));
345 void nbd_client_get(NBDClient *client);
346 void nbd_client_put(NBDClient *client);
347 
348 void nbd_server_is_qemu_nbd(int max_connections);
349 bool nbd_server_is_running(void);
350 int nbd_server_max_connections(void);
351 void nbd_server_start(SocketAddress *addr, const char *tls_creds,
352                       const char *tls_authz, uint32_t max_connections,
353                       Error **errp);
354 void nbd_server_start_options(NbdServerOptions *arg, Error **errp);
355 
356 /* nbd_read
357  * Reads @size bytes from @ioc. Returns 0 on success.
358  */
359 static inline int nbd_read(QIOChannel *ioc, void *buffer, size_t size,
360                            const char *desc, Error **errp)
361 {
362     ERRP_GUARD();
363     int ret = qio_channel_read_all(ioc, buffer, size, errp) < 0 ? -EIO : 0;
364 
365     if (ret < 0) {
366         if (desc) {
367             error_prepend(errp, "Failed to read %s: ", desc);
368         }
369         return ret;
370     }
371 
372     return 0;
373 }
374 
375 #define DEF_NBD_READ_N(bits)                                            \
376 static inline int nbd_read##bits(QIOChannel *ioc,                       \
377                                  uint##bits##_t *val,                   \
378                                  const char *desc, Error **errp)        \
379 {                                                                       \
380     int ret = nbd_read(ioc, val, sizeof(*val), desc, errp);             \
381     if (ret < 0) {                                                      \
382         return ret;                                                     \
383     }                                                                   \
384     *val = be##bits##_to_cpu(*val);                                     \
385     return 0;                                                           \
386 }
387 
388 DEF_NBD_READ_N(16) /* Defines nbd_read16(). */
389 DEF_NBD_READ_N(32) /* Defines nbd_read32(). */
390 DEF_NBD_READ_N(64) /* Defines nbd_read64(). */
391 
392 #undef DEF_NBD_READ_N
393 
394 static inline bool nbd_reply_is_simple(NBDReply *reply)
395 {
396     return reply->magic == NBD_SIMPLE_REPLY_MAGIC;
397 }
398 
399 static inline bool nbd_reply_is_structured(NBDReply *reply)
400 {
401     return reply->magic == NBD_STRUCTURED_REPLY_MAGIC;
402 }
403 
404 const char *nbd_reply_type_lookup(uint16_t type);
405 const char *nbd_opt_lookup(uint32_t opt);
406 const char *nbd_rep_lookup(uint32_t rep);
407 const char *nbd_info_lookup(uint16_t info);
408 const char *nbd_cmd_lookup(uint16_t info);
409 const char *nbd_err_lookup(int err);
410 
411 /* nbd/client-connection.c */
412 typedef struct NBDClientConnection NBDClientConnection;
413 
414 void nbd_client_connection_enable_retry(NBDClientConnection *conn);
415 
416 NBDClientConnection *nbd_client_connection_new(const SocketAddress *saddr,
417                                                bool do_negotiation,
418                                                const char *export_name,
419                                                const char *x_dirty_bitmap,
420                                                QCryptoTLSCreds *tlscreds,
421                                                const char *tlshostname);
422 void nbd_client_connection_release(NBDClientConnection *conn);
423 
424 QIOChannel *coroutine_fn
425 nbd_co_establish_connection(NBDClientConnection *conn, NBDExportInfo *info,
426                             bool blocking, Error **errp);
427 
428 void nbd_co_establish_connection_cancel(NBDClientConnection *conn);
429 
430 #endif
431