Debian Codegraph @

src/nvme/fabrics.c

raw
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2 /*
3 * This file is part of libnvme.
4 * Copyright (c) 2020 Western Digital Corporation or its affiliates.
5 *
6 * Authors: Keith Busch <[email protected]>
7 * Chaitanya Kulkarni <[email protected]>
8 */
9
10 #include <ctype.h>
11 #include <errno.h>
12 #include <fcntl.h>
13 #include <limits.h>
14 #include <stdbool.h>
15 #include <stddef.h>
16 #include <stdlib.h>
17 #include <stdio.h>
18 #include <string.h>
19 #include <unistd.h>
20 #include <dirent.h>
21 #include <inttypes.h>
22
23 #include <sys/param.h>
24 #include <sys/stat.h>
25 #include <sys/types.h>
26 #include <arpa/inet.h>
27 #include <netdb.h>
28 #include <net/if.h>
29
30 #include <ccan/endian/endian.h>
31 #include <ccan/list/list.h>
32 #include <ccan/array_size/array_size.h>
33 #include <ccan/str/str.h>
34
35 #include "cleanup.h"
36 #include "fabrics.h"
37 #include "linux.h"
38 #include "ioctl.h"
39 #include "util.h"
40 #include "log.h"
41 #include "private.h"
42
43 #define NVMF_HOSTID_SIZE 37
44
45 #define NVMF_HOSTNQN_FILE SYSCONFDIR "/nvme/hostnqn"
46 #define NVMF_HOSTID_FILE SYSCONFDIR "/nvme/hostid"
47
48 const char *nvmf_dev = "/dev/nvme-fabrics";
49
50 /**
51 * strchomp() - Strip trailing spaces
52 * @str: String to strip
53 * @max: Maximum length of string
54 */
55 static void strchomp(char *str, int max)
56 {
57 int i;
58
59 for (i = max - 1; i >= 0 && str[i] == ' '; i--) {
60 str[i] = '\0';
61 }
62 }
63
64 const char *arg_str(const char * const *strings,
65 size_t array_size, size_t idx)
66 {
67 if (idx < array_size && strings[idx])
68 return strings[idx];
69 return "unrecognized";
70 }
71
72 const char * const trtypes[] = {
73 [NVMF_TRTYPE_RDMA] = "rdma",
74 [NVMF_TRTYPE_FC] = "fc",
75 [NVMF_TRTYPE_TCP] = "tcp",
76 [NVMF_TRTYPE_LOOP] = "loop",
77 };
78
79 const char *nvmf_trtype_str(__u8 trtype)
80 {
81 return arg_str(trtypes, ARRAY_SIZE(trtypes), trtype);
82 }
83
84 static const char * const adrfams[] = {
85 [NVMF_ADDR_FAMILY_PCI] = "pci",
86 [NVMF_ADDR_FAMILY_IP4] = "ipv4",
87 [NVMF_ADDR_FAMILY_IP6] = "ipv6",
88 [NVMF_ADDR_FAMILY_IB] = "infiniband",
89 [NVMF_ADDR_FAMILY_FC] = "fibre-channel",
90 };
91
92 const char *nvmf_adrfam_str(__u8 adrfam)
93 {
94 return arg_str(adrfams, ARRAY_SIZE(adrfams), adrfam);
95 }
96
97 static const char * const subtypes[] = {
98 [NVME_NQN_DISC] = "discovery subsystem referral",
99 [NVME_NQN_NVME] = "nvme subsystem",
100 [NVME_NQN_CURR] = "current discovery subsystem",
101 };
102
103 const char *nvmf_subtype_str(__u8 subtype)
104 {
105 return arg_str(subtypes, ARRAY_SIZE(subtypes), subtype);
106 }
107
108 static const char * const treqs[] = {
109 [NVMF_TREQ_NOT_SPECIFIED] = "not specified",
110 [NVMF_TREQ_REQUIRED] = "required",
111 [NVMF_TREQ_NOT_REQUIRED] = "not required",
112 [NVMF_TREQ_NOT_SPECIFIED |
113 NVMF_TREQ_DISABLE_SQFLOW] = "not specified, "
114 "sq flow control disable supported",
115 [NVMF_TREQ_REQUIRED |
116 NVMF_TREQ_DISABLE_SQFLOW] = "required, "
117 "sq flow control disable supported",
118 [NVMF_TREQ_NOT_REQUIRED |
119 NVMF_TREQ_DISABLE_SQFLOW] = "not required, "
120 "sq flow control disable supported",
121 };
122
123 const char *nvmf_treq_str(__u8 treq)
124 {
125 return arg_str(treqs, ARRAY_SIZE(treqs), treq);
126 }
127
128 static const char * const eflags_strings[] = {
129 [NVMF_DISC_EFLAGS_NONE] = "none",
130 [NVMF_DISC_EFLAGS_EPCSD] = "explicit discovery connections",
131 [NVMF_DISC_EFLAGS_DUPRETINFO] = "duplicate discovery information",
132 [NVMF_DISC_EFLAGS_EPCSD |
133 NVMF_DISC_EFLAGS_DUPRETINFO] = "explicit discovery connections, "
134 "duplicate discovery information",
135 [NVMF_DISC_EFLAGS_NCC] = "no cdc connectivity",
136 [NVMF_DISC_EFLAGS_EPCSD |
137 NVMF_DISC_EFLAGS_NCC] = "explicit discovery connections, "
138 "no cdc connectivity",
139 [NVMF_DISC_EFLAGS_DUPRETINFO |
140 NVMF_DISC_EFLAGS_NCC] = "duplicate discovery information, "
141 "no cdc connectivity",
142 [NVMF_DISC_EFLAGS_EPCSD |
143 NVMF_DISC_EFLAGS_DUPRETINFO |
144 NVMF_DISC_EFLAGS_NCC] = "explicit discovery connections, "
145 "duplicate discovery information, "
146 "no cdc connectivity",
147 };
148
149 const char *nvmf_eflags_str(__u16 eflags)
150 {
151 return arg_str(eflags_strings, ARRAY_SIZE(eflags_strings), eflags);
152 }
153
154 static const char * const sectypes[] = {
155 [NVMF_TCP_SECTYPE_NONE] = "none",
156 [NVMF_TCP_SECTYPE_TLS] = "tls",
157 [NVMF_TCP_SECTYPE_TLS13] = "tls13",
158 };
159
160 const char *nvmf_sectype_str(__u8 sectype)
161 {
162 return arg_str(sectypes, ARRAY_SIZE(sectypes), sectype);
163 }
164
165 static const char * const prtypes[] = {
166 [NVMF_RDMA_PRTYPE_NOT_SPECIFIED] = "not specified",
167 [NVMF_RDMA_PRTYPE_IB] = "infiniband",
168 [NVMF_RDMA_PRTYPE_ROCE] = "roce",
169 [NVMF_RDMA_PRTYPE_ROCEV2] = "roce-v2",
170 [NVMF_RDMA_PRTYPE_IWARP] = "iwarp",
171 };
172
173 const char *nvmf_prtype_str(__u8 prtype)
174 {
175 return arg_str(prtypes, ARRAY_SIZE(prtypes), prtype);
176 }
177
178 static const char * const qptypes[] = {
179 [NVMF_RDMA_QPTYPE_CONNECTED] = "connected",
180 [NVMF_RDMA_QPTYPE_DATAGRAM] = "datagram",
181 };
182
183 const char *nvmf_qptype_str(__u8 qptype)
184 {
185 return arg_str(qptypes, ARRAY_SIZE(qptypes), qptype);
186 }
187
188 static const char * const cms[] = {
189 [NVMF_RDMA_CMS_RDMA_CM] = "rdma-cm",
190 };
191
192 const char *nvmf_cms_str(__u8 cm)
193 {
194 return arg_str(cms, ARRAY_SIZE(cms), cm);
195 }
196
197 /*
198 * Derived from Linux's supported options (the opt_tokens table)
199 * when the mechanism to report supported options was added (f18ee3d988157).
200 * Not all of these options may actually be supported,
201 * but we retain the old behavior of passing all that might be.
202 */
203 static const struct nvme_fabric_options default_supported_options = {
204 .ctrl_loss_tmo = true,
205 .data_digest = true,
206 .disable_sqflow = true,
207 .discovery = true,
208 .duplicate_connect = true,
209 .fast_io_fail_tmo = true,
210 .hdr_digest = true,
211 .host_iface = true,
212 .host_traddr = true,
213 .hostid = true,
214 .hostnqn = true,
215 .keep_alive_tmo = true,
216 .nqn = true,
217 .nr_io_queues = true,
218 .nr_poll_queues = true,
219 .nr_write_queues = true,
220 .queue_size = true,
221 .reconnect_delay = true,
222 .tos = true,
223 .traddr = true,
224 .transport = true,
225 .trsvcid = true,
226 };
227
228 void nvmf_default_config(struct nvme_fabrics_config *cfg)
229 {
230 memset(cfg, 0, sizeof(*cfg));
231 cfg->tos = -1;
232 cfg->ctrl_loss_tmo = NVMF_DEF_CTRL_LOSS_TMO;
233 }
234
235 #define MERGE_CFG_OPTION(c, n, o, d) \
236 if ((c)->o == d) (c)->o = (n)->o
237 #define MERGE_CFG_OPTION_STR(c, n, o, d) \
238 if ((c)->o == d && (n)->o) (c)->o = strdup((n)->o)
239 static struct nvme_fabrics_config *merge_config(nvme_ctrl_t c,
240 const struct nvme_fabrics_config *cfg)
241 {
242 struct nvme_fabrics_config *ctrl_cfg = nvme_ctrl_get_config(c);
243
244 MERGE_CFG_OPTION_STR(ctrl_cfg, cfg, host_traddr, NULL);
245 MERGE_CFG_OPTION_STR(ctrl_cfg, cfg, host_iface, NULL);
246 MERGE_CFG_OPTION(ctrl_cfg, cfg, nr_io_queues, 0);
247 MERGE_CFG_OPTION(ctrl_cfg, cfg, nr_write_queues, 0);
248 MERGE_CFG_OPTION(ctrl_cfg, cfg, nr_poll_queues, 0);
249 MERGE_CFG_OPTION(ctrl_cfg, cfg, queue_size, 0);
250 MERGE_CFG_OPTION(ctrl_cfg, cfg, keep_alive_tmo, 0);
251 MERGE_CFG_OPTION(ctrl_cfg, cfg, reconnect_delay, 0);
252 MERGE_CFG_OPTION(ctrl_cfg, cfg, ctrl_loss_tmo,
253 NVMF_DEF_CTRL_LOSS_TMO);
254 MERGE_CFG_OPTION(ctrl_cfg, cfg, fast_io_fail_tmo, 0);
255 MERGE_CFG_OPTION(ctrl_cfg, cfg, tos, -1);
256 MERGE_CFG_OPTION(ctrl_cfg, cfg, keyring, 0);
257 MERGE_CFG_OPTION(ctrl_cfg, cfg, tls_key, 0);
258 MERGE_CFG_OPTION(ctrl_cfg, cfg, duplicate_connect, false);
259 MERGE_CFG_OPTION(ctrl_cfg, cfg, disable_sqflow, false);
260 MERGE_CFG_OPTION(ctrl_cfg, cfg, hdr_digest, false);
261 MERGE_CFG_OPTION(ctrl_cfg, cfg, data_digest, false);
262 MERGE_CFG_OPTION(ctrl_cfg, cfg, tls, false);
263 MERGE_CFG_OPTION(ctrl_cfg, cfg, concat, false);
264
265 return ctrl_cfg;
266 }
267
268 #define UPDATE_CFG_OPTION(c, n, o, d) \
269 if ((n)->o != d) (c)->o = (n)->o
270 void nvmf_update_config(nvme_ctrl_t c, const struct nvme_fabrics_config *cfg)
271 {
272 struct nvme_fabrics_config *ctrl_cfg = nvme_ctrl_get_config(c);
273
274 UPDATE_CFG_OPTION(ctrl_cfg, cfg, host_traddr, NULL);
275 UPDATE_CFG_OPTION(ctrl_cfg, cfg, host_iface, NULL);
276 UPDATE_CFG_OPTION(ctrl_cfg, cfg, nr_io_queues, 0);
277 UPDATE_CFG_OPTION(ctrl_cfg, cfg, nr_write_queues, 0);
278 UPDATE_CFG_OPTION(ctrl_cfg, cfg, nr_poll_queues, 0);
279 UPDATE_CFG_OPTION(ctrl_cfg, cfg, queue_size, 0);
280 UPDATE_CFG_OPTION(ctrl_cfg, cfg, keep_alive_tmo, 0);
281 UPDATE_CFG_OPTION(ctrl_cfg, cfg, reconnect_delay, 0);
282 UPDATE_CFG_OPTION(ctrl_cfg, cfg, ctrl_loss_tmo,
283 NVMF_DEF_CTRL_LOSS_TMO);
284 UPDATE_CFG_OPTION(ctrl_cfg, cfg, fast_io_fail_tmo, 0);
285 UPDATE_CFG_OPTION(ctrl_cfg, cfg, tos, -1);
286 UPDATE_CFG_OPTION(ctrl_cfg, cfg, keyring, 0);
287 UPDATE_CFG_OPTION(ctrl_cfg, cfg, tls_key, 0);
288 UPDATE_CFG_OPTION(ctrl_cfg, cfg, duplicate_connect, false);
289 UPDATE_CFG_OPTION(ctrl_cfg, cfg, disable_sqflow, false);
290 UPDATE_CFG_OPTION(ctrl_cfg, cfg, hdr_digest, false);
291 UPDATE_CFG_OPTION(ctrl_cfg, cfg, data_digest, false);
292 UPDATE_CFG_OPTION(ctrl_cfg, cfg, tls, false);
293 UPDATE_CFG_OPTION(ctrl_cfg, cfg, concat, false);
294 }
295
296 static int __add_bool_argument(char **argstr, char *tok, bool arg)
297 {
298 char *nstr;
299
300 if (!arg)
301 return 0;
302 if (asprintf(&nstr, "%s,%s", *argstr, tok) < 0) {
303 errno = ENOMEM;
304 return -1;
305 }
306 free(*argstr);
307 *argstr = nstr;
308
309 return 0;
310 }
311
312 static int __add_hex_argument(char **argstr, char *tok, int arg, bool allow_zero)
313 {
314 char *nstr;
315
316 if (arg < 0 || (!arg && !allow_zero))
317 return 0;
318 if (asprintf(&nstr, "%s,%s=0x%08x", *argstr, tok, arg) < 0) {
319 errno = ENOMEM;
320 return -1;
321 }
322 free(*argstr);
323 *argstr = nstr;
324
325 return 0;
326 }
327
328 static int __add_int_argument(char **argstr, char *tok, int arg, bool allow_zero)
329 {
330 char *nstr;
331
332 if (arg < 0 || (!arg && !allow_zero))
333 return 0;
334 if (asprintf(&nstr, "%s,%s=%d", *argstr, tok, arg) < 0) {
335 errno = ENOMEM;
336 return -1;
337 }
338 free(*argstr);
339 *argstr = nstr;
340
341 return 0;
342 }
343
344 static int __add_int_or_minus_one_argument(char **argstr, char *tok, int arg)
345 {
346 char *nstr;
347
348 if (arg < -1)
349 return 0;
350 if (asprintf(&nstr, "%s,%s=%d", *argstr, tok, arg) < 0) {
351 errno = ENOMEM;
352 return -1;
353 }
354 free(*argstr);
355 *argstr = nstr;
356
357 return 0;
358 }
359
360 static int __add_argument(char **argstr, const char *tok, const char *arg)
361 {
362 char *nstr;
363
364 if (!arg || arg[0] == '\0' || !strcmp(arg, "none"))
365 return 0;
366 if (asprintf(&nstr, "%s,%s=%s", *argstr, tok, arg) < 0) {
367 errno = ENOMEM;
368 return -1;
369 }
370 free(*argstr);
371 *argstr = nstr;
372
373 return 0;
374 }
375
376 static int __nvmf_supported_options(nvme_root_t r);
377 #define nvmf_check_option(r, tok) \
378 ({ \
379 !__nvmf_supported_options(r) && (r)->options->tok; \
380 })
381
382 #define add_bool_argument(r, argstr, tok, arg) \
383 ({ \
384 int ret; \
385 if (nvmf_check_option(r, tok)) { \
386 ret = __add_bool_argument(argstr, \
387 stringify(tok), \
388 arg); \
389 } else { \
390 nvme_msg(r, LOG_DEBUG, \
391 "option \"%s\" ignored\n", \
392 stringify(tok)); \
393 ret = 0; \
394 } \
395 ret; \
396 })
397
398 #define add_hex_argument(r, argstr, tok, arg, allow_zero) \
399 ({ \
400 int ret; \
401 if (nvmf_check_option(r, tok)) { \
402 ret = __add_hex_argument(argstr, \
403 stringify(tok), \
404 arg, \
405 allow_zero); \
406 } else { \
407 nvme_msg(r, LOG_DEBUG, \
408 "option \"%s\" ignored\n", \
409 stringify(tok)); \
410 ret = 0; \
411 } \
412 ret; \
413 })
414
415 #define add_int_argument(r, argstr, tok, arg, allow_zero) \
416 ({ \
417 int ret; \
418 if (nvmf_check_option(r, tok)) { \
419 ret = __add_int_argument(argstr, \
420 stringify(tok), \
421 arg, \
422 allow_zero); \
423 } else { \
424 nvme_msg(r, LOG_DEBUG, \
425 "option \"%s\" ignored\n", \
426 stringify(tok)); \
427 ret = 0; \
428 } \
429 ret; \
430 })
431
432 #define add_int_or_minus_one_argument(r, argstr, tok, arg) \
433 ({ \
434 int ret; \
435 if (nvmf_check_option(r, tok)) { \
436 ret = __add_int_or_minus_one_argument(argstr, \
437 stringify(tok), \
438 arg); \
439 } else { \
440 nvme_msg(r, LOG_DEBUG, \
441 "option \"%s\" ignored\n", \
442 stringify(tok)); \
443 ret = 0; \
444 } \
445 ret; \
446 })
447
448 #define add_argument(r, argstr, tok, arg) \
449 ({ \
450 int ret; \
451 if (nvmf_check_option(r, tok)) { \
452 ret = __add_argument(argstr, \
453 stringify(tok), \
454 arg); \
455 } else { \
456 nvme_msg(r, LOG_NOTICE, \
457 "option \"%s\" ignored\n", \
458 stringify(tok)); \
459 ret = 0; \
460 } \
461 ret; \
462 })
463
464 static int inet4_pton(const char *src, uint16_t port,
465 struct sockaddr_storage *addr)
466 {
467 struct sockaddr_in *addr4 = (struct sockaddr_in *)addr;
468
469 if (strlen(src) > INET_ADDRSTRLEN)
470 return -EINVAL;
471
472 if (inet_pton(AF_INET, src, &addr4->sin_addr.s_addr) <= 0)
473 return -EINVAL;
474
475 addr4->sin_family = AF_INET;
476 addr4->sin_port = htons(port);
477
478 return 0;
479 }
480
481 static int inet6_pton(nvme_root_t r, const char *src, uint16_t port,
482 struct sockaddr_storage *addr)
483 {
484 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)addr;
485 const char *scope = NULL;
486 char *p;
487
488 if (strlen(src) > INET6_ADDRSTRLEN)
489 return -EINVAL;
490
491 _cleanup_free_ char *tmp = strdup(src);
492 if (!tmp) {
493 nvme_msg(r, LOG_ERR, "cannot copy: %s\n", src);
494 return -ENOMEM;
495 }
496
497 p = strchr(tmp, '%');
498 if (p) {
499 *p = '\0';
500 scope = src + (p - tmp) + 1;
501 }
502
503 if (inet_pton(AF_INET6, tmp, &addr6->sin6_addr) != 1)
504 return -EINVAL;
505
506 if (IN6_IS_ADDR_LINKLOCAL(&addr6->sin6_addr) && scope) {
507 addr6->sin6_scope_id = if_nametoindex(scope);
508 if (addr6->sin6_scope_id == 0) {
509 nvme_msg(r, LOG_ERR,
510 "can't find iface index for: %s (%m)\n", scope);
511 return -EINVAL;
512 }
513 }
514
515 addr6->sin6_family = AF_INET6;
516 addr6->sin6_port = htons(port);
517 return 0;
518 }
519
520 /**
521 * inet_pton_with_scope - convert an IPv4/IPv6 to socket address
522 * @r: nvme_root_t object
523 * @af: address family, AF_INET, AF_INET6 or AF_UNSPEC for either
524 * @src: the start of the address string
525 * @trsvcid: transport service identifier
526 * @addr: output socket address
527 *
528 * Return 0 on success, errno otherwise.
529 */
530 static int inet_pton_with_scope(nvme_root_t r, int af,
531 const char *src, const char * trsvcid,
532 struct sockaddr_storage *addr)
533 {
534 int ret = -EINVAL;
535 uint16_t port = 0;
536
537 if (trsvcid) {
538 unsigned long long tmp = strtoull(trsvcid, NULL, 0);
539 port = (uint16_t)tmp;
540 if (tmp != port) {
541 nvme_msg(r, LOG_ERR, "trsvcid out of range: %s\n",
542 trsvcid);
543 return -ERANGE;
544 }
545 } else {
546 port = 0;
547 }
548
549 switch (af) {
550 case AF_INET:
551 ret = inet4_pton(src, port, addr);
552 break;
553 case AF_INET6:
554 ret = inet6_pton(r, src, port, addr);
555 break;
556 case AF_UNSPEC:
557 ret = inet4_pton(src, port, addr);
558 if (ret)
559 ret = inet6_pton(r, src, port, addr);
560 break;
561 default:
562 nvme_msg(r, LOG_ERR, "unexpected address family %d\n", af);
563 }
564
565 return ret;
566 }
567
568 static bool traddr_is_hostname(nvme_root_t r, nvme_ctrl_t c)
569 {
570 struct sockaddr_storage addr;
571
572 if (!c->traddr)
573 return false;
574 if (strcmp(c->transport, "tcp") && strcmp(c->transport, "rdma"))
575 return false;
576 if (inet_pton_with_scope(r, AF_UNSPEC, c->traddr, c->trsvcid, &addr) == 0)
577 return false;
578 return true;
579 }
580
581 static int build_options(nvme_host_t h, nvme_ctrl_t c, char **argstr)
582 {
583 struct nvme_fabrics_config *cfg = nvme_ctrl_get_config(c);
584 const char *transport = nvme_ctrl_get_transport(c);
585 const char *hostnqn, *hostid, *hostkey, *ctrlkey;
586 bool discover = false, discovery_nqn = false;
587 nvme_root_t r = h->r;
588 long keyring_id = 0;
589 long key_id = 0;
590 int ret;
591
592 if (!transport) {
593 nvme_msg(h->r, LOG_ERR, "need a transport (-t) argument\n");
594 errno = ENVME_CONNECT_TARG;
595 return -1;
596 }
597
598 if (strncmp(transport, "loop", 4)) {
599 if (!nvme_ctrl_get_traddr(c)) {
600 nvme_msg(h->r, LOG_ERR, "need a address (-a) argument\n");
601 errno = ENVME_CONNECT_AARG;
602 return -1;
603 }
604 }
605
606 /* always specify nqn as first arg - this will init the string */
607 if (asprintf(argstr, "nqn=%s",
608 nvme_ctrl_get_subsysnqn(c)) < 0) {
609 errno = ENOMEM;
610 return -1;
611 }
612
613 if (!strcmp(nvme_ctrl_get_subsysnqn(c), NVME_DISC_SUBSYS_NAME)) {
614 nvme_ctrl_set_discovery_ctrl(c, true);
615 nvme_ctrl_set_unique_discovery_ctrl(c, false);
616 discovery_nqn = true;
617 }
618
619 if (nvme_ctrl_is_discovery_ctrl(c))
620 discover = true;
621
622 hostnqn = nvme_host_get_hostnqn(h);
623 hostid = nvme_host_get_hostid(h);
624 hostkey = nvme_host_get_dhchap_key(h);
625 if (!hostkey)
626 hostkey = nvme_ctrl_get_dhchap_host_key(c);
627
628 ctrlkey = nvme_ctrl_get_dhchap_key(c);
629
630 if (cfg->tls) {
631 ret = __nvme_import_keys_from_config(h, c, &keyring_id, &key_id);
632 if (ret) {
633 errno = -ret;
634 return -1;
635 }
636
637 if (key_id == 0) {
638 if (cfg->tls_configured_key)
639 key_id = cfg->tls_configured_key;
640 else
641 key_id = cfg->tls_key;
642 }
643 }
644
645 if (add_argument(r, argstr, transport, transport) ||
646 add_argument(r, argstr, traddr,
647 nvme_ctrl_get_traddr(c)) ||
648 add_argument(r, argstr, host_traddr,
649 cfg->host_traddr) ||
650 add_argument(r, argstr, host_iface,
651 cfg->host_iface) ||
652 add_argument(r, argstr, trsvcid,
653 nvme_ctrl_get_trsvcid(c)) ||
654 (hostnqn && add_argument(r, argstr, hostnqn, hostnqn)) ||
655 (hostid && add_argument(r, argstr, hostid, hostid)) ||
656 (discover && !discovery_nqn &&
657 add_bool_argument(r, argstr, discovery, true)) ||
658 (!discover && hostkey &&
659 add_argument(r, argstr, dhchap_secret, hostkey)) ||
660 (!discover && ctrlkey &&
661 add_argument(r, argstr, dhchap_ctrl_secret, ctrlkey)) ||
662 (!discover &&
663 add_int_argument(r, argstr, nr_io_queues,
664 cfg->nr_io_queues, false)) ||
665 (!discover &&
666 add_int_argument(r, argstr, nr_write_queues,
667 cfg->nr_write_queues, false)) ||
668 (!discover &&
669 add_int_argument(r, argstr, nr_poll_queues,
670 cfg->nr_poll_queues, false)) ||
671 (!discover &&
672 add_int_argument(r, argstr, queue_size,
673 cfg->queue_size, false)) ||
674 add_int_argument(r, argstr, keep_alive_tmo,
675 cfg->keep_alive_tmo, false) ||
676 add_int_argument(r, argstr, reconnect_delay,
677 cfg->reconnect_delay, false) ||
678 (strcmp(transport, "loop") &&
679 add_int_or_minus_one_argument(r, argstr, ctrl_loss_tmo,
680 cfg->ctrl_loss_tmo)) ||
681 (strcmp(transport, "loop") &&
682 add_int_argument(r, argstr, fast_io_fail_tmo,
683 cfg->fast_io_fail_tmo, false)) ||
684 (strcmp(transport, "loop") &&
685 add_int_argument(r, argstr, tos, cfg->tos, true)) ||
686 add_hex_argument(r, argstr, keyring, keyring_id, false) ||
687 (!strcmp(transport, "tcp") &&
688 add_hex_argument(r, argstr, tls_key, key_id, false)) ||
689 add_bool_argument(r, argstr, duplicate_connect,
690 cfg->duplicate_connect) ||
691 add_bool_argument(r, argstr, disable_sqflow,
692 cfg->disable_sqflow) ||
693 (!strcmp(transport, "tcp") &&
694 add_bool_argument(r, argstr, hdr_digest, cfg->hdr_digest)) ||
695 (!strcmp(transport, "tcp") &&
696 add_bool_argument(r, argstr, data_digest, cfg->data_digest)) ||
697 (!strcmp(transport, "tcp") &&
698 add_bool_argument(r, argstr, tls, cfg->tls)) ||
699 (!strcmp(transport, "tcp") &&
700 add_bool_argument(r, argstr, concat, cfg->concat))) {
701 free(*argstr);
702 return -1;
703 }
704
705 return 0;
706 }
707
708 #define parse_option(r, v, name) \
709 if (!strcmp(v, stringify(name))) { \
710 r->options->name = true; \
711 continue; \
712 }
713
714 static int __nvmf_supported_options(nvme_root_t r)
715 {
716 char buf[0x1000], *options, *p, *v;
717 _cleanup_fd_ int fd = -1;
718 ssize_t len;
719
720 if (r->options)
721 return 0;
722
723 r->options = calloc(1, sizeof(*r->options));
724 if (!r->options)
725 return -ENOMEM;
726
727 fd = open(nvmf_dev, O_RDONLY);
728 if (fd < 0) {
729 nvme_msg(r, LOG_ERR, "Failed to open %s: %s\n",
730 nvmf_dev, strerror(errno));
731 return -ENVME_CONNECT_OPEN;
732 }
733
734 memset(buf, 0x0, sizeof(buf));
735 len = read(fd, buf, sizeof(buf) - 1);
736 if (len < 0) {
737 if (errno == EINVAL) {
738 /*
739 * Older Linux kernels don't allow reading from nvmf_dev
740 * to get supported options, so use a default set
741 */
742 nvme_msg(r, LOG_DEBUG,
743 "Cannot read %s, using default options\n",
744 nvmf_dev);
745 *r->options = default_supported_options;
746 return 0;
747 }
748
749 nvme_msg(r, LOG_ERR, "Failed to read from %s: %s\n",
750 nvmf_dev, strerror(errno));
751 return -ENVME_CONNECT_READ;
752 }
753
754 buf[len] = '\0';
755 options = buf;
756
757 nvme_msg(r, LOG_DEBUG, "kernel supports: ");
758
759 while ((p = strsep(&options, ",\n")) != NULL) {
760 if (!*p)
761 continue;
762 v = strsep(&p, "= ");
763 if (!v)
764 continue;
765 nvme_msg(r, LOG_DEBUG, "%s ", v);
766
767 parse_option(r, v, cntlid);
768 parse_option(r, v, concat);
769 parse_option(r, v, ctrl_loss_tmo);
770 parse_option(r, v, data_digest);
771 parse_option(r, v, dhchap_ctrl_secret);
772 parse_option(r, v, dhchap_secret);
773 parse_option(r, v, disable_sqflow);
774 parse_option(r, v, discovery);
775 parse_option(r, v, duplicate_connect);
776 parse_option(r, v, fast_io_fail_tmo);
777 parse_option(r, v, hdr_digest);
778 parse_option(r, v, host_iface);
779 parse_option(r, v, host_traddr);
780 parse_option(r, v, hostid);
781 parse_option(r, v, hostnqn);
782 parse_option(r, v, instance);
783 parse_option(r, v, keep_alive_tmo);
784 parse_option(r, v, keyring);
785 parse_option(r, v, nqn);
786 parse_option(r, v, nr_io_queues);
787 parse_option(r, v, nr_poll_queues);
788 parse_option(r, v, nr_write_queues);
789 parse_option(r, v, queue_size);
790 parse_option(r, v, reconnect_delay);
791 parse_option(r, v, tls);
792 parse_option(r, v, tls_key);
793 parse_option(r, v, tos);
794 parse_option(r, v, traddr);
795 parse_option(r, v, transport);
796 parse_option(r, v, trsvcid);
797 }
798 nvme_msg(r, LOG_DEBUG, "\n");
799 return 0;
800 }
801
802 static int __nvmf_add_ctrl(nvme_root_t r, const char *argstr)
803 {
804 _cleanup_fd_ int fd = -1;
805 int ret, len = strlen(argstr);
806 char buf[0x1000], *options, *p;
807
808 fd = open(nvmf_dev, O_RDWR);
809 if (fd < 0) {
810 nvme_msg(r, LOG_ERR, "Failed to open %s: %s\n",
811 nvmf_dev, strerror(errno));
812 return -ENVME_CONNECT_OPEN;
813 }
814
815 nvme_msg(r, LOG_DEBUG, "connect ctrl, '%.*s'\n",
816 (int)strcspn(argstr,"\n"), argstr);
817 ret = write(fd, argstr, len);
818 if (ret != len) {
819 nvme_msg(r, LOG_INFO, "Failed to write to %s: %s\n",
820 nvmf_dev, strerror(errno));
821 switch (errno) {
822 case EALREADY:
823 return -ENVME_CONNECT_ALREADY;
824 case EINVAL:
825 return -ENVME_CONNECT_INVAL;
826 case EADDRINUSE:
827 return -ENVME_CONNECT_ADDRINUSE;
828 case ENODEV:
829 return -ENVME_CONNECT_NODEV;
830 case EOPNOTSUPP:
831 return -ENVME_CONNECT_OPNOTSUPP;
832 case ECONNREFUSED:
833 return -ENVME_CONNECT_CONNREFUSED;
834 case EADDRNOTAVAIL:
835 return -ENVME_CONNECT_ADDRNOTAVAIL;
836 case ENOKEY:
837 return -ENVME_CONNECT_NOKEY;
838 default:
839 return -ENVME_CONNECT_WRITE;
840 }
841 }
842
843 memset(buf, 0x0, sizeof(buf));
844 len = read(fd, buf, sizeof(buf) - 1);
845 if (len < 0) {
846 nvme_msg(r, LOG_ERR, "Failed to read from %s: %s\n",
847 nvmf_dev, strerror(errno));
848 return -ENVME_CONNECT_READ;
849 }
850 nvme_msg(r, LOG_DEBUG, "connect ctrl, response '%.*s'\n",
851 (int)strcspn(buf, "\n"), buf);
852 buf[len] = '\0';
853 options = buf;
854 while ((p = strsep(&options, ",\n")) != NULL) {
855 if (!*p)
856 continue;
857 if (sscanf(p, "instance=%d", &ret) == 1)
858 return ret;
859 }
860
861 nvme_msg(r, LOG_ERR, "Failed to parse ctrl info for \"%s\"\n", argstr);
862 return -ENVME_CONNECT_PARSE;
863 }
864
865 static const char *lookup_context(nvme_root_t r, nvme_ctrl_t c)
866 {
867
868 nvme_host_t h;
869 nvme_subsystem_t s;
870
871 nvme_for_each_host(r, h) {
872 nvme_for_each_subsystem(h, s) {
873 if (__nvme_lookup_ctrl(s, nvme_ctrl_get_transport(c),
874 nvme_ctrl_get_traddr(c),
875 NULL,
876 NULL,
877 nvme_ctrl_get_trsvcid(c),
878 NULL,
879 NULL))
880 return nvme_subsystem_get_application(s);
881 }
882 }
883
884 return NULL;
885 }
886
887 int nvmf_add_ctrl(nvme_host_t h, nvme_ctrl_t c,
888 const struct nvme_fabrics_config *cfg)
889 {
890 nvme_subsystem_t s;
891 const char *root_app, *app;
892 _cleanup_free_ char *argstr = NULL;
893 int ret;
894
895 /* highest prio have configs from command line */
896 cfg = merge_config(c, cfg);
897
898 /* apply configuration from config file (JSON) */
899 s = nvme_lookup_subsystem(h, NULL, nvme_ctrl_get_subsysnqn(c));
900 if (s) {
901 nvme_ctrl_t fc;
902
903 fc = __nvme_lookup_ctrl(s, nvme_ctrl_get_transport(c),
904 nvme_ctrl_get_traddr(c),
905 nvme_ctrl_get_host_traddr(c),
906 nvme_ctrl_get_host_iface(c),
907 nvme_ctrl_get_trsvcid(c),
908 NULL,
909 NULL);
910 if (fc) {
911 const char *key;
912
913 cfg = merge_config(c, nvme_ctrl_get_config(fc));
914 /*
915 * An authentication key might already been set
916 * in @cfg, so ensure to update @c with the correct
917 * controller key.
918 */
919 key = nvme_ctrl_get_dhchap_host_key(fc);
920 if (key)
921 nvme_ctrl_set_dhchap_host_key(c, key);
922 key = nvme_ctrl_get_dhchap_key(fc);
923 if (key)
924 nvme_ctrl_set_dhchap_key(c, key);
925 key = nvme_ctrl_get_keyring(fc);
926 if (key)
927 nvme_ctrl_set_keyring(c, key);
928 key = nvme_ctrl_get_tls_key_identity(fc);
929 if (key)
930 nvme_ctrl_set_tls_key_identity(c, key);
931 key = nvme_ctrl_get_tls_key(fc);
932 if (key)
933 nvme_ctrl_set_tls_key(c, key);
934 }
935
936 }
937
938 root_app = nvme_root_get_application(h->r);
939 if (root_app) {
940 app = nvme_subsystem_get_application(s);
941 if (!app && nvme_ctrl_is_discovery_ctrl(c))
942 app = lookup_context(h->r, c);
943
944 /*
945 * configuration is managed by an application,
946 * refuse to act on subsystems which either have
947 * no application set or which habe a different
948 * application string.
949 */
950 if (app && strcmp(app, root_app)) {
951 nvme_msg(h->r, LOG_INFO, "skip %s, not managed by %s\n",
952 nvme_subsystem_get_nqn(s), root_app);
953 errno = ENVME_CONNECT_IGNORED;
954 return -1;
955 }
956 }
957
958 nvme_ctrl_set_discovered(c, true);
959 if (traddr_is_hostname(h->r, c)) {
960 char *traddr = c->traddr;
961
962 c->traddr = hostname2traddr(h->r, traddr);
963 if (!c->traddr) {
964 c->traddr = traddr;
965 errno = ENVME_CONNECT_TRADDR;
966 return -1;
967 }
968 free(traddr);
969 }
970
971 ret = build_options(h, c, &argstr);
972 if (ret)
973 return ret;
974
975 ret = __nvmf_add_ctrl(h->r, argstr);
976 if (ret < 0) {
977 errno = -ret;
978 return -1;
979 }
980
981 nvme_msg(h->r, LOG_INFO, "nvme%d: %s connected\n", ret,
982 nvme_ctrl_get_subsysnqn(c));
983 return nvme_init_ctrl(h, c, ret);
984 }
985
986 int nvmf_connect_ctrl(nvme_ctrl_t c)
987 {
988 _cleanup_free_ char *argstr = NULL;
989 int ret;
990
991 ret = build_options(c->s->h, c, &argstr);
992 if (ret)
993 return ret;
994
995 ret = __nvmf_add_ctrl(c->s->h->r, argstr);
996 if (ret < 0) {
997 errno = -ret;
998 return -1;
999 }
1000
1001 return 0;
1002 }
1003
1004 nvme_ctrl_t nvmf_connect_disc_entry(nvme_host_t h,
1005 struct nvmf_disc_log_entry *e,
1006 const struct nvme_fabrics_config *cfg,
1007 bool *discover)
1008 {
1009 const char *transport;
1010 char *traddr = NULL, *trsvcid = NULL;
1011 nvme_ctrl_t c;
1012 int ret;
1013
1014 switch (e->trtype) {
1015 case NVMF_TRTYPE_RDMA:
1016 case NVMF_TRTYPE_TCP:
1017 switch (e->adrfam) {
1018 case NVMF_ADDR_FAMILY_IP4:
1019 case NVMF_ADDR_FAMILY_IP6:
1020 traddr = e->traddr;
1021 trsvcid = e->trsvcid;
1022 break;
1023 default:
1024 nvme_msg(h->r, LOG_ERR,
1025 "skipping unsupported adrfam %d\n",
1026 e->adrfam);
1027 errno = EINVAL;
1028 return NULL;
1029 }
1030 break;
1031 case NVMF_TRTYPE_FC:
1032 switch (e->adrfam) {
1033 case NVMF_ADDR_FAMILY_FC:
1034 traddr = e->traddr;
1035 break;
1036 default:
1037 nvme_msg(h->r, LOG_ERR,
1038 "skipping unsupported adrfam %d\n",
1039 e->adrfam);
1040 errno = EINVAL;
1041 return NULL;
1042 }
1043 break;
1044 case NVMF_TRTYPE_LOOP:
1045 traddr = strlen(e->traddr) ? e->traddr : NULL;
1046 break;
1047 default:
1048 nvme_msg(h->r, LOG_ERR, "skipping unsupported transport %d\n",
1049 e->trtype);
1050 errno = EINVAL;
1051 return NULL;
1052 }
1053
1054 transport = nvmf_trtype_str(e->trtype);
1055
1056 nvme_msg(h->r, LOG_DEBUG, "lookup ctrl "
1057 "(transport: %s, traddr: %s, trsvcid %s)\n",
1058 transport, traddr, trsvcid);
1059 c = nvme_create_ctrl(h->r, e->subnqn, transport, traddr,
1060 cfg->host_traddr, cfg->host_iface, trsvcid);
1061 if (!c) {
1062 nvme_msg(h->r, LOG_DEBUG, "skipping discovery entry, "
1063 "failed to allocate %s controller with traddr %s\n",
1064 transport, traddr);
1065 errno = ENOMEM;
1066 return NULL;
1067 }
1068
1069 switch (e->subtype) {
1070 case NVME_NQN_CURR:
1071 nvme_ctrl_set_discovered(c, true);
1072 nvme_ctrl_set_unique_discovery_ctrl(c,
1073 strcmp(e->subnqn, NVME_DISC_SUBSYS_NAME));
1074 break;
1075 case NVME_NQN_DISC:
1076 if (discover)
1077 *discover = true;
1078 nvme_ctrl_set_discovery_ctrl(c, true);
1079 nvme_ctrl_set_unique_discovery_ctrl(c,
1080 strcmp(e->subnqn, NVME_DISC_SUBSYS_NAME));
1081 break;
1082 default:
1083 nvme_msg(h->r, LOG_ERR, "unsupported subtype %d\n",
1084 e->subtype);
1085 fallthrough;
1086 case NVME_NQN_NVME:
1087 nvme_ctrl_set_discovery_ctrl(c, false);
1088 nvme_ctrl_set_unique_discovery_ctrl(c, false);
1089 break;
1090 }
1091
1092 if (nvme_ctrl_is_discovered(c)) {
1093 nvme_free_ctrl(c);
1094 errno = EAGAIN;
1095 return NULL;
1096 }
1097
1098 if (e->treq & NVMF_TREQ_DISABLE_SQFLOW &&
1099 nvmf_check_option(h->r, disable_sqflow))
1100 c->cfg.disable_sqflow = true;
1101
1102 if (e->trtype == NVMF_TRTYPE_TCP &&
1103 e->tsas.tcp.sectype != NVMF_TCP_SECTYPE_NONE)
1104 c->cfg.tls = true;
1105
1106 ret = nvmf_add_ctrl(h, c, cfg);
1107 if (!ret)
1108 return c;
1109
1110 if (errno == EINVAL && c->cfg.disable_sqflow) {
1111 errno = 0;
1112 /* disable_sqflow is unrecognized option on older kernels */
1113 nvme_msg(h->r, LOG_INFO, "failed to connect controller, "
1114 "retry with disabling SQ flow control\n");
1115 c->cfg.disable_sqflow = false;
1116 ret = nvmf_add_ctrl(h, c, cfg);
1117 if (!ret)
1118 return c;
1119 }
1120 nvme_free_ctrl(c);
1121 return NULL;
1122 }
1123
1124 /*
1125 * Most of nvmf_discovery_log is reserved, so only fetch the initial bytes.
1126 * 8 bytes for GENCTR, 8 for NUMREC, and 2 for RECFMT.
1127 * Since only multiples of 4 bytes are allowed, round 18 up to 20.
1128 */
1129 #define DISCOVERY_HEADER_LEN 20
1130
1131 static struct nvmf_discovery_log *nvme_discovery_log(
1132 const struct nvme_get_discovery_args *args)
1133 {
1134 nvme_root_t r = root_from_ctrl(args->c);
1135 struct nvmf_discovery_log *log;
1136 int retries = 0;
1137 int err;
1138 const char *name = nvme_ctrl_get_name(args->c);
1139 uint64_t genctr, numrec;
1140 int fd = nvme_ctrl_get_fd(args->c);
1141 struct nvme_get_log_args log_args = {
1142 .result = args->result,
1143 .args_size = sizeof(log_args),
1144 .timeout = args->timeout,
1145 .lid = NVME_LOG_LID_DISCOVER,
1146 .nsid = NVME_NSID_NONE,
1147 .csi = NVME_CSI_NVM,
1148 .lsi = NVME_LOG_LSI_NONE,
1149 .lsp = args->lsp,
1150 .uuidx = NVME_UUID_NONE,
1151 };
1152
1153 log = __nvme_alloc(sizeof(*log));
1154 if (!log) {
1155 nvme_msg(r, LOG_ERR,
1156 "could not allocate memory for discovery log header\n");
1157 errno = ENOMEM;
1158 return NULL;
1159 }
1160
1161 nvme_msg(r, LOG_DEBUG, "%s: get header (try %d/%d)\n",
1162 name, retries, args->max_retries);
1163 log_args.log = log;
1164 log_args.len = DISCOVERY_HEADER_LEN;
1165 err = nvme_get_log_page(fd, NVME_LOG_PAGE_PDU_SIZE, &log_args);
1166 if (err) {
1167 nvme_msg(r, LOG_INFO,
1168 "%s: discover try %d/%d failed, errno %d status 0x%x\n",
1169 name, retries, args->max_retries, errno, err);
1170 goto out_free_log;
1171 }
1172
1173 do {
1174 size_t entries_size;
1175
1176 numrec = le64_to_cpu(log->numrec);
1177 genctr = le64_to_cpu(log->genctr);
1178
1179 if (numrec == 0)
1180 break;
1181
1182 free(log);
1183 entries_size = sizeof(*log->entries) * numrec;
1184 log = __nvme_alloc(sizeof(*log) + entries_size);
1185 if (!log) {
1186 nvme_msg(r, LOG_ERR,
1187 "could not alloc memory for discovery log page\n");
1188 errno = ENOMEM;
1189 return NULL;
1190 }
1191
1192 nvme_msg(r, LOG_DEBUG,
1193 "%s: get %" PRIu64 " records (genctr %" PRIu64 ")\n",
1194 name, numrec, genctr);
1195
1196 log_args.lpo = sizeof(*log);
1197 log_args.log = log->entries;
1198 log_args.len = entries_size;
1199 err = nvme_get_log_page(fd, NVME_LOG_PAGE_PDU_SIZE, &log_args);
1200 if (err) {
1201 nvme_msg(r, LOG_INFO,
1202 "%s: discover try %d/%d failed, errno %d status 0x%x\n",
1203 name, retries, args->max_retries, errno, err);
1204 goto out_free_log;
1205 }
1206
1207 /*
1208 * If the log page was read with multiple Get Log Page commands,
1209 * genctr must be checked afterwards to ensure atomicity
1210 */
1211 nvme_msg(r, LOG_DEBUG, "%s: get header again\n", name);
1212
1213 log_args.lpo = 0;
1214 log_args.log = log;
1215 log_args.len = DISCOVERY_HEADER_LEN;
1216 err = nvme_get_log_page(fd, NVME_LOG_PAGE_PDU_SIZE, &log_args);
1217 if (err) {
1218 nvme_msg(r, LOG_INFO,
1219 "%s: discover try %d/%d failed, errno %d status 0x%x\n",
1220 name, retries, args->max_retries, errno, err);
1221 goto out_free_log;
1222 }
1223 } while (genctr != le64_to_cpu(log->genctr) &&
1224 ++retries < args->max_retries);
1225
1226 if (genctr != le64_to_cpu(log->genctr)) {
1227 nvme_msg(r, LOG_INFO, "%s: discover genctr mismatch\n", name);
1228 errno = EAGAIN;
1229 } else if (numrec != le64_to_cpu(log->numrec)) {
1230 nvme_msg(r, LOG_INFO,
1231 "%s: numrec changed unexpectedly "
1232 "from %" PRIu64 " to %" PRIu64 "\n",
1233 name, numrec, le64_to_cpu(log->numrec));
1234 errno = EBADSLT;
1235 } else {
1236 return log;
1237 }
1238
1239 out_free_log:
1240 free(log);
1241 if (!errno)
1242 errno = nvme_status_to_errno(err, true);
1243 return NULL;
1244 }
1245
1246 static void sanitize_discovery_log_entry(struct nvmf_disc_log_entry *e)
1247 {
1248 strchomp(e->trsvcid, sizeof(e->trsvcid));
1249 strchomp(e->traddr, sizeof(e->traddr));
1250 }
1251
1252 int nvmf_get_discovery_log(nvme_ctrl_t c, struct nvmf_discovery_log **logp,
1253 int max_retries)
1254 {
1255 struct nvme_get_discovery_args args = {
1256 .c = c,
1257 .max_retries = max_retries,
1258 .timeout = NVME_DEFAULT_IOCTL_TIMEOUT,
1259 .lsp = NVMF_LOG_DISC_LSP_NONE,
1260 };
1261
1262 *logp = nvmf_get_discovery_wargs(&args);
1263 return *logp ? 0 : -1;
1264 }
1265
1266 struct nvmf_discovery_log *nvmf_get_discovery_wargs(struct nvme_get_discovery_args *args)
1267 {
1268 struct nvmf_discovery_log *log;
1269
1270 log = nvme_discovery_log(args);
1271 if (!log)
1272 return NULL;
1273
1274 for (int i = 0; i < le64_to_cpu(log->numrec); i++)
1275 sanitize_discovery_log_entry(&log->entries[i]);
1276
1277 return log;
1278 }
1279
1280 static int uuid_from_device_tree(char *system_uuid)
1281 {
1282 _cleanup_fd_ int f = -1;
1283 ssize_t len;
1284
1285 f = open(nvme_uuid_ibm_filename(), O_RDONLY);
1286 if (f < 0)
1287 return -ENXIO;
1288
1289 memset(system_uuid, 0, NVME_UUID_LEN_STRING);
1290 len = read(f, system_uuid, NVME_UUID_LEN_STRING - 1);
1291 if (len < 0)
1292 return -ENXIO;
1293
1294 return strlen(system_uuid) ? 0 : -ENXIO;
1295 }
1296
1297 /*
1298 * See System Management BIOS (SMBIOS) Reference Specification
1299 * https://www.dmtf.org/sites/default/files/standards/documents/DSP0134_3.2.0.pdf
1300 */
1301 #define DMI_SYSTEM_INFORMATION 1
1302
1303 static bool is_dmi_uuid_valid(const char *buf, size_t len)
1304 {
1305 int i;
1306
1307 /* UUID bytes are from byte 8 to 23 */
1308 if (len < 24)
1309 return false;
1310
1311 /* Test it's a invalid UUID with all zeros */
1312 for (i = 8; i < 24; i++) {
1313 if (buf[i])
1314 break;
1315 }
1316 if (i == 24)
1317 return false;
1318
1319 return true;
1320 }
1321
1322 static int uuid_from_dmi_entries(char *system_uuid)
1323 {
1324 _cleanup_dir_ DIR *d = NULL;
1325 const char *entries_dir = nvme_dmi_entries_dir();
1326 int f;
1327 struct dirent *de;
1328 char buf[512] = {0};
1329
1330 system_uuid[0] = '\0';
1331 d = opendir(entries_dir);
1332 if (!d)
1333 return -ENXIO;
1334 while ((de = readdir(d))) {
1335 char filename[PATH_MAX];
1336 int len, type;
1337
1338 if (de->d_name[0] == '.')
1339 continue;
1340 sprintf(filename, "%s/%s/type", entries_dir, de->d_name);
1341 f = open(filename, O_RDONLY);
1342 if (f < 0)
1343 continue;
1344 len = read(f, buf, 512);
1345 close(f);
1346 if (len <= 0)
1347 continue;
1348 if (sscanf(buf, "%d", &type) != 1)
1349 continue;
1350 if (type != DMI_SYSTEM_INFORMATION)
1351 continue;
1352 sprintf(filename, "%s/%s/raw", entries_dir, de->d_name);
1353 f = open(filename, O_RDONLY);
1354 if (f < 0)
1355 continue;
1356 len = read(f, buf, 512);
1357 close(f);
1358 if (len <= 0)
1359 continue;
1360
1361 if (!is_dmi_uuid_valid(buf, len))
1362 continue;
1363
1364 /* Sigh. https://en.wikipedia.org/wiki/Overengineering */
1365 /* DMTF SMBIOS 3.0 Section 7.2.1 System UUID */
1366 sprintf(system_uuid,
1367 "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-"
1368 "%02x%02x%02x%02x%02x%02x",
1369 (uint8_t)buf[8 + 3], (uint8_t)buf[8 + 2],
1370 (uint8_t)buf[8 + 1], (uint8_t)buf[8 + 0],
1371 (uint8_t)buf[8 + 5], (uint8_t)buf[8 + 4],
1372 (uint8_t)buf[8 + 7], (uint8_t)buf[8 + 6],
1373 (uint8_t)buf[8 + 8], (uint8_t)buf[8 + 9],
1374 (uint8_t)buf[8 + 10], (uint8_t)buf[8 + 11],
1375 (uint8_t)buf[8 + 12], (uint8_t)buf[8 + 13],
1376 (uint8_t)buf[8 + 14], (uint8_t)buf[8 + 15]);
1377 break;
1378 }
1379 return strlen(system_uuid) ? 0 : -ENXIO;
1380 }
1381
1382 #define PATH_DMI_PROD_UUID "/sys/class/dmi/id/product_uuid"
1383
1384 /**
1385 * uuid_from_product_uuid() - Get system UUID from product_uuid
1386 * @system_uuid: Where to save the system UUID.
1387 *
1388 * Return: 0 on success, -ENXIO otherwise.
1389 */
1390 static int uuid_from_product_uuid(char *system_uuid)
1391 {
1392 _cleanup_file_ FILE *stream = NULL;
1393 ssize_t nread;
1394 _cleanup_free_ char *line = NULL;
1395 size_t len = 0;
1396
1397 stream = fopen(PATH_DMI_PROD_UUID, "re");
1398 if (!stream)
1399 return -ENXIO;
1400 system_uuid[0] = '\0';
1401
1402 nread = getline(&line, &len, stream);
1403 if (nread != NVME_UUID_LEN_STRING)
1404 return -ENXIO;
1405
1406 /* The kernel is handling the byte swapping according DMTF
1407 * SMBIOS 3.0 Section 7.2.1 System UUID */
1408
1409 memcpy(system_uuid, line, NVME_UUID_LEN_STRING - 1);
1410 system_uuid[NVME_UUID_LEN_STRING - 1] = '\0';
1411
1412 return 0;
1413 }
1414
1415 /**
1416 * uuid_from_dmi() - read system UUID
1417 * @system_uuid: buffer for the UUID
1418 *
1419 * The system UUID can be read from two different locations:
1420 *
1421 * 1) /sys/class/dmi/id/product_uuid
1422 * 2) /sys/firmware/dmi/entries
1423 *
1424 * Note that the second location is not present on Debian-based systems.
1425 *
1426 * Return: 0 on success, negative errno otherwise.
1427 */
1428 static int uuid_from_dmi(char *system_uuid)
1429 {
1430 int ret = uuid_from_product_uuid(system_uuid);
1431 if (ret != 0)
1432 ret = uuid_from_dmi_entries(system_uuid);
1433 return ret;
1434 }
1435
1436 char *nvmf_hostid_generate()
1437 {
1438 int ret;
1439 char uuid_str[NVME_UUID_LEN_STRING];
1440 unsigned char uuid[NVME_UUID_LEN];
1441
1442 ret = uuid_from_dmi(uuid_str);
1443 if (ret < 0)
1444 ret = uuid_from_device_tree(uuid_str);
1445 if (ret < 0) {
1446 if (nvme_uuid_random(uuid) < 0)
1447 memset(uuid, 0, NVME_UUID_LEN);
1448 nvme_uuid_to_string(uuid, uuid_str);
1449 }
1450
1451 return strdup(uuid_str);
1452 }
1453
1454 char *nvmf_hostnqn_generate_from_hostid(char *hostid)
1455 {
1456 char *hid = NULL;
1457 char *hostnqn;
1458 int ret;
1459
1460 if (!hostid)
1461 hostid = hid = nvmf_hostid_generate();
1462
1463 ret = asprintf(&hostnqn, "nqn.2014-08.org.nvmexpress:uuid:%s", hostid);
1464 free(hid);
1465
1466 return (ret < 0) ? NULL : hostnqn;
1467 }
1468
1469 char *nvmf_hostnqn_generate()
1470 {
1471 return nvmf_hostnqn_generate_from_hostid(NULL);
1472 }
1473
1474 static char *nvmf_read_file(const char *f, int len)
1475 {
1476 char buf[len];
1477 _cleanup_fd_ int fd = -1;
1478 int ret;
1479
1480 fd = open(f, O_RDONLY);
1481 if (fd < 0)
1482 return NULL;
1483
1484 memset(buf, 0, len);
1485 ret = read(fd, buf, len - 1);
1486
1487 if (ret < 0 || !strlen(buf))
1488 return NULL;
1489 return strndup(buf, strcspn(buf, "\n"));
1490 }
1491
1492 char *nvmf_hostnqn_from_file()
1493 {
1494 char *hostnqn = getenv("LIBNVME_HOSTNQN");
1495
1496 if (hostnqn) {
1497 if (!strcmp(hostnqn, ""))
1498 return NULL;
1499 return strdup(hostnqn);
1500 }
1501
1502 return nvmf_read_file(NVMF_HOSTNQN_FILE, NVMF_NQN_SIZE);
1503 }
1504
1505 char *nvmf_hostid_from_file()
1506 {
1507 char *hostid = getenv("LIBNVME_HOSTID");
1508
1509 if (hostid) {
1510 if (!strcmp(hostid, ""))
1511 return NULL;
1512 return strdup(hostid);
1513 }
1514
1515 return nvmf_read_file(NVMF_HOSTID_FILE, NVMF_HOSTID_SIZE);
1516 }
1517
1518 /**
1519 * nvmf_get_tel() - Calculate the amount of memory needed for a DIE.
1520 * @hostsymname: Symbolic name (may be NULL)
1521 *
1522 * Each Discovery Information Entry (DIE) must contain at a minimum an
1523 * Extended Attribute for the HostID. The Entry may optionally contain an
1524 * Extended Attribute for the Symbolic Name.
1525 *
1526 * Return: Total Entry Length
1527 */
1528 static __u32 nvmf_get_tel(const char *hostsymname)
1529 {
1530 __u32 tel = sizeof(struct nvmf_ext_die);
1531 __u16 len;
1532
1533 /* Host ID is mandatory */
1534 tel += nvmf_exat_size(NVME_UUID_LEN);
1535
1536 /* Symbolic name is optional */
1537 len = hostsymname ? strlen(hostsymname) : 0;
1538 if (len)
1539 tel += nvmf_exat_size(len);
1540
1541 return tel;
1542 }
1543
1544 /**
1545 * nvmf_fill_die() - Fill a Discovery Information Entry.
1546 * @die: Pointer to Discovery Information Entry to be filled
1547 * @h: Pointer to the host data structure
1548 * @tel: Length of the DIE
1549 * @trtype: Transport type
1550 * @adrfam: Address family
1551 * @reg_addr: Address to register. Setting this to an empty string tells
1552 * the DC to infer address from the source address of the socket.
1553 * @tsas: Transport Specific Address Subtype for the address being
1554 * registered.
1555 */
1556 static void nvmf_fill_die(struct nvmf_ext_die *die, struct nvme_host *h,
1557 __u32 tel, __u8 trtype, __u8 adrfam,
1558 const char *reg_addr, union nvmf_tsas *tsas)
1559 {
1560 __u16 numexat = 0;
1561 size_t symname_len;
1562 struct nvmf_ext_attr *exat;
1563
1564 die->tel = cpu_to_le32(tel);
1565 die->trtype = trtype;
1566 die->adrfam = adrfam;
1567
1568 memcpy(die->nqn, h->hostnqn, MIN(sizeof(die->nqn), strlen(h->hostnqn)));
1569 memcpy(die->traddr, reg_addr, MIN(sizeof(die->traddr), strlen(reg_addr)));
1570
1571 if (tsas)
1572 memcpy(&die->tsas, tsas, sizeof(die->tsas));
1573
1574 /* Extended Attribute for the HostID (mandatory) */
1575 numexat++;
1576 exat = die->exat;
1577 exat->exattype = cpu_to_le16(NVMF_EXATTYPE_HOSTID);
1578 exat->exatlen = cpu_to_le16(nvmf_exat_len(NVME_UUID_LEN));
1579 nvme_uuid_from_string(h->hostid, exat->exatval);
1580
1581 /* Extended Attribute for the Symbolic Name (optional) */
1582 symname_len = h->hostsymname ? strlen(h->hostsymname) : 0;
1583 if (symname_len) {
1584 __u16 exatlen = nvmf_exat_len(symname_len);
1585
1586 numexat++;
1587 exat = nvmf_exat_ptr_next(exat);
1588 exat->exattype = cpu_to_le16(NVMF_EXATTYPE_SYMNAME);
1589 exat->exatlen = cpu_to_le16(exatlen);
1590 memcpy(exat->exatval, h->hostsymname, symname_len);
1591 /* Per Base specs, ASCII strings must be padded with spaces */
1592 memset(&exat->exatval[symname_len], ' ', exatlen - symname_len);
1593 }
1594
1595 die->numexat = cpu_to_le16(numexat);
1596 }
1597
1598 /**
1599 * nvmf_dim() - Explicit reg, dereg, reg-update issuing DIM
1600 * @c: Host NVMe controller instance maintaining the admin queue used to
1601 * submit the DIM command to the DC.
1602 * @tas: Task field of the Command Dword 10 (cdw10). Indicates whether to
1603 * perform a Registration, Deregistration, or Registration-update.
1604 * @trtype: Transport type (&enum nvmf_trtype - must be NVMF_TRTYPE_TCP)
1605 * @adrfam: Address family (&enum nvmf_addr_family)
1606 * @reg_addr: Address to register. Setting this to an empty string tells
1607 * the DC to infer address from the source address of the socket.
1608 * @tsas: Transport Specific Address Subtype for the address being
1609 * registered.
1610 * @result: Location where to save the command-specific result returned by
1611 * the discovery controller.
1612 *
1613 * Perform explicit registration, deregistration, or
1614 * registration-update (specified by @tas) by sending a Discovery
1615 * Information Management (DIM) command to the Discovery Controller
1616 * (DC).
1617 *
1618 * Return: 0 on success; on failure -1 is returned and errno is set
1619 */
1620 static int nvmf_dim(nvme_ctrl_t c, enum nvmf_dim_tas tas, __u8 trtype,
1621 __u8 adrfam, const char *reg_addr, union nvmf_tsas *tsas,
1622 __u32 *result)
1623 {
1624 nvme_root_t r = c->s && c->s->h ? c->s->h->r : NULL;
1625 _cleanup_free_ struct nvmf_dim_data *dim = NULL;
1626 struct nvmf_ext_die *die;
1627 __u32 tdl;
1628 __u32 tel;
1629 int ret;
1630
1631 struct nvme_dim_args args = {
1632 .args_size = sizeof(args),
1633 .fd = nvme_ctrl_get_fd(c),
1634 .result = result,
1635 .timeout = NVME_DEFAULT_IOCTL_TIMEOUT,
1636 .tas = tas
1637 };
1638
1639 if (!c->s) {
1640 nvme_msg(r, LOG_ERR,
1641 "%s: failed to perform DIM. subsystem undefined.\n",
1642 c->name);
1643 errno = EINVAL;
1644 return -1;
1645 }
1646
1647 if (!c->s->h) {
1648 nvme_msg(r, LOG_ERR,
1649 "%s: failed to perform DIM. host undefined.\n",
1650 c->name);
1651 errno = EINVAL;
1652 return -1;
1653 }
1654
1655 if (!c->s->h->hostid) {
1656 nvme_msg(r, LOG_ERR,
1657 "%s: failed to perform DIM. hostid undefined.\n",
1658 c->name);
1659 errno = EINVAL;
1660 return -1;
1661 }
1662
1663 if (!c->s->h->hostnqn) {
1664 nvme_msg(r, LOG_ERR,
1665 "%s: failed to perform DIM. hostnqn undefined.\n",
1666 c->name);
1667 errno = EINVAL;
1668 return -1;
1669 }
1670
1671 if (strcmp(c->transport, "tcp")) {
1672 nvme_msg(r, LOG_ERR,
1673 "%s: DIM only supported for TCP connections.\n",
1674 c->name);
1675 errno = EINVAL;
1676 return -1;
1677 }
1678
1679 /* Register one Discovery Information Entry (DIE) of size TEL */
1680 tel = nvmf_get_tel(c->s->h->hostsymname);
1681 tdl = sizeof(struct nvmf_dim_data) + tel;
1682
1683 dim = (struct nvmf_dim_data *)calloc(1, tdl);
1684 if (!dim) {
1685 errno = ENOMEM;
1686 return -1;
1687 }
1688
1689 dim->tdl = cpu_to_le32(tdl);
1690 dim->nument = cpu_to_le64(1); /* only one DIE to register */
1691 dim->entfmt = cpu_to_le16(NVMF_DIM_ENTFMT_EXTENDED);
1692 dim->etype = cpu_to_le16(NVMF_DIM_ETYPE_HOST);
1693 dim->ektype = cpu_to_le16(0x5F); /* must be 0x5F per specs */
1694
1695 memcpy(dim->eid, c->s->h->hostnqn,
1696 MIN(sizeof(dim->eid), strlen(c->s->h->hostnqn)));
1697
1698 ret = get_entity_name(dim->ename, sizeof(dim->ename));
1699 if (ret <= 0)
1700 nvme_msg(r, LOG_INFO, "%s: Failed to retrieve ENAME. %s.\n",
1701 c->name, strerror(errno));
1702
1703 ret = get_entity_version(dim->ever, sizeof(dim->ever));
1704 if (ret <= 0)
1705 nvme_msg(r, LOG_INFO, "%s: Failed to retrieve EVER.\n", c->name);
1706
1707 die = &dim->die->extended;
1708 nvmf_fill_die(die, c->s->h, tel, trtype, adrfam, reg_addr, tsas);
1709
1710 args.data_len = tdl;
1711 args.data = dim;
1712 return nvme_dim_send(&args);
1713 }
1714
1715 /**
1716 * nvme_get_adrfam() - Get address family for the address we're registering
1717 * with the DC.
1718 *
1719 * We retrieve this info from the socket itself. If we can't get the source
1720 * address from the socket, then we'll infer the address family from the
1721 * address of the DC since the DC address has the same address family.
1722 *
1723 * @ctrl: Host NVMe controller instance maintaining the admin queue used to
1724 * submit the DIM command to the DC.
1725 *
1726 * Return: The address family of the source address associated with the
1727 * socket connected to the DC.
1728 */
1729 static __u8 nvme_get_adrfam(nvme_ctrl_t c)
1730 {
1731 struct sockaddr_storage addr;
1732 __u8 adrfam = NVMF_ADDR_FAMILY_IP4;
1733 nvme_root_t r = c->s && c->s->h ? c->s->h->r : NULL;
1734
1735 if (!inet_pton_with_scope(r, AF_UNSPEC, c->traddr, c->trsvcid, &addr)) {
1736 if (addr.ss_family == AF_INET6)
1737 adrfam = NVMF_ADDR_FAMILY_IP6;
1738 }
1739
1740 return adrfam;
1741 }
1742
1743 /* These string definitions must match with the kernel */
1744 static const char *cntrltype_str[] = {
1745 [NVME_CTRL_CNTRLTYPE_IO] = "io",
1746 [NVME_CTRL_CNTRLTYPE_DISCOVERY] = "discovery",
1747 [NVME_CTRL_CNTRLTYPE_ADMIN] = "admin",
1748 };
1749
1750 static const char *dctype_str[] = {
1751 [NVME_CTRL_DCTYPE_NOT_REPORTED] = "none",
1752 [NVME_CTRL_DCTYPE_DDC] = "ddc",
1753 [NVME_CTRL_DCTYPE_CDC] = "cdc",
1754 };
1755
1756 /**
1757 * nvme_fetch_cntrltype_dctype_from_id - Get cntrltype and dctype from identify command
1758 * @c: Controller instance
1759 *
1760 * On legacy kernels the cntrltype and dctype are not exposed through the
1761 * sysfs. We must get them directly from the controller by performing an
1762 * identify command.
1763 */
1764 static int nvme_fetch_cntrltype_dctype_from_id(nvme_ctrl_t c)
1765 {
1766 _cleanup_free_ struct nvme_id_ctrl *id = NULL;
1767 int ret;
1768
1769 id = __nvme_alloc(sizeof(*id));
1770 if (!id) {
1771 errno = ENOMEM;
1772 return -1;
1773 }
1774
1775 ret = nvme_ctrl_identify(c, id);
1776 if (ret)
1777 return ret;
1778
1779 if (!c->cntrltype) {
1780 if (id->cntrltype > NVME_CTRL_CNTRLTYPE_ADMIN || !cntrltype_str[id->cntrltype])
1781 c->cntrltype = strdup("reserved");
1782 else
1783 c->cntrltype = strdup(cntrltype_str[id->cntrltype]);
1784 }
1785
1786 if (!c->dctype) {
1787 if (id->dctype > NVME_CTRL_DCTYPE_CDC || !dctype_str[id->dctype])
1788 c->dctype = strdup("reserved");
1789 else
1790 c->dctype = strdup(dctype_str[id->dctype]);
1791 }
1792 return 0;
1793 }
1794
1795 bool nvmf_is_registration_supported(nvme_ctrl_t c)
1796 {
1797 if (!c->cntrltype || !c->dctype)
1798 if (nvme_fetch_cntrltype_dctype_from_id(c))
1799 return false;
1800
1801 return !strcmp(c->dctype, "ddc") || !strcmp(c->dctype, "cdc");
1802 }
1803
1804 int nvmf_register_ctrl(nvme_ctrl_t c, enum nvmf_dim_tas tas, __u32 *result)
1805 {
1806 if (!nvmf_is_registration_supported(c)) {
1807 errno = ENOTSUP;
1808 return -1;
1809 }
1810
1811 /* We're registering our source address with the DC. To do
1812 * that, we can simply send an empty string. This tells the DC
1813 * to retrieve the source address from the socket and use that
1814 * as the registration address.
1815 */
1816 return nvmf_dim(c, tas, NVMF_TRTYPE_TCP, nvme_get_adrfam(c), "", NULL, result);
1817 }
1818
1819 #define IS_XDIGIT(c) ((c >= '0' && c <= '9') || \
1820 (c >= 'A' && c <= 'F') || \
1821 (c >= 'a' && c <= 'f'))
1822 #define XDIGIT_VAL(c) ((c >= '0' && c <= '9') ? c - '0' : ( \
1823 (c >= 'A' && c <= 'F') ? c - 'A' + 10 : c - 'a' + 10))
1824
1825 /* returns newly allocated string */
1826 static char *unescape_uri(const char *str, int len)
1827 {
1828 char *dst;
1829 int l;
1830 int i, j;
1831
1832 l = len > 0 ? len : strlen(str);
1833 dst = malloc(l + 1);
1834 for (i = 0, j = 0; i < l; i++, j++) {
1835 if (str[i] == '%' && i + 2 < l &&
1836 IS_XDIGIT(str[i + 1]) && IS_XDIGIT(str[i + 2])) {
1837 dst[j] = (XDIGIT_VAL(str[i + 1]) << 4) +
1838 XDIGIT_VAL(str[i + 2]);
1839 i += 2;
1840 } else
1841 dst[j] = str[i];
1842 }
1843 dst[j] = '\0';
1844 return dst;
1845 }
1846
1847 struct nvme_fabrics_uri *nvme_parse_uri(const char *str)
1848 {
1849 struct nvme_fabrics_uri *uri;
1850 _cleanup_free_ char *scheme = NULL;
1851 _cleanup_free_ char *authority = NULL;
1852 _cleanup_free_ char *path = NULL;
1853 _cleanup_free_ char *h = NULL;
1854 const char *host;
1855 int i;
1856
1857 /* As defined in Boot Specification rev. 1.0:
1858 *
1859 * section 1.5.7: NVMe-oF URI Format
1860 * nvme+tcp://192.168.1.1:4420/
1861 * nvme+tcp://[FE80::1010]:4420/
1862 *
1863 * section 3.1.2.5.3: DHCP Root-Path - a hierarchical NVMe-oF URI Format
1864 * NVME<+PROTOCOL>://<SERVERNAME/IP>[:TRANSPORT PORT]/<SUBSYS NQN>/<NID>
1865 * or
1866 * NVME<+PROTOCOL>://<DISCOVERY CONTROLLER ADDRESS>[:DISCOVERY-
1867 * -CONTROLLER PORT]/NQN.2014-08.ORG.NVMEXPRESS.DISCOVERY/<NID>
1868 */
1869
1870 uri = calloc(1, sizeof(struct nvme_fabrics_uri));
1871 if (!uri)
1872 return NULL;
1873
1874 if (sscanf(str, "%m[^:/]://%m[^/?#]%ms",
1875 &scheme, &authority, &path) < 2) {
1876 nvme_free_uri(uri);
1877 errno = EINVAL;
1878 return NULL;
1879 }
1880
1881 if (sscanf(scheme, "%m[^+]+%ms",
1882 &uri->scheme, &uri->protocol) < 1) {
1883 nvme_free_uri(uri);
1884 errno = EINVAL;
1885 return NULL;
1886 }
1887
1888 /* split userinfo */
1889 host = strrchr(authority, '@');
1890 if (host) {
1891 host++;
1892 uri->userinfo = unescape_uri(authority, host - authority);
1893 } else
1894 host = authority;
1895
1896 /* try matching IPv6 address first */
1897 if (sscanf(host, "[%m[^]]]:%d",
1898 &uri->host, &uri->port) < 1) {
1899 /* treat it as IPv4/hostname */
1900 if (sscanf(host, "%m[^:]:%d",
1901 &h, &uri->port) < 1) {
1902 nvme_free_uri(uri);
1903 errno = EINVAL;
1904 return NULL;
1905 }
1906 uri->host = unescape_uri(h, 0);
1907 }
1908
1909 /* split path into elements */
1910 if (path) {
1911 char *e, *elem;
1912
1913 /* separate the fragment */
1914 e = strrchr(path, '#');
1915 if (e) {
1916 uri->fragment = unescape_uri(e + 1, 0);
1917 *e = '\0';
1918 }
1919 /* separate the query string */
1920 e = strrchr(path, '?');
1921 if (e) {
1922 uri->query = unescape_uri(e + 1, 0);
1923 *e = '\0';
1924 }
1925
1926 /* count elements first */
1927 for (i = 0, e = path; *e; e++)
1928 if (*e == '/' && *(e + 1) != '/')
1929 i++;
1930 uri->path_segments = calloc(i + 2, sizeof(char *));
1931
1932 i = 0;
1933 elem = strtok_r(path, "/", &e);
1934 if (elem)
1935 uri->path_segments[i++] = unescape_uri(elem, 0);
1936 while (elem && strlen(elem)) {
1937 elem = strtok_r(NULL, "/", &e);
1938 if (elem)
1939 uri->path_segments[i++] = unescape_uri(elem, 0);
1940 }
1941 }
1942
1943 return uri;
1944 }
1945
1946 void nvme_free_uri(struct nvme_fabrics_uri *uri)
1947 {
1948 char **s;
1949
1950 if (!uri)
1951 return;
1952 free(uri->scheme);
1953 free(uri->protocol);
1954 free(uri->userinfo);
1955 free(uri->host);
1956 for (s = uri->path_segments; s && *s; s++)
1957 free(*s);
1958 free(uri->path_segments);
1959 free(uri->query);
1960 free(uri->fragment);
1961 free(uri);
1962 }