Skip to contentSkip to conversation

ctlv: Add a schema-driven TLV uAPI for character devices

RFC PATCH Superseded Jiri Pirko 3 participants 25 messages Nov 13 – Nov 25

Subsystems (4)
lore
Share & tools
lore

Jiri Pirko

author
#0 lore raw

v2 cover ctlv: Add a schema-driven TLV uAPI for character devices

From: Jiri Pirko <[email protected]>

RFC v1 [1] posted CTLV together with its first user, the attestation subsystem. v2 posts them as two series: this one, and the attestation series, which applies on top of it and is posted alongside as

[PATCH RFC v2 0/9] attestation: Add a common subsystem and TDX support

CTLV is a schema-driven TLV uAPI on a character device, meant for uAPIs too unconstrained for fixed structures: lists of records, nested and variable-sized data, optional fields. Every request is checked against the family's YAML schema before the driver sees it, and the UAPI header, the bindings and the docs are generated from the same schema. A family grows without versions, by new ops and optional fields. One ioctl over a global number space lets strace or a seccomp supervisor decode any family, and a query whose answer is larger than the caller's buffer is answered in parts, with a cursor and a generation that keep them consistent.

An ioctl with structures of its own fixes their layout, needs pointers to more structures for variable data, and has to be validated and decoded on its own. sysfs and configfs would assemble one request through several files, where CTLV checks and executes it at once. Netlink is built around sockets and network namespaces, while these devices want an fd and the DAC model of a device node, and it was turned down for the TSM's SPDM uAPI [2]. For a value or two, sysfs or a plain ioctl stays simpler, and CTLV is not meant for that.

The uAPI is one ioctl on the device's fd:

  struct ctlv_op_exec {
          __u32 size;
          __u32 flags;
          __aligned_u64 op_id;
          __aligned_u64 request;
          __aligned_u64 reply;
          __u32 request_len;
          __u32 reply_len;
          __aligned_u64 generation;
          __aligned_u64 cursor;
  };

  ioctl(fd, CTLV_IOC_OP_EXEC, &exec);

An op is an action, executed once, or a query, which the generation and the cursor carry across replies. Each op needs read or read-write access, checked against the mode the device was opened with. A failed op returns an errno, and in the reply buffer why the request was refused and the offset of the offending TLV.

A family is specified in YAML. The root family, which every device answers, lets a program not compiled against a family discover it. Its first op:

ops:
# The families this device answers, this one first and the device family # last. The only names any reply of this family carries. family-get:
type: query
fd-access: read
reply:
# One entry per family of the chain.
families[]:
# The family ID, which bits 63..48 of the family's types carry.
id: uint
# The registry name, also what a uevent carries. Bounded here, this # being the only place a message carries a family name.
name: string(..63)

ctlvgen --signatures prints a family's ops as calls, ? marking what may be absent and [] what may repeat. The root family's three, with the purpose of each:

# The device's family chain, root first.
family-get() -> { families[]: { id, name } }

# Every op the device publishes, with its type, access and lengths. op-get() ->

      { ops[]: { id, type, availability?, disabled?, request-max-len?,
                 action-reply-max-len?, query-reply-min-len?,
                 query-reply-suggested-len?, fd-access?, error-info-max-len? } }

# The tree of one op's request and reply. op-schema-get(id) -> { request?: schema-node, reply?: schema-node }

libctlv is a small C library for the mechanical parts: opening a device by its family, building requests, parsing replies, reassembling queries and building blob descriptors, with typed bindings generated per family. ctlvctl needs no generated code, only the family's specification, or the .json the build writes from it, for the names. Both build with the kernel's CROSS_COMPILE, LLVM and O=. Here they run in a VM, on a device of the simulation provider from the branch [3], with CTLV_SPEC_DIR pointing at Documentation/ctlv/specs. The device's MR 1 can be extended, and its evidence object 2 is an event log:

# Every CTLV device and its family chain.

  $ ctlvctl list
  attestation/attestation0        ctlv/ctlv-attestation/ctlv-attestation-sim

# The ops the device publishes.

  $ ctlvctl ops attestation/attestation0
  # ctlv/ctlv-attestation/ctlv-attestation-sim, generation 0
  family-get     query   read        fixed  request 16    reply 112..65536
  op-get         query   read        fixed  request 16    reply 56..65536
  op-schema-get  query   read        fixed  request 40    reply 168..65536
  ...
  mr-read        query   read        fixed  request 80    reply 112..4096
  mr-extend      action  read-write  fixed  request 7232  reply 2824
  ...

# mr-read's request and reply.

  $ ctlvctl schema attestation/attestation0 mr-read
  mr-read (query)
  request:
    root record
      mr-read id required uint [0, 4294967295]
      device-generation optional uint [0, 4294967295]
      mr-read options optional record
  reply:
    root record
      device-generation required uint [0, 4294967295]
      mr-generation required uint [0, 4294967295]
      mr-values required record x23
        mr-value.hash-algo required enum [0, 22] {HASH_ALGO_MD4, ...}
        mr-value.data required binary len [16, 64]

# MR 1's banks.

  $ ctlvctl exec attestation/attestation0 mr-read id=1
  # mr-read, 1 fragment, generation 0
    device-generation 0
    mr-generation 2
    mr-values
      mr-value.hash-algo HASH_ALGO_SHA256
      mr-value.data hex:0000000000000000000000000000000000000000000000000000000000000000
    mr-values
      mr-value.hash-algo HASH_ALGO_SHA384
      mr-value.data hex:000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

# Extend MR 1 by a digest for each of its banks.

  $ ctlvctl exec attestation/attestation0 mr-extend --json '{"id":1,
          "mr-values":[
            {"hash-algo":"HASH_ALGO_SHA256","data":"hex:b1a3c4fc2b10743a5f79ce443178df6e99b4426fcae2ef3e1f76a6a26d8f0860"},
            {"hash-algo":"HASH_ALGO_SHA384","data":"hex:c8a6d5e64f03a5f3cad5125670fccff0c065a9db91f00a81eb6630836629a85969802308430aa28ea0d6fdd8b1eb0cc8"}]}'
  # mr-extend, 1 fragment, generation 0
    device-generation 0
    mr-generation 3
    mr-values
      mr-value.hash-algo HASH_ALGO_SHA256
      mr-value.data hex:b1a3c4fc2b10743a5f79ce443178df6e99b4426fcae2ef3e1f76a6a26d8f0860
    mr-values
      mr-value.hash-algo HASH_ALGO_SHA384
      mr-value.data hex:c8a6d5e64f03a5f3cad5125670fccff0c065a9db91f00a81eb6630836629a85969802308430aa28ea0d6fdd8b1eb0cc8

# MR 1 again, with its new value and generation.

  $ ctlvctl exec attestation/attestation0 mr-read id=1
  # mr-read, 1 fragment, generation 1
    device-generation 0
    mr-generation 3
    mr-values
      mr-value.hash-algo HASH_ALGO_SHA256
      mr-value.data hex:a4fb91fd25115ec617cc4f17a40590e685cc58de5a65bb119e821e09d780a158
    mr-values
      mr-value.hash-algo HASH_ALGO_SHA384
      mr-value.data hex:1dcbf559ca9d6b48d782d268933c07a9e33c96bb21e1b868c2db7be929a852d3c5dbc5cf44427400c268a2f557c38c75
  # The event log, an output blob, written to a file.
  $ ctlvctl exec attestation/attestation0 evidence-get --json \
          '{"objects":[{"id":2,"data":{"file":"log.bin"}}]}'
  # evidence-get, 1 fragment, generation 0
    device-generation 0
    evidence-get evidence-generation 1
    evidence-get results
      evidence-get results.format ccel
      evidence-get results.length 65

There are no versions. struct ctlv_op_exec carries its size and grows only at its end. A family grows by new ops and new optional fields, and anything incompatible is a new op. Each family has a checked-in ABI snapshot, and regen refuses a change that breaks it.

Events, a per-fd queue of what changed on a device, are left out until their first user is posted, and so are memfd and dma-buf blobs. Both are on the branch [3], with the generator's tests, KUnit, test families and selftests.

The series adds 23787 lines:

  generator, Python                 7864
  core, C                           5643
  ctlvctl                           3519
  libctlv                           3242
  docs                              1510
  generated files                   1161
  meta-schemas, registry             368
  root family specification          211
  ABI snapshots                      118
  build                              151

Changes since RFC v1, each patch listing its own:

- Specs are written as Jason suggested: enums, flags, records and ops, each op the tree of its request and reply, every type derived from where its field sits. Attribute groups and sets are gone. The comment above an item is its doc, in the UAPI headers and the rendered docs, and ctlvgen --signatures prints the ops as above.
- TLV, type, record and field replace attr and nest.
- The events are left out, with read() and poll().
- A subsystem allocates its device and embeds CTLV, as fwctl does, and may route the ioctl from its own file operations. The engine is in lib/ctlv/, and a subsystem's class gets its nodes from CTLV, and there is no ctlv class.
- struct ctlv_op_exec is sized by its size field and read with copy_struct_from_user(). A reply buffer may be any length, and an output blob too short fails with EMSGSIZE and the length it needs.
- Enum extension points: an enum whose values a descendant family gives.
- An op that reads is <object>-get: families-dump and ops-dump are family-get and op-get.
- Inline messages are at most 64 KiB, and records nest at most 8 deep.
- The UAPI headers are in include/uapi/ctlv/.
- regen writes the ABI snapshots too, and refuses an ABI break unless ABI_BREAK=1.
- The userspace ABI opens with the goals, a worked example and a glossary, and collects the compatibility rules. The family guide is built around a worked example family.
- libctlv and ctlvctl are posted. ctlvctl runs every op with exec, takes a blob in --json as a file, as Aneesh's patched copy did, and sizes an output blob by the length the op fails with.

The patches:

1-3 the spec language and generator, the message format and the
family API, and the root family

  4      the userspace ABI
  5-11   messages, blobs, validation and introspection, then dispatch
  12     character device nodes
  13     how to write a family
  14-15  libctlv and ctlvctl

Note to reviewers: the uAPI, in 1, 2 and 4, and the family API, in 2 and 13, matter most at this stage.

