xref: /spdk/examples/nvme/hello_world/hello_world.c (revision 06b537bfdb4393dea857e204b85d8df46a351d8a)
1 /*-
2  *   BSD LICENSE
3  *
4  *   Copyright (c) Intel Corporation.
5  *   All rights reserved.
6  *
7  *   Redistribution and use in source and binary forms, with or without
8  *   modification, are permitted provided that the following conditions
9  *   are met:
10  *
11  *     * Redistributions of source code must retain the above copyright
12  *       notice, this list of conditions and the following disclaimer.
13  *     * Redistributions in binary form must reproduce the above copyright
14  *       notice, this list of conditions and the following disclaimer in
15  *       the documentation and/or other materials provided with the
16  *       distribution.
17  *     * Neither the name of Intel Corporation nor the names of its
18  *       contributors may be used to endorse or promote products derived
19  *       from this software without specific prior written permission.
20  *
21  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24  *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25  *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26  *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27  *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33 
34 #include "spdk/stdinc.h"
35 
36 #include "spdk/nvme.h"
37 #include "spdk/vmd.h"
38 #include "spdk/env.h"
39 
40 struct ctrlr_entry {
41 	struct spdk_nvme_ctrlr		*ctrlr;
42 	TAILQ_ENTRY(ctrlr_entry)	link;
43 	char				name[1024];
44 };
45 
46 struct ns_entry {
47 	struct spdk_nvme_ctrlr	*ctrlr;
48 	struct spdk_nvme_ns	*ns;
49 	TAILQ_ENTRY(ns_entry)	link;
50 	struct spdk_nvme_qpair	*qpair;
51 };
52 
53 static TAILQ_HEAD(, ctrlr_entry) g_controllers = TAILQ_HEAD_INITIALIZER(g_controllers);
54 static TAILQ_HEAD(, ns_entry) g_namespaces = TAILQ_HEAD_INITIALIZER(g_namespaces);
55 
56 static bool g_vmd = false;
57 
58 static void
59 register_ns(struct spdk_nvme_ctrlr *ctrlr, struct spdk_nvme_ns *ns)
60 {
61 	struct ns_entry *entry;
62 
63 	if (!spdk_nvme_ns_is_active(ns)) {
64 		return;
65 	}
66 
67 	entry = malloc(sizeof(struct ns_entry));
68 	if (entry == NULL) {
69 		perror("ns_entry malloc");
70 		exit(1);
71 	}
72 
73 	entry->ctrlr = ctrlr;
74 	entry->ns = ns;
75 	TAILQ_INSERT_TAIL(&g_namespaces, entry, link);
76 
77 	printf("  Namespace ID: %d size: %juGB\n", spdk_nvme_ns_get_id(ns),
78 	       spdk_nvme_ns_get_size(ns) / 1000000000);
79 }
80 
81 struct hello_world_sequence {
82 	struct ns_entry	*ns_entry;
83 	char		*buf;
84 	unsigned        using_cmb_io;
85 	int		is_completed;
86 };
87 
88 static void
89 read_complete(void *arg, const struct spdk_nvme_cpl *completion)
90 {
91 	struct hello_world_sequence *sequence = arg;
92 
93 	/* Assume the I/O was successful */
94 	sequence->is_completed = 1;
95 	/* See if an error occurred. If so, display information
96 	 * about it, and set completion value so that I/O
97 	 * caller is aware that an error occurred.
98 	 */
99 	if (spdk_nvme_cpl_is_error(completion)) {
100 		spdk_nvme_qpair_print_completion(sequence->ns_entry->qpair, (struct spdk_nvme_cpl *)completion);
101 		fprintf(stderr, "I/O error status: %s\n", spdk_nvme_cpl_get_status_string(&completion->status));
102 		fprintf(stderr, "Read I/O failed, aborting run\n");
103 		sequence->is_completed = 2;
104 	}
105 
106 	/*
107 	 * The read I/O has completed.  Print the contents of the
108 	 *  buffer, free the buffer, then mark the sequence as
109 	 *  completed.  This will trigger the hello_world() function
110 	 *  to exit its polling loop.
111 	 */
112 	printf("%s", sequence->buf);
113 	spdk_free(sequence->buf);
114 }
115 
116 static void
117 write_complete(void *arg, const struct spdk_nvme_cpl *completion)
118 {
119 	struct hello_world_sequence	*sequence = arg;
120 	struct ns_entry			*ns_entry = sequence->ns_entry;
121 	int				rc;
122 
123 	/* See if an error occurred. If so, display information
124 	 * about it, and set completion value so that I/O
125 	 * caller is aware that an error occurred.
126 	 */
127 	if (spdk_nvme_cpl_is_error(completion)) {
128 		spdk_nvme_qpair_print_completion(sequence->ns_entry->qpair, (struct spdk_nvme_cpl *)completion);
129 		fprintf(stderr, "I/O error status: %s\n", spdk_nvme_cpl_get_status_string(&completion->status));
130 		fprintf(stderr, "Write I/O failed, aborting run\n");
131 		sequence->is_completed = 2;
132 		exit(1);
133 	}
134 	/*
135 	 * The write I/O has completed.  Free the buffer associated with
136 	 *  the write I/O and allocate a new zeroed buffer for reading
137 	 *  the data back from the NVMe namespace.
138 	 */
139 	if (sequence->using_cmb_io) {
140 		spdk_nvme_ctrlr_unmap_cmb(ns_entry->ctrlr);
141 	} else {
142 		spdk_free(sequence->buf);
143 	}
144 	sequence->buf = spdk_zmalloc(0x1000, 0x1000, NULL, SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
145 
146 	rc = spdk_nvme_ns_cmd_read(ns_entry->ns, ns_entry->qpair, sequence->buf,
147 				   0, /* LBA start */
148 				   1, /* number of LBAs */
149 				   read_complete, (void *)sequence, 0);
150 	if (rc != 0) {
151 		fprintf(stderr, "starting read I/O failed\n");
152 		exit(1);
153 	}
154 }
155 
156 static void
157 hello_world(void)
158 {
159 	struct ns_entry			*ns_entry;
160 	struct hello_world_sequence	sequence;
161 	int				rc;
162 	size_t				sz;
163 
164 	TAILQ_FOREACH(ns_entry, &g_namespaces, link) {
165 		/*
166 		 * Allocate an I/O qpair that we can use to submit read/write requests
167 		 *  to namespaces on the controller.  NVMe controllers typically support
168 		 *  many qpairs per controller.  Any I/O qpair allocated for a controller
169 		 *  can submit I/O to any namespace on that controller.
170 		 *
171 		 * The SPDK NVMe driver provides no synchronization for qpair accesses -
172 		 *  the application must ensure only a single thread submits I/O to a
173 		 *  qpair, and that same thread must also check for completions on that
174 		 *  qpair.  This enables extremely efficient I/O processing by making all
175 		 *  I/O operations completely lockless.
176 		 */
177 		ns_entry->qpair = spdk_nvme_ctrlr_alloc_io_qpair(ns_entry->ctrlr, NULL, 0);
178 		if (ns_entry->qpair == NULL) {
179 			printf("ERROR: spdk_nvme_ctrlr_alloc_io_qpair() failed\n");
180 			return;
181 		}
182 
183 		/*
184 		 * Use spdk_dma_zmalloc to allocate a 4KB zeroed buffer.  This memory
185 		 * will be pinned, which is required for data buffers used for SPDK NVMe
186 		 * I/O operations.
187 		 */
188 		sequence.using_cmb_io = 1;
189 		sequence.buf = spdk_nvme_ctrlr_map_cmb(ns_entry->ctrlr, &sz);
190 		if (sequence.buf == NULL || sz < 0x1000) {
191 			sequence.using_cmb_io = 0;
192 			sequence.buf = spdk_zmalloc(0x1000, 0x1000, NULL, SPDK_ENV_SOCKET_ID_ANY, SPDK_MALLOC_DMA);
193 		}
194 		if (sequence.buf == NULL) {
195 			printf("ERROR: write buffer allocation failed\n");
196 			return;
197 		}
198 		if (sequence.using_cmb_io) {
199 			printf("INFO: using controller memory buffer for IO\n");
200 		} else {
201 			printf("INFO: using host memory buffer for IO\n");
202 		}
203 		sequence.is_completed = 0;
204 		sequence.ns_entry = ns_entry;
205 
206 		/*
207 		 * Print "Hello world!" to sequence.buf.  We will write this data to LBA
208 		 *  0 on the namespace, and then later read it back into a separate buffer
209 		 *  to demonstrate the full I/O path.
210 		 */
211 		snprintf(sequence.buf, 0x1000, "%s", "Hello world!\n");
212 
213 		/*
214 		 * Write the data buffer to LBA 0 of this namespace.  "write_complete" and
215 		 *  "&sequence" are specified as the completion callback function and
216 		 *  argument respectively.  write_complete() will be called with the
217 		 *  value of &sequence as a parameter when the write I/O is completed.
218 		 *  This allows users to potentially specify different completion
219 		 *  callback routines for each I/O, as well as pass a unique handle
220 		 *  as an argument so the application knows which I/O has completed.
221 		 *
222 		 * Note that the SPDK NVMe driver will only check for completions
223 		 *  when the application calls spdk_nvme_qpair_process_completions().
224 		 *  It is the responsibility of the application to trigger the polling
225 		 *  process.
226 		 */
227 		rc = spdk_nvme_ns_cmd_write(ns_entry->ns, ns_entry->qpair, sequence.buf,
228 					    0, /* LBA start */
229 					    1, /* number of LBAs */
230 					    write_complete, &sequence, 0);
231 		if (rc != 0) {
232 			fprintf(stderr, "starting write I/O failed\n");
233 			exit(1);
234 		}
235 
236 		/*
237 		 * Poll for completions.  0 here means process all available completions.
238 		 *  In certain usage models, the caller may specify a positive integer
239 		 *  instead of 0 to signify the maximum number of completions it should
240 		 *  process.  This function will never block - if there are no
241 		 *  completions pending on the specified qpair, it will return immediately.
242 		 *
243 		 * When the write I/O completes, write_complete() will submit a new I/O
244 		 *  to read LBA 0 into a separate buffer, specifying read_complete() as its
245 		 *  completion routine.  When the read I/O completes, read_complete() will
246 		 *  print the buffer contents and set sequence.is_completed = 1.  That will
247 		 *  break this loop and then exit the program.
248 		 */
249 		while (!sequence.is_completed) {
250 			spdk_nvme_qpair_process_completions(ns_entry->qpair, 0);
251 		}
252 
253 		/*
254 		 * Free the I/O qpair.  This typically is done when an application exits.
255 		 *  But SPDK does support freeing and then reallocating qpairs during
256 		 *  operation.  It is the responsibility of the caller to ensure all
257 		 *  pending I/O are completed before trying to free the qpair.
258 		 */
259 		spdk_nvme_ctrlr_free_io_qpair(ns_entry->qpair);
260 	}
261 }
262 
263 static bool
264 probe_cb(void *cb_ctx, const struct spdk_nvme_transport_id *trid,
265 	 struct spdk_nvme_ctrlr_opts *opts)
266 {
267 	printf("Attaching to %s\n", trid->traddr);
268 
269 	return true;
270 }
271 
272 static void
273 attach_cb(void *cb_ctx, const struct spdk_nvme_transport_id *trid,
274 	  struct spdk_nvme_ctrlr *ctrlr, const struct spdk_nvme_ctrlr_opts *opts)
275 {
276 	int nsid, num_ns;
277 	struct ctrlr_entry *entry;
278 	struct spdk_nvme_ns *ns;
279 	const struct spdk_nvme_ctrlr_data *cdata;
280 
281 	entry = malloc(sizeof(struct ctrlr_entry));
282 	if (entry == NULL) {
283 		perror("ctrlr_entry malloc");
284 		exit(1);
285 	}
286 
287 	printf("Attached to %s\n", trid->traddr);
288 
289 	/*
290 	 * spdk_nvme_ctrlr is the logical abstraction in SPDK for an NVMe
291 	 *  controller.  During initialization, the IDENTIFY data for the
292 	 *  controller is read using an NVMe admin command, and that data
293 	 *  can be retrieved using spdk_nvme_ctrlr_get_data() to get
294 	 *  detailed information on the controller.  Refer to the NVMe
295 	 *  specification for more details on IDENTIFY for NVMe controllers.
296 	 */
297 	cdata = spdk_nvme_ctrlr_get_data(ctrlr);
298 
299 	snprintf(entry->name, sizeof(entry->name), "%-20.20s (%-20.20s)", cdata->mn, cdata->sn);
300 
301 	entry->ctrlr = ctrlr;
302 	TAILQ_INSERT_TAIL(&g_controllers, entry, link);
303 
304 	/*
305 	 * Each controller has one or more namespaces.  An NVMe namespace is basically
306 	 *  equivalent to a SCSI LUN.  The controller's IDENTIFY data tells us how
307 	 *  many namespaces exist on the controller.  For Intel(R) P3X00 controllers,
308 	 *  it will just be one namespace.
309 	 *
310 	 * Note that in NVMe, namespace IDs start at 1, not 0.
311 	 */
312 	num_ns = spdk_nvme_ctrlr_get_num_ns(ctrlr);
313 	printf("Using controller %s with %d namespaces.\n", entry->name, num_ns);
314 	for (nsid = 1; nsid <= num_ns; nsid++) {
315 		ns = spdk_nvme_ctrlr_get_ns(ctrlr, nsid);
316 		if (ns == NULL) {
317 			continue;
318 		}
319 		register_ns(ctrlr, ns);
320 	}
321 }
322 
323 static void
324 cleanup(void)
325 {
326 	struct ns_entry *ns_entry, *tmp_ns_entry;
327 	struct ctrlr_entry *ctrlr_entry, *tmp_ctrlr_entry;
328 
329 	TAILQ_FOREACH_SAFE(ns_entry, &g_namespaces, link, tmp_ns_entry) {
330 		TAILQ_REMOVE(&g_namespaces, ns_entry, link);
331 		free(ns_entry);
332 	}
333 
334 	TAILQ_FOREACH_SAFE(ctrlr_entry, &g_controllers, link, tmp_ctrlr_entry) {
335 		TAILQ_REMOVE(&g_controllers, ctrlr_entry, link);
336 		spdk_nvme_detach(ctrlr_entry->ctrlr);
337 		free(ctrlr_entry);
338 	}
339 }
340 
341 static void
342 usage(const char *program_name)
343 {
344 	printf("%s [options]", program_name);
345 	printf("\n");
346 	printf("options:\n");
347 	printf(" -V         enumerate VMD\n");
348 }
349 
350 static int
351 parse_args(int argc, char **argv)
352 {
353 	int op;
354 
355 	while ((op = getopt(argc, argv, "V")) != -1) {
356 		switch (op) {
357 		case 'V':
358 			g_vmd = true;
359 			break;
360 		default:
361 			usage(argv[0]);
362 			return 1;
363 		}
364 	}
365 
366 	return 0;
367 }
368 
369 int main(int argc, char **argv)
370 {
371 	int rc;
372 	struct spdk_env_opts opts;
373 
374 	rc = parse_args(argc, argv);
375 	if (rc != 0) {
376 		return rc;
377 	}
378 
379 	/*
380 	 * SPDK relies on an abstraction around the local environment
381 	 * named env that handles memory allocation and PCI device operations.
382 	 * This library must be initialized first.
383 	 *
384 	 */
385 	spdk_env_opts_init(&opts);
386 	opts.name = "hello_world";
387 	opts.shm_id = 0;
388 	if (spdk_env_init(&opts) < 0) {
389 		fprintf(stderr, "Unable to initialize SPDK env\n");
390 		return 1;
391 	}
392 
393 	printf("Initializing NVMe Controllers\n");
394 
395 	if (g_vmd && spdk_vmd_init()) {
396 		fprintf(stderr, "Failed to initialize VMD."
397 			" Some NVMe devices can be unavailable.\n");
398 	}
399 
400 	/*
401 	 * Start the SPDK NVMe enumeration process.  probe_cb will be called
402 	 *  for each NVMe controller found, giving our application a choice on
403 	 *  whether to attach to each controller.  attach_cb will then be
404 	 *  called for each controller after the SPDK NVMe driver has completed
405 	 *  initializing the controller we chose to attach.
406 	 */
407 	rc = spdk_nvme_probe(NULL, NULL, probe_cb, attach_cb, NULL);
408 	if (rc != 0) {
409 		fprintf(stderr, "spdk_nvme_probe() failed\n");
410 		cleanup();
411 		return 1;
412 	}
413 
414 	if (TAILQ_EMPTY(&g_controllers)) {
415 		fprintf(stderr, "no NVMe controllers found\n");
416 		cleanup();
417 		return 1;
418 	}
419 
420 	printf("Initialization complete.\n");
421 	hello_world();
422 	cleanup();
423 	if (g_vmd) {
424 		spdk_vmd_fini();
425 	}
426 
427 	return 0;
428 }
429