xref: /freebsd/sbin/nvmecontrol/logpage.c (revision edf8578117e8844e02c0121147f45e4609b30680)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2013 EMC Corp.
5  * All rights reserved.
6  *
7  * Copyright (C) 2012-2013 Intel Corporation
8  * All rights reserved.
9  * Copyright (C) 2018-2019 Alexander Motin <mav@FreeBSD.org>
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 #include <sys/cdefs.h>
34 #include <sys/param.h>
35 #include <sys/ioccom.h>
36 
37 #include <ctype.h>
38 #include <err.h>
39 #include <fcntl.h>
40 #include <stdbool.h>
41 #include <stddef.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <sysexits.h>
46 #include <unistd.h>
47 #include <sys/endian.h>
48 
49 #include "nvmecontrol.h"
50 
51 /* Tables for command line parsing */
52 
53 static cmd_fn_t logpage;
54 
55 #define NONE 0xffffffffu
56 static struct options {
57 	bool		binary;
58 	bool		hex;
59 	uint32_t	page;
60 	uint8_t		lsp;
61 	uint16_t	lsi;
62 	bool		rae;
63 	const char	*vendor;
64 	const char	*dev;
65 } opt = {
66 	.binary = false,
67 	.hex = false,
68 	.page = NONE,
69 	.lsp = 0,
70 	.lsi = 0,
71 	.rae = false,
72 	.vendor = NULL,
73 	.dev = NULL,
74 };
75 
76 static const struct opts logpage_opts[] = {
77 #define OPT(l, s, t, opt, addr, desc) { l, s, t, &opt.addr, desc }
78 	OPT("binary", 'b', arg_none, opt, binary,
79 	    "Dump the log page as binary"),
80 	OPT("hex", 'x', arg_none, opt, hex,
81 	    "Dump the log page as hex"),
82 	OPT("page", 'p', arg_uint32, opt, page,
83 	    "Page to dump"),
84 	OPT("lsp", 'f', arg_uint8, opt, lsp,
85 	    "Log Specific Field"),
86 	OPT("lsi", 'i', arg_uint16, opt, lsi,
87 	    "Log Specific Identifier"),
88 	OPT("rae", 'r', arg_none, opt, rae,
89 	    "Retain Asynchronous Event"),
90 	OPT("vendor", 'v', arg_string, opt, vendor,
91 	    "Vendor specific formatting"),
92 	{ NULL, 0, arg_none, NULL, NULL }
93 };
94 #undef OPT
95 
96 static const struct args logpage_args[] = {
97 	{ arg_string, &opt.dev, "<controller id|namespace id>" },
98 	{ arg_none, NULL, NULL },
99 };
100 
101 static struct cmd logpage_cmd = {
102 	.name = "logpage",
103 	.fn = logpage,
104 	.descr = "Print logpages in human-readable form",
105 	.ctx_size = sizeof(opt),
106 	.opts = logpage_opts,
107 	.args = logpage_args,
108 };
109 
110 CMD_COMMAND(logpage_cmd);
111 
112 /* End of tables for command line parsing */
113 
114 #define MAX_FW_SLOTS	(7)
115 
116 static SLIST_HEAD(,logpage_function) logpages;
117 
118 static int
119 logpage_compare(struct logpage_function *a, struct logpage_function *b)
120 {
121 	int c;
122 
123 	if ((a->vendor == NULL) != (b->vendor == NULL))
124 		return (a->vendor == NULL ? -1 : 1);
125 	if (a->vendor != NULL) {
126 		c = strcmp(a->vendor, b->vendor);
127 		if (c != 0)
128 			return (c);
129 	}
130 	return ((int)a->log_page - (int)b->log_page);
131 }
132 
133 void
134 logpage_register(struct logpage_function *p)
135 {
136 	struct logpage_function *l, *a;
137 
138 	a = NULL;
139 	l = SLIST_FIRST(&logpages);
140 	while (l != NULL) {
141 		if (logpage_compare(l, p) > 0)
142 			break;
143 		a = l;
144 		l = SLIST_NEXT(l, link);
145 	}
146 	if (a == NULL)
147 		SLIST_INSERT_HEAD(&logpages, p, link);
148 	else
149 		SLIST_INSERT_AFTER(a, p, link);
150 }
151 
152 const char *
153 kv_lookup(const struct kv_name *kv, size_t kv_count, uint32_t key)
154 {
155 	static char bad[32];
156 	size_t i;
157 
158 	for (i = 0; i < kv_count; i++, kv++)
159 		if (kv->key == key)
160 			return kv->name;
161 	snprintf(bad, sizeof(bad), "Attribute %#x", key);
162 	return bad;
163 }
164 
165 static void
166 print_log_hex(const struct nvme_controller_data *cdata __unused, void *data, uint32_t length)
167 {
168 
169 	print_hex(data, length);
170 }
171 
172 static void
173 print_bin(const struct nvme_controller_data *cdata __unused, void *data, uint32_t length)
174 {
175 
176 	write(STDOUT_FILENO, data, length);
177 }
178 
179 static void *
180 get_log_buffer(uint32_t size)
181 {
182 	void	*buf;
183 
184 	if ((buf = malloc(size)) == NULL)
185 		errx(EX_OSERR, "unable to malloc %u bytes", size);
186 
187 	memset(buf, 0, size);
188 	return (buf);
189 }
190 
191 void
192 read_logpage(int fd, uint8_t log_page, uint32_t nsid, uint8_t lsp,
193     uint16_t lsi, uint8_t rae, void *payload, uint32_t payload_size)
194 {
195 	struct nvme_pt_command	pt;
196 	struct nvme_error_information_entry	*err_entry;
197 	u_int i, err_pages, numd;
198 
199 	numd = payload_size / sizeof(uint32_t) - 1;
200 	memset(&pt, 0, sizeof(pt));
201 	pt.cmd.opc = NVME_OPC_GET_LOG_PAGE;
202 	pt.cmd.nsid = htole32(nsid);
203 	pt.cmd.cdw10 = htole32(
204 	    (numd << 16) |			/* NUMDL */
205 	    (rae << 15) |			/* RAE */
206 	    (lsp << 8) |			/* LSP */
207 	    log_page);				/* LID */
208 	pt.cmd.cdw11 = htole32(
209 	    ((uint32_t)lsi << 16) |		/* LSI */
210 	    (numd >> 16));			/* NUMDU */
211 	pt.cmd.cdw12 = 0;			/* LPOL */
212 	pt.cmd.cdw13 = 0;			/* LPOU */
213 	pt.cmd.cdw14 = 0;			/* UUID Index */
214 	pt.buf = payload;
215 	pt.len = payload_size;
216 	pt.is_read = 1;
217 
218 	if (ioctl(fd, NVME_PASSTHROUGH_CMD, &pt) < 0)
219 		err(EX_IOERR, "get log page request failed");
220 
221 	/* Convert data to host endian */
222 	switch (log_page) {
223 	case NVME_LOG_ERROR:
224 		err_entry = (struct nvme_error_information_entry *)payload;
225 		err_pages = payload_size / sizeof(struct nvme_error_information_entry);
226 		for (i = 0; i < err_pages; i++)
227 			nvme_error_information_entry_swapbytes(err_entry++);
228 		break;
229 	case NVME_LOG_HEALTH_INFORMATION:
230 		nvme_health_information_page_swapbytes(
231 		    (struct nvme_health_information_page *)payload);
232 		break;
233 	case NVME_LOG_FIRMWARE_SLOT:
234 		nvme_firmware_page_swapbytes(
235 		    (struct nvme_firmware_page *)payload);
236 		break;
237 	case NVME_LOG_CHANGED_NAMESPACE:
238 		nvme_ns_list_swapbytes((struct nvme_ns_list *)payload);
239 		break;
240 	case NVME_LOG_DEVICE_SELF_TEST:
241 		nvme_device_self_test_swapbytes(
242 		    (struct nvme_device_self_test_page *)payload);
243 		break;
244 	case NVME_LOG_COMMAND_EFFECT:
245 		nvme_command_effects_page_swapbytes(
246 		    (struct nvme_command_effects_page *)payload);
247 		break;
248 	case NVME_LOG_RES_NOTIFICATION:
249 		nvme_res_notification_page_swapbytes(
250 		    (struct nvme_res_notification_page *)payload);
251 		break;
252 	case NVME_LOG_SANITIZE_STATUS:
253 		nvme_sanitize_status_page_swapbytes(
254 		    (struct nvme_sanitize_status_page *)payload);
255 		break;
256 	case INTEL_LOG_TEMP_STATS:
257 		intel_log_temp_stats_swapbytes(
258 		    (struct intel_log_temp_stats *)payload);
259 		break;
260 	default:
261 		break;
262 	}
263 
264 	if (nvme_completion_is_error(&pt.cpl))
265 		errx(EX_IOERR, "get log page request returned error");
266 }
267 
268 static void
269 print_log_error(const struct nvme_controller_data *cdata __unused, void *buf, uint32_t size)
270 {
271 	int					i, nentries;
272 	uint16_t				status;
273 	uint8_t					p, sc, sct, m, dnr;
274 	struct nvme_error_information_entry	*entry = buf;
275 
276 	printf("Error Information Log\n");
277 	printf("=====================\n");
278 
279 	if (entry->error_count == 0) {
280 		printf("No error entries found\n");
281 		return;
282 	}
283 
284 	nentries = size/sizeof(struct nvme_error_information_entry);
285 	for (i = 0; i < nentries; i++, entry++) {
286 		if (entry->error_count == 0)
287 			break;
288 
289 		status = entry->status;
290 
291 		p = NVME_STATUS_GET_P(status);
292 		sc = NVME_STATUS_GET_SC(status);
293 		sct = NVME_STATUS_GET_SCT(status);
294 		m = NVME_STATUS_GET_M(status);
295 		dnr = NVME_STATUS_GET_DNR(status);
296 
297 		printf("Entry %02d\n", i + 1);
298 		printf("=========\n");
299 		printf(" Error count:          %ju\n", entry->error_count);
300 		printf(" Submission queue ID:  %u\n", entry->sqid);
301 		printf(" Command ID:           %u\n", entry->cid);
302 		/* TODO: Export nvme_status_string structures from kernel? */
303 		printf(" Status:\n");
304 		printf("  Phase tag:           %d\n", p);
305 		printf("  Status code:         %d\n", sc);
306 		printf("  Status code type:    %d\n", sct);
307 		printf("  More:                %d\n", m);
308 		printf("  DNR:                 %d\n", dnr);
309 		printf(" Error location:       %u\n", entry->error_location);
310 		printf(" LBA:                  %ju\n", entry->lba);
311 		printf(" Namespace ID:         %u\n", entry->nsid);
312 		printf(" Vendor specific info: %u\n", entry->vendor_specific);
313 		printf(" Transport type:       %u\n", entry->trtype);
314 		printf(" Command specific info:%ju\n", entry->csi);
315 		printf(" Transport specific:   %u\n", entry->ttsi);
316 	}
317 }
318 
319 void
320 print_temp_K(uint16_t t)
321 {
322 	printf("%u K, %2.2f C, %3.2f F\n", t, (float)t - 273.15, (float)t * 9 / 5 - 459.67);
323 }
324 
325 void
326 print_temp_C(uint16_t t)
327 {
328 	printf("%2.2f K, %u C, %3.2f F\n", (float)t + 273.15, t, (float)t * 9 / 5 + 32);
329 }
330 
331 static void
332 print_log_health(const struct nvme_controller_data *cdata __unused, void *buf, uint32_t size __unused)
333 {
334 	struct nvme_health_information_page *health = buf;
335 	char cbuf[UINT128_DIG + 1];
336 	uint8_t	warning;
337 	int i;
338 
339 	warning = health->critical_warning;
340 
341 	printf("SMART/Health Information Log\n");
342 	printf("============================\n");
343 
344 	printf("Critical Warning State:         0x%02x\n", warning);
345 	printf(" Available spare:               %d\n",
346 	    !!(warning & NVME_CRIT_WARN_ST_AVAILABLE_SPARE));
347 	printf(" Temperature:                   %d\n",
348 	    !!(warning & NVME_CRIT_WARN_ST_TEMPERATURE));
349 	printf(" Device reliability:            %d\n",
350 	    !!(warning & NVME_CRIT_WARN_ST_DEVICE_RELIABILITY));
351 	printf(" Read only:                     %d\n",
352 	    !!(warning & NVME_CRIT_WARN_ST_READ_ONLY));
353 	printf(" Volatile memory backup:        %d\n",
354 	    !!(warning & NVME_CRIT_WARN_ST_VOLATILE_MEMORY_BACKUP));
355 	printf("Temperature:                    ");
356 	print_temp_K(health->temperature);
357 	printf("Available spare:                %u\n",
358 	    health->available_spare);
359 	printf("Available spare threshold:      %u\n",
360 	    health->available_spare_threshold);
361 	printf("Percentage used:                %u\n",
362 	    health->percentage_used);
363 
364 	printf("Data units (512,000 byte) read: %s\n",
365 	    uint128_to_str(to128(health->data_units_read), cbuf, sizeof(cbuf)));
366 	printf("Data units written:             %s\n",
367 	    uint128_to_str(to128(health->data_units_written), cbuf, sizeof(cbuf)));
368 	printf("Host read commands:             %s\n",
369 	    uint128_to_str(to128(health->host_read_commands), cbuf, sizeof(cbuf)));
370 	printf("Host write commands:            %s\n",
371 	    uint128_to_str(to128(health->host_write_commands), cbuf, sizeof(cbuf)));
372 	printf("Controller busy time (minutes): %s\n",
373 	    uint128_to_str(to128(health->controller_busy_time), cbuf, sizeof(cbuf)));
374 	printf("Power cycles:                   %s\n",
375 	    uint128_to_str(to128(health->power_cycles), cbuf, sizeof(cbuf)));
376 	printf("Power on hours:                 %s\n",
377 	    uint128_to_str(to128(health->power_on_hours), cbuf, sizeof(cbuf)));
378 	printf("Unsafe shutdowns:               %s\n",
379 	    uint128_to_str(to128(health->unsafe_shutdowns), cbuf, sizeof(cbuf)));
380 	printf("Media errors:                   %s\n",
381 	    uint128_to_str(to128(health->media_errors), cbuf, sizeof(cbuf)));
382 	printf("No. error info log entries:     %s\n",
383 	    uint128_to_str(to128(health->num_error_info_log_entries), cbuf, sizeof(cbuf)));
384 
385 	printf("Warning Temp Composite Time:    %d\n", health->warning_temp_time);
386 	printf("Error Temp Composite Time:      %d\n", health->error_temp_time);
387 	for (i = 0; i < 8; i++) {
388 		if (health->temp_sensor[i] == 0)
389 			continue;
390 		printf("Temperature Sensor %d:           ", i + 1);
391 		print_temp_K(health->temp_sensor[i]);
392 	}
393 	printf("Temperature 1 Transition Count: %d\n", health->tmt1tc);
394 	printf("Temperature 2 Transition Count: %d\n", health->tmt2tc);
395 	printf("Total Time For Temperature 1:   %d\n", health->ttftmt1);
396 	printf("Total Time For Temperature 2:   %d\n", health->ttftmt2);
397 }
398 
399 static void
400 print_log_firmware(const struct nvme_controller_data *cdata, void *buf, uint32_t size __unused)
401 {
402 	int				i, slots;
403 	const char			*status;
404 	struct nvme_firmware_page	*fw = buf;
405 	uint8_t				afi_slot;
406 	uint16_t			oacs_fw;
407 	uint8_t				fw_num_slots;
408 
409 	afi_slot = fw->afi >> NVME_FIRMWARE_PAGE_AFI_SLOT_SHIFT;
410 	afi_slot &= NVME_FIRMWARE_PAGE_AFI_SLOT_MASK;
411 
412 	oacs_fw = (cdata->oacs >> NVME_CTRLR_DATA_OACS_FIRMWARE_SHIFT) &
413 		NVME_CTRLR_DATA_OACS_FIRMWARE_MASK;
414 	fw_num_slots = (cdata->frmw >> NVME_CTRLR_DATA_FRMW_NUM_SLOTS_SHIFT) &
415 		NVME_CTRLR_DATA_FRMW_NUM_SLOTS_MASK;
416 
417 	printf("Firmware Slot Log\n");
418 	printf("=================\n");
419 
420 	if (oacs_fw == 0)
421 		slots = 1;
422 	else
423 		slots = MIN(fw_num_slots, MAX_FW_SLOTS);
424 
425 	for (i = 0; i < slots; i++) {
426 		printf("Slot %d: ", i + 1);
427 		if (afi_slot == i + 1)
428 			status = "  Active";
429 		else
430 			status = "Inactive";
431 
432 		if (fw->revision[i] == 0LLU)
433 			printf("Empty\n");
434 		else
435 			if (isprint(*(char *)&fw->revision[i]))
436 				printf("[%s] %.8s\n", status,
437 				    (char *)&fw->revision[i]);
438 			else
439 				printf("[%s] %016jx\n", status,
440 				    fw->revision[i]);
441 	}
442 }
443 
444 static void
445 print_log_ns(const struct nvme_controller_data *cdata __unused, void *buf,
446     uint32_t size __unused)
447 {
448 	struct nvme_ns_list *nsl;
449 	u_int i;
450 
451 	nsl = (struct nvme_ns_list *)buf;
452 	printf("Changed Namespace List\n");
453 	printf("======================\n");
454 
455 	for (i = 0; i < nitems(nsl->ns) && nsl->ns[i] != 0; i++) {
456 		printf("%08x\n", nsl->ns[i]);
457 	}
458 }
459 
460 static void
461 print_log_command_effects(const struct nvme_controller_data *cdata __unused,
462     void *buf, uint32_t size __unused)
463 {
464 	struct nvme_command_effects_page *ce;
465 	u_int i;
466 	uint32_t s;
467 
468 	ce = (struct nvme_command_effects_page *)buf;
469 	printf("Commands Supported and Effects\n");
470 	printf("==============================\n");
471 	printf("  Command\tLBCC\tNCC\tNIC\tCCC\tCSE\tUUID\n");
472 
473 	for (i = 0; i < 255; i++) {
474 		s = ce->acs[i];
475 		if (((s >> NVME_CE_PAGE_CSUP_SHIFT) &
476 		     NVME_CE_PAGE_CSUP_MASK) == 0)
477 			continue;
478 		printf("Admin\t%02x\t%s\t%s\t%s\t%s\t%u\t%s\n", i,
479 		    ((s >> NVME_CE_PAGE_LBCC_SHIFT) &
480 		     NVME_CE_PAGE_LBCC_MASK) ? "Yes" : "No",
481 		    ((s >> NVME_CE_PAGE_NCC_SHIFT) &
482 		     NVME_CE_PAGE_NCC_MASK) ? "Yes" : "No",
483 		    ((s >> NVME_CE_PAGE_NIC_SHIFT) &
484 		     NVME_CE_PAGE_NIC_MASK) ? "Yes" : "No",
485 		    ((s >> NVME_CE_PAGE_CCC_SHIFT) &
486 		     NVME_CE_PAGE_CCC_MASK) ? "Yes" : "No",
487 		    ((s >> NVME_CE_PAGE_CSE_SHIFT) &
488 		     NVME_CE_PAGE_CSE_MASK),
489 		    ((s >> NVME_CE_PAGE_UUID_SHIFT) &
490 		     NVME_CE_PAGE_UUID_MASK) ? "Yes" : "No");
491 	}
492 	for (i = 0; i < 255; i++) {
493 		s = ce->iocs[i];
494 		if (((s >> NVME_CE_PAGE_CSUP_SHIFT) &
495 		     NVME_CE_PAGE_CSUP_MASK) == 0)
496 			continue;
497 		printf("I/O\t%02x\t%s\t%s\t%s\t%s\t%u\t%s\n", i,
498 		    ((s >> NVME_CE_PAGE_LBCC_SHIFT) &
499 		     NVME_CE_PAGE_LBCC_MASK) ? "Yes" : "No",
500 		    ((s >> NVME_CE_PAGE_NCC_SHIFT) &
501 		     NVME_CE_PAGE_NCC_MASK) ? "Yes" : "No",
502 		    ((s >> NVME_CE_PAGE_NIC_SHIFT) &
503 		     NVME_CE_PAGE_NIC_MASK) ? "Yes" : "No",
504 		    ((s >> NVME_CE_PAGE_CCC_SHIFT) &
505 		     NVME_CE_PAGE_CCC_MASK) ? "Yes" : "No",
506 		    ((s >> NVME_CE_PAGE_CSE_SHIFT) &
507 		     NVME_CE_PAGE_CSE_MASK),
508 		    ((s >> NVME_CE_PAGE_UUID_SHIFT) &
509 		     NVME_CE_PAGE_UUID_MASK) ? "Yes" : "No");
510 	}
511 }
512 
513 static void
514 print_log_res_notification(const struct nvme_controller_data *cdata __unused,
515     void *buf, uint32_t size __unused)
516 {
517 	struct nvme_res_notification_page *rn;
518 
519 	rn = (struct nvme_res_notification_page *)buf;
520 	printf("Reservation Notification\n");
521 	printf("========================\n");
522 
523 	printf("Log Page Count:                %ju\n", rn->log_page_count);
524 	printf("Log Page Type:                 ");
525 	switch (rn->log_page_type) {
526 	case 0:
527 		printf("Empty Log Page\n");
528 		break;
529 	case 1:
530 		printf("Registration Preempted\n");
531 		break;
532 	case 2:
533 		printf("Reservation Released\n");
534 		break;
535 	case 3:
536 		printf("Reservation Preempted\n");
537 		break;
538 	default:
539 		printf("Unknown %x\n", rn->log_page_type);
540 		break;
541 	};
542 	printf("Number of Available Log Pages: %d\n", rn->available_log_pages);
543 	printf("Namespace ID:                  0x%x\n", rn->nsid);
544 }
545 
546 static void
547 print_log_sanitize_status(const struct nvme_controller_data *cdata __unused,
548     void *buf, uint32_t size __unused)
549 {
550 	struct nvme_sanitize_status_page *ss;
551 	u_int p;
552 
553 	ss = (struct nvme_sanitize_status_page *)buf;
554 	printf("Sanitize Status\n");
555 	printf("===============\n");
556 
557 	printf("Sanitize Progress:                   %u%% (%u/65535)\n",
558 	    (ss->sprog * 100 + 32768) / 65536, ss->sprog);
559 	printf("Sanitize Status:                     ");
560 	switch ((ss->sstat >> NVME_SS_PAGE_SSTAT_STATUS_SHIFT) &
561 	    NVME_SS_PAGE_SSTAT_STATUS_MASK) {
562 	case NVME_SS_PAGE_SSTAT_STATUS_NEVER:
563 		printf("Never sanitized");
564 		break;
565 	case NVME_SS_PAGE_SSTAT_STATUS_COMPLETED:
566 		printf("Completed");
567 		break;
568 	case NVME_SS_PAGE_SSTAT_STATUS_INPROG:
569 		printf("In Progress");
570 		break;
571 	case NVME_SS_PAGE_SSTAT_STATUS_FAILED:
572 		printf("Failed");
573 		break;
574 	case NVME_SS_PAGE_SSTAT_STATUS_COMPLETEDWD:
575 		printf("Completed with deallocation");
576 		break;
577 	default:
578 		printf("Unknown");
579 		break;
580 	}
581 	p = (ss->sstat >> NVME_SS_PAGE_SSTAT_PASSES_SHIFT) &
582 	    NVME_SS_PAGE_SSTAT_PASSES_MASK;
583 	if (p > 0)
584 		printf(", %d passes", p);
585 	if ((ss->sstat >> NVME_SS_PAGE_SSTAT_GDE_SHIFT) &
586 	    NVME_SS_PAGE_SSTAT_GDE_MASK)
587 		printf(", Global Data Erased");
588 	printf("\n");
589 	printf("Sanitize Command Dword 10:           0x%x\n", ss->scdw10);
590 	printf("Time For Overwrite:                  %u sec\n", ss->etfo);
591 	printf("Time For Block Erase:                %u sec\n", ss->etfbe);
592 	printf("Time For Crypto Erase:               %u sec\n", ss->etfce);
593 	printf("Time For Overwrite No-Deallocate:    %u sec\n", ss->etfownd);
594 	printf("Time For Block Erase No-Deallocate:  %u sec\n", ss->etfbewnd);
595 	printf("Time For Crypto Erase No-Deallocate: %u sec\n", ss->etfcewnd);
596 }
597 
598 static const char *
599 self_test_res[] = {
600 	[0] = "completed without error",
601 	[1] = "aborted by a Device Self-test command",
602 	[2] = "aborted by a Controller Level Reset",
603 	[3] = "aborted due to namespace removal",
604 	[4] = "aborted due to Format NVM command",
605 	[5] = "failed due to fatal or unknown test error",
606 	[6] = "completed with an unknown segment that failed",
607 	[7] = "completed with one or more failed segments",
608 	[8] = "aborted for unknown reason",
609 	[9] = "aborted due to a sanitize operation",
610 };
611 static uint32_t self_test_res_max = nitems(self_test_res);
612 
613 static void
614 print_log_self_test_status(const struct nvme_controller_data *cdata __unused,
615     void *buf, uint32_t size __unused)
616 {
617 	struct nvme_device_self_test_page *dst;
618 	uint32_t r;
619 
620 	dst = buf;
621 	printf("Device Self-test Status\n");
622 	printf("=======================\n");
623 
624 	printf("Current Operation: ");
625 	switch (dst->curr_operation) {
626 	case 0x0:
627 		printf("No device self-test operation in progress\n");
628 		break;
629 	case 0x1:
630 		printf("Short device self-test operation in progress\n");
631 		break;
632 	case 0x2:
633 		printf("Extended device self-test operation in progress\n");
634 		break;
635 	case 0xe:
636 		printf("Vendor specific\n");
637 		break;
638 	default:
639 		printf("Reserved (0x%x)\n", dst->curr_operation);
640 	}
641 
642 	if (dst->curr_operation != 0)
643 		printf("Current Completion: %u%%\n", dst->curr_compl & 0x7f);
644 
645 	printf("Results\n");
646 	for (r = 0; r < 20; r++) {
647 		uint64_t failing_lba;
648 		uint8_t code, res;
649 
650 		code = (dst->result[r].status >> 4) & 0xf;
651 		res  = dst->result[r].status & 0xf;
652 
653 		if (res == 0xf)
654 			continue;
655 
656 		printf("[%2u] ", r);
657 		switch (code) {
658 		case 0x1:
659 			printf("Short device self-test");
660 			break;
661 		case 0x2:
662 			printf("Extended device self-test");
663 			break;
664 		case 0xe:
665 			printf("Vendor specific");
666 			break;
667 		default:
668 			printf("Reserved (0x%x)", code);
669 		}
670 		if (res < self_test_res_max)
671 			printf(" %s", self_test_res[res]);
672 		else
673 			printf(" Reserved status 0x%x", res);
674 
675 		if (res == 7)
676 			printf(" starting in segment %u", dst->result[r].segment_num);
677 
678 #define BIT(b) (1 << (b))
679 		if (dst->result[r].valid_diag_info & BIT(0))
680 			printf(" NSID=0x%x", dst->result[r].nsid);
681 		if (dst->result[r].valid_diag_info & BIT(1)) {
682 			memcpy(&failing_lba, dst->result[r].failing_lba,
683 			    sizeof(failing_lba));
684 			printf(" FLBA=0x%jx", failing_lba);
685 		}
686 		if (dst->result[r].valid_diag_info & BIT(2))
687 			printf(" SCT=0x%x", dst->result[r].status_code_type);
688 		if (dst->result[r].valid_diag_info & BIT(3))
689 			printf(" SC=0x%x", dst->result[r].status_code);
690 #undef BIT
691 		printf("\n");
692 	}
693 }
694 
695 /*
696  * Table of log page printer / sizing.
697  *
698  * Make sure you keep all the pages of one vendor together so -v help
699  * lists all the vendors pages.
700  */
701 NVME_LOGPAGE(error,
702     NVME_LOG_ERROR,			NULL,	"Drive Error Log",
703     print_log_error, 			0);
704 NVME_LOGPAGE(health,
705     NVME_LOG_HEALTH_INFORMATION,	NULL,	"Health/SMART Data",
706     print_log_health, 			sizeof(struct nvme_health_information_page));
707 NVME_LOGPAGE(fw,
708     NVME_LOG_FIRMWARE_SLOT,		NULL,	"Firmware Information",
709     print_log_firmware,			sizeof(struct nvme_firmware_page));
710 NVME_LOGPAGE(ns,
711     NVME_LOG_CHANGED_NAMESPACE,		NULL,	"Changed Namespace List",
712     print_log_ns,			sizeof(struct nvme_ns_list));
713 NVME_LOGPAGE(ce,
714     NVME_LOG_COMMAND_EFFECT,		NULL,	"Commands Supported and Effects",
715     print_log_command_effects,		sizeof(struct nvme_command_effects_page));
716 NVME_LOGPAGE(dst,
717     NVME_LOG_DEVICE_SELF_TEST,		NULL,	"Device Self-test",
718     print_log_self_test_status,		sizeof(struct nvme_device_self_test_page));
719 NVME_LOGPAGE(thi,
720     NVME_LOG_TELEMETRY_HOST_INITIATED,	NULL,	"Telemetry Host-Initiated",
721     NULL,				DEFAULT_SIZE);
722 NVME_LOGPAGE(tci,
723     NVME_LOG_TELEMETRY_CONTROLLER_INITIATED,	NULL,	"Telemetry Controller-Initiated",
724     NULL,				DEFAULT_SIZE);
725 NVME_LOGPAGE(egi,
726     NVME_LOG_ENDURANCE_GROUP_INFORMATION,	NULL,	"Endurance Group Information",
727     NULL,				DEFAULT_SIZE);
728 NVME_LOGPAGE(plpns,
729     NVME_LOG_PREDICTABLE_LATENCY_PER_NVM_SET,	NULL,	"Predictable Latency Per NVM Set",
730     NULL,				DEFAULT_SIZE);
731 NVME_LOGPAGE(ple,
732     NVME_LOG_PREDICTABLE_LATENCY_EVENT_AGGREGATE,	NULL,	"Predictable Latency Event Aggregate",
733     NULL,				DEFAULT_SIZE);
734 NVME_LOGPAGE(ana,
735     NVME_LOG_ASYMMETRIC_NAMESPACE_ACCESS,	NULL,	"Asymmetric Namespace Access",
736     NULL,				DEFAULT_SIZE);
737 NVME_LOGPAGE(pel,
738     NVME_LOG_PERSISTENT_EVENT_LOG,	NULL,	"Persistent Event Log",
739     NULL,				DEFAULT_SIZE);
740 NVME_LOGPAGE(lbasi,
741     NVME_LOG_LBA_STATUS_INFORMATION,	NULL,	"LBA Status Information",
742     NULL,				DEFAULT_SIZE);
743 NVME_LOGPAGE(egea,
744     NVME_LOG_ENDURANCE_GROUP_EVENT_AGGREGATE,	NULL,	"Endurance Group Event Aggregate",
745     NULL,				DEFAULT_SIZE);
746 NVME_LOGPAGE(res_notification,
747     NVME_LOG_RES_NOTIFICATION,		NULL,	"Reservation Notification",
748     print_log_res_notification,		sizeof(struct nvme_res_notification_page));
749 NVME_LOGPAGE(sanitize_status,
750     NVME_LOG_SANITIZE_STATUS,		NULL,	"Sanitize Status",
751     print_log_sanitize_status,		sizeof(struct nvme_sanitize_status_page));
752 
753 static void
754 logpage_help(void)
755 {
756 	const struct logpage_function	*f;
757 	const char 			*v;
758 
759 	fprintf(stderr, "\n");
760 	fprintf(stderr, "%-8s %-10s %s\n", "Page", "Vendor","Page Name");
761 	fprintf(stderr, "-------- ---------- ----------\n");
762 	SLIST_FOREACH(f, &logpages, link) {
763 		v = f->vendor == NULL ? "-" : f->vendor;
764 		fprintf(stderr, "0x%02x     %-10s %s\n", f->log_page, v, f->name);
765 	}
766 
767 	exit(EX_USAGE);
768 }
769 
770 static void
771 logpage(const struct cmd *f, int argc, char *argv[])
772 {
773 	int				fd;
774 	char				*path;
775 	uint32_t			nsid, size;
776 	void				*buf;
777 	const struct logpage_function	*lpf;
778 	struct nvme_controller_data	cdata;
779 	print_fn_t			print_fn;
780 	uint8_t				ns_smart;
781 
782 	if (arg_parse(argc, argv, f))
783 		return;
784 	if (opt.hex && opt.binary) {
785 		fprintf(stderr,
786 		    "Can't specify both binary and hex\n");
787 		arg_help(argc, argv, f);
788 	}
789 	if (opt.vendor != NULL && strcmp(opt.vendor, "help") == 0)
790 		logpage_help();
791 	if (opt.page == NONE) {
792 		fprintf(stderr, "Missing page_id (-p).\n");
793 		arg_help(argc, argv, f);
794 	}
795 	open_dev(opt.dev, &fd, 0, 1);
796 	get_nsid(fd, &path, &nsid);
797 	if (nsid == 0) {
798 		nsid = NVME_GLOBAL_NAMESPACE_TAG;
799 	} else {
800 		close(fd);
801 		open_dev(path, &fd, 0, 1);
802 	}
803 	free(path);
804 
805 	if (read_controller_data(fd, &cdata))
806 		errx(EX_IOERR, "Identify request failed");
807 
808 	ns_smart = (cdata.lpa >> NVME_CTRLR_DATA_LPA_NS_SMART_SHIFT) &
809 		NVME_CTRLR_DATA_LPA_NS_SMART_MASK;
810 
811 	/*
812 	 * The log page attributes indicate whether or not the controller
813 	 * supports the SMART/Health information log page on a per
814 	 * namespace basis.
815 	 */
816 	if (nsid != NVME_GLOBAL_NAMESPACE_TAG) {
817 		if (opt.page != NVME_LOG_HEALTH_INFORMATION)
818 			errx(EX_USAGE, "log page %d valid only at controller level",
819 			    opt.page);
820 		if (ns_smart == 0)
821 			errx(EX_UNAVAILABLE,
822 			    "controller does not support per namespace "
823 			    "smart/health information");
824 	}
825 
826 	print_fn = print_log_hex;
827 	size = DEFAULT_SIZE;
828 	if (opt.binary)
829 		print_fn = print_bin;
830 	if (!opt.binary && !opt.hex) {
831 		/*
832 		 * See if there is a pretty print function for the specified log
833 		 * page.  If one isn't found, we just revert to the default
834 		 * (print_hex). If there was a vendor specified by the user, and
835 		 * the page is vendor specific, don't match the print function
836 		 * unless the vendors match.
837 		 */
838 		SLIST_FOREACH(lpf, &logpages, link) {
839 			if (lpf->vendor != NULL && opt.vendor != NULL &&
840 			    strcmp(lpf->vendor, opt.vendor) != 0)
841 				continue;
842 			if (opt.page != lpf->log_page)
843 				continue;
844 			if (lpf->print_fn != NULL)
845 				print_fn = lpf->print_fn;
846 			size = lpf->size;
847 			break;
848 		}
849 	}
850 
851 	if (opt.page == NVME_LOG_ERROR) {
852 		size = sizeof(struct nvme_error_information_entry);
853 		size *= (cdata.elpe + 1);
854 	}
855 
856 	/* Read the log page */
857 	buf = get_log_buffer(size);
858 	read_logpage(fd, opt.page, nsid, opt.lsp, opt.lsi, opt.rae, buf, size);
859 	print_fn(&cdata, buf, size);
860 
861 	close(fd);
862 	exit(0);
863 }
864