[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/[email protected]/
[3] https://github.com/jpirko/linux_mlxsw/commits/wip_attestation_all_2

Jiri Pirko (15):
ctlv: Add the schema language and generator
ctlv: Add the UAPI message format and family API
ctlv: Add the root family specification and generated files
Documentation: ctlv: Add userspace ABI
ctlv: Prepare message input handling
ctlv: Prepare blob descriptor validation
ctlv: Prepare schema validation
ctlv: Prepare message output handling
ctlv: Prepare VA blob handling
ctlv: Prepare runtime introspection
ctlv: Add operation dispatch
ctlv: Add character device nodes
Documentation: ctlv: Describe how to write a family tools/ctlv: Add the userspace library
tools/ctlv: Add ctlvctl

 Documentation/ctlv/abi/ctlv.yaml              |  111 +
 Documentation/ctlv/abi/families.registry.yaml |    7 +
 Documentation/ctlv/ctlv-registry-schema.yaml  |   38 +
 Documentation/ctlv/ctlv-schema.yaml           |  227 ++
 Documentation/ctlv/families.yaml              |   17 +
 .../ctlv/generated-files-schema.yaml          |   68 +
 Documentation/ctlv/generated-files.yaml       |   18 +
 Documentation/ctlv/specs/ctlv.yaml            |  211 ++
 Documentation/driver-api/ctlv.rst             |  723 +++++
 Documentation/driver-api/index.rst            |    1 +
 Documentation/userspace-api/ctlv.rst          |  783 +++++
 Documentation/userspace-api/index.rst         |    1 +
 .../userspace-api/ioctl/ioctl-number.rst      |    2 +
 MAINTAINERS                                   |   12 +
 include/linux/ctlv.h                          |  149 +
 include/linux/ctlv_device.h                   |   57 +
 include/linux/ctlv_family.h                   |  652 ++++
 include/linux/ctlv_gen.h                      |  154 +
 include/uapi/ctlv/ctlv.h                      |  180 ++
 include/uapi/ctlv/ctlv_families_gen.h         |   17 +
 include/uapi/ctlv/ctlv_gen.h                  |  278 ++
 lib/Kconfig                                   |    2 +
 lib/Makefile                                  |    2 +
 lib/ctlv/Kconfig                              |   13 +
 lib/ctlv/Makefile                             |    5 +
 lib/ctlv/blob.c                               |  421 +++
 lib/ctlv/blob.h                               |   15 +
 lib/ctlv/blob_desc.c                          |  101 +
 lib/ctlv/blob_desc.h                          |   29 +
 lib/ctlv/builder.c                            |  455 +++
 lib/ctlv/builder.h                            |   14 +
 lib/ctlv/core.c                               | 1169 +++++++
 lib/ctlv/ctlv_gen.c                           |  161 +
 lib/ctlv/device.c                             |  179 ++
 lib/ctlv/internal.h                           |   87 +
 lib/ctlv/introspection.c                      |  505 +++
 lib/ctlv/message.c                            |  393 +++
 lib/ctlv/message.h                            |   91 +
 lib/ctlv/schema.c                             | 1092 +++++++
 lib/ctlv/schema.h                             |   54 +
 tools/Makefile                                |    9 +-
 tools/ctlv/Makefile                           |   62 +
 tools/ctlv/ctlv-regen.sh                      |   64 +
 tools/ctlv/ctlvctl/.gitignore                 |    4 +
 tools/ctlv/ctlvctl/Makefile                   |   64 +
 tools/ctlv/ctlvctl/ctlvctl.c                  | 2787 +++++++++++++++++
 tools/ctlv/ctlvctl/spec.c                     |  672 ++++
 tools/ctlv/ctlvctl/spec.h                     |   60 +
 tools/ctlv/ctlvgen/__init__.py                |    1 +
 tools/ctlv/ctlvgen/cli.py                     |  178 ++
 tools/ctlv/ctlvgen/lib/__init__.py            |    1 +
 tools/ctlv/ctlvgen/lib/cenum.py               |  178 ++
 tools/ctlv/ctlvgen/lib/cgen.py                |  763 +++++
 tools/ctlv/ctlvgen/lib/compat.py              |  877 ++++++
 tools/ctlv/ctlvgen/lib/dump.py                |  161 +
 tools/ctlv/ctlvgen/lib/errors.py              |   16 +
 tools/ctlv/ctlvgen/lib/gen_doc.py             |  684 ++++
 tools/ctlv/ctlvgen/lib/gen_family.py          |  285 ++
 tools/ctlv/ctlvgen/lib/gen_kernel.py          |  576 ++++
 tools/ctlv/ctlvgen/lib/gen_runtime.py         |   66 +
 tools/ctlv/ctlvgen/lib/gen_uapi.py            |  182 ++
 tools/ctlv/ctlvgen/lib/gen_user.py            |  808 +++++
 tools/ctlv/ctlvgen/lib/outputs.py             |  363 +++
 tools/ctlv/ctlvgen/lib/semantics.py           | 1219 +++++++
 tools/ctlv/ctlvgen/lib/sizes.py               |  239 ++
 tools/ctlv/ctlvgen/lib/spec.py                |  813 +++++
 tools/ctlv/ctlvgen/lib/tree.py                |  158 +
 tools/ctlv/ctlvgen/lib/yamlload.py            |  138 +
 tools/ctlv/libctlv/Makefile                   |   41 +
 tools/ctlv/libctlv/ctlv.h                     |  413 +++
 tools/ctlv/libctlv/ctlv_user_gen.c            |  551 ++++
 tools/ctlv/libctlv/device.c                   |  412 +++
 tools/ctlv/libctlv/internal.h                 |  161 +
 tools/ctlv/libctlv/introspection.c            |  238 ++
 tools/ctlv/libctlv/message.c                  |  518 +++
 tools/ctlv/libctlv/schema.c                   |  742 +++++
 tools/ctlv/libctlv/spec.c                     |  186 ++
 tools/ctlv/libctlv/transport.c                |  572 ++++
 tools/ctlv/pyproject.toml                     |   30 +
 tools/ctlv/requirements.txt                   |    2 +
 80 files changed, 23787 insertions(+), 1 deletion(-)
 create mode 100644 Documentation/ctlv/abi/ctlv.yaml
 create mode 100644 Documentation/ctlv/abi/families.registry.yaml
 create mode 100644 Documentation/ctlv/ctlv-registry-schema.yaml
 create mode 100644 Documentation/ctlv/ctlv-schema.yaml
 create mode 100644 Documentation/ctlv/families.yaml
 create mode 100644 Documentation/ctlv/generated-files-schema.yaml
 create mode 100644 Documentation/ctlv/generated-files.yaml
 create mode 100644 Documentation/ctlv/specs/ctlv.yaml
 create mode 100644 Documentation/driver-api/ctlv.rst
 create mode 100644 Documentation/userspace-api/ctlv.rst
 create mode 100644 include/linux/ctlv.h
 create mode 100644 include/linux/ctlv_device.h
 create mode 100644 include/linux/ctlv_family.h
 create mode 100644 include/linux/ctlv_gen.h
 create mode 100644 include/uapi/ctlv/ctlv.h
 create mode 100644 include/uapi/ctlv/ctlv_families_gen.h
 create mode 100644 include/uapi/ctlv/ctlv_gen.h
 create mode 100644 lib/ctlv/Kconfig
 create mode 100644 lib/ctlv/Makefile
 create mode 100644 lib/ctlv/blob.c
 create mode 100644 lib/ctlv/blob.h
 create mode 100644 lib/ctlv/blob_desc.c
 create mode 100644 lib/ctlv/blob_desc.h
 create mode 100644 lib/ctlv/builder.c
 create mode 100644 lib/ctlv/builder.h
 create mode 100644 lib/ctlv/core.c
 create mode 100644 lib/ctlv/ctlv_gen.c
 create mode 100644 lib/ctlv/device.c
 create mode 100644 lib/ctlv/internal.h
 create mode 100644 lib/ctlv/introspection.c
 create mode 100644 lib/ctlv/message.c
 create mode 100644 lib/ctlv/message.h
 create mode 100644 lib/ctlv/schema.c
 create mode 100644 lib/ctlv/schema.h
 create mode 100644 tools/ctlv/Makefile
 create mode 100755 tools/ctlv/ctlv-regen.sh
 create mode 100644 tools/ctlv/ctlvctl/.gitignore
 create mode 100644 tools/ctlv/ctlvctl/Makefile
 create mode 100644 tools/ctlv/ctlvctl/ctlvctl.c
 create mode 100644 tools/ctlv/ctlvctl/spec.c
 create mode 100644 tools/ctlv/ctlvctl/spec.h
 create mode 100644 tools/ctlv/ctlvgen/__init__.py
 create mode 100755 tools/ctlv/ctlvgen/cli.py
 create mode 100644 tools/ctlv/ctlvgen/lib/__init__.py
 create mode 100644 tools/ctlv/ctlvgen/lib/cenum.py
 create mode 100644 tools/ctlv/ctlvgen/lib/cgen.py
 create mode 100644 tools/ctlv/ctlvgen/lib/compat.py
 create mode 100644 tools/ctlv/ctlvgen/lib/dump.py
 create mode 100644 tools/ctlv/ctlvgen/lib/errors.py
 create mode 100644 tools/ctlv/ctlvgen/lib/gen_doc.py
 create mode 100644 tools/ctlv/ctlvgen/lib/gen_family.py
 create mode 100644 tools/ctlv/ctlvgen/lib/gen_kernel.py
 create mode 100644 tools/ctlv/ctlvgen/lib/gen_runtime.py
 create mode 100644 tools/ctlv/ctlvgen/lib/gen_uapi.py
 create mode 100644 tools/ctlv/ctlvgen/lib/gen_user.py
 create mode 100644 tools/ctlv/ctlvgen/lib/outputs.py
 create mode 100644 tools/ctlv/ctlvgen/lib/semantics.py
 create mode 100644 tools/ctlv/ctlvgen/lib/sizes.py
 create mode 100644 tools/ctlv/ctlvgen/lib/spec.py
 create mode 100644 tools/ctlv/ctlvgen/lib/tree.py
 create mode 100644 tools/ctlv/ctlvgen/lib/yamlload.py
 create mode 100644 tools/ctlv/libctlv/Makefile
 create mode 100644 tools/ctlv/libctlv/ctlv.h
 create mode 100644 tools/ctlv/libctlv/ctlv_user_gen.c
 create mode 100644 tools/ctlv/libctlv/device.c
 create mode 100644 tools/ctlv/libctlv/internal.h
 create mode 100644 tools/ctlv/libctlv/introspection.c
 create mode 100644 tools/ctlv/libctlv/message.c
 create mode 100644 tools/ctlv/libctlv/schema.c
 create mode 100644 tools/ctlv/libctlv/spec.c
 create mode 100644 tools/ctlv/libctlv/transport.c
 create mode 100644 tools/ctlv/pyproject.toml
 create mode 100644 tools/ctlv/requirements.txt
Signature · 1 line
2.56.0
author
#1 lore raw

RFC PATCH v2 1/15 ctlv: Add the schema language and generator

From: Jiri Pirko <[email protected]>

Define the YAML schema and append-only family registry. Add ctlvgen to validate specifications and emit kernel and UAPI outputs.

Assisted-by Cursor: GPT-5.6 Sol
Assisted-by Cursor: Claude Opus 5.5

---
RFC->RFCv2:
- dropped the family priv and its lifecycle hooks, handing callbacks the CTLV instance
- fixed the ABI check to accept max-occurrences widened to unlimited
- made a --mode and file kind pair with no generator a usage error
- stated the attr form rules in the meta-schema
- computed each op's error information length
- generated no reply lengths into user headers
- checked the limits against <linux/ctlv_family.h>
- lowered the inline message limit to 64 KiB
- lowered the record depth limit to 8
- stopped reserving the callback typedef names
- dropped the event op type
- renamed stubs to extension points
- let an enum take its values from a C header
- made abi-check report a changed attr kind, not fail on its bounds
- left an optional blob below the root out of a reply
- wrote each op's request and reply as a tree of fields, naming a record only where it is reused
- derived every type from where its field sits, so a spec carries no numbers and the ABI snapshot only checks them
- named the spec in every generated file, and gave each field and op one constant
- said TLV, type, record and field instead of attr
- said record instead of nest, the root being one
- said node, field or placed record instead of placement
- numbered every enum member and flag bit in the generated headers
- generated the UAPI headers into include/uapi/ctlv/
- type-checked ctlvgen with mypy --strict in make lint
- required a comment on every spec item, each enum member and flag
- printed each enum member's comment in the UAPI headers
- put each field's doc above its generated helpers
- folded abi-update into regen, refusing a break of the committed ABI unless ABI_BREAK=1, and validate, abi-check and check-regen into all
- added enum extension points, whose values a descendant family gives
- said message instead of wire
- let a count name an enum, one entry per value
- let an integer in bytes take K, M and G
- kept a hyphenated name whole when wrapping a generated comment

---
 Documentation/ctlv/ctlv-registry-schema.yaml  |   38 +
 Documentation/ctlv/ctlv-schema.yaml           |  227 +++
 .../ctlv/generated-files-schema.yaml          |   64 +
 MAINTAINERS                                   |    7 +
 tools/ctlv/Makefile                           |   39 +
 tools/ctlv/ctlv-regen.sh                      |   64 +
 tools/ctlv/ctlvgen/__init__.py                |    1 +
 tools/ctlv/ctlvgen/cli.py                     |  137 ++
 tools/ctlv/ctlvgen/lib/__init__.py            |    1 +
 tools/ctlv/ctlvgen/lib/cenum.py               |  178 +++
 tools/ctlv/ctlvgen/lib/cgen.py                |  763 +++++++++++
 tools/ctlv/ctlvgen/lib/compat.py              |  877 ++++++++++++
 tools/ctlv/ctlvgen/lib/errors.py              |   16 +
 tools/ctlv/ctlvgen/lib/gen_family.py          |  285 ++++
 tools/ctlv/ctlvgen/lib/gen_kernel.py          |  576 ++++++++
 tools/ctlv/ctlvgen/lib/gen_uapi.py            |  182 +++
 tools/ctlv/ctlvgen/lib/outputs.py             |  355 +++++
 tools/ctlv/ctlvgen/lib/semantics.py           | 1219 +++++++++++++++++
 tools/ctlv/ctlvgen/lib/sizes.py               |  239 ++++
 tools/ctlv/ctlvgen/lib/spec.py                |  813 +++++++++++
 tools/ctlv/ctlvgen/lib/tree.py                |  158 +++
 tools/ctlv/ctlvgen/lib/yamlload.py            |  138 ++
 tools/ctlv/pyproject.toml                     |   30 +
 tools/ctlv/requirements.txt                   |    2 +
 24 files changed, 6409 insertions(+)
 create mode 100644 Documentation/ctlv/ctlv-registry-schema.yaml
 create mode 100644 Documentation/ctlv/ctlv-schema.yaml
 create mode 100644 Documentation/ctlv/generated-files-schema.yaml
 create mode 100644 tools/ctlv/Makefile
 create mode 100755 tools/ctlv/ctlv-regen.sh
 create mode 100644 tools/ctlv/ctlvgen/__init__.py
 create mode 100755 tools/ctlv/ctlvgen/cli.py
 create mode 100644 tools/ctlv/ctlvgen/lib/__init__.py
 create mode 100644 tools/ctlv/ctlvgen/lib/cenum.py
 create mode 100644 tools/ctlv/ctlvgen/lib/cgen.py
 create mode 100644 tools/ctlv/ctlvgen/lib/compat.py
 create mode 100644 tools/ctlv/ctlvgen/lib/errors.py
 create mode 100644 tools/ctlv/ctlvgen/lib/gen_family.py
 create mode 100644 tools/ctlv/ctlvgen/lib/gen_kernel.py
 create mode 100644 tools/ctlv/ctlvgen/lib/gen_uapi.py
 create mode 100644 tools/ctlv/ctlvgen/lib/outputs.py
 create mode 100644 tools/ctlv/ctlvgen/lib/semantics.py
 create mode 100644 tools/ctlv/ctlvgen/lib/sizes.py
 create mode 100644 tools/ctlv/ctlvgen/lib/spec.py
 create mode 100644 tools/ctlv/ctlvgen/lib/tree.py
 create mode 100644 tools/ctlv/ctlvgen/lib/yamlload.py
 create mode 100644 tools/ctlv/pyproject.toml
 create mode 100644 tools/ctlv/requirements.txt
Documentation/ctlv/ctlv-registry-schema.yaml new file +38 -0
new file mode 100644
index 000000000000..d9a2840fc230
@@ -0,0 +1,38 @@
+# SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)
+%YAML 1.2
+---
+$id: http://kernel.org/schemas/ctlv/ctlv-registry-schema.yaml#
+$schema: https://json-schema.org/draft-07/schema
+
+$defs:
+  name:
+    type: string
+    maxLength: 63
+    pattern: ^[a-z0-9]+(-[a-z0-9]+)*$
+
+title: CTLV family registry
+description: Append-only list of CTLV family names, indexed by family ID
+type: object
+required: [ families ]
+additionalProperties: false
+properties:
+  families:
+    description: |
+      Family names in family ID order: the entry at index N has family ID N.
+      The root family owns ID 0 and so is the first entry, and cannot be
+      deprecated. Every other entry comes after the entry of the family it
+      inherits. A deprecated entry keeps its ID reserved.
+    type: array
+    minItems: 1
+    maxItems: 65536
+    items:
+      oneOf:
+        - $ref: '#/$defs/name'
+        - type: object
+          required: [ name, deprecated ]
+          additionalProperties: false
+          properties:
+            name:
+              $ref: '#/$defs/name'
+            deprecated:
+              const: true
Documentation/ctlv/ctlv-schema.yaml new file +227 -0

227 lines not on this page · raw message

Documentation/ctlv/generated-files-schema.yaml new file +64 -0

64 lines not on this page · raw message

MAINTAINERS +7 -0
index 93abbb315065..5c8e7ad9b599 100644
@@ -7183,6 +7183,13 @@ M:	Jaya Kumar <[email protected]>
 S:	Maintained
 F:	sound/pci/cs5535audio/
 
+CTLV SUBSYSTEM
+M:	Jiri Pirko <[email protected]>
+L:	[email protected]
+S:	Maintained
+F:	Documentation/ctlv/
+F:	tools/ctlv/
+
 CTU CAN FD DRIVER
 M:	Pavel Pisa <[email protected]>
 M:	Ondrej Ille <[email protected]>
tools/ctlv/Makefile new file +39 -0
new file mode 100644
index 000000000000..bdec011595aa
@@ -0,0 +1,39 @@
+# SPDX-License-Identifier: GPL-2.0
+
+KDIR = ../..
+DOCDIR = $(KDIR)/Documentation/ctlv
+
+# Writes nothing. Fails on an invalid specification, and on any generated file
+# or ABI snapshot that regen would change.
+all:
+	@./ctlv-regen.sh -c
+
+# Rewrites every generated file and ABI snapshot, and names each one it writes.
+# A specification change that breaks the committed ABI is refused unless
+# ABI_BREAK=1 says it is meant.
+regen:
+	@./ctlv-regen.sh $(if $(filter 1,$(ABI_BREAK)),-b)
+
+# Style and type checks, needing yamllint, pycodestyle, pyflakes, and mypy
+# with types-PyYAML and types-jsonschema, which the tool itself does not use.
+#
+# A flow sequence is written "[ one, two ]" here, as in the tree's other
+# meta-schemas, which stock yamllint rejects; the same relaxation is in
+# Documentation/devicetree/bindings/.yamllint.
+YAMLLINT_CONF = {extends: default, rules: {brackets: {max-spaces-inside: 1}}}
+
+PYSRC = ctlvgen
+
+lint:
+	yamllint -d "$(YAMLLINT_CONF)" $(DOCDIR)
+	python3 -m pycodestyle $(PYSRC)
+	python3 -m pyflakes $(PYSRC)
+	python3 -m mypy $(PYSRC)
+
+clean:
+	rm -rf ctlvgen/__pycache__
+	rm -rf ctlvgen/lib/__pycache__
+	rm -rf ctlvgen.egg-info
+	rm -rf build
+
+.PHONY: all regen lint clean
tools/ctlv/ctlv-regen.sh new file +64 -0

64 lines not on this page · raw message

tools/ctlv/ctlvgen/__init__.py new file +1 -0
new file mode 100644
index 000000000000..f84069cb2c3d
@@ -0,0 +1 @@
+# SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
tools/ctlv/ctlvgen/cli.py new file +137 -0

137 lines not on this page · raw message

tools/ctlv/ctlvgen/lib/__init__.py new file +1 -0
new file mode 100644
index 000000000000..f84069cb2c3d
@@ -0,0 +1 @@
+# SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
tools/ctlv/ctlvgen/lib/cenum.py new file +178 -0

178 lines not on this page · raw message

tools/ctlv/ctlvgen/lib/cgen.py new file +763 -0

763 lines not on this page · raw message

tools/ctlv/ctlvgen/lib/compat.py new file +877 -0

877 lines not on this page · raw message

tools/ctlv/ctlvgen/lib/errors.py new file +16 -0
new file mode 100644
index 000000000000..f6d557d90f38
@@ -0,0 +1,16 @@
+# SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
+"""The single error type reported by the CTLV schema tool."""
+
+from __future__ import annotations
+
+
+class CtlvError(Exception):
+    """A specification, registry or ABI snapshot is not acceptable.
+
+    The test suite matches diagnostics, so a message's wording is contract.
+    """
+
+    def __init__(self, where: str | None, what: str) -> None:
+        self.where = where
+        self.what = what
+        super().__init__(f'{where}: {what}' if where else what)
tools/ctlv/ctlvgen/lib/gen_family.py new file +285 -0

285 lines not on this page · raw message

tools/ctlv/ctlvgen/lib/gen_kernel.py new file +576 -0

297 lines not on this page · raw message

tools/ctlv/ctlvgen/lib/gen_uapi.py new file +182 -0

182 lines not on this page · raw message

tools/ctlv/ctlvgen/lib/outputs.py new file +355 -0

355 lines not on this page · raw message

tools/ctlv/ctlvgen/lib/semantics.py new file +1219 -0

1,219 lines not on this page · raw message

tools/ctlv/ctlvgen/lib/sizes.py new file +239 -0

239 lines not on this page · raw message

tools/ctlv/ctlvgen/lib/spec.py new file +813 -0

813 lines not on this page · raw message

tools/ctlv/ctlvgen/lib/tree.py new file +158 -0

158 lines not on this page · raw message

tools/ctlv/ctlvgen/lib/yamlload.py new file +138 -0

138 lines not on this page · raw message

tools/ctlv/pyproject.toml new file +30 -0
new file mode 100644
index 000000000000..fe1d04f589b2

Lines of this file are not shown. View the raw message.

tools/ctlv/requirements.txt new file +2 -0
new file mode 100644
index 000000000000..2a73e762f9b9

Lines of this file are not shown. View the raw message.

The rest of this diff is not shown. View the raw message.

Signature · 1 line
2.56.0

Part of the diff is not shown here. View the raw message.

#2 lore raw

Re: [PATCH RFC v2 01/15] ctlv: Add the schema language and generator

Thank you for your contribution! Sashiko AI review found 7 potential issues to consider: - [Low] ctlv: compat: broken $include and shared field reconstruction in _foreign() - [Low] ctlv: semantics…

Thank you for your contribution! Sashiko AI review found 7 potential issues to consider:
- [Low] ctlv: compat: broken $include and shared field reconstruction in _foreign()
- [Low] ctlv: semantics: filled extension point accepted as normal record in _named()
- [Low] ctlv: semantics: order-dependent false record cycle error in _held()
- [Low] ctlv: spec: unresolved relative Path parent traversal in Paths and load()
- [Low] ctlv: semantics: single-pass _check_fills() misses nested extension sites
- [Low] ctlv: spec: _blob() accepts empty argument as valid backing list
- [Low] ctlv: missing composed size and fill depth checks in _check_composed()
--

commit c7763c8379c0de88c3274d5b9d07a09e53102368
Author: Jiri Pirko <[email protected]>

ctlv: Add the schema language and generator

This commit adds the YAML meta-schemas for CTLV family specifications, the family registry, and generated-file manifests, along with the ctlvgen tool to validate specifications, check ABI compatibility, and emit UAPI and kernel C files.

Quoted 5 lines
tools/ctlv/ctlvgen/lib/compat.py new file +0 -0
new file mode 100644
index 0000000000000..76bd14f60750b

[ ... ]

Quoted 13 lines
tools/ctlv/ctlvgen/lib/compat.py new file +13 -0
+def _foreign(family: semantics.Family, record: semantics.Record,
+             own: set[int]) -> dict[str, bool]:
+    """What a record has that it does not declare: placed records and includes.
+
+    An include is one member, optional when it made a field optional that the
+    record it splices requires.
+    """
+    members = {}
+    for member in record.members:
+        field = member.field
+        if field.type in own:
+            continue
+        if field.shared:

tools/ctlv/ctlvgen/lib/compat.py line 288

Quoted 10 lines
tools/ctlv/ctlvgen/lib/compat.py new file +10 -0
+            members[f'record {field.name}'] = member.required
+            continue
+        key = f'$include {field.record}'
+        source = family.records[field.record]
+        declared = any(item.required for item in source.members
+                       if item.field.type == field.type)
+        members.setdefault(key, True)
+        if declared and not member.required:
+            members[key] = False
+    return members

[Severity: Low]
Does reconstructing foreign members from the flattened record.members corrupt ABI snapshots and trigger false ABI breaks?

Because _include() splices target.members directly into the including record while keeping each field's original field.record and field.shared values, if record A places a shared field f or includes record C and record B has "$include: A", _foreign() records "record f" or "$include C" in B's snapshot instead of "$include A".

In addition, _foreign() infers whether "$include X" was written with "?" by checking if any field in X is required while its spliced member is optional. If a request record has "$include: X?" and the last required field in X is later relaxed to optional, declared becomes False for every field of X, so members['$include X'] flips from False to True and _compare_members() reports a false "$include X became required" ABI break.

Quoted 5 lines
tools/ctlv/ctlvgen/lib/semantics.py new file +0 -0
new file mode 100644
index 0000000000000..86725e7c1d693

[ ... ]

tools/ctlv/ctlvgen/lib/semantics.py line 762

Quoted 9 lines
tools/ctlv/ctlvgen/lib/semantics.py new file +9 -0
+    def _named(self, name: str, where: str | None) -> Record:
+        """Return the named record or field of records: called name."""
+        if name in self.named:
+            return self.named[name]
+        if name not in self.declared:
+            if name in self.extensions:
+                raise CtlvError(where, f'{name} is an extension point, which '
+                                       'extension names')
+            raise CtlvError(where, f'no record is called {name}')

[Severity: Low]
Can a filled extension point be referenced as a normal named record via "record <name>" or "$include: <name>"?

When a descendant family fills an inherited extension point in records:, _add_records() adds that name to self.declared and self.named. Because _named() only checks self.extensions when name is absent from self.named and self.declared, referencing the extension point via "record <name>" or "$include: <name>" in the filling family or a further descendant bypasses the self.extensions check and treats the fill as a regular reusable record.

Quoted 3 lines
tools/ctlv/ctlvgen/lib/semantics.py new file +3 -0
+        if name in self.building:
+            raise CtlvError(where, 'record cycle: ' +
+                                   ' -> '.join(self.building + (name,)))

[ ... ]

tools/ctlv/ctlvgen/lib/semantics.py line 815

Quoted 13 lines
tools/ctlv/ctlvgen/lib/semantics.py new file +13 -0
+    def _held(self, name: str, where: str) -> str:
+        """Return the path of the named record a field holds."""
+        self.used.add(name)
+        if name in self.building:
+            # A record holding itself, which the tree re-enters.
+            is_field = self.declared[name][3].body is None
+        else:
+            is_field = self._named(name, where).role == 'field'
+        if is_field:
+            raise CtlvError(where, f'record {name} holds a named record, and '
+                                   f'{name} is a field of records:, which '
+                                   'bare record places')
+        return name

[Severity: Low]
Does _held() raise an order-dependent false "record cycle" error when a held record includes the enclosing record?

If record A has a field "b?: record B" and record B has "$include: A", declaring B before A succeeds because _held('B') sees 'B' in self.building and inspects self.declared['B'][3].body directly. If A is declared before B, _named('A') calls _held('B') while 'A' is in self.building, and _held('B') calls _named('B'), which resolves "$include: A" and fails with "record cycle: A -> B -> A". Checking self.declared[name][3].body whenever name is in self.declared avoids resolving B while A is still being built.

[ ... ]

tools/ctlv/ctlvgen/lib/semantics.py line 1071

Quoted 10 lines
tools/ctlv/ctlvgen/lib/semantics.py new file +10 -0
+    def _check_fills(self, fills: tuple[Fill, ...]) -> None:
+        """Hold each fill to every place its extension point sits.
+
+        A fill nested in another is met after it, so its places are known.
+        """
+        for fill in fills:
+            where = self.declared[fill.name][1]
+            for site, context, level in self.sites.get(fill.name, []):
+                self._check_subtree(f'{where} in {site}', fill.root, context,
+                                    level)

[Severity: Low]
Can a single pass in _check_fills() miss extension sites when a later fill reuses a record containing an earlier-filled extension point?

If an ancestor family declares extension point ext-b inside a named record
rec-b and extension point ext-a in an op, and a descendant fills ext-b before ext-a (either earlier in records: or in an intermediate parent family) while filling ext-a using rec-b, ext-b precedes ext-a in fills. _check_fills() then checks ext-b before visiting ext-a, so the site for ext-b inside ext-a is appended to self.sites['ext-b'] after ext-b's loop has already finished, skipping context and depth validation for ext-b at that site.

[ ... ]

Quoted 18 lines
tools/ctlv/ctlvgen/lib/semantics.py new file +18 -0
+def _check_composed(family: Family) -> None:
+    def walk_composed(where: str, node: Node) -> int:
+        members = composed_members(family, node)
+        required = sum(not optional for _child, optional in members)
+        optional = len(members) - required
+
+        _check_count(where, 'composed required fields', required,
+                     spec.U32_MAX)
+        _check_count(where, 'composed optional fields', optional,
+                     spec.U32_MAX)
+        count = 1
+        for child, _optional in members:
+            count += walk_composed(where, child)
+        return count
+
+    for op in family.ops:
+        total = 0
+        for which, root in (('request', op.request), ('reply', op.reply)):

tools/ctlv/ctlvgen/lib/semantics.py line 1164

Quoted 10 lines
tools/ctlv/ctlvgen/lib/semantics.py new file +10 -0
+            if root is None:
+                continue
+            where = f'{family.path}: op {op.name} {which}'
+            count = walk_composed(where, root)
+            _check_count(where, 'composed schema nodes', count,
+                         spec.U32_MAX)
+            total += count
+        _check_count(f'{family.path}: op {op.name}',
+                     'composed request and reply nodes', total,
+                     spec.U32_MAX)

[Severity: Low]
Does _check_composed() miss checking composed op message sizes against MAX_INLINE_MESSAGE_LEN?

_add_ops() runs sizes.compute() on the uncomposed op tree where extension points are empty, while sizes.composed() in tools/ctlv/ctlvgen/lib/sizes.py is never called here. Even after commit "tools/ctlv: Add the userspace library" calls sizes.composed() in gen_user.py, running ctlvgen with --validate or --mode kernel (or reconciling manifests without optional user-source outputs) will not reject extension fills that push an inherited op's composed request, action reply, or minimum query reply length past MAX_INLINE_MESSAGE_LEN.

Similarly, in tools/ctlv/ctlvgen/lib/gen_kernel.py:_limits(), returning early when family.local_ops is empty skips emitting the CTLV_MAX_DECLARED_RECORD_DEPTH static_assert for family.fills on descendant families that only fill inherited extension points.

Quoted 5 lines
tools/ctlv/ctlvgen/lib/spec.py new file +0 -0
new file mode 100644
index 0000000000000..7d1f2e14f70fd

[ ... ]

Quoted 21 lines
tools/ctlv/ctlvgen/lib/spec.py new file +21 -0
+class Paths:
+    """Where the specs, the registry and the meta-schemas are."""
+
+    def __init__(self, spec: pathlib.Path | str,
+                 schema: pathlib.Path | str | None = None,
+                 registry: pathlib.Path | str | None = None,
+                 abi: pathlib.Path | str | None = None) -> None:
+        self.spec = pathlib.Path(spec)
+        self.spec_dir = self.spec.parent
+        self.doc_dir = self.spec.parent.parent
+        self.schema = pathlib.Path(schema or self.doc_dir / 'ctlv-schema.yaml')
+        self.registry = pathlib.Path(registry or
+                                     self.doc_dir / 'families.yaml')
+        # The two meta-schemas ship together, so overriding one locates both.
+        self.registry_schema = (self.schema.parent /
+                                'ctlv-registry-schema.yaml')
+        self.abi_dir = pathlib.Path(abi or self.doc_dir / 'abi')
+        self.registry_abi = self.abi_dir / 'families.registry.yaml'
+        self.generated = self.doc_dir / 'generated-files.yaml'
+        self.generated_schema = self.doc_dir / 'generated-files-schema.yaml'
+        self.kernel_dir = self.schema.parent.parent.parent

[ ... ]

tools/ctlv/ctlvgen/lib/spec.py line 359

Quoted 8 lines
tools/ctlv/ctlvgen/lib/spec.py new file +8 -0
+def load(path: pathlib.Path | str, schema: pathlib.Path) -> FamilySpec:
+    """Load, syntax-check and normalize one family specification."""
+    path = pathlib.Path(path)
+    data, lines = yamlload.load_with_lines(path)
+    _validate_syntax(path, data, schema)
+
+    reader = _Reader(path, lines,
+                     pathlib.Path(schema).parent.parent.parent / UAPI_DIR)

[Severity: Low]
Does traversing .parent on unresolved relative Path objects in Paths.__init__() and load() misresolve kernel_dir and the UAPI directory?

In pathlib, taking .parent on a relative path strips components until it reaches Path('.'), where .parent stays Path('.'). If ctlvgen is invoked from Documentation/ctlv/ with "--spec specs/ctlv.yaml --validate", self.schema is Path('ctlv-schema.yaml') and self.schema.parent.parent.parent collapses to Path('.') instead of the kernel tree root, mislocating both self.kernel_dir and include/uapi. Resolving the paths first (or using os.path.abspath) avoids this.

[ ... ]

Quoted 8 lines
tools/ctlv/ctlvgen/lib/spec.py new file +8 -0
+    def _blob(self, where: str, args: str) -> BlobDecl:
+        parts = _arguments(args) if args is not None else ['']
+        direction = DIRECTIONS.get(parts[0])
+        if direction is None:
+            raise CtlvError(where, 'a blob starts with its direction, in, '
+                                   'out or inout')
+        maximum, alignment, backings = None, None, None
+        for arg in parts[1:]:

tools/ctlv/ctlvgen/lib/spec.py line 744

Quoted 10 lines
tools/ctlv/ctlvgen/lib/spec.py new file +10 -0
+            aligned = _ALIGN.fullmatch(arg)
+            if arg.startswith('..') and maximum is None:
+                maximum = self._size(where, arg[2:].strip(), 'blob length',
+                                     U64_MAX)
+            elif aligned is not None and alignment is None:
+                alignment = self._size(where, aligned['value'],
+                                       'blob alignment')
+            elif backings is None and all(word in BACKINGS
+                                          for word in arg.split()):
+                backings = tuple(arg.split())

[Severity: Low]
Does _blob() silently accept an empty comma-separated argument such as "blob(in, )"?

When arg is empty, arg.split() is [], so all(word in BACKINGS for word in arg.split()) evaluates to True and sets backings = (), which is then replaced by DEFAULT_BACKINGS via "backings or DEFAULT_BACKINGS". Checking that arg.split() is non-empty would reject malformed empty arguments.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
author
#3 lore raw

RFC PATCH v2 2/15 ctlv: Add the UAPI message format and family API

In reply to Jiri Pirko

From: Jiri Pirko <[email protected]>

Define CTLV's common TLV transport, ioctl and identifiers. Add the in-kernel API used by family implementations and generated code, including the implementation limits: userspace learns the lengths of each op from the device, so they stay out of the UAPI.

Assisted-by Cursor: GPT-5.6 Sol
Assisted-by Cursor: Claude Opus 5.5

---
RFC->RFCv2:
- handed family callbacks the CTLV instance, and dropped the family priv and its lifecycle hooks
- sized struct ctlv_op_exec by a field, not the ioctl number
- moved the implementation limits to <linux/ctlv_family.h>
- lowered the inline message limit to 64 KiB
- lowered the record depth limit to 8
- aligned attrs with __ALIGN_KERNEL()
- defined the attr flags with _BITUL()
- spelled out the callback signatures in the ops structures
- wrote the schema macros as compound literals
- dropped the event record header and CTLV_OP_SCHEMA_EVENT()
- renamed the stub schemas and ops to extension schemas and ops
- let an enum's range start at any value
- said how long a cursor lives and what bounds the record depth
- renamed struct ctlv_attr to struct ctlv_hdr and its attr_id to type
- built a type from the family, a record and a field, in place of an attr group and number
- said TLV, type, record and field instead of attr
- said record instead of nest, the root being one
- dropped "physical" from the cursor kernel-doc
- numbered every enum member
- moved the UAPI header to include/uapi/ctlv/, as <ctlv/ctlv.h>
- added the schemas of enum extension points and their fills
- said message instead of wire
- retitled from "Add the UAPI wire format and family API"
- moved the ioctl number registration to the dispatch patch

---
 MAINTAINERS                 |   2 +
 include/linux/ctlv.h        |  57 +++++
 include/linux/ctlv_family.h | 431 ++++++++++++++++++++++++++++++++++++
 include/uapi/ctlv/ctlv.h    | 180 +++++++++++++++
 4 files changed, 670 insertions(+)
 create mode 100644 include/linux/ctlv.h
 create mode 100644 include/linux/ctlv_family.h
 create mode 100644 include/uapi/ctlv/ctlv.h
MAINTAINERS +2 -0
index 5c8e7ad9b599..bf6d5bab0da9 100644
@@ -7188,6 +7188,8 @@ M:	Jiri Pirko <[email protected]>
 L:	[email protected]
 S:	Maintained
 F:	Documentation/ctlv/
+F:	include/linux/ctlv*.h
+F:	include/uapi/ctlv/
 F:	tools/ctlv/
 
 CTU CAN FD DRIVER
include/linux/ctlv.h new file +57 -0

57 lines not on this page · raw message

include/linux/ctlv_family.h new file +431 -0

431 lines not on this page · raw message

include/uapi/ctlv/ctlv.h new file +180 -0

180 lines not on this page · raw message

Signature · 1 line
2.56.0
author
#4 lore raw

RFC PATCH v2 3/15 ctlv: Add the root family specification and generated files

In reply to Jiri Pirko

From: Jiri Pirko <[email protected]>

Define the root family used by every CTLV device. Add its ABI snapshot, registry and manifest entries, and generated outputs.

The generated kernel descriptor is preparatory and is linked after its handlers arrive with operation dispatch.

Assisted-by Cursor: GPT-5.6 Sol
Assisted-by Cursor: Claude Opus 5.5

---
RFC->RFCv2:
- reported the error information length of actions and queries
- dropped the root family's priv and its hooks
- dropped the event ops, the events and the sets, groups and attrs only they use
- warned against adding a family before agreeing its position
- wrote the spec as op trees and records
- added required-length to the error information
- said node instead of placement
- said record instead of nest, the root being one
- numbered every enum member
- moved the generated UAPI headers to include/uapi/ctlv/
- documented every item of the spec
- put each field's doc above its generated helpers
- renamed families-dump and ops-dump to family-get and op-get
- put ctlv_gen.c in lib/ctlv/
- said message instead of wire

---
 Documentation/ctlv/abi/ctlv.yaml              | 111 +++++++
 Documentation/ctlv/abi/families.registry.yaml |   7 +
 Documentation/ctlv/families.yaml              |  17 ++
 Documentation/ctlv/generated-files.yaml       |  17 ++
 Documentation/ctlv/specs/ctlv.yaml            | 211 +++++++++++++
 include/linux/ctlv_gen.h                      | 154 ++++++++++
 include/uapi/ctlv/ctlv_families_gen.h         |  17 ++
 include/uapi/ctlv/ctlv_gen.h                  | 278 ++++++++++++++++++
 lib/ctlv/ctlv_gen.c                           | 161 ++++++++++
 9 files changed, 973 insertions(+)
 create mode 100644 Documentation/ctlv/abi/ctlv.yaml
 create mode 100644 Documentation/ctlv/abi/families.registry.yaml
 create mode 100644 Documentation/ctlv/families.yaml
 create mode 100644 Documentation/ctlv/generated-files.yaml
 create mode 100644 Documentation/ctlv/specs/ctlv.yaml
 create mode 100644 include/linux/ctlv_gen.h
 create mode 100644 include/uapi/ctlv/ctlv_families_gen.h
 create mode 100644 include/uapi/ctlv/ctlv_gen.h
 create mode 100644 lib/ctlv/ctlv_gen.c
Documentation/ctlv/abi/ctlv.yaml new file +111 -0
new file mode 100644
index 000000000000..dc26ba575a68
@@ -0,0 +1,111 @@
+# SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)
+%YAML 1.2
+---
+# Checked-in ABI snapshot of the ctlv family, from
+# Documentation/ctlv/specs/ctlv.yaml, written by
+# "make -C tools/ctlv regen".
+#
+# Updating the file is how a UAPI change gets reviewed; an update that
+# removes or renumbers anything, narrows a bound, or makes a member required
+# is an ABI break, whatever the file says afterwards.
+family: {name: ctlv, id: 0}
+enums:
+  op-type: {action: 1, query: 2}
+  op-availability: {fixed: 1, dynamic: 2}
+  blob-type: {va: 1}
+  blob-direction: {input: 1, output: 2, inout: 3}
+  validation-reason: {malformed-message: 1, unknown-type: 2, unknown-flag: 3,
+                      record-too-deep: 4, missing-field: 5,
+                      too-many-occurrences: 6, value-out-of-range: 7,
+                      bad-length: 8, bad-string: 9, bad-blob-descriptor: 10,
+                      stale-generation: 11, noncontiguous-type: 12}
+  op-fd-access: {read: 1, read-write: 2}
+records:
+  blob:
+    id: 0x00010000
+    fields:
+      type: {number: 1, enum: blob-type}
+      address: {number: 2, type: uint, optional: true}
+      fd: {number: 3, type: uint, max: s32-max, optional: true}
+      offset: {number: 4, type: uint, optional: true}
+      length: {number: 5, type: uint, min: 1}
+  error-info:
+    id: 0x00020000
+    fields:
+      reason: {number: 1, enum: validation-reason, optional: true}
+      message: {number: 2, type: string, max-length: 255, optional: true}
+      bad-tlv-offset: {number: 3, type: uint, optional: true}
+      record-offset: {number: 4, type: uint, optional: true}
+      missing-type: {number: 5, type: uint, optional: true}
+      expected-generation: {number: 6, type: uint, optional: true}
+      current-generation: {number: 7, type: uint, optional: true}
+      required-length: {number: 8, type: uint, optional: true}
+  schema-node:
+    id: 0x00030000
+    fields:
+      type: {number: 1, type: uint}
+      kind: {number: 2, type: uint}
+      max-occurrences: {number: 3, type: uint}
+      min: {number: 4, type: uint, optional: true}
+      max: {number: 5, type: uint, optional: true}
+      min-length: {number: 6, type: uint, optional: true}
+      max-length: {number: 7, type: uint, optional: true}
+      flags-mask: {number: 8, type: uint, optional: true}
+      unit: {number: 9, type: uint, optional: true}
+      scale: {number: 10, type: sint, optional: true}
+      blob-direction: {number: 11, enum: blob-direction, optional: true}
+      blob-backings: {number: 12, type: uint, optional: true}
+      blob-max-length: {number: 13, type: uint, optional: true}
+      blob-alignment: {number: 14, type: uint, optional: true}
+      reenters: {number: 15, type: uint, min: 1, optional: true}
+      fields: {number: 16, record: schema-node, max-occurrences: unlimited,
+               optional: true}
+      optional-fields: {number: 17, record: schema-node,
+                        max-occurrences: unlimited, optional: true}
+  family-get request:
+    id: 0x80010000
+  family-get reply:
+    id: 0xc0010000
+    fields:
+      families: {number: 1, record: family-get families,
+                 max-occurrences: unlimited}
+  family-get families:
+    id: 0xc0011000
+    fields:
+      id: {number: 1, type: uint}
+      name: {number: 2, type: string, max-length: 63}
+  op-get request:
+    id: 0x80020000
+  op-get reply:
+    id: 0xc0020000
+    fields:
+      ops: {number: 1, record: op-get ops, max-occurrences: unlimited}
+  op-get ops:
+    id: 0xc0021000
+    fields:
+      id: {number: 1, type: uint, min: 1}
+      type: {number: 2, enum: op-type}
+      availability: {number: 3, enum: op-availability, optional: true}
+      disabled: {number: 4, type: bool, optional: true}
+      request-max-len: {number: 5, type: uint, optional: true}
+      action-reply-max-len: {number: 6, type: uint, optional: true}
+      query-reply-min-len: {number: 7, type: uint, optional: true}
+      query-reply-suggested-len: {number: 8, type: uint, optional: true}
+      fd-access: {number: 9, enum: op-fd-access, optional: true}
+      error-info-max-len: {number: 10, type: uint, optional: true}
+  op-schema-get request:
+    id: 0x80030000
+    fields:
+      id: {number: 1, type: uint, min: 1}
+  op-schema-get reply:
+    id: 0xc0030000
+    fields:
+      request: {number: 1, record: schema-node, optional: true}
+      reply: {number: 2, record: schema-node, optional: true}
+ops:
+  family-get: {id: 1, type: query, fd-access: read, request: family-get request,
+               reply: family-get reply}
+  op-get: {id: 2, type: query, fd-access: read, request: op-get request,
+           reply: op-get reply}
+  op-schema-get: {id: 3, type: query, fd-access: read,
+                  request: op-schema-get request, reply: op-schema-get reply}
Documentation/ctlv/abi/families.registry.yaml new file +7 -0
new file mode 100644
index 000000000000..5845e7457771
@@ -0,0 +1,7 @@
+# SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)
+%YAML 1.2
+---
+# Checked-in ABI baseline of the ordered CTLV family registry.
+# Written by "make -C tools/ctlv regen".
+families:
+  - ctlv
Documentation/ctlv/families.yaml new file +17 -0
new file mode 100644
index 000000000000..4d219d7af74a
@@ -0,0 +1,17 @@
+# SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)
+%YAML 1.2
+---
+# Do not add a family without agreeing its position with the CTLV
+# maintainers (CTLV SUBSYSTEM in MAINTAINERS) first. The position is the
+# family ID, so families added in parallel trees end up with the same ID.
+#
+# Append-only registry of CTLV family names, indexed by family ID: the entry at
+# index N has family ID N, up to 65535. The root family owns ID 0 and heads the
+# list, and every other entry comes after the entry of the family it inherits.
+# An entry may be marked deprecated, but never reordered, removed, renamed or
+# reused, its position being its family ID. Every entry must have a
+# specification in specs/<name>.yaml, and is added by the change that adds the
+# implementation. Fixtures under tools/ctlv/tests/ are not registered.
+
+families:
+  - ctlv
Documentation/ctlv/generated-files.yaml new file +17 -0
new file mode 100644
index 000000000000..5488ddf40e17
@@ -0,0 +1,17 @@
+# SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)
+%YAML 1.2
+---
+# Generated files for registered families.
+version: 1
+registry:
+  source: Documentation/ctlv/families.yaml
+  outputs:
+    uapi-header: include/uapi/ctlv/ctlv_families_gen.h
+
+families:
+  - name: ctlv
+    source: Documentation/ctlv/specs/ctlv.yaml
+    outputs:
+      uapi-header: include/uapi/ctlv/ctlv_gen.h
+      kernel-header: include/linux/ctlv_gen.h
+      kernel-source: lib/ctlv/ctlv_gen.c
Documentation/ctlv/specs/ctlv.yaml new file +211 -0

211 lines not on this page · raw message

include/linux/ctlv_gen.h new file +154 -0

154 lines not on this page · raw message

include/uapi/ctlv/ctlv_families_gen.h new file +17 -0
new file mode 100644
index 000000000000..83f1719c89aa
@@ -0,0 +1,17 @@
+/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) */
+/*
+ * Generated from Documentation/ctlv/families.yaml by
+ * tools/ctlv/ctlv-regen.sh. Do not edit.
+ */
+/* CTLV-GEN uapi header */
+
+/* CTLV family numbers. */
+
+#ifndef _UAPI_CTLV_CTLV_FAMILIES_GEN_H
+#define _UAPI_CTLV_CTLV_FAMILIES_GEN_H
+
+enum _ctlv_family {
+	CTLV_FAMILY_ROOT = 0,
+};
+
+#endif /* _UAPI_CTLV_CTLV_FAMILIES_GEN_H */
include/uapi/ctlv/ctlv_gen.h new file +278 -0

