Skip to contentSkip to conversation

nvme-cli: add nvme top command for real-time monitoring

PATCH Superseded Nilay Shroff 1 participant 8 messages May 11

Subsystems (2)

v2 of 3 Superseded Latest is v3 →

lore
Share & tools
lore
#1 lore raw

PATCH v2 1/7 nvme: add support for unsigned and long types in table_get_value_width()

In reply to Nilay Shroff

The table API automatically adjusts column width based on the width of the value being printed. While table_print_XXX() already supports unsigned, unsigned long, and long data types, the corresponding helper table_get_value_width() does not account for these types.

Add support for unsigned, unsigned long, and long in table_get_value_ width() so that column width calculation is consistent with the supported print helpers.

This will be used by the nvme top dashboard, where several statistics are represented using these data types.

---
 util/table.c | 9 +++++++++
 1 file changed, 9 insertions(+)
util/table.c +9 -0
index 76366b93d..cad88d39d 100644
@@ -34,6 +34,15 @@ static int table_get_value_width(struct value *v)
 	case FMT_INT:
 		len = snprintf(buf, sizeof(buf), "%d", v->i);
 		break;
+	case FMT_UNSIGNED:
+		len = snprintf(buf, sizeof(buf), "%u", v->u);
+		break;
+	case FMT_UNSIGNED_LONG:
+		len = snprintf(buf, sizeof(buf), "%lu", v->lu);
+		break;
+	case FMT_LONG:
+		len = snprintf(buf, sizeof(buf), "%ld", v->ld);
+		break;
 	default:
 		printf("Invalid print format!\n");
 		break;
Signature · 1 line
2.53.0
#0 lore raw

v2 cover nvme-cli: add nvme top command for real-time monitoring

Hi,

Monitoring NVMe devices and paths in production is currently limited to static snapshots via nvme-cli. While this is sufficient for basic inspection, it is not ideal for NVMe-oF (fabrics) deployments where path conditions can change dynamically due to varying network latency, congestion, or link failures.

In multipath environments, administrators often need continuous visibility into path state, ANA status, queue depth, link speed, and error counters. Today, this typically requires repeatedly invoking commands or relying on ad-hoc tooling, making it harder to quickly identify issues.

This patch series introduces "nvme top", a tool for real-time monitoring of NVMe devices and fabrics paths, similar in spirit to tools such as top or iotop. The goal is to provide a continuously updating view of device and path health, enabling faster detection of link degradation, multipath imbalances, and transient failures.

The series first adds the necessary building blocks for supporting a top-like dashboard. The initial patches extend the table APIs (including support for additional data types such as unsigned, long, float, and double) and introduce a generic dashboard framework. The final patch adds the nvme top command built on top of this framework.

Future work:
- Export NVMe statistics to external monitoring systems (e.g. Grafana).
- Improve topology change detection in multipath configurations. The current implementation relies on kobject uevents for topology change, but namespace path add/delete events are not exported by the kernel since they are associated with hidden gendisk kobjects. This may require explicit uevent generation from the NVMe driver for namespace path changes.
- Wire nvme top into an MCP pipeline and feed it to an LLM

As usual feedback, comments, and suggestions are welcome!

Changes since v1:
- Addressed review comments from AI chatbot Copilot:

    https://github.com/linux-nvme/nvme-cli/pull/3333

Link to v1: https://lore.kernel.org/all/[email protected]/

Nilay Shroff (7):
nvme: add support for unsigned and long types in
table_get_value_width()
nvme: use table_get_value_width() in table_print_centered()
nvme: add support for float and double types in table_print_XXX()
nvme: allow table output to be directed to a FILE stream
nvme: add sigaction for SIGWINCH
nvme: add generic top-like dashboard framework
nvme: add nvme top command

 meson.build         |    1 +
 nvme-builtin.h      |    1 +
 nvme-print-stdout.c | 1206 +++++++++++++++++++++++++++++++++++++++++++
 nvme-print.c        |    5 +
 nvme-print.h        |    5 +-
 nvme-top.c          |  345 +++++++++++++
 nvme-top.h          |   30 ++
 nvme.c              |   39 ++
 util/dashboard.c    |  882 +++++++++++++++++++++++++++++++
 util/dashboard.h    |   55 ++
 util/meson.build    |    3 +-
 util/sighdl.c       |   16 +-
 util/sighdl.h       |    4 +-
 util/table.c        |  124 +++--
 util/table.h        |   28 +
 15 files changed, 2684 insertions(+), 60 deletions(-)
 create mode 100644 nvme-top.c
 create mode 100644 nvme-top.h
 create mode 100644 util/dashboard.c
 create mode 100644 util/dashboard.h
Signature · 1 line
2.53.0
#5 lore raw

PATCH v2 5/7 nvme: add sigaction for SIGWINCH

Add a sigaction handler for SIGWINCH so that nvme-top can detect terminal window size changes.

This allows the dashboard layout to be adjusted and redrawn when the terminal is resized. To avoid undefined behavior and async-signal-safety the data type for nvme_sigwinch_received is defined as volatile sig_atomic_t.

While we are at it, also update the data type of nvme_sigint_received to volatile sig_atomic_t.

---
 util/sighdl.c | 16 ++++++++++++----
 util/sighdl.h |  4 +++-
 2 files changed, 15 insertions(+), 5 deletions(-)
util/sighdl.c +12 -4
index 146591e5d..2899e9cb3 100644
@@ -5,11 +5,15 @@
 
 #include "sighdl.h"
 
-bool nvme_sigint_received;
+volatile sig_atomic_t nvme_sigint_received;
+volatile sig_atomic_t nvme_sigwinch_received;
 
-static void nvme_sigint_handler(int signum)
+static void nvme_sig_handler(int signum)
 {
-	nvme_sigint_received = true;
+	if (signum == SIGINT)
+		nvme_sigint_received = true;
+	else if (signum == SIGWINCH)
+		nvme_sigwinch_received = true;
 }
 
 int nvme_install_sigint_handler(void)
@@ -17,12 +21,16 @@ int nvme_install_sigint_handler(void)
 	struct sigaction act;
 
 	sigemptyset(&act.sa_mask);
-	act.sa_handler = nvme_sigint_handler;
+	act.sa_handler = nvme_sig_handler;
 	act.sa_flags = 0;
 
 	nvme_sigint_received = false;
 	if (sigaction(SIGINT, &act, NULL) == -1)
 		return -errno;
 
+	nvme_sigwinch_received = false;
+	if (sigaction(SIGWINCH, &act, NULL) == -1)
+		return -errno;
+
 	return 0;
 }
util/sighdl.h +3 -1
index 8d5d1c126..41c823abe 100644
@@ -3,8 +3,10 @@
 #define __NVME_SIGHDL
 
 #include <stdbool.h>
+#include <signal.h>
 
-extern bool nvme_sigint_received;
+extern volatile sig_atomic_t nvme_sigint_received;
+extern volatile sig_atomic_t nvme_sigwinch_received;
 
 int nvme_install_sigint_handler(void);
 
Signature · 1 line
2.53.0
#4 lore raw

PATCH v2 4/7 nvme: allow table output to be directed to a FILE stream

In reply to Nilay Shroff

The table APIs currently print output only to stdout. However, callers may need to direct output to other destinations such as stderr, a file, or an in-memory buffer.

Add support for passing a FILE * stream so callers can choose where the table output is written.

This will be used by the nvme top dashboard to control how statistics are displayed.

---
 util/table.c | 75 +++++++++++++++++++++++++++++-----------------------
 util/table.h |  2 ++
 2 files changed, 44 insertions(+), 33 deletions(-)
