diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d95440f493..14e1267e66 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -60,35 +60,36 @@ string, a callback, and optionally an alias, a `deprecated` flag, or a ### Add a command to an existing group -The built-in (no-plugin-prefix) commands are split by feature area across -`src/nvme-cmds-*.c` (e.g. `src/nvme-cmds-io.c` for read/write/flush/..., -`src/nvme-cmds-registers.c` for register access, etc.). Pick the file that -matches your command's area, or add a new `src/nvme-cmds-.c` if none -fit -- just add the one line to `src/meson.build`'s `sources` list. Each -such file ends with a block like this one from `src/nvme-cmds-discovery.c`: +The top-level commands (`nvme read`, `nvme connect`, ...) live in plugins +without a command group of their own, one per feature area: e.g. +`plugins/cmds-io` for read/write/flush, `plugins/cmds-admin` for format, +sanitize and reset, `plugins/cmds-fabrics` for connect and discover. Pick +the plugin that matches the area of your command. Each ends with a block +like this one from `plugins/cmds-io/cmds-io-plugin.c`: ```c -static struct command get_log_cmd = { - .name = "get-log", - .help = "Generic NVMe get log, returns log in raw format", - .fn = get_log, +static struct command flush_cmd_cmd = { + .name = "flush", + .help = "Submit a Flush command, return results", + .fn = flush_cmd, }; static struct command *commands[] = { - &get_log_cmd, + &flush_cmd_cmd, /* ... */ NULL, }; -static void __shr_constructor register_group(void) +NVME_PLUGIN_INIT(register_plugin) { - plugin_add_group(&builtin, "Log Page & Identify", commands); + plugin_add_group(&builtin, "I/O Commands", commands); } ``` To add a command, write its callback function, add a `struct command` -literal for it, and add that entry to the `commands[]` array. The -callback's prototype is: +literal for it, add that entry to the `commands[]` array, and add its name +to `plugin_commands` in the plugin's `meson.build` (see "Top-level +commands in a plugin" below). The callback's prototype is: ```c int f(int argc, char **argv, struct command *command, struct plugin *plugin); @@ -97,16 +98,16 @@ int f(int argc, char **argv, struct command *command, struct plugin *plugin); `argc`/`argv` are adjusted to start after the sub-command. For `nvme foo --option=bar`, `argc` is 1 and `argv` starts at `--option`. Use `.alias = "other-name"` for an alias, and `.deprecated = true` for a -deprecated command (deprecated built-ins live in -`src/nvme-cmds-deprecated.c`, gated by `#ifdef CONFIG_DEPRECATED_CMDS`). +deprecated command (the deprecated top-level commands live in the +`plugins/cmds-deprecated` plugin, built with `-Ddeprecated-cmds=enabled`). Set `.no_device = true` for a command that doesn't take a positional `` argument (e.g. `nvme list` or `nvme gen-hostnqn`) -- this drops `` from its usage line and, when none of a plugin's commands need one, from that plugin's `--help` output too. -The `title` passed to `plugin_add_group()` (`"Log Page & Identify"` above) -is the heading shown for that group's commands in `nvme help`; pass `NULL` -for no heading (that's what plugins normally do, see below). +The `title` passed to `plugin_add_group()` (`"I/O Commands"` above) is the +heading of the group in `nvme help`. Pass `NULL` for no heading, as plugins +with their own command group normally do (see below). ### Add a new plugin @@ -180,9 +181,29 @@ group's commands instead of in the flat "core NVMe/NVMeoF plugins" list. This only affects display -- the plugin is still invoked as `nvme foo bar`, not merged into the flat top-level command namespace. +#### Top-level commands in a plugin + +A plugin can add top-level commands, `nvme bar` rather than `nvme foo bar`. +Its `NVME_PLUGIN_INIT()` function calls +`plugin_add_group(&builtin, title, commands)` with one of the titles of +`builtin_groups` in `src/nvme.c`. The title gives the commands their place +in `nvme help` and in the command lists. A plugin with only top-level +commands calls no `register_extension()` and sets +`plugin_extension = false` in its `meson.build`. The `meson.build` lists +the top-level commands and their aliases: + +```meson +plugin_commands = ['bar', 'baz'] +plugin_command_aliases = {'bar': 'old-bar'} +``` + +nvme looks a top-level command it doesn't have up in these lists and +loads the module. The `command-index` test checks that the lists name +exactly the commands of the plugin. + #### Multi-file plugins -A plugin can span multiple `.c` files (see `plugins/ocp` or +A plugin can span multiple `.c` files (see `plugins/cmds-ocp` or `plugins/solidigm` for real examples): put the `struct plugin` definition and any shared declarations in a small header, and `#include` it from each file. A plugin has one `NVME_PLUGIN_INIT()` function. To show the commands @@ -199,7 +220,7 @@ Neither needs hardware. `Documentation/TESTING.md` describes the tools. **Mock tests** run the real `nvme` binary against a mocked controller: `tests/cli/libmock_nvme.c` intercepts the ioctls and hands every command to a Python object in the test, which answers it (`tests/cli/nvme_mock.py`). -Vendor tests live in `tests/cli//`; `tests/cli/ocp/` (a shared +Vendor tests live in `tests/cli//`; `tests/cli/cmds_ocp/` (a shared controller class, one file per command), `tests/cli/wdc/` (several models) and `tests/cli/micron/` are examples. A test @@ -507,7 +528,7 @@ how to triage and fix findings. Give it precise input data: checks. For example: "Add mock tests for `nvme ` in -`tests/cli//` following `tests/cli/ocp/`. The log layout is in +`tests/cli//` following `tests/cli/cmds_ocp/`. The log layout is in ``, the output of a real drive in ``. Use non-zero values in every field and check normal and JSON output. Then add the command to the device fuzz table, sweep it and compare its coverage with and without the diff --git a/Documentation/BUILDING.md b/Documentation/BUILDING.md index dfeb0037f0..ce8a77015b 100644 --- a/Documentation/BUILDING.md +++ b/Documentation/BUILDING.md @@ -285,9 +285,12 @@ $ make PLUGINS="" ## Plugin modules The plugins are modules of their own, which nvme loads when a command -uses them, so a command loads at most the module of its plugin. nvme -loads all modules only for the lists of commands, `nvme help` and -`nvme utils dump-command-metadata`, and for a command it doesn't know. +uses them. The top-level commands live in modules too: `cmds-io` for the +I/O commands, `cmds-fabrics` for connect and discover, `cmds-list` for +list and top, and so on. A command loads only the module which provides +it, and the plugins that module needs. nvme loads all modules only for +the lists of commands, `nvme help` and `nvme utils dump-command-metadata`, +and for a command it doesn't know. The `plugin-modules` option decides: ```shell @@ -301,11 +304,16 @@ $ meson setup .build -Dplugin-modules=disabled | `disabled` | linked into nvme | The modules are installed in `/nvme-cli//plugins`, with -the `runtime` install tag. A module works only with an nvme of the same +the `runtime` install tag. A module is named after the directory of its +plugin, e.g. `sandisk.so` for `nvme sndk`. A module works only with an nvme of the same version, built with the same `src/plugin.h`: nvme ignores another one with a warning. Without the module of a plugin, `nvme ` says the plugin is not -installed, so a distribution can package plugins on their own. +installed, and without the module of a top-level command, nvme says the +command is not installed. So a distribution can package plugins on their +own. An initramfs needs the modules of the commands it runs, e.g. +`cmds-fabrics.so` for `nvme connect-all`, `cmds-list.so` for +`nvme list-subsys` and `cmds-nbft.so` for `nvme nbft show`. Run from the build tree, nvme takes the modules of the build tree (`.build/plugins`). The environment variable `NVME_PLUGIN_DIR` names diff --git a/Documentation/PRIVSEP.md b/Documentation/PRIVSEP.md index 516eec2f15..256ccdac00 100644 --- a/Documentation/PRIVSEP.md +++ b/Documentation/PRIVSEP.md @@ -219,13 +219,14 @@ writes its report to a file. Some printers stay in process (`nvme_print_sandboxed()`): -- the libnvme tree printers (`list`, `list-subsys`, `show-topology`, - `relatives`), which read sysfs while they print and decode no device - data; +- the libnvme tree printers (`list`, `list-subsys`, `show-topology`), + which read sysfs while they print and decode no device data; - plugin printers run through `nvme_print_decoder()` with `sandbox` set to false, e.g. the zns zone list printers, which pass a JSON object from - one call to the next; -- `top`, which is interactive, and `config_conn_list`; + one call to the next, the cmds-admin `relatives` printer, which reads + sysfs like the libnvme tree printers, and the connection list of + `config show`, which prints no device data; +- `top`, which is interactive; - `show_init`/`show_finish`, and the status and error messages, unless a sandboxed printer prints them. diff --git a/Documentation/TESTING.md b/Documentation/TESTING.md index 45d2551e8a..5a05459958 100644 --- a/Documentation/TESTING.md +++ b/Documentation/TESTING.md @@ -279,10 +279,10 @@ Firmware Table, which `nvme nbft show` parses and prints (`nbft`). The `iostat` target fuzzes the I/O statistics of `nvme top`: the block layer stat files of the namespaces and paths of a captured sysfs tree, -which libnvme parses, and the rates `src/nvme-iostat.c` computes from two -samples. The first line of an input is the time between the samples in -milliseconds, the target takes over `clock_gettime()` for it. It needs a -dynamically linked Linux build. +which libnvme parses, and the rates `plugins/cmds-list/nvme-iostat.c` +computes from two samples. The first line of an input is the time between +the samples in milliseconds, the target takes over `clock_gettime()` for +it. It needs a dynamically linked Linux build. The `device` target fuzzes what nvme-cli does with the data a device returns. It runs one of the commands which print, or size a buffer by, diff --git a/MAINTAINERS b/MAINTAINERS index 478cf32bcc..ff040a1a02 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -113,8 +113,8 @@ M: Broc Going (@brgoing) M: Jeff Lien (@jeff-lien-sndk) M: Brandon Paupore (@brandon-paupore-sndk) S: Supported -F: plugins/ocp/ -F: tests/cli/ocp/ +F: plugins/cmds-ocp/ +F: tests/cli/cmds_ocp/ SAMSUNG PLUGIN M: Hyuntae Kim (@h1219-kim) diff --git a/NEWS.md b/NEWS.md index 27f1384ea5..529588b3bc 100644 --- a/NEWS.md +++ b/NEWS.md @@ -55,15 +55,17 @@ in a build without libkmod. nvme declares it in an ELF `.note.dlopen` note. Static builds still link it. -* The plugins are modules, which nvme loads when a command uses them: - a command loads at most the module of its plugin, so nvme starts as - fast as before. They are installed in - `/nvme-cli//plugins`. Without the module of a - plugin, `nvme ` says the plugin is not installed, so packages - can ship plugins on their own. The new `plugin-modules` option - (`auto` by default) decides; static builds, Windows and fuzz builds - link the plugins in, as before. An initramfs which runs a plugin - command needs its module, e.g. `nbft.so` for `nvme nbft show`. See +* The plugins and the top-level commands are modules, which nvme loads + when a command uses them: a command loads only the module which + provides it, so nvme starts as fast as before, and the nvme binary + shrinks to about a third. They are installed in + `/nvme-cli//plugins`. Without the module, nvme says + the plugin or the command is not installed, so packages can ship + plugins on their own. The new `plugin-modules` option (`auto` by + default) decides; static builds, Windows and fuzz builds link the + plugins in, as before. An initramfs needs the modules of the commands + it runs, e.g. `cmds-fabrics.so` for `nvme connect-all`, `cmds-list.so` + for `nvme list-subsys` and `cmds-nbft.so` for `nvme nbft show`. See [BUILDING.md](Documentation/BUILDING.md). ### Fabrics diff --git a/meson.build b/meson.build index f7e54b7a14..40ad0bef14 100644 --- a/meson.build +++ b/meson.build @@ -223,8 +223,6 @@ conf.set('LIBNVME_PRIVSEP_HELPER', conf.set('CONFIG_LOOPBACK', want_ioctl_tests, description: 'Is the ioctl loopback test transport enabled') conf.set('CONFIG_TOP', want_top, description: 'Is nvme top enabled') -conf.set('CONFIG_DEPRECATED_CMDS', want_deprecated_cmds, - description: 'Deprecated commands enabled') if host_system == 'windows' kernel32_dep = cc.find_library('kernel32', required: true) diff --git a/plugins/amzn/amzn-nvme.c b/plugins/amzn/amzn-nvme.c index 0fab8c8910..db389c04b4 100644 --- a/plugins/amzn/amzn-nvme.c +++ b/plugins/amzn/amzn-nvme.c @@ -15,7 +15,7 @@ #include "global-ctx.h" #include "nvme-print.h" #include "plugin.h" -#include "plugins/id/id.h" +#include "plugins/cmds-id/id.h" #define AMZN_NVME_STATS_LOGPAGE_ID 0xD0 #define AMZN_NVME_STATS_DETAIL_IO_VERSION 1 diff --git a/src/nvme-cmds-ctrl.c b/plugins/cmds-admin/cmds-admin-ctrl.c similarity index 96% rename from src/nvme-cmds-ctrl.c rename to plugins/cmds-admin/cmds-admin-ctrl.c index 4d1467764e..0a95dc4fec 100644 --- a/src/nvme-cmds-ctrl.c +++ b/plugins/cmds-admin/cmds-admin-ctrl.c @@ -20,8 +20,6 @@ #include -#include - #include "argconfig.h" #include "cleanup.h" #include "global-ctx.h" @@ -30,6 +28,8 @@ #include "nvme-print.h" #include "plugin.h" +#include "cmds-admin.h" + static const char *only_ctrl_dev = "Only controller device is allowed"; static int virtual_mgmt(int argc, char **argv, struct command *acmd, struct plugin *plugin) @@ -216,15 +216,10 @@ static struct command virtual_mgmt_cmd = { .fn = virtual_mgmt, }; -static struct command *commands[] = { +struct command *admin_ctrl_commands[] = { &reset_cmd, &subsystem_reset_cmd, &ns_rescan_cmd, &virtual_mgmt_cmd, NULL, }; - -static void __shr_constructor register_group(void) -{ - plugin_add_group(&builtin, "Controller Management", commands); -} diff --git a/src/nvme-cmds-sanitize.c b/plugins/cmds-admin/cmds-admin-plugin.c similarity index 99% rename from src/nvme-cmds-sanitize.c rename to plugins/cmds-admin/cmds-admin-plugin.c index cfb22c8c74..4b04a6b3fa 100644 --- a/src/nvme-cmds-sanitize.c +++ b/plugins/cmds-admin/cmds-admin-plugin.c @@ -33,7 +33,6 @@ #include #include #include -#include #include #include #include @@ -49,6 +48,9 @@ #include "nvme-print.h" #include "plugin.h" +#include "cmds-admin.h" +#include "cmds-admin-print.h" + static const char *ish = "Ignore Shutdown (for NVMe-MI command)"; static const char dash[51] = {[0 ... 49] = '=', '\0'}; static const char space[51] = {[0 ... 49] = ' ', '\0'}; @@ -1027,7 +1029,11 @@ static struct command *commands[] = { NULL, }; -static void __shr_constructor register_group(void) +NVME_PLUGIN_INIT(register_plugin) { + plugin_add_group(&builtin, "Controller Management", + admin_ctrl_commands); plugin_add_group(&builtin, "Media Management", commands); + plugin_add_group(&builtin, "Security & Access Control", + admin_security_commands); } diff --git a/plugins/cmds-admin/cmds-admin-print-stdout.c b/plugins/cmds-admin/cmds-admin-print-stdout.c new file mode 100644 index 0000000000..29e5ec094b --- /dev/null +++ b/plugins/cmds-admin/cmds-admin-print-stdout.c @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include + +#include + +#include "cmds-admin-print.h" +#include "nvme-print.h" +#include "nvme-resources.h" + +static struct admin_print_ops admin_stdout_print_ops; + +static void stdout_relatives(struct libnvme_global_ctx *ctx, const char *name) +{ + struct nvme_resources res; + struct htable_ns_iter it; + bool block = true; + bool first = true; + struct libnvme_ctrl *c; + struct libnvme_path *p; + struct libnvme_ns *n; + int nsid; + int ret; + int id; + + ret = sscanf(name, "nvme%dn%d", &id, &nsid); + + switch (ret) { + case 1: + block = false; + break; + case 2: + break; + default: + return; + } + + nvme_resources_init(ctx, &res); + + if (block) { + fprintf(stderr, + "Namespace %s has parent controller(s):", name); + for (n = htable_ns_getfirst(&res.ht_n, name, &it); n; + n = htable_ns_getnext(&res.ht_n, name, &it)) { + if (libnvme_ns_get_ctrl(n)) { + c = libnvme_ns_get_ctrl(n); + fprintf(stderr, "%s", libnvme_ctrl_get_name(c)); + break; + } + libnvme_namespace_for_each_path(n, p) { + c = libnvme_path_get_ctrl(p); + fprintf(stderr, "%s%s", first ? "" : ", ", + libnvme_ctrl_get_name(c)); + if (first) + first = false; + } + } + fprintf(stderr, "\n\n"); + } else { + c = htable_ctrl_get(&res.ht_c, name); + if (c) { + fprintf(stderr, + "Controller %s has child namespace(s):", name); + libnvme_ctrl_for_each_ns(c, n) { + fprintf(stderr, "%s%s", first ? "" : ", ", + libnvme_ns_get_name(n)); + if (first) + first = false; + } + fprintf(stderr, "\n\n"); + } + } + + nvme_resources_free(&res); +} + +static struct admin_print_ops admin_stdout_print_ops = { + .relatives = stdout_relatives, +}; + +struct admin_print_ops *admin_get_stdout_print_ops(nvme_print_flags_t flags) +{ + admin_stdout_print_ops.flags = flags; + return &admin_stdout_print_ops; +} diff --git a/plugins/cmds-admin/cmds-admin-print.c b/plugins/cmds-admin/cmds-admin-print.c new file mode 100644 index 0000000000..d048336465 --- /dev/null +++ b/plugins/cmds-admin/cmds-admin-print.c @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include + +#include "cmds-admin-print.h" +#include "nvme-print.h" + +/* + * The relatives printer reads sysfs, so it runs in process. Like + * nvme_print(), silently skip printers that an output format does not + * implement. + */ +#define admin_print(name, flags, ...) \ + do { \ + struct admin_print_ops *ops = admin_print_ops(flags); \ + \ + if (ops && ops->name) \ + nvme_print_decoder(ops, name, false, flags, \ + ##__VA_ARGS__); \ + } while (false) + +/* Only the normal output format has printers */ +static struct admin_print_ops *admin_print_ops(nvme_print_flags_t flags) +{ + if (flags & JSON || nvme_is_output_format_json()) + return NULL; + if (flags & BINARY) + return NULL; + + return admin_get_stdout_print_ops(flags); +} + +void nvme_show_relatives(struct libnvme_global_ctx *ctx, const char *name, + nvme_print_flags_t flags) +{ + admin_print(relatives, flags, ctx, name); +} diff --git a/plugins/cmds-admin/cmds-admin-print.h b/plugins/cmds-admin/cmds-admin-print.h new file mode 100644 index 0000000000..78a049a85d --- /dev/null +++ b/plugins/cmds-admin/cmds-admin-print.h @@ -0,0 +1,16 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#pragma once + +#include + +#include "args.h" + +struct admin_print_ops { + void (*relatives)(struct libnvme_global_ctx *ctx, const char *name); + nvme_print_flags_t flags; +}; + +struct admin_print_ops *admin_get_stdout_print_ops(nvme_print_flags_t flags); + +void nvme_show_relatives(struct libnvme_global_ctx *ctx, const char *name, + nvme_print_flags_t flags); diff --git a/src/nvme-cmds-security.c b/plugins/cmds-admin/cmds-admin-security.c similarity index 95% rename from src/nvme-cmds-security.c rename to plugins/cmds-admin/cmds-admin-security.c index 2dd134e737..3ec48d334d 100644 --- a/src/nvme-cmds-security.c +++ b/plugins/cmds-admin/cmds-admin-security.c @@ -9,13 +9,13 @@ #include -#include - #include "cleanup.h" #include "global-ctx.h" #include "nvme-print.h" #include "plugin.h" +#include "cmds-admin.h" + static int lockdown_cmd(int argc, char **argv, struct command *acmd, struct plugin *plugin) { const char *desc = "The Lockdown command is used to control the\n" @@ -128,12 +128,7 @@ static struct command lockdown_cmd_cmd = { .fn = lockdown_cmd, }; -static struct command *commands[] = { +struct command *admin_security_commands[] = { &lockdown_cmd_cmd, NULL, }; - -static void __shr_constructor register_group(void) -{ - plugin_add_group(&builtin, "Security & Access Control", commands); -} diff --git a/plugins/cmds-admin/cmds-admin.h b/plugins/cmds-admin/cmds-admin.h new file mode 100644 index 0000000000..ac6df61050 --- /dev/null +++ b/plugins/cmds-admin/cmds-admin.h @@ -0,0 +1,7 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#pragma once + +struct command; + +extern struct command *admin_ctrl_commands[]; +extern struct command *admin_security_commands[]; diff --git a/plugins/cmds-admin/meson.build b/plugins/cmds-admin/meson.build new file mode 100644 index 0000000000..494a0da426 --- /dev/null +++ b/plugins/cmds-admin/meson.build @@ -0,0 +1,26 @@ +# SPDX-License-Identifier: GPL-2.0-or-later +# +# The controller and media management top-level commands. +# plugins/meson.build always builds this plugin. + +plugin_extension = false + +plugin_sources += [ + 'plugins/cmds-admin/cmds-admin-plugin.c', + 'plugins/cmds-admin/cmds-admin-ctrl.c', + 'plugins/cmds-admin/cmds-admin-security.c', + 'plugins/cmds-admin/cmds-admin-print.c', + 'plugins/cmds-admin/cmds-admin-print-stdout.c', +] + +plugin_commands = [ + 'reset', + 'subsystem-reset', + 'ns-rescan', + 'virt-mgmt', + 'device-self-test', + 'sanitize', + 'sanitize-ns', + 'format', + 'lockdown', +] diff --git a/src/config-create.c b/plugins/cmds-config/config-create.c similarity index 99% rename from src/config-create.c rename to plugins/cmds-config/config-create.c index 1e0cc02617..777cfbd58a 100644 --- a/src/config-create.c +++ b/plugins/cmds-config/config-create.c @@ -17,9 +17,9 @@ #include "argconfig.h" #include "cleanup.h" #include "config-create.h" -#include "fabrics.h" #include "global-ctx.h" #include "nvme-print.h" +#include "plugins/cmds-fabrics/fabrics.h" struct reload_ctx { struct libnvmf_config_emitter *emitter; diff --git a/src/config-create.h b/plugins/cmds-config/config-create.h similarity index 100% rename from src/config-create.h rename to plugins/cmds-config/config-create.h diff --git a/plugins/config/config-nvme.c b/plugins/cmds-config/config-nvme.c similarity index 96% rename from plugins/config/config-nvme.c rename to plugins/cmds-config/config-nvme.c index 26e9c2679c..1554b17670 100644 --- a/plugins/config/config-nvme.c +++ b/plugins/cmds-config/config-nvme.c @@ -7,10 +7,10 @@ */ #include -#include "config-convert.h" #include "config-create.h" -#include "fabrics.h" #include "plugin.h" +#include "plugins/cmds-fabrics/config-convert.h" +#include "plugins/cmds-fabrics/fabrics.h" static int config_validate_cmd(int argc, char **argv, struct command *cmd, struct plugin *plugin) diff --git a/plugins/cmds-config/meson.build b/plugins/cmds-config/meson.build new file mode 100644 index 0000000000..46265eb431 --- /dev/null +++ b/plugins/cmds-config/meson.build @@ -0,0 +1,11 @@ +# SPDX-License-Identifier: GPL-2.0-or-later + +plugin_name = 'config' + +if want_fabrics + plugin_needs = ['cmds-fabrics'] + plugin_sources += [ + 'plugins/cmds-config/config-create.c', + 'plugins/cmds-config/config-nvme.c', + ] +endif diff --git a/src/nvme-cmds-deprecated.c b/plugins/cmds-deprecated/deprecated-plugin.c similarity index 98% rename from src/nvme-cmds-deprecated.c rename to plugins/cmds-deprecated/deprecated-plugin.c index d15e803ac5..1cd4956544 100644 --- a/src/nvme-cmds-deprecated.c +++ b/plugins/cmds-deprecated/deprecated-plugin.c @@ -17,15 +17,11 @@ #include -#include - #include "argconfig.h" #include "args.h" #include "cleanup.h" #include "plugin.h" -#ifdef CONFIG_DEPRECATED_CMDS - #ifdef CONFIG_FABRICS /* * gen-kxchap-secret dropped --nqn with the transform that used it. Take @@ -446,9 +442,8 @@ static struct command *commands[] = { NULL, }; -static void __shr_constructor register_group(void) +NVME_PLUGIN_INIT(register_plugin) { - plugin_add_group(&builtin, NULL, commands); + /* The help lists no deprecated command, nor the title */ + plugin_add_group(&builtin, "Deprecated", commands); } - -#endif /* CONFIG_DEPRECATED_CMDS */ diff --git a/plugins/cmds-deprecated/meson.build b/plugins/cmds-deprecated/meson.build new file mode 100644 index 0000000000..57ff3aa826 --- /dev/null +++ b/plugins/cmds-deprecated/meson.build @@ -0,0 +1,96 @@ +# SPDX-License-Identifier: GPL-2.0-or-later +# +# The deprecated top-level commands, which run the commands that replace +# them. plugins/meson.build builds this plugin with -Ddeprecated-cmds. + +plugin_extension = false + +plugin_sources += [ + 'plugins/cmds-deprecated/deprecated-plugin.c', +] + +plugin_commands = [ + 'id-ctrl', + 'id-ns', + 'id-ns-granularity', + 'id-ns-lba-format', + 'list-ns', + 'list-ctrl', + 'nvm-id-ctrl', + 'nvm-id-ns', + 'nvm-id-ns-lba-format', + 'primary-ctrl-caps', + 'list-secondary', + 'cmdset-ind-id-ns', + 'ns-descs', + 'id-nvmset', + 'id-uuid', + 'id-iocs', + 'id-domain', + 'list-endgrp', + 'create-ns', + 'delete-ns', + 'attach-ns', + 'detach-ns', + 'get-ns-id', + 'supported-log-pages', + 'telemetry-log', + 'fw-log', + 'changed-ns-list-log', + 'smart-log', + 'ana-log', + 'error-log', + 'effects-log', + 'endurance-log', + 'predictable-lat-log', + 'pred-lat-event-agg-log', + 'persistent-event-log', + 'endurance-event-agg-log', + 'lba-status-log', + 'resv-notif-log', + 'boot-part-log', + 'phy-rx-eom-log', + 'self-test-log', + 'fid-support-effects-log', + 'mi-cmd-support-effects-log', + 'media-unit-stat-log', + 'supported-cap-config-log', + 'mgmt-addr-list-log', + 'rotational-media-info-log', + 'changed-alloc-ns-list-log', + 'dispersed-ns-participating-nss-log', + 'reachability-groups-log', + 'reachability-associations-log', + 'host-discovery-log', + 'ave-discovery-log', + 'pull-model-ddc-req-log', + 'power-measurement-log', + 'fw-commit', + 'fw-download', + 'security-send', + 'security-recv', + 'resv-acquire', + 'resv-register', + 'resv-release', + 'resv-report', + 'sanitize-log', + 'dir-receive', + 'dir-send', + 'io-mgmt-recv', + 'io-mgmt-send', + 'nvme-mi-recv', + 'nvme-mi-send', +] +plugin_command_aliases = { + 'fw-commit': 'fw-activate', +} + +if want_fabrics + plugin_commands += [ + 'gen-dhchap-key', + 'check-dhchap-key', + 'gen-tls-key', + 'check-tls-key', + 'tls-key', + ] +endif diff --git a/plugins/dir/dir-plugin.c b/plugins/cmds-dir/dir-plugin.c similarity index 99% rename from plugins/dir/dir-plugin.c rename to plugins/cmds-dir/dir-plugin.c index 6e95b11f14..d9b7f55a39 100644 --- a/plugins/dir/dir-plugin.c +++ b/plugins/cmds-dir/dir-plugin.c @@ -22,6 +22,7 @@ #include "argconfig.h" #include "cleanup.h" +#include "dir-print.h" #include "global-ctx.h" #include "nvme-print.h" #include "plugin.h" diff --git a/plugins/cmds-dir/dir-print-binary.c b/plugins/cmds-dir/dir-print-binary.c new file mode 100644 index 0000000000..963d65595d --- /dev/null +++ b/plugins/cmds-dir/dir-print-binary.c @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include + +#include "dir-print.h" +#include "nvme-print.h" + +static void binary_directive(__u8 type, __u8 oper, __u16 spec, __u32 nsid, + __u64 result, void *buf, __u32 len) +{ + if (!buf) + return; + + d_raw(buf, len); +} + +static struct dir_print_ops binary_dir_print_ops = { + .directive = binary_directive, +}; + +struct dir_print_ops *dir_get_binary_print_ops(nvme_print_flags_t flags) +{ + binary_dir_print_ops.flags = flags; + return &binary_dir_print_ops; +} diff --git a/plugins/cmds-dir/dir-print-json.c b/plugins/cmds-dir/dir-print-json.c new file mode 100644 index 0000000000..09d5895d93 --- /dev/null +++ b/plugins/cmds-dir/dir-print-json.c @@ -0,0 +1,168 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include + +#include + +#include + +#include "dir-print.h" +#include "nvme-print.h" +#include "nvme-print-json.h" + +static void json_directive_show_fields_identify(__u8 doper, __u8 *field, + __u32 len, + struct json_object *r) +{ + struct json_object *support; + struct json_object *enabled; + struct json_object *persistent; + + switch (doper) { + case NVME_DIRECTIVE_RECEIVE_IDENTIFY_DOPER_PARAM: + if (len < NVME_DIRECTIVE_IDENTIFY_PARAM_LEN) { + obj_add_str(r, "Error", "directive data too short"); + break; + } + support = json_create_object(); + obj_add_obj(r, "Directive support", support); + obj_add_str(support, "Identify Directive", + *field & 0x1 ? "Supported" : "Not supported"); + obj_add_str(support, "Stream Directive", + *field & 0x2 ? "Supported" : "Not supported"); + obj_add_str(support, "Data Placement Directive", + *field & 0x4 ? "Supported" : "Not supported"); + enabled = json_create_object(); + obj_add_obj(r, "Directive enabled", enabled); + obj_add_str(enabled, "Identify Directive", + *(field + 32) & 0x1 ? "Enabled" : "Disabled"); + obj_add_str(enabled, "Stream Directive", + *(field + 32) & 0x2 ? "Enabled" : "Disabled"); + obj_add_str(enabled, "Data Placement Directive", + *(field + 32) & 0x4 ? "Enabled" : "Disabled"); + persistent = json_create_object(); + obj_add_obj(r, + "Directive Persistent Across Controller Level Resets", + persistent); + obj_add_str(persistent, "Identify Directive", + *(field + 64) & 0x1 ? "Enabled" : "Disabled"); + obj_add_str(persistent, "Stream Directive", + *(field + 64) & 0x2 ? "Enabled" : "Disabled"); + obj_add_str(persistent, "Data Placement Directive", + *(field + 64) & 0x4 ? "Enabled" : "Disabled"); + break; + default: + obj_add_str(r, "Error", + "invalid directive operations for Identify Directives"); + break; + } +} + +static void json_directive_show_fields_streams(__u8 doper, + unsigned int result, __u8 *field, + __u32 len, struct json_object *r) +{ + struct nvme_streams_directive_params *params = (void *)field; + struct nvme_streams_directive_status *status = (void *)field; + int count; + int i; + char json_str[STR_LEN]; + + switch (doper) { + case NVME_DIRECTIVE_RECEIVE_STREAMS_DOPER_PARAM: + if (len < sizeof(*params)) { + obj_add_str(r, "Error", "directive data too short"); + break; + } + obj_add_uint(r, "Max Streams Limit (MSL)", + le16_to_cpu(params->msl)); + obj_add_uint(r, "NVM Subsystem Streams Available (NSSA)", + le16_to_cpu(params->nssa)); + obj_add_uint(r, "NVM Subsystem Streams Open (NSSO)", + le16_to_cpu(params->nsso)); + obj_add_uint(r, "NVM Subsystem Stream Capability (NSSC)", + params->nssc); + obj_add_uint(r, "Stream Write Size (in unit of LB size) (SWS)", + le32_to_cpu(params->sws)); + obj_add_uint(r, + "Stream Granularity Size (in unit of SWS) (SGS)", + le16_to_cpu(params->sgs)); + obj_add_uint(r, "Namespace Streams Allocated (NSA)", + le16_to_cpu(params->nsa)); + obj_add_uint(r, "Namespace Streams Open (NSO)", + le16_to_cpu(params->nso)); + break; + case NVME_DIRECTIVE_RECEIVE_STREAMS_DOPER_STATUS: + if (len < sizeof(*status)) { + obj_add_str(r, "Error", "directive data too short"); + break; + } + count = nvme_streams_status_nr_sid(status, len); + obj_add_uint(r, "Open Stream Count", le16_to_cpu(status->osc)); + for (i = 0; i < count; i++) { + sprintf(json_str, "Stream Identifier %.6u", i + 1); + obj_add_uint(r, json_str, le16_to_cpu(status->sid[i])); + } + break; + case NVME_DIRECTIVE_RECEIVE_STREAMS_DOPER_RESOURCE: + obj_add_uint(r, "Namespace Streams Allocated (NSA)", + result & 0xffff); + break; + default: + obj_add_str(r, "Error", + "invalid directive operations for Streams Directives"); + break; + } +} + +static void json_directive_show_fields(__u8 dtype, __u8 doper, + unsigned int result, __u8 *field, + __u32 len, struct json_object *r) +{ + switch (dtype) { + case NVME_DIRECTIVE_DTYPE_IDENTIFY: + json_directive_show_fields_identify(doper, field, len, r); + break; + case NVME_DIRECTIVE_DTYPE_STREAMS: + json_directive_show_fields_streams(doper, result, field, len, + r); + break; + default: + obj_add_str(r, "Error", "invalid directive type"); + break; + } +} + +static void json_directive_show(__u8 type, __u8 oper, __u16 spec, + __u32 nsid, __u64 result, void *buf, __u32 len) +{ + struct json_object *r = json_root(); + char json_str[STR_LEN]; + + sprintf(json_str, "%#x", type); + obj_add_str(r, "Type", json_str); + sprintf(json_str, "%#x", oper); + obj_add_str(r, "Operation", json_str); + sprintf(json_str, "%#x", spec); + obj_add_str(r, "spec", json_str); + sprintf(json_str, "%#x", nsid); + obj_add_str(r, "NSID", json_str); + sprintf(json_str, "%#"PRIx64, (uint64_t)result); + obj_add_result(r, "%s", json_str); + + if (json_verbose_mode()) + json_directive_show_fields(type, oper, result, buf, len, r); + else if (buf) + obj_d(r, "data", buf, len, 16, 1); +} + +static struct dir_print_ops dir_json_print_ops = { + .directive = json_directive_show, +}; + +struct dir_print_ops *dir_get_json_print_ops(nvme_print_flags_t flags) +{ + dir_json_print_ops.flags = flags; + return &dir_json_print_ops; +} diff --git a/plugins/cmds-dir/dir-print-stdout.c b/plugins/cmds-dir/dir-print-stdout.c new file mode 100644 index 0000000000..bdd36f2a52 --- /dev/null +++ b/plugins/cmds-dir/dir-print-stdout.c @@ -0,0 +1,201 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include + +#include + +#include +#include + +#include "dir-print.h" +#include "nvme-print.h" +#include "nvme-print-stdout.h" + +static struct dir_print_ops dir_stdout_print_ops; + +static void stdout_directive_show_fields(__u8 dtype, __u8 doper, + unsigned int result, + unsigned char *buf, __u32 len) +{ + struct nvme_streams_directive_params *params = (void *)buf; + struct nvme_streams_directive_status *status = (void *)buf; + __u8 *field = buf; + int count, i; + struct shr_table *t; + + switch (dtype) { + case NVME_DIRECTIVE_DTYPE_IDENTIFY: + switch (doper) { + case NVME_DIRECTIVE_RECEIVE_IDENTIFY_DOPER_PARAM: + if (len < NVME_DIRECTIVE_IDENTIFY_PARAM_LEN) { + fprintf(stderr, "directive data too short\n"); + break; + } + printf("\tDirective support\n"); + + t = stdout_kv_table_create(); + if (!t) + return; + + shr_table_set_indent(t, 2); + stdout_kv_add(t, "Identify Directive", "%s", + (*field & 0x1) ? + "supported" : "not supported"); + stdout_kv_add(t, "Stream Directive", "%s", + (*field & 0x2) ? + "supported" : "not supported"); + stdout_kv_add(t, "Data Placement Directive", "%s", + (*field & 0x4) ? + "supported" : "not supported"); + + stdout_kv_table_finish(t, "directive-show"); + + printf("\tDirective enabled\n"); + + t = stdout_kv_table_create(); + if (!t) + return; + + shr_table_set_indent(t, 2); + stdout_kv_add(t, "Identify Directive", "%s", + (*(field + 32) & 0x1) ? + "enabled" : "disabled"); + stdout_kv_add(t, "Stream Directive", "%s", + (*(field + 32) & 0x2) ? + "enabled" : "disabled"); + stdout_kv_add(t, "Data Placement Directive", "%s", + (*(field + 32) & 0x4) ? + "enabled" : "disabled"); + + stdout_kv_table_finish(t, "directive-show"); + + printf( + "\tDirective Persistent Across Controller Level Resets\n"); + + t = stdout_kv_table_create(); + if (!t) + return; + + shr_table_set_indent(t, 2); + stdout_kv_add(t, "Identify Directive", "%s", + (*(field + 64) & 0x1) ? + "enabled" : "disabled"); + stdout_kv_add(t, "Stream Directive", "%s", + (*(field + 64) & 0x2) ? + "enabled" : "disabled"); + stdout_kv_add(t, "Data Placement Directive", "%s", + (*(field + 64) & 0x4) ? + "enabled" : "disabled"); + + stdout_kv_table_finish(t, "directive-show"); + break; + default: + fprintf(stderr, + "invalid directive operations for Identify Directives\n"); + break; + } + break; + case NVME_DIRECTIVE_DTYPE_STREAMS: + switch (doper) { + case NVME_DIRECTIVE_RECEIVE_STREAMS_DOPER_PARAM: + if (len < sizeof(*params)) { + fprintf(stderr, "directive data too short\n"); + break; + } + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, "Max Streams Limit (MSL)", "%u", + le16_to_cpu(params->msl)); + stdout_kv_add(t, + "NVM Subsystem Streams Available (NSSA)", + "%u", le16_to_cpu(params->nssa)); + stdout_kv_add(t, + "NVM Subsystem Streams Open (NSSO)", + "%u", le16_to_cpu(params->nsso)); + stdout_kv_add(t, + "NVM Subsystem Stream Capability (NSSC)", + "%u", params->nssc); + stdout_kv_add(t, + "Stream Write Size (in unit of LB size) (SWS)", + "%u", le32_to_cpu(params->sws)); + stdout_kv_add(t, + "Stream Granularity Size (in unit of SWS) (SGS)", + "%u", le16_to_cpu(params->sgs)); + stdout_kv_add(t, + "Namespace Streams Allocated (NSA)", + "%u", le16_to_cpu(params->nsa)); + stdout_kv_add(t, "Namespace Streams Open (NSO)", "%u", + le16_to_cpu(params->nso)); + + stdout_kv_table_finish(t, "directive-show"); + break; + case NVME_DIRECTIVE_RECEIVE_STREAMS_DOPER_STATUS: + if (len < sizeof(*status)) { + fprintf(stderr, "directive data too short\n"); + break; + } + count = nvme_streams_status_nr_sid(status, len); + + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, "Open Stream Count", "%u", + le16_to_cpu(status->osc)); + for (i = 0; i < count; i++) { + char name[32]; + + snprintf(name, sizeof(name), + "Stream Identifier %.6u", i + 1); + stdout_kv_add(t, name, "%u", + le16_to_cpu(status->sid[i])); + } + + stdout_kv_table_finish(t, "directive-show"); + break; + case NVME_DIRECTIVE_RECEIVE_STREAMS_DOPER_RESOURCE: + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, "Namespace Streams Allocated (NSA)", + "%u", result & 0xffff); + + stdout_kv_table_finish(t, "directive-show"); + break; + default: + fprintf(stderr, + "invalid directive operations for Streams Directives\n"); + break; + } + break; + default: + fprintf(stderr, "invalid directive type\n"); + break; + } +} + +static void stdout_directive_show(__u8 type, __u8 oper, __u16 spec, + __u32 nsid, __u64 result, void *buf, + __u32 len) +{ + printf("dir-receive: type:%#x operation:%#x spec:%#x nsid:%#x result:%#" + PRIx64 "\n", type, oper, spec, nsid, (uint64_t)result); + if (dir_stdout_print_ops.flags & VERBOSE) + stdout_directive_show_fields(type, oper, result, buf, len); + else if (buf) + d(buf, len, 16, 1); +} + +static struct dir_print_ops dir_stdout_print_ops = { + .directive = stdout_directive_show, +}; + +struct dir_print_ops *dir_get_stdout_print_ops(nvme_print_flags_t flags) +{ + dir_stdout_print_ops.flags = flags; + return &dir_stdout_print_ops; +} diff --git a/plugins/cmds-dir/dir-print.c b/plugins/cmds-dir/dir-print.c new file mode 100644 index 0000000000..45ff5e1328 --- /dev/null +++ b/plugins/cmds-dir/dir-print.c @@ -0,0 +1,40 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include + +#include "dir-print.h" +#include "nvme-print.h" + +/* + * Run the printers in the sandbox. Like nvme_print(), silently skip + * printers that an output format does not implement. + */ +#define dir_print(name, flags, ...) \ + do { \ + struct dir_print_ops *ops = dir_print_ops(flags); \ + \ + if (ops && ops->name) \ + nvme_print_decoder(ops, name, true, flags, \ + ##__VA_ARGS__); \ + } while (false) + +static struct dir_print_ops *dir_print_ops(nvme_print_flags_t flags) +{ + struct dir_print_ops *ops = NULL; + + if (flags & JSON || nvme_is_output_format_json()) + ops = dir_get_json_print_ops(flags); + else if (flags & BINARY) + ops = dir_get_binary_print_ops(flags); + else + ops = dir_get_stdout_print_ops(flags); + + return ops; +} + +void nvme_directive_show(__u8 type, __u8 oper, __u16 spec, __u32 nsid, + __u64 result, void *buf, __u32 len, + nvme_print_flags_t flags) +{ + dir_print(directive, flags, type, oper, spec, nsid, result, buf, len); +} diff --git a/plugins/cmds-dir/dir-print.h b/plugins/cmds-dir/dir-print.h new file mode 100644 index 0000000000..633e81fb63 --- /dev/null +++ b/plugins/cmds-dir/dir-print.h @@ -0,0 +1,52 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#pragma once + +#include + +#include + +#include "args.h" + +/* + * The bytes of the Identify Directive Return Parameters the printers + * decode: the directives supported, enabled and persistent across + * controller level resets. + */ +#define NVME_DIRECTIVE_IDENTIFY_PARAM_LEN 96 + +/* + * The Stream Identifiers of a Streams Directive Get Status data structure + * of @len bytes, which holds at least its Open Stream Count: the count + * the device reports, but at most as many as fit. + */ +static inline int nvme_streams_status_nr_sid( + struct nvme_streams_directive_status *status, __u32 len) +{ + int max = (len - sizeof(*status)) / sizeof(status->sid[0]); + int n = le16_to_cpu(status->osc); + + return n < max ? n : max; +} + +struct dir_print_ops { + void (*directive)(__u8 type, __u8 oper, __u16 spec, __u32 nsid, + __u64 result, void *buf, __u32 len); + nvme_print_flags_t flags; +}; + +struct dir_print_ops *dir_get_stdout_print_ops(nvme_print_flags_t flags); +struct dir_print_ops *dir_get_binary_print_ops(nvme_print_flags_t flags); + +#ifdef CONFIG_JSONC +struct dir_print_ops *dir_get_json_print_ops(nvme_print_flags_t flags); +#else +static inline struct dir_print_ops * +dir_get_json_print_ops(nvme_print_flags_t flags) +{ + return NULL; +} +#endif + +void nvme_directive_show(__u8 type, __u8 oper, __u16 spec, __u32 nsid, + __u64 result, void *buf, __u32 len, + nvme_print_flags_t flags); diff --git a/plugins/cmds-dir/meson.build b/plugins/cmds-dir/meson.build new file mode 100644 index 0000000000..cc33726165 --- /dev/null +++ b/plugins/cmds-dir/meson.build @@ -0,0 +1,16 @@ +# SPDX-License-Identifier: GPL-2.0-or-later + +plugin_name = 'dir' + +plugin_sources += [ + 'plugins/cmds-dir/dir-plugin.c', + 'plugins/cmds-dir/dir-print.c', + 'plugins/cmds-dir/dir-print-stdout.c', + 'plugins/cmds-dir/dir-print-binary.c', +] + +if json_c_dep.found() + plugin_sources += [ + 'plugins/cmds-dir/dir-print-json.c', + ] +endif diff --git a/plugins/exclusion/exclusion-nvme.c b/plugins/cmds-exclusion/exclusion-nvme.c similarity index 100% rename from plugins/exclusion/exclusion-nvme.c rename to plugins/cmds-exclusion/exclusion-nvme.c diff --git a/plugins/nbft/meson.build b/plugins/cmds-exclusion/meson.build similarity index 55% rename from plugins/nbft/meson.build rename to plugins/cmds-exclusion/meson.build index 541e05d1dc..08e48bfb49 100644 --- a/plugins/nbft/meson.build +++ b/plugins/cmds-exclusion/meson.build @@ -1,7 +1,9 @@ # SPDX-License-Identifier: GPL-2.0-or-later +plugin_name = 'exclusion' + if want_fabrics plugin_sources += [ - 'plugins/nbft/nbft-plugin.c', + 'plugins/cmds-exclusion/exclusion-nvme.c', ] endif diff --git a/src/nvme-cmds-fabrics.c b/plugins/cmds-fabrics/cmds-fabrics-plugin.c similarity index 97% rename from src/nvme-cmds-fabrics.c rename to plugins/cmds-fabrics/cmds-fabrics-plugin.c index 2ad129aef1..86a51b0e9d 100644 --- a/src/nvme-cmds-fabrics.c +++ b/plugins/cmds-fabrics/cmds-fabrics-plugin.c @@ -33,7 +33,6 @@ #include #include #include -#include #include #include #include @@ -44,12 +43,11 @@ #include "argconfig.h" #include "cleanup.h" #include "fabrics.h" +#include "fabrics-print.h" #include "nvme-print.h" #include "plugin.h" #include "privsep.h" -#ifdef CONFIG_FABRICS - static int gen_hostnqn_cmd(int argc, char **argv, struct command *acmd, struct plugin *plugin) { const char *desc = "Generate a hostnqn"; @@ -248,9 +246,8 @@ static struct command *commands[] = { NULL, }; -static void __shr_constructor register_group(void) +NVME_PLUGIN_INIT(register_plugin) { plugin_add_group(&builtin, "Fabrics", commands); + fabrics_register_log_decoder(); } - -#endif /* CONFIG_FABRICS */ diff --git a/src/config-convert.c b/plugins/cmds-fabrics/config-convert.c similarity index 100% rename from src/config-convert.c rename to plugins/cmds-fabrics/config-convert.c diff --git a/src/config-convert.h b/plugins/cmds-fabrics/config-convert.h similarity index 100% rename from src/config-convert.h rename to plugins/cmds-fabrics/config-convert.h diff --git a/plugins/cmds-fabrics/fabrics-print-binary.c b/plugins/cmds-fabrics/fabrics-print-binary.c new file mode 100644 index 0000000000..4a6b922db2 --- /dev/null +++ b/plugins/cmds-fabrics/fabrics-print-binary.c @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include + +#include "fabrics-print.h" +#include "nvme-print.h" + +static void binary_discovery_log(const struct nvmf_discovery_log *log, + int numrec) +{ + d_raw((unsigned char *)log, + sizeof(struct nvmf_discovery_log) + + numrec * sizeof(struct nvmf_disc_log_entry)); +} + +static struct fabrics_print_ops binary_fabrics_print_ops = { + .discovery_log = binary_discovery_log, +}; + +struct fabrics_print_ops * +fabrics_get_binary_print_ops(nvme_print_flags_t flags) +{ + binary_fabrics_print_ops.flags = flags; + return &binary_fabrics_print_ops; +} diff --git a/plugins/cmds-fabrics/fabrics-print-json.c b/plugins/cmds-fabrics/fabrics-print-json.c new file mode 100644 index 0000000000..727fe54d2e --- /dev/null +++ b/plugins/cmds-fabrics/fabrics-print-json.c @@ -0,0 +1,128 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include + +#include +#include + +#include "cleanup.h" +#include "fabrics-print.h" +#include "nvme-print.h" +#include "nvme-print-json.h" + +static void json_discovery_log(const struct nvmf_discovery_log *log, int numrec) +{ + struct json_object *r = json_root(); + struct json_object *entries = json_create_array(); + int i; + + obj_add_uint64(r, "genctr", le64_to_cpu(log->genctr)); + obj_add_array(r, "records", entries); + + for (i = 0; i < numrec; i++) { + const struct nvmf_disc_log_entry *e = &log->entries[i]; + struct json_object *entry = json_create_object(); + /* + * e->trsvcid/subnqn/traddr are fixed-width fields off the wire, + * not guaranteed NUL-terminated. json_object_new_string() + * needs a NUL-terminated C string, so make NUL-terminated + * copies and trim trailing spaces (if any). Members of e + * cannot be modified directly (we do not own that data). + */ + __cleanup_free char *trsvcid = NULL; + __cleanup_free char *traddr = NULL; + __cleanup_free char *subnqn = NULL; + + trsvcid = shr_buf2str(e->trsvcid, sizeof(e->trsvcid)); + traddr = shr_buf2str(e->traddr, sizeof(e->traddr)); + subnqn = shr_buf2str(e->subnqn, sizeof(e->subnqn)); + + obj_add_str(entry, "trtype", libnvmf_trtype_str(e->trtype)); + obj_add_str(entry, "adrfam", libnvmf_adrfam_str(e->adrfam)); + obj_add_str(entry, "subtype", libnvmf_subtype_str(e->subtype)); + obj_add_str(entry, "treq", libnvmf_treq_str(e->treq)); + obj_add_uint(entry, "portid", le16_to_cpu(e->portid)); + obj_add_str(entry, "trsvcid", trsvcid); + obj_add_str(entry, "subnqn", subnqn); + obj_add_str(entry, "traddr", traddr); + obj_add_str(entry, "eflags", + libnvmf_eflags_str(le16_to_cpu(e->eflags))); + + switch (e->trtype) { + case NVMF_TRTYPE_RDMA: + obj_add_str(entry, "rdma_prtype", + libnvmf_prtype_str(e->tsas.rdma.prtype)); + obj_add_str(entry, "rdma_qptype", + libnvmf_qptype_str(e->tsas.rdma.qptype)); + obj_add_str(entry, "rdma_cms", + libnvmf_cms_str(e->tsas.rdma.cms)); + obj_add_uint(entry, "rdma_pkey", + le16_to_cpu(e->tsas.rdma.pkey)); + break; + case NVMF_TRTYPE_TCP: + obj_add_str(entry, "sectype", + libnvmf_sectype_str(e->tsas.tcp.sectype)); + break; + default: + break; + } + array_add_obj(entries, entry); + } +} + +static void json_add_param(const char *key, const char *value, void *user_data) +{ + obj_add_str(user_data, key, value); +} + +/* + * libnvmf_config_conn_for_each() callback for "nvme config show -o json". + * Reports fields as configured, not canonicalized through a TID (which has + * no per-field accessors). hostnqn/hostid are null when a persona falls + * back to the system default, not the value it would resolve to. + */ +static void json_add_conn(const struct libnvmf_config_conn *c, void *user_data) +{ + struct json_object *entries = user_data; + struct json_object *entry = json_create_object(); + struct json_object *params_obj = json_create_object(); + const struct libnvmf_params *params = libnvmf_config_conn_get_params(c); + + obj_add_str(entry, "source", libnvmf_config_conn_get_source(c)); + obj_add_bool(entry, "is_dc", libnvmf_config_conn_is_dc(c)); + obj_add_str(entry, "transport", libnvmf_config_conn_get_transport(c)); + obj_add_str(entry, "traddr", libnvmf_config_conn_get_traddr(c)); + obj_add_str(entry, "trsvcid", libnvmf_config_conn_get_trsvcid(c)); + obj_add_str(entry, "nqn", libnvmf_config_conn_get_subsysnqn(c)); + obj_add_str(entry, "host-traddr", + libnvmf_config_conn_get_host_traddr(c)); + obj_add_str(entry, "host-iface", libnvmf_config_conn_get_host_iface(c)); + obj_add_str(entry, "hostnqn", libnvmf_config_conn_get_hostnqn(c)); + obj_add_str(entry, "hostid", libnvmf_config_conn_get_hostid(c)); + + libnvmf_params_for_each(params, json_add_param, params_obj); + obj_add_obj(entry, "params", params_obj); + + array_add_obj(entries, entry); +} + +static void json_config_conn_list(struct libnvmf_config *config) +{ + struct json_object *r = json_root(); + struct json_object *entries = json_create_array(); + + obj_add_array(r, "connections", entries); + libnvmf_config_conn_for_each(config, json_add_conn, entries); +} + +static struct fabrics_print_ops json_fabrics_print_ops = { + .discovery_log = json_discovery_log, + .config_conn_list = json_config_conn_list, +}; + +struct fabrics_print_ops * +fabrics_get_json_print_ops(nvme_print_flags_t flags) +{ + json_fabrics_print_ops.flags = flags; + return &json_fabrics_print_ops; +} diff --git a/plugins/cmds-fabrics/fabrics-print-stdout.c b/plugins/cmds-fabrics/fabrics-print-stdout.c new file mode 100644 index 0000000000..22a67660a3 --- /dev/null +++ b/plugins/cmds-fabrics/fabrics-print-stdout.c @@ -0,0 +1,191 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include + +#include + +#include +#include +#include + +#include "cleanup.h" +#include "fabrics-print.h" +#include "nvme-print.h" +#include "nvme-print-stdout.h" + +static void stdout_discovery_log(const struct nvmf_discovery_log *log, + int numrec) +{ + int i; + + printf("\nDiscovery Log Number of Records %d, Generation counter %" + PRIu64"\n", numrec, le64_to_cpu(log->genctr)); + + for (i = 0; i < numrec; i++) { + const struct nvmf_disc_log_entry *e = &log->entries[i]; + + /* + * e->trsvcid/subnqn/traddr are fixed-width fields off the + * wire, space-padded per the spec, and not guaranteed + * NUL-terminated by a non-compliant DC. shr_buf2str() bounds + * the read to the field's own size and strips the padding. + */ + __cleanup_free char *trsvcid = NULL; + __cleanup_free char *subnqn = NULL; + __cleanup_free char *traddr = NULL; + struct shr_table *t; + + trsvcid = shr_buf2str(e->trsvcid, sizeof(e->trsvcid)); + subnqn = shr_buf2str(e->subnqn, sizeof(e->subnqn)); + traddr = shr_buf2str(e->traddr, sizeof(e->traddr)); + + printf("=====Discovery Log Entry %d======\n", i); + + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, "trtype", "%s", libnvmf_trtype_str(e->trtype)); + stdout_kv_add(t, "adrfam", "%s", + e->traddr[0] ? + libnvmf_adrfam_str(e->adrfam) : ""); + stdout_kv_add(t, "subtype", "%s", + libnvmf_subtype_str(e->subtype)); + stdout_kv_add(t, "treq", "%s", libnvmf_treq_str(e->treq)); + stdout_kv_add(t, "portid", "%d", le16_to_cpu(e->portid)); + stdout_kv_add(t, "trsvcid", "%s", trsvcid); + stdout_kv_add(t, "subnqn", "%s", subnqn); + stdout_kv_add(t, "traddr", "%s", traddr); + stdout_kv_add(t, "eflags", "%s", + libnvmf_eflags_str(le16_to_cpu(e->eflags))); + + switch (e->trtype) { + case NVMF_TRTYPE_RDMA: + stdout_kv_add(t, "rdma_prtype", "%s", + libnvmf_prtype_str(e->tsas.rdma.prtype)); + stdout_kv_add(t, "rdma_qptype", "%s", + libnvmf_qptype_str(e->tsas.rdma.qptype)); + stdout_kv_add(t, "rdma_cms", "%s", + libnvmf_cms_str(e->tsas.rdma.cms)); + stdout_kv_add(t, "rdma_pkey", "%#04x", + le16_to_cpu(e->tsas.rdma.pkey)); + break; + case NVMF_TRTYPE_TCP: + stdout_kv_add(t, "sectype", "%s", + libnvmf_sectype_str(e->tsas.tcp.sectype)); + break; + } + + stdout_kv_table_finish(t, "discovery-log"); + } +} + +/* + * libnvmf_connect_args_emit() callback for "nvme config show": print each + * formatted "--option=value" straight to stdout as part of the running + * "nvme connect" line. + */ +static void stdout_print_conn_arg(const char *arg, void *user_data) +{ + printf(" %s", arg); +} + +static void stdout_print_conn_field(const char *name, const char *value) +{ + if (value) + printf(" --%s=%s", name, value); +} + +/* + * libnvmf_config_conn_for_each() callback for "nvme config show": render + * one resolved connection as its equivalent "nvme connect" command line. + * + * Identity is deliberately left unresolved here (unlike build_conn_tid()'s + * connect-time callers): a persona with no hostnqn/hostid falls back to the + * system default at connect time, not parse time, so showing the concrete + * value here would suggest a fixed identity the config doesn't actually pin. + * + * Addressing is not resolved either, and no TID is built for a hostname: + * "show" must never touch the network, and a hostname traddr is legitimate + * INI content a TID (numeric-only) can't represent. The canonicalized TID + * rendering is used when the address is already numeric; a raw hostname + * falls back to printing the field as configured. + */ +static void stdout_print_conn(const struct libnvmf_config_conn *conn, + void *user_data) +{ + bool is_dc = libnvmf_config_conn_is_dc(conn); + const char *hostnqn = libnvmf_config_conn_get_hostnqn(conn); + const char *hostid = libnvmf_config_conn_get_hostid(conn); + const struct libnvmf_params *params = + libnvmf_config_conn_get_params(conn); + __cleanup_nvmf_tid struct libnvmf_tid *tid = NULL; + + printf("# %s: %s\n", libnvmf_config_conn_get_source(conn), + is_dc ? "Discovery Controller" : "I/O Controller"); + + libnvmf_tid_from_fields( + libnvmf_config_conn_get_transport(conn), + libnvmf_config_conn_get_traddr(conn), + libnvmf_config_conn_get_trsvcid(conn), + libnvmf_config_conn_get_subsysnqn(conn), + libnvmf_config_conn_get_host_traddr(conn), + libnvmf_config_conn_get_host_iface(conn), + hostnqn, hostid, &tid); + + /* + * A DC entry is consumed via libnvmf_discover() (log in, fetch the + * discovery log, connect everything returned) -- "nvme connect-all" + * is its real equivalent, not a bare "nvme connect" (which would + * only open the admin queue, matching just the niche "connect -J" + * mode instead of the primary discover/connect-all consumption + * path this command documents). + */ + printf("nvme %s", is_dc ? "connect-all" : "connect"); + if (tid) { + libnvmf_connect_args_emit(tid, params, stdout_print_conn_arg, + NULL); + } else { + const char *transport = libnvmf_config_conn_get_transport(conn); + const char *traddr = libnvmf_config_conn_get_traddr(conn); + const char *trsvcid = libnvmf_config_conn_get_trsvcid(conn); + const char *subsysnqn = libnvmf_config_conn_get_subsysnqn(conn); + const char *host_traddr = + libnvmf_config_conn_get_host_traddr(conn); + const char *host_iface = + libnvmf_config_conn_get_host_iface(conn); + + stdout_print_conn_field("transport", transport); + stdout_print_conn_field("traddr", traddr); + stdout_print_conn_field("trsvcid", trsvcid); + stdout_print_conn_field("nqn", subsysnqn); + stdout_print_conn_field("host-traddr", host_traddr); + stdout_print_conn_field("host-iface", host_iface); + stdout_print_conn_field("hostnqn", hostnqn); + stdout_print_conn_field("hostid", hostid); + libnvmf_connect_args_emit(NULL, params, stdout_print_conn_arg, + NULL); + } + printf("\n"); + if (!hostnqn || !hostid) + printf(" (hostnqn/hostid: system default)\n"); + printf("\n"); +} + +static void stdout_config_conn_list(struct libnvmf_config *config) +{ + libnvmf_config_conn_for_each(config, stdout_print_conn, NULL); +} + +static struct fabrics_print_ops stdout_fabrics_print_ops = { + .discovery_log = stdout_discovery_log, + .config_conn_list = stdout_config_conn_list, +}; + +struct fabrics_print_ops * +fabrics_get_stdout_print_ops(nvme_print_flags_t flags) +{ + stdout_fabrics_print_ops.flags = flags; + return &stdout_fabrics_print_ops; +} diff --git a/plugins/cmds-fabrics/fabrics-print.c b/plugins/cmds-fabrics/fabrics-print.c new file mode 100644 index 0000000000..8ed23942e1 --- /dev/null +++ b/plugins/cmds-fabrics/fabrics-print.c @@ -0,0 +1,81 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include + +#include +#include + +#include "fabrics-print.h" +#include "nvme-print.h" + +/* + * Like nvme_print(), silently skip printers that an output format does + * not implement. + */ +#define fabrics_print(name, sandbox, flags, ...) \ + do { \ + struct fabrics_print_ops *__fops = \ + fabrics_print_ops(flags); \ + \ + if (__fops && __fops->name) \ + nvme_print_decoder(__fops, name, sandbox, \ + flags, ##__VA_ARGS__); \ + } while (false) + +static struct fabrics_print_ops *fabrics_print_ops(nvme_print_flags_t flags) +{ + struct fabrics_print_ops *ops = NULL; + + if (flags & JSON || nvme_is_output_format_json()) + ops = fabrics_get_json_print_ops(flags); + else if (flags & BINARY) + ops = fabrics_get_binary_print_ops(flags); + else + ops = fabrics_get_stdout_print_ops(flags); + + return ops; +} + +/* The log page comes from the device: decode it in the sandbox */ +void fabrics_show_discovery_log(const struct nvmf_discovery_log *log, + uint64_t numrec, nvme_print_flags_t flags) +{ + fabrics_print(discovery_log, true, flags, log, numrec); +} + +/* The configuration is no device data: print it in process */ +void fabrics_show_config_conn_list(struct libnvmf_config *config, + nvme_print_flags_t flags) +{ + fabrics_print(config_conn_list, false, flags, config); +} + +static bool fabrics_show_log(const char *devname, + enum nvme_cmd_get_log_lid lid, __u32 nsid, + __u16 lsi, __u8 lsp, void *log, __u32 len, + nvme_print_flags_t flags) +{ + struct nvmf_discovery_log *discovery_log = log; + __u64 nr; + + if (lid != NVME_LOG_LID_DISCOVERY) + return false; + + /* no more records than the log holds, before size_t cuts it */ + nr = min_t(__u64, le64_to_cpu(discovery_log->numrec), len); + fabrics_show_discovery_log(discovery_log, + nvme_log_nr_entries(nr, len, sizeof(*discovery_log), + sizeof(discovery_log->entries[0])), + flags); + + return true; +} + +static struct nvme_log_decoder fabrics_log_decoder = { + .show = fabrics_show_log, +}; + +void fabrics_register_log_decoder(void) +{ + nvme_register_log_decoder(&fabrics_log_decoder); +} diff --git a/plugins/cmds-fabrics/fabrics-print.h b/plugins/cmds-fabrics/fabrics-print.h new file mode 100644 index 0000000000..303d696d2b --- /dev/null +++ b/plugins/cmds-fabrics/fabrics-print.h @@ -0,0 +1,35 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#pragma once + +#include + +#include "args.h" + +struct fabrics_print_ops { + void (*discovery_log)(const struct nvmf_discovery_log *log, int numrec); + void (*config_conn_list)(struct libnvmf_config *config); + nvme_print_flags_t flags; +}; + +struct fabrics_print_ops * +fabrics_get_stdout_print_ops(nvme_print_flags_t flags); +struct fabrics_print_ops * +fabrics_get_binary_print_ops(nvme_print_flags_t flags); + +#ifdef CONFIG_JSONC +struct fabrics_print_ops *fabrics_get_json_print_ops(nvme_print_flags_t flags); +#else +static inline struct fabrics_print_ops * +fabrics_get_json_print_ops(nvme_print_flags_t flags) +{ + return NULL; +} +#endif + +void fabrics_show_discovery_log(const struct nvmf_discovery_log *log, + uint64_t numrec, nvme_print_flags_t flags); +void fabrics_show_config_conn_list(struct libnvmf_config *config, + nvme_print_flags_t flags); + +/* Register the Discovery log page decoder for get-log -v */ +void fabrics_register_log_decoder(void); diff --git a/src/fabrics.c b/plugins/cmds-fabrics/fabrics.c similarity index 99% rename from src/fabrics.c rename to plugins/cmds-fabrics/fabrics.c index daddf743c9..ef30edd643 100644 --- a/src/fabrics.c +++ b/plugins/cmds-fabrics/fabrics.c @@ -55,6 +55,7 @@ #include "cleanup.h" #include "config-convert.h" #include "fabrics.h" +#include "fabrics-print.h" #include "pre-os.h" #include "global-ctx.h" #include "logging.h" @@ -335,7 +336,7 @@ static void hook_discovery_log(struct libnvmf_context *fctx, if (hfd->raw) save_discovery_log(hfd->raw, log); else if (!libnvmf_context_get_connect(fctx)) - nvme_show_discovery_log(log, numrec, hfd->flags); + fabrics_show_discovery_log(log, numrec, hfd->flags); } /* @@ -1961,7 +1962,7 @@ int fabrics_config_show(const char *desc, int argc, char **argv) return ret; } - nvme_show_config_conn_list(cfg, flags); + fabrics_show_config_conn_list(cfg, flags); libnvmf_config_free(cfg); return 0; diff --git a/src/fabrics.h b/plugins/cmds-fabrics/fabrics.h similarity index 100% rename from src/fabrics.h rename to plugins/cmds-fabrics/fabrics.h diff --git a/plugins/cmds-fabrics/meson.build b/plugins/cmds-fabrics/meson.build new file mode 100644 index 0000000000..13e6713567 --- /dev/null +++ b/plugins/cmds-fabrics/meson.build @@ -0,0 +1,34 @@ +# SPDX-License-Identifier: GPL-2.0-or-later +# +# The fabrics top-level commands. plugins/meson.build builds this plugin +# with -Dfabrics. The config plugin uses its functions. + +plugin_extension = false + +if want_fabrics + plugin_sources += [ + 'plugins/cmds-fabrics/cmds-fabrics-plugin.c', + 'plugins/cmds-fabrics/config-convert.c', + 'plugins/cmds-fabrics/fabrics.c', + 'plugins/cmds-fabrics/fabrics-print.c', + 'plugins/cmds-fabrics/fabrics-print-binary.c', + 'plugins/cmds-fabrics/fabrics-print-stdout.c', + 'plugins/cmds-fabrics/pre-os.c', + ] + if json_c_dep.found() + plugin_sources += [ + 'plugins/cmds-fabrics/fabrics-print-json.c', + ] + endif + + plugin_commands = [ + 'discover', + 'connect-all', + 'connect', + 'disconnect', + 'disconnect-all', + 'dim', + 'gen-hostnqn', + 'show-hostnqn', + ] +endif diff --git a/src/pre-os.c b/plugins/cmds-fabrics/pre-os.c similarity index 100% rename from src/pre-os.c rename to plugins/cmds-fabrics/pre-os.c diff --git a/src/pre-os.h b/plugins/cmds-fabrics/pre-os.h similarity index 100% rename from src/pre-os.h rename to plugins/cmds-fabrics/pre-os.h diff --git a/plugins/fdp/fdp-print-binary.c b/plugins/cmds-fdp/fdp-print-binary.c similarity index 100% rename from plugins/fdp/fdp-print-binary.c rename to plugins/cmds-fdp/fdp-print-binary.c diff --git a/plugins/fdp/fdp-print-json.c b/plugins/cmds-fdp/fdp-print-json.c similarity index 100% rename from plugins/fdp/fdp-print-json.c rename to plugins/cmds-fdp/fdp-print-json.c diff --git a/plugins/fdp/fdp-print-stdout.c b/plugins/cmds-fdp/fdp-print-stdout.c similarity index 100% rename from plugins/fdp/fdp-print-stdout.c rename to plugins/cmds-fdp/fdp-print-stdout.c diff --git a/plugins/fdp/fdp-print.c b/plugins/cmds-fdp/fdp-print.c similarity index 100% rename from plugins/fdp/fdp-print.c rename to plugins/cmds-fdp/fdp-print.c diff --git a/plugins/fdp/fdp-print.h b/plugins/cmds-fdp/fdp-print.h similarity index 100% rename from plugins/fdp/fdp-print.h rename to plugins/cmds-fdp/fdp-print.h diff --git a/plugins/fdp/fdp.c b/plugins/cmds-fdp/fdp.c similarity index 100% rename from plugins/fdp/fdp.c rename to plugins/cmds-fdp/fdp.c diff --git a/plugins/cmds-fdp/meson.build b/plugins/cmds-fdp/meson.build new file mode 100644 index 0000000000..3db7837325 --- /dev/null +++ b/plugins/cmds-fdp/meson.build @@ -0,0 +1,16 @@ +# SPDX-License-Identifier: GPL-2.0-or-later + +plugin_name = 'fdp' + +plugin_sources += [ + 'plugins/cmds-fdp/fdp.c', + 'plugins/cmds-fdp/fdp-print.c', + 'plugins/cmds-fdp/fdp-print-stdout.c', + 'plugins/cmds-fdp/fdp-print-binary.c', +] + +if json_c_dep.found() + plugin_sources += [ + 'plugins/cmds-fdp/fdp-print-json.c', + ] +endif diff --git a/src/nvme-cmds-feature.c b/plugins/cmds-feat/feat-cmds.c similarity index 97% rename from src/nvme-cmds-feature.c rename to plugins/cmds-feat/feat-cmds.c index 443849f111..c2e228d911 100644 --- a/src/nvme-cmds-feature.c +++ b/plugins/cmds-feat/feat-cmds.c @@ -51,10 +51,25 @@ #include "nvme-print.h" #include "plugin.h" +#include "feat-cmds.h" +#include "feat-print.h" + static const char *buf_len = "buffer len (if) data is sent or received"; static const char *namespace_desired = "desired namespace"; static const char *uuid_index_specify = "specify uuid index"; +struct feat_cfg { + __u8 feature_id; /* enum nvme_features_id */ + __u8 sel; /* enum nvme_get_features_sel */ + __u32 namespace_id; + __u32 cdw11; + __u32 cdw12; + __u8 uuid_index; + __u32 data_len; + bool raw_binary; + bool changed; +}; + static OPT_VALS(feature_name) = { VAL_BYTE("arbitration", NVME_FEAT_FID_ARBITRATION), VAL_BYTE("power-mgmt", NVME_FEAT_FID_POWER_MGMT), @@ -493,13 +508,8 @@ static struct command set_feature_cmd = { .fn = set_feature, }; -static struct command *commands[] = { +struct command *feat_builtin_commands[] = { &get_feature_cmd, &set_feature_cmd, NULL, }; - -static void __shr_constructor register_group(void) -{ - plugin_add_group(&builtin, "Features", commands); -} diff --git a/plugins/cmds-feat/feat-cmds.h b/plugins/cmds-feat/feat-cmds.h new file mode 100644 index 0000000000..e6ce85eb86 --- /dev/null +++ b/plugins/cmds-feat/feat-cmds.h @@ -0,0 +1,7 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#pragma once + +#include "plugin.h" + +/* get-feature and set-feature, the top-level commands of the plugin */ +extern struct command *feat_builtin_commands[]; diff --git a/plugins/feat/feat-nvme.c b/plugins/cmds-feat/feat-nvme.c similarity index 99% rename from plugins/feat/feat-nvme.c rename to plugins/cmds-feat/feat-nvme.c index 6dce46f3db..bfde6e0660 100644 --- a/plugins/feat/feat-nvme.c +++ b/plugins/cmds-feat/feat-nvme.c @@ -15,6 +15,9 @@ #include "nvme-print.h" #include "plugin.h" +#include "feat-cmds.h" +#include "feat-print.h" + #define FEAT_PLUGIN_VERSION "1.0" #define POWER_MGMT_DESC "Get and set power management feature" @@ -2035,5 +2038,6 @@ static struct plugin plugin = { NVME_PLUGIN_INIT(register_plugin) { plugin_add_group(&plugin, NULL, commands); + plugin_add_group(&builtin, "Features", feat_builtin_commands); register_extension(&plugin); } diff --git a/plugins/cmds-feat/feat-print-binary.c b/plugins/cmds-feat/feat-print-binary.c new file mode 100644 index 0000000000..d4a1713df5 --- /dev/null +++ b/plugins/cmds-feat/feat-print-binary.c @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include + +#include "feat-print.h" +#include "nvme-print.h" + +static void binary_feature_show(enum nvme_features_id fid, int sel, + unsigned int result, void *buf, __u32 data_len) +{ + if (buf) + d_raw(buf, data_len); +} + +static struct feat_print_ops feat_binary_print_ops = { + .show_feature = binary_feature_show, +}; + +struct feat_print_ops *feat_get_binary_print_ops(nvme_print_flags_t flags) +{ + feat_binary_print_ops.flags = flags; + return &feat_binary_print_ops; +} diff --git a/plugins/cmds-feat/feat-print-json.c b/plugins/cmds-feat/feat-print-json.c new file mode 100644 index 0000000000..9960a0bb0c --- /dev/null +++ b/plugins/cmds-feat/feat-print-json.c @@ -0,0 +1,1048 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "feat-print.h" +#include "nvme-print.h" +#include "nvme-print-json.h" + +#define VAL_LEN 4096 + +static void json_select_result(enum nvme_features_id fid, __u64 result) +{ + struct json_object *r = json_root(); + char json_str[STR_LEN]; + struct json_object *feature = json_create_array(); + + if (result & 0x1) + array_add_str(feature, "saveable"); + if (result & 0x2) + array_add_str(feature, "per-namespace"); + if (result & 0x4) + array_add_str(feature, "changeable"); + + sprintf(json_str, "Feature: %#0*x: select", fid ? 4 : 2, fid); + obj_add_array(r, json_str, feature); +} + +static void json_feature_show_fields_arbitration(struct json_object *r, + unsigned int result) +{ + char json_str[STR_LEN]; + + obj_add_uint(r, "High Priority Weight (HPW)", + ((result & 0xff000000) >> 24) + 1); + obj_add_uint(r, "Medium Priority Weight (MPW)", + ((result & 0xff0000) >> 16) + 1); + obj_add_uint(r, "Low Priority Weight (LPW)", + ((result & 0xff00) >> 8) + 1); + + if ((result & 7) == 7) + sprintf(json_str, "No limit"); + else + sprintf(json_str, "%u", 1 << (result & 7)); + + obj_add_str(r, "Arbitration Burst (AB)", json_str); +} + +static void json_feature_show_fields_power_mgmt(struct json_object *r, + unsigned int result) +{ + __u8 field = (result & 0xe0) >> 5; + + obj_add_uint(r, "Workload Hint (WH)", field); + obj_add_str(r, "WH description", + nvme_feature_wl_hints_to_string(field)); + obj_add_uint(r, "Power State (PS)", result & 0x1f); + obj_add_uint(r, "Idle I/O Exit Latency Limit (IIELL)", + NVME_FEAT_PM_IIELL(result)); +} + +static void json_lba_range_entry(struct nvme_lba_range_type *lbrt, + int nr_ranges, struct json_object *r) +{ + char json_str[STR_LEN]; + struct json_object *lbare; + int i; + struct json_object *lbara = json_create_array(); + + obj_add_array(r, "LBA Ranges", lbara); + + for (i = 0; i <= nr_ranges; i++) { + lbare = json_create_object(); + array_add_obj(lbara, lbare); + + obj_add_int(lbare, "LBA range", i); + + obj_add_uint_nx(lbare, "type", lbrt->entry[i].type); + + obj_add_str(lbare, "type description", + nvme_feature_lba_type_to_string(lbrt->entry[i].type)); + + obj_add_uint_nx(lbare, "attributes", lbrt->entry[i].attributes); + + obj_add_str(lbare, "attribute[0]", + lbrt->entry[i].attributes & 1 ? + "LBA range may be overwritten" : + "LBA range should not be overwritten"); + + obj_add_str(lbare, "attribute[1]", + lbrt->entry[i].attributes & 2 ? + "LBA range should be hidden from the OS/EFI/BIOS" : + "LBA range should be visible from the OS/EFI/BIOS"); + + obj_add_nprix64(lbare, "slba", + le64_to_cpu(lbrt->entry[i].slba)); + + obj_add_nprix64(lbare, "nlb", le64_to_cpu(lbrt->entry[i].nlb)); + + shr_bin_to_hex(json_str, sizeof(json_str), lbrt->entry[i].guid, + sizeof(lbrt->entry[i].guid), 0); + + obj_add_str(lbare, "guid", json_str); + } +} + +static void json_feature_show_fields_lba_range(struct json_object *r, + __u8 field, unsigned char *buf) +{ + obj_add_uint(r, "Number of LBA Ranges (NUM)", field + 1); + + if (buf) + json_lba_range_entry((struct nvme_lba_range_type *)buf, field, + r); +} + +static void json_feature_show_fields_temp_thresh(struct json_object *r, + unsigned int result) +{ + char json_str[STR_LEN]; + __u8 field; + + field = (result & 0x1c00000) >> 22; + sprintf(json_str, "%s", nvme_degrees_string(field)); + obj_add_str(r, "Temperature Threshold Hysteresis (TMPTHH)", json_str); + + sprintf(json_str, "%u K", field); + obj_add_str(r, "TMPTHH kelvin", json_str); + + field = (result & 0x300000) >> 20; + obj_add_uint(r, "Threshold Type Select (THSEL)", field); + obj_add_str(r, "THSEL description", + nvme_feature_temp_type_to_string(field)); + + field = (result & 0xf0000) >> 16; + + obj_add_uint(r, "Threshold Temperature Select (TMPSEL)", field); + obj_add_str(r, "TMPSEL description", + nvme_feature_temp_sel_to_string(field)); + + sprintf(json_str, "%s", nvme_degrees_string(result & 0xffff)); + obj_add_str(r, "Temperature Threshold (TMPTH)", json_str); + + sprintf(json_str, "%u K", result & 0xffff); + obj_add_str(r, "TMPTH kelvin", json_str); +} + +static void json_feature_show_fields_err_recovery(struct json_object *r, + unsigned int result) +{ + char json_str[STR_LEN]; + + obj_add_str(r, + "Deallocated or Unwritten Logical Block Error Enable (DULBE)", + (result & 0x10000) >> 16 ? "Enabled" : "Disabled"); + + sprintf(json_str, "%u ms", (result & 0xffff) * 100); + obj_add_str(r, "Time Limited Error Recovery (TLER)", json_str); +} + +static void json_feature_show_fields_volatile_wc(struct json_object *r, + unsigned int result) +{ + obj_add_str(r, "Volatile Write Cache Enable (WCE)", + result & 1 ? "Enabled" : "Disabled"); +} + +static void json_feature_show_fields_num_queues(struct json_object *r, + unsigned int result) +{ + obj_add_uint(r, "Number of IO Completion Queues Allocated (NCQA)", + ((result & 0xffff0000) >> 16) + 1); + obj_add_uint(r, "Number of IO Submission Queues Allocated (NSQA)", + (result & 0xffff) + 1); +} + +static void json_feature_show_fields_irq_coalesce(struct json_object *r, + unsigned int result) +{ + char json_str[STR_LEN]; + + sprintf(json_str, "%u usec", ((result & 0xff00) >> 8) * 100); + obj_add_str(r, "Aggregation Time (TIME)", json_str); + + obj_add_uint(r, "Aggregation Threshold (THR)", (result & 0xff) + 1); +} + +static void json_feature_show_fields_irq_config(struct json_object *r, + unsigned int result) +{ + obj_add_str(r, "Coalescing Disable (CD)", + (result & 0x10000) >> 16 ? "True" : "False"); + obj_add_uint(r, "Interrupt Vector (IV)", result & 0xffff); +} + +static void json_feature_show_fields_write_atomic(struct json_object *r, + unsigned int result) +{ + obj_add_str(r, "Disable Normal (DN)", result & 1 ? "True" : "False"); +} + +static void json_feature_show_fields_async_event(struct json_object *r, + unsigned int result) +{ + const char *async = "Send async event"; + const char *no_async = "Do not send async event"; + + obj_add_str(r, feat_ae_dlpcn, + NVME_FEAT_AE_DLPCN(result) ? async : no_async); + obj_add_str(r, feat_ae_hdlpcn, + NVME_FEAT_AE_HDLPCN(result) ? async : no_async); + obj_add_str(r, feat_ae_adlpcn, + NVME_FEAT_AE_ADLPCN(result) ? async : no_async); + obj_add_str(r, feat_ae_pmdrlpcn, + NVME_FEAT_AE_PMDRLPCN(result) ? async : no_async); + obj_add_str(r, feat_ae_zdcn, + NVME_FEAT_AE_ZDCN(result) ? async : no_async); + obj_add_str(r, feat_ae_tthry, + NVME_FEAT_AE_TTHRY(result) ? async : no_async); + obj_add_str(r, feat_ae_rlccn, + NVME_FEAT_AE_RLCCN(result) ? async : no_async); + obj_add_str(r, feat_ae_lhcn, + NVME_FEAT_AE_LHCN(result) ? async : no_async); + obj_add_str(r, feat_ae_ccrcn, + NVME_FEAT_AE_CCRCN(result) ? async : no_async); + obj_add_str(r, feat_ae_ansan, + NVME_FEAT_AE_ANSAN(result) ? async : no_async); + obj_add_str(r, feat_ae_rgrp0, + NVME_FEAT_AE_RGRP0(result) ? async : no_async); + obj_add_str(r, feat_ae_rassn, + NVME_FEAT_AE_RASSN(result) ? async : no_async); + obj_add_str(r, feat_ae_nnsshdn, + NVME_FEAT_AE_NNSSHDN(result) ? async : no_async); + obj_add_str(r, feat_ae_ega, + NVME_FEAT_AE_EGA(result) ? async : no_async); + obj_add_str(r, feat_ae_lbas, + NVME_FEAT_AE_LBAS(result) ? async : no_async); + obj_add_str(r, feat_ae_pla, + NVME_FEAT_AE_PLA(result) ? async : no_async); + obj_add_str(r, feat_ae_ana, + NVME_FEAT_AE_ANA(result) ? async : no_async); + obj_add_str(r, feat_ae_telem, + NVME_FEAT_AE_TELEM(result) ? async : no_async); + obj_add_str(r, feat_ae_fw, NVME_FEAT_AE_FW(result) ? async : no_async); + obj_add_str(r, feat_ae_nan, + NVME_FEAT_AE_NAN(result) ? async : no_async); + obj_add_str(r, feat_ae_smart, + NVME_FEAT_AE_SMART(result) ? async : no_async); +} + +static void json_auto_pst(struct nvme_feat_auto_pst *apst, + struct json_object *r) +{ + int i; + __u64 value; + char json_str[STR_LEN]; + struct json_object *apsta = json_create_array(); + struct json_object *apste; + + obj_add_array(r, "Auto PST Entries", apsta); + + for (i = 0; i < ARRAY_SIZE(apst->apst_entry); i++) { + apste = json_create_object(); + array_add_obj(apsta, apste); + sprintf(json_str, "%2d", i); + obj_add_str(apste, "entry", json_str); + value = le64_to_cpu(apst->apst_entry[i]); + sprintf(json_str, "%u ms", + (__u32)NVME_GET(value, APST_ENTRY_ITPT)); + obj_add_str(apste, "Idle Time Prior to Transition (ITPT)", + json_str); + obj_add_uint(apste, "Idle Transition Power State (ITPS)", + (__u32)NVME_GET(value, APST_ENTRY_ITPS)); + } +} + +static void json_feature_show_fields_auto_pst(struct json_object *r, + unsigned int result, + unsigned char *buf) +{ + obj_add_str(r, "Autonomous Power State Transition Enable (APSTE)", + result & 1 ? "Enabled" : "Disabled"); + + if (buf) + json_auto_pst((struct nvme_feat_auto_pst *)buf, r); +} + +static void json_host_mem_buffer(struct nvme_host_mem_buf_attrs *hmb, + struct json_object *r) +{ + char json_str[STR_LEN]; + + obj_add_uint(r, "Host Memory Descriptor List Entry Count (HMDLEC)", + le32_to_cpu(hmb->hmdlec)); + + sprintf(json_str, "0x%x", le32_to_cpu(hmb->hmdlau)); + obj_add_str(r, "Host Memory Descriptor List Address (HMDLAU)", + json_str); + + sprintf(json_str, "0x%x", le32_to_cpu(hmb->hmdlal)); + obj_add_str(r, "Host Memory Descriptor List Address (HMDLAL)", + json_str); + + obj_add_uint(r, "Host Memory Buffer Size (HSIZE)", + le32_to_cpu(hmb->hsize)); +} + +static void json_feature_show_fields_host_mem_buf(struct json_object *r, + unsigned int result, + unsigned char *buf) +{ + obj_add_str(r, "Enable Host Memory (EHM)", + result & 1 ? "Enabled" : "Disabled"); + obj_add_str(r, + "Host Memory Non-operational Access Restriction Enable (HMNARE)", + (result & 0x00000004) ? "True" : "False"); + obj_add_str(r, "Host Memory Non-operational Access Restricted (HMNAR)", + (result & 0x00000008) ? "True" : "False"); + + if (buf) + json_host_mem_buffer((struct nvme_host_mem_buf_attrs *)buf, r); +} + +static void json_feature_show_fields_timestamp(struct json_object *r, + unsigned char *buf) +{ + if (buf) + json_timestamp(r, (struct nvme_timestamp *)buf); +} + +static void json_feature_show_fields_kato(struct json_object *r, + unsigned int result) +{ + obj_add_uint(r, "Keep Alive Timeout (KATO) in milliseconds", result); +} + +static void json_feature_show_fields_hctm(struct json_object *r, + unsigned int result) +{ + char json_str[STR_LEN]; + + sprintf(json_str, "%u K", result >> 16); + obj_add_str(r, "Thermal Management Temperature 1 (TMT1)", json_str); + + sprintf(json_str, "%s", nvme_degrees_string(result >> 16)); + obj_add_str(r, "TMT1 celsius", json_str); + + sprintf(json_str, "%u K", result & 0xffff); + obj_add_str(r, "Thermal Management Temperature 2", json_str); + + sprintf(json_str, "%s", nvme_degrees_string(result & 0xffff)); + obj_add_str(r, "TMT2 celsius", json_str); +} + +static void json_feature_show_fields_nopsc(struct json_object *r, + unsigned int result) +{ + obj_add_str(r, + "Non-Operational Power State Permissive Mode Enable (NOPPME)", + result & 1 ? "True" : "False"); +} + +static void json_feature_show_fields_rrl(struct json_object *r, + unsigned int result) +{ + obj_add_uint(r, "Read Recovery Level (RRL)", result & 0xf); +} + +static void json_plm_config(struct nvme_plm_config *plmcfg, + struct json_object *r) +{ + char json_str[STR_LEN]; + + sprintf(json_str, "%04x", le16_to_cpu(plmcfg->ee)); + obj_add_str(r, "Enable Event", json_str); + + obj_add_uint64(r, "DTWIN Reads Threshold", + le64_to_cpu(plmcfg->dtwinrt)); + obj_add_uint64(r, "DTWIN Writes Threshold", + le64_to_cpu(plmcfg->dtwinwt)); + obj_add_uint64(r, "DTWIN Time Threshold", le64_to_cpu(plmcfg->dtwintt)); +} + +static void json_feature_show_fields_plm_config(struct json_object *r, + unsigned int result, + unsigned char *buf) +{ + obj_add_str(r, "Predictable Latency Window Enabled", + result & 1 ? "True" : "False"); + + if (buf) + json_plm_config((struct nvme_plm_config *)buf, r); +} + +static void json_feature_show_fields_plm_window(struct json_object *r, + unsigned int result) +{ + obj_add_str(r, "Window Select", nvme_plm_window_to_string(result)); +} + +static void json_feature_show_fields_lba_sts_interval(struct json_object *r, + unsigned int result) +{ + obj_add_uint(r, "LBA Status Information Poll Interval (LSIPI)", + result >> 16); + obj_add_uint(r, "LBA Status Information Report Interval (LSIRI)", + result & 0xffff); +} + +static void json_feature_show_fields_host_behavior(struct json_object *r, + unsigned char *buf) +{ + if (buf) { + struct nvme_feat_host_behavior *host = + (struct nvme_feat_host_behavior *)buf; + + obj_add_str(r, "Host Behavior Support", + buf[0] & 0x1 ? "True" : "False"); + obj_add_str(r, "Advanced Command Retry Enable (ACRE)", + host->acre ? "True" : "False"); + obj_add_str(r, + "Extended Telemetry Data Area 4 Supported (ETDAS)", + host->etdas ? "True" : "False"); + obj_add_str(r, "LBA Format Extension Enable (LBAFEE)", + host->lbafee ? "True" : "False"); + obj_add_str(r, "Host Dispersed Namespace Support (HDISNS)", + host->hdisns ? "Enabled" : "Disabled"); + obj_add_str(r, "Copy Descriptor Format 2h Enable (CDF2E)", + host->cdfe & (1 << 2) ? "True" : "False"); + obj_add_str(r, "Copy Descriptor Format 3h Enable (CDF3E)", + host->cdfe & (1 << 3) ? "True" : "False"); + obj_add_str(r, "Copy Descriptor Format 4h Enable (CDF4E)", + host->cdfe & (1 << 4) ? "True" : "False"); + } +} + +static void json_feature_show_fields_sanitize(struct json_object *r, + unsigned int result) +{ + obj_add_uint(r, "No-Deallocate Response Mode (NODRM)", result & 1); +} + +static void json_feature_show_fields_endurance_evt_cfg(struct json_object *r, + unsigned int result) +{ + obj_add_uint(r, "Endurance Group Identifier (ENDGID)", result & 0xffff); + obj_add_uint(r, "Endurance Group Critical Warnings", + result >> 16 & 0xff); +} + +static void json_feature_show_fields_iocs_profile(struct json_object *r, + unsigned int result) +{ + obj_add_str(r, "I/O Command Set Profile", + result & 0x1 ? "True" : "False"); +} + +static void json_feature_show_fields_spinup_control(struct json_object *r, + unsigned int result) +{ + obj_add_str(r, "Spinup control feature Enabled", + result & 1 ? "True" : "False"); +} + +static void json_feature_show_fields_power_loss_signal(struct json_object *r, + unsigned int result) +{ + obj_add_str(r, "Power Loss Signaling Mode (PLSM)", + nvme_pls_mode_to_string(NVME_GET(result, FEAT_PLS_MODE))); +} + +static void json_feat_perfc_std(struct json_object *r, + struct nvme_std_perf_attr *data) +{ + obj_add_str(r, "random 4 kib average read latency", + nvme_feature_perfc_r4karl_to_string(data->r4karl)); + obj_add_uint_02x(r, "R4KARL", data->r4karl); +} + +static void json_feat_perfc_id_list(struct json_object *r, + struct nvme_perf_attr_id_list *data) +{ + int i; + int attri_vs; + char json_str[STR_LEN]; + struct json_object *paida = json_create_array(); + struct json_object *paide; + + obj_add_str(r, "attribute type", + nvme_feature_perfc_attrtyp_to_string(data->attrtyp)); + obj_add_uint_02x(r, "ATTRTYP", data->attrtyp); + obj_add_int(r, + "maximum saveable vendor specific performance attributes (MSVSPA)", + data->msvspa); + obj_add_int(r, + "unused saveable vendor specific performance attributes (USVSPA)", + data->usvspa); + + obj_add_array(r, "performance attribute identifier list", paida); + for (i = 0; i < ARRAY_SIZE(data->id_list); i++) { + paide = json_create_object(); + array_add_obj(paida, paide); + attri_vs = i + NVME_FEAT_PERFC_ATTRI_VS_MIN; + sprintf(json_str, + "performance attribute %02xh identifier (PA%02XHI)", + attri_vs, attri_vs); + obj_add_str(paide, json_str, + shr_uuid_to_string(data->id_list[i].id)); + } +} + +static void json_feat_perfc_vs(struct json_object *r, + struct nvme_vs_perf_attr *data) +{ + __u16 attrl = le16_to_cpu(data->attrl); + + obj_add_str(r, "performance attribute identifier (PAID)", + shr_uuid_to_string(data->paid)); + obj_add_uint(r, "attribute length (ATTRL)", attrl); + obj_d(r, "vendor specific (VS)", (unsigned char *)data->vs, + min_t(size_t, attrl, sizeof(data->vs)), 16, 1); +} + +static void json_feat_perfc(struct json_object *r, enum nvme_features_id fid, + unsigned int result, + struct nvme_perf_characteristics *data) +{ + __u8 attri; + bool rvspa; + + nvme_feature_decode_perf_characteristics(result, &attri, &rvspa); + + obj_add_str(r, "attribute index", + nvme_feature_perfc_attri_to_string(attri)); + obj_add_uint_02x(r, "ATTRI", attri); + + switch (attri) { + case NVME_FEAT_PERFC_ATTRI_STD: + json_feat_perfc_std(r, data->std_perf); + break; + case NVME_FEAT_PERFC_ATTRI_ID_LIST: + json_feat_perfc_id_list(r, data->id_list); + break; + case NVME_FEAT_PERFC_ATTRI_VS_MIN ... NVME_FEAT_PERFC_ATTRI_VS_MAX: + json_feat_perfc_vs(r, data->vs_perf); + break; + default: + break; + } +} + +static void json_host_metadata(struct json_object *r, enum nvme_features_id fid, + struct nvme_host_metadata *data) +{ + struct nvme_metadata_element_desc desc; + const __u8 *v; + size_t off = 0; + int i; + char val[VAL_LEN]; + __u16 len; + char json_str[STR_LEN]; + struct json_object *desca = json_create_array(); + struct json_object *desce; + + obj_add_int(r, "Num Metadata Element Descriptors", data->ndesc); + + obj_add_array(r, "Metadata Element Descriptors", desca); + + for (i = 0; i < data->ndesc; i++) { + v = nvme_host_metadata_element(data, &off, &desc, &len); + if (!v) + break; + + desce = json_create_object(); + array_add_obj(desca, desce); + + obj_add_int(desce, "Element", i); + + snprintf(json_str, sizeof(json_str), "0x%02x", desc.type); + obj_add_str(desce, "Type", json_str); + + obj_add_str(desce, "Type definition", + nvme_host_metadata_type_to_string(fid, desc.type)); + + obj_add_int(desce, "Revision", desc.rev); + + obj_add_int(desce, "Length", le16_to_cpu(desc.len)); + + snprintf(val, sizeof(val), "%.*s", len, (const char *)v); + obj_add_str(desce, "Value", val); + } +} + +static void json_feature_show_fields_ns_metadata(struct json_object *r, + enum nvme_features_id fid, + unsigned char *buf) +{ + if (buf) + json_host_metadata(r, fid, (struct nvme_host_metadata *)buf); +} + +static void json_feature_show_fields_sw_progress(struct json_object *r, + unsigned int result) +{ + obj_add_uint(r, "Pre-boot Software Load Count (PBSLC)", result & 0xff); +} + +static void json_feature_show_fields_host_id(struct json_object *r, + unsigned int result, unsigned char *hostid) +{ + bool exhid; + + if (!hostid) + return; + + nvme_feature_decode_host_id(result, &exhid); + + if (exhid) + obj_add_str(r, "Host Identifier (HOSTID)", + uint128_t_to_l10n_string(le128_to_cpu(hostid))); + else + obj_add_uint64(r, "Host Identifier (HOSTID)", + le64_to_cpu(*(__le64 *)hostid)); +} + +static void json_feature_show_fields_resv_nf_mask(struct json_object *r, + unsigned int result) +{ + obj_add_str(r, "Mask Reservation Preempted Notification (RESPRE)", + (result & 8) >> 3 ? "True" : "False"); + obj_add_str(r, "Mask Reservation Released Notification (RESREL)", + (result & 4) >> 2 ? "True" : "False"); + obj_add_str(r, "Mask Registration Preempted Notification (REGPRE)", + (result & 2) >> 1 ? "True" : "False"); +} + +static void json_feature_show_fields_resv_persist(struct json_object *r, + unsigned int result) +{ + obj_add_str(r, "Persist Through Power Loss (PTPL)", + result & 1 ? "True" : "False"); +} + +static void json_feature_show_fields_write_protect(struct json_object *r, + unsigned int result) +{ + obj_add_str(r, "Namespace Write Protect", + nvme_ns_wp_cfg_to_string(result)); +} + +static void json_feature_show_fields_fdp(struct json_object *r, + unsigned int result) +{ + obj_add_str(r, "Flexible Direct Placement Enable (FDPE)", + result & 1 ? "Yes" : "No"); + obj_add_uint(r, "Flexible Direct Placement Configuration Index", + result >> 8 & 0xf); +} + +static void json_feature_show_fields_fdp_events(struct json_object *r, + unsigned int result, + unsigned char *buf) +{ + unsigned int i; + struct nvme_fdp_supported_event_desc *d; + char json_str[STR_LEN]; + + // NOET is in bits 7:0; bits 31:8 are reserved. + for (i = 0; i < (result & 0xff); i++) { + d = &((struct nvme_fdp_supported_event_desc *)buf)[i]; + sprintf(json_str, "%s", + d->evta & 0x1 ? "Enabled" : "Not enabled"); + obj_add_str(r, nvme_fdp_event_to_string(d->evt), json_str); + } +} + +static void json_feature_show_fields_bpwp(struct json_object *r, + unsigned int result) +{ + __u8 field; + + field = NVME_FEAT_BPWPC_BP0WPS(result); + obj_add_str(r, "Boot Partition 0 Write Protection State", + nvme_bpwps_to_string(field)); + field = NVME_FEAT_BPWPC_BP1WPS(result); + obj_add_str(r, "Boot Partition 1 Write Protection State", + nvme_bpwps_to_string(field)); +} + +static char *get_power_and_scale(__u16 power, __u8 scale) +{ + char *str; + int ret; + + switch (scale) { + case NVME_PSD_PS_NOT_REPORTED: + /* Not reported for this power state */ + ret = asprintf(&str, "-"); + break; + case NVME_PSD_PS_100_MICRO_WATT: + /* Units of 0.0001W */ + ret = asprintf(&str, "%01u.%04uW", power / 10000, + power % 10000); + break; + case NVME_PSD_PS_10_MILLI_WATT: + /* Units of 0.01W */ + ret = asprintf(&str, "%01u.%02uW", power / 100, power % 100); + break; + default: + ret = asprintf(&str, "reserved"); + break; + } + + if (ret > 0) + return str; + + return NULL; +} + +static void json_feature_show_fields_power_limit(struct json_object *r, + unsigned int result) +{ + __u8 field = NVME_FEAT_POWER_LIMIT_PLS(result); + + __cleanup_free char *k = + get_power_and_scale(NVME_FEAT_POWER_LIMIT_PLV(result), field); + + obj_add_str(r, "Power Limit Scale (PLS)", + nvme_feature_power_limit_scale_to_string(field)); + obj_add_uint(r, "Power Limit Value (PLV)", + NVME_FEAT_POWER_LIMIT_PLV(result)); + obj_add_str(r, "Power Limit", k); +} + +static void json_feature_show_fields_power_thresh(struct json_object *r, + unsigned int result) +{ + __u8 field; + __u16 ptv; + __cleanup_free char *k = NULL; + + field = NVME_FEAT_POWER_THRESH_EPT(result); + + obj_add_str(r, "Enable Power Threshold (EPT)", + field ? "Enabled" : "Disabled"); + + field = NVME_FEAT_POWER_THRESH_PMTS(result); + obj_add_str(r, "Power Measurement Type Select (PMTS)", + nvme_power_measurement_type_to_string(field)); + + field = NVME_FEAT_POWER_THRESH_PTS(result); + obj_add_str(r, "Power Threshold Scale (PTS)", + nvme_feature_power_limit_scale_to_string(field)); + + ptv = NVME_FEAT_POWER_THRESH_PTV(result); + + obj_add_uint(r, "Power Threshold Value (PTV)", ptv); + + k = get_power_and_scale(ptv, NVME_FEAT_POWER_THRESH_PTS(result)); + obj_add_str(r, "Power Threshold", k); +} + +static void json_feature_show_fields_power_meas(struct json_object *r, + unsigned int result) +{ + __u8 field; + __u16 smt; + + field = NVME_FEAT_POWER_MEAS_ACT(result); + obj_add_str(r, "Action (ACT)", + nvme_power_measurement_action_to_string(field)); + + field = NVME_FEAT_POWER_MEAS_PMTS(result); + obj_add_str(r, "Power Measurement Type Select (PMTS)", + nvme_power_measurement_type_to_string(field)); + + smt = NVME_FEAT_POWER_MEAS_SMT(result); + + obj_add_uint(r, "Stop Measurement Time (SMT)", smt); +} + +static void json_feature_show_fields_voltage_threshold(struct json_object *r, + unsigned int result) +{ + obj_add_uint(r, "Voltage Sensor Select (VSENS)", + NVME_FEAT_VOLTAGE_THRESHOLD_VSENS(result)); + obj_add_str(r, "Enable Voltage Threshold (EVT)", + result & NVME_FEAT_VOLTAGE_THRESHOLD_EVT ? + "Enabled" : "Disabled"); + obj_add_uint(r, "Overvoltage Threshold (OVT)", + NVME_FEAT_VOLTAGE_THRESHOLD_OVT(result)); + obj_add_uint(r, "Undervoltage Threshold (UVT)", + NVME_FEAT_VOLTAGE_THRESHOLD_UVT(result)); +} + +static void json_feature_show_fields_voltage_measurement(struct json_object *r, + unsigned int result) +{ + obj_add_uint(r, "Action (ACT)", + NVME_FEAT_VOLTAGE_MEASUREMENT_ACT(result)); +} + +static void json_rate_limiting_data(struct json_object *r, + struct nvme_rate_limiting_data *rld) +{ + __u16 rlc = le16_to_cpu(rld->rlc); + __u16 rlm = NVME_RATE_LIMITING_RLC_RLM(rlc); + + obj_add_str(r, "Rate Limiting Enable (RLE)", + NVME_RATE_LIMITING_RLC_RLE(rlc) ? "Enabled" : "Disabled"); + obj_add_uint(r, "Rate Limiting Mode (RLM)", rlm); + obj_add_str(r, "RLM description", + rlm == NVME_RATE_LIMITING_MODE_SOFT_LIMIT ? "Soft Limit" : + rlm == NVME_RATE_LIMITING_MODE_HARD_LIMIT ? + "Hard Limit" : "Reserved"); + obj_add_uint(r, "Bandwidth Scale Factor (BWSF)", rld->bwsf); + obj_add_uint64(r, "Total Bandwidth Value (TBWV)", + le64_to_cpu(rld->tbwv)); + obj_add_uint64(r, "Write Bandwidth Value (WBWV)", + le64_to_cpu(rld->wbwv)); + obj_add_uint(r, "Total IOPS (TIOPS)", le32_to_cpu(rld->tiops)); + obj_add_uint(r, "Write IOPS (WIOPS)", le32_to_cpu(rld->wiops)); + obj_add_uint(r, "Read IOPS Ratio (RIOPSR)", rld->riopsr); + obj_add_uint(r, "Write IOPS Ratio (WIOPSR)", rld->wiopsr); + obj_add_uint(r, "Read Bandwidth Ratio (RBWR)", rld->rbwr); + obj_add_uint(r, "Write Bandwidth Ratio (WBWR)", rld->wbwr); +} + +static void json_feature_show_fields_rate_limiting(struct json_object *r, + unsigned char *buf) +{ + if (buf) + json_rate_limiting_data(r, + (struct nvme_rate_limiting_data *)buf); +} + +static void json_feature_show(enum nvme_features_id fid, int sel, + unsigned int result, void *buf, __u32 data_len) +{ + struct json_object *r; + char json_str[STR_LEN]; + + sprintf(json_str, "feature: %#0*x", fid ? 4 : 2, fid); + r = obj_create(json_str); + + obj_add_str(r, "name", nvme_feature_to_string(fid)); + + sprintf(json_str, "%#0*x", result ? 10 : 8, result); + obj_add_str(r, nvme_select_to_string(sel), json_str); + + obj_print(r); + + if (NVME_CHECK(sel, GET_FEATURES_SEL, SUPPORTED)) + json_select_result(fid, result); + else + json_feature_show_fields(fid, result, buf); +} + +void json_feature_show_fields(enum nvme_features_id fid, unsigned int result, + unsigned char *buf) +{ + struct json_object *r; + char json_str[STR_LEN]; + + sprintf(json_str, "Feature: %#0*x", fid ? 4 : 2, fid); + r = obj_create(json_str); + + switch (fid) { + case NVME_FEAT_FID_ARBITRATION: + json_feature_show_fields_arbitration(r, result); + break; + case NVME_FEAT_FID_POWER_MGMT: + json_feature_show_fields_power_mgmt(r, result); + break; + case NVME_FEAT_FID_LBA_RANGE: + json_feature_show_fields_lba_range(r, result & 0x3f, buf); + break; + case NVME_FEAT_FID_TEMP_THRESH: + json_feature_show_fields_temp_thresh(r, result); + break; + case NVME_FEAT_FID_ERR_RECOVERY: + json_feature_show_fields_err_recovery(r, result); + break; + case NVME_FEAT_FID_VOLATILE_WC: + json_feature_show_fields_volatile_wc(r, result); + break; + case NVME_FEAT_FID_NUM_QUEUES: + json_feature_show_fields_num_queues(r, result); + break; + case NVME_FEAT_FID_IRQ_COALESCE: + json_feature_show_fields_irq_coalesce(r, result); + break; + case NVME_FEAT_FID_IRQ_CONFIG: + json_feature_show_fields_irq_config(r, result); + break; + case NVME_FEAT_FID_WRITE_ATOMIC: + json_feature_show_fields_write_atomic(r, result); + break; + case NVME_FEAT_FID_ASYNC_EVENT: + json_feature_show_fields_async_event(r, result); + break; + case NVME_FEAT_FID_AUTO_PST: + json_feature_show_fields_auto_pst(r, result, buf); + break; + case NVME_FEAT_FID_HOST_MEM_BUF: + json_feature_show_fields_host_mem_buf(r, result, buf); + break; + case NVME_FEAT_FID_TIMESTAMP: + json_feature_show_fields_timestamp(r, buf); + break; + case NVME_FEAT_FID_KATO: + json_feature_show_fields_kato(r, result); + break; + case NVME_FEAT_FID_HCTM: + json_feature_show_fields_hctm(r, result); + break; + case NVME_FEAT_FID_NOPSC: + json_feature_show_fields_nopsc(r, result); + break; + case NVME_FEAT_FID_RRL: + json_feature_show_fields_rrl(r, result); + break; + case NVME_FEAT_FID_PLM_CONFIG: + json_feature_show_fields_plm_config(r, result, buf); + break; + case NVME_FEAT_FID_PLM_WINDOW: + json_feature_show_fields_plm_window(r, result); + break; + case NVME_FEAT_FID_LBA_STS_INTERVAL: + json_feature_show_fields_lba_sts_interval(r, result); + break; + case NVME_FEAT_FID_HOST_BEHAVIOR: + json_feature_show_fields_host_behavior(r, buf); + break; + case NVME_FEAT_FID_SANITIZE: + json_feature_show_fields_sanitize(r, result); + break; + case NVME_FEAT_FID_ENDURANCE_EVT_CFG: + json_feature_show_fields_endurance_evt_cfg(r, result); + break; + case NVME_FEAT_FID_IOCS_PROFILE: + json_feature_show_fields_iocs_profile(r, result); + break; + case NVME_FEAT_FID_SPINUP_CONTROL: + json_feature_show_fields_spinup_control(r, result); + break; + case NVME_FEAT_FID_POWER_LOSS_SIGNAL: + json_feature_show_fields_power_loss_signal(r, result); + break; + case NVME_FEAT_FID_PERF_CHARACTERISTICS: + json_feat_perfc(r, fid, result, + (struct nvme_perf_characteristics *)buf); + break; + case NVME_FEAT_FID_ENH_CTRL_METADATA: + case NVME_FEAT_FID_CTRL_METADATA: + case NVME_FEAT_FID_NS_METADATA: + json_feature_show_fields_ns_metadata(r, fid, buf); + break; + case NVME_FEAT_FID_SW_PROGRESS: + json_feature_show_fields_sw_progress(r, result); + break; + case NVME_FEAT_FID_HOST_ID: + json_feature_show_fields_host_id(r, result, buf); + break; + case NVME_FEAT_FID_RESV_NF_MASK: + json_feature_show_fields_resv_nf_mask(r, result); + break; + case NVME_FEAT_FID_RESV_PERSIST: + json_feature_show_fields_resv_persist(r, result); + break; + case NVME_FEAT_FID_WRITE_PROTECT: + json_feature_show_fields_write_protect(r, result); + break; + case NVME_FEAT_FID_FDP: + json_feature_show_fields_fdp(r, result); + break; + case NVME_FEAT_FID_FDP_EVENTS: + json_feature_show_fields_fdp_events(r, result, buf); + break; + case NVME_FEAT_FID_BP_WRITE_PROTECT: + json_feature_show_fields_bpwp(r, result); + break; + case NVME_FEAT_FID_POWER_LIMIT: + json_feature_show_fields_power_limit(r, result); + break; + case NVME_FEAT_FID_POWER_THRESH: + json_feature_show_fields_power_thresh(r, result); + break; + case NVME_FEAT_FID_POWER_MEASUREMENT: + json_feature_show_fields_power_meas(r, result); + break; + case NVME_FEAT_FID_VOLTAGE_THRESHOLD: + json_feature_show_fields_voltage_threshold(r, result); + break; + case NVME_FEAT_FID_VOLTAGE_MEASUREMENT: + json_feature_show_fields_voltage_measurement(r, result); + break; + case NVME_FEAT_FID_RATE_LIMITING: + json_feature_show_fields_rate_limiting(r, buf); + break; + default: + break; + } + + obj_print(r); +} + +static void json_lba_range(struct nvme_lba_range_type *lbrt, int nr_ranges) +{ + struct json_object *r = json_root(); + + json_lba_range_entry(lbrt, nr_ranges, r); +} + +static void json_lba_status_info(__u64 result) +{ + struct json_object *r = json_root(); + + obj_add_uint(r, "LBA Status Information Poll Interval (LSIPI)", + (result >> 16) & 0xffff); + obj_add_uint(r, "LBA Status Information Report Interval (LSIRI)", + result & 0xffff); +} + +static struct feat_print_ops feat_json_print_ops = { + .select_result = json_select_result, + .show_feature = json_feature_show, + .show_feature_fields = json_feature_show_fields, + .lba_range = json_lba_range, + .lba_status_info = json_lba_status_info, +}; + +struct feat_print_ops *feat_get_json_print_ops(nvme_print_flags_t flags) +{ + feat_json_print_ops.flags = flags; + return &feat_json_print_ops; +} diff --git a/plugins/cmds-feat/feat-print-stdout.c b/plugins/cmds-feat/feat-print-stdout.c new file mode 100644 index 0000000000..6ebdaa099b --- /dev/null +++ b/plugins/cmds-feat/feat-print-stdout.c @@ -0,0 +1,1066 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "feat-print.h" +#include "nvme-print.h" +#include "nvme-print-stdout.h" + +static void stdout_select_result(enum nvme_features_id fid, __u64 result) +{ + struct shr_table *t; + + t = stdout_kv_table_create(); + if (!t) + return; + + if (result & 0x1) + stdout_kv_add(t, "", "Feature is saveable"); + if (result & 0x2) + stdout_kv_add(t, "", "Feature is per-namespace"); + if (result & 0x4) + stdout_kv_add(t, "", "Feature is changeable"); + + stdout_kv_table_finish(t, "select-result"); +} + +static void stdout_lba_range(struct nvme_lba_range_type *lbrt, int nr_ranges) +{ + int i; + + for (i = 0; i <= nr_ranges; i++) { + struct nvme_lba_range_type_entry *e = &lbrt->entry[i]; + struct shr_table *t; + char guid[2 * ARRAY_SIZE(e->guid) + 1]; + + t = stdout_kv_table_create(); + if (!t) + return; + + shr_table_set_indent(t, 1); + + stdout_kv_add(t, "type", "%#x - %s", e->type, + nvme_feature_lba_type_to_string(e->type)); + const char *overwrite_str = + NVME_LBART_ATTRB_LBARO(e->attributes) ? + "LBA range may be overwritten" : + "LBA range should not be overwritten"; + const char *hidden_str = NVME_LBART_ATTRB_HLBAR(e->attributes) ? + "LBA range should be hidden from the OS/EFI/BIOS" : + "LBA range should be visible from the OS/EFI/BIOS"; + + stdout_kv_add(t, "attributes", "%#x - %s, %s", e->attributes, + overwrite_str, hidden_str); + stdout_kv_add(t, "slba", "%#"PRIx64, le64_to_cpu(e->slba)); + stdout_kv_add(t, "nlb", "%#"PRIx64, le64_to_cpu(e->nlb)); + + shr_bin_to_hex(guid, sizeof(guid), e->guid, sizeof(e->guid), 0); + stdout_kv_add(t, "guid", "%s", guid); + + stdout_kv_table_finish(t, "lba-range"); + } +} + +static void stdout_auto_pst(struct nvme_feat_auto_pst *apst) +{ + int i; + __u64 value; + + printf("\tAuto PST Entries"); + printf("\t.................\n"); + for (i = 0; i < ARRAY_SIZE(apst->apst_entry); i++) { + struct shr_table *t; + + value = le64_to_cpu(apst->apst_entry[i]); + + printf("\tEntry[%2d]\n", i); + printf("\t.................\n"); + + t = stdout_kv_table_create(); + if (!t) + return; + + shr_table_set_indent(t, 2); + stdout_kv_add(t, "Idle Time Prior to Transition (ITPT)", + "%u ms", + (__u32)NVME_GET(value, APST_ENTRY_ITPT)); + stdout_kv_add(t, "Idle Transition Power State (ITPS)", "%u", + (__u32)NVME_GET(value, APST_ENTRY_ITPS)); + + stdout_kv_table_finish(t, "auto-pst"); + + printf("\t.................\n"); + } +} + +static struct shr_table *stdout_timestamp_attr_table(__u8 attr) +{ + struct shr_table *t; + __u8 to = NVME_TIMESTAMP_ATTR_TO(attr); + __u8 sync = NVME_TIMESTAMP_ATTR_SYNC(attr); + + t = stdout_bits_table_create(); + if (!t) + return NULL; + + stdout_bits_add(t, "[3:1]", to, "%s", + nvme_format_timestamp_origin(attr)); + stdout_bits_add(t, "[0:0]", sync, "%s", + nvme_format_timestamp_sync(attr)); + + return t; +} + +static void stdout_timestamp(struct nvme_timestamp *ts) +{ + struct shr_table *t; + int row; + + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, "Timestamp", "%s", + stdout_format_timestamp(ts->timestamp)); + + row = stdout_kv_add(t, "Attributes", "%#x", ts->attr); + shr_table_set_row_subtable(t, row, + stdout_timestamp_attr_table(ts->attr)); + + stdout_kv_table_finish(t, "timestamp"); +} + +static void stdout_host_mem_buffer(struct nvme_host_mem_buf_attrs *hmb) +{ + struct shr_table *t; + + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, "Host Memory Descriptor List Entry Count (HMDLEC)", + "%u", le32_to_cpu(hmb->hmdlec)); + stdout_kv_add(t, "Host Memory Descriptor List Address (HMDLAU)", + "%#x", le32_to_cpu(hmb->hmdlau)); + stdout_kv_add(t, "Host Memory Descriptor List Address (HMDLAL)", + "%#x", le32_to_cpu(hmb->hmdlal)); + stdout_kv_add(t, "Host Memory Buffer Size (HSIZE)", "%u", + le32_to_cpu(hmb->hsize)); + + stdout_kv_table_finish(t, "host-mem-buffer"); +} + +static void stdout_lba_status_info(__u64 result) +{ + struct shr_table *t; + + t = stdout_kv_table_create(); + if (!t) + return; + + shr_table_set_indent(t, 1); + + stdout_kv_add(t, "LBA Status Information Poll Interval (LSIPI)", + "%u", (__u32)NVME_FEAT_LBAS_LSIPI(result)); + stdout_kv_add(t, "LBA Status Information Report Interval (LSIRI)", + "%u", (__u32)NVME_FEAT_LBAS_LSIRI(result)); + + stdout_kv_table_finish(t, "lba-status-info"); +} + +static void stdout_plm_config(struct nvme_plm_config *plmcfg) +{ + struct shr_table *t; + + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, "Enable Event", "%04x", le16_to_cpu(plmcfg->ee)); + stdout_kv_add(t, "DTWIN Reads Threshold", "%"PRIu64, + le64_to_cpu(plmcfg->dtwinrt)); + stdout_kv_add(t, "DTWIN Writes Threshold", "%"PRIu64, + le64_to_cpu(plmcfg->dtwinwt)); + stdout_kv_add(t, "DTWIN Time Threshold", "%"PRIu64, + le64_to_cpu(plmcfg->dtwintt)); + + stdout_kv_table_finish(t, "plm-config"); +} + +static void stdout_rate_limiting_data(struct nvme_rate_limiting_data *rld) +{ + __u16 rlc = le16_to_cpu(rld->rlc); + __u16 rlm = NVME_RATE_LIMITING_RLC_RLM(rlc); + struct shr_table *t; + + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, "Rate Limiting Enable (RLE)", "%s", + NVME_RATE_LIMITING_RLC_RLE(rlc) ? "Enabled" : "Disabled"); + stdout_kv_add(t, "Rate Limiting Mode (RLM)", "%u - %s", rlm, + rlm == NVME_RATE_LIMITING_MODE_SOFT_LIMIT ? "Soft Limit" : + rlm == NVME_RATE_LIMITING_MODE_HARD_LIMIT ? + "Hard Limit" : "Reserved"); + stdout_kv_add(t, "Bandwidth Scale Factor (BWSF)", "%u", rld->bwsf); + stdout_kv_add(t, "Total Bandwidth Value (TBWV)", "%"PRIu64, + le64_to_cpu(rld->tbwv)); + stdout_kv_add(t, "Write Bandwidth Value (WBWV)", "%"PRIu64, + le64_to_cpu(rld->wbwv)); + stdout_kv_add(t, "Total IOPS (TIOPS)", "%u", le32_to_cpu(rld->tiops)); + stdout_kv_add(t, "Write IOPS (WIOPS)", "%u", le32_to_cpu(rld->wiops)); + stdout_kv_add(t, "Read IOPS Ratio (RIOPSR)", "%u", rld->riopsr); + stdout_kv_add(t, "Write IOPS Ratio (WIOPSR)", "%u", rld->wiopsr); + stdout_kv_add(t, "Read Bandwidth Ratio (RBWR)", "%u", rld->rbwr); + stdout_kv_add(t, "Write Bandwidth Ratio (WBWR)", "%u", rld->wbwr); + + stdout_kv_table_finish(t, "rate-limiting-data"); +} + +static void stdout_feat_perfc_std(struct nvme_std_perf_attr *data) +{ + struct shr_table *t; + + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, "random 4 kib average read latency (R4KARL)", + "%s (0x%02x)", + nvme_feature_perfc_r4karl_to_string(data->r4karl), + data->r4karl); + + stdout_kv_table_finish(t, "feat-perfc-std"); +} + +static void stdout_feat_perfc_id_list(struct nvme_perf_attr_id_list *data) +{ + int i; + int attri_vs; + struct shr_table *t; + + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, "attribute type (ATTRTYP)", "%s (0x%02x)", + nvme_feature_perfc_attrtyp_to_string(data->attrtyp), + data->attrtyp); + stdout_kv_add(t, + "maximum saveable vendor specific performance attributes (MSVSPA)", + "%d", data->msvspa); + stdout_kv_add(t, + "unused saveable vendor specific performance attributes (USVSPA)", + "%d", data->usvspa); + + stdout_kv_table_finish(t, "feat-perfc-id-list"); + + printf("performance attribute identifier list\n"); + + t = stdout_kv_table_create(); + if (!t) + return; + + for (i = 0; i < ARRAY_SIZE(data->id_list); i++) { + char name[48]; + + attri_vs = i + NVME_FEAT_PERFC_ATTRI_VS_MIN; + snprintf(name, sizeof(name), + "performance attribute %02xh identifier (PA%02XHI)", + attri_vs, attri_vs); + stdout_kv_add(t, name, "%s", + shr_uuid_to_string(data->id_list[i].id)); + } + + stdout_kv_table_finish(t, "feat-perfc-id-list"); +} + +static void stdout_feat_perfc_vs(struct nvme_vs_perf_attr *data) +{ + __u16 attrl = le16_to_cpu(data->attrl); + struct shr_table *t; + + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, "performance attribute identifier (PAID)", "%s", + shr_uuid_to_string(data->paid)); + stdout_kv_add(t, "attribute length (ATTRL)", "%u", attrl); + + stdout_kv_table_finish(t, "feat-perfc-vs"); + + printf("vendor specific (VS):\n"); + d((unsigned char *)data->vs, + min_t(size_t, attrl, sizeof(data->vs)), 16, 1); +} + +static void stdout_feat_perfc(unsigned int result, + struct nvme_perf_characteristics *data) +{ + __u8 attri; + bool rvspa; + struct shr_table *t; + + nvme_feature_decode_perf_characteristics(result, &attri, &rvspa); + + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, "attribute index (ATTRI)", "%s (0x%02x)", + nvme_feature_perfc_attri_to_string(attri), attri); + + stdout_kv_table_finish(t, "feat-perfc"); + + switch (attri) { + case NVME_FEAT_PERFC_ATTRI_STD: + stdout_feat_perfc_std(data->std_perf); + break; + case NVME_FEAT_PERFC_ATTRI_ID_LIST: + stdout_feat_perfc_id_list(data->id_list); + break; + case NVME_FEAT_PERFC_ATTRI_VS_MIN ... NVME_FEAT_PERFC_ATTRI_VS_MAX: + stdout_feat_perfc_vs(data->vs_perf); + break; + default: + break; + } +} + +static void stdout_host_metadata(enum nvme_features_id fid, + struct nvme_host_metadata *data) +{ + struct nvme_metadata_element_desc desc; + const __u8 *val; + size_t off = 0; + int i; + __u16 len; + struct shr_table *t; + + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, "Num Metadata Element Descriptors", "%d", data->ndesc); + + stdout_kv_table_finish(t, "host-metadata"); + + for (i = 0; i < data->ndesc; i++) { + val = nvme_host_metadata_element(data, &off, &desc, &len); + if (!val) + break; + + printf("\tElement[%-3d]:\n", i); + + t = stdout_kv_table_create(); + if (!t) + return; + + shr_table_set_indent(t, 2); + stdout_kv_add(t, "Type", "%#02x (%s)", desc.type, + nvme_host_metadata_type_to_string(fid, + desc.type)); + stdout_kv_add(t, "Revision", "%d", desc.rev); + stdout_kv_add(t, "Length", "%d", le16_to_cpu(desc.len)); + stdout_kv_add(t, "Value", "%.*s", len, (const char *)val); + + stdout_kv_table_finish(t, "host-metadata"); + } +} + +static void stdout_feat_host_id(unsigned int result, unsigned char *hostid) +{ + bool exhid; + struct shr_table *t; + + if (!hostid) + return; + + nvme_feature_decode_host_id(result, &exhid); + + t = stdout_kv_table_create(); + if (!t) + return; + + if (exhid) + stdout_kv_add(t, "Host Identifier (HOSTID)", "%s", + uint128_t_to_l10n_string(le128_to_cpu(hostid))); + else + stdout_kv_add(t, "Host Identifier (HOSTID)", "%"PRIu64, + le64_to_cpu(*(__le64 *)hostid)); + + stdout_kv_table_finish(t, "feat-host-id"); +} + +static void stdout_feature_show(enum nvme_features_id fid, int sel, + unsigned int result, void *buf, __u32 data_len) +{ + printf("get-feature:%#0*x (%s), %s value:%#0*x\n", fid ? 4 : 2, fid, + nvme_feature_to_string(fid), nvme_select_to_string(sel), + result ? 10 : 8, result); + + if (NVME_CHECK(sel, GET_FEATURES_SEL, SUPPORTED)) + stdout_select_result(fid, result); + else if (stdout_print_ops.flags & VERBOSE) + stdout_feature_show_fields(fid, result, buf); + else if (buf) + d(buf, data_len, 16, 1); +} + +void stdout_feature_show_fields(enum nvme_features_id fid, unsigned int result, + unsigned char *buf) +{ + const char *async = "Send async event"; + const char *no_async = "Do not send async event"; + struct shr_table *t; + __u16 field; + + switch (fid) { + case NVME_FEAT_FID_ARBITRATION: + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, "High Priority Weight (HPW)", "%u", + NVME_FEAT_ARB_HPW(result) + 1); + stdout_kv_add(t, "Medium Priority Weight (MPW)", "%u", + NVME_FEAT_ARB_MPW(result) + 1); + stdout_kv_add(t, "Low Priority Weight (LPW)", "%u", + NVME_FEAT_ARB_LPW(result) + 1); + if (NVME_FEAT_ARB_BURST(result) == + NVME_FEAT_ARBITRATION_BURST_MASK) + stdout_kv_add(t, "Arbitration Burst (AB)", "No limit"); + else + stdout_kv_add(t, "Arbitration Burst (AB)", "%u", + 1 << NVME_FEAT_ARB_BURST(result)); + + stdout_kv_table_finish(t, "feature-show-fields"); + break; + case NVME_FEAT_FID_POWER_MGMT: + t = stdout_kv_table_create(); + if (!t) + return; + + field = NVME_FEAT_PM_WH(result); + stdout_kv_add(t, "Workload Hint (WH)", "%u - %s", field, + nvme_feature_wl_hints_to_string(field)); + stdout_kv_add(t, "Power State (PS)", "%u", + NVME_FEAT_PM_PS(result)); + field = NVME_FEAT_PM_IIELL(result); + if (field) + stdout_kv_add(t, "Idle I/O Exit Latency Limit (IIELL)", + "%uus", field * 100); + else + stdout_kv_add(t, "Idle I/O Exit Latency Limit (IIELL)", + "disabled"); + + stdout_kv_table_finish(t, "feature-show-fields"); + break; + case NVME_FEAT_FID_LBA_RANGE: + field = NVME_FEAT_LBAR_NR(result); + + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, "Number of LBA Ranges (NUM)", "%u", field + 1); + + stdout_kv_table_finish(t, "feature-show-fields"); + + if (buf) + stdout_lba_range((struct nvme_lba_range_type *)buf, + field); + break; + case NVME_FEAT_FID_TEMP_THRESH: + t = stdout_kv_table_create(); + if (!t) + return; + + field = NVME_FEAT_TT_TMPTHH(result); + stdout_kv_add(t, "Temperature Threshold Hysteresis (TMPTHH)", + "%s (%u K, %s)", nvme_degrees_string(field), + field, nvme_degrees_fahrenheit_string(field)); + field = NVME_FEAT_TT_THSEL(result); + stdout_kv_add(t, "Threshold Type Select (THSEL)", "%u - %s", + field, nvme_feature_temp_type_to_string(field)); + field = NVME_FEAT_TT_TMPSEL(result); + stdout_kv_add(t, "Threshold Temperature Select (TMPSEL)", + "%u - %s", field, + nvme_feature_temp_sel_to_string(field)); + field = NVME_FEAT_TT_TMPTH(result); + stdout_kv_add(t, "Temperature Threshold (TMPTH)", + "%s (%u K, %s)", + nvme_degrees_string(field), field, + nvme_degrees_fahrenheit_string(field)); + + stdout_kv_table_finish(t, "feature-show-fields"); + break; + case NVME_FEAT_FID_ERR_RECOVERY: + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, + "Deallocated or Unwritten Logical Block Error Enable (DULBE)", + "%s", + NVME_FEAT_ER_DULBE(result) ? + "Enabled" : "Disabled"); + stdout_kv_add(t, "Time Limited Error Recovery (TLER)", "%u ms", + NVME_FEAT_ER_TLER(result) * 100); + + stdout_kv_table_finish(t, "feature-show-fields"); + break; + case NVME_FEAT_FID_VOLATILE_WC: + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, "Volatile Write Cache Enable (WCE)", "%s", + NVME_FEAT_VWC_WCE(result) ? + "Enabled" : "Disabled"); + + stdout_kv_table_finish(t, "feature-show-fields"); + break; + case NVME_FEAT_FID_NUM_QUEUES: + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, + "Number of IO Completion Queues Allocated (NCQA)", + "%u", NVME_FEAT_NRQS_NCQR(result) + 1); + stdout_kv_add(t, + "Number of IO Submission Queues Allocated (NSQA)", + "%u", NVME_FEAT_NRQS_NSQR(result) + 1); + + stdout_kv_table_finish(t, "feature-show-fields"); + break; + case NVME_FEAT_FID_IRQ_COALESCE: + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, "Aggregation Time (TIME)", "%u usec", + NVME_FEAT_IRQC_TIME(result) * 100); + stdout_kv_add(t, "Aggregation Threshold (THR)", "%u", + NVME_FEAT_IRQC_THR(result) + 1); + + stdout_kv_table_finish(t, "feature-show-fields"); + break; + case NVME_FEAT_FID_IRQ_CONFIG: + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, "Coalescing Disable (CD)", "%s", + NVME_FEAT_ICFG_CD(result) ? "True" : "False"); + stdout_kv_add(t, "Interrupt Vector (IV)", "%u", + NVME_FEAT_ICFG_IV(result)); + + stdout_kv_table_finish(t, "feature-show-fields"); + break; + case NVME_FEAT_FID_WRITE_ATOMIC: + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, "Disable Normal (DN)", "%s", + NVME_FEAT_WA_DN(result) ? "True" : "False"); + + stdout_kv_table_finish(t, "feature-show-fields"); + break; + case NVME_FEAT_FID_ASYNC_EVENT: + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, feat_ae_dlpcn, "%s", + NVME_FEAT_AE_DLPCN(result) ? async : no_async); + stdout_kv_add(t, feat_ae_hdlpcn, "%s", + NVME_FEAT_AE_HDLPCN(result) ? async : no_async); + stdout_kv_add(t, feat_ae_adlpcn, "%s", + NVME_FEAT_AE_ADLPCN(result) ? async : no_async); + stdout_kv_add(t, feat_ae_pmdrlpcn, "%s", + NVME_FEAT_AE_PMDRLPCN(result) ? async : no_async); + stdout_kv_add(t, feat_ae_zdcn, "%s", + NVME_FEAT_AE_ZDCN(result) ? async : no_async); + stdout_kv_add(t, feat_ae_rlccn, "%s", + NVME_FEAT_AE_RLCCN(result) ? async : no_async); + stdout_kv_add(t, feat_ae_lhcn, "%s", + NVME_FEAT_AE_LHCN(result) ? async : no_async); + stdout_kv_add(t, feat_ae_ccrcn, "%s", + NVME_FEAT_AE_CCRCN(result) ? async : no_async); + stdout_kv_add(t, feat_ae_ansan, "%s", + NVME_FEAT_AE_ANSAN(result) ? async : no_async); + stdout_kv_add(t, feat_ae_rgrp0, "%s", + NVME_FEAT_AE_RGRP0(result) ? async : no_async); + stdout_kv_add(t, feat_ae_rassn, "%s", + NVME_FEAT_AE_RASSN(result) ? async : no_async); + stdout_kv_add(t, feat_ae_tthry, "%s", + NVME_FEAT_AE_TTHRY(result) ? async : no_async); + stdout_kv_add(t, feat_ae_nnsshdn, "%s", + NVME_FEAT_AE_NNSSHDN(result) ? async : no_async); + stdout_kv_add(t, feat_ae_ega, "%s", + NVME_FEAT_AE_EGA(result) ? async : no_async); + stdout_kv_add(t, feat_ae_lbas, "%s", + NVME_FEAT_AE_LBAS(result) ? async : no_async); + stdout_kv_add(t, feat_ae_pla, "%s", + NVME_FEAT_AE_PLA(result) ? async : no_async); + stdout_kv_add(t, feat_ae_ana, "%s", + NVME_FEAT_AE_ANA(result) ? async : no_async); + stdout_kv_add(t, feat_ae_telem, "%s", + NVME_FEAT_AE_TELEM(result) ? async : no_async); + stdout_kv_add(t, feat_ae_fw, "%s", + NVME_FEAT_AE_FW(result) ? async : no_async); + stdout_kv_add(t, feat_ae_nan, "%s", + NVME_FEAT_AE_NAN(result) ? async : no_async); + stdout_kv_add(t, feat_ae_smart, "%s", + NVME_FEAT_AE_SMART(result) ? async : no_async); + + stdout_kv_table_finish(t, "feature-show-fields"); + break; + case NVME_FEAT_FID_AUTO_PST: + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, + "Autonomous Power State Transition Enable (APSTE)", + "%s", + NVME_FEAT_APST_APSTE(result) ? + "Enabled" : "Disabled"); + + stdout_kv_table_finish(t, "feature-show-fields"); + + if (buf) + stdout_auto_pst((struct nvme_feat_auto_pst *)buf); + break; + case NVME_FEAT_FID_HOST_MEM_BUF: + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, "Enable Host Memory (EHM)", "%s", + NVME_FEAT_HMEM_EHM(result) ? + "Enabled" : "Disabled"); + stdout_kv_add(t, + "Host Memory Non-operational Access Restriction Enable (HMNARE)", + "%s", (result & 0x00000004) ? "True" : "False"); + stdout_kv_add(t, + "Host Memory Non-operational Access Restricted (HMNAR)", + "%s", (result & 0x00000008) ? "True" : "False"); + + stdout_kv_table_finish(t, "feature-show-fields"); + + if (buf) + stdout_host_mem_buffer( + (struct nvme_host_mem_buf_attrs *)buf); + break; + case NVME_FEAT_FID_TIMESTAMP: + if (buf) + stdout_timestamp((struct nvme_timestamp *)buf); + break; + case NVME_FEAT_FID_KATO: + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, "Keep Alive Timeout (KATO) in milliseconds", + "%u", result); + + stdout_kv_table_finish(t, "feature-show-fields"); + break; + case NVME_FEAT_FID_HCTM: + t = stdout_kv_table_create(); + if (!t) + return; + + field = NVME_FEAT_HCTM_TMT1(result); + stdout_kv_add(t, "Thermal Management Temperature 1 (TMT1)", + "%u K (%s, %s)", field, + nvme_degrees_string(field), + nvme_degrees_fahrenheit_string(field)); + field = NVME_FEAT_HCTM_TMT2(result); + stdout_kv_add(t, "Thermal Management Temperature 2 (TMT2)", + "%u K (%s, %s)", field, + nvme_degrees_string(field), + nvme_degrees_fahrenheit_string(field)); + + stdout_kv_table_finish(t, "feature-show-fields"); + break; + case NVME_FEAT_FID_NOPSC: + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, + "Non-Operational Power State Permissive Mode Enable (NOPPME)", + "%s", + NVME_FEAT_NOPS_NOPPME(result) ? "True" : "False"); + + stdout_kv_table_finish(t, "feature-show-fields"); + break; + case NVME_FEAT_FID_RRL: + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, "Read Recovery Level (RRL)", "%u", + NVME_FEAT_RRL_RRL(result)); + + stdout_kv_table_finish(t, "feature-show-fields"); + break; + case NVME_FEAT_FID_PLM_CONFIG: + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, "Predictable Latency Window Enabled", "%s", + NVME_FEAT_PLM_LPE(result) ? "True" : "False"); + + stdout_kv_table_finish(t, "feature-show-fields"); + + if (buf) + stdout_plm_config((struct nvme_plm_config *)buf); + break; + case NVME_FEAT_FID_PLM_WINDOW: + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, "Window Select", "%s", + nvme_plm_window_to_string(result)); + + stdout_kv_table_finish(t, "feature-show-fields"); + break; + case NVME_FEAT_FID_LBA_STS_INTERVAL: + stdout_lba_status_info(result); + break; + case NVME_FEAT_FID_HOST_BEHAVIOR: + if (buf) { + struct nvme_feat_host_behavior *hb = + (struct nvme_feat_host_behavior *)buf; + + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, "Advanced Command Retry Enable (ACRE)", + "%s", hb->acre ? "True" : "False"); + stdout_kv_add(t, + "Extended Telemetry Data Area 4 Supported (ETDAS)", + "%s", hb->etdas ? "True" : "False"); + stdout_kv_add(t, "LBA Format Extension Enable (LBAFEE)", + "%s", hb->lbafee ? "True" : "False"); + stdout_kv_add(t, + "Host Dispersed Namespace Support (HDISNS)", + "%s", + hb->hdisns ? "Enabled" : "Disabled"); + stdout_kv_add(t, + "Copy Descriptor Format 2h Enabled (CDF2E)", + "%s", + hb->cdfe & (1 << 2) ? "True" : "False"); + stdout_kv_add(t, + "Copy Descriptor Format 3h Enabled (CDF3E)", + "%s", + hb->cdfe & (1 << 3) ? "True" : "False"); + stdout_kv_add(t, + "Copy Descriptor Format 4h Enabled (CDF4E)", + "%s", + hb->cdfe & (1 << 4) ? "True" : "False"); + + stdout_kv_table_finish(t, "feature-show-fields"); + } + break; + case NVME_FEAT_FID_SANITIZE: + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, "No-Deallocate Response Mode (NODRM)", "%u", + NVME_FEAT_SC_NODRM(result)); + + stdout_kv_table_finish(t, "feature-show-fields"); + break; + case NVME_FEAT_FID_ENDURANCE_EVT_CFG: + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, "Endurance Group Identifier (ENDGID)", "%u", + NVME_FEAT_EG_ENDGID(result)); + stdout_kv_add(t, "Endurance Group Critical Warnings", "%u", + NVME_FEAT_EG_EGCW(result)); + + stdout_kv_table_finish(t, "feature-show-fields"); + break; + case NVME_FEAT_FID_IOCS_PROFILE: + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, "I/O Command Set Profile", "%s", + result & 0x1 ? "True" : "False"); + + stdout_kv_table_finish(t, "feature-show-fields"); + break; + case NVME_FEAT_FID_SPINUP_CONTROL: + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, "Spinup control feature Enabled", "%s", + (result & 1) ? "True" : "False"); + + stdout_kv_table_finish(t, "feature-show-fields"); + break; + case NVME_FEAT_FID_POWER_LOSS_SIGNAL: + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, "Power Loss Signaling Mode (PLSM)", "%s", + nvme_pls_mode_to_string( + NVME_GET(result, FEAT_PLS_MODE))); + + stdout_kv_table_finish(t, "feature-show-fields"); + break; + case NVME_FEAT_FID_PERF_CHARACTERISTICS: + stdout_feat_perfc(result, + (struct nvme_perf_characteristics *)buf); + break; + case NVME_FEAT_FID_ENH_CTRL_METADATA: + case NVME_FEAT_FID_CTRL_METADATA: + case NVME_FEAT_FID_NS_METADATA: + if (buf) + stdout_host_metadata(fid, + (struct nvme_host_metadata *)buf); + break; + case NVME_FEAT_FID_SW_PROGRESS: + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, "Pre-boot Software Load Count (PBSLC)", "%u", + NVME_FEAT_SPM_PBSLC(result)); + + stdout_kv_table_finish(t, "feature-show-fields"); + break; + case NVME_FEAT_FID_HOST_ID: + stdout_feat_host_id(result, buf); + break; + case NVME_FEAT_FID_RESV_NF_MASK: + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, + "Mask Reservation Preempted Notification (RESPRE)", + "%s", + NVME_FEAT_RM_RESPRE(result) ? "True" : "False"); + stdout_kv_add(t, + "Mask Reservation Released Notification (RESREL)", + "%s", + NVME_FEAT_RM_RESREL(result) ? "True" : "False"); + stdout_kv_add(t, + "Mask Registration Preempted Notification (REGPRE)", + "%s", + NVME_FEAT_RM_REGPRE(result) ? "True" : "False"); + + stdout_kv_table_finish(t, "feature-show-fields"); + break; + case NVME_FEAT_FID_RESV_PERSIST: + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, "Persist Through Power Loss (PTPL)", "%s", + NVME_FEAT_RP_PTPL(result) ? "True" : "False"); + + stdout_kv_table_finish(t, "feature-show-fields"); + break; + case NVME_FEAT_FID_WRITE_PROTECT: + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, "Namespace Write Protect", "%s", + nvme_ns_wp_cfg_to_string(result)); + + stdout_kv_table_finish(t, "feature-show-fields"); + break; + case NVME_FEAT_FID_FDP: + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, "Flexible Direct Placement Enable (FDPE)", + "%s", NVME_FEAT_FDPE(result) ? "Yes" : "No"); + stdout_kv_add(t, + "Flexible Direct Placement Configuration Index", + "%u", NVME_FEAT_FDPCIDX(result)); + + stdout_kv_table_finish(t, "feature-show-fields"); + break; + case NVME_FEAT_FID_FDP_EVENTS: + t = stdout_kv_table_create(); + if (!t) + return; + + // NOET is in bits 7:0; bits 31:8 are reserved. + for (unsigned int i = 0; i < (result & 0xff); i++) { + struct nvme_fdp_supported_event_desc *d; + + d = &((struct nvme_fdp_supported_event_desc *)buf)[i]; + + stdout_kv_add(t, nvme_fdp_event_to_string(d->evt), + "%sEnabled", d->evta & 0x1 ? "" : "Not "); + } + + stdout_kv_table_finish(t, "feature-show-fields"); + break; + case NVME_FEAT_FID_BP_WRITE_PROTECT: + t = stdout_kv_table_create(); + if (!t) + return; + + field = NVME_FEAT_BPWPC_BP1WPS(result); + stdout_kv_add(t, + "Boot Partition 1 Write Protection State (BP1WPS)", + "%s", nvme_bpwps_to_string(field)); + field = NVME_FEAT_BPWPC_BP0WPS(result); + stdout_kv_add(t, + "Boot Partition 0 Write Protection State (BP0WPS)", + "%s", nvme_bpwps_to_string(field)); + + stdout_kv_table_finish(t, "feature-show-fields"); + break; + case NVME_FEAT_FID_POWER_LIMIT: { + __cleanup_free char *power_str = NULL; + + t = stdout_kv_table_create(); + if (!t) + return; + + field = NVME_FEAT_POWER_LIMIT_PLS(result); + power_str = stdout_power_and_scale_str( + NVME_FEAT_POWER_LIMIT_PLV(result), field); + stdout_kv_add(t, "Power Limit Scale (PLS)", "%u - %s", field, + nvme_feature_power_limit_scale_to_string(field)); + stdout_kv_add(t, "Power Limit Value (PLV)", "%u", + NVME_FEAT_POWER_LIMIT_PLV(result)); + stdout_kv_add(t, "Power Limit", "%s", power_str); + + stdout_kv_table_finish(t, "feature-show-fields"); + break; + } + case NVME_FEAT_FID_POWER_THRESH: { + __cleanup_free char *power_str = NULL; + + t = stdout_kv_table_create(); + if (!t) + return; + + field = NVME_FEAT_POWER_THRESH_EPT(result); + stdout_kv_add(t, "Enable Power Threshold (EPT)", "%u - %s", + field, field ? "Enabled" : "Disabled"); + field = NVME_FEAT_POWER_THRESH_PMTS(result); + stdout_kv_add(t, "Power Measurement Type Select (PMTS)", + "%u - %s", field, + nvme_power_measurement_type_to_string(field)); + field = NVME_FEAT_POWER_THRESH_PTS(result); + power_str = stdout_power_and_scale_str( + NVME_FEAT_POWER_THRESH_PTV(result), field); + stdout_kv_add(t, "Power Threshold Scale (PTS)", "%u - %s", + field, + nvme_feature_power_limit_scale_to_string(field)); + stdout_kv_add(t, "Power Threshold Value (PTV)", "%u", + NVME_FEAT_POWER_THRESH_PTV(result)); + stdout_kv_add(t, "Power Threshold", "%s", power_str); + + stdout_kv_table_finish(t, "feature-show-fields"); + break; + } + case NVME_FEAT_FID_POWER_MEASUREMENT: + t = stdout_kv_table_create(); + if (!t) + return; + + field = NVME_FEAT_POWER_MEAS_ACT(result); + stdout_kv_add(t, "Action (ACT)", "%u - %s", field, + nvme_power_measurement_action_to_string(field)); + field = NVME_FEAT_POWER_MEAS_PMTS(result); + stdout_kv_add(t, "Power Measurement Type Select (PMTS)", + "%u - %s", field, + nvme_power_measurement_type_to_string(field)); + stdout_kv_add(t, "Stop Measurement Time (SMT)", "%u", + NVME_FEAT_POWER_MEAS_SMT(result)); + + stdout_kv_table_finish(t, "feature-show-fields"); + break; + case NVME_FEAT_FID_VOLTAGE_THRESHOLD: + t = stdout_kv_table_create(); + if (!t) + return; + + field = NVME_FEAT_VOLTAGE_THRESHOLD_VSENS(result); + stdout_kv_add(t, "Voltage Sensor Select (VSENS)", "%u", field); + stdout_kv_add(t, "Enable Voltage Threshold (EVT)", "%u - %s", + !!(result & NVME_FEAT_VOLTAGE_THRESHOLD_EVT), + result & NVME_FEAT_VOLTAGE_THRESHOLD_EVT ? + "Enabled" : "Disabled"); + stdout_kv_add(t, "Overvoltage Threshold (OVT)", "%u", + NVME_FEAT_VOLTAGE_THRESHOLD_OVT(result)); + stdout_kv_add(t, "Undervoltage Threshold (UVT)", "%u", + NVME_FEAT_VOLTAGE_THRESHOLD_UVT(result)); + + stdout_kv_table_finish(t, "feature-show-fields"); + break; + case NVME_FEAT_FID_VOLTAGE_MEASUREMENT: + t = stdout_kv_table_create(); + if (!t) + return; + + field = NVME_FEAT_VOLTAGE_MEASUREMENT_ACT(result); + stdout_kv_add(t, "Action (ACT)", "%u", field); + + stdout_kv_table_finish(t, "feature-show-fields"); + break; + case NVME_FEAT_FID_RATE_LIMITING: + if (buf) + stdout_rate_limiting_data( + (struct nvme_rate_limiting_data *)buf); + break; + default: + break; + } +} + +static struct feat_print_ops feat_stdout_print_ops = { + .select_result = stdout_select_result, + .show_feature = stdout_feature_show, + .show_feature_fields = stdout_feature_show_fields, + .lba_range = stdout_lba_range, + .lba_status_info = stdout_lba_status_info, +}; + +struct feat_print_ops *feat_get_stdout_print_ops(nvme_print_flags_t flags) +{ + feat_stdout_print_ops.flags = flags; + return &feat_stdout_print_ops; +} diff --git a/plugins/cmds-feat/feat-print.c b/plugins/cmds-feat/feat-print.c new file mode 100644 index 0000000000..496b5733f1 --- /dev/null +++ b/plugins/cmds-feat/feat-print.c @@ -0,0 +1,530 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include + +#include "feat-print.h" +#include "nvme-print.h" + +const char *feat_ae_dlpcn = "Discovery Log Page Change Notices"; +const char *feat_ae_hdlpcn = "Host Discovery Log Page Change Notification"; +const char *feat_ae_adlpcn = "AVE Discovery Log Page Change Notification"; +const char *feat_ae_pmdrlpcn = + "Pull Model DDC Request Log Page Change Notification"; +const char *feat_ae_zdcn = "Zone Descriptor Changed Notices"; +const char *feat_ae_rlccn = "Rate Limiting Configuration Change Notices"; +const char *feat_ae_lhcn = "Lost Host Communication Notices"; +const char *feat_ae_ccrcn = "Cross-Controller Reset Completed Notices"; +const char *feat_ae_ansan = "Allocated Namespace Attribute Notices"; +const char *feat_ae_rgrp0 = "Reachability Group"; +const char *feat_ae_rassn = "Reachability Association"; +const char *feat_ae_tthry = "Temperature Threshold Hysteresis Recovery"; +const char *feat_ae_nnsshdn = "Normal NVM Subsystem Shutdown"; +const char *feat_ae_ega = "Endurance Group Event Aggregate Log Change Notices"; +const char *feat_ae_lbas = "LBA Status Information Notices"; +const char *feat_ae_pla = + "Predictable Latency Event Aggregate Log Change Notices"; +const char *feat_ae_ana = "Asymmetric Namespace Access Change Notices"; +const char *feat_ae_telem = "Telemetry Log Notices"; +const char *feat_ae_fw = "Firmware Activation Notices"; +const char *feat_ae_nan = "Attached Namespace Attribute Notices"; +const char *feat_ae_smart = "SMART / Health Critical Warnings"; + +/* + * Run the printers in the sandbox. Like nvme_print(), silently skip + * printers that an output format does not implement. + */ +#define feat_print(name, flags, ...) \ + do { \ + struct feat_print_ops *__fops = feat_print_ops(flags); \ + \ + if (__fops && __fops->name) \ + nvme_print_decoder(__fops, name, true, flags, \ + ##__VA_ARGS__); \ + } while (false) + +/* Like feat_print(), but for dry runs as well */ +#define feat_print_always(name, flags, ...) \ + do { \ + struct feat_print_ops *__fops = feat_print_ops(flags); \ + \ + if (__fops && __fops->name) \ + nvme_print_decoder_always(__fops, name, true, \ + flags, ##__VA_ARGS__); \ + } while (false) + +static struct feat_print_ops *feat_print_ops(nvme_print_flags_t flags) +{ + struct feat_print_ops *ops = NULL; + + if (flags & JSON || nvme_is_output_format_json()) + ops = feat_get_json_print_ops(flags); + else if (flags & BINARY) + ops = feat_get_binary_print_ops(flags); + else + ops = feat_get_stdout_print_ops(flags); + + return ops; +} + +const char *nvme_feature_to_string(enum nvme_features_id feature) +{ + switch (feature) { + case NVME_FEAT_FID_ARBITRATION: + return "Arbitration"; + case NVME_FEAT_FID_POWER_MGMT: + return "Power Management"; + case NVME_FEAT_FID_LBA_RANGE: + return "LBA Range Type"; + case NVME_FEAT_FID_TEMP_THRESH: + return "Temperature Threshold"; + case NVME_FEAT_FID_ERR_RECOVERY: + return "Error Recovery"; + case NVME_FEAT_FID_VOLATILE_WC: + return "Volatile Write Cache"; + case NVME_FEAT_FID_NUM_QUEUES: + return "Number of Queues"; + case NVME_FEAT_FID_IRQ_COALESCE: + return "Interrupt Coalescing"; + case NVME_FEAT_FID_IRQ_CONFIG: + return "Interrupt Vector Configuration"; + case NVME_FEAT_FID_WRITE_ATOMIC: + return "Write Atomicity Normal"; + case NVME_FEAT_FID_ASYNC_EVENT: + return "Async Event Configuration"; + case NVME_FEAT_FID_AUTO_PST: + return "Autonomous Power State Transition"; + case NVME_FEAT_FID_HOST_MEM_BUF: + return "Host Memory Buffer"; + case NVME_FEAT_FID_TIMESTAMP: + return "Timestamp"; + case NVME_FEAT_FID_KATO: + return "Keep Alive Timer"; + case NVME_FEAT_FID_HCTM: + return "Host Controlled Thermal Management"; + case NVME_FEAT_FID_NOPSC: + return "Non-Operational Power State Config"; + case NVME_FEAT_FID_RRL: + return "Read Recovery Level"; + case NVME_FEAT_FID_PLM_CONFIG: + return "Predictable Latency Mode Config"; + case NVME_FEAT_FID_PLM_WINDOW: + return "Predictable Latency Mode Window"; + case NVME_FEAT_FID_LBA_STS_INTERVAL: + return "LBA Status Interval"; + case NVME_FEAT_FID_HOST_BEHAVIOR: + return "Host Behavior"; + case NVME_FEAT_FID_SANITIZE: + return "Sanitize"; + case NVME_FEAT_FID_ENDURANCE_EVT_CFG: + return "Endurance Event Group Configuration"; + case NVME_FEAT_FID_IOCS_PROFILE: + return "I/O Command Set Profile"; + case NVME_FEAT_FID_SPINUP_CONTROL: + return "Spinup Control"; + case NVME_FEAT_FID_POWER_LOSS_SIGNAL: + return "Power Loss Signaling Config"; + case NVME_FEAT_FID_PERF_CHARACTERISTICS: + return "Performance Characteristics"; + case NVME_FEAT_FID_FDP: + return "Flexible Direct Placement"; + case NVME_FEAT_FID_FDP_EVENTS: + return "Flexible Direct Placement Events"; + case NVME_FEAT_FID_NS_ADMIN_LABEL: + return "Namespace Admin Label"; + case NVME_FEAT_FID_KEY_VALUE: + return "Key Value Configuration"; + case NVME_FEAT_FID_CTRL_DATA_QUEUE: + return "Controller Data Queue"; + case NVME_FEAT_FID_CONF_DEV_PERSONALITY: + return "Configurable Device Personality"; + case NVME_FEAT_FID_POWER_LIMIT: + return "Power Limit"; + case NVME_FEAT_FID_POWER_THRESH: + return "Power Threshold"; + case NVME_FEAT_FID_POWER_MEASUREMENT: + return "Power Measurement"; + case NVME_FEAT_FID_VOLTAGE_THRESHOLD: + return "Voltage Threshold"; + case NVME_FEAT_FID_VOLTAGE_MEASUREMENT: + return "Voltage Measurement"; + case NVME_FEAT_FID_RATE_LIMITING: + return "Rate Limiting"; + case NVME_FEAT_FID_EMB_MGMT_CTRL_ADDR: + return "Embedded Management Controller Address"; + case NVME_FEAT_FID_HOST_MGMT_AGENT_ADDR: + return "Host Management Agent Address"; + case NVME_FEAT_FID_ENH_CTRL_METADATA: + return "Enhanced Controller Metadata"; + case NVME_FEAT_FID_CTRL_METADATA: + return "Controller Metadata"; + case NVME_FEAT_FID_NS_METADATA: + return "Namespace Metadata"; + case NVME_FEAT_FID_SW_PROGRESS: + return "Software Progress"; + case NVME_FEAT_FID_HOST_ID: + return "Host Identifier"; + case NVME_FEAT_FID_RESV_NF_MASK: + return "Reservation Notification Mask"; + case NVME_FEAT_FID_RESV_PERSIST: + return "Reservation Persistence"; + case NVME_FEAT_FID_WRITE_PROTECT: + return "Namespace Write Protect"; + case NVME_FEAT_FID_BP_WRITE_PROTECT: + return "Boot Partition Write Protection Config"; + } + /* + * We don't use the "default:" statement to let the compiler warning if + * some values of the enum nvme_features_id are missing in the switch(). + * The following return is acting as the default: statement. + */ + return "Unknown"; +} + +const char *nvme_select_to_string(int sel) +{ + switch (sel) { + case NVME_GET_FEATURES_SEL_CURRENT: + return "Current"; + case NVME_GET_FEATURES_SEL_DEFAULT: + return "Default"; + case NVME_GET_FEATURES_SEL_SAVED: + return "Saved"; + case NVME_GET_FEATURES_SEL_SUPPORTED: + return "Supported capabilities"; + default: + break; + } + return "Reserved"; +} + +void nvme_show_select_result(enum nvme_features_id fid, __u64 result) +{ + feat_print(select_result, NORMAL, fid, result); +} + +const char *nvme_feature_lba_type_to_string(__u8 type) +{ + switch (type) { + case 0: return "General Purpose"; + case 1: return "Filesystem"; + case 2: return "RAID"; + case 3: return "Cache"; + case 4: return "Page / Swap file"; + default: + if (type >= 0x05 && type <= 0x7f) + return "Reserved"; + else + return "Vendor Specific"; + } +} + +void nvme_show_lba_range(struct nvme_lba_range_type *lbrt, int nr_ranges, + nvme_print_flags_t flags) +{ + feat_print(lba_range, flags, lbrt, nr_ranges); +} + +const char *nvme_feature_wl_hints_to_string(__u8 wh) +{ + switch (wh) { + case 0: + return "No Workload"; + case 1: + return "Extended Idle Period with a Burst of Random Writes"; + case 2: + return "Heavy Sequential Writes"; + default: + return "Reserved"; + } +} + +const char *nvme_feature_temp_type_to_string(__u8 type) +{ + switch (type) { + case 0: return "Over Temperature Threshold"; + case 1: return "Under Temperature Threshold"; + default:return "Reserved"; + } +} + +const char *nvme_feature_temp_sel_to_string(__u8 sel) +{ + switch (sel) { + case 0: return "Composite Temperature"; + case 1: return "Temperature Sensor 1"; + case 2: return "Temperature Sensor 2"; + case 3: return "Temperature Sensor 3"; + case 4: return "Temperature Sensor 4"; + case 5: return "Temperature Sensor 5"; + case 6: return "Temperature Sensor 6"; + case 7: return "Temperature Sensor 7"; + case 8: return "Temperature Sensor 8"; + default:return "Reserved"; + } +} + +const char *nvme_feature_perfc_attri_to_string(__u8 attri) +{ + switch (attri) { + case NVME_FEAT_PERFC_ATTRI_STD: + return "standard performance attribute"; + case NVME_FEAT_PERFC_ATTRI_ID_LIST: + return "performance attribute identifier list"; + case NVME_FEAT_PERFC_ATTRI_VS_MIN ... NVME_FEAT_PERFC_ATTRI_VS_MAX: + return "vendor specific performance attribute"; + default: + break; + } + + return "reserved"; +} + +const char *nvme_feature_perfc_r4karl_to_string(__u8 r4karl) +{ + switch (r4karl) { + case NVME_FEAT_PERFC_R4KARL_NO_REPORT: + return "not reported"; + case NVME_FEAT_PERFC_R4KARL_GE_100_SEC: + return "greater than or equal to 100 seconds"; + case NVME_FEAT_PERFC_R4KARL_GE_50_SEC: + return ( + "greater than or equal to 50 seconds and less than 100 seconds"); + case NVME_FEAT_PERFC_R4KARL_GE_10_SEC: + return ( + "greater than or equal to 10 seconds and less than 50 seconds"); + case NVME_FEAT_PERFC_R4KARL_GE_5_SEC: + return ( + "greater than or equal to 5 seconds and less than 10 seconds"); + case NVME_FEAT_PERFC_R4KARL_GE_1_SEC: + return ( + "greater than or equal to 1 second and less than 5 seconds"); + case NVME_FEAT_PERFC_R4KARL_GE_500_MS: + return ( + "greater than or equal to 500 milliseconds and less than 1 second"); + case NVME_FEAT_PERFC_R4KARL_GE_100_MS: + return ( + "greater than or equal to 100 milliseconds and less than 500 milliseconds"); + case NVME_FEAT_PERFC_R4KARL_GE_50_MS: + return ( + "greater than or equal to 50 milliseconds and less than 100 milliseconds"); + case NVME_FEAT_PERFC_R4KARL_GE_10_MS: + return ( + "greater than or equal to 10 milliseconds and less than 50 milliseconds"); + case NVME_FEAT_PERFC_R4KARL_GE_5_MS: + return ( + "greater than or equal to 5 milliseconds and less than 10 milliseconds"); + case NVME_FEAT_PERFC_R4KARL_GE_1_MS: + return ( + "greater than or equal to 1 millisecond and less than 5 milliseconds"); + case NVME_FEAT_PERFC_R4KARL_GE_500_US: + return ( + "greater than or equal to 500 microseconds and less than 1 millisecond"); + case NVME_FEAT_PERFC_R4KARL_GE_100_US: + return ( + "greater than or equal to 100 microseconds and less than 500 microseconds"); + case NVME_FEAT_PERFC_R4KARL_GE_50_US: + return ( + "greater than or equal to 50 microseconds and less than 100 microseconds"); + case NVME_FEAT_PERFC_R4KARL_GE_10_US: + return ( + "greater than or equal to 10 microseconds and less than 50 microseconds"); + case NVME_FEAT_PERFC_R4KARL_GE_5_US: + return ( + "greater than or equal to 5 microseconds and less than 10 microseconds"); + case NVME_FEAT_PERFC_R4KARL_GE_1_US: + return ( + "greater than or equal to 1 microsecond and less than 5 microseconds"); + case NVME_FEAT_PERFC_R4KARL_GE_500_NS: + return ( + "greater than or equal to 500 nanoseconds and less than 1 microsecond"); + case NVME_FEAT_PERFC_R4KARL_GE_100_NS: + return ( + "greater than or equal to 100 nanoseconds and less than 500 nanoseconds"); + case NVME_FEAT_PERFC_R4KARL_GE_50_NS: + return ( + "greater than or equal to 50 nanoseconds and less than 100 nanoseconds"); + case NVME_FEAT_PERFC_R4KARL_GE_10_NS: + return ( + "greater than or equal to 10 nanoseconds and less than 50 nanoseconds"); + case NVME_FEAT_PERFC_R4KARL_GE_5_NS: + return ( + "greater than or equal to 5 nanoseconds and less than 10 nanoseconds"); + case NVME_FEAT_PERFC_R4KARL_GE_1_NS: + return ( + "greater than or equal to 1 nanosecond and less than 5 nanoseconds"); + default: + break; + } + + return "reserved"; +} + +const char *nvme_feature_perfc_attrtyp_to_string(__u8 attrtyp) +{ + switch (attrtyp) { + case NVME_GET_FEATURES_SEL_CURRENT: + return "current attribute"; + case NVME_GET_FEATURES_SEL_DEFAULT: + return "default attribute"; + case NVME_GET_FEATURES_SEL_SAVED: + return "saved attribute"; + default: + break; + } + + return "reserved"; +} + +const char *nvme_ns_wp_cfg_to_string(enum nvme_ns_write_protect_cfg state) +{ + switch (state) { + case NVME_NS_WP_CFG_NONE: + return "No Write Protect"; + case NVME_NS_WP_CFG_PROTECT: + return "Write Protect"; + case NVME_NS_WP_CFG_PROTECT_POWER_CYCLE: + return "Write Protect Until Power Cycle"; + case NVME_NS_WP_CFG_PROTECT_PERMANENT: + return "Permanent Write Protect"; + default: + return "Reserved"; + } +} + +const char *nvme_bpwps_to_string(__u8 bpwps) +{ + switch (bpwps) { + case NVME_FEAT_BPWPS_CHANGE_NOT_REQUESTED: + return "Change in state not requested"; + case NVME_FEAT_BPWPS_WRITE_UNLOCKED: + return "Write Unlocked"; + case NVME_FEAT_BPWPS_WRITE_LOCKED: + return "Write Locked"; + case NVME_FEAT_BPWPS_WRITE_LOCKED_PWR_CYCLE: + return "Write Locked Until Power Cycle"; + case NVME_FEAT_BPWPS_WRITE_PROTECTION_RPMB: + return "Write Protection controlled by RPMB"; + default: + return "Reserved"; + } +} + +const char *nvme_plm_window_to_string(__u32 plm) +{ + switch (NVME_FEAT_PLMW_WS(plm)) { + case 1: + return "Deterministic Window (DTWIN)"; + case 2: + return "Non-deterministic Window (NDWIN)"; + default: + return "Reserved"; + } +} + +void nvme_show_lba_status_info(__u64 result) +{ + feat_print(lba_status_info, NORMAL, result); +} + +const char *nvme_host_metadata_type_to_string(enum nvme_features_id fid, + __u8 type) +{ + switch (fid) { + case NVME_FEAT_FID_ENH_CTRL_METADATA: + case NVME_FEAT_FID_CTRL_METADATA: + switch (type) { + case NVME_CTRL_METADATA_OS_CTRL_NAME: + return "Operating System Controller Name"; + case NVME_CTRL_METADATA_OS_DRIVER_NAME: + return "Operating System Driver Name"; + case NVME_CTRL_METADATA_OS_DRIVER_VER: + return "Operating System Driver Version"; + case NVME_CTRL_METADATA_PRE_BOOT_CTRL_NAME: + return "Pre-boot Controller Name"; + case NVME_CTRL_METADATA_PRE_BOOT_DRIVER_NAME: + return "Pre-boot Driver Name"; + case NVME_CTRL_METADATA_PRE_BOOT_DRIVER_VER: + return "Pre-boot Driver Version"; + case NVME_CTRL_METADATA_SYS_PROC_MODEL: + return "System Processor Model"; + case NVME_CTRL_METADATA_CHIPSET_DRV_NAME: + return "Chipset Driver Name"; + case NVME_CTRL_METADATA_CHIPSET_DRV_VERSION: + return "Chipset Driver Version"; + case NVME_CTRL_METADATA_OS_NAME_AND_BUILD: + return "Operating System Name and Build"; + case NVME_CTRL_METADATA_SYS_PROD_NAME: + return "System Product Name"; + case NVME_CTRL_METADATA_FIRMWARE_VERSION: + return "Firmware Version"; + case NVME_CTRL_METADATA_OS_DRIVER_FILENAME: + return "Operating System Driver Filename"; + case NVME_CTRL_METADATA_DISPLAY_DRV_NAME: + return "Display Driver Name"; + case NVME_CTRL_METADATA_DISPLAY_DRV_VERSION: + return "Display Driver Version"; + case NVME_CTRL_METADATA_HOST_DET_FAIL_REC: + return "Host-Determined Failure Record"; + default: + return "Unknown Controller Type"; + } + case NVME_FEAT_FID_NS_METADATA: + switch (type) { + case NVME_NS_METADATA_OS_NS_NAME: + return "Operating System Namespace Name"; + case NVME_NS_METADATA_PRE_BOOT_NS_NAME: + return "Pre-boot Namespace Name"; + case NVME_NS_METADATA_OS_NS_QUAL_1: + return "Operating System Namespace Name Qualifier 1"; + case NVME_NS_METADATA_OS_NS_QUAL_2: + return "Operating System Namespace Name Qualifier 2"; + default: + return "Unknown Namespace Type"; + } + default: + return "Unknown Feature"; + } +} + +const char *nvme_pls_mode_to_string(__u8 mode) +{ + switch (mode) { + case 0: + return "not enabled"; + case 1: + return "enabled with Emergency Power Fail"; + case 2: + return "enabled with Forced Quiescence"; + default: + break; + } + + return "Reserved"; +} + +const char *nvme_power_measurement_action_to_string(__u8 act) +{ + switch (act) { + case 0: + return "Stop"; + case 1: + return "Start"; + default: + break; + } + + return "Reserved"; +} + +void nvme_show_feature(enum nvme_features_id fid, int sel, unsigned int result, + void *buf, __u32 data_len, nvme_print_flags_t flags) +{ + feat_print(show_feature, flags, fid, sel, result, buf, data_len); +} + +void nvme_feature_show_fields(enum nvme_features_id fid, unsigned int result, + unsigned char *buf) +{ + /* Always show the fields, the set commands show what they set */ + feat_print_always(show_feature_fields, NORMAL, fid, result, buf); +} diff --git a/plugins/cmds-feat/feat-print.h b/plugins/cmds-feat/feat-print.h new file mode 100644 index 0000000000..96417d7901 --- /dev/null +++ b/plugins/cmds-feat/feat-print.h @@ -0,0 +1,87 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#pragma once + +#include + +#include "args.h" + +struct feat_print_ops { + void (*select_result)(enum nvme_features_id fid, __u64 result); + void (*show_feature)(enum nvme_features_id fid, int sel, + unsigned int result, void *buf, __u32 data_len); + void (*show_feature_fields)(enum nvme_features_id fid, + unsigned int result, unsigned char *buf); + void (*lba_range)(struct nvme_lba_range_type *lbrt, int nr_ranges); + void (*lba_status_info)(__u64 result); + nvme_print_flags_t flags; +}; + +struct feat_print_ops *feat_get_stdout_print_ops(nvme_print_flags_t flags); +struct feat_print_ops *feat_get_binary_print_ops(nvme_print_flags_t flags); + +#ifdef CONFIG_JSONC +struct feat_print_ops *feat_get_json_print_ops(nvme_print_flags_t flags); +#else +static inline struct feat_print_ops * +feat_get_json_print_ops(nvme_print_flags_t flags) +{ + return NULL; +} +#endif + +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_feature_show_fields(enum nvme_features_id fid, unsigned int result, + unsigned char *buf); +void nvme_show_select_result(enum nvme_features_id fid, __u64 result); +void nvme_show_lba_range(struct nvme_lba_range_type *lbrt, int nr_ranges, + nvme_print_flags_t flags); +void nvme_show_lba_status_info(__u64 result); + +/* The feature fields printers, for the persistent event log of log */ +void stdout_feature_show_fields(enum nvme_features_id fid, unsigned int result, + unsigned char *buf); +#ifdef CONFIG_JSONC +void json_feature_show_fields(enum nvme_features_id fid, unsigned int result, + unsigned char *buf); +#endif + +const char *nvme_feature_to_string(enum nvme_features_id feature); +const char *nvme_select_to_string(int sel); +const char *nvme_feature_lba_type_to_string(__u8 type); +const char *nvme_feature_temp_sel_to_string(__u8 sel); +const char *nvme_feature_temp_type_to_string(__u8 type); +const char *nvme_feature_wl_hints_to_string(__u8 wh); +const char *nvme_feature_perfc_attri_to_string(__u8 attri); +const char *nvme_feature_perfc_r4karl_to_string(__u8 r4karl); +const char *nvme_feature_perfc_attrtyp_to_string(__u8 attrtyp); +const char *nvme_host_metadata_type_to_string(enum nvme_features_id fid, + __u8 type); +const char *nvme_plm_window_to_string(__u32 plm); +const char *nvme_ns_wp_cfg_to_string(enum nvme_ns_write_protect_cfg state); +const char *nvme_pls_mode_to_string(__u8 mode); +const char *nvme_bpwps_to_string(__u8 bpwps); +const char *nvme_power_measurement_action_to_string(__u8 act); + +/* The events of the Asynchronous Event Configuration */ +extern const char *feat_ae_dlpcn; +extern const char *feat_ae_hdlpcn; +extern const char *feat_ae_adlpcn; +extern const char *feat_ae_pmdrlpcn; +extern const char *feat_ae_zdcn; +extern const char *feat_ae_rlccn; +extern const char *feat_ae_lhcn; +extern const char *feat_ae_ccrcn; +extern const char *feat_ae_ansan; +extern const char *feat_ae_rgrp0; +extern const char *feat_ae_rassn; +extern const char *feat_ae_tthry; +extern const char *feat_ae_nnsshdn; +extern const char *feat_ae_ega; +extern const char *feat_ae_lbas; +extern const char *feat_ae_pla; +extern const char *feat_ae_ana; +extern const char *feat_ae_telem; +extern const char *feat_ae_fw; +extern const char *feat_ae_nan; +extern const char *feat_ae_smart; diff --git a/plugins/cmds-feat/meson.build b/plugins/cmds-feat/meson.build new file mode 100644 index 0000000000..43ef716d34 --- /dev/null +++ b/plugins/cmds-feat/meson.build @@ -0,0 +1,22 @@ +# SPDX-License-Identifier: GPL-2.0-or-later + +plugin_name = 'feat' + +plugin_sources += [ + 'plugins/cmds-feat/feat-nvme.c', + 'plugins/cmds-feat/feat-cmds.c', + 'plugins/cmds-feat/feat-print.c', + 'plugins/cmds-feat/feat-print-stdout.c', + 'plugins/cmds-feat/feat-print-binary.c', +] + +if json_c_dep.found() + plugin_sources += [ + 'plugins/cmds-feat/feat-print-json.c', + ] +endif + +plugin_commands = [ + 'get-feature', + 'set-feature', +] diff --git a/plugins/fw/fw-plugin.c b/plugins/cmds-fw/fw-plugin.c similarity index 100% rename from plugins/fw/fw-plugin.c rename to plugins/cmds-fw/fw-plugin.c diff --git a/plugins/io-mgmt/meson.build b/plugins/cmds-fw/meson.build similarity index 54% rename from plugins/io-mgmt/meson.build rename to plugins/cmds-fw/meson.build index ef89cb2aa3..859d2a3113 100644 --- a/plugins/io-mgmt/meson.build +++ b/plugins/cmds-fw/meson.build @@ -1,5 +1,7 @@ # SPDX-License-Identifier: GPL-2.0-or-later +plugin_name = 'fw' + plugin_sources += [ - 'plugins/io-mgmt/io-mgmt-plugin.c', + 'plugins/cmds-fw/fw-plugin.c', ] diff --git a/plugins/id/id-plugin.c b/plugins/cmds-id/id-plugin.c similarity index 100% rename from plugins/id/id-plugin.c rename to plugins/cmds-id/id-plugin.c diff --git a/plugins/id/id-print-binary.c b/plugins/cmds-id/id-print-binary.c similarity index 100% rename from plugins/id/id-print-binary.c rename to plugins/cmds-id/id-print-binary.c diff --git a/plugins/id/id-print-json.c b/plugins/cmds-id/id-print-json.c similarity index 97% rename from plugins/id/id-print-json.c rename to plugins/cmds-id/id-print-json.c index 0e5c79c156..7705b5c4e6 100644 --- a/plugins/id/id-print-json.c +++ b/plugins/cmds-id/id-print-json.c @@ -459,6 +459,26 @@ static void json_nvme_id_ns_descs(void *data, unsigned int nsid) obj_add_array(r, "ns-descs", json_array); } +static void json_id_ctrl_rpmbs(__le32 ctrl_rpmbs) +{ + struct json_object *r = json_root(); + __u32 rpmbs = le32_to_cpu(ctrl_rpmbs); + __u32 asz = (rpmbs & 0xFF000000) >> 24; + __u32 tsz = (rpmbs & 0xFF0000) >> 16; + __u32 rsvd = (rpmbs & 0xFFC0) >> 6; + __u32 auth = (rpmbs & 0x38) >> 3; + __u32 rpmb = rpmbs & 7; + + obj_add_uint_nx(r, "[31:24]: Access Size", asz); + obj_add_uint_nx(r, "[23:16]: Total Size", tsz); + + if (rsvd) + obj_add_uint_nx(r, "[15:6]: Reserved", rsvd); + + obj_add_uint_nx(r, "[5:3]: Authentication Method", auth); + obj_add_uint_nx(r, "[2:0]: Number of RPMB Units", rpmb); +} + static void json_nvme_id_ctrl_nvm(struct nvme_id_ctrl_nvm *ctrl_nvm) { struct json_object *r = json_root(); @@ -756,6 +776,7 @@ static struct id_print_ops id_json_print_ops = { .endurance_group_list = json_nvme_endurance_group_list, .id_ctrl = json_nvme_id_ctrl, .id_ctrl_nvm = json_nvme_id_ctrl_nvm, + .id_ctrl_rpmbs = json_id_ctrl_rpmbs, .id_domain_list = json_id_domain_list, .id_independent_id_ns = json_nvme_cmd_set_independent_id_ns, .id_iocs = json_id_iocs, diff --git a/plugins/id/id-print-stdout.c b/plugins/cmds-id/id-print-stdout.c similarity index 99% rename from plugins/id/id-print-stdout.c rename to plugins/cmds-id/id-print-stdout.c index af95821049..8899121aff 100644 --- a/plugins/id/id-print-stdout.c +++ b/plugins/cmds-id/id-print-stdout.c @@ -704,6 +704,30 @@ static struct shr_table *stdout_id_ctrl_unvmcap_table(__u8 *unvmcap) return t; } +static struct shr_table *stdout_id_ctrl_rpmbs_table(__le32 ctrl_rpmbs) +{ + struct shr_table *t; + __u32 rpmbs = le32_to_cpu(ctrl_rpmbs); + __u32 asz = (rpmbs & 0xFF000000) >> 24; + __u32 tsz = (rpmbs & 0xFF0000) >> 16; + __u32 rsvd = (rpmbs & 0xFFC0) >> 6; + __u32 auth = (rpmbs & 0x38) >> 3; + __u32 rpmb = rpmbs & 0x7; + + t = stdout_bits_table_create(); + if (!t) + return NULL; + + stdout_bits_add(t, "[31:24]", asz, "Access Size"); + stdout_bits_add(t, "[23:16]", tsz, "Total Size"); + if (rsvd) + stdout_bits_add(t, "[15:6]", rsvd, "Reserved"); + stdout_bits_add(t, "[5:3]", auth, "Authentication Method"); + stdout_bits_add(t, "[2:0]", rpmb, "Number of RPMB Units"); + + return t; +} + static struct shr_table *stdout_id_ctrl_dsto_table(__u8 dsto) { struct shr_table *t; @@ -3088,6 +3112,13 @@ static const char *stdout_id_ctrl_nvm_lbamqf_str(__u8 lbamqf) } } +static void stdout_id_ctrl_rpmbs(__le32 ctrl_rpmbs) +{ + stdout_kv_table_finish(stdout_id_ctrl_rpmbs_table(ctrl_rpmbs), + "id-ctrl-rpmbs"); + printf("\n"); +} + static void stdout_id_ctrl_nvm(struct nvme_id_ctrl_nvm *ctrl_nvm) { bool verbose = id_stdout_print_ops.flags & VERBOSE; @@ -3782,6 +3813,7 @@ static struct id_print_ops id_stdout_print_ops = { .endurance_group_list = stdout_endurance_group_list, .id_ctrl = stdout_id_ctrl, .id_ctrl_nvm = stdout_id_ctrl_nvm, + .id_ctrl_rpmbs = stdout_id_ctrl_rpmbs, .id_domain_list = stdout_id_domain_list, .id_independent_id_ns = stdout_cmd_set_independent_id_ns, .id_iocs = stdout_id_iocs, diff --git a/plugins/id/id-print.c b/plugins/cmds-id/id-print.c similarity index 96% rename from plugins/id/id-print.c rename to plugins/cmds-id/id-print.c index 2dbdcc7232..53f733db4d 100644 --- a/plugins/id/id-print.c +++ b/plugins/cmds-id/id-print.c @@ -71,6 +71,11 @@ void nvme_show_id_ctrl_nvm(struct nvme_id_ctrl_nvm *ctrl_nvm, id_print(id_ctrl_nvm, flags, ctrl_nvm); } +void nvme_show_id_ctrl_rpmbs(__le32 ctrl_rpmbs, nvme_print_flags_t flags) +{ + id_print(id_ctrl_rpmbs, flags, ctrl_rpmbs); +} + void nvme_show_nvm_id_ns(struct nvme_nvm_id_ns *nvm_ns, unsigned int nsid, struct nvme_id_ns *ns, unsigned int lba_index, bool cap_only, nvme_print_flags_t flags) diff --git a/plugins/id/id-print.h b/plugins/cmds-id/id-print.h similarity index 98% rename from plugins/id/id-print.h rename to plugins/cmds-id/id-print.h index 7e3621749f..60da503a88 100644 --- a/plugins/id/id-print.h +++ b/plugins/cmds-id/id-print.h @@ -14,6 +14,7 @@ struct id_print_ops { void (*id_ctrl)(struct nvme_id_ctrl *ctrl, const char *product_name, void (*vs)(__u8 *vs, struct json_object *root)); void (*id_ctrl_nvm)(struct nvme_id_ctrl_nvm *ctrl_nvm); + void (*id_ctrl_rpmbs)(__le32 ctrl_rpmbs); void (*id_domain_list)(struct nvme_id_domain_list *id_dom); void (*id_independent_id_ns)(struct nvme_id_independent_id_ns *ns, unsigned int nsid); diff --git a/plugins/id/id.h b/plugins/cmds-id/id.h similarity index 84% rename from plugins/id/id.h rename to plugins/cmds-id/id.h index fdb193a489..4356ab9e7f 100644 --- a/plugins/id/id.h +++ b/plugins/cmds-id/id.h @@ -23,3 +23,5 @@ void nvme_show_id_ctrl(struct libnvme_global_ctx *ctx, struct libnvme_transport_handle *hdl, struct nvme_id_ctrl *ctrl, nvme_print_flags_t flags, void (*vendor_show)(__u8 *vs, struct json_object *root)); +/* Show the RPMB Support field of Identify Controller */ +void nvme_show_id_ctrl_rpmbs(__le32 ctrl_rpmbs, nvme_print_flags_t flags); diff --git a/plugins/cmds-id/meson.build b/plugins/cmds-id/meson.build new file mode 100644 index 0000000000..fc08ee34b2 --- /dev/null +++ b/plugins/cmds-id/meson.build @@ -0,0 +1,17 @@ +# SPDX-License-Identifier: GPL-2.0-or-later + +plugin_name = 'id' + +plugin_sources += [ + 'plugins/cmds-id/id-plugin.c', + 'plugins/cmds-id/nvme-models.c', + 'plugins/cmds-id/id-print.c', + 'plugins/cmds-id/id-print-stdout.c', + 'plugins/cmds-id/id-print-binary.c', +] + +if json_c_dep.found() + plugin_sources += [ + 'plugins/cmds-id/id-print-json.c', + ] +endif diff --git a/plugins/id/nvme-models.c b/plugins/cmds-id/nvme-models.c similarity index 100% rename from plugins/id/nvme-models.c rename to plugins/cmds-id/nvme-models.c diff --git a/plugins/id/nvme-models.h b/plugins/cmds-id/nvme-models.h similarity index 100% rename from plugins/id/nvme-models.h rename to plugins/cmds-id/nvme-models.h diff --git a/plugins/io-mgmt/io-mgmt-plugin.c b/plugins/cmds-io-mgmt/io-mgmt-plugin.c similarity index 100% rename from plugins/io-mgmt/io-mgmt-plugin.c rename to plugins/cmds-io-mgmt/io-mgmt-plugin.c diff --git a/plugins/cmds-io-mgmt/meson.build b/plugins/cmds-io-mgmt/meson.build new file mode 100644 index 0000000000..5d2ba5a1e7 --- /dev/null +++ b/plugins/cmds-io-mgmt/meson.build @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: GPL-2.0-or-later + +plugin_name = 'io-mgmt' + +plugin_sources += [ + 'plugins/cmds-io-mgmt/io-mgmt-plugin.c', +] diff --git a/src/nvme-cmds-io.c b/plugins/cmds-io/cmds-io-plugin.c similarity index 99% rename from src/nvme-cmds-io.c rename to plugins/cmds-io/cmds-io-plugin.c index 0c803aa5c4..dfe9baeb34 100644 --- a/src/nvme-cmds-io.c +++ b/plugins/cmds-io/cmds-io-plugin.c @@ -43,6 +43,7 @@ #include "argconfig.h" #include "cleanup.h" +#include "cmds-io-print.h" #include "global-ctx.h" #include "nvme-errno.h" #include "nvme-print.h" @@ -1704,7 +1705,7 @@ static struct command *commands[] = { NULL, }; -static void __shr_constructor register_group(void) +NVME_PLUGIN_INIT(register_plugin) { plugin_add_group(&builtin, "I/O Commands", commands); } diff --git a/plugins/cmds-io/cmds-io-print-binary.c b/plugins/cmds-io/cmds-io-print-binary.c new file mode 100644 index 0000000000..3ee461cf18 --- /dev/null +++ b/plugins/cmds-io/cmds-io-print-binary.c @@ -0,0 +1,21 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include + +#include "cmds-io-print.h" +#include "nvme-print.h" + +static void binary_lba_status(struct nvme_lba_status *list, unsigned long len) +{ + d_raw((unsigned char *)list, len); +} + +static struct cmds_io_print_ops cmds_io_binary_print_ops = { + .lba_status = binary_lba_status, +}; + +struct cmds_io_print_ops *cmds_io_get_binary_print_ops(nvme_print_flags_t flags) +{ + cmds_io_binary_print_ops.flags = flags; + return &cmds_io_binary_print_ops; +} diff --git a/plugins/cmds-io/cmds-io-print-json.c b/plugins/cmds-io/cmds-io-print-json.c new file mode 100644 index 0000000000..99e68a92d0 --- /dev/null +++ b/plugins/cmds-io/cmds-io-print-json.c @@ -0,0 +1,68 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include + +#include + +#include + +#include "cmds-io-print.h" +#include "nvme-print.h" +#include "nvme-print-json.h" + +static void json_lba_status(struct nvme_lba_status *list, + unsigned long len) +{ + struct json_object *r = json_root(); + __u32 nlsd = le32_to_cpu(list->nlsd); + size_t nr = nvme_log_nr_entries(nlsd, len, sizeof(*list), + sizeof(list->descs[0])); + size_t idx; + struct nvme_lba_status_desc *e; + struct json_object *lsde; + char json_str[STR_LEN]; + + obj_add_uint(r, "Number of LBA Status Descriptors (NLSD)", nlsd); + obj_add_uint(r, "Completion Condition (CMPC)", list->cmpc); + + switch (list->cmpc) { + case NVME_LBA_STATUS_CMPC_NO_CMPC: + obj_add_str(r, "cmpc-definition", + "No indication of the completion condition"); + break; + case NVME_LBA_STATUS_CMPC_INCOMPLETE: + obj_add_str(r, "cmpc-definition", + "Completed transferring the amount of data specified in theMNDW field. But, additional LBA Status Descriptor Entries areavailable to transfer or scan did not complete (if ATYPE = 10h)"); + break; + case NVME_LBA_STATUS_CMPC_COMPLETE: + obj_add_str(r, "cmpc-definition", + "Completed the specified action over the number of LBAs specifiedin the Range Length field and transferred all available LBA StatusDescriptor Entries"); + break; + default: + break; + } + + for (idx = 0; idx < nr; idx++) { + lsde = json_create_object(); + sprintf(json_str, "LSD entry %zu", idx); + obj_add_obj(r, json_str, lsde); + e = &list->descs[idx]; + sprintf(json_str, "0x%016"PRIx64"", le64_to_cpu(e->dslba)); + obj_add_str(lsde, "DSLBA", json_str); + sprintf(json_str, "0x%08x", le32_to_cpu(e->nlb)); + obj_add_str(lsde, "NLB", json_str); + sprintf(json_str, "0x%02x", e->status); + obj_add_str(lsde, "status", json_str); + } +} + +static struct cmds_io_print_ops cmds_io_json_print_ops = { + .lba_status = json_lba_status, +}; + +struct cmds_io_print_ops *cmds_io_get_json_print_ops(nvme_print_flags_t flags) +{ + cmds_io_json_print_ops.flags = flags; + return &cmds_io_json_print_ops; +} diff --git a/plugins/cmds-io/cmds-io-print-stdout.c b/plugins/cmds-io/cmds-io-print-stdout.c new file mode 100644 index 0000000000..3cb334592b --- /dev/null +++ b/plugins/cmds-io/cmds-io-print-stdout.c @@ -0,0 +1,96 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include + +#include + +#include +#include +#include + +#include "cmds-io-print.h" +#include "nvme-print.h" +#include "nvme-print-stdout.h" + +static void stdout_lba_status(struct nvme_lba_status *list, + unsigned long len) +{ + struct shr_table_column columns[] = { + { "DSLBA", LEFT, AUTO_WIDTH }, + { "NLB", LEFT, AUTO_WIDTH }, + { "Status", LEFT, AUTO_WIDTH }, + }; + struct shr_table *t; + __u32 nlsd = le32_to_cpu(list->nlsd); + size_t nr = nvme_log_nr_entries(nlsd, len, sizeof(*list), + sizeof(list->descs[0])); + size_t idx; + int row; + + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, "Number of LBA Status Descriptors(NLSD)", "%"PRIu32, + nlsd); + stdout_kv_add(t, "Completion Condition(CMPC)", "%u", list->cmpc); + + stdout_kv_table_finish(t, "lba-status"); + + switch (list->cmpc) { + case NVME_LBA_STATUS_CMPC_NO_CMPC: + printf("\tNo indication of the completion condition\n"); + break; + case NVME_LBA_STATUS_CMPC_INCOMPLETE: + printf("%s%s%s", + "\tCompleted transferring the amount of data specified in the\n", + "\tMNDW field. But, additional LBA Status Descriptor Entries are\n", + "\tavailable to transfer or scan did not complete (if ATYPE = 10h)\n"); + break; + case NVME_LBA_STATUS_CMPC_COMPLETE: + printf("%s%s%s", + "\tCompleted the specified action over the number of LBAs specified\n", + "\tin the Range Length field and transferred all available LBA Status\n", + "\tDescriptor Entries\n"); + break; + default: + break; + } + + if (!nr) + return; + + t = shr_table_init_with_columns(columns, ARRAY_SIZE(columns)); + if (!t) + return; + + for (idx = 0; idx < nr; idx++) { + struct nvme_lba_status_desc *e = &list->descs[idx]; + char dslba[24], nlb[16], status[8]; + + snprintf(dslba, sizeof(dslba), "%#016"PRIx64, + le64_to_cpu(e->dslba)); + snprintf(nlb, sizeof(nlb), "%#08x", le32_to_cpu(e->nlb)); + snprintf(status, sizeof(status), "%#02x", e->status); + + row = shr_table_get_row_id(t); + shr_table_set_value_str(t, 0, row, dslba, LEFT); + shr_table_set_value_str(t, 1, row, nlb, LEFT); + shr_table_set_value_str(t, 2, row, status, LEFT); + shr_table_add_row(t, row); + } + + shr_table_print(t); + shr_table_free(t); +} + +static struct cmds_io_print_ops cmds_io_stdout_print_ops = { + .lba_status = stdout_lba_status, +}; + +struct cmds_io_print_ops *cmds_io_get_stdout_print_ops(nvme_print_flags_t flags) +{ + cmds_io_stdout_print_ops.flags = flags; + return &cmds_io_stdout_print_ops; +} diff --git a/plugins/cmds-io/cmds-io-print.c b/plugins/cmds-io/cmds-io-print.c new file mode 100644 index 0000000000..c4e508bae1 --- /dev/null +++ b/plugins/cmds-io/cmds-io-print.c @@ -0,0 +1,40 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include + +#include "cmds-io-print.h" +#include "nvme-print.h" + +/* + * Run the printers in the sandbox. Like nvme_print(), silently skip + * printers that an output format does not implement. + */ +#define cmds_io_print(name, flags, ...) \ + do { \ + struct cmds_io_print_ops *ops = \ + cmds_io_print_ops(flags); \ + \ + if (ops && ops->name) \ + nvme_print_decoder(ops, name, true, flags, \ + ##__VA_ARGS__); \ + } while (false) + +static struct cmds_io_print_ops *cmds_io_print_ops(nvme_print_flags_t flags) +{ + struct cmds_io_print_ops *ops = NULL; + + if (flags & JSON || nvme_is_output_format_json()) + ops = cmds_io_get_json_print_ops(flags); + else if (flags & BINARY) + ops = cmds_io_get_binary_print_ops(flags); + else + ops = cmds_io_get_stdout_print_ops(flags); + + return ops; +} + +void nvme_show_lba_status(struct nvme_lba_status *list, unsigned long len, + nvme_print_flags_t flags) +{ + cmds_io_print(lba_status, flags, list, len); +} diff --git a/plugins/cmds-io/cmds-io-print.h b/plugins/cmds-io/cmds-io-print.h new file mode 100644 index 0000000000..63eb3c71b4 --- /dev/null +++ b/plugins/cmds-io/cmds-io-print.h @@ -0,0 +1,29 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#pragma once + +#include + +#include "args.h" + +struct cmds_io_print_ops { + void (*lba_status)(struct nvme_lba_status *list, unsigned long len); + nvme_print_flags_t flags; +}; + +struct cmds_io_print_ops * +cmds_io_get_stdout_print_ops(nvme_print_flags_t flags); +struct cmds_io_print_ops * +cmds_io_get_binary_print_ops(nvme_print_flags_t flags); + +#ifdef CONFIG_JSONC +struct cmds_io_print_ops *cmds_io_get_json_print_ops(nvme_print_flags_t flags); +#else +static inline struct cmds_io_print_ops * +cmds_io_get_json_print_ops(nvme_print_flags_t flags) +{ + return NULL; +} +#endif + +void nvme_show_lba_status(struct nvme_lba_status *list, unsigned long len, + nvme_print_flags_t flags); diff --git a/plugins/cmds-io/meson.build b/plugins/cmds-io/meson.build new file mode 100644 index 0000000000..f11431e04e --- /dev/null +++ b/plugins/cmds-io/meson.build @@ -0,0 +1,32 @@ +# SPDX-License-Identifier: GPL-2.0-or-later +# +# The I/O commands. plugins/meson.build always builds this plugin. + +plugin_extension = false + +plugin_sources += [ + 'plugins/cmds-io/cmds-io-plugin.c', + 'plugins/cmds-io/cmds-io-print.c', + 'plugins/cmds-io/cmds-io-print-stdout.c', + 'plugins/cmds-io/cmds-io-print-binary.c', +] + +if json_c_dep.found() + plugin_sources += [ + 'plugins/cmds-io/cmds-io-print-json.c', + ] +endif + +plugin_commands = [ + 'dsm', + 'copy', + 'flush', + 'compare', + 'read', + 'write', + 'write-zeroes', + 'write-uncor', + 'verify', + 'get-lba-status', + 'capacity-mgmt', +] diff --git a/plugins/keys/keys-plugin.c b/plugins/cmds-keys/keys-plugin.c similarity index 100% rename from plugins/keys/keys-plugin.c rename to plugins/cmds-keys/keys-plugin.c diff --git a/plugins/config/meson.build b/plugins/cmds-keys/meson.build similarity index 59% rename from plugins/config/meson.build rename to plugins/cmds-keys/meson.build index 9a00896d59..af64ed6ad2 100644 --- a/plugins/config/meson.build +++ b/plugins/cmds-keys/meson.build @@ -1,7 +1,9 @@ # SPDX-License-Identifier: GPL-2.0-or-later +plugin_name = 'keys' + if want_fabrics plugin_sources += [ - 'plugins/config/config-nvme.c', + 'plugins/cmds-keys/keys-plugin.c', ] endif diff --git a/src/nvme-cmds-enumerate.c b/plugins/cmds-list/cmds-list-plugin.c similarity index 98% rename from src/nvme-cmds-enumerate.c rename to plugins/cmds-list/cmds-list-plugin.c index 53b2233a55..49cd57680d 100644 --- a/src/nvme-cmds-enumerate.c +++ b/plugins/cmds-list/cmds-list-plugin.c @@ -20,7 +20,6 @@ #include -#include #include #include "argconfig.h" @@ -28,6 +27,7 @@ #include "global-ctx.h" #include "logging.h" #include "nvme-cmds-common.h" +#include "cmds-list-print.h" #include "nvme-print.h" #include "plugin.h" @@ -293,7 +293,7 @@ static struct command *commands[] = { NULL, }; -static void __shr_constructor register_group(void) +NVME_PLUGIN_INIT(register_plugin) { plugin_add_group(&builtin, "Device Enumeration", commands); } diff --git a/plugins/cmds-list/cmds-list-print-json.c b/plugins/cmds-list/cmds-list-print-json.c new file mode 100644 index 0000000000..5bdacc77ee --- /dev/null +++ b/plugins/cmds-list/cmds-list-print-json.c @@ -0,0 +1,1055 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include + +#include + +#include + +#include "cleanup.h" +#include "cmds-list-print.h" +#include "global-ctx.h" +#include "nvme-iostat.h" +#include "nvme-json.h" +#include "nvme-print.h" +#include "nvme-print-json.h" + +#define NAME_LEN 128 + +static struct cmds_list_print_ops json_list_print_ops; + +static bool verbose_mode(void) +{ + return json_list_print_ops.flags & VERBOSE; +} + +static void obj_add_ctrl_address(struct json_object *o, struct libnvme_ctrl *c) +{ + const char *address = libnvme_ctrl_get_address(c); + + /* controllers without an address, e.g. loop, don't report one */ + obj_add_str(o, "Address", address ? address : ""); +} + +static void obj_add_ctrl_address_details(struct json_object *o, const char *k, + struct libnvme_ctrl *c) +{ + struct json_object *address_details = json_create_object(); + const char *value; + bool has_value = false; + + value = libnvme_ctrl_get_traddr(c); + if (value) { + obj_add_str(address_details, "traddr", value); + has_value = true; + } + + value = libnvme_ctrl_get_host_traddr(c); + if (value) { + obj_add_str(address_details, "host_traddr", value); + has_value = true; + } + + value = libnvme_ctrl_get_host_iface(c); + if (value) { + obj_add_str(address_details, "host_iface", value); + has_value = true; + } + + value = libnvme_ctrl_get_trsvcid(c); + if (value) { + obj_add_str(address_details, "trsvcid", value); + has_value = true; + } + + if (!has_value) { + json_free_object(address_details); + return; + } + + obj_add_obj(o, k, address_details); +} + + +static unsigned int +json_print_nvme_subsystem_multipath(struct libnvme_subsystem *s, + json_object *paths) +{ + struct libnvme_ns *n; + struct libnvme_path *p; + unsigned int i = 0; + + n = libnvme_subsystem_first_ns(s); + if (!n) + return 0; + + libnvme_namespace_for_each_path(n, p) { + struct json_object *path_attrs; + struct libnvme_ctrl *c = libnvme_path_get_ctrl(p); + const char *ana_state; + + libnvme_path_get_ana_state(p, &ana_state, ""); + path_attrs = json_create_object(); + obj_add_str(path_attrs, "Name", libnvme_ctrl_get_name(c)); + obj_add_str(path_attrs, "Transport", + libnvme_ctrl_get_transport(c)); + obj_add_ctrl_address(path_attrs, c); + obj_add_ctrl_address_details(path_attrs, "AddressDetails", c); + obj_add_str(path_attrs, "State", libnvme_ctrl_get_state(c)); + obj_add_str(path_attrs, "ANAState", ana_state); + array_add_obj(paths, path_attrs); + i++; + } + + return i; +} + +static void json_print_nvme_subsystem_ctrls(struct libnvme_subsystem *s, + json_object *paths) +{ + struct libnvme_ctrl *c; + + libnvme_subsystem_for_each_ctrl(s, c) { + struct json_object *path_attrs; + + path_attrs = json_create_object(); + obj_add_str(path_attrs, "Name", libnvme_ctrl_get_name(c)); + obj_add_str(path_attrs, "Transport", + libnvme_ctrl_get_transport(c)); + obj_add_ctrl_address(path_attrs, c); + obj_add_ctrl_address_details(path_attrs, "AddressDetails", c); + obj_add_str(path_attrs, "State", libnvme_ctrl_get_state(c)); + array_add_obj(paths, path_attrs); + } +} + +static void json_print_nvme_subsystem_list(struct libnvme_global_ctx *ctx, + bool show_ana) +{ + struct json_object *host_attrs, *subsystem_attrs; + struct json_object *subsystems, *paths; + struct json_object *a = json_create_array(); + struct libnvme_host *h; + + libnvme_for_each_host(ctx, h) { + struct libnvme_subsystem *s; + const char *hostid; + + host_attrs = json_create_object(); + obj_add_str(host_attrs, "HostNQN", libnvme_host_get_hostnqn(h)); + hostid = libnvme_host_get_hostid(h); + if (hostid) + obj_add_str(host_attrs, "HostID", hostid); + subsystems = json_create_array(); + libnvme_for_each_subsystem(h, s) { + struct libnvme_ctrl *c; + bool no_ctrl = true; + + libnvme_subsystem_for_each_ctrl(s, c) + no_ctrl = false; + if (no_ctrl) + continue; + + subsystem_attrs = json_create_object(); + obj_add_str(subsystem_attrs, "Name", + libnvme_subsystem_get_name(s)); + obj_add_str(subsystem_attrs, "NQN", + libnvme_subsystem_get_subsysnqn(s)); + + if (verbose_mode()) { + const char *model; + const char *serial; + const char *firmware; + const char *iopolicy; + + libnvme_subsystem_get_model(s, &model, ""); + libnvme_subsystem_get_serial(s, &serial, ""); + libnvme_subsystem_get_firmware(s, &firmware, + ""); + libnvme_subsystem_get_iopolicy(s, &iopolicy, + ""); + + obj_add_str(subsystem_attrs, "Model", model); + obj_add_str(subsystem_attrs, "Serial", serial); + obj_add_str(subsystem_attrs, "Firmware", + firmware); + obj_add_str(subsystem_attrs, "IOPolicy", + iopolicy); + obj_add_str(subsystem_attrs, "Type", + libnvme_subsystem_get_subsystype(s)); + } + + array_add_obj(subsystems, subsystem_attrs); + paths = json_create_array(); + + if (!show_ana || + !json_print_nvme_subsystem_multipath(s, paths)) + json_print_nvme_subsystem_ctrls(s, paths); + + obj_add_array(subsystem_attrs, "Paths", paths); + } + obj_add_array(host_attrs, "Subsystems", subsystems); + array_add_obj(a, host_attrs); + } + + json_print(a); +} + +static void json_print_detail_list_multipath(struct libnvme_subsystem *s, + struct json_object *jss) +{ + struct libnvme_ns *n; + struct libnvme_path *p; + struct json_object *jnss = json_create_array(); + + libnvme_subsystem_for_each_ns(s, n) { + struct json_object *jns = json_create_object(); + struct json_object *jpaths = json_create_array(); + int lba; + uint64_t lba_count, nsze, nuse; + + libnvme_ns_get_lba_size(n, &lba, 0); + libnvme_ns_get_lba_count(n, &lba_count, 0); + nsze = lba_count * lba; + libnvme_ns_get_lba_util(n, &nuse, 0); + nuse *= lba; + + obj_add_str(jns, "NameSpace", libnvme_ns_get_name(n)); + obj_add_str(jns, "Generic", libnvme_ns_get_generic_name(n)); + obj_add_int(jns, "NSID", libnvme_ns_get_nsid(n)); + obj_add_uint64(jns, "UsedBytes", nuse); + obj_add_uint64(jns, "MaximumLBA", lba_count); + obj_add_uint64(jns, "PhysicalSize", nsze); + obj_add_int(jns, "SectorSize", lba); + + libnvme_namespace_for_each_path(n, p) { + struct libnvme_ctrl *c; + struct json_object *jpath = json_create_object(); + const char *slot; + const char *cntlid; + const char *serial; + const char *model; + const char *firmware; + const char *ana_state; + + libnvme_path_get_ana_state(p, &ana_state, ""); + obj_add_str(jpath, "Path", libnvme_path_get_name(p)); + obj_add_str(jpath, "ANAState", ana_state); + + /* + * For multipath, each path maps to one controller. + * So get the controller from the path and then add + * controller attributes. + */ + c = libnvme_path_get_ctrl(p); + libnvme_ctrl_get_phy_slot(c, &slot, ""); + libnvme_ctrl_get_cntlid(c, &cntlid, ""); + libnvme_ctrl_get_serial(c, &serial, ""); + libnvme_ctrl_get_model(c, &model, ""); + libnvme_ctrl_get_firmware(c, &firmware, ""); + obj_add_str(jpath, "Controller", + libnvme_ctrl_get_name(c)); + obj_add_str(jpath, "Cntlid", cntlid); + obj_add_str(jpath, "SerialNumber", serial); + obj_add_str(jpath, "ModelNumber", model); + obj_add_str(jpath, "Firmware", firmware); + obj_add_str(jpath, "Transport", + libnvme_ctrl_get_transport(c)); + obj_add_ctrl_address(jpath, c); + obj_add_ctrl_address_details(jpath, "AddressDetails", + c); + obj_add_str(jpath, "Slot", slot ? slot : ""); + + array_add_obj(jpaths, jpath); + } + + obj_add_obj(jns, "Paths", jpaths); + array_add_obj(jnss, jns); + } + obj_add_obj(jss, "Namespaces", jnss); +} + +static void json_print_detail_list(struct libnvme_subsystem *s, + struct json_object *jss) +{ + struct libnvme_ctrl *c; + struct libnvme_ns *n; + struct json_object *jctrls = json_create_array(); + + libnvme_subsystem_for_each_ctrl(s, c) { + struct json_object *jctrl = json_create_object(); + struct json_object *jnss = json_create_array(); + const char *slot; + const char *cntlid; + const char *serial; + const char *model; + const char *firmware; + + libnvme_ctrl_get_phy_slot(c, &slot, ""); + libnvme_ctrl_get_cntlid(c, &cntlid, ""); + libnvme_ctrl_get_serial(c, &serial, ""); + libnvme_ctrl_get_model(c, &model, ""); + libnvme_ctrl_get_firmware(c, &firmware, ""); + + obj_add_str(jctrl, "Controller", libnvme_ctrl_get_name(c)); + obj_add_str(jctrl, "Cntlid", cntlid); + obj_add_str(jctrl, "SerialNumber", serial); + obj_add_str(jctrl, "ModelNumber", model); + obj_add_str(jctrl, "Firmware", firmware); + obj_add_str(jctrl, "Transport", libnvme_ctrl_get_transport(c)); + obj_add_ctrl_address(jctrl, c); + obj_add_ctrl_address_details(jctrl, "AddressDetails", c); + obj_add_str(jctrl, "Slot", slot ? slot : ""); + + libnvme_ctrl_for_each_ns(c, n) { + struct json_object *jns = json_create_object(); + int lba; + uint64_t lba_count, nsze, nuse; + + libnvme_ns_get_lba_size(n, &lba, 0); + libnvme_ns_get_lba_count(n, &lba_count, 0); + nsze = lba_count * lba; + libnvme_ns_get_lba_util(n, &nuse, 0); + nuse *= lba; + + obj_add_str(jns, "NameSpace", libnvme_ns_get_name(n)); + obj_add_str(jns, "Generic", + libnvme_ns_get_generic_name(n)); + obj_add_int(jns, "NSID", libnvme_ns_get_nsid(n)); + obj_add_uint64(jns, "UsedBytes", nuse); + obj_add_uint64(jns, "MaximumLBA", lba_count); + obj_add_uint64(jns, "PhysicalSize", nsze); + obj_add_int(jns, "SectorSize", lba); + + array_add_obj(jnss, jns); + } + + obj_add_obj(jctrl, "Namespaces", jnss); + array_add_obj(jctrls, jctrl); + } + + obj_add_obj(jss, "Controllers", jctrls); +} + +static void json_detail_list_v2(struct libnvme_global_ctx *ctx) +{ + struct json_object *r = json_root(); + struct json_object *jdev = json_create_array(); + + struct libnvme_host *h; + struct libnvme_subsystem *s; + + libnvme_for_each_host(ctx, h) { + struct json_object *hss = json_create_object(); + struct json_object *jsslist = json_create_array(); + const char *hostid; + + obj_add_str(hss, "HostNQN", libnvme_host_get_hostnqn(h)); + hostid = libnvme_host_get_hostid(h); + if (hostid) + obj_add_str(hss, "HostID", hostid); + + libnvme_for_each_subsystem(h, s) { + struct json_object *jss = json_create_object(); + + obj_add_str(jss, "Subsystem", + libnvme_subsystem_get_name(s)); + obj_add_str(jss, "SubsystemNQN", + libnvme_subsystem_get_subsysnqn(s)); + + if (nvme_is_multipath(s)) + json_print_detail_list_multipath(s, jss); + else + json_print_detail_list(s, jss); + + array_add_obj(jsslist, jss); + } + + obj_add_obj(hss, "Subsystems", jsslist); + array_add_obj(jdev, hss); + } + + obj_add_array(r, "Devices", jdev); +} + +static void json_detail_list(struct libnvme_global_ctx *ctx) +{ + struct json_object *r = json_root(); + struct json_object *jdev = json_create_array(); + + struct libnvme_host *h; + struct libnvme_subsystem *s; + struct libnvme_ctrl *c; + struct libnvme_path *p; + struct libnvme_ns *n; + + libnvme_for_each_host(ctx, h) { + struct json_object *hss = json_create_object(); + struct json_object *jsslist = json_create_array(); + const char *hostid; + + obj_add_str(hss, "HostNQN", libnvme_host_get_hostnqn(h)); + hostid = libnvme_host_get_hostid(h); + if (hostid) + obj_add_str(hss, "HostID", hostid); + + libnvme_for_each_subsystem(h, s) { + struct json_object *jss = json_create_object(); + struct json_object *jctrls = json_create_array(); + struct json_object *jnss = json_create_array(); + + obj_add_str(jss, "Subsystem", + libnvme_subsystem_get_name(s)); + obj_add_str(jss, "SubsystemNQN", + libnvme_subsystem_get_subsysnqn(s)); + + libnvme_subsystem_for_each_ctrl(s, c) { + struct json_object *jctrl = + json_create_object(); + struct json_object *jnss = json_create_array(); + struct json_object *jpaths = + json_create_array(); + const char *cntlid; + const char *serial; + const char *model; + const char *firmware; + const char *slot; + + libnvme_ctrl_get_cntlid(c, &cntlid, ""); + libnvme_ctrl_get_serial(c, &serial, ""); + libnvme_ctrl_get_model(c, &model, ""); + libnvme_ctrl_get_firmware(c, &firmware, ""); + libnvme_ctrl_get_phy_slot(c, &slot, ""); + + obj_add_str(jctrl, "Controller", + libnvme_ctrl_get_name(c)); + obj_add_str(jctrl, "Cntlid", cntlid); + obj_add_str(jctrl, "SerialNumber", serial); + obj_add_str(jctrl, "ModelNumber", model); + obj_add_str(jctrl, "Firmware", firmware); + obj_add_str(jctrl, "Transport", + libnvme_ctrl_get_transport(c)); + obj_add_ctrl_address(jctrl, c); + obj_add_ctrl_address_details(jctrl, + "AddressDetails", + c); + obj_add_str(jctrl, "Slot", slot); + + libnvme_ctrl_for_each_ns(c, n) { + struct json_object *jns = + json_create_object(); + int lba; + uint64_t lba_count, nsze, nuse; + + libnvme_ns_get_lba_size(n, &lba, 0); + libnvme_ns_get_lba_count(n, + &lba_count, 0); + nsze = lba_count * lba; + libnvme_ns_get_lba_util(n, &nuse, 0); + nuse *= lba; + + obj_add_str(jns, "NameSpace", + libnvme_ns_get_name(n)); + obj_add_str(jns, "Generic", + libnvme_ns_get_generic_name(n)); + obj_add_int(jns, "NSID", + libnvme_ns_get_nsid(n)); + obj_add_uint64(jns, "UsedBytes", nuse); + obj_add_uint64(jns, "MaximumLBA", + lba_count); + obj_add_uint64(jns, "PhysicalSize", + nsze); + obj_add_int(jns, "SectorSize", lba); + + array_add_obj(jnss, jns); + } + obj_add_obj(jctrl, "Namespaces", jnss); + + libnvme_ctrl_for_each_path(c, p) { + struct json_object *jpath = + json_create_object(); + const char *ana_state; + + libnvme_path_get_ana_state(p, + &ana_state, ""); + obj_add_str(jpath, "Path", + libnvme_path_get_name(p)); + obj_add_str(jpath, "ANAState", + ana_state); + + array_add_obj(jpaths, jpath); + } + obj_add_obj(jctrl, "Paths", jpaths); + + array_add_obj(jctrls, jctrl); + } + obj_add_obj(jss, "Controllers", jctrls); + + libnvme_subsystem_for_each_ns(s, n) { + struct json_object *jns = json_create_object(); + int lba; + uint64_t lba_count, nsze, nuse; + + libnvme_ns_get_lba_size(n, &lba, 0); + libnvme_ns_get_lba_count(n, &lba_count, 0); + nsze = lba_count * lba; + libnvme_ns_get_lba_util(n, &nuse, 0); + nuse *= lba; + + obj_add_str(jns, "NameSpace", + libnvme_ns_get_name(n)); + obj_add_str(jns, "Generic", + libnvme_ns_get_generic_name(n)); + obj_add_int(jns, "NSID", + libnvme_ns_get_nsid(n)); + obj_add_uint64(jns, "UsedBytes", nuse); + obj_add_uint64(jns, "MaximumLBA", lba_count); + obj_add_uint64(jns, "PhysicalSize", nsze); + obj_add_int(jns, "SectorSize", lba); + + array_add_obj(jnss, jns); + } + obj_add_obj(jss, "Namespaces", jnss); + + array_add_obj(jsslist, jss); + } + + obj_add_obj(hss, "Subsystems", jsslist); + array_add_obj(jdev, hss); + } + + obj_add_array(r, "Devices", jdev); +} + +static struct json_object *json_list_item_obj(struct libnvme_ns *n) +{ + struct json_object *r = json_create_object(); + char devname[NAME_LEN] = { 0 }; + char genname[NAME_LEN] = { 0 }; + int lba; + uint64_t lba_count, nsze, nuse; + + libnvme_ns_get_lba_size(n, &lba, 0); + libnvme_ns_get_lba_count(n, &lba_count, 0); + nsze = lba_count * lba; + libnvme_ns_get_lba_util(n, &nuse, 0); + nuse *= lba; + + nvme_dev_full_path(n, devname, sizeof(devname)); + nvme_generic_full_path(n, genname, sizeof(genname)); + + obj_add_int(r, "NameSpace", libnvme_ns_get_nsid(n)); + obj_add_str(r, "DevicePath", devname); + obj_add_str(r, "GenericPath", genname); + obj_add_str(r, "Firmware", libnvme_ns_get_firmware(n)); + obj_add_str(r, "ModelNumber", libnvme_ns_get_model(n)); + obj_add_str(r, "SerialNumber", libnvme_ns_get_serial(n)); + obj_add_uint64(r, "UsedBytes", nuse); + obj_add_uint64(r, "MaximumLBA", lba_count); + obj_add_uint64(r, "PhysicalSize", nsze); + obj_add_int(r, "SectorSize", lba); + + return r; +} + +static void json_simple_list(struct libnvme_global_ctx *ctx) +{ + struct json_object *r = json_root(); + struct json_object *jdevices = json_create_array(); + + struct libnvme_host *h; + struct libnvme_subsystem *s; + struct libnvme_ctrl *c; + struct libnvme_ns *n; + + libnvme_for_each_host(ctx, h) { + libnvme_for_each_subsystem(h, s) { + libnvme_subsystem_for_each_ns(s, n) + array_add_obj(jdevices, json_list_item_obj(n)); + + libnvme_subsystem_for_each_ctrl(s, c) { + libnvme_ctrl_for_each_ns(c, n) + array_add_obj(jdevices, + json_list_item_obj(n)); + } + } + } + + obj_add_array(r, "Devices", jdevices); +} + +static void json_list_item(struct libnvme_ns *n, struct shr_table *t) +{ + struct json_object *r = json_list_item_obj(n); + + json_print(r); +} + +static void json_print_list_items(struct libnvme_global_ctx *ctx) +{ + if (json_list_print_ops.flags & VERBOSE) { + if (nvme_args.output_format_ver == 2) + json_detail_list_v2(ctx); + else + json_detail_list(ctx); + } else + json_simple_list(ctx); +} + +static unsigned int +json_subsystem_topology_multipath(struct libnvme_subsystem *s, + json_object *namespaces) +{ + struct libnvme_ns *n; + struct libnvme_path *p; + unsigned int i = 0; + const char *iopolicy; + + libnvme_subsystem_get_iopolicy(s, &iopolicy, ""); + + libnvme_subsystem_for_each_ns(s, n) { + struct json_object *ns_attrs; + struct json_object *paths; + + ns_attrs = json_create_object(); + obj_add_int(ns_attrs, "NSID", libnvme_ns_get_nsid(n)); + obj_add_str(ns_attrs, "Name", libnvme_ns_get_name(n)); + + paths = json_create_array(); + libnvme_namespace_for_each_path(n, p) { + struct json_object *path_attrs; + struct json_object *ctrls, *ctrl_attrs; + struct libnvme_ctrl *c; + const char *ana_state; + + libnvme_path_get_ana_state(p, &ana_state, ""); + path_attrs = json_create_object(); + obj_add_str(path_attrs, "Path", + libnvme_path_get_name(p)); + obj_add_str(path_attrs, "ANAState", ana_state); + + /* + * For iopolicy numa exclude "Qdepth", for iopolicy + * queue-depth exclude "NUMANodes" and for iopolicy + * round-robin exclude both "Qdepth" and "NUMANodes". + */ + if (streq(iopolicy, "numa")) { + const char *numa_nodes; + + libnvme_path_get_numa_nodes(p, &numa_nodes, + ""); + obj_add_str(path_attrs, "NUMANodes", + numa_nodes); + } else if (streq(iopolicy, "queue-depth")) { + int queue_depth; + + libnvme_path_get_queue_depth(p, &queue_depth, + 0); + obj_add_int(path_attrs, "Qdepth", queue_depth); + } + + c = libnvme_path_get_ctrl(p); + ctrls = json_create_array(); + ctrl_attrs = json_create_object(); + obj_add_str(ctrl_attrs, "Name", + libnvme_ctrl_get_name(c)); + obj_add_str(ctrl_attrs, "Transport", + libnvme_ctrl_get_transport(c)); + obj_add_ctrl_address(ctrl_attrs, c); + obj_add_ctrl_address_details(ctrl_attrs, + "AddressDetails", c); + obj_add_str(ctrl_attrs, "State", + libnvme_ctrl_get_state(c)); + array_add_obj(ctrls, ctrl_attrs); + obj_add_array(path_attrs, "Controller", ctrls); + + array_add_obj(paths, path_attrs); + } + obj_add_array(ns_attrs, "Paths", paths); + array_add_obj(namespaces, ns_attrs); + i++; + } + + return i; +} + +static void json_print_nvme_subsystem_topology(struct libnvme_subsystem *s, + json_object *namespaces) +{ + struct libnvme_ctrl *c; + struct libnvme_ns *n; + + libnvme_subsystem_for_each_ctrl(s, c) { + libnvme_ctrl_for_each_ns(c, n) { + struct json_object *ctrl_attrs; + struct json_object *ns_attrs; + struct json_object *ctrl; + + ns_attrs = json_create_object(); + obj_add_int(ns_attrs, "NSID", libnvme_ns_get_nsid(n)); + obj_add_str(ns_attrs, "Name", libnvme_ns_get_name(n)); + + ctrl = json_create_array(); + ctrl_attrs = json_create_object(); + obj_add_str(ctrl_attrs, "Name", + libnvme_ctrl_get_name(c)); + obj_add_str(ctrl_attrs, "Transport", + libnvme_ctrl_get_transport(c)); + obj_add_ctrl_address(ctrl_attrs, c); + obj_add_ctrl_address_details(ctrl_attrs, + "AddressDetails", c); + obj_add_str(ctrl_attrs, "State", + libnvme_ctrl_get_state(c)); + + array_add_obj(ctrl, ctrl_attrs); + obj_add_array(ns_attrs, "Controller", ctrl); + array_add_obj(namespaces, ns_attrs); + } + } +} + +static void json_simple_topology(struct libnvme_global_ctx *ctx) +{ + struct json_object *host_attrs, *subsystem_attrs; + struct json_object *subsystems, *namespaces; + struct json_object *a = json_create_array(); + struct libnvme_host *h; + + libnvme_for_each_host(ctx, h) { + struct libnvme_subsystem *s; + const char *hostid; + + host_attrs = json_create_object(); + obj_add_str(host_attrs, "HostNQN", libnvme_host_get_hostnqn(h)); + hostid = libnvme_host_get_hostid(h); + if (hostid) + obj_add_str(host_attrs, "HostID", hostid); + subsystems = json_create_array(); + libnvme_for_each_subsystem(h, s) { + const char *iopolicy; + + subsystem_attrs = json_create_object(); + obj_add_str(subsystem_attrs, "Name", + libnvme_subsystem_get_name(s)); + obj_add_str(subsystem_attrs, "NQN", + libnvme_subsystem_get_subsysnqn(s)); + libnvme_subsystem_get_iopolicy(s, &iopolicy, ""); + obj_add_str(subsystem_attrs, "IOPolicy", iopolicy); + + if (verbose_mode()) { + const char *model; + const char *serial; + const char *firmware; + + libnvme_subsystem_get_model(s, &model, ""); + libnvme_subsystem_get_serial(s, &serial, ""); + libnvme_subsystem_get_firmware(s, &firmware, + ""); + + obj_add_str(subsystem_attrs, "Model", model); + obj_add_str(subsystem_attrs, "Serial", serial); + obj_add_str(subsystem_attrs, "Firmware", + firmware); + obj_add_str(subsystem_attrs, "Type", + libnvme_subsystem_get_subsystype(s)); + } + + array_add_obj(subsystems, subsystem_attrs); + namespaces = json_create_array(); + + if (!json_subsystem_topology_multipath(s, namespaces)) + json_print_nvme_subsystem_topology(s, + namespaces); + + obj_add_array(subsystem_attrs, "Namespaces", + namespaces); + } + obj_add_array(host_attrs, "Subsystems", subsystems); + array_add_obj(a, host_attrs); + } + + json_print(a); +} + +#ifdef CONFIG_TOP +/* A rate with two decimals, as nvme top shows it */ +static void obj_add_rate(struct json_object *o, const char *k, double v) +{ + char buf[64]; + + snprintf(buf, sizeof(buf), "%.2f", v); + json_object_object_add(o, k, json_object_new_double_s(v, buf)); +} + +/* An attribute of a kernel which may not have it is left out */ +static void obj_add_count(struct json_object *o, const char *k, int ret, + long v) +{ + if (!ret) + json_object_object_add(o, k, json_object_new_int64(v)); +} + +static void obj_add_iostat(struct json_object *o, const struct nvme_iostat *st) +{ + struct json_object *r = json_create_object(); + + obj_add_rate(r, "ReadIOPS", st->r_iops); + obj_add_rate(r, "WriteIOPS", st->w_iops); + obj_add_rate(r, "ReadLatencyMs", st->r_lat); + obj_add_rate(r, "WriteLatencyMs", st->w_lat); + obj_add_rate(r, "ReadBytesPerSec", st->r_bw); + obj_add_rate(r, "WriteBytesPerSec", st->w_bw); + obj_add_uint(r, "Inflights", st->inflights); + obj_add_rate(r, "UtilPercent", st->util); + + obj_add_obj(o, "Stats", r); +} + +/* The sum of the rates, and the highest latencies and utilization */ +static void obj_add_iostat_aggr(struct json_object *o, + const struct nvme_iostat *st) +{ + struct json_object *r = json_create_object(); + + obj_add_rate(r, "ReadIOPS", st->r_iops); + obj_add_rate(r, "WriteIOPS", st->w_iops); + obj_add_rate(r, "MaxReadLatencyMs", st->r_lat); + obj_add_rate(r, "MaxWriteLatencyMs", st->w_lat); + obj_add_rate(r, "ReadBytesPerSec", st->r_bw); + obj_add_rate(r, "WriteBytesPerSec", st->w_bw); + obj_add_rate(r, "MaxUtilPercent", st->util); + + obj_add_obj(o, "Stats", r); +} + +static struct json_object *json_top_path(struct libnvme_path *p) +{ + struct json_object *r = json_create_object(); + struct nvme_iostat st; + const char *str; + int qdepth, ret; + long v; + + obj_add_str(r, "Name", libnvme_path_get_name(p)); + obj_add_str(r, "Controller", + libnvme_ctrl_get_name(libnvme_path_get_ctrl(p))); + if (!libnvme_path_get_ana_state(p, &str, NULL)) + obj_add_str(r, "ANAState", str); + if (!libnvme_path_get_numa_nodes(p, &str, NULL)) + obj_add_str(r, "NUMANodes", str); + if (!libnvme_path_get_queue_depth(p, &qdepth, 0)) + obj_add_int(r, "Qdepth", qdepth); + ret = libnvme_path_get_command_retry_count(p, &v, 0); + obj_add_count(r, "Retries", ret, v); + ret = libnvme_path_get_multipath_failover_count(p, &v, 0); + obj_add_count(r, "Failovers", ret, v); + ret = libnvme_path_get_command_error_count(p, &v, 0); + obj_add_count(r, "Errors", ret, v); + + nvme_iostat_path(p, &st); + obj_add_iostat(r, &st); + + return r; +} + +static struct json_object *json_top_nshead(struct libnvme_ns *n, + struct nvme_iostat *aggr) +{ + struct json_object *r = json_create_object(); + struct json_object *paths = json_create_array(); + struct libnvme_path *p; + struct nvme_iostat st; + int ret; + long v; + + obj_add_str(r, "Name", libnvme_ns_get_name(n)); + obj_add_uint(r, "NSID", libnvme_ns_get_nsid(n)); + ret = libnvme_ns_get_io_requeue_no_usable_path_count(n, &v, 0); + obj_add_count(r, "RequeueIO", ret, v); + ret = libnvme_ns_get_io_fail_no_available_path_count(n, &v, 0); + obj_add_count(r, "FailIO", ret, v); + + nvme_iostat_ns(n, &st); + nvme_iostat_aggr(aggr, &st); + obj_add_iostat(r, &st); + + libnvme_namespace_for_each_path(n, p) + array_add_obj(paths, json_top_path(p)); + obj_add_array(r, "Paths", paths); + + return r; +} + +static struct json_object *json_top_ns(struct libnvme_ns *n, + struct libnvme_ctrl *c, + struct nvme_iostat *aggr) +{ + struct json_object *r = json_create_object(); + struct nvme_iostat st; + int ret; + long v; + + obj_add_str(r, "Name", libnvme_ns_get_name(n)); + obj_add_uint(r, "NSID", libnvme_ns_get_nsid(n)); + obj_add_str(r, "Controller", libnvme_ctrl_get_name(c)); + ret = libnvme_ns_get_command_retry_count(n, &v, 0); + obj_add_count(r, "Retries", ret, v); + ret = libnvme_ns_get_command_error_count(n, &v, 0); + obj_add_count(r, "Errors", ret, v); + + nvme_iostat_ns(n, &st); + nvme_iostat_aggr(aggr, &st); + obj_add_iostat(r, &st); + + return r; +} + +static struct json_object *json_top_ctrl(struct libnvme_ctrl *c, + bool multipath) +{ + struct json_object *r = json_create_object(); + struct nvme_iostat aggr = { 0 }, st; + struct libnvme_path *p; + struct libnvme_ns *n; + const char *node; + int npaths = 0, ret; + long v; + + obj_add_str(r, "Name", libnvme_ctrl_get_name(c)); + obj_add_str(r, "Transport", libnvme_ctrl_get_transport(c)); + obj_add_ctrl_address(r, c); + obj_add_str(r, "State", libnvme_ctrl_get_state(c)); + if (!libnvme_ctrl_get_numa_node(c, &node, NULL)) + obj_add_int(r, "NUMANode", atoi(node)); + ret = libnvme_ctrl_get_reset_count(c, &v, 0); + obj_add_count(r, "Resets", ret, v); + ret = libnvme_ctrl_get_reconnect_count(c, &v, 0); + obj_add_count(r, "Reconnects", ret, v); + ret = libnvme_ctrl_get_command_error_count(c, &v, 0); + obj_add_count(r, "Errors", ret, v); + + if (multipath) { + libnvme_ctrl_for_each_path(c, p) { + npaths++; + nvme_iostat_path(p, &st); + nvme_iostat_aggr(&aggr, &st); + } + obj_add_int(r, "Paths", npaths); + } else { + libnvme_ctrl_for_each_ns(c, n) { + nvme_iostat_ns(n, &st); + nvme_iostat_aggr(&aggr, &st); + } + } + obj_add_iostat_aggr(r, &aggr); + + return r; +} + +static struct json_object *json_top_subsys(struct libnvme_subsystem *s) +{ + struct json_object *r = json_create_object(); + struct json_object *namespaces = json_create_array(); + struct json_object *ctrls = json_create_array(); + bool multipath = nvme_is_multipath(s); + struct nvme_iostat aggr = { 0 }; + struct libnvme_ctrl *c; + struct libnvme_ns *n; + const char *str; + + obj_add_str(r, "Name", libnvme_subsystem_get_name(s)); + obj_add_str(r, "NQN", libnvme_subsystem_get_subsysnqn(s)); + obj_add_str(r, "HostNQN", + libnvme_host_get_hostnqn(libnvme_subsystem_get_host(s))); + if (!libnvme_subsystem_get_iopolicy(s, &str, NULL)) + obj_add_str(r, "IOPolicy", str); + if (!libnvme_subsystem_get_model(s, &str, NULL)) + obj_add_str(r, "Model", str); + if (!libnvme_subsystem_get_serial(s, &str, NULL)) + obj_add_str(r, "Serial", str); + if (!libnvme_subsystem_get_firmware(s, &str, NULL)) + obj_add_str(r, "Firmware", str); + obj_add_str(r, "Type", libnvme_subsystem_get_subsystype(s)); + + if (multipath) { + libnvme_subsystem_for_each_ns(s, n) + array_add_obj(namespaces, json_top_nshead(n, &aggr)); + } else { + libnvme_subsystem_for_each_ctrl(s, c) + libnvme_ctrl_for_each_ns(c, n) + array_add_obj(namespaces, + json_top_ns(n, c, &aggr)); + } + obj_add_iostat_aggr(r, &aggr); + obj_add_array(r, "Namespaces", namespaces); + + libnvme_subsystem_for_each_ctrl(s, c) + array_add_obj(ctrls, json_top_ctrl(c, multipath)); + obj_add_array(r, "Controllers", ctrls); + + return r; +} + +static void json_top_update(struct libnvme_global_ctx *ctx) +{ + struct libnvme_subsystem *s; + struct libnvme_host *h; + + libnvme_for_each_host(ctx, h) + libnvme_for_each_subsystem(h, s) + nvme_iostat_update_subsys(s, nvme_is_multipath(s)); +} + +/* Takes two samples @interval seconds apart and prints the rates */ +static void json_top(int interval) +{ + __cleanup_nvme_global_ctx struct libnvme_global_ctx *ctx = NULL; + struct json_object *r, *subsystems; + struct libnvme_subsystem *s; + struct libnvme_host *h; + int err; + + err = nvme_create_global_ctx(&ctx); + if (err) + return; + + if (libnvme_scan_topology(ctx, NULL, NULL)) { + nvme_show_error("Failed to scan topology"); + return; + } + + json_top_update(ctx); + sleep(interval); + json_top_update(ctx); + + r = json_create_object(); + obj_add_int(r, "Interval", interval); + subsystems = json_create_array(); + libnvme_for_each_host(ctx, h) + libnvme_for_each_subsystem(h, s) + array_add_obj(subsystems, json_top_subsys(s)); + obj_add_array(r, "Subsystems", subsystems); + + json_print(r); +} +#endif /* CONFIG_TOP */ + +static struct cmds_list_print_ops json_list_print_ops = { + .list_item = json_list_item, + .list_items = json_print_list_items, + .print_nvme_subsystem_list = json_print_nvme_subsystem_list, + .topology_ctrl = json_simple_topology, + .topology_namespace = json_simple_topology, + .topology_multipath = json_simple_topology, +#ifdef CONFIG_TOP + .top = json_top, +#endif +}; + +struct cmds_list_print_ops * +cmds_list_get_json_print_ops(nvme_print_flags_t flags) +{ + json_list_print_ops.flags = flags; + return &json_list_print_ops; +} diff --git a/src/nvme-print-stdout-top.c b/plugins/cmds-list/cmds-list-print-stdout-top.c similarity index 99% rename from src/nvme-print-stdout-top.c rename to plugins/cmds-list/cmds-list-print-stdout-top.c index e2d3f41554..858ffddd58 100644 --- a/src/nvme-print-stdout-top.c +++ b/plugins/cmds-list/cmds-list-print-stdout-top.c @@ -29,6 +29,7 @@ #include "dashboard.h" #include "global-ctx.h" #include "nvme-iostat.h" +#include "cmds-list-print.h" #include "nvme-print.h" static bool stdout_top_nvme_ctrl_is_fabric(struct libnvme_ctrl *c) diff --git a/plugins/cmds-list/cmds-list-print-stdout.c b/plugins/cmds-list/cmds-list-print-stdout.c new file mode 100644 index 0000000000..3e286e787a --- /dev/null +++ b/plugins/cmds-list/cmds-list-print-stdout.c @@ -0,0 +1,1195 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +#include "cleanup.h" +#include "cmds-list-print.h" +#include "nvme-print.h" +#include "nvme-print-stdout.h" +#include "nvme-resources.h" + +static struct cmds_list_print_ops stdout_list_print_ops; + +enum simple_list_col { + SIMPLE_LIST_COL_NODE, + SIMPLE_LIST_COL_GENERIC, + SIMPLE_LIST_COL_SN, + SIMPLE_LIST_COL_MODEL, + SIMPLE_LIST_COL_NS, + SIMPLE_LIST_COL_USAGE, + SIMPLE_LIST_COL_FORMAT, + SIMPLE_LIST_COL_FW_REV, +}; + +/* + * Device names share a common textual prefix (e.g. "nvme", "nvme0n") + * followed by an integer index, so a plain byte-wise comparison would + * order "nvme10" before "nvme2". Walk both strings together and, + * whenever a run of digits begins in both, compare the runs by + * numeric value; otherwise fall back to byte comparison. + */ +static int name_natcmp(const char *sa, const char *sb) +{ + while (*sa && *sb) { + if (isdigit((unsigned char)*sa) && + isdigit((unsigned char)*sb)) { + char *enda, *endb; + unsigned long va = strtoul(sa, &enda, 10); + unsigned long vb = strtoul(sb, &endb, 10); + + if (va != vb) + return va < vb ? -1 : 1; + + sa = enda; + sb = endb; + continue; + } + + if (*sa != *sb) + return (unsigned char)*sa - (unsigned char)*sb; + + sa++; + sb++; + } + + return (unsigned char)*sa - (unsigned char)*sb; +} + +static int name_natcmp_qsort(const void *a, const void *b) +{ + return name_natcmp(*(const char * const *)a, *(const char * const *)b); +} + +struct name_collector { + const char **names; + size_t count; + size_t capacity; +}; + +static bool name_collect(const char *name, void *arg) +{ + struct name_collector *nc = arg; + + if (nc->count == nc->capacity) { + const char **tmp; + + nc->capacity = nc->capacity ? nc->capacity * 2 : 16; + tmp = realloc(nc->names, nc->capacity * sizeof(*nc->names)); + if (!tmp) + return false; + nc->names = tmp; + } + + nc->names[nc->count++] = name; + + return true; +} + +/* + * Like strset_iterate(), but visits members in natural (numeric-aware) + * order instead of the strset's underlying byte-lexicographic trie + * order, so e.g. "nvme2" sorts before "nvme10". + */ +#define strset_iterate_sorted(set, handle, arg) \ + strset_iterate_sorted_((set), typesafe_cb_preargs(bool, void *, \ + (handle), (arg), \ + const char *), \ + (arg)) + +static void strset_iterate_sorted_(const struct strset *set, + bool (*handle)(const char *, void *), + const void *data) +{ + struct name_collector nc = { 0 }; + size_t i; + + strset_iterate_(set, name_collect, &nc); + qsort(nc.names, nc.count, sizeof(*nc.names), name_natcmp_qsort); + + for (i = 0; i < nc.count; i++) { + if (!handle(nc.names[i], (void *)data)) + break; + } + + free(nc.names); +} + +struct nvme_resources_table { + struct nvme_resources *res; + struct shr_table *t; +}; + +static unsigned int stdout_subsystem_multipath(struct libnvme_subsystem *s) +{ + struct libnvme_ns *n; + struct libnvme_path *p; + unsigned int i = 0; + + n = libnvme_subsystem_first_ns(s); + if (!n) + return 0; + + libnvme_namespace_for_each_path(n, p) { + struct libnvme_ctrl *c = libnvme_path_get_ctrl(p); + const char *ana_state; + + libnvme_path_get_ana_state(p, &ana_state, ""); + + printf(" +- %s %s %s %s %s\n", + libnvme_ctrl_get_name(c), + libnvme_ctrl_get_transport(c), + libnvme_ctrl_get_traddr(c), + libnvme_ctrl_get_state(c), + ana_state); + i++; + } + + return i; +} + +static void stdout_subsystem_ctrls(struct libnvme_subsystem *s) +{ + struct libnvme_ctrl *c; + + libnvme_subsystem_for_each_ctrl(s, c) { + printf(" +- %s %s %s %s\n", + libnvme_ctrl_get_name(c), + libnvme_ctrl_get_transport(c), + libnvme_ctrl_get_traddr(c), + libnvme_ctrl_get_state(c)); + } +} + +static void stdout_subsys_config(struct libnvme_subsystem *s, + bool show_iopolicy) +{ + int len = strlen(libnvme_subsystem_get_name(s)); + + printf("%s - NQN=%s\n", libnvme_subsystem_get_name(s), + libnvme_subsystem_get_subsysnqn(s)); + printf("%*s hostnqn=%s\n", len, " ", + libnvme_host_get_hostnqn(libnvme_subsystem_get_host(s))); + if (show_iopolicy) { + const char *iopolicy; + + libnvme_subsystem_get_iopolicy(s, &iopolicy, ""); + printf("%*s iopolicy=%s\n", len, " ", iopolicy); + } + + if (stdout_list_print_ops.flags & VERBOSE) { + const char *model; + const char *serial; + const char *firmware; + + libnvme_subsystem_get_model(s, &model, "undefined"); + libnvme_subsystem_get_serial(s, &serial, ""); + libnvme_subsystem_get_firmware(s, &firmware, ""); + + printf("%*s model=%s\n", len, " ", model); + printf("%*s serial=%s\n", len, " ", serial); + printf("%*s firmware=%s\n", len, " ", firmware); + printf("%*s type=%s\n", len, " ", + libnvme_subsystem_get_subsystype(s)); + } +} + +static void stdout_subsystem(struct libnvme_global_ctx *ctx, bool show_ana) +{ + struct libnvme_host *h; + bool first = true; + + libnvme_for_each_host(ctx, h) { + struct libnvme_subsystem *s; + + libnvme_for_each_subsystem(h, s) { + bool no_ctrl = true; + struct libnvme_ctrl *c; + + libnvme_subsystem_for_each_ctrl(s, c) + no_ctrl = false; + if (no_ctrl) + continue; + + if (!first) + printf("\n"); + first = false; + + stdout_subsys_config(s, + stdout_list_print_ops.flags & VERBOSE); + printf("\\\n"); + + if (!show_ana || !stdout_subsystem_multipath(s)) + stdout_subsystem_ctrls(s); + } + } +} + +static void stdout_subsystem_list(struct libnvme_global_ctx *ctx, bool show_ana) +{ + stdout_subsystem(ctx, show_ana); +} + +static void stdout_dev_full_path(struct libnvme_ns *n, char *path, size_t len) +{ + struct stat st; + + snprintf(path, len, "%s", libnvme_ns_get_name(n)); + if (shr_startswith(path, "/dev/spdk/") && stat(path, &st) == 0) + return; + + snprintf(path, len, "/dev/%s", libnvme_ns_get_name(n)); + if (stat(path, &st) == 0) + return; + + /* + * We could start trying to search for it but let's make + * it simple and just don't show the path at all. + */ + snprintf(path, len, "%s", libnvme_ns_get_name(n)); +} + +static void stdout_generic_full_path(struct libnvme_ns *n, char *path, + size_t len) +{ + int head_instance; + int instance; + struct stat st; + + /* + * There is no block devices for SPDK, point generic path to existing + * chardevice. + */ + snprintf(path, len, "%s", libnvme_ns_get_name(n)); + if (shr_startswith(path, "/dev/spdk/") && stat(path, &st) == 0) + return; + + if (sscanf(libnvme_ns_get_name(n), "nvme%dn%d", &instance, + &head_instance) != 2) + return; + + snprintf(path, len, "/dev/ng%dn%d", instance, head_instance); + + if (stat(path, &st) == 0) + return; + + /* + * We could start trying to search for it but let's make + * it simple and just don't show the path at all. + */ + snprintf(path, len, "%s", libnvme_ns_get_generic_name(n)); +} + +static void list_item(struct libnvme_ns *n, struct shr_table *t) +{ + char usage[128] = { 0 }, format[128] = { 0 }; + char devname[128] = { 0 }; char genname[128] = { 0 }; + int lba_size, meta_size; + uint64_t lba_count, lba_util; + long long lba; + double nsze, nuse; + const char *s_suffix, *u_suffix, *l_suffix; + char ns[STR_LEN]; + int row; + + libnvme_ns_get_lba_size(n, &lba_size, 0); + libnvme_ns_get_lba_count(n, &lba_count, 0); + libnvme_ns_get_lba_util(n, &lba_util, 0); + libnvme_ns_get_meta_size(n, &meta_size, 0); + + lba = lba_size; + nsze = lba_count * lba; + nuse = lba_util * lba; + + s_suffix = shr_suffix_si_get(&nsze); + u_suffix = shr_suffix_si_get(&nuse); + l_suffix = shr_suffix_binary_get(&lba); + + snprintf(usage, sizeof(usage), "%6.2f %2sB / %6.2f %2sB", nuse, + u_suffix, nsze, s_suffix); + snprintf(format, sizeof(format), "%3.0f %2sB + %2d B", (double)lba, + l_suffix, meta_size); + + stdout_dev_full_path(n, devname, sizeof(devname)); + stdout_generic_full_path(n, genname, sizeof(genname)); + + row = shr_table_get_row_id(t); + if (row < 0) { + printf("Failed to add row\n"); + return; + } + if (shr_table_set_value_str(t, SIMPLE_LIST_COL_NODE, row, devname, + LEFT)) { + printf("Failed to set node value\n"); + return; + } + if (shr_table_set_value_str(t, SIMPLE_LIST_COL_GENERIC, row, genname, + LEFT)) { + printf("Failed to set generic value\n"); + return; + } + if (shr_table_set_value_str(t, SIMPLE_LIST_COL_SN, row, + libnvme_ns_get_serial(n), LEFT)) { + printf("Failed to set sn value\n"); + return; + } + if (shr_table_set_value_str(t, SIMPLE_LIST_COL_MODEL, row, + libnvme_ns_get_model(n), LEFT)) { + printf("Failed to set model value\n"); + return; + } + if (!sprintf(ns, "0x%x", libnvme_ns_get_nsid(n))) { + printf("Failed to output ns string\n"); + return; + } + if (shr_table_set_value_str(t, SIMPLE_LIST_COL_NS, row, ns, LEFT)) { + printf("Failed to set ns value\n"); + return; + } + if (shr_table_set_value_str(t, SIMPLE_LIST_COL_USAGE, row, usage, + LEFT)) { + printf("Failed to set usage value\n"); + return; + } + if (shr_table_set_value_str(t, SIMPLE_LIST_COL_FORMAT, row, format, + LEFT)) { + printf("Failed to set format value\n"); + return; + } + if (shr_table_set_value_str(t, SIMPLE_LIST_COL_FW_REV, row, + libnvme_ns_get_firmware(n), LEFT)) { + printf("Failed to set fw rev value\n"); + return; + } + shr_table_add_row(t, row); +} + +static void stdout_list_item(struct libnvme_ns *n, struct shr_table *t) +{ + list_item(n, t); +} + +static void stdout_list_item_table(struct libnvme_ns *n, struct shr_table *t) +{ + list_item(n, t); +} + +static bool stdout_simple_ns(const char *name, void *arg) +{ + struct nvme_resources_table *rst_t = arg; + struct nvme_resources *res = rst_t->res; + struct libnvme_ns *n; + + n = htable_ns_get(&res->ht_n, name); + stdout_list_item_table(n, rst_t->t); + + return true; +} + +static void stdout_simple_list(struct libnvme_global_ctx *ctx) +{ + struct nvme_resources res; + struct shr_table_column columns[] = { + { "Node", LEFT, 21 }, + { "Generic", LEFT, 21 }, + { "SN", LEFT, 20 }, + { "Model", LEFT, 40 }, + { "Namespace", LEFT, 10 }, + { "Usage", LEFT, 26 }, + { "Format", LEFT, 16 }, + { "FW Rev", LEFT, 8 }, + }; + struct shr_table *t = shr_table_init_with_columns(columns, + ARRAY_SIZE(columns)); + struct nvme_resources_table res_t = { &res, t }; + + if (!t) { + printf("Failed to init table\n"); + return; + } + + nvme_resources_init(ctx, &res); + + strset_iterate_sorted(&res.namespaces, stdout_simple_ns, &res_t); + + shr_table_print(t); + + nvme_resources_free(&res); + shr_table_free(t); +} + +static void stdout_ns_details(struct libnvme_ns *n) +{ + char usage[128] = { 0 }, format[128] = { 0 }, usage_binary[128] = { 0 }; + char devname[128] = { 0 }, genname[128] = { 0 }; + int lba_size, meta_size; + uint64_t lba_count, lba_util; + long long lba; + double nsze, nuse; + double nsze_binary, nuse_binary; + const char *s_suffix, *u_suffix, *l_suffix; + const char *s_suffix_binary, *u_suffix_binary; + + libnvme_ns_get_lba_size(n, &lba_size, 0); + libnvme_ns_get_lba_count(n, &lba_count, 0); + libnvme_ns_get_lba_util(n, &lba_util, 0); + libnvme_ns_get_meta_size(n, &meta_size, 0); + + lba = lba_size; + nsze = lba_count * lba; + nuse = lba_util * lba; + nsze_binary = nsze; + nuse_binary = nuse; + + s_suffix = shr_suffix_si_get(&nsze); + u_suffix = shr_suffix_si_get(&nuse); + l_suffix = shr_suffix_binary_get(&lba); + + sprintf(usage, "%6.2f %1sB / %6.2f %1sB", nuse, u_suffix, nsze, + s_suffix); + sprintf(format, "%3.0f %2sB + %2d B", (double)lba, l_suffix, meta_size); + + s_suffix_binary = shr_suffix_dbinary_get(&nsze_binary); + u_suffix_binary = shr_suffix_dbinary_get(&nuse_binary); + sprintf(usage_binary, "(%7.2f %2sB / %7.2f %2sB)", nuse_binary, + u_suffix_binary, + nsze_binary, s_suffix_binary); + + nvme_dev_full_path(n, devname, sizeof(devname)); + nvme_generic_full_path(n, genname, sizeof(genname)); + + printf("%-17s %-20s %#-10x %-21s %-25s %-16s ", devname, + genname, libnvme_ns_get_nsid(n), usage, usage_binary, format); +} + +static bool stdout_detailed_name(const char *name, void *arg) +{ + bool *first = arg; + + printf("%s%s", *first ? "" : ", ", name); + *first = false; + + return true; +} + +static bool stdout_detailed_subsys(const char *name, void *arg) +{ + struct nvme_resources *res = arg; + struct htable_subsys_iter it; + struct strset ctrls; + struct libnvme_subsystem *s; + struct libnvme_ctrl *c; + bool first; + + strset_init(&ctrls); + first = true; + for (s = htable_subsys_getfirst(&res->ht_s, name, &it); + s; + s = htable_subsys_getnext(&res->ht_s, name, &it)) { + if (first) { + printf("%-16s %-96s ", name, + libnvme_subsystem_get_subsysnqn(s)); + first = false; + } + + libnvme_subsystem_for_each_ctrl(s, c) + strset_add(&ctrls, libnvme_ctrl_get_name(c)); + } + + first = true; + strset_iterate_sorted(&ctrls, stdout_detailed_name, &first); + strset_clear(&ctrls); + printf("\n"); + + return true; +} + +static bool stdout_detailed_ctrl(const char *name, void *arg) +{ + struct nvme_resources *res = arg; + struct strset namespaces; + struct libnvme_ctrl *c; + struct libnvme_path *p; + struct libnvme_ns *n; + bool first; + + c = htable_ctrl_get(&res->ht_c, name); + assert(c); + + { + const char *tr = libnvme_ctrl_get_transport(c); + __cleanup_free char *reg_owner = libnvme_ctrl_owner(c); + const char *slot; + const char *cntlid; + const char *serial; + const char *model; + const char *firmware; + const char *owner_str; + + libnvme_ctrl_get_phy_slot(c, &slot, NULL); + libnvme_ctrl_get_cntlid(c, &cntlid, ""); + libnvme_ctrl_get_serial(c, &serial, ""); + libnvme_ctrl_get_model(c, &model, ""); + libnvme_ctrl_get_firmware(c, &firmware, ""); + + if (!libnvme_ctrl_is_transport_fabric(c)) + owner_str = "kernel"; + else + owner_str = reg_owner ? reg_owner : "-"; + + printf( + "%-16s %-12s %-6s %-20s %-40s %-8s %-6s %-14s %-6s %-12s ", + libnvme_ctrl_get_name(c), + owner_str, + cntlid, + serial, + model, + firmware, + tr, + libnvme_ctrl_get_address(c), + slot ? slot : "", + libnvme_subsystem_get_name( + libnvme_ctrl_get_subsystem(c))); + } + + strset_init(&namespaces); + + libnvme_ctrl_for_each_ns(c, n) + strset_add(&namespaces, libnvme_ns_get_name(n)); + libnvme_ctrl_for_each_path(c, p) { + n = libnvme_path_get_ns(p); + if (!n) + continue; + strset_add(&namespaces, libnvme_ns_get_name(n)); + } + + first = true; + strset_iterate_sorted(&namespaces, stdout_detailed_name, &first); + strset_clear(&namespaces); + + printf("\n"); + + return true; +} + +static bool stdout_detailed_ns(const char *name, void *arg) +{ + struct nvme_resources *res = arg; + struct htable_ns_iter it; + struct strset ctrls; + struct libnvme_ctrl *c; + struct libnvme_path *p; + struct libnvme_ns *n; + bool first; + + strset_init(&ctrls); + first = true; + for (n = htable_ns_getfirst(&res->ht_n, name, &it); + n; + n = htable_ns_getnext(&res->ht_n, name, &it)) { + if (first) { + stdout_ns_details(n); + first = false; + } + + if (libnvme_ns_get_ctrl(n)) { + printf("%s\n", + libnvme_ctrl_get_name(libnvme_ns_get_ctrl(n))); + return true; + } + + libnvme_namespace_for_each_path(n, p) { + c = libnvme_path_get_ctrl(p); + strset_add(&ctrls, libnvme_ctrl_get_name(c)); + } + } + + first = true; + strset_iterate_sorted(&ctrls, stdout_detailed_name, &first); + strset_clear(&ctrls); + + printf("\n"); + return true; +} + +static void stdout_detailed_list(struct libnvme_global_ctx *ctx) +{ + struct nvme_resources res; + + nvme_resources_init(ctx, &res); + + printf("%-16s %-96s %-.16s\n", "Subsystem", "Subsystem-NQN", + "Controllers"); + printf("%-.16s %-.96s %-.16s\n", dash, dash, dash); + strset_iterate_sorted(&res.subsystems, stdout_detailed_subsys, &res); + printf("\n"); + + printf( + "%-16s %-12s %-6s %-20s %-40s %-8s %-6s %-14s %-6s %-12s %-16s\n", + "Device", "Orchestrator", "Cntlid", "SN", "MN", "FR", "TxPort", + "Address", "Slot", "Subsystem", "Namespaces"); + printf( + "%-.16s %-.12s %-.6s %-.20s %-.40s %-.8s %-.6s %-.14s %-.6s %-.12s %-.16s\n", + dash, dash, dash, dash, dash, dash, dash, dash, dash, dash, + dash); + strset_iterate_sorted(&res.ctrls, stdout_detailed_ctrl, &res); + printf("\n"); + + printf("%-17s %-20s %-10s %-49s %-16s %-16s\n", "Device", "Generic", + "NSID", "Usage", "Format", "Controllers"); + printf("%-.17s %-.20s %-.10s %-.49s %-.16s %-.16s\n", dash, dash, dash, + dash, dash, dash); + strset_iterate_sorted(&res.namespaces, stdout_detailed_ns, &res); + + nvme_resources_free(&res); +} + +static void stdout_list_items(struct libnvme_global_ctx *ctx) +{ + if (stdout_list_print_ops.flags & VERBOSE) + stdout_detailed_list(ctx); + else + stdout_simple_list(ctx); +} + +static int subsystem_topology_multipath_add_row(struct shr_table *t, + const char *iopolicy, const char *nshead, + const char *nsid, const char *nspath, + const char *anastate, const char *iopolicy_info, + const char *ctrl, const char *trtype, + const char *address, const char *state) +{ + int row; + int col = -1; + + row = shr_table_get_row_id(t); + if (row < 0) { + nvme_show_error("Failed to add subsys topology multipath row"); + return row; + } + + shr_table_set_value_str(t, ++col, row, nshead, CENTERED); + shr_table_set_value_str(t, ++col, row, nsid, CENTERED); + shr_table_set_value_str(t, ++col, row, nspath, CENTERED); + shr_table_set_value_str(t, ++col, row, anastate, CENTERED); + if (streq(iopolicy, "numa") || streq(iopolicy, "queue-depth")) + shr_table_set_value_str(t, ++col, row, iopolicy_info, CENTERED); + shr_table_set_value_str(t, ++col, row, ctrl, CENTERED); + shr_table_set_value_str(t, ++col, row, trtype, CENTERED); + shr_table_set_value_str(t, ++col, row, address, CENTERED); + shr_table_set_value_str(t, ++col, row, state, CENTERED); + + shr_table_add_row(t, row); + + return 0; +} + +static void +stdout_tabular_subsystem_topology_multipath(struct libnvme_subsystem *s) +{ + struct libnvme_ns *n; + struct libnvme_path *p; + struct libnvme_ctrl *c; + bool first; + char nshead[32], nsid[32]; + char iopolicy_info[256]; + int ret, num_path; + struct shr_table *t; + const char *iopolicy; + struct shr_table_column columns[] = { + {"NSHead", LEFT, AUTO_WIDTH}, + {"NSID", LEFT, AUTO_WIDTH}, + {"NSPath", LEFT, AUTO_WIDTH}, + {"ANAState", LEFT, AUTO_WIDTH}, + {"Nodes", LEFT, AUTO_WIDTH}, + {"Qdepth", LEFT, AUTO_WIDTH}, + {"Controller", LEFT, AUTO_WIDTH}, + {"TrType", LEFT, AUTO_WIDTH}, + {"Address", LEFT, AUTO_WIDTH}, + {"State", LEFT, AUTO_WIDTH}, + }; + + t = shr_table_create(); + if (!t) { + nvme_show_error( + "Failed to init subsys topology multipath table"); + return; + } + + if (shr_table_add_columns_filter(t, columns, ARRAY_SIZE(columns), + subsystem_iopolicy_filter, (void *)s) < 0) { + nvme_show_error( + "Failed to add subsys topology multipath columns"); + goto free_tbl; + } + + libnvme_subsystem_get_iopolicy(s, &iopolicy, ""); + + libnvme_subsystem_for_each_ns(s, n) { + first = true; + libnvme_namespace_for_each_path(n, p) { + const char *ana_state; + int queue_depth; + const char *numa_nodes; + + c = libnvme_path_get_ctrl(p); + libnvme_path_get_ana_state(p, &ana_state, ""); + + /* + * For the first row we print actual NSHead name, + * however, for the subsequent rows we print "arrow" + * ("-->") symbol for NSHead. This "arrow" style makes + * it visually obvious that susequenet entries (if + * present) are a path under the first NSHead. + */ + if (first) { + snprintf(nshead, sizeof(nshead), "%s", + libnvme_ns_get_name(n)); + first = false; + } else + snprintf(nshead, sizeof(nshead), "%s", "-->"); + + snprintf(nsid, sizeof(nsid), "%u", + libnvme_ns_get_nsid(n)); + + if (streq(iopolicy, "numa")) { + libnvme_path_get_numa_nodes(p, &numa_nodes, ""); + snprintf(iopolicy_info, sizeof(iopolicy_info), + "%s", numa_nodes); + } else if (streq(iopolicy, "queue-depth")) { + libnvme_path_get_queue_depth(p, &queue_depth, + 0); + snprintf(iopolicy_info, sizeof(iopolicy_info), + "%d", queue_depth); + } else { + snprintf(iopolicy_info, sizeof(iopolicy_info), + "--"); + } + + ret = subsystem_topology_multipath_add_row(t, + iopolicy, + nshead, + nsid, + libnvme_path_get_name(p), + ana_state, + iopolicy_info, + libnvme_ctrl_get_name(c), + libnvme_ctrl_get_transport(c), + libnvme_ctrl_get_address(c), + libnvme_ctrl_get_state(c)); + if (ret < 0) + goto free_tbl; + } + } + + /* + * Next we print controller in the subsystem which may not have any + * nvme path associated to it. + */ + libnvme_subsystem_for_each_ctrl(s, c) { + num_path = 0; + libnvme_ctrl_for_each_path(c, p) + num_path++; + + if (!num_path) { + ret = subsystem_topology_multipath_add_row(t, + iopolicy, + "--", /* NSHead */ + "--", /* NSID */ + "--", /* NSPath */ + "--", /* ANAState */ + "--", /* Nodes/Qdepth */ + libnvme_ctrl_get_name(c), + libnvme_ctrl_get_transport(c), + libnvme_ctrl_get_address(c), + libnvme_ctrl_get_state(c)); + if (ret < 0) + goto free_tbl; + } + } + + shr_table_print(t); +free_tbl: + shr_table_free(t); +} + +static void +stdout_subsystem_topology_multipath(struct libnvme_subsystem *s, + enum nvme_cli_topo_ranking ranking) +{ + struct libnvme_ns *n; + struct libnvme_path *p; + struct libnvme_ctrl *c; + const char *iopolicy; + + libnvme_subsystem_get_iopolicy(s, &iopolicy, ""); + + if (ranking == NVME_CLI_TOPO_NAMESPACE) { + libnvme_subsystem_for_each_ns(s, n) { + if (!libnvme_namespace_first_path(n)) + continue; + + printf(" +- ns %d\n", libnvme_ns_get_nsid(n)); + printf(" \\\n"); + + libnvme_namespace_for_each_path(n, p) { + const char *ana_state; + + c = libnvme_path_get_ctrl(p); + libnvme_path_get_ana_state(p, &ana_state, ""); + + printf(" +- %s %s %s %s %s\n", + libnvme_ctrl_get_name(c), + libnvme_ctrl_get_transport(c), + libnvme_ctrl_get_address(c), + libnvme_ctrl_get_state(c), + ana_state); + } + } + } else if (ranking == NVME_CLI_TOPO_CTRL) { + /* NVME_CLI_TOPO_CTRL */ + libnvme_subsystem_for_each_ctrl(s, c) { + printf(" +- %s %s %s\n", + libnvme_ctrl_get_name(c), + libnvme_ctrl_get_transport(c), + libnvme_ctrl_get_address(c)); + printf(" \\\n"); + + libnvme_subsystem_for_each_ns(s, n) { + libnvme_namespace_for_each_path(n, p) { + const char *ana_state; + + if (libnvme_path_get_ctrl(p) != c) + continue; + + libnvme_path_get_ana_state(p, + &ana_state, ""); + printf(" +- ns %d %s %s\n", + libnvme_ns_get_nsid(n), + libnvme_ctrl_get_state(c), + ana_state); + } + } + } + } else { + /* NVME_CLI_TOPO_MULTIPATH */ + libnvme_subsystem_for_each_ns(s, n) { + printf(" +- %s (ns %d)\n", + libnvme_ns_get_name(n), + libnvme_ns_get_nsid(n)); + printf(" \\\n"); + libnvme_namespace_for_each_path(n, p) { + const char *ana_state; + + c = libnvme_path_get_ctrl(p); + libnvme_path_get_ana_state(p, &ana_state, ""); + + if (streq(iopolicy, "numa")) { + const char *numa_nodes; + + /* + * For iopolicy numa, exclude printing + * qdepth. + */ + libnvme_path_get_numa_nodes(p, + &numa_nodes, ""); + printf(" +- %s %s %s %s %s %s %s\n", + libnvme_path_get_name(p), + ana_state, + numa_nodes, + libnvme_ctrl_get_name(c), + libnvme_ctrl_get_transport(c), + libnvme_ctrl_get_address(c), + libnvme_ctrl_get_state(c)); + + } else if (streq(iopolicy, "queue-depth")) { + int queue_depth; + + /* + * For iopolicy queue-depth, exclude + * printing numa nodes. + */ + libnvme_path_get_queue_depth(p, + &queue_depth, 0); + printf(" +- %s %s %d %s %s %s %s\n", + libnvme_path_get_name(p), + ana_state, + queue_depth, + libnvme_ctrl_get_name(c), + libnvme_ctrl_get_transport(c), + libnvme_ctrl_get_address(c), + libnvme_ctrl_get_state(c)); + + } else { /* round-robin */ + /* + * For iopolicy round-robin, exclude + * printing numa nodes and qdepth. + */ + printf(" +- %s %s %s %s %s %s\n", + libnvme_path_get_name(p), + ana_state, + libnvme_ctrl_get_name(c), + libnvme_ctrl_get_transport(c), + libnvme_ctrl_get_address(c), + libnvme_ctrl_get_state(c)); + } + } + } + } +} + +static int subsystem_topology_add_row(struct shr_table *t, + const char *ns, const char *nsid, const char *ctrl, + const char *trtype, const char *address, const char *state) +{ + int row = shr_table_get_row_id(t); + + if (row < 0) { + nvme_show_error("Failed to add subsys topology row"); + return row; + } + + shr_table_set_value_str(t, 0, row, ns, CENTERED); + shr_table_set_value_str(t, 1, row, nsid, CENTERED); + shr_table_set_value_str(t, 2, row, ctrl, CENTERED); + shr_table_set_value_str(t, 3, row, trtype, CENTERED); + shr_table_set_value_str(t, 4, row, address, CENTERED); + shr_table_set_value_str(t, 5, row, state, CENTERED); + + shr_table_add_row(t, row); + + return 0; +} + +static void stdout_tabular_subsystem_topology(struct libnvme_subsystem *s) +{ + struct libnvme_ctrl *c; + struct libnvme_ns *n; + int ret, num_ns; + struct shr_table *t; + struct shr_table_column columns[] = { + {"Namespace", LEFT, AUTO_WIDTH}, + {"NSID", LEFT, AUTO_WIDTH}, + {"Controller", LEFT, AUTO_WIDTH}, + {"Trtype", LEFT, AUTO_WIDTH}, + {"Address", LEFT, AUTO_WIDTH}, + {"State", LEFT, AUTO_WIDTH}, + }; + + t = shr_table_create(); + if (!t) { + nvme_show_error("Failed to init subsys topology table"); + return; + } + + if (shr_table_add_columns(t, columns, ARRAY_SIZE(columns)) < 0) { + nvme_show_error("Failed to add subsys topology columns"); + goto free_tbl; + } + + libnvme_subsystem_for_each_ctrl(s, c) { + num_ns = 0; + + libnvme_ctrl_for_each_ns(c, n) + num_ns++; + + if (!num_ns) { + ret = subsystem_topology_add_row(t, + "--", /* Namespace */ + "--", /* NSID */ + libnvme_ctrl_get_name(c), + libnvme_ctrl_get_transport(c), + libnvme_ctrl_get_address(c), + libnvme_ctrl_get_state(c)); + if (ret < 0) + goto free_tbl; + } else { + libnvme_ctrl_for_each_ns(c, n) { + char nsid[32]; + + snprintf(nsid, sizeof(nsid), "%u", + libnvme_ns_get_nsid(n)); + + ret = subsystem_topology_add_row(t, + libnvme_ns_get_name(n), + (const char *)nsid, + libnvme_ctrl_get_name(c), + libnvme_ctrl_get_transport(c), + libnvme_ctrl_get_address(c), + libnvme_ctrl_get_state(c)); + if (ret < 0) + goto free_tbl; + } + } + } + shr_table_print(t); +free_tbl: + shr_table_free(t); +} + +static void stdout_subsystem_topology(struct libnvme_subsystem *s, + enum nvme_cli_topo_ranking ranking) +{ + struct libnvme_ctrl *c; + struct libnvme_ns *n; + + if (ranking == NVME_CLI_TOPO_NAMESPACE) { + libnvme_subsystem_for_each_ctrl(s, c) { + libnvme_ctrl_for_each_ns(c, n) { + printf(" +- ns %d\n", libnvme_ns_get_nsid(n)); + printf(" \\\n"); + printf(" +- %s %s %s %s\n", + libnvme_ctrl_get_name(c), + libnvme_ctrl_get_transport(c), + libnvme_ctrl_get_address(c), + libnvme_ctrl_get_state(c)); + } + } + } else if (ranking == NVME_CLI_TOPO_CTRL) { + /* NVME_CLI_TOPO_CTRL */ + libnvme_subsystem_for_each_ctrl(s, c) { + printf(" +- %s %s %s\n", + libnvme_ctrl_get_name(c), + libnvme_ctrl_get_transport(c), + libnvme_ctrl_get_address(c)); + printf(" \\\n"); + libnvme_ctrl_for_each_ns(c, n) { + printf(" +- ns %d %s\n", + libnvme_ns_get_nsid(n), + libnvme_ctrl_get_state(c)); + } + } + } else { + /* NVME_CLI_TOPO_MULTIPATH */ + libnvme_subsystem_for_each_ctrl(s, c) { + libnvme_ctrl_for_each_ns(c, n) { + c = libnvme_ns_get_ctrl(n); + + printf(" +- %s (ns %d)\n", + libnvme_ns_get_name(n), + libnvme_ns_get_nsid(n)); + printf(" \\\n"); + printf(" +- %s %s %s %s\n", + libnvme_ctrl_get_name(c), + libnvme_ctrl_get_transport(c), + libnvme_ctrl_get_address(c), + libnvme_ctrl_get_state(c)); + } + } + } +} + +static void stdout_topology_tabular(struct libnvme_global_ctx *ctx) +{ + struct libnvme_host *h; + struct libnvme_subsystem *s; + bool first = true; + + libnvme_for_each_host(ctx, h) { + libnvme_for_each_subsystem(h, s) { + bool no_ctrl = true; + struct libnvme_ctrl *c; + + libnvme_subsystem_for_each_ctrl(s, c) + no_ctrl = false; + + if (no_ctrl) + continue; + + if (!first) + printf("\n"); + first = false; + + stdout_subsys_config(s, true); + printf("\n"); + + if (nvme_is_multipath(s)) + stdout_tabular_subsystem_topology_multipath(s); + else + stdout_tabular_subsystem_topology(s); + } + } +} + +static void stdout_simple_topology(struct libnvme_global_ctx *ctx, + enum nvme_cli_topo_ranking ranking) +{ + struct libnvme_host *h; + struct libnvme_subsystem *s; + bool first = true; + + libnvme_for_each_host(ctx, h) { + libnvme_for_each_subsystem(h, s) { + bool no_ctrl = true; + struct libnvme_ctrl *c; + + libnvme_subsystem_for_each_ctrl(s, c) + no_ctrl = false; + + if (no_ctrl) + continue; + + if (!first) + printf("\n"); + first = false; + + stdout_subsys_config(s, true); + printf("\\\n"); + + if (nvme_is_multipath(s)) + stdout_subsystem_topology_multipath(s, ranking); + else + stdout_subsystem_topology(s, ranking); + } + } +} + +static void stdout_topology_namespace(struct libnvme_global_ctx *ctx) +{ + stdout_simple_topology(ctx, NVME_CLI_TOPO_NAMESPACE); +} + +static void stdout_topology_ctrl(struct libnvme_global_ctx *ctx) +{ + stdout_simple_topology(ctx, NVME_CLI_TOPO_CTRL); +} + +static void stdout_topology_multipath(struct libnvme_global_ctx *ctx) +{ + stdout_simple_topology(ctx, NVME_CLI_TOPO_MULTIPATH); +} + +static struct cmds_list_print_ops stdout_list_print_ops = { + .list_item = stdout_list_item, + .list_items = stdout_list_items, + .print_nvme_subsystem_list = stdout_subsystem_list, + .topology_ctrl = stdout_topology_ctrl, + .topology_namespace = stdout_topology_namespace, + .topology_multipath = stdout_topology_multipath, + .topology_tabular = stdout_topology_tabular, +#ifdef CONFIG_TOP + .top = stdout_top, +#else + .top = NULL, +#endif +}; + +struct cmds_list_print_ops * +cmds_list_get_stdout_print_ops(nvme_print_flags_t flags) +{ + stdout_list_print_ops.flags = flags; + return &stdout_list_print_ops; +} diff --git a/plugins/cmds-list/cmds-list-print.c b/plugins/cmds-list/cmds-list-print.c new file mode 100644 index 0000000000..8128a21f15 --- /dev/null +++ b/plugins/cmds-list/cmds-list-print.c @@ -0,0 +1,125 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include + +#include + +#include + +#include "cmds-list-print.h" +#include "nvme-print.h" + +/* + * Run the printers in process: they read sysfs while printing. Like + * nvme_print(), silently skip printers that an output format does not + * implement. + */ +#define cmds_list_print(name, flags, ...) \ + do { \ + struct cmds_list_print_ops *__lops = \ + cmds_list_print_ops(flags); \ + \ + if (__lops && __lops->name) \ + nvme_print_decoder(__lops, name, false, flags, \ + ##__VA_ARGS__); \ + } while (false) + +static struct cmds_list_print_ops *cmds_list_print_ops(nvme_print_flags_t flags) +{ + struct cmds_list_print_ops *ops = NULL; + + if (flags & JSON || nvme_is_output_format_json()) + ops = cmds_list_get_json_print_ops(flags); + else if (!(flags & BINARY)) + ops = cmds_list_get_stdout_print_ops(flags); + + return ops; +} + +void nvme_dev_full_path(struct libnvme_ns *n, char *path, size_t len) +{ + struct stat st; + + snprintf(path, len, "%s", libnvme_ns_get_name(n)); + if (shr_startswith(path, "/dev/spdk/") && stat(path, &st) == 0) + return; + + snprintf(path, len, "/dev/%s", libnvme_ns_get_name(n)); + if (stat(path, &st) == 0) + return; + /* + * We could start trying to search for it but let's make + * it simple and just don't show the path at all. + */ + snprintf(path, len, "%s", libnvme_ns_get_name(n)); +} + +void nvme_generic_full_path(struct libnvme_ns *n, char *path, size_t len) +{ + int head_instance; + int instance; + struct stat st; + + /* + * There is no block devices for SPDK, point generic path to existing + * chardevice. + */ + snprintf(path, len, "%s", libnvme_ns_get_name(n)); + if (shr_startswith(path, "/dev/spdk/") && stat(path, &st) == 0) + return; + + if (sscanf(libnvme_ns_get_name(n), "nvme%dn%d", &instance, + &head_instance) != 2) + return; + + snprintf(path, len, "/dev/ng%dn%d", instance, head_instance); + + if (stat(path, &st) == 0) + return; + /* + * We could start trying to search for it but let's make + * it simple and just don't show the path at all. + */ + snprintf(path, len, "%s", libnvme_ns_get_generic_name(n)); +} + +void nvme_show_list_item(struct libnvme_ns *n, struct shr_table *t) +{ + cmds_list_print(list_item, NORMAL, n, t); +} + +void nvme_show_list_items(struct libnvme_global_ctx *ctx, + nvme_print_flags_t flags) +{ + cmds_list_print(list_items, flags, ctx); +} + +void nvme_show_subsystem_list(struct libnvme_global_ctx *ctx, bool show_ana, + nvme_print_flags_t flags) +{ + cmds_list_print(print_nvme_subsystem_list, flags, ctx, show_ana); +} + +void nvme_show_top(nvme_print_flags_t flags, int refresh_interval) +{ + cmds_list_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) +{ + if (ranking == NVME_CLI_TOPO_NAMESPACE) + cmds_list_print(topology_namespace, flags, ctx); + else if (ranking == NVME_CLI_TOPO_CTRL) + cmds_list_print(topology_ctrl, flags, ctx); + else + cmds_list_print(topology_multipath, flags, ctx); +} + +void nvme_show_topology_tabular(struct libnvme_global_ctx *ctx, + nvme_print_flags_t flags) +{ + cmds_list_print(topology_tabular, flags, ctx); +} diff --git a/plugins/cmds-list/cmds-list-print.h b/plugins/cmds-list/cmds-list-print.h new file mode 100644 index 0000000000..4e8c092d17 --- /dev/null +++ b/plugins/cmds-list/cmds-list-print.h @@ -0,0 +1,103 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#pragma once + +#include + +#include +#include + +#include "args.h" + +enum nvme_cli_topo_ranking { + NVME_CLI_TOPO_NAMESPACE, + NVME_CLI_TOPO_CTRL, + NVME_CLI_TOPO_MULTIPATH, +}; + +static inline bool nvme_is_multipath(struct libnvme_subsystem *s) +{ + struct libnvme_ns *n; + struct libnvme_path *p; + + libnvme_subsystem_for_each_ns(s, n) + libnvme_namespace_for_each_path(n, p) + return true; + + return false; +} + +static inline bool subsystem_iopolicy_filter(const char *name, void *arg) +{ + struct libnvme_subsystem *s = arg; + const char *iopolicy; + + libnvme_subsystem_get_iopolicy(s, &iopolicy, ""); + + if (streq(iopolicy, "queue-depth")) { + /* exclude "Nodes" for iopolicy queue-depth */ + if (streq(name, "Nodes")) + return false; + } else if (streq(iopolicy, "numa")) { + /* exclude "Qdepth" for iopolicy numa */ + if (streq(name, "Qdepth")) + return false; + } else { /* round-robin */ + /* exclude "Nodes" and "Qdepth" for iopolicy round-robin */ + if (streq(name, "Nodes") || streq(name, "Qdepth")) + return false; + } + + return true; +} + +/* + * The printers of the libnvme tree and of nvme top. They run in process: + * they read sysfs while printing. + */ +struct cmds_list_print_ops { + void (*list_item)(struct libnvme_ns *n, struct shr_table *t); + void (*list_items)(struct libnvme_global_ctx *ctx); + void (*print_nvme_subsystem_list)(struct libnvme_global_ctx *ctx, + bool show_ana); + void (*topology_ctrl)(struct libnvme_global_ctx *ctx); + void (*topology_namespace)(struct libnvme_global_ctx *ctx); + void (*topology_multipath)(struct libnvme_global_ctx *ctx); + void (*topology_tabular)(struct libnvme_global_ctx *ctx); + void (*top)(int refresh_interval); + nvme_print_flags_t flags; +}; + +struct cmds_list_print_ops * +cmds_list_get_stdout_print_ops(nvme_print_flags_t flags); + +#ifdef CONFIG_JSONC +struct cmds_list_print_ops * +cmds_list_get_json_print_ops(nvme_print_flags_t flags); +#else +static inline struct cmds_list_print_ops * +cmds_list_get_json_print_ops(nvme_print_flags_t flags) +{ + return NULL; +} +#endif + +#ifdef CONFIG_TOP +void stdout_top(int refresh_interval); +#endif + +void nvme_dev_full_path(struct libnvme_ns *n, char *path, size_t len); +void nvme_generic_full_path(struct libnvme_ns *n, char *path, size_t len); + +void nvme_show_list_items(struct libnvme_global_ctx *ctx, + nvme_print_flags_t flags); +void nvme_show_subsystem_list(struct libnvme_global_ctx *ctx, bool show_ana, + nvme_print_flags_t flags); +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_top(nvme_print_flags_t flags, int refresh_interval); + +/* A row of the table of nvme list, used by "nvme zns list" as well */ +void nvme_show_list_item(struct libnvme_ns *n, struct shr_table *t); diff --git a/src/dashboard.c b/plugins/cmds-list/dashboard.c similarity index 100% rename from src/dashboard.c rename to plugins/cmds-list/dashboard.c diff --git a/src/dashboard.h b/plugins/cmds-list/dashboard.h similarity index 100% rename from src/dashboard.h rename to plugins/cmds-list/dashboard.h diff --git a/plugins/cmds-list/meson.build b/plugins/cmds-list/meson.build new file mode 100644 index 0000000000..1c13175608 --- /dev/null +++ b/plugins/cmds-list/meson.build @@ -0,0 +1,34 @@ +# SPDX-License-Identifier: GPL-2.0-or-later +# +# The device enumeration commands, which show the devices found in sysfs. + +plugin_extension = false + +plugin_sources += [ + 'plugins/cmds-list/cmds-list-plugin.c', + 'plugins/cmds-list/cmds-list-print.c', + 'plugins/cmds-list/cmds-list-print-stdout.c', +] + +if json_c_dep.found() + plugin_sources += [ + 'plugins/cmds-list/cmds-list-print-json.c', + ] +endif + +plugin_commands = [ + 'list', + 'list-subsys', + 'show-topology', +] + +if want_top + plugin_sources += [ + 'plugins/cmds-list/cmds-list-print-stdout-top.c', + 'plugins/cmds-list/dashboard.c', + 'plugins/cmds-list/nvme-iostat.c', + ] + plugin_commands += [ + 'top', + ] +endif diff --git a/src/nvme-iostat.c b/plugins/cmds-list/nvme-iostat.c similarity index 100% rename from src/nvme-iostat.c rename to plugins/cmds-list/nvme-iostat.c diff --git a/src/nvme-iostat.h b/plugins/cmds-list/nvme-iostat.h similarity index 100% rename from src/nvme-iostat.h rename to plugins/cmds-list/nvme-iostat.h diff --git a/plugins/lm/lm-nvme.c b/plugins/cmds-lm/lm-nvme.c similarity index 100% rename from plugins/lm/lm-nvme.c rename to plugins/cmds-lm/lm-nvme.c diff --git a/plugins/lm/lm-print-binary.c b/plugins/cmds-lm/lm-print-binary.c similarity index 100% rename from plugins/lm/lm-print-binary.c rename to plugins/cmds-lm/lm-print-binary.c diff --git a/plugins/lm/lm-print-json.c b/plugins/cmds-lm/lm-print-json.c similarity index 100% rename from plugins/lm/lm-print-json.c rename to plugins/cmds-lm/lm-print-json.c diff --git a/plugins/lm/lm-print-stdout.c b/plugins/cmds-lm/lm-print-stdout.c similarity index 100% rename from plugins/lm/lm-print-stdout.c rename to plugins/cmds-lm/lm-print-stdout.c diff --git a/plugins/lm/lm-print.c b/plugins/cmds-lm/lm-print.c similarity index 100% rename from plugins/lm/lm-print.c rename to plugins/cmds-lm/lm-print.c diff --git a/plugins/lm/lm-print.h b/plugins/cmds-lm/lm-print.h similarity index 100% rename from plugins/lm/lm-print.h rename to plugins/cmds-lm/lm-print.h diff --git a/plugins/cmds-lm/meson.build b/plugins/cmds-lm/meson.build new file mode 100644 index 0000000000..2d3e5e5e0e --- /dev/null +++ b/plugins/cmds-lm/meson.build @@ -0,0 +1,16 @@ +# SPDX-License-Identifier: GPL-2.0-or-later + +plugin_name = 'lm' + +plugin_sources += [ + 'plugins/cmds-lm/lm-nvme.c', + 'plugins/cmds-lm/lm-print.c', + 'plugins/cmds-lm/lm-print-stdout.c', + 'plugins/cmds-lm/lm-print-binary.c', +] + +if json_c_dep.found() + plugin_sources += [ + 'plugins/cmds-lm/lm-print-json.c', + ] +endif diff --git a/src/nvme-cmds-discovery.c b/plugins/cmds-log/get-log.c similarity index 89% rename from src/nvme-cmds-discovery.c rename to plugins/cmds-log/get-log.c index 514dbfa2fd..9a29db55b4 100644 --- a/src/nvme-cmds-discovery.c +++ b/plugins/cmds-log/get-log.c @@ -18,15 +18,19 @@ #include -#include +#include +#include +#include #include "argconfig.h" #include "cleanup.h" +#include "get-log.h" #include "global-ctx.h" +#include "log-print.h" #include "logging.h" -#include "nvme-cmds-common.h" #include "nvme-print.h" #include "plugin.h" +#include "plugin-loader.h" static const char *rae = "Retain an Asynchronous Event"; static const char *lsp = "log specific field"; @@ -34,6 +38,25 @@ static const char *csi = "command set identifier"; static const char *namespace_desired = "desired namespace"; static const char *ish = "Ignore Shutdown (for NVMe-MI command)"; +/* Plugins that register log page decoders */ +static const char *const log_decoder_plugins[] = { + "fdp", "zns", "cmds-fabrics", +}; + +static void nvme_show_log(const char *devname, enum nvme_cmd_get_log_lid lid, + __u32 nsid, __u16 lsi, __u8 lsp, void *log, + __u32 len, nvme_print_flags_t flags) +{ + size_t i; + + for (i = 0; i < ARRAY_SIZE(log_decoder_plugins); i++) + nvme_load_plugin(log_decoder_plugins[i]); + + if (!log_show_log(devname, lid, nsid, lsi, lsp, log, len, flags)) + nvme_show_log_decoded(devname, lid, nsid, lsi, lsp, log, len, + flags); +} + static int get_log(int argc, char **argv, struct command *acmd, struct plugin *plugin) { const char *desc = "Retrieve desired number of bytes " @@ -187,20 +210,6 @@ static int get_log(int argc, char **argv, struct command *acmd, struct plugin *p if (!log) return -ENOMEM; - struct nvme_get_log_args args = { - .nsid = cfg.namespace_id, - .rae = cfg.rae, - .lsp = cfg.lsp, - .lid = cfg.log_id, - .lsi = cfg.lsi, - .csi = cfg.csi, - .ot = cfg.ot, - .uidx = cfg.uuid_index, - .lpo = cfg.lpo, - .log = log, - .len = cfg.log_len, - .result = NULL, - }; nvme_init_get_log(&cmd, cfg.namespace_id, cfg.log_id, cfg.csi, log, cfg.log_len); if (cfg.ish) { @@ -236,9 +245,9 @@ static int get_log(int argc, char **argv, struct command *acmd, struct plugin *p cfg.namespace_id); d(log, cfg.log_len, 16, 1); if (nvme_args.verbose) - nvme_show_log(libnvme_transport_handle_get_name(hdl), args.lid, - args.nsid, args.lsi, args.lsp, args.log, args.len, - VERBOSE); + nvme_show_log(libnvme_transport_handle_get_name(hdl), + cfg.log_id, cfg.namespace_id, cfg.lsi, + cfg.lsp, log, cfg.log_len, VERBOSE); } else { d_raw((unsigned char *)log, cfg.log_len); } @@ -257,7 +266,7 @@ static struct command *commands[] = { NULL, }; -static void __shr_constructor register_group(void) +void log_register_get_log(void) { plugin_add_group(&builtin, "Log Page & Identify", commands); } diff --git a/plugins/cmds-log/get-log.h b/plugins/cmds-log/get-log.h new file mode 100644 index 0000000000..b9ce0b248f --- /dev/null +++ b/plugins/cmds-log/get-log.h @@ -0,0 +1,5 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#pragma once + +/* Adds the top-level command get-log */ +void log_register_get_log(void); diff --git a/plugins/log/log-plugin.c b/plugins/cmds-log/log-plugin.c similarity index 99% rename from plugins/log/log-plugin.c rename to plugins/cmds-log/log-plugin.c index 3a1299f388..7097e8ecef 100644 --- a/plugins/log/log-plugin.c +++ b/plugins/cmds-log/log-plugin.c @@ -42,6 +42,7 @@ #include "argconfig.h" #include "cleanup.h" +#include "get-log.h" #include "global-ctx.h" #include "log-print.h" #include "nvme-cmds.h" @@ -3181,13 +3182,9 @@ static struct plugin plugin = { .group = "Log Page & Identify", }; -static struct nvme_log_decoder log_decoder = { - .show = log_show_log, -}; - NVME_PLUGIN_INIT(register_plugin) { plugin_add_group(&plugin, NULL, commands); register_extension(&plugin); - nvme_register_log_decoder(&log_decoder); + log_register_get_log(); } diff --git a/plugins/log/log-print-binary.c b/plugins/cmds-log/log-print-binary.c similarity index 100% rename from plugins/log/log-print-binary.c rename to plugins/cmds-log/log-print-binary.c diff --git a/plugins/log/log-print-json.c b/plugins/cmds-log/log-print-json.c similarity index 99% rename from plugins/log/log-print-json.c rename to plugins/cmds-log/log-print-json.c index e2c65b364e..1cbe92d8d7 100644 --- a/plugins/log/log-print-json.c +++ b/plugins/cmds-log/log-print-json.c @@ -25,6 +25,7 @@ #include "log-print.h" #include "nvme-json.h" #include "nvme-print.h" +#include "plugins/cmds-feat/feat-print.h" #include "nvme-print-json.h" static void json_error_log(struct nvme_error_log_page *err_log, int entries, diff --git a/plugins/log/log-print-stdout.c b/plugins/cmds-log/log-print-stdout.c similarity index 99% rename from plugins/log/log-print-stdout.c rename to plugins/cmds-log/log-print-stdout.c index a5424f8338..4e711129fa 100644 --- a/plugins/log/log-print-stdout.c +++ b/plugins/cmds-log/log-print-stdout.c @@ -14,6 +14,7 @@ #include "log-print.h" #include "logging.h" #include "nvme-print.h" +#include "plugins/cmds-feat/feat-print.h" #include "nvme-print-stdout.h" static void stdout_smart_log(struct nvme_smart_log *smart, unsigned int nsid, diff --git a/plugins/log/log-print.c b/plugins/cmds-log/log-print.c similarity index 100% rename from plugins/log/log-print.c rename to plugins/cmds-log/log-print.c diff --git a/plugins/log/log-print.h b/plugins/cmds-log/log-print.h similarity index 100% rename from plugins/log/log-print.h rename to plugins/cmds-log/log-print.h diff --git a/plugins/cmds-log/meson.build b/plugins/cmds-log/meson.build new file mode 100644 index 0000000000..fc367a19b9 --- /dev/null +++ b/plugins/cmds-log/meson.build @@ -0,0 +1,22 @@ +# SPDX-License-Identifier: GPL-2.0-or-later + +plugin_name = 'log' + +plugin_needs = ['feat'] + +plugin_sources += [ + 'plugins/cmds-log/log-plugin.c', + 'plugins/cmds-log/get-log.c', + 'plugins/cmds-log/log-print.c', + 'plugins/cmds-log/log-print-stdout.c', + 'plugins/cmds-log/log-print-binary.c', +] + +if json_c_dep.found() + plugin_sources += [ + 'plugins/cmds-log/log-print-json.c', + ] +endif + +# get-log, a top-level command +plugin_commands = ['get-log'] diff --git a/plugins/keys/meson.build b/plugins/cmds-nbft/meson.build similarity index 59% rename from plugins/keys/meson.build rename to plugins/cmds-nbft/meson.build index 660e19d6ac..b042d47d7e 100644 --- a/plugins/keys/meson.build +++ b/plugins/cmds-nbft/meson.build @@ -1,7 +1,9 @@ # SPDX-License-Identifier: GPL-2.0-or-later +plugin_name = 'nbft' + if want_fabrics plugin_sources += [ - 'plugins/keys/keys-plugin.c', + 'plugins/cmds-nbft/nbft-plugin.c', ] endif diff --git a/plugins/nbft/nbft-plugin.c b/plugins/cmds-nbft/nbft-plugin.c similarity index 100% rename from plugins/nbft/nbft-plugin.c rename to plugins/cmds-nbft/nbft-plugin.c diff --git a/plugins/dir/meson.build b/plugins/cmds-ns/meson.build similarity index 54% rename from plugins/dir/meson.build rename to plugins/cmds-ns/meson.build index 42f268c91e..d707f0948e 100644 --- a/plugins/dir/meson.build +++ b/plugins/cmds-ns/meson.build @@ -1,5 +1,7 @@ # SPDX-License-Identifier: GPL-2.0-or-later +plugin_name = 'ns' + plugin_sources += [ - 'plugins/dir/dir-plugin.c', + 'plugins/cmds-ns/ns-plugin.c', ] diff --git a/plugins/ns/ns-plugin.c b/plugins/cmds-ns/ns-plugin.c similarity index 100% rename from plugins/ns/ns-plugin.c rename to plugins/cmds-ns/ns-plugin.c diff --git a/plugins/cmds-nvme-mi/meson.build b/plugins/cmds-nvme-mi/meson.build new file mode 100644 index 0000000000..389d9fdaab --- /dev/null +++ b/plugins/cmds-nvme-mi/meson.build @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: GPL-2.0-or-later + +plugin_name = 'nvme-mi' + +plugin_sources += [ + 'plugins/cmds-nvme-mi/nvme-mi-plugin.c', +] diff --git a/plugins/nvme-mi/nvme-mi-plugin.c b/plugins/cmds-nvme-mi/nvme-mi-plugin.c similarity index 100% rename from plugins/nvme-mi/nvme-mi-plugin.c rename to plugins/cmds-nvme-mi/nvme-mi-plugin.c diff --git a/plugins/cmds-ocp/meson.build b/plugins/cmds-ocp/meson.build new file mode 100644 index 0000000000..40c96db808 --- /dev/null +++ b/plugins/cmds-ocp/meson.build @@ -0,0 +1,24 @@ +# SPDX-License-Identifier: GPL-2.0-or-later + +plugin_name = 'ocp' + +plugin_needs = ['log', 'feat'] + +plugin_sources += [ + 'plugins/cmds-ocp/ocp-utils.c', + 'plugins/cmds-ocp/ocp-nvme.c', + 'plugins/cmds-ocp/ocp-clear-features.c', + 'plugins/cmds-ocp/ocp-smart-extended-log.c', + 'plugins/cmds-ocp/ocp-fw-activation-history.c', + 'plugins/cmds-ocp/ocp-telemetry-decode.c', + 'plugins/cmds-ocp/ocp-hardware-component-log.c', + 'plugins/cmds-ocp/ocp-print.c', + 'plugins/cmds-ocp/ocp-print-stdout.c', + 'plugins/cmds-ocp/ocp-print-binary.c', +] + +if json_c_dep.found() + plugin_sources += [ + 'plugins/cmds-ocp/ocp-print-json.c', + ] +endif diff --git a/plugins/ocp/ocp-clear-features.c b/plugins/cmds-ocp/ocp-clear-features.c similarity index 98% rename from plugins/ocp/ocp-clear-features.c rename to plugins/cmds-ocp/ocp-clear-features.c index e1398dccc0..8f90dcf427 100644 --- a/plugins/ocp/ocp-clear-features.c +++ b/plugins/cmds-ocp/ocp-clear-features.c @@ -14,6 +14,7 @@ #include "global-ctx.h" #include "nvme-cmds.h" #include "nvme-print.h" +#include "plugins/cmds-feat/feat-print.h" #include "ocp-nvme.h" #include "ocp-utils.h" #include "plugin.h" diff --git a/plugins/ocp/ocp-clear-features.h b/plugins/cmds-ocp/ocp-clear-features.h similarity index 100% rename from plugins/ocp/ocp-clear-features.h rename to plugins/cmds-ocp/ocp-clear-features.h diff --git a/plugins/ocp/ocp-fw-activation-history.c b/plugins/cmds-ocp/ocp-fw-activation-history.c similarity index 100% rename from plugins/ocp/ocp-fw-activation-history.c rename to plugins/cmds-ocp/ocp-fw-activation-history.c diff --git a/plugins/ocp/ocp-fw-activation-history.h b/plugins/cmds-ocp/ocp-fw-activation-history.h similarity index 100% rename from plugins/ocp/ocp-fw-activation-history.h rename to plugins/cmds-ocp/ocp-fw-activation-history.h diff --git a/plugins/ocp/ocp-hardware-component-log.c b/plugins/cmds-ocp/ocp-hardware-component-log.c similarity index 100% rename from plugins/ocp/ocp-hardware-component-log.c rename to plugins/cmds-ocp/ocp-hardware-component-log.c diff --git a/plugins/ocp/ocp-hardware-component-log.h b/plugins/cmds-ocp/ocp-hardware-component-log.h similarity index 100% rename from plugins/ocp/ocp-hardware-component-log.h rename to plugins/cmds-ocp/ocp-hardware-component-log.h diff --git a/plugins/ocp/ocp-nvme.c b/plugins/cmds-ocp/ocp-nvme.c similarity index 99% rename from plugins/ocp/ocp-nvme.c rename to plugins/cmds-ocp/ocp-nvme.c index e328bb846e..4987935769 100644 --- a/plugins/ocp/ocp-nvme.c +++ b/plugins/cmds-ocp/ocp-nvme.c @@ -28,6 +28,7 @@ #include "global-ctx.h" #include "nvme-cmds.h" #include "nvme-print.h" +#include "plugins/cmds-feat/feat-print.h" #include "plugin.h" #define OCP_PLUGIN_VERSION "3.2.0" diff --git a/plugins/ocp/ocp-nvme.h b/plugins/cmds-ocp/ocp-nvme.h similarity index 100% rename from plugins/ocp/ocp-nvme.h rename to plugins/cmds-ocp/ocp-nvme.h diff --git a/plugins/ocp/ocp-print-binary.c b/plugins/cmds-ocp/ocp-print-binary.c similarity index 100% rename from plugins/ocp/ocp-print-binary.c rename to plugins/cmds-ocp/ocp-print-binary.c diff --git a/plugins/ocp/ocp-print-json.c b/plugins/cmds-ocp/ocp-print-json.c similarity index 99% rename from plugins/ocp/ocp-print-json.c rename to plugins/cmds-ocp/ocp-print-json.c index 989bc466e1..58b4207a10 100644 --- a/plugins/ocp/ocp-print-json.c +++ b/plugins/cmds-ocp/ocp-print-json.c @@ -20,7 +20,7 @@ #include "ocp-smart-extended-log.h" #include "ocp-telemetry-decode.h" #include "ocp-utils.h" -#include "plugins/log/log-print.h" +#include "plugins/cmds-log/log-print.h" #define array_add_obj json_array_add_value_object #define array_add_str json_array_add_value_string diff --git a/plugins/ocp/ocp-print-stdout.c b/plugins/cmds-ocp/ocp-print-stdout.c similarity index 99% rename from plugins/ocp/ocp-print-stdout.c rename to plugins/cmds-ocp/ocp-print-stdout.c index 6499a9069e..6bf0590e7d 100644 --- a/plugins/ocp/ocp-print-stdout.c +++ b/plugins/cmds-ocp/ocp-print-stdout.c @@ -18,7 +18,7 @@ #include "ocp-smart-extended-log.h" #include "ocp-telemetry-decode.h" #include "ocp-utils.h" -#include "plugins/log/log-print.h" +#include "plugins/cmds-log/log-print.h" static struct ocp_print_ops stdout_print_ops; diff --git a/plugins/ocp/ocp-print.c b/plugins/cmds-ocp/ocp-print.c similarity index 100% rename from plugins/ocp/ocp-print.c rename to plugins/cmds-ocp/ocp-print.c diff --git a/plugins/ocp/ocp-print.h b/plugins/cmds-ocp/ocp-print.h similarity index 100% rename from plugins/ocp/ocp-print.h rename to plugins/cmds-ocp/ocp-print.h diff --git a/plugins/ocp/ocp-smart-extended-log.c b/plugins/cmds-ocp/ocp-smart-extended-log.c similarity index 100% rename from plugins/ocp/ocp-smart-extended-log.c rename to plugins/cmds-ocp/ocp-smart-extended-log.c diff --git a/plugins/ocp/ocp-smart-extended-log.h b/plugins/cmds-ocp/ocp-smart-extended-log.h similarity index 100% rename from plugins/ocp/ocp-smart-extended-log.h rename to plugins/cmds-ocp/ocp-smart-extended-log.h diff --git a/plugins/ocp/ocp-telemetry-decode.c b/plugins/cmds-ocp/ocp-telemetry-decode.c similarity index 100% rename from plugins/ocp/ocp-telemetry-decode.c rename to plugins/cmds-ocp/ocp-telemetry-decode.c diff --git a/plugins/ocp/ocp-telemetry-decode.h b/plugins/cmds-ocp/ocp-telemetry-decode.h similarity index 100% rename from plugins/ocp/ocp-telemetry-decode.h rename to plugins/cmds-ocp/ocp-telemetry-decode.h diff --git a/plugins/ocp/ocp-types.h b/plugins/cmds-ocp/ocp-types.h similarity index 100% rename from plugins/ocp/ocp-types.h rename to plugins/cmds-ocp/ocp-types.h diff --git a/plugins/ocp/ocp-utils.c b/plugins/cmds-ocp/ocp-utils.c similarity index 100% rename from plugins/ocp/ocp-utils.c rename to plugins/cmds-ocp/ocp-utils.c diff --git a/plugins/ocp/ocp-utils.h b/plugins/cmds-ocp/ocp-utils.h similarity index 100% rename from plugins/ocp/ocp-utils.h rename to plugins/cmds-ocp/ocp-utils.h diff --git a/src/nvme-cmds-passthru.c b/plugins/cmds-passthru/cmds-passthru-plugin.c similarity index 96% rename from src/nvme-cmds-passthru.c rename to plugins/cmds-passthru/cmds-passthru-plugin.c index 5ced3123f8..9013a47ad9 100644 --- a/src/nvme-cmds-passthru.c +++ b/plugins/cmds-passthru/cmds-passthru-plugin.c @@ -34,7 +34,6 @@ #include #include #include -#include #include #include #include @@ -46,7 +45,6 @@ #include "cleanup.h" #include "global-ctx.h" #include "logging.h" -#include "nvme-cmds-common.h" #include "nvme-print.h" #include "plugin.h" @@ -54,6 +52,31 @@ static const char *latency = "output latency statistics"; static const char *namespace_desired = "desired namespace"; static const char *raw_dump = "dump output in binary format"; +struct passthru_config { + __u8 opcode; + __u8 flags; + __u16 rsvd; + __u32 namespace_id; + __u32 data_len; + __u32 metadata_len; + __u32 cdw2; + __u32 cdw3; + __u32 cdw10; + __u32 cdw11; + __u32 cdw12; + __u32 cdw13; + __u32 cdw14; + __u32 cdw15; + char *input_file; + char *metadata; + bool raw_binary; + bool show_command; + bool read; + bool write; + __u8 prefill; + bool latency; +}; + static void passthru_print_read_output(struct passthru_config cfg, void *data, int dfd, void *mdata, int mfd, int err) { @@ -367,7 +390,7 @@ static struct command *commands[] = { NULL, }; -static void __shr_constructor register_group(void) +NVME_PLUGIN_INIT(register_plugin) { plugin_add_group(&builtin, "Passthrough", commands); } diff --git a/plugins/cmds-passthru/meson.build b/plugins/cmds-passthru/meson.build new file mode 100644 index 0000000000..c434c2444c --- /dev/null +++ b/plugins/cmds-passthru/meson.build @@ -0,0 +1,14 @@ +# SPDX-License-Identifier: GPL-2.0-or-later +# +# The passthru commands. plugins/meson.build always builds this plugin. + +plugin_extension = false + +plugin_sources += [ + 'plugins/cmds-passthru/cmds-passthru-plugin.c', +] + +plugin_commands = [ + 'admin-passthru', + 'io-passthru', +] diff --git a/plugins/exclusion/meson.build b/plugins/cmds-registry/meson.build similarity index 56% rename from plugins/exclusion/meson.build rename to plugins/cmds-registry/meson.build index 5b6dcb0d9e..e5a6fa0f46 100644 --- a/plugins/exclusion/meson.build +++ b/plugins/cmds-registry/meson.build @@ -1,7 +1,9 @@ # SPDX-License-Identifier: GPL-2.0-or-later +plugin_name = 'registry' + if want_fabrics plugin_sources += [ - 'plugins/exclusion/exclusion-nvme.c', + 'plugins/cmds-registry/registry-nvme.c', ] endif diff --git a/plugins/registry/registry-nvme.c b/plugins/cmds-registry/registry-nvme.c similarity index 100% rename from plugins/registry/registry-nvme.c rename to plugins/cmds-registry/registry-nvme.c diff --git a/src/bitfields.c b/plugins/cmds-regs/bitfields.c similarity index 100% rename from src/bitfields.c rename to plugins/cmds-regs/bitfields.c diff --git a/src/bitfields.h b/plugins/cmds-regs/bitfields.h similarity index 100% rename from src/bitfields.h rename to plugins/cmds-regs/bitfields.h diff --git a/src/nvme-cmds-registers.c b/plugins/cmds-regs/cmds-regs-plugin.c similarity index 99% rename from src/nvme-cmds-registers.c rename to plugins/cmds-regs/cmds-regs-plugin.c index b5305dca1b..ce7420cae4 100644 --- a/src/nvme-cmds-registers.c +++ b/plugins/cmds-regs/cmds-regs-plugin.c @@ -21,7 +21,6 @@ #include #include -#include #include #include "argconfig.h" @@ -31,6 +30,7 @@ #include "nvme-cmds-common.h" #include "nvme-print.h" #include "nvme-regs.h" +#include "regs-print.h" #include "plugin.h" #define ALL_REGS ((UINT32_C(1) << NVME_NR_REGS) - 1) @@ -669,7 +669,7 @@ static struct command *commands[] = { NULL, }; -static void __shr_constructor register_group(void) +NVME_PLUGIN_INIT(register_plugin) { plugin_add_group(&builtin, "Registers", commands); } diff --git a/plugins/cmds-regs/meson.build b/plugins/cmds-regs/meson.build new file mode 100644 index 0000000000..30340fae42 --- /dev/null +++ b/plugins/cmds-regs/meson.build @@ -0,0 +1,29 @@ +# SPDX-License-Identifier: GPL-2.0-or-later +# +# The commands of the controller registers. plugins/meson.build always +# builds this plugin. + +plugin_extension = false + +plugin_sources += [ + 'plugins/cmds-regs/cmds-regs-plugin.c', + 'plugins/cmds-regs/bitfields.c', + 'plugins/cmds-regs/nvme-regs.c', + 'plugins/cmds-regs/regs-print.c', + 'plugins/cmds-regs/regs-print-stdout.c', + 'plugins/cmds-regs/regs-print-binary.c', +] + +if json_c_dep.found() + plugin_sources += [ + 'plugins/cmds-regs/regs-print-json.c', + ] +endif + +plugin_commands = [ + 'show-regs', + 'set-reg', + 'get-reg', + 'set-property', + 'get-property', +] diff --git a/src/nvme-regs.c b/plugins/cmds-regs/nvme-regs.c similarity index 100% rename from src/nvme-regs.c rename to plugins/cmds-regs/nvme-regs.c diff --git a/src/nvme-regs.h b/plugins/cmds-regs/nvme-regs.h similarity index 100% rename from src/nvme-regs.h rename to plugins/cmds-regs/nvme-regs.h diff --git a/plugins/cmds-regs/regs-print-binary.c b/plugins/cmds-regs/regs-print-binary.c new file mode 100644 index 0000000000..0e3d859c43 --- /dev/null +++ b/plugins/cmds-regs/regs-print-binary.c @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include + +#include +#include + +#include "nvme-print.h" +#include "regs-print.h" + +/* + * The registers as they are in BAR0, 0h to E1Bh, the ones not read zero: + * all of them for a PCIe controller, the properties of a fabrics one. + */ +static void binary_ctrl_registers(const struct nvme_reg_val *vals, + unsigned int nr, + enum nvme_regs_style style __shr_unused) +{ + const unsigned int size = NVME_REG_PMRMSCU + sizeof(uint32_t); + unsigned char page[NVME_REG_PMRMSCU + sizeof(uint32_t)] = { 0 }; + unsigned int i; + + for (i = 0; i < nr; i++) { + const struct nvme_reg *reg = vals[i].reg; + + if (reg->offset + reg->size > size) + continue; + if (reg->size == 8) + shr_mmio_write64(page + reg->offset, vals[i].value, + true); + else + shr_mmio_write32(page + reg->offset, vals[i].value); + } + + d_raw(page, size); +} + +static struct regs_print_ops binary_regs_print_ops = { + .ctrl_registers = binary_ctrl_registers, +}; + +struct regs_print_ops *regs_get_binary_print_ops(nvme_print_flags_t flags) +{ + binary_regs_print_ops.flags = flags; + return &binary_regs_print_ops; +} diff --git a/plugins/cmds-regs/regs-print-json.c b/plugins/cmds-regs/regs-print-json.c new file mode 100644 index 0000000000..21f10034c2 --- /dev/null +++ b/plugins/cmds-regs/regs-print-json.c @@ -0,0 +1,60 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include + +#include + +#include "nvme-print.h" +#include "nvme-print-json.h" +#include "regs-print.h" + +/* Adds the fields @fields of @value to @o, decoded, under their names */ +static void json_bitfields(struct json_object *o, + const struct bitfield *fields, unsigned int nr, + uint64_t value) +{ + char buf[128]; + unsigned int i; + + for (i = 0; i < nr; i++) { + bitfield_str(&fields[i], value, buf, sizeof(buf)); + obj_add_str(o, fields[i].name, buf); + } +} + +/* + * The same for each style: the value of each register under its symbol, + * with -v an object of the value and its fields. + */ +static void json_ctrl_registers(const struct nvme_reg_val *vals, + unsigned int nr, + enum nvme_regs_style style __shr_unused) +{ + struct json_object *r = json_root(); + struct json_object *o; + unsigned int i; + + for (i = 0; i < nr; i++) { + const struct nvme_reg *reg = vals[i].reg; + + if (!json_verbose_mode()) { + obj_add_uint64(r, reg->sym, vals[i].value); + continue; + } + + o = json_create_object(); + obj_add_uint64(o, "value", vals[i].value); + json_bitfields(o, reg->fields, reg->nr_fields, vals[i].value); + obj_add_obj(r, reg->sym, o); + } +} + +static struct regs_print_ops regs_json_print_ops = { + .ctrl_registers = json_ctrl_registers, +}; + +struct regs_print_ops *regs_get_json_print_ops(nvme_print_flags_t flags) +{ + regs_json_print_ops.flags = flags; + return ®s_json_print_ops; +} diff --git a/plugins/cmds-regs/regs-print-stdout.c b/plugins/cmds-regs/regs-print-stdout.c new file mode 100644 index 0000000000..250faac0ec --- /dev/null +++ b/plugins/cmds-regs/regs-print-stdout.c @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include + +#include + +#include + +#include "nvme-print.h" +#include "nvme-print-stdout.h" +#include "regs-print.h" + +static struct regs_print_ops regs_stdout_print_ops; + +/* + * The "field : value" table of the fields @fields of @value, decoded: the + * subtable of a row with the value itself. + */ +static struct shr_table *stdout_bitfields_table(const struct bitfield *fields, + unsigned int nr, + uint64_t value) +{ + struct shr_table *t; + char buf[128]; + unsigned int i; + + t = stdout_kv_table_create(); + if (!t) + return NULL; + + for (i = 0; i < nr; i++) { + bitfield_str(&fields[i], value, buf, sizeof(buf)); + stdout_kv_add(t, fields[i].name, "%s", buf); + } + + return t; +} + +static void stdout_ctrl_registers(const struct nvme_reg_val *vals, + unsigned int nr, enum nvme_regs_style style) +{ + bool verbose = !!(regs_stdout_print_ops.flags & VERBOSE); + struct shr_table *t; + unsigned int i; + int row; + + t = stdout_kv_table_create(); + if (!t) + return; + + for (i = 0; i < nr; i++) { + const struct nvme_reg *reg = vals[i].reg; + uint64_t value = vals[i].value; + + if (style == NVME_REGS_TABLE) + row = stdout_kv_add(t, reg->sym, "%#"PRIx64, value); + else if (verbose) + row = stdout_kv_add(t, reg->name, "%#"PRIx64, value); + else + row = stdout_kv_add(t, + style == NVME_REGS_PROPERTY ? "property" : + "register", + "%#04x (%s), value: %#"PRIx64, reg->offset, + reg->name, value); + if (verbose && reg->nr_fields) + shr_table_set_row_subtable(t, row, + stdout_bitfields_table(reg->fields, + reg->nr_fields, value)); + } + + stdout_kv_table_finish(t, "registers"); +} + +static struct regs_print_ops regs_stdout_print_ops = { + .ctrl_registers = stdout_ctrl_registers, +}; + +struct regs_print_ops *regs_get_stdout_print_ops(nvme_print_flags_t flags) +{ + regs_stdout_print_ops.flags = flags; + return ®s_stdout_print_ops; +} diff --git a/plugins/cmds-regs/regs-print.c b/plugins/cmds-regs/regs-print.c new file mode 100644 index 0000000000..49690f4ca1 --- /dev/null +++ b/plugins/cmds-regs/regs-print.c @@ -0,0 +1,40 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include + +#include "nvme-print.h" +#include "regs-print.h" + +/* + * Run the printers in the sandbox. Like nvme_print(), silently skip + * printers that an output format does not implement. + */ +#define regs_print(name, flags, ...) \ + do { \ + struct regs_print_ops *ops = regs_print_ops(flags); \ + \ + if (ops && ops->name) \ + nvme_print_decoder(ops, name, true, flags, \ + ##__VA_ARGS__); \ + } while (false) + +static struct regs_print_ops *regs_print_ops(nvme_print_flags_t flags) +{ + struct regs_print_ops *ops = NULL; + + if (flags & JSON || nvme_is_output_format_json()) + ops = regs_get_json_print_ops(flags); + else if (flags & BINARY) + ops = regs_get_binary_print_ops(flags); + else + ops = regs_get_stdout_print_ops(flags); + + return ops; +} + +void nvme_show_ctrl_registers(const struct nvme_reg_val *vals, unsigned int nr, + enum nvme_regs_style style, + nvme_print_flags_t flags) +{ + regs_print(ctrl_registers, flags, vals, nr, style); +} diff --git a/plugins/cmds-regs/regs-print.h b/plugins/cmds-regs/regs-print.h new file mode 100644 index 0000000000..11734c23dd --- /dev/null +++ b/plugins/cmds-regs/regs-print.h @@ -0,0 +1,37 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#pragma once + +#include + +#include "args.h" +#include "nvme-regs.h" + +/* How nvme_show_ctrl_registers() shows the registers */ +enum nvme_regs_style { + NVME_REGS_TABLE, /* show-regs: a row for each */ + NVME_REGS_REGISTER, /* get-reg: "register : offset (name), value" */ + NVME_REGS_PROPERTY, /* get-property: "property : ..." */ +}; + +struct regs_print_ops { + void (*ctrl_registers)(const struct nvme_reg_val *vals, unsigned int nr, + enum nvme_regs_style style); + nvme_print_flags_t flags; +}; + +struct regs_print_ops *regs_get_stdout_print_ops(nvme_print_flags_t flags); +struct regs_print_ops *regs_get_binary_print_ops(nvme_print_flags_t flags); + +#ifdef CONFIG_JSONC +struct regs_print_ops *regs_get_json_print_ops(nvme_print_flags_t flags); +#else +static inline struct regs_print_ops * +regs_get_json_print_ops(nvme_print_flags_t flags) +{ + return NULL; +} +#endif + +void nvme_show_ctrl_registers(const struct nvme_reg_val *vals, unsigned int nr, + enum nvme_regs_style style, + nvme_print_flags_t flags); diff --git a/plugins/cmds-resv/meson.build b/plugins/cmds-resv/meson.build new file mode 100644 index 0000000000..06fe167b04 --- /dev/null +++ b/plugins/cmds-resv/meson.build @@ -0,0 +1,16 @@ +# SPDX-License-Identifier: GPL-2.0-or-later + +plugin_name = 'resv' + +plugin_sources += [ + 'plugins/cmds-resv/resv-plugin.c', + 'plugins/cmds-resv/resv-print.c', + 'plugins/cmds-resv/resv-print-stdout.c', + 'plugins/cmds-resv/resv-print-binary.c', +] + +if json_c_dep.found() + plugin_sources += [ + 'plugins/cmds-resv/resv-print-json.c', + ] +endif diff --git a/plugins/resv/resv-plugin.c b/plugins/cmds-resv/resv-plugin.c similarity index 99% rename from plugins/resv/resv-plugin.c rename to plugins/cmds-resv/resv-plugin.c index cde39c7943..d7fc7e7ed6 100644 --- a/plugins/resv/resv-plugin.c +++ b/plugins/cmds-resv/resv-plugin.c @@ -20,6 +20,7 @@ #include "global-ctx.h" #include "nvme-print.h" #include "plugin.h" +#include "resv-print.h" static const char *crkey = "current reservation key"; static const char *iekey = "ignore existing res. key"; diff --git a/plugins/cmds-resv/resv-print-binary.c b/plugins/cmds-resv/resv-print-binary.c new file mode 100644 index 0000000000..cec0d86650 --- /dev/null +++ b/plugins/cmds-resv/resv-print-binary.c @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include + +#include "nvme-print.h" +#include "resv-print.h" + +static void binary_resv_report(struct nvme_resv_status *status, int bytes, + bool eds) +{ + d_raw((unsigned char *)status, bytes); +} + +static struct resv_print_ops binary_resv_print_ops = { + .resv_report = binary_resv_report, +}; + +struct resv_print_ops *resv_get_binary_print_ops(nvme_print_flags_t flags) +{ + binary_resv_print_ops.flags = flags; + return &binary_resv_print_ops; +} diff --git a/plugins/cmds-resv/resv-print-json.c b/plugins/cmds-resv/resv-print-json.c new file mode 100644 index 0000000000..d76ca20242 --- /dev/null +++ b/plugins/cmds-resv/resv-print-json.c @@ -0,0 +1,93 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include + +#include +#include + +#include "nvme-print.h" +#include "nvme-print-json.h" +#include "resv-print.h" + +static void json_nvme_resv_report(struct nvme_resv_status *status, + int bytes, bool eds) +{ + struct json_object *r = json_root(); + struct json_object *rcs = json_create_array(); + int i, entries; + int regstrnt = status->regstrnt[0] | (status->regstrnt[1] << 8); + + obj_add_uint(r, "gen", le32_to_cpu(status->gen)); + obj_add_int(r, "rtype", status->rtype); + obj_add_int(r, "regstrnt", regstrnt); + obj_add_int(r, "ptpls", status->ptpls); + + /* check Extended Data Structure bit */ + if (!eds) { + /* + * if status buffer was too small, don't loop past the end of + * the buffer + */ + entries = (bytes - 24) / 24; + if (entries < regstrnt) + regstrnt = entries; + + obj_add_array(r, "registrants", rcs); + for (i = 0; i < regstrnt; i++) { + struct json_object *rc = json_create_object(); + + obj_add_int(rc, "cntlid", + le16_to_cpu(status->registrant_ds[i].cntlid)); + obj_add_int(rc, "rcsts", + status->registrant_ds[i].rcsts); + obj_add_uint64(rc, "hostid", + le64_to_cpu(status->registrant_ds[i].hostid)); + obj_add_uint64(rc, "rkey", + le64_to_cpu(status->registrant_ds[i].rkey)); + + array_add_obj(rcs, rc); + } + } else { + char hostid[33]; + + /* + * if status buffer was too small, don't loop past the end of + * the buffer + */ + entries = (bytes - 64) / 64; + + if (entries < regstrnt) + regstrnt = entries; + + obj_add_array(r, "registrantext", rcs); + + for (i = 0; i < regstrnt; i++) { + struct json_object *rc = json_create_object(); + + obj_add_int(rc, "cntlid", + le16_to_cpu(status->registrant_eds[i].cntlid)); + obj_add_int(rc, "rcsts", + status->registrant_eds[i].rcsts); + obj_add_uint64(rc, "rkey", + le64_to_cpu(status->registrant_eds[i].rkey)); + + shr_bin_to_hex(hostid, sizeof(hostid), + status->registrant_eds[i].hostid, + sizeof(status->registrant_eds[i].hostid), + 0); + + obj_add_str(rc, "hostid", hostid); + array_add_obj(rcs, rc); + } + } +} + +static struct resv_print_ops resv_json_print_ops = { + .resv_report = json_nvme_resv_report, +}; + +struct resv_print_ops *resv_get_json_print_ops(nvme_print_flags_t flags) +{ + resv_json_print_ops.flags = flags; + return &resv_json_print_ops; +} diff --git a/plugins/cmds-resv/resv-print-stdout.c b/plugins/cmds-resv/resv-print-stdout.c new file mode 100644 index 0000000000..0d3cdb242f --- /dev/null +++ b/plugins/cmds-resv/resv-print-stdout.c @@ -0,0 +1,112 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include +#include + +#include + +#include +#include +#include + +#include "nvme-print.h" +#include "nvme-print-stdout.h" +#include "resv-print.h" + +static void stdout_resv_report(struct nvme_resv_status *status, int bytes, + bool eds) +{ + struct shr_table *t; + int i, regstrnt, entries; + char hex[33]; + + regstrnt = status->regstrnt[0] | (status->regstrnt[1] << 8); + + printf("\nNVME Reservation status:\n\n"); + + t = stdout_kv_table_create(); + if (!t) + return; + + stdout_kv_add(t, "gen", "%u", le32_to_cpu(status->gen)); + stdout_kv_add(t, "rtype", "%d", status->rtype); + stdout_kv_add(t, "regstrnt", "%d", regstrnt); + stdout_kv_add(t, "ptpls", "%d", status->ptpls); + + stdout_kv_table_finish(t, "resv-report"); + + /* check Extended Data Structure bit */ + if (!eds) { + /* + * if status buffer was too small, don't loop past the end of + * the buffer + */ + entries = (bytes - 24) / 24; + if (entries < regstrnt) + regstrnt = entries; + + for (i = 0; i < regstrnt; i++) { + struct nvme_registrant *reg = &status->registrant_ds[i]; + + printf("registrant[%d] :\n", i); + + t = stdout_kv_table_create(); + if (!t) + return; + shr_table_set_indent(t, 2); + + stdout_kv_add(t, "cntlid", "%x", + le16_to_cpu(reg->cntlid)); + stdout_kv_add(t, "rcsts", "%x", reg->rcsts); + stdout_kv_add(t, "hostid", "%"PRIx64, + le64_to_cpu(reg->hostid)); + stdout_kv_add(t, "rkey", "%"PRIx64, + le64_to_cpu(reg->rkey)); + + stdout_kv_table_finish(t, "registrant"); + } + } else { + /* + * if status buffer was too small, don't loop past the end of + * the buffer + */ + entries = (bytes - 64) / 64; + if (entries < regstrnt) + regstrnt = entries; + + for (i = 0; i < regstrnt; i++) { + struct nvme_registrant_ext *reg = + &status->registrant_eds[i]; + + printf("registrantext[%d] :\n", i); + + t = stdout_kv_table_create(); + if (!t) + return; + shr_table_set_indent(t, 2); + + stdout_kv_add(t, "cntlid", "%x", + le16_to_cpu(reg->cntlid)); + stdout_kv_add(t, "rcsts", "%x", reg->rcsts); + stdout_kv_add(t, "rkey", "%"PRIx64, + le64_to_cpu(reg->rkey)); + + shr_bin_to_hex(hex, sizeof(hex), reg->hostid, + sizeof(reg->hostid), 0); + stdout_kv_add(t, "hostid", "%s", hex); + + stdout_kv_table_finish(t, "registrant"); + } + } + printf("\n"); +} + +static struct resv_print_ops resv_stdout_print_ops = { + .resv_report = stdout_resv_report, +}; + +struct resv_print_ops *resv_get_stdout_print_ops(nvme_print_flags_t flags) +{ + resv_stdout_print_ops.flags = flags; + return &resv_stdout_print_ops; +} diff --git a/plugins/cmds-resv/resv-print.c b/plugins/cmds-resv/resv-print.c new file mode 100644 index 0000000000..d5095244fc --- /dev/null +++ b/plugins/cmds-resv/resv-print.c @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include + +#include "nvme-print.h" +#include "resv-print.h" + +/* + * Run the printers in the sandbox. Like nvme_print(), silently skip + * printers that an output format does not implement. + */ +#define resv_print(name, flags, ...) \ + do { \ + struct resv_print_ops *ops = resv_print_ops(flags); \ + \ + if (ops && ops->name) \ + nvme_print_decoder(ops, name, true, flags, \ + ##__VA_ARGS__); \ + } while (false) + +static struct resv_print_ops *resv_print_ops(nvme_print_flags_t flags) +{ + struct resv_print_ops *ops = NULL; + + if (flags & JSON || nvme_is_output_format_json()) + ops = resv_get_json_print_ops(flags); + else if (flags & BINARY) + ops = resv_get_binary_print_ops(flags); + else + ops = resv_get_stdout_print_ops(flags); + + return ops; +} + +void nvme_show_resv_report(struct nvme_resv_status *status, int bytes, + bool eds, nvme_print_flags_t flags) +{ + resv_print(resv_report, flags, status, bytes, eds); +} diff --git a/plugins/cmds-resv/resv-print.h b/plugins/cmds-resv/resv-print.h new file mode 100644 index 0000000000..70f87e0da5 --- /dev/null +++ b/plugins/cmds-resv/resv-print.h @@ -0,0 +1,28 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#pragma once + +#include + +#include "args.h" + +struct resv_print_ops { + void (*resv_report)(struct nvme_resv_status *status, int bytes, + bool eds); + nvme_print_flags_t flags; +}; + +struct resv_print_ops *resv_get_stdout_print_ops(nvme_print_flags_t flags); +struct resv_print_ops *resv_get_binary_print_ops(nvme_print_flags_t flags); + +#ifdef CONFIG_JSONC +struct resv_print_ops *resv_get_json_print_ops(nvme_print_flags_t flags); +#else +static inline struct resv_print_ops * +resv_get_json_print_ops(nvme_print_flags_t flags) +{ + return NULL; +} +#endif + +void nvme_show_resv_report(struct nvme_resv_status *status, int bytes, + bool eds, nvme_print_flags_t flags); diff --git a/plugins/cmds-rpmb/meson.build b/plugins/cmds-rpmb/meson.build new file mode 100644 index 0000000000..80ded470eb --- /dev/null +++ b/plugins/cmds-rpmb/meson.build @@ -0,0 +1,9 @@ +# SPDX-License-Identifier: GPL-2.0-or-later + +plugin_name = 'rpmb' + +plugin_needs += 'id' + +plugin_sources += [ + 'plugins/cmds-rpmb/rpmb.c', +] diff --git a/plugins/rpmb/rpmb.c b/plugins/cmds-rpmb/rpmb.c similarity index 99% rename from plugins/rpmb/rpmb.c rename to plugins/cmds-rpmb/rpmb.c index 30a569696b..21292edd33 100644 --- a/plugins/rpmb/rpmb.c +++ b/plugins/cmds-rpmb/rpmb.c @@ -38,6 +38,7 @@ #include "global-ctx.h" #include "nvme-print.h" #include "plugin.h" +#include "plugins/cmds-id/id.h" /* Read data from given file into buffer and return its length */ static int read_file(const char *file, unsigned char **data, unsigned int *len) @@ -793,7 +794,7 @@ static int rpmb_info(int argc, char **argv, struct command *acmd, struct plugin if (err) return err; - nvme_show_id_ctrl_rpmbs(regs.rpmbs, 0); + nvme_show_id_ctrl_rpmbs(cpu_to_le32(regs.rpmbs), 0); return 0; } diff --git a/plugins/cmds-security/meson.build b/plugins/cmds-security/meson.build new file mode 100644 index 0000000000..e4b08d10d0 --- /dev/null +++ b/plugins/cmds-security/meson.build @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: GPL-2.0-or-later + +plugin_name = 'security' + +plugin_sources += [ + 'plugins/cmds-security/security-plugin.c', +] diff --git a/plugins/security/security-plugin.c b/plugins/cmds-security/security-plugin.c similarity index 100% rename from plugins/security/security-plugin.c rename to plugins/cmds-security/security-plugin.c diff --git a/plugins/cmds-sed/meson.build b/plugins/cmds-sed/meson.build new file mode 100644 index 0000000000..953d664609 --- /dev/null +++ b/plugins/cmds-sed/meson.build @@ -0,0 +1,10 @@ +# SPDX-License-Identifier: GPL-2.0-or-later + +plugin_name = 'sed' + +if want_sed + plugin_sources += [ + 'plugins/cmds-sed/sed.c', + 'plugins/cmds-sed/sedopal_cmd.c', + ] +endif diff --git a/plugins/sed/sed.c b/plugins/cmds-sed/sed.c similarity index 100% rename from plugins/sed/sed.c rename to plugins/cmds-sed/sed.c diff --git a/plugins/sed/sedopal_cmd.c b/plugins/cmds-sed/sedopal_cmd.c similarity index 100% rename from plugins/sed/sedopal_cmd.c rename to plugins/cmds-sed/sedopal_cmd.c diff --git a/plugins/sed/sedopal_cmd.h b/plugins/cmds-sed/sedopal_cmd.h similarity index 100% rename from plugins/sed/sedopal_cmd.h rename to plugins/cmds-sed/sedopal_cmd.h diff --git a/plugins/utils/command-metadata-schema.json b/plugins/cmds-utils/command-metadata-schema.json similarity index 100% rename from plugins/utils/command-metadata-schema.json rename to plugins/cmds-utils/command-metadata-schema.json diff --git a/plugins/utils/command-metadata.c b/plugins/cmds-utils/command-metadata.c similarity index 100% rename from plugins/utils/command-metadata.c rename to plugins/cmds-utils/command-metadata.c diff --git a/plugins/utils/command-metadata.h b/plugins/cmds-utils/command-metadata.h similarity index 100% rename from plugins/utils/command-metadata.h rename to plugins/cmds-utils/command-metadata.h diff --git a/plugins/cmds-utils/meson.build b/plugins/cmds-utils/meson.build new file mode 100644 index 0000000000..ee72406db7 --- /dev/null +++ b/plugins/cmds-utils/meson.build @@ -0,0 +1,8 @@ +# SPDX-License-Identifier: GPL-2.0-or-later + +plugin_name = 'utils' + +plugin_sources += [ + 'plugins/cmds-utils/utils.c', + 'plugins/cmds-utils/command-metadata.c', +] diff --git a/plugins/utils/utils.c b/plugins/cmds-utils/utils.c similarity index 100% rename from plugins/utils/utils.c rename to plugins/cmds-utils/utils.c diff --git a/plugins/cmds-zns/meson.build b/plugins/cmds-zns/meson.build new file mode 100644 index 0000000000..ea35341e62 --- /dev/null +++ b/plugins/cmds-zns/meson.build @@ -0,0 +1,19 @@ +# SPDX-License-Identifier: GPL-2.0-or-later + +plugin_name = 'zns' + +# zns list prints its table with the row printer of nvme list +plugin_needs = ['cmds-list'] + +plugin_sources += [ + 'plugins/cmds-zns/zns.c', + 'plugins/cmds-zns/zns-print.c', + 'plugins/cmds-zns/zns-print-stdout.c', + 'plugins/cmds-zns/zns-print-binary.c', +] + +if json_c_dep.found() + plugin_sources += [ + 'plugins/cmds-zns/zns-print-json.c', + ] +endif diff --git a/plugins/zns/zns-print-binary.c b/plugins/cmds-zns/zns-print-binary.c similarity index 100% rename from plugins/zns/zns-print-binary.c rename to plugins/cmds-zns/zns-print-binary.c diff --git a/plugins/zns/zns-print-json.c b/plugins/cmds-zns/zns-print-json.c similarity index 100% rename from plugins/zns/zns-print-json.c rename to plugins/cmds-zns/zns-print-json.c diff --git a/plugins/zns/zns-print-stdout.c b/plugins/cmds-zns/zns-print-stdout.c similarity index 100% rename from plugins/zns/zns-print-stdout.c rename to plugins/cmds-zns/zns-print-stdout.c diff --git a/plugins/zns/zns-print.c b/plugins/cmds-zns/zns-print.c similarity index 100% rename from plugins/zns/zns-print.c rename to plugins/cmds-zns/zns-print.c diff --git a/plugins/zns/zns-print.h b/plugins/cmds-zns/zns-print.h similarity index 100% rename from plugins/zns/zns-print.h rename to plugins/cmds-zns/zns-print.h diff --git a/plugins/zns/zns.c b/plugins/cmds-zns/zns.c similarity index 99% rename from plugins/zns/zns.c rename to plugins/cmds-zns/zns.c index db7e506110..82d4dcda2f 100644 --- a/plugins/zns/zns.c +++ b/plugins/cmds-zns/zns.c @@ -16,6 +16,7 @@ #include "global-ctx.h" #include "nvme-print.h" +#include "plugins/cmds-list/cmds-list-print.h" #include "plugin.h" #include "src/cleanup.h" #include "zns-print.h" diff --git a/plugins/dell/dell-nvme.c b/plugins/dell/dell-nvme.c index f0a4e156c1..d0afc6fd66 100644 --- a/plugins/dell/dell-nvme.c +++ b/plugins/dell/dell-nvme.c @@ -13,7 +13,7 @@ #include #include "plugin.h" -#include "plugins/id/id.h" +#include "plugins/cmds-id/id.h" #define ARRAY_NAME_LEN 80 diff --git a/plugins/fdp/meson.build b/plugins/fdp/meson.build deleted file mode 100644 index 93d57a6e99..0000000000 --- a/plugins/fdp/meson.build +++ /dev/null @@ -1,14 +0,0 @@ -# SPDX-License-Identifier: GPL-2.0-or-later - -plugin_sources += [ - 'plugins/fdp/fdp.c', - 'plugins/fdp/fdp-print.c', - 'plugins/fdp/fdp-print-stdout.c', - 'plugins/fdp/fdp-print-binary.c', -] - -if json_c_dep.found() - plugin_sources += [ - 'plugins/fdp/fdp-print-json.c', - ] -endif diff --git a/plugins/feat/meson.build b/plugins/feat/meson.build deleted file mode 100644 index b97fc41bc8..0000000000 --- a/plugins/feat/meson.build +++ /dev/null @@ -1,5 +0,0 @@ -# SPDX-License-Identifier: GPL-2.0-or-later - -plugin_sources += [ - 'plugins/feat/feat-nvme.c', -] diff --git a/plugins/fw/meson.build b/plugins/fw/meson.build deleted file mode 100644 index 79c0902453..0000000000 --- a/plugins/fw/meson.build +++ /dev/null @@ -1,5 +0,0 @@ -# SPDX-License-Identifier: GPL-2.0-or-later - -plugin_sources += [ - 'plugins/fw/fw-plugin.c', -] diff --git a/plugins/huawei/huawei-nvme.c b/plugins/huawei/huawei-nvme.c index bd924d59f1..953d73ed76 100644 --- a/plugins/huawei/huawei-nvme.c +++ b/plugins/huawei/huawei-nvme.c @@ -37,7 +37,7 @@ #include "global-ctx.h" #include "nvme-print.h" #include "plugin.h" -#include "plugins/id/id.h" +#include "plugins/cmds-id/id.h" #define HW_SSD_PCI_VENDOR_ID 0x19E5 #define ARRAY_NAME_LEN 80 diff --git a/plugins/ibm/ibm-nvme.c b/plugins/ibm/ibm-nvme.c index ddf9dd9b53..690e1f1919 100644 --- a/plugins/ibm/ibm-nvme.c +++ b/plugins/ibm/ibm-nvme.c @@ -13,7 +13,7 @@ #include "nvme-cmds.h" #include "nvme-print.h" #include "plugin.h" -#include "plugins/log/log-print.h" +#include "plugins/cmds-log/log-print.h" #pragma pack(push, 1) struct nvme_ibm_log_f0_item { diff --git a/plugins/id/meson.build b/plugins/id/meson.build deleted file mode 100644 index 385ffadf74..0000000000 --- a/plugins/id/meson.build +++ /dev/null @@ -1,15 +0,0 @@ -# SPDX-License-Identifier: GPL-2.0-or-later - -plugin_sources += [ - 'plugins/id/id-plugin.c', - 'plugins/id/nvme-models.c', - 'plugins/id/id-print.c', - 'plugins/id/id-print-stdout.c', - 'plugins/id/id-print-binary.c', -] - -if json_c_dep.found() - plugin_sources += [ - 'plugins/id/id-print-json.c', - ] -endif diff --git a/plugins/intel/intel-nvme.c b/plugins/intel/intel-nvme.c index 482e6d7da3..078b8f1e04 100644 --- a/plugins/intel/intel-nvme.c +++ b/plugins/intel/intel-nvme.c @@ -19,7 +19,7 @@ #include "nvme-cmds.h" #include "nvme-print.h" #include "plugin.h" -#include "plugins/id/id.h" +#include "plugins/cmds-id/id.h" struct __packed nvme_additional_smart_log_item { __u8 key; diff --git a/plugins/lm/meson.build b/plugins/lm/meson.build deleted file mode 100644 index 723ab07e2f..0000000000 --- a/plugins/lm/meson.build +++ /dev/null @@ -1,14 +0,0 @@ -# SPDX-License-Identifier: GPL-2.0-or-later - -plugin_sources += [ - 'plugins/lm/lm-nvme.c', - 'plugins/lm/lm-print.c', - 'plugins/lm/lm-print-stdout.c', - 'plugins/lm/lm-print-binary.c', -] - -if json_c_dep.found() - plugin_sources += [ - 'plugins/lm/lm-print-json.c', - ] -endif diff --git a/plugins/log/meson.build b/plugins/log/meson.build deleted file mode 100644 index b97b1e06f3..0000000000 --- a/plugins/log/meson.build +++ /dev/null @@ -1,14 +0,0 @@ -# SPDX-License-Identifier: GPL-2.0-or-later - -plugin_sources += [ - 'plugins/log/log-plugin.c', - 'plugins/log/log-print.c', - 'plugins/log/log-print-stdout.c', - 'plugins/log/log-print-binary.c', -] - -if json_c_dep.found() - plugin_sources += [ - 'plugins/log/log-print-json.c', - ] -endif diff --git a/plugins/mangoboost/mangoboost-nvme.c b/plugins/mangoboost/mangoboost-nvme.c index 512b079a7a..c6020b7704 100644 --- a/plugins/mangoboost/mangoboost-nvme.c +++ b/plugins/mangoboost/mangoboost-nvme.c @@ -18,7 +18,7 @@ #include #include "plugin.h" -#include "plugins/id/id.h" +#include "plugins/cmds-id/id.h" struct nvme_vu_id_ctrl_field { __u16 json_rpc_2_0_mjr; diff --git a/plugins/memblaze/memblaze-nvme.c b/plugins/memblaze/memblaze-nvme.c index 2df6e700e9..3ebfd9e46c 100644 --- a/plugins/memblaze/memblaze-nvme.c +++ b/plugins/memblaze/memblaze-nvme.c @@ -507,7 +507,7 @@ static int mb_get_powermanager_status(int argc, char **argv, struct command *acm if (!err) printf("get-feature:0x%02x (%s), %s value: %#016" PRIx64 "\n", feature_id, mb_feature_to_string(feature_id), - nvme_select_to_string(0), (uint64_t)result); + "Current", (uint64_t)result); else nvme_show_err(err, "get-feature"); return err; diff --git a/plugins/meson.build b/plugins/meson.build index 49af66945e..871880eb5d 100644 --- a/plugins/meson.build +++ b/plugins/meson.build @@ -4,16 +4,41 @@ fs = import('fs') selected_plugins = get_option('plugins') -# Each plugin directory appends its sources to plugin_sources. It may set -# plugin_name, the name of the plugin on the command line, when it is not -# the name of the directory, and plugin_needs to the plugins whose -# functions it calls. Plugins needed by a selected plugin are selected as -# well: each round visits the plugins needed by the previous round. +# A plugin lives in plugins/, or in plugins/cmds- for the +# plugins of nvme itself. Its directory appends its sources to +# plugin_sources. It may set plugin_name, the name of the plugin on the +# command line, when it is not the name of the directory, and plugin_needs +# to the plugins whose functions it calls. Plugins needed by a selected +# plugin are selected as well: each round visits the plugins needed by the +# previous round. +# +# A plugin which adds top-level commands ("nvme ") lists them in +# plugin_commands, and their aliases in plugin_command_aliases, a dict +# from command to alias. nvme loads the module for these commands. A +# plugin with only top-level commands, without "nvme ", sets +# plugin_extension to false. plugin_sources = [] enabled_plugins = [] plugin_defs = [] visited_plugins = [] pending_plugins = selected_plugins +# The deprecated top-level commands are a plugin of their own +if want_deprecated_cmds + pending_plugins += 'deprecated' +endif +# The I/O commands +pending_plugins += 'cmds-io' +pending_plugins += 'cmds-admin' +# The register commands +pending_plugins += 'cmds-regs' +# The passthru commands +pending_plugins += 'cmds-passthru' +# get-feature and set-feature are top-level commands of the feat plugin +pending_plugins += 'feat' +# The device enumeration commands +pending_plugins += 'cmds-list' +# The fabrics top-level commands +pending_plugins += 'cmds-fabrics' foreach round : range(16) if pending_plugins.length() == 0 break @@ -25,10 +50,17 @@ foreach round : range(16) continue endif visited_plugins += plugin_dir + plugin_subdir = plugin_dir + if fs.is_dir(meson.current_source_dir() / ('cmds-' + plugin_dir)) + plugin_subdir = 'cmds-' + plugin_dir + endif n_sources_before = plugin_sources.length() - plugin_name = plugin_dir + plugin_name = plugin_subdir plugin_needs = [] - subdir(plugin_dir) + plugin_extension = true + plugin_commands = [] + plugin_command_aliases = {} + subdir(plugin_subdir) if plugin_sources.length() > n_sources_before enabled_plugins += plugin_dir srcs = [] @@ -37,9 +69,13 @@ foreach round : range(16) endforeach plugin_defs += { 'dir': plugin_dir, + 'subdir': plugin_subdir, 'name': plugin_name, 'sources': srcs, 'needs': plugin_needs, + 'extension': plugin_extension, + 'commands': plugin_commands, + 'aliases': plugin_command_aliases, } foreach need : plugin_needs if need not in visited_plugins and need not in needed_plugins @@ -100,6 +136,28 @@ foreach def : plugin_defs endif endforeach +# The top-level commands of the plugins: ":[=]" +plugin_command_index = [] +command_index = [] +foreach def : plugin_defs + foreach cmd, alias : def['aliases'] + if cmd not in def['commands'] + error('the @0@ plugin has an alias for no command: @1@'.format( + def['dir'], cmd)) + endif + endforeach + foreach cmd : def['commands'] + alias = def['aliases'].get(cmd, '') + entry = '@0@:@1@'.format(def['subdir'], cmd) + if alias != '' + entry += '=' + alias + endif + plugin_command_index += entry + command_index += '{ "@0@", @1@, "@2@" }, '.format( + cmd, alias != '' ? '"' + alias + '"' : 'NULL', def['subdir']) + endforeach +endforeach + plugin_deps = [] foreach d : [config_dep, ccan_dep, libnvme_dep, shared_dep, json_c_dep, libkmod_dep] @@ -121,15 +179,26 @@ if want_plugin_modules configuration: {'NVME_PLUGIN_ABI': '"' + conf.get_unquoted('NVME_PLUGIN_ABI') + '"'}, ) - # The plugins of this build, a missing module is "not installed" + # The plugins of this build and their modules, which are named after + # the directory of the plugin. A missing module is "not installed". plugin_names = [] foreach def : plugin_defs - plugin_names += '"@0@"'.format(def['name']) + if def['extension'] + plugin_names += '{ "@0@", "@1@" }'.format(def['name'], def['subdir']) + endif endforeach configure_file( output: 'plugin-names.h', configuration: {'NVME_PLUGIN_NAMES': ', '.join(plugin_names)}, ) + + # The top-level commands of the modules, see plugin-loader.c + configure_file( + output: 'command-index.h', + configuration: { + 'NVME_COMMAND_INDEX': ''.join(command_index) + '{ NULL, NULL, NULL }', + }, + ) endif plugin_names_inc = include_directories('.') foreach def : ordered_plugin_defs @@ -160,7 +229,7 @@ foreach def : ordered_plugin_defs 'include_directories': include_directories('../src'), 'c_args': c_args + [ '-DNVME_PLUGIN_MODULE', - '-DNVME_PLUGIN_ID=' + def['name'].replace('-', '_'), + '-DNVME_PLUGIN_ID=' + def['subdir'].replace('-', '_'), ], 'dependencies': plugin_deps, 'link_with': link_with, @@ -171,9 +240,9 @@ foreach def : ordered_plugin_defs 'install_dir': plugin_module_dir, } if def['dir'] in plugin_providers - target = shared_library(def['name'], srcs, kwargs: module_kwargs) + target = shared_library(def['subdir'], srcs, kwargs: module_kwargs) else - target = shared_module(def['name'], srcs, kwargs: module_kwargs) + target = shared_module(def['subdir'], srcs, kwargs: module_kwargs) endif plugin_targets += {def['dir']: target} plugin_module_targets += target @@ -195,11 +264,16 @@ endforeach core_plugins = [] vendor_plugins = [] disabled_plugins = [] +plugin_subdirs = {} +foreach def : plugin_defs + plugin_subdirs += {def['dir']: def['subdir']} +endforeach foreach plugin_name : all_plugin_names if plugin_name in enabled_plugins is_core = false + plugin_subdir = plugin_subdirs.get(plugin_name, plugin_name) foreach src : plugin_sources - if src.startswith('plugins/' + plugin_name + '/') and fs.read(meson.project_source_root() / src).contains('.core = true') + if src.startswith('plugins/' + plugin_subdir + '/') and fs.read(meson.project_source_root() / src).contains('.core = true') is_core = true endif endforeach diff --git a/plugins/micron/micron-nvme.c b/plugins/micron/micron-nvme.c index a9e33f1f2d..db03af12ef 100644 --- a/plugins/micron/micron-nvme.c +++ b/plugins/micron/micron-nvme.c @@ -43,7 +43,7 @@ #include "nvme-pci-ids.h" #include "nvme-print.h" #include "plugin.h" -#include "plugins/id/id.h" +#include "plugins/cmds-id/id.h" #include "src/cleanup.h" /* Supported Vendor specific feature ids */ diff --git a/plugins/ns/meson.build b/plugins/ns/meson.build deleted file mode 100644 index 65e387753f..0000000000 --- a/plugins/ns/meson.build +++ /dev/null @@ -1,5 +0,0 @@ -# SPDX-License-Identifier: GPL-2.0-or-later - -plugin_sources += [ - 'plugins/ns/ns-plugin.c', -] diff --git a/plugins/nvidia/nvidia-nvme.c b/plugins/nvidia/nvidia-nvme.c index c9416870d6..552bfa8184 100644 --- a/plugins/nvidia/nvidia-nvme.c +++ b/plugins/nvidia/nvidia-nvme.c @@ -12,7 +12,7 @@ #include #include "plugin.h" -#include "plugins/id/id.h" +#include "plugins/cmds-id/id.h" struct nvme_vu_id_ctrl_field { __u16 json_rpc_2_0_mjr; diff --git a/plugins/nvme-mi/meson.build b/plugins/nvme-mi/meson.build deleted file mode 100644 index 235964aa9b..0000000000 --- a/plugins/nvme-mi/meson.build +++ /dev/null @@ -1,5 +0,0 @@ -# SPDX-License-Identifier: GPL-2.0-or-later - -plugin_sources += [ - 'plugins/nvme-mi/nvme-mi-plugin.c', -] diff --git a/plugins/ocp/meson.build b/plugins/ocp/meson.build deleted file mode 100644 index 58ca157b85..0000000000 --- a/plugins/ocp/meson.build +++ /dev/null @@ -1,22 +0,0 @@ -# SPDX-License-Identifier: GPL-2.0-or-later - -plugin_needs = ['log'] - -plugin_sources += [ - 'plugins/ocp/ocp-utils.c', - 'plugins/ocp/ocp-nvme.c', - 'plugins/ocp/ocp-clear-features.c', - 'plugins/ocp/ocp-smart-extended-log.c', - 'plugins/ocp/ocp-fw-activation-history.c', - 'plugins/ocp/ocp-telemetry-decode.c', - 'plugins/ocp/ocp-hardware-component-log.c', - 'plugins/ocp/ocp-print.c', - 'plugins/ocp/ocp-print-stdout.c', - 'plugins/ocp/ocp-print-binary.c', -] - -if json_c_dep.found() - plugin_sources += [ - 'plugins/ocp/ocp-print-json.c', - ] -endif diff --git a/plugins/registry/meson.build b/plugins/registry/meson.build deleted file mode 100644 index e9c2bc5437..0000000000 --- a/plugins/registry/meson.build +++ /dev/null @@ -1,7 +0,0 @@ -# SPDX-License-Identifier: GPL-2.0-or-later - -if want_fabrics - plugin_sources += [ - 'plugins/registry/registry-nvme.c', - ] -endif diff --git a/plugins/resv/meson.build b/plugins/resv/meson.build deleted file mode 100644 index 5799a69240..0000000000 --- a/plugins/resv/meson.build +++ /dev/null @@ -1,5 +0,0 @@ -# SPDX-License-Identifier: GPL-2.0-or-later - -plugin_sources += [ - 'plugins/resv/resv-plugin.c', -] diff --git a/plugins/rpmb/meson.build b/plugins/rpmb/meson.build deleted file mode 100644 index f2775321bc..0000000000 --- a/plugins/rpmb/meson.build +++ /dev/null @@ -1,5 +0,0 @@ -# SPDX-License-Identifier: GPL-2.0-or-later - -plugin_sources += [ - 'plugins/rpmb/rpmb.c', -] diff --git a/plugins/security/meson.build b/plugins/security/meson.build deleted file mode 100644 index 4c26817b0e..0000000000 --- a/plugins/security/meson.build +++ /dev/null @@ -1,5 +0,0 @@ -# SPDX-License-Identifier: GPL-2.0-or-later - -plugin_sources += [ - 'plugins/security/security-plugin.c', -] diff --git a/plugins/sed/meson.build b/plugins/sed/meson.build deleted file mode 100644 index 0199e6aef3..0000000000 --- a/plugins/sed/meson.build +++ /dev/null @@ -1,8 +0,0 @@ -# SPDX-License-Identifier: GPL-2.0-or-later - -if want_sed - plugin_sources += [ - 'plugins/sed/sed.c', - 'plugins/sed/sedopal_cmd.c', - ] -endif diff --git a/plugins/shannon/shannon-nvme.c b/plugins/shannon/shannon-nvme.c index 1fcfdc8841..3391a06e00 100644 --- a/plugins/shannon/shannon-nvme.c +++ b/plugins/shannon/shannon-nvme.c @@ -16,7 +16,7 @@ #include "nvme-cmds.h" #include "nvme-print.h" #include "plugin.h" -#include "plugins/id/id.h" +#include "plugins/cmds-id/id.h" enum { PROGRAM_FAIL_CNT, diff --git a/plugins/solidigm/solidigm-internal-logs.c b/plugins/solidigm/solidigm-internal-logs.c index 01453187bf..764d5098dc 100644 --- a/plugins/solidigm/solidigm-internal-logs.c +++ b/plugins/solidigm/solidigm-internal-logs.c @@ -33,7 +33,7 @@ #include "nvme-cmds.h" #include "nvme-print.h" #include "plugin.h" -#include "plugins/log/log-print.h" +#include "plugins/cmds-log/log-print.h" #include "solidigm-util.h" #define DWORD_SIZE 4 diff --git a/plugins/solidigm/solidigm-log-page-dir.c b/plugins/solidigm/solidigm-log-page-dir.c index f66121ec80..b43bc2f151 100644 --- a/plugins/solidigm/solidigm-log-page-dir.c +++ b/plugins/solidigm/solidigm-log-page-dir.c @@ -18,9 +18,9 @@ #include "global-ctx.h" #include "nvme-print.h" #include "plugin.h" -#include "plugins/log/log-print.h" -#include "plugins/ocp/ocp-nvme.h" -#include "plugins/ocp/ocp-utils.h" +#include "plugins/cmds-log/log-print.h" +#include "plugins/cmds-ocp/ocp-nvme.h" +#include "plugins/cmds-ocp/ocp-utils.h" #include "solidigm-log-page-dir.h" #include "solidigm-util.h" diff --git a/plugins/solidigm/solidigm-nvme.c b/plugins/solidigm/solidigm-nvme.c index 0013f1b071..923878b3ce 100644 --- a/plugins/solidigm/solidigm-nvme.c +++ b/plugins/solidigm/solidigm-nvme.c @@ -12,10 +12,10 @@ #define SOLIDIGM_PLUGIN_VERSION "1.27" -#include "plugins/id/id.h" -#include "plugins/ocp/ocp-clear-features.h" -#include "plugins/ocp/ocp-fw-activation-history.h" -#include "plugins/ocp/ocp-smart-extended-log.h" +#include "plugins/cmds-id/id.h" +#include "plugins/cmds-ocp/ocp-clear-features.h" +#include "plugins/cmds-ocp/ocp-fw-activation-history.h" +#include "plugins/cmds-ocp/ocp-smart-extended-log.h" #include "solidigm-garbage-collection.h" #include "solidigm-get-drive-info.h" #include "solidigm-id-ctrl.h" diff --git a/plugins/utils/meson.build b/plugins/utils/meson.build deleted file mode 100644 index b41d48fa7e..0000000000 --- a/plugins/utils/meson.build +++ /dev/null @@ -1,6 +0,0 @@ -# SPDX-License-Identifier: GPL-2.0-or-later - -plugin_sources += [ - 'plugins/utils/utils.c', - 'plugins/utils/command-metadata.c', -] diff --git a/plugins/wdc/wdc-nvme.c b/plugins/wdc/wdc-nvme.c index 25cc68b2cc..8429c14564 100644 --- a/plugins/wdc/wdc-nvme.c +++ b/plugins/wdc/wdc-nvme.c @@ -54,7 +54,7 @@ #include "nvme-pci-ids.h" #include "nvme-print.h" #include "plugin.h" -#include "plugins/id/id.h" +#include "plugins/cmds-id/id.h" #include "src/cleanup.h" #define WDC_PLUGIN_VERSION "3.2.0" diff --git a/plugins/zns/meson.build b/plugins/zns/meson.build deleted file mode 100644 index 14a7f120d9..0000000000 --- a/plugins/zns/meson.build +++ /dev/null @@ -1,14 +0,0 @@ -# SPDX-License-Identifier: GPL-2.0-or-later - -plugin_sources += [ - 'plugins/zns/zns.c', - 'plugins/zns/zns-print.c', - 'plugins/zns/zns-print-stdout.c', - 'plugins/zns/zns-print-binary.c', -] - -if json_c_dep.found() - plugin_sources += [ - 'plugins/zns/zns-print-json.c', - ] -endif diff --git a/src/meson.build b/src/meson.build index 9d1c6c7d98..a9aa2e2d63 100644 --- a/src/meson.build +++ b/src/meson.build @@ -10,25 +10,11 @@ sources = [ 'src/nvme-pci-ids.c', 'src/nvme-print-binary.c', 'src/nvme-print-stdout.c', - 'src/nvme-print-stdout-id.c', - 'src/nvme-print-stdout-log.c', 'src/nvme-print.c', - 'src/nvme-regs.c', + 'src/nvme-resources.c', 'src/nvme.c', - 'src/nvme-cmds-enumerate.c', - 'src/nvme-cmds-ctrl.c', - 'src/nvme-cmds-deprecated.c', - 'src/nvme-cmds-discovery.c', - 'src/nvme-cmds-fabrics.c', - 'src/nvme-cmds-feature.c', - 'src/nvme-cmds-io.c', - 'src/nvme-cmds-passthru.c', - 'src/nvme-cmds-registers.c', - 'src/nvme-cmds-sanitize.c', - 'src/nvme-cmds-security.c', 'src/plugin.c', 'src/privsep.c', - 'src/bitfields.c', 'src/field-parser.c', ] @@ -39,7 +25,6 @@ endif if host_system == 'linux' sources += [ 'src/nvme-pci-ids-linux.c', - 'src/dashboard.c', ] elif host_system == 'windows' sources += [ @@ -58,15 +43,3 @@ if json_c_dep.found() ] endif -if want_fabrics - sources += [ - 'src/fabrics.c', - 'src/config-convert.c', - 'src/config-create.c', - 'src/pre-os.c', - ] -endif - -if want_top - sources += ['src/nvme-iostat.c', 'src/nvme-print-stdout-top.c'] -endif diff --git a/src/nvme-cmds-common.h b/src/nvme-cmds-common.h index 99efce91f8..0e7f7ad7bc 100644 --- a/src/nvme-cmds-common.h +++ b/src/nvme-cmds-common.h @@ -15,58 +15,6 @@ #include "nvme-print.h" -struct feat_cfg { - __u8 feature_id; /* enum nvme_features_id */ - __u8 sel; /* enum nvme_get_features_sel */ - __u32 namespace_id; - __u32 cdw11; - __u32 cdw12; - __u8 uuid_index; - __u32 data_len; - bool raw_binary; - bool changed; -}; - -struct passthru_config { - __u8 opcode; - __u8 flags; - __u16 rsvd; - __u32 namespace_id; - __u32 data_len; - __u32 metadata_len; - __u32 cdw2; - __u32 cdw3; - __u32 cdw10; - __u32 cdw11; - __u32 cdw12; - __u32 cdw13; - __u32 cdw14; - __u32 cdw15; - char *input_file; - char *metadata; - bool raw_binary; - bool show_command; - bool read; - bool write; - __u8 prefill; - bool latency; -}; - -struct nvme_get_log_args { - __u32 nsid; - bool rae; - __u8 lsp; - enum nvme_cmd_get_log_lid lid; - __u16 lsi; - enum nvme_csi csi; - bool ot; - __u8 uidx; - __u64 lpo; - void *log; - __u32 len; - __u64 *result; -}; - static inline bool nvme_match_devname(char *devname, struct libnvme_ns *ns) { struct libnvme_ctrl *c = libnvme_ns_get_ctrl(ns); diff --git a/src/nvme-print-binary.c b/src/nvme-print-binary.c index 581a62f061..0a1adcc5d1 100644 --- a/src/nvme-print-binary.c +++ b/src/nvme-print-binary.c @@ -3,104 +3,18 @@ #include #include -#include -#include #include "nvme-print.h" static struct print_ops binary_print_ops; -/* - * The registers as they are in BAR0, 0h to E1Bh, the ones not read zero: - * all of them for a PCIe controller, the properties of a fabrics one. - */ -static void binary_ctrl_registers(const struct nvme_reg_val *vals, - unsigned int nr, - enum nvme_regs_style style __shr_unused) -{ - const unsigned int size = NVME_REG_PMRMSCU + sizeof(uint32_t); - unsigned char page[NVME_REG_PMRMSCU + sizeof(uint32_t)] = { 0 }; - unsigned int i; - - for (i = 0; i < nr; i++) { - const struct nvme_reg *reg = vals[i].reg; - - if (reg->offset + reg->size > size) - continue; - if (reg->size == 8) - shr_mmio_write64(page + reg->offset, vals[i].value, - true); - else - shr_mmio_write32(page + reg->offset, vals[i].value); - } - - d_raw(page, size); -} - -static void binary_resv_report(struct nvme_resv_status *status, int bytes, - bool eds) -{ - d_raw((unsigned char *)status, bytes); -} - - -static void binary_directive(__u8 type, __u8 oper, __u16 spec, __u32 nsid, __u64 result, - void *buf, __u32 len) -{ - if (!buf) - return; - - d_raw(buf, len); -} - -static void binary_lba_status(struct nvme_lba_status *list, unsigned long len) -{ - d_raw((unsigned char *)list, len); -} - -static void binary_discovery_log(const struct nvmf_discovery_log *log, - int numrec) -{ - d_raw((unsigned char *)log, - sizeof(struct nvmf_discovery_log) + - numrec * sizeof(struct nvmf_disc_log_entry)); -} - -static void binary_feature_show(enum nvme_features_id fid, int sel, - unsigned int result, void *buf, __u32 data_len) -{ - if (buf) { - d_raw(buf, data_len); - } -} - static struct print_ops binary_print_ops = { /* libnvme types.h print functions */ - .ctrl_registers = binary_ctrl_registers, - .directive = binary_directive, - .discovery_log = binary_discovery_log, - .lba_status = binary_lba_status, - .resv_report = binary_resv_report, - .select_result = NULL, - .show_feature = binary_feature_show, - .show_feature_fields = NULL, - .id_ctrl_rpmbs = NULL, - .lba_range = NULL, - .lba_status_info = NULL, .d = NULL, .show_init = NULL, .show_finish = NULL, - /* libnvme tree print functions */ - .list_item = NULL, - .list_items = NULL, - .print_nvme_subsystem_list = NULL, - .topology_ctrl = NULL, - .topology_namespace = NULL, - .topology_multipath = NULL, - /* status and error messages */ - .connect_msg = NULL, .show_message = NULL, .show_perror = NULL, .show_status = NULL, diff --git a/src/nvme-print-json.c b/src/nvme-print-json.c index 461f0217a2..f267f1f14d 100644 --- a/src/nvme-print-json.c +++ b/src/nvme-print-json.c @@ -4,2498 +4,172 @@ #include #include #include -#include -#ifdef CONFIG_FABRICS -#include -#include -#endif - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "cleanup.h" -#include "global-ctx.h" -#include "nvme-iostat.h" -#include "nvme-json.h" -#include "nvme-print.h" -#include "nvme-print-json.h" - -#define ERROR_MSG_LEN 100 -#define NAME_LEN 128 -#define BUF_LEN 320 -#define VAL_LEN 4096 - -static struct print_ops json_print_ops; -static struct json_object *json_r; -static bool json_init; - -static void d_json(unsigned char *buf, int len, int width, int group, struct json_object *array) -{ - int i; - char ascii[32 + 1] = { 0 }; - - assert(width < sizeof(ascii)); - - for (i = 0; i < len; i++) { - ascii[i % width] = (buf[i] >= '!' && buf[i] <= '~') ? buf[i] : '.'; - if (!((i + 1) % width)) { - array_add_str(array, ascii); - memset(ascii, 0, sizeof(ascii)); - } - } - - if (strlen(ascii)) { - ascii[i % width + 1] = '\0'; - array_add_str(array, ascii); - } -} - -void obj_d(struct json_object *o, const char *k, unsigned char *buf, int len, - int width, int group) -{ - struct json_object *data = json_create_array(); - - d_json(buf, len, width, group, data); - obj_add_array(o, k, data); -} - - -void obj_add_uint_nx(struct json_object *o, const char *k, __u32 v) -{ - char str[STR_LEN]; - - sprintf(str, "%#x", v); - obj_add_str(o, k, str); -} - - -static void obj_add_ctrl_address(struct json_object *o, struct libnvme_ctrl *c) -{ - const char *address = libnvme_ctrl_get_address(c); - - /* controllers without an address, e.g. loop, don't report one */ - obj_add_str(o, "Address", address ? address : ""); -} - -static void obj_add_ctrl_address_details(struct json_object *o, const char *k, - struct libnvme_ctrl *c) -{ - struct json_object *address_details = json_create_object(); - const char *value; - bool has_value = false; - - value = libnvme_ctrl_get_traddr(c); - if (value) { - obj_add_str(address_details, "traddr", value); - has_value = true; - } - - value = libnvme_ctrl_get_host_traddr(c); - if (value) { - obj_add_str(address_details, "host_traddr", value); - has_value = true; - } - - value = libnvme_ctrl_get_host_iface(c); - if (value) { - obj_add_str(address_details, "host_iface", value); - has_value = true; - } - - value = libnvme_ctrl_get_trsvcid(c); - if (value) { - obj_add_str(address_details, "trsvcid", value); - has_value = true; - } - - if (!has_value) { - json_free_object(address_details); - return; - } - - obj_add_obj(o, k, address_details); -} - - -void obj_add_result(struct json_object *o, const char *v, ...) -{ - va_list ap; - - __cleanup_free char *value = NULL; - - va_start(ap, v); - - if (vasprintf(&value, v, ap) < 0) - value = NULL; - - obj_add_str(o, "Result", value ? value : alloc_error); - - va_end(ap); -} - -void obj_add_key(struct json_object *o, const char *k, const char *v, ...) -{ - va_list ap; - - __cleanup_free char *value = NULL; - - va_start(ap, v); - - if (vasprintf(&value, v, ap) < 0) - value = NULL; - - obj_add_str(o, k, value ? value : alloc_error); - - va_end(ap); -} - -struct json_object *obj_create_array_obj(struct json_object *o, const char *k) -{ - struct json_object *array = json_create_array(); - struct json_object *obj = json_create_object(); - - obj_add_array(o, k, array); - array_add_obj(array, obj); - - return obj; -} - -struct json_object *obj_create(const char *k) -{ - struct json_object *array; - struct json_object *obj = json_create_object(); - - if (json_r) { - array = json_create_array(); - obj_add_array(json_r, k, array); - array_add_obj(array, obj); - } - - return obj; -} - -void json_print(struct json_object *r) -{ - json_print_object(r, NULL); - printf("\n"); - json_free_object(r); -} - -void obj_print(struct json_object *o) -{ - if (!json_r) - json_print(o); -} - -static bool verbose_mode(void) -{ - return json_print_ops.flags & VERBOSE; -} - -bool json_verbose_mode(void) -{ - return verbose_mode(); -} - -struct json_object *json_root(void) -{ - return json_r; -} - -void json_nvme_resv_report(struct nvme_resv_status *status, - int bytes, bool eds) -{ - struct json_object *r = json_r; - struct json_object *rcs = json_create_array(); - int i, entries; - int regstrnt = status->regstrnt[0] | (status->regstrnt[1] << 8); - - obj_add_uint(r, "gen", le32_to_cpu(status->gen)); - obj_add_int(r, "rtype", status->rtype); - obj_add_int(r, "regstrnt", regstrnt); - obj_add_int(r, "ptpls", status->ptpls); - - /* check Extended Data Structure bit */ - if (!eds) { - /* - * if status buffer was too small, don't loop past the end of - * the buffer - */ - entries = (bytes - 24) / 24; - if (entries < regstrnt) - regstrnt = entries; - - obj_add_array(r, "registrants", rcs); - for (i = 0; i < regstrnt; i++) { - struct json_object *rc = json_create_object(); - - obj_add_int(rc, "cntlid", le16_to_cpu(status->registrant_ds[i].cntlid)); - obj_add_int(rc, "rcsts", status->registrant_ds[i].rcsts); - obj_add_uint64(rc, "hostid", le64_to_cpu(status->registrant_ds[i].hostid)); - obj_add_uint64(rc, "rkey", le64_to_cpu(status->registrant_ds[i].rkey)); - - array_add_obj(rcs, rc); - } - } else { - char hostid[33]; - - /* if status buffer was too small, don't loop past the end of the buffer */ - entries = (bytes - 64) / 64; - - if (entries < regstrnt) - regstrnt = entries; - - obj_add_array(r, "registrantext", rcs); - - for (i = 0; i < regstrnt; i++) { - struct json_object *rc = json_create_object(); - - obj_add_int(rc, "cntlid", le16_to_cpu(status->registrant_eds[i].cntlid)); - obj_add_int(rc, "rcsts", status->registrant_eds[i].rcsts); - obj_add_uint64(rc, "rkey", le64_to_cpu(status->registrant_eds[i].rkey)); - - shr_bin_to_hex(hostid, sizeof(hostid), - status->registrant_eds[i].hostid, - sizeof(status->registrant_eds[i].hostid), - 0); - - obj_add_str(rc, "hostid", hostid); - array_add_obj(rcs, rc); - } - } -} - -static void json_select_result(enum nvme_features_id fid, __u64 result) -{ - struct json_object *r = json_r; - char json_str[STR_LEN]; - struct json_object *feature = json_create_array(); - - if (result & 0x1) - array_add_str(feature, "saveable"); - if (result & 0x2) - array_add_str(feature, "per-namespace"); - if (result & 0x4) - array_add_str(feature, "changeable"); - - sprintf(json_str, "Feature: %#0*x: select", fid ? 4 : 2, fid); - obj_add_array(r, json_str, feature); -} - -static void json_lba_status(struct nvme_lba_status *list, - unsigned long len) -{ - struct json_object *r = json_r; - __u32 nlsd = le32_to_cpu(list->nlsd); - size_t nr = nvme_log_nr_entries(nlsd, len, sizeof(*list), - sizeof(list->descs[0])); - size_t idx; - struct nvme_lba_status_desc *e; - struct json_object *lsde; - char json_str[STR_LEN]; - - obj_add_uint(r, "Number of LBA Status Descriptors (NLSD)", nlsd); - obj_add_uint(r, "Completion Condition (CMPC)", list->cmpc); - - switch (list->cmpc) { - case NVME_LBA_STATUS_CMPC_NO_CMPC: - obj_add_str(r, "cmpc-definition", "No indication of the completion condition"); - break; - case NVME_LBA_STATUS_CMPC_INCOMPLETE: - obj_add_str(r, "cmpc-definition", - "Completed transferring the amount of data specified in the"\ - "MNDW field. But, additional LBA Status Descriptor Entries are"\ - "available to transfer or scan did not complete (if ATYPE = 10h)"); - break; - case NVME_LBA_STATUS_CMPC_COMPLETE: - obj_add_str(r, "cmpc-definition", - "Completed the specified action over the number of LBAs specified"\ - "in the Range Length field and transferred all available LBA Status"\ - "Descriptor Entries"); - break; - default: - break; - } - - for (idx = 0; idx < nr; idx++) { - lsde = json_create_object(); - sprintf(json_str, "LSD entry %zu", idx); - obj_add_obj(r, json_str, lsde); - e = &list->descs[idx]; - sprintf(json_str, "0x%016"PRIx64"", le64_to_cpu(e->dslba)); - obj_add_str(lsde, "DSLBA", json_str); - sprintf(json_str, "0x%08x", le32_to_cpu(e->nlb)); - obj_add_str(lsde, "NLB", json_str); - sprintf(json_str, "0x%02x", e->status); - obj_add_str(lsde, "status", json_str); - } -} - -static unsigned int json_print_nvme_subsystem_multipath(struct libnvme_subsystem *s, json_object *paths) -{ - struct libnvme_ns *n; - struct libnvme_path *p; - unsigned int i = 0; - - n = libnvme_subsystem_first_ns(s); - if (!n) - return 0; - - libnvme_namespace_for_each_path(n, p) { - struct json_object *path_attrs; - struct libnvme_ctrl *c = libnvme_path_get_ctrl(p); - const char *ana_state; - - libnvme_path_get_ana_state(p, &ana_state, ""); - path_attrs = json_create_object(); - obj_add_str(path_attrs, "Name", libnvme_ctrl_get_name(c)); - obj_add_str(path_attrs, "Transport", libnvme_ctrl_get_transport(c)); - obj_add_ctrl_address(path_attrs, c); - obj_add_ctrl_address_details(path_attrs, "AddressDetails", c); - obj_add_str(path_attrs, "State", libnvme_ctrl_get_state(c)); - obj_add_str(path_attrs, "ANAState", ana_state); - array_add_obj(paths, path_attrs); - i++; - } - - return i; -} - -static void json_print_nvme_subsystem_ctrls(struct libnvme_subsystem *s, - json_object *paths) -{ - struct libnvme_ctrl *c; - - libnvme_subsystem_for_each_ctrl(s, c) { - struct json_object *path_attrs; - - path_attrs = json_create_object(); - obj_add_str(path_attrs, "Name", libnvme_ctrl_get_name(c)); - obj_add_str(path_attrs, "Transport", libnvme_ctrl_get_transport(c)); - obj_add_ctrl_address(path_attrs, c); - obj_add_ctrl_address_details(path_attrs, "AddressDetails", c); - obj_add_str(path_attrs, "State", libnvme_ctrl_get_state(c)); - array_add_obj(paths, path_attrs); - } -} - -static void json_print_nvme_subsystem_list(struct libnvme_global_ctx *ctx, - bool show_ana) -{ - struct json_object *host_attrs, *subsystem_attrs; - struct json_object *subsystems, *paths; - struct json_object *a = json_create_array(); - struct libnvme_host *h; - - libnvme_for_each_host(ctx, h) { - struct libnvme_subsystem *s; - const char *hostid; - - host_attrs = json_create_object(); - obj_add_str(host_attrs, "HostNQN", libnvme_host_get_hostnqn(h)); - hostid = libnvme_host_get_hostid(h); - if (hostid) - obj_add_str(host_attrs, "HostID", hostid); - subsystems = json_create_array(); - libnvme_for_each_subsystem(h, s) { - struct libnvme_ctrl *c; - bool no_ctrl = true; - - libnvme_subsystem_for_each_ctrl(s, c) - no_ctrl = false; - if (no_ctrl) - continue; - - subsystem_attrs = json_create_object(); - obj_add_str(subsystem_attrs, "Name", libnvme_subsystem_get_name(s)); - obj_add_str(subsystem_attrs, "NQN", libnvme_subsystem_get_subsysnqn(s)); - - if (verbose_mode()) { - const char *model; - const char *serial; - const char *firmware; - const char *iopolicy; - - libnvme_subsystem_get_model(s, &model, ""); - libnvme_subsystem_get_serial(s, &serial, ""); - libnvme_subsystem_get_firmware(s, &firmware, - ""); - libnvme_subsystem_get_iopolicy(s, &iopolicy, - ""); - - obj_add_str(subsystem_attrs, "Model", model); - obj_add_str(subsystem_attrs, "Serial", serial); - obj_add_str(subsystem_attrs, "Firmware", - firmware); - obj_add_str(subsystem_attrs, "IOPolicy", - iopolicy); - obj_add_str(subsystem_attrs, "Type", - libnvme_subsystem_get_subsystype(s)); - } - - array_add_obj(subsystems, subsystem_attrs); - paths = json_create_array(); - - if (!show_ana || !json_print_nvme_subsystem_multipath(s, paths)) - json_print_nvme_subsystem_ctrls(s, paths); - - obj_add_array(subsystem_attrs, "Paths", paths); - } - obj_add_array(host_attrs, "Subsystems", subsystems); - array_add_obj(a, host_attrs); - } - - json_print(a); -} - -/* Adds the fields @fields of @value to @o, decoded, under their names */ -void json_bitfields(struct json_object *o, const struct bitfield *fields, - unsigned int nr, uint64_t value) -{ - char buf[128]; - unsigned int i; - - for (i = 0; i < nr; i++) { - bitfield_str(&fields[i], value, buf, sizeof(buf)); - obj_add_str(o, fields[i].name, buf); - } -} - -/* - * The same for each style: the value of each register under its symbol, - * with -v an object of the value and its fields. - */ -static void json_ctrl_registers(const struct nvme_reg_val *vals, - unsigned int nr, - enum nvme_regs_style style __shr_unused) -{ - struct json_object *r = json_r; - struct json_object *o; - unsigned int i; - - for (i = 0; i < nr; i++) { - const struct nvme_reg *reg = vals[i].reg; - - if (!verbose_mode()) { - obj_add_uint64(r, reg->sym, vals[i].value); - continue; - } - - o = json_create_object(); - obj_add_uint64(o, "value", vals[i].value); - json_bitfields(o, reg->fields, reg->nr_fields, vals[i].value); - obj_add_obj(r, reg->sym, o); - } -} - -static void json_feature_show_fields_arbitration(struct json_object *r, unsigned int result) -{ - char json_str[STR_LEN]; - - obj_add_uint(r, "High Priority Weight (HPW)", ((result & 0xff000000) >> 24) + 1); - obj_add_uint(r, "Medium Priority Weight (MPW)", ((result & 0xff0000) >> 16) + 1); - obj_add_uint(r, "Low Priority Weight (LPW)", ((result & 0xff00) >> 8) + 1); - - if ((result & 7) == 7) - sprintf(json_str, "No limit"); - else - sprintf(json_str, "%u", 1 << (result & 7)); - - obj_add_str(r, "Arbitration Burst (AB)", json_str); -} - -static void json_feature_show_fields_power_mgmt(struct json_object *r, unsigned int result) -{ - __u8 field = (result & 0xe0) >> 5; - - obj_add_uint(r, "Workload Hint (WH)", field); - obj_add_str(r, "WH description", nvme_feature_wl_hints_to_string(field)); - obj_add_uint(r, "Power State (PS)", result & 0x1f); - obj_add_uint(r, "Idle I/O Exit Latency Limit (IIELL)", - NVME_FEAT_PM_IIELL(result)); -} - -static void json_lba_range_entry(struct nvme_lba_range_type *lbrt, int nr_ranges, - struct json_object *r) -{ - char json_str[STR_LEN]; - struct json_object *lbare; - int i; - struct json_object *lbara = json_create_array(); - - obj_add_array(r, "LBA Ranges", lbara); - - for (i = 0; i <= nr_ranges; i++) { - lbare = json_create_object(); - array_add_obj(lbara, lbare); - - obj_add_int(lbare, "LBA range", i); - - obj_add_uint_nx(lbare, "type", lbrt->entry[i].type); - - obj_add_str(lbare, "type description", - nvme_feature_lba_type_to_string(lbrt->entry[i].type)); - - obj_add_uint_nx(lbare, "attributes", lbrt->entry[i].attributes); - - obj_add_str(lbare, "attribute[0]", lbrt->entry[i].attributes & 1 ? - "LBA range may be overwritten" : "LBA range should not be overwritten"); - - obj_add_str(lbare, "attribute[1]", lbrt->entry[i].attributes & 2 ? - "LBA range should be hidden from the OS/EFI/BIOS" : - "LBA range should be visible from the OS/EFI/BIOS"); - - obj_add_nprix64(lbare, "slba", le64_to_cpu(lbrt->entry[i].slba)); - - obj_add_nprix64(lbare, "nlb", le64_to_cpu(lbrt->entry[i].nlb)); - - shr_bin_to_hex(json_str, sizeof(json_str), lbrt->entry[i].guid, - sizeof(lbrt->entry[i].guid), 0); - - obj_add_str(lbare, "guid", json_str); - } -} - -static void json_feature_show_fields_lba_range(struct json_object *r, __u8 field, - unsigned char *buf) -{ - obj_add_uint(r, "Number of LBA Ranges (NUM)", field + 1); - - if (buf) - json_lba_range_entry((struct nvme_lba_range_type *)buf, field, r); -} - -static void json_feature_show_fields_temp_thresh(struct json_object *r, unsigned int result) -{ - char json_str[STR_LEN]; - __u8 field; - - field = (result & 0x1c00000) >> 22; - sprintf(json_str, "%s", nvme_degrees_string(field)); - obj_add_str(r, "Temperature Threshold Hysteresis (TMPTHH)", json_str); - - sprintf(json_str, "%u K", field); - obj_add_str(r, "TMPTHH kelvin", json_str); - - field = (result & 0x300000) >> 20; - obj_add_uint(r, "Threshold Type Select (THSEL)", field); - obj_add_str(r, "THSEL description", nvme_feature_temp_type_to_string(field)); - - field = (result & 0xf0000) >> 16; - - obj_add_uint(r, "Threshold Temperature Select (TMPSEL)", field); - obj_add_str(r, "TMPSEL description", nvme_feature_temp_sel_to_string(field)); - - sprintf(json_str, "%s", nvme_degrees_string(result & 0xffff)); - obj_add_str(r, "Temperature Threshold (TMPTH)", json_str); - - sprintf(json_str, "%u K", result & 0xffff); - obj_add_str(r, "TMPTH kelvin", json_str); -} - -static void json_feature_show_fields_err_recovery(struct json_object *r, unsigned int result) -{ - char json_str[STR_LEN]; - - obj_add_str(r, "Deallocated or Unwritten Logical Block Error Enable (DULBE)", - (result & 0x10000) >> 16 ? "Enabled" : "Disabled"); - - sprintf(json_str, "%u ms", (result & 0xffff) * 100); - obj_add_str(r, "Time Limited Error Recovery (TLER)", json_str); -} - -static void json_feature_show_fields_volatile_wc(struct json_object *r, unsigned int result) -{ - obj_add_str(r, "Volatile Write Cache Enable (WCE)", result & 1 ? "Enabled" : "Disabled"); -} - -static void json_feature_show_fields_num_queues(struct json_object *r, unsigned int result) -{ - obj_add_uint(r, "Number of IO Completion Queues Allocated (NCQA)", - ((result & 0xffff0000) >> 16) + 1); - obj_add_uint(r, "Number of IO Submission Queues Allocated (NSQA)", (result & 0xffff) + 1); -} - -static void json_feature_show_fields_irq_coalesce(struct json_object *r, unsigned int result) -{ - char json_str[STR_LEN]; - - sprintf(json_str, "%u usec", ((result & 0xff00) >> 8) * 100); - obj_add_str(r, "Aggregation Time (TIME)", json_str); - - obj_add_uint(r, "Aggregation Threshold (THR)", (result & 0xff) + 1); -} - -static void json_feature_show_fields_irq_config(struct json_object *r, unsigned int result) -{ - obj_add_str(r, "Coalescing Disable (CD)", (result & 0x10000) >> 16 ? "True" : "False"); - obj_add_uint(r, "Interrupt Vector (IV)", result & 0xffff); -} - -static void json_feature_show_fields_write_atomic(struct json_object *r, unsigned int result) -{ - obj_add_str(r, "Disable Normal (DN)", result & 1 ? "True" : "False"); -} - -static void json_feature_show_fields_async_event(struct json_object *r, unsigned int result) -{ - const char *async = "Send async event"; - const char *no_async = "Do not send async event"; - - obj_add_str(r, feat_ae_dlpcn, - NVME_FEAT_AE_DLPCN(result) ? async : no_async); - obj_add_str(r, feat_ae_hdlpcn, - NVME_FEAT_AE_HDLPCN(result) ? async : no_async); - obj_add_str(r, feat_ae_adlpcn, - NVME_FEAT_AE_ADLPCN(result) ? async : no_async); - obj_add_str(r, feat_ae_pmdrlpcn, - NVME_FEAT_AE_PMDRLPCN(result) ? async : no_async); - obj_add_str(r, feat_ae_zdcn, - NVME_FEAT_AE_ZDCN(result) ? async : no_async); - obj_add_str(r, feat_ae_tthry, - NVME_FEAT_AE_TTHRY(result) ? async : no_async); - obj_add_str(r, feat_ae_rlccn, - NVME_FEAT_AE_RLCCN(result) ? async : no_async); - obj_add_str(r, feat_ae_lhcn, - NVME_FEAT_AE_LHCN(result) ? async : no_async); - obj_add_str(r, feat_ae_ccrcn, - NVME_FEAT_AE_CCRCN(result) ? async : no_async); - obj_add_str(r, feat_ae_ansan, - NVME_FEAT_AE_ANSAN(result) ? async : no_async); - obj_add_str(r, feat_ae_rgrp0, - NVME_FEAT_AE_RGRP0(result) ? async : no_async); - obj_add_str(r, feat_ae_rassn, - NVME_FEAT_AE_RASSN(result) ? async : no_async); - obj_add_str(r, feat_ae_nnsshdn, - NVME_FEAT_AE_NNSSHDN(result) ? async : no_async); - obj_add_str(r, feat_ae_ega, - NVME_FEAT_AE_EGA(result) ? async : no_async); - obj_add_str(r, feat_ae_lbas, - NVME_FEAT_AE_LBAS(result) ? async : no_async); - obj_add_str(r, feat_ae_pla, - NVME_FEAT_AE_PLA(result) ? async : no_async); - obj_add_str(r, feat_ae_ana, - NVME_FEAT_AE_ANA(result) ? async : no_async); - obj_add_str(r, feat_ae_telem, - NVME_FEAT_AE_TELEM(result) ? async : no_async); - obj_add_str(r, feat_ae_fw, NVME_FEAT_AE_FW(result) ? async : no_async); - obj_add_str(r, feat_ae_nan, - NVME_FEAT_AE_NAN(result) ? async : no_async); - obj_add_str(r, feat_ae_smart, - NVME_FEAT_AE_SMART(result) ? async : no_async); -} - -static void json_auto_pst(struct nvme_feat_auto_pst *apst, struct json_object *r) -{ - int i; - __u64 value; - char json_str[STR_LEN]; - struct json_object *apsta = json_create_array(); - struct json_object *apste; - - obj_add_array(r, "Auto PST Entries", apsta); - - for (i = 0; i < ARRAY_SIZE(apst->apst_entry); i++) { - apste = json_create_object(); - array_add_obj(apsta, apste); - sprintf(json_str, "%2d", i); - obj_add_str(apste, "entry", json_str); - value = le64_to_cpu(apst->apst_entry[i]); - sprintf(json_str, "%u ms", (__u32)NVME_GET(value, APST_ENTRY_ITPT)); - obj_add_str(apste, "Idle Time Prior to Transition (ITPT)", json_str); - obj_add_uint(apste, "Idle Transition Power State (ITPS)", - (__u32)NVME_GET(value, APST_ENTRY_ITPS)); - } -} - -static void json_feature_show_fields_auto_pst(struct json_object *r, unsigned int result, - unsigned char *buf) -{ - obj_add_str(r, "Autonomous Power State Transition Enable (APSTE)", result & 1 ? "Enabled" : - "Disabled"); - - if (buf) - json_auto_pst((struct nvme_feat_auto_pst *)buf, r); -} - -static void json_host_mem_buffer(struct nvme_host_mem_buf_attrs *hmb, struct json_object *r) -{ - char json_str[STR_LEN]; - - obj_add_uint(r, "Host Memory Descriptor List Entry Count (HMDLEC)", le32_to_cpu(hmb->hmdlec)); - - sprintf(json_str, "0x%x", le32_to_cpu(hmb->hmdlau)); - obj_add_str(r, "Host Memory Descriptor List Address (HMDLAU)", json_str); - - sprintf(json_str, "0x%x", le32_to_cpu(hmb->hmdlal)); - obj_add_str(r, "Host Memory Descriptor List Address (HMDLAL)", json_str); - - obj_add_uint(r, "Host Memory Buffer Size (HSIZE)", le32_to_cpu(hmb->hsize)); -} - -static void json_feature_show_fields_host_mem_buf(struct json_object *r, unsigned int result, - unsigned char *buf) -{ - obj_add_str(r, "Enable Host Memory (EHM)", result & 1 ? "Enabled" : "Disabled"); - obj_add_str(r, "Host Memory Non-operational Access Restriction Enable (HMNARE)", - (result & 0x00000004) ? "True" : "False"); - obj_add_str(r, "Host Memory Non-operational Access Restricted (HMNAR)", - (result & 0x00000008) ? "True" : "False"); - - if (buf) - json_host_mem_buffer((struct nvme_host_mem_buf_attrs *)buf, r); -} - -void json_timestamp(struct json_object *r, struct nvme_timestamp *ts) -{ - obj_add_uint64(r, "timestamp", int48_to_long(ts->timestamp)); - obj_add_str(r, "timestamp string", nvme_format_timestamp(ts->timestamp)); - obj_add_str(r, "timestamp origin", nvme_format_timestamp_origin(ts->attr)); - obj_add_str(r, "synch", nvme_format_timestamp_sync(ts->attr)); -} - -static void json_feature_show_fields_timestamp(struct json_object *r, unsigned char *buf) -{ - if (buf) - json_timestamp(r, (struct nvme_timestamp *)buf); -} - -static void json_feature_show_fields_kato(struct json_object *r, unsigned int result) -{ - obj_add_uint(r, "Keep Alive Timeout (KATO) in milliseconds", result); -} - -static void json_feature_show_fields_hctm(struct json_object *r, unsigned int result) -{ - char json_str[STR_LEN]; - - sprintf(json_str, "%u K", result >> 16); - obj_add_str(r, "Thermal Management Temperature 1 (TMT1)", json_str); - - sprintf(json_str, "%s", nvme_degrees_string(result >> 16)); - obj_add_str(r, "TMT1 celsius", json_str); - - sprintf(json_str, "%u K", result & 0xffff); - obj_add_str(r, "Thermal Management Temperature 2", json_str); - - sprintf(json_str, "%s", nvme_degrees_string(result & 0xffff)); - obj_add_str(r, "TMT2 celsius", json_str); -} - -static void json_feature_show_fields_nopsc(struct json_object *r, unsigned int result) -{ - obj_add_str(r, "Non-Operational Power State Permissive Mode Enable (NOPPME)", result & 1 ? - "True" : "False"); -} - -static void json_feature_show_fields_rrl(struct json_object *r, unsigned int result) -{ - obj_add_uint(r, "Read Recovery Level (RRL)", result & 0xf); -} - -static void json_plm_config(struct nvme_plm_config *plmcfg, struct json_object *r) -{ - char json_str[STR_LEN]; - - sprintf(json_str, "%04x", le16_to_cpu(plmcfg->ee)); - obj_add_str(r, "Enable Event", json_str); - - obj_add_uint64(r, "DTWIN Reads Threshold", le64_to_cpu(plmcfg->dtwinrt)); - obj_add_uint64(r, "DTWIN Writes Threshold", le64_to_cpu(plmcfg->dtwinwt)); - obj_add_uint64(r, "DTWIN Time Threshold", le64_to_cpu(plmcfg->dtwintt)); -} - -static void json_feature_show_fields_plm_config(struct json_object *r, unsigned int result, - unsigned char *buf) -{ - obj_add_str(r, "Predictable Latency Window Enabled", result & 1 ? "True" : "False"); - - if (buf) - json_plm_config((struct nvme_plm_config *)buf, r); -} - -static void json_feature_show_fields_plm_window(struct json_object *r, unsigned int result) -{ - obj_add_str(r, "Window Select", nvme_plm_window_to_string(result)); -} - -static void json_feature_show_fields_lba_sts_interval(struct json_object *r, unsigned int result) -{ - obj_add_uint(r, "LBA Status Information Poll Interval (LSIPI)", result >> 16); - obj_add_uint(r, "LBA Status Information Report Interval (LSIRI)", result & 0xffff); -} - -static void json_feature_show_fields_host_behavior(struct json_object *r, unsigned char *buf) -{ - if (buf) { - struct nvme_feat_host_behavior *host = (struct nvme_feat_host_behavior *)buf; - - obj_add_str(r, "Host Behavior Support", buf[0] & 0x1 ? "True" : "False"); - obj_add_str(r, "Advanced Command Retry Enable (ACRE)", host->acre ? - "True" : "False"); - obj_add_str(r, "Extended Telemetry Data Area 4 Supported (ETDAS)", host->etdas ? - "True" : "False"); - obj_add_str(r, "LBA Format Extension Enable (LBAFEE)", host->lbafee ? - "True" : "False"); - obj_add_str(r, "Host Dispersed Namespace Support (HDISNS)", host->hdisns ? - "Enabled" : "Disabled"); - obj_add_str(r, "Copy Descriptor Format 2h Enable (CDF2E)", host->cdfe & (1 << 2) ? - "True" : "False"); - obj_add_str(r, "Copy Descriptor Format 3h Enable (CDF3E)", host->cdfe & (1 << 3) ? - "True" : "False"); - obj_add_str(r, "Copy Descriptor Format 4h Enable (CDF4E)", host->cdfe & (1 << 4) ? - "True" : "False"); - } -} - -static void json_feature_show_fields_sanitize(struct json_object *r, unsigned int result) -{ - obj_add_uint(r, "No-Deallocate Response Mode (NODRM)", result & 1); -} - -static void json_feature_show_fields_endurance_evt_cfg(struct json_object *r, unsigned int result) -{ - obj_add_uint(r, "Endurance Group Identifier (ENDGID)", result & 0xffff); - obj_add_uint(r, "Endurance Group Critical Warnings", result >> 16 & 0xff); -} - -static void json_feature_show_fields_iocs_profile(struct json_object *r, unsigned int result) -{ - obj_add_str(r, "I/O Command Set Profile", result & 0x1 ? "True" : "False"); -} - -static void json_feature_show_fields_spinup_control(struct json_object *r, unsigned int result) -{ - obj_add_str(r, "Spinup control feature Enabled", result & 1 ? "True" : "False"); -} - -static void json_feature_show_fields_power_loss_signal(struct json_object *r, unsigned int result) -{ - obj_add_str(r, "Power Loss Signaling Mode (PLSM)", - nvme_pls_mode_to_string(NVME_GET(result, FEAT_PLS_MODE))); -} - -static void json_feat_perfc_std(struct json_object *r, struct nvme_std_perf_attr *data) -{ - obj_add_str(r, "random 4 kib average read latency", - nvme_feature_perfc_r4karl_to_string(data->r4karl)); - obj_add_uint_02x(r, "R4KARL", data->r4karl); -} - -static void json_feat_perfc_id_list(struct json_object *r, struct nvme_perf_attr_id_list *data) -{ - int i; - int attri_vs; - char json_str[STR_LEN]; - struct json_object *paida = json_create_array(); - struct json_object *paide; - - obj_add_str(r, "attribute type", nvme_feature_perfc_attrtyp_to_string(data->attrtyp)); - obj_add_uint_02x(r, "ATTRTYP", data->attrtyp); - obj_add_int(r, "maximum saveable vendor specific performance attributes (MSVSPA)", - data->msvspa); - obj_add_int(r, "unused saveable vendor specific performance attributes (USVSPA)", - data->usvspa); - - obj_add_array(r, "performance attribute identifier list", paida); - for (i = 0; i < ARRAY_SIZE(data->id_list); i++) { - paide = json_create_object(); - array_add_obj(paida, paide); - attri_vs = i + NVME_FEAT_PERFC_ATTRI_VS_MIN; - sprintf(json_str, "performance attribute %02xh identifier (PA%02XHI)", attri_vs, - attri_vs); - obj_add_str(paide, json_str, shr_uuid_to_string(data->id_list[i].id)); - } -} - -static void json_feat_perfc_vs(struct json_object *r, struct nvme_vs_perf_attr *data) -{ - __u16 attrl = le16_to_cpu(data->attrl); - - obj_add_str(r, "performance attribute identifier (PAID)", shr_uuid_to_string(data->paid)); - obj_add_uint(r, "attribute length (ATTRL)", attrl); - obj_d(r, "vendor specific (VS)", (unsigned char *)data->vs, - min_t(size_t, attrl, sizeof(data->vs)), 16, 1); -} - -static void json_feat_perfc(struct json_object *r, enum nvme_features_id fid, unsigned int result, - struct nvme_perf_characteristics *data) -{ - __u8 attri; - bool rvspa; - - nvme_feature_decode_perf_characteristics(result, &attri, &rvspa); - - obj_add_str(r, "attribute index", nvme_feature_perfc_attri_to_string(attri)); - obj_add_uint_02x(r, "ATTRI", attri); - - switch (attri) { - case NVME_FEAT_PERFC_ATTRI_STD: - json_feat_perfc_std(r, data->std_perf); - break; - case NVME_FEAT_PERFC_ATTRI_ID_LIST: - json_feat_perfc_id_list(r, data->id_list); - break; - case NVME_FEAT_PERFC_ATTRI_VS_MIN ... NVME_FEAT_PERFC_ATTRI_VS_MAX: - json_feat_perfc_vs(r, data->vs_perf); - break; - default: - break; - } -} - -static void json_host_metadata(struct json_object *r, enum nvme_features_id fid, - struct nvme_host_metadata *data) -{ - struct nvme_metadata_element_desc desc; - const __u8 *v; - size_t off = 0; - int i; - char val[VAL_LEN]; - __u16 len; - char json_str[STR_LEN]; - struct json_object *desca = json_create_array(); - struct json_object *desce; - - obj_add_int(r, "Num Metadata Element Descriptors", data->ndesc); - - obj_add_array(r, "Metadata Element Descriptors", desca); - - for (i = 0; i < data->ndesc; i++) { - v = nvme_host_metadata_element(data, &off, &desc, &len); - if (!v) - break; - - desce = json_create_object(); - array_add_obj(desca, desce); - - obj_add_int(desce, "Element", i); - - snprintf(json_str, sizeof(json_str), "0x%02x", desc.type); - obj_add_str(desce, "Type", json_str); - - obj_add_str(desce, "Type definition", - nvme_host_metadata_type_to_string(fid, desc.type)); - - obj_add_int(desce, "Revision", desc.rev); - - obj_add_int(desce, "Length", le16_to_cpu(desc.len)); - - snprintf(val, sizeof(val), "%.*s", len, (const char *)v); - obj_add_str(desce, "Value", val); - } -} - -static void json_feature_show_fields_ns_metadata(struct json_object *r, enum nvme_features_id fid, - unsigned char *buf) -{ - if (buf) - json_host_metadata(r, fid, (struct nvme_host_metadata *)buf); -} - -static void json_feature_show_fields_sw_progress(struct json_object *r, unsigned int result) -{ - obj_add_uint(r, "Pre-boot Software Load Count (PBSLC)", result & 0xff); -} - -static void json_feature_show_fields_host_id(struct json_object *r, - unsigned int result, unsigned char *hostid) -{ - bool exhid; - - if (!hostid) - return; - - nvme_feature_decode_host_id(result, &exhid); - - if (exhid) - obj_add_str(r, "Host Identifier (HOSTID)", - uint128_t_to_l10n_string(le128_to_cpu(hostid))); - else - obj_add_uint64(r, "Host Identifier (HOSTID)", - le64_to_cpu(*(__le64 *)hostid)); -} - -static void json_feature_show_fields_resv_nf_mask(struct json_object *r, unsigned int result) -{ - obj_add_str(r, "Mask Reservation Preempted Notification (RESPRE)", (result & 8) >> 3 ? - "True" : "False"); - obj_add_str(r, "Mask Reservation Released Notification (RESREL)", (result & 4) >> 2 ? - "True" : "False"); - obj_add_str(r, "Mask Registration Preempted Notification (REGPRE)", (result & 2) >> 1 ? - "True" : "False"); -} - -static void json_feature_show_fields_resv_persist(struct json_object *r, unsigned int result) -{ - obj_add_str(r, "Persist Through Power Loss (PTPL)", result & 1 ? "True" : "False"); -} - -static void json_feature_show_fields_write_protect(struct json_object *r, unsigned int result) -{ - obj_add_str(r, "Namespace Write Protect", nvme_ns_wp_cfg_to_string(result)); -} - -static void json_feature_show_fields_fdp(struct json_object *r, unsigned int result) -{ - obj_add_str(r, "Flexible Direct Placement Enable (FDPE)", result & 1 ? "Yes" : "No"); - obj_add_uint(r, "Flexible Direct Placement Configuration Index", result >> 8 & 0xf); -} - -static void json_feature_show_fields_fdp_events(struct json_object *r, unsigned int result, - unsigned char *buf) -{ - unsigned int i; - struct nvme_fdp_supported_event_desc *d; - char json_str[STR_LEN]; - - // NOET is in bits 7:0; bits 31:8 are reserved. - for (i = 0; i < (result & 0xff); i++) { - d = &((struct nvme_fdp_supported_event_desc *)buf)[i]; - sprintf(json_str, "%s", d->evta & 0x1 ? "Enabled" : "Not enabled"); - obj_add_str(r, nvme_fdp_event_to_string(d->evt), json_str); - } -} - -static void json_feature_show_fields_bpwp(struct json_object *r, unsigned int result) -{ - __u8 field; - - field = NVME_FEAT_BPWPC_BP0WPS(result); - obj_add_str(r, "Boot Partition 0 Write Protection State", nvme_bpwps_to_string(field)); - field = NVME_FEAT_BPWPC_BP1WPS(result); - obj_add_str(r, "Boot Partition 1 Write Protection State", nvme_bpwps_to_string(field)); -} - -static char *get_power_and_scale(__u16 power, __u8 scale) -{ - char *str; - int ret; - - switch (scale) { - case NVME_PSD_PS_NOT_REPORTED: - /* Not reported for this power state */ - ret = asprintf(&str, "-"); - break; - case NVME_PSD_PS_100_MICRO_WATT: - /* Units of 0.0001W */ - ret = asprintf(&str, "%01u.%04uW", power / 10000, - power % 10000); - break; - case NVME_PSD_PS_10_MILLI_WATT: - /* Units of 0.01W */ - ret = asprintf(&str, "%01u.%02uW", power / 100, power % 100); - break; - default: - ret = asprintf(&str, "reserved"); - break; - } - - if (ret > 0) - return str; - - return NULL; -} - -static void json_feature_show_fields_power_limit(struct json_object *r, - unsigned int result) -{ - __u8 field = NVME_FEAT_POWER_LIMIT_PLS(result); - - __cleanup_free char *k = - get_power_and_scale(NVME_FEAT_POWER_LIMIT_PLV(result), field); - - obj_add_str(r, "Power Limit Scale (PLS)", - nvme_feature_power_limit_scale_to_string(field)); - obj_add_uint(r, "Power Limit Value (PLV)", - NVME_FEAT_POWER_LIMIT_PLV(result)); - obj_add_str(r, "Power Limit", k); -} - -static void json_feature_show_fields_power_thresh(struct json_object *r, - unsigned int result) -{ - __u8 field; - __u16 ptv; - __cleanup_free char *k = NULL; - - field = NVME_FEAT_POWER_THRESH_EPT(result); - - obj_add_str(r, "Enable Power Threshold (EPT)", - field ? "Enabled" : "Disabled"); - - field = NVME_FEAT_POWER_THRESH_PMTS(result); - obj_add_str(r, "Power Measurement Type Select (PMTS)", - nvme_power_measurement_type_to_string(field)); - - field = NVME_FEAT_POWER_THRESH_PTS(result); - obj_add_str(r, "Power Threshold Scale (PTS)", - nvme_feature_power_limit_scale_to_string(field)); - - ptv = NVME_FEAT_POWER_THRESH_PTV(result); - - obj_add_uint(r, "Power Threshold Value (PTV)", ptv); - - k = get_power_and_scale(ptv, NVME_FEAT_POWER_THRESH_PTS(result)); - obj_add_str(r, "Power Threshold", k); -} - -static void json_feature_show_fields_power_meas(struct json_object *r, - unsigned int result) -{ - __u8 field; - __u16 smt; - - field = NVME_FEAT_POWER_MEAS_ACT(result); - obj_add_str(r, "Action (ACT)", - nvme_power_measurement_action_to_string(field)); - - field = NVME_FEAT_POWER_MEAS_PMTS(result); - obj_add_str(r, "Power Measurement Type Select (PMTS)", - nvme_power_measurement_type_to_string(field)); - - smt = NVME_FEAT_POWER_MEAS_SMT(result); - - obj_add_uint(r, "Stop Measurement Time (SMT)", smt); -} - -static void json_feature_show_fields_voltage_threshold(struct json_object *r, - unsigned int result) -{ - obj_add_uint(r, "Voltage Sensor Select (VSENS)", - NVME_FEAT_VOLTAGE_THRESHOLD_VSENS(result)); - obj_add_str(r, "Enable Voltage Threshold (EVT)", - result & NVME_FEAT_VOLTAGE_THRESHOLD_EVT ? "Enabled" : "Disabled"); - obj_add_uint(r, "Overvoltage Threshold (OVT)", - NVME_FEAT_VOLTAGE_THRESHOLD_OVT(result)); - obj_add_uint(r, "Undervoltage Threshold (UVT)", - NVME_FEAT_VOLTAGE_THRESHOLD_UVT(result)); -} - -static void json_feature_show_fields_voltage_measurement(struct json_object *r, - unsigned int result) -{ - obj_add_uint(r, "Action (ACT)", NVME_FEAT_VOLTAGE_MEASUREMENT_ACT(result)); -} - -static void json_rate_limiting_data(struct json_object *r, struct nvme_rate_limiting_data *rld) -{ - __u16 rlc = le16_to_cpu(rld->rlc); - __u16 rlm = NVME_RATE_LIMITING_RLC_RLM(rlc); - - obj_add_str(r, "Rate Limiting Enable (RLE)", - NVME_RATE_LIMITING_RLC_RLE(rlc) ? "Enabled" : "Disabled"); - obj_add_uint(r, "Rate Limiting Mode (RLM)", rlm); - obj_add_str(r, "RLM description", - rlm == NVME_RATE_LIMITING_MODE_SOFT_LIMIT ? "Soft Limit" : - rlm == NVME_RATE_LIMITING_MODE_HARD_LIMIT ? "Hard Limit" : "Reserved"); - obj_add_uint(r, "Bandwidth Scale Factor (BWSF)", rld->bwsf); - obj_add_uint64(r, "Total Bandwidth Value (TBWV)", le64_to_cpu(rld->tbwv)); - obj_add_uint64(r, "Write Bandwidth Value (WBWV)", le64_to_cpu(rld->wbwv)); - obj_add_uint(r, "Total IOPS (TIOPS)", le32_to_cpu(rld->tiops)); - obj_add_uint(r, "Write IOPS (WIOPS)", le32_to_cpu(rld->wiops)); - obj_add_uint(r, "Read IOPS Ratio (RIOPSR)", rld->riopsr); - obj_add_uint(r, "Write IOPS Ratio (WIOPSR)", rld->wiopsr); - obj_add_uint(r, "Read Bandwidth Ratio (RBWR)", rld->rbwr); - obj_add_uint(r, "Write Bandwidth Ratio (WBWR)", rld->wbwr); -} - -static void json_feature_show_fields_rate_limiting(struct json_object *r, unsigned char *buf) -{ - if (buf) - json_rate_limiting_data(r, (struct nvme_rate_limiting_data *)buf); -} - -static void json_feature_show(enum nvme_features_id fid, int sel, - unsigned int result, void *buf, __u32 data_len) -{ - struct json_object *r; - char json_str[STR_LEN]; - - sprintf(json_str, "feature: %#0*x", fid ? 4 : 2, fid); - r = obj_create(json_str); - - obj_add_str(r, "name", nvme_feature_to_string(fid)); - - sprintf(json_str, "%#0*x", result ? 10 : 8, result); - obj_add_str(r, nvme_select_to_string(sel), json_str); - - obj_print(r); - - if (NVME_CHECK(sel, GET_FEATURES_SEL, SUPPORTED)) - json_select_result(fid, result); - else - json_feature_show_fields(fid, result, buf); -} - -void json_feature_show_fields(enum nvme_features_id fid, unsigned int result, - unsigned char *buf) -{ - struct json_object *r; - char json_str[STR_LEN]; - - sprintf(json_str, "Feature: %#0*x", fid ? 4 : 2, fid); - r = obj_create(json_str); - - switch (fid) { - case NVME_FEAT_FID_ARBITRATION: - json_feature_show_fields_arbitration(r, result); - break; - case NVME_FEAT_FID_POWER_MGMT: - json_feature_show_fields_power_mgmt(r, result); - break; - case NVME_FEAT_FID_LBA_RANGE: - json_feature_show_fields_lba_range(r, result & 0x3f, buf); - break; - case NVME_FEAT_FID_TEMP_THRESH: - json_feature_show_fields_temp_thresh(r, result); - break; - case NVME_FEAT_FID_ERR_RECOVERY: - json_feature_show_fields_err_recovery(r, result); - break; - case NVME_FEAT_FID_VOLATILE_WC: - json_feature_show_fields_volatile_wc(r, result); - break; - case NVME_FEAT_FID_NUM_QUEUES: - json_feature_show_fields_num_queues(r, result); - break; - case NVME_FEAT_FID_IRQ_COALESCE: - json_feature_show_fields_irq_coalesce(r, result); - break; - case NVME_FEAT_FID_IRQ_CONFIG: - json_feature_show_fields_irq_config(r, result); - break; - case NVME_FEAT_FID_WRITE_ATOMIC: - json_feature_show_fields_write_atomic(r, result); - break; - case NVME_FEAT_FID_ASYNC_EVENT: - json_feature_show_fields_async_event(r, result); - break; - case NVME_FEAT_FID_AUTO_PST: - json_feature_show_fields_auto_pst(r, result, buf); - break; - case NVME_FEAT_FID_HOST_MEM_BUF: - json_feature_show_fields_host_mem_buf(r, result, buf); - break; - case NVME_FEAT_FID_TIMESTAMP: - json_feature_show_fields_timestamp(r, buf); - break; - case NVME_FEAT_FID_KATO: - json_feature_show_fields_kato(r, result); - break; - case NVME_FEAT_FID_HCTM: - json_feature_show_fields_hctm(r, result); - break; - case NVME_FEAT_FID_NOPSC: - json_feature_show_fields_nopsc(r, result); - break; - case NVME_FEAT_FID_RRL: - json_feature_show_fields_rrl(r, result); - break; - case NVME_FEAT_FID_PLM_CONFIG: - json_feature_show_fields_plm_config(r, result, buf); - break; - case NVME_FEAT_FID_PLM_WINDOW: - json_feature_show_fields_plm_window(r, result); - break; - case NVME_FEAT_FID_LBA_STS_INTERVAL: - json_feature_show_fields_lba_sts_interval(r, result); - break; - case NVME_FEAT_FID_HOST_BEHAVIOR: - json_feature_show_fields_host_behavior(r, buf); - break; - case NVME_FEAT_FID_SANITIZE: - json_feature_show_fields_sanitize(r, result); - break; - case NVME_FEAT_FID_ENDURANCE_EVT_CFG: - json_feature_show_fields_endurance_evt_cfg(r, result); - break; - case NVME_FEAT_FID_IOCS_PROFILE: - json_feature_show_fields_iocs_profile(r, result); - break; - case NVME_FEAT_FID_SPINUP_CONTROL: - json_feature_show_fields_spinup_control(r, result); - break; - case NVME_FEAT_FID_POWER_LOSS_SIGNAL: - json_feature_show_fields_power_loss_signal(r, result); - break; - case NVME_FEAT_FID_PERF_CHARACTERISTICS: - json_feat_perfc(r, fid, result, (struct nvme_perf_characteristics *)buf); - break; - case NVME_FEAT_FID_ENH_CTRL_METADATA: - case NVME_FEAT_FID_CTRL_METADATA: - case NVME_FEAT_FID_NS_METADATA: - json_feature_show_fields_ns_metadata(r, fid, buf); - break; - case NVME_FEAT_FID_SW_PROGRESS: - json_feature_show_fields_sw_progress(r, result); - break; - case NVME_FEAT_FID_HOST_ID: - json_feature_show_fields_host_id(r, result, buf); - break; - case NVME_FEAT_FID_RESV_NF_MASK: - json_feature_show_fields_resv_nf_mask(r, result); - break; - case NVME_FEAT_FID_RESV_PERSIST: - json_feature_show_fields_resv_persist(r, result); - break; - case NVME_FEAT_FID_WRITE_PROTECT: - json_feature_show_fields_write_protect(r, result); - break; - case NVME_FEAT_FID_FDP: - json_feature_show_fields_fdp(r, result); - break; - case NVME_FEAT_FID_FDP_EVENTS: - json_feature_show_fields_fdp_events(r, result, buf); - break; - case NVME_FEAT_FID_BP_WRITE_PROTECT: - json_feature_show_fields_bpwp(r, result); - break; - case NVME_FEAT_FID_POWER_LIMIT: - json_feature_show_fields_power_limit(r, result); - break; - case NVME_FEAT_FID_POWER_THRESH: - json_feature_show_fields_power_thresh(r, result); - break; - case NVME_FEAT_FID_POWER_MEASUREMENT: - json_feature_show_fields_power_meas(r, result); - break; - case NVME_FEAT_FID_VOLTAGE_THRESHOLD: - json_feature_show_fields_voltage_threshold(r, result); - break; - case NVME_FEAT_FID_VOLTAGE_MEASUREMENT: - json_feature_show_fields_voltage_measurement(r, result); - break; - case NVME_FEAT_FID_RATE_LIMITING: - json_feature_show_fields_rate_limiting(r, buf); - break; - default: - break; - } - - obj_print(r); -} - -void json_id_ctrl_rpmbs(__le32 ctrl_rpmbs) -{ - struct json_object *r = json_r; - __u32 rpmbs = le32_to_cpu(ctrl_rpmbs); - __u32 asz = (rpmbs & 0xFF000000) >> 24; - __u32 tsz = (rpmbs & 0xFF0000) >> 16; - __u32 rsvd = (rpmbs & 0xFFC0) >> 6; - __u32 auth = (rpmbs & 0x38) >> 3; - __u32 rpmb = rpmbs & 7; - - obj_add_uint_nx(r, "[31:24]: Access Size", asz); - obj_add_uint_nx(r, "[23:16]: Total Size", tsz); - - if (rsvd) - obj_add_uint_nx(r, "[15:6]: Reserved", rsvd); - - obj_add_uint_nx(r, "[5:3]: Authentication Method", auth); - obj_add_uint_nx(r, "[2:0]: Number of RPMB Units", rpmb); -} - -static void json_lba_range(struct nvme_lba_range_type *lbrt, int nr_ranges) -{ - struct json_object *r = json_r; - - json_lba_range_entry(lbrt, nr_ranges, r); -} - -static void json_lba_status_info(__u64 result) -{ - struct json_object *r = json_r; - - obj_add_uint(r, "LBA Status Information Poll Interval (LSIPI)", (result >> 16) & 0xffff); - obj_add_uint(r, "LBA Status Information Report Interval (LSIRI)", result & 0xffff); -} - -void json_d(unsigned char *buf, int len, int width, int group) -{ - struct json_object *r = json_r; - char json_str[STR_LEN]; - - sprintf(json_str, "data: buf=%p len=%d width=%d group=%d", buf, len, width, group); - obj_d(r, json_str, buf, len, width, group); -} - -static void json_print_detail_list_multipath(struct libnvme_subsystem *s, - struct json_object *jss) -{ - struct libnvme_ns *n; - struct libnvme_path *p; - struct json_object *jnss = json_create_array(); - - libnvme_subsystem_for_each_ns(s, n) { - struct json_object *jns = json_create_object(); - struct json_object *jpaths = json_create_array(); - int lba; - uint64_t lba_count, nsze, nuse; - - libnvme_ns_get_lba_size(n, &lba, 0); - libnvme_ns_get_lba_count(n, &lba_count, 0); - nsze = lba_count * lba; - libnvme_ns_get_lba_util(n, &nuse, 0); - nuse *= lba; - - obj_add_str(jns, "NameSpace", libnvme_ns_get_name(n)); - obj_add_str(jns, "Generic", libnvme_ns_get_generic_name(n)); - obj_add_int(jns, "NSID", libnvme_ns_get_nsid(n)); - obj_add_uint64(jns, "UsedBytes", nuse); - obj_add_uint64(jns, "MaximumLBA", lba_count); - obj_add_uint64(jns, "PhysicalSize", nsze); - obj_add_int(jns, "SectorSize", lba); - - libnvme_namespace_for_each_path(n, p) { - struct libnvme_ctrl *c; - struct json_object *jpath = json_create_object(); - const char *slot; - const char *cntlid; - const char *serial; - const char *model; - const char *firmware; - const char *ana_state; - - libnvme_path_get_ana_state(p, &ana_state, ""); - obj_add_str(jpath, "Path", libnvme_path_get_name(p)); - obj_add_str(jpath, "ANAState", ana_state); - - /* - * For multipath, each path maps to one controller. - * So get the controller from the path and then add - * controller attributes. - */ - c = libnvme_path_get_ctrl(p); - libnvme_ctrl_get_phy_slot(c, &slot, ""); - libnvme_ctrl_get_cntlid(c, &cntlid, ""); - libnvme_ctrl_get_serial(c, &serial, ""); - libnvme_ctrl_get_model(c, &model, ""); - libnvme_ctrl_get_firmware(c, &firmware, ""); - obj_add_str(jpath, "Controller", libnvme_ctrl_get_name(c)); - obj_add_str(jpath, "Cntlid", cntlid); - obj_add_str(jpath, "SerialNumber", serial); - obj_add_str(jpath, "ModelNumber", model); - obj_add_str(jpath, "Firmware", firmware); - obj_add_str(jpath, "Transport", libnvme_ctrl_get_transport(c)); - obj_add_ctrl_address(jpath, c); - obj_add_ctrl_address_details(jpath, "AddressDetails", c); - obj_add_str(jpath, "Slot", slot ? slot : ""); - - array_add_obj(jpaths, jpath); - } +#include +#include - obj_add_obj(jns, "Paths", jpaths); - array_add_obj(jnss, jns); - } - obj_add_obj(jss, "Namespaces", jnss); -} +#include +#include +#include +#include +#include +#include +#include +#include +#include -static void json_print_detail_list(struct libnvme_subsystem *s, struct json_object *jss) -{ - struct libnvme_ctrl *c; - struct libnvme_ns *n; - struct json_object *jctrls = json_create_array(); - - libnvme_subsystem_for_each_ctrl(s, c) { - struct json_object *jctrl = json_create_object(); - struct json_object *jnss = json_create_array(); - const char *slot; - const char *cntlid; - const char *serial; - const char *model; - const char *firmware; - - libnvme_ctrl_get_phy_slot(c, &slot, ""); - libnvme_ctrl_get_cntlid(c, &cntlid, ""); - libnvme_ctrl_get_serial(c, &serial, ""); - libnvme_ctrl_get_model(c, &model, ""); - libnvme_ctrl_get_firmware(c, &firmware, ""); - - obj_add_str(jctrl, "Controller", libnvme_ctrl_get_name(c)); - obj_add_str(jctrl, "Cntlid", cntlid); - obj_add_str(jctrl, "SerialNumber", serial); - obj_add_str(jctrl, "ModelNumber", model); - obj_add_str(jctrl, "Firmware", firmware); - obj_add_str(jctrl, "Transport", libnvme_ctrl_get_transport(c)); - obj_add_ctrl_address(jctrl, c); - obj_add_ctrl_address_details(jctrl, "AddressDetails", c); - obj_add_str(jctrl, "Slot", slot ? slot : ""); - - libnvme_ctrl_for_each_ns(c, n) { - struct json_object *jns = json_create_object(); - int lba; - uint64_t lba_count, nsze, nuse; - - libnvme_ns_get_lba_size(n, &lba, 0); - libnvme_ns_get_lba_count(n, &lba_count, 0); - nsze = lba_count * lba; - libnvme_ns_get_lba_util(n, &nuse, 0); - nuse *= lba; - - obj_add_str(jns, "NameSpace", libnvme_ns_get_name(n)); - obj_add_str(jns, "Generic", libnvme_ns_get_generic_name(n)); - obj_add_int(jns, "NSID", libnvme_ns_get_nsid(n)); - obj_add_uint64(jns, "UsedBytes", nuse); - obj_add_uint64(jns, "MaximumLBA", lba_count); - obj_add_uint64(jns, "PhysicalSize", nsze); - obj_add_int(jns, "SectorSize", lba); - - array_add_obj(jnss, jns); - } +#include "cleanup.h" +#include "nvme-json.h" +#include "nvme-print.h" +#include "nvme-print-json.h" - obj_add_obj(jctrl, "Namespaces", jnss); - array_add_obj(jctrls, jctrl); - } +#define ERROR_MSG_LEN 100 +#define BUF_LEN 320 - obj_add_obj(jss, "Controllers", jctrls); -} +static struct print_ops json_print_ops; +static struct json_object *json_r; +static bool json_init; -static void json_detail_list_v2(struct libnvme_global_ctx *ctx) +static void d_json(unsigned char *buf, int len, int width, int group, struct json_object *array) { - struct json_object *r = json_r; - struct json_object *jdev = json_create_array(); - - struct libnvme_host *h; - struct libnvme_subsystem *s; - - libnvme_for_each_host(ctx, h) { - struct json_object *hss = json_create_object(); - struct json_object *jsslist = json_create_array(); - const char *hostid; - - obj_add_str(hss, "HostNQN", libnvme_host_get_hostnqn(h)); - hostid = libnvme_host_get_hostid(h); - if (hostid) - obj_add_str(hss, "HostID", hostid); - - libnvme_for_each_subsystem(h, s) { - struct json_object *jss = json_create_object(); - - obj_add_str(jss, "Subsystem", libnvme_subsystem_get_name(s)); - obj_add_str(jss, "SubsystemNQN", libnvme_subsystem_get_subsysnqn(s)); - - if (nvme_is_multipath(s)) - json_print_detail_list_multipath(s, jss); - else - json_print_detail_list(s, jss); - - array_add_obj(jsslist, jss); - } - - obj_add_obj(hss, "Subsystems", jsslist); - array_add_obj(jdev, hss); - } + int i; + char ascii[32 + 1] = { 0 }; - obj_add_array(r, "Devices", jdev); -} + assert(width < sizeof(ascii)); -static void json_detail_list(struct libnvme_global_ctx *ctx) -{ - struct json_object *r = json_r; - struct json_object *jdev = json_create_array(); - - struct libnvme_host *h; - struct libnvme_subsystem *s; - struct libnvme_ctrl *c; - struct libnvme_path *p; - struct libnvme_ns *n; - - libnvme_for_each_host(ctx, h) { - struct json_object *hss = json_create_object(); - struct json_object *jsslist = json_create_array(); - const char *hostid; - - obj_add_str(hss, "HostNQN", libnvme_host_get_hostnqn(h)); - hostid = libnvme_host_get_hostid(h); - if (hostid) - obj_add_str(hss, "HostID", hostid); - - libnvme_for_each_subsystem(h, s) { - struct json_object *jss = json_create_object(); - struct json_object *jctrls = json_create_array(); - struct json_object *jnss = json_create_array(); - - obj_add_str(jss, "Subsystem", libnvme_subsystem_get_name(s)); - obj_add_str(jss, "SubsystemNQN", libnvme_subsystem_get_subsysnqn(s)); - - libnvme_subsystem_for_each_ctrl(s, c) { - struct json_object *jctrl = json_create_object(); - struct json_object *jnss = json_create_array(); - struct json_object *jpaths = json_create_array(); - const char *cntlid; - const char *serial; - const char *model; - const char *firmware; - const char *slot; - - libnvme_ctrl_get_cntlid(c, &cntlid, ""); - libnvme_ctrl_get_serial(c, &serial, ""); - libnvme_ctrl_get_model(c, &model, ""); - libnvme_ctrl_get_firmware(c, &firmware, ""); - libnvme_ctrl_get_phy_slot(c, &slot, ""); - - obj_add_str(jctrl, "Controller", libnvme_ctrl_get_name(c)); - obj_add_str(jctrl, "Cntlid", cntlid); - obj_add_str(jctrl, "SerialNumber", serial); - obj_add_str(jctrl, "ModelNumber", model); - obj_add_str(jctrl, "Firmware", firmware); - obj_add_str(jctrl, "Transport", libnvme_ctrl_get_transport(c)); - obj_add_ctrl_address(jctrl, c); - obj_add_ctrl_address_details(jctrl, "AddressDetails", c); - obj_add_str(jctrl, "Slot", slot); - - libnvme_ctrl_for_each_ns(c, n) { - struct json_object *jns = json_create_object(); - int lba; - uint64_t lba_count, nsze, nuse; - - libnvme_ns_get_lba_size(n, &lba, 0); - libnvme_ns_get_lba_count(n, - &lba_count, 0); - nsze = lba_count * lba; - libnvme_ns_get_lba_util(n, &nuse, 0); - nuse *= lba; - - obj_add_str(jns, "NameSpace", libnvme_ns_get_name(n)); - obj_add_str(jns, "Generic", libnvme_ns_get_generic_name(n)); - obj_add_int(jns, "NSID", libnvme_ns_get_nsid(n)); - obj_add_uint64(jns, "UsedBytes", nuse); - obj_add_uint64(jns, "MaximumLBA", - lba_count); - obj_add_uint64(jns, "PhysicalSize", nsze); - obj_add_int(jns, "SectorSize", lba); - - array_add_obj(jnss, jns); - } - obj_add_obj(jctrl, "Namespaces", jnss); - - libnvme_ctrl_for_each_path(c, p) { - struct json_object *jpath = json_create_object(); - const char *ana_state; - - libnvme_path_get_ana_state(p, - &ana_state, ""); - obj_add_str(jpath, "Path", libnvme_path_get_name(p)); - obj_add_str(jpath, "ANAState", - ana_state); - - array_add_obj(jpaths, jpath); - } - obj_add_obj(jctrl, "Paths", jpaths); - - array_add_obj(jctrls, jctrl); - } - obj_add_obj(jss, "Controllers", jctrls); - - libnvme_subsystem_for_each_ns(s, n) { - struct json_object *jns = json_create_object(); - int lba; - uint64_t lba_count, nsze, nuse; - - libnvme_ns_get_lba_size(n, &lba, 0); - libnvme_ns_get_lba_count(n, &lba_count, 0); - nsze = lba_count * lba; - libnvme_ns_get_lba_util(n, &nuse, 0); - nuse *= lba; - - obj_add_str(jns, "NameSpace", libnvme_ns_get_name(n)); - obj_add_str(jns, "Generic", libnvme_ns_get_generic_name(n)); - obj_add_int(jns, "NSID", libnvme_ns_get_nsid(n)); - obj_add_uint64(jns, "UsedBytes", nuse); - obj_add_uint64(jns, "MaximumLBA", lba_count); - obj_add_uint64(jns, "PhysicalSize", nsze); - obj_add_int(jns, "SectorSize", lba); - - array_add_obj(jnss, jns); - } - obj_add_obj(jss, "Namespaces", jnss); - - array_add_obj(jsslist, jss); + for (i = 0; i < len; i++) { + ascii[i % width] = (buf[i] >= '!' && buf[i] <= '~') ? buf[i] : '.'; + if (!((i + 1) % width)) { + array_add_str(array, ascii); + memset(ascii, 0, sizeof(ascii)); } - - obj_add_obj(hss, "Subsystems", jsslist); - array_add_obj(jdev, hss); } - obj_add_array(r, "Devices", jdev); -} - -static struct json_object *json_list_item_obj(struct libnvme_ns *n) -{ - struct json_object *r = json_create_object(); - char devname[NAME_LEN] = { 0 }; - char genname[NAME_LEN] = { 0 }; - int lba; - uint64_t lba_count, nsze, nuse; - - libnvme_ns_get_lba_size(n, &lba, 0); - libnvme_ns_get_lba_count(n, &lba_count, 0); - nsze = lba_count * lba; - libnvme_ns_get_lba_util(n, &nuse, 0); - nuse *= lba; - - nvme_dev_full_path(n, devname, sizeof(devname)); - nvme_generic_full_path(n, genname, sizeof(genname)); - - obj_add_int(r, "NameSpace", libnvme_ns_get_nsid(n)); - obj_add_str(r, "DevicePath", devname); - obj_add_str(r, "GenericPath", genname); - obj_add_str(r, "Firmware", libnvme_ns_get_firmware(n)); - obj_add_str(r, "ModelNumber", libnvme_ns_get_model(n)); - obj_add_str(r, "SerialNumber", libnvme_ns_get_serial(n)); - obj_add_uint64(r, "UsedBytes", nuse); - obj_add_uint64(r, "MaximumLBA", lba_count); - obj_add_uint64(r, "PhysicalSize", nsze); - obj_add_int(r, "SectorSize", lba); - - return r; -} - -static void json_simple_list(struct libnvme_global_ctx *ctx) -{ - struct json_object *r = json_r; - struct json_object *jdevices = json_create_array(); - - struct libnvme_host *h; - struct libnvme_subsystem *s; - struct libnvme_ctrl *c; - struct libnvme_ns *n; - - libnvme_for_each_host(ctx, h) { - libnvme_for_each_subsystem(h, s) { - libnvme_subsystem_for_each_ns(s, n) - array_add_obj(jdevices, json_list_item_obj(n)); - - libnvme_subsystem_for_each_ctrl(s, c) { - libnvme_ctrl_for_each_ns(c, n) - array_add_obj(jdevices, json_list_item_obj(n)); - } - } + if (strlen(ascii)) { + ascii[i % width + 1] = '\0'; + array_add_str(array, ascii); } - - obj_add_array(r, "Devices", jdevices); } -static void json_list_item(struct libnvme_ns *n, struct shr_table *t) +void obj_d(struct json_object *o, const char *k, unsigned char *buf, int len, + int width, int group) { - struct json_object *r = json_list_item_obj(n); + struct json_object *data = json_create_array(); - json_print(r); + d_json(buf, len, width, group, data); + obj_add_array(o, k, data); } -static void json_print_list_items(struct libnvme_global_ctx *ctx) -{ - if (json_print_ops.flags & VERBOSE) { - if (nvme_args.output_format_ver == 2) - json_detail_list_v2(ctx); - else - json_detail_list(ctx); - } else - json_simple_list(ctx); -} -static unsigned int json_subsystem_topology_multipath(struct libnvme_subsystem *s, - json_object *namespaces) +void obj_add_uint_nx(struct json_object *o, const char *k, __u32 v) { - struct libnvme_ns *n; - struct libnvme_path *p; - unsigned int i = 0; - const char *iopolicy; - - libnvme_subsystem_get_iopolicy(s, &iopolicy, ""); - - libnvme_subsystem_for_each_ns(s, n) { - struct json_object *ns_attrs; - struct json_object *paths; - - ns_attrs = json_create_object(); - obj_add_int(ns_attrs, "NSID", libnvme_ns_get_nsid(n)); - obj_add_str(ns_attrs, "Name", libnvme_ns_get_name(n)); - - paths = json_create_array(); - libnvme_namespace_for_each_path(n, p) { - struct json_object *path_attrs; - struct json_object *ctrls, *ctrl_attrs; - struct libnvme_ctrl *c; - const char *ana_state; - - libnvme_path_get_ana_state(p, &ana_state, ""); - path_attrs = json_create_object(); - obj_add_str(path_attrs, "Path", libnvme_path_get_name(p)); - obj_add_str(path_attrs, "ANAState", ana_state); - - /* - * For iopolicy numa exclude "Qdepth", for iopolicy - * queue-depth exclude "NUMANodes" and for iopolicy - * round-robin exclude both "Qdepth" and "NUMANodes". - */ - if (streq(iopolicy, "numa")) { - const char *numa_nodes; - - libnvme_path_get_numa_nodes(p, &numa_nodes, - ""); - obj_add_str(path_attrs, "NUMANodes", - numa_nodes); - } else if (streq(iopolicy, "queue-depth")) { - int queue_depth; - - libnvme_path_get_queue_depth(p, &queue_depth, - 0); - obj_add_int(path_attrs, "Qdepth", queue_depth); - } - - c = libnvme_path_get_ctrl(p); - ctrls = json_create_array(); - ctrl_attrs = json_create_object(); - obj_add_str(ctrl_attrs, "Name", libnvme_ctrl_get_name(c)); - obj_add_str(ctrl_attrs, "Transport", libnvme_ctrl_get_transport(c)); - obj_add_ctrl_address(ctrl_attrs, c); - obj_add_ctrl_address_details(ctrl_attrs, "AddressDetails", c); - obj_add_str(ctrl_attrs, "State", libnvme_ctrl_get_state(c)); - array_add_obj(ctrls, ctrl_attrs); - obj_add_array(path_attrs, "Controller", ctrls); - - array_add_obj(paths, path_attrs); - } - obj_add_array(ns_attrs, "Paths", paths); - array_add_obj(namespaces, ns_attrs); - i++; - } + char str[STR_LEN]; - return i; + sprintf(str, "%#x", v); + obj_add_str(o, k, str); } -static void json_print_nvme_subsystem_topology(struct libnvme_subsystem *s, - json_object *namespaces) -{ - struct libnvme_ctrl *c; - struct libnvme_ns *n; - - libnvme_subsystem_for_each_ctrl(s, c) { - libnvme_ctrl_for_each_ns(c, n) { - struct json_object *ctrl_attrs; - struct json_object *ns_attrs; - struct json_object *ctrl; - - ns_attrs = json_create_object(); - obj_add_int(ns_attrs, "NSID", libnvme_ns_get_nsid(n)); - obj_add_str(ns_attrs, "Name", libnvme_ns_get_name(n)); - - ctrl = json_create_array(); - ctrl_attrs = json_create_object(); - obj_add_str(ctrl_attrs, "Name", - libnvme_ctrl_get_name(c)); - obj_add_str(ctrl_attrs, "Transport", - libnvme_ctrl_get_transport(c)); - obj_add_ctrl_address(ctrl_attrs, c); - obj_add_ctrl_address_details(ctrl_attrs, "AddressDetails", c); - obj_add_str(ctrl_attrs, "State", - libnvme_ctrl_get_state(c)); - - array_add_obj(ctrl, ctrl_attrs); - obj_add_array(ns_attrs, "Controller", ctrl); - array_add_obj(namespaces, ns_attrs); - } - } -} -static void json_simple_topology(struct libnvme_global_ctx *ctx) +void obj_add_result(struct json_object *o, const char *v, ...) { - struct json_object *host_attrs, *subsystem_attrs; - struct json_object *subsystems, *namespaces; - struct json_object *a = json_create_array(); - struct libnvme_host *h; - - libnvme_for_each_host(ctx, h) { - struct libnvme_subsystem *s; - const char *hostid; - - host_attrs = json_create_object(); - obj_add_str(host_attrs, "HostNQN", libnvme_host_get_hostnqn(h)); - hostid = libnvme_host_get_hostid(h); - if (hostid) - obj_add_str(host_attrs, "HostID", hostid); - subsystems = json_create_array(); - libnvme_for_each_subsystem(h, s) { - const char *iopolicy; - - subsystem_attrs = json_create_object(); - obj_add_str(subsystem_attrs, "Name", libnvme_subsystem_get_name(s)); - obj_add_str(subsystem_attrs, "NQN", libnvme_subsystem_get_subsysnqn(s)); - libnvme_subsystem_get_iopolicy(s, &iopolicy, ""); - obj_add_str(subsystem_attrs, "IOPolicy", iopolicy); - - if (verbose_mode()) { - const char *model; - const char *serial; - const char *firmware; - - libnvme_subsystem_get_model(s, &model, ""); - libnvme_subsystem_get_serial(s, &serial, ""); - libnvme_subsystem_get_firmware(s, &firmware, - ""); - - obj_add_str(subsystem_attrs, "Model", model); - obj_add_str(subsystem_attrs, "Serial", serial); - obj_add_str(subsystem_attrs, "Firmware", - firmware); - obj_add_str(subsystem_attrs, "Type", - libnvme_subsystem_get_subsystype(s)); - } - - array_add_obj(subsystems, subsystem_attrs); - namespaces = json_create_array(); - - if (!json_subsystem_topology_multipath(s, namespaces)) - json_print_nvme_subsystem_topology(s, namespaces); - - obj_add_array(subsystem_attrs, "Namespaces", namespaces); - } - obj_add_array(host_attrs, "Subsystems", subsystems); - array_add_obj(a, host_attrs); - } + va_list ap; - json_print(a); -} + __cleanup_free char *value = NULL; -#ifdef CONFIG_TOP -/* A rate with two decimals, as nvme top shows it */ -static void obj_add_rate(struct json_object *o, const char *k, double v) -{ - char buf[64]; + va_start(ap, v); - snprintf(buf, sizeof(buf), "%.2f", v); - json_object_object_add(o, k, json_object_new_double_s(v, buf)); -} + if (vasprintf(&value, v, ap) < 0) + value = NULL; -/* An attribute of a kernel which may not have it is left out */ -static void obj_add_count(struct json_object *o, const char *k, int ret, - long v) -{ - if (!ret) - json_object_object_add(o, k, json_object_new_int64(v)); -} + obj_add_str(o, "Result", value ? value : alloc_error); -static void obj_add_iostat(struct json_object *o, const struct nvme_iostat *st) -{ - struct json_object *r = json_create_object(); - - obj_add_rate(r, "ReadIOPS", st->r_iops); - obj_add_rate(r, "WriteIOPS", st->w_iops); - obj_add_rate(r, "ReadLatencyMs", st->r_lat); - obj_add_rate(r, "WriteLatencyMs", st->w_lat); - obj_add_rate(r, "ReadBytesPerSec", st->r_bw); - obj_add_rate(r, "WriteBytesPerSec", st->w_bw); - obj_add_uint(r, "Inflights", st->inflights); - obj_add_rate(r, "UtilPercent", st->util); - - obj_add_obj(o, "Stats", r); + va_end(ap); } -/* The sum of the rates, and the highest latencies and utilization */ -static void obj_add_iostat_aggr(struct json_object *o, - const struct nvme_iostat *st) +void obj_add_key(struct json_object *o, const char *k, const char *v, ...) { - struct json_object *r = json_create_object(); - - obj_add_rate(r, "ReadIOPS", st->r_iops); - obj_add_rate(r, "WriteIOPS", st->w_iops); - obj_add_rate(r, "MaxReadLatencyMs", st->r_lat); - obj_add_rate(r, "MaxWriteLatencyMs", st->w_lat); - obj_add_rate(r, "ReadBytesPerSec", st->r_bw); - obj_add_rate(r, "WriteBytesPerSec", st->w_bw); - obj_add_rate(r, "MaxUtilPercent", st->util); - - obj_add_obj(o, "Stats", r); -} + va_list ap; -static struct json_object *json_top_path(struct libnvme_path *p) -{ - struct json_object *r = json_create_object(); - struct nvme_iostat st; - const char *str; - int qdepth, ret; - long v; - - obj_add_str(r, "Name", libnvme_path_get_name(p)); - obj_add_str(r, "Controller", - libnvme_ctrl_get_name(libnvme_path_get_ctrl(p))); - if (!libnvme_path_get_ana_state(p, &str, NULL)) - obj_add_str(r, "ANAState", str); - if (!libnvme_path_get_numa_nodes(p, &str, NULL)) - obj_add_str(r, "NUMANodes", str); - if (!libnvme_path_get_queue_depth(p, &qdepth, 0)) - obj_add_int(r, "Qdepth", qdepth); - ret = libnvme_path_get_command_retry_count(p, &v, 0); - obj_add_count(r, "Retries", ret, v); - ret = libnvme_path_get_multipath_failover_count(p, &v, 0); - obj_add_count(r, "Failovers", ret, v); - ret = libnvme_path_get_command_error_count(p, &v, 0); - obj_add_count(r, "Errors", ret, v); - - nvme_iostat_path(p, &st); - obj_add_iostat(r, &st); - - return r; -} + __cleanup_free char *value = NULL; -static struct json_object *json_top_nshead(struct libnvme_ns *n, - struct nvme_iostat *aggr) -{ - struct json_object *r = json_create_object(); - struct json_object *paths = json_create_array(); - struct libnvme_path *p; - struct nvme_iostat st; - int ret; - long v; - - obj_add_str(r, "Name", libnvme_ns_get_name(n)); - obj_add_uint(r, "NSID", libnvme_ns_get_nsid(n)); - ret = libnvme_ns_get_io_requeue_no_usable_path_count(n, &v, 0); - obj_add_count(r, "RequeueIO", ret, v); - ret = libnvme_ns_get_io_fail_no_available_path_count(n, &v, 0); - obj_add_count(r, "FailIO", ret, v); - - nvme_iostat_ns(n, &st); - nvme_iostat_aggr(aggr, &st); - obj_add_iostat(r, &st); - - libnvme_namespace_for_each_path(n, p) - array_add_obj(paths, json_top_path(p)); - obj_add_array(r, "Paths", paths); - - return r; -} + va_start(ap, v); -static struct json_object *json_top_ns(struct libnvme_ns *n, - struct libnvme_ctrl *c, - struct nvme_iostat *aggr) -{ - struct json_object *r = json_create_object(); - struct nvme_iostat st; - int ret; - long v; - - obj_add_str(r, "Name", libnvme_ns_get_name(n)); - obj_add_uint(r, "NSID", libnvme_ns_get_nsid(n)); - obj_add_str(r, "Controller", libnvme_ctrl_get_name(c)); - ret = libnvme_ns_get_command_retry_count(n, &v, 0); - obj_add_count(r, "Retries", ret, v); - ret = libnvme_ns_get_command_error_count(n, &v, 0); - obj_add_count(r, "Errors", ret, v); - - nvme_iostat_ns(n, &st); - nvme_iostat_aggr(aggr, &st); - obj_add_iostat(r, &st); - - return r; -} + if (vasprintf(&value, v, ap) < 0) + value = NULL; -static struct json_object *json_top_ctrl(struct libnvme_ctrl *c, - bool multipath) -{ - struct json_object *r = json_create_object(); - struct nvme_iostat aggr = { 0 }, st; - struct libnvme_path *p; - struct libnvme_ns *n; - const char *node; - int npaths = 0, ret; - long v; - - obj_add_str(r, "Name", libnvme_ctrl_get_name(c)); - obj_add_str(r, "Transport", libnvme_ctrl_get_transport(c)); - obj_add_ctrl_address(r, c); - obj_add_str(r, "State", libnvme_ctrl_get_state(c)); - if (!libnvme_ctrl_get_numa_node(c, &node, NULL)) - obj_add_int(r, "NUMANode", atoi(node)); - ret = libnvme_ctrl_get_reset_count(c, &v, 0); - obj_add_count(r, "Resets", ret, v); - ret = libnvme_ctrl_get_reconnect_count(c, &v, 0); - obj_add_count(r, "Reconnects", ret, v); - ret = libnvme_ctrl_get_command_error_count(c, &v, 0); - obj_add_count(r, "Errors", ret, v); - - if (multipath) { - libnvme_ctrl_for_each_path(c, p) { - npaths++; - nvme_iostat_path(p, &st); - nvme_iostat_aggr(&aggr, &st); - } - obj_add_int(r, "Paths", npaths); - } else { - libnvme_ctrl_for_each_ns(c, n) { - nvme_iostat_ns(n, &st); - nvme_iostat_aggr(&aggr, &st); - } - } - obj_add_iostat_aggr(r, &aggr); + obj_add_str(o, k, value ? value : alloc_error); - return r; + va_end(ap); } -static struct json_object *json_top_subsys(struct libnvme_subsystem *s) +struct json_object *obj_create_array_obj(struct json_object *o, const char *k) { - struct json_object *r = json_create_object(); - struct json_object *namespaces = json_create_array(); - struct json_object *ctrls = json_create_array(); - bool multipath = nvme_is_multipath(s); - struct nvme_iostat aggr = { 0 }; - struct libnvme_ctrl *c; - struct libnvme_ns *n; - const char *str; - - obj_add_str(r, "Name", libnvme_subsystem_get_name(s)); - obj_add_str(r, "NQN", libnvme_subsystem_get_subsysnqn(s)); - obj_add_str(r, "HostNQN", - libnvme_host_get_hostnqn(libnvme_subsystem_get_host(s))); - if (!libnvme_subsystem_get_iopolicy(s, &str, NULL)) - obj_add_str(r, "IOPolicy", str); - if (!libnvme_subsystem_get_model(s, &str, NULL)) - obj_add_str(r, "Model", str); - if (!libnvme_subsystem_get_serial(s, &str, NULL)) - obj_add_str(r, "Serial", str); - if (!libnvme_subsystem_get_firmware(s, &str, NULL)) - obj_add_str(r, "Firmware", str); - obj_add_str(r, "Type", libnvme_subsystem_get_subsystype(s)); - - if (multipath) { - libnvme_subsystem_for_each_ns(s, n) - array_add_obj(namespaces, json_top_nshead(n, &aggr)); - } else { - libnvme_subsystem_for_each_ctrl(s, c) - libnvme_ctrl_for_each_ns(c, n) - array_add_obj(namespaces, - json_top_ns(n, c, &aggr)); - } - obj_add_iostat_aggr(r, &aggr); - obj_add_array(r, "Namespaces", namespaces); - - libnvme_subsystem_for_each_ctrl(s, c) - array_add_obj(ctrls, json_top_ctrl(c, multipath)); - obj_add_array(r, "Controllers", ctrls); - - return r; -} + struct json_object *array = json_create_array(); + struct json_object *obj = json_create_object(); -static void json_top_update(struct libnvme_global_ctx *ctx) -{ - struct libnvme_subsystem *s; - struct libnvme_host *h; + obj_add_array(o, k, array); + array_add_obj(array, obj); - libnvme_for_each_host(ctx, h) - libnvme_for_each_subsystem(h, s) - nvme_iostat_update_subsys(s, nvme_is_multipath(s)); + return obj; } -/* Takes two samples @interval seconds apart and prints the rates */ -static void json_top(int interval) +struct json_object *obj_create(const char *k) { - __cleanup_nvme_global_ctx struct libnvme_global_ctx *ctx = NULL; - struct json_object *r, *subsystems; - struct libnvme_subsystem *s; - struct libnvme_host *h; - int err; - - err = nvme_create_global_ctx(&ctx); - if (err) - return; - - if (libnvme_scan_topology(ctx, NULL, NULL)) { - nvme_show_error("Failed to scan topology"); - return; - } - - json_top_update(ctx); - sleep(interval); - json_top_update(ctx); - - r = json_create_object(); - obj_add_int(r, "Interval", interval); - subsystems = json_create_array(); - libnvme_for_each_host(ctx, h) - libnvme_for_each_subsystem(h, s) - array_add_obj(subsystems, json_top_subsys(s)); - obj_add_array(r, "Subsystems", subsystems); - - json_print(r); -} -#endif /* CONFIG_TOP */ + struct json_object *array; + struct json_object *obj = json_create_object(); -static void json_directive_show_fields_identify(__u8 doper, __u8 *field, - __u32 len, - struct json_object *r) -{ - struct json_object *support; - struct json_object *enabled; - struct json_object *persistent; - - switch (doper) { - case NVME_DIRECTIVE_RECEIVE_IDENTIFY_DOPER_PARAM: - if (len < NVME_DIRECTIVE_IDENTIFY_PARAM_LEN) { - obj_add_str(r, "Error", "directive data too short"); - break; - } - support = json_create_object(); - obj_add_obj(r, "Directive support", support); - obj_add_str(support, "Identify Directive", - *field & 0x1 ? "Supported" : "Not supported"); - obj_add_str(support, "Stream Directive", - *field & 0x2 ? "Supported" : "Not supported"); - obj_add_str(support, "Data Placement Directive", - *field & 0x4 ? "Supported" : "Not supported"); - enabled = json_create_object(); - obj_add_obj(r, "Directive enabled", enabled); - obj_add_str(enabled, "Identify Directive", - *(field + 32) & 0x1 ? "Enabled" : "Disabled"); - obj_add_str(enabled, "Stream Directive", - *(field + 32) & 0x2 ? "Enabled" : "Disabled"); - obj_add_str(enabled, "Data Placement Directive", - *(field + 32) & 0x4 ? "Enabled" : "Disabled"); - persistent = json_create_object(); - obj_add_obj(r, - "Directive Persistent Across Controller Level Resets", - persistent); - obj_add_str(persistent, "Identify Directive", - *(field + 64) & 0x1 ? "Enabled" : "Disabled"); - obj_add_str(persistent, "Stream Directive", - *(field + 64) & 0x2 ? "Enabled" : "Disabled"); - obj_add_str(persistent, "Data Placement Directive", - *(field + 64) & 0x4 ? "Enabled" : "Disabled"); - break; - default: - obj_add_str(r, "Error", "invalid directive operations for Identify Directives"); - break; + if (json_r) { + array = json_create_array(); + obj_add_array(json_r, k, array); + array_add_obj(array, obj); } -} - -static void json_directive_show_fields_streams(__u8 doper, - unsigned int result, __u8 *field, - __u32 len, struct json_object *r) -{ - struct nvme_streams_directive_params *params = (void *)field; - struct nvme_streams_directive_status *status = (void *)field; - int count; - int i; - char json_str[STR_LEN]; - switch (doper) { - case NVME_DIRECTIVE_RECEIVE_STREAMS_DOPER_PARAM: - if (len < sizeof(*params)) { - obj_add_str(r, "Error", "directive data too short"); - break; - } - obj_add_uint(r, "Max Streams Limit (MSL)", - le16_to_cpu(params->msl)); - obj_add_uint(r, "NVM Subsystem Streams Available (NSSA)", - le16_to_cpu(params->nssa)); - obj_add_uint(r, "NVM Subsystem Streams Open (NSSO)", - le16_to_cpu(params->nsso)); - obj_add_uint(r, "NVM Subsystem Stream Capability (NSSC)", - params->nssc); - obj_add_uint(r, "Stream Write Size (in unit of LB size) (SWS)", - le32_to_cpu(params->sws)); - obj_add_uint(r, "Stream Granularity Size (in unit of SWS) (SGS)", - le16_to_cpu(params->sgs)); - obj_add_uint(r, "Namespace Streams Allocated (NSA)", - le16_to_cpu(params->nsa)); - obj_add_uint(r, "Namespace Streams Open (NSO)", - le16_to_cpu(params->nso)); - break; - case NVME_DIRECTIVE_RECEIVE_STREAMS_DOPER_STATUS: - if (len < sizeof(*status)) { - obj_add_str(r, "Error", "directive data too short"); - break; - } - count = nvme_streams_status_nr_sid(status, len); - obj_add_uint(r, "Open Stream Count", le16_to_cpu(status->osc)); - for (i = 0; i < count; i++) { - sprintf(json_str, "Stream Identifier %.6u", i + 1); - obj_add_uint(r, json_str, le16_to_cpu(status->sid[i])); - } - break; - case NVME_DIRECTIVE_RECEIVE_STREAMS_DOPER_RESOURCE: - obj_add_uint(r, "Namespace Streams Allocated (NSA)", result & 0xffff); - break; - default: - obj_add_str(r, "Error", - "invalid directive operations for Streams Directives"); - break; - } + return obj; } -static void json_directive_show_fields(__u8 dtype, __u8 doper, unsigned int result, - __u8 *field, __u32 len, - struct json_object *r) +void json_print(struct json_object *r) { - switch (dtype) { - case NVME_DIRECTIVE_DTYPE_IDENTIFY: - json_directive_show_fields_identify(doper, field, len, r); - break; - case NVME_DIRECTIVE_DTYPE_STREAMS: - json_directive_show_fields_streams(doper, result, field, len, - r); - break; - default: - obj_add_str(r, "Error", "invalid directive type"); - break; - } + json_print_object(r, NULL); + printf("\n"); + json_free_object(r); } -static void json_directive_show(__u8 type, __u8 oper, __u16 spec, __u32 nsid, __u64 result, - void *buf, __u32 len) +void obj_print(struct json_object *o) { - struct json_object *r = json_r; - struct json_object *data; - char json_str[STR_LEN]; - - sprintf(json_str, "%#x", type); - obj_add_str(r, "Type", json_str); - sprintf(json_str, "%#x", oper); - obj_add_str(r, "Operation", json_str); - sprintf(json_str, "%#x", spec); - obj_add_str(r, "spec", json_str); - sprintf(json_str, "%#x", nsid); - obj_add_str(r, "NSID", json_str); - sprintf(json_str, "%#"PRIx64, (uint64_t)result); - obj_add_result(r, "%s", json_str); - - if (verbose_mode()) { - json_directive_show_fields(type, oper, result, buf, len, r); - } else if (buf) { - data = json_create_array(); - d_json((unsigned char *)buf, len, 16, 1, data); - obj_add_array(r, "data", data); - } + if (!json_r) + json_print(o); } -#ifdef CONFIG_FABRICS -static void json_discovery_log(const struct nvmf_discovery_log *log, int numrec) -{ - struct json_object *r = json_r; - struct json_object *entries = json_create_array(); - int i; - - obj_add_uint64(r, "genctr", le64_to_cpu(log->genctr)); - obj_add_array(r, "records", entries); - - for (i = 0; i < numrec; i++) { - const struct nvmf_disc_log_entry *e = &log->entries[i]; - struct json_object *entry = json_create_object(); - /* - * e->trsvcid/subnqn/traddr are fixed-width fields off the wire, - * not guaranteed NUL-terminated. json_object_new_string() - * needs a NUL-terminated C string, so make NUL-terminated - * copies and trim trailing spaces (if any). Members of e - * cannot be modified directly (we do not own that data). - */ - __cleanup_free char *trsvcid = NULL; - __cleanup_free char *traddr = NULL; - __cleanup_free char *subnqn = NULL; - - trsvcid = shr_buf2str(e->trsvcid, sizeof(e->trsvcid)); - traddr = shr_buf2str(e->traddr, sizeof(e->traddr)); - subnqn = shr_buf2str(e->subnqn, sizeof(e->subnqn)); - - obj_add_str(entry, "trtype", libnvmf_trtype_str(e->trtype)); - obj_add_str(entry, "adrfam", libnvmf_adrfam_str(e->adrfam)); - obj_add_str(entry, "subtype", libnvmf_subtype_str(e->subtype)); - obj_add_str(entry, "treq", libnvmf_treq_str(e->treq)); - obj_add_uint(entry, "portid", le16_to_cpu(e->portid)); - obj_add_str(entry, "trsvcid", trsvcid); - obj_add_str(entry, "subnqn", subnqn); - obj_add_str(entry, "traddr", traddr); - obj_add_str(entry, "eflags", libnvmf_eflags_str(le16_to_cpu(e->eflags))); - - switch (e->trtype) { - case NVMF_TRTYPE_RDMA: - obj_add_str(entry, "rdma_prtype", libnvmf_prtype_str(e->tsas.rdma.prtype)); - obj_add_str(entry, "rdma_qptype", libnvmf_qptype_str(e->tsas.rdma.qptype)); - obj_add_str(entry, "rdma_cms", libnvmf_cms_str(e->tsas.rdma.cms)); - obj_add_uint(entry, "rdma_pkey", le16_to_cpu(e->tsas.rdma.pkey)); - break; - case NVMF_TRTYPE_TCP: - obj_add_str(entry, "sectype", libnvmf_sectype_str(e->tsas.tcp.sectype)); - break; - default: - break; - } - array_add_obj(entries, entry); - } -} -#else -static void json_discovery_log(const struct nvmf_discovery_log *log, - int numrec) +static bool verbose_mode(void) { + return json_print_ops.flags & VERBOSE; } -#endif -#ifdef CONFIG_FABRICS -static void json_add_param(const char *key, const char *value, void *user_data) +bool json_verbose_mode(void) { - obj_add_str(user_data, key, value); + return verbose_mode(); } -/* - * libnvmf_config_conn_for_each() callback for "nvme config show -o json". - * Reports fields as configured, not canonicalized through a TID (which has - * no per-field accessors). hostnqn/hostid are null when a persona falls - * back to the system default, not the value it would resolve to. - */ -static void json_add_conn(const struct libnvmf_config_conn *c, void *user_data) +struct json_object *json_root(void) { - struct json_object *entries = user_data; - struct json_object *entry = json_create_object(); - struct json_object *params_obj = json_create_object(); - const struct libnvmf_params *params = libnvmf_config_conn_get_params(c); - - obj_add_str(entry, "source", libnvmf_config_conn_get_source(c)); - obj_add_bool(entry, "is_dc", libnvmf_config_conn_is_dc(c)); - obj_add_str(entry, "transport", libnvmf_config_conn_get_transport(c)); - obj_add_str(entry, "traddr", libnvmf_config_conn_get_traddr(c)); - obj_add_str(entry, "trsvcid", libnvmf_config_conn_get_trsvcid(c)); - obj_add_str(entry, "nqn", libnvmf_config_conn_get_subsysnqn(c)); - obj_add_str(entry, "host-traddr", - libnvmf_config_conn_get_host_traddr(c)); - obj_add_str(entry, "host-iface", libnvmf_config_conn_get_host_iface(c)); - obj_add_str(entry, "hostnqn", libnvmf_config_conn_get_hostnqn(c)); - obj_add_str(entry, "hostid", libnvmf_config_conn_get_hostid(c)); - - libnvmf_params_for_each(params, json_add_param, params_obj); - obj_add_obj(entry, "params", params_obj); - - array_add_obj(entries, entry); + return json_r; } -static void json_config_conn_list(struct libnvmf_config *config) +void json_timestamp(struct json_object *r, struct nvme_timestamp *ts) { - struct json_object *r = json_r; - struct json_object *entries = json_create_array(); - - obj_add_array(r, "connections", entries); - libnvmf_config_conn_for_each(config, json_add_conn, entries); + obj_add_uint64(r, "timestamp", int48_to_long(ts->timestamp)); + obj_add_str(r, "timestamp string", nvme_format_timestamp(ts->timestamp)); + obj_add_str(r, "timestamp origin", nvme_format_timestamp_origin(ts->attr)); + obj_add_str(r, "synch", nvme_format_timestamp_sync(ts->attr)); } -#else -static void json_config_conn_list(struct libnvmf_config *config) {} -#endif -static void json_connect_msg(struct libnvme_ctrl *c) +void json_d(unsigned char *buf, int len, int width, int group) { struct json_object *r = json_r; + char json_str[STR_LEN]; - obj_add_str(r, "device", libnvme_ctrl_get_name(c)); + sprintf(json_str, "data: buf=%p len=%d width=%d group=%d", buf, len, width, group); + obj_d(r, json_str, buf, len, width, group); } static void json_output_object(struct json_object *r) @@ -2830,39 +504,13 @@ static int json_capture_add(const void *buf, size_t len) static struct print_ops json_print_ops = { /* libnvme types.h print functions */ - .ctrl_registers = json_ctrl_registers, - .directive = json_directive_show, - .discovery_log = json_discovery_log, - .lba_status = json_lba_status, - .resv_report = json_nvme_resv_report, - .select_result = json_select_result, - .show_feature = json_feature_show, - .show_feature_fields = json_feature_show_fields, - .id_ctrl_rpmbs = json_id_ctrl_rpmbs, - .lba_range = json_lba_range, - .lba_status_info = json_lba_status_info, .d = json_d, .show_init = json_show_init, .show_finish = json_show_finish, - /* libnvme tree print functions */ - .list_item = json_list_item, - .list_items = json_print_list_items, - .print_nvme_subsystem_list = json_print_nvme_subsystem_list, - .topology_ctrl = json_simple_topology, - .topology_namespace = json_simple_topology, - .topology_multipath = json_simple_topology, - - /* nvme top */ -#ifdef CONFIG_TOP - .top = json_top, -#endif - /* config show */ - .config_conn_list = json_config_conn_list, /* status and error messages */ - .connect_msg = json_connect_msg, .show_message = json_output_message, .show_perror = json_output_perror, .show_status = json_output_status, diff --git a/src/nvme-print-json.h b/src/nvme-print-json.h index 65449ad1d2..ea08ba7da2 100644 --- a/src/nvme-print-json.h +++ b/src/nvme-print-json.h @@ -45,6 +45,4 @@ void obj_add_key(struct json_object *o, const char *k, const char *v, ...) __attribute__((format(printf, 3, 4))); /* log */ -void json_feature_show_fields(enum nvme_features_id fid, unsigned int result, - unsigned char *buf); void json_timestamp(struct json_object *r, struct nvme_timestamp *ts); diff --git a/src/nvme-print-stdout-id.c b/src/nvme-print-stdout-id.c deleted file mode 100644 index b32ea830fb..0000000000 --- a/src/nvme-print-stdout-id.c +++ /dev/null @@ -1,40 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-or-later -#include -#include -#include -#include - -#include "cleanup.h" -#include "nvme-print.h" -#include "nvme-print-stdout.h" - -struct shr_table *stdout_id_ctrl_rpmbs_table(__le32 ctrl_rpmbs) -{ - struct shr_table *t; - __u32 rpmbs = le32_to_cpu(ctrl_rpmbs); - __u32 asz = (rpmbs & 0xFF000000) >> 24; - __u32 tsz = (rpmbs & 0xFF0000) >> 16; - __u32 rsvd = (rpmbs & 0xFFC0) >> 6; - __u32 auth = (rpmbs & 0x38) >> 3; - __u32 rpmb = rpmbs & 0x7; - - t = stdout_bits_table_create(); - if (!t) - return NULL; - - stdout_bits_add(t, "[31:24]", asz, "Access Size"); - stdout_bits_add(t, "[23:16]", tsz, "Total Size"); - if (rsvd) - stdout_bits_add(t, "[15:6]", rsvd, "Reserved"); - stdout_bits_add(t, "[5:3]", auth, "Authentication Method"); - stdout_bits_add(t, "[2:0]", rpmb, "Number of RPMB Units"); - - return t; -} - -void stdout_id_ctrl_rpmbs(__le32 ctrl_rpmbs) -{ - stdout_kv_table_finish(stdout_id_ctrl_rpmbs_table(ctrl_rpmbs), - "id-ctrl-rpmbs"); - printf("\n"); -} diff --git a/src/nvme-print-stdout-log.c b/src/nvme-print-stdout-log.c deleted file mode 100644 index ea95885ab8..0000000000 --- a/src/nvme-print-stdout-log.c +++ /dev/null @@ -1,85 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-or-later -#include - -#ifdef CONFIG_FABRICS -#include -#endif /* CONFIG_FABRICS */ - -#include -#include -#include -#include - -#include "cleanup.h" -#include "logging.h" -#include "nvme-print.h" -#include "nvme-print-stdout.h" - -#ifdef CONFIG_FABRICS -void stdout_discovery_log(const struct nvmf_discovery_log *log, int numrec) -{ - int i; - - printf("\nDiscovery Log Number of Records %d, Generation counter %" - PRIu64"\n", numrec, le64_to_cpu(log->genctr)); - - for (i = 0; i < numrec; i++) { - const struct nvmf_disc_log_entry *e = &log->entries[i]; - - /* - * e->trsvcid/subnqn/traddr are fixed-width fields off the - * wire, space-padded per the spec, and not guaranteed - * NUL-terminated by a non-compliant DC. shr_buf2str() bounds - * the read to the field's own size and strips the padding. - */ - __cleanup_free char *trsvcid = NULL; - __cleanup_free char *subnqn = NULL; - __cleanup_free char *traddr = NULL; - struct shr_table *t; - - trsvcid = shr_buf2str(e->trsvcid, sizeof(e->trsvcid)); - subnqn = shr_buf2str(e->subnqn, sizeof(e->subnqn)); - traddr = shr_buf2str(e->traddr, sizeof(e->traddr)); - - printf("=====Discovery Log Entry %d======\n", i); - - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, "trtype", "%s", libnvmf_trtype_str(e->trtype)); - stdout_kv_add(t, "adrfam", "%s", - e->traddr[0] ? - libnvmf_adrfam_str(e->adrfam) : ""); - stdout_kv_add(t, "subtype", "%s", - libnvmf_subtype_str(e->subtype)); - stdout_kv_add(t, "treq", "%s", libnvmf_treq_str(e->treq)); - stdout_kv_add(t, "portid", "%d", le16_to_cpu(e->portid)); - stdout_kv_add(t, "trsvcid", "%s", trsvcid); - stdout_kv_add(t, "subnqn", "%s", subnqn); - stdout_kv_add(t, "traddr", "%s", traddr); - stdout_kv_add(t, "eflags", "%s", - libnvmf_eflags_str(le16_to_cpu(e->eflags))); - - switch (e->trtype) { - case NVMF_TRTYPE_RDMA: - stdout_kv_add(t, "rdma_prtype", "%s", - libnvmf_prtype_str(e->tsas.rdma.prtype)); - stdout_kv_add(t, "rdma_qptype", "%s", - libnvmf_qptype_str(e->tsas.rdma.qptype)); - stdout_kv_add(t, "rdma_cms", "%s", - libnvmf_cms_str(e->tsas.rdma.cms)); - stdout_kv_add(t, "rdma_pkey", "%#04x", - le16_to_cpu(e->tsas.rdma.pkey)); - break; - case NVMF_TRTYPE_TCP: - stdout_kv_add(t, "sectype", "%s", - libnvmf_sectype_str(e->tsas.tcp.sectype)); - break; - } - - stdout_kv_table_finish(t, "discovery-log"); - } -} - -#endif /* CONFIG_FABRICS */ diff --git a/src/nvme-print-stdout.c b/src/nvme-print-stdout.c index fb295c5e75..b9384f7c04 100644 --- a/src/nvme-print-stdout.c +++ b/src/nvme-print-stdout.c @@ -1,34 +1,22 @@ // SPDX-License-Identifier: GPL-2.0-or-later #include -#include #include #include #include #include -#include #include #include -#ifdef CONFIG_FABRICS -#include -#include -#endif - #include #include #include #include -#include -#include -#include #include #include -#include #include #include #include -#include #include #include #include @@ -40,364 +28,12 @@ #include "nvme-print.h" #include "nvme-print-stdout.h" -enum simple_list_col { - SIMPLE_LIST_COL_NODE, - SIMPLE_LIST_COL_GENERIC, - SIMPLE_LIST_COL_SN, - SIMPLE_LIST_COL_MODEL, - SIMPLE_LIST_COL_NS, - SIMPLE_LIST_COL_USAGE, - SIMPLE_LIST_COL_FORMAT, - SIMPLE_LIST_COL_FW_REV, -}; - const char dash[100] = {[0 ... 99] = '-'}; struct print_ops stdout_print_ops; -static const char *subsys_key(const struct libnvme_subsystem *s) -{ - return libnvme_subsystem_get_name((struct libnvme_subsystem *)s); -} - -static const char *ctrl_key(const struct libnvme_ctrl *c) -{ - return libnvme_ctrl_get_name((struct libnvme_ctrl *)c); -} - -static const char *ns_key(const struct libnvme_ns *n) -{ - return libnvme_ns_get_name((struct libnvme_ns *)n); -} - -static bool subsys_cmp(const struct libnvme_subsystem *s, const char *name) -{ - return streq(libnvme_subsystem_get_name((struct libnvme_subsystem *)s), - name); -} - -static bool ctrl_cmp(const struct libnvme_ctrl *c, const char *name) -{ - return streq(libnvme_ctrl_get_name((struct libnvme_ctrl *)c), name); -} - -static bool ns_cmp(const struct libnvme_ns *n, const char *name) -{ - return streq(libnvme_ns_get_name((struct libnvme_ns *)n), name); -} - -HTABLE_DEFINE_TYPE(struct libnvme_subsystem, subsys_key, hash_string, - subsys_cmp, htable_subsys); -HTABLE_DEFINE_TYPE(struct libnvme_ctrl, ctrl_key, hash_string, - ctrl_cmp, htable_ctrl); -HTABLE_DEFINE_TYPE(struct libnvme_ns, ns_key, hash_string, - ns_cmp, htable_ns); - -static void htable_ctrl_add_unique(struct htable_ctrl *ht, struct libnvme_ctrl *c) -{ - if (htable_ctrl_get(ht, libnvme_ctrl_get_name(c))) - return; - - htable_ctrl_add(ht, c); -} - -static void htable_ns_add_unique(struct htable_ns *ht, struct libnvme_ns *n) -{ - struct htable_ns_iter it; - struct libnvme_ns *_n; - - /* - * Test if namespace pointer is already in the hash, and thus avoid - * inserting severaltimes the same pointer. - */ - for (_n = htable_ns_getfirst(ht, libnvme_ns_get_name(n), &it); - _n; - _n = htable_ns_getnext(ht, libnvme_ns_get_name(n), &it)) { - if (_n == n) - return; - } - htable_ns_add(ht, n); -} - -/* - * Device names share a common textual prefix (e.g. "nvme", "nvme0n") - * followed by an integer index, so a plain byte-wise comparison would - * order "nvme10" before "nvme2". Walk both strings together and, - * whenever a run of digits begins in both, compare the runs by - * numeric value; otherwise fall back to byte comparison. - */ -static int name_natcmp(const char *sa, const char *sb) -{ - while (*sa && *sb) { - if (isdigit((unsigned char)*sa) && isdigit((unsigned char)*sb)) { - char *enda, *endb; - unsigned long va = strtoul(sa, &enda, 10); - unsigned long vb = strtoul(sb, &endb, 10); - - if (va != vb) - return va < vb ? -1 : 1; - - sa = enda; - sb = endb; - continue; - } - - if (*sa != *sb) - return (unsigned char)*sa - (unsigned char)*sb; - - sa++; - sb++; - } - - return (unsigned char)*sa - (unsigned char)*sb; -} - -static int name_natcmp_qsort(const void *a, const void *b) -{ - return name_natcmp(*(const char * const *)a, *(const char * const *)b); -} - -struct name_collector { - const char **names; - size_t count; - size_t capacity; -}; - -static bool name_collect(const char *name, void *arg) -{ - struct name_collector *nc = arg; - - if (nc->count == nc->capacity) { - const char **tmp; - - nc->capacity = nc->capacity ? nc->capacity * 2 : 16; - tmp = realloc(nc->names, nc->capacity * sizeof(*nc->names)); - if (!tmp) - return false; - nc->names = tmp; - } - - nc->names[nc->count++] = name; - - return true; -} - -/* - * Like strset_iterate(), but visits members in natural (numeric-aware) - * order instead of the strset's underlying byte-lexicographic trie - * order, so e.g. "nvme2" sorts before "nvme10". - */ -#define strset_iterate_sorted(set, handle, arg) \ - strset_iterate_sorted_((set), typesafe_cb_preargs(bool, void *, \ - (handle), (arg), \ - const char *), \ - (arg)) - -static void strset_iterate_sorted_(const struct strset *set, - bool (*handle)(const char *, void *), - const void *data) -{ - struct name_collector nc = { 0 }; - size_t i; - - strset_iterate_(set, name_collect, &nc); - qsort(nc.names, nc.count, sizeof(*nc.names), name_natcmp_qsort); - - for (i = 0; i < nc.count; i++) { - if (!handle(nc.names[i], (void *)data)) - break; - } - - free(nc.names); -} - -struct nvme_resources { - struct libnvme_global_ctx *ctx; - - struct htable_subsys ht_s; - struct htable_ctrl ht_c; - struct htable_ns ht_n; - struct strset subsystems; - struct strset ctrls; - struct strset namespaces; -}; - -struct nvme_resources_table { - struct nvme_resources *res; - struct shr_table *t; -}; - -static int nvme_resources_init(struct libnvme_global_ctx *ctx, struct nvme_resources *res) -{ - struct libnvme_host *h; - struct libnvme_subsystem *s; - struct libnvme_ctrl *c; - struct libnvme_ns *n; - struct libnvme_path *p; - - res->ctx = ctx; - htable_subsys_init(&res->ht_s); - htable_ctrl_init(&res->ht_c); - htable_ns_init(&res->ht_n); - strset_init(&res->subsystems); - strset_init(&res->ctrls); - strset_init(&res->namespaces); - - libnvme_for_each_host(ctx, h) { - libnvme_for_each_subsystem(h, s) { - htable_subsys_add(&res->ht_s, s); - strset_add(&res->subsystems, libnvme_subsystem_get_name(s)); - - libnvme_subsystem_for_each_ctrl(s, c) { - htable_ctrl_add_unique(&res->ht_c, c); - strset_add(&res->ctrls, libnvme_ctrl_get_name(c)); - - libnvme_ctrl_for_each_ns(c, n) { - htable_ns_add_unique(&res->ht_n, n); - strset_add(&res->namespaces, libnvme_ns_get_name(n)); - } - - libnvme_ctrl_for_each_path(c, p) { - n = libnvme_path_get_ns(p); - if (n) { - htable_ns_add_unique(&res->ht_n, n); - strset_add(&res->namespaces, libnvme_ns_get_name(n)); - } - } - } - - libnvme_subsystem_for_each_ns(s, n) { - htable_ns_add_unique(&res->ht_n, n); - strset_add(&res->namespaces, libnvme_ns_get_name(n)); - } - } - } - - return 0; -} - -static void nvme_resources_free(struct nvme_resources *res) -{ - strset_clear(&res->namespaces); - strset_clear(&res->ctrls); - strset_clear(&res->subsystems); - htable_ns_clear(&res->ht_n); - htable_ctrl_clear(&res->ht_c); - htable_subsys_clear(&res->ht_s); -} - static void stdout_kv_render(FILE *stream, struct shr_table *t); -static unsigned int stdout_subsystem_multipath(struct libnvme_subsystem *s) -{ - struct libnvme_ns *n; - struct libnvme_path *p; - unsigned int i = 0; - - n = libnvme_subsystem_first_ns(s); - if (!n) - return 0; - - libnvme_namespace_for_each_path(n, p) { - struct libnvme_ctrl *c = libnvme_path_get_ctrl(p); - const char *ana_state; - - libnvme_path_get_ana_state(p, &ana_state, ""); - - printf(" +- %s %s %s %s %s\n", - libnvme_ctrl_get_name(c), - libnvme_ctrl_get_transport(c), - libnvme_ctrl_get_traddr(c), - libnvme_ctrl_get_state(c), - ana_state); - i++; - } - - return i; -} - -static void stdout_subsystem_ctrls(struct libnvme_subsystem *s) -{ - struct libnvme_ctrl *c; - - libnvme_subsystem_for_each_ctrl(s, c) { - printf(" +- %s %s %s %s\n", - libnvme_ctrl_get_name(c), - libnvme_ctrl_get_transport(c), - libnvme_ctrl_get_traddr(c), - libnvme_ctrl_get_state(c)); - } -} - -static void stdout_subsys_config(struct libnvme_subsystem *s, - bool show_iopolicy) -{ - int len = strlen(libnvme_subsystem_get_name(s)); - - printf("%s - NQN=%s\n", libnvme_subsystem_get_name(s), - libnvme_subsystem_get_subsysnqn(s)); - printf("%*s hostnqn=%s\n", len, " ", - libnvme_host_get_hostnqn(libnvme_subsystem_get_host(s))); - if (show_iopolicy) { - const char *iopolicy; - - libnvme_subsystem_get_iopolicy(s, &iopolicy, ""); - printf("%*s iopolicy=%s\n", len, " ", iopolicy); - } - - if (stdout_print_ops.flags & VERBOSE) { - const char *model; - const char *serial; - const char *firmware; - - libnvme_subsystem_get_model(s, &model, "undefined"); - libnvme_subsystem_get_serial(s, &serial, ""); - libnvme_subsystem_get_firmware(s, &firmware, ""); - - printf("%*s model=%s\n", len, " ", model); - printf("%*s serial=%s\n", len, " ", serial); - printf("%*s firmware=%s\n", len, " ", firmware); - printf("%*s type=%s\n", len, " ", - libnvme_subsystem_get_subsystype(s)); - } -} - -static void stdout_subsystem(struct libnvme_global_ctx *ctx, bool show_ana) -{ - struct libnvme_host *h; - bool first = true; - - libnvme_for_each_host(ctx, h) { - struct libnvme_subsystem *s; - - libnvme_for_each_subsystem(h, s) { - bool no_ctrl = true; - struct libnvme_ctrl *c; - - libnvme_subsystem_for_each_ctrl(s, c) - no_ctrl = false; - if (no_ctrl) - continue; - - if (!first) - printf("\n"); - first = false; - - stdout_subsys_config(s, - stdout_print_ops.flags & VERBOSE); - printf("\\\n"); - - if (!show_ana || !stdout_subsystem_multipath(s)) - stdout_subsystem_ctrls(s); - } - } -} - -static void stdout_subsystem_list(struct libnvme_global_ctx *ctx, bool show_ana) -{ - stdout_subsystem(ctx, show_ana); -} - /* * Shared by stdout_kv_add() and stdout_prop_cap_add(): adds one row (name, * ':', the vasprintf()'d value) to @t and returns its row id. The ':' is its @@ -577,64 +213,6 @@ void stdout_kv_table_finish(struct shr_table *t, const char *what) shr_table_free(t); } -/* - * The "field : value" table of the fields @fields of @value, decoded: the - * subtable of a row with the value itself. - */ -struct shr_table *stdout_bitfields_table(const struct bitfield *fields, - unsigned int nr, uint64_t value) -{ - struct shr_table *t; - char buf[128]; - unsigned int i; - - t = stdout_kv_table_create(); - if (!t) - return NULL; - - for (i = 0; i < nr; i++) { - bitfield_str(&fields[i], value, buf, sizeof(buf)); - stdout_kv_add(t, fields[i].name, "%s", buf); - } - - return t; -} - -static void stdout_ctrl_registers(const struct nvme_reg_val *vals, - unsigned int nr, enum nvme_regs_style style) -{ - bool verbose = !!(stdout_print_ops.flags & VERBOSE); - struct shr_table *t; - unsigned int i; - int row; - - t = stdout_kv_table_create(); - if (!t) - return; - - for (i = 0; i < nr; i++) { - const struct nvme_reg *reg = vals[i].reg; - uint64_t value = vals[i].value; - - if (style == NVME_REGS_TABLE) - row = stdout_kv_add(t, reg->sym, "%#"PRIx64, value); - else if (verbose) - row = stdout_kv_add(t, reg->name, "%#"PRIx64, value); - else - row = stdout_kv_add(t, - style == NVME_REGS_PROPERTY ? "property" : - "register", - "%#04x (%s), value: %#"PRIx64, reg->offset, - reg->name, value); - if (verbose && reg->nr_fields) - shr_table_set_row_subtable(t, row, - stdout_bitfields_table(reg->fields, - reg->nr_fields, value)); - } - - stdout_kv_table_finish(t, "registers"); -} - /* The status line, which may follow other text */ static void stdout_status_line(int status) { @@ -728,181 +306,6 @@ char *stdout_power_and_scale_str(__u16 power, __u8 scale) return s; } -static void stdout_resv_report(struct nvme_resv_status *status, int bytes, - bool eds) -{ - struct shr_table *t; - int i, regstrnt, entries; - char hex[33]; - - regstrnt = status->regstrnt[0] | (status->regstrnt[1] << 8); - - printf("\nNVME Reservation status:\n\n"); - - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, "gen", "%u", le32_to_cpu(status->gen)); - stdout_kv_add(t, "rtype", "%d", status->rtype); - stdout_kv_add(t, "regstrnt", "%d", regstrnt); - stdout_kv_add(t, "ptpls", "%d", status->ptpls); - - stdout_kv_table_finish(t, "resv-report"); - - /* check Extended Data Structure bit */ - if (!eds) { - /* - * if status buffer was too small, don't loop past the end of - * the buffer - */ - entries = (bytes - 24) / 24; - if (entries < regstrnt) - regstrnt = entries; - - for (i = 0; i < regstrnt; i++) { - struct nvme_registrant *reg = &status->registrant_ds[i]; - - printf("registrant[%d] :\n", i); - - t = stdout_kv_table_create(); - if (!t) - return; - shr_table_set_indent(t, 2); - - stdout_kv_add(t, "cntlid", "%x", - le16_to_cpu(reg->cntlid)); - stdout_kv_add(t, "rcsts", "%x", reg->rcsts); - stdout_kv_add(t, "hostid", "%"PRIx64, - le64_to_cpu(reg->hostid)); - stdout_kv_add(t, "rkey", "%"PRIx64, - le64_to_cpu(reg->rkey)); - - stdout_kv_table_finish(t, "registrant"); - } - } else { - /* - * if status buffer was too small, don't loop past the end of - * the buffer - */ - entries = (bytes - 64) / 64; - if (entries < regstrnt) - regstrnt = entries; - - for (i = 0; i < regstrnt; i++) { - struct nvme_registrant_ext *reg = - &status->registrant_eds[i]; - - printf("registrantext[%d] :\n", i); - - t = stdout_kv_table_create(); - if (!t) - return; - shr_table_set_indent(t, 2); - - stdout_kv_add(t, "cntlid", "%x", - le16_to_cpu(reg->cntlid)); - stdout_kv_add(t, "rcsts", "%x", reg->rcsts); - stdout_kv_add(t, "rkey", "%"PRIx64, - le64_to_cpu(reg->rkey)); - - shr_bin_to_hex(hex, sizeof(hex), reg->hostid, - sizeof(reg->hostid), 0); - stdout_kv_add(t, "hostid", "%s", hex); - - stdout_kv_table_finish(t, "registrant"); - } - } - printf("\n"); -} - -static void stdout_select_result(enum nvme_features_id fid, __u64 result) -{ - struct shr_table *t; - - t = stdout_kv_table_create(); - if (!t) - return; - - if (result & 0x1) - stdout_kv_add(t, "", "Feature is saveable"); - if (result & 0x2) - stdout_kv_add(t, "", "Feature is per-namespace"); - if (result & 0x4) - stdout_kv_add(t, "", "Feature is changeable"); - - stdout_kv_table_finish(t, "select-result"); -} - -static void stdout_lba_range(struct nvme_lba_range_type *lbrt, int nr_ranges) -{ - int i; - - for (i = 0; i <= nr_ranges; i++) { - struct nvme_lba_range_type_entry *e = &lbrt->entry[i]; - struct shr_table *t; - char guid[2 * ARRAY_SIZE(e->guid) + 1]; - - t = stdout_kv_table_create(); - if (!t) - return; - - shr_table_set_indent(t, 1); - - stdout_kv_add(t, "type", "%#x - %s", e->type, - nvme_feature_lba_type_to_string(e->type)); - const char *overwrite_str = - NVME_LBART_ATTRB_LBARO(e->attributes) ? - "LBA range may be overwritten" : - "LBA range should not be overwritten"; - const char *hidden_str = NVME_LBART_ATTRB_HLBAR(e->attributes) ? - "LBA range should be hidden from the OS/EFI/BIOS" : - "LBA range should be visible from the OS/EFI/BIOS"; - - stdout_kv_add(t, "attributes", "%#x - %s, %s", e->attributes, - overwrite_str, hidden_str); - stdout_kv_add(t, "slba", "%#"PRIx64, le64_to_cpu(e->slba)); - stdout_kv_add(t, "nlb", "%#"PRIx64, le64_to_cpu(e->nlb)); - - shr_bin_to_hex(guid, sizeof(guid), e->guid, sizeof(e->guid), 0); - stdout_kv_add(t, "guid", "%s", guid); - - stdout_kv_table_finish(t, "lba-range"); - } -} - -static void stdout_auto_pst(struct nvme_feat_auto_pst *apst) -{ - int i; - __u64 value; - - printf("\tAuto PST Entries"); - printf("\t.................\n"); - for (i = 0; i < ARRAY_SIZE(apst->apst_entry); i++) { - struct shr_table *t; - - value = le64_to_cpu(apst->apst_entry[i]); - - printf("\tEntry[%2d]\n", i); - printf("\t.................\n"); - - t = stdout_kv_table_create(); - if (!t) - return; - - shr_table_set_indent(t, 2); - stdout_kv_add(t, "Idle Time Prior to Transition (ITPT)", - "%u ms", - (__u32)NVME_GET(value, APST_ENTRY_ITPT)); - stdout_kv_add(t, "Idle Transition Power State (ITPS)", "%u", - (__u32)NVME_GET(value, APST_ENTRY_ITPS)); - - stdout_kv_table_finish(t, "auto-pst"); - - printf("\t.................\n"); - } -} - const char *stdout_format_timestamp(__u8 *timestamp_bytes) { static char buf[STR_LEN]; @@ -914,255 +317,6 @@ const char *stdout_format_timestamp(__u8 *timestamp_bytes) return buf; } -static struct shr_table *stdout_timestamp_attr_table(__u8 attr) -{ - struct shr_table *t; - __u8 to = NVME_TIMESTAMP_ATTR_TO(attr); - __u8 sync = NVME_TIMESTAMP_ATTR_SYNC(attr); - - t = stdout_bits_table_create(); - if (!t) - return NULL; - - stdout_bits_add(t, "[3:1]", to, "%s", - nvme_format_timestamp_origin(attr)); - stdout_bits_add(t, "[0:0]", sync, "%s", - nvme_format_timestamp_sync(attr)); - - return t; -} - -static void stdout_timestamp(struct nvme_timestamp *ts) -{ - struct shr_table *t; - int row; - - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, "Timestamp", "%s", - stdout_format_timestamp(ts->timestamp)); - - row = stdout_kv_add(t, "Attributes", "%#x", ts->attr); - shr_table_set_row_subtable(t, row, - stdout_timestamp_attr_table(ts->attr)); - - stdout_kv_table_finish(t, "timestamp"); -} - -static void stdout_host_mem_buffer(struct nvme_host_mem_buf_attrs *hmb) -{ - struct shr_table *t; - - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, "Host Memory Descriptor List Entry Count (HMDLEC)", - "%u", le32_to_cpu(hmb->hmdlec)); - stdout_kv_add(t, "Host Memory Descriptor List Address (HMDLAU)", - "%#x", le32_to_cpu(hmb->hmdlau)); - stdout_kv_add(t, "Host Memory Descriptor List Address (HMDLAL)", - "%#x", le32_to_cpu(hmb->hmdlal)); - stdout_kv_add(t, "Host Memory Buffer Size (HSIZE)", "%u", - le32_to_cpu(hmb->hsize)); - - stdout_kv_table_finish(t, "host-mem-buffer"); -} - -static void stdout_directive_show_fields(__u8 dtype, __u8 doper, - unsigned int result, - unsigned char *buf, __u32 len) -{ - struct nvme_streams_directive_params *params = (void *)buf; - struct nvme_streams_directive_status *status = (void *)buf; - __u8 *field = buf; - int count, i; - struct shr_table *t; - - switch (dtype) { - case NVME_DIRECTIVE_DTYPE_IDENTIFY: - switch (doper) { - case NVME_DIRECTIVE_RECEIVE_IDENTIFY_DOPER_PARAM: - if (len < NVME_DIRECTIVE_IDENTIFY_PARAM_LEN) { - fprintf(stderr, "directive data too short\n"); - break; - } - printf("\tDirective support\n"); - - t = stdout_kv_table_create(); - if (!t) - return; - - shr_table_set_indent(t, 2); - stdout_kv_add(t, "Identify Directive", "%s", - (*field & 0x1) ? - "supported" : "not supported"); - stdout_kv_add(t, "Stream Directive", "%s", - (*field & 0x2) ? - "supported" : "not supported"); - stdout_kv_add(t, "Data Placement Directive", "%s", - (*field & 0x4) ? - "supported" : "not supported"); - - stdout_kv_table_finish(t, "directive-show"); - - printf("\tDirective enabled\n"); - - t = stdout_kv_table_create(); - if (!t) - return; - - shr_table_set_indent(t, 2); - stdout_kv_add(t, "Identify Directive", "%s", - (*(field + 32) & 0x1) ? - "enabled" : "disabled"); - stdout_kv_add(t, "Stream Directive", "%s", - (*(field + 32) & 0x2) ? - "enabled" : "disabled"); - stdout_kv_add(t, "Data Placement Directive", "%s", - (*(field + 32) & 0x4) ? - "enabled" : "disabled"); - - stdout_kv_table_finish(t, "directive-show"); - - printf("\tDirective Persistent Across Controller Level Resets\n"); - - t = stdout_kv_table_create(); - if (!t) - return; - - shr_table_set_indent(t, 2); - stdout_kv_add(t, "Identify Directive", "%s", - (*(field + 64) & 0x1) ? - "enabled" : "disabled"); - stdout_kv_add(t, "Stream Directive", "%s", - (*(field + 64) & 0x2) ? - "enabled" : "disabled"); - stdout_kv_add(t, "Data Placement Directive", "%s", - (*(field + 64) & 0x4) ? - "enabled" : "disabled"); - - stdout_kv_table_finish(t, "directive-show"); - break; - default: - fprintf(stderr, - "invalid directive operations for Identify Directives\n"); - break; - } - break; - case NVME_DIRECTIVE_DTYPE_STREAMS: - switch (doper) { - case NVME_DIRECTIVE_RECEIVE_STREAMS_DOPER_PARAM: - if (len < sizeof(*params)) { - fprintf(stderr, "directive data too short\n"); - break; - } - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, "Max Streams Limit (MSL)", "%u", - le16_to_cpu(params->msl)); - stdout_kv_add(t, - "NVM Subsystem Streams Available (NSSA)", - "%u", le16_to_cpu(params->nssa)); - stdout_kv_add(t, - "NVM Subsystem Streams Open (NSSO)", - "%u", le16_to_cpu(params->nsso)); - stdout_kv_add(t, - "NVM Subsystem Stream Capability (NSSC)", - "%u", params->nssc); - stdout_kv_add(t, - "Stream Write Size (in unit of LB size) (SWS)", - "%u", le32_to_cpu(params->sws)); - stdout_kv_add(t, - "Stream Granularity Size (in unit of SWS) (SGS)", - "%u", le16_to_cpu(params->sgs)); - stdout_kv_add(t, - "Namespace Streams Allocated (NSA)", - "%u", le16_to_cpu(params->nsa)); - stdout_kv_add(t, "Namespace Streams Open (NSO)", "%u", - le16_to_cpu(params->nso)); - - stdout_kv_table_finish(t, "directive-show"); - break; - case NVME_DIRECTIVE_RECEIVE_STREAMS_DOPER_STATUS: - if (len < sizeof(*status)) { - fprintf(stderr, "directive data too short\n"); - break; - } - count = nvme_streams_status_nr_sid(status, len); - - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, "Open Stream Count", "%u", - le16_to_cpu(status->osc)); - for (i = 0; i < count; i++) { - char name[32]; - - snprintf(name, sizeof(name), - "Stream Identifier %.6u", i + 1); - stdout_kv_add(t, name, "%u", - le16_to_cpu(status->sid[i])); - } - - stdout_kv_table_finish(t, "directive-show"); - break; - case NVME_DIRECTIVE_RECEIVE_STREAMS_DOPER_RESOURCE: - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, "Namespace Streams Allocated (NSA)", - "%u", result & 0xffff); - - stdout_kv_table_finish(t, "directive-show"); - break; - default: - fprintf(stderr, - "invalid directive operations for Streams Directives\n"); - break; - } - break; - default: - fprintf(stderr, "invalid directive type\n"); - break; - } -} - -static void stdout_directive_show(__u8 type, __u8 oper, __u16 spec, __u32 nsid, __u64 result, - void *buf, __u32 len) -{ - printf("dir-receive: type:%#x operation:%#x spec:%#x nsid:%#x result:%#"PRIx64"\n", - type, oper, spec, nsid, (uint64_t)result); - if (stdout_print_ops.flags & VERBOSE) - stdout_directive_show_fields(type, oper, result, buf, len); - else if (buf) - d(buf, len, 16, 1); -} - -static void stdout_lba_status_info(__u64 result) -{ - struct shr_table *t; - - t = stdout_kv_table_create(); - if (!t) - return; - - shr_table_set_indent(t, 1); - - stdout_kv_add(t, "LBA Status Information Poll Interval (LSIPI)", - "%u", (__u32)NVME_FEAT_LBAS_LSIPI(result)); - stdout_kv_add(t, "LBA Status Information Report Interval (LSIRI)", - "%u", (__u32)NVME_FEAT_LBAS_LSIRI(result)); - - stdout_kv_table_finish(t, "lba-status-info"); -} - static bool line_equal(unsigned char *buf, int len, int width, int offset) { if (!offset || len < offset + width || @@ -1224,1848 +378,11 @@ void stdout_d(unsigned char *buf, int len, int width, int group) printf("\n"); } -static void stdout_plm_config(struct nvme_plm_config *plmcfg) +static void stdout_message(bool error, const char *msg, va_list ap) { - struct shr_table *t; - - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, "Enable Event", "%04x", le16_to_cpu(plmcfg->ee)); - stdout_kv_add(t, "DTWIN Reads Threshold", "%"PRIu64, - le64_to_cpu(plmcfg->dtwinrt)); - stdout_kv_add(t, "DTWIN Writes Threshold", "%"PRIu64, - le64_to_cpu(plmcfg->dtwinwt)); - stdout_kv_add(t, "DTWIN Time Threshold", "%"PRIu64, - le64_to_cpu(plmcfg->dtwintt)); - - stdout_kv_table_finish(t, "plm-config"); -} - -static void stdout_rate_limiting_data(struct nvme_rate_limiting_data *rld) -{ - __u16 rlc = le16_to_cpu(rld->rlc); - __u16 rlm = NVME_RATE_LIMITING_RLC_RLM(rlc); - struct shr_table *t; - - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, "Rate Limiting Enable (RLE)", "%s", - NVME_RATE_LIMITING_RLC_RLE(rlc) ? "Enabled" : "Disabled"); - stdout_kv_add(t, "Rate Limiting Mode (RLM)", "%u - %s", rlm, - rlm == NVME_RATE_LIMITING_MODE_SOFT_LIMIT ? "Soft Limit" : - rlm == NVME_RATE_LIMITING_MODE_HARD_LIMIT ? - "Hard Limit" : "Reserved"); - stdout_kv_add(t, "Bandwidth Scale Factor (BWSF)", "%u", rld->bwsf); - stdout_kv_add(t, "Total Bandwidth Value (TBWV)", "%"PRIu64, - le64_to_cpu(rld->tbwv)); - stdout_kv_add(t, "Write Bandwidth Value (WBWV)", "%"PRIu64, - le64_to_cpu(rld->wbwv)); - stdout_kv_add(t, "Total IOPS (TIOPS)", "%u", le32_to_cpu(rld->tiops)); - stdout_kv_add(t, "Write IOPS (WIOPS)", "%u", le32_to_cpu(rld->wiops)); - stdout_kv_add(t, "Read IOPS Ratio (RIOPSR)", "%u", rld->riopsr); - stdout_kv_add(t, "Write IOPS Ratio (WIOPSR)", "%u", rld->wiopsr); - stdout_kv_add(t, "Read Bandwidth Ratio (RBWR)", "%u", rld->rbwr); - stdout_kv_add(t, "Write Bandwidth Ratio (WBWR)", "%u", rld->wbwr); - - stdout_kv_table_finish(t, "rate-limiting-data"); -} - -static void stdout_feat_perfc_std(struct nvme_std_perf_attr *data) -{ - struct shr_table *t; - - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, "random 4 kib average read latency (R4KARL)", - "%s (0x%02x)", - nvme_feature_perfc_r4karl_to_string(data->r4karl), - data->r4karl); - - stdout_kv_table_finish(t, "feat-perfc-std"); -} - -static void stdout_feat_perfc_id_list(struct nvme_perf_attr_id_list *data) -{ - int i; - int attri_vs; - struct shr_table *t; - - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, "attribute type (ATTRTYP)", "%s (0x%02x)", - nvme_feature_perfc_attrtyp_to_string(data->attrtyp), - data->attrtyp); - stdout_kv_add(t, - "maximum saveable vendor specific performance attributes (MSVSPA)", - "%d", data->msvspa); - stdout_kv_add(t, - "unused saveable vendor specific performance attributes (USVSPA)", - "%d", data->usvspa); - - stdout_kv_table_finish(t, "feat-perfc-id-list"); - - printf("performance attribute identifier list\n"); - - t = stdout_kv_table_create(); - if (!t) - return; - - for (i = 0; i < ARRAY_SIZE(data->id_list); i++) { - char name[48]; - - attri_vs = i + NVME_FEAT_PERFC_ATTRI_VS_MIN; - snprintf(name, sizeof(name), - "performance attribute %02xh identifier (PA%02XHI)", - attri_vs, attri_vs); - stdout_kv_add(t, name, "%s", - shr_uuid_to_string(data->id_list[i].id)); - } - - stdout_kv_table_finish(t, "feat-perfc-id-list"); -} - -static void stdout_feat_perfc_vs(struct nvme_vs_perf_attr *data) -{ - __u16 attrl = le16_to_cpu(data->attrl); - struct shr_table *t; - - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, "performance attribute identifier (PAID)", "%s", - shr_uuid_to_string(data->paid)); - stdout_kv_add(t, "attribute length (ATTRL)", "%u", attrl); - - stdout_kv_table_finish(t, "feat-perfc-vs"); - - printf("vendor specific (VS):\n"); - d((unsigned char *)data->vs, - min_t(size_t, attrl, sizeof(data->vs)), 16, 1); -} - -static void stdout_feat_perfc(unsigned int result, - struct nvme_perf_characteristics *data) -{ - __u8 attri; - bool rvspa; - struct shr_table *t; - - nvme_feature_decode_perf_characteristics(result, &attri, &rvspa); - - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, "attribute index (ATTRI)", "%s (0x%02x)", - nvme_feature_perfc_attri_to_string(attri), attri); - - stdout_kv_table_finish(t, "feat-perfc"); - - switch (attri) { - case NVME_FEAT_PERFC_ATTRI_STD: - stdout_feat_perfc_std(data->std_perf); - break; - case NVME_FEAT_PERFC_ATTRI_ID_LIST: - stdout_feat_perfc_id_list(data->id_list); - break; - case NVME_FEAT_PERFC_ATTRI_VS_MIN ... NVME_FEAT_PERFC_ATTRI_VS_MAX: - stdout_feat_perfc_vs(data->vs_perf); - break; - default: - break; - } -} - -static void stdout_host_metadata(enum nvme_features_id fid, - struct nvme_host_metadata *data) -{ - struct nvme_metadata_element_desc desc; - const __u8 *val; - size_t off = 0; - int i; - __u16 len; - struct shr_table *t; - - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, "Num Metadata Element Descriptors", "%d", data->ndesc); - - stdout_kv_table_finish(t, "host-metadata"); - - for (i = 0; i < data->ndesc; i++) { - val = nvme_host_metadata_element(data, &off, &desc, &len); - if (!val) - break; - - printf("\tElement[%-3d]:\n", i); - - t = stdout_kv_table_create(); - if (!t) - return; - - shr_table_set_indent(t, 2); - stdout_kv_add(t, "Type", "%#02x (%s)", desc.type, - nvme_host_metadata_type_to_string(fid, - desc.type)); - stdout_kv_add(t, "Revision", "%d", desc.rev); - stdout_kv_add(t, "Length", "%d", le16_to_cpu(desc.len)); - stdout_kv_add(t, "Value", "%.*s", len, (const char *)val); - - stdout_kv_table_finish(t, "host-metadata"); - } -} - -static void stdout_feat_host_id(unsigned int result, unsigned char *hostid) -{ - bool exhid; - struct shr_table *t; - - if (!hostid) - return; - - nvme_feature_decode_host_id(result, &exhid); - - t = stdout_kv_table_create(); - if (!t) - return; - - if (exhid) - stdout_kv_add(t, "Host Identifier (HOSTID)", "%s", - uint128_t_to_l10n_string(le128_to_cpu(hostid))); - else - stdout_kv_add(t, "Host Identifier (HOSTID)", "%"PRIu64, - le64_to_cpu(*(__le64 *)hostid)); - - stdout_kv_table_finish(t, "feat-host-id"); -} - -static void stdout_feature_show(enum nvme_features_id fid, int sel, - unsigned int result, void *buf, __u32 data_len) -{ - printf("get-feature:%#0*x (%s), %s value:%#0*x\n", fid ? 4 : 2, fid, - nvme_feature_to_string(fid), nvme_select_to_string(sel), result ? 10 : 8, result); - - if (NVME_CHECK(sel, GET_FEATURES_SEL, SUPPORTED)) - stdout_select_result(fid, result); - else if (stdout_print_ops.flags & VERBOSE) - stdout_feature_show_fields(fid, result, buf); - else if (buf) - d(buf, data_len, 16, 1); -} - -void stdout_feature_show_fields(enum nvme_features_id fid, unsigned int result, - unsigned char *buf) -{ - const char *async = "Send async event"; - const char *no_async = "Do not send async event"; - struct shr_table *t; - __u16 field; - - switch (fid) { - case NVME_FEAT_FID_ARBITRATION: - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, "High Priority Weight (HPW)", "%u", - NVME_FEAT_ARB_HPW(result) + 1); - stdout_kv_add(t, "Medium Priority Weight (MPW)", "%u", - NVME_FEAT_ARB_MPW(result) + 1); - stdout_kv_add(t, "Low Priority Weight (LPW)", "%u", - NVME_FEAT_ARB_LPW(result) + 1); - if (NVME_FEAT_ARB_BURST(result) == NVME_FEAT_ARBITRATION_BURST_MASK) - stdout_kv_add(t, "Arbitration Burst (AB)", "No limit"); - else - stdout_kv_add(t, "Arbitration Burst (AB)", "%u", - 1 << NVME_FEAT_ARB_BURST(result)); - - stdout_kv_table_finish(t, "feature-show-fields"); - break; - case NVME_FEAT_FID_POWER_MGMT: - t = stdout_kv_table_create(); - if (!t) - return; - - field = NVME_FEAT_PM_WH(result); - stdout_kv_add(t, "Workload Hint (WH)", "%u - %s", field, - nvme_feature_wl_hints_to_string(field)); - stdout_kv_add(t, "Power State (PS)", "%u", - NVME_FEAT_PM_PS(result)); - field = NVME_FEAT_PM_IIELL(result); - if (field) - stdout_kv_add(t, "Idle I/O Exit Latency Limit (IIELL)", - "%uus", field * 100); - else - stdout_kv_add(t, "Idle I/O Exit Latency Limit (IIELL)", - "disabled"); - - stdout_kv_table_finish(t, "feature-show-fields"); - break; - case NVME_FEAT_FID_LBA_RANGE: - field = NVME_FEAT_LBAR_NR(result); - - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, "Number of LBA Ranges (NUM)", "%u", field + 1); - - stdout_kv_table_finish(t, "feature-show-fields"); - - if (buf) - stdout_lba_range((struct nvme_lba_range_type *)buf, field); - break; - case NVME_FEAT_FID_TEMP_THRESH: - t = stdout_kv_table_create(); - if (!t) - return; - - field = NVME_FEAT_TT_TMPTHH(result); - stdout_kv_add(t, "Temperature Threshold Hysteresis (TMPTHH)", - "%s (%u K, %s)", nvme_degrees_string(field), - field, nvme_degrees_fahrenheit_string(field)); - field = NVME_FEAT_TT_THSEL(result); - stdout_kv_add(t, "Threshold Type Select (THSEL)", "%u - %s", - field, nvme_feature_temp_type_to_string(field)); - field = NVME_FEAT_TT_TMPSEL(result); - stdout_kv_add(t, "Threshold Temperature Select (TMPSEL)", - "%u - %s", field, - nvme_feature_temp_sel_to_string(field)); - field = NVME_FEAT_TT_TMPTH(result); - stdout_kv_add(t, "Temperature Threshold (TMPTH)", - "%s (%u K, %s)", - nvme_degrees_string(field), field, - nvme_degrees_fahrenheit_string(field)); - - stdout_kv_table_finish(t, "feature-show-fields"); - break; - case NVME_FEAT_FID_ERR_RECOVERY: - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, - "Deallocated or Unwritten Logical Block Error Enable (DULBE)", - "%s", - NVME_FEAT_ER_DULBE(result) ? - "Enabled" : "Disabled"); - stdout_kv_add(t, "Time Limited Error Recovery (TLER)", "%u ms", - NVME_FEAT_ER_TLER(result) * 100); - - stdout_kv_table_finish(t, "feature-show-fields"); - break; - case NVME_FEAT_FID_VOLATILE_WC: - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, "Volatile Write Cache Enable (WCE)", "%s", - NVME_FEAT_VWC_WCE(result) ? - "Enabled" : "Disabled"); - - stdout_kv_table_finish(t, "feature-show-fields"); - break; - case NVME_FEAT_FID_NUM_QUEUES: - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, - "Number of IO Completion Queues Allocated (NCQA)", - "%u", NVME_FEAT_NRQS_NCQR(result) + 1); - stdout_kv_add(t, - "Number of IO Submission Queues Allocated (NSQA)", - "%u", NVME_FEAT_NRQS_NSQR(result) + 1); - - stdout_kv_table_finish(t, "feature-show-fields"); - break; - case NVME_FEAT_FID_IRQ_COALESCE: - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, "Aggregation Time (TIME)", "%u usec", - NVME_FEAT_IRQC_TIME(result) * 100); - stdout_kv_add(t, "Aggregation Threshold (THR)", "%u", - NVME_FEAT_IRQC_THR(result) + 1); - - stdout_kv_table_finish(t, "feature-show-fields"); - break; - case NVME_FEAT_FID_IRQ_CONFIG: - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, "Coalescing Disable (CD)", "%s", - NVME_FEAT_ICFG_CD(result) ? "True" : "False"); - stdout_kv_add(t, "Interrupt Vector (IV)", "%u", - NVME_FEAT_ICFG_IV(result)); - - stdout_kv_table_finish(t, "feature-show-fields"); - break; - case NVME_FEAT_FID_WRITE_ATOMIC: - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, "Disable Normal (DN)", "%s", - NVME_FEAT_WA_DN(result) ? "True" : "False"); - - stdout_kv_table_finish(t, "feature-show-fields"); - break; - case NVME_FEAT_FID_ASYNC_EVENT: - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, feat_ae_dlpcn, "%s", - NVME_FEAT_AE_DLPCN(result) ? async : no_async); - stdout_kv_add(t, feat_ae_hdlpcn, "%s", - NVME_FEAT_AE_HDLPCN(result) ? async : no_async); - stdout_kv_add(t, feat_ae_adlpcn, "%s", - NVME_FEAT_AE_ADLPCN(result) ? async : no_async); - stdout_kv_add(t, feat_ae_pmdrlpcn, "%s", - NVME_FEAT_AE_PMDRLPCN(result) ? async : no_async); - stdout_kv_add(t, feat_ae_zdcn, "%s", - NVME_FEAT_AE_ZDCN(result) ? async : no_async); - stdout_kv_add(t, feat_ae_rlccn, "%s", - NVME_FEAT_AE_RLCCN(result) ? async : no_async); - stdout_kv_add(t, feat_ae_lhcn, "%s", - NVME_FEAT_AE_LHCN(result) ? async : no_async); - stdout_kv_add(t, feat_ae_ccrcn, "%s", - NVME_FEAT_AE_CCRCN(result) ? async : no_async); - stdout_kv_add(t, feat_ae_ansan, "%s", - NVME_FEAT_AE_ANSAN(result) ? async : no_async); - stdout_kv_add(t, feat_ae_rgrp0, "%s", - NVME_FEAT_AE_RGRP0(result) ? async : no_async); - stdout_kv_add(t, feat_ae_rassn, "%s", - NVME_FEAT_AE_RASSN(result) ? async : no_async); - stdout_kv_add(t, feat_ae_tthry, "%s", - NVME_FEAT_AE_TTHRY(result) ? async : no_async); - stdout_kv_add(t, feat_ae_nnsshdn, "%s", - NVME_FEAT_AE_NNSSHDN(result) ? async : no_async); - stdout_kv_add(t, feat_ae_ega, "%s", - NVME_FEAT_AE_EGA(result) ? async : no_async); - stdout_kv_add(t, feat_ae_lbas, "%s", - NVME_FEAT_AE_LBAS(result) ? async : no_async); - stdout_kv_add(t, feat_ae_pla, "%s", - NVME_FEAT_AE_PLA(result) ? async : no_async); - stdout_kv_add(t, feat_ae_ana, "%s", - NVME_FEAT_AE_ANA(result) ? async : no_async); - stdout_kv_add(t, feat_ae_telem, "%s", - NVME_FEAT_AE_TELEM(result) ? async : no_async); - stdout_kv_add(t, feat_ae_fw, "%s", - NVME_FEAT_AE_FW(result) ? async : no_async); - stdout_kv_add(t, feat_ae_nan, "%s", - NVME_FEAT_AE_NAN(result) ? async : no_async); - stdout_kv_add(t, feat_ae_smart, "%s", - NVME_FEAT_AE_SMART(result) ? async : no_async); - - stdout_kv_table_finish(t, "feature-show-fields"); - break; - case NVME_FEAT_FID_AUTO_PST: - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, - "Autonomous Power State Transition Enable (APSTE)", - "%s", - NVME_FEAT_APST_APSTE(result) ? - "Enabled" : "Disabled"); - - stdout_kv_table_finish(t, "feature-show-fields"); - - if (buf) - stdout_auto_pst((struct nvme_feat_auto_pst *)buf); - break; - case NVME_FEAT_FID_HOST_MEM_BUF: - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, "Enable Host Memory (EHM)", "%s", - NVME_FEAT_HMEM_EHM(result) ? - "Enabled" : "Disabled"); - stdout_kv_add(t, - "Host Memory Non-operational Access Restriction Enable (HMNARE)", - "%s", (result & 0x00000004) ? "True" : "False"); - stdout_kv_add(t, - "Host Memory Non-operational Access Restricted (HMNAR)", - "%s", (result & 0x00000008) ? "True" : "False"); - - stdout_kv_table_finish(t, "feature-show-fields"); - - if (buf) - stdout_host_mem_buffer((struct nvme_host_mem_buf_attrs *)buf); - break; - case NVME_FEAT_FID_TIMESTAMP: - if (buf) - stdout_timestamp((struct nvme_timestamp *)buf); - break; - case NVME_FEAT_FID_KATO: - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, "Keep Alive Timeout (KATO) in milliseconds", - "%u", result); - - stdout_kv_table_finish(t, "feature-show-fields"); - break; - case NVME_FEAT_FID_HCTM: - t = stdout_kv_table_create(); - if (!t) - return; - - field = NVME_FEAT_HCTM_TMT1(result); - stdout_kv_add(t, "Thermal Management Temperature 1 (TMT1)", - "%u K (%s, %s)", field, - nvme_degrees_string(field), - nvme_degrees_fahrenheit_string(field)); - field = NVME_FEAT_HCTM_TMT2(result); - stdout_kv_add(t, "Thermal Management Temperature 2 (TMT2)", - "%u K (%s, %s)", field, - nvme_degrees_string(field), - nvme_degrees_fahrenheit_string(field)); - - stdout_kv_table_finish(t, "feature-show-fields"); - break; - case NVME_FEAT_FID_NOPSC: - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, - "Non-Operational Power State Permissive Mode Enable (NOPPME)", - "%s", - NVME_FEAT_NOPS_NOPPME(result) ? "True" : "False"); - - stdout_kv_table_finish(t, "feature-show-fields"); - break; - case NVME_FEAT_FID_RRL: - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, "Read Recovery Level (RRL)", "%u", - NVME_FEAT_RRL_RRL(result)); - - stdout_kv_table_finish(t, "feature-show-fields"); - break; - case NVME_FEAT_FID_PLM_CONFIG: - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, "Predictable Latency Window Enabled", "%s", - NVME_FEAT_PLM_LPE(result) ? "True" : "False"); - - stdout_kv_table_finish(t, "feature-show-fields"); - - if (buf) - stdout_plm_config((struct nvme_plm_config *)buf); - break; - case NVME_FEAT_FID_PLM_WINDOW: - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, "Window Select", "%s", - nvme_plm_window_to_string(result)); - - stdout_kv_table_finish(t, "feature-show-fields"); - break; - case NVME_FEAT_FID_LBA_STS_INTERVAL: - stdout_lba_status_info(result); - break; - case NVME_FEAT_FID_HOST_BEHAVIOR: - if (buf) { - struct nvme_feat_host_behavior *hb = - (struct nvme_feat_host_behavior *)buf; - - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, "Advanced Command Retry Enable (ACRE)", - "%s", hb->acre ? "True" : "False"); - stdout_kv_add(t, - "Extended Telemetry Data Area 4 Supported (ETDAS)", - "%s", hb->etdas ? "True" : "False"); - stdout_kv_add(t, "LBA Format Extension Enable (LBAFEE)", - "%s", hb->lbafee ? "True" : "False"); - stdout_kv_add(t, - "Host Dispersed Namespace Support (HDISNS)", - "%s", - hb->hdisns ? "Enabled" : "Disabled"); - stdout_kv_add(t, - "Copy Descriptor Format 2h Enabled (CDF2E)", - "%s", - hb->cdfe & (1 << 2) ? "True" : "False"); - stdout_kv_add(t, - "Copy Descriptor Format 3h Enabled (CDF3E)", - "%s", - hb->cdfe & (1 << 3) ? "True" : "False"); - stdout_kv_add(t, - "Copy Descriptor Format 4h Enabled (CDF4E)", - "%s", - hb->cdfe & (1 << 4) ? "True" : "False"); - - stdout_kv_table_finish(t, "feature-show-fields"); - } - break; - case NVME_FEAT_FID_SANITIZE: - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, "No-Deallocate Response Mode (NODRM)", "%u", - NVME_FEAT_SC_NODRM(result)); - - stdout_kv_table_finish(t, "feature-show-fields"); - break; - case NVME_FEAT_FID_ENDURANCE_EVT_CFG: - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, "Endurance Group Identifier (ENDGID)", "%u", - NVME_FEAT_EG_ENDGID(result)); - stdout_kv_add(t, "Endurance Group Critical Warnings", "%u", - NVME_FEAT_EG_EGCW(result)); - - stdout_kv_table_finish(t, "feature-show-fields"); - break; - case NVME_FEAT_FID_IOCS_PROFILE: - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, "I/O Command Set Profile", "%s", - result & 0x1 ? "True" : "False"); - - stdout_kv_table_finish(t, "feature-show-fields"); - break; - case NVME_FEAT_FID_SPINUP_CONTROL: - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, "Spinup control feature Enabled", "%s", - (result & 1) ? "True" : "False"); - - stdout_kv_table_finish(t, "feature-show-fields"); - break; - case NVME_FEAT_FID_POWER_LOSS_SIGNAL: - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, "Power Loss Signaling Mode (PLSM)", "%s", - nvme_pls_mode_to_string( - NVME_GET(result, FEAT_PLS_MODE))); - - stdout_kv_table_finish(t, "feature-show-fields"); - break; - case NVME_FEAT_FID_PERF_CHARACTERISTICS: - stdout_feat_perfc(result, - (struct nvme_perf_characteristics *)buf); - break; - case NVME_FEAT_FID_ENH_CTRL_METADATA: - case NVME_FEAT_FID_CTRL_METADATA: - case NVME_FEAT_FID_NS_METADATA: - if (buf) - stdout_host_metadata(fid, (struct nvme_host_metadata *)buf); - break; - case NVME_FEAT_FID_SW_PROGRESS: - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, "Pre-boot Software Load Count (PBSLC)", "%u", - NVME_FEAT_SPM_PBSLC(result)); - - stdout_kv_table_finish(t, "feature-show-fields"); - break; - case NVME_FEAT_FID_HOST_ID: - stdout_feat_host_id(result, buf); - break; - case NVME_FEAT_FID_RESV_NF_MASK: - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, - "Mask Reservation Preempted Notification (RESPRE)", - "%s", - NVME_FEAT_RM_RESPRE(result) ? "True" : "False"); - stdout_kv_add(t, - "Mask Reservation Released Notification (RESREL)", - "%s", - NVME_FEAT_RM_RESREL(result) ? "True" : "False"); - stdout_kv_add(t, - "Mask Registration Preempted Notification (REGPRE)", - "%s", - NVME_FEAT_RM_REGPRE(result) ? "True" : "False"); - - stdout_kv_table_finish(t, "feature-show-fields"); - break; - case NVME_FEAT_FID_RESV_PERSIST: - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, "Persist Through Power Loss (PTPL)", "%s", - NVME_FEAT_RP_PTPL(result) ? "True" : "False"); - - stdout_kv_table_finish(t, "feature-show-fields"); - break; - case NVME_FEAT_FID_WRITE_PROTECT: - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, "Namespace Write Protect", "%s", - nvme_ns_wp_cfg_to_string(result)); - - stdout_kv_table_finish(t, "feature-show-fields"); - break; - case NVME_FEAT_FID_FDP: - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, "Flexible Direct Placement Enable (FDPE)", - "%s", NVME_FEAT_FDPE(result) ? "Yes" : "No"); - stdout_kv_add(t, - "Flexible Direct Placement Configuration Index", - "%u", NVME_FEAT_FDPCIDX(result)); - - stdout_kv_table_finish(t, "feature-show-fields"); - break; - case NVME_FEAT_FID_FDP_EVENTS: - t = stdout_kv_table_create(); - if (!t) - return; - - // NOET is in bits 7:0; bits 31:8 are reserved. - for (unsigned int i = 0; i < (result & 0xff); i++) { - struct nvme_fdp_supported_event_desc *d; - - d = &((struct nvme_fdp_supported_event_desc *)buf)[i]; - - stdout_kv_add(t, nvme_fdp_event_to_string(d->evt), - "%sEnabled", d->evta & 0x1 ? "" : "Not "); - } - - stdout_kv_table_finish(t, "feature-show-fields"); - break; - case NVME_FEAT_FID_BP_WRITE_PROTECT: - t = stdout_kv_table_create(); - if (!t) - return; - - field = NVME_FEAT_BPWPC_BP1WPS(result); - stdout_kv_add(t, - "Boot Partition 1 Write Protection State (BP1WPS)", - "%s", nvme_bpwps_to_string(field)); - field = NVME_FEAT_BPWPC_BP0WPS(result); - stdout_kv_add(t, - "Boot Partition 0 Write Protection State (BP0WPS)", - "%s", nvme_bpwps_to_string(field)); - - stdout_kv_table_finish(t, "feature-show-fields"); - break; - case NVME_FEAT_FID_POWER_LIMIT: { - __cleanup_free char *power_str = NULL; - - t = stdout_kv_table_create(); - if (!t) - return; - - field = NVME_FEAT_POWER_LIMIT_PLS(result); - power_str = stdout_power_and_scale_str( - NVME_FEAT_POWER_LIMIT_PLV(result), field); - stdout_kv_add(t, "Power Limit Scale (PLS)", "%u - %s", field, - nvme_feature_power_limit_scale_to_string(field)); - stdout_kv_add(t, "Power Limit Value (PLV)", "%u", - NVME_FEAT_POWER_LIMIT_PLV(result)); - stdout_kv_add(t, "Power Limit", "%s", power_str); - - stdout_kv_table_finish(t, "feature-show-fields"); - break; - } - case NVME_FEAT_FID_POWER_THRESH: { - __cleanup_free char *power_str = NULL; - - t = stdout_kv_table_create(); - if (!t) - return; - - field = NVME_FEAT_POWER_THRESH_EPT(result); - stdout_kv_add(t, "Enable Power Threshold (EPT)", "%u - %s", - field, field ? "Enabled" : "Disabled"); - field = NVME_FEAT_POWER_THRESH_PMTS(result); - stdout_kv_add(t, "Power Measurement Type Select (PMTS)", - "%u - %s", field, - nvme_power_measurement_type_to_string(field)); - field = NVME_FEAT_POWER_THRESH_PTS(result); - power_str = stdout_power_and_scale_str( - NVME_FEAT_POWER_THRESH_PTV(result), field); - stdout_kv_add(t, "Power Threshold Scale (PTS)", "%u - %s", - field, - nvme_feature_power_limit_scale_to_string(field)); - stdout_kv_add(t, "Power Threshold Value (PTV)", "%u", - NVME_FEAT_POWER_THRESH_PTV(result)); - stdout_kv_add(t, "Power Threshold", "%s", power_str); - - stdout_kv_table_finish(t, "feature-show-fields"); - break; - } - case NVME_FEAT_FID_POWER_MEASUREMENT: - t = stdout_kv_table_create(); - if (!t) - return; - - field = NVME_FEAT_POWER_MEAS_ACT(result); - stdout_kv_add(t, "Action (ACT)", "%u - %s", field, - nvme_power_measurement_action_to_string(field)); - field = NVME_FEAT_POWER_MEAS_PMTS(result); - stdout_kv_add(t, "Power Measurement Type Select (PMTS)", - "%u - %s", field, - nvme_power_measurement_type_to_string(field)); - stdout_kv_add(t, "Stop Measurement Time (SMT)", "%u", - NVME_FEAT_POWER_MEAS_SMT(result)); - - stdout_kv_table_finish(t, "feature-show-fields"); - break; - case NVME_FEAT_FID_VOLTAGE_THRESHOLD: - t = stdout_kv_table_create(); - if (!t) - return; - - field = NVME_FEAT_VOLTAGE_THRESHOLD_VSENS(result); - stdout_kv_add(t, "Voltage Sensor Select (VSENS)", "%u", field); - stdout_kv_add(t, "Enable Voltage Threshold (EVT)", "%u - %s", - !!(result & NVME_FEAT_VOLTAGE_THRESHOLD_EVT), - result & NVME_FEAT_VOLTAGE_THRESHOLD_EVT ? - "Enabled" : "Disabled"); - stdout_kv_add(t, "Overvoltage Threshold (OVT)", "%u", - NVME_FEAT_VOLTAGE_THRESHOLD_OVT(result)); - stdout_kv_add(t, "Undervoltage Threshold (UVT)", "%u", - NVME_FEAT_VOLTAGE_THRESHOLD_UVT(result)); - - stdout_kv_table_finish(t, "feature-show-fields"); - break; - case NVME_FEAT_FID_VOLTAGE_MEASUREMENT: - t = stdout_kv_table_create(); - if (!t) - return; - - field = NVME_FEAT_VOLTAGE_MEASUREMENT_ACT(result); - stdout_kv_add(t, "Action (ACT)", "%u", field); - - stdout_kv_table_finish(t, "feature-show-fields"); - break; - case NVME_FEAT_FID_RATE_LIMITING: - if (buf) - stdout_rate_limiting_data((struct nvme_rate_limiting_data *)buf); - break; - default: - break; - } -} - -static void stdout_lba_status(struct nvme_lba_status *list, - unsigned long len) -{ - struct shr_table_column columns[] = { - { "DSLBA", LEFT, AUTO_WIDTH }, - { "NLB", LEFT, AUTO_WIDTH }, - { "Status", LEFT, AUTO_WIDTH }, - }; - struct shr_table *t; - __u32 nlsd = le32_to_cpu(list->nlsd); - size_t nr = nvme_log_nr_entries(nlsd, len, sizeof(*list), - sizeof(list->descs[0])); - size_t idx; - int row; - - t = stdout_kv_table_create(); - if (!t) - return; - - stdout_kv_add(t, "Number of LBA Status Descriptors(NLSD)", "%"PRIu32, - nlsd); - stdout_kv_add(t, "Completion Condition(CMPC)", "%u", list->cmpc); - - stdout_kv_table_finish(t, "lba-status"); - - switch (list->cmpc) { - case NVME_LBA_STATUS_CMPC_NO_CMPC: - printf("\tNo indication of the completion condition\n"); - break; - case NVME_LBA_STATUS_CMPC_INCOMPLETE: - printf("\tCompleted transferring the amount of data specified in the\n"\ - "\tMNDW field. But, additional LBA Status Descriptor Entries are\n"\ - "\tavailable to transfer or scan did not complete (if ATYPE = 10h)\n"); - break; - case NVME_LBA_STATUS_CMPC_COMPLETE: - printf("\tCompleted the specified action over the number of LBAs specified\n"\ - "\tin the Range Length field and transferred all available LBA Status\n"\ - "\tDescriptor Entries\n"); - break; - default: - break; - } - - if (!nr) - return; - - t = shr_table_init_with_columns(columns, ARRAY_SIZE(columns)); - if (!t) - return; - - for (idx = 0; idx < nr; idx++) { - struct nvme_lba_status_desc *e = &list->descs[idx]; - char dslba[24], nlb[16], status[8]; - - snprintf(dslba, sizeof(dslba), "%#016"PRIx64, - le64_to_cpu(e->dslba)); - snprintf(nlb, sizeof(nlb), "%#08x", le32_to_cpu(e->nlb)); - snprintf(status, sizeof(status), "%#02x", e->status); - - row = shr_table_get_row_id(t); - shr_table_set_value_str(t, 0, row, dslba, LEFT); - shr_table_set_value_str(t, 1, row, nlb, LEFT); - shr_table_set_value_str(t, 2, row, status, LEFT); - shr_table_add_row(t, row); - } - - shr_table_print(t); - shr_table_free(t); -} - -static void stdout_dev_full_path(struct libnvme_ns *n, char *path, size_t len) -{ - struct stat st; - - snprintf(path, len, "%s", libnvme_ns_get_name(n)); - if (shr_startswith(path, "/dev/spdk/") && stat(path, &st) == 0) - return; - - snprintf(path, len, "/dev/%s", libnvme_ns_get_name(n)); - if (stat(path, &st) == 0) - return; - - /* - * We could start trying to search for it but let's make - * it simple and just don't show the path at all. - */ - snprintf(path, len, "%s", libnvme_ns_get_name(n)); -} - -static void stdout_generic_full_path(struct libnvme_ns *n, char *path, size_t len) -{ - int head_instance; - int instance; - struct stat st; - - /* - * There is no block devices for SPDK, point generic path to existing - * chardevice. - */ - snprintf(path, len, "%s", libnvme_ns_get_name(n)); - if (shr_startswith(path, "/dev/spdk/") && stat(path, &st) == 0) - return; - - if (sscanf(libnvme_ns_get_name(n), "nvme%dn%d", &instance, &head_instance) != 2) - return; - - snprintf(path, len, "/dev/ng%dn%d", instance, head_instance); - - if (stat(path, &st) == 0) - return; - - /* - * We could start trying to search for it but let's make - * it simple and just don't show the path at all. - */ - snprintf(path, len, "%s", libnvme_ns_get_generic_name(n)); -} - -static void list_item(struct libnvme_ns *n, struct shr_table *t) -{ - char usage[128] = { 0 }, format[128] = { 0 }; - char devname[128] = { 0 }; char genname[128] = { 0 }; - int lba_size, meta_size; - uint64_t lba_count, lba_util; - long long lba; - double nsze, nuse; - const char *s_suffix, *u_suffix, *l_suffix; - char ns[STR_LEN]; - int row; - - libnvme_ns_get_lba_size(n, &lba_size, 0); - libnvme_ns_get_lba_count(n, &lba_count, 0); - libnvme_ns_get_lba_util(n, &lba_util, 0); - libnvme_ns_get_meta_size(n, &meta_size, 0); - - lba = lba_size; - nsze = lba_count * lba; - nuse = lba_util * lba; - - s_suffix = shr_suffix_si_get(&nsze); - u_suffix = shr_suffix_si_get(&nuse); - l_suffix = shr_suffix_binary_get(&lba); - - snprintf(usage, sizeof(usage), "%6.2f %2sB / %6.2f %2sB", nuse, - u_suffix, nsze, s_suffix); - snprintf(format, sizeof(format), "%3.0f %2sB + %2d B", (double)lba, - l_suffix, meta_size); - - stdout_dev_full_path(n, devname, sizeof(devname)); - stdout_generic_full_path(n, genname, sizeof(genname)); - - row = shr_table_get_row_id(t); - if (row < 0) { - printf("Failed to add row\n"); - return; - } - if (shr_table_set_value_str(t, SIMPLE_LIST_COL_NODE, row, devname, LEFT)) { - printf("Failed to set node value\n"); - return; - } - if (shr_table_set_value_str(t, SIMPLE_LIST_COL_GENERIC, row, genname, LEFT)) { - printf("Failed to set generic value\n"); - return; - } - if (shr_table_set_value_str(t, SIMPLE_LIST_COL_SN, row, libnvme_ns_get_serial(n), LEFT)) { - printf("Failed to set sn value\n"); - return; - } - if (shr_table_set_value_str(t, SIMPLE_LIST_COL_MODEL, row, libnvme_ns_get_model(n), LEFT)) { - printf("Failed to set model value\n"); - return; - } - if (!sprintf(ns, "0x%x", libnvme_ns_get_nsid(n))) { - printf("Failed to output ns string\n"); - return; - } - if (shr_table_set_value_str(t, SIMPLE_LIST_COL_NS, row, ns, LEFT)) { - printf("Failed to set ns value\n"); - return; - } - if (shr_table_set_value_str(t, SIMPLE_LIST_COL_USAGE, row, usage, LEFT)) { - printf("Failed to set usage value\n"); - return; - } - if (shr_table_set_value_str(t, SIMPLE_LIST_COL_FORMAT, row, format, LEFT)) { - printf("Failed to set format value\n"); - return; - } - if (shr_table_set_value_str(t, SIMPLE_LIST_COL_FW_REV, row, libnvme_ns_get_firmware(n), LEFT)) { - printf("Failed to set fw rev value\n"); - return; - } - shr_table_add_row(t, row); -} - -static void stdout_list_item(struct libnvme_ns *n, struct shr_table *t) -{ - list_item(n, t); -} - -static void stdout_list_item_table(struct libnvme_ns *n, struct shr_table *t) -{ - list_item(n, t); -} - -static bool stdout_simple_ns(const char *name, void *arg) -{ - struct nvme_resources_table *rst_t = arg; - struct nvme_resources *res = rst_t->res; - struct libnvme_ns *n; - - n = htable_ns_get(&res->ht_n, name); - stdout_list_item_table(n, rst_t->t); - - return true; -} - -static void stdout_simple_list(struct libnvme_global_ctx *ctx) -{ - struct nvme_resources res; - struct shr_table_column columns[] = { - { "Node", LEFT, 21 }, - { "Generic", LEFT, 21 }, - { "SN", LEFT, 20 }, - { "Model", LEFT, 40 }, - { "Namespace", LEFT, 10 }, - { "Usage", LEFT, 26 }, - { "Format", LEFT, 16 }, - { "FW Rev", LEFT, 8 }, - }; - struct shr_table *t = shr_table_init_with_columns(columns, ARRAY_SIZE(columns)); - struct nvme_resources_table res_t = { &res, t }; - - if (!t) { - printf("Failed to init table\n"); - return; - } - - nvme_resources_init(ctx, &res); - - strset_iterate_sorted(&res.namespaces, stdout_simple_ns, &res_t); - - shr_table_print(t); - - nvme_resources_free(&res); - shr_table_free(t); -} - -static void stdout_ns_details(struct libnvme_ns *n) -{ - char usage[128] = { 0 }, format[128] = { 0 }, usage_binary[128] = { 0 }; - char devname[128] = { 0 }, genname[128] = { 0 }; - int lba_size, meta_size; - uint64_t lba_count, lba_util; - long long lba; - double nsze, nuse; - double nsze_binary, nuse_binary; - const char *s_suffix, *u_suffix, *l_suffix; - const char *s_suffix_binary, *u_suffix_binary; - - libnvme_ns_get_lba_size(n, &lba_size, 0); - libnvme_ns_get_lba_count(n, &lba_count, 0); - libnvme_ns_get_lba_util(n, &lba_util, 0); - libnvme_ns_get_meta_size(n, &meta_size, 0); - - lba = lba_size; - nsze = lba_count * lba; - nuse = lba_util * lba; - nsze_binary = nsze; - nuse_binary = nuse; - - s_suffix = shr_suffix_si_get(&nsze); - u_suffix = shr_suffix_si_get(&nuse); - l_suffix = shr_suffix_binary_get(&lba); - - sprintf(usage, "%6.2f %1sB / %6.2f %1sB", nuse, u_suffix, nsze, s_suffix); - sprintf(format, "%3.0f %2sB + %2d B", (double)lba, l_suffix, meta_size); - - s_suffix_binary = shr_suffix_dbinary_get(&nsze_binary); - u_suffix_binary = shr_suffix_dbinary_get(&nuse_binary); - sprintf(usage_binary, "(%7.2f %2sB / %7.2f %2sB)", nuse_binary, u_suffix_binary, - nsze_binary, s_suffix_binary); - - nvme_dev_full_path(n, devname, sizeof(devname)); - nvme_generic_full_path(n, genname, sizeof(genname)); - - printf("%-17s %-20s %#-10x %-21s %-25s %-16s ", devname, - genname, libnvme_ns_get_nsid(n), usage, usage_binary, format); -} - -static bool stdout_detailed_name(const char *name, void *arg) -{ - bool *first = arg; - - printf("%s%s", *first ? "" : ", ", name); - *first = false; - - return true; -} - -static bool stdout_detailed_subsys(const char *name, void *arg) -{ - struct nvme_resources *res = arg; - struct htable_subsys_iter it; - struct strset ctrls; - struct libnvme_subsystem *s; - struct libnvme_ctrl *c; - bool first; - - strset_init(&ctrls); - first = true; - for (s = htable_subsys_getfirst(&res->ht_s, name, &it); - s; - s = htable_subsys_getnext(&res->ht_s, name, &it)) { - if (first) { - printf("%-16s %-96s ", name, - libnvme_subsystem_get_subsysnqn(s)); - first = false; - } - - libnvme_subsystem_for_each_ctrl(s, c) - strset_add(&ctrls, libnvme_ctrl_get_name(c)); - } - - first = true; - strset_iterate_sorted(&ctrls, stdout_detailed_name, &first); - strset_clear(&ctrls); - printf("\n"); - - return true; -} - -static bool stdout_detailed_ctrl(const char *name, void *arg) -{ - struct nvme_resources *res = arg; - struct strset namespaces; - struct libnvme_ctrl *c; - struct libnvme_path *p; - struct libnvme_ns *n; - bool first; - - c = htable_ctrl_get(&res->ht_c, name); - assert(c); - - { - const char *tr = libnvme_ctrl_get_transport(c); - __cleanup_free char *reg_owner = libnvme_ctrl_owner(c); - const char *slot; - const char *cntlid; - const char *serial; - const char *model; - const char *firmware; - const char *owner_str; - - libnvme_ctrl_get_phy_slot(c, &slot, NULL); - libnvme_ctrl_get_cntlid(c, &cntlid, ""); - libnvme_ctrl_get_serial(c, &serial, ""); - libnvme_ctrl_get_model(c, &model, ""); - libnvme_ctrl_get_firmware(c, &firmware, ""); - - if (!libnvme_ctrl_is_transport_fabric(c)) - owner_str = "kernel"; - else - owner_str = reg_owner ? reg_owner : "-"; - - printf("%-16s %-12s %-6s %-20s %-40s %-8s %-6s %-14s %-6s %-12s ", - libnvme_ctrl_get_name(c), - owner_str, - cntlid, - serial, - model, - firmware, - tr, - libnvme_ctrl_get_address(c), - slot ? slot : "", - libnvme_subsystem_get_name(libnvme_ctrl_get_subsystem(c))); - } - - strset_init(&namespaces); - - libnvme_ctrl_for_each_ns(c, n) - strset_add(&namespaces, libnvme_ns_get_name(n)); - libnvme_ctrl_for_each_path(c, p) { - n = libnvme_path_get_ns(p); - if (!n) - continue; - strset_add(&namespaces, libnvme_ns_get_name(n)); - } - - first = true; - strset_iterate_sorted(&namespaces, stdout_detailed_name, &first); - strset_clear(&namespaces); - - printf("\n"); - - return true; -} - -static bool stdout_detailed_ns(const char *name, void *arg) -{ - struct nvme_resources *res = arg; - struct htable_ns_iter it; - struct strset ctrls; - struct libnvme_ctrl *c; - struct libnvme_path *p; - struct libnvme_ns *n; - bool first; - - strset_init(&ctrls); - first = true; - for (n = htable_ns_getfirst(&res->ht_n, name, &it); - n; - n = htable_ns_getnext(&res->ht_n, name, &it)) { - if (first) { - stdout_ns_details(n); - first = false; - } - - if (libnvme_ns_get_ctrl(n)) { - printf("%s\n", libnvme_ctrl_get_name(libnvme_ns_get_ctrl(n))); - return true; - } - - libnvme_namespace_for_each_path(n, p) { - c = libnvme_path_get_ctrl(p); - strset_add(&ctrls, libnvme_ctrl_get_name(c)); - } - } - - first = true; - strset_iterate_sorted(&ctrls, stdout_detailed_name, &first); - strset_clear(&ctrls); - - printf("\n"); - return true; -} - -static void stdout_detailed_list(struct libnvme_global_ctx *ctx) -{ - struct nvme_resources res; - - nvme_resources_init(ctx, &res); - - printf("%-16s %-96s %-.16s\n", "Subsystem", "Subsystem-NQN", "Controllers"); - printf("%-.16s %-.96s %-.16s\n", dash, dash, dash); - strset_iterate_sorted(&res.subsystems, stdout_detailed_subsys, &res); - printf("\n"); - - printf("%-16s %-12s %-6s %-20s %-40s %-8s %-6s %-14s %-6s %-12s %-16s\n", - "Device", "Orchestrator", "Cntlid", "SN", "MN", "FR", "TxPort", - "Address", "Slot", "Subsystem", "Namespaces"); - printf("%-.16s %-.12s %-.6s %-.20s %-.40s %-.8s %-.6s %-.14s %-.6s %-.12s %-.16s\n", - dash, dash, dash, dash, dash, dash, dash, dash, dash, dash, dash); - strset_iterate_sorted(&res.ctrls, stdout_detailed_ctrl, &res); - printf("\n"); - - printf("%-17s %-20s %-10s %-49s %-16s %-16s\n", "Device", "Generic", - "NSID", "Usage", "Format", "Controllers"); - printf("%-.17s %-.20s %-.10s %-.49s %-.16s %-.16s\n", dash, dash, dash, - dash, dash, dash); - strset_iterate_sorted(&res.namespaces, stdout_detailed_ns, &res); - - nvme_resources_free(&res); -} - -static void stdout_list_items(struct libnvme_global_ctx *ctx) -{ - if (stdout_print_ops.flags & VERBOSE) - stdout_detailed_list(ctx); - else - stdout_simple_list(ctx); -} - -static int subsystem_topology_multipath_add_row(struct shr_table *t, - const char *iopolicy, const char *nshead, - const char *nsid, const char *nspath, - const char *anastate, const char *iopolicy_info, - const char *ctrl, const char *trtype, - const char *address, const char *state) -{ - int row; - int col = -1; - - row = shr_table_get_row_id(t); - if (row < 0) { - nvme_show_error("Failed to add subsys topology multipath row"); - return row; - } - - shr_table_set_value_str(t, ++col, row, nshead, CENTERED); - shr_table_set_value_str(t, ++col, row, nsid, CENTERED); - shr_table_set_value_str(t, ++col, row, nspath, CENTERED); - shr_table_set_value_str(t, ++col, row, anastate, CENTERED); - if (streq(iopolicy, "numa") || streq(iopolicy, "queue-depth")) - shr_table_set_value_str(t, ++col, row, iopolicy_info, CENTERED); - shr_table_set_value_str(t, ++col, row, ctrl, CENTERED); - shr_table_set_value_str(t, ++col, row, trtype, CENTERED); - shr_table_set_value_str(t, ++col, row, address, CENTERED); - shr_table_set_value_str(t, ++col, row, state, CENTERED); - - shr_table_add_row(t, row); - - return 0; -} - -static void stdout_tabular_subsystem_topology_multipath(struct libnvme_subsystem *s) -{ - struct libnvme_ns *n; - struct libnvme_path *p; - struct libnvme_ctrl *c; - bool first; - char nshead[32], nsid[32]; - char iopolicy_info[256]; - int ret, num_path; - struct shr_table *t; - const char *iopolicy; - struct shr_table_column columns[] = { - {"NSHead", LEFT, AUTO_WIDTH}, - {"NSID", LEFT, AUTO_WIDTH}, - {"NSPath", LEFT, AUTO_WIDTH}, - {"ANAState", LEFT, AUTO_WIDTH}, - {"Nodes", LEFT, AUTO_WIDTH}, - {"Qdepth", LEFT, AUTO_WIDTH}, - {"Controller", LEFT, AUTO_WIDTH}, - {"TrType", LEFT, AUTO_WIDTH}, - {"Address", LEFT, AUTO_WIDTH}, - {"State", LEFT, AUTO_WIDTH}, - }; - - t = shr_table_create(); - if (!t) { - nvme_show_error("Failed to init subsys topology multipath table"); - return; - } - - if (shr_table_add_columns_filter(t, columns, ARRAY_SIZE(columns), - subsystem_iopolicy_filter, (void *)s) < 0) { - nvme_show_error("Failed to add subsys topology multipath columns"); - goto free_tbl; - } - - libnvme_subsystem_get_iopolicy(s, &iopolicy, ""); - - libnvme_subsystem_for_each_ns(s, n) { - first = true; - libnvme_namespace_for_each_path(n, p) { - const char *ana_state; - int queue_depth; - const char *numa_nodes; - - c = libnvme_path_get_ctrl(p); - libnvme_path_get_ana_state(p, &ana_state, ""); - - /* - * For the first row we print actual NSHead name, - * however, for the subsequent rows we print "arrow" - * ("-->") symbol for NSHead. This "arrow" style makes - * it visually obvious that susequenet entries (if - * present) are a path under the first NSHead. - */ - if (first) { - snprintf(nshead, sizeof(nshead), "%s", - libnvme_ns_get_name(n)); - first = false; - } else - snprintf(nshead, sizeof(nshead), "%s", "-->"); - - snprintf(nsid, sizeof(nsid), "%u", libnvme_ns_get_nsid(n)); - - if (streq(iopolicy, "numa")) { - libnvme_path_get_numa_nodes(p, &numa_nodes, ""); - snprintf(iopolicy_info, sizeof(iopolicy_info), - "%s", numa_nodes); - } else if (streq(iopolicy, "queue-depth")) { - libnvme_path_get_queue_depth(p, &queue_depth, - 0); - snprintf(iopolicy_info, sizeof(iopolicy_info), - "%d", queue_depth); - } else { - snprintf(iopolicy_info, sizeof(iopolicy_info), "--"); - } - - ret = subsystem_topology_multipath_add_row(t, - iopolicy, - nshead, - nsid, - libnvme_path_get_name(p), - ana_state, - iopolicy_info, - libnvme_ctrl_get_name(c), - libnvme_ctrl_get_transport(c), - libnvme_ctrl_get_address(c), - libnvme_ctrl_get_state(c)); - if (ret < 0) - goto free_tbl; - } - } - - /* - * Next we print controller in the subsystem which may not have any - * nvme path associated to it. - */ - libnvme_subsystem_for_each_ctrl(s, c) { - num_path = 0; - libnvme_ctrl_for_each_path(c, p) - num_path++; - - if (!num_path) { - ret = subsystem_topology_multipath_add_row(t, - iopolicy, - "--", /* NSHead */ - "--", /* NSID */ - "--", /* NSPath */ - "--", /* ANAState */ - "--", /* Nodes/Qdepth */ - libnvme_ctrl_get_name(c), - libnvme_ctrl_get_transport(c), - libnvme_ctrl_get_address(c), - libnvme_ctrl_get_state(c)); - if (ret < 0) - goto free_tbl; - } - } - - shr_table_print(t); -free_tbl: - shr_table_free(t); -} - -static void stdout_subsystem_topology_multipath(struct libnvme_subsystem *s, - enum nvme_cli_topo_ranking ranking) -{ - struct libnvme_ns *n; - struct libnvme_path *p; - struct libnvme_ctrl *c; - const char *iopolicy; - - libnvme_subsystem_get_iopolicy(s, &iopolicy, ""); - - if (ranking == NVME_CLI_TOPO_NAMESPACE) { - libnvme_subsystem_for_each_ns(s, n) { - if (!libnvme_namespace_first_path(n)) - continue; - - printf(" +- ns %d\n", libnvme_ns_get_nsid(n)); - printf(" \\\n"); - - libnvme_namespace_for_each_path(n, p) { - const char *ana_state; - - c = libnvme_path_get_ctrl(p); - libnvme_path_get_ana_state(p, &ana_state, ""); - - printf(" +- %s %s %s %s %s\n", - libnvme_ctrl_get_name(c), - libnvme_ctrl_get_transport(c), - libnvme_ctrl_get_address(c), - libnvme_ctrl_get_state(c), - ana_state); - } - } - } else if (ranking == NVME_CLI_TOPO_CTRL) { - /* NVME_CLI_TOPO_CTRL */ - libnvme_subsystem_for_each_ctrl(s, c) { - printf(" +- %s %s %s\n", - libnvme_ctrl_get_name(c), - libnvme_ctrl_get_transport(c), - libnvme_ctrl_get_address(c)); - printf(" \\\n"); - - libnvme_subsystem_for_each_ns(s, n) { - libnvme_namespace_for_each_path(n, p) { - const char *ana_state; - - if (libnvme_path_get_ctrl(p) != c) - continue; - - libnvme_path_get_ana_state(p, - &ana_state, ""); - printf(" +- ns %d %s %s\n", - libnvme_ns_get_nsid(n), - libnvme_ctrl_get_state(c), - ana_state); - } - } - } - } else { - /* NVME_CLI_TOPO_MULTIPATH */ - libnvme_subsystem_for_each_ns(s, n) { - printf(" +- %s (ns %d)\n", - libnvme_ns_get_name(n), - libnvme_ns_get_nsid(n)); - printf(" \\\n"); - libnvme_namespace_for_each_path(n, p) { - const char *ana_state; - - c = libnvme_path_get_ctrl(p); - libnvme_path_get_ana_state(p, &ana_state, ""); - - if (streq(iopolicy, "numa")) { - const char *numa_nodes; - - /* - * For iopolicy numa, exclude printing - * qdepth. - */ - libnvme_path_get_numa_nodes(p, - &numa_nodes, ""); - printf(" +- %s %s %s %s %s %s %s\n", - libnvme_path_get_name(p), - ana_state, - numa_nodes, - libnvme_ctrl_get_name(c), - libnvme_ctrl_get_transport(c), - libnvme_ctrl_get_address(c), - libnvme_ctrl_get_state(c)); - - } else if (streq(iopolicy, "queue-depth")) { - int queue_depth; - - /* - * For iopolicy queue-depth, exclude - * printing numa nodes. - */ - libnvme_path_get_queue_depth(p, - &queue_depth, 0); - printf(" +- %s %s %d %s %s %s %s\n", - libnvme_path_get_name(p), - ana_state, - queue_depth, - libnvme_ctrl_get_name(c), - libnvme_ctrl_get_transport(c), - libnvme_ctrl_get_address(c), - libnvme_ctrl_get_state(c)); - - } else { /* round-robin */ - /* - * For iopolicy round-robin, exclude - * printing numa nodes and qdepth. - */ - printf(" +- %s %s %s %s %s %s\n", - libnvme_path_get_name(p), - ana_state, - libnvme_ctrl_get_name(c), - libnvme_ctrl_get_transport(c), - libnvme_ctrl_get_address(c), - libnvme_ctrl_get_state(c)); - } - } - } - } -} - -static int subsystem_topology_add_row(struct shr_table *t, - const char *ns, const char *nsid, const char *ctrl, - const char *trtype, const char *address, const char *state) -{ - int row = shr_table_get_row_id(t); - if (row < 0) { - nvme_show_error("Failed to add subsys topology row"); - return row; - } - - shr_table_set_value_str(t, 0, row, ns, CENTERED); - shr_table_set_value_str(t, 1, row, nsid, CENTERED); - shr_table_set_value_str(t, 2, row, ctrl, CENTERED); - shr_table_set_value_str(t, 3, row, trtype, CENTERED); - shr_table_set_value_str(t, 4, row, address, CENTERED); - shr_table_set_value_str(t, 5, row, state, CENTERED); - - shr_table_add_row(t, row); - - return 0; -} - -static void stdout_tabular_subsystem_topology(struct libnvme_subsystem *s) -{ - struct libnvme_ctrl *c; - struct libnvme_ns *n; - int ret, num_ns; - struct shr_table *t; - struct shr_table_column columns[] = { - {"Namespace", LEFT, AUTO_WIDTH}, - {"NSID", LEFT, AUTO_WIDTH}, - {"Controller", LEFT, AUTO_WIDTH}, - {"Trtype", LEFT, AUTO_WIDTH}, - {"Address", LEFT, AUTO_WIDTH}, - {"State", LEFT, AUTO_WIDTH}, - }; - - t = shr_table_create(); - if (!t) { - nvme_show_error("Failed to init subsys topology table"); - return; - } - - if (shr_table_add_columns(t, columns, ARRAY_SIZE(columns)) < 0) { - nvme_show_error("Failed to add subsys topology columns"); - goto free_tbl; - } - - libnvme_subsystem_for_each_ctrl(s, c) { - num_ns = 0; - - libnvme_ctrl_for_each_ns(c, n) - num_ns++; - - if (!num_ns) { - ret = subsystem_topology_add_row(t, - "--", /* Namespace */ - "--", /* NSID */ - libnvme_ctrl_get_name(c), - libnvme_ctrl_get_transport(c), - libnvme_ctrl_get_address(c), - libnvme_ctrl_get_state(c)); - if (ret < 0) - goto free_tbl; - } else { - libnvme_ctrl_for_each_ns(c, n) { - char nsid[32]; - - snprintf(nsid, sizeof(nsid), "%u", - libnvme_ns_get_nsid(n)); - - ret = subsystem_topology_add_row(t, - libnvme_ns_get_name(n), - (const char *)nsid, - libnvme_ctrl_get_name(c), - libnvme_ctrl_get_transport(c), - libnvme_ctrl_get_address(c), - libnvme_ctrl_get_state(c)); - if (ret < 0) - goto free_tbl; - } - } - } - shr_table_print(t); -free_tbl: - shr_table_free(t); -} - -static void stdout_subsystem_topology(struct libnvme_subsystem *s, - enum nvme_cli_topo_ranking ranking) -{ - struct libnvme_ctrl *c; - struct libnvme_ns *n; - - if (ranking == NVME_CLI_TOPO_NAMESPACE) { - libnvme_subsystem_for_each_ctrl(s, c) { - libnvme_ctrl_for_each_ns(c, n) { - printf(" +- ns %d\n", libnvme_ns_get_nsid(n)); - printf(" \\\n"); - printf(" +- %s %s %s %s\n", - libnvme_ctrl_get_name(c), - libnvme_ctrl_get_transport(c), - libnvme_ctrl_get_address(c), - libnvme_ctrl_get_state(c)); - } - } - } else if (ranking == NVME_CLI_TOPO_CTRL) { - /* NVME_CLI_TOPO_CTRL */ - libnvme_subsystem_for_each_ctrl(s, c) { - printf(" +- %s %s %s\n", - libnvme_ctrl_get_name(c), - libnvme_ctrl_get_transport(c), - libnvme_ctrl_get_address(c)); - printf(" \\\n"); - libnvme_ctrl_for_each_ns(c, n) { - printf(" +- ns %d %s\n", - libnvme_ns_get_nsid(n), - libnvme_ctrl_get_state(c)); - } - } - } else { - /* NVME_CLI_TOPO_MULTIPATH */ - libnvme_subsystem_for_each_ctrl(s, c) { - libnvme_ctrl_for_each_ns(c, n) { - c = libnvme_ns_get_ctrl(n); - - printf(" +- %s (ns %d)\n", - libnvme_ns_get_name(n), - libnvme_ns_get_nsid(n)); - printf(" \\\n"); - printf(" +- %s %s %s %s\n", - libnvme_ctrl_get_name(c), - libnvme_ctrl_get_transport(c), - libnvme_ctrl_get_address(c), - libnvme_ctrl_get_state(c)); - } - } - } -} - -static void stdout_topology_tabular(struct libnvme_global_ctx *ctx) -{ - struct libnvme_host *h; - struct libnvme_subsystem *s; - bool first = true; - - libnvme_for_each_host(ctx, h) { - libnvme_for_each_subsystem(h, s) { - bool no_ctrl = true; - struct libnvme_ctrl *c; - - libnvme_subsystem_for_each_ctrl(s, c) - no_ctrl = false; - - if (no_ctrl) - continue; - - if (!first) - printf("\n"); - first = false; - - stdout_subsys_config(s, true); - printf("\n"); - - if (nvme_is_multipath(s)) - stdout_tabular_subsystem_topology_multipath(s); - else - stdout_tabular_subsystem_topology(s); - } - } -} - -static void stdout_simple_topology(struct libnvme_global_ctx *ctx, - enum nvme_cli_topo_ranking ranking) -{ - struct libnvme_host *h; - struct libnvme_subsystem *s; - bool first = true; - - libnvme_for_each_host(ctx, h) { - libnvme_for_each_subsystem(h, s) { - bool no_ctrl = true; - struct libnvme_ctrl *c; - - libnvme_subsystem_for_each_ctrl(s, c) - no_ctrl = false; - - if (no_ctrl) - continue; - - if (!first) - printf("\n"); - first = false; - - stdout_subsys_config(s, true); - printf("\\\n"); - - if (nvme_is_multipath(s)) - stdout_subsystem_topology_multipath(s, ranking); - else - stdout_subsystem_topology(s, ranking); - } - } -} - -static void stdout_topology_namespace(struct libnvme_global_ctx *ctx) -{ - stdout_simple_topology(ctx, NVME_CLI_TOPO_NAMESPACE); -} - -static void stdout_topology_ctrl(struct libnvme_global_ctx *ctx) -{ - stdout_simple_topology(ctx, NVME_CLI_TOPO_CTRL); -} - -static void stdout_topology_multipath(struct libnvme_global_ctx *ctx) -{ - stdout_simple_topology(ctx, NVME_CLI_TOPO_MULTIPATH); -} - -static void stdout_message(bool error, const char *msg, va_list ap) -{ - if (error) - argconfig_print_error_label(); - vfprintf(error ? stderr : stdout, msg, ap); + if (error) + argconfig_print_error_label(); + vfprintf(error ? stderr : stdout, msg, ap); fprintf(error ? stderr : stdout, "\n"); } @@ -3093,210 +410,15 @@ static void stdout_key_value(const char *key, const char *val, va_list ap) printf("%s: %s\n", key, value ? value : alloc_error); } -#ifdef CONFIG_FABRICS -/* - * libnvmf_connect_args_emit() callback for "nvme config show": print each - * formatted "--option=value" straight to stdout as part of the running - * "nvme connect" line. - */ -static void stdout_print_conn_arg(const char *arg, void *user_data) -{ - printf(" %s", arg); -} - -static void stdout_print_conn_field(const char *name, const char *value) -{ - if (value) - printf(" --%s=%s", name, value); -} - -/* - * libnvmf_config_conn_for_each() callback for "nvme config show": render - * one resolved connection as its equivalent "nvme connect" command line. - * - * Identity is deliberately left unresolved here (unlike build_conn_tid()'s - * connect-time callers): a persona with no hostnqn/hostid falls back to the - * system default at connect time, not parse time, so showing the concrete - * value here would suggest a fixed identity the config doesn't actually pin. - * - * Addressing is not resolved either, and no TID is built for a hostname: - * "show" must never touch the network, and a hostname traddr is legitimate - * INI content a TID (numeric-only) can't represent. The canonicalized TID - * rendering is used when the address is already numeric; a raw hostname - * falls back to printing the field as configured. - */ -static void stdout_print_conn(const struct libnvmf_config_conn *conn, - void *user_data) -{ - bool is_dc = libnvmf_config_conn_is_dc(conn); - const char *hostnqn = libnvmf_config_conn_get_hostnqn(conn); - const char *hostid = libnvmf_config_conn_get_hostid(conn); - const struct libnvmf_params *params = - libnvmf_config_conn_get_params(conn); - __cleanup_nvmf_tid struct libnvmf_tid *tid = NULL; - - printf("# %s: %s\n", libnvmf_config_conn_get_source(conn), - is_dc ? "Discovery Controller" : "I/O Controller"); - - libnvmf_tid_from_fields( - libnvmf_config_conn_get_transport(conn), - libnvmf_config_conn_get_traddr(conn), - libnvmf_config_conn_get_trsvcid(conn), - libnvmf_config_conn_get_subsysnqn(conn), - libnvmf_config_conn_get_host_traddr(conn), - libnvmf_config_conn_get_host_iface(conn), - hostnqn, hostid, &tid); - - /* - * A DC entry is consumed via libnvmf_discover() (log in, fetch the - * discovery log, connect everything returned) -- "nvme connect-all" - * is its real equivalent, not a bare "nvme connect" (which would - * only open the admin queue, matching just the niche "connect -J" - * mode instead of the primary discover/connect-all consumption - * path this command documents). - */ - printf("nvme %s", is_dc ? "connect-all" : "connect"); - if (tid) { - libnvmf_connect_args_emit(tid, params, stdout_print_conn_arg, - NULL); - } else { - const char *transport = libnvmf_config_conn_get_transport(conn); - const char *traddr = libnvmf_config_conn_get_traddr(conn); - const char *trsvcid = libnvmf_config_conn_get_trsvcid(conn); - const char *subsysnqn = libnvmf_config_conn_get_subsysnqn(conn); - const char *host_traddr = - libnvmf_config_conn_get_host_traddr(conn); - const char *host_iface = - libnvmf_config_conn_get_host_iface(conn); - - stdout_print_conn_field("transport", transport); - stdout_print_conn_field("traddr", traddr); - stdout_print_conn_field("trsvcid", trsvcid); - stdout_print_conn_field("nqn", subsysnqn); - stdout_print_conn_field("host-traddr", host_traddr); - stdout_print_conn_field("host-iface", host_iface); - stdout_print_conn_field("hostnqn", hostnqn); - stdout_print_conn_field("hostid", hostid); - libnvmf_connect_args_emit(NULL, params, stdout_print_conn_arg, - NULL); - } - printf("\n"); - if (!hostnqn || !hostid) - printf(" (hostnqn/hostid: system default)\n"); - printf("\n"); -} - -static void stdout_config_conn_list(struct libnvmf_config *config) -{ - libnvmf_config_conn_for_each(config, stdout_print_conn, NULL); -} -#else /* CONFIG_FABRICS */ -static void stdout_config_conn_list(struct libnvmf_config *config) {} -#endif /* CONFIG_FABRICS */ - -static void stdout_connect_msg(struct libnvme_ctrl *c) -{ - printf("connecting to device: %s\n", libnvme_ctrl_get_name(c)); -} - -static void stdout_relatives(struct libnvme_global_ctx *ctx, const char *name) -{ - struct nvme_resources res; - struct htable_ns_iter it; - bool block = true; - bool first = true; - struct libnvme_ctrl *c; - struct libnvme_path *p; - struct libnvme_ns *n; - int nsid; - int ret; - int id; - - ret = sscanf(name, "nvme%dn%d", &id, &nsid); - - switch (ret) { - case 1: - block = false; - break; - case 2: - break; - default: - return; - } - - nvme_resources_init(ctx, &res); - - if (block) { - fprintf(stderr, "Namespace %s has parent controller(s):", name); - for (n = htable_ns_getfirst(&res.ht_n, name, &it); n; - n = htable_ns_getnext(&res.ht_n, name, &it)) { - if (libnvme_ns_get_ctrl(n)) { - fprintf(stderr, "%s", libnvme_ctrl_get_name(libnvme_ns_get_ctrl(n))); - break; - } - libnvme_namespace_for_each_path(n, p) { - c = libnvme_path_get_ctrl(p); - fprintf(stderr, "%s%s", first ? "" : ", ", libnvme_ctrl_get_name(c)); - if (first) - first = false; - } - } - fprintf(stderr, "\n\n"); - } else { - c = htable_ctrl_get(&res.ht_c, name); - if (c) { - fprintf(stderr, "Controller %s has child namespace(s):", name); - libnvme_ctrl_for_each_ns(c, n) { - fprintf(stderr, "%s%s", first ? "" : ", ", libnvme_ns_get_name(n)); - if (first) - first = false; - } - fprintf(stderr, "\n\n"); - } - } - - nvme_resources_free(&res); -} - struct print_ops stdout_print_ops = { /* libnvme types.h print functions */ - .ctrl_registers = stdout_ctrl_registers, - .directive = stdout_directive_show, - .discovery_log = stdout_discovery_log, - .lba_status = stdout_lba_status, - .relatives = stdout_relatives, - .resv_report = stdout_resv_report, - .select_result = stdout_select_result, - .show_feature = stdout_feature_show, - .show_feature_fields = stdout_feature_show_fields, - .id_ctrl_rpmbs = stdout_id_ctrl_rpmbs, - .lba_range = stdout_lba_range, - .lba_status_info = stdout_lba_status_info, .d = stdout_d, .show_init = NULL, .show_finish = NULL, - /* libnvme tree print functions */ - .list_item = stdout_list_item, - .list_items = stdout_list_items, - .print_nvme_subsystem_list = stdout_subsystem_list, - .topology_ctrl = stdout_topology_ctrl, - .topology_namespace = stdout_topology_namespace, - .topology_multipath = stdout_topology_multipath, - .topology_tabular = stdout_topology_tabular, - /* config show */ - .config_conn_list = stdout_config_conn_list, - - /* nvme top */ -#ifdef CONFIG_TOP - .top = stdout_top, -#else - .top = NULL, -#endif /* status and error messages */ - .connect_msg = stdout_connect_msg, .show_message = stdout_message, .show_perror = stdout_perror, .show_status = stdout_status, diff --git a/src/nvme-print-stdout.h b/src/nvme-print-stdout.h index cbf224d19c..f765a05c7e 100644 --- a/src/nvme-print-stdout.h +++ b/src/nvme-print-stdout.h @@ -11,20 +11,7 @@ struct shr_table *stdout_kv_table_create(void); int stdout_kv_add(struct shr_table *t, const char *name, const char *fmt, ...); void stdout_kv_table_finish(struct shr_table *t, const char *what); -struct shr_table *stdout_bitfields_table(const struct bitfield *fields, - unsigned int nr, uint64_t value); struct shr_table *stdout_bits_table_create(void); void stdout_bits_add(struct shr_table *t, const char *bits, unsigned int val, const char *desc_fmt, ...); const char *stdout_format_timestamp(__u8 *timestamp_bytes); -void stdout_feature_show_fields(enum nvme_features_id fid, unsigned int result, - unsigned char *buf); -void stdout_id_ctrl_rpmbs(__le32 ctrl_rpmbs); -#ifdef CONFIG_FABRICS -void stdout_discovery_log(const struct nvmf_discovery_log *log, int numrec); -#else /* CONFIG_FABRICS */ -#define stdout_discovery_log NULL -#endif /* CONFIG_FABRICS */ - -/* id */ -struct shr_table *stdout_id_ctrl_rpmbs_table(__le32 ctrl_rpmbs); diff --git a/src/nvme-print.c b/src/nvme-print.c index ea04459884..f9025e6251 100644 --- a/src/nvme-print.c +++ b/src/nvme-print.c @@ -5,7 +5,6 @@ #include #include #include -#include #include #include @@ -13,16 +12,13 @@ #include #include -#include #include #include #include -#include #include #include "cleanup.h" #include "nvme-print.h" -#include "plugin-loader.h" /* * A printer runs between nvme_print_begin() and nvme_print_end(). The @@ -44,29 +40,6 @@ nvme_print(name, nvme_is_output_format_json() ? JSON : NORMAL, ##__VA_ARGS__); const char *alloc_error = "Could not allocate string"; -const char *feat_ae_dlpcn = "Discovery Log Page Change Notices"; -const char *feat_ae_hdlpcn = "Host Discovery Log Page Change Notification"; -const char *feat_ae_adlpcn = "AVE Discovery Log Page Change Notification"; -const char *feat_ae_pmdrlpcn = - "Pull Model DDC Request Log Page Change Notification"; -const char *feat_ae_zdcn = "Zone Descriptor Changed Notices"; -const char *feat_ae_rlccn = "Rate Limiting Configuration Change Notices"; -const char *feat_ae_lhcn = "Lost Host Communication Notices"; -const char *feat_ae_ccrcn = "Cross-Controller Reset Completed Notices"; -const char *feat_ae_ansan = "Allocated Namespace Attribute Notices"; -const char *feat_ae_rgrp0 = "Reachability Group"; -const char *feat_ae_rassn = "Reachability Association"; -const char *feat_ae_tthry = "Temperature Threshold Hysteresis Recovery"; -const char *feat_ae_nnsshdn = "Normal NVM Subsystem Shutdown"; -const char *feat_ae_ega = "Endurance Group Event Aggregate Log Change Notices"; -const char *feat_ae_lbas = "LBA Status Information Notices"; -const char *feat_ae_pla = - "Predictable Latency Event Aggregate Log Change Notices"; -const char *feat_ae_ana = "Asymmetric Namespace Access Change Notices"; -const char *feat_ae_telem = "Telemetry Log Notices"; -const char *feat_ae_fw = "Firmware Activation Notices"; -const char *feat_ae_nan = "Attached Namespace Attribute Notices"; -const char *feat_ae_smart = "SMART / Health Critical Warnings"; static struct print_ops *nvme_print_ops(nvme_print_flags_t flags) { @@ -96,20 +69,11 @@ bool nvme_show_failed(void) return print_failed; } -/* - * The printers which stay in process: the ones of the libnvme tree, which - * read sysfs while printing, the ones which hand JSON objects to their - * caller, the interactive one and the document. - */ +/* The hooks of the JSON document stay in process */ static bool nvme_print_sandboxed(struct print_ops *ops, void *func) { void *in_process[] = { - ops->relatives, ops->list_item, ops->list_items, - ops->print_nvme_subsystem_list, ops->topology_ctrl, - ops->topology_namespace, ops->topology_multipath, - ops->topology_tabular, ops->config_conn_list, ops->top, ops->show_init, ops->show_finish, - ops->connect_msg, }; size_t i; @@ -200,26 +164,30 @@ static bool nvme_print_check(struct print_ops *ops, void *func) if (func == ops->d) return true; - /* Always show feature fields since called set features command */ - if (func == ops->show_feature_fields) - return true; - if (nvme_args.dry_run) return false; return true; } -bool nvme_print_decoder_begin(nvme_print_flags_t flags, bool sandbox) +bool nvme_print_decoder_begin_always(nvme_print_flags_t flags, bool sandbox) { struct print_ops *ops = nvme_print_ops(flags); - if (!ops || nvme_args.dry_run) + if (!ops) return false; return nvme_print_begin(ops, sandbox); } +bool nvme_print_decoder_begin(nvme_print_flags_t flags, bool sandbox) +{ + if (nvme_args.dry_run) + return false; + + return nvme_print_decoder_begin_always(flags, sandbox); +} + void nvme_print_decoder_end(nvme_print_flags_t flags) { nvme_print_end(nvme_print_ops(flags)); @@ -318,25 +286,6 @@ const char *nvme_fdp_event_to_string(enum nvme_fdp_event_type event) return "Unknown"; } -void nvme_show_subsystem_list(struct libnvme_global_ctx *ctx, bool show_ana, - nvme_print_flags_t flags) -{ - nvme_print(print_nvme_subsystem_list, flags, ctx, show_ana); -} - -void nvme_show_ctrl_registers(const struct nvme_reg_val *vals, unsigned int nr, - enum nvme_regs_style style, - nvme_print_flags_t flags) -{ - nvme_print(ctrl_registers, flags, vals, nr, style); -} - -void nvme_show_relatives(struct libnvme_global_ctx *ctx, const char *name, - nvme_print_flags_t flags) -{ - nvme_print(relatives, flags, ctx, name); -} - void d(unsigned char *buf, int len, int width, int group) { nvme_print(d, NORMAL, buf, len, width, group); @@ -430,17 +379,6 @@ void nvme_show_error_status(int status, const char *msg, ...) va_end(ap); } -void nvme_show_id_ctrl_rpmbs(__le32 ctrl_rpmbs, nvme_print_flags_t flags) -{ - nvme_print(id_ctrl_rpmbs, flags, ctrl_rpmbs); -} - -void nvme_show_resv_report(struct nvme_resv_status *status, int bytes, - bool eds, nvme_print_flags_t flags) -{ - nvme_print(resv_report, flags, status, bytes, eds); -} - const char *nvme_degrees_string(long t) { static char str[STR_LEN]; @@ -505,354 +443,6 @@ const char *nvme_format_timestamp_sync(__u8 attr) "The controller counted time in milliseconds continuously since the Timestamp value was initialized."; } -const char *nvme_feature_to_string(enum nvme_features_id feature) -{ - switch (feature) { - case NVME_FEAT_FID_ARBITRATION: return "Arbitration"; - case NVME_FEAT_FID_POWER_MGMT: return "Power Management"; - case NVME_FEAT_FID_LBA_RANGE: return "LBA Range Type"; - case NVME_FEAT_FID_TEMP_THRESH: return "Temperature Threshold"; - case NVME_FEAT_FID_ERR_RECOVERY: return "Error Recovery"; - case NVME_FEAT_FID_VOLATILE_WC: return "Volatile Write Cache"; - case NVME_FEAT_FID_NUM_QUEUES: return "Number of Queues"; - case NVME_FEAT_FID_IRQ_COALESCE: return "Interrupt Coalescing"; - case NVME_FEAT_FID_IRQ_CONFIG: return "Interrupt Vector Configuration"; - case NVME_FEAT_FID_WRITE_ATOMIC: return "Write Atomicity Normal"; - case NVME_FEAT_FID_ASYNC_EVENT: return "Async Event Configuration"; - case NVME_FEAT_FID_AUTO_PST: return "Autonomous Power State Transition"; - case NVME_FEAT_FID_HOST_MEM_BUF: return "Host Memory Buffer"; - case NVME_FEAT_FID_TIMESTAMP: return "Timestamp"; - case NVME_FEAT_FID_KATO: return "Keep Alive Timer"; - case NVME_FEAT_FID_HCTM: return "Host Controlled Thermal Management"; - case NVME_FEAT_FID_NOPSC: return "Non-Operational Power State Config"; - case NVME_FEAT_FID_RRL: return "Read Recovery Level"; - case NVME_FEAT_FID_PLM_CONFIG: return "Predictable Latency Mode Config"; - case NVME_FEAT_FID_PLM_WINDOW: return "Predictable Latency Mode Window"; - case NVME_FEAT_FID_LBA_STS_INTERVAL: return "LBA Status Interval"; - case NVME_FEAT_FID_HOST_BEHAVIOR: return "Host Behavior"; - case NVME_FEAT_FID_SANITIZE: return "Sanitize"; - case NVME_FEAT_FID_ENDURANCE_EVT_CFG: return "Endurance Event Group Configuration"; - case NVME_FEAT_FID_IOCS_PROFILE: return "I/O Command Set Profile"; - case NVME_FEAT_FID_SPINUP_CONTROL: return "Spinup Control"; - case NVME_FEAT_FID_POWER_LOSS_SIGNAL: return "Power Loss Signaling Config"; - case NVME_FEAT_FID_PERF_CHARACTERISTICS:return "Performance Characteristics"; - case NVME_FEAT_FID_FDP: return "Flexible Direct Placement"; - case NVME_FEAT_FID_FDP_EVENTS: return "Flexible Direct Placement Events"; - case NVME_FEAT_FID_NS_ADMIN_LABEL: return "Namespace Admin Label"; - case NVME_FEAT_FID_KEY_VALUE: return "Key Value Configuration"; - case NVME_FEAT_FID_CTRL_DATA_QUEUE: return "Controller Data Queue"; - case NVME_FEAT_FID_CONF_DEV_PERSONALITY:return "Configurable Device Personality"; - case NVME_FEAT_FID_POWER_LIMIT: return "Power Limit"; - case NVME_FEAT_FID_POWER_THRESH: return "Power Threshold"; - case NVME_FEAT_FID_POWER_MEASUREMENT: return "Power Measurement"; - case NVME_FEAT_FID_VOLTAGE_THRESHOLD: return "Voltage Threshold"; - case NVME_FEAT_FID_VOLTAGE_MEASUREMENT: return "Voltage Measurement"; - case NVME_FEAT_FID_RATE_LIMITING: return "Rate Limiting"; - case NVME_FEAT_FID_EMB_MGMT_CTRL_ADDR: return "Embedded Management Controller Address"; - case NVME_FEAT_FID_HOST_MGMT_AGENT_ADDR:return "Host Management Agent Address"; - case NVME_FEAT_FID_ENH_CTRL_METADATA: return "Enhanced Controller Metadata"; - case NVME_FEAT_FID_CTRL_METADATA: return "Controller Metadata"; - case NVME_FEAT_FID_NS_METADATA: return "Namespace Metadata"; - case NVME_FEAT_FID_SW_PROGRESS: return "Software Progress"; - case NVME_FEAT_FID_HOST_ID: return "Host Identifier"; - case NVME_FEAT_FID_RESV_NF_MASK: return "Reservation Notification Mask"; - case NVME_FEAT_FID_RESV_PERSIST: return "Reservation Persistence"; - case NVME_FEAT_FID_WRITE_PROTECT: return "Namespace Write Protect"; - case NVME_FEAT_FID_BP_WRITE_PROTECT: return "Boot Partition Write Protection Config"; - } - /* - * We don't use the "default:" statement to let the compiler warning if - * some values of the enum nvme_features_id are missing in the switch(). - * The following return is acting as the default: statement. - */ - return "Unknown"; -} - -const char *nvme_select_to_string(int sel) -{ - switch (sel) { - case NVME_GET_FEATURES_SEL_CURRENT: - return "Current"; - case NVME_GET_FEATURES_SEL_DEFAULT: - return "Default"; - case NVME_GET_FEATURES_SEL_SAVED: - return "Saved"; - case NVME_GET_FEATURES_SEL_SUPPORTED: - return "Supported capabilities"; - default: - break; - } - return "Reserved"; -} - -void nvme_show_select_result(enum nvme_features_id fid, __u64 result) -{ - nvme_print(select_result, NORMAL, fid, result); -} - -const char *nvme_feature_lba_type_to_string(__u8 type) -{ - switch (type) { - case 0: return "General Purpose"; - case 1: return "Filesystem"; - case 2: return "RAID"; - case 3: return "Cache"; - case 4: return "Page / Swap file"; - default: - if (type >= 0x05 && type <= 0x7f) - return "Reserved"; - else - return "Vendor Specific"; - } -} - -void nvme_show_lba_range(struct nvme_lba_range_type *lbrt, int nr_ranges, - nvme_print_flags_t flags) -{ - nvme_print(lba_range, flags, lbrt, nr_ranges); -} - -const char *nvme_feature_wl_hints_to_string(__u8 wh) -{ - switch (wh) { - case 0: return "No Workload"; - case 1: return "Extended Idle Period with a Burst of Random Writes"; - case 2: return "Heavy Sequential Writes"; - default:return "Reserved"; - } -} - -const char *nvme_feature_temp_type_to_string(__u8 type) -{ - switch (type) { - case 0: return "Over Temperature Threshold"; - case 1: return "Under Temperature Threshold"; - default:return "Reserved"; - } -} - -const char *nvme_feature_temp_sel_to_string(__u8 sel) -{ - switch (sel) { - case 0: return "Composite Temperature"; - case 1: return "Temperature Sensor 1"; - case 2: return "Temperature Sensor 2"; - case 3: return "Temperature Sensor 3"; - case 4: return "Temperature Sensor 4"; - case 5: return "Temperature Sensor 5"; - case 6: return "Temperature Sensor 6"; - case 7: return "Temperature Sensor 7"; - case 8: return "Temperature Sensor 8"; - default:return "Reserved"; - } -} - -const char *nvme_feature_perfc_attri_to_string(__u8 attri) -{ - switch (attri) { - case NVME_FEAT_PERFC_ATTRI_STD: - return "standard performance attribute"; - case NVME_FEAT_PERFC_ATTRI_ID_LIST: - return "performance attribute identifier list"; - case NVME_FEAT_PERFC_ATTRI_VS_MIN ... NVME_FEAT_PERFC_ATTRI_VS_MAX: - return "vendor specific performance attribute"; - default: - break; - } - - return "reserved"; -} - -const char *nvme_feature_perfc_r4karl_to_string(__u8 r4karl) -{ - switch (r4karl) { - case NVME_FEAT_PERFC_R4KARL_NO_REPORT: - return "not reported"; - case NVME_FEAT_PERFC_R4KARL_GE_100_SEC: - return "greater than or equal to 100 seconds"; - case NVME_FEAT_PERFC_R4KARL_GE_50_SEC: - return "greater than or equal to 50 seconds and less than 100 seconds"; - case NVME_FEAT_PERFC_R4KARL_GE_10_SEC: - return "greater than or equal to 10 seconds and less than 50 seconds"; - case NVME_FEAT_PERFC_R4KARL_GE_5_SEC: - return "greater than or equal to 5 seconds and less than 10 seconds"; - case NVME_FEAT_PERFC_R4KARL_GE_1_SEC: - return "greater than or equal to 1 second and less than 5 seconds"; - case NVME_FEAT_PERFC_R4KARL_GE_500_MS: - return "greater than or equal to 500 milliseconds and less than 1 second"; - case NVME_FEAT_PERFC_R4KARL_GE_100_MS: - return "greater than or equal to 100 milliseconds and less than 500 milliseconds"; - case NVME_FEAT_PERFC_R4KARL_GE_50_MS: - return "greater than or equal to 50 milliseconds and less than 100 milliseconds"; - case NVME_FEAT_PERFC_R4KARL_GE_10_MS: - return "greater than or equal to 10 milliseconds and less than 50 milliseconds"; - case NVME_FEAT_PERFC_R4KARL_GE_5_MS: - return "greater than or equal to 5 milliseconds and less than 10 milliseconds"; - case NVME_FEAT_PERFC_R4KARL_GE_1_MS: - return "greater than or equal to 1 millisecond and less than 5 milliseconds"; - case NVME_FEAT_PERFC_R4KARL_GE_500_US: - return "greater than or equal to 500 microseconds and less than 1 millisecond"; - case NVME_FEAT_PERFC_R4KARL_GE_100_US: - return "greater than or equal to 100 microseconds and less than 500 microseconds"; - case NVME_FEAT_PERFC_R4KARL_GE_50_US: - return "greater than or equal to 50 microseconds and less than 100 microseconds"; - case NVME_FEAT_PERFC_R4KARL_GE_10_US: - return "greater than or equal to 10 microseconds and less than 50 microseconds"; - case NVME_FEAT_PERFC_R4KARL_GE_5_US: - return "greater than or equal to 5 microseconds and less than 10 microseconds"; - case NVME_FEAT_PERFC_R4KARL_GE_1_US: - return "greater than or equal to 1 microsecond and less than 5 microseconds"; - case NVME_FEAT_PERFC_R4KARL_GE_500_NS: - return "greater than or equal to 500 nanoseconds and less than 1 microsecond"; - case NVME_FEAT_PERFC_R4KARL_GE_100_NS: - return "greater than or equal to 100 nanoseconds and less than 500 nanoseconds"; - case NVME_FEAT_PERFC_R4KARL_GE_50_NS: - return "greater than or equal to 50 nanoseconds and less than 100 nanoseconds"; - case NVME_FEAT_PERFC_R4KARL_GE_10_NS: - return "greater than or equal to 10 nanoseconds and less than 50 nanoseconds"; - case NVME_FEAT_PERFC_R4KARL_GE_5_NS: - return "greater than or equal to 5 nanoseconds and less than 10 nanoseconds"; - case NVME_FEAT_PERFC_R4KARL_GE_1_NS: - return "greater than or equal to 1 nanosecond and less than 5 nanoseconds"; - default: - break; - } - - return "reserved"; -} - -const char *nvme_feature_perfc_attrtyp_to_string(__u8 attrtyp) -{ - switch (attrtyp) { - case NVME_GET_FEATURES_SEL_CURRENT: - return "current attribute"; - case NVME_GET_FEATURES_SEL_DEFAULT: - return "default attribute"; - case NVME_GET_FEATURES_SEL_SAVED: - return "saved attribute"; - default: - break; - } - - return "reserved"; -} - -const char *nvme_ns_wp_cfg_to_string(enum nvme_ns_write_protect_cfg state) -{ - switch (state) { - case NVME_NS_WP_CFG_NONE: - return "No Write Protect"; - case NVME_NS_WP_CFG_PROTECT: - return "Write Protect"; - case NVME_NS_WP_CFG_PROTECT_POWER_CYCLE: - return "Write Protect Until Power Cycle"; - case NVME_NS_WP_CFG_PROTECT_PERMANENT: - return "Permanent Write Protect"; - default: - return "Reserved"; - } -} - -const char *nvme_bpwps_to_string(__u8 bpwps) -{ - switch (bpwps) { - case NVME_FEAT_BPWPS_CHANGE_NOT_REQUESTED: - return "Change in state not requested"; - case NVME_FEAT_BPWPS_WRITE_UNLOCKED: - return "Write Unlocked"; - case NVME_FEAT_BPWPS_WRITE_LOCKED: - return "Write Locked"; - case NVME_FEAT_BPWPS_WRITE_LOCKED_PWR_CYCLE: - return "Write Locked Until Power Cycle"; - case NVME_FEAT_BPWPS_WRITE_PROTECTION_RPMB: - return "Write Protection controlled by RPMB"; - default: - return "Reserved"; - } -} - -void nvme_directive_show(__u8 type, __u8 oper, __u16 spec, __u32 nsid, __u64 result, - void *buf, __u32 len, nvme_print_flags_t flags) -{ - nvme_print(directive, flags, type, oper, spec, nsid, result, buf, len); -} - -const char *nvme_plm_window_to_string(__u32 plm) -{ - switch (NVME_FEAT_PLMW_WS(plm)) { - case 1: - return "Deterministic Window (DTWIN)"; - case 2: - return "Non-deterministic Window (NDWIN)"; - default: - return "Reserved"; - } -} - -void nvme_show_lba_status_info(__u64 result) -{ - nvme_print(lba_status_info, NORMAL, result); -} - -const char *nvme_host_metadata_type_to_string(enum nvme_features_id fid, __u8 type) -{ - switch (fid) { - case NVME_FEAT_FID_ENH_CTRL_METADATA: - case NVME_FEAT_FID_CTRL_METADATA: - switch (type) { - case NVME_CTRL_METADATA_OS_CTRL_NAME: - return "Operating System Controller Name"; - case NVME_CTRL_METADATA_OS_DRIVER_NAME: - return "Operating System Driver Name"; - case NVME_CTRL_METADATA_OS_DRIVER_VER: - return "Operating System Driver Version"; - case NVME_CTRL_METADATA_PRE_BOOT_CTRL_NAME: - return "Pre-boot Controller Name"; - case NVME_CTRL_METADATA_PRE_BOOT_DRIVER_NAME: - return "Pre-boot Driver Name"; - case NVME_CTRL_METADATA_PRE_BOOT_DRIVER_VER: - return "Pre-boot Driver Version"; - case NVME_CTRL_METADATA_SYS_PROC_MODEL: - return "System Processor Model"; - case NVME_CTRL_METADATA_CHIPSET_DRV_NAME: - return "Chipset Driver Name"; - case NVME_CTRL_METADATA_CHIPSET_DRV_VERSION: - return "Chipset Driver Version"; - case NVME_CTRL_METADATA_OS_NAME_AND_BUILD: - return "Operating System Name and Build"; - case NVME_CTRL_METADATA_SYS_PROD_NAME: - return "System Product Name"; - case NVME_CTRL_METADATA_FIRMWARE_VERSION: - return "Firmware Version"; - case NVME_CTRL_METADATA_OS_DRIVER_FILENAME: - return "Operating System Driver Filename"; - case NVME_CTRL_METADATA_DISPLAY_DRV_NAME: - return "Display Driver Name"; - case NVME_CTRL_METADATA_DISPLAY_DRV_VERSION: - return "Display Driver Version"; - case NVME_CTRL_METADATA_HOST_DET_FAIL_REC: - return "Host-Determined Failure Record"; - default: - return "Unknown Controller Type"; - } - case NVME_FEAT_FID_NS_METADATA: - switch (type) { - case NVME_NS_METADATA_OS_NS_NAME: - return "Operating System Namespace Name"; - case NVME_NS_METADATA_PRE_BOOT_NS_NAME: - return "Pre-boot Namespace Name"; - case NVME_NS_METADATA_OS_NS_QUAL_1: - return "Operating System Namespace Name Qualifier 1"; - case NVME_NS_METADATA_OS_NS_QUAL_2: - return "Operating System Namespace Name Qualifier 2"; - default: - return "Unknown Namespace Type"; - } - default: - return "Unknown Feature"; - } -} - const char *nvme_time_scale_to_string(__u8 ts) { switch (ts) { @@ -889,22 +479,6 @@ const char *nvme_time_scale_to_string(__u8 ts) return "Reserved"; } -const char *nvme_pls_mode_to_string(__u8 mode) -{ - switch (mode) { - case 0: - return "not enabled"; - case 1: - return "enabled with Emergency Power Fail"; - case 2: - return "enabled with Forced Quiescence"; - default: - break; - } - - return "Reserved"; -} - const char *nvme_feature_power_limit_scale_to_string(__u8 pls) { switch (pls) { @@ -935,21 +509,6 @@ const char *nvme_power_measurement_type_to_string(__u8 pmt) return "Reserved"; } - -const char *nvme_power_measurement_action_to_string(__u8 act) -{ - switch (act) { - case 0: - return "Stop"; - case 1: - return "Start"; - default: - break; - } - - return "Reserved"; -} - const char *nvme_ipmsr_srs_to_string(__u8 srs) { switch (srs) { @@ -970,101 +529,6 @@ const char *nvme_ipmsr_srs_to_string(__u8 srs) } } -void nvme_show_feature(enum nvme_features_id fid, int sel, unsigned int result, - void *buf, __u32 data_len, nvme_print_flags_t flags) -{ - nvme_print(show_feature, flags, fid, sel, result, buf, data_len); -} - -void nvme_feature_show_fields(enum nvme_features_id fid, unsigned int result, unsigned char *buf) -{ - nvme_print(show_feature_fields, NORMAL, fid, result, buf); -} - -void nvme_show_lba_status(struct nvme_lba_status *list, unsigned long len, - nvme_print_flags_t flags) -{ - nvme_print(lba_status, flags, list, len); -} - -void nvme_dev_full_path(struct libnvme_ns *n, char *path, size_t len) -{ - struct stat st; - - snprintf(path, len, "%s", libnvme_ns_get_name(n)); - if (shr_startswith(path, "/dev/spdk/") && stat(path, &st) == 0) - return; - - snprintf(path, len, "/dev/%s", libnvme_ns_get_name(n)); - if (stat(path, &st) == 0) - return; - /* - * We could start trying to search for it but let's make - * it simple and just don't show the path at all. - */ - snprintf(path, len, "%s", libnvme_ns_get_name(n)); -} - -void nvme_generic_full_path(struct libnvme_ns *n, char *path, size_t len) -{ - int head_instance; - int instance; - struct stat st; - - /* - * There is no block devices for SPDK, point generic path to existing - * chardevice. - */ - snprintf(path, len, "%s", libnvme_ns_get_name(n)); - if (shr_startswith(path, "/dev/spdk/") && stat(path, &st) == 0) - return; - - if (sscanf(libnvme_ns_get_name(n), "nvme%dn%d", &instance, &head_instance) != 2) - return; - - snprintf(path, len, "/dev/ng%dn%d", instance, head_instance); - - if (stat(path, &st) == 0) - return; - /* - * We could start trying to search for it but let's make - * it simple and just don't show the path at all. - */ - snprintf(path, len, "%s", libnvme_ns_get_generic_name(n)); -} - -void nvme_show_list_item(struct libnvme_ns *n, struct shr_table *t) -{ - nvme_print(list_item, NORMAL, n, t); -} - -void nvme_show_list_items(struct libnvme_global_ctx *ctx, nvme_print_flags_t flags) -{ - 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) -{ - if (ranking == NVME_CLI_TOPO_NAMESPACE) - nvme_print(topology_namespace, flags, ctx); - else if (ranking == NVME_CLI_TOPO_CTRL) - nvme_print(topology_ctrl, flags, ctx); - else - nvme_print(topology_multipath, flags, ctx); -} - -void nvme_show_topology_tabular(struct libnvme_global_ctx *ctx, nvme_print_flags_t flags) -{ - nvme_print(topology_tabular, flags, ctx); -} - /* * The message helpers keep errno: a caller may report the failure of a * call before it returns its errno. @@ -1163,23 +627,6 @@ void nvme_show_verbose_key_value(const char *key, const char *val, ...) va_end(ap); } -void nvme_show_discovery_log(const struct nvmf_discovery_log *log, - uint64_t numrec, nvme_print_flags_t flags) -{ - nvme_print(discovery_log, flags, log, numrec); -} - -void nvme_show_connect_msg(struct libnvme_ctrl *c, nvme_print_flags_t flags) -{ - nvme_print(connect_msg, flags, c); -} - -void nvme_show_config_conn_list(struct libnvmf_config *config, - nvme_print_flags_t flags) -{ - nvme_print(config_conn_list, flags, config); -} - void nvme_show_init(void) { nvme_print_output_format(show_init); @@ -1198,19 +645,11 @@ void nvme_register_log_decoder(struct nvme_log_decoder *dec) log_decoders = dec; } -/* Plugins that register log page decoders */ -static const char *const log_decoder_plugins[] = { "log", "fdp", "zns" }; - -static bool nvme_show_log_decoded(const char *devname, - enum nvme_cmd_get_log_lid lid, __u32 nsid, - __u16 lsi, __u8 lsp, void *log, __u32 len, - nvme_print_flags_t flags) +bool nvme_show_log_decoded(const char *devname, enum nvme_cmd_get_log_lid lid, + __u32 nsid, __u16 lsi, __u8 lsp, void *log, + __u32 len, nvme_print_flags_t flags) { struct nvme_log_decoder *dec; - size_t i; - - for (i = 0; i < ARRAY_SIZE(log_decoder_plugins); i++) - nvme_load_plugin(log_decoder_plugins[i]); for (dec = log_decoders; dec; dec = dec->next) if (dec->show(devname, lid, nsid, lsi, lsp, log, len, flags)) @@ -1219,29 +658,6 @@ static bool nvme_show_log_decoded(const char *devname, return false; } -void nvme_show_log(const char *devname, enum nvme_cmd_get_log_lid lid, __u32 nsid, __u16 lsi, - __u8 lsp, void *log, __u32 len, nvme_print_flags_t flags) -{ - switch (lid) { - case NVME_LOG_LID_DISCOVERY: { - struct nvmf_discovery_log *discovery_log = log; - /* no more records than the log holds, before size_t cuts it */ - __u64 nr = min_t(__u64, le64_to_cpu(discovery_log->numrec), - len); - - nvme_show_discovery_log(discovery_log, - nvme_log_nr_entries(nr, len, sizeof(*discovery_log), - sizeof(discovery_log->entries[0])), - flags); - break; - } - default: - nvme_show_log_decoded(devname, lid, nsid, lsi, lsp, log, len, - flags); - break; - } -} - const char *nvme_support_str(bool support) { if (support) diff --git a/src/nvme-print.h b/src/nvme-print.h index 539a2abbcc..1ea52ab4cc 100644 --- a/src/nvme-print.h +++ b/src/nvme-print.h @@ -12,7 +12,6 @@ #include "args.h" #include "nvme-json.h" -#include "nvme-regs.h" #include #include #include @@ -43,19 +42,6 @@ typedef struct nvme_effects_log_node { void d(unsigned char *buf, int len, int width, int group); void d_raw(unsigned char *buf, unsigned len); -enum nvme_cli_topo_ranking { - NVME_CLI_TOPO_NAMESPACE, - NVME_CLI_TOPO_CTRL, - NVME_CLI_TOPO_MULTIPATH, -}; - -/* How nvme_show_ctrl_registers() shows the registers */ -enum nvme_regs_style { - NVME_REGS_TABLE, /* show-regs: a row for each */ - NVME_REGS_REGISTER, /* get-reg: "register : offset (name), value" */ - NVME_REGS_PROPERTY, /* get-property: "property : ..." */ -}; - /* * NPSS is a 0's based value. A device can report more power states than * the power state descriptor table holds. @@ -79,27 +65,6 @@ static inline int nvme_id_ns_nr_lbaf(struct nvme_id_ns *ns) return n < max ? n : max; } -/* - * The bytes of the Identify Directive Return Parameters the printers - * decode: the directives supported, enabled and persistent across - * controller level resets. - */ -#define NVME_DIRECTIVE_IDENTIFY_PARAM_LEN 96 - -/* - * The Stream Identifiers of a Streams Directive Get Status data structure - * of @len bytes, which holds at least its Open Stream Count: the count - * the device reports, but at most as many as fit. - */ -static inline int nvme_streams_status_nr_sid( - struct nvme_streams_directive_status *status, __u32 len) -{ - int max = (len - sizeof(*status)) / sizeof(status->sid[0]); - int n = le16_to_cpu(status->osc); - - return n < max ? n : max; -} - /* * A log page counts its entries, but the count comes from the device and * the page may be shorter: a later read can report more entries than the @@ -166,85 +131,13 @@ static inline unsigned int nvme_lbaf_data_size(__u8 ds) return ds < 32 ? 1U << ds : 0; } -static inline bool nvme_is_multipath(struct libnvme_subsystem *s) -{ - struct libnvme_ns *n; - struct libnvme_path *p; - - libnvme_subsystem_for_each_ns(s, n) - libnvme_namespace_for_each_path(n, p) - return true; - - return false; -} - -static inline bool subsystem_iopolicy_filter(const char *name, void *arg) -{ - struct libnvme_subsystem *s = arg; - const char *iopolicy; - - libnvme_subsystem_get_iopolicy(s, &iopolicy, ""); - - if (streq(iopolicy, "queue-depth")) { - /* exclude "Nodes" for iopolicy queue-depth */ - if (streq(name, "Nodes")) - return false; - } else if (streq(iopolicy, "numa")) { - /* exclude "Qdepth" for iopolicy numa */ - if (streq(name, "Qdepth")) - return false; - } else { /* round-robin */ - /* exclude "Nodes" and "Qdepth" for iopolicy round-robin */ - if (streq(name, "Nodes") || streq(name, "Qdepth")) - return false; - } - - return true; -} - - -/* config.h is fabrics-only; forward-declare so this header stays valid in a - * -Dfabrics=disabled build. - */ -struct libnvmf_config; - struct print_ops { /* libnvme types.h print functions */ - void (*ctrl_registers)(const struct nvme_reg_val *vals, unsigned int nr, - enum nvme_regs_style style); - void (*directive)(__u8 type, __u8 oper, __u16 spec, __u32 nsid, __u64 result, void *buf, __u32 len); - void (*discovery_log)(const struct nvmf_discovery_log *log, int numrec); - void (*lba_status)(struct nvme_lba_status *list, unsigned long len); - void (*relatives)(struct libnvme_global_ctx *ctx, const char *name); - void (*resv_report)(struct nvme_resv_status *status, int bytes, bool eds); - void (*select_result)(enum nvme_features_id fid, __u64 result); - void (*show_feature)(enum nvme_features_id fid, int sel, - unsigned int result, void *buf, __u32 data_len); - void (*show_feature_fields)(enum nvme_features_id fid, unsigned int result, unsigned char *buf); - void (*id_ctrl_rpmbs)(__le32 ctrl_rpmbs); - void (*lba_range)(struct nvme_lba_range_type *lbrt, int nr_ranges); - void (*lba_status_info)(__u64 result); void (*d)(unsigned char *buf, int len, int width, int group); void (*show_init)(void); void (*show_finish)(void); - /* libnvme tree print functions */ - void (*list_item)(struct libnvme_ns *n, struct shr_table *t); - void (*list_items)(struct libnvme_global_ctx *ctx); - void (*print_nvme_subsystem_list)(struct libnvme_global_ctx *ctx, bool show_ana); - void (*topology_ctrl)(struct libnvme_global_ctx *ctx); - void (*topology_namespace)(struct libnvme_global_ctx *ctx); - void (*topology_multipath)(struct libnvme_global_ctx *ctx); - void (*topology_tabular)(struct libnvme_global_ctx *ctx); - - /* config show */ - void (*config_conn_list)(struct libnvmf_config *config); - - /* nvme top */ - void (*top)(int refresh_interval); - /* status and error messages */ - void (*connect_msg)(struct libnvme_ctrl *c); void (*show_message)(bool error, const char *msg, va_list ap); void (*show_perror)(const char *msg, va_list ap); void (*show_status)(int status); @@ -285,20 +178,33 @@ bool nvme_show_failed(void); * Documentation/PRIVSEP.md. */ bool nvme_print_decoder_begin(nvme_print_flags_t flags, bool sandbox); +bool nvme_print_decoder_begin_always(nvme_print_flags_t flags, bool sandbox); void nvme_print_decoder_end(nvme_print_flags_t flags); -#define nvme_print_decoder(ops, name, sandbox, flags, ...) \ +#define __nvme_print_decoder(begin, ops, name, sandbox, flags, ...) \ do { \ typeof(ops) __ops = (ops); \ \ if (!__ops || !__ops->name) \ nvme_show_error("unhandled output format"); \ - else if (nvme_print_decoder_begin(flags, sandbox)) { \ + else if (begin(flags, sandbox)) { \ __ops->name(__VA_ARGS__); \ nvme_print_decoder_end(flags); \ } \ } while (false) +#define nvme_print_decoder(ops, name, sandbox, flags, ...) \ + __nvme_print_decoder(nvme_print_decoder_begin, ops, name, \ + sandbox, flags, ##__VA_ARGS__) + +/* + * Like nvme_print_decoder(), but run the printer for dry runs as well. + * A command uses it to show the fields of the value it sets. + */ +#define nvme_print_decoder_always(ops, name, sandbox, flags, ...) \ + __nvme_print_decoder(nvme_print_decoder_begin_always, ops, name, \ + sandbox, flags, ##__VA_ARGS__) + /* * Log page decoder registered by a plugin for get-log -v. ->show returns * true if it decoded the log page. @@ -312,24 +218,20 @@ struct nvme_log_decoder { void nvme_register_log_decoder(struct nvme_log_decoder *dec); +/* Run the registered decoders, true if one of them decoded the log page */ +bool nvme_show_log_decoded(const char *devname, enum nvme_cmd_get_log_lid lid, + __u32 nsid, __u16 lsi, __u8 lsp, void *log, + __u32 len, nvme_print_flags_t flags); + struct print_ops *nvme_get_stdout_print_ops(nvme_print_flags_t flags); struct print_ops *nvme_get_binary_print_ops(nvme_print_flags_t flags); -void stdout_top(int refresh_interval); void nvme_show_status(int status); void nvme_show_err(int err, const char *fmt, ...); void nvme_show_io_cmd_err(const char *msg, __u8 opcode, int err); void nvme_show_admin_cmd_err(const char *msg, __u8 opcode, int err); void nvme_show_opcode_status(int status, bool admin, __u8 opcode); -void nvme_show_lba_status_info(__u64 result); -void nvme_show_relatives(struct libnvme_global_ctx *ctx, const char *name, nvme_print_flags_t flags); - -void nvme_show_id_ctrl_rpmbs(__le32 ctrl_rpmbs, nvme_print_flags_t flags); -void nvme_show_resv_report(struct nvme_resv_status *status, int bytes, bool eds, - nvme_print_flags_t flags); -void nvme_show_lba_range(struct nvme_lba_range_type *lbrt, int nr_ranges, - nvme_print_flags_t flags); /* * The Metadata Element Descriptor at offset *@off of a Host Metadata data @@ -360,58 +262,14 @@ nvme_host_metadata_element(const struct nvme_host_metadata *data, return val; } -void nvme_show_ctrl_registers(const struct nvme_reg_val *vals, unsigned int nr, - enum nvme_regs_style style, - nvme_print_flags_t flags); -void nvme_show_lba_status(struct nvme_lba_status *list, unsigned long len, - nvme_print_flags_t flags); -void nvme_show_list_items(struct libnvme_global_ctx *ctx, nvme_print_flags_t flags); -void nvme_show_subsystem_list(struct libnvme_global_ctx *ctx, bool show_ana, - nvme_print_flags_t flags); -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); -void nvme_show_select_result(enum nvme_features_id fid, __u64 result); - -void nvme_show_list_item(struct libnvme_ns *n, struct shr_table *t); - -void nvme_show_discovery_log(const struct nvmf_discovery_log *log, - uint64_t numrec, nvme_print_flags_t flags); -void nvme_show_connect_msg(struct libnvme_ctrl *c, nvme_print_flags_t flags); -void nvme_show_config_conn_list(struct libnvmf_config *config, - nvme_print_flags_t flags); const char *nvme_cmd_to_string(int admin, __u8 opcode); const char *nvme_fdp_event_to_string(enum nvme_fdp_event_type event); -const char *nvme_feature_lba_type_to_string(__u8 type); -const char *nvme_feature_temp_sel_to_string(__u8 sel); -const char *nvme_feature_temp_type_to_string(__u8 type); -const char *nvme_feature_to_string(enum nvme_features_id feature); -const char *nvme_feature_wl_hints_to_string(__u8 wh); -const char *nvme_feature_perfc_attri_to_string(__u8 attri); -const char *nvme_feature_perfc_r4karl_to_string(__u8 r4karl); -const char *nvme_feature_perfc_attrtyp_to_string(__u8 attrtyp); -const char *nvme_host_metadata_type_to_string(enum nvme_features_id fid, __u8 type); -const char *nvme_select_to_string(int sel); -const char *nvme_plm_window_to_string(__u32 plm); -const char *nvme_ns_wp_cfg_to_string(enum nvme_ns_write_protect_cfg state); const char *nvme_time_scale_to_string(__u8 ts); -const char *nvme_pls_mode_to_string(__u8 mode); -const char *nvme_bpwps_to_string(__u8 bpwps); const char *nvme_feature_power_limit_scale_to_string(__u8 pls); const char *nvme_power_measurement_type_to_string(__u8 pmt); -const char *nvme_power_measurement_action_to_string(__u8 act); const char *nvme_ipmsr_srs_to_string(__u8 srs); -void nvme_dev_full_path(struct libnvme_ns *n, char *path, size_t len); -void nvme_generic_full_path(struct libnvme_ns *n, char *path, size_t len); void nvme_show_message(bool error, const char *msg, ...); void nvme_show_verbose_message(const char *msg, ...); void nvme_show_perror(const char *msg, ...); @@ -428,32 +286,7 @@ const char *nvme_format_timestamp_sync(__u8 attr); void print_array(char *name, __u8 *data, int size); void json_print(struct json_object *r); struct json_object *obj_create_array_obj(struct json_object *o, const char *k); -void json_bitfields(struct json_object *o, const struct bitfield *fields, - unsigned int nr, uint64_t value); -void nvme_show_log(const char *devname, enum nvme_cmd_get_log_lid lid, __u32 nsid, __u16 lsi, - __u8 lsp, void *log, __u32 len, nvme_print_flags_t flags); const char *nvme_support_str(bool support); const char *nvme_yes_str(bool yes); extern const char *alloc_error; -extern const char *feat_ae_dlpcn; -extern const char *feat_ae_hdlpcn; -extern const char *feat_ae_adlpcn; -extern const char *feat_ae_pmdrlpcn; -extern const char *feat_ae_zdcn; -extern const char *feat_ae_rlccn; -extern const char *feat_ae_lhcn; -extern const char *feat_ae_ccrcn; -extern const char *feat_ae_ansan; -extern const char *feat_ae_rgrp0; -extern const char *feat_ae_rassn; -extern const char *feat_ae_tthry; -extern const char *feat_ae_nnsshdn; -extern const char *feat_ae_ega; -extern const char *feat_ae_lbas; -extern const char *feat_ae_pla; -extern const char *feat_ae_ana; -extern const char *feat_ae_telem; -extern const char *feat_ae_fw; -extern const char *feat_ae_nan; -extern const char *feat_ae_smart; diff --git a/src/nvme-resources.c b/src/nvme-resources.c new file mode 100644 index 0000000000..52ac4be8dd --- /dev/null +++ b/src/nvme-resources.c @@ -0,0 +1,97 @@ +// SPDX-License-Identifier: GPL-2.0-or-later + +#include + +#include "nvme-resources.h" + +static void htable_ctrl_add_unique(struct htable_ctrl *ht, + struct libnvme_ctrl *c) +{ + if (htable_ctrl_get(ht, libnvme_ctrl_get_name(c))) + return; + + htable_ctrl_add(ht, c); +} + +static void htable_ns_add_unique(struct htable_ns *ht, struct libnvme_ns *n) +{ + struct htable_ns_iter it; + struct libnvme_ns *_n; + + /* + * Test if namespace pointer is already in the hash, and thus avoid + * inserting severaltimes the same pointer. + */ + for (_n = htable_ns_getfirst(ht, libnvme_ns_get_name(n), &it); + _n; + _n = htable_ns_getnext(ht, libnvme_ns_get_name(n), &it)) { + if (_n == n) + return; + } + htable_ns_add(ht, n); +} + +int nvme_resources_init(struct libnvme_global_ctx *ctx, + struct nvme_resources *res) +{ + struct libnvme_host *h; + struct libnvme_subsystem *s; + struct libnvme_ctrl *c; + struct libnvme_ns *n; + struct libnvme_path *p; + + res->ctx = ctx; + htable_subsys_init(&res->ht_s); + htable_ctrl_init(&res->ht_c); + htable_ns_init(&res->ht_n); + strset_init(&res->subsystems); + strset_init(&res->ctrls); + strset_init(&res->namespaces); + + libnvme_for_each_host(ctx, h) { + libnvme_for_each_subsystem(h, s) { + htable_subsys_add(&res->ht_s, s); + strset_add(&res->subsystems, + libnvme_subsystem_get_name(s)); + + libnvme_subsystem_for_each_ctrl(s, c) { + htable_ctrl_add_unique(&res->ht_c, c); + strset_add(&res->ctrls, + libnvme_ctrl_get_name(c)); + + libnvme_ctrl_for_each_ns(c, n) { + htable_ns_add_unique(&res->ht_n, n); + strset_add(&res->namespaces, + libnvme_ns_get_name(n)); + } + + libnvme_ctrl_for_each_path(c, p) { + n = libnvme_path_get_ns(p); + if (!n) + continue; + htable_ns_add_unique(&res->ht_n, n); + strset_add(&res->namespaces, + libnvme_ns_get_name(n)); + } + } + + libnvme_subsystem_for_each_ns(s, n) { + htable_ns_add_unique(&res->ht_n, n); + strset_add(&res->namespaces, + libnvme_ns_get_name(n)); + } + } + } + + return 0; +} + +void nvme_resources_free(struct nvme_resources *res) +{ + strset_clear(&res->namespaces); + strset_clear(&res->ctrls); + strset_clear(&res->subsystems); + htable_ns_clear(&res->ht_n); + htable_ctrl_clear(&res->ht_c); + htable_subsys_clear(&res->ht_s); +} diff --git a/src/nvme-resources.h b/src/nvme-resources.h new file mode 100644 index 0000000000..069d64f565 --- /dev/null +++ b/src/nvme-resources.h @@ -0,0 +1,68 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#pragma once + +#include + +#include +#include +#include +#include +#include + +/* + * The subsystems, controllers and namespaces of a libnvme tree, by name. + * A namespace may be found more than once under the same name. + */ +static inline const char *subsys_key(const struct libnvme_subsystem *s) +{ + return libnvme_subsystem_get_name((struct libnvme_subsystem *)s); +} + +static inline const char *ctrl_key(const struct libnvme_ctrl *c) +{ + return libnvme_ctrl_get_name((struct libnvme_ctrl *)c); +} + +static inline const char *ns_key(const struct libnvme_ns *n) +{ + return libnvme_ns_get_name((struct libnvme_ns *)n); +} + +static inline bool subsys_cmp(const struct libnvme_subsystem *s, + const char *name) +{ + return streq(libnvme_subsystem_get_name((struct libnvme_subsystem *)s), + name); +} + +static inline bool ctrl_cmp(const struct libnvme_ctrl *c, const char *name) +{ + return streq(libnvme_ctrl_get_name((struct libnvme_ctrl *)c), name); +} + +static inline bool ns_cmp(const struct libnvme_ns *n, const char *name) +{ + return streq(libnvme_ns_get_name((struct libnvme_ns *)n), name); +} + +HTABLE_DEFINE_TYPE(struct libnvme_subsystem, subsys_key, hash_string, + subsys_cmp, htable_subsys); +HTABLE_DEFINE_TYPE(struct libnvme_ctrl, ctrl_key, hash_string, + ctrl_cmp, htable_ctrl); +HTABLE_DEFINE_TYPE(struct libnvme_ns, ns_key, hash_string, + ns_cmp, htable_ns); + +struct nvme_resources { + struct libnvme_global_ctx *ctx; + + struct htable_subsys ht_s; + struct htable_ctrl ht_c; + struct htable_ns ht_n; + struct strset subsystems; + struct strset ctrls; + struct strset namespaces; +}; + +int nvme_resources_init(struct libnvme_global_ctx *ctx, + struct nvme_resources *res); +void nvme_resources_free(struct nvme_resources *res); diff --git a/src/nvme.c b/src/nvme.c index 1e96f833e8..ba00482bfc 100644 --- a/src/nvme.c +++ b/src/nvme.c @@ -54,11 +54,28 @@ static const char nvme_version_string[] = NVME_VERSION; +/* The groups of the top-level commands, in the order of the help */ +static const char *const builtin_groups[] = { + "Device Enumeration", + "Controller Management", + "Deprecated", + "Log Page & Identify", + "Fabrics", + "Features", + "I/O Commands", + "Passthrough", + "Registers", + "Media Management", + "Security & Access Control", + NULL, +}; + struct plugin builtin = { .name = NULL, .desc = NULL, .next = NULL, .tail = &builtin, + .group_order = builtin_groups, }; static struct program nvme = { @@ -165,6 +182,19 @@ int nvme_main(int argc, char **argv) #endif nvme.extensions->parent = &nvme; + + /* + * The top-level commands come from plugins, which may not be loaded + * yet. Start with an empty list. + */ + if (!builtin.commands) { + builtin.commands = calloc(1, sizeof(*builtin.commands)); + if (!builtin.commands) { + fprintf(stderr, "%s: out of memory\n", argv[0]); + return 1; + } + } + if (argc < 2) { general_help(&builtin, NULL); return 0; diff --git a/src/plugin-loader.c b/src/plugin-loader.c index 69dee84841..19215aed92 100644 --- a/src/plugin-loader.c +++ b/src/plugin-loader.c @@ -1,11 +1,13 @@ // SPDX-License-Identifier: GPL-2.0-or-later /* * The plugin modules. nvme loads a module when its plugin is used: by its - * name on the command line, or all of them for the lists of commands. + * name on the command line, or all of them for the lists of commands. A + * module is named after the directory of its plugin, which may differ from + * the name of the plugin, e.g. cmds-id.so for "nvme id". * - * The module .so exports nvme_plugin__abi, the interface it was + * The module .so exports nvme_plugin__abi, the interface it was * built for, and nvme_plugin__init(), which registers its plugin, with - * the name with '_' for '-'. The loader calls it only when the + * the module name with '_' for '-'. The loader calls it only when the * interface is the one of this nvme. */ #include @@ -23,6 +25,7 @@ #include #include +#include "command-index.h" #include "plugin-loader.h" #include "plugin-names.h" @@ -116,7 +119,7 @@ static bool is_loaded(void *handle) return false; } -/* The symbol @sym of the module of plugin @name, see NVME_PLUGIN_INIT() */ +/* The symbol @sym of the module @name, see NVME_PLUGIN_INIT() */ static void *module_sym(void *handle, const char *name, const char *sym) { char buf[NAME_MAX + 32]; @@ -180,7 +183,7 @@ static void load_module(const char *dir, const char *name) init(); } -/* A plugin name, not a path */ +/* A plugin or module name, not a path */ static bool valid_name(const char *name) { size_t len = strspn(name, "abcdefghijklmnopqrstuvwxyz0123456789-_"); @@ -188,34 +191,61 @@ static bool valid_name(const char *name) return len && len <= NAME_MAX - strlen(MODULE_SUFFIX) && !name[len]; } +/* The plugins of this build and their modules */ +static const struct { + const char *name; + const char *module; +} plugins[] = { NVME_PLUGIN_NAMES }; + +/* The module of the plugin @name, or @name for a module name */ +static const char *plugin_module(const char *name) +{ + size_t i; + + for (i = 0; i < ARRAY_SIZE(plugins); i++) { + if (streq(name, plugins[i].name)) + return plugins[i].module; + } + return name; +} + void nvme_load_plugin(const char *name) { + const char *module = plugin_module(name); char path[PATH_MAX]; int len; - if (all_loaded || !valid_name(name)) + if (all_loaded || !valid_name(module)) return; len = snprintf(path, sizeof(path), "%s/%s" MODULE_SUFFIX, - nvme_plugin_dir(), name); + nvme_plugin_dir(), module); if (len < 0 || (size_t)len >= sizeof(path) || access(path, F_OK)) return; - load_module(nvme_plugin_dir(), name); + load_module(nvme_plugin_dir(), module); } bool nvme_plugin_known(const char *name) { - static const char *const names[] = { NVME_PLUGIN_NAMES }; size_t i; - for (i = 0; i < ARRAY_SIZE(names); i++) { - if (streq(name, names[i])) + for (i = 0; i < ARRAY_SIZE(plugins); i++) { + if (streq(name, plugins[i].name)) return true; } return false; } +const struct nvme_command_entry *nvme_command_index(void) +{ + static const struct nvme_command_entry index[] = { + NVME_COMMAND_INDEX + }; + + return index; +} + static int is_module(const struct dirent *entry) { size_t len = strlen(entry->d_name); @@ -225,6 +255,29 @@ static int is_module(const struct dirent *entry) streq(entry->d_name + len - suffix, MODULE_SUFFIX); } +/* The name of the plugin of the module file @file, or the module name */ +static const char *file_plugin(const char *file, char *buf, size_t size) +{ + size_t i; + + snprintf(buf, size, "%.*s", (int)(strlen(file) - strlen(MODULE_SUFFIX)), + file); + for (i = 0; i < ARRAY_SIZE(plugins); i++) { + if (streq(buf, plugins[i].module)) + return plugins[i].name; + } + return buf; +} + +/* Load the modules in the order of their plugin names, not file names */ +static int by_plugin(const struct dirent **a, const struct dirent **b) +{ + char buf_a[NAME_MAX + 1], buf_b[NAME_MAX + 1]; + + return strcmp(file_plugin((*a)->d_name, buf_a, sizeof(buf_a)), + file_plugin((*b)->d_name, buf_b, sizeof(buf_b))); +} + void nvme_load_plugins(void) { struct dirent **entries; @@ -236,14 +289,14 @@ void nvme_load_plugins(void) all_loaded = true; dir = nvme_plugin_dir(); - n = scandir(dir, &entries, is_module, alphasort); + n = scandir(dir, &entries, is_module, by_plugin); if (n < 0) return; for (i = 0; i < n; i++) { char *name = entries[i]->d_name; - /* the plugin name: the file name without the suffix */ + /* the module name: the file name without the suffix */ name[strlen(name) - strlen(MODULE_SUFFIX)] = '\0'; if (valid_name(name)) load_module(dir, name); diff --git a/src/plugin-loader.h b/src/plugin-loader.h index f87b323a90..e45f7350fc 100644 --- a/src/plugin-loader.h +++ b/src/plugin-loader.h @@ -2,6 +2,14 @@ #pragma once #include +#include + +/* A top-level command of a module, see plugin_commands in the plugins */ +struct nvme_command_entry { + const char *name; + const char *alias; + const char *module; +}; #if NVME_PLUGIN_MODULES /* The directory of the plugin modules */ @@ -12,6 +20,8 @@ void nvme_load_plugin(const char *name); void nvme_load_plugins(void); /* Whether @name is a plugin of this build, as a module */ bool nvme_plugin_known(const char *name); +/* The top-level commands of the modules, up to an entry without name */ +const struct nvme_command_entry *nvme_command_index(void); #else static inline const char *nvme_plugin_dir(void) { return "nvme"; } static inline void nvme_load_plugin(const char *name) { (void)name; } @@ -21,4 +31,10 @@ static inline bool nvme_plugin_known(const char *name) (void)name; return false; } +static inline const struct nvme_command_entry *nvme_command_index(void) +{ + static const struct nvme_command_entry index[] = { { NULL } }; + + return index; +} #endif diff --git a/src/plugin.c b/src/plugin.c index 9c76316c86..f78642174d 100644 --- a/src/plugin.c +++ b/src/plugin.c @@ -37,30 +37,99 @@ static int version_cmd(struct plugin *plugin) return 0; } +/* The command of @plugin with the name or alias @name */ +static struct command *find_exact_command(struct plugin *plugin, + const char *name) +{ + struct command **cmd; + + for (cmd = plugin->commands; *cmd; cmd++) { + if (streq(name, (*cmd)->name) || + ((*cmd)->alias && streq(name, (*cmd)->alias))) + return *cmd; + } + return NULL; +} + /* * The command @name selects: an exact name or alias, otherwise the only - * command whose name starts with @name. + * command whose name starts with @name. The top-level commands of the + * modules which aren't loaded take part, from the command index. When + * @name selects one of them, it is returned in @entry instead. */ -static struct command *find_command(struct plugin *plugin, const char *name) +static struct command *lookup_command(struct plugin *plugin, const char *name, + const struct nvme_command_entry **entry) { + const struct nvme_command_entry *e; struct command **cmd, *match = NULL; size_t len = strlen(name); - bool unique = false; + unsigned int n = 0; - for (cmd = plugin->commands; *cmd; cmd++) { - if (streq(name, (*cmd)->name) || - ((*cmd)->alias && streq(name, (*cmd)->alias))) - return *cmd; + *entry = NULL; + match = find_exact_command(plugin, name); + if (match) + return match; + + /* Only the built-in plugin has the top-level commands */ + if (!plugin->name) { + for (e = nvme_command_index(); e->name; e++) { + if (streq(name, e->name) || + (e->alias && streq(name, e->alias))) { + *entry = e; + return NULL; + } + } } for (cmd = plugin->commands; *cmd; cmd++) { if (strncmp(name, (*cmd)->name, len)) continue; - unique = !match; match = *cmd; + n++; } + if (!plugin->name) { + for (e = nvme_command_index(); e->name; e++) { + /* the commands of loaded modules are counted above */ + if (strncmp(name, e->name, len) || + find_exact_command(plugin, e->name)) + continue; + *entry = e; + n++; + } + } + + if (n != 1) { + *entry = NULL; + return NULL; + } + return *entry ? NULL : match; +} - return unique ? match : NULL; +/* + * The command @name selects. A top-level command of a module which isn't + * loaded yet loads it. + */ +static struct command *find_command(struct plugin *plugin, const char *name) +{ + const struct nvme_command_entry *entry; + struct command *cmd; + + cmd = lookup_command(plugin, name, &entry); + if (!entry) + return cmd; + + nvme_load_plugin(entry->module); + return find_exact_command(plugin, entry->name); +} + +/* The top-level command @name selects, of a module which isn't loaded */ +static const struct nvme_command_entry *find_module_command( + struct plugin *plugin, const char *name) +{ + const struct nvme_command_entry *entry; + + lookup_command(plugin, name, &entry); + return entry; } static struct plugin *__find_extension(struct plugin *plugin, const char *name) @@ -209,35 +278,58 @@ static void build_command_usage(char *use, size_t size, struct program *prog, plugin->name, cmd->name, device[cmd->device]); } +/* The position of the group @title in the help of @plugin */ +static int group_rank(struct plugin *plugin, const char *title) +{ + int i; + + if (!plugin->group_order) + return 0; + for (i = 0; plugin->group_order[i]; i++) { + if (shr_streq0(title, plugin->group_order[i])) + break; + } + return i; +} + void plugin_add_group(struct plugin *plugin, const char *title, struct command **commands) { - struct command_group *group, **tail; + struct command_group *group, **pos; struct command **merged; - size_t old_count = 0, new_count = 0; + size_t count = 0, i; + int rank; group = malloc(sizeof(*group)); if (!group) return; group->title = title; group->commands = commands; - group->next = NULL; - for (tail = &plugin->groups; *tail; tail = &(*tail)->next) - ; - *tail = group; + /* before the first group which comes after it */ + rank = group_rank(plugin, title); + for (pos = &plugin->groups; *pos; pos = &(*pos)->next) { + if (group_rank(plugin, (*pos)->title) > rank) + break; + } + group->next = *pos; + *pos = group; - if (plugin->commands) - while (plugin->commands[old_count]) - old_count++; - while (commands[new_count]) - new_count++; + for (group = plugin->groups; group; group = group->next) { + for (i = 0; group->commands[i]; i++) + count++; + } - merged = realloc(plugin->commands, (old_count + new_count + 1) * sizeof(*merged)); + merged = realloc(plugin->commands, (count + 1) * sizeof(*merged)); if (!merged) return; - memcpy(&merged[old_count], commands, (new_count + 1) * sizeof(*merged)); + count = 0; + for (group = plugin->groups; group; group = group->next) { + for (i = 0; group->commands[i]; i++) + merged[count++] = group->commands[i]; + } + merged[count] = NULL; plugin->commands = merged; } @@ -656,7 +748,7 @@ int plugin_lookup(int argc, char **argv, struct plugin *plugin, return 0; /* Only the built-in plugin has extensions */ - if (plugin->name) { + if (plugin->name || find_module_command(plugin, argv[0])) { call->action = PLUGIN_ERROR; call->err = -ENOTTY; call->str = argv[0]; @@ -680,6 +772,7 @@ void plugin_call_free(struct plugin_call *call) int plugin_call_run(struct plugin_call *call) { + const struct nvme_command_entry *entry; struct plugin *plugin = call->plugin; __cleanup_free char *e = NULL; @@ -694,6 +787,14 @@ int plugin_call_run(struct plugin_call *call) general_help(plugin, NULL); return 0; case PLUGIN_ERROR: + entry = call->str && !plugin->name ? + find_module_command(plugin, call->str) : NULL; + if (entry) { + argconfig_error( + "command %s not installed: plugin %s has no module in %s", + entry->name, entry->module, nvme_plugin_dir()); + return call->err; + } if (call->str && !plugin->name && nvme_plugin_known(call->str)) { argconfig_error( diff --git a/src/plugin.h b/src/plugin.h index b28d52e5bf..f54606e770 100644 --- a/src/plugin.h +++ b/src/plugin.h @@ -40,6 +40,12 @@ struct plugin { * flat "core NVMe/NVMeoF plugins" list. */ const char *group; + /* + * The titles of the groups in the order the help lists them, up to + * NULL. A plugin module adds its group at its place. Groups with + * other titles follow, in the order they are added. + */ + const char *const *group_order; }; /* The operand of a command */ @@ -83,6 +89,11 @@ struct command { * files attach to it directly with plugin_add_group() rather than going * through register_extension(), since it's already the root of the * extensions list. + * + * A plugin adds top-level commands the same way, from its + * NVME_PLUGIN_INIT() function, with a title of builtin.group_order. A + * module lists them in plugin_commands in its meson.build: nvme looks up a + * top-level command it doesn't have there and loads the module. */ extern struct plugin builtin; diff --git a/tests/cli/ocp/__init__.py b/tests/cli/cmds_ocp/__init__.py similarity index 100% rename from tests/cli/ocp/__init__.py rename to tests/cli/cmds_ocp/__init__.py diff --git a/tests/cli/ocp/meson.build b/tests/cli/cmds_ocp/meson.build similarity index 100% rename from tests/cli/ocp/meson.build rename to tests/cli/cmds_ocp/meson.build diff --git a/tests/cli/ocp/ocp_clear_pcie_correctable_errors_mock_test.py b/tests/cli/cmds_ocp/ocp_clear_pcie_correctable_errors_mock_test.py similarity index 98% rename from tests/cli/ocp/ocp_clear_pcie_correctable_errors_mock_test.py rename to tests/cli/cmds_ocp/ocp_clear_pcie_correctable_errors_mock_test.py index 683c96dace..cdd078213a 100644 --- a/tests/cli/ocp/ocp_clear_pcie_correctable_errors_mock_test.py +++ b/tests/cli/cmds_ocp/ocp_clear_pcie_correctable_errors_mock_test.py @@ -32,7 +32,7 @@ """ from tests.cli.nvme_mock import (NSID_ALL, OPC_GET_FEATURES, OPC_SET_FEATURES, SC_INVALID_FIELD, main) -from tests.cli.ocp.ocp_mock_test import (CHANGEABLE_CAPABILITIES, SEL_NAMES, +from tests.cli.cmds_ocp.ocp_mock_test import (CHANGEABLE_CAPABILITIES, SEL_NAMES, UUID_INDEX, OCPFeatureController, OCPFeatureTestBase, OCPUUIDTests) diff --git a/tests/cli/ocp/ocp_device_capability_log_mock_test.py b/tests/cli/cmds_ocp/ocp_device_capability_log_mock_test.py similarity index 97% rename from tests/cli/ocp/ocp_device_capability_log_mock_test.py rename to tests/cli/cmds_ocp/ocp_device_capability_log_mock_test.py index 7618252393..220db53555 100644 --- a/tests/cli/ocp/ocp_device_capability_log_mock_test.py +++ b/tests/cli/cmds_ocp/ocp_device_capability_log_mock_test.py @@ -8,7 +8,7 @@ """Tests for "nvme ocp device-capability-log" against a mocked controller. The mock serves a synthetic C4h Device Capabilities page built by -tests/e2e/plugins/ocp/ocp_c4_layout.py, transcribed from the OCP +tests/e2e/plugins/cmds_ocp/ocp_c4_layout.py, transcribed from the OCP specification rather than from nvme-cli's struct. Tests in this module verify: @@ -26,8 +26,8 @@ import json from tests.cli.nvme_mock import main -from tests.cli.ocp.ocp_mock_test import OCPMockTestBase -from tests.e2e.plugins.ocp import ocp_c4_layout as layout +from tests.cli.cmds_ocp.ocp_mock_test import OCPMockTestBase +from tests.e2e.plugins.cmds_ocp import ocp_c4_layout as layout UNKNOWN_GUID_MSG = 'Unknown GUID in C4 Log Page data' READ_FAILURE_MSG = 'Failure reading the C4h Log Page' diff --git a/tests/cli/ocp/ocp_dssd_async_event_config_mock_test.py b/tests/cli/cmds_ocp/ocp_dssd_async_event_config_mock_test.py similarity index 98% rename from tests/cli/ocp/ocp_dssd_async_event_config_mock_test.py rename to tests/cli/cmds_ocp/ocp_dssd_async_event_config_mock_test.py index cc4ea2bf6c..c1b29fafee 100644 --- a/tests/cli/ocp/ocp_dssd_async_event_config_mock_test.py +++ b/tests/cli/cmds_ocp/ocp_dssd_async_event_config_mock_test.py @@ -36,7 +36,7 @@ python3 ocp_dssd_async_event_config_mock_test.py """ from tests.cli.nvme_mock import OPC_SET_FEATURES, main -from tests.cli.ocp.ocp_mock_test import (CHANGEABLE_CAPABILITIES, +from tests.cli.cmds_ocp.ocp_mock_test import (CHANGEABLE_CAPABILITIES, SEL_NAMES, UUID_INDEX, OCPFeatureController, OCPFeatureTestBase, OCPUUIDTests) diff --git a/tests/cli/ocp/ocp_dssd_power_state_mock_test.py b/tests/cli/cmds_ocp/ocp_dssd_power_state_mock_test.py similarity index 98% rename from tests/cli/ocp/ocp_dssd_power_state_mock_test.py rename to tests/cli/cmds_ocp/ocp_dssd_power_state_mock_test.py index 70ef44e8a3..b38fd73935 100644 --- a/tests/cli/ocp/ocp_dssd_power_state_mock_test.py +++ b/tests/cli/cmds_ocp/ocp_dssd_power_state_mock_test.py @@ -31,7 +31,7 @@ """ from tests.cli.nvme_mock import (OPC_GET_FEATURES, OPC_SET_FEATURES, SC_INVALID_FIELD, main) -from tests.cli.ocp.ocp_mock_test import (SEL_NAMES, UUID_INDEX, +from tests.cli.cmds_ocp.ocp_mock_test import (SEL_NAMES, UUID_INDEX, OCPFeatureController, OCPFeatureTestBase, OCPUUIDTests) diff --git a/tests/cli/ocp/ocp_eol_plp_failure_mode_mock_test.py b/tests/cli/cmds_ocp/ocp_eol_plp_failure_mode_mock_test.py similarity index 98% rename from tests/cli/ocp/ocp_eol_plp_failure_mode_mock_test.py rename to tests/cli/cmds_ocp/ocp_eol_plp_failure_mode_mock_test.py index f8992b8ef2..cd5b949e1d 100644 --- a/tests/cli/ocp/ocp_eol_plp_failure_mode_mock_test.py +++ b/tests/cli/cmds_ocp/ocp_eol_plp_failure_mode_mock_test.py @@ -37,7 +37,7 @@ from tests.cli.nvme_mock import (OPC_GET_FEATURES, OPC_SET_FEATURES, SC_INVALID_FIELD, main) -from tests.cli.ocp.ocp_mock_test import (SEL_NAMES, UUID_INDEX, +from tests.cli.cmds_ocp.ocp_mock_test import (SEL_NAMES, UUID_INDEX, OCPFeatureController, OCPFeatureTestBase, OCPUUIDTests) diff --git a/tests/cli/ocp/ocp_error_injection_mock_test.py b/tests/cli/cmds_ocp/ocp_error_injection_mock_test.py similarity index 99% rename from tests/cli/ocp/ocp_error_injection_mock_test.py rename to tests/cli/cmds_ocp/ocp_error_injection_mock_test.py index abbb2ea304..f101879190 100644 --- a/tests/cli/ocp/ocp_error_injection_mock_test.py +++ b/tests/cli/cmds_ocp/ocp_error_injection_mock_test.py @@ -45,7 +45,7 @@ from tests.cli.nvme_mock import (CNS_UUID_LIST, NSID_ALL, OPC_GET_FEATURES, OPC_SET_FEATURES, SC_INVALID_FIELD, Reply, main) -from tests.cli.ocp.ocp_mock_test import (CHANGEABLE_CAPABILITIES, UUID_INDEX, +from tests.cli.cmds_ocp.ocp_mock_test import (CHANGEABLE_CAPABILITIES, UUID_INDEX, OCPFeatureController, OCPFeatureTestBase, OCPUUIDTests) diff --git a/tests/cli/ocp/ocp_error_recovery_log_mock_test.py b/tests/cli/cmds_ocp/ocp_error_recovery_log_mock_test.py similarity index 97% rename from tests/cli/ocp/ocp_error_recovery_log_mock_test.py rename to tests/cli/cmds_ocp/ocp_error_recovery_log_mock_test.py index 856891e1bc..fd08150f8c 100644 --- a/tests/cli/ocp/ocp_error_recovery_log_mock_test.py +++ b/tests/cli/cmds_ocp/ocp_error_recovery_log_mock_test.py @@ -8,7 +8,7 @@ """Tests for "nvme ocp error-recovery-log" against a mocked controller. The mock serves synthetic C1h Error Recovery pages built by -tests/e2e/plugins/ocp/ocp_c1_layout.py, transcribed from the OCP +tests/e2e/plugins/cmds_ocp/ocp_c1_layout.py, transcribed from the OCP specification (2.7 section 4.8.7.2) rather than from nvme-cli's struct. The reports label the fields with the names OCP 2.6 gives them (Panic for what 2.7 calls Error). @@ -31,9 +31,9 @@ import re from tests.cli.nvme_mock import NSID_ALL, main -from tests.cli.ocp.ocp_mock_test import (UUID_INDEX, UUID_SLOT, +from tests.cli.cmds_ocp.ocp_mock_test import (UUID_INDEX, UUID_SLOT, OCPMockTestBase, report_fields) -from tests.e2e.plugins.ocp import ocp_c1_layout as layout +from tests.e2e.plugins.cmds_ocp import ocp_c1_layout as layout UNKNOWN_GUID_MSG = 'Unknown GUID in C1 Log Page data' GUID_TEXT = '0x' + layout.GUID_BYTES[::-1].hex() diff --git a/tests/cli/ocp/ocp_fw_activation_history_mock_test.py b/tests/cli/cmds_ocp/ocp_fw_activation_history_mock_test.py similarity index 97% rename from tests/cli/ocp/ocp_fw_activation_history_mock_test.py rename to tests/cli/cmds_ocp/ocp_fw_activation_history_mock_test.py index 4928e7ad0e..154b60ee55 100644 --- a/tests/cli/ocp/ocp_fw_activation_history_mock_test.py +++ b/tests/cli/cmds_ocp/ocp_fw_activation_history_mock_test.py @@ -9,7 +9,7 @@ clear-fw-activate-history" against a mocked controller. The mock serves synthetic C2h Firmware Activation History pages built by -tests/e2e/plugins/ocp/ocp_c2_layout.py, transcribed from the OCP +tests/e2e/plugins/cmds_ocp/ocp_c2_layout.py, transcribed from the OCP specification 2.0 (section 4.8.7) rather than from nvme-cli's struct. Clear Firmware Update History (FID C1h) is checked against 2.0 section 4.12.4 (CFUH), and what the plugin shows against the plug-in @@ -51,11 +51,11 @@ from tests.cli.nvme_mock import (NSID_ALL, OPC_SET_FEATURES, SC_INVALID_FIELD, Reply, main) -from tests.cli.ocp.ocp_mock_test import (UUID_INDEX, UUID_SLOT, +from tests.cli.cmds_ocp.ocp_mock_test import (UUID_INDEX, UUID_SLOT, OCPController, OCPMockTestBase, OCPUUIDTests) -from tests.e2e.plugins.ocp import ocp_c2_layout as layout -from tests.e2e.plugins.ocp.ocp_c2_layout import Entry +from tests.e2e.plugins.cmds_ocp import ocp_c2_layout as layout +from tests.e2e.plugins.cmds_ocp.ocp_c2_layout import Entry FID_CLEAR_FW_UPDATE_HISTORY = 0xC1 CLEAR = 1 << 31 diff --git a/tests/cli/ocp/ocp_hwcomp_log_mock_test.py b/tests/cli/cmds_ocp/ocp_hwcomp_log_mock_test.py similarity index 98% rename from tests/cli/ocp/ocp_hwcomp_log_mock_test.py rename to tests/cli/cmds_ocp/ocp_hwcomp_log_mock_test.py index b90aeb27d8..fdcc23c47c 100644 --- a/tests/cli/ocp/ocp_hwcomp_log_mock_test.py +++ b/tests/cli/cmds_ocp/ocp_hwcomp_log_mock_test.py @@ -9,7 +9,7 @@ controller. The mock serves synthetic C6h Hardware Component pages built by -tests/e2e/plugins/ocp/ocp_c6_layout.py, transcribed from the OCP +tests/e2e/plugins/cmds_ocp/ocp_c6_layout.py, transcribed from the OCP specification (2.7 section 4.8.13) rather than from nvme-cli's struct. Tests in this module verify: @@ -39,10 +39,10 @@ import unittest from tests.cli.nvme_mock import main -from tests.cli.ocp.ocp_mock_test import (UUID_INDEX, UUID_SLOT, +from tests.cli.cmds_ocp.ocp_mock_test import (UUID_INDEX, UUID_SLOT, OCPMockTestBase) -from tests.e2e.plugins.ocp import ocp_c6_layout as layout -from tests.e2e.plugins.ocp.ocp_c6_layout import Descriptor +from tests.e2e.plugins.cmds_ocp import ocp_c6_layout as layout +from tests.e2e.plugins.cmds_ocp.ocp_c6_layout import Descriptor NO_INFORMATION = 'No information provided' diff --git a/tests/cli/ocp/ocp_idle_wakeup_time_mock_test.py b/tests/cli/cmds_ocp/ocp_idle_wakeup_time_mock_test.py similarity index 98% rename from tests/cli/ocp/ocp_idle_wakeup_time_mock_test.py rename to tests/cli/cmds_ocp/ocp_idle_wakeup_time_mock_test.py index 340f1b4bde..4831469f47 100644 --- a/tests/cli/ocp/ocp_idle_wakeup_time_mock_test.py +++ b/tests/cli/cmds_ocp/ocp_idle_wakeup_time_mock_test.py @@ -34,7 +34,7 @@ import unittest from tests.cli.nvme_mock import NSID_ALL, OPC_GET_FEATURES, main -from tests.cli.ocp.ocp_mock_test import (SEL_NAMES, UUID_INDEX, +from tests.cli.cmds_ocp.ocp_mock_test import (SEL_NAMES, UUID_INDEX, OCPFeatureController, OCPFeatureTestBase, OCPUUIDTests) diff --git a/tests/cli/ocp/ocp_ieee1667_silo_mock_test.py b/tests/cli/cmds_ocp/ocp_ieee1667_silo_mock_test.py similarity index 98% rename from tests/cli/ocp/ocp_ieee1667_silo_mock_test.py rename to tests/cli/cmds_ocp/ocp_ieee1667_silo_mock_test.py index 15148b5b7a..2b6133c20c 100644 --- a/tests/cli/ocp/ocp_ieee1667_silo_mock_test.py +++ b/tests/cli/cmds_ocp/ocp_ieee1667_silo_mock_test.py @@ -38,7 +38,7 @@ from tests.cli.nvme_mock import (OPC_GET_FEATURES, OPC_SET_FEATURES, SC_CMD_SEQ_ERROR, Reply, main) -from tests.cli.ocp.ocp_mock_test import (SEL_NAMES, UUID_INDEX, +from tests.cli.cmds_ocp.ocp_mock_test import (SEL_NAMES, UUID_INDEX, OCPController, OCPFeatureController, OCPFeatureTestBase, OCPMockTestBase, OCPUUIDTests) diff --git a/tests/cli/ocp/ocp_internal_log_event_fifo_mock_test.py b/tests/cli/cmds_ocp/ocp_internal_log_event_fifo_mock_test.py similarity index 99% rename from tests/cli/ocp/ocp_internal_log_event_fifo_mock_test.py rename to tests/cli/cmds_ocp/ocp_internal_log_event_fifo_mock_test.py index ba7a2d78bb..855340c83a 100644 --- a/tests/cli/ocp/ocp_internal_log_event_fifo_mock_test.py +++ b/tests/cli/cmds_ocp/ocp_internal_log_event_fifo_mock_test.py @@ -13,7 +13,7 @@ Telemetry String Log. A real drive only ever produces the events it happens to log, so here the telemetry log and string log are synthetic files (passed with -l and -s) built by -tests/e2e/plugins/ocp/ocp_telemetry_layout.py, and every event class, +tests/e2e/plugins/cmds_ocp/ocp_telemetry_layout.py, and every event class, size boundary and string table lookup is an input. Both the JSON report and the text report (-o normal) are checked; they @@ -73,9 +73,9 @@ import unittest from tests.cli.nvme_mock import main -from tests.cli.ocp.ocp_mock_test import (MODES, STR_DA_EVENT_FIFO_INFO, +from tests.cli.cmds_ocp.ocp_mock_test import (MODES, STR_DA_EVENT_FIFO_INFO, OCPInternalLogTestBase) -from tests.e2e.plugins.ocp import ocp_telemetry_layout as layout +from tests.e2e.plugins.cmds_ocp import ocp_telemetry_layout as layout PHYS_NAMES = {n: f'PHYS FIFO {n:02d}' for n in range(1, layout.MAX_FIFOS + 1)} FIFO_1 = f'EVENT FIFO 1 - {PHYS_NAMES[1]}' diff --git a/tests/cli/ocp/ocp_internal_log_mock_test.py b/tests/cli/cmds_ocp/ocp_internal_log_mock_test.py similarity index 99% rename from tests/cli/ocp/ocp_internal_log_mock_test.py rename to tests/cli/cmds_ocp/ocp_internal_log_mock_test.py index 8f269d9a8b..650da62a1c 100644 --- a/tests/cli/ocp/ocp_internal_log_mock_test.py +++ b/tests/cli/cmds_ocp/ocp_internal_log_mock_test.py @@ -11,7 +11,7 @@ Without -l and -s, internal-log reads the telemetry log and the C9h Telemetry String Log from the drive, saves both, and decodes them; with them it decodes the given files. The mock serves synthetic logs built by -tests/e2e/plugins/ocp/ocp_telemetry_layout.py and records every command, +tests/e2e/plugins/cmds_ocp/ocp_telemetry_layout.py and records every command, so the tests can check how each log was requested as well as how it was decoded. Event FIFO decoding has its own suite, ocp_internal_log_event_fifo_mock_test.py. @@ -72,13 +72,13 @@ LPA_TELEMETRY, NSID_ALL, OPC_GET_LOG_PAGE, OPC_SET_FEATURES, SC_INVALID_FIELD, host_behavior, main) -from tests.cli.ocp.ocp_mock_test import (MODES, STR_DA_EVENT_FIFO_INFO, +from tests.cli.cmds_ocp.ocp_mock_test import (MODES, STR_DA_EVENT_FIFO_INFO, STR_DA_STATS, TEXT_RULE, OCPController, OCPInternalLogTestBase, pack_id_ctrl, parse_text_report, text_fields, text_records) -from tests.e2e.plugins.ocp import ocp_telemetry_layout as layout +from tests.e2e.plugins.cmds_ocp import ocp_telemetry_layout as layout # Get Log Page Log Specific Parameter for the host-initiated log. LSP_RETAIN = 0 diff --git a/tests/cli/ocp/ocp_internal_log_no_json_mock_test.py b/tests/cli/cmds_ocp/ocp_internal_log_no_json_mock_test.py similarity index 96% rename from tests/cli/ocp/ocp_internal_log_no_json_mock_test.py rename to tests/cli/cmds_ocp/ocp_internal_log_no_json_mock_test.py index 3c9e688eeb..422c664fdb 100644 --- a/tests/cli/ocp/ocp_internal_log_no_json_mock_test.py +++ b/tests/cli/cmds_ocp/ocp_internal_log_no_json_mock_test.py @@ -26,9 +26,9 @@ """ import os -from tests.cli.ocp.ocp_internal_log_mock_test import string_log, telemetry_log +from tests.cli.cmds_ocp.ocp_internal_log_mock_test import string_log, telemetry_log from tests.cli.nvme_mock import main -from tests.cli.ocp.ocp_mock_test import (MODES, STR_DA_STATS, +from tests.cli.cmds_ocp.ocp_mock_test import (MODES, STR_DA_STATS, OCPInternalLogTestBase, parse_text_report, text_records) diff --git a/tests/cli/ocp/ocp_latency_monitor_feature_mock_test.py b/tests/cli/cmds_ocp/ocp_latency_monitor_feature_mock_test.py similarity index 98% rename from tests/cli/ocp/ocp_latency_monitor_feature_mock_test.py rename to tests/cli/cmds_ocp/ocp_latency_monitor_feature_mock_test.py index a9db0a1bfb..a819abafbc 100644 --- a/tests/cli/ocp/ocp_latency_monitor_feature_mock_test.py +++ b/tests/cli/cmds_ocp/ocp_latency_monitor_feature_mock_test.py @@ -33,7 +33,7 @@ from tests.cli.nvme_mock import (NSID_ALL, OPC_GET_FEATURES, OPC_SET_FEATURES, main) -from tests.cli.ocp.ocp_mock_test import (SEL_NAMES, UUID_INDEX, +from tests.cli.cmds_ocp.ocp_mock_test import (SEL_NAMES, UUID_INDEX, OCPFeatureController, OCPFeatureTestBase, OCPMockTestBase, OCPUUIDTests) diff --git a/tests/cli/ocp/ocp_latency_monitor_log_mock_test.py b/tests/cli/cmds_ocp/ocp_latency_monitor_log_mock_test.py similarity index 99% rename from tests/cli/ocp/ocp_latency_monitor_log_mock_test.py rename to tests/cli/cmds_ocp/ocp_latency_monitor_log_mock_test.py index 5451a530e6..93d19318b3 100644 --- a/tests/cli/ocp/ocp_latency_monitor_log_mock_test.py +++ b/tests/cli/cmds_ocp/ocp_latency_monitor_log_mock_test.py @@ -8,7 +8,7 @@ """Tests for "nvme ocp latency-monitor-log" against a mocked controller. The mock serves a synthetic C3h Latency Monitor page built by -tests/e2e/plugins/ocp/ocp_c3_layout.py, transcribed from the OCP +tests/e2e/plugins/cmds_ocp/ocp_c3_layout.py, transcribed from the OCP specification rather than from nvme-cli's struct. Tests in this module verify: @@ -46,8 +46,8 @@ from datetime import datetime, timezone from tests.cli.nvme_mock import CNS_UUID_LIST, main -from tests.cli.ocp.ocp_mock_test import OCPMockTestBase -from tests.e2e.plugins.ocp import ocp_c3_layout as layout +from tests.cli.cmds_ocp.ocp_mock_test import OCPMockTestBase +from tests.e2e.plugins.cmds_ocp import ocp_c3_layout as layout UNKNOWN_GUID_MSG = 'Unknown GUID in C3 Log Page data' diff --git a/tests/cli/ocp/ocp_mock_test.py b/tests/cli/cmds_ocp/ocp_mock_test.py similarity index 99% rename from tests/cli/ocp/ocp_mock_test.py rename to tests/cli/cmds_ocp/ocp_mock_test.py index 23cf1333d3..d3cb043ea2 100644 --- a/tests/cli/ocp/ocp_mock_test.py +++ b/tests/cli/cmds_ocp/ocp_mock_test.py @@ -34,7 +34,7 @@ OPC_GET_FEATURES, OPC_SET_FEATURES, MockController, MockTestCase, Reply, id_ctrl, uuid_list) -from tests.e2e.plugins.ocp.ocp_c0_layout import OCP_UUID +from tests.e2e.plugins.cmds_ocp.ocp_c0_layout import OCP_UUID # uuid_slot 1 puts the OCP UUID in the second entry: UUID index 2, so a # command sent with index 0 or 1 shows. diff --git a/tests/cli/ocp/ocp_persistent_event_log_mock_test.py b/tests/cli/cmds_ocp/ocp_persistent_event_log_mock_test.py similarity index 99% rename from tests/cli/ocp/ocp_persistent_event_log_mock_test.py rename to tests/cli/cmds_ocp/ocp_persistent_event_log_mock_test.py index 852092f496..cf9eeec788 100644 --- a/tests/cli/ocp/ocp_persistent_event_log_mock_test.py +++ b/tests/cli/cmds_ocp/ocp_persistent_event_log_mock_test.py @@ -8,7 +8,7 @@ """Tests for "nvme ocp persistent-event-log" against a mocked controller. The mock serves a synthetic Persistent Event log built by -tests/e2e/plugins/ocp/ocp_pel_layout.py, transcribed from the NVM Express +tests/e2e/plugins/cmds_ocp/ocp_pel_layout.py, transcribed from the NVM Express Base specification and the OCP 2.7 TCG Activity Event Format rather than from nvme-cli's structs. It keeps a reporting context as a controller does: Establish Context and Read Log Data (01b) takes a snapshot of the @@ -63,8 +63,8 @@ from tests.cli.nvme_mock import (NSID_ALL, SC_CMD_SEQ_ERROR, SC_INTERNAL, SC_INVALID_FIELD, main) -from tests.cli.ocp.ocp_mock_test import OCPController, OCPMockTestBase -from tests.e2e.plugins.ocp import ocp_pel_layout as layout +from tests.cli.cmds_ocp.ocp_mock_test import OCPController, OCPMockTestBase +from tests.e2e.plugins.cmds_ocp import ocp_pel_layout as layout SHORT_LEN_HINT = 'at least 512 bytes is required' GEN_CHANGED_MSG = 'Collected Persistent Event Log may be invalid' diff --git a/tests/cli/ocp/ocp_plp_health_check_interval_mock_test.py b/tests/cli/cmds_ocp/ocp_plp_health_check_interval_mock_test.py similarity index 98% rename from tests/cli/ocp/ocp_plp_health_check_interval_mock_test.py rename to tests/cli/cmds_ocp/ocp_plp_health_check_interval_mock_test.py index 76d1308600..4566059a07 100644 --- a/tests/cli/ocp/ocp_plp_health_check_interval_mock_test.py +++ b/tests/cli/cmds_ocp/ocp_plp_health_check_interval_mock_test.py @@ -31,7 +31,7 @@ python3 ocp_plp_health_check_interval_mock_test.py """ from tests.cli.nvme_mock import OPC_SET_FEATURES, SC_INVALID_FIELD, main -from tests.cli.ocp.ocp_mock_test import (SEL_NAMES, UUID_INDEX, +from tests.cli.cmds_ocp.ocp_mock_test import (SEL_NAMES, UUID_INDEX, OCPFeatureController, OCPFeatureTestBase, OCPUUIDTests) diff --git a/tests/cli/ocp/ocp_smart_add_log_mock_test.py b/tests/cli/cmds_ocp/ocp_smart_add_log_mock_test.py similarity index 99% rename from tests/cli/ocp/ocp_smart_add_log_mock_test.py rename to tests/cli/cmds_ocp/ocp_smart_add_log_mock_test.py index d6b8f45f4d..35a25f24ce 100644 --- a/tests/cli/ocp/ocp_smart_add_log_mock_test.py +++ b/tests/cli/cmds_ocp/ocp_smart_add_log_mock_test.py @@ -18,7 +18,7 @@ down, since a real drive reports whatever it reports. Field offsets, widths and version gating come from -tests/e2e/plugins/ocp/ocp_c0_layout.py, transcribed from the OCP +tests/e2e/plugins/cmds_ocp/ocp_c0_layout.py, transcribed from the OCP specification rather than from nvme-cli's own struct, so a disagreement between the two shows up as a failure here. @@ -46,8 +46,8 @@ import subprocess from tests.cli.nvme_mock import CNS_UUID_LIST, NSID_ALL, NVME_BIN, main -from tests.cli.ocp.ocp_mock_test import OCPController, OCPMockTestBase -from tests.e2e.plugins.ocp import ocp_c0_layout as layout +from tests.cli.cmds_ocp.ocp_mock_test import OCPController, OCPMockTestBase +from tests.e2e.plugins.cmds_ocp import ocp_c0_layout as layout _OCP_LID_SMART = 0xC0 diff --git a/tests/cli/ocp/ocp_tcg_configuration_log_mock_test.py b/tests/cli/cmds_ocp/ocp_tcg_configuration_log_mock_test.py similarity index 96% rename from tests/cli/ocp/ocp_tcg_configuration_log_mock_test.py rename to tests/cli/cmds_ocp/ocp_tcg_configuration_log_mock_test.py index e7da8bda0e..2706c775a7 100644 --- a/tests/cli/ocp/ocp_tcg_configuration_log_mock_test.py +++ b/tests/cli/cmds_ocp/ocp_tcg_configuration_log_mock_test.py @@ -9,7 +9,7 @@ controller. The mock serves synthetic C7h TCG Configuration pages built by -tests/e2e/plugins/ocp/ocp_c7_layout.py, transcribed from the OCP +tests/e2e/plugins/cmds_ocp/ocp_c7_layout.py, transcribed from the OCP specification (2.7 section 4.8.14, and 2.5 and 2.6 for log page versions 1 and 2) rather than from nvme-cli's struct. @@ -28,9 +28,9 @@ Usage: python3 ocp_tcg_configuration_log_mock_test.py """ from tests.cli.nvme_mock import NSID_ALL, main -from tests.cli.ocp.ocp_mock_test import (UUID_INDEX, UUID_SLOT, +from tests.cli.cmds_ocp.ocp_mock_test import (UUID_INDEX, UUID_SLOT, OCPMockTestBase, report_fields) -from tests.e2e.plugins.ocp import ocp_c7_layout as layout +from tests.e2e.plugins.cmds_ocp import ocp_c7_layout as layout UNKNOWN_GUID_MSG = 'Unknown GUID in C7 Log Page data' GUID_HEX = layout.GUID_BYTES[::-1].hex() diff --git a/tests/cli/ocp/ocp_telemetry_profile_mock_test.py b/tests/cli/cmds_ocp/ocp_telemetry_profile_mock_test.py similarity index 98% rename from tests/cli/ocp/ocp_telemetry_profile_mock_test.py rename to tests/cli/cmds_ocp/ocp_telemetry_profile_mock_test.py index 80b99fcfd8..45e123ef43 100644 --- a/tests/cli/ocp/ocp_telemetry_profile_mock_test.py +++ b/tests/cli/cmds_ocp/ocp_telemetry_profile_mock_test.py @@ -29,7 +29,7 @@ """ from tests.cli.nvme_mock import (NSID_ALL, OPC_GET_FEATURES, OPC_SET_FEATURES, SC_INVALID_FIELD, main) -from tests.cli.ocp.ocp_mock_test import (SEL_NAMES, UUID_INDEX, +from tests.cli.cmds_ocp.ocp_mock_test import (SEL_NAMES, UUID_INDEX, OCPFeatureController, OCPFeatureTestBase, OCPUUIDTests) diff --git a/tests/cli/ocp/ocp_telemetry_string_log_mock_test.py b/tests/cli/cmds_ocp/ocp_telemetry_string_log_mock_test.py similarity index 99% rename from tests/cli/ocp/ocp_telemetry_string_log_mock_test.py rename to tests/cli/cmds_ocp/ocp_telemetry_string_log_mock_test.py index c2790b7b91..9e9695bef1 100644 --- a/tests/cli/ocp/ocp_telemetry_string_log_mock_test.py +++ b/tests/cli/cmds_ocp/ocp_telemetry_string_log_mock_test.py @@ -40,7 +40,7 @@ from tests.cli.nvme_mock import (CNS_UUID_LIST, NSID_ALL, SC_INVALID_FIELD, main) -from tests.cli.ocp.ocp_mock_test import OCPController, OCPMockTestBase +from tests.cli.cmds_ocp.ocp_mock_test import OCPController, OCPMockTestBase _OCP_LID_TELSLG = 0xC9 diff --git a/tests/cli/ocp/ocp_unsupported_reqs_log_mock_test.py b/tests/cli/cmds_ocp/ocp_unsupported_reqs_log_mock_test.py similarity index 96% rename from tests/cli/ocp/ocp_unsupported_reqs_log_mock_test.py rename to tests/cli/cmds_ocp/ocp_unsupported_reqs_log_mock_test.py index eb4e04b23d..fbff8d2386 100644 --- a/tests/cli/ocp/ocp_unsupported_reqs_log_mock_test.py +++ b/tests/cli/cmds_ocp/ocp_unsupported_reqs_log_mock_test.py @@ -8,7 +8,7 @@ """Tests for "nvme ocp unsupported-reqs-log" against a mocked controller. The mock serves synthetic C5h Unsupported Requirements pages built by -tests/e2e/plugins/ocp/ocp_c5_layout.py, transcribed from the OCP +tests/e2e/plugins/cmds_ocp/ocp_c5_layout.py, transcribed from the OCP specification (2.7 section 4.8.12) rather than from nvme-cli's struct. Tests in this module verify: @@ -26,9 +26,9 @@ Usage: python3 ocp_unsupported_reqs_log_mock_test.py """ from tests.cli.nvme_mock import NSID_ALL, main -from tests.cli.ocp.ocp_mock_test import (UUID_INDEX, UUID_SLOT, +from tests.cli.cmds_ocp.ocp_mock_test import (UUID_INDEX, UUID_SLOT, OCPMockTestBase, report_fields) -from tests.e2e.plugins.ocp import ocp_c5_layout as layout +from tests.e2e.plugins.cmds_ocp import ocp_c5_layout as layout UNKNOWN_GUID_MSG = 'Unknown GUID in C5 Log Page data' GUID_HEX = layout.GUID_BYTES[::-1].hex() diff --git a/tests/cli/meson.build b/tests/cli/meson.build index 156e5ef1c7..a21b8cd817 100644 --- a/tests/cli/meson.build +++ b/tests/cli/meson.build @@ -12,6 +12,8 @@ cli_test_env.set('NVME_TEST_JSON', json_c_dep.found() ? '1' : '0') cli_test_env.set('NVME_TEST_LIBARCHIVE', libarchive_dep.found() ? '1' : '0') # Without libkmod, nvme doesn't load the nvme-fabrics module. cli_test_env.set('NVME_TEST_LIBKMOD', libkmod_dep.found() ? '1' : '0') +# get-log is a command of the log plugin. +cli_test_env.set('NVME_TEST_GET_LOG', 'log' in selected_plugins ? '1' : '0') if python3.found() # Standalone CLI test for the ownership registry. It needs no device @@ -90,6 +92,22 @@ if python3.found() suite: 'mock') endif + # The modules of the top-level commands, with the deprecated ones + if want_plugin_modules and want_deprecated_cmds and \ + 'log' in selected_plugins and 'fw' in selected_plugins and \ + 'ns' in selected_plugins + test('nvme-cli - command-modules', + python3, + args: [ + files('nvme_command_modules_test.py'), + nvme_exe, + meson.project_build_root() / 'plugins', + ], + env: cli_test_env, + depends: nvme_runtime, + suite: 'mock') + endif + # nvme top in a pseudo terminal, and its JSON output, on captured sysfs if want_top test('nvme-cli - top', @@ -361,7 +379,7 @@ if python3.found() endif if 'ocp' in selected_plugins - subdir('ocp') + subdir('cmds_ocp') endif if 'netapp' in selected_plugins diff --git a/tests/cli/nvme_command_modules_test.py b/tests/cli/nvme_command_modules_test.py new file mode 100644 index 0000000000..e5437a62a0 --- /dev/null +++ b/tests/cli/nvme_command_modules_test.py @@ -0,0 +1,177 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-or-later +# +# This file is part of nvme-cli. +"""Tests for the top-level commands of the plugin modules. + +nvme loads the module of a top-level command it doesn't have from the +command index. The deprecated commands are such commands: "nvme smart-log" +loads cmds-deprecated.so, which runs "nvme log smart" from cmds-log.so. So are the +I/O commands: "nvme read" loads cmds-io.so. + +Each test runs nvme with NVME_PLUGIN_DIR on a directory with links to some +of the modules, and a file which is no module. nvme reports that file when +it loads all modules, so a test sees when nvme loaded more than it needed. + +Usage: python3 nvme_command_modules_test.py +""" +import os +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +if len(sys.argv) < 3: + print("usage: %s " % sys.argv[0]) + sys.exit(77) + +NVME_BIN = sys.argv[1] +MODULE_DIR = os.path.abspath(sys.argv[2]) +LOAD_ERROR = 'cannot load plugin' +# sysfs trees captured from real systems, from the libnvme tests +SYSFS_DATA = Path(__file__).resolve().parents[2] / 'libnvme/tests/sysfs/data' + + +class CommandModulesTest(unittest.TestCase): + + def setUp(self): + self.dir = tempfile.mkdtemp() + with open(os.path.join(self.dir, 'not-a-module.so'), 'w', + encoding='utf-8') as f: + f.write('not a module\n') + + def tearDown(self): + shutil.rmtree(self.dir) + + def modules(self, *names): + for name in names: + os.symlink(os.path.join(MODULE_DIR, name + '.so'), + os.path.join(self.dir, name + '.so')) + + def nvme(self, *args): + env = dict(os.environ, NVME_PLUGIN_DIR=self.dir) + return subprocess.run([NVME_BIN] + list(args), capture_output=True, + text=True, encoding='utf-8', + stdin=subprocess.DEVNULL, env=env, + check=False) + + def test_all_modules_report_the_file(self): + """The help loads all modules, and reports the file.""" + r = self.nvme('help') + self.assertIn(LOAD_ERROR, r.stderr) + self.assertIn('not-a-module.so', r.stderr) + + def test_command_loads_only_its_module(self): + self.modules('cmds-deprecated', 'cmds-log') + r = self.nvme('smart-log', '--help') + self.assertEqual(r.returncode, 0, r.stderr) + self.assertIn("'smart-log' is deprecated", r.stderr) + self.assertIn('Usage: nvme log smart ', r.stdout) + self.assertNotIn(LOAD_ERROR, r.stderr) + + def test_io_command_loads_only_its_module(self): + self.modules('cmds-io') + r = self.nvme('read', '--help') + self.assertEqual(r.returncode, 0, r.stderr) + self.assertIn('Usage: nvme read ', r.stdout) + self.assertNotIn(LOAD_ERROR, r.stderr) + + def test_list_loads_only_its_module(self): + self.modules('cmds-list') + r = self.nvme('list', '--help') + self.assertEqual(r.returncode, 0, r.stderr) + self.assertIn('Usage: nvme list', r.stdout) + self.assertNotIn(LOAD_ERROR, r.stderr) + + def test_list_module_not_installed(self): + r = self.nvme('list') + self.assertNotEqual(r.returncode, 0) + self.assertEqual(r.stdout, '') + self.assertIn('command list not installed: plugin cmds-list has no ' + 'module in ' + self.dir, r.stderr) + + @unittest.skipUnless(sys.platform.startswith('linux'), + 'the sysfs tree is a Linux one') + def test_zns_list_needs_cmds_list(self): + """zns list prints its rows with the printer of cmds-list.""" + if not os.path.exists(os.path.join(MODULE_DIR, 'cmds-zns.so')): + self.skipTest('nvme has no zns plugin') + self.modules('cmds-zns', 'cmds-list') + sysfs = os.path.join(self.dir, 'sysfs') + os.mkdir(sysfs) + subprocess.run(['tar', 'xJf', SYSFS_DATA / 'tree-pcie.tar.xz', + '-C', sysfs], check=True) + zoned = os.path.join(sysfs, 'sys/class/nvme/nvme0/nvme0n1', + 'queue/zoned') + os.chmod(zoned, 0o644) + with open(zoned, 'w', encoding='utf-8') as f: + f.write('host-managed\n') + r = self.nvme('--set-options', 'test-sysfs-dir=' + sysfs, + 'zns', 'list') + self.assertEqual(r.returncode, 0, r.stderr) + self.assertEqual(r.stdout.splitlines()[2].split()[:3], + ['nvme0n1', 'ng0n1', 'S7DFNG0W700063']) + self.assertNotIn(LOAD_ERROR, r.stderr) + + def test_fabrics_command_loads_only_its_module(self): + if not os.path.exists(os.path.join(MODULE_DIR, 'cmds-fabrics.so')): + self.skipTest('nvme has no fabrics commands') + self.modules('cmds-fabrics') + r = self.nvme('connect-all', '--help') + self.assertEqual(r.returncode, 0, r.stderr) + self.assertIn('Usage: nvme connect-all', r.stdout) + self.assertNotIn(LOAD_ERROR, r.stderr) + + def test_alias(self): + self.modules('cmds-deprecated', 'cmds-fw') + r = self.nvme('fw-activate', '--help') + self.assertEqual(r.returncode, 0, r.stderr) + self.assertIn("'fw-commit' is deprecated", r.stderr) + self.assertIn('Usage: nvme fw commit ', r.stdout) + self.assertNotIn(LOAD_ERROR, r.stderr) + + def test_prefix(self): + self.modules('cmds-deprecated', 'cmds-log') + r = self.nvme('smart-lo', '--help') + self.assertEqual(r.returncode, 0, r.stderr) + self.assertIn('Usage: nvme log smart ', r.stdout) + self.assertNotIn(LOAD_ERROR, r.stderr) + + def test_ambiguous_prefix_loads_no_command_module(self): + """"ns" starts ns-rescan and the deprecated ns-descs: it is the + plugin ns.""" + self.modules('cmds-ns') + r = self.nvme('ns', 'create', '--help') + self.assertEqual(r.returncode, 0, r.stderr) + self.assertIn('Usage: nvme ns create ', r.stdout) + self.assertNotIn(LOAD_ERROR, r.stderr) + + def test_unknown_command(self): + r = self.nvme('zzz') + self.assertNotEqual(r.returncode, 0) + self.assertEqual(r.stdout, '') + self.assertIn("invalid sub-command 'zzz'", r.stderr) + self.assertIn("See 'nvme --help' for the commands.", r.stderr) + + def test_module_not_installed(self): + self.modules('cmds-log') + r = self.nvme('smart-log', '/dev/nvme0') + self.assertNotEqual(r.returncode, 0) + self.assertEqual(r.stdout, '') + self.assertIn('command smart-log not installed: plugin cmds-deprecated ' + 'has no module in ' + self.dir, r.stderr) + self.assertNotIn(LOAD_ERROR, r.stderr) + + def test_io_module_not_installed(self): + r = self.nvme('read', '/dev/nvme0n1') + self.assertNotEqual(r.returncode, 0) + self.assertEqual(r.stdout, '') + self.assertIn('command read not installed: plugin cmds-io has no ' + 'module in ' + self.dir, r.stderr) + self.assertNotIn(LOAD_ERROR, r.stderr) + + +if __name__ == '__main__': + unittest.main(argv=sys.argv[:1]) diff --git a/tests/cli/nvme_dir_receive_test.py b/tests/cli/nvme_dir_receive_test.py index 3988297348..84aa56cd89 100644 --- a/tests/cli/nvme_dir_receive_test.py +++ b/tests/cli/nvme_dir_receive_test.py @@ -93,6 +93,14 @@ def test_identify_too_short(self): result = self._receive(DTYPE_IDENTIFY, 1, '--data-len=16') self.assertIn(TOO_SHORT, result.stderr) + def test_decoded_in_sandbox(self): + for args in ([], ['--verbose']): + with self.subTest(args=args): + self.assertDecodedInSandbox( + 'dir', 'receive', self.ctrl, + f'--dir-type={DTYPE_STREAMS}', + f'--dir-oper={DOPER_STREAMS_STATUS}', *args) + def test_namespace_id(self): """The namespace of a namespace device, namespace 1 of a controller device, unless --namespace-id is given""" diff --git a/tests/cli/nvme_fabrics_mock_test.py b/tests/cli/nvme_fabrics_mock_test.py index c7e55a88ae..4606e620ed 100644 --- a/tests/cli/nvme_fabrics_mock_test.py +++ b/tests/cli/nvme_fabrics_mock_test.py @@ -16,15 +16,17 @@ Usage: python3 nvme_fabrics_mock_test.py """ import errno +import json +import os import shutil import struct import unittest from pathlib import Path -from tests.cli.nvme_mock import (CNS_CTRL, HAVE_LIBKMOD, MockController, - MockTestCase, Reply, id_ctrl, main, - write_sysfs_ctrl) -from tests.cli.nvme_mock_ipc import NIC_QUEUES_FMT +from tests.cli.nvme_mock import (CNS_CTRL, HAVE_JSON, HAVE_LIBKMOD, + MockController, MockTestCase, Reply, id_ctrl, + main, write_sysfs_ctrl) +from tests.cli.nvme_mock_ipc import NIC_QUEUES_FMT, run_nvme # The vendor defaults libnvme ships. VENDOR_D = Path(__file__).resolve().parents[2] / 'libnvme/sysfiles/vendor.d' @@ -317,6 +319,89 @@ def test_discover_simple(self): self.assertIn("192.168.1.200", res.stdout) self.assertIn("4420", res.stdout) + _DLP_NQN = 'nqn.2014-08.org.nvmexpress:mock-dlp-subsystem' + + def _one_dlp_entry(self): + self.server.discovery_entries = [ + {'traddr': '192.168.1.201', 'subsysnqn': self._DLP_NQN}, + ] + + def test_discover_json(self): + """discover -o json lists the records of the log page.""" + if not HAVE_JSON: + self.skipTest('needs json-c') + self._one_dlp_entry() + res = self._run('discover', '-t', 'tcp', '-a', '192.168.1.1', + '-o', 'json') + (rec,) = json.loads(res.stdout)['records'] + self.assertEqual(rec['subnqn'], self._DLP_NQN) + self.assertEqual(rec['traddr'], '192.168.1.201') + + def test_discover_decodes_in_sandbox(self): + """discover decodes the log page of the DC in the sandbox.""" + self._one_dlp_entry() + self.assertDecodedInSandbox('discover', '-t', 'tcp', + '-a', '192.168.1.1') + + def test_get_log_decodes_discovery_log(self): + """get-log --verbose decodes a Discovery log page, in text and + in JSON.""" + self._one_dlp_entry() + args = ('get-log', self.ctrl, '--log-id=0x70', '--log-len=2048', + '--verbose') + res = self._run(*args) + self.assertIn('Discovery Log Number of Records 1', res.stdout) + self.assertIn('=====Discovery Log Entry 0======', res.stdout) + self.assertIn(self._DLP_NQN, res.stdout) + if not HAVE_JSON: + return + res = self._run(*args, '-o', 'json') + (rec,) = json.loads(res.stdout)['records'] + self.assertEqual(rec['subnqn'], self._DLP_NQN) + + def _config_show_conf(self): + if self.nvme('config', 'show', '--help').returncode: + self.skipTest('nvme has no config plugin') + conf = Path(self.base_dir) / 'show.conf' + conf.write_text( + '[Subsystem]\n' + 'nqn = nqn.2014-08.org.nvmexpress:show\n' + 'controller = transport=tcp;traddr=192.168.50.10;' + 'trsvcid=4420\n') + return str(conf) + + def test_config_show(self): + """config show prints the connections, in text and in JSON.""" + conf = self._config_show_conf() + res = self._run('config', 'show', '-J', conf) + self.assertIn('nvme connect', res.stdout) + self.assertIn('--traddr=192.168.50.10', res.stdout) + if not HAVE_JSON: + return + res = self._run('config', 'show', '-J', conf, '-o', 'json') + (conn,) = json.loads(res.stdout)['connections'] + self.assertEqual(conn['traddr'], '192.168.50.10') + self.assertEqual(conn['nqn'], 'nqn.2014-08.org.nvmexpress:show') + + def test_config_show_in_process(self): + """config show reads no device data: it prints in process, also + with the sandbox on and no child process allowed.""" + if os.geteuid() == 0: + self.skipTest('process limits do not apply to root') + conf = self._config_show_conf() + wrapper = Path(self.tmp) / 'nvme-no-fork' + wrapper.write_text('#!/bin/sh\nulimit -u 1 || exit 99\n' + 'exec "$REAL_NVME" "$@"\n') + wrapper.chmod(0o755) + env = dict(self.env, REAL_NVME=self.nvme_bin, NVME_SANDBOX='1') + env.pop('NVME_PRIVSEP_TEST_HELPER', None) + res = run_nvme(str(wrapper), env, self.sysfs_dir, self.base_dir, + 'config', 'show', '-J', conf) + if res.returncode == 99: + self.skipTest('ulimit -u not supported') + self.assertOk(res) + self.assertIn('--traddr=192.168.50.10', res.stdout) + def test_connect_simple(self): """Test connecting to a single target.""" subsysnqn = "nqn.2014-08.org.nvmexpress:my-io-subsys-1" diff --git a/tests/cli/nvme_fdp_test.py b/tests/cli/nvme_fdp_test.py index 4e2c50b8b0..ffe02ea5e9 100644 --- a/tests/cli/nvme_fdp_test.py +++ b/tests/cli/nvme_fdp_test.py @@ -13,8 +13,8 @@ """ import struct -from tests.cli.nvme_mock import (HAVE_JSON, NVME_IOCTL_ID, MockTestCase, - Reply, main) +from tests.cli.nvme_mock import (HAVE_GET_LOG, HAVE_JSON, NVME_IOCTL_ID, + MockTestCase, Reply, main) LID_FDP_CONFIGS = 0x20 LID_FDP_RUH_USAGE = 0x21 @@ -67,6 +67,11 @@ def setUp(self): class FdpGetLogTest(FdpTestCase): + def setUp(self): + super().setUp() + if not HAVE_GET_LOG: + self.skipTest('built without the log plugin') + def get_log(self, lid, *args): log = _LOGS[lid][0] result = self.nvme('get-log', self.ctrl, f'--log-id={lid:#x}', diff --git a/tests/cli/nvme_features_test.py b/tests/cli/nvme_features_test.py index 89e304c533..f239bec36a 100644 --- a/tests/cli/nvme_features_test.py +++ b/tests/cli/nvme_features_test.py @@ -19,9 +19,10 @@ import os import struct -from tests.cli.nvme_mock import (FID_HOST_BEHAVIOR, NSID_ALL, NVME_IOCTL_ID, - OPC_GET_FEATURES, OPC_SET_FEATURES, - MockTestCase, Reply, host_behavior, main) +from tests.cli.nvme_mock import (FID_HOST_BEHAVIOR, HAVE_JSON, NSID_ALL, + NVME_IOCTL_ID, OPC_GET_FEATURES, + OPC_SET_FEATURES, MockTestCase, Reply, + host_behavior, main) SV = 1 << 31 @@ -413,5 +414,35 @@ def test_lba_range_type_count_mismatch(self): self.assertEqual(self.set_features(), []) +class DryRunTest(FeaturesTestBase): + """--dry-run sends no Set Features. The feat commands still show the + fields of the value they would set, the other decoders don't run.""" + + def test_feat_shows_the_fields(self): + for fmt, expected in ( + ([], 'Volatile Write Cache Enable (WCE) : Enabled\n'), + (['--output-format=json'], + '"Volatile Write Cache Enable (WCE)":"Enabled"')): + if fmt and not HAVE_JSON: + continue + with self.subTest(fmt=fmt): + result = self.assertOk(self.nvme('feat', 'volatile-wc', + self.ctrl, '--wce', + '--dry-run', *fmt)) + self.assertIn(expected, result.stdout) + self.assertEqual(self.set_features(), []) + + def test_set_feature_skips_the_decoder(self): + args = ('set-feature', self.ctrl, '--feature-id=0x15', + '--value=0x10002') + result = self.assertOk(self.nvme(*args)) + self.assertIn('Information Poll Interval (LSIPI)', result.stdout) + + self.server.commands.clear() + result = self.assertOk(self.nvme(*args, '--dry-run')) + self.assertNotIn('Information Poll Interval', result.stdout) + self.assertEqual(self.set_features(), []) + + if __name__ == '__main__': main() diff --git a/tests/cli/nvme_fuzz_record_test.py b/tests/cli/nvme_fuzz_record_test.py index 02f924f135..cfb23b7d70 100644 --- a/tests/cli/nvme_fuzz_record_test.py +++ b/tests/cli/nvme_fuzz_record_test.py @@ -16,8 +16,8 @@ from pathlib import Path from tests.cli import nvme_mock_ipc -from tests.cli.nvme_mock import (OPC_GET_LOG_PAGE, SC_INVALID_FIELD, - MockTestCase, main) +from tests.cli.nvme_mock import (HAVE_GET_LOG, OPC_GET_LOG_PAGE, + SC_INVALID_FIELD, MockTestCase, main) from tests.cli.nvme_mock_ipc import MockIPCServer _LOG_LEN = 512 @@ -59,6 +59,8 @@ def setUp(self): nvme_mock_ipc._fuzz_recorder.dir = self.record_dir def _record(self, *args): + if not args and not HAVE_GET_LOG: + self.skipTest('built without the log plugin') args = args or ('get-log', self.ctrl, '--log-id=2', f'--log-len={_LOG_LEN}') result = self.nvme(*args) @@ -93,6 +95,8 @@ def test_pci_ids(self): self.assertEqual(self._record()['pci'], [0x1344, 0x51c0]) def test_off(self): + if not HAVE_GET_LOG: + self.skipTest('built without the log plugin') nvme_mock_ipc._fuzz_recorder.dir = None self.nvme('get-log', self.ctrl, '--log-id=2', '--log-len=512') self.assertEqual(list(Path(self.record_dir).iterdir()), []) diff --git a/tests/cli/nvme_io_test.py b/tests/cli/nvme_io_test.py index a96d9c904b..18018df2f7 100644 --- a/tests/cli/nvme_io_test.py +++ b/tests/cli/nvme_io_test.py @@ -8,16 +8,19 @@ """Tests the NVM command set I/O commands: flush, dsm, write-zeroes, write-uncor, verify, read, write, compare and copy, and the admin command get-lba-status. Checks the fields and data of the commands against the -NVM Express NVM Command Set Specification 1.3. +NVM Express NVM Command Set Specification 1.3, and the output of +get-lba-status. Usage: python3 nvme_io_test.py """ +import json import os import struct -from tests.cli.nvme_mock import (CNS_NS, NVME_IOCTL_ID, OPC_NVM_READ, - OPC_NVM_WRITE, MockTestCase, Reply, id_ns, - main) +from tests.cli.nvme_mock import (CNS_NS, HAVE_JSON, NVME_IOCTL_ID, + OPC_NVM_READ, OPC_NVM_WRITE, MockTestCase, + Reply, id_ns, main) +from tests.cli.nvme_mock_ipc import run_nvme OPC_NVM_FLUSH = 0x00 OPC_NVM_COMPARE = 0x05 @@ -341,6 +344,15 @@ def test_invalid(self): OPC_NVM_COPY) +def lba_status(): + """An LBA Status Data with two descriptors, the scan completed""" + # NLSD, CMPC; per descriptor DSLBA, NLB, Status + data = struct.pack(' """Tests for get_pif_sts()/get_pif_sts_via_qpif() and invalid_tags() in -src/nvme-cmds-io.c. +plugins/cmds-io/cmds-io-plugin.c. Usage: python3 nvme_pif_sts_test.py """ diff --git a/tests/cli/nvme_print_test.py b/tests/cli/nvme_print_test.py index 9a16a2e41a..71acec13d3 100644 --- a/tests/cli/nvme_print_test.py +++ b/tests/cli/nvme_print_test.py @@ -158,7 +158,9 @@ def answer(self, cmd): ['dir', 'receive', 'NS', '-D', '0', '-O', '1'], ['dir', 'receive', 'NS', '-D', '1', '-O', '1'], ['dir', 'receive', 'NS', '-D', '1', '-O', '2', '-l', '64'], - ['dir', 'receive', 'NS', '-D', '1', '-O', '3']] + ['dir', 'receive', 'NS', '-D', '1', '-O', '3'], + ['rpmb', 'info'], + ['get-lba-status', 'NS', '-a', '2', '-m', '15']] _FORMATS = [[], ['-v'], ['-o', 'json'], ['-o', 'binary']] # sysfs trees captured from real systems, from the libnvme tests. diff --git a/tests/cli/nvme_privsep_test.py b/tests/cli/nvme_privsep_test.py index 93bad50d8e..1daeb55f57 100644 --- a/tests/cli/nvme_privsep_test.py +++ b/tests/cli/nvme_privsep_test.py @@ -59,6 +59,15 @@ def test_needs_root_command_skips_helper(self): result = self.nvme('/nonexistent/nvme-privsep-helper', 'list') self.assertNotIn(_HELPER_ERROR, result.stderr) + def test_module_needs_root_command_skips_helper(self): + """A command of a module which keeps root does not start the + helper either: nvme loads the module before it decides.""" + if self.nvme(None, 'show-hostnqn', '--help').returncode: + self.skipTest('nvme has no fabrics commands') + result = self.nvme('/nonexistent/nvme-privsep-helper', + 'show-hostnqn') + self.assertNotIn(_HELPER_ERROR, result.stderr) + def test_mi_device_skips_helper(self): """An MI device keeps root, a file named like one does not.""" result = self.nvme('/nonexistent/nvme-privsep-helper', diff --git a/tests/cli/nvme_registers_test.py b/tests/cli/nvme_registers_test.py index db2ab8a919..6ff8bd031e 100644 --- a/tests/cli/nvme_registers_test.py +++ b/tests/cli/nvme_registers_test.py @@ -516,6 +516,20 @@ def test_set_reg_read_only_name(self): self.assertNotEqual(result.returncode, 0) self.assertEqual(self.regs(), self.expected()) + def test_show_regs_binary(self): + """The registers as they are in BAR0, 0h to E1Bh""" + result = self.nvme('show-regs', self.ctrl, '--output-format=binary', + encoding=None) + self.assertOk(result) + self.assertEqual(result.stdout, self.resource0.read_bytes()[:0xe1c]) + + def test_decoded_in_sandbox(self): + for cmd in (['show-regs'], ['get-reg', '--register=cc']): + for args in ([], ['--verbose'], ['--output-format=binary']): + with self.subTest(cmd=cmd, args=args): + self.assertDecodedInSandbox(cmd[0], self.ctrl, + *cmd[1:], *args) + class FabricsRegsTest(MockTestCase): """A fabrics controller, whose properties are REGS""" @@ -590,6 +604,12 @@ def test_get_property(self): 'property : 0000 (Controller Capabilities), ' 'value: 0x2028030fff') + def test_decoded_in_sandbox(self): + for args in ([], ['--verbose']): + with self.subTest(args=args): + self.assertDecodedInSandbox('get-property', self.ctrl, + '--offset=0', *args) + def test_get_property_json(self): """The same as show-regs, for the property asked for, also one out of the register table""" diff --git a/tests/cli/nvme_resv_test.py b/tests/cli/nvme_resv_test.py index 4f8ae71fe6..3f31e07b9f 100644 --- a/tests/cli/nvme_resv_test.py +++ b/tests/cli/nvme_resv_test.py @@ -151,6 +151,13 @@ def test_numd(self): cmd, = self.resv(OPC_RESV_REPORT, 'report', self.ns, '--numd=11') self.assertEqual((cmd.cdw10, cmd.data_len), (11, 48)) + def test_decoded_in_sandbox(self): + self.server.io[OPC_RESV_REPORT] = resv_status(2) + for args in ([], ['--eds']): + with self.subTest(args=args): + self.assertDecodedInSandbox('resv', 'report', self.ns, + *args) + if __name__ == '__main__': main() diff --git a/tests/cli/nvme_rpmb_test.py b/tests/cli/nvme_rpmb_test.py index b22bf017bd..7b25e816d5 100644 --- a/tests/cli/nvme_rpmb_test.py +++ b/tests/cli/nvme_rpmb_test.py @@ -5,20 +5,21 @@ # Copyright (c) 2026 SUSE LLC # # Authors: Daniel Wagner -"""Tests the files of the rpmb plugin: an absolute --msgfile names the -file to write as it is, not one below the current directory, -read-data writes the sectors it read, read-counter reads the write -counter, and write-data / write-config write authenticated frames. +"""Tests the rpmb plugin: an absolute --msgfile names the file to write +as it is, not one below the current directory, info decodes the RPMBS +field, read-data writes the sectors it read, read-counter reads the +write counter, and write-data / write-config write authenticated frames. Usage: python3 nvme_rpmb_test.py """ import hashlib import hmac +import json import os import struct -from tests.cli.nvme_mock import (CNS_CTRL, OPC_SECURITY_RECV, MockTestCase, - id_ctrl, main) +from tests.cli.nvme_mock import (CNS_CTRL, HAVE_JSON, OPC_SECURITY_RECV, + MockTestCase, id_ctrl, main) _CONFIG_BLOCK_SIZE = 512 _SECTOR = 512 @@ -72,6 +73,39 @@ def test_absolute_msgfile(self): self.assertEqual(os.path.getsize(path), _CONFIG_BLOCK_SIZE) +class RpmbInfoTest(MockTestCase): + """info decodes the RPMBS field of Identify Controller""" + + def setUp(self): + super().setUp() + self.server.identify[CNS_CTRL] = id_ctrl(rpmbs=0x12340a5b) + + def test_info(self): + result = self.assertOk(self.nvme('rpmb', 'info', self.ctrl)) + self.assertEqual(result.stdout, + ' [31:24] : 0x12 Access Size\n' + ' [23:16] : 0x34 Total Size\n' + ' [15:6] : 0x29 Reserved\n' + ' [5:3] : 0x3 Authentication Method\n' + ' [2:0] : 0x3 Number of RPMB Units\n' + '\n') + + def test_info_json(self): + if not HAVE_JSON: + self.skipTest('built without json-c') + result = self.assertOk(self.nvme('rpmb', 'info', self.ctrl, + '-o', 'json')) + self.assertEqual(json.loads(result.stdout), + {'[31:24]: Access Size': '0x12', + '[23:16]: Total Size': '0x34', + '[15:6]: Reserved': '0x29', + '[5:3]: Authentication Method': '0x3', + '[2:0]: Number of RPMB Units': '0x3'}) + + def test_info_decoded_in_sandbox(self): + self.assertDecodedInSandbox('rpmb', 'info', self.ctrl) + + class RpmbReadDataTest(MockTestCase): """A controller with one RPMB target which transfers a sector at a time, and answers each authenticated data read with the sectors it diff --git a/tests/cli/nvme_sed_test.py b/tests/cli/nvme_sed_test.py index 5cbfca0c91..29fa7e3727 100644 --- a/tests/cli/nvme_sed_test.py +++ b/tests/cli/nvme_sed_test.py @@ -5,7 +5,7 @@ # Copyright (c) 2026 SUSE LLC # # Authors: Daniel Wagner -"""Tests for the sed plugin (plugins/sed/) and the libnvme sed module +"""Tests for the sed plugin (plugins/cmds-sed/) and the libnvme sed module it uses. Level 0 Discovery is answered as an admin passthru Security Receive. The Opal operations are kernel ioctls, which libmock_nvme.c forwards raw. The test decodes their arguments and checks them. diff --git a/tests/cli/nvme_zns_test.py b/tests/cli/nvme_zns_test.py index 4ae89b5ea4..242883e794 100644 --- a/tests/cli/nvme_zns_test.py +++ b/tests/cli/nvme_zns_test.py @@ -13,9 +13,9 @@ """ import os -from tests.cli.nvme_mock import (CNS_CSI_NS, CNS_NS, HAVE_JSON, - NVME_IOCTL_ID, MockTestCase, Reply, id_ns, - main) +from tests.cli.nvme_mock import (CNS_CSI_NS, CNS_NS, HAVE_GET_LOG, + HAVE_JSON, NVME_IOCTL_ID, MockTestCase, + Reply, id_ns, main) from tests.cli.nvme_mock_ipc import run_nvme OPC_ZONE_MGMT_SEND = 0x79 @@ -257,6 +257,8 @@ def test_decoded_in_sandbox(self): def test_get_log_decoded(self): """get-log -v decodes the Changed Zone List log through the plugin, with and without the sandbox.""" + if not HAVE_GET_LOG: + self.skipTest('built without the log plugin') out = [] for sandbox in ('0', '1'): result = run_nvme(self.nvme_bin, diff --git a/tests/e2e/plugins/README.md b/tests/e2e/plugins/README.md index 30ea3342dc..75e22376db 100644 --- a/tests/e2e/plugins/README.md +++ b/tests/e2e/plugins/README.md @@ -92,7 +92,7 @@ meson test -C .build "ocp - e2e-smart-add-log" ## Writing a New Test 1. Create a file in the appropriate plugin directory (e.g., - `tests/e2e/plugins/ocp/ocp_smart_add_log_test.py`). + `tests/e2e/plugins/cmds_ocp/ocp_smart_add_log_test.py`). 2. Inherit from the plugin base class and write test methods. diff --git a/tests/e2e/plugins/ocp/__init__.py b/tests/e2e/plugins/cmds_ocp/__init__.py similarity index 100% rename from tests/e2e/plugins/ocp/__init__.py rename to tests/e2e/plugins/cmds_ocp/__init__.py diff --git a/tests/e2e/plugins/ocp/meson.build b/tests/e2e/plugins/cmds_ocp/meson.build similarity index 91% rename from tests/e2e/plugins/ocp/meson.build rename to tests/e2e/plugins/cmds_ocp/meson.build index 2decbafaf7..c75e5ca2a7 100644 --- a/tests/e2e/plugins/ocp/meson.build +++ b/tests/e2e/plugins/cmds_ocp/meson.build @@ -20,7 +20,7 @@ foreach t : ocp_tests e2e_runner, '--source-root', meson.project_source_root(), '--config', e2e_config_file, - 'tests.e2e.plugins.ocp.@0@'.format(t_name), + 'tests.e2e.plugins.cmds_ocp.@0@'.format(t_name), ], env: test_env, timeout: 500, diff --git a/tests/e2e/plugins/ocp/ocp_c0_layout.py b/tests/e2e/plugins/cmds_ocp/ocp_c0_layout.py similarity index 99% rename from tests/e2e/plugins/ocp/ocp_c0_layout.py rename to tests/e2e/plugins/cmds_ocp/ocp_c0_layout.py index 59f213756f..c0f7098cdf 100644 --- a/tests/e2e/plugins/ocp/ocp_c0_layout.py +++ b/tests/e2e/plugins/cmds_ocp/ocp_c0_layout.py @@ -16,7 +16,7 @@ away here. * `stdout_label`, `v1_key` and `v2_key` are nvme-cli's own output names, which no spec dictates. Those are taken from the printers in - plugins/ocp/ocp-print-{stdout,json}.c and are expected to track + plugins/cmds-ocp/ocp-print-{stdout,json}.c and are expected to track them. `kind` describes how a field is encoded on the wire *and* how the @@ -42,7 +42,7 @@ LOG_PAGE_SIZE = 512 -# scao_guid in plugins/ocp/ocp-smart-extended-log.c, on the wire. +# scao_guid in plugins/cmds-ocp/ocp-smart-extended-log.c, on the wire. SCAO_GUID_BYTES = bytes(( 0xC5, 0xAF, 0x10, 0x28, 0xEA, 0xBF, 0xF2, 0xA4, @@ -50,7 +50,7 @@ 0xC9, 0x14, 0xD5, 0xAF, )) -# ocp_uuid in plugins/ocp/ocp-utils.c: the vendor UUID whose index in the +# ocp_uuid in plugins/cmds-ocp/ocp-utils.c: the vendor UUID whose index in the # drive's UUID list goes into CDW14[6:0] of the Get Log Page command. OCP_UUID = bytes(( 0xC1, 0x94, 0xD5, 0x5B, 0xE0, 0x94, 0x47, 0x94, 0xA2, 0x1D, diff --git a/tests/e2e/plugins/ocp/ocp_c1_layout.py b/tests/e2e/plugins/cmds_ocp/ocp_c1_layout.py similarity index 100% rename from tests/e2e/plugins/ocp/ocp_c1_layout.py rename to tests/e2e/plugins/cmds_ocp/ocp_c1_layout.py diff --git a/tests/e2e/plugins/ocp/ocp_c2_layout.py b/tests/e2e/plugins/cmds_ocp/ocp_c2_layout.py similarity index 100% rename from tests/e2e/plugins/ocp/ocp_c2_layout.py rename to tests/e2e/plugins/cmds_ocp/ocp_c2_layout.py diff --git a/tests/e2e/plugins/ocp/ocp_c3_layout.py b/tests/e2e/plugins/cmds_ocp/ocp_c3_layout.py similarity index 100% rename from tests/e2e/plugins/ocp/ocp_c3_layout.py rename to tests/e2e/plugins/cmds_ocp/ocp_c3_layout.py diff --git a/tests/e2e/plugins/ocp/ocp_c4_layout.py b/tests/e2e/plugins/cmds_ocp/ocp_c4_layout.py similarity index 97% rename from tests/e2e/plugins/ocp/ocp_c4_layout.py rename to tests/e2e/plugins/cmds_ocp/ocp_c4_layout.py index e27f075604..0ba8aec03b 100644 --- a/tests/e2e/plugins/ocp/ocp_c4_layout.py +++ b/tests/e2e/plugins/cmds_ocp/ocp_c4_layout.py @@ -39,7 +39,7 @@ FIPS_140_MIN_VERSION = 2 -# dev_cap_req_guid in plugins/ocp/ocp-nvme.c, on the wire. +# dev_cap_req_guid in plugins/cmds-ocp/ocp-nvme.c, on the wire. GUID_BYTES = bytes.fromhex('9742050dd1e1c9985d49584b913c05b7') # Fixed fields ahead of the power state descriptors, as (offset, value), diff --git a/tests/e2e/plugins/ocp/ocp_c5_layout.py b/tests/e2e/plugins/cmds_ocp/ocp_c5_layout.py similarity index 100% rename from tests/e2e/plugins/ocp/ocp_c5_layout.py rename to tests/e2e/plugins/cmds_ocp/ocp_c5_layout.py diff --git a/tests/e2e/plugins/ocp/ocp_c6_layout.py b/tests/e2e/plugins/cmds_ocp/ocp_c6_layout.py similarity index 100% rename from tests/e2e/plugins/ocp/ocp_c6_layout.py rename to tests/e2e/plugins/cmds_ocp/ocp_c6_layout.py diff --git a/tests/e2e/plugins/ocp/ocp_c7_layout.py b/tests/e2e/plugins/cmds_ocp/ocp_c7_layout.py similarity index 100% rename from tests/e2e/plugins/ocp/ocp_c7_layout.py rename to tests/e2e/plugins/cmds_ocp/ocp_c7_layout.py diff --git a/tests/e2e/plugins/ocp/ocp_internal_log_test.py b/tests/e2e/plugins/cmds_ocp/ocp_internal_log_test.py similarity index 99% rename from tests/e2e/plugins/ocp/ocp_internal_log_test.py rename to tests/e2e/plugins/cmds_ocp/ocp_internal_log_test.py index ff98234a09..9c4be14a61 100644 --- a/tests/e2e/plugins/ocp/ocp_internal_log_test.py +++ b/tests/e2e/plugins/cmds_ocp/ocp_internal_log_test.py @@ -12,7 +12,7 @@ ocp_telemetry_layout.py and check that the report agrees with the bytes the drive returned, whatever those turn out to be. Every event class, size boundary and string table lookup is tested without hardware by the -tests/cli/ocp/ocp_internal_log_*_mock_test.py suites. +tests/cli/cmds_ocp/ocp_internal_log_*_mock_test.py suites. Every run with -t host has the drive create a new host-initiated telemetry snapshot, so the tests share a single capture of Data Areas 1 and 2. On a diff --git a/tests/e2e/plugins/ocp/ocp_pel_layout.py b/tests/e2e/plugins/cmds_ocp/ocp_pel_layout.py similarity index 100% rename from tests/e2e/plugins/ocp/ocp_pel_layout.py rename to tests/e2e/plugins/cmds_ocp/ocp_pel_layout.py diff --git a/tests/e2e/plugins/ocp/ocp_smart_add_log_test.py b/tests/e2e/plugins/cmds_ocp/ocp_smart_add_log_test.py similarity index 100% rename from tests/e2e/plugins/ocp/ocp_smart_add_log_test.py rename to tests/e2e/plugins/cmds_ocp/ocp_smart_add_log_test.py diff --git a/tests/e2e/plugins/ocp/ocp_telemetry_layout.py b/tests/e2e/plugins/cmds_ocp/ocp_telemetry_layout.py similarity index 99% rename from tests/e2e/plugins/ocp/ocp_telemetry_layout.py rename to tests/e2e/plugins/cmds_ocp/ocp_telemetry_layout.py index 4a56eaf023..4ac2a01d9d 100644 --- a/tests/e2e/plugins/ocp/ocp_telemetry_layout.py +++ b/tests/e2e/plugins/cmds_ocp/ocp_telemetry_layout.py @@ -11,7 +11,7 @@ reference the internal-log tests build fixtures from and decode against. It is transcribed from the OCP Datacenter NVMe SSD specification's telemetry and string log tables, deliberately *not* from the structs in -plugins/ocp/ocp-telemetry-decode.h, so a disagreement between the two +plugins/cmds-ocp/ocp-telemetry-decode.h, so a disagreement between the two shows up as a test failure rather than being copied into the fixtures. All start and size fields are Dword counts. Event FIFO and statistic diff --git a/tests/e2e/plugins/ocp/ocp_test.py b/tests/e2e/plugins/cmds_ocp/ocp_test.py similarity index 100% rename from tests/e2e/plugins/ocp/ocp_test.py rename to tests/e2e/plugins/cmds_ocp/ocp_test.py diff --git a/tests/e2e/plugins/meson.build b/tests/e2e/plugins/meson.build index 7d4752c104..4284374f0e 100644 --- a/tests/e2e/plugins/meson.build +++ b/tests/e2e/plugins/meson.build @@ -12,8 +12,15 @@ known_plugin_tests = ['micron', 'ocp'] plugin_tests = get_option('plugin-tests') +# The tests of a plugin of nvme itself live in cmds_, see +# plugins/meson.build. Python can't import a package with a '-'. +fs = import('fs') foreach name : known_plugin_tests if name in plugin_tests and name in selected_plugins - subdir(name) + if fs.is_dir(meson.current_source_dir() / ('cmds_' + name)) + subdir('cmds_' + name) + else + subdir(name) + endif endif endforeach diff --git a/tests/fuzz/fuzz-iostat.c b/tests/fuzz/fuzz-iostat.c index 4e9c0e20ba..ea93a5a635 100644 --- a/tests/fuzz/fuzz-iostat.c +++ b/tests/fuzz/fuzz-iostat.c @@ -31,7 +31,7 @@ #include #include "fuzz.h" -#include "nvme-iostat.h" +#include "plugins/cmds-list/nvme-iostat.h" #define MAX_STATS 16 diff --git a/tests/fuzz/meson.build b/tests/fuzz/meson.build index 85265d88c7..32e19d4954 100644 --- a/tests/fuzz/meson.build +++ b/tests/fuzz/meson.build @@ -66,7 +66,10 @@ endif if want_top and have_mock_nvme fuzz_targets += { 'iostat': { - 'sources': ['fuzz-iostat.c', '../../src/nvme-iostat.c'], + 'sources': [ + 'fuzz-iostat.c', + '../../plugins/cmds-list/nvme-iostat.c', + ], 'c_args': [ '-DFUZZ_IOSTAT_TREE="' + (meson.project_source_root() / 'libnvme/tests/sysfs/data/tree-pcie.tar.xz') + '"', diff --git a/tests/unit/c/meson.build b/tests/unit/c/meson.build index 6e7fcc3f94..27d2011b8b 100644 --- a/tests/unit/c/meson.build +++ b/tests/unit/c/meson.build @@ -65,8 +65,8 @@ test('nvme-cli - plugin-dispatch', test_plugin, suite: 'unit') test_bitfields = executable( 'test-bitfields', - ['test-bitfields.c', '../../../src/bitfields.c'], - include_directories: '../../../src', + ['test-bitfields.c', '../../../plugins/cmds-regs/bitfields.c'], + include_directories: '../../../plugins/cmds-regs', dependencies: [config_dep], ) @@ -76,9 +76,10 @@ test_regs = executable( 'test-regs', [ 'test-regs.c', - '../../../src/nvme-regs.c', - '../../../src/bitfields.c', + '../../../plugins/cmds-regs/nvme-regs.c', + '../../../plugins/cmds-regs/bitfields.c', ], + include_directories: '../../../plugins/cmds-regs', dependencies: [ config_dep, ccan_dep, @@ -91,7 +92,7 @@ test('nvme-cli - regs', test_regs, suite: 'unit') if want_top test_iostat = executable( 'test-iostat', - ['test-iostat.c', '../../../src/nvme-iostat.c'], + ['test-iostat.c', '../../../plugins/cmds-list/nvme-iostat.c'], include_directories: '../../../src', dependencies: [config_dep, libnvme_dep], ) diff --git a/tests/unit/c/test-iostat.c b/tests/unit/c/test-iostat.c index 272f1ce641..f6c134aace 100644 --- a/tests/unit/c/test-iostat.c +++ b/tests/unit/c/test-iostat.c @@ -16,7 +16,7 @@ #include #include -#include "nvme-iostat.h" +#include "plugins/cmds-list/nvme-iostat.h" static bool report(const char *what, bool pass) { diff --git a/tests/unit/c/test-plugin.c b/tests/unit/c/test-plugin.c index c2513f8cf3..e904828299 100644 --- a/tests/unit/c/test-plugin.c +++ b/tests/unit/c/test-plugin.c @@ -117,11 +117,16 @@ static struct plugin ext_plugin = { .core = true, }; +static const char *const builtin_groups[] = { + "Core Commands", "Module Commands", "List Commands", NULL, +}; + static struct plugin builtin_plugin = { .name = NULL, .desc = "test built-in", .version = "1.0", .next = &ext_plugin, + .group_order = builtin_groups, }; static struct program prog = { @@ -151,6 +156,41 @@ static struct plugin lazy_plugin = { .parent = &prog, }; +/* + * The module "cmds" adds top-level commands. The module of "missing-cmd" is + * not installed. + */ +DEFINE_STUB(top_fn, "top-cmd", 99) +DEFINE_STUB(list_c_fn, "list-c", 111) +DEFINE_STUB(stop_fn, "stop-cmd", 122) + +static struct command cmd_top = { + "top-cmd", "top-level command", top_fn, "tc", false +}; +static struct command cmd_list_c = { + "list-c", "list-c command", list_c_fn, NULL, false +}; +static struct command cmd_stop = { + "stop-cmd", "stop command", stop_fn, NULL, false +}; +static struct command *cmds_commands[] = { + &cmd_top, &cmd_list_c, &cmd_stop, NULL +}; +static bool cmds_loaded; + +const struct nvme_command_entry *nvme_command_index(void) +{ + static const struct nvme_command_entry index[] = { + { "top-cmd", "tc", "cmds" }, + { "list-c", NULL, "cmds" }, + { "stop-cmd", NULL, "cmds" }, + { "missing-cmd", NULL, "missing" }, + { NULL }, + }; + + return index; +} + static char loaded_name[32]; static int nr_load_plugin, nr_load_plugins; @@ -162,18 +202,30 @@ static void load_lazy(void) } } +static void load_cmds(void) +{ + if (!cmds_loaded) { + plugin_add_group(&builtin_plugin, "Module Commands", + cmds_commands); + cmds_loaded = true; + } +} + void nvme_load_plugin(const char *name) { nr_load_plugin++; snprintf(loaded_name, sizeof(loaded_name), "%s", name); if (!strcmp(name, "lazy")) load_lazy(); + if (!strcmp(name, "cmds")) + load_cmds(); } void nvme_load_plugins(void) { nr_load_plugins++; load_lazy(); + load_cmds(); } /* "gone" is a plugin of the build without its module */ @@ -187,13 +239,28 @@ const char *nvme_plugin_dir(void) return "/test/plugins"; } +static void add_builtin_groups(void); + static void unload_lazy(void) { + struct command_group *group; + ext_plugin.next = NULL; free(lazy_plugin.commands); lazy_plugin.commands = NULL; free(lazy_plugin.groups); lazy_plugin.groups = NULL; + if (cmds_loaded) { + while (builtin_plugin.groups) { + group = builtin_plugin.groups; + builtin_plugin.groups = group->next; + free(group); + } + free(builtin_plugin.commands); + builtin_plugin.commands = NULL; + add_builtin_groups(); + cmds_loaded = false; + } nr_load_plugin = 0; nr_load_plugins = 0; loaded_name[0] = '\0'; @@ -560,8 +627,57 @@ static const struct { { { "gone", "cmd" }, -ENOTTY, 1, "gone", 1, "", "plugin gone not installed: no module in /test/plugins", "a plugin without its module is not installed" }, + { { "top-cmd" }, 99, 1, "cmds", 0, "", "", + "a top-level command loads only its module" }, + { { "tc" }, 99, 1, "cmds", 0, "", "", + "the alias of a top-level command loads its module" }, + { { "top" }, 99, 1, "cmds", 0, "", "", + "the prefix of a top-level command loads its module" }, + { { "list" }, -ENOTTY, 1, "list", 1, "", + "invalid sub-command 'list'", + "a prefix of commands of the program and a module is no command" }, + { { "st" }, -ENOTTY, 1, "st", 1, "", + "invalid sub-command 'st'", + "a prefix of a program and a module command is no command" }, + { { "sto" }, 122, 1, "cmds", 0, "", "", + "a prefix of only a command of a module loads its module" }, + { { "missing-cmd" }, -ENOTTY, 1, "missing", 0, "", + "command missing-cmd not installed: plugin missing has no module in /test/plugins", + "a top-level command without its module is not installed" }, }; +/* The commands of a module are listed at the place of their group */ +static void test_group_order(void) +{ + static const char *const expect[] = { + "foo", "bar", "status", "old-cmd", "top-cmd", "list-c", + "stop-cmd", "list-a", "list-b", + }; + struct captured_output cap; + char *argv[2]; + size_t i; + + unload_lazy(); + load_cmds(); + for (i = 0; i < ARRAY_SIZE(expect); i++) { + check(builtin_plugin.commands[i] && + !strcmp(builtin_plugin.commands[i]->name, expect[i]), + "group_order: command order"); + } + check(!builtin_plugin.commands[i], "group_order: command count"); + + argv[0] = "test-prog"; + argv[1] = "help"; + run_handle_plugin(argv, ARRAY_SIZE(argv), &builtin_plugin, &cap); + check(strstr(cap.out, "Core Commands:") < + strstr(cap.out, "Module Commands:") && + strstr(cap.out, "Module Commands:") < + strstr(cap.out, "List Commands:"), + "group_order: help lists the group at its place"); + + unload_lazy(); +} + /* Modules are loaded only for the commands which need them */ static void test_lazy_loading(void) { @@ -681,6 +797,12 @@ static void test_lookup(void) argconfig_set_global_options(NULL); } +static void add_builtin_groups(void) +{ + plugin_add_group(&builtin_plugin, "Core Commands", core_commands); + plugin_add_group(&builtin_plugin, "List Commands", list_commands); +} + int main(void) { test_rc = 0; @@ -688,8 +810,7 @@ int main(void) builtin_plugin.parent = &prog; ext_plugin.parent = &prog; - plugin_add_group(&builtin_plugin, "Core Commands", core_commands); - plugin_add_group(&builtin_plugin, "List Commands", list_commands); + add_builtin_groups(); plugin_add_group(&ext_plugin, NULL, ext_commands); test_dispatch_exact(); @@ -711,6 +832,7 @@ int main(void) test_lookup(); #if NVME_PLUGIN_MODULES test_lazy_loading(); + test_group_order(); #endif return test_rc ? EXIT_FAILURE : EXIT_SUCCESS; diff --git a/tests/unit/c/test-regs.c b/tests/unit/c/test-regs.c index e6b78b9cdd..83151401d7 100644 --- a/tests/unit/c/test-regs.c +++ b/tests/unit/c/test-regs.c @@ -21,7 +21,7 @@ #include #include -#include "../src/nvme-regs.h" +#include "nvme-regs.h" static bool report(const char *what, bool pass) { diff --git a/tests/unit/py/meson.build b/tests/unit/py/meson.build index 4574da0545..3566269692 100644 --- a/tests/unit/py/meson.build +++ b/tests/unit/py/meson.build @@ -17,13 +17,29 @@ if python3.found() args: [ files('test_command_metadata_schema.py'), nvme_exe, - meson.project_source_root() / 'plugins' / 'utils' / 'command-metadata-schema.json', + meson.project_source_root() / 'plugins' / 'cmds-utils' / 'command-metadata-schema.json', ], depends: nvme_runtime, timeout: 120, suite: 'check', ) + # The index of the top-level commands of the plugins lists the + # commands each module adds. + test( + 'nvme-cli - command-index', + python3, + args: [ + files('test_command_index.py'), + nvme_exe, + want_plugin_modules ? + meson.project_build_root() / 'plugins' : '-', + ] + plugin_command_index, + depends: nvme_runtime, + timeout: 120, + suite: 'check', + ) + # The global options are one table; the documentation has to list # each of them, also as a key of nvme-cli.conf. test( @@ -119,7 +135,7 @@ if python3.found() args: [ files('test_completion_fixture_schema.py'), meson.project_source_root() / 'completions' / 'test-command-metadata.json', - meson.project_source_root() / 'plugins' / 'utils' / 'command-metadata-schema.json', + meson.project_source_root() / 'plugins' / 'cmds-utils' / 'command-metadata-schema.json', ], timeout: 60, suite: 'check', diff --git a/tests/unit/py/test_command_index.py b/tests/unit/py/test_command_index.py new file mode 100644 index 0000000000..b57888dfd1 --- /dev/null +++ b/tests/unit/py/test_command_index.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-or-later +# +# This file is part of nvme-cli. +"""Check the index of the top-level commands of the plugins. + +A plugin lists its top-level commands in plugin_commands and their aliases +in plugin_command_aliases (plugins/meson.build). nvme loads the module of a +top-level command it doesn't have from this index, so the index has to +list exactly the commands each module adds. + +The commands come from `nvme utils dump-command-metadata`. With modules, +the test runs it with only the utils module, and with the utils module and +one more: the commands it adds are the ones of that module. + +Usage: test_command_index.py |- [...] + +An entry is ":[=]", "-" means no modules. +""" +import json +import os +import shutil +import subprocess +import sys +import tempfile +import unittest + +if len(sys.argv) < 3: + print("usage: %s |- [...]" % + sys.argv[0]) + sys.exit(77) + +NVME_BIN = sys.argv[1] +MODULE_DIR = None if sys.argv[2] == '-' else os.path.abspath(sys.argv[2]) +MODULE_SUFFIX = '.so' +METADATA_MODULE = 'cmds-utils' + + +def parse_index(entries): + """{command: (plugin, alias)} of the entries, and the duplicates.""" + index = {} + dups = [] + for entry in entries: + plugin, cmd = entry.split(':', 1) + cmd, _, alias = cmd.partition('=') + if cmd in index: + dups.append(cmd) + index[cmd] = (plugin, alias or None) + return index, dups + + +INDEX, DUPLICATES = parse_index(sys.argv[3:]) + + +def top_level_commands(module_dir=None): + """{command: alias} of the top-level commands of nvme.""" + env = dict(os.environ) + if module_dir is not None: + env['NVME_PLUGIN_DIR'] = module_dir + # the libraries the modules are linked to + env['LD_LIBRARY_PATH'] = MODULE_DIR + proc = subprocess.run([NVME_BIN, 'utils', 'dump-command-metadata'], + capture_output=True, text=True, encoding='utf-8', + env=env, check=True) + model = json.loads(proc.stdout) + return {c['name']: c.get('alias') for c in model['commands']} + + +def modules(): + """The names of the modules in MODULE_DIR.""" + return sorted(f[:-len(MODULE_SUFFIX)] for f in os.listdir(MODULE_DIR) + if f.endswith(MODULE_SUFFIX)) + + +class CommandIndexTest(unittest.TestCase): + + @classmethod + def setUpClass(cls): + cls.commands = top_level_commands() + + def test_no_duplicates(self): + self.assertEqual(DUPLICATES, []) + names = list(INDEX) + [a for _, a in INDEX.values() if a] + self.assertEqual(sorted(set(names)), sorted(names)) + + def test_index_commands_exist(self): + """Every command of the index is a command of nvme.""" + for cmd, (plugin, alias) in INDEX.items(): + with self.subTest(command=cmd, plugin=plugin): + self.assertIn(cmd, self.commands) + self.assertEqual(self.commands[cmd], alias) + + @unittest.skipIf(MODULE_DIR is None, 'built without modules') + def test_module_commands_indexed(self): + """The commands each module adds are its commands in the index.""" + names = modules() + self.assertIn(METADATA_MODULE, names) + for cmd, (plugin, _) in INDEX.items(): + with self.subTest(command=cmd, plugin=plugin): + self.assertIn(plugin, names) + + tmp = tempfile.mkdtemp() + try: + def link(name): + os.symlink(os.path.join(MODULE_DIR, name + MODULE_SUFFIX), + os.path.join(tmp, name + MODULE_SUFFIX)) + + def unlink(name): + os.unlink(os.path.join(tmp, name + MODULE_SUFFIX)) + + link(METADATA_MODULE) + base = top_level_commands(tmp) + for cmd, (plugin, _) in INDEX.items(): + if plugin == METADATA_MODULE: + with self.subTest(command=cmd, plugin=plugin): + self.assertIn(cmd, base) + + for name in names: + if name == METADATA_MODULE: + continue + link(name) + added = set(top_level_commands(tmp)) - set(base) + unlink(name) + indexed = {c for c, (p, _) in INDEX.items() if p == name} + with self.subTest(module=name): + self.assertEqual(sorted(added), sorted(indexed)) + finally: + shutil.rmtree(tmp) + + +if __name__ == '__main__': + unittest.main(argv=sys.argv[:1])