278 lines not on this page · raw message

lib/ctlv/ctlv_gen.c new file +161 -0

161 lines not on this page · raw message

Signature · 1 line
2.56.0
author
#5 lore raw

RFC PATCH v2 4/15 Documentation: ctlv: Add userspace ABI

In reply to Jiri Pirko

From: Jiri Pirko <[email protected]>

Describe what CTLV is for, its terms, transport, discovery, message format and userspace compatibility rules.

Existing interfaces each miss some of the needs listed under Goals. An ioctl with a structure of its own fixes its layout, so variable data needs pointers to more structures, each subsystem validates its own, and strace needs a decoder for every ioctl. sysfs and configfs assemble one request through several files, with no point where the whole request is checked and executed at once. Netlink is built around sockets and network namespaces, a poor fit for devices that have nothing to do with either and want the DAC model of a device node.

Assisted-by Cursor: GPT-5.6 Sol
Assisted-by Cursor: Claude Opus 5.5

---
RFC->RFCv2:
- documented the size and flags of struct ctlv_op_exec
- documented EOVERFLOW for a blob range that wraps
- documented that a reply buffer may be any length
- replaced the limits section with the lengths a device reports
- dropped the events
- reworked the document after review, opening with a worked example
- said how a program finds a device's family
- said what a blob descriptor is made of and how a bad one fails
- said TLV, type, record and field instead of attr
- said record instead of nest, the root being one
- said how a type is made of a family, a record and a field
- imported path_id in the udev rule that matches ID_PATH
- opened with the goals
- added a glossary, and dropped "physical"
- collected the compatibility rules in one section
- kept open()'s errors apart from the ioctls'
- documented required-length, the length an output blob needs
- took the UAPI headers from include/uapi/ctlv/
- documented enum extension points
- said message instead of wire
- added a worked type example
- led the devices section with a subsystem's own nodes
- said where stable device names come from, with a udev rule
- gave the glossary an example of an extension point

---
 Documentation/userspace-api/ctlv.rst  | 694 ++++++++++++++++++++++++++
 Documentation/userspace-api/index.rst |   1 +
 MAINTAINERS                           |   1 +
 3 files changed, 696 insertions(+)
 create mode 100644 Documentation/userspace-api/ctlv.rst
Documentation/userspace-api/ctlv.rst new file +694 -0
new file mode 100644
index 000000000000..f1f775071a78
@@ -0,0 +1,694 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+==================
+CTLV userspace ABI
+==================
+
+:Author: Jiri Pirko
+
+Char-Device Tag-Length-Value (CTLV) is a flexible way to describe system calls
+delivered over ioctl for a kernel subsystem. It provides a 64-bit operation
+number with variable-length input and output arguments described in a YAML
+schema. The arguments are serialized using a TLV scheme. Strong support for
+forward and backward compatibility is baked into the schema design.
+
+CTLV excels for uAPIs that are too unconstrained to fit in simple structs:
+things that have arrays of arrays, variable-size structs, variable-sized data,
+strings and similar, which are challenging to represent otherwise.
+
+As a transport, CTLV uses a global number space. Inspection tools like strace,
+or a seccomp user-notification supervisor, can always decode a CTLV ioctl
+without having to know what subsystem is using it. The global number space is
+organized into families, each roughly corresponding to a subsystem.
+
+A family describes what its devices accept in YAML, a generator turns that into
+kernel metadata, UAPI headers and userspace bindings, and CTLV validates every
+message before a family callback sees it. Userspace executes every operation
+through one ioctl.
+
+This document is the ABI. What each family accepts is specified under
+``Documentation/ctlv/specs``; writing a family is :doc:`/driver-api/ctlv`.
+
+Goals
+=====
+
+A uAPI too unconstrained for fixed structures needs four things: every request
+checked before a driver sees it, against one description that its headers and
+documentation come from too; room to grow in both directions without versions;
+one encoding that tools decode without knowing the subsystem; and answers
+larger than the caller's buffer, read in parts that stay consistent.
+
+CTLV is not worth it for a value or two, where a sysfs attribute or a plain
+ioctl is simpler.
+
+Each part of the design serves one of the needs:
+
+- The schema. CTLV checks a message's bounds, lengths, occurrence counts and
+  record depth (a record is a TLV of TLVs) against it before a family callback
+  runs, and the generator makes the kernel metadata, the UAPI header, the
+  userspace bindings and the documentation from it.
+- The tree of TLVs, for records and variable data. Fields are optional or
+  required by declaration, so a message can grow without breaking a caller
+  that does not know the new field.
+- One ioctl over a global number space. A new operation is a new
+  specification entry rather than a new ioctl number, and strace or a seccomp
+  supervisor decodes any family.
+- Queries apart from actions. Only a query can be answered in parts: the
+  kernel returns what fits with a cursor to continue from, and a generation,
+  so that a caller whose answer changed between the parts gets ``ESTALE``
+  rather than a mix of two states.
+- Introspection. Every device answers ``family-get``, ``op-get`` and
+  ``op-schema-get``, so a program built without a family still learns what
+  the device accepts.
+
+`Compatibility`_ collects the rules for growing a family.
+
+An example
+==========
+
+Take ``ctlv-example``, a small invented family whose devices hold numbered
+items, each with an optional label; :doc:`/driver-api/ctlv` writes it. Its
+system calls are::
+
+    item_set_action(u64 index, string label?, blob data?) -> status;
+    item_get_query() -> { u64 index; string label?; }[];
+
+``?`` marks an optional argument. The family's specification declares
+``item-set`` with the bounds the kernel checks:
+
+.. code-block:: yaml
+
+    ops:
+      # Sets an item's label and data.
+      item-set:
+        type: action
+        request:
+          # Which item it is.
+          index: uint(..4095)
+          # What the item is called.
+          label?: string(..63)
+          # The item's contents, which the device reads.
+          data?: blob(in, ..1M, align 8, va)
+
+To set the label of item 3 to "ab", a program builds a request of two TLVs,
+the index and the label, under the root every message starts with::
+
+    offset  TLV               len  flags   contents
+    ------  ----------------  ---  ------  ----------------
+         0  root               64  RECORD  type = 0
+        16  .. index           24  -       3
+        40  .. label           19  -       "ab" and its NUL
+        64  end of message
+
+and passes it to the device:
+
+.. code-block:: c
+
+    struct ctlv_op_exec exec = {
+            .size = sizeof(exec),
+            .op_id = CTLV_EXAMPLE_OP_ITEM_SET,
+            .request = (__u64)(uintptr_t)msg,
+            .request_len = 64,
+    };
+
+    if (ioctl(fd, CTLV_IOC_OP_EXEC, &exec))
+            err(1, "item-set");
+
+The op ID and the types come from the family's generated UAPI header.
+Before the family sees the request, the kernel checks it against the
+specification: ``index`` must be at most 4095 and ``label`` at most 63 bytes.
+
+The sections below define each piece: the device, the message format, the
+ioctl, queries, blobs and introspection, and then the rules of compatibility.
+
+Terms
+=====
+
+family
+    The specification of what a device accepts, its operations and records,
+    under one number of the global number space. A family may inherit another,
+    its parent, taking its operations and filling the extension points it
+    leaves. A device answers as one family and is compatible with each of its
+    ancestors.
+
+operation, op
+    What a family declares a device does: an action, executed once and
+    acknowledged, or a query.
+
+TLV
+    Type, length, value: a ``struct ctlv_hdr`` and its payload.
+
+record
+    A TLV whose payload is TLVs, its fields, flagged ``CTLV_HDR_F_RECORD``:
+    a named record of the family, an operation's request or reply, or a
+    record declared inside one of those.
+
+root
+    The record a message starts with, of type zero: the operation's request
+    or reply.
+
+message
+    A request or a reply: one root record.
+
+field
+    One member of a record, a value or a record, required or optional, with its
+    bounds and how often it may repeat.
+
+type
+    The 64-bit number in a TLV's header naming its family, its record and its
+    field.
+
+extension point
+    A field a family leaves for a descendant family to fill with a record of
+    its own, as ``ctlv-accelerator`` leaves ``device-info`` for
+    ``ctlv-accelerator-foo``.
+
+enum extension point
+    An enum a family leaves for a descendant family to give values, so that a
+    device takes the values its own family chain gives.
+
+query
+    An operation answered in as many fragments as its answer needs, which a
+    generation keeps consistent.
+
+fragment
+    One reply of a query: as much of the answer as fits, with a cursor to
+    continue from.
+
+Devices
+========
+
+A device appears in one of two places, and the same ioctls run its family's
+operations on both:
+
+- a character device of a subsystem, in its class and ``/dev`` directory, as
+  an accelerator subsystem would have it::
+
+      /dev/accelerator/accelerator0
+      /sys/class/accelerator/accelerator0
+
+- a file whose other operations are a subsystem's own.
+
+Sysfs shows class membership, the ``dev`` number and the device-model link to
+the parent device. There is no family sysfs attribute; ``family-get`` on an
+open descriptor is the authoritative answer to what a device is.
+
+The number in a name says nothing about the device and, like ``sdX`` or
+``eventN``, may differ between boots. Stable names come from udev rules
+matching the uevent properties described under Discovery. A container is
+given such a name, ``/dev/ctlv-example`` below, rather than whichever number
+the device got.
+
+``O_RDONLY`` opens an observation fd, ``O_RDWR`` opens a full-control fd, and
+``O_WRONLY`` is rejected with ``-EACCES``. Every action and query declares the
+authority it needs: ``read`` permits either accepted fd, while ``read-write``
+requires full control. ``dup()`` and ``SCM_RIGHTS`` preserve that authority;
+attenuation requires a separate observation open.
+
+Discovery
+---------
+
+Both uevents, addition and removal, carry the family chain as numbered
+properties::
+
+    CTLV_FAMILY=ctlv-accelerator-foo
+    CTLV_COMPATIBLE_0=ctlv
+    CTLV_COMPATIBLE_1=ctlv-accelerator
+    CTLV_COMPATIBLE_2=ctlv-accelerator-foo
+    CTLV_COMPATIBLE_N=3
+
+``CTLV_FAMILY`` is the family the device answers as, the numbered properties
+are its ancestry from the root to that family, and ``CTLV_COMPATIBLE_N`` is
+how many there are. An index never moves: changing a family's parent is an
+ABI break, adding a descendant only appends.
+
+A device's uevents carry them whichever subsystem it is in, so a program finds
+every device by ``CTLV_FAMILY`` rather than by class. A program that wants
+every device, including ones appearing while it starts, must listen before it
+looks, which closes the window between enumerating and subscribing::
+
+    1. create a udev monitor and enable it
+    2. enumerate the existing character devices whose uevent has CTLV_FAMILY
+    3. drain the events already queued on the monitor, keeping those with it
+    4. deduplicate by sysfs path
+    5. open the device node
+    6. ask family-get on the open descriptor for the authoritative chain
+
+Steps 1 to 4 are pre-open discovery, all a udev rule can match on; step 6 does
+not need a udev database. A rule matches a family through the compatibility
+properties::
+
+    # /etc/udev/rules.d/70-ctlv.rules
+    #
+    # Anything of one family, whatever family implementation registered it.
+    ENV{CTLV_FAMILY}=="ctlv-accelerator-foo", GROUP="accel", MODE="0660"
+
+    # Anything descended from a family.
+    ENV{CTLV_COMPATIBLE_1}=="ctlv-accelerator", TAG+="uaccess"
+
+    # A stable name for a family with one device per system.
+    ENV{CTLV_FAMILY}=="ctlv-example", SYMLINK+="ctlv-example"
+
+    # A stable name per parent device, for a family with several devices.
+    ENV{CTLV_FAMILY}=="ctlv-accelerator-foo", IMPORT{builtin}="path_id"
+    ENV{CTLV_FAMILY}=="ctlv-accelerator-foo", ENV{ID_PATH}=="?*", \
+        SYMLINK+="accel/by-path/$env{ID_PATH}"
+
+A device whose uevent leaves the family out has a file a program opens by the
+device's own name, and the open descriptor answers ``family-get`` all the
+same.
+
+CTLV does not standardise such aliases and does not promise that a generic
+identifier survives a reboot or a reprobe; a family with a meaningful identity
+exposes it through an operation of its own.
+
+Message format
+==============
+
+A message is a tree of TLVs. Every TLV begins with the same header, at an
+eight-byte boundary::
+
+    struct ctlv_hdr {
+            __u32 len;              /* header + payload, without padding */
+            __u32 flags;            /* CTLV_HDR_F_* */
+            __aligned_u64 type;     /* family, record, field; 0 for a root */
+    };
+
+One unsigned integer TLV with an eight-byte payload, in a message::
+
+     0                   1                   2                   3
+     0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+    +---------------------------------------------------------------+
+    |                        len = 24                               |
+    +---------------------------------------------------------------+
+    |                        flags = 0                              |
+    +---------------------------------------------------------------+
+    |                                                               |
+    +                       type                                    +
+    |                                                               |
+    +---------------------------------------------------------------+
+    |                                                               |
+    +                       payload                                 +
+    |                                                               |
+    +---------------------------------------------------------------+
+
+The rules that make a tree out of that:
+
+- ``CTLV_ALIGNTO`` is 8 and ``CTLV_ALIGN()`` rounds up to it. Every TLV
+  starts at a multiple of eight.
+- ``len`` counts this header plus this TLV's payload, not its own trailing
+  padding.
+- A record's payload is the concatenation of ``CTLV_ALIGN(child.len)`` bytes
+  per child, so a child's padding is counted inside its parent's ``len`` and
+  a leaf's own padding by nobody.
+- ``CTLV_HDR_F_RECORD`` is set exactly on a record, the root included.
+- A message begins with one root, whose ``type`` is ``CTLV_TYPE_ROOT``
+  (zero) and whose payload is the message. A root never appears inside a
+  record, and a record never carries the root type.
+- Scalar payloads are native-endian and their lengths exact: eight bytes for
+  an integer, one byte holding zero or one for a boolean, the string including
+  its NUL terminator, the declared length for binary data.
+- A message goes no deeper than its operation's schema, the root being level
+  zero.
+
+A whole message with every offset, for a request of one integer and one record
+carrying a string and a further record::
+
+    offset  TLV                             len  flags   contents
+    ------  ------------------------------  ---  ------  ----------------
+         0  root                            120  RECORD  type = 0
+        16  .. chunks                        24  -       8-byte integer
+        40  .. chunk                         80  RECORD
+        56     .. label                      19  -       "ab" and its NUL
+        80     .. item                       40  RECORD
+        96        .. value                   24  -       8-byte integer
+       120  end of message
+
+    +----------------------------------------------------------------------+ 0
+    | root: len = 120, flags = RECORD, type = 0                            |
+    |   +----------------------------------------------------------------+ | 16
+    |   | chunks: len = 24 | payload: 8 bytes                            | |
+    |   +----------------------------------------------------------------+ | 40
+    |   | chunk: len = 80, flags = RECORD                                | |
+    |   |   +----------------------------------------------------------+ | | 56
+    |   |   | label: len = 19 | payload: 'a' 'b' 0 | 5 bytes padding   | | |
+    |   |   +----------------------------------------------------------+ | | 80
+    |   |   | item: len = 40, flags = RECORD                           | | |
+    |   |   |   +----------------------------------------------------+ | | | 96
+    |   |   |   | value: len = 24 | payload: 8 bytes                 | | | |
+    |   |   |   +----------------------------------------------------+ | | | 120
+    |   |   +----------------------------------------------------------+ | |
+    |   +----------------------------------------------------------------+ |
+    +----------------------------------------------------------------------+
+
+``label.len`` is 19: its header and three payload bytes, not the five bytes of
+padding after it. ``chunk`` counts those five, its ``len`` of 80 being its
+header plus ``CTLV_ALIGN(19)`` plus ``CTLV_ALIGN(40)``. A walk over a record's
+children advances by ``CTLV_ALIGN(child.len)``, a walk of one payload by
+``child.len``.
+
+A type names the family that declared it, a record within that family and a
+field within that record::
+
+     63      48 47 46 45     32 31 28 27 24 23 20 19 16 15        0
+    +----------+-----+---------+-----+-----+-----+-----+-----------+
+    |  family  |kind |  index  | L1  | L2  | L3  | L4  |   field   |
+    +----------+-----+---------+-----+-----+-----+-----+-----------+
+               |<--------------- record -------------->|
+
+    CTLV_TYPE(family, record, field)
+    CTLV_TYPE_FAMILY(type) / CTLV_TYPE_KIND(type) / CTLV_TYPE_RECORD(type) /
+    CTLV_TYPE_FIELD(type)
+
+A record's type kind, ``enum ctlv_type_kind``, says what it starts from: a
+named record of the family (``CTLV_TYPE_KIND_NAMED``), an op's request
+(``_REQUEST``), or an op's reply (``_REPLY``). The index
+is the named record's place among the family's records, or the op's number. A
+record declared inside one of those adds a path, one hex digit a level for up
+to four levels, saying which it is among the records declared beside it,
+from 1; zero ends the path. The field is its place in its record, from 1. A
+named record has the same types in every message that carries it.
+
+If ``ctlv-example`` were family 7, ``label`` in an item of the reply of
+``item-get``, its op 2, would be ``0x0007c00210000002``. Read in blocks of
+four hex digits, ``0007`` is the family, ``c002`` op 2's reply, ``1000`` the
+path to ``items``, the reply's first record, and ``0002`` the field, the
+second of an item.
+
+An operation ID is the family and the op's number, with the record bits
+zero::
+
+    CTLV_OP(family, op)
+    CTLV_OP_FAMILY(op) / CTLV_OP_NUMBER(op)
+
+Use the generated types and op IDs. A family's header defines every type it
+declares and includes its parent's.
+
+TLV order
+---------
+
+TLVs may come in any order, with one rule: within the root and within each
+record of a request, all TLVs of one type, such as the elements of an array,
+must be next to each other. ``A A B`` and ``B A A`` are valid; ``A B A`` is
+not. An unknown TLV the kernel skips (see the next section) separates two of
+them too, so ``A X A`` is invalid even when ``X`` is skipped.
+
+TLVs an older kernel may skip
+-----------------------------
+
+A program built against a newer version of a family may want to send a field
+that an older kernel does not know. Normally an unknown type fails the
+request. Setting ``CTLV_HDR_F_IGNORE_IF_UNKNOWN`` in a TLV's header asks the
+kernel to skip it instead, together with everything in it.
+
+The flag only matters for a type that none of the device's families
+declares. A type the device knows is validated as usual, flag or not:
+it fails the request where the schema does not place it, and is checked
+against its bounds where it does. A skipped TLV still has to be well
+formed: its length must fit inside its record, and its header may carry only
+defined flags. The root cannot carry the flag, and replies never do.
+
+So the kernel acts on what it knows and ignores the rest. A caller that needs
+to know which of its fields will be acted on asks ``op-schema-get`` first.
+
+Executing an operation
+======================
+
+One ioctl executes every operation::
+
+    struct ctlv_op_exec {
+            __u32 size;                 /* sizeof(struct ctlv_op_exec) */
+            __u32 flags;                /* must be zero */
+            __aligned_u64 op_id;
+            __aligned_u64 request;      /* struct ctlv_hdr __user * */
+            __aligned_u64 reply;        /* struct ctlv_hdr __user * */
+            __u32 request_len;
+            __u32 reply_len;
+            __aligned_u64 generation;   /* queries only */
+            __aligned_u64 cursor;       /* queries only */
+    };
+
+    #define CTLV_IOC_OP_EXEC _IO(0xBB, 0x00)
+
+``size`` is the size of the structure the caller was built with, at least the
+56 bytes of this first version. The structure only grows at its end, and the
+kernel reads ``size`` bytes: a field past the end of an older caller's
+structure reads as zero, and bytes a newer caller sends past the fields this
+kernel knows must be zero. The kernel writes back only within ``size``.
+
+``request_len`` is how many bytes the kernel may read at ``request`` and
+``reply_len`` how many it may write at ``reply``. They are copy boundaries, not
+message lengths: a root's ``len`` may be shorter than ``request_len``, the
+bytes after it being ignored, and may not be longer. ``reply_len`` is never
+overwritten; the length written is the reply root's ``len``. It may be any
+length: a query's fragment stops at a limit of the kernel's own, leaving the
+rest of a longer buffer unused. The pointers are fixed-width so a 32-bit and a
+64-bit process pass the same structure.
+
+Every action and query carries a request root, even where the request is
+empty, so ``request_len`` is at least one header. The
+``request-max-len`` reported by ``op-get`` is the maximum request composed
+from the known schema; a newer caller may exceed it with well-formed unknown
+TLVs marked ``IGNORE_IF_UNKNOWN``. The kernel refuses a request longer than a
+limit of its own, which no request composed from a schema exceeds.
+
+The two op types differ in what they answer:
+
+action
+    Executed once and acknowledged. ``reply_len`` is at least the
+    ``action-reply-max-len`` in ``op-get``, zero for an action that answers
+    nothing.
+
+query
+    Executed once and answered in as many fragments as it needs, using
+    ``generation`` and ``cursor``. ``reply_len`` is at least the
+    ``query-reply-min-len`` in ``op-get``, which also suggests a length as
+    ``query-reply-suggested-len``.
+
+Errors
+------
+
+A failed operation returns a negative errno. Where the failure is a rule the
+message broke and the caller offered a reply buffer, CTLV also writes
+error information there in TLV form: a ``validation-reason`` value, a
+human-readable message, the offset of the offending TLV, the offset of the
+record it was in, the type of a missing field, the length an output blob
+needs, and for a stale query the expected and the current generation. A
+buffer of the operation's ``error-info-max-len`` in ``op-get`` has room for
+it, and one too small leaves it unwritten; the errno is authoritative either
+way.
+
+What the ioctls answer with, as against a family's own callback:
+
+``ENOTTY``
+    Any ioctl but ``CTLV_IOC_OP_EXEC``, on a file only CTLV answers. Where the
+    file is also another subsystem's, that subsystem answers any other ioctl.
+
+``EINVAL``
+    ``size`` was below 56, ``flags`` was not zero, ``op_id`` was zero,
+    ``generation`` or ``cursor`` was set on something that is not a query, or
+    the message broke a rule of the format or of the schema.
+
+``E2BIG``
+    ``size`` was larger than the structure this kernel knows, and the bytes
+    past it were not zero.
+
+``EFAULT``
+    The structure, the request or the reply was not accessible.
+
+``EOVERFLOW``
+    A blob descriptor's address or offset plus its length does not fit in 64
+    bits.
+
+``EOPNOTSUPP``
+    The device does not publish the operation, or publishes it but has it
+    disabled.
+
+``EACCES``
+    The fd lacks the operation's declared authority.
+
+``EMSGSIZE``
+    ``reply_len`` is shorter than the operation's ``action-reply-max-len`` or
+    ``query-reply-min-len``, and nothing was executed; or an ``output`` blob
+    is too short, which the error information reports with
+    ``required-length``; see `Blobs`_.
+
+``ESTALE``
+    A continuation whose ``generation`` no longer matches. Start the query
+    again.
+
+``ENODEV``
+    The device was unregistered. Descriptors stay open and every operation on
+    them fails this way.
+
+``EBADF``, ``EIO``
+    A blob descriptor named something that is not a file, or the file refused
+    the transfer.
+
+``ENOMEM``
+    The kernel could not allocate what the operation needed.
+
+``open()`` answers ``EACCES`` for ``O_WRONLY``, which no operation accepts,
+``ENODEV`` once the device has been unregistered, and ``ENOMEM`` when the
+kernel could not allocate the open file.
+
+Queries and fragments
+=====================
+
+A query's answer may be larger than the buffer the caller wants to commit, so
+the kernel fills the buffer with as much of it as fits where the tree can be
+cut. The first call passes ``generation`` and ``cursor`` zero. On return:
+
+- the kernel puts the query's generation in ``generation``;
+- ``cursor`` is nonzero when there is more to come, zero when the answer is
+  complete;
+- the reply root carries ``CTLV_HDR_F_FRAG_MORE`` when the answer continues,
+  and so does every record still logically open at the cut.
+
+To continue, the caller repeats the call with the same ``op_id`` and request,
+the returned ``cursor`` and the returned ``generation``, and reassembles by
+concatenating the children of each still-open record.
+
+One answer of three items, cut by a buffer that holds two::
+
+    call 1: cursor in = 0             call 2: cursor in = c
+            cursor out = c                    cursor out = 0
+
+    +----------------------------+    +----------------------------+
+    | root: FRAG_MORE            |    | root: (no FRAG_MORE)       |
+    |  +-----------------------+ |    |  +-----------------------+ |
+    |  | chunk: FRAG_MORE      | |    |  | chunk:                | |
+    |  |  +------------------+ | |    |  |  +------------------+ | |
+    |  |  | item: value = 1  | | |    |  |  | item: value = 3  | | |
+    |  |  +------------------+ | |    |  |  +------------------+ | |
+    |  |  | item: value = 2  | | |    |  +-----------------------+ |
+    |  |  +------------------+ | |    +----------------------------+
+    |  +-----------------------+ |
+    +----------------------------+
+
+    reassembled: root -> chunk -> item(1), item(2), item(3)
+
+``FRAG_MORE`` on the root says the answer continues; on ``chunk`` it says the
+next fragment resumes inside that same chunk. A complete record does not carry
+it, so a reader knows whether to append or to open a new record beside it.
+
+Every continuing fragment adds at least one complete logical TLV beyond its
+repeated path, and a cursor value cannot recur within one logical reply.
+A reader must reject either violation.
+
+A continuation whose generation no longer matches fails with ``-ESTALE``, and
+the error information carries the expected and the current generation.
+
+Blobs
+=====
+
+A ``binary`` field carries its bytes in the message itself, within the
+length its family declares. An operation that moves more data than a message
+should carry declares a blob field instead, and the caller passes a
+descriptor rather than the data: the root family's ``blob`` record, declared
+in ``Documentation/ctlv/specs/ctlv.yaml`` and numbered in
+``include/uapi/ctlv/ctlv_gen.h``. ``blob.type`` names the backing and
+``blob.length`` the length in bytes; the backing says which of
+``blob.address``, ``blob.fd`` and ``blob.offset`` name the memory. One
+backing is defined:
+
+``va``
+    Anonymous userspace memory of the calling process, named by an address in
+    ``blob.address``.
+
+The backings a field accepts, the direction data may flow, the maximum
+length and the required alignment are declared by the family and reported by
+``op-schema-get``. Memory is acquired for the operation and released before it
+returns; a descriptor the operation may not use is refused before the callback.
+While the operation is in flight, userspace must not modify an ``input`` blob
+or access an ``output`` or ``inout`` blob. Whether two descriptors overlap is
+also the caller's responsibility. Keep every named VA mapping valid until the
+operation returns.
+
+A descriptor is checked with the rest of the request, before any memory is
+acquired. A malformed field fails like any other. A backing the
+blob field does not accept, fields that do not fit the backing, a zero length
+or one above the maximum, or a misaligned address or offset fails with
+``EINVAL``, and a range that does not fit in 64 bits with ``EOVERFLOW``; both
+report ``bad-blob-descriptor`` at the descriptor. The memory is acquired when
+the operation first uses it, and a failure there, such as ``ENOMEM``, reports
+the same reason at the same place. An operation that
+finds an ``output`` blob too short for what it has to write there fails with
+``EMSGSIZE``, and reports the same with ``required-length``, how long the blob
+has to be, so the caller can retry with one that long.
+
+Breaking the in-flight rules harms only the caller. The kernel copies blob
+data, so what such an operation reads or writes is unspecified and the
+operation may fail, but no kernel memory is at risk.
+
+Introspection
+=============
+
+Three queries describe a device to a program that was not compiled against it.
+The CTLV core answers all three on every device.
+
+``family-get``
+    The device's family chain, root first, as a numeric ID and a name per
+    entry. The authoritative answer to what the device is.
+
+``op-get``
+    One entry per published operation: its ID, op type, required fd access,
+    whether its availability is fixed or dynamic, whether it is currently
+    disabled, and those of its lengths on this device that apply to its op type:
+    ``request-max-len``, ``action-reply-max-len``, ``query-reply-min-len``,
+    ``query-reply-suggested-len`` and ``error-info-max-len``. An unpublished
+    operation has no entry and is indistinguishable from one no family ever
+    declared.
+
+``op-schema-get``
+    The whole tree of one operation: every field of the request and the
+    reply, with its type, its schema kind, its bounds, its occurrence limit,
+    and its unit and scale where it has them.
+
+A schema that describes a schema does not end, so it is reported through
+re-entry: a node whose fields are those of a level already described carries
+``schema-node.reenters``, saying how many levels up that level is. A consumer
+that follows ``reenters`` handles any depth.
+
+The lengths in ``op-get`` include whatever a descendant family added to an
+inherited operation, so ask rather than compute: a family's generated maximum
+is right for its own devices and a lower bound on a descendant's. Likewise, an
+enum extension point's bounds are the values the device's family chain gives
+it, from 1 to 0 when it gives none, and their names are in the uapi header of
+the family that gives them.
+
+A program compiled against a family needs only ``family-get``, once, when
+it opens the device. The chain runs from ``ctlv`` to the device's family, and
+a HW driver usually has a family of its own, such as
+``ctlv-accelerator-foo``, so the last entry also says whose fields the replies
+carry. The answer comes from the open descriptor, so it works where udev never
+ran, such as inside a container; the uevent variables under Discovery are for
+udev rules. A field a descendant family adds to an inherited operation also
+carries that family's ID, in bits 63..48 of its type.
+
+Compatibility
+=============
+
+CTLV has no versions. A program built against one kernel keeps working on a
+later one, and a later program finds out what an earlier kernel acts on, by
+these rules:
+
+- ``struct ctlv_op_exec`` carries its size and grows only at its end; see
+  `Executing an operation`_.
+- A family grows by new operations and new optional fields. A field's type
+  includes its place in its record, so a new field goes last, and the others
+  keep their types.
+- A reply may carry TLVs an older program does not know, and it skips them. A
+  request TLV the kernel does not know fails the request unless the program
+  marks it ``CTLV_HDR_F_IGNORE_IF_UNKNOWN``, and ``op-schema-get`` tells a
+  newer program which of its fields the kernel acts on; see
+  `TLVs an older kernel may skip`_.
+- Anything incompatible is a new operation.
+
+Each family has a checked-in ABI snapshot under ``Documentation/ctlv/abi``, so
+a change to its uAPI shows as a change to that file. ``make -C tools/ctlv
+regen`` rewrites the snapshot from the family's specification, and refuses
+removing or renumbering anything, changing a field's kind or an operation's
+type, access or availability, narrowing a bound or an occurrence limit,
+making a field that the kernel writes optional, and, in any message,
+making a field required or adding a required one.
Documentation/userspace-api/index.rst +1 -0
index a68b1bea57a8..d1b53c4e16eb 100644
@@ -45,6 +45,7 @@ Devices and I/O
    :maxdepth: 1
 
    accelerators/ocxl
