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