util/table.c +42 -33
index 60302fff7..5f19a7aa1 100644
@@ -57,7 +57,7 @@ static int table_get_value_width(struct value *v)
 	return len;
 }
 
-static void table_print_centered(struct value *val, int width, enum fmt_type type)
+static void table_print_centered(FILE *stream, struct value *val, int width)
 {
 	int i, len, left_pad, right_pad;
 
@@ -70,29 +70,30 @@ static void table_print_centered(struct value *val, int width, enum fmt_type typ
 
 	/* add left padding */
 	for (i = 0; i < left_pad; i++)
-		putchar(' ');
+		fputc(' ', stream);
 
 	/* print value */
 	switch (val->type) {
 	case FMT_STRING:
-		printf("%s", val->s);
+		fprintf(stream, "%s", val->s);
 		break;
 	case FMT_INT:
-		printf("%d", val->i);
+		fprintf(stream, "%d", val->i);
 		break;
 	case FMT_UNSIGNED:
-		printf("%u", val->u);
+		fprintf(stream, "%u", val->u);
 		break;
 	case FMT_LONG:
-		printf("%ld", val->ld);
+		fprintf(stream, "%ld", val->ld);
 		break;
 	case FMT_UNSIGNED_LONG:
-		printf("%lu", val->lu);
+		fprintf(stream, "%lu", val->lu);
+		break;
 	case FMT_FLOAT:
-		printf("%.2f", val->f);
+		fprintf(stream, "%.2f", val->f);
 		break;
 	case FMT_DOUBLE:
-		printf("%.2f", val->d);
+		fprintf(stream, "%.2f", val->d);
 		break;
 	default:
 		nvme_show_error("Invalid print format!\n");
@@ -101,10 +102,10 @@ static void table_print_centered(struct value *val, int width, enum fmt_type typ
 
 	/* add right padding */
 	for (i = 0; i < right_pad; i++)
-		putchar(' ');
+		fputc(' ', stream);
 }
 
-static void table_print_columns(const struct table *t)
+static void table_print_columns(FILE *stream, const struct table *t)
 {
 	int col, j, width;
 	struct table_column *c;
@@ -117,32 +118,33 @@ static void table_print_columns(const struct table *t)
 		case CENTERED:
 			v.s = c->name;
 			v.align = c->align;
-			table_print_centered(&v, width, FMT_STRING);
+			v.type = FMT_STRING;
+			table_print_centered(stream, &v, width);
 			break;
 		case LEFT:
 			width *= -1;
 			fallthrough;
 		default:
-			printf("%*s", width, c->name);
+			fprintf(stream, "%*s", width, c->name);
 			break;
 		}
 		if (col + 1 != t->num_columns)
-			putchar(' ');
+			fputc(' ', stream);
 	}
 
-	printf("\n");
+	fprintf(stream, "\n");
 
 	for (col = 0; col < t->num_columns; col++) {
 		for (j = 0; j < t->columns[col].width; j++)
-			putchar('-');
+			fputc('-', stream);
 		if (col + 1 != t->num_columns)
-			putchar(' ');
+			fputc(' ', stream);
 	}
 
-	printf("\n");
+	fprintf(stream, "\n");
 }
 
-static void table_print_rows(const struct table *t)
+static void table_print_rows(FILE *stream, const struct table *t)
 {
 	int row, col;
 	struct table_column *c;
@@ -151,15 +153,15 @@ static void table_print_rows(const struct table *t)
 	struct value *v;
 
 	for (row = 0; row < t->num_rows; row++) {
+		r = &t->rows[row];
 		for (col = 0; col < t->num_columns; col++) {
 			c = &t->columns[col];
-			r = &t->rows[row];
 			v = &r->val[col];
 
 			width = c->width;
 			switch (v->align) {
 			case CENTERED:
-				table_print_centered(v, width, v->type);
+				table_print_centered(stream, v, width);
 				break;
 			case LEFT:
 				width *= -1;
@@ -167,24 +169,25 @@ static void table_print_rows(const struct table *t)
 			default:
 				switch (v->type) {
 				case FMT_STRING:
-					printf("%*s", width, v->s);
+					fprintf(stream, "%*s", width, v->s);
 					break;
 				case FMT_INT:
-					printf("%*d", width, v->i);
+					fprintf(stream, "%*d", width, v->i);
 					break;
 				case FMT_UNSIGNED:
-					printf("%*u", width, v->u);
+					fprintf(stream, "%*u", width, v->u);
 					break;
 				case FMT_LONG:
-					printf("%*ld", width, v->ld);
+					fprintf(stream, "%*ld", width, v->ld);
 					break;
 				case FMT_UNSIGNED_LONG:
-					printf("%*lu", width, v->lu);
+					fprintf(stream, "%*lu", width, v->lu);
+					break;
 				case FMT_FLOAT:
-					printf("%*.2f", width, v->f);
+					fprintf(stream, "%*.2f", width, v->f);
 					break;
 				case FMT_DOUBLE:
-					printf("%*.2f", width, v->d);
+					fprintf(stream, "%*.2f", width, v->d);
 					break;
 				default:
 					nvme_show_error("Invalid format!\n");
@@ -193,19 +196,25 @@ static void table_print_rows(const struct table *t)
 				break;
 			}
 			if (col + 1 != t->num_columns)
-				putchar(' ');
+				fputc(' ', stream);
 		}
-		printf("\n");
+
+		fprintf(stream, "\n");
 	}
 }
 
-void table_print(struct table *t)
+void table_print_stream(FILE *stream, struct table *t)
 {
 	/* first print columns */
-	table_print_columns(t);
+	table_print_columns(stream, t);
 
 	/* next print rows */
-	table_print_rows(t);
+	table_print_rows(stream, t);
+}
+
+void table_print(struct table *t)
+{
+	table_print_stream(stdout, t);
 }
 
 int table_get_row_id(struct table *t)
util/table.h +2 -0
index 045ed2439..cb374947f 100644
@@ -2,6 +2,7 @@
 #ifndef _TABLE_H_
 #define _TABLE_H_
 
+#include <stdio.h>
 #include <stdbool.h>
 
 enum fmt_type {
@@ -169,6 +170,7 @@ int table_add_columns_filter(struct table *t, struct table_column *c,
 			void *arg);
 int table_get_row_id(struct table *t);
 void table_add_row(struct table *t, int row);
+void table_print_stream(FILE *stream, struct table *t);
 void table_print(struct table *t);
 void table_free(struct table *t);
 
Signature · 1 line
2.53.0
#2 lore raw

PATCH v2 2/7 nvme: use table_get_value_width() in table_print_centered()

In reply to Nilay Shroff

table_print_centered() open-codes the logic to determine the width of a table value, even though a helper already exists for this purpose.

Replace the open-coded width calculation with a call to table_get_value_width() to avoid duplication and keep the behavior consistent across the table helpers. Also, ensure that table_get_value_width() returns -1 on failure so the caller could then handle error as needed.

---
 util/table.c | 26 ++++----------------------
 1 file changed, 4 insertions(+), 22 deletions(-)
util/table.c +4 -22
index cad88d39d..1fed89db8 100644
@@ -25,7 +25,7 @@
 static int table_get_value_width(struct value *v)
 {
 	char buf[64];
-	int len = 0;
+	int len = -1;
 
 	switch (v->type) {
 	case FMT_STRING:
@@ -53,28 +53,10 @@ static int table_get_value_width(struct value *v)
 static void table_print_centered(struct value *val, int width, enum fmt_type type)
 {
 	int i, len, left_pad, right_pad;
-	char buf[64];
 
-	switch (type) {
-	case FMT_STRING:
-		len = strlen(val->s);
-		break;
-	case FMT_INT:
-		len = snprintf(buf, sizeof(buf), "%d", val->i);
-		break;
-	case FMT_UNSIGNED:
-		len = snprintf(buf, sizeof(buf), "%u", val->u);
-		break;
-	case FMT_LONG:
-		len = snprintf(buf, sizeof(buf), "%ld", val->ld);
-		break;
-	case FMT_UNSIGNED_LONG:
-		len = snprintf(buf, sizeof(buf), "%lu", val->lu);
-		break;
-	default:
-		fprintf(stderr, "Invalid format!\n");
+	len = table_get_value_width(val);
+	if (len < 0)
 		return;
-	}
 
 	left_pad = (width - len) / 2;
 	right_pad = width - len - left_pad;
@@ -84,7 +66,7 @@ static void table_print_centered(struct value *val, int width, enum fmt_type typ
 		putchar(' ');
 
 	/* print value */
-	switch (type) {
+	switch (val->type) {
 	case FMT_STRING:
 		printf("%s", val->s);
 		break;
Signature · 1 line
2.53.0
#6 lore raw

PATCH v2 6/7 nvme: add generic top-like dashboard framework

In reply to Nilay Shroff

Add a generic dashboard framework to support interactive, top-like views. The framework renders data within a fixed-size window backed by a larger buffer and provides event-driven APIs for updating the display.

Supported events:

- key input (ESC, Enter, 'q')
- escape sequences (up/down arrows)
- SIGWINCH for terminal resize handling
- periodic refresh via timeout
- kobject uevents (via netlink) to detect NVMe topology changes (subsystem, controller, namespace)
- reverse video highlighting for rows

Exported APIs:

- FILE *dashboard_init(struct dashboard_ctx **db_ctx, int interval) Initialize the dashboard context. Returns a FILE * stream used by the caller to write data for rendering. The returned context is used by all other dashboard APIs. The @interval is specified in seconds which represents the dashboard refresh interval.

- void dashboard_exit(struct dashboard_ctx *db_ctx) Tear down the dashboard and free all resources.

- int dashboard_draw_frame(struct dashboard_ctx *db_ctx, int scroll) Render the current frame. If @scroll is non-zero, adjust the view based on scrolling (up/down); otherwise render a new buffer.

- enum event_type dashboard_wait_for_event(struct dashboard_ctx *db_ctx) Wait for events such as key input, timeout, uevent, or SIGWINCH. Callers are expected to implement an event loop, and then based on returned event type take the action. For instance, if the returned event is timeout then caller shall update/refill the data store buffer and invoke dashboard_draw_frame() so that new/updated data could be rendered on dashboard . If the returned event type is up/down arrow keys then caller shall adjust the data start index in data store buffer and invoke dashboard_draw_frame() for rendering data. If the returned event type is key press 'ESC' or 'q' or kobject uevent then user shall take action as appropriate.

Reverse video helpers:

dashboard_{set,reset}_header_row_reverse()
dashboard_{set,reset}_footer_row_reverse()
dashboard_{set,reset}_data_row_reverse()

Additional getters/setters:

dashboard_get_interval()
dashboard_get_header_rows()
dashboard_set_header_rows()
dashboard_get_footer_rows()
dashboard_set_footer_rows()
dashboard_get_data_rows()
dashboard_get_data_start()
dashboard_set_data_start()
dashboard_get_frame_data_rows()

This framework is intended for use by nvme-top and similar tools that require dynamic, event-driven terminal dashboards.

---
 util/dashboard.c | 882 +++++++++++++++++++++++++++++++++++++++++++++++
 util/dashboard.h |  55 +++
 util/meson.build |   3 +-
 3 files changed, 939 insertions(+), 1 deletion(-)
 create mode 100644 util/dashboard.c
 create mode 100644 util/dashboard.h
util/dashboard.c new file +882 -0
new file mode 100644
index 000000000..284522f07
@@ -0,0 +1,882 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+/*
+ * dashboard.c : Generic implementation for live dashboard.
+ *
+ * Copyright (c) 2026 Nilay Shroff, IBM
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ */
+
+#include <stdio.h>
+#include <signal.h>
+#include <sys/select.h>
+#include <sys/ioctl.h>
+#include <termios.h>
+#include <unistd.h>
+#include <string.h>
+#include <errno.h>
+#include <stdbool.h>
+#include <time.h>
+#include <stdlib.h>
+#include <fcntl.h>
+#include <linux/netlink.h>
+#include <sys/socket.h>
+#include <asm/types.h>
+
+#include "sighdl.h"
+#include "common.h"
+#include "nvme-print.h"
+#include "dashboard.h"
+
+#define NSEC_PER_SEC	1000000000L
+
+struct win_frame {
+	/* num of data rows which could fit in visible frame */
+	int data_rows;
+
+	/* Header start offset in window frame (always 0) */
+	int header_start_off;
+
+	/* data start offset in window frame */
+	int data_start_off;
+
+	/* footer start offset in window frame */
+	int footer_start_off;
+
+	/* Total num of rows in window frame */
+	int rows;
+};
+
+struct data_store {
+	/* mem-stream backing the buffer */
+	FILE *stream;
+
+	/* data buffer which is dynamically allocated by mem-stream  */
+	char *buf;
+	/* buffer length */
+	size_t len;
+
+	/* per-row offsets into the data buffer */
+	size_t *row_off;
+
+	/* header, data, footer, and total rows */
+	int header_rows;
+	int data_rows;
+	int footer_rows;
+	int num_rows;
+
+	/*
+	 * Index of the first data row to display. It can be adjusted
+	 * if user navigates/scrolls the screen using arrow keys.
+	 * Range: [0 - data_rows).
+	 */
+	int data_start_idx;
+
+	/* highlighted rows (reverse-video) */
+	int rev_header_row;
+	int rev_data_row;
+	int rev_footer_row;
+};
+
+struct dashboard_ctx {
+	struct data_store ds;	/* data store */
+	struct win_frame frame;	/* window frame */
+	int interval;		/* nvme top refresh interval in seconds */
+	struct timespec rem_interval;	/* remaining refresh interval */
+	int uevent_fd;		/* kernel uevent fd */
+	int term_fd;		/* controlling terminal fd */
+	sigset_t orig_set;	/* original signal mask of the calling thread */
+	struct termios orig_ts;	/* original termio settings of the controlling terminal */
+};
+
+/*
+ * The following comments describes how this generic dashboard implementation
+ * renders data using a fixed-size window frame backed by a potentially larger
+ * data store buffer. It clarifies offsets, row calculations, and scrolling
+ * behavior:
+ *
+ * Window Frame Layout (struct win_frame):
+ * ======================================
+ *    _ _ _ _ _ _ _ _ _ _ _ _ _ _ header_start_off
+ *  /            _ _ _ _ _ _ _ _  data_start_off
+ * |           /             _ _  footer_start_off
+ * |          |            /
+ * |          |            |
+ * v_ _ _ _ _ v _ _ _ _ _ _v_ _ _ _ _ _
+ * |          |            |           |
+ * |  header  |    data    |   footer  |
+ * |_ _ _ _ _ |_ _ _ _ _ _ |_ _ _ _ _ _|
+ * |<-------->|<---------->|<---------->
+ *                  ^     ^
+ *                  |     |
+ *                  |     \_ _ last_data_row
+ *                  \_ _ data_rows
+ *
+ * - The window frame represents the visible terminal screen area. It is
+ *   logically divided into three contiguous regions/sections:
+ *   header, data and footer.
+ * - The window frame size is limited by the terminal dimensions.
+ * - Header and footer sizes are fixed per dashboard layout.
+ * - The data area (includes area remaining after we account for space needed
+ *   for header and footer from the terminal screen area) expands or shrinks
+ *   based on available screen space.
+ *
+ * Data Store Buffer Layout (struct data_store):
+ * =============================================
+ *    _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _  header_start_off
+ *  /            _ _ _ _ _ _ _ _ _ _ _ data_start_off
+ * |           /                    _ _footer_start_off
+ * |          |                   /
+ * |          |                  |
+ * v_ _ _ _ _ v_ _ _ _ _ _ _ _ _ v_ _ _ _ _ _
+ * |          |                  |           |
+ * |  header  |       data       |   footer  |
+ * |_ _ _ _ _ |_ _ _ _ _ _ _ _ _ |_ _ _ _ _ _|
+ * |<-------->|<---------------->|<--------->|
+ * |    ^     ^          ^             ^     |
+ * |    |     |          |             |     |
+ * |    | data_start_idx |             \_ _ _|_footer_rows
+ * |    |                \_ _ _data_rows     |
+ * |    \_ _ _header_rows                    |
+ * |                                         |
+ * |<----------------num_rows -------------->|
+ *
+ *
+ * - The data store buffer holds the complete dashboard content generated at
+ *   each refresh interval. Its size may exceed the window frame, enabling
+ *   scrolling.
+ * - Represents the full logical dashboard content.
+ * - Used as the authoritative source for rendering.
+ * - Scrolling adjusts which portion of the data area is mapped into the
+ *   window frame.
+ *
+ * Relationship Between window frame and data store:
+ * =================================================
+ *  - The data store is transposed onto the window frame at render time.
+ *
+ *  a) Fixed relationship:
+ *     - Header always starts at offset 0.
+ *       In window frame, frame->header_start_off = 0
+ *       In data store, header_start_off = 0
+ *
+ *     - Header height is constant.
+ *       In window frame, frame->data_start_off = ds->header_rows
+ *       In data store, data_start_off = ds->header_rows + ds->data_start_idx
+ *
+ *  b) Footer placement:
+ *     - In the data store,
+ *       footer_start_off = ds->header_rows + ds->data_rows
+ *
+ *     - In the window frame,
+ *       frame->footer_start_off = frame->data_start_off + frame->data_rows
+ *
+ *     These two offsets (footer_start_off in data store and frame->footer_
+ *     start_off) may differ if the frame cannot display all data rows.
+ *
+ *  c) Scrolling Semantics:
+ *     - Scrolling affects only ds->data_start_idx.
+ *     - Header and footer remain pinned and are never scrolled.
+ *     - The frame’s data area acts as a viewport into the data store’s data
+ *       region.
+ *     - The ds->data_start_idx is adjusted based on the terminal scrolling.
+ *       For the first time when dashboard is displayed typically the value of
+ *       ds->data_start_idx is zero, but then if user scrolls the window then
+ *       ds->data_start_idx would be updated. The ds->data_start_idx should be
+ *       never set to less than zero and it should never execeed the num of data
+ *       rows available in the data staore buffer.
+ *
+ *  d) Last visible data row in window frame:
+ *
+ *     If in case window frame data area size is greater than the data store
+ *     data area then we would left with some empty space/rows in data area of
+ *     window frame. So we then clear the empty space beofre start drawing the
+ *     footer.
+ *
+ *     last_data_row = ds->header_rows + frame->data_rows
+ *     If last_data_row > ds->data_rows,
+ *     - The remaining frame rows are cleared.
+ *     - Footer is drawn immediately after the cleared region.
+ *
+ * Reverse-Video Highlighting:
+ * ===========================
+ *  The following fields indicate rows that should be rendered using reverse
+ *  video:
+ *  - rev_header_row
+ *  - rev_data_row
+ *  - rev_footer_row
+ *  These are relative to their respective sections and allow focused
+ *  highlighting.
+ */
+
+static void tty_reset(int fd, struct termios *ts)
+{
+	if (tcsetattr(fd, TCSANOW, ts) < 0)
+		nvme_show_perror("reset terminal attributes");
+}
+
+static int tty_set_raw(int fd, struct termios *ots)
+{
+	struct termios ts;
+
+	if (tcgetattr(fd, &ts) < 0) {
+		nvme_show_perror("get terminal attributes");
+		return -1;
+	}
+
+	*ots = ts;
+
+	ts.c_lflag &= ~(ICANON | ECHO);
+	ts.c_cc[VMIN] = 1;
+	ts.c_cc[VTIME] = 0;
+
+	if (tcsetattr(fd, TCSAFLUSH, &ts) < 0) {
+		nvme_show_perror("set terminal attributes");
+		return -1;
+	}
+
+	return 0;
+}
+
+int dashboard_get_interval(struct dashboard_ctx *db_ctx)
+{
+	return db_ctx->interval;
+}
+
+int dashboard_get_header_rows(struct dashboard_ctx *db_ctx)
+{
+	return db_ctx->ds.header_rows;
+}
+
+void dashboard_set_header_rows(struct dashboard_ctx *db_ctx, int rows)
+{
+	db_ctx->ds.header_rows = rows;
+}
+
+int dashboard_get_footer_rows(struct dashboard_ctx *db_ctx)
+{
+	return db_ctx->ds.footer_rows;
+}
+
+void dashboard_set_footer_rows(struct dashboard_ctx *db_ctx, int rows)
+{
+	db_ctx->ds.footer_rows = rows;
+}
+
+int dashboard_get_data_rows(struct dashboard_ctx *db_ctx)
+{
+	return db_ctx->ds.data_rows;
+}
+
+int dashboard_get_data_start(struct dashboard_ctx *db_ctx)
+{
+	return db_ctx->ds.data_start_idx;
+}
+
+int dashboard_set_data_start(struct dashboard_ctx *db_ctx, int off)
+{
+	if (off >= db_ctx->ds.data_rows)
+		return -EINVAL;
+
+	db_ctx->ds.data_start_idx = off;
+
+	return 0;
+}
+
+int dashboard_get_frame_data_rows(struct dashboard_ctx *db_ctx)
+{
+	return db_ctx->frame.data_rows;
+}
+
+void dashboard_set_data_raw_reverse(struct dashboard_ctx *db_ctx, int row)
+{
+	db_ctx->ds.rev_data_row = row;
+}
+
+void dashboard_reset_data_raw_reverse(struct dashboard_ctx *db_ctx)
+{
+	db_ctx->ds.rev_data_row = -1;
+}
+
+void dashboard_set_header_raw_reverse(struct dashboard_ctx *db_ctx, int row)
+{
+	db_ctx->ds.rev_header_row = row;
+}
+
+void dashboard_reset_header_raw_reverse(struct dashboard_ctx *db_ctx)
+{
+	db_ctx->ds.rev_header_row = -1;
+}
+
+void dashboard_set_footer_raw_reverse(struct dashboard_ctx *db_ctx, int row)
+{
+	db_ctx->ds.rev_footer_row = row;
+}
+
+void dashboard_reset_footer_raw_reverse(struct dashboard_ctx *db_ctx)
+{
+	db_ctx->ds.rev_footer_row = -1;
+}
+
+static void calc_rem_time(struct dashboard_ctx *db_ctx, struct timespec *start)
+{
+	struct timespec now;
+	long interval_ns, rem_interval_ns, start_time_ns, cur_time_ns;
+
+	clock_gettime(CLOCK_MONOTONIC, &now);
+	cur_time_ns = now.tv_sec * NSEC_PER_SEC + now.tv_nsec;
+	start_time_ns = start->tv_sec * NSEC_PER_SEC + start->tv_nsec;
+	if (cur_time_ns <= start_time_ns)
+		return;
+
+	interval_ns = db_ctx->interval * NSEC_PER_SEC;
+	rem_interval_ns = interval_ns - (cur_time_ns - start_time_ns);
+	db_ctx->rem_interval.tv_sec = rem_interval_ns / NSEC_PER_SEC;
+	db_ctx->rem_interval.tv_nsec = rem_interval_ns % NSEC_PER_SEC;
+}
+
+static int wait_for_event(struct dashboard_ctx *db_ctx,
+		unsigned char *c, bool esc_seq)
+{
+	fd_set set;
+	struct timespec ts, t0;
+	int ret, interval_sec, interval_nsec;
+	int term_fd = db_ctx->term_fd;
+	int uevent_fd = db_ctx->uevent_fd;
+	int max_fd = (term_fd > uevent_fd) ? term_fd : uevent_fd;
+
+	/* For escape sequence read, we wait for up to 1 ms. */
+	if (esc_seq) {
+		interval_sec = 0;
+		interval_nsec = 1000000;
+	} else {
+		/*
+		 * If previous pselect() woke up prematurely (might be due to
+		 * due to a key pressed other than allowed-key or non-nvme
+		 * uevent) then sleep for the remaining interval.
+		 */
+		if (db_ctx->rem_interval.tv_sec
+		    || db_ctx->rem_interval.tv_nsec) {
+			interval_sec = db_ctx->rem_interval.tv_sec;
+			interval_nsec = db_ctx->rem_interval.tv_nsec;
+		} else {
+			interval_sec = db_ctx->interval;
+			interval_nsec = 0;
+		}
+	}
+	while (1) {
+		FD_ZERO(&set);
+		FD_SET(term_fd, &set);
+		FD_SET(uevent_fd, &set);
+again:
+		ts.tv_sec = interval_sec;
+		ts.tv_nsec = interval_nsec;
+
+		/*
+		 * Store the time when we start pselect; we may use it later to
+		 * compute the remaining time to sleep in case pselect breaks
+		 * out prematurely (maybe due to interrupted syscall or due to
+		 * any user input).
+		 */
+		clock_gettime(CLOCK_MONOTONIC, &t0);
+
+		ret = pselect(max_fd + 1, &set, NULL, NULL, &ts,
+				&db_ctx->orig_set);
+		if (ret < 0) {
+			if (errno == EINTR) {
+				/* Interrupted, signal is received ? */
+				if (nvme_sigwinch_received) {
+					struct winsize ws;
+
+					if (ioctl(db_ctx->term_fd, TIOCGWINSZ,
+							&ws) < 0)
+						return -1;
+
+					db_ctx->frame.rows = ws.ws_row;
+					nvme_sigwinch_received = false;
+
+					/*
+					 * Returning 0 would force screen redraw
+					 * based on the updated window size.
+					 */
+					return EVENT_TYPE_SIGWINCH;
+				}
+
+				/* compute remaining time */
+				calc_rem_time(db_ctx, &t0);
+				goto again;
+			}
+
+			nvme_show_perror("pselect");
+			return EVENT_TYPE_ERROR;
+		}
+
+		if (ret == 0) {/* timed out waiting */
+			db_ctx->rem_interval.tv_sec = 0;
+			db_ctx->rem_interval.tv_nsec = 0;
+			return EVENT_TYPE_TIMEOUT;
+		}
+
+		if (!esc_seq)
+			calc_rem_time(db_ctx, &t0);
+
+		if (FD_ISSET(uevent_fd, &set)) {
+			char buf[2048];
+			int i, n;
+			int is_subsys_block = 0, is_devname_nvme = 0;
+			int is_subsys_nvme_subsys = 0, is_subsys_nvme = 0;
+
+			while (1) {
+				n = recv(uevent_fd, buf, sizeof(buf),
+						MSG_DONTWAIT);
+				if (n < 0) {
+					if (errno == EAGAIN)
+						break;
+
+					if (errno == EINTR)
+						continue;
+
+					nvme_show_perror("read from uevent fd");
+					return n;
+				}
+
+				for (i = 0; i < n; ) {
+					char *s = &buf[i];
+
+					if (!strncmp(s, "SUBSYSTEM=block", 15))
+						is_subsys_block = 1;
+
+					if (!strncmp(s, "DEVNAME=nvme", 12))
+						is_devname_nvme = 1;
+
+					if (!strncmp(s,
+						"SUBSYSTEM=nvme-subsystem", 24))
+						is_subsys_nvme_subsys = 1;
+
+					if (!strncmp(s, "SUBSYSTEM=nvme", 14))
+						is_subsys_nvme = 1;
+
+					i += strlen(s) + 1;
+				}
+
+				if (is_subsys_block || is_subsys_nvme_subsys ||
+					is_subsys_nvme || is_devname_nvme)
+					return EVENT_TYPE_NVME_UEVENT;
+
+			}
+		}
+
+		if (FD_ISSET(term_fd, &set)) {
+			while (1) {
+				ret = read(term_fd, c, 1);
+				if (ret < 0) {
+					if (errno == EINTR)
+						continue;
+					nvme_show_perror("read from term fd");
+					return EVENT_TYPE_ERROR;
+				}
+				if (ret == 1)
+					return EVENT_TYPE_KEY_PRESS;
+			}
+		}
+	}
+}
+
+enum event_type dashboard_wait_for_event(struct dashboard_ctx *db_ctx)
+{
+	int event;
+	unsigned char c;
+
+	db_ctx->rem_interval.tv_sec = 0;
+	db_ctx->rem_interval.tv_nsec = 0;
+
+	while (1) {
+		event = wait_for_event(db_ctx, &c, 0);
+		switch (event) {
+		case EVENT_TYPE_ERROR:		/* fall through */
+		case EVENT_TYPE_TIMEOUT:	/* fall through */
+		case EVENT_TYPE_NVME_UEVENT:	/* fall through */
+		case EVENT_TYPE_SIGWINCH:
+			return event;
+		default:
+			if (c == 27) {	/* 'ESC' key */
+				/* read escape sequence */
+				event = wait_for_event(db_ctx, &c, 1);
+				switch (event) {
+				case EVENT_TYPE_ERROR:
+					return event;
+				case EVENT_TYPE_TIMEOUT:
+					return EVENT_TYPE_KEY_ESC;
+				default:
+					if (c == 91) {	/* '[' key */
+						event = wait_for_event(db_ctx, &c, 1);
+						switch (event) {
+						case EVENT_TYPE_ERROR:
+							return event;
+						case EVENT_TYPE_TIMEOUT:
+							break;
+						default:
+							if (c == 65)
+								return EVENT_TYPE_KEY_UP;
+							else if (c == 66)
+								return EVENT_TYPE_KEY_DOWN;
+							/* else ignore */
+							break;
+						}
+					} /* else ignore */
+					break;
+				}
+			} else if (c == '\n' || c == '\r') {
+				return EVENT_TYPE_KEY_RETURN;
+			} else if (c == 'q') {
+				return EVENT_TYPE_KEY_QUIT;
+			} /* else ignore */
+			break;
+		}
+	}
+}
+
+static void draw_line(int row, char *buf, bool reverse)
+{
+	/* move cursor to @row */
+	printf("\033[%d;1H", row);
+
+	/* clear the row */
+	printf("\033[2K");
+
+	if (reverse)
+		printf("\033[7m");	/* turn on reversed video */
+
+	if (buf) {
+		/*
+		 * As we move cursor to individual row and print each line,
+		 * we don't need to print '\n'.
+		 */
+		while (*buf != '\n' && *buf != '\0')
+			putchar(*buf++);
+	}
+
+	if (reverse)
+		printf("\033[m");	/* turn off reversed video */
+}
+
+int dashboard_draw_frame(struct dashboard_ctx *db_ctx, int scroll)
+{
+	char *pos;
+	int header_start_off, header_end_off;
+	int footer_start_off, footer_end_off;
+	int data_start_off, data_end_off, data_rows;
+	int row, off, num, resrv_rows;
+	int rev_header_off = -1, rev_data_off = -1, rev_footer_off = -1;
+	struct data_store *ds = &db_ctx->ds;
+	FILE *stream = ds->stream;
+	struct win_frame *frame = &db_ctx->frame;
+
+	/*
+	 * If this is scrolling update then just re-adjust the rows in a frame
+	 * otherwise we repaint the enitre frame post processing the screen
+	 * buffer.
+	 */
+	if (!scroll) {
+		/* flushing stream would synchronize screen buffer */
+		fflush(stream);
+
+		/*
+		 * Rewind the stream to reset the file offset position to the
+		 * start of the buffer.
+		 */
+		rewind(stream);
+
+		/* If there's nothing to print then return early. */
+		if (!ds->len)
+			return 0;
+
+		ds->buf[ds->len] = '\0';
+
+		/*
+		 * Parse screen buffer to find num of rows in the buffer (each
+		 * row ends with new-line) and annotate each row offset. As we
+		 * render the dashboard line by line we count num of lines/rows
+		 * present in the data store buffer and then also calculate as
+		 * well as store the start offset of each line.
+		 */
+		ds->num_rows = 0;
+		pos = ds->buf;
+		while (*pos) {
+			if (*pos++ == '\n')
+				ds->num_rows++;
+		}
+
+		/* If there're no lines in the buffer then return. */
+		if (!ds->num_rows) {
+			nvme_show_error("data buffer doesn't contain any line");
+			return -EINVAL;
+		}
+
+		free(ds->row_off);
+
+		ds->row_off = calloc(ds->num_rows, sizeof(*ds->row_off));
+		if (!ds->row_off) {
+			nvme_show_error("Failed to allocate row offset buffer");
+			return -ENOMEM;
+		}
+
+		num = 0;
+		ds->row_off[num] = 0;	/* first line starts at offset 0 */
+		pos = ds->buf;
+		while (*pos && num + 1 < ds->num_rows) {
+			if (*pos++ == '\n')
+				ds->row_off[++num] = pos - ds->buf;
+		}
+	}
+
+	/*
+	 * Calculate the number of rows that can be displayed in a single
+	 * screen frame. Printing more rows than could fit on the one screen
+	 * causes the terminal to scroll, leading to noticeable flicker and a
+	 * cluttered dashboard display.
+	 * We draw the dashboard data including header and footer. We know
+	 * the current window size and hence we reserved rows for header and
+	 * footer first. Then whatever num of rows are remaining is used to
+	 * draw the data.
+	 */
+	resrv_rows = ds->header_rows + ds->footer_rows;
+	frame->data_rows = frame->rows - resrv_rows;
+
+	/*
+	 * If the current window size is less than num of reserved rows
+	 * (i.e. header + footer) then we can't draw frame. In such case
+	 * return without drawig anything.
+	 */
+	if (frame->data_rows < 0)
+		return 0;
+
+	frame->header_start_off = header_start_off = 0;
+	header_end_off = header_start_off + ds->header_rows;
+
+	/* total num of data rows present in the current screen buffer */
+	ds->data_rows = ds->num_rows - resrv_rows;
+
+	/*
+	 * Num of data rows which should be printed starting at index
+	 * @ds->data_start_idx.
+	 */
+	data_rows = ds->data_rows - ds->data_start_idx;
+
+	/*
+	 * Calculate data rows which could be actually accomodated in the
+	 * current frame. If @data_rows is greater than @frame->data_rows
+	 * then we clamp it to frame->data_row.
+	 */
+	data_rows = min(data_rows, frame->data_rows);
+	data_start_off = ds->header_rows + ds->data_start_idx;
+	data_end_off = data_start_off + data_rows;
+
+	frame->data_start_off = frame->header_start_off + ds->header_rows;
+
+	frame->footer_start_off = frame->data_start_off + frame->data_rows;
+	footer_start_off = ds->header_rows + ds->data_rows;
+	footer_end_off = footer_start_off + ds->footer_rows;
+
+
+	 /* print header */
+	if (ds->rev_header_row >= 0)
+		rev_header_off = ds->rev_header_row;
+
+	for (off = header_start_off, row = frame->header_start_off + 1;
+			off < header_end_off; off++, row++)
+		draw_line(row, ds->buf + ds->row_off[off],
+				off == rev_header_off);
+
+	/* print data */
+	if (ds->rev_data_row >= 0)
+		rev_data_off = ds->header_rows + ds->rev_data_row;
+
+	for (off = data_start_off, row = frame->data_start_off + 1;
+			off < data_end_off; off++, row++)
+		draw_line(row, ds->buf + ds->row_off[off],
+				off == rev_data_off);
+
+	/*
+	 * Clear remaining data rows, if any. If @data_rows is less than the
+	 * @frame->data_rows then we would have some empty rows at the end of
+	 * data and we have to clear it off.
+	 */
+	if (data_rows < frame->data_rows) {
+		int last_data_row = ds->header_rows + frame->data_rows;
+
+		for (row = frame->data_start_off + data_rows + 1;
+				row <= last_data_row; row++)
+			draw_line(row, NULL, false);
+	}
+
+	/* print footer */
+	if (ds->rev_footer_row >= 0)
+		rev_footer_off = ds->header_rows + ds->data_rows +
+					ds->rev_footer_row;
+
+	for (off = footer_start_off, row = frame->footer_start_off + 1;
+			off < footer_end_off; off++, row++)
+		draw_line(row, ds->buf + ds->row_off[off],
+				off == rev_footer_off);
+
+	fflush(stdout);
+
+	return 0;
+}
+
+void dashboard_reset(struct dashboard_ctx *db_ctx)
+{
+	dashboard_set_header_rows(db_ctx, 0);
+	dashboard_set_data_start(db_ctx, 0);
+	dashboard_set_footer_rows(db_ctx, 0);
+
+	dashboard_reset_data_raw_reverse(db_ctx);
+	dashboard_reset_header_raw_reverse(db_ctx);
+	dashboard_reset_footer_raw_reverse(db_ctx);
+
+	fflush(db_ctx->ds.stream);
+
+	/* clear screen */
+	printf("\033[2J");
+}
+
+static int dashboard_uevent_fd(void)
+{
+	int fd, ret;
+	struct sockaddr_nl sa;
+
+	fd = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
+	if (fd < 0) {
+		nvme_show_perror("uevent socket");
+		return fd;
+	}
+
+	sa.nl_family = AF_NETLINK;
+	sa.nl_pad = 0;
+	sa.nl_pid = getpid();
+	sa.nl_groups = 1;
+
+	ret = bind(fd, (struct sockaddr *)&sa, sizeof(struct sockaddr_nl));
+	if (ret < 0) {
+		close(fd);
+		nvme_show_perror("uevent bind");
+		return ret;
+	}
+
+	return fd;
+}
+
+FILE *dashboard_init(struct dashboard_ctx **db_ctx, int refresh_interval)
+{
+	sigset_t sigwinch_set;
+	struct termios ts;
+	struct winsize ws;
+	struct data_store *ds;
+	struct dashboard_ctx *ctx;
+
+	ctx = malloc(sizeof(struct dashboard_ctx));
+	if (!ctx)
+		return NULL;
+	memset(ctx, 0, sizeof(struct dashboard_ctx));
+
+	ctx->interval = refresh_interval;
+
+	ctx->term_fd = open(ctermid(NULL), O_RDWR);
+	if (ctx->term_fd < 0) {
+		free(ctx);
+		nvme_show_perror("open controlling terminal");
+		return NULL;
+	}
+
+	/*
+	 * listen for kobject uevent
+	 */
+	ctx->uevent_fd = dashboard_uevent_fd();
+	if (ctx->uevent_fd < 0)
+		goto out_term_fd;
+
+	/*
+	 * First block SIGWINCH and note down the current window size; we'd
+	 * later atomically unblock SIGWINCH and wait for both user input and
+	 * window size change events using pselect(). This ensures that we don't
+	 * miss window size change events.
+	 */
+	sigemptyset(&sigwinch_set);
+	sigemptyset(&ctx->orig_set);
+	sigaddset(&sigwinch_set, SIGWINCH);
+	/* block SIGWINCH */
+	sigprocmask(SIG_SETMASK, &sigwinch_set, &ctx->orig_set);
+	/* get current value of window size */
+	if (ioctl(ctx->term_fd, TIOCGWINSZ, &ws) < 0) {
+		nvme_show_perror("ioctl TIOCGWINSZ");
+		goto out_reset_mask;
+	}
+
+	ctx->frame.rows = ws.ws_row;
+
+	/* put terminal in raw mode */
+	if (tty_set_raw(ctx->term_fd, &ts) < 0) {
+		nvme_show_error("Failed to set tty in raw mode");
+		goto out_reset_mask;
+	}
+	ctx->orig_ts = ts;
+
+	ds = &ctx->ds;
+	ds->stream = open_memstream(&ds->buf, &ds->len);
+	if (!ds->stream) {
+		nvme_show_perror("open memstream");
+		goto out_reset_tty;
+	}
+	ds->rev_data_row = ds->rev_header_row = ds->rev_footer_row = -1;
+
+	/* hide cursor */
+	printf("\033[?25l");
+
+	/* clear screen */
+	printf("\033[2J");
+	fflush(stdout);
+
+	*db_ctx = ctx;
+	return ds->stream;
+out_reset_tty:
+	/* reset terminal */
+	tty_reset(ctx->term_fd, &ctx->orig_ts);
+out_reset_mask:
+	/* restore the original signal mask */
+	sigprocmask(SIG_SETMASK, &ctx->orig_set, NULL);
+	close(ctx->uevent_fd);
+out_term_fd:
+	close(ctx->term_fd);
+	free(ctx);
+	return NULL;
+}
+
+void dashboard_exit(struct dashboard_ctx *db_ctx)
+{
+	struct data_store *ds = &db_ctx->ds;
+
+	/* show cursor */
+	printf("\033[?25h\n");
+	fflush(stdout);
+
+	fclose(ds->stream);
+	free(ds->buf);
+	free(ds->row_off);
+
+	/* reset terminal */
+	tty_reset(db_ctx->term_fd, &db_ctx->orig_ts);
+
+	/* restore the original signal mask */
+	sigprocmask(SIG_SETMASK, &db_ctx->orig_set, NULL);
+	close(db_ctx->term_fd);
+	close(db_ctx->uevent_fd);
+	free(db_ctx);
+}
util/dashboard.h new file +55 -0

55 lines not on this page · raw message

util/meson.build +2 -1
index 42412705d..5656b14a6 100644
@@ -14,7 +14,8 @@ else
         'util/suffix.c',
         'util/types.c',
         'util/utils.c',
-        'util/table.c'
+        'util/table.c',
+        'util/dashboard.c',
     ]
 
     if json_c_dep.found()
Signature · 1 line
2.53.0
#7 lore raw

PATCH v2 7/7 nvme: add nvme top command

In reply to Nilay Shroff

Add a new "nvme top" CLI command that provides an interactive, top-like dashboard for real-time monitoring of NVMe devices and paths.

The dashboard presents continuously updated information about NVMe fabrics/PCIe paths and devices, similar in spirit to tools such as top or iotop. It helps administrators observe device health, detect path degradation, identify multipath imbalances, and catch transient failures.

The interface consists of two views:

* Subsystem list view
Displays all NVMe subsystems present on the system. Users can navigate the list using arrow keys and select a subsystem for detailed inspection.

* Subsystem detail view
Shows detailed statistics for the selected subsystem. When native multipath is enabled, this includes namespace head statistics, path statistics, path health, and controller summary. Without multipath, it displays namespace statistics and controller summary.

Users can switch between views using the ESC/return key, exit with 'q', and navigate using arrow keys.

This command builds on the generic dashboard framework to provide a flexible and extensible real-time monitoring interface.

---
 meson.build         |    1 +
 nvme-builtin.h      |    1 +
 nvme-print-stdout.c | 1206 +++++++++++++++++++++++++++++++++++++++++++
 nvme-print.c        |    5 +
 nvme-print.h        |    5 +-
 nvme-top.c          |  345 +++++++++++++
 nvme-top.h          |   30 ++
 nvme.c              |   39 ++
 8 files changed, 1631 insertions(+), 1 deletion(-)
 create mode 100644 nvme-top.c
 create mode 100644 nvme-top.h
meson.build +1 -0
index adc8ece7f..ceff6a6d1 100644
@@ -514,6 +514,7 @@ if want_nvme
             'nvme-rpmb.c',
             'nvme.c',
             'plugin.c',
+            'nvme-top.c',
         ]
 
         if json_c_dep.found()
nvme-builtin.h +1 -0
index 2ebf37fc2..ed08de04c 100644
@@ -8,6 +8,7 @@
 #include "cmd.h"
 
 COMMAND_LIST(
+	ENTRY("top", "nvme top", top)
 	ENTRY("list", "List all NVMe devices and namespaces on machine", list)
 	ENTRY("list-subsys", "List nvme subsystems", list_subsys)
 	ENTRY("id-ctrl", "Send NVMe Identify Controller", id_ctrl)
nvme-print-stdout.c +1206 -0

1,233 lines not on this page · raw message

nvme-print.c +5 -0
index 545854f30..8a116db5a 100644
@@ -1679,6 +1679,11 @@ void nvme_show_list_items(struct libnvme_global_ctx *ctx, nvme_print_flags_t fla
 	nvme_print(list_items, flags, ctx);
 }
 
+void nvme_show_top(nvme_print_flags_t flags, int refresh_interval)
+{
+	nvme_print(top, flags, refresh_interval);
+}
+
 void nvme_show_topology(struct libnvme_global_ctx *ctx,
 			enum nvme_cli_topo_ranking ranking,
 			nvme_print_flags_t flags)
nvme-print.h +4 -1
index bd88410d1..cca77e7a1 100644
@@ -114,6 +114,9 @@ struct print_ops {
 	void (*topology_multipath)(struct libnvme_global_ctx *ctx);
 	void (*topology_tabular)(struct libnvme_global_ctx *ctx);
 
+	/* nvme top */
+	void (*top)(int refresh_interval);
+
 	/* status and error messages */
 	void (*connect_msg)(libnvme_ctrl_t c);
 	void (*show_message)(bool error, const char *msg, va_list ap);
@@ -263,9 +266,9 @@ void nvme_show_topology(struct libnvme_global_ctx *ctx,
 			enum nvme_cli_topo_ranking ranking,
 			nvme_print_flags_t flags);
 void nvme_show_topology_tabular(struct libnvme_global_ctx *ctx, nvme_print_flags_t flags);
-
 void nvme_show_feature(enum nvme_features_id fid, int sel, unsigned int result,
 		       void *buf, __u32 data_len, nvme_print_flags_t flags);
+void nvme_show_top(nvme_print_flags_t flags, int refresh_interval);
 void nvme_feature_show_fields(enum nvme_features_id fid, unsigned int result, unsigned char *buf);
 void nvme_directive_show(__u8 type, __u8 oper, __u16 spec, __u32 nsid, __u64 result,
 	void *buf, __u32 len, nvme_print_flags_t flags);
nvme-top.c new file +345 -0

345 lines not on this page · raw message

nvme-top.h new file +30 -0
new file mode 100644
index 000000000..9ce4905cb
@@ -0,0 +1,30 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+#ifndef NVME_TOP_H
+#define NVME_TOP_H
+
+#include <stdio.h>
+#include <stddef.h>
+#include <libnvme.h>
+
+int nvme_format_iops(double iops, char *buf, size_t size);
+int nvme_format_bw(double bw, char *buf, size_t size);
+
+void nvme_ns_calc_aggr_stat(libnvme_ns_t n, double *r_iops, double *w_iops,
+		double *r_bw, double *w_bw, double *max_rlat, double *max_wlat,
+		double *max_util);
+void nvme_path_calc_aggr_stat(libnvme_path_t p, double *r_iops, double *w_iops,
+		double *r_bw, double *w_bw, double *max_rlat, double *max_wlat,
+		double *max_util);
+void nvme_ns_calc_stat(libnvme_ns_t n, double *r_iops, double *w_iops,
+		double *r_lat, double *w_lat, double *r_bw, double *w_bw,
+		double *util, unsigned int *inflights);
+void nvme_path_calc_stat(libnvme_path_t p, double *r_iops, double *w_iops,
+		double *r_lat, double *w_lat, double *r_bw, double *w_bw,
+		double *util, unsigned int *inflights);
+
+static inline int nvme_format_lat(double lat, char *buf, size_t size)
+{
+	return snprintf(buf, size, "%.2f", lat);
+}
+
+#endif /* NVME_TOP_H */
nvme.c +39 -0
index d723170ea..ac4451cee 100644
@@ -3550,6 +3550,45 @@ static int list_subsys(int argc, char **argv, struct command *acmd,
 	return 0;
 }
 
+static int top(int argc, char **argv, struct command *acmd,
+		struct plugin *plugin)
+{
+	int err;
+	nvme_print_flags_t flags = 0;
+	const char *desc = "show nvme top output";
+	const char *delay = "refresh interval in seconds";
+
+	struct config {
+		int delay;
+	};
+
+	struct config cfg = {
+		.delay = 1,
+	};
+
+	NVME_ARGS(opts,
+		  OPT_INT("delay", 'd', &cfg.delay, delay));
+
+	err = parse_args(argc, argv, desc, opts);
+	if (err)
+		return err;
+
+	err = validate_output_format(nvme_args.output_format, &flags);
+	if (err < 0 || flags != NORMAL) {
+		nvme_show_error("Invalid output format");
+		return -EINVAL;
+	}
+
+	if (cfg.delay < 1) {
+		nvme_show_error("delay must be greater than or equal to 1");
+		return -EINVAL;
+	}
+
+	nvme_show_top(flags, cfg.delay);
+
+	return err;
+}
+
 static int list(int argc, char **argv, struct command *acmd, struct plugin *plugin)
 {
 	const char *desc = "Retrieve basic information for all NVMe namespaces";
Signature · 1 line
2.53.0
#3 lore raw

PATCH v2 3/7 nvme: add support for float and double types in table_print_XXX()

In reply to Nilay Shroff

The table_print_XXX() APIs do not currently support printing values of type float or double.

Add support for float and double so that these data types can be used with the table printing helpers. This will be later used for printing nvme-top stat.

While at it, switch error reporting to nvme_show_error() for consistency with the rest of the code.

---
 util/table.c | 22 ++++++++++++++++++++--
 util/table.h | 26 ++++++++++++++++++++++++++
 2 files changed, 46 insertions(+), 2 deletions(-)
util/table.c +20 -2
index 1fed89db8..60302fff7 100644
@@ -20,6 +20,7 @@
 #include <errno.h>
 #include <string.h>
 
+#include "nvme-print.h"
 #include "table.h"
 
 static int table_get_value_width(struct value *v)
@@ -43,8 +44,14 @@ static int table_get_value_width(struct value *v)
 	case FMT_LONG:
 		len = snprintf(buf, sizeof(buf), "%ld", v->ld);
 		break;
+	case FMT_FLOAT:
+		len = snprintf(buf, sizeof(buf), "%.2f", v->f);
+		break;
+	case FMT_DOUBLE:
+		len = snprintf(buf, sizeof(buf), "%.2f", v->d);
+		break;
 	default:
-		printf("Invalid print format!\n");
+		nvme_show_error("Invalid print format!\n");
 		break;
 	}
 	return len;
@@ -81,8 +88,14 @@ static void table_print_centered(struct value *val, int width, enum fmt_type typ
 		break;
 	case FMT_UNSIGNED_LONG:
 		printf("%lu", val->lu);
+	case FMT_FLOAT:
+		printf("%.2f", val->f);
+		break;
+	case FMT_DOUBLE:
+		printf("%.2f", val->d);
 		break;
 	default:
+		nvme_show_error("Invalid print format!\n");
 		break;
 	}
 
@@ -167,9 +180,14 @@ static void table_print_rows(const struct table *t)
 					break;
 				case FMT_UNSIGNED_LONG:
 					printf("%*lu", width, v->lu);
+				case FMT_FLOAT:
+					printf("%*.2f", width, v->f);
+					break;
+				case FMT_DOUBLE:
+					printf("%*.2f", width, v->d);
 					break;
 				default:
-					fprintf(stderr, "Invalid format!\n");
+					nvme_show_error("Invalid format!\n");
 					break;
 				}
 				break;
util/table.h +26 -0
index a2ab2860f..045ed2439 100644
@@ -10,6 +10,8 @@ enum fmt_type {
 	FMT_UNSIGNED,
 	FMT_LONG,
 	FMT_UNSIGNED_LONG,
+	FMT_FLOAT,
+	FMT_DOUBLE,
 };
 
 enum alignment {
@@ -25,6 +27,8 @@ struct value {
 		unsigned int u;
 		long ld;
 		unsigned long lu;
+		float f;
+		double d;
 	};
 	enum alignment align;
 	enum fmt_type type;
@@ -135,6 +139,28 @@ static inline void table_set_value_unsigned_long(struct table *t, int col,
 	v->type = FMT_UNSIGNED_LONG;
 }
 
+static inline void table_set_value_float(struct table *t, int col,
+		int row, float f, enum alignment align)
+{
+	struct table_row *r = &t->rows[row];
+	struct value *v = &r->val[col];
+
+	v->f = f;
+	v->align = align;
+	v->type = FMT_FLOAT;
+}
+
+static inline void table_set_value_double(struct table *t, int col,
+		int row, double d, enum alignment align)
+{
+	struct table_row *r = &t->rows[row];
+	struct value *v = &r->val[col];
+
+	v->d = d;
+	v->align = align;
+	v->type = FMT_DOUBLE;
+}
+
 struct table *table_create(void);
 int table_add_columns(struct table *t, struct table_column *c, int num_columns);
 int table_add_columns_filter(struct table *t, struct table_column *c,
Signature · 1 line
2.53.0