+   ctlv
    dma-buf-heaps
    dma-buf-alloc-exchange
    fwctl/index
MAINTAINERS +1 -0
index bf6d5bab0da9..e6748a4ad282 100644
@@ -7188,6 +7188,7 @@ M:	Jiri Pirko <[email protected]>
 L:	[email protected]
 S:	Maintained
 F:	Documentation/ctlv/
+F:	Documentation/userspace-api/ctlv.rst
 F:	include/linux/ctlv*.h
 F:	include/uapi/ctlv/
 F:	tools/ctlv/
Signature · 1 line
2.56.0
author
#6 lore raw

RFC PATCH v2 5/15 ctlv: Prepare message input handling

In reply to Jiri Pirko

From: Jiri Pirko <[email protected]>

Add TLV walking, request indexing and validated input accessors for generated family readers, and CTLV_ASSERT() for the core's invariants that no error path depends on, checked only with CONFIG_CTLV_DEBUG.

Keep CONFIG_CTLV unwired until dispatch completes the module.

Assisted-by Cursor: GPT-5.6 Sol
Assisted-by Cursor: Claude Opus 5.5

---
RFC->RFCv2:
- made ctlv_attr_next() end the walk on an attr overrunning its scope
- made CTLV a symbol its users select, with no prompt or help
- used void pointer arithmetic for attr addresses
- scoped the rebind loop variable to its loop
- cleared the binary attr length once
- dropped the comment ending message.c
- added CTLV_ASSERT(), checked only with CONFIG_CTLV_DEBUG
- said TLV, type, record and field instead of attr
- said record instead of nest, the root being one
- kept the length an output blob needs with the error
- separated the steps of the longer functions
- numbered every enum member
- took the UAPI headers from include/uapi/ctlv/
- moved to lib/ctlv/

---
 MAINTAINERS                 |   1 +
 include/linux/ctlv_family.h | 135 +++++++++++++
 lib/ctlv/Kconfig            |  13 ++
 lib/ctlv/Makefile           |   4 +
 lib/ctlv/internal.h         |  74 +++++++
 lib/ctlv/message.c          | 393 ++++++++++++++++++++++++++++++++++++
 lib/ctlv/message.h          |  91 +++++++++
 7 files changed, 711 insertions(+)
 create mode 100644 lib/ctlv/Kconfig
 create mode 100644 lib/ctlv/Makefile
 create mode 100644 lib/ctlv/internal.h
 create mode 100644 lib/ctlv/message.c
 create mode 100644 lib/ctlv/message.h
MAINTAINERS +1 -0
index e6748a4ad282..29bdb4de915d 100644
@@ -7191,6 +7191,7 @@ F:	Documentation/ctlv/
 F:	Documentation/userspace-api/ctlv.rst
 F:	include/linux/ctlv*.h
 F:	include/uapi/ctlv/
+F:	lib/ctlv/
 F:	tools/ctlv/
 
 CTU CAN FD DRIVER
include/linux/ctlv_family.h +135 -0

139 lines not on this page · raw message

lib/ctlv/Kconfig new file +13 -0
new file mode 100644
index 000000000000..465663bb7efa
@@ -0,0 +1,13 @@
+# SPDX-License-Identifier: GPL-2.0-only
+config CTLV
+	tristate
+
+config CTLV_DEBUG
+	bool "CTLV core self-checks"
+	depends on CTLV
+	help
+	  Checks the CTLV core's own bookkeeping where no error path depends
+	  on the result, and warns once when it is wrong. The checks that do
+	  guard an error path are made either way.
+
+	  If you are unsure, say N.
lib/ctlv/Makefile new file +4 -0
new file mode 100644
index 000000000000..4f0fe41bc9e1
@@ -0,0 +1,4 @@
+# SPDX-License-Identifier: GPL-2.0
+obj-$(CONFIG_CTLV) += ctlv.o
+
+ctlv-y += message.o
lib/ctlv/internal.h new file +74 -0

74 lines not on this page · raw message

lib/ctlv/message.c new file +393 -0

393 lines not on this page · raw message

lib/ctlv/message.h new file +91 -0

91 lines not on this page · raw message

Signature · 1 line
2.56.0
author
#7 lore raw

RFC PATCH v2 6/15 ctlv: Prepare blob descriptor validation

In reply to Jiri Pirko

From: Jiri Pirko <[email protected]>

Add parsing and VA checks for blob descriptors shared by schema validation and runtime acquisition.

Keep CONFIG_CTLV unwired until dispatch completes the module.

Assisted-by Cursor: GPT-5.6 Sol
Assisted-by Cursor: Claude Opus 5.5

---
RFC->RFCv2:
- returned EOVERFLOW for a blob range that wraps
- said TLV, type, record and field instead of attr
- said record instead of nest, the root being one
- numbered every enum member
- took the UAPI headers from include/uapi/ctlv/
- moved to lib/ctlv/

---
 lib/ctlv/Makefile    |   2 +-
 lib/ctlv/blob_desc.c | 101 +++++++++++++++++++++++++++++++++++++++++++
 lib/ctlv/blob_desc.h |  29 +++++++++++++
 3 files changed, 131 insertions(+), 1 deletion(-)
 create mode 100644 lib/ctlv/blob_desc.c
 create mode 100644 lib/ctlv/blob_desc.h
lib/ctlv/Makefile +1 -1
index 4f0fe41bc9e1..5edc0b4b973f 100644
@@ -1,4 +1,4 @@
 # SPDX-License-Identifier: GPL-2.0
 obj-$(CONFIG_CTLV) += ctlv.o
 
-ctlv-y += message.o
+ctlv-y += blob_desc.o message.o
lib/ctlv/blob_desc.c new file +101 -0

101 lines not on this page · raw message

lib/ctlv/blob_desc.h new file +29 -0
new file mode 100644
index 000000000000..e88693cbee4b
@@ -0,0 +1,29 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+#ifndef _CTLV_BLOB_DESC_H
+#define _CTLV_BLOB_DESC_H
+
+#include <linux/ctlv_family.h>
+#include <linux/types.h>
+
+#include <uapi/ctlv/ctlv.h>
+
+/* The members of a descriptor, in the order the root family declares them. */
+enum {
+	CTLV_BLOB_MEMBER_TYPE = 0,
+	CTLV_BLOB_MEMBER_ADDRESS = 1,
+	CTLV_BLOB_MEMBER_FD = 2,
+	CTLV_BLOB_MEMBER_OFFSET = 3,
+	CTLV_BLOB_MEMBER_LENGTH = 4,
+	CTLV_BLOB_MEMBERS = 5,
+};
+
+struct ctlv_blob_desc {
+	u64 member[CTLV_BLOB_MEMBERS];
+	u32 present;
+};
+
+u32 ctlv_blob_desc_read(const struct ctlv_hdr *blob, struct ctlv_blob_desc *desc,
+			const struct ctlv_hdr **bad);
+int ctlv_blob_desc_check(const struct ctlv_blob_desc *desc, const struct ctlv_node_schema *node);
+
+#endif /* _CTLV_BLOB_DESC_H */
Signature · 1 line
2.56.0
author
#8 lore raw

RFC PATCH v2 7/15 ctlv: Prepare schema validation

In reply to Jiri Pirko

From: Jiri Pirko <[email protected]>

Add generated-schema walking, message validation and request indexing. Use the descriptor layer to check blob fields.

Keep CONFIG_CTLV unwired until dispatch completes the module.

Assisted-by Cursor: GPT-5.6 Sol
Assisted-by Cursor: Claude Opus 5.5

---
RFC->RFCv2:
- refused extension points in a re-entering query reply
- returned EOVERFLOW for a blob range that wraps
- simplified growing the request index
- declared the request index free in schema.h
- dropped the event record length
- renamed stubs to extension points
- made a check no error path depends on a CTLV_ASSERT()
- said TLV, type, record and field instead of attr
- said record instead of nest, the root being one
- said node or field instead of placement
- separated the steps of the longer functions
- took the UAPI headers from include/uapi/ctlv/
- took the values the device's family chain gives an enum extension point
- moved to lib/ctlv/
- said message instead of wire

---
 lib/ctlv/Makefile |    2 +-
 lib/ctlv/schema.c | 1092 +++++++++++++++++++++++++++++++++++++++++++++
 lib/ctlv/schema.h |   54 +++
 3 files changed, 1147 insertions(+), 1 deletion(-)
 create mode 100644 lib/ctlv/schema.c
 create mode 100644 lib/ctlv/schema.h
lib/ctlv/Makefile +1 -1
index 5edc0b4b973f..3fd656835b8a 100644
@@ -1,4 +1,4 @@
 # SPDX-License-Identifier: GPL-2.0
 obj-$(CONFIG_CTLV) += ctlv.o
 
-ctlv-y += blob_desc.o message.o
+ctlv-y += blob_desc.o message.o schema.o
lib/ctlv/schema.c new file +1092 -0

1,092 lines not on this page · raw message

lib/ctlv/schema.h new file +54 -0

54 lines not on this page · raw message

Signature · 1 line
2.56.0
#9 lore raw

Re: [PATCH RFC v2 07/15] ctlv: Prepare schema validation

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] ctlv: ctlv_schema_min_len() enforces record depth limit on leaf nodes --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] ctlv: ctlv_schema_min_len() enforces record depth limit on leaf nodes
--

commit f7e5c872905b61fc69a0da34a919232ff36227be
Author: Jiri Pirko <[email protected]>

ctlv: Prepare schema validation

This commit adds generated-schema walking, message validation, and request indexing for CTLV schemas.

Quoted 6 lines
lib/ctlv/schema.c new file +0 -0
new file mode 100644
index 0000000000000..8ff3c7c5b5fe0
@@ -0,0 +1,1092 @@

[ ... ]

Quoted 42 lines
lib/ctlv/schema.c new file +42 -0
+/* Buffer length that the largest indivisible leaf and its records need. */
+static u64 ctlv_schema_min_len(struct ctlv_schema_length_walk *walk,
+			       const struct ctlv_schema_tree *tree, u32 index, u32 above, u32 depth)
+{
+	const struct ctlv_node_schema *node = &tree->node_schemas[index];
+	bool has_children = false;
+	u64 deepest = 0;
+	u32 i;
+
+	if (depth > CTLV_MAX_DECLARED_RECORD_DEPTH) {
+		walk->bad = true;
+		return 0;
+	}
+
+	for (i = 0; i < node->children_count; i++) {
+		u32 child = node->first_child + i;
+
+		has_children = true;
+		deepest = max(deepest,
+			      ctlv_schema_min_len(walk, tree, child,
+						  above + sizeof(struct ctlv_hdr), depth + 1));
+	}
+
+	for (i = 0; i < tree->ext_schemas_count; i++) {
+		const struct ctlv_ext_schema *ext_schema = &tree->ext_schemas[i];
+		const struct ctlv_ext_fill_schema *fill_schema;
+		const struct ctlv_node_schema *root;
+		u32 member;
+
+		if (ext_schema->node != index)
+			continue;
+		fill_schema =
+			ctlv_schema_fill(walk->family, ext_schema->family_id, ext_schema->ext_id);
+		if (!fill_schema)
+			continue;
+		root = &fill_schema->members.node_schemas[0];
+		for (member = 0; member < root->children_count; member++) {
+			has_children = true;
+			deepest = max(deepest, ctlv_schema_min_len(walk, &fill_schema->members,
+								   root->first_child + member,
+								   above + sizeof(struct ctlv_hdr),
+								   depth + 1));

lib/ctlv/schema.c line 329

Quoted 10 lines
lib/ctlv/schema.c new file +10 -0
+		}
+	}
+
+	if (has_children)
+		return deepest;
+	/* An empty root is a message of its own header alone. */
+	if (!index)
+		return above + sizeof(struct ctlv_hdr);
+	return above + ALIGN(ctlv_schema_tlv_max_len(walk, tree, index, depth), CTLV_ALIGNTO);
+}

[Severity: Medium]
Does ctlv_schema_min_len() reject valid leaf fields inside a record at CTLV_MAX_DECLARED_RECORD_DEPTH?

Unlike ctlv_schema_children_max_len(), which is only entered for CTLV_SCHEMA_RECORD nodes, ctlv_schema_min_len() recurses into every child and extension fill member with depth + 1 and checks depth > CTLV_MAX_DECLARED_RECORD_DEPTH at entry for all nodes. When a non-reentering query reply has a record at depth CTLV_MAX_DECLARED_RECORD_DEPTH (7), its leaf children are visited at depth 8, setting walk->bad = true and causing ctlv_schema_op_sizes() to fail with -EINVAL.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
author
#10 lore raw

RFC PATCH v2 8/15 ctlv: Prepare message output handling

In reply to Jiri Pirko

From: Jiri Pirko <[email protected]>

Add schema-aware reply construction, generated output accessors, operation errors and query fragment completion.

Keep CONFIG_CTLV unwired until dispatch completes the module.

Assisted-by Cursor: GPT-5.6 Sol
Assisted-by Cursor: Claude Opus 5.5

---
RFC->RFCv2:
- added ctlv_record_cancel()
- moved the function kernel-doc to the definitions
- made the warning for a reply past its declared length a CTLV_ASSERT()
- said TLV, type, record and field instead of attr
- said record instead of nest, the root being one
- took the UAPI headers from include/uapi/ctlv/
- moved to lib/ctlv/

---
 include/linux/ctlv.h        |  24 ++
 include/linux/ctlv_family.h |  41 ++++
 lib/ctlv/Makefile           |   2 +-
 lib/ctlv/builder.c          | 455 ++++++++++++++++++++++++++++++++++++
 lib/ctlv/builder.h          |  14 ++
 5 files changed, 535 insertions(+), 1 deletion(-)
 create mode 100644 lib/ctlv/builder.c
 create mode 100644 lib/ctlv/builder.h
include/linux/ctlv.h +24 -0
index e151e32a0ffd..5b75550de678 100644
@@ -34,6 +34,8 @@ struct ctlv_schema_tree;
  * @depth: record levels above this position, the root being zero
  * @index_record_scope: schema scope used to read the members of @hdr, a record
  * @index_scope: core-private schema scope containing this TLV
+ * @progress: writing, whether the fragment had progressed before this record
+ *	opened
  *
  * Fixed-size, so family code can put a child cursor on the stack.
  * ctlv_record_start() opens at most CTLV_MAX_RECORD_DEPTH levels, which bounds
@@ -52,6 +54,28 @@ struct ctlv_cursor {
 	u32 depth;
 	u32 index_record_scope;
 	u32 index_scope;
+	bool progress;
 };
 
+void ctlv_record_end(struct ctlv_cursor *child);
+void ctlv_record_cancel(struct ctlv_cursor *child);
+
+int ctlv_op_error(struct ctlv_op_ctx *ctx, int error, const char *message);
+__printf(3, 4)
+int ctlv_op_errorf(struct ctlv_op_ctx *ctx, int error, const char *fmt, ...);
+
+/*
+ * The core retains no query state. A continuation repeats the request and
+ * passes back the family's generation and nonzero cursor. It fails with
+ * -ESTALE if the generation changed. Each fragment must complete a logical
+ * leaf and return a cursor different from its input.
+ *
+ * ctlv_op_query_more() marks still-open records, whose cursors must stay live.
+ */
+u64 ctlv_op_query_generation(const struct ctlv_op_ctx *ctx);
+u64 ctlv_op_query_cursor(const struct ctlv_op_ctx *ctx);
+int ctlv_op_query_more(struct ctlv_op_ctx *ctx, u64 generation,
+		       u64 next_cursor);
+int ctlv_op_query_done(struct ctlv_op_ctx *ctx, u64 generation);
+
 #endif /* _LINUX_CTLV_H */
include/linux/ctlv_family.h +41 -0

47 lines not on this page · raw message

lib/ctlv/Makefile +1 -1
index 3fd656835b8a..e1a22a199ef1 100644
@@ -1,4 +1,4 @@
 # SPDX-License-Identifier: GPL-2.0
 obj-$(CONFIG_CTLV) += ctlv.o
 
-ctlv-y += blob_desc.o message.o schema.o
+ctlv-y += blob_desc.o builder.o message.o schema.o
lib/ctlv/builder.c new file +455 -0

455 lines not on this page · raw message

lib/ctlv/builder.h new file +14 -0
new file mode 100644
index 000000000000..744595ebd88e
@@ -0,0 +1,14 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+#ifndef _CTLV_BUILDER_H
+#define _CTLV_BUILDER_H
+
+#include <linux/types.h>
+
+struct ctlv_msg;
+struct ctlv_op_ctx;
+struct ctlv_schema_tree;
+
+void ctlv_message_output_init(struct ctlv_msg *msg, struct ctlv_op_ctx *ctx, void *buf, size_t len,
+			      const struct ctlv_schema_tree *tree);
+
+#endif /* _CTLV_BUILDER_H */
Signature · 1 line
2.56.0
author
#11 lore raw

RFC PATCH v2 9/15 ctlv: Prepare VA blob handling

In reply to Jiri Pirko

From: Jiri Pirko <[email protected]>

Add task-bound VA blob resolution and CPU read/write access for CTLV families.

The blob object can be compile-checked individually. CONFIG_CTLV remains unwired until operation dispatch completes the module.

Assisted-by Cursor: GPT-5.6 Sol
Assisted-by Cursor: Claude Opus 5.5

---
RFC->RFCv2:
- released a context's blobs from any task
- returned EOVERFLOW for a blob range that wraps
- moved the function kernel-doc to the definitions
- said TLV, type, record and field instead of attr
- said record instead of nest, the root being one
- added ctlv_blob_too_short() for an output blob too short
- took the UAPI headers from include/uapi/ctlv/
- moved to lib/ctlv/

---
 include/linux/ctlv.h        |   9 +
 include/linux/ctlv_family.h |  23 ++
 lib/ctlv/Makefile           |   2 +-
 lib/ctlv/blob.c             | 421 ++++++++++++++++++++++++++++++++++++
 lib/ctlv/blob.h             |  15 ++
 lib/ctlv/internal.h         |   8 +
 6 files changed, 477 insertions(+), 1 deletion(-)
 create mode 100644 lib/ctlv/blob.c
 create mode 100644 lib/ctlv/blob.h
include/linux/ctlv.h +9 -0
index 5b75550de678..afb71cc643d3 100644
@@ -78,4 +78,13 @@ int ctlv_op_query_more(struct ctlv_op_ctx *ctx, u64 generation,
 		       u64 next_cursor);
 int ctlv_op_query_done(struct ctlv_op_ctx *ctx, u64 generation);
 
+struct ctlv_blob;
+
+int ctlv_blob_put(struct ctlv_blob *blob);
+u64 ctlv_blob_len(const struct ctlv_blob *blob);
+int ctlv_blob_read(struct ctlv_blob *blob, u64 offset, void *dst, size_t len);
+int ctlv_blob_write(struct ctlv_blob *blob, u64 offset, const void *src,
+		    size_t len);
+int ctlv_blob_too_short(struct ctlv_blob *blob, u64 len);
+
 #endif /* _LINUX_CTLV_H */
include/linux/ctlv_family.h +23 -0
index 4d7d4fb65fec..61ae5b7cec83 100644
@@ -451,6 +451,8 @@ bool ctlv_put_binary(struct ctlv_cursor *record, u64 type, u8 kind,
 bool ctlv_record_start(struct ctlv_cursor *record, struct ctlv_cursor *child,
 		       u64 type, u8 kind);
 
+struct ctlv_blob *ctlv_blob_resolve(struct ctlv_op_ctx *ctx,
+				    const struct ctlv_cursor *blob);
 #define __CTLV_DEFINE_PUT(_name, _ctype, _put_fn, _type, _kind)	\
 static inline bool _name##_put(struct ctlv_cursor *record,	\
 			       _ctype value)			\
@@ -560,6 +562,17 @@ static inline void _name##_get(struct ctlv_cursor *inner,	\
 	ctlv_input_field(inner, record, _name##_ref());		\
 }
 
+#define CTLV_IN_BLOB(_name)					\
+static inline struct ctlv_blob *				\
+_name##_resolve(struct ctlv_op_ctx *ctx,			\
+		const struct ctlv_cursor *record)		\
+{								\
+	struct ctlv_cursor cursor;				\
+								\
+	ctlv_input_field(&cursor, record, _name##_ref());	\
+	return ctlv_blob_resolve(ctx, &cursor);			\
+}
+
 #define CTLV_IN_EACH_U64(_name)					\
 static inline u64 _name##_get(const struct ctlv_cursor *cursor)	\
 {								\
@@ -604,4 +617,14 @@ _name##_get(const struct ctlv_cursor *cursor, u32 *len)		\
 	return ctlv_cursor_binary(cursor, len);			\
 }
 
+#define CTLV_IN_EACH_BLOB(_name)				\
+static inline struct ctlv_blob *				\
+_name##_resolve(struct ctlv_op_ctx *ctx,			\
+		const struct ctlv_cursor *cursor)		\
+{								\
+	if (!ctlv_input_cursor(cursor, _name##_ref()))		\
+		return ERR_PTR(-EINVAL);			\
+	return ctlv_blob_resolve(ctx, cursor);			\
+}
+
 #endif /* _LINUX_CTLV_FAMILY_H */
lib/ctlv/Makefile +1 -1
index e1a22a199ef1..4455062f83d7 100644
@@ -1,4 +1,4 @@
 # SPDX-License-Identifier: GPL-2.0
 obj-$(CONFIG_CTLV) += ctlv.o
 
-ctlv-y += blob_desc.o builder.o message.o schema.o
+ctlv-y += blob.o blob_desc.o builder.o message.o schema.o
lib/ctlv/blob.c new file +421 -0

421 lines not on this page · raw message

lib/ctlv/blob.h new file +15 -0
new file mode 100644
index 000000000000..bb7b933a1ced
@@ -0,0 +1,15 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+#ifndef _CTLV_BLOB_H
+#define _CTLV_BLOB_H
+
+#include <linux/types.h>
+
+struct ctlv_blob;
+struct ctlv_op_ctx;
+
+void ctlv_blob_context_init(struct ctlv_op_ctx *ctx);
+void ctlv_blob_context_track(struct ctlv_blob *blob,
+			     struct ctlv_op_ctx *ctx);
+int ctlv_blob_context_finish(struct ctlv_op_ctx *ctx);
+
+#endif /* _CTLV_BLOB_H */
lib/ctlv/internal.h +8 -0
index 90d07d2638d3..1dbab9709261 100644
@@ -9,6 +9,7 @@
 
 #include <linux/bug.h>
 #include <linux/ctlv_family.h>
+#include <linux/list.h>
 #include <linux/types.h>
 
 #include <uapi/ctlv/ctlv.h>
@@ -22,6 +23,8 @@
 #define CTLV_ASSERT(cond) BUILD_BUG_ON_INVALID(cond)
 #endif
 
+struct task_struct;
+
 #define CTLV_ERROR_MESSAGE_LEN 256
 
 /* An op that is always enabled has no per-device availability state. */
@@ -58,6 +61,8 @@ struct ctlv_query_fragment {
 
 struct ctlv_op_ctx {
 	const struct ctlv_family *family;
+	/* Compared against current and never followed: identity, not a hold. */
+	const struct task_struct *submitter;
 	const struct ctlv_op_entry *op;
 
 	struct ctlv_msg request;
@@ -68,6 +73,9 @@ struct ctlv_op_ctx {
 	struct ctlv_cursor *deepest;
 
 	struct ctlv_query_fragment frag;
+	struct list_head blobs;
+	bool blobs_live;
+	int blob_error;
 	struct ctlv_error error;
 };
 
Signature · 1 line
2.56.0
#12 lore raw

Re: [PATCH RFC v2 09/15] ctlv: Prepare VA blob handling

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] ctlv: pages allocated before RLIMIT_MEMLOCK check in ctlv_blob_va_acquire() - [Medium] ctlv…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] ctlv: pages allocated before RLIMIT_MEMLOCK check in ctlv_blob_va_acquire()
- [Medium] ctlv: inconsistent record_offset on bad blob in ctlv_blob_resolve()
--

commit 58ccd80be391ba28c6e0a0c8cd4d357c3b9b3b37
Author: Jiri Pirko <[email protected]>

ctlv: Prepare VA blob handling

This commit adds task-bound VA blob resolution and CPU read/write access helpers for CTLV families.

Quoted 5 lines
lib/ctlv/blob.c new file +0 -0
new file mode 100644
index 0000000000000..14cbbc4bcab1c

[ ... ]

Quoted 38 lines
lib/ctlv/blob.c new file +38 -0
+static int ctlv_blob_va_range(u64 address, u64 len, unsigned long *first_page,
+			      unsigned long *pages_count)
+{
+	unsigned long first, last, span, count;
+	size_t bytes;
+	u64 end;
+
+	if (!len)
+		return -EINVAL;
+	if (check_add_overflow(address, len, &end))
+		return -EOVERFLOW;
+	if (end > TASK_SIZE)
+		return -EFAULT;
+
+	/* Bounded by an unsigned long above, so nothing below loses a bit. */
+	first = (unsigned long)address & PAGE_MASK;
+	last = ((unsigned long)end - 1) & PAGE_MASK;
+	if (check_sub_overflow(last, first, &span) ||
+	    check_add_overflow(span >> PAGE_SHIFT, 1UL, &count) ||
+	    check_mul_overflow(count, sizeof(struct page *), &bytes))
+		return -EOVERFLOW;
+
+	*first_page = first;
+	*pages_count = count;
+	return 0;
+}
+
+static int ctlv_blob_va_acquire(struct ctlv_blob *blob, u64 address)
+{
+	unsigned long pinned = 0, first, pages_count;
+	unsigned int gup_flags = 0;
+	struct page **pages;
+	int ret;
+
+	/* Before charging or allocating, both of which this sizes. */
+	ret = ctlv_blob_va_range(address, blob->len, &first, &pages_count);
+	if (ret)
+		return ret;

lib/ctlv/blob.c line 135

Quoted 10 lines
lib/ctlv/blob.c new file +10 -0
+
+	pages = kvmalloc_array(pages_count, sizeof(*pages), GFP_KERNEL_ACCOUNT);
+	if (!pages)
+		return -ENOMEM;
+
+	if (ctlv_blob_writable(blob))
+		gup_flags |= FOLL_WRITE;
+	ret = ctlv_blob_pin_charge(current->mm, pages_count);
+	if (ret)
+		goto err_free_pages;

[Severity: Medium]
Should ctlv_blob_pin_charge() run before kvmalloc_array()?

An unprivileged caller with a small RLIMIT_MEMLOCK can pass a large blob length to force a multi-megabyte vmalloc allocation that is immediately freed when ctlv_blob_pin_charge() rejects the page count. In addition, check_mul_overflow() only bounds bytes to SIZE_MAX, so if a schema allows a blob whose page array exceeds INT_MAX bytes, kvmalloc_array() without __GFP_NOWARN will trigger the size warning in __kvmalloc_node_noprof().

[ ... ]

Quoted 14 lines
lib/ctlv/blob.c new file +14 -0
+/*
+ * Which of an op's blobs was the unusable one, in the shape validation would
+ * have used. The errno the family returns says what went wrong.
+ */
+static void ctlv_blob_context_fail(struct ctlv_op_ctx *ctx, u32 tlv_offset, u32 record_offset,
+				   u64 required_length)
+{
+	if (ctx->error.reason)
+		return;
+	ctx->error.reason = CTLV_VALIDATION_REASON_BAD_BLOB_DESCRIPTOR;
+	ctx->error.bad_tlv_offset = tlv_offset;
+	ctx->error.record_offset = record_offset;
+	ctx->error.required_length = required_length;
+}

[ ... ]

Quoted 18 lines
lib/ctlv/blob.c new file +18 -0
+struct ctlv_blob *ctlv_blob_resolve(struct ctlv_op_ctx *ctx, const struct ctlv_cursor *blob)
+{
+	const struct ctlv_hdr *bad = NULL;
+	const struct ctlv_node_schema *node;
+	u32 tlv_offset, record_offset;
+	struct ctlv_blob_desc desc;
+	struct ctlv_blob *acquired;
+
+	/* An absent blob, or a cursor from some other execution entirely. */
+	if (WARN_ON_ONCE(blob->msg != &ctx->request || !ctlv_cursor_ok(blob)))
+		return ERR_PTR(-EINVAL);
+	node = &blob->tree->node_schemas[blob->node];
+	if (WARN_ON_ONCE(node->kind != CTLV_SCHEMA_BLOB))
+		return ERR_PTR(-EINVAL);
+	if (WARN_ON_ONCE(!ctx->blobs_live || !ctx->submitter || ctx->submitter != current))
+		return ERR_PTR(-EINVAL);
+	/* Validated before the callback, so anything wrong with it is a bug. */
+	if (WARN_ON_ONCE(ctlv_blob_desc_read(blob->hdr, &desc, &bad) ||

lib/ctlv/blob.c line 415

Quoted 10 lines
lib/ctlv/blob.c new file +10 -0
+			 ctlv_blob_desc_check(&desc, node)))
+		return ERR_PTR(-EINVAL);
+
+	tlv_offset = ctlv_message_offset(blob->msg, blob->hdr);
+	record_offset = ctlv_message_offset(blob->msg, blob->parent);
+	acquired = ctlv_blob_acquire(&desc, node->blob.direction);
+	if (IS_ERR(acquired)) {
+		ctlv_blob_context_fail(ctx, tlv_offset, record_offset, 0);
+		return acquired;
+	}

[Severity: Medium]
Does record_offset here match what schema validation reports for CTLV_VALIDATION_REASON_BAD_BLOB_DESCRIPTOR?

ctlv_blob_resolve() sets record_offset to blob->parent, the record containing the blob descriptor. However, when ctlv_blob_desc_check() fails during validation, ctlv_schema_check_blob() passes the blob TLV itself as the record argument to ctlv_schema_bad():

lib/ctlv/schema.c:ctlv_schema_check_blob() {
    ...
	err = ctlv_blob_desc_check(&desc, node);
	if (err)
		ctlv_schema_bad(v, CTLV_VALIDATION_REASON_BAD_BLOB_DESCRIPTOR, blob, NULL);
	return err;
}

Because hdr is NULL there, ctlv_schema_bad() sets both bad_tlv_offset and record_offset to the offset of blob, so userspace sees a different record_offset depending on whether the blob failed validation or resolution.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
author
#13 lore raw

RFC PATCH v2 10/15 ctlv: Prepare runtime introspection

In reply to Jiri Pirko

From: Jiri Pirko <[email protected]>

Add handlers that expose registered families, effective operations and message schemas through the CTLV root family. Start struct ctlv with the device, family, operations and op state they read.

The introspection object can be compile-checked here. CONFIG_CTLV remains unwired until operation dispatch completes the module.

Assisted-by Cursor: GPT-5.6 Sol
Assisted-by Cursor: Claude Opus 5.5

---
RFC->RFCv2:
- handed the introspection ops the CTLV instance
- reported each op's error information length
- emitted introspection fields without staging them
- kept each guard() on one line
- gave each dump cursor field its own mask and said what it holds
- took struct ctlv from the event patch, without the event state
- dropped the event record length from op-get
- renamed stubs to extension points
- made a check no error path depends on a CTLV_ASSERT()
- said TLV, type, record and field instead of attr
- said record instead of nest, the root being one
- said node instead of placement
- numbered every enum member
- reported the values the device's family chain gives an enum extension point
- moved to lib/ctlv/

---
 include/linux/ctlv.h     |  26 ++
 lib/ctlv/Makefile        |   3 +-
 lib/ctlv/internal.h      |   3 +
 lib/ctlv/introspection.c | 505 +++++++++++++++++++++++++++++++++++++++
 4 files changed, 536 insertions(+), 1 deletion(-)
 create mode 100644 lib/ctlv/introspection.c
include/linux/ctlv.h +26 -0
index afb71cc643d3..3847f8411edf 100644
@@ -7,6 +7,8 @@
 #ifndef _LINUX_CTLV_H
 #define _LINUX_CTLV_H
 
+#include <linux/device.h>
+#include <linux/spinlock_types.h>
 #include <linux/types.h>
 
 #include <uapi/ctlv/ctlv.h>
@@ -15,6 +17,7 @@ struct ctlv_family;
 struct ctlv;
 struct ctlv_msg;
 struct ctlv_op_ctx;
+struct ctlv_op_entry;
 struct ctlv_schema_tree;
 
 /**
@@ -57,6 +60,29 @@ struct ctlv_cursor {
 	bool progress;
 };
 
+/**
+ * struct ctlv - The CTLV state of one device, embedded by its subsystem.
+ * @dev: device whose release frees the structure embedding this instance;
+ *	every open file pins it
+ *
+ * A family callback is handed the instance and reaches its own state with
+ * container_of().
+ */
+struct ctlv {
+	struct device *dev;
+	/* private: */
+	const struct ctlv_family *family;
+
+	struct ctlv_op_entry *ops;
+	u32 ops_count;
+
+	/* Op publication and state writers, never the dispatch path. */
+	spinlock_t transition_lock;
+	u64 state_generation;
+	u32 dynamic_ops_count;
+	unsigned long *disabled;
+};
+
 void ctlv_record_end(struct ctlv_cursor *child);
 void ctlv_record_cancel(struct ctlv_cursor *child);
 
lib/ctlv/Makefile +2 -1
index 4455062f83d7..76010d52dd8a 100644
@@ -1,4 +1,5 @@
 # SPDX-License-Identifier: GPL-2.0
 obj-$(CONFIG_CTLV) += ctlv.o
 
-ctlv-y += blob.o blob_desc.o builder.o message.o schema.o
+ctlv-y += blob.o blob_desc.o builder.o introspection.o message.o \
+	  schema.o
lib/ctlv/internal.h +3 -0
index 1dbab9709261..2e1e36799a17 100644
@@ -60,6 +60,7 @@ struct ctlv_query_fragment {
 };
 
 struct ctlv_op_ctx {
+	struct ctlv *ctlv;
 	const struct ctlv_family *family;
 	/* Compared against current and never followed: identity, not a hold. */
 	const struct task_struct *submitter;
@@ -79,4 +80,6 @@ struct ctlv_op_ctx {
 	struct ctlv_error error;
 };
 
+struct ctlv_op_entry *ctlv_op_find(struct ctlv *ctlv, u64 op_id);
+
 #endif /* _CTLV_INTERNAL_H */
lib/ctlv/introspection.c new file +505 -0

505 lines not on this page · raw message

Signature · 1 line
2.56.0
#14 lore raw

Re: [PATCH RFC v2 10/15] ctlv: Prepare runtime introspection

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] ctlv: premature depth limit in ctlv_introspection_children() triggers WARN --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] ctlv: premature depth limit in ctlv_introspection_children() triggers WARN
--

commit 04c73a263bc43bc51c0a09b62604d548973da60c
Author: Jiri Pirko <[email protected]>

ctlv: Prepare runtime introspection

This commit adds runtime introspection handlers for registered families, effective operations, and message schemas through the CTLV root family, and introduces struct ctlv.

Quoted 5 lines
lib/ctlv/introspection.c new file +0 -0
new file mode 100644
index 0000000000000..d030debe69e3c

[ ... ]

Quoted 13 lines
lib/ctlv/introspection.c new file +13 -0
+/* The members of a fill inherit the optionality of its extension point. */
+static bool ctlv_introspection_children(struct ctlv_introspection_walk *walk, u32 depth,
+					const struct ctlv_schema_tree *tree, u32 index,
+					bool force_optional)
+{
+	const struct ctlv_node_schema *node = &tree->node_schemas[index];
+	u32 i;
+
+	if (WARN_ON_ONCE(depth + 1 >= CTLV_MAX_RECORD_DEPTH)) {
+		/* Deeper than a specification may declare, so unreachable. */
+		walk->error = -EINVAL;
+		return false;
+	}

[ ... ]

Quoted 24 lines
lib/ctlv/introspection.c new file +24 -0
+/* One node, into the record that stands for it. */
+static bool ctlv_introspection_node(struct ctlv_introspection_walk *walk, u32 depth,
+				    const struct ctlv_schema_tree *tree, u32 index)
+{
+	const struct ctlv_node_schema *node = &tree->node_schemas[index];
+	u32 reenters = 0;
+
+	if (node->reenters) {
+		reenters = ctlv_introspection_reenters(walk, depth, tree, node);
+		if (!reenters)
+			return false;
+	}
+	if (!ctlv_introspection_node_fields(walk, depth, node, reenters))
+		return false;
+	/*
+	 * A node that re-enters a level says so instead of listing that level's
+	 * members again, which is what makes unbounded depth describable.
+	 */
+	if (!node->reenters && !ctlv_introspection_children(walk, depth, tree, index, false))
+		return false;
+	if (walk->frames[depth].open)
+		ctlv_record_end(&walk->frames[depth].record);
+	return true;
+}

[ ... ]

Quoted 3 lines
lib/ctlv/introspection.c new file +3 -0
+int ctlv_op_schema_get_query(struct ctlv *ctlv, struct ctlv_op_ctx *ctx,
+			     const struct ctlv_cursor *request, struct ctlv_cursor *reply)
+{

[ ... ]

lib/ctlv/introspection.c line 489

Quoted 6 lines
lib/ctlv/introspection.c new file +6 -0
+	/*
+	 * One frame per level the reply may reach, too many for the stack: a
+	 * description is one level deeper than the message it describes.
+	 */
+	struct ctlv_introspection_frame *frames __free(kfree) =
+		kcalloc(CTLV_MAX_RECORD_DEPTH, sizeof(*frames), GFP_KERNEL);

[Severity: Medium]
Can ctlv_op_schema_get_query() trigger WARN_ON_ONCE() in ctlv_introspection_children() and fail with -EINVAL on valid schemas near CTLV_MAX_DECLARED_RECORD_DEPTH?

ctlv_introspection_node() calls ctlv_introspection_children() on every non-reentering node, including scalar leaves with no children or extension points, and ctlv_introspection_children() checks depth + 1 >= CTLV_MAX_RECORD_DEPTH (8) before checking whether the node has any children. A leaf field inside 6 nested records sits at walk depth 7, so describing it hits the WARN_ON_ONCE() and returns -EINVAL.

In addition, CTLV_MAX_DECLARED_RECORD_DEPTH (7) counts only record levels, whereas op-schema-get wraps both the message root (walk->frames[0]) and the leaf fields of the deepest record in CTLV_SCHEMA_RECORD nodes. A message at the maximum declared record depth of 7 needs walk depth 8 (9 record levels in the reply), which exceeds both the kcalloc(CTLV_MAX_RECORD_DEPTH, ...) allocation and the CTLV_MAX_RECORD_DEPTH limit in ctlv_record_start().

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=10
author
#15 lore raw

RFC PATCH v2 11/15 ctlv: Add operation dispatch

In reply to Jiri Pirko

From: Jiri Pirko <[email protected]>

Let a subsystem embed a CTLV instance in a device of its own, resolve family chains and dispatch operations through validated messages. Wire CONFIG_CTLV and the generated root family into lib/ after all module objects are present.

Assisted-by Cursor: GPT-5.6 Sol
Assisted-by Cursor: Claude Opus 5.5

---
RFC->RFCv2:
- let the subsystem allocate the device and embed CTLV, as fwctl does
- let a subsystem route the CTLV ioctl from its own file operations
- moved to lib/ctlv/, and the device nodes to the next patch
- dropped the family lifecycle hooks and the per-family privs
- used only gotos in ctlv_op_exec()
- read struct ctlv_op_exec with copy_struct_from_user()
- took a reply buffer of any length
- made plain what the breaks in ctlv_file_open() leave
- kept each guard() on one line
- moved the function kernel-doc to the definitions
- dropped read(), poll() and the op state and removal events
- renamed ctlv_stub_fill() to ctlv_ext_fill()
- said TLV, type, record and field instead of attr
- said record instead of nest, the root being one
- reported the length an output blob needs as required-length
- separated the steps of the longer functions
- took the UAPI headers from include/uapi/ctlv/
- said message instead of wire
- registered the ioctl number, which this patch handles first

---
 .../userspace-api/ioctl/ioctl-number.rst      |    2 +
 include/linux/ctlv.h                          |   33 +
 include/linux/ctlv_family.h                   |   22 +
 lib/Kconfig                                   |    2 +
 lib/Makefile                                  |    2 +
 lib/ctlv/Makefile                             |    4 +-
 lib/ctlv/core.c                               | 1152 +++++++++++++++++
 7 files changed, 1215 insertions(+), 2 deletions(-)
 create mode 100644 lib/ctlv/core.c
Documentation/userspace-api/ioctl/ioctl-number.rst +2 -0
index dbe462040999..f257b1a22ec2 100644
@@ -387,6 +387,8 @@ Code  Seq#    Include File                                             Comments
                                                                        <mailto:[email protected]>
 0xBA  00-0F  uapi/linux/liveupdate.h                                   Pasha Tatashin
                                                                        <mailto:[email protected]>
+0xBB  00-0F  uapi/ctlv/ctlv.h                                          CTLV
+                                                                       <mailto:[email protected]>
 0xC0  00-0F  linux/usb/iowarrior.h
 0xCA  00-0F  uapi/misc/cxl.h                                           Dead since 6.15
 0xCA  10-2F  uapi/misc/ocxl.h
include/linux/ctlv.h +33 -0
index 3847f8411edf..f075d0a99b80 100644
@@ -8,17 +8,20 @@
 #define _LINUX_CTLV_H
 
 #include <linux/device.h>
+#include <linux/rwsem.h>
 #include <linux/spinlock_types.h>
 #include <linux/types.h>
 
 #include <uapi/ctlv/ctlv.h>
 
 struct ctlv_family;
+struct ctlv_file;
 struct ctlv;
 struct ctlv_msg;
 struct ctlv_op_ctx;
 struct ctlv_op_entry;
 struct ctlv_schema_tree;
+struct file;
 
 /**
  * struct ctlv_cursor - One TLV position in one message.
@@ -60,6 +63,16 @@ struct ctlv_cursor {
 	bool progress;
 };
 
+/**
+ * struct ctlv_hooks - What a device runs around the ops of its instance.
+ * @pre: entered before every op the core does not answer, and may refuse it
+ * @post: entered after every op whose @pre succeeded
+ */
+struct ctlv_hooks {
+	int (*pre)(struct ctlv *ctlv, struct ctlv_op_ctx *ctx);
+	void (*post)(struct ctlv *ctlv, struct ctlv_op_ctx *ctx);
+};
+
 /**
  * struct ctlv - The CTLV state of one device, embedded by its subsystem.
  * @dev: device whose release frees the structure embedding this instance;
@@ -71,6 +84,9 @@ struct ctlv_cursor {
 struct ctlv {
 	struct device *dev;
 	/* private: */
+	const struct ctlv_hooks *hooks;
+	struct rw_semaphore registration_lock;
+	bool registered;
 	const struct ctlv_family *family;
 
 	struct ctlv_op_entry *ops;
@@ -78,14 +94,31 @@ struct ctlv {
 
 	/* Op publication and state writers, never the dispatch path. */
 	spinlock_t transition_lock;
+	bool published;
+	bool destroying;
 	u64 state_generation;
 	u32 dynamic_ops_count;
 	unsigned long *disabled;
 };
 
+int ctlv_init(struct ctlv *ctlv, struct device *dev,
+	      const struct ctlv_family *family, const struct ctlv_hooks *hooks);
+void ctlv_publish(struct ctlv *ctlv);
+void ctlv_unpublish(struct ctlv *ctlv);
+void ctlv_fini(struct ctlv *ctlv);
+bool ctlv_family_inherits(const struct ctlv_family *family,
+			  const struct ctlv_family *ancestor);
+
+struct ctlv_file *ctlv_file_open(struct ctlv *ctlv, struct file *filp);
+long ctlv_file_ioctl(struct ctlv_file *cfile, unsigned int cmd,
+		     unsigned long arg);
+void ctlv_file_close(struct ctlv_file *cfile);
+
 void ctlv_record_end(struct ctlv_cursor *child);
 void ctlv_record_cancel(struct ctlv_cursor *child);
 
+int ctlv_ext_fill(struct ctlv_op_ctx *ctx, const struct ctlv_cursor *request,
+		  struct ctlv_cursor *record);
 int ctlv_op_error(struct ctlv_op_ctx *ctx, int error, const char *message);
 __printf(3, 4)
 int ctlv_op_errorf(struct ctlv_op_ctx *ctx, int error, const char *fmt, ...);
include/linux/ctlv_family.h +22 -0
index 61ae5b7cec83..d8abdd4964c9 100644
@@ -428,6 +428,9 @@ extern const struct ctlv_family ctlv_family;
 
 u32 ctlv_enum_ext_max(const struct ctlv_family *family, u16 family_id, u32 ext_id);
 
+void ctlv_op_provide(struct ctlv *ctlv, u64 op_id);
+void ctlv_op_state_set(struct ctlv *ctlv, u64 op_id, bool disabled);
+
 struct ctlv_cursor *
 ctlv_input_field(struct ctlv_cursor *cursor, const struct ctlv_cursor *record,
 		 struct ctlv_input_ref ref);
@@ -453,6 +456,25 @@ bool ctlv_record_start(struct ctlv_cursor *record, struct ctlv_cursor *child,
 
 struct ctlv_blob *ctlv_blob_resolve(struct ctlv_op_ctx *ctx,
 				    const struct ctlv_cursor *blob);
+
+#define CTLV_OP_PROVIDE(_name, _op_id)				\
+static inline void _name##_provide(struct ctlv *ctlv)	\
+{								\
+	ctlv_op_provide(ctlv, (_op_id));		\
+}
+
+#define CTLV_OP_ENABLE(_name, _op_id)				\
+static inline void _name##_enable(struct ctlv *ctlv)	\
+{								\
+	ctlv_op_state_set(ctlv, (_op_id), false);	\
+}
+
+#define CTLV_OP_DISABLE(_name, _op_id)				\
+static inline void _name##_disable(struct ctlv *ctlv)	\
+{								\
+	ctlv_op_state_set(ctlv, (_op_id), true);	\
+}
+
 #define __CTLV_DEFINE_PUT(_name, _ctype, _put_fn, _type, _kind)	\
 static inline bool _name##_put(struct ctlv_cursor *record,	\
 			       _ctype value)			\
lib/Kconfig +2 -0
index 1e42f5167c68..7d81e1d502d1 100644
@@ -496,6 +496,8 @@ source "lib/vdso/Kconfig"
 
 source "lib/fonts/Kconfig"
 
+source "lib/ctlv/Kconfig"
+
 config SG_SPLIT
 	def_bool n
 	help
lib/Makefile +2 -0
index a2afe954805c..db7e4fcc2c6f 100644
@@ -342,6 +342,8 @@ obj-$(CONFIG_OBJAGG) += objagg.o
 # pldmfw library
 obj-$(CONFIG_PLDMFW) += pldmfw/
 
+obj-$(CONFIG_CTLV) += ctlv/
+
 obj-$(CONFIG_GENERIC_LIB_DEVMEM_IS_ALLOWED) += devmem_is_allowed.o
 
 obj-$(CONFIG_FIRMWARE_TABLE) += fw_table.o
lib/ctlv/Makefile +2 -2
index 76010d52dd8a..73acdbdf387d 100644
@@ -1,5 +1,5 @@
 # SPDX-License-Identifier: GPL-2.0
 obj-$(CONFIG_CTLV) += ctlv.o
 
-ctlv-y += blob.o blob_desc.o builder.o introspection.o message.o \
-	  schema.o
+ctlv-y += blob.o blob_desc.o builder.o core.o introspection.o \
+	  message.o schema.o ctlv_gen.o
lib/ctlv/core.c new file +1152 -0

1,152 lines not on this page · raw message

Signature · 1 line
2.56.0
#16 lore raw

Re: [PATCH RFC v2 11/15] ctlv: Add operation dispatch

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] ctlv: broken request rebinding and WARN_ON_ONCE in ctlv_ext_fill() - [Low] ctlv: unclaimed…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] ctlv: broken request rebinding and WARN_ON_ONCE in ctlv_ext_fill()
- [Low] ctlv: unclaimed ancestor families and bad log in ctlv_init() --

commit d099e8b67fe7bf2eb3f3e45b3042be1ff1f88e98
Author: Jiri Pirko <[email protected]>

ctlv: Add operation dispatch

This commit adds CTLV family resolution, instance registration, file operations, and ioctl operation dispatch.

Quoted 5 lines
lib/ctlv/core.c new file +0 -0
new file mode 100644
index 0000000000000..605f191de77ba

[ ... ]

Quoted 33 lines
lib/ctlv/core.c new file +33 -0
+/**
+ * ctlv_ext_fill - Delegate an extension-point output record.
+ * @ctx: operation context
+ * @request: validated request root
+ * @record: output record selected by the generated helper
+ *
+ * Return: filling callback result, or 0 for an unfilled point.
+ */
+int ctlv_ext_fill(struct ctlv_op_ctx *ctx, const struct ctlv_cursor *request,
+		  struct ctlv_cursor *record)
+{
+	const struct ctlv_schema_tree *tree;
+	u32 index;
+
+	if (WARN_ON_ONCE(!record->tree))
+		return -EINVAL;
+	tree = record->tree;
+
+	for (index = 0; index < tree->ext_schemas_count; index++) {
+		const struct ctlv_ext_schema *ext_schema = &tree->ext_schemas[index];
+		const struct ctlv_cursor *filled_request = request;
+		const struct ctlv_ext_fill_schema *fill_schema;
+		const struct ctlv_ext_ops *ext_ops;
+		struct ctlv_cursor filled;
+		int ret;
+
+		if (ext_schema->node != record->node)
+			continue;
+		ext_ops = ctlv_ext_ops_find(ctx->ctlv, ext_schema);
+		if (!ext_ops || !ext_ops->fill)
+			continue;
+
+		if (request) {

lib/ctlv/core.c line 848

Quoted 10 lines
lib/ctlv/core.c new file +10 -0
+			fill_schema = ctlv_schema_fill(ctx->family, ext_schema->family_id,
+						       ext_schema->ext_id);
+			if (WARN_ON_ONCE(!fill_schema))
+				return -EINVAL;
+			filled = *request;
+			if (ctlv_message_input_rebind(&filled, &fill_schema->members, 0))
+				filled_request = &filled;
+			else
+				filled_request = NULL;
+		}

[Severity: Medium]
Can ctlv_ext_fill() trigger WARN_ON_ONCE(!record->hdr) in ctlv_message_input_rebind() when userspace omits an optional request extension record?

When a parent operation looks up the request extension-point record with its generated helper and the optional record was omitted in the request message, ctlv_input_field() sets request->hdr = NULL. Passing that cursor to ctlv_ext_fill() enters the if (request) branch and passes filled.hdr == NULL to ctlv_message_input_rebind():

lib/ctlv/message.c:ctlv_message_input_rebind() {
	if (WARN_ON_ONCE(!record->hdr || !record->msg || !record->msg->index))
		return false;
    ...
}

Also, the kernel-doc above says @request is the validated request root, whereas extension fill scopes are attached to the child extension record rather than index->records[0], so passing the request root cursor always fails to rebind and sets filled_request = NULL. Should ctlv_ext_fill() check ctlv_cursor_ok(request) (setting filled_request = NULL when absent) and document @request as the matching request extension record?

[ ... ]

Quoted 26 lines
lib/ctlv/core.c new file +26 -0
+int ctlv_init(struct ctlv *ctlv, struct device *dev,
+	      const struct ctlv_family *family, const struct ctlv_hooks *hooks)
+{
+	int ret;
+
+	/* Nothing in common means no pair, not half of one. */
+	if (!dev || !family || (hooks && (!hooks->pre || !hooks->post)))
+		return -EINVAL;
+
+	ctlv->dev = dev;
+	ctlv->hooks = hooks;
+	init_rwsem(&ctlv->registration_lock);
+	spin_lock_init(&ctlv->transition_lock);
+
+	/* Before anything reads the schema through this instance. */
+	ret = ctlv_op_resolution_init(ctlv, family);
+	if (ret)
+		return ret;
+
+	/* Before a subsystem announces a device that could not be. */
+	ret = ctlv_uevent_check(family);
+	if (ret)
+		return ret;
+
+	if (ctlv->dynamic_ops_count) {
+		ctlv->disabled = bitmap_zalloc(ctlv->dynamic_ops_count, GFP_KERNEL);

lib/ctlv/core.c line 1084

Quoted 10 lines
lib/ctlv/core.c new file +10 -0
+		if (!ctlv->disabled)
+			return -ENOMEM;
+	}
+
+	ret = ctlv_family_claim_add(family->schema);
+	if (ret)
+		return ret;
+	ctlv->family = family;
+	return 0;
+}

[Severity: Low]
Does ctlv_init() leave intermediate ancestor families unclaimed in ctlv_family_claims?

ctlv_init() only calls ctlv_family_claim_add(family->schema) on the leaf family, so base families that are only inherited and never instantiated on their own are not recorded in ctlv_family_claims, allowing conflicting ancestor names or family_ids across chains.

In addition, when ctlv_family_claim_add() hits a name collision with a different family_id (same_name && !same_id), its pr_err() reports that schema->family_id belongs to claim->name instead of claim->family_id. Finally, ctlv_family_chain_check() and ctlv_family_descriptor_check() do not check that child->schema->name[len + 1] is non-NUL after '-' or that strlen(schema->name) fits the 63-byte limit of CTLV_T_FAMILY_GET_FAMILIES_NAME before CTLV_OP_FAMILY_GET hits a runtime WARN_ON_ONCE in ctlv_put_string().

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=11
author
#17 lore raw

RFC PATCH v2 12/15 ctlv: Add character device nodes

In reply to Jiri Pirko

From: Jiri Pirko <[email protected]>

Give a subsystem's device a node of the subsystem's own class, whose file operations are the CTLV ones. The subsystem registers the class with CTLV, which takes its device numbers, and embeds a struct ctlv_device beside the instance.

Assisted-by Cursor: GPT-5.6 Sol
Assisted-by Cursor: Claude Opus 5.5

---
RFC->RFCv2:
- split out of the device and operation dispatch patch
- made a library each subsystem's class builds its nodes with, and dropped the ctlv class

---
 include/linux/ctlv_device.h |  57 ++++++++++++
 lib/ctlv/Makefile           |   2 +-
 lib/ctlv/core.c             |  17 ++++
 lib/ctlv/device.c           | 179 ++++++++++++++++++++++++++++++++++++
 lib/ctlv/internal.h         |   2 +
 5 files changed, 256 insertions(+), 1 deletion(-)
 create mode 100644 include/linux/ctlv_device.h
 create mode 100644 lib/ctlv/device.c
include/linux/ctlv_device.h new file +57 -0
new file mode 100644
index 000000000000..9ff10ce7368f
@@ -0,0 +1,57 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES
+ *
+ * Character device nodes of CTLV instances, in a subsystem's own class.
+ */
+#ifndef _LINUX_CTLV_DEVICE_H
+#define _LINUX_CTLV_DEVICE_H
+
+#include <linux/cdev.h>
+#include <linux/device.h>
+#include <linux/idr.h>
+#include <linux/types.h>
+
+struct ctlv;
+struct module;
+
+/**
+ * struct ctlv_device_class - The class of a subsystem's nodes.
+ * @class: the class, whose dev_release frees a node's structure; CTLV sets
+ *	its dev_uevent
+ * @max_devices: how many nodes the class may have at once
+ */
+struct ctlv_device_class {
+	struct class class;
+	unsigned int max_devices;
+	/* private: */
+	struct module *owner;
+	dev_t devt;
+	struct ida ids;
+};
+
+/**
+ * struct ctlv_device - The node of one instance.
+ * @dev: the node's device, named for its class and a number of its own
+ *
+ * Embedded beside the instance in the subsystem's device structure.
+ */
+struct ctlv_device {
+	struct device dev;
+	/* private: */
+	struct cdev cdev;
+	struct ctlv *ctlv;
+	struct ctlv_device_class *cls;
+};
+
+int __ctlv_device_class_register(struct ctlv_device_class *cls, struct module *owner);
+#define ctlv_device_class_register(cls) __ctlv_device_class_register(cls, THIS_MODULE)
+void ctlv_device_class_unregister(struct ctlv_device_class *cls);
+
+int ctlv_device_init(struct ctlv_device *ctlvdev, struct ctlv_device_class *cls,
+		     struct device *parent, struct ctlv *ctlv);
+void ctlv_device_fini(struct ctlv_device *ctlvdev);
+int ctlv_device_add(struct ctlv_device *ctlvdev);
+void ctlv_device_del(struct ctlv_device *ctlvdev);
+
+#endif /* _LINUX_CTLV_DEVICE_H */
lib/ctlv/Makefile +1 -1
index 73acdbdf387d..e783ad450c12 100644
@@ -1,5 +1,5 @@
 # SPDX-License-Identifier: GPL-2.0
 obj-$(CONFIG_CTLV) += ctlv.o
 
-ctlv-y += blob.o blob_desc.o builder.o core.o introspection.o \
+ctlv-y += blob.o blob_desc.o builder.o core.o device.o introspection.o \
 	  message.o schema.o ctlv_gen.o
lib/ctlv/core.c +17 -0
index 605f191de77b..eb493104da62 100644
@@ -1034,6 +1034,23 @@ static int ctlv_uevent_check(const struct ctlv_family *family)
 	return ret;
 }
 
+/**
+ * ctlv_uevent - Add the family variables to a device uevent.
+ * @ctlv: instance
+ * @env: uevent environment
+ *
+ * Return: 0, or a negative error.
+ */
+int ctlv_uevent(const struct ctlv *ctlv, struct kobj_uevent_env *env)
+{
+	/* Read unlocked: a uevent may be asked for under the registration lock. */
+	const struct ctlv_family *family = READ_ONCE(ctlv->family);
+
+	if (!family)
+		return 0;
+	return ctlv_uevent_families(env, family);
+}
+
 /**
  * ctlv_init - Prepare an embedded instance for one family.
  * @ctlv: zeroed instance
lib/ctlv/device.c new file +179 -0

179 lines not on this page · raw message

lib/ctlv/internal.h +2 -0
index 2e1e36799a17..8fb5f0abdc47 100644
@@ -23,6 +23,7 @@
 #define CTLV_ASSERT(cond) BUILD_BUG_ON_INVALID(cond)
 #endif
 
+struct kobj_uevent_env;
 struct task_struct;
 
 #define CTLV_ERROR_MESSAGE_LEN 256
@@ -81,5 +82,6 @@ struct ctlv_op_ctx {
 };
 
 struct ctlv_op_entry *ctlv_op_find(struct ctlv *ctlv, u64 op_id);
+int ctlv_uevent(const struct ctlv *ctlv, struct kobj_uevent_env *env);
 
 #endif /* _CTLV_INTERNAL_H */
Signature · 1 line
2.56.0
author
#18 lore raw

RFC PATCH v2 13/15 Documentation: ctlv: Describe how to write a family

In reply to Jiri Pirko

From: Jiri Pirko <[email protected]>

Describe the YAML language, generated family descriptors, lifecycle, operations, blobs, inheritance and compatible extension rules.

Assisted-by Cursor: GPT-5.6 Sol
Assisted-by Cursor: Claude Opus 5.5

---
RFC->RFCv2:
- fixed the family descriptor name in the ctlv_create() example
- documented ctlv_record_cancel()
- stated how the generator keeps every message within the limit
- dropped the events
- reworked the guide after review, around a worked example family
- warned that a family's registry position is its ID
- renamed stubs to extension points
- added the kernel-doc of the family API
- described specs as op trees and records
- said to return ctlv_blob_too_short() for an output blob too short
- said what validation accepted instead of placements
- said record instead of nest, the root being one
- took the UAPI headers from include/uapi/ctlv/
- documented every item of the example family's spec
- generated and recorded a family's ABI with one regen, and listed the files it should change
- described enum extension points
- said how to name an op that reads
- described a subsystem's nodes in place of the ctlv class
- said message instead of wire

---
 Documentation/driver-api/ctlv.rst  | 716 +++++++++++++++++++++++++++++
 Documentation/driver-api/index.rst |   1 +
 MAINTAINERS                        |   1 +
 3 files changed, 718 insertions(+)
 create mode 100644 Documentation/driver-api/ctlv.rst
Documentation/driver-api/ctlv.rst new file +716 -0
new file mode 100644
index 000000000000..34d20c14a9bf
@@ -0,0 +1,716 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+=====================
+Writing a CTLV family
+=====================
+
+:Author: Jiri Pirko
+
+A CTLV family is a set of system calls for one sort of device: actions and
+queries a program executes. The family is written as a
+YAML specification, a generator turns that into headers, and the family
+implementation supplies the callbacks the generated header names. CTLV checks
+every request against the specification before a callback sees it. The
+userspace ABI is :doc:`/userspace-api/ctlv`; the in-tree specifications are
+under ``Documentation/ctlv/specs``.
+
+The example
+===========
+
+This guide writes a small invented family, ``ctlv-example``, with two system
+calls::
+
+    item_set_action(u64 index, string label?, blob data?) -> status;
+    item_get_query() -> { u64 index; string label?; }[];
+
+``index`` is 0..4095, ``label`` is at most 63 bytes excluding NUL, and
+``data`` is at most 1 MiB with 8-byte alignment. ``?`` marks an optional
+argument. An action runs once and returns a status. A query returns an answer
+that may be larger than the caller's buffer, which CTLV delivers in as many
+fragments as the buffer needs; a list, as here, is the usual case.
+
+Write the specification
+=======================
+
+The specification starts with the family. ``ctlv-example`` inherits ``ctlv``,
+the root family every device answers:
+
+.. code-block:: yaml
+
+    # SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)
+    %YAML 1.2
+    ---
+    # Numbered items, each with an optional label.
+    family: ctlv-example
+    inherits: ctlv
+
+The comment on the lines above an entry is its documentation, which the
+generated headers carry. The generator refuses a family, record, field, op,
+enum or flags without one, and an enum value or a flag without its own, so
+values go one to a line.
+
+Each system call is an op:
+
+.. code-block:: yaml
+
+    ops:
+      # Sets an item's label and data.
+      item-set:
+        type: action
+        request:
+          # Which item it is.
+          index: uint(..4095)
+          # What the item is called.
+          label?: string(..63)
+          # The item's contents, which the device reads.
+          data?: blob(in, ..1M, align 8, va)
+
+      # Lists the items.
+      item-get:
+        type: query
+        reply:
+          # Every item the device keeps.
+          items[]:
+            # Which item it is.
+            index: uint(..4095)
+            # What the item is called.
+            label?: string(..63)
+
+``request`` is what an op takes and ``reply`` what it returns. An op
+without a ``request`` takes no arguments, and an action without a ``reply``
+returns only its status. An action or a query may also set these keys:
+
+=========================== ========== ========================================
+Key                         Default    What it does
+=========================== ========== ========================================
+``fd-access``               read-write ``read`` lets an ``O_RDONLY`` fd run it
+``suggested-reply-length``  64K        the buffer a caller starts a query with
+``optional``                false      see `Optional operations`_
+``availability``            fixed      see `Dynamic availability`_
+``pre-post``                false      see `Hooks`_
+=========================== ========== ========================================
+
+An op that reads is named ``<object>-get``, the object in the singular, and
+each kind of object has one. A get over a collection, as ``item-get`` is, is a
+query even while it returns one object, as an op's type never changes; its
+request fields are optional filters, none meaning every object. A filter
+matching nothing gives an empty answer, and an ID naming nothing fails with
+``ENOENT``. An action get returns exactly one thing, such as the device.
+
+What an op takes or returns is a record: the fields one level of a message
+may hold, one per line. ``name?`` is an optional field, ``name[N]`` one that
+occurs up to N times, ``name[enum]`` one that occurs up to once per value of
+the enum, and ``name[]`` one a query's reply repeats any number of times. A
+field with fields indented below it is a record, the one declared there, as
+``items[]`` is. Each field has generated helpers named after its op and the
+records it is in: ``ctlv_example_item_set_index_get()`` reads ``index`` in an
+``item-set`` request, and ``ctlv_example_item_get_items_index_put()`` writes
+it in an item of the ``item-get`` reply.
+
+Fields that several messages repeat can be declared once as a named record,
+and then the specification reads:
+
+.. code-block:: yaml
+
+    records:
+      # One item, as item-set takes it and item-get lists it.
+      item:
+        # Which item it is.
+        index: uint(..4095)
+        # What the item is called.
+        label?: string(..63)
+
+    ops:
+      # Sets an item's label and data.
+      item-set:
+        type: action
+        request:
+          $include: item
+          # The item's contents, which the device reads.
+          data?: blob(in, ..1M, align 8, va)
+
+      # Lists the items.
+      item-get:
+        type: query
+        reply:
+          # Every item the device keeps.
+          items[]: record item
+
+``$include: item`` puts the record's fields in place, and ``record item`` makes
+it a whole message or a record's field. The field is then the same wherever it
+appears: ``item.index`` has one type, one bound and one generated helper in
+the ``item-set`` request and in the items ``item-get`` returns, and
+``ctlv_example_item_index_put()`` writes it in the latter. This guide keeps
+the fields spelled out.
+
+A field's type, the ID it has in a message, is made of the family's number,
+its record and its place in that record. A named record is numbered by its
+place in ``records``, an op's request and reply by the op's place in ``ops``,
+and a record declared in place by its place among the records declared beside
+it. Every one of those places is ABI, so records, fields and ops are only ever
+appended. Records declared in place go at most four deep and fifteen side by
+side below a named record or an op's message; a deeper or wider tree takes
+another named record.
+
+A field has one schema kind. Bounds follow it in parentheses, inclusive, with
+limits such as ``u32-max`` written by name and sizes such as ``4K``, which an
+integer takes only with the ``bytes`` unit, as in ``uint(1..4K, bytes)``:
+
+============ ============================== ==================================
+Kind         Holds                          Declared as, for example
+============ ============================== ==================================
+``uint``     an unsigned 64-bit integer     ``uint(..4095)``
+``sint``     a signed 64-bit integer        ``sint(-8..8)``
+``bool``     true or false                  ``bool``
+``string``   text, bounded without its NUL  ``string(..63)``
+``binary``   bytes                          ``binary(16..64)``
+enum         one value of an enum           the enum's name
+flags        a set of flags                 the flags' name
+record       fields                         ``record item``, or fields below
+``blob``     caller memory, see `Blobs`_    ``blob(in, ..1M, align 8, va)``
+============ ============================== ==================================
+
+Bounds, record membership and whether a field is required are ABI.
+
+The top-level keys may come in any order; the in-tree specifications put
+``enums`` and ``flags`` first, then ``records`` and ``ops``.
+
+An enum a uapi header already defines names the header in ``$header``, a path
+under ``include/uapi``, and the enum in ``$enum``. The enum's constants are its
+values, under their own names and numbers, whatever they start from and
+whatever gaps they leave, and need no comments. ``$end`` names a sentinel,
+leaving it and every constant after it out:
+
+.. code-block:: yaml
+
+    enums:
+      # The kernel's hash algorithms.
+      hash-algo:
+        $header: linux/hash_info.h
+        $enum: hash_algo
+        $end: HASH_ALGO__LAST
+
+The generated code includes the header rather than repeating the enum. CTLV
+takes any number from the lowest value up to one below ``$end``, or to the
+highest value without it, so a number in a gap reaches the callback, which
+refuses it. ``$end`` may move later as the header grows, never earlier. An
+enum written as ``extension`` has no values of its own; see
+`Inheritance and HW driver fields`_.
+
+No message outgrows the core's inline limit, ``CTLV_MAX_INLINE_MESSAGE_LEN``
+(64 KiB): the generator refuses an operation whose request or action reply
+could be longer, or a query whose longest field could not fit in one
+fragment. Larger data goes in a blob.
+
+Generate the family
+===================
+
+A new family is one change holding its specification, its registry entry and
+its output manifest entry::
+
+    Documentation/ctlv/specs/ctlv-example.yaml
+    Documentation/ctlv/families.yaml
+    Documentation/ctlv/generated-files.yaml
+
+The family's position in ``families.yaml`` is its family ID, part of every
+type and op ID it generates. Append only: never reorder, remove,
+rename or reuse an entry. Agree the position with the CTLV maintainers (CTLV
+SUBSYSTEM in MAINTAINERS) before adding a family, since families added in
+parallel trees would otherwise end up with the same ID. The output manifest
+says where the generated UAPI, kernel and userspace files go.
+
+Generate the files and record the new family's ABI::
+
+    make -C tools/ctlv regen
+
+``regen`` names each file it writes. A new family should add its generated
+files, its snapshot, ``Documentation/ctlv/abi/ctlv-example.yaml``, its entry
+in ``Documentation/ctlv/abi/families.registry.yaml`` and one line in
+``include/uapi/ctlv/ctlv_families_gen.h``, and change nothing generated for
+another family. Anything else means the specification or the generator
+changed more than intended. ``regen`` refuses a specification change that
+breaks the ABI as last committed unless ``ABI_BREAK=1`` says it is meant, so a
+snapshot's diff shows every ABI change for review. ``make -C tools/ctlv``
+checks the same without writing anything.
+
+Never edit a generated file; change the YAML or the generator and regenerate.
+
+Create and destroy a device
+===========================
+
+CTLV comes in two parts. The engine in ``lib/ctlv/`` is what a subsystem embeds
+in its devices and calls from their file operations. The nodes, declared in
+``<linux/ctlv_device.h>``, are character devices of the subsystem's own class,
+with the engine's file operations.
+
+A device's CTLV state is a ``struct ctlv``, embedded in the structure of
+whoever gives the device. A callback gets the instance and reaches that
+structure with ``container_of()``. The node is a ``struct ctlv_device``, which
+the structure embeds beside the instance:
+
+.. code-block:: c
+
+    struct example_device {
+            struct ctlv_device ctlvdev;
+            struct ctlv ctlv;
+            u64 items_count;
+            u64 generation;
+    };
+
+    static struct example_device *to_example(struct ctlv *ctlv)
+    {
+            return container_of(ctlv, struct example_device, ctlv);
+    }
+
+The subsystem's class is a ``struct ctlv_device_class``, registered once with
+``ctlv_device_class_register()``, which takes its device numbers. Its
+``dev_release`` frees the structure, so an open node holds the module that
+registered the class:
+
+.. code-block:: c
+
+    static void example_release(struct device *dev)
+    {
+            struct example_device *example =
+                    container_of(dev, struct example_device, ctlvdev.dev);
+
+            ctlv_fini(&example->ctlv);
+            ctlv_device_fini(&example->ctlvdev);
+            kfree(example);
+    }
+
+    static struct ctlv_device_class example_class = {
+            .class = {
+                    .name = "example",
+                    .dev_release = example_release,
+            },
+            .max_devices = 16,
+    };
+
+A device of the class is then made:
+
+.. code-block:: c
+
+    example = kzalloc(sizeof(*example), GFP_KERNEL);
+    if (!example)
+            return -ENOMEM;
+    ret = ctlv_device_init(&example->ctlvdev, &example_class, parent,
+                           &example->ctlv);
+    if (!ret)
+            ret = ctlv_init(&example->ctlv, &example->ctlvdev.dev,
+                            &ctlv_example_family, NULL);
+    if (ret)
+            goto err_put;
+    ctlv_publish(&example->ctlv);
+    ret = ctlv_device_add(&example->ctlvdev);
+    if (ret)
+            goto err_unpublish;
+
+``ctlv_device_init()`` names the node after the class, ``/dev/example0``.
+``ctlv_init()`` resolves the family chain. Until the instance is published, the
+driver selects its optional operations and their initial dynamic state, see
+Hooks and availability. ``ctlv_publish()`` makes operations live, and only then
+may the node be added, as a program may open it as soon as it appears.
+``ctlv_device_add()`` adds the node, whose uevent names the family; that is how
+udev finds the device. Destruction is the reverse:
+
+.. code-block:: c
+
+    ctlv_device_del(&example->ctlvdev);
+    ctlv_unpublish(&example->ctlv);
+    put_device(&example->ctlvdev.dev);
+
+``ctlv_unpublish()`` waits for the operations in flight; no callback runs
+afterwards. Each open file description fails its operations with ``-ENODEV``.
+The structure is freed with the last reference, the device's or an open file's,
+so what the callbacks used may stay in it. From ``ctlv_device_init()`` on,
+``put_device()`` alone unwinds a failed initialization, as it does a failed add
+once the instance is unpublished.
+
+A file of another subsystem
+---------------------------
+
+A subsystem may serve the instance on a file of its own instead, a misc device
+whose other operations are the subsystem's, say. It publishes the instance
+around the life of that file, attaches CTLV to each open file and passes on its
+ioctls:
+
+.. code-block:: c
+
+    static int foo_open(struct inode *inode, struct file *filp)
+    {
+            struct foo *foo = container_of(filp->private_data, struct foo, misc);
+            struct ctlv_file *cfile = ctlv_file_open(&foo->ctlv, filp);
+
+            if (IS_ERR(cfile))
+                    return PTR_ERR(cfile);
+            filp->private_data = cfile;
+            return 0;
+    }
+
+    static long foo_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
+    {
+            long ret = ctlv_file_ioctl(filp->private_data, cmd, arg);
+
+            return ret == -ENOIOCTLCMD ? foo_own_ioctl(filp, cmd, arg) : ret;
+    }
+
+Its release calls ``ctlv_file_close()``. The file's uevent is the other
+subsystem's and names no family, so a program opens the file by its name.
+
+The ``struct ctlv_hooks`` passed to ``ctlv_init()`` holds the device's pre and
+post hooks, see `Hooks`_. The device structure's release calls ``ctlv_fini()``
+when the last reference goes.
+
+Implement operations
+====================
+
+Action
+------
+
+Generated getters read only what validation accepted, and generated
+serializers write only what the reply declares:
+
+.. code-block:: c
+
+    int ctlv_example_item_set_action(struct ctlv *ctlv,
+                                     struct ctlv_op_ctx *ctx,
+                                     const struct ctlv_cursor *request,
+                                     struct ctlv_cursor *reply)
+    {
+            struct example_device *example = to_example(ctlv);
+            u64 index = ctlv_example_item_set_index_get(request);
+
+            if (item_busy(example, index))
+                    return ctlv_op_error(ctx, -EBUSY, "item is busy");
+            return item_set(example, index);
+    }
+
+Use ``_present()`` for optional fields and ``_for_each()`` for repeated
+ones. ``ctlv_op_error()`` preserves the errno and adds a short diagnostic when
+the caller supplied enough reply space.
+
+Query
+-----
+
+.. code-block:: c
+
+    int ctlv_example_item_get_query(struct ctlv *ctlv,
+                                      struct ctlv_op_ctx *ctx,
+                                      const struct ctlv_cursor *request,
+                                      struct ctlv_cursor *reply)
+    {
+            struct example_device *example = to_example(ctlv);
+            u64 generation = READ_ONCE(example->generation);
+            u64 cursor = ctlv_op_query_cursor(ctx);
+            struct ctlv_cursor item;
+            u64 i = cursor ? cursor - 1 : 0;
+
+            if (cursor && ctlv_op_query_generation(ctx) != generation)
+                    return -ESTALE;
+            for (; i < example->items_count; i++) {
+                    if (!ctlv_example_item_get_items_start(reply, &item))
+                            return ctlv_op_query_more(ctx, generation, i + 1);
+                    if (!ctlv_example_item_get_items_index_put(&item, i)) {
+                            ctlv_record_cancel(&item);
+                            return ctlv_op_query_more(ctx, generation, i + 1);
+                    }
+                    ctlv_record_end(&item);
+            }
+            return ctlv_op_query_done(ctx, generation);
+    }
+
+A continuation cursor is nonzero and advances. Every continuing fragment
+completes a logical leaf. An item that runs out of room partway is dropped with
+``ctlv_record_cancel()``, for the next fragment to write again. Call
+``ctlv_op_query_more()`` while cursors for open continuation records are alive.
+A generation mismatch returns ``-ESTALE``.
+
+Hooks and availability
+======================
+
+Hooks
+-----
+
+The pre and post hooks of the ``struct ctlv_hooks`` passed to ``ctlv_init()``
+run around every action and query the core does not answer. An op declared
+with ``pre-post: true`` also runs hooks of its own family, inside the
+device's:
+
+.. code-block:: yaml
+
+    item-get:
+      type: query
+      pre-post: true
+
+The family then implements ``ctlv_example_item_get_pre()`` and
+``ctlv_example_item_get_post()``, and the order is::
+
+    device pre -> operation pre -> availability check -> callback
+               -> operation post -> device post
+
+Each successful pre hook has one post hook. A failing pre hook undoes its own
+work. Hooks may sleep and must not retain ``ctx``. Each hook and callback gets
+the instance.
+
+Optional operations
+-------------------
+
+An op declared ``optional: true`` is published only on a device whose driver
+provides it before publishing the instance:
+
+.. code-block:: yaml
+
+    item-set:
+      type: action
+      optional: true
+
+.. code-block:: c
+
+    ctlv_example_item_set_provide(&example->ctlv);
+
+On a device that does not provide it, a program finds no entry for the
+operation in ``op-get`` or ``op-schema-get``, and executing it fails with
+``-EOPNOTSUPP``.
+
+Dynamic availability
+--------------------
+
+An op declared ``availability: dynamic`` can be refused for a while on a
+device that publishes it:
+
+.. code-block:: yaml
+
+    item-get:
+      type: query
+      availability: dynamic
+
+.. code-block:: c
+
+    ctlv_example_item_get_disable(&example->ctlv);
+    ctlv_example_item_get_enable(&example->ctlv);
+
+A disabled operation stays in ``op-get``, which reports it disabled, and
+returns ``-EOPNOTSUPP``.
+
+Blobs
+=====
+
+A blob field describes caller-owned memory. Resolve it only in the callback
+that received its request and release every successful resolve before return:
+
+.. code-block:: c
+
+    blob = ctlv_example_item_set_data_resolve(ctx, request);
+    if (IS_ERR(blob))
+            return PTR_ERR(blob);
+
+    ret = ctlv_blob_read(blob, 0, buf, ctlv_blob_len(blob));
+    put_ret = ctlv_blob_put(blob);
+    return ret ?: put_ret;
+
+The schema fixes direction, backing, length, and alignment. Resolution holds
+the backing for the ioctl. An output blob too short for
+what the operation produces is the caller's to enlarge: return
+``ctlv_blob_too_short()`` with the length needed, rather than writing part of
+it.
+
+Only a request carries a blob; the generator refuses one in a reply. A request
+that shares fields with a reply includes them and declares its blob beside them,
+as ``item-set`` does when it includes ``item``.
+
+Inheritance and HW driver fields
+================================
+
+Several HW drivers can implement ``ctlv-example``, and each knows things
+about its devices that a program may want, such as which bank of the foo
+chip's SRAM holds the items. Those do not belong in ``ctlv-example``, which
+all of them share. Instead, ``ctlv-example`` leaves a place for them, an
+extension point, and each HW driver has a family of its own that inherits
+``ctlv-example`` and fills it.
+
+Say ``ctlv-example`` gains a system call reporting the device::
+
+    device_get_action() -> { details? };
+
+On a device of the foo driver, ``details`` holds foo's fields::
+
+    device_get_action() -> { details? { u64 sram_bank; }; };
+
+``ctlv-example`` declares the op and leaves the contents of ``details`` to the
+HW driver, with an extension point:
+
+.. code-block:: yaml
+
+    ops:
+      # Reports the device.
+      device-get:
+        type: action
+        fd-access: read
+        reply:
+          # Empty here; a HW driver's family fills it with fields of its own.
+          details?: extension device-details
+
+The foo driver's family fills it by declaring a record of the same name:
+
+.. code-block:: yaml
+
+    # The devices of the foo driver, which fill what ctlv-example leaves open.
+    family: ctlv-example-foo
+    inherits: ctlv-example
+
+    records:
+      # The extension point ctlv-example left empty, filled for foo devices.
+      device-details:
+        # The bank of the foo chip's SRAM that holds the items.
+        sram-bank: uint(..3)
+
+The foo driver initializes its instances with ``ctlv_example_foo_family``, and
+they answer every ``ctlv-example`` op. A family implements only the ops it
+declares, so the inherited ones keep the callbacks and hooks of
+``ctlv-example``, and the foo module depends on the module that implements
+``ctlv-example``.
+
+The ``device-get`` callback in ``ctlv-example`` opens the record and has the
+device's family fill it:
+
+.. code-block:: c
+
+    if (ctlv_example_device_get_details_start(reply, &details)) {
+            ret = ctlv_ext_fill(ctx, NULL, &details);
+            ctlv_record_end(&details);
+            if (ret)
+                    return ret;
+    }
+
+The foo family implements the generated fill callback:
+
+.. code-block:: c
+
+    int ctlv_example_foo_device_details_fill(struct ctlv *ctlv,
+                                             struct ctlv_op_ctx *ctx,
+                                             const struct ctlv_cursor *request,
+                                             struct ctlv_cursor *record)
+    {
+            struct foo_device *foo = container_of(ctlv, struct foo_device,
+                                                  example.ctlv);
+
+            ctlv_example_foo_device_details_sram_bank_put(record,
+                                                          foo->sram_bank);
+            return 0;
+    }
+
+``request`` is the matching record of the request, for an op whose request has
+an extension point too; ``device-get`` has none and passes ``NULL``. An
+extension point no family fills adds no record and no length. ``ctlv-example``
+never names ``ctlv-example-foo``, and the foo family names nothing of
+``ctlv-example`` beyond the extension point it fills.
+
+A program knows whose fields it is reading without looking at them. A
+device's family chain runs from the root to the family of its instance,
+here ``ctlv``, ``ctlv-example`` and ``ctlv-example-foo``, and that last one,
+the leaf, is the HW driver's. ``family-get`` reports the chain on the open
+device, so a program picks its handler for the HW driver's fields once, when
+it opens the device; the uevent carries the same chain for udev rules. A tool
+that knows only ``ctlv-example`` skips the TLVs it does not know, as on any
+reply. Each TLV in a filled record also carries the family that declared its
+field, in bits 63..48 of its type: ``CTLV_TYPE_FAMILY()`` extracts it and
+``family-get`` maps it to a name.
+
+An enum can be left open the same way, when each HW driver has values of its
+own, such as the data formats its devices produce. ``ctlv-example`` declares
+the enum as an enum extension point, and its fields name it as any enum:
+
+.. code-block:: yaml
+
+    enums:
+      # The format of a device's data; a HW driver's family gives the values.
+      data-format: extension
+
+The foo driver's family gives the values, by declaring an enum of that name:
+
+.. code-block:: yaml
+
+    enums:
+      # Fills ctlv-example's data-format.
+      data-format:
+        # The foo device's own layout.
+        - foo-raw
+
+One family of a chain gives the values, numbered from 1 and appended to as any
+enum's. The core takes only those values on a device of that family, in a
+request and in what its driver puts in a reply, and none on a device whose
+chain gives none. The names are in the uapi header of the family that gives
+them, such as ``CTLV_EXAMPLE_FOO_DATA_FORMAT_FOO_RAW``. A family that checks
+values a HW driver hands it, before any reaches a reply, asks
+``ctlv_enum_ext_max()`` for the highest the driver's family gives.
+
+The structures embed one another as the families inherit. The module
+implementing ``ctlv-example`` keeps what every device of that family has in a
+structure around the instance, and exports what initializes it for a family
+that inherits ``ctlv-example``. A HW driver embeds that structure in its own
+and describes itself there, for the ``ctlv-example`` callbacks to use:
+
+.. code-block:: c
+
+    struct ctlv_example_device {
+            struct ctlv ctlv;
+            const struct ctlv_example_provider *provider;
+    };
+
+    struct foo_device {
+            struct ctlv_device ctlvdev;
+            struct ctlv_example_device example;
+            u32 sram_bank;
+    };
+
+    static const struct ctlv_example_provider foo_provider = {
+            .name = "foo",
+            .ops = &foo_provider_ops,
+    };
+
+    foo = kzalloc(sizeof(*foo), GFP_KERNEL);
+    if (!foo)
+            return -ENOMEM;
+    ret = ctlv_device_init(&foo->ctlvdev, &foo_class, parent,
+                           &foo->example.ctlv);
+    if (!ret)
+            ret = ctlv_example_device_init(&foo->example, &foo->ctlvdev.dev,
+                                           &ctlv_example_foo_family,
+                                           &foo_provider);
+
+The node is of the foo driver's own class, ``foo_class``, registered as
+``example_class`` is above. ``ctlv_example_device_init()`` refuses a family
+that ``ctlv_family_inherits()`` says is not ``ctlv-example`` or a descendant,
+then calls ``ctlv_init()``.
+
+Reporting an error
+------------------
+
+A callback returns a negative errno, and that is what the ioctl returns. Where
+CTLV itself refuses a message it also writes error information into the
+caller's reply buffer, naming the reason and the offset of the offending
+TLV. A family implementation does not build that; it adds its own errno
+and its reply.
+
+Configuration
+=============
+
+``CONFIG_CTLV``
+    CTLV. A family implementation selects it.
+
+Kernel API
+==========
+
+.. kernel-doc:: include/linux/ctlv.h
+.. kernel-doc:: lib/ctlv/core.c
+   :export:
+.. kernel-doc:: lib/ctlv/builder.c
+   :export:
+.. kernel-doc:: lib/ctlv/schema.c
+   :export:
+.. kernel-doc:: lib/ctlv/blob.c
+   :export:
+.. kernel-doc:: include/linux/ctlv_device.h
+.. kernel-doc:: lib/ctlv/device.c
+   :export:
Documentation/driver-api/index.rst +1 -0
index aaf5d76ed074..0c5b9d2165d8 100644
@@ -37,6 +37,7 @@ of interest to most developers working on device drivers.
 
    early-userspace/index
    connector
+   ctlv
    device-io
    devfreq
    dma-buf
MAINTAINERS +1 -0
index 29bdb4de915d..b16bedbbe0b6 100644
@@ -7188,6 +7188,7 @@ M:	Jiri Pirko <[email protected]>
 L:	[email protected]
 S:	Maintained
 F:	Documentation/ctlv/
+F:	Documentation/driver-api/ctlv.rst
 F:	Documentation/userspace-api/ctlv.rst
 F:	include/linux/ctlv*.h
 F:	include/uapi/ctlv/
Signature · 1 line
2.56.0
#19 lore raw

Re: [PATCH RFC v2 13/15] Documentation: ctlv: Describe how to write a family

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Low] docs: ctlv: direct -ESTALE return in query example skips error-info - [Low] docs: ctlv: inaccurate…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Low] docs: ctlv: direct -ESTALE return in query example skips error-info
- [Low] docs: ctlv: inaccurate claim that unfilled extension adds no record
--

commit 37d8b6224a7e92519379e383dd7fb525d99c7126
Author: Jiri Pirko <[email protected]>

Documentation: ctlv: Describe how to write a family

This commit adds driver-api documentation explaining how to define a CTLV family specification in YAML and implement its kernel callbacks.

Quoted 6 lines
Documentation/driver-api/ctlv.rst new file +0 -0
new file mode 100644
index 0000000000000..34d20c14a9bfa
@@ -0,0 +1,716 @@

[ ... ]

Documentation/driver-api/ctlv.rst line 410

Quoted 13 lines
Documentation/driver-api/ctlv.rst new file +13 -0
+    int ctlv_example_item_get_query(struct ctlv *ctlv,
+                                      struct ctlv_op_ctx *ctx,
+                                      const struct ctlv_cursor *request,
+                                      struct ctlv_cursor *reply)
+    {
+            struct example_device *example = to_example(ctlv);
+            u64 generation = READ_ONCE(example->generation);
+            u64 cursor = ctlv_op_query_cursor(ctx);
+            struct ctlv_cursor item;
+            u64 i = cursor ? cursor - 1 : 0;
+
+            if (cursor && ctlv_op_query_generation(ctx) != generation)
+                    return -ESTALE;

[Severity: Low]
Does returning -ESTALE directly here skip populating ctx->error for ctlv_error_info()?

ctlv_query_fragment_end() (called by ctlv_op_query_done() and ctlv_op_query_more()) is the only place that sets CTLV_VALIDATION_REASON_STALE_GENERATION along with expected_generation and current_generation:

lib/ctlv/builder.c:ctlv_query_fragment_end() {
    ...
	if (ctx->frag.cursor && generation != ctx->frag.generation) {
		ctx->error.reason = CTLV_VALIDATION_REASON_STALE_GENERATION;
		ctx->error.expected_generation = ctx->frag.generation;
		ctx->error.current_generation = generation;
		return -ESTALE;
	}
    ...
}

When a callback returns -ESTALE directly, ctlv_error_info() sees ctx->error.reason == 0 and omits the stale-generation error-info message documented in Documentation/userspace-api/ctlv.rst. Calling ctlv_op_query_done(ctx, generation) on mismatch or letting the loop finish into ctlv_op_query_done() would populate the error info and return -ESTALE.

[ ... ]

Quoted 22 lines
Documentation/driver-api/ctlv.rst new file +22 -0
+The ``device-get`` callback in ``ctlv-example`` opens the record and has the
+device's family fill it:
+
+.. code-block:: c
+
+    if (ctlv_example_device_get_details_start(reply, &details)) {
+            ret = ctlv_ext_fill(ctx, NULL, &details);
+            ctlv_record_end(&details);
+            if (ret)
+                    return ret;
+    }
+
+The foo family implements the generated fill callback:
+
+.. code-block:: c
+
+    int ctlv_example_foo_device_details_fill(struct ctlv *ctlv,
+                                             struct ctlv_op_ctx *ctx,
+                                             const struct ctlv_cursor *request,
+                                             struct ctlv_cursor *record)
+    {
+            struct foo_device *foo = container_of(ctlv, struct foo_device,

Documentation/driver-api/ctlv.rst

Quoted 10 lines
Documentation/driver-api/ctlv.rst new file +10 -0
+                                                  example.ctlv);
+
+            ctlv_example_foo_device_details_sram_bank_put(record,
+                                                          foo->sram_bank);
+            return 0;
+    }
+
+``request`` is the matching record of the request, for an op whose request has
+an extension point too; ``device-get`` has none and passes ``NULL``. An
+extension point no family fills adds no record and no length.

[Severity: Low]
Is it accurate that an unfilled extension point adds no record and no length?

ctlv_example_device_get_details_start() calls ctlv_record_start(), which writes a 16-byte struct ctlv_hdr with CTLV_HDR_F_RECORD into the reply and adds 16 bytes to each ancestor record's length. When no family in the chain fills the extension point, ctlv_ext_fill() returns 0 and ctlv_record_end() leaves that empty 16-byte record in the output buffer (and the schema size calculations in schema.c and sizes.py likewise count 16 bytes for the empty extension record header).

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=13
author
#20 lore raw

RFC PATCH v2 14/15 tools/ctlv: Add the userspace library

In reply to Jiri Pirko

From: Jiri Pirko <[email protected]>

Provide family-independent userspace transport, message handling, discovery, schemas and blob descriptors. Generated bindings build on this API.

Assisted-by Cursor: GPT-5.6 Sol
Assisted-by Cursor: Claude Opus 5.5
---
 .../ctlv/generated-files-schema.yaml          |   4 +
 Documentation/ctlv/generated-files.yaml       |   1 +
 Documentation/driver-api/ctlv.rst             |   2 +-
 Documentation/userspace-api/ctlv.rst          |  17 +
 tools/ctlv/Makefile                           |   8 +-
 tools/ctlv/ctlvgen/cli.py                     |   8 +-
 tools/ctlv/ctlvgen/lib/gen_user.py            | 808 ++++++++++++++++++
 tools/ctlv/ctlvgen/lib/outputs.py             |  12 +-
 tools/ctlv/libctlv/Makefile                   |  41 +
 tools/ctlv/libctlv/ctlv.h                     | 413 +++++++++
 tools/ctlv/libctlv/ctlv_user_gen.c            | 551 ++++++++++++
 tools/ctlv/libctlv/device.c                   | 412 +++++++++
 tools/ctlv/libctlv/internal.h                 | 161 ++++
 tools/ctlv/libctlv/introspection.c            | 238 ++++++
 tools/ctlv/libctlv/message.c                  | 518 +++++++++++
 tools/ctlv/libctlv/schema.c                   | 742 ++++++++++++++++
 tools/ctlv/libctlv/spec.c                     | 186 ++++
 tools/ctlv/libctlv/transport.c                | 572 +++++++++++++
 18 files changed, 4689 insertions(+), 5 deletions(-)
 create mode 100644 tools/ctlv/ctlvgen/lib/gen_user.py
 create mode 100644 tools/ctlv/libctlv/Makefile
 create mode 100644 tools/ctlv/libctlv/ctlv.h
 create mode 100644 tools/ctlv/libctlv/ctlv_user_gen.c
 create mode 100644 tools/ctlv/libctlv/device.c
 create mode 100644 tools/ctlv/libctlv/internal.h
 create mode 100644 tools/ctlv/libctlv/introspection.c
 create mode 100644 tools/ctlv/libctlv/message.c
 create mode 100644 tools/ctlv/libctlv/schema.c
 create mode 100644 tools/ctlv/libctlv/spec.c
 create mode 100644 tools/ctlv/libctlv/transport.c
Documentation/ctlv/generated-files-schema.yaml +4 -0
index d3529ce6e8e7..d5f2d3763c48 100644
@@ -20,6 +20,10 @@ $defs:
         $ref: '#/$defs/path'
       kernel-source:
         $ref: '#/$defs/path'
+      user-header:
+        $ref: '#/$defs/path'
+      user-source:
+        $ref: '#/$defs/path'
 
   registry:
     type: object
Documentation/ctlv/generated-files.yaml +1 -0
index 5488ddf40e17..d4766b176ceb 100644
@@ -15,3 +15,4 @@ families:
       uapi-header: include/uapi/ctlv/ctlv_gen.h
       kernel-header: include/linux/ctlv_gen.h
       kernel-source: lib/ctlv/ctlv_gen.c
+      user-source: tools/ctlv/libctlv/ctlv_user_gen.c
Documentation/driver-api/ctlv.rst +1 -1
index 34d20c14a9bf..f6a4f9632e3a 100644
@@ -312,7 +312,7 @@ driver selects its optional operations and their initial dynamic state, see
 Hooks and availability. ``ctlv_publish()`` makes operations live, and only then
 may the node be added, as a program may open it as soon as it appears.
 ``ctlv_device_add()`` adds the node, whose uevent names the family; that is how
-udev finds the device. Destruction is the reverse:
+libctlv and udev find the device. Destruction is the reverse:
 
 .. code-block:: c
 
Documentation/userspace-api/ctlv.rst +17 -0
index f1f775071a78..8a8ade33b490 100644
@@ -118,6 +118,21 @@ The op ID and the types come from the family's generated UAPI header.
 Before the family sees the request, the kernel checks it against the
 specification: ``index`` must be at most 4095 and ``label`` at most 63 bytes.
 
+``libctlv`` and the generated bindings build and send the same message:
+
+.. code-block:: c
+
+    struct ctlv_error error;
+    struct ctlv_msg *req;
+    struct ctlv_dev *dev;
+
+    /* Error checks left out. */
+    ctlv_open("ctlv-example", 0, O_RDWR, &dev);
+    ctlv_example_item_set_request_new(&req);
+    ctlv_example_item_set_index_put(req, 3);
+    ctlv_example_item_set_label_put(req, "ab");
+    ctlv_example_item_set(dev, req, &error);
+
 The sections below define each piece: the device, the message format, the
 ioctl, queries, blobs and introspection, and then the rules of compatibility.
 
@@ -410,6 +425,8 @@ defined flags. The root cannot carry the flag, and replies never do.
 
 So the kernel acts on what it knows and ignores the rest. A caller that needs
 to know which of its fields will be acted on asks ``op-schema-get`` first.
+``libctlv`` sets the flag with ``ctlv_msg_ignore_if_unknown()`` on the TLV
+written last.
 
 Executing an operation
 ======================
tools/ctlv/Makefile +7 -1
index bdec011595aa..881fae9127c7 100644
@@ -30,10 +30,16 @@ lint:
 	python3 -m pyflakes $(PYSRC)
 	python3 -m mypy $(PYSRC)
 
+# The C half of this directory: the userspace library, which is not generated
+# and not Python, so it is its own target rather than part of the checks above.
+programs:
+	$(MAKE) -C libctlv
+
 clean:
 	rm -rf ctlvgen/__pycache__
 	rm -rf ctlvgen/lib/__pycache__
 	rm -rf ctlvgen.egg-info
 	rm -rf build
+	$(MAKE) -C libctlv clean
 
-.PHONY: all regen lint clean
+.PHONY: all regen lint programs clean
tools/ctlv/ctlvgen/cli.py +7 -1
index 78e09cfd620e..59180f9757e8 100755
@@ -16,6 +16,7 @@ sys.path.append(pathlib.Path(__file__).resolve().parents[1].as_posix())
 from ctlvgen.lib import cgen  # noqa: E402
 from ctlvgen.lib import gen_kernel  # noqa: E402
 from ctlvgen.lib import gen_uapi  # noqa: E402
+from ctlvgen.lib import gen_user  # noqa: E402
 from ctlvgen.lib import semantics  # noqa: E402
 from ctlvgen.lib import spec  # noqa: E402
 from ctlvgen.lib import tree  # noqa: E402
@@ -27,6 +28,8 @@ GENERATORS: dict[tuple[str, str], Callable[..., str]] = {
     ('uapi', 'header'): gen_uapi.render,
     ('kernel', 'header'): gen_kernel.render_header,
     ('kernel', 'source'): gen_kernel.render_source,
+    ('user', 'header'): gen_user.render_header,
+    ('user', 'source'): gen_user.render_source,
 }
 
 
@@ -50,7 +53,7 @@ def main() -> int:
                         help='regenerate every file in the output manifests '
                              'and every ABI snapshot')
     action.add_argument('--mode',
-                        choices=('uapi', 'kernel'),
+                        choices=('uapi', 'kernel', 'user'),
                         help='generate the files of this mode')
     parser.add_argument('--schema-only', action='store_true',
                         help='omit the family API from kernel output')
@@ -105,6 +108,9 @@ def main() -> int:
         family = semantics.load(paths)
         if args.validate:
             cgen.symbols(family)
+            # The root family has no binding: libctlv is that binding.
+            if family.name != spec.CORE_FAMILY_NAME:
+                cgen.user_symbols(family)
         else:
             assert file is not None
             _generate(args, file, family)
tools/ctlv/ctlvgen/lib/gen_user.py new file +808 -0

808 lines not on this page · raw message

tools/ctlv/ctlvgen/lib/outputs.py +10 -2
index a295055c46b2..6ee8abe7f765 100644
@@ -14,6 +14,7 @@ from typing import Optional
 from . import cgen
 from . import gen_kernel
 from . import gen_uapi
+from . import gen_user
 from . import semantics
 from . import spec
 from . import yamlload
@@ -24,16 +25,21 @@ FLAVOURS: dict[str, Callable[..., str]] = {
     'uapi-header': gen_uapi.render,
     'kernel-header': gen_kernel.render_header,
     'kernel-source': gen_kernel.render_source,
+    'user-header': gen_user.render_header,
+    'user-source': gen_user.render_source,
 }
 
 IDENTITIES: dict[str, tuple[str, str, str]] = {
     'uapi-header': ('uapi', 'header', '.h'),
     'kernel-header': ('kernel', 'header', '.h'),
     'kernel-source': ('kernel', 'source', '.c'),
+    'user-header': ('user', 'header', '.h'),
+    'user-source': ('user', 'source', '.c'),
 }
 
-ROOT_FLAVOURS = frozenset(FLAVOURS)
-FAMILY_FLAVOURS: frozenset[str] = frozenset(FLAVOURS)
+USER_FLAVOURS = frozenset({'user-header', 'user-source'})
+ROOT_FLAVOURS = frozenset(FLAVOURS) - {'user-header'}
+FAMILY_FLAVOURS: frozenset[str] = frozenset(FLAVOURS) - USER_FLAVOURS
 FIXTURE_FLAVOURS: frozenset[str] = frozenset({
     'uapi-header', 'kernel-header', 'kernel-source',
 })
@@ -143,6 +149,8 @@ def load(paths: spec.Paths) -> tuple[Output, ...]:
             if not fixture and name == spec.CORE_FAMILY_NAME:
                 required = ROOT_FLAVOURS
             flavours = frozenset(record['outputs'])
+            if required == FAMILY_FLAVOURS and flavours & USER_FLAVOURS:
+                required |= USER_FLAVOURS
             if flavours != required:
                 missing = sorted(required - flavours)
                 extra = sorted(flavours - required)
tools/ctlv/libctlv/Makefile new file +41 -0

41 lines not on this page · raw message

tools/ctlv/libctlv/ctlv.h new file +413 -0

413 lines not on this page · raw message

tools/ctlv/libctlv/ctlv_user_gen.c new file +551 -0

551 lines not on this page · raw message

tools/ctlv/libctlv/device.c new file +412 -0

412 lines not on this page · raw message

tools/ctlv/libctlv/internal.h new file +161 -0

161 lines not on this page · raw message

tools/ctlv/libctlv/introspection.c new file +238 -0

238 lines not on this page · raw message

tools/ctlv/libctlv/message.c new file +518 -0

238 lines not on this page · raw message

tools/ctlv/libctlv/schema.c new file +742 -0

742 lines not on this page · raw message

tools/ctlv/libctlv/spec.c new file +186 -0

186 lines not on this page · raw message

tools/ctlv/libctlv/transport.c new file +572 -0

572 lines not on this page · raw message

The rest of this diff is not shown. View the raw message.

Signature · 1 line
2.56.0

Part of the diff is not shown here. View the raw message.

#21 lore raw

Re: [PATCH RFC v2 14/15] tools/ctlv: Add the userspace library

Thank you for your contribution! Sashiko AI review found 7 potential issues to consider: - [Medium] tools/ctlv: missing ctlv_hdr_is_record() check in record walkers and getters - [Low] tools/ctlv…

Thank you for your contribution! Sashiko AI review found 7 potential issues to consider:
- [Medium] tools/ctlv: missing ctlv_hdr_is_record() check in record walkers and getters
- [Low] tools/ctlv: ctlv_put_str() bypasses sticky msg->err on length overflow
- [Low] tools/ctlv: memory leak in ctlv_msg_new_max() when ctlv_record_start() fails
- [Low] tools/ctlv: unpopulated ctlv_error in ctlv_spec_check() and ctlv_query_sized()
- [Low] tools/ctlv: stale bound and truncation of reason in ctlv_error_parse()
- [Low] tools/ctlv: missing progress check on final fragment in ctlv_query_guard_next()
- [Low] tools/ctlv: missing -ESTALE retry loop in ctlv_ops_get() --

commit 128e9e8121ea589172c7fc1358fcc6d31f685bab
Author: Jiri Pirko <[email protected]>

tools/ctlv: Add the userspace library

This commit adds the libctlv userspace library for transport, message building and parsing, device discovery, and schema checking, along with the userspace code generator in ctlvgen.

Quoted 5 lines
tools/ctlv/libctlv/introspection.c new file +0 -0
new file mode 100644
index 0000000000000..1bd2662e58317

[ ... ]

tools/ctlv/libctlv/introspection.c line 182

Quoted 10 lines
tools/ctlv/libctlv/introspection.c new file +10 -0
+int ctlv_ops_get(struct ctlv_dev *dev, struct ctlv_ops **opsp,
+		 struct ctlv_error *error)
+{
+	struct ctlv_reply *reply = NULL;
+	int ret;
+
+	/* Sized, or the dump kept for op lengths would ask for itself. */
+	ret = ctlv_query_sized(dev, CTLV_OP_OP_GET, NULL, 0, &reply, error);
+	if (ret)
+		return ret;

[Severity: Low]
Should ctlv_ops_get() retry up to QUERY_RESTARTS times on -ESTALE like ctlv_query() does?

Because ctlv_ops_get() calls ctlv_query_sized() directly to avoid recursing into ctlv_dev_sizes(), a dynamic op state change between fragments of an op-get dump causes ctlv_ops_get(), ctlv_dev_sizes(), and ctlv_spec_check() to fail with -ESTALE instead of restarting the dump.

[ ... ]

Quoted 5 lines
tools/ctlv/libctlv/message.c new file +0 -0
new file mode 100644
index 0000000000000..ab4464fb8af2d

[ ... ]

Quoted 10 lines
tools/ctlv/libctlv/message.c new file +10 -0
+int ctlv_msg_new_max(__u32 capacity, __u32 max, struct ctlv_msg **msgp)
+{
+	struct ctlv_msg *msg;
+
+	if (!capacity || capacity > max)
+		return -EINVAL;
+	msg = calloc(1, sizeof(*msg));
+	if (!msg)
+		return -ENOMEM;
+	/* Separate from the handle, so growing the buffer does not move it. */

tools/ctlv/libctlv/message.c line 129

Quoted 10 lines
tools/ctlv/libctlv/message.c new file +10 -0
+	msg->buf = malloc(capacity);
+	if (!msg->buf) {
+		free(msg);
+		return -ENOMEM;
+	}
+	msg->capacity = capacity;
+	msg->max = max;
+	*msgp = msg;
+	return ctlv_record_start(msg, CTLV_TYPE_ROOT);
+}

[Severity: Low]
Does ctlv_msg_new_max() leak msg and msg->buf if ctlv_record_start() fails?

When capacity is smaller than sizeof(struct ctlv_hdr) (16 bytes), ctlv_record_start() has to grow msg->buf; if max < 16 or realloc() fails, ctlv_msg_new_max() returns a negative errno with *msgp pointing to the allocated struct, which callers such as reply_new() do not free on error.

[ ... ]

tools/ctlv/libctlv/message.c line 266

Quoted 9 lines
tools/ctlv/libctlv/message.c new file +9 -0
+/* The terminator is part of the payload, and a declared length excludes it. */
+int ctlv_put_str(struct ctlv_msg *msg, __u64 type, const char *value)
+{
+	size_t len = strlen(value) + 1;
+
+	if (len > UINT32_MAX)
+		return -EMSGSIZE;
+	return ctlv_msg_put(msg, type, 0, value, len);
+}

[Severity: Low]
Does the length overflow path in ctlv_put_str() bypass msg->err?

If len > UINT32_MAX, returning -EMSGSIZE directly neither preserves an earlier msg->err nor records -EMSGSIZE in msg->err, so a caller checking ctlv_msg_err() or ctlv_msg_done() at the end will miss the failure and send an incomplete message.

[ ... ]

Quoted 20 lines
tools/ctlv/libctlv/message.c new file +20 -0
+const struct ctlv_hdr *ctlv_hdr_first(const struct ctlv_hdr *record)
+{
+	if (record->len <= sizeof(*record))
+		return NULL;
+	/* A record too short to hold the header it announces holds no child. */
+	if (record->len - sizeof(*record) < sizeof(*record))
+		return NULL;
+	return record + 1;
+}
+
+/*
+ * The next child is a step of this one's aligned length. Both the step and the
+ * header it lands on have to stay inside the record.
+ */
+const struct ctlv_hdr *ctlv_hdr_next(const struct ctlv_hdr *record,
+				     const struct ctlv_hdr *child)
+{
+	const char *end = (const char *)record + record->len;
+	const char *next = (const char *)child;
+	__u32 step;

tools/ctlv/libctlv/message.c line 331

Quoted 10 lines
tools/ctlv/libctlv/message.c new file +10 -0
+
+	if (aligned(child->len, &step))
+		return NULL;
+	next += step;
+	if (next < (const char *)child || next > end)
+		return NULL;
+	if ((size_t)(end - next) < sizeof(*child))
+		return NULL;
+	return (const struct ctlv_hdr *)next;
+}

[Severity: Medium]
Should ctlv_hdr_first(), ctlv_hdr_next(), and the generated record getters verify ctlv_hdr_is_record()?

check_record() only validates nested TLV headers when CTLV_HDR_F_RECORD is set, and the scalar getters reject records via ctlv_hdr_is_record(hdr), but ctlv_hdr_first() and ctlv_hdr_next() walk any TLV whose len is at least 32 bytes. Generated record getters in tools/ctlv/ctlvgen/lib/gen_user.py:_getter() also return ctlv_hdr_find() without checking ctlv_hdr_is_record().

If a non-record TLV is passed to ctlv_hdr_first() or returned by a record getter, its unvalidated payload bytes are interpreted as struct ctlv_hdr, which can spin forever in ctlv_for_each() when the first 4 payload bytes are zero (step == 0) or read out of bounds when a child's len is smaller than sizeof(struct ctlv_hdr).

[ ... ]

Quoted 5 lines
tools/ctlv/libctlv/spec.c new file +0 -0
new file mode 100644
index 0000000000000..194966e29e2d8

[ ... ]

Quoted 5 lines
tools/ctlv/libctlv/spec.c new file +5 -0
+int ctlv_spec_check(struct ctlv_dev *dev, const struct ctlv_family_spec *spec,
+		    char *diff, size_t len, struct ctlv_error *error)
+{
+	struct ctlv_ops *ops;
+	unsigned int i;

tools/ctlv/libctlv/spec.c line 161

Quoted 10 lines
tools/ctlv/libctlv/spec.c new file +10 -0
+	int ret;
+
+	if (diff && len)
+		*diff = '\0';
+	ret = chain_check(dev, spec, diff, len);
+	if (ret)
+		return ret;
+	ret = ctlv_ops_get(dev, &ops, error);
+	if (ret)
+		return ret;

[Severity: Low]
Does ctlv_spec_check() leave *error uninitialized or cleared with error->err == 0 on failure?

If chain_check() fails, *error is never initialized, and if a later check fails with -ENOMSG (such as an unknown op, info_check(), ctlv_schema_equal() in schema_check(), or required_ops_check()), error->err remains 0 from ctlv_ops_get(). Similarly, in tools/ctlv/libctlv/transport.c:ctlv_query_sized(), if reply_new() fails it jumps to out_free_buf instead of out_set_err, leaving error->err as 0.

Quoted 5 lines
tools/ctlv/libctlv/transport.c new file +0 -0
new file mode 100644
index 0000000000000..647bab085c9e1

[ ... ]

tools/ctlv/libctlv/transport.c line 64

Quoted 7 lines
tools/ctlv/libctlv/transport.c new file +7 -0
+	hdr = ctlv_hdr_find(root, CTLV_T_ERROR_INFO_REASON);
+	if (hdr && !ctlv_get_enum(hdr, 1,
+				  CTLV_VALIDATION_REASON_STALE_GENERATION,
+				  &value, NULL)) {
+		error->reason = value;
+		error->present |= CTLV_ERROR_HAS_REASON;
+	}

[Severity: Low]
Does ctlv_error_parse() ignore the enum bounds and truncate value into error->reason?

ctlv_get_enum() only checks min and max when the known pointer is non-NULL, so passing NULL accepts any 64-bit value (including 0 or values above UINT32_MAX) and truncates it into the 32-bit error->reason field. In addition, the upper bound passed here is CTLV_VALIDATION_REASON_STALE_GENERATION (11) rather than CTLV_VALIDATION_REASON_NONCONTIGUOUS_TYPE (12).

[ ... ]

tools/ctlv/libctlv/transport.c line 307

Quoted 10 lines
tools/ctlv/libctlv/transport.c new file +10 -0
+int ctlv_query_guard_next(struct ctlv_query_guard *guard, __u64 cursor,
+			  bool progress)
+{
+	unsigned int slot;
+	int ret;
+
+	if (!cursor)
+		return 0;
+	if (!progress)
+		return -EPROTO;

[Severity: Low]
Does returning early on !cursor skip the progress check for the final fragment of a multi-fragment query?

When guard->cursors_count > 0 and the final continuation fragment ends with cursor == 0 without adding any complete TLV (progress == false), ctlv_query_guard_next() returns 0 instead of rejecting it with -EPROTO.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=14
author
#22 lore raw

RFC PATCH v2 15/15 tools/ctlv: Add ctlvctl

In reply to Jiri Pirko

From: Jiri Pirko <[email protected]>

Add a command-line client that discovers and queries any CTLV device, with optional names from a specification directory.

Examples:
Root-family discovery on any CTLV device:
ctlvctl --spec-dir Documentation/ctlv/specs \
exec ctlv-example family-get
The operations the same device publishes:

    ctlvctl --spec-dir Documentation/ctlv/specs ops ctlv-example
Assisted-by Cursor: GPT-5.6 Sol
Assisted-by Cursor: Claude Opus 5.5
---
 Documentation/driver-api/ctlv.rst     |   29 +-
 Documentation/userspace-api/ctlv.rst  |   80 +-
 tools/Makefile                        |    9 +-
 tools/ctlv/Makefile                   |   23 +-
 tools/ctlv/ctlvctl/.gitignore         |    4 +
 tools/ctlv/ctlvctl/Makefile           |   64 +
 tools/ctlv/ctlvctl/ctlvctl.c          | 2787 +++++++++++++++++++++++++
 tools/ctlv/ctlvctl/spec.c             |  672 ++++++
 tools/ctlv/ctlvctl/spec.h             |   60 +
 tools/ctlv/ctlvgen/cli.py             |   47 +-
 tools/ctlv/ctlvgen/lib/dump.py        |  161 ++
 tools/ctlv/ctlvgen/lib/gen_doc.py     |  684 ++++++
 tools/ctlv/ctlvgen/lib/gen_runtime.py |   66 +
 13 files changed, 4661 insertions(+), 25 deletions(-)
 create mode 100644 tools/ctlv/ctlvctl/.gitignore
 create mode 100644 tools/ctlv/ctlvctl/Makefile
 create mode 100644 tools/ctlv/ctlvctl/ctlvctl.c
 create mode 100644 tools/ctlv/ctlvctl/spec.c
 create mode 100644 tools/ctlv/ctlvctl/spec.h
 create mode 100644 tools/ctlv/ctlvgen/lib/dump.py
 create mode 100644 tools/ctlv/ctlvgen/lib/gen_doc.py
 create mode 100644 tools/ctlv/ctlvgen/lib/gen_runtime.py
Documentation/driver-api/ctlv.rst +18 -11
index f6a4f9632e3a..e8e6ecdf6ab6 100644
@@ -235,6 +235,9 @@ checks the same without writing anything.
 
 Never edit a generated file; change the YAML or the generator and regenerate.
 
+``make -C tools/ctlv docs`` writes optional RST reference pages to
+``Documentation/output/ctlv/families``.
+
 Create and destroy a device
 ===========================
 
@@ -684,20 +687,24 @@ The node is of the foo driver's own class, ``foo_class``, registered as
 that ``ctlv_family_inherits()`` says is not ``ctlv-example`` or a descendant,
 then calls ``ctlv_init()``.
 
-Reporting an error
-------------------
+Tests and examples
+==================
+
+``Documentation/ctlv/specs/ctlv-test.yaml``
+    Every schema kind, records, actions, queries, blobs, availability, hooks,
+    and an extension point.
+
+``drivers/ctlv/tests/ctlv_test.c``
+    The ``ctlv-test`` family implementation.
 
-A callback returns a negative errno, and that is what the ioctl returns. Where
-CTLV itself refuses a message it also writes error information into the
-caller's reply buffer, naming the reason and the offset of the offending
-TLV. A family implementation does not build that; it adds its own errno
-and its reply.
+``drivers/ctlv/tests/ctlv_test_child.c``
+    A separately built inheriting family and extension-point fill.
 
-Configuration
-=============
+``lib/ctlv/tests/*_kunit.c``
+    Unit tests of the engine and of its nodes.
 
-``CONFIG_CTLV``
-    CTLV. A family implementation selects it.
+``tools/testing/selftests/ctlv/``
+    Raw-message, generated-binding, allocation-failure, and mutation selftests.
 
 Kernel API
 ==========
Documentation/userspace-api/ctlv.rst +76 -4

107 lines not on this page · raw message

tools/Makefile +8 -1
index cb40961a740f..d8d0003b16a5 100644
@@ -13,6 +13,7 @@ help:
 	@echo '  bpf                    - misc BPF tools'
 	@echo '  counter                - counter tools'
 	@echo '  cpupower               - a tool for all things x86 CPU power'
+	@echo '  ctlv                   - CTLV library and ctlvctl, after make headers'
 	@echo '  debugging              - tools for debugging'
 	@echo '  dma                    - tools for DMA mapping'
 	@echo '  firewire               - the userspace part of nosy, an IEEE-1394 traffic sniffer'
@@ -70,6 +71,9 @@ acpi: FORCE
 cpupower: FORCE
 	$(call descend,power/$@)
 
+ctlv: FORCE
+	$(call descend,ctlv/ctlvctl)
+
 counter dma firewire hv guest bootconfig spi usb virtio mm bpf iio gpio objtool leds wmi firmware debugging tracing: FORCE
 	$(call descend,$@)
 
@@ -179,6 +183,9 @@ acpi_clean:
 cpupower_clean:
 	$(call descend,power/cpupower,clean)
 
+ctlv_clean:
+	$(call descend,ctlv/ctlvctl,clean)
+
 counter_clean dma_clean hv_clean firewire_clean bootconfig_clean spi_clean usb_clean virtio_clean mm_clean wmi_clean bpf_clean iio_clean gpio_clean objtool_clean leds_clean firmware_clean debugging_clean tracing_clean:
 	$(call descend,$(@:_clean=),clean)
 
@@ -225,7 +232,7 @@ build_clean:
 ynl_clean:
 	$(call descend,net/$(@:_clean=),clean)
 
-clean: acpi_clean counter_clean cpupower_clean dma_clean hv_clean firewire_clean \
+clean: acpi_clean counter_clean cpupower_clean ctlv_clean dma_clean hv_clean firewire_clean \
 		perf_clean selftests_clean turbostat_clean bootconfig_clean spi_clean usb_clean virtio_clean \
 		mm_clean bpf_clean iio_clean x86_energy_perf_policy_clean tmon_clean \
 		freefall_clean build_clean libbpf_clean libsubcmd_clean \
tools/ctlv/Makefile +20 -3
index 881fae9127c7..83c0ece690e8 100644
@@ -2,6 +2,10 @@
 
 KDIR = ../..
 DOCDIR = $(KDIR)/Documentation/ctlv
+SPECDIR = $(DOCDIR)/specs
+SPECS = $(wildcard $(SPECDIR)/*.yaml)
+TOOL = ./ctlvgen/cli.py
+DOC_OUTPUT ?= $(KDIR)/Documentation/output/ctlv/families
 
 # Writes nothing. Fails on an invalid specification, and on any generated file
 # or ABI snapshot that regen would change.
@@ -30,16 +34,29 @@ lint:
 	python3 -m pyflakes $(PYSRC)
 	python3 -m mypy $(PYSRC)
 
-# The C half of this directory: the userspace library, which is not generated
-# and not Python, so it is its own target rather than part of the checks above.
+docs:
+	@mkdir -p $(DOC_OUTPUT)
+	@for spec in $(SPECS) ; do \
+		name=$$(basename $$spec .yaml) ; \
+		echo -e "\tDOC $$name.rst" ; \
+		$(TOOL) --spec $$spec --mode doc --rst \
+			-o $(DOC_OUTPUT)/$$name.rst || exit 1 ; \
+	done
+
+# The C half of this directory: the userspace library, and the tool that drives
+# a device it was never compiled against. Neither is generated and neither is
+# Python, so they are their own target rather than part of the checks above.
 programs:
 	$(MAKE) -C libctlv
+	$(MAKE) -C ctlvctl
 
 clean:
 	rm -rf ctlvgen/__pycache__
 	rm -rf ctlvgen/lib/__pycache__
 	rm -rf ctlvgen.egg-info
 	rm -rf build
+	rm -rf $(DOC_OUTPUT)
 	$(MAKE) -C libctlv clean
+	$(MAKE) -C ctlvctl clean
 
-.PHONY: all regen lint programs clean
+.PHONY: all regen lint docs programs clean
tools/ctlv/ctlvctl/.gitignore new file +4 -0
new file mode 100644
index 000000000000..dcade74af00e
@@ -0,0 +1,4 @@
+# SPDX-License-Identifier: GPL-2.0-only
+/*.json
+/ctlvctl
+/libctlv/
tools/ctlv/ctlvctl/Makefile new file +64 -0

64 lines not on this page · raw message

tools/ctlv/ctlvctl/ctlvctl.c new file +2787 -0

2,706 lines not on this page · raw message

tools/ctlv/ctlvctl/spec.c new file +672 -0

672 lines not on this page · raw message

tools/ctlv/ctlvctl/spec.h new file +60 -0

60 lines not on this page · raw message

tools/ctlv/ctlvgen/cli.py +41 -6

47 lines not on this page · raw message

tools/ctlv/ctlvgen/lib/dump.py new file +161 -0

161 lines not on this page · raw message

tools/ctlv/ctlvgen/lib/gen_doc.py new file +684 -0

684 lines not on this page · raw message

tools/ctlv/ctlvgen/lib/gen_runtime.py new file +66 -0

66 lines not on this page · raw message

The rest of this diff is not shown. View the raw message.

Signature · 1 line
2.56.0

Part of the diff is not shown here. View the raw message.

#23 lore raw

Re: [PATCH RFC v2 15/15] tools/ctlv: Add ctlvctl

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Low] Documentation: ctlv: driver-api guide drops sections and cites missing tests - [Low] tools/ctlv…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Low] Documentation: ctlv: driver-api guide drops sections and cites missing tests
- [Low] tools/ctlv: uncleaned libctlv build artifacts in ctlv_clean target
--

commit 44c8b60bf07b7ca2b82f88cb4a596bb865f2b940
Author: Jiri Pirko <[email protected]>

tools/ctlv: Add ctlvctl

This commit adds the ctlvctl command-line client for discovering and querying CTLV devices, along with runtime manifest and RST documentation generators in ctlvgen.

Quoted 4 lines
Documentation/driver-api/ctlv.rst +0 -0
index f6a4f9632e3a5..e8e6ecdf6ab66 100644

[ ... ]

Quoted 26 lines
Documentation/driver-api/ctlv.rst +11 -9
@@ -684,20 +687,24 @@ The node is of the foo driver's own class, ``foo_class``, registered as
 that ``ctlv_family_inherits()`` says is not ``ctlv-example`` or a descendant,
 then calls ``ctlv_init()``.
 
-Reporting an error
-------------------
+Tests and examples
+==================
+
+``Documentation/ctlv/specs/ctlv-test.yaml``
+    Every schema kind, records, actions, queries, blobs, availability, hooks,
+    and an extension point.
+
+``drivers/ctlv/tests/ctlv_test.c``
+    The ``ctlv-test`` family implementation.
 
-A callback returns a negative errno, and that is what the ioctl returns. Where
-CTLV itself refuses a message it also writes error information into the
-caller's reply buffer, naming the reason and the offset of the offending
-TLV. A family implementation does not build that; it adds its own errno
-and its reply.
+``drivers/ctlv/tests/ctlv_test_child.c``
+    A separately built inheriting family and extension-point fill.
 
-Configuration
-=============

Documentation/driver-api/ctlv.rst The node is of the foo driver's own class, ``foo_class``, registered as · line 710

Quoted 10 lines
Documentation/driver-api/ctlv.rst +4 -2
+``lib/ctlv/tests/*_kunit.c``
+    Unit tests of the engine and of its nodes.
 
-``CONFIG_CTLV``
-    CTLV. A family implementation selects it.
+``tools/testing/selftests/ctlv/``
+    Raw-message, generated-binding, allocation-failure, and mutation selftests.
 
 Kernel API
 ==========

[Severity: Low]
Were the "Reporting an error" and "Configuration" sections added in commit "Documentation: ctlv: Describe how to write a family" dropped here by mistake? Also, none of the five test paths listed under "Tests and examples" exist in the tree at this commit.

[ ... ]

Quoted 4 lines
tools/Makefile +0 -0
index cb40961a740f7..d8d0003b16a5f 100644

[ ... ]

Quoted 7 lines
tools/Makefile +3 -0
@@ -179,6 +183,9 @@ acpi_clean:
 cpupower_clean:
 	$(call descend,power/cpupower,clean)
 
+ctlv_clean:
+	$(call descend,ctlv/ctlvctl,clean)
+

[ ... ]

Quoted 5 lines
tools/ctlv/ctlvctl/Makefile new file +0 -0
new file mode 100644
index 0000000000000..dcfca390d4024

[ ... ]

tools/ctlv/ctlvctl/Makefile line 59

Quoted 7 lines

+$(LIB): FORCE

tools/ctlv/ctlvctl/Makefile new file +6 -0
+	$(if $(LIBCTLV_OUTPUT),$(Q)mkdir -p $(LIBCTLV_OUTPUT))
+	$(Q)$(MAKE) -C $(LIBDIR) OUTPUT=$(LIBCTLV_OUTPUT)
+
+clean:
+	rm -f $(OUTPUT)ctlvctl $(OBJS) $(MANIFESTS)
+	$(if $(LIBCTLV_OUTPUT),rm -rf $(LIBCTLV_OUTPUT))

[Severity: Low]
Does the clean target leave libctlv build artifacts behind when building in tree without O=? When OUTPUT and LIBCTLV_OUTPUT are empty, $(LIB) builds objects and libctlv.a inside tools/ctlv/libctlv/, but neither ctlv_clean in tools/Makefile nor clean in tools/ctlv/ctlvctl/Makefile cleans $(LIBDIR).

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=15
Tested-by Reviewed-by on the v2 series
#24 lore raw
In reply to Jiri Pirko

I've tested with my FIRME and arm-cca-guest implementations based on this patch series. So for this series,

Quoted 422 lines · Jiri Pirko

From: Jiri Pirko <[email protected]>

RFC v1 [1] posted CTLV together with its first user, the attestation subsystem. v2 posts them as two series: this one, and the attestation series, which applies on top of it and is posted alongside as

[PATCH RFC v2 0/9] attestation: Add a common subsystem and TDX support

CTLV is a schema-driven TLV uAPI on a character device, meant for uAPIs too unconstrained for fixed structures: lists of records, nested and variable-sized data, optional fields. Every request is checked against the family's YAML schema before the driver sees it, and the UAPI header, the bindings and the docs are generated from the same schema. A family grows without versions, by new ops and optional fields. One ioctl over a global number space lets strace or a seccomp supervisor decode any family, and a query whose answer is larger than the caller's buffer is answered in parts, with a cursor and a generation that keep them consistent.

An ioctl with structures of its own fixes their layout, needs pointers to more structures for variable data, and has to be validated and decoded on its own. sysfs and configfs would assemble one request through several files, where CTLV checks and executes it at once. Netlink is built around sockets and network namespaces, while these devices want an fd and the DAC model of a device node, and it was turned down for the TSM's SPDM uAPI [2]. For a value or two, sysfs or a plain ioctl stays simpler, and CTLV is not meant for that.

The uAPI is one ioctl on the device's fd:

  struct ctlv_op_exec {
          __u32 size;
          __u32 flags;
          __aligned_u64 op_id;
          __aligned_u64 request;
          __aligned_u64 reply;
          __u32 request_len;
          __u32 reply_len;
          __aligned_u64 generation;
          __aligned_u64 cursor;
  };

  ioctl(fd, CTLV_IOC_OP_EXEC, &exec);

An op is an action, executed once, or a query, which the generation and the cursor carry across replies. Each op needs read or read-write access, checked against the mode the device was opened with. A failed op returns an errno, and in the reply buffer why the request was refused and the offset of the offending TLV.

A family is specified in YAML. The root family, which every device answers, lets a program not compiled against a family discover it. Its first op:

ops:
# The families this device answers, this one first and the device family # last. The only names any reply of this family carries. family-get:
type: query
fd-access: read
reply:
# One entry per family of the chain.
families[]:
# The family ID, which bits 63..48 of the family's types carry.
id: uint
# The registry name, also what a uevent carries. Bounded here, this # being the only place a message carries a family name.
name: string(..63)

ctlvgen --signatures prints a family's ops as calls, ? marking what may be absent and [] what may repeat. The root family's three, with the purpose of each:

# The device's family chain, root first.
family-get() -> { families[]: { id, name } }

# Every op the device publishes, with its type, access and lengths. op-get() ->

      { ops[]: { id, type, availability?, disabled?, request-max-len?,
                 action-reply-max-len?, query-reply-min-len?,
                 query-reply-suggested-len?, fd-access?, error-info-max-len? } }

# The tree of one op's request and reply. op-schema-get(id) -> { request?: schema-node, reply?: schema-node }

libctlv is a small C library for the mechanical parts: opening a device by its family, building requests, parsing replies, reassembling queries and building blob descriptors, with typed bindings generated per family. ctlvctl needs no generated code, only the family's specification, or the .json the build writes from it, for the names. Both build with the kernel's CROSS_COMPILE, LLVM and O=. Here they run in a VM, on a device of the simulation provider from the branch [3], with CTLV_SPEC_DIR pointing at Documentation/ctlv/specs. The device's MR 1 can be extended, and its evidence object 2 is an event log:

# Every CTLV device and its family chain.

  $ ctlvctl list
  attestation/attestation0        ctlv/ctlv-attestation/ctlv-attestation-sim

# The ops the device publishes.

  $ ctlvctl ops attestation/attestation0
  # ctlv/ctlv-attestation/ctlv-attestation-sim, generation 0
  family-get     query   read        fixed  request 16    reply 112..65536
  op-get         query   read        fixed  request 16    reply 56..65536
  op-schema-get  query   read        fixed  request 40    reply 168..65536
  ...
  mr-read        query   read        fixed  request 80    reply 112..4096
  mr-extend      action  read-write  fixed  request 7232  reply 2824
  ...

# mr-read's request and reply.

  $ ctlvctl schema attestation/attestation0 mr-read
  mr-read (query)
  request:
    root record
      mr-read id required uint [0, 4294967295]
      device-generation optional uint [0, 4294967295]
      mr-read options optional record
  reply:
    root record
      device-generation required uint [0, 4294967295]
      mr-generation required uint [0, 4294967295]
      mr-values required record x23
        mr-value.hash-algo required enum [0, 22] {HASH_ALGO_MD4, ...}
        mr-value.data required binary len [16, 64]

# MR 1's banks.

  $ ctlvctl exec attestation/attestation0 mr-read id=1
  # mr-read, 1 fragment, generation 0
    device-generation 0
    mr-generation 2
    mr-values
      mr-value.hash-algo HASH_ALGO_SHA256
      mr-value.data hex:0000000000000000000000000000000000000000000000000000000000000000
    mr-values
      mr-value.hash-algo HASH_ALGO_SHA384
      mr-value.data hex:000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

# Extend MR 1 by a digest for each of its banks.

  $ ctlvctl exec attestation/attestation0 mr-extend --json '{"id":1,
          "mr-values":[
            {"hash-algo":"HASH_ALGO_SHA256","data":"hex:b1a3c4fc2b10743a5f79ce443178df6e99b4426fcae2ef3e1f76a6a26d8f0860"},
            {"hash-algo":"HASH_ALGO_SHA384","data":"hex:c8a6d5e64f03a5f3cad5125670fccff0c065a9db91f00a81eb6630836629a85969802308430aa28ea0d6fdd8b1eb0cc8"}]}'
  # mr-extend, 1 fragment, generation 0
    device-generation 0
    mr-generation 3
    mr-values
      mr-value.hash-algo HASH_ALGO_SHA256
      mr-value.data hex:b1a3c4fc2b10743a5f79ce443178df6e99b4426fcae2ef3e1f76a6a26d8f0860
    mr-values
      mr-value.hash-algo HASH_ALGO_SHA384
      mr-value.data hex:c8a6d5e64f03a5f3cad5125670fccff0c065a9db91f00a81eb6630836629a85969802308430aa28ea0d6fdd8b1eb0cc8

# MR 1 again, with its new value and generation.

  $ ctlvctl exec attestation/attestation0 mr-read id=1
  # mr-read, 1 fragment, generation 1
    device-generation 0
    mr-generation 3
    mr-values
      mr-value.hash-algo HASH_ALGO_SHA256
      mr-value.data hex:a4fb91fd25115ec617cc4f17a40590e685cc58de5a65bb119e821e09d780a158
    mr-values
      mr-value.hash-algo HASH_ALGO_SHA384
      mr-value.data hex:1dcbf559ca9d6b48d782d268933c07a9e33c96bb21e1b868c2db7be929a852d3c5dbc5cf44427400c268a2f557c38c75
  # The event log, an output blob, written to a file.
  $ ctlvctl exec attestation/attestation0 evidence-get --json \
          '{"objects":[{"id":2,"data":{"file":"log.bin"}}]}'
  # evidence-get, 1 fragment, generation 0
    device-generation 0
    evidence-get evidence-generation 1
    evidence-get results
      evidence-get results.format ccel
      evidence-get results.length 65

There are no versions. struct ctlv_op_exec carries its size and grows only at its end. A family grows by new ops and new optional fields, and anything incompatible is a new op. Each family has a checked-in ABI snapshot, and regen refuses a change that breaks it.

Events, a per-fd queue of what changed on a device, are left out until their first user is posted, and so are memfd and dma-buf blobs. Both are on the branch [3], with the generator's tests, KUnit, test families and selftests.

The series adds 23787 lines:

  generator, Python                 7864
  core, C                           5643
  ctlvctl                           3519
  libctlv                           3242
  docs                              1510
  generated files                   1161
  meta-schemas, registry             368
  root family specification          211
  ABI snapshots                      118
  build                              151

Changes since RFC v1, each patch listing its own:

- Specs are written as Jason suggested: enums, flags, records and ops, each op the tree of its request and reply, every type derived from where its field sits. Attribute groups and sets are gone. The comment above an item is its doc, in the UAPI headers and the rendered docs, and ctlvgen --signatures prints the ops as above.
- TLV, type, record and field replace attr and nest.
- The events are left out, with read() and poll().
- A subsystem allocates its device and embeds CTLV, as fwctl does, and may route the ioctl from its own file operations. The engine is in lib/ctlv/, and a subsystem's class gets its nodes from CTLV, and there is no ctlv class.
- struct ctlv_op_exec is sized by its size field and read with copy_struct_from_user(). A reply buffer may be any length, and an output blob too short fails with EMSGSIZE and the length it needs.
- Enum extension points: an enum whose values a descendant family gives.
- An op that reads is <object>-get: families-dump and ops-dump are family-get and op-get.
- Inline messages are at most 64 KiB, and records nest at most 8 deep.
- The UAPI headers are in include/uapi/ctlv/.
- regen writes the ABI snapshots too, and refuses an ABI break unless ABI_BREAK=1.
- The userspace ABI opens with the goals, a worked example and a glossary, and collects the compatibility rules. The family guide is built around a worked example family.
- libctlv and ctlvctl are posted. ctlvctl runs every op with exec, takes a blob in --json as a file, as Aneesh's patched copy did, and sizes an output blob by the length the op fails with.

The patches:

1-3 the spec language and generator, the message format and the
family API, and the root family

  4      the userspace ABI
  5-11   messages, blobs, validation and introspection, then dispatch
  12     character device nodes
  13     how to write a family
  14-15  libctlv and ctlvctl

Note to reviewers: the uAPI, in 1, 2 and 4, and the family API, in 2 and 13, matter most at this stage.

[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/[email protected]/
[3] https://github.com/jpirko/linux_mlxsw/commits/wip_attestation_all_2

Jiri Pirko (15):
ctlv: Add the schema language and generator
ctlv: Add the UAPI message format and family API
ctlv: Add the root family specification and generated files
Documentation: ctlv: Add userspace ABI
ctlv: Prepare message input handling
ctlv: Prepare blob descriptor validation
ctlv: Prepare schema validation
ctlv: Prepare message output handling
ctlv: Prepare VA blob handling
ctlv: Prepare runtime introspection
ctlv: Add operation dispatch
ctlv: Add character device nodes
Documentation: ctlv: Describe how to write a family tools/ctlv: Add the userspace library
tools/ctlv: Add ctlvctl

 Documentation/ctlv/abi/ctlv.yaml              |  111 +
 Documentation/ctlv/abi/families.registry.yaml |    7 +
 Documentation/ctlv/ctlv-registry-schema.yaml  |   38 +
 Documentation/ctlv/ctlv-schema.yaml           |  227 ++
 Documentation/ctlv/families.yaml              |   17 +
 .../ctlv/generated-files-schema.yaml          |   68 +
 Documentation/ctlv/generated-files.yaml       |   18 +
 Documentation/ctlv/specs/ctlv.yaml            |  211 ++
 Documentation/driver-api/ctlv.rst             |  723 +++++
 Documentation/driver-api/index.rst            |    1 +
 Documentation/userspace-api/ctlv.rst          |  783 +++++
 Documentation/userspace-api/index.rst         |    1 +
 .../userspace-api/ioctl/ioctl-number.rst      |    2 +
 MAINTAINERS                                   |   12 +
 include/linux/ctlv.h                          |  149 +
 include/linux/ctlv_device.h                   |   57 +
 include/linux/ctlv_family.h                   |  652 ++++
 include/linux/ctlv_gen.h                      |  154 +
 include/uapi/ctlv/ctlv.h                      |  180 ++
 include/uapi/ctlv/ctlv_families_gen.h         |   17 +
 include/uapi/ctlv/ctlv_gen.h                  |  278 ++
 lib/Kconfig                                   |    2 +
 lib/Makefile                                  |    2 +
 lib/ctlv/Kconfig                              |   13 +
 lib/ctlv/Makefile                             |    5 +
 lib/ctlv/blob.c                               |  421 +++
 lib/ctlv/blob.h                               |   15 +
 lib/ctlv/blob_desc.c                          |  101 +
 lib/ctlv/blob_desc.h                          |   29 +
 lib/ctlv/builder.c                            |  455 +++
 lib/ctlv/builder.h                            |   14 +
 lib/ctlv/core.c                               | 1169 +++++++
 lib/ctlv/ctlv_gen.c                           |  161 +
 lib/ctlv/device.c                             |  179 ++
 lib/ctlv/internal.h                           |   87 +
 lib/ctlv/introspection.c                      |  505 +++
 lib/ctlv/message.c                            |  393 +++
 lib/ctlv/message.h                            |   91 +
 lib/ctlv/schema.c                             | 1092 +++++++
 lib/ctlv/schema.h                             |   54 +
 tools/Makefile                                |    9 +-
 tools/ctlv/Makefile                           |   62 +
 tools/ctlv/ctlv-regen.sh                      |   64 +
 tools/ctlv/ctlvctl/.gitignore                 |    4 +
 tools/ctlv/ctlvctl/Makefile                   |   64 +
 tools/ctlv/ctlvctl/ctlvctl.c                  | 2787 +++++++++++++++++
 tools/ctlv/ctlvctl/spec.c                     |  672 ++++
 tools/ctlv/ctlvctl/spec.h                     |   60 +
 tools/ctlv/ctlvgen/__init__.py                |    1 +
 tools/ctlv/ctlvgen/cli.py                     |  178 ++
 tools/ctlv/ctlvgen/lib/__init__.py            |    1 +
 tools/ctlv/ctlvgen/lib/cenum.py               |  178 ++
 tools/ctlv/ctlvgen/lib/cgen.py                |  763 +++++
 tools/ctlv/ctlvgen/lib/compat.py              |  877 ++++++
 tools/ctlv/ctlvgen/lib/dump.py                |  161 +
 tools/ctlv/ctlvgen/lib/errors.py              |   16 +
 tools/ctlv/ctlvgen/lib/gen_doc.py             |  684 ++++
 tools/ctlv/ctlvgen/lib/gen_family.py          |  285 ++
 tools/ctlv/ctlvgen/lib/gen_kernel.py          |  576 ++++
 tools/ctlv/ctlvgen/lib/gen_runtime.py         |   66 +
 tools/ctlv/ctlvgen/lib/gen_uapi.py            |  182 ++
 tools/ctlv/ctlvgen/lib/gen_user.py            |  808 +++++
 tools/ctlv/ctlvgen/lib/outputs.py             |  363 +++
 tools/ctlv/ctlvgen/lib/semantics.py           | 1219 +++++++
 tools/ctlv/ctlvgen/lib/sizes.py               |  239 ++
 tools/ctlv/ctlvgen/lib/spec.py                |  813 +++++
 tools/ctlv/ctlvgen/lib/tree.py                |  158 +
 tools/ctlv/ctlvgen/lib/yamlload.py            |  138 +
 tools/ctlv/libctlv/Makefile                   |   41 +
 tools/ctlv/libctlv/ctlv.h                     |  413 +++
 tools/ctlv/libctlv/ctlv_user_gen.c            |  551 ++++
 tools/ctlv/libctlv/device.c                   |  412 +++
 tools/ctlv/libctlv/internal.h                 |  161 +
 tools/ctlv/libctlv/introspection.c            |  238 ++
 tools/ctlv/libctlv/message.c                  |  518 +++
 tools/ctlv/libctlv/schema.c                   |  742 +++++
 tools/ctlv/libctlv/spec.c                     |  186 ++
 tools/ctlv/libctlv/transport.c                |  572 ++++
 tools/ctlv/pyproject.toml                     |   30 +
 tools/ctlv/requirements.txt                   |    2 +
 80 files changed, 23787 insertions(+), 1 deletion(-)
 create mode 100644 Documentation/ctlv/abi/ctlv.yaml
 create mode 100644 Documentation/ctlv/abi/families.registry.yaml
 create mode 100644 Documentation/ctlv/ctlv-registry-schema.yaml
 create mode 100644 Documentation/ctlv/ctlv-schema.yaml
 create mode 100644 Documentation/ctlv/families.yaml
 create mode 100644 Documentation/ctlv/generated-files-schema.yaml
 create mode 100644 Documentation/ctlv/generated-files.yaml
 create mode 100644 Documentation/ctlv/specs/ctlv.yaml
 create mode 100644 Documentation/driver-api/ctlv.rst
 create mode 100644 Documentation/userspace-api/ctlv.rst
 create mode 100644 include/linux/ctlv.h
 create mode 100644 include/linux/ctlv_device.h
 create mode 100644 include/linux/ctlv_family.h
 create mode 100644 include/linux/ctlv_gen.h
 create mode 100644 include/uapi/ctlv/ctlv.h
 create mode 100644 include/uapi/ctlv/ctlv_families_gen.h
 create mode 100644 include/uapi/ctlv/ctlv_gen.h
 create mode 100644 lib/ctlv/Kconfig
 create mode 100644 lib/ctlv/Makefile
 create mode 100644 lib/ctlv/blob.c
 create mode 100644 lib/ctlv/blob.h
 create mode 100644 lib/ctlv/blob_desc.c
 create mode 100644 lib/ctlv/blob_desc.h
 create mode 100644 lib/ctlv/builder.c
 create mode 100644 lib/ctlv/builder.h
 create mode 100644 lib/ctlv/core.c
 create mode 100644 lib/ctlv/ctlv_gen.c
 create mode 100644 lib/ctlv/device.c
 create mode 100644 lib/ctlv/internal.h
 create mode 100644 lib/ctlv/introspection.c
 create mode 100644 lib/ctlv/message.c
 create mode 100644 lib/ctlv/message.h
 create mode 100644 lib/ctlv/schema.c
 create mode 100644 lib/ctlv/schema.h
 create mode 100644 tools/ctlv/Makefile
 create mode 100755 tools/ctlv/ctlv-regen.sh
 create mode 100644 tools/ctlv/ctlvctl/.gitignore
 create mode 100644 tools/ctlv/ctlvctl/Makefile
 create mode 100644 tools/ctlv/ctlvctl/ctlvctl.c
 create mode 100644 tools/ctlv/ctlvctl/spec.c
 create mode 100644 tools/ctlv/ctlvctl/spec.h
 create mode 100644 tools/ctlv/ctlvgen/__init__.py
 create mode 100755 tools/ctlv/ctlvgen/cli.py
 create mode 100644 tools/ctlv/ctlvgen/lib/__init__.py
 create mode 100644 tools/ctlv/ctlvgen/lib/cenum.py
 create mode 100644 tools/ctlv/ctlvgen/lib/cgen.py
 create mode 100644 tools/ctlv/ctlvgen/lib/compat.py
 create mode 100644 tools/ctlv/ctlvgen/lib/dump.py
 create mode 100644 tools/ctlv/ctlvgen/lib/errors.py
 create mode 100644 tools/ctlv/ctlvgen/lib/gen_doc.py
 create mode 100644 tools/ctlv/ctlvgen/lib/gen_family.py
 create mode 100644 tools/ctlv/ctlvgen/lib/gen_kernel.py
 create mode 100644 tools/ctlv/ctlvgen/lib/gen_runtime.py
 create mode 100644 tools/ctlv/ctlvgen/lib/gen_uapi.py
 create mode 100644 tools/ctlv/ctlvgen/lib/gen_user.py
 create mode 100644 tools/ctlv/ctlvgen/lib/outputs.py
 create mode 100644 tools/ctlv/ctlvgen/lib/semantics.py
 create mode 100644 tools/ctlv/ctlvgen/lib/sizes.py
 create mode 100644 tools/ctlv/ctlvgen/lib/spec.py
 create mode 100644 tools/ctlv/ctlvgen/lib/tree.py
 create mode 100644 tools/ctlv/ctlvgen/lib/yamlload.py
 create mode 100644 tools/ctlv/libctlv/Makefile
 create mode 100644 tools/ctlv/libctlv/ctlv.h
 create mode 100644 tools/ctlv/libctlv/ctlv_user_gen.c
 create mode 100644 tools/ctlv/libctlv/device.c
 create mode 100644 tools/ctlv/libctlv/internal.h
 create mode 100644 tools/ctlv/libctlv/introspection.c
 create mode 100644 tools/ctlv/libctlv/message.c
 create mode 100644 tools/ctlv/libctlv/schema.c
 create mode 100644 tools/ctlv/libctlv/spec.c
 create mode 100644 tools/ctlv/libctlv/transport.c
 create mode 100644 tools/ctlv/pyproject.toml
 create mode 100644 tools/ctlv/requirements.txt
Signature · 1 line
2.56.0
Signature · 2 lines
Sincerely,
Yeoreum Yun