AI Trajectory


Trajectory: (Expand/Collapse All)
Seq Timestamp Type Name Duration
0/0 2026/10/15 19:11 flow patch-triage
4m Args:
null

Results:
{
  "EnableConfigs": null,
  "FocusSymbols": [],
  "KMSANReasoning": "",
  "NeedsKMSAN": false,
  "Reasoning": "The patch series introduces the CTLV subsystem (character device TLV UAPI transport), an Attestation subsystem, and an Intel TDX attestation provider. The only provider implemented for CTLV/Attestation that calls ctlv_create() to instantiate character devices (/dev/ctlv*) is the TDX attestation provider. However, the TDX provider depends on the TDX guest driver (drivers/virt/coco/tdx-guest/tdx-guest.c), which strictly requires Intel Trust Domain Extensions hardware support (X86_FEATURE_TDX_GUEST) and exits with -ENODEV in tdx_guest_init() when running in standard virtualized environments (standard QEMU or GCE). Because no TDX hardware is present, tdx_guest_client_attach() is never called, ctlv_create() is never invoked, and no CTLV character devices can ever be created or opened by userspace. Consequently, all newly added CTLV and attestation operational logic is structurally unreachable in standard fuzzing environments.",
  "WorthFuzzing": false
}

1/1 2026/10/15 19:11 action read-patch-diff
0m Args:
null

Results:
{
  "PatchDiff": "commit f1fe376af05c53e6ada5d982f65c56cf65f0ef29\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate:   Thu Oct 15 19:11:08 2026 +0000\n\n    syz-cluster: applied patch under review\n\ndiff --git a/Documentation/ctlv/abi/ctlv-attestation-tdx.yaml b/Documentation/ctlv/abi/ctlv-attestation-tdx.yaml\nnew file mode 100644\nindex 0000000000000..89b80d84e7f1a\n--- /dev/null\n+++ b/Documentation/ctlv/abi/ctlv-attestation-tdx.yaml\n@@ -0,0 +1,22 @@\n+# SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)\n+%YAML 1.2\n+---\n+# Checked-in ABI snapshot of the ctlv-attestation-tdx family, written by\n+# \"make -C tools/ctlv abi-update\".\n+#\n+# The checker compares this family's declarations and inherited stub fills\n+# against this file. Updating it is how a UAPI change gets reviewed; an update\n+# that removes or renumbers anything, narrows a bound, or makes a placement\n+# required is an ABI break, whatever this file says afterwards.\n+family: {name: ctlv-attestation-tdx, id: 2, inherits: ctlv-attestation,\n+         pre-init: true}\n+attr-groups:\n+  info:\n+    id: 1\n+    attrs:\n+      mrconfigid: {id: 1, type: binary, length: 48}\n+      mrowner: {id: 2, type: binary, length: 48}\n+      mrownerconfig: {id: 3, type: binary, length: 48}\n+fills:\n+  device-info:\n+    attrs: [info.mrconfigid, info.mrowner, info.mrownerconfig]\ndiff --git a/Documentation/ctlv/abi/ctlv-attestation.yaml b/Documentation/ctlv/abi/ctlv-attestation.yaml\nnew file mode 100644\nindex 0000000000000..a857e5ce00394\n--- /dev/null\n+++ b/Documentation/ctlv/abi/ctlv-attestation.yaml\n@@ -0,0 +1,184 @@\n+# SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)\n+%YAML 1.2\n+---\n+# Checked-in ABI snapshot of the ctlv-attestation family, written by\n+# \"make -C tools/ctlv abi-update\".\n+#\n+# The checker compares this family's declarations and inherited stub fills\n+# against this file. Updating it is how a UAPI change gets reviewed; an update\n+# that removes or renumbers anything, narrows a bound, or makes a placement\n+# required is an ABI break, whatever this file says afterwards.\n+family: {name: ctlv-attestation, id: 1, inherits: ctlv, post-init: true,\n+         pre-fini: true}\n+enums:\n+  evidence-representation: {raw: 1}\n+  evidence-blob-class: {primary: 1}\n+  mr-log-event: {info: 1, extend: 2}\n+flags:\n+  mr-device-caps: {read: 0, extend: 1}\n+  mr-caps: {read: 0, extend: 1}\n+attr-groups:\n+  device:\n+    id: 1\n+    attrs:\n+      generation: {id: 1, type: uint, max: 4294967295}\n+      caps: {id: 2, type: nested}\n+      info: {id: 3, type: nested}\n+  cap:\n+    id: 2\n+    attrs:\n+      evidence: {id: 1, type: nested}\n+      mr: {id: 2, type: nested}\n+      min-challenge-length: {id: 3, type: uint}\n+      max-challenge-length: {id: 4, type: uint}\n+      max-total-output-length: {id: 5, type: uint}\n+      mr-flags: {id: 6, flags: mr-device-caps}\n+      object: {id: 7, type: nested, max-occurrences: 16}\n+      blob-class: {id: 8, enum: evidence-blob-class}\n+      format: {id: 9, type: string, min-length: 1, max-length: 128}\n+      representation: {id: 10, enum: evidence-representation}\n+      max-length: {id: 11, type: uint}\n+  evidence:\n+    id: 3\n+    attrs:\n+      challenge: {id: 1, type: binary, max-length: 4096}\n+      object: {id: 2, type: nested, max-occurrences: 16}\n+      blob-class: {id: 3, enum: evidence-blob-class}\n+      format: {id: 4, type: string, min-length: 1, max-length: 128}\n+      representation: {id: 5, enum: evidence-representation}\n+      data: {id: 6, blob: output, backings: [va], max-length: 4294967295}\n+      object-length: {id: 7, type: uint, max-occurrences: 16}\n+  mr:\n+    id: 4\n+    attrs:\n+      id: {id: 1, type: uint, max: 4294967295}\n+      name: {id: 2, type: string, min-length: 1, max-length: 128}\n+      hash-algo: {id: 3, type: uint, max: 20}\n+      supported-hash-algo: {id: 4, type: uint, max: 20, max-occurrences: 21}\n+      register-index: {id: 5, type: uint, max: 4294967295}\n+      caps: {id: 6, flags: mr-caps}\n+      item: {id: 7, type: nested, max-occurrences: unlimited}\n+      value: {id: 8, type: nested, max-occurrences: 21}\n+      data: {id: 9, type: binary, min-length: 16, max-length: 64}\n+      generation: {id: 10, type: uint, max: 4294967295}\n+      selection: {id: 11, type: nested, max-occurrences: 256}\n+      start-generation: {id: 12, type: uint, max: 4294967295}\n+      end-generation: {id: 13, type: uint, max: 4294967295}\n+  log:\n+    id: 5\n+    attrs:\n+      entry: {id: 1, type: nested, max-occurrences: unlimited}\n+      event: {id: 2, enum: mr-log-event}\n+      mr: {id: 3, type: nested}\n+  notification:\n+    id: 6\n+    attrs:\n+      entry: {id: 1, type: nested}\n+attr-sets:\n+  device-info: {id: 1, stub: true}\n+  evidence-object-cap: {id: 2}\n+  evidence-cap: {id: 3}\n+  mr-device-cap: {id: 4}\n+  device-caps: {id: 5}\n+  device-reply: {id: 6}\n+  evidence-object-request: {id: 7}\n+  evidence-request: {id: 8}\n+  evidence-reply: {id: 9}\n+  mr-props: {id: 10}\n+  mr-dump-entry: {id: 11}\n+  mr-id-request: {id: 12}\n+  mr-read-request: {id: 13}\n+  mr-value: {id: 14}\n+  mr-read-reply: {id: 15}\n+  mr-extend-request: {id: 16}\n+  mr-change-reply: {id: 17}\n+  mr-log-info: {id: 18}\n+  mr-log-entry: {id: 19}\n+  mr-log-event: {id: 20}\n+  mr-log-selection: {id: 21}\n+  mr-log-request: {id: 22}\n+  mr-log-reply: {id: 23}\n+ops:\n+  device-get:\n+    abi: {id: 1, type: action, fd-access: read}\n+    reply:\n+      attrs:\n+        - device.caps:\n+            optional-attrs:\n+              - cap.evidence:\n+                  attrs:\n+                    - cap.min-challenge-length\n+                    - cap.max-challenge-length\n+                    - cap.max-total-output-length\n+                    - cap.object:\n+                        attrs: [cap.blob-class, cap.format, cap.representation,\n+                                cap.max-length]\n+              - cap.mr: {attrs: [cap.mr-flags]}\n+        - device.info: {attrs: [device-info]}\n+  evidence-get:\n+    abi: {id: 2, type: action, availability: dynamic, optional: true}\n+    request:\n+      attrs:\n+        - evidence.challenge\n+        - evidence.object:\n+            attrs: [evidence.blob-class, evidence.format,\n+                    evidence.representation, evidence.data]\n+    reply:\n+      attrs: [evidence.object-length]\n+      optional-attrs: [mr.generation]\n+  mr-get:\n+    abi: {id: 3, type: action, fd-access: read, optional: true}\n+    request: {attrs: [mr.id]}\n+    reply:\n+      attrs: [mr.name, mr.supported-hash-algo, mr.caps]\n+      optional-attrs: [mr.register-index]\n+  mr-dump:\n+    abi: {id: 4, type: query, fd-access: read, optional: true}\n+    reply:\n+      attrs:\n+        - mr.item:\n+            attrs: [mr.id, mr.name, mr.supported-hash-algo, mr.caps]\n+            optional-attrs: [mr.register-index]\n+  mr-read:\n+    abi: {id: 5, type: query, fd-access: read, optional: true}\n+    request: {attrs: [mr.id]}\n+    reply:\n+      attrs:\n+        - mr.generation\n+        - mr.value: {attrs: [mr.hash-algo, mr.data]}\n+  mr-extend:\n+    abi: {id: 6, type: action, optional: true}\n+    request:\n+      attrs:\n+        - mr.id\n+        - mr.value: {attrs: [mr.hash-algo, mr.data]}\n+    reply: {attrs: [mr.generation]}\n+  mr-log-entry-appended:\n+    abi: {id: 7, type: event}\n+    reply:\n+      attrs:\n+        - notification.entry:\n+            attrs: [mr.generation, mr.id, log.event]\n+            optional-attrs:\n+              - mr.value: {attrs: [mr.hash-algo, mr.data]}\n+              - log.mr:\n+                  attrs: [mr.name, mr.supported-hash-algo, mr.caps]\n+                  optional-attrs: [mr.register-index]\n+  mr-log-get:\n+    abi: {id: 8, type: query, fd-access: read, optional: true}\n+    request:\n+      optional-attrs:\n+        - mr.selection: {attrs: [mr.id]}\n+        - mr.start-generation\n+        - mr.end-generation\n+    reply:\n+      optional-attrs:\n+        - mr.start-generation\n+        - mr.end-generation\n+        - log.entry:\n+            attrs: [mr.generation, mr.id, log.event]\n+            optional-attrs:\n+              - mr.value: {attrs: [mr.hash-algo, mr.data]}\n+              - log.mr:\n+                  attrs: [mr.name, mr.supported-hash-algo, mr.caps]\n+                  optional-attrs: [mr.register-index]\ndiff --git a/Documentation/ctlv/abi/ctlv.yaml b/Documentation/ctlv/abi/ctlv.yaml\nnew file mode 100644\nindex 0000000000000..fa11bce98f462\n--- /dev/null\n+++ b/Documentation/ctlv/abi/ctlv.yaml\n@@ -0,0 +1,186 @@\n+# SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)\n+%YAML 1.2\n+---\n+# Checked-in ABI snapshot of the ctlv family, written by\n+# \"make -C tools/ctlv abi-update\".\n+#\n+# The checker compares this family's declarations and inherited stub fills\n+# against this file. Updating it is how a UAPI change gets reviewed; an update\n+# that removes or renumbers anything, narrows a bound, or makes a placement\n+# required is an ABI break, whatever this file says afterwards.\n+family: {name: ctlv, id: 0}\n+enums:\n+  op-type: {action: 1, query: 2, event: 3}\n+  op-availability: {fixed: 1, dynamic: 2}\n+  blob-type: {va: 1}\n+  blob-direction: {input: 1, output: 2, inout: 3}\n+  validation-reason: {malformed-message: 1, unknown-attr: 2, unknown-flag: 3,\n+                      nesting-too-deep: 4, missing-attr: 5,\n+                      too-many-occurrences: 6, value-out-of-range: 7,\n+                      bad-length: 8, bad-string: 9, bad-blob-descriptor: 10,\n+                      stale-generation: 11, noncontiguous-attr: 12}\n+  op-fd-access: {read: 1, read-write: 2}\n+attr-groups:\n+  family:\n+    id: 1\n+    attrs:\n+      id: {id: 1, type: uint}\n+      name: {id: 2, type: string, max-length: 63}\n+      entry: {id: 3, type: nested, max-occurrences: unlimited}\n+  blob:\n+    id: 2\n+    attrs:\n+      type: {id: 1, enum: blob-type}\n+      address: {id: 2, type: uint}\n+      fd: {id: 3, type: uint, max: 2147483647}\n+      offset: {id: 4, type: uint}\n+      length: {id: 5, type: uint, min: 1}\n+  error:\n+    id: 3\n+    attrs:\n+      reason: {id: 1, enum: validation-reason}\n+      message: {id: 2, type: string, max-length: 255}\n+      bad-attr-offset: {id: 3, type: uint}\n+      nest-offset: {id: 4, type: uint}\n+      missing-attr-id: {id: 5, type: uint}\n+      expected-generation: {id: 6, type: uint}\n+      current-generation: {id: 7, type: uint}\n+  op:\n+    id: 4\n+    attrs:\n+      id: {id: 1, type: uint, min: 1}\n+      type: {id: 2, enum: op-type}\n+      availability: {id: 3, enum: op-availability}\n+      disabled: {id: 4, type: bool}\n+      request-max-len: {id: 5, type: uint}\n+      action-reply-max-len: {id: 6, type: uint}\n+      query-reply-min-len: {id: 7, type: uint}\n+      query-reply-suggested-len: {id: 8, type: uint}\n+      event-record-max-len: {id: 9, type: uint}\n+      state-generation: {id: 10, type: uint}\n+      entry: {id: 11, type: nested, max-occurrences: unlimited}\n+      fd-access: {id: 12, enum: op-fd-access}\n+  schema:\n+    id: 5\n+    attrs:\n+      attr-id: {id: 1, type: uint}\n+      kind: {id: 2, type: uint}\n+      max-occurrences: {id: 3, type: uint}\n+      min: {id: 4, type: uint}\n+      max: {id: 5, type: uint}\n+      min-length: {id: 6, type: uint}\n+      max-length: {id: 7, type: uint}\n+      flags-mask: {id: 8, type: uint}\n+      unit: {id: 9, type: uint}\n+      scale: {id: 10, type: sint}\n+      blob-direction: {id: 11, enum: blob-direction}\n+      blob-backings: {id: 12, type: uint}\n+      blob-max-length: {id: 13, type: uint}\n+      blob-alignment: {id: 14, type: uint}\n+      reenters: {id: 15, type: uint, min: 1}\n+      attrs: {id: 16, type: nested, max-occurrences: unlimited}\n+      optional-attrs: {id: 17, type: nested, max-occurrences: unlimited}\n+      request: {id: 18, type: nested}\n+      reply: {id: 19, type: nested}\n+  event:\n+    id: 6\n+    attrs:\n+      op-id: {id: 1, type: uint, min: 1, max-occurrences: 256}\n+      queue-len: {id: 2, type: uint, min: 1, max: 16777216, unit: bytes}\n+      queue-used: {id: 3, type: uint, unit: bytes}\n+      first-sequence: {id: 4, type: uint}\n+      last-sequence: {id: 5, type: uint}\n+      dropped-count: {id: 6, type: uint}\n+attr-sets:\n+  family-entry: {id: 1}\n+  op-entry: {id: 2}\n+  op-schema-request: {id: 3}\n+  schema-node: {id: 4}\n+  op-schema-info: {id: 5}\n+  op-change-info: {id: 6}\n+  error-info: {id: 7}\n+  event-subscription: {id: 8}\n+  event-queue-limit: {id: 9}\n+  event-queue-state: {id: 10}\n+  event-overflow-info: {id: 11}\n+ops:\n+  families-dump:\n+    abi: {id: 1, type: query, fd-access: read}\n+    reply:\n+      attrs:\n+        - family.entry: {attrs: [family.id, family.name]}\n+  ops-dump:\n+    abi: {id: 2, type: query, fd-access: read}\n+    reply:\n+      attrs:\n+        - op.entry:\n+            attrs: [op.id, op.type]\n+            optional-attrs: [op.availability, op.disabled, op.request-max-len,\n+                             op.action-reply-max-len, op.query-reply-min-len,\n+                             op.query-reply-suggested-len,\n+                             op.event-record-max-len, op.fd-access]\n+  op-schema-get:\n+    abi: {id: 3, type: query, fd-access: read}\n+    request: {attrs: [op.id]}\n+    reply:\n+      optional-attrs:\n+        - schema.request:\n+            attrs: [schema.attr-id, schema.kind, schema.max-occurrences]\n+            optional-attrs:\n+              - schema.min\n+              - schema.max\n+              - schema.min-length\n+              - schema.max-length\n+              - schema.flags-mask\n+              - schema.unit\n+              - schema.scale\n+              - schema.blob-direction\n+              - schema.blob-backings\n+              - schema.blob-max-length\n+              - schema.blob-alignment\n+              - schema.reenters\n+              - schema.attrs:\n+                  reenters: schema-node\n+              - schema.optional-attrs:\n+                  reenters: schema-node\n+        - schema.reply:\n+            attrs: [schema.attr-id, schema.kind, schema.max-occurrences]\n+            optional-attrs:\n+              - schema.min\n+              - schema.max\n+              - schema.min-length\n+              - schema.max-length\n+              - schema.flags-mask\n+              - schema.unit\n+              - schema.scale\n+              - schema.blob-direction\n+              - schema.blob-backings\n+              - schema.blob-max-length\n+              - schema.blob-alignment\n+              - schema.reenters\n+              - schema.attrs:\n+                  reenters: schema-node\n+              - schema.optional-attrs:\n+                  reenters: schema-node\n+  subscriptions-add:\n+    abi: {id: 4, type: action, fd-access: read}\n+    request: {attrs: [event.op-id]}\n+  subscriptions-remove:\n+    abi: {id: 5, type: action, fd-access: read}\n+    request: {attrs: [event.op-id]}\n+  event-queue-get:\n+    abi: {id: 6, type: query, fd-access: read}\n+    reply: {attrs: [event.queue-len, event.queue-used]}\n+  event-queue-set:\n+    abi: {id: 7, type: action, fd-access: read}\n+    request: {attrs: [event.queue-len]}\n+  op-changed:\n+    abi: {id: 8, type: event}\n+    reply: {attrs: [op.id, op.disabled, op.state-generation]}\n+  event-overflow:\n+    abi: {id: 9, type: event}\n+    reply:\n+      attrs: [event.first-sequence, event.last-sequence, event.dropped-count]\n+  device-removed:\n+    abi: {id: 10, type: event}\n+    reply: {}\ndiff --git a/Documentation/ctlv/abi/families.registry.yaml b/Documentation/ctlv/abi/families.registry.yaml\nnew file mode 100644\nindex 0000000000000..193e3570ab959\n--- /dev/null\n+++ b/Documentation/ctlv/abi/families.registry.yaml\n@@ -0,0 +1,9 @@\n+# SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)\n+%YAML 1.2\n+---\n+# Checked-in ABI baseline of the ordered CTLV family registry.\n+# Updated deliberately by \"make -C tools/ctlv abi-update\".\n+families:\n+  - ctlv\n+  - ctlv-attestation\n+  - ctlv-attestation-tdx\ndiff --git a/Documentation/ctlv/ctlv-registry-schema.yaml b/Documentation/ctlv/ctlv-registry-schema.yaml\nnew file mode 100644\nindex 0000000000000..d9a2840fc230e\n--- /dev/null\n+++ b/Documentation/ctlv/ctlv-registry-schema.yaml\n@@ -0,0 +1,38 @@\n+# SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)\n+%YAML 1.2\n+---\n+$id: http://kernel.org/schemas/ctlv/ctlv-registry-schema.yaml#\n+$schema: https://json-schema.org/draft-07/schema\n+\n+$defs:\n+  name:\n+    type: string\n+    maxLength: 63\n+    pattern: ^[a-z0-9]+(-[a-z0-9]+)*$\n+\n+title: CTLV family registry\n+description: Append-only list of CTLV family names, indexed by family ID\n+type: object\n+required: [ families ]\n+additionalProperties: false\n+properties:\n+  families:\n+    description: |\n+      Family names in family ID order: the entry at index N has family ID N.\n+      The root family owns ID 0 and so is the first entry, and cannot be\n+      deprecated. Every other entry comes after the entry of the family it\n+      inherits. A deprecated entry keeps its ID reserved.\n+    type: array\n+    minItems: 1\n+    maxItems: 65536\n+    items:\n+      oneOf:\n+        - $ref: '#/$defs/name'\n+        - type: object\n+          required: [ name, deprecated ]\n+          additionalProperties: false\n+          properties:\n+            name:\n+              $ref: '#/$defs/name'\n+            deprecated:\n+              const: true\ndiff --git a/Documentation/ctlv/ctlv-schema.yaml b/Documentation/ctlv/ctlv-schema.yaml\nnew file mode 100644\nindex 0000000000000..38fd56e6627cc\n--- /dev/null\n+++ b/Documentation/ctlv/ctlv-schema.yaml\n@@ -0,0 +1,359 @@\n+# SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)\n+%YAML 1.2\n+---\n+$id: http://kernel.org/schemas/ctlv/ctlv-schema.yaml#\n+$schema: https://json-schema.org/draft-07/schema\n+\n+# The syntax gate for a CTLV family specification: permitted keys, their shapes\n+# and the closed sets of keywords. Anything needing more than one declaration at\n+# a time is checked by tools/ctlv/ctlvgen/lib/semantics.py.\n+\n+$defs:\n+  name:\n+    description: Kebab-case identifier. A dot is reserved for selectors.\n+    type: string\n+    pattern: ^[a-z0-9]+(-[a-z0-9]+)*$\n+\n+  family-name:\n+    description: Name carried by family discovery.\n+    allOf:\n+      - $ref: '#/$defs/name'\n+      - maxLength: 63\n+\n+  selector:\n+    description: |\n+      A named attr set, a whole attr group, or one exact attr as\n+      \"group.attr\". There are no tuple selectors and no cross-family\n+      qualification.\n+    type: string\n+    pattern: ^[a-z0-9]+(-[a-z0-9]+)*(\\.[a-z0-9]+(-[a-z0-9]+)*)?$\n+\n+  selectors:\n+    oneOf:\n+      - $ref: '#/$defs/selector'\n+      - type: array\n+        minItems: 1\n+        items:\n+          $ref: '#/$defs/selector'\n+\n+  uint:\n+    type: integer\n+    minimum: 0\n+    maximum: 4294967295\n+\n+  integer-bound:\n+    type: integer\n+    minimum: -9223372036854775808\n+    maximum: 18446744073709551615\n+\n+  max-occurrences:\n+    description: |\n+      A finite positive count, or unlimited, which is reachable only from\n+      query replies.\n+    oneOf:\n+      - type: integer\n+        minimum: 1\n+        maximum: 4294967295\n+      - const: unlimited\n+\n+  unit:\n+    description: CTLV-owned unit, matching enum ctlv_unit.\n+    enum: [ seconds, hertz, bytes, celsius ]\n+\n+  value-list:\n+    description: An enum or a flags definition.\n+    type: object\n+    required: [ name, values ]\n+    additionalProperties: false\n+    properties:\n+      name:\n+        $ref: '#/$defs/name'\n+      values:\n+        description: |\n+          Value names in declaration order. Enum values are numbered from 1\n+          because 0 is reserved; flag bits are numbered from bit 0. Both are\n+          append-only.\n+        type: array\n+        minItems: 1\n+        items:\n+          $ref: '#/$defs/name'\n+\n+  enum-list:\n+    allOf:\n+      - $ref: '#/$defs/value-list'\n+      - properties:\n+          values:\n+            maxItems: 4294967295\n+\n+  flags-list:\n+    allOf:\n+      - $ref: '#/$defs/value-list'\n+      - properties:\n+          values:\n+            maxItems: 64\n+\n+  blob:\n+    type: object\n+    required: [ direction, allowed-backings, max-length ]\n+    additionalProperties: false\n+    properties:\n+      direction:\n+        description: How the family may use the described memory.\n+        enum: [ input, output, inout ]\n+      allowed-backings:\n+        type: array\n+        minItems: 1\n+        uniqueItems: true\n+        items:\n+          enum: [ va ]\n+      max-length:\n+        description: |\n+          Authoritative maximum external payload length for this placement,\n+          independent of the inline message limit.\n+        type: integer\n+        minimum: 1\n+        maximum: 18446744073709551615\n+      alignment:\n+        description: Required alignment of the described address or offset.\n+        type: integer\n+        minimum: 1\n+        maximum: 4294967295\n+\n+  attr:\n+    description: |\n+      One attr declaration. Exactly one primary form out of type, enum,\n+      flags, attrs and blob must be present. optional-attrs and recursive\n+      may only accompany attrs.\n+    type: object\n+    required: [ name ]\n+    additionalProperties: false\n+    properties:\n+      name:\n+        $ref: '#/$defs/name'\n+      type:\n+        description: |\n+          Primitive payload. Integers are always 64-bit, and a bool is one\n+          byte holding zero or one.\n+        enum: [ uint, sint, bool, string, binary ]\n+      enum:\n+        description: Name of an enum definition; implies an unsigned payload.\n+        $ref: '#/$defs/name'\n+      flags:\n+        description: Name of a flags definition; implies an unsigned payload.\n+        $ref: '#/$defs/name'\n+      attrs:\n+        description: Nested payload, given as selectors.\n+        $ref: '#/$defs/selectors'\n+      optional-attrs:\n+        description: Further nested payload whose placements are optional.\n+        $ref: '#/$defs/selectors'\n+      recursive:\n+        description: |\n+          The nested payload is one attr set that may contain this attr\n+          again, describing a structure of any depth. Only a query reply can\n+          hold one, since such a nest has no maximum length.\n+        const: true\n+      blob:\n+        $ref: '#/$defs/blob'\n+      min:\n+        description: Inclusive minimum of an integer payload.\n+        $ref: '#/$defs/integer-bound'\n+      max:\n+        description: Inclusive maximum of an integer payload.\n+        $ref: '#/$defs/integer-bound'\n+      length:\n+        description: Exact payload length of a binary attr.\n+        $ref: '#/$defs/uint'\n+      min-length:\n+        description: |\n+          Minimum payload length, excluding the terminator of a string.\n+        $ref: '#/$defs/uint'\n+      max-length:\n+        description: |\n+          Maximum payload length, excluding the terminator of a string.\n+        $ref: '#/$defs/uint'\n+      unit:\n+        $ref: '#/$defs/unit'\n+      scale:\n+        description: Decimal exponent applied to the payload.\n+        type: integer\n+        minimum: -128\n+        maximum: 127\n+      max-occurrences:\n+        $ref: '#/$defs/max-occurrences'\n+\n+  attr-group:\n+    description: |\n+      A namespace of attr declarations. The group name is also the generated\n+      symbol prefix of its attrs.\n+    type: object\n+    required: [ name, attrs ]\n+    additionalProperties: false\n+    properties:\n+      name:\n+        $ref: '#/$defs/name'\n+      attrs:\n+        type: array\n+        minItems: 1\n+        maxItems: 4294967295\n+        items:\n+          $ref: '#/$defs/attr'\n+\n+  attr-set:\n+    description: |\n+      A compositional schema unit. Either a stub, which may be filled once\n+      by one descendant family, or a set of members. After fills are composed,\n+      every attr ID at one nesting level must still have one placement.\n+    type: object\n+    required: [ name ]\n+    additionalProperties: false\n+    properties:\n+      name:\n+        $ref: '#/$defs/name'\n+      stub:\n+        const: true\n+      attrs:\n+        $ref: '#/$defs/selectors'\n+      optional-attrs:\n+        $ref: '#/$defs/selectors'\n+\n+  placements:\n+    description: The required and optional attr placements at one level.\n+    type: object\n+    additionalProperties: false\n+    minProperties: 1\n+    properties:\n+      attrs:\n+        $ref: '#/$defs/selectors'\n+      optional-attrs:\n+        $ref: '#/$defs/selectors'\n+\n+  op:\n+    type: object\n+    required: [ name, type ]\n+    additionalProperties: false\n+    properties:\n+      name:\n+        $ref: '#/$defs/name'\n+      type:\n+        description: |\n+          action is invoked once and never fragments, query may fragment its\n+          reply, and event is an unsolicited reply-only schema.\n+        enum: [ action, query, event ]\n+      fd-access:\n+        description: |\n+          Authority needed to execute an action or query. read permits an\n+          observation fd; read-write, the default, requires a full-control fd.\n+          Events are always readable and cannot declare this property.\n+        enum: [ read, read-write ]\n+      availability:\n+        description: |\n+          Whether a family may enable and disable this op per device. fixed,\n+          the default, is always enabled. dynamic is action and query only,\n+          and is a permission rather than a state: every device starts with\n+          the op enabled.\n+        enum: [ fixed, dynamic ]\n+      optional:\n+        description: |\n+          Whether family initialization must opt in before publication for\n+          this op to exist on the device. Action and query only, and false by\n+          default. An op not opted into is absent from introspection.\n+        type: boolean\n+      pre-post:\n+        description: |\n+          Whether this op gets a generated pre/post hook pair of its own,\n+          which its declaring family implements. It runs inside the pair of\n+          the device family, or the core family for a core op.\n+          Action and query only, and false by default. Kernel implementation\n+          metadata: it reaches neither UAPI nor op-schema introspection.\n+        type: boolean\n+      request:\n+        description: |\n+          Omitted means a request root with no children. An event has no\n+          request.\n+        $ref: '#/$defs/placements'\n+      reply:\n+        description: |\n+          Required on a query. Omitted on an action means ACK-only, while an\n+          event always has a reply root, so omitting it there means a root\n+          with no children.\n+        $ref: '#/$defs/placements'\n+      suggested-reply-length:\n+        description: |\n+          Query only. An omitted value is CTLV_DEFAULT_QUERY_REPLY_LEN raised\n+          to the computed minimum. A declared value must be between that\n+          minimum and CTLV_MAX_INLINE_MESSAGE_LEN.\n+        type: integer\n+        minimum: 1\n+        maximum: 1048576\n+\n+title: CTLV family\n+description: Specification of one CTLV family schema\n+type: object\n+required: [ family ]\n+additionalProperties: false\n+properties:\n+  family:\n+    type: object\n+    required: [ name ]\n+    additionalProperties: false\n+    properties:\n+      name:\n+        description: |\n+          Registered family name. It carries no numeric ID; the ID comes\n+          from the position in Documentation/ctlv/families.yaml.\n+        $ref: '#/$defs/family-name'\n+      inherits:\n+        description: |\n+          Name of the single direct parent family, which every family but\n+          the root one names. The complete parent schema is inherited and\n+          its definitions keep the parent's IDs. The name above must be\n+          this name, one dash, and a local suffix.\n+        $ref: '#/$defs/family-name'\n+      pre-init:\n+        description: |\n+          Whether this family implements the generated pre-init callback\n+          which translates its init info for its parent. False by default;\n+          without one, the parent receives NULL.\n+        type: boolean\n+      post-init:\n+        description: |\n+          Whether this family implements the generated post-init callback\n+          after every family priv has been initialized. False by default.\n+        type: boolean\n+      pre-fini:\n+        description: |\n+          Whether this family implements the generated pre-fini callback\n+          before any family priv is finalized. False by default.\n+        type: boolean\n+  enums:\n+    type: array\n+    minItems: 1\n+    items:\n+      $ref: '#/$defs/enum-list'\n+\n+  flags:\n+    type: array\n+    minItems: 1\n+    items:\n+      $ref: '#/$defs/flags-list'\n+\n+  attr-groups:\n+    type: array\n+    minItems: 1\n+    maxItems: 65535\n+    items:\n+      $ref: '#/$defs/attr-group'\n+\n+  attr-sets:\n+    type: array\n+    minItems: 1\n+    items:\n+      $ref: '#/$defs/attr-set'\n+\n+  ops:\n+    type: array\n+    minItems: 1\n+    maxItems: 4294967295\n+    items:\n+      $ref: '#/$defs/op'\ndiff --git a/Documentation/ctlv/families.yaml b/Documentation/ctlv/families.yaml\nnew file mode 100644\nindex 0000000000000..d0e1493db498e\n--- /dev/null\n+++ b/Documentation/ctlv/families.yaml\n@@ -0,0 +1,15 @@\n+# SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)\n+%YAML 1.2\n+---\n+# Append-only registry of CTLV family names, indexed by family ID: the entry at\n+# index N has family ID N, up to 65535. The root family owns ID 0 and heads the\n+# list, and every other entry comes after the entry of the family it inherits.\n+# An entry may be marked deprecated, but never reordered, removed, renamed or\n+# reused, its position being its wire identity. Every entry must have a\n+# specification in specs/\u003cname\u003e.yaml, and is added by the change that adds the\n+# implementation. Fixtures under tools/ctlv/tests/ are not registered.\n+\n+families:\n+  - ctlv\n+  - ctlv-attestation\n+  - ctlv-attestation-tdx\ndiff --git a/Documentation/ctlv/generated-files-schema.yaml b/Documentation/ctlv/generated-files-schema.yaml\nnew file mode 100644\nindex 0000000000000..d3529ce6e8e75\n--- /dev/null\n+++ b/Documentation/ctlv/generated-files-schema.yaml\n@@ -0,0 +1,64 @@\n+# SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)\n+%YAML 1.2\n+---\n+$schema: https://json-schema.org/draft-07/schema\n+\n+$defs:\n+  path:\n+    type: string\n+    minLength: 1\n+    pattern: ^[^/].*$\n+\n+  outputs:\n+    type: object\n+    minProperties: 1\n+    additionalProperties: false\n+    properties:\n+      uapi-header:\n+        $ref: '#/$defs/path'\n+      kernel-header:\n+        $ref: '#/$defs/path'\n+      kernel-source:\n+        $ref: '#/$defs/path'\n+\n+  registry:\n+    type: object\n+    required: [ source, outputs ]\n+    additionalProperties: false\n+    properties:\n+      source:\n+        $ref: '#/$defs/path'\n+      outputs:\n+        type: object\n+        required: [ uapi-header ]\n+        additionalProperties: false\n+        properties:\n+          uapi-header:\n+            $ref: '#/$defs/path'\n+\n+  family:\n+    type: object\n+    required: [ name, source, outputs ]\n+    additionalProperties: false\n+    properties:\n+      name:\n+        type: string\n+      source:\n+        $ref: '#/$defs/path'\n+      outputs:\n+        $ref: '#/$defs/outputs'\n+\n+title: CTLV generated-file manifest\n+type: object\n+required: [ version, registry, families ]\n+additionalProperties: false\n+properties:\n+  version:\n+    const: 1\n+  registry:\n+    $ref: '#/$defs/registry'\n+  families:\n+    type: array\n+    minItems: 1\n+    items:\n+      $ref: '#/$defs/family'\ndiff --git a/Documentation/ctlv/generated-files.yaml b/Documentation/ctlv/generated-files.yaml\nnew file mode 100644\nindex 0000000000000..00ad23af7f659\n--- /dev/null\n+++ b/Documentation/ctlv/generated-files.yaml\n@@ -0,0 +1,31 @@\n+# SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)\n+%YAML 1.2\n+---\n+# Generated files for registered families.\n+version: 1\n+registry:\n+  source: Documentation/ctlv/families.yaml\n+  outputs:\n+    uapi-header: include/uapi/linux/ctlv_families_gen.h\n+\n+families:\n+  - name: ctlv\n+    source: Documentation/ctlv/specs/ctlv.yaml\n+    outputs:\n+      uapi-header: include/uapi/linux/ctlv_gen.h\n+      kernel-header: include/linux/ctlv_gen.h\n+      kernel-source: drivers/ctlv/ctlv_gen.c\n+\n+  - name: ctlv-attestation\n+    source: Documentation/ctlv/specs/ctlv-attestation.yaml\n+    outputs:\n+      uapi-header: include/uapi/linux/ctlv_attestation_gen.h\n+      kernel-header: drivers/attestation/generated/ctlv_attestation_gen.h\n+      kernel-source: drivers/attestation/generated/ctlv_attestation_gen.c\n+\n+  - name: ctlv-attestation-tdx\n+    source: Documentation/ctlv/specs/ctlv-attestation-tdx.yaml\n+    outputs:\n+      uapi-header: include/uapi/linux/ctlv_attestation_tdx_gen.h\n+      kernel-header: drivers/attestation/generated/ctlv_attestation_tdx_gen.h\n+      kernel-source: drivers/attestation/generated/ctlv_attestation_tdx_gen.c\ndiff --git a/Documentation/ctlv/specs/ctlv-attestation-tdx.yaml b/Documentation/ctlv/specs/ctlv-attestation-tdx.yaml\nnew file mode 100644\nindex 0000000000000..09f4d9916f82a\n--- /dev/null\n+++ b/Documentation/ctlv/specs/ctlv-attestation-tdx.yaml\n@@ -0,0 +1,30 @@\n+# SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)\n+%YAML 1.2\n+---\n+family:\n+  name: ctlv-attestation-tdx\n+  inherits: ctlv-attestation\n+  pre-init: true\n+\n+attr-groups:\n+  - name: info\n+    attrs:\n+      - name: mrconfigid\n+        type: binary\n+        min-length: 48\n+        max-length: 48\n+      - name: mrowner\n+        type: binary\n+        min-length: 48\n+        max-length: 48\n+      - name: mrownerconfig\n+        type: binary\n+        min-length: 48\n+        max-length: 48\n+\n+attr-sets:\n+  - name: device-info\n+    attrs:\n+      - info.mrconfigid\n+      - info.mrowner\n+      - info.mrownerconfig\ndiff --git a/Documentation/ctlv/specs/ctlv-attestation.yaml b/Documentation/ctlv/specs/ctlv-attestation.yaml\nnew file mode 100644\nindex 0000000000000..c0d7fc8db18ea\n--- /dev/null\n+++ b/Documentation/ctlv/specs/ctlv-attestation.yaml\n@@ -0,0 +1,347 @@\n+# SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)\n+%YAML 1.2\n+---\n+family:\n+  name: ctlv-attestation\n+  inherits: ctlv\n+  post-init: true\n+  pre-fini: true\n+\n+enums:\n+  - name: evidence-representation\n+    values:\n+      - raw\n+\n+  - name: evidence-blob-class\n+    values:\n+      - primary\n+\n+  - name: mr-log-event\n+    values:\n+      - info\n+      - extend\n+\n+flags:\n+  - name: mr-device-caps\n+    values:\n+      - read\n+      - extend\n+\n+  - name: mr-caps\n+    values:\n+      - read\n+      - extend\n+\n+attr-groups:\n+  - name: device\n+    attrs:\n+      # Reserved until provider-driven state changes are introduced.\n+      - name: generation\n+        type: uint\n+        max: 4294967295\n+      - name: caps\n+        attrs: device-caps\n+      - name: info\n+        attrs: device-info\n+\n+  - name: cap\n+    attrs:\n+      - name: evidence\n+        attrs: evidence-cap\n+      - name: mr\n+        attrs: mr-device-cap\n+      - name: min-challenge-length\n+        type: uint\n+      - name: max-challenge-length\n+        type: uint\n+      - name: max-total-output-length\n+        type: uint\n+      - name: mr-flags\n+        flags: mr-device-caps\n+      - name: object\n+        attrs: evidence-object-cap\n+        max-occurrences: 16\n+      - name: blob-class\n+        enum: evidence-blob-class\n+      - name: format\n+        type: string\n+        min-length: 1\n+        max-length: 128\n+      - name: representation\n+        enum: evidence-representation\n+      - name: max-length\n+        type: uint\n+\n+  - name: evidence\n+    attrs:\n+      - name: challenge\n+        type: binary\n+        max-length: 4096\n+      - name: object\n+        attrs: evidence-object-request\n+        max-occurrences: 16\n+      - name: blob-class\n+        enum: evidence-blob-class\n+      - name: format\n+        type: string\n+        min-length: 1\n+        max-length: 128\n+      - name: representation\n+        enum: evidence-representation\n+      - name: data\n+        blob:\n+          direction: output\n+          allowed-backings: [ va ]\n+          max-length: 4294967295\n+          alignment: 1\n+      - name: object-length\n+        type: uint\n+        max-occurrences: 16\n+\n+  - name: mr\n+    attrs:\n+      - name: id\n+        type: uint\n+        max: 4294967295\n+      - name: name\n+        type: string\n+        min-length: 1\n+        max-length: 128\n+      - name: hash-algo\n+        type: uint\n+        max: 20\n+      - name: supported-hash-algo\n+        type: uint\n+        max: 20\n+        max-occurrences: 21\n+      - name: register-index\n+        type: uint\n+        max: 4294967295\n+      - name: caps\n+        flags: mr-caps\n+      - name: item\n+        attrs: mr-dump-entry\n+        max-occurrences: unlimited\n+      - name: value\n+        attrs: mr-value\n+        max-occurrences: 21\n+      - name: data\n+        type: binary\n+        min-length: 16\n+        max-length: 64\n+      - name: generation\n+        type: uint\n+        max: 4294967295\n+      - name: selection\n+        attrs: mr-log-selection\n+        max-occurrences: 256\n+      - name: start-generation\n+        type: uint\n+        max: 4294967295\n+      - name: end-generation\n+        type: uint\n+        max: 4294967295\n+\n+  - name: log\n+    attrs:\n+      - name: entry\n+        attrs: mr-log-entry\n+        max-occurrences: unlimited\n+      - name: event\n+        enum: mr-log-event\n+      - name: mr\n+        attrs: mr-log-info\n+\n+  - name: notification\n+    attrs:\n+      - name: entry\n+        attrs: mr-log-entry\n+\n+attr-sets:\n+  - name: device-info\n+    stub: true\n+\n+  - name: evidence-object-cap\n+    attrs:\n+      - cap.blob-class\n+      - cap.format\n+      - cap.representation\n+      - cap.max-length\n+\n+  - name: evidence-cap\n+    attrs:\n+      - cap.min-challenge-length\n+      - cap.max-challenge-length\n+      - cap.max-total-output-length\n+      - cap.object\n+\n+  - name: mr-device-cap\n+    attrs: cap.mr-flags\n+\n+  - name: device-caps\n+    optional-attrs:\n+      - cap.evidence\n+      - cap.mr\n+\n+  - name: device-reply\n+    attrs:\n+      - device.caps\n+      - device.info\n+\n+  - name: evidence-object-request\n+    attrs:\n+      - evidence.blob-class\n+      - evidence.format\n+      - evidence.representation\n+      - evidence.data\n+\n+  - name: evidence-request\n+    attrs:\n+      - evidence.challenge\n+      - evidence.object\n+\n+  - name: evidence-reply\n+    attrs: evidence.object-length\n+    optional-attrs:\n+      - mr.generation\n+\n+  - name: mr-props\n+    attrs:\n+      - mr.name\n+      - mr.supported-hash-algo\n+      - mr.caps\n+    optional-attrs: mr.register-index\n+\n+  - name: mr-dump-entry\n+    attrs:\n+      - mr.id\n+      - mr.name\n+      - mr.supported-hash-algo\n+      - mr.caps\n+    optional-attrs: mr.register-index\n+\n+  - name: mr-id-request\n+    attrs: mr.id\n+\n+  - name: mr-read-request\n+    attrs: mr.id\n+\n+  - name: mr-value\n+    attrs:\n+      - mr.hash-algo\n+      - mr.data\n+\n+  - name: mr-read-reply\n+    attrs:\n+      - mr.generation\n+      - mr.value\n+\n+  - name: mr-extend-request\n+    attrs:\n+      - mr.id\n+      - mr.value\n+\n+  - name: mr-change-reply\n+    attrs: mr.generation\n+\n+  - name: mr-log-info\n+    attrs:\n+      - mr.name\n+      - mr.supported-hash-algo\n+      - mr.caps\n+    optional-attrs: mr.register-index\n+\n+  - name: mr-log-entry\n+    attrs:\n+      - mr.generation\n+      - mr.id\n+      - log.event\n+    optional-attrs:\n+      - mr.value\n+      - log.mr\n+\n+  - name: mr-log-event\n+    attrs: notification.entry\n+\n+  - name: mr-log-selection\n+    attrs: mr.id\n+\n+  - name: mr-log-request\n+    optional-attrs:\n+      - mr.selection\n+      - mr.start-generation\n+      - mr.end-generation\n+\n+  - name: mr-log-reply\n+    optional-attrs:\n+      - mr.start-generation\n+      - mr.end-generation\n+      - log.entry\n+\n+ops:\n+  - name: device-get\n+    type: action\n+    fd-access: read\n+    reply:\n+      attrs: device-reply\n+\n+  - name: evidence-get\n+    type: action\n+    fd-access: read-write\n+    availability: dynamic\n+    optional: true\n+    request:\n+      attrs: evidence-request\n+    reply:\n+      attrs: evidence-reply\n+\n+  - name: mr-get\n+    type: action\n+    fd-access: read\n+    optional: true\n+    request:\n+      attrs: mr-id-request\n+    reply:\n+      attrs: mr-props\n+\n+  - name: mr-dump\n+    type: query\n+    fd-access: read\n+    optional: true\n+    reply:\n+      attrs: mr.item\n+    suggested-reply-length: 4096\n+\n+  - name: mr-read\n+    type: query\n+    fd-access: read\n+    optional: true\n+    request:\n+      attrs: mr-read-request\n+    reply:\n+      attrs: mr-read-reply\n+    suggested-reply-length: 4096\n+\n+  - name: mr-extend\n+    type: action\n+    fd-access: read-write\n+    optional: true\n+    request:\n+      attrs: mr-extend-request\n+    reply:\n+      attrs: mr-change-reply\n+\n+  - name: mr-log-entry-appended\n+    type: event\n+    reply:\n+      attrs: mr-log-event\n+\n+  - name: mr-log-get\n+    type: query\n+    fd-access: read\n+    optional: true\n+    request:\n+      attrs: mr-log-request\n+    reply:\n+      attrs: mr-log-reply\n+    suggested-reply-length: 131072\ndiff --git a/Documentation/ctlv/specs/ctlv.yaml b/Documentation/ctlv/specs/ctlv.yaml\nnew file mode 100644\nindex 0000000000000..d58f02747e0f0\n--- /dev/null\n+++ b/Documentation/ctlv/specs/ctlv.yaml\n@@ -0,0 +1,379 @@\n+# SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)\n+%YAML 1.2\n+---\n+# The root CTLV family, family ID 0 and the first entry in families.yaml. It\n+# inherits nothing, and every other family name begins with \"ctlv-\". Every CTLV\n+# device answers these ops in addition to its own family's, and the attrs\n+# declared here appear inside family messages: the blob group is the descriptor\n+# nest of every family blob attr, the error group the error information written\n+# on failure. Nothing here may be reordered or removed.\n+\n+family:\n+  name: ctlv\n+\n+enums:\n+  - name: op-type\n+    values:\n+      - action\n+      - query\n+      - event\n+\n+  # A permission, not a state: what a device currently allows is op.disabled.\n+  - name: op-availability\n+    values:\n+      - fixed\n+      - dynamic\n+\n+  - name: blob-type\n+    values:\n+      - va\n+\n+  - name: blob-direction\n+    values:\n+      - input\n+      - output\n+      - inout\n+\n+  - name: validation-reason\n+    values:\n+      - malformed-message\n+      - unknown-attr\n+      - unknown-flag\n+      - nesting-too-deep\n+      - missing-attr\n+      - too-many-occurrences\n+      - value-out-of-range\n+      - bad-length\n+      - bad-string\n+      - bad-blob-descriptor\n+      - stale-generation\n+      - noncontiguous-attr\n+\n+  - name: op-fd-access\n+    values:\n+      - read\n+      - read-write\n+\n+attr-groups:\n+  # One record per family of the chain a device answers, as reported by\n+  # families-dump.\n+  - name: family\n+    attrs:\n+      - name: id\n+        type: uint\n+      # The registry name, also what a uevent carries. Bounded here, this being\n+      # the only place a family name is on the wire.\n+      - name: name\n+        type: string\n+        max-length: 63\n+      - name: entry\n+        attrs: family-entry\n+        max-occurrences: unlimited\n+\n+  # The nest carried by every family blob attr. va uses address; fd and offset\n+  # are reserved for later fd-backed types.\n+  - name: blob\n+    attrs:\n+      - name: type\n+        enum: blob-type\n+      - name: address\n+        type: uint\n+      - name: fd\n+        type: uint\n+        max: 2147483647\n+      - name: offset\n+        type: uint\n+      - name: length\n+        type: uint\n+        min: 1\n+\n+  # Error information: only what describes the first failure is present.\n+  - name: error\n+    attrs:\n+      - name: reason\n+        enum: validation-reason\n+      - name: message\n+        type: string\n+        max-length: 255\n+      - name: bad-attr-offset\n+        type: uint\n+      - name: nest-offset\n+        type: uint\n+      - name: missing-attr-id\n+        type: uint\n+      - name: expected-generation\n+        type: uint\n+      - name: current-generation\n+        type: uint\n+\n+  # One entry per effective op, as reported by ops-dump. Length members that do\n+  # not apply to an entry's op type are absent, as are fd access, availability\n+  # and disabled for an event.\n+  - name: op\n+    attrs:\n+      - name: id\n+        type: uint\n+        min: 1\n+      - name: type\n+        enum: op-type\n+      - name: availability\n+        enum: op-availability\n+      - name: disabled\n+        type: bool\n+      - name: request-max-len\n+        type: uint\n+      - name: action-reply-max-len\n+        type: uint\n+      - name: query-reply-min-len\n+        type: uint\n+      - name: query-reply-suggested-len\n+        type: uint\n+      - name: event-record-max-len\n+        type: uint\n+      # Advances once per op state change on one device.\n+      - name: state-generation\n+        type: uint\n+      - name: entry\n+        attrs: op-entry\n+        max-occurrences: unlimited\n+      - name: fd-access\n+        enum: op-fd-access\n+\n+  # One node of an op's request or reply tree, as reported by op-schema-get. A\n+  # node describes a node, so attrs and optional-attrs hold these same members\n+  # one level further in. Nothing here is a name: a caller matches the family\n+  # chain from families-dump to find the generated UAPI.\n+  - name: schema\n+    attrs:\n+      # Zero in a message root node, as on the wire.\n+      - name: attr-id\n+        type: uint\n+      # enum ctlv_schema_kind.\n+      - name: kind\n+        type: uint\n+      # Zero where the placement may repeat as often as the message has room.\n+      - name: max-occurrences\n+        type: uint\n+      # Inclusive bounds of an integer or enum payload, raw 64-bit values read\n+      # according to kind. An enum's values are numbered without gaps.\n+      - name: min\n+        type: uint\n+      - name: max\n+        type: uint\n+      # Payload length bounds of a string or binary attr, a string's\n+      # terminator excluded.\n+      - name: min-length\n+        type: uint\n+      - name: max-length\n+        type: uint\n+      - name: flags-mask\n+        type: uint\n+      # enum ctlv_unit, absent when the payload is dimensionless, and a scale\n+      # only ever accompanies a unit.\n+      - name: unit\n+        type: uint\n+      - name: scale\n+        type: sint\n+      - name: blob-direction\n+        enum: blob-direction\n+      # Mask of BIT(enum ctlv_blob_type): the backings this placement takes.\n+      - name: blob-backings\n+        type: uint\n+      # Maximum external payload length, unrelated to the inline message limit.\n+      - name: blob-max-length\n+        type: uint\n+      - name: blob-alignment\n+        type: uint\n+      # Levels to climb to the node whose members are this one's as well, one\n+      # meaning the node this one is a member of. A node that carries it lists\n+      # no members itself.\n+      - name: reenters\n+        type: uint\n+        min: 1\n+      # The nodes one level in; required and optional are different attrs.\n+      - name: attrs\n+        attrs: schema-node\n+        recursive: true\n+        max-occurrences: unlimited\n+      - name: optional-attrs\n+        attrs: schema-node\n+        recursive: true\n+        max-occurrences: unlimited\n+      # The root of each of an op's two trees, a node like any other.\n+      - name: request\n+        attrs: schema-node\n+      - name: reply\n+        attrs: schema-node\n+\n+  - name: event\n+    attrs:\n+      - name: op-id\n+        type: uint\n+        min: 1\n+        max-occurrences: 256\n+      - name: queue-len\n+        type: uint\n+        unit: bytes\n+        min: 1\n+        max: 16777216\n+      - name: queue-used\n+        type: uint\n+        unit: bytes\n+      - name: first-sequence\n+        type: uint\n+      - name: last-sequence\n+        type: uint\n+      - name: dropped-count\n+        type: uint\n+\n+attr-sets:\n+  - name: family-entry\n+    attrs:\n+      - family.id\n+      - family.name\n+\n+  - name: op-entry\n+    attrs:\n+      - op.id\n+      - op.type\n+    optional-attrs:\n+      - op.availability\n+      - op.disabled\n+      - op.request-max-len\n+      - op.action-reply-max-len\n+      - op.query-reply-min-len\n+      - op.query-reply-suggested-len\n+      - op.event-record-max-len\n+      - op.fd-access\n+\n+  - name: op-schema-request\n+    attrs: op.id\n+\n+  # Only the members the node's form has are present.\n+  - name: schema-node\n+    attrs:\n+      - schema.attr-id\n+      - schema.kind\n+      - schema.max-occurrences\n+    optional-attrs:\n+      - schema.min\n+      - schema.max\n+      - schema.min-length\n+      - schema.max-length\n+      - schema.flags-mask\n+      - schema.unit\n+      - schema.scale\n+      - schema.blob-direction\n+      - schema.blob-backings\n+      - schema.blob-max-length\n+      - schema.blob-alignment\n+      - schema.reenters\n+      - schema.attrs\n+      - schema.optional-attrs\n+\n+  # The two trees of one op, each absent when the op has no such message. An\n+  # event's one tree is reported as the reply.\n+  - name: op-schema-info\n+    optional-attrs:\n+      - schema.request\n+      - schema.reply\n+\n+  # What changed about one op, in the same attrs a dump entry uses.\n+  - name: op-change-info\n+    attrs:\n+      - op.id\n+      - op.disabled\n+      - op.state-generation\n+\n+  # The root of an error information message.\n+  - name: error-info\n+    optional-attrs:\n+      - error.reason\n+      - error.message\n+      - error.bad-attr-offset\n+      - error.nest-offset\n+      - error.missing-attr-id\n+      - error.expected-generation\n+      - error.current-generation\n+\n+  - name: event-subscription\n+    attrs: event.op-id\n+\n+  - name: event-queue-limit\n+    attrs: event.queue-len\n+\n+  - name: event-queue-state\n+    attrs:\n+      - event.queue-len\n+      - event.queue-used\n+\n+  - name: event-overflow-info\n+    attrs:\n+      - event.first-sequence\n+      - event.last-sequence\n+      - event.dropped-count\n+\n+ops:\n+  # The families this device answers, this one first and the device family\n+  # last. The only names any reply of this family carries.\n+  - name: families-dump\n+    type: query\n+    fd-access: read\n+    reply:\n+      attrs: family.entry\n+\n+  - name: ops-dump\n+    type: query\n+    fd-access: read\n+    reply:\n+      attrs: op.entry\n+\n+  # The request and reply ABI of one op, whether or not it can be called right\n+  # now. A removed op answers as one that was never declared.\n+  - name: op-schema-get\n+    type: query\n+    fd-access: read\n+    request:\n+      attrs: op-schema-request\n+    reply:\n+      attrs: op-schema-info\n+\n+  - name: subscriptions-add\n+    type: action\n+    fd-access: read\n+    request:\n+      attrs: event-subscription\n+\n+  - name: subscriptions-remove\n+    type: action\n+    fd-access: read\n+    request:\n+      attrs: event-subscription\n+\n+  - name: event-queue-get\n+    type: query\n+    fd-access: read\n+    reply:\n+      attrs: event-queue-state\n+\n+  - name: event-queue-set\n+    type: action\n+    fd-access: read\n+    request:\n+      attrs: event-queue-limit\n+\n+  # A dynamically available op was enabled or disabled. The name is not about\n+  # availability: a later mutable op property reports its state here too.\n+  - name: op-changed\n+    type: event\n+    reply:\n+      attrs: op-change-info\n+\n+  - name: event-overflow\n+    type: event\n+    reply:\n+      attrs: event-overflow-info\n+\n+  # Payload-free: the record itself is the whole indication.\n+  - name: device-removed\n+    type: event\ndiff --git a/Documentation/driver-api/attestation.rst b/Documentation/driver-api/attestation.rst\nnew file mode 100644\nindex 0000000000000..f253c848e8565\n--- /dev/null\n+++ b/Documentation/driver-api/attestation.rst\n@@ -0,0 +1,64 @@\n+.. SPDX-License-Identifier: GPL-2.0-only\n+\n+===========\n+Attestation\n+===========\n+\n+The attestation subsystem publishes provider devices as descendants of the\n+``ctlv-attestation`` family.  It owns common evidence retrieval,\n+measurement-register topology and an append-only extension journal.\n+Providers retain ownership of native hardware access and immutable capability\n+descriptions.\n+\n+Registering a provider\n+======================\n+\n+A provider defines ``struct attestation_provider`` and passes it to the base\n+family through its generated ``pre_init`` callback.  The descriptor, evidence\n+capabilities, fixed MR properties, strings and arrays remain immutable until\n+``ctlv_destroy()`` or failed-creation unwind completes.\n+\n+The provider family creates the CTLV device with its own generated family\n+descriptor.  Its family-wide operation hooks delegate once to\n+``ctlv_attestation_op_pre()`` and ``ctlv_attestation_op_post()`` using the\n+attestation parent priv.  The hooks serialize an operation, its native\n+callback, journal commit and event emission with one instance mutex.\n+\n+Fixed MRs are listed in the provider descriptor.  Their property storage\n+remains valid until ``ctlv_destroy()`` or failed-creation unwind completes.\n+\n+MR journal\n+==========\n+\n+MR extension is transactional.  The core allocates the complete journal entry\n+and event before invoking ``mr_extend``.  A successful callback is followed\n+only by infallible publication, so userspace observes the same ordered\n+journal.\n+\n+``MR_READ`` uses ``mr_read_generation`` only to validate query continuation;\n+the returned ``mr.generation`` is the journal boundary at which the values\n+were read.\n+\n+Teardown\n+========\n+\n+CTLV first drains userspace operations.  The base ``pre_fini`` callback then\n+withdraws the instance from the kernel registry while provider state and CTLV\n+event emission remain available.  CTLV stops events only after that callback\n+returns; provider and base ``fini`` callbacks may then release native storage.\n+\n+TDX provider\n+============\n+\n+``CONFIG_ATTESTATION_TDX`` registers a ``ctlv-attestation-tdx`` instance for\n+the native TDX guest service.  MRTD has stable MR ID 0 and is read-only.\n+RTMR0 through RTMR3 have IDs 1 through 4 and are readable and extendable with\n+SHA-384.\n+\n+``EVIDENCE_GET`` supports complete raw TDREPORT and Quote objects.  Both\n+formats cryptographically bind all architectural TDX measurement registers,\n+so successful replies carry the matching MR-journal boundary.  The provider\n+exposes no verdict or device-security operation.\n+\n+The provider consumes only ``\u003clinux/tdx-guest.h\u003e``.  It does not call the TDX\n+misc ioctl, configfs TSM-report, or TSM-MR sysfs frontends.\ndiff --git a/Documentation/driver-api/ctlv.rst b/Documentation/driver-api/ctlv.rst\nnew file mode 100644\nindex 0000000000000..461e2977a4839\n--- /dev/null\n+++ b/Documentation/driver-api/ctlv.rst\n@@ -0,0 +1,422 @@\n+.. SPDX-License-Identifier: GPL-2.0\n+\n+=====================\n+Writing a CTLV family\n+=====================\n+\n+:Author: Jiri Pirko\n+\n+A CTLV family is a YAML specification plus the callbacks named by its generated\n+header. CTLV validates requests before a callback sees them. The wire ABI is\n+:doc:`/userspace-api/ctlv`; family specifications are under\n+``Documentation/ctlv/specs``.\n+\n+The code here is a small invented family, ``ctlv-example``.\n+\n+Add the specification, registry entry, and output manifest entry in one change::\n+\n+    Documentation/ctlv/specs/ctlv-example.yaml\n+    Documentation/ctlv/families.yaml\n+    Documentation/ctlv/generated-files.yaml\n+\n+``families.yaml`` is append-only. Its array index is the family ID and is part\n+of every generated attribute and operation ID. Never reorder, remove, rename,\n+or reuse an entry. ``Documentation/ctlv/abi/families.registry.yaml`` is the\n+checked-in registry ABI. The output manifest selects the generated UAPI,\n+kernel and userspace paths and generation modes.\n+\n+Generate and verify them with::\n+\n+    make -C tools/ctlv regen\n+    make -C tools/ctlv all\n+\n+Never edit a generated output. Change the YAML or generator and regenerate it.\n+Optional RST reference pages are written to\n+``Documentation/output/ctlv/families`` by::\n+\n+    make -C tools/ctlv docs\n+\n+Write the specification\n+=======================\n+\n+.. code-block:: yaml\n+\n+    # SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)\n+    %YAML 1.2\n+    ---\n+    family:\n+      name: ctlv-example\n+      inherits: ctlv\n+      post-init: true\n+      pre-fini: true\n+\n+    attr-groups:\n+      - name: item\n+        attrs:\n+          - name: index\n+            type: uint\n+            max: 4095\n+          - name: label\n+            type: string\n+            max-length: 63\n+          - name: data\n+            blob:\n+              direction: input\n+              allowed-backings: [ va ]\n+              max-length: 1048576\n+              alignment: 8\n+      - name: list\n+        attrs:\n+          - name: item\n+            attrs: item-reply\n+            max-occurrences: unlimited\n+\n+    attr-sets:\n+      - name: item-request\n+        attrs: item.index\n+        optional-attrs:\n+          - item.label\n+          - item.data\n+      - name: item-reply\n+        attrs: item.index\n+        optional-attrs: item.label\n+      - name: items-reply\n+        optional-attrs: list.item\n+\n+    ops:\n+      - name: item-set\n+        type: action\n+        optional: true\n+        request:\n+          attrs: item-request\n+      - name: items-dump\n+        type: query\n+        availability: dynamic\n+        pre-post: true\n+        reply:\n+          attrs: items-reply\n+        suggested-reply-length: 4096\n+      - name: item-changed\n+        type: event\n+        reply:\n+          attrs: item-reply\n+\n+An attribute has one payload form: ``type``, ``enum``, ``flags``, ``attrs``, or\n+``blob``. An attr set names one message level. ``attrs`` are required and\n+``optional-attrs`` are optional. Its bounds and membership are ABI.\n+\n+Inheritance and extension points\n+================================\n+\n+A descendant implements only the operations it declares. Inherited operations\n+keep the callbacks and operation hooks of their declaring family. Every module\n+therefore depends on the module containing its parent implementation.\n+\n+A parent reserves an extension point with an empty stub set:\n+\n+.. code-block:: yaml\n+\n+    attr-groups:\n+      - name: device\n+        attrs:\n+          - name: details\n+            attrs: details-extension\n+\n+    attr-sets:\n+      - name: details-extension\n+        stub: true\n+      - name: device-reply\n+        optional-attrs: device.details\n+\n+A child fills that same set:\n+\n+.. code-block:: yaml\n+\n+    family:\n+      name: ctlv-example-vendor\n+      inherits: ctlv-example\n+      pre-init: true\n+\n+    attr-groups:\n+      - name: vendor\n+        attrs:\n+          - name: serial\n+            type: uint\n+\n+    attr-sets:\n+      - name: details-extension\n+        optional-attrs: vendor.serial\n+\n+The parent implementation opens the physical nest and delegates its members:\n+\n+.. code-block:: c\n+\n+    if (ctlv_example_device_details_start(reply, \u0026details)) {\n+            ret = ctlv_stub_fill(ctx, request_details, \u0026details);\n+            ctlv_nest_end(\u0026details);\n+            if (ret)\n+                    return ret;\n+    }\n+\n+The generated child callback fills it:\n+\n+.. code-block:: c\n+\n+    int ctlv_example_vendor_details_extension_fill(\n+                            void *priv, struct ctlv_op_ctx *ctx,\n+                            const struct ctlv_cursor *request,\n+                            struct ctlv_cursor *nest)\n+    {\n+            ctlv_example_vendor_vendor_serial_put(nest,\n+                                                   example_serial(priv));\n+            return 0;\n+    }\n+\n+An unfilled stub contributes no nest or message length. Neither side names the\n+family on the other side.\n+\n+Create and destroy a device\n+===========================\n+\n+``ctlv_create()`` takes the leaf family descriptor and leaf initialization\n+information:\n+\n+.. code-block:: c\n+\n+    struct ctlv_example_vendor_init_info info = {\n+            .dev = dev,\n+    };\n+    struct ctlv_device *ctlvdev;\n+\n+    ctlvdev = ctlv_create(dev, \u0026ctlv_example_vendor_ctlv_family, \u0026info);\n+    if (IS_ERR(ctlvdev))\n+            return PTR_ERR(ctlvdev);\n+\n+A family with ``pre-init: true`` supplies initialization information to its\n+direct parent. A typical provider descriptor is static and immutable:\n+\n+.. code-block:: c\n+\n+    static const struct ctlv_example_provider example_provider = {\n+            .name = \"vendor-example\",\n+            .ops = \u0026example_provider_ops,\n+    };\n+\n+    const void *ctlv_example_vendor_pre_init(const void *init_info)\n+    {\n+            return \u0026example_provider;\n+    }\n+\n+The leaf's per-device ``init_info`` still reaches its own ``init`` callback; it\n+is not forwarded as the parent's descriptor. ``pre_init`` runs leaf to root and\n+may return an ``ERR_PTR()``. It must not acquire resources or return automatic\n+storage.\n+\n+Each family supplies ``priv_size``, ``init``, and ``fini``. The YAML flags add\n+``pre_init``, ``post_init``, and ``pre_fini`` callbacks. Creation order is::\n+\n+    leaf -\u003e root     pre_init\n+    root -\u003e leaf     init\n+                     freeze published operations; start event admission\n+    leaf -\u003e root     post_init\n+                     register the character device\n+\n+Select optional operations and their initial dynamic state in ``init``. A\n+``post_init`` callback may publish the device to kernel consumers because all\n+family privs and event emission are then available.\n+\n+Normal destruction is ordered as follows::\n+\n+    withdraw userspace access; drain admitted operation callbacks\n+    root -\u003e leaf     pre_fini\n+    stop and drain event contexts; queue DEVICE_REMOVED\n+    leaf -\u003e root     fini\n+\n+A family published in ``post_init`` withdraws and drains its consumers in\n+``pre_fini``. Provider state and events remain available until all\n+``pre_fini`` callbacks finish. ``ctlv_destroy()`` consumes the reference from\n+``ctlv_create()``; open file descriptions remain only to drain queued records\n+and otherwise fail with ``-ENODEV``.\n+\n+If ``init`` fails, that callback releases its partial resources and CTLV calls\n+``fini`` only for initialized ancestors. A failure after initialization uses\n+the normal ``pre_fini`` and ``fini`` ordering.\n+\n+CTLV allocates one zeroed, cache-line-aligned priv per family. Direct neighbors\n+are available without naming their types globally:\n+\n+.. code-block:: c\n+\n+    parent = ctlv_priv_parent(priv);\n+    child = ctlv_priv_child(priv);\n+\n+During ``init``, the child is not initialized yet. During ``pre_fini`` it still\n+is; during ``fini`` it has already been finalized. Allocate a separately\n+aligned object when cache-line alignment is insufficient.\n+\n+Implement operations\n+====================\n+\n+Action\n+------\n+\n+Generated getters read only validated placements and generated serializers\n+write only declared replies:\n+\n+.. code-block:: c\n+\n+    int ctlv_example_item_set_action(void *priv, struct ctlv_op_ctx *ctx,\n+                                     const struct ctlv_cursor *request,\n+                                     struct ctlv_cursor *reply)\n+    {\n+            u64 index = ctlv_example_item_index_get(request);\n+\n+            if (item_busy(priv, index))\n+                    return ctlv_op_error(ctx, -EBUSY, \"item is busy\");\n+            return item_set(priv, index);\n+    }\n+\n+Use ``_present()`` for optional attributes and ``_for_each()`` for repeated\n+ones. ``ctlv_op_error()`` preserves the errno and adds a short diagnostic when\n+the caller supplied enough reply space.\n+\n+Query\n+-----\n+\n+.. code-block:: c\n+\n+    int ctlv_example_items_dump_query(void *priv, struct ctlv_op_ctx *ctx,\n+                                      const struct ctlv_cursor *request,\n+                                      struct ctlv_cursor *reply)\n+    {\n+            struct ctlv_example *example = priv;\n+            u64 generation = READ_ONCE(example-\u003egeneration);\n+            u64 cursor = ctlv_op_query_cursor(ctx);\n+            struct ctlv_cursor item;\n+            u64 i = cursor ? cursor - 1 : 0;\n+\n+            if (cursor \u0026\u0026 ctlv_op_query_generation(ctx) != generation)\n+                    return -ESTALE;\n+            for (; i \u003c example-\u003eitems_count; i++) {\n+                    if (!ctlv_example_list_item_start(reply, \u0026item))\n+                            return ctlv_op_query_more(ctx, generation, i + 1);\n+                    ctlv_example_item_index_put(\u0026item, i);\n+                    ctlv_nest_end(\u0026item);\n+            }\n+            return ctlv_op_query_done(ctx, generation);\n+    }\n+\n+A continuation cursor is nonzero and advances. Every continuing fragment\n+completes a logical leaf. Call ``ctlv_op_query_more()`` while cursors for open\n+continuation nests are alive. A generation mismatch returns ``-ESTALE``.\n+\n+Hooks and availability\n+======================\n+\n+The leaf family's hooks wrap each effective non-core action or query. An\n+operation with ``pre-post: true`` has its declaring family's pair inside them::\n+\n+    family pre -\u003e operation pre -\u003e availability check -\u003e callback\n+               -\u003e operation post -\u003e family post\n+\n+Each successful pre hook has one post hook. A failing pre hook undoes its own\n+work. Hooks may sleep and must not retain ``ctx``. Each hook and callback gets\n+the priv of the family implementing it.\n+\n+Optional and dynamic operations are separate choices:\n+\n+.. code-block:: c\n+\n+    /* During init: publish this optional operation on this device. */\n+    ctlv_example_item_set_provide(ctlvdev);\n+\n+    /* At runtime: temporarily refuse a published dynamic operation. */\n+    ctlv_example_items_dump_disable(ctlvdev);\n+    ctlv_example_items_dump_enable(ctlvdev);\n+\n+Declare the latter with ``availability: dynamic``. An unpublished optional\n+operation has no schema entry. A disabled operation remains discoverable and\n+returns ``-EOPNOTSUPP``; a state change emits ``op-changed``.\n+\n+Blobs\n+=====\n+\n+A blob attribute describes caller-owned memory. Resolve it only in the callback\n+that received its request and release every successful resolve before return:\n+\n+.. code-block:: c\n+\n+    blob = ctlv_example_item_data_resolve(ctx, request);\n+    if (IS_ERR(blob))\n+            return PTR_ERR(blob);\n+\n+    ret = ctlv_blob_read(blob, 0, buf, ctlv_blob_len(blob));\n+    put_ret = ctlv_blob_put(blob);\n+    return ret ?: put_ret;\n+\n+The schema fixes direction, backing, length, and alignment. Resolution holds\n+the backing for the ioctl.\n+\n+Events\n+======\n+\n+.. code-block:: c\n+\n+    ctx = ctlv_example_item_changed_create(ctlvdev, \u0026event, GFP_KERNEL);\n+    if (IS_ERR(ctx))\n+            return PTR_ERR(ctx);\n+    ctlv_example_item_index_put(event, index);\n+    return ctlv_event_emit(ctx);\n+\n+Exactly one of ``ctlv_event_emit()`` and ``ctlv_event_abort()`` ends the context. The\n+GFP argument covers subscriber copies; atomic producers use ``GFP_NOWAIT`` or\n+``GFP_ATOMIC``. Event APIs are not called from interrupt context, and hooks do\n+not run around events.\n+\n+If an event occurred but allocation failed, commit the state change and call\n+``ctlv_event_lost()``. It neither allocates nor sleeps. Do not use it for an\n+aborted event or for per-subscriber drops already tracked by\n+``ctlv_event_emit()``.\n+\n+If hardware changed before an event context could be allocated, the family\n+must commit its invalidation and explicitly report the missing notification:\n+\n+.. code-block:: c\n+\n+    invalidate_stale_state(priv);\n+    priv-\u003egeneration++;\n+\n+    ctx = ctlv_example_thing_happened_create(ctlvdev, \u0026event, GFP_ATOMIC);\n+    if (IS_ERR(ctx)) {\n+            if (PTR_ERR(ctx) == -ENOMEM)\n+                    ctlv_event_lost(ctlvdev,\n+                                    CTLV_EXAMPLE_OP_THING_HAPPENED);\n+            return;\n+    }\n+    ctlv_example_generation_put(event, priv-\u003egeneration);\n+    ctlv_op_emit(ctx);\n+\n+``ctlv_event_lost()`` allocates nothing and does not sleep. For each subscribed\n+file description it advances the event sequence and aggregates the loss into\n+the preallocated ``EVENT_OVERFLOW`` record. The caller keeps the device alive\n+and serializes the report with normal emission of that event. Like event\n+emission, it is not called from interrupt context. It is only for an event that\n+actually occurred but could not be constructed: do not call it for an aborted\n+event or for copy-allocation and full-queue drops already accounted for by\n+``ctlv_op_emit()``. Reports after event shutdown or the terminal\n+``DEVICE_REMOVED`` record are ignored.\n+\n+Reporting an error\n+------------------\n+\n+A callback returns a negative errno, and that is what the ioctl returns. Where\n+CTLV itself refuses a message it also writes error information into the\n+caller's reply buffer, naming the reason and the offset of the offending\n+attribute. A family implementation does not build that; it adds its own errno\n+and its reply.\n+\n+Configuration\n+=============\n+\n+``CONFIG_CTLV``\n+    CTLV. A family implementation selects it.\ndiff --git a/Documentation/driver-api/index.rst b/Documentation/driver-api/index.rst\nindex 6601a258690f8..ecf82a9330fcf 100644\n--- a/Documentation/driver-api/index.rst\n+++ b/Documentation/driver-api/index.rst\n@@ -37,6 +37,8 @@ of interest to most developers working on device drivers.\n \n    early-userspace/index\n    connector\n+   ctlv\n+   attestation\n    device-io\n    devfreq\n    dma-buf\ndiff --git a/Documentation/userspace-api/ctlv.rst b/Documentation/userspace-api/ctlv.rst\nnew file mode 100644\nindex 0000000000000..5ebca3d4d94af\n--- /dev/null\n+++ b/Documentation/userspace-api/ctlv.rst\n@@ -0,0 +1,507 @@\n+.. SPDX-License-Identifier: GPL-2.0\n+\n+==================\n+CTLV userspace ABI\n+==================\n+\n+:Author: Jiri Pirko\n+\n+CTLV is a transport for device control interfaces. A family describes what its\n+devices accept in YAML, a generator turns that into kernel metadata and UAPI\n+headers, and CTLV validates every message before a family callback sees it.\n+Userspace sees one character device per instance, one ioctl, and ``read()`` for\n+events.\n+\n+This document is the ABI. What each family accepts is specified under\n+``Documentation/ctlv/specs``; writing a family is :doc:`/driver-api/ctlv`.\n+\n+Why a TLV transport\n+===================\n+\n+CTLV puts the rules of every operation in one description and validates them\n+once:\n+\n+- One ioctl carries every operation of every family, so a new operation is a\n+  new specification entry, not a new ioctl number.\n+- Attributes are optional or required by declaration, so a message can grow\n+  without breaking a caller that does not know the new attribute.\n+- An unknown attribute is refused on a request and tolerated on a reply, so a\n+  new kernel can say more to an old program. A request may mark an attribute an\n+  old kernel is welcome to skip, so a new program can say more too.\n+- Bounds, lengths, occurrence counts and nesting depth are checked before a\n+  family callback runs.\n+\n+Devices\n+=======\n+\n+Each registered instance appears as a character device in the ``ctlv`` class\n+with a dynamic minor::\n+\n+    /dev/ctlv0\n+    /sys/class/ctlv/ctlv0\n+\n+Sysfs shows class membership, the ``dev`` number and the device-model link to\n+the parent device. There is no family sysfs attribute; ``families-dump`` on an\n+open descriptor is the authoritative answer to what a device is.\n+\n+Each open file description has its own event subscriptions and event queue.\n+``O_RDONLY`` opens an observation fd, ``O_RDWR`` opens a full-control fd, and\n+``O_WRONLY`` is rejected with ``-EACCES``. Every action and query declares the\n+authority it needs: ``read`` permits either accepted fd, while ``read-write``\n+requires full control. Events are readable and subscribable through both.\n+``dup()`` and ``SCM_RIGHTS`` preserve that authority; attenuation requires a\n+separate observation open.\n+\n+Discovery\n+---------\n+\n+Both uevents, addition and removal, carry the family chain as numbered\n+properties::\n+\n+    CTLV_FAMILY=ctlv-accelerator-foo\n+    CTLV_COMPATIBLE_0=ctlv\n+    CTLV_COMPATIBLE_1=ctlv-accelerator\n+    CTLV_COMPATIBLE_2=ctlv-accelerator-foo\n+    CTLV_COMPATIBLE_N=3\n+\n+``CTLV_FAMILY`` is the family the device answers as, the numbered properties\n+are its ancestry from the root to that family, and\n+``CTLV_COMPATIBLE_N`` is how many there are. An index never moves: changing a\n+family's parent is an ABI\n+break, adding a descendant only appends.\n+\n+A program that wants every device, including ones appearing while it starts,\n+must listen before it looks, which closes the window between enumerating and\n+subscribing::\n+\n+    1. create a udev monitor filtered to the ctlv subsystem, and enable it\n+    2. enumerate the existing ctlv class devices\n+    3. drain the events already queued on the monitor\n+    4. deduplicate by sysfs path\n+    5. open the device node\n+    6. ask families-dump on the open descriptor for the authoritative chain\n+\n+Steps 1 to 4 are pre-open discovery, all a udev rule can match on; step 6 does\n+not need a udev database. A rule matches a family through the compatibility\n+properties::\n+\n+    # /etc/udev/rules.d/70-ctlv.rules\n+    #\n+    # Anything of one family, whatever family implementation registered it.\n+    SUBSYSTEM==\"ctlv\", ENV{CTLV_FAMILY}==\"ctlv-accelerator-foo\", \\\n+        GROUP=\"accel\", MODE=\"0660\"\n+\n+    # Anything descended from a family.\n+    SUBSYSTEM==\"ctlv\", ENV{CTLV_COMPATIBLE_1}==\"ctlv-accelerator\", \\\n+        TAG+=\"uaccess\"\n+\n+    # A stable name from the parent device, which is deployment policy.\n+    SUBSYSTEM==\"ctlv\", ENV{CTLV_FAMILY}==\"ctlv-accelerator-foo\", \\\n+        SYMLINK+=\"accel/by-path/$env{ID_PATH}\"\n+\n+CTLV does not standardise such aliases and does not promise that a generic\n+identifier survives a reboot or a reprobe; a family with a meaningful identity\n+exposes it through an operation of its own.\n+\n+Wire format\n+===========\n+\n+A message is a tree of attributes. Every attribute begins with the same\n+header, at an eight-byte boundary::\n+\n+    struct ctlv_attr {\n+            __u32 len;              /* header + payload, without padding */\n+            __u32 flags;            /* CTLV_ATTR_F_* */\n+            __aligned_u64 attr_id;  /* complete ID, or 0 for a root */\n+    };\n+\n+One unsigned integer attribute with an eight-byte payload, on the wire::\n+\n+     0                   1                   2                   3\n+     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\n+    +---------------------------------------------------------------+\n+    |                        len = 24                               |\n+    +---------------------------------------------------------------+\n+    |                        flags = 0                              |\n+    +---------------------------------------------------------------+\n+    |                                                               |\n+    +                       attr_id                                 +\n+    |                                                               |\n+    +---------------------------------------------------------------+\n+    |                                                               |\n+    +                       payload                                 +\n+    |                                                               |\n+    +---------------------------------------------------------------+\n+\n+The rules that make a tree out of that:\n+\n+- ``CTLV_ALIGNTO`` is 8 and ``CTLV_ALIGN()`` rounds up to it. Every attribute\n+  starts at a multiple of eight.\n+- ``len`` counts this header plus this attribute's payload, not its own\n+  trailing padding.\n+- A nested payload is the concatenation of ``CTLV_ALIGN(child.len)`` bytes per\n+  child, so a child's padding is counted inside its parent's ``len`` and a\n+  leaf's own padding by nobody.\n+- ``CTLV_ATTR_F_NESTED`` is set exactly on a root and on a nest.\n+- A message begins with one root attribute, whose ``attr_id`` is\n+  ``CTLV_ATTR_ROOT`` (zero) and whose payload is the message. A root never\n+  appears inside a nest, and a nest never carries the root ID.\n+- Scalar payloads are native-endian and their lengths exact: eight bytes for\n+  an integer, one byte holding zero or one for a boolean, the string including\n+  its NUL terminator, the declared length for binary data.\n+- Nesting is limited to ``CTLV_MAX_NEST_DEPTH`` levels, the root being level\n+  zero.\n+\n+A whole message with every offset, for a request of one integer and one nest\n+carrying a string and a further nest::\n+\n+    offset  attribute                       len  flags   contents\n+    ------  ------------------------------  ---  ------  ----------------\n+         0  root                            120  NESTED  attr_id = 0\n+        16  .. chunks                        24  -       8-byte integer\n+        40  .. chunk                         80  NESTED\n+        56     .. label                      19  -       \"ab\" and its NUL\n+        80     .. item                       40  NESTED\n+        96        .. value                   24  -       8-byte integer\n+       120  end of message\n+\n+    +--------------------------------------------------------------+ 0\n+    | root: len = 120, flags = NESTED, attr_id = 0                 |\n+    +--------------------------------------------------------------+ 16\n+    | chunks: len = 24 | payload: 8 bytes                          |\n+    +--------------------------------------------------------------+ 40\n+    | chunk: len = 80, flags = NESTED                              |\n+    |   +--------------------------------------------------------+ | 56\n+    |   | label: len = 19 | payload: 'a' 'b' 0 | 5 bytes padding | |\n+    |   +--------------------------------------------------------+ | 80\n+    |   | item: len = 40, flags = NESTED                         | |\n+    |   |   +--------------------------------------------------+ | | 96\n+    |   |   | value: len = 24 | payload: 8 bytes               | | |\n+    |   |   +--------------------------------------------------+ | | 120\n+    +--------------------------------------------------------------+\n+\n+``label.len`` is 19: its header and three payload bytes, not the five bytes of\n+padding after it. ``chunk`` counts those five, its ``len`` of 80 being its\n+header plus ``CTLV_ALIGN(19)`` plus ``CTLV_ALIGN(40)``. A walk over a nest's\n+children advances by ``CTLV_ALIGN(child.len)``, a walk of one payload by\n+``child.len``.\n+\n+An attribute ID names the family that declared it, a group within that family\n+and an attribute within that group::\n+\n+    63           48 47           32 31                             0\n+    +--------------+--------------+--------------------------------+\n+    |    family    |    group     |             attr               |\n+    +--------------+--------------+--------------------------------+\n+\n+    CTLV_ATTR(family, group, attr)\n+    CTLV_ATTR_FAMILY(attr) / CTLV_ATTR_GROUP(attr) / CTLV_ATTR_NUMBER(attr)\n+\n+An operation ID is the same shape with the group bits zero::\n+\n+    CTLV_OP(family, op)\n+    CTLV_OP_FAMILY(op) / CTLV_OP_NUMBER(op)\n+\n+Use generated complete IDs. A family's header defines every ID it declares\n+and includes its parent's.\n+\n+Request occurrence order\n+------------------------\n+\n+Occurrences of one attribute ID must be contiguous within each request root or\n+nest. ``A A B`` is valid, while ``A B A`` is not. An ignored unknown attribute\n+is not an occurrence of any known attribute, but it ends the preceding run, so\n+``A ignored-unknown A`` is also invalid. Different IDs otherwise have no\n+required numeric or schema order.\n+\n+Attributes a kernel may skip\n+----------------------------\n+\n+A request attribute, the root aside, may carry\n+``CTLV_ATTR_F_IGNORE_IF_UNKNOWN``. If no family the device answers declares\n+that complete ID, the kernel steps over the whole attribute without looking\n+inside it; without the bit, an attribute the schema does not place where it\n+appears fails the request as it always has.\n+\n+The bit forgives an ID this kernel has never heard of and nothing else. An ID\n+the device's schema declares somewhere is held to that schema, so an attribute\n+sent where it does not belong fails whether the bit is set or not, and one sent\n+where it does belong is checked as usual. Every other rule applies too: the\n+length has to fit its nest and the header may carry no bit the format does not\n+define. Replies and events never carry it.\n+\n+This is how a program built against a newer version of a family talks to an\n+older kernel. What that kernel knows is validated, what it does not is\n+ignored, and a caller that has to know which is which asks ``op-schema-get``\n+first.\n+\n+Executing an operation\n+======================\n+\n+One ioctl executes every operation::\n+\n+    struct ctlv_op_exec {\n+            __aligned_u64 op_id;\n+            __aligned_u64 request;      /* struct ctlv_attr __user * */\n+            __aligned_u64 reply;        /* struct ctlv_attr __user * */\n+            __u32 request_len;\n+            __u32 reply_len;\n+            __aligned_u64 generation;   /* queries only */\n+            __aligned_u64 cursor;       /* queries only */\n+            __aligned_u64 reserved[2];  /* must be zero */\n+    };\n+\n+    #define CTLV_IOC_OP_EXEC _IOWR(0xBB, 0x00, struct ctlv_op_exec)\n+\n+``request_len`` is how many bytes the kernel may read at ``request`` and\n+``reply_len`` how many it may write at ``reply``. They are copy boundaries, not\n+message lengths: a root's ``len`` may be shorter than ``request_len``, the\n+bytes after it being ignored, and may not be longer. ``reply_len`` is never\n+overwritten; the length written is the reply root's ``len``. The pointers are\n+fixed-width so a 32-bit and a 64-bit process pass the same structure, and in\n+place of a size field the ioctl number encodes the size and ``reserved``, which\n+must be zero, covers compatible growth.\n+\n+Every action and query carries a physical request root, including an empty\n+request. ``request_len`` is therefore at least one attr header and at most the\n+1 MiB transport limit. The ``request-max-len`` reported by ``ops-dump`` is the\n+maximum request composed from the known schema; a newer caller may exceed it\n+with well-formed unknown attrs marked ``IGNORE_IF_UNKNOWN``, up to the\n+transport limit.\n+\n+The three kinds of operation differ in what they answer:\n+\n+action\n+    Executed once and acknowledged. An action with no reply takes\n+    ``reply_len`` zero; one with a bounded reply has its maximum in\n+    ``ops-dump``.\n+\n+query\n+    Executed once and answered in as many fragments as it needs, using\n+    ``generation`` and ``cursor``.\n+\n+event\n+    Not executed. A device produces records and a subscribed file description\n+    reads them.\n+\n+Errors\n+------\n+\n+A failed operation returns a negative errno. Where the failure is a rule the\n+message broke and the caller offered a reply buffer, CTLV also writes\n+error information there in TLV form: a ``validation-reason`` value, a\n+human-readable message, the offset of the offending attribute, the offset of\n+the nest it was in, the ID of a missing attribute, and for a stale query the\n+expected and the current generation. A buffer too small leaves it unwritten;\n+the errno is authoritative either way.\n+\n+What the transport answers with, as against a family's own callback:\n+\n+``ENOTTY``\n+    Not ``CTLV_IOC_OP_EXEC``; this transport has one ioctl.\n+\n+``EINVAL``\n+    A reserved field was not zero, ``op_id`` was zero, ``generation`` or\n+    ``cursor`` was set on something that is not a query, or the message broke\n+    a rule of the format or of the schema.\n+\n+``EFAULT``\n+    The structure, the request or the reply was not accessible.\n+\n+``EOPNOTSUPP``\n+    The device does not publish the operation, publishes it but has it\n+    disabled, or the operation is an event, which is read rather than executed.\n+\n+``EACCES``\n+    The fd lacks the operation's declared authority, or an ``O_WRONLY`` open\n+    was attempted.\n+\n+``EMSGSIZE``\n+    ``reply_len`` is smaller than the smallest fragment the operation can\n+    answer with. Nothing was executed.\n+\n+``ESTALE``\n+    A continuation whose ``generation`` no longer matches. Start the query\n+    again.\n+\n+``ENODEV``\n+    The device was unregistered. Descriptors stay open and every operation on\n+    them fails this way.\n+\n+``EBADF``, ``EIO``\n+    A blob descriptor named something that is not a file, or the file refused\n+    the transfer.\n+\n+``ENOMEM``\n+    The kernel could not allocate what the operation needed.\n+\n+``read()`` answers ``EAGAIN`` when no record is queued on a non-blocking\n+description, ``EINTR`` when a blocking read was interrupted, ``EMSGSIZE`` when\n+the buffer cannot hold the record at the head of the queue, and ``ENODEV``\n+once a removed device's queue has been drained.\n+\n+Queries and fragments\n+=====================\n+\n+A query's answer may be larger than the buffer the caller wants to commit, so\n+the kernel fills the buffer with as much of it as fits where the tree can be\n+cut. The first call passes ``generation`` and ``cursor`` zero. On return:\n+\n+- the kernel puts the query's generation in ``generation``;\n+- ``cursor`` is nonzero when there is more to come, zero when the answer is\n+  complete;\n+- the reply root carries ``CTLV_ATTR_F_FRAG_MORE`` when the answer continues,\n+  and so does every nest still logically open at the cut.\n+\n+To continue, the caller repeats the call with the same ``op_id`` and request,\n+the returned ``cursor`` and the returned ``generation``, and reassembles by\n+concatenating the children of each still-open nest.\n+\n+One answer of three items, cut by a buffer that holds two::\n+\n+    call 1: cursor in = 0             call 2: cursor in = c\n+            cursor out = c                    cursor out = 0\n+\n+    +----------------------------+    +----------------------------+\n+    | root: FRAG_MORE            |    | root: (no FRAG_MORE)       |\n+    |  +-----------------------+ |    |  +-----------------------+ |\n+    |  | chunk: FRAG_MORE      | |    |  | chunk:                | |\n+    |  |  +------------------+ | |    |  |  +------------------+ | |\n+    |  |  | item: value = 1  | | |    |  |  | item: value = 3  | | |\n+    |  |  +------------------+ | |    |  |  +------------------+ | |\n+    |  |  | item: value = 2  | | |    |  +-----------------------+ |\n+    |  |  +------------------+ | |    +----------------------------+\n+    |  +-----------------------+ |\n+    +----------------------------+\n+\n+    reassembled: root -\u003e chunk -\u003e item(1), item(2), item(3)\n+\n+``FRAG_MORE`` on the root says the answer continues; on ``chunk`` it says the\n+next fragment resumes inside that same chunk. A complete nest does not carry\n+it, so a reader knows whether to append or to open a new nest beside it.\n+\n+Every continuing fragment adds at least one complete logical attr beyond its\n+repeated path, and a cursor value cannot recur within one logical reply.\n+A reader must reject either violation.\n+\n+A continuation whose generation no longer matches fails with ``-ESTALE``, and\n+the error information carries the expected and the current generation.\n+\n+Events\n+======\n+\n+An event reaches a file description that asked for it, and only that one:\n+\n+1. subscribe with the ``subscriptions-add`` action, naming operation IDs;\n+2. read records with ``read()``, one complete record per call;\n+3. unsubscribe with ``subscriptions-remove``.\n+\n+``poll()`` reports readability when a record is queued. Each record is a\n+header followed by exactly one root attribute::\n+\n+    struct ctlv_event_hdr {\n+            __u32 length;             /* header + aligned root */\n+            __u32 flags;              /* zero */\n+            __aligned_u64 op_id;      /* the event op that produced it */\n+            __aligned_u64 sequence;   /* per file description */\n+    };\n+\n+One ``read()`` returns one record, the header and the aligned root::\n+\n+    +---------------------------------------------------------------+ 0\n+    | length = 24 + CTLV_ALIGN(root.len)     | flags = 0            |\n+    +---------------------------------------------------------------+ 8\n+    | op_id: the event operation that produced this record          |\n+    +---------------------------------------------------------------+ 16\n+    | sequence: counted per file description                        |\n+    +---------------------------------------------------------------+ 24\n+    | root: len, flags = NESTED, attr_id = 0                        |\n+    |   the event's attributes, exactly as a reply carries them      |\n+    +---------------------------------------------------------------+ length\n+\n+A buffer shorter than ``length`` reads nothing and fails with ``-EMSGSIZE``. A\n+record is one message, bounded by ``CTLV_MAX_INLINE_MESSAGE_LEN``. A sequence\n+number is assigned to every eligible record, dropped ones included, so a gap in\n+the sequence is exactly what was lost.\n+\n+The queue is per file description: ``event-queue-get`` reports its length and\n+how much is in use, ``event-queue-set`` changes it up to\n+``CTLV_MAX_EVENT_QUEUE_LEN``. A record that does not fit is dropped, and the\n+next read returns an ``event-overflow`` record carrying the first and last\n+sequence numbers lost and how many records that was.\n+\n+Two events come from the root family:\n+\n+op-changed\n+    An operation with dynamic availability was enabled or disabled. The record\n+    carries the operation ID, the new state, and the state generation that\n+    ``ops-dump`` also reports, so a client can order dump against event.\n+\n+device-removed\n+    The device is gone. Operations fail from then on and the descriptor stays\n+    valid until it is closed.\n+\n+Blobs\n+=====\n+\n+An operation that moves more data than a message should carry declares a blob\n+attribute, and the caller passes a descriptor instead of the data: a nest\n+carrying the backing type, the length and the identifier of the memory. One\n+backing is defined:\n+\n+``va``\n+    Anonymous userspace memory of the calling process, named by an address in\n+    ``blob.address``.\n+\n+The backings an attribute accepts, the direction data may flow, the maximum\n+length and the required alignment are declared by the family and reported by\n+``op-schema-get``. Memory is acquired for the operation and released before it\n+returns; a descriptor the operation may not use is refused before the callback.\n+While the operation is in flight, userspace must not modify an ``input`` blob\n+or access an ``output`` or ``inout`` blob. Whether two descriptors overlap is\n+also the caller's responsibility. Keep every named VA mapping valid until the\n+operation returns.\n+\n+Introspection\n+=============\n+\n+Three queries describe a device to a program that was not compiled against it.\n+The CTLV core answers all three on every device.\n+\n+``families-dump``\n+    The device's family chain, root first, as a numeric ID and a name per\n+    entry. The authoritative answer to what the device is.\n+\n+``ops-dump``\n+    One entry per published operation: its ID, kind, required fd access,\n+    whether its availability is fixed or dynamic, whether it is currently\n+    disabled, and the message lengths that apply on this device. An\n+    unpublished operation has no entry and is indistinguishable from one no\n+    family ever declared. Event entries have no fd-access field.\n+\n+``op-schema-get``\n+    The whole tree of one operation: every attribute of the request and the\n+    reply, with its payload form, its bounds, its occurrence limit, and its\n+    unit and scale where it has them.\n+\n+A schema that describes a schema does not end, so it is reported through\n+re-entry: a node whose members are those of a level already described carries\n+``schema.reenters``, saying how many levels up that level is. A consumer that\n+follows ``reenters`` handles any depth.\n+\n+The lengths in ``ops-dump`` include whatever a descendant family added to an\n+inherited operation, so ask rather than compute: a family's generated maximum\n+is right for its own devices and a lower bound on a descendant's.\n+\n+Limits\n+======\n+\n+Implementation limits, not encoded maxima of the wire fields, so raising one\n+later is a compatible change::\n+\n+    CTLV_MAX_INLINE_MESSAGE_LEN   1 MiB    request roots, action replies,\n+                                           query fragments, event roots\n+    CTLV_MAX_ERROR_LEN            16 KiB   error information\n+    CTLV_MAX_NEST_DEPTH           32       levels, root at zero\n+    CTLV_DEFAULT_QUERY_REPLY_LEN  64 KiB   suggested query buffer\n+    CTLV_MAX_EVENT_QUEUE_LEN      16 MiB   per file description\ndiff --git a/Documentation/userspace-api/index.rst b/Documentation/userspace-api/index.rst\nindex a68b1bea57a85..d1b53c4e16ebb 100644\n--- a/Documentation/userspace-api/index.rst\n+++ b/Documentation/userspace-api/index.rst\n@@ -45,6 +45,7 @@ Devices and I/O\n    :maxdepth: 1\n \n    accelerators/ocxl\n+   ctlv\n    dma-buf-heaps\n    dma-buf-alloc-exchange\n    fwctl/index\ndiff --git a/Documentation/userspace-api/ioctl/ioctl-number.rst b/Documentation/userspace-api/ioctl/ioctl-number.rst\nindex 2fc53093752d1..e545669c773c7 100644\n--- a/Documentation/userspace-api/ioctl/ioctl-number.rst\n+++ b/Documentation/userspace-api/ioctl/ioctl-number.rst\n@@ -386,6 +386,8 @@ Code  Seq#    Include File                                             Comments\n                                                                        \u003cmailto:linux-hyperv@vger.kernel.org\u003e\n 0xBA  00-0F  uapi/linux/liveupdate.h                                   Pasha Tatashin\n                                                                        \u003cmailto:pasha.tatashin@soleen.com\u003e\n+0xBB  00-0F  uapi/linux/ctlv.h                                         CTLV\n+                                                                       \u003cmailto:jiri@resnulli.us\u003e\n 0xC0  00-0F  linux/usb/iowarrior.h\n 0xCA  00-0F  uapi/misc/cxl.h                                           Dead since 6.15\n 0xCA  10-2F  uapi/misc/ocxl.h\ndiff --git a/Documentation/virt/coco/tdx-guest.rst b/Documentation/virt/coco/tdx-guest.rst\nindex 46e316db6bb47..759497b1434a2 100644\n--- a/Documentation/virt/coco/tdx-guest.rst\n+++ b/Documentation/virt/coco/tdx-guest.rst\n@@ -50,3 +50,21 @@ TDX reference material is collected here:\n https://www.intel.com/content/www/us/en/developer/articles/technical/intel-trust-domain-extensions.html\n \n The driver is based on TDX module specification v1.0 and TDX GHCI specification v1.0.\n+\n+Kernel clients\n+==============\n+\n+``\u003clinux/tdx-guest.h\u003e`` exposes the same native service to one in-kernel\n+client.  The client receives the misc device as its lifetime anchor and a\n+complete ``struct tdx_guest_ops``.  The operations retrieve TDREPORT or Quote\n+bytes, read MRTD/RTMR values, extend an RTMR, and return immutable construction\n+fields.\n+\n+Registering a client attaches it immediately when the service is already\n+available.  Otherwise attachment occurs when the TDX guest driver finishes\n+initialization.  Driver removal calls the client's remove callback before\n+freeing report or Quote buffers.  Client unregistration similarly drains the\n+attachment before returning.\n+\n+The misc ioctl, TSM-report configfs interface, and TSM-MR sysfs attributes\n+remain independent frontends over the same native serialization and buffers.\ndiff --git a/MAINTAINERS b/MAINTAINERS\nindex 31699b112d3ef..a05d10976011f 100644\n--- a/MAINTAINERS\n+++ b/MAINTAINERS\n@@ -4331,6 +4331,17 @@ F:\trust/kernel/sync/atomic.rs\n F:\trust/kernel/sync/atomic/\n F:\trust/kernel/sync/refcount.rs\n \n+ATTESTATION SUBSYSTEM\n+M:\tJiri Pirko \u003cjiri@nvidia.com\u003e\n+L:\tlinux-security-module@vger.kernel.org\n+S:\tSupported\n+F:\tDocumentation/ctlv/abi/ctlv-attestation*\n+F:\tDocumentation/ctlv/specs/ctlv-attestation*\n+F:\tDocumentation/driver-api/attestation.rst\n+F:\tdrivers/attestation/\n+F:\tinclude/linux/attestation*\n+F:\tinclude/uapi/linux/ctlv_attestation*\n+\n ATTO EXPRESSSAS SAS/SATA RAID SCSI DRIVER\n M:\tBradley Grove \u003clinuxdrivers@attotech.com\u003e\n L:\tlinux-scsi@vger.kernel.org\n@@ -7001,6 +7012,18 @@ M:\tJaya Kumar \u003cjayakumar.alsa@gmail.com\u003e\n S:\tMaintained\n F:\tsound/pci/cs5535audio/\n \n+CTLV SUBSYSTEM\n+M:\tJiri Pirko \u003cjiri@resnulli.us\u003e\n+L:\tlinux-kernel@vger.kernel.org\n+S:\tMaintained\n+F:\tDocumentation/ctlv/\n+F:\tDocumentation/driver-api/ctlv.rst\n+F:\tDocumentation/userspace-api/ctlv.rst\n+F:\tdrivers/ctlv/\n+F:\tinclude/linux/ctlv*.h\n+F:\tinclude/uapi/linux/ctlv*.h\n+F:\ttools/ctlv/\n+\n CTU CAN FD DRIVER\n M:\tPavel Pisa \u003cpisa@cmp.felk.cvut.cz\u003e\n M:\tOndrej Ille \u003condrej.ille@gmail.com\u003e\n@@ -29646,6 +29669,9 @@ L:\tlinux-coco@lists.linux.dev\n L:\tkvm@vger.kernel.org\n S:\tSupported\n T:\tgit git://git.kernel.org/pub/scm/linux/kernel/git/tip/tip.git x86/tdx\n+F:\tDocumentation/virt/coco/tdx-guest.rst\n+F:\tdrivers/virt/coco/tdx-guest/\n+F:\tinclude/linux/tdx-guest.h\n N:\ttdx\n K:\t\\b(tdx)\n \ndiff --git a/drivers/Kconfig b/drivers/Kconfig\nindex f2bed2ddeb662..971db1f0192ca 100644\n--- a/drivers/Kconfig\n+++ b/drivers/Kconfig\n@@ -25,6 +25,10 @@ source \"drivers/cache/Kconfig\"\n \n source \"drivers/connector/Kconfig\"\n \n+source \"drivers/ctlv/Kconfig\"\n+\n+source \"drivers/attestation/Kconfig\"\n+\n source \"drivers/firmware/Kconfig\"\n \n source \"drivers/fwctl/Kconfig\"\ndiff --git a/drivers/Makefile b/drivers/Makefile\nindex 0841ea851847e..2b4dfc8e256b0 100644\n--- a/drivers/Makefile\n+++ b/drivers/Makefile\n@@ -135,6 +135,8 @@ obj-$(CONFIG_MEMSTICK)\t\t+= memstick/\n obj-$(CONFIG_INFINIBAND)\t+= infiniband/\n obj-y\t\t\t\t+= firmware/\n obj-$(CONFIG_FWCTL)\t\t+= fwctl/\n+obj-$(CONFIG_CTLV)\t\t+= ctlv/\n+obj-$(CONFIG_ATTESTATION)\t+= attestation/\n obj-$(CONFIG_CRYPTO)\t\t+= crypto/\n obj-$(CONFIG_SUPERH)\t\t+= sh/\n obj-y\t\t\t\t+= clocksource/\ndiff --git a/drivers/attestation/Kconfig b/drivers/attestation/Kconfig\nnew file mode 100644\nindex 0000000000000..139bcc7100191\n--- /dev/null\n+++ b/drivers/attestation/Kconfig\n@@ -0,0 +1,26 @@\n+# SPDX-License-Identifier: GPL-2.0-only\n+menuconfig ATTESTATION\n+\ttristate \"Attestation\"\n+\tdepends on CTLV\n+\thelp\n+\t  Provides a CTLV family for evidence, measurement registers,\n+\t  and an append-only measurement journal.\n+\n+\t  Providers register one instance for a physical or logical device and\n+\t  translate the common operations to their native service.\n+\n+\t  If you are unsure, say N.\n+\n+if ATTESTATION\n+\n+config ATTESTATION_TDX\n+\ttristate \"TDX attestation provider\"\n+\tdepends on TDX_GUEST_DRIVER\n+\thelp\n+\t  Exposes TDREPORT, Quote, MRTD and RTMR operations through the common\n+\t  attestation CTLV family. The native TDX misc, TSM-report and TSM-MR\n+\t  interfaces remain available independently.\n+\n+\t  If you are unsure, say N.\n+\n+endif # ATTESTATION\ndiff --git a/drivers/attestation/Makefile b/drivers/attestation/Makefile\nnew file mode 100644\nindex 0000000000000..d56df9adaa757\n--- /dev/null\n+++ b/drivers/attestation/Makefile\n@@ -0,0 +1,10 @@\n+# SPDX-License-Identifier: GPL-2.0\n+obj-$(CONFIG_ATTESTATION) += attestation.o\n+\n+attestation-y := core/core.o core/ctlv.o core/events.o core/mr.o \\\n+\t\t generated/ctlv_attestation_gen.o\n+\n+obj-$(CONFIG_ATTESTATION_TDX) += attestation-tdx.o\n+\n+attestation-tdx-y := providers/tdx.o \\\n+\t\t     generated/ctlv_attestation_tdx_gen.o\ndiff --git a/drivers/attestation/core/core.c b/drivers/attestation/core/core.c\nnew file mode 100644\nindex 0000000000000..3fb58f344663b\n--- /dev/null\n+++ b/drivers/attestation/core/core.c\n@@ -0,0 +1,354 @@\n+// SPDX-License-Identifier: GPL-2.0-only\n+#include \u003ccrypto/hash_info.h\u003e\n+#include \u003clinux/cleanup.h\u003e\n+#include \u003clinux/ctlv.h\u003e\n+#include \u003clinux/device.h\u003e\n+#include \u003clinux/err.h\u003e\n+#include \u003clinux/limits.h\u003e\n+#include \u003clinux/module.h\u003e\n+#include \u003clinux/overflow.h\u003e\n+#include \u003clinux/slab.h\u003e\n+#include \u003clinux/string.h\u003e\n+\n+#include \"internal.h\"\n+\n+static DEFINE_XARRAY(attestation_instances);\n+\n+static DEFINE_MUTEX(attestation_registry_lock);\n+static unsigned long attestation_next_index;\n+\n+static bool attestation_algorithm_valid(enum hash_algo algorithm)\n+{\n+\treturn algorithm \u003e= 0 \u0026\u0026 algorithm \u003c HASH_ALGO__LAST \u0026\u0026 hash_digest_size[algorithm] \u0026\u0026\n+\t       hash_digest_size[algorithm] \u003c= HASH_MAX_DIGESTSIZE;\n+}\n+\n+static int attestation_mr_props_validate(const struct attestation_provider *provider,\n+\t\t\t\t\t const struct attestation_mr_props *props)\n+{\n+\tsize_t index;\n+\n+\tif (!props || !props-\u003ename || !*props-\u003ename || strlen(props-\u003ename) \u003e 128 ||\n+\t    !props-\u003ealgorithms || !props-\u003ealgorithms_count || props-\u003ealgorithms_count \u003e 21)\n+\t\treturn -EINVAL;\n+\tfor (index = 0; index \u003c props-\u003ealgorithms_count; index++) {\n+\t\tenum hash_algo algorithm = props-\u003ealgorithms[index];\n+\n+\t\tif (!attestation_algorithm_valid(algorithm) ||\n+\t\t    (index \u0026\u0026 props-\u003ealgorithms[index - 1] \u003e= algorithm))\n+\t\t\treturn -EINVAL;\n+\t}\n+\tif (props-\u003ereadable \u0026\u0026 !provider-\u003emr_read)\n+\t\treturn -EINVAL;\n+\tif (props-\u003eextendable \u0026\u0026 !provider-\u003emr_extend)\n+\t\treturn -EINVAL;\n+\treturn 0;\n+}\n+\n+static int attestation_evidence_caps_validate(const struct attestation_provider *provider)\n+{\n+\tconst struct attestation_evidence_caps *caps = provider-\u003eevidence_caps;\n+\tsize_t object_index;\n+\n+\tif (!caps)\n+\t\treturn provider-\u003eevidence_get ? -EINVAL : 0;\n+\tif (!provider-\u003eevidence_get || !caps-\u003eobjects || !caps-\u003eobjects_count ||\n+\t    caps-\u003eobjects_count \u003e 16 || caps-\u003emin_challenge_length \u003e caps-\u003emax_challenge_length ||\n+\t    caps-\u003emax_challenge_length \u003e 4096 || !caps-\u003emax_total_output_length)\n+\t\treturn -EINVAL;\n+\tfor (object_index = 0; object_index \u003c caps-\u003eobjects_count; object_index++) {\n+\t\tconst struct attestation_evidence_supported_object *object =\n+\t\t\t\u0026caps-\u003eobjects[object_index];\n+\t\tsize_t index;\n+\n+\t\tif (!object-\u003eformat || !*object-\u003eformat || strlen(object-\u003eformat) \u003e 128 ||\n+\t\t    !object-\u003emax_length || object-\u003emax_length \u003e UINT_MAX ||\n+\t\t    object-\u003emax_length \u003e caps-\u003emax_total_output_length)\n+\t\t\treturn -EINVAL;\n+\t\tfor (index = 0; index \u003c object_index; index++) {\n+\t\t\tconst struct attestation_evidence_supported_object *prior =\n+\t\t\t\t\u0026caps-\u003eobjects[index];\n+\n+\t\t\tif (!strcmp(prior-\u003eformat, object-\u003eformat))\n+\t\t\t\treturn -EINVAL;\n+\t\t}\n+\t}\n+\treturn 0;\n+}\n+\n+int attestation_provider_validate(const struct attestation_provider *provider)\n+{\n+\tsize_t index;\n+\tint ret;\n+\n+\tif (!provider)\n+\t\treturn -EINVAL;\n+\tret = attestation_evidence_caps_validate(provider);\n+\tif (ret)\n+\t\treturn ret;\n+\tif (!!provider-\u003emrs != !!provider-\u003emrs_count)\n+\t\treturn -EINVAL;\n+\tif ((provider-\u003emr_read || provider-\u003emr_extend) \u0026\u0026 !provider-\u003emrs_count)\n+\t\treturn -EINVAL;\n+\tfor (index = 0; index \u003c provider-\u003emrs_count; index++) {\n+\t\tret = attestation_mr_props_validate(provider, \u0026provider-\u003emrs[index]);\n+\t\tif (ret)\n+\t\t\treturn ret;\n+\t}\n+\treturn 0;\n+}\n+\n+static bool attestation_parent_exists(struct device *parent)\n+{\n+\tstruct attestation *att;\n+\tunsigned long index;\n+\n+\txa_for_each(\u0026attestation_instances, index, att)\n+\t\tif (ctlv_device_parent(att-\u003ectlvdev) == parent)\n+\t\t\treturn true;\n+\treturn false;\n+}\n+\n+static int attestation_registry_insert(struct attestation *att)\n+{\n+\tunsigned long index;\n+\tvoid *old;\n+\tint ret;\n+\n+\tguard(mutex)\n+\t\t(\u0026attestation_registry_lock);\n+\tif (attestation_next_index \u003e UINT_MAX)\n+\t\treturn -ENOSPC;\n+\tindex = attestation_next_index;\n+\tret = xa_reserve(\u0026attestation_instances, index, GFP_KERNEL);\n+\tif (ret)\n+\t\treturn ret;\n+\n+\txa_lock(\u0026attestation_instances);\n+\tif (attestation_parent_exists(ctlv_device_parent(att-\u003ectlvdev))) {\n+\t\t__xa_erase(\u0026attestation_instances, index);\n+\t\tret = -EEXIST;\n+\t\tgoto out_unlock;\n+\t}\n+\told = __xa_store(\u0026attestation_instances, index, att, GFP_NOWAIT);\n+\tret = xa_err(old);\n+\tif (!ret) {\n+\t\tatt-\u003eindex = index;\n+\t\tattestation_next_index++;\n+\t}\n+out_unlock:\n+\txa_unlock(\u0026attestation_instances);\n+\treturn ret;\n+}\n+\n+static void attestation_registry_remove(struct attestation *att)\n+{\n+\txa_erase(\u0026attestation_instances, att-\u003eindex);\n+}\n+\n+bool attestation_registered(struct attestation *att)\n+{\n+\tbool registered;\n+\n+\tlockdep_assert_held(\u0026att-\u003elock);\n+\txa_lock(\u0026attestation_instances);\n+\tregistered = xa_get_mark(\u0026attestation_instances, att-\u003eindex, ATTESTATION_REGISTERED);\n+\txa_unlock(\u0026attestation_instances);\n+\treturn registered;\n+}\n+\n+void attestation_mr_changed(struct attestation *att)\n+{\n+\tlockdep_assert_held(\u0026att-\u003elock);\n+\tatt-\u003elog-\u003egeneration++;\n+\tatt-\u003emr_read_generation++;\n+}\n+\n+void attestation_stop(struct attestation *att)\n+{\n+\tlockdep_assert_held(\u0026att-\u003elock);\n+\txa_lock(\u0026attestation_instances);\n+\t__xa_clear_mark(\u0026attestation_instances, att-\u003eindex, ATTESTATION_REGISTERED);\n+\txa_unlock(\u0026attestation_instances);\n+}\n+\n+static struct attestation_mr *attestation_mr_alloc(struct attestation *att,\n+\t\t\t\t\t\t   const struct attestation_mr_props *props)\n+{\n+\tstruct attestation_mr *mr;\n+\tint ret;\n+\n+\tret = attestation_mr_props_validate(att-\u003eprovider, props);\n+\tif (ret)\n+\t\treturn ERR_PTR(ret);\n+\tif (xa_load(\u0026att-\u003emrs, props-\u003eid))\n+\t\treturn ERR_PTR(-EEXIST);\n+\tmr = kzalloc_obj(*mr, GFP_KERNEL);\n+\tif (!mr)\n+\t\treturn ERR_PTR(-ENOMEM);\n+\tmr-\u003eprops = props;\n+\tret = xa_insert(\u0026att-\u003emrs, props-\u003eid, mr, GFP_KERNEL);\n+\tif (ret) {\n+\t\tkfree(mr);\n+\t\treturn ERR_PTR(ret);\n+\t}\n+\treturn mr;\n+}\n+\n+struct attestation_mr *attestation_mr_lookup_live(struct attestation *att, unsigned int mr_id)\n+{\n+\tstruct attestation_mr *mr;\n+\n+\tlockdep_assert_held(\u0026att-\u003elock);\n+\tmr = xa_load(\u0026att-\u003emrs, mr_id);\n+\treturn mr ? mr : ERR_PTR(-ENOENT);\n+}\n+\n+void attestation_provide_ops(struct attestation *att)\n+{\n+\tconst struct attestation_provider *provider = att-\u003eprovider;\n+\tstruct ctlv_device *ctlvdev = att-\u003ectlvdev;\n+\n+\tif (provider-\u003eevidence_caps) {\n+\t\tctlv_attestation_evidence_get_provide(ctlvdev);\n+\t\tctlv_attestation_evidence_get_enable(ctlvdev);\n+\t}\n+\tif (provider-\u003emrs_count) {\n+\t\tctlv_attestation_mr_get_provide(ctlvdev);\n+\t\tctlv_attestation_mr_dump_provide(ctlvdev);\n+\t\tctlv_attestation_mr_log_get_provide(ctlvdev);\n+\t\tif (provider-\u003emr_read)\n+\t\t\tctlv_attestation_mr_read_provide(ctlvdev);\n+\t\tif (provider-\u003emr_extend)\n+\t\t\tctlv_attestation_mr_extend_provide(ctlvdev);\n+\t}\n+}\n+\n+int attestation_core_init(struct attestation *att, struct ctlv_device *ctlvdev,\n+\t\t\t  const struct attestation_provider *provider)\n+{\n+\tsize_t index;\n+\tint ret;\n+\n+\tret = attestation_provider_validate(provider);\n+\tif (ret)\n+\t\treturn ret;\n+\tmutex_init(\u0026att-\u003elock);\n+\txa_init(\u0026att-\u003emrs);\n+\tatt-\u003ectlvdev = ctlvdev;\n+\tatt-\u003eprovider = provider;\n+\tfor (index = 0; index \u003c provider-\u003emrs_count; index++) {\n+\t\tstruct attestation_mr *mr;\n+\n+\t\tmr = attestation_mr_alloc(att, \u0026provider-\u003emrs[index]);\n+\t\tif (IS_ERR(mr)) {\n+\t\t\tret = PTR_ERR(mr);\n+\t\t\tgoto err_mrs;\n+\t\t}\n+\t}\n+\tret = attestation_registry_insert(att);\n+\tif (ret)\n+\t\tgoto err_mrs;\n+\tattestation_provide_ops(att);\n+\tatt-\u003einitialized = true;\n+\treturn 0;\n+\n+err_mrs:\n+\tattestation_core_fini(att);\n+\treturn ret;\n+}\n+\n+void attestation_core_fini(struct attestation *att)\n+{\n+\tstruct attestation_mr *mr;\n+\tunsigned long index;\n+\n+\tif (!att-\u003ectlvdev)\n+\t\treturn;\n+\tif (att-\u003einitialized)\n+\t\tattestation_registry_remove(att);\n+\txa_for_each(\u0026att-\u003emrs, index, mr) {\n+\t\txa_erase(\u0026att-\u003emrs, index);\n+\t\tkfree(mr);\n+\t}\n+\tattestation_mr_log_free(att-\u003elog);\n+\txa_destroy(\u0026att-\u003emrs);\n+\tmutex_destroy(\u0026att-\u003elock);\n+\tatt-\u003ectlvdev = NULL;\n+}\n+\n+size_t ctlv_attestation_priv_size(void)\n+{\n+\treturn sizeof(struct attestation);\n+}\n+\n+int ctlv_attestation_init(struct ctlv_device *ctlvdev, const void *init_info, void *priv)\n+{\n+\treturn attestation_core_init(priv, ctlvdev, init_info);\n+}\n+\n+int ctlv_attestation_post_init(struct ctlv_device *ctlvdev, void *priv)\n+{\n+\tstruct attestation *att = priv;\n+\tint ret;\n+\n+\tret = attestation_mr_log_init(att);\n+\tif (ret)\n+\t\treturn ret;\n+\txa_lock(\u0026attestation_instances);\n+\t__xa_set_mark(\u0026attestation_instances, att-\u003eindex, ATTESTATION_REGISTERED);\n+\txa_unlock(\u0026attestation_instances);\n+\treturn 0;\n+}\n+\n+void ctlv_attestation_pre_fini(struct ctlv_device *ctlvdev, void *priv)\n+{\n+\tstruct attestation *att = priv;\n+\n+\txa_lock(\u0026attestation_instances);\n+\t__xa_clear_mark(\u0026attestation_instances, att-\u003eindex, ATTESTATION_REGISTERED);\n+\txa_unlock(\u0026attestation_instances);\n+}\n+\n+void ctlv_attestation_fini(struct ctlv_device *ctlvdev, void *priv)\n+{\n+\tattestation_core_fini(priv);\n+}\n+\n+int ctlv_attestation_op_pre(void *priv, struct ctlv_op_ctx *ctx)\n+{\n+\tstruct attestation *att = priv;\n+\n+\tmutex_lock(\u0026att-\u003elock);\n+\tif (!attestation_registered(att)) {\n+\t\tmutex_unlock(\u0026att-\u003elock);\n+\t\treturn -ENODEV;\n+\t}\n+\treturn 0;\n+}\n+EXPORT_SYMBOL_NS_GPL(ctlv_attestation_op_pre, \"ATTESTATION\");\n+\n+void ctlv_attestation_op_post(void *priv, struct ctlv_op_ctx *ctx)\n+{\n+\tstruct attestation *att = priv;\n+\n+\tmutex_unlock(\u0026att-\u003elock);\n+}\n+EXPORT_SYMBOL_NS_GPL(ctlv_attestation_op_post, \"ATTESTATION\");\n+\n+static int __init attestation_module_init(void)\n+{\n+\treturn 0;\n+}\n+\n+static void __exit attestation_module_exit(void)\n+{\n+\tWARN_ON_ONCE(!xa_empty(\u0026attestation_instances));\n+\txa_destroy(\u0026attestation_instances);\n+}\n+\n+module_init(attestation_module_init);\n+module_exit(attestation_module_exit);\n+MODULE_DESCRIPTION(\"Attestation core\");\n+MODULE_LICENSE(\"GPL\");\n+MODULE_IMPORT_NS(\"CTLV\");\ndiff --git a/drivers/attestation/core/ctlv.c b/drivers/attestation/core/ctlv.c\nnew file mode 100644\nindex 0000000000000..ff19400843c2c\n--- /dev/null\n+++ b/drivers/attestation/core/ctlv.c\n@@ -0,0 +1,520 @@\n+// SPDX-License-Identifier: GPL-2.0-only\n+#include \u003ccrypto/hash_info.h\u003e\n+#include \u003clinux/cleanup.h\u003e\n+#include \u003clinux/err.h\u003e\n+#include \u003clinux/limits.h\u003e\n+#include \u003clinux/slab.h\u003e\n+#include \u003clinux/sort.h\u003e\n+#include \u003clinux/string.h\u003e\n+\n+#include \"internal.h\"\n+\n+static const struct attestation_evidence_supported_object *\n+attestation_evidence_object_find(const struct attestation_evidence_caps *caps, const char *format)\n+{\n+\tsize_t index;\n+\n+\tfor (index = 0; index \u003c caps-\u003eobjects_count; index++) {\n+\t\tconst struct attestation_evidence_supported_object *object = \u0026caps-\u003eobjects[index];\n+\n+\t\tif (!strcmp(object-\u003eformat, format))\n+\t\t\treturn object;\n+\t}\n+\treturn NULL;\n+}\n+\n+static int attestation_device_caps_put(struct attestation *att, struct ctlv_cursor *reply)\n+{\n+\tconst struct attestation_provider *provider = att-\u003eprovider;\n+\tstruct ctlv_cursor caps_nest, group, object;\n+\tbool ok = true;\n+\tsize_t index;\n+\tu64 flags;\n+\n+\tif (!ctlv_attestation_device_caps_start(reply, \u0026caps_nest))\n+\t\treturn -EMSGSIZE;\n+\tif (provider-\u003eevidence_caps) {\n+\t\tconst struct attestation_evidence_caps *caps = provider-\u003eevidence_caps;\n+\t\tu64 blob_class = CTLV_ATTESTATION_EVIDENCE_BLOB_CLASS_PRIMARY;\n+\t\tu64 representation = CTLV_ATTESTATION_EVIDENCE_REPRESENTATION_RAW;\n+\t\tu64 max_output_length = caps-\u003emax_total_output_length;\n+\n+\t\tif (!ctlv_attestation_cap_evidence_start(\u0026caps_nest, \u0026group))\n+\t\t\treturn -EMSGSIZE;\n+\t\tok \u0026= ctlv_attestation_cap_min_challenge_length_put(\u0026group,\n+\t\t\t\t\t\t\t\t    caps-\u003emin_challenge_length);\n+\t\tok \u0026= ctlv_attestation_cap_max_challenge_length_put(\u0026group,\n+\t\t\t\t\t\t\t\t    caps-\u003emax_challenge_length);\n+\t\tok \u0026= ctlv_attestation_cap_max_total_output_length_put(\u0026group, max_output_length);\n+\t\tfor (index = 0; index \u003c caps-\u003eobjects_count; index++) {\n+\t\t\tconst struct attestation_evidence_supported_object *cap =\n+\t\t\t\t\u0026caps-\u003eobjects[index];\n+\n+\t\t\tif (!ctlv_attestation_cap_object_start(\u0026group, \u0026object)) {\n+\t\t\t\tok = false;\n+\t\t\t\tbreak;\n+\t\t\t}\n+\t\t\tok \u0026= ctlv_attestation_cap_blob_class_put(\u0026object, blob_class);\n+\t\t\tok \u0026= ctlv_attestation_cap_format_put(\u0026object, cap-\u003eformat);\n+\t\t\tok \u0026= ctlv_attestation_cap_representation_put(\u0026object, representation);\n+\t\t\tok \u0026= ctlv_attestation_cap_max_length_put(\u0026object, cap-\u003emax_length);\n+\t\t\tctlv_nest_end(\u0026object);\n+\t\t}\n+\t\tctlv_nest_end(\u0026group);\n+\t}\n+\tif (provider-\u003emrs_count) {\n+\t\tif (!ctlv_attestation_cap_mr_start(\u0026caps_nest, \u0026group))\n+\t\t\treturn -EMSGSIZE;\n+\t\tflags = 0;\n+\t\tif (provider-\u003emr_read)\n+\t\t\tflags |= CTLV_ATTESTATION_MR_DEVICE_CAPS_READ;\n+\t\tif (provider-\u003emr_extend)\n+\t\t\tflags |= CTLV_ATTESTATION_MR_DEVICE_CAPS_EXTEND;\n+\t\tok \u0026= ctlv_attestation_cap_mr_flags_put(\u0026group, flags);\n+\t\tctlv_nest_end(\u0026group);\n+\t}\n+\tctlv_nest_end(\u0026caps_nest);\n+\treturn ok ? 0 : -EMSGSIZE;\n+}\n+\n+int ctlv_attestation_device_get_action(void *priv, struct ctlv_op_ctx *ctx,\n+\t\t\t\t       const struct ctlv_cursor *request, struct ctlv_cursor *reply)\n+{\n+\tstruct attestation *att = priv;\n+\tstruct ctlv_cursor info;\n+\tint ret;\n+\n+\tret = attestation_device_caps_put(att, reply);\n+\tif (ret)\n+\t\treturn ret;\n+\tif (!ctlv_attestation_device_info_start(reply, \u0026info))\n+\t\treturn -EMSGSIZE;\n+\tret = ctlv_stub_fill(ctx, request, \u0026info);\n+\tctlv_nest_end(\u0026info);\n+\treturn ret;\n+}\n+\n+static int\n+attestation_evidence_decode_objects(struct attestation *att, struct ctlv_op_ctx *ctx,\n+\t\t\t\t    const struct ctlv_cursor *request,\n+\t\t\t\t    struct attestation_evidence_request *decoded,\n+\t\t\t\t    struct attestation_evidence_object_request **objects_out)\n+{\n+\tconst struct attestation_evidence_caps *caps = att-\u003eprovider-\u003eevidence_caps;\n+\tstruct attestation_evidence_object_request *objects;\n+\tstruct ctlv_cursor object;\n+\tsize_t count = 0, index = 0, previous;\n+\n+\tctlv_attestation_evidence_get_evidence_object_for_each(\u0026object, request) count++;\n+\tobjects = kcalloc(count, sizeof(*objects), GFP_KERNEL);\n+\tif (!objects)\n+\t\treturn -ENOMEM;\n+\tctlv_attestation_evidence_get_evidence_object_for_each(\u0026object, request)\n+\t{\n+\t\tconst struct attestation_evidence_supported_object *supported;\n+\t\tconst char *format;\n+\t\tsize_t total = 0;\n+\n+\t\tformat = ctlv_attestation_evidence_get_object_evidence_format_get(\u0026object);\n+\t\tsupported = attestation_evidence_object_find(caps, format);\n+\t\tif (!supported) {\n+\t\t\tkfree(objects);\n+\t\t\treturn -EOPNOTSUPP;\n+\t\t}\n+\t\tfor (previous = 0; previous \u003c index; previous++)\n+\t\t\tif (objects[previous].supported_object == supported) {\n+\t\t\t\tkfree(objects);\n+\t\t\t\treturn -EINVAL;\n+\t\t\t}\n+\t\tobjects[index].supported_object = supported;\n+\t\tobjects[index].output =\n+\t\t\tctlv_attestation_evidence_get_object_evidence_data_resolve(ctx, \u0026object);\n+\t\tif (IS_ERR(objects[index].output)) {\n+\t\t\tint ret = PTR_ERR(objects[index].output);\n+\n+\t\t\tobjects[index].output = NULL;\n+\t\t\twhile (index)\n+\t\t\t\tctlv_blob_put(objects[--index].output);\n+\t\t\tkfree(objects);\n+\t\t\treturn ret;\n+\t\t}\n+\t\tif (ctlv_blob_len(objects[index].output) \u003c supported-\u003emax_length) {\n+\t\t\tfor (previous = 0; previous \u003c= index; previous++)\n+\t\t\t\tctlv_blob_put(objects[previous].output);\n+\t\t\tkfree(objects);\n+\t\t\treturn -EMSGSIZE;\n+\t\t}\n+\t\tfor (previous = 0; previous \u003c= index; previous++) {\n+\t\t\tif (check_add_overflow(total, ctlv_blob_len(objects[previous].output),\n+\t\t\t\t\t       \u0026total) ||\n+\t\t\t    total \u003e caps-\u003emax_total_output_length) {\n+\t\t\t\tfor (previous = 0; previous \u003c= index; previous++)\n+\t\t\t\t\tctlv_blob_put(objects[previous].output);\n+\t\t\t\tkfree(objects);\n+\t\t\t\treturn -E2BIG;\n+\t\t\t}\n+\t\t}\n+\t\tindex++;\n+\t}\n+\tdecoded-\u003eobjects = objects;\n+\tdecoded-\u003eobjects_count = count;\n+\t*objects_out = objects;\n+\treturn 0;\n+}\n+\n+static int attestation_evidence_request_decode(struct attestation *att, struct ctlv_op_ctx *ctx,\n+\t\t\t\t\t       const struct ctlv_cursor *request,\n+\t\t\t\t\t       struct attestation_evidence_request *decoded,\n+\t\t\t\t\t       struct attestation_evidence_object_request **objects)\n+{\n+\tconst struct attestation_evidence_caps *caps = att-\u003eprovider-\u003eevidence_caps;\n+\tu32 challenge_length;\n+\n+\tdecoded-\u003echallenge =\n+\t\tctlv_attestation_evidence_get_evidence_challenge_get(request, \u0026challenge_length);\n+\tdecoded-\u003echallenge_length = challenge_length;\n+\tif (challenge_length \u003c caps-\u003emin_challenge_length ||\n+\t    challenge_length \u003e caps-\u003emax_challenge_length)\n+\t\treturn -EINVAL;\n+\treturn attestation_evidence_decode_objects(att, ctx, request, decoded, objects);\n+}\n+\n+static void attestation_evidence_request_free(struct attestation_evidence_object_request *objects,\n+\t\t\t\t\t      size_t count)\n+{\n+\twhile (count) {\n+\t\tcount--;\n+\t\tif (objects[count].output)\n+\t\t\tctlv_blob_put(objects[count].output);\n+\t}\n+\tkfree(objects);\n+}\n+\n+int ctlv_attestation_evidence_get_action(void *priv, struct ctlv_op_ctx *ctx,\n+\t\t\t\t\t const struct ctlv_cursor *request,\n+\t\t\t\t\t struct ctlv_cursor *reply)\n+{\n+\tstruct attestation_evidence_object_request *objects = NULL;\n+\tstruct attestation_evidence_request decoded = {};\n+\tstruct attestation_evidence_result result = {};\n+\tstruct attestation *att = priv;\n+\tbool mr_dependent = false;\n+\tsize_t index;\n+\tint put_ret;\n+\tint ret;\n+\n+\tret = attestation_evidence_request_decode(att, ctx, request, \u0026decoded, \u0026objects);\n+\tif (ret)\n+\t\tgoto out;\n+\tresult.object_lengths =\n+\t\tkcalloc(decoded.objects_count, sizeof(*result.object_lengths), GFP_KERNEL);\n+\tif (!result.object_lengths) {\n+\t\tret = -ENOMEM;\n+\t\tgoto out;\n+\t}\n+\tfor (index = 0; index \u003c decoded.objects_count; index++)\n+\t\tmr_dependent |= decoded.objects[index].supported_object-\u003ebinds_mrs;\n+\tret = att-\u003eprovider-\u003eevidence_get(att, \u0026decoded, \u0026result);\n+\tif (ret)\n+\t\tgoto out;\n+\tfor (index = 0; index \u003c decoded.objects_count; index++) {\n+\t\tif (result.object_lengths[index] \u003e\n+\t\t\t    decoded.objects[index].supported_object-\u003emax_length ||\n+\t\t    result.object_lengths[index] \u003e ctlv_blob_len(decoded.objects[index].output)) {\n+\t\t\tret = -E2BIG;\n+\t\t\tgoto out;\n+\t\t}\n+\t}\n+\tfor (index = 0; index \u003c decoded.objects_count; index++) {\n+\t\tput_ret = ctlv_blob_put(decoded.objects[index].output);\n+\t\tobjects[index].output = NULL;\n+\t\tif (!ret)\n+\t\t\tret = put_ret;\n+\t}\n+\tif (ret)\n+\t\tgoto out;\n+\tif (mr_dependent \u0026\u0026 !ctlv_attestation_mr_generation_put(reply, att-\u003elog-\u003egeneration)) {\n+\t\tret = -EMSGSIZE;\n+\t\tgoto out;\n+\t}\n+\tfor (index = 0; index \u003c decoded.objects_count; index++)\n+\t\tif (!ctlv_attestation_evidence_object_length_put(reply,\n+\t\t\t\t\t\t\t\t result.object_lengths[index])) {\n+\t\t\tret = -EMSGSIZE;\n+\t\t\tgoto out;\n+\t\t}\n+out:\n+\tkfree(result.object_lengths);\n+\tattestation_evidence_request_free(objects, decoded.objects_count);\n+\treturn ret;\n+}\n+\n+int ctlv_attestation_mr_get_action(void *priv, struct ctlv_op_ctx *ctx,\n+\t\t\t\t   const struct ctlv_cursor *request, struct ctlv_cursor *reply)\n+{\n+\tstruct attestation *att = priv;\n+\tstruct attestation_mr *mr;\n+\tu64 id = ctlv_attestation_mr_get_mr_id_get(request);\n+\n+\tif (id \u003e UINT_MAX)\n+\t\treturn -ERANGE;\n+\tmr = attestation_mr_lookup_live(att, id);\n+\treturn IS_ERR(mr) ? PTR_ERR(mr) : attestation_mr_props_encode(reply, mr, false);\n+}\n+\n+int ctlv_attestation_mr_dump_query(void *priv, struct ctlv_op_ctx *ctx,\n+\t\t\t\t   const struct ctlv_cursor *request, struct ctlv_cursor *reply)\n+{\n+\tstruct attestation *att = priv;\n+\tstruct attestation_mr *mr;\n+\tstruct ctlv_cursor nested;\n+\tunsigned long id;\n+\tu64 cursor = ctlv_op_query_cursor(ctx);\n+\tunsigned int generation = att-\u003elog-\u003egeneration;\n+\tint ret;\n+\n+\tif (cursor \u0026\u0026 ctlv_op_query_generation(ctx) != generation)\n+\t\treturn -ESTALE;\n+\tid = cursor ? cursor - 1 : 0;\n+\tmr = xa_find(\u0026att-\u003emrs, \u0026id, UINT_MAX, XA_PRESENT);\n+\twhile (mr) {\n+\t\tif (!ctlv_attestation_mr_item_start(reply, \u0026nested))\n+\t\t\treturn ctlv_op_query_more(ctx, generation, id + 1);\n+\t\tret = attestation_mr_props_encode(\u0026nested, mr, true);\n+\t\tctlv_nest_end(\u0026nested);\n+\t\tif (ret)\n+\t\t\treturn ret;\n+\t\tmr = xa_find_after(\u0026att-\u003emrs, \u0026id, UINT_MAX, XA_PRESENT);\n+\t}\n+\treturn ctlv_op_query_done(ctx, generation);\n+}\n+\n+static int attestation_mr_values_put(struct ctlv_cursor *reply,\n+\t\t\t\t     const struct attestation_digest_set *values)\n+{\n+\tstruct ctlv_cursor nested;\n+\tsize_t index;\n+\tbool ok;\n+\n+\tfor (index = 0; index \u003c values-\u003evalues_count; index++) {\n+\t\tconst struct attestation_digest *value = \u0026values-\u003evalues[index];\n+\t\tenum hash_algo algorithm = value-\u003ealgorithm;\n+\t\tsize_t length = hash_digest_size[algorithm];\n+\n+\t\tif (!ctlv_attestation_mr_value_start(reply, \u0026nested))\n+\t\t\treturn -EMSGSIZE;\n+\t\tok = ctlv_attestation_mr_hash_algo_put(\u0026nested, algorithm);\n+\t\tok \u0026= ctlv_attestation_mr_data_put(\u0026nested, value-\u003edata, length);\n+\t\tctlv_nest_end(\u0026nested);\n+\t\tif (!ok)\n+\t\t\treturn -EMSGSIZE;\n+\t}\n+\treturn 0;\n+}\n+\n+int ctlv_attestation_mr_read_query(void *priv, struct ctlv_op_ctx *ctx,\n+\t\t\t\t   const struct ctlv_cursor *request, struct ctlv_cursor *reply)\n+{\n+\tstruct attestation_digest_set values = {};\n+\tstruct attestation *att = priv;\n+\tstruct attestation_mr *mr;\n+\tu64 id;\n+\tint ret;\n+\n+\tif (ctlv_op_query_cursor(ctx) \u0026\u0026\n+\t    ctlv_op_query_generation(ctx) != att-\u003emr_read_generation)\n+\t\treturn -ESTALE;\n+\tid = ctlv_attestation_mr_read_mr_id_get(request);\n+\tif (id \u003e UINT_MAX)\n+\t\treturn -ERANGE;\n+\tmr = attestation_mr_lookup_live(att, id);\n+\tif (IS_ERR(mr))\n+\t\treturn PTR_ERR(mr);\n+\tif (!mr-\u003eprops-\u003ereadable)\n+\t\treturn -EOPNOTSUPP;\n+\tvalues.values_count = mr-\u003eprops-\u003ealgorithms_count;\n+\tvalues.values = kcalloc(values.values_count, sizeof(*values.values), GFP_KERNEL);\n+\tif (!values.values)\n+\t\treturn -ENOMEM;\n+\tfor (id = 0; id \u003c values.values_count; id++)\n+\t\tvalues.values[id].algorithm = mr-\u003eprops-\u003ealgorithms[id];\n+\tret = att-\u003eprovider-\u003emr_read(att, mr-\u003eprops-\u003eid, \u0026values);\n+\tif (!ret)\n+\t\tret = attestation_mr_values_validate(mr, \u0026values);\n+\tif (!ret \u0026\u0026 !ctlv_attestation_mr_generation_put(reply, att-\u003elog-\u003egeneration))\n+\t\tret = -EMSGSIZE;\n+\tif (!ret)\n+\t\tret = attestation_mr_values_put(reply, \u0026values);\n+\tkfree(values.values);\n+\tif (ret)\n+\t\treturn ret;\n+\treturn ctlv_op_query_done(ctx, att-\u003emr_read_generation);\n+}\n+\n+static int attestation_digest_compare(const void *left, const void *right)\n+{\n+\tconst struct attestation_digest *a = left;\n+\tconst struct attestation_digest *b = right;\n+\n+\treturn (int)a-\u003ealgorithm - (int)b-\u003ealgorithm;\n+}\n+\n+static int attestation_mr_extend_decode(const struct ctlv_cursor *request,\n+\t\t\t\t\tstruct attestation_digest_set *values)\n+{\n+\tstruct ctlv_cursor item;\n+\tsize_t count = 0, index = 0;\n+\n+\tctlv_attestation_mr_extend_mr_value_for_each(\u0026item, request) count++;\n+\tvalues-\u003evalues = kcalloc(count, sizeof(*values-\u003evalues), GFP_KERNEL);\n+\tif (!values-\u003evalues)\n+\t\treturn -ENOMEM;\n+\tvalues-\u003evalues_count = count;\n+\tctlv_attestation_mr_extend_mr_value_for_each(\u0026item, request)\n+\t{\n+\t\tstruct attestation_digest *value = \u0026values-\u003evalues[index++];\n+\t\tu32 length;\n+\t\tconst void *data;\n+\t\tu64 algorithm;\n+\n+\t\talgorithm =\n+\t\t\tctlv_attestation_mr_extend_value_mr_hash_algo_get(\u0026item);\n+\t\tif (algorithm \u003e= HASH_ALGO__LAST || !hash_digest_size[algorithm])\n+\t\t\treturn -EINVAL;\n+\t\tdata = ctlv_attestation_mr_extend_value_mr_data_get(\u0026item, \u0026length);\n+\t\tif (length != hash_digest_size[algorithm])\n+\t\t\treturn -EINVAL;\n+\t\tvalue-\u003ealgorithm = algorithm;\n+\t\tmemcpy(value-\u003edata, data, length);\n+\t}\n+\tsort(values-\u003evalues, values-\u003evalues_count, sizeof(*values-\u003evalues),\n+\t     attestation_digest_compare, NULL);\n+\treturn 0;\n+}\n+\n+int ctlv_attestation_mr_extend_action(void *priv, struct ctlv_op_ctx *ctx,\n+\t\t\t\t      const struct ctlv_cursor *request, struct ctlv_cursor *reply)\n+{\n+\tstruct attestation_digest_set values = {};\n+\tstruct attestation_mr_change *change;\n+\tconst struct attestation_mr_log_entry *entry;\n+\tstruct attestation *att = priv;\n+\tstruct attestation_mr *mr;\n+\tu64 id;\n+\tint ret;\n+\n+\tid = ctlv_attestation_mr_extend_mr_id_get(request);\n+\tif (id \u003e UINT_MAX)\n+\t\treturn -ERANGE;\n+\tmr = attestation_mr_lookup_live(att, id);\n+\tif (IS_ERR(mr))\n+\t\treturn PTR_ERR(mr);\n+\tif (!mr-\u003eprops-\u003eextendable)\n+\t\treturn -EOPNOTSUPP;\n+\tret = attestation_mr_extend_decode(request, \u0026values);\n+\tif (ret)\n+\t\tgoto out_values;\n+\tret = attestation_mr_values_validate(mr, \u0026values);\n+\tif (ret)\n+\t\tgoto out_values;\n+\tchange = attestation_mr_change_prepare(att, mr, \u0026values);\n+\tif (IS_ERR(change)) {\n+\t\tret = PTR_ERR(change);\n+\t\tgoto out_values;\n+\t}\n+\tentry = attestation_mr_extend_locked(att, change);\n+\tif (IS_ERR(entry))\n+\t\tret = PTR_ERR(entry);\n+\telse if (!ctlv_attestation_mr_generation_put(reply, entry-\u003emr_generation))\n+\t\tret = -EMSGSIZE;\n+\tattestation_mr_change_free(change);\n+out_values:\n+\tkfree(values.values);\n+\treturn ret;\n+}\n+\n+static bool attestation_log_selected(const unsigned int *ids, size_t count, unsigned int id)\n+{\n+\tsize_t index;\n+\n+\tif (!count)\n+\t\treturn true;\n+\tfor (index = 0; index \u003c count; index++)\n+\t\tif (ids[index] == id)\n+\t\t\treturn true;\n+\treturn false;\n+}\n+\n+int ctlv_attestation_mr_log_get_query(void *priv, struct ctlv_op_ctx *ctx,\n+\t\t\t\t      const struct ctlv_cursor *request, struct ctlv_cursor *reply)\n+{\n+\tstruct attestation *att = priv;\n+\tstruct attestation_mr_log_entry *entry;\n+\tstruct ctlv_cursor item, nested;\n+\tunsigned int ids[256];\n+\tsize_t ids_count = 0, index;\n+\tunsigned int start, end;\n+\tunsigned long xa_index;\n+\tu64 boundary;\n+\tu64 cursor = ctlv_op_query_cursor(ctx);\n+\tint ret;\n+\n+\tctlv_attestation_mr_log_get_mr_selection_for_each(\u0026item, request)\n+\t{\n+\t\tu64 id = ctlv_attestation_mr_log_get_selection_mr_id_get(\u0026item);\n+\n+\t\tif (id \u003e UINT_MAX)\n+\t\t\treturn -ERANGE;\n+\t\tfor (index = 0; index \u003c ids_count; index++)\n+\t\t\tif (ids[index] == id)\n+\t\t\t\treturn -EINVAL;\n+\t\tids[ids_count++] = id;\n+\t}\n+\tif (cursor)\n+\t\tboundary = ctlv_op_query_generation(ctx);\n+\telse\n+\t\tboundary = att-\u003elog-\u003egeneration;\n+\tif (boundary \u003e UINT_MAX || boundary \u003e att-\u003elog-\u003egeneration)\n+\t\treturn -ESTALE;\n+\tend = boundary;\n+\tif (ctlv_attestation_mr_log_get_mr_end_generation_present(request)) {\n+\t\tu64 requested_end = ctlv_attestation_mr_log_get_mr_end_generation_get(request);\n+\n+\t\tend = min_t(u64, end, requested_end);\n+\t}\n+\tstart = 1;\n+\tif (ctlv_attestation_mr_log_get_mr_start_generation_present(request)) {\n+\t\tu64 value = ctlv_attestation_mr_log_get_mr_start_generation_get(request);\n+\n+\t\tif (value \u003e UINT_MAX)\n+\t\t\treturn -EINVAL;\n+\t\tstart = value;\n+\t}\n+\tif (att-\u003elog-\u003egeneration \u0026\u0026 start \u003e end)\n+\t\treturn -EINVAL;\n+\tif (!cursor \u0026\u0026 att-\u003elog-\u003egeneration) {\n+\t\tif (!ctlv_attestation_mr_start_generation_put(reply, start) ||\n+\t\t    !ctlv_attestation_mr_end_generation_put(reply, end))\n+\t\t\treturn -EMSGSIZE;\n+\t}\n+\txa_index = cursor ? cursor : start;\n+\tentry = xa_find(\u0026att-\u003elog-\u003eentries, \u0026xa_index, end, XA_PRESENT);\n+\twhile (entry \u0026\u0026 !attestation_log_selected(ids, ids_count, entry-\u003emr_id))\n+\t\tentry = xa_find_after(\u0026att-\u003elog-\u003eentries, \u0026xa_index, end, XA_PRESENT);\n+\tif (!entry)\n+\t\treturn ctlv_op_query_done(ctx, boundary);\n+\tif (!cursor)\n+\t\treturn ctlv_op_query_more(ctx, boundary, entry-\u003emr_generation);\n+\tif (!ctlv_attestation_log_entry_start(reply, \u0026nested))\n+\t\treturn -EMSGSIZE;\n+\tret = attestation_mr_log_entry_encode(\u0026nested, entry);\n+\tctlv_nest_end(\u0026nested);\n+\tif (ret)\n+\t\treturn ret;\n+\tentry = xa_find_after(\u0026att-\u003elog-\u003eentries, \u0026xa_index, end, XA_PRESENT);\n+\twhile (entry \u0026\u0026 !attestation_log_selected(ids, ids_count, entry-\u003emr_id))\n+\t\tentry = xa_find_after(\u0026att-\u003elog-\u003eentries, \u0026xa_index, end, XA_PRESENT);\n+\tif (entry)\n+\t\treturn ctlv_op_query_more(ctx, boundary, entry-\u003emr_generation);\n+\treturn ctlv_op_query_done(ctx, boundary);\n+}\ndiff --git a/drivers/attestation/core/events.c b/drivers/attestation/core/events.c\nnew file mode 100644\nindex 0000000000000..2cf8df4b64792\n--- /dev/null\n+++ b/drivers/attestation/core/events.c\n@@ -0,0 +1,65 @@\n+// SPDX-License-Identifier: GPL-2.0-only\n+#include \u003clinux/err.h\u003e\n+\n+#include \"internal.h\"\n+\n+int attestation_events_prepare(struct attestation *att, struct attestation_event_batch *events)\n+{\n+\tstruct attestation_event *event = \u0026events-\u003emr_log;\n+\n+\tlockdep_assert_held(\u0026att-\u003elock);\n+\tevent-\u003ectx = ctlv_attestation_mr_log_entry_appended_create(att-\u003ectlvdev, \u0026event-\u003ereply,\n+\t\t\t\t\t\t\t\t   GFP_KERNEL);\n+\tif (IS_ERR(event-\u003ectx)) {\n+\t\tint ret = PTR_ERR(event-\u003ectx);\n+\n+\t\tevent-\u003ectx = NULL;\n+\t\tevent-\u003ereply = NULL;\n+\t\treturn ret;\n+\t}\n+\treturn 0;\n+}\n+\n+void attestation_events_abort(struct attestation_event_batch *events)\n+{\n+\tstruct attestation_event *event = \u0026events-\u003emr_log;\n+\n+\tif (!event-\u003ectx)\n+\t\treturn;\n+\tctlv_event_abort(event-\u003ectx);\n+\tevent-\u003ectx = NULL;\n+\tevent-\u003ereply = NULL;\n+}\n+\n+static void attestation_event_finish(struct attestation_event *event, int ret)\n+{\n+\tif (ret) {\n+\t\tpr_err(\"attestation event encoding failed: %d\\n\", ret);\n+\t\tctlv_event_abort(event-\u003ectx);\n+\t} else {\n+\t\tret = ctlv_event_emit(event-\u003ectx);\n+\t\tif (ret)\n+\t\t\tpr_err(\"attestation event emission failed: %d\\n\", ret);\n+\t}\n+\tevent-\u003ectx = NULL;\n+\tevent-\u003ereply = NULL;\n+}\n+\n+void attestation_mr_log_event_emit(struct attestation_event_batch *events,\n+\t\t\t\t   const struct attestation_mr_log_entry *entry)\n+{\n+\tstruct attestation_event *event = \u0026events-\u003emr_log;\n+\tstruct ctlv_cursor nested;\n+\tint ret;\n+\n+\tif (!event-\u003ectx)\n+\t\treturn;\n+\tif (!ctlv_attestation_notification_entry_start(event-\u003ereply, \u0026nested)) {\n+\t\tret = -EMSGSIZE;\n+\t\tgoto out;\n+\t}\n+\tret = attestation_mr_log_entry_encode(\u0026nested, entry);\n+\tctlv_nest_end(\u0026nested);\n+out:\n+\tattestation_event_finish(event, ret);\n+}\ndiff --git a/drivers/attestation/core/internal.h b/drivers/attestation/core/internal.h\nnew file mode 100644\nindex 0000000000000..64dca12a3d04a\n--- /dev/null\n+++ b/drivers/attestation/core/internal.h\n@@ -0,0 +1,108 @@\n+/* SPDX-License-Identifier: GPL-2.0-only */\n+#ifndef _ATTESTATION_INTERNAL_H\n+#define _ATTESTATION_INTERNAL_H\n+\n+#include \u003clinux/attestation.h\u003e\n+#include \u003clinux/ctlv.h\u003e\n+#include \u003clinux/mutex.h\u003e\n+#include \u003clinux/xarray.h\u003e\n+\n+#include \"../generated/ctlv_attestation_gen.h\"\n+\n+#define ATTESTATION_REGISTERED XA_MARK_1\n+\n+enum attestation_mr_log_entry_type {\n+\tATTESTATION_MR_LOG_ENTRY_INFO,\n+\tATTESTATION_MR_LOG_ENTRY_EXTEND,\n+};\n+\n+struct attestation_mr_log_entry {\n+\tunsigned int mr_generation;\n+\tunsigned int mr_id;\n+\tenum attestation_mr_log_entry_type type;\n+};\n+\n+struct attestation_mr_log_entry_info {\n+\tstruct attestation_mr_log_entry entry;\n+\tstruct attestation_mr_props props;\n+};\n+\n+struct attestation_mr_log_entry_extend {\n+\tstruct attestation_mr_log_entry entry;\n+\tstruct attestation_digest_set values;\n+};\n+\n+struct attestation_mr_log {\n+\tunsigned int generation;\n+\tstruct xarray entries;\n+};\n+\n+struct attestation {\n+\tstruct ctlv_device *ctlvdev;\n+\tconst struct attestation_provider *provider;\n+\tunsigned int index;\n+\n+\t/* Mutable instance, MR, and journal state. */\n+\tstruct mutex lock;\n+\tunsigned int mr_read_generation;\n+\n+\tstruct xarray mrs;\n+\tstruct attestation_mr_log *log;\n+\tbool initialized;\n+};\n+\n+struct attestation_mr {\n+\tconst struct attestation_mr_props *props;\n+};\n+\n+struct attestation_event {\n+\tstruct ctlv_op_ctx *ctx;\n+\tstruct ctlv_cursor *reply;\n+};\n+\n+struct attestation_event_batch {\n+\tstruct attestation_event mr_log;\n+};\n+\n+struct attestation_mr_change {\n+\tstruct attestation_mr *mr;\n+\tstruct attestation_mr_log_entry_extend *entry;\n+\tstruct attestation_event_batch events;\n+};\n+\n+int attestation_core_init(struct attestation *att, struct ctlv_device *ctlvdev,\n+\t\t\t  const struct attestation_provider *provider);\n+void attestation_core_fini(struct attestation *att);\n+bool attestation_registered(struct attestation *att);\n+void attestation_stop(struct attestation *att);\n+void attestation_mr_changed(struct attestation *att);\n+\n+int attestation_provider_validate(const struct attestation_provider *provider);\n+void attestation_provide_ops(struct attestation *att);\n+\n+struct attestation_mr *attestation_mr_lookup_live(struct attestation *att, unsigned int mr_id);\n+int attestation_mr_values_validate(const struct attestation_mr *mr,\n+\t\t\t\t   const struct attestation_digest_set *values);\n+int attestation_mr_log_init(struct attestation *att);\n+struct attestation_mr_log_entry_info *attestation_mr_info_alloc(const struct attestation_mr *mr);\n+void attestation_mr_log_entry_free(struct attestation_mr_log_entry *entry);\n+void attestation_mr_log_free(struct attestation_mr_log *log);\n+void attestation_mr_log_append(struct attestation *att, struct attestation_mr_log_entry *entry);\n+struct attestation_mr_change *\n+attestation_mr_change_prepare(struct attestation *att, struct attestation_mr *mr,\n+\t\t\t      const struct attestation_digest_set *values);\n+const struct attestation_mr_log_entry *\n+attestation_mr_extend_locked(struct attestation *att, struct attestation_mr_change *change);\n+void attestation_mr_change_free(struct attestation_mr_change *change);\n+\n+int attestation_events_prepare(struct attestation *att, struct attestation_event_batch *events);\n+void attestation_events_abort(struct attestation_event_batch *events);\n+void attestation_mr_log_event_emit(struct attestation_event_batch *events,\n+\t\t\t\t   const struct attestation_mr_log_entry *entry);\n+\n+int attestation_mr_log_entry_encode(struct ctlv_cursor *reply,\n+\t\t\t\t    const struct attestation_mr_log_entry *entry);\n+int attestation_mr_props_encode(struct ctlv_cursor *reply, const struct attestation_mr *mr,\n+\t\t\t\tbool include_id);\n+\n+#endif /* _ATTESTATION_INTERNAL_H */\ndiff --git a/drivers/attestation/core/mr.c b/drivers/attestation/core/mr.c\nnew file mode 100644\nindex 0000000000000..db80cbd2b5827\n--- /dev/null\n+++ b/drivers/attestation/core/mr.c\n@@ -0,0 +1,376 @@\n+// SPDX-License-Identifier: GPL-2.0-only\n+#include \u003ccrypto/hash_info.h\u003e\n+#include \u003clinux/cleanup.h\u003e\n+#include \u003clinux/err.h\u003e\n+#include \u003clinux/slab.h\u003e\n+#include \u003clinux/string.h\u003e\n+\n+#include \"internal.h\"\n+\n+int attestation_mr_values_validate(const struct attestation_mr *mr,\n+\t\t\t\t   const struct attestation_digest_set *values)\n+{\n+\tsize_t index;\n+\n+\tif (!values || !values-\u003evalues || values-\u003evalues_count != mr-\u003eprops-\u003ealgorithms_count)\n+\t\treturn -EINVAL;\n+\tfor (index = 0; index \u003c values-\u003evalues_count; index++)\n+\t\tif (values-\u003evalues[index].algorithm != mr-\u003eprops-\u003ealgorithms[index])\n+\t\t\treturn -EINVAL;\n+\treturn 0;\n+}\n+\n+static int attestation_digest_set_copy(struct attestation_digest_set *dst,\n+\t\t\t\t       const struct attestation_digest_set *src)\n+{\n+\tsize_t index;\n+\n+\tif (!src || !src-\u003evalues || !src-\u003evalues_count)\n+\t\treturn -EINVAL;\n+\tfor (index = 0; index \u003c src-\u003evalues_count; index++) {\n+\t\tenum hash_algo algorithm = src-\u003evalues[index].algorithm;\n+\n+\t\tif (algorithm \u003e= HASH_ALGO__LAST || !hash_digest_size[algorithm] ||\n+\t\t    (index \u0026\u0026 src-\u003evalues[index - 1].algorithm \u003e= algorithm))\n+\t\t\treturn -EINVAL;\n+\t}\n+\tdst-\u003evalues =\n+\t\tkmemdup_array(src-\u003evalues, src-\u003evalues_count, sizeof(*src-\u003evalues), GFP_KERNEL);\n+\tif (!dst-\u003evalues)\n+\t\treturn -ENOMEM;\n+\tdst-\u003evalues_count = src-\u003evalues_count;\n+\treturn 0;\n+}\n+\n+static void attestation_digest_set_free(struct attestation_digest_set *set)\n+{\n+\tkfree(set-\u003evalues);\n+\tset-\u003evalues = NULL;\n+\tset-\u003evalues_count = 0;\n+}\n+\n+struct attestation_mr_log_entry_info *attestation_mr_info_alloc(const struct attestation_mr *mr)\n+{\n+\tstruct attestation_mr_log_entry_info *info;\n+\tenum hash_algo *algorithms;\n+\tchar *name;\n+\n+\tinfo = kzalloc_obj(*info, GFP_KERNEL);\n+\tif (!info)\n+\t\treturn ERR_PTR(-ENOMEM);\n+\tname = kstrdup(mr-\u003eprops-\u003ename, GFP_KERNEL);\n+\tif (!name)\n+\t\tgoto err_info;\n+\talgorithms = kmemdup_array(mr-\u003eprops-\u003ealgorithms, mr-\u003eprops-\u003ealgorithms_count,\n+\t\t\t\t   sizeof(*algorithms), GFP_KERNEL);\n+\tif (!algorithms)\n+\t\tgoto err_name;\n+\tinfo-\u003eentry.type = ATTESTATION_MR_LOG_ENTRY_INFO;\n+\tinfo-\u003eentry.mr_id = mr-\u003eprops-\u003eid;\n+\tinfo-\u003eprops = *mr-\u003eprops;\n+\tinfo-\u003eprops.name = name;\n+\tinfo-\u003eprops.algorithms = algorithms;\n+\treturn info;\n+\n+err_name:\n+\tkfree(name);\n+err_info:\n+\tkfree(info);\n+\treturn ERR_PTR(-ENOMEM);\n+}\n+\n+void attestation_mr_log_entry_free(struct attestation_mr_log_entry *entry)\n+{\n+\tif (!entry)\n+\t\treturn;\n+\tswitch (entry-\u003etype) {\n+\tcase ATTESTATION_MR_LOG_ENTRY_INFO: {\n+\t\tstruct attestation_mr_log_entry_info *info =\n+\t\t\tcontainer_of(entry, typeof(*info), entry);\n+\n+\t\tkfree(info-\u003eprops.algorithms);\n+\t\tkfree(info-\u003eprops.name);\n+\t\tkfree(info);\n+\t\tbreak;\n+\t}\n+\tcase ATTESTATION_MR_LOG_ENTRY_EXTEND: {\n+\t\tstruct attestation_mr_log_entry_extend *extend =\n+\t\t\tcontainer_of(entry, typeof(*extend), entry);\n+\n+\t\tattestation_digest_set_free(\u0026extend-\u003evalues);\n+\t\tkfree(extend);\n+\t\tbreak;\n+\t}\n+\t}\n+}\n+\n+void attestation_mr_log_free(struct attestation_mr_log *log)\n+{\n+\tstruct attestation_mr_log_entry *entry;\n+\tunsigned long index;\n+\n+\tif (!log)\n+\t\treturn;\n+\txa_for_each(\u0026log-\u003eentries, index, entry) {\n+\t\txa_erase(\u0026log-\u003eentries, index);\n+\t\tattestation_mr_log_entry_free(entry);\n+\t}\n+\txa_destroy(\u0026log-\u003eentries);\n+\tkfree(log);\n+}\n+\n+void attestation_mr_log_append(struct attestation *att, struct attestation_mr_log_entry *entry)\n+{\n+\tstruct attestation_mr_log *log = att-\u003elog;\n+\n+\txa_store(\u0026log-\u003eentries, entry-\u003emr_generation, entry, GFP_NOWAIT);\n+}\n+\n+int attestation_mr_log_init(struct attestation *att)\n+{\n+\tstruct attestation_mr_log_entry_info **infos;\n+\tstruct attestation_mr_log *log;\n+\tstruct attestation_mr *mr;\n+\tunsigned long mr_id;\n+\tsize_t count = 0;\n+\tsize_t index = 0;\n+\tint ret = -ENOMEM;\n+\n+\txa_for_each(\u0026att-\u003emrs, mr_id, mr)\n+\t\tcount++;\n+\tlog = kzalloc_obj(*log, GFP_KERNEL);\n+\tif (!log)\n+\t\treturn -ENOMEM;\n+\txa_init(\u0026log-\u003eentries);\n+\tinfos = kcalloc(count, sizeof(*infos), GFP_KERNEL);\n+\tif (count \u0026\u0026 !infos)\n+\t\tgoto err_log;\n+\txa_for_each(\u0026att-\u003emrs, mr_id, mr) {\n+\t\tinfos[index] = attestation_mr_info_alloc(mr);\n+\t\tif (IS_ERR(infos[index])) {\n+\t\t\tret = PTR_ERR(infos[index]);\n+\t\t\tinfos[index] = NULL;\n+\t\t\tgoto err_infos;\n+\t\t}\n+\t\tindex++;\n+\t}\n+\n+\tatt-\u003elog = log;\n+\tindex = 0;\n+\txa_for_each(\u0026att-\u003emrs, mr_id, mr) {\n+\t\tstruct attestation_mr_log_entry *entry = \u0026infos[index]-\u003eentry;\n+\n+\t\tif (log-\u003egeneration == UINT_MAX) {\n+\t\t\tret = -EOVERFLOW;\n+\t\t\tgoto err_attached;\n+\t\t}\n+\t\tentry-\u003emr_generation = ++log-\u003egeneration;\n+\t\tret = xa_insert(\u0026log-\u003eentries, entry-\u003emr_generation, entry, GFP_KERNEL);\n+\t\tif (ret)\n+\t\t\tgoto err_attached;\n+\t\tinfos[index++] = NULL;\n+\t}\n+\tkfree(infos);\n+\treturn 0;\n+\n+err_attached:\n+\tatt-\u003elog = NULL;\n+\tattestation_mr_log_free(log);\n+\tlog = NULL;\n+err_infos:\n+\tfor (index = 0; index \u003c count; index++)\n+\t\tif (infos[index])\n+\t\t\tattestation_mr_log_entry_free(\u0026infos[index]-\u003eentry);\n+\tkfree(infos);\n+err_log:\n+\tattestation_mr_log_free(log);\n+\treturn ret;\n+}\n+\n+static struct attestation_mr_log_entry_extend *\n+attestation_extend_alloc(enum attestation_mr_log_entry_type type, size_t size,\n+\t\t\t struct attestation_mr *mr, const struct attestation_digest_set *values)\n+{\n+\tstruct attestation_mr_log_entry_extend *extend;\n+\tint ret;\n+\n+\textend = kzalloc(size, GFP_KERNEL);\n+\tif (!extend)\n+\t\treturn ERR_PTR(-ENOMEM);\n+\textend-\u003eentry.type = type;\n+\textend-\u003eentry.mr_id = mr-\u003eprops-\u003eid;\n+\tret = attestation_digest_set_copy(\u0026extend-\u003evalues, values);\n+\tif (ret) {\n+\t\tkfree(extend);\n+\t\treturn ERR_PTR(ret);\n+\t}\n+\treturn extend;\n+}\n+\n+struct attestation_mr_change *\n+attestation_mr_change_prepare(struct attestation *att, struct attestation_mr *mr,\n+\t\t\t      const struct attestation_digest_set *values)\n+{\n+\tstruct attestation_mr_change *change;\n+\tint ret;\n+\n+\tlockdep_assert_held(\u0026att-\u003elock);\n+\tchange = kzalloc_obj(*change, GFP_KERNEL);\n+\tif (!change)\n+\t\treturn ERR_PTR(-ENOMEM);\n+\tchange-\u003emr = mr;\n+\tchange-\u003eentry = attestation_extend_alloc(ATTESTATION_MR_LOG_ENTRY_EXTEND,\n+\t\t\t\t\t\t sizeof(*change-\u003eentry), mr, values);\n+\tif (IS_ERR(change-\u003eentry)) {\n+\t\tret = PTR_ERR(change-\u003eentry);\n+\t\tgoto err_change;\n+\t}\n+\tret = attestation_events_prepare(att, \u0026change-\u003eevents);\n+\tif (ret)\n+\t\tgoto err_entry;\n+\treturn change;\n+\n+err_entry:\n+\tattestation_mr_log_entry_free(\u0026change-\u003eentry-\u003eentry);\n+err_change:\n+\tkfree(change);\n+\treturn ERR_PTR(ret);\n+}\n+\n+const struct attestation_mr_log_entry *\n+attestation_mr_extend_locked(struct attestation *att, struct attestation_mr_change *change)\n+{\n+\tstruct attestation_mr_log_entry_extend *extend = change-\u003eentry;\n+\tstruct attestation_mr_log_entry *entry = \u0026extend-\u003eentry;\n+\tint ret;\n+\n+\tlockdep_assert_held(\u0026att-\u003elock);\n+\tif (att-\u003elog-\u003egeneration == UINT_MAX) {\n+\t\tattestation_stop(att);\n+\t\treturn ERR_PTR(-EOVERFLOW);\n+\t}\n+\tentry-\u003emr_generation = att-\u003elog-\u003egeneration + 1;\n+\tret = xa_reserve(\u0026att-\u003elog-\u003eentries, entry-\u003emr_generation, GFP_KERNEL);\n+\tif (ret)\n+\t\treturn ERR_PTR(ret);\n+\tret = att-\u003eprovider-\u003emr_extend(att, change-\u003emr-\u003eprops-\u003eid, \u0026extend-\u003evalues);\n+\tif (ret) {\n+\t\txa_release(\u0026att-\u003elog-\u003eentries, entry-\u003emr_generation);\n+\t\treturn ERR_PTR(ret);\n+\t}\n+\tattestation_mr_changed(att);\n+\tattestation_mr_log_append(att, entry);\n+\tattestation_mr_log_event_emit(\u0026change-\u003eevents, entry);\n+\tchange-\u003eentry = NULL;\n+\treturn entry;\n+}\n+\n+void attestation_mr_change_free(struct attestation_mr_change *change)\n+{\n+\tif (!change)\n+\t\treturn;\n+\tattestation_events_abort(\u0026change-\u003eevents);\n+\tif (change-\u003eentry)\n+\t\tattestation_mr_log_entry_free(\u0026change-\u003eentry-\u003eentry);\n+\tkfree(change);\n+}\n+\n+int attestation_mr_props_encode(struct ctlv_cursor *reply, const struct attestation_mr *mr,\n+\t\t\t\tbool include_id)\n+{\n+\tu64 caps = 0;\n+\tsize_t index;\n+\tbool ok = true;\n+\n+\tif (include_id)\n+\t\tok \u0026= ctlv_attestation_mr_id_put(reply, mr-\u003eprops-\u003eid);\n+\tok \u0026= ctlv_attestation_mr_name_put(reply, mr-\u003eprops-\u003ename);\n+\tfor (index = 0; index \u003c mr-\u003eprops-\u003ealgorithms_count; index++)\n+\t\tok \u0026= ctlv_attestation_mr_supported_hash_algo_put(reply,\n+\t\t\t\t\t\t\t\t  mr-\u003eprops-\u003ealgorithms[index]);\n+\tif (mr-\u003eprops-\u003ehas_register_index)\n+\t\tok \u0026= ctlv_attestation_mr_register_index_put(reply, mr-\u003eprops-\u003eregister_index);\n+\tif (mr-\u003eprops-\u003ereadable)\n+\t\tcaps |= CTLV_ATTESTATION_MR_CAPS_READ;\n+\tif (mr-\u003eprops-\u003eextendable)\n+\t\tcaps |= CTLV_ATTESTATION_MR_CAPS_EXTEND;\n+\tok \u0026= ctlv_attestation_mr_caps_put(reply, caps);\n+\treturn ok ? 0 : -EMSGSIZE;\n+}\n+\n+static int attestation_values_encode(struct ctlv_cursor *reply,\n+\t\t\t\t     const struct attestation_digest_set *values)\n+{\n+\tstruct ctlv_cursor nested;\n+\tsize_t index;\n+\tbool ok = true;\n+\n+\tfor (index = 0; index \u003c values-\u003evalues_count; index++) {\n+\t\tconst struct attestation_digest *value = \u0026values-\u003evalues[index];\n+\n+\t\tif (!ctlv_attestation_mr_value_start(reply, \u0026nested))\n+\t\t\treturn -EMSGSIZE;\n+\t\tok \u0026= ctlv_attestation_mr_hash_algo_put(\u0026nested, value-\u003ealgorithm);\n+\t\tok \u0026= ctlv_attestation_mr_data_put(\u0026nested, value-\u003edata,\n+\t\t\t\t\t\t   hash_digest_size[value-\u003ealgorithm]);\n+\t\tctlv_nest_end(\u0026nested);\n+\t}\n+\treturn ok ? 0 : -EMSGSIZE;\n+}\n+\n+static int attestation_mr_info_encode(struct ctlv_cursor *reply,\n+\t\t\t\t      const struct attestation_mr_props *props)\n+{\n+\tu64 caps = 0;\n+\tsize_t index;\n+\tbool ok;\n+\n+\tok = ctlv_attestation_mr_name_put(reply, props-\u003ename);\n+\tfor (index = 0; index \u003c props-\u003ealgorithms_count; index++)\n+\t\tok \u0026= ctlv_attestation_mr_supported_hash_algo_put(reply,\n+\t\t\t\t\t\t\t\t  props-\u003ealgorithms[index]);\n+\tif (props-\u003ehas_register_index)\n+\t\tok \u0026= ctlv_attestation_mr_register_index_put(reply, props-\u003eregister_index);\n+\tif (props-\u003ereadable)\n+\t\tcaps |= CTLV_ATTESTATION_MR_CAPS_READ;\n+\tif (props-\u003eextendable)\n+\t\tcaps |= CTLV_ATTESTATION_MR_CAPS_EXTEND;\n+\tok \u0026= ctlv_attestation_mr_caps_put(reply, caps);\n+\treturn ok ? 0 : -EMSGSIZE;\n+}\n+\n+int attestation_mr_log_entry_encode(struct ctlv_cursor *reply,\n+\t\t\t\t    const struct attestation_mr_log_entry *entry)\n+{\n+\tstruct ctlv_cursor nested;\n+\tbool ok;\n+\tint ret;\n+\n+\tok = ctlv_attestation_mr_generation_put(reply, entry-\u003emr_generation);\n+\tok \u0026= ctlv_attestation_mr_id_put(reply, entry-\u003emr_id);\n+\tok \u0026= ctlv_attestation_log_event_put(reply, entry-\u003etype == ATTESTATION_MR_LOG_ENTRY_INFO ?\n+\t\t\t\t\t\t\t    CTLV_ATTESTATION_MR_LOG_EVENT_INFO :\n+\t\t\t\t\t\t\t    CTLV_ATTESTATION_MR_LOG_EVENT_EXTEND);\n+\tif (!ok)\n+\t\treturn -EMSGSIZE;\n+\n+\tif (entry-\u003etype == ATTESTATION_MR_LOG_ENTRY_INFO) {\n+\t\tconst struct attestation_mr_log_entry_info *info =\n+\t\t\tcontainer_of(entry, typeof(*info), entry);\n+\n+\t\tif (!ctlv_attestation_log_mr_start(reply, \u0026nested))\n+\t\t\treturn -EMSGSIZE;\n+\t\tret = attestation_mr_info_encode(\u0026nested, \u0026info-\u003eprops);\n+\t\tctlv_nest_end(\u0026nested);\n+\t\treturn ret;\n+\t}\n+\n+\tret = attestation_values_encode(reply,\n+\t\t\t\t\t\u0026container_of(entry,\n+\t\t\t\t\t\t      const struct attestation_mr_log_entry_extend,\n+\t\t\t\t\t\t      entry)\n+\t\t\t\t\t\t -\u003evalues);\n+\tif (ret)\n+\t\treturn ret;\n+\treturn 0;\n+}\ndiff --git a/drivers/attestation/generated/ctlv_attestation_gen.c b/drivers/attestation/generated/ctlv_attestation_gen.c\nnew file mode 100644\nindex 0000000000000..c9fbeae00e385\n--- /dev/null\n+++ b/drivers/attestation/generated/ctlv_attestation_gen.c\n@@ -0,0 +1,234 @@\n+// SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)\n+/* Do not edit, regenerate with tools/ctlv/ctlv-regen.sh, from: */\n+/*\tDocumentation/ctlv/specs/ctlv-attestation.yaml */\n+/* CTLV-GEN kernel source */\n+\n+#define _CTLV_GENERATED_METADATA_ONLY\n+#include \u003clinux/array_size.h\u003e\n+#include \u003clinux/bits.h\u003e\n+#include \u003clinux/build_bug.h\u003e\n+#include \u003clinux/ctlv_family.h\u003e\n+#include \u003clinux/export.h\u003e\n+#include \u003clinux/limits.h\u003e\n+\n+#include \u003cuapi/linux/ctlv_gen.h\u003e\n+#include \u003cuapi/linux/ctlv_attestation_gen.h\u003e\n+\n+#include \"ctlv_attestation_gen.h\"\n+\n+static const struct ctlv_node_schema device_get_request_node_schemas[] = {\n+\tCTLV_NODE_SCHEMA_ROOT(0, 0, 0),\n+};\n+\n+static const struct ctlv_node_schema device_get_reply_node_schemas[] = {\n+\tCTLV_NODE_SCHEMA_ROOT(1, 2, 2),\n+\tCTLV_NODE_SCHEMA_NEST(CTLV_ATTESTATION_ATTR_DEVICE_CAPS, 1, 3, 2, 0),\n+\tCTLV_NODE_SCHEMA_NEST(CTLV_ATTESTATION_ATTR_DEVICE_INFO, 1, 0, 0, 0),\n+\tCTLV_NODE_SCHEMA_NEST(CTLV_ATTESTATION_ATTR_CAP_EVIDENCE, 1, 5, 4, 4),\n+\tCTLV_NODE_SCHEMA_NEST(CTLV_ATTESTATION_ATTR_CAP_MR, 1, 9, 1, 1),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_CAP_MIN_CHALLENGE_LENGTH, 1, 0, U64_MAX),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_CAP_MAX_CHALLENGE_LENGTH, 1, 0, U64_MAX),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_CAP_MAX_TOTAL_OUTPUT_LENGTH, 1, 0, U64_MAX),\n+\tCTLV_NODE_SCHEMA_NEST(CTLV_ATTESTATION_ATTR_CAP_OBJECT, 16, 10, 4, 4),\n+\tCTLV_NODE_SCHEMA_FLAGS(CTLV_ATTESTATION_ATTR_CAP_MR_FLAGS, 1,\n+\t\t\t       CTLV_ATTESTATION_MR_DEVICE_CAPS_MASK),\n+\tCTLV_NODE_SCHEMA_ENUM(CTLV_ATTESTATION_ATTR_CAP_BLOB_CLASS, 1, 1),\n+\tCTLV_NODE_SCHEMA_STRING(CTLV_ATTESTATION_ATTR_CAP_FORMAT, 1, 1, 128),\n+\tCTLV_NODE_SCHEMA_ENUM(CTLV_ATTESTATION_ATTR_CAP_REPRESENTATION, 1, 1),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_CAP_MAX_LENGTH, 1, 0, U64_MAX),\n+};\n+\n+/* Extension points selected by this tree. */\n+static const struct ctlv_stub_schema device_get_reply_stub_schemas[] = {\n+\tCTLV_STUB_SCHEMA(CTLV_FAMILY_ATTESTATION, CTLV_ATTESTATION_SET_DEVICE_INFO, 2),\n+};\n+\n+static const struct ctlv_node_schema evidence_get_request_node_schemas[] = {\n+\tCTLV_NODE_SCHEMA_ROOT(1, 2, 2),\n+\tCTLV_NODE_SCHEMA_BINARY(CTLV_ATTESTATION_ATTR_EVIDENCE_CHALLENGE, 1, 0, 4096),\n+\tCTLV_NODE_SCHEMA_NEST(CTLV_ATTESTATION_ATTR_EVIDENCE_OBJECT, 16, 3, 4, 4),\n+\tCTLV_NODE_SCHEMA_ENUM(CTLV_ATTESTATION_ATTR_EVIDENCE_BLOB_CLASS, 1, 1),\n+\tCTLV_NODE_SCHEMA_STRING(CTLV_ATTESTATION_ATTR_EVIDENCE_FORMAT, 1, 1, 128),\n+\tCTLV_NODE_SCHEMA_ENUM(CTLV_ATTESTATION_ATTR_EVIDENCE_REPRESENTATION, 1, 1),\n+\tCTLV_NODE_SCHEMA_BLOB(CTLV_ATTESTATION_ATTR_EVIDENCE_DATA, 1, U32_MAX, 1,\n+\t\t\t      BIT(CTLV_BLOB_TYPE_VA),\n+\t\t\t      CTLV_BLOB_DIRECTION_OUTPUT),\n+};\n+\n+static const struct ctlv_node_schema evidence_get_reply_node_schemas[] = {\n+\tCTLV_NODE_SCHEMA_ROOT(1, 2, 1),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_EVIDENCE_OBJECT_LENGTH, 16, 0, U64_MAX),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_GENERATION, 1, 0, U32_MAX),\n+};\n+\n+static const struct ctlv_node_schema mr_get_request_node_schemas[] = {\n+\tCTLV_NODE_SCHEMA_ROOT(1, 1, 1),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_ID, 1, 0, U32_MAX),\n+};\n+\n+static const struct ctlv_node_schema mr_get_reply_node_schemas[] = {\n+\tCTLV_NODE_SCHEMA_ROOT(1, 4, 3),\n+\tCTLV_NODE_SCHEMA_STRING(CTLV_ATTESTATION_ATTR_MR_NAME, 1, 1, 128),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_SUPPORTED_HASH_ALGO, 21, 0, 20),\n+\tCTLV_NODE_SCHEMA_FLAGS(CTLV_ATTESTATION_ATTR_MR_CAPS, 1, CTLV_ATTESTATION_MR_CAPS_MASK),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_REGISTER_INDEX, 1, 0, U32_MAX),\n+};\n+\n+static const struct ctlv_node_schema mr_dump_request_node_schemas[] = {\n+\tCTLV_NODE_SCHEMA_ROOT(0, 0, 0),\n+};\n+\n+static const struct ctlv_node_schema mr_dump_reply_node_schemas[] = {\n+\tCTLV_NODE_SCHEMA_ROOT(1, 1, 1),\n+\tCTLV_NODE_SCHEMA_NEST(CTLV_ATTESTATION_ATTR_MR_ITEM, CTLV_NODE_SCHEMA_UNLIMITED, 2, 5, 4),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_ID, 1, 0, U32_MAX),\n+\tCTLV_NODE_SCHEMA_STRING(CTLV_ATTESTATION_ATTR_MR_NAME, 1, 1, 128),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_SUPPORTED_HASH_ALGO, 21, 0, 20),\n+\tCTLV_NODE_SCHEMA_FLAGS(CTLV_ATTESTATION_ATTR_MR_CAPS, 1, CTLV_ATTESTATION_MR_CAPS_MASK),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_REGISTER_INDEX, 1, 0, U32_MAX),\n+};\n+\n+static const struct ctlv_node_schema mr_read_request_node_schemas[] = {\n+\tCTLV_NODE_SCHEMA_ROOT(1, 1, 1),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_ID, 1, 0, U32_MAX),\n+};\n+\n+static const struct ctlv_node_schema mr_read_reply_node_schemas[] = {\n+\tCTLV_NODE_SCHEMA_ROOT(1, 2, 2),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_GENERATION, 1, 0, U32_MAX),\n+\tCTLV_NODE_SCHEMA_NEST(CTLV_ATTESTATION_ATTR_MR_VALUE, 21, 3, 2, 2),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_HASH_ALGO, 1, 0, 20),\n+\tCTLV_NODE_SCHEMA_BINARY(CTLV_ATTESTATION_ATTR_MR_DATA, 1, 16, 64),\n+};\n+\n+static const struct ctlv_node_schema mr_extend_request_node_schemas[] = {\n+\tCTLV_NODE_SCHEMA_ROOT(1, 2, 2),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_ID, 1, 0, U32_MAX),\n+\tCTLV_NODE_SCHEMA_NEST(CTLV_ATTESTATION_ATTR_MR_VALUE, 21, 3, 2, 2),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_HASH_ALGO, 1, 0, 20),\n+\tCTLV_NODE_SCHEMA_BINARY(CTLV_ATTESTATION_ATTR_MR_DATA, 1, 16, 64),\n+};\n+\n+static const struct ctlv_node_schema mr_extend_reply_node_schemas[] = {\n+\tCTLV_NODE_SCHEMA_ROOT(1, 1, 1),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_GENERATION, 1, 0, U32_MAX),\n+};\n+\n+static const struct ctlv_node_schema mr_log_entry_appended_reply_node_schemas[] = {\n+\tCTLV_NODE_SCHEMA_ROOT(1, 1, 1),\n+\tCTLV_NODE_SCHEMA_NEST(CTLV_ATTESTATION_ATTR_NOTIFICATION_ENTRY, 1, 2, 5, 3),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_GENERATION, 1, 0, U32_MAX),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_ID, 1, 0, U32_MAX),\n+\tCTLV_NODE_SCHEMA_ENUM(CTLV_ATTESTATION_ATTR_LOG_EVENT, 1, 2),\n+\tCTLV_NODE_SCHEMA_NEST(CTLV_ATTESTATION_ATTR_MR_VALUE, 21, 7, 2, 2),\n+\tCTLV_NODE_SCHEMA_NEST(CTLV_ATTESTATION_ATTR_LOG_MR, 1, 9, 4, 3),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_HASH_ALGO, 1, 0, 20),\n+\tCTLV_NODE_SCHEMA_BINARY(CTLV_ATTESTATION_ATTR_MR_DATA, 1, 16, 64),\n+\tCTLV_NODE_SCHEMA_STRING(CTLV_ATTESTATION_ATTR_MR_NAME, 1, 1, 128),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_SUPPORTED_HASH_ALGO, 21, 0, 20),\n+\tCTLV_NODE_SCHEMA_FLAGS(CTLV_ATTESTATION_ATTR_MR_CAPS, 1, CTLV_ATTESTATION_MR_CAPS_MASK),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_REGISTER_INDEX, 1, 0, U32_MAX),\n+};\n+\n+static const struct ctlv_node_schema mr_log_get_request_node_schemas[] = {\n+\tCTLV_NODE_SCHEMA_ROOT(1, 3, 0),\n+\tCTLV_NODE_SCHEMA_NEST(CTLV_ATTESTATION_ATTR_MR_SELECTION, 256, 4, 1, 1),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_START_GENERATION, 1, 0, U32_MAX),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_END_GENERATION, 1, 0, U32_MAX),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_ID, 1, 0, U32_MAX),\n+};\n+\n+static const struct ctlv_node_schema mr_log_get_reply_node_schemas[] = {\n+\tCTLV_NODE_SCHEMA_ROOT(1, 3, 0),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_START_GENERATION, 1, 0, U32_MAX),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_END_GENERATION, 1, 0, U32_MAX),\n+\tCTLV_NODE_SCHEMA_NEST(CTLV_ATTESTATION_ATTR_LOG_ENTRY, CTLV_NODE_SCHEMA_UNLIMITED, 4, 5, 3),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_GENERATION, 1, 0, U32_MAX),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_ID, 1, 0, U32_MAX),\n+\tCTLV_NODE_SCHEMA_ENUM(CTLV_ATTESTATION_ATTR_LOG_EVENT, 1, 2),\n+\tCTLV_NODE_SCHEMA_NEST(CTLV_ATTESTATION_ATTR_MR_VALUE, 21, 9, 2, 2),\n+\tCTLV_NODE_SCHEMA_NEST(CTLV_ATTESTATION_ATTR_LOG_MR, 1, 11, 4, 3),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_HASH_ALGO, 1, 0, 20),\n+\tCTLV_NODE_SCHEMA_BINARY(CTLV_ATTESTATION_ATTR_MR_DATA, 1, 16, 64),\n+\tCTLV_NODE_SCHEMA_STRING(CTLV_ATTESTATION_ATTR_MR_NAME, 1, 1, 128),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_SUPPORTED_HASH_ALGO, 21, 0, 20),\n+\tCTLV_NODE_SCHEMA_FLAGS(CTLV_ATTESTATION_ATTR_MR_CAPS, 1, CTLV_ATTESTATION_MR_CAPS_MASK),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_REGISTER_INDEX, 1, 0, U32_MAX),\n+};\n+\n+/* The ops this family declares, in declaration order. */\n+const struct ctlv_op_schema ctlv_attestation_op_schemas[] = {\n+\tCTLV_OP_SCHEMA_ACTION(CTLV_ATTESTATION_OP_DEVICE_GET, CTLV_OP_FD_ACCESS_READ,\n+\t\t\t      CTLV_OP_AVAILABILITY_FIXED, 16, 4016,\n+\t\t\t      CTLV_SCHEMA_TREE(device_get_request),\n+\t\t\t      CTLV_SCHEMA_TREE_STUBS(device_get_reply)),\n+\tCTLV_OP_SCHEMA_ACTION(CTLV_ATTESTATION_OP_EVIDENCE_GET, CTLV_OP_FD_ACCESS_READ_WRITE,\n+\t\t\t      CTLV_OP_AVAILABILITY_DYNAMIC, 8992, 424,\n+\t\t\t      CTLV_SCHEMA_TREE(evidence_get_request),\n+\t\t\t      CTLV_SCHEMA_TREE(evidence_get_reply), .optional = true),\n+\tCTLV_OP_SCHEMA_ACTION(CTLV_ATTESTATION_OP_MR_GET, CTLV_OP_FD_ACCESS_READ,\n+\t\t\t      CTLV_OP_AVAILABILITY_FIXED, 40, 720, CTLV_SCHEMA_TREE(mr_get_request),\n+\t\t\t      CTLV_SCHEMA_TREE(mr_get_reply), .optional = true),\n+\tCTLV_OP_SCHEMA_QUERY(CTLV_ATTESTATION_OP_MR_DUMP, CTLV_OP_FD_ACCESS_READ,\n+\t\t\t     CTLV_OP_AVAILABILITY_FIXED, 16, 184, 4096,\n+\t\t\t     CTLV_SCHEMA_TREE(mr_dump_request), CTLV_SCHEMA_TREE(mr_dump_reply),\n+\t\t\t     .optional = true),\n+\tCTLV_OP_SCHEMA_QUERY(CTLV_ATTESTATION_OP_MR_READ, CTLV_OP_FD_ACCESS_READ,\n+\t\t\t     CTLV_OP_AVAILABILITY_FIXED, 40, 112, 4096,\n+\t\t\t     CTLV_SCHEMA_TREE(mr_read_request), CTLV_SCHEMA_TREE(mr_read_reply),\n+\t\t\t     .optional = true),\n+\tCTLV_OP_SCHEMA_ACTION(CTLV_ATTESTATION_OP_MR_EXTEND, CTLV_OP_FD_ACCESS_READ_WRITE,\n+\t\t\t      CTLV_OP_AVAILABILITY_FIXED, 2560, 40,\n+\t\t\t      CTLV_SCHEMA_TREE(mr_extend_request),\n+\t\t\t      CTLV_SCHEMA_TREE(mr_extend_reply), .optional = true),\n+\tCTLV_OP_SCHEMA_EVENT(CTLV_ATTESTATION_OP_MR_LOG_ENTRY_APPENDED, 3368,\n+\t\t\t     CTLV_SCHEMA_TREE(mr_log_entry_appended_reply)),\n+\tCTLV_OP_SCHEMA_QUERY(CTLV_ATTESTATION_OP_MR_LOG_GET, CTLV_OP_FD_ACCESS_READ,\n+\t\t\t     CTLV_OP_AVAILABILITY_FIXED, 10304, 200, 131072,\n+\t\t\t     CTLV_SCHEMA_TREE(mr_log_get_request),\n+\t\t\t     CTLV_SCHEMA_TREE(mr_log_get_reply), .optional = true),\n+};\n+\n+/* The family ID is its position in the central registry. */\n+const struct ctlv_family_schema ctlv_attestation_schema = {\n+\t.name = \"ctlv-attestation\",\n+\t.family_id = 1,\n+\t.ops = ctlv_attestation_op_schemas,\n+\t.ops_count = ARRAY_SIZE(ctlv_attestation_op_schemas),\n+};\n+\n+/* Maximum uevent cost for this family chain. */\n+static_assert(107 \u003c= CTLV_UEVENT_MAX_LEN);\n+static_assert(4 \u003c= CTLV_UEVENT_MAX_VARS);\n+\n+/* Guards for generated maxima. */\n+static_assert(131072 \u003c= CTLV_MAX_INLINE_MESSAGE_LEN);\n+static_assert(3368 \u003c= CTLV_MAX_EVENT_QUEUE_LEN);\n+static_assert(3 \u003c= CTLV_MAX_DECLARED_NEST_DEPTH);\n+\n+/* Local action and query bindings in declaration order. */\n+static const struct ctlv_op ctlv_attestation_ops[] = {\n+\tCTLV_OP_ACTION(ctlv_attestation_device_get),\n+\tCTLV_OP_ACTION(ctlv_attestation_evidence_get),\n+\tCTLV_OP_ACTION(ctlv_attestation_mr_get),\n+\tCTLV_OP_QUERY(ctlv_attestation_mr_dump),\n+\tCTLV_OP_QUERY(ctlv_attestation_mr_read),\n+\tCTLV_OP_ACTION(ctlv_attestation_mr_extend),\n+\tCTLV_OP_QUERY(ctlv_attestation_mr_log_get),\n+};\n+\n+/* Family descriptor used by ctlv_create(). */\n+const struct ctlv_family ctlv_attestation_family = {\n+\t.schema = \u0026ctlv_attestation_schema,\n+\t.parent = \u0026ctlv_family,\n+\t.ops = ctlv_attestation_ops,\n+\t.ops_count = ARRAY_SIZE(ctlv_attestation_ops),\n+\t.pre = ctlv_attestation_op_pre,\n+\t.post = ctlv_attestation_op_post,\n+\t.priv_size = ctlv_attestation_priv_size,\n+\t.init = ctlv_attestation_init,\n+\t.post_init = ctlv_attestation_post_init,\n+\t.pre_fini = ctlv_attestation_pre_fini,\n+\t.fini = ctlv_attestation_fini,\n+};\n+EXPORT_SYMBOL_NS_GPL(ctlv_attestation_family, \"CTLV\");\ndiff --git a/drivers/attestation/generated/ctlv_attestation_gen.h b/drivers/attestation/generated/ctlv_attestation_gen.h\nnew file mode 100644\nindex 0000000000000..a40ed0757756b\n--- /dev/null\n+++ b/drivers/attestation/generated/ctlv_attestation_gen.h\n@@ -0,0 +1,198 @@\n+/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) */\n+/* Do not edit, regenerate with tools/ctlv/ctlv-regen.sh, from: */\n+/*\tDocumentation/ctlv/specs/ctlv-attestation.yaml */\n+/* CTLV-GEN kernel header */\n+\n+/* Kernel metadata and family API of the ctlv-attestation CTLV family. */\n+\n+#ifndef _LINUX_CTLV_ATTESTATION_GEN_H\n+#define _LINUX_CTLV_ATTESTATION_GEN_H\n+\n+#include \u003clinux/ctlv_family.h\u003e\n+#include \u003clinux/err.h\u003e\n+#include \u003clinux/errno.h\u003e\n+\n+#include \u003cuapi/linux/ctlv_attestation_gen.h\u003e\n+\n+/* Ops this family declares, in declaration order. */\n+extern const struct ctlv_op_schema ctlv_attestation_op_schemas[];\n+\n+extern const struct ctlv_family_schema ctlv_attestation_schema;\n+\n+/* Implemented by this family, one per action and query it declares. */\n+int ctlv_attestation_device_get_action(void *priv, struct ctlv_op_ctx *ctx,\n+\t\t\t\t       const struct ctlv_cursor *request,\n+\t\t\t\t       struct ctlv_cursor *reply);\n+int ctlv_attestation_evidence_get_action(void *priv, struct ctlv_op_ctx *ctx,\n+\t\t\t\t\t const struct ctlv_cursor *request,\n+\t\t\t\t\t struct ctlv_cursor *reply);\n+int ctlv_attestation_mr_get_action(void *priv, struct ctlv_op_ctx *ctx,\n+\t\t\t\t   const struct ctlv_cursor *request, struct ctlv_cursor *reply);\n+int ctlv_attestation_mr_dump_query(void *priv, struct ctlv_op_ctx *ctx,\n+\t\t\t\t   const struct ctlv_cursor *request, struct ctlv_cursor *reply);\n+int ctlv_attestation_mr_read_query(void *priv, struct ctlv_op_ctx *ctx,\n+\t\t\t\t   const struct ctlv_cursor *request, struct ctlv_cursor *reply);\n+int ctlv_attestation_mr_extend_action(void *priv, struct ctlv_op_ctx *ctx,\n+\t\t\t\t      const struct ctlv_cursor *request, struct ctlv_cursor *reply);\n+int ctlv_attestation_mr_log_get_query(void *priv, struct ctlv_op_ctx *ctx,\n+\t\t\t\t      const struct ctlv_cursor *request, struct ctlv_cursor *reply);\n+\n+/* Family-wide hooks around every effective non-core op. */\n+int ctlv_attestation_op_pre(void *priv, struct ctlv_op_ctx *ctx);\n+void ctlv_attestation_op_post(void *priv, struct ctlv_op_ctx *ctx);\n+\n+/* Core-allocated family priv lifecycle. */\n+size_t ctlv_attestation_priv_size(void);\n+int ctlv_attestation_init(struct ctlv_device *ctlvdev, const void *init_info, void *priv);\n+int ctlv_attestation_post_init(struct ctlv_device *ctlvdev, void *priv);\n+void ctlv_attestation_pre_fini(struct ctlv_device *ctlvdev, void *priv);\n+void ctlv_attestation_fini(struct ctlv_device *ctlvdev, void *priv);\n+\n+extern const struct ctlv_family ctlv_attestation_family;\n+\n+#ifndef _CTLV_GENERATED_METADATA_ONLY\n+\n+/* Optional publication and dynamic availability helpers. */\n+CTLV_OP_PROVIDE(ctlv_attestation_evidence_get, CTLV_ATTESTATION_OP_EVIDENCE_GET)\n+CTLV_OP_ENABLE(ctlv_attestation_evidence_get, CTLV_ATTESTATION_OP_EVIDENCE_GET)\n+CTLV_OP_DISABLE(ctlv_attestation_evidence_get, CTLV_ATTESTATION_OP_EVIDENCE_GET)\n+CTLV_OP_PROVIDE(ctlv_attestation_mr_get, CTLV_ATTESTATION_OP_MR_GET)\n+CTLV_OP_PROVIDE(ctlv_attestation_mr_dump, CTLV_ATTESTATION_OP_MR_DUMP)\n+CTLV_OP_PROVIDE(ctlv_attestation_mr_read, CTLV_ATTESTATION_OP_MR_READ)\n+CTLV_OP_PROVIDE(ctlv_attestation_mr_extend, CTLV_ATTESTATION_OP_MR_EXTEND)\n+CTLV_OP_PROVIDE(ctlv_attestation_mr_log_get, CTLV_ATTESTATION_OP_MR_LOG_GET)\n+\n+/* Reading a validated message. A blob has a resolver instead of a getter. */\n+CTLV_IN_REF(ctlv_attestation_evidence_get_evidence_challenge,\n+\t    \u0026ctlv_attestation_op_schemas[1].request, CTLV_ATTESTATION_ATTR_EVIDENCE_CHALLENGE, 0, 0,\n+\t    CTLV_SCHEMA_BINARY)\n+CTLV_IN_HAS(ctlv_attestation_evidence_get_evidence_challenge)\n+CTLV_IN_BINARY(ctlv_attestation_evidence_get_evidence_challenge)\n+CTLV_IN_REF(ctlv_attestation_evidence_get_evidence_object, \u0026ctlv_attestation_op_schemas[1].request,\n+\t    CTLV_ATTESTATION_ATTR_EVIDENCE_OBJECT, 0, 1, CTLV_SCHEMA_NEST)\n+#define ctlv_attestation_evidence_get_evidence_object_for_each(_attr, _nest) \\\n+\tCTLV_IN_FOR_EACH(ctlv_attestation_evidence_get_evidence_object, _attr, _nest)\n+CTLV_IN_REF(ctlv_attestation_evidence_get_object_evidence_blob_class,\n+\t    \u0026ctlv_attestation_op_schemas[1].request, CTLV_ATTESTATION_ATTR_EVIDENCE_BLOB_CLASS, 2,\n+\t    0, CTLV_SCHEMA_ENUM)\n+CTLV_IN_HAS(ctlv_attestation_evidence_get_object_evidence_blob_class)\n+CTLV_IN_U64(ctlv_attestation_evidence_get_object_evidence_blob_class)\n+CTLV_IN_REF(ctlv_attestation_evidence_get_object_evidence_format,\n+\t    \u0026ctlv_attestation_op_schemas[1].request, CTLV_ATTESTATION_ATTR_EVIDENCE_FORMAT, 2, 1,\n+\t    CTLV_SCHEMA_STRING)\n+CTLV_IN_HAS(ctlv_attestation_evidence_get_object_evidence_format)\n+CTLV_IN_STRING(ctlv_attestation_evidence_get_object_evidence_format)\n+CTLV_IN_REF(ctlv_attestation_evidence_get_object_evidence_representation,\n+\t    \u0026ctlv_attestation_op_schemas[1].request, CTLV_ATTESTATION_ATTR_EVIDENCE_REPRESENTATION,\n+\t    2, 2, CTLV_SCHEMA_ENUM)\n+CTLV_IN_HAS(ctlv_attestation_evidence_get_object_evidence_representation)\n+CTLV_IN_U64(ctlv_attestation_evidence_get_object_evidence_representation)\n+CTLV_IN_REF(ctlv_attestation_evidence_get_object_evidence_data,\n+\t    \u0026ctlv_attestation_op_schemas[1].request, CTLV_ATTESTATION_ATTR_EVIDENCE_DATA, 2, 3,\n+\t    CTLV_SCHEMA_BLOB)\n+CTLV_IN_HAS(ctlv_attestation_evidence_get_object_evidence_data)\n+CTLV_IN_BLOB(ctlv_attestation_evidence_get_object_evidence_data)\n+CTLV_IN_REF(ctlv_attestation_mr_get_mr_id, \u0026ctlv_attestation_op_schemas[2].request,\n+\t    CTLV_ATTESTATION_ATTR_MR_ID, 0, 0, CTLV_SCHEMA_UINT)\n+CTLV_IN_HAS(ctlv_attestation_mr_get_mr_id)\n+CTLV_IN_U64(ctlv_attestation_mr_get_mr_id)\n+CTLV_IN_REF(ctlv_attestation_mr_read_mr_id, \u0026ctlv_attestation_op_schemas[4].request,\n+\t    CTLV_ATTESTATION_ATTR_MR_ID, 0, 0, CTLV_SCHEMA_UINT)\n+CTLV_IN_HAS(ctlv_attestation_mr_read_mr_id)\n+CTLV_IN_U64(ctlv_attestation_mr_read_mr_id)\n+CTLV_IN_REF(ctlv_attestation_mr_extend_mr_id, \u0026ctlv_attestation_op_schemas[5].request,\n+\t    CTLV_ATTESTATION_ATTR_MR_ID, 0, 0, CTLV_SCHEMA_UINT)\n+CTLV_IN_HAS(ctlv_attestation_mr_extend_mr_id)\n+CTLV_IN_U64(ctlv_attestation_mr_extend_mr_id)\n+CTLV_IN_REF(ctlv_attestation_mr_extend_mr_value, \u0026ctlv_attestation_op_schemas[5].request,\n+\t    CTLV_ATTESTATION_ATTR_MR_VALUE, 0, 1, CTLV_SCHEMA_NEST)\n+#define ctlv_attestation_mr_extend_mr_value_for_each(_attr, _nest) \\\n+\tCTLV_IN_FOR_EACH(ctlv_attestation_mr_extend_mr_value, _attr, _nest)\n+CTLV_IN_REF(ctlv_attestation_mr_extend_value_mr_hash_algo, \u0026ctlv_attestation_op_schemas[5].request,\n+\t    CTLV_ATTESTATION_ATTR_MR_HASH_ALGO, 2, 0, CTLV_SCHEMA_UINT)\n+CTLV_IN_HAS(ctlv_attestation_mr_extend_value_mr_hash_algo)\n+CTLV_IN_U64(ctlv_attestation_mr_extend_value_mr_hash_algo)\n+CTLV_IN_REF(ctlv_attestation_mr_extend_value_mr_data, \u0026ctlv_attestation_op_schemas[5].request,\n+\t    CTLV_ATTESTATION_ATTR_MR_DATA, 2, 1, CTLV_SCHEMA_BINARY)\n+CTLV_IN_HAS(ctlv_attestation_mr_extend_value_mr_data)\n+CTLV_IN_BINARY(ctlv_attestation_mr_extend_value_mr_data)\n+CTLV_IN_REF(ctlv_attestation_mr_log_get_mr_selection, \u0026ctlv_attestation_op_schemas[7].request,\n+\t    CTLV_ATTESTATION_ATTR_MR_SELECTION, 0, 0, CTLV_SCHEMA_NEST)\n+#define ctlv_attestation_mr_log_get_mr_selection_for_each(_attr, _nest) \\\n+\tCTLV_IN_FOR_EACH(ctlv_attestation_mr_log_get_mr_selection, _attr, _nest)\n+CTLV_IN_REF(ctlv_attestation_mr_log_get_mr_start_generation,\n+\t    \u0026ctlv_attestation_op_schemas[7].request, CTLV_ATTESTATION_ATTR_MR_START_GENERATION, 0,\n+\t    1, CTLV_SCHEMA_UINT)\n+CTLV_IN_HAS(ctlv_attestation_mr_log_get_mr_start_generation)\n+CTLV_IN_U64(ctlv_attestation_mr_log_get_mr_start_generation)\n+CTLV_IN_REF(ctlv_attestation_mr_log_get_mr_end_generation, \u0026ctlv_attestation_op_schemas[7].request,\n+\t    CTLV_ATTESTATION_ATTR_MR_END_GENERATION, 0, 2, CTLV_SCHEMA_UINT)\n+CTLV_IN_HAS(ctlv_attestation_mr_log_get_mr_end_generation)\n+CTLV_IN_U64(ctlv_attestation_mr_log_get_mr_end_generation)\n+CTLV_IN_REF(ctlv_attestation_mr_log_get_selection_mr_id, \u0026ctlv_attestation_op_schemas[7].request,\n+\t    CTLV_ATTESTATION_ATTR_MR_ID, 1, 0, CTLV_SCHEMA_UINT)\n+CTLV_IN_HAS(ctlv_attestation_mr_log_get_selection_mr_id)\n+CTLV_IN_U64(ctlv_attestation_mr_log_get_selection_mr_id)\n+\n+/* Writing a reply. An append is atomic; a nest ends with ctlv_nest_end(). */\n+CTLV_PUT_U64(ctlv_attestation_device_generation, CTLV_ATTESTATION_ATTR_DEVICE_GENERATION,\n+\t     CTLV_SCHEMA_UINT)\n+CTLV_NEST_START(ctlv_attestation_device_caps, CTLV_ATTESTATION_ATTR_DEVICE_CAPS, CTLV_SCHEMA_NEST)\n+CTLV_NEST_START(ctlv_attestation_device_info, CTLV_ATTESTATION_ATTR_DEVICE_INFO, CTLV_SCHEMA_NEST)\n+CTLV_NEST_START(ctlv_attestation_cap_evidence, CTLV_ATTESTATION_ATTR_CAP_EVIDENCE, CTLV_SCHEMA_NEST)\n+CTLV_NEST_START(ctlv_attestation_cap_mr, CTLV_ATTESTATION_ATTR_CAP_MR, CTLV_SCHEMA_NEST)\n+CTLV_PUT_U64(ctlv_attestation_cap_min_challenge_length,\n+\t     CTLV_ATTESTATION_ATTR_CAP_MIN_CHALLENGE_LENGTH, CTLV_SCHEMA_UINT)\n+CTLV_PUT_U64(ctlv_attestation_cap_max_challenge_length,\n+\t     CTLV_ATTESTATION_ATTR_CAP_MAX_CHALLENGE_LENGTH, CTLV_SCHEMA_UINT)\n+CTLV_PUT_U64(ctlv_attestation_cap_max_total_output_length,\n+\t     CTLV_ATTESTATION_ATTR_CAP_MAX_TOTAL_OUTPUT_LENGTH, CTLV_SCHEMA_UINT)\n+CTLV_PUT_U64(ctlv_attestation_cap_mr_flags, CTLV_ATTESTATION_ATTR_CAP_MR_FLAGS, CTLV_SCHEMA_FLAGS)\n+CTLV_NEST_START(ctlv_attestation_cap_object, CTLV_ATTESTATION_ATTR_CAP_OBJECT, CTLV_SCHEMA_NEST)\n+CTLV_PUT_U64(ctlv_attestation_cap_blob_class, CTLV_ATTESTATION_ATTR_CAP_BLOB_CLASS,\n+\t     CTLV_SCHEMA_ENUM)\n+CTLV_PUT_STRING(ctlv_attestation_cap_format, CTLV_ATTESTATION_ATTR_CAP_FORMAT, CTLV_SCHEMA_STRING)\n+CTLV_PUT_U64(ctlv_attestation_cap_representation, CTLV_ATTESTATION_ATTR_CAP_REPRESENTATION,\n+\t     CTLV_SCHEMA_ENUM)\n+CTLV_PUT_U64(ctlv_attestation_cap_max_length, CTLV_ATTESTATION_ATTR_CAP_MAX_LENGTH,\n+\t     CTLV_SCHEMA_UINT)\n+CTLV_PUT_BINARY(ctlv_attestation_evidence_challenge, CTLV_ATTESTATION_ATTR_EVIDENCE_CHALLENGE,\n+\t\tCTLV_SCHEMA_BINARY)\n+CTLV_NEST_START(ctlv_attestation_evidence_object, CTLV_ATTESTATION_ATTR_EVIDENCE_OBJECT,\n+\t\tCTLV_SCHEMA_NEST)\n+CTLV_PUT_U64(ctlv_attestation_evidence_blob_class, CTLV_ATTESTATION_ATTR_EVIDENCE_BLOB_CLASS,\n+\t     CTLV_SCHEMA_ENUM)\n+CTLV_PUT_STRING(ctlv_attestation_evidence_format, CTLV_ATTESTATION_ATTR_EVIDENCE_FORMAT,\n+\t\tCTLV_SCHEMA_STRING)\n+CTLV_PUT_U64(ctlv_attestation_evidence_representation,\n+\t     CTLV_ATTESTATION_ATTR_EVIDENCE_REPRESENTATION, CTLV_SCHEMA_ENUM)\n+CTLV_PUT_U64(ctlv_attestation_evidence_object_length, CTLV_ATTESTATION_ATTR_EVIDENCE_OBJECT_LENGTH,\n+\t     CTLV_SCHEMA_UINT)\n+CTLV_PUT_U64(ctlv_attestation_mr_id, CTLV_ATTESTATION_ATTR_MR_ID, CTLV_SCHEMA_UINT)\n+CTLV_PUT_STRING(ctlv_attestation_mr_name, CTLV_ATTESTATION_ATTR_MR_NAME, CTLV_SCHEMA_STRING)\n+CTLV_PUT_U64(ctlv_attestation_mr_hash_algo, CTLV_ATTESTATION_ATTR_MR_HASH_ALGO, CTLV_SCHEMA_UINT)\n+CTLV_PUT_U64(ctlv_attestation_mr_supported_hash_algo, CTLV_ATTESTATION_ATTR_MR_SUPPORTED_HASH_ALGO,\n+\t     CTLV_SCHEMA_UINT)\n+CTLV_PUT_U64(ctlv_attestation_mr_register_index, CTLV_ATTESTATION_ATTR_MR_REGISTER_INDEX,\n+\t     CTLV_SCHEMA_UINT)\n+CTLV_PUT_U64(ctlv_attestation_mr_caps, CTLV_ATTESTATION_ATTR_MR_CAPS, CTLV_SCHEMA_FLAGS)\n+CTLV_NEST_START(ctlv_attestation_mr_item, CTLV_ATTESTATION_ATTR_MR_ITEM, CTLV_SCHEMA_NEST)\n+CTLV_NEST_START(ctlv_attestation_mr_value, CTLV_ATTESTATION_ATTR_MR_VALUE, CTLV_SCHEMA_NEST)\n+CTLV_PUT_BINARY(ctlv_attestation_mr_data, CTLV_ATTESTATION_ATTR_MR_DATA, CTLV_SCHEMA_BINARY)\n+CTLV_PUT_U64(ctlv_attestation_mr_generation, CTLV_ATTESTATION_ATTR_MR_GENERATION, CTLV_SCHEMA_UINT)\n+CTLV_NEST_START(ctlv_attestation_mr_selection, CTLV_ATTESTATION_ATTR_MR_SELECTION, CTLV_SCHEMA_NEST)\n+CTLV_PUT_U64(ctlv_attestation_mr_start_generation, CTLV_ATTESTATION_ATTR_MR_START_GENERATION,\n+\t     CTLV_SCHEMA_UINT)\n+CTLV_PUT_U64(ctlv_attestation_mr_end_generation, CTLV_ATTESTATION_ATTR_MR_END_GENERATION,\n+\t     CTLV_SCHEMA_UINT)\n+CTLV_NEST_START(ctlv_attestation_log_entry, CTLV_ATTESTATION_ATTR_LOG_ENTRY, CTLV_SCHEMA_NEST)\n+CTLV_PUT_U64(ctlv_attestation_log_event, CTLV_ATTESTATION_ATTR_LOG_EVENT, CTLV_SCHEMA_ENUM)\n+CTLV_NEST_START(ctlv_attestation_log_mr, CTLV_ATTESTATION_ATTR_LOG_MR, CTLV_SCHEMA_NEST)\n+CTLV_NEST_START(ctlv_attestation_notification_entry, CTLV_ATTESTATION_ATTR_NOTIFICATION_ENTRY,\n+\t\tCTLV_SCHEMA_NEST)\n+\n+/* Building one event, passed to ctlv_event_emit() or ctlv_event_abort() once. */\n+CTLV_EVENT_CREATE(ctlv_attestation_mr_log_entry_appended, CTLV_ATTESTATION_OP_MR_LOG_ENTRY_APPENDED)\n+#endif /* _CTLV_GENERATED_METADATA_ONLY */\n+\n+#endif /* _LINUX_CTLV_ATTESTATION_GEN_H */\ndiff --git a/drivers/attestation/generated/ctlv_attestation_tdx_gen.c b/drivers/attestation/generated/ctlv_attestation_tdx_gen.c\nnew file mode 100644\nindex 0000000000000..25f03a8d68fea\n--- /dev/null\n+++ b/drivers/attestation/generated/ctlv_attestation_tdx_gen.c\n@@ -0,0 +1,61 @@\n+// SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)\n+/* Do not edit, regenerate with tools/ctlv/ctlv-regen.sh, from: */\n+/*\tDocumentation/ctlv/specs/ctlv-attestation-tdx.yaml */\n+/* CTLV-GEN kernel source */\n+\n+#define _CTLV_GENERATED_METADATA_ONLY\n+#include \u003clinux/array_size.h\u003e\n+#include \u003clinux/build_bug.h\u003e\n+#include \u003clinux/ctlv_family.h\u003e\n+#include \u003clinux/export.h\u003e\n+\n+#include \u003cuapi/linux/ctlv_gen.h\u003e\n+#include \u003cuapi/linux/ctlv_attestation_tdx_gen.h\u003e\n+\n+#include \"ctlv_attestation_tdx_gen.h\"\n+\n+static const struct ctlv_node_schema device_info_fill_node_schemas[] = {\n+\tCTLV_NODE_SCHEMA_ROOT(1, 3, 3),\n+\tCTLV_NODE_SCHEMA_BINARY(CTLV_ATTESTATION_TDX_ATTR_INFO_MRCONFIGID, 1, 48, 48),\n+\tCTLV_NODE_SCHEMA_BINARY(CTLV_ATTESTATION_TDX_ATTR_INFO_MROWNER, 1, 48, 48),\n+\tCTLV_NODE_SCHEMA_BINARY(CTLV_ATTESTATION_TDX_ATTR_INFO_MROWNERCONFIG, 1, 48, 48),\n+};\n+\n+/* The extension points this family fills. */\n+static const struct ctlv_stub_fill_schema ctlv_attestation_tdx_stub_fill_schemas[] = {\n+\tCTLV_STUB_FILL_SCHEMA(CTLV_FAMILY_ATTESTATION, CTLV_ATTESTATION_SET_DEVICE_INFO,\n+\t\t\t      device_info),\n+};\n+\n+/* The family ID is its position in the central registry. */\n+const struct ctlv_family_schema ctlv_attestation_tdx_schema = {\n+\t.name = \"ctlv-attestation-tdx\",\n+\t.family_id = 2,\n+\t.stub_fill_schemas = ctlv_attestation_tdx_stub_fill_schemas,\n+\t.stub_fill_schemas_count = ARRAY_SIZE(ctlv_attestation_tdx_stub_fill_schemas),\n+};\n+\n+/* Maximum uevent cost for this family chain. */\n+static_assert(150 \u003c= CTLV_UEVENT_MAX_LEN);\n+static_assert(5 \u003c= CTLV_UEVENT_MAX_VARS);\n+\n+/* Extension-point callbacks. */\n+static const struct ctlv_stub_ops ctlv_attestation_tdx_stub_ops[] = {\n+\tCTLV_STUB_OPS(CTLV_FAMILY_ATTESTATION, CTLV_ATTESTATION_SET_DEVICE_INFO,\n+\t\t      ctlv_attestation_tdx_device_info),\n+};\n+\n+/* Family descriptor used by ctlv_create(). */\n+const struct ctlv_family ctlv_attestation_tdx_family = {\n+\t.schema = \u0026ctlv_attestation_tdx_schema,\n+\t.parent = \u0026ctlv_attestation_family,\n+\t.pre = ctlv_attestation_tdx_op_pre,\n+\t.post = ctlv_attestation_tdx_op_post,\n+\t.priv_size = ctlv_attestation_tdx_priv_size,\n+\t.pre_init = ctlv_attestation_tdx_pre_init,\n+\t.init = ctlv_attestation_tdx_init,\n+\t.fini = ctlv_attestation_tdx_fini,\n+\t.stub_ops = ctlv_attestation_tdx_stub_ops,\n+\t.stub_ops_count = ARRAY_SIZE(ctlv_attestation_tdx_stub_ops),\n+};\n+EXPORT_SYMBOL_NS_GPL(ctlv_attestation_tdx_family, \"CTLV\");\ndiff --git a/drivers/attestation/generated/ctlv_attestation_tdx_gen.h b/drivers/attestation/generated/ctlv_attestation_tdx_gen.h\nnew file mode 100644\nindex 0000000000000..d182d04cb086b\n--- /dev/null\n+++ b/drivers/attestation/generated/ctlv_attestation_tdx_gen.h\n@@ -0,0 +1,66 @@\n+/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) */\n+/* Do not edit, regenerate with tools/ctlv/ctlv-regen.sh, from: */\n+/*\tDocumentation/ctlv/specs/ctlv-attestation-tdx.yaml */\n+/* CTLV-GEN kernel header */\n+\n+/* Kernel metadata and family API of the ctlv-attestation-tdx CTLV family. */\n+\n+#ifndef _LINUX_CTLV_ATTESTATION_TDX_GEN_H\n+#define _LINUX_CTLV_ATTESTATION_TDX_GEN_H\n+\n+#include \u003clinux/ctlv_family.h\u003e\n+#include \u003clinux/err.h\u003e\n+#include \u003clinux/errno.h\u003e\n+\n+#include \u003cuapi/linux/ctlv_attestation_tdx_gen.h\u003e\n+\n+#include \"ctlv_attestation_gen.h\"\n+\n+extern const struct ctlv_family_schema ctlv_attestation_tdx_schema;\n+\n+/* Family-wide hooks around every effective non-core op. */\n+int ctlv_attestation_tdx_op_pre(void *priv, struct ctlv_op_ctx *ctx);\n+void ctlv_attestation_tdx_op_post(void *priv, struct ctlv_op_ctx *ctx);\n+\n+/* Core-allocated family priv lifecycle. */\n+size_t ctlv_attestation_tdx_priv_size(void);\n+const void *ctlv_attestation_tdx_pre_init(const void *init_info);\n+int ctlv_attestation_tdx_init(struct ctlv_device *ctlvdev, const void *init_info, void *priv);\n+void ctlv_attestation_tdx_fini(struct ctlv_device *ctlvdev, void *priv);\n+\n+/* device-info of ctlv-attestation: fill callback. */\n+int ctlv_attestation_tdx_device_info_fill(void *priv, struct ctlv_op_ctx *ctx,\n+\t\t\t\t\t  const struct ctlv_cursor *request,\n+\t\t\t\t\t  struct ctlv_cursor *nest);\n+\n+extern const struct ctlv_family ctlv_attestation_tdx_family;\n+\n+#ifndef _CTLV_GENERATED_METADATA_ONLY\n+\n+/* Reading a validated message. A blob has a resolver instead of a getter. */\n+CTLV_IN_REF(ctlv_attestation_tdx_device_info_info_mrconfigid,\n+\t    \u0026ctlv_attestation_tdx_schema.stub_fill_schemas[0].members,\n+\t    CTLV_ATTESTATION_TDX_ATTR_INFO_MRCONFIGID, 0, 0, CTLV_SCHEMA_BINARY)\n+CTLV_IN_HAS(ctlv_attestation_tdx_device_info_info_mrconfigid)\n+CTLV_IN_BINARY(ctlv_attestation_tdx_device_info_info_mrconfigid)\n+CTLV_IN_REF(ctlv_attestation_tdx_device_info_info_mrowner,\n+\t    \u0026ctlv_attestation_tdx_schema.stub_fill_schemas[0].members,\n+\t    CTLV_ATTESTATION_TDX_ATTR_INFO_MROWNER, 0, 1, CTLV_SCHEMA_BINARY)\n+CTLV_IN_HAS(ctlv_attestation_tdx_device_info_info_mrowner)\n+CTLV_IN_BINARY(ctlv_attestation_tdx_device_info_info_mrowner)\n+CTLV_IN_REF(ctlv_attestation_tdx_device_info_info_mrownerconfig,\n+\t    \u0026ctlv_attestation_tdx_schema.stub_fill_schemas[0].members,\n+\t    CTLV_ATTESTATION_TDX_ATTR_INFO_MROWNERCONFIG, 0, 2, CTLV_SCHEMA_BINARY)\n+CTLV_IN_HAS(ctlv_attestation_tdx_device_info_info_mrownerconfig)\n+CTLV_IN_BINARY(ctlv_attestation_tdx_device_info_info_mrownerconfig)\n+\n+/* Writing a reply. An append is atomic; a nest ends with ctlv_nest_end(). */\n+CTLV_PUT_BINARY(ctlv_attestation_tdx_info_mrconfigid, CTLV_ATTESTATION_TDX_ATTR_INFO_MRCONFIGID,\n+\t\tCTLV_SCHEMA_BINARY)\n+CTLV_PUT_BINARY(ctlv_attestation_tdx_info_mrowner, CTLV_ATTESTATION_TDX_ATTR_INFO_MROWNER,\n+\t\tCTLV_SCHEMA_BINARY)\n+CTLV_PUT_BINARY(ctlv_attestation_tdx_info_mrownerconfig,\n+\t\tCTLV_ATTESTATION_TDX_ATTR_INFO_MROWNERCONFIG, CTLV_SCHEMA_BINARY)\n+#endif /* _CTLV_GENERATED_METADATA_ONLY */\n+\n+#endif /* _LINUX_CTLV_ATTESTATION_TDX_GEN_H */\ndiff --git a/drivers/attestation/providers/tdx.c b/drivers/attestation/providers/tdx.c\nnew file mode 100644\nindex 0000000000000..9b41b985c783a\n--- /dev/null\n+++ b/drivers/attestation/providers/tdx.c\n@@ -0,0 +1,277 @@\n+// SPDX-License-Identifier: GPL-2.0-only\n+#include \u003ccrypto/sha2.h\u003e\n+#include \u003clinux/attestation.h\u003e\n+#include \u003clinux/ctlv.h\u003e\n+#include \u003clinux/err.h\u003e\n+#include \u003clinux/module.h\u003e\n+#include \u003clinux/slab.h\u003e\n+#include \u003clinux/tdx-guest.h\u003e\n+\n+#include \"../generated/ctlv_attestation_tdx_gen.h\"\n+\n+struct attestation_tdx_init_info {\n+\tstruct device *parent_dev;\n+\tconst struct tdx_guest_ops *ops;\n+};\n+\n+struct attestation_tdx {\n+\tstruct device *parent_dev;\n+\tconst struct tdx_guest_ops *ops;\n+};\n+\n+static const enum hash_algo attestation_tdx_algorithms[] = {\n+\tHASH_ALGO_SHA384,\n+};\n+\n+static const struct attestation_mr_props attestation_tdx_mrs[] = {\n+\t{\n+\t\t.id = 0,\n+\t\t.name = \"mrtd\",\n+\t\t.algorithms = attestation_tdx_algorithms,\n+\t\t.algorithms_count = ARRAY_SIZE(attestation_tdx_algorithms),\n+\t\t.readable = true,\n+\t},\n+\t{\n+\t\t.id = 1,\n+\t\t.name = \"rtmr0\",\n+\t\t.algorithms = attestation_tdx_algorithms,\n+\t\t.algorithms_count = ARRAY_SIZE(attestation_tdx_algorithms),\n+\t\t.has_register_index = true,\n+\t\t.register_index = 0,\n+\t\t.readable = true,\n+\t\t.extendable = true,\n+\t},\n+\t{\n+\t\t.id = 2,\n+\t\t.name = \"rtmr1\",\n+\t\t.algorithms = attestation_tdx_algorithms,\n+\t\t.algorithms_count = ARRAY_SIZE(attestation_tdx_algorithms),\n+\t\t.has_register_index = true,\n+\t\t.register_index = 1,\n+\t\t.readable = true,\n+\t\t.extendable = true,\n+\t},\n+\t{\n+\t\t.id = 3,\n+\t\t.name = \"rtmr2\",\n+\t\t.algorithms = attestation_tdx_algorithms,\n+\t\t.algorithms_count = ARRAY_SIZE(attestation_tdx_algorithms),\n+\t\t.has_register_index = true,\n+\t\t.register_index = 2,\n+\t\t.readable = true,\n+\t\t.extendable = true,\n+\t},\n+\t{\n+\t\t.id = 4,\n+\t\t.name = \"rtmr3\",\n+\t\t.algorithms = attestation_tdx_algorithms,\n+\t\t.algorithms_count = ARRAY_SIZE(attestation_tdx_algorithms),\n+\t\t.has_register_index = true,\n+\t\t.register_index = 3,\n+\t\t.readable = true,\n+\t\t.extendable = true,\n+\t},\n+};\n+\n+static const struct attestation_evidence_supported_object\n+attestation_tdx_evidence_objects[] = {\n+\t{\n+\t\t.format = \"tdx-tdreport-1.0\",\n+\t\t.max_length = TDX_GUEST_REPORT_LEN,\n+\t\t.binds_mrs = true,\n+\t},\n+\t{\n+\t\t.format = \"tdx-quote-1.0\",\n+\t\t.max_length = TDX_GUEST_QUOTE_MAX_LEN,\n+\t\t.binds_mrs = true,\n+\t},\n+};\n+\n+static const struct attestation_evidence_caps attestation_tdx_evidence_caps = {\n+\t.min_challenge_length = TDX_GUEST_REPORTDATA_LEN,\n+\t.max_challenge_length = TDX_GUEST_REPORTDATA_LEN,\n+\t.max_total_output_length = TDX_GUEST_QUOTE_MAX_LEN,\n+\t.objects = attestation_tdx_evidence_objects,\n+\t.objects_count = ARRAY_SIZE(attestation_tdx_evidence_objects),\n+};\n+\n+static int\n+attestation_tdx_evidence_get(struct attestation *att,\n+\t\t\t     const struct attestation_evidence_request *request,\n+\t\t\t     struct attestation_evidence_result *result)\n+{\n+\tconst struct attestation_evidence_object_request *object;\n+\tstruct attestation_tdx *tdx = ctlv_priv_child(att);\n+\tsize_t length;\n+\tvoid *buffer;\n+\tint ret;\n+\n+\tif (request-\u003eobjects_count != 1)\n+\t\treturn -EOPNOTSUPP;\n+\tobject = \u0026request-\u003eobjects[0];\n+\tbuffer = kvmalloc(object-\u003esupported_object-\u003emax_length, GFP_KERNEL);\n+\tif (!buffer)\n+\t\treturn -ENOMEM;\n+\tif (object-\u003esupported_object == \u0026attestation_tdx_evidence_objects[0])\n+\t\tret = tdx-\u003eops-\u003ereport_get(tdx-\u003eparent_dev,\n+\t\t\trequest-\u003echallenge,\n+\t\t\trequest-\u003echallenge_length, buffer,\n+\t\t\tobject-\u003esupported_object-\u003emax_length, \u0026length);\n+\telse if (object-\u003esupported_object ==\n+\t\t \u0026attestation_tdx_evidence_objects[1])\n+\t\tret = tdx-\u003eops-\u003equote_get(tdx-\u003eparent_dev,\n+\t\t\trequest-\u003echallenge,\n+\t\t\trequest-\u003echallenge_length, buffer,\n+\t\t\tobject-\u003esupported_object-\u003emax_length, \u0026length);\n+\telse\n+\t\tret = -EOPNOTSUPP;\n+\tif (!ret)\n+\t\tret = ctlv_blob_write(object-\u003eoutput, 0, buffer, length);\n+\tif (!ret)\n+\t\tresult-\u003eobject_lengths[0] = length;\n+\tkvfree(buffer);\n+\treturn ret;\n+}\n+\n+static int attestation_tdx_mr_read(struct attestation *att, unsigned int mr_id,\n+\t\t\t\t   struct attestation_digest_set *values)\n+{\n+\tstatic const enum tdx_guest_mr native_mrs[] = {\n+\t\tTDX_GUEST_MR_MRTD,\n+\t\tTDX_GUEST_MR_RTMR0,\n+\t\tTDX_GUEST_MR_RTMR1,\n+\t\tTDX_GUEST_MR_RTMR2,\n+\t\tTDX_GUEST_MR_RTMR3,\n+\t};\n+\tstruct attestation_tdx *tdx = ctlv_priv_child(att);\n+\n+\tif (mr_id \u003e= ARRAY_SIZE(native_mrs) ||\n+\t    values-\u003evalues_count != 1 ||\n+\t    values-\u003evalues[0].algorithm != HASH_ALGO_SHA384)\n+\t\treturn -EINVAL;\n+\treturn tdx-\u003eops-\u003emr_read(tdx-\u003eparent_dev, native_mrs[mr_id],\n+\t\tvalues-\u003evalues[0].data);\n+}\n+\n+static int\n+attestation_tdx_mr_extend(struct attestation *att, unsigned int mr_id,\n+\t\t\t  const struct attestation_digest_set *values)\n+{\n+\tstruct attestation_tdx *tdx = ctlv_priv_child(att);\n+\n+\tif (mr_id \u003c 1 || mr_id \u003e 4)\n+\t\treturn -EOPNOTSUPP;\n+\tif (values-\u003evalues_count != 1 ||\n+\t    values-\u003evalues[0].algorithm != HASH_ALGO_SHA384)\n+\t\treturn -EINVAL;\n+\treturn tdx-\u003eops-\u003ertmr_extend(tdx-\u003eparent_dev, mr_id - 1,\n+\t\t\t\t     values-\u003evalues[0].data);\n+}\n+\n+static const struct attestation_provider attestation_tdx_provider = {\n+\t.evidence_get = attestation_tdx_evidence_get,\n+\t.mr_read = attestation_tdx_mr_read,\n+\t.mr_extend = attestation_tdx_mr_extend,\n+\t.evidence_caps = \u0026attestation_tdx_evidence_caps,\n+\t.mrs = attestation_tdx_mrs,\n+\t.mrs_count = ARRAY_SIZE(attestation_tdx_mrs),\n+};\n+\n+size_t ctlv_attestation_tdx_priv_size(void)\n+{\n+\treturn sizeof(struct attestation_tdx);\n+}\n+\n+const void *ctlv_attestation_tdx_pre_init(const void *init_info)\n+{\n+\treturn \u0026attestation_tdx_provider;\n+}\n+\n+int ctlv_attestation_tdx_init(struct ctlv_device *ctlvdev,\n+\t\t\t      const void *init_info, void *priv)\n+{\n+\tconst struct attestation_tdx_init_info *info = init_info;\n+\tstruct attestation_tdx *tdx = priv;\n+\n+\tif (!info || !info-\u003eparent_dev || !info-\u003eops)\n+\t\treturn -EINVAL;\n+\ttdx-\u003eparent_dev = info-\u003eparent_dev;\n+\ttdx-\u003eops = info-\u003eops;\n+\treturn 0;\n+}\n+\n+void ctlv_attestation_tdx_fini(struct ctlv_device *ctlvdev, void *priv)\n+{\n+}\n+\n+int ctlv_attestation_tdx_op_pre(void *priv, struct ctlv_op_ctx *ctx)\n+{\n+\treturn ctlv_attestation_op_pre(ctlv_priv_parent(priv), ctx);\n+}\n+\n+void ctlv_attestation_tdx_op_post(void *priv, struct ctlv_op_ctx *ctx)\n+{\n+\tctlv_attestation_op_post(ctlv_priv_parent(priv), ctx);\n+}\n+\n+int ctlv_attestation_tdx_device_info_fill(void *priv,\n+\t\t\t\t\t  struct ctlv_op_ctx *ctx,\n+\t\t\t\t\t  const struct ctlv_cursor *request,\n+\t\t\t\t\t  struct ctlv_cursor *nest)\n+{\n+\tstruct attestation_tdx *tdx = priv;\n+\tconst struct tdx_guest_info *info =\n+\t\ttdx-\u003eops-\u003einfo_get(tdx-\u003eparent_dev);\n+\tbool ok;\n+\n+\tif (!info)\n+\t\treturn -ENODEV;\n+\tok = ctlv_attestation_tdx_info_mrconfigid_put(nest, info-\u003emrconfigid,\n+\t\t\t\t\t\t      sizeof(info-\u003emrconfigid));\n+\tok \u0026= ctlv_attestation_tdx_info_mrowner_put(nest, info-\u003emrowner,\n+\t\t\t\t\t\t    sizeof(info-\u003emrowner));\n+\tok \u0026= ctlv_attestation_tdx_info_mrownerconfig_put(nest,\n+\t\t\t\t\t\t\t   info-\u003emrownerconfig,\n+\t\t\t\t\t\t\t   sizeof(info-\u003emrownerconfig));\n+\treturn ok ? 0 : -EMSGSIZE;\n+}\n+\n+static void *attestation_tdx_add(struct device *parent_dev,\n+\t\t\t\t const struct tdx_guest_ops *ops)\n+{\n+\tstruct attestation_tdx_init_info info = {\n+\t\t.parent_dev = parent_dev,\n+\t\t.ops = ops,\n+\t};\n+\n+\treturn ctlv_create(parent_dev, \u0026ctlv_attestation_tdx_family,\n+\t\t\t   \u0026info);\n+}\n+\n+static void attestation_tdx_remove(void *client_priv)\n+{\n+\tctlv_destroy(client_priv);\n+}\n+\n+static const struct tdx_guest_client attestation_tdx_client = {\n+\t.add = attestation_tdx_add,\n+\t.remove = attestation_tdx_remove,\n+};\n+\n+static int __init attestation_tdx_init_module(void)\n+{\n+\treturn tdx_guest_client_register(\u0026attestation_tdx_client);\n+}\n+\n+static void __exit attestation_tdx_exit_module(void)\n+{\n+\ttdx_guest_client_unregister(\u0026attestation_tdx_client);\n+}\n+\n+module_init(attestation_tdx_init_module);\n+module_exit(attestation_tdx_exit_module);\n+MODULE_DESCRIPTION(\"TDX attestation provider\");\n+MODULE_LICENSE(\"GPL\");\n+MODULE_IMPORT_NS(\"ATTESTATION\");\n+MODULE_IMPORT_NS(\"CTLV\");\n+MODULE_IMPORT_NS(\"TDX_GUEST\");\ndiff --git a/drivers/ctlv/Kconfig b/drivers/ctlv/Kconfig\nnew file mode 100644\nindex 0000000000000..aed3243c55fd4\n--- /dev/null\n+++ b/drivers/ctlv/Kconfig\n@@ -0,0 +1,12 @@\n+# SPDX-License-Identifier: GPL-2.0-only\n+menuconfig CTLV\n+\ttristate \"CTLV character device TLV UAPI\"\n+\thelp\n+\t  CTLV provides character device UAPIs described by a checked-in YAML\n+\t  specification. It owns the character device lifetime, the strict TLV\n+\t  message format, request validation, reply serialization, the large\n+\t  payloads a request describes rather than carries, per-open event\n+\t  queues and runtime schema introspection, so families only implement\n+\t  semantics.\n+\n+\t  If you don't know what to do here, say N.\ndiff --git a/drivers/ctlv/Makefile b/drivers/ctlv/Makefile\nnew file mode 100644\nindex 0000000000000..2f6fe8d2db735\n--- /dev/null\n+++ b/drivers/ctlv/Makefile\n@@ -0,0 +1,5 @@\n+# SPDX-License-Identifier: GPL-2.0\n+obj-$(CONFIG_CTLV) += ctlv.o\n+\n+ctlv-y += blob.o blob_desc.o builder.o core.o event.o introspection.o \\\n+\t  message.o schema.o ctlv_gen.o\ndiff --git a/drivers/ctlv/blob.c b/drivers/ctlv/blob.c\nnew file mode 100644\nindex 0000000000000..2c93da62b2010\n--- /dev/null\n+++ b/drivers/ctlv/blob.c\n@@ -0,0 +1,355 @@\n+// SPDX-License-Identifier: GPL-2.0-only\n+/*\n+ * Copyright (c) 2026, NVIDIA CORPORATION \u0026 AFFILIATES\n+ *\n+ * Blob backing is acquired lazily in the submitting task and held until put.\n+ */\n+#include \u003clinux/align.h\u003e\n+#include \u003clinux/atomic.h\u003e\n+#include \u003clinux/bits.h\u003e\n+#include \u003clinux/capability.h\u003e\n+#include \u003clinux/ctlv.h\u003e\n+#include \u003clinux/err.h\u003e\n+#include \u003clinux/errno.h\u003e\n+#include \u003clinux/highmem.h\u003e\n+#include \u003clinux/limits.h\u003e\n+#include \u003clinux/minmax.h\u003e\n+#include \u003clinux/mm.h\u003e\n+#include \u003clinux/mm_types.h\u003e\n+#include \u003clinux/overflow.h\u003e\n+#include \u003clinux/sched.h\u003e\n+#include \u003clinux/sched/mm.h\u003e\n+#include \u003clinux/sched/signal.h\u003e\n+#include \u003clinux/slab.h\u003e\n+#include \u003clinux/types.h\u003e\n+\n+#include \u003cuapi/linux/ctlv.h\u003e\n+#include \u003cuapi/linux/ctlv_gen.h\u003e\n+\n+#include \"blob.h\"\n+#include \"blob_desc.h\"\n+#include \"internal.h\"\n+#include \"message.h\"\n+\n+struct ctlv_blob {\n+\tu64 len;\n+\tu8 direction;\n+\tu8 type;\n+\tstruct ctlv_op_ctx *ctx;\n+\tstruct list_head entry;\n+\tunion {\n+\t\tstruct {\n+\t\t\tstruct mm_struct *mm;\n+\t\t\tstruct page **pages;\n+\t\t\tunsigned long pages_count;\n+\t\t\tu32 start;\n+\t\t} va;\n+\t};\n+};\n+\n+static bool ctlv_blob_readable(const struct ctlv_blob *blob)\n+{\n+\treturn blob-\u003edirection != CTLV_BLOB_DIRECTION_OUTPUT;\n+}\n+\n+static bool ctlv_blob_writable(const struct ctlv_blob *blob)\n+{\n+\treturn blob-\u003edirection != CTLV_BLOB_DIRECTION_INPUT;\n+}\n+\n+static bool ctlv_blob_same_task(const struct ctlv_blob *blob)\n+{\n+\treturn !blob-\u003ectx || !blob-\u003ectx-\u003esubmitter || blob-\u003ectx-\u003esubmitter == current;\n+}\n+\n+static bool ctlv_blob_access_live(const struct ctlv_blob *blob)\n+{\n+\treturn ctlv_blob_same_task(blob) \u0026\u0026 (!blob-\u003ectx || blob-\u003ectx-\u003eblobs_live);\n+}\n+\n+/*\n+ * Charged against RLIMIT_MEMLOCK of the address space the pages came from. A\n+ * pin lasts one op, which is why it is not FOLL_LONGTERM.\n+ */\n+static int ctlv_blob_pin_charge(struct mm_struct *mm, unsigned long pages_count)\n+{\n+\tunsigned long limit = rlimit(RLIMIT_MEMLOCK) \u003e\u003e PAGE_SHIFT;\n+\n+\tif (atomic64_add_return(pages_count, \u0026mm-\u003epinned_vm) \u003e limit \u0026\u0026 !capable(CAP_IPC_LOCK)) {\n+\t\tatomic64_sub(pages_count, \u0026mm-\u003epinned_vm);\n+\t\treturn -ENOMEM;\n+\t}\n+\treturn 0;\n+}\n+\n+static int ctlv_blob_va_range(u64 address, u64 len, unsigned long *first_page,\n+\t\t\t      unsigned long *pages_count)\n+{\n+\tunsigned long first, last, span, count;\n+\tsize_t bytes;\n+\tu64 end;\n+\n+\tif (!len)\n+\t\treturn -EINVAL;\n+\tif (check_add_overflow(address, len, \u0026end) || end \u003e TASK_SIZE)\n+\t\treturn -EFAULT;\n+\n+\t/* Bounded by an unsigned long above, so nothing below loses a bit. */\n+\tfirst = (unsigned long)address \u0026 PAGE_MASK;\n+\tlast = ((unsigned long)end - 1) \u0026 PAGE_MASK;\n+\tif (check_sub_overflow(last, first, \u0026span) ||\n+\t    check_add_overflow(span \u003e\u003e PAGE_SHIFT, 1UL, \u0026count) ||\n+\t    check_mul_overflow(count, sizeof(struct page *), \u0026bytes))\n+\t\treturn -EFAULT;\n+\n+\t*first_page = first;\n+\t*pages_count = count;\n+\treturn 0;\n+}\n+\n+static int ctlv_blob_va_acquire(struct ctlv_blob *blob, u64 address)\n+{\n+\tunsigned long pinned = 0, first, pages_count;\n+\tunsigned int gup_flags = 0;\n+\tstruct page **pages;\n+\tint ret;\n+\n+\t/* Before charging or allocating, both of which this sizes. */\n+\tret = ctlv_blob_va_range(address, blob-\u003elen, \u0026first, \u0026pages_count);\n+\tif (ret)\n+\t\treturn ret;\n+\n+\tpages = kvmalloc_array(pages_count, sizeof(*pages), GFP_KERNEL_ACCOUNT);\n+\tif (!pages)\n+\t\treturn -ENOMEM;\n+\n+\tif (ctlv_blob_writable(blob))\n+\t\tgup_flags |= FOLL_WRITE;\n+\tret = ctlv_blob_pin_charge(current-\u003emm, pages_count);\n+\tif (ret)\n+\t\tgoto err_free_pages;\n+\n+\twhile (pinned \u003c pages_count) {\n+\t\tlong got = pin_user_pages_fast(first + (pinned \u003c\u003c PAGE_SHIFT),\n+\t\t\t\t\t       min_t(unsigned long, pages_count - pinned, INT_MAX),\n+\t\t\t\t\t       gup_flags, pages + pinned);\n+\n+\t\t/* A short pin is progress; nothing pinned is the caller's. */\n+\t\tif (got \u003c= 0) {\n+\t\t\tret = got ? (int)got : -EFAULT;\n+\t\t\tgoto err_unpin;\n+\t\t}\n+\t\tpinned += got;\n+\t}\n+\n+\t/* Referenced, so the unpin is safe however far the submitter got. */\n+\tmmgrab(current-\u003emm);\n+\tblob-\u003eva.start = offset_in_page(address);\n+\tblob-\u003eva.mm = current-\u003emm;\n+\tblob-\u003eva.pages = pages;\n+\tblob-\u003eva.pages_count = pages_count;\n+\treturn 0;\n+\n+\t/* The pins taken, and the whole charge, which covered every page. */\n+err_unpin:\n+\tunpin_user_pages(pages, pinned);\n+\tatomic64_sub(pages_count, \u0026current-\u003emm-\u003epinned_vm);\n+err_free_pages:\n+\tkvfree(pages);\n+\treturn ret;\n+}\n+\n+static void ctlv_blob_va_release(struct ctlv_blob *blob)\n+{\n+\t/* Dirtied, so that what the kernel wrote survives the unpin. */\n+\tunpin_user_pages_dirty_lock(blob-\u003eva.pages, blob-\u003eva.pages_count, ctlv_blob_writable(blob));\n+\tatomic64_sub(blob-\u003eva.pages_count, \u0026blob-\u003eva.mm-\u003epinned_vm);\n+\tkvfree(blob-\u003eva.pages);\n+\tmmdrop(blob-\u003eva.mm);\n+}\n+\n+static void ctlv_blob_va_copy(struct ctlv_blob *blob, u64 offset, void *buf, size_t len, bool write)\n+{\n+\tu64 at = blob-\u003eva.start + offset;\n+\tunsigned long index = at \u003e\u003e PAGE_SHIFT;\n+\tu32 in_page = offset_in_page(at);\n+\tu8 *bytes = buf;\n+\n+\twhile (len) {\n+\t\tstruct page *page = blob-\u003eva.pages[index++];\n+\t\tsize_t step = min_t(size_t, len, PAGE_SIZE - in_page);\n+\n+\t\tif (write)\n+\t\t\tmemcpy_to_page(page, in_page, bytes, step);\n+\t\telse\n+\t\t\tmemcpy_from_page(bytes, page, in_page, step);\n+\t\tbytes += step;\n+\t\tlen -= step;\n+\t\tin_page = 0;\n+\t}\n+}\n+\n+u64 ctlv_blob_len(const struct ctlv_blob *blob)\n+{\n+\treturn blob-\u003elen;\n+}\n+EXPORT_SYMBOL_NS_GPL(ctlv_blob_len, \"CTLV\");\n+\n+/*\n+ * The length, the direction and addressing from zero are all the family's own\n+ * to know, so getting one wrong is a kernel bug rather than a caller's.\n+ */\n+static bool ctlv_blob_range_ok(struct ctlv_blob *blob, u64 offset, size_t len, bool write)\n+{\n+\tu64 end;\n+\n+\tif (WARN_ON_ONCE(write ? !ctlv_blob_writable(blob) : !ctlv_blob_readable(blob)))\n+\t\treturn false;\n+\tif (WARN_ON_ONCE(!ctlv_blob_access_live(blob)))\n+\t\treturn false;\n+\tif (WARN_ON_ONCE(check_add_overflow(offset, (u64)len, \u0026end) || end \u003e blob-\u003elen))\n+\t\treturn false;\n+\treturn true;\n+}\n+\n+static int ctlv_blob_copy(struct ctlv_blob *blob, u64 offset, void *buf, size_t len, bool write)\n+{\n+\tif (!ctlv_blob_range_ok(blob, offset, len, write))\n+\t\treturn -EINVAL;\n+\tif (!len)\n+\t\treturn 0;\n+\n+\tswitch (blob-\u003etype) {\n+\tcase CTLV_BLOB_TYPE_VA:\n+\t\tctlv_blob_va_copy(blob, offset, buf, len, write);\n+\t\treturn 0;\n+\tdefault:\n+\t\treturn -EINVAL;\n+\t}\n+}\n+\n+int ctlv_blob_read(struct ctlv_blob *blob, u64 offset, void *dst, size_t len)\n+{\n+\treturn ctlv_blob_copy(blob, offset, dst, len, false);\n+}\n+EXPORT_SYMBOL_NS_GPL(ctlv_blob_read, \"CTLV\");\n+\n+int ctlv_blob_write(struct ctlv_blob *blob, u64 offset, const void *src, size_t len)\n+{\n+\treturn ctlv_blob_copy(blob, offset, (void *)src, len, true);\n+}\n+EXPORT_SYMBOL_NS_GPL(ctlv_blob_write, \"CTLV\");\n+\n+int ctlv_blob_put(struct ctlv_blob *blob)\n+{\n+\tif (!blob)\n+\t\treturn 0;\n+\tif (WARN_ON_ONCE(!ctlv_blob_same_task(blob)))\n+\t\treturn -EINVAL;\n+\n+\tswitch (blob-\u003etype) {\n+\tcase CTLV_BLOB_TYPE_VA:\n+\t\tctlv_blob_va_release(blob);\n+\t\tbreak;\n+\t}\n+\tif (blob-\u003ectx) {\n+\t\tlist_del(\u0026blob-\u003eentry);\n+\t\tblob-\u003ectx = NULL;\n+\t}\n+\tkfree(blob);\n+\treturn 0;\n+}\n+EXPORT_SYMBOL_NS_GPL(ctlv_blob_put, \"CTLV\");\n+\n+void ctlv_blob_context_init(struct ctlv_op_ctx *ctx)\n+{\n+\tINIT_LIST_HEAD(\u0026ctx-\u003eblobs);\n+\tctx-\u003eblobs_live = true;\n+\tctx-\u003eblob_error = 0;\n+}\n+\n+void ctlv_blob_context_track(struct ctlv_blob *blob, struct ctlv_op_ctx *ctx)\n+{\n+\tblob-\u003ectx = ctx;\n+\tlist_add_tail(\u0026blob-\u003eentry, \u0026ctx-\u003eblobs);\n+}\n+\n+int ctlv_blob_context_finish(struct ctlv_op_ctx *ctx)\n+{\n+\tctx-\u003eblobs_live = false;\n+\tif (WARN_ON_ONCE(!list_empty(\u0026ctx-\u003eblobs)) \u0026\u0026 !ctx-\u003eblob_error)\n+\t\tctx-\u003eblob_error = -EINVAL;\n+\twhile (!list_empty(\u0026ctx-\u003eblobs)) {\n+\t\tstruct ctlv_blob *blob = list_first_entry(\u0026ctx-\u003eblobs, struct ctlv_blob, entry);\n+\n+\t\tctlv_blob_put(blob);\n+\t}\n+\treturn ctx-\u003eblob_error;\n+}\n+\n+/*\n+ * Which of an op's blobs was the unusable one, in the shape validation would\n+ * have used. The errno the family returns says what went wrong.\n+ */\n+static void ctlv_blob_context_fail(struct ctlv_op_ctx *ctx, const struct ctlv_cursor *cursor)\n+{\n+\tif (ctx-\u003eerror.reason)\n+\t\treturn;\n+\tctx-\u003eerror = (struct ctlv_error){\n+\t\t.reason = CTLV_VALIDATION_REASON_BAD_BLOB_DESCRIPTOR,\n+\t\t.bad_attr_offset = ctlv_message_offset(cursor-\u003emsg, cursor-\u003eattr),\n+\t\t.nest_offset = ctlv_message_offset(cursor-\u003emsg, cursor-\u003eparent),\n+\t};\n+}\n+\n+static struct ctlv_blob *ctlv_blob_acquire(const struct ctlv_blob_desc *desc, u8 direction)\n+{\n+\tu64 address = desc-\u003emember[CTLV_BLOB_MEMBER_ADDRESS];\n+\tu64 len = desc-\u003emember[CTLV_BLOB_MEMBER_LENGTH];\n+\tstruct ctlv_blob *blob;\n+\tint ret;\n+\n+\tblob = kzalloc_obj(*blob, GFP_KERNEL_ACCOUNT);\n+\tif (!blob)\n+\t\treturn ERR_PTR(-ENOMEM);\n+\tINIT_LIST_HEAD(\u0026blob-\u003eentry);\n+\tblob-\u003elen = len;\n+\tblob-\u003edirection = direction;\n+\tblob-\u003etype = desc-\u003emember[CTLV_BLOB_MEMBER_TYPE];\n+\n+\tret = ctlv_blob_va_acquire(blob, address);\n+\tif (ret) {\n+\t\tkfree(blob);\n+\t\treturn ERR_PTR(ret);\n+\t}\n+\treturn blob;\n+}\n+\n+struct ctlv_blob *ctlv_blob_resolve(struct ctlv_op_ctx *ctx, const struct ctlv_cursor *blob)\n+{\n+\tconst struct ctlv_attr *bad = NULL;\n+\tconst struct ctlv_node_schema *node;\n+\tstruct ctlv_blob_desc desc;\n+\tstruct ctlv_blob *acquired;\n+\n+\t/* An absent blob, or a cursor from some other execution entirely. */\n+\tif (WARN_ON_ONCE(blob-\u003emsg != \u0026ctx-\u003erequest || !ctlv_attr_ok(blob)))\n+\t\treturn ERR_PTR(-EINVAL);\n+\tnode = \u0026blob-\u003etree-\u003enode_schemas[blob-\u003enode];\n+\tif (WARN_ON_ONCE(node-\u003ekind != CTLV_SCHEMA_BLOB))\n+\t\treturn ERR_PTR(-EINVAL);\n+\tif (WARN_ON_ONCE(!ctx-\u003eblobs_live || !ctx-\u003esubmitter || ctx-\u003esubmitter != current))\n+\t\treturn ERR_PTR(-EINVAL);\n+\t/* Validated before the callback, so anything wrong with it is a bug. */\n+\tif (WARN_ON_ONCE(ctlv_blob_desc_read(blob-\u003eattr, \u0026desc, \u0026bad) ||\n+\t\t\t ctlv_blob_desc_check(\u0026desc, node)))\n+\t\treturn ERR_PTR(-EINVAL);\n+\n+\tacquired = ctlv_blob_acquire(\u0026desc, node-\u003eblob.direction);\n+\tif (IS_ERR(acquired))\n+\t\tctlv_blob_context_fail(ctx, blob);\n+\telse\n+\t\tctlv_blob_context_track(acquired, ctx);\n+\treturn acquired;\n+}\n+EXPORT_SYMBOL_NS_GPL(ctlv_blob_resolve, \"CTLV\");\ndiff --git a/drivers/ctlv/blob.h b/drivers/ctlv/blob.h\nnew file mode 100644\nindex 0000000000000..bb7b933a1ced8\n--- /dev/null\n+++ b/drivers/ctlv/blob.h\n@@ -0,0 +1,15 @@\n+/* SPDX-License-Identifier: GPL-2.0-only */\n+#ifndef _CTLV_BLOB_H\n+#define _CTLV_BLOB_H\n+\n+#include \u003clinux/types.h\u003e\n+\n+struct ctlv_blob;\n+struct ctlv_op_ctx;\n+\n+void ctlv_blob_context_init(struct ctlv_op_ctx *ctx);\n+void ctlv_blob_context_track(struct ctlv_blob *blob,\n+\t\t\t     struct ctlv_op_ctx *ctx);\n+int ctlv_blob_context_finish(struct ctlv_op_ctx *ctx);\n+\n+#endif /* _CTLV_BLOB_H */\ndiff --git a/drivers/ctlv/blob_desc.c b/drivers/ctlv/blob_desc.c\nnew file mode 100644\nindex 0000000000000..b84be3d723abd\n--- /dev/null\n+++ b/drivers/ctlv/blob_desc.c\n@@ -0,0 +1,102 @@\n+// SPDX-License-Identifier: GPL-2.0-only\n+/*\n+ * Copyright (c) 2026, NVIDIA CORPORATION \u0026 AFFILIATES\n+ *\n+ * Blob descriptor parsing and validation.\n+ */\n+#include \u003clinux/align.h\u003e\n+#include \u003clinux/bits.h\u003e\n+#include \u003clinux/overflow.h\u003e\n+#include \u003clinux/types.h\u003e\n+\n+#include \u003cuapi/linux/ctlv.h\u003e\n+#include \u003cuapi/linux/ctlv_gen.h\u003e\n+\n+#include \"blob_desc.h\"\n+#include \"message.h\"\n+\n+static int ctlv_blob_member(u64 attr_id)\n+{\n+\tswitch (attr_id) {\n+\tcase CTLV_ATTR_BLOB_TYPE:\n+\t\treturn CTLV_BLOB_MEMBER_TYPE;\n+\tcase CTLV_ATTR_BLOB_ADDRESS:\n+\t\treturn CTLV_BLOB_MEMBER_ADDRESS;\n+\tcase CTLV_ATTR_BLOB_FD:\n+\t\treturn CTLV_BLOB_MEMBER_FD;\n+\tcase CTLV_ATTR_BLOB_OFFSET:\n+\t\treturn CTLV_BLOB_MEMBER_OFFSET;\n+\tcase CTLV_ATTR_BLOB_LENGTH:\n+\t\treturn CTLV_BLOB_MEMBER_LENGTH;\n+\tdefault:\n+\t\treturn -1;\n+\t}\n+}\n+\n+u32 ctlv_blob_desc_read(const struct ctlv_attr *blob, struct ctlv_blob_desc *desc,\n+\t\t\tconst struct ctlv_attr **bad)\n+{\n+\tconst struct ctlv_attr *child = NULL;\n+\tenum ctlv_message_step step;\n+\n+\t*desc = (struct ctlv_blob_desc){};\n+\twhile ((step = ctlv_message_next(blob, \u0026child)) == CTLV_MESSAGE_STEP_ATTR) {\n+\t\tint member = ctlv_blob_member(child-\u003eattr_id);\n+\n+\t\t*bad = child;\n+\t\tif (child-\u003eflags \u0026 ~CTLV_ATTR_F_NESTED)\n+\t\t\treturn CTLV_VALIDATION_REASON_UNKNOWN_FLAG;\n+\t\tif (child-\u003eflags \u0026 CTLV_ATTR_F_NESTED)\n+\t\t\treturn CTLV_VALIDATION_REASON_MALFORMED_MESSAGE;\n+\t\tif (member \u003c 0)\n+\t\t\treturn CTLV_VALIDATION_REASON_UNKNOWN_ATTR;\n+\t\tif (ctlv_message_attr_payload_len(child) != sizeof(u64))\n+\t\t\treturn CTLV_VALIDATION_REASON_BAD_LENGTH;\n+\t\tif (desc-\u003epresent \u0026 BIT(member))\n+\t\t\treturn CTLV_VALIDATION_REASON_BAD_BLOB_DESCRIPTOR;\n+\t\tdesc-\u003epresent |= BIT(member);\n+\t\tdesc-\u003emember[member] = *(const u64 *)ctlv_message_attr_payload(child);\n+\t}\n+\t*bad = NULL;\n+\tif (step == CTLV_MESSAGE_STEP_BAD)\n+\t\treturn CTLV_VALIDATION_REASON_MALFORMED_MESSAGE;\n+\treturn 0;\n+}\n+\n+static u32 ctlv_blob_variant(const struct ctlv_blob_desc *desc)\n+{\n+\tu32 required = BIT(CTLV_BLOB_MEMBER_TYPE) | BIT(CTLV_BLOB_MEMBER_LENGTH);\n+\n+\tswitch (desc-\u003emember[CTLV_BLOB_MEMBER_TYPE]) {\n+\tcase CTLV_BLOB_TYPE_VA:\n+\t\trequired |= BIT(CTLV_BLOB_MEMBER_ADDRESS);\n+\t\tbreak;\n+\tdefault:\n+\t\treturn CTLV_VALIDATION_REASON_BAD_BLOB_DESCRIPTOR;\n+\t}\n+\tif (desc-\u003epresent != required)\n+\t\treturn CTLV_VALIDATION_REASON_BAD_BLOB_DESCRIPTOR;\n+\treturn 0;\n+}\n+\n+u32 ctlv_blob_desc_check(const struct ctlv_blob_desc *desc, const struct ctlv_node_schema *node)\n+{\n+\tu64 start, length, end;\n+\tu32 reason;\n+\n+\treason = ctlv_blob_variant(desc);\n+\tif (reason)\n+\t\treturn reason;\n+\tif (!(node-\u003eblob.backings \u0026 BIT(desc-\u003emember[CTLV_BLOB_MEMBER_TYPE])))\n+\t\treturn CTLV_VALIDATION_REASON_BAD_BLOB_DESCRIPTOR;\n+\n+\tlength = desc-\u003emember[CTLV_BLOB_MEMBER_LENGTH];\n+\tif (!length || length \u003e node-\u003eblob.max_len)\n+\t\treturn CTLV_VALIDATION_REASON_BAD_BLOB_DESCRIPTOR;\n+\tstart = desc-\u003emember[desc-\u003epresent \u0026 BIT(CTLV_BLOB_MEMBER_ADDRESS) ?\n+\t\t\t\t     CTLV_BLOB_MEMBER_ADDRESS :\n+\t\t\t\t     CTLV_BLOB_MEMBER_OFFSET];\n+\tif (!IS_ALIGNED(start, node-\u003eblob.alignment) || check_add_overflow(start, length, \u0026end))\n+\t\treturn CTLV_VALIDATION_REASON_BAD_BLOB_DESCRIPTOR;\n+\treturn 0;\n+}\ndiff --git a/drivers/ctlv/blob_desc.h b/drivers/ctlv/blob_desc.h\nnew file mode 100644\nindex 0000000000000..27f77af16f019\n--- /dev/null\n+++ b/drivers/ctlv/blob_desc.h\n@@ -0,0 +1,29 @@\n+/* SPDX-License-Identifier: GPL-2.0-only */\n+#ifndef _CTLV_BLOB_DESC_H\n+#define _CTLV_BLOB_DESC_H\n+\n+#include \u003clinux/ctlv_family.h\u003e\n+#include \u003clinux/types.h\u003e\n+\n+#include \u003cuapi/linux/ctlv.h\u003e\n+\n+/* The members of a descriptor, in the order the root family declares them. */\n+enum {\n+\tCTLV_BLOB_MEMBER_TYPE,\n+\tCTLV_BLOB_MEMBER_ADDRESS,\n+\tCTLV_BLOB_MEMBER_FD,\n+\tCTLV_BLOB_MEMBER_OFFSET,\n+\tCTLV_BLOB_MEMBER_LENGTH,\n+\tCTLV_BLOB_MEMBERS,\n+};\n+\n+struct ctlv_blob_desc {\n+\tu64 member[CTLV_BLOB_MEMBERS];\n+\tu32 present;\n+};\n+\n+u32 ctlv_blob_desc_read(const struct ctlv_attr *blob, struct ctlv_blob_desc *desc,\n+\t\t\tconst struct ctlv_attr **bad);\n+u32 ctlv_blob_desc_check(const struct ctlv_blob_desc *desc, const struct ctlv_node_schema *node);\n+\n+#endif /* _CTLV_BLOB_DESC_H */\ndiff --git a/drivers/ctlv/builder.c b/drivers/ctlv/builder.c\nnew file mode 100644\nindex 0000000000000..41748ceae1a34\n--- /dev/null\n+++ b/drivers/ctlv/builder.c\n@@ -0,0 +1,374 @@\n+// SPDX-License-Identifier: GPL-2.0-only\n+/*\n+ * Copyright (c) 2026, NVIDIA CORPORATION \u0026 AFFILIATES\n+ *\n+ * Schema-aware reply construction and operation completion.\n+ */\n+#include \u003clinux/align.h\u003e\n+#include \u003clinux/bug.h\u003e\n+#include \u003clinux/ctlv.h\u003e\n+#include \u003clinux/errno.h\u003e\n+#include \u003clinux/export.h\u003e\n+#include \u003clinux/stdarg.h\u003e\n+#include \u003clinux/string.h\u003e\n+#include \u003clinux/types.h\u003e\n+\n+#include \u003cuapi/linux/ctlv.h\u003e\n+#include \u003cuapi/linux/ctlv_gen.h\u003e\n+\n+#include \"builder.h\"\n+#include \"internal.h\"\n+#include \"message.h\"\n+#include \"schema.h\"\n+\n+static void ctlv_message_output_frag_mark(struct ctlv_op_ctx *ctx);\n+\n+void ctlv_message_output_init(struct ctlv_msg *msg, struct ctlv_op_ctx *ctx, void *buf, size_t len,\n+\t\t\t      const struct ctlv_schema_tree *tree)\n+{\n+\t*msg = (struct ctlv_msg){\n+\t\t.root = buf,\n+\t\t.len = len,\n+\t\t.tree = tree,\n+\t\t.family = ctx-\u003efamily,\n+\t\t.ctx = ctx,\n+\t};\n+\t*msg-\u003eroot = (struct ctlv_attr){\n+\t\t.len = sizeof(*msg-\u003eroot),\n+\t\t.flags = CTLV_ATTR_F_NESTED,\n+\t\t.attr_id = CTLV_ATTR_ROOT,\n+\t};\n+}\n+\n+/* The first thing that went wrong is what the op ends up failing with. */\n+static bool ctlv_message_output_poison(struct ctlv_cursor *nest, int error)\n+{\n+\tif (!nest-\u003emsg-\u003epoison)\n+\t\tnest-\u003emsg-\u003epoison = error;\n+\treturn false;\n+}\n+\n+/* A poisoned message is refused silently: whatever poisoned it has warned. */\n+static bool ctlv_message_output_ready(struct ctlv_cursor *nest)\n+{\n+\tif (WARN_ON_ONCE(!nest-\u003emsg || !nest-\u003eattr))\n+\t\treturn false;\n+\t/* Also what refuses a cursor that reads a request. */\n+\tif (WARN_ON_ONCE(!nest-\u003emsg-\u003ectx))\n+\t\treturn false;\n+\tif (nest-\u003emsg-\u003epoison)\n+\t\treturn false;\n+\tif (WARN_ON_ONCE(nest-\u003emsg-\u003ectx-\u003edeepest != nest))\n+\t\treturn ctlv_message_output_poison(nest, -EINVAL);\n+\treturn true;\n+}\n+\n+/* What the schema places in this nest under one ID, as one kind. */\n+static const struct ctlv_node_schema *ctlv_message_output_member(struct ctlv_cursor *nest,\n+\t\t\t\t\t\t\t\t u64 attr_id, u8 kind,\n+\t\t\t\t\t\t\t\t struct ctlv_schema_pos *pos)\n+{\n+\tconst struct ctlv_node_schema *node;\n+\n+\tif (!ctlv_message_output_ready(nest))\n+\t\treturn NULL;\n+\tif (WARN_ON_ONCE(!ctlv_schema_member(nest-\u003emsg-\u003efamily, nest-\u003etree,\n+\t\t\t\t\t     nest-\u003enode, attr_id, pos))) {\n+\t\tctlv_message_output_poison(nest, -EINVAL);\n+\t\treturn NULL;\n+\t}\n+\tnode = \u0026pos-\u003etree-\u003enode_schemas[pos-\u003enode];\n+\tif (WARN_ON_ONCE(node-\u003ekind != kind)) {\n+\t\tctlv_message_output_poison(nest, -EINVAL);\n+\t\treturn NULL;\n+\t}\n+\treturn node;\n+}\n+\n+/*\n+ * A query is offered whatever room its caller had, so running out ends a\n+ * fragment. Anything else wrote a message its own schema does not describe.\n+ */\n+static bool ctlv_message_output_full(struct ctlv_cursor *nest)\n+{\n+\tconst struct ctlv_op_schema *op = nest-\u003emsg-\u003ectx-\u003eop-\u003eschema;\n+\n+\tif (op-\u003etype == CTLV_OP_TYPE_QUERY)\n+\t\treturn false;\n+\tWARN_ONCE(1, \"ctlv: op %#018llx wrote past the reply length its schema declares\\n\",\n+\t\t  op-\u003eop_id);\n+\treturn ctlv_message_output_poison(nest, -EMSGSIZE);\n+}\n+\n+/* What one cursor stands on, as the buffer this direction may change. */\n+static struct ctlv_attr *ctlv_message_output_attr(const struct ctlv_cursor *nest)\n+{\n+\treturn (struct ctlv_attr *)((u8 *)nest-\u003emsg-\u003eroot + nest-\u003estart);\n+}\n+\n+/* The pad is written rather than left as it was: it belongs to the nest. */\n+static struct ctlv_attr *ctlv_message_output_write(struct ctlv_cursor *nest, u64 attr_id, u32 flags,\n+\t\t\t\t\t\t   const void *payload, u32 payload_len)\n+{\n+\tu32 len = sizeof(struct ctlv_attr) + payload_len;\n+\tsize_t step = ALIGN((size_t)len, CTLV_ALIGNTO);\n+\tstruct ctlv_msg *msg = nest-\u003emsg;\n+\tstruct ctlv_cursor *open;\n+\tstruct ctlv_attr *attr;\n+\tsize_t offset;\n+\n+\toffset = nest-\u003estart + ctlv_message_output_attr(nest)-\u003elen;\n+\tif (offset + step \u003e msg-\u003elen) {\n+\t\tctlv_message_output_full(nest);\n+\t\treturn NULL;\n+\t}\n+\n+\tattr = (struct ctlv_attr *)((u8 *)msg-\u003eroot + offset);\n+\t*attr = (struct ctlv_attr){\n+\t\t.len = len,\n+\t\t.flags = flags,\n+\t\t.attr_id = attr_id,\n+\t};\n+\tif (payload_len)\n+\t\tmemcpy(attr + 1, payload, payload_len);\n+\tmemset((u8 *)attr + len, 0, step - len);\n+\tif (!(flags \u0026 CTLV_ATTR_F_NESTED))\n+\t\tmsg-\u003ectx-\u003efrag.progress = true;\n+\n+\t/* Every nest the attr landed in is that much longer, the root too. */\n+\tfor (open = nest; open; open = open-\u003eup)\n+\t\tctlv_message_output_attr(open)-\u003elen += step;\n+\treturn attr;\n+}\n+\n+/* The 64-bit payload that every integer, enum and flags attr carries. */\n+static bool ctlv_message_put_scalar(struct ctlv_cursor *nest, u64 attr_id, u8 kind, u64 value)\n+{\n+\tconst struct ctlv_node_schema *node;\n+\tstruct ctlv_schema_pos pos;\n+\n+\tnode = ctlv_message_output_member(nest, attr_id, kind, \u0026pos);\n+\tif (!node)\n+\t\treturn false;\n+\t/* A value outside what the attr declares is one nothing may be told. */\n+\tif (WARN_ON_ONCE(!ctlv_schema_value_ok(node, value)))\n+\t\treturn ctlv_message_output_poison(nest, -EINVAL);\n+\treturn ctlv_message_output_write(nest, attr_id, 0, \u0026value, sizeof(value));\n+}\n+\n+bool ctlv_put_u64(struct ctlv_cursor *nest, u64 attr_id, u8 kind, u64 value)\n+{\n+\treturn ctlv_message_put_scalar(nest, attr_id, kind, value);\n+}\n+EXPORT_SYMBOL_NS_GPL(ctlv_put_u64, \"CTLV\");\n+\n+bool ctlv_put_s64(struct ctlv_cursor *nest, u64 attr_id, u8 kind, s64 value)\n+{\n+\treturn ctlv_message_put_scalar(nest, attr_id, kind, value);\n+}\n+EXPORT_SYMBOL_NS_GPL(ctlv_put_s64, \"CTLV\");\n+\n+bool ctlv_put_bool(struct ctlv_cursor *nest, u64 attr_id, u8 kind, bool value)\n+{\n+\tu8 payload = value;\n+\tstruct ctlv_schema_pos pos;\n+\n+\tif (!ctlv_message_output_member(nest, attr_id, kind, \u0026pos))\n+\t\treturn false;\n+\treturn ctlv_message_output_write(nest, attr_id, 0, \u0026payload, sizeof(payload));\n+}\n+EXPORT_SYMBOL_NS_GPL(ctlv_put_bool, \"CTLV\");\n+\n+bool ctlv_put_string(struct ctlv_cursor *nest, u64 attr_id, u8 kind, const char *value)\n+{\n+\tconst struct ctlv_node_schema *node;\n+\tstruct ctlv_schema_pos pos;\n+\tsize_t len;\n+\n+\tnode = ctlv_message_output_member(nest, attr_id, kind, \u0026pos);\n+\tif (!node)\n+\t\treturn false;\n+\tlen = strnlen(value, (size_t)node-\u003elength.max_len + 1);\n+\tif (WARN_ON_ONCE(len \u003e node-\u003elength.max_len || !ctlv_schema_length_ok(node, len)))\n+\t\treturn ctlv_message_output_poison(nest, -EINVAL);\n+\treturn ctlv_message_output_write(nest, attr_id, 0, value, len + 1);\n+}\n+EXPORT_SYMBOL_NS_GPL(ctlv_put_string, \"CTLV\");\n+\n+bool ctlv_put_binary(struct ctlv_cursor *nest, u64 attr_id, u8 kind, const void *value, u32 len)\n+{\n+\tconst struct ctlv_node_schema *node;\n+\tstruct ctlv_schema_pos pos;\n+\n+\tnode = ctlv_message_output_member(nest, attr_id, kind, \u0026pos);\n+\tif (!node)\n+\t\treturn false;\n+\tif (WARN_ON_ONCE(!ctlv_schema_length_ok(node, len)))\n+\t\treturn ctlv_message_output_poison(nest, -EINVAL);\n+\treturn ctlv_message_output_write(nest, attr_id, 0, value, len);\n+}\n+EXPORT_SYMBOL_NS_GPL(ctlv_put_binary, \"CTLV\");\n+\n+bool ctlv_nest_start(struct ctlv_cursor *nest, struct ctlv_cursor *child, u64 attr_id, u8 kind)\n+{\n+\tstruct ctlv_schema_pos pos;\n+\tstruct ctlv_attr *attr;\n+\n+\t*child = (struct ctlv_cursor){};\n+\tif (!ctlv_message_output_member(nest, attr_id, kind, \u0026pos))\n+\t\treturn false;\n+\t/* Unreachable through any schema the generator would have accepted. */\n+\tif (WARN_ON_ONCE(nest-\u003edepth + 1 \u003e CTLV_MAX_NEST_DEPTH))\n+\t\treturn ctlv_message_output_poison(nest, -EINVAL);\n+\n+\tattr = ctlv_message_output_write(nest, attr_id, CTLV_ATTR_F_NESTED, NULL, 0);\n+\tif (!attr)\n+\t\treturn false;\n+\n+\t*child = (struct ctlv_cursor){\n+\t\t.msg = nest-\u003emsg,\n+\t\t.attr = attr,\n+\t\t.up = nest,\n+\t\t.start = ctlv_message_offset(nest-\u003emsg, attr),\n+\t\t.tree = pos.tree,\n+\t\t.node = pos.node,\n+\t\t.depth = nest-\u003edepth + 1,\n+\t};\n+\tnest-\u003emsg-\u003ectx-\u003edeepest = child;\n+\treturn true;\n+}\n+EXPORT_SYMBOL_NS_GPL(ctlv_nest_start, \"CTLV\");\n+\n+void ctlv_nest_end(struct ctlv_cursor *child)\n+{\n+\tstruct ctlv_op_ctx *ctx;\n+\n+\tif (WARN_ON_ONCE(!child-\u003emsg || !child-\u003emsg-\u003ectx || !child-\u003eup))\n+\t\treturn;\n+\tctx = child-\u003emsg-\u003ectx;\n+\tif (child-\u003emsg-\u003epoison)\n+\t\treturn;\n+\tif (WARN_ON_ONCE(ctx-\u003edeepest != child)) {\n+\t\tctlv_message_output_poison(child, -EINVAL);\n+\t\treturn;\n+\t}\n+\tif (ctlv_message_output_attr(child)-\u003elen == sizeof(struct ctlv_attr))\n+\t\tctx-\u003efrag.progress = true;\n+\tctx-\u003edeepest = child-\u003eup;\n+}\n+EXPORT_SYMBOL_NS_GPL(ctlv_nest_end, \"CTLV\");\n+\n+static bool ctlv_op_error_valid(int error)\n+{\n+\treturn !WARN_ON_ONCE(error \u003e= 0 || error \u003c -MAX_ERRNO);\n+}\n+\n+int ctlv_op_error(struct ctlv_op_ctx *ctx, int error, const char *message)\n+{\n+\tif (!ctlv_op_error_valid(error))\n+\t\treturn error \u003c 0 \u0026\u0026 error \u003e= -MAX_ERRNO ? error : -EINVAL;\n+\tif (!ctx-\u003eerror.message[0])\n+\t\tstrscpy(ctx-\u003eerror.message, message, sizeof(ctx-\u003eerror.message));\n+\treturn error;\n+}\n+EXPORT_SYMBOL_NS_GPL(ctlv_op_error, \"CTLV\");\n+\n+int ctlv_op_errorf(struct ctlv_op_ctx *ctx, int error, const char *fmt, ...)\n+{\n+\tva_list args;\n+\n+\tif (!ctlv_op_error_valid(error))\n+\t\treturn error \u003c 0 \u0026\u0026 error \u003e= -MAX_ERRNO ? error : -EINVAL;\n+\tif (ctx-\u003eerror.message[0])\n+\t\treturn error;\n+\tva_start(args, fmt);\n+\tvscnprintf(ctx-\u003eerror.message, sizeof(ctx-\u003eerror.message), fmt, args);\n+\tva_end(args);\n+\treturn error;\n+}\n+EXPORT_SYMBOL_NS_GPL(ctlv_op_errorf, \"CTLV\");\n+\n+/* Continuation is a query's, so asking about one anywhere else is a bug. */\n+static bool ctlv_op_is_query(const struct ctlv_op_ctx *ctx)\n+{\n+\treturn !WARN_ON_ONCE(ctx-\u003eop-\u003eschema-\u003etype != CTLV_OP_TYPE_QUERY);\n+}\n+\n+u64 ctlv_op_query_generation(const struct ctlv_op_ctx *ctx)\n+{\n+\tif (!ctlv_op_is_query(ctx))\n+\t\treturn 0;\n+\treturn ctx-\u003efrag.generation;\n+}\n+EXPORT_SYMBOL_NS_GPL(ctlv_op_query_generation, \"CTLV\");\n+\n+u64 ctlv_op_query_cursor(const struct ctlv_op_ctx *ctx)\n+{\n+\tif (!ctlv_op_is_query(ctx))\n+\t\treturn 0;\n+\treturn ctx-\u003efrag.cursor;\n+}\n+EXPORT_SYMBOL_NS_GPL(ctlv_op_query_cursor, \"CTLV\");\n+\n+/*\n+ * What both endings check: a query, one ending, and a generation that has not\n+ * moved under a continuation, which no fragment can be delivered across.\n+ */\n+static int ctlv_query_fragment_end(struct ctlv_op_ctx *ctx, u64 generation)\n+{\n+\tif (!ctlv_op_is_query(ctx))\n+\t\treturn -EINVAL;\n+\tif (WARN_ON_ONCE(ctx-\u003efrag.answered))\n+\t\treturn -EINVAL;\n+\tctx-\u003efrag.answered = true;\n+\t/* Whatever the builder gave up on has warned about it already. */\n+\tif (ctx-\u003eoutput.poison)\n+\t\treturn ctx-\u003eoutput.poison;\n+\tif (ctx-\u003efrag.cursor \u0026\u0026 generation != ctx-\u003efrag.generation) {\n+\t\tctx-\u003eerror.reason = CTLV_VALIDATION_REASON_STALE_GENERATION;\n+\t\tctx-\u003eerror.expected_generation = ctx-\u003efrag.generation;\n+\t\tctx-\u003eerror.current_generation = generation;\n+\t\treturn -ESTALE;\n+\t}\n+\tctx-\u003efrag.reported = generation;\n+\treturn 0;\n+}\n+\n+int ctlv_op_query_more(struct ctlv_op_ctx *ctx, u64 generation, u64 next_cursor)\n+{\n+\tint ret = ctlv_query_fragment_end(ctx, generation);\n+\n+\tif (!ret \u0026\u0026\n+\t    WARN_ON_ONCE(!ctx-\u003efrag.progress || !next_cursor || next_cursor == ctx-\u003efrag.cursor))\n+\t\tret = -EINVAL;\n+\tif (!ret) {\n+\t\tctlv_message_output_frag_mark(ctx);\n+\t\tctx-\u003efrag.next_cursor = next_cursor;\n+\t}\n+\tctx-\u003efrag.result = ret;\n+\treturn ret;\n+}\n+EXPORT_SYMBOL_NS_GPL(ctlv_op_query_more, \"CTLV\");\n+\n+int ctlv_op_query_done(struct ctlv_op_ctx *ctx, u64 generation)\n+{\n+\tint ret = ctlv_query_fragment_end(ctx, generation);\n+\n+\tif (!ret \u0026\u0026 WARN_ON_ONCE(ctx-\u003edeepest != \u0026ctx-\u003eoutput_root)) {\n+\t\t/* A cursor of a frame that has returned is not followed. */\n+\t\tctx-\u003edeepest = \u0026ctx-\u003eoutput_root;\n+\t\tret = -EINVAL;\n+\t}\n+\tctx-\u003efrag.result = ret;\n+\treturn ret;\n+}\n+EXPORT_SYMBOL_NS_GPL(ctlv_op_query_done, \"CTLV\");\n+\n+static void ctlv_message_output_frag_mark(struct ctlv_op_ctx *ctx)\n+{\n+\tstruct ctlv_cursor *open;\n+\n+\tfor (open = ctx-\u003edeepest; open; open = open-\u003eup)\n+\t\tctlv_message_output_attr(open)-\u003eflags |= CTLV_ATTR_F_FRAG_MORE;\n+\tctx-\u003edeepest = \u0026ctx-\u003eoutput_root;\n+}\ndiff --git a/drivers/ctlv/builder.h b/drivers/ctlv/builder.h\nnew file mode 100644\nindex 0000000000000..744595ebd88e9\n--- /dev/null\n+++ b/drivers/ctlv/builder.h\n@@ -0,0 +1,14 @@\n+/* SPDX-License-Identifier: GPL-2.0-only */\n+#ifndef _CTLV_BUILDER_H\n+#define _CTLV_BUILDER_H\n+\n+#include \u003clinux/types.h\u003e\n+\n+struct ctlv_msg;\n+struct ctlv_op_ctx;\n+struct ctlv_schema_tree;\n+\n+void ctlv_message_output_init(struct ctlv_msg *msg, struct ctlv_op_ctx *ctx, void *buf, size_t len,\n+\t\t\t      const struct ctlv_schema_tree *tree);\n+\n+#endif /* _CTLV_BUILDER_H */\ndiff --git a/drivers/ctlv/core.c b/drivers/ctlv/core.c\nnew file mode 100644\nindex 0000000000000..aeab29fe2fdd4\n--- /dev/null\n+++ b/drivers/ctlv/core.c\n@@ -0,0 +1,1517 @@\n+// SPDX-License-Identifier: GPL-2.0-only\n+/*\n+ * Copyright (c) 2026, NVIDIA CORPORATION \u0026 AFFILIATES\n+ */\n+#define pr_fmt(fmt) \"ctlv: \" fmt\n+#include \u003clinux/align.h\u003e\n+#include \u003clinux/bitmap.h\u003e\n+#include \u003clinux/bitops.h\u003e\n+#include \u003clinux/build_bug.h\u003e\n+#include \u003clinux/cache.h\u003e\n+#include \u003clinux/cleanup.h\u003e\n+#include \u003clinux/container_of.h\u003e\n+#include \u003clinux/ctlv.h\u003e\n+#include \u003clinux/ctlv_gen.h\u003e\n+#include \u003clinux/device.h\u003e\n+#include \u003clinux/err.h\u003e\n+#include \u003clinux/fs.h\u003e\n+#include \u003clinux/idr.h\u003e\n+#include \u003clinux/kdev_t.h\u003e\n+#include \u003clinux/kobject.h\u003e\n+#include \u003clinux/list.h\u003e\n+#include \u003clinux/lockdep.h\u003e\n+#include \u003clinux/module.h\u003e\n+#include \u003clinux/mutex.h\u003e\n+#include \u003clinux/overflow.h\u003e\n+#include \u003clinux/poll.h\u003e\n+#include \u003clinux/slab.h\u003e\n+#include \u003clinux/stddef.h\u003e\n+#include \u003clinux/string.h\u003e\n+#include \u003clinux/uaccess.h\u003e\n+#include \u003clinux/vmalloc.h\u003e\n+\n+#include \u003cuapi/linux/ctlv.h\u003e\n+\n+#include \"blob.h\"\n+#include \"builder.h\"\n+#include \"device.h\"\n+#include \"event.h\"\n+#include \"internal.h\"\n+#include \"schema.h\"\n+\n+enum {\n+\tCTLV_MAX_DEVICES = 4096,\n+};\n+\n+/*\n+ * One layout on every ABI, including compat. Alignment is asserted too because\n+ * a 32-bit ABI aligns a plain __u64 to four bytes.\n+ */\n+static_assert(sizeof(struct ctlv_attr) == 16);\n+static_assert(__alignof__(struct ctlv_attr) == CTLV_ALIGNTO);\n+\n+static_assert(sizeof(struct ctlv_op_exec) == 64);\n+static_assert(__alignof__(struct ctlv_op_exec) == CTLV_ALIGNTO);\n+\n+static_assert(sizeof(struct ctlv_event_hdr) == 24);\n+static_assert(__alignof__(struct ctlv_event_hdr) == CTLV_ALIGNTO);\n+\n+static dev_t ctlv_device_number;\n+static DEFINE_IDA(ctlv_device_ids);\n+\n+/* Every family priv has core-owned links immediately before it. */\n+#define CTLV_PRIV_ALIGN SMP_CACHE_BYTES\n+\n+struct ctlv_priv_container {\n+\tstruct ctlv_priv_container *parent;\n+\tstruct ctlv_priv_container *child;\n+\tu8 priv[] __aligned(CTLV_PRIV_ALIGN);\n+};\n+\n+static inline const struct ctlv_priv_container *ctlv_priv_container(const void *priv)\n+{\n+\treturn container_of_const(priv, struct ctlv_priv_container, priv);\n+}\n+\n+struct ctlv_family_priv {\n+\tconst struct ctlv_family *family;\n+\tvoid *priv;\n+\tsize_t priv_offset;\n+\tconst void *init_info;\n+\tbool initialized;\n+};\n+\n+/* Claims persist across unload so one ID cannot later name another family. */\n+struct ctlv_family_claim {\n+\tstruct list_head entry;\n+\tchar *name;\n+\tu16 family_id;\n+};\n+\n+static LIST_HEAD(ctlv_family_claims);\n+static DEFINE_MUTEX(ctlv_family_claims_lock);\n+\n+static int ctlv_family_claim_add(const struct ctlv_family_schema *schema)\n+{\n+\tstruct ctlv_family_claim *claim;\n+\n+\tguard(mutex)\n+\t\t(\u0026ctlv_family_claims_lock);\n+\tlist_for_each_entry(claim, \u0026ctlv_family_claims, entry) {\n+\t\tbool same_id = claim-\u003efamily_id == schema-\u003efamily_id;\n+\t\tbool same_name = !strcmp(claim-\u003ename, schema-\u003ename);\n+\n+\t\tif (same_id \u0026\u0026 same_name)\n+\t\t\treturn 0;\n+\t\tif (same_id || same_name) {\n+\t\t\tpr_err(\"family %s wants ID %u, which belongs to %s\\n\", schema-\u003ename,\n+\t\t\t       schema-\u003efamily_id, claim-\u003ename);\n+\t\t\treturn -EEXIST;\n+\t\t}\n+\t}\n+\n+\tclaim = kzalloc_obj(*claim, GFP_KERNEL);\n+\tif (!claim)\n+\t\treturn -ENOMEM;\n+\tclaim-\u003ename = kstrdup(schema-\u003ename, GFP_KERNEL);\n+\tif (!claim-\u003ename) {\n+\t\tkfree(claim);\n+\t\treturn -ENOMEM;\n+\t}\n+\tclaim-\u003efamily_id = schema-\u003efamily_id;\n+\tlist_add_tail(\u0026claim-\u003eentry, \u0026ctlv_family_claims);\n+\treturn 0;\n+}\n+\n+static void ctlv_family_claims_free(void)\n+{\n+\tstruct ctlv_family_claim *claim, *next;\n+\n+\tlist_for_each_entry_safe(claim, next, \u0026ctlv_family_claims, entry) {\n+\t\tlist_del(\u0026claim-\u003eentry);\n+\t\tkfree(claim-\u003ename);\n+\t\tkfree(claim);\n+\t}\n+}\n+\n+/*\n+ * Everything resolved below is generated, so a failure here is a bug, checked\n+ * anyway because an out-of-tree family comes from another generator.\n+ */\n+\n+static const char *ctlv_family_name(const struct ctlv_family *family)\n+{\n+\tif (!family-\u003eschema || !family-\u003eschema-\u003ename)\n+\t\treturn \"(unnamed)\";\n+\treturn family-\u003eschema-\u003ename;\n+}\n+\n+static int ctlv_family_bad(const struct ctlv_family *family, const char *what)\n+{\n+\tpr_err(\"family %s: %s\\n\", ctlv_family_name(family), what);\n+\treturn -EINVAL;\n+}\n+\n+static int ctlv_op_bad(const struct ctlv_family *family, u64 op_id, const char *what)\n+{\n+\tpr_err(\"family %s: op %#018llx %s\\n\", ctlv_family_name(family), op_id, what);\n+\treturn -EINVAL;\n+}\n+\n+/*\n+ * A family is named its parent's whole name plus a suffix, so one name states\n+ * the chain it belongs to and every family of this core is ctlv-something.\n+ */\n+static int ctlv_family_chain_check(const struct ctlv_family *family)\n+{\n+\tconst struct ctlv_family *child;\n+\n+\tfor (child = family; child != \u0026ctlv_family; child = child-\u003eparent) {\n+\t\tconst struct ctlv_family *parent;\n+\t\tsize_t len;\n+\n+\t\tif (!child)\n+\t\t\treturn ctlv_family_bad(family, \"heads no chain of the core's\");\n+\t\tparent = child-\u003eparent;\n+\t\tif (!child-\u003eschema || !parent || !parent-\u003eschema)\n+\t\t\treturn ctlv_family_bad(child, \"does not name a complete parent descriptor\");\n+\t\tif (!child-\u003eschema-\u003ename || !parent-\u003eschema-\u003ename)\n+\t\t\treturn ctlv_family_bad(family, \"inherits a family with no name\");\n+\t\tif (parent-\u003eschema-\u003efamily_id \u003e= child-\u003eschema-\u003efamily_id)\n+\t\t\treturn ctlv_family_bad(child, \"does not follow its parent in the registry\");\n+\t\tlen = strlen(parent-\u003eschema-\u003ename);\n+\t\tif (!len || strncmp(child-\u003eschema-\u003ename, parent-\u003eschema-\u003ename, len) ||\n+\t\t    child-\u003eschema-\u003ename[len] != '-')\n+\t\t\treturn ctlv_family_bad(family, \"is not named after the family it inherits\");\n+\t}\n+\treturn 0;\n+}\n+\n+/* One descriptor of a chain: what it answers with, and what it fills. */\n+static int ctlv_family_descriptor_check(const struct ctlv_family *family)\n+{\n+\tconst struct ctlv_family_schema *schema = family-\u003eschema;\n+\tu32 index;\n+\n+\t/*\n+\t * A family that declares no op of its own binds nothing: what it\n+\t * inherited is answered where it was declared.\n+\t */\n+\tif (!schema || !schema-\u003ename || !*schema-\u003ename || (family-\u003eops_count \u0026\u0026 !family-\u003eops))\n+\t\treturn ctlv_family_bad(family, \"descriptor is incomplete\");\n+\t/* Nothing in common means an empty pair, not an absent one. */\n+\tif (!family-\u003epre || !family-\u003epost)\n+\t\treturn ctlv_family_bad(family, \"has no hook pair\");\n+\tif (!family-\u003epriv_size || !family-\u003einit || !family-\u003efini)\n+\t\treturn ctlv_family_bad(family, \"has no priv lifecycle\");\n+\t/* Every device answers the root family already, as the core. */\n+\tif (schema-\u003efamily_id == CTLV_FAMILY_ROOT \u0026\u0026 family != \u0026ctlv_family)\n+\t\treturn ctlv_family_bad(family, \"claims the root family ID\");\n+\t/* An extension point is answered by whichever family filled it. */\n+\tif (family-\u003estub_ops_count != schema-\u003estub_fill_schemas_count)\n+\t\treturn ctlv_family_bad(family, \"answers other extension points than it fills\");\n+\tfor (index = 0; index \u003c family-\u003estub_ops_count; index++) {\n+\t\tconst struct ctlv_stub_fill_schema *fill_schema = \u0026schema-\u003estub_fill_schemas[index];\n+\t\tconst struct ctlv_stub_ops *stub_ops = \u0026family-\u003estub_ops[index];\n+\n+\t\tif (stub_ops-\u003efamily_id == fill_schema-\u003efamily_id \u0026\u0026\n+\t\t    stub_ops-\u003eset_id == fill_schema-\u003eset_id)\n+\t\t\tcontinue;\n+\t\treturn ctlv_family_bad(family, \"answers an extension point it does not fill\");\n+\t}\n+\treturn 0;\n+}\n+\n+/* Every descriptor binds its local schema and supplies a complete lifecycle. */\n+static int ctlv_family_descriptors_check(const struct ctlv_family *family)\n+{\n+\tconst struct ctlv_family *descriptor;\n+\n+\tfor (descriptor = family; descriptor; descriptor = descriptor-\u003eparent) {\n+\t\tint ret;\n+\n+\t\tret = ctlv_family_descriptor_check(descriptor);\n+\t\tif (ret)\n+\t\t\treturn ret;\n+\t}\n+\treturn 0;\n+}\n+\n+/* The graph a device answers over, and the descriptors standing on it. */\n+static int ctlv_family_check(const struct ctlv_family *family)\n+{\n+\tint ret;\n+\n+\tif (!family-\u003eschema)\n+\t\treturn ctlv_family_bad(family, \"descriptor is incomplete\");\n+\tret = ctlv_family_chain_check(family);\n+\tif (ret)\n+\t\treturn ret;\n+\treturn ctlv_family_descriptors_check(family);\n+}\n+\n+static struct ctlv_family_priv *ctlv_family_priv_find(const struct ctlv_device *ctlvdev,\n+\t\t\t\t\t\t      const struct ctlv_family *family)\n+{\n+\tu32 index;\n+\n+\tfor (index = 0; index \u003c ctlvdev-\u003eprivs_count; index++)\n+\t\tif (ctlvdev-\u003eprivs[index].family == family)\n+\t\t\treturn \u0026ctlvdev-\u003eprivs[index];\n+\treturn NULL;\n+}\n+\n+static void ctlv_family_privs_free(struct ctlv_device *ctlvdev)\n+{\n+\tkvfree(ctlvdev-\u003epriv_block);\n+\tctlvdev-\u003epriv_block = NULL;\n+\tkfree(ctlvdev-\u003eprivs);\n+\tctlvdev-\u003eprivs = NULL;\n+\tctlvdev-\u003eprivs_count = 0;\n+}\n+\n+static int ctlv_family_privs_alloc(struct ctlv_device *ctlvdev, const struct ctlv_family *family)\n+{\n+\tstruct ctlv_priv_container *parent = NULL;\n+\tvoid *aligned;\n+\tsize_t alloc_len;\n+\tsize_t len = 0;\n+\tu32 index;\n+\n+\tctlvdev-\u003eprivs_count = ctlv_family_levels(family);\n+\tctlvdev-\u003eprivs = kcalloc(ctlvdev-\u003eprivs_count, sizeof(*ctlvdev-\u003eprivs), GFP_KERNEL);\n+\tif (!ctlvdev-\u003eprivs)\n+\t\treturn -ENOMEM;\n+\n+\tfor (index = 0; index \u003c ctlvdev-\u003eprivs_count; index++) {\n+\t\tstruct ctlv_family_priv *family_priv = \u0026ctlvdev-\u003eprivs[index];\n+\t\tsize_t size, aligned_len;\n+\n+\t\tfamily_priv-\u003efamily =\n+\t\t\tctlv_family_ancestor(family, ctlvdev-\u003eprivs_count - index - 1);\n+\t\tsize = max_t(size_t, family_priv-\u003efamily-\u003epriv_size(), 1);\n+\t\tif (check_add_overflow(len, offsetof(struct ctlv_priv_container, priv),\n+\t\t\t\t       \u0026aligned_len) ||\n+\t\t    check_add_overflow(aligned_len, CTLV_PRIV_ALIGN - 1, \u0026aligned_len))\n+\t\t\tgoto overflow;\n+\t\taligned_len = ALIGN_DOWN(aligned_len, CTLV_PRIV_ALIGN);\n+\t\tfamily_priv-\u003epriv_offset = aligned_len;\n+\t\tif (check_add_overflow(aligned_len, size, \u0026len))\n+\t\t\tgoto overflow;\n+\t}\n+\tif (check_add_overflow(len, CTLV_PRIV_ALIGN - 1, \u0026alloc_len))\n+\t\tgoto overflow;\n+\tctlvdev-\u003epriv_block = kvzalloc(alloc_len, GFP_KERNEL);\n+\tif (!ctlvdev-\u003epriv_block) {\n+\t\tctlv_family_privs_free(ctlvdev);\n+\t\treturn -ENOMEM;\n+\t}\n+\taligned = PTR_ALIGN(ctlvdev-\u003epriv_block, CTLV_PRIV_ALIGN);\n+\n+\tfor (index = 0; index \u003c ctlvdev-\u003eprivs_count; index++) {\n+\t\tstruct ctlv_family_priv *family_priv = \u0026ctlvdev-\u003eprivs[index];\n+\t\tstruct ctlv_priv_container *container;\n+\t\tvoid *priv;\n+\n+\t\tpriv = (u8 *)aligned + family_priv-\u003epriv_offset;\n+\t\tfamily_priv-\u003epriv = priv;\n+\t\tcontainer = container_of_const(priv, struct ctlv_priv_container, priv);\n+\t\tcontainer-\u003eparent = parent;\n+\t\tcontainer-\u003echild = NULL;\n+\t\tif (parent)\n+\t\t\tparent-\u003echild = container;\n+\t\tparent = container;\n+\t}\n+\treturn 0;\n+\n+overflow:\n+\tctlv_family_privs_free(ctlvdev);\n+\treturn -EOVERFLOW;\n+}\n+\n+static int ctlv_family_privs_pre_init(struct ctlv_device *ctlvdev, const void *init_info)\n+{\n+\tu32 index;\n+\n+\tfor (index = ctlvdev-\u003eprivs_count; index; index--) {\n+\t\tstruct ctlv_family_priv *family_priv = \u0026ctlvdev-\u003eprivs[index - 1];\n+\n+\t\tfamily_priv-\u003einit_info = init_info;\n+\t\tif (!family_priv-\u003efamily-\u003epre_init) {\n+\t\t\tinit_info = NULL;\n+\t\t\tcontinue;\n+\t\t}\n+\t\tinit_info = family_priv-\u003efamily-\u003epre_init(init_info);\n+\t\tif (IS_ERR(init_info))\n+\t\t\treturn PTR_ERR(init_info);\n+\t}\n+\tif (WARN_ON_ONCE(init_info))\n+\t\treturn -EINVAL;\n+\treturn 0;\n+}\n+\n+static void ctlv_family_privs_pre_fini(struct ctlv_device *ctlvdev)\n+{\n+\tu32 index;\n+\n+\tlockdep_assert_not_held(\u0026ctlvdev-\u003eregistration_lock);\n+\tlockdep_assert_not_held(\u0026ctlvdev-\u003etransition_lock);\n+\tlockdep_assert_not_held(\u0026ctlvdev-\u003eevents_lock);\n+\n+\tfor (index = 0; index \u003c ctlvdev-\u003eprivs_count; index++) {\n+\t\tstruct ctlv_family_priv *family_priv = \u0026ctlvdev-\u003eprivs[index];\n+\n+\t\tif (!family_priv-\u003einitialized || !family_priv-\u003efamily-\u003epre_fini)\n+\t\t\tcontinue;\n+\t\tfamily_priv-\u003efamily-\u003epre_fini(ctlvdev, family_priv-\u003epriv);\n+\t}\n+}\n+\n+static void ctlv_family_privs_fini_only(struct ctlv_device *ctlvdev)\n+{\n+\tu32 index;\n+\n+\tfor (index = ctlvdev-\u003eprivs_count; index; index--) {\n+\t\tstruct ctlv_family_priv *family_priv = \u0026ctlvdev-\u003eprivs[index - 1];\n+\n+\t\tif (!family_priv-\u003einitialized)\n+\t\t\tcontinue;\n+\t\tfamily_priv-\u003efamily-\u003efini(ctlvdev, family_priv-\u003epriv);\n+\t\tfamily_priv-\u003einitialized = false;\n+\t}\n+}\n+\n+static int ctlv_family_privs_init(struct ctlv_device *ctlvdev)\n+{\n+\tu32 index;\n+\tint ret;\n+\n+\tfor (index = 0; index \u003c ctlvdev-\u003eprivs_count; index++) {\n+\t\tstruct ctlv_family_priv *family_priv = \u0026ctlvdev-\u003eprivs[index];\n+\n+\t\tret = family_priv-\u003efamily-\u003einit(ctlvdev, family_priv-\u003einit_info, family_priv-\u003epriv);\n+\t\tfamily_priv-\u003einit_info = NULL;\n+\t\tif (ret) {\n+\t\t\tctlv_family_privs_fini_only(ctlvdev);\n+\t\t\treturn ret;\n+\t\t}\n+\t\tfamily_priv-\u003einitialized = true;\n+\t}\n+\treturn 0;\n+}\n+\n+static int ctlv_family_privs_post_init(struct ctlv_device *ctlvdev)\n+{\n+\tu32 index;\n+\tint ret;\n+\n+\tfor (index = ctlvdev-\u003eprivs_count; index; index--) {\n+\t\tstruct ctlv_family_priv *family_priv = \u0026ctlvdev-\u003eprivs[index - 1];\n+\n+\t\tif (!family_priv-\u003efamily-\u003epost_init)\n+\t\t\tcontinue;\n+\t\tret = family_priv-\u003efamily-\u003epost_init(ctlvdev, family_priv-\u003epriv);\n+\t\tif (ret)\n+\t\t\treturn ret;\n+\t}\n+\treturn 0;\n+}\n+\n+static void ctlv_device_fini(struct ctlv_device *ctlvdev)\n+{\n+\tctlv_family_privs_pre_fini(ctlvdev);\n+\n+\t/* No provider can remain after pre_fini has drained its consumers. */\n+\tscoped_guard(spinlock, \u0026ctlvdev-\u003etransition_lock) {\n+\t\tctlvdev-\u003edestroying = true;\n+\t\tctlv_event_contexts_stop(ctlvdev);\n+\t}\n+\tctlv_event_contexts_wait(ctlvdev);\n+\tctlv_event_device_dead(ctlvdev);\n+\n+\tctlv_family_privs_fini_only(ctlvdev);\n+}\n+\n+/* What one walk of the chain has accounted for so far. */\n+struct ctlv_op_resolution {\n+\tstruct ctlv_device *ctlvdev;\n+\tconst struct ctlv_family *target;\n+\tconst struct ctlv_family *family;\n+\tu32 bound;\n+\tu32 dynamic;\n+\tu32 events;\n+\tu64 previous;\n+};\n+\n+/* Every binding of one family answers an op, so a spare one answers nothing. */\n+static int ctlv_op_resolution_family_bound(const struct ctlv_op_resolution *state)\n+{\n+\tconst struct ctlv_family *family = state-\u003efamily;\n+\n+\tif (!family || state-\u003ebound == family-\u003eops_count)\n+\t\treturn 0;\n+\t/* The core's own table is this core's bug, not a family's. */\n+\tif (WARN_ON_ONCE(family == \u0026ctlv_family))\n+\t\treturn -EINVAL;\n+\treturn ctlv_family_bad(family, \"binds more than its schema asks for\");\n+}\n+\n+/*\n+ * The ops of one family are contiguous in the walk, so the family before this\n+ * one is complete as soon as another family's op arrives.\n+ */\n+static int ctlv_op_resolution_family_enter(struct ctlv_op_resolution *state,\n+\t\t\t\t\t   const struct ctlv_family *family)\n+{\n+\tint ret;\n+\n+\tif (state-\u003efamily == family)\n+\t\treturn 0;\n+\tret = ctlv_op_resolution_family_bound(state);\n+\tif (ret)\n+\t\treturn ret;\n+\tstate-\u003efamily = family;\n+\tstate-\u003ebound = 0;\n+\treturn 0;\n+}\n+\n+static int ctlv_op_resolution_add(struct ctlv_op_resolution *state, const struct ctlv_family *owner,\n+\t\t\t\t  const struct ctlv_op_schema *op, struct ctlv_op_entry *entry)\n+{\n+\tconst struct ctlv_family *target = state-\u003etarget;\n+\tconst struct ctlv_family *family = state-\u003efamily;\n+\tstruct ctlv_family_priv *family_priv;\n+\tint ret;\n+\n+\tfamily_priv = ctlv_family_priv_find(state-\u003ectlvdev, family);\n+\tif (WARN_ON_ONCE(!family_priv))\n+\t\treturn -EINVAL;\n+\tentry-\u003eschema = op;\n+\tentry-\u003epriv = family_priv-\u003epriv;\n+\tentry-\u003estate_index = CTLV_OP_STATE_NONE;\n+\n+\t/*\n+\t * An op ID is its family's ID and a number within it, so a walk from\n+\t * the oldest ancestor down ascends, which covers uniqueness too.\n+\t */\n+\tif (!CTLV_OP_NUMBER(op-\u003eop_id) || CTLV_OP_FAMILY(op-\u003eop_id) != owner-\u003eschema-\u003efamily_id)\n+\t\treturn ctlv_op_bad(target, op-\u003eop_id, \"belongs to another family\");\n+\tif (op-\u003eop_id \u003c= state-\u003eprevious)\n+\t\treturn ctlv_op_bad(target, op-\u003eop_id, \"is out of order\");\n+\tstate-\u003eprevious = op-\u003eop_id;\n+\n+\tswitch (op-\u003etype) {\n+\tcase CTLV_OP_TYPE_ACTION:\n+\tcase CTLV_OP_TYPE_QUERY:\n+\t\tif (op-\u003efd_access != CTLV_OP_FD_ACCESS_READ \u0026\u0026\n+\t\t    op-\u003efd_access != CTLV_OP_FD_ACCESS_READ_WRITE)\n+\t\t\treturn ctlv_op_bad(family, op-\u003eop_id, \"has an unknown fd access\");\n+\t\t/* The family that declared the op is the one that answers it. */\n+\t\tif (state-\u003ebound \u003e= family-\u003eops_count)\n+\t\t\treturn ctlv_op_bad(family, op-\u003eop_id, \"has nothing bound to it\");\n+\t\tentry-\u003ebinding = \u0026family-\u003eops[state-\u003ebound++];\n+\t\t/* Required even for an op this device disables or withholds. */\n+\t\tif (!entry-\u003ebinding-\u003eaction)\n+\t\t\treturn ctlv_op_bad(family, op-\u003eop_id, \"has no callback\");\n+\t\t/* An optional op arrives absent, for the opt-in to clear. */\n+\t\tentry-\u003eabsent = op-\u003eoptional;\n+\t\t/* An op has a whole pair of hooks of its own, or none. */\n+\t\tif (!entry-\u003ebinding-\u003epre != !entry-\u003ebinding-\u003epost)\n+\t\t\treturn ctlv_op_bad(family, op-\u003eop_id, \"has half a hook pair\");\n+\t\t/* A pair is on no wire, so this is the only check of it. */\n+\t\tif (!entry-\u003ebinding-\u003epre != !op-\u003epre_post)\n+\t\t\treturn ctlv_op_bad(family, op-\u003eop_id, \"disagrees about its hook pair\");\n+\t\tbreak;\n+\tcase CTLV_OP_TYPE_EVENT:\n+\t\tif (op-\u003efd_access)\n+\t\t\treturn ctlv_op_bad(target, op-\u003eop_id, \"is an event with fd access\");\n+\t\tif (op-\u003eoptional)\n+\t\t\treturn ctlv_op_bad(target, op-\u003eop_id, \"is an event a device could omit\");\n+\t\t/*\n+\t\t * Produced rather than answered, so nothing to bind: an event\n+\t\t * gets a subscription bit, numbered as the walk meets it.\n+\t\t */\n+\t\tentry-\u003eevent_index = state-\u003eevents++;\n+\t\tbreak;\n+\tdefault:\n+\t\treturn ctlv_op_bad(target, op-\u003eop_id, \"has an unknown type\");\n+\t}\n+\n+\tswitch (op-\u003eavailability) {\n+\tcase CTLV_OP_AVAILABILITY_FIXED:\n+\t\tbreak;\n+\tcase CTLV_OP_AVAILABILITY_DYNAMIC:\n+\t\tif (op-\u003etype == CTLV_OP_TYPE_EVENT)\n+\t\t\treturn ctlv_op_bad(target, op-\u003eop_id, \"is an event a device could disable\");\n+\t\t/*\n+\t\t * Numbered from zero as the walk meets them, per device: two\n+\t\t * families of one chain need not have the same ops.\n+\t\t */\n+\t\tentry-\u003estate_index = state-\u003edynamic++;\n+\t\tbreak;\n+\tdefault:\n+\t\treturn ctlv_op_bad(target, op-\u003eop_id, \"has an unknown availability\");\n+\t}\n+\n+\t/*\n+\t * Once per device: what an inherited op may carry depends on the\n+\t * extension points this family filled and on nothing that changes later.\n+\t */\n+\tret = ctlv_schema_op_sizes(target, op, \u0026entry-\u003esizes);\n+\tif (ret)\n+\t\treturn ctlv_op_bad(target, op-\u003eop_id, \"needs messages this core cannot carry\");\n+\treturn 0;\n+}\n+\n+static int ctlv_op_resolution_init(struct ctlv_device *ctlvdev, const struct ctlv_family *family)\n+{\n+\tstruct ctlv_op_resolution state = {\n+\t\t.ctlvdev = ctlvdev,\n+\t\t.target = family,\n+\t};\n+\tconst struct ctlv_family *owner;\n+\tconst struct ctlv_op_schema *op;\n+\tstruct ctlv_schema_cursor cursor;\n+\tu32 ops_count = 0;\n+\tint ret;\n+\n+\tret = ctlv_family_check(family);\n+\tif (ret)\n+\t\treturn ret;\n+\tret = ctlv_family_privs_alloc(ctlvdev, family);\n+\tif (ret)\n+\t\treturn ret;\n+\n+\tctlv_schema_cursor_init(\u0026cursor, family);\n+\twhile (ctlv_schema_next_op(\u0026cursor, \u0026owner))\n+\t\tops_count++;\n+\tif (!ops_count)\n+\t\treturn ctlv_family_bad(family, \"has an effective schema with no op\");\n+\n+\tctlvdev-\u003eops = kcalloc(ops_count, sizeof(*ctlvdev-\u003eops), GFP_KERNEL);\n+\tif (!ctlvdev-\u003eops)\n+\t\treturn -ENOMEM;\n+\tctlvdev-\u003eops_count = ops_count;\n+\n+\tops_count = 0;\n+\tctlv_schema_cursor_init(\u0026cursor, family);\n+\twhile ((op = ctlv_schema_next_op(\u0026cursor, \u0026owner))) {\n+\t\tret = ctlv_op_resolution_family_enter(\u0026state, owner);\n+\t\tif (ret)\n+\t\t\treturn ret;\n+\t\tret = ctlv_op_resolution_add(\u0026state, owner, op, \u0026ctlvdev-\u003eops[ops_count++]);\n+\t\tif (ret)\n+\t\t\treturn ret;\n+\t}\n+\t/* The device family, no op of another having ended its table. */\n+\tret = ctlv_op_resolution_family_bound(\u0026state);\n+\tif (ret)\n+\t\treturn ret;\n+\tctlvdev-\u003edynamic_ops_count = state.dynamic;\n+\tctlvdev-\u003eevents_count = state.events;\n+\treturn 0;\n+}\n+\n+void *ctlv_priv_parent(const void *priv)\n+{\n+\tconst struct ctlv_priv_container *container = ctlv_priv_container(priv);\n+\n+\treturn container-\u003eparent ? container-\u003eparent-\u003epriv : NULL;\n+}\n+EXPORT_SYMBOL_NS_GPL(ctlv_priv_parent, \"CTLV\");\n+\n+void *ctlv_priv_child(const void *priv)\n+{\n+\tconst struct ctlv_priv_container *container = ctlv_priv_container(priv);\n+\n+\treturn container-\u003echild ? container-\u003echild-\u003epriv : NULL;\n+}\n+EXPORT_SYMBOL_NS_GPL(ctlv_priv_child, \"CTLV\");\n+\n+struct device *ctlv_device_parent(const struct ctlv_device *ctlvdev)\n+{\n+\treturn ctlvdev-\u003edev.parent;\n+}\n+EXPORT_SYMBOL_NS_GPL(ctlv_device_parent, \"CTLV\");\n+\n+/*\n+ * Dispatch reads the availability bit under no lock, so an op already admitted\n+ * is neither cancelled nor waited for by a disable.\n+ */\n+\n+struct ctlv_op_entry *ctlv_op_find(struct ctlv_device *ctlvdev, u64 op_id)\n+{\n+\tu32 index;\n+\n+\t/* The index ascends by op ID, so a miss stops early. */\n+\tfor (index = 0; index \u003c ctlvdev-\u003eops_count; index++) {\n+\t\tif (ctlvdev-\u003eops[index].schema-\u003eop_id == op_id)\n+\t\t\treturn \u0026ctlvdev-\u003eops[index];\n+\t\tif (ctlvdev-\u003eops[index].schema-\u003eop_id \u003e op_id)\n+\t\t\tbreak;\n+\t}\n+\treturn NULL;\n+}\n+\n+static bool ctlv_op_disabled(struct ctlv_device *ctlvdev, const struct ctlv_op_entry *op)\n+{\n+\tif (op-\u003estate_index == CTLV_OP_STATE_NONE)\n+\t\treturn false;\n+\t/* Acquire, so what the family prepared before enabling is visible. */\n+\treturn test_bit_acquire(op-\u003estate_index, ctlvdev-\u003edisabled);\n+}\n+\n+static void ctlv_op_publish_all(struct ctlv_device *ctlvdev)\n+{\n+\tu32 published = 0;\n+\tu32 index;\n+\n+\t/* Against a family still opting in as this is called. */\n+\tguard(spinlock)\n+\t\t(\u0026ctlvdev-\u003etransition_lock);\n+\tfor (index = 0; index \u003c ctlvdev-\u003eops_count; index++) {\n+\t\tif (ctlvdev-\u003eops[index].absent)\n+\t\t\tcontinue;\n+\t\tctlvdev-\u003eops[published++] = ctlvdev-\u003eops[index];\n+\t}\n+\tctlvdev-\u003eops_count = published;\n+\tctlvdev-\u003epublished = true;\n+}\n+\n+void ctlv_device_op_provide(struct ctlv_device *ctlvdev, u64 op_id)\n+{\n+\tstruct ctlv_op_entry *op;\n+\n+\tguard(spinlock)\n+\t\t(\u0026ctlvdev-\u003etransition_lock);\n+\tif (WARN_ON_ONCE(ctlvdev-\u003epublished || ctlvdev-\u003edestroying))\n+\t\treturn;\n+\top = ctlv_op_find(ctlvdev, op_id);\n+\t/* An event is produced rather than answered, so there is none. */\n+\tif (WARN_ON_ONCE(!op) || WARN_ON_ONCE(!op-\u003ebinding))\n+\t\treturn;\n+\top-\u003eabsent = false;\n+}\n+EXPORT_SYMBOL_NS_GPL(ctlv_device_op_provide, \"CTLV\");\n+\n+void ctlv_device_op_state_set(struct ctlv_device *ctlvdev, u64 op_id, bool disabled)\n+{\n+\tconst struct ctlv_op_entry *op;\n+\n+\t/*\n+\t * Also serializes lookup against publication, which compacts the\n+\t * array, and against teardown stopping state changes.\n+\t */\n+\tguard(spinlock)\n+\t\t(\u0026ctlvdev-\u003etransition_lock);\n+\tif (ctlvdev-\u003edestroying)\n+\t\treturn;\n+\top = ctlv_op_find(ctlvdev, op_id);\n+\tif (WARN_ON_ONCE(!op) || WARN_ON_ONCE(op-\u003estate_index == CTLV_OP_STATE_NONE))\n+\t\treturn;\n+\t/* An op this device never took on has no state to change. */\n+\tif (WARN_ON_ONCE(op-\u003eabsent))\n+\t\treturn;\n+\t/*\n+\t * Fully ordered, releasing what the family prepared to the acquire in\n+\t * ctlv_op_disabled(). The old state makes a repeat change nothing.\n+\t */\n+\tif (disabled ? test_and_set_bit(op-\u003estate_index, ctlvdev-\u003edisabled) :\n+\t\t       !test_and_clear_bit(op-\u003estate_index, ctlvdev-\u003edisabled))\n+\t\treturn;\n+\tif (!ctlvdev-\u003epublished)\n+\t\treturn;\n+\tctlvdev-\u003estate_generation++;\n+\t/* Still holding the serializer, so records reach queues in order. */\n+\tctlv_event_op_changed(ctlvdev, op, disabled, ctlvdev-\u003estate_generation);\n+}\n+EXPORT_SYMBOL_NS_GPL(ctlv_device_op_state_set, \"CTLV\");\n+\n+static int ctlv_op_check_mode(const struct file *filp, const struct ctlv_op_entry *op)\n+{\n+\tif (op-\u003eschema-\u003etype == CTLV_OP_TYPE_EVENT)\n+\t\treturn -EOPNOTSUPP;\n+\n+\tswitch (op-\u003eschema-\u003efd_access) {\n+\tcase CTLV_OP_FD_ACCESS_READ:\n+\t\treturn filp-\u003ef_mode \u0026 FMODE_READ ? 0 : -EACCES;\n+\tcase CTLV_OP_FD_ACCESS_READ_WRITE:\n+\t\treturn (filp-\u003ef_mode \u0026 (FMODE_READ | FMODE_WRITE)) == (FMODE_READ | FMODE_WRITE) ?\n+\t\t\t       0 :\n+\t\t\t       -EACCES;\n+\tdefault:\n+\t\t/* Registration rejects this before the device is visible. */\n+\t\treturn -EACCES;\n+\t}\n+}\n+\n+static u32 ctlv_reply_needed(const struct ctlv_op_entry *op)\n+{\n+\tif (op-\u003eschema-\u003etype == CTLV_OP_TYPE_QUERY)\n+\t\treturn op-\u003esizes.query_reply_min_len;\n+\treturn op-\u003esizes.action_reply_max_len;\n+}\n+\n+/*\n+ * request_len is the copy boundary; root length frames the message. Ignored\n+ * unknown attrs may exceed the schema maximum up to the transport limit.\n+ */\n+static int ctlv_request_frame(struct ctlv_op_ctx *ctx, const struct ctlv_op_exec *exec,\n+\t\t\t      const struct ctlv_attr *root)\n+{\n+\tif (root-\u003elen \u003c sizeof(*root) || root-\u003elen \u003e exec-\u003erequest_len ||\n+\t    root-\u003eattr_id != CTLV_ATTR_ROOT || root-\u003eflags != CTLV_ATTR_F_NESTED) {\n+\t\tctx-\u003eerror.reason = CTLV_VALIDATION_REASON_MALFORMED_MESSAGE;\n+\t\treturn -EINVAL;\n+\t}\n+\treturn 0;\n+}\n+\n+static int ctlv_request_validate(struct ctlv_op_ctx *ctx, const struct ctlv_op_exec *exec,\n+\t\t\t\t struct ctlv_attr *root)\n+{\n+\tint ret;\n+\n+\tret = ctlv_request_frame(ctx, exec, root);\n+\tif (ret)\n+\t\treturn ret;\n+\tif (!ctx-\u003eop-\u003eschema-\u003erequest.node_schemas)\n+\t\treturn 0;\n+\n+\tctx-\u003erequest = (struct ctlv_msg){\n+\t\t.root = root,\n+\t\t.len = exec-\u003erequest_len,\n+\t\t.tree = \u0026ctx-\u003eop-\u003eschema-\u003erequest,\n+\t\t.family = ctx-\u003efamily,\n+\t\t.request = true,\n+\t};\n+\treturn ctlv_schema_validate(\u0026ctx-\u003erequest, \u0026ctx-\u003eerror);\n+}\n+\n+/*\n+ * An action is given exactly the maximum its schema allows, so running out of\n+ * room is this kernel's mistake. A query is given whatever the caller offered.\n+ */\n+static u32 ctlv_reply_capacity(const struct ctlv_op_entry *op, const struct ctlv_op_exec *exec)\n+{\n+\tif (!op-\u003eschema-\u003ereply.node_schemas)\n+\t\treturn 0;\n+\tif (op-\u003eschema-\u003etype == CTLV_OP_TYPE_QUERY)\n+\t\treturn exec-\u003ereply_len;\n+\treturn op-\u003esizes.action_reply_max_len;\n+}\n+\n+/* Actions and final query fragments must be complete schema-valid replies. */\n+static int ctlv_reply_finish(struct ctlv_op_ctx *ctx)\n+{\n+\tstruct ctlv_error refused = {};\n+\n+\tif (!ctx-\u003eoutput.root)\n+\t\treturn 0;\n+\t/* Whatever poisoned it has warned about it already. */\n+\tif (ctx-\u003eoutput.poison)\n+\t\treturn ctx-\u003eoutput.poison;\n+\t/* A query was held to its open nests by the ending it came to. */\n+\tif (ctx-\u003eop-\u003eschema-\u003etype == CTLV_OP_TYPE_QUERY) {\n+\t\tif (ctx-\u003efrag.cursor || ctx-\u003efrag.next_cursor)\n+\t\t\treturn 0;\n+\t} else if (WARN_ON_ONCE(ctx-\u003edeepest != \u0026ctx-\u003eoutput_root)) {\n+\t\t/* A cursor of a returned frame is reset, never followed. */\n+\t\tctx-\u003edeepest = \u0026ctx-\u003eoutput_root;\n+\t\treturn -EINVAL;\n+\t}\n+\tif (WARN_ON_ONCE(ctlv_schema_validate(\u0026ctx-\u003eoutput, \u0026refused)))\n+\t\treturn -EINVAL;\n+\treturn 0;\n+}\n+\n+/* A successful query callback must end exactly one fragment. */\n+static int ctlv_query_fragment_result(struct ctlv_op_ctx *ctx)\n+{\n+\tif (WARN_ON_ONCE(!ctx-\u003efrag.answered))\n+\t\treturn -EINVAL;\n+\treturn ctx-\u003efrag.result;\n+}\n+\n+static int ctlv_op_call(struct ctlv_op_ctx *ctx)\n+{\n+\tconst struct ctlv_op_entry *op = ctx-\u003eop;\n+\tstruct ctlv_cursor *request = NULL;\n+\tstruct ctlv_cursor *reply = NULL;\n+\tint blob_ret;\n+\tint ret;\n+\n+\tif (ctx-\u003erequest.root) {\n+\t\tctlv_message_root(\u0026ctx-\u003erequest_root, \u0026ctx-\u003erequest);\n+\t\trequest = \u0026ctx-\u003erequest_root;\n+\t}\n+\tif (ctx-\u003eoutput.root)\n+\t\treply = \u0026ctx-\u003eoutput_root;\n+\n+\tctlv_blob_context_init(ctx);\n+\tif (op-\u003eschema-\u003etype == CTLV_OP_TYPE_ACTION) {\n+\t\tret = op-\u003ebinding-\u003eaction(op-\u003epriv, ctx, request, reply);\n+\t} else {\n+\t\tret = op-\u003ebinding-\u003equery(op-\u003epriv, ctx, request, reply);\n+\t\tif (!ret)\n+\t\t\tret = ctlv_query_fragment_result(ctx);\n+\t}\n+\tblob_ret = ctlv_blob_context_finish(ctx);\n+\tif (!ret)\n+\t\tret = blob_ret;\n+\tif (ret)\n+\t\treturn ret;\n+\treturn ctlv_reply_finish(ctx);\n+}\n+\n+/*\n+ * The device family's hooks around the declaring op's, except that a core op\n+ * uses the core family. The availability check is innermost.\n+ */\n+static int ctlv_op_dispatch(struct ctlv_op_ctx *ctx)\n+{\n+\tconst struct ctlv_op *op = ctx-\u003eop-\u003ebinding;\n+\tconst struct ctlv_family *family;\n+\tvoid *family_priv;\n+\tint ret;\n+\n+\tif (CTLV_OP_FAMILY(ctx-\u003eop-\u003eschema-\u003eop_id) == CTLV_FAMILY_ROOT) {\n+\t\tfamily = \u0026ctlv_family;\n+\t\tfamily_priv = ctx-\u003ectlvdev-\u003eprivs[0].priv;\n+\t} else {\n+\t\tfamily = ctx-\u003ectlvdev-\u003efamily;\n+\t\tfamily_priv = ctx-\u003ectlvdev-\u003eprivs[ctx-\u003ectlvdev-\u003eprivs_count - 1].priv;\n+\t}\n+\tret = family-\u003epre(family_priv, ctx);\n+\tif (ret)\n+\t\treturn ret;\n+\n+\tif (op-\u003epre) {\n+\t\tret = op-\u003epre(ctx-\u003eop-\u003epriv, ctx);\n+\t\tif (ret)\n+\t\t\tgoto out;\n+\t}\n+\n+\t/* The only authoritative check: introspection is advisory. */\n+\tif (ctlv_op_disabled(ctx-\u003ectlvdev, ctx-\u003eop))\n+\t\tret = -EOPNOTSUPP;\n+\telse\n+\t\tret = ctlv_op_call(ctx);\n+\n+\tif (op-\u003epost)\n+\t\top-\u003epost(ctx-\u003eop-\u003epriv, ctx);\n+out:\n+\tfamily-\u003epost(family_priv, ctx);\n+\treturn ret;\n+}\n+\n+/* Error information replaces the reply atomically; errno remains authoritative. */\n+static void ctlv_error_info(struct ctlv_op_ctx *ctx, u32 room, void **reply, u32 *reply_len)\n+{\n+\tconst struct ctlv_error *error = \u0026ctx-\u003eerror;\n+\tstruct ctlv_cursor *root = \u0026ctx-\u003eoutput_root;\n+\tvoid *buf;\n+\n+\tif ((!error-\u003ereason \u0026\u0026 !error-\u003emessage[0]) || !room)\n+\t\treturn;\n+\tbuf = kvmalloc(CTLV_ERROR_INFO_MAX_LEN, GFP_KERNEL_ACCOUNT);\n+\tif (!buf)\n+\t\treturn;\n+\n+\t/* The same builder over another schema, and a buffer of its own. */\n+\tctlv_message_output_init(\u0026ctx-\u003eoutput, ctx, buf, CTLV_ERROR_INFO_MAX_LEN,\n+\t\t\t\t \u0026ctlv_error_info_schema);\n+\tctlv_message_root(root, \u0026ctx-\u003eoutput);\n+\tctx-\u003edeepest = root;\n+\n+\tif (error-\u003ereason)\n+\t\tctlv_put_u64(root, CTLV_ATTR_ERROR_REASON, CTLV_SCHEMA_ENUM, error-\u003ereason);\n+\tif (error-\u003emessage[0])\n+\t\tctlv_error_message_put(root, error-\u003emessage);\n+\tif (error-\u003ereason == CTLV_VALIDATION_REASON_STALE_GENERATION) {\n+\t\t/* The one failure that is about no part of any message. */\n+\t\tctlv_put_u64(root, CTLV_ATTR_ERROR_EXPECTED_GENERATION, CTLV_SCHEMA_UINT,\n+\t\t\t     error-\u003eexpected_generation);\n+\t\tctlv_put_u64(root, CTLV_ATTR_ERROR_CURRENT_GENERATION, CTLV_SCHEMA_UINT,\n+\t\t\t     error-\u003ecurrent_generation);\n+\t} else if (error-\u003ereason) {\n+\t\tctlv_put_u64(root, CTLV_ATTR_ERROR_BAD_ATTR_OFFSET, CTLV_SCHEMA_UINT,\n+\t\t\t     error-\u003ebad_attr_offset);\n+\t\tctlv_put_u64(root, CTLV_ATTR_ERROR_NEST_OFFSET, CTLV_SCHEMA_UINT,\n+\t\t\t     error-\u003enest_offset);\n+\t\t/* No attr is numbered zero, so a zero names nothing. */\n+\t\tif (error-\u003emissing_attr_id)\n+\t\t\tctlv_put_u64(root, CTLV_ATTR_ERROR_MISSING_ATTR_ID, CTLV_SCHEMA_UINT,\n+\t\t\t\t     error-\u003emissing_attr_id);\n+\t}\n+\n+\tif (ctx-\u003eoutput.poison || ctx-\u003eoutput.root-\u003elen \u003e room) {\n+\t\tkvfree(buf);\n+\t\treturn;\n+\t}\n+\t*reply = buf;\n+\t*reply_len = ctx-\u003eoutput.root-\u003elen;\n+}\n+\n+/*\n+ * Everything that needs the device to still have a family. @reply is built\n+ * here and becomes the caller's to free, to copy out once the family is gone.\n+ */\n+static int ctlv_op_exec(struct ctlv_file *cfile, struct file *filp, struct ctlv_op_exec *exec,\n+\t\t\tvoid **reply, u32 *reply_len)\n+{\n+\tstruct ctlv_device *ctlvdev = cfile-\u003ectlvdev;\n+\tconst struct ctlv_op_entry *op;\n+\tstruct ctlv_op_ctx ctx = {};\n+\tu32 capacity;\n+\tint ret;\n+\n+\t/* No family numbers an op zero, so a zero here is an unset field. */\n+\tif (!exec-\u003eop_id)\n+\t\treturn -EINVAL;\n+\top = ctlv_op_find(ctlvdev, exec-\u003eop_id);\n+\tif (!op)\n+\t\treturn -EOPNOTSUPP;\n+\tret = ctlv_op_check_mode(filp, op);\n+\tif (ret)\n+\t\treturn ret;\n+\t/*\n+\t * Only a query resumes. A cursor says which fragment this is, so a\n+\t * generation without one continues what was never started.\n+\t */\n+\tif (op-\u003eschema-\u003etype == CTLV_OP_TYPE_QUERY) {\n+\t\tif (!exec-\u003ecursor \u0026\u0026 exec-\u003egeneration)\n+\t\t\treturn -EINVAL;\n+\t\tctx.frag.generation = exec-\u003egeneration;\n+\t\tctx.frag.cursor = exec-\u003ecursor;\n+\t} else if (exec-\u003egeneration || exec-\u003ecursor) {\n+\t\treturn -EINVAL;\n+\t}\n+\n+\t/* Before the callback, so a buffer too small mutates nothing. */\n+\tif (exec-\u003ereply_len \u003c ctlv_reply_needed(op))\n+\t\treturn -EMSGSIZE;\n+\t/* And no longer than a message of this core may be. */\n+\tif (exec-\u003ereply_len \u003e CTLV_MAX_INLINE_MESSAGE_LEN)\n+\t\treturn -EINVAL;\n+\n+\tctx.ctlvdev = ctlvdev;\n+\tctx.family = ctlvdev-\u003efamily;\n+\tctx.file = cfile;\n+\t/* Whose memory a blob descriptor of this request describes. */\n+\tctx.submitter = current;\n+\tctx.op = op;\n+\n+\tvoid *snapshot __free(kvfree) = NULL;\n+\tvoid *out __free(kvfree) = NULL;\n+\n+\tif (exec-\u003erequest_len \u003c sizeof(struct ctlv_attr) ||\n+\t    exec-\u003erequest_len \u003e CTLV_MAX_INLINE_MESSAGE_LEN)\n+\t\treturn -EINVAL;\n+\t/* Everything after this reads the snapshot, never userspace. */\n+\tsnapshot = kvmalloc(exec-\u003erequest_len, GFP_KERNEL_ACCOUNT);\n+\tif (!snapshot)\n+\t\treturn -ENOMEM;\n+\tif (copy_from_user(snapshot, u64_to_user_ptr(exec-\u003erequest), exec-\u003erequest_len))\n+\t\treturn -EFAULT;\n+\t/* Before any hook, so that no family code sees an unchecked attr. */\n+\tret = ctlv_request_validate(\u0026ctx, exec, snapshot);\n+\tif (ret)\n+\t\tgoto out_error_info;\n+\n+\tcapacity = ctlv_reply_capacity(op, exec);\n+\tif (capacity) {\n+\t\t/*\n+\t\t * Not zeroed: a byte is copied out only once the root's\n+\t\t * length covers it, padding included.\n+\t\t */\n+\t\tout = kvmalloc(capacity, GFP_KERNEL_ACCOUNT);\n+\t\tif (!out) {\n+\t\t\tret = -ENOMEM;\n+\t\t\tgoto out_request;\n+\t\t}\n+\t\tctlv_message_output_init(\u0026ctx.output, \u0026ctx, out, capacity, \u0026op-\u003eschema-\u003ereply);\n+\t\tctlv_message_root(\u0026ctx.output_root, \u0026ctx.output);\n+\t\tctx.deepest = \u0026ctx.output_root;\n+\t}\n+\n+\tret = ctlv_op_dispatch(\u0026ctx);\n+\tif (ret)\n+\t\tgoto out_error_info;\n+\n+\t/* Where the caller carries on from, zero for anything but a query. */\n+\texec-\u003egeneration = ctx.frag.reported;\n+\texec-\u003ecursor = ctx.frag.next_cursor;\n+\t*reply_len = ctx.output.root ? ctx.output.root-\u003elen : 0;\n+\t*reply = no_free_ptr(out);\n+\tret = 0;\n+\tgoto out_request;\n+\n+out_error_info:\n+\tctlv_error_info(\u0026ctx, exec-\u003ereply_len, reply, reply_len);\n+out_request:\n+\tctlv_message_index_free(\u0026ctx.request);\n+\treturn ret;\n+}\n+\n+/* What one family of this device's chain does with one extension point. */\n+static const struct ctlv_stub_ops *ctlv_stub_ops_find(const struct ctlv_device *ctlvdev,\n+\t\t\t\t\t\t      const struct ctlv_stub_schema *stub_schema,\n+\t\t\t\t\t\t      void **priv)\n+{\n+\tconst struct ctlv_family *family;\n+\tu32 index;\n+\n+\t/* From the device family towards the core, where the fill was found. */\n+\tfor (family = ctlvdev-\u003efamily; family; family = family-\u003eparent)\n+\t\tfor (index = 0; index \u003c family-\u003estub_ops_count; index++)\n+\t\t\tif (family-\u003estub_ops[index].family_id == stub_schema-\u003efamily_id \u0026\u0026\n+\t\t\t    family-\u003estub_ops[index].set_id == stub_schema-\u003eset_id) {\n+\t\t\t\tstruct ctlv_family_priv *family_priv;\n+\n+\t\t\t\tfamily_priv = ctlv_family_priv_find(ctlvdev, family);\n+\t\t\t\tif (WARN_ON_ONCE(!family_priv))\n+\t\t\t\t\treturn NULL;\n+\t\t\t\t*priv = family_priv-\u003epriv;\n+\t\t\t\treturn \u0026family-\u003estub_ops[index];\n+\t\t\t}\n+\treturn NULL;\n+}\n+\n+int ctlv_stub_fill(struct ctlv_op_ctx *ctx, const struct ctlv_cursor *request,\n+\t\t   struct ctlv_cursor *nest)\n+{\n+\tconst struct ctlv_schema_tree *tree;\n+\tu32 index;\n+\n+\tif (WARN_ON_ONCE(!nest-\u003etree))\n+\t\treturn -EINVAL;\n+\ttree = nest-\u003etree;\n+\tfor (index = 0; index \u003c tree-\u003estub_schemas_count; index++) {\n+\t\tconst struct ctlv_stub_schema *stub_schema = \u0026tree-\u003estub_schemas[index];\n+\t\tconst struct ctlv_cursor *filled_request = request;\n+\t\tconst struct ctlv_stub_fill_schema *fill_schema;\n+\t\tconst struct ctlv_stub_ops *stub_ops;\n+\t\tstruct ctlv_cursor filled;\n+\t\tvoid *priv;\n+\t\tint ret;\n+\n+\t\tif (stub_schema-\u003enode != nest-\u003enode)\n+\t\t\tcontinue;\n+\t\tstub_ops = ctlv_stub_ops_find(ctx-\u003ectlvdev, stub_schema, \u0026priv);\n+\t\tif (!stub_ops || !stub_ops-\u003efill)\n+\t\t\tcontinue;\n+\t\tif (request) {\n+\t\t\tfill_schema = ctlv_schema_fill(ctx-\u003efamily, stub_schema-\u003efamily_id,\n+\t\t\t\t\t\t       stub_schema-\u003eset_id);\n+\t\t\tif (WARN_ON_ONCE(!fill_schema))\n+\t\t\t\treturn -EINVAL;\n+\t\t\tfilled = *request;\n+\t\t\tif (ctlv_message_input_rebind(\u0026filled, \u0026fill_schema-\u003emembers, 0))\n+\t\t\t\tfilled_request = \u0026filled;\n+\t\t\telse\n+\t\t\t\tfilled_request = NULL;\n+\t\t}\n+\t\tret = stub_ops-\u003efill(priv, ctx, filled_request, nest);\n+\t\tif (ret)\n+\t\t\treturn ret;\n+\t}\n+\treturn 0;\n+}\n+EXPORT_SYMBOL_NS_GPL(ctlv_stub_fill, \"CTLV\");\n+\n+/*\n+ * The core answers the root family through the same generated descriptor a\n+ * family creates with, so it needs the same callbacks.\n+ */\n+int ctlv_op_pre(void *priv, struct ctlv_op_ctx *ctx)\n+{\n+\treturn 0;\n+}\n+\n+void ctlv_op_post(void *priv, struct ctlv_op_ctx *ctx)\n+{\n+}\n+\n+size_t ctlv_priv_size(void)\n+{\n+\treturn 0;\n+}\n+\n+int ctlv_init(struct ctlv_device *ctlvdev, const void *init_info, void *priv)\n+{\n+\tif (WARN_ON_ONCE(init_info) || WARN_ON_ONCE(ctlv_priv_parent(priv)))\n+\t\treturn -EINVAL;\n+\treturn 0;\n+}\n+\n+void ctlv_fini(struct ctlv_device *ctlvdev, void *priv)\n+{\n+}\n+\n+static long ctlv_file_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)\n+{\n+\tstruct ctlv_op_exec __user *uexec = (struct ctlv_op_exec __user *)arg;\n+\tstruct ctlv_file *cfile = filp-\u003eprivate_data;\n+\tstruct ctlv_device *ctlvdev = cfile-\u003ectlvdev;\n+\tstruct ctlv_op_exec exec;\n+\tu32 reply_len = 0;\n+\tint ret;\n+\n+\tif (cmd != CTLV_IOC_OP_EXEC)\n+\t\treturn -ENOIOCTLCMD;\n+\tif (copy_from_user(\u0026exec, uexec, sizeof(exec)))\n+\t\treturn -EFAULT;\n+\t/* Reserved fields are what a compatible growth of this ioctl uses. */\n+\tif (exec.reserved[0] || exec.reserved[1])\n+\t\treturn -EINVAL;\n+\n+\tvoid *reply __free(kvfree) = NULL;\n+\n+\tscoped_guard(rwsem_read, \u0026ctlvdev-\u003eregistration_lock) {\n+\t\tif (!ctlvdev-\u003eregistered || !ctlvdev-\u003efamily)\n+\t\t\treturn -ENODEV;\n+\t\tret = ctlv_op_exec(cfile, filp, \u0026exec, \u0026reply, \u0026reply_len);\n+\t}\n+\t/* Do not make destruction wait for a faulting userspace copy. */\n+\tif (reply_len \u0026\u0026 copy_to_user(u64_to_user_ptr(exec.reply), reply, reply_len))\n+\t\treturn ret ?: -EFAULT;\n+\t/*\n+\t * The only fields the kernel writes back, a field at a time so that\n+\t * what the caller stated about its own buffers stays the caller's.\n+\t */\n+\tif (!ret \u0026\u0026 (put_user(exec.generation, \u0026uexec-\u003egeneration) ||\n+\t\t     put_user(exec.cursor, \u0026uexec-\u003ecursor)))\n+\t\treturn -EFAULT;\n+\treturn ret;\n+}\n+\n+/*\n+ * One record per read, so a reader never gets a partial event. The offset says\n+ * nothing about a queue and is neither read nor advanced.\n+ */\n+static ssize_t ctlv_file_read(struct file *filp, char __user *buf, size_t len, loff_t *ppos)\n+{\n+\tstruct ctlv_file *cfile = filp-\u003eprivate_data;\n+\n+\treturn ctlv_event_file_read(cfile, buf, len, !(filp-\u003ef_flags \u0026 O_NONBLOCK));\n+}\n+\n+static __poll_t ctlv_file_poll(struct file *filp, struct poll_table_struct *wait)\n+{\n+\tstruct ctlv_file *cfile = filp-\u003eprivate_data;\n+\n+\treturn ctlv_event_file_poll(cfile, filp, wait);\n+}\n+\n+static bool ctlv_file_open_allowed(struct ctlv_device *ctlvdev)\n+{\n+\tlockdep_assert_held_read(\u0026ctlvdev-\u003eregistration_lock);\n+\treturn ctlvdev-\u003eregistered \u0026\u0026 ctlvdev-\u003efamily;\n+}\n+\n+static void ctlv_file_open_pinned(struct ctlv_device *ctlvdev)\n+{\n+}\n+\n+static int ctlv_file_open(struct inode *inode, struct file *filp)\n+{\n+\tstruct ctlv_device *ctlvdev = container_of(inode-\u003ei_cdev, struct ctlv_device, cdev);\n+\tstruct ctlv_file *cfile;\n+\tint ret;\n+\n+\t/*\n+\t * A failed create can withdraw the cdev while an open is waiting for\n+\t * the lifecycle lock, so admission itself first pins core storage.\n+\t */\n+\tget_device(\u0026ctlvdev-\u003edev);\n+\tctlv_file_open_pinned(ctlvdev);\n+\tscoped_guard(rwsem_read, \u0026ctlvdev-\u003eregistration_lock) {\n+\t\tif (!ctlv_file_open_allowed(ctlvdev)) {\n+\t\t\tret = -ENODEV;\n+\t\t\tbreak;\n+\t\t}\n+\t\tif (!(filp-\u003ef_mode \u0026 FMODE_READ)) {\n+\t\t\tret = -EACCES;\n+\t\t\tbreak;\n+\t\t}\n+\n+\t\tcfile = kzalloc_obj(*cfile, GFP_KERNEL_ACCOUNT);\n+\t\tif (!cfile) {\n+\t\t\tret = -ENOMEM;\n+\t\t\tbreak;\n+\t\t}\n+\t\tcfile-\u003ectlvdev = ctlvdev;\n+\t\t/*\n+\t\t * Commits this description to the device. An open that failed\n+\t\t * after this would have to take it back.\n+\t\t */\n+\t\tret = ctlv_event_file_init(cfile);\n+\t\tif (ret) {\n+\t\t\tkfree(cfile);\n+\t\t\tbreak;\n+\t\t}\n+\t\t/* This description keeps the reference taken on entry. */\n+\t\tfilp-\u003eprivate_data = cfile;\n+\t\treturn 0;\n+\t}\n+\n+\tput_device(\u0026ctlvdev-\u003edev);\n+\treturn ret;\n+}\n+\n+static int ctlv_file_release(struct inode *inode, struct file *filp)\n+{\n+\tstruct ctlv_file *cfile = filp-\u003eprivate_data;\n+\tstruct ctlv_device *ctlvdev = cfile-\u003ectlvdev;\n+\n+\tctlv_event_file_exit(cfile);\n+\tkfree(cfile);\n+\tput_device(\u0026ctlvdev-\u003edev);\n+\treturn 0;\n+}\n+\n+static const struct file_operations ctlv_file_operations = {\n+\t.owner = THIS_MODULE,\n+\t.open = ctlv_file_open,\n+\t.release = ctlv_file_release,\n+\t.read = ctlv_file_read,\n+\t.poll = ctlv_file_poll,\n+\t.unlocked_ioctl = ctlv_file_ioctl,\n+\t/* Every ioctl field is fixed width, so one entry point serves both. */\n+\t.compat_ioctl = compat_ptr_ioctl,\n+};\n+\n+/* Uevent identity is available to rules before the device can be opened. */\n+static int ctlv_device_uevent_families(struct kobj_uevent_env *env,\n+\t\t\t\t       const struct ctlv_family *family)\n+{\n+\tu32 levels = ctlv_family_levels(family);\n+\tu32 level;\n+\tint ret;\n+\n+\tret = add_uevent_var(env, \"CTLV_FAMILY=%s\", family-\u003eschema-\u003ename);\n+\tif (ret)\n+\t\treturn ret;\n+\tfor (level = 0; level \u003c levels; level++) {\n+\t\tconst struct ctlv_family *ancestor =\n+\t\t\tctlv_family_ancestor(family, levels - 1 - level);\n+\n+\t\tret = add_uevent_var(env, \"CTLV_COMPATIBLE_%u=%s\", level, ancestor-\u003eschema-\u003ename);\n+\t\tif (ret)\n+\t\t\treturn ret;\n+\t}\n+\treturn add_uevent_var(env, \"CTLV_COMPATIBLE_N=%u\", levels);\n+}\n+\n+static int ctlv_device_uevent_check(const struct ctlv_family *family)\n+{\n+\tstruct kobj_uevent_env *env;\n+\tint ret;\n+\n+\tenv = kzalloc_obj(*env, GFP_KERNEL);\n+\tif (!env)\n+\t\treturn -ENOMEM;\n+\tret = ctlv_device_uevent_families(env, family);\n+\tif (!ret \u0026\u0026 (env-\u003ebuflen \u003e CTLV_UEVENT_MAX_LEN || env-\u003eenvp_idx \u003e CTLV_UEVENT_MAX_VARS)) {\n+\t\tpr_err(\"family %s: its chain of names needs %d bytes in %d properties of a uevent, more than the %d in %d it may take\\n\",\n+\t\t       family-\u003eschema-\u003ename, env-\u003ebuflen, env-\u003eenvp_idx, CTLV_UEVENT_MAX_LEN,\n+\t\t       CTLV_UEVENT_MAX_VARS);\n+\t\tret = -E2BIG;\n+\t}\n+\tkfree(env);\n+\treturn ret;\n+}\n+\n+/* Read unlocked: a uevent may be asked for under the registration lock. */\n+static int ctlv_device_uevent(const struct device *dev, struct kobj_uevent_env *env)\n+{\n+\tconst struct ctlv_device *ctlvdev = container_of_const(dev, struct ctlv_device, dev);\n+\tconst struct ctlv_family *family = READ_ONCE(ctlvdev-\u003efamily);\n+\n+\tif (!family)\n+\t\treturn 0;\n+\treturn ctlv_device_uevent_families(env, family);\n+}\n+\n+static void ctlv_device_release(struct device *dev)\n+{\n+\tstruct ctlv_device *ctlvdev = container_of(dev, struct ctlv_device, dev);\n+\n+\tida_free(\u0026ctlv_device_ids, ctlvdev-\u003edev.devt - ctlv_device_number);\n+\tbitmap_free(ctlvdev-\u003edisabled);\n+\tctlv_family_privs_free(ctlvdev);\n+\tkfree(ctlvdev-\u003eops);\n+\tkfree(ctlvdev);\n+}\n+\n+static struct class ctlv_device_class = {\n+\t.name = \"ctlv\",\n+\t.dev_release = ctlv_device_release,\n+\t.dev_uevent = ctlv_device_uevent,\n+};\n+\n+static int ctlv_device_add(struct ctlv_device *ctlvdev)\n+{\n+\tlockdep_assert_held_write(\u0026ctlvdev-\u003eregistration_lock);\n+\n+\treturn cdev_device_add(\u0026ctlvdev-\u003ecdev, \u0026ctlvdev-\u003edev);\n+}\n+\n+static void ctlv_device_del(struct ctlv_device *ctlvdev)\n+{\n+\tcdev_device_del(\u0026ctlvdev-\u003ecdev, \u0026ctlvdev-\u003edev);\n+}\n+\n+struct ctlv_device *ctlv_create(struct device *parent_dev, const struct ctlv_family *family,\n+\t\t\t\tconst void *init_info)\n+{\n+\tstruct ctlv_device *ctlvdev;\n+\tint devnum, ret;\n+\n+\tif (!parent_dev || !family)\n+\t\treturn ERR_PTR(-EINVAL);\n+\n+\tctlvdev = kzalloc_obj(*ctlvdev, GFP_KERNEL);\n+\tif (!ctlvdev)\n+\t\treturn ERR_PTR(-ENOMEM);\n+\tctlvdev-\u003efamily = family;\n+\tinit_rwsem(\u0026ctlvdev-\u003eregistration_lock);\n+\tspin_lock_init(\u0026ctlvdev-\u003etransition_lock);\n+\tctlv_event_device_init(ctlvdev);\n+\n+\t/* Before anything reads the schema through this device. */\n+\tret = ctlv_op_resolution_init(ctlvdev, family);\n+\tif (ret)\n+\t\tgoto err_free;\n+\t/* What this family's events need of every queue opened on it. */\n+\tret = ctlv_event_sizes(ctlvdev);\n+\tif (ret)\n+\t\tgoto err_free;\n+\t/* Before a minor is spent on a device that could not be announced. */\n+\tret = ctlv_device_uevent_check(family);\n+\tif (ret)\n+\t\tgoto err_free;\n+\tif (ctlvdev-\u003edynamic_ops_count) {\n+\t\tctlvdev-\u003edisabled = bitmap_zalloc(ctlvdev-\u003edynamic_ops_count, GFP_KERNEL);\n+\t\tif (!ctlvdev-\u003edisabled) {\n+\t\t\tret = -ENOMEM;\n+\t\t\tgoto err_free;\n+\t\t}\n+\t}\n+\tdevnum = ida_alloc_max(\u0026ctlv_device_ids, CTLV_MAX_DEVICES - 1, GFP_KERNEL);\n+\tif (devnum \u003c 0) {\n+\t\tret = devnum;\n+\t\tgoto err_free;\n+\t}\n+\n+\tctlvdev-\u003edev.devt = ctlv_device_number + devnum;\n+\tctlvdev-\u003edev.class = \u0026ctlv_device_class;\n+\tctlvdev-\u003edev.parent = parent_dev;\n+\tdevice_initialize(\u0026ctlvdev-\u003edev);\n+\t/*\n+\t * The core owns the file operations, so an open holds the core module\n+\t * and not the family's, which may unload while readers remain.\n+\t */\n+\tcdev_init(\u0026ctlvdev-\u003ecdev, \u0026ctlv_file_operations);\n+\tctlvdev-\u003ecdev.owner = THIS_MODULE;\n+\n+\tret = dev_set_name(\u0026ctlvdev-\u003edev, \"ctlv%d\", devnum);\n+\tif (ret)\n+\t\tgoto err_put;\n+\tret = ctlv_family_claim_add(family-\u003eschema);\n+\tif (ret)\n+\t\tgoto err_put;\n+\tret = ctlv_family_privs_pre_init(ctlvdev, init_info);\n+\tif (ret)\n+\t\tgoto err_put;\n+\tret = ctlv_family_privs_init(ctlvdev);\n+\tif (ret)\n+\t\tgoto err_put;\n+\tctlv_op_publish_all(ctlvdev);\n+\tctlv_event_contexts_start(ctlvdev);\n+\tret = ctlv_family_privs_post_init(ctlvdev);\n+\tif (ret)\n+\t\tgoto err_fini;\n+\tscoped_guard(rwsem_write, \u0026ctlvdev-\u003eregistration_lock) {\n+\t\tret = ctlv_device_add(ctlvdev);\n+\t\tif (!ret)\n+\t\t\tctlvdev-\u003eregistered = true;\n+\t}\n+\tif (ret)\n+\t\tgoto err_fini;\n+\treturn ctlvdev;\n+\n+err_fini:\n+\tctlv_device_fini(ctlvdev);\n+err_put:\n+\tput_device(\u0026ctlvdev-\u003edev);\n+\treturn ERR_PTR(ret);\n+err_free:\n+\tbitmap_free(ctlvdev-\u003edisabled);\n+\tctlv_family_privs_free(ctlvdev);\n+\tkfree(ctlvdev-\u003eops);\n+\tkfree(ctlvdev);\n+\treturn ERR_PTR(ret);\n+}\n+EXPORT_SYMBOL_NS_GPL(ctlv_create, \"CTLV\");\n+\n+void ctlv_destroy(struct ctlv_device *ctlvdev)\n+{\n+\tu32 index;\n+\n+\t/* No new opens, no discovery entry, and no node to open. */\n+\tctlv_device_del(ctlvdev);\n+\n+\t/*\n+\t * The write side waits for admitted callbacks while their events still\n+\t * work. Once held, registration state keeps every later ioctl out.\n+\t */\n+\tscoped_guard(rwsem_write, \u0026ctlvdev-\u003eregistration_lock)\n+\t\tctlvdev-\u003eregistered = false;\n+\n+\tctlv_device_fini(ctlvdev);\n+\n+\t/* No callback can reach what the family owns after finalization. */\n+\tscoped_guard(rwsem_write, \u0026ctlvdev-\u003eregistration_lock)\n+\t\tWRITE_ONCE(ctlvdev-\u003efamily, NULL);\n+\tfor (index = 0; index \u003c ctlvdev-\u003eops_count; index++) {\n+\t\tctlvdev-\u003eops[index].binding = NULL;\n+\t\tctlvdev-\u003eops[index].priv = NULL;\n+\t}\n+\tctlv_family_privs_free(ctlvdev);\n+\tput_device(\u0026ctlvdev-\u003edev);\n+}\n+EXPORT_SYMBOL_NS_GPL(ctlv_destroy, \"CTLV\");\n+\n+static int __init ctlv_module_init(void)\n+{\n+\tint ret;\n+\n+\tret = alloc_chrdev_region(\u0026ctlv_device_number, 0, CTLV_MAX_DEVICES, \"ctlv\");\n+\tif (ret)\n+\t\treturn ret;\n+\n+\tret = class_register(\u0026ctlv_device_class);\n+\tif (ret)\n+\t\tgoto err_unregister_chrdev_region;\n+\n+\treturn 0;\n+\n+err_unregister_chrdev_region:\n+\tunregister_chrdev_region(ctlv_device_number, CTLV_MAX_DEVICES);\n+\treturn ret;\n+}\n+\n+static void __exit ctlv_module_exit(void)\n+{\n+\tclass_unregister(\u0026ctlv_device_class);\n+\tunregister_chrdev_region(ctlv_device_number, CTLV_MAX_DEVICES);\n+\tctlv_family_claims_free();\n+\tida_destroy(\u0026ctlv_device_ids);\n+}\n+\n+subsys_initcall(ctlv_module_init);\n+module_exit(ctlv_module_exit);\n+MODULE_DESCRIPTION(\"CTLV character device TLV UAPI core\");\n+MODULE_LICENSE(\"GPL\");\ndiff --git a/drivers/ctlv/ctlv_gen.c b/drivers/ctlv/ctlv_gen.c\nnew file mode 100644\nindex 0000000000000..daf54495658f5\n--- /dev/null\n+++ b/drivers/ctlv/ctlv_gen.c\n@@ -0,0 +1,229 @@\n+// SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)\n+/* Do not edit, regenerate with tools/ctlv/ctlv-regen.sh, from: */\n+/*\tDocumentation/ctlv/specs/ctlv.yaml */\n+/* CTLV-GEN kernel source */\n+\n+#define _CTLV_GENERATED_METADATA_ONLY\n+#include \u003clinux/array_size.h\u003e\n+#include \u003clinux/build_bug.h\u003e\n+#include \u003clinux/ctlv_family.h\u003e\n+#include \u003clinux/export.h\u003e\n+#include \u003clinux/limits.h\u003e\n+\n+#include \u003cuapi/linux/ctlv_gen.h\u003e\n+\n+#include \u003clinux/ctlv_gen.h\u003e\n+\n+static const struct ctlv_node_schema families_dump_request_node_schemas[] = {\n+\tCTLV_NODE_SCHEMA_ROOT(0, 0, 0),\n+};\n+\n+static const struct ctlv_node_schema families_dump_reply_node_schemas[] = {\n+\tCTLV_NODE_SCHEMA_ROOT(1, 1, 1),\n+\tCTLV_NODE_SCHEMA_NEST(CTLV_ATTR_FAMILY_ENTRY, CTLV_NODE_SCHEMA_UNLIMITED, 2, 2, 2),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_FAMILY_ID, 1, 0, U64_MAX),\n+\tCTLV_NODE_SCHEMA_STRING(CTLV_ATTR_FAMILY_NAME, 1, 0, 63),\n+};\n+\n+static const struct ctlv_node_schema ops_dump_request_node_schemas[] = {\n+\tCTLV_NODE_SCHEMA_ROOT(0, 0, 0),\n+};\n+\n+static const struct ctlv_node_schema ops_dump_reply_node_schemas[] = {\n+\tCTLV_NODE_SCHEMA_ROOT(1, 1, 1),\n+\tCTLV_NODE_SCHEMA_NEST(CTLV_ATTR_OP_ENTRY, CTLV_NODE_SCHEMA_UNLIMITED, 2, 10, 2),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_OP_ID, 1, 1, U64_MAX),\n+\tCTLV_NODE_SCHEMA_ENUM(CTLV_ATTR_OP_TYPE, 1, 3),\n+\tCTLV_NODE_SCHEMA_ENUM(CTLV_ATTR_OP_AVAILABILITY, 1, 2),\n+\tCTLV_NODE_SCHEMA_BOOL(CTLV_ATTR_OP_DISABLED, 1),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_OP_REQUEST_MAX_LEN, 1, 0, U64_MAX),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_OP_ACTION_REPLY_MAX_LEN, 1, 0, U64_MAX),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_OP_QUERY_REPLY_MIN_LEN, 1, 0, U64_MAX),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_OP_QUERY_REPLY_SUGGESTED_LEN, 1, 0, U64_MAX),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_OP_EVENT_RECORD_MAX_LEN, 1, 0, U64_MAX),\n+\tCTLV_NODE_SCHEMA_ENUM(CTLV_ATTR_OP_FD_ACCESS, 1, 2),\n+};\n+\n+static const struct ctlv_node_schema op_schema_get_request_node_schemas[] = {\n+\tCTLV_NODE_SCHEMA_ROOT(1, 1, 1),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_OP_ID, 1, 1, U64_MAX),\n+};\n+\n+static const struct ctlv_node_schema op_schema_get_reply_node_schemas[] = {\n+\tCTLV_NODE_SCHEMA_ROOT(1, 2, 0),\n+\tCTLV_NODE_SCHEMA_NEST(CTLV_ATTR_SCHEMA_REQUEST, 1, 3, 17, 3),\n+\tCTLV_NODE_SCHEMA_NEST(CTLV_ATTR_SCHEMA_REPLY, 1, 20, 17, 3),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_ATTR_ID, 1, 0, U64_MAX),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_KIND, 1, 0, U64_MAX),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_MAX_OCCURRENCES, 1, 0, U64_MAX),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_MIN, 1, 0, U64_MAX),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_MAX, 1, 0, U64_MAX),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_MIN_LENGTH, 1, 0, U64_MAX),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_MAX_LENGTH, 1, 0, U64_MAX),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_FLAGS_MASK, 1, 0, U64_MAX),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_UNIT, 1, 0, U64_MAX),\n+\tCTLV_NODE_SCHEMA_SINT(CTLV_ATTR_SCHEMA_SCALE, 1, S64_MIN, S64_MAX),\n+\tCTLV_NODE_SCHEMA_ENUM(CTLV_ATTR_SCHEMA_BLOB_DIRECTION, 1, 3),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_BLOB_BACKINGS, 1, 0, U64_MAX),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_BLOB_MAX_LENGTH, 1, 0, U64_MAX),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_BLOB_ALIGNMENT, 1, 0, U64_MAX),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_REENTERS, 1, 1, U64_MAX),\n+\tCTLV_NODE_SCHEMA_NEST_REENTERS(CTLV_ATTR_SCHEMA_ATTRS, CTLV_NODE_SCHEMA_UNLIMITED, 3, 17,\n+\t\t\t\t       3),\n+\tCTLV_NODE_SCHEMA_NEST_REENTERS(CTLV_ATTR_SCHEMA_OPTIONAL_ATTRS, CTLV_NODE_SCHEMA_UNLIMITED,\n+\t\t\t\t       3, 17, 3),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_ATTR_ID, 1, 0, U64_MAX),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_KIND, 1, 0, U64_MAX),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_MAX_OCCURRENCES, 1, 0, U64_MAX),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_MIN, 1, 0, U64_MAX),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_MAX, 1, 0, U64_MAX),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_MIN_LENGTH, 1, 0, U64_MAX),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_MAX_LENGTH, 1, 0, U64_MAX),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_FLAGS_MASK, 1, 0, U64_MAX),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_UNIT, 1, 0, U64_MAX),\n+\tCTLV_NODE_SCHEMA_SINT(CTLV_ATTR_SCHEMA_SCALE, 1, S64_MIN, S64_MAX),\n+\tCTLV_NODE_SCHEMA_ENUM(CTLV_ATTR_SCHEMA_BLOB_DIRECTION, 1, 3),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_BLOB_BACKINGS, 1, 0, U64_MAX),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_BLOB_MAX_LENGTH, 1, 0, U64_MAX),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_BLOB_ALIGNMENT, 1, 0, U64_MAX),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_REENTERS, 1, 1, U64_MAX),\n+\tCTLV_NODE_SCHEMA_NEST_REENTERS(CTLV_ATTR_SCHEMA_ATTRS, CTLV_NODE_SCHEMA_UNLIMITED, 20, 17,\n+\t\t\t\t       3),\n+\tCTLV_NODE_SCHEMA_NEST_REENTERS(CTLV_ATTR_SCHEMA_OPTIONAL_ATTRS, CTLV_NODE_SCHEMA_UNLIMITED,\n+\t\t\t\t       20, 17, 3),\n+};\n+\n+static const struct ctlv_node_schema subscriptions_add_request_node_schemas[] = {\n+\tCTLV_NODE_SCHEMA_ROOT(1, 1, 1),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_EVENT_OP_ID, 256, 1, U64_MAX),\n+};\n+\n+static const struct ctlv_node_schema subscriptions_remove_request_node_schemas[] = {\n+\tCTLV_NODE_SCHEMA_ROOT(1, 1, 1),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_EVENT_OP_ID, 256, 1, U64_MAX),\n+};\n+\n+static const struct ctlv_node_schema event_queue_get_request_node_schemas[] = {\n+\tCTLV_NODE_SCHEMA_ROOT(0, 0, 0),\n+};\n+\n+static const struct ctlv_node_schema event_queue_get_reply_node_schemas[] = {\n+\tCTLV_NODE_SCHEMA_ROOT(1, 2, 2),\n+\tCTLV_NODE_SCHEMA_UINT_UNIT(CTLV_ATTR_EVENT_QUEUE_LEN, 1, 1, 16777216, CTLV_UNIT_BYTES, 0),\n+\tCTLV_NODE_SCHEMA_UINT_UNIT(CTLV_ATTR_EVENT_QUEUE_USED, 1, 0, U64_MAX, CTLV_UNIT_BYTES, 0),\n+};\n+\n+static const struct ctlv_node_schema event_queue_set_request_node_schemas[] = {\n+\tCTLV_NODE_SCHEMA_ROOT(1, 1, 1),\n+\tCTLV_NODE_SCHEMA_UINT_UNIT(CTLV_ATTR_EVENT_QUEUE_LEN, 1, 1, 16777216, CTLV_UNIT_BYTES, 0),\n+};\n+\n+static const struct ctlv_node_schema op_changed_reply_node_schemas[] = {\n+\tCTLV_NODE_SCHEMA_ROOT(1, 3, 3),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_OP_ID, 1, 1, U64_MAX),\n+\tCTLV_NODE_SCHEMA_BOOL(CTLV_ATTR_OP_DISABLED, 1),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_OP_STATE_GENERATION, 1, 0, U64_MAX),\n+};\n+\n+static const struct ctlv_node_schema event_overflow_reply_node_schemas[] = {\n+\tCTLV_NODE_SCHEMA_ROOT(1, 3, 3),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_EVENT_FIRST_SEQUENCE, 1, 0, U64_MAX),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_EVENT_LAST_SEQUENCE, 1, 0, U64_MAX),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_EVENT_DROPPED_COUNT, 1, 0, U64_MAX),\n+};\n+\n+static const struct ctlv_node_schema device_removed_reply_node_schemas[] = {\n+\tCTLV_NODE_SCHEMA_ROOT(0, 0, 0),\n+};\n+\n+static const struct ctlv_node_schema error_info_node_schemas[] = {\n+\tCTLV_NODE_SCHEMA_ROOT(1, 7, 0),\n+\tCTLV_NODE_SCHEMA_ENUM(CTLV_ATTR_ERROR_REASON, 1, 12),\n+\tCTLV_NODE_SCHEMA_STRING(CTLV_ATTR_ERROR_MESSAGE, 1, 0, 255),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_ERROR_BAD_ATTR_OFFSET, 1, 0, U64_MAX),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_ERROR_NEST_OFFSET, 1, 0, U64_MAX),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_ERROR_MISSING_ATTR_ID, 1, 0, U64_MAX),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_ERROR_EXPECTED_GENERATION, 1, 0, U64_MAX),\n+\tCTLV_NODE_SCHEMA_UINT(CTLV_ATTR_ERROR_CURRENT_GENERATION, 1, 0, U64_MAX),\n+};\n+\n+const struct ctlv_schema_tree ctlv_error_info_schema = {\n+\t.node_schemas = error_info_node_schemas,\n+\t.node_schemas_count =\n+\t\tARRAY_SIZE(error_info_node_schemas),\n+};\n+\n+static_assert(CTLV_ERROR_INFO_MAX_LEN \u003c= CTLV_MAX_ERROR_LEN);\n+\n+/* The ops this family declares, in declaration order. */\n+const struct ctlv_op_schema ctlv_op_schemas[] = {\n+\tCTLV_OP_SCHEMA_QUERY(CTLV_OP_FAMILIES_DUMP, CTLV_OP_FD_ACCESS_READ,\n+\t\t\t     CTLV_OP_AVAILABILITY_FIXED, 16, 112, 65536,\n+\t\t\t     CTLV_SCHEMA_TREE(families_dump_request),\n+\t\t\t     CTLV_SCHEMA_TREE(families_dump_reply)),\n+\tCTLV_OP_SCHEMA_QUERY(CTLV_OP_OPS_DUMP, CTLV_OP_FD_ACCESS_READ, CTLV_OP_AVAILABILITY_FIXED,\n+\t\t\t     16, 56, 65536, CTLV_SCHEMA_TREE(ops_dump_request),\n+\t\t\t     CTLV_SCHEMA_TREE(ops_dump_reply)),\n+\tCTLV_OP_SCHEMA_QUERY(CTLV_OP_OP_SCHEMA_GET, CTLV_OP_FD_ACCESS_READ,\n+\t\t\t     CTLV_OP_AVAILABILITY_FIXED, 40, 552, 65536,\n+\t\t\t     CTLV_SCHEMA_TREE(op_schema_get_request),\n+\t\t\t     CTLV_SCHEMA_TREE(op_schema_get_reply)),\n+\tCTLV_OP_SCHEMA_ACTION(CTLV_OP_SUBSCRIPTIONS_ADD, CTLV_OP_FD_ACCESS_READ,\n+\t\t\t      CTLV_OP_AVAILABILITY_FIXED, 6160, 0,\n+\t\t\t      CTLV_SCHEMA_TREE(subscriptions_add_request), CTLV_SCHEMA_TREE_NONE()),\n+\tCTLV_OP_SCHEMA_ACTION(CTLV_OP_SUBSCRIPTIONS_REMOVE, CTLV_OP_FD_ACCESS_READ,\n+\t\t\t      CTLV_OP_AVAILABILITY_FIXED, 6160, 0,\n+\t\t\t      CTLV_SCHEMA_TREE(subscriptions_remove_request),\n+\t\t\t      CTLV_SCHEMA_TREE_NONE()),\n+\tCTLV_OP_SCHEMA_QUERY(CTLV_OP_EVENT_QUEUE_GET, CTLV_OP_FD_ACCESS_READ,\n+\t\t\t     CTLV_OP_AVAILABILITY_FIXED, 16, 40, 65536,\n+\t\t\t     CTLV_SCHEMA_TREE(event_queue_get_request),\n+\t\t\t     CTLV_SCHEMA_TREE(event_queue_get_reply)),\n+\tCTLV_OP_SCHEMA_ACTION(CTLV_OP_EVENT_QUEUE_SET, CTLV_OP_FD_ACCESS_READ,\n+\t\t\t      CTLV_OP_AVAILABILITY_FIXED, 40, 0,\n+\t\t\t      CTLV_SCHEMA_TREE(event_queue_set_request), CTLV_SCHEMA_TREE_NONE()),\n+\tCTLV_OP_SCHEMA_EVENT(CTLV_OP_OP_CHANGED, 112, CTLV_SCHEMA_TREE(op_changed_reply)),\n+\tCTLV_OP_SCHEMA_EVENT(CTLV_OP_EVENT_OVERFLOW, 112, CTLV_SCHEMA_TREE(event_overflow_reply)),\n+\tCTLV_OP_SCHEMA_EVENT(CTLV_OP_DEVICE_REMOVED, 40, CTLV_SCHEMA_TREE(device_removed_reply)),\n+};\n+\n+/* The family ID is its position in the central registry. */\n+const struct ctlv_family_schema ctlv_schema = {\n+\t.name = \"ctlv\",\n+\t.family_id = 0,\n+\t.ops = ctlv_op_schemas,\n+\t.ops_count = ARRAY_SIZE(ctlv_op_schemas),\n+};\n+\n+/* Maximum uevent cost for this family chain. */\n+static_assert(60 \u003c= CTLV_UEVENT_MAX_LEN);\n+static_assert(3 \u003c= CTLV_UEVENT_MAX_VARS);\n+\n+/* Guards for generated maxima. */\n+static_assert(65536 \u003c= CTLV_MAX_INLINE_MESSAGE_LEN);\n+static_assert(112 \u003c= CTLV_MAX_EVENT_QUEUE_LEN);\n+static_assert(2 \u003c= CTLV_MAX_DECLARED_NEST_DEPTH);\n+\n+/* Local action and query bindings in declaration order. */\n+static const struct ctlv_op ctlv_ops[] = {\n+\tCTLV_OP_QUERY(ctlv_families_dump),\n+\tCTLV_OP_QUERY(ctlv_ops_dump),\n+\tCTLV_OP_QUERY(ctlv_op_schema_get),\n+\tCTLV_OP_ACTION(ctlv_subscriptions_add),\n+\tCTLV_OP_ACTION(ctlv_subscriptions_remove),\n+\tCTLV_OP_QUERY(ctlv_event_queue_get),\n+\tCTLV_OP_ACTION(ctlv_event_queue_set),\n+};\n+\n+/* Root-family descriptor used by the CTLV core. */\n+const struct ctlv_family ctlv_family = {\n+\t.schema = \u0026ctlv_schema,\n+\t.ops = ctlv_ops,\n+\t.ops_count = ARRAY_SIZE(ctlv_ops),\n+\t.pre = ctlv_op_pre,\n+\t.post = ctlv_op_post,\n+\t.priv_size = ctlv_priv_size,\n+\t.init = ctlv_init,\n+\t.fini = ctlv_fini,\n+};\n+EXPORT_SYMBOL_NS_GPL(ctlv_family, \"CTLV\");\ndiff --git a/drivers/ctlv/device.h b/drivers/ctlv/device.h\nnew file mode 100644\nindex 0000000000000..e51366d3fca10\n--- /dev/null\n+++ b/drivers/ctlv/device.h\n@@ -0,0 +1,55 @@\n+/* SPDX-License-Identifier: GPL-2.0-only */\n+#ifndef _CTLV_DEVICE_H\n+#define _CTLV_DEVICE_H\n+\n+#include \u003clinux/cdev.h\u003e\n+#include \u003clinux/device.h\u003e\n+#include \u003clinux/list.h\u003e\n+#include \u003clinux/rwsem.h\u003e\n+#include \u003clinux/spinlock.h\u003e\n+#include \u003clinux/types.h\u003e\n+#include \u003clinux/wait.h\u003e\n+\n+struct ctlv_event_record;\n+struct ctlv_family;\n+struct ctlv_family_priv;\n+struct ctlv_op_entry;\n+\n+struct ctlv_device {\n+\tstruct device dev;\n+\tstruct cdev cdev;\n+\n+\tstruct rw_semaphore registration_lock;\n+\tbool registered;\n+\tconst struct ctlv_family *family;\n+\tstruct ctlv_family_priv *privs;\n+\tu32 privs_count;\n+\tvoid *priv_block;\n+\n+\tstruct ctlv_op_entry *ops;\n+\tu32 ops_count;\n+\n+\t/* Op publication and state writers, never the dispatch path. */\n+\tspinlock_t transition_lock;\n+\tbool published;\n+\tbool destroying;\n+\tu64 state_generation;\n+\tu32 dynamic_ops_count;\n+\tunsigned long *disabled;\n+\n+\t/* Everything about the queues, and nothing family code runs under. */\n+\tspinlock_t events_lock;\n+\tstruct list_head files;\n+\tbool dead_announced;\n+\twait_queue_head_t event_context_wait;\n+\tu32 active_event_contexts;\n+\tbool events_live;\n+\tu32 events_count;\n+\tconst struct ctlv_op_entry *overflow_op;\n+\tconst struct ctlv_op_entry *removed_op;\n+\tu32 queue_min;\n+\tu32 queue_reserved;\n+\tu32 queue_default;\n+};\n+\n+#endif /* _CTLV_DEVICE_H */\ndiff --git a/drivers/ctlv/event.c b/drivers/ctlv/event.c\nnew file mode 100644\nindex 0000000000000..0f68d33e031c8\n--- /dev/null\n+++ b/drivers/ctlv/event.c\n@@ -0,0 +1,713 @@\n+// SPDX-License-Identifier: GPL-2.0-only\n+/*\n+ * Copyright (c) 2026, NVIDIA CORPORATION \u0026 AFFILIATES\n+ *\n+ * Per-open event queues and loss reporting.\n+ */\n+\n+#include \u003clinux/bitmap.h\u003e\n+#include \u003clinux/build_bug.h\u003e\n+#include \u003clinux/ctlv.h\u003e\n+#include \u003clinux/ctlv_gen.h\u003e\n+#include \u003clinux/err.h\u003e\n+#include \u003clinux/errno.h\u003e\n+#include \u003clinux/list.h\u003e\n+#include \u003clinux/minmax.h\u003e\n+#include \u003clinux/overflow.h\u003e\n+#include \u003clinux/poll.h\u003e\n+#include \u003clinux/sizes.h\u003e\n+#include \u003clinux/slab.h\u003e\n+#include \u003clinux/spinlock.h\u003e\n+#include \u003clinux/string.h\u003e\n+#include \u003clinux/uaccess.h\u003e\n+#include \u003clinux/wait.h\u003e\n+\n+#include \"builder.h\"\n+#include \"device.h\"\n+#include \"event.h\"\n+#include \"internal.h\"\n+#include \"message.h\"\n+#include \"schema.h\"\n+\n+/* Header and root form one naturally aligned copy range. */\n+static_assert(offsetof(struct ctlv_event_record, root) ==\n+\t      offsetof(struct ctlv_event_record, hdr) + sizeof(struct ctlv_event_hdr));\n+static_assert(sizeof(struct ctlv_event_hdr) % CTLV_ALIGNTO == 0);\n+\n+static u32 ctlv_event_len(const struct ctlv_op_entry *op)\n+{\n+\treturn op-\u003esizes.event_record_max_len;\n+}\n+\n+int ctlv_event_sizes(struct ctlv_device *ctlvdev)\n+{\n+\tu32 largest = 0;\n+\tu32 index;\n+\n+\tfor (index = 0; index \u003c ctlvdev-\u003eops_count; index++) {\n+\t\tconst struct ctlv_op_entry *op = \u0026ctlvdev-\u003eops[index];\n+\n+\t\tif (op-\u003eschema-\u003etype != CTLV_OP_TYPE_EVENT)\n+\t\t\tcontinue;\n+\t\tlargest = max(largest, ctlv_event_len(op));\n+\t\tif (op-\u003eschema-\u003eop_id == CTLV_OP_EVENT_OVERFLOW)\n+\t\t\tctlvdev-\u003eoverflow_op = op;\n+\t\telse if (op-\u003eschema-\u003eop_id == CTLV_OP_DEVICE_REMOVED)\n+\t\t\tctlvdev-\u003eremoved_op = op;\n+\t}\n+\t/* Every chain inherits the root, so every device has both of them. */\n+\tif (WARN_ON_ONCE(!ctlvdev-\u003eoverflow_op || !ctlvdev-\u003eremoved_op))\n+\t\treturn -EINVAL;\n+\n+\tctlvdev-\u003equeue_reserved =\n+\t\tctlv_event_len(ctlvdev-\u003eoverflow_op) + ctlv_event_len(ctlvdev-\u003eremoved_op);\n+\tctlvdev-\u003equeue_min = largest + ctlvdev-\u003equeue_reserved;\n+\tif (ctlvdev-\u003equeue_min \u003e CTLV_MAX_EVENT_QUEUE_LEN)\n+\t\treturn -EMSGSIZE;\n+\tctlvdev-\u003equeue_default =\n+\t\tclamp(max(SZ_256K, 4 * largest), ctlvdev-\u003equeue_min, CTLV_MAX_EVENT_QUEUE_LEN);\n+\treturn 0;\n+}\n+\n+void ctlv_event_device_init(struct ctlv_device *ctlvdev)\n+{\n+\tspin_lock_init(\u0026ctlvdev-\u003eevents_lock);\n+\tINIT_LIST_HEAD(\u0026ctlvdev-\u003efiles);\n+\tinit_waitqueue_head(\u0026ctlvdev-\u003eevent_context_wait);\n+}\n+\n+void ctlv_event_contexts_start(struct ctlv_device *ctlvdev)\n+{\n+\tguard(spinlock)\n+\t\t(\u0026ctlvdev-\u003eevents_lock);\n+\tif (WARN_ON_ONCE(ctlvdev-\u003eevents_live || ctlvdev-\u003eactive_event_contexts))\n+\t\treturn;\n+\tctlvdev-\u003eevents_live = true;\n+}\n+\n+void ctlv_event_contexts_stop(struct ctlv_device *ctlvdev)\n+{\n+\tguard(spinlock)\n+\t\t(\u0026ctlvdev-\u003eevents_lock);\n+\tctlvdev-\u003eevents_live = false;\n+}\n+\n+static bool ctlv_event_contexts_idle(struct ctlv_device *ctlvdev)\n+{\n+\tguard(spinlock)\n+\t\t(\u0026ctlvdev-\u003eevents_lock);\n+\treturn !ctlvdev-\u003eactive_event_contexts;\n+}\n+\n+void ctlv_event_contexts_wait(struct ctlv_device *ctlvdev)\n+{\n+\twait_event(ctlvdev-\u003eevent_context_wait, ctlv_event_contexts_idle(ctlvdev));\n+}\n+\n+/* @room bounds storage from the header through the root. */\n+static struct ctlv_event_record *ctlv_event_record_alloc(u32 room, gfp_t gfp)\n+{\n+\tstruct ctlv_event_record *rec;\n+\n+\trec = kmalloc(struct_size(rec, root, room - sizeof(rec-\u003ehdr)), gfp);\n+\tif (!rec)\n+\t\treturn NULL;\n+\tINIT_LIST_HEAD(\u0026rec-\u003enode);\n+\trec-\u003elen = 0;\n+\trec-\u003eroom = room;\n+\trec-\u003ereserved = false;\n+\treturn rec;\n+}\n+\n+/* Core events use root schemas and may outlive the device family. */\n+static void ctlv_event_record_build(struct ctlv_op_ctx *ctx, struct ctlv_event_record *rec,\n+\t\t\t\t    const struct ctlv_op_entry *op)\n+{\n+\tctx-\u003efamily = \u0026ctlv_family;\n+\tctx-\u003eop = op;\n+\tctlv_message_output_init(\u0026ctx-\u003eoutput, ctx, rec-\u003eroot, rec-\u003eroom - sizeof(rec-\u003ehdr),\n+\t\t\t\t \u0026op-\u003eschema-\u003ereply);\n+\tctlv_message_root(\u0026ctx-\u003eoutput_root, \u0026ctx-\u003eoutput);\n+\tctx-\u003edeepest = \u0026ctx-\u003eoutput_root;\n+}\n+\n+/* The padding is written rather than left as the allocation found it. */\n+static void ctlv_event_record_done(struct ctlv_op_ctx *ctx, struct ctlv_event_record *rec)\n+{\n+\tu32 root_len = ctx-\u003eoutput.root-\u003elen;\n+\n+\trec-\u003elen = sizeof(rec-\u003ehdr) + CTLV_ALIGN(root_len);\n+\trec-\u003ehdr.length = rec-\u003elen;\n+\tmemset(rec-\u003eroot + root_len, 0, rec-\u003elen - sizeof(rec-\u003ehdr) - root_len);\n+}\n+\n+static struct ctlv_event_record *ctlv_event_record_reserve(struct ctlv_device *ctlvdev,\n+\t\t\t\t\t\t\t   const struct ctlv_op_entry *op)\n+{\n+\tstruct ctlv_event_record *rec;\n+\n+\trec = ctlv_event_record_alloc(ctlv_event_len(op), GFP_KERNEL_ACCOUNT);\n+\tif (!rec)\n+\t\treturn NULL;\n+\trec-\u003ehdr.flags = 0;\n+\trec-\u003ehdr.op_id = op-\u003eschema-\u003eop_id;\n+\trec-\u003ereserved = true;\n+\treturn rec;\n+}\n+\n+int ctlv_event_file_init(struct ctlv_file *cfile)\n+{\n+\tstruct ctlv_device *ctlvdev = cfile-\u003ectlvdev;\n+\tstruct ctlv_op_ctx ctx = { .ctlvdev = ctlvdev };\n+\n+\tINIT_LIST_HEAD(\u0026cfile-\u003enode);\n+\tINIT_LIST_HEAD(\u0026cfile-\u003erecords);\n+\tinit_waitqueue_head(\u0026cfile-\u003ereaders);\n+\tmutex_init(\u0026cfile-\u003ereading);\n+\tcfile-\u003equeue_len = ctlvdev-\u003equeue_default;\n+\tcfile-\u003equeue_used = ctlvdev-\u003equeue_reserved;\n+\n+\tcfile-\u003esubscribed = bitmap_zalloc(ctlvdev-\u003eevents_count, GFP_KERNEL_ACCOUNT);\n+\tcfile-\u003eoverflow = ctlv_event_record_reserve(ctlvdev, ctlvdev-\u003eoverflow_op);\n+\tcfile-\u003eremoved = ctlv_event_record_reserve(ctlvdev, ctlvdev-\u003eremoved_op);\n+\tif (!cfile-\u003esubscribed || !cfile-\u003eoverflow || !cfile-\u003eremoved) {\n+\t\tctlv_event_file_exit(cfile);\n+\t\treturn -ENOMEM;\n+\t}\n+\tctlv_event_record_build(\u0026ctx, cfile-\u003eremoved, ctlvdev-\u003eremoved_op);\n+\tctlv_event_record_done(\u0026ctx, cfile-\u003eremoved);\n+\n+\tguard(spinlock)\n+\t\t(\u0026ctlvdev-\u003eevents_lock);\n+\tlist_add_tail(\u0026cfile-\u003enode, \u0026ctlvdev-\u003efiles);\n+\treturn 0;\n+}\n+\n+void ctlv_event_file_exit(struct ctlv_file *cfile)\n+{\n+\tstruct ctlv_event_record *rec, *next;\n+\n+\tscoped_guard(spinlock, \u0026cfile-\u003ectlvdev-\u003eevents_lock)\n+\t\tlist_del_init(\u0026cfile-\u003enode);\n+\n+\t/* Unreachable records are ours; reserved records free by identity. */\n+\tlist_for_each_entry_safe(rec, next, \u0026cfile-\u003erecords, node)\n+\t\tif (!rec-\u003ereserved)\n+\t\t\tkfree(rec);\n+\tkfree(cfile-\u003eoverflow);\n+\tkfree(cfile-\u003eremoved);\n+\tbitmap_free(cfile-\u003esubscribed);\n+\tmutex_destroy(\u0026cfile-\u003ereading);\n+}\n+\n+static void ctlv_event_queue_add(struct ctlv_file *cfile, struct ctlv_event_record *rec)\n+{\n+\tlist_add_tail(\u0026rec-\u003enode, \u0026cfile-\u003erecords);\n+\twake_up_interruptible(\u0026cfile-\u003ereaders);\n+}\n+\n+static void ctlv_event_queue_link(struct ctlv_file *cfile, struct ctlv_event_record *rec)\n+{\n+\trec-\u003ehdr.sequence = ++cfile-\u003esequence;\n+\tctlv_event_queue_add(cfile, rec);\n+}\n+\n+/* One reserved marker aggregates each contiguous drop epoch. */\n+static void ctlv_event_queue_dropped(struct ctlv_file *cfile, u64 sequence)\n+{\n+\tif (!cfile-\u003eoverflowing) {\n+\t\tcfile-\u003eoverflowing = true;\n+\t\tcfile-\u003efirst_dropped = sequence;\n+\t\tcfile-\u003edropped = 0;\n+\t\tif (!cfile-\u003ereading_overflow)\n+\t\t\tctlv_event_queue_add(cfile, cfile-\u003eoverflow);\n+\t}\n+\tcfile-\u003elast_dropped = sequence;\n+\tcfile-\u003edropped++;\n+}\n+\n+/* Delivered and dropped subscribed events both consume a sequence number. */\n+static void ctlv_event_queue_event(struct ctlv_file *cfile, const struct ctlv_op_entry *op,\n+\t\t\t\t   struct ctlv_event_record *rec)\n+{\n+\tu64 sequence;\n+\n+\tlockdep_assert_held(\u0026cfile-\u003ectlvdev-\u003eevents_lock);\n+\tif (!test_bit(op-\u003eevent_index, cfile-\u003esubscribed))\n+\t\treturn;\n+\tsequence = ++cfile-\u003esequence;\n+\tif (cfile-\u003eoverflowing || !rec || cfile-\u003equeue_used + rec-\u003elen \u003e cfile-\u003equeue_len) {\n+\t\tctlv_event_queue_dropped(cfile, sequence);\n+\t\treturn;\n+\t}\n+\tcfile-\u003equeue_used += rec-\u003elen;\n+\trec-\u003ehdr.sequence = sequence;\n+\tlist_move_tail(\u0026rec-\u003enode, \u0026cfile-\u003erecords);\n+\twake_up_interruptible(\u0026cfile-\u003ereaders);\n+}\n+\n+static void ctlv_event_free(struct ctlv_op_ctx *ctx);\n+\n+struct ctlv_op_ctx *ctlv_event_create(struct ctlv_device *ctlvdev, u64 op_id,\n+\t\t\t\t      struct ctlv_cursor **reply, gfp_t gfp)\n+{\n+\tconst struct ctlv_op_entry *op;\n+\tstruct ctlv_op_ctx *ctx;\n+\tvoid *out;\n+\tu32 room;\n+\tint ret;\n+\n+\tctx = kzalloc_obj(*ctx, gfp);\n+\tif (!ctx)\n+\t\treturn ERR_PTR(-ENOMEM);\n+\tscoped_guard(spinlock, \u0026ctlvdev-\u003eevents_lock) {\n+\t\tconst struct ctlv_family *family;\n+\n+\t\tif (!ctlvdev-\u003eevents_live) {\n+\t\t\tret = -ENODEV;\n+\t\t\tgoto err_free_ctx;\n+\t\t}\n+\t\tif (WARN_ON_ONCE(ctlvdev-\u003eactive_event_contexts == U32_MAX)) {\n+\t\t\tret = -EOVERFLOW;\n+\t\t\tgoto err_free_ctx;\n+\t\t}\n+\t\t/* Admission pins the op until emit or abort. */\n+\t\tfamily = READ_ONCE(ctlvdev-\u003efamily);\n+\t\tif (!family) {\n+\t\t\tret = -ENODEV;\n+\t\t\tgoto err_free_ctx;\n+\t\t}\n+\t\tget_device(\u0026ctlvdev-\u003edev);\n+\t\tctlvdev-\u003eactive_event_contexts++;\n+\t\tctx-\u003ectlvdev = ctlvdev;\n+\t\tctx-\u003efamily = family;\n+\t}\n+\n+\top = ctlv_op_find(ctlvdev, op_id);\n+\tif (WARN_ON_ONCE(!op) || WARN_ON_ONCE(op-\u003eschema-\u003etype != CTLV_OP_TYPE_EVENT)) {\n+\t\tret = -EINVAL;\n+\t\tgoto err_put_ctx;\n+\t}\n+\troom = ctlv_event_len(op) - sizeof(struct ctlv_event_hdr);\n+\tout = kmalloc(room, gfp);\n+\tif (!out) {\n+\t\tret = -ENOMEM;\n+\t\tgoto err_put_ctx;\n+\t}\n+\n+\tctx-\u003egfp = gfp;\n+\tctx-\u003eop = op;\n+\tctlv_message_output_init(\u0026ctx-\u003eoutput, ctx, out, room, \u0026op-\u003eschema-\u003ereply);\n+\tctlv_message_root(\u0026ctx-\u003eoutput_root, \u0026ctx-\u003eoutput);\n+\tctx-\u003edeepest = \u0026ctx-\u003eoutput_root;\n+\t*reply = \u0026ctx-\u003eoutput_root;\n+\treturn ctx;\n+\n+err_put_ctx:\n+\tctlv_event_free(ctx);\n+\treturn ERR_PTR(ret);\n+err_free_ctx:\n+\tkfree(ctx);\n+\treturn ERR_PTR(ret);\n+}\n+EXPORT_SYMBOL_NS_GPL(ctlv_event_create, \"CTLV\");\n+\n+static void ctlv_event_free(struct ctlv_op_ctx *ctx)\n+{\n+\tstruct ctlv_device *ctlvdev = ctx-\u003ectlvdev;\n+\tbool wake;\n+\n+\tkfree(ctx-\u003eoutput.root);\n+\tkfree(ctx);\n+\n+\tscoped_guard(spinlock, \u0026ctlvdev-\u003eevents_lock) {\n+\t\tif (WARN_ON_ONCE(!ctlvdev-\u003eactive_event_contexts))\n+\t\t\twake = true;\n+\t\telse\n+\t\t\twake = !--ctlvdev-\u003eactive_event_contexts;\n+\t}\n+\tif (wake)\n+\t\twake_up_all(\u0026ctlvdev-\u003eevent_context_wait);\n+\tput_device(\u0026ctlvdev-\u003edev);\n+}\n+\n+/* Reject an incomplete or schema-invalid family event before queueing. */\n+static int ctlv_event_finish(struct ctlv_op_ctx *ctx)\n+{\n+\tstruct ctlv_error refused = {};\n+\n+\t/* Whatever poisoned it has warned about it already. */\n+\tif (ctx-\u003eoutput.poison)\n+\t\treturn ctx-\u003eoutput.poison;\n+\tif (WARN_ON_ONCE(ctx-\u003edeepest != \u0026ctx-\u003eoutput_root)) {\n+\t\t/* A cursor of a frame that has returned is not followed. */\n+\t\tctx-\u003edeepest = \u0026ctx-\u003eoutput_root;\n+\t\treturn -EINVAL;\n+\t}\n+\tif (WARN_ON_ONCE(ctlv_schema_validate(\u0026ctx-\u003eoutput, \u0026refused)))\n+\t\treturn -EINVAL;\n+\treturn 0;\n+}\n+\n+/* Allocate subscriber records before taking queue spinlocks. */\n+static void ctlv_event_copies(struct ctlv_op_ctx *ctx, u32 len, struct list_head *spare, u32 wanted)\n+{\n+\tconst struct ctlv_attr *root = ctx-\u003eoutput.root;\n+\tstruct ctlv_event_record *rec;\n+\n+\twhile (wanted--) {\n+\t\trec = ctlv_event_record_alloc(len, ctx-\u003egfp);\n+\t\tif (!rec)\n+\t\t\treturn;\n+\t\trec-\u003elen = len;\n+\t\trec-\u003ehdr.length = len;\n+\t\trec-\u003ehdr.flags = 0;\n+\t\trec-\u003ehdr.op_id = ctx-\u003eop-\u003eschema-\u003eop_id;\n+\t\t/* Padded, since what is copied out is the whole record. */\n+\t\tmemcpy_and_pad(rec-\u003eroot, len - sizeof(rec-\u003ehdr), root, root-\u003elen, 0);\n+\t\tlist_add_tail(\u0026rec-\u003enode, spare);\n+\t}\n+}\n+\n+static void ctlv_event_deliver(struct ctlv_op_ctx *ctx, struct list_head *spare)\n+{\n+\tstruct ctlv_device *ctlvdev = ctx-\u003ectlvdev;\n+\tstruct ctlv_event_record *rec;\n+\tstruct ctlv_file *cfile;\n+\n+\tguard(spinlock)\n+\t\t(\u0026ctlvdev-\u003eevents_lock);\n+\tif (ctlvdev-\u003edead_announced)\n+\t\treturn;\n+\tlist_for_each_entry(cfile, \u0026ctlvdev-\u003efiles, node) {\n+\t\trec = list_first_entry_or_null(spare, struct ctlv_event_record, node);\n+\t\tctlv_event_queue_event(cfile, ctx-\u003eop, rec);\n+\t}\n+}\n+\n+int ctlv_event_emit(struct ctlv_op_ctx *ctx)\n+{\n+\tstruct ctlv_device *ctlvdev = ctx-\u003ectlvdev;\n+\tstruct ctlv_event_record *rec, *next;\n+\tstruct ctlv_file *cfile;\n+\tu32 len, wanted = 0;\n+\tLIST_HEAD(spare);\n+\tint ret;\n+\n+\tif (WARN_ON_ONCE(ctx-\u003efile))\n+\t\treturn -EINVAL;\n+\tret = ctlv_event_finish(ctx);\n+\tif (ret)\n+\t\tgoto out_free;\n+\n+\tlen = sizeof(struct ctlv_event_hdr) + CTLV_ALIGN(ctx-\u003eoutput.root-\u003elen);\n+\tscoped_guard(spinlock, \u0026ctlvdev-\u003eevents_lock) {\n+\t\tif (ctlvdev-\u003edead_announced)\n+\t\t\tgoto out_free;\n+\t\tlist_for_each_entry(cfile, \u0026ctlvdev-\u003efiles, node)\n+\t\t\tif (test_bit(ctx-\u003eop-\u003eevent_index, cfile-\u003esubscribed))\n+\t\t\t\twanted++;\n+\t}\n+\tif (wanted) {\n+\t\tctlv_event_copies(ctx, len, \u0026spare, wanted);\n+\t\tctlv_event_deliver(ctx, \u0026spare);\n+\t\tlist_for_each_entry_safe(rec, next, \u0026spare, node)\n+\t\t\tkfree(rec);\n+\t}\n+\n+out_free:\n+\tctlv_event_free(ctx);\n+\treturn ret;\n+}\n+EXPORT_SYMBOL_NS_GPL(ctlv_event_emit, \"CTLV\");\n+\n+void ctlv_event_abort(struct ctlv_op_ctx *ctx)\n+{\n+\tif (WARN_ON_ONCE(ctx-\u003efile))\n+\t\treturn;\n+\tctlv_event_free(ctx);\n+}\n+EXPORT_SYMBOL_NS_GPL(ctlv_event_abort, \"CTLV\");\n+\n+void ctlv_event_lost(struct ctlv_device *ctlvdev, u64 op_id)\n+{\n+\tconst struct ctlv_op_entry *op;\n+\tstruct ctlv_file *cfile;\n+\n+\tguard(spinlock)\n+\t\t(\u0026ctlvdev-\u003eevents_lock);\n+\tif (!ctlvdev-\u003eevents_live || ctlvdev-\u003edead_announced)\n+\t\treturn;\n+\top = ctlv_op_find(ctlvdev, op_id);\n+\tif (WARN_ON_ONCE(!op) || WARN_ON_ONCE(op-\u003eschema-\u003etype != CTLV_OP_TYPE_EVENT))\n+\t\treturn;\n+\tlist_for_each_entry(cfile, \u0026ctlvdev-\u003efiles, node)\n+\t\tctlv_event_queue_event(cfile, op, NULL);\n+}\n+EXPORT_SYMBOL_NS_GPL(ctlv_event_lost, \"CTLV\");\n+\n+void ctlv_event_op_changed(struct ctlv_device *ctlvdev, const struct ctlv_op_entry *op,\n+\t\t\t   bool disabled, u64 generation)\n+{\n+\tstruct ctlv_cursor *reply;\n+\tstruct ctlv_op_ctx *ctx;\n+\n+\tctx = ctlv_op_changed_create(ctlvdev, \u0026reply, GFP_NOWAIT);\n+\tif (IS_ERR(ctx)) {\n+\t\tctlv_event_lost(ctlvdev, CTLV_OP_OP_CHANGED);\n+\t\treturn;\n+\t}\n+\tctlv_op_id_put(reply, op-\u003eschema-\u003eop_id);\n+\tctlv_op_disabled_put(reply, disabled);\n+\tctlv_op_state_generation_put(reply, generation);\n+\tctlv_event_emit(ctx);\n+}\n+\n+void ctlv_event_device_dead(struct ctlv_device *ctlvdev)\n+{\n+\tstruct ctlv_file *cfile;\n+\n+\tguard(spinlock)\n+\t\t(\u0026ctlvdev-\u003eevents_lock);\n+\tif (WARN_ON_ONCE(ctlvdev-\u003edead_announced))\n+\t\treturn;\n+\tlist_for_each_entry(cfile, \u0026ctlvdev-\u003efiles, node)\n+\t\tctlv_event_queue_link(cfile, cfile-\u003eremoved);\n+\t/* Publish dead only after terminal records are queued. */\n+\tctlvdev-\u003edead_announced = true;\n+\tlist_for_each_entry(cfile, \u0026ctlvdev-\u003efiles, node)\n+\t\twake_up_interruptible(\u0026cfile-\u003ereaders);\n+}\n+\n+/* Materialize the final loss count when taking the marker. */\n+static void ctlv_event_overflow_fill(struct ctlv_file *cfile)\n+{\n+\tstruct ctlv_device *ctlvdev = cfile-\u003ectlvdev;\n+\tstruct ctlv_op_ctx ctx = { .ctlvdev = ctlvdev };\n+\tstruct ctlv_cursor *root;\n+\n+\tctlv_event_record_build(\u0026ctx, cfile-\u003eoverflow, ctlvdev-\u003eoverflow_op);\n+\tcfile-\u003eoverflow-\u003ehdr.sequence = cfile-\u003efirst_dropped;\n+\troot = \u0026ctx.output_root;\n+\tctlv_event_first_sequence_put(root, cfile-\u003efirst_dropped);\n+\tctlv_event_last_sequence_put(root, cfile-\u003elast_dropped);\n+\tctlv_event_dropped_count_put(root, cfile-\u003edropped);\n+\t/* Reserved storage is the most this event can be, so it all fits. */\n+\tWARN_ON_ONCE(ctx.output.poison);\n+\tctlv_event_record_done(\u0026ctx, cfile-\u003eoverflow);\n+\n+\tcfile-\u003ereading_overflow = true;\n+\tcfile-\u003eoverflowing = false;\n+\tcfile-\u003efirst_reported = cfile-\u003efirst_dropped;\n+\tcfile-\u003elast_reported = cfile-\u003elast_dropped;\n+\tcfile-\u003edropped_reported = cfile-\u003edropped;\n+\tcfile-\u003edropped = 0;\n+}\n+\n+static struct ctlv_event_record *ctlv_event_queue_take(struct ctlv_file *cfile)\n+{\n+\tstruct ctlv_event_record *rec;\n+\n+\tguard(spinlock)\n+\t\t(\u0026cfile-\u003ectlvdev-\u003eevents_lock);\n+\trec = list_first_entry_or_null(\u0026cfile-\u003erecords, struct ctlv_event_record, node);\n+\tif (!rec)\n+\t\treturn NULL;\n+\tlist_del_init(\u0026rec-\u003enode);\n+\tif (rec == cfile-\u003eoverflow)\n+\t\tctlv_event_overflow_fill(cfile);\n+\telse if (!rec-\u003ereserved)\n+\t\tcfile-\u003equeue_used -= rec-\u003elen;\n+\treturn rec;\n+}\n+\n+/* Restore an undelivered record, merging an overflow marker's epoch. */\n+static void ctlv_event_queue_untake(struct ctlv_file *cfile, struct ctlv_event_record *rec)\n+{\n+\tguard(spinlock)\n+\t\t(\u0026cfile-\u003ectlvdev-\u003eevents_lock);\n+\tif (rec == cfile-\u003eoverflow) {\n+\t\tcfile-\u003ereading_overflow = false;\n+\t\tcfile-\u003efirst_dropped = cfile-\u003efirst_reported;\n+\t\tif (!cfile-\u003eoverflowing)\n+\t\t\tcfile-\u003elast_dropped = cfile-\u003elast_reported;\n+\t\tcfile-\u003edropped += cfile-\u003edropped_reported;\n+\t\tcfile-\u003eoverflowing = true;\n+\t} else if (!rec-\u003ereserved) {\n+\t\tcfile-\u003equeue_used += rec-\u003elen;\n+\t}\n+\tlist_add(\u0026rec-\u003enode, \u0026cfile-\u003erecords);\n+}\n+\n+/* Requeue a marker if another loss epoch opened while it was out. */\n+static void ctlv_event_queue_consumed(struct ctlv_file *cfile, struct ctlv_event_record *rec)\n+{\n+\tif (rec == cfile-\u003eoverflow) {\n+\t\tguard(spinlock)\n+\t\t\t(\u0026cfile-\u003ectlvdev-\u003eevents_lock);\n+\t\tcfile-\u003ereading_overflow = false;\n+\t\tif (cfile-\u003eoverflowing)\n+\t\t\tctlv_event_queue_add(cfile, rec);\n+\t\treturn;\n+\t}\n+\tif (!rec-\u003ereserved)\n+\t\tkfree(rec);\n+}\n+\n+static bool ctlv_event_waiting(struct ctlv_file *cfile)\n+{\n+\tstruct ctlv_device *ctlvdev = cfile-\u003ectlvdev;\n+\n+\tguard(spinlock)\n+\t\t(\u0026ctlvdev-\u003eevents_lock);\n+\treturn !list_empty(\u0026cfile-\u003erecords) || ctlvdev-\u003edead_announced;\n+}\n+\n+ssize_t ctlv_event_file_read(struct ctlv_file *cfile, char __user *buf, size_t len, bool blocking)\n+{\n+\tstruct ctlv_device *ctlvdev = cfile-\u003ectlvdev;\n+\tstruct ctlv_event_record *rec;\n+\tssize_t ret;\n+\n+\t/* dup() and SCM_RIGHTS share one serialized queue. */\n+\tif (mutex_lock_interruptible(\u0026cfile-\u003ereading))\n+\t\treturn -ERESTARTSYS;\n+\n+\twhile (!(rec = ctlv_event_queue_take(cfile))) {\n+\t\t/* Drained, and the device is gone. */\n+\t\tif (READ_ONCE(ctlvdev-\u003edead_announced)) {\n+\t\t\tret = -ENODEV;\n+\t\t\tgoto out_unlock;\n+\t\t}\n+\t\tif (!blocking) {\n+\t\t\tret = -EAGAIN;\n+\t\t\tgoto out_unlock;\n+\t\t}\n+\t\tret = wait_event_interruptible(cfile-\u003ereaders, ctlv_event_waiting(cfile));\n+\t\tif (ret) {\n+\t\t\tret = -ERESTARTSYS;\n+\t\t\tgoto out_unlock;\n+\t\t}\n+\t}\n+\n+\tif (rec-\u003elen \u003e len) {\n+\t\tctlv_event_queue_untake(cfile, rec);\n+\t\tret = -EMSGSIZE;\n+\t\tgoto out_unlock;\n+\t}\n+\tif (copy_to_user(buf, \u0026rec-\u003ehdr, rec-\u003elen)) {\n+\t\tctlv_event_queue_untake(cfile, rec);\n+\t\tret = -EFAULT;\n+\t\tgoto out_unlock;\n+\t}\n+\tret = rec-\u003elen;\n+\tctlv_event_queue_consumed(cfile, rec);\n+\n+out_unlock:\n+\tmutex_unlock(\u0026cfile-\u003ereading);\n+\treturn ret;\n+}\n+\n+__poll_t ctlv_event_file_poll(struct ctlv_file *cfile, struct file *filp,\n+\t\t\t      struct poll_table_struct *wait)\n+{\n+\tstruct ctlv_device *ctlvdev = cfile-\u003ectlvdev;\n+\t__poll_t mask = 0;\n+\n+\tpoll_wait(filp, \u0026cfile-\u003ereaders, wait);\n+\n+\tguard(spinlock)\n+\t\t(\u0026ctlvdev-\u003eevents_lock);\n+\tif (!list_empty(\u0026cfile-\u003erecords))\n+\t\tmask |= EPOLLIN | EPOLLRDNORM;\n+\t/* Which a reader sees beside what it has not drained yet. */\n+\tif (ctlvdev-\u003edead_announced)\n+\t\tmask |= EPOLLHUP;\n+\treturn mask;\n+}\n+\n+/* Validate every ID before changing any subscription. */\n+static const struct ctlv_op_entry *ctlv_event_subscription_find(struct ctlv_device *ctlvdev,\n+\t\t\t\t\t\t\t\tu64 op_id)\n+{\n+\tconst struct ctlv_op_entry *op = ctlv_op_find(ctlvdev, op_id);\n+\n+\treturn op \u0026\u0026 op-\u003eschema-\u003etype == CTLV_OP_TYPE_EVENT ? op : NULL;\n+}\n+\n+static int ctlv_event_subscriptions_set(struct ctlv_op_ctx *ctx, const struct ctlv_cursor *request,\n+\t\t\t\t\tstruct ctlv_input_ref ref, bool subscribe)\n+{\n+\tstruct ctlv_device *ctlvdev = ctx-\u003ectlvdev;\n+\tstruct ctlv_cursor attr;\n+\n+\tfor (ctlv_input_attr(\u0026attr, request, ref); ctlv_attr_ok(\u0026attr); ctlv_attr_next(\u0026attr)) {\n+\t\tu64 op_id = ctlv_attr_u64(\u0026attr);\n+\n+\t\tif (!ctlv_event_subscription_find(ctlvdev, op_id))\n+\t\t\treturn ctlv_op_errorf(ctx, -EOPNOTSUPP,\n+\t\t\t\t\t      \"op %#llx is not an event this device emits\",\n+\t\t\t\t\t      (unsigned long long)op_id);\n+\t}\n+\n+\tguard(spinlock)\n+\t\t(\u0026ctlvdev-\u003eevents_lock);\n+\tfor (ctlv_input_attr(\u0026attr, request, ref); ctlv_attr_ok(\u0026attr); ctlv_attr_next(\u0026attr)) {\n+\t\tu64 op_id = ctlv_attr_u64(\u0026attr);\n+\t\tconst struct ctlv_op_entry *op = ctlv_event_subscription_find(ctlvdev, op_id);\n+\n+\t\tif (subscribe)\n+\t\t\tset_bit(op-\u003eevent_index, ctx-\u003efile-\u003esubscribed);\n+\t\telse\n+\t\t\tclear_bit(op-\u003eevent_index, ctx-\u003efile-\u003esubscribed);\n+\t}\n+\treturn 0;\n+}\n+\n+int ctlv_subscriptions_add_action(void *priv, struct ctlv_op_ctx *ctx,\n+\t\t\t\t  const struct ctlv_cursor *request, struct ctlv_cursor *reply)\n+{\n+\treturn ctlv_event_subscriptions_set(ctx, request, ctlv_subscriptions_add_event_op_id_ref(),\n+\t\t\t\t\t    true);\n+}\n+\n+int ctlv_subscriptions_remove_action(void *priv, struct ctlv_op_ctx *ctx,\n+\t\t\t\t     const struct ctlv_cursor *request, struct ctlv_cursor *reply)\n+{\n+\treturn ctlv_event_subscriptions_set(ctx, request,\n+\t\t\t\t\t    ctlv_subscriptions_remove_event_op_id_ref(), false);\n+}\n+\n+int ctlv_event_queue_get_query(void *priv, struct ctlv_op_ctx *ctx,\n+\t\t\t       const struct ctlv_cursor *request, struct ctlv_cursor *reply)\n+{\n+\tstruct ctlv_file *cfile = ctx-\u003efile;\n+\n+\tscoped_guard(spinlock, \u0026ctx-\u003ectlvdev-\u003eevents_lock) {\n+\t\tctlv_event_queue_len_put(reply, cfile-\u003equeue_len);\n+\t\tctlv_event_queue_used_put(reply, cfile-\u003equeue_used);\n+\t}\n+\t/* One state, whole, so there is never a second fragment of it. */\n+\treturn ctlv_op_query_done(ctx, 0);\n+}\n+\n+/* Resizing never discards queued records or reserved capacity. */\n+int ctlv_event_queue_set_action(void *priv, struct ctlv_op_ctx *ctx,\n+\t\t\t\tconst struct ctlv_cursor *request, struct ctlv_cursor *reply)\n+{\n+\tstruct ctlv_device *ctlvdev = ctx-\u003ectlvdev;\n+\tu64 len = ctlv_event_queue_set_event_queue_len_get(request);\n+\n+\tif (len \u003c ctlvdev-\u003equeue_min || len \u003e CTLV_MAX_EVENT_QUEUE_LEN)\n+\t\treturn ctlv_op_errorf(ctx, -EINVAL, \"event queue length %llu is outside %u..%u\",\n+\t\t\t\t      (unsigned long long)len, ctlvdev-\u003equeue_min,\n+\t\t\t\t      CTLV_MAX_EVENT_QUEUE_LEN);\n+\n+\tguard(spinlock)\n+\t\t(\u0026ctlvdev-\u003eevents_lock);\n+\tif (len \u003c ctx-\u003efile-\u003equeue_used)\n+\t\treturn ctlv_op_error(ctx, -EBUSY,\n+\t\t\t\t     \"event queue contains more data than the requested limit\");\n+\tctx-\u003efile-\u003equeue_len = len;\n+\treturn 0;\n+}\ndiff --git a/drivers/ctlv/event.h b/drivers/ctlv/event.h\nnew file mode 100644\nindex 0000000000000..80898c7700347\n--- /dev/null\n+++ b/drivers/ctlv/event.h\n@@ -0,0 +1,69 @@\n+/* SPDX-License-Identifier: GPL-2.0-only */\n+#ifndef _CTLV_EVENT_H\n+#define _CTLV_EVENT_H\n+\n+#include \u003clinux/gfp_types.h\u003e\n+#include \u003clinux/list.h\u003e\n+#include \u003clinux/mutex.h\u003e\n+#include \u003clinux/poll.h\u003e\n+#include \u003clinux/types.h\u003e\n+#include \u003clinux/wait.h\u003e\n+\n+#include \u003cuapi/linux/ctlv.h\u003e\n+\n+struct ctlv_device;\n+struct ctlv_op_entry;\n+struct file;\n+struct poll_table_struct;\n+\n+struct ctlv_event_record {\n+\tstruct list_head node;\n+\tu32 len;\n+\tu32 room;\n+\tbool reserved;\n+\tstruct ctlv_event_hdr hdr;\n+\tu8 root[] __aligned(8);\n+};\n+\n+struct ctlv_file {\n+\tstruct ctlv_device *ctlvdev;\n+\tstruct list_head node;\n+\n+\tstruct list_head records;\n+\tu32 queue_len;\n+\tu32 queue_used;\n+\tu64 sequence;\n+\tunsigned long *subscribed;\n+\tstruct ctlv_event_record *overflow;\n+\tstruct ctlv_event_record *removed;\n+\tbool overflowing;\n+\tu64 first_dropped;\n+\tu64 last_dropped;\n+\tu64 dropped;\n+\tbool reading_overflow;\n+\tu64 first_reported;\n+\tu64 last_reported;\n+\tu64 dropped_reported;\n+\n+\twait_queue_head_t readers;\n+\t/* One reader of this description at a time, however many hold it. */\n+\tstruct mutex reading;\n+};\n+\n+int ctlv_event_sizes(struct ctlv_device *ctlvdev);\n+void ctlv_event_device_init(struct ctlv_device *ctlvdev);\n+void ctlv_event_contexts_start(struct ctlv_device *ctlvdev);\n+void ctlv_event_contexts_stop(struct ctlv_device *ctlvdev);\n+void ctlv_event_contexts_wait(struct ctlv_device *ctlvdev);\n+void ctlv_event_device_dead(struct ctlv_device *ctlvdev);\n+int ctlv_event_file_init(struct ctlv_file *cfile);\n+void ctlv_event_file_exit(struct ctlv_file *cfile);\n+ssize_t ctlv_event_file_read(struct ctlv_file *cfile, char __user *buf,\n+\t\t\t     size_t len, bool blocking);\n+__poll_t ctlv_event_file_poll(struct ctlv_file *cfile, struct file *filp,\n+\t\t\t      struct poll_table_struct *wait);\n+void ctlv_event_op_changed(struct ctlv_device *ctlvdev,\n+\t\t\t   const struct ctlv_op_entry *op, bool disabled,\n+\t\t\t   u64 generation);\n+\n+#endif /* _CTLV_EVENT_H */\ndiff --git a/drivers/ctlv/internal.h b/drivers/ctlv/internal.h\nnew file mode 100644\nindex 0000000000000..7e6ec9d1f73e1\n--- /dev/null\n+++ b/drivers/ctlv/internal.h\n@@ -0,0 +1,81 @@\n+/* SPDX-License-Identifier: GPL-2.0-only */\n+/*\n+ * Copyright (c) 2026, NVIDIA CORPORATION \u0026 AFFILIATES\n+ *\n+ * CTLV core internals.\n+ */\n+#ifndef _CTLV_INTERNAL_H\n+#define _CTLV_INTERNAL_H\n+\n+#include \u003clinux/ctlv_family.h\u003e\n+#include \u003clinux/list.h\u003e\n+#include \u003clinux/types.h\u003e\n+\n+#include \u003cuapi/linux/ctlv.h\u003e\n+\n+#include \"message.h\"\n+\n+struct task_struct;\n+struct ctlv_file;\n+\n+#define CTLV_ERROR_MESSAGE_LEN 256\n+\n+/* An op that is always enabled has no per-device availability state. */\n+#define CTLV_OP_STATE_NONE U32_MAX\n+\n+struct ctlv_op_entry {\n+\tconst struct ctlv_op_schema *schema;\n+\tconst struct ctlv_op *binding;\n+\tvoid *priv;\n+\tstruct ctlv_op_sizes sizes;\n+\tu32 state_index;\n+\tbool absent;\n+\tu32 event_index;\n+};\n+\n+struct ctlv_error {\n+\tu32 reason;\n+\tchar message[CTLV_ERROR_MESSAGE_LEN];\n+\tu32 bad_attr_offset;\n+\tu32 nest_offset;\n+\tu64 missing_attr_id;\n+\tu64 expected_generation;\n+\tu64 current_generation;\n+};\n+\n+struct ctlv_query_fragment {\n+\tu64 generation;\n+\tu64 cursor;\n+\tu64 reported;\n+\tu64 next_cursor;\n+\tbool progress;\n+\tbool answered;\n+\tint result;\n+};\n+\n+struct ctlv_op_ctx {\n+\tstruct ctlv_device *ctlvdev;\n+\tconst struct ctlv_family *family;\n+\tstruct ctlv_file *file;\n+\t/* Compared against current and never followed: identity, not a hold. */\n+\tconst struct task_struct *submitter;\n+\tgfp_t gfp;\n+\tconst struct ctlv_op_entry *op;\n+\n+\tstruct ctlv_msg request;\n+\tstruct ctlv_cursor request_root;\n+\n+\tstruct ctlv_msg output;\n+\tstruct ctlv_cursor output_root;\n+\tstruct ctlv_cursor *deepest;\n+\n+\tstruct ctlv_query_fragment frag;\n+\tstruct list_head blobs;\n+\tbool blobs_live;\n+\tint blob_error;\n+\tstruct ctlv_error error;\n+};\n+\n+struct ctlv_op_entry *ctlv_op_find(struct ctlv_device *ctlvdev, u64 op_id);\n+\n+#endif /* _CTLV_INTERNAL_H */\ndiff --git a/drivers/ctlv/introspection.c b/drivers/ctlv/introspection.c\nnew file mode 100644\nindex 0000000000000..7460dfa6d6618\n--- /dev/null\n+++ b/drivers/ctlv/introspection.c\n@@ -0,0 +1,512 @@\n+// SPDX-License-Identifier: GPL-2.0-only\n+/*\n+ * Copyright (c) 2026, NVIDIA CORPORATION \u0026 AFFILIATES\n+ *\n+ * Root-family discovery queries and their fragmentation.\n+ */\n+\n+#include \u003clinux/bitmap.h\u003e\n+#include \u003clinux/bits.h\u003e\n+#include \u003clinux/cleanup.h\u003e\n+#include \u003clinux/ctlv.h\u003e\n+#include \u003clinux/ctlv_gen.h\u003e\n+#include \u003clinux/errno.h\u003e\n+#include \u003clinux/slab.h\u003e\n+#include \u003clinux/spinlock.h\u003e\n+#include \u003clinux/types.h\u003e\n+\n+#include \"device.h\"\n+#include \"internal.h\"\n+#include \"schema.h\"\n+\n+/* A cursor packs the record and member where fragmentation resumes. */\n+#define CTLV_INTROSPECTION_MEMBER_SHIFT 48\n+#define CTLV_INTROSPECTION_RECORD_MASK GENMASK_ULL(CTLV_INTROSPECTION_MEMBER_SHIFT - 1, 0)\n+\n+struct ctlv_introspection_dump_position {\n+\tu64 record;\n+\tu32 member;\n+};\n+\n+static void ctlv_introspection_dump_resume(struct ctlv_introspection_dump_position *pos, u64 cursor)\n+{\n+\tpos-\u003erecord = cursor \u0026 CTLV_INTROSPECTION_RECORD_MASK;\n+\tpos-\u003emember = cursor \u003e\u003e CTLV_INTROSPECTION_MEMBER_SHIFT;\n+}\n+\n+static u64 ctlv_introspection_dump_cursor(const struct ctlv_introspection_dump_position *pos)\n+{\n+\treturn pos-\u003erecord | (u64)pos-\u003emember \u003c\u003c CTLV_INTROSPECTION_MEMBER_SHIFT;\n+}\n+\n+/* The immutable root-first chain always has generation zero. */\n+static bool ctlv_introspection_family_record(struct ctlv_cursor *reply, struct ctlv_cursor *entry,\n+\t\t\t\t\t     const struct ctlv_family *family,\n+\t\t\t\t\t     struct ctlv_introspection_dump_position *pos)\n+{\n+\tconst struct ctlv_family_schema *schema = family-\u003eschema;\n+\n+\tif (!ctlv_family_entry_start(reply, entry))\n+\t\treturn false;\n+\tif (pos-\u003emember == 0) {\n+\t\tif (!ctlv_family_id_put(entry, schema-\u003efamily_id))\n+\t\t\treturn false;\n+\t\tpos-\u003emember = 1;\n+\t}\n+\tif (pos-\u003emember == 1) {\n+\t\tif (!ctlv_family_name_put(entry, schema-\u003ename))\n+\t\t\treturn false;\n+\t\tpos-\u003emember = 2;\n+\t}\n+\tctlv_nest_end(entry);\n+\tpos-\u003emember = 0;\n+\treturn true;\n+}\n+\n+int ctlv_families_dump_query(void *priv, struct ctlv_op_ctx *ctx, const struct ctlv_cursor *request,\n+\t\t\t     struct ctlv_cursor *reply)\n+{\n+\tconst struct ctlv_family *family = ctx-\u003efamily;\n+\tu32 levels = ctlv_family_levels(family);\n+\tstruct ctlv_cursor entry;\n+\tstruct ctlv_introspection_dump_position pos;\n+\n+\tctlv_introspection_dump_resume(\u0026pos, ctlv_op_query_cursor(ctx));\n+\tfor (; pos.record \u003c levels; pos.record++) {\n+\t\tconst struct ctlv_family *ancestor =\n+\t\t\tctlv_family_ancestor(family, levels - 1 - pos.record);\n+\n+\t\tif (!ctlv_introspection_family_record(reply, \u0026entry, ancestor, \u0026pos))\n+\t\t\treturn ctlv_op_query_more(ctx, 0, ctlv_introspection_dump_cursor(\u0026pos));\n+\t}\n+\treturn ctlv_op_query_done(ctx, 0);\n+}\n+\n+/* Snapshot published-op state and generation once per fragment. */\n+struct ctlv_op_snapshot {\n+\tunsigned long *disabled;\n+\tu64 generation;\n+};\n+\n+static int ctlv_introspection_snapshot_take(struct ctlv_device *ctlvdev,\n+\t\t\t\t\t    struct ctlv_op_snapshot *snapshot)\n+{\n+\tif (ctlvdev-\u003edynamic_ops_count) {\n+\t\tsnapshot-\u003edisabled = bitmap_zalloc(ctlvdev-\u003edynamic_ops_count, GFP_KERNEL);\n+\t\tif (!snapshot-\u003edisabled)\n+\t\t\treturn -ENOMEM;\n+\t}\n+\tguard(spinlock)\n+\t\t(\u0026ctlvdev-\u003etransition_lock);\n+\tsnapshot-\u003egeneration = ctlvdev-\u003estate_generation;\n+\tif (snapshot-\u003edisabled)\n+\t\tbitmap_copy(snapshot-\u003edisabled, ctlvdev-\u003edisabled, ctlvdev-\u003edynamic_ops_count);\n+\treturn 0;\n+}\n+\n+static bool ctlv_introspection_op_disabled(const struct ctlv_op_snapshot *snapshot,\n+\t\t\t\t\t   const struct ctlv_op_entry *op)\n+{\n+\tif (op-\u003estate_index == CTLV_OP_STATE_NONE)\n+\t\treturn false;\n+\treturn test_bit(op-\u003estate_index, snapshot-\u003edisabled);\n+}\n+\n+/* Report effective lengths, including descendant fills. */\n+enum ctlv_introspection_op_field {\n+\tCTLV_INTROSPECTION_OP_FIELD_ID,\n+\tCTLV_INTROSPECTION_OP_FIELD_TYPE,\n+\tCTLV_INTROSPECTION_OP_FIELD_AVAILABILITY,\n+\tCTLV_INTROSPECTION_OP_FIELD_DISABLED,\n+\tCTLV_INTROSPECTION_OP_FIELD_REQUEST_MAX_LEN,\n+\tCTLV_INTROSPECTION_OP_FIELD_ACTION_REPLY_MAX_LEN,\n+\tCTLV_INTROSPECTION_OP_FIELD_QUERY_REPLY_MIN_LEN,\n+\tCTLV_INTROSPECTION_OP_FIELD_QUERY_REPLY_SUGGESTED_LEN,\n+\tCTLV_INTROSPECTION_OP_FIELD_EVENT_RECORD_MAX_LEN,\n+\tCTLV_INTROSPECTION_OP_FIELD_FD_ACCESS,\n+\tCTLV_INTROSPECTION_OP_FIELD_END,\n+};\n+\n+static bool ctlv_introspection_op_field_put(struct ctlv_cursor *entry,\n+\t\t\t\t\t    const struct ctlv_op_snapshot *snapshot,\n+\t\t\t\t\t    const struct ctlv_op_entry *op, u32 member)\n+{\n+\tconst struct ctlv_op_sizes *sizes = \u0026op-\u003esizes;\n+\n+\tswitch (member) {\n+\tcase CTLV_INTROSPECTION_OP_FIELD_ID:\n+\t\treturn ctlv_op_id_put(entry, op-\u003eschema-\u003eop_id);\n+\tcase CTLV_INTROSPECTION_OP_FIELD_TYPE:\n+\t\treturn ctlv_op_type_put(entry, op-\u003eschema-\u003etype);\n+\tcase CTLV_INTROSPECTION_OP_FIELD_AVAILABILITY:\n+\t\treturn ctlv_op_availability_put(entry, op-\u003eschema-\u003eavailability);\n+\tcase CTLV_INTROSPECTION_OP_FIELD_DISABLED:\n+\t\treturn ctlv_op_disabled_put(entry, ctlv_introspection_op_disabled(snapshot, op));\n+\tcase CTLV_INTROSPECTION_OP_FIELD_REQUEST_MAX_LEN:\n+\t\treturn ctlv_op_request_max_len_put(entry, sizes-\u003erequest_max_len);\n+\tcase CTLV_INTROSPECTION_OP_FIELD_ACTION_REPLY_MAX_LEN:\n+\t\t/* Zero is a reply that acknowledges and no more. */\n+\t\treturn ctlv_op_action_reply_max_len_put(entry, sizes-\u003eaction_reply_max_len);\n+\tcase CTLV_INTROSPECTION_OP_FIELD_QUERY_REPLY_MIN_LEN:\n+\t\treturn ctlv_op_query_reply_min_len_put(entry, sizes-\u003equery_reply_min_len);\n+\tcase CTLV_INTROSPECTION_OP_FIELD_QUERY_REPLY_SUGGESTED_LEN:\n+\t\treturn ctlv_op_query_reply_suggested_len_put(entry,\n+\t\t\t\t\t\t\t     sizes-\u003equery_reply_suggested_len);\n+\tcase CTLV_INTROSPECTION_OP_FIELD_FD_ACCESS:\n+\t\treturn ctlv_op_fd_access_put(entry, op-\u003eschema-\u003efd_access);\n+\tdefault:\n+\t\treturn ctlv_op_event_record_max_len_put(entry, sizes-\u003eevent_record_max_len);\n+\t}\n+}\n+\n+static bool ctlv_introspection_op_field_applies(const struct ctlv_op_entry *op, u32 member)\n+{\n+\tswitch (member) {\n+\tcase CTLV_INTROSPECTION_OP_FIELD_ID:\n+\tcase CTLV_INTROSPECTION_OP_FIELD_TYPE:\n+\t\treturn true;\n+\tcase CTLV_INTROSPECTION_OP_FIELD_AVAILABILITY:\n+\tcase CTLV_INTROSPECTION_OP_FIELD_DISABLED:\n+\tcase CTLV_INTROSPECTION_OP_FIELD_REQUEST_MAX_LEN:\n+\tcase CTLV_INTROSPECTION_OP_FIELD_FD_ACCESS:\n+\t\treturn op-\u003eschema-\u003etype != CTLV_OP_TYPE_EVENT;\n+\tcase CTLV_INTROSPECTION_OP_FIELD_ACTION_REPLY_MAX_LEN:\n+\t\treturn op-\u003eschema-\u003etype == CTLV_OP_TYPE_ACTION;\n+\tcase CTLV_INTROSPECTION_OP_FIELD_EVENT_RECORD_MAX_LEN:\n+\t\treturn op-\u003eschema-\u003etype == CTLV_OP_TYPE_EVENT;\n+\tdefault:\n+\t\treturn op-\u003eschema-\u003etype == CTLV_OP_TYPE_QUERY;\n+\t}\n+}\n+\n+static bool ctlv_introspection_op_record(struct ctlv_cursor *reply, struct ctlv_cursor *entry,\n+\t\t\t\t\t const struct ctlv_op_snapshot *snapshot,\n+\t\t\t\t\t const struct ctlv_op_entry *op,\n+\t\t\t\t\t struct ctlv_introspection_dump_position *pos)\n+{\n+\tif (!ctlv_op_entry_start(reply, entry))\n+\t\treturn false;\n+\tfor (; pos-\u003emember \u003c CTLV_INTROSPECTION_OP_FIELD_END; pos-\u003emember++) {\n+\t\tif (!ctlv_introspection_op_field_applies(op, pos-\u003emember))\n+\t\t\tcontinue;\n+\t\tif (!ctlv_introspection_op_field_put(entry, snapshot, op, pos-\u003emember))\n+\t\t\treturn false;\n+\t}\n+\tctlv_nest_end(entry);\n+\tpos-\u003emember = 0;\n+\treturn true;\n+}\n+\n+int ctlv_ops_dump_query(void *priv, struct ctlv_op_ctx *ctx, const struct ctlv_cursor *request,\n+\t\t\tstruct ctlv_cursor *reply)\n+{\n+\tstruct ctlv_device *ctlvdev = ctx-\u003ectlvdev;\n+\tstruct ctlv_op_snapshot snapshot = {};\n+\tstruct ctlv_cursor entry;\n+\tstruct ctlv_introspection_dump_position pos;\n+\tint ret;\n+\n+\tret = ctlv_introspection_snapshot_take(ctlvdev, \u0026snapshot);\n+\tif (ret)\n+\t\treturn ret;\n+\tunsigned long *disabled __free(bitmap) = snapshot.disabled;\n+\n+\t/* The published index is immutable, so a cursor into it holds. */\n+\tctlv_introspection_dump_resume(\u0026pos, ctlv_op_query_cursor(ctx));\n+\tfor (; pos.record \u003c ctlvdev-\u003eops_count; pos.record++)\n+\t\tif (!ctlv_introspection_op_record(reply, \u0026entry, \u0026snapshot,\n+\t\t\t\t\t\t  \u0026ctlvdev-\u003eops[pos.record], \u0026pos))\n+\t\t\treturn ctlv_op_query_more(ctx, snapshot.generation,\n+\t\t\t\t\t\t  ctlv_introspection_dump_cursor(\u0026pos));\n+\treturn ctlv_op_query_done(ctx, snapshot.generation);\n+}\n+\n+/* A leaf-count cursor permits a fragment boundary at any tree depth. */\n+\n+/* One nest of the description: the placement of one node of the schema. */\n+struct ctlv_introspection_frame {\n+\tstruct ctlv_cursor nest;\n+\tu64 attr_id;\n+\tbool open;\n+\t/* Which node this stands for, so that a re-entry can be measured. */\n+\tconst struct ctlv_schema_tree *tree;\n+\tu32 node;\n+};\n+\n+/* The frames outlive the walk, a fragment's open nests having to stay alive. */\n+struct ctlv_introspection_walk {\n+\tconst struct ctlv_family *family;\n+\tstruct ctlv_cursor *root;\n+\tstruct ctlv_introspection_frame *frames;\n+\tu64 ordinal;\n+\tu64 resume;\n+\tint error;\n+};\n+\n+/* One member of one node, which is every leaf this reply has. */\n+struct ctlv_introspection_field {\n+\tu64 attr_id;\n+\tu8 kind;\n+\tu64 value;\n+};\n+\n+/* Three every node has, the widest bounds, a unit, a scale, a re-entry. */\n+#define CTLV_INTROSPECTION_MAX_FIELDS 10\n+\n+struct ctlv_introspection_fields {\n+\tstruct ctlv_introspection_field fields[CTLV_INTROSPECTION_MAX_FIELDS];\n+\tu32 fields_count;\n+};\n+\n+static void ctlv_introspection_field(struct ctlv_introspection_fields *fields, u64 attr_id, u8 kind,\n+\t\t\t\t     u64 value)\n+{\n+\tif (WARN_ON_ONCE(fields-\u003efields_count == CTLV_INTROSPECTION_MAX_FIELDS))\n+\t\treturn;\n+\tfields-\u003efields[fields-\u003efields_count++] = (struct ctlv_introspection_field){\n+\t\t.attr_id = attr_id,\n+\t\t.kind = kind,\n+\t\t.value = value,\n+\t};\n+}\n+\n+static void ctlv_introspection_uint(struct ctlv_introspection_fields *fields, u64 attr_id,\n+\t\t\t\t    u64 value)\n+{\n+\tctlv_introspection_field(fields, attr_id, CTLV_SCHEMA_UINT, value);\n+}\n+\n+/* Emit only constraints for this node's payload kind. */\n+static void ctlv_introspection_node_fields(struct ctlv_introspection_fields *fields,\n+\t\t\t\t\t   const struct ctlv_node_schema *node, u32 reenters)\n+{\n+\tctlv_introspection_uint(fields, CTLV_ATTR_SCHEMA_ATTR_ID, node-\u003eattr_id);\n+\tctlv_introspection_uint(fields, CTLV_ATTR_SCHEMA_KIND, node-\u003ekind);\n+\tctlv_introspection_uint(fields, CTLV_ATTR_SCHEMA_MAX_OCCURRENCES, node-\u003emax_occurrences);\n+\n+\tswitch (node-\u003ekind) {\n+\tcase CTLV_SCHEMA_UINT:\n+\tcase CTLV_SCHEMA_SINT:\n+\tcase CTLV_SCHEMA_ENUM:\n+\t\tctlv_introspection_uint(fields, CTLV_ATTR_SCHEMA_MIN, node-\u003erange.min);\n+\t\tctlv_introspection_uint(fields, CTLV_ATTR_SCHEMA_MAX, node-\u003erange.max);\n+\t\tbreak;\n+\tcase CTLV_SCHEMA_FLAGS:\n+\t\tctlv_introspection_uint(fields, CTLV_ATTR_SCHEMA_FLAGS_MASK, node-\u003eflags_mask);\n+\t\tbreak;\n+\tcase CTLV_SCHEMA_STRING:\n+\tcase CTLV_SCHEMA_BINARY:\n+\t\tctlv_introspection_uint(fields, CTLV_ATTR_SCHEMA_MIN_LENGTH, node-\u003elength.min_len);\n+\t\tctlv_introspection_uint(fields, CTLV_ATTR_SCHEMA_MAX_LENGTH, node-\u003elength.max_len);\n+\t\tbreak;\n+\tcase CTLV_SCHEMA_BLOB:\n+\t\tctlv_introspection_field(fields, CTLV_ATTR_SCHEMA_BLOB_DIRECTION, CTLV_SCHEMA_ENUM,\n+\t\t\t\t\t node-\u003eblob.direction);\n+\t\tctlv_introspection_uint(fields, CTLV_ATTR_SCHEMA_BLOB_BACKINGS,\n+\t\t\t\t\tnode-\u003eblob.backings);\n+\t\tctlv_introspection_uint(fields, CTLV_ATTR_SCHEMA_BLOB_MAX_LENGTH,\n+\t\t\t\t\tnode-\u003eblob.max_len);\n+\t\tctlv_introspection_uint(fields, CTLV_ATTR_SCHEMA_BLOB_ALIGNMENT,\n+\t\t\t\t\tnode-\u003eblob.alignment);\n+\t\tbreak;\n+\tdefault:\n+\t\tbreak;\n+\t}\n+\n+\tif (node-\u003eunit != CTLV_UNIT_NONE) {\n+\t\tctlv_introspection_uint(fields, CTLV_ATTR_SCHEMA_UNIT, node-\u003eunit);\n+\t\tctlv_introspection_field(fields, CTLV_ATTR_SCHEMA_SCALE, CTLV_SCHEMA_SINT,\n+\t\t\t\t\t node-\u003escale);\n+\t}\n+\tif (reenters)\n+\t\tctlv_introspection_uint(fields, CTLV_ATTR_SCHEMA_REENTERS, reenters);\n+}\n+\n+/* A nest is opened by the first thing written inside it. */\n+static bool ctlv_introspection_open(struct ctlv_introspection_walk *walk, u32 depth)\n+{\n+\tstruct ctlv_introspection_frame *frame = \u0026walk-\u003eframes[depth];\n+\tstruct ctlv_cursor *up = walk-\u003eroot;\n+\n+\tif (frame-\u003eopen)\n+\t\treturn true;\n+\tif (depth) {\n+\t\tif (!ctlv_introspection_open(walk, depth - 1))\n+\t\t\treturn false;\n+\t\tup = \u0026walk-\u003eframes[depth - 1].nest;\n+\t}\n+\tif (!ctlv_nest_start(up, \u0026frame-\u003enest, frame-\u003eattr_id, CTLV_SCHEMA_NEST))\n+\t\treturn false;\n+\tframe-\u003eopen = true;\n+\treturn true;\n+}\n+\n+/* Skipped leaves advance the ordinal; a failed write remains the resume point. */\n+static bool ctlv_introspection_put(struct ctlv_introspection_walk *walk, u32 depth,\n+\t\t\t\t   const struct ctlv_introspection_field *field)\n+{\n+\tstruct ctlv_cursor *nest = \u0026walk-\u003eframes[depth].nest;\n+\tbool ok;\n+\n+\tif (walk-\u003eordinal \u003c walk-\u003eresume) {\n+\t\twalk-\u003eordinal++;\n+\t\treturn true;\n+\t}\n+\tif (!ctlv_introspection_open(walk, depth))\n+\t\treturn false;\n+\tif (field-\u003ekind == CTLV_SCHEMA_SINT)\n+\t\tok = ctlv_put_s64(nest, field-\u003eattr_id, field-\u003ekind, field-\u003evalue);\n+\telse\n+\t\tok = ctlv_put_u64(nest, field-\u003eattr_id, field-\u003ekind, field-\u003evalue);\n+\tif (!ok)\n+\t\treturn false;\n+\twalk-\u003eordinal++;\n+\treturn true;\n+}\n+\n+/* Re-entry targets an ancestor with the same child range. */\n+static u32 ctlv_introspection_reenters(struct ctlv_introspection_walk *walk, u32 depth,\n+\t\t\t\t       const struct ctlv_schema_tree *tree,\n+\t\t\t\t       const struct ctlv_node_schema *node)\n+{\n+\tu32 levels;\n+\n+\tfor (levels = 1; levels \u003c= depth; levels++) {\n+\t\tconst struct ctlv_introspection_frame *up = \u0026walk-\u003eframes[depth - levels];\n+\n+\t\tif (up-\u003etree == tree \u0026\u0026\n+\t\t    tree-\u003enode_schemas[up-\u003enode].first_child == node-\u003efirst_child)\n+\t\t\treturn levels;\n+\t}\n+\t/* A back edge to nothing is metadata this core cannot describe. */\n+\tWARN_ON_ONCE(1);\n+\twalk-\u003eerror = -EINVAL;\n+\treturn 0;\n+}\n+\n+static bool ctlv_introspection_node(struct ctlv_introspection_walk *walk, u32 depth,\n+\t\t\t\t    const struct ctlv_schema_tree *tree, u32 index);\n+\n+/* Filled stub members inherit the stub placement's optionality. */\n+static bool ctlv_introspection_children(struct ctlv_introspection_walk *walk, u32 depth,\n+\t\t\t\t\tconst struct ctlv_schema_tree *tree, u32 index,\n+\t\t\t\t\tbool force_optional)\n+{\n+\tconst struct ctlv_node_schema *node = \u0026tree-\u003enode_schemas[index];\n+\tu32 i;\n+\n+\tif (WARN_ON_ONCE(depth + 1 \u003e= CTLV_MAX_NEST_DEPTH)) {\n+\t\t/* Deeper than a specification may declare, so unreachable. */\n+\t\twalk-\u003eerror = -EINVAL;\n+\t\treturn false;\n+\t}\n+\tfor (i = 0; i \u003c node-\u003echildren_count; i++) {\n+\t\tu32 child = node-\u003efirst_child + i;\n+\t\tbool required = !force_optional \u0026\u0026 i \u003c node-\u003erequired_children_count;\n+\n+\t\twalk-\u003eframes[depth + 1] = (struct ctlv_introspection_frame){\n+\t\t\t.attr_id = required ? CTLV_ATTR_SCHEMA_ATTRS :\n+\t\t\t\t\t      CTLV_ATTR_SCHEMA_OPTIONAL_ATTRS,\n+\t\t\t.tree = tree,\n+\t\t\t.node = child,\n+\t\t};\n+\t\tif (!ctlv_introspection_node(walk, depth + 1, tree, child))\n+\t\t\treturn false;\n+\t}\n+\tfor (i = 0; i \u003c tree-\u003estub_schemas_count; i++) {\n+\t\tconst struct ctlv_stub_schema *stub_schema = \u0026tree-\u003estub_schemas[i];\n+\t\tconst struct ctlv_stub_fill_schema *fill_schema;\n+\n+\t\tif (stub_schema-\u003enode != index)\n+\t\t\tcontinue;\n+\t\tfill_schema =\n+\t\t\tctlv_schema_fill(walk-\u003efamily, stub_schema-\u003efamily_id, stub_schema-\u003eset_id);\n+\t\t/* Nothing of this chain filled it, so it contributes none. */\n+\t\tif (!fill_schema)\n+\t\t\tcontinue;\n+\t\t/* A fill schema's root is the stub, its children the members. */\n+\t\tif (!ctlv_introspection_children(walk, depth, \u0026fill_schema-\u003emembers, 0,\n+\t\t\t\t\t\t force_optional || stub_schema-\u003eoptional))\n+\t\t\treturn false;\n+\t}\n+\treturn true;\n+}\n+\n+/* One node, into the nest that stands for it. */\n+static bool ctlv_introspection_node(struct ctlv_introspection_walk *walk, u32 depth,\n+\t\t\t\t    const struct ctlv_schema_tree *tree, u32 index)\n+{\n+\tconst struct ctlv_node_schema *node = \u0026tree-\u003enode_schemas[index];\n+\tstruct ctlv_introspection_fields fields = {};\n+\tu32 reenters = 0;\n+\tu32 i;\n+\n+\tif (node-\u003ereenters) {\n+\t\treenters = ctlv_introspection_reenters(walk, depth, tree, node);\n+\t\tif (!reenters)\n+\t\t\treturn false;\n+\t}\n+\tctlv_introspection_node_fields(\u0026fields, node, reenters);\n+\tfor (i = 0; i \u003c fields.fields_count; i++)\n+\t\tif (!ctlv_introspection_put(walk, depth, \u0026fields.fields[i]))\n+\t\t\treturn false;\n+\t/*\n+\t * A node that re-enters a level says so instead of listing that level's\n+\t * members again, which is what makes an unbounded nesting describable.\n+\t */\n+\tif (!node-\u003ereenters \u0026\u0026 !ctlv_introspection_children(walk, depth, tree, index, false))\n+\t\treturn false;\n+\tif (walk-\u003eframes[depth].open)\n+\t\tctlv_nest_end(\u0026walk-\u003eframes[depth].nest);\n+\treturn true;\n+}\n+\n+/* One of the two messages of an op, the root of it being a node like any. */\n+static bool ctlv_introspection_message(struct ctlv_introspection_walk *walk, u64 attr_id,\n+\t\t\t\t       const struct ctlv_schema_tree *tree)\n+{\n+\t/* An op without such a message has nothing to describe. */\n+\tif (!tree-\u003enode_schemas)\n+\t\treturn true;\n+\twalk-\u003eframes[0] = (struct ctlv_introspection_frame){\n+\t\t.attr_id = attr_id,\n+\t\t.tree = tree,\n+\t};\n+\treturn ctlv_introspection_node(walk, 0, tree, 0);\n+}\n+\n+int ctlv_op_schema_get_query(void *priv, struct ctlv_op_ctx *ctx, const struct ctlv_cursor *request,\n+\t\t\t     struct ctlv_cursor *reply)\n+{\n+\tstruct ctlv_introspection_walk walk = {\n+\t\t.family = ctx-\u003efamily,\n+\t\t.root = reply,\n+\t\t.resume = ctlv_op_query_cursor(ctx),\n+\t};\n+\tconst struct ctlv_op_entry *op;\n+\n+\t/* Describe published ops regardless of current dynamic state. */\n+\top = ctlv_op_find(ctx-\u003ectlvdev, ctlv_op_schema_get_op_id_get(request));\n+\tif (!op)\n+\t\treturn -EOPNOTSUPP;\n+\n+\t/*\n+\t * One frame per level the reply may nest, too many for the stack: a\n+\t * description is one level deeper than the message it describes.\n+\t */\n+\tstruct ctlv_introspection_frame *frames __free(kfree) =\n+\t\tkcalloc(CTLV_MAX_NEST_DEPTH, sizeof(*frames), GFP_KERNEL);\n+\n+\tif (!frames)\n+\t\treturn -ENOMEM;\n+\twalk.frames = frames;\n+\n+\tif (!ctlv_introspection_message(\u0026walk, CTLV_ATTR_SCHEMA_REQUEST, \u0026op-\u003eschema-\u003erequest) ||\n+\t    !ctlv_introspection_message(\u0026walk, CTLV_ATTR_SCHEMA_REPLY, \u0026op-\u003eschema-\u003ereply)) {\n+\t\tif (walk.error)\n+\t\t\treturn walk.error;\n+\t\t/* A schema is immutable, so there is nothing to be stale. */\n+\t\treturn ctlv_op_query_more(ctx, 0, walk.ordinal);\n+\t}\n+\treturn ctlv_op_query_done(ctx, 0);\n+}\ndiff --git a/drivers/ctlv/message.c b/drivers/ctlv/message.c\nnew file mode 100644\nindex 0000000000000..7e5742ba8f708\n--- /dev/null\n+++ b/drivers/ctlv/message.c\n@@ -0,0 +1,403 @@\n+// SPDX-License-Identifier: GPL-2.0-only\n+/*\n+ * Copyright (c) 2026, NVIDIA CORPORATION \u0026 AFFILIATES\n+ *\n+ * Message walking, indexing, and generated-accessor primitives.\n+ */\n+#include \u003clinux/align.h\u003e\n+#include \u003clinux/bits.h\u003e\n+#include \u003clinux/bug.h\u003e\n+#include \u003clinux/ctlv.h\u003e\n+#include \u003clinux/err.h\u003e\n+#include \u003clinux/errno.h\u003e\n+#include \u003clinux/export.h\u003e\n+#include \u003clinux/string.h\u003e\n+#include \u003clinux/types.h\u003e\n+\n+#include \u003cuapi/linux/ctlv.h\u003e\n+#include \u003cuapi/linux/ctlv_gen.h\u003e\n+\n+#include \"internal.h\"\n+#include \"message.h\"\n+\n+enum ctlv_message_step ctlv_message_next(const struct ctlv_attr *nest,\n+\t\t\t\t\t const struct ctlv_attr **child)\n+{\n+\tconst u8 *end = (const u8 *)nest + nest-\u003elen;\n+\tconst u8 *next;\n+\tsize_t room;\n+\n+\tif (nest-\u003elen \u003c sizeof(*nest))\n+\t\treturn CTLV_MESSAGE_STEP_BAD;\n+\tif (*child)\n+\t\tnext = (const u8 *)*child + ALIGN((size_t)(*child)-\u003elen, CTLV_ALIGNTO);\n+\telse\n+\t\tnext = (const u8 *)(nest + 1);\n+\tif (next \u003e= end)\n+\t\treturn next == end ? CTLV_MESSAGE_STEP_END : CTLV_MESSAGE_STEP_BAD;\n+\n+\troom = end - next;\n+\tif (room \u003c sizeof(**child))\n+\t\treturn CTLV_MESSAGE_STEP_BAD;\n+\t*child = (const struct ctlv_attr *)next;\n+\t/*\n+\t * Length before alignment, so that aligning a length this nest could\n+\t * never hold is not what overflows.\n+\t */\n+\tif ((*child)-\u003elen \u003c sizeof(**child) || (*child)-\u003elen \u003e room)\n+\t\treturn CTLV_MESSAGE_STEP_BAD;\n+\tif (ALIGN((size_t)(*child)-\u003elen, CTLV_ALIGNTO) \u003e room)\n+\t\treturn CTLV_MESSAGE_STEP_BAD;\n+\treturn CTLV_MESSAGE_STEP_ATTR;\n+}\n+\n+u32 ctlv_message_offset(const struct ctlv_msg *msg, const struct ctlv_attr *attr)\n+{\n+\treturn (const u8 *)attr - (const u8 *)msg-\u003eroot;\n+}\n+\n+void ctlv_message_root(struct ctlv_cursor *cursor, struct ctlv_msg *msg)\n+{\n+\t*cursor = (struct ctlv_cursor){\n+\t\t.msg = msg,\n+\t\t.attr = msg-\u003eroot,\n+\t\t.tree = msg-\u003etree,\n+\t\t.index_nest_scope = CTLV_MESSAGE_INPUT_INDEX_NONE,\n+\t\t.index_scope = CTLV_MESSAGE_INPUT_INDEX_NONE,\n+\t};\n+\tif (msg-\u003erequest \u0026\u0026 msg-\u003eindex)\n+\t\tcursor-\u003eindex_nest_scope = msg-\u003eindex-\u003enests[0].first_scope;\n+}\n+\n+static bool ctlv_message_nest_index_ok(const struct ctlv_cursor *nest)\n+{\n+\tconst struct ctlv_message_input_index *index = nest-\u003emsg-\u003eindex;\n+\tconst struct ctlv_message_input_nest *indexed;\n+\tconst struct ctlv_message_input_scope *scope;\n+\tconst struct ctlv_attr *attr;\n+\n+\tif (WARN_ON_ONCE(!nest-\u003emsg-\u003erequest || !index ||\n+\t\t\t nest-\u003eindex_nest_scope \u003e= index-\u003escopes_count))\n+\t\treturn false;\n+\tscope = \u0026index-\u003escopes[nest-\u003eindex_nest_scope];\n+\tif (WARN_ON_ONCE(scope-\u003enest \u003e= index-\u003enests_count))\n+\t\treturn false;\n+\tindexed = \u0026index-\u003enests[scope-\u003enest];\n+\tattr = (const void *)((const u8 *)nest-\u003emsg-\u003eroot + indexed-\u003eoffset);\n+\tif (WARN_ON_ONCE(attr != nest-\u003eattr))\n+\t\treturn false;\n+\treturn !WARN_ON_ONCE(scope-\u003etree != nest-\u003etree || scope-\u003enode != nest-\u003enode);\n+}\n+\n+static bool ctlv_message_input_scope_ok(const struct ctlv_message_input_index *index,\n+\t\t\t\t\tconst struct ctlv_message_input_scope *scope)\n+{\n+\treturn !WARN_ON_ONCE(scope-\u003efirst_slot \u003e index-\u003eslots_count ||\n+\t\t\t     scope-\u003eslots_count \u003e index-\u003eslots_count - scope-\u003efirst_slot);\n+}\n+\n+static const struct ctlv_node_schema *ctlv_message_input_ref_node(struct ctlv_input_ref ref)\n+{\n+\tconst struct ctlv_node_schema *parent;\n+\tconst struct ctlv_node_schema *node;\n+\n+\tif (WARN_ON_ONCE(!ref.tree-\u003enode_schemas || ref.node \u003e= ref.tree-\u003enode_schemas_count))\n+\t\treturn NULL;\n+\tparent = \u0026ref.tree-\u003enode_schemas[ref.node];\n+\tif (WARN_ON_ONCE(ref.slot \u003e= parent-\u003echildren_count ||\n+\t\t\t parent-\u003efirst_child + ref.slot \u003e= ref.tree-\u003enode_schemas_count))\n+\t\treturn NULL;\n+\tnode = \u0026ref.tree-\u003enode_schemas[parent-\u003efirst_child + ref.slot];\n+\tif (WARN_ON_ONCE(node-\u003eattr_id != ref.attr_id || node-\u003ekind != ref.kind))\n+\t\treturn NULL;\n+\treturn node;\n+}\n+\n+static const struct ctlv_message_input_slot *\n+ctlv_message_cursor_index(const struct ctlv_cursor *cursor)\n+{\n+\tconst struct ctlv_message_input_index *index;\n+\tconst struct ctlv_message_input_scope *scope;\n+\tconst struct ctlv_node_schema *parent;\n+\tconst struct ctlv_node_schema *node;\n+\tconst struct ctlv_message_input_slot *slot;\n+\tconst struct ctlv_message_input_nest *nest;\n+\tu32 local_slot;\n+\tu32 offset;\n+\n+\tif (WARN_ON_ONCE(!cursor-\u003emsg || !cursor-\u003etree || !cursor-\u003emsg-\u003erequest ||\n+\t\t\t !cursor-\u003emsg-\u003eindex))\n+\t\treturn NULL;\n+\tindex = cursor-\u003emsg-\u003eindex;\n+\tif (WARN_ON_ONCE(cursor-\u003eindex_scope \u003e= index-\u003escopes_count))\n+\t\treturn NULL;\n+\tscope = \u0026index-\u003escopes[cursor-\u003eindex_scope];\n+\tif (!ctlv_message_input_scope_ok(index, scope))\n+\t\treturn NULL;\n+\tparent = \u0026scope-\u003etree-\u003enode_schemas[scope-\u003enode];\n+\tif (WARN_ON_ONCE(scope-\u003etree != cursor-\u003etree || cursor-\u003enode \u003c parent-\u003efirst_child ||\n+\t\t\t cursor-\u003enode \u003e= parent-\u003efirst_child + scope-\u003eslots_count))\n+\t\treturn NULL;\n+\tlocal_slot = cursor-\u003enode - parent-\u003efirst_child;\n+\tnode = \u0026cursor-\u003etree-\u003enode_schemas[cursor-\u003enode];\n+\tslot = \u0026index-\u003eslots[scope-\u003efirst_slot + local_slot];\n+\tif (!cursor-\u003eattr)\n+\t\treturn slot;\n+\tif (WARN_ON_ONCE(cursor-\u003eattr-\u003eattr_id != node-\u003eattr_id))\n+\t\treturn NULL;\n+\tif (WARN_ON_ONCE(scope-\u003enest \u003e= index-\u003enests_count))\n+\t\treturn NULL;\n+\tnest = \u0026index-\u003enests[scope-\u003enest];\n+\tif (WARN_ON_ONCE(cursor-\u003eparent !=\n+\t\t\t (const void *)((const u8 *)cursor-\u003emsg-\u003eroot + nest-\u003eoffset)))\n+\t\treturn NULL;\n+\toffset = ctlv_message_offset(cursor-\u003emsg, cursor-\u003eattr);\n+\tif (WARN_ON_ONCE(offset \u003c slot-\u003efirst_offset || offset \u003e= slot-\u003eend_offset ||\n+\t\t\t offset + ALIGN((size_t)cursor-\u003eattr-\u003elen, CTLV_ALIGNTO) \u003e\n+\t\t\t\t slot-\u003eend_offset))\n+\t\treturn NULL;\n+\tif (node-\u003ekind == CTLV_SCHEMA_NEST) {\n+\t\tconst struct ctlv_message_input_scope *nest_scope;\n+\n+\t\tif (WARN_ON_ONCE(cursor-\u003eindex_nest_scope \u003e= index-\u003escopes_count))\n+\t\t\treturn NULL;\n+\t\tnest_scope = \u0026index-\u003escopes[cursor-\u003eindex_nest_scope];\n+\t\tif (WARN_ON_ONCE(nest_scope-\u003enest \u003e= index-\u003enests_count ||\n+\t\t\t\t index-\u003enests[nest_scope-\u003enest].offset != offset ||\n+\t\t\t\t nest_scope-\u003etree != cursor-\u003etree ||\n+\t\t\t\t nest_scope-\u003enode != cursor-\u003enode))\n+\t\t\treturn NULL;\n+\t} else if (WARN_ON_ONCE(cursor-\u003eindex_nest_scope != CTLV_MESSAGE_INPUT_INDEX_NONE)) {\n+\t\treturn NULL;\n+\t}\n+\treturn slot;\n+}\n+\n+bool ctlv_message_input_rebind(struct ctlv_cursor *nest, const struct ctlv_schema_tree *tree,\n+\t\t\t       u32 node)\n+{\n+\tconst struct ctlv_message_input_scope *bound_scope;\n+\tconst struct ctlv_message_input_nest *indexed;\n+\tu32 i;\n+\n+\tif (WARN_ON_ONCE(!nest-\u003eattr || !nest-\u003emsg || !nest-\u003emsg-\u003eindex))\n+\t\treturn false;\n+\tif (!ctlv_message_nest_index_ok(nest))\n+\t\treturn false;\n+\tbound_scope = \u0026nest-\u003emsg-\u003eindex-\u003escopes[nest-\u003eindex_nest_scope];\n+\tindexed = \u0026nest-\u003emsg-\u003eindex-\u003enests[bound_scope-\u003enest];\n+\tfor (i = 0; i \u003c indexed-\u003escopes_count; i++) {\n+\t\tu32 scope_index = indexed-\u003efirst_scope + i;\n+\t\tconst struct ctlv_message_input_scope *scope =\n+\t\t\t\u0026nest-\u003emsg-\u003eindex-\u003escopes[scope_index];\n+\n+\t\tif (scope-\u003etree != tree || scope-\u003enode != node)\n+\t\t\tcontinue;\n+\t\tnest-\u003etree = tree;\n+\t\tnest-\u003enode = node;\n+\t\tnest-\u003eindex_nest_scope = scope_index;\n+\t\treturn true;\n+\t}\n+\treturn false;\n+}\n+\n+struct ctlv_cursor *ctlv_input_attr(struct ctlv_cursor *cursor, const struct ctlv_cursor *nest,\n+\t\t\t\t    struct ctlv_input_ref ref)\n+{\n+\tconst struct ctlv_message_input_index *index;\n+\tconst struct ctlv_message_input_scope *scope;\n+\tconst struct ctlv_message_input_slot *indexed;\n+\tconst struct ctlv_node_schema *schema;\n+\n+\t*cursor = (struct ctlv_cursor){\n+\t\t.index_nest_scope = CTLV_MESSAGE_INPUT_INDEX_NONE,\n+\t\t.index_scope = CTLV_MESSAGE_INPUT_INDEX_NONE,\n+\t};\n+\tif (WARN_ON_ONCE(!nest-\u003eattr || !nest-\u003emsg))\n+\t\treturn cursor;\n+\tif (!ctlv_message_nest_index_ok(nest))\n+\t\treturn cursor;\n+\tindex = nest-\u003emsg-\u003eindex;\n+\tif (WARN_ON_ONCE(nest-\u003eindex_nest_scope \u003e= index-\u003escopes_count))\n+\t\treturn cursor;\n+\tscope = \u0026index-\u003escopes[nest-\u003eindex_nest_scope];\n+\tif (!ctlv_message_input_scope_ok(index, scope))\n+\t\treturn cursor;\n+\tif (WARN_ON_ONCE(scope-\u003etree != ref.tree || scope-\u003enode != ref.node ||\n+\t\t\t nest-\u003etree != ref.tree || nest-\u003enode != ref.node ||\n+\t\t\t ref.slot \u003e= scope-\u003eslots_count))\n+\t\treturn cursor;\n+\tschema = ctlv_message_input_ref_node(ref);\n+\tif (!schema)\n+\t\treturn cursor;\n+\tindexed = \u0026index-\u003eslots[scope-\u003efirst_slot + ref.slot];\n+\t*cursor = (struct ctlv_cursor){\n+\t\t.msg = nest-\u003emsg,\n+\t\t.parent = nest-\u003eattr,\n+\t\t.attr = indexed-\u003ecount ? (const void *)((const u8 *)nest-\u003emsg-\u003eroot +\n+\t\t\t\t\t\t\tindexed-\u003efirst_offset) :\n+\t\t\t\t\t NULL,\n+\t\t.tree = ref.tree,\n+\t\t.node = ref.tree-\u003enode_schemas[ref.node].first_child + ref.slot,\n+\t\t.depth = nest-\u003edepth + 1,\n+\t\t.index_nest_scope = CTLV_MESSAGE_INPUT_INDEX_NONE,\n+\t\t.index_scope = nest-\u003eindex_nest_scope,\n+\t};\n+\tif (indexed-\u003ecount \u0026\u0026 schema-\u003ekind == CTLV_SCHEMA_NEST) {\n+\t\tif (WARN_ON_ONCE(indexed-\u003efirst_nest \u003e= index-\u003enests_count))\n+\t\t\treturn cursor;\n+\t\tcursor-\u003eindex_nest_scope = index-\u003enests[indexed-\u003efirst_nest].first_scope;\n+\t}\n+\treturn cursor;\n+}\n+EXPORT_SYMBOL_NS_GPL(ctlv_input_attr, \"CTLV\");\n+\n+bool ctlv_input_cursor(const struct ctlv_cursor *cursor, struct ctlv_input_ref ref)\n+{\n+\tconst struct ctlv_message_input_scope *scope;\n+\tconst struct ctlv_node_schema *schema;\n+\n+\tif (!ctlv_message_cursor_index(cursor))\n+\t\treturn false;\n+\tschema = ctlv_message_input_ref_node(ref);\n+\tif (!schema)\n+\t\treturn false;\n+\tscope = \u0026cursor-\u003emsg-\u003eindex-\u003escopes[cursor-\u003eindex_scope];\n+\treturn !WARN_ON_ONCE(scope-\u003etree != ref.tree ||\n+\t\t\t     scope-\u003enode != ref.node ||\n+\t\t\t     cursor-\u003etree != ref.tree ||\n+\t\t\t     cursor-\u003enode !=\n+\t\t\t\t     ref.tree-\u003enode_schemas[ref.node].first_child +\n+\t\t\t\t\t     ref.slot);\n+}\n+EXPORT_SYMBOL_NS_GPL(ctlv_input_cursor, \"CTLV\");\n+\n+void ctlv_attr_next(struct ctlv_cursor *cursor)\n+{\n+\tconst struct ctlv_message_input_slot *slot;\n+\tconst struct ctlv_message_input_scope *scope;\n+\tconst struct ctlv_node_schema *node;\n+\tconst struct ctlv_attr *next;\n+\tu32 next_nest;\n+\tu32 next_offset;\n+\n+\tslot = ctlv_message_cursor_index(cursor);\n+\tif (!slot || WARN_ON_ONCE(!cursor-\u003eattr))\n+\t\treturn;\n+\tnext = (const void *)((const u8 *)cursor-\u003eattr +\n+\t\t\t      ALIGN((size_t)cursor-\u003eattr-\u003elen, CTLV_ALIGNTO));\n+\tnext_offset = ctlv_message_offset(cursor-\u003emsg, next);\n+\tif (next_offset == slot-\u003eend_offset) {\n+\t\tcursor-\u003eattr = NULL;\n+\t\tcursor-\u003eindex_nest_scope = CTLV_MESSAGE_INPUT_INDEX_NONE;\n+\t\treturn;\n+\t}\n+\tif (WARN_ON_ONCE(next_offset \u003e slot-\u003eend_offset))\n+\t\treturn;\n+\tcursor-\u003eattr = next;\n+\tnode = \u0026cursor-\u003etree-\u003enode_schemas[cursor-\u003enode];\n+\tif (node-\u003ekind == CTLV_SCHEMA_NEST) {\n+\t\tif (WARN_ON_ONCE(cursor-\u003eindex_nest_scope \u003e= cursor-\u003emsg-\u003eindex-\u003escopes_count))\n+\t\t\treturn;\n+\t\tscope = \u0026cursor-\u003emsg-\u003eindex-\u003escopes[cursor-\u003eindex_nest_scope];\n+\t\tif (WARN_ON_ONCE(scope-\u003enest \u003e= cursor-\u003emsg-\u003eindex-\u003enests_count))\n+\t\t\treturn;\n+\t\tnext_nest = cursor-\u003emsg-\u003eindex-\u003enests[scope-\u003enest].next;\n+\t\tif (WARN_ON_ONCE(next_nest == CTLV_MESSAGE_INPUT_INDEX_NONE ||\n+\t\t\t\t next_nest \u003e= cursor-\u003emsg-\u003eindex-\u003enests_count))\n+\t\t\treturn;\n+\t\tcursor-\u003eindex_nest_scope = cursor-\u003emsg-\u003eindex-\u003enests[next_nest].first_scope;\n+\t}\n+\tWARN_ON_ONCE(!ctlv_message_cursor_index(cursor));\n+}\n+EXPORT_SYMBOL_NS_GPL(ctlv_attr_next, \"CTLV\");\n+\n+bool ctlv_attr_ok(const struct ctlv_cursor *cursor)\n+{\n+\treturn cursor \u0026\u0026 cursor-\u003eattr \u0026\u0026 ctlv_message_cursor_index(cursor);\n+}\n+EXPORT_SYMBOL_NS_GPL(ctlv_attr_ok, \"CTLV\");\n+\n+/* The payload, checked against the kinds a reader of this C type accepts. */\n+static const void *ctlv_message_cursor_payload(const struct ctlv_cursor *cursor, u32 kinds,\n+\t\t\t\t\t       u32 *len)\n+{\n+\tconst struct ctlv_node_schema *node;\n+\n+\tif (!ctlv_message_cursor_index(cursor) || WARN_ON_ONCE(!cursor-\u003eattr))\n+\t\treturn NULL;\n+\tnode = \u0026cursor-\u003etree-\u003enode_schemas[cursor-\u003enode];\n+\tif (WARN_ON_ONCE(!(kinds \u0026 BIT(node-\u003ekind))))\n+\t\treturn NULL;\n+\t*len = ctlv_message_attr_payload_len(cursor-\u003eattr);\n+\treturn ctlv_message_attr_payload(cursor-\u003eattr);\n+}\n+\n+/* A length disagreeing with a validated kind is this core's mistake. */\n+static const void *ctlv_message_cursor_fixed(const struct ctlv_cursor *cursor, u32 kinds,\n+\t\t\t\t\t     u32 expected)\n+{\n+\tconst void *payload;\n+\tu32 len;\n+\n+\tpayload = ctlv_message_cursor_payload(cursor, kinds, \u0026len);\n+\tif (!payload || WARN_ON_ONCE(len != expected))\n+\t\treturn NULL;\n+\treturn payload;\n+}\n+\n+u64 ctlv_attr_u64(const struct ctlv_cursor *cursor)\n+{\n+\tconst u64 *value = ctlv_message_cursor_fixed(cursor,\n+\t\t\t\t\t\t     BIT(CTLV_SCHEMA_UINT) | BIT(CTLV_SCHEMA_ENUM) |\n+\t\t\t\t\t\t\t     BIT(CTLV_SCHEMA_FLAGS),\n+\t\t\t\t\t\t     sizeof(u64));\n+\n+\treturn value ? *value : 0;\n+}\n+EXPORT_SYMBOL_NS_GPL(ctlv_attr_u64, \"CTLV\");\n+\n+s64 ctlv_attr_s64(const struct ctlv_cursor *cursor)\n+{\n+\tconst s64 *value = ctlv_message_cursor_fixed(cursor, BIT(CTLV_SCHEMA_SINT), sizeof(s64));\n+\n+\treturn value ? *value : 0;\n+}\n+EXPORT_SYMBOL_NS_GPL(ctlv_attr_s64, \"CTLV\");\n+\n+bool ctlv_attr_bool(const struct ctlv_cursor *cursor)\n+{\n+\tconst u8 *value = ctlv_message_cursor_fixed(cursor, BIT(CTLV_SCHEMA_BOOL), sizeof(u8));\n+\n+\treturn value ? *value : false;\n+}\n+EXPORT_SYMBOL_NS_GPL(ctlv_attr_bool, \"CTLV\");\n+\n+const char *ctlv_attr_string(const struct ctlv_cursor *cursor)\n+{\n+\tconst char *value;\n+\tu32 len;\n+\n+\tvalue = ctlv_message_cursor_payload(cursor, BIT(CTLV_SCHEMA_STRING), \u0026len);\n+\tif (!value || WARN_ON_ONCE(!len || value[len - 1]))\n+\t\treturn NULL;\n+\treturn value;\n+}\n+EXPORT_SYMBOL_NS_GPL(ctlv_attr_string, \"CTLV\");\n+\n+const void *ctlv_attr_binary(const struct ctlv_cursor *cursor, u32 *len)\n+{\n+\tconst void *value;\n+\n+\t*len = 0;\n+\tvalue = ctlv_message_cursor_payload(cursor, BIT(CTLV_SCHEMA_BINARY), len);\n+\tif (!value)\n+\t\t*len = 0;\n+\treturn value;\n+}\n+EXPORT_SYMBOL_NS_GPL(ctlv_attr_binary, \"CTLV\");\n+\n+/*\n+ * The room is measured before anything is written, which is what leaves a\n+ * refused attr's message exactly as it was, padding included.\n+ */\ndiff --git a/drivers/ctlv/message.h b/drivers/ctlv/message.h\nnew file mode 100644\nindex 0000000000000..efd781af9b373\n--- /dev/null\n+++ b/drivers/ctlv/message.h\n@@ -0,0 +1,92 @@\n+/* SPDX-License-Identifier: GPL-2.0-only */\n+/*\n+ * Copyright (c) 2026, NVIDIA CORPORATION \u0026 AFFILIATES\n+ *\n+ * Private message representation and nest walking.\n+ */\n+#ifndef _CTLV_MESSAGE_H\n+#define _CTLV_MESSAGE_H\n+\n+#include \u003clinux/ctlv_family.h\u003e\n+#include \u003clinux/types.h\u003e\n+\n+#include \u003cuapi/linux/ctlv.h\u003e\n+\n+#define CTLV_MESSAGE_INPUT_INDEX_NONE U32_MAX\n+\n+/* Attr identity remains in the generated schema, not in this request index. */\n+struct ctlv_message_input_slot {\n+\tu32 first_offset;\n+\tu32 end_offset;\n+\tu32 count;\n+\tu32 excess_offset;\n+\tu32 first_nest;\n+\tu32 last_nest;\n+};\n+\n+struct ctlv_message_input_scope {\n+\tconst struct ctlv_schema_tree *tree;\n+\tu32 nest;\n+\tu32 node;\n+\tu32 first_slot;\n+\tu32 slots_count;\n+\tbool optional;\n+};\n+\n+struct ctlv_message_input_nest {\n+\tu32 offset;\n+\tu32 first_scope;\n+\tu32 scopes_count;\n+\tu32 next;\n+};\n+\n+struct ctlv_message_input_index {\n+\tstruct ctlv_message_input_nest *nests;\n+\tstruct ctlv_message_input_scope *scopes;\n+\tstruct ctlv_message_input_slot *slots;\n+\tu32 nests_count;\n+\tu32 nests_capacity;\n+\tu32 scopes_count;\n+\tu32 scopes_capacity;\n+\tu32 slots_count;\n+\tu32 slots_capacity;\n+};\n+\n+struct ctlv_msg {\n+\tstruct ctlv_attr *root;\n+\tsize_t len;\n+\tconst struct ctlv_schema_tree *tree;\n+\tconst struct ctlv_family *family;\n+\tstruct ctlv_op_ctx *ctx;\n+\tstruct ctlv_message_input_index *index;\n+\tbool request;\n+\tint poison;\n+};\n+\n+enum ctlv_message_step {\n+\tCTLV_MESSAGE_STEP_ATTR,\n+\tCTLV_MESSAGE_STEP_END,\n+\tCTLV_MESSAGE_STEP_BAD,\n+};\n+\n+enum ctlv_message_step ctlv_message_next(const struct ctlv_attr *nest,\n+\t\t\t\t\t const struct ctlv_attr **child);\n+u32 ctlv_message_offset(const struct ctlv_msg *msg,\n+\t\t\tconst struct ctlv_attr *attr);\n+void ctlv_message_root(struct ctlv_cursor *cursor, struct ctlv_msg *msg);\n+void ctlv_message_index_free(struct ctlv_msg *msg);\n+bool ctlv_message_input_rebind(struct ctlv_cursor *nest,\n+\t\t\t       const struct ctlv_schema_tree *tree, u32 node);\n+\n+static inline u32 ctlv_message_attr_payload_len(const struct ctlv_attr *attr)\n+{\n+\treturn attr-\u003elen - sizeof(*attr);\n+}\n+\n+static inline const void *\n+ctlv_message_attr_payload(const struct ctlv_attr *attr)\n+{\n+\treturn attr + 1;\n+}\n+\n+#endif /* _CTLV_MESSAGE_H */\ndiff --git a/drivers/ctlv/schema.c b/drivers/ctlv/schema.c\nnew file mode 100644\nindex 0000000000000..b74f9a358bc34\n--- /dev/null\n+++ b/drivers/ctlv/schema.c\n@@ -0,0 +1,1047 @@\n+// SPDX-License-Identifier: GPL-2.0-only\n+/*\n+ * Copyright (c) 2026, NVIDIA CORPORATION \u0026 AFFILIATES\n+ *\n+ * Generated metadata remains owner-local; effective schemas walk the chain.\n+ */\n+#include \u003clinux/align.h\u003e\n+#include \u003clinux/bits.h\u003e\n+#include \u003clinux/ctlv.h\u003e\n+#include \u003clinux/err.h\u003e\n+#include \u003clinux/errno.h\u003e\n+#include \u003clinux/limits.h\u003e\n+#include \u003clinux/minmax.h\u003e\n+#include \u003clinux/overflow.h\u003e\n+#include \u003clinux/slab.h\u003e\n+#include \u003clinux/string.h\u003e\n+#include \u003clinux/types.h\u003e\n+\n+#include \u003cuapi/linux/ctlv.h\u003e\n+#include \u003cuapi/linux/ctlv_gen.h\u003e\n+\n+#include \"blob_desc.h\"\n+#include \"internal.h\"\n+#include \"message.h\"\n+#include \"schema.h\"\n+\n+/* Every 64-bit payload, and every blob descriptor member, is this long. */\n+#define CTLV_SCHEMA_SCALAR_ATTR_LEN (sizeof(struct ctlv_attr) + sizeof(u64))\n+\n+/*\n+ * Where composing a tree's maximum length gives up, which keeps the check on a\n+ * composed length from being passed by a total that wrapped.\n+ */\n+#define CTLV_SCHEMA_MAX_COMPOSED_LEN CTLV_MAX_EVENT_QUEUE_LEN\n+\n+const struct ctlv_family *ctlv_family_ancestor(const struct ctlv_family *family, u32 up)\n+{\n+\twhile (up-- \u0026\u0026 family)\n+\t\tfamily = family-\u003eparent;\n+\treturn family;\n+}\n+\n+u32 ctlv_family_levels(const struct ctlv_family *family)\n+{\n+\tconst struct ctlv_family *ancestor;\n+\tu32 levels = 0;\n+\n+\tfor (ancestor = family; ancestor; ancestor = ancestor-\u003eparent)\n+\t\tlevels++;\n+\treturn levels;\n+}\n+\n+void ctlv_schema_cursor_init(struct ctlv_schema_cursor *cursor, const struct ctlv_family *family)\n+{\n+\tcursor-\u003etarget = family;\n+\tcursor-\u003elevel = ctlv_family_levels(family);\n+\tcursor-\u003efamily = NULL;\n+\tcursor-\u003eindex = 0;\n+}\n+\n+const struct ctlv_op_schema *ctlv_schema_next_op(struct ctlv_schema_cursor *cursor,\n+\t\t\t\t\t\t const struct ctlv_family **family)\n+{\n+\twhile (cursor-\u003elevel) {\n+\t\tconst struct ctlv_family_schema *schema;\n+\n+\t\tif (!cursor-\u003efamily)\n+\t\t\tcursor-\u003efamily = ctlv_family_ancestor(cursor-\u003etarget, cursor-\u003elevel - 1);\n+\t\tschema = cursor-\u003efamily-\u003eschema;\n+\t\tif (cursor-\u003eindex \u003c schema-\u003eops_count) {\n+\t\t\t*family = cursor-\u003efamily;\n+\t\t\treturn \u0026schema-\u003eops[cursor-\u003eindex++];\n+\t\t}\n+\t\tcursor-\u003elevel--;\n+\t\tcursor-\u003efamily = NULL;\n+\t\tcursor-\u003eindex = 0;\n+\t}\n+\treturn NULL;\n+}\n+\n+bool ctlv_schema_member(const struct ctlv_family *family, const struct ctlv_schema_tree *tree,\n+\t\t\tu32 node, u64 attr_id, struct ctlv_schema_pos *member)\n+{\n+\tconst struct ctlv_node_schema *nest;\n+\tu32 index;\n+\n+\tif (!tree-\u003enode_schemas || node \u003e= tree-\u003enode_schemas_count)\n+\t\treturn false;\n+\tnest = \u0026tree-\u003enode_schemas[node];\n+\n+\tfor (index = 0; index \u003c nest-\u003echildren_count; index++) {\n+\t\tu32 child = nest-\u003efirst_child + index;\n+\n+\t\tif (tree-\u003enode_schemas[child].attr_id == attr_id) {\n+\t\t\t*member = (struct ctlv_schema_pos){\n+\t\t\t\t.tree = tree,\n+\t\t\t\t.node = child,\n+\t\t\t};\n+\t\t\treturn true;\n+\t\t}\n+\t}\n+\tfor (index = 0; index \u003c tree-\u003estub_schemas_count; index++) {\n+\t\tconst struct ctlv_stub_schema *stub_schema = \u0026tree-\u003estub_schemas[index];\n+\t\tconst struct ctlv_stub_fill_schema *fill_schema;\n+\n+\t\tif (stub_schema-\u003enode != node)\n+\t\t\tcontinue;\n+\t\tfill_schema = ctlv_schema_fill(family, stub_schema-\u003efamily_id, stub_schema-\u003eset_id);\n+\t\t/* Filled-stub members are children of the fill schema's root. */\n+\t\tif (fill_schema \u0026\u0026\n+\t\t    ctlv_schema_member(family, \u0026fill_schema-\u003emembers, 0, attr_id, member))\n+\t\t\treturn true;\n+\t}\n+\treturn false;\n+}\n+\n+const struct ctlv_stub_fill_schema *ctlv_schema_fill(const struct ctlv_family *family,\n+\t\t\t\t\t\t     u16 family_id, u32 set_id)\n+{\n+\tconst struct ctlv_family *owner;\n+\tu32 index;\n+\n+\tfor (owner = family; owner; owner = owner-\u003eparent) {\n+\t\tconst struct ctlv_family_schema *schema = owner-\u003eschema;\n+\n+\t\tfor (index = 0; index \u003c schema-\u003estub_fill_schemas_count; index++)\n+\t\t\tif (schema-\u003estub_fill_schemas[index].family_id == family_id \u0026\u0026\n+\t\t\t    schema-\u003estub_fill_schemas[index].set_id == set_id)\n+\t\t\t\treturn \u0026schema-\u003estub_fill_schemas[index];\n+\t}\n+\treturn NULL;\n+}\n+\n+/*\n+ * The same arithmetic the generator did, over the tree it emitted plus this\n+ * family's stub fill schemas, since a fill makes an extension point longer.\n+ */\n+\n+struct ctlv_schema_length_walk {\n+\tconst struct ctlv_family *family;\n+\tbool bad;\n+};\n+\n+static u64 ctlv_schema_children_max_len(struct ctlv_schema_length_walk *walk,\n+\t\t\t\t\tconst struct ctlv_schema_tree *tree, u32 index, u32 depth);\n+\n+static u64 ctlv_schema_payload_max_len(struct ctlv_schema_length_walk *walk,\n+\t\t\t\t       const struct ctlv_schema_tree *tree, u32 index, u32 depth)\n+{\n+\tconst struct ctlv_node_schema *node = \u0026tree-\u003enode_schemas[index];\n+\n+\tswitch (node-\u003ekind) {\n+\tcase CTLV_SCHEMA_UINT:\n+\tcase CTLV_SCHEMA_SINT:\n+\tcase CTLV_SCHEMA_ENUM:\n+\tcase CTLV_SCHEMA_FLAGS:\n+\t\treturn sizeof(u64);\n+\tcase CTLV_SCHEMA_BOOL:\n+\t\treturn 1;\n+\tcase CTLV_SCHEMA_STRING:\n+\t\t/*\n+\t\t * One terminating NUL, which the declared maximum excludes.\n+\t\t * Widened first so that a maximum at U32_MAX cannot wrap.\n+\t\t */\n+\t\treturn (u64)node-\u003elength.max_len + 1;\n+\tcase CTLV_SCHEMA_BINARY:\n+\t\treturn node-\u003elength.max_len;\n+\tcase CTLV_SCHEMA_BLOB:\n+\t\t/*\n+\t\t * Type, length and an address; anything but a bare VA is one\n+\t\t * member wider, an fd with an optional offset.\n+\t\t */\n+\t\treturn (node-\u003eblob.backings == BIT(CTLV_BLOB_TYPE_VA) ? 3 : 4) *\n+\t\t       ALIGN(CTLV_SCHEMA_SCALAR_ATTR_LEN, CTLV_ALIGNTO);\n+\tdefault:\n+\t\treturn ctlv_schema_children_max_len(walk, tree, index, depth);\n+\t}\n+}\n+\n+static u64 ctlv_schema_attr_max_len(struct ctlv_schema_length_walk *walk,\n+\t\t\t\t    const struct ctlv_schema_tree *tree, u32 index, u32 depth)\n+{\n+\treturn sizeof(struct ctlv_attr) + ctlv_schema_payload_max_len(walk, tree, index, depth);\n+}\n+\n+static u64 ctlv_schema_children_max_len(struct ctlv_schema_length_walk *walk,\n+\t\t\t\t\tconst struct ctlv_schema_tree *tree, u32 index, u32 depth)\n+{\n+\tconst struct ctlv_node_schema *node = \u0026tree-\u003enode_schemas[index];\n+\tu64 total = 0;\n+\tu32 i;\n+\n+\tif (depth \u003e CTLV_MAX_DECLARED_NEST_DEPTH) {\n+\t\twalk-\u003ebad = true;\n+\t\treturn 0;\n+\t}\n+\tfor (i = 0; i \u003c node-\u003echildren_count; i++) {\n+\t\tu32 child = node-\u003efirst_child + i;\n+\t\tu64 each, all;\n+\n+\t\t/*\n+\t\t * Neither an unlimited placement nor one that re-enters has a\n+\t\t * maximum, and only a query reply may hold either.\n+\t\t */\n+\t\tif (tree-\u003enode_schemas[child].reenters ||\n+\t\t    !tree-\u003enode_schemas[child].max_occurrences) {\n+\t\t\twalk-\u003ebad = true;\n+\t\t\treturn 0;\n+\t\t}\n+\t\teach = ALIGN(ctlv_schema_attr_max_len(walk, tree, child, depth + 1), CTLV_ALIGNTO);\n+\t\tif (check_mul_overflow((u64)tree-\u003enode_schemas[child].max_occurrences, each,\n+\t\t\t\t       \u0026all) ||\n+\t\t    check_add_overflow(total, all, \u0026total) ||\n+\t\t    total \u003e CTLV_SCHEMA_MAX_COMPOSED_LEN) {\n+\t\t\twalk-\u003ebad = true;\n+\t\t\treturn 0;\n+\t\t}\n+\t}\n+\tfor (i = 0; i \u003c tree-\u003estub_schemas_count; i++) {\n+\t\tconst struct ctlv_stub_schema *stub_schema = \u0026tree-\u003estub_schemas[i];\n+\t\tconst struct ctlv_stub_fill_schema *fill_schema;\n+\n+\t\tif (stub_schema-\u003enode != index)\n+\t\t\tcontinue;\n+\t\tfill_schema =\n+\t\t\tctlv_schema_fill(walk-\u003efamily, stub_schema-\u003efamily_id, stub_schema-\u003eset_id);\n+\t\tif (!fill_schema)\n+\t\t\tcontinue;\n+\t\tif (check_add_overflow(total,\n+\t\t\t\t       ctlv_schema_children_max_len(walk, \u0026fill_schema-\u003emembers, 0,\n+\t\t\t\t\t\t\t\t    depth),\n+\t\t\t\t       \u0026total) ||\n+\t\t    total \u003e CTLV_SCHEMA_MAX_COMPOSED_LEN) {\n+\t\t\twalk-\u003ebad = true;\n+\t\t\treturn 0;\n+\t\t}\n+\t}\n+\treturn total;\n+}\n+\n+/* Buffer length that the largest indivisible leaf and its nests need. */\n+static u64 ctlv_schema_min_len(struct ctlv_schema_length_walk *walk,\n+\t\t\t       const struct ctlv_schema_tree *tree, u32 index, u32 above, u32 depth)\n+{\n+\tconst struct ctlv_node_schema *node = \u0026tree-\u003enode_schemas[index];\n+\tbool has_children = false;\n+\tu64 deepest = 0;\n+\tu32 i;\n+\n+\tif (depth \u003e CTLV_MAX_DECLARED_NEST_DEPTH) {\n+\t\twalk-\u003ebad = true;\n+\t\treturn 0;\n+\t}\n+\tfor (i = 0; i \u003c node-\u003echildren_count; i++) {\n+\t\tu32 child = node-\u003efirst_child + i;\n+\n+\t\thas_children = true;\n+\t\tdeepest = max(deepest,\n+\t\t\t      ctlv_schema_min_len(walk, tree, child,\n+\t\t\t\t\t\t  above + sizeof(struct ctlv_attr), depth + 1));\n+\t}\n+\tfor (i = 0; i \u003c tree-\u003estub_schemas_count; i++) {\n+\t\tconst struct ctlv_stub_schema *stub_schema = \u0026tree-\u003estub_schemas[i];\n+\t\tconst struct ctlv_stub_fill_schema *fill_schema;\n+\t\tconst struct ctlv_node_schema *root;\n+\t\tu32 member;\n+\n+\t\tif (stub_schema-\u003enode != index)\n+\t\t\tcontinue;\n+\t\tfill_schema =\n+\t\t\tctlv_schema_fill(walk-\u003efamily, stub_schema-\u003efamily_id, stub_schema-\u003eset_id);\n+\t\tif (!fill_schema)\n+\t\t\tcontinue;\n+\t\troot = \u0026fill_schema-\u003emembers.node_schemas[0];\n+\t\tfor (member = 0; member \u003c root-\u003echildren_count; member++) {\n+\t\t\thas_children = true;\n+\t\t\tdeepest = max(deepest, ctlv_schema_min_len(walk, \u0026fill_schema-\u003emembers,\n+\t\t\t\t\t\t\t\t   root-\u003efirst_child + member,\n+\t\t\t\t\t\t\t\t   above + sizeof(struct ctlv_attr),\n+\t\t\t\t\t\t\t\t   depth + 1));\n+\t\t}\n+\t}\n+\tif (has_children)\n+\t\treturn deepest;\n+\t/* An empty root is a message of its own header alone. */\n+\tif (!index)\n+\t\treturn above + sizeof(struct ctlv_attr);\n+\treturn above + ALIGN(ctlv_schema_attr_max_len(walk, tree, index, depth), CTLV_ALIGNTO);\n+}\n+\n+static u64 ctlv_schema_root_max_len(struct ctlv_schema_length_walk *walk,\n+\t\t\t\t    const struct ctlv_schema_tree *tree)\n+{\n+\treturn sizeof(struct ctlv_attr) + ctlv_schema_children_max_len(walk, tree, 0, 0);\n+}\n+\n+/* Size one deepest legal leaf and every nest above it. */\n+static u64 ctlv_schema_reentering_min_len(struct ctlv_schema_length_walk *walk,\n+\t\t\t\t\t  const struct ctlv_schema_tree *tree)\n+{\n+\tu64 leaf = 0;\n+\tu32 index;\n+\n+\tfor (index = 1; index \u003c tree-\u003enode_schemas_count; index++) {\n+\t\tif (tree-\u003enode_schemas[index].kind == CTLV_SCHEMA_NEST)\n+\t\t\tcontinue;\n+\t\tleaf = max(leaf,\n+\t\t\t   ALIGN(ctlv_schema_attr_max_len(walk, tree, index, 0), CTLV_ALIGNTO));\n+\t}\n+\treturn (CTLV_MAX_NEST_DEPTH + 1) * sizeof(struct ctlv_attr) + leaf;\n+}\n+\n+static bool ctlv_schema_tree_reenters(const struct ctlv_schema_tree *tree)\n+{\n+\tu32 index;\n+\n+\tfor (index = 0; index \u003c tree-\u003enode_schemas_count; index++)\n+\t\tif (tree-\u003enode_schemas[index].reenters)\n+\t\t\treturn true;\n+\treturn false;\n+}\n+\n+int ctlv_schema_op_sizes(const struct ctlv_family *family, const struct ctlv_op_schema *op,\n+\t\t\t struct ctlv_op_sizes *sizes)\n+{\n+\tstruct ctlv_schema_length_walk walk = { .family = family };\n+\tu64 request = 0, reply = 0, record = 0;\n+\n+\tif (op-\u003erequest.node_schemas)\n+\t\trequest = ctlv_schema_root_max_len(\u0026walk, \u0026op-\u003erequest);\n+\n+\tswitch (op-\u003etype) {\n+\tcase CTLV_OP_TYPE_ACTION:\n+\t\tif (op-\u003ereply.node_schemas)\n+\t\t\treply = ctlv_schema_root_max_len(\u0026walk, \u0026op-\u003ereply);\n+\t\tbreak;\n+\tcase CTLV_OP_TYPE_QUERY:\n+\t\tif (ctlv_schema_tree_reenters(\u0026op-\u003ereply))\n+\t\t\treply = ctlv_schema_reentering_min_len(\u0026walk, \u0026op-\u003ereply);\n+\t\telse\n+\t\t\treply = ctlv_schema_min_len(\u0026walk, \u0026op-\u003ereply, 0, 0, 0);\n+\t\tbreak;\n+\tcase CTLV_OP_TYPE_EVENT:\n+\t\trecord = sizeof(struct ctlv_event_hdr) +\n+\t\t\t ALIGN(ctlv_schema_root_max_len(\u0026walk, \u0026op-\u003ereply), CTLV_ALIGNTO);\n+\t\tbreak;\n+\tdefault:\n+\t\treturn -EINVAL;\n+\t}\n+\n+\tif (walk.bad || request \u003e CTLV_MAX_INLINE_MESSAGE_LEN ||\n+\t    reply \u003e CTLV_MAX_INLINE_MESSAGE_LEN || record \u003e CTLV_MAX_EVENT_QUEUE_LEN)\n+\t\treturn -EINVAL;\n+\n+\t*sizes = (struct ctlv_op_sizes){ .request_max_len = request };\n+\tswitch (op-\u003etype) {\n+\tcase CTLV_OP_TYPE_ACTION:\n+\t\tsizes-\u003eaction_reply_max_len = reply;\n+\t\tbreak;\n+\tcase CTLV_OP_TYPE_QUERY:\n+\t\tsizes-\u003equery_reply_min_len = reply;\n+\t\t/*\n+\t\t * What the specification asked for, unless a filled extension\n+\t\t * point made one fragment longer than that.\n+\t\t */\n+\t\tsizes-\u003equery_reply_suggested_len =\n+\t\t\tmax_t(u32, op-\u003esizes.query_reply_suggested_len, reply);\n+\t\tbreak;\n+\tdefault:\n+\t\tsizes-\u003eevent_record_max_len = record;\n+\t\tbreak;\n+\t}\n+\treturn 0;\n+}\n+\n+/*\n+ * Only a completely valid request reaches family code; nothing is repaired or\n+ * normalized. The first failure is the one recorded, and the walk stops there.\n+ */\n+\n+struct ctlv_schema_validation {\n+\tstruct ctlv_msg *msg;\n+\tstruct ctlv_error *error;\n+};\n+\n+void ctlv_message_index_free(struct ctlv_msg *msg)\n+{\n+\tstruct ctlv_message_input_index *index;\n+\n+\tif (!msg || !msg-\u003eindex)\n+\t\treturn;\n+\tindex = msg-\u003eindex;\n+\tkvfree(index-\u003eslots);\n+\tkvfree(index-\u003escopes);\n+\tkvfree(index-\u003enests);\n+\tkfree(index);\n+\tmsg-\u003eindex = NULL;\n+}\n+\n+static void *ctlv_schema_index_grow(void *items, u32 *capacity, u32 needed, size_t item_size)\n+{\n+\tu32 grown = max_t(u32, *capacity, 16);\n+\tsize_t bytes;\n+\tvoid *new;\n+\n+\tif (needed \u003c= *capacity)\n+\t\treturn items;\n+\twhile (grown \u003c needed) {\n+\t\tif (grown \u003e U32_MAX / 2)\n+\t\t\treturn ERR_PTR(-EOVERFLOW);\n+\t\tgrown *= 2;\n+\t}\n+\tif (check_mul_overflow((size_t)grown, item_size, \u0026bytes))\n+\t\treturn ERR_PTR(-EOVERFLOW);\n+\tnew = kvrealloc(items, bytes, GFP_KERNEL_ACCOUNT);\n+\tif (!new)\n+\t\treturn ERR_PTR(-ENOMEM);\n+\t*capacity = grown;\n+\treturn new;\n+}\n+\n+static int ctlv_schema_index_slots_add(struct ctlv_message_input_index *index, u32 count,\n+\t\t\t\t       u32 *first)\n+{\n+\tstruct ctlv_message_input_slot *slots;\n+\tu32 needed;\n+\tu32 i;\n+\n+\tif (check_add_overflow(index-\u003eslots_count, count, \u0026needed))\n+\t\treturn -EOVERFLOW;\n+\tslots = ctlv_schema_index_grow(index-\u003eslots, \u0026index-\u003eslots_capacity, needed,\n+\t\t\t\t       sizeof(*slots));\n+\tif (IS_ERR(slots))\n+\t\treturn PTR_ERR(slots);\n+\tindex-\u003eslots = slots;\n+\t*first = index-\u003eslots_count;\n+\tfor (i = index-\u003eslots_count; i \u003c needed; i++)\n+\t\tindex-\u003eslots[i] = (struct ctlv_message_input_slot){\n+\t\t\t.excess_offset = CTLV_MESSAGE_INPUT_INDEX_NONE,\n+\t\t\t.first_nest = CTLV_MESSAGE_INPUT_INDEX_NONE,\n+\t\t\t.last_nest = CTLV_MESSAGE_INPUT_INDEX_NONE,\n+\t\t};\n+\tindex-\u003eslots_count = needed;\n+\treturn 0;\n+}\n+\n+static int ctlv_schema_index_scope_add(struct ctlv_schema_validation *v, u32 nest_index,\n+\t\t\t\t       const struct ctlv_schema_tree *tree, u32 node, bool optional)\n+{\n+\tstruct ctlv_message_input_index *index = v-\u003emsg-\u003eindex;\n+\tconst struct ctlv_node_schema *parent = \u0026tree-\u003enode_schemas[node];\n+\tstruct ctlv_message_input_scope *scopes;\n+\tu32 needed;\n+\tu32 first_slot;\n+\tu32 scope_index;\n+\tu32 i;\n+\tint ret;\n+\n+\tif (check_add_overflow(index-\u003escopes_count, 1U, \u0026needed))\n+\t\treturn -EOVERFLOW;\n+\tscopes = ctlv_schema_index_grow(index-\u003escopes, \u0026index-\u003escopes_capacity, needed,\n+\t\t\t\t\tsizeof(*scopes));\n+\tif (IS_ERR(scopes))\n+\t\treturn PTR_ERR(scopes);\n+\tindex-\u003escopes = scopes;\n+\tret = ctlv_schema_index_slots_add(index, parent-\u003echildren_count, \u0026first_slot);\n+\tif (ret)\n+\t\treturn ret;\n+\tscope_index = index-\u003escopes_count++;\n+\tindex-\u003escopes[scope_index] = (struct ctlv_message_input_scope){\n+\t\t.tree = tree,\n+\t\t.nest = nest_index,\n+\t\t.node = node,\n+\t\t.first_slot = first_slot,\n+\t\t.slots_count = parent-\u003echildren_count,\n+\t\t.optional = optional,\n+\t};\n+\tindex-\u003enests[nest_index].scopes_count++;\n+\n+\tfor (i = 0; i \u003c tree-\u003estub_schemas_count; i++) {\n+\t\tconst struct ctlv_stub_schema *stub_schema = \u0026tree-\u003estub_schemas[i];\n+\t\tconst struct ctlv_stub_fill_schema *fill_schema;\n+\n+\t\tif (stub_schema-\u003enode != node)\n+\t\t\tcontinue;\n+\t\tfill_schema = ctlv_schema_fill(v-\u003emsg-\u003efamily, stub_schema-\u003efamily_id,\n+\t\t\t\t\t       stub_schema-\u003eset_id);\n+\t\tif (!fill_schema)\n+\t\t\tcontinue;\n+\t\tret = ctlv_schema_index_scope_add(v, nest_index, \u0026fill_schema-\u003emembers, 0,\n+\t\t\t\t\t\t  optional || stub_schema-\u003eoptional);\n+\t\tif (ret)\n+\t\t\treturn ret;\n+\t}\n+\treturn 0;\n+}\n+\n+static int ctlv_schema_index_nest_add(struct ctlv_schema_validation *v,\n+\t\t\t\t      const struct ctlv_schema_tree *tree, u32 node,\n+\t\t\t\t      const struct ctlv_attr *nest_attr, u32 *nest_index)\n+{\n+\tstruct ctlv_message_input_index *index = v-\u003emsg-\u003eindex;\n+\tstruct ctlv_message_input_nest *nests;\n+\tu32 needed;\n+\tu32 added;\n+\tint ret;\n+\n+\tif (check_add_overflow(index-\u003enests_count, 1U, \u0026needed))\n+\t\treturn -EOVERFLOW;\n+\tnests = ctlv_schema_index_grow(index-\u003enests, \u0026index-\u003enests_capacity, needed,\n+\t\t\t\t       sizeof(*nests));\n+\tif (IS_ERR(nests))\n+\t\treturn PTR_ERR(nests);\n+\tindex-\u003enests = nests;\n+\tadded = index-\u003enests_count++;\n+\tindex-\u003enests[added] = (struct ctlv_message_input_nest){\n+\t\t.offset = ctlv_message_offset(v-\u003emsg, nest_attr),\n+\t\t.first_scope = index-\u003escopes_count,\n+\t\t.next = CTLV_MESSAGE_INPUT_INDEX_NONE,\n+\t};\n+\tret = ctlv_schema_index_scope_add(v, added, tree, node, false);\n+\tif (ret)\n+\t\treturn ret;\n+\t*nest_index = added;\n+\treturn 0;\n+}\n+\n+/* A request is never a fragment: only a reply of a query is ever incomplete. */\n+#define CTLV_SCHEMA_ATTR_F_REQUEST (CTLV_ATTR_F_NESTED | CTLV_ATTR_F_IGNORE_IF_UNKNOWN)\n+#define CTLV_SCHEMA_ATTR_F_REPLY CTLV_ATTR_F_NESTED\n+\n+/*\n+ * Record the first failure and refuse the message. @attr is NULL when what is\n+ * wrong with the nest is something it does not carry.\n+ */\n+static int ctlv_schema_bad(struct ctlv_schema_validation *v, u32 reason,\n+\t\t\t   const struct ctlv_attr *nest, const struct ctlv_attr *attr)\n+{\n+\t*v-\u003eerror = (struct ctlv_error){\n+\t\t.reason = reason,\n+\t\t.bad_attr_offset = ctlv_message_offset(v-\u003emsg, attr ?: nest),\n+\t\t.nest_offset = ctlv_message_offset(v-\u003emsg, nest),\n+\t};\n+\treturn -EINVAL;\n+}\n+\n+/* The one failure that names an attr the message does not contain. */\n+static int ctlv_schema_bad_missing(struct ctlv_schema_validation *v, const struct ctlv_attr *nest,\n+\t\t\t\t   u64 attr_id)\n+{\n+\tctlv_schema_bad(v, CTLV_VALIDATION_REASON_MISSING_ATTR, nest, NULL);\n+\tv-\u003eerror-\u003emissing_attr_id = attr_id;\n+\treturn -EINVAL;\n+}\n+\n+static struct ctlv_message_input_slot *ctlv_schema_index_slot(struct ctlv_schema_validation *v,\n+\t\t\t\t\t\t\t      u32 nest_index,\n+\t\t\t\t\t\t\t      const struct ctlv_schema_pos *pos)\n+{\n+\tstruct ctlv_message_input_index *index = v-\u003emsg-\u003eindex;\n+\tconst struct ctlv_message_input_nest *nest;\n+\tu32 i;\n+\n+\tif (WARN_ON_ONCE(nest_index \u003e= index-\u003enests_count))\n+\t\treturn NULL;\n+\tnest = \u0026index-\u003enests[nest_index];\n+\tfor (i = 0; i \u003c nest-\u003escopes_count; i++) {\n+\t\tconst struct ctlv_message_input_scope *scope =\n+\t\t\t\u0026index-\u003escopes[nest-\u003efirst_scope + i];\n+\t\tconst struct ctlv_node_schema *parent;\n+\t\tu32 slot;\n+\n+\t\tif (scope-\u003etree != pos-\u003etree)\n+\t\t\tcontinue;\n+\t\tparent = \u0026scope-\u003etree-\u003enode_schemas[scope-\u003enode];\n+\t\tif (pos-\u003enode \u003c parent-\u003efirst_child ||\n+\t\t    pos-\u003enode \u003e= parent-\u003efirst_child + scope-\u003eslots_count)\n+\t\t\tcontinue;\n+\t\tslot = pos-\u003enode - parent-\u003efirst_child;\n+\t\treturn \u0026index-\u003eslots[scope-\u003efirst_slot + slot];\n+\t}\n+\tWARN_ON_ONCE(1);\n+\treturn NULL;\n+}\n+\n+static int ctlv_schema_index_record(struct ctlv_schema_validation *v, u32 nest_index,\n+\t\t\t\t    const struct ctlv_schema_pos *pos, const struct ctlv_attr *attr,\n+\t\t\t\t    bool *seen)\n+{\n+\tstruct ctlv_message_input_slot *slot = ctlv_schema_index_slot(v, nest_index, pos);\n+\tconst struct ctlv_node_schema *schema = \u0026pos-\u003etree-\u003enode_schemas[pos-\u003enode];\n+\tu32 offset = ctlv_message_offset(v-\u003emsg, attr);\n+\n+\tif (!slot)\n+\t\treturn -EINVAL;\n+\t*seen = slot-\u003ecount;\n+\tif (!slot-\u003ecount)\n+\t\tslot-\u003efirst_offset = offset;\n+\tslot-\u003ecount++;\n+\tif (schema-\u003emax_occurrences \u0026\u0026 slot-\u003ecount \u003e schema-\u003emax_occurrences \u0026\u0026\n+\t    slot-\u003eexcess_offset == CTLV_MESSAGE_INPUT_INDEX_NONE)\n+\t\tslot-\u003eexcess_offset = offset;\n+\tslot-\u003eend_offset = offset + ALIGN((size_t)attr-\u003elen, CTLV_ALIGNTO);\n+\treturn 0;\n+}\n+\n+static void ctlv_schema_index_nest_link(struct ctlv_message_input_index *index,\n+\t\t\t\t\tstruct ctlv_message_input_slot *slot, u32 nest_index)\n+{\n+\tif (slot-\u003efirst_nest == CTLV_MESSAGE_INPUT_INDEX_NONE)\n+\t\tslot-\u003efirst_nest = nest_index;\n+\telse\n+\t\tindex-\u003enests[slot-\u003elast_nest].next = nest_index;\n+\tslot-\u003elast_nest = nest_index;\n+}\n+\n+static int ctlv_schema_index_required(struct ctlv_schema_validation *v, u32 nest_index,\n+\t\t\t\t      const struct ctlv_attr *nest_attr)\n+{\n+\tconst struct ctlv_message_input_index *index = v-\u003emsg-\u003eindex;\n+\tconst struct ctlv_message_input_nest *nest = \u0026index-\u003enests[nest_index];\n+\tu32 i;\n+\n+\tfor (i = 0; i \u003c nest-\u003escopes_count; i++) {\n+\t\tconst struct ctlv_message_input_scope *scope =\n+\t\t\t\u0026index-\u003escopes[nest-\u003efirst_scope + i];\n+\t\tconst struct ctlv_node_schema *parent = \u0026scope-\u003etree-\u003enode_schemas[scope-\u003enode];\n+\t\tu32 slot;\n+\n+\t\tfor (slot = 0; slot \u003c scope-\u003eslots_count; slot++) {\n+\t\t\tconst struct ctlv_message_input_slot *indexed;\n+\t\t\tconst struct ctlv_node_schema *child =\n+\t\t\t\t\u0026scope-\u003etree-\u003enode_schemas[parent-\u003efirst_child + slot];\n+\t\t\tconst struct ctlv_attr *excess;\n+\n+\t\t\tindexed = \u0026index-\u003eslots[scope-\u003efirst_slot + slot];\n+\t\t\tif (!indexed-\u003ecount \u0026\u0026 slot \u003c parent-\u003erequired_children_count \u0026\u0026\n+\t\t\t    !scope-\u003eoptional)\n+\t\t\t\treturn ctlv_schema_bad_missing(v, nest_attr, child-\u003eattr_id);\n+\t\t\tif (!child-\u003emax_occurrences || indexed-\u003ecount \u003c= child-\u003emax_occurrences)\n+\t\t\t\tcontinue;\n+\t\t\tif (WARN_ON_ONCE(indexed-\u003eexcess_offset == CTLV_MESSAGE_INPUT_INDEX_NONE))\n+\t\t\t\treturn -EINVAL;\n+\t\t\texcess = (const void *)((const u8 *)v-\u003emsg-\u003eroot + indexed-\u003eexcess_offset);\n+\t\t\treturn ctlv_schema_bad(v, CTLV_VALIDATION_REASON_TOO_MANY_OCCURRENCES,\n+\t\t\t\t\t       nest_attr, excess);\n+\t\t}\n+\t}\n+\treturn 0;\n+}\n+\n+/* The bits an attr of this message may carry, whichever way it travelled. */\n+static u32 ctlv_schema_flags_allowed(const struct ctlv_schema_validation *v)\n+{\n+\treturn v-\u003emsg-\u003erequest ? CTLV_SCHEMA_ATTR_F_REQUEST : CTLV_SCHEMA_ATTR_F_REPLY;\n+}\n+\n+static u64 ctlv_schema_scalar_value(const struct ctlv_attr *attr)\n+{\n+\t/* Aligned by the wire format: the root began an allocation. */\n+\treturn *(const u64 *)ctlv_message_attr_payload(attr);\n+}\n+\n+bool ctlv_schema_value_ok(const struct ctlv_node_schema *node, u64 value)\n+{\n+\tswitch (node-\u003ekind) {\n+\tcase CTLV_SCHEMA_SINT:\n+\t\treturn (s64)value \u003e= (s64)node-\u003erange.min \u0026\u0026 (s64)value \u003c= (s64)node-\u003erange.max;\n+\tcase CTLV_SCHEMA_FLAGS:\n+\t\t/* A bit no family declared is one nothing can be told about. */\n+\t\treturn !(value \u0026 ~node-\u003eflags_mask);\n+\tcase CTLV_SCHEMA_BOOL:\n+\t\treturn value \u003c= 1;\n+\tdefault:\n+\t\t/*\n+\t\t * An enum's values are numbered from one in declaration order\n+\t\t * and never skipped, so its range bounds it like an integer.\n+\t\t */\n+\t\treturn value \u003e= node-\u003erange.min \u0026\u0026 value \u003c= node-\u003erange.max;\n+\t}\n+}\n+\n+bool ctlv_schema_length_ok(const struct ctlv_node_schema *node, u32 len)\n+{\n+\treturn len \u003e= node-\u003elength.min_len \u0026\u0026 len \u003c= node-\u003elength.max_len;\n+}\n+\n+static int ctlv_schema_check_integer(struct ctlv_schema_validation *v,\n+\t\t\t\t     const struct ctlv_node_schema *node,\n+\t\t\t\t     const struct ctlv_attr *nest, const struct ctlv_attr *attr)\n+{\n+\tu64 value;\n+\n+\tif (ctlv_message_attr_payload_len(attr) != sizeof(value))\n+\t\treturn ctlv_schema_bad(v, CTLV_VALIDATION_REASON_BAD_LENGTH, nest, attr);\n+\tvalue = ctlv_schema_scalar_value(attr);\n+\tif (ctlv_schema_value_ok(node, value))\n+\t\treturn 0;\n+\tif (node-\u003ekind == CTLV_SCHEMA_FLAGS)\n+\t\treturn ctlv_schema_bad(v, CTLV_VALIDATION_REASON_UNKNOWN_FLAG, nest, attr);\n+\treturn ctlv_schema_bad(v, CTLV_VALIDATION_REASON_VALUE_OUT_OF_RANGE, nest, attr);\n+}\n+\n+static int ctlv_schema_check_bool(struct ctlv_schema_validation *v,\n+\t\t\t\t  const struct ctlv_node_schema *node, const struct ctlv_attr *nest,\n+\t\t\t\t  const struct ctlv_attr *attr)\n+{\n+\tconst u8 *value = ctlv_message_attr_payload(attr);\n+\n+\tif (ctlv_message_attr_payload_len(attr) != sizeof(*value))\n+\t\treturn ctlv_schema_bad(v, CTLV_VALIDATION_REASON_BAD_LENGTH, nest, attr);\n+\tif (!ctlv_schema_value_ok(node, *value))\n+\t\treturn ctlv_schema_bad(v, CTLV_VALIDATION_REASON_VALUE_OUT_OF_RANGE, nest, attr);\n+\treturn 0;\n+}\n+\n+static int ctlv_schema_check_string(struct ctlv_schema_validation *v,\n+\t\t\t\t    const struct ctlv_node_schema *node,\n+\t\t\t\t    const struct ctlv_attr *nest, const struct ctlv_attr *attr)\n+{\n+\tu32 len = ctlv_message_attr_payload_len(attr);\n+\tconst char *value = ctlv_message_attr_payload(attr);\n+\n+\t/*\n+\t * One terminating NUL and no other, so a family may hand the payload\n+\t * to anything that takes a C string.\n+\t */\n+\tif (!len || value[len - 1] || strnlen(value, len) != len - 1)\n+\t\treturn ctlv_schema_bad(v, CTLV_VALIDATION_REASON_BAD_STRING, nest, attr);\n+\tif (!ctlv_schema_length_ok(node, len - 1))\n+\t\treturn ctlv_schema_bad(v, CTLV_VALIDATION_REASON_BAD_LENGTH, nest, attr);\n+\treturn 0;\n+}\n+\n+static int ctlv_schema_check_binary(struct ctlv_schema_validation *v,\n+\t\t\t\t    const struct ctlv_node_schema *node,\n+\t\t\t\t    const struct ctlv_attr *nest, const struct ctlv_attr *attr)\n+{\n+\tif (!ctlv_schema_length_ok(node, ctlv_message_attr_payload_len(attr)))\n+\t\treturn ctlv_schema_bad(v, CTLV_VALIDATION_REASON_BAD_LENGTH, nest, attr);\n+\treturn 0;\n+}\n+\n+/*\n+ * The one shape the tree cannot describe: a nest of core-owned attrs\n+ * whose members depend on its type. Nothing here acquires anything.\n+ */\n+static int ctlv_schema_check_blob(struct ctlv_schema_validation *v,\n+\t\t\t\t  const struct ctlv_node_schema *node, const struct ctlv_attr *blob)\n+{\n+\tconst struct ctlv_attr *bad = NULL;\n+\tstruct ctlv_blob_desc desc;\n+\tu32 reason;\n+\n+\treason = ctlv_blob_desc_read(blob, \u0026desc, \u0026bad);\n+\tif (!reason)\n+\t\treason = ctlv_blob_desc_check(\u0026desc, node);\n+\tif (reason)\n+\t\treturn ctlv_schema_bad(v, reason, blob, bad);\n+\treturn 0;\n+}\n+\n+static int ctlv_schema_check_nest(struct ctlv_schema_validation *v,\n+\t\t\t\t  const struct ctlv_schema_tree *tree, u32 node,\n+\t\t\t\t  const struct ctlv_attr *nest, u32 depth);\n+static int ctlv_schema_check_indexed_nest(struct ctlv_schema_validation *v,\n+\t\t\t\t\t  const struct ctlv_schema_tree *tree, u32 node,\n+\t\t\t\t\t  const struct ctlv_attr *nest, u32 depth, u32 *nest_index);\n+\n+static int ctlv_schema_check_attr(struct ctlv_schema_validation *v,\n+\t\t\t\t  const struct ctlv_schema_pos *pos, const struct ctlv_attr *nest,\n+\t\t\t\t  const struct ctlv_attr *attr, u32 depth, u32 *nest_index)\n+{\n+\tconst struct ctlv_node_schema *node = \u0026pos-\u003etree-\u003enode_schemas[pos-\u003enode];\n+\tbool nested = node-\u003ekind == CTLV_SCHEMA_NEST || node-\u003ekind == CTLV_SCHEMA_BLOB;\n+\n+\tif (attr-\u003eflags \u0026 ~ctlv_schema_flags_allowed(v))\n+\t\treturn ctlv_schema_bad(v, CTLV_VALIDATION_REASON_UNKNOWN_FLAG, nest, attr);\n+\t/* Whether an attr is a nest is the schema's to say, not the sender's. */\n+\tif (!(attr-\u003eflags \u0026 CTLV_ATTR_F_NESTED) != !nested)\n+\t\treturn ctlv_schema_bad(v, CTLV_VALIDATION_REASON_MALFORMED_MESSAGE, nest, attr);\n+\n+\tswitch (node-\u003ekind) {\n+\tcase CTLV_SCHEMA_BOOL:\n+\t\treturn ctlv_schema_check_bool(v, node, nest, attr);\n+\tcase CTLV_SCHEMA_STRING:\n+\t\treturn ctlv_schema_check_string(v, node, nest, attr);\n+\tcase CTLV_SCHEMA_BINARY:\n+\t\treturn ctlv_schema_check_binary(v, node, nest, attr);\n+\tcase CTLV_SCHEMA_BLOB:\n+\t\treturn ctlv_schema_check_blob(v, node, attr);\n+\tcase CTLV_SCHEMA_NEST:\n+\t\tif (v-\u003emsg-\u003erequest)\n+\t\t\treturn ctlv_schema_check_indexed_nest(v, pos-\u003etree, pos-\u003enode, attr,\n+\t\t\t\t\t\t\t      depth + 1, nest_index);\n+\t\treturn ctlv_schema_check_nest(v, pos-\u003etree, pos-\u003enode, attr, depth + 1);\n+\tdefault:\n+\t\treturn ctlv_schema_check_integer(v, node, nest, attr);\n+\t}\n+}\n+\n+/* How many times one member occurs, and where the one too many is. */\n+static u32 ctlv_schema_occurrences(const struct ctlv_attr *nest, u64 attr_id, u32 max,\n+\t\t\t\t   const struct ctlv_attr **excess)\n+{\n+\tconst struct ctlv_attr *child = NULL;\n+\tu32 count = 0;\n+\n+\twhile (ctlv_message_next(nest, \u0026child) == CTLV_MESSAGE_STEP_ATTR) {\n+\t\tif (child-\u003eattr_id != attr_id)\n+\t\t\tcontinue;\n+\t\tcount++;\n+\t\tif (max \u0026\u0026 count == max + 1)\n+\t\t\t*excess = child;\n+\t}\n+\treturn count;\n+}\n+\n+/*\n+ * An optional stub makes everything it was filled with optional too: what a\n+ * descendant added cannot be something an ancestor's caller had to send.\n+ */\n+static int ctlv_schema_check_members(struct ctlv_schema_validation *v,\n+\t\t\t\t     const struct ctlv_schema_tree *tree, u32 node,\n+\t\t\t\t     const struct ctlv_attr *nest, bool optional)\n+{\n+\tconst struct ctlv_node_schema *parent = \u0026tree-\u003enode_schemas[node];\n+\tu32 index;\n+\n+\tfor (index = 0; index \u003c parent-\u003echildren_count; index++) {\n+\t\tconst struct ctlv_attr *excess = NULL;\n+\t\tconst struct ctlv_node_schema *child;\n+\t\tu32 count;\n+\n+\t\tchild = \u0026tree-\u003enode_schemas[parent-\u003efirst_child + index];\n+\t\tcount = ctlv_schema_occurrences(nest, child-\u003eattr_id, child-\u003emax_occurrences,\n+\t\t\t\t\t\t\u0026excess);\n+\t\tif (!count) {\n+\t\t\tif (index \u003c parent-\u003erequired_children_count \u0026\u0026 !optional)\n+\t\t\t\treturn ctlv_schema_bad_missing(v, nest, child-\u003eattr_id);\n+\t\t\tcontinue;\n+\t\t}\n+\t\t/* An unlimited placement, which only a reply may hold. */\n+\t\tif (child-\u003emax_occurrences \u0026\u0026 count \u003e child-\u003emax_occurrences)\n+\t\t\treturn ctlv_schema_bad(v, CTLV_VALIDATION_REASON_TOO_MANY_OCCURRENCES, nest,\n+\t\t\t\t\t       excess);\n+\t}\n+\n+\tfor (index = 0; index \u003c tree-\u003estub_schemas_count; index++) {\n+\t\tconst struct ctlv_stub_schema *stub_schema = \u0026tree-\u003estub_schemas[index];\n+\t\tconst struct ctlv_stub_fill_schema *fill_schema;\n+\t\tint ret;\n+\n+\t\tif (stub_schema-\u003enode != node)\n+\t\t\tcontinue;\n+\t\tfill_schema = ctlv_schema_fill(v-\u003emsg-\u003efamily, stub_schema-\u003efamily_id,\n+\t\t\t\t\t       stub_schema-\u003eset_id);\n+\t\tif (!fill_schema)\n+\t\t\tcontinue;\n+\t\tret = ctlv_schema_check_members(v, \u0026fill_schema-\u003emembers, 0, nest,\n+\t\t\t\t\t\toptional || stub_schema-\u003eoptional);\n+\t\tif (ret)\n+\t\t\treturn ret;\n+\t}\n+\treturn 0;\n+}\n+\n+/* Whether one tree places one attr ID anywhere, filled stubs included. */\n+static bool ctlv_schema_tree_declares(const struct ctlv_family *family,\n+\t\t\t\t      const struct ctlv_schema_tree *tree, u64 attr_id)\n+{\n+\tu32 index;\n+\n+\tfor (index = 0; index \u003c tree-\u003enode_schemas_count; index++)\n+\t\tif (tree-\u003enode_schemas[index].attr_id == attr_id)\n+\t\t\treturn true;\n+\tfor (index = 0; index \u003c tree-\u003estub_schemas_count; index++) {\n+\t\tconst struct ctlv_stub_schema *stub_schema = \u0026tree-\u003estub_schemas[index];\n+\t\tconst struct ctlv_stub_fill_schema *fill_schema;\n+\n+\t\tfill_schema = ctlv_schema_fill(family, stub_schema-\u003efamily_id, stub_schema-\u003eset_id);\n+\t\tif (fill_schema \u0026\u0026\n+\t\t    ctlv_schema_tree_declares(family, \u0026fill_schema-\u003emembers, attr_id))\n+\t\t\treturn true;\n+\t}\n+\treturn false;\n+}\n+\n+/* Search every attr ID known anywhere in the effective schema. */\n+static bool ctlv_schema_declares(const struct ctlv_family *family, u64 attr_id)\n+{\n+\tconst struct ctlv_family *owner;\n+\tstruct ctlv_schema_cursor cursor;\n+\tconst struct ctlv_op_schema *op;\n+\n+\tctlv_schema_cursor_init(\u0026cursor, family);\n+\twhile ((op = ctlv_schema_next_op(\u0026cursor, \u0026owner)))\n+\t\tif (ctlv_schema_tree_declares(family, \u0026op-\u003erequest, attr_id) ||\n+\t\t    ctlv_schema_tree_declares(family, \u0026op-\u003ereply, attr_id))\n+\t\t\treturn true;\n+\treturn false;\n+}\n+\n+/*\n+ * Unknown IDs remain reserved unless explicitly ignorable; ignored unknown\n+ * nests are opaque.\n+ */\n+static int ctlv_schema_check_unknown(struct ctlv_schema_validation *v, const struct ctlv_attr *nest,\n+\t\t\t\t     const struct ctlv_attr *attr)\n+{\n+\t/* Which refuses the bit itself on a reply, where it means nothing. */\n+\tif (attr-\u003eflags \u0026 ~ctlv_schema_flags_allowed(v))\n+\t\treturn ctlv_schema_bad(v, CTLV_VALIDATION_REASON_UNKNOWN_FLAG, nest, attr);\n+\tif (!(attr-\u003eflags \u0026 CTLV_ATTR_F_IGNORE_IF_UNKNOWN) ||\n+\t    ctlv_schema_declares(v-\u003emsg-\u003efamily, attr-\u003eattr_id))\n+\t\treturn ctlv_schema_bad(v, CTLV_VALIDATION_REASON_UNKNOWN_ATTR, nest, attr);\n+\treturn 0;\n+}\n+\n+static int ctlv_schema_check_indexed_nest(struct ctlv_schema_validation *v,\n+\t\t\t\t\t  const struct ctlv_schema_tree *tree, u32 node,\n+\t\t\t\t\t  const struct ctlv_attr *nest, u32 depth, u32 *nest_index)\n+{\n+\tstruct ctlv_message_input_index *index = v-\u003emsg-\u003eindex;\n+\tconst struct ctlv_attr *child = NULL;\n+\tconst struct ctlv_attr *split = NULL;\n+\tu64 previous = 0;\n+\tbool previous_valid = false;\n+\tu32 added;\n+\tenum ctlv_message_step step;\n+\tint ret;\n+\n+\tif (depth \u003e CTLV_MAX_NEST_DEPTH)\n+\t\treturn ctlv_schema_bad(v, CTLV_VALIDATION_REASON_NESTING_TOO_DEEP, nest, NULL);\n+\tret = ctlv_schema_index_nest_add(v, tree, node, nest, \u0026added);\n+\tif (ret)\n+\t\treturn ret;\n+\n+\twhile ((step = ctlv_message_next(nest, \u0026child)) == CTLV_MESSAGE_STEP_ATTR) {\n+\t\tstruct ctlv_schema_pos pos;\n+\t\tbool seen;\n+\n+\t\tif (!ctlv_schema_member(v-\u003emsg-\u003efamily, tree, node, child-\u003eattr_id, \u0026pos)) {\n+\t\t\tprevious_valid = false;\n+\t\t\tcontinue;\n+\t\t}\n+\t\tret = ctlv_schema_index_record(v, added, \u0026pos, child, \u0026seen);\n+\t\tif (ret)\n+\t\t\treturn ret;\n+\t\tif (seen \u0026\u0026 (!previous_valid || previous != child-\u003eattr_id) \u0026\u0026 !split)\n+\t\t\tsplit = child;\n+\t\tprevious = child-\u003eattr_id;\n+\t\tprevious_valid = true;\n+\t}\n+\tret = ctlv_schema_index_required(v, added, nest);\n+\tif (ret)\n+\t\treturn ret;\n+\tif (step == CTLV_MESSAGE_STEP_BAD)\n+\t\treturn ctlv_schema_bad(v, CTLV_VALIDATION_REASON_MALFORMED_MESSAGE, nest, NULL);\n+\n+\tchild = NULL;\n+\twhile (ctlv_message_next(nest, \u0026child) == CTLV_MESSAGE_STEP_ATTR) {\n+\t\tstruct ctlv_schema_pos pos;\n+\t\tstruct ctlv_message_input_slot *slot;\n+\t\tu32 child_nest = CTLV_MESSAGE_INPUT_INDEX_NONE;\n+\n+\t\tif (!ctlv_schema_member(v-\u003emsg-\u003efamily, tree, node, child-\u003eattr_id, \u0026pos)) {\n+\t\t\tret = ctlv_schema_check_unknown(v, nest, child);\n+\t\t\tif (ret)\n+\t\t\t\treturn ret;\n+\t\t\tcontinue;\n+\t\t}\n+\t\tif (child == split)\n+\t\t\treturn ctlv_schema_bad(v, CTLV_VALIDATION_REASON_NONCONTIGUOUS_ATTR, nest,\n+\t\t\t\t\t       child);\n+\t\tret = ctlv_schema_check_attr(v, \u0026pos, nest, child, depth, \u0026child_nest);\n+\t\tif (ret)\n+\t\t\treturn ret;\n+\t\tif (child_nest != CTLV_MESSAGE_INPUT_INDEX_NONE) {\n+\t\t\tslot = ctlv_schema_index_slot(v, added, \u0026pos);\n+\t\t\tif (!slot)\n+\t\t\t\treturn -EINVAL;\n+\t\t\tctlv_schema_index_nest_link(index, slot, child_nest);\n+\t\t}\n+\t}\n+\t*nest_index = added;\n+\treturn 0;\n+}\n+\n+/*\n+ * Required members first, then every attr in the order the nest carries them,\n+ * so that what is reported is the first thing a caller has to fix.\n+ */\n+static int ctlv_schema_check_nest(struct ctlv_schema_validation *v,\n+\t\t\t\t  const struct ctlv_schema_tree *tree, u32 node,\n+\t\t\t\t  const struct ctlv_attr *nest, u32 depth)\n+{\n+\tconst struct ctlv_attr *child = NULL;\n+\tenum ctlv_message_step step;\n+\tint ret;\n+\n+\tif (depth \u003e CTLV_MAX_NEST_DEPTH)\n+\t\treturn ctlv_schema_bad(v, CTLV_VALIDATION_REASON_NESTING_TOO_DEEP, nest, NULL);\n+\n+\tret = ctlv_schema_check_members(v, tree, node, nest, false);\n+\tif (ret)\n+\t\treturn ret;\n+\n+\twhile ((step = ctlv_message_next(nest, \u0026child)) == CTLV_MESSAGE_STEP_ATTR) {\n+\t\tstruct ctlv_schema_pos pos;\n+\n+\t\tif (!ctlv_schema_member(v-\u003emsg-\u003efamily, tree, node, child-\u003eattr_id, \u0026pos)) {\n+\t\t\tret = ctlv_schema_check_unknown(v, nest, child);\n+\t\t\tif (ret)\n+\t\t\t\treturn ret;\n+\t\t\t/* Skipped whole: the step past it checked its length. */\n+\t\t\tcontinue;\n+\t\t}\n+\t\tret = ctlv_schema_check_attr(v, \u0026pos, nest, child, depth, NULL);\n+\t\tif (ret)\n+\t\t\treturn ret;\n+\t}\n+\tif (step == CTLV_MESSAGE_STEP_BAD)\n+\t\treturn ctlv_schema_bad(v, CTLV_VALIDATION_REASON_MALFORMED_MESSAGE, nest, NULL);\n+\treturn 0;\n+}\n+\n+int ctlv_schema_validate(struct ctlv_msg *msg, struct ctlv_error *error)\n+{\n+\tstruct ctlv_schema_validation validate = { .msg = msg, .error = error };\n+\tu32 root_index;\n+\tint ret;\n+\n+\tif (!msg-\u003erequest)\n+\t\treturn ctlv_schema_check_nest(\u0026validate, msg-\u003etree, 0, msg-\u003eroot, 0);\n+\tif (WARN_ON_ONCE(msg-\u003eindex))\n+\t\treturn -EINVAL;\n+\tmsg-\u003eindex = kzalloc_obj(*msg-\u003eindex, GFP_KERNEL_ACCOUNT);\n+\tif (!msg-\u003eindex)\n+\t\treturn -ENOMEM;\n+\tret = ctlv_schema_check_indexed_nest(\u0026validate, msg-\u003etree, 0, msg-\u003eroot, 0, \u0026root_index);\n+\tif (ret || WARN_ON_ONCE(root_index)) {\n+\t\tctlv_message_index_free(msg);\n+\t\treturn ret ?: -EINVAL;\n+\t}\n+\treturn 0;\n+}\ndiff --git a/drivers/ctlv/schema.h b/drivers/ctlv/schema.h\nnew file mode 100644\nindex 0000000000000..4552a392da60c\n--- /dev/null\n+++ b/drivers/ctlv/schema.h\n@@ -0,0 +1,50 @@\n+/* SPDX-License-Identifier: GPL-2.0-only */\n+/*\n+ * Copyright (c) 2026, NVIDIA CORPORATION \u0026 AFFILIATES\n+ *\n+ * Private generated-schema walkers.\n+ */\n+#ifndef _CTLV_SCHEMA_H\n+#define _CTLV_SCHEMA_H\n+\n+#include \u003clinux/ctlv_family.h\u003e\n+#include \u003clinux/types.h\u003e\n+\n+struct ctlv_schema_cursor {\n+\tconst struct ctlv_family *target;\n+\tconst struct ctlv_family *family;\n+\tu32 level;\n+\tu32 index;\n+};\n+\n+struct ctlv_schema_pos {\n+\tconst struct ctlv_schema_tree *tree;\n+\tu32 node;\n+};\n+\n+const struct ctlv_family *\n+ctlv_family_ancestor(const struct ctlv_family *family, u32 up);\n+u32 ctlv_family_levels(const struct ctlv_family *family);\n+void ctlv_schema_cursor_init(struct ctlv_schema_cursor *cursor,\n+\t\t\t     const struct ctlv_family *family);\n+const struct ctlv_op_schema *\n+ctlv_schema_next_op(struct ctlv_schema_cursor *cursor,\n+\t\t    const struct ctlv_family **family);\n+const struct ctlv_stub_fill_schema *\n+ctlv_schema_fill(const struct ctlv_family *family, u16 family_id,\n+\t\t u32 set_id);\n+int ctlv_schema_op_sizes(const struct ctlv_family *family,\n+\t\t\t const struct ctlv_op_schema *op,\n+\t\t\t struct ctlv_op_sizes *sizes);\n+bool ctlv_schema_member(const struct ctlv_family *family,\n+\t\t\tconst struct ctlv_schema_tree *tree, u32 node,\n+\t\t\tu64 attr_id, struct ctlv_schema_pos *member);\n+bool ctlv_schema_value_ok(const struct ctlv_node_schema *node, u64 value);\n+bool ctlv_schema_length_ok(const struct ctlv_node_schema *node, u32 len);\n+\n+struct ctlv_error;\n+struct ctlv_msg;\n+\n+int ctlv_schema_validate(struct ctlv_msg *msg, struct ctlv_error *error);\n+\n+#endif /* _CTLV_SCHEMA_H */\ndiff --git a/drivers/virt/coco/tdx-guest/tdx-guest.c b/drivers/virt/coco/tdx-guest/tdx-guest.c\nindex d0303e31e8161..0d53170602463 100644\n--- a/drivers/virt/coco/tdx-guest/tdx-guest.c\n+++ b/drivers/virt/coco/tdx-guest/tdx-guest.c\n@@ -19,6 +19,7 @@\n #include \u003clinux/sockptr.h\u003e\n #include \u003clinux/tsm.h\u003e\n #include \u003clinux/tsm-mr.h\u003e\n+#include \u003clinux/tdx-guest.h\u003e\n \n #include \u003cuapi/linux/tdx-guest.h\u003e\n \n@@ -27,10 +28,21 @@\n \n /* TDREPORT buffer */\n static u8 *tdx_report_buf;\n+static struct tdx_guest_info tdx_guest_info;\n+static struct miscdevice tdx_misc_dev;\n+\n+static_assert(TDX_REPORTDATA_LEN == TDX_GUEST_REPORTDATA_LEN);\n+static_assert(TDX_REPORT_LEN == TDX_GUEST_REPORT_LEN);\n \n /* Lock to serialize TDG.MR.REPORT and TDG.MR.RTMR.EXTEND TDCALLs */\n static DEFINE_MUTEX(mr_lock);\n \n+/* Serializes native client registration and service attachment. */\n+static DEFINE_MUTEX(client_lock);\n+static const struct tdx_guest_client *tdx_client;\n+static void *tdx_client_priv;\n+static bool tdx_service_ready;\n+\n /* TDREPORT fields */\n enum {\n \tTDREPORT_reportdata = 128,\n@@ -49,24 +61,30 @@ enum {\n \tTDREPORT_servtd_hash = TDREPORT_rtmr3 + SHA384_DIGEST_SIZE,\n };\n \n-static int tdx_do_report(sockptr_t data, sockptr_t tdreport)\n+static int __tdx_do_report(sockptr_t data, sockptr_t tdreport)\n {\n-\tscoped_cond_guard(mutex_intr, return -EINTR, \u0026mr_lock) {\n-\t\tu8 *reportdata = tdx_report_buf + TDREPORT_reportdata;\n-\t\tint ret;\n+\tu8 *reportdata = tdx_report_buf + TDREPORT_reportdata;\n+\tint ret;\n \n-\t\tif (!sockptr_is_null(data) \u0026\u0026\n-\t\t    copy_from_sockptr(reportdata, data, TDX_REPORTDATA_LEN))\n-\t\t\treturn -EFAULT;\n+\tlockdep_assert_held(\u0026mr_lock);\n+\tif (!sockptr_is_null(data) \u0026\u0026\n+\t    copy_from_sockptr(reportdata, data, TDX_REPORTDATA_LEN))\n+\t\treturn -EFAULT;\n \n-\t\tret = tdx_mcall_get_report0(reportdata, tdx_report_buf);\n-\t\tif (WARN_ONCE(ret, \"tdx_mcall_get_report0() failed: %d\", ret))\n-\t\t\treturn ret;\n+\tret = tdx_mcall_get_report0(reportdata, tdx_report_buf);\n+\tif (WARN_ONCE(ret, \"tdx_mcall_get_report0() failed: %d\", ret))\n+\t\treturn ret;\n \n-\t\tif (!sockptr_is_null(tdreport) \u0026\u0026\n-\t\t    copy_to_sockptr(tdreport, tdx_report_buf, TDX_REPORT_LEN))\n-\t\t\treturn -EFAULT;\n-\t}\n+\tif (!sockptr_is_null(tdreport) \u0026\u0026\n+\t    copy_to_sockptr(tdreport, tdx_report_buf, TDX_REPORT_LEN))\n+\t\treturn -EFAULT;\n+\treturn 0;\n+}\n+\n+static int tdx_do_report(sockptr_t data, sockptr_t tdreport)\n+{\n+\tscoped_cond_guard(mutex_intr, return -EINTR, \u0026mr_lock)\n+\t\treturn __tdx_do_report(data, tdreport);\n \treturn 0;\n }\n \n@@ -90,6 +108,76 @@ static int tdx_do_extend(u8 mr_ind, const u8 *data)\n \treturn 0;\n }\n \n+static bool tdx_guest_device_valid(struct device *dev)\n+{\n+\treturn dev \u0026\u0026 dev == tdx_misc_dev.this_device;\n+}\n+\n+static const struct tdx_guest_info *tdx_guest_info_get(struct device *dev)\n+{\n+\treturn tdx_guest_device_valid(dev) ? \u0026tdx_guest_info : NULL;\n+}\n+\n+static int tdx_guest_report_get(struct device *dev, const u8 *reportdata,\n+\t\t\t\tsize_t length, void *out, size_t capacity,\n+\t\t\t\tsize_t *out_length)\n+{\n+\tint ret;\n+\n+\tif (!tdx_guest_device_valid(dev))\n+\t\treturn -ENODEV;\n+\tif (!reportdata || length != TDX_REPORTDATA_LEN || !out || !out_length)\n+\t\treturn -EINVAL;\n+\tif (capacity \u003c TDX_REPORT_LEN)\n+\t\treturn -EMSGSIZE;\n+\tscoped_cond_guard(mutex_intr, return -EINTR, \u0026mr_lock) {\n+\t\tret = __tdx_do_report(KERNEL_SOCKPTR((void *)reportdata),\n+\t\t\t\t      KERNEL_SOCKPTR(NULL));\n+\t\tif (ret)\n+\t\t\treturn ret;\n+\t\tmemcpy(out, tdx_report_buf, TDX_REPORT_LEN);\n+\t}\n+\t*out_length = TDX_REPORT_LEN;\n+\treturn 0;\n+}\n+\n+static int tdx_guest_mr_read(struct device *dev, enum tdx_guest_mr mr,\n+\t\t\t     u8 value[SHA384_DIGEST_SIZE])\n+{\n+\tstatic const size_t offsets[] = {\n+\t\t[TDX_GUEST_MR_MRTD] = TDREPORT_mrtd,\n+\t\t[TDX_GUEST_MR_RTMR0] = TDREPORT_rtmr0,\n+\t\t[TDX_GUEST_MR_RTMR1] = TDREPORT_rtmr1,\n+\t\t[TDX_GUEST_MR_RTMR2] = TDREPORT_rtmr2,\n+\t\t[TDX_GUEST_MR_RTMR3] = TDREPORT_rtmr3,\n+\t};\n+\tint ret;\n+\n+\tif (!tdx_guest_device_valid(dev))\n+\t\treturn -ENODEV;\n+\tif (mr \u003e= ARRAY_SIZE(offsets) || !value)\n+\t\treturn -EINVAL;\n+\tscoped_cond_guard(mutex_intr, return -EINTR, \u0026mr_lock) {\n+\t\tret = __tdx_do_report(KERNEL_SOCKPTR(NULL),\n+\t\t\t\t      KERNEL_SOCKPTR(NULL));\n+\t\tif (ret)\n+\t\t\treturn ret;\n+\t\tmemcpy(value, tdx_report_buf + offsets[mr],\n+\t\t       SHA384_DIGEST_SIZE);\n+\t}\n+\treturn 0;\n+}\n+\n+static int tdx_guest_rtmr_extend(struct device *dev, unsigned int rtmr,\n+\t\t\t\t const u8 value[SHA384_DIGEST_SIZE])\n+{\n+\tif (!tdx_guest_device_valid(dev))\n+\t\treturn -ENODEV;\n+\tif (rtmr \u003e= 4 || !value)\n+\t\treturn -EINVAL;\n+\treturn tdx_do_extend(rtmr, value);\n+}\n+\n #define TDX_MR_(r) .mr_value = (void *)TDREPORT_##r, TSM_MR_(r, SHA384)\n static struct tsm_measurement_register tdx_mrs[] = {\n \t{ TDX_MR_(rtmr0) | TSM_MR_F_RTMR },\n@@ -135,6 +223,12 @@ static const struct attribute_group *tdx_mr_init(void)\n \trc = tdx_mr_refresh(\u0026tdx_measurements);\n \tif (rc)\n \t\treturn ERR_PTR(rc);\n+\tmemcpy(tdx_guest_info.mrconfigid,\n+\t       buf + TDREPORT_mrconfigid, SHA384_DIGEST_SIZE);\n+\tmemcpy(tdx_guest_info.mrowner,\n+\t       buf + TDREPORT_mrowner, SHA384_DIGEST_SIZE);\n+\tmemcpy(tdx_guest_info.mrownerconfig,\n+\t       buf + TDREPORT_mrownerconfig, SHA384_DIGEST_SIZE);\n \n \t/*\n \t * @mr_value was initialized with the offset only, while the base\n@@ -191,6 +285,8 @@ struct tdx_quote_buf {\n \tu8 data[];\n };\n \n+static_assert(TDX_QUOTE_MAX_LEN == TDX_GUEST_QUOTE_MAX_LEN);\n+\n /* Quote data buffer */\n static void *quote_data;\n \n@@ -265,15 +361,18 @@ static int wait_for_quote_completion(struct tdx_quote_buf *quote_buf, u32 timeou\n \treturn (i == timeout) ? -ETIMEDOUT : 0;\n }\n \n-static int tdx_report_new_locked(struct tsm_report *report, void *data)\n+static int __tdx_guest_quote_get(const u8 *reportdata, size_t length,\n+\t\t\t\t void *out, size_t capacity,\n+\t\t\t\t size_t *out_length)\n {\n-\tu8 *buf;\n \tstruct tdx_quote_buf *quote_buf = quote_data;\n-\tstruct tsm_report_desc *desc = \u0026report-\u003edesc;\n \tu32 out_len;\n \tint ret;\n \tu64 err;\n \n+\tlockdep_assert_held(\u0026quote_lock);\n+\tif (!reportdata || length != TDX_REPORTDATA_LEN || !out || !out_length)\n+\t\treturn -EINVAL;\n \t/*\n \t * If the previous request is timedout or interrupted, and the\n \t * Quote buf status is still in GET_QUOTE_IN_FLIGHT (owned by\n@@ -282,16 +381,13 @@ static int tdx_report_new_locked(struct tsm_report *report, void *data)\n \tif (quote_buf-\u003estatus == GET_QUOTE_IN_FLIGHT)\n \t\treturn -EBUSY;\n \n-\tif (desc-\u003einblob_len != TDX_REPORTDATA_LEN)\n-\t\treturn -EINVAL;\n-\n \tmemset(quote_data, 0, GET_QUOTE_BUF_SIZE);\n \n \t/* Update Quote buffer header */\n \tquote_buf-\u003eversion = GET_QUOTE_CMD_VER;\n \tquote_buf-\u003ein_len = TDX_REPORT_LEN;\n \n-\tret = tdx_do_report(KERNEL_SOCKPTR(desc-\u003einblob),\n+\tret = tdx_do_report(KERNEL_SOCKPTR((void *)reportdata),\n \t\t\t    KERNEL_SOCKPTR(quote_buf-\u003edata));\n \tif (ret)\n \t\treturn ret;\n@@ -317,13 +413,10 @@ static int tdx_report_new_locked(struct tsm_report *report, void *data)\n \n \tif (out_len \u003e TDX_QUOTE_MAX_LEN)\n \t\treturn -EFBIG;\n-\n-\tbuf = kvmemdup(quote_buf-\u003edata, out_len, GFP_KERNEL);\n-\tif (!buf)\n-\t\treturn -ENOMEM;\n-\n-\treport-\u003eoutblob = buf;\n-\treport-\u003eoutblob_len = out_len;\n+\tif (out_len \u003e capacity)\n+\t\treturn -EMSGSIZE;\n+\tmemcpy(out, quote_buf-\u003edata, out_len);\n+\t*out_length = out_len;\n \n \t/*\n \t * TODO: parse the PEM-formatted cert chain out of the quote buffer when\n@@ -333,6 +426,39 @@ static int tdx_report_new_locked(struct tsm_report *report, void *data)\n \treturn ret;\n }\n \n+static int tdx_guest_quote_get(struct device *dev, const u8 *reportdata,\n+\t\t\t       size_t length, void *out, size_t capacity,\n+\t\t\t       size_t *out_length)\n+{\n+\tif (!tdx_guest_device_valid(dev))\n+\t\treturn -ENODEV;\n+\tscoped_cond_guard(mutex_intr, return -EINTR, \u0026quote_lock)\n+\t\treturn __tdx_guest_quote_get(reportdata, length, out,\n+\t\t\t\t\t     capacity, out_length);\n+\treturn 0;\n+}\n+\n+static int tdx_report_new_locked(struct tsm_report *report, void *data)\n+{\n+\tstruct tsm_report_desc *desc = \u0026report-\u003edesc;\n+\tsize_t length;\n+\tvoid *buf;\n+\tint ret;\n+\n+\tbuf = kvmalloc(TDX_QUOTE_MAX_LEN, GFP_KERNEL);\n+\tif (!buf)\n+\t\treturn -ENOMEM;\n+\tret = __tdx_guest_quote_get(desc-\u003einblob, desc-\u003einblob_len,\n+\t\t\t\t    buf, TDX_QUOTE_MAX_LEN, \u0026length);\n+\tif (ret) {\n+\t\tkvfree(buf);\n+\t\treturn ret;\n+\t}\n+\treport-\u003eoutblob = buf;\n+\treport-\u003eoutblob_len = length;\n+\treturn 0;\n+}\n+\n static int tdx_report_new(struct tsm_report *report, void *data)\n {\n \tscoped_cond_guard(mutex_intr, return -EINTR, \u0026quote_lock)\n@@ -402,6 +528,68 @@ static const struct tsm_report_ops tdx_tsm_ops = {\n \t.report_bin_attr_visible = tdx_report_bin_attr_visible,\n };\n \n+static const struct tdx_guest_ops tdx_guest_ops = {\n+\t.info_get = tdx_guest_info_get,\n+\t.report_get = tdx_guest_report_get,\n+\t.quote_get = tdx_guest_quote_get,\n+\t.mr_read = tdx_guest_mr_read,\n+\t.rtmr_extend = tdx_guest_rtmr_extend,\n+};\n+\n+static bool tdx_client_attached;\n+\n+static int tdx_guest_client_attach(void)\n+{\n+\tvoid *priv;\n+\n+\tlockdep_assert_held(\u0026client_lock);\n+\tif (!tdx_client || !tdx_service_ready)\n+\t\treturn 0;\n+\tpriv = tdx_client-\u003eadd(tdx_misc_dev.this_device, \u0026tdx_guest_ops);\n+\tif (IS_ERR(priv))\n+\t\treturn PTR_ERR(priv);\n+\ttdx_client_priv = priv;\n+\ttdx_client_attached = true;\n+\treturn 0;\n+}\n+\n+static void tdx_guest_client_detach(void)\n+{\n+\tlockdep_assert_held(\u0026client_lock);\n+\tif (!tdx_client_attached)\n+\t\treturn;\n+\ttdx_client-\u003eremove(tdx_client_priv);\n+\ttdx_client_priv = NULL;\n+\ttdx_client_attached = false;\n+}\n+\n+int tdx_guest_client_register(const struct tdx_guest_client *client)\n+{\n+\tint ret;\n+\n+\tif (!client || !client-\u003eadd || !client-\u003eremove)\n+\t\treturn -EINVAL;\n+\tguard(mutex)(\u0026client_lock);\n+\tif (tdx_client)\n+\t\treturn -EBUSY;\n+\ttdx_client = client;\n+\tret = tdx_guest_client_attach();\n+\tif (ret)\n+\t\ttdx_client = NULL;\n+\treturn ret;\n+}\n+EXPORT_SYMBOL_NS_GPL(tdx_guest_client_register, \"TDX_GUEST\");\n+\n+void tdx_guest_client_unregister(const struct tdx_guest_client *client)\n+{\n+\tguard(mutex)(\u0026client_lock);\n+\tif (WARN_ON_ONCE(client != tdx_client))\n+\t\treturn;\n+\ttdx_guest_client_detach();\n+\ttdx_client = NULL;\n+}\n+EXPORT_SYMBOL_NS_GPL(tdx_guest_client_unregister, \"TDX_GUEST\");\n+\n static int __init tdx_guest_init(void)\n {\n \tint ret;\n@@ -427,9 +615,19 @@ static int __init tdx_guest_init(void)\n \tret = tsm_report_register(\u0026tdx_tsm_ops, NULL);\n \tif (ret)\n \t\tgoto free_quote;\n+\tscoped_guard(mutex, \u0026client_lock) {\n+\t\ttdx_service_ready = true;\n+\t\tret = tdx_guest_client_attach();\n+\t\tif (ret)\n+\t\t\ttdx_service_ready = false;\n+\t}\n+\tif (ret)\n+\t\tgoto unregister_tsm;\n \n \treturn 0;\n \n+unregister_tsm:\n+\ttsm_report_unregister(\u0026tdx_tsm_ops);\n free_quote:\n \tfree_quote_buf(quote_data);\n free_misc:\n@@ -443,6 +641,10 @@ module_init(tdx_guest_init);\n \n static void __exit tdx_guest_exit(void)\n {\n+\tscoped_guard(mutex, \u0026client_lock) {\n+\t\ttdx_guest_client_detach();\n+\t\ttdx_service_ready = false;\n+\t}\n \ttsm_report_unregister(\u0026tdx_tsm_ops);\n \tfree_quote_buf(quote_data);\n \tmisc_deregister(\u0026tdx_misc_dev);\ndiff --git a/include/linux/attestation.h b/include/linux/attestation.h\nnew file mode 100644\nindex 0000000000000..0fd806ea77d8d\n--- /dev/null\n+++ b/include/linux/attestation.h\n@@ -0,0 +1,138 @@\n+/* SPDX-License-Identifier: GPL-2.0-only */\n+#ifndef _LINUX_ATTESTATION_H\n+#define _LINUX_ATTESTATION_H\n+\n+#include \u003ccrypto/hash.h\u003e\n+#include \u003clinux/types.h\u003e\n+\n+#include \u003cuapi/linux/ctlv_attestation_gen.h\u003e\n+#include \u003cuapi/linux/hash_info.h\u003e\n+\n+struct attestation;\n+struct ctlv_blob;\n+\n+/**\n+ * struct attestation_digest - One MR digest.\n+ * @algorithm: hash algorithm\n+ * @data: digest bytes\n+ */\n+struct attestation_digest {\n+\tenum hash_algo algorithm;\n+\tu8 data[HASH_MAX_DIGESTSIZE];\n+};\n+\n+/**\n+ * struct attestation_digest_set - Digests ordered as the MR algorithms.\n+ * @values_count: number of digests\n+ * @values: digest array\n+ */\n+struct attestation_digest_set {\n+\tsize_t values_count;\n+\tstruct attestation_digest *values;\n+};\n+\n+/**\n+ * struct attestation_mr_props - Immutable MR properties.\n+ * @id: provider-unique MR ID\n+ * @name: MR name\n+ * @algorithms: ordered hash algorithms\n+ * @algorithms_count: number of algorithms\n+ * @has_register_index: whether @register_index is valid\n+ * @register_index: native register index\n+ * @readable: MR can be read\n+ * @extendable: MR can be extended\n+ */\n+struct attestation_mr_props {\n+\tunsigned int id;\n+\tconst char *name;\n+\tconst enum hash_algo *algorithms;\n+\tsize_t algorithms_count;\n+\tbool has_register_index;\n+\tunsigned int register_index;\n+\tbool readable;\n+\tbool extendable;\n+};\n+\n+/**\n+ * struct attestation_evidence_supported_object - Evidence output description.\n+ * @format: evidence format name\n+ * @max_length: maximum output bytes\n+ * @binds_mrs: evidence validity depends on MR state\n+ */\n+struct attestation_evidence_supported_object {\n+\tconst char *format;\n+\tsize_t max_length;\n+\tbool binds_mrs;\n+};\n+\n+/**\n+ * struct attestation_evidence_caps - Immutable evidence capabilities.\n+ * @min_challenge_length: minimum challenge bytes\n+ * @max_challenge_length: maximum challenge bytes\n+ * @max_total_output_length: maximum bytes across all objects\n+ * @objects: supported evidence objects\n+ * @objects_count: number of objects\n+ */\n+struct attestation_evidence_caps {\n+\tsize_t min_challenge_length;\n+\tsize_t max_challenge_length;\n+\tsize_t max_total_output_length;\n+\tconst struct attestation_evidence_supported_object *objects;\n+\tsize_t objects_count;\n+};\n+\n+/**\n+ * struct attestation_evidence_object_request - One resolved output object.\n+ * @supported_object: matching capability entry\n+ * @output: resolved output blob\n+ */\n+struct attestation_evidence_object_request {\n+\tconst struct attestation_evidence_supported_object *supported_object;\n+\tstruct ctlv_blob *output;\n+};\n+\n+/**\n+ * struct attestation_evidence_request - Validated evidence request.\n+ * @challenge: challenge bytes\n+ * @challenge_length: challenge length\n+ * @objects: requested output objects\n+ * @objects_count: number of objects\n+ */\n+struct attestation_evidence_request {\n+\tconst u8 *challenge;\n+\tsize_t challenge_length;\n+\tconst struct attestation_evidence_object_request *objects;\n+\tsize_t objects_count;\n+};\n+\n+/**\n+ * struct attestation_evidence_result - Provider evidence result.\n+ * @object_lengths: produced length for every requested object\n+ */\n+struct attestation_evidence_result {\n+\tsize_t *object_lengths;\n+};\n+\n+/**\n+ * struct attestation_provider - Immutable provider operations and properties.\n+ * @evidence_get: produce requested evidence\n+ * @mr_read: read one MR\n+ * @mr_extend: extend one MR\n+ * @evidence_caps: evidence capabilities, or NULL\n+ * @mrs: fixed MR properties\n+ * @mrs_count: number of fixed MRs\n+ */\n+struct attestation_provider {\n+\tint (*evidence_get)(struct attestation *att,\n+\t\t\t    const struct attestation_evidence_request *request,\n+\t\t\t    struct attestation_evidence_result *result);\n+\tint (*mr_read)(struct attestation *att, unsigned int mr_id,\n+\t\t       struct attestation_digest_set *values);\n+\tint (*mr_extend)(struct attestation *att, unsigned int mr_id,\n+\t\t\t const struct attestation_digest_set *values);\n+\tconst struct attestation_evidence_caps *evidence_caps;\n+\tconst struct attestation_mr_props *mrs;\n+\tsize_t mrs_count;\n+};\n+\n+#endif /* _LINUX_ATTESTATION_H */\ndiff --git a/include/linux/ctlv.h b/include/linux/ctlv.h\nnew file mode 100644\nindex 0000000000000..5f59acac7dc44\n--- /dev/null\n+++ b/include/linux/ctlv.h\n@@ -0,0 +1,249 @@\n+/* SPDX-License-Identifier: GPL-2.0-only */\n+/*\n+ * Copyright (c) 2026, NVIDIA CORPORATION \u0026 AFFILIATES\n+ *\n+ * CTLV family API.\n+ */\n+#ifndef _LINUX_CTLV_H\n+#define _LINUX_CTLV_H\n+\n+#include \u003clinux/types.h\u003e\n+\n+#include \u003cuapi/linux/ctlv.h\u003e\n+\n+struct ctlv_device;\n+struct ctlv_family;\n+struct ctlv_msg;\n+struct ctlv_op_ctx;\n+struct ctlv_schema_tree;\n+\n+/**\n+ * struct ctlv_cursor - One attr position in one message.\n+ * @msg: the message this position is in, core-private bookkeeping\n+ * @attr: the attr itself, or NULL when a lookup found nothing\n+ * @parent: reading, the nest containing @attr, NULL at the root\n+ * @up: writing, cursor of the nest containing @attr, NULL at the root. The\n+ *\tchain of them is the open-nest stack\n+ * @start: writing, where @attr begins in the message. An append reaches what\n+ *\tit lengthens through the buffer rather than through @attr, that buffer\n+ *\tbeing the core's own\n+ * @tree: schema tree the node belongs to, which is a fill's own tree for an\n+ *\tattr that arrived through one\n+ * @node: index of the node within @tree\n+ * @depth: nesting levels above this position, the root being zero\n+ * @index_nest_scope: schema scope used to read members of the physical nest\n+ * @index_scope: core-private schema scope containing this attr\n+ *\n+ * Fixed-size, so family code can put a child cursor on the stack. The members\n+ * belong to the core: a family reaches a message through what was generated\n+ * for the op it answers. One direction at a time, a helper of the other\n+ * direction refusing the cursor.\n+ */\n+struct ctlv_cursor {\n+\tstruct ctlv_msg *msg;\n+\tconst struct ctlv_attr *attr;\n+\tconst struct ctlv_attr *parent;\n+\tstruct ctlv_cursor *up;\n+\tsize_t start;\n+\tconst struct ctlv_schema_tree *tree;\n+\tu32 node;\n+\tu32 depth;\n+\tu32 index_nest_scope;\n+\tu32 index_scope;\n+};\n+\n+/**\n+ * ctlv_priv_parent - Get the direct parent family private data.\n+ * @priv: core-allocated private data passed to a family callback\n+ *\n+ * Return: parent private data, or NULL for the root family.\n+ */\n+void *ctlv_priv_parent(const void *priv);\n+\n+/**\n+ * ctlv_priv_child - Get the direct child family private data.\n+ * @priv: core-allocated private data passed to a family callback\n+ *\n+ * Return: child private data, or NULL for the device family.\n+ */\n+void *ctlv_priv_child(const void *priv);\n+\n+struct device;\n+\n+/**\n+ * ctlv_device_parent - Get the backing device.\n+ * @ctlvdev: CTLV device\n+ *\n+ * Return: backing device passed to ctlv_create().\n+ */\n+struct device *ctlv_device_parent(const struct ctlv_device *ctlvdev);\n+\n+/**\n+ * ctlv_create - Create and register a CTLV device.\n+ * @parent_dev: backing device\n+ * @family: device family\n+ * @init_info: family initialization data\n+ *\n+ * Return: CTLV device, or an error pointer.\n+ */\n+struct ctlv_device *ctlv_create(struct device *parent_dev,\n+\t\t\t\tconst struct ctlv_family *family,\n+\t\t\t\tconst void *init_info);\n+\n+/**\n+ * ctlv_destroy - Unregister and destroy a CTLV device.\n+ * @ctlvdev: CTLV device\n+ */\n+void ctlv_destroy(struct ctlv_device *ctlvdev);\n+\n+/**\n+ * ctlv_nest_end - Finish an output nest.\n+ * @child: nest cursor returned by a generated start helper\n+ */\n+void ctlv_nest_end(struct ctlv_cursor *child);\n+\n+/**\n+ * ctlv_stub_fill - Delegate an extension-point output nest.\n+ * @ctx: operation context\n+ * @request: validated request root\n+ * @nest: output nest selected by the generated helper\n+ *\n+ * Return: filling callback result, or 0 for an unfilled point.\n+ */\n+int ctlv_stub_fill(struct ctlv_op_ctx *ctx, const struct ctlv_cursor *request,\n+\t\t   struct ctlv_cursor *nest);\n+\n+/**\n+ * ctlv_op_error - Record an operation error message.\n+ * @ctx: operation context\n+ * @error: negative error to return\n+ * @message: message copied into the operation result\n+ *\n+ * Return: @error, or -EINVAL if @error is invalid.\n+ */\n+int ctlv_op_error(struct ctlv_op_ctx *ctx, int error, const char *message);\n+\n+/**\n+ * ctlv_op_errorf - Format an operation error message.\n+ * @ctx: operation context\n+ * @error: negative error to return\n+ * @fmt: printf format and arguments\n+ *\n+ * Return: @error, or -EINVAL if @error is invalid.\n+ */\n+__printf(3, 4)\n+int ctlv_op_errorf(struct ctlv_op_ctx *ctx, int error, const char *fmt, ...);\n+\n+/*\n+ * The core retains no query state. A continuation repeats the request and\n+ * passes back the family's generation and nonzero cursor. It fails with\n+ * -ESTALE if the generation changed. Each fragment must complete a logical\n+ * leaf and return a cursor different from its input.\n+ *\n+ * ctlv_op_query_more() marks still-open nests, whose cursors must remain live.\n+ */\n+/**\n+ * ctlv_op_query_generation - Get a query continuation generation.\n+ * @ctx: query operation context\n+ *\n+ * Return: generation supplied by the previous fragment, or zero initially.\n+ */\n+u64 ctlv_op_query_generation(const struct ctlv_op_ctx *ctx);\n+\n+/**\n+ * ctlv_op_query_cursor - Get a query continuation cursor.\n+ * @ctx: query operation context\n+ *\n+ * Return: cursor supplied by the previous fragment, or zero initially.\n+ */\n+u64 ctlv_op_query_cursor(const struct ctlv_op_ctx *ctx);\n+\n+/**\n+ * ctlv_op_query_more - Complete a query fragment with more data pending.\n+ * @ctx: query operation context\n+ * @generation: current data generation\n+ * @next_cursor: nonzero cursor for the next fragment\n+ *\n+ * Return: 0, or a negative error.\n+ */\n+int ctlv_op_query_more(struct ctlv_op_ctx *ctx, u64 generation,\n+\t\t       u64 next_cursor);\n+\n+/**\n+ * ctlv_op_query_done - Complete the last query fragment.\n+ * @ctx: query operation context\n+ * @generation: current data generation\n+ *\n+ * Return: 0, or a negative error.\n+ */\n+int ctlv_op_query_done(struct ctlv_op_ctx *ctx, u64 generation);\n+\n+struct ctlv_blob;\n+\n+/**\n+ * ctlv_blob_put - Release a resolved blob.\n+ * @blob: blob returned by a generated resolve helper\n+ *\n+ * Return: 0, or a negative error.\n+ */\n+int ctlv_blob_put(struct ctlv_blob *blob);\n+\n+/**\n+ * ctlv_blob_len - Get a resolved blob's length.\n+ * @blob: resolved blob\n+ *\n+ * Return: blob length in bytes.\n+ */\n+u64 ctlv_blob_len(const struct ctlv_blob *blob);\n+\n+/**\n+ * ctlv_blob_read - Copy bytes from a resolved input blob.\n+ * @blob: resolved blob\n+ * @offset: byte offset\n+ * @dst: destination buffer\n+ * @len: number of bytes\n+ *\n+ * Return: 0, or a negative error.\n+ */\n+int ctlv_blob_read(struct ctlv_blob *blob, u64 offset, void *dst, size_t len);\n+\n+/**\n+ * ctlv_blob_write - Copy bytes to a resolved output blob.\n+ * @blob: resolved blob\n+ * @offset: byte offset\n+ * @src: source buffer\n+ * @len: number of bytes\n+ *\n+ * Return: 0, or a negative error.\n+ */\n+int ctlv_blob_write(struct ctlv_blob *blob, u64 offset, const void *src,\n+\t\t    size_t len);\n+\n+/**\n+ * ctlv_event_lost - Report an event that could not be created.\n+ * @ctlvdev: CTLV device\n+ * @op_id: event operation ID\n+ *\n+ * This does not allocate or sleep. It is not for interrupt context.\n+ */\n+void ctlv_event_lost(struct ctlv_device *ctlvdev, u64 op_id);\n+\n+/**\n+ * ctlv_event_emit - Validate and publish a completed event.\n+ * @ctx: context returned by a generated event create helper\n+ *\n+ * This consumes @ctx. It is not for interrupt context.\n+ *\n+ * Return: 0, or a negative error.\n+ */\n+int ctlv_event_emit(struct ctlv_op_ctx *ctx);\n+\n+/**\n+ * ctlv_event_abort - Discard an event under construction.\n+ * @ctx: context returned by a generated event create helper\n+ *\n+ * This consumes @ctx. It is not for interrupt context.\n+ */\n+void ctlv_event_abort(struct ctlv_op_ctx *ctx);\n+\n+#endif /* _LINUX_CTLV_H */\ndiff --git a/include/linux/ctlv_family.h b/include/linux/ctlv_family.h\nnew file mode 100644\nindex 0000000000000..66e62733f9057\n--- /dev/null\n+++ b/include/linux/ctlv_family.h\n@@ -0,0 +1,551 @@\n+/* SPDX-License-Identifier: GPL-2.0-only */\n+/*\n+ * Copyright (c) 2026, NVIDIA CORPORATION \u0026 AFFILIATES\n+ *\n+ * CTLV family metadata and generated-code support.\n+ */\n+#ifndef _LINUX_CTLV_FAMILY_H\n+#define _LINUX_CTLV_FAMILY_H\n+\n+#include \u003clinux/ctlv.h\u003e\n+#include \u003clinux/gfp_types.h\u003e\n+#include \u003clinux/kobject.h\u003e\n+#include \u003clinux/types.h\u003e\n+\n+#include \u003cuapi/linux/ctlv.h\u003e\n+\n+/* op-schema-get needs one level to describe the declared schema. */\n+#define CTLV_MAX_DECLARED_NEST_DEPTH (CTLV_MAX_NEST_DEPTH - 1)\n+\n+struct ctlv_node_schema {\n+\tu64 attr_id;\n+\tu8 kind;\n+\tu8 unit;\n+\ts8 scale;\n+\tbool reenters;\n+\tu32 max_occurrences;\n+\tu32 first_child;\n+\tu32 children_count;\n+\tu32 required_children_count;\n+\tunion {\n+\t\tstruct {\n+\t\t\tu64 min;\n+\t\t\tu64 max;\n+\t\t} range;\n+\t\tu64 flags_mask;\n+\t\tstruct {\n+\t\t\tu32 min_len;\n+\t\t\tu32 max_len;\n+\t\t} length;\n+\t\tstruct {\n+\t\t\tu64 max_len;\n+\t\t\tu32 alignment;\n+\t\t\tu16 backings;\n+\t\t\tu8 direction;\n+\t\t} blob;\n+\t};\n+};\n+\n+#define CTLV_NODE_SCHEMA_UNLIMITED 0\n+\n+#define __CTLV_NODE_SCHEMA(_attr, _kind, _occurrences, ...)\t\\\n+\t{ .attr_id = (_attr), .kind = (_kind),\t\t\t\\\n+\t  .max_occurrences = (_occurrences), __VA_ARGS__ }\n+\n+#define __CTLV_NODE_SCHEMA_CHILDREN(_first, _count, _required)\t\\\n+\t.first_child = (_first), .children_count = (_count),\t\\\n+\t.required_children_count = (_required)\n+\n+#define CTLV_NODE_SCHEMA_ROOT(_first, _count, _required)\t\\\n+\t__CTLV_NODE_SCHEMA(CTLV_ATTR_ROOT, CTLV_SCHEMA_NEST, 1,\t\\\n+\t\t\t   __CTLV_NODE_SCHEMA_CHILDREN(_first, _count, _required))\n+\n+#define CTLV_NODE_SCHEMA_NEST(_attr, _occurrences, _first, _count, _required) \\\n+\t__CTLV_NODE_SCHEMA(_attr, CTLV_SCHEMA_NEST, _occurrences,\t\\\n+\t\t\t   __CTLV_NODE_SCHEMA_CHILDREN(_first, _count, _required))\n+\n+#define CTLV_NODE_SCHEMA_NEST_REENTERS(_attr, _occurrences, _first, _count, _required) \\\n+\t__CTLV_NODE_SCHEMA(_attr, CTLV_SCHEMA_NEST, _occurrences,\t\\\n+\t\t\t   .reenters = true,\t\t\t\t\\\n+\t\t\t   __CTLV_NODE_SCHEMA_CHILDREN(_first, _count, _required))\n+\n+#define CTLV_NODE_SCHEMA_UINT(_attr, _occurrences, _min, _max)\t\\\n+\t__CTLV_NODE_SCHEMA(_attr, CTLV_SCHEMA_UINT, _occurrences,\t\\\n+\t\t\t   .range = { .min = (_min), .max = (_max) })\n+\n+#define CTLV_NODE_SCHEMA_UINT_UNIT(_attr, _occurrences, _min, _max, _unit, _scale) \\\n+\t__CTLV_NODE_SCHEMA(_attr, CTLV_SCHEMA_UINT, _occurrences,\t\\\n+\t\t\t   .range = { .min = (_min), .max = (_max) },\t\\\n+\t\t\t   .unit = (_unit), .scale = (_scale))\n+\n+#define CTLV_NODE_SCHEMA_SINT(_attr, _occurrences, _min, _max)\t\\\n+\t__CTLV_NODE_SCHEMA(_attr, CTLV_SCHEMA_SINT, _occurrences,\t\\\n+\t\t\t   .range = { .min = (_min), .max = (_max) })\n+\n+#define CTLV_NODE_SCHEMA_SINT_UNIT(_attr, _occurrences, _min, _max, _unit, _scale) \\\n+\t__CTLV_NODE_SCHEMA(_attr, CTLV_SCHEMA_SINT, _occurrences,\t\\\n+\t\t\t   .range = { .min = (_min), .max = (_max) },\t\\\n+\t\t\t   .unit = (_unit), .scale = (_scale))\n+\n+#define CTLV_NODE_SCHEMA_ENUM(_attr, _occurrences, _max)\t\\\n+\t__CTLV_NODE_SCHEMA(_attr, CTLV_SCHEMA_ENUM, _occurrences,\t\\\n+\t\t\t   .range = { .min = 1, .max = (_max) })\n+\n+#define CTLV_NODE_SCHEMA_FLAGS(_attr, _occurrences, _mask)\t\\\n+\t__CTLV_NODE_SCHEMA(_attr, CTLV_SCHEMA_FLAGS, _occurrences,\t\\\n+\t\t\t   .flags_mask = (_mask))\n+\n+#define CTLV_NODE_SCHEMA_BOOL(_attr, _occurrences)\t\t\\\n+\t__CTLV_NODE_SCHEMA(_attr, CTLV_SCHEMA_BOOL, _occurrences)\n+\n+#define CTLV_NODE_SCHEMA_STRING(_attr, _occurrences, _min, _max) \\\n+\t__CTLV_NODE_SCHEMA(_attr, CTLV_SCHEMA_STRING, _occurrences,\t\\\n+\t\t\t   .length = { .min_len = (_min), .max_len = (_max) })\n+\n+#define CTLV_NODE_SCHEMA_BINARY(_attr, _occurrences, _min, _max) \\\n+\t__CTLV_NODE_SCHEMA(_attr, CTLV_SCHEMA_BINARY, _occurrences,\t\\\n+\t\t\t   .length = { .min_len = (_min), .max_len = (_max) })\n+\n+#define CTLV_NODE_SCHEMA_BLOB(_attr, _occurrences, _max, _alignment, _backings, _dir) \\\n+\t__CTLV_NODE_SCHEMA(_attr, CTLV_SCHEMA_BLOB, _occurrences,\t\\\n+\t\t\t   .blob = { .max_len = (_max),\t\t\t\\\n+\t\t\t\t     .alignment = (_alignment),\t\t\\\n+\t\t\t\t     .backings = (_backings),\t\t\\\n+\t\t\t\t     .direction = (_dir) })\n+\n+struct ctlv_stub_schema {\n+\tu16 family_id;\n+\tu32 set_id;\n+\tu32 node;\n+\tbool optional;\n+};\n+\n+#define __CTLV_STUB_SCHEMA(_family, _set, _node, _optional)\t\\\n+\t{ .family_id = (_family), .set_id = (_set),\t\t\\\n+\t  .node = (_node), .optional = (_optional) }\n+\n+#define CTLV_STUB_SCHEMA(_family, _set, _node)\t\t\t\\\n+\t__CTLV_STUB_SCHEMA(_family, _set, _node, false)\n+\n+#define CTLV_STUB_SCHEMA_OPTIONAL(_family, _set, _node)\t\t\\\n+\t__CTLV_STUB_SCHEMA(_family, _set, _node, true)\n+\n+struct ctlv_schema_tree {\n+\tconst struct ctlv_node_schema *node_schemas;\n+\tu32 node_schemas_count;\n+\tconst struct ctlv_stub_schema *stub_schemas;\n+\tu32 stub_schemas_count;\n+};\n+\n+#define CTLV_SCHEMA_TREE(_name) {\t\t\t\t\\\n+\t.node_schemas = _name##_node_schemas,\t\t\t\\\n+\t.node_schemas_count = ARRAY_SIZE(_name##_node_schemas),\t\\\n+}\n+\n+#define CTLV_SCHEMA_TREE_STUBS(_name) {\t\t\t\t\\\n+\t.node_schemas = _name##_node_schemas,\t\t\t\\\n+\t.node_schemas_count = ARRAY_SIZE(_name##_node_schemas),\t\\\n+\t.stub_schemas = _name##_stub_schemas,\t\t\t\\\n+\t.stub_schemas_count = ARRAY_SIZE(_name##_stub_schemas),\t\\\n+}\n+\n+#define CTLV_SCHEMA_TREE_NONE() { }\n+\n+struct ctlv_stub_fill_schema {\n+\tu16 family_id;\n+\tu32 set_id;\n+\tstruct ctlv_schema_tree members;\n+};\n+\n+#define CTLV_STUB_FILL_SCHEMA(_family, _set, _name) {\t\t\\\n+\t.family_id = (_family),\t\t\t\t\t\\\n+\t.set_id = (_set),\t\t\t\t\t\\\n+\t.members = CTLV_SCHEMA_TREE(_name##_fill),\t\t\\\n+}\n+\n+struct ctlv_op_sizes {\n+\tu32 request_max_len;\n+\tu32 action_reply_max_len;\n+\tu32 query_reply_min_len;\n+\tu32 query_reply_suggested_len;\n+\tu32 event_record_max_len;\n+};\n+\n+struct ctlv_op_schema {\n+\tu64 op_id;\n+\tu8 type;\n+\tu8 fd_access;\n+\tu8 availability;\n+\tbool optional;\n+\tbool pre_post;\n+\tstruct ctlv_schema_tree request;\n+\tstruct ctlv_schema_tree reply;\n+\tstruct ctlv_op_sizes sizes;\n+};\n+\n+#define __CTLV_OP_SCHEMA(_op, _type, _availability, ...)\t\\\n+\t{ .op_id = (_op), .type = (_type),\t\t\t\\\n+\t  .availability = (_availability), __VA_ARGS__ }\n+\n+#define CTLV_OP_SCHEMA_ACTION(_op, _access, _availability, _request_len, _reply_len, \\\n+\t\t\t      _request, _reply, ...)\t\t\t\\\n+\t__CTLV_OP_SCHEMA(_op, CTLV_OP_TYPE_ACTION, _availability,\t\\\n+\t\t\t .fd_access = (_access),\t\t\t\\\n+\t\t\t .request = _request, .reply = _reply,\t\t\\\n+\t\t\t .sizes = {\t\t\t\t\t\\\n+\t\t\t\t.request_max_len = (_request_len),\t\\\n+\t\t\t\t.action_reply_max_len = (_reply_len),\t\\\n+\t\t\t },\t\t\t\t\t\t\\\n+\t\t\t __VA_ARGS__)\n+\n+#define CTLV_OP_SCHEMA_QUERY(_op, _access, _availability, _request_len, _reply_min, \\\n+\t\t\t     _reply_suggested, _request, _reply, ...)\t\\\n+\t__CTLV_OP_SCHEMA(_op, CTLV_OP_TYPE_QUERY, _availability,\t\\\n+\t\t\t .fd_access = (_access),\t\t\t\\\n+\t\t\t .request = _request, .reply = _reply,\t\t\\\n+\t\t\t .sizes = {\t\t\t\t\t\\\n+\t\t\t\t.request_max_len = (_request_len),\t\\\n+\t\t\t\t.query_reply_min_len = (_reply_min),\t\\\n+\t\t\t\t.query_reply_suggested_len =\t\t\\\n+\t\t\t\t\t(_reply_suggested),\t\t\\\n+\t\t\t },\t\t\t\t\t\t\\\n+\t\t\t __VA_ARGS__)\n+\n+#define CTLV_OP_SCHEMA_EVENT(_op, _record_len, _reply, ...)\t\\\n+\t__CTLV_OP_SCHEMA(_op, CTLV_OP_TYPE_EVENT,\t\t\\\n+\t\t\t CTLV_OP_AVAILABILITY_FIXED,\t\t\t\\\n+\t\t\t .reply = _reply,\t\t\t\t\\\n+\t\t\t .sizes = {\t\t\t\t\t\\\n+\t\t\t\t.event_record_max_len = (_record_len),\t\\\n+\t\t\t },\t\t\t\t\t\t\\\n+\t\t\t __VA_ARGS__)\n+\n+struct ctlv_family_schema {\n+\tconst char *name;\n+\tu16 family_id;\n+\tconst struct ctlv_op_schema *ops;\n+\tu32 ops_count;\n+\tconst struct ctlv_stub_fill_schema *stub_fill_schemas;\n+\tu32 stub_fill_schemas_count;\n+};\n+\n+/* Leave half of a uevent environment to the device model. */\n+#define CTLV_UEVENT_MAX_LEN (UEVENT_BUFFER_SIZE / 2)\n+#define CTLV_UEVENT_MAX_VARS (UEVENT_NUM_ENVP / 2)\n+\n+struct ctlv_input_ref {\n+\tconst struct ctlv_schema_tree *tree;\n+\tu64 attr_id;\n+\tu32 node;\n+\tu32 slot;\n+\tu8 kind;\n+};\n+\n+typedef int (*ctlv_action_fn)(void *priv, struct ctlv_op_ctx *ctx,\n+\t\t\t      const struct ctlv_cursor *request,\n+\t\t\t      struct ctlv_cursor *reply);\n+typedef int (*ctlv_query_fn)(void *priv, struct ctlv_op_ctx *ctx,\n+\t\t\t     const struct ctlv_cursor *request,\n+\t\t\t     struct ctlv_cursor *reply);\n+typedef int (*ctlv_op_pre_fn)(void *priv, struct ctlv_op_ctx *ctx);\n+typedef void (*ctlv_op_post_fn)(void *priv, struct ctlv_op_ctx *ctx);\n+\n+struct ctlv_op {\n+\tunion {\n+\t\tctlv_action_fn action;\n+\t\tctlv_query_fn query;\n+\t};\n+\tctlv_op_pre_fn pre;\n+\tctlv_op_post_fn post;\n+};\n+\n+#define CTLV_OP_ACTION(_name) { .action = _name##_action }\n+#define CTLV_OP_QUERY(_name) { .query = _name##_query }\n+#define CTLV_OP_ACTION_PRE_POST(_name)\t\t\t\t\\\n+\t{ .action = _name##_action, .pre = _name##_pre,\t\t\\\n+\t  .post = _name##_post }\n+#define CTLV_OP_QUERY_PRE_POST(_name)\t\t\t\t\\\n+\t{ .query = _name##_query, .pre = _name##_pre,\t\t\\\n+\t  .post = _name##_post }\n+\n+typedef size_t (*ctlv_family_priv_size_fn)(void);\n+typedef const void *(*ctlv_family_pre_init_fn)(const void *init_info);\n+typedef int (*ctlv_family_init_fn)(struct ctlv_device *ctlvdev,\n+\t\t\t\t   const void *init_info, void *priv);\n+typedef int (*ctlv_family_post_init_fn)(struct ctlv_device *ctlvdev,\n+\t\t\t\t\tvoid *priv);\n+typedef void (*ctlv_family_pre_fini_fn)(struct ctlv_device *ctlvdev,\n+\t\t\t\t\tvoid *priv);\n+typedef void (*ctlv_family_fini_fn)(struct ctlv_device *ctlvdev, void *priv);\n+\n+typedef int (*ctlv_stub_fill_fn)(void *priv, struct ctlv_op_ctx *ctx,\n+\t\t\t\t const struct ctlv_cursor *request,\n+\t\t\t\t struct ctlv_cursor *nest);\n+\n+struct ctlv_stub_ops {\n+\tu16 family_id;\n+\tu32 set_id;\n+\tctlv_stub_fill_fn fill;\n+};\n+\n+#define CTLV_STUB_OPS(_family, _set, _name) {\t\t\t\\\n+\t.family_id = (_family),\t\t\t\t\t\\\n+\t.set_id = (_set),\t\t\t\t\t\\\n+\t.fill = _name##_fill,\t\t\t\t\t\\\n+}\n+\n+struct ctlv_family {\n+\tconst struct ctlv_family_schema *schema;\n+\tconst struct ctlv_family *parent;\n+\tconst struct ctlv_op *ops;\n+\tu32 ops_count;\n+\tctlv_op_pre_fn pre;\n+\tctlv_op_post_fn post;\n+\tctlv_family_priv_size_fn priv_size;\n+\tctlv_family_pre_init_fn pre_init;\n+\tctlv_family_init_fn init;\n+\tctlv_family_post_init_fn post_init;\n+\tctlv_family_pre_fini_fn pre_fini;\n+\tctlv_family_fini_fn fini;\n+\tconst struct ctlv_stub_ops *stub_ops;\n+\tu32 stub_ops_count;\n+};\n+\n+extern const struct ctlv_family ctlv_family;\n+\n+void ctlv_device_op_provide(struct ctlv_device *ctlvdev, u64 op_id);\n+void ctlv_device_op_state_set(struct ctlv_device *ctlvdev, u64 op_id,\n+\t\t\t      bool disabled);\n+\n+struct ctlv_cursor *\n+ctlv_input_attr(struct ctlv_cursor *cursor, const struct ctlv_cursor *nest,\n+\t\tstruct ctlv_input_ref ref);\n+bool ctlv_input_cursor(const struct ctlv_cursor *cursor,\n+\t\t       struct ctlv_input_ref ref);\n+void ctlv_attr_next(struct ctlv_cursor *cursor);\n+bool ctlv_attr_ok(const struct ctlv_cursor *cursor);\n+u64 ctlv_attr_u64(const struct ctlv_cursor *cursor);\n+s64 ctlv_attr_s64(const struct ctlv_cursor *cursor);\n+bool ctlv_attr_bool(const struct ctlv_cursor *cursor);\n+const char *ctlv_attr_string(const struct ctlv_cursor *cursor);\n+const void *ctlv_attr_binary(const struct ctlv_cursor *cursor, u32 *len);\n+\n+bool ctlv_put_u64(struct ctlv_cursor *nest, u64 attr_id, u8 kind, u64 value);\n+bool ctlv_put_s64(struct ctlv_cursor *nest, u64 attr_id, u8 kind, s64 value);\n+bool ctlv_put_bool(struct ctlv_cursor *nest, u64 attr_id, u8 kind, bool value);\n+bool ctlv_put_string(struct ctlv_cursor *nest, u64 attr_id, u8 kind,\n+\t\t     const char *value);\n+bool ctlv_put_binary(struct ctlv_cursor *nest, u64 attr_id, u8 kind,\n+\t\t     const void *value, u32 len);\n+bool ctlv_nest_start(struct ctlv_cursor *nest, struct ctlv_cursor *child,\n+\t\t     u64 attr_id, u8 kind);\n+\n+struct ctlv_blob *ctlv_blob_resolve(struct ctlv_op_ctx *ctx,\n+\t\t\t\t    const struct ctlv_cursor *blob);\n+struct ctlv_op_ctx *ctlv_event_create(struct ctlv_device *ctlvdev, u64 op_id,\n+\t\t\t\t      struct ctlv_cursor **event, gfp_t gfp);\n+\n+#define CTLV_OP_PROVIDE(_name, _op_id)\t\t\t\t\\\n+static inline void _name##_provide(struct ctlv_device *ctlvdev)\t\\\n+{\t\t\t\t\t\t\t\t\\\n+\tctlv_device_op_provide(ctlvdev, (_op_id));\t\t\\\n+}\n+\n+#define CTLV_OP_ENABLE(_name, _op_id)\t\t\t\t\\\n+static inline void _name##_enable(struct ctlv_device *ctlvdev)\t\\\n+{\t\t\t\t\t\t\t\t\\\n+\tctlv_device_op_state_set(ctlvdev, (_op_id), false);\t\\\n+}\n+\n+#define CTLV_OP_DISABLE(_name, _op_id)\t\t\t\t\\\n+static inline void _name##_disable(struct ctlv_device *ctlvdev)\t\\\n+{\t\t\t\t\t\t\t\t\\\n+\tctlv_device_op_state_set(ctlvdev, (_op_id), true);\t\\\n+}\n+\n+#define CTLV_EVENT_CREATE(_name, _op_id)\t\t\t\\\n+static inline struct ctlv_op_ctx *\t\t\t\t\\\n+_name##_create(struct ctlv_device *ctlvdev,\t\t\t\\\n+\t       struct ctlv_cursor **reply, gfp_t gfp)\t\t\\\n+{\t\t\t\t\t\t\t\t\\\n+\treturn ctlv_event_create(ctlvdev, (_op_id), reply, gfp);\t\\\n+}\n+\n+#define __CTLV_DEFINE_PUT(_name, _type, _put_fn, _attr_id, _kind) \\\n+static inline bool _name##_put(struct ctlv_cursor *nest,\t\t\\\n+\t\t\t       _type value)\t\t\t\\\n+{\t\t\t\t\t\t\t\t\\\n+\treturn _put_fn(nest, (_attr_id), (_kind), value);\t\t\\\n+}\n+\n+#define CTLV_PUT_U64(_name, _attr_id, _kind)\t\t\t\\\n+\t__CTLV_DEFINE_PUT(_name, u64, ctlv_put_u64, _attr_id, _kind)\n+#define CTLV_PUT_S64(_name, _attr_id, _kind)\t\t\t\\\n+\t__CTLV_DEFINE_PUT(_name, s64, ctlv_put_s64, _attr_id, _kind)\n+#define CTLV_PUT_BOOL(_name, _attr_id, _kind)\t\t\t\\\n+\t__CTLV_DEFINE_PUT(_name, bool, ctlv_put_bool, _attr_id, _kind)\n+#define CTLV_PUT_STRING(_name, _attr_id, _kind)\t\t\t\\\n+\t__CTLV_DEFINE_PUT(_name, const char *, ctlv_put_string,\t\\\n+\t\t\t  _attr_id, _kind)\n+\n+#define CTLV_PUT_BINARY(_name, _attr_id, _kind)\t\t\t\\\n+static inline bool _name##_put(struct ctlv_cursor *nest,\t\t\\\n+\t\t\t       const void *value, u32 len)\t\t\\\n+{\t\t\t\t\t\t\t\t\\\n+\treturn ctlv_put_binary(nest, (_attr_id), (_kind), value, len); \\\n+}\n+\n+#define CTLV_NEST_START(_name, _attr_id, _kind)\t\t\t\\\n+static inline bool _name##_start(struct ctlv_cursor *nest,\t\\\n+\t\t\t\t struct ctlv_cursor *nested)\t\\\n+{\t\t\t\t\t\t\t\t\\\n+\treturn ctlv_nest_start(nest, nested, (_attr_id), (_kind));\t\\\n+}\n+\n+#define CTLV_IN_REF(_name, _tree, _attr_id, _node, _slot, _kind) \\\n+static inline struct ctlv_input_ref _name##_ref(void)\t\t\\\n+{\t\t\t\t\t\t\t\t\\\n+\treturn (struct ctlv_input_ref){\t\t\t\t\\\n+\t\t.tree = (_tree),\t\t\t\t\t\\\n+\t\t.attr_id = (_attr_id),\t\t\t\t\\\n+\t\t.node = (_node),\t\t\t\t\t\\\n+\t\t.slot = (_slot),\t\t\t\t\t\\\n+\t\t.kind = (_kind),\t\t\t\t\t\\\n+\t};\t\t\t\t\t\t\t\\\n+}\n+\n+#define CTLV_IN_FOR_EACH(_name, _attr, _nest)\t\t\t\\\n+\tfor (struct ctlv_cursor *__ctlv_attr =\t\t\t\\\n+\t\tctlv_input_attr(_attr, _nest, _name##_ref());\t\\\n+\t     ctlv_attr_ok(__ctlv_attr);\t\t\t\t\\\n+\t     ctlv_attr_next(__ctlv_attr))\n+\n+#define CTLV_IN_HAS(_name)\t\t\t\t\t\\\n+static inline bool _name##_present(const struct ctlv_cursor *nest) \\\n+{\t\t\t\t\t\t\t\t\\\n+\tstruct ctlv_cursor attr;\t\t\t\t\\\n+\t\t\t\t\t\t\t\t\\\n+\tctlv_input_attr(\u0026attr, nest, _name##_ref());\t\t\\\n+\treturn ctlv_attr_ok(\u0026attr);\t\t\t\t\\\n+}\n+\n+#define CTLV_IN_U64(_name)\t\t\t\t\t\\\n+static inline u64 _name##_get(const struct ctlv_cursor *nest)\t\\\n+{\t\t\t\t\t\t\t\t\\\n+\tstruct ctlv_cursor attr;\t\t\t\t\\\n+\t\t\t\t\t\t\t\t\\\n+\tctlv_input_attr(\u0026attr, nest, _name##_ref());\t\t\\\n+\treturn ctlv_attr_u64(\u0026attr);\t\t\t\t\\\n+}\n+\n+#define CTLV_IN_S64(_name)\t\t\t\t\t\\\n+static inline s64 _name##_get(const struct ctlv_cursor *nest)\t\\\n+{\t\t\t\t\t\t\t\t\\\n+\tstruct ctlv_cursor attr;\t\t\t\t\\\n+\t\t\t\t\t\t\t\t\\\n+\tctlv_input_attr(\u0026attr, nest, _name##_ref());\t\t\\\n+\treturn ctlv_attr_s64(\u0026attr);\t\t\t\t\\\n+}\n+\n+#define CTLV_IN_BOOL(_name)\t\t\t\t\t\\\n+static inline bool _name##_get(const struct ctlv_cursor *nest)\t\\\n+{\t\t\t\t\t\t\t\t\\\n+\tstruct ctlv_cursor attr;\t\t\t\t\\\n+\t\t\t\t\t\t\t\t\\\n+\tctlv_input_attr(\u0026attr, nest, _name##_ref());\t\t\\\n+\treturn ctlv_attr_bool(\u0026attr);\t\t\t\t\\\n+}\n+\n+#define CTLV_IN_STRING(_name)\t\t\t\t\t\\\n+static inline const char *\t\t\t\t\t\\\n+_name##_get(const struct ctlv_cursor *nest)\t\t\t\\\n+{\t\t\t\t\t\t\t\t\\\n+\tstruct ctlv_cursor attr;\t\t\t\t\\\n+\t\t\t\t\t\t\t\t\\\n+\tctlv_input_attr(\u0026attr, nest, _name##_ref());\t\t\\\n+\treturn ctlv_attr_string(\u0026attr);\t\t\t\t\\\n+}\n+\n+#define CTLV_IN_BINARY(_name)\t\t\t\t\t\\\n+static inline const void *\t\t\t\t\t\\\n+_name##_get(const struct ctlv_cursor *nest, u32 *len)\t\t\\\n+{\t\t\t\t\t\t\t\t\\\n+\tstruct ctlv_cursor attr;\t\t\t\t\\\n+\t\t\t\t\t\t\t\t\\\n+\tctlv_input_attr(\u0026attr, nest, _name##_ref());\t\t\\\n+\treturn ctlv_attr_binary(\u0026attr, len);\t\t\t\\\n+}\n+\n+#define CTLV_IN_NEST(_name)\t\t\t\t\t\\\n+static inline void _name##_get(struct ctlv_cursor *nested,\t\\\n+\t\t\t       const struct ctlv_cursor *nest)\t\\\n+{\t\t\t\t\t\t\t\t\\\n+\tctlv_input_attr(nested, nest, _name##_ref());\t\t\\\n+}\n+\n+#define CTLV_IN_BLOB(_name)\t\t\t\t\t\\\n+static inline struct ctlv_blob *\t\t\t\t\\\n+_name##_resolve(struct ctlv_op_ctx *ctx,\t\t\t\\\n+\t\tconst struct ctlv_cursor *nest)\t\t\t\\\n+{\t\t\t\t\t\t\t\t\\\n+\tstruct ctlv_cursor attr;\t\t\t\t\\\n+\t\t\t\t\t\t\t\t\\\n+\tctlv_input_attr(\u0026attr, nest, _name##_ref());\t\t\\\n+\treturn ctlv_blob_resolve(ctx, \u0026attr);\t\t\t\\\n+}\n+\n+#define CTLV_IN_EACH_U64(_name)\t\t\t\t\t\\\n+static inline u64 _name##_get(const struct ctlv_cursor *attr)\t\\\n+{\t\t\t\t\t\t\t\t\\\n+\tif (!ctlv_input_cursor(attr, _name##_ref()))\t\t\\\n+\t\treturn 0;\t\t\t\t\t\\\n+\treturn ctlv_attr_u64(attr);\t\t\t\t\\\n+}\n+\n+#define CTLV_IN_EACH_S64(_name)\t\t\t\t\t\\\n+static inline s64 _name##_get(const struct ctlv_cursor *attr)\t\\\n+{\t\t\t\t\t\t\t\t\\\n+\tif (!ctlv_input_cursor(attr, _name##_ref()))\t\t\\\n+\t\treturn 0;\t\t\t\t\t\\\n+\treturn ctlv_attr_s64(attr);\t\t\t\t\\\n+}\n+\n+#define CTLV_IN_EACH_BOOL(_name)\t\t\t\t\\\n+static inline bool _name##_get(const struct ctlv_cursor *attr)\t\\\n+{\t\t\t\t\t\t\t\t\\\n+\tif (!ctlv_input_cursor(attr, _name##_ref()))\t\t\\\n+\t\treturn false;\t\t\t\t\t\\\n+\treturn ctlv_attr_bool(attr);\t\t\t\t\\\n+}\n+\n+#define CTLV_IN_EACH_STRING(_name)\t\t\t\t\\\n+static inline const char *\t\t\t\t\t\\\n+_name##_get(const struct ctlv_cursor *attr)\t\t\t\\\n+{\t\t\t\t\t\t\t\t\\\n+\tif (!ctlv_input_cursor(attr, _name##_ref()))\t\t\\\n+\t\treturn NULL;\t\t\t\t\t\\\n+\treturn ctlv_attr_string(attr);\t\t\t\t\\\n+}\n+\n+#define CTLV_IN_EACH_BINARY(_name)\t\t\t\t\\\n+static inline const void *\t\t\t\t\t\\\n+_name##_get(const struct ctlv_cursor *attr, u32 *len)\t\t\\\n+{\t\t\t\t\t\t\t\t\\\n+\tif (!ctlv_input_cursor(attr, _name##_ref())) {\t\t\\\n+\t\t*len = 0;\t\t\t\t\t\\\n+\t\treturn NULL;\t\t\t\t\t\\\n+\t}\t\t\t\t\t\t\t\\\n+\treturn ctlv_attr_binary(attr, len);\t\t\t\\\n+}\n+\n+#define CTLV_IN_EACH_BLOB(_name)\t\t\t\t\\\n+static inline struct ctlv_blob *\t\t\t\t\\\n+_name##_resolve(struct ctlv_op_ctx *ctx,\t\t\t\\\n+\t\tconst struct ctlv_cursor *attr)\t\t\t\\\n+{\t\t\t\t\t\t\t\t\\\n+\tif (!ctlv_input_cursor(attr, _name##_ref()))\t\t\\\n+\t\treturn ERR_PTR(-EINVAL);\t\t\t\t\\\n+\treturn ctlv_blob_resolve(ctx, attr);\t\t\t\\\n+}\n+\n+#endif /* _LINUX_CTLV_FAMILY_H */\ndiff --git a/include/linux/ctlv_gen.h b/include/linux/ctlv_gen.h\nnew file mode 100644\nindex 0000000000000..e389803449a00\n--- /dev/null\n+++ b/include/linux/ctlv_gen.h\n@@ -0,0 +1,137 @@\n+/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) */\n+/* Do not edit, regenerate with tools/ctlv/ctlv-regen.sh, from: */\n+/*\tDocumentation/ctlv/specs/ctlv.yaml */\n+/* CTLV-GEN kernel header */\n+\n+/* Kernel metadata and family API of the ctlv CTLV family. */\n+\n+#ifndef _LINUX_CTLV_GEN_H\n+#define _LINUX_CTLV_GEN_H\n+\n+#include \u003clinux/ctlv_family.h\u003e\n+#include \u003clinux/err.h\u003e\n+#include \u003clinux/errno.h\u003e\n+\n+#include \u003cuapi/linux/ctlv_gen.h\u003e\n+\n+/* Ops this family declares, in declaration order. */\n+extern const struct ctlv_op_schema ctlv_op_schemas[];\n+\n+extern const struct ctlv_family_schema ctlv_schema;\n+\n+/* The error-info message, built by the core. */\n+#define CTLV_ERROR_INFO_MAX_LEN 432\n+\n+extern const struct ctlv_schema_tree ctlv_error_info_schema;\n+\n+/* Implemented by the CTLV core, one per action and query it declares. */\n+int ctlv_families_dump_query(void *priv, struct ctlv_op_ctx *ctx, const struct ctlv_cursor *request,\n+\t\t\t     struct ctlv_cursor *reply);\n+int ctlv_ops_dump_query(void *priv, struct ctlv_op_ctx *ctx, const struct ctlv_cursor *request,\n+\t\t\tstruct ctlv_cursor *reply);\n+int ctlv_op_schema_get_query(void *priv, struct ctlv_op_ctx *ctx, const struct ctlv_cursor *request,\n+\t\t\t     struct ctlv_cursor *reply);\n+int ctlv_subscriptions_add_action(void *priv, struct ctlv_op_ctx *ctx,\n+\t\t\t\t  const struct ctlv_cursor *request, struct ctlv_cursor *reply);\n+int ctlv_subscriptions_remove_action(void *priv, struct ctlv_op_ctx *ctx,\n+\t\t\t\t     const struct ctlv_cursor *request, struct ctlv_cursor *reply);\n+int ctlv_event_queue_get_query(void *priv, struct ctlv_op_ctx *ctx,\n+\t\t\t       const struct ctlv_cursor *request, struct ctlv_cursor *reply);\n+int ctlv_event_queue_set_action(void *priv, struct ctlv_op_ctx *ctx,\n+\t\t\t\tconst struct ctlv_cursor *request, struct ctlv_cursor *reply);\n+\n+/* Root-family hooks around every core action or query. */\n+int ctlv_op_pre(void *priv, struct ctlv_op_ctx *ctx);\n+void ctlv_op_post(void *priv, struct ctlv_op_ctx *ctx);\n+\n+/* Core-allocated family priv lifecycle. */\n+size_t ctlv_priv_size(void);\n+int ctlv_init(struct ctlv_device *ctlvdev, const void *init_info, void *priv);\n+void ctlv_fini(struct ctlv_device *ctlvdev, void *priv);\n+\n+extern const struct ctlv_family ctlv_family;\n+\n+#ifndef _CTLV_GENERATED_METADATA_ONLY\n+\n+/* Reading a validated message. A blob has a resolver instead of a getter. */\n+CTLV_IN_REF(ctlv_op_schema_get_op_id, \u0026ctlv_op_schemas[2].request, CTLV_ATTR_OP_ID, 0, 0,\n+\t    CTLV_SCHEMA_UINT)\n+CTLV_IN_HAS(ctlv_op_schema_get_op_id)\n+CTLV_IN_U64(ctlv_op_schema_get_op_id)\n+CTLV_IN_REF(ctlv_subscriptions_add_event_op_id, \u0026ctlv_op_schemas[3].request, CTLV_ATTR_EVENT_OP_ID,\n+\t    0, 0, CTLV_SCHEMA_UINT)\n+#define ctlv_subscriptions_add_event_op_id_for_each(_attr, _nest) \\\n+\tCTLV_IN_FOR_EACH(ctlv_subscriptions_add_event_op_id, _attr, _nest)\n+CTLV_IN_EACH_U64(ctlv_subscriptions_add_event_op_id)\n+CTLV_IN_REF(ctlv_subscriptions_remove_event_op_id, \u0026ctlv_op_schemas[4].request,\n+\t    CTLV_ATTR_EVENT_OP_ID, 0, 0, CTLV_SCHEMA_UINT)\n+#define ctlv_subscriptions_remove_event_op_id_for_each(_attr, _nest) \\\n+\tCTLV_IN_FOR_EACH(ctlv_subscriptions_remove_event_op_id, _attr, _nest)\n+CTLV_IN_EACH_U64(ctlv_subscriptions_remove_event_op_id)\n+CTLV_IN_REF(ctlv_event_queue_set_event_queue_len, \u0026ctlv_op_schemas[6].request,\n+\t    CTLV_ATTR_EVENT_QUEUE_LEN, 0, 0, CTLV_SCHEMA_UINT)\n+CTLV_IN_HAS(ctlv_event_queue_set_event_queue_len)\n+CTLV_IN_U64(ctlv_event_queue_set_event_queue_len)\n+\n+/* Writing a reply. An append is atomic; a nest ends with ctlv_nest_end(). */\n+CTLV_PUT_U64(ctlv_family_id, CTLV_ATTR_FAMILY_ID, CTLV_SCHEMA_UINT)\n+CTLV_PUT_STRING(ctlv_family_name, CTLV_ATTR_FAMILY_NAME, CTLV_SCHEMA_STRING)\n+CTLV_NEST_START(ctlv_family_entry, CTLV_ATTR_FAMILY_ENTRY, CTLV_SCHEMA_NEST)\n+CTLV_PUT_U64(ctlv_blob_type, CTLV_ATTR_BLOB_TYPE, CTLV_SCHEMA_ENUM)\n+CTLV_PUT_U64(ctlv_blob_address, CTLV_ATTR_BLOB_ADDRESS, CTLV_SCHEMA_UINT)\n+CTLV_PUT_U64(ctlv_blob_fd, CTLV_ATTR_BLOB_FD, CTLV_SCHEMA_UINT)\n+CTLV_PUT_U64(ctlv_blob_offset, CTLV_ATTR_BLOB_OFFSET, CTLV_SCHEMA_UINT)\n+CTLV_PUT_U64(ctlv_blob_length, CTLV_ATTR_BLOB_LENGTH, CTLV_SCHEMA_UINT)\n+CTLV_PUT_U64(ctlv_error_reason, CTLV_ATTR_ERROR_REASON, CTLV_SCHEMA_ENUM)\n+CTLV_PUT_STRING(ctlv_error_message, CTLV_ATTR_ERROR_MESSAGE, CTLV_SCHEMA_STRING)\n+CTLV_PUT_U64(ctlv_error_bad_attr_offset, CTLV_ATTR_ERROR_BAD_ATTR_OFFSET, CTLV_SCHEMA_UINT)\n+CTLV_PUT_U64(ctlv_error_nest_offset, CTLV_ATTR_ERROR_NEST_OFFSET, CTLV_SCHEMA_UINT)\n+CTLV_PUT_U64(ctlv_error_missing_attr_id, CTLV_ATTR_ERROR_MISSING_ATTR_ID, CTLV_SCHEMA_UINT)\n+CTLV_PUT_U64(ctlv_error_expected_generation, CTLV_ATTR_ERROR_EXPECTED_GENERATION, CTLV_SCHEMA_UINT)\n+CTLV_PUT_U64(ctlv_error_current_generation, CTLV_ATTR_ERROR_CURRENT_GENERATION, CTLV_SCHEMA_UINT)\n+CTLV_PUT_U64(ctlv_op_id, CTLV_ATTR_OP_ID, CTLV_SCHEMA_UINT)\n+CTLV_PUT_U64(ctlv_op_type, CTLV_ATTR_OP_TYPE, CTLV_SCHEMA_ENUM)\n+CTLV_PUT_U64(ctlv_op_availability, CTLV_ATTR_OP_AVAILABILITY, CTLV_SCHEMA_ENUM)\n+CTLV_PUT_BOOL(ctlv_op_disabled, CTLV_ATTR_OP_DISABLED, CTLV_SCHEMA_BOOL)\n+CTLV_PUT_U64(ctlv_op_request_max_len, CTLV_ATTR_OP_REQUEST_MAX_LEN, CTLV_SCHEMA_UINT)\n+CTLV_PUT_U64(ctlv_op_action_reply_max_len, CTLV_ATTR_OP_ACTION_REPLY_MAX_LEN, CTLV_SCHEMA_UINT)\n+CTLV_PUT_U64(ctlv_op_query_reply_min_len, CTLV_ATTR_OP_QUERY_REPLY_MIN_LEN, CTLV_SCHEMA_UINT)\n+CTLV_PUT_U64(ctlv_op_query_reply_suggested_len, CTLV_ATTR_OP_QUERY_REPLY_SUGGESTED_LEN,\n+\t     CTLV_SCHEMA_UINT)\n+CTLV_PUT_U64(ctlv_op_event_record_max_len, CTLV_ATTR_OP_EVENT_RECORD_MAX_LEN, CTLV_SCHEMA_UINT)\n+CTLV_PUT_U64(ctlv_op_state_generation, CTLV_ATTR_OP_STATE_GENERATION, CTLV_SCHEMA_UINT)\n+CTLV_NEST_START(ctlv_op_entry, CTLV_ATTR_OP_ENTRY, CTLV_SCHEMA_NEST)\n+CTLV_PUT_U64(ctlv_op_fd_access, CTLV_ATTR_OP_FD_ACCESS, CTLV_SCHEMA_ENUM)\n+CTLV_PUT_U64(ctlv_schema_attr_id, CTLV_ATTR_SCHEMA_ATTR_ID, CTLV_SCHEMA_UINT)\n+CTLV_PUT_U64(ctlv_schema_kind, CTLV_ATTR_SCHEMA_KIND, CTLV_SCHEMA_UINT)\n+CTLV_PUT_U64(ctlv_schema_max_occurrences, CTLV_ATTR_SCHEMA_MAX_OCCURRENCES, CTLV_SCHEMA_UINT)\n+CTLV_PUT_U64(ctlv_schema_min, CTLV_ATTR_SCHEMA_MIN, CTLV_SCHEMA_UINT)\n+CTLV_PUT_U64(ctlv_schema_max, CTLV_ATTR_SCHEMA_MAX, CTLV_SCHEMA_UINT)\n+CTLV_PUT_U64(ctlv_schema_min_length, CTLV_ATTR_SCHEMA_MIN_LENGTH, CTLV_SCHEMA_UINT)\n+CTLV_PUT_U64(ctlv_schema_max_length, CTLV_ATTR_SCHEMA_MAX_LENGTH, CTLV_SCHEMA_UINT)\n+CTLV_PUT_U64(ctlv_schema_flags_mask, CTLV_ATTR_SCHEMA_FLAGS_MASK, CTLV_SCHEMA_UINT)\n+CTLV_PUT_U64(ctlv_schema_unit, CTLV_ATTR_SCHEMA_UNIT, CTLV_SCHEMA_UINT)\n+CTLV_PUT_S64(ctlv_schema_scale, CTLV_ATTR_SCHEMA_SCALE, CTLV_SCHEMA_SINT)\n+CTLV_PUT_U64(ctlv_schema_blob_direction, CTLV_ATTR_SCHEMA_BLOB_DIRECTION, CTLV_SCHEMA_ENUM)\n+CTLV_PUT_U64(ctlv_schema_blob_backings, CTLV_ATTR_SCHEMA_BLOB_BACKINGS, CTLV_SCHEMA_UINT)\n+CTLV_PUT_U64(ctlv_schema_blob_max_length, CTLV_ATTR_SCHEMA_BLOB_MAX_LENGTH, CTLV_SCHEMA_UINT)\n+CTLV_PUT_U64(ctlv_schema_blob_alignment, CTLV_ATTR_SCHEMA_BLOB_ALIGNMENT, CTLV_SCHEMA_UINT)\n+CTLV_PUT_U64(ctlv_schema_reenters, CTLV_ATTR_SCHEMA_REENTERS, CTLV_SCHEMA_UINT)\n+CTLV_NEST_START(ctlv_schema_attrs, CTLV_ATTR_SCHEMA_ATTRS, CTLV_SCHEMA_NEST)\n+CTLV_NEST_START(ctlv_schema_optional_attrs, CTLV_ATTR_SCHEMA_OPTIONAL_ATTRS, CTLV_SCHEMA_NEST)\n+CTLV_NEST_START(ctlv_schema_request, CTLV_ATTR_SCHEMA_REQUEST, CTLV_SCHEMA_NEST)\n+CTLV_NEST_START(ctlv_schema_reply, CTLV_ATTR_SCHEMA_REPLY, CTLV_SCHEMA_NEST)\n+CTLV_PUT_U64(ctlv_event_op_id, CTLV_ATTR_EVENT_OP_ID, CTLV_SCHEMA_UINT)\n+CTLV_PUT_U64(ctlv_event_queue_len, CTLV_ATTR_EVENT_QUEUE_LEN, CTLV_SCHEMA_UINT)\n+CTLV_PUT_U64(ctlv_event_queue_used, CTLV_ATTR_EVENT_QUEUE_USED, CTLV_SCHEMA_UINT)\n+CTLV_PUT_U64(ctlv_event_first_sequence, CTLV_ATTR_EVENT_FIRST_SEQUENCE, CTLV_SCHEMA_UINT)\n+CTLV_PUT_U64(ctlv_event_last_sequence, CTLV_ATTR_EVENT_LAST_SEQUENCE, CTLV_SCHEMA_UINT)\n+CTLV_PUT_U64(ctlv_event_dropped_count, CTLV_ATTR_EVENT_DROPPED_COUNT, CTLV_SCHEMA_UINT)\n+\n+/* Building one event, passed to ctlv_event_emit() or ctlv_event_abort() once. */\n+CTLV_EVENT_CREATE(ctlv_op_changed, CTLV_OP_OP_CHANGED)\n+CTLV_EVENT_CREATE(ctlv_event_overflow, CTLV_OP_EVENT_OVERFLOW)\n+CTLV_EVENT_CREATE(ctlv_device_removed, CTLV_OP_DEVICE_REMOVED)\n+#endif /* _CTLV_GENERATED_METADATA_ONLY */\n+\n+#endif /* _LINUX_CTLV_GEN_H */\ndiff --git a/include/linux/tdx-guest.h b/include/linux/tdx-guest.h\nnew file mode 100644\nindex 0000000000000..65f367e4956a3\n--- /dev/null\n+++ b/include/linux/tdx-guest.h\n@@ -0,0 +1,75 @@\n+/* SPDX-License-Identifier: GPL-2.0-only */\n+#ifndef _LINUX_TDX_GUEST_H\n+#define _LINUX_TDX_GUEST_H\n+\n+#include \u003ccrypto/sha2.h\u003e\n+#include \u003clinux/types.h\u003e\n+\n+struct device;\n+\n+#define TDX_GUEST_REPORTDATA_LEN 64\n+#define TDX_GUEST_REPORT_LEN 1024\n+#define TDX_GUEST_QUOTE_MAX_LEN ((128 * 1024) - 24)\n+\n+struct tdx_guest_info {\n+\tu8 mrconfigid[SHA384_DIGEST_SIZE];\n+\tu8 mrowner[SHA384_DIGEST_SIZE];\n+\tu8 mrownerconfig[SHA384_DIGEST_SIZE];\n+};\n+\n+enum tdx_guest_mr {\n+\tTDX_GUEST_MR_MRTD,\n+\tTDX_GUEST_MR_RTMR0,\n+\tTDX_GUEST_MR_RTMR1,\n+\tTDX_GUEST_MR_RTMR2,\n+\tTDX_GUEST_MR_RTMR3,\n+};\n+\n+/**\n+ * struct tdx_guest_ops - Native TDX guest operations\n+ * @info_get: Return immutable TD construction fields\n+ * @report_get: Get a TDREPORT bound to report data\n+ * @quote_get: Get a Quote bound to report data\n+ * @mr_read: Read MRTD or an RTMR\n+ * @rtmr_extend: Extend an RTMR\n+ */\n+struct tdx_guest_ops {\n+\tconst struct tdx_guest_info *(*info_get)(struct device *dev);\n+\tint (*report_get)(struct device *dev, const u8 *reportdata,\n+\t\t\t  size_t length, void *out, size_t capacity,\n+\t\t\t  size_t *out_length);\n+\tint (*quote_get)(struct device *dev, const u8 *reportdata,\n+\t\t\t size_t length, void *out, size_t capacity,\n+\t\t\t size_t *out_length);\n+\tint (*mr_read)(struct device *dev, enum tdx_guest_mr mr,\n+\t\t       u8 value[SHA384_DIGEST_SIZE]);\n+\tint (*rtmr_extend)(struct device *dev, unsigned int rtmr,\n+\t\t\t   const u8 value[SHA384_DIGEST_SIZE]);\n+};\n+\n+/**\n+ * struct tdx_guest_client - Native TDX service consumer\n+ * @add: Attach to the service and return client private data or an ERR_PTR\n+ * @remove: Detach the client private data returned by @add\n+ */\n+struct tdx_guest_client {\n+\tvoid *(*add)(struct device *parent_dev,\n+\t\t     const struct tdx_guest_ops *ops);\n+\tvoid (*remove)(void *client_priv);\n+};\n+\n+/**\n+ * tdx_guest_client_register - Register one native TDX service consumer\n+ * @client: Immutable add/remove callback pair\n+ *\n+ * Return: 0, or a negative errno.\n+ */\n+int tdx_guest_client_register(const struct tdx_guest_client *client);\n+\n+/**\n+ * tdx_guest_client_unregister - Unregister a native TDX service consumer\n+ * @client: Descriptor passed to tdx_guest_client_register()\n+ */\n+void tdx_guest_client_unregister(const struct tdx_guest_client *client);\n+\n+#endif /* _LINUX_TDX_GUEST_H */\ndiff --git a/include/uapi/linux/ctlv.h b/include/uapi/linux/ctlv.h\nnew file mode 100644\nindex 0000000000000..6bc0d1a296e67\n--- /dev/null\n+++ b/include/uapi/linux/ctlv.h\n@@ -0,0 +1,183 @@\n+/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) */\n+/*\n+ * Copyright (c) 2026, NVIDIA CORPORATION \u0026 AFFILIATES\n+ *\n+ * CTLV transport UAPI: the TLV wire format, the op-execution ioctl, the event\n+ * record header and transport limits. Schema-free; a family's constants\n+ * are generated into \u003clinux/\u003cfamily\u003e_gen.h\u003e, the root family's into\n+ * \u003clinux/ctlv_gen.h\u003e.\n+ */\n+#ifndef _UAPI_LINUX_CTLV_H\n+#define _UAPI_LINUX_CTLV_H\n+\n+#include \u003clinux/ioctl.h\u003e\n+#include \u003clinux/types.h\u003e\n+\n+/**\n+ * struct ctlv_attr - Attr header.\n+ * @len: this header plus its payload, excluding this attr's trailing padding\n+ * @flags: CTLV_ATTR_F_* bits\n+ * @attr_id: complete attr ID, or CTLV_ATTR_ROOT for a message root\n+ *\n+ * Attrs are aligned to CTLV_ALIGNTO, which is why @attr_id is __aligned_u64: a\n+ * 32-bit ABI would otherwise align this structure to four bytes. A nested\n+ * payload is the concatenation of CTLV_ALIGN(child.len) bytes per child, so\n+ * child padding counts inside the containing attr's @len while a leaf's own\n+ * padding does not. Scalar payloads are native-endian. Within each request\n+ * root or nest, occurrences of one @attr_id are contiguous; different IDs\n+ * otherwise have no required order.\n+ */\n+struct ctlv_attr {\n+\t__u32 len;\n+\t__u32 flags;\n+\t__aligned_u64 attr_id;\n+};\n+\n+#define CTLV_ALIGNTO 8\n+#define CTLV_ALIGN(_len) (((_len) + CTLV_ALIGNTO - 1) \u0026 ~(CTLV_ALIGNTO - 1))\n+\n+/* Set exactly on root and nested attrs, clear on scalar attrs. */\n+#define CTLV_ATTR_F_NESTED\t\t(1U \u003c\u003c 0)\n+/* Query fragments: set on the root and each nest logically open at the end. */\n+#define CTLV_ATTR_F_FRAG_MORE\t\t(1U \u003c\u003c 1)\n+/*\n+ * A request attr, never the root, that a device whose schema does not declare\n+ * its ID skips whole instead of refusing the message. An ID that schema does\n+ * declare is held to it wherever it appears, so this asks to be forgiven what\n+ * this kernel has never heard of and nothing else.\n+ */\n+#define CTLV_ATTR_F_IGNORE_IF_UNKNOWN\t(1U \u003c\u003c 2)\n+\n+/* Root attr: carries CTLV_ATTR_F_NESTED, valid only at a message start. */\n+#define CTLV_ATTR_ROOT 0ULL\n+\n+/* Complete attr: family in bits 63..48, group in 47..32, attr in 31..0. */\n+#define CTLV_ATTR(_family, _group, _attr)\t\\\n+\t(((__u64)(_family) \u003c\u003c 48) |\t\t\\\n+\t ((__u64)(_group) \u003c\u003c 32) |\t\t\\\n+\t (__u64)(_attr))\n+\n+#define CTLV_ATTR_FAMILY(_attr)\t((__u16)((_attr) \u003e\u003e 48))\n+#define CTLV_ATTR_GROUP(_attr)\t((__u16)((_attr) \u003e\u003e 32))\n+#define CTLV_ATTR_NUMBER(_attr)\t((__u32)(_attr))\n+\n+/* Complete op: family in bits 63..48, zero in 47..32, op in 31..0. */\n+#define CTLV_OP(_family, _op)\t\\\n+\t(((__u64)(_family) \u003c\u003c 48) | (__u64)(_op))\n+\n+#define CTLV_OP_FAMILY(_op)\t\t((__u16)((_op) \u003e\u003e 48))\n+#define CTLV_OP_NUMBER(_op)\t\t((__u32)(_op))\n+\n+/**\n+ * enum ctlv_unit - CTLV-defined unit of an integer attr payload.\n+ * @CTLV_UNIT_NONE: dimensionless\n+ * @CTLV_UNIT_SECONDS: seconds\n+ * @CTLV_UNIT_HERTZ: hertz\n+ * @CTLV_UNIT_BYTES: bytes\n+ * @CTLV_UNIT_CELSIUS: degrees Celsius\n+ *\n+ * A payload is value * 10^scale of this unit, from the decimal scale the attr\n+ * declares alongside. Changing either is an ABI break.\n+ */\n+enum ctlv_unit {\n+\tCTLV_UNIT_NONE = 0,\n+\tCTLV_UNIT_SECONDS,\n+\tCTLV_UNIT_HERTZ,\n+\tCTLV_UNIT_BYTES,\n+\tCTLV_UNIT_CELSIUS,\n+};\n+\n+/**\n+ * enum ctlv_schema_kind - CTLV-defined form of one attr payload.\n+ * @CTLV_SCHEMA_UINT: unsigned integer payload bounded by a range\n+ * @CTLV_SCHEMA_SINT: signed integer payload bounded by a range\n+ * @CTLV_SCHEMA_BOOL: one payload byte holding zero or one\n+ * @CTLV_SCHEMA_STRING: NUL-terminated string payload bounded by length\n+ * @CTLV_SCHEMA_BINARY: opaque payload bounded by length\n+ * @CTLV_SCHEMA_ENUM: unsigned integer payload restricted to a range\n+ * @CTLV_SCHEMA_FLAGS: unsigned integer payload restricted to a mask\n+ * @CTLV_SCHEMA_NEST: nested payload described by further nodes\n+ * @CTLV_SCHEMA_BLOB: blob descriptor nest\n+ *\n+ * Exactly one form applies to an attr. These are the values op-schema-get\n+ * reports, and the set is append-only.\n+ */\n+enum ctlv_schema_kind {\n+\tCTLV_SCHEMA_UINT,\n+\tCTLV_SCHEMA_SINT,\n+\tCTLV_SCHEMA_BOOL,\n+\tCTLV_SCHEMA_STRING,\n+\tCTLV_SCHEMA_BINARY,\n+\tCTLV_SCHEMA_ENUM,\n+\tCTLV_SCHEMA_FLAGS,\n+\tCTLV_SCHEMA_NEST,\n+\tCTLV_SCHEMA_BLOB,\n+};\n+\n+/**\n+ * struct ctlv_op_exec - Op-execution ioctl argument.\n+ * @op_id: complete op ID; zero is invalid\n+ * @request: struct ctlv_attr __user *, the mandatory complete request root\n+ * @reply: struct ctlv_attr __user *, the success reply or the error\n+ *\tinformation\n+ * @request_len: readable bytes beginning at @request, at least one root header;\n+ *\tthe transport copy boundary, which may exceed the root's own length\n+ * @reply_len: writable bytes beginning at @reply; input only, never\n+ *\toverwritten by the kernel\n+ * @generation: query only; zero on a first fragment, the previously returned\n+ *\tvalue on continuation, and the query generation on output. Actions must\n+ *\tset zero.\n+ * @cursor: query only; zero starts a query and a nonzero value resumes it. On\n+ *\toutput it is the next cursor when the root carries\n+ *\tCTLV_ATTR_F_FRAG_MORE and zero when no further fragment exists. Actions\n+ *\tmust set zero.\n+ * @reserved: must be zero\n+ *\n+ * No size field: the ioctl number encodes the structure size and @reserved\n+ * covers compatible growth. @request and @reply are fixed-width\n+ * representations of userspace pointers so that the compat layout is identical.\n+ */\n+struct ctlv_op_exec {\n+\t__aligned_u64 op_id;\n+\t__aligned_u64 request;\n+\t__aligned_u64 reply;\n+\t__u32 request_len;\n+\t__u32 reply_len;\n+\t__aligned_u64 generation;\n+\t__aligned_u64 cursor;\n+\t__aligned_u64 reserved[2];\n+};\n+\n+#define CTLV_IOC_MAGIC 0xBB\n+\n+#define CTLV_IOC_OP_EXEC _IOWR(CTLV_IOC_MAGIC, 0x00, struct ctlv_op_exec)\n+\n+/**\n+ * struct ctlv_event_hdr - Header of one queued event record.\n+ * @length: complete record length, this header plus the aligned root\n+ * @flags: must be zero\n+ * @op_id: complete op ID of the event op that produced the record\n+ * @sequence: per open file description sequence number, assigned to every\n+ *\teligible enqueue attempt including dropped ones\n+ *\n+ * Exactly one root attr follows the header, and one read() returns one record.\n+ */\n+struct ctlv_event_hdr {\n+\t__u32 length;\n+\t__u32 flags;\n+\t__aligned_u64 op_id;\n+\t__aligned_u64 sequence;\n+};\n+\n+/* Implementation limits, not wire-field maxima: raising them is compatible. */\n+\n+/* Request roots, action replies, query reply fragments and event roots. */\n+#define CTLV_MAX_INLINE_MESSAGE_LEN\t0x100000\t/* 1 MiB */\n+/* Includes the error information root. */\n+#define CTLV_MAX_ERROR_LEN\t\t0x4000\t\t/* 16 KiB */\n+/* The root attr is at depth zero. */\n+#define CTLV_MAX_NEST_DEPTH\t\t32\n+#define CTLV_DEFAULT_QUERY_REPLY_LEN\t0x10000\t\t/* 64 KiB */\n+#define CTLV_MAX_EVENT_QUEUE_LEN\t0x1000000\t/* 16 MiB */\n+\n+#endif /* _UAPI_LINUX_CTLV_H */\ndiff --git a/include/uapi/linux/ctlv_attestation_gen.h b/include/uapi/linux/ctlv_attestation_gen.h\nnew file mode 100644\nindex 0000000000000..888bbf06618b1\n--- /dev/null\n+++ b/include/uapi/linux/ctlv_attestation_gen.h\n@@ -0,0 +1,252 @@\n+/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) */\n+/* Do not edit, regenerate with tools/ctlv/ctlv-regen.sh, from: */\n+/*\tDocumentation/ctlv/specs/ctlv-attestation.yaml */\n+/* CTLV-GEN uapi header */\n+\n+/*\n+ * Constants of the ctlv-attestation CTLV family. Attr and op IDs are complete; the wire format\n+ * carrying them is in \u003clinux/ctlv.h\u003e.\n+ *\n+ * The inherited ctlv header is included here, so one include covers the whole effective schema.\n+ */\n+\n+#ifndef _UAPI_LINUX_CTLV_ATTESTATION_GEN_H\n+#define _UAPI_LINUX_CTLV_ATTESTATION_GEN_H\n+\n+#include \u003clinux/const.h\u003e\n+#include \u003clinux/ctlv.h\u003e\n+#include \u003clinux/ctlv_families_gen.h\u003e\n+#include \u003clinux/ctlv_gen.h\u003e\n+\n+/* enum evidence-representation */\n+enum _ctlv_attestation_evidence_representation {\n+\tCTLV_ATTESTATION_EVIDENCE_REPRESENTATION_RAW = 1,\n+};\n+\n+/* enum evidence-blob-class */\n+enum _ctlv_attestation_evidence_blob_class {\n+\tCTLV_ATTESTATION_EVIDENCE_BLOB_CLASS_PRIMARY = 1,\n+};\n+\n+/* enum mr-log-event */\n+enum _ctlv_attestation_mr_log_event {\n+\tCTLV_ATTESTATION_MR_LOG_EVENT_INFO = 1,\n+\tCTLV_ATTESTATION_MR_LOG_EVENT_EXTEND,\n+};\n+\n+/* flags mr-device-caps */\n+enum _ctlv_attestation_mr_device_caps_bit {\n+\tCTLV_ATTESTATION_MR_DEVICE_CAPS_READ_BIT,\n+\tCTLV_ATTESTATION_MR_DEVICE_CAPS_EXTEND_BIT,\n+};\n+\n+#define CTLV_ATTESTATION_MR_DEVICE_CAPS_READ _BITULL(CTLV_ATTESTATION_MR_DEVICE_CAPS_READ_BIT)\n+#define CTLV_ATTESTATION_MR_DEVICE_CAPS_EXTEND _BITULL(CTLV_ATTESTATION_MR_DEVICE_CAPS_EXTEND_BIT)\n+#define CTLV_ATTESTATION_MR_DEVICE_CAPS_MASK \\\n+\t(CTLV_ATTESTATION_MR_DEVICE_CAPS_READ | \\\n+\t CTLV_ATTESTATION_MR_DEVICE_CAPS_EXTEND)\n+\n+/* flags mr-caps */\n+enum _ctlv_attestation_mr_caps_bit {\n+\tCTLV_ATTESTATION_MR_CAPS_READ_BIT,\n+\tCTLV_ATTESTATION_MR_CAPS_EXTEND_BIT,\n+};\n+\n+#define CTLV_ATTESTATION_MR_CAPS_READ _BITULL(CTLV_ATTESTATION_MR_CAPS_READ_BIT)\n+#define CTLV_ATTESTATION_MR_CAPS_EXTEND _BITULL(CTLV_ATTESTATION_MR_CAPS_EXTEND_BIT)\n+#define CTLV_ATTESTATION_MR_CAPS_MASK \\\n+\t(CTLV_ATTESTATION_MR_CAPS_READ | \\\n+\t CTLV_ATTESTATION_MR_CAPS_EXTEND)\n+\n+/* attr groups */\n+enum _ctlv_attestation_group {\n+\tCTLV_ATTESTATION_GROUP_DEVICE = 1,\n+\tCTLV_ATTESTATION_GROUP_CAP,\n+\tCTLV_ATTESTATION_GROUP_EVIDENCE,\n+\tCTLV_ATTESTATION_GROUP_MR,\n+\tCTLV_ATTESTATION_GROUP_LOG,\n+\tCTLV_ATTESTATION_GROUP_NOTIFICATION,\n+};\n+\n+#define _CTLV_ATTESTATION_ATTR(_group, _attr) CTLV_ATTR(CTLV_FAMILY_ATTESTATION, (_group), (_attr))\n+\n+/* attrs of group device */\n+#define _CTLV_ATTESTATION_ATTR_DEVICE(_attr) \\\n+\t_CTLV_ATTESTATION_ATTR(CTLV_ATTESTATION_GROUP_DEVICE, _CTLV_ATTESTATION_ATTR_DEVICE_##_attr)\n+\n+enum _ctlv_attestation_attr_device {\n+\t_CTLV_ATTESTATION_ATTR_DEVICE_GENERATION = 1,\n+\t_CTLV_ATTESTATION_ATTR_DEVICE_CAPS,\n+\t_CTLV_ATTESTATION_ATTR_DEVICE_INFO,\n+};\n+\n+#define CTLV_ATTESTATION_ATTR_DEVICE_GENERATION _CTLV_ATTESTATION_ATTR_DEVICE(GENERATION)\n+#define CTLV_ATTESTATION_ATTR_DEVICE_CAPS _CTLV_ATTESTATION_ATTR_DEVICE(CAPS)\n+#define CTLV_ATTESTATION_ATTR_DEVICE_INFO _CTLV_ATTESTATION_ATTR_DEVICE(INFO)\n+\n+/* attrs of group cap */\n+#define _CTLV_ATTESTATION_ATTR_CAP(_attr) \\\n+\t_CTLV_ATTESTATION_ATTR(CTLV_ATTESTATION_GROUP_CAP, _CTLV_ATTESTATION_ATTR_CAP_##_attr)\n+\n+enum _ctlv_attestation_attr_cap {\n+\t_CTLV_ATTESTATION_ATTR_CAP_EVIDENCE = 1,\n+\t_CTLV_ATTESTATION_ATTR_CAP_MR,\n+\t_CTLV_ATTESTATION_ATTR_CAP_MIN_CHALLENGE_LENGTH,\n+\t_CTLV_ATTESTATION_ATTR_CAP_MAX_CHALLENGE_LENGTH,\n+\t_CTLV_ATTESTATION_ATTR_CAP_MAX_TOTAL_OUTPUT_LENGTH,\n+\t_CTLV_ATTESTATION_ATTR_CAP_MR_FLAGS,\n+\t_CTLV_ATTESTATION_ATTR_CAP_OBJECT,\n+\t_CTLV_ATTESTATION_ATTR_CAP_BLOB_CLASS,\n+\t_CTLV_ATTESTATION_ATTR_CAP_FORMAT,\n+\t_CTLV_ATTESTATION_ATTR_CAP_REPRESENTATION,\n+\t_CTLV_ATTESTATION_ATTR_CAP_MAX_LENGTH,\n+};\n+\n+#define CTLV_ATTESTATION_ATTR_CAP_EVIDENCE _CTLV_ATTESTATION_ATTR_CAP(EVIDENCE)\n+#define CTLV_ATTESTATION_ATTR_CAP_MR _CTLV_ATTESTATION_ATTR_CAP(MR)\n+#define CTLV_ATTESTATION_ATTR_CAP_MIN_CHALLENGE_LENGTH \\\n+\t_CTLV_ATTESTATION_ATTR_CAP(MIN_CHALLENGE_LENGTH)\n+#define CTLV_ATTESTATION_ATTR_CAP_MAX_CHALLENGE_LENGTH \\\n+\t_CTLV_ATTESTATION_ATTR_CAP(MAX_CHALLENGE_LENGTH)\n+#define CTLV_ATTESTATION_ATTR_CAP_MAX_TOTAL_OUTPUT_LENGTH \\\n+\t_CTLV_ATTESTATION_ATTR_CAP(MAX_TOTAL_OUTPUT_LENGTH)\n+#define CTLV_ATTESTATION_ATTR_CAP_MR_FLAGS _CTLV_ATTESTATION_ATTR_CAP(MR_FLAGS)\n+#define CTLV_ATTESTATION_ATTR_CAP_OBJECT _CTLV_ATTESTATION_ATTR_CAP(OBJECT)\n+#define CTLV_ATTESTATION_ATTR_CAP_BLOB_CLASS _CTLV_ATTESTATION_ATTR_CAP(BLOB_CLASS)\n+#define CTLV_ATTESTATION_ATTR_CAP_FORMAT _CTLV_ATTESTATION_ATTR_CAP(FORMAT)\n+#define CTLV_ATTESTATION_ATTR_CAP_REPRESENTATION _CTLV_ATTESTATION_ATTR_CAP(REPRESENTATION)\n+#define CTLV_ATTESTATION_ATTR_CAP_MAX_LENGTH _CTLV_ATTESTATION_ATTR_CAP(MAX_LENGTH)\n+\n+/* attrs of group evidence */\n+#define _CTLV_ATTESTATION_ATTR_EVIDENCE(_attr) \\\n+\t_CTLV_ATTESTATION_ATTR(CTLV_ATTESTATION_GROUP_EVIDENCE, \\\n+\t\t\t       _CTLV_ATTESTATION_ATTR_EVIDENCE_##_attr)\n+\n+enum _ctlv_attestation_attr_evidence {\n+\t_CTLV_ATTESTATION_ATTR_EVIDENCE_CHALLENGE = 1,\n+\t_CTLV_ATTESTATION_ATTR_EVIDENCE_OBJECT,\n+\t_CTLV_ATTESTATION_ATTR_EVIDENCE_BLOB_CLASS,\n+\t_CTLV_ATTESTATION_ATTR_EVIDENCE_FORMAT,\n+\t_CTLV_ATTESTATION_ATTR_EVIDENCE_REPRESENTATION,\n+\t_CTLV_ATTESTATION_ATTR_EVIDENCE_DATA,\n+\t_CTLV_ATTESTATION_ATTR_EVIDENCE_OBJECT_LENGTH,\n+};\n+\n+#define CTLV_ATTESTATION_ATTR_EVIDENCE_CHALLENGE _CTLV_ATTESTATION_ATTR_EVIDENCE(CHALLENGE)\n+#define CTLV_ATTESTATION_ATTR_EVIDENCE_OBJECT _CTLV_ATTESTATION_ATTR_EVIDENCE(OBJECT)\n+#define CTLV_ATTESTATION_ATTR_EVIDENCE_BLOB_CLASS _CTLV_ATTESTATION_ATTR_EVIDENCE(BLOB_CLASS)\n+#define CTLV_ATTESTATION_ATTR_EVIDENCE_FORMAT _CTLV_ATTESTATION_ATTR_EVIDENCE(FORMAT)\n+#define CTLV_ATTESTATION_ATTR_EVIDENCE_REPRESENTATION \\\n+\t_CTLV_ATTESTATION_ATTR_EVIDENCE(REPRESENTATION)\n+#define CTLV_ATTESTATION_ATTR_EVIDENCE_DATA _CTLV_ATTESTATION_ATTR_EVIDENCE(DATA)\n+#define CTLV_ATTESTATION_ATTR_EVIDENCE_OBJECT_LENGTH _CTLV_ATTESTATION_ATTR_EVIDENCE(OBJECT_LENGTH)\n+\n+/* attrs of group mr */\n+#define _CTLV_ATTESTATION_ATTR_MR(_attr) \\\n+\t_CTLV_ATTESTATION_ATTR(CTLV_ATTESTATION_GROUP_MR, _CTLV_ATTESTATION_ATTR_MR_##_attr)\n+\n+enum _ctlv_attestation_attr_mr {\n+\t_CTLV_ATTESTATION_ATTR_MR_ID = 1,\n+\t_CTLV_ATTESTATION_ATTR_MR_NAME,\n+\t_CTLV_ATTESTATION_ATTR_MR_HASH_ALGO,\n+\t_CTLV_ATTESTATION_ATTR_MR_SUPPORTED_HASH_ALGO,\n+\t_CTLV_ATTESTATION_ATTR_MR_REGISTER_INDEX,\n+\t_CTLV_ATTESTATION_ATTR_MR_CAPS,\n+\t_CTLV_ATTESTATION_ATTR_MR_ITEM,\n+\t_CTLV_ATTESTATION_ATTR_MR_VALUE,\n+\t_CTLV_ATTESTATION_ATTR_MR_DATA,\n+\t_CTLV_ATTESTATION_ATTR_MR_GENERATION,\n+\t_CTLV_ATTESTATION_ATTR_MR_SELECTION,\n+\t_CTLV_ATTESTATION_ATTR_MR_START_GENERATION,\n+\t_CTLV_ATTESTATION_ATTR_MR_END_GENERATION,\n+};\n+\n+#define CTLV_ATTESTATION_ATTR_MR_ID _CTLV_ATTESTATION_ATTR_MR(ID)\n+#define CTLV_ATTESTATION_ATTR_MR_NAME _CTLV_ATTESTATION_ATTR_MR(NAME)\n+#define CTLV_ATTESTATION_ATTR_MR_HASH_ALGO _CTLV_ATTESTATION_ATTR_MR(HASH_ALGO)\n+#define CTLV_ATTESTATION_ATTR_MR_SUPPORTED_HASH_ALGO _CTLV_ATTESTATION_ATTR_MR(SUPPORTED_HASH_ALGO)\n+#define CTLV_ATTESTATION_ATTR_MR_REGISTER_INDEX _CTLV_ATTESTATION_ATTR_MR(REGISTER_INDEX)\n+#define CTLV_ATTESTATION_ATTR_MR_CAPS _CTLV_ATTESTATION_ATTR_MR(CAPS)\n+#define CTLV_ATTESTATION_ATTR_MR_ITEM _CTLV_ATTESTATION_ATTR_MR(ITEM)\n+#define CTLV_ATTESTATION_ATTR_MR_VALUE _CTLV_ATTESTATION_ATTR_MR(VALUE)\n+#define CTLV_ATTESTATION_ATTR_MR_DATA _CTLV_ATTESTATION_ATTR_MR(DATA)\n+#define CTLV_ATTESTATION_ATTR_MR_GENERATION _CTLV_ATTESTATION_ATTR_MR(GENERATION)\n+#define CTLV_ATTESTATION_ATTR_MR_SELECTION _CTLV_ATTESTATION_ATTR_MR(SELECTION)\n+#define CTLV_ATTESTATION_ATTR_MR_START_GENERATION _CTLV_ATTESTATION_ATTR_MR(START_GENERATION)\n+#define CTLV_ATTESTATION_ATTR_MR_END_GENERATION _CTLV_ATTESTATION_ATTR_MR(END_GENERATION)\n+\n+/* attrs of group log */\n+#define _CTLV_ATTESTATION_ATTR_LOG(_attr) \\\n+\t_CTLV_ATTESTATION_ATTR(CTLV_ATTESTATION_GROUP_LOG, _CTLV_ATTESTATION_ATTR_LOG_##_attr)\n+\n+enum _ctlv_attestation_attr_log {\n+\t_CTLV_ATTESTATION_ATTR_LOG_ENTRY = 1,\n+\t_CTLV_ATTESTATION_ATTR_LOG_EVENT,\n+\t_CTLV_ATTESTATION_ATTR_LOG_MR,\n+};\n+\n+#define CTLV_ATTESTATION_ATTR_LOG_ENTRY _CTLV_ATTESTATION_ATTR_LOG(ENTRY)\n+#define CTLV_ATTESTATION_ATTR_LOG_EVENT _CTLV_ATTESTATION_ATTR_LOG(EVENT)\n+#define CTLV_ATTESTATION_ATTR_LOG_MR _CTLV_ATTESTATION_ATTR_LOG(MR)\n+\n+/* attrs of group notification */\n+#define _CTLV_ATTESTATION_ATTR_NOTIFICATION(_attr) \\\n+\t_CTLV_ATTESTATION_ATTR(CTLV_ATTESTATION_GROUP_NOTIFICATION, \\\n+\t\t\t       _CTLV_ATTESTATION_ATTR_NOTIFICATION_##_attr)\n+\n+enum _ctlv_attestation_attr_notification {\n+\t_CTLV_ATTESTATION_ATTR_NOTIFICATION_ENTRY = 1,\n+};\n+\n+#define CTLV_ATTESTATION_ATTR_NOTIFICATION_ENTRY _CTLV_ATTESTATION_ATTR_NOTIFICATION(ENTRY)\n+\n+/* attr sets */\n+enum _ctlv_attestation_set {\n+\tCTLV_ATTESTATION_SET_DEVICE_INFO = 1,\n+\tCTLV_ATTESTATION_SET_EVIDENCE_OBJECT_CAP,\n+\tCTLV_ATTESTATION_SET_EVIDENCE_CAP,\n+\tCTLV_ATTESTATION_SET_MR_DEVICE_CAP,\n+\tCTLV_ATTESTATION_SET_DEVICE_CAPS,\n+\tCTLV_ATTESTATION_SET_DEVICE_REPLY,\n+\tCTLV_ATTESTATION_SET_EVIDENCE_OBJECT_REQUEST,\n+\tCTLV_ATTESTATION_SET_EVIDENCE_REQUEST,\n+\tCTLV_ATTESTATION_SET_EVIDENCE_REPLY,\n+\tCTLV_ATTESTATION_SET_MR_PROPS,\n+\tCTLV_ATTESTATION_SET_MR_DUMP_ENTRY,\n+\tCTLV_ATTESTATION_SET_MR_ID_REQUEST,\n+\tCTLV_ATTESTATION_SET_MR_READ_REQUEST,\n+\tCTLV_ATTESTATION_SET_MR_VALUE,\n+\tCTLV_ATTESTATION_SET_MR_READ_REPLY,\n+\tCTLV_ATTESTATION_SET_MR_EXTEND_REQUEST,\n+\tCTLV_ATTESTATION_SET_MR_CHANGE_REPLY,\n+\tCTLV_ATTESTATION_SET_MR_LOG_INFO,\n+\tCTLV_ATTESTATION_SET_MR_LOG_ENTRY,\n+\tCTLV_ATTESTATION_SET_MR_LOG_EVENT,\n+\tCTLV_ATTESTATION_SET_MR_LOG_SELECTION,\n+\tCTLV_ATTESTATION_SET_MR_LOG_REQUEST,\n+\tCTLV_ATTESTATION_SET_MR_LOG_REPLY,\n+};\n+\n+/* ops */\n+enum _ctlv_attestation_op {\n+\t_CTLV_ATTESTATION_OP_DEVICE_GET = 1,\n+\t_CTLV_ATTESTATION_OP_EVIDENCE_GET,\n+\t_CTLV_ATTESTATION_OP_MR_GET,\n+\t_CTLV_ATTESTATION_OP_MR_DUMP,\n+\t_CTLV_ATTESTATION_OP_MR_READ,\n+\t_CTLV_ATTESTATION_OP_MR_EXTEND,\n+\t_CTLV_ATTESTATION_OP_MR_LOG_ENTRY_APPENDED,\n+\t_CTLV_ATTESTATION_OP_MR_LOG_GET,\n+};\n+\n+#define _CTLV_ATTESTATION_OP(_op) CTLV_OP(CTLV_FAMILY_ATTESTATION, _CTLV_ATTESTATION_OP_##_op)\n+#define CTLV_ATTESTATION_OP_DEVICE_GET _CTLV_ATTESTATION_OP(DEVICE_GET)\n+#define CTLV_ATTESTATION_OP_EVIDENCE_GET _CTLV_ATTESTATION_OP(EVIDENCE_GET)\n+#define CTLV_ATTESTATION_OP_MR_GET _CTLV_ATTESTATION_OP(MR_GET)\n+#define CTLV_ATTESTATION_OP_MR_DUMP _CTLV_ATTESTATION_OP(MR_DUMP)\n+#define CTLV_ATTESTATION_OP_MR_READ _CTLV_ATTESTATION_OP(MR_READ)\n+#define CTLV_ATTESTATION_OP_MR_EXTEND _CTLV_ATTESTATION_OP(MR_EXTEND)\n+#define CTLV_ATTESTATION_OP_MR_LOG_ENTRY_APPENDED _CTLV_ATTESTATION_OP(MR_LOG_ENTRY_APPENDED)\n+#define CTLV_ATTESTATION_OP_MR_LOG_GET _CTLV_ATTESTATION_OP(MR_LOG_GET)\n+\n+#endif /* _UAPI_LINUX_CTLV_ATTESTATION_GEN_H */\ndiff --git a/include/uapi/linux/ctlv_attestation_tdx_gen.h b/include/uapi/linux/ctlv_attestation_tdx_gen.h\nnew file mode 100644\nindex 0000000000000..04c8dbc3d07c8\n--- /dev/null\n+++ b/include/uapi/linux/ctlv_attestation_tdx_gen.h\n@@ -0,0 +1,44 @@\n+/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) */\n+/* Do not edit, regenerate with tools/ctlv/ctlv-regen.sh, from: */\n+/*\tDocumentation/ctlv/specs/ctlv-attestation-tdx.yaml */\n+/* CTLV-GEN uapi header */\n+\n+/*\n+ * Constants of the ctlv-attestation-tdx CTLV family. Attr and op IDs are complete; the wire format\n+ * carrying them is in \u003clinux/ctlv.h\u003e.\n+ *\n+ * The inherited ctlv-attestation header is included here, so one include covers the whole effective\n+ * schema.\n+ */\n+\n+#ifndef _UAPI_LINUX_CTLV_ATTESTATION_TDX_GEN_H\n+#define _UAPI_LINUX_CTLV_ATTESTATION_TDX_GEN_H\n+\n+#include \u003clinux/ctlv.h\u003e\n+#include \u003clinux/ctlv_attestation_gen.h\u003e\n+#include \u003clinux/ctlv_families_gen.h\u003e\n+\n+/* attr groups */\n+enum _ctlv_attestation_tdx_group {\n+\tCTLV_ATTESTATION_TDX_GROUP_INFO = 1,\n+};\n+\n+#define _CTLV_ATTESTATION_TDX_ATTR(_group, _attr) \\\n+\tCTLV_ATTR(CTLV_FAMILY_ATTESTATION_TDX, (_group), (_attr))\n+\n+/* attrs of group info */\n+#define _CTLV_ATTESTATION_TDX_ATTR_INFO(_attr) \\\n+\t_CTLV_ATTESTATION_TDX_ATTR(CTLV_ATTESTATION_TDX_GROUP_INFO, \\\n+\t\t\t\t   _CTLV_ATTESTATION_TDX_ATTR_INFO_##_attr)\n+\n+enum _ctlv_attestation_tdx_attr_info {\n+\t_CTLV_ATTESTATION_TDX_ATTR_INFO_MRCONFIGID = 1,\n+\t_CTLV_ATTESTATION_TDX_ATTR_INFO_MROWNER,\n+\t_CTLV_ATTESTATION_TDX_ATTR_INFO_MROWNERCONFIG,\n+};\n+\n+#define CTLV_ATTESTATION_TDX_ATTR_INFO_MRCONFIGID _CTLV_ATTESTATION_TDX_ATTR_INFO(MRCONFIGID)\n+#define CTLV_ATTESTATION_TDX_ATTR_INFO_MROWNER _CTLV_ATTESTATION_TDX_ATTR_INFO(MROWNER)\n+#define CTLV_ATTESTATION_TDX_ATTR_INFO_MROWNERCONFIG _CTLV_ATTESTATION_TDX_ATTR_INFO(MROWNERCONFIG)\n+\n+#endif /* _UAPI_LINUX_CTLV_ATTESTATION_TDX_GEN_H */\ndiff --git a/include/uapi/linux/ctlv_families_gen.h b/include/uapi/linux/ctlv_families_gen.h\nnew file mode 100644\nindex 0000000000000..25c90509d8adf\n--- /dev/null\n+++ b/include/uapi/linux/ctlv_families_gen.h\n@@ -0,0 +1,17 @@\n+/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) */\n+/* Do not edit, regenerate with tools/ctlv/ctlv-regen.sh, from: */\n+/*\tDocumentation/ctlv/families.yaml */\n+/* CTLV-GEN uapi header */\n+\n+/* CTLV family numbers. */\n+\n+#ifndef _UAPI_LINUX_CTLV_FAMILIES_GEN_H\n+#define _UAPI_LINUX_CTLV_FAMILIES_GEN_H\n+\n+enum _ctlv_family {\n+\tCTLV_FAMILY_ROOT,\n+\tCTLV_FAMILY_ATTESTATION,\n+\tCTLV_FAMILY_ATTESTATION_TDX,\n+};\n+\n+#endif /* _UAPI_LINUX_CTLV_FAMILIES_GEN_H */\ndiff --git a/include/uapi/linux/ctlv_gen.h b/include/uapi/linux/ctlv_gen.h\nnew file mode 100644\nindex 0000000000000..64eba093a6d49\n--- /dev/null\n+++ b/include/uapi/linux/ctlv_gen.h\n@@ -0,0 +1,271 @@\n+/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) */\n+/* Do not edit, regenerate with tools/ctlv/ctlv-regen.sh, from: */\n+/*\tDocumentation/ctlv/specs/ctlv.yaml */\n+/* CTLV-GEN uapi header */\n+\n+/*\n+ * Constants of the ctlv CTLV family. Attr and op IDs are complete; the wire format carrying them is\n+ * in \u003clinux/ctlv.h\u003e.\n+ */\n+\n+#ifndef _UAPI_LINUX_CTLV_GEN_H\n+#define _UAPI_LINUX_CTLV_GEN_H\n+\n+#include \u003clinux/ctlv.h\u003e\n+#include \u003clinux/ctlv_families_gen.h\u003e\n+\n+/* enum op-type */\n+enum _ctlv_op_type {\n+\tCTLV_OP_TYPE_ACTION = 1,\n+\tCTLV_OP_TYPE_QUERY,\n+\tCTLV_OP_TYPE_EVENT,\n+};\n+\n+/* enum op-availability */\n+enum _ctlv_op_availability {\n+\tCTLV_OP_AVAILABILITY_FIXED = 1,\n+\tCTLV_OP_AVAILABILITY_DYNAMIC,\n+};\n+\n+/* enum blob-type */\n+enum _ctlv_blob_type {\n+\tCTLV_BLOB_TYPE_VA = 1,\n+};\n+\n+/* enum blob-direction */\n+enum _ctlv_blob_direction {\n+\tCTLV_BLOB_DIRECTION_INPUT = 1,\n+\tCTLV_BLOB_DIRECTION_OUTPUT,\n+\tCTLV_BLOB_DIRECTION_INOUT,\n+};\n+\n+/* enum validation-reason */\n+enum _ctlv_validation_reason {\n+\tCTLV_VALIDATION_REASON_MALFORMED_MESSAGE = 1,\n+\tCTLV_VALIDATION_REASON_UNKNOWN_ATTR,\n+\tCTLV_VALIDATION_REASON_UNKNOWN_FLAG,\n+\tCTLV_VALIDATION_REASON_NESTING_TOO_DEEP,\n+\tCTLV_VALIDATION_REASON_MISSING_ATTR,\n+\tCTLV_VALIDATION_REASON_TOO_MANY_OCCURRENCES,\n+\tCTLV_VALIDATION_REASON_VALUE_OUT_OF_RANGE,\n+\tCTLV_VALIDATION_REASON_BAD_LENGTH,\n+\tCTLV_VALIDATION_REASON_BAD_STRING,\n+\tCTLV_VALIDATION_REASON_BAD_BLOB_DESCRIPTOR,\n+\tCTLV_VALIDATION_REASON_STALE_GENERATION,\n+\tCTLV_VALIDATION_REASON_NONCONTIGUOUS_ATTR,\n+};\n+\n+/* enum op-fd-access */\n+enum _ctlv_op_fd_access {\n+\tCTLV_OP_FD_ACCESS_READ = 1,\n+\tCTLV_OP_FD_ACCESS_READ_WRITE,\n+};\n+\n+/* attr groups */\n+enum _ctlv_group {\n+\tCTLV_GROUP_FAMILY = 1,\n+\tCTLV_GROUP_BLOB,\n+\tCTLV_GROUP_ERROR,\n+\tCTLV_GROUP_OP,\n+\tCTLV_GROUP_SCHEMA,\n+\tCTLV_GROUP_EVENT,\n+};\n+\n+#define _CTLV_ATTR(_group, _attr) CTLV_ATTR(CTLV_FAMILY_ROOT, (_group), (_attr))\n+\n+/* attrs of group family */\n+#define _CTLV_ATTR_FAMILY(_attr) _CTLV_ATTR(CTLV_GROUP_FAMILY, _CTLV_ATTR_FAMILY_##_attr)\n+\n+enum _ctlv_attr_family {\n+\t_CTLV_ATTR_FAMILY_ID = 1,\n+\t_CTLV_ATTR_FAMILY_NAME,\n+\t_CTLV_ATTR_FAMILY_ENTRY,\n+};\n+\n+#define CTLV_ATTR_FAMILY_ID _CTLV_ATTR_FAMILY(ID)\n+#define CTLV_ATTR_FAMILY_NAME _CTLV_ATTR_FAMILY(NAME)\n+#define CTLV_ATTR_FAMILY_ENTRY _CTLV_ATTR_FAMILY(ENTRY)\n+\n+/* attrs of group blob */\n+#define _CTLV_ATTR_BLOB(_attr) _CTLV_ATTR(CTLV_GROUP_BLOB, _CTLV_ATTR_BLOB_##_attr)\n+\n+enum _ctlv_attr_blob {\n+\t_CTLV_ATTR_BLOB_TYPE = 1,\n+\t_CTLV_ATTR_BLOB_ADDRESS,\n+\t_CTLV_ATTR_BLOB_FD,\n+\t_CTLV_ATTR_BLOB_OFFSET,\n+\t_CTLV_ATTR_BLOB_LENGTH,\n+};\n+\n+#define CTLV_ATTR_BLOB_TYPE _CTLV_ATTR_BLOB(TYPE)\n+#define CTLV_ATTR_BLOB_ADDRESS _CTLV_ATTR_BLOB(ADDRESS)\n+#define CTLV_ATTR_BLOB_FD _CTLV_ATTR_BLOB(FD)\n+#define CTLV_ATTR_BLOB_OFFSET _CTLV_ATTR_BLOB(OFFSET)\n+#define CTLV_ATTR_BLOB_LENGTH _CTLV_ATTR_BLOB(LENGTH)\n+\n+/* attrs of group error */\n+#define _CTLV_ATTR_ERROR(_attr) _CTLV_ATTR(CTLV_GROUP_ERROR, _CTLV_ATTR_ERROR_##_attr)\n+\n+enum _ctlv_attr_error {\n+\t_CTLV_ATTR_ERROR_REASON = 1,\n+\t_CTLV_ATTR_ERROR_MESSAGE,\n+\t_CTLV_ATTR_ERROR_BAD_ATTR_OFFSET,\n+\t_CTLV_ATTR_ERROR_NEST_OFFSET,\n+\t_CTLV_ATTR_ERROR_MISSING_ATTR_ID,\n+\t_CTLV_ATTR_ERROR_EXPECTED_GENERATION,\n+\t_CTLV_ATTR_ERROR_CURRENT_GENERATION,\n+};\n+\n+#define CTLV_ATTR_ERROR_REASON _CTLV_ATTR_ERROR(REASON)\n+#define CTLV_ATTR_ERROR_MESSAGE _CTLV_ATTR_ERROR(MESSAGE)\n+#define CTLV_ATTR_ERROR_BAD_ATTR_OFFSET _CTLV_ATTR_ERROR(BAD_ATTR_OFFSET)\n+#define CTLV_ATTR_ERROR_NEST_OFFSET _CTLV_ATTR_ERROR(NEST_OFFSET)\n+#define CTLV_ATTR_ERROR_MISSING_ATTR_ID _CTLV_ATTR_ERROR(MISSING_ATTR_ID)\n+#define CTLV_ATTR_ERROR_EXPECTED_GENERATION _CTLV_ATTR_ERROR(EXPECTED_GENERATION)\n+#define CTLV_ATTR_ERROR_CURRENT_GENERATION _CTLV_ATTR_ERROR(CURRENT_GENERATION)\n+\n+/* attrs of group op */\n+#define _CTLV_ATTR_OP(_attr) _CTLV_ATTR(CTLV_GROUP_OP, _CTLV_ATTR_OP_##_attr)\n+\n+enum _ctlv_attr_op {\n+\t_CTLV_ATTR_OP_ID = 1,\n+\t_CTLV_ATTR_OP_TYPE,\n+\t_CTLV_ATTR_OP_AVAILABILITY,\n+\t_CTLV_ATTR_OP_DISABLED,\n+\t_CTLV_ATTR_OP_REQUEST_MAX_LEN,\n+\t_CTLV_ATTR_OP_ACTION_REPLY_MAX_LEN,\n+\t_CTLV_ATTR_OP_QUERY_REPLY_MIN_LEN,\n+\t_CTLV_ATTR_OP_QUERY_REPLY_SUGGESTED_LEN,\n+\t_CTLV_ATTR_OP_EVENT_RECORD_MAX_LEN,\n+\t_CTLV_ATTR_OP_STATE_GENERATION,\n+\t_CTLV_ATTR_OP_ENTRY,\n+\t_CTLV_ATTR_OP_FD_ACCESS,\n+};\n+\n+#define CTLV_ATTR_OP_ID _CTLV_ATTR_OP(ID)\n+#define CTLV_ATTR_OP_TYPE _CTLV_ATTR_OP(TYPE)\n+#define CTLV_ATTR_OP_AVAILABILITY _CTLV_ATTR_OP(AVAILABILITY)\n+#define CTLV_ATTR_OP_DISABLED _CTLV_ATTR_OP(DISABLED)\n+#define CTLV_ATTR_OP_REQUEST_MAX_LEN _CTLV_ATTR_OP(REQUEST_MAX_LEN)\n+#define CTLV_ATTR_OP_ACTION_REPLY_MAX_LEN _CTLV_ATTR_OP(ACTION_REPLY_MAX_LEN)\n+#define CTLV_ATTR_OP_QUERY_REPLY_MIN_LEN _CTLV_ATTR_OP(QUERY_REPLY_MIN_LEN)\n+#define CTLV_ATTR_OP_QUERY_REPLY_SUGGESTED_LEN _CTLV_ATTR_OP(QUERY_REPLY_SUGGESTED_LEN)\n+#define CTLV_ATTR_OP_EVENT_RECORD_MAX_LEN _CTLV_ATTR_OP(EVENT_RECORD_MAX_LEN)\n+#define CTLV_ATTR_OP_STATE_GENERATION _CTLV_ATTR_OP(STATE_GENERATION)\n+#define CTLV_ATTR_OP_ENTRY _CTLV_ATTR_OP(ENTRY)\n+#define CTLV_ATTR_OP_FD_ACCESS _CTLV_ATTR_OP(FD_ACCESS)\n+\n+/* attrs of group schema */\n+#define _CTLV_ATTR_SCHEMA(_attr) _CTLV_ATTR(CTLV_GROUP_SCHEMA, _CTLV_ATTR_SCHEMA_##_attr)\n+\n+enum _ctlv_attr_schema {\n+\t_CTLV_ATTR_SCHEMA_ATTR_ID = 1,\n+\t_CTLV_ATTR_SCHEMA_KIND,\n+\t_CTLV_ATTR_SCHEMA_MAX_OCCURRENCES,\n+\t_CTLV_ATTR_SCHEMA_MIN,\n+\t_CTLV_ATTR_SCHEMA_MAX,\n+\t_CTLV_ATTR_SCHEMA_MIN_LENGTH,\n+\t_CTLV_ATTR_SCHEMA_MAX_LENGTH,\n+\t_CTLV_ATTR_SCHEMA_FLAGS_MASK,\n+\t_CTLV_ATTR_SCHEMA_UNIT,\n+\t_CTLV_ATTR_SCHEMA_SCALE,\n+\t_CTLV_ATTR_SCHEMA_BLOB_DIRECTION,\n+\t_CTLV_ATTR_SCHEMA_BLOB_BACKINGS,\n+\t_CTLV_ATTR_SCHEMA_BLOB_MAX_LENGTH,\n+\t_CTLV_ATTR_SCHEMA_BLOB_ALIGNMENT,\n+\t_CTLV_ATTR_SCHEMA_REENTERS,\n+\t_CTLV_ATTR_SCHEMA_ATTRS,\n+\t_CTLV_ATTR_SCHEMA_OPTIONAL_ATTRS,\n+\t_CTLV_ATTR_SCHEMA_REQUEST,\n+\t_CTLV_ATTR_SCHEMA_REPLY,\n+};\n+\n+#define CTLV_ATTR_SCHEMA_ATTR_ID _CTLV_ATTR_SCHEMA(ATTR_ID)\n+#define CTLV_ATTR_SCHEMA_KIND _CTLV_ATTR_SCHEMA(KIND)\n+#define CTLV_ATTR_SCHEMA_MAX_OCCURRENCES _CTLV_ATTR_SCHEMA(MAX_OCCURRENCES)\n+#define CTLV_ATTR_SCHEMA_MIN _CTLV_ATTR_SCHEMA(MIN)\n+#define CTLV_ATTR_SCHEMA_MAX _CTLV_ATTR_SCHEMA(MAX)\n+#define CTLV_ATTR_SCHEMA_MIN_LENGTH _CTLV_ATTR_SCHEMA(MIN_LENGTH)\n+#define CTLV_ATTR_SCHEMA_MAX_LENGTH _CTLV_ATTR_SCHEMA(MAX_LENGTH)\n+#define CTLV_ATTR_SCHEMA_FLAGS_MASK _CTLV_ATTR_SCHEMA(FLAGS_MASK)\n+#define CTLV_ATTR_SCHEMA_UNIT _CTLV_ATTR_SCHEMA(UNIT)\n+#define CTLV_ATTR_SCHEMA_SCALE _CTLV_ATTR_SCHEMA(SCALE)\n+#define CTLV_ATTR_SCHEMA_BLOB_DIRECTION _CTLV_ATTR_SCHEMA(BLOB_DIRECTION)\n+#define CTLV_ATTR_SCHEMA_BLOB_BACKINGS _CTLV_ATTR_SCHEMA(BLOB_BACKINGS)\n+#define CTLV_ATTR_SCHEMA_BLOB_MAX_LENGTH _CTLV_ATTR_SCHEMA(BLOB_MAX_LENGTH)\n+#define CTLV_ATTR_SCHEMA_BLOB_ALIGNMENT _CTLV_ATTR_SCHEMA(BLOB_ALIGNMENT)\n+#define CTLV_ATTR_SCHEMA_REENTERS _CTLV_ATTR_SCHEMA(REENTERS)\n+#define CTLV_ATTR_SCHEMA_ATTRS _CTLV_ATTR_SCHEMA(ATTRS)\n+#define CTLV_ATTR_SCHEMA_OPTIONAL_ATTRS _CTLV_ATTR_SCHEMA(OPTIONAL_ATTRS)\n+#define CTLV_ATTR_SCHEMA_REQUEST _CTLV_ATTR_SCHEMA(REQUEST)\n+#define CTLV_ATTR_SCHEMA_REPLY _CTLV_ATTR_SCHEMA(REPLY)\n+\n+/* attrs of group event */\n+#define _CTLV_ATTR_EVENT(_attr) _CTLV_ATTR(CTLV_GROUP_EVENT, _CTLV_ATTR_EVENT_##_attr)\n+\n+enum _ctlv_attr_event {\n+\t_CTLV_ATTR_EVENT_OP_ID = 1,\n+\t_CTLV_ATTR_EVENT_QUEUE_LEN,\n+\t_CTLV_ATTR_EVENT_QUEUE_USED,\n+\t_CTLV_ATTR_EVENT_FIRST_SEQUENCE,\n+\t_CTLV_ATTR_EVENT_LAST_SEQUENCE,\n+\t_CTLV_ATTR_EVENT_DROPPED_COUNT,\n+};\n+\n+#define CTLV_ATTR_EVENT_OP_ID _CTLV_ATTR_EVENT(OP_ID)\n+#define CTLV_ATTR_EVENT_QUEUE_LEN _CTLV_ATTR_EVENT(QUEUE_LEN)\n+#define CTLV_ATTR_EVENT_QUEUE_USED _CTLV_ATTR_EVENT(QUEUE_USED)\n+#define CTLV_ATTR_EVENT_FIRST_SEQUENCE _CTLV_ATTR_EVENT(FIRST_SEQUENCE)\n+#define CTLV_ATTR_EVENT_LAST_SEQUENCE _CTLV_ATTR_EVENT(LAST_SEQUENCE)\n+#define CTLV_ATTR_EVENT_DROPPED_COUNT _CTLV_ATTR_EVENT(DROPPED_COUNT)\n+\n+/* metadata of group event */\n+enum _ctlv_attr_event_metadata {\n+\tCTLV_ATTR_EVENT_QUEUE_LEN_UNIT = CTLV_UNIT_BYTES,\n+\tCTLV_ATTR_EVENT_QUEUE_LEN_SCALE = 0,\n+\tCTLV_ATTR_EVENT_QUEUE_USED_UNIT = CTLV_UNIT_BYTES,\n+\tCTLV_ATTR_EVENT_QUEUE_USED_SCALE = 0,\n+};\n+\n+/* attr sets */\n+enum _ctlv_set {\n+\tCTLV_SET_FAMILY_ENTRY = 1,\n+\tCTLV_SET_OP_ENTRY,\n+\tCTLV_SET_OP_SCHEMA_REQUEST,\n+\tCTLV_SET_SCHEMA_NODE,\n+\tCTLV_SET_OP_SCHEMA_INFO,\n+\tCTLV_SET_OP_CHANGE_INFO,\n+\tCTLV_SET_ERROR_INFO,\n+\tCTLV_SET_EVENT_SUBSCRIPTION,\n+\tCTLV_SET_EVENT_QUEUE_LIMIT,\n+\tCTLV_SET_EVENT_QUEUE_STATE,\n+\tCTLV_SET_EVENT_OVERFLOW_INFO,\n+};\n+\n+/* ops */\n+enum _ctlv_op {\n+\t_CTLV_OP_FAMILIES_DUMP = 1,\n+\t_CTLV_OP_OPS_DUMP,\n+\t_CTLV_OP_OP_SCHEMA_GET,\n+\t_CTLV_OP_SUBSCRIPTIONS_ADD,\n+\t_CTLV_OP_SUBSCRIPTIONS_REMOVE,\n+\t_CTLV_OP_EVENT_QUEUE_GET,\n+\t_CTLV_OP_EVENT_QUEUE_SET,\n+\t_CTLV_OP_OP_CHANGED,\n+\t_CTLV_OP_EVENT_OVERFLOW,\n+\t_CTLV_OP_DEVICE_REMOVED,\n+};\n+\n+#define _CTLV_OP(_op) CTLV_OP(CTLV_FAMILY_ROOT, _CTLV_OP_##_op)\n+#define CTLV_OP_FAMILIES_DUMP _CTLV_OP(FAMILIES_DUMP)\n+#define CTLV_OP_OPS_DUMP _CTLV_OP(OPS_DUMP)\n+#define CTLV_OP_OP_SCHEMA_GET _CTLV_OP(OP_SCHEMA_GET)\n+#define CTLV_OP_SUBSCRIPTIONS_ADD _CTLV_OP(SUBSCRIPTIONS_ADD)\n+#define CTLV_OP_SUBSCRIPTIONS_REMOVE _CTLV_OP(SUBSCRIPTIONS_REMOVE)\n+#define CTLV_OP_EVENT_QUEUE_GET _CTLV_OP(EVENT_QUEUE_GET)\n+#define CTLV_OP_EVENT_QUEUE_SET _CTLV_OP(EVENT_QUEUE_SET)\n+#define CTLV_OP_OP_CHANGED _CTLV_OP(OP_CHANGED)\n+#define CTLV_OP_EVENT_OVERFLOW _CTLV_OP(EVENT_OVERFLOW)\n+#define CTLV_OP_DEVICE_REMOVED _CTLV_OP(DEVICE_REMOVED)\n+\n+#endif /* _UAPI_LINUX_CTLV_GEN_H */\ndiff --git a/tools/ctlv/Makefile b/tools/ctlv/Makefile\nnew file mode 100644\nindex 0000000000000..bb3129405fb54\n--- /dev/null\n+++ b/tools/ctlv/Makefile\n@@ -0,0 +1,59 @@\n+# SPDX-License-Identifier: GPL-2.0\n+\n+KDIR = ../..\n+DOCDIR = $(KDIR)/Documentation/ctlv\n+SPECDIR = $(DOCDIR)/specs\n+SPECS = $(wildcard $(SPECDIR)/*.yaml)\n+TOOL = ./ctlvgen/cli.py\n+\n+all: validate abi-check\n+\n+validate:\n+\t@for spec in $(SPECS) ; do \\\n+\t\techo -e \"\\tVALIDATE $$(basename $$spec)\" ; \\\n+\t\t$(TOOL) --spec $$spec --validate || exit 1 ; \\\n+\tdone\n+\n+# Fails when a specification no longer matches its checked-in ABI snapshot.\n+abi-check:\n+\t@for spec in $(SPECS) ; do \\\n+\t\techo -e \"\\tABICHECK $$(basename $$spec)\" ; \\\n+\t\t$(TOOL) --spec $$spec --abi-check || exit 1 ; \\\n+\tdone\n+\n+# Deliberate: an updated snapshot is how a UAPI change gets reviewed.\n+abi-update:\n+\t@for spec in $(SPECS) ; do \\\n+\t\t$(TOOL) --spec $$spec --abi-update || exit 1 ; \\\n+\tdone\n+\n+# Style checks, needing yamllint, pycodestyle and pyflakes, which the tool\n+# itself does not use.\n+#\n+# A flow sequence is written \"[ one, two ]\" here, as in the tree's other\n+# meta-schemas, which stock yamllint rejects; the same relaxation is in\n+# Documentation/devicetree/bindings/.yamllint.\n+YAMLLINT_CONF = {extends: default, rules: {brackets: {max-spaces-inside: 1}}}\n+\n+PYSRC = ctlvgen\n+\n+lint:\n+\tyamllint -d \"$(YAMLLINT_CONF)\" $(DOCDIR)\n+\tpython3 -m pycodestyle $(PYSRC)\n+\tpython3 -m pyflakes $(PYSRC)\n+\n+regen:\n+\t@./ctlv-regen.sh\n+\n+# Fails when a checked-in generated file does not match what the generator\n+# produces from the current specifications. Writes nothing.\n+check-regen:\n+\t@./ctlv-regen.sh -c\n+\n+clean:\n+\trm -rf ctlvgen/__pycache__\n+\trm -rf ctlvgen/lib/__pycache__\n+\trm -rf ctlvgen.egg-info\n+\trm -rf build\n+\n+.PHONY: all validate abi-check abi-update lint regen check-regen clean\ndiff --git a/tools/ctlv/ctlv-regen.sh b/tools/ctlv/ctlv-regen.sh\nnew file mode 100755\nindex 0000000000000..575114ba93e7c\n--- /dev/null\n+++ b/tools/ctlv/ctlv-regen.sh\n@@ -0,0 +1,55 @@\n+#!/bin/bash\n+# SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause\n+#\n+# Reconcile the checked-in files against the independent output manifests.\n+#\n+#   -f  accepted for compatibility; reconciliation always renders everything\n+#   -c  do not write anything, fail if any output differs from what the\n+#       generator produces now\n+#   -p  search the given directory instead of the kernel tree\n+\n+TOOL=$(dirname \"$(realpath \"$0\")\")/ctlvgen/cli.py\n+check=\n+search=\n+\n+while getopts ':fcp:' option; do\n+\tcase \"$option\" in\n+\tf)\n+\t\t;;\n+\tc)\n+\t\tcheck=yes\n+\t\t;;\n+\tp)\n+\t\tif [ -z \"$OPTARG\" ]; then\n+\t\t\techo \"Option -p needs a nonempty directory\" \u003e\u00262\n+\t\t\texit 1\n+\t\tfi\n+\t\tsearch=$OPTARG\n+\t\t;;\n+\t:)\n+\t\techo \"Option -$OPTARG needs an argument\" \u003e\u00262\n+\t\texit 1\n+\t\t;;\n+\t?)\n+\t\techo \"Unrecognized option '-$OPTARG'\" \u003e\u00262\n+\t\texit 1\n+\t\t;;\n+\tesac\n+done\n+shift $((OPTIND - 1))\n+if [ \"$#\" -ne 0 ]; then\n+\techo \"Unexpected argument '$1'\" \u003e\u00262\n+\texit 1\n+fi\n+\n+KDIR=$(realpath \"$(dirname \"$0\")/../..\")\n+args=(--spec \"$KDIR/Documentation/ctlv/specs/ctlv.yaml\")\n+if [ -n \"$search\" ]; then\n+\targs+=(--output-root \"$search\")\n+fi\n+if [ -n \"$check\" ]; then\n+\targs+=(--outputs-check)\n+else\n+\targs+=(--outputs-update)\n+fi\n+exec \"$TOOL\" \"${args[@]}\"\ndiff --git a/tools/ctlv/ctlvgen/__init__.py b/tools/ctlv/ctlvgen/__init__.py\nnew file mode 100644\nindex 0000000000000..f84069cb2c3d0\n--- /dev/null\n+++ b/tools/ctlv/ctlvgen/__init__.py\n@@ -0,0 +1 @@\n+# SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause\ndiff --git a/tools/ctlv/ctlvgen/cli.py b/tools/ctlv/ctlvgen/cli.py\nnew file mode 100755\nindex 0000000000000..c6bfafeb28525\n--- /dev/null\n+++ b/tools/ctlv/ctlvgen/cli.py\n@@ -0,0 +1,172 @@\n+#!/usr/bin/env python3\n+# SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause\n+\"\"\"Command line front end of the CTLV schema tool.\"\"\"\n+\n+import argparse\n+import pathlib\n+import sys\n+\n+# So that this file works both as a module of the ctlvgen package and as the\n+# script the Makefile and ctlv-regen.sh run. The imports below have to follow.\n+sys.path.append(pathlib.Path(__file__).resolve().parent.as_posix())\n+\n+from lib import cgen  # noqa: E402\n+from lib import compat  # noqa: E402\n+from lib import gen_kernel  # noqa: E402\n+from lib import gen_uapi  # noqa: E402\n+from lib import outputs  # noqa: E402\n+from lib import semantics  # noqa: E402\n+from lib import spec  # noqa: E402\n+from lib import tree  # noqa: E402\n+from lib.errors import CtlvError  # noqa: E402\n+\n+\n+# What each non-kernel --mode and file kind generates.\n+GENERATORS = {\n+    ('uapi', 'header'): gen_uapi.render,\n+}\n+\n+\n+def main():\n+    parser = argparse.ArgumentParser(description='CTLV schema tool')\n+    parser.add_argument('--spec', type=str, required=True,\n+                        help='path to a CTLV family specification')\n+    parser.add_argument('--schema', type=str,\n+                        help='path to the meta-schema, derived from --spec '\n+                             'when not given')\n+    parser.add_argument('--registry', type=str,\n+                        help='path to the family registry, derived from '\n+                             '--spec when not given')\n+    parser.add_argument('--abi', type=str,\n+                        help='directory of the ABI snapshots, derived from '\n+                             '--spec when not given')\n+    action = parser.add_mutually_exclusive_group(required=True)\n+    action.add_argument('--validate', action='store_true',\n+                        help='validate the specification and exit')\n+    action.add_argument('--abi-check', action='store_true',\n+                        help='check the specification against its ABI '\n+                             'snapshot')\n+    action.add_argument('--abi-update', action='store_true',\n+                        help='rewrite the ABI snapshot from the '\n+                             'specification')\n+    action.add_argument('--tree-check', action='store_true',\n+                        help='check registry, spec, snapshot and output '\n+                             'coverage')\n+    action.add_argument('--tree-check-update', action='store_true',\n+                        help='check whole-tree inputs before an ABI update')\n+    action.add_argument('--registry-abi-update', action='store_true',\n+                        help='update the ordered family registry baseline')\n+    action.add_argument('--outputs-check', action='store_true',\n+                        help='check every file in the output manifests')\n+    action.add_argument('--outputs-update', action='store_true',\n+                        help='regenerate every file in the output manifests')\n+    action.add_argument('--mode',\n+                        choices=('uapi', 'kernel'),\n+                        help='generate the files of this mode')\n+    parser.add_argument('--schema-only', action='store_true',\n+                        help='omit the family API from kernel output')\n+    kind = parser.add_mutually_exclusive_group()\n+    kind.add_argument('--header', action='store_true',\n+                      help='generate the header of --mode')\n+    kind.add_argument('--source', action='store_true',\n+                      help='generate the source of --mode')\n+    parser.add_argument('-o', '--output', type=str,\n+                        help='write to this file instead of standard output')\n+    parser.add_argument('--cmp-out', action='store_true',\n+                        help='leave the output file alone when its contents '\n+                             'would not change')\n+    parser.add_argument('--output-root', type=str,\n+                        help='alternate destination root for generated files')\n+    args = parser.parse_args()\n+\n+    kinds = (args.header, args.source)\n+    if args.mode and not any(kinds):\n+        parser.error('--mode needs --header or --source')\n+    if any(kinds) and not args.mode:\n+        parser.error('--header and --source need --mode')\n+    if args.schema_only and args.mode != 'kernel':\n+        parser.error('--schema-only needs --mode kernel')\n+    output_action = args.outputs_check or args.outputs_update\n+    if args.output is not None and not args.mode:\n+        parser.error('-o/--output needs --mode')\n+    if args.cmp_out and (not args.mode or args.output is None):\n+        parser.error('--cmp-out needs --mode and --output')\n+    if args.output_root is not None:\n+        if not output_action:\n+            parser.error('--output-root needs an outputs action')\n+        if not args.output_root:\n+            parser.error('--output-root cannot be empty')\n+\n+    paths = spec.Paths(args.spec, schema=args.schema, registry=args.registry,\n+                       abi=args.abi)\n+    try:\n+        if args.tree_check:\n+            tree.check(paths)\n+            return 0\n+        elif args.tree_check_update:\n+            tree.check_for_update(paths)\n+            return 0\n+        elif args.registry_abi_update:\n+            registry = tree.finish_update(paths)\n+            paths.registry_abi.write_text(\n+                compat.registry_render(registry), encoding='utf-8')\n+            print(f'ctlvgen: wrote {paths.registry_abi}', file=sys.stderr)\n+            return 0\n+        elif args.outputs_check:\n+            tree.check(paths)\n+            outputs.reconcile(paths, args.output_root, check=True)\n+            return 0\n+        elif args.outputs_update:\n+            tree.check_for_update(paths)\n+            changed = outputs.reconcile(paths, args.output_root)\n+            for item in changed:\n+                print(f'ctlvgen: {item}', file=sys.stderr)\n+            return 0\n+        family = semantics.load(paths)\n+        if args.validate:\n+            cgen.symbols(family)\n+        elif args.abi_check:\n+            compat.registry_check(paths, spec.load_registry(paths))\n+            compat.check(family, paths.abi(family.name))\n+        elif args.abi_update:\n+            _abi_update(paths, family)\n+        else:\n+            _generate(args, family)\n+    except CtlvError as exc:\n+        print(f'ctlvgen: {exc}', file=sys.stderr)\n+        return 1\n+    return 0\n+\n+\n+def _abi_update(paths, family):\n+    path = paths.abi(family.name)\n+    path.parent.mkdir(parents=True, exist_ok=True)\n+    path.write_text(compat.render(family), encoding='utf-8')\n+    print(f'ctlvgen: wrote {path}', file=sys.stderr)\n+\n+\n+def _generate(args, family):\n+    if args.header:\n+        kind = 'header'\n+    else:\n+        kind = 'source'\n+    if args.mode == 'kernel':\n+        renderer = (gen_kernel.render_header if args.header\n+                    else gen_kernel.render_source)\n+        text = renderer(family, family_api=not args.schema_only)\n+    else:\n+        text = GENERATORS[(args.mode, kind)](family)\n+    if args.output is None:\n+        sys.stdout.write(text)\n+        return\n+    path = pathlib.Path(args.output)\n+    # Leaving an unchanged file untouched keeps its timestamp, which is what\n+    # ctlv-regen.sh compares against the specification.\n+    if args.cmp_out and path.exists() and \\\n+            path.read_text(encoding='utf-8') == text:\n+        return\n+    path.write_text(text, encoding='utf-8')\n+\n+\n+if __name__ == '__main__':\n+    sys.exit(main())\ndiff --git a/tools/ctlv/ctlvgen/lib/__init__.py b/tools/ctlv/ctlvgen/lib/__init__.py\nnew file mode 100644\nindex 0000000000000..f84069cb2c3d0\n--- /dev/null\n+++ b/tools/ctlv/ctlvgen/lib/__init__.py\n@@ -0,0 +1 @@\n+# SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause\ndiff --git a/tools/ctlv/ctlvgen/lib/cgen.py b/tools/ctlv/ctlvgen/lib/cgen.py\nnew file mode 100644\nindex 0000000000000..2cb754b42106d\n--- /dev/null\n+++ b/tools/ctlv/ctlvgen/lib/cgen.py\n@@ -0,0 +1,825 @@\n+# SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause\n+\"\"\"C output scaffolding shared by the CTLV generators.\n+\n+The preamble ctlv-regen.sh recovers a file's specification and mode from, which\n+is why the specification stays directly above the marker.\n+\"\"\"\n+\n+from __future__ import annotations\n+\n+import os\n+\n+from . import semantics\n+from . import spec\n+from .errors import CtlvError\n+\n+REGEN = 'tools/ctlv/ctlv-regen.sh'\n+\n+LINE_LIMIT = 100\n+HARD_LINE_LIMIT = 100\n+TAB_WIDTH = 8\n+\n+# C spelling of each primary form. A test checks these against\n+# enum ctlv_schema_kind.\n+KINDS = {\n+    'uint': 'CTLV_SCHEMA_UINT',\n+    'sint': 'CTLV_SCHEMA_SINT',\n+    'bool': 'CTLV_SCHEMA_BOOL',\n+    'string': 'CTLV_SCHEMA_STRING',\n+    'binary': 'CTLV_SCHEMA_BINARY',\n+    'enum': 'CTLV_SCHEMA_ENUM',\n+    'flags': 'CTLV_SCHEMA_FLAGS',\n+    'nested': 'CTLV_SCHEMA_NEST',\n+    'blob': 'CTLV_SCHEMA_BLOB',\n+}\n+\n+LIFECYCLE_API_SYMBOLS = (\n+    'ctlv_create',\n+    'ctlv_destroy',\n+    'ctlv_family_priv_size_fn',\n+    'ctlv_family_pre_init_fn',\n+    'ctlv_family_init_fn',\n+    'ctlv_family_post_init_fn',\n+    'ctlv_family_pre_fini_fn',\n+    'ctlv_family_fini_fn',\n+    'ctlv_priv_parent',\n+    'ctlv_priv_child',\n+)\n+\n+\n+def width(line):\n+    \"\"\"Return the display width of one line, a tab being eight columns.\"\"\"\n+    return len(line.expandtabs(TAB_WIDTH))\n+\n+\n+def ident(*names):\n+    \"\"\"Return the lower case C spelling of one or more schema names.\"\"\"\n+    return '_'.join(name.replace('-', '_') for name in names)\n+\n+\n+def macro(*names):\n+    \"\"\"Return the upper case C spelling of one or more schema names.\"\"\"\n+    return ident(*names).upper()\n+\n+\n+def enum_tag(*names):\n+    return f'_{ident(*names)}'\n+\n+\n+def family_suffix(family_name):\n+    suffix = family_name\n+    if family_name.startswith('ctlv-'):\n+        suffix = family_name.removeprefix('ctlv-')\n+    return macro(suffix)\n+\n+\n+def family_const(family_name):\n+    if family_name == 'ctlv':\n+        return 'CTLV_FAMILY_ROOT'\n+    return f'CTLV_FAMILY_{family_suffix(family_name)}'\n+\n+\n+def uapi_header(family_name, in_kernel=False):\n+    \"\"\"Return the include of the generated UAPI header of family_name.\"\"\"\n+    prefix = 'uapi/' if in_kernel else ''\n+    return f'\u003c{prefix}linux/{ident(family_name)}_gen.h\u003e'\n+\n+\n+def families_uapi_header(in_kernel=False):\n+    prefix = 'uapi/' if in_kernel else ''\n+    return f'\u003c{prefix}linux/ctlv_families_gen.h\u003e'\n+\n+\n+def kernel_header(family_name):\n+    \"\"\"Return the include of the generated kernel header of family_name.\n+\n+    The root family's interface is installed beside \u003clinux/ctlv.h\u003e; any other\n+    family's is private to the family implementation compiling it.\n+    \"\"\"\n+    name = f'{ident(family_name)}_gen.h'\n+    if family_name == spec.CORE_FAMILY_NAME:\n+        return f'\u003clinux/{name}\u003e'\n+    return f'\"{name}\"'\n+\n+\n+def spec_path(path):\n+    \"\"\"Return path relative to the kernel tree that holds it.\n+\n+    ctlv-regen.sh resolves it from the tree root, so it must not depend on how\n+    the generator was invoked. Outside a kernel tree it is recorded as given.\n+    \"\"\"\n+    full = os.path.abspath(path)\n+    relative = ''\n+    while True:\n+        relative = os.path.join(os.path.basename(full), relative)\n+        parent = os.path.dirname(full)\n+        if os.path.exists(os.path.join(parent, 'MAINTAINERS')):\n+            return relative[:-1]\n+        if parent == full:\n+            return str(path)\n+        full = parent\n+\n+\n+def wrapped(opening, items, closing, trailer='', adaptive=False):\n+    \"\"\"Return the lines of one parenthesized list, wrapped at the limit.\n+\n+    trailer is what a continued line ends with beyond the item: a backslash\n+    inside a macro definition, nothing elsewhere.\n+    \"\"\"\n+    parts = [f'{item}, ' for item in items[:-1]] + [items[-1] + closing]\n+    column = width(opening)\n+    part_width = max(width(part.rstrip() + trailer) for part in parts)\n+    indent_column = column\n+    if adaptive:\n+        indent_column = min(column, max(0, LINE_LIMIT - part_width))\n+    indent = '\\t' * (indent_column // TAB_WIDTH) + \\\n+        ' ' * (indent_column % TAB_WIDTH)\n+    lines = []\n+    line = opening\n+    for part in parts:\n+        if width(line + part.rstrip() + trailer) \u003e LINE_LIMIT:\n+            if line != opening:\n+                lines.append(line.rstrip())\n+            elif adaptive and opening.rstrip():\n+                lines.append(opening.rstrip())\n+            else:\n+                line += part\n+                continue\n+            line = indent\n+        line += part\n+    lines.append(line.rstrip())\n+    return lines\n+\n+\n+class Writer:\n+    \"\"\"The lines of one generated file.\"\"\"\n+\n+    def __init__(self):\n+        self._lines = []\n+\n+    def line(self, text=''):\n+        self._lines.append(text)\n+\n+    def comment(self, *lines):\n+        \"\"\"One comment block, one input line per output line.\"\"\"\n+        if len(lines) == 1:\n+            self.line(f'/* {lines[0]} */')\n+            return\n+        self.line('/*')\n+        for text in lines:\n+            self.line(f' * {text}'.rstrip())\n+        self.line(' */')\n+\n+    def define_block(self, name, *lines):\n+        \"\"\"One #define whose value takes more than the one line.\"\"\"\n+        header = f'#define {name} \\\\'\n+        if width(header) \u003e LINE_LIMIT and '(' in name:\n+            macro, params = name.removesuffix(')').split('(', 1)\n+            for text in wrapped(f'#define {macro}(',\n+                                tuple(params.split(', ')), ')', ' \\\\',\n+                                adaptive=True):\n+                self.line(f'{text} \\\\')\n+        else:\n+            self.line(header)\n+        for text in lines[:-1]:\n+            self.line(f'{text} \\\\')\n+        self.line(lines[-1])\n+\n+    def define(self, name, value):\n+        \"\"\"One #define, continued when it would run past the line limit.\"\"\"\n+        text = f'#define {name} {value}'\n+        if width(text) \u003c= LINE_LIMIT:\n+            self.line(text)\n+            return\n+        self.define_block(name, f'\\t{value}')\n+\n+    def define_call(self, name, function, *args):\n+        \"\"\"One #define whose value is a call, wrapped where it has to be.\"\"\"\n+        call = f'{function}({\", \".join(args)})'\n+        if width(f'#define {name} {call}') \u003c= LINE_LIMIT:\n+            self.line(f'#define {name} {call}')\n+            return\n+        if width(f'\\t{call}') \u003c= LINE_LIMIT:\n+            self.define_block(name, f'\\t{call}')\n+            return\n+        self.define_block(\n+            name, *wrapped(f'\\t{function}(', args, ')', ' \\\\',\n+                           adaptive=True))\n+\n+    def declaration(self, prefix, declarator):\n+        \"\"\"One declaration, continued when it would run past the limit.\"\"\"\n+        text = f'{prefix} {declarator}'\n+        if width(text) \u003c= LINE_LIMIT:\n+            self.line(text)\n+            return\n+        indent = prefix[:len(prefix) - len(prefix.lstrip('\\t'))]\n+        self.line(prefix)\n+        continuation = f'{indent}\\t'\n+        if width(f'{continuation}{declarator}') \u003e LINE_LIMIT:\n+            continuation = '\\t'\n+        self.line(f'{continuation}{declarator}')\n+\n+    def parenthesized(self, opening, items, closing):\n+        \"\"\"One parenthesized list, wrapped at the line limit.\"\"\"\n+        for text in wrapped(opening, items, closing, adaptive=True):\n+            self.line(text)\n+\n+    def assertion(self, left, operator, right):\n+        \"\"\"One static_assert, broken after its operator when it must be.\"\"\"\n+        opening = 'static_assert('\n+        text = f'{opening}{left} {operator} {right});'\n+        if width(text) \u003c= LINE_LIMIT:\n+            self.line(text)\n+            return\n+        column = width(opening)\n+        indent = '\\t' * (column // TAB_WIDTH) + ' ' * (column % TAB_WIDTH)\n+        self.line(f'{opening}{left} {operator}')\n+        self.line(f'{indent}{right});')\n+\n+    def signature(self, prefix, name, params, closing=');'):\n+        \"\"\"One function signature, wrapped at the line limit.\"\"\"\n+        lines = wrapped(f'{prefix} {name}(', params, closing)\n+        one_line = f'{prefix} {name}({\", \".join(params)}{closing}'\n+        if lines[0].endswith('(') and width(one_line) \u003c= HARD_LINE_LIMIT:\n+            self.line(one_line)\n+            return\n+        if max(width(line) for line in lines) \u003c= LINE_LIMIT:\n+            for text in lines:\n+                self.line(text)\n+            return\n+        if name.startswith('*'):\n+            self.line(f'{prefix} *')\n+            name = name.removeprefix('*')\n+        else:\n+            self.line(prefix)\n+        declarator = f'{name}({\", \".join(params)}{closing}'\n+        if width(declarator) \u003c= HARD_LINE_LIMIT:\n+            self.line(declarator)\n+            return\n+        opening = f'{name}('\n+        lines = wrapped(opening, params, closing)\n+        if max(width(line) for line in lines) \u003e LINE_LIMIT:\n+            self.line(opening)\n+            self.parenthesized('\\t', params, closing)\n+        else:\n+            for text in lines:\n+                self.line(text)\n+\n+    def open_guard(self, guard):\n+        self.line(f'#ifndef {guard}')\n+        self.line(f'#define {guard}')\n+        self.line()\n+\n+    def close_guard(self, guard):\n+        self.line(f'#endif /* {guard} */')\n+\n+    def includes(self, *headers):\n+        \"\"\"One include block, an empty entry separating two groups.\"\"\"\n+        for header in headers:\n+            self.line(f'#include {header}' if header else '')\n+        self.line()\n+\n+    def text(self):\n+        while self._lines and not self._lines[-1]:\n+            self._lines.pop()\n+        return '\\n'.join(self._lines) + '\\n'\n+\n+\n+def preamble(origin, mode, kind, source=None):\n+    \"\"\"Return a Writer holding the preamble of one generated file.\"\"\"\n+    writer = Writer()\n+    if kind == 'source':\n+        writer.line(f'// SPDX-License-Identifier: {origin.license}')\n+    else:\n+        writer.line(f'/* SPDX-License-Identifier: {origin.license} */')\n+    writer.line(f'/* Do not edit, regenerate with {REGEN}, from: */')\n+    writer.line(f'/*\\t{spec_path(source or origin.path)} */')\n+    writer.line(f'/* CTLV-GEN {mode} {kind} */')\n+    writer.line()\n+    return writer\n+\n+\n+class Names:\n+    \"\"\"The C names of one effective family's declarations.\n+\n+    A declaration is named after the family that owns it, so an inherited attr\n+    keeps the name its own family's header gives it.\n+    \"\"\"\n+\n+    def __init__(self, family):\n+        self.family = family\n+        self.prefix = macro(family.name)\n+        self.ident = ident(family.name)\n+\n+    def owner_prefix(self, family_id):\n+        return macro(self.family.owners[family_id])\n+\n+    def owner_ident(self, family_id):\n+        return ident(self.family.owners[family_id])\n+\n+    # Names that a family's UAPI header defines.\n+\n+    def family_const(self):\n+        return family_const(self.family.name)\n+\n+    def group(self, group):\n+        return f'{self.owner_prefix(group.family_id)}_GROUP_' \\\n+               f'{macro(group.name)}'\n+\n+    def group_enum(self, group):\n+        return enum_tag(self.family.owners[group.family_id], 'group')\n+\n+    def group_attr_enum(self, group):\n+        return enum_tag(self.family.owners[group.family_id],\n+                        'attr', group.name)\n+\n+    def group_metadata_enum(self, group):\n+        return enum_tag(self.family.owners[group.family_id],\n+                        'attr', group.name, 'metadata')\n+\n+    def group_attr(self, group):\n+        return f'_{self.owner_prefix(group.family_id)}_ATTR_' \\\n+               f'{macro(group.name)}'\n+\n+    def family_attr(self, group):\n+        return f'_{self.owner_prefix(group.family_id)}_ATTR'\n+\n+    def local_attr_prefix(self, group):\n+        return f'_{self.owner_prefix(group.family_id)}_ATTR_' \\\n+               f'{macro(group.name)}_'\n+\n+    def local_attr(self, attr):\n+        group = self.family.groups[attr.group]\n+        return f'{self.local_attr_prefix(group)}{macro(attr.name)}'\n+\n+    def attr(self, attr):\n+        return f'{self.owner_prefix(attr.family_id)}_ATTR_' \\\n+               f'{macro(attr.group, attr.name)}'\n+\n+    def attr_unit(self, attr):\n+        return f'{self.attr(attr)}_UNIT'\n+\n+    def attr_scale(self, attr):\n+        return f'{self.attr(attr)}_SCALE'\n+\n+    def attr_set(self, attr_set):\n+        return f'{self.owner_prefix(attr_set.family_id)}_SET_' \\\n+               f'{macro(attr_set.name)}'\n+\n+    def set_enum(self, attr_set):\n+        return enum_tag(self.family.owners[attr_set.family_id], 'set')\n+\n+    def op_prefix(self, op):\n+        return f'_{self.owner_prefix(op.family_id)}_OP_'\n+\n+    def op(self, op):\n+        return f'{self.op_prefix(op)}{macro(op.name)}'\n+\n+    def operation(self, op):\n+        return f'_{self.owner_prefix(op.family_id)}_OP'\n+\n+    def op_enum(self, op):\n+        return enum_tag(self.family.owners[op.family_id], 'op')\n+\n+    def op_id(self, op):\n+        return f'{self.owner_prefix(op.family_id)}_OP_{macro(op.name)}'\n+\n+    def definition(self, definition):\n+        \"\"\"The C type name of an enum definition.\"\"\"\n+        return enum_tag(self.family.owners[definition.family_id],\n+                        definition.name)\n+\n+    def value(self, definition, value_name):\n+        \"\"\"One enum value or flag bit.\"\"\"\n+        return f'{self.owner_prefix(definition.family_id)}_' \\\n+               f'{macro(definition.name, value_name)}'\n+\n+    def value_bit(self, definition, value_name):\n+        return f'{self.value(definition, value_name)}_BIT'\n+\n+    def bit_enum(self, definition):\n+        return enum_tag(self.family.owners[definition.family_id],\n+                        definition.name, 'bit')\n+\n+    def value_mask(self, definition):\n+        \"\"\"The mask of every bit a flags definition declares.\"\"\"\n+        return f'{self.owner_prefix(definition.family_id)}_' \\\n+               f'{macro(definition.name)}_MASK'\n+\n+    # Names that a family's kernel metadata defines: its own ops and the\n+    # stubs it fills.\n+\n+    def op_schemas(self):\n+        return f'{self.ident}_op_schemas'\n+\n+    def schema(self):\n+        return f'{self.ident}_schema'\n+\n+    def stub_fill_schemas(self):\n+        return f'{self.ident}_stub_fill_schemas'\n+\n+    def node_schemas(self, op, which):\n+        # File scope, so no family prefix: an op name is unique within its\n+        # effective family.\n+        return f'{ident(op.name)}_{which}_node_schemas'\n+\n+    def stub_schemas(self, op, which):\n+        return f'{ident(op.name)}_{which}_stub_schemas'\n+\n+    def fill_node_schemas(self, fill):\n+        return f'{ident(fill.name)}_fill_node_schemas'\n+\n+    def message_node_schemas(self, message):\n+        return f'{ident(message.name)}_node_schemas'\n+\n+    def message_schema(self, message):\n+        \"\"\"The tree the core builds one of its own messages against.\"\"\"\n+        return f'{self.ident}_{ident(message.name)}_schema'\n+\n+    def message_max_len(self, message):\n+        return f'{self.prefix}_{macro(message.name)}_MAX_LEN'\n+\n+    # Names that a family's device descriptor defines. Named after the family\n+    # that declared what they answer: an inherited op is answered by that\n+    # family implementation, on whatever device it arrived at.\n+\n+    def descriptor(self):\n+        return f'{self.ident}_family'\n+\n+    def ops(self):\n+        return f'{self.ident}_ops'\n+\n+    def stub_ops(self):\n+        return f'{self.ident}_stub_ops'\n+\n+    def stub_ident(self, fill):\n+        return f'{self.ident}_{ident(fill.name)}'\n+\n+    def stub_callback(self, fill, which):\n+        \"\"\"One half of what this family does with an extension point.\"\"\"\n+        return f'{self.stub_ident(fill)}_{which}'\n+\n+    def lifecycle_hook(self, which):\n+        \"\"\"One operation in the lifecycle of this family's priv.\"\"\"\n+        return f'{self.ident}_{which}'\n+\n+    def op_ident(self, op):\n+        return f'{self.owner_ident(op.family_id)}_{ident(op.name)}'\n+\n+    def callback(self, op):\n+        return f'{self.op_ident(op)}_{op.type}'\n+\n+    def op_helper(self, op, what):\n+        \"\"\"What one device decides about one op.\"\"\"\n+        return f'{self.op_ident(op)}_{what}'\n+\n+    def attr_helper(self, attr, what):\n+        \"\"\"One helper for one attr: reading it, or appending it.\n+\n+        Named after the family that declares the attr, like the constant that\n+        names it on the wire.\n+        \"\"\"\n+        return f'{self.owner_ident(attr.family_id)}_' \\\n+               f'{ident(attr.group, attr.name)}_{what}'\n+\n+    def attr_iterator(self, attr):\n+        \"\"\"What walks every occurrence of one repeated attr.\"\"\"\n+        return f'{self.owner_ident(attr.family_id)}_{ident(attr.group)}_' \\\n+               f'for_each_{ident(attr.name)}'\n+\n+    def input_name(self, scope, attr):\n+        \"\"\"The stem of one request-placement-specific reader.\"\"\"\n+        owner_parts = self.family.name.split('-')\n+        group = ()\n+        if attr.group not in (*scope.name, *owner_parts):\n+            group = (attr.group,)\n+        parts = (*scope.name, *group, attr.name)\n+        parts = tuple(part for index, part in enumerate(parts)\n+                      if not index or part != parts[index - 1])\n+        return f'{self.ident}_{ident(*parts)}'\n+\n+    def input_helper(self, scope, attr, what):\n+        return f'{self.input_name(scope, attr)}_{what}'\n+\n+    def input_iterator(self, scope, attr):\n+        return self.input_helper(scope, attr, 'for_each')\n+\n+    def input_ref(self, scope, attr):\n+        return self.input_helper(scope, attr, 'ref')\n+\n+    def family_hook(self, which):\n+        \"\"\"One half of the pair that wraps every op of this family.\"\"\"\n+        return f'{self.ident}_op_{which}'\n+\n+    def op_hook(self, op, which):\n+        \"\"\"One half of the pair that wraps this op alone.\"\"\"\n+        return f'{self.op_ident(op)}_{which}'\n+\n+    # Where a generated file lives: the installed constants, the schema\n+    # metadata a family compiles, and the descriptor it registers.\n+\n+    def uapi_guard(self):\n+        return f'_UAPI_LINUX_{self.prefix}_GEN_H'\n+\n+    def uapi_header(self, in_kernel=False):\n+        return uapi_header(self.family.name, in_kernel)\n+\n+    def kernel_guard(self):\n+        return f'_LINUX_{self.prefix}_GEN_H'\n+\n+    def kernel_header(self):\n+        return kernel_header(self.family.name)\n+\n+    def user_guard(self):\n+        return f'_CTLV_{self.prefix}_USER_GEN_H'\n+\n+    def user_header(self):\n+        return f'\"{self.ident}_user_gen.h\"'\n+\n+    # Names that a family's userspace binding defines, after the family that\n+    # declared the op, as a per-op helper is in the kernel.\n+\n+    def user_op(self, op):\n+        return f'{self.owner_ident(op.family_id)}_{ident(op.name)}'\n+\n+    def user_op_helper(self, op, what):\n+        return f'{self.user_op(op)}_{what}'\n+\n+    def user_op_len(self, op, what):\n+        \"\"\"One length of one op, as its specification computed it.\"\"\"\n+        return f'{self.op_id(op)}_{macro(what)}'\n+\n+    def user_node_schema(self, op, which):\n+        # File scope, so no family prefix, as on the kernel side.\n+        return f'{ident(op.name)}_{which}_node_schema'\n+\n+    def user_spec(self):\n+        \"\"\"What this family's specification says, to compare a device to.\"\"\"\n+        return f'{self.ident}_spec'\n+\n+    def user_op_specs(self):\n+        return f'{self.ident}_op_specs'\n+\n+\n+def attr_getter_value(attr):\n+    \"\"\"Whether an attr has a getter beside the reader that locates it.\"\"\"\n+    return attr.decl.kind != 'blob' and \\\n+        not (attr.decl.kind == 'nested' and attr.decl.max_occurrences != 1)\n+\n+\n+def input_readers(names, scope, attr):\n+    readers = [names.input_ref(scope, attr)]\n+    readers.append(names.input_iterator(scope, attr)\n+                   if attr.decl.max_occurrences != 1\n+                   else names.input_helper(scope, attr, 'present'))\n+    if attr.decl.kind == 'blob':\n+        readers.append(names.input_helper(scope, attr, 'resolve'))\n+    elif attr_getter_value(attr):\n+        readers.append(names.input_helper(scope, attr, 'get'))\n+    return tuple(readers)\n+\n+\n+def attr_writers(names, attr):\n+    \"\"\"The names of what appends one attr, as the family API declares them.\n+\n+    A blob has none: a request carries one and a reply never does.\n+    \"\"\"\n+    if attr.decl.kind == 'blob':\n+        return ()\n+    what = 'start' if attr.decl.kind == 'nested' else 'put'\n+    return (names.attr_helper(attr, what),)\n+\n+\n+# What a blob attr may be backed by, and the libctlv call describing one. A\n+# putter exists per backing the placement permits, so what a caller may\n+# describe is decided by the specification.\n+BLOB_PUTTERS = {\n+    'va': ('va', ('const void *address', '__u64 length')),\n+}\n+\n+# What an event gets in the place of a wrapper.\n+EVENT_HELPERS = ('is', 'subscribe', 'unsubscribe')\n+\n+# The lengths a user-mode header states for one op, by sizes.OpSizes member.\n+USER_LENGTHS = {\n+    'request_max_len': 'request-max-len',\n+    'action_reply_max_len': 'action-reply-max-len',\n+    'query_reply_min_len': 'query-reply-min-len',\n+    'query_reply_suggested_len': 'query-reply-suggested-len',\n+    'event_record_max_len': 'event-record-max-len',\n+}\n+\n+\n+def user_attr_readers(names, attr):\n+    \"\"\"The names of what reads one attr in the userspace binding.\"\"\"\n+    if attr.decl.kind == 'blob':\n+        return ()\n+    readers = [names.attr_iterator(attr) if attr.decl.max_occurrences != 1\n+               else names.attr_helper(attr, 'present')]\n+    if attr_getter_value(attr):\n+        readers.append(names.attr_helper(attr, 'get'))\n+    return tuple(readers)\n+\n+\n+def user_attr_writers(names, attr):\n+    \"\"\"The names of what appends one attr in the userspace binding.\n+\n+    A blob has one putter per backing the placement allows, where the kernel\n+    side has none.\n+    \"\"\"\n+    if attr.decl.kind == 'blob':\n+        return tuple(names.attr_helper(attr, f'put_{BLOB_PUTTERS[backing][0]}')\n+                     for backing in attr.decl.blob.backings)\n+    what = 'start' if attr.decl.kind == 'nested' else 'put'\n+    return (names.attr_helper(attr, what),)\n+\n+\n+def user_symbols(family):\n+    \"\"\"Return every C name of family's binding, mapped to its origin.\n+\n+    The binding covers this family's own attrs and ops, reaching the rest\n+    through the parent's header.\n+    \"\"\"\n+    names = Names(family)\n+    table = {}\n+\n+    def add(name, origin):\n+        previous = table.get(name)\n+        if previous is not None:\n+            raise CtlvError(f'{family.path}: {origin}',\n+                            f'generated name {name} is already used by '\n+                            f'{previous}')\n+        table[name] = origin\n+\n+    for group in family.local_groups:\n+        for attr in group.attrs:\n+            what = f'attr {attr.full_name}'\n+            for helper in user_attr_readers(names, attr) + \\\n+                    user_attr_writers(names, attr):\n+                add(helper, what)\n+    for op in family.local_ops:\n+        what = f'op {op.name}'\n+        # An event has those helpers and no wrapper of its own name.\n+        if op.type == 'event':\n+            for helper in EVENT_HELPERS:\n+                add(names.user_op_helper(op, helper), what)\n+        else:\n+            add(names.user_op(op), what)\n+            if op.request is not None:\n+                add(names.user_op_helper(op, 'request_new'), what)\n+        for field, what_len in USER_LENGTHS.items():\n+            if getattr(op.sizes, field):\n+                add(names.user_op_len(op, what_len), what)\n+    return table\n+\n+\n+def _stubs_anywhere(node):\n+    return bool(node.stubs) or any(_stubs_anywhere(child)\n+                                   for child in node.children())\n+\n+\n+def symbols(family):\n+    \"\"\"Return every generated C name of family, mapped to its declaration.\n+\n+    Dashes become underscores, so two YAML names can spell one C name. That\n+    has to be an error: one of the two constants would silently not exist.\n+    \"\"\"\n+    names = Names(family)\n+    table = {}\n+\n+    def add(name, origin):\n+        previous = table.get(name)\n+        if previous is not None:\n+            raise CtlvError(f'{family.path}: {origin}',\n+                            f'generated name {name} is already used by '\n+                            f'{previous}')\n+        table[name] = origin\n+\n+    for name in LIFECYCLE_API_SYMBOLS:\n+        add(name, 'the CTLV lifecycle API')\n+    add(names.family_const(), f'family {family.name}')\n+    # A child header may include every ancestor's family API, and built-in\n+    # families also share one linker namespace with the root.\n+    for family_id, owner in family.owners.items():\n+        owner_ident = ident(owner)\n+        if any(op.family_id == family_id for op in family.ops):\n+            add(f'{owner_ident}_op_schemas', f'family {owner}')\n+        add(f'{owner_ident}_schema', f'family {owner}')\n+        add(f'{owner_ident}_family', f'family {owner}')\n+        for which in ('pre', 'post'):\n+            add(f'{owner_ident}_op_{which}', f'family {owner}')\n+        for which in ('priv_size', 'pre_init', 'init', 'post_init',\n+                      'pre_fini', 'fini'):\n+            add(f'{owner_ident}_device_{which}', f'family {owner}')\n+    for fill in family.fills:\n+        for which in ('fill', 'read'):\n+            add(names.stub_callback(fill, which), f'attr set {fill.name}')\n+    for definition in family.definitions.values():\n+        what = f'{definition.kind} {definition.name}'\n+        if definition.kind == 'enum':\n+            add(f'enum {names.definition(definition)}', what)\n+        else:\n+            add(f'enum {names.bit_enum(definition)}', what)\n+            add(names.value_mask(definition), what)\n+        for value_name, _ in definition.values:\n+            if definition.kind == 'flags':\n+                add(names.value_bit(definition, value_name), what)\n+            add(names.value(definition, value_name), what)\n+    group_enums = set()\n+    family_attrs = set()\n+    for group in family.groups.values():\n+        group_enum = f'enum {names.group_enum(group)}'\n+        if group_enum not in group_enums:\n+            add(group_enum, f'family {family.owners[group.family_id]} groups')\n+            group_enums.add(group_enum)\n+        family_attr = names.family_attr(group)\n+        if family_attr not in family_attrs:\n+            add(family_attr, f'family {family.owners[group.family_id]} attrs')\n+            family_attrs.add(family_attr)\n+        add(names.group(group), f'attr group {group.name}')\n+        add(f'enum {names.group_attr_enum(group)}',\n+            f'attr group {group.name}')\n+        if any(attr.decl.unit is not None for attr in group.attrs):\n+            add(f'enum {names.group_metadata_enum(group)}',\n+                f'attr group {group.name} metadata')\n+        add(names.group_attr(group), f'attr group {group.name}')\n+        for attr in group.attrs:\n+            what = f'attr {attr.full_name}'\n+            add(names.local_attr(attr), what)\n+            add(names.attr(attr), what)\n+            if attr.decl.unit is not None:\n+                add(names.attr_unit(attr), what)\n+                add(names.attr_scale(attr), what)\n+            for helper in attr_writers(names, attr):\n+                add(helper, what)\n+    for ancestor in family.chain[:-1]:\n+        ancestor_names = Names(ancestor)\n+        owner_family_id = next(\n+            family_id for family_id, owner in family.owners.items()\n+            if owner == ancestor.name)\n+\n+        for scope in semantics.input_scopes(family, owner_family_id):\n+            for child in scope.node.children():\n+                what = f'attr {child.attr.full_name} in ancestor ' \\\n+                       f'{ancestor.name}'\n+                for helper in input_readers(ancestor_names, scope,\n+                                            child.attr):\n+                    add(helper, what)\n+    for scope in semantics.input_scopes(family):\n+        for child in scope.node.children():\n+            what = f'attr {child.attr.full_name} in {\".\".join(scope.name)}'\n+            for helper in input_readers(names, scope, child.attr):\n+                add(helper, what)\n+    set_enums = set()\n+    for attr_set in family.sets.values():\n+        set_enum = f'enum {names.set_enum(attr_set)}'\n+        if set_enum not in set_enums:\n+            add(set_enum, f'family {family.owners[attr_set.family_id]} sets')\n+            set_enums.add(set_enum)\n+        add(names.attr_set(attr_set), f'attr set {attr_set.name}')\n+    operation_enums = set()\n+    for op in family.ops:\n+        what = f'op {op.name}'\n+        operation_enum = f'enum {names.op_enum(op)}'\n+        if operation_enum not in operation_enums:\n+            add(operation_enum,\n+                f'family {family.owners[op.family_id]} operations')\n+            add(names.operation(op),\n+                f'family {family.owners[op.family_id]} operations')\n+            operation_enums.add(operation_enum)\n+        add(names.op(op), what)\n+        add(names.op_id(op), what)\n+        if op.type == 'event':\n+            add(names.op_helper(op, 'create'), what)\n+            continue\n+        add(names.callback(op), what)\n+        if op.optional:\n+            add(names.op_helper(op, 'provide'), what)\n+        if op.availability == 'dynamic':\n+            add(names.op_helper(op, 'enable'), what)\n+            add(names.op_helper(op, 'disable'), what)\n+        if op.pre_post:\n+            add(names.op_hook(op, 'pre'), what)\n+            add(names.op_hook(op, 'post'), what)\n+    for message in family.messages:\n+        what = f'attr set {message.name}'\n+        add(names.message_node_schemas(message), what)\n+        add(names.message_schema(message), what)\n+        add(names.message_max_len(message), what)\n+    if family.fills:\n+        add(names.stub_fill_schemas(), f'family {family.name}')\n+        add(names.stub_ops(), f'family {family.name}')\n+    if any(op.type != 'event' for op in family.local_ops):\n+        add(names.ops(), f'family {family.name}')\n+    for op in family.local_ops:\n+        what = f'op {op.name}'\n+        for which in ('request', 'reply'):\n+            root = getattr(op, which)\n+            if root is None:\n+                continue\n+            add(names.node_schemas(op, which), what)\n+            if _stubs_anywhere(root):\n+                add(names.stub_schemas(op, which), what)\n+    for fill in family.fills:\n+        add(names.fill_node_schemas(fill), f'attr set {fill.name}')\n+    return table\ndiff --git a/tools/ctlv/ctlvgen/lib/compat.py b/tools/ctlv/ctlvgen/lib/compat.py\nnew file mode 100644\nindex 0000000000000..4cf93af06ea90\n--- /dev/null\n+++ b/tools/ctlv/ctlvgen/lib/compat.py\n@@ -0,0 +1,821 @@\n+# SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause\n+\"\"\"ABI snapshots and the compatibility checker.\n+\n+A change is compatible only if the new schema still contains everything the\n+checked-in snapshot describes, with the same IDs, no narrowed bound and no\n+placement that became required. A new placement has to be optional. Updating a\n+snapshot is deliberate: it is how the change gets reviewed.\n+\"\"\"\n+\n+from __future__ import annotations\n+\n+import yaml\n+\n+from . import spec\n+from . import yamlload\n+from .errors import CtlvError\n+\n+HEADER = '''\\\n+# SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)\n+%YAML 1.2\n+---\n+# Checked-in ABI snapshot of the {name} family, written by\n+# \"make -C tools/ctlv abi-update\".\n+#\n+# The checker compares this family's declarations and inherited stub fills\n+# against this file. Updating it is how a UAPI change gets reviewed; an update\n+# that removes or renumbers anything, narrows a bound, or makes a placement\n+# required is an ABI break, whatever this file says afterwards.\n+'''\n+\n+REGISTRY_HEADER = '''\\\n+# SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)\n+%YAML 1.2\n+---\n+# Checked-in ABI baseline of the ordered CTLV family registry.\n+# Updated deliberately by \"make -C tools/ctlv abi-update\".\n+'''\n+\n+\n+class _Dumper(yaml.SafeDumper):\n+    \"\"\"Dumper that never emits anchors, which the strict loader rejects.\"\"\"\n+\n+    def ignore_aliases(self, data):\n+        return True\n+\n+    def increase_indent(self, flow=False, indentless=False):\n+        # Indent a sequence under its key, not flush left as pyyaml does.\n+        return super().increase_indent(flow, False)\n+\n+\n+class _FlowMap(dict):\n+    pass\n+\n+\n+class _FlowSeq(list):\n+    pass\n+\n+\n+_Dumper.add_representer(\n+    _FlowMap,\n+    lambda dumper, value: dumper.represent_mapping(\n+        'tag:yaml.org,2002:map', value, flow_style=True))\n+_Dumper.add_representer(\n+    _FlowSeq,\n+    lambda dumper, value: dumper.represent_sequence(\n+        'tag:yaml.org,2002:seq', value, flow_style=True))\n+\n+\n+def build(family):\n+    \"\"\"Return one family's ABI in the comparison form.\"\"\"\n+    return {\n+        'family': family.name,\n+        'family-id': family.family_id,\n+        'parent': family.parent,\n+        'pre-init': family.pre_init,\n+        'post-init': family.post_init,\n+        'pre-fini': family.pre_fini,\n+        'definitions': _definitions(family.local_definitions),\n+        'groups': _groups(family.local_groups),\n+        'sets': _sets(family.local_sets),\n+        'fills': _fills(family.fills),\n+        'ops': _ops(family.local_ops),\n+    }\n+\n+\n+def render(family):\n+    \"\"\"Return one family's compact snapshot as YAML text.\"\"\"\n+    return render_data(build(family))\n+\n+\n+def render_data(data):\n+    \"\"\"Render comparison-form data as a compact snapshot.\"\"\"\n+    body = yaml.dump(_compact(data), Dumper=_Dumper, sort_keys=False,\n+                     default_flow_style=False, width=1000000)\n+    body = '\\n'.join(line for source in body.splitlines()\n+                     for line in _wrap_flow(source)) + '\\n'\n+    return HEADER.format(name=data['family']) + body\n+\n+\n+def _wrap_flow(line, width=80):\n+    \"\"\"Wrap one flow collection with continuations aligned after its opener.\"\"\"\n+    if len(line) \u003c= width:\n+        return (line,)\n+    starts = [index for index in (line.find('{'), line.find('['))\n+              if index \u003e= 0]\n+    if not starts:\n+        return (line,)\n+    start = min(starts)\n+    end, items = _flow_items(line, start)\n+    if end is None:\n+        return (line,)\n+\n+    prefix = line[:start + 1]\n+    suffix = line[end:]\n+    indent = ' ' * (start + 1)\n+    wrapped = []\n+    current = prefix\n+    for index, item in enumerate(items):\n+        last = index + 1 == len(items)\n+        token = item + ('' if last else ',')\n+        separator = '' if current.endswith(('{', '[')) else ' '\n+        closing = len(suffix) if last else 0\n+        if len(current) + len(separator) + len(token) + closing \u003e width:\n+            wrapped.append(current)\n+            current = indent + token\n+        else:\n+            current += separator + token\n+    current += suffix\n+    wrapped.append(current)\n+    return tuple(wrapped)\n+\n+\n+def _flow_items(line, start):\n+    pairs = {'{': '}', '[': ']'}\n+    stack = [line[start]]\n+    quote = None\n+    escape = False\n+    item_start = start + 1\n+    items = []\n+    for index in range(start + 1, len(line)):\n+        char = line[index]\n+        if quote is not None:\n+            if escape:\n+                escape = False\n+            elif char == '\\\\':\n+                escape = True\n+            elif char == quote:\n+                quote = None\n+            continue\n+        if char in ('\"', \"'\"):\n+            quote = char\n+        elif char in pairs:\n+            stack.append(char)\n+        elif char in pairs.values():\n+            if pairs[stack[-1]] != char:\n+                return None, ()\n+            stack.pop()\n+            if not stack:\n+                items.append(line[item_start:index].strip())\n+                return index, tuple(item for item in items if item)\n+        elif char == ',' and len(stack) == 1:\n+            items.append(line[item_start:index].strip())\n+            item_start = index + 1\n+    return None, ()\n+\n+\n+def check(family, path):\n+    \"\"\"Compare a family against its snapshot, or raise with every problem.\"\"\"\n+    snapshot = _expand(yamlload.load(path))\n+    problems = _compare(snapshot, build(family))\n+    if problems:\n+        raise CtlvError(f'{family.name} against {path}',\n+                        'the schema is not compatible with its snapshot\\n' +\n+                        '\\n'.join(f'  {problem}' for problem in problems))\n+\n+\n+def _compact(data):\n+    family = _FlowMap({\n+        'name': data['family'],\n+        'id': data['family-id'],\n+    })\n+    if data['parent'] is not None:\n+        family['inherits'] = data['parent']\n+    for name in ('pre-init', 'post-init', 'pre-fini'):\n+        if data[name]:\n+            family[name] = True\n+\n+    compact = {'family': family}\n+    for kind, section in (('enum', 'enums'), ('flags', 'flags')):\n+        definitions = {\n+            name: _FlowMap(entry['values'])\n+            for name, entry in data['definitions'].items()\n+            if entry['kind'] == kind\n+        }\n+        if definitions:\n+            compact[section] = definitions\n+    if data['groups']:\n+        compact['attr-groups'] = _compact_groups(data['groups'])\n+    if data['sets']:\n+        compact['attr-sets'] = {\n+            name: _FlowMap({\n+                'id': entry['set-id'],\n+                **({'stub': True} if entry.get('stub') else {}),\n+            })\n+            for name, entry in data['sets'].items()\n+        }\n+    if data['fills']:\n+        compact['fills'] = {\n+            name: _compact_tree(nodes)\n+            for name, nodes in data['fills'].items()\n+        }\n+    if data['ops']:\n+        compact['ops'] = {\n+            name: _compact_op(entry)\n+            for name, entry in data['ops'].items()\n+        }\n+    return compact\n+\n+\n+def _compact_groups(groups):\n+    compact = {}\n+    for name, group in groups.items():\n+        compact[name] = {\n+            'id': group['group-id'],\n+            'attrs': {\n+                attr_name: _compact_attr(attr)\n+                for attr_name, attr in group['attrs'].items()\n+            },\n+        }\n+    return compact\n+\n+\n+def _compact_attr(attr):\n+    kind = attr['kind']\n+    compact = _FlowMap({'id': attr['local-id']})\n+    if kind in ('enum', 'flags'):\n+        compact[kind] = attr['definition']\n+    elif kind == 'blob':\n+        blob = attr['blob']\n+        compact['blob'] = blob['direction']\n+        compact['backings'] = _FlowSeq(blob['backings'])\n+        compact['max-length'] = blob['max-length']\n+        if blob['alignment'] != 1:\n+            compact['alignment'] = blob['alignment']\n+    else:\n+        compact['type'] = kind\n+\n+    if kind in ('uint', 'sint'):\n+        low, high = ((0, spec.U64_MAX) if kind == 'uint'\n+                     else (spec.S64_MIN, spec.S64_MAX))\n+        minimum = attr.get('min', low)\n+        maximum = attr.get('max', high)\n+        if minimum != low:\n+            compact['min'] = minimum\n+        if maximum != high:\n+            compact['max'] = maximum\n+        if 'unit' in attr:\n+            compact['unit'] = attr['unit']\n+            if attr['scale']:\n+                compact['scale'] = attr['scale']\n+    elif kind in ('string', 'binary'):\n+        minimum = attr.get('min-length', 0)\n+        maximum = attr['max-length']\n+        if kind == 'binary' and minimum == maximum:\n+            compact['length'] = maximum\n+        else:\n+            if minimum:\n+                compact['min-length'] = minimum\n+            compact['max-length'] = maximum\n+\n+    maximum = attr['max-occurrences']\n+    if maximum != 1:\n+        compact['max-occurrences'] = (\n+            'unlimited' if maximum == spec.UNLIMITED else maximum)\n+    return compact\n+\n+\n+def _compact_op(op):\n+    abi = _FlowMap({\n+        'id': op['op-id'],\n+        'type': op['type'],\n+    })\n+    if (op['type'] != 'event' and\n+            op.get('fd-access') != spec.DEFAULT_FD_ACCESS):\n+        abi['fd-access'] = op.get('fd-access')\n+    availability = op.get('availability', spec.DEFAULT_AVAILABILITY)\n+    if availability != spec.DEFAULT_AVAILABILITY:\n+        abi['availability'] = availability\n+    if op.get('optional', False):\n+        abi['optional'] = True\n+    if op.get('pre-post', False):\n+        abi['pre-post'] = True\n+    compact = {'abi': abi}\n+    if op.get('request'):\n+        compact['request'] = _compact_tree(op['request'])\n+    if op.get('reply') is not None:\n+        compact['reply'] = _compact_tree(op['reply'])\n+    return compact\n+\n+\n+def _compact_tree(nodes):\n+    required = []\n+    optional = []\n+    for node in nodes:\n+        destination = required if node['required'] else optional\n+        destination.append(_compact_node(node))\n+    compact = {}\n+    if required:\n+        compact['attrs'] = _compact_nodes(required)\n+    if optional:\n+        compact['optional-attrs'] = _compact_nodes(optional)\n+    if compact and _simple_tree_length(compact) \u003c= 54:\n+        return _FlowMap(compact)\n+    return compact\n+\n+\n+def _simple_tree_length(tree):\n+    length = 2\n+    for index, (name, selectors) in enumerate(tree.items()):\n+        if not isinstance(selectors, _FlowSeq):\n+            return 55\n+        if index:\n+            length += 2\n+        length += len(name) + 4\n+        length += sum(len(selector) + 2 for selector in selectors)\n+    return length\n+\n+\n+def _compact_nodes(nodes):\n+    if all(isinstance(node, str) for node in nodes):\n+        return _FlowSeq(nodes)\n+    return nodes\n+\n+\n+def _compact_node(node):\n+    name = node.get('attr', node.get('stub'))\n+    children = _compact_tree(node.get('children', []))\n+    if 'reenters' in node:\n+        children['reenters'] = node['reenters']\n+    if not children:\n+        return name\n+    return {name: children}\n+\n+\n+def _expand(compact):\n+    family = compact['family']\n+    family_id = family['id']\n+    definitions = {}\n+    for kind, section in (('enum', 'enums'), ('flags', 'flags')):\n+        for name, values in compact.get(section, {}).items():\n+            definitions[name] = {\n+                'kind': kind,\n+                'values': values,\n+            }\n+    return {\n+        'family': family['name'],\n+        'family-id': family_id,\n+        'parent': family.get('inherits'),\n+        'pre-init': family.get('pre-init', False),\n+        'post-init': family.get('post-init', False),\n+        'pre-fini': family.get('pre-fini', False),\n+        'definitions': definitions,\n+        'groups': _expand_groups(compact.get('attr-groups', {})),\n+        'sets': _expand_sets(compact.get('attr-sets', {})),\n+        'fills': {\n+            name: _expand_tree(tree)\n+            for name, tree in compact.get('fills', {}).items()\n+        },\n+        'ops': _expand_ops(compact.get('ops', {})),\n+    }\n+\n+\n+def _expand_groups(groups):\n+    expanded = {}\n+    for name, group in groups.items():\n+        expanded[name] = {\n+            'group-id': group['id'],\n+            'attrs': {\n+                attr_name: _expand_attr(attr)\n+                for attr_name, attr in group['attrs'].items()\n+            },\n+        }\n+    return expanded\n+\n+\n+def _expand_attr(compact):\n+    primary = [name for name in ('type', 'enum', 'flags', 'blob')\n+               if name in compact]\n+    if len(primary) != 1:\n+        raise CtlvError('ABI snapshot attr',\n+                        'expected one of type, enum, flags or blob')\n+    kind = compact[primary[0]] if primary[0] == 'type' else primary[0]\n+    attr = {\n+        'local-id': compact['id'],\n+        'kind': kind,\n+        'max-occurrences': compact.get('max-occurrences', 1),\n+    }\n+    if attr['max-occurrences'] == 'unlimited':\n+        attr['max-occurrences'] = spec.UNLIMITED\n+    if kind in ('enum', 'flags'):\n+        attr['definition'] = compact[kind]\n+    elif kind in ('uint', 'sint'):\n+        low, high = ((0, spec.U64_MAX) if kind == 'uint'\n+                     else (spec.S64_MIN, spec.S64_MAX))\n+        attr['min'] = compact.get('min', low)\n+        attr['max'] = compact.get('max', high)\n+        if 'unit' in compact:\n+            attr['unit'] = compact['unit']\n+            attr['scale'] = compact.get('scale', 0)\n+    elif kind in ('string', 'binary'):\n+        if 'length' in compact:\n+            attr['min-length'] = compact['length']\n+            attr['max-length'] = compact['length']\n+        else:\n+            attr['min-length'] = compact.get('min-length', 0)\n+            attr['max-length'] = compact['max-length']\n+    elif kind == 'blob':\n+        attr['blob'] = {\n+            'direction': compact['blob'],\n+            'backings': list(compact['backings']),\n+            'max-length': compact['max-length'],\n+            'alignment': compact.get('alignment', 1),\n+        }\n+    return attr\n+\n+\n+def _expand_sets(attr_sets):\n+    return {\n+        name: {\n+            'set-id': entry['id'],\n+            **({'stub': True} if entry.get('stub') else {}),\n+        }\n+        for name, entry in attr_sets.items()\n+    }\n+\n+\n+def _expand_ops(ops):\n+    expanded = {}\n+    for name, op in ops.items():\n+        abi = op['abi']\n+        op_type = abi['type']\n+        entry = {\n+            'op-id': abi['id'],\n+            'type': op_type,\n+            'availability': abi.get(\n+                'availability', spec.DEFAULT_AVAILABILITY),\n+            'optional': abi.get('optional', False),\n+            'pre-post': abi.get('pre-post', False),\n+            'request': (None if op_type == 'event'\n+                        else _expand_tree(op.get('request', {}))),\n+            'reply': (None if 'reply' not in op\n+                      else _expand_tree(op['reply'])),\n+        }\n+        if op_type != 'event':\n+            entry['fd-access'] = abi.get(\n+                'fd-access', spec.DEFAULT_FD_ACCESS)\n+        expanded[name] = entry\n+    return expanded\n+\n+\n+def _expand_tree(tree):\n+    nodes = []\n+    for required, key in ((True, 'attrs'), (False, 'optional-attrs')):\n+        for selector in tree.get(key, []):\n+            nodes.append(_expand_node(selector, required))\n+    return nodes\n+\n+\n+def _expand_node(selector, required):\n+    if isinstance(selector, str):\n+        name = selector\n+        nested = {}\n+    else:\n+        if not isinstance(selector, dict) or len(selector) != 1:\n+            raise CtlvError('ABI snapshot tree',\n+                            'expected an attr name or one nested attr')\n+        name, nested = next(iter(selector.items()))\n+    if '.' not in name:\n+        return {'stub': name, 'required': required}\n+    node = {'attr': name, 'required': required}\n+    children = _expand_tree(nested)\n+    if children:\n+        node['children'] = children\n+    if 'reenters' in nested:\n+        node['reenters'] = nested['reenters']\n+    return node\n+\n+\n+def registry_build(registry):\n+    \"\"\"Return the registry in the same normalized form as its source.\"\"\"\n+    families = []\n+    for entry in registry.entries:\n+        if entry.deprecated:\n+            families.append({'name': entry.name, 'deprecated': True})\n+        else:\n+            families.append(entry.name)\n+    return {'families': families}\n+\n+\n+def registry_render(registry):\n+    body = yaml.dump(registry_build(registry), Dumper=_Dumper,\n+                     sort_keys=False, default_flow_style=False, width=76)\n+    return REGISTRY_HEADER + body\n+\n+\n+def registry_problems(old, current, exact):\n+    problems = []\n+    for family_id, was in enumerate(old.entries):\n+        if family_id \u003e= len(current.entries):\n+            problems.append(f'family ID {family_id} ({was.name}) was removed')\n+            continue\n+        now = current.entries[family_id]\n+        if now.name != was.name:\n+            problems.append(f'family ID {family_id} was {was.name}, now '\n+                            f'{now.name}')\n+        elif was.deprecated and not now.deprecated:\n+            problems.append(f'family ID {family_id} ({was.name}) was reused '\n+                            'after deprecation')\n+    if exact and not problems and old.entries != current.entries:\n+        problems.append('the registry ABI baseline needs updating')\n+    return problems\n+\n+\n+def registry_check(paths, registry, exact=True):\n+    baseline = spec.load_registry(paths, paths.registry_abi)\n+    problems = registry_problems(baseline, registry, exact)\n+    if problems:\n+        raise CtlvError(f'{paths.registry} against {paths.registry_abi}',\n+                        'the family registry is not compatible with its '\n+                        'baseline\\n' +\n+                        '\\n'.join(f'  {problem}' for problem in problems))\n+\n+\n+def _definitions(items):\n+    definitions = {}\n+    for definition in items:\n+        definitions[definition.name] = {\n+            'kind': definition.kind,\n+            'values': dict(definition.values),\n+        }\n+    return definitions\n+\n+\n+def _groups(items):\n+    groups = {}\n+    for group in items:\n+        groups[group.name] = {\n+            'group-id': group.group_id,\n+            'attrs': {attr.name: _attr(attr) for attr in group.attrs},\n+        }\n+    return groups\n+\n+\n+def _attr(attr):\n+    decl = attr.decl\n+    entry = {'local-id': attr.local_id, 'kind': decl.kind}\n+    if decl.ref is not None:\n+        entry['definition'] = decl.ref\n+    for name, value in (('min', decl.min), ('max', decl.max),\n+                        ('min-length', decl.min_length),\n+                        ('max-length', decl.max_length),\n+                        ('unit', decl.unit), ('scale', decl.scale)):\n+        if value is not None:\n+            entry[name] = value\n+    if decl.blob is not None:\n+        entry['blob'] = {\n+            'direction': decl.blob.direction,\n+            'backings': list(decl.blob.backings),\n+            'max-length': decl.blob.max_length,\n+            'alignment': decl.blob.alignment,\n+        }\n+    entry['max-occurrences'] = decl.max_occurrences\n+    return entry\n+\n+\n+def _sets(attr_sets):\n+    sets = {}\n+    for attr_set in attr_sets:\n+        entry = {\n+            'set-id': attr_set.set_id,\n+        }\n+        if attr_set.stub:\n+            entry['stub'] = True\n+        sets[attr_set.name] = entry\n+    return sets\n+\n+\n+def _fills(fills):\n+    return {fill.name: _tree(fill.root) for fill in fills}\n+\n+\n+def _ops(items):\n+    ops = {}\n+    for op in items:\n+        entry = {\n+            'op-id': op.local_id,\n+            'type': op.type,\n+            'availability': op.availability,\n+            'optional': op.optional,\n+            'pre-post': op.pre_post,\n+            'request': _tree(op.request),\n+            'reply': _tree(op.reply),\n+        }\n+        if op.type != 'event':\n+            entry['fd-access'] = op.fd_access\n+        ops[op.name] = entry\n+    return ops\n+\n+\n+def _tree(root):\n+    if root is None:\n+        return None\n+    children = [_node(child) for child in root.children()]\n+    children += [_stub(stub) for stub in root.stubs]\n+    return children\n+\n+\n+def _node(node):\n+    entry = {'attr': node.attr.full_name, 'required': node.required}\n+    if node.reenters is not None:\n+        # The members are recorded above, so record where they come from.\n+        entry['reenters'] = node.reenters\n+        return entry\n+    children = _tree(node)\n+    if children:\n+        entry['children'] = children\n+    return entry\n+\n+\n+def _stub(stub):\n+    return {'stub': stub.name, 'required': not stub.optional}\n+\n+\n+def _compare(old, new):\n+    problems = []\n+    if old['family'] != new['family']:\n+        problems.append(f'family was renamed from {old[\"family\"]} to '\n+                        f'{new[\"family\"]}')\n+    if old['family-id'] != new['family-id']:\n+        problems.append(f'family-id was {old[\"family-id\"]}, now '\n+                        f'{new[\"family-id\"]}')\n+    # A name carries its ancestry, so reparenting renames every symbol.\n+    if old['parent'] != new['parent']:\n+        problems.append(f'the inherited family was {old[\"parent\"]}, now '\n+                        f'{new[\"parent\"]}')\n+    for key in ('pre-init', 'post-init', 'pre-fini'):\n+        if old.get(key, False) != new[key]:\n+            problems.append(f'family: {key} was {old.get(key, False)}, now '\n+                            f'{new[key]}')\n+    _compare_definitions(problems, old['definitions'], new['definitions'])\n+    _compare_groups(problems, old['groups'], new['groups'])\n+    _compare_sets(problems, old['sets'], new['sets'])\n+    _compare_fills(problems, old['fills'], new['fills'])\n+    _compare_ops(problems, old['ops'], new['ops'])\n+    return problems\n+\n+\n+def _compare_definitions(problems, old, new):\n+    for name, was in old.items():\n+        now = new.get(name)\n+        if now is None:\n+            problems.append(f'{was[\"kind\"]} {name} was removed')\n+            continue\n+        where = f'{was[\"kind\"]} {name}'\n+        if now['kind'] != was['kind']:\n+            problems.append(f'{where} is now a {now[\"kind\"]} definition')\n+        for value, number in was['values'].items():\n+            if value not in now['values']:\n+                problems.append(f'{where}: value {value} was removed')\n+            elif now['values'][value] != number:\n+                problems.append(f'{where}: value {value} was {number}, now '\n+                                f'{now[\"values\"][value]}')\n+\n+\n+def _compare_groups(problems, old, new):\n+    for name, was in old.items():\n+        now = new.get(name)\n+        if now is None:\n+            problems.append(f'attr group {name} was removed')\n+            continue\n+        where = f'attr group {name}'\n+        if was['group-id'] != now['group-id']:\n+            problems.append(f'{where}: group-id was {was[\"group-id\"]}, now '\n+                            f'{now[\"group-id\"]}')\n+        for attr, attr_was in was['attrs'].items():\n+            attr_now = now['attrs'].get(attr)\n+            if attr_now is None:\n+                problems.append(f'attr {name}.{attr} was removed')\n+                continue\n+            _compare_attr(problems, f'attr {name}.{attr}', attr_was, attr_now)\n+\n+\n+def _compare_attr(problems, where, was, now):\n+    for key in ('local-id', 'kind', 'definition', 'unit', 'scale'):\n+        if was.get(key) != now.get(key):\n+            problems.append(f'{where}: {key} was {was.get(key)}, now '\n+                            f'{now.get(key)}')\n+    for key in ('min', 'min-length'):\n+        if key in was and now.get(key, 0) \u003e was[key]:\n+            problems.append(f'{where}: {key} was narrowed from {was[key]} to '\n+                            f'{now[key]}')\n+    for key in ('max', 'max-length'):\n+        if key in was and now.get(key, 0) \u003c was[key]:\n+            problems.append(f'{where}: {key} was narrowed from {was[key]} to '\n+                            f'{now[key]}')\n+    _compare_occurrences(problems, where, was, now)\n+    if 'blob' in was:\n+        _compare_blob(problems, where, was['blob'], now.get('blob', {}))\n+\n+\n+def _compare_occurrences(problems, where, was, now):\n+    old_max = was['max-occurrences']\n+    new_max = now['max-occurrences']\n+    if old_max == new_max:\n+        return\n+    if old_max == spec.UNLIMITED or new_max \u003c old_max:\n+        problems.append(f'{where}: max-occurrences was narrowed from '\n+                        f'{_occurrences(old_max)} to {_occurrences(new_max)}')\n+\n+\n+def _compare_blob(problems, where, was, now):\n+    for key in ('direction', 'alignment'):\n+        if was.get(key) != now.get(key):\n+            problems.append(f'{where}: blob {key} was {was.get(key)}, now '\n+                            f'{now.get(key)}')\n+    for backing in was.get('backings', []):\n+        if backing not in now.get('backings', []):\n+            problems.append(f'{where}: blob backing {backing} was removed')\n+    if now.get('max-length', 0) \u003c was.get('max-length', 0):\n+        problems.append(f'{where}: blob max-length was narrowed from '\n+                        f'{was[\"max-length\"]} to {now[\"max-length\"]}')\n+\n+\n+def _compare_sets(problems, old, new):\n+    for name, was in old.items():\n+        now = new.get(name)\n+        if now is None:\n+            problems.append(f'attr set {name} was removed')\n+            continue\n+        for key in ('set-id', 'stub'):\n+            was_value = was.get(key, False)\n+            now_value = now.get(key, False)\n+            if was_value != now_value:\n+                problems.append(f'attr set {name}: {key} was {was_value}, '\n+                                f'now {now_value}')\n+\n+\n+def _compare_fills(problems, old, new):\n+    for name, was in old.items():\n+        now = new.get(name)\n+        if now is None:\n+            problems.append(f'stub fill {name} was removed')\n+            continue\n+        _compare_nodes(problems, f'stub fill {name}', was, now)\n+\n+\n+def _compare_ops(problems, old, new):\n+    for name, was in old.items():\n+        now = new.get(name)\n+        if now is None:\n+            problems.append(f'op {name} was removed')\n+            continue\n+        where = f'op {name}'\n+        # Whether an op may be disabled or withheld is what userspace compiles\n+        # against; whether it is either right now is per device.\n+        for key in ('op-id', 'type', 'fd-access',\n+                    'availability', 'optional', 'pre-post'):\n+            if was.get(key) != now.get(key):\n+                problems.append(f'{where}: {key} was {was.get(key)}, now '\n+                                f'{now.get(key)}')\n+        for what in ('request', 'reply'):\n+            if (what == 'reply' and was['type'] == 'action' and\n+                    was[what] is None and now[what] is not None):\n+                problems.append(f'{where}: an ACK-only action gained a '\n+                                'reply schema')\n+            elif was[what] is not None and now[what] is None:\n+                problems.append(f'{where}: the {what} schema was removed')\n+            elif was[what] is not None:\n+                _compare_nodes(problems, f'{where} {what}', was[what],\n+                               now[what])\n+\n+\n+def _compare_nodes(problems, where, old, new):\n+    by_name = {_node_key(node): node for node in new}\n+    for was in old:\n+        key = _node_key(was)\n+        name = _node_name(was)\n+        now = by_name.pop(key, None)\n+        if now is None:\n+            problems.append(f'{where}: {name} was removed')\n+            continue\n+        if now['required'] and not was['required']:\n+            problems.append(f'{where}: {name} became required')\n+        if was.get('reenters') != now.get('reenters'):\n+            problems.append(f'{where}: {name} re-entered '\n+                            f'{was.get(\"reenters\")}, now '\n+                            f'{now.get(\"reenters\")}')\n+        _compare_nodes(problems, f'{where} {name}',\n+                       was.get('children', []), now.get('children', []))\n+    for node in by_name.values():\n+        if node['required']:\n+            problems.append(\n+                f'{where}: new {_node_name(node)} must be optional')\n+\n+\n+def _node_key(node):\n+    if 'attr' in node:\n+        return 'attr', node['attr']\n+    return 'stub', node['stub']\n+\n+\n+def _node_name(node):\n+    if 'attr' in node:\n+        return node['attr']\n+    return f'stub {node[\"stub\"]}'\n+\n+\n+def _occurrences(max_occurrences):\n+    if max_occurrences == spec.UNLIMITED:\n+        return 'unlimited'\n+    return str(max_occurrences)\ndiff --git a/tools/ctlv/ctlvgen/lib/errors.py b/tools/ctlv/ctlvgen/lib/errors.py\nnew file mode 100644\nindex 0000000000000..a165218a381ea\n--- /dev/null\n+++ b/tools/ctlv/ctlvgen/lib/errors.py\n@@ -0,0 +1,14 @@\n+# SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause\n+\"\"\"The single error type reported by the CTLV schema tool.\"\"\"\n+\n+\n+class CtlvError(Exception):\n+    \"\"\"A specification, registry or ABI snapshot is not acceptable.\n+\n+    The test suite matches diagnostics, so a message's wording is contract.\n+    \"\"\"\n+\n+    def __init__(self, where, what):\n+        self.where = where\n+        self.what = what\n+        super().__init__(f'{where}: {what}' if where else what)\ndiff --git a/tools/ctlv/ctlvgen/lib/gen_family.py b/tools/ctlv/ctlvgen/lib/gen_family.py\nnew file mode 100644\nindex 0000000000000..92309334f979f\n--- /dev/null\n+++ b/tools/ctlv/ctlvgen/lib/gen_family.py\n@@ -0,0 +1,347 @@\n+# SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause\n+\"\"\"The descriptor of one family: who answers the wire.\n+\n+One struct ctlv_family and one struct ctlv_op per action or query\n+this family declares, plus the helpers a device uses to decide them. A family\n+answers what it declared: an inherited op is answered through the descriptor\n+of the family that declared it, by that family implementation.\n+\"\"\"\n+\n+from __future__ import annotations\n+\n+import dataclasses\n+\n+from . import cgen\n+from . import spec\n+\n+# The family's priv, the request/reply, and a context for core helpers.\n+CALLBACK_PARAMS = ('void *priv', 'struct ctlv_op_ctx *ctx',\n+                   'const struct ctlv_cursor *request',\n+                   'struct ctlv_cursor *reply')\n+\n+# What a hook takes, and what each half returns: a pre may refuse the op.\n+HOOK_PARAMS = ('void *priv', 'struct ctlv_op_ctx *ctx')\n+HOOK_RETURNS = (('pre', 'int'), ('post', 'void'))\n+\n+# How every family prepares, initializes and finalizes its priv.\n+LIFECYCLE_HOOKS = (\n+    ('priv_size', 'size_t', ('void',)),\n+    ('pre_init', 'const void', ('const void *init_info',)),\n+    ('init', 'int', ('struct ctlv_device *ctlvdev',\n+                     'const void *init_info', 'void *priv')),\n+    ('post_init', 'int', ('struct ctlv_device *ctlvdev', 'void *priv')),\n+    ('pre_fini', 'void', ('struct ctlv_device *ctlvdev', 'void *priv')),\n+    ('fini', 'void', ('struct ctlv_device *ctlvdev', 'void *priv')),\n+)\n+OPTIONAL_LIFECYCLE_HOOKS = ('pre_init', 'post_init', 'pre_fini')\n+\n+# The reply-side callback for an extension point.\n+STUB_HOOKS = (\n+    ('fill', 'int', ('void *priv', 'struct ctlv_op_ctx *ctx',\n+                     'const struct ctlv_cursor *request',\n+                     'struct ctlv_cursor *nest')),\n+)\n+\n+# The state helpers of a dynamically available op.\n+STATES = ('enable', 'disable')\n+\n+\n+@dataclasses.dataclass(frozen=True)\n+class ReaderScope:\n+    name: tuple\n+    node: object\n+    tree: str\n+    node_index: int\n+\n+\n+INPUT_MACROS = {\n+    'uint': 'U64',\n+    'sint': 'S64',\n+    'bool': 'BOOL',\n+    'string': 'STRING',\n+    'binary': 'BINARY',\n+    'enum': 'U64',\n+    'flags': 'U64',\n+    'nested': 'NEST',\n+    'blob': 'BLOB',\n+}\n+\n+PUT_MACROS = {\n+    'uint': 'U64',\n+    'sint': 'S64',\n+    'bool': 'BOOL',\n+    'string': 'STRING',\n+    'binary': 'BINARY',\n+    'enum': 'U64',\n+    'flags': 'U64',\n+}\n+\n+\n+def bindings(family):\n+    \"\"\"The ops family binds, in the order it binds them.\n+\n+    Its own actions and queries, in declaration order. An op it inherited is\n+    answered by the family that declared it, and an event by nobody.\n+    \"\"\"\n+    return tuple(op for op in family.local_ops if op.type != 'event')\n+\n+\n+def _implementer(family):\n+    \"\"\"Who writes the callbacks of a family.\"\"\"\n+    if family.name == spec.CORE_FAMILY_NAME:\n+        return 'the CTLV core'\n+    return 'this family'\n+\n+\n+def _macro(writer, name, args):\n+    writer.parenthesized(f'{name}(', args, ')')\n+\n+\n+def emit_header(writer, names, family, reader_scopes):\n+    \"\"\"Append the family API to a generated kernel header.\"\"\"\n+    bound = bindings(family)\n+    if bound:\n+        writer.comment(f'Implemented by {_implementer(family)}, one per '\n+                       'action and query it declares.')\n+    for op in bound:\n+        writer.signature('int', names.callback(op), CALLBACK_PARAMS)\n+    if bound:\n+        writer.line()\n+    _hooks(writer, names, family)\n+    _lifecycle_hooks(writer, names, family)\n+    _stub_hooks(writer, names, family)\n+    writer.line()\n+    writer.declaration('extern const struct ctlv_family',\n+                       f'{names.descriptor()};')\n+    writer.line()\n+    writer.line('#ifndef _CTLV_GENERATED_METADATA_ONLY')\n+    _helpers(writer, names, family)\n+    _readers(writer, names, reader_scopes)\n+    _writers(writer, names, family)\n+    _creators(writer, names, family)\n+    writer.line('#endif /* _CTLV_GENERATED_METADATA_ONLY */')\n+    writer.line()\n+\n+\n+def _hooks(writer, names, family):\n+    \"\"\"The pair around every op, and the pair around one op.\"\"\"\n+    if family.name == spec.CORE_FAMILY_NAME:\n+        writer.comment('Root-family hooks around every core action or query.')\n+    else:\n+        writer.comment('Family-wide hooks around every effective non-core op.')\n+    for which, returns in HOOK_RETURNS:\n+        writer.signature(returns, names.family_hook(which), HOOK_PARAMS)\n+\n+    marked = [op for op in bindings(family) if op.pre_post]\n+    if not marked:\n+        return\n+    writer.line()\n+    writer.comment('Per-op hooks nested inside the family-wide pair.')\n+    for first, op in enumerate(marked):\n+        if first:\n+            writer.line()\n+        for which, returns in HOOK_RETURNS:\n+            writer.signature(returns, names.op_hook(op, which), HOOK_PARAMS)\n+\n+\n+def _declared_lifecycle_hooks(family):\n+    return tuple(hook for hook in LIFECYCLE_HOOKS\n+                 if hook[0] not in OPTIONAL_LIFECYCLE_HOOKS or\n+                 getattr(family, hook[0]))\n+\n+\n+def _lifecycle_hooks(writer, names, family):\n+    \"\"\"The generated lifecycle of this family's priv.\"\"\"\n+    writer.line()\n+    writer.comment('Core-allocated family priv lifecycle.')\n+    for which, returns, params in _declared_lifecycle_hooks(family):\n+        name = names.lifecycle_hook(which)\n+\n+        writer.signature(returns, f'*{name}' if which == 'pre_init' else name,\n+                         params)\n+\n+\n+def _stub_hooks(writer, names, family):\n+    \"\"\"What this family puts into each stub it fills.\"\"\"\n+    if not family.fills:\n+        return\n+    for fill in family.fills:\n+        owner = family.owners[fill.family_id]\n+        writer.line()\n+        writer.comment(f'{fill.name} of {owner}: fill callback.')\n+        for which, returns, params in STUB_HOOKS:\n+            writer.signature(returns, names.stub_callback(fill, which),\n+                             params)\n+\n+\n+def _helpers(writer, names, family):\n+    \"\"\"What one device may decide about each op this family declares.\"\"\"\n+    ops = [op for op in family.local_ops if op.type != 'event' and\n+           (op.optional or op.availability == 'dynamic')]\n+    if not ops:\n+        return\n+    writer.line()\n+    writer.comment('Optional publication and dynamic availability helpers.')\n+    for op in ops:\n+        if op.optional:\n+            _macro(writer, 'CTLV_OP_PROVIDE',\n+                   (names.op_ident(op), names.op_id(op)))\n+        if op.availability == 'dynamic':\n+            for state in STATES:\n+                _macro(writer, f'CTLV_OP_{state.upper()}',\n+                       (names.op_ident(op), names.op_id(op)))\n+\n+\n+def _readers(writer, names, scopes):\n+    \"\"\"Placement-specific indexed access to callback requests.\"\"\"\n+    if not any(scope.node.children() for scope in scopes):\n+        return\n+    writer.line()\n+    writer.comment('Reading a validated message. A blob has a resolver '\n+                   'instead of a getter.')\n+    for scope in scopes:\n+        for slot, child in enumerate(scope.node.children()):\n+            attr = child.attr\n+            repeated = attr.decl.max_occurrences != 1\n+            name = _input_name(names, scope, attr)\n+            _macro(writer, 'CTLV_IN_REF',\n+                   _input_args(names, scope, slot, attr))\n+            if repeated:\n+                _iterator(writer, names, scope, attr)\n+            else:\n+                _macro(writer, 'CTLV_IN_HAS', (name,))\n+            if attr.decl.kind == 'blob':\n+                macro = 'CTLV_IN_' + ('EACH_' if repeated else '') + 'BLOB'\n+                _macro(writer, macro, (name,))\n+            elif cgen.attr_getter_value(attr):\n+                macro = 'CTLV_IN_' + ('EACH_' if repeated else '') + \\\n+                        INPUT_MACROS[attr.decl.kind]\n+                _macro(writer, macro, (name,))\n+\n+\n+def _writers(writer, names, family):\n+    \"\"\"What a callback appends to the reply it was handed.\n+\n+    One helper per attr, returning whether the attr made it into the message.\n+    \"\"\"\n+    attrs = [attr for group in family.local_groups for attr in group.attrs\n+             if cgen.attr_writers(names, attr)]\n+    if not attrs:\n+        return\n+    writer.line()\n+    writer.comment('Writing a reply. An append is atomic; a nest ends with '\n+                   'ctlv_nest_end().')\n+    for attr in attrs:\n+        if attr.decl.kind == 'nested':\n+            macro = 'CTLV_NEST_START'\n+        else:\n+            macro = f'CTLV_PUT_{PUT_MACROS[attr.decl.kind]}'\n+        what = 'start' if attr.decl.kind == 'nested' else 'put'\n+        name = names.attr_helper(attr, what).removesuffix(f'_{what}')\n+        _macro(writer, macro,\n+               (name,\n+                names.attr(attr), cgen.KINDS[attr.decl.kind]))\n+\n+\n+def _creators(writer, names, family):\n+    \"\"\"What begins one event of each kind this family declares.\n+\n+    A creator hands back a context and the cursor of its root.\n+    \"\"\"\n+    events = [op for op in family.local_ops if op.type == 'event']\n+    if not events:\n+        return\n+    writer.line()\n+    writer.comment('Building one event, passed to ctlv_event_emit() or '\n+                   'ctlv_event_abort() once.')\n+    for op in events:\n+        _macro(writer, 'CTLV_EVENT_CREATE',\n+               (names.op_ident(op), names.op_id(op)))\n+\n+\n+def _input_name(names, scope, attr):\n+    return names.input_ref(scope, attr).removesuffix('_ref')\n+\n+\n+def _input_args(names, scope, slot, attr):\n+    return (_input_name(names, scope, attr), scope.tree, names.attr(attr),\n+            str(scope.node_index), str(slot), cgen.KINDS[attr.decl.kind])\n+\n+\n+def _iterator(writer, names, scope, attr):\n+    \"\"\"Every occurrence of a repeated attr, in wire order.\"\"\"\n+    writer.define_call(\n+        f'{names.input_iterator(scope, attr)}(_attr, _nest)',\n+        'CTLV_IN_FOR_EACH', names.input_name(scope, attr), '_attr', '_nest')\n+\n+\n+def emit_source(writer, names, family):\n+    \"\"\"Append the family bindings to a generated kernel source.\"\"\"\n+    _bindings(writer, names, family)\n+    _stub_ops(writer, names, family)\n+    _descriptor(writer, names, family)\n+\n+\n+def _bindings(writer, names, family):\n+    bound = bindings(family)\n+    if not bound:\n+        return\n+    writer.comment('Local action and query bindings in declaration order.')\n+    writer.declaration('static const struct ctlv_op',\n+                       f'{names.ops()}[] = {{')\n+    for op in bound:\n+        suffix = '_PRE_POST' if op.pre_post else ''\n+        writer.line(f'\\tCTLV_OP_{op.type.upper()}{suffix}('\n+                    f'{names.op_ident(op)}),')\n+    writer.line('};')\n+    writer.line()\n+\n+\n+def _stub_ops(writer, names, family):\n+    \"\"\"One entry per extension point this family fills, in the same order.\"\"\"\n+    if not family.fills:\n+        return\n+    writer.comment('Extension-point callbacks.')\n+    writer.declaration('static const struct ctlv_stub_ops',\n+                       f'{names.stub_ops()}[] = {{')\n+    for fill in family.fills:\n+        attr_set = family.sets[fill.name]\n+        args = (cgen.family_const(family.owners[fill.family_id]),\n+                names.attr_set(attr_set), names.stub_ident(fill))\n+        writer.parenthesized('\\tCTLV_STUB_OPS(', args, '),')\n+    writer.line('};')\n+    writer.line()\n+\n+\n+def _descriptor(writer, names, family):\n+    if family.name == spec.CORE_FAMILY_NAME:\n+        writer.comment('Root-family descriptor used by the CTLV core.')\n+    else:\n+        writer.comment('Family descriptor used by ctlv_create().')\n+    writer.declaration('const struct ctlv_family',\n+                       f'{names.descriptor()} = {{')\n+    writer.line(f'\\t.schema = \u0026{names.schema()},')\n+    parent = _parent_descriptor(family)\n+    if parent:\n+        writer.line(f'\\t.parent = \u0026{parent},')\n+    if bindings(family):\n+        writer.line(f'\\t.ops = {names.ops()},')\n+        writer.line(f'\\t.ops_count = ARRAY_SIZE({names.ops()}),')\n+    for which, _ in HOOK_RETURNS:\n+        writer.line(f'\\t.{which} = {names.family_hook(which)},')\n+    for which, _, _ in _declared_lifecycle_hooks(family):\n+        writer.line(f'\\t.{which} = {names.lifecycle_hook(which)},')\n+    if family.fills:\n+        stub_ops = names.stub_ops()\n+        writer.line(f'\\t.stub_ops = {stub_ops},')\n+        writer.line(f'\\t.stub_ops_count = ARRAY_SIZE({stub_ops}),')\n+    writer.line('};')\n+    # The one symbol an inheriting family's module needs of this one.\n+    writer.line(f'EXPORT_SYMBOL_NS_GPL({names.descriptor()}, \"CTLV\");')\n+\n+\n+def _parent_descriptor(family):\n+    \"\"\"The direct parent descriptor, none only for the root family.\"\"\"\n+    if family.parent is None:\n+        return None\n+    return cgen.Names(family.chain[-2]).descriptor()\ndiff --git a/tools/ctlv/ctlvgen/lib/gen_kernel.py b/tools/ctlv/ctlvgen/lib/gen_kernel.py\nnew file mode 100644\nindex 0000000000000..1854bd004f367\n--- /dev/null\n+++ b/tools/ctlv/ctlvgen/lib/gen_kernel.py\n@@ -0,0 +1,517 @@\n+# SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause\n+\"\"\"The kernel metadata of one family.\n+\n+Each family describes only what it declares. Each op request and reply becomes\n+one flat, breadth-first array of struct ctlv_node_schema the core walks by\n+index.\n+\"\"\"\n+\n+from __future__ import annotations\n+\n+import dataclasses\n+\n+from . import cgen\n+from . import gen_family\n+from . import semantics\n+from . import spec\n+\n+\n+def root_macro(*names):\n+    \"\"\"Return a constant of the root family's generated UAPI header.\"\"\"\n+    return cgen.macro(spec.CORE_FAMILY_NAME, *names)\n+\n+\n+FD_ACCESSES = {access: root_macro('op-fd-access', access)\n+               for access in spec.FD_ACCESSES}\n+\n+AVAILABILITIES = {availability: root_macro('op-availability', availability)\n+                  for availability in spec.AVAILABILITIES}\n+\n+# Lengths that have to fit the inline message limit. An event record is checked\n+# against the event queue instead.\n+INLINE_FIELDS = ('request_max_len', 'action_reply_max_len',\n+                 'query_reply_min_len', 'query_reply_suggested_len')\n+\n+# A bound written as its symbolic extreme stays readable.\n+U64_MAX = (1 \u003c\u003c 64) - 1\n+S64_MIN = -(1 \u003c\u003c 63)\n+S64_MAX = (1 \u003c\u003c 63) - 1\n+EXTREMES = {\n+    ('uint', spec.U32_MAX): 'U32_MAX',\n+    ('uint', U64_MAX): 'U64_MAX',\n+    ('sint', S64_MIN): 'S64_MIN',\n+    ('sint', S64_MAX): 'S64_MAX',\n+}\n+\n+\n+@dataclasses.dataclass(frozen=True)\n+class FlatNode:\n+    \"\"\"One node of a flattened tree, with its children as an index range.\"\"\"\n+\n+    node: object\n+    first_child: int\n+    children_count: int\n+    required_children_count: int\n+\n+\n+def flatten(root):\n+    \"\"\"Return the nodes of one tree breadth first, the root first.\n+\n+    A re-entering node points back at nodes already laid out, which is what\n+    keeps the array finite.\n+    \"\"\"\n+    flat = []\n+    queue = [(root, {})]\n+    next_index = 1\n+    while queue:\n+        node, levels = queue.pop(0)\n+        if node.reenters is not None:\n+            first_child, children_count, required_count = levels[node.reenters]\n+            flat.append(FlatNode(node=node, first_child=first_child,\n+                                 children_count=children_count,\n+                                 required_children_count=required_count))\n+            continue\n+        children = node.children()\n+        level = (next_index if children else 0, len(children),\n+                 len(node.required_children))\n+        flat.append(FlatNode(node=node, first_child=level[0],\n+                             children_count=level[1],\n+                             required_children_count=level[2]))\n+        next_index += len(children)\n+        if node.expands:\n+            levels = levels | {node.expands: level}\n+        queue += [(child, levels) for child in children]\n+    return tuple(flat)\n+\n+\n+def stub_schemas(root):\n+    \"\"\"Return each stub schema with the node index it joins.\"\"\"\n+    schemas = []\n+    for index, flat in enumerate(flatten(root)):\n+        for stub in flat.node.stubs:\n+            schemas.append((index, stub))\n+    return tuple(schemas)\n+\n+\n+def render_header(family, *, family_api):\n+    \"\"\"Return one family's generated kernel header.\"\"\"\n+    names = cgen.Names(family)\n+    cgen.symbols(family)\n+    guard = names.kernel_guard()\n+    local = family.local_ops\n+\n+    writer = cgen.preamble(family, 'kernel', 'header')\n+    what = 'Kernel metadata and family API' if family_api else \\\n+           'Schema metadata'\n+    writer.comment(f'{what} of the {family.name} CTLV family.')\n+    writer.line()\n+    writer.open_guard(guard)\n+    writer.includes(*_header_includes(family, names, family_api))\n+\n+    if local:\n+        writer.comment('Ops this family declares, in declaration order.')\n+        writer.declaration('extern const struct ctlv_op_schema',\n+                           f'{names.op_schemas()}[];')\n+        writer.line()\n+    writer.declaration('extern const struct ctlv_family_schema',\n+                       f'{names.schema()};')\n+    writer.line()\n+    _message_decls(writer, names, family)\n+    if family_api:\n+        gen_family.emit_header(writer, names, family,\n+                               _reader_scopes(family, names))\n+    writer.close_guard(guard)\n+    return writer.text()\n+\n+\n+def _reader_scopes(family, names):\n+    scopes = []\n+    indexes = {}\n+    for scope in semantics.input_scopes(family):\n+        if scope.kind == 'op':\n+            root = family.local_ops[scope.index].request\n+            tree = f'\u0026{names.op_schemas()}[{scope.index}].request'\n+        else:\n+            root = family.fills[scope.index].root\n+            tree = f'\u0026{names.schema()}.stub_fill_schemas[' \\\n+                   f'{scope.index}].members'\n+        key = (scope.kind, scope.index)\n+        if key not in indexes:\n+            indexes[key] = {id(flat.node): index\n+                            for index, flat in enumerate(flatten(root))}\n+        scopes.append(gen_family.ReaderScope(\n+            name=scope.name, node=scope.node, tree=tree,\n+            node_index=indexes[key][id(scope.node)]))\n+    return tuple(scopes)\n+\n+\n+def _message_decls(writer, names, family):\n+    \"\"\"The messages the core builds itself, and the room each one needs.\"\"\"\n+    for message in family.messages:\n+        writer.comment(f'The {message.name} message, built by the core.')\n+        writer.define(names.message_max_len(message), str(message.max_len))\n+        writer.line()\n+        writer.declaration('extern const struct ctlv_schema_tree',\n+                           f'{names.message_schema(message)};')\n+        writer.line()\n+\n+\n+def _header_includes(family, names, family_api):\n+    \"\"\"The generated types, constants and direct parent API.\"\"\"\n+    headers = ['\u003clinux/ctlv_family.h\u003e']\n+    if not family_api:\n+        return tuple(headers)\n+    headers += ['\u003clinux/err.h\u003e', '\u003clinux/errno.h\u003e', '',\n+                names.uapi_header(in_kernel=True)]\n+    if family.parent not in (None, spec.CORE_FAMILY_NAME):\n+        headers += ['', cgen.Names(family.chain[-2]).kernel_header()]\n+    return tuple(headers)\n+\n+\n+def render_source(family, *, family_api):\n+    \"\"\"Return one family's generated kernel source.\"\"\"\n+    names = cgen.Names(family)\n+    cgen.symbols(family)\n+    trees = _trees(family)\n+\n+    writer = cgen.preamble(family, 'kernel', 'source')\n+    if family_api:\n+        writer.line('#define _CTLV_GENERATED_METADATA_ONLY')\n+    writer.includes(*_includes(names, family, trees, family_api))\n+    for op, which, root in trees:\n+        _node_schemas(writer, family, names,\n+                      names.node_schemas(op, which), root)\n+        _stub_schemas(writer, family, names, op, which, root)\n+    _stub_fill_schemas(writer, family, names)\n+    _messages(writer, family, names)\n+    _table(writer, names, family)\n+    _descriptor(writer, names, family)\n+    _uevent(writer, family)\n+    _limits(writer, family, trees)\n+    if family_api:\n+        if family.local_ops:\n+            writer.line()\n+        gen_family.emit_source(writer, names, family)\n+    return writer.text()\n+\n+\n+def _trees(family):\n+    \"\"\"Every tree of every local op, in the order they are emitted.\"\"\"\n+    trees = []\n+    for op in family.local_ops:\n+        if op.request is not None:\n+            trees.append((op, 'request', op.request))\n+        if op.reply is not None:\n+            trees.append((op, 'reply', op.reply))\n+    return trees\n+\n+\n+def _roots(family, trees):\n+    \"\"\"Every emitted tree root: an op's, a fill's and a core message's.\"\"\"\n+    return [root for _, _, root in trees] + \\\n+           [fill.root for fill in family.fills] + \\\n+           [message.root for message in family.messages]\n+\n+\n+def _kinds(roots):\n+    return {flat.node.attr.decl.kind\n+            for root in roots for flat in flatten(root)\n+            if not flat.node.is_root}\n+\n+\n+def _includes(names, family, trees, family_api):\n+    headers = ['\u003clinux/array_size.h\u003e', '\u003clinux/build_bug.h\u003e',\n+               '\u003clinux/ctlv_family.h\u003e']\n+    if family_api:\n+        headers.append('\u003clinux/export.h\u003e')\n+    # The root family's enums name op types, availabilities and blob backings.\n+    uapi = [cgen.uapi_header(spec.CORE_FAMILY_NAME, in_kernel=True)]\n+    if family.name != spec.CORE_FAMILY_NAME:\n+        uapi.append(names.uapi_header(in_kernel=family_api))\n+    kinds = _kinds(_roots(family, trees))\n+    if 'blob' in kinds:\n+        # BIT(), for the mask of permitted blob backings.\n+        headers.append('\u003clinux/bits.h\u003e')\n+    if kinds \u0026 {'uint', 'sint'}:\n+        # The symbolic extremes of an unbounded integer bound.\n+        headers.append('\u003clinux/limits.h\u003e')\n+    groups = [sorted(headers), uapi, [names.kernel_header()]]\n+    lines = []\n+    for group in groups:\n+        if not group:\n+            continue\n+        if lines:\n+            lines.append('')\n+        lines += group\n+    return lines\n+\n+\n+def _has_event(family):\n+    return any(op.type == 'event' for op in family.local_ops)\n+\n+\n+def _node_schemas(writer, family, names, symbol, root):\n+    writer.declaration('static const struct ctlv_node_schema',\n+                       f'{symbol}[] = {{')\n+    for flat in flatten(root):\n+        _node(writer, family, names, flat)\n+    writer.line('};')\n+    writer.line()\n+\n+\n+def _node(writer, family, names, flat):\n+    macro, args = _node_initializer(family, names, flat)\n+    if macro == 'CTLV_NODE_SCHEMA_BLOB':\n+        _blob_node(writer, macro, args)\n+    else:\n+        writer.parenthesized(f'\\t{macro}(', args, '),')\n+\n+\n+def _blob_node(writer, macro, args):\n+    opening = f'\\t{macro}('\n+\n+    for line in cgen.wrapped(opening, args[:4], ','):\n+        writer.line(line)\n+    column = cgen.width(opening)\n+    indent = '\\t' * (column // cgen.TAB_WIDTH) + \\\n+        ' ' * (column % cgen.TAB_WIDTH)\n+    backings = args[4].split(' | ')\n+    for backing in backings[:-1]:\n+        writer.line(f'{indent}{backing} |')\n+    writer.line(f'{indent}{backings[-1]},')\n+    writer.line(f'{indent}{args[5]}),')\n+\n+\n+def _node_initializer(family, names, flat):\n+    node = flat.node\n+\n+    if node.is_root:\n+        return 'CTLV_NODE_SCHEMA_ROOT', (\n+            str(flat.first_child),\n+            str(flat.children_count),\n+            str(flat.required_children_count),\n+        )\n+\n+    decl = node.attr.decl\n+    kind = cgen.KINDS[decl.kind].removeprefix('CTLV_SCHEMA_')\n+    macro = f'CTLV_NODE_SCHEMA_{kind}'\n+    occurrences = str(node.max_occurrences) if node.max_occurrences else \\\n+        'CTLV_NODE_SCHEMA_UNLIMITED'\n+    args = [names.attr(node.attr), occurrences]\n+    if decl.kind == 'nested':\n+        if node.reenters is not None:\n+            macro += '_REENTERS'\n+        args += [str(flat.first_child), str(flat.children_count),\n+                 str(flat.required_children_count)]\n+    else:\n+        if decl.kind in ('uint', 'sint') and decl.unit is not None:\n+            macro += '_UNIT'\n+        args += _constraint_args(family, names, decl)\n+    return macro, tuple(args)\n+\n+\n+def _stub_schemas(writer, family, names, op, which, root):\n+    \"\"\"The extension points of one tree, by the node they widen.\"\"\"\n+    schemas = stub_schemas(root)\n+    if not schemas:\n+        return\n+    writer.comment('Extension points selected by this tree.')\n+    writer.declaration('static const struct ctlv_stub_schema',\n+                       f'{names.stub_schemas(op, which)}[] = {{')\n+    for index, stub in schemas:\n+        macro = 'CTLV_STUB_SCHEMA_OPTIONAL' if stub.optional else \\\n+            'CTLV_STUB_SCHEMA'\n+        attr_set = family.sets[stub.name]\n+        args = (cgen.family_const(family.owners[stub.family_id]),\n+                names.attr_set(attr_set), str(index))\n+        writer.parenthesized(f'\\t{macro}(', args, '),')\n+    writer.line('};')\n+    writer.line()\n+\n+\n+def _stub_fill_schemas(writer, family, names):\n+    \"\"\"The members this family puts into the stubs it inherited.\"\"\"\n+    if not family.fills:\n+        return\n+    for fill in family.fills:\n+        _node_schemas(writer, family, names,\n+                      names.fill_node_schemas(fill), fill.root)\n+    writer.comment('The extension points this family fills.')\n+    writer.declaration('static const struct ctlv_stub_fill_schema',\n+                       f'{names.stub_fill_schemas()}[] = {{')\n+    for fill in family.fills:\n+        attr_set = family.sets[fill.name]\n+        args = (cgen.family_const(family.owners[fill.family_id]),\n+                names.attr_set(attr_set), cgen.ident(fill.name))\n+        writer.parenthesized('\\tCTLV_STUB_FILL_SCHEMA(', args, '),')\n+    writer.line('};')\n+    writer.line()\n+\n+\n+def _messages(writer, family, names):\n+    \"\"\"The messages the core builds where no op declared one.\"\"\"\n+    for message in family.messages:\n+        _node_schemas(writer, family, names,\n+                      names.message_node_schemas(message), message.root)\n+        writer.declaration('const struct ctlv_schema_tree',\n+                           f'{names.message_schema(message)} = {{')\n+        node_schemas = names.message_node_schemas(message)\n+        writer.line(f'\\t.node_schemas = {node_schemas},')\n+        writer.line('\\t.node_schemas_count =')\n+        writer.line(f'\\t\\tARRAY_SIZE({node_schemas}),')\n+        writer.line('};')\n+        writer.line()\n+        writer.assertion(names.message_max_len(message), '\u003c=', message.limit)\n+        writer.line()\n+\n+\n+def _constraint_args(family, names, decl):\n+    \"\"\"The kind-specific arguments of one node-schema macro.\"\"\"\n+    if decl.kind in ('uint', 'sint'):\n+        low = _bound(decl.kind, decl.min)\n+        high = _bound(decl.kind, decl.max)\n+        args = [low, high]\n+        if decl.unit is not None:\n+            args += [f'CTLV_UNIT_{cgen.macro(decl.unit)}', str(decl.scale)]\n+        return args\n+    if decl.kind == 'enum':\n+        highest = max(family.definitions[decl.ref].numbers())\n+        return [str(highest)]\n+    if decl.kind == 'flags':\n+        return [names.value_mask(family.definitions[decl.ref])]\n+    if decl.kind in ('string', 'binary'):\n+        return [str(decl.min_length), str(decl.max_length)]\n+    if decl.kind == 'blob':\n+        return _blob_args(decl.blob)\n+    return []\n+\n+\n+def _bound(kind, value):\n+    extreme = EXTREMES.get((kind, value))\n+\n+    if extreme:\n+        return extreme\n+    if kind == 'uint' and value \u003e spec.S64_MAX:\n+        return f'{value}ULL'\n+    return str(value)\n+\n+\n+def _blob_args(blob):\n+    direction = root_macro('blob-direction', blob.direction)\n+    return [_bound('uint', blob.max_length), str(blob.alignment),\n+            _backings(blob.backings), direction]\n+\n+\n+def _backings(backings):\n+    terms = [f'BIT({root_macro(\"blob-type\", backing)})'\n+             for backing in backings]\n+    return ' | '.join(terms)\n+\n+\n+def _table(writer, names, family):\n+    local = family.local_ops\n+    if not local:\n+        return\n+    writer.comment('The ops this family declares, in declaration order.')\n+    writer.declaration('const struct ctlv_op_schema',\n+                       f'{names.op_schemas()}[] = {{')\n+    for op in local:\n+        macro, args = _op_schema_initializer(names, op)\n+        writer.parenthesized(f'\\t{macro}(', args, '),')\n+    writer.line('};')\n+    writer.line()\n+\n+\n+def _op_schema_initializer(names, op):\n+    sizes = op.sizes\n+    if op.type == 'action':\n+        macro = 'CTLV_OP_SCHEMA_ACTION'\n+        args = [names.op_id(op), FD_ACCESSES[op.fd_access],\n+                AVAILABILITIES[op.availability],\n+                str(sizes.request_max_len),\n+                str(sizes.action_reply_max_len),\n+                _op_tree(op, 'request'), _op_tree(op, 'reply')]\n+    elif op.type == 'query':\n+        macro = 'CTLV_OP_SCHEMA_QUERY'\n+        args = [names.op_id(op), FD_ACCESSES[op.fd_access],\n+                AVAILABILITIES[op.availability],\n+                str(sizes.request_max_len),\n+                str(sizes.query_reply_min_len),\n+                str(sizes.query_reply_suggested_len),\n+                _op_tree(op, 'request'), _op_tree(op, 'reply')]\n+    else:\n+        macro = 'CTLV_OP_SCHEMA_EVENT'\n+        args = [names.op_id(op), str(sizes.event_record_max_len),\n+                _op_tree(op, 'reply')]\n+    if op.optional:\n+        args.append('.optional = true')\n+    if op.pre_post:\n+        args.append('.pre_post = true')\n+    return macro, tuple(args)\n+\n+\n+def _op_tree(op, which):\n+    root = getattr(op, which)\n+    if root is None:\n+        return 'CTLV_SCHEMA_TREE_NONE()'\n+    macro = 'CTLV_SCHEMA_TREE_STUBS' if stub_schemas(root) else \\\n+        'CTLV_SCHEMA_TREE'\n+    return f'{macro}({cgen.ident(op.name, which)})'\n+\n+\n+def _descriptor(writer, names, family):\n+    \"\"\"This family's node of the schema graph.\"\"\"\n+    writer.comment('The family ID is its position in the central registry.')\n+    writer.declaration('const struct ctlv_family_schema',\n+                       f'{names.schema()} = {{')\n+    writer.line(f'\\t.name = \"{family.name}\",')\n+    writer.line(f'\\t.family_id = {family.family_id},')\n+    if family.local_ops:\n+        writer.line(f'\\t.ops = {names.op_schemas()},')\n+        writer.line(f'\\t.ops_count = ARRAY_SIZE({names.op_schemas()}),')\n+    if family.fills:\n+        stub_fill_schemas = names.stub_fill_schemas()\n+        writer.line(f'\\t.stub_fill_schemas = {stub_fill_schemas},')\n+        writer.line(f'\\t.stub_fill_schemas_count = '\n+                    f'ARRAY_SIZE({stub_fill_schemas}),')\n+    writer.line('};')\n+    writer.line()\n+\n+\n+def _uevent(writer, family):\n+    \"\"\"What this chain's names cost a device's uevent environment.\"\"\"\n+    names = [item.name for item in family.chain]\n+    variables = [f'CTLV_FAMILY={names[-1]}']\n+    variables += [f'CTLV_COMPATIBLE_{index}={name}'\n+                  for index, name in enumerate(names)]\n+    variables.append(f'CTLV_COMPATIBLE_N={len(names)}')\n+    # \"KEY=value\" plus the NUL, as add_uevent_var() charges it.\n+    writer.comment('Maximum uevent cost for this family chain.')\n+    writer.line(f'static_assert({sum(len(item) + 1 for item in variables)} \u003c= '\n+                'CTLV_UEVENT_MAX_LEN);')\n+    writer.line(f'static_assert({len(variables)} \u003c= CTLV_UEVENT_MAX_VARS);')\n+    writer.line()\n+\n+\n+def _limits(writer, family, trees):\n+    local = family.local_ops\n+    if not local:\n+        return\n+    writer.comment('Guards for generated maxima.')\n+    inline = max(getattr(op.sizes, field)\n+                 for op in local for field in INLINE_FIELDS)\n+    writer.line(f'static_assert({inline} \u003c= CTLV_MAX_INLINE_MESSAGE_LEN);')\n+    if _has_event(family):\n+        record = max(op.sizes.event_record_max_len for op in local)\n+        writer.line(f'static_assert({record} \u003c= CTLV_MAX_EVENT_QUEUE_LEN);')\n+    depth = max(_nest_depth(root) for root in _roots(family, trees))\n+    if depth:\n+        writer.line(f'static_assert({depth} \u003c= '\n+                    'CTLV_MAX_DECLARED_NEST_DEPTH);')\n+\n+\n+def _nest_depth(node):\n+    \"\"\"Deepest nest below node, which is itself at depth zero.\"\"\"\n+    depths = [1 + _nest_depth(child) for child in node.children()\n+              if child.attr.decl.kind == 'nested']\n+    return max(depths, default=0)\ndiff --git a/tools/ctlv/ctlvgen/lib/gen_uapi.py b/tools/ctlv/ctlvgen/lib/gen_uapi.py\nnew file mode 100644\nindex 0000000000000..14330248f1444\n--- /dev/null\n+++ b/tools/ctlv/ctlvgen/lib/gen_uapi.py\n@@ -0,0 +1,223 @@\n+# SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause\n+\"\"\"The UAPI header of one family.\n+\n+Names for numbers: complete attr and op IDs, group and attr-set IDs, enum\n+values, flag bits and units. The wire format is the transport\n+header's. An inherited declaration is not repeated, already having a name in\n+the header of the family that owns it.\n+\"\"\"\n+\n+from __future__ import annotations\n+\n+import textwrap\n+\n+from . import cgen\n+\n+# \" * \" plus the text has to stay inside the line limit.\n+COMMENT_WIDTH = cgen.LINE_LIMIT - 3\n+\n+\n+def render(family):\n+    \"\"\"Return the UAPI header of family as text.\"\"\"\n+    names = cgen.Names(family)\n+    cgen.symbols(family)\n+    guard = names.uapi_guard()\n+\n+    writer = cgen.preamble(family, 'uapi', 'header')\n+    _file_comment(writer, family)\n+    writer.line()\n+    writer.open_guard(guard)\n+    writer.includes(*_includes(family))\n+\n+    _definitions(writer, family, names)\n+    _groups(writer, family, names)\n+    _sets(writer, family, names)\n+    _ops(writer, family, names)\n+\n+    writer.close_guard(guard)\n+    return writer.text()\n+\n+\n+def render_families(registry):\n+    \"\"\"Return the family-number header of one registry.\"\"\"\n+    guard = '_UAPI_LINUX_CTLV_FAMILIES_GEN_H'\n+    values = [(cgen.family_const(entry.name), family_id)\n+              for family_id, entry in enumerate(registry.entries)]\n+    writer = cgen.preamble(registry, 'uapi', 'header', registry.path)\n+\n+    writer.comment('CTLV family numbers.')\n+    writer.line()\n+    writer.open_guard(guard)\n+    _sequential_enum(writer, '_ctlv_family', values)\n+    writer.line()\n+    writer.close_guard(guard)\n+    return writer.text()\n+\n+\n+def _includes(family):\n+    headers = ['\u003clinux/ctlv.h\u003e', cgen.families_uapi_header()]\n+    if family.parent:\n+        # Inherited constants live in the parent's header, so one include is\n+        # enough for the whole effective schema.\n+        headers.append(cgen.uapi_header(family.parent))\n+    if any(definition.kind == 'flags'\n+           for definition in _own(family, family.definitions.values())):\n+        # _BITULL(), which is the form of BIT_ULL() that userspace has.\n+        headers.append('\u003clinux/const.h\u003e')\n+    return sorted(headers)\n+\n+\n+def _file_comment(writer, family):\n+    paragraphs = [\n+        f'Constants of the {family.name} CTLV family. Attr and op IDs are '\n+        'complete; the wire format carrying them is in \u003clinux/ctlv.h\u003e.',\n+    ]\n+    if family.parent:\n+        paragraphs.append(\n+            f'The inherited {family.parent} header is included here, so one '\n+            'include covers the whole effective schema.')\n+    lines = []\n+    for paragraph in paragraphs:\n+        if lines:\n+            lines.append('')\n+        lines += textwrap.wrap(paragraph, COMMENT_WIDTH)\n+    writer.comment(*lines)\n+\n+\n+def _own(family, declarations):\n+    \"\"\"Only what this family declares itself, in declaration order.\"\"\"\n+    return [item for item in declarations\n+            if item.family_id == family.family_id]\n+\n+\n+def _definitions(writer, family, names):\n+    for definition in _own(family, family.definitions.values()):\n+        if definition.kind == 'enum':\n+            _enum(writer, names, definition)\n+        else:\n+            _flags(writer, names, definition)\n+        writer.line()\n+\n+\n+def _enum(writer, names, definition):\n+    writer.comment(f'enum {definition.name}')\n+    values = [(names.value(definition, value_name), number)\n+              for value_name, number in definition.values]\n+    _sequential_enum(writer, names.definition(definition), values)\n+\n+\n+def _flags(writer, names, definition):\n+    writer.comment(f'flags {definition.name}')\n+    bits = [(names.value_bit(definition, value_name), bit)\n+            for value_name, bit in definition.values]\n+    _sequential_enum(writer, names.bit_enum(definition), bits)\n+    writer.line()\n+    values = []\n+    for value_name, _bit in definition.values:\n+        value = names.value(definition, value_name)\n+        writer.define(value,\n+                      f'_BITULL({names.value_bit(definition, value_name)})')\n+        values.append(value)\n+    _flags_mask(writer, names.value_mask(definition), values)\n+\n+\n+def _groups(writer, family, names):\n+    groups = _own(family, family.groups.values())\n+    if not groups:\n+        return\n+    writer.comment('attr groups')\n+    _sequential_enum(writer, names.group_enum(groups[0]),\n+                     [(names.group(group), group.group_id)\n+                      for group in groups])\n+    writer.line()\n+    writer.define_call(\n+        f'{names.family_attr(groups[0])}(_group, _attr)', 'CTLV_ATTR',\n+        names.family_const(), '(_group)', '(_attr)')\n+    writer.line()\n+    for group in groups:\n+        if not group.attrs:\n+            continue\n+        writer.comment(f'attrs of group {group.name}')\n+        writer.define_call(f'{names.group_attr(group)}(_attr)',\n+                           names.family_attr(group),\n+                           names.group(group),\n+                           f'{names.local_attr_prefix(group)}##_attr')\n+        writer.line()\n+        _sequential_enum(writer, names.group_attr_enum(group),\n+                         [(names.local_attr(attr), attr.local_id)\n+                          for attr in group.attrs])\n+        writer.line()\n+        for attr in group.attrs:\n+            _attr(writer, names, group, attr)\n+        _attr_metadata(writer, names, group)\n+        writer.line()\n+\n+\n+def _attr(writer, names, group, attr):\n+    writer.define_call(names.attr(attr), names.group_attr(group),\n+                       cgen.macro(attr.name))\n+\n+\n+def _attr_metadata(writer, names, group):\n+    attrs = [attr for attr in group.attrs if attr.decl.unit is not None]\n+    if not attrs:\n+        return\n+    writer.line()\n+    writer.comment(f'metadata of group {group.name}')\n+    writer.line(f'enum {names.group_metadata_enum(group)} {{')\n+    for attr in attrs:\n+        writer.line(f'\\t{names.attr_unit(attr)} = '\n+                    f'CTLV_UNIT_{cgen.macro(attr.decl.unit)},')\n+        writer.line(f'\\t{names.attr_scale(attr)} = {attr.decl.scale},')\n+    writer.line('};')\n+\n+\n+def _sequential_enum(writer, name, values):\n+    first = values[0][1]\n+\n+    assert all(number == first + index\n+               for index, (_value, number) in enumerate(values))\n+    writer.line(f'enum {name} {{')\n+    for index, (value, number) in enumerate(values):\n+        assignment = f' = {number}' if not index and number else ''\n+        writer.line(f'\\t{value}{assignment},')\n+    writer.line('};')\n+\n+\n+def _flags_mask(writer, name, values):\n+    if len(values) == 1:\n+        writer.define(name, values[0])\n+        return\n+    lines = [f'\\t({values[0]} |']\n+    lines += [f'\\t {value} |' for value in values[1:-1]]\n+    lines.append(f'\\t {values[-1]})')\n+    writer.define_block(name, *lines)\n+\n+\n+def _sets(writer, family, names):\n+    own = _own(family, family.sets.values())\n+    if not own:\n+        return\n+    writer.comment('attr sets')\n+    _sequential_enum(writer, names.set_enum(own[0]),\n+                     [(names.attr_set(attr_set), attr_set.set_id)\n+                      for attr_set in own])\n+    writer.line()\n+\n+\n+def _ops(writer, family, names):\n+    own = _own(family, family.ops)\n+    if not own:\n+        return\n+    writer.comment('ops')\n+    _sequential_enum(writer, names.op_enum(own[0]),\n+                     [(names.op(op), op.local_id)\n+                      for op in own])\n+    writer.line()\n+    writer.define_call(f'{names.operation(own[0])}(_op)',\n+                       'CTLV_OP', names.family_const(),\n+                       f'{names.op_prefix(own[0])}##_op')\n+    for op in own:\n+        writer.define_call(names.op_id(op), names.operation(op),\n+                           cgen.macro(op.name))\n+    writer.line()\ndiff --git a/tools/ctlv/ctlvgen/lib/outputs.py b/tools/ctlv/ctlvgen/lib/outputs.py\nnew file mode 100644\nindex 0000000000000..4df7ae60c1c1e\n--- /dev/null\n+++ b/tools/ctlv/ctlvgen/lib/outputs.py\n@@ -0,0 +1,329 @@\n+# SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause\n+\"\"\"The complete set of generated files and its reconciliation.\"\"\"\n+\n+from __future__ import annotations\n+\n+import dataclasses\n+import os\n+import pathlib\n+import subprocess\n+import tempfile\n+\n+from . import gen_kernel\n+from . import gen_uapi\n+from . import semantics\n+from . import spec\n+from . import yamlload\n+from .errors import CtlvError\n+\n+\n+FLAVOURS = {\n+    'uapi-header': gen_uapi.render,\n+    'kernel-header': gen_kernel.render_header,\n+    'kernel-source': gen_kernel.render_source,\n+}\n+\n+IDENTITIES = {\n+    'uapi-header': ('uapi', 'header', '.h'),\n+    'kernel-header': ('kernel', 'header', '.h'),\n+    'kernel-source': ('kernel', 'source', '.c'),\n+}\n+\n+ROOT_FLAVOURS = frozenset(FLAVOURS)\n+FAMILY_FLAVOURS = frozenset(FLAVOURS)\n+FIXTURE_FLAVOURS = frozenset({\n+    'uapi-header', 'kernel-header', 'kernel-source',\n+})\n+\n+\n+@dataclasses.dataclass(frozen=True)\n+class Output:\n+    family: str\n+    source: pathlib.PurePosixPath\n+    registry: pathlib.PurePosixPath\n+    flavour: str\n+    path: pathlib.PurePosixPath\n+\n+\n+def _spec_paths(paths, source, registry):\n+    return spec.Paths(paths.kernel_dir / source, schema=paths.schema,\n+                      registry=paths.kernel_dir / registry)\n+\n+\n+def _relative(where, value):\n+    path = pathlib.PurePosixPath(value)\n+    if path.is_absolute() or '..' in path.parts or \\\n+            any(part.startswith('.') for part in path.parts) or \\\n+            str(path) != value:\n+        raise CtlvError(where, f'\"{value}\" is not a normalized relative path')\n+    return path\n+\n+\n+def _repository_path(paths, path):\n+    return pathlib.PurePosixPath(\n+        pathlib.Path(path).relative_to(paths.kernel_dir).as_posix())\n+\n+\n+def _manifest_contexts(paths):\n+    fixtures_dir = paths.kernel_dir / 'tools/ctlv/tests/specs'\n+    contexts = [\n+        (paths.generated, _repository_path(paths, paths.registry),\n+         _repository_path(paths, paths.spec_dir), None, False),\n+    ]\n+    manifest = fixtures_dir.parent / 'generated-files.yaml'\n+    if manifest.exists():\n+        fixtures = sorted(path.stem for path in fixtures_dir.glob('*.yaml'))\n+        contexts.append((\n+            manifest,\n+            _repository_path(paths, fixtures_dir.parent / 'families.yaml'),\n+            _repository_path(paths, fixtures_dir), fixtures, True))\n+    return tuple(contexts)\n+\n+\n+def load(paths):\n+    \"\"\"Load and validate every generated-file manifest.\"\"\"\n+    outputs = []\n+    families = set()\n+    destinations = set()\n+    for manifest, expected_registry, source_dir, expected_names, fixture in \\\n+            _manifest_contexts(paths):\n+        data = yamlload.load(manifest)\n+        spec._validate_syntax(manifest, data, paths.generated_schema)\n+        registry_record = data['registry']\n+        where = f'{manifest}: registry'\n+        registry_source = _relative(where, registry_record['source'])\n+        if registry_source != expected_registry:\n+            raise CtlvError(where, f'source is {registry_source}, expected '\n+                                   f'{expected_registry}')\n+        registry = spec.load_registry(\n+            paths, paths.kernel_dir / registry_source)\n+        if expected_names is None:\n+            expected_names = [entry.name for entry in registry.entries]\n+        records = data['families']\n+        if [record['name'] for record in records] != expected_names:\n+            raise CtlvError(str(manifest),\n+                            'manifest families do not match their sources')\n+\n+        for flavour, value in registry_record['outputs'].items():\n+            destination = _relative(f'{where} {flavour}', value)\n+            suffix = IDENTITIES[flavour][2]\n+            if destination.suffix != suffix:\n+                raise CtlvError(f'{where} {flavour}',\n+                                f'output must end in {suffix}')\n+            if destination in destinations:\n+                raise CtlvError(f'{where} {flavour}',\n+                                f'duplicate output path {destination}')\n+            destinations.add(destination)\n+            outputs.append(Output(None, registry_source, registry_source,\n+                                  flavour, destination))\n+\n+        for record in records:\n+            name = record['name']\n+            where = f'{manifest}: family {name}'\n+            if name in families:\n+                raise CtlvError(where, 'duplicate family')\n+            families.add(name)\n+\n+            expected_source = source_dir / f'{name}.yaml'\n+            source = _relative(where, record['source'])\n+            if source != expected_source:\n+                raise CtlvError(where, f'source is {source}, expected '\n+                                       f'{expected_source}')\n+\n+            required = FIXTURE_FLAVOURS if fixture else FAMILY_FLAVOURS\n+            if not fixture and name == spec.CORE_FAMILY_NAME:\n+                required = ROOT_FLAVOURS\n+            flavours = frozenset(record['outputs'])\n+            if flavours != required:\n+                missing = sorted(required - flavours)\n+                extra = sorted(flavours - required)\n+                detail = []\n+                if missing:\n+                    detail.append(f'missing {\", \".join(missing)}')\n+                if extra:\n+                    detail.append(f'unexpected {\", \".join(extra)}')\n+                raise CtlvError(where, '; '.join(detail))\n+\n+            family = semantics.load(\n+                _spec_paths(paths, source, registry_source))\n+            if family.name != name:\n+                raise CtlvError(where, f'source declares family '\n+                                       f'{family.name}')\n+            for flavour, value in record['outputs'].items():\n+                destination = _relative(f'{where} {flavour}', value)\n+                suffix = IDENTITIES[flavour][2]\n+                if destination.suffix != suffix:\n+                    raise CtlvError(f'{where} {flavour}',\n+                                    f'output must end in {suffix}')\n+                if destination in destinations:\n+                    raise CtlvError(f'{where} {flavour}',\n+                                    f'duplicate output path {destination}')\n+                destinations.add(destination)\n+                outputs.append(Output(name, source, registry_source, flavour,\n+                                      destination))\n+    return tuple(outputs)\n+\n+\n+def render(paths, plan):\n+    \"\"\"Render every planned output before any destination is changed.\"\"\"\n+    families = {}\n+    rendered = {}\n+    registered_registry = _repository_path(paths, paths.registry)\n+    for output in plan:\n+        source = _output_source(output)\n+        if output.family is None:\n+            registry = spec.load_registry(\n+                paths, paths.kernel_dir / output.registry)\n+            text = gen_uapi.render_families(registry)\n+        else:\n+            key = (output.source, output.registry)\n+            family = families.get(key)\n+            if family is None:\n+                family = semantics.load(\n+                    _spec_paths(paths, output.source, output.registry))\n+                families[key] = family\n+            renderer = FLAVOURS[output.flavour]\n+            if output.flavour in ('kernel-header', 'kernel-source'):\n+                text = renderer(\n+                    family, family_api=output.registry == registered_registry)\n+            else:\n+                text = renderer(family)\n+        mode, kind, _ = IDENTITIES[output.flavour]\n+        if _identity(text) != (source, mode, kind):\n+            raise CtlvError(str(output.path),\n+                            'generator emitted the wrong output marker')\n+        rendered[output.path] = text\n+    return rendered\n+\n+\n+def _output_source(output):\n+    return output.source.as_posix()\n+\n+\n+def _marked_files(root):\n+    if (root / '.git').exists():\n+        result = subprocess.run(\n+            ['git', 'grep', '--untracked', '--files-with-matches',\n+             'CTLV-GEN', '--', '*.c', '*.h', '*.rst'],\n+            cwd=root, capture_output=True, text=True, check=False)\n+        if result.returncode not in (0, 1):\n+            raise CtlvError(str(root), result.stderr.strip())\n+        candidates = (root / line for line in result.stdout.splitlines())\n+    else:\n+        candidates = (path for suffix in ('*.c', '*.h', '*.rst')\n+                      for path in root.rglob(suffix))\n+\n+    marked = set()\n+    for path in candidates:\n+        if path.is_symlink() or not path.is_file():\n+            continue\n+        text = path.read_text(encoding='utf-8', errors='replace')\n+        if _identity(text) is not None:\n+            marked.add(path.relative_to(root).as_posix())\n+    return marked\n+\n+\n+def _destination(root, relative):\n+    destination = root.joinpath(*relative.parts)\n+    if destination.is_symlink():\n+        raise CtlvError(str(destination),\n+                        'generated output cannot be a symlink')\n+    parent = destination.parent\n+    while parent != root and not parent.exists():\n+        parent = parent.parent\n+    if parent.is_symlink() or root.resolve() not in (\n+            parent.resolve(), *parent.resolve().parents):\n+        raise CtlvError(str(destination),\n+                        'generated output escapes its output root')\n+    return destination\n+\n+\n+def _replace(destination, text):\n+    destination.parent.mkdir(parents=True, exist_ok=True)\n+    fd, temporary = tempfile.mkstemp(dir=destination.parent,\n+                                     prefix=f'.{destination.name}.')\n+    try:\n+        with os.fdopen(fd, 'w', encoding='utf-8') as stream:\n+            stream.write(text)\n+        os.chmod(temporary, 0o644)\n+        os.replace(temporary, destination)\n+    finally:\n+        if os.path.exists(temporary):\n+            os.unlink(temporary)\n+\n+\n+def _identity(text):\n+    lines = text.splitlines()\n+    if len(lines) \u003c 4:\n+        return None\n+    c_spdx = (lines[0].startswith('// SPDX-License-Identifier: ') or\n+              (lines[0].startswith('/* SPDX-License-Identifier: ') and\n+               lines[0].endswith(' */')))\n+    if c_spdx and \\\n+            lines[1] == ('/* Do not edit, regenerate with '\n+                         'tools/ctlv/ctlv-regen.sh, from: */') and \\\n+            lines[2].startswith('/*\\t') and lines[2].endswith(' */') and \\\n+            lines[3].startswith('/* CTLV-GEN ') and lines[3].endswith(' */'):\n+        source = lines[2][3:-3]\n+        fields = lines[3][3:-3].split()\n+    elif lines[0].startswith('.. SPDX-License-Identifier: ') and \\\n+            lines[1] == ('.. Do not edit, regenerate with '\n+                         'tools/ctlv/ctlv-regen.sh, from:') and \\\n+            lines[2].startswith('..\\t') and \\\n+            lines[3].startswith('.. CTLV-GEN '):\n+        source = lines[2][3:]\n+        fields = lines[3][3:].split()\n+    else:\n+        return None\n+    if len(fields) == 3 and fields[0] == 'CTLV-GEN':\n+        return source, fields[1], fields[2]\n+    return None\n+\n+\n+def reconcile(paths, output_root=None, check=False):\n+    \"\"\"Check or atomically update every generated output.\"\"\"\n+    plan = load(paths)\n+    rendered = render(paths, plan)\n+    root = pathlib.Path(paths.kernel_dir if output_root is None\n+                        else output_root)\n+    if not root.is_dir():\n+        raise CtlvError(str(root), 'output root is not a directory')\n+    expected = {output.path.as_posix() for output in plan}\n+    unexpected = sorted(_marked_files(root) - expected)\n+    if unexpected:\n+        raise CtlvError('generated outputs',\n+                        'unexpected files\\n' +\n+                        '\\n'.join(f'  {path}' for path in unexpected))\n+\n+    states = {}\n+    problems = []\n+    unsafe = []\n+    by_path = {output.path: output for output in plan}\n+    for relative, text in rendered.items():\n+        destination = _destination(root, relative)\n+        if not destination.exists():\n+            problems.append(f'missing {relative}')\n+            states[relative] = (destination, text)\n+            continue\n+        if not destination.is_file():\n+            raise CtlvError(str(destination),\n+                            'generated output is not a regular file')\n+        current = destination.read_text(encoding='utf-8')\n+        if current == text:\n+            continue\n+        problems.append(f'stale {relative}')\n+        output = by_path[relative]\n+        mode, kind, _ = IDENTITIES[output.flavour]\n+        if not check and _identity(current) != (\n+                _output_source(output), mode, kind):\n+            unsafe.append(f'{relative} is not the planned generated file')\n+        states[relative] = (destination, text)\n+    if unsafe:\n+        raise CtlvError('generated outputs',\n+                        'refusing to overwrite files\\n' +\n+                        '\\n'.join(f'  {problem}' for problem in unsafe))\n+    if check and problems:\n+        raise CtlvError('generated outputs', '\\n'.join(problems))\n+    for destination, text in states.values():\n+        _replace(destination, text)\n+    return tuple(problems)\ndiff --git a/tools/ctlv/ctlvgen/lib/semantics.py b/tools/ctlv/ctlvgen/lib/semantics.py\nnew file mode 100644\nindex 0000000000000..83290bfb2f460\n--- /dev/null\n+++ b/tools/ctlv/ctlvgen/lib/semantics.py\n@@ -0,0 +1,893 @@\n+# SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause\n+\"\"\"The effective form of a CTLV family.\n+\n+The specifications of one inheritance chain resolved into one schema: numeric\n+IDs from declaration positions, selectors expanded into placements, and one\n+tree per op request and reply. A rule enforced here is not re-enforced\n+downstream.\n+\"\"\"\n+\n+from __future__ import annotations\n+\n+import dataclasses\n+\n+from . import sizes\n+from . import spec\n+from .errors import CtlvError\n+\n+MAX_FLAG_BITS = 64\n+\n+# These root enums are stored more narrowly than a generic enum range.\n+ROOT_ENUM_VALUES_MAX = {\n+    'op-type': spec.U8_MAX,\n+    'op-availability': spec.U8_MAX,\n+    'op-fd-access': spec.U8_MAX,\n+    'blob-direction': spec.U8_MAX,\n+    # BIT(value) is stored in struct ctlv_node_schema.blob.backings.\n+    'blob-type': 15,\n+}\n+\n+\n+def _check_count(where, what, count, maximum):\n+    if count \u003e maximum:\n+        raise CtlvError(where, f'{count} {what} exceed the {maximum} maximum')\n+\n+\n+@dataclasses.dataclass(frozen=True)\n+class Definition:\n+    \"\"\"An effective enum or flags definition.\"\"\"\n+\n+    name: str\n+    kind: str\n+    family_id: int\n+    values: tuple\n+\n+    def numbers(self):\n+        return tuple(number for _, number in self.values)\n+\n+\n+@dataclasses.dataclass(frozen=True)\n+class Attr:\n+    \"\"\"An effective attr, with its complete wire ID.\"\"\"\n+\n+    group: str\n+    name: str\n+    family_id: int\n+    group_id: int\n+    local_id: int\n+    attr_id: int\n+    decl: spec.AttrDecl\n+\n+    @property\n+    def full_name(self):\n+        return f'{self.group}.{self.name}'\n+\n+\n+@dataclasses.dataclass(frozen=True)\n+class Group:\n+    name: str\n+    family_id: int\n+    group_id: int\n+    attrs: tuple\n+\n+\n+@dataclasses.dataclass(frozen=True)\n+class AttrSet:\n+    \"\"\"An effective attr set. A stub that nobody filled stays a stub.\"\"\"\n+\n+    name: str\n+    family_id: int\n+    set_id: int\n+    stub: bool\n+    attrs: tuple\n+    optional_attrs: tuple\n+\n+\n+@dataclasses.dataclass(frozen=True)\n+class Stub:\n+    \"\"\"One place where a descendant's fill of a stub splices in.\n+\n+    The declaring family's metadata carries this in place of those members.\n+    \"\"\"\n+\n+    name: str\n+    family_id: int\n+    set_id: int\n+    optional: bool\n+\n+\n+@dataclasses.dataclass(frozen=True)\n+class Fill:\n+    \"\"\"The members one family puts into a stub it inherited.\n+\n+    root stands for the stub itself, so its children are what splices in.\n+    \"\"\"\n+\n+    name: str\n+    owner_family_id: int\n+    family_id: int\n+    set_id: int\n+    root: Node\n+\n+\n+@dataclasses.dataclass(frozen=True)\n+class Node:\n+    \"\"\"One node of an expanded op tree. The root has no attr.\n+\n+    stubs are the extension points selected here and still unfilled. A\n+    recursive nest becomes a node naming the set in expands and childless\n+    nodes below it naming it in reenters, so walking children terminates.\n+    \"\"\"\n+\n+    attr: Attr\n+    required: bool\n+    max_occurrences: int\n+    required_children: tuple\n+    optional_children: tuple\n+    stubs: tuple = ()\n+    expands: str = None\n+    reenters: str = None\n+\n+    @property\n+    def is_root(self):\n+        return self.attr is None\n+\n+    def children(self):\n+        return self.required_children + self.optional_children\n+\n+\n+@dataclasses.dataclass(frozen=True)\n+class Message:\n+    \"\"\"One message root that no op declares, built by the core unasked.\n+\n+    Only the root family declares one.\n+    \"\"\"\n+\n+    name: str\n+    family_id: int\n+    set_id: int\n+    root: Node\n+    max_len: int\n+    limit: str\n+\n+\n+@dataclasses.dataclass(frozen=True)\n+class Op:\n+    \"\"\"An effective op.\n+\n+    availability is the permission to enable and disable the op per device,\n+    not a state. optional means a device has the op only once its family opts\n+    in. pre_post asks for a pair of this op's own, on top of the family-wide\n+    one.\n+    \"\"\"\n+\n+    name: str\n+    type: str\n+    fd_access: str\n+    availability: str\n+    optional: bool\n+    pre_post: bool\n+    family_id: int\n+    local_id: int\n+    op_id: int\n+    request: Node\n+    reply: Node\n+    sizes: sizes.OpSizes\n+\n+\n+@dataclasses.dataclass(frozen=True)\n+class Family:\n+    \"\"\"One effective family: itself plus everything it inherits.\n+\n+    owners maps a family ID to its name for every family in the chain. fills\n+    is what a generator emits, chain_fills what a device answers with.\n+    \"\"\"\n+\n+    name: str\n+    family_id: int\n+    path: str\n+    chain: tuple\n+    owners: dict\n+    definitions: dict\n+    groups: dict\n+    attrs: dict\n+    sets: dict\n+    ops: tuple\n+    fills: tuple\n+    chain_fills: tuple\n+    messages: tuple\n+\n+    @property\n+    def parent(self):\n+        return self.chain[-1].inherits\n+\n+    @property\n+    def license(self):\n+        return self.chain[-1].license\n+\n+    @property\n+    def pre_init(self):\n+        return self.chain[-1].pre_init\n+\n+    @property\n+    def post_init(self):\n+        return self.chain[-1].post_init\n+\n+    @property\n+    def pre_fini(self):\n+        return self.chain[-1].pre_fini\n+\n+    def _local(self, items):\n+        return tuple(item for item in items\n+                     if item.family_id == self.family_id)\n+\n+    @property\n+    def local_definitions(self):\n+        return self._local(self.definitions.values())\n+\n+    @property\n+    def local_groups(self):\n+        return self._local(self.groups.values())\n+\n+    @property\n+    def local_sets(self):\n+        \"\"\"Sets this family declares, a stub it inherited excluded.\"\"\"\n+        return self._local(self.sets.values())\n+\n+    @property\n+    def local_ops(self):\n+        return self._local(self.ops)\n+\n+\n+@dataclasses.dataclass(frozen=True)\n+class InputScope:\n+    kind: str\n+    index: int\n+    name: tuple\n+    node: Node\n+\n+\n+def input_scopes(family, owner_family_id=None):\n+    \"\"\"Every schema scope family code may read, with a unique name.\"\"\"\n+    def walk(kind, index, name, node):\n+        yield InputScope(kind, index, name, node)\n+        for child in node.children():\n+            if child.attr.decl.kind != 'nested':\n+                continue\n+            child_name = name + (child.attr.name,)\n+            yield from walk(kind, index, child_name, child)\n+\n+    if owner_family_id is None:\n+        ops = family.local_ops\n+        fills = family.fills\n+    else:\n+        ops = tuple(op for op in family.ops\n+                    if op.family_id == owner_family_id)\n+        fills = tuple(fill for fill in family.chain_fills\n+                      if fill.owner_family_id == owner_family_id)\n+\n+    for index, op in enumerate(ops):\n+        if op.request is not None:\n+            yield from walk('op', index, (op.name,), op.request)\n+    for index, fill in enumerate(fills):\n+        yield from walk('fill', index, (fill.name,), fill.root)\n+\n+\n+def load(paths):\n+    \"\"\"Load the family at paths.spec, resolved against its whole chain.\"\"\"\n+    registry = spec.load_registry(paths)\n+    return _Resolver(paths, registry).resolve()\n+\n+\n+class _Resolver:\n+    def __init__(self, paths, registry):\n+        self.paths = paths\n+        self.registry = registry\n+        self.definitions = {}\n+        self.groups = {}\n+        self.attrs = {}\n+        self.sets = {}\n+        self.ops = []\n+        # Which family filled each stub, to name it if a second one tries.\n+        self.stub_fillers = {}\n+        # Where each set was declared, for diagnostics.\n+        self.set_paths = {}\n+\n+    def resolve(self):\n+        chain = self._load_chain()\n+        self._check_names(chain)\n+        self._check_order(chain)\n+        target = chain[-1]\n+        for family in chain:\n+            self._add_family(family)\n+        self._check_sets()\n+        for family in chain:\n+            self._add_ops(family)\n+        fills = self._fills(target)\n+        chain_fills = self._fills(None)\n+        _check_count(f'{target.path}: family {target.name}', 'stub fills',\n+                     len(fills), spec.U32_MAX)\n+        resolved = Family(\n+            name=target.name,\n+            family_id=self._family_id(target),\n+            path=target.path,\n+            chain=chain,\n+            owners={self._family_id(item): item.name for item in chain},\n+            definitions=self.definitions,\n+            groups=self.groups,\n+            attrs=self.attrs,\n+            sets=self.sets,\n+            ops=tuple(self.ops),\n+            fills=fills,\n+            chain_fills=chain_fills,\n+            messages=self._messages(target),\n+        )\n+        _check_composed(resolved)\n+        return resolved\n+\n+    def _messages(self, family):\n+        \"\"\"The message roots this family declares that no op selects.\n+\n+        The root family alone has them, and has to have them.\n+        \"\"\"\n+        messages = []\n+        for name in sizes.CORE_MESSAGES:\n+            attr_set = self.sets.get(name)\n+            if attr_set is None:\n+                if family.name != spec.CORE_FAMILY_NAME:\n+                    continue\n+                raise CtlvError(f'{family.path}: family {family.name}',\n+                                f'the root family has to declare the \"{name}\" '\n+                                'attr set, which the core builds a message of')\n+            if attr_set.family_id != self._family_id(family):\n+                continue\n+            where = f'{self.set_paths[name]}: attr set {name}'\n+            nodes, stubs = self._expand_placements(\n+                spec.Placements(attr_set.attrs, attr_set.optional_attrs),\n+                where, (), 0, (name,))\n+            if stubs:\n+                raise CtlvError(where, 'a message the core builds cannot '\n+                                       'select an extension point')\n+            root = _root(nodes)\n+            _check_tree_size(where, root)\n+            messages.append(Message(\n+                name=name,\n+                family_id=attr_set.family_id,\n+                set_id=attr_set.set_id,\n+                root=root,\n+                max_len=sizes.message_max_len(where, name, root),\n+                limit=sizes.CORE_MESSAGES[name][0],\n+            ))\n+        return tuple(messages)\n+\n+    def _fills(self, family):\n+        \"\"\"The stubs one family fills, with the members it puts in each.\n+\n+        Passing None asks for the fills of the whole chain.\n+        \"\"\"\n+        fills = []\n+        for name, filler in self.stub_fillers.items():\n+            if family is not None and filler != family.name:\n+                continue\n+            attr_set = self.sets[name]\n+            nodes, stubs = self._expand_placements(\n+                spec.Placements(attr_set.attrs, attr_set.optional_attrs),\n+                f'{self.set_paths[name]}: attr set {name}', (), 0, (name,))\n+            root = _root(nodes, stubs)\n+            where = f'{self.set_paths[name]}: attr set {name}'\n+            _check_tree_size(where, root)\n+            if _reenters_anywhere(root):\n+                raise CtlvError(\n+                    where, 'a stub fill cannot contain a recursive attr')\n+            fills.append(Fill(\n+                name=name,\n+                owner_family_id=self.registry.family_id(filler),\n+                family_id=attr_set.family_id,\n+                set_id=attr_set.set_id,\n+                root=root,\n+            ))\n+        return tuple(fills)\n+\n+    # Loading and identity\n+\n+    def _load_chain(self):\n+        family = spec.load(self.paths.spec, self.paths.schema)\n+        if self.paths.spec.stem != family.name:\n+            raise CtlvError(f'{family.path}: family {family.name}',\n+                            'a specification must be named after its family, '\n+                            f'so this file must be {family.name}.yaml')\n+        chain = [family]\n+        seen = [family.name]\n+        self._check_root(family)\n+        while chain[0].inherits:\n+            parent_name = chain[0].inherits\n+            child = chain[0]\n+            if parent_name in seen:\n+                # seen runs from the selected family to its ancestors.\n+                raise CtlvError(f'{child.path}: family {child.name}',\n+                                'inheritance cycle: ' +\n+                                ' -\u003e '.join(seen + [parent_name]))\n+            parent_path = self.paths.sibling_spec(parent_name)\n+            parent = spec.load(parent_path, self.paths.schema)\n+            if parent.name != parent_name:\n+                raise CtlvError(f'{parent_path}: family {parent.name}',\n+                                f'expected family {parent_name}')\n+            self._check_root(parent)\n+            seen.append(parent_name)\n+            chain.insert(0, parent)\n+        return tuple(chain)\n+\n+    def _check_root(self, family):\n+        \"\"\"Require every family but the root one to name what it inherits.\"\"\"\n+        if family.name == spec.CORE_FAMILY_NAME:\n+            if family.inherits:\n+                raise CtlvError(f'{family.path}: family {family.name}',\n+                                'the root family heads every chain, so it '\n+                                'inherits nothing')\n+        elif not family.inherits:\n+            raise CtlvError(f'{family.path}: family {family.name}',\n+                            'must name the family it inherits, which is the '\n+                            f'root {spec.CORE_FAMILY_NAME} for a family '\n+                            'directly below it')\n+\n+    def _check_names(self, chain):\n+        \"\"\"Require every child family name to carry its whole ancestry.\n+\n+        A dash is the only separator; a dot selects group.attr.\n+        \"\"\"\n+        for parent, child in zip(chain, chain[1:]):\n+            suffix = child.name.removeprefix(f'{parent.name}-')\n+            if not suffix or suffix == child.name:\n+                raise CtlvError(f'{child.path}: family {child.name}',\n+                                f'a family that inherits {parent.name} must '\n+                                f'be named {parent.name}-\u003csuffix\u003e')\n+\n+    def _check_order(self, chain):\n+        \"\"\"Require a parent to be registered before what inherits it.\n+\n+        Ascending positions let the core walk a chain once and index it.\n+        \"\"\"\n+        for parent, child in zip(chain, chain[1:]):\n+            if self._family_id(parent) \u003e= self._family_id(child):\n+                raise CtlvError(f'{child.path}: family {child.name}',\n+                                f'is registered before {parent.name}, the '\n+                                'family it inherits')\n+\n+    def _family_id(self, family):\n+        family_id = self.registry.family_id(family.name)\n+        if family_id is None:\n+            raise CtlvError(f'{family.path}: family {family.name}',\n+                            f'not registered in {self.registry.path}')\n+        return family_id\n+\n+    # Declarations\n+\n+    def _add_family(self, family):\n+        family_id = self._family_id(family)\n+        self._add_definitions(family, family_id, family.enums, 'enum')\n+        self._add_definitions(family, family_id, family.flags, 'flags')\n+        self._add_groups(family, family_id)\n+        self._add_sets(family, family_id)\n+\n+    def _add_definitions(self, family, family_id, definitions, kind):\n+        for definition in definitions:\n+            where = f'{family.path}: {kind} {definition.name}'\n+            self._reject_redeclaration(where, self.definitions,\n+                                       definition.name, 'enum or flags')\n+            if kind == 'flags' and len(definition.values) \u003e MAX_FLAG_BITS:\n+                raise CtlvError(where, f'more than {MAX_FLAG_BITS} flag bits')\n+            if kind == 'enum':\n+                _check_count(where, 'enum values', len(definition.values),\n+                             spec.U32_MAX)\n+                if family_id == spec.CORE_FAMILY_ID:\n+                    maximum = ROOT_ENUM_VALUES_MAX.get(definition.name)\n+                    if maximum is not None:\n+                        _check_count(where, 'enum values',\n+                                     len(definition.values), maximum)\n+            # Enum values from one, zero being reserved; flag bits from zero.\n+            first = 1 if kind == 'enum' else 0\n+            values = tuple((name, first + index)\n+                           for index, name in enumerate(definition.values))\n+            self.definitions[definition.name] = Definition(\n+                definition.name, kind, family_id, values)\n+\n+    def _add_groups(self, family, family_id):\n+        _check_count(f'{family.path}: family {family.name}', 'attr groups',\n+                     len(family.groups), spec.U16_MAX)\n+        for group_id, group in enumerate(family.groups, start=1):\n+            where = f'{family.path}: attr group {group.name}'\n+            self._reject_redeclaration(where, self.groups, group.name,\n+                                       'attr group')\n+            self._reject_redeclaration(where, self.sets, group.name,\n+                                       'attr set')\n+            attrs = []\n+            names = set()\n+            _check_count(where, 'attrs', len(group.attrs), spec.U32_MAX)\n+            for local_id, decl in enumerate(group.attrs, start=1):\n+                attr_where = f'{family.path}: attr {group.name}.{decl.name}'\n+                if decl.name in names:\n+                    raise CtlvError(attr_where, 'duplicate attr')\n+                names.add(decl.name)\n+                self._check_reference(attr_where, decl)\n+                attrs.append(Attr(\n+                    group=group.name,\n+                    name=decl.name,\n+                    family_id=family_id,\n+                    group_id=group_id,\n+                    local_id=local_id,\n+                    attr_id=(family_id \u003c\u003c 48) | (group_id \u003c\u003c 32) | local_id,\n+                    decl=decl,\n+                ))\n+            effective = Group(group.name, family_id, group_id, tuple(attrs))\n+            self.groups[group.name] = effective\n+            for attr in attrs:\n+                self.attrs[attr.full_name] = attr\n+\n+    def _check_reference(self, where, decl):\n+        if decl.kind not in ('enum', 'flags'):\n+            return\n+        definition = self.definitions.get(decl.ref)\n+        if definition is None:\n+            raise CtlvError(where, f'unknown {decl.kind} \"{decl.ref}\"')\n+        if definition.kind != decl.kind:\n+            raise CtlvError(where, f'\"{decl.ref}\" is a {definition.kind} '\n+                                   f'definition, not {decl.kind}')\n+\n+    def _add_sets(self, family, family_id):\n+        set_id = 0\n+        for attr_set in family.sets:\n+            where = f'{family.path}: attr set {attr_set.name}'\n+            existing = self.sets.get(attr_set.name)\n+            if existing is not None:\n+                self._fill_stub(where, family, existing, attr_set)\n+                continue\n+            self._reject_redeclaration(where, self.groups, attr_set.name,\n+                                       'attr group')\n+            _check_count(where, 'new attr sets', set_id + 1,\n+                         spec.U32_MAX)\n+            set_id += 1\n+            self.set_paths[attr_set.name] = family.path\n+            self.sets[attr_set.name] = AttrSet(\n+                name=attr_set.name,\n+                family_id=family_id,\n+                set_id=set_id,\n+                stub=attr_set.stub,\n+                attrs=attr_set.attrs,\n+                optional_attrs=attr_set.optional_attrs,\n+            )\n+\n+    def _fill_stub(self, where, family, existing, filler):\n+        \"\"\"Replace an inherited empty stub with a descendant's members.\"\"\"\n+        filled_by = self.stub_fillers.get(existing.name)\n+        if filled_by is not None:\n+            raise CtlvError(where, f'stub was already filled by family '\n+                                   f'{filled_by}')\n+        if not existing.stub:\n+            raise CtlvError(where, 'attr set is already declared by an '\n+                                   'inherited family')\n+        if filler.stub:\n+            raise CtlvError(where, 'a stub cannot be redeclared; a further '\n+                                   'extension point needs a new name')\n+        self.stub_fillers[existing.name] = family.name\n+        self.set_paths[existing.name] = family.path\n+        # A fill completes an inherited set, so the IDs are the declarer's.\n+        self.sets[existing.name] = dataclasses.replace(\n+            existing, stub=False, attrs=filler.attrs,\n+            optional_attrs=filler.optional_attrs)\n+\n+    def _check_sets(self):\n+        \"\"\"Expand every set, so one that no op selects is still checked.\"\"\"\n+        for name, attr_set in self.sets.items():\n+            where = f'{self.set_paths[name]}: attr set {name}'\n+            # Seeding the stack makes a cycle read from the set expanded.\n+            _nodes, _stubs = self._expand_placements(\n+                spec.Placements(attr_set.attrs, attr_set.optional_attrs),\n+                where, (), 0, set_stack=(attr_set.name,),\n+                opened=(attr_set.name,))\n+\n+    def _reject_redeclaration(self, where, namespace, name, what):\n+        if name in namespace:\n+            raise CtlvError(where, f'{what} \"{name}\" is already declared')\n+\n+    # Ops\n+\n+    def _add_ops(self, family):\n+        family_id = self._family_id(family)\n+        _check_count(f'{family.path}: family {family.name}', 'ops',\n+                     len(family.ops), spec.U32_MAX)\n+        _check_count(f'{family.path}: family {family.name}', 'effective ops',\n+                     len(self.ops) + len(family.ops), spec.U32_MAX)\n+        for local_id, op in enumerate(family.ops, start=1):\n+            where = f'{family.path}: op {op.name}'\n+            if any(existing.name == op.name for existing in self.ops):\n+                raise CtlvError(where, f'op \"{op.name}\" is already declared')\n+            request = None\n+            if op.request is not None:\n+                request = self._tree(op.request, where + ' request')\n+            reply = None\n+            if op.reply is not None:\n+                reply = self._tree(op.reply, where + ' reply')\n+            self._check_context(where, op, request, reply)\n+            self.ops.append(Op(\n+                name=op.name,\n+                type=op.type,\n+                fd_access=op.fd_access,\n+                availability=op.availability,\n+                optional=op.optional,\n+                pre_post=op.pre_post,\n+                family_id=family_id,\n+                local_id=local_id,\n+                op_id=(family_id \u003c\u003c 48) | local_id,\n+                request=request,\n+                reply=reply,\n+                sizes=sizes.compute(where, op, request, reply),\n+            ))\n+\n+    def _tree(self, placements, where):\n+        children, stubs = self._expand_placements(placements, where, (), 0)\n+        root = _root(children, stubs)\n+        _check_tree_size(where, root)\n+        return root\n+\n+    def _expand_placements(self, placements, where, stack, depth,\n+                           set_stack=(), opened=()):\n+        \"\"\"Return the child nodes of one level and the stubs selected there.\"\"\"\n+        merged = {}\n+        expanded, stubs = self._expand(placements.attrs, False, where,\n+                                       set_stack)\n+        optional, more = self._expand(placements.optional_attrs, True, where,\n+                                      set_stack)\n+        expanded += optional\n+        stubs += more\n+        for attr, required, fill in expanded:\n+            entry = merged.get(attr.attr_id)\n+            if entry is None:\n+                merged[attr.attr_id] = [attr, required, fill]\n+            elif entry[2] != fill and (entry[2] is not None or\n+                                       fill is not None):\n+                raise CtlvError(\n+                    where, f'attr {attr.full_name} is selected more than '\n+                           'once in one composed nest')\n+            elif required:\n+                # A required selection at this level beats an optional one.\n+                entry[1] = True\n+        nodes = tuple(self._node(attr, required, where, stack, depth, opened)\n+                      for attr, required, _fill in merged.values())\n+        return nodes, _merge_stubs(stubs)\n+\n+    def _expand(self, selectors, force_optional, where, stack):\n+        expanded = []\n+        stubs = ()\n+        for selector in selectors:\n+            attrs, found = self._expand_one(selector, force_optional, where,\n+                                            stack)\n+            expanded += attrs\n+            stubs += found\n+        return expanded, stubs\n+\n+    def _expand_one(self, selector, force_optional, where, stack):\n+        if '.' in selector:\n+            attr = self.attrs.get(selector)\n+            if attr is None:\n+                raise CtlvError(where, f'unknown attr \"{selector}\"')\n+            return [(attr, not force_optional, None)], ()\n+        group = self.groups.get(selector)\n+        if group is not None:\n+            return [(attr, not force_optional, None)\n+                    for attr in group.attrs], ()\n+        attr_set = self.sets.get(selector)\n+        if attr_set is None:\n+            raise CtlvError(where, f'unknown selector \"{selector}\"')\n+        if attr_set.stub:\n+            # Nothing to expand until a descendant fills it.\n+            return [], (Stub(attr_set.name, attr_set.family_id,\n+                             attr_set.set_id, force_optional),)\n+        if selector in stack:\n+            raise CtlvError(where, 'attr set cycle: ' +\n+                                   ' -\u003e '.join(stack + (selector,)))\n+        stack += (selector,)\n+        # Under an optional selection every member becomes optional.\n+        expanded, stubs = self._expand(attr_set.attrs, force_optional, where,\n+                                       stack)\n+        optional, more = self._expand(attr_set.optional_attrs, True, where,\n+                                      stack)\n+        expanded += optional\n+        if selector in self.stub_fillers:\n+            expanded = [(attr, required, selector)\n+                        for attr, required, _fill in expanded]\n+        return expanded, stubs + more\n+\n+    def _node(self, attr, required, where, stack, depth, opened=()):\n+        decl = attr.decl\n+        if decl.kind != 'nested':\n+            return Node(attr, required, decl.max_occurrences, (), ())\n+        holds = self._nested_set(where, attr)\n+        if decl.recursive and holds in opened:\n+            # Open above, so one level further down rather than a new one.\n+            return Node(attr, required, decl.max_occurrences, (), (),\n+                        reenters=holds)\n+        if attr.attr_id in stack:\n+            names = [self._attr_by_id(i).full_name for i in stack]\n+            raise CtlvError(where, 'nesting cycle: ' +\n+                                   ' -\u003e '.join(names + [attr.full_name]))\n+        if depth + 1 \u003e sizes.MAX_DECLARED_NEST_DEPTH:\n+            raise CtlvError(where, f'{attr.full_name} nests deeper than the '\n+                                   f'{sizes.MAX_DECLARED_NEST_DEPTH} level '\n+                                   'limit')\n+        children, stubs = self._expand_placements(\n+            spec.Placements(decl.attrs, decl.optional_attrs), where,\n+            stack + (attr.attr_id,), depth + 1,\n+            opened=opened + ((holds,) if holds else ()))\n+        node = Node(attr, required, decl.max_occurrences,\n+                    tuple(child for child in children if child.required),\n+                    tuple(child for child in children if not child.required),\n+                    stubs, expands=holds)\n+        if decl.recursive and not _reenters(node, holds):\n+            raise CtlvError(where, f'{attr.full_name} is recursive, but attr '\n+                                   f'set \"{holds}\" never selects it again')\n+        return node\n+\n+    def _nested_set(self, where, attr):\n+        \"\"\"The one attr set a nest holds, when that is all it holds.\n+\n+        Only such a nest can be re-entered, a re-entry meaning the members\n+        open above.\n+        \"\"\"\n+        decl = attr.decl\n+        if not decl.recursive:\n+            if decl.optional_attrs or len(decl.attrs) != 1:\n+                return None\n+            return decl.attrs[0] if decl.attrs[0] in self.sets else None\n+        target = decl.attrs[0]\n+        if target in self.groups:\n+            raise CtlvError(where, f'{attr.full_name} is recursive, so it '\n+                                   f'nests an attr set, and \"{target}\" is an '\n+                                   'attr group')\n+        if target not in self.sets:\n+            raise CtlvError(where, f'unknown selector \"{target}\"')\n+        return target\n+\n+    def _attr_by_id(self, attr_id):\n+        for attr in self.attrs.values():\n+            if attr.attr_id == attr_id:\n+                return attr\n+        raise AssertionError(f'no attr with ID {attr_id:#x}')\n+\n+    def _check_context(self, where, op, request, reply):\n+        if request is not None:\n+            self._check_subtree(where, request, 'request')\n+        if reply is None:\n+            return\n+        if op.type == 'query':\n+            self._check_subtree(where, reply, 'query reply')\n+            self._check_reentry(where, reply)\n+        elif op.type == 'event':\n+            self._check_subtree(where, reply, 'event')\n+        else:\n+            self._check_subtree(where, reply, 'action reply')\n+\n+    def _check_reentry(self, where, root):\n+        \"\"\"A repeating level cannot also be widened by a descendant.\"\"\"\n+        if not _reenters_anywhere(root) or not _stubs_anywhere(root):\n+            return\n+        raise CtlvError(f'{where} query reply',\n+                        're-enters a level and selects an extension point, '\n+                        'and a descendant cannot widen a level that repeats')\n+\n+    def _check_subtree(self, where, node, context):\n+        if node.attr is not None:\n+            name = node.attr.full_name\n+            if (node.max_occurrences == spec.UNLIMITED and\n+                    context != 'query reply'):\n+                raise CtlvError(f'{where} {context}',\n+                                f'{name} has unlimited occurrences, which '\n+                                'only a query reply may contain')\n+            if node.reenters is not None and context != 'query reply':\n+                raise CtlvError(f'{where} {context}',\n+                                f'{name} re-enters \"{node.reenters}\", so it '\n+                                'has no maximum length, which only a query '\n+                                'reply may contain')\n+            if node.attr.decl.kind == 'blob' and context != 'request':\n+                raise CtlvError(f'{where} {context}',\n+                                f'{name} is a blob attr, which only a '\n+                                'request may contain')\n+        for child in node.children():\n+            self._check_subtree(where, child, context)\n+\n+\n+def _reenters(node, name):\n+    \"\"\"Whether anything below node re-enters name.\"\"\"\n+    return any(child.reenters == name or _reenters(child, name)\n+               for child in node.children())\n+\n+\n+def _reenters_anywhere(node):\n+    return any(child.reenters is not None or _reenters_anywhere(child)\n+               for child in node.children())\n+\n+\n+def _stubs_anywhere(node):\n+    return bool(node.stubs) or any(_stubs_anywhere(child)\n+                                   for child in node.children())\n+\n+\n+def _composed_members(fills, node, force_optional=False):\n+    members = [(child, force_optional)\n+               for child in node.required_children]\n+    members += [(child, True) for child in node.optional_children]\n+    for stub in node.stubs:\n+        fill = fills.get((stub.family_id, stub.set_id))\n+        if fill is not None:\n+            members += _composed_members(\n+                fills, fill.root, force_optional or stub.optional)\n+    return members\n+\n+\n+def _check_composed(family):\n+    fills = {(fill.family_id, fill.set_id): fill\n+             for fill in family.chain_fills}\n+\n+    def walk(where, node):\n+        members = _composed_members(fills, node)\n+        required = sum(not optional for _child, optional in members)\n+        optional = len(members) - required\n+        seen = set()\n+\n+        _check_count(where, 'composed required attrs', required,\n+                     spec.U32_MAX)\n+        _check_count(where, 'composed optional attrs', optional,\n+                     spec.U32_MAX)\n+        count = 1\n+        for child, _optional in members:\n+            if child.attr.attr_id in seen:\n+                raise CtlvError(\n+                    where, f'attr {child.attr.full_name} is selected more '\n+                           'than once in one composed nest')\n+            seen.add(child.attr.attr_id)\n+            count += walk(where, child)\n+        return count\n+\n+    for op in family.ops:\n+        total = 0\n+        for which, root in (('request', op.request), ('reply', op.reply)):\n+            if root is None:\n+                continue\n+            where = f'{family.path}: op {op.name} {which}'\n+            count = walk(where, root)\n+            _check_count(where, 'composed schema nodes', count,\n+                         spec.U32_MAX)\n+            total += count\n+        _check_count(f'{family.path}: op {op.name}',\n+                     'composed request and reply nodes', total,\n+                     spec.U32_MAX)\n+\n+\n+def _node_count(node):\n+    return 1 + sum(_node_count(child) for child in node.children())\n+\n+\n+def _stub_count(node):\n+    return len(node.stubs) + sum(_stub_count(child)\n+                                 for child in node.children())\n+\n+\n+def _check_tree_size(where, root):\n+    _check_count(where, 'schema nodes', _node_count(root), spec.U32_MAX)\n+    _check_count(where, 'schema stubs', _stub_count(root), spec.U32_MAX)\n+\n+\n+def _root(children, stubs=()):\n+    return Node(None, True, 1,\n+                tuple(node for node in children if node.required),\n+                tuple(node for node in children if not node.required),\n+                stubs)\n+\n+\n+def _merge_stubs(stubs):\n+    \"\"\"One reference per stub selected at a level, required winning.\"\"\"\n+    merged = {}\n+    for stub in stubs:\n+        previous = merged.get(stub.name)\n+        if previous is None or not stub.optional:\n+            merged[stub.name] = stub\n+    return tuple(merged.values())\ndiff --git a/tools/ctlv/ctlvgen/lib/sizes.py b/tools/ctlv/ctlvgen/lib/sizes.py\nnew file mode 100644\nindex 0000000000000..864e3b6873e7a\n--- /dev/null\n+++ b/tools/ctlv/ctlvgen/lib/sizes.py\n@@ -0,0 +1,238 @@\n+# SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause\n+\"\"\"Length arithmetic over an expanded op tree.\n+\n+These numbers decide whether an op can run at all, so they are kept apart from\n+the rest of resolution and tested against independently calculated lengths.\n+The constants mirror include/uapi/linux/ctlv.h, and a test checks that.\n+\"\"\"\n+\n+from __future__ import annotations\n+\n+import dataclasses\n+\n+from . import spec\n+from .errors import CtlvError\n+\n+ALIGNTO = 8\n+ATTR_HDR_LEN = 16\n+EVENT_HDR_LEN = 24\n+\n+MAX_INLINE_MESSAGE_LEN = 0x100000\n+MAX_ERROR_LEN = 0x4000\n+MAX_NEST_DEPTH = 32\n+DEFAULT_QUERY_REPLY_LEN = 0x10000\n+MAX_EVENT_QUEUE_LEN = 0x1000000\n+\n+# One level short of what the transport carries: op-schema-get describes a\n+# message, and a description nests one level deeper than what it describes.\n+MAX_DECLARED_NEST_DEPTH = MAX_NEST_DEPTH - 1\n+\n+# Every integer, enum and flags payload is 64-bit.\n+SCALAR_PAYLOAD_LEN = 8\n+\n+# A bool payload is one byte, padded to eight only as a placement.\n+BOOL_PAYLOAD_LEN = 1\n+\n+# How many core scalar descriptor attrs each blob backing carries. A test\n+# checks these against the blob group of the core family.\n+BLOB_DESCRIPTOR_ATTRS = {\n+    'va': 3,\n+}\n+\n+# Attr sets of the root family that are message roots in their own right, each\n+# with the transport header's limit and the name the header gives it.\n+CORE_MESSAGES = {\n+    'error-info': ('CTLV_MAX_ERROR_LEN', MAX_ERROR_LEN),\n+}\n+\n+\n+@dataclasses.dataclass(frozen=True)\n+class OpSizes:\n+    \"\"\"Generated lengths of one op. Zero means \"does not apply\".\"\"\"\n+\n+    request_max_len: int\n+    action_reply_max_len: int\n+    query_reply_min_len: int\n+    query_reply_suggested_len: int\n+    event_record_max_len: int\n+\n+\n+def align(length):\n+    return (length + ALIGNTO - 1) \u0026 ~(ALIGNTO - 1)\n+\n+\n+def attr_max_len(node):\n+    \"\"\"Maximum length of one occurrence of node, excluding its own padding.\"\"\"\n+    return ATTR_HDR_LEN + _payload_max_len(node)\n+\n+\n+def root_max_len(root):\n+    \"\"\"Maximum length of a complete message root.\"\"\"\n+    return ATTR_HDR_LEN + _payload_max_len(root)\n+\n+\n+def min_reply_len(root):\n+    \"\"\"Buffer length needed for the largest indivisible leaf and its path.\n+\n+    A leaf below a re-entered level sits as deep as the transport allows.\n+    \"\"\"\n+    if _reenters(root):\n+        return (MAX_NEST_DEPTH + 1) * ATTR_HDR_LEN + _largest_leaf(root)\n+    return _min_walk(root, 0)\n+\n+\n+def compute(where, op, request, reply):\n+    \"\"\"Return the generated lengths of one op.\"\"\"\n+    request_max_len = 0\n+    if request is not None:\n+        request_max_len = root_max_len(request)\n+        _check_inline(where, 'request', request_max_len)\n+\n+    action_reply_max_len = 0\n+    query_reply_min_len = 0\n+    query_reply_suggested_len = 0\n+    event_record_max_len = 0\n+\n+    if op.type == 'action' and reply is not None:\n+        action_reply_max_len = root_max_len(reply)\n+        _check_inline(where, 'action reply', action_reply_max_len)\n+    elif op.type == 'query':\n+        query_reply_min_len = min_reply_len(reply)\n+        _check_inline(where, 'largest query reply leaf and its path',\n+                      query_reply_min_len)\n+        query_reply_suggested_len = _suggested_len(\n+            where, op.suggested_reply_length, query_reply_min_len)\n+    elif op.type == 'event':\n+        payload_max_len = root_max_len(reply)\n+        _check_inline(where, 'event payload', payload_max_len)\n+        event_record_max_len = EVENT_HDR_LEN + align(payload_max_len)\n+\n+    return OpSizes(request_max_len=request_max_len,\n+                   action_reply_max_len=action_reply_max_len,\n+                   query_reply_min_len=query_reply_min_len,\n+                   query_reply_suggested_len=query_reply_suggested_len,\n+                   event_record_max_len=event_record_max_len)\n+\n+\n+def composed(where, op, request, reply):\n+    \"\"\"Return the lengths one op needs for one family.\n+\n+    compute()'s numbers over the composed tree, fills spliced in. A suggestion\n+    is raised here rather than refused.\n+    \"\"\"\n+    sizes = OpSizes(request_max_len=root_max_len(request) if request else 0,\n+                    action_reply_max_len=0, query_reply_min_len=0,\n+                    query_reply_suggested_len=0, event_record_max_len=0)\n+    _check_inline(where, 'request', sizes.request_max_len)\n+\n+    if op.type == 'action' and reply is not None:\n+        sizes = dataclasses.replace(sizes,\n+                                    action_reply_max_len=root_max_len(reply))\n+        _check_inline(where, 'action reply', sizes.action_reply_max_len)\n+    elif op.type == 'query':\n+        minimum = min_reply_len(reply)\n+        _check_inline(where, 'largest query reply leaf and its path', minimum)\n+        sizes = dataclasses.replace(\n+            sizes, query_reply_min_len=minimum,\n+            query_reply_suggested_len=max(op.sizes.query_reply_suggested_len,\n+                                          minimum))\n+    elif op.type == 'event':\n+        payload_max_len = root_max_len(reply)\n+        _check_inline(where, 'event payload', payload_max_len)\n+        record = EVENT_HDR_LEN + align(payload_max_len)\n+        if record \u003e MAX_EVENT_QUEUE_LEN:\n+            raise CtlvError(where, f'event record needs {record} bytes, more '\n+                                   f'than the {MAX_EVENT_QUEUE_LEN} byte '\n+                                   'event queue limit')\n+        sizes = dataclasses.replace(sizes, event_record_max_len=record)\n+    return sizes\n+\n+\n+def message_max_len(where, name, root):\n+    \"\"\"Return the maximum length of one core message, against its limit.\"\"\"\n+    limit_name, limit = CORE_MESSAGES[name]\n+    length = root_max_len(root)\n+    if length \u003e limit:\n+        raise CtlvError(where, f'needs {length} bytes, more than the {limit} '\n+                               f'of {limit_name}')\n+    return length\n+\n+\n+def _payload_max_len(node):\n+    if node.is_root:\n+        return _children_max_len(node)\n+\n+    decl = node.attr.decl\n+    if decl.kind in ('uint', 'sint', 'enum', 'flags'):\n+        return SCALAR_PAYLOAD_LEN\n+    if decl.kind == 'bool':\n+        return BOOL_PAYLOAD_LEN\n+    if decl.kind == 'string':\n+        # One terminating NUL, which max-length excludes.\n+        return decl.max_length + 1\n+    if decl.kind == 'binary':\n+        return decl.max_length\n+    if decl.kind == 'blob':\n+        widest = max(BLOB_DESCRIPTOR_ATTRS[backing]\n+                     for backing in decl.blob.backings)\n+        return widest * align(ATTR_HDR_LEN + SCALAR_PAYLOAD_LEN)\n+    return _children_max_len(node)\n+\n+\n+def _children_max_len(node):\n+    total = 0\n+    for child in node.children():\n+        if child.max_occurrences == spec.UNLIMITED:\n+            raise AssertionError(\n+                f'{child.attr.full_name} has unlimited occurrences, so it has '\n+                'no maximum length')\n+        if child.reenters is not None:\n+            raise AssertionError(\n+                f'{child.attr.full_name} re-enters {child.reenters}, so it '\n+                'has no maximum length')\n+        total += child.max_occurrences * align(attr_max_len(child))\n+    return total\n+\n+\n+def _min_walk(node, ancestors_len):\n+    children = node.children()\n+    if children:\n+        return max(_min_walk(child, ancestors_len + ATTR_HDR_LEN)\n+                   for child in children)\n+    if node.is_root:\n+        return ancestors_len + ATTR_HDR_LEN\n+    return ancestors_len + align(attr_max_len(node))\n+\n+\n+def _reenters(node):\n+    return any(child.reenters is not None or _reenters(child)\n+               for child in node.children())\n+\n+\n+def _largest_leaf(node):\n+    \"\"\"The longest placement of the tree that a fragment cannot split.\"\"\"\n+    lengths = [align(attr_max_len(child))\n+               for child in node.children()\n+               if child.attr.decl.kind != 'nested']\n+    lengths += [_largest_leaf(child) for child in node.children()]\n+    return max(lengths, default=0)\n+\n+\n+def _check_inline(where, what, length):\n+    if length \u003e MAX_INLINE_MESSAGE_LEN:\n+        raise CtlvError(where, f'{what} needs {length} bytes, more than the '\n+                               f'{MAX_INLINE_MESSAGE_LEN} byte inline '\n+                               'message limit')\n+\n+\n+def _suggested_len(where, declared, minimum):\n+    if declared is None:\n+        return max(DEFAULT_QUERY_REPLY_LEN, minimum)\n+    if declared \u003c minimum:\n+        raise CtlvError(where, f'suggested-reply-length {declared} is below '\n+                               f'the computed minimum of {minimum}')\n+    if declared \u003e MAX_INLINE_MESSAGE_LEN:\n+        raise CtlvError(where, f'suggested-reply-length {declared} exceeds '\n+                               f'the {MAX_INLINE_MESSAGE_LEN} byte inline '\n+                               'message limit')\n+    return declared\ndiff --git a/tools/ctlv/ctlvgen/lib/spec.py b/tools/ctlv/ctlvgen/lib/spec.py\nnew file mode 100644\nindex 0000000000000..8942664d88a73\n--- /dev/null\n+++ b/tools/ctlv/ctlvgen/lib/spec.py\n@@ -0,0 +1,583 @@\n+# SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause\n+\"\"\"The as-written form of a CTLV family specification.\n+\n+The strict YAML subset, the meta-schema, and every rule that one declaration\n+decides on its own. Comparing declarations and walking a chain are\n+semantics.py's. Omitted values are normalized here, once.\n+\"\"\"\n+\n+from __future__ import annotations\n+\n+import dataclasses\n+import pathlib\n+import re\n+\n+import jsonschema\n+\n+from . import yamlload\n+from .errors import CtlvError\n+\n+# A generated file carries the license of its specification's first line.\n+LICENSE = re.compile(r'#\\s*SPDX-License-Identifier:\\s*(\\S.*?)\\s*$')\n+\n+# The registry is indexed by family ID, so the root family is its first entry.\n+CORE_FAMILY_NAME = 'ctlv'\n+CORE_FAMILY_ID = 0\n+\n+MAX_FAMILY_NAME_LEN = 63\n+U8_MAX = (1 \u003c\u003c 8) - 1\n+U16_MAX = (1 \u003c\u003c 16) - 1\n+U32_MAX = (1 \u003c\u003c 32) - 1\n+MAX_FAMILY_ID = U16_MAX\n+\n+# Zero means unlimited, as the introspection wire form has it.\n+UNLIMITED = 0\n+\n+U64_MAX = (1 \u003c\u003c 64) - 1\n+S64_MIN = -(1 \u003c\u003c 63)\n+S64_MAX = (1 \u003c\u003c 63) - 1\n+S8_MIN = -(1 \u003c\u003c 7)\n+S8_MAX = (1 \u003c\u003c 7) - 1\n+\n+PRIMARY_KEYS = ('type', 'enum', 'flags', 'attrs', 'blob')\n+\n+INTEGER_KINDS = ('uint', 'sint')\n+SCALAR_KINDS = ('uint', 'sint', 'bool', 'string', 'binary', 'enum', 'flags')\n+\n+FD_ACCESSES = ('read', 'read-write')\n+DEFAULT_FD_ACCESS = 'read-write'\n+\n+# Every op has one of these, and only an action or a query may be dynamic.\n+AVAILABILITIES = ('fixed', 'dynamic')\n+DEFAULT_AVAILABILITY = 'fixed'\n+\n+# Keys each primary form may add, beyond its own, name and max-occurrences.\n+_ACCESSORY_KEYS = {\n+    'uint': {'min', 'max', 'unit', 'scale'},\n+    'sint': {'min', 'max', 'unit', 'scale'},\n+    'bool': set(),\n+    'string': {'min-length', 'max-length'},\n+    'binary': {'length', 'min-length', 'max-length'},\n+    'enum': set(),\n+    'flags': set(),\n+    'nested': {'optional-attrs', 'recursive'},\n+    'blob': set(),\n+}\n+_COMMON_KEYS = {'name', 'max-occurrences'}\n+\n+\n+@dataclasses.dataclass(frozen=True)\n+class ValueList:\n+    \"\"\"An enum or a flags definition.\"\"\"\n+\n+    name: str\n+    values: tuple\n+\n+\n+@dataclasses.dataclass(frozen=True)\n+class BlobDecl:\n+    \"\"\"The blob properties of one blob attr declaration.\"\"\"\n+\n+    direction: str\n+    backings: tuple\n+    max_length: int\n+    alignment: int\n+\n+\n+@dataclasses.dataclass(frozen=True)\n+class AttrDecl:\n+    \"\"\"One attr declaration inside an attr group.\n+\n+    kind is the resolved primary form, and a field that does not apply stays\n+    None. recursive marks a nest whose attr set may select this attr again.\n+    \"\"\"\n+\n+    name: str\n+    kind: str\n+    ref: str = None\n+    attrs: tuple = ()\n+    optional_attrs: tuple = ()\n+    recursive: bool = False\n+    blob: BlobDecl = None\n+    min: int = None\n+    max: int = None\n+    min_length: int = None\n+    max_length: int = None\n+    unit: str = None\n+    scale: int = None\n+    max_occurrences: int = 1\n+\n+\n+@dataclasses.dataclass(frozen=True)\n+class AttrGroupSpec:\n+    name: str\n+    attrs: tuple\n+\n+\n+@dataclasses.dataclass(frozen=True)\n+class AttrSetSpec:\n+    name: str\n+    stub: bool\n+    attrs: tuple\n+    optional_attrs: tuple\n+\n+\n+@dataclasses.dataclass(frozen=True)\n+class Placements:\n+    \"\"\"The required and optional selectors declared at one level.\"\"\"\n+\n+    attrs: tuple = ()\n+    optional_attrs: tuple = ()\n+\n+\n+@dataclasses.dataclass(frozen=True)\n+class OpSpec:\n+    name: str\n+    type: str\n+    request: Placements\n+    reply: Placements = None\n+    fd_access: str = DEFAULT_FD_ACCESS\n+    availability: str = DEFAULT_AVAILABILITY\n+    optional: bool = False\n+    pre_post: bool = False\n+    suggested_reply_length: int = None\n+\n+\n+@dataclasses.dataclass(frozen=True)\n+class FamilySpec:\n+    \"\"\"One specification file, syntax-checked and normalized.\"\"\"\n+\n+    path: str\n+    name: str\n+    license: str\n+    inherits: str\n+    enums: tuple\n+    flags: tuple\n+    groups: tuple\n+    sets: tuple\n+    ops: tuple\n+    pre_init: bool = False\n+    post_init: bool = False\n+    pre_fini: bool = False\n+\n+\n+@dataclasses.dataclass(frozen=True)\n+class RegistryEntry:\n+    name: str\n+    deprecated: bool\n+\n+\n+@dataclasses.dataclass(frozen=True)\n+class Registry:\n+    \"\"\"The append-only family registry, indexed by family ID.\"\"\"\n+\n+    path: str\n+    entries: tuple\n+\n+    @property\n+    def license(self):\n+        return _license(self.path)\n+\n+    def family_id(self, name):\n+        \"\"\"Return the registered family ID of name, or None if unregistered.\"\"\"\n+        for family_id, entry in enumerate(self.entries):\n+            if entry.name == name:\n+                return family_id\n+        return None\n+\n+\n+class Paths:\n+    \"\"\"Where the specs, the registry and the meta-schemas are.\"\"\"\n+\n+    def __init__(self, spec, schema=None, registry=None, abi=None):\n+        self.spec = pathlib.Path(spec)\n+        self.spec_dir = self.spec.parent\n+        self.doc_dir = self.spec_dir.parent\n+        self.schema = pathlib.Path(schema or self.doc_dir / 'ctlv-schema.yaml')\n+        self.registry = pathlib.Path(registry or\n+                                     self.doc_dir / 'families.yaml')\n+        # The two meta-schemas ship together, so overriding one locates both.\n+        self.registry_schema = (self.schema.parent /\n+                                'ctlv-registry-schema.yaml')\n+        self.abi_dir = pathlib.Path(abi or self.doc_dir / 'abi')\n+        self.registry_abi = self.abi_dir / 'families.registry.yaml'\n+        self.generated = self.doc_dir / 'generated-files.yaml'\n+        self.generated_schema = self.doc_dir / 'generated-files-schema.yaml'\n+        self.kernel_dir = self.schema.parent.parent.parent\n+\n+    def sibling_spec(self, name):\n+        \"\"\"Return the path of another family's specification.\n+\n+        The one root family lives where the meta-schema does, so a corpus of\n+        fixtures inherits it rather than a copy.\n+        \"\"\"\n+        if name == CORE_FAMILY_NAME:\n+            return self.schema.parent / 'specs' / f'{name}.yaml'\n+        return self.spec_dir / f'{name}.yaml'\n+\n+    def abi(self, name):\n+        \"\"\"Return the path of one family's checked-in ABI snapshot.\"\"\"\n+        return self.abi_dir / f'{name}.yaml'\n+\n+\n+def load_registry(paths, path=None):\n+    \"\"\"Load and check the family registry.\"\"\"\n+    path = pathlib.Path(path or paths.registry)\n+    data = yamlload.load(path)\n+    _validate_syntax(path, data, paths.registry_schema)\n+\n+    entries = []\n+    seen = set()\n+    for item in data['families']:\n+        if isinstance(item, dict):\n+            entry = RegistryEntry(item['name'], item['deprecated'])\n+        else:\n+            entry = RegistryEntry(item, False)\n+        _family_name(f'{path}: family {entry.name}', entry.name)\n+        if entry.name in seen:\n+            raise CtlvError(f'{path}: {entry.name}', 'duplicate family')\n+        seen.add(entry.name)\n+        entries.append(entry)\n+\n+    core = entries[CORE_FAMILY_ID]\n+    if core.name != CORE_FAMILY_NAME:\n+        raise CtlvError(f'{path}: {core.name}',\n+                        f'family ID {CORE_FAMILY_ID} belongs to '\n+                        f'{CORE_FAMILY_NAME}, so it must be the first entry')\n+    if core.deprecated:\n+        raise CtlvError(f'{path}: {core.name}',\n+                        'the core family cannot be deprecated')\n+    if len(entries) - 1 \u003e MAX_FAMILY_ID:\n+        raise CtlvError(str(path),\n+                        f'{len(entries)} entries need a family ID past the '\n+                        f'{MAX_FAMILY_ID} maximum')\n+    return Registry(str(path), tuple(entries))\n+\n+\n+def load(path, schema=None):\n+    \"\"\"Load, syntax-check and normalize one family specification.\"\"\"\n+    path = pathlib.Path(path)\n+    data = yamlload.load(path)\n+    _validate_syntax(path, data, schema)\n+\n+    family = data['family']\n+    name = _family_name(f'{path}: family {family[\"name\"]}', family['name'])\n+    inherits = family.get('inherits')\n+    if inherits is not None:\n+        inherits = _family_name(f'{path}: family {name} parent', inherits)\n+    return FamilySpec(\n+        path=str(path),\n+        name=name,\n+        license=_license(path),\n+        inherits=inherits,\n+        enums=_value_lists(path, data.get('enums', []), 'enum'),\n+        flags=_value_lists(path, data.get('flags', []), 'flags'),\n+        groups=_groups(path, data.get('attr-groups', [])),\n+        sets=_sets(path, data.get('attr-sets', [])),\n+        ops=_ops(path, data.get('ops', [])),\n+        pre_init=family.get('pre-init', False),\n+        post_init=family.get('post-init', False),\n+        pre_fini=family.get('pre-fini', False),\n+    )\n+\n+\n+def _license(path):\n+    \"\"\"Return the SPDX identifier the specification's first line carries.\"\"\"\n+    with open(path, 'r', encoding='utf-8') as stream:\n+        found = LICENSE.match(stream.readline())\n+    if found is None:\n+        raise CtlvError(str(path),\n+                        'the first line must be an SPDX-License-Identifier '\n+                        'comment, which every generated file inherits')\n+    return found.group(1)\n+\n+\n+def _validate_syntax(path, data, schema_path):\n+    schema = yamlload.load(schema_path)\n+    validator = jsonschema.Draft7Validator(schema)\n+    error = jsonschema.exceptions.best_match(validator.iter_errors(data))\n+    if error is None:\n+        return\n+    where = f'{path}: {error.json_path}' if error.absolute_path else str(path)\n+    raise CtlvError(where, error.message)\n+\n+\n+def _family_name(where, name):\n+    if len(name) \u003e MAX_FAMILY_NAME_LEN:\n+        raise CtlvError(where, f'name is {len(name)} characters, more than '\n+                               f'the {MAX_FAMILY_NAME_LEN} maximum')\n+    return name\n+\n+\n+def _value_lists(path, raw_lists, what):\n+    lists = []\n+    for raw in raw_lists:\n+        name = raw['name']\n+        where = f'{path}: {what} {name}'\n+        values = []\n+        seen = set()\n+        for raw_value in raw['values']:\n+            value = raw_value\n+            if value in seen:\n+                raise CtlvError(where, f'duplicate value \"{value}\"')\n+            seen.add(value)\n+            values.append(value)\n+        lists.append(ValueList(name, tuple(values)))\n+    return tuple(lists)\n+\n+\n+def _groups(path, raw_groups):\n+    groups = []\n+    for raw in raw_groups:\n+        name = raw['name']\n+        attrs = tuple(_attr(f'{path}: attr {name}.{a[\"name\"]}', a)\n+                      for a in raw['attrs'])\n+        groups.append(AttrGroupSpec(name, attrs))\n+    return tuple(groups)\n+\n+\n+def _attr(where, raw):\n+    primary = _primary_key(where, raw)\n+    kind = _kind(primary, raw)\n+    _reject_unusable_keys(where, raw, primary, kind)\n+\n+    attr = {\n+        'name': raw['name'],\n+        'kind': kind,\n+        'max_occurrences': _max_occurrences(where, raw),\n+    }\n+    if kind in INTEGER_KINDS:\n+        attr.update(_integer_bounds(where, raw, kind))\n+    elif kind == 'string':\n+        attr.update(_string_lengths(where, raw))\n+    elif kind == 'binary':\n+        attr.update(_binary_lengths(where, raw))\n+    elif kind in ('enum', 'flags'):\n+        attr['ref'] = raw[kind]\n+    elif kind == 'nested':\n+        attr['attrs'] = _selectors(raw['attrs'])\n+        attr['optional_attrs'] = _selectors(raw.get('optional-attrs'))\n+        attr['recursive'] = raw.get('recursive', False)\n+        if attr['recursive']:\n+            _check_recursive(where, attr)\n+    elif kind == 'blob':\n+        attr['blob'] = _blob(where, raw['blob'])\n+    # A bool has nothing to normalize.\n+    return AttrDecl(**attr)\n+\n+\n+def _check_recursive(where, attr):\n+    \"\"\"A recursive nest is one named set, which is what it re-enters.\"\"\"\n+    if attr['optional_attrs']:\n+        raise CtlvError(where, 'a recursive attr cannot declare '\n+                               'optional-attrs; the attr set it names says '\n+                               'which of its own members are optional')\n+    if len(attr['attrs']) != 1:\n+        raise CtlvError(where, 'a recursive attr nests exactly one attr set')\n+    if '.' in attr['attrs'][0]:\n+        raise CtlvError(where, f'\"{attr[\"attrs\"][0]}\" is one attr, and a '\n+                               'recursive attr nests an attr set')\n+\n+\n+def _primary_key(where, raw):\n+    present = [key for key in PRIMARY_KEYS if key in raw]\n+    if not present:\n+        raise CtlvError(where, 'no primary declaration; expected one of '\n+                               'type, enum, flags, attrs or blob')\n+    if len(present) \u003e 1:\n+        raise CtlvError(where, 'conflicting primary declarations: ' +\n+                               ', '.join(present))\n+    return present[0]\n+\n+\n+def _kind(primary, raw):\n+    if primary == 'type':\n+        return raw['type']\n+    if primary == 'attrs':\n+        return 'nested'\n+    return primary\n+\n+\n+def _reject_unusable_keys(where, raw, primary, kind):\n+    allowed = _COMMON_KEYS | {primary} | _ACCESSORY_KEYS[kind]\n+    unusable = sorted(set(raw) - allowed)\n+    if unusable:\n+        raise CtlvError(where, f'a {kind} attr cannot declare ' +\n+                               ', '.join(unusable))\n+\n+\n+def _max_occurrences(where, raw):\n+    value = raw.get('max-occurrences', 1)\n+    if value == 'unlimited':\n+        return UNLIMITED\n+    if value \u003c 1 or value \u003e U32_MAX:\n+        raise CtlvError(where, f'max-occurrences {value} is outside the '\n+                               'u32 range')\n+    return value\n+\n+\n+def _integer_bounds(where, raw, kind):\n+    low, high = (0, U64_MAX) if kind == 'uint' else (S64_MIN, S64_MAX)\n+    minimum = raw.get('min', low)\n+    maximum = raw.get('max', high)\n+    if minimum \u003c low or minimum \u003e high:\n+        raise CtlvError(where, f'min {minimum} is outside the {kind} range')\n+    if maximum \u003c low or maximum \u003e high:\n+        raise CtlvError(where, f'max {maximum} is outside the {kind} range')\n+    if minimum \u003e maximum:\n+        raise CtlvError(where, f'min {minimum} is greater than max {maximum}')\n+    if 'scale' in raw and 'unit' not in raw:\n+        raise CtlvError(where, 'scale requires unit')\n+    scale = raw.get('scale', 0) if 'unit' in raw else None\n+    if scale is not None and (scale \u003c S8_MIN or scale \u003e S8_MAX):\n+        raise CtlvError(where, f'scale {scale} is outside the s8 range')\n+    return {\n+        'min': minimum,\n+        'max': maximum,\n+        'unit': raw.get('unit'),\n+        'scale': scale,\n+    }\n+\n+\n+def _u32_value(where, what, value):\n+    if value \u003c 0 or value \u003e U32_MAX:\n+        raise CtlvError(where, f'{what} {value} is outside the u32 range')\n+    return value\n+\n+\n+def _string_lengths(where, raw):\n+    if 'max-length' not in raw:\n+        raise CtlvError(where, 'a string attr requires max-length')\n+    minimum = _u32_value(where, 'min-length', raw.get('min-length', 0))\n+    maximum = _u32_value(where, 'max-length', raw['max-length'])\n+    if minimum \u003e maximum:\n+        raise CtlvError(where, f'min-length {minimum} is greater than '\n+                               f'max-length {maximum}')\n+    return {'min_length': minimum, 'max_length': maximum}\n+\n+\n+def _binary_lengths(where, raw):\n+    if 'length' in raw:\n+        if 'min-length' in raw or 'max-length' in raw:\n+            raise CtlvError(where, 'length cannot be combined with '\n+                                   'min-length or max-length')\n+        length = _u32_value(where, 'length', raw['length'])\n+        return {'min_length': length, 'max_length': length}\n+    if 'max-length' not in raw:\n+        raise CtlvError(where, 'a binary attr requires length or max-length')\n+    minimum = _u32_value(where, 'min-length', raw.get('min-length', 0))\n+    maximum = _u32_value(where, 'max-length', raw['max-length'])\n+    if minimum \u003e maximum:\n+        raise CtlvError(where, f'min-length {minimum} is greater than '\n+                               f'max-length {maximum}')\n+    return {'min_length': minimum, 'max_length': maximum}\n+\n+\n+def _blob(where, raw):\n+    alignment = raw.get('alignment', 1)\n+    maximum = raw['max-length']\n+    if maximum \u003c 1 or maximum \u003e U64_MAX:\n+        raise CtlvError(where, f'blob max-length {maximum} is outside the '\n+                               'u64 range')\n+    if alignment \u003c 1 or alignment \u003e U32_MAX:\n+        raise CtlvError(where, f'blob alignment {alignment} is outside the '\n+                               'u32 range')\n+    if alignment \u0026 (alignment - 1):\n+        raise CtlvError(where, f'blob alignment {alignment} is not a power '\n+                               'of two')\n+    if maximum % alignment:\n+        raise CtlvError(where, f'blob max-length {maximum} is not '\n+                               f'a multiple of alignment {alignment}')\n+    return BlobDecl(direction=raw['direction'],\n+                    backings=tuple(raw['allowed-backings']),\n+                    max_length=maximum,\n+                    alignment=alignment)\n+\n+\n+def _sets(path, raw_sets):\n+    sets = []\n+    for raw in raw_sets:\n+        name = raw['name']\n+        where = f'{path}: attr set {name}'\n+        stub = raw.get('stub', False)\n+        attrs = _selectors(raw.get('attrs'))\n+        optional = _selectors(raw.get('optional-attrs'))\n+        if stub and (attrs or optional):\n+            raise CtlvError(where, 'a stub attr set cannot declare members')\n+        if not stub and not attrs and not optional:\n+            raise CtlvError(where, 'attr set has no members; declare '\n+                                   'stub: true for an extension point')\n+        sets.append(AttrSetSpec(name, stub, attrs, optional))\n+    return tuple(sets)\n+\n+\n+def _ops(path, raw_ops):\n+    ops = []\n+    for raw in raw_ops:\n+        name = raw['name']\n+        where = f'{path}: op {name}'\n+        op_type = raw['type']\n+        suggested = raw.get('suggested-reply-length')\n+        if suggested is not None:\n+            suggested = _u32_value(where, 'suggested-reply-length',\n+                                   suggested)\n+        if op_type == 'event' and 'request' in raw:\n+            raise CtlvError(where, 'an event op cannot declare a request')\n+        if op_type == 'query' and 'reply' not in raw:\n+            raise CtlvError(where, 'a query op must declare a reply')\n+        if 'suggested-reply-length' in raw and op_type != 'query':\n+            raise CtlvError(where, 'suggested-reply-length is only valid on '\n+                                   'a query op')\n+        if 'fd-access' in raw and op_type == 'event':\n+            raise CtlvError(where, 'fd-access is only valid on an action or '\n+                                   'a query op')\n+        # An event is not executed, so there is nothing to enable or disable.\n+        if 'availability' in raw and op_type == 'event':\n+            raise CtlvError(where, 'availability is only valid on an action '\n+                                   'or a query op')\n+        # An event is produced rather than answered, so there is nothing for a\n+        # device to opt in to.\n+        if 'optional' in raw and op_type == 'event':\n+            raise CtlvError(where, 'optional is only valid on an action or a '\n+                                   'query op')\n+        # A hook pair wraps the execution of an op, and an event has none.\n+        if 'pre-post' in raw and op_type == 'event':\n+            raise CtlvError(where, 'pre-post is only valid on an action or a '\n+                                   'query op')\n+        # An omitted action or query request means a root with no children.\n+        request = None\n+        if op_type != 'event':\n+            request = _placements(raw.get('request'))\n+        # Omitted: an action reply is ACK-only, an event reply payload-free.\n+        reply = None\n+        if 'reply' in raw:\n+            reply = _placements(raw['reply'])\n+        elif op_type == 'event':\n+            reply = Placements()\n+        ops.append(OpSpec(\n+            name=name,\n+            type=op_type,\n+            request=request,\n+            reply=reply,\n+            fd_access=raw.get('fd-access', DEFAULT_FD_ACCESS),\n+            availability=raw.get('availability', DEFAULT_AVAILABILITY),\n+            optional=raw.get('optional', False),\n+            pre_post=raw.get('pre-post', False),\n+            suggested_reply_length=suggested,\n+        ))\n+    return tuple(ops)\n+\n+\n+def _placements(raw):\n+    if raw is None:\n+        return Placements()\n+    return Placements(_selectors(raw.get('attrs')),\n+                      _selectors(raw.get('optional-attrs')))\n+\n+\n+def _selectors(raw):\n+    if raw is None:\n+        return ()\n+    if isinstance(raw, str):\n+        return (raw,)\n+    return tuple(raw)\ndiff --git a/tools/ctlv/ctlvgen/lib/tree.py b/tools/ctlv/ctlvgen/lib/tree.py\nnew file mode 100644\nindex 0000000000000..62f4fb3634697\n--- /dev/null\n+++ b/tools/ctlv/ctlvgen/lib/tree.py\n@@ -0,0 +1,71 @@\n+# SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause\n+\"\"\"Whole-tree registry, specification and ABI coverage checks.\"\"\"\n+\n+from __future__ import annotations\n+\n+from . import compat\n+from . import outputs\n+from . import spec\n+from .errors import CtlvError\n+\n+\n+def _stems(directory, exclude=()):\n+    return {path.stem for path in directory.glob('*.yaml')\n+            if path.name not in exclude}\n+\n+\n+def coverage_problems(paths, registry, snapshots=True,\n+                      allowed_missing_snapshots=()):\n+    expected = {entry.name for entry in registry.entries}\n+    problems = []\n+\n+    actual_specs = _stems(paths.spec_dir)\n+    for name in sorted(expected - actual_specs):\n+        problems.append(f'missing specification {name}.yaml')\n+    for name in sorted(actual_specs - expected):\n+        problems.append(f'unexpected specification {name}.yaml')\n+\n+    if snapshots:\n+        actual_abi = _stems(paths.abi_dir,\n+                            exclude=(paths.registry_abi.name,))\n+        missing = expected - actual_abi - set(allowed_missing_snapshots)\n+        for name in sorted(missing):\n+            problems.append(f'missing ABI snapshot {name}.yaml')\n+        for name in sorted(actual_abi - expected):\n+            problems.append(f'unexpected ABI snapshot {name}.yaml')\n+    return problems\n+\n+\n+def check(paths):\n+    \"\"\"Check all inputs whose expected set comes from the registry.\"\"\"\n+    registry = spec.load_registry(paths)\n+    compat.registry_check(paths, registry)\n+    problems = coverage_problems(paths, registry)\n+    if problems:\n+        raise CtlvError('CTLV tree', '\\n'.join(problems))\n+    outputs.load(paths)\n+    return registry\n+\n+\n+def check_for_update(paths):\n+    \"\"\"Validate a registry update without requiring new snapshots yet.\"\"\"\n+    registry = spec.load_registry(paths)\n+    compat.registry_check(paths, registry, exact=False)\n+    baseline = spec.load_registry(paths, paths.registry_abi)\n+    appended = {entry.name\n+                for entry in registry.entries[len(baseline.entries):]}\n+    problems = coverage_problems(paths, registry,\n+                                 allowed_missing_snapshots=appended)\n+    if problems:\n+        raise CtlvError('CTLV tree', '\\n'.join(problems))\n+    outputs.load(paths)\n+    return registry\n+\n+\n+def finish_update(paths):\n+    \"\"\"Require complete snapshots before advancing the registry baseline.\"\"\"\n+    registry = check_for_update(paths)\n+    problems = coverage_problems(paths, registry)\n+    if problems:\n+        raise CtlvError('CTLV tree', '\\n'.join(problems))\n+    return registry\ndiff --git a/tools/ctlv/ctlvgen/lib/yamlload.py b/tools/ctlv/ctlvgen/lib/yamlload.py\nnew file mode 100644\nindex 0000000000000..f043d87c98182\n--- /dev/null\n+++ b/tools/ctlv/ctlvgen/lib/yamlload.py\n@@ -0,0 +1,83 @@\n+# SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause\n+\"\"\"Strict YAML subset loader.\n+\n+Anchors, aliases, merge keys, explicit tags, duplicate mapping keys and\n+multiple documents per file are all rejected: they let two readers of a file\n+that defines an ABI disagree about what it says.\n+\"\"\"\n+\n+import yaml\n+\n+from .errors import CtlvError\n+\n+\n+def _mark(path, mark):\n+    if mark is None:\n+        return str(path)\n+    return f'{path}:{mark.line + 1}'\n+\n+\n+class _StrictLoader(yaml.SafeLoader):\n+    \"\"\"SafeLoader without the features that make a document ambiguous.\"\"\"\n+\n+    def __init__(self, stream, path):\n+        super().__init__(stream)\n+        self.ctlv_path = path\n+\n+    def _reject(self, mark, what):\n+        raise CtlvError(_mark(self.ctlv_path, mark), what)\n+\n+    def compose_node(self, parent, index):\n+        event = self.peek_event()\n+        if isinstance(event, yaml.events.AliasEvent):\n+            self._reject(event.start_mark, 'YAML aliases are not allowed')\n+        if getattr(event, 'anchor', None) is not None:\n+            self._reject(event.start_mark, 'YAML anchors are not allowed')\n+        if _has_explicit_tag(event):\n+            self._reject(event.start_mark,\n+                         f'explicit YAML tag \"{event.tag}\" is not allowed')\n+        return super().compose_node(parent, index)\n+\n+    def construct_mapping(self, node, deep=False):\n+        seen = set()\n+        for key_node, _ in node.value:\n+            if key_node.tag == 'tag:yaml.org,2002:merge':\n+                self._reject(key_node.start_mark,\n+                             'YAML merge keys are not allowed')\n+            key = self.construct_object(key_node, deep=deep)\n+            if key in seen:\n+                self._reject(key_node.start_mark, f'duplicate key \"{key}\"')\n+            seen.add(key)\n+        return super().construct_mapping(node, deep=deep)\n+\n+\n+def _has_explicit_tag(event):\n+    if event.tag is None:\n+        return False\n+    implicit = getattr(event, 'implicit', False)\n+    if isinstance(implicit, tuple):\n+        return not (implicit[0] or implicit[1])\n+    return not implicit\n+\n+\n+def load(path):\n+    \"\"\"Return the single YAML document in path as plain Python objects.\"\"\"\n+    try:\n+        with open(path, 'r', encoding='utf-8') as stream:\n+            loader = _StrictLoader(stream, path)\n+            try:\n+                data = loader.get_single_data()\n+            finally:\n+                loader.dispose()\n+    except OSError as exc:\n+        raise CtlvError(str(path), f'cannot read: {exc.strerror}') from exc\n+    except yaml.YAMLError as exc:\n+        mark = getattr(exc, 'problem_mark', None)\n+        described = [getattr(exc, 'context', None),\n+                     getattr(exc, 'problem', None)]\n+        problem = ', '.join(part for part in described if part) or str(exc)\n+        raise CtlvError(_mark(path, mark), problem) from exc\n+\n+    if not isinstance(data, dict):\n+        raise CtlvError(str(path), 'expected a YAML mapping at the top level')\n+    return data\ndiff --git a/tools/ctlv/pyproject.toml b/tools/ctlv/pyproject.toml\nnew file mode 100644\nindex 0000000000000..7ecae2de30657\n--- /dev/null\n+++ b/tools/ctlv/pyproject.toml\n@@ -0,0 +1,22 @@\n+[build-system]\n+requires = [\"setuptools\u003e=61.0\"]\n+build-backend = \"setuptools.build_meta\"\n+\n+[project]\n+name = \"ctlvgen\"\n+authors = [\n+    {name = \"Jiri Pirko\", email = \"jiri@resnulli.us\"},\n+]\n+description = \"CTLV schema tool\"\n+version = \"0.0.1\"\n+requires-python = \"\u003e=3.9\"\n+dependencies = [\n+    \"pyyaml==6.*\",\n+    \"jsonschema==4.*\"\n+]\n+\n+[tool.setuptools.packages.find]\n+include = [\"ctlvgen\", \"ctlvgen.lib\"]\n+\n+[project.scripts]\n+ctlvgen = \"ctlvgen.cli:main\"\ndiff --git a/tools/ctlv/requirements.txt b/tools/ctlv/requirements.txt\nnew file mode 100644\nindex 0000000000000..2a73e762f9b91\n--- /dev/null\n+++ b/tools/ctlv/requirements.txt\n@@ -0,0 +1,2 @@\n+pyyaml==6.*\n+jsonschema==4.*\n"
}

2/1 2026/10/15 19:11 agent patch-evaluator
4m Model:
core

Args:
null

Results:
{
  "EnableConfigs": null,
  "FocusSymbols": [],
  "Reasoning": "The patch series introduces the CTLV subsystem (character device TLV UAPI transport), an Attestation subsystem, and an Intel TDX attestation provider. The only provider implemented for CTLV/Attestation that calls ctlv_create() to instantiate character devices (/dev/ctlv*) is the TDX attestation provider. However, the TDX provider depends on the TDX guest driver (drivers/virt/coco/tdx-guest/tdx-guest.c), which strictly requires Intel Trust Domain Extensions hardware support (X86_FEATURE_TDX_GUEST) and exits with -ENODEV in tdx_guest_init() when running in standard virtualized environments (standard QEMU or GCE). Because no TDX hardware is present, tdx_guest_client_attach() is never called, ctlv_create() is never invoked, and no CTLV character devices can ever be created or opened by userspace. Consequently, all newly added CTLV and attestation operational logic is structurally unreachable in standard fuzzing environments.",
  "WorthFuzzing": false
}

Instruction:
You are an expert Linux kernel maintainer and security engineer.
Your job is to review a provided patch series and evaluate whether it warrants fuzzing with syzkaller.

IMPORTANT: The changes have ALREADY been applied and committed as the HEAD commit in
your workspace. Do NOT rely on internal assumptions. You must actively use your code access
tools to inspect the actual source code, callers, and surrounding context.

================================================================================
1. CORE TRIAGE PHILOSOPHY
================================================================================
The goal of patch fuzzing is to discover crashes, regressions, exposed latent bugs,
and newly triggered assertions introduced by the patch series.

- REACHABILITY IS THE PRIMARY GATE:
  Fuzzing can only discover bugs in code that can actually execute in standard virtualized
  environments (GCE or QEMU, utilizing software-emulated devices like USB gadgets, netdev, tun/tap).
  If the modified code is structurally unreachable (see Section 2), it MUST NOT be fuzzed,
  regardless of whether it adds assertions or complex logic.

- DO NOT BLINDLY TRUST "NO FUNCTIONAL CHANGE" (NFCI) OR "REFACTORING" CLAIMS:
  Patch authors routinely label changes as "cleanups", "refactorings", or state
  "No functional change intended". Do NOT take these claims at face value.
  Code refactorings that rearrange logic, introduce helper functions, or alter state management
  in core subsystems frequently introduce subtle semantic shifts or uncover latent kernel bugs.
  If reachable executable code is modified or refactored, it MUST be fuzzed.

- NEW OR MODIFIED ASSERTIONS IN REACHABLE CODE MUST BE FUZZED:
  When a patch introduces or modifies runtime checks or assertions (e.g., WARN_ON*, VM_WARN_ON*,
  BUG_ON*, lockdep_assert*) in reachable code paths, it enforces new or stricter invariants.
  Even if the author believes the invariant always holds, fuzzing is essential to verify whether
  an unusual sequence of operations can violate it.

================================================================================
2. WHEN TO RETURN WorthFuzzing=false (NEGATIVE CRITERIA)
================================================================================
Return WorthFuzzing=false ONLY IF all modified code falls strictly into one or more of these categories:

- Non-kernel and non-executable changes:
  * Modifications to Documentation/, comments, or spelling fixes.
  * User-space directories, self-tests, samples, or scripts (e.g., tools/, samples/, scripts/, usr/)
    that do not affect the compiled kernel image (vmlinux) or kernel modules.
  * Purely decorative logging (e.g., message strings in pr_err, printk, dev_info) or tracepoints
    that do not alter control flow or data structures.
  * Build system or Kconfig changes that do not alter compiled C logic.
- Structurally unreachable hardware:
  * Vendor-specific PCIe switches, SmartNICs, or GPU drivers (e.g., mlxsw, pds_core, qed,
    ionic, amdgpu) requiring physical ASIC/PCIe cards not emulated in standard QEMU.
- Unreachable execution paths:
  * Driver teardown callbacks (.remove, .shutdown, pci_unregister_driver) executed only during
    physical PCI hot-unplug or manual sysfs driver unbinding.
  * Code paths exclusive to architectures other than the target architecture.

================================================================================
3. WHEN TO RETURN WorthFuzzing=true (POSITIVE CRITERIA)
================================================================================
Return WorthFuzzing=true whenever the patch touches reachable executable code, including:
- Core Subsystems:
  * Any logic modifications in memory management (mm/), synchronization/locking (kernel/locking/),
    BPF, scheduler, core networking, VFS, or syscall handling.
- Refactorings and Code Cleanups:
  * Any restructuring of reachable data structures, helper abstractions, or algorithm flows.
- Runtime Assertions and Defensive Checks:
  * Any introduction or alteration of assertions (WARN_ON*, VM_WARN_ON*, BUG_ON*, etc.) in reachable paths.
- Reachable Drivers and Protocols:
  * Drivers accessible via virtual buses (virtio, USB gadget, loopback, netlink, binder, sockets, etc.).

================================================================================
4. EXTRACTING FocusSymbols (PREVENTING DILUTION)
================================================================================
When WorthFuzzing=true, you must extract specific kernel functions into FocusSymbols to guide the fuzzer:

- AVOID UBIQUITOUS LIFECYCLE HOT-PATHS:
  Do NOT list generic, ubiquitous functions called by almost every program in the corpus
  (including, but not limited to: general memory allocators and deallocators, page fault
  and trap handlers, or core synchronization primitives; this is not an exhaustive list).
  Listing ubiquitous functions causes the fuzzer to classify thousands of unrelated tests as "focused",
  which severely dilutes fuzzing effort away from the actual changes.

- TARGET SPECIFIC FEATURE LOGIC AND ENTRYPOINTS:
  List functions that specifically implement the logic being added or altered, or direct API entrypoints
  for the subsystem feature under review.

- HANDLING STATIC INLINE FUNCTIONS IN HEADERS (.h):
  Compiler-inlined static functions (such as static inlines in mm/*.h or include/linux/*.h) lack
  distinct symbol addresses in vmlinux and cannot be targeted directly by symbol coverage filters.
  If the changes are primarily in static inline helpers, identify non-static, feature-specific caller
  functions in .c files that exercise them (avoiding ubiquitous lifecycle wrappers).

================================================================================
5. IDENTIFYING EnableConfigs
================================================================================
Identify any specific CONFIG_ options required to properly compile and reach the modified code:
- Inspect Kconfig files and #ifdef guards; do not make assumptions.
- Check "depends on" lines in Kconfig to include any non-standard parent subsystem configs needed.
- Strip any 'CONFIG_' prefix (e.g., return "NET_IPV4" instead of "CONFIG_NET_IPV4").
Prefer calling several tools at the same time to save round-trips.


Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.

Prompt:
Target architecture: amd64

For your convenience, here is the diff of the changes:
commit f1fe376af05c53e6ada5d982f65c56cf65f0ef29
Author: syz-cluster <triage@syzkaller.com>
Date:   Thu Oct 15 19:11:08 2026 +0000

    syz-cluster: applied patch under review

diff --git a/Documentation/ctlv/abi/ctlv-attestation-tdx.yaml b/Documentation/ctlv/abi/ctlv-attestation-tdx.yaml
new file mode 100644
index 0000000000000..89b80d84e7f1a
--- /dev/null
+++ b/Documentation/ctlv/abi/ctlv-attestation-tdx.yaml
@@ -0,0 +1,22 @@
+# SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)
+%YAML 1.2
+---
+# Checked-in ABI snapshot of the ctlv-attestation-tdx family, written by
+# "make -C tools/ctlv abi-update".
+#
+# The checker compares this family's declarations and inherited stub fills
+# against this file. Updating it is how a UAPI change gets reviewed; an update
+# that removes or renumbers anything, narrows a bound, or makes a placement
+# required is an ABI break, whatever this file says afterwards.
+family: {name: ctlv-attestation-tdx, id: 2, inherits: ctlv-attestation,
+         pre-init: true}
+attr-groups:
+  info:
+    id: 1
+    attrs:
+      mrconfigid: {id: 1, type: binary, length: 48}
+      mrowner: {id: 2, type: binary, length: 48}
+      mrownerconfig: {id: 3, type: binary, length: 48}
+fills:
+  device-info:
+    attrs: [info.mrconfigid, info.mrowner, info.mrownerconfig]
diff --git a/Documentation/ctlv/abi/ctlv-attestation.yaml b/Documentation/ctlv/abi/ctlv-attestation.yaml
new file mode 100644
index 0000000000000..a857e5ce00394
--- /dev/null
+++ b/Documentation/ctlv/abi/ctlv-attestation.yaml
@@ -0,0 +1,184 @@
+# SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)
+%YAML 1.2
+---
+# Checked-in ABI snapshot of the ctlv-attestation family, written by
+# "make -C tools/ctlv abi-update".
+#
+# The checker compares this family's declarations and inherited stub fills
+# against this file. Updating it is how a UAPI change gets reviewed; an update
+# that removes or renumbers anything, narrows a bound, or makes a placement
+# required is an ABI break, whatever this file says afterwards.
+family: {name: ctlv-attestation, id: 1, inherits: ctlv, post-init: true,
+         pre-fini: true}
+enums:
+  evidence-representation: {raw: 1}
+  evidence-blob-class: {primary: 1}
+  mr-log-event: {info: 1, extend: 2}
+flags:
+  mr-device-caps: {read: 0, extend: 1}
+  mr-caps: {read: 0, extend: 1}
+attr-groups:
+  device:
+    id: 1
+    attrs:
+      generation: {id: 1, type: uint, max: 4294967295}
+      caps: {id: 2, type: nested}
+      info: {id: 3, type: nested}
+  cap:
+    id: 2
+    attrs:
+      evidence: {id: 1, type: nested}
+      mr: {id: 2, type: nested}
+      min-challenge-length: {id: 3, type: uint}
+      max-challenge-length: {id: 4, type: uint}
+      max-total-output-length: {id: 5, type: uint}
+      mr-flags: {id: 6, flags: mr-device-caps}
+      object: {id: 7, type: nested, max-occurrences: 16}
+      blob-class: {id: 8, enum: evidence-blob-class}
+      format: {id: 9, type: string, min-length: 1, max-length: 128}
+      representation: {id: 10, enum: evidence-representation}
+      max-length: {id: 11, type: uint}
+  evidence:
+    id: 3
+    attrs:
+      challenge: {id: 1, type: binary, max-length: 4096}
+      object: {id: 2, type: nested, max-occurrences: 16}
+      blob-class: {id: 3, enum: evidence-blob-class}
+      format: {id: 4, type: string, min-length: 1, max-length: 128}
+      representation: {id: 5, enum: evidence-representation}
+      data: {id: 6, blob: output, backings: [va], max-length: 4294967295}
+      object-length: {id: 7, type: uint, max-occurrences: 16}
+  mr:
+    id: 4
+    attrs:
+      id: {id: 1, type: uint, max: 4294967295}
+      name: {id: 2, type: string, min-length: 1, max-length: 128}
+      hash-algo: {id: 3, type: uint, max: 20}
+      supported-hash-algo: {id: 4, type: uint, max: 20, max-occurrences: 21}
+      register-index: {id: 5, type: uint, max: 4294967295}
+      caps: {id: 6, flags: mr-caps}
+      item: {id: 7, type: nested, max-occurrences: unlimited}
+      value: {id: 8, type: nested, max-occurrences: 21}
+      data: {id: 9, type: binary, min-length: 16, max-length: 64}
+      generation: {id: 10, type: uint, max: 4294967295}
+      selection: {id: 11, type: nested, max-occurrences: 256}
+      start-generation: {id: 12, type: uint, max: 4294967295}
+      end-generation: {id: 13, type: uint, max: 4294967295}
+  log:
+    id: 5
+    attrs:
+      entry: {id: 1, type: nested, max-occurrences: unlimited}
+      event: {id: 2, enum: mr-log-event}
+      mr: {id: 3, type: nested}
+  notification:
+    id: 6
+    attrs:
+      entry: {id: 1, type: nested}
+attr-sets:
+  device-info: {id: 1, stub: true}
+  evidence-object-cap: {id: 2}
+  evidence-cap: {id: 3}
+  mr-device-cap: {id: 4}
+  device-caps: {id: 5}
+  device-reply: {id: 6}
+  evidence-object-request: {id: 7}
+  evidence-request: {id: 8}
+  evidence-reply: {id: 9}
+  mr-props: {id: 10}
+  mr-dump-entry: {id: 11}
+  mr-id-request: {id: 12}
+  mr-read-request: {id: 13}
+  mr-value: {id: 14}
+  mr-read-reply: {id: 15}
+  mr-extend-request: {id: 16}
+  mr-change-reply: {id: 17}
+  mr-log-info: {id: 18}
+  mr-log-entry: {id: 19}
+  mr-log-event: {id: 20}
+  mr-log-selection: {id: 21}
+  mr-log-request: {id: 22}
+  mr-log-reply: {id: 23}
+ops:
+  device-get:
+    abi: {id: 1, type: action, fd-access: read}
+    reply:
+      attrs:
+        - device.caps:
+            optional-attrs:
+              - cap.evidence:
+                  attrs:
+                    - cap.min-challenge-length
+                    - cap.max-challenge-length
+                    - cap.max-total-output-length
+                    - cap.object:
+                        attrs: [cap.blob-class, cap.format, cap.representation,
+                                cap.max-length]
+              - cap.mr: {attrs: [cap.mr-flags]}
+        - device.info: {attrs: [device-info]}
+  evidence-get:
+    abi: {id: 2, type: action, availability: dynamic, optional: true}
+    request:
+      attrs:
+        - evidence.challenge
+        - evidence.object:
+            attrs: [evidence.blob-class, evidence.format,
+                    evidence.representation, evidence.data]
+    reply:
+      attrs: [evidence.object-length]
+      optional-attrs: [mr.generation]
+  mr-get:
+    abi: {id: 3, type: action, fd-access: read, optional: true}
+    request: {attrs: [mr.id]}
+    reply:
+      attrs: [mr.name, mr.supported-hash-algo, mr.caps]
+      optional-attrs: [mr.register-index]
+  mr-dump:
+    abi: {id: 4, type: query, fd-access: read, optional: true}
+    reply:
+      attrs:
+        - mr.item:
+            attrs: [mr.id, mr.name, mr.supported-hash-algo, mr.caps]
+            optional-attrs: [mr.register-index]
+  mr-read:
+    abi: {id: 5, type: query, fd-access: read, optional: true}
+    request: {attrs: [mr.id]}
+    reply:
+      attrs:
+        - mr.generation
+        - mr.value: {attrs: [mr.hash-algo, mr.data]}
+  mr-extend:
+    abi: {id: 6, type: action, optional: true}
+    request:
+      attrs:
+        - mr.id
+        - mr.value: {attrs: [mr.hash-algo, mr.data]}
+    reply: {attrs: [mr.generation]}
+  mr-log-entry-appended:
+    abi: {id: 7, type: event}
+    reply:
+      attrs:
+        - notification.entry:
+            attrs: [mr.generation, mr.id, log.event]
+            optional-attrs:
+              - mr.value: {attrs: [mr.hash-algo, mr.data]}
+              - log.mr:
+                  attrs: [mr.name, mr.supported-hash-algo, mr.caps]
+                  optional-attrs: [mr.register-index]
+  mr-log-get:
+    abi: {id: 8, type: query, fd-access: read, optional: true}
+    request:
+      optional-attrs:
+        - mr.selection: {attrs: [mr.id]}
+        - mr.start-generation
+        - mr.end-generation
+    reply:
+      optional-attrs:
+        - mr.start-generation
+        - mr.end-generation
+        - log.entry:
+            attrs: [mr.generation, mr.id, log.event]
+            optional-attrs:
+              - mr.value: {attrs: [mr.hash-algo, mr.data]}
+              - log.mr:
+                  attrs: [mr.name, mr.supported-hash-algo, mr.caps]
+                  optional-attrs: [mr.register-index]
diff --git a/Documentation/ctlv/abi/ctlv.yaml b/Documentation/ctlv/abi/ctlv.yaml
new file mode 100644
index 0000000000000..fa11bce98f462
--- /dev/null
+++ b/Documentation/ctlv/abi/ctlv.yaml
@@ -0,0 +1,186 @@
+# 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, written by
+# "make -C tools/ctlv abi-update".
+#
+# The checker compares this family's declarations and inherited stub fills
+# against this file. Updating it is how a UAPI change gets reviewed; an update
+# that removes or renumbers anything, narrows a bound, or makes a placement
+# required is an ABI break, whatever this file says afterwards.
+family: {name: ctlv, id: 0}
+enums:
+  op-type: {action: 1, query: 2, event: 3}
+  op-availability: {fixed: 1, dynamic: 2}
+  blob-type: {va: 1}
+  blob-direction: {input: 1, output: 2, inout: 3}
+  validation-reason: {malformed-message: 1, unknown-attr: 2, unknown-flag: 3,
+                      nesting-too-deep: 4, missing-attr: 5,
+                      too-many-occurrences: 6, value-out-of-range: 7,
+                      bad-length: 8, bad-string: 9, bad-blob-descriptor: 10,
+                      stale-generation: 11, noncontiguous-attr: 12}
+  op-fd-access: {read: 1, read-write: 2}
+attr-groups:
+  family:
+    id: 1
+    attrs:
+      id: {id: 1, type: uint}
+      name: {id: 2, type: string, max-length: 63}
+      entry: {id: 3, type: nested, max-occurrences: unlimited}
+  blob:
+    id: 2
+    attrs:
+      type: {id: 1, enum: blob-type}
+      address: {id: 2, type: uint}
+      fd: {id: 3, type: uint, max: 2147483647}
+      offset: {id: 4, type: uint}
+      length: {id: 5, type: uint, min: 1}
+  error:
+    id: 3
+    attrs:
+      reason: {id: 1, enum: validation-reason}
+      message: {id: 2, type: string, max-length: 255}
+      bad-attr-offset: {id: 3, type: uint}
+      nest-offset: {id: 4, type: uint}
+      missing-attr-id: {id: 5, type: uint}
+      expected-generation: {id: 6, type: uint}
+      current-generation: {id: 7, type: uint}
+  op:
+    id: 4
+    attrs:
+      id: {id: 1, type: uint, min: 1}
+      type: {id: 2, enum: op-type}
+      availability: {id: 3, enum: op-availability}
+      disabled: {id: 4, type: bool}
+      request-max-len: {id: 5, type: uint}
+      action-reply-max-len: {id: 6, type: uint}
+      query-reply-min-len: {id: 7, type: uint}
+      query-reply-suggested-len: {id: 8, type: uint}
+      event-record-max-len: {id: 9, type: uint}
+      state-generation: {id: 10, type: uint}
+      entry: {id: 11, type: nested, max-occurrences: unlimited}
+      fd-access: {id: 12, enum: op-fd-access}
+  schema:
+    id: 5
+    attrs:
+      attr-id: {id: 1, type: uint}
+      kind: {id: 2, type: uint}
+      max-occurrences: {id: 3, type: uint}
+      min: {id: 4, type: uint}
+      max: {id: 5, type: uint}
+      min-length: {id: 6, type: uint}
+      max-length: {id: 7, type: uint}
+      flags-mask: {id: 8, type: uint}
+      unit: {id: 9, type: uint}
+      scale: {id: 10, type: sint}
+      blob-direction: {id: 11, enum: blob-direction}
+      blob-backings: {id: 12, type: uint}
+      blob-max-length: {id: 13, type: uint}
+      blob-alignment: {id: 14, type: uint}
+      reenters: {id: 15, type: uint, min: 1}
+      attrs: {id: 16, type: nested, max-occurrences: unlimited}
+      optional-attrs: {id: 17, type: nested, max-occurrences: unlimited}
+      request: {id: 18, type: nested}
+      reply: {id: 19, type: nested}
+  event:
+    id: 6
+    attrs:
+      op-id: {id: 1, type: uint, min: 1, max-occurrences: 256}
+      queue-len: {id: 2, type: uint, min: 1, max: 16777216, unit: bytes}
+      queue-used: {id: 3, type: uint, unit: bytes}
+      first-sequence: {id: 4, type: uint}
+      last-sequence: {id: 5, type: uint}
+      dropped-count: {id: 6, type: uint}
+attr-sets:
+  family-entry: {id: 1}
+  op-entry: {id: 2}
+  op-schema-request: {id: 3}
+  schema-node: {id: 4}
+  op-schema-info: {id: 5}
+  op-change-info: {id: 6}
+  error-info: {id: 7}
+  event-subscription: {id: 8}
+  event-queue-limit: {id: 9}
+  event-queue-state: {id: 10}
+  event-overflow-info: {id: 11}
+ops:
+  families-dump:
+    abi: {id: 1, type: query, fd-access: read}
+    reply:
+      attrs:
+        - family.entry: {attrs: [family.id, family.name]}
+  ops-dump:
+    abi: {id: 2, type: query, fd-access: read}
+    reply:
+      attrs:
+        - op.entry:
+            attrs: [op.id, op.type]
+            optional-attrs: [op.availability, op.disabled, op.request-max-len,
+                             op.action-reply-max-len, op.query-reply-min-len,
+                             op.query-reply-suggested-len,
+                             op.event-record-max-len, op.fd-access]
+  op-schema-get:
+    abi: {id: 3, type: query, fd-access: read}
+    request: {attrs: [op.id]}
+    reply:
+      optional-attrs:
+        - schema.request:
+            attrs: [schema.attr-id, schema.kind, schema.max-occurrences]
+            optional-attrs:
+              - schema.min
+              - schema.max
+              - schema.min-length
+              - schema.max-length
+              - schema.flags-mask
+              - schema.unit
+              - schema.scale
+              - schema.blob-direction
+              - schema.blob-backings
+              - schema.blob-max-length
+              - schema.blob-alignment
+              - schema.reenters
+              - schema.attrs:
+                  reenters: schema-node
+              - schema.optional-attrs:
+                  reenters: schema-node
+        - schema.reply:
+            attrs: [schema.attr-id, schema.kind, schema.max-occurrences]
+            optional-attrs:
+              - schema.min
+              - schema.max
+              - schema.min-length
+              - schema.max-length
+              - schema.flags-mask
+              - schema.unit
+              - schema.scale
+              - schema.blob-direction
+              - schema.blob-backings
+              - schema.blob-max-length
+              - schema.blob-alignment
+              - schema.reenters
+              - schema.attrs:
+                  reenters: schema-node
+              - schema.optional-attrs:
+                  reenters: schema-node
+  subscriptions-add:
+    abi: {id: 4, type: action, fd-access: read}
+    request: {attrs: [event.op-id]}
+  subscriptions-remove:
+    abi: {id: 5, type: action, fd-access: read}
+    request: {attrs: [event.op-id]}
+  event-queue-get:
+    abi: {id: 6, type: query, fd-access: read}
+    reply: {attrs: [event.queue-len, event.queue-used]}
+  event-queue-set:
+    abi: {id: 7, type: action, fd-access: read}
+    request: {attrs: [event.queue-len]}
+  op-changed:
+    abi: {id: 8, type: event}
+    reply: {attrs: [op.id, op.disabled, op.state-generation]}
+  event-overflow:
+    abi: {id: 9, type: event}
+    reply:
+      attrs: [event.first-sequence, event.last-sequence, event.dropped-count]
+  device-removed:
+    abi: {id: 10, type: event}
+    reply: {}
diff --git a/Documentation/ctlv/abi/families.registry.yaml b/Documentation/ctlv/abi/families.registry.yaml
new file mode 100644
index 0000000000000..193e3570ab959
--- /dev/null
+++ b/Documentation/ctlv/abi/families.registry.yaml
@@ -0,0 +1,9 @@
+# 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.
+# Updated deliberately by "make -C tools/ctlv abi-update".
+families:
+  - ctlv
+  - ctlv-attestation
+  - ctlv-attestation-tdx
diff --git a/Documentation/ctlv/ctlv-registry-schema.yaml b/Documentation/ctlv/ctlv-registry-schema.yaml
new file mode 100644
index 0000000000000..d9a2840fc230e
--- /dev/null
+++ b/Documentation/ctlv/ctlv-registry-schema.yaml
@@ -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
diff --git a/Documentation/ctlv/ctlv-schema.yaml b/Documentation/ctlv/ctlv-schema.yaml
new file mode 100644
index 0000000000000..38fd56e6627cc
--- /dev/null
+++ b/Documentation/ctlv/ctlv-schema.yaml
@@ -0,0 +1,359 @@
+# SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)
+%YAML 1.2
+---
+$id: http://kernel.org/schemas/ctlv/ctlv-schema.yaml#
+$schema: https://json-schema.org/draft-07/schema
+
+# The syntax gate for a CTLV family specification: permitted keys, their shapes
+# and the closed sets of keywords. Anything needing more than one declaration at
+# a time is checked by tools/ctlv/ctlvgen/lib/semantics.py.
+
+$defs:
+  name:
+    description: Kebab-case identifier. A dot is reserved for selectors.
+    type: string
+    pattern: ^[a-z0-9]+(-[a-z0-9]+)*$
+
+  family-name:
+    description: Name carried by family discovery.
+    allOf:
+      - $ref: '#/$defs/name'
+      - maxLength: 63
+
+  selector:
+    description: |
+      A named attr set, a whole attr group, or one exact attr as
+      "group.attr". There are no tuple selectors and no cross-family
+      qualification.
+    type: string
+    pattern: ^[a-z0-9]+(-[a-z0-9]+)*(\.[a-z0-9]+(-[a-z0-9]+)*)?$
+
+  selectors:
+    oneOf:
+      - $ref: '#/$defs/selector'
+      - type: array
+        minItems: 1
+        items:
+          $ref: '#/$defs/selector'
+
+  uint:
+    type: integer
+    minimum: 0
+    maximum: 4294967295
+
+  integer-bound:
+    type: integer
+    minimum: -9223372036854775808
+    maximum: 18446744073709551615
+
+  max-occurrences:
+    description: |
+      A finite positive count, or unlimited, which is reachable only from
+      query replies.
+    oneOf:
+      - type: integer
+        minimum: 1
+        maximum: 4294967295
+      - const: unlimited
+
+  unit:
+    description: CTLV-owned unit, matching enum ctlv_unit.
+    enum: [ seconds, hertz, bytes, celsius ]
+
+  value-list:
+    description: An enum or a flags definition.
+    type: object
+    required: [ name, values ]
+    additionalProperties: false
+    properties:
+      name:
+        $ref: '#/$defs/name'
+      values:
+        description: |
+          Value names in declaration order. Enum values are numbered from 1
+          because 0 is reserved; flag bits are numbered from bit 0. Both are
+          append-only.
+        type: array
+        minItems: 1
+        items:
+          $ref: '#/$defs/name'
+
+  enum-list:
+    allOf:
+      - $ref: '#/$defs/value-list'
+      - properties:
+          values:
+            maxItems: 4294967295
+
+  flags-list:
+    allOf:
+      - $ref: '#/$defs/value-list'
+      - properties:
+          values:
+            maxItems: 64
+
+  blob:
+    type: object
+    required: [ direction, allowed-backings, max-length ]
+    additionalProperties: false
+    properties:
+      direction:
+        description: How the family may use the described memory.
+        enum: [ input, output, inout ]
+      allowed-backings:
+        type: array
+        minItems: 1
+        uniqueItems: true
+        items:
+          enum: [ va ]
+      max-length:
+        description: |
+          Authoritative maximum external payload length for this placement,
+          independent of the inline message limit.
+        type: integer
+        minimum: 1
+        maximum: 18446744073709551615
+      alignment:
+        description: Required alignment of the described address or offset.
+        type: integer
+        minimum: 1
+        maximum: 4294967295
+
+  attr:
+    description: |
+      One attr declaration. Exactly one primary form out of type, enum,
+      flags, attrs and blob must be present. optional-attrs and recursive
+      may only accompany attrs.
+    type: object
+    required: [ name ]
+    additionalProperties: false
+    properties:
+      name:
+        $ref: '#/$defs/name'
+      type:
+        description: |
+          Primitive payload. Integers are always 64-bit, and a bool is one
+          byte holding zero or one.
+        enum: [ uint, sint, bool, string, binary ]
+      enum:
+        description: Name of an enum definition; implies an unsigned payload.
+        $ref: '#/$defs/name'
+      flags:
+        description: Name of a flags definition; implies an unsigned payload.
+        $ref: '#/$defs/name'
+      attrs:
+        description: Nested payload, given as selectors.
+        $ref: '#/$defs/selectors'
+      optional-attrs:
+        description: Further nested payload whose placements are optional.
+        $ref: '#/$defs/selectors'
+      recursive:
+        description: |
+          The nested payload is one attr set that may contain this attr
+          again, describing a structure of any depth. Only a query reply can
+          hold one, since such a nest has no maximum length.
+        const: true
+      blob:
+        $ref: '#/$defs/blob'
+      min:
+        description: Inclusive minimum of an integer payload.
+        $ref: '#/$defs/integer-bound'
+      max:
+        description: Inclusive maximum of an integer payload.
+        $ref: '#/$defs/integer-bound'
+      length:
+        description: Exact payload length of a binary attr.
+        $ref: '#/$defs/uint'
+      min-length:
+        description: |
+          Minimum payload length, excluding the terminator of a string.
+        $ref: '#/$defs/uint'
+      max-length:
+        description: |
+          Maximum payload length, excluding the terminator of a string.
+        $ref: '#/$defs/uint'
+      unit:
+        $ref: '#/$defs/unit'
+      scale:
+        description: Decimal exponent applied to the payload.
+        type: integer
+        minimum: -128
+        maximum: 127
+      max-occurrences:
+        $ref: '#/$defs/max-occurrences'
+
+  attr-group:
+    description: |
+      A namespace of attr declarations. The group name is also the generated
+      symbol prefix of its attrs.
+    type: object
+    required: [ name, attrs ]
+    additionalProperties: false
+    properties:
+      name:
+        $ref: '#/$defs/name'
+      attrs:
+        type: array
+        minItems: 1
+        maxItems: 4294967295
+        items:
+          $ref: '#/$defs/attr'
+
+  attr-set:
+    description: |
+      A compositional schema unit. Either a stub, which may be filled once
+      by one descendant family, or a set of members. After fills are composed,
+      every attr ID at one nesting level must still have one placement.
+    type: object
+    required: [ name ]
+    additionalProperties: false
+    properties:
+      name:
+        $ref: '#/$defs/name'
+      stub:
+        const: true
+      attrs:
+        $ref: '#/$defs/selectors'
+      optional-attrs:
+        $ref: '#/$defs/selectors'
+
+  placements:
+    description: The required and optional attr placements at one level.
+    type: object
+    additionalProperties: false
+    minProperties: 1
+    properties:
+      attrs:
+        $ref: '#/$defs/selectors'
+      optional-attrs:
+        $ref: '#/$defs/selectors'
+
+  op:
+    type: object
+    required: [ name, type ]
+    additionalProperties: false
+    properties:
+      name:
+        $ref: '#/$defs/name'
+      type:
+        description: |
+          action is invoked once and never fragments, query may fragment its
+          reply, and event is an unsolicited reply-only schema.
+        enum: [ action, query, event ]
+      fd-access:
+        description: |
+          Authority needed to execute an action or query. read permits an
+          observation fd; read-write, the default, requires a full-control fd.
+          Events are always readable and cannot declare this property.
+        enum: [ read, read-write ]
+      availability:
+        description: |
+          Whether a family may enable and disable this op per device. fixed,
+          the default, is always enabled. dynamic is action and query only,
+          and is a permission rather than a state: every device starts with
+          the op enabled.
+        enum: [ fixed, dynamic ]
+      optional:
+        description: |
+          Whether family initialization must opt in before publication for
+          this op to exist on the device. Action and query only, and false by
+          default. An op not opted into is absent from introspection.
+        type: boolean
+      pre-post:
+        description: |
+          Whether this op gets a generated pre/post hook pair of its own,
+          which its declaring family implements. It runs inside the pair of
+          the device family, or the core family for a core op.
+          Action and query only, and false by default. Kernel implementation
+          metadata: it reaches neither UAPI nor op-schema introspection.
+        type: boolean
+      request:
+        description: |
+          Omitted means a request root with no children. An event has no
+          request.
+        $ref: '#/$defs/placements'
+      reply:
+        description: |
+          Required on a query. Omitted on an action means ACK-only, while an
+          event always has a reply root, so omitting it there means a root
+          with no children.
+        $ref: '#/$defs/placements'
+      suggested-reply-length:
+        description: |
+          Query only. An omitted value is CTLV_DEFAULT_QUERY_REPLY_LEN raised
+          to the computed minimum. A declared value must be between that
+          minimum and CTLV_MAX_INLINE_MESSAGE_LEN.
+        type: integer
+        minimum: 1
+        maximum: 1048576
+
+title: CTLV family
+description: Specification of one CTLV family schema
+type: object
+required: [ family ]
+additionalProperties: false
+properties:
+  family:
+    type: object
+    required: [ name ]
+    additionalProperties: false
+    properties:
+      name:
+        description: |
+          Registered family name. It carries no numeric ID; the ID comes
+          from the position in Documentation/ctlv/families.yaml.
+        $ref: '#/$defs/family-name'
+      inherits:
+        description: |
+          Name of the single direct parent family, which every family but
+          the root one names. The complete parent schema is inherited and
+          its definitions keep the parent's IDs. The name above must be
+          this name, one dash, and a local suffix.
+        $ref: '#/$defs/family-name'
+      pre-init:
+        description: |
+          Whether this family implements the generated pre-init callback
+          which translates its init info for its parent. False by default;
+          without one, the parent receives NULL.
+        type: boolean
+      post-init:
+        description: |
+          Whether this family implements the generated post-init callback
+          after every family priv has been initialized. False by default.
+        type: boolean
+      pre-fini:
+        description: |
+          Whether this family implements the generated pre-fini callback
+          before any family priv is finalized. False by default.
+        type: boolean
+  enums:
+    type: array
+    minItems: 1
+    items:
+      $ref: '#/$defs/enum-list'
+
+  flags:
+    type: array
+    minItems: 1
+    items:
+      $ref: '#/$defs/flags-list'
+
+  attr-groups:
+    type: array
+    minItems: 1
+    maxItems: 65535
+    items:
+      $ref: '#/$defs/attr-group'
+
+  attr-sets:
+    type: array
+    minItems: 1
+    items:
+      $ref: '#/$defs/attr-set'
+
+  ops:
+    type: array
+    minItems: 1
+    maxItems: 4294967295
+    items:
+      $ref: '#/$defs/op'
diff --git a/Documentation/ctlv/families.yaml b/Documentation/ctlv/families.yaml
new file mode 100644
index 0000000000000..d0e1493db498e
--- /dev/null
+++ b/Documentation/ctlv/families.yaml
@@ -0,0 +1,15 @@
+# SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)
+%YAML 1.2
+---
+# 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 wire identity. 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
+  - ctlv-attestation
+  - ctlv-attestation-tdx
diff --git a/Documentation/ctlv/generated-files-schema.yaml b/Documentation/ctlv/generated-files-schema.yaml
new file mode 100644
index 0000000000000..d3529ce6e8e75
--- /dev/null
+++ b/Documentation/ctlv/generated-files-schema.yaml
@@ -0,0 +1,64 @@
+# SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)
+%YAML 1.2
+---
+$schema: https://json-schema.org/draft-07/schema
+
+$defs:
+  path:
+    type: string
+    minLength: 1
+    pattern: ^[^/].*$
+
+  outputs:
+    type: object
+    minProperties: 1
+    additionalProperties: false
+    properties:
+      uapi-header:
+        $ref: '#/$defs/path'
+      kernel-header:
+        $ref: '#/$defs/path'
+      kernel-source:
+        $ref: '#/$defs/path'
+
+  registry:
+    type: object
+    required: [ source, outputs ]
+    additionalProperties: false
+    properties:
+      source:
+        $ref: '#/$defs/path'
+      outputs:
+        type: object
+        required: [ uapi-header ]
+        additionalProperties: false
+        properties:
+          uapi-header:
+            $ref: '#/$defs/path'
+
+  family:
+    type: object
+    required: [ name, source, outputs ]
+    additionalProperties: false
+    properties:
+      name:
+        type: string
+      source:
+        $ref: '#/$defs/path'
+      outputs:
+        $ref: '#/$defs/outputs'
+
+title: CTLV generated-file manifest
+type: object
+required: [ version, registry, families ]
+additionalProperties: false
+properties:
+  version:
+    const: 1
+  registry:
+    $ref: '#/$defs/registry'
+  families:
+    type: array
+    minItems: 1
+    items:
+      $ref: '#/$defs/family'
diff --git a/Documentation/ctlv/generated-files.yaml b/Documentation/ctlv/generated-files.yaml
new file mode 100644
index 0000000000000..00ad23af7f659
--- /dev/null
+++ b/Documentation/ctlv/generated-files.yaml
@@ -0,0 +1,31 @@
+# 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/linux/ctlv_families_gen.h
+
+families:
+  - name: ctlv
+    source: Documentation/ctlv/specs/ctlv.yaml
+    outputs:
+      uapi-header: include/uapi/linux/ctlv_gen.h
+      kernel-header: include/linux/ctlv_gen.h
+      kernel-source: drivers/ctlv/ctlv_gen.c
+
+  - name: ctlv-attestation
+    source: Documentation/ctlv/specs/ctlv-attestation.yaml
+    outputs:
+      uapi-header: include/uapi/linux/ctlv_attestation_gen.h
+      kernel-header: drivers/attestation/generated/ctlv_attestation_gen.h
+      kernel-source: drivers/attestation/generated/ctlv_attestation_gen.c
+
+  - name: ctlv-attestation-tdx
+    source: Documentation/ctlv/specs/ctlv-attestation-tdx.yaml
+    outputs:
+      uapi-header: include/uapi/linux/ctlv_attestation_tdx_gen.h
+      kernel-header: drivers/attestation/generated/ctlv_attestation_tdx_gen.h
+      kernel-source: drivers/attestation/generated/ctlv_attestation_tdx_gen.c
diff --git a/Documentation/ctlv/specs/ctlv-attestation-tdx.yaml b/Documentation/ctlv/specs/ctlv-attestation-tdx.yaml
new file mode 100644
index 0000000000000..09f4d9916f82a
--- /dev/null
+++ b/Documentation/ctlv/specs/ctlv-attestation-tdx.yaml
@@ -0,0 +1,30 @@
+# SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)
+%YAML 1.2
+---
+family:
+  name: ctlv-attestation-tdx
+  inherits: ctlv-attestation
+  pre-init: true
+
+attr-groups:
+  - name: info
+    attrs:
+      - name: mrconfigid
+        type: binary
+        min-length: 48
+        max-length: 48
+      - name: mrowner
+        type: binary
+        min-length: 48
+        max-length: 48
+      - name: mrownerconfig
+        type: binary
+        min-length: 48
+        max-length: 48
+
+attr-sets:
+  - name: device-info
+    attrs:
+      - info.mrconfigid
+      - info.mrowner
+      - info.mrownerconfig
diff --git a/Documentation/ctlv/specs/ctlv-attestation.yaml b/Documentation/ctlv/specs/ctlv-attestation.yaml
new file mode 100644
index 0000000000000..c0d7fc8db18ea
--- /dev/null
+++ b/Documentation/ctlv/specs/ctlv-attestation.yaml
@@ -0,0 +1,347 @@
+# SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)
+%YAML 1.2
+---
+family:
+  name: ctlv-attestation
+  inherits: ctlv
+  post-init: true
+  pre-fini: true
+
+enums:
+  - name: evidence-representation
+    values:
+      - raw
+
+  - name: evidence-blob-class
+    values:
+      - primary
+
+  - name: mr-log-event
+    values:
+      - info
+      - extend
+
+flags:
+  - name: mr-device-caps
+    values:
+      - read
+      - extend
+
+  - name: mr-caps
+    values:
+      - read
+      - extend
+
+attr-groups:
+  - name: device
+    attrs:
+      # Reserved until provider-driven state changes are introduced.
+      - name: generation
+        type: uint
+        max: 4294967295
+      - name: caps
+        attrs: device-caps
+      - name: info
+        attrs: device-info
+
+  - name: cap
+    attrs:
+      - name: evidence
+        attrs: evidence-cap
+      - name: mr
+        attrs: mr-device-cap
+      - name: min-challenge-length
+        type: uint
+      - name: max-challenge-length
+        type: uint
+      - name: max-total-output-length
+        type: uint
+      - name: mr-flags
+        flags: mr-device-caps
+      - name: object
+        attrs: evidence-object-cap
+        max-occurrences: 16
+      - name: blob-class
+        enum: evidence-blob-class
+      - name: format
+        type: string
+        min-length: 1
+        max-length: 128
+      - name: representation
+        enum: evidence-representation
+      - name: max-length
+        type: uint
+
+  - name: evidence
+    attrs:
+      - name: challenge
+        type: binary
+        max-length: 4096
+      - name: object
+        attrs: evidence-object-request
+        max-occurrences: 16
+      - name: blob-class
+        enum: evidence-blob-class
+      - name: format
+        type: string
+        min-length: 1
+        max-length: 128
+      - name: representation
+        enum: evidence-representation
+      - name: data
+        blob:
+          direction: output
+          allowed-backings: [ va ]
+          max-length: 4294967295
+          alignment: 1
+      - name: object-length
+        type: uint
+        max-occurrences: 16
+
+  - name: mr
+    attrs:
+      - name: id
+        type: uint
+        max: 4294967295
+      - name: name
+        type: string
+        min-length: 1
+        max-length: 128
+      - name: hash-algo
+        type: uint
+        max: 20
+      - name: supported-hash-algo
+        type: uint
+        max: 20
+        max-occurrences: 21
+      - name: register-index
+        type: uint
+        max: 4294967295
+      - name: caps
+        flags: mr-caps
+      - name: item
+        attrs: mr-dump-entry
+        max-occurrences: unlimited
+      - name: value
+        attrs: mr-value
+        max-occurrences: 21
+      - name: data
+        type: binary
+        min-length: 16
+        max-length: 64
+      - name: generation
+        type: uint
+        max: 4294967295
+      - name: selection
+        attrs: mr-log-selection
+        max-occurrences: 256
+      - name: start-generation
+        type: uint
+        max: 4294967295
+      - name: end-generation
+        type: uint
+        max: 4294967295
+
+  - name: log
+    attrs:
+      - name: entry
+        attrs: mr-log-entry
+        max-occurrences: unlimited
+      - name: event
+        enum: mr-log-event
+      - name: mr
+        attrs: mr-log-info
+
+  - name: notification
+    attrs:
+      - name: entry
+        attrs: mr-log-entry
+
+attr-sets:
+  - name: device-info
+    stub: true
+
+  - name: evidence-object-cap
+    attrs:
+      - cap.blob-class
+      - cap.format
+      - cap.representation
+      - cap.max-length
+
+  - name: evidence-cap
+    attrs:
+      - cap.min-challenge-length
+      - cap.max-challenge-length
+      - cap.max-total-output-length
+      - cap.object
+
+  - name: mr-device-cap
+    attrs: cap.mr-flags
+
+  - name: device-caps
+    optional-attrs:
+      - cap.evidence
+      - cap.mr
+
+  - name: device-reply
+    attrs:
+      - device.caps
+      - device.info
+
+  - name: evidence-object-request
+    attrs:
+      - evidence.blob-class
+      - evidence.format
+      - evidence.representation
+      - evidence.data
+
+  - name: evidence-request
+    attrs:
+      - evidence.challenge
+      - evidence.object
+
+  - name: evidence-reply
+    attrs: evidence.object-length
+    optional-attrs:
+      - mr.generation
+
+  - name: mr-props
+    attrs:
+      - mr.name
+      - mr.supported-hash-algo
+      - mr.caps
+    optional-attrs: mr.register-index
+
+  - name: mr-dump-entry
+    attrs:
+      - mr.id
+      - mr.name
+      - mr.supported-hash-algo
+      - mr.caps
+    optional-attrs: mr.register-index
+
+  - name: mr-id-request
+    attrs: mr.id
+
+  - name: mr-read-request
+    attrs: mr.id
+
+  - name: mr-value
+    attrs:
+      - mr.hash-algo
+      - mr.data
+
+  - name: mr-read-reply
+    attrs:
+      - mr.generation
+      - mr.value
+
+  - name: mr-extend-request
+    attrs:
+      - mr.id
+      - mr.value
+
+  - name: mr-change-reply
+    attrs: mr.generation
+
+  - name: mr-log-info
+    attrs:
+      - mr.name
+      - mr.supported-hash-algo
+      - mr.caps
+    optional-attrs: mr.register-index
+
+  - name: mr-log-entry
+    attrs:
+      - mr.generation
+      - mr.id
+      - log.event
+    optional-attrs:
+      - mr.value
+      - log.mr
+
+  - name: mr-log-event
+    attrs: notification.entry
+
+  - name: mr-log-selection
+    attrs: mr.id
+
+  - name: mr-log-request
+    optional-attrs:
+      - mr.selection
+      - mr.start-generation
+      - mr.end-generation
+
+  - name: mr-log-reply
+    optional-attrs:
+      - mr.start-generation
+      - mr.end-generation
+      - log.entry
+
+ops:
+  - name: device-get
+    type: action
+    fd-access: read
+    reply:
+      attrs: device-reply
+
+  - name: evidence-get
+    type: action
+    fd-access: read-write
+    availability: dynamic
+    optional: true
+    request:
+      attrs: evidence-request
+    reply:
+      attrs: evidence-reply
+
+  - name: mr-get
+    type: action
+    fd-access: read
+    optional: true
+    request:
+      attrs: mr-id-request
+    reply:
+      attrs: mr-props
+
+  - name: mr-dump
+    type: query
+    fd-access: read
+    optional: true
+    reply:
+      attrs: mr.item
+    suggested-reply-length: 4096
+
+  - name: mr-read
+    type: query
+    fd-access: read
+    optional: true
+    request:
+      attrs: mr-read-request
+    reply:
+      attrs: mr-read-reply
+    suggested-reply-length: 4096
+
+  - name: mr-extend
+    type: action
+    fd-access: read-write
+    optional: true
+    request:
+      attrs: mr-extend-request
+    reply:
+      attrs: mr-change-reply
+
+  - name: mr-log-entry-appended
+    type: event
+    reply:
+      attrs: mr-log-event
+
+  - name: mr-log-get
+    type: query
+    fd-access: read
+    optional: true
+    request:
+      attrs: mr-log-request
+    reply:
+      attrs: mr-log-reply
+    suggested-reply-length: 131072
diff --git a/Documentation/ctlv/specs/ctlv.yaml b/Documentation/ctlv/specs/ctlv.yaml
new file mode 100644
index 0000000000000..d58f02747e0f0
--- /dev/null
+++ b/Documentation/ctlv/specs/ctlv.yaml
@@ -0,0 +1,379 @@
+# SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)
+%YAML 1.2
+---
+# The root CTLV family, family ID 0 and the first entry in families.yaml. It
+# inherits nothing, and every other family name begins with "ctlv-". Every CTLV
+# device answers these ops in addition to its own family's, and the attrs
+# declared here appear inside family messages: the blob group is the descriptor
+# nest of every family blob attr, the error group the error information written
+# on failure. Nothing here may be reordered or removed.
+
+family:
+  name: ctlv
+
+enums:
+  - name: op-type
+    values:
+      - action
+      - query
+      - event
+
+  # A permission, not a state: what a device currently allows is op.disabled.
+  - name: op-availability
+    values:
+      - fixed
+      - dynamic
+
+  - name: blob-type
+    values:
+      - va
+
+  - name: blob-direction
+    values:
+      - input
+      - output
+      - inout
+
+  - name: validation-reason
+    values:
+      - malformed-message
+      - unknown-attr
+      - unknown-flag
+      - nesting-too-deep
+      - missing-attr
+      - too-many-occurrences
+      - value-out-of-range
+      - bad-length
+      - bad-string
+      - bad-blob-descriptor
+      - stale-generation
+      - noncontiguous-attr
+
+  - name: op-fd-access
+    values:
+      - read
+      - read-write
+
+attr-groups:
+  # One record per family of the chain a device answers, as reported by
+  # families-dump.
+  - name: family
+    attrs:
+      - name: id
+        type: uint
+      # The registry name, also what a uevent carries. Bounded here, this being
+      # the only place a family name is on the wire.
+      - name: name
+        type: string
+        max-length: 63
+      - name: entry
+        attrs: family-entry
+        max-occurrences: unlimited
+
+  # The nest carried by every family blob attr. va uses address; fd and offset
+  # are reserved for later fd-backed types.
+  - name: blob
+    attrs:
+      - name: type
+        enum: blob-type
+      - name: address
+        type: uint
+      - name: fd
+        type: uint
+        max: 2147483647
+      - name: offset
+        type: uint
+      - name: length
+        type: uint
+        min: 1
+
+  # Error information: only what describes the first failure is present.
+  - name: error
+    attrs:
+      - name: reason
+        enum: validation-reason
+      - name: message
+        type: string
+        max-length: 255
+      - name: bad-attr-offset
+        type: uint
+      - name: nest-offset
+        type: uint
+      - name: missing-attr-id
+        type: uint
+      - name: expected-generation
+        type: uint
+      - name: current-generation
+        type: uint
+
+  # One entry per effective op, as reported by ops-dump. Length members that do
+  # not apply to an entry's op type are absent, as are fd access, availability
+  # and disabled for an event.
+  - name: op
+    attrs:
+      - name: id
+        type: uint
+        min: 1
+      - name: type
+        enum: op-type
+      - name: availability
+        enum: op-availability
+      - name: disabled
+        type: bool
+      - name: request-max-len
+        type: uint
+      - name: action-reply-max-len
+        type: uint
+      - name: query-reply-min-len
+        type: uint
+      - name: query-reply-suggested-len
+        type: uint
+      - name: event-record-max-len
+        type: uint
+      # Advances once per op state change on one device.
+      - name: state-generation
+        type: uint
+      - name: entry
+        attrs: op-entry
+        max-occurrences: unlimited
+      - name: fd-access
+        enum: op-fd-access
+
+  # One node of an op's request or reply tree, as reported by op-schema-get. A
+  # node describes a node, so attrs and optional-attrs hold these same members
+  # one level further in. Nothing here is a name: a caller matches the family
+  # chain from families-dump to find the generated UAPI.
+  - name: schema
+    attrs:
+      # Zero in a message root node, as on the wire.
+      - name: attr-id
+        type: uint
+      # enum ctlv_schema_kind.
+      - name: kind
+        type: uint
+      # Zero where the placement may repeat as often as the message has room.
+      - name: max-occurrences
+        type: uint
+      # Inclusive bounds of an integer or enum payload, raw 64-bit values read
+      # according to kind. An enum's values are numbered without gaps.
+      - name: min
+        type: uint
+      - name: max
+        type: uint
+      # Payload length bounds of a string or binary attr, a string's
+      # terminator excluded.
+      - name: min-length
+        type: uint
+      - name: max-length
+        type: uint
+      - name: flags-mask
+        type: uint
+      # enum ctlv_unit, absent when the payload is dimensionless, and a scale
+      # only ever accompanies a unit.
+      - name: unit
+        type: uint
+      - name: scale
+        type: sint
+      - name: blob-direction
+        enum: blob-direction
+      # Mask of BIT(enum ctlv_blob_type): the backings this placement takes.
+      - name: blob-backings
+        type: uint
+      # Maximum external payload length, unrelated to the inline message limit.
+      - name: blob-max-length
+        type: uint
+      - name: blob-alignment
+        type: uint
+      # Levels to climb to the node whose members are this one's as well, one
+      # meaning the node this one is a member of. A node that carries it lists
+      # no members itself.
+      - name: reenters
+        type: uint
+        min: 1
+      # The nodes one level in; required and optional are different attrs.
+      - name: attrs
+        attrs: schema-node
+        recursive: true
+        max-occurrences: unlimited
+      - name: optional-attrs
+        attrs: schema-node
+        recursive: true
+        max-occurrences: unlimited
+      # The root of each of an op's two trees, a node like any other.
+      - name: request
+        attrs: schema-node
+      - name: reply
+        attrs: schema-node
+
+  - name: event
+    attrs:
+      - name: op-id
+        type: uint
+        min: 1
+        max-occurrences: 256
+      - name: queue-len
+        type: uint
+        unit: bytes
+        min: 1
+        max: 16777216
+      - name: queue-used
+        type: uint
+        unit: bytes
+      - name: first-sequence
+        type: uint
+      - name: last-sequence
+        type: uint
+      - name: dropped-count
+        type: uint
+
+attr-sets:
+  - name: family-entry
+    attrs:
+      - family.id
+      - family.name
+
+  - name: op-entry
+    attrs:
+      - op.id
+      - op.type
+    optional-attrs:
+      - op.availability
+      - op.disabled
+      - op.request-max-len
+      - op.action-reply-max-len
+      - op.query-reply-min-len
+      - op.query-reply-suggested-len
+      - op.event-record-max-len
+      - op.fd-access
+
+  - name: op-schema-request
+    attrs: op.id
+
+  # Only the members the node's form has are present.
+  - name: schema-node
+    attrs:
+      - schema.attr-id
+      - schema.kind
+      - schema.max-occurrences
+    optional-attrs:
+      - schema.min
+      - schema.max
+      - schema.min-length
+      - schema.max-length
+      - schema.flags-mask
+      - schema.unit
+      - schema.scale
+      - schema.blob-direction
+      - schema.blob-backings
+      - schema.blob-max-length
+      - schema.blob-alignment
+      - schema.reenters
+      - schema.attrs
+      - schema.optional-attrs
+
+  # The two trees of one op, each absent when the op has no such message. An
+  # event's one tree is reported as the reply.
+  - name: op-schema-info
+    optional-attrs:
+      - schema.request
+      - schema.reply
+
+  # What changed about one op, in the same attrs a dump entry uses.
+  - name: op-change-info
+    attrs:
+      - op.id
+      - op.disabled
+      - op.state-generation
+
+  # The root of an error information message.
+  - name: error-info
+    optional-attrs:
+      - error.reason
+      - error.message
+      - error.bad-attr-offset
+      - error.nest-offset
+      - error.missing-attr-id
+      - error.expected-generation
+      - error.current-generation
+
+  - name: event-subscription
+    attrs: event.op-id
+
+  - name: event-queue-limit
+    attrs: event.queue-len
+
+  - name: event-queue-state
+    attrs:
+      - event.queue-len
+      - event.queue-used
+
+  - name: event-overflow-info
+    attrs:
+      - event.first-sequence
+      - event.last-sequence
+      - event.dropped-count
+
+ops:
+  # The families this device answers, this one first and the device family
+  # last. The only names any reply of this family carries.
+  - name: families-dump
+    type: query
+    fd-access: read
+    reply:
+      attrs: family.entry
+
+  - name: ops-dump
+    type: query
+    fd-access: read
+    reply:
+      attrs: op.entry
+
+  # The request and reply ABI of one op, whether or not it can be called right
+  # now. A removed op answers as one that was never declared.
+  - name: op-schema-get
+    type: query
+    fd-access: read
+    request:
+      attrs: op-schema-request
+    reply:
+      attrs: op-schema-info
+
+  - name: subscriptions-add
+    type: action
+    fd-access: read
+    request:
+      attrs: event-subscription
+
+  - name: subscriptions-remove
+    type: action
+    fd-access: read
+    request:
+      attrs: event-subscription
+
+  - name: event-queue-get
+    type: query
+    fd-access: read
+    reply:
+      attrs: event-queue-state
+
+  - name: event-queue-set
+    type: action
+    fd-access: read
+    request:
+      attrs: event-queue-limit
+
+  # A dynamically available op was enabled or disabled. The name is not about
+  # availability: a later mutable op property reports its state here too.
+  - name: op-changed
+    type: event
+    reply:
+      attrs: op-change-info
+
+  - name: event-overflow
+    type: event
+    reply:
+      attrs: event-overflow-info
+
+  # Payload-free: the record itself is the whole indication.
+  - name: device-removed
+    type: event
diff --git a/Documentation/driver-api/attestation.rst b/Documentation/driver-api/attestation.rst
new file mode 100644
index 0000000000000..f253c848e8565
--- /dev/null
+++ b/Documentation/driver-api/attestation.rst
@@ -0,0 +1,64 @@
+.. SPDX-License-Identifier: GPL-2.0-only
+
+===========
+Attestation
+===========
+
+The attestation subsystem publishes provider devices as descendants of the
+``ctlv-attestation`` family.  It owns common evidence retrieval,
+measurement-register topology and an append-only extension journal.
+Providers retain ownership of native hardware access and immutable capability
+descriptions.
+
+Registering a provider
+======================
+
+A provider defines ``struct attestation_provider`` and passes it to the base
+family through its generated ``pre_init`` callback.  The descriptor, evidence
+capabilities, fixed MR properties, strings and arrays remain immutable until
+``ctlv_destroy()`` or failed-creation unwind completes.
+
+The provider family creates the CTLV device with its own generated family
+descriptor.  Its family-wide operation hooks delegate once to
+``ctlv_attestation_op_pre()`` and ``ctlv_attestation_op_post()`` using the
+attestation parent priv.  The hooks serialize an operation, its native
+callback, journal commit and event emission with one instance mutex.
+
+Fixed MRs are listed in the provider descriptor.  Their property storage
+remains valid until ``ctlv_destroy()`` or failed-creation unwind completes.
+
+MR journal
+==========
+
+MR extension is transactional.  The core allocates the complete journal entry
+and event before invoking ``mr_extend``.  A successful callback is followed
+only by infallible publication, so userspace observes the same ordered
+journal.
+
+``MR_READ`` uses ``mr_read_generation`` only to validate query continuation;
+the returned ``mr.generation`` is the journal boundary at which the values
+were read.
+
+Teardown
+========
+
+CTLV first drains userspace operations.  The base ``pre_fini`` callback then
+withdraws the instance from the kernel registry while provider state and CTLV
+event emission remain available.  CTLV stops events only after that callback
+returns; provider and base ``fini`` callbacks may then release native storage.
+
+TDX provider
+============
+
+``CONFIG_ATTESTATION_TDX`` registers a ``ctlv-attestation-tdx`` instance for
+the native TDX guest service.  MRTD has stable MR ID 0 and is read-only.
+RTMR0 through RTMR3 have IDs 1 through 4 and are readable and extendable with
+SHA-384.
+
+``EVIDENCE_GET`` supports complete raw TDREPORT and Quote objects.  Both
+formats cryptographically bind all architectural TDX measurement registers,
+so successful replies carry the matching MR-journal boundary.  The provider
+exposes no verdict or device-security operation.
+
+The provider consumes only ``<linux/tdx-guest.h>``.  It does not call the TDX
+misc ioctl, configfs TSM-report, or TSM-MR sysfs frontends.
diff --git a/Documentation/driver-api/ctlv.rst b/Documentation/driver-api/ctlv.rst
new file mode 100644
index 0000000000000..461e2977a4839
--- /dev/null
+++ b/Documentation/driver-api/ctlv.rst
@@ -0,0 +1,422 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+=====================
+Writing a CTLV family
+=====================
+
+:Author: Jiri Pirko
+
+A CTLV family is a YAML specification plus the callbacks named by its generated
+header. CTLV validates requests before a callback sees them. The wire ABI is
+:doc:`/userspace-api/ctlv`; family specifications are under
+``Documentation/ctlv/specs``.
+
+The code here is a small invented family, ``ctlv-example``.
+
+Add the specification, registry entry, and output manifest entry in one change::
+
+    Documentation/ctlv/specs/ctlv-example.yaml
+    Documentation/ctlv/families.yaml
+    Documentation/ctlv/generated-files.yaml
+
+``families.yaml`` is append-only. Its array index is the family ID and is part
+of every generated attribute and operation ID. Never reorder, remove, rename,
+or reuse an entry. ``Documentation/ctlv/abi/families.registry.yaml`` is the
+checked-in registry ABI. The output manifest selects the generated UAPI,
+kernel and userspace paths and generation modes.
+
+Generate and verify them with::
+
+    make -C tools/ctlv regen
+    make -C tools/ctlv all
+
+Never edit a generated output. Change the YAML or generator and regenerate it.
+Optional RST reference pages are written to
+``Documentation/output/ctlv/families`` by::
+
+    make -C tools/ctlv docs
+
+Write the specification
+=======================
+
+.. code-block:: yaml
+
+    # SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)
+    %YAML 1.2
+    ---
+    family:
+      name: ctlv-example
+      inherits: ctlv
+      post-init: true
+      pre-fini: true
+
+    attr-groups:
+      - name: item
+        attrs:
+          - name: index
+            type: uint
+            max: 4095
+          - name: label
+            type: string
+            max-length: 63
+          - name: data
+            blob:
+              direction: input
+              allowed-backings: [ va ]
+              max-length: 1048576
+              alignment: 8
+      - name: list
+        attrs:
+          - name: item
+            attrs: item-reply
+            max-occurrences: unlimited
+
+    attr-sets:
+      - name: item-request
+        attrs: item.index
+        optional-attrs:
+          - item.label
+          - item.data
+      - name: item-reply
+        attrs: item.index
+        optional-attrs: item.label
+      - name: items-reply
+        optional-attrs: list.item
+
+    ops:
+      - name: item-set
+        type: action
+        optional: true
+        request:
+          attrs: item-request
+      - name: items-dump
+        type: query
+        availability: dynamic
+        pre-post: true
+        reply:
+          attrs: items-reply
+        suggested-reply-length: 4096
+      - name: item-changed
+        type: event
+        reply:
+          attrs: item-reply
+
+An attribute has one payload form: ``type``, ``enum``, ``flags``, ``attrs``, or
+``blob``. An attr set names one message level. ``attrs`` are required and
+``optional-attrs`` are optional. Its bounds and membership are ABI.
+
+Inheritance and extension points
+================================
+
+A descendant implements only the operations it declares. Inherited operations
+keep the callbacks and operation hooks of their declaring family. Every module
+therefore depends on the module containing its parent implementation.
+
+A parent reserves an extension point with an empty stub set:
+
+.. code-block:: yaml
+
+    attr-groups:
+      - name: device
+        attrs:
+          - name: details
+            attrs: details-extension
+
+    attr-sets:
+      - name: details-extension
+        stub: true
+      - name: device-reply
+        optional-attrs: device.details
+
+A child fills that same set:
+
+.. code-block:: yaml
+
+    family:
+      name: ctlv-example-vendor
+      inherits: ctlv-example
+      pre-init: true
+
+    attr-groups:
+      - name: vendor
+        attrs:
+          - name: serial
+            type: uint
+
+    attr-sets:
+      - name: details-extension
+        optional-attrs: vendor.serial
+
+The parent implementation opens the physical nest and delegates its members:
+
+.. code-block:: c
+
+    if (ctlv_example_device_details_start(reply, &details)) {
+            ret = ctlv_stub_fill(ctx, request_details, &details);
+            ctlv_nest_end(&details);
+            if (ret)
+                    return ret;
+    }
+
+The generated child callback fills it:
+
+.. code-block:: c
+
+    int ctlv_example_vendor_details_extension_fill(
+                            void *priv, struct ctlv_op_ctx *ctx,
+                            const struct ctlv_cursor *request,
+                            struct ctlv_cursor *nest)
+    {
+            ctlv_example_vendor_vendor_serial_put(nest,
+                                                   example_serial(priv));
+            return 0;
+    }
+
+An unfilled stub contributes no nest or message length. Neither side names the
+family on the other side.
+
+Create and destroy a device
+===========================
+
+``ctlv_create()`` takes the leaf family descriptor and leaf initialization
+information:
+
+.. code-block:: c
+
+    struct ctlv_example_vendor_init_info info = {
+            .dev = dev,
+    };
+    struct ctlv_device *ctlvdev;
+
+    ctlvdev = ctlv_create(dev, &ctlv_example_vendor_ctlv_family, &info);
+    if (IS_ERR(ctlvdev))
+            return PTR_ERR(ctlvdev);
+
+A family with ``pre-init: true`` supplies initialization information to its
+direct parent. A typical provider descriptor is static and immutable:
+
+.. code-block:: c
+
+    static const struct ctlv_example_provider example_provider = {
+            .name = "vendor-example",
+            .ops = &example_provider_ops,
+    };
+
+    const void *ctlv_example_vendor_pre_init(const void *init_info)
+    {
+            return &example_provider;
+    }
+
+The leaf's per-device ``init_info`` still reaches its own ``init`` callback; it
+is not forwarded as the parent's descriptor. ``pre_init`` runs leaf to root and
+may return an ``ERR_PTR()``. It must not acquire resources or return automatic
+storage.
+
+Each family supplies ``priv_size``, ``init``, and ``fini``. The YAML flags add
+``pre_init``, ``post_init``, and ``pre_fini`` callbacks. Creation order is::
+
+    leaf -> root     pre_init
+    root -> leaf     init
+                     freeze published operations; start event admission
+    leaf -> root     post_init
+                     register the character device
+
+Select optional operations and their initial dynamic state in ``init``. A
+``post_init`` callback may publish the device to kernel consumers because all
+family privs and event emission are then available.
+
+Normal destruction is ordered as follows::
+
+    withdraw userspace access; drain admitted operation callbacks
+    root -> leaf     pre_fini
+    stop and drain event contexts; queue DEVICE_REMOVED
+    leaf -> root     fini
+
+A family published in ``post_init`` withdraws and drains its consumers in
+``pre_fini``. Provider state and events remain available until all
+``pre_fini`` callbacks finish. ``ctlv_destroy()`` consumes the reference from
+``ctlv_create()``; open file descriptions remain only to drain queued records
+and otherwise fail with ``-ENODEV``.
+
+If ``init`` fails, that callback releases its partial resources and CTLV calls
+``fini`` only for initialized ancestors. A failure after initialization uses
+the normal ``pre_fini`` and ``fini`` ordering.
+
+CTLV allocates one zeroed, cache-line-aligned priv per family. Direct neighbors
+are available without naming their types globally:
+
+.. code-block:: c
+
+    parent = ctlv_priv_parent(priv);
+    child = ctlv_priv_child(priv);
+
+During ``init``, the child is not initialized yet. During ``pre_fini`` it still
+is; during ``fini`` it has already been finalized. Allocate a separately
+aligned object when cache-line alignment is insufficient.
+
+Implement operations
+====================
+
+Action
+------
+
+Generated getters read only validated placements and generated serializers
+write only declared replies:
+
+.. code-block:: c
+
+    int ctlv_example_item_set_action(void *priv, struct ctlv_op_ctx *ctx,
+                                     const struct ctlv_cursor *request,
+                                     struct ctlv_cursor *reply)
+    {
+            u64 index = ctlv_example_item_index_get(request);
+
+            if (item_busy(priv, index))
+                    return ctlv_op_error(ctx, -EBUSY, "item is busy");
+            return item_set(priv, index);
+    }
+
+Use ``_present()`` for optional attributes 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_items_dump_query(void *priv, struct ctlv_op_ctx *ctx,
+                                      const struct ctlv_cursor *request,
+                                      struct ctlv_cursor *reply)
+    {
+            struct ctlv_example *example = priv;
+            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_list_item_start(reply, &item))
+                            return ctlv_op_query_more(ctx, generation, i + 1);
+                    ctlv_example_item_index_put(&item, i);
+                    ctlv_nest_end(&item);
+            }
+            return ctlv_op_query_done(ctx, generation);
+    }
+
+A continuation cursor is nonzero and advances. Every continuing fragment
+completes a logical leaf. Call ``ctlv_op_query_more()`` while cursors for open
+continuation nests are alive. A generation mismatch returns ``-ESTALE``.
+
+Hooks and availability
+======================
+
+The leaf family's hooks wrap each effective non-core action or query. An
+operation with ``pre-post: true`` has its declaring family's pair inside them::
+
+    family pre -> operation pre -> availability check -> callback
+               -> operation post -> family 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 priv of the family implementing it.
+
+Optional and dynamic operations are separate choices:
+
+.. code-block:: c
+
+    /* During init: publish this optional operation on this device. */
+    ctlv_example_item_set_provide(ctlvdev);
+
+    /* At runtime: temporarily refuse a published dynamic operation. */
+    ctlv_example_items_dump_disable(ctlvdev);
+    ctlv_example_items_dump_enable(ctlvdev);
+
+Declare the latter with ``availability: dynamic``. An unpublished optional
+operation has no schema entry. A disabled operation remains discoverable and
+returns ``-EOPNOTSUPP``; a state change emits ``op-changed``.
+
+Blobs
+=====
+
+A blob attribute 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_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.
+
+Events
+======
+
+.. code-block:: c
+
+    ctx = ctlv_example_item_changed_create(ctlvdev, &event, GFP_KERNEL);
+    if (IS_ERR(ctx))
+            return PTR_ERR(ctx);
+    ctlv_example_item_index_put(event, index);
+    return ctlv_event_emit(ctx);
+
+Exactly one of ``ctlv_event_emit()`` and ``ctlv_event_abort()`` ends the context. The
+GFP argument covers subscriber copies; atomic producers use ``GFP_NOWAIT`` or
+``GFP_ATOMIC``. Event APIs are not called from interrupt context, and hooks do
+not run around events.
+
+If an event occurred but allocation failed, commit the state change and call
+``ctlv_event_lost()``. It neither allocates nor sleeps. Do not use it for an
+aborted event or for per-subscriber drops already tracked by
+``ctlv_event_emit()``.
+
+If hardware changed before an event context could be allocated, the family
+must commit its invalidation and explicitly report the missing notification:
+
+.. code-block:: c
+
+    invalidate_stale_state(priv);
+    priv->generation++;
+
+    ctx = ctlv_example_thing_happened_create(ctlvdev, &event, GFP_ATOMIC);
+    if (IS_ERR(ctx)) {
+            if (PTR_ERR(ctx) == -ENOMEM)
+                    ctlv_event_lost(ctlvdev,
+                                    CTLV_EXAMPLE_OP_THING_HAPPENED);
+            return;
+    }
+    ctlv_example_generation_put(event, priv->generation);
+    ctlv_op_emit(ctx);
+
+``ctlv_event_lost()`` allocates nothing and does not sleep. For each subscribed
+file description it advances the event sequence and aggregates the loss into
+the preallocated ``EVENT_OVERFLOW`` record. The caller keeps the device alive
+and serializes the report with normal emission of that event. Like event
+emission, it is not called from interrupt context. It is only for an event that
+actually occurred but could not be constructed: do not call it for an aborted
+event or for copy-allocation and full-queue drops already accounted for by
+``ctlv_op_emit()``. Reports after event shutdown or the terminal
+``DEVICE_REMOVED`` record are ignored.
+
+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
+attribute. A family implementation does not build that; it adds its own errno
+and its reply.
+
+Configuration
+=============
+
+``CONFIG_CTLV``
+    CTLV. A family implementation selects it.
diff --git a/Documentation/driver-api/index.rst b/Documentation/driver-api/index.rst
index 6601a258690f8..ecf82a9330fcf 100644
--- a/Documentation/driver-api/index.rst
+++ b/Documentation/driver-api/index.rst
@@ -37,6 +37,8 @@ of interest to most developers working on device drivers.
 
    early-userspace/index
    connector
+   ctlv
+   attestation
    device-io
    devfreq
    dma-buf
diff --git a/Documentation/userspace-api/ctlv.rst b/Documentation/userspace-api/ctlv.rst
new file mode 100644
index 0000000000000..5ebca3d4d94af
--- /dev/null
+++ b/Documentation/userspace-api/ctlv.rst
@@ -0,0 +1,507 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+==================
+CTLV userspace ABI
+==================
+
+:Author: Jiri Pirko
+
+CTLV is a transport for device control interfaces. A family describes what its
+devices accept in YAML, a generator turns that into kernel metadata and UAPI
+headers, and CTLV validates every message before a family callback sees it.
+Userspace sees one character device per instance, one ioctl, and ``read()`` for
+events.
+
+This document is the ABI. What each family accepts is specified under
+``Documentation/ctlv/specs``; writing a family is :doc:`/driver-api/ctlv`.
+
+Why a TLV transport
+===================
+
+CTLV puts the rules of every operation in one description and validates them
+once:
+
+- One ioctl carries every operation of every family, so a new operation is a
+  new specification entry, not a new ioctl number.
+- Attributes are optional or required by declaration, so a message can grow
+  without breaking a caller that does not know the new attribute.
+- An unknown attribute is refused on a request and tolerated on a reply, so a
+  new kernel can say more to an old program. A request may mark an attribute an
+  old kernel is welcome to skip, so a new program can say more too.
+- Bounds, lengths, occurrence counts and nesting depth are checked before a
+  family callback runs.
+
+Devices
+=======
+
+Each registered instance appears as a character device in the ``ctlv`` class
+with a dynamic minor::
+
+    /dev/ctlv0
+    /sys/class/ctlv/ctlv0
+
+Sysfs shows class membership, the ``dev`` number and the device-model link to
+the parent device. There is no family sysfs attribute; ``families-dump`` on an
+open descriptor is the authoritative answer to what a device is.
+
+Each open file description has its own event subscriptions and event queue.
+``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. Events are readable and subscribable through both.
+``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 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 filtered to the ctlv subsystem, and enable it
+    2. enumerate the existing ctlv class devices
+    3. drain the events already queued on the monitor
+    4. deduplicate by sysfs path
+    5. open the device node
+    6. ask families-dump 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.
+    SUBSYSTEM=="ctlv", ENV{CTLV_FAMILY}=="ctlv-accelerator-foo", \
+        GROUP="accel", MODE="0660"
+
+    # Anything descended from a family.
+    SUBSYSTEM=="ctlv", ENV{CTLV_COMPATIBLE_1}=="ctlv-accelerator", \
+        TAG+="uaccess"
+
+    # A stable name from the parent device, which is deployment policy.
+    SUBSYSTEM=="ctlv", ENV{CTLV_FAMILY}=="ctlv-accelerator-foo", \
+        SYMLINK+="accel/by-path/$env{ID_PATH}"
+
+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.
+
+Wire format
+===========
+
+A message is a tree of attributes. Every attribute begins with the same
+header, at an eight-byte boundary::
+
+    struct ctlv_attr {
+            __u32 len;              /* header + payload, without padding */
+            __u32 flags;            /* CTLV_ATTR_F_* */
+            __aligned_u64 attr_id;  /* complete ID, or 0 for a root */
+    };
+
+One unsigned integer attribute with an eight-byte payload, on the wire::
+
+     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                              |
+    +---------------------------------------------------------------+
+    |                                                               |
+    +                       attr_id                                 +
+    |                                                               |
+    +---------------------------------------------------------------+
+    |                                                               |
+    +                       payload                                 +
+    |                                                               |
+    +---------------------------------------------------------------+
+
+The rules that make a tree out of that:
+
+- ``CTLV_ALIGNTO`` is 8 and ``CTLV_ALIGN()`` rounds up to it. Every attribute
+  starts at a multiple of eight.
+- ``len`` counts this header plus this attribute's payload, not its own
+  trailing padding.
+- A nested 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_ATTR_F_NESTED`` is set exactly on a root and on a nest.
+- A message begins with one root attribute, whose ``attr_id`` is
+  ``CTLV_ATTR_ROOT`` (zero) and whose payload is the message. A root never
+  appears inside a nest, and a nest never carries the root ID.
+- 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.
+- Nesting is limited to ``CTLV_MAX_NEST_DEPTH`` levels, the root being level
+  zero.
+
+A whole message with every offset, for a request of one integer and one nest
+carrying a string and a further nest::
+
+    offset  attribute                       len  flags   contents
+    ------  ------------------------------  ---  ------  ----------------
+         0  root                            120  NESTED  attr_id = 0
+        16  .. chunks                        24  -       8-byte integer
+        40  .. chunk                         80  NESTED
+        56     .. label                      19  -       "ab" and its NUL
+        80     .. item                       40  NESTED
+        96        .. value                   24  -       8-byte integer
+       120  end of message
+
+    +--------------------------------------------------------------+ 0
+    | root: len = 120, flags = NESTED, attr_id = 0                 |
+    +--------------------------------------------------------------+ 16
+    | chunks: len = 24 | payload: 8 bytes                          |
+    +--------------------------------------------------------------+ 40
+    | chunk: len = 80, flags = NESTED                              |
+    |   +--------------------------------------------------------+ | 56
+    |   | label: len = 19 | payload: 'a' 'b' 0 | 5 bytes padding | |
+    |   +--------------------------------------------------------+ | 80
+    |   | item: len = 40, flags = NESTED                         | |
+    |   |   +--------------------------------------------------+ | | 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 nest's
+children advances by ``CTLV_ALIGN(child.len)``, a walk of one payload by
+``child.len``.
+
+An attribute ID names the family that declared it, a group within that family
+and an attribute within that group::
+
+    63           48 47           32 31                             0
+    +--------------+--------------+--------------------------------+
+    |    family    |    group     |             attr               |
+    +--------------+--------------+--------------------------------+
+
+    CTLV_ATTR(family, group, attr)
+    CTLV_ATTR_FAMILY(attr) / CTLV_ATTR_GROUP(attr) / CTLV_ATTR_NUMBER(attr)
+
+An operation ID is the same shape with the group bits zero::
+
+    CTLV_OP(family, op)
+    CTLV_OP_FAMILY(op) / CTLV_OP_NUMBER(op)
+
+Use generated complete IDs. A family's header defines every ID it declares
+and includes its parent's.
+
+Request occurrence order
+------------------------
+
+Occurrences of one attribute ID must be contiguous within each request root or
+nest. ``A A B`` is valid, while ``A B A`` is not. An ignored unknown attribute
+is not an occurrence of any known attribute, but it ends the preceding run, so
+``A ignored-unknown A`` is also invalid. Different IDs otherwise have no
+required numeric or schema order.
+
+Attributes a kernel may skip
+----------------------------
+
+A request attribute, the root aside, may carry
+``CTLV_ATTR_F_IGNORE_IF_UNKNOWN``. If no family the device answers declares
+that complete ID, the kernel steps over the whole attribute without looking
+inside it; without the bit, an attribute the schema does not place where it
+appears fails the request as it always has.
+
+The bit forgives an ID this kernel has never heard of and nothing else. An ID
+the device's schema declares somewhere is held to that schema, so an attribute
+sent where it does not belong fails whether the bit is set or not, and one sent
+where it does belong is checked as usual. Every other rule applies too: the
+length has to fit its nest and the header may carry no bit the format does not
+define. Replies and events never carry it.
+
+This is how a program built against a newer version of a family talks to an
+older kernel. What that kernel knows is validated, what it does not is
+ignored, and a caller that has to know which is which asks ``op-schema-get``
+first.
+
+Executing an operation
+======================
+
+One ioctl executes every operation::
+
+    struct ctlv_op_exec {
+            __aligned_u64 op_id;
+            __aligned_u64 request;      /* struct ctlv_attr __user * */
+            __aligned_u64 reply;        /* struct ctlv_attr __user * */
+            __u32 request_len;
+            __u32 reply_len;
+            __aligned_u64 generation;   /* queries only */
+            __aligned_u64 cursor;       /* queries only */
+            __aligned_u64 reserved[2];  /* must be zero */
+    };
+
+    #define CTLV_IOC_OP_EXEC _IOWR(0xBB, 0x00, struct ctlv_op_exec)
+
+``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``. The pointers are
+fixed-width so a 32-bit and a 64-bit process pass the same structure, and in
+place of a size field the ioctl number encodes the size and ``reserved``, which
+must be zero, covers compatible growth.
+
+Every action and query carries a physical request root, including an empty
+request. ``request_len`` is therefore at least one attr header and at most the
+1 MiB transport limit. The ``request-max-len`` reported by ``ops-dump`` is the
+maximum request composed from the known schema; a newer caller may exceed it
+with well-formed unknown attrs marked ``IGNORE_IF_UNKNOWN``, up to the
+transport limit.
+
+The three kinds of operation differ in what they answer:
+
+action
+    Executed once and acknowledged. An action with no reply takes
+    ``reply_len`` zero; one with a bounded reply has its maximum in
+    ``ops-dump``.
+
+query
+    Executed once and answered in as many fragments as it needs, using
+    ``generation`` and ``cursor``.
+
+event
+    Not executed. A device produces records and a subscribed file description
+    reads them.
+
+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 attribute, the offset of
+the nest it was in, the ID of a missing attribute, and for a stale query the
+expected and the current generation. A buffer too small leaves it unwritten;
+the errno is authoritative either way.
+
+What the transport answers with, as against a family's own callback:
+
+``ENOTTY``
+    Not ``CTLV_IOC_OP_EXEC``; this transport has one ioctl.
+
+``EINVAL``
+    A reserved field 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.
+
+``EFAULT``
+    The structure, the request or the reply was not accessible.
+
+``EOPNOTSUPP``
+    The device does not publish the operation, publishes it but has it
+    disabled, or the operation is an event, which is read rather than executed.
+
+``EACCES``
+    The fd lacks the operation's declared authority, or an ``O_WRONLY`` open
+    was attempted.
+
+``EMSGSIZE``
+    ``reply_len`` is smaller than the smallest fragment the operation can
+    answer with. Nothing was executed.
+
+``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.
+
+``read()`` answers ``EAGAIN`` when no record is queued on a non-blocking
+description, ``EINTR`` when a blocking read was interrupted, ``EMSGSIZE`` when
+the buffer cannot hold the record at the head of the queue, and ``ENODEV``
+once a removed device's queue has been drained.
+
+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_ATTR_F_FRAG_MORE`` when the answer continues,
+  and so does every nest 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 nest.
+
+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 nest does not carry
+it, so a reader knows whether to append or to open a new nest beside it.
+
+Every continuing fragment adds at least one complete logical attr 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.
+
+Events
+======
+
+An event reaches a file description that asked for it, and only that one:
+
+1. subscribe with the ``subscriptions-add`` action, naming operation IDs;
+2. read records with ``read()``, one complete record per call;
+3. unsubscribe with ``subscriptions-remove``.
+
+``poll()`` reports readability when a record is queued. Each record is a
+header followed by exactly one root attribute::
+
+    struct ctlv_event_hdr {
+            __u32 length;             /* header + aligned root */
+            __u32 flags;              /* zero */
+            __aligned_u64 op_id;      /* the event op that produced it */
+            __aligned_u64 sequence;   /* per file description */
+    };
+
+One ``read()`` returns one record, the header and the aligned root::
+
+    +---------------------------------------------------------------+ 0
+    | length = 24 + CTLV_ALIGN(root.len)     | flags = 0            |
+    +---------------------------------------------------------------+ 8
+    | op_id: the event operation that produced this record          |
+    +---------------------------------------------------------------+ 16
+    | sequence: counted per file description                        |
+    +---------------------------------------------------------------+ 24
+    | root: len, flags = NESTED, attr_id = 0                        |
+    |   the event's attributes, exactly as a reply carries them      |
+    +---------------------------------------------------------------+ length
+
+A buffer shorter than ``length`` reads nothing and fails with ``-EMSGSIZE``. A
+record is one message, bounded by ``CTLV_MAX_INLINE_MESSAGE_LEN``. A sequence
+number is assigned to every eligible record, dropped ones included, so a gap in
+the sequence is exactly what was lost.
+
+The queue is per file description: ``event-queue-get`` reports its length and
+how much is in use, ``event-queue-set`` changes it up to
+``CTLV_MAX_EVENT_QUEUE_LEN``. A record that does not fit is dropped, and the
+next read returns an ``event-overflow`` record carrying the first and last
+sequence numbers lost and how many records that was.
+
+Two events come from the root family:
+
+op-changed
+    An operation with dynamic availability was enabled or disabled. The record
+    carries the operation ID, the new state, and the state generation that
+    ``ops-dump`` also reports, so a client can order dump against event.
+
+device-removed
+    The device is gone. Operations fail from then on and the descriptor stays
+    valid until it is closed.
+
+Blobs
+=====
+
+An operation that moves more data than a message should carry declares a blob
+attribute, and the caller passes a descriptor instead of the data: a nest
+carrying the backing type, the length and the identifier of the memory. One
+backing is defined:
+
+``va``
+    Anonymous userspace memory of the calling process, named by an address in
+    ``blob.address``.
+
+The backings an attribute 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.
+
+Introspection
+=============
+
+Three queries describe a device to a program that was not compiled against it.
+The CTLV core answers all three on every device.
+
+``families-dump``
+    The device's family chain, root first, as a numeric ID and a name per
+    entry. The authoritative answer to what the device is.
+
+``ops-dump``
+    One entry per published operation: its ID, kind, required fd access,
+    whether its availability is fixed or dynamic, whether it is currently
+    disabled, and the message lengths that apply on this device. An
+    unpublished operation has no entry and is indistinguishable from one no
+    family ever declared. Event entries have no fd-access field.
+
+``op-schema-get``
+    The whole tree of one operation: every attribute of the request and the
+    reply, with its payload form, 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 members are those of a level already described carries
+``schema.reenters``, saying how many levels up that level is. A consumer that
+follows ``reenters`` handles any depth.
+
+The lengths in ``ops-dump`` 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.
+
+Limits
+======
+
+Implementation limits, not encoded maxima of the wire fields, so raising one
+later is a compatible change::
+
+    CTLV_MAX_INLINE_MESSAGE_LEN   1 MiB    request roots, action replies,
+                                           query fragments, event roots
+    CTLV_MAX_ERROR_LEN            16 KiB   error information
+    CTLV_MAX_NEST_DEPTH           32       levels, root at zero
+    CTLV_DEFAULT_QUERY_REPLY_LEN  64 KiB   suggested query buffer
+    CTLV_MAX_EVENT_QUEUE_LEN      16 MiB   per file description
diff --git a/Documentation/userspace-api/index.rst b/Documentation/userspace-api/index.rst
index a68b1bea57a85..d1b53c4e16ebb 100644
--- a/Documentation/userspace-api/index.rst
+++ b/Documentation/userspace-api/index.rst
@@ -45,6 +45,7 @@ Devices and I/O
    :maxdepth: 1
 
    accelerators/ocxl
+   ctlv
    dma-buf-heaps
    dma-buf-alloc-exchange
    fwctl/index
diff --git a/Documentation/userspace-api/ioctl/ioctl-number.rst b/Documentation/userspace-api/ioctl/ioctl-number.rst
index 2fc53093752d1..e545669c773c7 100644
--- a/Documentation/userspace-api/ioctl/ioctl-number.rst
+++ b/Documentation/userspace-api/ioctl/ioctl-number.rst
@@ -386,6 +386,8 @@ Code  Seq#    Include File                                             Comments
                                                                        <mailto:linux-hyperv@vger.kernel.org>
 0xBA  00-0F  uapi/linux/liveupdate.h                                   Pasha Tatashin
                                                                        <mailto:pasha.tatashin@soleen.com>
+0xBB  00-0F  uapi/linux/ctlv.h                                         CTLV
+                                                                       <mailto:jiri@resnulli.us>
 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
diff --git a/Documentation/virt/coco/tdx-guest.rst b/Documentation/virt/coco/tdx-guest.rst
index 46e316db6bb47..759497b1434a2 100644
--- a/Documentation/virt/coco/tdx-guest.rst
+++ b/Documentation/virt/coco/tdx-guest.rst
@@ -50,3 +50,21 @@ TDX reference material is collected here:
 https://www.intel.com/content/www/us/en/developer/articles/technical/intel-trust-domain-extensions.html
 
 The driver is based on TDX module specification v1.0 and TDX GHCI specification v1.0.
+
+Kernel clients
+==============
+
+``<linux/tdx-guest.h>`` exposes the same native service to one in-kernel
+client.  The client receives the misc device as its lifetime anchor and a
+complete ``struct tdx_guest_ops``.  The operations retrieve TDREPORT or Quote
+bytes, read MRTD/RTMR values, extend an RTMR, and return immutable construction
+fields.
+
+Registering a client attaches it immediately when the service is already
+available.  Otherwise attachment occurs when the TDX guest driver finishes
+initialization.  Driver removal calls the client's remove callback before
+freeing report or Quote buffers.  Client unregistration similarly drains the
+attachment before returning.
+
+The misc ioctl, TSM-report configfs interface, and TSM-MR sysfs attributes
+remain independent frontends over the same native serialization and buffers.
diff --git a/MAINTAINERS b/MAINTAINERS
index 31699b112d3ef..a05d10976011f 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -4331,6 +4331,17 @@ F:	rust/kernel/sync/atomic.rs
 F:	rust/kernel/sync/atomic/
 F:	rust/kernel/sync/refcount.rs
 
+ATTESTATION SUBSYSTEM
+M:	Jiri Pirko <jiri@nvidia.com>
+L:	linux-security-module@vger.kernel.org
+S:	Supported
+F:	Documentation/ctlv/abi/ctlv-attestation*
+F:	Documentation/ctlv/specs/ctlv-attestation*
+F:	Documentation/driver-api/attestation.rst
+F:	drivers/attestation/
+F:	include/linux/attestation*
+F:	include/uapi/linux/ctlv_attestation*
+
 ATTO EXPRESSSAS SAS/SATA RAID SCSI DRIVER
 M:	Bradley Grove <linuxdrivers@attotech.com>
 L:	linux-scsi@vger.kernel.org
@@ -7001,6 +7012,18 @@ M:	Jaya Kumar <jayakumar.alsa@gmail.com>
 S:	Maintained
 F:	sound/pci/cs5535audio/
 
+CTLV SUBSYSTEM
+M:	Jiri Pirko <jiri@resnulli.us>
+L:	linux-kernel@vger.kernel.org
+S:	Maintained
+F:	Documentation/ctlv/
+F:	Documentation/driver-api/ctlv.rst
+F:	Documentation/userspace-api/ctlv.rst
+F:	drivers/ctlv/
+F:	include/linux/ctlv*.h
+F:	include/uapi/linux/ctlv*.h
+F:	tools/ctlv/
+
 CTU CAN FD DRIVER
 M:	Pavel Pisa <pisa@cmp.felk.cvut.cz>
 M:	Ondrej Ille <ondrej.ille@gmail.com>
@@ -29646,6 +29669,9 @@ L:	linux-coco@lists.linux.dev
 L:	kvm@vger.kernel.org
 S:	Supported
 T:	git git://git.kernel.org/pub/scm/linux/kernel/git/tip/tip.git x86/tdx
+F:	Documentation/virt/coco/tdx-guest.rst
+F:	drivers/virt/coco/tdx-guest/
+F:	include/linux/tdx-guest.h
 N:	tdx
 K:	\b(tdx)
 
diff --git a/drivers/Kconfig b/drivers/Kconfig
index f2bed2ddeb662..971db1f0192ca 100644
--- a/drivers/Kconfig
+++ b/drivers/Kconfig
@@ -25,6 +25,10 @@ source "drivers/cache/Kconfig"
 
 source "drivers/connector/Kconfig"
 
+source "drivers/ctlv/Kconfig"
+
+source "drivers/attestation/Kconfig"
+
 source "drivers/firmware/Kconfig"
 
 source "drivers/fwctl/Kconfig"
diff --git a/drivers/Makefile b/drivers/Makefile
index 0841ea851847e..2b4dfc8e256b0 100644
--- a/drivers/Makefile
+++ b/drivers/Makefile
@@ -135,6 +135,8 @@ obj-$(CONFIG_MEMSTICK)		+= memstick/
 obj-$(CONFIG_INFINIBAND)	+= infiniband/
 obj-y				+= firmware/
 obj-$(CONFIG_FWCTL)		+= fwctl/
+obj-$(CONFIG_CTLV)		+= ctlv/
+obj-$(CONFIG_ATTESTATION)	+= attestation/
 obj-$(CONFIG_CRYPTO)		+= crypto/
 obj-$(CONFIG_SUPERH)		+= sh/
 obj-y				+= clocksource/
diff --git a/drivers/attestation/Kconfig b/drivers/attestation/Kconfig
new file mode 100644
index 0000000000000..139bcc7100191
--- /dev/null
+++ b/drivers/attestation/Kconfig
@@ -0,0 +1,26 @@
+# SPDX-License-Identifier: GPL-2.0-only
+menuconfig ATTESTATION
+	tristate "Attestation"
+	depends on CTLV
+	help
+	  Provides a CTLV family for evidence, measurement registers,
+	  and an append-only measurement journal.
+
+	  Providers register one instance for a physical or logical device and
+	  translate the common operations to their native service.
+
+	  If you are unsure, say N.
+
+if ATTESTATION
+
+config ATTESTATION_TDX
+	tristate "TDX attestation provider"
+	depends on TDX_GUEST_DRIVER
+	help
+	  Exposes TDREPORT, Quote, MRTD and RTMR operations through the common
+	  attestation CTLV family. The native TDX misc, TSM-report and TSM-MR
+	  interfaces remain available independently.
+
+	  If you are unsure, say N.
+
+endif # ATTESTATION
diff --git a/drivers/attestation/Makefile b/drivers/attestation/Makefile
new file mode 100644
index 0000000000000..d56df9adaa757
--- /dev/null
+++ b/drivers/attestation/Makefile
@@ -0,0 +1,10 @@
+# SPDX-License-Identifier: GPL-2.0
+obj-$(CONFIG_ATTESTATION) += attestation.o
+
+attestation-y := core/core.o core/ctlv.o core/events.o core/mr.o \
+		 generated/ctlv_attestation_gen.o
+
+obj-$(CONFIG_ATTESTATION_TDX) += attestation-tdx.o
+
+attestation-tdx-y := providers/tdx.o \
+		     generated/ctlv_attestation_tdx_gen.o
diff --git a/drivers/attestation/core/core.c b/drivers/attestation/core/core.c
new file mode 100644
index 0000000000000..3fb58f344663b
--- /dev/null
+++ b/drivers/attestation/core/core.c
@@ -0,0 +1,354 @@
+// SPDX-License-Identifier: GPL-2.0-only
+#include <crypto/hash_info.h>
+#include <linux/cleanup.h>
+#include <linux/ctlv.h>
+#include <linux/device.h>
+#include <linux/err.h>
+#include <linux/limits.h>
+#include <linux/module.h>
+#include <linux/overflow.h>
+#include <linux/slab.h>
+#include <linux/string.h>
+
+#include "internal.h"
+
+static DEFINE_XARRAY(attestation_instances);
+
+static DEFINE_MUTEX(attestation_registry_lock);
+static unsigned long attestation_next_index;
+
+static bool attestation_algorithm_valid(enum hash_algo algorithm)
+{
+	return algorithm >= 0 && algorithm < HASH_ALGO__LAST && hash_digest_size[algorithm] &&
+	       hash_digest_size[algorithm] <= HASH_MAX_DIGESTSIZE;
+}
+
+static int attestation_mr_props_validate(const struct attestation_provider *provider,
+					 const struct attestation_mr_props *props)
+{
+	size_t index;
+
+	if (!props || !props->name || !*props->name || strlen(props->name) > 128 ||
+	    !props->algorithms || !props->algorithms_count || props->algorithms_count > 21)
+		return -EINVAL;
+	for (index = 0; index < props->algorithms_count; index++) {
+		enum hash_algo algorithm = props->algorithms[index];
+
+		if (!attestation_algorithm_valid(algorithm) ||
+		    (index && props->algorithms[index - 1] >= algorithm))
+			return -EINVAL;
+	}
+	if (props->readable && !provider->mr_read)
+		return -EINVAL;
+	if (props->extendable && !provider->mr_extend)
+		return -EINVAL;
+	return 0;
+}
+
+static int attestation_evidence_caps_validate(const struct attestation_provider *provider)
+{
+	const struct attestation_evidence_caps *caps = provider->evidence_caps;
+	size_t object_index;
+
+	if (!caps)
+		return provider->evidence_get ? -EINVAL : 0;
+	if (!provider->evidence_get || !caps->objects || !caps->objects_count ||
+	    caps->objects_count > 16 || caps->min_challenge_length > caps->max_challenge_length ||
+	    caps->max_challenge_length > 4096 || !caps->max_total_output_length)
+		return -EINVAL;
+	for (object_index = 0; object_index < caps->objects_count; object_index++) {
+		const struct attestation_evidence_supported_object *object =
+			&caps->objects[object_index];
+		size_t index;
+
+		if (!object->format || !*object->format || strlen(object->format) > 128 ||
+		    !object->max_length || object->max_length > UINT_MAX ||
+		    object->max_length > caps->max_total_output_length)
+			return -EINVAL;
+		for (index = 0; index < object_index; index++) {
+			const struct attestation_evidence_supported_object *prior =
+				&caps->objects[index];
+
+			if (!strcmp(prior->format, object->format))
+				return -EINVAL;
+		}
+	}
+	return 0;
+}
+
+int attestation_provider_validate(const struct attestation_provider *provider)
+{
+	size_t index;
+	int ret;
+
+	if (!provider)
+		return -EINVAL;
+	ret = attestation_evidence_caps_validate(provider);
+	if (ret)
+		return ret;
+	if (!!provider->mrs != !!provider->mrs_count)
+		return -EINVAL;
+	if ((provider->mr_read || provider->mr_extend) && !provider->mrs_count)
+		return -EINVAL;
+	for (index = 0; index < provider->mrs_count; index++) {
+		ret = attestation_mr_props_validate(provider, &provider->mrs[index]);
+		if (ret)
+			return ret;
+	}
+	return 0;
+}
+
+static bool attestation_parent_exists(struct device *parent)
+{
+	struct attestation *att;
+	unsigned long index;
+
+	xa_for_each(&attestation_instances, index, att)
+		if (ctlv_device_parent(att->ctlvdev) == parent)
+			return true;
+	return false;
+}
+
+static int attestation_registry_insert(struct attestation *att)
+{
+	unsigned long index;
+	void *old;
+	int ret;
+
+	guard(mutex)
+		(&attestation_registry_lock);
+	if (attestation_next_index > UINT_MAX)
+		return -ENOSPC;
+	index = attestation_next_index;
+	ret = xa_reserve(&attestation_instances, index, GFP_KERNEL);
+	if (ret)
+		return ret;
+
+	xa_lock(&attestation_instances);
+	if (attestation_parent_exists(ctlv_device_parent(att->ctlvdev))) {
+		__xa_erase(&attestation_instances, index);
+		ret = -EEXIST;
+		goto out_unlock;
+	}
+	old = __xa_store(&attestation_instances, index, att, GFP_NOWAIT);
+	ret = xa_err(old);
+	if (!ret) {
+		att->index = index;
+		attestation_next_index++;
+	}
+out_unlock:
+	xa_unlock(&attestation_instances);
+	return ret;
+}
+
+static void attestation_registry_remove(struct attestation *att)
+{
+	xa_erase(&attestation_instances, att->index);
+}
+
+bool attestation_registered(struct attestation *att)
+{
+	bool registered;
+
+	lockdep_assert_held(&att->lock);
+	xa_lock(&attestation_instances);
+	registered = xa_get_mark(&attestation_instances, att->index, ATTESTATION_REGISTERED);
+	xa_unlock(&attestation_instances);
+	return registered;
+}
+
+void attestation_mr_changed(struct attestation *att)
+{
+	lockdep_assert_held(&att->lock);
+	att->log->generation++;
+	att->mr_read_generation++;
+}
+
+void attestation_stop(struct attestation *att)
+{
+	lockdep_assert_held(&att->lock);
+	xa_lock(&attestation_instances);
+	__xa_clear_mark(&attestation_instances, att->index, ATTESTATION_REGISTERED);
+	xa_unlock(&attestation_instances);
+}
+
+static struct attestation_mr *attestation_mr_alloc(struct attestation *att,
+						   const struct attestation_mr_props *props)
+{
+	struct attestation_mr *mr;
+	int ret;
+
+	ret = attestation_mr_props_validate(att->provider, props);
+	if (ret)
+		return ERR_PTR(ret);
+	if (xa_load(&att->mrs, props->id))
+		return ERR_PTR(-EEXIST);
+	mr = kzalloc_obj(*mr, GFP_KERNEL);
+	if (!mr)
+		return ERR_PTR(-ENOMEM);
+	mr->props = props;
+	ret = xa_insert(&att->mrs, props->id, mr, GFP_KERNEL);
+	if (ret) {
+		kfree(mr);
+		return ERR_PTR(ret);
+	}
+	return mr;
+}
+
+struct attestation_mr *attestation_mr_lookup_live(struct attestation *att, unsigned int mr_id)
+{
+	struct attestation_mr *mr;
+
+	lockdep_assert_held(&att->lock);
+	mr = xa_load(&att->mrs, mr_id);
+	return mr ? mr : ERR_PTR(-ENOENT);
+}
+
+void attestation_provide_ops(struct attestation *att)
+{
+	const struct attestation_provider *provider = att->provider;
+	struct ctlv_device *ctlvdev = att->ctlvdev;
+
+	if (provider->evidence_caps) {
+		ctlv_attestation_evidence_get_provide(ctlvdev);
+		ctlv_attestation_evidence_get_enable(ctlvdev);
+	}
+	if (provider->mrs_count) {
+		ctlv_attestation_mr_get_provide(ctlvdev);
+		ctlv_attestation_mr_dump_provide(ctlvdev);
+		ctlv_attestation_mr_log_get_provide(ctlvdev);
+		if (provider->mr_read)
+			ctlv_attestation_mr_read_provide(ctlvdev);
+		if (provider->mr_extend)
+			ctlv_attestation_mr_extend_provide(ctlvdev);
+	}
+}
+
+int attestation_core_init(struct attestation *att, struct ctlv_device *ctlvdev,
+			  const struct attestation_provider *provider)
+{
+	size_t index;
+	int ret;
+
+	ret = attestation_provider_validate(provider);
+	if (ret)
+		return ret;
+	mutex_init(&att->lock);
+	xa_init(&att->mrs);
+	att->ctlvdev = ctlvdev;
+	att->provider = provider;
+	for (index = 0; index < provider->mrs_count; index++) {
+		struct attestation_mr *mr;
+
+		mr = attestation_mr_alloc(att, &provider->mrs[index]);
+		if (IS_ERR(mr)) {
+			ret = PTR_ERR(mr);
+			goto err_mrs;
+		}
+	}
+	ret = attestation_registry_insert(att);
+	if (ret)
+		goto err_mrs;
+	attestation_provide_ops(att);
+	att->initialized = true;
+	return 0;
+
+err_mrs:
+	attestation_core_fini(att);
+	return ret;
+}
+
+void attestation_core_fini(struct attestation *att)
+{
+	struct attestation_mr *mr;
+	unsigned long index;
+
+	if (!att->ctlvdev)
+		return;
+	if (att->initialized)
+		attestation_registry_remove(att);
+	xa_for_each(&att->mrs, index, mr) {
+		xa_erase(&att->mrs, index);
+		kfree(mr);
+	}
+	attestation_mr_log_free(att->log);
+	xa_destroy(&att->mrs);
+	mutex_destroy(&att->lock);
+	att->ctlvdev = NULL;
+}
+
+size_t ctlv_attestation_priv_size(void)
+{
+	return sizeof(struct attestation);
+}
+
+int ctlv_attestation_init(struct ctlv_device *ctlvdev, const void *init_info, void *priv)
+{
+	return attestation_core_init(priv, ctlvdev, init_info);
+}
+
+int ctlv_attestation_post_init(struct ctlv_device *ctlvdev, void *priv)
+{
+	struct attestation *att = priv;
+	int ret;
+
+	ret = attestation_mr_log_init(att);
+	if (ret)
+		return ret;
+	xa_lock(&attestation_instances);
+	__xa_set_mark(&attestation_instances, att->index, ATTESTATION_REGISTERED);
+	xa_unlock(&attestation_instances);
+	return 0;
+}
+
+void ctlv_attestation_pre_fini(struct ctlv_device *ctlvdev, void *priv)
+{
+	struct attestation *att = priv;
+
+	xa_lock(&attestation_instances);
+	__xa_clear_mark(&attestation_instances, att->index, ATTESTATION_REGISTERED);
+	xa_unlock(&attestation_instances);
+}
+
+void ctlv_attestation_fini(struct ctlv_device *ctlvdev, void *priv)
+{
+	attestation_core_fini(priv);
+}
+
+int ctlv_attestation_op_pre(void *priv, struct ctlv_op_ctx *ctx)
+{
+	struct attestation *att = priv;
+
+	mutex_lock(&att->lock);
+	if (!attestation_registered(att)) {
+		mutex_unlock(&att->lock);
+		return -ENODEV;
+	}
+	return 0;
+}
+EXPORT_SYMBOL_NS_GPL(ctlv_attestation_op_pre, "ATTESTATION");
+
+void ctlv_attestation_op_post(void *priv, struct ctlv_op_ctx *ctx)
+{
+	struct attestation *att = priv;
+
+	mutex_unlock(&att->lock);
+}
+EXPORT_SYMBOL_NS_GPL(ctlv_attestation_op_post, "ATTESTATION");
+
+static int __init attestation_module_init(void)
+{
+	return 0;
+}
+
+static void __exit attestation_module_exit(void)
+{
+	WARN_ON_ONCE(!xa_empty(&attestation_instances));
+	xa_destroy(&attestation_instances);
+}
+
+module_init(attestation_module_init);
+module_exit(attestation_module_exit);
+MODULE_DESCRIPTION("Attestation core");
+MODULE_LICENSE("GPL");
+MODULE_IMPORT_NS("CTLV");
diff --git a/drivers/attestation/core/ctlv.c b/drivers/attestation/core/ctlv.c
new file mode 100644
index 0000000000000..ff19400843c2c
--- /dev/null
+++ b/drivers/attestation/core/ctlv.c
@@ -0,0 +1,520 @@
+// SPDX-License-Identifier: GPL-2.0-only
+#include <crypto/hash_info.h>
+#include <linux/cleanup.h>
+#include <linux/err.h>
+#include <linux/limits.h>
+#include <linux/slab.h>
+#include <linux/sort.h>
+#include <linux/string.h>
+
+#include "internal.h"
+
+static const struct attestation_evidence_supported_object *
+attestation_evidence_object_find(const struct attestation_evidence_caps *caps, const char *format)
+{
+	size_t index;
+
+	for (index = 0; index < caps->objects_count; index++) {
+		const struct attestation_evidence_supported_object *object = &caps->objects[index];
+
+		if (!strcmp(object->format, format))
+			return object;
+	}
+	return NULL;
+}
+
+static int attestation_device_caps_put(struct attestation *att, struct ctlv_cursor *reply)
+{
+	const struct attestation_provider *provider = att->provider;
+	struct ctlv_cursor caps_nest, group, object;
+	bool ok = true;
+	size_t index;
+	u64 flags;
+
+	if (!ctlv_attestation_device_caps_start(reply, &caps_nest))
+		return -EMSGSIZE;
+	if (provider->evidence_caps) {
+		const struct attestation_evidence_caps *caps = provider->evidence_caps;
+		u64 blob_class = CTLV_ATTESTATION_EVIDENCE_BLOB_CLASS_PRIMARY;
+		u64 representation = CTLV_ATTESTATION_EVIDENCE_REPRESENTATION_RAW;
+		u64 max_output_length = caps->max_total_output_length;
+
+		if (!ctlv_attestation_cap_evidence_start(&caps_nest, &group))
+			return -EMSGSIZE;
+		ok &= ctlv_attestation_cap_min_challenge_length_put(&group,
+								    caps->min_challenge_length);
+		ok &= ctlv_attestation_cap_max_challenge_length_put(&group,
+								    caps->max_challenge_length);
+		ok &= ctlv_attestation_cap_max_total_output_length_put(&group, max_output_length);
+		for (index = 0; index < caps->objects_count; index++) {
+			const struct attestation_evidence_supported_object *cap =
+				&caps->objects[index];
+
+			if (!ctlv_attestation_cap_object_start(&group, &object)) {
+				ok = false;
+				break;
+			}
+			ok &= ctlv_attestation_cap_blob_class_put(&object, blob_class);
+			ok &= ctlv_attestation_cap_format_put(&object, cap->format);
+			ok &= ctlv_attestation_cap_representation_put(&object, representation);
+			ok &= ctlv_attestation_cap_max_length_put(&object, cap->max_length);
+			ctlv_nest_end(&object);
+		}
+		ctlv_nest_end(&group);
+	}
+	if (provider->mrs_count) {
+		if (!ctlv_attestation_cap_mr_start(&caps_nest, &group))
+			return -EMSGSIZE;
+		flags = 0;
+		if (provider->mr_read)
+			flags |= CTLV_ATTESTATION_MR_DEVICE_CAPS_READ;
+		if (provider->mr_extend)
+			flags |= CTLV_ATTESTATION_MR_DEVICE_CAPS_EXTEND;
+		ok &= ctlv_attestation_cap_mr_flags_put(&group, flags);
+		ctlv_nest_end(&group);
+	}
+	ctlv_nest_end(&caps_nest);
+	return ok ? 0 : -EMSGSIZE;
+}
+
+int ctlv_attestation_device_get_action(void *priv, struct ctlv_op_ctx *ctx,
+				       const struct ctlv_cursor *request, struct ctlv_cursor *reply)
+{
+	struct attestation *att = priv;
+	struct ctlv_cursor info;
+	int ret;
+
+	ret = attestation_device_caps_put(att, reply);
+	if (ret)
+		return ret;
+	if (!ctlv_attestation_device_info_start(reply, &info))
+		return -EMSGSIZE;
+	ret = ctlv_stub_fill(ctx, request, &info);
+	ctlv_nest_end(&info);
+	return ret;
+}
+
+static int
+attestation_evidence_decode_objects(struct attestation *att, struct ctlv_op_ctx *ctx,
+				    const struct ctlv_cursor *request,
+				    struct attestation_evidence_request *decoded,
+				    struct attestation_evidence_object_request **objects_out)
+{
+	const struct attestation_evidence_caps *caps = att->provider->evidence_caps;
+	struct attestation_evidence_object_request *objects;
+	struct ctlv_cursor object;
+	size_t count = 0, index = 0, previous;
+
+	ctlv_attestation_evidence_get_evidence_object_for_each(&object, request) count++;
+	objects = kcalloc(count, sizeof(*objects), GFP_KERNEL);
+	if (!objects)
+		return -ENOMEM;
+	ctlv_attestation_evidence_get_evidence_object_for_each(&object, request)
+	{
+		const struct attestation_evidence_supported_object *supported;
+		const char *format;
+		size_t total = 0;
+
+		format = ctlv_attestation_evidence_get_object_evidence_format_get(&object);
+		supported = attestation_evidence_object_find(caps, format);
+		if (!supported) {
+			kfree(objects);
+			return -EOPNOTSUPP;
+		}
+		for (previous = 0; previous < index; previous++)
+			if (objects[previous].supported_object == supported) {
+				kfree(objects);
+				return -EINVAL;
+			}
+		objects[index].supported_object = supported;
+		objects[index].output =
+			ctlv_attestation_evidence_get_object_evidence_data_resolve(ctx, &object);
+		if (IS_ERR(objects[index].output)) {
+			int ret = PTR_ERR(objects[index].output);
+
+			objects[index].output = NULL;
+			while (index)
+				ctlv_blob_put(objects[--index].output);
+			kfree(objects);
+			return ret;
+		}
+		if (ctlv_blob_len(objects[index].output) < supported->max_length) {
+			for (previous = 0; previous <= index; previous++)
+				ctlv_blob_put(objects[previous].output);
+			kfree(objects);
+			return -EMSGSIZE;
+		}
+		for (previous = 0; previous <= index; previous++) {
+			if (check_add_overflow(total, ctlv_blob_len(objects[previous].output),
+					       &total) ||
+			    total > caps->max_total_output_length) {
+				for (previous = 0; previous <= index; previous++)
+					ctlv_blob_put(objects[previous].output);
+				kfree(objects);
+				return -E2BIG;
+			}
+		}
+		index++;
+	}
+	decoded->objects = objects;
+	decoded->objects_count = count;
+	*objects_out = objects;
+	return 0;
+}
+
+static int attestation_evidence_request_decode(struct attestation *att, struct ctlv_op_ctx *ctx,
+					       const struct ctlv_cursor *request,
+					       struct attestation_evidence_request *decoded,
+					       struct attestation_evidence_object_request **objects)
+{
+	const struct attestation_evidence_caps *caps = att->provider->evidence_caps;
+	u32 challenge_length;
+
+	decoded->challenge =
+		ctlv_attestation_evidence_get_evidence_challenge_get(request, &challenge_length);
+	decoded->challenge_length = challenge_length;
+	if (challenge_length < caps->min_challenge_length ||
+	    challenge_length > caps->max_challenge_length)
+		return -EINVAL;
+	return attestation_evidence_decode_objects(att, ctx, request, decoded, objects);
+}
+
+static void attestation_evidence_request_free(struct attestation_evidence_object_request *objects,
+					      size_t count)
+{
+	while (count) {
+		count--;
+		if (objects[count].output)
+			ctlv_blob_put(objects[count].output);
+	}
+	kfree(objects);
+}
+
+int ctlv_attestation_evidence_get_action(void *priv, struct ctlv_op_ctx *ctx,
+					 const struct ctlv_cursor *request,
+					 struct ctlv_cursor *reply)
+{
+	struct attestation_evidence_object_request *objects = NULL;
+	struct attestation_evidence_request decoded = {};
+	struct attestation_evidence_result result = {};
+	struct attestation *att = priv;
+	bool mr_dependent = false;
+	size_t index;
+	int put_ret;
+	int ret;
+
+	ret = attestation_evidence_request_decode(att, ctx, request, &decoded, &objects);
+	if (ret)
+		goto out;
+	result.object_lengths =
+		kcalloc(decoded.objects_count, sizeof(*result.object_lengths), GFP_KERNEL);
+	if (!result.object_lengths) {
+		ret = -ENOMEM;
+		goto out;
+	}
+	for (index = 0; index < decoded.objects_count; index++)
+		mr_dependent |= decoded.objects[index].supported_object->binds_mrs;
+	ret = att->provider->evidence_get(att, &decoded, &result);
+	if (ret)
+		goto out;
+	for (index = 0; index < decoded.objects_count; index++) {
+		if (result.object_lengths[index] >
+			    decoded.objects[index].supported_object->max_length ||
+		    result.object_lengths[index] > ctlv_blob_len(decoded.objects[index].output)) {
+			ret = -E2BIG;
+			goto out;
+		}
+	}
+	for (index = 0; index < decoded.objects_count; index++) {
+		put_ret = ctlv_blob_put(decoded.objects[index].output);
+		objects[index].output = NULL;
+		if (!ret)
+			ret = put_ret;
+	}
+	if (ret)
+		goto out;
+	if (mr_dependent && !ctlv_attestation_mr_generation_put(reply, att->log->generation)) {
+		ret = -EMSGSIZE;
+		goto out;
+	}
+	for (index = 0; index < decoded.objects_count; index++)
+		if (!ctlv_attestation_evidence_object_length_put(reply,
+								 result.object_lengths[index])) {
+			ret = -EMSGSIZE;
+			goto out;
+		}
+out:
+	kfree(result.object_lengths);
+	attestation_evidence_request_free(objects, decoded.objects_count);
+	return ret;
+}
+
+int ctlv_attestation_mr_get_action(void *priv, struct ctlv_op_ctx *ctx,
+				   const struct ctlv_cursor *request, struct ctlv_cursor *reply)
+{
+	struct attestation *att = priv;
+	struct attestation_mr *mr;
+	u64 id = ctlv_attestation_mr_get_mr_id_get(request);
+
+	if (id > UINT_MAX)
+		return -ERANGE;
+	mr = attestation_mr_lookup_live(att, id);
+	return IS_ERR(mr) ? PTR_ERR(mr) : attestation_mr_props_encode(reply, mr, false);
+}
+
+int ctlv_attestation_mr_dump_query(void *priv, struct ctlv_op_ctx *ctx,
+				   const struct ctlv_cursor *request, struct ctlv_cursor *reply)
+{
+	struct attestation *att = priv;
+	struct attestation_mr *mr;
+	struct ctlv_cursor nested;
+	unsigned long id;
+	u64 cursor = ctlv_op_query_cursor(ctx);
+	unsigned int generation = att->log->generation;
+	int ret;
+
+	if (cursor && ctlv_op_query_generation(ctx) != generation)
+		return -ESTALE;
+	id = cursor ? cursor - 1 : 0;
+	mr = xa_find(&att->mrs, &id, UINT_MAX, XA_PRESENT);
+	while (mr) {
+		if (!ctlv_attestation_mr_item_start(reply, &nested))
+			return ctlv_op_query_more(ctx, generation, id + 1);
+		ret = attestation_mr_props_encode(&nested, mr, true);
+		ctlv_nest_end(&nested);
+		if (ret)
+			return ret;
+		mr = xa_find_after(&att->mrs, &id, UINT_MAX, XA_PRESENT);
+	}
+	return ctlv_op_query_done(ctx, generation);
+}
+
+static int attestation_mr_values_put(struct ctlv_cursor *reply,
+				     const struct attestation_digest_set *values)
+{
+	struct ctlv_cursor nested;
+	size_t index;
+	bool ok;
+
+	for (index = 0; index < values->values_count; index++) {
+		const struct attestation_digest *value = &values->values[index];
+		enum hash_algo algorithm = value->algorithm;
+		size_t length = hash_digest_size[algorithm];
+
+		if (!ctlv_attestation_mr_value_start(reply, &nested))
+			return -EMSGSIZE;
+		ok = ctlv_attestation_mr_hash_algo_put(&nested, algorithm);
+		ok &= ctlv_attestation_mr_data_put(&nested, value->data, length);
+		ctlv_nest_end(&nested);
+		if (!ok)
+			return -EMSGSIZE;
+	}
+	return 0;
+}
+
+int ctlv_attestation_mr_read_query(void *priv, struct ctlv_op_ctx *ctx,
+				   const struct ctlv_cursor *request, struct ctlv_cursor *reply)
+{
+	struct attestation_digest_set values = {};
+	struct attestation *att = priv;
+	struct attestation_mr *mr;
+	u64 id;
+	int ret;
+
+	if (ctlv_op_query_cursor(ctx) &&
+	    ctlv_op_query_generation(ctx) != att->mr_read_generation)
+		return -ESTALE;
+	id = ctlv_attestation_mr_read_mr_id_get(request);
+	if (id > UINT_MAX)
+		return -ERANGE;
+	mr = attestation_mr_lookup_live(att, id);
+	if (IS_ERR(mr))
+		return PTR_ERR(mr);
+	if (!mr->props->readable)
+		return -EOPNOTSUPP;
+	values.values_count = mr->props->algorithms_count;
+	values.values = kcalloc(values.values_count, sizeof(*values.values), GFP_KERNEL);
+	if (!values.values)
+		return -ENOMEM;
+	for (id = 0; id < values.values_count; id++)
+		values.values[id].algorithm = mr->props->algorithms[id];
+	ret = att->provider->mr_read(att, mr->props->id, &values);
+	if (!ret)
+		ret = attestation_mr_values_validate(mr, &values);
+	if (!ret && !ctlv_attestation_mr_generation_put(reply, att->log->generation))
+		ret = -EMSGSIZE;
+	if (!ret)
+		ret = attestation_mr_values_put(reply, &values);
+	kfree(values.values);
+	if (ret)
+		return ret;
+	return ctlv_op_query_done(ctx, att->mr_read_generation);
+}
+
+static int attestation_digest_compare(const void *left, const void *right)
+{
+	const struct attestation_digest *a = left;
+	const struct attestation_digest *b = right;
+
+	return (int)a->algorithm - (int)b->algorithm;
+}
+
+static int attestation_mr_extend_decode(const struct ctlv_cursor *request,
+					struct attestation_digest_set *values)
+{
+	struct ctlv_cursor item;
+	size_t count = 0, index = 0;
+
+	ctlv_attestation_mr_extend_mr_value_for_each(&item, request) count++;
+	values->values = kcalloc(count, sizeof(*values->values), GFP_KERNEL);
+	if (!values->values)
+		return -ENOMEM;
+	values->values_count = count;
+	ctlv_attestation_mr_extend_mr_value_for_each(&item, request)
+	{
+		struct attestation_digest *value = &values->values[index++];
+		u32 length;
+		const void *data;
+		u64 algorithm;
+
+		algorithm =
+			ctlv_attestation_mr_extend_value_mr_hash_algo_get(&item);
+		if (algorithm >= HASH_ALGO__LAST || !hash_digest_size[algorithm])
+			return -EINVAL;
+		data = ctlv_attestation_mr_extend_value_mr_data_get(&item, &length);
+		if (length != hash_digest_size[algorithm])
+			return -EINVAL;
+		value->algorithm = algorithm;
+		memcpy(value->data, data, length);
+	}
+	sort(values->values, values->values_count, sizeof(*values->values),
+	     attestation_digest_compare, NULL);
+	return 0;
+}
+
+int ctlv_attestation_mr_extend_action(void *priv, struct ctlv_op_ctx *ctx,
+				      const struct ctlv_cursor *request, struct ctlv_cursor *reply)
+{
+	struct attestation_digest_set values = {};
+	struct attestation_mr_change *change;
+	const struct attestation_mr_log_entry *entry;
+	struct attestation *att = priv;
+	struct attestation_mr *mr;
+	u64 id;
+	int ret;
+
+	id = ctlv_attestation_mr_extend_mr_id_get(request);
+	if (id > UINT_MAX)
+		return -ERANGE;
+	mr = attestation_mr_lookup_live(att, id);
+	if (IS_ERR(mr))
+		return PTR_ERR(mr);
+	if (!mr->props->extendable)
+		return -EOPNOTSUPP;
+	ret = attestation_mr_extend_decode(request, &values);
+	if (ret)
+		goto out_values;
+	ret = attestation_mr_values_validate(mr, &values);
+	if (ret)
+		goto out_values;
+	change = attestation_mr_change_prepare(att, mr, &values);
+	if (IS_ERR(change)) {
+		ret = PTR_ERR(change);
+		goto out_values;
+	}
+	entry = attestation_mr_extend_locked(att, change);
+	if (IS_ERR(entry))
+		ret = PTR_ERR(entry);
+	else if (!ctlv_attestation_mr_generation_put(reply, entry->mr_generation))
+		ret = -EMSGSIZE;
+	attestation_mr_change_free(change);
+out_values:
+	kfree(values.values);
+	return ret;
+}
+
+static bool attestation_log_selected(const unsigned int *ids, size_t count, unsigned int id)
+{
+	size_t index;
+
+	if (!count)
+		return true;
+	for (index = 0; index < count; index++)
+		if (ids[index] == id)
+			return true;
+	return false;
+}
+
+int ctlv_attestation_mr_log_get_query(void *priv, struct ctlv_op_ctx *ctx,
+				      const struct ctlv_cursor *request, struct ctlv_cursor *reply)
+{
+	struct attestation *att = priv;
+	struct attestation_mr_log_entry *entry;
+	struct ctlv_cursor item, nested;
+	unsigned int ids[256];
+	size_t ids_count = 0, index;
+	unsigned int start, end;
+	unsigned long xa_index;
+	u64 boundary;
+	u64 cursor = ctlv_op_query_cursor(ctx);
+	int ret;
+
+	ctlv_attestation_mr_log_get_mr_selection_for_each(&item, request)
+	{
+		u64 id = ctlv_attestation_mr_log_get_selection_mr_id_get(&item);
+
+		if (id > UINT_MAX)
+			return -ERANGE;
+		for (index = 0; index < ids_count; index++)
+			if (ids[index] == id)
+				return -EINVAL;
+		ids[ids_count++] = id;
+	}
+	if (cursor)
+		boundary = ctlv_op_query_generation(ctx);
+	else
+		boundary = att->log->generation;
+	if (boundary > UINT_MAX || boundary > att->log->generation)
+		return -ESTALE;
+	end = boundary;
+	if (ctlv_attestation_mr_log_get_mr_end_generation_present(request)) {
+		u64 requested_end = ctlv_attestation_mr_log_get_mr_end_generation_get(request);
+
+		end = min_t(u64, end, requested_end);
+	}
+	start = 1;
+	if (ctlv_attestation_mr_log_get_mr_start_generation_present(request)) {
+		u64 value = ctlv_attestation_mr_log_get_mr_start_generation_get(request);
+
+		if (value > UINT_MAX)
+			return -EINVAL;
+		start = value;
+	}
+	if (att->log->generation && start > end)
+		return -EINVAL;
+	if (!cursor && att->log->generation) {
+		if (!ctlv_attestation_mr_start_generation_put(reply, start) ||
+		    !ctlv_attestation_mr_end_generation_put(reply, end))
+			return -EMSGSIZE;
+	}
+	xa_index = cursor ? cursor : start;
+	entry = xa_find(&att->log->entries, &xa_index, end, XA_PRESENT);
+	while (entry && !attestation_log_selected(ids, ids_count, entry->mr_id))
+		entry = xa_find_after(&att->log->entries, &xa_index, end, XA_PRESENT);
+	if (!entry)
+		return ctlv_op_query_done(ctx, boundary);
+	if (!cursor)
+		return ctlv_op_query_more(ctx, boundary, entry->mr_generation);
+	if (!ctlv_attestation_log_entry_start(reply, &nested))
+		return -EMSGSIZE;
+	ret = attestation_mr_log_entry_encode(&nested, entry);
+	ctlv_nest_end(&nested);
+	if (ret)
+		return ret;
+	entry = xa_find_after(&att->log->entries, &xa_index, end, XA_PRESENT);
+	while (entry && !attestation_log_selected(ids, ids_count, entry->mr_id))
+		entry = xa_find_after(&att->log->entries, &xa_index, end, XA_PRESENT);
+	if (entry)
+		return ctlv_op_query_more(ctx, boundary, entry->mr_generation);
+	return ctlv_op_query_done(ctx, boundary);
+}
diff --git a/drivers/attestation/core/events.c b/drivers/attestation/core/events.c
new file mode 100644
index 0000000000000..2cf8df4b64792
--- /dev/null
+++ b/drivers/attestation/core/events.c
@@ -0,0 +1,65 @@
+// SPDX-License-Identifier: GPL-2.0-only
+#include <linux/err.h>
+
+#include "internal.h"
+
+int attestation_events_prepare(struct attestation *att, struct attestation_event_batch *events)
+{
+	struct attestation_event *event = &events->mr_log;
+
+	lockdep_assert_held(&att->lock);
+	event->ctx = ctlv_attestation_mr_log_entry_appended_create(att->ctlvdev, &event->reply,
+								   GFP_KERNEL);
+	if (IS_ERR(event->ctx)) {
+		int ret = PTR_ERR(event->ctx);
+
+		event->ctx = NULL;
+		event->reply = NULL;
+		return ret;
+	}
+	return 0;
+}
+
+void attestation_events_abort(struct attestation_event_batch *events)
+{
+	struct attestation_event *event = &events->mr_log;
+
+	if (!event->ctx)
+		return;
+	ctlv_event_abort(event->ctx);
+	event->ctx = NULL;
+	event->reply = NULL;
+}
+
+static void attestation_event_finish(struct attestation_event *event, int ret)
+{
+	if (ret) {
+		pr_err("attestation event encoding failed: %d\n", ret);
+		ctlv_event_abort(event->ctx);
+	} else {
+		ret = ctlv_event_emit(event->ctx);
+		if (ret)
+			pr_err("attestation event emission failed: %d\n", ret);
+	}
+	event->ctx = NULL;
+	event->reply = NULL;
+}
+
+void attestation_mr_log_event_emit(struct attestation_event_batch *events,
+				   const struct attestation_mr_log_entry *entry)
+{
+	struct attestation_event *event = &events->mr_log;
+	struct ctlv_cursor nested;
+	int ret;
+
+	if (!event->ctx)
+		return;
+	if (!ctlv_attestation_notification_entry_start(event->reply, &nested)) {
+		ret = -EMSGSIZE;
+		goto out;
+	}
+	ret = attestation_mr_log_entry_encode(&nested, entry);
+	ctlv_nest_end(&nested);
+out:
+	attestation_event_finish(event, ret);
+}
diff --git a/drivers/attestation/core/internal.h b/drivers/attestation/core/internal.h
new file mode 100644
index 0000000000000..64dca12a3d04a
--- /dev/null
+++ b/drivers/attestation/core/internal.h
@@ -0,0 +1,108 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+#ifndef _ATTESTATION_INTERNAL_H
+#define _ATTESTATION_INTERNAL_H
+
+#include <linux/attestation.h>
+#include <linux/ctlv.h>
+#include <linux/mutex.h>
+#include <linux/xarray.h>
+
+#include "../generated/ctlv_attestation_gen.h"
+
+#define ATTESTATION_REGISTERED XA_MARK_1
+
+enum attestation_mr_log_entry_type {
+	ATTESTATION_MR_LOG_ENTRY_INFO,
+	ATTESTATION_MR_LOG_ENTRY_EXTEND,
+};
+
+struct attestation_mr_log_entry {
+	unsigned int mr_generation;
+	unsigned int mr_id;
+	enum attestation_mr_log_entry_type type;
+};
+
+struct attestation_mr_log_entry_info {
+	struct attestation_mr_log_entry entry;
+	struct attestation_mr_props props;
+};
+
+struct attestation_mr_log_entry_extend {
+	struct attestation_mr_log_entry entry;
+	struct attestation_digest_set values;
+};
+
+struct attestation_mr_log {
+	unsigned int generation;
+	struct xarray entries;
+};
+
+struct attestation {
+	struct ctlv_device *ctlvdev;
+	const struct attestation_provider *provider;
+	unsigned int index;
+
+	/* Mutable instance, MR, and journal state. */
+	struct mutex lock;
+	unsigned int mr_read_generation;
+
+	struct xarray mrs;
+	struct attestation_mr_log *log;
+	bool initialized;
+};
+
+struct attestation_mr {
+	const struct attestation_mr_props *props;
+};
+
+struct attestation_event {
+	struct ctlv_op_ctx *ctx;
+	struct ctlv_cursor *reply;
+};
+
+struct attestation_event_batch {
+	struct attestation_event mr_log;
+};
+
+struct attestation_mr_change {
+	struct attestation_mr *mr;
+	struct attestation_mr_log_entry_extend *entry;
+	struct attestation_event_batch events;
+};
+
+int attestation_core_init(struct attestation *att, struct ctlv_device *ctlvdev,
+			  const struct attestation_provider *provider);
+void attestation_core_fini(struct attestation *att);
+bool attestation_registered(struct attestation *att);
+void attestation_stop(struct attestation *att);
+void attestation_mr_changed(struct attestation *att);
+
+int attestation_provider_validate(const struct attestation_provider *provider);
+void attestation_provide_ops(struct attestation *att);
+
+struct attestation_mr *attestation_mr_lookup_live(struct attestation *att, unsigned int mr_id);
+int attestation_mr_values_validate(const struct attestation_mr *mr,
+				   const struct attestation_digest_set *values);
+int attestation_mr_log_init(struct attestation *att);
+struct attestation_mr_log_entry_info *attestation_mr_info_alloc(const struct attestation_mr *mr);
+void attestation_mr_log_entry_free(struct attestation_mr_log_entry *entry);
+void attestation_mr_log_free(struct attestation_mr_log *log);
+void attestation_mr_log_append(struct attestation *att, struct attestation_mr_log_entry *entry);
+struct attestation_mr_change *
+attestation_mr_change_prepare(struct attestation *att, struct attestation_mr *mr,
+			      const struct attestation_digest_set *values);
+const struct attestation_mr_log_entry *
+attestation_mr_extend_locked(struct attestation *att, struct attestation_mr_change *change);
+void attestation_mr_change_free(struct attestation_mr_change *change);
+
+int attestation_events_prepare(struct attestation *att, struct attestation_event_batch *events);
+void attestation_events_abort(struct attestation_event_batch *events);
+void attestation_mr_log_event_emit(struct attestation_event_batch *events,
+				   const struct attestation_mr_log_entry *entry);
+
+int attestation_mr_log_entry_encode(struct ctlv_cursor *reply,
+				    const struct attestation_mr_log_entry *entry);
+int attestation_mr_props_encode(struct ctlv_cursor *reply, const struct attestation_mr *mr,
+				bool include_id);
+
+#endif /* _ATTESTATION_INTERNAL_H */
diff --git a/drivers/attestation/core/mr.c b/drivers/attestation/core/mr.c
new file mode 100644
index 0000000000000..db80cbd2b5827
--- /dev/null
+++ b/drivers/attestation/core/mr.c
@@ -0,0 +1,376 @@
+// SPDX-License-Identifier: GPL-2.0-only
+#include <crypto/hash_info.h>
+#include <linux/cleanup.h>
+#include <linux/err.h>
+#include <linux/slab.h>
+#include <linux/string.h>
+
+#include "internal.h"
+
+int attestation_mr_values_validate(const struct attestation_mr *mr,
+				   const struct attestation_digest_set *values)
+{
+	size_t index;
+
+	if (!values || !values->values || values->values_count != mr->props->algorithms_count)
+		return -EINVAL;
+	for (index = 0; index < values->values_count; index++)
+		if (values->values[index].algorithm != mr->props->algorithms[index])
+			return -EINVAL;
+	return 0;
+}
+
+static int attestation_digest_set_copy(struct attestation_digest_set *dst,
+				       const struct attestation_digest_set *src)
+{
+	size_t index;
+
+	if (!src || !src->values || !src->values_count)
+		return -EINVAL;
+	for (index = 0; index < src->values_count; index++) {
+		enum hash_algo algorithm = src->values[index].algorithm;
+
+		if (algorithm >= HASH_ALGO__LAST || !hash_digest_size[algorithm] ||
+		    (index && src->values[index - 1].algorithm >= algorithm))
+			return -EINVAL;
+	}
+	dst->values =
+		kmemdup_array(src->values, src->values_count, sizeof(*src->values), GFP_KERNEL);
+	if (!dst->values)
+		return -ENOMEM;
+	dst->values_count = src->values_count;
+	return 0;
+}
+
+static void attestation_digest_set_free(struct attestation_digest_set *set)
+{
+	kfree(set->values);
+	set->values = NULL;
+	set->values_count = 0;
+}
+
+struct attestation_mr_log_entry_info *attestation_mr_info_alloc(const struct attestation_mr *mr)
+{
+	struct attestation_mr_log_entry_info *info;
+	enum hash_algo *algorithms;
+	char *name;
+
+	info = kzalloc_obj(*info, GFP_KERNEL);
+	if (!info)
+		return ERR_PTR(-ENOMEM);
+	name = kstrdup(mr->props->name, GFP_KERNEL);
+	if (!name)
+		goto err_info;
+	algorithms = kmemdup_array(mr->props->algorithms, mr->props->algorithms_count,
+				   sizeof(*algorithms), GFP_KERNEL);
+	if (!algorithms)
+		goto err_name;
+	info->entry.type = ATTESTATION_MR_LOG_ENTRY_INFO;
+	info->entry.mr_id = mr->props->id;
+	info->props = *mr->props;
+	info->props.name = name;
+	info->props.algorithms = algorithms;
+	return info;
+
+err_name:
+	kfree(name);
+err_info:
+	kfree(info);
+	return ERR_PTR(-ENOMEM);
+}
+
+void attestation_mr_log_entry_free(struct attestation_mr_log_entry *entry)
+{
+	if (!entry)
+		return;
+	switch (entry->type) {
+	case ATTESTATION_MR_LOG_ENTRY_INFO: {
+		struct attestation_mr_log_entry_info *info =
+			container_of(entry, typeof(*info), entry);
+
+		kfree(info->props.algorithms);
+		kfree(info->props.name);
+		kfree(info);
+		break;
+	}
+	case ATTESTATION_MR_LOG_ENTRY_EXTEND: {
+		struct attestation_mr_log_entry_extend *extend =
+			container_of(entry, typeof(*extend), entry);
+
+		attestation_digest_set_free(&extend->values);
+		kfree(extend);
+		break;
+	}
+	}
+}
+
+void attestation_mr_log_free(struct attestation_mr_log *log)
+{
+	struct attestation_mr_log_entry *entry;
+	unsigned long index;
+
+	if (!log)
+		return;
+	xa_for_each(&log->entries, index, entry) {
+		xa_erase(&log->entries, index);
+		attestation_mr_log_entry_free(entry);
+	}
+	xa_destroy(&log->entries);
+	kfree(log);
+}
+
+void attestation_mr_log_append(struct attestation *att, struct attestation_mr_log_entry *entry)
+{
+	struct attestation_mr_log *log = att->log;
+
+	xa_store(&log->entries, entry->mr_generation, entry, GFP_NOWAIT);
+}
+
+int attestation_mr_log_init(struct attestation *att)
+{
+	struct attestation_mr_log_entry_info **infos;
+	struct attestation_mr_log *log;
+	struct attestation_mr *mr;
+	unsigned long mr_id;
+	size_t count = 0;
+	size_t index = 0;
+	int ret = -ENOMEM;
+
+	xa_for_each(&att->mrs, mr_id, mr)
+		count++;
+	log = kzalloc_obj(*log, GFP_KERNEL);
+	if (!log)
+		return -ENOMEM;
+	xa_init(&log->entries);
+	infos = kcalloc(count, sizeof(*infos), GFP_KERNEL);
+	if (count && !infos)
+		goto err_log;
+	xa_for_each(&att->mrs, mr_id, mr) {
+		infos[index] = attestation_mr_info_alloc(mr);
+		if (IS_ERR(infos[index])) {
+			ret = PTR_ERR(infos[index]);
+			infos[index] = NULL;
+			goto err_infos;
+		}
+		index++;
+	}
+
+	att->log = log;
+	index = 0;
+	xa_for_each(&att->mrs, mr_id, mr) {
+		struct attestation_mr_log_entry *entry = &infos[index]->entry;
+
+		if (log->generation == UINT_MAX) {
+			ret = -EOVERFLOW;
+			goto err_attached;
+		}
+		entry->mr_generation = ++log->generation;
+		ret = xa_insert(&log->entries, entry->mr_generation, entry, GFP_KERNEL);
+		if (ret)
+			goto err_attached;
+		infos[index++] = NULL;
+	}
+	kfree(infos);
+	return 0;
+
+err_attached:
+	att->log = NULL;
+	attestation_mr_log_free(log);
+	log = NULL;
+err_infos:
+	for (index = 0; index < count; index++)
+		if (infos[index])
+			attestation_mr_log_entry_free(&infos[index]->entry);
+	kfree(infos);
+err_log:
+	attestation_mr_log_free(log);
+	return ret;
+}
+
+static struct attestation_mr_log_entry_extend *
+attestation_extend_alloc(enum attestation_mr_log_entry_type type, size_t size,
+			 struct attestation_mr *mr, const struct attestation_digest_set *values)
+{
+	struct attestation_mr_log_entry_extend *extend;
+	int ret;
+
+	extend = kzalloc(size, GFP_KERNEL);
+	if (!extend)
+		return ERR_PTR(-ENOMEM);
+	extend->entry.type = type;
+	extend->entry.mr_id = mr->props->id;
+	ret = attestation_digest_set_copy(&extend->values, values);
+	if (ret) {
+		kfree(extend);
+		return ERR_PTR(ret);
+	}
+	return extend;
+}
+
+struct attestation_mr_change *
+attestation_mr_change_prepare(struct attestation *att, struct attestation_mr *mr,
+			      const struct attestation_digest_set *values)
+{
+	struct attestation_mr_change *change;
+	int ret;
+
+	lockdep_assert_held(&att->lock);
+	change = kzalloc_obj(*change, GFP_KERNEL);
+	if (!change)
+		return ERR_PTR(-ENOMEM);
+	change->mr = mr;
+	change->entry = attestation_extend_alloc(ATTESTATION_MR_LOG_ENTRY_EXTEND,
+						 sizeof(*change->entry), mr, values);
+	if (IS_ERR(change->entry)) {
+		ret = PTR_ERR(change->entry);
+		goto err_change;
+	}
+	ret = attestation_events_prepare(att, &change->events);
+	if (ret)
+		goto err_entry;
+	return change;
+
+err_entry:
+	attestation_mr_log_entry_free(&change->entry->entry);
+err_change:
+	kfree(change);
+	return ERR_PTR(ret);
+}
+
+const struct attestation_mr_log_entry *
+attestation_mr_extend_locked(struct attestation *att, struct attestation_mr_change *change)
+{
+	struct attestation_mr_log_entry_extend *extend = change->entry;
+	struct attestation_mr_log_entry *entry = &extend->entry;
+	int ret;
+
+	lockdep_assert_held(&att->lock);
+	if (att->log->generation == UINT_MAX) {
+		attestation_stop(att);
+		return ERR_PTR(-EOVERFLOW);
+	}
+	entry->mr_generation = att->log->generation + 1;
+	ret = xa_reserve(&att->log->entries, entry->mr_generation, GFP_KERNEL);
+	if (ret)
+		return ERR_PTR(ret);
+	ret = att->provider->mr_extend(att, change->mr->props->id, &extend->values);
+	if (ret) {
+		xa_release(&att->log->entries, entry->mr_generation);
+		return ERR_PTR(ret);
+	}
+	attestation_mr_changed(att);
+	attestation_mr_log_append(att, entry);
+	attestation_mr_log_event_emit(&change->events, entry);
+	change->entry = NULL;
+	return entry;
+}
+
+void attestation_mr_change_free(struct attestation_mr_change *change)
+{
+	if (!change)
+		return;
+	attestation_events_abort(&change->events);
+	if (change->entry)
+		attestation_mr_log_entry_free(&change->entry->entry);
+	kfree(change);
+}
+
+int attestation_mr_props_encode(struct ctlv_cursor *reply, const struct attestation_mr *mr,
+				bool include_id)
+{
+	u64 caps = 0;
+	size_t index;
+	bool ok = true;
+
+	if (include_id)
+		ok &= ctlv_attestation_mr_id_put(reply, mr->props->id);
+	ok &= ctlv_attestation_mr_name_put(reply, mr->props->name);
+	for (index = 0; index < mr->props->algorithms_count; index++)
+		ok &= ctlv_attestation_mr_supported_hash_algo_put(reply,
+								  mr->props->algorithms[index]);
+	if (mr->props->has_register_index)
+		ok &= ctlv_attestation_mr_register_index_put(reply, mr->props->register_index);
+	if (mr->props->readable)
+		caps |= CTLV_ATTESTATION_MR_CAPS_READ;
+	if (mr->props->extendable)
+		caps |= CTLV_ATTESTATION_MR_CAPS_EXTEND;
+	ok &= ctlv_attestation_mr_caps_put(reply, caps);
+	return ok ? 0 : -EMSGSIZE;
+}
+
+static int attestation_values_encode(struct ctlv_cursor *reply,
+				     const struct attestation_digest_set *values)
+{
+	struct ctlv_cursor nested;
+	size_t index;
+	bool ok = true;
+
+	for (index = 0; index < values->values_count; index++) {
+		const struct attestation_digest *value = &values->values[index];
+
+		if (!ctlv_attestation_mr_value_start(reply, &nested))
+			return -EMSGSIZE;
+		ok &= ctlv_attestation_mr_hash_algo_put(&nested, value->algorithm);
+		ok &= ctlv_attestation_mr_data_put(&nested, value->data,
+						   hash_digest_size[value->algorithm]);
+		ctlv_nest_end(&nested);
+	}
+	return ok ? 0 : -EMSGSIZE;
+}
+
+static int attestation_mr_info_encode(struct ctlv_cursor *reply,
+				      const struct attestation_mr_props *props)
+{
+	u64 caps = 0;
+	size_t index;
+	bool ok;
+
+	ok = ctlv_attestation_mr_name_put(reply, props->name);
+	for (index = 0; index < props->algorithms_count; index++)
+		ok &= ctlv_attestation_mr_supported_hash_algo_put(reply,
+								  props->algorithms[index]);
+	if (props->has_register_index)
+		ok &= ctlv_attestation_mr_register_index_put(reply, props->register_index);
+	if (props->readable)
+		caps |= CTLV_ATTESTATION_MR_CAPS_READ;
+	if (props->extendable)
+		caps |= CTLV_ATTESTATION_MR_CAPS_EXTEND;
+	ok &= ctlv_attestation_mr_caps_put(reply, caps);
+	return ok ? 0 : -EMSGSIZE;
+}
+
+int attestation_mr_log_entry_encode(struct ctlv_cursor *reply,
+				    const struct attestation_mr_log_entry *entry)
+{
+	struct ctlv_cursor nested;
+	bool ok;
+	int ret;
+
+	ok = ctlv_attestation_mr_generation_put(reply, entry->mr_generation);
+	ok &= ctlv_attestation_mr_id_put(reply, entry->mr_id);
+	ok &= ctlv_attestation_log_event_put(reply, entry->type == ATTESTATION_MR_LOG_ENTRY_INFO ?
+							    CTLV_ATTESTATION_MR_LOG_EVENT_INFO :
+							    CTLV_ATTESTATION_MR_LOG_EVENT_EXTEND);
+	if (!ok)
+		return -EMSGSIZE;
+
+	if (entry->type == ATTESTATION_MR_LOG_ENTRY_INFO) {
+		const struct attestation_mr_log_entry_info *info =
+			container_of(entry, typeof(*info), entry);
+
+		if (!ctlv_attestation_log_mr_start(reply, &nested))
+			return -EMSGSIZE;
+		ret = attestation_mr_info_encode(&nested, &info->props);
+		ctlv_nest_end(&nested);
+		return ret;
+	}
+
+	ret = attestation_values_encode(reply,
+					&container_of(entry,
+						      const struct attestation_mr_log_entry_extend,
+						      entry)
+						 ->values);
+	if (ret)
+		return ret;
+	return 0;
+}
diff --git a/drivers/attestation/generated/ctlv_attestation_gen.c b/drivers/attestation/generated/ctlv_attestation_gen.c
new file mode 100644
index 0000000000000..c9fbeae00e385
--- /dev/null
+++ b/drivers/attestation/generated/ctlv_attestation_gen.c
@@ -0,0 +1,234 @@
+// SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)
+/* Do not edit, regenerate with tools/ctlv/ctlv-regen.sh, from: */
+/*	Documentation/ctlv/specs/ctlv-attestation.yaml */
+/* CTLV-GEN kernel source */
+
+#define _CTLV_GENERATED_METADATA_ONLY
+#include <linux/array_size.h>
+#include <linux/bits.h>
+#include <linux/build_bug.h>
+#include <linux/ctlv_family.h>
+#include <linux/export.h>
+#include <linux/limits.h>
+
+#include <uapi/linux/ctlv_gen.h>
+#include <uapi/linux/ctlv_attestation_gen.h>
+
+#include "ctlv_attestation_gen.h"
+
+static const struct ctlv_node_schema device_get_request_node_schemas[] = {
+	CTLV_NODE_SCHEMA_ROOT(0, 0, 0),
+};
+
+static const struct ctlv_node_schema device_get_reply_node_schemas[] = {
+	CTLV_NODE_SCHEMA_ROOT(1, 2, 2),
+	CTLV_NODE_SCHEMA_NEST(CTLV_ATTESTATION_ATTR_DEVICE_CAPS, 1, 3, 2, 0),
+	CTLV_NODE_SCHEMA_NEST(CTLV_ATTESTATION_ATTR_DEVICE_INFO, 1, 0, 0, 0),
+	CTLV_NODE_SCHEMA_NEST(CTLV_ATTESTATION_ATTR_CAP_EVIDENCE, 1, 5, 4, 4),
+	CTLV_NODE_SCHEMA_NEST(CTLV_ATTESTATION_ATTR_CAP_MR, 1, 9, 1, 1),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_CAP_MIN_CHALLENGE_LENGTH, 1, 0, U64_MAX),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_CAP_MAX_CHALLENGE_LENGTH, 1, 0, U64_MAX),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_CAP_MAX_TOTAL_OUTPUT_LENGTH, 1, 0, U64_MAX),
+	CTLV_NODE_SCHEMA_NEST(CTLV_ATTESTATION_ATTR_CAP_OBJECT, 16, 10, 4, 4),
+	CTLV_NODE_SCHEMA_FLAGS(CTLV_ATTESTATION_ATTR_CAP_MR_FLAGS, 1,
+			       CTLV_ATTESTATION_MR_DEVICE_CAPS_MASK),
+	CTLV_NODE_SCHEMA_ENUM(CTLV_ATTESTATION_ATTR_CAP_BLOB_CLASS, 1, 1),
+	CTLV_NODE_SCHEMA_STRING(CTLV_ATTESTATION_ATTR_CAP_FORMAT, 1, 1, 128),
+	CTLV_NODE_SCHEMA_ENUM(CTLV_ATTESTATION_ATTR_CAP_REPRESENTATION, 1, 1),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_CAP_MAX_LENGTH, 1, 0, U64_MAX),
+};
+
+/* Extension points selected by this tree. */
+static const struct ctlv_stub_schema device_get_reply_stub_schemas[] = {
+	CTLV_STUB_SCHEMA(CTLV_FAMILY_ATTESTATION, CTLV_ATTESTATION_SET_DEVICE_INFO, 2),
+};
+
+static const struct ctlv_node_schema evidence_get_request_node_schemas[] = {
+	CTLV_NODE_SCHEMA_ROOT(1, 2, 2),
+	CTLV_NODE_SCHEMA_BINARY(CTLV_ATTESTATION_ATTR_EVIDENCE_CHALLENGE, 1, 0, 4096),
+	CTLV_NODE_SCHEMA_NEST(CTLV_ATTESTATION_ATTR_EVIDENCE_OBJECT, 16, 3, 4, 4),
+	CTLV_NODE_SCHEMA_ENUM(CTLV_ATTESTATION_ATTR_EVIDENCE_BLOB_CLASS, 1, 1),
+	CTLV_NODE_SCHEMA_STRING(CTLV_ATTESTATION_ATTR_EVIDENCE_FORMAT, 1, 1, 128),
+	CTLV_NODE_SCHEMA_ENUM(CTLV_ATTESTATION_ATTR_EVIDENCE_REPRESENTATION, 1, 1),
+	CTLV_NODE_SCHEMA_BLOB(CTLV_ATTESTATION_ATTR_EVIDENCE_DATA, 1, U32_MAX, 1,
+			      BIT(CTLV_BLOB_TYPE_VA),
+			      CTLV_BLOB_DIRECTION_OUTPUT),
+};
+
+static const struct ctlv_node_schema evidence_get_reply_node_schemas[] = {
+	CTLV_NODE_SCHEMA_ROOT(1, 2, 1),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_EVIDENCE_OBJECT_LENGTH, 16, 0, U64_MAX),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_GENERATION, 1, 0, U32_MAX),
+};
+
+static const struct ctlv_node_schema mr_get_request_node_schemas[] = {
+	CTLV_NODE_SCHEMA_ROOT(1, 1, 1),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_ID, 1, 0, U32_MAX),
+};
+
+static const struct ctlv_node_schema mr_get_reply_node_schemas[] = {
+	CTLV_NODE_SCHEMA_ROOT(1, 4, 3),
+	CTLV_NODE_SCHEMA_STRING(CTLV_ATTESTATION_ATTR_MR_NAME, 1, 1, 128),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_SUPPORTED_HASH_ALGO, 21, 0, 20),
+	CTLV_NODE_SCHEMA_FLAGS(CTLV_ATTESTATION_ATTR_MR_CAPS, 1, CTLV_ATTESTATION_MR_CAPS_MASK),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_REGISTER_INDEX, 1, 0, U32_MAX),
+};
+
+static const struct ctlv_node_schema mr_dump_request_node_schemas[] = {
+	CTLV_NODE_SCHEMA_ROOT(0, 0, 0),
+};
+
+static const struct ctlv_node_schema mr_dump_reply_node_schemas[] = {
+	CTLV_NODE_SCHEMA_ROOT(1, 1, 1),
+	CTLV_NODE_SCHEMA_NEST(CTLV_ATTESTATION_ATTR_MR_ITEM, CTLV_NODE_SCHEMA_UNLIMITED, 2, 5, 4),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_ID, 1, 0, U32_MAX),
+	CTLV_NODE_SCHEMA_STRING(CTLV_ATTESTATION_ATTR_MR_NAME, 1, 1, 128),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_SUPPORTED_HASH_ALGO, 21, 0, 20),
+	CTLV_NODE_SCHEMA_FLAGS(CTLV_ATTESTATION_ATTR_MR_CAPS, 1, CTLV_ATTESTATION_MR_CAPS_MASK),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_REGISTER_INDEX, 1, 0, U32_MAX),
+};
+
+static const struct ctlv_node_schema mr_read_request_node_schemas[] = {
+	CTLV_NODE_SCHEMA_ROOT(1, 1, 1),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_ID, 1, 0, U32_MAX),
+};
+
+static const struct ctlv_node_schema mr_read_reply_node_schemas[] = {
+	CTLV_NODE_SCHEMA_ROOT(1, 2, 2),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_GENERATION, 1, 0, U32_MAX),
+	CTLV_NODE_SCHEMA_NEST(CTLV_ATTESTATION_ATTR_MR_VALUE, 21, 3, 2, 2),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_HASH_ALGO, 1, 0, 20),
+	CTLV_NODE_SCHEMA_BINARY(CTLV_ATTESTATION_ATTR_MR_DATA, 1, 16, 64),
+};
+
+static const struct ctlv_node_schema mr_extend_request_node_schemas[] = {
+	CTLV_NODE_SCHEMA_ROOT(1, 2, 2),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_ID, 1, 0, U32_MAX),
+	CTLV_NODE_SCHEMA_NEST(CTLV_ATTESTATION_ATTR_MR_VALUE, 21, 3, 2, 2),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_HASH_ALGO, 1, 0, 20),
+	CTLV_NODE_SCHEMA_BINARY(CTLV_ATTESTATION_ATTR_MR_DATA, 1, 16, 64),
+};
+
+static const struct ctlv_node_schema mr_extend_reply_node_schemas[] = {
+	CTLV_NODE_SCHEMA_ROOT(1, 1, 1),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_GENERATION, 1, 0, U32_MAX),
+};
+
+static const struct ctlv_node_schema mr_log_entry_appended_reply_node_schemas[] = {
+	CTLV_NODE_SCHEMA_ROOT(1, 1, 1),
+	CTLV_NODE_SCHEMA_NEST(CTLV_ATTESTATION_ATTR_NOTIFICATION_ENTRY, 1, 2, 5, 3),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_GENERATION, 1, 0, U32_MAX),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_ID, 1, 0, U32_MAX),
+	CTLV_NODE_SCHEMA_ENUM(CTLV_ATTESTATION_ATTR_LOG_EVENT, 1, 2),
+	CTLV_NODE_SCHEMA_NEST(CTLV_ATTESTATION_ATTR_MR_VALUE, 21, 7, 2, 2),
+	CTLV_NODE_SCHEMA_NEST(CTLV_ATTESTATION_ATTR_LOG_MR, 1, 9, 4, 3),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_HASH_ALGO, 1, 0, 20),
+	CTLV_NODE_SCHEMA_BINARY(CTLV_ATTESTATION_ATTR_MR_DATA, 1, 16, 64),
+	CTLV_NODE_SCHEMA_STRING(CTLV_ATTESTATION_ATTR_MR_NAME, 1, 1, 128),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_SUPPORTED_HASH_ALGO, 21, 0, 20),
+	CTLV_NODE_SCHEMA_FLAGS(CTLV_ATTESTATION_ATTR_MR_CAPS, 1, CTLV_ATTESTATION_MR_CAPS_MASK),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_REGISTER_INDEX, 1, 0, U32_MAX),
+};
+
+static const struct ctlv_node_schema mr_log_get_request_node_schemas[] = {
+	CTLV_NODE_SCHEMA_ROOT(1, 3, 0),
+	CTLV_NODE_SCHEMA_NEST(CTLV_ATTESTATION_ATTR_MR_SELECTION, 256, 4, 1, 1),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_START_GENERATION, 1, 0, U32_MAX),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_END_GENERATION, 1, 0, U32_MAX),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_ID, 1, 0, U32_MAX),
+};
+
+static const struct ctlv_node_schema mr_log_get_reply_node_schemas[] = {
+	CTLV_NODE_SCHEMA_ROOT(1, 3, 0),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_START_GENERATION, 1, 0, U32_MAX),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_END_GENERATION, 1, 0, U32_MAX),
+	CTLV_NODE_SCHEMA_NEST(CTLV_ATTESTATION_ATTR_LOG_ENTRY, CTLV_NODE_SCHEMA_UNLIMITED, 4, 5, 3),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_GENERATION, 1, 0, U32_MAX),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_ID, 1, 0, U32_MAX),
+	CTLV_NODE_SCHEMA_ENUM(CTLV_ATTESTATION_ATTR_LOG_EVENT, 1, 2),
+	CTLV_NODE_SCHEMA_NEST(CTLV_ATTESTATION_ATTR_MR_VALUE, 21, 9, 2, 2),
+	CTLV_NODE_SCHEMA_NEST(CTLV_ATTESTATION_ATTR_LOG_MR, 1, 11, 4, 3),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_HASH_ALGO, 1, 0, 20),
+	CTLV_NODE_SCHEMA_BINARY(CTLV_ATTESTATION_ATTR_MR_DATA, 1, 16, 64),
+	CTLV_NODE_SCHEMA_STRING(CTLV_ATTESTATION_ATTR_MR_NAME, 1, 1, 128),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_SUPPORTED_HASH_ALGO, 21, 0, 20),
+	CTLV_NODE_SCHEMA_FLAGS(CTLV_ATTESTATION_ATTR_MR_CAPS, 1, CTLV_ATTESTATION_MR_CAPS_MASK),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTESTATION_ATTR_MR_REGISTER_INDEX, 1, 0, U32_MAX),
+};
+
+/* The ops this family declares, in declaration order. */
+const struct ctlv_op_schema ctlv_attestation_op_schemas[] = {
+	CTLV_OP_SCHEMA_ACTION(CTLV_ATTESTATION_OP_DEVICE_GET, CTLV_OP_FD_ACCESS_READ,
+			      CTLV_OP_AVAILABILITY_FIXED, 16, 4016,
+			      CTLV_SCHEMA_TREE(device_get_request),
+			      CTLV_SCHEMA_TREE_STUBS(device_get_reply)),
+	CTLV_OP_SCHEMA_ACTION(CTLV_ATTESTATION_OP_EVIDENCE_GET, CTLV_OP_FD_ACCESS_READ_WRITE,
+			      CTLV_OP_AVAILABILITY_DYNAMIC, 8992, 424,
+			      CTLV_SCHEMA_TREE(evidence_get_request),
+			      CTLV_SCHEMA_TREE(evidence_get_reply), .optional = true),
+	CTLV_OP_SCHEMA_ACTION(CTLV_ATTESTATION_OP_MR_GET, CTLV_OP_FD_ACCESS_READ,
+			      CTLV_OP_AVAILABILITY_FIXED, 40, 720, CTLV_SCHEMA_TREE(mr_get_request),
+			      CTLV_SCHEMA_TREE(mr_get_reply), .optional = true),
+	CTLV_OP_SCHEMA_QUERY(CTLV_ATTESTATION_OP_MR_DUMP, CTLV_OP_FD_ACCESS_READ,
+			     CTLV_OP_AVAILABILITY_FIXED, 16, 184, 4096,
+			     CTLV_SCHEMA_TREE(mr_dump_request), CTLV_SCHEMA_TREE(mr_dump_reply),
+			     .optional = true),
+	CTLV_OP_SCHEMA_QUERY(CTLV_ATTESTATION_OP_MR_READ, CTLV_OP_FD_ACCESS_READ,
+			     CTLV_OP_AVAILABILITY_FIXED, 40, 112, 4096,
+			     CTLV_SCHEMA_TREE(mr_read_request), CTLV_SCHEMA_TREE(mr_read_reply),
+			     .optional = true),
+	CTLV_OP_SCHEMA_ACTION(CTLV_ATTESTATION_OP_MR_EXTEND, CTLV_OP_FD_ACCESS_READ_WRITE,
+			      CTLV_OP_AVAILABILITY_FIXED, 2560, 40,
+			      CTLV_SCHEMA_TREE(mr_extend_request),
+			      CTLV_SCHEMA_TREE(mr_extend_reply), .optional = true),
+	CTLV_OP_SCHEMA_EVENT(CTLV_ATTESTATION_OP_MR_LOG_ENTRY_APPENDED, 3368,
+			     CTLV_SCHEMA_TREE(mr_log_entry_appended_reply)),
+	CTLV_OP_SCHEMA_QUERY(CTLV_ATTESTATION_OP_MR_LOG_GET, CTLV_OP_FD_ACCESS_READ,
+			     CTLV_OP_AVAILABILITY_FIXED, 10304, 200, 131072,
+			     CTLV_SCHEMA_TREE(mr_log_get_request),
+			     CTLV_SCHEMA_TREE(mr_log_get_reply), .optional = true),
+};
+
+/* The family ID is its position in the central registry. */
+const struct ctlv_family_schema ctlv_attestation_schema = {
+	.name = "ctlv-attestation",
+	.family_id = 1,
+	.ops = ctlv_attestation_op_schemas,
+	.ops_count = ARRAY_SIZE(ctlv_attestation_op_schemas),
+};
+
+/* Maximum uevent cost for this family chain. */
+static_assert(107 <= CTLV_UEVENT_MAX_LEN);
+static_assert(4 <= CTLV_UEVENT_MAX_VARS);
+
+/* Guards for generated maxima. */
+static_assert(131072 <= CTLV_MAX_INLINE_MESSAGE_LEN);
+static_assert(3368 <= CTLV_MAX_EVENT_QUEUE_LEN);
+static_assert(3 <= CTLV_MAX_DECLARED_NEST_DEPTH);
+
+/* Local action and query bindings in declaration order. */
+static const struct ctlv_op ctlv_attestation_ops[] = {
+	CTLV_OP_ACTION(ctlv_attestation_device_get),
+	CTLV_OP_ACTION(ctlv_attestation_evidence_get),
+	CTLV_OP_ACTION(ctlv_attestation_mr_get),
+	CTLV_OP_QUERY(ctlv_attestation_mr_dump),
+	CTLV_OP_QUERY(ctlv_attestation_mr_read),
+	CTLV_OP_ACTION(ctlv_attestation_mr_extend),
+	CTLV_OP_QUERY(ctlv_attestation_mr_log_get),
+};
+
+/* Family descriptor used by ctlv_create(). */
+const struct ctlv_family ctlv_attestation_family = {
+	.schema = &ctlv_attestation_schema,
+	.parent = &ctlv_family,
+	.ops = ctlv_attestation_ops,
+	.ops_count = ARRAY_SIZE(ctlv_attestation_ops),
+	.pre = ctlv_attestation_op_pre,
+	.post = ctlv_attestation_op_post,
+	.priv_size = ctlv_attestation_priv_size,
+	.init = ctlv_attestation_init,
+	.post_init = ctlv_attestation_post_init,
+	.pre_fini = ctlv_attestation_pre_fini,
+	.fini = ctlv_attestation_fini,
+};
+EXPORT_SYMBOL_NS_GPL(ctlv_attestation_family, "CTLV");
diff --git a/drivers/attestation/generated/ctlv_attestation_gen.h b/drivers/attestation/generated/ctlv_attestation_gen.h
new file mode 100644
index 0000000000000..a40ed0757756b
--- /dev/null
+++ b/drivers/attestation/generated/ctlv_attestation_gen.h
@@ -0,0 +1,198 @@
+/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) */
+/* Do not edit, regenerate with tools/ctlv/ctlv-regen.sh, from: */
+/*	Documentation/ctlv/specs/ctlv-attestation.yaml */
+/* CTLV-GEN kernel header */
+
+/* Kernel metadata and family API of the ctlv-attestation CTLV family. */
+
+#ifndef _LINUX_CTLV_ATTESTATION_GEN_H
+#define _LINUX_CTLV_ATTESTATION_GEN_H
+
+#include <linux/ctlv_family.h>
+#include <linux/err.h>
+#include <linux/errno.h>
+
+#include <uapi/linux/ctlv_attestation_gen.h>
+
+/* Ops this family declares, in declaration order. */
+extern const struct ctlv_op_schema ctlv_attestation_op_schemas[];
+
+extern const struct ctlv_family_schema ctlv_attestation_schema;
+
+/* Implemented by this family, one per action and query it declares. */
+int ctlv_attestation_device_get_action(void *priv, struct ctlv_op_ctx *ctx,
+				       const struct ctlv_cursor *request,
+				       struct ctlv_cursor *reply);
+int ctlv_attestation_evidence_get_action(void *priv, struct ctlv_op_ctx *ctx,
+					 const struct ctlv_cursor *request,
+					 struct ctlv_cursor *reply);
+int ctlv_attestation_mr_get_action(void *priv, struct ctlv_op_ctx *ctx,
+				   const struct ctlv_cursor *request, struct ctlv_cursor *reply);
+int ctlv_attestation_mr_dump_query(void *priv, struct ctlv_op_ctx *ctx,
+				   const struct ctlv_cursor *request, struct ctlv_cursor *reply);
+int ctlv_attestation_mr_read_query(void *priv, struct ctlv_op_ctx *ctx,
+				   const struct ctlv_cursor *request, struct ctlv_cursor *reply);
+int ctlv_attestation_mr_extend_action(void *priv, struct ctlv_op_ctx *ctx,
+				      const struct ctlv_cursor *request, struct ctlv_cursor *reply);
+int ctlv_attestation_mr_log_get_query(void *priv, struct ctlv_op_ctx *ctx,
+				      const struct ctlv_cursor *request, struct ctlv_cursor *reply);
+
+/* Family-wide hooks around every effective non-core op. */
+int ctlv_attestation_op_pre(void *priv, struct ctlv_op_ctx *ctx);
+void ctlv_attestation_op_post(void *priv, struct ctlv_op_ctx *ctx);
+
+/* Core-allocated family priv lifecycle. */
+size_t ctlv_attestation_priv_size(void);
+int ctlv_attestation_init(struct ctlv_device *ctlvdev, const void *init_info, void *priv);
+int ctlv_attestation_post_init(struct ctlv_device *ctlvdev, void *priv);
+void ctlv_attestation_pre_fini(struct ctlv_device *ctlvdev, void *priv);
+void ctlv_attestation_fini(struct ctlv_device *ctlvdev, void *priv);
+
+extern const struct ctlv_family ctlv_attestation_family;
+
+#ifndef _CTLV_GENERATED_METADATA_ONLY
+
+/* Optional publication and dynamic availability helpers. */
+CTLV_OP_PROVIDE(ctlv_attestation_evidence_get, CTLV_ATTESTATION_OP_EVIDENCE_GET)
+CTLV_OP_ENABLE(ctlv_attestation_evidence_get, CTLV_ATTESTATION_OP_EVIDENCE_GET)
+CTLV_OP_DISABLE(ctlv_attestation_evidence_get, CTLV_ATTESTATION_OP_EVIDENCE_GET)
+CTLV_OP_PROVIDE(ctlv_attestation_mr_get, CTLV_ATTESTATION_OP_MR_GET)
+CTLV_OP_PROVIDE(ctlv_attestation_mr_dump, CTLV_ATTESTATION_OP_MR_DUMP)
+CTLV_OP_PROVIDE(ctlv_attestation_mr_read, CTLV_ATTESTATION_OP_MR_READ)
+CTLV_OP_PROVIDE(ctlv_attestation_mr_extend, CTLV_ATTESTATION_OP_MR_EXTEND)
+CTLV_OP_PROVIDE(ctlv_attestation_mr_log_get, CTLV_ATTESTATION_OP_MR_LOG_GET)
+
+/* Reading a validated message. A blob has a resolver instead of a getter. */
+CTLV_IN_REF(ctlv_attestation_evidence_get_evidence_challenge,
+	    &ctlv_attestation_op_schemas[1].request, CTLV_ATTESTATION_ATTR_EVIDENCE_CHALLENGE, 0, 0,
+	    CTLV_SCHEMA_BINARY)
+CTLV_IN_HAS(ctlv_attestation_evidence_get_evidence_challenge)
+CTLV_IN_BINARY(ctlv_attestation_evidence_get_evidence_challenge)
+CTLV_IN_REF(ctlv_attestation_evidence_get_evidence_object, &ctlv_attestation_op_schemas[1].request,
+	    CTLV_ATTESTATION_ATTR_EVIDENCE_OBJECT, 0, 1, CTLV_SCHEMA_NEST)
+#define ctlv_attestation_evidence_get_evidence_object_for_each(_attr, _nest) \
+	CTLV_IN_FOR_EACH(ctlv_attestation_evidence_get_evidence_object, _attr, _nest)
+CTLV_IN_REF(ctlv_attestation_evidence_get_object_evidence_blob_class,
+	    &ctlv_attestation_op_schemas[1].request, CTLV_ATTESTATION_ATTR_EVIDENCE_BLOB_CLASS, 2,
+	    0, CTLV_SCHEMA_ENUM)
+CTLV_IN_HAS(ctlv_attestation_evidence_get_object_evidence_blob_class)
+CTLV_IN_U64(ctlv_attestation_evidence_get_object_evidence_blob_class)
+CTLV_IN_REF(ctlv_attestation_evidence_get_object_evidence_format,
+	    &ctlv_attestation_op_schemas[1].request, CTLV_ATTESTATION_ATTR_EVIDENCE_FORMAT, 2, 1,
+	    CTLV_SCHEMA_STRING)
+CTLV_IN_HAS(ctlv_attestation_evidence_get_object_evidence_format)
+CTLV_IN_STRING(ctlv_attestation_evidence_get_object_evidence_format)
+CTLV_IN_REF(ctlv_attestation_evidence_get_object_evidence_representation,
+	    &ctlv_attestation_op_schemas[1].request, CTLV_ATTESTATION_ATTR_EVIDENCE_REPRESENTATION,
+	    2, 2, CTLV_SCHEMA_ENUM)
+CTLV_IN_HAS(ctlv_attestation_evidence_get_object_evidence_representation)
+CTLV_IN_U64(ctlv_attestation_evidence_get_object_evidence_representation)
+CTLV_IN_REF(ctlv_attestation_evidence_get_object_evidence_data,
+	    &ctlv_attestation_op_schemas[1].request, CTLV_ATTESTATION_ATTR_EVIDENCE_DATA, 2, 3,
+	    CTLV_SCHEMA_BLOB)
+CTLV_IN_HAS(ctlv_attestation_evidence_get_object_evidence_data)
+CTLV_IN_BLOB(ctlv_attestation_evidence_get_object_evidence_data)
+CTLV_IN_REF(ctlv_attestation_mr_get_mr_id, &ctlv_attestation_op_schemas[2].request,
+	    CTLV_ATTESTATION_ATTR_MR_ID, 0, 0, CTLV_SCHEMA_UINT)
+CTLV_IN_HAS(ctlv_attestation_mr_get_mr_id)
+CTLV_IN_U64(ctlv_attestation_mr_get_mr_id)
+CTLV_IN_REF(ctlv_attestation_mr_read_mr_id, &ctlv_attestation_op_schemas[4].request,
+	    CTLV_ATTESTATION_ATTR_MR_ID, 0, 0, CTLV_SCHEMA_UINT)
+CTLV_IN_HAS(ctlv_attestation_mr_read_mr_id)
+CTLV_IN_U64(ctlv_attestation_mr_read_mr_id)
+CTLV_IN_REF(ctlv_attestation_mr_extend_mr_id, &ctlv_attestation_op_schemas[5].request,
+	    CTLV_ATTESTATION_ATTR_MR_ID, 0, 0, CTLV_SCHEMA_UINT)
+CTLV_IN_HAS(ctlv_attestation_mr_extend_mr_id)
+CTLV_IN_U64(ctlv_attestation_mr_extend_mr_id)
+CTLV_IN_REF(ctlv_attestation_mr_extend_mr_value, &ctlv_attestation_op_schemas[5].request,
+	    CTLV_ATTESTATION_ATTR_MR_VALUE, 0, 1, CTLV_SCHEMA_NEST)
+#define ctlv_attestation_mr_extend_mr_value_for_each(_attr, _nest) \
+	CTLV_IN_FOR_EACH(ctlv_attestation_mr_extend_mr_value, _attr, _nest)
+CTLV_IN_REF(ctlv_attestation_mr_extend_value_mr_hash_algo, &ctlv_attestation_op_schemas[5].request,
+	    CTLV_ATTESTATION_ATTR_MR_HASH_ALGO, 2, 0, CTLV_SCHEMA_UINT)
+CTLV_IN_HAS(ctlv_attestation_mr_extend_value_mr_hash_algo)
+CTLV_IN_U64(ctlv_attestation_mr_extend_value_mr_hash_algo)
+CTLV_IN_REF(ctlv_attestation_mr_extend_value_mr_data, &ctlv_attestation_op_schemas[5].request,
+	    CTLV_ATTESTATION_ATTR_MR_DATA, 2, 1, CTLV_SCHEMA_BINARY)
+CTLV_IN_HAS(ctlv_attestation_mr_extend_value_mr_data)
+CTLV_IN_BINARY(ctlv_attestation_mr_extend_value_mr_data)
+CTLV_IN_REF(ctlv_attestation_mr_log_get_mr_selection, &ctlv_attestation_op_schemas[7].request,
+	    CTLV_ATTESTATION_ATTR_MR_SELECTION, 0, 0, CTLV_SCHEMA_NEST)
+#define ctlv_attestation_mr_log_get_mr_selection_for_each(_attr, _nest) \
+	CTLV_IN_FOR_EACH(ctlv_attestation_mr_log_get_mr_selection, _attr, _nest)
+CTLV_IN_REF(ctlv_attestation_mr_log_get_mr_start_generation,
+	    &ctlv_attestation_op_schemas[7].request, CTLV_ATTESTATION_ATTR_MR_START_GENERATION, 0,
+	    1, CTLV_SCHEMA_UINT)
+CTLV_IN_HAS(ctlv_attestation_mr_log_get_mr_start_generation)
+CTLV_IN_U64(ctlv_attestation_mr_log_get_mr_start_generation)
+CTLV_IN_REF(ctlv_attestation_mr_log_get_mr_end_generation, &ctlv_attestation_op_schemas[7].request,
+	    CTLV_ATTESTATION_ATTR_MR_END_GENERATION, 0, 2, CTLV_SCHEMA_UINT)
+CTLV_IN_HAS(ctlv_attestation_mr_log_get_mr_end_generation)
+CTLV_IN_U64(ctlv_attestation_mr_log_get_mr_end_generation)
+CTLV_IN_REF(ctlv_attestation_mr_log_get_selection_mr_id, &ctlv_attestation_op_schemas[7].request,
+	    CTLV_ATTESTATION_ATTR_MR_ID, 1, 0, CTLV_SCHEMA_UINT)
+CTLV_IN_HAS(ctlv_attestation_mr_log_get_selection_mr_id)
+CTLV_IN_U64(ctlv_attestation_mr_log_get_selection_mr_id)
+
+/* Writing a reply. An append is atomic; a nest ends with ctlv_nest_end(). */
+CTLV_PUT_U64(ctlv_attestation_device_generation, CTLV_ATTESTATION_ATTR_DEVICE_GENERATION,
+	     CTLV_SCHEMA_UINT)
+CTLV_NEST_START(ctlv_attestation_device_caps, CTLV_ATTESTATION_ATTR_DEVICE_CAPS, CTLV_SCHEMA_NEST)
+CTLV_NEST_START(ctlv_attestation_device_info, CTLV_ATTESTATION_ATTR_DEVICE_INFO, CTLV_SCHEMA_NEST)
+CTLV_NEST_START(ctlv_attestation_cap_evidence, CTLV_ATTESTATION_ATTR_CAP_EVIDENCE, CTLV_SCHEMA_NEST)
+CTLV_NEST_START(ctlv_attestation_cap_mr, CTLV_ATTESTATION_ATTR_CAP_MR, CTLV_SCHEMA_NEST)
+CTLV_PUT_U64(ctlv_attestation_cap_min_challenge_length,
+	     CTLV_ATTESTATION_ATTR_CAP_MIN_CHALLENGE_LENGTH, CTLV_SCHEMA_UINT)
+CTLV_PUT_U64(ctlv_attestation_cap_max_challenge_length,
+	     CTLV_ATTESTATION_ATTR_CAP_MAX_CHALLENGE_LENGTH, CTLV_SCHEMA_UINT)
+CTLV_PUT_U64(ctlv_attestation_cap_max_total_output_length,
+	     CTLV_ATTESTATION_ATTR_CAP_MAX_TOTAL_OUTPUT_LENGTH, CTLV_SCHEMA_UINT)
+CTLV_PUT_U64(ctlv_attestation_cap_mr_flags, CTLV_ATTESTATION_ATTR_CAP_MR_FLAGS, CTLV_SCHEMA_FLAGS)
+CTLV_NEST_START(ctlv_attestation_cap_object, CTLV_ATTESTATION_ATTR_CAP_OBJECT, CTLV_SCHEMA_NEST)
+CTLV_PUT_U64(ctlv_attestation_cap_blob_class, CTLV_ATTESTATION_ATTR_CAP_BLOB_CLASS,
+	     CTLV_SCHEMA_ENUM)
+CTLV_PUT_STRING(ctlv_attestation_cap_format, CTLV_ATTESTATION_ATTR_CAP_FORMAT, CTLV_SCHEMA_STRING)
+CTLV_PUT_U64(ctlv_attestation_cap_representation, CTLV_ATTESTATION_ATTR_CAP_REPRESENTATION,
+	     CTLV_SCHEMA_ENUM)
+CTLV_PUT_U64(ctlv_attestation_cap_max_length, CTLV_ATTESTATION_ATTR_CAP_MAX_LENGTH,
+	     CTLV_SCHEMA_UINT)
+CTLV_PUT_BINARY(ctlv_attestation_evidence_challenge, CTLV_ATTESTATION_ATTR_EVIDENCE_CHALLENGE,
+		CTLV_SCHEMA_BINARY)
+CTLV_NEST_START(ctlv_attestation_evidence_object, CTLV_ATTESTATION_ATTR_EVIDENCE_OBJECT,
+		CTLV_SCHEMA_NEST)
+CTLV_PUT_U64(ctlv_attestation_evidence_blob_class, CTLV_ATTESTATION_ATTR_EVIDENCE_BLOB_CLASS,
+	     CTLV_SCHEMA_ENUM)
+CTLV_PUT_STRING(ctlv_attestation_evidence_format, CTLV_ATTESTATION_ATTR_EVIDENCE_FORMAT,
+		CTLV_SCHEMA_STRING)
+CTLV_PUT_U64(ctlv_attestation_evidence_representation,
+	     CTLV_ATTESTATION_ATTR_EVIDENCE_REPRESENTATION, CTLV_SCHEMA_ENUM)
+CTLV_PUT_U64(ctlv_attestation_evidence_object_length, CTLV_ATTESTATION_ATTR_EVIDENCE_OBJECT_LENGTH,
+	     CTLV_SCHEMA_UINT)
+CTLV_PUT_U64(ctlv_attestation_mr_id, CTLV_ATTESTATION_ATTR_MR_ID, CTLV_SCHEMA_UINT)
+CTLV_PUT_STRING(ctlv_attestation_mr_name, CTLV_ATTESTATION_ATTR_MR_NAME, CTLV_SCHEMA_STRING)
+CTLV_PUT_U64(ctlv_attestation_mr_hash_algo, CTLV_ATTESTATION_ATTR_MR_HASH_ALGO, CTLV_SCHEMA_UINT)
+CTLV_PUT_U64(ctlv_attestation_mr_supported_hash_algo, CTLV_ATTESTATION_ATTR_MR_SUPPORTED_HASH_ALGO,
+	     CTLV_SCHEMA_UINT)
+CTLV_PUT_U64(ctlv_attestation_mr_register_index, CTLV_ATTESTATION_ATTR_MR_REGISTER_INDEX,
+	     CTLV_SCHEMA_UINT)
+CTLV_PUT_U64(ctlv_attestation_mr_caps, CTLV_ATTESTATION_ATTR_MR_CAPS, CTLV_SCHEMA_FLAGS)
+CTLV_NEST_START(ctlv_attestation_mr_item, CTLV_ATTESTATION_ATTR_MR_ITEM, CTLV_SCHEMA_NEST)
+CTLV_NEST_START(ctlv_attestation_mr_value, CTLV_ATTESTATION_ATTR_MR_VALUE, CTLV_SCHEMA_NEST)
+CTLV_PUT_BINARY(ctlv_attestation_mr_data, CTLV_ATTESTATION_ATTR_MR_DATA, CTLV_SCHEMA_BINARY)
+CTLV_PUT_U64(ctlv_attestation_mr_generation, CTLV_ATTESTATION_ATTR_MR_GENERATION, CTLV_SCHEMA_UINT)
+CTLV_NEST_START(ctlv_attestation_mr_selection, CTLV_ATTESTATION_ATTR_MR_SELECTION, CTLV_SCHEMA_NEST)
+CTLV_PUT_U64(ctlv_attestation_mr_start_generation, CTLV_ATTESTATION_ATTR_MR_START_GENERATION,
+	     CTLV_SCHEMA_UINT)
+CTLV_PUT_U64(ctlv_attestation_mr_end_generation, CTLV_ATTESTATION_ATTR_MR_END_GENERATION,
+	     CTLV_SCHEMA_UINT)
+CTLV_NEST_START(ctlv_attestation_log_entry, CTLV_ATTESTATION_ATTR_LOG_ENTRY, CTLV_SCHEMA_NEST)
+CTLV_PUT_U64(ctlv_attestation_log_event, CTLV_ATTESTATION_ATTR_LOG_EVENT, CTLV_SCHEMA_ENUM)
+CTLV_NEST_START(ctlv_attestation_log_mr, CTLV_ATTESTATION_ATTR_LOG_MR, CTLV_SCHEMA_NEST)
+CTLV_NEST_START(ctlv_attestation_notification_entry, CTLV_ATTESTATION_ATTR_NOTIFICATION_ENTRY,
+		CTLV_SCHEMA_NEST)
+
+/* Building one event, passed to ctlv_event_emit() or ctlv_event_abort() once. */
+CTLV_EVENT_CREATE(ctlv_attestation_mr_log_entry_appended, CTLV_ATTESTATION_OP_MR_LOG_ENTRY_APPENDED)
+#endif /* _CTLV_GENERATED_METADATA_ONLY */
+
+#endif /* _LINUX_CTLV_ATTESTATION_GEN_H */
diff --git a/drivers/attestation/generated/ctlv_attestation_tdx_gen.c b/drivers/attestation/generated/ctlv_attestation_tdx_gen.c
new file mode 100644
index 0000000000000..25f03a8d68fea
--- /dev/null
+++ b/drivers/attestation/generated/ctlv_attestation_tdx_gen.c
@@ -0,0 +1,61 @@
+// SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)
+/* Do not edit, regenerate with tools/ctlv/ctlv-regen.sh, from: */
+/*	Documentation/ctlv/specs/ctlv-attestation-tdx.yaml */
+/* CTLV-GEN kernel source */
+
+#define _CTLV_GENERATED_METADATA_ONLY
+#include <linux/array_size.h>
+#include <linux/build_bug.h>
+#include <linux/ctlv_family.h>
+#include <linux/export.h>
+
+#include <uapi/linux/ctlv_gen.h>
+#include <uapi/linux/ctlv_attestation_tdx_gen.h>
+
+#include "ctlv_attestation_tdx_gen.h"
+
+static const struct ctlv_node_schema device_info_fill_node_schemas[] = {
+	CTLV_NODE_SCHEMA_ROOT(1, 3, 3),
+	CTLV_NODE_SCHEMA_BINARY(CTLV_ATTESTATION_TDX_ATTR_INFO_MRCONFIGID, 1, 48, 48),
+	CTLV_NODE_SCHEMA_BINARY(CTLV_ATTESTATION_TDX_ATTR_INFO_MROWNER, 1, 48, 48),
+	CTLV_NODE_SCHEMA_BINARY(CTLV_ATTESTATION_TDX_ATTR_INFO_MROWNERCONFIG, 1, 48, 48),
+};
+
+/* The extension points this family fills. */
+static const struct ctlv_stub_fill_schema ctlv_attestation_tdx_stub_fill_schemas[] = {
+	CTLV_STUB_FILL_SCHEMA(CTLV_FAMILY_ATTESTATION, CTLV_ATTESTATION_SET_DEVICE_INFO,
+			      device_info),
+};
+
+/* The family ID is its position in the central registry. */
+const struct ctlv_family_schema ctlv_attestation_tdx_schema = {
+	.name = "ctlv-attestation-tdx",
+	.family_id = 2,
+	.stub_fill_schemas = ctlv_attestation_tdx_stub_fill_schemas,
+	.stub_fill_schemas_count = ARRAY_SIZE(ctlv_attestation_tdx_stub_fill_schemas),
+};
+
+/* Maximum uevent cost for this family chain. */
+static_assert(150 <= CTLV_UEVENT_MAX_LEN);
+static_assert(5 <= CTLV_UEVENT_MAX_VARS);
+
+/* Extension-point callbacks. */
+static const struct ctlv_stub_ops ctlv_attestation_tdx_stub_ops[] = {
+	CTLV_STUB_OPS(CTLV_FAMILY_ATTESTATION, CTLV_ATTESTATION_SET_DEVICE_INFO,
+		      ctlv_attestation_tdx_device_info),
+};
+
+/* Family descriptor used by ctlv_create(). */
+const struct ctlv_family ctlv_attestation_tdx_family = {
+	.schema = &ctlv_attestation_tdx_schema,
+	.parent = &ctlv_attestation_family,
+	.pre = ctlv_attestation_tdx_op_pre,
+	.post = ctlv_attestation_tdx_op_post,
+	.priv_size = ctlv_attestation_tdx_priv_size,
+	.pre_init = ctlv_attestation_tdx_pre_init,
+	.init = ctlv_attestation_tdx_init,
+	.fini = ctlv_attestation_tdx_fini,
+	.stub_ops = ctlv_attestation_tdx_stub_ops,
+	.stub_ops_count = ARRAY_SIZE(ctlv_attestation_tdx_stub_ops),
+};
+EXPORT_SYMBOL_NS_GPL(ctlv_attestation_tdx_family, "CTLV");
diff --git a/drivers/attestation/generated/ctlv_attestation_tdx_gen.h b/drivers/attestation/generated/ctlv_attestation_tdx_gen.h
new file mode 100644
index 0000000000000..d182d04cb086b
--- /dev/null
+++ b/drivers/attestation/generated/ctlv_attestation_tdx_gen.h
@@ -0,0 +1,66 @@
+/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) */
+/* Do not edit, regenerate with tools/ctlv/ctlv-regen.sh, from: */
+/*	Documentation/ctlv/specs/ctlv-attestation-tdx.yaml */
+/* CTLV-GEN kernel header */
+
+/* Kernel metadata and family API of the ctlv-attestation-tdx CTLV family. */
+
+#ifndef _LINUX_CTLV_ATTESTATION_TDX_GEN_H
+#define _LINUX_CTLV_ATTESTATION_TDX_GEN_H
+
+#include <linux/ctlv_family.h>
+#include <linux/err.h>
+#include <linux/errno.h>
+
+#include <uapi/linux/ctlv_attestation_tdx_gen.h>
+
+#include "ctlv_attestation_gen.h"
+
+extern const struct ctlv_family_schema ctlv_attestation_tdx_schema;
+
+/* Family-wide hooks around every effective non-core op. */
+int ctlv_attestation_tdx_op_pre(void *priv, struct ctlv_op_ctx *ctx);
+void ctlv_attestation_tdx_op_post(void *priv, struct ctlv_op_ctx *ctx);
+
+/* Core-allocated family priv lifecycle. */
+size_t ctlv_attestation_tdx_priv_size(void);
+const void *ctlv_attestation_tdx_pre_init(const void *init_info);
+int ctlv_attestation_tdx_init(struct ctlv_device *ctlvdev, const void *init_info, void *priv);
+void ctlv_attestation_tdx_fini(struct ctlv_device *ctlvdev, void *priv);
+
+/* device-info of ctlv-attestation: fill callback. */
+int ctlv_attestation_tdx_device_info_fill(void *priv, struct ctlv_op_ctx *ctx,
+					  const struct ctlv_cursor *request,
+					  struct ctlv_cursor *nest);
+
+extern const struct ctlv_family ctlv_attestation_tdx_family;
+
+#ifndef _CTLV_GENERATED_METADATA_ONLY
+
+/* Reading a validated message. A blob has a resolver instead of a getter. */
+CTLV_IN_REF(ctlv_attestation_tdx_device_info_info_mrconfigid,
+	    &ctlv_attestation_tdx_schema.stub_fill_schemas[0].members,
+	    CTLV_ATTESTATION_TDX_ATTR_INFO_MRCONFIGID, 0, 0, CTLV_SCHEMA_BINARY)
+CTLV_IN_HAS(ctlv_attestation_tdx_device_info_info_mrconfigid)
+CTLV_IN_BINARY(ctlv_attestation_tdx_device_info_info_mrconfigid)
+CTLV_IN_REF(ctlv_attestation_tdx_device_info_info_mrowner,
+	    &ctlv_attestation_tdx_schema.stub_fill_schemas[0].members,
+	    CTLV_ATTESTATION_TDX_ATTR_INFO_MROWNER, 0, 1, CTLV_SCHEMA_BINARY)
+CTLV_IN_HAS(ctlv_attestation_tdx_device_info_info_mrowner)
+CTLV_IN_BINARY(ctlv_attestation_tdx_device_info_info_mrowner)
+CTLV_IN_REF(ctlv_attestation_tdx_device_info_info_mrownerconfig,
+	    &ctlv_attestation_tdx_schema.stub_fill_schemas[0].members,
+	    CTLV_ATTESTATION_TDX_ATTR_INFO_MROWNERCONFIG, 0, 2, CTLV_SCHEMA_BINARY)
+CTLV_IN_HAS(ctlv_attestation_tdx_device_info_info_mrownerconfig)
+CTLV_IN_BINARY(ctlv_attestation_tdx_device_info_info_mrownerconfig)
+
+/* Writing a reply. An append is atomic; a nest ends with ctlv_nest_end(). */
+CTLV_PUT_BINARY(ctlv_attestation_tdx_info_mrconfigid, CTLV_ATTESTATION_TDX_ATTR_INFO_MRCONFIGID,
+		CTLV_SCHEMA_BINARY)
+CTLV_PUT_BINARY(ctlv_attestation_tdx_info_mrowner, CTLV_ATTESTATION_TDX_ATTR_INFO_MROWNER,
+		CTLV_SCHEMA_BINARY)
+CTLV_PUT_BINARY(ctlv_attestation_tdx_info_mrownerconfig,
+		CTLV_ATTESTATION_TDX_ATTR_INFO_MROWNERCONFIG, CTLV_SCHEMA_BINARY)
+#endif /* _CTLV_GENERATED_METADATA_ONLY */
+
+#endif /* _LINUX_CTLV_ATTESTATION_TDX_GEN_H */
diff --git a/drivers/attestation/providers/tdx.c b/drivers/attestation/providers/tdx.c
new file mode 100644
index 0000000000000..9b41b985c783a
--- /dev/null
+++ b/drivers/attestation/providers/tdx.c
@@ -0,0 +1,277 @@
+// SPDX-License-Identifier: GPL-2.0-only
+#include <crypto/sha2.h>
+#include <linux/attestation.h>
+#include <linux/ctlv.h>
+#include <linux/err.h>
+#include <linux/module.h>
+#include <linux/slab.h>
+#include <linux/tdx-guest.h>
+
+#include "../generated/ctlv_attestation_tdx_gen.h"
+
+struct attestation_tdx_init_info {
+	struct device *parent_dev;
+	const struct tdx_guest_ops *ops;
+};
+
+struct attestation_tdx {
+	struct device *parent_dev;
+	const struct tdx_guest_ops *ops;
+};
+
+static const enum hash_algo attestation_tdx_algorithms[] = {
+	HASH_ALGO_SHA384,
+};
+
+static const struct attestation_mr_props attestation_tdx_mrs[] = {
+	{
+		.id = 0,
+		.name = "mrtd",
+		.algorithms = attestation_tdx_algorithms,
+		.algorithms_count = ARRAY_SIZE(attestation_tdx_algorithms),
+		.readable = true,
+	},
+	{
+		.id = 1,
+		.name = "rtmr0",
+		.algorithms = attestation_tdx_algorithms,
+		.algorithms_count = ARRAY_SIZE(attestation_tdx_algorithms),
+		.has_register_index = true,
+		.register_index = 0,
+		.readable = true,
+		.extendable = true,
+	},
+	{
+		.id = 2,
+		.name = "rtmr1",
+		.algorithms = attestation_tdx_algorithms,
+		.algorithms_count = ARRAY_SIZE(attestation_tdx_algorithms),
+		.has_register_index = true,
+		.register_index = 1,
+		.readable = true,
+		.extendable = true,
+	},
+	{
+		.id = 3,
+		.name = "rtmr2",
+		.algorithms = attestation_tdx_algorithms,
+		.algorithms_count = ARRAY_SIZE(attestation_tdx_algorithms),
+		.has_register_index = true,
+		.register_index = 2,
+		.readable = true,
+		.extendable = true,
+	},
+	{
+		.id = 4,
+		.name = "rtmr3",
+		.algorithms = attestation_tdx_algorithms,
+		.algorithms_count = ARRAY_SIZE(attestation_tdx_algorithms),
+		.has_register_index = true,
+		.register_index = 3,
+		.readable = true,
+		.extendable = true,
+	},
+};
+
+static const struct attestation_evidence_supported_object
+attestation_tdx_evidence_objects[] = {
+	{
+		.format = "tdx-tdreport-1.0",
+		.max_length = TDX_GUEST_REPORT_LEN,
+		.binds_mrs = true,
+	},
+	{
+		.format = "tdx-quote-1.0",
+		.max_length = TDX_GUEST_QUOTE_MAX_LEN,
+		.binds_mrs = true,
+	},
+};
+
+static const struct attestation_evidence_caps attestation_tdx_evidence_caps = {
+	.min_challenge_length = TDX_GUEST_REPORTDATA_LEN,
+	.max_challenge_length = TDX_GUEST_REPORTDATA_LEN,
+	.max_total_output_length = TDX_GUEST_QUOTE_MAX_LEN,
+	.objects = attestation_tdx_evidence_objects,
+	.objects_count = ARRAY_SIZE(attestation_tdx_evidence_objects),
+};
+
+static int
+attestation_tdx_evidence_get(struct attestation *att,
+			     const struct attestation_evidence_request *request,
+			     struct attestation_evidence_result *result)
+{
+	const struct attestation_evidence_object_request *object;
+	struct attestation_tdx *tdx = ctlv_priv_child(att);
+	size_t length;
+	void *buffer;
+	int ret;
+
+	if (request->objects_count != 1)
+		return -EOPNOTSUPP;
+	object = &request->objects[0];
+	buffer = kvmalloc(object->supported_object->max_length, GFP_KERNEL);
+	if (!buffer)
+		return -ENOMEM;
+	if (object->supported_object == &attestation_tdx_evidence_objects[0])
+		ret = tdx->ops->report_get(tdx->parent_dev,
+			request->challenge,
+			request->challenge_length, buffer,
+			object->supported_object->max_length, &length);
+	else if (object->supported_object ==
+		 &attestation_tdx_evidence_objects[1])
+		ret = tdx->ops->quote_get(tdx->parent_dev,
+			request->challenge,
+			request->challenge_length, buffer,
+			object->supported_object->max_length, &length);
+	else
+		ret = -EOPNOTSUPP;
+	if (!ret)
+		ret = ctlv_blob_write(object->output, 0, buffer, length);
+	if (!ret)
+		result->object_lengths[0] = length;
+	kvfree(buffer);
+	return ret;
+}
+
+static int attestation_tdx_mr_read(struct attestation *att, unsigned int mr_id,
+				   struct attestation_digest_set *values)
+{
+	static const enum tdx_guest_mr native_mrs[] = {
+		TDX_GUEST_MR_MRTD,
+		TDX_GUEST_MR_RTMR0,
+		TDX_GUEST_MR_RTMR1,
+		TDX_GUEST_MR_RTMR2,
+		TDX_GUEST_MR_RTMR3,
+	};
+	struct attestation_tdx *tdx = ctlv_priv_child(att);
+
+	if (mr_id >= ARRAY_SIZE(native_mrs) ||
+	    values->values_count != 1 ||
+	    values->values[0].algorithm != HASH_ALGO_SHA384)
+		return -EINVAL;
+	return tdx->ops->mr_read(tdx->parent_dev, native_mrs[mr_id],
+		values->values[0].data);
+}
+
+static int
+attestation_tdx_mr_extend(struct attestation *att, unsigned int mr_id,
+			  const struct attestation_digest_set *values)
+{
+	struct attestation_tdx *tdx = ctlv_priv_child(att);
+
+	if (mr_id < 1 || mr_id > 4)
+		return -EOPNOTSUPP;
+	if (values->values_count != 1 ||
+	    values->values[0].algorithm != HASH_ALGO_SHA384)
+		return -EINVAL;
+	return tdx->ops->rtmr_extend(tdx->parent_dev, mr_id - 1,
+				     values->values[0].data);
+}
+
+static const struct attestation_provider attestation_tdx_provider = {
+	.evidence_get = attestation_tdx_evidence_get,
+	.mr_read = attestation_tdx_mr_read,
+	.mr_extend = attestation_tdx_mr_extend,
+	.evidence_caps = &attestation_tdx_evidence_caps,
+	.mrs = attestation_tdx_mrs,
+	.mrs_count = ARRAY_SIZE(attestation_tdx_mrs),
+};
+
+size_t ctlv_attestation_tdx_priv_size(void)
+{
+	return sizeof(struct attestation_tdx);
+}
+
+const void *ctlv_attestation_tdx_pre_init(const void *init_info)
+{
+	return &attestation_tdx_provider;
+}
+
+int ctlv_attestation_tdx_init(struct ctlv_device *ctlvdev,
+			      const void *init_info, void *priv)
+{
+	const struct attestation_tdx_init_info *info = init_info;
+	struct attestation_tdx *tdx = priv;
+
+	if (!info || !info->parent_dev || !info->ops)
+		return -EINVAL;
+	tdx->parent_dev = info->parent_dev;
+	tdx->ops = info->ops;
+	return 0;
+}
+
+void ctlv_attestation_tdx_fini(struct ctlv_device *ctlvdev, void *priv)
+{
+}
+
+int ctlv_attestation_tdx_op_pre(void *priv, struct ctlv_op_ctx *ctx)
+{
+	return ctlv_attestation_op_pre(ctlv_priv_parent(priv), ctx);
+}
+
+void ctlv_attestation_tdx_op_post(void *priv, struct ctlv_op_ctx *ctx)
+{
+	ctlv_attestation_op_post(ctlv_priv_parent(priv), ctx);
+}
+
+int ctlv_attestation_tdx_device_info_fill(void *priv,
+					  struct ctlv_op_ctx *ctx,
+					  const struct ctlv_cursor *request,
+					  struct ctlv_cursor *nest)
+{
+	struct attestation_tdx *tdx = priv;
+	const struct tdx_guest_info *info =
+		tdx->ops->info_get(tdx->parent_dev);
+	bool ok;
+
+	if (!info)
+		return -ENODEV;
+	ok = ctlv_attestation_tdx_info_mrconfigid_put(nest, info->mrconfigid,
+						      sizeof(info->mrconfigid));
+	ok &= ctlv_attestation_tdx_info_mrowner_put(nest, info->mrowner,
+						    sizeof(info->mrowner));
+	ok &= ctlv_attestation_tdx_info_mrownerconfig_put(nest,
+							   info->mrownerconfig,
+							   sizeof(info->mrownerconfig));
+	return ok ? 0 : -EMSGSIZE;
+}
+
+static void *attestation_tdx_add(struct device *parent_dev,
+				 const struct tdx_guest_ops *ops)
+{
+	struct attestation_tdx_init_info info = {
+		.parent_dev = parent_dev,
+		.ops = ops,
+	};
+
+	return ctlv_create(parent_dev, &ctlv_attestation_tdx_family,
+			   &info);
+}
+
+static void attestation_tdx_remove(void *client_priv)
+{
+	ctlv_destroy(client_priv);
+}
+
+static const struct tdx_guest_client attestation_tdx_client = {
+	.add = attestation_tdx_add,
+	.remove = attestation_tdx_remove,
+};
+
+static int __init attestation_tdx_init_module(void)
+{
+	return tdx_guest_client_register(&attestation_tdx_client);
+}
+
+static void __exit attestation_tdx_exit_module(void)
+{
+	tdx_guest_client_unregister(&attestation_tdx_client);
+}
+
+module_init(attestation_tdx_init_module);
+module_exit(attestation_tdx_exit_module);
+MODULE_DESCRIPTION("TDX attestation provider");
+MODULE_LICENSE("GPL");
+MODULE_IMPORT_NS("ATTESTATION");
+MODULE_IMPORT_NS("CTLV");
+MODULE_IMPORT_NS("TDX_GUEST");
diff --git a/drivers/ctlv/Kconfig b/drivers/ctlv/Kconfig
new file mode 100644
index 0000000000000..aed3243c55fd4
--- /dev/null
+++ b/drivers/ctlv/Kconfig
@@ -0,0 +1,12 @@
+# SPDX-License-Identifier: GPL-2.0-only
+menuconfig CTLV
+	tristate "CTLV character device TLV UAPI"
+	help
+	  CTLV provides character device UAPIs described by a checked-in YAML
+	  specification. It owns the character device lifetime, the strict TLV
+	  message format, request validation, reply serialization, the large
+	  payloads a request describes rather than carries, per-open event
+	  queues and runtime schema introspection, so families only implement
+	  semantics.
+
+	  If you don't know what to do here, say N.
diff --git a/drivers/ctlv/Makefile b/drivers/ctlv/Makefile
new file mode 100644
index 0000000000000..2f6fe8d2db735
--- /dev/null
+++ b/drivers/ctlv/Makefile
@@ -0,0 +1,5 @@
+# SPDX-License-Identifier: GPL-2.0
+obj-$(CONFIG_CTLV) += ctlv.o
+
+ctlv-y += blob.o blob_desc.o builder.o core.o event.o introspection.o \
+	  message.o schema.o ctlv_gen.o
diff --git a/drivers/ctlv/blob.c b/drivers/ctlv/blob.c
new file mode 100644
index 0000000000000..2c93da62b2010
--- /dev/null
+++ b/drivers/ctlv/blob.c
@@ -0,0 +1,355 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES
+ *
+ * Blob backing is acquired lazily in the submitting task and held until put.
+ */
+#include <linux/align.h>
+#include <linux/atomic.h>
+#include <linux/bits.h>
+#include <linux/capability.h>
+#include <linux/ctlv.h>
+#include <linux/err.h>
+#include <linux/errno.h>
+#include <linux/highmem.h>
+#include <linux/limits.h>
+#include <linux/minmax.h>
+#include <linux/mm.h>
+#include <linux/mm_types.h>
+#include <linux/overflow.h>
+#include <linux/sched.h>
+#include <linux/sched/mm.h>
+#include <linux/sched/signal.h>
+#include <linux/slab.h>
+#include <linux/types.h>
+
+#include <uapi/linux/ctlv.h>
+#include <uapi/linux/ctlv_gen.h>
+
+#include "blob.h"
+#include "blob_desc.h"
+#include "internal.h"
+#include "message.h"
+
+struct ctlv_blob {
+	u64 len;
+	u8 direction;
+	u8 type;
+	struct ctlv_op_ctx *ctx;
+	struct list_head entry;
+	union {
+		struct {
+			struct mm_struct *mm;
+			struct page **pages;
+			unsigned long pages_count;
+			u32 start;
+		} va;
+	};
+};
+
+static bool ctlv_blob_readable(const struct ctlv_blob *blob)
+{
+	return blob->direction != CTLV_BLOB_DIRECTION_OUTPUT;
+}
+
+static bool ctlv_blob_writable(const struct ctlv_blob *blob)
+{
+	return blob->direction != CTLV_BLOB_DIRECTION_INPUT;
+}
+
+static bool ctlv_blob_same_task(const struct ctlv_blob *blob)
+{
+	return !blob->ctx || !blob->ctx->submitter || blob->ctx->submitter == current;
+}
+
+static bool ctlv_blob_access_live(const struct ctlv_blob *blob)
+{
+	return ctlv_blob_same_task(blob) && (!blob->ctx || blob->ctx->blobs_live);
+}
+
+/*
+ * Charged against RLIMIT_MEMLOCK of the address space the pages came from. A
+ * pin lasts one op, which is why it is not FOLL_LONGTERM.
+ */
+static int ctlv_blob_pin_charge(struct mm_struct *mm, unsigned long pages_count)
+{
+	unsigned long limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
+
+	if (atomic64_add_return(pages_count, &mm->pinned_vm) > limit && !capable(CAP_IPC_LOCK)) {
+		atomic64_sub(pages_count, &mm->pinned_vm);
+		return -ENOMEM;
+	}
+	return 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) || 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 -EFAULT;
+
+	*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;
+
+	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;
+
+	while (pinned < pages_count) {
+		long got = pin_user_pages_fast(first + (pinned << PAGE_SHIFT),
+					       min_t(unsigned long, pages_count - pinned, INT_MAX),
+					       gup_flags, pages + pinned);
+
+		/* A short pin is progress; nothing pinned is the caller's. */
+		if (got <= 0) {
+			ret = got ? (int)got : -EFAULT;
+			goto err_unpin;
+		}
+		pinned += got;
+	}
+
+	/* Referenced, so the unpin is safe however far the submitter got. */
+	mmgrab(current->mm);
+	blob->va.start = offset_in_page(address);
+	blob->va.mm = current->mm;
+	blob->va.pages = pages;
+	blob->va.pages_count = pages_count;
+	return 0;
+
+	/* The pins taken, and the whole charge, which covered every page. */
+err_unpin:
+	unpin_user_pages(pages, pinned);
+	atomic64_sub(pages_count, &current->mm->pinned_vm);
+err_free_pages:
+	kvfree(pages);
+	return ret;
+}
+
+static void ctlv_blob_va_release(struct ctlv_blob *blob)
+{
+	/* Dirtied, so that what the kernel wrote survives the unpin. */
+	unpin_user_pages_dirty_lock(blob->va.pages, blob->va.pages_count, ctlv_blob_writable(blob));
+	atomic64_sub(blob->va.pages_count, &blob->va.mm->pinned_vm);
+	kvfree(blob->va.pages);
+	mmdrop(blob->va.mm);
+}
+
+static void ctlv_blob_va_copy(struct ctlv_blob *blob, u64 offset, void *buf, size_t len, bool write)
+{
+	u64 at = blob->va.start + offset;
+	unsigned long index = at >> PAGE_SHIFT;
+	u32 in_page = offset_in_page(at);
+	u8 *bytes = buf;
+
+	while (len) {
+		struct page *page = blob->va.pages[index++];
+		size_t step = min_t(size_t, len, PAGE_SIZE - in_page);
+
+		if (write)
+			memcpy_to_page(page, in_page, bytes, step);
+		else
+			memcpy_from_page(bytes, page, in_page, step);
+		bytes += step;
+		len -= step;
+		in_page = 0;
+	}
+}
+
+u64 ctlv_blob_len(const struct ctlv_blob *blob)
+{
+	return blob->len;
+}
+EXPORT_SYMBOL_NS_GPL(ctlv_blob_len, "CTLV");
+
+/*
+ * The length, the direction and addressing from zero are all the family's own
+ * to know, so getting one wrong is a kernel bug rather than a caller's.
+ */
+static bool ctlv_blob_range_ok(struct ctlv_blob *blob, u64 offset, size_t len, bool write)
+{
+	u64 end;
+
+	if (WARN_ON_ONCE(write ? !ctlv_blob_writable(blob) : !ctlv_blob_readable(blob)))
+		return false;
+	if (WARN_ON_ONCE(!ctlv_blob_access_live(blob)))
+		return false;
+	if (WARN_ON_ONCE(check_add_overflow(offset, (u64)len, &end) || end > blob->len))
+		return false;
+	return true;
+}
+
+static int ctlv_blob_copy(struct ctlv_blob *blob, u64 offset, void *buf, size_t len, bool write)
+{
+	if (!ctlv_blob_range_ok(blob, offset, len, write))
+		return -EINVAL;
+	if (!len)
+		return 0;
+
+	switch (blob->type) {
+	case CTLV_BLOB_TYPE_VA:
+		ctlv_blob_va_copy(blob, offset, buf, len, write);
+		return 0;
+	default:
+		return -EINVAL;
+	}
+}
+
+int ctlv_blob_read(struct ctlv_blob *blob, u64 offset, void *dst, size_t len)
+{
+	return ctlv_blob_copy(blob, offset, dst, len, false);
+}
+EXPORT_SYMBOL_NS_GPL(ctlv_blob_read, "CTLV");
+
+int ctlv_blob_write(struct ctlv_blob *blob, u64 offset, const void *src, size_t len)
+{
+	return ctlv_blob_copy(blob, offset, (void *)src, len, true);
+}
+EXPORT_SYMBOL_NS_GPL(ctlv_blob_write, "CTLV");
+
+int ctlv_blob_put(struct ctlv_blob *blob)
+{
+	if (!blob)
+		return 0;
+	if (WARN_ON_ONCE(!ctlv_blob_same_task(blob)))
+		return -EINVAL;
+
+	switch (blob->type) {
+	case CTLV_BLOB_TYPE_VA:
+		ctlv_blob_va_release(blob);
+		break;
+	}
+	if (blob->ctx) {
+		list_del(&blob->entry);
+		blob->ctx = NULL;
+	}
+	kfree(blob);
+	return 0;
+}
+EXPORT_SYMBOL_NS_GPL(ctlv_blob_put, "CTLV");
+
+void ctlv_blob_context_init(struct ctlv_op_ctx *ctx)
+{
+	INIT_LIST_HEAD(&ctx->blobs);
+	ctx->blobs_live = true;
+	ctx->blob_error = 0;
+}
+
+void ctlv_blob_context_track(struct ctlv_blob *blob, struct ctlv_op_ctx *ctx)
+{
+	blob->ctx = ctx;
+	list_add_tail(&blob->entry, &ctx->blobs);
+}
+
+int ctlv_blob_context_finish(struct ctlv_op_ctx *ctx)
+{
+	ctx->blobs_live = false;
+	if (WARN_ON_ONCE(!list_empty(&ctx->blobs)) && !ctx->blob_error)
+		ctx->blob_error = -EINVAL;
+	while (!list_empty(&ctx->blobs)) {
+		struct ctlv_blob *blob = list_first_entry(&ctx->blobs, struct ctlv_blob, entry);
+
+		ctlv_blob_put(blob);
+	}
+	return ctx->blob_error;
+}
+
+/*
+ * 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, const struct ctlv_cursor *cursor)
+{
+	if (ctx->error.reason)
+		return;
+	ctx->error = (struct ctlv_error){
+		.reason = CTLV_VALIDATION_REASON_BAD_BLOB_DESCRIPTOR,
+		.bad_attr_offset = ctlv_message_offset(cursor->msg, cursor->attr),
+		.nest_offset = ctlv_message_offset(cursor->msg, cursor->parent),
+	};
+}
+
+static struct ctlv_blob *ctlv_blob_acquire(const struct ctlv_blob_desc *desc, u8 direction)
+{
+	u64 address = desc->member[CTLV_BLOB_MEMBER_ADDRESS];
+	u64 len = desc->member[CTLV_BLOB_MEMBER_LENGTH];
+	struct ctlv_blob *blob;
+	int ret;
+
+	blob = kzalloc_obj(*blob, GFP_KERNEL_ACCOUNT);
+	if (!blob)
+		return ERR_PTR(-ENOMEM);
+	INIT_LIST_HEAD(&blob->entry);
+	blob->len = len;
+	blob->direction = direction;
+	blob->type = desc->member[CTLV_BLOB_MEMBER_TYPE];
+
+	ret = ctlv_blob_va_acquire(blob, address);
+	if (ret) {
+		kfree(blob);
+		return ERR_PTR(ret);
+	}
+	return blob;
+}
+
+struct ctlv_blob *ctlv_blob_resolve(struct ctlv_op_ctx *ctx, const struct ctlv_cursor *blob)
+{
+	const struct ctlv_attr *bad = NULL;
+	const struct ctlv_node_schema *node;
+	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_attr_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->attr, &desc, &bad) ||
+			 ctlv_blob_desc_check(&desc, node)))
+		return ERR_PTR(-EINVAL);
+
+	acquired = ctlv_blob_acquire(&desc, node->blob.direction);
+	if (IS_ERR(acquired))
+		ctlv_blob_context_fail(ctx, blob);
+	else
+		ctlv_blob_context_track(acquired, ctx);
+	return acquired;
+}
+EXPORT_SYMBOL_NS_GPL(ctlv_blob_resolve, "CTLV");
diff --git a/drivers/ctlv/blob.h b/drivers/ctlv/blob.h
new file mode 100644
index 0000000000000..bb7b933a1ced8
--- /dev/null
+++ b/drivers/ctlv/blob.h
@@ -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 */
diff --git a/drivers/ctlv/blob_desc.c b/drivers/ctlv/blob_desc.c
new file mode 100644
index 0000000000000..b84be3d723abd
--- /dev/null
+++ b/drivers/ctlv/blob_desc.c
@@ -0,0 +1,102 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES
+ *
+ * Blob descriptor parsing and validation.
+ */
+#include <linux/align.h>
+#include <linux/bits.h>
+#include <linux/overflow.h>
+#include <linux/types.h>
+
+#include <uapi/linux/ctlv.h>
+#include <uapi/linux/ctlv_gen.h>
+
+#include "blob_desc.h"
+#include "message.h"
+
+static int ctlv_blob_member(u64 attr_id)
+{
+	switch (attr_id) {
+	case CTLV_ATTR_BLOB_TYPE:
+		return CTLV_BLOB_MEMBER_TYPE;
+	case CTLV_ATTR_BLOB_ADDRESS:
+		return CTLV_BLOB_MEMBER_ADDRESS;
+	case CTLV_ATTR_BLOB_FD:
+		return CTLV_BLOB_MEMBER_FD;
+	case CTLV_ATTR_BLOB_OFFSET:
+		return CTLV_BLOB_MEMBER_OFFSET;
+	case CTLV_ATTR_BLOB_LENGTH:
+		return CTLV_BLOB_MEMBER_LENGTH;
+	default:
+		return -1;
+	}
+}
+
+u32 ctlv_blob_desc_read(const struct ctlv_attr *blob, struct ctlv_blob_desc *desc,
+			const struct ctlv_attr **bad)
+{
+	const struct ctlv_attr *child = NULL;
+	enum ctlv_message_step step;
+
+	*desc = (struct ctlv_blob_desc){};
+	while ((step = ctlv_message_next(blob, &child)) == CTLV_MESSAGE_STEP_ATTR) {
+		int member = ctlv_blob_member(child->attr_id);
+
+		*bad = child;
+		if (child->flags & ~CTLV_ATTR_F_NESTED)
+			return CTLV_VALIDATION_REASON_UNKNOWN_FLAG;
+		if (child->flags & CTLV_ATTR_F_NESTED)
+			return CTLV_VALIDATION_REASON_MALFORMED_MESSAGE;
+		if (member < 0)
+			return CTLV_VALIDATION_REASON_UNKNOWN_ATTR;
+		if (ctlv_message_attr_payload_len(child) != sizeof(u64))
+			return CTLV_VALIDATION_REASON_BAD_LENGTH;
+		if (desc->present & BIT(member))
+			return CTLV_VALIDATION_REASON_BAD_BLOB_DESCRIPTOR;
+		desc->present |= BIT(member);
+		desc->member[member] = *(const u64 *)ctlv_message_attr_payload(child);
+	}
+	*bad = NULL;
+	if (step == CTLV_MESSAGE_STEP_BAD)
+		return CTLV_VALIDATION_REASON_MALFORMED_MESSAGE;
+	return 0;
+}
+
+static u32 ctlv_blob_variant(const struct ctlv_blob_desc *desc)
+{
+	u32 required = BIT(CTLV_BLOB_MEMBER_TYPE) | BIT(CTLV_BLOB_MEMBER_LENGTH);
+
+	switch (desc->member[CTLV_BLOB_MEMBER_TYPE]) {
+	case CTLV_BLOB_TYPE_VA:
+		required |= BIT(CTLV_BLOB_MEMBER_ADDRESS);
+		break;
+	default:
+		return CTLV_VALIDATION_REASON_BAD_BLOB_DESCRIPTOR;
+	}
+	if (desc->present != required)
+		return CTLV_VALIDATION_REASON_BAD_BLOB_DESCRIPTOR;
+	return 0;
+}
+
+u32 ctlv_blob_desc_check(const struct ctlv_blob_desc *desc, const struct ctlv_node_schema *node)
+{
+	u64 start, length, end;
+	u32 reason;
+
+	reason = ctlv_blob_variant(desc);
+	if (reason)
+		return reason;
+	if (!(node->blob.backings & BIT(desc->member[CTLV_BLOB_MEMBER_TYPE])))
+		return CTLV_VALIDATION_REASON_BAD_BLOB_DESCRIPTOR;
+
+	length = desc->member[CTLV_BLOB_MEMBER_LENGTH];
+	if (!length || length > node->blob.max_len)
+		return CTLV_VALIDATION_REASON_BAD_BLOB_DESCRIPTOR;
+	start = desc->member[desc->present & BIT(CTLV_BLOB_MEMBER_ADDRESS) ?
+				     CTLV_BLOB_MEMBER_ADDRESS :
+				     CTLV_BLOB_MEMBER_OFFSET];
+	if (!IS_ALIGNED(start, node->blob.alignment) || check_add_overflow(start, length, &end))
+		return CTLV_VALIDATION_REASON_BAD_BLOB_DESCRIPTOR;
+	return 0;
+}
diff --git a/drivers/ctlv/blob_desc.h b/drivers/ctlv/blob_desc.h
new file mode 100644
index 0000000000000..27f77af16f019
--- /dev/null
+++ b/drivers/ctlv/blob_desc.h
@@ -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/linux/ctlv.h>
+
+/* The members of a descriptor, in the order the root family declares them. */
+enum {
+	CTLV_BLOB_MEMBER_TYPE,
+	CTLV_BLOB_MEMBER_ADDRESS,
+	CTLV_BLOB_MEMBER_FD,
+	CTLV_BLOB_MEMBER_OFFSET,
+	CTLV_BLOB_MEMBER_LENGTH,
+	CTLV_BLOB_MEMBERS,
+};
+
+struct ctlv_blob_desc {
+	u64 member[CTLV_BLOB_MEMBERS];
+	u32 present;
+};
+
+u32 ctlv_blob_desc_read(const struct ctlv_attr *blob, struct ctlv_blob_desc *desc,
+			const struct ctlv_attr **bad);
+u32 ctlv_blob_desc_check(const struct ctlv_blob_desc *desc, const struct ctlv_node_schema *node);
+
+#endif /* _CTLV_BLOB_DESC_H */
diff --git a/drivers/ctlv/builder.c b/drivers/ctlv/builder.c
new file mode 100644
index 0000000000000..41748ceae1a34
--- /dev/null
+++ b/drivers/ctlv/builder.c
@@ -0,0 +1,374 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES
+ *
+ * Schema-aware reply construction and operation completion.
+ */
+#include <linux/align.h>
+#include <linux/bug.h>
+#include <linux/ctlv.h>
+#include <linux/errno.h>
+#include <linux/export.h>
+#include <linux/stdarg.h>
+#include <linux/string.h>
+#include <linux/types.h>
+
+#include <uapi/linux/ctlv.h>
+#include <uapi/linux/ctlv_gen.h>
+
+#include "builder.h"
+#include "internal.h"
+#include "message.h"
+#include "schema.h"
+
+static void ctlv_message_output_frag_mark(struct ctlv_op_ctx *ctx);
+
+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)
+{
+	*msg = (struct ctlv_msg){
+		.root = buf,
+		.len = len,
+		.tree = tree,
+		.family = ctx->family,
+		.ctx = ctx,
+	};
+	*msg->root = (struct ctlv_attr){
+		.len = sizeof(*msg->root),
+		.flags = CTLV_ATTR_F_NESTED,
+		.attr_id = CTLV_ATTR_ROOT,
+	};
+}
+
+/* The first thing that went wrong is what the op ends up failing with. */
+static bool ctlv_message_output_poison(struct ctlv_cursor *nest, int error)
+{
+	if (!nest->msg->poison)
+		nest->msg->poison = error;
+	return false;
+}
+
+/* A poisoned message is refused silently: whatever poisoned it has warned. */
+static bool ctlv_message_output_ready(struct ctlv_cursor *nest)
+{
+	if (WARN_ON_ONCE(!nest->msg || !nest->attr))
+		return false;
+	/* Also what refuses a cursor that reads a request. */
+	if (WARN_ON_ONCE(!nest->msg->ctx))
+		return false;
+	if (nest->msg->poison)
+		return false;
+	if (WARN_ON_ONCE(nest->msg->ctx->deepest != nest))
+		return ctlv_message_output_poison(nest, -EINVAL);
+	return true;
+}
+
+/* What the schema places in this nest under one ID, as one kind. */
+static const struct ctlv_node_schema *ctlv_message_output_member(struct ctlv_cursor *nest,
+								 u64 attr_id, u8 kind,
+								 struct ctlv_schema_pos *pos)
+{
+	const struct ctlv_node_schema *node;
+
+	if (!ctlv_message_output_ready(nest))
+		return NULL;
+	if (WARN_ON_ONCE(!ctlv_schema_member(nest->msg->family, nest->tree,
+					     nest->node, attr_id, pos))) {
+		ctlv_message_output_poison(nest, -EINVAL);
+		return NULL;
+	}
+	node = &pos->tree->node_schemas[pos->node];
+	if (WARN_ON_ONCE(node->kind != kind)) {
+		ctlv_message_output_poison(nest, -EINVAL);
+		return NULL;
+	}
+	return node;
+}
+
+/*
+ * A query is offered whatever room its caller had, so running out ends a
+ * fragment. Anything else wrote a message its own schema does not describe.
+ */
+static bool ctlv_message_output_full(struct ctlv_cursor *nest)
+{
+	const struct ctlv_op_schema *op = nest->msg->ctx->op->schema;
+
+	if (op->type == CTLV_OP_TYPE_QUERY)
+		return false;
+	WARN_ONCE(1, "ctlv: op %#018llx wrote past the reply length its schema declares\n",
+		  op->op_id);
+	return ctlv_message_output_poison(nest, -EMSGSIZE);
+}
+
+/* What one cursor stands on, as the buffer this direction may change. */
+static struct ctlv_attr *ctlv_message_output_attr(const struct ctlv_cursor *nest)
+{
+	return (struct ctlv_attr *)((u8 *)nest->msg->root + nest->start);
+}
+
+/* The pad is written rather than left as it was: it belongs to the nest. */
+static struct ctlv_attr *ctlv_message_output_write(struct ctlv_cursor *nest, u64 attr_id, u32 flags,
+						   const void *payload, u32 payload_len)
+{
+	u32 len = sizeof(struct ctlv_attr) + payload_len;
+	size_t step = ALIGN((size_t)len, CTLV_ALIGNTO);
+	struct ctlv_msg *msg = nest->msg;
+	struct ctlv_cursor *open;
+	struct ctlv_attr *attr;
+	size_t offset;
+
+	offset = nest->start + ctlv_message_output_attr(nest)->len;
+	if (offset + step > msg->len) {
+		ctlv_message_output_full(nest);
+		return NULL;
+	}
+
+	attr = (struct ctlv_attr *)((u8 *)msg->root + offset);
+	*attr = (struct ctlv_attr){
+		.len = len,
+		.flags = flags,
+		.attr_id = attr_id,
+	};
+	if (payload_len)
+		memcpy(attr + 1, payload, payload_len);
+	memset((u8 *)attr + len, 0, step - len);
+	if (!(flags & CTLV_ATTR_F_NESTED))
+		msg->ctx->frag.progress = true;
+
+	/* Every nest the attr landed in is that much longer, the root too. */
+	for (open = nest; open; open = open->up)
+		ctlv_message_output_attr(open)->len += step;
+	return attr;
+}
+
+/* The 64-bit payload that every integer, enum and flags attr carries. */
+static bool ctlv_message_put_scalar(struct ctlv_cursor *nest, u64 attr_id, u8 kind, u64 value)
+{
+	const struct ctlv_node_schema *node;
+	struct ctlv_schema_pos pos;
+
+	node = ctlv_message_output_member(nest, attr_id, kind, &pos);
+	if (!node)
+		return false;
+	/* A value outside what the attr declares is one nothing may be told. */
+	if (WARN_ON_ONCE(!ctlv_schema_value_ok(node, value)))
+		return ctlv_message_output_poison(nest, -EINVAL);
+	return ctlv_message_output_write(nest, attr_id, 0, &value, sizeof(value));
+}
+
+bool ctlv_put_u64(struct ctlv_cursor *nest, u64 attr_id, u8 kind, u64 value)
+{
+	return ctlv_message_put_scalar(nest, attr_id, kind, value);
+}
+EXPORT_SYMBOL_NS_GPL(ctlv_put_u64, "CTLV");
+
+bool ctlv_put_s64(struct ctlv_cursor *nest, u64 attr_id, u8 kind, s64 value)
+{
+	return ctlv_message_put_scalar(nest, attr_id, kind, value);
+}
+EXPORT_SYMBOL_NS_GPL(ctlv_put_s64, "CTLV");
+
+bool ctlv_put_bool(struct ctlv_cursor *nest, u64 attr_id, u8 kind, bool value)
+{
+	u8 payload = value;
+	struct ctlv_schema_pos pos;
+
+	if (!ctlv_message_output_member(nest, attr_id, kind, &pos))
+		return false;
+	return ctlv_message_output_write(nest, attr_id, 0, &payload, sizeof(payload));
+}
+EXPORT_SYMBOL_NS_GPL(ctlv_put_bool, "CTLV");
+
+bool ctlv_put_string(struct ctlv_cursor *nest, u64 attr_id, u8 kind, const char *value)
+{
+	const struct ctlv_node_schema *node;
+	struct ctlv_schema_pos pos;
+	size_t len;
+
+	node = ctlv_message_output_member(nest, attr_id, kind, &pos);
+	if (!node)
+		return false;
+	len = strnlen(value, (size_t)node->length.max_len + 1);
+	if (WARN_ON_ONCE(len > node->length.max_len || !ctlv_schema_length_ok(node, len)))
+		return ctlv_message_output_poison(nest, -EINVAL);
+	return ctlv_message_output_write(nest, attr_id, 0, value, len + 1);
+}
+EXPORT_SYMBOL_NS_GPL(ctlv_put_string, "CTLV");
+
+bool ctlv_put_binary(struct ctlv_cursor *nest, u64 attr_id, u8 kind, const void *value, u32 len)
+{
+	const struct ctlv_node_schema *node;
+	struct ctlv_schema_pos pos;
+
+	node = ctlv_message_output_member(nest, attr_id, kind, &pos);
+	if (!node)
+		return false;
+	if (WARN_ON_ONCE(!ctlv_schema_length_ok(node, len)))
+		return ctlv_message_output_poison(nest, -EINVAL);
+	return ctlv_message_output_write(nest, attr_id, 0, value, len);
+}
+EXPORT_SYMBOL_NS_GPL(ctlv_put_binary, "CTLV");
+
+bool ctlv_nest_start(struct ctlv_cursor *nest, struct ctlv_cursor *child, u64 attr_id, u8 kind)
+{
+	struct ctlv_schema_pos pos;
+	struct ctlv_attr *attr;
+
+	*child = (struct ctlv_cursor){};
+	if (!ctlv_message_output_member(nest, attr_id, kind, &pos))
+		return false;
+	/* Unreachable through any schema the generator would have accepted. */
+	if (WARN_ON_ONCE(nest->depth + 1 > CTLV_MAX_NEST_DEPTH))
+		return ctlv_message_output_poison(nest, -EINVAL);
+
+	attr = ctlv_message_output_write(nest, attr_id, CTLV_ATTR_F_NESTED, NULL, 0);
+	if (!attr)
+		return false;
+
+	*child = (struct ctlv_cursor){
+		.msg = nest->msg,
+		.attr = attr,
+		.up = nest,
+		.start = ctlv_message_offset(nest->msg, attr),
+		.tree = pos.tree,
+		.node = pos.node,
+		.depth = nest->depth + 1,
+	};
+	nest->msg->ctx->deepest = child;
+	return true;
+}
+EXPORT_SYMBOL_NS_GPL(ctlv_nest_start, "CTLV");
+
+void ctlv_nest_end(struct ctlv_cursor *child)
+{
+	struct ctlv_op_ctx *ctx;
+
+	if (WARN_ON_ONCE(!child->msg || !child->msg->ctx || !child->up))
+		return;
+	ctx = child->msg->ctx;
+	if (child->msg->poison)
+		return;
+	if (WARN_ON_ONCE(ctx->deepest != child)) {
+		ctlv_message_output_poison(child, -EINVAL);
+		return;
+	}
+	if (ctlv_message_output_attr(child)->len == sizeof(struct ctlv_attr))
+		ctx->frag.progress = true;
+	ctx->deepest = child->up;
+}
+EXPORT_SYMBOL_NS_GPL(ctlv_nest_end, "CTLV");
+
+static bool ctlv_op_error_valid(int error)
+{
+	return !WARN_ON_ONCE(error >= 0 || error < -MAX_ERRNO);
+}
+
+int ctlv_op_error(struct ctlv_op_ctx *ctx, int error, const char *message)
+{
+	if (!ctlv_op_error_valid(error))
+		return error < 0 && error >= -MAX_ERRNO ? error : -EINVAL;
+	if (!ctx->error.message[0])
+		strscpy(ctx->error.message, message, sizeof(ctx->error.message));
+	return error;
+}
+EXPORT_SYMBOL_NS_GPL(ctlv_op_error, "CTLV");
+
+int ctlv_op_errorf(struct ctlv_op_ctx *ctx, int error, const char *fmt, ...)
+{
+	va_list args;
+
+	if (!ctlv_op_error_valid(error))
+		return error < 0 && error >= -MAX_ERRNO ? error : -EINVAL;
+	if (ctx->error.message[0])
+		return error;
+	va_start(args, fmt);
+	vscnprintf(ctx->error.message, sizeof(ctx->error.message), fmt, args);
+	va_end(args);
+	return error;
+}
+EXPORT_SYMBOL_NS_GPL(ctlv_op_errorf, "CTLV");
+
+/* Continuation is a query's, so asking about one anywhere else is a bug. */
+static bool ctlv_op_is_query(const struct ctlv_op_ctx *ctx)
+{
+	return !WARN_ON_ONCE(ctx->op->schema->type != CTLV_OP_TYPE_QUERY);
+}
+
+u64 ctlv_op_query_generation(const struct ctlv_op_ctx *ctx)
+{
+	if (!ctlv_op_is_query(ctx))
+		return 0;
+	return ctx->frag.generation;
+}
+EXPORT_SYMBOL_NS_GPL(ctlv_op_query_generation, "CTLV");
+
+u64 ctlv_op_query_cursor(const struct ctlv_op_ctx *ctx)
+{
+	if (!ctlv_op_is_query(ctx))
+		return 0;
+	return ctx->frag.cursor;
+}
+EXPORT_SYMBOL_NS_GPL(ctlv_op_query_cursor, "CTLV");
+
+/*
+ * What both endings check: a query, one ending, and a generation that has not
+ * moved under a continuation, which no fragment can be delivered across.
+ */
+static int ctlv_query_fragment_end(struct ctlv_op_ctx *ctx, u64 generation)
+{
+	if (!ctlv_op_is_query(ctx))
+		return -EINVAL;
+	if (WARN_ON_ONCE(ctx->frag.answered))
+		return -EINVAL;
+	ctx->frag.answered = true;
+	/* Whatever the builder gave up on has warned about it already. */
+	if (ctx->output.poison)
+		return ctx->output.poison;
+	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;
+	}
+	ctx->frag.reported = generation;
+	return 0;
+}
+
+int ctlv_op_query_more(struct ctlv_op_ctx *ctx, u64 generation, u64 next_cursor)
+{
+	int ret = ctlv_query_fragment_end(ctx, generation);
+
+	if (!ret &&
+	    WARN_ON_ONCE(!ctx->frag.progress || !next_cursor || next_cursor == ctx->frag.cursor))
+		ret = -EINVAL;
+	if (!ret) {
+		ctlv_message_output_frag_mark(ctx);
+		ctx->frag.next_cursor = next_cursor;
+	}
+	ctx->frag.result = ret;
+	return ret;
+}
+EXPORT_SYMBOL_NS_GPL(ctlv_op_query_more, "CTLV");
+
+int ctlv_op_query_done(struct ctlv_op_ctx *ctx, u64 generation)
+{
+	int ret = ctlv_query_fragment_end(ctx, generation);
+
+	if (!ret && WARN_ON_ONCE(ctx->deepest != &ctx->output_root)) {
+		/* A cursor of a frame that has returned is not followed. */
+		ctx->deepest = &ctx->output_root;
+		ret = -EINVAL;
+	}
+	ctx->frag.result = ret;
+	return ret;
+}
+EXPORT_SYMBOL_NS_GPL(ctlv_op_query_done, "CTLV");
+
+static void ctlv_message_output_frag_mark(struct ctlv_op_ctx *ctx)
+{
+	struct ctlv_cursor *open;
+
+	for (open = ctx->deepest; open; open = open->up)
+		ctlv_message_output_attr(open)->flags |= CTLV_ATTR_F_FRAG_MORE;
+	ctx->deepest = &ctx->output_root;
+}
diff --git a/drivers/ctlv/builder.h b/drivers/ctlv/builder.h
new file mode 100644
index 0000000000000..744595ebd88e9
--- /dev/null
+++ b/drivers/ctlv/builder.h
@@ -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 */
diff --git a/drivers/ctlv/core.c b/drivers/ctlv/core.c
new file mode 100644
index 0000000000000..aeab29fe2fdd4
--- /dev/null
+++ b/drivers/ctlv/core.c
@@ -0,0 +1,1517 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES
+ */
+#define pr_fmt(fmt) "ctlv: " fmt
+#include <linux/align.h>
+#include <linux/bitmap.h>
+#include <linux/bitops.h>
+#include <linux/build_bug.h>
+#include <linux/cache.h>
+#include <linux/cleanup.h>
+#include <linux/container_of.h>
+#include <linux/ctlv.h>
+#include <linux/ctlv_gen.h>
+#include <linux/device.h>
+#include <linux/err.h>
+#include <linux/fs.h>
+#include <linux/idr.h>
+#include <linux/kdev_t.h>
+#include <linux/kobject.h>
+#include <linux/list.h>
+#include <linux/lockdep.h>
+#include <linux/module.h>
+#include <linux/mutex.h>
+#include <linux/overflow.h>
+#include <linux/poll.h>
+#include <linux/slab.h>
+#include <linux/stddef.h>
+#include <linux/string.h>
+#include <linux/uaccess.h>
+#include <linux/vmalloc.h>
+
+#include <uapi/linux/ctlv.h>
+
+#include "blob.h"
+#include "builder.h"
+#include "device.h"
+#include "event.h"
+#include "internal.h"
+#include "schema.h"
+
+enum {
+	CTLV_MAX_DEVICES = 4096,
+};
+
+/*
+ * One layout on every ABI, including compat. Alignment is asserted too because
+ * a 32-bit ABI aligns a plain __u64 to four bytes.
+ */
+static_assert(sizeof(struct ctlv_attr) == 16);
+static_assert(__alignof__(struct ctlv_attr) == CTLV_ALIGNTO);
+
+static_assert(sizeof(struct ctlv_op_exec) == 64);
+static_assert(__alignof__(struct ctlv_op_exec) == CTLV_ALIGNTO);
+
+static_assert(sizeof(struct ctlv_event_hdr) == 24);
+static_assert(__alignof__(struct ctlv_event_hdr) == CTLV_ALIGNTO);
+
+static dev_t ctlv_device_number;
+static DEFINE_IDA(ctlv_device_ids);
+
+/* Every family priv has core-owned links immediately before it. */
+#define CTLV_PRIV_ALIGN SMP_CACHE_BYTES
+
+struct ctlv_priv_container {
+	struct ctlv_priv_container *parent;
+	struct ctlv_priv_container *child;
+	u8 priv[] __aligned(CTLV_PRIV_ALIGN);
+};
+
+static inline const struct ctlv_priv_container *ctlv_priv_container(const void *priv)
+{
+	return container_of_const(priv, struct ctlv_priv_container, priv);
+}
+
+struct ctlv_family_priv {
+	const struct ctlv_family *family;
+	void *priv;
+	size_t priv_offset;
+	const void *init_info;
+	bool initialized;
+};
+
+/* Claims persist across unload so one ID cannot later name another family. */
+struct ctlv_family_claim {
+	struct list_head entry;
+	char *name;
+	u16 family_id;
+};
+
+static LIST_HEAD(ctlv_family_claims);
+static DEFINE_MUTEX(ctlv_family_claims_lock);
+
+static int ctlv_family_claim_add(const struct ctlv_family_schema *schema)
+{
+	struct ctlv_family_claim *claim;
+
+	guard(mutex)
+		(&ctlv_family_claims_lock);
+	list_for_each_entry(claim, &ctlv_family_claims, entry) {
+		bool same_id = claim->family_id == schema->family_id;
+		bool same_name = !strcmp(claim->name, schema->name);
+
+		if (same_id && same_name)
+			return 0;
+		if (same_id || same_name) {
+			pr_err("family %s wants ID %u, which belongs to %s\n", schema->name,
+			       schema->family_id, claim->name);
+			return -EEXIST;
+		}
+	}
+
+	claim = kzalloc_obj(*claim, GFP_KERNEL);
+	if (!claim)
+		return -ENOMEM;
+	claim->name = kstrdup(schema->name, GFP_KERNEL);
+	if (!claim->name) {
+		kfree(claim);
+		return -ENOMEM;
+	}
+	claim->family_id = schema->family_id;
+	list_add_tail(&claim->entry, &ctlv_family_claims);
+	return 0;
+}
+
+static void ctlv_family_claims_free(void)
+{
+	struct ctlv_family_claim *claim, *next;
+
+	list_for_each_entry_safe(claim, next, &ctlv_family_claims, entry) {
+		list_del(&claim->entry);
+		kfree(claim->name);
+		kfree(claim);
+	}
+}
+
+/*
+ * Everything resolved below is generated, so a failure here is a bug, checked
+ * anyway because an out-of-tree family comes from another generator.
+ */
+
+static const char *ctlv_family_name(const struct ctlv_family *family)
+{
+	if (!family->schema || !family->schema->name)
+		return "(unnamed)";
+	return family->schema->name;
+}
+
+static int ctlv_family_bad(const struct ctlv_family *family, const char *what)
+{
+	pr_err("family %s: %s\n", ctlv_family_name(family), what);
+	return -EINVAL;
+}
+
+static int ctlv_op_bad(const struct ctlv_family *family, u64 op_id, const char *what)
+{
+	pr_err("family %s: op %#018llx %s\n", ctlv_family_name(family), op_id, what);
+	return -EINVAL;
+}
+
+/*
+ * A family is named its parent's whole name plus a suffix, so one name states
+ * the chain it belongs to and every family of this core is ctlv-something.
+ */
+static int ctlv_family_chain_check(const struct ctlv_family *family)
+{
+	const struct ctlv_family *child;
+
+	for (child = family; child != &ctlv_family; child = child->parent) {
+		const struct ctlv_family *parent;
+		size_t len;
+
+		if (!child)
+			return ctlv_family_bad(family, "heads no chain of the core's");
+		parent = child->parent;
+		if (!child->schema || !parent || !parent->schema)
+			return ctlv_family_bad(child, "does not name a complete parent descriptor");
+		if (!child->schema->name || !parent->schema->name)
+			return ctlv_family_bad(family, "inherits a family with no name");
+		if (parent->schema->family_id >= child->schema->family_id)
+			return ctlv_family_bad(child, "does not follow its parent in the registry");
+		len = strlen(parent->schema->name);
+		if (!len || strncmp(child->schema->name, parent->schema->name, len) ||
+		    child->schema->name[len] != '-')
+			return ctlv_family_bad(family, "is not named after the family it inherits");
+	}
+	return 0;
+}
+
+/* One descriptor of a chain: what it answers with, and what it fills. */
+static int ctlv_family_descriptor_check(const struct ctlv_family *family)
+{
+	const struct ctlv_family_schema *schema = family->schema;
+	u32 index;
+
+	/*
+	 * A family that declares no op of its own binds nothing: what it
+	 * inherited is answered where it was declared.
+	 */
+	if (!schema || !schema->name || !*schema->name || (family->ops_count && !family->ops))
+		return ctlv_family_bad(family, "descriptor is incomplete");
+	/* Nothing in common means an empty pair, not an absent one. */
+	if (!family->pre || !family->post)
+		return ctlv_family_bad(family, "has no hook pair");
+	if (!family->priv_size || !family->init || !family->fini)
+		return ctlv_family_bad(family, "has no priv lifecycle");
+	/* Every device answers the root family already, as the core. */
+	if (schema->family_id == CTLV_FAMILY_ROOT && family != &ctlv_family)
+		return ctlv_family_bad(family, "claims the root family ID");
+	/* An extension point is answered by whichever family filled it. */
+	if (family->stub_ops_count != schema->stub_fill_schemas_count)
+		return ctlv_family_bad(family, "answers other extension points than it fills");
+	for (index = 0; index < family->stub_ops_count; index++) {
+		const struct ctlv_stub_fill_schema *fill_schema = &schema->stub_fill_schemas[index];
+		const struct ctlv_stub_ops *stub_ops = &family->stub_ops[index];
+
+		if (stub_ops->family_id == fill_schema->family_id &&
+		    stub_ops->set_id == fill_schema->set_id)
+			continue;
+		return ctlv_family_bad(family, "answers an extension point it does not fill");
+	}
+	return 0;
+}
+
+/* Every descriptor binds its local schema and supplies a complete lifecycle. */
+static int ctlv_family_descriptors_check(const struct ctlv_family *family)
+{
+	const struct ctlv_family *descriptor;
+
+	for (descriptor = family; descriptor; descriptor = descriptor->parent) {
+		int ret;
+
+		ret = ctlv_family_descriptor_check(descriptor);
+		if (ret)
+			return ret;
+	}
+	return 0;
+}
+
+/* The graph a device answers over, and the descriptors standing on it. */
+static int ctlv_family_check(const struct ctlv_family *family)
+{
+	int ret;
+
+	if (!family->schema)
+		return ctlv_family_bad(family, "descriptor is incomplete");
+	ret = ctlv_family_chain_check(family);
+	if (ret)
+		return ret;
+	return ctlv_family_descriptors_check(family);
+}
+
+static struct ctlv_family_priv *ctlv_family_priv_find(const struct ctlv_device *ctlvdev,
+						      const struct ctlv_family *family)
+{
+	u32 index;
+
+	for (index = 0; index < ctlvdev->privs_count; index++)
+		if (ctlvdev->privs[index].family == family)
+			return &ctlvdev->privs[index];
+	return NULL;
+}
+
+static void ctlv_family_privs_free(struct ctlv_device *ctlvdev)
+{
+	kvfree(ctlvdev->priv_block);
+	ctlvdev->priv_block = NULL;
+	kfree(ctlvdev->privs);
+	ctlvdev->privs = NULL;
+	ctlvdev->privs_count = 0;
+}
+
+static int ctlv_family_privs_alloc(struct ctlv_device *ctlvdev, const struct ctlv_family *family)
+{
+	struct ctlv_priv_container *parent = NULL;
+	void *aligned;
+	size_t alloc_len;
+	size_t len = 0;
+	u32 index;
+
+	ctlvdev->privs_count = ctlv_family_levels(family);
+	ctlvdev->privs = kcalloc(ctlvdev->privs_count, sizeof(*ctlvdev->privs), GFP_KERNEL);
+	if (!ctlvdev->privs)
+		return -ENOMEM;
+
+	for (index = 0; index < ctlvdev->privs_count; index++) {
+		struct ctlv_family_priv *family_priv = &ctlvdev->privs[index];
+		size_t size, aligned_len;
+
+		family_priv->family =
+			ctlv_family_ancestor(family, ctlvdev->privs_count - index - 1);
+		size = max_t(size_t, family_priv->family->priv_size(), 1);
+		if (check_add_overflow(len, offsetof(struct ctlv_priv_container, priv),
+				       &aligned_len) ||
+		    check_add_overflow(aligned_len, CTLV_PRIV_ALIGN - 1, &aligned_len))
+			goto overflow;
+		aligned_len = ALIGN_DOWN(aligned_len, CTLV_PRIV_ALIGN);
+		family_priv->priv_offset = aligned_len;
+		if (check_add_overflow(aligned_len, size, &len))
+			goto overflow;
+	}
+	if (check_add_overflow(len, CTLV_PRIV_ALIGN - 1, &alloc_len))
+		goto overflow;
+	ctlvdev->priv_block = kvzalloc(alloc_len, GFP_KERNEL);
+	if (!ctlvdev->priv_block) {
+		ctlv_family_privs_free(ctlvdev);
+		return -ENOMEM;
+	}
+	aligned = PTR_ALIGN(ctlvdev->priv_block, CTLV_PRIV_ALIGN);
+
+	for (index = 0; index < ctlvdev->privs_count; index++) {
+		struct ctlv_family_priv *family_priv = &ctlvdev->privs[index];
+		struct ctlv_priv_container *container;
+		void *priv;
+
+		priv = (u8 *)aligned + family_priv->priv_offset;
+		family_priv->priv = priv;
+		container = container_of_const(priv, struct ctlv_priv_container, priv);
+		container->parent = parent;
+		container->child = NULL;
+		if (parent)
+			parent->child = container;
+		parent = container;
+	}
+	return 0;
+
+overflow:
+	ctlv_family_privs_free(ctlvdev);
+	return -EOVERFLOW;
+}
+
+static int ctlv_family_privs_pre_init(struct ctlv_device *ctlvdev, const void *init_info)
+{
+	u32 index;
+
+	for (index = ctlvdev->privs_count; index; index--) {
+		struct ctlv_family_priv *family_priv = &ctlvdev->privs[index - 1];
+
+		family_priv->init_info = init_info;
+		if (!family_priv->family->pre_init) {
+			init_info = NULL;
+			continue;
+		}
+		init_info = family_priv->family->pre_init(init_info);
+		if (IS_ERR(init_info))
+			return PTR_ERR(init_info);
+	}
+	if (WARN_ON_ONCE(init_info))
+		return -EINVAL;
+	return 0;
+}
+
+static void ctlv_family_privs_pre_fini(struct ctlv_device *ctlvdev)
+{
+	u32 index;
+
+	lockdep_assert_not_held(&ctlvdev->registration_lock);
+	lockdep_assert_not_held(&ctlvdev->transition_lock);
+	lockdep_assert_not_held(&ctlvdev->events_lock);
+
+	for (index = 0; index < ctlvdev->privs_count; index++) {
+		struct ctlv_family_priv *family_priv = &ctlvdev->privs[index];
+
+		if (!family_priv->initialized || !family_priv->family->pre_fini)
+			continue;
+		family_priv->family->pre_fini(ctlvdev, family_priv->priv);
+	}
+}
+
+static void ctlv_family_privs_fini_only(struct ctlv_device *ctlvdev)
+{
+	u32 index;
+
+	for (index = ctlvdev->privs_count; index; index--) {
+		struct ctlv_family_priv *family_priv = &ctlvdev->privs[index - 1];
+
+		if (!family_priv->initialized)
+			continue;
+		family_priv->family->fini(ctlvdev, family_priv->priv);
+		family_priv->initialized = false;
+	}
+}
+
+static int ctlv_family_privs_init(struct ctlv_device *ctlvdev)
+{
+	u32 index;
+	int ret;
+
+	for (index = 0; index < ctlvdev->privs_count; index++) {
+		struct ctlv_family_priv *family_priv = &ctlvdev->privs[index];
+
+		ret = family_priv->family->init(ctlvdev, family_priv->init_info, family_priv->priv);
+		family_priv->init_info = NULL;
+		if (ret) {
+			ctlv_family_privs_fini_only(ctlvdev);
+			return ret;
+		}
+		family_priv->initialized = true;
+	}
+	return 0;
+}
+
+static int ctlv_family_privs_post_init(struct ctlv_device *ctlvdev)
+{
+	u32 index;
+	int ret;
+
+	for (index = ctlvdev->privs_count; index; index--) {
+		struct ctlv_family_priv *family_priv = &ctlvdev->privs[index - 1];
+
+		if (!family_priv->family->post_init)
+			continue;
+		ret = family_priv->family->post_init(ctlvdev, family_priv->priv);
+		if (ret)
+			return ret;
+	}
+	return 0;
+}
+
+static void ctlv_device_fini(struct ctlv_device *ctlvdev)
+{
+	ctlv_family_privs_pre_fini(ctlvdev);
+
+	/* No provider can remain after pre_fini has drained its consumers. */
+	scoped_guard(spinlock, &ctlvdev->transition_lock) {
+		ctlvdev->destroying = true;
+		ctlv_event_contexts_stop(ctlvdev);
+	}
+	ctlv_event_contexts_wait(ctlvdev);
+	ctlv_event_device_dead(ctlvdev);
+
+	ctlv_family_privs_fini_only(ctlvdev);
+}
+
+/* What one walk of the chain has accounted for so far. */
+struct ctlv_op_resolution {
+	struct ctlv_device *ctlvdev;
+	const struct ctlv_family *target;
+	const struct ctlv_family *family;
+	u32 bound;
+	u32 dynamic;
+	u32 events;
+	u64 previous;
+};
+
+/* Every binding of one family answers an op, so a spare one answers nothing. */
+static int ctlv_op_resolution_family_bound(const struct ctlv_op_resolution *state)
+{
+	const struct ctlv_family *family = state->family;
+
+	if (!family || state->bound == family->ops_count)
+		return 0;
+	/* The core's own table is this core's bug, not a family's. */
+	if (WARN_ON_ONCE(family == &ctlv_family))
+		return -EINVAL;
+	return ctlv_family_bad(family, "binds more than its schema asks for");
+}
+
+/*
+ * The ops of one family are contiguous in the walk, so the family before this
+ * one is complete as soon as another family's op arrives.
+ */
+static int ctlv_op_resolution_family_enter(struct ctlv_op_resolution *state,
+					   const struct ctlv_family *family)
+{
+	int ret;
+
+	if (state->family == family)
+		return 0;
+	ret = ctlv_op_resolution_family_bound(state);
+	if (ret)
+		return ret;
+	state->family = family;
+	state->bound = 0;
+	return 0;
+}
+
+static int ctlv_op_resolution_add(struct ctlv_op_resolution *state, const struct ctlv_family *owner,
+				  const struct ctlv_op_schema *op, struct ctlv_op_entry *entry)
+{
+	const struct ctlv_family *target = state->target;
+	const struct ctlv_family *family = state->family;
+	struct ctlv_family_priv *family_priv;
+	int ret;
+
+	family_priv = ctlv_family_priv_find(state->ctlvdev, family);
+	if (WARN_ON_ONCE(!family_priv))
+		return -EINVAL;
+	entry->schema = op;
+	entry->priv = family_priv->priv;
+	entry->state_index = CTLV_OP_STATE_NONE;
+
+	/*
+	 * An op ID is its family's ID and a number within it, so a walk from
+	 * the oldest ancestor down ascends, which covers uniqueness too.
+	 */
+	if (!CTLV_OP_NUMBER(op->op_id) || CTLV_OP_FAMILY(op->op_id) != owner->schema->family_id)
+		return ctlv_op_bad(target, op->op_id, "belongs to another family");
+	if (op->op_id <= state->previous)
+		return ctlv_op_bad(target, op->op_id, "is out of order");
+	state->previous = op->op_id;
+
+	switch (op->type) {
+	case CTLV_OP_TYPE_ACTION:
+	case CTLV_OP_TYPE_QUERY:
+		if (op->fd_access != CTLV_OP_FD_ACCESS_READ &&
+		    op->fd_access != CTLV_OP_FD_ACCESS_READ_WRITE)
+			return ctlv_op_bad(family, op->op_id, "has an unknown fd access");
+		/* The family that declared the op is the one that answers it. */
+		if (state->bound >= family->ops_count)
+			return ctlv_op_bad(family, op->op_id, "has nothing bound to it");
+		entry->binding = &family->ops[state->bound++];
+		/* Required even for an op this device disables or withholds. */
+		if (!entry->binding->action)
+			return ctlv_op_bad(family, op->op_id, "has no callback");
+		/* An optional op arrives absent, for the opt-in to clear. */
+		entry->absent = op->optional;
+		/* An op has a whole pair of hooks of its own, or none. */
+		if (!entry->binding->pre != !entry->binding->post)
+			return ctlv_op_bad(family, op->op_id, "has half a hook pair");
+		/* A pair is on no wire, so this is the only check of it. */
+		if (!entry->binding->pre != !op->pre_post)
+			return ctlv_op_bad(family, op->op_id, "disagrees about its hook pair");
+		break;
+	case CTLV_OP_TYPE_EVENT:
+		if (op->fd_access)
+			return ctlv_op_bad(target, op->op_id, "is an event with fd access");
+		if (op->optional)
+			return ctlv_op_bad(target, op->op_id, "is an event a device could omit");
+		/*
+		 * Produced rather than answered, so nothing to bind: an event
+		 * gets a subscription bit, numbered as the walk meets it.
+		 */
+		entry->event_index = state->events++;
+		break;
+	default:
+		return ctlv_op_bad(target, op->op_id, "has an unknown type");
+	}
+
+	switch (op->availability) {
+	case CTLV_OP_AVAILABILITY_FIXED:
+		break;
+	case CTLV_OP_AVAILABILITY_DYNAMIC:
+		if (op->type == CTLV_OP_TYPE_EVENT)
+			return ctlv_op_bad(target, op->op_id, "is an event a device could disable");
+		/*
+		 * Numbered from zero as the walk meets them, per device: two
+		 * families of one chain need not have the same ops.
+		 */
+		entry->state_index = state->dynamic++;
+		break;
+	default:
+		return ctlv_op_bad(target, op->op_id, "has an unknown availability");
+	}
+
+	/*
+	 * Once per device: what an inherited op may carry depends on the
+	 * extension points this family filled and on nothing that changes later.
+	 */
+	ret = ctlv_schema_op_sizes(target, op, &entry->sizes);
+	if (ret)
+		return ctlv_op_bad(target, op->op_id, "needs messages this core cannot carry");
+	return 0;
+}
+
+static int ctlv_op_resolution_init(struct ctlv_device *ctlvdev, const struct ctlv_family *family)
+{
+	struct ctlv_op_resolution state = {
+		.ctlvdev = ctlvdev,
+		.target = family,
+	};
+	const struct ctlv_family *owner;
+	const struct ctlv_op_schema *op;
+	struct ctlv_schema_cursor cursor;
+	u32 ops_count = 0;
+	int ret;
+
+	ret = ctlv_family_check(family);
+	if (ret)
+		return ret;
+	ret = ctlv_family_privs_alloc(ctlvdev, family);
+	if (ret)
+		return ret;
+
+	ctlv_schema_cursor_init(&cursor, family);
+	while (ctlv_schema_next_op(&cursor, &owner))
+		ops_count++;
+	if (!ops_count)
+		return ctlv_family_bad(family, "has an effective schema with no op");
+
+	ctlvdev->ops = kcalloc(ops_count, sizeof(*ctlvdev->ops), GFP_KERNEL);
+	if (!ctlvdev->ops)
+		return -ENOMEM;
+	ctlvdev->ops_count = ops_count;
+
+	ops_count = 0;
+	ctlv_schema_cursor_init(&cursor, family);
+	while ((op = ctlv_schema_next_op(&cursor, &owner))) {
+		ret = ctlv_op_resolution_family_enter(&state, owner);
+		if (ret)
+			return ret;
+		ret = ctlv_op_resolution_add(&state, owner, op, &ctlvdev->ops[ops_count++]);
+		if (ret)
+			return ret;
+	}
+	/* The device family, no op of another having ended its table. */
+	ret = ctlv_op_resolution_family_bound(&state);
+	if (ret)
+		return ret;
+	ctlvdev->dynamic_ops_count = state.dynamic;
+	ctlvdev->events_count = state.events;
+	return 0;
+}
+
+void *ctlv_priv_parent(const void *priv)
+{
+	const struct ctlv_priv_container *container = ctlv_priv_container(priv);
+
+	return container->parent ? container->parent->priv : NULL;
+}
+EXPORT_SYMBOL_NS_GPL(ctlv_priv_parent, "CTLV");
+
+void *ctlv_priv_child(const void *priv)
+{
+	const struct ctlv_priv_container *container = ctlv_priv_container(priv);
+
+	return container->child ? container->child->priv : NULL;
+}
+EXPORT_SYMBOL_NS_GPL(ctlv_priv_child, "CTLV");
+
+struct device *ctlv_device_parent(const struct ctlv_device *ctlvdev)
+{
+	return ctlvdev->dev.parent;
+}
+EXPORT_SYMBOL_NS_GPL(ctlv_device_parent, "CTLV");
+
+/*
+ * Dispatch reads the availability bit under no lock, so an op already admitted
+ * is neither cancelled nor waited for by a disable.
+ */
+
+struct ctlv_op_entry *ctlv_op_find(struct ctlv_device *ctlvdev, u64 op_id)
+{
+	u32 index;
+
+	/* The index ascends by op ID, so a miss stops early. */
+	for (index = 0; index < ctlvdev->ops_count; index++) {
+		if (ctlvdev->ops[index].schema->op_id == op_id)
+			return &ctlvdev->ops[index];
+		if (ctlvdev->ops[index].schema->op_id > op_id)
+			break;
+	}
+	return NULL;
+}
+
+static bool ctlv_op_disabled(struct ctlv_device *ctlvdev, const struct ctlv_op_entry *op)
+{
+	if (op->state_index == CTLV_OP_STATE_NONE)
+		return false;
+	/* Acquire, so what the family prepared before enabling is visible. */
+	return test_bit_acquire(op->state_index, ctlvdev->disabled);
+}
+
+static void ctlv_op_publish_all(struct ctlv_device *ctlvdev)
+{
+	u32 published = 0;
+	u32 index;
+
+	/* Against a family still opting in as this is called. */
+	guard(spinlock)
+		(&ctlvdev->transition_lock);
+	for (index = 0; index < ctlvdev->ops_count; index++) {
+		if (ctlvdev->ops[index].absent)
+			continue;
+		ctlvdev->ops[published++] = ctlvdev->ops[index];
+	}
+	ctlvdev->ops_count = published;
+	ctlvdev->published = true;
+}
+
+void ctlv_device_op_provide(struct ctlv_device *ctlvdev, u64 op_id)
+{
+	struct ctlv_op_entry *op;
+
+	guard(spinlock)
+		(&ctlvdev->transition_lock);
+	if (WARN_ON_ONCE(ctlvdev->published || ctlvdev->destroying))
+		return;
+	op = ctlv_op_find(ctlvdev, op_id);
+	/* An event is produced rather than answered, so there is none. */
+	if (WARN_ON_ONCE(!op) || WARN_ON_ONCE(!op->binding))
+		return;
+	op->absent = false;
+}
+EXPORT_SYMBOL_NS_GPL(ctlv_device_op_provide, "CTLV");
+
+void ctlv_device_op_state_set(struct ctlv_device *ctlvdev, u64 op_id, bool disabled)
+{
+	const struct ctlv_op_entry *op;
+
+	/*
+	 * Also serializes lookup against publication, which compacts the
+	 * array, and against teardown stopping state changes.
+	 */
+	guard(spinlock)
+		(&ctlvdev->transition_lock);
+	if (ctlvdev->destroying)
+		return;
+	op = ctlv_op_find(ctlvdev, op_id);
+	if (WARN_ON_ONCE(!op) || WARN_ON_ONCE(op->state_index == CTLV_OP_STATE_NONE))
+		return;
+	/* An op this device never took on has no state to change. */
+	if (WARN_ON_ONCE(op->absent))
+		return;
+	/*
+	 * Fully ordered, releasing what the family prepared to the acquire in
+	 * ctlv_op_disabled(). The old state makes a repeat change nothing.
+	 */
+	if (disabled ? test_and_set_bit(op->state_index, ctlvdev->disabled) :
+		       !test_and_clear_bit(op->state_index, ctlvdev->disabled))
+		return;
+	if (!ctlvdev->published)
+		return;
+	ctlvdev->state_generation++;
+	/* Still holding the serializer, so records reach queues in order. */
+	ctlv_event_op_changed(ctlvdev, op, disabled, ctlvdev->state_generation);
+}
+EXPORT_SYMBOL_NS_GPL(ctlv_device_op_state_set, "CTLV");
+
+static int ctlv_op_check_mode(const struct file *filp, const struct ctlv_op_entry *op)
+{
+	if (op->schema->type == CTLV_OP_TYPE_EVENT)
+		return -EOPNOTSUPP;
+
+	switch (op->schema->fd_access) {
+	case CTLV_OP_FD_ACCESS_READ:
+		return filp->f_mode & FMODE_READ ? 0 : -EACCES;
+	case CTLV_OP_FD_ACCESS_READ_WRITE:
+		return (filp->f_mode & (FMODE_READ | FMODE_WRITE)) == (FMODE_READ | FMODE_WRITE) ?
+			       0 :
+			       -EACCES;
+	default:
+		/* Registration rejects this before the device is visible. */
+		return -EACCES;
+	}
+}
+
+static u32 ctlv_reply_needed(const struct ctlv_op_entry *op)
+{
+	if (op->schema->type == CTLV_OP_TYPE_QUERY)
+		return op->sizes.query_reply_min_len;
+	return op->sizes.action_reply_max_len;
+}
+
+/*
+ * request_len is the copy boundary; root length frames the message. Ignored
+ * unknown attrs may exceed the schema maximum up to the transport limit.
+ */
+static int ctlv_request_frame(struct ctlv_op_ctx *ctx, const struct ctlv_op_exec *exec,
+			      const struct ctlv_attr *root)
+{
+	if (root->len < sizeof(*root) || root->len > exec->request_len ||
+	    root->attr_id != CTLV_ATTR_ROOT || root->flags != CTLV_ATTR_F_NESTED) {
+		ctx->error.reason = CTLV_VALIDATION_REASON_MALFORMED_MESSAGE;
+		return -EINVAL;
+	}
+	return 0;
+}
+
+static int ctlv_request_validate(struct ctlv_op_ctx *ctx, const struct ctlv_op_exec *exec,
+				 struct ctlv_attr *root)
+{
+	int ret;
+
+	ret = ctlv_request_frame(ctx, exec, root);
+	if (ret)
+		return ret;
+	if (!ctx->op->schema->request.node_schemas)
+		return 0;
+
+	ctx->request = (struct ctlv_msg){
+		.root = root,
+		.len = exec->request_len,
+		.tree = &ctx->op->schema->request,
+		.family = ctx->family,
+		.request = true,
+	};
+	return ctlv_schema_validate(&ctx->request, &ctx->error);
+}
+
+/*
+ * An action is given exactly the maximum its schema allows, so running out of
+ * room is this kernel's mistake. A query is given whatever the caller offered.
+ */
+static u32 ctlv_reply_capacity(const struct ctlv_op_entry *op, const struct ctlv_op_exec *exec)
+{
+	if (!op->schema->reply.node_schemas)
+		return 0;
+	if (op->schema->type == CTLV_OP_TYPE_QUERY)
+		return exec->reply_len;
+	return op->sizes.action_reply_max_len;
+}
+
+/* Actions and final query fragments must be complete schema-valid replies. */
+static int ctlv_reply_finish(struct ctlv_op_ctx *ctx)
+{
+	struct ctlv_error refused = {};
+
+	if (!ctx->output.root)
+		return 0;
+	/* Whatever poisoned it has warned about it already. */
+	if (ctx->output.poison)
+		return ctx->output.poison;
+	/* A query was held to its open nests by the ending it came to. */
+	if (ctx->op->schema->type == CTLV_OP_TYPE_QUERY) {
+		if (ctx->frag.cursor || ctx->frag.next_cursor)
+			return 0;
+	} else if (WARN_ON_ONCE(ctx->deepest != &ctx->output_root)) {
+		/* A cursor of a returned frame is reset, never followed. */
+		ctx->deepest = &ctx->output_root;
+		return -EINVAL;
+	}
+	if (WARN_ON_ONCE(ctlv_schema_validate(&ctx->output, &refused)))
+		return -EINVAL;
+	return 0;
+}
+
+/* A successful query callback must end exactly one fragment. */
+static int ctlv_query_fragment_result(struct ctlv_op_ctx *ctx)
+{
+	if (WARN_ON_ONCE(!ctx->frag.answered))
+		return -EINVAL;
+	return ctx->frag.result;
+}
+
+static int ctlv_op_call(struct ctlv_op_ctx *ctx)
+{
+	const struct ctlv_op_entry *op = ctx->op;
+	struct ctlv_cursor *request = NULL;
+	struct ctlv_cursor *reply = NULL;
+	int blob_ret;
+	int ret;
+
+	if (ctx->request.root) {
+		ctlv_message_root(&ctx->request_root, &ctx->request);
+		request = &ctx->request_root;
+	}
+	if (ctx->output.root)
+		reply = &ctx->output_root;
+
+	ctlv_blob_context_init(ctx);
+	if (op->schema->type == CTLV_OP_TYPE_ACTION) {
+		ret = op->binding->action(op->priv, ctx, request, reply);
+	} else {
+		ret = op->binding->query(op->priv, ctx, request, reply);
+		if (!ret)
+			ret = ctlv_query_fragment_result(ctx);
+	}
+	blob_ret = ctlv_blob_context_finish(ctx);
+	if (!ret)
+		ret = blob_ret;
+	if (ret)
+		return ret;
+	return ctlv_reply_finish(ctx);
+}
+
+/*
+ * The device family's hooks around the declaring op's, except that a core op
+ * uses the core family. The availability check is innermost.
+ */
+static int ctlv_op_dispatch(struct ctlv_op_ctx *ctx)
+{
+	const struct ctlv_op *op = ctx->op->binding;
+	const struct ctlv_family *family;
+	void *family_priv;
+	int ret;
+
+	if (CTLV_OP_FAMILY(ctx->op->schema->op_id) == CTLV_FAMILY_ROOT) {
+		family = &ctlv_family;
+		family_priv = ctx->ctlvdev->privs[0].priv;
+	} else {
+		family = ctx->ctlvdev->family;
+		family_priv = ctx->ctlvdev->privs[ctx->ctlvdev->privs_count - 1].priv;
+	}
+	ret = family->pre(family_priv, ctx);
+	if (ret)
+		return ret;
+
+	if (op->pre) {
+		ret = op->pre(ctx->op->priv, ctx);
+		if (ret)
+			goto out;
+	}
+
+	/* The only authoritative check: introspection is advisory. */
+	if (ctlv_op_disabled(ctx->ctlvdev, ctx->op))
+		ret = -EOPNOTSUPP;
+	else
+		ret = ctlv_op_call(ctx);
+
+	if (op->post)
+		op->post(ctx->op->priv, ctx);
+out:
+	family->post(family_priv, ctx);
+	return ret;
+}
+
+/* Error information replaces the reply atomically; errno remains authoritative. */
+static void ctlv_error_info(struct ctlv_op_ctx *ctx, u32 room, void **reply, u32 *reply_len)
+{
+	const struct ctlv_error *error = &ctx->error;
+	struct ctlv_cursor *root = &ctx->output_root;
+	void *buf;
+
+	if ((!error->reason && !error->message[0]) || !room)
+		return;
+	buf = kvmalloc(CTLV_ERROR_INFO_MAX_LEN, GFP_KERNEL_ACCOUNT);
+	if (!buf)
+		return;
+
+	/* The same builder over another schema, and a buffer of its own. */
+	ctlv_message_output_init(&ctx->output, ctx, buf, CTLV_ERROR_INFO_MAX_LEN,
+				 &ctlv_error_info_schema);
+	ctlv_message_root(root, &ctx->output);
+	ctx->deepest = root;
+
+	if (error->reason)
+		ctlv_put_u64(root, CTLV_ATTR_ERROR_REASON, CTLV_SCHEMA_ENUM, error->reason);
+	if (error->message[0])
+		ctlv_error_message_put(root, error->message);
+	if (error->reason == CTLV_VALIDATION_REASON_STALE_GENERATION) {
+		/* The one failure that is about no part of any message. */
+		ctlv_put_u64(root, CTLV_ATTR_ERROR_EXPECTED_GENERATION, CTLV_SCHEMA_UINT,
+			     error->expected_generation);
+		ctlv_put_u64(root, CTLV_ATTR_ERROR_CURRENT_GENERATION, CTLV_SCHEMA_UINT,
+			     error->current_generation);
+	} else if (error->reason) {
+		ctlv_put_u64(root, CTLV_ATTR_ERROR_BAD_ATTR_OFFSET, CTLV_SCHEMA_UINT,
+			     error->bad_attr_offset);
+		ctlv_put_u64(root, CTLV_ATTR_ERROR_NEST_OFFSET, CTLV_SCHEMA_UINT,
+			     error->nest_offset);
+		/* No attr is numbered zero, so a zero names nothing. */
+		if (error->missing_attr_id)
+			ctlv_put_u64(root, CTLV_ATTR_ERROR_MISSING_ATTR_ID, CTLV_SCHEMA_UINT,
+				     error->missing_attr_id);
+	}
+
+	if (ctx->output.poison || ctx->output.root->len > room) {
+		kvfree(buf);
+		return;
+	}
+	*reply = buf;
+	*reply_len = ctx->output.root->len;
+}
+
+/*
+ * Everything that needs the device to still have a family. @reply is built
+ * here and becomes the caller's to free, to copy out once the family is gone.
+ */
+static int ctlv_op_exec(struct ctlv_file *cfile, struct file *filp, struct ctlv_op_exec *exec,
+			void **reply, u32 *reply_len)
+{
+	struct ctlv_device *ctlvdev = cfile->ctlvdev;
+	const struct ctlv_op_entry *op;
+	struct ctlv_op_ctx ctx = {};
+	u32 capacity;
+	int ret;
+
+	/* No family numbers an op zero, so a zero here is an unset field. */
+	if (!exec->op_id)
+		return -EINVAL;
+	op = ctlv_op_find(ctlvdev, exec->op_id);
+	if (!op)
+		return -EOPNOTSUPP;
+	ret = ctlv_op_check_mode(filp, op);
+	if (ret)
+		return ret;
+	/*
+	 * Only a query resumes. A cursor says which fragment this is, so a
+	 * generation without one continues what was never started.
+	 */
+	if (op->schema->type == CTLV_OP_TYPE_QUERY) {
+		if (!exec->cursor && exec->generation)
+			return -EINVAL;
+		ctx.frag.generation = exec->generation;
+		ctx.frag.cursor = exec->cursor;
+	} else if (exec->generation || exec->cursor) {
+		return -EINVAL;
+	}
+
+	/* Before the callback, so a buffer too small mutates nothing. */
+	if (exec->reply_len < ctlv_reply_needed(op))
+		return -EMSGSIZE;
+	/* And no longer than a message of this core may be. */
+	if (exec->reply_len > CTLV_MAX_INLINE_MESSAGE_LEN)
+		return -EINVAL;
+
+	ctx.ctlvdev = ctlvdev;
+	ctx.family = ctlvdev->family;
+	ctx.file = cfile;
+	/* Whose memory a blob descriptor of this request describes. */
+	ctx.submitter = current;
+	ctx.op = op;
+
+	void *snapshot __free(kvfree) = NULL;
+	void *out __free(kvfree) = NULL;
+
+	if (exec->request_len < sizeof(struct ctlv_attr) ||
+	    exec->request_len > CTLV_MAX_INLINE_MESSAGE_LEN)
+		return -EINVAL;
+	/* Everything after this reads the snapshot, never userspace. */
+	snapshot = kvmalloc(exec->request_len, GFP_KERNEL_ACCOUNT);
+	if (!snapshot)
+		return -ENOMEM;
+	if (copy_from_user(snapshot, u64_to_user_ptr(exec->request), exec->request_len))
+		return -EFAULT;
+	/* Before any hook, so that no family code sees an unchecked attr. */
+	ret = ctlv_request_validate(&ctx, exec, snapshot);
+	if (ret)
+		goto out_error_info;
+
+	capacity = ctlv_reply_capacity(op, exec);
+	if (capacity) {
+		/*
+		 * Not zeroed: a byte is copied out only once the root's
+		 * length covers it, padding included.
+		 */
+		out = kvmalloc(capacity, GFP_KERNEL_ACCOUNT);
+		if (!out) {
+			ret = -ENOMEM;
+			goto out_request;
+		}
+		ctlv_message_output_init(&ctx.output, &ctx, out, capacity, &op->schema->reply);
+		ctlv_message_root(&ctx.output_root, &ctx.output);
+		ctx.deepest = &ctx.output_root;
+	}
+
+	ret = ctlv_op_dispatch(&ctx);
+	if (ret)
+		goto out_error_info;
+
+	/* Where the caller carries on from, zero for anything but a query. */
+	exec->generation = ctx.frag.reported;
+	exec->cursor = ctx.frag.next_cursor;
+	*reply_len = ctx.output.root ? ctx.output.root->len : 0;
+	*reply = no_free_ptr(out);
+	ret = 0;
+	goto out_request;
+
+out_error_info:
+	ctlv_error_info(&ctx, exec->reply_len, reply, reply_len);
+out_request:
+	ctlv_message_index_free(&ctx.request);
+	return ret;
+}
+
+/* What one family of this device's chain does with one extension point. */
+static const struct ctlv_stub_ops *ctlv_stub_ops_find(const struct ctlv_device *ctlvdev,
+						      const struct ctlv_stub_schema *stub_schema,
+						      void **priv)
+{
+	const struct ctlv_family *family;
+	u32 index;
+
+	/* From the device family towards the core, where the fill was found. */
+	for (family = ctlvdev->family; family; family = family->parent)
+		for (index = 0; index < family->stub_ops_count; index++)
+			if (family->stub_ops[index].family_id == stub_schema->family_id &&
+			    family->stub_ops[index].set_id == stub_schema->set_id) {
+				struct ctlv_family_priv *family_priv;
+
+				family_priv = ctlv_family_priv_find(ctlvdev, family);
+				if (WARN_ON_ONCE(!family_priv))
+					return NULL;
+				*priv = family_priv->priv;
+				return &family->stub_ops[index];
+			}
+	return NULL;
+}
+
+int ctlv_stub_fill(struct ctlv_op_ctx *ctx, const struct ctlv_cursor *request,
+		   struct ctlv_cursor *nest)
+{
+	const struct ctlv_schema_tree *tree;
+	u32 index;
+
+	if (WARN_ON_ONCE(!nest->tree))
+		return -EINVAL;
+	tree = nest->tree;
+	for (index = 0; index < tree->stub_schemas_count; index++) {
+		const struct ctlv_stub_schema *stub_schema = &tree->stub_schemas[index];
+		const struct ctlv_cursor *filled_request = request;
+		const struct ctlv_stub_fill_schema *fill_schema;
+		const struct ctlv_stub_ops *stub_ops;
+		struct ctlv_cursor filled;
+		void *priv;
+		int ret;
+
+		if (stub_schema->node != nest->node)
+			continue;
+		stub_ops = ctlv_stub_ops_find(ctx->ctlvdev, stub_schema, &priv);
+		if (!stub_ops || !stub_ops->fill)
+			continue;
+		if (request) {
+			fill_schema = ctlv_schema_fill(ctx->family, stub_schema->family_id,
+						       stub_schema->set_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;
+		}
+		ret = stub_ops->fill(priv, ctx, filled_request, nest);
+		if (ret)
+			return ret;
+	}
+	return 0;
+}
+EXPORT_SYMBOL_NS_GPL(ctlv_stub_fill, "CTLV");
+
+/*
+ * The core answers the root family through the same generated descriptor a
+ * family creates with, so it needs the same callbacks.
+ */
+int ctlv_op_pre(void *priv, struct ctlv_op_ctx *ctx)
+{
+	return 0;
+}
+
+void ctlv_op_post(void *priv, struct ctlv_op_ctx *ctx)
+{
+}
+
+size_t ctlv_priv_size(void)
+{
+	return 0;
+}
+
+int ctlv_init(struct ctlv_device *ctlvdev, const void *init_info, void *priv)
+{
+	if (WARN_ON_ONCE(init_info) || WARN_ON_ONCE(ctlv_priv_parent(priv)))
+		return -EINVAL;
+	return 0;
+}
+
+void ctlv_fini(struct ctlv_device *ctlvdev, void *priv)
+{
+}
+
+static long ctlv_file_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
+{
+	struct ctlv_op_exec __user *uexec = (struct ctlv_op_exec __user *)arg;
+	struct ctlv_file *cfile = filp->private_data;
+	struct ctlv_device *ctlvdev = cfile->ctlvdev;
+	struct ctlv_op_exec exec;
+	u32 reply_len = 0;
+	int ret;
+
+	if (cmd != CTLV_IOC_OP_EXEC)
+		return -ENOIOCTLCMD;
+	if (copy_from_user(&exec, uexec, sizeof(exec)))
+		return -EFAULT;
+	/* Reserved fields are what a compatible growth of this ioctl uses. */
+	if (exec.reserved[0] || exec.reserved[1])
+		return -EINVAL;
+
+	void *reply __free(kvfree) = NULL;
+
+	scoped_guard(rwsem_read, &ctlvdev->registration_lock) {
+		if (!ctlvdev->registered || !ctlvdev->family)
+			return -ENODEV;
+		ret = ctlv_op_exec(cfile, filp, &exec, &reply, &reply_len);
+	}
+	/* Do not make destruction wait for a faulting userspace copy. */
+	if (reply_len && copy_to_user(u64_to_user_ptr(exec.reply), reply, reply_len))
+		return ret ?: -EFAULT;
+	/*
+	 * The only fields the kernel writes back, a field at a time so that
+	 * what the caller stated about its own buffers stays the caller's.
+	 */
+	if (!ret && (put_user(exec.generation, &uexec->generation) ||
+		     put_user(exec.cursor, &uexec->cursor)))
+		return -EFAULT;
+	return ret;
+}
+
+/*
+ * One record per read, so a reader never gets a partial event. The offset says
+ * nothing about a queue and is neither read nor advanced.
+ */
+static ssize_t ctlv_file_read(struct file *filp, char __user *buf, size_t len, loff_t *ppos)
+{
+	struct ctlv_file *cfile = filp->private_data;
+
+	return ctlv_event_file_read(cfile, buf, len, !(filp->f_flags & O_NONBLOCK));
+}
+
+static __poll_t ctlv_file_poll(struct file *filp, struct poll_table_struct *wait)
+{
+	struct ctlv_file *cfile = filp->private_data;
+
+	return ctlv_event_file_poll(cfile, filp, wait);
+}
+
+static bool ctlv_file_open_allowed(struct ctlv_device *ctlvdev)
+{
+	lockdep_assert_held_read(&ctlvdev->registration_lock);
+	return ctlvdev->registered && ctlvdev->family;
+}
+
+static void ctlv_file_open_pinned(struct ctlv_device *ctlvdev)
+{
+}
+
+static int ctlv_file_open(struct inode *inode, struct file *filp)
+{
+	struct ctlv_device *ctlvdev = container_of(inode->i_cdev, struct ctlv_device, cdev);
+	struct ctlv_file *cfile;
+	int ret;
+
+	/*
+	 * A failed create can withdraw the cdev while an open is waiting for
+	 * the lifecycle lock, so admission itself first pins core storage.
+	 */
+	get_device(&ctlvdev->dev);
+	ctlv_file_open_pinned(ctlvdev);
+	scoped_guard(rwsem_read, &ctlvdev->registration_lock) {
+		if (!ctlv_file_open_allowed(ctlvdev)) {
+			ret = -ENODEV;
+			break;
+		}
+		if (!(filp->f_mode & FMODE_READ)) {
+			ret = -EACCES;
+			break;
+		}
+
+		cfile = kzalloc_obj(*cfile, GFP_KERNEL_ACCOUNT);
+		if (!cfile) {
+			ret = -ENOMEM;
+			break;
+		}
+		cfile->ctlvdev = ctlvdev;
+		/*
+		 * Commits this description to the device. An open that failed
+		 * after this would have to take it back.
+		 */
+		ret = ctlv_event_file_init(cfile);
+		if (ret) {
+			kfree(cfile);
+			break;
+		}
+		/* This description keeps the reference taken on entry. */
+		filp->private_data = cfile;
+		return 0;
+	}
+
+	put_device(&ctlvdev->dev);
+	return ret;
+}
+
+static int ctlv_file_release(struct inode *inode, struct file *filp)
+{
+	struct ctlv_file *cfile = filp->private_data;
+	struct ctlv_device *ctlvdev = cfile->ctlvdev;
+
+	ctlv_event_file_exit(cfile);
+	kfree(cfile);
+	put_device(&ctlvdev->dev);
+	return 0;
+}
+
+static const struct file_operations ctlv_file_operations = {
+	.owner = THIS_MODULE,
+	.open = ctlv_file_open,
+	.release = ctlv_file_release,
+	.read = ctlv_file_read,
+	.poll = ctlv_file_poll,
+	.unlocked_ioctl = ctlv_file_ioctl,
+	/* Every ioctl field is fixed width, so one entry point serves both. */
+	.compat_ioctl = compat_ptr_ioctl,
+};
+
+/* Uevent identity is available to rules before the device can be opened. */
+static int ctlv_device_uevent_families(struct kobj_uevent_env *env,
+				       const struct ctlv_family *family)
+{
+	u32 levels = ctlv_family_levels(family);
+	u32 level;
+	int ret;
+
+	ret = add_uevent_var(env, "CTLV_FAMILY=%s", family->schema->name);
+	if (ret)
+		return ret;
+	for (level = 0; level < levels; level++) {
+		const struct ctlv_family *ancestor =
+			ctlv_family_ancestor(family, levels - 1 - level);
+
+		ret = add_uevent_var(env, "CTLV_COMPATIBLE_%u=%s", level, ancestor->schema->name);
+		if (ret)
+			return ret;
+	}
+	return add_uevent_var(env, "CTLV_COMPATIBLE_N=%u", levels);
+}
+
+static int ctlv_device_uevent_check(const struct ctlv_family *family)
+{
+	struct kobj_uevent_env *env;
+	int ret;
+
+	env = kzalloc_obj(*env, GFP_KERNEL);
+	if (!env)
+		return -ENOMEM;
+	ret = ctlv_device_uevent_families(env, family);
+	if (!ret && (env->buflen > CTLV_UEVENT_MAX_LEN || env->envp_idx > CTLV_UEVENT_MAX_VARS)) {
+		pr_err("family %s: its chain of names needs %d bytes in %d properties of a uevent, more than the %d in %d it may take\n",
+		       family->schema->name, env->buflen, env->envp_idx, CTLV_UEVENT_MAX_LEN,
+		       CTLV_UEVENT_MAX_VARS);
+		ret = -E2BIG;
+	}
+	kfree(env);
+	return ret;
+}
+
+/* Read unlocked: a uevent may be asked for under the registration lock. */
+static int ctlv_device_uevent(const struct device *dev, struct kobj_uevent_env *env)
+{
+	const struct ctlv_device *ctlvdev = container_of_const(dev, struct ctlv_device, dev);
+	const struct ctlv_family *family = READ_ONCE(ctlvdev->family);
+
+	if (!family)
+		return 0;
+	return ctlv_device_uevent_families(env, family);
+}
+
+static void ctlv_device_release(struct device *dev)
+{
+	struct ctlv_device *ctlvdev = container_of(dev, struct ctlv_device, dev);
+
+	ida_free(&ctlv_device_ids, ctlvdev->dev.devt - ctlv_device_number);
+	bitmap_free(ctlvdev->disabled);
+	ctlv_family_privs_free(ctlvdev);
+	kfree(ctlvdev->ops);
+	kfree(ctlvdev);
+}
+
+static struct class ctlv_device_class = {
+	.name = "ctlv",
+	.dev_release = ctlv_device_release,
+	.dev_uevent = ctlv_device_uevent,
+};
+
+static int ctlv_device_add(struct ctlv_device *ctlvdev)
+{
+	lockdep_assert_held_write(&ctlvdev->registration_lock);
+
+	return cdev_device_add(&ctlvdev->cdev, &ctlvdev->dev);
+}
+
+static void ctlv_device_del(struct ctlv_device *ctlvdev)
+{
+	cdev_device_del(&ctlvdev->cdev, &ctlvdev->dev);
+}
+
+struct ctlv_device *ctlv_create(struct device *parent_dev, const struct ctlv_family *family,
+				const void *init_info)
+{
+	struct ctlv_device *ctlvdev;
+	int devnum, ret;
+
+	if (!parent_dev || !family)
+		return ERR_PTR(-EINVAL);
+
+	ctlvdev = kzalloc_obj(*ctlvdev, GFP_KERNEL);
+	if (!ctlvdev)
+		return ERR_PTR(-ENOMEM);
+	ctlvdev->family = family;
+	init_rwsem(&ctlvdev->registration_lock);
+	spin_lock_init(&ctlvdev->transition_lock);
+	ctlv_event_device_init(ctlvdev);
+
+	/* Before anything reads the schema through this device. */
+	ret = ctlv_op_resolution_init(ctlvdev, family);
+	if (ret)
+		goto err_free;
+	/* What this family's events need of every queue opened on it. */
+	ret = ctlv_event_sizes(ctlvdev);
+	if (ret)
+		goto err_free;
+	/* Before a minor is spent on a device that could not be announced. */
+	ret = ctlv_device_uevent_check(family);
+	if (ret)
+		goto err_free;
+	if (ctlvdev->dynamic_ops_count) {
+		ctlvdev->disabled = bitmap_zalloc(ctlvdev->dynamic_ops_count, GFP_KERNEL);
+		if (!ctlvdev->disabled) {
+			ret = -ENOMEM;
+			goto err_free;
+		}
+	}
+	devnum = ida_alloc_max(&ctlv_device_ids, CTLV_MAX_DEVICES - 1, GFP_KERNEL);
+	if (devnum < 0) {
+		ret = devnum;
+		goto err_free;
+	}
+
+	ctlvdev->dev.devt = ctlv_device_number + devnum;
+	ctlvdev->dev.class = &ctlv_device_class;
+	ctlvdev->dev.parent = parent_dev;
+	device_initialize(&ctlvdev->dev);
+	/*
+	 * The core owns the file operations, so an open holds the core module
+	 * and not the family's, which may unload while readers remain.
+	 */
+	cdev_init(&ctlvdev->cdev, &ctlv_file_operations);
+	ctlvdev->cdev.owner = THIS_MODULE;
+
+	ret = dev_set_name(&ctlvdev->dev, "ctlv%d", devnum);
+	if (ret)
+		goto err_put;
+	ret = ctlv_family_claim_add(family->schema);
+	if (ret)
+		goto err_put;
+	ret = ctlv_family_privs_pre_init(ctlvdev, init_info);
+	if (ret)
+		goto err_put;
+	ret = ctlv_family_privs_init(ctlvdev);
+	if (ret)
+		goto err_put;
+	ctlv_op_publish_all(ctlvdev);
+	ctlv_event_contexts_start(ctlvdev);
+	ret = ctlv_family_privs_post_init(ctlvdev);
+	if (ret)
+		goto err_fini;
+	scoped_guard(rwsem_write, &ctlvdev->registration_lock) {
+		ret = ctlv_device_add(ctlvdev);
+		if (!ret)
+			ctlvdev->registered = true;
+	}
+	if (ret)
+		goto err_fini;
+	return ctlvdev;
+
+err_fini:
+	ctlv_device_fini(ctlvdev);
+err_put:
+	put_device(&ctlvdev->dev);
+	return ERR_PTR(ret);
+err_free:
+	bitmap_free(ctlvdev->disabled);
+	ctlv_family_privs_free(ctlvdev);
+	kfree(ctlvdev->ops);
+	kfree(ctlvdev);
+	return ERR_PTR(ret);
+}
+EXPORT_SYMBOL_NS_GPL(ctlv_create, "CTLV");
+
+void ctlv_destroy(struct ctlv_device *ctlvdev)
+{
+	u32 index;
+
+	/* No new opens, no discovery entry, and no node to open. */
+	ctlv_device_del(ctlvdev);
+
+	/*
+	 * The write side waits for admitted callbacks while their events still
+	 * work. Once held, registration state keeps every later ioctl out.
+	 */
+	scoped_guard(rwsem_write, &ctlvdev->registration_lock)
+		ctlvdev->registered = false;
+
+	ctlv_device_fini(ctlvdev);
+
+	/* No callback can reach what the family owns after finalization. */
+	scoped_guard(rwsem_write, &ctlvdev->registration_lock)
+		WRITE_ONCE(ctlvdev->family, NULL);
+	for (index = 0; index < ctlvdev->ops_count; index++) {
+		ctlvdev->ops[index].binding = NULL;
+		ctlvdev->ops[index].priv = NULL;
+	}
+	ctlv_family_privs_free(ctlvdev);
+	put_device(&ctlvdev->dev);
+}
+EXPORT_SYMBOL_NS_GPL(ctlv_destroy, "CTLV");
+
+static int __init ctlv_module_init(void)
+{
+	int ret;
+
+	ret = alloc_chrdev_region(&ctlv_device_number, 0, CTLV_MAX_DEVICES, "ctlv");
+	if (ret)
+		return ret;
+
+	ret = class_register(&ctlv_device_class);
+	if (ret)
+		goto err_unregister_chrdev_region;
+
+	return 0;
+
+err_unregister_chrdev_region:
+	unregister_chrdev_region(ctlv_device_number, CTLV_MAX_DEVICES);
+	return ret;
+}
+
+static void __exit ctlv_module_exit(void)
+{
+	class_unregister(&ctlv_device_class);
+	unregister_chrdev_region(ctlv_device_number, CTLV_MAX_DEVICES);
+	ctlv_family_claims_free();
+	ida_destroy(&ctlv_device_ids);
+}
+
+subsys_initcall(ctlv_module_init);
+module_exit(ctlv_module_exit);
+MODULE_DESCRIPTION("CTLV character device TLV UAPI core");
+MODULE_LICENSE("GPL");
diff --git a/drivers/ctlv/ctlv_gen.c b/drivers/ctlv/ctlv_gen.c
new file mode 100644
index 0000000000000..daf54495658f5
--- /dev/null
+++ b/drivers/ctlv/ctlv_gen.c
@@ -0,0 +1,229 @@
+// SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)
+/* Do not edit, regenerate with tools/ctlv/ctlv-regen.sh, from: */
+/*	Documentation/ctlv/specs/ctlv.yaml */
+/* CTLV-GEN kernel source */
+
+#define _CTLV_GENERATED_METADATA_ONLY
+#include <linux/array_size.h>
+#include <linux/build_bug.h>
+#include <linux/ctlv_family.h>
+#include <linux/export.h>
+#include <linux/limits.h>
+
+#include <uapi/linux/ctlv_gen.h>
+
+#include <linux/ctlv_gen.h>
+
+static const struct ctlv_node_schema families_dump_request_node_schemas[] = {
+	CTLV_NODE_SCHEMA_ROOT(0, 0, 0),
+};
+
+static const struct ctlv_node_schema families_dump_reply_node_schemas[] = {
+	CTLV_NODE_SCHEMA_ROOT(1, 1, 1),
+	CTLV_NODE_SCHEMA_NEST(CTLV_ATTR_FAMILY_ENTRY, CTLV_NODE_SCHEMA_UNLIMITED, 2, 2, 2),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_FAMILY_ID, 1, 0, U64_MAX),
+	CTLV_NODE_SCHEMA_STRING(CTLV_ATTR_FAMILY_NAME, 1, 0, 63),
+};
+
+static const struct ctlv_node_schema ops_dump_request_node_schemas[] = {
+	CTLV_NODE_SCHEMA_ROOT(0, 0, 0),
+};
+
+static const struct ctlv_node_schema ops_dump_reply_node_schemas[] = {
+	CTLV_NODE_SCHEMA_ROOT(1, 1, 1),
+	CTLV_NODE_SCHEMA_NEST(CTLV_ATTR_OP_ENTRY, CTLV_NODE_SCHEMA_UNLIMITED, 2, 10, 2),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_OP_ID, 1, 1, U64_MAX),
+	CTLV_NODE_SCHEMA_ENUM(CTLV_ATTR_OP_TYPE, 1, 3),
+	CTLV_NODE_SCHEMA_ENUM(CTLV_ATTR_OP_AVAILABILITY, 1, 2),
+	CTLV_NODE_SCHEMA_BOOL(CTLV_ATTR_OP_DISABLED, 1),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_OP_REQUEST_MAX_LEN, 1, 0, U64_MAX),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_OP_ACTION_REPLY_MAX_LEN, 1, 0, U64_MAX),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_OP_QUERY_REPLY_MIN_LEN, 1, 0, U64_MAX),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_OP_QUERY_REPLY_SUGGESTED_LEN, 1, 0, U64_MAX),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_OP_EVENT_RECORD_MAX_LEN, 1, 0, U64_MAX),
+	CTLV_NODE_SCHEMA_ENUM(CTLV_ATTR_OP_FD_ACCESS, 1, 2),
+};
+
+static const struct ctlv_node_schema op_schema_get_request_node_schemas[] = {
+	CTLV_NODE_SCHEMA_ROOT(1, 1, 1),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_OP_ID, 1, 1, U64_MAX),
+};
+
+static const struct ctlv_node_schema op_schema_get_reply_node_schemas[] = {
+	CTLV_NODE_SCHEMA_ROOT(1, 2, 0),
+	CTLV_NODE_SCHEMA_NEST(CTLV_ATTR_SCHEMA_REQUEST, 1, 3, 17, 3),
+	CTLV_NODE_SCHEMA_NEST(CTLV_ATTR_SCHEMA_REPLY, 1, 20, 17, 3),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_ATTR_ID, 1, 0, U64_MAX),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_KIND, 1, 0, U64_MAX),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_MAX_OCCURRENCES, 1, 0, U64_MAX),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_MIN, 1, 0, U64_MAX),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_MAX, 1, 0, U64_MAX),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_MIN_LENGTH, 1, 0, U64_MAX),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_MAX_LENGTH, 1, 0, U64_MAX),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_FLAGS_MASK, 1, 0, U64_MAX),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_UNIT, 1, 0, U64_MAX),
+	CTLV_NODE_SCHEMA_SINT(CTLV_ATTR_SCHEMA_SCALE, 1, S64_MIN, S64_MAX),
+	CTLV_NODE_SCHEMA_ENUM(CTLV_ATTR_SCHEMA_BLOB_DIRECTION, 1, 3),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_BLOB_BACKINGS, 1, 0, U64_MAX),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_BLOB_MAX_LENGTH, 1, 0, U64_MAX),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_BLOB_ALIGNMENT, 1, 0, U64_MAX),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_REENTERS, 1, 1, U64_MAX),
+	CTLV_NODE_SCHEMA_NEST_REENTERS(CTLV_ATTR_SCHEMA_ATTRS, CTLV_NODE_SCHEMA_UNLIMITED, 3, 17,
+				       3),
+	CTLV_NODE_SCHEMA_NEST_REENTERS(CTLV_ATTR_SCHEMA_OPTIONAL_ATTRS, CTLV_NODE_SCHEMA_UNLIMITED,
+				       3, 17, 3),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_ATTR_ID, 1, 0, U64_MAX),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_KIND, 1, 0, U64_MAX),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_MAX_OCCURRENCES, 1, 0, U64_MAX),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_MIN, 1, 0, U64_MAX),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_MAX, 1, 0, U64_MAX),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_MIN_LENGTH, 1, 0, U64_MAX),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_MAX_LENGTH, 1, 0, U64_MAX),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_FLAGS_MASK, 1, 0, U64_MAX),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_UNIT, 1, 0, U64_MAX),
+	CTLV_NODE_SCHEMA_SINT(CTLV_ATTR_SCHEMA_SCALE, 1, S64_MIN, S64_MAX),
+	CTLV_NODE_SCHEMA_ENUM(CTLV_ATTR_SCHEMA_BLOB_DIRECTION, 1, 3),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_BLOB_BACKINGS, 1, 0, U64_MAX),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_BLOB_MAX_LENGTH, 1, 0, U64_MAX),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_BLOB_ALIGNMENT, 1, 0, U64_MAX),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_SCHEMA_REENTERS, 1, 1, U64_MAX),
+	CTLV_NODE_SCHEMA_NEST_REENTERS(CTLV_ATTR_SCHEMA_ATTRS, CTLV_NODE_SCHEMA_UNLIMITED, 20, 17,
+				       3),
+	CTLV_NODE_SCHEMA_NEST_REENTERS(CTLV_ATTR_SCHEMA_OPTIONAL_ATTRS, CTLV_NODE_SCHEMA_UNLIMITED,
+				       20, 17, 3),
+};
+
+static const struct ctlv_node_schema subscriptions_add_request_node_schemas[] = {
+	CTLV_NODE_SCHEMA_ROOT(1, 1, 1),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_EVENT_OP_ID, 256, 1, U64_MAX),
+};
+
+static const struct ctlv_node_schema subscriptions_remove_request_node_schemas[] = {
+	CTLV_NODE_SCHEMA_ROOT(1, 1, 1),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_EVENT_OP_ID, 256, 1, U64_MAX),
+};
+
+static const struct ctlv_node_schema event_queue_get_request_node_schemas[] = {
+	CTLV_NODE_SCHEMA_ROOT(0, 0, 0),
+};
+
+static const struct ctlv_node_schema event_queue_get_reply_node_schemas[] = {
+	CTLV_NODE_SCHEMA_ROOT(1, 2, 2),
+	CTLV_NODE_SCHEMA_UINT_UNIT(CTLV_ATTR_EVENT_QUEUE_LEN, 1, 1, 16777216, CTLV_UNIT_BYTES, 0),
+	CTLV_NODE_SCHEMA_UINT_UNIT(CTLV_ATTR_EVENT_QUEUE_USED, 1, 0, U64_MAX, CTLV_UNIT_BYTES, 0),
+};
+
+static const struct ctlv_node_schema event_queue_set_request_node_schemas[] = {
+	CTLV_NODE_SCHEMA_ROOT(1, 1, 1),
+	CTLV_NODE_SCHEMA_UINT_UNIT(CTLV_ATTR_EVENT_QUEUE_LEN, 1, 1, 16777216, CTLV_UNIT_BYTES, 0),
+};
+
+static const struct ctlv_node_schema op_changed_reply_node_schemas[] = {
+	CTLV_NODE_SCHEMA_ROOT(1, 3, 3),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_OP_ID, 1, 1, U64_MAX),
+	CTLV_NODE_SCHEMA_BOOL(CTLV_ATTR_OP_DISABLED, 1),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_OP_STATE_GENERATION, 1, 0, U64_MAX),
+};
+
+static const struct ctlv_node_schema event_overflow_reply_node_schemas[] = {
+	CTLV_NODE_SCHEMA_ROOT(1, 3, 3),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_EVENT_FIRST_SEQUENCE, 1, 0, U64_MAX),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_EVENT_LAST_SEQUENCE, 1, 0, U64_MAX),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_EVENT_DROPPED_COUNT, 1, 0, U64_MAX),
+};
+
+static const struct ctlv_node_schema device_removed_reply_node_schemas[] = {
+	CTLV_NODE_SCHEMA_ROOT(0, 0, 0),
+};
+
+static const struct ctlv_node_schema error_info_node_schemas[] = {
+	CTLV_NODE_SCHEMA_ROOT(1, 7, 0),
+	CTLV_NODE_SCHEMA_ENUM(CTLV_ATTR_ERROR_REASON, 1, 12),
+	CTLV_NODE_SCHEMA_STRING(CTLV_ATTR_ERROR_MESSAGE, 1, 0, 255),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_ERROR_BAD_ATTR_OFFSET, 1, 0, U64_MAX),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_ERROR_NEST_OFFSET, 1, 0, U64_MAX),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_ERROR_MISSING_ATTR_ID, 1, 0, U64_MAX),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_ERROR_EXPECTED_GENERATION, 1, 0, U64_MAX),
+	CTLV_NODE_SCHEMA_UINT(CTLV_ATTR_ERROR_CURRENT_GENERATION, 1, 0, U64_MAX),
+};
+
+const struct ctlv_schema_tree ctlv_error_info_schema = {
+	.node_schemas = error_info_node_schemas,
+	.node_schemas_count =
+		ARRAY_SIZE(error_info_node_schemas),
+};
+
+static_assert(CTLV_ERROR_INFO_MAX_LEN <= CTLV_MAX_ERROR_LEN);
+
+/* The ops this family declares, in declaration order. */
+const struct ctlv_op_schema ctlv_op_schemas[] = {
+	CTLV_OP_SCHEMA_QUERY(CTLV_OP_FAMILIES_DUMP, CTLV_OP_FD_ACCESS_READ,
+			     CTLV_OP_AVAILABILITY_FIXED, 16, 112, 65536,
+			     CTLV_SCHEMA_TREE(families_dump_request),
+			     CTLV_SCHEMA_TREE(families_dump_reply)),
+	CTLV_OP_SCHEMA_QUERY(CTLV_OP_OPS_DUMP, CTLV_OP_FD_ACCESS_READ, CTLV_OP_AVAILABILITY_FIXED,
+			     16, 56, 65536, CTLV_SCHEMA_TREE(ops_dump_request),
+			     CTLV_SCHEMA_TREE(ops_dump_reply)),
+	CTLV_OP_SCHEMA_QUERY(CTLV_OP_OP_SCHEMA_GET, CTLV_OP_FD_ACCESS_READ,
+			     CTLV_OP_AVAILABILITY_FIXED, 40, 552, 65536,
+			     CTLV_SCHEMA_TREE(op_schema_get_request),
+			     CTLV_SCHEMA_TREE(op_schema_get_reply)),
+	CTLV_OP_SCHEMA_ACTION(CTLV_OP_SUBSCRIPTIONS_ADD, CTLV_OP_FD_ACCESS_READ,
+			      CTLV_OP_AVAILABILITY_FIXED, 6160, 0,
+			      CTLV_SCHEMA_TREE(subscriptions_add_request), CTLV_SCHEMA_TREE_NONE()),
+	CTLV_OP_SCHEMA_ACTION(CTLV_OP_SUBSCRIPTIONS_REMOVE, CTLV_OP_FD_ACCESS_READ,
+			      CTLV_OP_AVAILABILITY_FIXED, 6160, 0,
+			      CTLV_SCHEMA_TREE(subscriptions_remove_request),
+			      CTLV_SCHEMA_TREE_NONE()),
+	CTLV_OP_SCHEMA_QUERY(CTLV_OP_EVENT_QUEUE_GET, CTLV_OP_FD_ACCESS_READ,
+			     CTLV_OP_AVAILABILITY_FIXED, 16, 40, 65536,
+			     CTLV_SCHEMA_TREE(event_queue_get_request),
+			     CTLV_SCHEMA_TREE(event_queue_get_reply)),
+	CTLV_OP_SCHEMA_ACTION(CTLV_OP_EVENT_QUEUE_SET, CTLV_OP_FD_ACCESS_READ,
+			      CTLV_OP_AVAILABILITY_FIXED, 40, 0,
+			      CTLV_SCHEMA_TREE(event_queue_set_request), CTLV_SCHEMA_TREE_NONE()),
+	CTLV_OP_SCHEMA_EVENT(CTLV_OP_OP_CHANGED, 112, CTLV_SCHEMA_TREE(op_changed_reply)),
+	CTLV_OP_SCHEMA_EVENT(CTLV_OP_EVENT_OVERFLOW, 112, CTLV_SCHEMA_TREE(event_overflow_reply)),
+	CTLV_OP_SCHEMA_EVENT(CTLV_OP_DEVICE_REMOVED, 40, CTLV_SCHEMA_TREE(device_removed_reply)),
+};
+
+/* The family ID is its position in the central registry. */
+const struct ctlv_family_schema ctlv_schema = {
+	.name = "ctlv",
+	.family_id = 0,
+	.ops = ctlv_op_schemas,
+	.ops_count = ARRAY_SIZE(ctlv_op_schemas),
+};
+
+/* Maximum uevent cost for this family chain. */
+static_assert(60 <= CTLV_UEVENT_MAX_LEN);
+static_assert(3 <= CTLV_UEVENT_MAX_VARS);
+
+/* Guards for generated maxima. */
+static_assert(65536 <= CTLV_MAX_INLINE_MESSAGE_LEN);
+static_assert(112 <= CTLV_MAX_EVENT_QUEUE_LEN);
+static_assert(2 <= CTLV_MAX_DECLARED_NEST_DEPTH);
+
+/* Local action and query bindings in declaration order. */
+static const struct ctlv_op ctlv_ops[] = {
+	CTLV_OP_QUERY(ctlv_families_dump),
+	CTLV_OP_QUERY(ctlv_ops_dump),
+	CTLV_OP_QUERY(ctlv_op_schema_get),
+	CTLV_OP_ACTION(ctlv_subscriptions_add),
+	CTLV_OP_ACTION(ctlv_subscriptions_remove),
+	CTLV_OP_QUERY(ctlv_event_queue_get),
+	CTLV_OP_ACTION(ctlv_event_queue_set),
+};
+
+/* Root-family descriptor used by the CTLV core. */
+const struct ctlv_family ctlv_family = {
+	.schema = &ctlv_schema,
+	.ops = ctlv_ops,
+	.ops_count = ARRAY_SIZE(ctlv_ops),
+	.pre = ctlv_op_pre,
+	.post = ctlv_op_post,
+	.priv_size = ctlv_priv_size,
+	.init = ctlv_init,
+	.fini = ctlv_fini,
+};
+EXPORT_SYMBOL_NS_GPL(ctlv_family, "CTLV");
diff --git a/drivers/ctlv/device.h b/drivers/ctlv/device.h
new file mode 100644
index 0000000000000..e51366d3fca10
--- /dev/null
+++ b/drivers/ctlv/device.h
@@ -0,0 +1,55 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+#ifndef _CTLV_DEVICE_H
+#define _CTLV_DEVICE_H
+
+#include <linux/cdev.h>
+#include <linux/device.h>
+#include <linux/list.h>
+#include <linux/rwsem.h>
+#include <linux/spinlock.h>
+#include <linux/types.h>
+#include <linux/wait.h>
+
+struct ctlv_event_record;
+struct ctlv_family;
+struct ctlv_family_priv;
+struct ctlv_op_entry;
+
+struct ctlv_device {
+	struct device dev;
+	struct cdev cdev;
+
+	struct rw_semaphore registration_lock;
+	bool registered;
+	const struct ctlv_family *family;
+	struct ctlv_family_priv *privs;
+	u32 privs_count;
+	void *priv_block;
+
+	struct ctlv_op_entry *ops;
+	u32 ops_count;
+
+	/* 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;
+
+	/* Everything about the queues, and nothing family code runs under. */
+	spinlock_t events_lock;
+	struct list_head files;
+	bool dead_announced;
+	wait_queue_head_t event_context_wait;
+	u32 active_event_contexts;
+	bool events_live;
+	u32 events_count;
+	const struct ctlv_op_entry *overflow_op;
+	const struct ctlv_op_entry *removed_op;
+	u32 queue_min;
+	u32 queue_reserved;
+	u32 queue_default;
+};
+
+#endif /* _CTLV_DEVICE_H */
diff --git a/drivers/ctlv/event.c b/drivers/ctlv/event.c
new file mode 100644
index 0000000000000..0f68d33e031c8
--- /dev/null
+++ b/drivers/ctlv/event.c
@@ -0,0 +1,713 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES
+ *
+ * Per-open event queues and loss reporting.
+ */
+
+#include <linux/bitmap.h>
+#include <linux/build_bug.h>
+#include <linux/ctlv.h>
+#include <linux/ctlv_gen.h>
+#include <linux/err.h>
+#include <linux/errno.h>
+#include <linux/list.h>
+#include <linux/minmax.h>
+#include <linux/overflow.h>
+#include <linux/poll.h>
+#include <linux/sizes.h>
+#include <linux/slab.h>
+#include <linux/spinlock.h>
+#include <linux/string.h>
+#include <linux/uaccess.h>
+#include <linux/wait.h>
+
+#include "builder.h"
+#include "device.h"
+#include "event.h"
+#include "internal.h"
+#include "message.h"
+#include "schema.h"
+
+/* Header and root form one naturally aligned copy range. */
+static_assert(offsetof(struct ctlv_event_record, root) ==
+	      offsetof(struct ctlv_event_record, hdr) + sizeof(struct ctlv_event_hdr));
+static_assert(sizeof(struct ctlv_event_hdr) % CTLV_ALIGNTO == 0);
+
+static u32 ctlv_event_len(const struct ctlv_op_entry *op)
+{
+	return op->sizes.event_record_max_len;
+}
+
+int ctlv_event_sizes(struct ctlv_device *ctlvdev)
+{
+	u32 largest = 0;
+	u32 index;
+
+	for (index = 0; index < ctlvdev->ops_count; index++) {
+		const struct ctlv_op_entry *op = &ctlvdev->ops[index];
+
+		if (op->schema->type != CTLV_OP_TYPE_EVENT)
+			continue;
+		largest = max(largest, ctlv_event_len(op));
+		if (op->schema->op_id == CTLV_OP_EVENT_OVERFLOW)
+			ctlvdev->overflow_op = op;
+		else if (op->schema->op_id == CTLV_OP_DEVICE_REMOVED)
+			ctlvdev->removed_op = op;
+	}
+	/* Every chain inherits the root, so every device has both of them. */
+	if (WARN_ON_ONCE(!ctlvdev->overflow_op || !ctlvdev->removed_op))
+		return -EINVAL;
+
+	ctlvdev->queue_reserved =
+		ctlv_event_len(ctlvdev->overflow_op) + ctlv_event_len(ctlvdev->removed_op);
+	ctlvdev->queue_min = largest + ctlvdev->queue_reserved;
+	if (ctlvdev->queue_min > CTLV_MAX_EVENT_QUEUE_LEN)
+		return -EMSGSIZE;
+	ctlvdev->queue_default =
+		clamp(max(SZ_256K, 4 * largest), ctlvdev->queue_min, CTLV_MAX_EVENT_QUEUE_LEN);
+	return 0;
+}
+
+void ctlv_event_device_init(struct ctlv_device *ctlvdev)
+{
+	spin_lock_init(&ctlvdev->events_lock);
+	INIT_LIST_HEAD(&ctlvdev->files);
+	init_waitqueue_head(&ctlvdev->event_context_wait);
+}
+
+void ctlv_event_contexts_start(struct ctlv_device *ctlvdev)
+{
+	guard(spinlock)
+		(&ctlvdev->events_lock);
+	if (WARN_ON_ONCE(ctlvdev->events_live || ctlvdev->active_event_contexts))
+		return;
+	ctlvdev->events_live = true;
+}
+
+void ctlv_event_contexts_stop(struct ctlv_device *ctlvdev)
+{
+	guard(spinlock)
+		(&ctlvdev->events_lock);
+	ctlvdev->events_live = false;
+}
+
+static bool ctlv_event_contexts_idle(struct ctlv_device *ctlvdev)
+{
+	guard(spinlock)
+		(&ctlvdev->events_lock);
+	return !ctlvdev->active_event_contexts;
+}
+
+void ctlv_event_contexts_wait(struct ctlv_device *ctlvdev)
+{
+	wait_event(ctlvdev->event_context_wait, ctlv_event_contexts_idle(ctlvdev));
+}
+
+/* @room bounds storage from the header through the root. */
+static struct ctlv_event_record *ctlv_event_record_alloc(u32 room, gfp_t gfp)
+{
+	struct ctlv_event_record *rec;
+
+	rec = kmalloc(struct_size(rec, root, room - sizeof(rec->hdr)), gfp);
+	if (!rec)
+		return NULL;
+	INIT_LIST_HEAD(&rec->node);
+	rec->len = 0;
+	rec->room = room;
+	rec->reserved = false;
+	return rec;
+}
+
+/* Core events use root schemas and may outlive the device family. */
+static void ctlv_event_record_build(struct ctlv_op_ctx *ctx, struct ctlv_event_record *rec,
+				    const struct ctlv_op_entry *op)
+{
+	ctx->family = &ctlv_family;
+	ctx->op = op;
+	ctlv_message_output_init(&ctx->output, ctx, rec->root, rec->room - sizeof(rec->hdr),
+				 &op->schema->reply);
+	ctlv_message_root(&ctx->output_root, &ctx->output);
+	ctx->deepest = &ctx->output_root;
+}
+
+/* The padding is written rather than left as the allocation found it. */
+static void ctlv_event_record_done(struct ctlv_op_ctx *ctx, struct ctlv_event_record *rec)
+{
+	u32 root_len = ctx->output.root->len;
+
+	rec->len = sizeof(rec->hdr) + CTLV_ALIGN(root_len);
+	rec->hdr.length = rec->len;
+	memset(rec->root + root_len, 0, rec->len - sizeof(rec->hdr) - root_len);
+}
+
+static struct ctlv_event_record *ctlv_event_record_reserve(struct ctlv_device *ctlvdev,
+							   const struct ctlv_op_entry *op)
+{
+	struct ctlv_event_record *rec;
+
+	rec = ctlv_event_record_alloc(ctlv_event_len(op), GFP_KERNEL_ACCOUNT);
+	if (!rec)
+		return NULL;
+	rec->hdr.flags = 0;
+	rec->hdr.op_id = op->schema->op_id;
+	rec->reserved = true;
+	return rec;
+}
+
+int ctlv_event_file_init(struct ctlv_file *cfile)
+{
+	struct ctlv_device *ctlvdev = cfile->ctlvdev;
+	struct ctlv_op_ctx ctx = { .ctlvdev = ctlvdev };
+
+	INIT_LIST_HEAD(&cfile->node);
+	INIT_LIST_HEAD(&cfile->records);
+	init_waitqueue_head(&cfile->readers);
+	mutex_init(&cfile->reading);
+	cfile->queue_len = ctlvdev->queue_default;
+	cfile->queue_used = ctlvdev->queue_reserved;
+
+	cfile->subscribed = bitmap_zalloc(ctlvdev->events_count, GFP_KERNEL_ACCOUNT);
+	cfile->overflow = ctlv_event_record_reserve(ctlvdev, ctlvdev->overflow_op);
+	cfile->removed = ctlv_event_record_reserve(ctlvdev, ctlvdev->removed_op);
+	if (!cfile->subscribed || !cfile->overflow || !cfile->removed) {
+		ctlv_event_file_exit(cfile);
+		return -ENOMEM;
+	}
+	ctlv_event_record_build(&ctx, cfile->removed, ctlvdev->removed_op);
+	ctlv_event_record_done(&ctx, cfile->removed);
+
+	guard(spinlock)
+		(&ctlvdev->events_lock);
+	list_add_tail(&cfile->node, &ctlvdev->files);
+	return 0;
+}
+
+void ctlv_event_file_exit(struct ctlv_file *cfile)
+{
+	struct ctlv_event_record *rec, *next;
+
+	scoped_guard(spinlock, &cfile->ctlvdev->events_lock)
+		list_del_init(&cfile->node);
+
+	/* Unreachable records are ours; reserved records free by identity. */
+	list_for_each_entry_safe(rec, next, &cfile->records, node)
+		if (!rec->reserved)
+			kfree(rec);
+	kfree(cfile->overflow);
+	kfree(cfile->removed);
+	bitmap_free(cfile->subscribed);
+	mutex_destroy(&cfile->reading);
+}
+
+static void ctlv_event_queue_add(struct ctlv_file *cfile, struct ctlv_event_record *rec)
+{
+	list_add_tail(&rec->node, &cfile->records);
+	wake_up_interruptible(&cfile->readers);
+}
+
+static void ctlv_event_queue_link(struct ctlv_file *cfile, struct ctlv_event_record *rec)
+{
+	rec->hdr.sequence = ++cfile->sequence;
+	ctlv_event_queue_add(cfile, rec);
+}
+
+/* One reserved marker aggregates each contiguous drop epoch. */
+static void ctlv_event_queue_dropped(struct ctlv_file *cfile, u64 sequence)
+{
+	if (!cfile->overflowing) {
+		cfile->overflowing = true;
+		cfile->first_dropped = sequence;
+		cfile->dropped = 0;
+		if (!cfile->reading_overflow)
+			ctlv_event_queue_add(cfile, cfile->overflow);
+	}
+	cfile->last_dropped = sequence;
+	cfile->dropped++;
+}
+
+/* Delivered and dropped subscribed events both consume a sequence number. */
+static void ctlv_event_queue_event(struct ctlv_file *cfile, const struct ctlv_op_entry *op,
+				   struct ctlv_event_record *rec)
+{
+	u64 sequence;
+
+	lockdep_assert_held(&cfile->ctlvdev->events_lock);
+	if (!test_bit(op->event_index, cfile->subscribed))
+		return;
+	sequence = ++cfile->sequence;
+	if (cfile->overflowing || !rec || cfile->queue_used + rec->len > cfile->queue_len) {
+		ctlv_event_queue_dropped(cfile, sequence);
+		return;
+	}
+	cfile->queue_used += rec->len;
+	rec->hdr.sequence = sequence;
+	list_move_tail(&rec->node, &cfile->records);
+	wake_up_interruptible(&cfile->readers);
+}
+
+static void ctlv_event_free(struct ctlv_op_ctx *ctx);
+
+struct ctlv_op_ctx *ctlv_event_create(struct ctlv_device *ctlvdev, u64 op_id,
+				      struct ctlv_cursor **reply, gfp_t gfp)
+{
+	const struct ctlv_op_entry *op;
+	struct ctlv_op_ctx *ctx;
+	void *out;
+	u32 room;
+	int ret;
+
+	ctx = kzalloc_obj(*ctx, gfp);
+	if (!ctx)
+		return ERR_PTR(-ENOMEM);
+	scoped_guard(spinlock, &ctlvdev->events_lock) {
+		const struct ctlv_family *family;
+
+		if (!ctlvdev->events_live) {
+			ret = -ENODEV;
+			goto err_free_ctx;
+		}
+		if (WARN_ON_ONCE(ctlvdev->active_event_contexts == U32_MAX)) {
+			ret = -EOVERFLOW;
+			goto err_free_ctx;
+		}
+		/* Admission pins the op until emit or abort. */
+		family = READ_ONCE(ctlvdev->family);
+		if (!family) {
+			ret = -ENODEV;
+			goto err_free_ctx;
+		}
+		get_device(&ctlvdev->dev);
+		ctlvdev->active_event_contexts++;
+		ctx->ctlvdev = ctlvdev;
+		ctx->family = family;
+	}
+
+	op = ctlv_op_find(ctlvdev, op_id);
+	if (WARN_ON_ONCE(!op) || WARN_ON_ONCE(op->schema->type != CTLV_OP_TYPE_EVENT)) {
+		ret = -EINVAL;
+		goto err_put_ctx;
+	}
+	room = ctlv_event_len(op) - sizeof(struct ctlv_event_hdr);
+	out = kmalloc(room, gfp);
+	if (!out) {
+		ret = -ENOMEM;
+		goto err_put_ctx;
+	}
+
+	ctx->gfp = gfp;
+	ctx->op = op;
+	ctlv_message_output_init(&ctx->output, ctx, out, room, &op->schema->reply);
+	ctlv_message_root(&ctx->output_root, &ctx->output);
+	ctx->deepest = &ctx->output_root;
+	*reply = &ctx->output_root;
+	return ctx;
+
+err_put_ctx:
+	ctlv_event_free(ctx);
+	return ERR_PTR(ret);
+err_free_ctx:
+	kfree(ctx);
+	return ERR_PTR(ret);
+}
+EXPORT_SYMBOL_NS_GPL(ctlv_event_create, "CTLV");
+
+static void ctlv_event_free(struct ctlv_op_ctx *ctx)
+{
+	struct ctlv_device *ctlvdev = ctx->ctlvdev;
+	bool wake;
+
+	kfree(ctx->output.root);
+	kfree(ctx);
+
+	scoped_guard(spinlock, &ctlvdev->events_lock) {
+		if (WARN_ON_ONCE(!ctlvdev->active_event_contexts))
+			wake = true;
+		else
+			wake = !--ctlvdev->active_event_contexts;
+	}
+	if (wake)
+		wake_up_all(&ctlvdev->event_context_wait);
+	put_device(&ctlvdev->dev);
+}
+
+/* Reject an incomplete or schema-invalid family event before queueing. */
+static int ctlv_event_finish(struct ctlv_op_ctx *ctx)
+{
+	struct ctlv_error refused = {};
+
+	/* Whatever poisoned it has warned about it already. */
+	if (ctx->output.poison)
+		return ctx->output.poison;
+	if (WARN_ON_ONCE(ctx->deepest != &ctx->output_root)) {
+		/* A cursor of a frame that has returned is not followed. */
+		ctx->deepest = &ctx->output_root;
+		return -EINVAL;
+	}
+	if (WARN_ON_ONCE(ctlv_schema_validate(&ctx->output, &refused)))
+		return -EINVAL;
+	return 0;
+}
+
+/* Allocate subscriber records before taking queue spinlocks. */
+static void ctlv_event_copies(struct ctlv_op_ctx *ctx, u32 len, struct list_head *spare, u32 wanted)
+{
+	const struct ctlv_attr *root = ctx->output.root;
+	struct ctlv_event_record *rec;
+
+	while (wanted--) {
+		rec = ctlv_event_record_alloc(len, ctx->gfp);
+		if (!rec)
+			return;
+		rec->len = len;
+		rec->hdr.length = len;
+		rec->hdr.flags = 0;
+		rec->hdr.op_id = ctx->op->schema->op_id;
+		/* Padded, since what is copied out is the whole record. */
+		memcpy_and_pad(rec->root, len - sizeof(rec->hdr), root, root->len, 0);
+		list_add_tail(&rec->node, spare);
+	}
+}
+
+static void ctlv_event_deliver(struct ctlv_op_ctx *ctx, struct list_head *spare)
+{
+	struct ctlv_device *ctlvdev = ctx->ctlvdev;
+	struct ctlv_event_record *rec;
+	struct ctlv_file *cfile;
+
+	guard(spinlock)
+		(&ctlvdev->events_lock);
+	if (ctlvdev->dead_announced)
+		return;
+	list_for_each_entry(cfile, &ctlvdev->files, node) {
+		rec = list_first_entry_or_null(spare, struct ctlv_event_record, node);
+		ctlv_event_queue_event(cfile, ctx->op, rec);
+	}
+}
+
+int ctlv_event_emit(struct ctlv_op_ctx *ctx)
+{
+	struct ctlv_device *ctlvdev = ctx->ctlvdev;
+	struct ctlv_event_record *rec, *next;
+	struct ctlv_file *cfile;
+	u32 len, wanted = 0;
+	LIST_HEAD(spare);
+	int ret;
+
+	if (WARN_ON_ONCE(ctx->file))
+		return -EINVAL;
+	ret = ctlv_event_finish(ctx);
+	if (ret)
+		goto out_free;
+
+	len = sizeof(struct ctlv_event_hdr) + CTLV_ALIGN(ctx->output.root->len);
+	scoped_guard(spinlock, &ctlvdev->events_lock) {
+		if (ctlvdev->dead_announced)
+			goto out_free;
+		list_for_each_entry(cfile, &ctlvdev->files, node)
+			if (test_bit(ctx->op->event_index, cfile->subscribed))
+				wanted++;
+	}
+	if (wanted) {
+		ctlv_event_copies(ctx, len, &spare, wanted);
+		ctlv_event_deliver(ctx, &spare);
+		list_for_each_entry_safe(rec, next, &spare, node)
+			kfree(rec);
+	}
+
+out_free:
+	ctlv_event_free(ctx);
+	return ret;
+}
+EXPORT_SYMBOL_NS_GPL(ctlv_event_emit, "CTLV");
+
+void ctlv_event_abort(struct ctlv_op_ctx *ctx)
+{
+	if (WARN_ON_ONCE(ctx->file))
+		return;
+	ctlv_event_free(ctx);
+}
+EXPORT_SYMBOL_NS_GPL(ctlv_event_abort, "CTLV");
+
+void ctlv_event_lost(struct ctlv_device *ctlvdev, u64 op_id)
+{
+	const struct ctlv_op_entry *op;
+	struct ctlv_file *cfile;
+
+	guard(spinlock)
+		(&ctlvdev->events_lock);
+	if (!ctlvdev->events_live || ctlvdev->dead_announced)
+		return;
+	op = ctlv_op_find(ctlvdev, op_id);
+	if (WARN_ON_ONCE(!op) || WARN_ON_ONCE(op->schema->type != CTLV_OP_TYPE_EVENT))
+		return;
+	list_for_each_entry(cfile, &ctlvdev->files, node)
+		ctlv_event_queue_event(cfile, op, NULL);
+}
+EXPORT_SYMBOL_NS_GPL(ctlv_event_lost, "CTLV");
+
+void ctlv_event_op_changed(struct ctlv_device *ctlvdev, const struct ctlv_op_entry *op,
+			   bool disabled, u64 generation)
+{
+	struct ctlv_cursor *reply;
+	struct ctlv_op_ctx *ctx;
+
+	ctx = ctlv_op_changed_create(ctlvdev, &reply, GFP_NOWAIT);
+	if (IS_ERR(ctx)) {
+		ctlv_event_lost(ctlvdev, CTLV_OP_OP_CHANGED);
+		return;
+	}
+	ctlv_op_id_put(reply, op->schema->op_id);
+	ctlv_op_disabled_put(reply, disabled);
+	ctlv_op_state_generation_put(reply, generation);
+	ctlv_event_emit(ctx);
+}
+
+void ctlv_event_device_dead(struct ctlv_device *ctlvdev)
+{
+	struct ctlv_file *cfile;
+
+	guard(spinlock)
+		(&ctlvdev->events_lock);
+	if (WARN_ON_ONCE(ctlvdev->dead_announced))
+		return;
+	list_for_each_entry(cfile, &ctlvdev->files, node)
+		ctlv_event_queue_link(cfile, cfile->removed);
+	/* Publish dead only after terminal records are queued. */
+	ctlvdev->dead_announced = true;
+	list_for_each_entry(cfile, &ctlvdev->files, node)
+		wake_up_interruptible(&cfile->readers);
+}
+
+/* Materialize the final loss count when taking the marker. */
+static void ctlv_event_overflow_fill(struct ctlv_file *cfile)
+{
+	struct ctlv_device *ctlvdev = cfile->ctlvdev;
+	struct ctlv_op_ctx ctx = { .ctlvdev = ctlvdev };
+	struct ctlv_cursor *root;
+
+	ctlv_event_record_build(&ctx, cfile->overflow, ctlvdev->overflow_op);
+	cfile->overflow->hdr.sequence = cfile->first_dropped;
+	root = &ctx.output_root;
+	ctlv_event_first_sequence_put(root, cfile->first_dropped);
+	ctlv_event_last_sequence_put(root, cfile->last_dropped);
+	ctlv_event_dropped_count_put(root, cfile->dropped);
+	/* Reserved storage is the most this event can be, so it all fits. */
+	WARN_ON_ONCE(ctx.output.poison);
+	ctlv_event_record_done(&ctx, cfile->overflow);
+
+	cfile->reading_overflow = true;
+	cfile->overflowing = false;
+	cfile->first_reported = cfile->first_dropped;
+	cfile->last_reported = cfile->last_dropped;
+	cfile->dropped_reported = cfile->dropped;
+	cfile->dropped = 0;
+}
+
+static struct ctlv_event_record *ctlv_event_queue_take(struct ctlv_file *cfile)
+{
+	struct ctlv_event_record *rec;
+
+	guard(spinlock)
+		(&cfile->ctlvdev->events_lock);
+	rec = list_first_entry_or_null(&cfile->records, struct ctlv_event_record, node);
+	if (!rec)
+		return NULL;
+	list_del_init(&rec->node);
+	if (rec == cfile->overflow)
+		ctlv_event_overflow_fill(cfile);
+	else if (!rec->reserved)
+		cfile->queue_used -= rec->len;
+	return rec;
+}
+
+/* Restore an undelivered record, merging an overflow marker's epoch. */
+static void ctlv_event_queue_untake(struct ctlv_file *cfile, struct ctlv_event_record *rec)
+{
+	guard(spinlock)
+		(&cfile->ctlvdev->events_lock);
+	if (rec == cfile->overflow) {
+		cfile->reading_overflow = false;
+		cfile->first_dropped = cfile->first_reported;
+		if (!cfile->overflowing)
+			cfile->last_dropped = cfile->last_reported;
+		cfile->dropped += cfile->dropped_reported;
+		cfile->overflowing = true;
+	} else if (!rec->reserved) {
+		cfile->queue_used += rec->len;
+	}
+	list_add(&rec->node, &cfile->records);
+}
+
+/* Requeue a marker if another loss epoch opened while it was out. */
+static void ctlv_event_queue_consumed(struct ctlv_file *cfile, struct ctlv_event_record *rec)
+{
+	if (rec == cfile->overflow) {
+		guard(spinlock)
+			(&cfile->ctlvdev->events_lock);
+		cfile->reading_overflow = false;
+		if (cfile->overflowing)
+			ctlv_event_queue_add(cfile, rec);
+		return;
+	}
+	if (!rec->reserved)
+		kfree(rec);
+}
+
+static bool ctlv_event_waiting(struct ctlv_file *cfile)
+{
+	struct ctlv_device *ctlvdev = cfile->ctlvdev;
+
+	guard(spinlock)
+		(&ctlvdev->events_lock);
+	return !list_empty(&cfile->records) || ctlvdev->dead_announced;
+}
+
+ssize_t ctlv_event_file_read(struct ctlv_file *cfile, char __user *buf, size_t len, bool blocking)
+{
+	struct ctlv_device *ctlvdev = cfile->ctlvdev;
+	struct ctlv_event_record *rec;
+	ssize_t ret;
+
+	/* dup() and SCM_RIGHTS share one serialized queue. */
+	if (mutex_lock_interruptible(&cfile->reading))
+		return -ERESTARTSYS;
+
+	while (!(rec = ctlv_event_queue_take(cfile))) {
+		/* Drained, and the device is gone. */
+		if (READ_ONCE(ctlvdev->dead_announced)) {
+			ret = -ENODEV;
+			goto out_unlock;
+		}
+		if (!blocking) {
+			ret = -EAGAIN;
+			goto out_unlock;
+		}
+		ret = wait_event_interruptible(cfile->readers, ctlv_event_waiting(cfile));
+		if (ret) {
+			ret = -ERESTARTSYS;
+			goto out_unlock;
+		}
+	}
+
+	if (rec->len > len) {
+		ctlv_event_queue_untake(cfile, rec);
+		ret = -EMSGSIZE;
+		goto out_unlock;
+	}
+	if (copy_to_user(buf, &rec->hdr, rec->len)) {
+		ctlv_event_queue_untake(cfile, rec);
+		ret = -EFAULT;
+		goto out_unlock;
+	}
+	ret = rec->len;
+	ctlv_event_queue_consumed(cfile, rec);
+
+out_unlock:
+	mutex_unlock(&cfile->reading);
+	return ret;
+}
+
+__poll_t ctlv_event_file_poll(struct ctlv_file *cfile, struct file *filp,
+			      struct poll_table_struct *wait)
+{
+	struct ctlv_device *ctlvdev = cfile->ctlvdev;
+	__poll_t mask = 0;
+
+	poll_wait(filp, &cfile->readers, wait);
+
+	guard(spinlock)
+		(&ctlvdev->events_lock);
+	if (!list_empty(&cfile->records))
+		mask |= EPOLLIN | EPOLLRDNORM;
+	/* Which a reader sees beside what it has not drained yet. */
+	if (ctlvdev->dead_announced)
+		mask |= EPOLLHUP;
+	return mask;
+}
+
+/* Validate every ID before changing any subscription. */
+static const struct ctlv_op_entry *ctlv_event_subscription_find(struct ctlv_device *ctlvdev,
+								u64 op_id)
+{
+	const struct ctlv_op_entry *op = ctlv_op_find(ctlvdev, op_id);
+
+	return op && op->schema->type == CTLV_OP_TYPE_EVENT ? op : NULL;
+}
+
+static int ctlv_event_subscriptions_set(struct ctlv_op_ctx *ctx, const struct ctlv_cursor *request,
+					struct ctlv_input_ref ref, bool subscribe)
+{
+	struct ctlv_device *ctlvdev = ctx->ctlvdev;
+	struct ctlv_cursor attr;
+
+	for (ctlv_input_attr(&attr, request, ref); ctlv_attr_ok(&attr); ctlv_attr_next(&attr)) {
+		u64 op_id = ctlv_attr_u64(&attr);
+
+		if (!ctlv_event_subscription_find(ctlvdev, op_id))
+			return ctlv_op_errorf(ctx, -EOPNOTSUPP,
+					      "op %#llx is not an event this device emits",
+					      (unsigned long long)op_id);
+	}
+
+	guard(spinlock)
+		(&ctlvdev->events_lock);
+	for (ctlv_input_attr(&attr, request, ref); ctlv_attr_ok(&attr); ctlv_attr_next(&attr)) {
+		u64 op_id = ctlv_attr_u64(&attr);
+		const struct ctlv_op_entry *op = ctlv_event_subscription_find(ctlvdev, op_id);
+
+		if (subscribe)
+			set_bit(op->event_index, ctx->file->subscribed);
+		else
+			clear_bit(op->event_index, ctx->file->subscribed);
+	}
+	return 0;
+}
+
+int ctlv_subscriptions_add_action(void *priv, struct ctlv_op_ctx *ctx,
+				  const struct ctlv_cursor *request, struct ctlv_cursor *reply)
+{
+	return ctlv_event_subscriptions_set(ctx, request, ctlv_subscriptions_add_event_op_id_ref(),
+					    true);
+}
+
+int ctlv_subscriptions_remove_action(void *priv, struct ctlv_op_ctx *ctx,
+				     const struct ctlv_cursor *request, struct ctlv_cursor *reply)
+{
+	return ctlv_event_subscriptions_set(ctx, request,
+					    ctlv_subscriptions_remove_event_op_id_ref(), false);
+}
+
+int ctlv_event_queue_get_query(void *priv, struct ctlv_op_ctx *ctx,
+			       const struct ctlv_cursor *request, struct ctlv_cursor *reply)
+{
+	struct ctlv_file *cfile = ctx->file;
+
+	scoped_guard(spinlock, &ctx->ctlvdev->events_lock) {
+		ctlv_event_queue_len_put(reply, cfile->queue_len);
+		ctlv_event_queue_used_put(reply, cfile->queue_used);
+	}
+	/* One state, whole, so there is never a second fragment of it. */
+	return ctlv_op_query_done(ctx, 0);
+}
+
+/* Resizing never discards queued records or reserved capacity. */
+int ctlv_event_queue_set_action(void *priv, struct ctlv_op_ctx *ctx,
+				const struct ctlv_cursor *request, struct ctlv_cursor *reply)
+{
+	struct ctlv_device *ctlvdev = ctx->ctlvdev;
+	u64 len = ctlv_event_queue_set_event_queue_len_get(request);
+
+	if (len < ctlvdev->queue_min || len > CTLV_MAX_EVENT_QUEUE_LEN)
+		return ctlv_op_errorf(ctx, -EINVAL, "event queue length %llu is outside %u..%u",
+				      (unsigned long long)len, ctlvdev->queue_min,
+				      CTLV_MAX_EVENT_QUEUE_LEN);
+
+	guard(spinlock)
+		(&ctlvdev->events_lock);
+	if (len < ctx->file->queue_used)
+		return ctlv_op_error(ctx, -EBUSY,
+				     "event queue contains more data than the requested limit");
+	ctx->file->queue_len = len;
+	return 0;
+}
diff --git a/drivers/ctlv/event.h b/drivers/ctlv/event.h
new file mode 100644
index 0000000000000..80898c7700347
--- /dev/null
+++ b/drivers/ctlv/event.h
@@ -0,0 +1,69 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+#ifndef _CTLV_EVENT_H
+#define _CTLV_EVENT_H
+
+#include <linux/gfp_types.h>
+#include <linux/list.h>
+#include <linux/mutex.h>
+#include <linux/poll.h>
+#include <linux/types.h>
+#include <linux/wait.h>
+
+#include <uapi/linux/ctlv.h>
+
+struct ctlv_device;
+struct ctlv_op_entry;
+struct file;
+struct poll_table_struct;
+
+struct ctlv_event_record {
+	struct list_head node;
+	u32 len;
+	u32 room;
+	bool reserved;
+	struct ctlv_event_hdr hdr;
+	u8 root[] __aligned(8);
+};
+
+struct ctlv_file {
+	struct ctlv_device *ctlvdev;
+	struct list_head node;
+
+	struct list_head records;
+	u32 queue_len;
+	u32 queue_used;
+	u64 sequence;
+	unsigned long *subscribed;
+	struct ctlv_event_record *overflow;
+	struct ctlv_event_record *removed;
+	bool overflowing;
+	u64 first_dropped;
+	u64 last_dropped;
+	u64 dropped;
+	bool reading_overflow;
+	u64 first_reported;
+	u64 last_reported;
+	u64 dropped_reported;
+
+	wait_queue_head_t readers;
+	/* One reader of this description at a time, however many hold it. */
+	struct mutex reading;
+};
+
+int ctlv_event_sizes(struct ctlv_device *ctlvdev);
+void ctlv_event_device_init(struct ctlv_device *ctlvdev);
+void ctlv_event_contexts_start(struct ctlv_device *ctlvdev);
+void ctlv_event_contexts_stop(struct ctlv_device *ctlvdev);
+void ctlv_event_contexts_wait(struct ctlv_device *ctlvdev);
+void ctlv_event_device_dead(struct ctlv_device *ctlvdev);
+int ctlv_event_file_init(struct ctlv_file *cfile);
+void ctlv_event_file_exit(struct ctlv_file *cfile);
+ssize_t ctlv_event_file_read(struct ctlv_file *cfile, char __user *buf,
+			     size_t len, bool blocking);
+__poll_t ctlv_event_file_poll(struct ctlv_file *cfile, struct file *filp,
+			      struct poll_table_struct *wait);
+void ctlv_event_op_changed(struct ctlv_device *ctlvdev,
+			   const struct ctlv_op_entry *op, bool disabled,
+			   u64 generation);
+
+#endif /* _CTLV_EVENT_H */
diff --git a/drivers/ctlv/internal.h b/drivers/ctlv/internal.h
new file mode 100644
index 0000000000000..7e6ec9d1f73e1
--- /dev/null
+++ b/drivers/ctlv/internal.h
@@ -0,0 +1,81 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES
+ *
+ * CTLV core internals.
+ */
+#ifndef _CTLV_INTERNAL_H
+#define _CTLV_INTERNAL_H
+
+#include <linux/ctlv_family.h>
+#include <linux/list.h>
+#include <linux/types.h>
+
+#include <uapi/linux/ctlv.h>
+
+#include "message.h"
+
+struct task_struct;
+struct ctlv_file;
+
+#define CTLV_ERROR_MESSAGE_LEN 256
+
+/* An op that is always enabled has no per-device availability state. */
+#define CTLV_OP_STATE_NONE U32_MAX
+
+struct ctlv_op_entry {
+	const struct ctlv_op_schema *schema;
+	const struct ctlv_op *binding;
+	void *priv;
+	struct ctlv_op_sizes sizes;
+	u32 state_index;
+	bool absent;
+	u32 event_index;
+};
+
+struct ctlv_error {
+	u32 reason;
+	char message[CTLV_ERROR_MESSAGE_LEN];
+	u32 bad_attr_offset;
+	u32 nest_offset;
+	u64 missing_attr_id;
+	u64 expected_generation;
+	u64 current_generation;
+};
+
+struct ctlv_query_fragment {
+	u64 generation;
+	u64 cursor;
+	u64 reported;
+	u64 next_cursor;
+	bool progress;
+	bool answered;
+	int result;
+};
+
+struct ctlv_op_ctx {
+	struct ctlv_device *ctlvdev;
+	const struct ctlv_family *family;
+	struct ctlv_file *file;
+	/* Compared against current and never followed: identity, not a hold. */
+	const struct task_struct *submitter;
+	gfp_t gfp;
+	const struct ctlv_op_entry *op;
+
+	struct ctlv_msg request;
+	struct ctlv_cursor request_root;
+
+	struct ctlv_msg output;
+	struct ctlv_cursor output_root;
+	struct ctlv_cursor *deepest;
+
+	struct ctlv_query_fragment frag;
+	struct list_head blobs;
+	bool blobs_live;
+	int blob_error;
+	struct ctlv_error error;
+};
+
+struct ctlv_op_entry *ctlv_op_find(struct ctlv_device *ctlvdev, u64 op_id);
+
+#endif /* _CTLV_INTERNAL_H */
diff --git a/drivers/ctlv/introspection.c b/drivers/ctlv/introspection.c
new file mode 100644
index 0000000000000..7460dfa6d6618
--- /dev/null
+++ b/drivers/ctlv/introspection.c
@@ -0,0 +1,512 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES
+ *
+ * Root-family discovery queries and their fragmentation.
+ */
+
+#include <linux/bitmap.h>
+#include <linux/bits.h>
+#include <linux/cleanup.h>
+#include <linux/ctlv.h>
+#include <linux/ctlv_gen.h>
+#include <linux/errno.h>
+#include <linux/slab.h>
+#include <linux/spinlock.h>
+#include <linux/types.h>
+
+#include "device.h"
+#include "internal.h"
+#include "schema.h"
+
+/* A cursor packs the record and member where fragmentation resumes. */
+#define CTLV_INTROSPECTION_MEMBER_SHIFT 48
+#define CTLV_INTROSPECTION_RECORD_MASK GENMASK_ULL(CTLV_INTROSPECTION_MEMBER_SHIFT - 1, 0)
+
+struct ctlv_introspection_dump_position {
+	u64 record;
+	u32 member;
+};
+
+static void ctlv_introspection_dump_resume(struct ctlv_introspection_dump_position *pos, u64 cursor)
+{
+	pos->record = cursor & CTLV_INTROSPECTION_RECORD_MASK;
+	pos->member = cursor >> CTLV_INTROSPECTION_MEMBER_SHIFT;
+}
+
+static u64 ctlv_introspection_dump_cursor(const struct ctlv_introspection_dump_position *pos)
+{
+	return pos->record | (u64)pos->member << CTLV_INTROSPECTION_MEMBER_SHIFT;
+}
+
+/* The immutable root-first chain always has generation zero. */
+static bool ctlv_introspection_family_record(struct ctlv_cursor *reply, struct ctlv_cursor *entry,
+					     const struct ctlv_family *family,
+					     struct ctlv_introspection_dump_position *pos)
+{
+	const struct ctlv_family_schema *schema = family->schema;
+
+	if (!ctlv_family_entry_start(reply, entry))
+		return false;
+	if (pos->member == 0) {
+		if (!ctlv_family_id_put(entry, schema->family_id))
+			return false;
+		pos->member = 1;
+	}
+	if (pos->member == 1) {
+		if (!ctlv_family_name_put(entry, schema->name))
+			return false;
+		pos->member = 2;
+	}
+	ctlv_nest_end(entry);
+	pos->member = 0;
+	return true;
+}
+
+int ctlv_families_dump_query(void *priv, struct ctlv_op_ctx *ctx, const struct ctlv_cursor *request,
+			     struct ctlv_cursor *reply)
+{
+	const struct ctlv_family *family = ctx->family;
+	u32 levels = ctlv_family_levels(family);
+	struct ctlv_cursor entry;
+	struct ctlv_introspection_dump_position pos;
+
+	ctlv_introspection_dump_resume(&pos, ctlv_op_query_cursor(ctx));
+	for (; pos.record < levels; pos.record++) {
+		const struct ctlv_family *ancestor =
+			ctlv_family_ancestor(family, levels - 1 - pos.record);
+
+		if (!ctlv_introspection_family_record(reply, &entry, ancestor, &pos))
+			return ctlv_op_query_more(ctx, 0, ctlv_introspection_dump_cursor(&pos));
+	}
+	return ctlv_op_query_done(ctx, 0);
+}
+
+/* Snapshot published-op state and generation once per fragment. */
+struct ctlv_op_snapshot {
+	unsigned long *disabled;
+	u64 generation;
+};
+
+static int ctlv_introspection_snapshot_take(struct ctlv_device *ctlvdev,
+					    struct ctlv_op_snapshot *snapshot)
+{
+	if (ctlvdev->dynamic_ops_count) {
+		snapshot->disabled = bitmap_zalloc(ctlvdev->dynamic_ops_count, GFP_KERNEL);
+		if (!snapshot->disabled)
+			return -ENOMEM;
+	}
+	guard(spinlock)
+		(&ctlvdev->transition_lock);
+	snapshot->generation = ctlvdev->state_generation;
+	if (snapshot->disabled)
+		bitmap_copy(snapshot->disabled, ctlvdev->disabled, ctlvdev->dynamic_ops_count);
+	return 0;
+}
+
+static bool ctlv_introspection_op_disabled(const struct ctlv_op_snapshot *snapshot,
+					   const struct ctlv_op_entry *op)
+{
+	if (op->state_index == CTLV_OP_STATE_NONE)
+		return false;
+	return test_bit(op->state_index, snapshot->disabled);
+}
+
+/* Report effective lengths, including descendant fills. */
+enum ctlv_introspection_op_field {
+	CTLV_INTROSPECTION_OP_FIELD_ID,
+	CTLV_INTROSPECTION_OP_FIELD_TYPE,
+	CTLV_INTROSPECTION_OP_FIELD_AVAILABILITY,
+	CTLV_INTROSPECTION_OP_FIELD_DISABLED,
+	CTLV_INTROSPECTION_OP_FIELD_REQUEST_MAX_LEN,
+	CTLV_INTROSPECTION_OP_FIELD_ACTION_REPLY_MAX_LEN,
+	CTLV_INTROSPECTION_OP_FIELD_QUERY_REPLY_MIN_LEN,
+	CTLV_INTROSPECTION_OP_FIELD_QUERY_REPLY_SUGGESTED_LEN,
+	CTLV_INTROSPECTION_OP_FIELD_EVENT_RECORD_MAX_LEN,
+	CTLV_INTROSPECTION_OP_FIELD_FD_ACCESS,
+	CTLV_INTROSPECTION_OP_FIELD_END,
+};
+
+static bool ctlv_introspection_op_field_put(struct ctlv_cursor *entry,
+					    const struct ctlv_op_snapshot *snapshot,
+					    const struct ctlv_op_entry *op, u32 member)
+{
+	const struct ctlv_op_sizes *sizes = &op->sizes;
+
+	switch (member) {
+	case CTLV_INTROSPECTION_OP_FIELD_ID:
+		return ctlv_op_id_put(entry, op->schema->op_id);
+	case CTLV_INTROSPECTION_OP_FIELD_TYPE:
+		return ctlv_op_type_put(entry, op->schema->type);
+	case CTLV_INTROSPECTION_OP_FIELD_AVAILABILITY:
+		return ctlv_op_availability_put(entry, op->schema->availability);
+	case CTLV_INTROSPECTION_OP_FIELD_DISABLED:
+		return ctlv_op_disabled_put(entry, ctlv_introspection_op_disabled(snapshot, op));
+	case CTLV_INTROSPECTION_OP_FIELD_REQUEST_MAX_LEN:
+		return ctlv_op_request_max_len_put(entry, sizes->request_max_len);
+	case CTLV_INTROSPECTION_OP_FIELD_ACTION_REPLY_MAX_LEN:
+		/* Zero is a reply that acknowledges and no more. */
+		return ctlv_op_action_reply_max_len_put(entry, sizes->action_reply_max_len);
+	case CTLV_INTROSPECTION_OP_FIELD_QUERY_REPLY_MIN_LEN:
+		return ctlv_op_query_reply_min_len_put(entry, sizes->query_reply_min_len);
+	case CTLV_INTROSPECTION_OP_FIELD_QUERY_REPLY_SUGGESTED_LEN:
+		return ctlv_op_query_reply_suggested_len_put(entry,
+							     sizes->query_reply_suggested_len);
+	case CTLV_INTROSPECTION_OP_FIELD_FD_ACCESS:
+		return ctlv_op_fd_access_put(entry, op->schema->fd_access);
+	default:
+		return ctlv_op_event_record_max_len_put(entry, sizes->event_record_max_len);
+	}
+}
+
+static bool ctlv_introspection_op_field_applies(const struct ctlv_op_entry *op, u32 member)
+{
+	switch (member) {
+	case CTLV_INTROSPECTION_OP_FIELD_ID:
+	case CTLV_INTROSPECTION_OP_FIELD_TYPE:
+		return true;
+	case CTLV_INTROSPECTION_OP_FIELD_AVAILABILITY:
+	case CTLV_INTROSPECTION_OP_FIELD_DISABLED:
+	case CTLV_INTROSPECTION_OP_FIELD_REQUEST_MAX_LEN:
+	case CTLV_INTROSPECTION_OP_FIELD_FD_ACCESS:
+		return op->schema->type != CTLV_OP_TYPE_EVENT;
+	case CTLV_INTROSPECTION_OP_FIELD_ACTION_REPLY_MAX_LEN:
+		return op->schema->type == CTLV_OP_TYPE_ACTION;
+	case CTLV_INTROSPECTION_OP_FIELD_EVENT_RECORD_MAX_LEN:
+		return op->schema->type == CTLV_OP_TYPE_EVENT;
+	default:
+		return op->schema->type == CTLV_OP_TYPE_QUERY;
+	}
+}
+
+static bool ctlv_introspection_op_record(struct ctlv_cursor *reply, struct ctlv_cursor *entry,
+					 const struct ctlv_op_snapshot *snapshot,
+					 const struct ctlv_op_entry *op,
+					 struct ctlv_introspection_dump_position *pos)
+{
+	if (!ctlv_op_entry_start(reply, entry))
+		return false;
+	for (; pos->member < CTLV_INTROSPECTION_OP_FIELD_END; pos->member++) {
+		if (!ctlv_introspection_op_field_applies(op, pos->member))
+			continue;
+		if (!ctlv_introspection_op_field_put(entry, snapshot, op, pos->member))
+			return false;
+	}
+	ctlv_nest_end(entry);
+	pos->member = 0;
+	return true;
+}
+
+int ctlv_ops_dump_query(void *priv, struct ctlv_op_ctx *ctx, const struct ctlv_cursor *request,
+			struct ctlv_cursor *reply)
+{
+	struct ctlv_device *ctlvdev = ctx->ctlvdev;
+	struct ctlv_op_snapshot snapshot = {};
+	struct ctlv_cursor entry;
+	struct ctlv_introspection_dump_position pos;
+	int ret;
+
+	ret = ctlv_introspection_snapshot_take(ctlvdev, &snapshot);
+	if (ret)
+		return ret;
+	unsigned long *disabled __free(bitmap) = snapshot.disabled;
+
+	/* The published index is immutable, so a cursor into it holds. */
+	ctlv_introspection_dump_resume(&pos, ctlv_op_query_cursor(ctx));
+	for (; pos.record < ctlvdev->ops_count; pos.record++)
+		if (!ctlv_introspection_op_record(reply, &entry, &snapshot,
+						  &ctlvdev->ops[pos.record], &pos))
+			return ctlv_op_query_more(ctx, snapshot.generation,
+						  ctlv_introspection_dump_cursor(&pos));
+	return ctlv_op_query_done(ctx, snapshot.generation);
+}
+
+/* A leaf-count cursor permits a fragment boundary at any tree depth. */
+
+/* One nest of the description: the placement of one node of the schema. */
+struct ctlv_introspection_frame {
+	struct ctlv_cursor nest;
+	u64 attr_id;
+	bool open;
+	/* Which node this stands for, so that a re-entry can be measured. */
+	const struct ctlv_schema_tree *tree;
+	u32 node;
+};
+
+/* The frames outlive the walk, a fragment's open nests having to stay alive. */
+struct ctlv_introspection_walk {
+	const struct ctlv_family *family;
+	struct ctlv_cursor *root;
+	struct ctlv_introspection_frame *frames;
+	u64 ordinal;
+	u64 resume;
+	int error;
+};
+
+/* One member of one node, which is every leaf this reply has. */
+struct ctlv_introspection_field {
+	u64 attr_id;
+	u8 kind;
+	u64 value;
+};
+
+/* Three every node has, the widest bounds, a unit, a scale, a re-entry. */
+#define CTLV_INTROSPECTION_MAX_FIELDS 10
+
+struct ctlv_introspection_fields {
+	struct ctlv_introspection_field fields[CTLV_INTROSPECTION_MAX_FIELDS];
+	u32 fields_count;
+};
+
+static void ctlv_introspection_field(struct ctlv_introspection_fields *fields, u64 attr_id, u8 kind,
+				     u64 value)
+{
+	if (WARN_ON_ONCE(fields->fields_count == CTLV_INTROSPECTION_MAX_FIELDS))
+		return;
+	fields->fields[fields->fields_count++] = (struct ctlv_introspection_field){
+		.attr_id = attr_id,
+		.kind = kind,
+		.value = value,
+	};
+}
+
+static void ctlv_introspection_uint(struct ctlv_introspection_fields *fields, u64 attr_id,
+				    u64 value)
+{
+	ctlv_introspection_field(fields, attr_id, CTLV_SCHEMA_UINT, value);
+}
+
+/* Emit only constraints for this node's payload kind. */
+static void ctlv_introspection_node_fields(struct ctlv_introspection_fields *fields,
+					   const struct ctlv_node_schema *node, u32 reenters)
+{
+	ctlv_introspection_uint(fields, CTLV_ATTR_SCHEMA_ATTR_ID, node->attr_id);
+	ctlv_introspection_uint(fields, CTLV_ATTR_SCHEMA_KIND, node->kind);
+	ctlv_introspection_uint(fields, CTLV_ATTR_SCHEMA_MAX_OCCURRENCES, node->max_occurrences);
+
+	switch (node->kind) {
+	case CTLV_SCHEMA_UINT:
+	case CTLV_SCHEMA_SINT:
+	case CTLV_SCHEMA_ENUM:
+		ctlv_introspection_uint(fields, CTLV_ATTR_SCHEMA_MIN, node->range.min);
+		ctlv_introspection_uint(fields, CTLV_ATTR_SCHEMA_MAX, node->range.max);
+		break;
+	case CTLV_SCHEMA_FLAGS:
+		ctlv_introspection_uint(fields, CTLV_ATTR_SCHEMA_FLAGS_MASK, node->flags_mask);
+		break;
+	case CTLV_SCHEMA_STRING:
+	case CTLV_SCHEMA_BINARY:
+		ctlv_introspection_uint(fields, CTLV_ATTR_SCHEMA_MIN_LENGTH, node->length.min_len);
+		ctlv_introspection_uint(fields, CTLV_ATTR_SCHEMA_MAX_LENGTH, node->length.max_len);
+		break;
+	case CTLV_SCHEMA_BLOB:
+		ctlv_introspection_field(fields, CTLV_ATTR_SCHEMA_BLOB_DIRECTION, CTLV_SCHEMA_ENUM,
+					 node->blob.direction);
+		ctlv_introspection_uint(fields, CTLV_ATTR_SCHEMA_BLOB_BACKINGS,
+					node->blob.backings);
+		ctlv_introspection_uint(fields, CTLV_ATTR_SCHEMA_BLOB_MAX_LENGTH,
+					node->blob.max_len);
+		ctlv_introspection_uint(fields, CTLV_ATTR_SCHEMA_BLOB_ALIGNMENT,
+					node->blob.alignment);
+		break;
+	default:
+		break;
+	}
+
+	if (node->unit != CTLV_UNIT_NONE) {
+		ctlv_introspection_uint(fields, CTLV_ATTR_SCHEMA_UNIT, node->unit);
+		ctlv_introspection_field(fields, CTLV_ATTR_SCHEMA_SCALE, CTLV_SCHEMA_SINT,
+					 node->scale);
+	}
+	if (reenters)
+		ctlv_introspection_uint(fields, CTLV_ATTR_SCHEMA_REENTERS, reenters);
+}
+
+/* A nest is opened by the first thing written inside it. */
+static bool ctlv_introspection_open(struct ctlv_introspection_walk *walk, u32 depth)
+{
+	struct ctlv_introspection_frame *frame = &walk->frames[depth];
+	struct ctlv_cursor *up = walk->root;
+
+	if (frame->open)
+		return true;
+	if (depth) {
+		if (!ctlv_introspection_open(walk, depth - 1))
+			return false;
+		up = &walk->frames[depth - 1].nest;
+	}
+	if (!ctlv_nest_start(up, &frame->nest, frame->attr_id, CTLV_SCHEMA_NEST))
+		return false;
+	frame->open = true;
+	return true;
+}
+
+/* Skipped leaves advance the ordinal; a failed write remains the resume point. */
+static bool ctlv_introspection_put(struct ctlv_introspection_walk *walk, u32 depth,
+				   const struct ctlv_introspection_field *field)
+{
+	struct ctlv_cursor *nest = &walk->frames[depth].nest;
+	bool ok;
+
+	if (walk->ordinal < walk->resume) {
+		walk->ordinal++;
+		return true;
+	}
+	if (!ctlv_introspection_open(walk, depth))
+		return false;
+	if (field->kind == CTLV_SCHEMA_SINT)
+		ok = ctlv_put_s64(nest, field->attr_id, field->kind, field->value);
+	else
+		ok = ctlv_put_u64(nest, field->attr_id, field->kind, field->value);
+	if (!ok)
+		return false;
+	walk->ordinal++;
+	return true;
+}
+
+/* Re-entry targets an ancestor with the same child range. */
+static u32 ctlv_introspection_reenters(struct ctlv_introspection_walk *walk, u32 depth,
+				       const struct ctlv_schema_tree *tree,
+				       const struct ctlv_node_schema *node)
+{
+	u32 levels;
+
+	for (levels = 1; levels <= depth; levels++) {
+		const struct ctlv_introspection_frame *up = &walk->frames[depth - levels];
+
+		if (up->tree == tree &&
+		    tree->node_schemas[up->node].first_child == node->first_child)
+			return levels;
+	}
+	/* A back edge to nothing is metadata this core cannot describe. */
+	WARN_ON_ONCE(1);
+	walk->error = -EINVAL;
+	return 0;
+}
+
+static bool ctlv_introspection_node(struct ctlv_introspection_walk *walk, u32 depth,
+				    const struct ctlv_schema_tree *tree, u32 index);
+
+/* Filled stub members inherit the stub placement's optionality. */
+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_NEST_DEPTH)) {
+		/* Deeper than a specification may declare, so unreachable. */
+		walk->error = -EINVAL;
+		return false;
+	}
+	for (i = 0; i < node->children_count; i++) {
+		u32 child = node->first_child + i;
+		bool required = !force_optional && i < node->required_children_count;
+
+		walk->frames[depth + 1] = (struct ctlv_introspection_frame){
+			.attr_id = required ? CTLV_ATTR_SCHEMA_ATTRS :
+					      CTLV_ATTR_SCHEMA_OPTIONAL_ATTRS,
+			.tree = tree,
+			.node = child,
+		};
+		if (!ctlv_introspection_node(walk, depth + 1, tree, child))
+			return false;
+	}
+	for (i = 0; i < tree->stub_schemas_count; i++) {
+		const struct ctlv_stub_schema *stub_schema = &tree->stub_schemas[i];
+		const struct ctlv_stub_fill_schema *fill_schema;
+
+		if (stub_schema->node != index)
+			continue;
+		fill_schema =
+			ctlv_schema_fill(walk->family, stub_schema->family_id, stub_schema->set_id);
+		/* Nothing of this chain filled it, so it contributes none. */
+		if (!fill_schema)
+			continue;
+		/* A fill schema's root is the stub, its children the members. */
+		if (!ctlv_introspection_children(walk, depth, &fill_schema->members, 0,
+						 force_optional || stub_schema->optional))
+			return false;
+	}
+	return true;
+}
+
+/* One node, into the nest 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];
+	struct ctlv_introspection_fields fields = {};
+	u32 reenters = 0;
+	u32 i;
+
+	if (node->reenters) {
+		reenters = ctlv_introspection_reenters(walk, depth, tree, node);
+		if (!reenters)
+			return false;
+	}
+	ctlv_introspection_node_fields(&fields, node, reenters);
+	for (i = 0; i < fields.fields_count; i++)
+		if (!ctlv_introspection_put(walk, depth, &fields.fields[i]))
+			return false;
+	/*
+	 * A node that re-enters a level says so instead of listing that level's
+	 * members again, which is what makes an unbounded nesting describable.
+	 */
+	if (!node->reenters && !ctlv_introspection_children(walk, depth, tree, index, false))
+		return false;
+	if (walk->frames[depth].open)
+		ctlv_nest_end(&walk->frames[depth].nest);
+	return true;
+}
+
+/* One of the two messages of an op, the root of it being a node like any. */
+static bool ctlv_introspection_message(struct ctlv_introspection_walk *walk, u64 attr_id,
+				       const struct ctlv_schema_tree *tree)
+{
+	/* An op without such a message has nothing to describe. */
+	if (!tree->node_schemas)
+		return true;
+	walk->frames[0] = (struct ctlv_introspection_frame){
+		.attr_id = attr_id,
+		.tree = tree,
+	};
+	return ctlv_introspection_node(walk, 0, tree, 0);
+}
+
+int ctlv_op_schema_get_query(void *priv, struct ctlv_op_ctx *ctx, const struct ctlv_cursor *request,
+			     struct ctlv_cursor *reply)
+{
+	struct ctlv_introspection_walk walk = {
+		.family = ctx->family,
+		.root = reply,
+		.resume = ctlv_op_query_cursor(ctx),
+	};
+	const struct ctlv_op_entry *op;
+
+	/* Describe published ops regardless of current dynamic state. */
+	op = ctlv_op_find(ctx->ctlvdev, ctlv_op_schema_get_op_id_get(request));
+	if (!op)
+		return -EOPNOTSUPP;
+
+	/*
+	 * One frame per level the reply may nest, 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_NEST_DEPTH, sizeof(*frames), GFP_KERNEL);
+
+	if (!frames)
+		return -ENOMEM;
+	walk.frames = frames;
+
+	if (!ctlv_introspection_message(&walk, CTLV_ATTR_SCHEMA_REQUEST, &op->schema->request) ||
+	    !ctlv_introspection_message(&walk, CTLV_ATTR_SCHEMA_REPLY, &op->schema->reply)) {
+		if (walk.error)
+			return walk.error;
+		/* A schema is immutable, so there is nothing to be stale. */
+		return ctlv_op_query_more(ctx, 0, walk.ordinal);
+	}
+	return ctlv_op_query_done(ctx, 0);
+}
diff --git a/drivers/ctlv/message.c b/drivers/ctlv/message.c
new file mode 100644
index 0000000000000..7e5742ba8f708
--- /dev/null
+++ b/drivers/ctlv/message.c
@@ -0,0 +1,403 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES
+ *
+ * Message walking, indexing, and generated-accessor primitives.
+ */
+#include <linux/align.h>
+#include <linux/bits.h>
+#include <linux/bug.h>
+#include <linux/ctlv.h>
+#include <linux/err.h>
+#include <linux/errno.h>
+#include <linux/export.h>
+#include <linux/string.h>
+#include <linux/types.h>
+
+#include <uapi/linux/ctlv.h>
+#include <uapi/linux/ctlv_gen.h>
+
+#include "internal.h"
+#include "message.h"
+
+enum ctlv_message_step ctlv_message_next(const struct ctlv_attr *nest,
+					 const struct ctlv_attr **child)
+{
+	const u8 *end = (const u8 *)nest + nest->len;
+	const u8 *next;
+	size_t room;
+
+	if (nest->len < sizeof(*nest))
+		return CTLV_MESSAGE_STEP_BAD;
+	if (*child)
+		next = (const u8 *)*child + ALIGN((size_t)(*child)->len, CTLV_ALIGNTO);
+	else
+		next = (const u8 *)(nest + 1);
+	if (next >= end)
+		return next == end ? CTLV_MESSAGE_STEP_END : CTLV_MESSAGE_STEP_BAD;
+
+	room = end - next;
+	if (room < sizeof(**child))
+		return CTLV_MESSAGE_STEP_BAD;
+	*child = (const struct ctlv_attr *)next;
+	/*
+	 * Length before alignment, so that aligning a length this nest could
+	 * never hold is not what overflows.
+	 */
+	if ((*child)->len < sizeof(**child) || (*child)->len > room)
+		return CTLV_MESSAGE_STEP_BAD;
+	if (ALIGN((size_t)(*child)->len, CTLV_ALIGNTO) > room)
+		return CTLV_MESSAGE_STEP_BAD;
+	return CTLV_MESSAGE_STEP_ATTR;
+}
+
+u32 ctlv_message_offset(const struct ctlv_msg *msg, const struct ctlv_attr *attr)
+{
+	return (const u8 *)attr - (const u8 *)msg->root;
+}
+
+void ctlv_message_root(struct ctlv_cursor *cursor, struct ctlv_msg *msg)
+{
+	*cursor = (struct ctlv_cursor){
+		.msg = msg,
+		.attr = msg->root,
+		.tree = msg->tree,
+		.index_nest_scope = CTLV_MESSAGE_INPUT_INDEX_NONE,
+		.index_scope = CTLV_MESSAGE_INPUT_INDEX_NONE,
+	};
+	if (msg->request && msg->index)
+		cursor->index_nest_scope = msg->index->nests[0].first_scope;
+}
+
+static bool ctlv_message_nest_index_ok(const struct ctlv_cursor *nest)
+{
+	const struct ctlv_message_input_index *index = nest->msg->index;
+	const struct ctlv_message_input_nest *indexed;
+	const struct ctlv_message_input_scope *scope;
+	const struct ctlv_attr *attr;
+
+	if (WARN_ON_ONCE(!nest->msg->request || !index ||
+			 nest->index_nest_scope >= index->scopes_count))
+		return false;
+	scope = &index->scopes[nest->index_nest_scope];
+	if (WARN_ON_ONCE(scope->nest >= index->nests_count))
+		return false;
+	indexed = &index->nests[scope->nest];
+	attr = (const void *)((const u8 *)nest->msg->root + indexed->offset);
+	if (WARN_ON_ONCE(attr != nest->attr))
+		return false;
+	return !WARN_ON_ONCE(scope->tree != nest->tree || scope->node != nest->node);
+}
+
+static bool ctlv_message_input_scope_ok(const struct ctlv_message_input_index *index,
+					const struct ctlv_message_input_scope *scope)
+{
+	return !WARN_ON_ONCE(scope->first_slot > index->slots_count ||
+			     scope->slots_count > index->slots_count - scope->first_slot);
+}
+
+static const struct ctlv_node_schema *ctlv_message_input_ref_node(struct ctlv_input_ref ref)
+{
+	const struct ctlv_node_schema *parent;
+	const struct ctlv_node_schema *node;
+
+	if (WARN_ON_ONCE(!ref.tree->node_schemas || ref.node >= ref.tree->node_schemas_count))
+		return NULL;
+	parent = &ref.tree->node_schemas[ref.node];
+	if (WARN_ON_ONCE(ref.slot >= parent->children_count ||
+			 parent->first_child + ref.slot >= ref.tree->node_schemas_count))
+		return NULL;
+	node = &ref.tree->node_schemas[parent->first_child + ref.slot];
+	if (WARN_ON_ONCE(node->attr_id != ref.attr_id || node->kind != ref.kind))
+		return NULL;
+	return node;
+}
+
+static const struct ctlv_message_input_slot *
+ctlv_message_cursor_index(const struct ctlv_cursor *cursor)
+{
+	const struct ctlv_message_input_index *index;
+	const struct ctlv_message_input_scope *scope;
+	const struct ctlv_node_schema *parent;
+	const struct ctlv_node_schema *node;
+	const struct ctlv_message_input_slot *slot;
+	const struct ctlv_message_input_nest *nest;
+	u32 local_slot;
+	u32 offset;
+
+	if (WARN_ON_ONCE(!cursor->msg || !cursor->tree || !cursor->msg->request ||
+			 !cursor->msg->index))
+		return NULL;
+	index = cursor->msg->index;
+	if (WARN_ON_ONCE(cursor->index_scope >= index->scopes_count))
+		return NULL;
+	scope = &index->scopes[cursor->index_scope];
+	if (!ctlv_message_input_scope_ok(index, scope))
+		return NULL;
+	parent = &scope->tree->node_schemas[scope->node];
+	if (WARN_ON_ONCE(scope->tree != cursor->tree || cursor->node < parent->first_child ||
+			 cursor->node >= parent->first_child + scope->slots_count))
+		return NULL;
+	local_slot = cursor->node - parent->first_child;
+	node = &cursor->tree->node_schemas[cursor->node];
+	slot = &index->slots[scope->first_slot + local_slot];
+	if (!cursor->attr)
+		return slot;
+	if (WARN_ON_ONCE(cursor->attr->attr_id != node->attr_id))
+		return NULL;
+	if (WARN_ON_ONCE(scope->nest >= index->nests_count))
+		return NULL;
+	nest = &index->nests[scope->nest];
+	if (WARN_ON_ONCE(cursor->parent !=
+			 (const void *)((const u8 *)cursor->msg->root + nest->offset)))
+		return NULL;
+	offset = ctlv_message_offset(cursor->msg, cursor->attr);
+	if (WARN_ON_ONCE(offset < slot->first_offset || offset >= slot->end_offset ||
+			 offset + ALIGN((size_t)cursor->attr->len, CTLV_ALIGNTO) >
+				 slot->end_offset))
+		return NULL;
+	if (node->kind == CTLV_SCHEMA_NEST) {
+		const struct ctlv_message_input_scope *nest_scope;
+
+		if (WARN_ON_ONCE(cursor->index_nest_scope >= index->scopes_count))
+			return NULL;
+		nest_scope = &index->scopes[cursor->index_nest_scope];
+		if (WARN_ON_ONCE(nest_scope->nest >= index->nests_count ||
+				 index->nests[nest_scope->nest].offset != offset ||
+				 nest_scope->tree != cursor->tree ||
+				 nest_scope->node != cursor->node))
+			return NULL;
+	} else if (WARN_ON_ONCE(cursor->index_nest_scope != CTLV_MESSAGE_INPUT_INDEX_NONE)) {
+		return NULL;
+	}
+	return slot;
+}
+
+bool ctlv_message_input_rebind(struct ctlv_cursor *nest, const struct ctlv_schema_tree *tree,
+			       u32 node)
+{
+	const struct ctlv_message_input_scope *bound_scope;
+	const struct ctlv_message_input_nest *indexed;
+	u32 i;
+
+	if (WARN_ON_ONCE(!nest->attr || !nest->msg || !nest->msg->index))
+		return false;
+	if (!ctlv_message_nest_index_ok(nest))
+		return false;
+	bound_scope = &nest->msg->index->scopes[nest->index_nest_scope];
+	indexed = &nest->msg->index->nests[bound_scope->nest];
+	for (i = 0; i < indexed->scopes_count; i++) {
+		u32 scope_index = indexed->first_scope + i;
+		const struct ctlv_message_input_scope *scope =
+			&nest->msg->index->scopes[scope_index];
+
+		if (scope->tree != tree || scope->node != node)
+			continue;
+		nest->tree = tree;
+		nest->node = node;
+		nest->index_nest_scope = scope_index;
+		return true;
+	}
+	return false;
+}
+
+struct ctlv_cursor *ctlv_input_attr(struct ctlv_cursor *cursor, const struct ctlv_cursor *nest,
+				    struct ctlv_input_ref ref)
+{
+	const struct ctlv_message_input_index *index;
+	const struct ctlv_message_input_scope *scope;
+	const struct ctlv_message_input_slot *indexed;
+	const struct ctlv_node_schema *schema;
+
+	*cursor = (struct ctlv_cursor){
+		.index_nest_scope = CTLV_MESSAGE_INPUT_INDEX_NONE,
+		.index_scope = CTLV_MESSAGE_INPUT_INDEX_NONE,
+	};
+	if (WARN_ON_ONCE(!nest->attr || !nest->msg))
+		return cursor;
+	if (!ctlv_message_nest_index_ok(nest))
+		return cursor;
+	index = nest->msg->index;
+	if (WARN_ON_ONCE(nest->index_nest_scope >= index->scopes_count))
+		return cursor;
+	scope = &index->scopes[nest->index_nest_scope];
+	if (!ctlv_message_input_scope_ok(index, scope))
+		return cursor;
+	if (WARN_ON_ONCE(scope->tree != ref.tree || scope->node != ref.node ||
+			 nest->tree != ref.tree || nest->node != ref.node ||
+			 ref.slot >= scope->slots_count))
+		return cursor;
+	schema = ctlv_message_input_ref_node(ref);
+	if (!schema)
+		return cursor;
+	indexed = &index->slots[scope->first_slot + ref.slot];
+	*cursor = (struct ctlv_cursor){
+		.msg = nest->msg,
+		.parent = nest->attr,
+		.attr = indexed->count ? (const void *)((const u8 *)nest->msg->root +
+							indexed->first_offset) :
+					 NULL,
+		.tree = ref.tree,
+		.node = ref.tree->node_schemas[ref.node].first_child + ref.slot,
+		.depth = nest->depth + 1,
+		.index_nest_scope = CTLV_MESSAGE_INPUT_INDEX_NONE,
+		.index_scope = nest->index_nest_scope,
+	};
+	if (indexed->count && schema->kind == CTLV_SCHEMA_NEST) {
+		if (WARN_ON_ONCE(indexed->first_nest >= index->nests_count))
+			return cursor;
+		cursor->index_nest_scope = index->nests[indexed->first_nest].first_scope;
+	}
+	return cursor;
+}
+EXPORT_SYMBOL_NS_GPL(ctlv_input_attr, "CTLV");
+
+bool ctlv_input_cursor(const struct ctlv_cursor *cursor, struct ctlv_input_ref ref)
+{
+	const struct ctlv_message_input_scope *scope;
+	const struct ctlv_node_schema *schema;
+
+	if (!ctlv_message_cursor_index(cursor))
+		return false;
+	schema = ctlv_message_input_ref_node(ref);
+	if (!schema)
+		return false;
+	scope = &cursor->msg->index->scopes[cursor->index_scope];
+	return !WARN_ON_ONCE(scope->tree != ref.tree ||
+			     scope->node != ref.node ||
+			     cursor->tree != ref.tree ||
+			     cursor->node !=
+				     ref.tree->node_schemas[ref.node].first_child +
+					     ref.slot);
+}
+EXPORT_SYMBOL_NS_GPL(ctlv_input_cursor, "CTLV");
+
+void ctlv_attr_next(struct ctlv_cursor *cursor)
+{
+	const struct ctlv_message_input_slot *slot;
+	const struct ctlv_message_input_scope *scope;
+	const struct ctlv_node_schema *node;
+	const struct ctlv_attr *next;
+	u32 next_nest;
+	u32 next_offset;
+
+	slot = ctlv_message_cursor_index(cursor);
+	if (!slot || WARN_ON_ONCE(!cursor->attr))
+		return;
+	next = (const void *)((const u8 *)cursor->attr +
+			      ALIGN((size_t)cursor->attr->len, CTLV_ALIGNTO));
+	next_offset = ctlv_message_offset(cursor->msg, next);
+	if (next_offset == slot->end_offset) {
+		cursor->attr = NULL;
+		cursor->index_nest_scope = CTLV_MESSAGE_INPUT_INDEX_NONE;
+		return;
+	}
+	if (WARN_ON_ONCE(next_offset > slot->end_offset))
+		return;
+	cursor->attr = next;
+	node = &cursor->tree->node_schemas[cursor->node];
+	if (node->kind == CTLV_SCHEMA_NEST) {
+		if (WARN_ON_ONCE(cursor->index_nest_scope >= cursor->msg->index->scopes_count))
+			return;
+		scope = &cursor->msg->index->scopes[cursor->index_nest_scope];
+		if (WARN_ON_ONCE(scope->nest >= cursor->msg->index->nests_count))
+			return;
+		next_nest = cursor->msg->index->nests[scope->nest].next;
+		if (WARN_ON_ONCE(next_nest == CTLV_MESSAGE_INPUT_INDEX_NONE ||
+				 next_nest >= cursor->msg->index->nests_count))
+			return;
+		cursor->index_nest_scope = cursor->msg->index->nests[next_nest].first_scope;
+	}
+	WARN_ON_ONCE(!ctlv_message_cursor_index(cursor));
+}
+EXPORT_SYMBOL_NS_GPL(ctlv_attr_next, "CTLV");
+
+bool ctlv_attr_ok(const struct ctlv_cursor *cursor)
+{
+	return cursor && cursor->attr && ctlv_message_cursor_index(cursor);
+}
+EXPORT_SYMBOL_NS_GPL(ctlv_attr_ok, "CTLV");
+
+/* The payload, checked against the kinds a reader of this C type accepts. */
+static const void *ctlv_message_cursor_payload(const struct ctlv_cursor *cursor, u32 kinds,
+					       u32 *len)
+{
+	const struct ctlv_node_schema *node;
+
+	if (!ctlv_message_cursor_index(cursor) || WARN_ON_ONCE(!cursor->attr))
+		return NULL;
+	node = &cursor->tree->node_schemas[cursor->node];
+	if (WARN_ON_ONCE(!(kinds & BIT(node->kind))))
+		return NULL;
+	*len = ctlv_message_attr_payload_len(cursor->attr);
+	return ctlv_message_attr_payload(cursor->attr);
+}
+
+/* A length disagreeing with a validated kind is this core's mistake. */
+static const void *ctlv_message_cursor_fixed(const struct ctlv_cursor *cursor, u32 kinds,
+					     u32 expected)
+{
+	const void *payload;
+	u32 len;
+
+	payload = ctlv_message_cursor_payload(cursor, kinds, &len);
+	if (!payload || WARN_ON_ONCE(len != expected))
+		return NULL;
+	return payload;
+}
+
+u64 ctlv_attr_u64(const struct ctlv_cursor *cursor)
+{
+	const u64 *value = ctlv_message_cursor_fixed(cursor,
+						     BIT(CTLV_SCHEMA_UINT) | BIT(CTLV_SCHEMA_ENUM) |
+							     BIT(CTLV_SCHEMA_FLAGS),
+						     sizeof(u64));
+
+	return value ? *value : 0;
+}
+EXPORT_SYMBOL_NS_GPL(ctlv_attr_u64, "CTLV");
+
+s64 ctlv_attr_s64(const struct ctlv_cursor *cursor)
+{
+	const s64 *value = ctlv_message_cursor_fixed(cursor, BIT(CTLV_SCHEMA_SINT), sizeof(s64));
+
+	return value ? *value : 0;
+}
+EXPORT_SYMBOL_NS_GPL(ctlv_attr_s64, "CTLV");
+
+bool ctlv_attr_bool(const struct ctlv_cursor *cursor)
+{
+	const u8 *value = ctlv_message_cursor_fixed(cursor, BIT(CTLV_SCHEMA_BOOL), sizeof(u8));
+
+	return value ? *value : false;
+}
+EXPORT_SYMBOL_NS_GPL(ctlv_attr_bool, "CTLV");
+
+const char *ctlv_attr_string(const struct ctlv_cursor *cursor)
+{
+	const char *value;
+	u32 len;
+
+	value = ctlv_message_cursor_payload(cursor, BIT(CTLV_SCHEMA_STRING), &len);
+	if (!value || WARN_ON_ONCE(!len || value[len - 1]))
+		return NULL;
+	return value;
+}
+EXPORT_SYMBOL_NS_GPL(ctlv_attr_string, "CTLV");
+
+const void *ctlv_attr_binary(const struct ctlv_cursor *cursor, u32 *len)
+{
+	const void *value;
+
+	*len = 0;
+	value = ctlv_message_cursor_payload(cursor, BIT(CTLV_SCHEMA_BINARY), len);
+	if (!value)
+		*len = 0;
+	return value;
+}
+EXPORT_SYMBOL_NS_GPL(ctlv_attr_binary, "CTLV");
+
+/*
+ * The room is measured before anything is written, which is what leaves a
+ * refused attr's message exactly as it was, padding included.
+ */
diff --git a/drivers/ctlv/message.h b/drivers/ctlv/message.h
new file mode 100644
index 0000000000000..efd781af9b373
--- /dev/null
+++ b/drivers/ctlv/message.h
@@ -0,0 +1,92 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES
+ *
+ * Private message representation and nest walking.
+ */
+#ifndef _CTLV_MESSAGE_H
+#define _CTLV_MESSAGE_H
+
+#include <linux/ctlv_family.h>
+#include <linux/types.h>
+
+#include <uapi/linux/ctlv.h>
+
+#define CTLV_MESSAGE_INPUT_INDEX_NONE U32_MAX
+
+/* Attr identity remains in the generated schema, not in this request index. */
+struct ctlv_message_input_slot {
+	u32 first_offset;
+	u32 end_offset;
+	u32 count;
+	u32 excess_offset;
+	u32 first_nest;
+	u32 last_nest;
+};
+
+struct ctlv_message_input_scope {
+	const struct ctlv_schema_tree *tree;
+	u32 nest;
+	u32 node;
+	u32 first_slot;
+	u32 slots_count;
+	bool optional;
+};
+
+struct ctlv_message_input_nest {
+	u32 offset;
+	u32 first_scope;
+	u32 scopes_count;
+	u32 next;
+};
+
+struct ctlv_message_input_index {
+	struct ctlv_message_input_nest *nests;
+	struct ctlv_message_input_scope *scopes;
+	struct ctlv_message_input_slot *slots;
+	u32 nests_count;
+	u32 nests_capacity;
+	u32 scopes_count;
+	u32 scopes_capacity;
+	u32 slots_count;
+	u32 slots_capacity;
+};
+
+struct ctlv_msg {
+	struct ctlv_attr *root;
+	size_t len;
+	const struct ctlv_schema_tree *tree;
+	const struct ctlv_family *family;
+	struct ctlv_op_ctx *ctx;
+	struct ctlv_message_input_index *index;
+	bool request;
+	int poison;
+};
+
+enum ctlv_message_step {
+	CTLV_MESSAGE_STEP_ATTR,
+	CTLV_MESSAGE_STEP_END,
+	CTLV_MESSAGE_STEP_BAD,
+};
+
+enum ctlv_message_step ctlv_message_next(const struct ctlv_attr *nest,
+					 const struct ctlv_attr **child);
+u32 ctlv_message_offset(const struct ctlv_msg *msg,
+			const struct ctlv_attr *attr);
+void ctlv_message_root(struct ctlv_cursor *cursor, struct ctlv_msg *msg);
+void ctlv_message_index_free(struct ctlv_msg *msg);
+bool ctlv_message_input_rebind(struct ctlv_cursor *nest,
+			       const struct ctlv_schema_tree *tree, u32 node);
+
+static inline u32 ctlv_message_attr_payload_len(const struct ctlv_attr *attr)
+{
+	return attr->len - sizeof(*attr);
+}
+
+static inline const void *
+ctlv_message_attr_payload(const struct ctlv_attr *attr)
+{
+	return attr + 1;
+}
+
+#endif /* _CTLV_MESSAGE_H */
diff --git a/drivers/ctlv/schema.c b/drivers/ctlv/schema.c
new file mode 100644
index 0000000000000..b74f9a358bc34
--- /dev/null
+++ b/drivers/ctlv/schema.c
@@ -0,0 +1,1047 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES
+ *
+ * Generated metadata remains owner-local; effective schemas walk the chain.
+ */
+#include <linux/align.h>
+#include <linux/bits.h>
+#include <linux/ctlv.h>
+#include <linux/err.h>
+#include <linux/errno.h>
+#include <linux/limits.h>
+#include <linux/minmax.h>
+#include <linux/overflow.h>
+#include <linux/slab.h>
+#include <linux/string.h>
+#include <linux/types.h>
+
+#include <uapi/linux/ctlv.h>
+#include <uapi/linux/ctlv_gen.h>
+
+#include "blob_desc.h"
+#include "internal.h"
+#include "message.h"
+#include "schema.h"
+
+/* Every 64-bit payload, and every blob descriptor member, is this long. */
+#define CTLV_SCHEMA_SCALAR_ATTR_LEN (sizeof(struct ctlv_attr) + sizeof(u64))
+
+/*
+ * Where composing a tree's maximum length gives up, which keeps the check on a
+ * composed length from being passed by a total that wrapped.
+ */
+#define CTLV_SCHEMA_MAX_COMPOSED_LEN CTLV_MAX_EVENT_QUEUE_LEN
+
+const struct ctlv_family *ctlv_family_ancestor(const struct ctlv_family *family, u32 up)
+{
+	while (up-- && family)
+		family = family->parent;
+	return family;
+}
+
+u32 ctlv_family_levels(const struct ctlv_family *family)
+{
+	const struct ctlv_family *ancestor;
+	u32 levels = 0;
+
+	for (ancestor = family; ancestor; ancestor = ancestor->parent)
+		levels++;
+	return levels;
+}
+
+void ctlv_schema_cursor_init(struct ctlv_schema_cursor *cursor, const struct ctlv_family *family)
+{
+	cursor->target = family;
+	cursor->level = ctlv_family_levels(family);
+	cursor->family = NULL;
+	cursor->index = 0;
+}
+
+const struct ctlv_op_schema *ctlv_schema_next_op(struct ctlv_schema_cursor *cursor,
+						 const struct ctlv_family **family)
+{
+	while (cursor->level) {
+		const struct ctlv_family_schema *schema;
+
+		if (!cursor->family)
+			cursor->family = ctlv_family_ancestor(cursor->target, cursor->level - 1);
+		schema = cursor->family->schema;
+		if (cursor->index < schema->ops_count) {
+			*family = cursor->family;
+			return &schema->ops[cursor->index++];
+		}
+		cursor->level--;
+		cursor->family = NULL;
+		cursor->index = 0;
+	}
+	return NULL;
+}
+
+bool ctlv_schema_member(const struct ctlv_family *family, const struct ctlv_schema_tree *tree,
+			u32 node, u64 attr_id, struct ctlv_schema_pos *member)
+{
+	const struct ctlv_node_schema *nest;
+	u32 index;
+
+	if (!tree->node_schemas || node >= tree->node_schemas_count)
+		return false;
+	nest = &tree->node_schemas[node];
+
+	for (index = 0; index < nest->children_count; index++) {
+		u32 child = nest->first_child + index;
+
+		if (tree->node_schemas[child].attr_id == attr_id) {
+			*member = (struct ctlv_schema_pos){
+				.tree = tree,
+				.node = child,
+			};
+			return true;
+		}
+	}
+	for (index = 0; index < tree->stub_schemas_count; index++) {
+		const struct ctlv_stub_schema *stub_schema = &tree->stub_schemas[index];
+		const struct ctlv_stub_fill_schema *fill_schema;
+
+		if (stub_schema->node != node)
+			continue;
+		fill_schema = ctlv_schema_fill(family, stub_schema->family_id, stub_schema->set_id);
+		/* Filled-stub members are children of the fill schema's root. */
+		if (fill_schema &&
+		    ctlv_schema_member(family, &fill_schema->members, 0, attr_id, member))
+			return true;
+	}
+	return false;
+}
+
+const struct ctlv_stub_fill_schema *ctlv_schema_fill(const struct ctlv_family *family,
+						     u16 family_id, u32 set_id)
+{
+	const struct ctlv_family *owner;
+	u32 index;
+
+	for (owner = family; owner; owner = owner->parent) {
+		const struct ctlv_family_schema *schema = owner->schema;
+
+		for (index = 0; index < schema->stub_fill_schemas_count; index++)
+			if (schema->stub_fill_schemas[index].family_id == family_id &&
+			    schema->stub_fill_schemas[index].set_id == set_id)
+				return &schema->stub_fill_schemas[index];
+	}
+	return NULL;
+}
+
+/*
+ * The same arithmetic the generator did, over the tree it emitted plus this
+ * family's stub fill schemas, since a fill makes an extension point longer.
+ */
+
+struct ctlv_schema_length_walk {
+	const struct ctlv_family *family;
+	bool bad;
+};
+
+static u64 ctlv_schema_children_max_len(struct ctlv_schema_length_walk *walk,
+					const struct ctlv_schema_tree *tree, u32 index, u32 depth);
+
+static u64 ctlv_schema_payload_max_len(struct ctlv_schema_length_walk *walk,
+				       const struct ctlv_schema_tree *tree, u32 index, u32 depth)
+{
+	const struct ctlv_node_schema *node = &tree->node_schemas[index];
+
+	switch (node->kind) {
+	case CTLV_SCHEMA_UINT:
+	case CTLV_SCHEMA_SINT:
+	case CTLV_SCHEMA_ENUM:
+	case CTLV_SCHEMA_FLAGS:
+		return sizeof(u64);
+	case CTLV_SCHEMA_BOOL:
+		return 1;
+	case CTLV_SCHEMA_STRING:
+		/*
+		 * One terminating NUL, which the declared maximum excludes.
+		 * Widened first so that a maximum at U32_MAX cannot wrap.
+		 */
+		return (u64)node->length.max_len + 1;
+	case CTLV_SCHEMA_BINARY:
+		return node->length.max_len;
+	case CTLV_SCHEMA_BLOB:
+		/*
+		 * Type, length and an address; anything but a bare VA is one
+		 * member wider, an fd with an optional offset.
+		 */
+		return (node->blob.backings == BIT(CTLV_BLOB_TYPE_VA) ? 3 : 4) *
+		       ALIGN(CTLV_SCHEMA_SCALAR_ATTR_LEN, CTLV_ALIGNTO);
+	default:
+		return ctlv_schema_children_max_len(walk, tree, index, depth);
+	}
+}
+
+static u64 ctlv_schema_attr_max_len(struct ctlv_schema_length_walk *walk,
+				    const struct ctlv_schema_tree *tree, u32 index, u32 depth)
+{
+	return sizeof(struct ctlv_attr) + ctlv_schema_payload_max_len(walk, tree, index, depth);
+}
+
+static u64 ctlv_schema_children_max_len(struct ctlv_schema_length_walk *walk,
+					const struct ctlv_schema_tree *tree, u32 index, u32 depth)
+{
+	const struct ctlv_node_schema *node = &tree->node_schemas[index];
+	u64 total = 0;
+	u32 i;
+
+	if (depth > CTLV_MAX_DECLARED_NEST_DEPTH) {
+		walk->bad = true;
+		return 0;
+	}
+	for (i = 0; i < node->children_count; i++) {
+		u32 child = node->first_child + i;
+		u64 each, all;
+
+		/*
+		 * Neither an unlimited placement nor one that re-enters has a
+		 * maximum, and only a query reply may hold either.
+		 */
+		if (tree->node_schemas[child].reenters ||
+		    !tree->node_schemas[child].max_occurrences) {
+			walk->bad = true;
+			return 0;
+		}
+		each = ALIGN(ctlv_schema_attr_max_len(walk, tree, child, depth + 1), CTLV_ALIGNTO);
+		if (check_mul_overflow((u64)tree->node_schemas[child].max_occurrences, each,
+				       &all) ||
+		    check_add_overflow(total, all, &total) ||
+		    total > CTLV_SCHEMA_MAX_COMPOSED_LEN) {
+			walk->bad = true;
+			return 0;
+		}
+	}
+	for (i = 0; i < tree->stub_schemas_count; i++) {
+		const struct ctlv_stub_schema *stub_schema = &tree->stub_schemas[i];
+		const struct ctlv_stub_fill_schema *fill_schema;
+
+		if (stub_schema->node != index)
+			continue;
+		fill_schema =
+			ctlv_schema_fill(walk->family, stub_schema->family_id, stub_schema->set_id);
+		if (!fill_schema)
+			continue;
+		if (check_add_overflow(total,
+				       ctlv_schema_children_max_len(walk, &fill_schema->members, 0,
+								    depth),
+				       &total) ||
+		    total > CTLV_SCHEMA_MAX_COMPOSED_LEN) {
+			walk->bad = true;
+			return 0;
+		}
+	}
+	return total;
+}
+
+/* Buffer length that the largest indivisible leaf and its nests 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_NEST_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_attr), depth + 1));
+	}
+	for (i = 0; i < tree->stub_schemas_count; i++) {
+		const struct ctlv_stub_schema *stub_schema = &tree->stub_schemas[i];
+		const struct ctlv_stub_fill_schema *fill_schema;
+		const struct ctlv_node_schema *root;
+		u32 member;
+
+		if (stub_schema->node != index)
+			continue;
+		fill_schema =
+			ctlv_schema_fill(walk->family, stub_schema->family_id, stub_schema->set_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_attr),
+								   depth + 1));
+		}
+	}
+	if (has_children)
+		return deepest;
+	/* An empty root is a message of its own header alone. */
+	if (!index)
+		return above + sizeof(struct ctlv_attr);
+	return above + ALIGN(ctlv_schema_attr_max_len(walk, tree, index, depth), CTLV_ALIGNTO);
+}
+
+static u64 ctlv_schema_root_max_len(struct ctlv_schema_length_walk *walk,
+				    const struct ctlv_schema_tree *tree)
+{
+	return sizeof(struct ctlv_attr) + ctlv_schema_children_max_len(walk, tree, 0, 0);
+}
+
+/* Size one deepest legal leaf and every nest above it. */
+static u64 ctlv_schema_reentering_min_len(struct ctlv_schema_length_walk *walk,
+					  const struct ctlv_schema_tree *tree)
+{
+	u64 leaf = 0;
+	u32 index;
+
+	for (index = 1; index < tree->node_schemas_count; index++) {
+		if (tree->node_schemas[index].kind == CTLV_SCHEMA_NEST)
+			continue;
+		leaf = max(leaf,
+			   ALIGN(ctlv_schema_attr_max_len(walk, tree, index, 0), CTLV_ALIGNTO));
+	}
+	return (CTLV_MAX_NEST_DEPTH + 1) * sizeof(struct ctlv_attr) + leaf;
+}
+
+static bool ctlv_schema_tree_reenters(const struct ctlv_schema_tree *tree)
+{
+	u32 index;
+
+	for (index = 0; index < tree->node_schemas_count; index++)
+		if (tree->node_schemas[index].reenters)
+			return true;
+	return false;
+}
+
+int ctlv_schema_op_sizes(const struct ctlv_family *family, const struct ctlv_op_schema *op,
+			 struct ctlv_op_sizes *sizes)
+{
+	struct ctlv_schema_length_walk walk = { .family = family };
+	u64 request = 0, reply = 0, record = 0;
+
+	if (op->request.node_schemas)
+		request = ctlv_schema_root_max_len(&walk, &op->request);
+
+	switch (op->type) {
+	case CTLV_OP_TYPE_ACTION:
+		if (op->reply.node_schemas)
+			reply = ctlv_schema_root_max_len(&walk, &op->reply);
+		break;
+	case CTLV_OP_TYPE_QUERY:
+		if (ctlv_schema_tree_reenters(&op->reply))
+			reply = ctlv_schema_reentering_min_len(&walk, &op->reply);
+		else
+			reply = ctlv_schema_min_len(&walk, &op->reply, 0, 0, 0);
+		break;
+	case CTLV_OP_TYPE_EVENT:
+		record = sizeof(struct ctlv_event_hdr) +
+			 ALIGN(ctlv_schema_root_max_len(&walk, &op->reply), CTLV_ALIGNTO);
+		break;
+	default:
+		return -EINVAL;
+	}
+
+	if (walk.bad || request > CTLV_MAX_INLINE_MESSAGE_LEN ||
+	    reply > CTLV_MAX_INLINE_MESSAGE_LEN || record > CTLV_MAX_EVENT_QUEUE_LEN)
+		return -EINVAL;
+
+	*sizes = (struct ctlv_op_sizes){ .request_max_len = request };
+	switch (op->type) {
+	case CTLV_OP_TYPE_ACTION:
+		sizes->action_reply_max_len = reply;
+		break;
+	case CTLV_OP_TYPE_QUERY:
+		sizes->query_reply_min_len = reply;
+		/*
+		 * What the specification asked for, unless a filled extension
+		 * point made one fragment longer than that.
+		 */
+		sizes->query_reply_suggested_len =
+			max_t(u32, op->sizes.query_reply_suggested_len, reply);
+		break;
+	default:
+		sizes->event_record_max_len = record;
+		break;
+	}
+	return 0;
+}
+
+/*
+ * Only a completely valid request reaches family code; nothing is repaired or
+ * normalized. The first failure is the one recorded, and the walk stops there.
+ */
+
+struct ctlv_schema_validation {
+	struct ctlv_msg *msg;
+	struct ctlv_error *error;
+};
+
+void ctlv_message_index_free(struct ctlv_msg *msg)
+{
+	struct ctlv_message_input_index *index;
+
+	if (!msg || !msg->index)
+		return;
+	index = msg->index;
+	kvfree(index->slots);
+	kvfree(index->scopes);
+	kvfree(index->nests);
+	kfree(index);
+	msg->index = NULL;
+}
+
+static void *ctlv_schema_index_grow(void *items, u32 *capacity, u32 needed, size_t item_size)
+{
+	u32 grown = max_t(u32, *capacity, 16);
+	size_t bytes;
+	void *new;
+
+	if (needed <= *capacity)
+		return items;
+	while (grown < needed) {
+		if (grown > U32_MAX / 2)
+			return ERR_PTR(-EOVERFLOW);
+		grown *= 2;
+	}
+	if (check_mul_overflow((size_t)grown, item_size, &bytes))
+		return ERR_PTR(-EOVERFLOW);
+	new = kvrealloc(items, bytes, GFP_KERNEL_ACCOUNT);
+	if (!new)
+		return ERR_PTR(-ENOMEM);
+	*capacity = grown;
+	return new;
+}
+
+static int ctlv_schema_index_slots_add(struct ctlv_message_input_index *index, u32 count,
+				       u32 *first)
+{
+	struct ctlv_message_input_slot *slots;
+	u32 needed;
+	u32 i;
+
+	if (check_add_overflow(index->slots_count, count, &needed))
+		return -EOVERFLOW;
+	slots = ctlv_schema_index_grow(index->slots, &index->slots_capacity, needed,
+				       sizeof(*slots));
+	if (IS_ERR(slots))
+		return PTR_ERR(slots);
+	index->slots = slots;
+	*first = index->slots_count;
+	for (i = index->slots_count; i < needed; i++)
+		index->slots[i] = (struct ctlv_message_input_slot){
+			.excess_offset = CTLV_MESSAGE_INPUT_INDEX_NONE,
+			.first_nest = CTLV_MESSAGE_INPUT_INDEX_NONE,
+			.last_nest = CTLV_MESSAGE_INPUT_INDEX_NONE,
+		};
+	index->slots_count = needed;
+	return 0;
+}
+
+static int ctlv_schema_index_scope_add(struct ctlv_schema_validation *v, u32 nest_index,
+				       const struct ctlv_schema_tree *tree, u32 node, bool optional)
+{
+	struct ctlv_message_input_index *index = v->msg->index;
+	const struct ctlv_node_schema *parent = &tree->node_schemas[node];
+	struct ctlv_message_input_scope *scopes;
+	u32 needed;
+	u32 first_slot;
+	u32 scope_index;
+	u32 i;
+	int ret;
+
+	if (check_add_overflow(index->scopes_count, 1U, &needed))
+		return -EOVERFLOW;
+	scopes = ctlv_schema_index_grow(index->scopes, &index->scopes_capacity, needed,
+					sizeof(*scopes));
+	if (IS_ERR(scopes))
+		return PTR_ERR(scopes);
+	index->scopes = scopes;
+	ret = ctlv_schema_index_slots_add(index, parent->children_count, &first_slot);
+	if (ret)
+		return ret;
+	scope_index = index->scopes_count++;
+	index->scopes[scope_index] = (struct ctlv_message_input_scope){
+		.tree = tree,
+		.nest = nest_index,
+		.node = node,
+		.first_slot = first_slot,
+		.slots_count = parent->children_count,
+		.optional = optional,
+	};
+	index->nests[nest_index].scopes_count++;
+
+	for (i = 0; i < tree->stub_schemas_count; i++) {
+		const struct ctlv_stub_schema *stub_schema = &tree->stub_schemas[i];
+		const struct ctlv_stub_fill_schema *fill_schema;
+
+		if (stub_schema->node != node)
+			continue;
+		fill_schema = ctlv_schema_fill(v->msg->family, stub_schema->family_id,
+					       stub_schema->set_id);
+		if (!fill_schema)
+			continue;
+		ret = ctlv_schema_index_scope_add(v, nest_index, &fill_schema->members, 0,
+						  optional || stub_schema->optional);
+		if (ret)
+			return ret;
+	}
+	return 0;
+}
+
+static int ctlv_schema_index_nest_add(struct ctlv_schema_validation *v,
+				      const struct ctlv_schema_tree *tree, u32 node,
+				      const struct ctlv_attr *nest_attr, u32 *nest_index)
+{
+	struct ctlv_message_input_index *index = v->msg->index;
+	struct ctlv_message_input_nest *nests;
+	u32 needed;
+	u32 added;
+	int ret;
+
+	if (check_add_overflow(index->nests_count, 1U, &needed))
+		return -EOVERFLOW;
+	nests = ctlv_schema_index_grow(index->nests, &index->nests_capacity, needed,
+				       sizeof(*nests));
+	if (IS_ERR(nests))
+		return PTR_ERR(nests);
+	index->nests = nests;
+	added = index->nests_count++;
+	index->nests[added] = (struct ctlv_message_input_nest){
+		.offset = ctlv_message_offset(v->msg, nest_attr),
+		.first_scope = index->scopes_count,
+		.next = CTLV_MESSAGE_INPUT_INDEX_NONE,
+	};
+	ret = ctlv_schema_index_scope_add(v, added, tree, node, false);
+	if (ret)
+		return ret;
+	*nest_index = added;
+	return 0;
+}
+
+/* A request is never a fragment: only a reply of a query is ever incomplete. */
+#define CTLV_SCHEMA_ATTR_F_REQUEST (CTLV_ATTR_F_NESTED | CTLV_ATTR_F_IGNORE_IF_UNKNOWN)
+#define CTLV_SCHEMA_ATTR_F_REPLY CTLV_ATTR_F_NESTED
+
+/*
+ * Record the first failure and refuse the message. @attr is NULL when what is
+ * wrong with the nest is something it does not carry.
+ */
+static int ctlv_schema_bad(struct ctlv_schema_validation *v, u32 reason,
+			   const struct ctlv_attr *nest, const struct ctlv_attr *attr)
+{
+	*v->error = (struct ctlv_error){
+		.reason = reason,
+		.bad_attr_offset = ctlv_message_offset(v->msg, attr ?: nest),
+		.nest_offset = ctlv_message_offset(v->msg, nest),
+	};
+	return -EINVAL;
+}
+
+/* The one failure that names an attr the message does not contain. */
+static int ctlv_schema_bad_missing(struct ctlv_schema_validation *v, const struct ctlv_attr *nest,
+				   u64 attr_id)
+{
+	ctlv_schema_bad(v, CTLV_VALIDATION_REASON_MISSING_ATTR, nest, NULL);
+	v->error->missing_attr_id = attr_id;
+	return -EINVAL;
+}
+
+static struct ctlv_message_input_slot *ctlv_schema_index_slot(struct ctlv_schema_validation *v,
+							      u32 nest_index,
+							      const struct ctlv_schema_pos *pos)
+{
+	struct ctlv_message_input_index *index = v->msg->index;
+	const struct ctlv_message_input_nest *nest;
+	u32 i;
+
+	if (WARN_ON_ONCE(nest_index >= index->nests_count))
+		return NULL;
+	nest = &index->nests[nest_index];
+	for (i = 0; i < nest->scopes_count; i++) {
+		const struct ctlv_message_input_scope *scope =
+			&index->scopes[nest->first_scope + i];
+		const struct ctlv_node_schema *parent;
+		u32 slot;
+
+		if (scope->tree != pos->tree)
+			continue;
+		parent = &scope->tree->node_schemas[scope->node];
+		if (pos->node < parent->first_child ||
+		    pos->node >= parent->first_child + scope->slots_count)
+			continue;
+		slot = pos->node - parent->first_child;
+		return &index->slots[scope->first_slot + slot];
+	}
+	WARN_ON_ONCE(1);
+	return NULL;
+}
+
+static int ctlv_schema_index_record(struct ctlv_schema_validation *v, u32 nest_index,
+				    const struct ctlv_schema_pos *pos, const struct ctlv_attr *attr,
+				    bool *seen)
+{
+	struct ctlv_message_input_slot *slot = ctlv_schema_index_slot(v, nest_index, pos);
+	const struct ctlv_node_schema *schema = &pos->tree->node_schemas[pos->node];
+	u32 offset = ctlv_message_offset(v->msg, attr);
+
+	if (!slot)
+		return -EINVAL;
+	*seen = slot->count;
+	if (!slot->count)
+		slot->first_offset = offset;
+	slot->count++;
+	if (schema->max_occurrences && slot->count > schema->max_occurrences &&
+	    slot->excess_offset == CTLV_MESSAGE_INPUT_INDEX_NONE)
+		slot->excess_offset = offset;
+	slot->end_offset = offset + ALIGN((size_t)attr->len, CTLV_ALIGNTO);
+	return 0;
+}
+
+static void ctlv_schema_index_nest_link(struct ctlv_message_input_index *index,
+					struct ctlv_message_input_slot *slot, u32 nest_index)
+{
+	if (slot->first_nest == CTLV_MESSAGE_INPUT_INDEX_NONE)
+		slot->first_nest = nest_index;
+	else
+		index->nests[slot->last_nest].next = nest_index;
+	slot->last_nest = nest_index;
+}
+
+static int ctlv_schema_index_required(struct ctlv_schema_validation *v, u32 nest_index,
+				      const struct ctlv_attr *nest_attr)
+{
+	const struct ctlv_message_input_index *index = v->msg->index;
+	const struct ctlv_message_input_nest *nest = &index->nests[nest_index];
+	u32 i;
+
+	for (i = 0; i < nest->scopes_count; i++) {
+		const struct ctlv_message_input_scope *scope =
+			&index->scopes[nest->first_scope + i];
+		const struct ctlv_node_schema *parent = &scope->tree->node_schemas[scope->node];
+		u32 slot;
+
+		for (slot = 0; slot < scope->slots_count; slot++) {
+			const struct ctlv_message_input_slot *indexed;
+			const struct ctlv_node_schema *child =
+				&scope->tree->node_schemas[parent->first_child + slot];
+			const struct ctlv_attr *excess;
+
+			indexed = &index->slots[scope->first_slot + slot];
+			if (!indexed->count && slot < parent->required_children_count &&
+			    !scope->optional)
+				return ctlv_schema_bad_missing(v, nest_attr, child->attr_id);
+			if (!child->max_occurrences || indexed->count <= child->max_occurrences)
+				continue;
+			if (WARN_ON_ONCE(indexed->excess_offset == CTLV_MESSAGE_INPUT_INDEX_NONE))
+				return -EINVAL;
+			excess = (const void *)((const u8 *)v->msg->root + indexed->excess_offset);
+			return ctlv_schema_bad(v, CTLV_VALIDATION_REASON_TOO_MANY_OCCURRENCES,
+					       nest_attr, excess);
+		}
+	}
+	return 0;
+}
+
+/* The bits an attr of this message may carry, whichever way it travelled. */
+static u32 ctlv_schema_flags_allowed(const struct ctlv_schema_validation *v)
+{
+	return v->msg->request ? CTLV_SCHEMA_ATTR_F_REQUEST : CTLV_SCHEMA_ATTR_F_REPLY;
+}
+
+static u64 ctlv_schema_scalar_value(const struct ctlv_attr *attr)
+{
+	/* Aligned by the wire format: the root began an allocation. */
+	return *(const u64 *)ctlv_message_attr_payload(attr);
+}
+
+bool ctlv_schema_value_ok(const struct ctlv_node_schema *node, u64 value)
+{
+	switch (node->kind) {
+	case CTLV_SCHEMA_SINT:
+		return (s64)value >= (s64)node->range.min && (s64)value <= (s64)node->range.max;
+	case CTLV_SCHEMA_FLAGS:
+		/* A bit no family declared is one nothing can be told about. */
+		return !(value & ~node->flags_mask);
+	case CTLV_SCHEMA_BOOL:
+		return value <= 1;
+	default:
+		/*
+		 * An enum's values are numbered from one in declaration order
+		 * and never skipped, so its range bounds it like an integer.
+		 */
+		return value >= node->range.min && value <= node->range.max;
+	}
+}
+
+bool ctlv_schema_length_ok(const struct ctlv_node_schema *node, u32 len)
+{
+	return len >= node->length.min_len && len <= node->length.max_len;
+}
+
+static int ctlv_schema_check_integer(struct ctlv_schema_validation *v,
+				     const struct ctlv_node_schema *node,
+				     const struct ctlv_attr *nest, const struct ctlv_attr *attr)
+{
+	u64 value;
+
+	if (ctlv_message_attr_payload_len(attr) != sizeof(value))
+		return ctlv_schema_bad(v, CTLV_VALIDATION_REASON_BAD_LENGTH, nest, attr);
+	value = ctlv_schema_scalar_value(attr);
+	if (ctlv_schema_value_ok(node, value))
+		return 0;
+	if (node->kind == CTLV_SCHEMA_FLAGS)
+		return ctlv_schema_bad(v, CTLV_VALIDATION_REASON_UNKNOWN_FLAG, nest, attr);
+	return ctlv_schema_bad(v, CTLV_VALIDATION_REASON_VALUE_OUT_OF_RANGE, nest, attr);
+}
+
+static int ctlv_schema_check_bool(struct ctlv_schema_validation *v,
+				  const struct ctlv_node_schema *node, const struct ctlv_attr *nest,
+				  const struct ctlv_attr *attr)
+{
+	const u8 *value = ctlv_message_attr_payload(attr);
+
+	if (ctlv_message_attr_payload_len(attr) != sizeof(*value))
+		return ctlv_schema_bad(v, CTLV_VALIDATION_REASON_BAD_LENGTH, nest, attr);
+	if (!ctlv_schema_value_ok(node, *value))
+		return ctlv_schema_bad(v, CTLV_VALIDATION_REASON_VALUE_OUT_OF_RANGE, nest, attr);
+	return 0;
+}
+
+static int ctlv_schema_check_string(struct ctlv_schema_validation *v,
+				    const struct ctlv_node_schema *node,
+				    const struct ctlv_attr *nest, const struct ctlv_attr *attr)
+{
+	u32 len = ctlv_message_attr_payload_len(attr);
+	const char *value = ctlv_message_attr_payload(attr);
+
+	/*
+	 * One terminating NUL and no other, so a family may hand the payload
+	 * to anything that takes a C string.
+	 */
+	if (!len || value[len - 1] || strnlen(value, len) != len - 1)
+		return ctlv_schema_bad(v, CTLV_VALIDATION_REASON_BAD_STRING, nest, attr);
+	if (!ctlv_schema_length_ok(node, len - 1))
+		return ctlv_schema_bad(v, CTLV_VALIDATION_REASON_BAD_LENGTH, nest, attr);
+	return 0;
+}
+
+static int ctlv_schema_check_binary(struct ctlv_schema_validation *v,
+				    const struct ctlv_node_schema *node,
+				    const struct ctlv_attr *nest, const struct ctlv_attr *attr)
+{
+	if (!ctlv_schema_length_ok(node, ctlv_message_attr_payload_len(attr)))
+		return ctlv_schema_bad(v, CTLV_VALIDATION_REASON_BAD_LENGTH, nest, attr);
+	return 0;
+}
+
+/*
+ * The one shape the tree cannot describe: a nest of core-owned attrs
+ * whose members depend on its type. Nothing here acquires anything.
+ */
+static int ctlv_schema_check_blob(struct ctlv_schema_validation *v,
+				  const struct ctlv_node_schema *node, const struct ctlv_attr *blob)
+{
+	const struct ctlv_attr *bad = NULL;
+	struct ctlv_blob_desc desc;
+	u32 reason;
+
+	reason = ctlv_blob_desc_read(blob, &desc, &bad);
+	if (!reason)
+		reason = ctlv_blob_desc_check(&desc, node);
+	if (reason)
+		return ctlv_schema_bad(v, reason, blob, bad);
+	return 0;
+}
+
+static int ctlv_schema_check_nest(struct ctlv_schema_validation *v,
+				  const struct ctlv_schema_tree *tree, u32 node,
+				  const struct ctlv_attr *nest, u32 depth);
+static int ctlv_schema_check_indexed_nest(struct ctlv_schema_validation *v,
+					  const struct ctlv_schema_tree *tree, u32 node,
+					  const struct ctlv_attr *nest, u32 depth, u32 *nest_index);
+
+static int ctlv_schema_check_attr(struct ctlv_schema_validation *v,
+				  const struct ctlv_schema_pos *pos, const struct ctlv_attr *nest,
+				  const struct ctlv_attr *attr, u32 depth, u32 *nest_index)
+{
+	const struct ctlv_node_schema *node = &pos->tree->node_schemas[pos->node];
+	bool nested = node->kind == CTLV_SCHEMA_NEST || node->kind == CTLV_SCHEMA_BLOB;
+
+	if (attr->flags & ~ctlv_schema_flags_allowed(v))
+		return ctlv_schema_bad(v, CTLV_VALIDATION_REASON_UNKNOWN_FLAG, nest, attr);
+	/* Whether an attr is a nest is the schema's to say, not the sender's. */
+	if (!(attr->flags & CTLV_ATTR_F_NESTED) != !nested)
+		return ctlv_schema_bad(v, CTLV_VALIDATION_REASON_MALFORMED_MESSAGE, nest, attr);
+
+	switch (node->kind) {
+	case CTLV_SCHEMA_BOOL:
+		return ctlv_schema_check_bool(v, node, nest, attr);
+	case CTLV_SCHEMA_STRING:
+		return ctlv_schema_check_string(v, node, nest, attr);
+	case CTLV_SCHEMA_BINARY:
+		return ctlv_schema_check_binary(v, node, nest, attr);
+	case CTLV_SCHEMA_BLOB:
+		return ctlv_schema_check_blob(v, node, attr);
+	case CTLV_SCHEMA_NEST:
+		if (v->msg->request)
+			return ctlv_schema_check_indexed_nest(v, pos->tree, pos->node, attr,
+							      depth + 1, nest_index);
+		return ctlv_schema_check_nest(v, pos->tree, pos->node, attr, depth + 1);
+	default:
+		return ctlv_schema_check_integer(v, node, nest, attr);
+	}
+}
+
+/* How many times one member occurs, and where the one too many is. */
+static u32 ctlv_schema_occurrences(const struct ctlv_attr *nest, u64 attr_id, u32 max,
+				   const struct ctlv_attr **excess)
+{
+	const struct ctlv_attr *child = NULL;
+	u32 count = 0;
+
+	while (ctlv_message_next(nest, &child) == CTLV_MESSAGE_STEP_ATTR) {
+		if (child->attr_id != attr_id)
+			continue;
+		count++;
+		if (max && count == max + 1)
+			*excess = child;
+	}
+	return count;
+}
+
+/*
+ * An optional stub makes everything it was filled with optional too: what a
+ * descendant added cannot be something an ancestor's caller had to send.
+ */
+static int ctlv_schema_check_members(struct ctlv_schema_validation *v,
+				     const struct ctlv_schema_tree *tree, u32 node,
+				     const struct ctlv_attr *nest, bool optional)
+{
+	const struct ctlv_node_schema *parent = &tree->node_schemas[node];
+	u32 index;
+
+	for (index = 0; index < parent->children_count; index++) {
+		const struct ctlv_attr *excess = NULL;
+		const struct ctlv_node_schema *child;
+		u32 count;
+
+		child = &tree->node_schemas[parent->first_child + index];
+		count = ctlv_schema_occurrences(nest, child->attr_id, child->max_occurrences,
+						&excess);
+		if (!count) {
+			if (index < parent->required_children_count && !optional)
+				return ctlv_schema_bad_missing(v, nest, child->attr_id);
+			continue;
+		}
+		/* An unlimited placement, which only a reply may hold. */
+		if (child->max_occurrences && count > child->max_occurrences)
+			return ctlv_schema_bad(v, CTLV_VALIDATION_REASON_TOO_MANY_OCCURRENCES, nest,
+					       excess);
+	}
+
+	for (index = 0; index < tree->stub_schemas_count; index++) {
+		const struct ctlv_stub_schema *stub_schema = &tree->stub_schemas[index];
+		const struct ctlv_stub_fill_schema *fill_schema;
+		int ret;
+
+		if (stub_schema->node != node)
+			continue;
+		fill_schema = ctlv_schema_fill(v->msg->family, stub_schema->family_id,
+					       stub_schema->set_id);
+		if (!fill_schema)
+			continue;
+		ret = ctlv_schema_check_members(v, &fill_schema->members, 0, nest,
+						optional || stub_schema->optional);
+		if (ret)
+			return ret;
+	}
+	return 0;
+}
+
+/* Whether one tree places one attr ID anywhere, filled stubs included. */
+static bool ctlv_schema_tree_declares(const struct ctlv_family *family,
+				      const struct ctlv_schema_tree *tree, u64 attr_id)
+{
+	u32 index;
+
+	for (index = 0; index < tree->node_schemas_count; index++)
+		if (tree->node_schemas[index].attr_id == attr_id)
+			return true;
+	for (index = 0; index < tree->stub_schemas_count; index++) {
+		const struct ctlv_stub_schema *stub_schema = &tree->stub_schemas[index];
+		const struct ctlv_stub_fill_schema *fill_schema;
+
+		fill_schema = ctlv_schema_fill(family, stub_schema->family_id, stub_schema->set_id);
+		if (fill_schema &&
+		    ctlv_schema_tree_declares(family, &fill_schema->members, attr_id))
+			return true;
+	}
+	return false;
+}
+
+/* Search every attr ID known anywhere in the effective schema. */
+static bool ctlv_schema_declares(const struct ctlv_family *family, u64 attr_id)
+{
+	const struct ctlv_family *owner;
+	struct ctlv_schema_cursor cursor;
+	const struct ctlv_op_schema *op;
+
+	ctlv_schema_cursor_init(&cursor, family);
+	while ((op = ctlv_schema_next_op(&cursor, &owner)))
+		if (ctlv_schema_tree_declares(family, &op->request, attr_id) ||
+		    ctlv_schema_tree_declares(family, &op->reply, attr_id))
+			return true;
+	return false;
+}
+
+/*
+ * Unknown IDs remain reserved unless explicitly ignorable; ignored unknown
+ * nests are opaque.
+ */
+static int ctlv_schema_check_unknown(struct ctlv_schema_validation *v, const struct ctlv_attr *nest,
+				     const struct ctlv_attr *attr)
+{
+	/* Which refuses the bit itself on a reply, where it means nothing. */
+	if (attr->flags & ~ctlv_schema_flags_allowed(v))
+		return ctlv_schema_bad(v, CTLV_VALIDATION_REASON_UNKNOWN_FLAG, nest, attr);
+	if (!(attr->flags & CTLV_ATTR_F_IGNORE_IF_UNKNOWN) ||
+	    ctlv_schema_declares(v->msg->family, attr->attr_id))
+		return ctlv_schema_bad(v, CTLV_VALIDATION_REASON_UNKNOWN_ATTR, nest, attr);
+	return 0;
+}
+
+static int ctlv_schema_check_indexed_nest(struct ctlv_schema_validation *v,
+					  const struct ctlv_schema_tree *tree, u32 node,
+					  const struct ctlv_attr *nest, u32 depth, u32 *nest_index)
+{
+	struct ctlv_message_input_index *index = v->msg->index;
+	const struct ctlv_attr *child = NULL;
+	const struct ctlv_attr *split = NULL;
+	u64 previous = 0;
+	bool previous_valid = false;
+	u32 added;
+	enum ctlv_message_step step;
+	int ret;
+
+	if (depth > CTLV_MAX_NEST_DEPTH)
+		return ctlv_schema_bad(v, CTLV_VALIDATION_REASON_NESTING_TOO_DEEP, nest, NULL);
+	ret = ctlv_schema_index_nest_add(v, tree, node, nest, &added);
+	if (ret)
+		return ret;
+
+	while ((step = ctlv_message_next(nest, &child)) == CTLV_MESSAGE_STEP_ATTR) {
+		struct ctlv_schema_pos pos;
+		bool seen;
+
+		if (!ctlv_schema_member(v->msg->family, tree, node, child->attr_id, &pos)) {
+			previous_valid = false;
+			continue;
+		}
+		ret = ctlv_schema_index_record(v, added, &pos, child, &seen);
+		if (ret)
+			return ret;
+		if (seen && (!previous_valid || previous != child->attr_id) && !split)
+			split = child;
+		previous = child->attr_id;
+		previous_valid = true;
+	}
+	ret = ctlv_schema_index_required(v, added, nest);
+	if (ret)
+		return ret;
+	if (step == CTLV_MESSAGE_STEP_BAD)
+		return ctlv_schema_bad(v, CTLV_VALIDATION_REASON_MALFORMED_MESSAGE, nest, NULL);
+
+	child = NULL;
+	while (ctlv_message_next(nest, &child) == CTLV_MESSAGE_STEP_ATTR) {
+		struct ctlv_schema_pos pos;
+		struct ctlv_message_input_slot *slot;
+		u32 child_nest = CTLV_MESSAGE_INPUT_INDEX_NONE;
+
+		if (!ctlv_schema_member(v->msg->family, tree, node, child->attr_id, &pos)) {
+			ret = ctlv_schema_check_unknown(v, nest, child);
+			if (ret)
+				return ret;
+			continue;
+		}
+		if (child == split)
+			return ctlv_schema_bad(v, CTLV_VALIDATION_REASON_NONCONTIGUOUS_ATTR, nest,
+					       child);
+		ret = ctlv_schema_check_attr(v, &pos, nest, child, depth, &child_nest);
+		if (ret)
+			return ret;
+		if (child_nest != CTLV_MESSAGE_INPUT_INDEX_NONE) {
+			slot = ctlv_schema_index_slot(v, added, &pos);
+			if (!slot)
+				return -EINVAL;
+			ctlv_schema_index_nest_link(index, slot, child_nest);
+		}
+	}
+	*nest_index = added;
+	return 0;
+}
+
+/*
+ * Required members first, then every attr in the order the nest carries them,
+ * so that what is reported is the first thing a caller has to fix.
+ */
+static int ctlv_schema_check_nest(struct ctlv_schema_validation *v,
+				  const struct ctlv_schema_tree *tree, u32 node,
+				  const struct ctlv_attr *nest, u32 depth)
+{
+	const struct ctlv_attr *child = NULL;
+	enum ctlv_message_step step;
+	int ret;
+
+	if (depth > CTLV_MAX_NEST_DEPTH)
+		return ctlv_schema_bad(v, CTLV_VALIDATION_REASON_NESTING_TOO_DEEP, nest, NULL);
+
+	ret = ctlv_schema_check_members(v, tree, node, nest, false);
+	if (ret)
+		return ret;
+
+	while ((step = ctlv_message_next(nest, &child)) == CTLV_MESSAGE_STEP_ATTR) {
+		struct ctlv_schema_pos pos;
+
+		if (!ctlv_schema_member(v->msg->family, tree, node, child->attr_id, &pos)) {
+			ret = ctlv_schema_check_unknown(v, nest, child);
+			if (ret)
+				return ret;
+			/* Skipped whole: the step past it checked its length. */
+			continue;
+		}
+		ret = ctlv_schema_check_attr(v, &pos, nest, child, depth, NULL);
+		if (ret)
+			return ret;
+	}
+	if (step == CTLV_MESSAGE_STEP_BAD)
+		return ctlv_schema_bad(v, CTLV_VALIDATION_REASON_MALFORMED_MESSAGE, nest, NULL);
+	return 0;
+}
+
+int ctlv_schema_validate(struct ctlv_msg *msg, struct ctlv_error *error)
+{
+	struct ctlv_schema_validation validate = { .msg = msg, .error = error };
+	u32 root_index;
+	int ret;
+
+	if (!msg->request)
+		return ctlv_schema_check_nest(&validate, msg->tree, 0, msg->root, 0);
+	if (WARN_ON_ONCE(msg->index))
+		return -EINVAL;
+	msg->index = kzalloc_obj(*msg->index, GFP_KERNEL_ACCOUNT);
+	if (!msg->index)
+		return -ENOMEM;
+	ret = ctlv_schema_check_indexed_nest(&validate, msg->tree, 0, msg->root, 0, &root_index);
+	if (ret || WARN_ON_ONCE(root_index)) {
+		ctlv_message_index_free(msg);
+		return ret ?: -EINVAL;
+	}
+	return 0;
+}
diff --git a/drivers/ctlv/schema.h b/drivers/ctlv/schema.h
new file mode 100644
index 0000000000000..4552a392da60c
--- /dev/null
+++ b/drivers/ctlv/schema.h
@@ -0,0 +1,50 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES
+ *
+ * Private generated-schema walkers.
+ */
+#ifndef _CTLV_SCHEMA_H
+#define _CTLV_SCHEMA_H
+
+#include <linux/ctlv_family.h>
+#include <linux/types.h>
+
+struct ctlv_schema_cursor {
+	const struct ctlv_family *target;
+	const struct ctlv_family *family;
+	u32 level;
+	u32 index;
+};
+
+struct ctlv_schema_pos {
+	const struct ctlv_schema_tree *tree;
+	u32 node;
+};
+
+const struct ctlv_family *
+ctlv_family_ancestor(const struct ctlv_family *family, u32 up);
+u32 ctlv_family_levels(const struct ctlv_family *family);
+void ctlv_schema_cursor_init(struct ctlv_schema_cursor *cursor,
+			     const struct ctlv_family *family);
+const struct ctlv_op_schema *
+ctlv_schema_next_op(struct ctlv_schema_cursor *cursor,
+		    const struct ctlv_family **family);
+const struct ctlv_stub_fill_schema *
+ctlv_schema_fill(const struct ctlv_family *family, u16 family_id,
+		 u32 set_id);
+int ctlv_schema_op_sizes(const struct ctlv_family *family,
+			 const struct ctlv_op_schema *op,
+			 struct ctlv_op_sizes *sizes);
+bool ctlv_schema_member(const struct ctlv_family *family,
+			const struct ctlv_schema_tree *tree, u32 node,
+			u64 attr_id, struct ctlv_schema_pos *member);
+bool ctlv_schema_value_ok(const struct ctlv_node_schema *node, u64 value);
+bool ctlv_schema_length_ok(const struct ctlv_node_schema *node, u32 len);
+
+struct ctlv_error;
+struct ctlv_msg;
+
+int ctlv_schema_validate(struct ctlv_msg *msg, struct ctlv_error *error);
+
+#endif /* _CTLV_SCHEMA_H */
diff --git a/drivers/virt/coco/tdx-guest/tdx-guest.c b/drivers/virt/coco/tdx-guest/tdx-guest.c
index d0303e31e8161..0d53170602463 100644
--- a/drivers/virt/coco/tdx-guest/tdx-guest.c
+++ b/drivers/virt/coco/tdx-guest/tdx-guest.c
@@ -19,6 +19,7 @@
 #include <linux/sockptr.h>
 #include <linux/tsm.h>
 #include <linux/tsm-mr.h>
+#include <linux/tdx-guest.h>
 
 #include <uapi/linux/tdx-guest.h>
 
@@ -27,10 +28,21 @@
 
 /* TDREPORT buffer */
 static u8 *tdx_report_buf;
+static struct tdx_guest_info tdx_guest_info;
+static struct miscdevice tdx_misc_dev;
+
+static_assert(TDX_REPORTDATA_LEN == TDX_GUEST_REPORTDATA_LEN);
+static_assert(TDX_REPORT_LEN == TDX_GUEST_REPORT_LEN);
 
 /* Lock to serialize TDG.MR.REPORT and TDG.MR.RTMR.EXTEND TDCALLs */
 static DEFINE_MUTEX(mr_lock);
 
+/* Serializes native client registration and service attachment. */
+static DEFINE_MUTEX(client_lock);
+static const struct tdx_guest_client *tdx_client;
+static void *tdx_client_priv;
+static bool tdx_service_ready;
+
 /* TDREPORT fields */
 enum {
 	TDREPORT_reportdata = 128,
@@ -49,24 +61,30 @@ enum {
 	TDREPORT_servtd_hash = TDREPORT_rtmr3 + SHA384_DIGEST_SIZE,
 };
 
-static int tdx_do_report(sockptr_t data, sockptr_t tdreport)
+static int __tdx_do_report(sockptr_t data, sockptr_t tdreport)
 {
-	scoped_cond_guard(mutex_intr, return -EINTR, &mr_lock) {
-		u8 *reportdata = tdx_report_buf + TDREPORT_reportdata;
-		int ret;
+	u8 *reportdata = tdx_report_buf + TDREPORT_reportdata;
+	int ret;
 
-		if (!sockptr_is_null(data) &&
-		    copy_from_sockptr(reportdata, data, TDX_REPORTDATA_LEN))
-			return -EFAULT;
+	lockdep_assert_held(&mr_lock);
+	if (!sockptr_is_null(data) &&
+	    copy_from_sockptr(reportdata, data, TDX_REPORTDATA_LEN))
+		return -EFAULT;
 
-		ret = tdx_mcall_get_report0(reportdata, tdx_report_buf);
-		if (WARN_ONCE(ret, "tdx_mcall_get_report0() failed: %d", ret))
-			return ret;
+	ret = tdx_mcall_get_report0(reportdata, tdx_report_buf);
+	if (WARN_ONCE(ret, "tdx_mcall_get_report0() failed: %d", ret))
+		return ret;
 
-		if (!sockptr_is_null(tdreport) &&
-		    copy_to_sockptr(tdreport, tdx_report_buf, TDX_REPORT_LEN))
-			return -EFAULT;
-	}
+	if (!sockptr_is_null(tdreport) &&
+	    copy_to_sockptr(tdreport, tdx_report_buf, TDX_REPORT_LEN))
+		return -EFAULT;
+	return 0;
+}
+
+static int tdx_do_report(sockptr_t data, sockptr_t tdreport)
+{
+	scoped_cond_guard(mutex_intr, return -EINTR, &mr_lock)
+		return __tdx_do_report(data, tdreport);
 	return 0;
 }
 
@@ -90,6 +108,76 @@ static int tdx_do_extend(u8 mr_ind, const u8 *data)
 	return 0;
 }
 
+static bool tdx_guest_device_valid(struct device *dev)
+{
+	return dev && dev == tdx_misc_dev.this_device;
+}
+
+static const struct tdx_guest_info *tdx_guest_info_get(struct device *dev)
+{
+	return tdx_guest_device_valid(dev) ? &tdx_guest_info : NULL;
+}
+
+static int tdx_guest_report_get(struct device *dev, const u8 *reportdata,
+				size_t length, void *out, size_t capacity,
+				size_t *out_length)
+{
+	int ret;
+
+	if (!tdx_guest_device_valid(dev))
+		return -ENODEV;
+	if (!reportdata || length != TDX_REPORTDATA_LEN || !out || !out_length)
+		return -EINVAL;
+	if (capacity < TDX_REPORT_LEN)
+		return -EMSGSIZE;
+	scoped_cond_guard(mutex_intr, return -EINTR, &mr_lock) {
+		ret = __tdx_do_report(KERNEL_SOCKPTR((void *)reportdata),
+				      KERNEL_SOCKPTR(NULL));
+		if (ret)
+			return ret;
+		memcpy(out, tdx_report_buf, TDX_REPORT_LEN);
+	}
+	*out_length = TDX_REPORT_LEN;
+	return 0;
+}
+
+static int tdx_guest_mr_read(struct device *dev, enum tdx_guest_mr mr,
+			     u8 value[SHA384_DIGEST_SIZE])
+{
+	static const size_t offsets[] = {
+		[TDX_GUEST_MR_MRTD] = TDREPORT_mrtd,
+		[TDX_GUEST_MR_RTMR0] = TDREPORT_rtmr0,
+		[TDX_GUEST_MR_RTMR1] = TDREPORT_rtmr1,
+		[TDX_GUEST_MR_RTMR2] = TDREPORT_rtmr2,
+		[TDX_GUEST_MR_RTMR3] = TDREPORT_rtmr3,
+	};
+	int ret;
+
+	if (!tdx_guest_device_valid(dev))
+		return -ENODEV;
+	if (mr >= ARRAY_SIZE(offsets) || !value)
+		return -EINVAL;
+	scoped_cond_guard(mutex_intr, return -EINTR, &mr_lock) {
+		ret = __tdx_do_report(KERNEL_SOCKPTR(NULL),
+				      KERNEL_SOCKPTR(NULL));
+		if (ret)
+			return ret;
+		memcpy(value, tdx_report_buf + offsets[mr],
+		       SHA384_DIGEST_SIZE);
+	}
+	return 0;
+}
+
+static int tdx_guest_rtmr_extend(struct device *dev, unsigned int rtmr,
+				 const u8 value[SHA384_DIGEST_SIZE])
+{
+	if (!tdx_guest_device_valid(dev))
+		return -ENODEV;
+	if (rtmr >= 4 || !value)
+		return -EINVAL;
+	return tdx_do_extend(rtmr, value);
+}
+
 #define TDX_MR_(r) .mr_value = (void *)TDREPORT_##r, TSM_MR_(r, SHA384)
 static struct tsm_measurement_register tdx_mrs[] = {
 	{ TDX_MR_(rtmr0) | TSM_MR_F_RTMR },
@@ -135,6 +223,12 @@ static const struct attribute_group *tdx_mr_init(void)
 	rc = tdx_mr_refresh(&tdx_measurements);
 	if (rc)
 		return ERR_PTR(rc);
+	memcpy(tdx_guest_info.mrconfigid,
+	       buf + TDREPORT_mrconfigid, SHA384_DIGEST_SIZE);
+	memcpy(tdx_guest_info.mrowner,
+	       buf + TDREPORT_mrowner, SHA384_DIGEST_SIZE);
+	memcpy(tdx_guest_info.mrownerconfig,
+	       buf + TDREPORT_mrownerconfig, SHA384_DIGEST_SIZE);
 
 	/*
 	 * @mr_value was initialized with the offset only, while the base
@@ -191,6 +285,8 @@ struct tdx_quote_buf {
 	u8 data[];
 };
 
+static_assert(TDX_QUOTE_MAX_LEN == TDX_GUEST_QUOTE_MAX_LEN);
+
 /* Quote data buffer */
 static void *quote_data;
 
@@ -265,15 +361,18 @@ static int wait_for_quote_completion(struct tdx_quote_buf *quote_buf, u32 timeou
 	return (i == timeout) ? -ETIMEDOUT : 0;
 }
 
-static int tdx_report_new_locked(struct tsm_report *report, void *data)
+static int __tdx_guest_quote_get(const u8 *reportdata, size_t length,
+				 void *out, size_t capacity,
+				 size_t *out_length)
 {
-	u8 *buf;
 	struct tdx_quote_buf *quote_buf = quote_data;
-	struct tsm_report_desc *desc = &report->desc;
 	u32 out_len;
 	int ret;
 	u64 err;
 
+	lockdep_assert_held(&quote_lock);
+	if (!reportdata || length != TDX_REPORTDATA_LEN || !out || !out_length)
+		return -EINVAL;
 	/*
 	 * If the previous request is timedout or interrupted, and the
 	 * Quote buf status is still in GET_QUOTE_IN_FLIGHT (owned by
@@ -282,16 +381,13 @@ static int tdx_report_new_locked(struct tsm_report *report, void *data)
 	if (quote_buf->status == GET_QUOTE_IN_FLIGHT)
 		return -EBUSY;
 
-	if (desc->inblob_len != TDX_REPORTDATA_LEN)
-		return -EINVAL;
-
 	memset(quote_data, 0, GET_QUOTE_BUF_SIZE);
 
 	/* Update Quote buffer header */
 	quote_buf->version = GET_QUOTE_CMD_VER;
 	quote_buf->in_len = TDX_REPORT_LEN;
 
-	ret = tdx_do_report(KERNEL_SOCKPTR(desc->inblob),
+	ret = tdx_do_report(KERNEL_SOCKPTR((void *)reportdata),
 			    KERNEL_SOCKPTR(quote_buf->data));
 	if (ret)
 		return ret;
@@ -317,13 +413,10 @@ static int tdx_report_new_locked(struct tsm_report *report, void *data)
 
 	if (out_len > TDX_QUOTE_MAX_LEN)
 		return -EFBIG;
-
-	buf = kvmemdup(quote_buf->data, out_len, GFP_KERNEL);
-	if (!buf)
-		return -ENOMEM;
-
-	report->outblob = buf;
-	report->outblob_len = out_len;
+	if (out_len > capacity)
+		return -EMSGSIZE;
+	memcpy(out, quote_buf->data, out_len);
+	*out_length = out_len;
 
 	/*
 	 * TODO: parse the PEM-formatted cert chain out of the quote buffer when
@@ -333,6 +426,39 @@ static int tdx_report_new_locked(struct tsm_report *report, void *data)
 	return ret;
 }
 
+static int tdx_guest_quote_get(struct device *dev, const u8 *reportdata,
+			       size_t length, void *out, size_t capacity,
+			       size_t *out_length)
+{
+	if (!tdx_guest_device_valid(dev))
+		return -ENODEV;
+	scoped_cond_guard(mutex_intr, return -EINTR, &quote_lock)
+		return __tdx_guest_quote_get(reportdata, length, out,
+					     capacity, out_length);
+	return 0;
+}
+
+static int tdx_report_new_locked(struct tsm_report *report, void *data)
+{
+	struct tsm_report_desc *desc = &report->desc;
+	size_t length;
+	void *buf;
+	int ret;
+
+	buf = kvmalloc(TDX_QUOTE_MAX_LEN, GFP_KERNEL);
+	if (!buf)
+		return -ENOMEM;
+	ret = __tdx_guest_quote_get(desc->inblob, desc->inblob_len,
+				    buf, TDX_QUOTE_MAX_LEN, &length);
+	if (ret) {
+		kvfree(buf);
+		return ret;
+	}
+	report->outblob = buf;
+	report->outblob_len = length;
+	return 0;
+}
+
 static int tdx_report_new(struct tsm_report *report, void *data)
 {
 	scoped_cond_guard(mutex_intr, return -EINTR, &quote_lock)
@@ -402,6 +528,68 @@ static const struct tsm_report_ops tdx_tsm_ops = {
 	.report_bin_attr_visible = tdx_report_bin_attr_visible,
 };
 
+static const struct tdx_guest_ops tdx_guest_ops = {
+	.info_get = tdx_guest_info_get,
+	.report_get = tdx_guest_report_get,
+	.quote_get = tdx_guest_quote_get,
+	.mr_read = tdx_guest_mr_read,
+	.rtmr_extend = tdx_guest_rtmr_extend,
+};
+
+static bool tdx_client_attached;
+
+static int tdx_guest_client_attach(void)
+{
+	void *priv;
+
+	lockdep_assert_held(&client_lock);
+	if (!tdx_client || !tdx_service_ready)
+		return 0;
+	priv = tdx_client->add(tdx_misc_dev.this_device, &tdx_guest_ops);
+	if (IS_ERR(priv))
+		return PTR_ERR(priv);
+	tdx_client_priv = priv;
+	tdx_client_attached = true;
+	return 0;
+}
+
+static void tdx_guest_client_detach(void)
+{
+	lockdep_assert_held(&client_lock);
+	if (!tdx_client_attached)
+		return;
+	tdx_client->remove(tdx_client_priv);
+	tdx_client_priv = NULL;
+	tdx_client_attached = false;
+}
+
+int tdx_guest_client_register(const struct tdx_guest_client *client)
+{
+	int ret;
+
+	if (!client || !client->add || !client->remove)
+		return -EINVAL;
+	guard(mutex)(&client_lock);
+	if (tdx_client)
+		return -EBUSY;
+	tdx_client = client;
+	ret = tdx_guest_client_attach();
+	if (ret)
+		tdx_client = NULL;
+	return ret;
+}
+EXPORT_SYMBOL_NS_GPL(tdx_guest_client_register, "TDX_GUEST");
+
+void tdx_guest_client_unregister(const struct tdx_guest_client *client)
+{
+	guard(mutex)(&client_lock);
+	if (WARN_ON_ONCE(client != tdx_client))
+		return;
+	tdx_guest_client_detach();
+	tdx_client = NULL;
+}
+EXPORT_SYMBOL_NS_GPL(tdx_guest_client_unregister, "TDX_GUEST");
+
 static int __init tdx_guest_init(void)
 {
 	int ret;
@@ -427,9 +615,19 @@ static int __init tdx_guest_init(void)
 	ret = tsm_report_register(&tdx_tsm_ops, NULL);
 	if (ret)
 		goto free_quote;
+	scoped_guard(mutex, &client_lock) {
+		tdx_service_ready = true;
+		ret = tdx_guest_client_attach();
+		if (ret)
+			tdx_service_ready = false;
+	}
+	if (ret)
+		goto unregister_tsm;
 
 	return 0;
 
+unregister_tsm:
+	tsm_report_unregister(&tdx_tsm_ops);
 free_quote:
 	free_quote_buf(quote_data);
 free_misc:
@@ -443,6 +641,10 @@ module_init(tdx_guest_init);
 
 static void __exit tdx_guest_exit(void)
 {
+	scoped_guard(mutex, &client_lock) {
+		tdx_guest_client_detach();
+		tdx_service_ready = false;
+	}
 	tsm_report_unregister(&tdx_tsm_ops);
 	free_quote_buf(quote_data);
 	misc_deregister(&tdx_misc_dev);
diff --git a/include/linux/attestation.h b/include/linux/attestation.h
new file mode 100644
index 0000000000000..0fd806ea77d8d
--- /dev/null
+++ b/include/linux/attestation.h
@@ -0,0 +1,138 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+#ifndef _LINUX_ATTESTATION_H
+#define _LINUX_ATTESTATION_H
+
+#include <crypto/hash.h>
+#include <linux/types.h>
+
+#include <uapi/linux/ctlv_attestation_gen.h>
+#include <uapi/linux/hash_info.h>
+
+struct attestation;
+struct ctlv_blob;
+
+/**
+ * struct attestation_digest - One MR digest.
+ * @algorithm: hash algorithm
+ * @data: digest bytes
+ */
+struct attestation_digest {
+	enum hash_algo algorithm;
+	u8 data[HASH_MAX_DIGESTSIZE];
+};
+
+/**
+ * struct attestation_digest_set - Digests ordered as the MR algorithms.
+ * @values_count: number of digests
+ * @values: digest array
+ */
+struct attestation_digest_set {
+	size_t values_count;
+	struct attestation_digest *values;
+};
+
+/**
+ * struct attestation_mr_props - Immutable MR properties.
+ * @id: provider-unique MR ID
+ * @name: MR name
+ * @algorithms: ordered hash algorithms
+ * @algorithms_count: number of algorithms
+ * @has_register_index: whether @register_index is valid
+ * @register_index: native register index
+ * @readable: MR can be read
+ * @extendable: MR can be extended
+ */
+struct attestation_mr_props {
+	unsigned int id;
+	const char *name;
+	const enum hash_algo *algorithms;
+	size_t algorithms_count;
+	bool has_register_index;
+	unsigned int register_index;
+	bool readable;
+	bool extendable;
+};
+
+/**
+ * struct attestation_evidence_supported_object - Evidence output description.
+ * @format: evidence format name
+ * @max_length: maximum output bytes
+ * @binds_mrs: evidence validity depends on MR state
+ */
+struct attestation_evidence_supported_object {
+	const char *format;
+	size_t max_length;
+	bool binds_mrs;
+};
+
+/**
+ * struct attestation_evidence_caps - Immutable evidence capabilities.
+ * @min_challenge_length: minimum challenge bytes
+ * @max_challenge_length: maximum challenge bytes
+ * @max_total_output_length: maximum bytes across all objects
+ * @objects: supported evidence objects
+ * @objects_count: number of objects
+ */
+struct attestation_evidence_caps {
+	size_t min_challenge_length;
+	size_t max_challenge_length;
+	size_t max_total_output_length;
+	const struct attestation_evidence_supported_object *objects;
+	size_t objects_count;
+};
+
+/**
+ * struct attestation_evidence_object_request - One resolved output object.
+ * @supported_object: matching capability entry
+ * @output: resolved output blob
+ */
+struct attestation_evidence_object_request {
+	const struct attestation_evidence_supported_object *supported_object;
+	struct ctlv_blob *output;
+};
+
+/**
+ * struct attestation_evidence_request - Validated evidence request.
+ * @challenge: challenge bytes
+ * @challenge_length: challenge length
+ * @objects: requested output objects
+ * @objects_count: number of objects
+ */
+struct attestation_evidence_request {
+	const u8 *challenge;
+	size_t challenge_length;
+	const struct attestation_evidence_object_request *objects;
+	size_t objects_count;
+};
+
+/**
+ * struct attestation_evidence_result - Provider evidence result.
+ * @object_lengths: produced length for every requested object
+ */
+struct attestation_evidence_result {
+	size_t *object_lengths;
+};
+
+/**
+ * struct attestation_provider - Immutable provider operations and properties.
+ * @evidence_get: produce requested evidence
+ * @mr_read: read one MR
+ * @mr_extend: extend one MR
+ * @evidence_caps: evidence capabilities, or NULL
+ * @mrs: fixed MR properties
+ * @mrs_count: number of fixed MRs
+ */
+struct attestation_provider {
+	int (*evidence_get)(struct attestation *att,
+			    const struct attestation_evidence_request *request,
+			    struct attestation_evidence_result *result);
+	int (*mr_read)(struct attestation *att, unsigned int mr_id,
+		       struct attestation_digest_set *values);
+	int (*mr_extend)(struct attestation *att, unsigned int mr_id,
+			 const struct attestation_digest_set *values);
+	const struct attestation_evidence_caps *evidence_caps;
+	const struct attestation_mr_props *mrs;
+	size_t mrs_count;
+};
+
+#endif /* _LINUX_ATTESTATION_H */
diff --git a/include/linux/ctlv.h b/include/linux/ctlv.h
new file mode 100644
index 0000000000000..5f59acac7dc44
--- /dev/null
+++ b/include/linux/ctlv.h
@@ -0,0 +1,249 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES
+ *
+ * CTLV family API.
+ */
+#ifndef _LINUX_CTLV_H
+#define _LINUX_CTLV_H
+
+#include <linux/types.h>
+
+#include <uapi/linux/ctlv.h>
+
+struct ctlv_device;
+struct ctlv_family;
+struct ctlv_msg;
+struct ctlv_op_ctx;
+struct ctlv_schema_tree;
+
+/**
+ * struct ctlv_cursor - One attr position in one message.
+ * @msg: the message this position is in, core-private bookkeeping
+ * @attr: the attr itself, or NULL when a lookup found nothing
+ * @parent: reading, the nest containing @attr, NULL at the root
+ * @up: writing, cursor of the nest containing @attr, NULL at the root. The
+ *	chain of them is the open-nest stack
+ * @start: writing, where @attr begins in the message. An append reaches what
+ *	it lengthens through the buffer rather than through @attr, that buffer
+ *	being the core's own
+ * @tree: schema tree the node belongs to, which is a fill's own tree for an
+ *	attr that arrived through one
+ * @node: index of the node within @tree
+ * @depth: nesting levels above this position, the root being zero
+ * @index_nest_scope: schema scope used to read members of the physical nest
+ * @index_scope: core-private schema scope containing this attr
+ *
+ * Fixed-size, so family code can put a child cursor on the stack. The members
+ * belong to the core: a family reaches a message through what was generated
+ * for the op it answers. One direction at a time, a helper of the other
+ * direction refusing the cursor.
+ */
+struct ctlv_cursor {
+	struct ctlv_msg *msg;
+	const struct ctlv_attr *attr;
+	const struct ctlv_attr *parent;
+	struct ctlv_cursor *up;
+	size_t start;
+	const struct ctlv_schema_tree *tree;
+	u32 node;
+	u32 depth;
+	u32 index_nest_scope;
+	u32 index_scope;
+};
+
+/**
+ * ctlv_priv_parent - Get the direct parent family private data.
+ * @priv: core-allocated private data passed to a family callback
+ *
+ * Return: parent private data, or NULL for the root family.
+ */
+void *ctlv_priv_parent(const void *priv);
+
+/**
+ * ctlv_priv_child - Get the direct child family private data.
+ * @priv: core-allocated private data passed to a family callback
+ *
+ * Return: child private data, or NULL for the device family.
+ */
+void *ctlv_priv_child(const void *priv);
+
+struct device;
+
+/**
+ * ctlv_device_parent - Get the backing device.
+ * @ctlvdev: CTLV device
+ *
+ * Return: backing device passed to ctlv_create().
+ */
+struct device *ctlv_device_parent(const struct ctlv_device *ctlvdev);
+
+/**
+ * ctlv_create - Create and register a CTLV device.
+ * @parent_dev: backing device
+ * @family: device family
+ * @init_info: family initialization data
+ *
+ * Return: CTLV device, or an error pointer.
+ */
+struct ctlv_device *ctlv_create(struct device *parent_dev,
+				const struct ctlv_family *family,
+				const void *init_info);
+
+/**
+ * ctlv_destroy - Unregister and destroy a CTLV device.
+ * @ctlvdev: CTLV device
+ */
+void ctlv_destroy(struct ctlv_device *ctlvdev);
+
+/**
+ * ctlv_nest_end - Finish an output nest.
+ * @child: nest cursor returned by a generated start helper
+ */
+void ctlv_nest_end(struct ctlv_cursor *child);
+
+/**
+ * ctlv_stub_fill - Delegate an extension-point output nest.
+ * @ctx: operation context
+ * @request: validated request root
+ * @nest: output nest selected by the generated helper
+ *
+ * Return: filling callback result, or 0 for an unfilled point.
+ */
+int ctlv_stub_fill(struct ctlv_op_ctx *ctx, const struct ctlv_cursor *request,
+		   struct ctlv_cursor *nest);
+
+/**
+ * ctlv_op_error - Record an operation error message.
+ * @ctx: operation context
+ * @error: negative error to return
+ * @message: message copied into the operation result
+ *
+ * Return: @error, or -EINVAL if @error is invalid.
+ */
+int ctlv_op_error(struct ctlv_op_ctx *ctx, int error, const char *message);
+
+/**
+ * ctlv_op_errorf - Format an operation error message.
+ * @ctx: operation context
+ * @error: negative error to return
+ * @fmt: printf format and arguments
+ *
+ * Return: @error, or -EINVAL if @error is invalid.
+ */
+__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 nests, whose cursors must remain live.
+ */
+/**
+ * ctlv_op_query_generation - Get a query continuation generation.
+ * @ctx: query operation context
+ *
+ * Return: generation supplied by the previous fragment, or zero initially.
+ */
+u64 ctlv_op_query_generation(const struct ctlv_op_ctx *ctx);
+
+/**
+ * ctlv_op_query_cursor - Get a query continuation cursor.
+ * @ctx: query operation context
+ *
+ * Return: cursor supplied by the previous fragment, or zero initially.
+ */
+u64 ctlv_op_query_cursor(const struct ctlv_op_ctx *ctx);
+
+/**
+ * ctlv_op_query_more - Complete a query fragment with more data pending.
+ * @ctx: query operation context
+ * @generation: current data generation
+ * @next_cursor: nonzero cursor for the next fragment
+ *
+ * Return: 0, or a negative error.
+ */
+int ctlv_op_query_more(struct ctlv_op_ctx *ctx, u64 generation,
+		       u64 next_cursor);
+
+/**
+ * ctlv_op_query_done - Complete the last query fragment.
+ * @ctx: query operation context
+ * @generation: current data generation
+ *
+ * Return: 0, or a negative error.
+ */
+int ctlv_op_query_done(struct ctlv_op_ctx *ctx, u64 generation);
+
+struct ctlv_blob;
+
+/**
+ * ctlv_blob_put - Release a resolved blob.
+ * @blob: blob returned by a generated resolve helper
+ *
+ * Return: 0, or a negative error.
+ */
+int ctlv_blob_put(struct ctlv_blob *blob);
+
+/**
+ * ctlv_blob_len - Get a resolved blob's length.
+ * @blob: resolved blob
+ *
+ * Return: blob length in bytes.
+ */
+u64 ctlv_blob_len(const struct ctlv_blob *blob);
+
+/**
+ * ctlv_blob_read - Copy bytes from a resolved input blob.
+ * @blob: resolved blob
+ * @offset: byte offset
+ * @dst: destination buffer
+ * @len: number of bytes
+ *
+ * Return: 0, or a negative error.
+ */
+int ctlv_blob_read(struct ctlv_blob *blob, u64 offset, void *dst, size_t len);
+
+/**
+ * ctlv_blob_write - Copy bytes to a resolved output blob.
+ * @blob: resolved blob
+ * @offset: byte offset
+ * @src: source buffer
+ * @len: number of bytes
+ *
+ * Return: 0, or a negative error.
+ */
+int ctlv_blob_write(struct ctlv_blob *blob, u64 offset, const void *src,
+		    size_t len);
+
+/**
+ * ctlv_event_lost - Report an event that could not be created.
+ * @ctlvdev: CTLV device
+ * @op_id: event operation ID
+ *
+ * This does not allocate or sleep. It is not for interrupt context.
+ */
+void ctlv_event_lost(struct ctlv_device *ctlvdev, u64 op_id);
+
+/**
+ * ctlv_event_emit - Validate and publish a completed event.
+ * @ctx: context returned by a generated event create helper
+ *
+ * This consumes @ctx. It is not for interrupt context.
+ *
+ * Return: 0, or a negative error.
+ */
+int ctlv_event_emit(struct ctlv_op_ctx *ctx);
+
+/**
+ * ctlv_event_abort - Discard an event under construction.
+ * @ctx: context returned by a generated event create helper
+ *
+ * This consumes @ctx. It is not for interrupt context.
+ */
+void ctlv_event_abort(struct ctlv_op_ctx *ctx);
+
+#endif /* _LINUX_CTLV_H */
diff --git a/include/linux/ctlv_family.h b/include/linux/ctlv_family.h
new file mode 100644
index 0000000000000..66e62733f9057
--- /dev/null
+++ b/include/linux/ctlv_family.h
@@ -0,0 +1,551 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES
+ *
+ * CTLV family metadata and generated-code support.
+ */
+#ifndef _LINUX_CTLV_FAMILY_H
+#define _LINUX_CTLV_FAMILY_H
+
+#include <linux/ctlv.h>
+#include <linux/gfp_types.h>
+#include <linux/kobject.h>
+#include <linux/types.h>
+
+#include <uapi/linux/ctlv.h>
+
+/* op-schema-get needs one level to describe the declared schema. */
+#define CTLV_MAX_DECLARED_NEST_DEPTH (CTLV_MAX_NEST_DEPTH - 1)
+
+struct ctlv_node_schema {
+	u64 attr_id;
+	u8 kind;
+	u8 unit;
+	s8 scale;
+	bool reenters;
+	u32 max_occurrences;
+	u32 first_child;
+	u32 children_count;
+	u32 required_children_count;
+	union {
+		struct {
+			u64 min;
+			u64 max;
+		} range;
+		u64 flags_mask;
+		struct {
+			u32 min_len;
+			u32 max_len;
+		} length;
+		struct {
+			u64 max_len;
+			u32 alignment;
+			u16 backings;
+			u8 direction;
+		} blob;
+	};
+};
+
+#define CTLV_NODE_SCHEMA_UNLIMITED 0
+
+#define __CTLV_NODE_SCHEMA(_attr, _kind, _occurrences, ...)	\
+	{ .attr_id = (_attr), .kind = (_kind),			\
+	  .max_occurrences = (_occurrences), __VA_ARGS__ }
+
+#define __CTLV_NODE_SCHEMA_CHILDREN(_first, _count, _required)	\
+	.first_child = (_first), .children_count = (_count),	\
+	.required_children_count = (_required)
+
+#define CTLV_NODE_SCHEMA_ROOT(_first, _count, _required)	\
+	__CTLV_NODE_SCHEMA(CTLV_ATTR_ROOT, CTLV_SCHEMA_NEST, 1,	\
+			   __CTLV_NODE_SCHEMA_CHILDREN(_first, _count, _required))
+
+#define CTLV_NODE_SCHEMA_NEST(_attr, _occurrences, _first, _count, _required) \
+	__CTLV_NODE_SCHEMA(_attr, CTLV_SCHEMA_NEST, _occurrences,	\
+			   __CTLV_NODE_SCHEMA_CHILDREN(_first, _count, _required))
+
+#define CTLV_NODE_SCHEMA_NEST_REENTERS(_attr, _occurrences, _first, _count, _required) \
+	__CTLV_NODE_SCHEMA(_attr, CTLV_SCHEMA_NEST, _occurrences,	\
+			   .reenters = true,				\
+			   __CTLV_NODE_SCHEMA_CHILDREN(_first, _count, _required))
+
+#define CTLV_NODE_SCHEMA_UINT(_attr, _occurrences, _min, _max)	\
+	__CTLV_NODE_SCHEMA(_attr, CTLV_SCHEMA_UINT, _occurrences,	\
+			   .range = { .min = (_min), .max = (_max) })
+
+#define CTLV_NODE_SCHEMA_UINT_UNIT(_attr, _occurrences, _min, _max, _unit, _scale) \
+	__CTLV_NODE_SCHEMA(_attr, CTLV_SCHEMA_UINT, _occurrences,	\
+			   .range = { .min = (_min), .max = (_max) },	\
+			   .unit = (_unit), .scale = (_scale))
+
+#define CTLV_NODE_SCHEMA_SINT(_attr, _occurrences, _min, _max)	\
+	__CTLV_NODE_SCHEMA(_attr, CTLV_SCHEMA_SINT, _occurrences,	\
+			   .range = { .min = (_min), .max = (_max) })
+
+#define CTLV_NODE_SCHEMA_SINT_UNIT(_attr, _occurrences, _min, _max, _unit, _scale) \
+	__CTLV_NODE_SCHEMA(_attr, CTLV_SCHEMA_SINT, _occurrences,	\
+			   .range = { .min = (_min), .max = (_max) },	\
+			   .unit = (_unit), .scale = (_scale))
+
+#define CTLV_NODE_SCHEMA_ENUM(_attr, _occurrences, _max)	\
+	__CTLV_NODE_SCHEMA(_attr, CTLV_SCHEMA_ENUM, _occurrences,	\
+			   .range = { .min = 1, .max = (_max) })
+
+#define CTLV_NODE_SCHEMA_FLAGS(_attr, _occurrences, _mask)	\
+	__CTLV_NODE_SCHEMA(_attr, CTLV_SCHEMA_FLAGS, _occurrences,	\
+			   .flags_mask = (_mask))
+
+#define CTLV_NODE_SCHEMA_BOOL(_attr, _occurrences)		\
+	__CTLV_NODE_SCHEMA(_attr, CTLV_SCHEMA_BOOL, _occurrences)
+
+#define CTLV_NODE_SCHEMA_STRING(_attr, _occurrences, _min, _max) \
+	__CTLV_NODE_SCHEMA(_attr, CTLV_SCHEMA_STRING, _occurrences,	\
+			   .length = { .min_len = (_min), .max_len = (_max) })
+
+#define CTLV_NODE_SCHEMA_BINARY(_attr, _occurrences, _min, _max) \
+	__CTLV_NODE_SCHEMA(_attr, CTLV_SCHEMA_BINARY, _occurrences,	\
+			   .length = { .min_len = (_min), .max_len = (_max) })
+
+#define CTLV_NODE_SCHEMA_BLOB(_attr, _occurrences, _max, _alignment, _backings, _dir) \
+	__CTLV_NODE_SCHEMA(_attr, CTLV_SCHEMA_BLOB, _occurrences,	\
+			   .blob = { .max_len = (_max),			\
+				     .alignment = (_alignment),		\
+				     .backings = (_backings),		\
+				     .direction = (_dir) })
+
+struct ctlv_stub_schema {
+	u16 family_id;
+	u32 set_id;
+	u32 node;
+	bool optional;
+};
+
+#define __CTLV_STUB_SCHEMA(_family, _set, _node, _optional)	\
+	{ .family_id = (_family), .set_id = (_set),		\
+	  .node = (_node), .optional = (_optional) }
+
+#define CTLV_STUB_SCHEMA(_family, _set, _node)			\
+	__CTLV_STUB_SCHEMA(_family, _set, _node, false)
+
+#define CTLV_STUB_SCHEMA_OPTIONAL(_family, _set, _node)		\
+	__CTLV_STUB_SCHEMA(_family, _set, _node, true)
+
+struct ctlv_schema_tree {
+	const struct ctlv_node_schema *node_schemas;
+	u32 node_schemas_count;
+	const struct ctlv_stub_schema *stub_schemas;
+	u32 stub_schemas_count;
+};
+
+#define CTLV_SCHEMA_TREE(_name) {				\
+	.node_schemas = _name##_node_schemas,			\
+	.node_schemas_count = ARRAY_SIZE(_name##_node_schemas),	\
+}
+
+#define CTLV_SCHEMA_TREE_STUBS(_name) {				\
+	.node_schemas = _name##_node_schemas,			\
+	.node_schemas_count = ARRAY_SIZE(_name##_node_schemas),	\
+	.stub_schemas = _name##_stub_schemas,			\
+	.stub_schemas_count = ARRAY_SIZE(_name##_stub_schemas),	\
+}
+
+#define CTLV_SCHEMA_TREE_NONE() { }
+
+struct ctlv_stub_fill_schema {
+	u16 family_id;
+	u32 set_id;
+	struct ctlv_schema_tree members;
+};
+
+#define CTLV_STUB_FILL_SCHEMA(_family, _set, _name) {		\
+	.family_id = (_family),					\
+	.set_id = (_set),					\
+	.members = CTLV_SCHEMA_TREE(_name##_fill),		\
+}
+
+struct ctlv_op_sizes {
+	u32 request_max_len;
+	u32 action_reply_max_len;
+	u32 query_reply_min_len;
+	u32 query_reply_suggested_len;
+	u32 event_record_max_len;
+};
+
+struct ctlv_op_schema {
+	u64 op_id;
+	u8 type;
+	u8 fd_access;
+	u8 availability;
+	bool optional;
+	bool pre_post;
+	struct ctlv_schema_tree request;
+	struct ctlv_schema_tree reply;
+	struct ctlv_op_sizes sizes;
+};
+
+#define __CTLV_OP_SCHEMA(_op, _type, _availability, ...)	\
+	{ .op_id = (_op), .type = (_type),			\
+	  .availability = (_availability), __VA_ARGS__ }
+
+#define CTLV_OP_SCHEMA_ACTION(_op, _access, _availability, _request_len, _reply_len, \
+			      _request, _reply, ...)			\
+	__CTLV_OP_SCHEMA(_op, CTLV_OP_TYPE_ACTION, _availability,	\
+			 .fd_access = (_access),			\
+			 .request = _request, .reply = _reply,		\
+			 .sizes = {					\
+				.request_max_len = (_request_len),	\
+				.action_reply_max_len = (_reply_len),	\
+			 },						\
+			 __VA_ARGS__)
+
+#define CTLV_OP_SCHEMA_QUERY(_op, _access, _availability, _request_len, _reply_min, \
+			     _reply_suggested, _request, _reply, ...)	\
+	__CTLV_OP_SCHEMA(_op, CTLV_OP_TYPE_QUERY, _availability,	\
+			 .fd_access = (_access),			\
+			 .request = _request, .reply = _reply,		\
+			 .sizes = {					\
+				.request_max_len = (_request_len),	\
+				.query_reply_min_len = (_reply_min),	\
+				.query_reply_suggested_len =		\
+					(_reply_suggested),		\
+			 },						\
+			 __VA_ARGS__)
+
+#define CTLV_OP_SCHEMA_EVENT(_op, _record_len, _reply, ...)	\
+	__CTLV_OP_SCHEMA(_op, CTLV_OP_TYPE_EVENT,		\
+			 CTLV_OP_AVAILABILITY_FIXED,			\
+			 .reply = _reply,				\
+			 .sizes = {					\
+				.event_record_max_len = (_record_len),	\
+			 },						\
+			 __VA_ARGS__)
+
+struct ctlv_family_schema {
+	const char *name;
+	u16 family_id;
+	const struct ctlv_op_schema *ops;
+	u32 ops_count;
+	const struct ctlv_stub_fill_schema *stub_fill_schemas;
+	u32 stub_fill_schemas_count;
+};
+
+/* Leave half of a uevent environment to the device model. */
+#define CTLV_UEVENT_MAX_LEN (UEVENT_BUFFER_SIZE / 2)
+#define CTLV_UEVENT_MAX_VARS (UEVENT_NUM_ENVP / 2)
+
+struct ctlv_input_ref {
+	const struct ctlv_schema_tree *tree;
+	u64 attr_id;
+	u32 node;
+	u32 slot;
+	u8 kind;
+};
+
+typedef int (*ctlv_action_fn)(void *priv, struct ctlv_op_ctx *ctx,
+			      const struct ctlv_cursor *request,
+			      struct ctlv_cursor *reply);
+typedef int (*ctlv_query_fn)(void *priv, struct ctlv_op_ctx *ctx,
+			     const struct ctlv_cursor *request,
+			     struct ctlv_cursor *reply);
+typedef int (*ctlv_op_pre_fn)(void *priv, struct ctlv_op_ctx *ctx);
+typedef void (*ctlv_op_post_fn)(void *priv, struct ctlv_op_ctx *ctx);
+
+struct ctlv_op {
+	union {
+		ctlv_action_fn action;
+		ctlv_query_fn query;
+	};
+	ctlv_op_pre_fn pre;
+	ctlv_op_post_fn post;
+};
+
+#define CTLV_OP_ACTION(_name) { .action = _name##_action }
+#define CTLV_OP_QUERY(_name) { .query = _name##_query }
+#define CTLV_OP_ACTION_PRE_POST(_name)				\
+	{ .action = _name##_action, .pre = _name##_pre,		\
+	  .post = _name##_post }
+#define CTLV_OP_QUERY_PRE_POST(_name)				\
+	{ .query = _name##_query, .pre = _name##_pre,		\
+	  .post = _name##_post }
+
+typedef size_t (*ctlv_family_priv_size_fn)(void);
+typedef const void *(*ctlv_family_pre_init_fn)(const void *init_info);
+typedef int (*ctlv_family_init_fn)(struct ctlv_device *ctlvdev,
+				   const void *init_info, void *priv);
+typedef int (*ctlv_family_post_init_fn)(struct ctlv_device *ctlvdev,
+					void *priv);
+typedef void (*ctlv_family_pre_fini_fn)(struct ctlv_device *ctlvdev,
+					void *priv);
+typedef void (*ctlv_family_fini_fn)(struct ctlv_device *ctlvdev, void *priv);
+
+typedef int (*ctlv_stub_fill_fn)(void *priv, struct ctlv_op_ctx *ctx,
+				 const struct ctlv_cursor *request,
+				 struct ctlv_cursor *nest);
+
+struct ctlv_stub_ops {
+	u16 family_id;
+	u32 set_id;
+	ctlv_stub_fill_fn fill;
+};
+
+#define CTLV_STUB_OPS(_family, _set, _name) {			\
+	.family_id = (_family),					\
+	.set_id = (_set),					\
+	.fill = _name##_fill,					\
+}
+
+struct ctlv_family {
+	const struct ctlv_family_schema *schema;
+	const struct ctlv_family *parent;
+	const struct ctlv_op *ops;
+	u32 ops_count;
+	ctlv_op_pre_fn pre;
+	ctlv_op_post_fn post;
+	ctlv_family_priv_size_fn priv_size;
+	ctlv_family_pre_init_fn pre_init;
+	ctlv_family_init_fn init;
+	ctlv_family_post_init_fn post_init;
+	ctlv_family_pre_fini_fn pre_fini;
+	ctlv_family_fini_fn fini;
+	const struct ctlv_stub_ops *stub_ops;
+	u32 stub_ops_count;
+};
+
+extern const struct ctlv_family ctlv_family;
+
+void ctlv_device_op_provide(struct ctlv_device *ctlvdev, u64 op_id);
+void ctlv_device_op_state_set(struct ctlv_device *ctlvdev, u64 op_id,
+			      bool disabled);
+
+struct ctlv_cursor *
+ctlv_input_attr(struct ctlv_cursor *cursor, const struct ctlv_cursor *nest,
+		struct ctlv_input_ref ref);
+bool ctlv_input_cursor(const struct ctlv_cursor *cursor,
+		       struct ctlv_input_ref ref);
+void ctlv_attr_next(struct ctlv_cursor *cursor);
+bool ctlv_attr_ok(const struct ctlv_cursor *cursor);
+u64 ctlv_attr_u64(const struct ctlv_cursor *cursor);
+s64 ctlv_attr_s64(const struct ctlv_cursor *cursor);
+bool ctlv_attr_bool(const struct ctlv_cursor *cursor);
+const char *ctlv_attr_string(const struct ctlv_cursor *cursor);
+const void *ctlv_attr_binary(const struct ctlv_cursor *cursor, u32 *len);
+
+bool ctlv_put_u64(struct ctlv_cursor *nest, u64 attr_id, u8 kind, u64 value);
+bool ctlv_put_s64(struct ctlv_cursor *nest, u64 attr_id, u8 kind, s64 value);
+bool ctlv_put_bool(struct ctlv_cursor *nest, u64 attr_id, u8 kind, bool value);
+bool ctlv_put_string(struct ctlv_cursor *nest, u64 attr_id, u8 kind,
+		     const char *value);
+bool ctlv_put_binary(struct ctlv_cursor *nest, u64 attr_id, u8 kind,
+		     const void *value, u32 len);
+bool ctlv_nest_start(struct ctlv_cursor *nest, struct ctlv_cursor *child,
+		     u64 attr_id, u8 kind);
+
+struct ctlv_blob *ctlv_blob_resolve(struct ctlv_op_ctx *ctx,
+				    const struct ctlv_cursor *blob);
+struct ctlv_op_ctx *ctlv_event_create(struct ctlv_device *ctlvdev, u64 op_id,
+				      struct ctlv_cursor **event, gfp_t gfp);
+
+#define CTLV_OP_PROVIDE(_name, _op_id)				\
+static inline void _name##_provide(struct ctlv_device *ctlvdev)	\
+{								\
+	ctlv_device_op_provide(ctlvdev, (_op_id));		\
+}
+
+#define CTLV_OP_ENABLE(_name, _op_id)				\
+static inline void _name##_enable(struct ctlv_device *ctlvdev)	\
+{								\
+	ctlv_device_op_state_set(ctlvdev, (_op_id), false);	\
+}
+
+#define CTLV_OP_DISABLE(_name, _op_id)				\
+static inline void _name##_disable(struct ctlv_device *ctlvdev)	\
+{								\
+	ctlv_device_op_state_set(ctlvdev, (_op_id), true);	\
+}
+
+#define CTLV_EVENT_CREATE(_name, _op_id)			\
+static inline struct ctlv_op_ctx *				\
+_name##_create(struct ctlv_device *ctlvdev,			\
+	       struct ctlv_cursor **reply, gfp_t gfp)		\
+{								\
+	return ctlv_event_create(ctlvdev, (_op_id), reply, gfp);	\
+}
+
+#define __CTLV_DEFINE_PUT(_name, _type, _put_fn, _attr_id, _kind) \
+static inline bool _name##_put(struct ctlv_cursor *nest,		\
+			       _type value)			\
+{								\
+	return _put_fn(nest, (_attr_id), (_kind), value);		\
+}
+
+#define CTLV_PUT_U64(_name, _attr_id, _kind)			\
+	__CTLV_DEFINE_PUT(_name, u64, ctlv_put_u64, _attr_id, _kind)
+#define CTLV_PUT_S64(_name, _attr_id, _kind)			\
+	__CTLV_DEFINE_PUT(_name, s64, ctlv_put_s64, _attr_id, _kind)
+#define CTLV_PUT_BOOL(_name, _attr_id, _kind)			\
+	__CTLV_DEFINE_PUT(_name, bool, ctlv_put_bool, _attr_id, _kind)
+#define CTLV_PUT_STRING(_name, _attr_id, _kind)			\
+	__CTLV_DEFINE_PUT(_name, const char *, ctlv_put_string,	\
+			  _attr_id, _kind)
+
+#define CTLV_PUT_BINARY(_name, _attr_id, _kind)			\
+static inline bool _name##_put(struct ctlv_cursor *nest,		\
+			       const void *value, u32 len)		\
+{								\
+	return ctlv_put_binary(nest, (_attr_id), (_kind), value, len); \
+}
+
+#define CTLV_NEST_START(_name, _attr_id, _kind)			\
+static inline bool _name##_start(struct ctlv_cursor *nest,	\
+				 struct ctlv_cursor *nested)	\
+{								\
+	return ctlv_nest_start(nest, nested, (_attr_id), (_kind));	\
+}
+
+#define CTLV_IN_REF(_name, _tree, _attr_id, _node, _slot, _kind) \
+static inline struct ctlv_input_ref _name##_ref(void)		\
+{								\
+	return (struct ctlv_input_ref){				\
+		.tree = (_tree),					\
+		.attr_id = (_attr_id),				\
+		.node = (_node),					\
+		.slot = (_slot),					\
+		.kind = (_kind),					\
+	};							\
+}
+
+#define CTLV_IN_FOR_EACH(_name, _attr, _nest)			\
+	for (struct ctlv_cursor *__ctlv_attr =			\
+		ctlv_input_attr(_attr, _nest, _name##_ref());	\
+	     ctlv_attr_ok(__ctlv_attr);				\
+	     ctlv_attr_next(__ctlv_attr))
+
+#define CTLV_IN_HAS(_name)					\
+static inline bool _name##_present(const struct ctlv_cursor *nest) \
+{								\
+	struct ctlv_cursor attr;				\
+								\
+	ctlv_input_attr(&attr, nest, _name##_ref());		\
+	return ctlv_attr_ok(&attr);				\
+}
+
+#define CTLV_IN_U64(_name)					\
+static inline u64 _name##_get(const struct ctlv_cursor *nest)	\
+{								\
+	struct ctlv_cursor attr;				\
+								\
+	ctlv_input_attr(&attr, nest, _name##_ref());		\
+	return ctlv_attr_u64(&attr);				\
+}
+
+#define CTLV_IN_S64(_name)					\
+static inline s64 _name##_get(const struct ctlv_cursor *nest)	\
+{								\
+	struct ctlv_cursor attr;				\
+								\
+	ctlv_input_attr(&attr, nest, _name##_ref());		\
+	return ctlv_attr_s64(&attr);				\
+}
+
+#define CTLV_IN_BOOL(_name)					\
+static inline bool _name##_get(const struct ctlv_cursor *nest)	\
+{								\
+	struct ctlv_cursor attr;				\
+								\
+	ctlv_input_attr(&attr, nest, _name##_ref());		\
+	return ctlv_attr_bool(&attr);				\
+}
+
+#define CTLV_IN_STRING(_name)					\
+static inline const char *					\
+_name##_get(const struct ctlv_cursor *nest)			\
+{								\
+	struct ctlv_cursor attr;				\
+								\
+	ctlv_input_attr(&attr, nest, _name##_ref());		\
+	return ctlv_attr_string(&attr);				\
+}
+
+#define CTLV_IN_BINARY(_name)					\
+static inline const void *					\
+_name##_get(const struct ctlv_cursor *nest, u32 *len)		\
+{								\
+	struct ctlv_cursor attr;				\
+								\
+	ctlv_input_attr(&attr, nest, _name##_ref());		\
+	return ctlv_attr_binary(&attr, len);			\
+}
+
+#define CTLV_IN_NEST(_name)					\
+static inline void _name##_get(struct ctlv_cursor *nested,	\
+			       const struct ctlv_cursor *nest)	\
+{								\
+	ctlv_input_attr(nested, nest, _name##_ref());		\
+}
+
+#define CTLV_IN_BLOB(_name)					\
+static inline struct ctlv_blob *				\
+_name##_resolve(struct ctlv_op_ctx *ctx,			\
+		const struct ctlv_cursor *nest)			\
+{								\
+	struct ctlv_cursor attr;				\
+								\
+	ctlv_input_attr(&attr, nest, _name##_ref());		\
+	return ctlv_blob_resolve(ctx, &attr);			\
+}
+
+#define CTLV_IN_EACH_U64(_name)					\
+static inline u64 _name##_get(const struct ctlv_cursor *attr)	\
+{								\
+	if (!ctlv_input_cursor(attr, _name##_ref()))		\
+		return 0;					\
+	return ctlv_attr_u64(attr);				\
+}
+
+#define CTLV_IN_EACH_S64(_name)					\
+static inline s64 _name##_get(const struct ctlv_cursor *attr)	\
+{								\
+	if (!ctlv_input_cursor(attr, _name##_ref()))		\
+		return 0;					\
+	return ctlv_attr_s64(attr);				\
+}
+
+#define CTLV_IN_EACH_BOOL(_name)				\
+static inline bool _name##_get(const struct ctlv_cursor *attr)	\
+{								\
+	if (!ctlv_input_cursor(attr, _name##_ref()))		\
+		return false;					\
+	return ctlv_attr_bool(attr);				\
+}
+
+#define CTLV_IN_EACH_STRING(_name)				\
+static inline const char *					\
+_name##_get(const struct ctlv_cursor *attr)			\
+{								\
+	if (!ctlv_input_cursor(attr, _name##_ref()))		\
+		return NULL;					\
+	return ctlv_attr_string(attr);				\
+}
+
+#define CTLV_IN_EACH_BINARY(_name)				\
+static inline const void *					\
+_name##_get(const struct ctlv_cursor *attr, u32 *len)		\
+{								\
+	if (!ctlv_input_cursor(attr, _name##_ref())) {		\
+		*len = 0;					\
+		return NULL;					\
+	}							\
+	return ctlv_attr_binary(attr, len);			\
+}
+
+#define CTLV_IN_EACH_BLOB(_name)				\
+static inline struct ctlv_blob *				\
+_name##_resolve(struct ctlv_op_ctx *ctx,			\
+		const struct ctlv_cursor *attr)			\
+{								\
+	if (!ctlv_input_cursor(attr, _name##_ref()))		\
+		return ERR_PTR(-EINVAL);				\
+	return ctlv_blob_resolve(ctx, attr);			\
+}
+
+#endif /* _LINUX_CTLV_FAMILY_H */
diff --git a/include/linux/ctlv_gen.h b/include/linux/ctlv_gen.h
new file mode 100644
index 0000000000000..e389803449a00
--- /dev/null
+++ b/include/linux/ctlv_gen.h
@@ -0,0 +1,137 @@
+/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) */
+/* Do not edit, regenerate with tools/ctlv/ctlv-regen.sh, from: */
+/*	Documentation/ctlv/specs/ctlv.yaml */
+/* CTLV-GEN kernel header */
+
+/* Kernel metadata and family API of the ctlv CTLV family. */
+
+#ifndef _LINUX_CTLV_GEN_H
+#define _LINUX_CTLV_GEN_H
+
+#include <linux/ctlv_family.h>
+#include <linux/err.h>
+#include <linux/errno.h>
+
+#include <uapi/linux/ctlv_gen.h>
+
+/* Ops this family declares, in declaration order. */
+extern const struct ctlv_op_schema ctlv_op_schemas[];
+
+extern const struct ctlv_family_schema ctlv_schema;
+
+/* The error-info message, built by the core. */
+#define CTLV_ERROR_INFO_MAX_LEN 432
+
+extern const struct ctlv_schema_tree ctlv_error_info_schema;
+
+/* Implemented by the CTLV core, one per action and query it declares. */
+int ctlv_families_dump_query(void *priv, struct ctlv_op_ctx *ctx, const struct ctlv_cursor *request,
+			     struct ctlv_cursor *reply);
+int ctlv_ops_dump_query(void *priv, struct ctlv_op_ctx *ctx, const struct ctlv_cursor *request,
+			struct ctlv_cursor *reply);
+int ctlv_op_schema_get_query(void *priv, struct ctlv_op_ctx *ctx, const struct ctlv_cursor *request,
+			     struct ctlv_cursor *reply);
+int ctlv_subscriptions_add_action(void *priv, struct ctlv_op_ctx *ctx,
+				  const struct ctlv_cursor *request, struct ctlv_cursor *reply);
+int ctlv_subscriptions_remove_action(void *priv, struct ctlv_op_ctx *ctx,
+				     const struct ctlv_cursor *request, struct ctlv_cursor *reply);
+int ctlv_event_queue_get_query(void *priv, struct ctlv_op_ctx *ctx,
+			       const struct ctlv_cursor *request, struct ctlv_cursor *reply);
+int ctlv_event_queue_set_action(void *priv, struct ctlv_op_ctx *ctx,
+				const struct ctlv_cursor *request, struct ctlv_cursor *reply);
+
+/* Root-family hooks around every core action or query. */
+int ctlv_op_pre(void *priv, struct ctlv_op_ctx *ctx);
+void ctlv_op_post(void *priv, struct ctlv_op_ctx *ctx);
+
+/* Core-allocated family priv lifecycle. */
+size_t ctlv_priv_size(void);
+int ctlv_init(struct ctlv_device *ctlvdev, const void *init_info, void *priv);
+void ctlv_fini(struct ctlv_device *ctlvdev, void *priv);
+
+extern const struct ctlv_family ctlv_family;
+
+#ifndef _CTLV_GENERATED_METADATA_ONLY
+
+/* Reading a validated message. A blob has a resolver instead of a getter. */
+CTLV_IN_REF(ctlv_op_schema_get_op_id, &ctlv_op_schemas[2].request, CTLV_ATTR_OP_ID, 0, 0,
+	    CTLV_SCHEMA_UINT)
+CTLV_IN_HAS(ctlv_op_schema_get_op_id)
+CTLV_IN_U64(ctlv_op_schema_get_op_id)
+CTLV_IN_REF(ctlv_subscriptions_add_event_op_id, &ctlv_op_schemas[3].request, CTLV_ATTR_EVENT_OP_ID,
+	    0, 0, CTLV_SCHEMA_UINT)
+#define ctlv_subscriptions_add_event_op_id_for_each(_attr, _nest) \
+	CTLV_IN_FOR_EACH(ctlv_subscriptions_add_event_op_id, _attr, _nest)
+CTLV_IN_EACH_U64(ctlv_subscriptions_add_event_op_id)
+CTLV_IN_REF(ctlv_subscriptions_remove_event_op_id, &ctlv_op_schemas[4].request,
+	    CTLV_ATTR_EVENT_OP_ID, 0, 0, CTLV_SCHEMA_UINT)
+#define ctlv_subscriptions_remove_event_op_id_for_each(_attr, _nest) \
+	CTLV_IN_FOR_EACH(ctlv_subscriptions_remove_event_op_id, _attr, _nest)
+CTLV_IN_EACH_U64(ctlv_subscriptions_remove_event_op_id)
+CTLV_IN_REF(ctlv_event_queue_set_event_queue_len, &ctlv_op_schemas[6].request,
+	    CTLV_ATTR_EVENT_QUEUE_LEN, 0, 0, CTLV_SCHEMA_UINT)
+CTLV_IN_HAS(ctlv_event_queue_set_event_queue_len)
+CTLV_IN_U64(ctlv_event_queue_set_event_queue_len)
+
+/* Writing a reply. An append is atomic; a nest ends with ctlv_nest_end(). */
+CTLV_PUT_U64(ctlv_family_id, CTLV_ATTR_FAMILY_ID, CTLV_SCHEMA_UINT)
+CTLV_PUT_STRING(ctlv_family_name, CTLV_ATTR_FAMILY_NAME, CTLV_SCHEMA_STRING)
+CTLV_NEST_START(ctlv_family_entry, CTLV_ATTR_FAMILY_ENTRY, CTLV_SCHEMA_NEST)
+CTLV_PUT_U64(ctlv_blob_type, CTLV_ATTR_BLOB_TYPE, CTLV_SCHEMA_ENUM)
+CTLV_PUT_U64(ctlv_blob_address, CTLV_ATTR_BLOB_ADDRESS, CTLV_SCHEMA_UINT)
+CTLV_PUT_U64(ctlv_blob_fd, CTLV_ATTR_BLOB_FD, CTLV_SCHEMA_UINT)
+CTLV_PUT_U64(ctlv_blob_offset, CTLV_ATTR_BLOB_OFFSET, CTLV_SCHEMA_UINT)
+CTLV_PUT_U64(ctlv_blob_length, CTLV_ATTR_BLOB_LENGTH, CTLV_SCHEMA_UINT)
+CTLV_PUT_U64(ctlv_error_reason, CTLV_ATTR_ERROR_REASON, CTLV_SCHEMA_ENUM)
+CTLV_PUT_STRING(ctlv_error_message, CTLV_ATTR_ERROR_MESSAGE, CTLV_SCHEMA_STRING)
+CTLV_PUT_U64(ctlv_error_bad_attr_offset, CTLV_ATTR_ERROR_BAD_ATTR_OFFSET, CTLV_SCHEMA_UINT)
+CTLV_PUT_U64(ctlv_error_nest_offset, CTLV_ATTR_ERROR_NEST_OFFSET, CTLV_SCHEMA_UINT)
+CTLV_PUT_U64(ctlv_error_missing_attr_id, CTLV_ATTR_ERROR_MISSING_ATTR_ID, CTLV_SCHEMA_UINT)
+CTLV_PUT_U64(ctlv_error_expected_generation, CTLV_ATTR_ERROR_EXPECTED_GENERATION, CTLV_SCHEMA_UINT)
+CTLV_PUT_U64(ctlv_error_current_generation, CTLV_ATTR_ERROR_CURRENT_GENERATION, CTLV_SCHEMA_UINT)
+CTLV_PUT_U64(ctlv_op_id, CTLV_ATTR_OP_ID, CTLV_SCHEMA_UINT)
+CTLV_PUT_U64(ctlv_op_type, CTLV_ATTR_OP_TYPE, CTLV_SCHEMA_ENUM)
+CTLV_PUT_U64(ctlv_op_availability, CTLV_ATTR_OP_AVAILABILITY, CTLV_SCHEMA_ENUM)
+CTLV_PUT_BOOL(ctlv_op_disabled, CTLV_ATTR_OP_DISABLED, CTLV_SCHEMA_BOOL)
+CTLV_PUT_U64(ctlv_op_request_max_len, CTLV_ATTR_OP_REQUEST_MAX_LEN, CTLV_SCHEMA_UINT)
+CTLV_PUT_U64(ctlv_op_action_reply_max_len, CTLV_ATTR_OP_ACTION_REPLY_MAX_LEN, CTLV_SCHEMA_UINT)
+CTLV_PUT_U64(ctlv_op_query_reply_min_len, CTLV_ATTR_OP_QUERY_REPLY_MIN_LEN, CTLV_SCHEMA_UINT)
+CTLV_PUT_U64(ctlv_op_query_reply_suggested_len, CTLV_ATTR_OP_QUERY_REPLY_SUGGESTED_LEN,
+	     CTLV_SCHEMA_UINT)
+CTLV_PUT_U64(ctlv_op_event_record_max_len, CTLV_ATTR_OP_EVENT_RECORD_MAX_LEN, CTLV_SCHEMA_UINT)
+CTLV_PUT_U64(ctlv_op_state_generation, CTLV_ATTR_OP_STATE_GENERATION, CTLV_SCHEMA_UINT)
+CTLV_NEST_START(ctlv_op_entry, CTLV_ATTR_OP_ENTRY, CTLV_SCHEMA_NEST)
+CTLV_PUT_U64(ctlv_op_fd_access, CTLV_ATTR_OP_FD_ACCESS, CTLV_SCHEMA_ENUM)
+CTLV_PUT_U64(ctlv_schema_attr_id, CTLV_ATTR_SCHEMA_ATTR_ID, CTLV_SCHEMA_UINT)
+CTLV_PUT_U64(ctlv_schema_kind, CTLV_ATTR_SCHEMA_KIND, CTLV_SCHEMA_UINT)
+CTLV_PUT_U64(ctlv_schema_max_occurrences, CTLV_ATTR_SCHEMA_MAX_OCCURRENCES, CTLV_SCHEMA_UINT)
+CTLV_PUT_U64(ctlv_schema_min, CTLV_ATTR_SCHEMA_MIN, CTLV_SCHEMA_UINT)
+CTLV_PUT_U64(ctlv_schema_max, CTLV_ATTR_SCHEMA_MAX, CTLV_SCHEMA_UINT)
+CTLV_PUT_U64(ctlv_schema_min_length, CTLV_ATTR_SCHEMA_MIN_LENGTH, CTLV_SCHEMA_UINT)
+CTLV_PUT_U64(ctlv_schema_max_length, CTLV_ATTR_SCHEMA_MAX_LENGTH, CTLV_SCHEMA_UINT)
+CTLV_PUT_U64(ctlv_schema_flags_mask, CTLV_ATTR_SCHEMA_FLAGS_MASK, CTLV_SCHEMA_UINT)
+CTLV_PUT_U64(ctlv_schema_unit, CTLV_ATTR_SCHEMA_UNIT, CTLV_SCHEMA_UINT)
+CTLV_PUT_S64(ctlv_schema_scale, CTLV_ATTR_SCHEMA_SCALE, CTLV_SCHEMA_SINT)
+CTLV_PUT_U64(ctlv_schema_blob_direction, CTLV_ATTR_SCHEMA_BLOB_DIRECTION, CTLV_SCHEMA_ENUM)
+CTLV_PUT_U64(ctlv_schema_blob_backings, CTLV_ATTR_SCHEMA_BLOB_BACKINGS, CTLV_SCHEMA_UINT)
+CTLV_PUT_U64(ctlv_schema_blob_max_length, CTLV_ATTR_SCHEMA_BLOB_MAX_LENGTH, CTLV_SCHEMA_UINT)
+CTLV_PUT_U64(ctlv_schema_blob_alignment, CTLV_ATTR_SCHEMA_BLOB_ALIGNMENT, CTLV_SCHEMA_UINT)
+CTLV_PUT_U64(ctlv_schema_reenters, CTLV_ATTR_SCHEMA_REENTERS, CTLV_SCHEMA_UINT)
+CTLV_NEST_START(ctlv_schema_attrs, CTLV_ATTR_SCHEMA_ATTRS, CTLV_SCHEMA_NEST)
+CTLV_NEST_START(ctlv_schema_optional_attrs, CTLV_ATTR_SCHEMA_OPTIONAL_ATTRS, CTLV_SCHEMA_NEST)
+CTLV_NEST_START(ctlv_schema_request, CTLV_ATTR_SCHEMA_REQUEST, CTLV_SCHEMA_NEST)
+CTLV_NEST_START(ctlv_schema_reply, CTLV_ATTR_SCHEMA_REPLY, CTLV_SCHEMA_NEST)
+CTLV_PUT_U64(ctlv_event_op_id, CTLV_ATTR_EVENT_OP_ID, CTLV_SCHEMA_UINT)
+CTLV_PUT_U64(ctlv_event_queue_len, CTLV_ATTR_EVENT_QUEUE_LEN, CTLV_SCHEMA_UINT)
+CTLV_PUT_U64(ctlv_event_queue_used, CTLV_ATTR_EVENT_QUEUE_USED, CTLV_SCHEMA_UINT)
+CTLV_PUT_U64(ctlv_event_first_sequence, CTLV_ATTR_EVENT_FIRST_SEQUENCE, CTLV_SCHEMA_UINT)
+CTLV_PUT_U64(ctlv_event_last_sequence, CTLV_ATTR_EVENT_LAST_SEQUENCE, CTLV_SCHEMA_UINT)
+CTLV_PUT_U64(ctlv_event_dropped_count, CTLV_ATTR_EVENT_DROPPED_COUNT, CTLV_SCHEMA_UINT)
+
+/* Building one event, passed to ctlv_event_emit() or ctlv_event_abort() once. */
+CTLV_EVENT_CREATE(ctlv_op_changed, CTLV_OP_OP_CHANGED)
+CTLV_EVENT_CREATE(ctlv_event_overflow, CTLV_OP_EVENT_OVERFLOW)
+CTLV_EVENT_CREATE(ctlv_device_removed, CTLV_OP_DEVICE_REMOVED)
+#endif /* _CTLV_GENERATED_METADATA_ONLY */
+
+#endif /* _LINUX_CTLV_GEN_H */
diff --git a/include/linux/tdx-guest.h b/include/linux/tdx-guest.h
new file mode 100644
index 0000000000000..65f367e4956a3
--- /dev/null
+++ b/include/linux/tdx-guest.h
@@ -0,0 +1,75 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+#ifndef _LINUX_TDX_GUEST_H
+#define _LINUX_TDX_GUEST_H
+
+#include <crypto/sha2.h>
+#include <linux/types.h>
+
+struct device;
+
+#define TDX_GUEST_REPORTDATA_LEN 64
+#define TDX_GUEST_REPORT_LEN 1024
+#define TDX_GUEST_QUOTE_MAX_LEN ((128 * 1024) - 24)
+
+struct tdx_guest_info {
+	u8 mrconfigid[SHA384_DIGEST_SIZE];
+	u8 mrowner[SHA384_DIGEST_SIZE];
+	u8 mrownerconfig[SHA384_DIGEST_SIZE];
+};
+
+enum tdx_guest_mr {
+	TDX_GUEST_MR_MRTD,
+	TDX_GUEST_MR_RTMR0,
+	TDX_GUEST_MR_RTMR1,
+	TDX_GUEST_MR_RTMR2,
+	TDX_GUEST_MR_RTMR3,
+};
+
+/**
+ * struct tdx_guest_ops - Native TDX guest operations
+ * @info_get: Return immutable TD construction fields
+ * @report_get: Get a TDREPORT bound to report data
+ * @quote_get: Get a Quote bound to report data
+ * @mr_read: Read MRTD or an RTMR
+ * @rtmr_extend: Extend an RTMR
+ */
+struct tdx_guest_ops {
+	const struct tdx_guest_info *(*info_get)(struct device *dev);
+	int (*report_get)(struct device *dev, const u8 *reportdata,
+			  size_t length, void *out, size_t capacity,
+			  size_t *out_length);
+	int (*quote_get)(struct device *dev, const u8 *reportdata,
+			 size_t length, void *out, size_t capacity,
+			 size_t *out_length);
+	int (*mr_read)(struct device *dev, enum tdx_guest_mr mr,
+		       u8 value[SHA384_DIGEST_SIZE]);
+	int (*rtmr_extend)(struct device *dev, unsigned int rtmr,
+			   const u8 value[SHA384_DIGEST_SIZE]);
+};
+
+/**
+ * struct tdx_guest_client - Native TDX service consumer
+ * @add: Attach to the service and return client private data or an ERR_PTR
+ * @remove: Detach the client private data returned by @add
+ */
+struct tdx_guest_client {
+	void *(*add)(struct device *parent_dev,
+		     const struct tdx_guest_ops *ops);
+	void (*remove)(void *client_priv);
+};
+
+/**
+ * tdx_guest_client_register - Register one native TDX service consumer
+ * @client: Immutable add/remove callback pair
+ *
+ * Return: 0, or a negative errno.
+ */
+int tdx_guest_client_register(const struct tdx_guest_client *client);
+
+/**
+ * tdx_guest_client_unregister - Unregister a native TDX service consumer
+ * @client: Descriptor passed to tdx_guest_client_register()
+ */
+void tdx_guest_client_unregister(const struct tdx_guest_client *client);
+
+#endif /* _LINUX_TDX_GUEST_H */
diff --git a/include/uapi/linux/ctlv.h b/include/uapi/linux/ctlv.h
new file mode 100644
index 0000000000000..6bc0d1a296e67
--- /dev/null
+++ b/include/uapi/linux/ctlv.h
@@ -0,0 +1,183 @@
+/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) */
+/*
+ * Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES
+ *
+ * CTLV transport UAPI: the TLV wire format, the op-execution ioctl, the event
+ * record header and transport limits. Schema-free; a family's constants
+ * are generated into <linux/<family>_gen.h>, the root family's into
+ * <linux/ctlv_gen.h>.
+ */
+#ifndef _UAPI_LINUX_CTLV_H
+#define _UAPI_LINUX_CTLV_H
+
+#include <linux/ioctl.h>
+#include <linux/types.h>
+
+/**
+ * struct ctlv_attr - Attr header.
+ * @len: this header plus its payload, excluding this attr's trailing padding
+ * @flags: CTLV_ATTR_F_* bits
+ * @attr_id: complete attr ID, or CTLV_ATTR_ROOT for a message root
+ *
+ * Attrs are aligned to CTLV_ALIGNTO, which is why @attr_id is __aligned_u64: a
+ * 32-bit ABI would otherwise align this structure to four bytes. A nested
+ * payload is the concatenation of CTLV_ALIGN(child.len) bytes per child, so
+ * child padding counts inside the containing attr's @len while a leaf's own
+ * padding does not. Scalar payloads are native-endian. Within each request
+ * root or nest, occurrences of one @attr_id are contiguous; different IDs
+ * otherwise have no required order.
+ */
+struct ctlv_attr {
+	__u32 len;
+	__u32 flags;
+	__aligned_u64 attr_id;
+};
+
+#define CTLV_ALIGNTO 8
+#define CTLV_ALIGN(_len) (((_len) + CTLV_ALIGNTO - 1) & ~(CTLV_ALIGNTO - 1))
+
+/* Set exactly on root and nested attrs, clear on scalar attrs. */
+#define CTLV_ATTR_F_NESTED		(1U << 0)
+/* Query fragments: set on the root and each nest logically open at the end. */
+#define CTLV_ATTR_F_FRAG_MORE		(1U << 1)
+/*
+ * A request attr, never the root, that a device whose schema does not declare
+ * its ID skips whole instead of refusing the message. An ID that schema does
+ * declare is held to it wherever it appears, so this asks to be forgiven what
+ * this kernel has never heard of and nothing else.
+ */
+#define CTLV_ATTR_F_IGNORE_IF_UNKNOWN	(1U << 2)
+
+/* Root attr: carries CTLV_ATTR_F_NESTED, valid only at a message start. */
+#define CTLV_ATTR_ROOT 0ULL
+
+/* Complete attr: family in bits 63..48, group in 47..32, attr in 31..0. */
+#define CTLV_ATTR(_family, _group, _attr)	\
+	(((__u64)(_family) << 48) |		\
+	 ((__u64)(_group) << 32) |		\
+	 (__u64)(_attr))
+
+#define CTLV_ATTR_FAMILY(_attr)	((__u16)((_attr) >> 48))
+#define CTLV_ATTR_GROUP(_attr)	((__u16)((_attr) >> 32))
+#define CTLV_ATTR_NUMBER(_attr)	((__u32)(_attr))
+
+/* Complete op: family in bits 63..48, zero in 47..32, op in 31..0. */
+#define CTLV_OP(_family, _op)	\
+	(((__u64)(_family) << 48) | (__u64)(_op))
+
+#define CTLV_OP_FAMILY(_op)		((__u16)((_op) >> 48))
+#define CTLV_OP_NUMBER(_op)		((__u32)(_op))
+
+/**
+ * enum ctlv_unit - CTLV-defined unit of an integer attr payload.
+ * @CTLV_UNIT_NONE: dimensionless
+ * @CTLV_UNIT_SECONDS: seconds
+ * @CTLV_UNIT_HERTZ: hertz
+ * @CTLV_UNIT_BYTES: bytes
+ * @CTLV_UNIT_CELSIUS: degrees Celsius
+ *
+ * A payload is value * 10^scale of this unit, from the decimal scale the attr
+ * declares alongside. Changing either is an ABI break.
+ */
+enum ctlv_unit {
+	CTLV_UNIT_NONE = 0,
+	CTLV_UNIT_SECONDS,
+	CTLV_UNIT_HERTZ,
+	CTLV_UNIT_BYTES,
+	CTLV_UNIT_CELSIUS,
+};
+
+/**
+ * enum ctlv_schema_kind - CTLV-defined form of one attr payload.
+ * @CTLV_SCHEMA_UINT: unsigned integer payload bounded by a range
+ * @CTLV_SCHEMA_SINT: signed integer payload bounded by a range
+ * @CTLV_SCHEMA_BOOL: one payload byte holding zero or one
+ * @CTLV_SCHEMA_STRING: NUL-terminated string payload bounded by length
+ * @CTLV_SCHEMA_BINARY: opaque payload bounded by length
+ * @CTLV_SCHEMA_ENUM: unsigned integer payload restricted to a range
+ * @CTLV_SCHEMA_FLAGS: unsigned integer payload restricted to a mask
+ * @CTLV_SCHEMA_NEST: nested payload described by further nodes
+ * @CTLV_SCHEMA_BLOB: blob descriptor nest
+ *
+ * Exactly one form applies to an attr. These are the values op-schema-get
+ * reports, and the set is append-only.
+ */
+enum ctlv_schema_kind {
+	CTLV_SCHEMA_UINT,
+	CTLV_SCHEMA_SINT,
+	CTLV_SCHEMA_BOOL,
+	CTLV_SCHEMA_STRING,
+	CTLV_SCHEMA_BINARY,
+	CTLV_SCHEMA_ENUM,
+	CTLV_SCHEMA_FLAGS,
+	CTLV_SCHEMA_NEST,
+	CTLV_SCHEMA_BLOB,
+};
+
+/**
+ * struct ctlv_op_exec - Op-execution ioctl argument.
+ * @op_id: complete op ID; zero is invalid
+ * @request: struct ctlv_attr __user *, the mandatory complete request root
+ * @reply: struct ctlv_attr __user *, the success reply or the error
+ *	information
+ * @request_len: readable bytes beginning at @request, at least one root header;
+ *	the transport copy boundary, which may exceed the root's own length
+ * @reply_len: writable bytes beginning at @reply; input only, never
+ *	overwritten by the kernel
+ * @generation: query only; zero on a first fragment, the previously returned
+ *	value on continuation, and the query generation on output. Actions must
+ *	set zero.
+ * @cursor: query only; zero starts a query and a nonzero value resumes it. On
+ *	output it is the next cursor when the root carries
+ *	CTLV_ATTR_F_FRAG_MORE and zero when no further fragment exists. Actions
+ *	must set zero.
+ * @reserved: must be zero
+ *
+ * No size field: the ioctl number encodes the structure size and @reserved
+ * covers compatible growth. @request and @reply are fixed-width
+ * representations of userspace pointers so that the compat layout is identical.
+ */
+struct ctlv_op_exec {
+	__aligned_u64 op_id;
+	__aligned_u64 request;
+	__aligned_u64 reply;
+	__u32 request_len;
+	__u32 reply_len;
+	__aligned_u64 generation;
+	__aligned_u64 cursor;
+	__aligned_u64 reserved[2];
+};
+
+#define CTLV_IOC_MAGIC 0xBB
+
+#define CTLV_IOC_OP_EXEC _IOWR(CTLV_IOC_MAGIC, 0x00, struct ctlv_op_exec)
+
+/**
+ * struct ctlv_event_hdr - Header of one queued event record.
+ * @length: complete record length, this header plus the aligned root
+ * @flags: must be zero
+ * @op_id: complete op ID of the event op that produced the record
+ * @sequence: per open file description sequence number, assigned to every
+ *	eligible enqueue attempt including dropped ones
+ *
+ * Exactly one root attr follows the header, and one read() returns one record.
+ */
+struct ctlv_event_hdr {
+	__u32 length;
+	__u32 flags;
+	__aligned_u64 op_id;
+	__aligned_u64 sequence;
+};
+
+/* Implementation limits, not wire-field maxima: raising them is compatible. */
+
+/* Request roots, action replies, query reply fragments and event roots. */
+#define CTLV_MAX_INLINE_MESSAGE_LEN	0x100000	/* 1 MiB */
+/* Includes the error information root. */
+#define CTLV_MAX_ERROR_LEN		0x4000		/* 16 KiB */
+/* The root attr is at depth zero. */
+#define CTLV_MAX_NEST_DEPTH		32
+#define CTLV_DEFAULT_QUERY_REPLY_LEN	0x10000		/* 64 KiB */
+#define CTLV_MAX_EVENT_QUEUE_LEN	0x1000000	/* 16 MiB */
+
+#endif /* _UAPI_LINUX_CTLV_H */
diff --git a/include/uapi/linux/ctlv_attestation_gen.h b/include/uapi/linux/ctlv_attestation_gen.h
new file mode 100644
index 0000000000000..888bbf06618b1
--- /dev/null
+++ b/include/uapi/linux/ctlv_attestation_gen.h
@@ -0,0 +1,252 @@
+/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) */
+/* Do not edit, regenerate with tools/ctlv/ctlv-regen.sh, from: */
+/*	Documentation/ctlv/specs/ctlv-attestation.yaml */
+/* CTLV-GEN uapi header */
+
+/*
+ * Constants of the ctlv-attestation CTLV family. Attr and op IDs are complete; the wire format
+ * carrying them is in <linux/ctlv.h>.
+ *
+ * The inherited ctlv header is included here, so one include covers the whole effective schema.
+ */
+
+#ifndef _UAPI_LINUX_CTLV_ATTESTATION_GEN_H
+#define _UAPI_LINUX_CTLV_ATTESTATION_GEN_H
+
+#include <linux/const.h>
+#include <linux/ctlv.h>
+#include <linux/ctlv_families_gen.h>
+#include <linux/ctlv_gen.h>
+
+/* enum evidence-representation */
+enum _ctlv_attestation_evidence_representation {
+	CTLV_ATTESTATION_EVIDENCE_REPRESENTATION_RAW = 1,
+};
+
+/* enum evidence-blob-class */
+enum _ctlv_attestation_evidence_blob_class {
+	CTLV_ATTESTATION_EVIDENCE_BLOB_CLASS_PRIMARY = 1,
+};
+
+/* enum mr-log-event */
+enum _ctlv_attestation_mr_log_event {
+	CTLV_ATTESTATION_MR_LOG_EVENT_INFO = 1,
+	CTLV_ATTESTATION_MR_LOG_EVENT_EXTEND,
+};
+
+/* flags mr-device-caps */
+enum _ctlv_attestation_mr_device_caps_bit {
+	CTLV_ATTESTATION_MR_DEVICE_CAPS_READ_BIT,
+	CTLV_ATTESTATION_MR_DEVICE_CAPS_EXTEND_BIT,
+};
+
+#define CTLV_ATTESTATION_MR_DEVICE_CAPS_READ _BITULL(CTLV_ATTESTATION_MR_DEVICE_CAPS_READ_BIT)
+#define CTLV_ATTESTATION_MR_DEVICE_CAPS_EXTEND _BITULL(CTLV_ATTESTATION_MR_DEVICE_CAPS_EXTEND_BIT)
+#define CTLV_ATTESTATION_MR_DEVICE_CAPS_MASK \
+	(CTLV_ATTESTATION_MR_DEVICE_CAPS_READ | \
+	 CTLV_ATTESTATION_MR_DEVICE_CAPS_EXTEND)
+
+/* flags mr-caps */
+enum _ctlv_attestation_mr_caps_bit {
+	CTLV_ATTESTATION_MR_CAPS_READ_BIT,
+	CTLV_ATTESTATION_MR_CAPS_EXTEND_BIT,
+};
+
+#define CTLV_ATTESTATION_MR_CAPS_READ _BITULL(CTLV_ATTESTATION_MR_CAPS_READ_BIT)
+#define CTLV_ATTESTATION_MR_CAPS_EXTEND _BITULL(CTLV_ATTESTATION_MR_CAPS_EXTEND_BIT)
+#define CTLV_ATTESTATION_MR_CAPS_MASK \
+	(CTLV_ATTESTATION_MR_CAPS_READ | \
+	 CTLV_ATTESTATION_MR_CAPS_EXTEND)
+
+/* attr groups */
+enum _ctlv_attestation_group {
+	CTLV_ATTESTATION_GROUP_DEVICE = 1,
+	CTLV_ATTESTATION_GROUP_CAP,
+	CTLV_ATTESTATION_GROUP_EVIDENCE,
+	CTLV_ATTESTATION_GROUP_MR,
+	CTLV_ATTESTATION_GROUP_LOG,
+	CTLV_ATTESTATION_GROUP_NOTIFICATION,
+};
+
+#define _CTLV_ATTESTATION_ATTR(_group, _attr) CTLV_ATTR(CTLV_FAMILY_ATTESTATION, (_group), (_attr))
+
+/* attrs of group device */
+#define _CTLV_ATTESTATION_ATTR_DEVICE(_attr) \
+	_CTLV_ATTESTATION_ATTR(CTLV_ATTESTATION_GROUP_DEVICE, _CTLV_ATTESTATION_ATTR_DEVICE_##_attr)
+
+enum _ctlv_attestation_attr_device {
+	_CTLV_ATTESTATION_ATTR_DEVICE_GENERATION = 1,
+	_CTLV_ATTESTATION_ATTR_DEVICE_CAPS,
+	_CTLV_ATTESTATION_ATTR_DEVICE_INFO,
+};
+
+#define CTLV_ATTESTATION_ATTR_DEVICE_GENERATION _CTLV_ATTESTATION_ATTR_DEVICE(GENERATION)
+#define CTLV_ATTESTATION_ATTR_DEVICE_CAPS _CTLV_ATTESTATION_ATTR_DEVICE(CAPS)
+#define CTLV_ATTESTATION_ATTR_DEVICE_INFO _CTLV_ATTESTATION_ATTR_DEVICE(INFO)
+
+/* attrs of group cap */
+#define _CTLV_ATTESTATION_ATTR_CAP(_attr) \
+	_CTLV_ATTESTATION_ATTR(CTLV_ATTESTATION_GROUP_CAP, _CTLV_ATTESTATION_ATTR_CAP_##_attr)
+
+enum _ctlv_attestation_attr_cap {
+	_CTLV_ATTESTATION_ATTR_CAP_EVIDENCE = 1,
+	_CTLV_ATTESTATION_ATTR_CAP_MR,
+	_CTLV_ATTESTATION_ATTR_CAP_MIN_CHALLENGE_LENGTH,
+	_CTLV_ATTESTATION_ATTR_CAP_MAX_CHALLENGE_LENGTH,
+	_CTLV_ATTESTATION_ATTR_CAP_MAX_TOTAL_OUTPUT_LENGTH,
+	_CTLV_ATTESTATION_ATTR_CAP_MR_FLAGS,
+	_CTLV_ATTESTATION_ATTR_CAP_OBJECT,
+	_CTLV_ATTESTATION_ATTR_CAP_BLOB_CLASS,
+	_CTLV_ATTESTATION_ATTR_CAP_FORMAT,
+	_CTLV_ATTESTATION_ATTR_CAP_REPRESENTATION,
+	_CTLV_ATTESTATION_ATTR_CAP_MAX_LENGTH,
+};
+
+#define CTLV_ATTESTATION_ATTR_CAP_EVIDENCE _CTLV_ATTESTATION_ATTR_CAP(EVIDENCE)
+#define CTLV_ATTESTATION_ATTR_CAP_MR _CTLV_ATTESTATION_ATTR_CAP(MR)
+#define CTLV_ATTESTATION_ATTR_CAP_MIN_CHALLENGE_LENGTH \
+	_CTLV_ATTESTATION_ATTR_CAP(MIN_CHALLENGE_LENGTH)
+#define CTLV_ATTESTATION_ATTR_CAP_MAX_CHALLENGE_LENGTH \
+	_CTLV_ATTESTATION_ATTR_CAP(MAX_CHALLENGE_LENGTH)
+#define CTLV_ATTESTATION_ATTR_CAP_MAX_TOTAL_OUTPUT_LENGTH \
+	_CTLV_ATTESTATION_ATTR_CAP(MAX_TOTAL_OUTPUT_LENGTH)
+#define CTLV_ATTESTATION_ATTR_CAP_MR_FLAGS _CTLV_ATTESTATION_ATTR_CAP(MR_FLAGS)
+#define CTLV_ATTESTATION_ATTR_CAP_OBJECT _CTLV_ATTESTATION_ATTR_CAP(OBJECT)
+#define CTLV_ATTESTATION_ATTR_CAP_BLOB_CLASS _CTLV_ATTESTATION_ATTR_CAP(BLOB_CLASS)
+#define CTLV_ATTESTATION_ATTR_CAP_FORMAT _CTLV_ATTESTATION_ATTR_CAP(FORMAT)
+#define CTLV_ATTESTATION_ATTR_CAP_REPRESENTATION _CTLV_ATTESTATION_ATTR_CAP(REPRESENTATION)
+#define CTLV_ATTESTATION_ATTR_CAP_MAX_LENGTH _CTLV_ATTESTATION_ATTR_CAP(MAX_LENGTH)
+
+/* attrs of group evidence */
+#define _CTLV_ATTESTATION_ATTR_EVIDENCE(_attr) \
+	_CTLV_ATTESTATION_ATTR(CTLV_ATTESTATION_GROUP_EVIDENCE, \
+			       _CTLV_ATTESTATION_ATTR_EVIDENCE_##_attr)
+
+enum _ctlv_attestation_attr_evidence {
+	_CTLV_ATTESTATION_ATTR_EVIDENCE_CHALLENGE = 1,
+	_CTLV_ATTESTATION_ATTR_EVIDENCE_OBJECT,
+	_CTLV_ATTESTATION_ATTR_EVIDENCE_BLOB_CLASS,
+	_CTLV_ATTESTATION_ATTR_EVIDENCE_FORMAT,
+	_CTLV_ATTESTATION_ATTR_EVIDENCE_REPRESENTATION,
+	_CTLV_ATTESTATION_ATTR_EVIDENCE_DATA,
+	_CTLV_ATTESTATION_ATTR_EVIDENCE_OBJECT_LENGTH,
+};
+
+#define CTLV_ATTESTATION_ATTR_EVIDENCE_CHALLENGE _CTLV_ATTESTATION_ATTR_EVIDENCE(CHALLENGE)
+#define CTLV_ATTESTATION_ATTR_EVIDENCE_OBJECT _CTLV_ATTESTATION_ATTR_EVIDENCE(OBJECT)
+#define CTLV_ATTESTATION_ATTR_EVIDENCE_BLOB_CLASS _CTLV_ATTESTATION_ATTR_EVIDENCE(BLOB_CLASS)
+#define CTLV_ATTESTATION_ATTR_EVIDENCE_FORMAT _CTLV_ATTESTATION_ATTR_EVIDENCE(FORMAT)
+#define CTLV_ATTESTATION_ATTR_EVIDENCE_REPRESENTATION \
+	_CTLV_ATTESTATION_ATTR_EVIDENCE(REPRESENTATION)
+#define CTLV_ATTESTATION_ATTR_EVIDENCE_DATA _CTLV_ATTESTATION_ATTR_EVIDENCE(DATA)
+#define CTLV_ATTESTATION_ATTR_EVIDENCE_OBJECT_LENGTH _CTLV_ATTESTATION_ATTR_EVIDENCE(OBJECT_LENGTH)
+
+/* attrs of group mr */
+#define _CTLV_ATTESTATION_ATTR_MR(_attr) \
+	_CTLV_ATTESTATION_ATTR(CTLV_ATTESTATION_GROUP_MR, _CTLV_ATTESTATION_ATTR_MR_##_attr)
+
+enum _ctlv_attestation_attr_mr {
+	_CTLV_ATTESTATION_ATTR_MR_ID = 1,
+	_CTLV_ATTESTATION_ATTR_MR_NAME,
+	_CTLV_ATTESTATION_ATTR_MR_HASH_ALGO,
+	_CTLV_ATTESTATION_ATTR_MR_SUPPORTED_HASH_ALGO,
+	_CTLV_ATTESTATION_ATTR_MR_REGISTER_INDEX,
+	_CTLV_ATTESTATION_ATTR_MR_CAPS,
+	_CTLV_ATTESTATION_ATTR_MR_ITEM,
+	_CTLV_ATTESTATION_ATTR_MR_VALUE,
+	_CTLV_ATTESTATION_ATTR_MR_DATA,
+	_CTLV_ATTESTATION_ATTR_MR_GENERATION,
+	_CTLV_ATTESTATION_ATTR_MR_SELECTION,
+	_CTLV_ATTESTATION_ATTR_MR_START_GENERATION,
+	_CTLV_ATTESTATION_ATTR_MR_END_GENERATION,
+};
+
+#define CTLV_ATTESTATION_ATTR_MR_ID _CTLV_ATTESTATION_ATTR_MR(ID)
+#define CTLV_ATTESTATION_ATTR_MR_NAME _CTLV_ATTESTATION_ATTR_MR(NAME)
+#define CTLV_ATTESTATION_ATTR_MR_HASH_ALGO _CTLV_ATTESTATION_ATTR_MR(HASH_ALGO)
+#define CTLV_ATTESTATION_ATTR_MR_SUPPORTED_HASH_ALGO _CTLV_ATTESTATION_ATTR_MR(SUPPORTED_HASH_ALGO)
+#define CTLV_ATTESTATION_ATTR_MR_REGISTER_INDEX _CTLV_ATTESTATION_ATTR_MR(REGISTER_INDEX)
+#define CTLV_ATTESTATION_ATTR_MR_CAPS _CTLV_ATTESTATION_ATTR_MR(CAPS)
+#define CTLV_ATTESTATION_ATTR_MR_ITEM _CTLV_ATTESTATION_ATTR_MR(ITEM)
+#define CTLV_ATTESTATION_ATTR_MR_VALUE _CTLV_ATTESTATION_ATTR_MR(VALUE)
+#define CTLV_ATTESTATION_ATTR_MR_DATA _CTLV_ATTESTATION_ATTR_MR(DATA)
+#define CTLV_ATTESTATION_ATTR_MR_GENERATION _CTLV_ATTESTATION_ATTR_MR(GENERATION)
+#define CTLV_ATTESTATION_ATTR_MR_SELECTION _CTLV_ATTESTATION_ATTR_MR(SELECTION)
+#define CTLV_ATTESTATION_ATTR_MR_START_GENERATION _CTLV_ATTESTATION_ATTR_MR(START_GENERATION)
+#define CTLV_ATTESTATION_ATTR_MR_END_GENERATION _CTLV_ATTESTATION_ATTR_MR(END_GENERATION)
+
+/* attrs of group log */
+#define _CTLV_ATTESTATION_ATTR_LOG(_attr) \
+	_CTLV_ATTESTATION_ATTR(CTLV_ATTESTATION_GROUP_LOG, _CTLV_ATTESTATION_ATTR_LOG_##_attr)
+
+enum _ctlv_attestation_attr_log {
+	_CTLV_ATTESTATION_ATTR_LOG_ENTRY = 1,
+	_CTLV_ATTESTATION_ATTR_LOG_EVENT,
+	_CTLV_ATTESTATION_ATTR_LOG_MR,
+};
+
+#define CTLV_ATTESTATION_ATTR_LOG_ENTRY _CTLV_ATTESTATION_ATTR_LOG(ENTRY)
+#define CTLV_ATTESTATION_ATTR_LOG_EVENT _CTLV_ATTESTATION_ATTR_LOG(EVENT)
+#define CTLV_ATTESTATION_ATTR_LOG_MR _CTLV_ATTESTATION_ATTR_LOG(MR)
+
+/* attrs of group notification */
+#define _CTLV_ATTESTATION_ATTR_NOTIFICATION(_attr) \
+	_CTLV_ATTESTATION_ATTR(CTLV_ATTESTATION_GROUP_NOTIFICATION, \
+			       _CTLV_ATTESTATION_ATTR_NOTIFICATION_##_attr)
+
+enum _ctlv_attestation_attr_notification {
+	_CTLV_ATTESTATION_ATTR_NOTIFICATION_ENTRY = 1,
+};
+
+#define CTLV_ATTESTATION_ATTR_NOTIFICATION_ENTRY _CTLV_ATTESTATION_ATTR_NOTIFICATION(ENTRY)
+
+/* attr sets */
+enum _ctlv_attestation_set {
+	CTLV_ATTESTATION_SET_DEVICE_INFO = 1,
+	CTLV_ATTESTATION_SET_EVIDENCE_OBJECT_CAP,
+	CTLV_ATTESTATION_SET_EVIDENCE_CAP,
+	CTLV_ATTESTATION_SET_MR_DEVICE_CAP,
+	CTLV_ATTESTATION_SET_DEVICE_CAPS,
+	CTLV_ATTESTATION_SET_DEVICE_REPLY,
+	CTLV_ATTESTATION_SET_EVIDENCE_OBJECT_REQUEST,
+	CTLV_ATTESTATION_SET_EVIDENCE_REQUEST,
+	CTLV_ATTESTATION_SET_EVIDENCE_REPLY,
+	CTLV_ATTESTATION_SET_MR_PROPS,
+	CTLV_ATTESTATION_SET_MR_DUMP_ENTRY,
+	CTLV_ATTESTATION_SET_MR_ID_REQUEST,
+	CTLV_ATTESTATION_SET_MR_READ_REQUEST,
+	CTLV_ATTESTATION_SET_MR_VALUE,
+	CTLV_ATTESTATION_SET_MR_READ_REPLY,
+	CTLV_ATTESTATION_SET_MR_EXTEND_REQUEST,
+	CTLV_ATTESTATION_SET_MR_CHANGE_REPLY,
+	CTLV_ATTESTATION_SET_MR_LOG_INFO,
+	CTLV_ATTESTATION_SET_MR_LOG_ENTRY,
+	CTLV_ATTESTATION_SET_MR_LOG_EVENT,
+	CTLV_ATTESTATION_SET_MR_LOG_SELECTION,
+	CTLV_ATTESTATION_SET_MR_LOG_REQUEST,
+	CTLV_ATTESTATION_SET_MR_LOG_REPLY,
+};
+
+/* ops */
+enum _ctlv_attestation_op {
+	_CTLV_ATTESTATION_OP_DEVICE_GET = 1,
+	_CTLV_ATTESTATION_OP_EVIDENCE_GET,
+	_CTLV_ATTESTATION_OP_MR_GET,
+	_CTLV_ATTESTATION_OP_MR_DUMP,
+	_CTLV_ATTESTATION_OP_MR_READ,
+	_CTLV_ATTESTATION_OP_MR_EXTEND,
+	_CTLV_ATTESTATION_OP_MR_LOG_ENTRY_APPENDED,
+	_CTLV_ATTESTATION_OP_MR_LOG_GET,
+};
+
+#define _CTLV_ATTESTATION_OP(_op) CTLV_OP(CTLV_FAMILY_ATTESTATION, _CTLV_ATTESTATION_OP_##_op)
+#define CTLV_ATTESTATION_OP_DEVICE_GET _CTLV_ATTESTATION_OP(DEVICE_GET)
+#define CTLV_ATTESTATION_OP_EVIDENCE_GET _CTLV_ATTESTATION_OP(EVIDENCE_GET)
+#define CTLV_ATTESTATION_OP_MR_GET _CTLV_ATTESTATION_OP(MR_GET)
+#define CTLV_ATTESTATION_OP_MR_DUMP _CTLV_ATTESTATION_OP(MR_DUMP)
+#define CTLV_ATTESTATION_OP_MR_READ _CTLV_ATTESTATION_OP(MR_READ)
+#define CTLV_ATTESTATION_OP_MR_EXTEND _CTLV_ATTESTATION_OP(MR_EXTEND)
+#define CTLV_ATTESTATION_OP_MR_LOG_ENTRY_APPENDED _CTLV_ATTESTATION_OP(MR_LOG_ENTRY_APPENDED)
+#define CTLV_ATTESTATION_OP_MR_LOG_GET _CTLV_ATTESTATION_OP(MR_LOG_GET)
+
+#endif /* _UAPI_LINUX_CTLV_ATTESTATION_GEN_H */
diff --git a/include/uapi/linux/ctlv_attestation_tdx_gen.h b/include/uapi/linux/ctlv_attestation_tdx_gen.h
new file mode 100644
index 0000000000000..04c8dbc3d07c8
--- /dev/null
+++ b/include/uapi/linux/ctlv_attestation_tdx_gen.h
@@ -0,0 +1,44 @@
+/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) */
+/* Do not edit, regenerate with tools/ctlv/ctlv-regen.sh, from: */
+/*	Documentation/ctlv/specs/ctlv-attestation-tdx.yaml */
+/* CTLV-GEN uapi header */
+
+/*
+ * Constants of the ctlv-attestation-tdx CTLV family. Attr and op IDs are complete; the wire format
+ * carrying them is in <linux/ctlv.h>.
+ *
+ * The inherited ctlv-attestation header is included here, so one include covers the whole effective
+ * schema.
+ */
+
+#ifndef _UAPI_LINUX_CTLV_ATTESTATION_TDX_GEN_H
+#define _UAPI_LINUX_CTLV_ATTESTATION_TDX_GEN_H
+
+#include <linux/ctlv.h>
+#include <linux/ctlv_attestation_gen.h>
+#include <linux/ctlv_families_gen.h>
+
+/* attr groups */
+enum _ctlv_attestation_tdx_group {
+	CTLV_ATTESTATION_TDX_GROUP_INFO = 1,
+};
+
+#define _CTLV_ATTESTATION_TDX_ATTR(_group, _attr) \
+	CTLV_ATTR(CTLV_FAMILY_ATTESTATION_TDX, (_group), (_attr))
+
+/* attrs of group info */
+#define _CTLV_ATTESTATION_TDX_ATTR_INFO(_attr) \
+	_CTLV_ATTESTATION_TDX_ATTR(CTLV_ATTESTATION_TDX_GROUP_INFO, \
+				   _CTLV_ATTESTATION_TDX_ATTR_INFO_##_attr)
+
+enum _ctlv_attestation_tdx_attr_info {
+	_CTLV_ATTESTATION_TDX_ATTR_INFO_MRCONFIGID = 1,
+	_CTLV_ATTESTATION_TDX_ATTR_INFO_MROWNER,
+	_CTLV_ATTESTATION_TDX_ATTR_INFO_MROWNERCONFIG,
+};
+
+#define CTLV_ATTESTATION_TDX_ATTR_INFO_MRCONFIGID _CTLV_ATTESTATION_TDX_ATTR_INFO(MRCONFIGID)
+#define CTLV_ATTESTATION_TDX_ATTR_INFO_MROWNER _CTLV_ATTESTATION_TDX_ATTR_INFO(MROWNER)
+#define CTLV_ATTESTATION_TDX_ATTR_INFO_MROWNERCONFIG _CTLV_ATTESTATION_TDX_ATTR_INFO(MROWNERCONFIG)
+
+#endif /* _UAPI_LINUX_CTLV_ATTESTATION_TDX_GEN_H */
diff --git a/include/uapi/linux/ctlv_families_gen.h b/include/uapi/linux/ctlv_families_gen.h
new file mode 100644
index 0000000000000..25c90509d8adf
--- /dev/null
+++ b/include/uapi/linux/ctlv_families_gen.h
@@ -0,0 +1,17 @@
+/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) */
+/* Do not edit, regenerate with tools/ctlv/ctlv-regen.sh, from: */
+/*	Documentation/ctlv/families.yaml */
+/* CTLV-GEN uapi header */
+
+/* CTLV family numbers. */
+
+#ifndef _UAPI_LINUX_CTLV_FAMILIES_GEN_H
+#define _UAPI_LINUX_CTLV_FAMILIES_GEN_H
+
+enum _ctlv_family {
+	CTLV_FAMILY_ROOT,
+	CTLV_FAMILY_ATTESTATION,
+	CTLV_FAMILY_ATTESTATION_TDX,
+};
+
+#endif /* _UAPI_LINUX_CTLV_FAMILIES_GEN_H */
diff --git a/include/uapi/linux/ctlv_gen.h b/include/uapi/linux/ctlv_gen.h
new file mode 100644
index 0000000000000..64eba093a6d49
--- /dev/null
+++ b/include/uapi/linux/ctlv_gen.h
@@ -0,0 +1,271 @@
+/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) */
+/* Do not edit, regenerate with tools/ctlv/ctlv-regen.sh, from: */
+/*	Documentation/ctlv/specs/ctlv.yaml */
+/* CTLV-GEN uapi header */
+
+/*
+ * Constants of the ctlv CTLV family. Attr and op IDs are complete; the wire format carrying them is
+ * in <linux/ctlv.h>.
+ */
+
+#ifndef _UAPI_LINUX_CTLV_GEN_H
+#define _UAPI_LINUX_CTLV_GEN_H
+
+#include <linux/ctlv.h>
+#include <linux/ctlv_families_gen.h>
+
+/* enum op-type */
+enum _ctlv_op_type {
+	CTLV_OP_TYPE_ACTION = 1,
+	CTLV_OP_TYPE_QUERY,
+	CTLV_OP_TYPE_EVENT,
+};
+
+/* enum op-availability */
+enum _ctlv_op_availability {
+	CTLV_OP_AVAILABILITY_FIXED = 1,
+	CTLV_OP_AVAILABILITY_DYNAMIC,
+};
+
+/* enum blob-type */
+enum _ctlv_blob_type {
+	CTLV_BLOB_TYPE_VA = 1,
+};
+
+/* enum blob-direction */
+enum _ctlv_blob_direction {
+	CTLV_BLOB_DIRECTION_INPUT = 1,
+	CTLV_BLOB_DIRECTION_OUTPUT,
+	CTLV_BLOB_DIRECTION_INOUT,
+};
+
+/* enum validation-reason */
+enum _ctlv_validation_reason {
+	CTLV_VALIDATION_REASON_MALFORMED_MESSAGE = 1,
+	CTLV_VALIDATION_REASON_UNKNOWN_ATTR,
+	CTLV_VALIDATION_REASON_UNKNOWN_FLAG,
+	CTLV_VALIDATION_REASON_NESTING_TOO_DEEP,
+	CTLV_VALIDATION_REASON_MISSING_ATTR,
+	CTLV_VALIDATION_REASON_TOO_MANY_OCCURRENCES,
+	CTLV_VALIDATION_REASON_VALUE_OUT_OF_RANGE,
+	CTLV_VALIDATION_REASON_BAD_LENGTH,
+	CTLV_VALIDATION_REASON_BAD_STRING,
+	CTLV_VALIDATION_REASON_BAD_BLOB_DESCRIPTOR,
+	CTLV_VALIDATION_REASON_STALE_GENERATION,
+	CTLV_VALIDATION_REASON_NONCONTIGUOUS_ATTR,
+};
+
+/* enum op-fd-access */
+enum _ctlv_op_fd_access {
+	CTLV_OP_FD_ACCESS_READ = 1,
+	CTLV_OP_FD_ACCESS_READ_WRITE,
+};
+
+/* attr groups */
+enum _ctlv_group {
+	CTLV_GROUP_FAMILY = 1,
+	CTLV_GROUP_BLOB,
+	CTLV_GROUP_ERROR,
+	CTLV_GROUP_OP,
+	CTLV_GROUP_SCHEMA,
+	CTLV_GROUP_EVENT,
+};
+
+#define _CTLV_ATTR(_group, _attr) CTLV_ATTR(CTLV_FAMILY_ROOT, (_group), (_attr))
+
+/* attrs of group family */
+#define _CTLV_ATTR_FAMILY(_attr) _CTLV_ATTR(CTLV_GROUP_FAMILY, _CTLV_ATTR_FAMILY_##_attr)
+
+enum _ctlv_attr_family {
+	_CTLV_ATTR_FAMILY_ID = 1,
+	_CTLV_ATTR_FAMILY_NAME,
+	_CTLV_ATTR_FAMILY_ENTRY,
+};
+
+#define CTLV_ATTR_FAMILY_ID _CTLV_ATTR_FAMILY(ID)
+#define CTLV_ATTR_FAMILY_NAME _CTLV_ATTR_FAMILY(NAME)
+#define CTLV_ATTR_FAMILY_ENTRY _CTLV_ATTR_FAMILY(ENTRY)
+
+/* attrs of group blob */
+#define _CTLV_ATTR_BLOB(_attr) _CTLV_ATTR(CTLV_GROUP_BLOB, _CTLV_ATTR_BLOB_##_attr)
+
+enum _ctlv_attr_blob {
+	_CTLV_ATTR_BLOB_TYPE = 1,
+	_CTLV_ATTR_BLOB_ADDRESS,
+	_CTLV_ATTR_BLOB_FD,
+	_CTLV_ATTR_BLOB_OFFSET,
+	_CTLV_ATTR_BLOB_LENGTH,
+};
+
+#define CTLV_ATTR_BLOB_TYPE _CTLV_ATTR_BLOB(TYPE)
+#define CTLV_ATTR_BLOB_ADDRESS _CTLV_ATTR_BLOB(ADDRESS)
+#define CTLV_ATTR_BLOB_FD _CTLV_ATTR_BLOB(FD)
+#define CTLV_ATTR_BLOB_OFFSET _CTLV_ATTR_BLOB(OFFSET)
+#define CTLV_ATTR_BLOB_LENGTH _CTLV_ATTR_BLOB(LENGTH)
+
+/* attrs of group error */
+#define _CTLV_ATTR_ERROR(_attr) _CTLV_ATTR(CTLV_GROUP_ERROR, _CTLV_ATTR_ERROR_##_attr)
+
+enum _ctlv_attr_error {
+	_CTLV_ATTR_ERROR_REASON = 1,
+	_CTLV_ATTR_ERROR_MESSAGE,
+	_CTLV_ATTR_ERROR_BAD_ATTR_OFFSET,
+	_CTLV_ATTR_ERROR_NEST_OFFSET,
+	_CTLV_ATTR_ERROR_MISSING_ATTR_ID,
+	_CTLV_ATTR_ERROR_EXPECTED_GENERATION,
+	_CTLV_ATTR_ERROR_CURRENT_GENERATION,
+};
+
+#define CTLV_ATTR_ERROR_REASON _CTLV_ATTR_ERROR(REASON)
+#define CTLV_ATTR_ERROR_MESSAGE _CTLV_ATTR_ERROR(MESSAGE)
+#define CTLV_ATTR_ERROR_BAD_ATTR_OFFSET _CTLV_ATTR_ERROR(BAD_ATTR_OFFSET)
+#define CTLV_ATTR_ERROR_NEST_OFFSET _CTLV_ATTR_ERROR(NEST_OFFSET)
+#define CTLV_ATTR_ERROR_MISSING_ATTR_ID _CTLV_ATTR_ERROR(MISSING_ATTR_ID)
+#define CTLV_ATTR_ERROR_EXPECTED_GENERATION _CTLV_ATTR_ERROR(EXPECTED_GENERATION)
+#define CTLV_ATTR_ERROR_CURRENT_GENERATION _CTLV_ATTR_ERROR(CURRENT_GENERATION)
+
+/* attrs of group op */
+#define _CTLV_ATTR_OP(_attr) _CTLV_ATTR(CTLV_GROUP_OP, _CTLV_ATTR_OP_##_attr)
+
+enum _ctlv_attr_op {
+	_CTLV_ATTR_OP_ID = 1,
+	_CTLV_ATTR_OP_TYPE,
+	_CTLV_ATTR_OP_AVAILABILITY,
+	_CTLV_ATTR_OP_DISABLED,
+	_CTLV_ATTR_OP_REQUEST_MAX_LEN,
+	_CTLV_ATTR_OP_ACTION_REPLY_MAX_LEN,
+	_CTLV_ATTR_OP_QUERY_REPLY_MIN_LEN,
+	_CTLV_ATTR_OP_QUERY_REPLY_SUGGESTED_LEN,
+	_CTLV_ATTR_OP_EVENT_RECORD_MAX_LEN,
+	_CTLV_ATTR_OP_STATE_GENERATION,
+	_CTLV_ATTR_OP_ENTRY,
+	_CTLV_ATTR_OP_FD_ACCESS,
+};
+
+#define CTLV_ATTR_OP_ID _CTLV_ATTR_OP(ID)
+#define CTLV_ATTR_OP_TYPE _CTLV_ATTR_OP(TYPE)
+#define CTLV_ATTR_OP_AVAILABILITY _CTLV_ATTR_OP(AVAILABILITY)
+#define CTLV_ATTR_OP_DISABLED _CTLV_ATTR_OP(DISABLED)
+#define CTLV_ATTR_OP_REQUEST_MAX_LEN _CTLV_ATTR_OP(REQUEST_MAX_LEN)
+#define CTLV_ATTR_OP_ACTION_REPLY_MAX_LEN _CTLV_ATTR_OP(ACTION_REPLY_MAX_LEN)
+#define CTLV_ATTR_OP_QUERY_REPLY_MIN_LEN _CTLV_ATTR_OP(QUERY_REPLY_MIN_LEN)
+#define CTLV_ATTR_OP_QUERY_REPLY_SUGGESTED_LEN _CTLV_ATTR_OP(QUERY_REPLY_SUGGESTED_LEN)
+#define CTLV_ATTR_OP_EVENT_RECORD_MAX_LEN _CTLV_ATTR_OP(EVENT_RECORD_MAX_LEN)
+#define CTLV_ATTR_OP_STATE_GENERATION _CTLV_ATTR_OP(STATE_GENERATION)
+#define CTLV_ATTR_OP_ENTRY _CTLV_ATTR_OP(ENTRY)
+#define CTLV_ATTR_OP_FD_ACCESS _CTLV_ATTR_OP(FD_ACCESS)
+
+/* attrs of group schema */
+#define _CTLV_ATTR_SCHEMA(_attr) _CTLV_ATTR(CTLV_GROUP_SCHEMA, _CTLV_ATTR_SCHEMA_##_attr)
+
+enum _ctlv_attr_schema {
+	_CTLV_ATTR_SCHEMA_ATTR_ID = 1,
+	_CTLV_ATTR_SCHEMA_KIND,
+	_CTLV_ATTR_SCHEMA_MAX_OCCURRENCES,
+	_CTLV_ATTR_SCHEMA_MIN,
+	_CTLV_ATTR_SCHEMA_MAX,
+	_CTLV_ATTR_SCHEMA_MIN_LENGTH,
+	_CTLV_ATTR_SCHEMA_MAX_LENGTH,
+	_CTLV_ATTR_SCHEMA_FLAGS_MASK,
+	_CTLV_ATTR_SCHEMA_UNIT,
+	_CTLV_ATTR_SCHEMA_SCALE,
+	_CTLV_ATTR_SCHEMA_BLOB_DIRECTION,
+	_CTLV_ATTR_SCHEMA_BLOB_BACKINGS,
+	_CTLV_ATTR_SCHEMA_BLOB_MAX_LENGTH,
+	_CTLV_ATTR_SCHEMA_BLOB_ALIGNMENT,
+	_CTLV_ATTR_SCHEMA_REENTERS,
+	_CTLV_ATTR_SCHEMA_ATTRS,
+	_CTLV_ATTR_SCHEMA_OPTIONAL_ATTRS,
+	_CTLV_ATTR_SCHEMA_REQUEST,
+	_CTLV_ATTR_SCHEMA_REPLY,
+};
+
+#define CTLV_ATTR_SCHEMA_ATTR_ID _CTLV_ATTR_SCHEMA(ATTR_ID)
+#define CTLV_ATTR_SCHEMA_KIND _CTLV_ATTR_SCHEMA(KIND)
+#define CTLV_ATTR_SCHEMA_MAX_OCCURRENCES _CTLV_ATTR_SCHEMA(MAX_OCCURRENCES)
+#define CTLV_ATTR_SCHEMA_MIN _CTLV_ATTR_SCHEMA(MIN)
+#define CTLV_ATTR_SCHEMA_MAX _CTLV_ATTR_SCHEMA(MAX)
+#define CTLV_ATTR_SCHEMA_MIN_LENGTH _CTLV_ATTR_SCHEMA(MIN_LENGTH)
+#define CTLV_ATTR_SCHEMA_MAX_LENGTH _CTLV_ATTR_SCHEMA(MAX_LENGTH)
+#define CTLV_ATTR_SCHEMA_FLAGS_MASK _CTLV_ATTR_SCHEMA(FLAGS_MASK)
+#define CTLV_ATTR_SCHEMA_UNIT _CTLV_ATTR_SCHEMA(UNIT)
+#define CTLV_ATTR_SCHEMA_SCALE _CTLV_ATTR_SCHEMA(SCALE)
+#define CTLV_ATTR_SCHEMA_BLOB_DIRECTION _CTLV_ATTR_SCHEMA(BLOB_DIRECTION)
+#define CTLV_ATTR_SCHEMA_BLOB_BACKINGS _CTLV_ATTR_SCHEMA(BLOB_BACKINGS)
+#define CTLV_ATTR_SCHEMA_BLOB_MAX_LENGTH _CTLV_ATTR_SCHEMA(BLOB_MAX_LENGTH)
+#define CTLV_ATTR_SCHEMA_BLOB_ALIGNMENT _CTLV_ATTR_SCHEMA(BLOB_ALIGNMENT)
+#define CTLV_ATTR_SCHEMA_REENTERS _CTLV_ATTR_SCHEMA(REENTERS)
+#define CTLV_ATTR_SCHEMA_ATTRS _CTLV_ATTR_SCHEMA(ATTRS)
+#define CTLV_ATTR_SCHEMA_OPTIONAL_ATTRS _CTLV_ATTR_SCHEMA(OPTIONAL_ATTRS)
+#define CTLV_ATTR_SCHEMA_REQUEST _CTLV_ATTR_SCHEMA(REQUEST)
+#define CTLV_ATTR_SCHEMA_REPLY _CTLV_ATTR_SCHEMA(REPLY)
+
+/* attrs of group event */
+#define _CTLV_ATTR_EVENT(_attr) _CTLV_ATTR(CTLV_GROUP_EVENT, _CTLV_ATTR_EVENT_##_attr)
+
+enum _ctlv_attr_event {
+	_CTLV_ATTR_EVENT_OP_ID = 1,
+	_CTLV_ATTR_EVENT_QUEUE_LEN,
+	_CTLV_ATTR_EVENT_QUEUE_USED,
+	_CTLV_ATTR_EVENT_FIRST_SEQUENCE,
+	_CTLV_ATTR_EVENT_LAST_SEQUENCE,
+	_CTLV_ATTR_EVENT_DROPPED_COUNT,
+};
+
+#define CTLV_ATTR_EVENT_OP_ID _CTLV_ATTR_EVENT(OP_ID)
+#define CTLV_ATTR_EVENT_QUEUE_LEN _CTLV_ATTR_EVENT(QUEUE_LEN)
+#define CTLV_ATTR_EVENT_QUEUE_USED _CTLV_ATTR_EVENT(QUEUE_USED)
+#define CTLV_ATTR_EVENT_FIRST_SEQUENCE _CTLV_ATTR_EVENT(FIRST_SEQUENCE)
+#define CTLV_ATTR_EVENT_LAST_SEQUENCE _CTLV_ATTR_EVENT(LAST_SEQUENCE)
+#define CTLV_ATTR_EVENT_DROPPED_COUNT _CTLV_ATTR_EVENT(DROPPED_COUNT)
+
+/* metadata of group event */
+enum _ctlv_attr_event_metadata {
+	CTLV_ATTR_EVENT_QUEUE_LEN_UNIT = CTLV_UNIT_BYTES,
+	CTLV_ATTR_EVENT_QUEUE_LEN_SCALE = 0,
+	CTLV_ATTR_EVENT_QUEUE_USED_UNIT = CTLV_UNIT_BYTES,
+	CTLV_ATTR_EVENT_QUEUE_USED_SCALE = 0,
+};
+
+/* attr sets */
+enum _ctlv_set {
+	CTLV_SET_FAMILY_ENTRY = 1,
+	CTLV_SET_OP_ENTRY,
+	CTLV_SET_OP_SCHEMA_REQUEST,
+	CTLV_SET_SCHEMA_NODE,
+	CTLV_SET_OP_SCHEMA_INFO,
+	CTLV_SET_OP_CHANGE_INFO,
+	CTLV_SET_ERROR_INFO,
+	CTLV_SET_EVENT_SUBSCRIPTION,
+	CTLV_SET_EVENT_QUEUE_LIMIT,
+	CTLV_SET_EVENT_QUEUE_STATE,
+	CTLV_SET_EVENT_OVERFLOW_INFO,
+};
+
+/* ops */
+enum _ctlv_op {
+	_CTLV_OP_FAMILIES_DUMP = 1,
+	_CTLV_OP_OPS_DUMP,
+	_CTLV_OP_OP_SCHEMA_GET,
+	_CTLV_OP_SUBSCRIPTIONS_ADD,
+	_CTLV_OP_SUBSCRIPTIONS_REMOVE,
+	_CTLV_OP_EVENT_QUEUE_GET,
+	_CTLV_OP_EVENT_QUEUE_SET,
+	_CTLV_OP_OP_CHANGED,
+	_CTLV_OP_EVENT_OVERFLOW,
+	_CTLV_OP_DEVICE_REMOVED,
+};
+
+#define _CTLV_OP(_op) CTLV_OP(CTLV_FAMILY_ROOT, _CTLV_OP_##_op)
+#define CTLV_OP_FAMILIES_DUMP _CTLV_OP(FAMILIES_DUMP)
+#define CTLV_OP_OPS_DUMP _CTLV_OP(OPS_DUMP)
+#define CTLV_OP_OP_SCHEMA_GET _CTLV_OP(OP_SCHEMA_GET)
+#define CTLV_OP_SUBSCRIPTIONS_ADD _CTLV_OP(SUBSCRIPTIONS_ADD)
+#define CTLV_OP_SUBSCRIPTIONS_REMOVE _CTLV_OP(SUBSCRIPTIONS_REMOVE)
+#define CTLV_OP_EVENT_QUEUE_GET _CTLV_OP(EVENT_QUEUE_GET)
+#define CTLV_OP_EVENT_QUEUE_SET _CTLV_OP(EVENT_QUEUE_SET)
+#define CTLV_OP_OP_CHANGED _CTLV_OP(OP_CHANGED)
+#define CTLV_OP_EVENT_OVERFLOW _CTLV_OP(EVENT_OVERFLOW)
+#define CTLV_OP_DEVICE_REMOVED _CTLV_OP(DEVICE_REMOVED)
+
+#endif /* _UAPI_LINUX_CTLV_GEN_H */
diff --git a/tools/ctlv/Makefile b/tools/ctlv/Makefile
new file mode 100644
index 0000000000000..bb3129405fb54
--- /dev/null
+++ b/tools/ctlv/Makefile
@@ -0,0 +1,59 @@
+# SPDX-License-Identifier: GPL-2.0
+
+KDIR = ../..
+DOCDIR = $(KDIR)/Documentation/ctlv
+SPECDIR = $(DOCDIR)/specs
+SPECS = $(wildcard $(SPECDIR)/*.yaml)
+TOOL = ./ctlvgen/cli.py
+
+all: validate abi-check
+
+validate:
+	@for spec in $(SPECS) ; do \
+		echo -e "\tVALIDATE $$(basename $$spec)" ; \
+		$(TOOL) --spec $$spec --validate || exit 1 ; \
+	done
+
+# Fails when a specification no longer matches its checked-in ABI snapshot.
+abi-check:
+	@for spec in $(SPECS) ; do \
+		echo -e "\tABICHECK $$(basename $$spec)" ; \
+		$(TOOL) --spec $$spec --abi-check || exit 1 ; \
+	done
+
+# Deliberate: an updated snapshot is how a UAPI change gets reviewed.
+abi-update:
+	@for spec in $(SPECS) ; do \
+		$(TOOL) --spec $$spec --abi-update || exit 1 ; \
+	done
+
+# Style checks, needing yamllint, pycodestyle and pyflakes, 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)
+
+regen:
+	@./ctlv-regen.sh
+
+# Fails when a checked-in generated file does not match what the generator
+# produces from the current specifications. Writes nothing.
+check-regen:
+	@./ctlv-regen.sh -c
+
+clean:
+	rm -rf ctlvgen/__pycache__
+	rm -rf ctlvgen/lib/__pycache__
+	rm -rf ctlvgen.egg-info
+	rm -rf build
+
+.PHONY: all validate abi-check abi-update lint regen check-regen clean
diff --git a/tools/ctlv/ctlv-regen.sh b/tools/ctlv/ctlv-regen.sh
new file mode 100755
index 0000000000000..575114ba93e7c
--- /dev/null
+++ b/tools/ctlv/ctlv-regen.sh
@@ -0,0 +1,55 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
+#
+# Reconcile the checked-in files against the independent output manifests.
+#
+#   -f  accepted for compatibility; reconciliation always renders everything
+#   -c  do not write anything, fail if any output differs from what the
+#       generator produces now
+#   -p  search the given directory instead of the kernel tree
+
+TOOL=$(dirname "$(realpath "$0")")/ctlvgen/cli.py
+check=
+search=
+
+while getopts ':fcp:' option; do
+	case "$option" in
+	f)
+		;;
+	c)
+		check=yes
+		;;
+	p)
+		if [ -z "$OPTARG" ]; then
+			echo "Option -p needs a nonempty directory" >&2
+			exit 1
+		fi
+		search=$OPTARG
+		;;
+	:)
+		echo "Option -$OPTARG needs an argument" >&2
+		exit 1
+		;;
+	?)
+		echo "Unrecognized option '-$OPTARG'" >&2
+		exit 1
+		;;
+	esac
+done
+shift $((OPTIND - 1))
+if [ "$#" -ne 0 ]; then
+	echo "Unexpected argument '$1'" >&2
+	exit 1
+fi
+
+KDIR=$(realpath "$(dirname "$0")/../..")
+args=(--spec "$KDIR/Documentation/ctlv/specs/ctlv.yaml")
+if [ -n "$search" ]; then
+	args+=(--output-root "$search")
+fi
+if [ -n "$check" ]; then
+	args+=(--outputs-check)
+else
+	args+=(--outputs-update)
+fi
+exec "$TOOL" "${args[@]}"
diff --git a/tools/ctlv/ctlvgen/__init__.py b/tools/ctlv/ctlvgen/__init__.py
new file mode 100644
index 0000000000000..f84069cb2c3d0
--- /dev/null
+++ b/tools/ctlv/ctlvgen/__init__.py
@@ -0,0 +1 @@
+# SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
diff --git a/tools/ctlv/ctlvgen/cli.py b/tools/ctlv/ctlvgen/cli.py
new file mode 100755
index 0000000000000..c6bfafeb28525
--- /dev/null
+++ b/tools/ctlv/ctlvgen/cli.py
@@ -0,0 +1,172 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
+"""Command line front end of the CTLV schema tool."""
+
+import argparse
+import pathlib
+import sys
+
+# So that this file works both as a module of the ctlvgen package and as the
+# script the Makefile and ctlv-regen.sh run. The imports below have to follow.
+sys.path.append(pathlib.Path(__file__).resolve().parent.as_posix())
+
+from lib import cgen  # noqa: E402
+from lib import compat  # noqa: E402
+from lib import gen_kernel  # noqa: E402
+from lib import gen_uapi  # noqa: E402
+from lib import outputs  # noqa: E402
+from lib import semantics  # noqa: E402
+from lib import spec  # noqa: E402
+from lib import tree  # noqa: E402
+from lib.errors import CtlvError  # noqa: E402
+
+
+# What each non-kernel --mode and file kind generates.
+GENERATORS = {
+    ('uapi', 'header'): gen_uapi.render,
+}
+
+
+def main():
+    parser = argparse.ArgumentParser(description='CTLV schema tool')
+    parser.add_argument('--spec', type=str, required=True,
+                        help='path to a CTLV family specification')
+    parser.add_argument('--schema', type=str,
+                        help='path to the meta-schema, derived from --spec '
+                             'when not given')
+    parser.add_argument('--registry', type=str,
+                        help='path to the family registry, derived from '
+                             '--spec when not given')
+    parser.add_argument('--abi', type=str,
+                        help='directory of the ABI snapshots, derived from '
+                             '--spec when not given')
+    action = parser.add_mutually_exclusive_group(required=True)
+    action.add_argument('--validate', action='store_true',
+                        help='validate the specification and exit')
+    action.add_argument('--abi-check', action='store_true',
+                        help='check the specification against its ABI '
+                             'snapshot')
+    action.add_argument('--abi-update', action='store_true',
+                        help='rewrite the ABI snapshot from the '
+                             'specification')
+    action.add_argument('--tree-check', action='store_true',
+                        help='check registry, spec, snapshot and output '
+                             'coverage')
+    action.add_argument('--tree-check-update', action='store_true',
+                        help='check whole-tree inputs before an ABI update')
+    action.add_argument('--registry-abi-update', action='store_true',
+                        help='update the ordered family registry baseline')
+    action.add_argument('--outputs-check', action='store_true',
+                        help='check every file in the output manifests')
+    action.add_argument('--outputs-update', action='store_true',
+                        help='regenerate every file in the output manifests')
+    action.add_argument('--mode',
+                        choices=('uapi', 'kernel'),
+                        help='generate the files of this mode')
+    parser.add_argument('--schema-only', action='store_true',
+                        help='omit the family API from kernel output')
+    kind = parser.add_mutually_exclusive_group()
+    kind.add_argument('--header', action='store_true',
+                      help='generate the header of --mode')
+    kind.add_argument('--source', action='store_true',
+                      help='generate the source of --mode')
+    parser.add_argument('-o', '--output', type=str,
+                        help='write to this file instead of standard output')
+    parser.add_argument('--cmp-out', action='store_true',
+                        help='leave the output file alone when its contents '
+                             'would not change')
+    parser.add_argument('--output-root', type=str,
+                        help='alternate destination root for generated files')
+    args = parser.parse_args()
+
+    kinds = (args.header, args.source)
+    if args.mode and not any(kinds):
+        parser.error('--mode needs --header or --source')
+    if any(kinds) and not args.mode:
+        parser.error('--header and --source need --mode')
+    if args.schema_only and args.mode != 'kernel':
+        parser.error('--schema-only needs --mode kernel')
+    output_action = args.outputs_check or args.outputs_update
+    if args.output is not None and not args.mode:
+        parser.error('-o/--output needs --mode')
+    if args.cmp_out and (not args.mode or args.output is None):
+        parser.error('--cmp-out needs --mode and --output')
+    if args.output_root is not None:
+        if not output_action:
+            parser.error('--output-root needs an outputs action')
+        if not args.output_root:
+            parser.error('--output-root cannot be empty')
+
+    paths = spec.Paths(args.spec, schema=args.schema, registry=args.registry,
+                       abi=args.abi)
+    try:
+        if args.tree_check:
+            tree.check(paths)
+            return 0
+        elif args.tree_check_update:
+            tree.check_for_update(paths)
+            return 0
+        elif args.registry_abi_update:
+            registry = tree.finish_update(paths)
+            paths.registry_abi.write_text(
+                compat.registry_render(registry), encoding='utf-8')
+            print(f'ctlvgen: wrote {paths.registry_abi}', file=sys.stderr)
+            return 0
+        elif args.outputs_check:
+            tree.check(paths)
+            outputs.reconcile(paths, args.output_root, check=True)
+            return 0
+        elif args.outputs_update:
+            tree.check_for_update(paths)
+            changed = outputs.reconcile(paths, args.output_root)
+            for item in changed:
+                print(f'ctlvgen: {item}', file=sys.stderr)
+            return 0
+        family = semantics.load(paths)
+        if args.validate:
+            cgen.symbols(family)
+        elif args.abi_check:
+            compat.registry_check(paths, spec.load_registry(paths))
+            compat.check(family, paths.abi(family.name))
+        elif args.abi_update:
+            _abi_update(paths, family)
+        else:
+            _generate(args, family)
+    except CtlvError as exc:
+        print(f'ctlvgen: {exc}', file=sys.stderr)
+        return 1
+    return 0
+
+
+def _abi_update(paths, family):
+    path = paths.abi(family.name)
+    path.parent.mkdir(parents=True, exist_ok=True)
+    path.write_text(compat.render(family), encoding='utf-8')
+    print(f'ctlvgen: wrote {path}', file=sys.stderr)
+
+
+def _generate(args, family):
+    if args.header:
+        kind = 'header'
+    else:
+        kind = 'source'
+    if args.mode == 'kernel':
+        renderer = (gen_kernel.render_header if args.header
+                    else gen_kernel.render_source)
+        text = renderer(family, family_api=not args.schema_only)
+    else:
+        text = GENERATORS[(args.mode, kind)](family)
+    if args.output is None:
+        sys.stdout.write(text)
+        return
+    path = pathlib.Path(args.output)
+    # Leaving an unchanged file untouched keeps its timestamp, which is what
+    # ctlv-regen.sh compares against the specification.
+    if args.cmp_out and path.exists() and \
+            path.read_text(encoding='utf-8') == text:
+        return
+    path.write_text(text, encoding='utf-8')
+
+
+if __name__ == '__main__':
+    sys.exit(main())
diff --git a/tools/ctlv/ctlvgen/lib/__init__.py b/tools/ctlv/ctlvgen/lib/__init__.py
new file mode 100644
index 0000000000000..f84069cb2c3d0
--- /dev/null
+++ b/tools/ctlv/ctlvgen/lib/__init__.py
@@ -0,0 +1 @@
+# SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
diff --git a/tools/ctlv/ctlvgen/lib/cgen.py b/tools/ctlv/ctlvgen/lib/cgen.py
new file mode 100644
index 0000000000000..2cb754b42106d
--- /dev/null
+++ b/tools/ctlv/ctlvgen/lib/cgen.py
@@ -0,0 +1,825 @@
+# SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
+"""C output scaffolding shared by the CTLV generators.
+
+The preamble ctlv-regen.sh recovers a file's specification and mode from, which
+is why the specification stays directly above the marker.
+"""
+
+from __future__ import annotations
+
+import os
+
+from . import semantics
+from . import spec
+from .errors import CtlvError
+
+REGEN = 'tools/ctlv/ctlv-regen.sh'
+
+LINE_LIMIT = 100
+HARD_LINE_LIMIT = 100
+TAB_WIDTH = 8
+
+# C spelling of each primary form. A test checks these against
+# enum ctlv_schema_kind.
+KINDS = {
+    'uint': 'CTLV_SCHEMA_UINT',
+    'sint': 'CTLV_SCHEMA_SINT',
+    'bool': 'CTLV_SCHEMA_BOOL',
+    'string': 'CTLV_SCHEMA_STRING',
+    'binary': 'CTLV_SCHEMA_BINARY',
+    'enum': 'CTLV_SCHEMA_ENUM',
+    'flags': 'CTLV_SCHEMA_FLAGS',
+    'nested': 'CTLV_SCHEMA_NEST',
+    'blob': 'CTLV_SCHEMA_BLOB',
+}
+
+LIFECYCLE_API_SYMBOLS = (
+    'ctlv_create',
+    'ctlv_destroy',
+    'ctlv_family_priv_size_fn',
+    'ctlv_family_pre_init_fn',
+    'ctlv_family_init_fn',
+    'ctlv_family_post_init_fn',
+    'ctlv_family_pre_fini_fn',
+    'ctlv_family_fini_fn',
+    'ctlv_priv_parent',
+    'ctlv_priv_child',
+)
+
+
+def width(line):
+    """Return the display width of one line, a tab being eight columns."""
+    return len(line.expandtabs(TAB_WIDTH))
+
+
+def ident(*names):
+    """Return the lower case C spelling of one or more schema names."""
+    return '_'.join(name.replace('-', '_') for name in names)
+
+
+def macro(*names):
+    """Return the upper case C spelling of one or more schema names."""
+    return ident(*names).upper()
+
+
+def enum_tag(*names):
+    return f'_{ident(*names)}'
+
+
+def family_suffix(family_name):
+    suffix = family_name
+    if family_name.startswith('ctlv-'):
+        suffix = family_name.removeprefix('ctlv-')
+    return macro(suffix)
+
+
+def family_const(family_name):
+    if family_name == 'ctlv':
+        return 'CTLV_FAMILY_ROOT'
+    return f'CTLV_FAMILY_{family_suffix(family_name)}'
+
+
+def uapi_header(family_name, in_kernel=False):
+    """Return the include of the generated UAPI header of family_name."""
+    prefix = 'uapi/' if in_kernel else ''
+    return f'<{prefix}linux/{ident(family_name)}_gen.h>'
+
+
+def families_uapi_header(in_kernel=False):
+    prefix = 'uapi/' if in_kernel else ''
+    return f'<{prefix}linux/ctlv_families_gen.h>'
+
+
+def kernel_header(family_name):
+    """Return the include of the generated kernel header of family_name.
+
+    The root family's interface is installed beside <linux/ctlv.h>; any other
+    family's is private to the family implementation compiling it.
+    """
+    name = f'{ident(family_name)}_gen.h'
+    if family_name == spec.CORE_FAMILY_NAME:
+        return f'<linux/{name}>'
+    return f'"{name}"'
+
+
+def spec_path(path):
+    """Return path relative to the kernel tree that holds it.
+
+    ctlv-regen.sh resolves it from the tree root, so it must not depend on how
+    the generator was invoked. Outside a kernel tree it is recorded as given.
+    """
+    full = os.path.abspath(path)
+    relative = ''
+    while True:
+        relative = os.path.join(os.path.basename(full), relative)
+        parent = os.path.dirname(full)
+        if os.path.exists(os.path.join(parent, 'MAINTAINERS')):
+            return relative[:-1]
+        if parent == full:
+            return str(path)
+        full = parent
+
+
+def wrapped(opening, items, closing, trailer='', adaptive=False):
+    """Return the lines of one parenthesized list, wrapped at the limit.
+
+    trailer is what a continued line ends with beyond the item: a backslash
+    inside a macro definition, nothing elsewhere.
+    """
+    parts = [f'{item}, ' for item in items[:-1]] + [items[-1] + closing]
+    column = width(opening)
+    part_width = max(width(part.rstrip() + trailer) for part in parts)
+    indent_column = column
+    if adaptive:
+        indent_column = min(column, max(0, LINE_LIMIT - part_width))
+    indent = '\t' * (indent_column // TAB_WIDTH) + \
+        ' ' * (indent_column % TAB_WIDTH)
+    lines = []
+    line = opening
+    for part in parts:
+        if width(line + part.rstrip() + trailer) > LINE_LIMIT:
+            if line != opening:
+                lines.append(line.rstrip())
+            elif adaptive and opening.rstrip():
+                lines.append(opening.rstrip())
+            else:
+                line += part
+                continue
+            line = indent
+        line += part
+    lines.append(line.rstrip())
+    return lines
+
+
+class Writer:
+    """The lines of one generated file."""
+
+    def __init__(self):
+        self._lines = []
+
+    def line(self, text=''):
+        self._lines.append(text)
+
+    def comment(self, *lines):
+        """One comment block, one input line per output line."""
+        if len(lines) == 1:
+            self.line(f'/* {lines[0]} */')
+            return
+        self.line('/*')
+        for text in lines:
+            self.line(f' * {text}'.rstrip())
+        self.line(' */')
+
+    def define_block(self, name, *lines):
+        """One #define whose value takes more than the one line."""
+        header = f'#define {name} \\'
+        if width(header) > LINE_LIMIT and '(' in name:
+            macro, params = name.removesuffix(')').split('(', 1)
+            for text in wrapped(f'#define {macro}(',
+                                tuple(params.split(', ')), ')', ' \\',
+                                adaptive=True):
+                self.line(f'{text} \\')
+        else:
+            self.line(header)
+        for text in lines[:-1]:
+            self.line(f'{text} \\')
+        self.line(lines[-1])
+
+    def define(self, name, value):
+        """One #define, continued when it would run past the line limit."""
+        text = f'#define {name} {value}'
+        if width(text) <= LINE_LIMIT:
+            self.line(text)
+            return
+        self.define_block(name, f'\t{value}')
+
+    def define_call(self, name, function, *args):
+        """One #define whose value is a call, wrapped where it has to be."""
+        call = f'{function}({", ".join(args)})'
+        if width(f'#define {name} {call}') <= LINE_LIMIT:
+            self.line(f'#define {name} {call}')
+            return
+        if width(f'\t{call}') <= LINE_LIMIT:
+            self.define_block(name, f'\t{call}')
+            return
+        self.define_block(
+            name, *wrapped(f'\t{function}(', args, ')', ' \\',
+                           adaptive=True))
+
+    def declaration(self, prefix, declarator):
+        """One declaration, continued when it would run past the limit."""
+        text = f'{prefix} {declarator}'
+        if width(text) <= LINE_LIMIT:
+            self.line(text)
+            return
+        indent = prefix[:len(prefix) - len(prefix.lstrip('\t'))]
+        self.line(prefix)
+        continuation = f'{indent}\t'
+        if width(f'{continuation}{declarator}') > LINE_LIMIT:
+            continuation = '\t'
+        self.line(f'{continuation}{declarator}')
+
+    def parenthesized(self, opening, items, closing):
+        """One parenthesized list, wrapped at the line limit."""
+        for text in wrapped(opening, items, closing, adaptive=True):
+            self.line(text)
+
+    def assertion(self, left, operator, right):
+        """One static_assert, broken after its operator when it must be."""
+        opening = 'static_assert('
+        text = f'{opening}{left} {operator} {right});'
+        if width(text) <= LINE_LIMIT:
+            self.line(text)
+            return
+        column = width(opening)
+        indent = '\t' * (column // TAB_WIDTH) + ' ' * (column % TAB_WIDTH)
+        self.line(f'{opening}{left} {operator}')
+        self.line(f'{indent}{right});')
+
+    def signature(self, prefix, name, params, closing=');'):
+        """One function signature, wrapped at the line limit."""
+        lines = wrapped(f'{prefix} {name}(', params, closing)
+        one_line = f'{prefix} {name}({", ".join(params)}{closing}'
+        if lines[0].endswith('(') and width(one_line) <= HARD_LINE_LIMIT:
+            self.line(one_line)
+            return
+        if max(width(line) for line in lines) <= LINE_LIMIT:
+            for text in lines:
+                self.line(text)
+            return
+        if name.startswith('*'):
+            self.line(f'{prefix} *')
+            name = name.removeprefix('*')
+        else:
+            self.line(prefix)
+        declarator = f'{name}({", ".join(params)}{closing}'
+        if width(declarator) <= HARD_LINE_LIMIT:
+            self.line(declarator)
+            return
+        opening = f'{name}('
+        lines = wrapped(opening, params, closing)
+        if max(width(line) for line in lines) > LINE_LIMIT:
+            self.line(opening)
+            self.parenthesized('\t', params, closing)
+        else:
+            for text in lines:
+                self.line(text)
+
+    def open_guard(self, guard):
+        self.line(f'#ifndef {guard}')
+        self.line(f'#define {guard}')
+        self.line()
+
+    def close_guard(self, guard):
+        self.line(f'#endif /* {guard} */')
+
+    def includes(self, *headers):
+        """One include block, an empty entry separating two groups."""
+        for header in headers:
+            self.line(f'#include {header}' if header else '')
+        self.line()
+
+    def text(self):
+        while self._lines and not self._lines[-1]:
+            self._lines.pop()
+        return '\n'.join(self._lines) + '\n'
+
+
+def preamble(origin, mode, kind, source=None):
+    """Return a Writer holding the preamble of one generated file."""
+    writer = Writer()
+    if kind == 'source':
+        writer.line(f'// SPDX-License-Identifier: {origin.license}')
+    else:
+        writer.line(f'/* SPDX-License-Identifier: {origin.license} */')
+    writer.line(f'/* Do not edit, regenerate with {REGEN}, from: */')
+    writer.line(f'/*\t{spec_path(source or origin.path)} */')
+    writer.line(f'/* CTLV-GEN {mode} {kind} */')
+    writer.line()
+    return writer
+
+
+class Names:
+    """The C names of one effective family's declarations.
+
+    A declaration is named after the family that owns it, so an inherited attr
+    keeps the name its own family's header gives it.
+    """
+
+    def __init__(self, family):
+        self.family = family
+        self.prefix = macro(family.name)
+        self.ident = ident(family.name)
+
+    def owner_prefix(self, family_id):
+        return macro(self.family.owners[family_id])
+
+    def owner_ident(self, family_id):
+        return ident(self.family.owners[family_id])
+
+    # Names that a family's UAPI header defines.
+
+    def family_const(self):
+        return family_const(self.family.name)
+
+    def group(self, group):
+        return f'{self.owner_prefix(group.family_id)}_GROUP_' \
+               f'{macro(group.name)}'
+
+    def group_enum(self, group):
+        return enum_tag(self.family.owners[group.family_id], 'group')
+
+    def group_attr_enum(self, group):
+        return enum_tag(self.family.owners[group.family_id],
+                        'attr', group.name)
+
+    def group_metadata_enum(self, group):
+        return enum_tag(self.family.owners[group.family_id],
+                        'attr', group.name, 'metadata')
+
+    def group_attr(self, group):
+        return f'_{self.owner_prefix(group.family_id)}_ATTR_' \
+               f'{macro(group.name)}'
+
+    def family_attr(self, group):
+        return f'_{self.owner_prefix(group.family_id)}_ATTR'
+
+    def local_attr_prefix(self, group):
+        return f'_{self.owner_prefix(group.family_id)}_ATTR_' \
+               f'{macro(group.name)}_'
+
+    def local_attr(self, attr):
+        group = self.family.groups[attr.group]
+        return f'{self.local_attr_prefix(group)}{macro(attr.name)}'
+
+    def attr(self, attr):
+        return f'{self.owner_prefix(attr.family_id)}_ATTR_' \
+               f'{macro(attr.group, attr.name)}'
+
+    def attr_unit(self, attr):
+        return f'{self.attr(attr)}_UNIT'
+
+    def attr_scale(self, attr):
+        return f'{self.attr(attr)}_SCALE'
+
+    def attr_set(self, attr_set):
+        return f'{self.owner_prefix(attr_set.family_id)}_SET_' \
+               f'{macro(attr_set.name)}'
+
+    def set_enum(self, attr_set):
+        return enum_tag(self.family.owners[attr_set.family_id], 'set')
+
+    def op_prefix(self, op):
+        return f'_{self.owner_prefix(op.family_id)}_OP_'
+
+    def op(self, op):
+        return f'{self.op_prefix(op)}{macro(op.name)}'
+
+    def operation(self, op):
+        return f'_{self.owner_prefix(op.family_id)}_OP'
+
+    def op_enum(self, op):
+        return enum_tag(self.family.owners[op.family_id], 'op')
+
+    def op_id(self, op):
+        return f'{self.owner_prefix(op.family_id)}_OP_{macro(op.name)}'
+
+    def definition(self, definition):
+        """The C type name of an enum definition."""
+        return enum_tag(self.family.owners[definition.family_id],
+                        definition.name)
+
+    def value(self, definition, value_name):
+        """One enum value or flag bit."""
+        return f'{self.owner_prefix(definition.family_id)}_' \
+               f'{macro(definition.name, value_name)}'
+
+    def value_bit(self, definition, value_name):
+        return f'{self.value(definition, value_name)}_BIT'
+
+    def bit_enum(self, definition):
+        return enum_tag(self.family.owners[definition.family_id],
+                        definition.name, 'bit')
+
+    def value_mask(self, definition):
+        """The mask of every bit a flags definition declares."""
+        return f'{self.owner_prefix(definition.family_id)}_' \
+               f'{macro(definition.name)}_MASK'
+
+    # Names that a family's kernel metadata defines: its own ops and the
+    # stubs it fills.
+
+    def op_schemas(self):
+        return f'{self.ident}_op_schemas'
+
+    def schema(self):
+        return f'{self.ident}_schema'
+
+    def stub_fill_schemas(self):
+        return f'{self.ident}_stub_fill_schemas'
+
+    def node_schemas(self, op, which):
+        # File scope, so no family prefix: an op name is unique within its
+        # effective family.
+        return f'{ident(op.name)}_{which}_node_schemas'
+
+    def stub_schemas(self, op, which):
+        return f'{ident(op.name)}_{which}_stub_schemas'
+
+    def fill_node_schemas(self, fill):
+        return f'{ident(fill.name)}_fill_node_schemas'
+
+    def message_node_schemas(self, message):
+        return f'{ident(message.name)}_node_schemas'
+
+    def message_schema(self, message):
+        """The tree the core builds one of its own messages against."""
+        return f'{self.ident}_{ident(message.name)}_schema'
+
+    def message_max_len(self, message):
+        return f'{self.prefix}_{macro(message.name)}_MAX_LEN'
+
+    # Names that a family's device descriptor defines. Named after the family
+    # that declared what they answer: an inherited op is answered by that
+    # family implementation, on whatever device it arrived at.
+
+    def descriptor(self):
+        return f'{self.ident}_family'
+
+    def ops(self):
+        return f'{self.ident}_ops'
+
+    def stub_ops(self):
+        return f'{self.ident}_stub_ops'
+
+    def stub_ident(self, fill):
+        return f'{self.ident}_{ident(fill.name)}'
+
+    def stub_callback(self, fill, which):
+        """One half of what this family does with an extension point."""
+        return f'{self.stub_ident(fill)}_{which}'
+
+    def lifecycle_hook(self, which):
+        """One operation in the lifecycle of this family's priv."""
+        return f'{self.ident}_{which}'
+
+    def op_ident(self, op):
+        return f'{self.owner_ident(op.family_id)}_{ident(op.name)}'
+
+    def callback(self, op):
+        return f'{self.op_ident(op)}_{op.type}'
+
+    def op_helper(self, op, what):
+        """What one device decides about one op."""
+        return f'{self.op_ident(op)}_{what}'
+
+    def attr_helper(self, attr, what):
+        """One helper for one attr: reading it, or appending it.
+
+        Named after the family that declares the attr, like the constant that
+        names it on the wire.
+        """
+        return f'{self.owner_ident(attr.family_id)}_' \
+               f'{ident(attr.group, attr.name)}_{what}'
+
+    def attr_iterator(self, attr):
+        """What walks every occurrence of one repeated attr."""
+        return f'{self.owner_ident(attr.family_id)}_{ident(attr.group)}_' \
+               f'for_each_{ident(attr.name)}'
+
+    def input_name(self, scope, attr):
+        """The stem of one request-placement-specific reader."""
+        owner_parts = self.family.name.split('-')
+        group = ()
+        if attr.group not in (*scope.name, *owner_parts):
+            group = (attr.group,)
+        parts = (*scope.name, *group, attr.name)
+        parts = tuple(part for index, part in enumerate(parts)
+                      if not index or part != parts[index - 1])
+        return f'{self.ident}_{ident(*parts)}'
+
+    def input_helper(self, scope, attr, what):
+        return f'{self.input_name(scope, attr)}_{what}'
+
+    def input_iterator(self, scope, attr):
+        return self.input_helper(scope, attr, 'for_each')
+
+    def input_ref(self, scope, attr):
+        return self.input_helper(scope, attr, 'ref')
+
+    def family_hook(self, which):
+        """One half of the pair that wraps every op of this family."""
+        return f'{self.ident}_op_{which}'
+
+    def op_hook(self, op, which):
+        """One half of the pair that wraps this op alone."""
+        return f'{self.op_ident(op)}_{which}'
+
+    # Where a generated file lives: the installed constants, the schema
+    # metadata a family compiles, and the descriptor it registers.
+
+    def uapi_guard(self):
+        return f'_UAPI_LINUX_{self.prefix}_GEN_H'
+
+    def uapi_header(self, in_kernel=False):
+        return uapi_header(self.family.name, in_kernel)
+
+    def kernel_guard(self):
+        return f'_LINUX_{self.prefix}_GEN_H'
+
+    def kernel_header(self):
+        return kernel_header(self.family.name)
+
+    def user_guard(self):
+        return f'_CTLV_{self.prefix}_USER_GEN_H'
+
+    def user_header(self):
+        return f'"{self.ident}_user_gen.h"'
+
+    # Names that a family's userspace binding defines, after the family that
+    # declared the op, as a per-op helper is in the kernel.
+
+    def user_op(self, op):
+        return f'{self.owner_ident(op.family_id)}_{ident(op.name)}'
+
+    def user_op_helper(self, op, what):
+        return f'{self.user_op(op)}_{what}'
+
+    def user_op_len(self, op, what):
+        """One length of one op, as its specification computed it."""
+        return f'{self.op_id(op)}_{macro(what)}'
+
+    def user_node_schema(self, op, which):
+        # File scope, so no family prefix, as on the kernel side.
+        return f'{ident(op.name)}_{which}_node_schema'
+
+    def user_spec(self):
+        """What this family's specification says, to compare a device to."""
+        return f'{self.ident}_spec'
+
+    def user_op_specs(self):
+        return f'{self.ident}_op_specs'
+
+
+def attr_getter_value(attr):
+    """Whether an attr has a getter beside the reader that locates it."""
+    return attr.decl.kind != 'blob' and \
+        not (attr.decl.kind == 'nested' and attr.decl.max_occurrences != 1)
+
+
+def input_readers(names, scope, attr):
+    readers = [names.input_ref(scope, attr)]
+    readers.append(names.input_iterator(scope, attr)
+                   if attr.decl.max_occurrences != 1
+                   else names.input_helper(scope, attr, 'present'))
+    if attr.decl.kind == 'blob':
+        readers.append(names.input_helper(scope, attr, 'resolve'))
+    elif attr_getter_value(attr):
+        readers.append(names.input_helper(scope, attr, 'get'))
+    return tuple(readers)
+
+
+def attr_writers(names, attr):
+    """The names of what appends one attr, as the family API declares them.
+
+    A blob has none: a request carries one and a reply never does.
+    """
+    if attr.decl.kind == 'blob':
+        return ()
+    what = 'start' if attr.decl.kind == 'nested' else 'put'
+    return (names.attr_helper(attr, what),)
+
+
+# What a blob attr may be backed by, and the libctlv call describing one. A
+# putter exists per backing the placement permits, so what a caller may
+# describe is decided by the specification.
+BLOB_PUTTERS = {
+    'va': ('va', ('const void *address', '__u64 length')),
+}
+
+# What an event gets in the place of a wrapper.
+EVENT_HELPERS = ('is', 'subscribe', 'unsubscribe')
+
+# The lengths a user-mode header states for one op, by sizes.OpSizes member.
+USER_LENGTHS = {
+    'request_max_len': 'request-max-len',
+    'action_reply_max_len': 'action-reply-max-len',
+    'query_reply_min_len': 'query-reply-min-len',
+    'query_reply_suggested_len': 'query-reply-suggested-len',
+    'event_record_max_len': 'event-record-max-len',
+}
+
+
+def user_attr_readers(names, attr):
+    """The names of what reads one attr in the userspace binding."""
+    if attr.decl.kind == 'blob':
+        return ()
+    readers = [names.attr_iterator(attr) if attr.decl.max_occurrences != 1
+               else names.attr_helper(attr, 'present')]
+    if attr_getter_value(attr):
+        readers.append(names.attr_helper(attr, 'get'))
+    return tuple(readers)
+
+
+def user_attr_writers(names, attr):
+    """The names of what appends one attr in the userspace binding.
+
+    A blob has one putter per backing the placement allows, where the kernel
+    side has none.
+    """
+    if attr.decl.kind == 'blob':
+        return tuple(names.attr_helper(attr, f'put_{BLOB_PUTTERS[backing][0]}')
+                     for backing in attr.decl.blob.backings)
+    what = 'start' if attr.decl.kind == 'nested' else 'put'
+    return (names.attr_helper(attr, what),)
+
+
+def user_symbols(family):
+    """Return every C name of family's binding, mapped to its origin.
+
+    The binding covers this family's own attrs and ops, reaching the rest
+    through the parent's header.
+    """
+    names = Names(family)
+    table = {}
+
+    def add(name, origin):
+        previous = table.get(name)
+        if previous is not None:
+            raise CtlvError(f'{family.path}: {origin}',
+                            f'generated name {name} is already used by '
+                            f'{previous}')
+        table[name] = origin
+
+    for group in family.local_groups:
+        for attr in group.attrs:
+            what = f'attr {attr.full_name}'
+            for helper in user_attr_readers(names, attr) + \
+                    user_attr_writers(names, attr):
+                add(helper, what)
+    for op in family.local_ops:
+        what = f'op {op.name}'
+        # An event has those helpers and no wrapper of its own name.
+        if op.type == 'event':
+            for helper in EVENT_HELPERS:
+                add(names.user_op_helper(op, helper), what)
+        else:
+            add(names.user_op(op), what)
+            if op.request is not None:
+                add(names.user_op_helper(op, 'request_new'), what)
+        for field, what_len in USER_LENGTHS.items():
+            if getattr(op.sizes, field):
+                add(names.user_op_len(op, what_len), what)
+    return table
+
+
+def _stubs_anywhere(node):
+    return bool(node.stubs) or any(_stubs_anywhere(child)
+                                   for child in node.children())
+
+
+def symbols(family):
+    """Return every generated C name of family, mapped to its declaration.
+
+    Dashes become underscores, so two YAML names can spell one C name. That
+    has to be an error: one of the two constants would silently not exist.
+    """
+    names = Names(family)
+    table = {}
+
+    def add(name, origin):
+        previous = table.get(name)
+        if previous is not None:
+            raise CtlvError(f'{family.path}: {origin}',
+                            f'generated name {name} is already used by '
+                            f'{previous}')
+        table[name] = origin
+
+    for name in LIFECYCLE_API_SYMBOLS:
+        add(name, 'the CTLV lifecycle API')
+    add(names.family_const(), f'family {family.name}')
+    # A child header may include every ancestor's family API, and built-in
+    # families also share one linker namespace with the root.
+    for family_id, owner in family.owners.items():
+        owner_ident = ident(owner)
+        if any(op.family_id == family_id for op in family.ops):
+            add(f'{owner_ident}_op_schemas', f'family {owner}')
+        add(f'{owner_ident}_schema', f'family {owner}')
+        add(f'{owner_ident}_family', f'family {owner}')
+        for which in ('pre', 'post'):
+            add(f'{owner_ident}_op_{which}', f'family {owner}')
+        for which in ('priv_size', 'pre_init', 'init', 'post_init',
+                      'pre_fini', 'fini'):
+            add(f'{owner_ident}_device_{which}', f'family {owner}')
+    for fill in family.fills:
+        for which in ('fill', 'read'):
+            add(names.stub_callback(fill, which), f'attr set {fill.name}')
+    for definition in family.definitions.values():
+        what = f'{definition.kind} {definition.name}'
+        if definition.kind == 'enum':
+            add(f'enum {names.definition(definition)}', what)
+        else:
+            add(f'enum {names.bit_enum(definition)}', what)
+            add(names.value_mask(definition), what)
+        for value_name, _ in definition.values:
+            if definition.kind == 'flags':
+                add(names.value_bit(definition, value_name), what)
+            add(names.value(definition, value_name), what)
+    group_enums = set()
+    family_attrs = set()
+    for group in family.groups.values():
+        group_enum = f'enum {names.group_enum(group)}'
+        if group_enum not in group_enums:
+            add(group_enum, f'family {family.owners[group.family_id]} groups')
+            group_enums.add(group_enum)
+        family_attr = names.family_attr(group)
+        if family_attr not in family_attrs:
+            add(family_attr, f'family {family.owners[group.family_id]} attrs')
+            family_attrs.add(family_attr)
+        add(names.group(group), f'attr group {group.name}')
+        add(f'enum {names.group_attr_enum(group)}',
+            f'attr group {group.name}')
+        if any(attr.decl.unit is not None for attr in group.attrs):
+            add(f'enum {names.group_metadata_enum(group)}',
+                f'attr group {group.name} metadata')
+        add(names.group_attr(group), f'attr group {group.name}')
+        for attr in group.attrs:
+            what = f'attr {attr.full_name}'
+            add(names.local_attr(attr), what)
+            add(names.attr(attr), what)
+            if attr.decl.unit is not None:
+                add(names.attr_unit(attr), what)
+                add(names.attr_scale(attr), what)
+            for helper in attr_writers(names, attr):
+                add(helper, what)
+    for ancestor in family.chain[:-1]:
+        ancestor_names = Names(ancestor)
+        owner_family_id = next(
+            family_id for family_id, owner in family.owners.items()
+            if owner == ancestor.name)
+
+        for scope in semantics.input_scopes(family, owner_family_id):
+            for child in scope.node.children():
+                what = f'attr {child.attr.full_name} in ancestor ' \
+                       f'{ancestor.name}'
+                for helper in input_readers(ancestor_names, scope,
+                                            child.attr):
+                    add(helper, what)
+    for scope in semantics.input_scopes(family):
+        for child in scope.node.children():
+            what = f'attr {child.attr.full_name} in {".".join(scope.name)}'
+            for helper in input_readers(names, scope, child.attr):
+                add(helper, what)
+    set_enums = set()
+    for attr_set in family.sets.values():
+        set_enum = f'enum {names.set_enum(attr_set)}'
+        if set_enum not in set_enums:
+            add(set_enum, f'family {family.owners[attr_set.family_id]} sets')
+            set_enums.add(set_enum)
+        add(names.attr_set(attr_set), f'attr set {attr_set.name}')
+    operation_enums = set()
+    for op in family.ops:
+        what = f'op {op.name}'
+        operation_enum = f'enum {names.op_enum(op)}'
+        if operation_enum not in operation_enums:
+            add(operation_enum,
+                f'family {family.owners[op.family_id]} operations')
+            add(names.operation(op),
+                f'family {family.owners[op.family_id]} operations')
+            operation_enums.add(operation_enum)
+        add(names.op(op), what)
+        add(names.op_id(op), what)
+        if op.type == 'event':
+            add(names.op_helper(op, 'create'), what)
+            continue
+        add(names.callback(op), what)
+        if op.optional:
+            add(names.op_helper(op, 'provide'), what)
+        if op.availability == 'dynamic':
+            add(names.op_helper(op, 'enable'), what)
+            add(names.op_helper(op, 'disable'), what)
+        if op.pre_post:
+            add(names.op_hook(op, 'pre'), what)
+            add(names.op_hook(op, 'post'), what)
+    for message in family.messages:
+        what = f'attr set {message.name}'
+        add(names.message_node_schemas(message), what)
+        add(names.message_schema(message), what)
+        add(names.message_max_len(message), what)
+    if family.fills:
+        add(names.stub_fill_schemas(), f'family {family.name}')
+        add(names.stub_ops(), f'family {family.name}')
+    if any(op.type != 'event' for op in family.local_ops):
+        add(names.ops(), f'family {family.name}')
+    for op in family.local_ops:
+        what = f'op {op.name}'
+        for which in ('request', 'reply'):
+            root = getattr(op, which)
+            if root is None:
+                continue
+            add(names.node_schemas(op, which), what)
+            if _stubs_anywhere(root):
+                add(names.stub_schemas(op, which), what)
+    for fill in family.fills:
+        add(names.fill_node_schemas(fill), f'attr set {fill.name}')
+    return table
diff --git a/tools/ctlv/ctlvgen/lib/compat.py b/tools/ctlv/ctlvgen/lib/compat.py
new file mode 100644
index 0000000000000..4cf93af06ea90
--- /dev/null
+++ b/tools/ctlv/ctlvgen/lib/compat.py
@@ -0,0 +1,821 @@
+# SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
+"""ABI snapshots and the compatibility checker.
+
+A change is compatible only if the new schema still contains everything the
+checked-in snapshot describes, with the same IDs, no narrowed bound and no
+placement that became required. A new placement has to be optional. Updating a
+snapshot is deliberate: it is how the change gets reviewed.
+"""
+
+from __future__ import annotations
+
+import yaml
+
+from . import spec
+from . import yamlload
+from .errors import CtlvError
+
+HEADER = '''\
+# SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)
+%YAML 1.2
+---
+# Checked-in ABI snapshot of the {name} family, written by
+# "make -C tools/ctlv abi-update".
+#
+# The checker compares this family's declarations and inherited stub fills
+# against this file. Updating it is how a UAPI change gets reviewed; an update
+# that removes or renumbers anything, narrows a bound, or makes a placement
+# required is an ABI break, whatever this file says afterwards.
+'''
+
+REGISTRY_HEADER = '''\
+# 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.
+# Updated deliberately by "make -C tools/ctlv abi-update".
+'''
+
+
+class _Dumper(yaml.SafeDumper):
+    """Dumper that never emits anchors, which the strict loader rejects."""
+
+    def ignore_aliases(self, data):
+        return True
+
+    def increase_indent(self, flow=False, indentless=False):
+        # Indent a sequence under its key, not flush left as pyyaml does.
+        return super().increase_indent(flow, False)
+
+
+class _FlowMap(dict):
+    pass
+
+
+class _FlowSeq(list):
+    pass
+
+
+_Dumper.add_representer(
+    _FlowMap,
+    lambda dumper, value: dumper.represent_mapping(
+        'tag:yaml.org,2002:map', value, flow_style=True))
+_Dumper.add_representer(
+    _FlowSeq,
+    lambda dumper, value: dumper.represent_sequence(
+        'tag:yaml.org,2002:seq', value, flow_style=True))
+
+
+def build(family):
+    """Return one family's ABI in the comparison form."""
+    return {
+        'family': family.name,
+        'family-id': family.family_id,
+        'parent': family.parent,
+        'pre-init': family.pre_init,
+        'post-init': family.post_init,
+        'pre-fini': family.pre_fini,
+        'definitions': _definitions(family.local_definitions),
+        'groups': _groups(family.local_groups),
+        'sets': _sets(family.local_sets),
+        'fills': _fills(family.fills),
+        'ops': _ops(family.local_ops),
+    }
+
+
+def render(family):
+    """Return one family's compact snapshot as YAML text."""
+    return render_data(build(family))
+
+
+def render_data(data):
+    """Render comparison-form data as a compact snapshot."""
+    body = yaml.dump(_compact(data), Dumper=_Dumper, sort_keys=False,
+                     default_flow_style=False, width=1000000)
+    body = '\n'.join(line for source in body.splitlines()
+                     for line in _wrap_flow(source)) + '\n'
+    return HEADER.format(name=data['family']) + body
+
+
+def _wrap_flow(line, width=80):
+    """Wrap one flow collection with continuations aligned after its opener."""
+    if len(line) <= width:
+        return (line,)
+    starts = [index for index in (line.find('{'), line.find('['))
+              if index >= 0]
+    if not starts:
+        return (line,)
+    start = min(starts)
+    end, items = _flow_items(line, start)
+    if end is None:
+        return (line,)
+
+    prefix = line[:start + 1]
+    suffix = line[end:]
+    indent = ' ' * (start + 1)
+    wrapped = []
+    current = prefix
+    for index, item in enumerate(items):
+        last = index + 1 == len(items)
+        token = item + ('' if last else ',')
+        separator = '' if current.endswith(('{', '[')) else ' '
+        closing = len(suffix) if last else 0
+        if len(current) + len(separator) + len(token) + closing > width:
+            wrapped.append(current)
+            current = indent + token
+        else:
+            current += separator + token
+    current += suffix
+    wrapped.append(current)
+    return tuple(wrapped)
+
+
+def _flow_items(line, start):
+    pairs = {'{': '}', '[': ']'}
+    stack = [line[start]]
+    quote = None
+    escape = False
+    item_start = start + 1
+    items = []
+    for index in range(start + 1, len(line)):
+        char = line[index]
+        if quote is not None:
+            if escape:
+                escape = False
+            elif char == '\\':
+                escape = True
+            elif char == quote:
+                quote = None
+            continue
+        if char in ('"', "'"):
+            quote = char
+        elif char in pairs:
+            stack.append(char)
+        elif char in pairs.values():
+            if pairs[stack[-1]] != char:
+                return None, ()
+            stack.pop()
+            if not stack:
+                items.append(line[item_start:index].strip())
+                return index, tuple(item for item in items if item)
+        elif char == ',' and len(stack) == 1:
+            items.append(line[item_start:index].strip())
+            item_start = index + 1
+    return None, ()
+
+
+def check(family, path):
+    """Compare a family against its snapshot, or raise with every problem."""
+    snapshot = _expand(yamlload.load(path))
+    problems = _compare(snapshot, build(family))
+    if problems:
+        raise CtlvError(f'{family.name} against {path}',
+                        'the schema is not compatible with its snapshot\n' +
+                        '\n'.join(f'  {problem}' for problem in problems))
+
+
+def _compact(data):
+    family = _FlowMap({
+        'name': data['family'],
+        'id': data['family-id'],
+    })
+    if data['parent'] is not None:
+        family['inherits'] = data['parent']
+    for name in ('pre-init', 'post-init', 'pre-fini'):
+        if data[name]:
+            family[name] = True
+
+    compact = {'family': family}
+    for kind, section in (('enum', 'enums'), ('flags', 'flags')):
+        definitions = {
+            name: _FlowMap(entry['values'])
+            for name, entry in data['definitions'].items()
+            if entry['kind'] == kind
+        }
+        if definitions:
+            compact[section] = definitions
+    if data['groups']:
+        compact['attr-groups'] = _compact_groups(data['groups'])
+    if data['sets']:
+        compact['attr-sets'] = {
+            name: _FlowMap({
+                'id': entry['set-id'],
+                **({'stub': True} if entry.get('stub') else {}),
+            })
+            for name, entry in data['sets'].items()
+        }
+    if data['fills']:
+        compact['fills'] = {
+            name: _compact_tree(nodes)
+            for name, nodes in data['fills'].items()
+        }
+    if data['ops']:
+        compact['ops'] = {
+            name: _compact_op(entry)
+            for name, entry in data['ops'].items()
+        }
+    return compact
+
+
+def _compact_groups(groups):
+    compact = {}
+    for name, group in groups.items():
+        compact[name] = {
+            'id': group['group-id'],
+            'attrs': {
+                attr_name: _compact_attr(attr)
+                for attr_name, attr in group['attrs'].items()
+            },
+        }
+    return compact
+
+
+def _compact_attr(attr):
+    kind = attr['kind']
+    compact = _FlowMap({'id': attr['local-id']})
+    if kind in ('enum', 'flags'):
+        compact[kind] = attr['definition']
+    elif kind == 'blob':
+        blob = attr['blob']
+        compact['blob'] = blob['direction']
+        compact['backings'] = _FlowSeq(blob['backings'])
+        compact['max-length'] = blob['max-length']
+        if blob['alignment'] != 1:
+            compact['alignment'] = blob['alignment']
+    else:
+        compact['type'] = kind
+
+    if kind in ('uint', 'sint'):
+        low, high = ((0, spec.U64_MAX) if kind == 'uint'
+                     else (spec.S64_MIN, spec.S64_MAX))
+        minimum = attr.get('min', low)
+        maximum = attr.get('max', high)
+        if minimum != low:
+            compact['min'] = minimum
+        if maximum != high:
+            compact['max'] = maximum
+        if 'unit' in attr:
+            compact['unit'] = attr['unit']
+            if attr['scale']:
+                compact['scale'] = attr['scale']
+    elif kind in ('string', 'binary'):
+        minimum = attr.get('min-length', 0)
+        maximum = attr['max-length']
+        if kind == 'binary' and minimum == maximum:
+            compact['length'] = maximum
+        else:
+            if minimum:
+                compact['min-length'] = minimum
+            compact['max-length'] = maximum
+
+    maximum = attr['max-occurrences']
+    if maximum != 1:
+        compact['max-occurrences'] = (
+            'unlimited' if maximum == spec.UNLIMITED else maximum)
+    return compact
+
+
+def _compact_op(op):
+    abi = _FlowMap({
+        'id': op['op-id'],
+        'type': op['type'],
+    })
+    if (op['type'] != 'event' and
+            op.get('fd-access') != spec.DEFAULT_FD_ACCESS):
+        abi['fd-access'] = op.get('fd-access')
+    availability = op.get('availability', spec.DEFAULT_AVAILABILITY)
+    if availability != spec.DEFAULT_AVAILABILITY:
+        abi['availability'] = availability
+    if op.get('optional', False):
+        abi['optional'] = True
+    if op.get('pre-post', False):
+        abi['pre-post'] = True
+    compact = {'abi': abi}
+    if op.get('request'):
+        compact['request'] = _compact_tree(op['request'])
+    if op.get('reply') is not None:
+        compact['reply'] = _compact_tree(op['reply'])
+    return compact
+
+
+def _compact_tree(nodes):
+    required = []
+    optional = []
+    for node in nodes:
+        destination = required if node['required'] else optional
+        destination.append(_compact_node(node))
+    compact = {}
+    if required:
+        compact['attrs'] = _compact_nodes(required)
+    if optional:
+        compact['optional-attrs'] = _compact_nodes(optional)
+    if compact and _simple_tree_length(compact) <= 54:
+        return _FlowMap(compact)
+    return compact
+
+
+def _simple_tree_length(tree):
+    length = 2
+    for index, (name, selectors) in enumerate(tree.items()):
+        if not isinstance(selectors, _FlowSeq):
+            return 55
+        if index:
+            length += 2
+        length += len(name) + 4
+        length += sum(len(selector) + 2 for selector in selectors)
+    return length
+
+
+def _compact_nodes(nodes):
+    if all(isinstance(node, str) for node in nodes):
+        return _FlowSeq(nodes)
+    return nodes
+
+
+def _compact_node(node):
+    name = node.get('attr', node.get('stub'))
+    children = _compact_tree(node.get('children', []))
+    if 'reenters' in node:
+        children['reenters'] = node['reenters']
+    if not children:
+        return name
+    return {name: children}
+
+
+def _expand(compact):
+    family = compact['family']
+    family_id = family['id']
+    definitions = {}
+    for kind, section in (('enum', 'enums'), ('flags', 'flags')):
+        for name, values in compact.get(section, {}).items():
+            definitions[name] = {
+                'kind': kind,
+                'values': values,
+            }
+    return {
+        'family': family['name'],
+        'family-id': family_id,
+        'parent': family.get('inherits'),
+        'pre-init': family.get('pre-init', False),
+        'post-init': family.get('post-init', False),
+        'pre-fini': family.get('pre-fini', False),
+        'definitions': definitions,
+        'groups': _expand_groups(compact.get('attr-groups', {})),
+        'sets': _expand_sets(compact.get('attr-sets', {})),
+        'fills': {
+            name: _expand_tree(tree)
+            for name, tree in compact.get('fills', {}).items()
+        },
+        'ops': _expand_ops(compact.get('ops', {})),
+    }
+
+
+def _expand_groups(groups):
+    expanded = {}
+    for name, group in groups.items():
+        expanded[name] = {
+            'group-id': group['id'],
+            'attrs': {
+                attr_name: _expand_attr(attr)
+                for attr_name, attr in group['attrs'].items()
+            },
+        }
+    return expanded
+
+
+def _expand_attr(compact):
+    primary = [name for name in ('type', 'enum', 'flags', 'blob')
+               if name in compact]
+    if len(primary) != 1:
+        raise CtlvError('ABI snapshot attr',
+                        'expected one of type, enum, flags or blob')
+    kind = compact[primary[0]] if primary[0] == 'type' else primary[0]
+    attr = {
+        'local-id': compact['id'],
+        'kind': kind,
+        'max-occurrences': compact.get('max-occurrences', 1),
+    }
+    if attr['max-occurrences'] == 'unlimited':
+        attr['max-occurrences'] = spec.UNLIMITED
+    if kind in ('enum', 'flags'):
+        attr['definition'] = compact[kind]
+    elif kind in ('uint', 'sint'):
+        low, high = ((0, spec.U64_MAX) if kind == 'uint'
+                     else (spec.S64_MIN, spec.S64_MAX))
+        attr['min'] = compact.get('min', low)
+        attr['max'] = compact.get('max', high)
+        if 'unit' in compact:
+            attr['unit'] = compact['unit']
+            attr['scale'] = compact.get('scale', 0)
+    elif kind in ('string', 'binary'):
+        if 'length' in compact:
+            attr['min-length'] = compact['length']
+            attr['max-length'] = compact['length']
+        else:
+            attr['min-length'] = compact.get('min-length', 0)
+            attr['max-length'] = compact['max-length']
+    elif kind == 'blob':
+        attr['blob'] = {
+            'direction': compact['blob'],
+            'backings': list(compact['backings']),
+            'max-length': compact['max-length'],
+            'alignment': compact.get('alignment', 1),
+        }
+    return attr
+
+
+def _expand_sets(attr_sets):
+    return {
+        name: {
+            'set-id': entry['id'],
+            **({'stub': True} if entry.get('stub') else {}),
+        }
+        for name, entry in attr_sets.items()
+    }
+
+
+def _expand_ops(ops):
+    expanded = {}
+    for name, op in ops.items():
+        abi = op['abi']
+        op_type = abi['type']
+        entry = {
+            'op-id': abi['id'],
+            'type': op_type,
+            'availability': abi.get(
+                'availability', spec.DEFAULT_AVAILABILITY),
+            'optional': abi.get('optional', False),
+            'pre-post': abi.get('pre-post', False),
+            'request': (None if op_type == 'event'
+                        else _expand_tree(op.get('request', {}))),
+            'reply': (None if 'reply' not in op
+                      else _expand_tree(op['reply'])),
+        }
+        if op_type != 'event':
+            entry['fd-access'] = abi.get(
+                'fd-access', spec.DEFAULT_FD_ACCESS)
+        expanded[name] = entry
+    return expanded
+
+
+def _expand_tree(tree):
+    nodes = []
+    for required, key in ((True, 'attrs'), (False, 'optional-attrs')):
+        for selector in tree.get(key, []):
+            nodes.append(_expand_node(selector, required))
+    return nodes
+
+
+def _expand_node(selector, required):
+    if isinstance(selector, str):
+        name = selector
+        nested = {}
+    else:
+        if not isinstance(selector, dict) or len(selector) != 1:
+            raise CtlvError('ABI snapshot tree',
+                            'expected an attr name or one nested attr')
+        name, nested = next(iter(selector.items()))
+    if '.' not in name:
+        return {'stub': name, 'required': required}
+    node = {'attr': name, 'required': required}
+    children = _expand_tree(nested)
+    if children:
+        node['children'] = children
+    if 'reenters' in nested:
+        node['reenters'] = nested['reenters']
+    return node
+
+
+def registry_build(registry):
+    """Return the registry in the same normalized form as its source."""
+    families = []
+    for entry in registry.entries:
+        if entry.deprecated:
+            families.append({'name': entry.name, 'deprecated': True})
+        else:
+            families.append(entry.name)
+    return {'families': families}
+
+
+def registry_render(registry):
+    body = yaml.dump(registry_build(registry), Dumper=_Dumper,
+                     sort_keys=False, default_flow_style=False, width=76)
+    return REGISTRY_HEADER + body
+
+
+def registry_problems(old, current, exact):
+    problems = []
+    for family_id, was in enumerate(old.entries):
+        if family_id >= len(current.entries):
+            problems.append(f'family ID {family_id} ({was.name}) was removed')
+            continue
+        now = current.entries[family_id]
+        if now.name != was.name:
+            problems.append(f'family ID {family_id} was {was.name}, now '
+                            f'{now.name}')
+        elif was.deprecated and not now.deprecated:
+            problems.append(f'family ID {family_id} ({was.name}) was reused '
+                            'after deprecation')
+    if exact and not problems and old.entries != current.entries:
+        problems.append('the registry ABI baseline needs updating')
+    return problems
+
+
+def registry_check(paths, registry, exact=True):
+    baseline = spec.load_registry(paths, paths.registry_abi)
+    problems = registry_problems(baseline, registry, exact)
+    if problems:
+        raise CtlvError(f'{paths.registry} against {paths.registry_abi}',
+                        'the family registry is not compatible with its '
+                        'baseline\n' +
+                        '\n'.join(f'  {problem}' for problem in problems))
+
+
+def _definitions(items):
+    definitions = {}
+    for definition in items:
+        definitions[definition.name] = {
+            'kind': definition.kind,
+            'values': dict(definition.values),
+        }
+    return definitions
+
+
+def _groups(items):
+    groups = {}
+    for group in items:
+        groups[group.name] = {
+            'group-id': group.group_id,
+            'attrs': {attr.name: _attr(attr) for attr in group.attrs},
+        }
+    return groups
+
+
+def _attr(attr):
+    decl = attr.decl
+    entry = {'local-id': attr.local_id, 'kind': decl.kind}
+    if decl.ref is not None:
+        entry['definition'] = decl.ref
+    for name, value in (('min', decl.min), ('max', decl.max),
+                        ('min-length', decl.min_length),
+                        ('max-length', decl.max_length),
+                        ('unit', decl.unit), ('scale', decl.scale)):
+        if value is not None:
+            entry[name] = value
+    if decl.blob is not None:
+        entry['blob'] = {
+            'direction': decl.blob.direction,
+            'backings': list(decl.blob.backings),
+            'max-length': decl.blob.max_length,
+            'alignment': decl.blob.alignment,
+        }
+    entry['max-occurrences'] = decl.max_occurrences
+    return entry
+
+
+def _sets(attr_sets):
+    sets = {}
+    for attr_set in attr_sets:
+        entry = {
+            'set-id': attr_set.set_id,
+        }
+        if attr_set.stub:
+            entry['stub'] = True
+        sets[attr_set.name] = entry
+    return sets
+
+
+def _fills(fills):
+    return {fill.name: _tree(fill.root) for fill in fills}
+
+
+def _ops(items):
+    ops = {}
+    for op in items:
+        entry = {
+            'op-id': op.local_id,
+            'type': op.type,
+            'availability': op.availability,
+            'optional': op.optional,
+            'pre-post': op.pre_post,
+            'request': _tree(op.request),
+            'reply': _tree(op.reply),
+        }
+        if op.type != 'event':
+            entry['fd-access'] = op.fd_access
+        ops[op.name] = entry
+    return ops
+
+
+def _tree(root):
+    if root is None:
+        return None
+    children = [_node(child) for child in root.children()]
+    children += [_stub(stub) for stub in root.stubs]
+    return children
+
+
+def _node(node):
+    entry = {'attr': node.attr.full_name, 'required': node.required}
+    if node.reenters is not None:
+        # The members are recorded above, so record where they come from.
+        entry['reenters'] = node.reenters
+        return entry
+    children = _tree(node)
+    if children:
+        entry['children'] = children
+    return entry
+
+
+def _stub(stub):
+    return {'stub': stub.name, 'required': not stub.optional}
+
+
+def _compare(old, new):
+    problems = []
+    if old['family'] != new['family']:
+        problems.append(f'family was renamed from {old["family"]} to '
+                        f'{new["family"]}')
+    if old['family-id'] != new['family-id']:
+        problems.append(f'family-id was {old["family-id"]}, now '
+                        f'{new["family-id"]}')
+    # A name carries its ancestry, so reparenting renames every symbol.
+    if old['parent'] != new['parent']:
+        problems.append(f'the inherited family was {old["parent"]}, now '
+                        f'{new["parent"]}')
+    for key in ('pre-init', 'post-init', 'pre-fini'):
+        if old.get(key, False) != new[key]:
+            problems.append(f'family: {key} was {old.get(key, False)}, now '
+                            f'{new[key]}')
+    _compare_definitions(problems, old['definitions'], new['definitions'])
+    _compare_groups(problems, old['groups'], new['groups'])
+    _compare_sets(problems, old['sets'], new['sets'])
+    _compare_fills(problems, old['fills'], new['fills'])
+    _compare_ops(problems, old['ops'], new['ops'])
+    return problems
+
+
+def _compare_definitions(problems, old, new):
+    for name, was in old.items():
+        now = new.get(name)
+        if now is None:
+            problems.append(f'{was["kind"]} {name} was removed')
+            continue
+        where = f'{was["kind"]} {name}'
+        if now['kind'] != was['kind']:
+            problems.append(f'{where} is now a {now["kind"]} definition')
+        for value, number in was['values'].items():
+            if value not in now['values']:
+                problems.append(f'{where}: value {value} was removed')
+            elif now['values'][value] != number:
+                problems.append(f'{where}: value {value} was {number}, now '
+                                f'{now["values"][value]}')
+
+
+def _compare_groups(problems, old, new):
+    for name, was in old.items():
+        now = new.get(name)
+        if now is None:
+            problems.append(f'attr group {name} was removed')
+            continue
+        where = f'attr group {name}'
+        if was['group-id'] != now['group-id']:
+            problems.append(f'{where}: group-id was {was["group-id"]}, now '
+                            f'{now["group-id"]}')
+        for attr, attr_was in was['attrs'].items():
+            attr_now = now['attrs'].get(attr)
+            if attr_now is None:
+                problems.append(f'attr {name}.{attr} was removed')
+                continue
+            _compare_attr(problems, f'attr {name}.{attr}', attr_was, attr_now)
+
+
+def _compare_attr(problems, where, was, now):
+    for key in ('local-id', 'kind', 'definition', 'unit', 'scale'):
+        if was.get(key) != now.get(key):
+            problems.append(f'{where}: {key} was {was.get(key)}, now '
+                            f'{now.get(key)}')
+    for key in ('min', 'min-length'):
+        if key in was and now.get(key, 0) > was[key]:
+            problems.append(f'{where}: {key} was narrowed from {was[key]} to '
+                            f'{now[key]}')
+    for key in ('max', 'max-length'):
+        if key in was and now.get(key, 0) < was[key]:
+            problems.append(f'{where}: {key} was narrowed from {was[key]} to '
+                            f'{now[key]}')
+    _compare_occurrences(problems, where, was, now)
+    if 'blob' in was:
+        _compare_blob(problems, where, was['blob'], now.get('blob', {}))
+
+
+def _compare_occurrences(problems, where, was, now):
+    old_max = was['max-occurrences']
+    new_max = now['max-occurrences']
+    if old_max == new_max:
+        return
+    if old_max == spec.UNLIMITED or new_max < old_max:
+        problems.append(f'{where}: max-occurrences was narrowed from '
+                        f'{_occurrences(old_max)} to {_occurrences(new_max)}')
+
+
+def _compare_blob(problems, where, was, now):
+    for key in ('direction', 'alignment'):
+        if was.get(key) != now.get(key):
+            problems.append(f'{where}: blob {key} was {was.get(key)}, now '
+                            f'{now.get(key)}')
+    for backing in was.get('backings', []):
+        if backing not in now.get('backings', []):
+            problems.append(f'{where}: blob backing {backing} was removed')
+    if now.get('max-length', 0) < was.get('max-length', 0):
+        problems.append(f'{where}: blob max-length was narrowed from '
+                        f'{was["max-length"]} to {now["max-length"]}')
+
+
+def _compare_sets(problems, old, new):
+    for name, was in old.items():
+        now = new.get(name)
+        if now is None:
+            problems.append(f'attr set {name} was removed')
+            continue
+        for key in ('set-id', 'stub'):
+            was_value = was.get(key, False)
+            now_value = now.get(key, False)
+            if was_value != now_value:
+                problems.append(f'attr set {name}: {key} was {was_value}, '
+                                f'now {now_value}')
+
+
+def _compare_fills(problems, old, new):
+    for name, was in old.items():
+        now = new.get(name)
+        if now is None:
+            problems.append(f'stub fill {name} was removed')
+            continue
+        _compare_nodes(problems, f'stub fill {name}', was, now)
+
+
+def _compare_ops(problems, old, new):
+    for name, was in old.items():
+        now = new.get(name)
+        if now is None:
+            problems.append(f'op {name} was removed')
+            continue
+        where = f'op {name}'
+        # Whether an op may be disabled or withheld is what userspace compiles
+        # against; whether it is either right now is per device.
+        for key in ('op-id', 'type', 'fd-access',
+                    'availability', 'optional', 'pre-post'):
+            if was.get(key) != now.get(key):
+                problems.append(f'{where}: {key} was {was.get(key)}, now '
+                                f'{now.get(key)}')
+        for what in ('request', 'reply'):
+            if (what == 'reply' and was['type'] == 'action' and
+                    was[what] is None and now[what] is not None):
+                problems.append(f'{where}: an ACK-only action gained a '
+                                'reply schema')
+            elif was[what] is not None and now[what] is None:
+                problems.append(f'{where}: the {what} schema was removed')
+            elif was[what] is not None:
+                _compare_nodes(problems, f'{where} {what}', was[what],
+                               now[what])
+
+
+def _compare_nodes(problems, where, old, new):
+    by_name = {_node_key(node): node for node in new}
+    for was in old:
+        key = _node_key(was)
+        name = _node_name(was)
+        now = by_name.pop(key, None)
+        if now is None:
+            problems.append(f'{where}: {name} was removed')
+            continue
+        if now['required'] and not was['required']:
+            problems.append(f'{where}: {name} became required')
+        if was.get('reenters') != now.get('reenters'):
+            problems.append(f'{where}: {name} re-entered '
+                            f'{was.get("reenters")}, now '
+                            f'{now.get("reenters")}')
+        _compare_nodes(problems, f'{where} {name}',
+                       was.get('children', []), now.get('children', []))
+    for node in by_name.values():
+        if node['required']:
+            problems.append(
+                f'{where}: new {_node_name(node)} must be optional')
+
+
+def _node_key(node):
+    if 'attr' in node:
+        return 'attr', node['attr']
+    return 'stub', node['stub']
+
+
+def _node_name(node):
+    if 'attr' in node:
+        return node['attr']
+    return f'stub {node["stub"]}'
+
+
+def _occurrences(max_occurrences):
+    if max_occurrences == spec.UNLIMITED:
+        return 'unlimited'
+    return str(max_occurrences)
diff --git a/tools/ctlv/ctlvgen/lib/errors.py b/tools/ctlv/ctlvgen/lib/errors.py
new file mode 100644
index 0000000000000..a165218a381ea
--- /dev/null
+++ b/tools/ctlv/ctlvgen/lib/errors.py
@@ -0,0 +1,14 @@
+# SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
+"""The single error type reported by the CTLV schema tool."""
+
+
+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, what):
+        self.where = where
+        self.what = what
+        super().__init__(f'{where}: {what}' if where else what)
diff --git a/tools/ctlv/ctlvgen/lib/gen_family.py b/tools/ctlv/ctlvgen/lib/gen_family.py
new file mode 100644
index 0000000000000..92309334f979f
--- /dev/null
+++ b/tools/ctlv/ctlvgen/lib/gen_family.py
@@ -0,0 +1,347 @@
+# SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
+"""The descriptor of one family: who answers the wire.
+
+One struct ctlv_family and one struct ctlv_op per action or query
+this family declares, plus the helpers a device uses to decide them. A family
+answers what it declared: an inherited op is answered through the descriptor
+of the family that declared it, by that family implementation.
+"""
+
+from __future__ import annotations
+
+import dataclasses
+
+from . import cgen
+from . import spec
+
+# The family's priv, the request/reply, and a context for core helpers.
+CALLBACK_PARAMS = ('void *priv', 'struct ctlv_op_ctx *ctx',
+                   'const struct ctlv_cursor *request',
+                   'struct ctlv_cursor *reply')
+
+# What a hook takes, and what each half returns: a pre may refuse the op.
+HOOK_PARAMS = ('void *priv', 'struct ctlv_op_ctx *ctx')
+HOOK_RETURNS = (('pre', 'int'), ('post', 'void'))
+
+# How every family prepares, initializes and finalizes its priv.
+LIFECYCLE_HOOKS = (
+    ('priv_size', 'size_t', ('void',)),
+    ('pre_init', 'const void', ('const void *init_info',)),
+    ('init', 'int', ('struct ctlv_device *ctlvdev',
+                     'const void *init_info', 'void *priv')),
+    ('post_init', 'int', ('struct ctlv_device *ctlvdev', 'void *priv')),
+    ('pre_fini', 'void', ('struct ctlv_device *ctlvdev', 'void *priv')),
+    ('fini', 'void', ('struct ctlv_device *ctlvdev', 'void *priv')),
+)
+OPTIONAL_LIFECYCLE_HOOKS = ('pre_init', 'post_init', 'pre_fini')
+
+# The reply-side callback for an extension point.
+STUB_HOOKS = (
+    ('fill', 'int', ('void *priv', 'struct ctlv_op_ctx *ctx',
+                     'const struct ctlv_cursor *request',
+                     'struct ctlv_cursor *nest')),
+)
+
+# The state helpers of a dynamically available op.
+STATES = ('enable', 'disable')
+
+
+@dataclasses.dataclass(frozen=True)
+class ReaderScope:
+    name: tuple
+    node: object
+    tree: str
+    node_index: int
+
+
+INPUT_MACROS = {
+    'uint': 'U64',
+    'sint': 'S64',
+    'bool': 'BOOL',
+    'string': 'STRING',
+    'binary': 'BINARY',
+    'enum': 'U64',
+    'flags': 'U64',
+    'nested': 'NEST',
+    'blob': 'BLOB',
+}
+
+PUT_MACROS = {
+    'uint': 'U64',
+    'sint': 'S64',
+    'bool': 'BOOL',
+    'string': 'STRING',
+    'binary': 'BINARY',
+    'enum': 'U64',
+    'flags': 'U64',
+}
+
+
+def bindings(family):
+    """The ops family binds, in the order it binds them.
+
+    Its own actions and queries, in declaration order. An op it inherited is
+    answered by the family that declared it, and an event by nobody.
+    """
+    return tuple(op for op in family.local_ops if op.type != 'event')
+
+
+def _implementer(family):
+    """Who writes the callbacks of a family."""
+    if family.name == spec.CORE_FAMILY_NAME:
+        return 'the CTLV core'
+    return 'this family'
+
+
+def _macro(writer, name, args):
+    writer.parenthesized(f'{name}(', args, ')')
+
+
+def emit_header(writer, names, family, reader_scopes):
+    """Append the family API to a generated kernel header."""
+    bound = bindings(family)
+    if bound:
+        writer.comment(f'Implemented by {_implementer(family)}, one per '
+                       'action and query it declares.')
+    for op in bound:
+        writer.signature('int', names.callback(op), CALLBACK_PARAMS)
+    if bound:
+        writer.line()
+    _hooks(writer, names, family)
+    _lifecycle_hooks(writer, names, family)
+    _stub_hooks(writer, names, family)
+    writer.line()
+    writer.declaration('extern const struct ctlv_family',
+                       f'{names.descriptor()};')
+    writer.line()
+    writer.line('#ifndef _CTLV_GENERATED_METADATA_ONLY')
+    _helpers(writer, names, family)
+    _readers(writer, names, reader_scopes)
+    _writers(writer, names, family)
+    _creators(writer, names, family)
+    writer.line('#endif /* _CTLV_GENERATED_METADATA_ONLY */')
+    writer.line()
+
+
+def _hooks(writer, names, family):
+    """The pair around every op, and the pair around one op."""
+    if family.name == spec.CORE_FAMILY_NAME:
+        writer.comment('Root-family hooks around every core action or query.')
+    else:
+        writer.comment('Family-wide hooks around every effective non-core op.')
+    for which, returns in HOOK_RETURNS:
+        writer.signature(returns, names.family_hook(which), HOOK_PARAMS)
+
+    marked = [op for op in bindings(family) if op.pre_post]
+    if not marked:
+        return
+    writer.line()
+    writer.comment('Per-op hooks nested inside the family-wide pair.')
+    for first, op in enumerate(marked):
+        if first:
+            writer.line()
+        for which, returns in HOOK_RETURNS:
+            writer.signature(returns, names.op_hook(op, which), HOOK_PARAMS)
+
+
+def _declared_lifecycle_hooks(family):
+    return tuple(hook for hook in LIFECYCLE_HOOKS
+                 if hook[0] not in OPTIONAL_LIFECYCLE_HOOKS or
+                 getattr(family, hook[0]))
+
+
+def _lifecycle_hooks(writer, names, family):
+    """The generated lifecycle of this family's priv."""
+    writer.line()
+    writer.comment('Core-allocated family priv lifecycle.')
+    for which, returns, params in _declared_lifecycle_hooks(family):
+        name = names.lifecycle_hook(which)
+
+        writer.signature(returns, f'*{name}' if which == 'pre_init' else name,
+                         params)
+
+
+def _stub_hooks(writer, names, family):
+    """What this family puts into each stub it fills."""
+    if not family.fills:
+        return
+    for fill in family.fills:
+        owner = family.owners[fill.family_id]
+        writer.line()
+        writer.comment(f'{fill.name} of {owner}: fill callback.')
+        for which, returns, params in STUB_HOOKS:
+            writer.signature(returns, names.stub_callback(fill, which),
+                             params)
+
+
+def _helpers(writer, names, family):
+    """What one device may decide about each op this family declares."""
+    ops = [op for op in family.local_ops if op.type != 'event' and
+           (op.optional or op.availability == 'dynamic')]
+    if not ops:
+        return
+    writer.line()
+    writer.comment('Optional publication and dynamic availability helpers.')
+    for op in ops:
+        if op.optional:
+            _macro(writer, 'CTLV_OP_PROVIDE',
+                   (names.op_ident(op), names.op_id(op)))
+        if op.availability == 'dynamic':
+            for state in STATES:
+                _macro(writer, f'CTLV_OP_{state.upper()}',
+                       (names.op_ident(op), names.op_id(op)))
+
+
+def _readers(writer, names, scopes):
+    """Placement-specific indexed access to callback requests."""
+    if not any(scope.node.children() for scope in scopes):
+        return
+    writer.line()
+    writer.comment('Reading a validated message. A blob has a resolver '
+                   'instead of a getter.')
+    for scope in scopes:
+        for slot, child in enumerate(scope.node.children()):
+            attr = child.attr
+            repeated = attr.decl.max_occurrences != 1
+            name = _input_name(names, scope, attr)
+            _macro(writer, 'CTLV_IN_REF',
+                   _input_args(names, scope, slot, attr))
+            if repeated:
+                _iterator(writer, names, scope, attr)
+            else:
+                _macro(writer, 'CTLV_IN_HAS', (name,))
+            if attr.decl.kind == 'blob':
+                macro = 'CTLV_IN_' + ('EACH_' if repeated else '') + 'BLOB'
+                _macro(writer, macro, (name,))
+            elif cgen.attr_getter_value(attr):
+                macro = 'CTLV_IN_' + ('EACH_' if repeated else '') + \
+                        INPUT_MACROS[attr.decl.kind]
+                _macro(writer, macro, (name,))
+
+
+def _writers(writer, names, family):
+    """What a callback appends to the reply it was handed.
+
+    One helper per attr, returning whether the attr made it into the message.
+    """
+    attrs = [attr for group in family.local_groups for attr in group.attrs
+             if cgen.attr_writers(names, attr)]
+    if not attrs:
+        return
+    writer.line()
+    writer.comment('Writing a reply. An append is atomic; a nest ends with '
+                   'ctlv_nest_end().')
+    for attr in attrs:
+        if attr.decl.kind == 'nested':
+            macro = 'CTLV_NEST_START'
+        else:
+            macro = f'CTLV_PUT_{PUT_MACROS[attr.decl.kind]}'
+        what = 'start' if attr.decl.kind == 'nested' else 'put'
+        name = names.attr_helper(attr, what).removesuffix(f'_{what}')
+        _macro(writer, macro,
+               (name,
+                names.attr(attr), cgen.KINDS[attr.decl.kind]))
+
+
+def _creators(writer, names, family):
+    """What begins one event of each kind this family declares.
+
+    A creator hands back a context and the cursor of its root.
+    """
+    events = [op for op in family.local_ops if op.type == 'event']
+    if not events:
+        return
+    writer.line()
+    writer.comment('Building one event, passed to ctlv_event_emit() or '
+                   'ctlv_event_abort() once.')
+    for op in events:
+        _macro(writer, 'CTLV_EVENT_CREATE',
+               (names.op_ident(op), names.op_id(op)))
+
+
+def _input_name(names, scope, attr):
+    return names.input_ref(scope, attr).removesuffix('_ref')
+
+
+def _input_args(names, scope, slot, attr):
+    return (_input_name(names, scope, attr), scope.tree, names.attr(attr),
+            str(scope.node_index), str(slot), cgen.KINDS[attr.decl.kind])
+
+
+def _iterator(writer, names, scope, attr):
+    """Every occurrence of a repeated attr, in wire order."""
+    writer.define_call(
+        f'{names.input_iterator(scope, attr)}(_attr, _nest)',
+        'CTLV_IN_FOR_EACH', names.input_name(scope, attr), '_attr', '_nest')
+
+
+def emit_source(writer, names, family):
+    """Append the family bindings to a generated kernel source."""
+    _bindings(writer, names, family)
+    _stub_ops(writer, names, family)
+    _descriptor(writer, names, family)
+
+
+def _bindings(writer, names, family):
+    bound = bindings(family)
+    if not bound:
+        return
+    writer.comment('Local action and query bindings in declaration order.')
+    writer.declaration('static const struct ctlv_op',
+                       f'{names.ops()}[] = {{')
+    for op in bound:
+        suffix = '_PRE_POST' if op.pre_post else ''
+        writer.line(f'\tCTLV_OP_{op.type.upper()}{suffix}('
+                    f'{names.op_ident(op)}),')
+    writer.line('};')
+    writer.line()
+
+
+def _stub_ops(writer, names, family):
+    """One entry per extension point this family fills, in the same order."""
+    if not family.fills:
+        return
+    writer.comment('Extension-point callbacks.')
+    writer.declaration('static const struct ctlv_stub_ops',
+                       f'{names.stub_ops()}[] = {{')
+    for fill in family.fills:
+        attr_set = family.sets[fill.name]
+        args = (cgen.family_const(family.owners[fill.family_id]),
+                names.attr_set(attr_set), names.stub_ident(fill))
+        writer.parenthesized('\tCTLV_STUB_OPS(', args, '),')
+    writer.line('};')
+    writer.line()
+
+
+def _descriptor(writer, names, family):
+    if family.name == spec.CORE_FAMILY_NAME:
+        writer.comment('Root-family descriptor used by the CTLV core.')
+    else:
+        writer.comment('Family descriptor used by ctlv_create().')
+    writer.declaration('const struct ctlv_family',
+                       f'{names.descriptor()} = {{')
+    writer.line(f'\t.schema = &{names.schema()},')
+    parent = _parent_descriptor(family)
+    if parent:
+        writer.line(f'\t.parent = &{parent},')
+    if bindings(family):
+        writer.line(f'\t.ops = {names.ops()},')
+        writer.line(f'\t.ops_count = ARRAY_SIZE({names.ops()}),')
+    for which, _ in HOOK_RETURNS:
+        writer.line(f'\t.{which} = {names.family_hook(which)},')
+    for which, _, _ in _declared_lifecycle_hooks(family):
+        writer.line(f'\t.{which} = {names.lifecycle_hook(which)},')
+    if family.fills:
+        stub_ops = names.stub_ops()
+        writer.line(f'\t.stub_ops = {stub_ops},')
+        writer.line(f'\t.stub_ops_count = ARRAY_SIZE({stub_ops}),')
+    writer.line('};')
+    # The one symbol an inheriting family's module needs of this one.
+    writer.line(f'EXPORT_SYMBOL_NS_GPL({names.descriptor()}, "CTLV");')
+
+
+def _parent_descriptor(family):
+    """The direct parent descriptor, none only for the root family."""
+    if family.parent is None:
+        return None
+    return cgen.Names(family.chain[-2]).descriptor()
diff --git a/tools/ctlv/ctlvgen/lib/gen_kernel.py b/tools/ctlv/ctlvgen/lib/gen_kernel.py
new file mode 100644
index 0000000000000..1854bd004f367
--- /dev/null
+++ b/tools/ctlv/ctlvgen/lib/gen_kernel.py
@@ -0,0 +1,517 @@
+# SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
+"""The kernel metadata of one family.
+
+Each family describes only what it declares. Each op request and reply becomes
+one flat, breadth-first array of struct ctlv_node_schema the core walks by
+index.
+"""
+
+from __future__ import annotations
+
+import dataclasses
+
+from . import cgen
+from . import gen_family
+from . import semantics
+from . import spec
+
+
+def root_macro(*names):
+    """Return a constant of the root family's generated UAPI header."""
+    return cgen.macro(spec.CORE_FAMILY_NAME, *names)
+
+
+FD_ACCESSES = {access: root_macro('op-fd-access', access)
+               for access in spec.FD_ACCESSES}
+
+AVAILABILITIES = {availability: root_macro('op-availability', availability)
+                  for availability in spec.AVAILABILITIES}
+
+# Lengths that have to fit the inline message limit. An event record is checked
+# against the event queue instead.
+INLINE_FIELDS = ('request_max_len', 'action_reply_max_len',
+                 'query_reply_min_len', 'query_reply_suggested_len')
+
+# A bound written as its symbolic extreme stays readable.
+U64_MAX = (1 << 64) - 1
+S64_MIN = -(1 << 63)
+S64_MAX = (1 << 63) - 1
+EXTREMES = {
+    ('uint', spec.U32_MAX): 'U32_MAX',
+    ('uint', U64_MAX): 'U64_MAX',
+    ('sint', S64_MIN): 'S64_MIN',
+    ('sint', S64_MAX): 'S64_MAX',
+}
+
+
+@dataclasses.dataclass(frozen=True)
+class FlatNode:
+    """One node of a flattened tree, with its children as an index range."""
+
+    node: object
+    first_child: int
+    children_count: int
+    required_children_count: int
+
+
+def flatten(root):
+    """Return the nodes of one tree breadth first, the root first.
+
+    A re-entering node points back at nodes already laid out, which is what
+    keeps the array finite.
+    """
+    flat = []
+    queue = [(root, {})]
+    next_index = 1
+    while queue:
+        node, levels = queue.pop(0)
+        if node.reenters is not None:
+            first_child, children_count, required_count = levels[node.reenters]
+            flat.append(FlatNode(node=node, first_child=first_child,
+                                 children_count=children_count,
+                                 required_children_count=required_count))
+            continue
+        children = node.children()
+        level = (next_index if children else 0, len(children),
+                 len(node.required_children))
+        flat.append(FlatNode(node=node, first_child=level[0],
+                             children_count=level[1],
+                             required_children_count=level[2]))
+        next_index += len(children)
+        if node.expands:
+            levels = levels | {node.expands: level}
+        queue += [(child, levels) for child in children]
+    return tuple(flat)
+
+
+def stub_schemas(root):
+    """Return each stub schema with the node index it joins."""
+    schemas = []
+    for index, flat in enumerate(flatten(root)):
+        for stub in flat.node.stubs:
+            schemas.append((index, stub))
+    return tuple(schemas)
+
+
+def render_header(family, *, family_api):
+    """Return one family's generated kernel header."""
+    names = cgen.Names(family)
+    cgen.symbols(family)
+    guard = names.kernel_guard()
+    local = family.local_ops
+
+    writer = cgen.preamble(family, 'kernel', 'header')
+    what = 'Kernel metadata and family API' if family_api else \
+           'Schema metadata'
+    writer.comment(f'{what} of the {family.name} CTLV family.')
+    writer.line()
+    writer.open_guard(guard)
+    writer.includes(*_header_includes(family, names, family_api))
+
+    if local:
+        writer.comment('Ops this family declares, in declaration order.')
+        writer.declaration('extern const struct ctlv_op_schema',
+                           f'{names.op_schemas()}[];')
+        writer.line()
+    writer.declaration('extern const struct ctlv_family_schema',
+                       f'{names.schema()};')
+    writer.line()
+    _message_decls(writer, names, family)
+    if family_api:
+        gen_family.emit_header(writer, names, family,
+                               _reader_scopes(family, names))
+    writer.close_guard(guard)
+    return writer.text()
+
+
+def _reader_scopes(family, names):
+    scopes = []
+    indexes = {}
+    for scope in semantics.input_scopes(family):
+        if scope.kind == 'op':
+            root = family.local_ops[scope.index].request
+            tree = f'&{names.op_schemas()}[{scope.index}].request'
+        else:
+            root = family.fills[scope.index].root
+            tree = f'&{names.schema()}.stub_fill_schemas[' \
+                   f'{scope.index}].members'
+        key = (scope.kind, scope.index)
+        if key not in indexes:
+            indexes[key] = {id(flat.node): index
+                            for index, flat in enumerate(flatten(root))}
+        scopes.append(gen_family.ReaderScope(
+            name=scope.name, node=scope.node, tree=tree,
+            node_index=indexes[key][id(scope.node)]))
+    return tuple(scopes)
+
+
+def _message_decls(writer, names, family):
+    """The messages the core builds itself, and the room each one needs."""
+    for message in family.messages:
+        writer.comment(f'The {message.name} message, built by the core.')
+        writer.define(names.message_max_len(message), str(message.max_len))
+        writer.line()
+        writer.declaration('extern const struct ctlv_schema_tree',
+                           f'{names.message_schema(message)};')
+        writer.line()
+
+
+def _header_includes(family, names, family_api):
+    """The generated types, constants and direct parent API."""
+    headers = ['<linux/ctlv_family.h>']
+    if not family_api:
+        return tuple(headers)
+    headers += ['<linux/err.h>', '<linux/errno.h>', '',
+                names.uapi_header(in_kernel=True)]
+    if family.parent not in (None, spec.CORE_FAMILY_NAME):
+        headers += ['', cgen.Names(family.chain[-2]).kernel_header()]
+    return tuple(headers)
+
+
+def render_source(family, *, family_api):
+    """Return one family's generated kernel source."""
+    names = cgen.Names(family)
+    cgen.symbols(family)
+    trees = _trees(family)
+
+    writer = cgen.preamble(family, 'kernel', 'source')
+    if family_api:
+        writer.line('#define _CTLV_GENERATED_METADATA_ONLY')
+    writer.includes(*_includes(names, family, trees, family_api))
+    for op, which, root in trees:
+        _node_schemas(writer, family, names,
+                      names.node_schemas(op, which), root)
+        _stub_schemas(writer, family, names, op, which, root)
+    _stub_fill_schemas(writer, family, names)
+    _messages(writer, family, names)
+    _table(writer, names, family)
+    _descriptor(writer, names, family)
+    _uevent(writer, family)
+    _limits(writer, family, trees)
+    if family_api:
+        if family.local_ops:
+            writer.line()
+        gen_family.emit_source(writer, names, family)
+    return writer.text()
+
+
+def _trees(family):
+    """Every tree of every local op, in the order they are emitted."""
+    trees = []
+    for op in family.local_ops:
+        if op.request is not None:
+            trees.append((op, 'request', op.request))
+        if op.reply is not None:
+            trees.append((op, 'reply', op.reply))
+    return trees
+
+
+def _roots(family, trees):
+    """Every emitted tree root: an op's, a fill's and a core message's."""
+    return [root for _, _, root in trees] + \
+           [fill.root for fill in family.fills] + \
+           [message.root for message in family.messages]
+
+
+def _kinds(roots):
+    return {flat.node.attr.decl.kind
+            for root in roots for flat in flatten(root)
+            if not flat.node.is_root}
+
+
+def _includes(names, family, trees, family_api):
+    headers = ['<linux/array_size.h>', '<linux/build_bug.h>',
+               '<linux/ctlv_family.h>']
+    if family_api:
+        headers.append('<linux/export.h>')
+    # The root family's enums name op types, availabilities and blob backings.
+    uapi = [cgen.uapi_header(spec.CORE_FAMILY_NAME, in_kernel=True)]
+    if family.name != spec.CORE_FAMILY_NAME:
+        uapi.append(names.uapi_header(in_kernel=family_api))
+    kinds = _kinds(_roots(family, trees))
+    if 'blob' in kinds:
+        # BIT(), for the mask of permitted blob backings.
+        headers.append('<linux/bits.h>')
+    if kinds & {'uint', 'sint'}:
+        # The symbolic extremes of an unbounded integer bound.
+        headers.append('<linux/limits.h>')
+    groups = [sorted(headers), uapi, [names.kernel_header()]]
+    lines = []
+    for group in groups:
+        if not group:
+            continue
+        if lines:
+            lines.append('')
+        lines += group
+    return lines
+
+
+def _has_event(family):
+    return any(op.type == 'event' for op in family.local_ops)
+
+
+def _node_schemas(writer, family, names, symbol, root):
+    writer.declaration('static const struct ctlv_node_schema',
+                       f'{symbol}[] = {{')
+    for flat in flatten(root):
+        _node(writer, family, names, flat)
+    writer.line('};')
+    writer.line()
+
+
+def _node(writer, family, names, flat):
+    macro, args = _node_initializer(family, names, flat)
+    if macro == 'CTLV_NODE_SCHEMA_BLOB':
+        _blob_node(writer, macro, args)
+    else:
+        writer.parenthesized(f'\t{macro}(', args, '),')
+
+
+def _blob_node(writer, macro, args):
+    opening = f'\t{macro}('
+
+    for line in cgen.wrapped(opening, args[:4], ','):
+        writer.line(line)
+    column = cgen.width(opening)
+    indent = '\t' * (column // cgen.TAB_WIDTH) + \
+        ' ' * (column % cgen.TAB_WIDTH)
+    backings = args[4].split(' | ')
+    for backing in backings[:-1]:
+        writer.line(f'{indent}{backing} |')
+    writer.line(f'{indent}{backings[-1]},')
+    writer.line(f'{indent}{args[5]}),')
+
+
+def _node_initializer(family, names, flat):
+    node = flat.node
+
+    if node.is_root:
+        return 'CTLV_NODE_SCHEMA_ROOT', (
+            str(flat.first_child),
+            str(flat.children_count),
+            str(flat.required_children_count),
+        )
+
+    decl = node.attr.decl
+    kind = cgen.KINDS[decl.kind].removeprefix('CTLV_SCHEMA_')
+    macro = f'CTLV_NODE_SCHEMA_{kind}'
+    occurrences = str(node.max_occurrences) if node.max_occurrences else \
+        'CTLV_NODE_SCHEMA_UNLIMITED'
+    args = [names.attr(node.attr), occurrences]
+    if decl.kind == 'nested':
+        if node.reenters is not None:
+            macro += '_REENTERS'
+        args += [str(flat.first_child), str(flat.children_count),
+                 str(flat.required_children_count)]
+    else:
+        if decl.kind in ('uint', 'sint') and decl.unit is not None:
+            macro += '_UNIT'
+        args += _constraint_args(family, names, decl)
+    return macro, tuple(args)
+
+
+def _stub_schemas(writer, family, names, op, which, root):
+    """The extension points of one tree, by the node they widen."""
+    schemas = stub_schemas(root)
+    if not schemas:
+        return
+    writer.comment('Extension points selected by this tree.')
+    writer.declaration('static const struct ctlv_stub_schema',
+                       f'{names.stub_schemas(op, which)}[] = {{')
+    for index, stub in schemas:
+        macro = 'CTLV_STUB_SCHEMA_OPTIONAL' if stub.optional else \
+            'CTLV_STUB_SCHEMA'
+        attr_set = family.sets[stub.name]
+        args = (cgen.family_const(family.owners[stub.family_id]),
+                names.attr_set(attr_set), str(index))
+        writer.parenthesized(f'\t{macro}(', args, '),')
+    writer.line('};')
+    writer.line()
+
+
+def _stub_fill_schemas(writer, family, names):
+    """The members this family puts into the stubs it inherited."""
+    if not family.fills:
+        return
+    for fill in family.fills:
+        _node_schemas(writer, family, names,
+                      names.fill_node_schemas(fill), fill.root)
+    writer.comment('The extension points this family fills.')
+    writer.declaration('static const struct ctlv_stub_fill_schema',
+                       f'{names.stub_fill_schemas()}[] = {{')
+    for fill in family.fills:
+        attr_set = family.sets[fill.name]
+        args = (cgen.family_const(family.owners[fill.family_id]),
+                names.attr_set(attr_set), cgen.ident(fill.name))
+        writer.parenthesized('\tCTLV_STUB_FILL_SCHEMA(', args, '),')
+    writer.line('};')
+    writer.line()
+
+
+def _messages(writer, family, names):
+    """The messages the core builds where no op declared one."""
+    for message in family.messages:
+        _node_schemas(writer, family, names,
+                      names.message_node_schemas(message), message.root)
+        writer.declaration('const struct ctlv_schema_tree',
+                           f'{names.message_schema(message)} = {{')
+        node_schemas = names.message_node_schemas(message)
+        writer.line(f'\t.node_schemas = {node_schemas},')
+        writer.line('\t.node_schemas_count =')
+        writer.line(f'\t\tARRAY_SIZE({node_schemas}),')
+        writer.line('};')
+        writer.line()
+        writer.assertion(names.message_max_len(message), '<=', message.limit)
+        writer.line()
+
+
+def _constraint_args(family, names, decl):
+    """The kind-specific arguments of one node-schema macro."""
+    if decl.kind in ('uint', 'sint'):
+        low = _bound(decl.kind, decl.min)
+        high = _bound(decl.kind, decl.max)
+        args = [low, high]
+        if decl.unit is not None:
+            args += [f'CTLV_UNIT_{cgen.macro(decl.unit)}', str(decl.scale)]
+        return args
+    if decl.kind == 'enum':
+        highest = max(family.definitions[decl.ref].numbers())
+        return [str(highest)]
+    if decl.kind == 'flags':
+        return [names.value_mask(family.definitions[decl.ref])]
+    if decl.kind in ('string', 'binary'):
+        return [str(decl.min_length), str(decl.max_length)]
+    if decl.kind == 'blob':
+        return _blob_args(decl.blob)
+    return []
+
+
+def _bound(kind, value):
+    extreme = EXTREMES.get((kind, value))
+
+    if extreme:
+        return extreme
+    if kind == 'uint' and value > spec.S64_MAX:
+        return f'{value}ULL'
+    return str(value)
+
+
+def _blob_args(blob):
+    direction = root_macro('blob-direction', blob.direction)
+    return [_bound('uint', blob.max_length), str(blob.alignment),
+            _backings(blob.backings), direction]
+
+
+def _backings(backings):
+    terms = [f'BIT({root_macro("blob-type", backing)})'
+             for backing in backings]
+    return ' | '.join(terms)
+
+
+def _table(writer, names, family):
+    local = family.local_ops
+    if not local:
+        return
+    writer.comment('The ops this family declares, in declaration order.')
+    writer.declaration('const struct ctlv_op_schema',
+                       f'{names.op_schemas()}[] = {{')
+    for op in local:
+        macro, args = _op_schema_initializer(names, op)
+        writer.parenthesized(f'\t{macro}(', args, '),')
+    writer.line('};')
+    writer.line()
+
+
+def _op_schema_initializer(names, op):
+    sizes = op.sizes
+    if op.type == 'action':
+        macro = 'CTLV_OP_SCHEMA_ACTION'
+        args = [names.op_id(op), FD_ACCESSES[op.fd_access],
+                AVAILABILITIES[op.availability],
+                str(sizes.request_max_len),
+                str(sizes.action_reply_max_len),
+                _op_tree(op, 'request'), _op_tree(op, 'reply')]
+    elif op.type == 'query':
+        macro = 'CTLV_OP_SCHEMA_QUERY'
+        args = [names.op_id(op), FD_ACCESSES[op.fd_access],
+                AVAILABILITIES[op.availability],
+                str(sizes.request_max_len),
+                str(sizes.query_reply_min_len),
+                str(sizes.query_reply_suggested_len),
+                _op_tree(op, 'request'), _op_tree(op, 'reply')]
+    else:
+        macro = 'CTLV_OP_SCHEMA_EVENT'
+        args = [names.op_id(op), str(sizes.event_record_max_len),
+                _op_tree(op, 'reply')]
+    if op.optional:
+        args.append('.optional = true')
+    if op.pre_post:
+        args.append('.pre_post = true')
+    return macro, tuple(args)
+
+
+def _op_tree(op, which):
+    root = getattr(op, which)
+    if root is None:
+        return 'CTLV_SCHEMA_TREE_NONE()'
+    macro = 'CTLV_SCHEMA_TREE_STUBS' if stub_schemas(root) else \
+        'CTLV_SCHEMA_TREE'
+    return f'{macro}({cgen.ident(op.name, which)})'
+
+
+def _descriptor(writer, names, family):
+    """This family's node of the schema graph."""
+    writer.comment('The family ID is its position in the central registry.')
+    writer.declaration('const struct ctlv_family_schema',
+                       f'{names.schema()} = {{')
+    writer.line(f'\t.name = "{family.name}",')
+    writer.line(f'\t.family_id = {family.family_id},')
+    if family.local_ops:
+        writer.line(f'\t.ops = {names.op_schemas()},')
+        writer.line(f'\t.ops_count = ARRAY_SIZE({names.op_schemas()}),')
+    if family.fills:
+        stub_fill_schemas = names.stub_fill_schemas()
+        writer.line(f'\t.stub_fill_schemas = {stub_fill_schemas},')
+        writer.line(f'\t.stub_fill_schemas_count = '
+                    f'ARRAY_SIZE({stub_fill_schemas}),')
+    writer.line('};')
+    writer.line()
+
+
+def _uevent(writer, family):
+    """What this chain's names cost a device's uevent environment."""
+    names = [item.name for item in family.chain]
+    variables = [f'CTLV_FAMILY={names[-1]}']
+    variables += [f'CTLV_COMPATIBLE_{index}={name}'
+                  for index, name in enumerate(names)]
+    variables.append(f'CTLV_COMPATIBLE_N={len(names)}')
+    # "KEY=value" plus the NUL, as add_uevent_var() charges it.
+    writer.comment('Maximum uevent cost for this family chain.')
+    writer.line(f'static_assert({sum(len(item) + 1 for item in variables)} <= '
+                'CTLV_UEVENT_MAX_LEN);')
+    writer.line(f'static_assert({len(variables)} <= CTLV_UEVENT_MAX_VARS);')
+    writer.line()
+
+
+def _limits(writer, family, trees):
+    local = family.local_ops
+    if not local:
+        return
+    writer.comment('Guards for generated maxima.')
+    inline = max(getattr(op.sizes, field)
+                 for op in local for field in INLINE_FIELDS)
+    writer.line(f'static_assert({inline} <= CTLV_MAX_INLINE_MESSAGE_LEN);')
+    if _has_event(family):
+        record = max(op.sizes.event_record_max_len for op in local)
+        writer.line(f'static_assert({record} <= CTLV_MAX_EVENT_QUEUE_LEN);')
+    depth = max(_nest_depth(root) for root in _roots(family, trees))
+    if depth:
+        writer.line(f'static_assert({depth} <= '
+                    'CTLV_MAX_DECLARED_NEST_DEPTH);')
+
+
+def _nest_depth(node):
+    """Deepest nest below node, which is itself at depth zero."""
+    depths = [1 + _nest_depth(child) for child in node.children()
+              if child.attr.decl.kind == 'nested']
+    return max(depths, default=0)
diff --git a/tools/ctlv/ctlvgen/lib/gen_uapi.py b/tools/ctlv/ctlvgen/lib/gen_uapi.py
new file mode 100644
index 0000000000000..14330248f1444
--- /dev/null
+++ b/tools/ctlv/ctlvgen/lib/gen_uapi.py
@@ -0,0 +1,223 @@
+# SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
+"""The UAPI header of one family.
+
+Names for numbers: complete attr and op IDs, group and attr-set IDs, enum
+values, flag bits and units. The wire format is the transport
+header's. An inherited declaration is not repeated, already having a name in
+the header of the family that owns it.
+"""
+
+from __future__ import annotations
+
+import textwrap
+
+from . import cgen
+
+# " * " plus the text has to stay inside the line limit.
+COMMENT_WIDTH = cgen.LINE_LIMIT - 3
+
+
+def render(family):
+    """Return the UAPI header of family as text."""
+    names = cgen.Names(family)
+    cgen.symbols(family)
+    guard = names.uapi_guard()
+
+    writer = cgen.preamble(family, 'uapi', 'header')
+    _file_comment(writer, family)
+    writer.line()
+    writer.open_guard(guard)
+    writer.includes(*_includes(family))
+
+    _definitions(writer, family, names)
+    _groups(writer, family, names)
+    _sets(writer, family, names)
+    _ops(writer, family, names)
+
+    writer.close_guard(guard)
+    return writer.text()
+
+
+def render_families(registry):
+    """Return the family-number header of one registry."""
+    guard = '_UAPI_LINUX_CTLV_FAMILIES_GEN_H'
+    values = [(cgen.family_const(entry.name), family_id)
+              for family_id, entry in enumerate(registry.entries)]
+    writer = cgen.preamble(registry, 'uapi', 'header', registry.path)
+
+    writer.comment('CTLV family numbers.')
+    writer.line()
+    writer.open_guard(guard)
+    _sequential_enum(writer, '_ctlv_family', values)
+    writer.line()
+    writer.close_guard(guard)
+    return writer.text()
+
+
+def _includes(family):
+    headers = ['<linux/ctlv.h>', cgen.families_uapi_header()]
+    if family.parent:
+        # Inherited constants live in the parent's header, so one include is
+        # enough for the whole effective schema.
+        headers.append(cgen.uapi_header(family.parent))
+    if any(definition.kind == 'flags'
+           for definition in _own(family, family.definitions.values())):
+        # _BITULL(), which is the form of BIT_ULL() that userspace has.
+        headers.append('<linux/const.h>')
+    return sorted(headers)
+
+
+def _file_comment(writer, family):
+    paragraphs = [
+        f'Constants of the {family.name} CTLV family. Attr and op IDs are '
+        'complete; the wire format carrying them is in <linux/ctlv.h>.',
+    ]
+    if family.parent:
+        paragraphs.append(
+            f'The inherited {family.parent} header is included here, so one '
+            'include covers the whole effective schema.')
+    lines = []
+    for paragraph in paragraphs:
+        if lines:
+            lines.append('')
+        lines += textwrap.wrap(paragraph, COMMENT_WIDTH)
+    writer.comment(*lines)
+
+
+def _own(family, declarations):
+    """Only what this family declares itself, in declaration order."""
+    return [item for item in declarations
+            if item.family_id == family.family_id]
+
+
+def _definitions(writer, family, names):
+    for definition in _own(family, family.definitions.values()):
+        if definition.kind == 'enum':
+            _enum(writer, names, definition)
+        else:
+            _flags(writer, names, definition)
+        writer.line()
+
+
+def _enum(writer, names, definition):
+    writer.comment(f'enum {definition.name}')
+    values = [(names.value(definition, value_name), number)
+              for value_name, number in definition.values]
+    _sequential_enum(writer, names.definition(definition), values)
+
+
+def _flags(writer, names, definition):
+    writer.comment(f'flags {definition.name}')
+    bits = [(names.value_bit(definition, value_name), bit)
+            for value_name, bit in definition.values]
+    _sequential_enum(writer, names.bit_enum(definition), bits)
+    writer.line()
+    values = []
+    for value_name, _bit in definition.values:
+        value = names.value(definition, value_name)
+        writer.define(value,
+                      f'_BITULL({names.value_bit(definition, value_name)})')
+        values.append(value)
+    _flags_mask(writer, names.value_mask(definition), values)
+
+
+def _groups(writer, family, names):
+    groups = _own(family, family.groups.values())
+    if not groups:
+        return
+    writer.comment('attr groups')
+    _sequential_enum(writer, names.group_enum(groups[0]),
+                     [(names.group(group), group.group_id)
+                      for group in groups])
+    writer.line()
+    writer.define_call(
+        f'{names.family_attr(groups[0])}(_group, _attr)', 'CTLV_ATTR',
+        names.family_const(), '(_group)', '(_attr)')
+    writer.line()
+    for group in groups:
+        if not group.attrs:
+            continue
+        writer.comment(f'attrs of group {group.name}')
+        writer.define_call(f'{names.group_attr(group)}(_attr)',
+                           names.family_attr(group),
+                           names.group(group),
+                           f'{names.local_attr_prefix(group)}##_attr')
+        writer.line()
+        _sequential_enum(writer, names.group_attr_enum(group),
+                         [(names.local_attr(attr), attr.local_id)
+                          for attr in group.attrs])
+        writer.line()
+        for attr in group.attrs:
+            _attr(writer, names, group, attr)
+        _attr_metadata(writer, names, group)
+        writer.line()
+
+
+def _attr(writer, names, group, attr):
+    writer.define_call(names.attr(attr), names.group_attr(group),
+                       cgen.macro(attr.name))
+
+
+def _attr_metadata(writer, names, group):
+    attrs = [attr for attr in group.attrs if attr.decl.unit is not None]
+    if not attrs:
+        return
+    writer.line()
+    writer.comment(f'metadata of group {group.name}')
+    writer.line(f'enum {names.group_metadata_enum(group)} {{')
+    for attr in attrs:
+        writer.line(f'\t{names.attr_unit(attr)} = '
+                    f'CTLV_UNIT_{cgen.macro(attr.decl.unit)},')
+        writer.line(f'\t{names.attr_scale(attr)} = {attr.decl.scale},')
+    writer.line('};')
+
+
+def _sequential_enum(writer, name, values):
+    first = values[0][1]
+
+    assert all(number == first + index
+               for index, (_value, number) in enumerate(values))
+    writer.line(f'enum {name} {{')
+    for index, (value, number) in enumerate(values):
+        assignment = f' = {number}' if not index and number else ''
+        writer.line(f'\t{value}{assignment},')
+    writer.line('};')
+
+
+def _flags_mask(writer, name, values):
+    if len(values) == 1:
+        writer.define(name, values[0])
+        return
+    lines = [f'\t({values[0]} |']
+    lines += [f'\t {value} |' for value in values[1:-1]]
+    lines.append(f'\t {values[-1]})')
+    writer.define_block(name, *lines)
+
+
+def _sets(writer, family, names):
+    own = _own(family, family.sets.values())
+    if not own:
+        return
+    writer.comment('attr sets')
+    _sequential_enum(writer, names.set_enum(own[0]),
+                     [(names.attr_set(attr_set), attr_set.set_id)
+                      for attr_set in own])
+    writer.line()
+
+
+def _ops(writer, family, names):
+    own = _own(family, family.ops)
+    if not own:
+        return
+    writer.comment('ops')
+    _sequential_enum(writer, names.op_enum(own[0]),
+                     [(names.op(op), op.local_id)
+                      for op in own])
+    writer.line()
+    writer.define_call(f'{names.operation(own[0])}(_op)',
+                       'CTLV_OP', names.family_const(),
+                       f'{names.op_prefix(own[0])}##_op')
+    for op in own:
+        writer.define_call(names.op_id(op), names.operation(op),
+                           cgen.macro(op.name))
+    writer.line()
diff --git a/tools/ctlv/ctlvgen/lib/outputs.py b/tools/ctlv/ctlvgen/lib/outputs.py
new file mode 100644
index 0000000000000..4df7ae60c1c1e
--- /dev/null
+++ b/tools/ctlv/ctlvgen/lib/outputs.py
@@ -0,0 +1,329 @@
+# SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
+"""The complete set of generated files and its reconciliation."""
+
+from __future__ import annotations
+
+import dataclasses
+import os
+import pathlib
+import subprocess
+import tempfile
+
+from . import gen_kernel
+from . import gen_uapi
+from . import semantics
+from . import spec
+from . import yamlload
+from .errors import CtlvError
+
+
+FLAVOURS = {
+    'uapi-header': gen_uapi.render,
+    'kernel-header': gen_kernel.render_header,
+    'kernel-source': gen_kernel.render_source,
+}
+
+IDENTITIES = {
+    'uapi-header': ('uapi', 'header', '.h'),
+    'kernel-header': ('kernel', 'header', '.h'),
+    'kernel-source': ('kernel', 'source', '.c'),
+}
+
+ROOT_FLAVOURS = frozenset(FLAVOURS)
+FAMILY_FLAVOURS = frozenset(FLAVOURS)
+FIXTURE_FLAVOURS = frozenset({
+    'uapi-header', 'kernel-header', 'kernel-source',
+})
+
+
+@dataclasses.dataclass(frozen=True)
+class Output:
+    family: str
+    source: pathlib.PurePosixPath
+    registry: pathlib.PurePosixPath
+    flavour: str
+    path: pathlib.PurePosixPath
+
+
+def _spec_paths(paths, source, registry):
+    return spec.Paths(paths.kernel_dir / source, schema=paths.schema,
+                      registry=paths.kernel_dir / registry)
+
+
+def _relative(where, value):
+    path = pathlib.PurePosixPath(value)
+    if path.is_absolute() or '..' in path.parts or \
+            any(part.startswith('.') for part in path.parts) or \
+            str(path) != value:
+        raise CtlvError(where, f'"{value}" is not a normalized relative path')
+    return path
+
+
+def _repository_path(paths, path):
+    return pathlib.PurePosixPath(
+        pathlib.Path(path).relative_to(paths.kernel_dir).as_posix())
+
+
+def _manifest_contexts(paths):
+    fixtures_dir = paths.kernel_dir / 'tools/ctlv/tests/specs'
+    contexts = [
+        (paths.generated, _repository_path(paths, paths.registry),
+         _repository_path(paths, paths.spec_dir), None, False),
+    ]
+    manifest = fixtures_dir.parent / 'generated-files.yaml'
+    if manifest.exists():
+        fixtures = sorted(path.stem for path in fixtures_dir.glob('*.yaml'))
+        contexts.append((
+            manifest,
+            _repository_path(paths, fixtures_dir.parent / 'families.yaml'),
+            _repository_path(paths, fixtures_dir), fixtures, True))
+    return tuple(contexts)
+
+
+def load(paths):
+    """Load and validate every generated-file manifest."""
+    outputs = []
+    families = set()
+    destinations = set()
+    for manifest, expected_registry, source_dir, expected_names, fixture in \
+            _manifest_contexts(paths):
+        data = yamlload.load(manifest)
+        spec._validate_syntax(manifest, data, paths.generated_schema)
+        registry_record = data['registry']
+        where = f'{manifest}: registry'
+        registry_source = _relative(where, registry_record['source'])
+        if registry_source != expected_registry:
+            raise CtlvError(where, f'source is {registry_source}, expected '
+                                   f'{expected_registry}')
+        registry = spec.load_registry(
+            paths, paths.kernel_dir / registry_source)
+        if expected_names is None:
+            expected_names = [entry.name for entry in registry.entries]
+        records = data['families']
+        if [record['name'] for record in records] != expected_names:
+            raise CtlvError(str(manifest),
+                            'manifest families do not match their sources')
+
+        for flavour, value in registry_record['outputs'].items():
+            destination = _relative(f'{where} {flavour}', value)
+            suffix = IDENTITIES[flavour][2]
+            if destination.suffix != suffix:
+                raise CtlvError(f'{where} {flavour}',
+                                f'output must end in {suffix}')
+            if destination in destinations:
+                raise CtlvError(f'{where} {flavour}',
+                                f'duplicate output path {destination}')
+            destinations.add(destination)
+            outputs.append(Output(None, registry_source, registry_source,
+                                  flavour, destination))
+
+        for record in records:
+            name = record['name']
+            where = f'{manifest}: family {name}'
+            if name in families:
+                raise CtlvError(where, 'duplicate family')
+            families.add(name)
+
+            expected_source = source_dir / f'{name}.yaml'
+            source = _relative(where, record['source'])
+            if source != expected_source:
+                raise CtlvError(where, f'source is {source}, expected '
+                                       f'{expected_source}')
+
+            required = FIXTURE_FLAVOURS if fixture else FAMILY_FLAVOURS
+            if not fixture and name == spec.CORE_FAMILY_NAME:
+                required = ROOT_FLAVOURS
+            flavours = frozenset(record['outputs'])
+            if flavours != required:
+                missing = sorted(required - flavours)
+                extra = sorted(flavours - required)
+                detail = []
+                if missing:
+                    detail.append(f'missing {", ".join(missing)}')
+                if extra:
+                    detail.append(f'unexpected {", ".join(extra)}')
+                raise CtlvError(where, '; '.join(detail))
+
+            family = semantics.load(
+                _spec_paths(paths, source, registry_source))
+            if family.name != name:
+                raise CtlvError(where, f'source declares family '
+                                       f'{family.name}')
+            for flavour, value in record['outputs'].items():
+                destination = _relative(f'{where} {flavour}', value)
+                suffix = IDENTITIES[flavour][2]
+                if destination.suffix != suffix:
+                    raise CtlvError(f'{where} {flavour}',
+                                    f'output must end in {suffix}')
+                if destination in destinations:
+                    raise CtlvError(f'{where} {flavour}',
+                                    f'duplicate output path {destination}')
+                destinations.add(destination)
+                outputs.append(Output(name, source, registry_source, flavour,
+                                      destination))
+    return tuple(outputs)
+
+
+def render(paths, plan):
+    """Render every planned output before any destination is changed."""
+    families = {}
+    rendered = {}
+    registered_registry = _repository_path(paths, paths.registry)
+    for output in plan:
+        source = _output_source(output)
+        if output.family is None:
+            registry = spec.load_registry(
+                paths, paths.kernel_dir / output.registry)
+            text = gen_uapi.render_families(registry)
+        else:
+            key = (output.source, output.registry)
+            family = families.get(key)
+            if family is None:
+                family = semantics.load(
+                    _spec_paths(paths, output.source, output.registry))
+                families[key] = family
+            renderer = FLAVOURS[output.flavour]
+            if output.flavour in ('kernel-header', 'kernel-source'):
+                text = renderer(
+                    family, family_api=output.registry == registered_registry)
+            else:
+                text = renderer(family)
+        mode, kind, _ = IDENTITIES[output.flavour]
+        if _identity(text) != (source, mode, kind):
+            raise CtlvError(str(output.path),
+                            'generator emitted the wrong output marker')
+        rendered[output.path] = text
+    return rendered
+
+
+def _output_source(output):
+    return output.source.as_posix()
+
+
+def _marked_files(root):
+    if (root / '.git').exists():
+        result = subprocess.run(
+            ['git', 'grep', '--untracked', '--files-with-matches',
+             'CTLV-GEN', '--', '*.c', '*.h', '*.rst'],
+            cwd=root, capture_output=True, text=True, check=False)
+        if result.returncode not in (0, 1):
+            raise CtlvError(str(root), result.stderr.strip())
+        candidates = (root / line for line in result.stdout.splitlines())
+    else:
+        candidates = (path for suffix in ('*.c', '*.h', '*.rst')
+                      for path in root.rglob(suffix))
+
+    marked = set()
+    for path in candidates:
+        if path.is_symlink() or not path.is_file():
+            continue
+        text = path.read_text(encoding='utf-8', errors='replace')
+        if _identity(text) is not None:
+            marked.add(path.relative_to(root).as_posix())
+    return marked
+
+
+def _destination(root, relative):
+    destination = root.joinpath(*relative.parts)
+    if destination.is_symlink():
+        raise CtlvError(str(destination),
+                        'generated output cannot be a symlink')
+    parent = destination.parent
+    while parent != root and not parent.exists():
+        parent = parent.parent
+    if parent.is_symlink() or root.resolve() not in (
+            parent.resolve(), *parent.resolve().parents):
+        raise CtlvError(str(destination),
+                        'generated output escapes its output root')
+    return destination
+
+
+def _replace(destination, text):
+    destination.parent.mkdir(parents=True, exist_ok=True)
+    fd, temporary = tempfile.mkstemp(dir=destination.parent,
+                                     prefix=f'.{destination.name}.')
+    try:
+        with os.fdopen(fd, 'w', encoding='utf-8') as stream:
+            stream.write(text)
+        os.chmod(temporary, 0o644)
+        os.replace(temporary, destination)
+    finally:
+        if os.path.exists(temporary):
+            os.unlink(temporary)
+
+
+def _identity(text):
+    lines = text.splitlines()
+    if len(lines) < 4:
+        return None
+    c_spdx = (lines[0].startswith('// SPDX-License-Identifier: ') or
+              (lines[0].startswith('/* SPDX-License-Identifier: ') and
+               lines[0].endswith(' */')))
+    if c_spdx and \
+            lines[1] == ('/* Do not edit, regenerate with '
+                         'tools/ctlv/ctlv-regen.sh, from: */') and \
+            lines[2].startswith('/*\t') and lines[2].endswith(' */') and \
+            lines[3].startswith('/* CTLV-GEN ') and lines[3].endswith(' */'):
+        source = lines[2][3:-3]
+        fields = lines[3][3:-3].split()
+    elif lines[0].startswith('.. SPDX-License-Identifier: ') and \
+            lines[1] == ('.. Do not edit, regenerate with '
+                         'tools/ctlv/ctlv-regen.sh, from:') and \
+            lines[2].startswith('..\t') and \
+            lines[3].startswith('.. CTLV-GEN '):
+        source = lines[2][3:]
+        fields = lines[3][3:].split()
+    else:
+        return None
+    if len(fields) == 3 and fields[0] == 'CTLV-GEN':
+        return source, fields[1], fields[2]
+    return None
+
+
+def reconcile(paths, output_root=None, check=False):
+    """Check or atomically update every generated output."""
+    plan = load(paths)
+    rendered = render(paths, plan)
+    root = pathlib.Path(paths.kernel_dir if output_root is None
+                        else output_root)
+    if not root.is_dir():
+        raise CtlvError(str(root), 'output root is not a directory')
+    expected = {output.path.as_posix() for output in plan}
+    unexpected = sorted(_marked_files(root) - expected)
+    if unexpected:
+        raise CtlvError('generated outputs',
+                        'unexpected files\n' +
+                        '\n'.join(f'  {path}' for path in unexpected))
+
+    states = {}
+    problems = []
+    unsafe = []
+    by_path = {output.path: output for output in plan}
+    for relative, text in rendered.items():
+        destination = _destination(root, relative)
+        if not destination.exists():
+            problems.append(f'missing {relative}')
+            states[relative] = (destination, text)
+            continue
+        if not destination.is_file():
+            raise CtlvError(str(destination),
+                            'generated output is not a regular file')
+        current = destination.read_text(encoding='utf-8')
+        if current == text:
+            continue
+        problems.append(f'stale {relative}')
+        output = by_path[relative]
+        mode, kind, _ = IDENTITIES[output.flavour]
+        if not check and _identity(current) != (
+                _output_source(output), mode, kind):
+            unsafe.append(f'{relative} is not the planned generated file')
+        states[relative] = (destination, text)
+    if unsafe:
+        raise CtlvError('generated outputs',
+                        'refusing to overwrite files\n' +
+                        '\n'.join(f'  {problem}' for problem in unsafe))
+    if check and problems:
+        raise CtlvError('generated outputs', '\n'.join(problems))
+    for destination, text in states.values():
+        _replace(destination, text)
+    return tuple(problems)
diff --git a/tools/ctlv/ctlvgen/lib/semantics.py b/tools/ctlv/ctlvgen/lib/semantics.py
new file mode 100644
index 0000000000000..83290bfb2f460
--- /dev/null
+++ b/tools/ctlv/ctlvgen/lib/semantics.py
@@ -0,0 +1,893 @@
+# SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
+"""The effective form of a CTLV family.
+
+The specifications of one inheritance chain resolved into one schema: numeric
+IDs from declaration positions, selectors expanded into placements, and one
+tree per op request and reply. A rule enforced here is not re-enforced
+downstream.
+"""
+
+from __future__ import annotations
+
+import dataclasses
+
+from . import sizes
+from . import spec
+from .errors import CtlvError
+
+MAX_FLAG_BITS = 64
+
+# These root enums are stored more narrowly than a generic enum range.
+ROOT_ENUM_VALUES_MAX = {
+    'op-type': spec.U8_MAX,
+    'op-availability': spec.U8_MAX,
+    'op-fd-access': spec.U8_MAX,
+    'blob-direction': spec.U8_MAX,
+    # BIT(value) is stored in struct ctlv_node_schema.blob.backings.
+    'blob-type': 15,
+}
+
+
+def _check_count(where, what, count, maximum):
+    if count > maximum:
+        raise CtlvError(where, f'{count} {what} exceed the {maximum} maximum')
+
+
+@dataclasses.dataclass(frozen=True)
+class Definition:
+    """An effective enum or flags definition."""
+
+    name: str
+    kind: str
+    family_id: int
+    values: tuple
+
+    def numbers(self):
+        return tuple(number for _, number in self.values)
+
+
+@dataclasses.dataclass(frozen=True)
+class Attr:
+    """An effective attr, with its complete wire ID."""
+
+    group: str
+    name: str
+    family_id: int
+    group_id: int
+    local_id: int
+    attr_id: int
+    decl: spec.AttrDecl
+
+    @property
+    def full_name(self):
+        return f'{self.group}.{self.name}'
+
+
+@dataclasses.dataclass(frozen=True)
+class Group:
+    name: str
+    family_id: int
+    group_id: int
+    attrs: tuple
+
+
+@dataclasses.dataclass(frozen=True)
+class AttrSet:
+    """An effective attr set. A stub that nobody filled stays a stub."""
+
+    name: str
+    family_id: int
+    set_id: int
+    stub: bool
+    attrs: tuple
+    optional_attrs: tuple
+
+
+@dataclasses.dataclass(frozen=True)
+class Stub:
+    """One place where a descendant's fill of a stub splices in.
+
+    The declaring family's metadata carries this in place of those members.
+    """
+
+    name: str
+    family_id: int
+    set_id: int
+    optional: bool
+
+
+@dataclasses.dataclass(frozen=True)
+class Fill:
+    """The members one family puts into a stub it inherited.
+
+    root stands for the stub itself, so its children are what splices in.
+    """
+
+    name: str
+    owner_family_id: int
+    family_id: int
+    set_id: int
+    root: Node
+
+
+@dataclasses.dataclass(frozen=True)
+class Node:
+    """One node of an expanded op tree. The root has no attr.
+
+    stubs are the extension points selected here and still unfilled. A
+    recursive nest becomes a node naming the set in expands and childless
+    nodes below it naming it in reenters, so walking children terminates.
+    """
+
+    attr: Attr
+    required: bool
+    max_occurrences: int
+    required_children: tuple
+    optional_children: tuple
+    stubs: tuple = ()
+    expands: str = None
+    reenters: str = None
+
+    @property
+    def is_root(self):
+        return self.attr is None
+
+    def children(self):
+        return self.required_children + self.optional_children
+
+
+@dataclasses.dataclass(frozen=True)
+class Message:
+    """One message root that no op declares, built by the core unasked.
+
+    Only the root family declares one.
+    """
+
+    name: str
+    family_id: int
+    set_id: int
+    root: Node
+    max_len: int
+    limit: str
+
+
+@dataclasses.dataclass(frozen=True)
+class Op:
+    """An effective op.
+
+    availability is the permission to enable and disable the op per device,
+    not a state. optional means a device has the op only once its family opts
+    in. pre_post asks for a pair of this op's own, on top of the family-wide
+    one.
+    """
+
+    name: str
+    type: str
+    fd_access: str
+    availability: str
+    optional: bool
+    pre_post: bool
+    family_id: int
+    local_id: int
+    op_id: int
+    request: Node
+    reply: Node
+    sizes: sizes.OpSizes
+
+
+@dataclasses.dataclass(frozen=True)
+class Family:
+    """One effective family: itself plus everything it inherits.
+
+    owners maps a family ID to its name for every family in the chain. fills
+    is what a generator emits, chain_fills what a device answers with.
+    """
+
+    name: str
+    family_id: int
+    path: str
+    chain: tuple
+    owners: dict
+    definitions: dict
+    groups: dict
+    attrs: dict
+    sets: dict
+    ops: tuple
+    fills: tuple
+    chain_fills: tuple
+    messages: tuple
+
+    @property
+    def parent(self):
+        return self.chain[-1].inherits
+
+    @property
+    def license(self):
+        return self.chain[-1].license
+
+    @property
+    def pre_init(self):
+        return self.chain[-1].pre_init
+
+    @property
+    def post_init(self):
+        return self.chain[-1].post_init
+
+    @property
+    def pre_fini(self):
+        return self.chain[-1].pre_fini
+
+    def _local(self, items):
+        return tuple(item for item in items
+                     if item.family_id == self.family_id)
+
+    @property
+    def local_definitions(self):
+        return self._local(self.definitions.values())
+
+    @property
+    def local_groups(self):
+        return self._local(self.groups.values())
+
+    @property
+    def local_sets(self):
+        """Sets this family declares, a stub it inherited excluded."""
+        return self._local(self.sets.values())
+
+    @property
+    def local_ops(self):
+        return self._local(self.ops)
+
+
+@dataclasses.dataclass(frozen=True)
+class InputScope:
+    kind: str
+    index: int
+    name: tuple
+    node: Node
+
+
+def input_scopes(family, owner_family_id=None):
+    """Every schema scope family code may read, with a unique name."""
+    def walk(kind, index, name, node):
+        yield InputScope(kind, index, name, node)
+        for child in node.children():
+            if child.attr.decl.kind != 'nested':
+                continue
+            child_name = name + (child.attr.name,)
+            yield from walk(kind, index, child_name, child)
+
+    if owner_family_id is None:
+        ops = family.local_ops
+        fills = family.fills
+    else:
+        ops = tuple(op for op in family.ops
+                    if op.family_id == owner_family_id)
+        fills = tuple(fill for fill in family.chain_fills
+                      if fill.owner_family_id == owner_family_id)
+
+    for index, op in enumerate(ops):
+        if op.request is not None:
+            yield from walk('op', index, (op.name,), op.request)
+    for index, fill in enumerate(fills):
+        yield from walk('fill', index, (fill.name,), fill.root)
+
+
+def load(paths):
+    """Load the family at paths.spec, resolved against its whole chain."""
+    registry = spec.load_registry(paths)
+    return _Resolver(paths, registry).resolve()
+
+
+class _Resolver:
+    def __init__(self, paths, registry):
+        self.paths = paths
+        self.registry = registry
+        self.definitions = {}
+        self.groups = {}
+        self.attrs = {}
+        self.sets = {}
+        self.ops = []
+        # Which family filled each stub, to name it if a second one tries.
+        self.stub_fillers = {}
+        # Where each set was declared, for diagnostics.
+        self.set_paths = {}
+
+    def resolve(self):
+        chain = self._load_chain()
+        self._check_names(chain)
+        self._check_order(chain)
+        target = chain[-1]
+        for family in chain:
+            self._add_family(family)
+        self._check_sets()
+        for family in chain:
+            self._add_ops(family)
+        fills = self._fills(target)
+        chain_fills = self._fills(None)
+        _check_count(f'{target.path}: family {target.name}', 'stub fills',
+                     len(fills), spec.U32_MAX)
+        resolved = Family(
+            name=target.name,
+            family_id=self._family_id(target),
+            path=target.path,
+            chain=chain,
+            owners={self._family_id(item): item.name for item in chain},
+            definitions=self.definitions,
+            groups=self.groups,
+            attrs=self.attrs,
+            sets=self.sets,
+            ops=tuple(self.ops),
+            fills=fills,
+            chain_fills=chain_fills,
+            messages=self._messages(target),
+        )
+        _check_composed(resolved)
+        return resolved
+
+    def _messages(self, family):
+        """The message roots this family declares that no op selects.
+
+        The root family alone has them, and has to have them.
+        """
+        messages = []
+        for name in sizes.CORE_MESSAGES:
+            attr_set = self.sets.get(name)
+            if attr_set is None:
+                if family.name != spec.CORE_FAMILY_NAME:
+                    continue
+                raise CtlvError(f'{family.path}: family {family.name}',
+                                f'the root family has to declare the "{name}" '
+                                'attr set, which the core builds a message of')
+            if attr_set.family_id != self._family_id(family):
+                continue
+            where = f'{self.set_paths[name]}: attr set {name}'
+            nodes, stubs = self._expand_placements(
+                spec.Placements(attr_set.attrs, attr_set.optional_attrs),
+                where, (), 0, (name,))
+            if stubs:
+                raise CtlvError(where, 'a message the core builds cannot '
+                                       'select an extension point')
+            root = _root(nodes)
+            _check_tree_size(where, root)
+            messages.append(Message(
+                name=name,
+                family_id=attr_set.family_id,
+                set_id=attr_set.set_id,
+                root=root,
+                max_len=sizes.message_max_len(where, name, root),
+                limit=sizes.CORE_MESSAGES[name][0],
+            ))
+        return tuple(messages)
+
+    def _fills(self, family):
+        """The stubs one family fills, with the members it puts in each.
+
+        Passing None asks for the fills of the whole chain.
+        """
+        fills = []
+        for name, filler in self.stub_fillers.items():
+            if family is not None and filler != family.name:
+                continue
+            attr_set = self.sets[name]
+            nodes, stubs = self._expand_placements(
+                spec.Placements(attr_set.attrs, attr_set.optional_attrs),
+                f'{self.set_paths[name]}: attr set {name}', (), 0, (name,))
+            root = _root(nodes, stubs)
+            where = f'{self.set_paths[name]}: attr set {name}'
+            _check_tree_size(where, root)
+            if _reenters_anywhere(root):
+                raise CtlvError(
+                    where, 'a stub fill cannot contain a recursive attr')
+            fills.append(Fill(
+                name=name,
+                owner_family_id=self.registry.family_id(filler),
+                family_id=attr_set.family_id,
+                set_id=attr_set.set_id,
+                root=root,
+            ))
+        return tuple(fills)
+
+    # Loading and identity
+
+    def _load_chain(self):
+        family = spec.load(self.paths.spec, self.paths.schema)
+        if self.paths.spec.stem != family.name:
+            raise CtlvError(f'{family.path}: family {family.name}',
+                            'a specification must be named after its family, '
+                            f'so this file must be {family.name}.yaml')
+        chain = [family]
+        seen = [family.name]
+        self._check_root(family)
+        while chain[0].inherits:
+            parent_name = chain[0].inherits
+            child = chain[0]
+            if parent_name in seen:
+                # seen runs from the selected family to its ancestors.
+                raise CtlvError(f'{child.path}: family {child.name}',
+                                'inheritance cycle: ' +
+                                ' -> '.join(seen + [parent_name]))
+            parent_path = self.paths.sibling_spec(parent_name)
+            parent = spec.load(parent_path, self.paths.schema)
+            if parent.name != parent_name:
+                raise CtlvError(f'{parent_path}: family {parent.name}',
+                                f'expected family {parent_name}')
+            self._check_root(parent)
+            seen.append(parent_name)
+            chain.insert(0, parent)
+        return tuple(chain)
+
+    def _check_root(self, family):
+        """Require every family but the root one to name what it inherits."""
+        if family.name == spec.CORE_FAMILY_NAME:
+            if family.inherits:
+                raise CtlvError(f'{family.path}: family {family.name}',
+                                'the root family heads every chain, so it '
+                                'inherits nothing')
+        elif not family.inherits:
+            raise CtlvError(f'{family.path}: family {family.name}',
+                            'must name the family it inherits, which is the '
+                            f'root {spec.CORE_FAMILY_NAME} for a family '
+                            'directly below it')
+
+    def _check_names(self, chain):
+        """Require every child family name to carry its whole ancestry.
+
+        A dash is the only separator; a dot selects group.attr.
+        """
+        for parent, child in zip(chain, chain[1:]):
+            suffix = child.name.removeprefix(f'{parent.name}-')
+            if not suffix or suffix == child.name:
+                raise CtlvError(f'{child.path}: family {child.name}',
+                                f'a family that inherits {parent.name} must '
+                                f'be named {parent.name}-<suffix>')
+
+    def _check_order(self, chain):
+        """Require a parent to be registered before what inherits it.
+
+        Ascending positions let the core walk a chain once and index it.
+        """
+        for parent, child in zip(chain, chain[1:]):
+            if self._family_id(parent) >= self._family_id(child):
+                raise CtlvError(f'{child.path}: family {child.name}',
+                                f'is registered before {parent.name}, the '
+                                'family it inherits')
+
+    def _family_id(self, family):
+        family_id = self.registry.family_id(family.name)
+        if family_id is None:
+            raise CtlvError(f'{family.path}: family {family.name}',
+                            f'not registered in {self.registry.path}')
+        return family_id
+
+    # Declarations
+
+    def _add_family(self, family):
+        family_id = self._family_id(family)
+        self._add_definitions(family, family_id, family.enums, 'enum')
+        self._add_definitions(family, family_id, family.flags, 'flags')
+        self._add_groups(family, family_id)
+        self._add_sets(family, family_id)
+
+    def _add_definitions(self, family, family_id, definitions, kind):
+        for definition in definitions:
+            where = f'{family.path}: {kind} {definition.name}'
+            self._reject_redeclaration(where, self.definitions,
+                                       definition.name, 'enum or flags')
+            if kind == 'flags' and len(definition.values) > MAX_FLAG_BITS:
+                raise CtlvError(where, f'more than {MAX_FLAG_BITS} flag bits')
+            if kind == 'enum':
+                _check_count(where, 'enum values', len(definition.values),
+                             spec.U32_MAX)
+                if family_id == spec.CORE_FAMILY_ID:
+                    maximum = ROOT_ENUM_VALUES_MAX.get(definition.name)
+                    if maximum is not None:
+                        _check_count(where, 'enum values',
+                                     len(definition.values), maximum)
+            # Enum values from one, zero being reserved; flag bits from zero.
+            first = 1 if kind == 'enum' else 0
+            values = tuple((name, first + index)
+                           for index, name in enumerate(definition.values))
+            self.definitions[definition.name] = Definition(
+                definition.name, kind, family_id, values)
+
+    def _add_groups(self, family, family_id):
+        _check_count(f'{family.path}: family {family.name}', 'attr groups',
+                     len(family.groups), spec.U16_MAX)
+        for group_id, group in enumerate(family.groups, start=1):
+            where = f'{family.path}: attr group {group.name}'
+            self._reject_redeclaration(where, self.groups, group.name,
+                                       'attr group')
+            self._reject_redeclaration(where, self.sets, group.name,
+                                       'attr set')
+            attrs = []
+            names = set()
+            _check_count(where, 'attrs', len(group.attrs), spec.U32_MAX)
+            for local_id, decl in enumerate(group.attrs, start=1):
+                attr_where = f'{family.path}: attr {group.name}.{decl.name}'
+                if decl.name in names:
+                    raise CtlvError(attr_where, 'duplicate attr')
+                names.add(decl.name)
+                self._check_reference(attr_where, decl)
+                attrs.append(Attr(
+                    group=group.name,
+                    name=decl.name,
+                    family_id=family_id,
+                    group_id=group_id,
+                    local_id=local_id,
+                    attr_id=(family_id << 48) | (group_id << 32) | local_id,
+                    decl=decl,
+                ))
+            effective = Group(group.name, family_id, group_id, tuple(attrs))
+            self.groups[group.name] = effective
+            for attr in attrs:
+                self.attrs[attr.full_name] = attr
+
+    def _check_reference(self, where, decl):
+        if decl.kind not in ('enum', 'flags'):
+            return
+        definition = self.definitions.get(decl.ref)
+        if definition is None:
+            raise CtlvError(where, f'unknown {decl.kind} "{decl.ref}"')
+        if definition.kind != decl.kind:
+            raise CtlvError(where, f'"{decl.ref}" is a {definition.kind} '
+                                   f'definition, not {decl.kind}')
+
+    def _add_sets(self, family, family_id):
+        set_id = 0
+        for attr_set in family.sets:
+            where = f'{family.path}: attr set {attr_set.name}'
+            existing = self.sets.get(attr_set.name)
+            if existing is not None:
+                self._fill_stub(where, family, existing, attr_set)
+                continue
+            self._reject_redeclaration(where, self.groups, attr_set.name,
+                                       'attr group')
+            _check_count(where, 'new attr sets', set_id + 1,
+                         spec.U32_MAX)
+            set_id += 1
+            self.set_paths[attr_set.name] = family.path
+            self.sets[attr_set.name] = AttrSet(
+                name=attr_set.name,
+                family_id=family_id,
+                set_id=set_id,
+                stub=attr_set.stub,
+                attrs=attr_set.attrs,
+                optional_attrs=attr_set.optional_attrs,
+            )
+
+    def _fill_stub(self, where, family, existing, filler):
+        """Replace an inherited empty stub with a descendant's members."""
+        filled_by = self.stub_fillers.get(existing.name)
+        if filled_by is not None:
+            raise CtlvError(where, f'stub was already filled by family '
+                                   f'{filled_by}')
+        if not existing.stub:
+            raise CtlvError(where, 'attr set is already declared by an '
+                                   'inherited family')
+        if filler.stub:
+            raise CtlvError(where, 'a stub cannot be redeclared; a further '
+                                   'extension point needs a new name')
+        self.stub_fillers[existing.name] = family.name
+        self.set_paths[existing.name] = family.path
+        # A fill completes an inherited set, so the IDs are the declarer's.
+        self.sets[existing.name] = dataclasses.replace(
+            existing, stub=False, attrs=filler.attrs,
+            optional_attrs=filler.optional_attrs)
+
+    def _check_sets(self):
+        """Expand every set, so one that no op selects is still checked."""
+        for name, attr_set in self.sets.items():
+            where = f'{self.set_paths[name]}: attr set {name}'
+            # Seeding the stack makes a cycle read from the set expanded.
+            _nodes, _stubs = self._expand_placements(
+                spec.Placements(attr_set.attrs, attr_set.optional_attrs),
+                where, (), 0, set_stack=(attr_set.name,),
+                opened=(attr_set.name,))
+
+    def _reject_redeclaration(self, where, namespace, name, what):
+        if name in namespace:
+            raise CtlvError(where, f'{what} "{name}" is already declared')
+
+    # Ops
+
+    def _add_ops(self, family):
+        family_id = self._family_id(family)
+        _check_count(f'{family.path}: family {family.name}', 'ops',
+                     len(family.ops), spec.U32_MAX)
+        _check_count(f'{family.path}: family {family.name}', 'effective ops',
+                     len(self.ops) + len(family.ops), spec.U32_MAX)
+        for local_id, op in enumerate(family.ops, start=1):
+            where = f'{family.path}: op {op.name}'
+            if any(existing.name == op.name for existing in self.ops):
+                raise CtlvError(where, f'op "{op.name}" is already declared')
+            request = None
+            if op.request is not None:
+                request = self._tree(op.request, where + ' request')
+            reply = None
+            if op.reply is not None:
+                reply = self._tree(op.reply, where + ' reply')
+            self._check_context(where, op, request, reply)
+            self.ops.append(Op(
+                name=op.name,
+                type=op.type,
+                fd_access=op.fd_access,
+                availability=op.availability,
+                optional=op.optional,
+                pre_post=op.pre_post,
+                family_id=family_id,
+                local_id=local_id,
+                op_id=(family_id << 48) | local_id,
+                request=request,
+                reply=reply,
+                sizes=sizes.compute(where, op, request, reply),
+            ))
+
+    def _tree(self, placements, where):
+        children, stubs = self._expand_placements(placements, where, (), 0)
+        root = _root(children, stubs)
+        _check_tree_size(where, root)
+        return root
+
+    def _expand_placements(self, placements, where, stack, depth,
+                           set_stack=(), opened=()):
+        """Return the child nodes of one level and the stubs selected there."""
+        merged = {}
+        expanded, stubs = self._expand(placements.attrs, False, where,
+                                       set_stack)
+        optional, more = self._expand(placements.optional_attrs, True, where,
+                                      set_stack)
+        expanded += optional
+        stubs += more
+        for attr, required, fill in expanded:
+            entry = merged.get(attr.attr_id)
+            if entry is None:
+                merged[attr.attr_id] = [attr, required, fill]
+            elif entry[2] != fill and (entry[2] is not None or
+                                       fill is not None):
+                raise CtlvError(
+                    where, f'attr {attr.full_name} is selected more than '
+                           'once in one composed nest')
+            elif required:
+                # A required selection at this level beats an optional one.
+                entry[1] = True
+        nodes = tuple(self._node(attr, required, where, stack, depth, opened)
+                      for attr, required, _fill in merged.values())
+        return nodes, _merge_stubs(stubs)
+
+    def _expand(self, selectors, force_optional, where, stack):
+        expanded = []
+        stubs = ()
+        for selector in selectors:
+            attrs, found = self._expand_one(selector, force_optional, where,
+                                            stack)
+            expanded += attrs
+            stubs += found
+        return expanded, stubs
+
+    def _expand_one(self, selector, force_optional, where, stack):
+        if '.' in selector:
+            attr = self.attrs.get(selector)
+            if attr is None:
+                raise CtlvError(where, f'unknown attr "{selector}"')
+            return [(attr, not force_optional, None)], ()
+        group = self.groups.get(selector)
+        if group is not None:
+            return [(attr, not force_optional, None)
+                    for attr in group.attrs], ()
+        attr_set = self.sets.get(selector)
+        if attr_set is None:
+            raise CtlvError(where, f'unknown selector "{selector}"')
+        if attr_set.stub:
+            # Nothing to expand until a descendant fills it.
+            return [], (Stub(attr_set.name, attr_set.family_id,
+                             attr_set.set_id, force_optional),)
+        if selector in stack:
+            raise CtlvError(where, 'attr set cycle: ' +
+                                   ' -> '.join(stack + (selector,)))
+        stack += (selector,)
+        # Under an optional selection every member becomes optional.
+        expanded, stubs = self._expand(attr_set.attrs, force_optional, where,
+                                       stack)
+        optional, more = self._expand(attr_set.optional_attrs, True, where,
+                                      stack)
+        expanded += optional
+        if selector in self.stub_fillers:
+            expanded = [(attr, required, selector)
+                        for attr, required, _fill in expanded]
+        return expanded, stubs + more
+
+    def _node(self, attr, required, where, stack, depth, opened=()):
+        decl = attr.decl
+        if decl.kind != 'nested':
+            return Node(attr, required, decl.max_occurrences, (), ())
+        holds = self._nested_set(where, attr)
+        if decl.recursive and holds in opened:
+            # Open above, so one level further down rather than a new one.
+            return Node(attr, required, decl.max_occurrences, (), (),
+                        reenters=holds)
+        if attr.attr_id in stack:
+            names = [self._attr_by_id(i).full_name for i in stack]
+            raise CtlvError(where, 'nesting cycle: ' +
+                                   ' -> '.join(names + [attr.full_name]))
+        if depth + 1 > sizes.MAX_DECLARED_NEST_DEPTH:
+            raise CtlvError(where, f'{attr.full_name} nests deeper than the '
+                                   f'{sizes.MAX_DECLARED_NEST_DEPTH} level '
+                                   'limit')
+        children, stubs = self._expand_placements(
+            spec.Placements(decl.attrs, decl.optional_attrs), where,
+            stack + (attr.attr_id,), depth + 1,
+            opened=opened + ((holds,) if holds else ()))
+        node = Node(attr, required, decl.max_occurrences,
+                    tuple(child for child in children if child.required),
+                    tuple(child for child in children if not child.required),
+                    stubs, expands=holds)
+        if decl.recursive and not _reenters(node, holds):
+            raise CtlvError(where, f'{attr.full_name} is recursive, but attr '
+                                   f'set "{holds}" never selects it again')
+        return node
+
+    def _nested_set(self, where, attr):
+        """The one attr set a nest holds, when that is all it holds.
+
+        Only such a nest can be re-entered, a re-entry meaning the members
+        open above.
+        """
+        decl = attr.decl
+        if not decl.recursive:
+            if decl.optional_attrs or len(decl.attrs) != 1:
+                return None
+            return decl.attrs[0] if decl.attrs[0] in self.sets else None
+        target = decl.attrs[0]
+        if target in self.groups:
+            raise CtlvError(where, f'{attr.full_name} is recursive, so it '
+                                   f'nests an attr set, and "{target}" is an '
+                                   'attr group')
+        if target not in self.sets:
+            raise CtlvError(where, f'unknown selector "{target}"')
+        return target
+
+    def _attr_by_id(self, attr_id):
+        for attr in self.attrs.values():
+            if attr.attr_id == attr_id:
+                return attr
+        raise AssertionError(f'no attr with ID {attr_id:#x}')
+
+    def _check_context(self, where, op, request, reply):
+        if request is not None:
+            self._check_subtree(where, request, 'request')
+        if reply is None:
+            return
+        if op.type == 'query':
+            self._check_subtree(where, reply, 'query reply')
+            self._check_reentry(where, reply)
+        elif op.type == 'event':
+            self._check_subtree(where, reply, 'event')
+        else:
+            self._check_subtree(where, reply, 'action reply')
+
+    def _check_reentry(self, where, root):
+        """A repeating level cannot also be widened by a descendant."""
+        if not _reenters_anywhere(root) or not _stubs_anywhere(root):
+            return
+        raise CtlvError(f'{where} query reply',
+                        're-enters a level and selects an extension point, '
+                        'and a descendant cannot widen a level that repeats')
+
+    def _check_subtree(self, where, node, context):
+        if node.attr is not None:
+            name = node.attr.full_name
+            if (node.max_occurrences == spec.UNLIMITED and
+                    context != 'query reply'):
+                raise CtlvError(f'{where} {context}',
+                                f'{name} has unlimited occurrences, which '
+                                'only a query reply may contain')
+            if node.reenters is not None and context != 'query reply':
+                raise CtlvError(f'{where} {context}',
+                                f'{name} re-enters "{node.reenters}", so it '
+                                'has no maximum length, which only a query '
+                                'reply may contain')
+            if node.attr.decl.kind == 'blob' and context != 'request':
+                raise CtlvError(f'{where} {context}',
+                                f'{name} is a blob attr, which only a '
+                                'request may contain')
+        for child in node.children():
+            self._check_subtree(where, child, context)
+
+
+def _reenters(node, name):
+    """Whether anything below node re-enters name."""
+    return any(child.reenters == name or _reenters(child, name)
+               for child in node.children())
+
+
+def _reenters_anywhere(node):
+    return any(child.reenters is not None or _reenters_anywhere(child)
+               for child in node.children())
+
+
+def _stubs_anywhere(node):
+    return bool(node.stubs) or any(_stubs_anywhere(child)
+                                   for child in node.children())
+
+
+def _composed_members(fills, node, force_optional=False):
+    members = [(child, force_optional)
+               for child in node.required_children]
+    members += [(child, True) for child in node.optional_children]
+    for stub in node.stubs:
+        fill = fills.get((stub.family_id, stub.set_id))
+        if fill is not None:
+            members += _composed_members(
+                fills, fill.root, force_optional or stub.optional)
+    return members
+
+
+def _check_composed(family):
+    fills = {(fill.family_id, fill.set_id): fill
+             for fill in family.chain_fills}
+
+    def walk(where, node):
+        members = _composed_members(fills, node)
+        required = sum(not optional for _child, optional in members)
+        optional = len(members) - required
+        seen = set()
+
+        _check_count(where, 'composed required attrs', required,
+                     spec.U32_MAX)
+        _check_count(where, 'composed optional attrs', optional,
+                     spec.U32_MAX)
+        count = 1
+        for child, _optional in members:
+            if child.attr.attr_id in seen:
+                raise CtlvError(
+                    where, f'attr {child.attr.full_name} is selected more '
+                           'than once in one composed nest')
+            seen.add(child.attr.attr_id)
+            count += walk(where, child)
+        return count
+
+    for op in family.ops:
+        total = 0
+        for which, root in (('request', op.request), ('reply', op.reply)):
+            if root is None:
+                continue
+            where = f'{family.path}: op {op.name} {which}'
+            count = walk(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)
+
+
+def _node_count(node):
+    return 1 + sum(_node_count(child) for child in node.children())
+
+
+def _stub_count(node):
+    return len(node.stubs) + sum(_stub_count(child)
+                                 for child in node.children())
+
+
+def _check_tree_size(where, root):
+    _check_count(where, 'schema nodes', _node_count(root), spec.U32_MAX)
+    _check_count(where, 'schema stubs', _stub_count(root), spec.U32_MAX)
+
+
+def _root(children, stubs=()):
+    return Node(None, True, 1,
+                tuple(node for node in children if node.required),
+                tuple(node for node in children if not node.required),
+                stubs)
+
+
+def _merge_stubs(stubs):
+    """One reference per stub selected at a level, required winning."""
+    merged = {}
+    for stub in stubs:
+        previous = merged.get(stub.name)
+        if previous is None or not stub.optional:
+            merged[stub.name] = stub
+    return tuple(merged.values())
diff --git a/tools/ctlv/ctlvgen/lib/sizes.py b/tools/ctlv/ctlvgen/lib/sizes.py
new file mode 100644
index 0000000000000..864e3b6873e7a
--- /dev/null
+++ b/tools/ctlv/ctlvgen/lib/sizes.py
@@ -0,0 +1,238 @@
+# SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
+"""Length arithmetic over an expanded op tree.
+
+These numbers decide whether an op can run at all, so they are kept apart from
+the rest of resolution and tested against independently calculated lengths.
+The constants mirror include/uapi/linux/ctlv.h, and a test checks that.
+"""
+
+from __future__ import annotations
+
+import dataclasses
+
+from . import spec
+from .errors import CtlvError
+
+ALIGNTO = 8
+ATTR_HDR_LEN = 16
+EVENT_HDR_LEN = 24
+
+MAX_INLINE_MESSAGE_LEN = 0x100000
+MAX_ERROR_LEN = 0x4000
+MAX_NEST_DEPTH = 32
+DEFAULT_QUERY_REPLY_LEN = 0x10000
+MAX_EVENT_QUEUE_LEN = 0x1000000
+
+# One level short of what the transport carries: op-schema-get describes a
+# message, and a description nests one level deeper than what it describes.
+MAX_DECLARED_NEST_DEPTH = MAX_NEST_DEPTH - 1
+
+# Every integer, enum and flags payload is 64-bit.
+SCALAR_PAYLOAD_LEN = 8
+
+# A bool payload is one byte, padded to eight only as a placement.
+BOOL_PAYLOAD_LEN = 1
+
+# How many core scalar descriptor attrs each blob backing carries. A test
+# checks these against the blob group of the core family.
+BLOB_DESCRIPTOR_ATTRS = {
+    'va': 3,
+}
+
+# Attr sets of the root family that are message roots in their own right, each
+# with the transport header's limit and the name the header gives it.
+CORE_MESSAGES = {
+    'error-info': ('CTLV_MAX_ERROR_LEN', MAX_ERROR_LEN),
+}
+
+
+@dataclasses.dataclass(frozen=True)
+class OpSizes:
+    """Generated lengths of one op. Zero means "does not apply"."""
+
+    request_max_len: int
+    action_reply_max_len: int
+    query_reply_min_len: int
+    query_reply_suggested_len: int
+    event_record_max_len: int
+
+
+def align(length):
+    return (length + ALIGNTO - 1) & ~(ALIGNTO - 1)
+
+
+def attr_max_len(node):
+    """Maximum length of one occurrence of node, excluding its own padding."""
+    return ATTR_HDR_LEN + _payload_max_len(node)
+
+
+def root_max_len(root):
+    """Maximum length of a complete message root."""
+    return ATTR_HDR_LEN + _payload_max_len(root)
+
+
+def min_reply_len(root):
+    """Buffer length needed for the largest indivisible leaf and its path.
+
+    A leaf below a re-entered level sits as deep as the transport allows.
+    """
+    if _reenters(root):
+        return (MAX_NEST_DEPTH + 1) * ATTR_HDR_LEN + _largest_leaf(root)
+    return _min_walk(root, 0)
+
+
+def compute(where, op, request, reply):
+    """Return the generated lengths of one op."""
+    request_max_len = 0
+    if request is not None:
+        request_max_len = root_max_len(request)
+        _check_inline(where, 'request', request_max_len)
+
+    action_reply_max_len = 0
+    query_reply_min_len = 0
+    query_reply_suggested_len = 0
+    event_record_max_len = 0
+
+    if op.type == 'action' and reply is not None:
+        action_reply_max_len = root_max_len(reply)
+        _check_inline(where, 'action reply', action_reply_max_len)
+    elif op.type == 'query':
+        query_reply_min_len = min_reply_len(reply)
+        _check_inline(where, 'largest query reply leaf and its path',
+                      query_reply_min_len)
+        query_reply_suggested_len = _suggested_len(
+            where, op.suggested_reply_length, query_reply_min_len)
+    elif op.type == 'event':
+        payload_max_len = root_max_len(reply)
+        _check_inline(where, 'event payload', payload_max_len)
+        event_record_max_len = EVENT_HDR_LEN + align(payload_max_len)
+
+    return OpSizes(request_max_len=request_max_len,
+                   action_reply_max_len=action_reply_max_len,
+                   query_reply_min_len=query_reply_min_len,
+                   query_reply_suggested_len=query_reply_suggested_len,
+                   event_record_max_len=event_record_max_len)
+
+
+def composed(where, op, request, reply):
+    """Return the lengths one op needs for one family.
+
+    compute()'s numbers over the composed tree, fills spliced in. A suggestion
+    is raised here rather than refused.
+    """
+    sizes = OpSizes(request_max_len=root_max_len(request) if request else 0,
+                    action_reply_max_len=0, query_reply_min_len=0,
+                    query_reply_suggested_len=0, event_record_max_len=0)
+    _check_inline(where, 'request', sizes.request_max_len)
+
+    if op.type == 'action' and reply is not None:
+        sizes = dataclasses.replace(sizes,
+                                    action_reply_max_len=root_max_len(reply))
+        _check_inline(where, 'action reply', sizes.action_reply_max_len)
+    elif op.type == 'query':
+        minimum = min_reply_len(reply)
+        _check_inline(where, 'largest query reply leaf and its path', minimum)
+        sizes = dataclasses.replace(
+            sizes, query_reply_min_len=minimum,
+            query_reply_suggested_len=max(op.sizes.query_reply_suggested_len,
+                                          minimum))
+    elif op.type == 'event':
+        payload_max_len = root_max_len(reply)
+        _check_inline(where, 'event payload', payload_max_len)
+        record = EVENT_HDR_LEN + align(payload_max_len)
+        if record > MAX_EVENT_QUEUE_LEN:
+            raise CtlvError(where, f'event record needs {record} bytes, more '
+                                   f'than the {MAX_EVENT_QUEUE_LEN} byte '
+                                   'event queue limit')
+        sizes = dataclasses.replace(sizes, event_record_max_len=record)
+    return sizes
+
+
+def message_max_len(where, name, root):
+    """Return the maximum length of one core message, against its limit."""
+    limit_name, limit = CORE_MESSAGES[name]
+    length = root_max_len(root)
+    if length > limit:
+        raise CtlvError(where, f'needs {length} bytes, more than the {limit} '
+                               f'of {limit_name}')
+    return length
+
+
+def _payload_max_len(node):
+    if node.is_root:
+        return _children_max_len(node)
+
+    decl = node.attr.decl
+    if decl.kind in ('uint', 'sint', 'enum', 'flags'):
+        return SCALAR_PAYLOAD_LEN
+    if decl.kind == 'bool':
+        return BOOL_PAYLOAD_LEN
+    if decl.kind == 'string':
+        # One terminating NUL, which max-length excludes.
+        return decl.max_length + 1
+    if decl.kind == 'binary':
+        return decl.max_length
+    if decl.kind == 'blob':
+        widest = max(BLOB_DESCRIPTOR_ATTRS[backing]
+                     for backing in decl.blob.backings)
+        return widest * align(ATTR_HDR_LEN + SCALAR_PAYLOAD_LEN)
+    return _children_max_len(node)
+
+
+def _children_max_len(node):
+    total = 0
+    for child in node.children():
+        if child.max_occurrences == spec.UNLIMITED:
+            raise AssertionError(
+                f'{child.attr.full_name} has unlimited occurrences, so it has '
+                'no maximum length')
+        if child.reenters is not None:
+            raise AssertionError(
+                f'{child.attr.full_name} re-enters {child.reenters}, so it '
+                'has no maximum length')
+        total += child.max_occurrences * align(attr_max_len(child))
+    return total
+
+
+def _min_walk(node, ancestors_len):
+    children = node.children()
+    if children:
+        return max(_min_walk(child, ancestors_len + ATTR_HDR_LEN)
+                   for child in children)
+    if node.is_root:
+        return ancestors_len + ATTR_HDR_LEN
+    return ancestors_len + align(attr_max_len(node))
+
+
+def _reenters(node):
+    return any(child.reenters is not None or _reenters(child)
+               for child in node.children())
+
+
+def _largest_leaf(node):
+    """The longest placement of the tree that a fragment cannot split."""
+    lengths = [align(attr_max_len(child))
+               for child in node.children()
+               if child.attr.decl.kind != 'nested']
+    lengths += [_largest_leaf(child) for child in node.children()]
+    return max(lengths, default=0)
+
+
+def _check_inline(where, what, length):
+    if length > MAX_INLINE_MESSAGE_LEN:
+        raise CtlvError(where, f'{what} needs {length} bytes, more than the '
+                               f'{MAX_INLINE_MESSAGE_LEN} byte inline '
+                               'message limit')
+
+
+def _suggested_len(where, declared, minimum):
+    if declared is None:
+        return max(DEFAULT_QUERY_REPLY_LEN, minimum)
+    if declared < minimum:
+        raise CtlvError(where, f'suggested-reply-length {declared} is below '
+                               f'the computed minimum of {minimum}')
+    if declared > MAX_INLINE_MESSAGE_LEN:
+        raise CtlvError(where, f'suggested-reply-length {declared} exceeds '
+                               f'the {MAX_INLINE_MESSAGE_LEN} byte inline '
+                               'message limit')
+    return declared
diff --git a/tools/ctlv/ctlvgen/lib/spec.py b/tools/ctlv/ctlvgen/lib/spec.py
new file mode 100644
index 0000000000000..8942664d88a73
--- /dev/null
+++ b/tools/ctlv/ctlvgen/lib/spec.py
@@ -0,0 +1,583 @@
+# SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
+"""The as-written form of a CTLV family specification.
+
+The strict YAML subset, the meta-schema, and every rule that one declaration
+decides on its own. Comparing declarations and walking a chain are
+semantics.py's. Omitted values are normalized here, once.
+"""
+
+from __future__ import annotations
+
+import dataclasses
+import pathlib
+import re
+
+import jsonschema
+
+from . import yamlload
+from .errors import CtlvError
+
+# A generated file carries the license of its specification's first line.
+LICENSE = re.compile(r'#\s*SPDX-License-Identifier:\s*(\S.*?)\s*$')
+
+# The registry is indexed by family ID, so the root family is its first entry.
+CORE_FAMILY_NAME = 'ctlv'
+CORE_FAMILY_ID = 0
+
+MAX_FAMILY_NAME_LEN = 63
+U8_MAX = (1 << 8) - 1
+U16_MAX = (1 << 16) - 1
+U32_MAX = (1 << 32) - 1
+MAX_FAMILY_ID = U16_MAX
+
+# Zero means unlimited, as the introspection wire form has it.
+UNLIMITED = 0
+
+U64_MAX = (1 << 64) - 1
+S64_MIN = -(1 << 63)
+S64_MAX = (1 << 63) - 1
+S8_MIN = -(1 << 7)
+S8_MAX = (1 << 7) - 1
+
+PRIMARY_KEYS = ('type', 'enum', 'flags', 'attrs', 'blob')
+
+INTEGER_KINDS = ('uint', 'sint')
+SCALAR_KINDS = ('uint', 'sint', 'bool', 'string', 'binary', 'enum', 'flags')
+
+FD_ACCESSES = ('read', 'read-write')
+DEFAULT_FD_ACCESS = 'read-write'
+
+# Every op has one of these, and only an action or a query may be dynamic.
+AVAILABILITIES = ('fixed', 'dynamic')
+DEFAULT_AVAILABILITY = 'fixed'
+
+# Keys each primary form may add, beyond its own, name and max-occurrences.
+_ACCESSORY_KEYS = {
+    'uint': {'min', 'max', 'unit', 'scale'},
+    'sint': {'min', 'max', 'unit', 'scale'},
+    'bool': set(),
+    'string': {'min-length', 'max-length'},
+    'binary': {'length', 'min-length', 'max-length'},
+    'enum': set(),
+    'flags': set(),
+    'nested': {'optional-attrs', 'recursive'},
+    'blob': set(),
+}
+_COMMON_KEYS = {'name', 'max-occurrences'}
+
+
+@dataclasses.dataclass(frozen=True)
+class ValueList:
+    """An enum or a flags definition."""
+
+    name: str
+    values: tuple
+
+
+@dataclasses.dataclass(frozen=True)
+class BlobDecl:
+    """The blob properties of one blob attr declaration."""
+
+    direction: str
+    backings: tuple
+    max_length: int
+    alignment: int
+
+
+@dataclasses.dataclass(frozen=True)
+class AttrDecl:
+    """One attr declaration inside an attr group.
+
+    kind is the resolved primary form, and a field that does not apply stays
+    None. recursive marks a nest whose attr set may select this attr again.
+    """
+
+    name: str
+    kind: str
+    ref: str = None
+    attrs: tuple = ()
+    optional_attrs: tuple = ()
+    recursive: bool = False
+    blob: BlobDecl = None
+    min: int = None
+    max: int = None
+    min_length: int = None
+    max_length: int = None
+    unit: str = None
+    scale: int = None
+    max_occurrences: int = 1
+
+
+@dataclasses.dataclass(frozen=True)
+class AttrGroupSpec:
+    name: str
+    attrs: tuple
+
+
+@dataclasses.dataclass(frozen=True)
+class AttrSetSpec:
+    name: str
+    stub: bool
+    attrs: tuple
+    optional_attrs: tuple
+
+
+@dataclasses.dataclass(frozen=True)
+class Placements:
+    """The required and optional selectors declared at one level."""
+
+    attrs: tuple = ()
+    optional_attrs: tuple = ()
+
+
+@dataclasses.dataclass(frozen=True)
+class OpSpec:
+    name: str
+    type: str
+    request: Placements
+    reply: Placements = None
+    fd_access: str = DEFAULT_FD_ACCESS
+    availability: str = DEFAULT_AVAILABILITY
+    optional: bool = False
+    pre_post: bool = False
+    suggested_reply_length: int = None
+
+
+@dataclasses.dataclass(frozen=True)
+class FamilySpec:
+    """One specification file, syntax-checked and normalized."""
+
+    path: str
+    name: str
+    license: str
+    inherits: str
+    enums: tuple
+    flags: tuple
+    groups: tuple
+    sets: tuple
+    ops: tuple
+    pre_init: bool = False
+    post_init: bool = False
+    pre_fini: bool = False
+
+
+@dataclasses.dataclass(frozen=True)
+class RegistryEntry:
+    name: str
+    deprecated: bool
+
+
+@dataclasses.dataclass(frozen=True)
+class Registry:
+    """The append-only family registry, indexed by family ID."""
+
+    path: str
+    entries: tuple
+
+    @property
+    def license(self):
+        return _license(self.path)
+
+    def family_id(self, name):
+        """Return the registered family ID of name, or None if unregistered."""
+        for family_id, entry in enumerate(self.entries):
+            if entry.name == name:
+                return family_id
+        return None
+
+
+class Paths:
+    """Where the specs, the registry and the meta-schemas are."""
+
+    def __init__(self, spec, schema=None, registry=None, abi=None):
+        self.spec = pathlib.Path(spec)
+        self.spec_dir = self.spec.parent
+        self.doc_dir = self.spec_dir.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
+
+    def sibling_spec(self, name):
+        """Return the path of another family's specification.
+
+        The one root family lives where the meta-schema does, so a corpus of
+        fixtures inherits it rather than a copy.
+        """
+        if name == CORE_FAMILY_NAME:
+            return self.schema.parent / 'specs' / f'{name}.yaml'
+        return self.spec_dir / f'{name}.yaml'
+
+    def abi(self, name):
+        """Return the path of one family's checked-in ABI snapshot."""
+        return self.abi_dir / f'{name}.yaml'
+
+
+def load_registry(paths, path=None):
+    """Load and check the family registry."""
+    path = pathlib.Path(path or paths.registry)
+    data = yamlload.load(path)
+    _validate_syntax(path, data, paths.registry_schema)
+
+    entries = []
+    seen = set()
+    for item in data['families']:
+        if isinstance(item, dict):
+            entry = RegistryEntry(item['name'], item['deprecated'])
+        else:
+            entry = RegistryEntry(item, False)
+        _family_name(f'{path}: family {entry.name}', entry.name)
+        if entry.name in seen:
+            raise CtlvError(f'{path}: {entry.name}', 'duplicate family')
+        seen.add(entry.name)
+        entries.append(entry)
+
+    core = entries[CORE_FAMILY_ID]
+    if core.name != CORE_FAMILY_NAME:
+        raise CtlvError(f'{path}: {core.name}',
+                        f'family ID {CORE_FAMILY_ID} belongs to '
+                        f'{CORE_FAMILY_NAME}, so it must be the first entry')
+    if core.deprecated:
+        raise CtlvError(f'{path}: {core.name}',
+                        'the core family cannot be deprecated')
+    if len(entries) - 1 > MAX_FAMILY_ID:
+        raise CtlvError(str(path),
+                        f'{len(entries)} entries need a family ID past the '
+                        f'{MAX_FAMILY_ID} maximum')
+    return Registry(str(path), tuple(entries))
+
+
+def load(path, schema=None):
+    """Load, syntax-check and normalize one family specification."""
+    path = pathlib.Path(path)
+    data = yamlload.load(path)
+    _validate_syntax(path, data, schema)
+
+    family = data['family']
+    name = _family_name(f'{path}: family {family["name"]}', family['name'])
+    inherits = family.get('inherits')
+    if inherits is not None:
+        inherits = _family_name(f'{path}: family {name} parent', inherits)
+    return FamilySpec(
+        path=str(path),
+        name=name,
+        license=_license(path),
+        inherits=inherits,
+        enums=_value_lists(path, data.get('enums', []), 'enum'),
+        flags=_value_lists(path, data.get('flags', []), 'flags'),
+        groups=_groups(path, data.get('attr-groups', [])),
+        sets=_sets(path, data.get('attr-sets', [])),
+        ops=_ops(path, data.get('ops', [])),
+        pre_init=family.get('pre-init', False),
+        post_init=family.get('post-init', False),
+        pre_fini=family.get('pre-fini', False),
+    )
+
+
+def _license(path):
+    """Return the SPDX identifier the specification's first line carries."""
+    with open(path, 'r', encoding='utf-8') as stream:
+        found = LICENSE.match(stream.readline())
+    if found is None:
+        raise CtlvError(str(path),
+                        'the first line must be an SPDX-License-Identifier '
+                        'comment, which every generated file inherits')
+    return found.group(1)
+
+
+def _validate_syntax(path, data, schema_path):
+    schema = yamlload.load(schema_path)
+    validator = jsonschema.Draft7Validator(schema)
+    error = jsonschema.exceptions.best_match(validator.iter_errors(data))
+    if error is None:
+        return
+    where = f'{path}: {error.json_path}' if error.absolute_path else str(path)
+    raise CtlvError(where, error.message)
+
+
+def _family_name(where, name):
+    if len(name) > MAX_FAMILY_NAME_LEN:
+        raise CtlvError(where, f'name is {len(name)} characters, more than '
+                               f'the {MAX_FAMILY_NAME_LEN} maximum')
+    return name
+
+
+def _value_lists(path, raw_lists, what):
+    lists = []
+    for raw in raw_lists:
+        name = raw['name']
+        where = f'{path}: {what} {name}'
+        values = []
+        seen = set()
+        for raw_value in raw['values']:
+            value = raw_value
+            if value in seen:
+                raise CtlvError(where, f'duplicate value "{value}"')
+            seen.add(value)
+            values.append(value)
+        lists.append(ValueList(name, tuple(values)))
+    return tuple(lists)
+
+
+def _groups(path, raw_groups):
+    groups = []
+    for raw in raw_groups:
+        name = raw['name']
+        attrs = tuple(_attr(f'{path}: attr {name}.{a["name"]}', a)
+                      for a in raw['attrs'])
+        groups.append(AttrGroupSpec(name, attrs))
+    return tuple(groups)
+
+
+def _attr(where, raw):
+    primary = _primary_key(where, raw)
+    kind = _kind(primary, raw)
+    _reject_unusable_keys(where, raw, primary, kind)
+
+    attr = {
+        'name': raw['name'],
+        'kind': kind,
+        'max_occurrences': _max_occurrences(where, raw),
+    }
+    if kind in INTEGER_KINDS:
+        attr.update(_integer_bounds(where, raw, kind))
+    elif kind == 'string':
+        attr.update(_string_lengths(where, raw))
+    elif kind == 'binary':
+        attr.update(_binary_lengths(where, raw))
+    elif kind in ('enum', 'flags'):
+        attr['ref'] = raw[kind]
+    elif kind == 'nested':
+        attr['attrs'] = _selectors(raw['attrs'])
+        attr['optional_attrs'] = _selectors(raw.get('optional-attrs'))
+        attr['recursive'] = raw.get('recursive', False)
+        if attr['recursive']:
+            _check_recursive(where, attr)
+    elif kind == 'blob':
+        attr['blob'] = _blob(where, raw['blob'])
+    # A bool has nothing to normalize.
+    return AttrDecl(**attr)
+
+
+def _check_recursive(where, attr):
+    """A recursive nest is one named set, which is what it re-enters."""
+    if attr['optional_attrs']:
+        raise CtlvError(where, 'a recursive attr cannot declare '
+                               'optional-attrs; the attr set it names says '
+                               'which of its own members are optional')
+    if len(attr['attrs']) != 1:
+        raise CtlvError(where, 'a recursive attr nests exactly one attr set')
+    if '.' in attr['attrs'][0]:
+        raise CtlvError(where, f'"{attr["attrs"][0]}" is one attr, and a '
+                               'recursive attr nests an attr set')
+
+
+def _primary_key(where, raw):
+    present = [key for key in PRIMARY_KEYS if key in raw]
+    if not present:
+        raise CtlvError(where, 'no primary declaration; expected one of '
+                               'type, enum, flags, attrs or blob')
+    if len(present) > 1:
+        raise CtlvError(where, 'conflicting primary declarations: ' +
+                               ', '.join(present))
+    return present[0]
+
+
+def _kind(primary, raw):
+    if primary == 'type':
+        return raw['type']
+    if primary == 'attrs':
+        return 'nested'
+    return primary
+
+
+def _reject_unusable_keys(where, raw, primary, kind):
+    allowed = _COMMON_KEYS | {primary} | _ACCESSORY_KEYS[kind]
+    unusable = sorted(set(raw) - allowed)
+    if unusable:
+        raise CtlvError(where, f'a {kind} attr cannot declare ' +
+                               ', '.join(unusable))
+
+
+def _max_occurrences(where, raw):
+    value = raw.get('max-occurrences', 1)
+    if value == 'unlimited':
+        return UNLIMITED
+    if value < 1 or value > U32_MAX:
+        raise CtlvError(where, f'max-occurrences {value} is outside the '
+                               'u32 range')
+    return value
+
+
+def _integer_bounds(where, raw, kind):
+    low, high = (0, U64_MAX) if kind == 'uint' else (S64_MIN, S64_MAX)
+    minimum = raw.get('min', low)
+    maximum = raw.get('max', high)
+    if minimum < low or minimum > high:
+        raise CtlvError(where, f'min {minimum} is outside the {kind} range')
+    if maximum < low or maximum > high:
+        raise CtlvError(where, f'max {maximum} is outside the {kind} range')
+    if minimum > maximum:
+        raise CtlvError(where, f'min {minimum} is greater than max {maximum}')
+    if 'scale' in raw and 'unit' not in raw:
+        raise CtlvError(where, 'scale requires unit')
+    scale = raw.get('scale', 0) if 'unit' in raw else None
+    if scale is not None and (scale < S8_MIN or scale > S8_MAX):
+        raise CtlvError(where, f'scale {scale} is outside the s8 range')
+    return {
+        'min': minimum,
+        'max': maximum,
+        'unit': raw.get('unit'),
+        'scale': scale,
+    }
+
+
+def _u32_value(where, what, value):
+    if value < 0 or value > U32_MAX:
+        raise CtlvError(where, f'{what} {value} is outside the u32 range')
+    return value
+
+
+def _string_lengths(where, raw):
+    if 'max-length' not in raw:
+        raise CtlvError(where, 'a string attr requires max-length')
+    minimum = _u32_value(where, 'min-length', raw.get('min-length', 0))
+    maximum = _u32_value(where, 'max-length', raw['max-length'])
+    if minimum > maximum:
+        raise CtlvError(where, f'min-length {minimum} is greater than '
+                               f'max-length {maximum}')
+    return {'min_length': minimum, 'max_length': maximum}
+
+
+def _binary_lengths(where, raw):
+    if 'length' in raw:
+        if 'min-length' in raw or 'max-length' in raw:
+            raise CtlvError(where, 'length cannot be combined with '
+                                   'min-length or max-length')
+        length = _u32_value(where, 'length', raw['length'])
+        return {'min_length': length, 'max_length': length}
+    if 'max-length' not in raw:
+        raise CtlvError(where, 'a binary attr requires length or max-length')
+    minimum = _u32_value(where, 'min-length', raw.get('min-length', 0))
+    maximum = _u32_value(where, 'max-length', raw['max-length'])
+    if minimum > maximum:
+        raise CtlvError(where, f'min-length {minimum} is greater than '
+                               f'max-length {maximum}')
+    return {'min_length': minimum, 'max_length': maximum}
+
+
+def _blob(where, raw):
+    alignment = raw.get('alignment', 1)
+    maximum = raw['max-length']
+    if maximum < 1 or maximum > U64_MAX:
+        raise CtlvError(where, f'blob max-length {maximum} is outside the '
+                               'u64 range')
+    if alignment < 1 or alignment > U32_MAX:
+        raise CtlvError(where, f'blob alignment {alignment} is outside the '
+                               'u32 range')
+    if alignment & (alignment - 1):
+        raise CtlvError(where, f'blob alignment {alignment} is not a power '
+                               'of two')
+    if maximum % alignment:
+        raise CtlvError(where, f'blob max-length {maximum} is not '
+                               f'a multiple of alignment {alignment}')
+    return BlobDecl(direction=raw['direction'],
+                    backings=tuple(raw['allowed-backings']),
+                    max_length=maximum,
+                    alignment=alignment)
+
+
+def _sets(path, raw_sets):
+    sets = []
+    for raw in raw_sets:
+        name = raw['name']
+        where = f'{path}: attr set {name}'
+        stub = raw.get('stub', False)
+        attrs = _selectors(raw.get('attrs'))
+        optional = _selectors(raw.get('optional-attrs'))
+        if stub and (attrs or optional):
+            raise CtlvError(where, 'a stub attr set cannot declare members')
+        if not stub and not attrs and not optional:
+            raise CtlvError(where, 'attr set has no members; declare '
+                                   'stub: true for an extension point')
+        sets.append(AttrSetSpec(name, stub, attrs, optional))
+    return tuple(sets)
+
+
+def _ops(path, raw_ops):
+    ops = []
+    for raw in raw_ops:
+        name = raw['name']
+        where = f'{path}: op {name}'
+        op_type = raw['type']
+        suggested = raw.get('suggested-reply-length')
+        if suggested is not None:
+            suggested = _u32_value(where, 'suggested-reply-length',
+                                   suggested)
+        if op_type == 'event' and 'request' in raw:
+            raise CtlvError(where, 'an event op cannot declare a request')
+        if op_type == 'query' and 'reply' not in raw:
+            raise CtlvError(where, 'a query op must declare a reply')
+        if 'suggested-reply-length' in raw and op_type != 'query':
+            raise CtlvError(where, 'suggested-reply-length is only valid on '
+                                   'a query op')
+        if 'fd-access' in raw and op_type == 'event':
+            raise CtlvError(where, 'fd-access is only valid on an action or '
+                                   'a query op')
+        # An event is not executed, so there is nothing to enable or disable.
+        if 'availability' in raw and op_type == 'event':
+            raise CtlvError(where, 'availability is only valid on an action '
+                                   'or a query op')
+        # An event is produced rather than answered, so there is nothing for a
+        # device to opt in to.
+        if 'optional' in raw and op_type == 'event':
+            raise CtlvError(where, 'optional is only valid on an action or a '
+                                   'query op')
+        # A hook pair wraps the execution of an op, and an event has none.
+        if 'pre-post' in raw and op_type == 'event':
+            raise CtlvError(where, 'pre-post is only valid on an action or a '
+                                   'query op')
+        # An omitted action or query request means a root with no children.
+        request = None
+        if op_type != 'event':
+            request = _placements(raw.get('request'))
+        # Omitted: an action reply is ACK-only, an event reply payload-free.
+        reply = None
+        if 'reply' in raw:
+            reply = _placements(raw['reply'])
+        elif op_type == 'event':
+            reply = Placements()
+        ops.append(OpSpec(
+            name=name,
+            type=op_type,
+            request=request,
+            reply=reply,
+            fd_access=raw.get('fd-access', DEFAULT_FD_ACCESS),
+            availability=raw.get('availability', DEFAULT_AVAILABILITY),
+            optional=raw.get('optional', False),
+            pre_post=raw.get('pre-post', False),
+            suggested_reply_length=suggested,
+        ))
+    return tuple(ops)
+
+
+def _placements(raw):
+    if raw is None:
+        return Placements()
+    return Placements(_selectors(raw.get('attrs')),
+                      _selectors(raw.get('optional-attrs')))
+
+
+def _selectors(raw):
+    if raw is None:
+        return ()
+    if isinstance(raw, str):
+        return (raw,)
+    return tuple(raw)
diff --git a/tools/ctlv/ctlvgen/lib/tree.py b/tools/ctlv/ctlvgen/lib/tree.py
new file mode 100644
index 0000000000000..62f4fb3634697
--- /dev/null
+++ b/tools/ctlv/ctlvgen/lib/tree.py
@@ -0,0 +1,71 @@
+# SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
+"""Whole-tree registry, specification and ABI coverage checks."""
+
+from __future__ import annotations
+
+from . import compat
+from . import outputs
+from . import spec
+from .errors import CtlvError
+
+
+def _stems(directory, exclude=()):
+    return {path.stem for path in directory.glob('*.yaml')
+            if path.name not in exclude}
+
+
+def coverage_problems(paths, registry, snapshots=True,
+                      allowed_missing_snapshots=()):
+    expected = {entry.name for entry in registry.entries}
+    problems = []
+
+    actual_specs = _stems(paths.spec_dir)
+    for name in sorted(expected - actual_specs):
+        problems.append(f'missing specification {name}.yaml')
+    for name in sorted(actual_specs - expected):
+        problems.append(f'unexpected specification {name}.yaml')
+
+    if snapshots:
+        actual_abi = _stems(paths.abi_dir,
+                            exclude=(paths.registry_abi.name,))
+        missing = expected - actual_abi - set(allowed_missing_snapshots)
+        for name in sorted(missing):
+            problems.append(f'missing ABI snapshot {name}.yaml')
+        for name in sorted(actual_abi - expected):
+            problems.append(f'unexpected ABI snapshot {name}.yaml')
+    return problems
+
+
+def check(paths):
+    """Check all inputs whose expected set comes from the registry."""
+    registry = spec.load_registry(paths)
+    compat.registry_check(paths, registry)
+    problems = coverage_problems(paths, registry)
+    if problems:
+        raise CtlvError('CTLV tree', '\n'.join(problems))
+    outputs.load(paths)
+    return registry
+
+
+def check_for_update(paths):
+    """Validate a registry update without requiring new snapshots yet."""
+    registry = spec.load_registry(paths)
+    compat.registry_check(paths, registry, exact=False)
+    baseline = spec.load_registry(paths, paths.registry_abi)
+    appended = {entry.name
+                for entry in registry.entries[len(baseline.entries):]}
+    problems = coverage_problems(paths, registry,
+                                 allowed_missing_snapshots=appended)
+    if problems:
+        raise CtlvError('CTLV tree', '\n'.join(problems))
+    outputs.load(paths)
+    return registry
+
+
+def finish_update(paths):
+    """Require complete snapshots before advancing the registry baseline."""
+    registry = check_for_update(paths)
+    problems = coverage_problems(paths, registry)
+    if problems:
+        raise CtlvError('CTLV tree', '\n'.join(problems))
+    return registry
diff --git a/tools/ctlv/ctlvgen/lib/yamlload.py b/tools/ctlv/ctlvgen/lib/yamlload.py
new file mode 100644
index 0000000000000..f043d87c98182
--- /dev/null
+++ b/tools/ctlv/ctlvgen/lib/yamlload.py
@@ -0,0 +1,83 @@
+# SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
+"""Strict YAML subset loader.
+
+Anchors, aliases, merge keys, explicit tags, duplicate mapping keys and
+multiple documents per file are all rejected: they let two readers of a file
+that defines an ABI disagree about what it says.
+"""
+
+import yaml
+
+from .errors import CtlvError
+
+
+def _mark(path, mark):
+    if mark is None:
+        return str(path)
+    return f'{path}:{mark.line + 1}'
+
+
+class _StrictLoader(yaml.SafeLoader):
+    """SafeLoader without the features that make a document ambiguous."""
+
+    def __init__(self, stream, path):
+        super().__init__(stream)
+        self.ctlv_path = path
+
+    def _reject(self, mark, what):
+        raise CtlvError(_mark(self.ctlv_path, mark), what)
+
+    def compose_node(self, parent, index):
+        event = self.peek_event()
+        if isinstance(event, yaml.events.AliasEvent):
+            self._reject(event.start_mark, 'YAML aliases are not allowed')
+        if getattr(event, 'anchor', None) is not None:
+            self._reject(event.start_mark, 'YAML anchors are not allowed')
+        if _has_explicit_tag(event):
+            self._reject(event.start_mark,
+                         f'explicit YAML tag "{event.tag}" is not allowed')
+        return super().compose_node(parent, index)
+
+    def construct_mapping(self, node, deep=False):
+        seen = set()
+        for key_node, _ in node.value:
+            if key_node.tag == 'tag:yaml.org,2002:merge':
+                self._reject(key_node.start_mark,
+                             'YAML merge keys are not allowed')
+            key = self.construct_object(key_node, deep=deep)
+            if key in seen:
+                self._reject(key_node.start_mark, f'duplicate key "{key}"')
+            seen.add(key)
+        return super().construct_mapping(node, deep=deep)
+
+
+def _has_explicit_tag(event):
+    if event.tag is None:
+        return False
+    implicit = getattr(event, 'implicit', False)
+    if isinstance(implicit, tuple):
+        return not (implicit[0] or implicit[1])
+    return not implicit
+
+
+def load(path):
+    """Return the single YAML document in path as plain Python objects."""
+    try:
+        with open(path, 'r', encoding='utf-8') as stream:
+            loader = _StrictLoader(stream, path)
+            try:
+                data = loader.get_single_data()
+            finally:
+                loader.dispose()
+    except OSError as exc:
+        raise CtlvError(str(path), f'cannot read: {exc.strerror}') from exc
+    except yaml.YAMLError as exc:
+        mark = getattr(exc, 'problem_mark', None)
+        described = [getattr(exc, 'context', None),
+                     getattr(exc, 'problem', None)]
+        problem = ', '.join(part for part in described if part) or str(exc)
+        raise CtlvError(_mark(path, mark), problem) from exc
+
+    if not isinstance(data, dict):
+        raise CtlvError(str(path), 'expected a YAML mapping at the top level')
+    return data
diff --git a/tools/ctlv/pyproject.toml b/tools/ctlv/pyproject.toml
new file mode 100644
index 0000000000000..7ecae2de30657
--- /dev/null
+++ b/tools/ctlv/pyproject.toml
@@ -0,0 +1,22 @@
+[build-system]
+requires = ["setuptools>=61.0"]
+build-backend = "setuptools.build_meta"
+
+[project]
+name = "ctlvgen"
+authors = [
+    {name = "Jiri Pirko", email = "jiri@resnulli.us"},
+]
+description = "CTLV schema tool"
+version = "0.0.1"
+requires-python = ">=3.9"
+dependencies = [
+    "pyyaml==6.*",
+    "jsonschema==4.*"
+]
+
+[tool.setuptools.packages.find]
+include = ["ctlvgen", "ctlvgen.lib"]
+
+[project.scripts]
+ctlvgen = "ctlvgen.cli:main"
diff --git a/tools/ctlv/requirements.txt b/tools/ctlv/requirements.txt
new file mode 100644
index 0000000000000..2a73e762f9b91
--- /dev/null
+++ b/tools/ctlv/requirements.txt
@@ -0,0 +1,2 @@
+pyyaml==6.*
+jsonschema==4.*

3/2 2026/10/15 19:11 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 234534
							output: 18
							thoughts: 321
						

Thoughts:
**Analyzing the CTLV Subsystem and TDX Attestation Provider**

Okay, let's dive into this patch. My immediate goal is to understand the implications of adding this new "CTLV" subsystem (specifically, the "CTLV character device TLV UAPI") along with the "Attestation" layer that seems to be built on top of it, particularly the TDX attestation provider. I need to get a handle on what CTLV *is*, how it's instantiated, what character devices it spawns, and whether those devices are actually accessible and utilized.

First, I'll start with a methodical, line-by-line review of the patch itself.

Let's begin by cataloging the core additions. I see the addition of `drivers/ctlv/` to the tree. Looking at the Kconfig, it looks like a new `config CTLV` option is introduced. Now, the documentation says that `/dev/ctlv0`, `/dev/ctlv1`, etc. character devices are created. Now, *how* is that accomplished? How are these `/dev/ctlvX` devices actually brought into existence? I need to follow the breadcrumbs here.

Ah, `ctlv_create()` is exported. It appears to be the central point of instantiation for these devices, taking a `parent_dev`, a `ctlv_family` struct, and initialization information. Okay, so who calls this function? That's the next critical question.

Let's see… I'll scan through the code and… Ah, here's an important find! In `drivers/attestation/providers/tdx.c`, `attestation_tdx_add()` is calling `ctlv_create()`. Specifically, `ctlv_create(parent_dev, &ctlv_attestation_tdx_family, &info);`.

But is that *it*? Or does something else call `ctlv_create()`? I need to be sure I've identified all the dependencies. I'll search the kernel codebase for all instances of `ctlv_create` using `grepper` to get the full picture.



4/2 2026/10/15 19:11 tool grepper
0m Args:
{
  "Expression": "ctlv_create"
}

Results:
{
  "Output": "Documentation/driver-api/ctlv.rst=178=Create and destroy a device\n--\nDocumentation/driver-api/ctlv.rst-180-\nDocumentation/driver-api/ctlv.rst:181:``ctlv_create()`` takes the leaf family descriptor and leaf initialization\nDocumentation/driver-api/ctlv.rst-182-information:\n--\nDocumentation/driver-api/ctlv.rst-190-\nDocumentation/driver-api/ctlv.rst:191:    ctlvdev = ctlv_create(dev, \u0026ctlv_example_vendor_ctlv_family, \u0026info);\nDocumentation/driver-api/ctlv.rst-192-    if (IS_ERR(ctlvdev))\n--\nDocumentation/driver-api/ctlv.rst=235=A family published in ``post_init`` withdraws and drains its consumers in\n--\nDocumentation/driver-api/ctlv.rst-237-``pre_fini`` callbacks finish. ``ctlv_destroy()`` consumes the reference from\nDocumentation/driver-api/ctlv.rst:238:``ctlv_create()``; open file descriptions remain only to drain queued records\nDocumentation/driver-api/ctlv.rst-239-and otherwise fail with ``-ENODEV``.\n--\ndrivers/attestation/generated/ctlv_attestation_gen.c=210=static const struct ctlv_op ctlv_attestation_ops[] = {\n--\ndrivers/attestation/generated/ctlv_attestation_gen.c-219-\ndrivers/attestation/generated/ctlv_attestation_gen.c:220:/* Family descriptor used by ctlv_create(). */\ndrivers/attestation/generated/ctlv_attestation_gen.c-221-const struct ctlv_family ctlv_attestation_family = {\n--\ndrivers/attestation/generated/ctlv_attestation_tdx_gen.c=43=static const struct ctlv_stub_ops ctlv_attestation_tdx_stub_ops[] = {\n--\ndrivers/attestation/generated/ctlv_attestation_tdx_gen.c-47-\ndrivers/attestation/generated/ctlv_attestation_tdx_gen.c:48:/* Family descriptor used by ctlv_create(). */\ndrivers/attestation/generated/ctlv_attestation_tdx_gen.c-49-const struct ctlv_family ctlv_attestation_tdx_family = {\n--\ndrivers/attestation/providers/tdx.c=239=static void *attestation_tdx_add(struct device *parent_dev,\n--\ndrivers/attestation/providers/tdx.c-246-\ndrivers/attestation/providers/tdx.c:247:\treturn ctlv_create(parent_dev, \u0026ctlv_attestation_tdx_family,\ndrivers/attestation/providers/tdx.c-248-\t\t\t   \u0026info);\n--\ndrivers/ctlv/core.c=1361=static void ctlv_device_del(struct ctlv_device *ctlvdev)\n--\ndrivers/ctlv/core.c-1365-\ndrivers/ctlv/core.c:1366:struct ctlv_device *ctlv_create(struct device *parent_dev, const struct ctlv_family *family,\ndrivers/ctlv/core.c-1367-\t\t\t\tconst void *init_info)\n--\ndrivers/ctlv/core.c-1456-}\ndrivers/ctlv/core.c:1457:EXPORT_SYMBOL_NS_GPL(ctlv_create, \"CTLV\");\ndrivers/ctlv/core.c-1458-\n--\ninclude/linux/ctlv.h=71=struct device;\n--\ninclude/linux/ctlv.h-76- *\ninclude/linux/ctlv.h:77: * Return: backing device passed to ctlv_create().\ninclude/linux/ctlv.h-78- */\ninclude/linux/ctlv.h=79=struct device *ctlv_device_parent(const struct ctlv_device *ctlvdev);\n--\ninclude/linux/ctlv.h-81-/**\ninclude/linux/ctlv.h:82: * ctlv_create - Create and register a CTLV device.\ninclude/linux/ctlv.h-83- * @parent_dev: backing device\n--\ninclude/linux/ctlv.h-88- */\ninclude/linux/ctlv.h:89:struct ctlv_device *ctlv_create(struct device *parent_dev,\ninclude/linux/ctlv.h-90-\t\t\t\tconst struct ctlv_family *family,\n--\ntools/ctlv/ctlvgen/lib/cgen.py=36=LIFECYCLE_API_SYMBOLS = (\ntools/ctlv/ctlvgen/lib/cgen.py:37:    'ctlv_create',\ntools/ctlv/ctlvgen/lib/cgen.py-38-    'ctlv_destroy',\n--\ntools/ctlv/ctlvgen/lib/gen_family.py=316=def _descriptor(writer, names, family):\n--\ntools/ctlv/ctlvgen/lib/gen_family.py-319-    else:\ntools/ctlv/ctlvgen/lib/gen_family.py:320:        writer.comment('Family descriptor used by ctlv_create().')\ntools/ctlv/ctlvgen/lib/gen_family.py-321-    writer.declaration('const struct ctlv_family',\n"
}

5/2 2026/10/15 19:11 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 236721
							output: 38
							thoughts: 363
						

Thoughts:
**Tracing the CTLV Creation in the TDX Attestation Flow**

Okay, so I see that `attestation_tdx_add` is the sole kernel caller of `ctlv_create`. That's the entry point to investigate. Let's dig into the code; the path is `drivers/attestation/providers/tdx.c`. Ah, there it is: `attestation_tdx_add`. It populates a `struct attestation_tdx_init_info` and then calls `ctlv_create` with this info.

Now, the important question is: what triggers the call to `attestation_tdx_add`?  It seems like `attestation_tdx_add` is a member of `attestation_tdx_client`. I see the `tdx_guest_client_register` function, called from within `attestation_tdx_init_module`. So I need to find out *who* calls `attestation_tdx_client.add` or `tdx_guest_client_register`. I need to figure out how this module gets initialized. Let's look at `drivers/virt/coco/tdx-guest/tdx-guest.c` to see if that gives me some clues. I should see how `tdx-guest.c` is initialized.



6/2 2026/10/15 19:11 tool grepper
0m Args:
{
  "Expression": "tdx_guest_init",
  "PathPrefixes": [
    "drivers/virt/coco/tdx-guest/"
  ]
}

Results:
{
  "Output": "drivers/virt/coco/tdx-guest/tdx-guest.c=591=EXPORT_SYMBOL_NS_GPL(tdx_guest_client_unregister, \"TDX_GUEST\");\ndrivers/virt/coco/tdx-guest/tdx-guest.c-592-\ndrivers/virt/coco/tdx-guest/tdx-guest.c:593:static int __init tdx_guest_init(void)\ndrivers/virt/coco/tdx-guest/tdx-guest.c-594-{\n--\ndrivers/virt/coco/tdx-guest/tdx-guest.c-639-}\ndrivers/virt/coco/tdx-guest/tdx-guest.c:640:module_init(tdx_guest_init);\ndrivers/virt/coco/tdx-guest/tdx-guest.c-641-\n"
}

7/2 2026/10/15 19:11 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 237635
							output: 45
							thoughts: 33
						

Thoughts:
Okay, here's my take on those thoughts, tailored for an expert audience, and from a first-person perspective:

**Diving into the TDX Guest Initialization**

Alright, let's get down to brass tacks. I'm thinking, let's crack open `drivers/virt/coco/tdx-guest/tdx-guest.c`, specifically around the `tdx_guest_init` function. I'm keen to understand the early stages of a TDX guest's life cycle. My primary interest lies in how the TDX-specific features are initially set up within the guest environment. I want to see the fundamental interactions with the TDX module and how the underlying hardware is configured. I'll likely pay close attention to the data structures being initialized, and the order of operations in the setup process. Are they allocating resources, verifying TDX availability, establishing communication channels? Specifically, I'm expecting to see how the kernel integrates with the TDX module. What hooks are being established? Are there any security-related initializations I should keep a close eye on? What are the key trust anchors? Let's get to the code and see.



8/2 2026/10/15 19:11 tool read-file
0m Args:
{
  "File": "drivers/virt/coco/tdx-guest/tdx-guest.c",
  "FirstLine": 585,
  "LineCount": 60
}

Results:
{
  "Contents": " 585:\t\tguard(mutex)(\u0026client_lock);\n 586:\t\tif (WARN_ON_ONCE(client != tdx_client))\n 587:\t\t\treturn;\n 588:\t\ttdx_guest_client_detach();\n 589:\t\ttdx_client = NULL;\n 590:\t}\n 591:\tEXPORT_SYMBOL_NS_GPL(tdx_guest_client_unregister, \"TDX_GUEST\");\n 592:\t\n 593:\tstatic int __init tdx_guest_init(void)\n 594:\t{\n 595:\t\tint ret;\n 596:\t\n 597:\t\tif (!x86_match_cpu(tdx_guest_ids))\n 598:\t\t\treturn -ENODEV;\n 599:\t\n 600:\t\ttdx_attr_groups[0] = tdx_mr_init();\n 601:\t\tif (IS_ERR(tdx_attr_groups[0]))\n 602:\t\t\treturn PTR_ERR(tdx_attr_groups[0]);\n 603:\t\n 604:\t\tret = misc_register(\u0026tdx_misc_dev);\n 605:\t\tif (ret)\n 606:\t\t\tgoto deinit_mr;\n 607:\t\n 608:\t\tquote_data = alloc_quote_buf();\n 609:\t\tif (!quote_data) {\n 610:\t\t\tpr_err(\"Failed to allocate Quote buffer\\n\");\n 611:\t\t\tret = -ENOMEM;\n 612:\t\t\tgoto free_misc;\n 613:\t\t}\n 614:\t\n 615:\t\tret = tsm_report_register(\u0026tdx_tsm_ops, NULL);\n 616:\t\tif (ret)\n 617:\t\t\tgoto free_quote;\n 618:\t\tscoped_guard(mutex, \u0026client_lock) {\n 619:\t\t\ttdx_service_ready = true;\n 620:\t\t\tret = tdx_guest_client_attach();\n 621:\t\t\tif (ret)\n 622:\t\t\t\ttdx_service_ready = false;\n 623:\t\t}\n 624:\t\tif (ret)\n 625:\t\t\tgoto unregister_tsm;\n 626:\t\n 627:\t\treturn 0;\n 628:\t\n 629:\tunregister_tsm:\n 630:\t\ttsm_report_unregister(\u0026tdx_tsm_ops);\n 631:\tfree_quote:\n 632:\t\tfree_quote_buf(quote_data);\n 633:\tfree_misc:\n 634:\t\tmisc_deregister(\u0026tdx_misc_dev);\n 635:\tdeinit_mr:\n 636:\t\ttdx_mr_deinit(tdx_attr_groups[0]);\n 637:\t\n 638:\t\treturn ret;\n 639:\t}\n 640:\tmodule_init(tdx_guest_init);\n 641:\t\n 642:\tstatic void __exit tdx_guest_exit(void)\n 643:\t{\n 644:\t\tscoped_guard(mutex, \u0026client_lock) {\n"
}

9/2 2026/10/15 19:11 llm patch-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 238814
							output: 38
							thoughts: 90
						

Thoughts:
Okay, here's my interpretation of that code snippet, presented as my own thought process:

**Diving into the TDX Guest Initialization**

Alright, let's see... Line 597 and 598 in this code are giving me a return `-ENODEV` if something called `x86_match_cpu(tdx_guest_ids)` doesn't pass. Hmm, interesting. The code's preventing this TDX guest initialization from proceeding if a CPU check fails.

But what the heck *is* `tdx_guest_ids`? I'm going to quickly jump over to `drivers/virt/coco/tdx-guest/tdx-guest.c`. I need to figure out what that variable represents. Knowing the context of `tdx_guest_ids` will tell me exactly what the CPU match check is doing and why it is so crucial to the operation of the TDX guest. This variable, or whatever it holds, must be fundamental to the hardware configuration for the system to boot as a TDX guest.



10/2 2026/10/15 19:12 tool grepper
0m Args:
{
  "Expression": "tdx_guest_ids",
  "PathPrefixes": [
    "drivers/virt/coco/tdx-guest/"
  ]
}

Results:
{
  "Output": "drivers/virt/coco/tdx-guest/tdx-guest.c=511=static struct miscdevice tdx_misc_dev = {\n--\ndrivers/virt/coco/tdx-guest/tdx-guest.c-517-\ndrivers/virt/coco/tdx-guest/tdx-guest.c:518:static const struct x86_cpu_id tdx_guest_ids[] = {\ndrivers/virt/coco/tdx-guest/tdx-guest.c-519-\tX86_MATCH_FEATURE(X86_FEATURE_TDX_GUEST, NULL),\n--\ndrivers/virt/coco/tdx-guest/tdx-guest.c-521-};\ndrivers/virt/coco/tdx-guest/tdx-guest.c:522:MODULE_DEVICE_TABLE(x86cpu, tdx_guest_ids);\ndrivers/virt/coco/tdx-guest/tdx-guest.c-523-\n--\ndrivers/virt/coco/tdx-guest/tdx-guest.c=593=static int __init tdx_guest_init(void)\n--\ndrivers/virt/coco/tdx-guest/tdx-guest.c-596-\ndrivers/virt/coco/tdx-guest/tdx-guest.c:597:\tif (!x86_match_cpu(tdx_guest_ids))\ndrivers/virt/coco/tdx-guest/tdx-guest.c-598-\t\treturn -ENODEV;\n"
}

11/2 2026/10/15 19:12 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 239553
							output: 41
							thoughts: 799
						

Thoughts:
**TDX Guest and `ctlv_create`: A Deep Dive**

Okay, so `X86_FEATURE_TDX_GUEST`… a flag that immediately raises a question: Can we even run a TDX guest in a standard QEMU or Google Compute Engine (GCE) environment?  My initial thought is no, but let’s be certain.  This is crucial because we know the instructions state that fuzzing should only target code reachable in standard virtualized environments. I need to make sure this isn't hardware specific.

Section 1 and 2 are clear on this point.  If the code is unreachable in standard environments like GCE or QEMU, it's a no-go for fuzzing.  Specifically, structurally unreachable hardware or execution paths are explicitly excluded.  Is this the case with a TDX guest?

So, back to the core question: Does standard Syzkaller, which runs QEMU on x86_64, or GCE VMs, support Intel TDX confidential VM guests (as indicated by `X86_FEATURE_TDX_GUEST`)? I'm pretty sure the answer is no. Standard QEMU and GCE aren't set up to run TDX guests.  But let's not assume, we need to know for sure.

Now, a key piece of this puzzle: Is the sole caller of `ctlv_create` the TDX guest? This is vital. If something *other* than the TDX guest creates the relevant character device, then the scope of our concerns expands significantly.

I've grepped the entire kernel repository for `ctlv_create`.  The results are conclusive: the only caller is `attestation_tdx_add` within `drivers/attestation/providers/tdx.c`. This function is registered via `tdx_guest_client_register` in `attestation_tdx_init_module`.  `attestation_tdx_client.add()` is *only* called from `tdx_guest_client_attach()` within `drivers/virt/coco/tdx-guest/tdx-guest.c`.

Crucially, `tdx-guest.c` only initializes if `!x86_match_cpu(tdx_guest_ids)` which translates to `X86_FEATURE_TDX_GUEST`.  If this condition isn't met, `tdx_guest_init` returns `-ENODEV`. This failure prevents `tdx_service_ready` from being true, stops `tdx_misc_dev` from being registered, means `tdx_guest_client_attach` *isn't* called, and therefore `attestation_tdx_add` isn't called. Thus, `ctlv_create()` is *never* invoked! Consequently, no `/dev/ctlv*` character devices are ever registered or created.

But, I need to be absolutely certain. Is there another way the `ctlv` character device could be created? Let's verify by checking `drivers/ctlv/core.c`.



12/2 2026/10/15 19:12 tool grepper
0m Args:
{
  "Expression": "cdev_add|device_add|cdev_device_add",
  "PathPrefixes": [
    "drivers/ctlv/"
  ]
}

Results:
{
  "Output": "drivers/ctlv/core.c=1348=static struct class ctlv_device_class = {\n--\ndrivers/ctlv/core.c-1353-\ndrivers/ctlv/core.c:1354:static int ctlv_device_add(struct ctlv_device *ctlvdev)\ndrivers/ctlv/core.c-1355-{\n--\ndrivers/ctlv/core.c-1357-\ndrivers/ctlv/core.c:1358:\treturn cdev_device_add(\u0026ctlvdev-\u003ecdev, \u0026ctlvdev-\u003edev);\ndrivers/ctlv/core.c-1359-}\n--\ndrivers/ctlv/core.c=1366=struct ctlv_device *ctlv_create(struct device *parent_dev, const struct ctlv_family *family,\n--\ndrivers/ctlv/core.c-1436-\tscoped_guard(rwsem_write, \u0026ctlvdev-\u003eregistration_lock) {\ndrivers/ctlv/core.c:1437:\t\tret = ctlv_device_add(ctlvdev);\ndrivers/ctlv/core.c-1438-\t\tif (!ret)\n"
}

13/2 2026/10/15 19:12 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 241371
							output: 37
							thoughts: 71
						

Thoughts:
Here's my thought process, as requested:

**Deconstructing the CTLV Device Initialization**

Okay, so `cdev_device_add`... I know that one's the crucial step for registering the character device, right? But where is it *actually* called? I need to trace this. Ah, it's exclusively within `ctlv_device_add`, which means it's pretty localized. And `ctlv_device_add` itself is only invoked from `ctlv_create`. That narrows down the initialization sequence considerably. That also suggests an issue in this area is also localized.

Now, what about `ctlv_module_init`? That’s where the drivers’ global state should be set up, so it's critical. I really should check that out too. Let's see what’s going on around that line in `drivers/ctlv/core.c`. I need to get a handle on what the module initialization is doing to the character device.



14/2 2026/10/15 19:12 tool read-file
0m Args:
{
  "File": "drivers/ctlv/core.c",
  "FirstLine": 1480,
  "LineCount": 40
}

Results:
{
  "Contents": "1480:\t\t\tctlvdev-\u003eops[index].priv = NULL;\n1481:\t\t}\n1482:\t\tctlv_family_privs_free(ctlvdev);\n1483:\t\tput_device(\u0026ctlvdev-\u003edev);\n1484:\t}\n1485:\tEXPORT_SYMBOL_NS_GPL(ctlv_destroy, \"CTLV\");\n1486:\t\n1487:\tstatic int __init ctlv_module_init(void)\n1488:\t{\n1489:\t\tint ret;\n1490:\t\n1491:\t\tret = alloc_chrdev_region(\u0026ctlv_device_number, 0, CTLV_MAX_DEVICES, \"ctlv\");\n1492:\t\tif (ret)\n1493:\t\t\treturn ret;\n1494:\t\n1495:\t\tret = class_register(\u0026ctlv_device_class);\n1496:\t\tif (ret)\n1497:\t\t\tgoto err_unregister_chrdev_region;\n1498:\t\n1499:\t\treturn 0;\n1500:\t\n1501:\terr_unregister_chrdev_region:\n1502:\t\tunregister_chrdev_region(ctlv_device_number, CTLV_MAX_DEVICES);\n1503:\t\treturn ret;\n1504:\t}\n1505:\t\n1506:\tstatic void __exit ctlv_module_exit(void)\n1507:\t{\n1508:\t\tclass_unregister(\u0026ctlv_device_class);\n1509:\t\tunregister_chrdev_region(ctlv_device_number, CTLV_MAX_DEVICES);\n1510:\t\tctlv_family_claims_free();\n1511:\t\tida_destroy(\u0026ctlv_device_ids);\n1512:\t}\n1513:\t\n1514:\tsubsys_initcall(ctlv_module_init);\n1515:\tmodule_exit(ctlv_module_exit);\n1516:\tMODULE_DESCRIPTION(\"CTLV character device TLV UAPI core\");\n1517:\tMODULE_LICENSE(\"GPL\");\n"
}

15/2 2026/10/15 19:12 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 242262
							output: 25
							thoughts: 444
						

Thoughts:
**My Analysis of the `ctlv` Module and its Limited Scope**

Okay, so let me break this down. From what I can see, the `ctlv_module_init` function is surprisingly simple. All it does is grab a character device region and register a class. The key takeaway here is that it *doesn't* create any device nodes like `/dev/ctlv*` directly. That's interesting, but not necessarily a red flag yet.

The device nodes are only created by `ctlv_create()`. This function seems to handle the actual allocation and setup of the device, including assigning a name using `dev_set_name` and adding the character device. The critical part is *who* calls `ctlv_create()`. My understanding is that the only place it's called in the entire kernel is from the `attestation_tdx_add` function in the `tdx.c` file.

Now, `attestation_tdx_add` is only called by `tdx_guest_client_attach`, which, in turn, is only called if the `X86_FEATURE_TDX_GUEST` feature is present! That's the real crux of this whole thing, I think.

This implies that the device and its driver are tied to running inside a TDX guest, a trusted domain enclave VM on physical hardware which is an Intel TDX secure enclave. This means the hardware needs to support TDX. So, Emerald Rapids or Sapphire Rapids Xeon CPUs, with TDX enabled in the BIOS/firmware, and the host KVM needs TDX host support. Standard QEMU/KVM or Google Compute Engine (GCE) instances *without* Intel TDX simply wouldn't have this feature, so it wouldn't even be available. Standard QEMU doesn't emulate the TDX hardware.

I should probably double-check the definition of `X86_FEATURE_TDX_GUEST` in the kernel source itself to be absolutely certain, but my gut feeling is that this whole `ctlv` module and its devices is completely irrelevant in most common virtualization or cloud environments. It's essentially a very specific, niche driver for a very specific hardware configuration.



16/2 2026/10/15 19:13 tool grepper
0m Args:
{
  "Expression": "X86_FEATURE_TDX_GUEST"
}

Results:
{
  "Output": "arch/x86/coco/tdx/tdx.c=1112=void __init tdx_early_init(void)\n--\narch/x86/coco/tdx/tdx.c-1121-\narch/x86/coco/tdx/tdx.c:1122:\tsetup_force_cpu_cap(X86_FEATURE_TDX_GUEST);\narch/x86/coco/tdx/tdx.c-1123-\n--\narch/x86/include/asm/cpufeatures.h-239-#define X86_FEATURE_VCPUPREEMPT\t\t( 8*32+21) /* PV vcpu_is_preempted function */\narch/x86/include/asm/cpufeatures.h:240:#define X86_FEATURE_TDX_GUEST\t\t( 8*32+22) /* \"tdx_guest\" Intel Trust Domain Extensions Guest */\narch/x86/include/asm/cpufeatures.h-241-\n--\narch/x86/include/asm/kvm_para.h=34=static inline long kvm_hypercall0(unsigned int nr)\n--\narch/x86/include/asm/kvm_para.h-37-\narch/x86/include/asm/kvm_para.h:38:\tif (cpu_feature_enabled(X86_FEATURE_TDX_GUEST))\narch/x86/include/asm/kvm_para.h-39-\t\treturn tdx_kvm_hypercall(nr, 0, 0, 0, 0);\n--\narch/x86/include/asm/kvm_para.h=48=static inline long kvm_hypercall1(unsigned int nr, unsigned long p1)\n--\narch/x86/include/asm/kvm_para.h-51-\narch/x86/include/asm/kvm_para.h:52:\tif (cpu_feature_enabled(X86_FEATURE_TDX_GUEST))\narch/x86/include/asm/kvm_para.h-53-\t\treturn tdx_kvm_hypercall(nr, p1, 0, 0, 0);\n--\narch/x86/include/asm/kvm_para.h=62=static inline long kvm_hypercall2(unsigned int nr, unsigned long p1,\n--\narch/x86/include/asm/kvm_para.h-66-\narch/x86/include/asm/kvm_para.h:67:\tif (cpu_feature_enabled(X86_FEATURE_TDX_GUEST))\narch/x86/include/asm/kvm_para.h-68-\t\treturn tdx_kvm_hypercall(nr, p1, p2, 0, 0);\n--\narch/x86/include/asm/kvm_para.h=77=static inline long kvm_hypercall3(unsigned int nr, unsigned long p1,\n--\narch/x86/include/asm/kvm_para.h-81-\narch/x86/include/asm/kvm_para.h:82:\tif (cpu_feature_enabled(X86_FEATURE_TDX_GUEST))\narch/x86/include/asm/kvm_para.h-83-\t\treturn tdx_kvm_hypercall(nr, p1, p2, p3, 0);\n--\narch/x86/include/asm/kvm_para.h=92=static inline long kvm_hypercall4(unsigned int nr, unsigned long p1,\n--\narch/x86/include/asm/kvm_para.h-97-\narch/x86/include/asm/kvm_para.h:98:\tif (cpu_feature_enabled(X86_FEATURE_TDX_GUEST))\narch/x86/include/asm/kvm_para.h-99-\t\treturn tdx_kvm_hypercall(nr, p1, p2, p3, p4);\n--\narch/x86/include/asm/unaccepted_memory.h=8=static inline void arch_accept_memory(phys_addr_t start, phys_addr_t end)\n--\narch/x86/include/asm/unaccepted_memory.h-10-\t/* Platform-specific memory-acceptance call goes here */\narch/x86/include/asm/unaccepted_memory.h:11:\tif (cpu_feature_enabled(X86_FEATURE_TDX_GUEST)) {\narch/x86/include/asm/unaccepted_memory.h-12-\t\tif (!tdx_accept_memory(start, end))\n--\narch/x86/include/asm/vmware.h=99=unsigned long vmware_hypercall1(unsigned long cmd, unsigned long in1)\n--\narch/x86/include/asm/vmware.h-102-\narch/x86/include/asm/vmware.h:103:\tif (cpu_feature_enabled(X86_FEATURE_TDX_GUEST))\narch/x86/include/asm/vmware.h-104-\t\treturn vmware_tdx_hypercall(cmd, in1, 0, 0, 0,\n--\narch/x86/include/asm/vmware.h=123=unsigned long vmware_hypercall3(unsigned long cmd, unsigned long in1,\n--\narch/x86/include/asm/vmware.h-127-\narch/x86/include/asm/vmware.h:128:\tif (cpu_feature_enabled(X86_FEATURE_TDX_GUEST))\narch/x86/include/asm/vmware.h-129-\t\treturn vmware_tdx_hypercall(cmd, in1, 0, 0, 0,\n--\narch/x86/include/asm/vmware.h=148=unsigned long vmware_hypercall4(unsigned long cmd, unsigned long in1,\n--\narch/x86/include/asm/vmware.h-152-\narch/x86/include/asm/vmware.h:153:\tif (cpu_feature_enabled(X86_FEATURE_TDX_GUEST))\narch/x86/include/asm/vmware.h-154-\t\treturn vmware_tdx_hypercall(cmd, in1, 0, 0, 0,\n--\narch/x86/include/asm/vmware.h=173=unsigned long vmware_hypercall5(unsigned long cmd, unsigned long in1,\n--\narch/x86/include/asm/vmware.h-178-\narch/x86/include/asm/vmware.h:179:\tif (cpu_feature_enabled(X86_FEATURE_TDX_GUEST))\narch/x86/include/asm/vmware.h-180-\t\treturn vmware_tdx_hypercall(cmd, in1, in3, in4, in5,\n--\narch/x86/include/asm/vmware.h=201=unsigned long vmware_hypercall6(unsigned long cmd, unsigned long in1,\n--\narch/x86/include/asm/vmware.h-206-\narch/x86/include/asm/vmware.h:207:\tif (cpu_feature_enabled(X86_FEATURE_TDX_GUEST))\narch/x86/include/asm/vmware.h-208-\t\treturn vmware_tdx_hypercall(cmd, in1, in3, 0, 0,\n--\narch/x86/include/asm/vmware.h=228=unsigned long vmware_hypercall7(unsigned long cmd, unsigned long in1,\n--\narch/x86/include/asm/vmware.h-234-\narch/x86/include/asm/vmware.h:235:\tif (cpu_feature_enabled(X86_FEATURE_TDX_GUEST))\narch/x86/include/asm/vmware.h-236-\t\treturn vmware_tdx_hypercall(cmd, in1, in3, in4, in5,\n--\narch/x86/kernel/cpu/mtrr/generic.c=440=void guest_force_mtrr_state(struct mtrr_var_range *var, unsigned int num_var,\n--\narch/x86/kernel/cpu/mtrr/generic.c-462-\t    !cpu_feature_enabled(X86_FEATURE_XENPV) \u0026\u0026\narch/x86/kernel/cpu/mtrr/generic.c:463:\t    !cpu_feature_enabled(X86_FEATURE_TDX_GUEST))\narch/x86/kernel/cpu/mtrr/generic.c-464-\t\treturn;\n--\narch/x86/kernel/process.c=938=void __init select_idle_routine(void)\n--\narch/x86/kernel/process.c-952-\t\tstatic_call_update(x86_idle, mwait_idle);\narch/x86/kernel/process.c:953:\t} else if (cpu_feature_enabled(X86_FEATURE_TDX_GUEST)) {\narch/x86/kernel/process.c-954-\t\tpr_info(\"using TDX aware idle routine\\n\");\n--\narch/x86/kernel/relocate_kernel_64.S=129=SYM_CODE_START_LOCAL_NOALIGN(identity_mapped)\n--\narch/x86/kernel/relocate_kernel_64.S-204-\tandl\t$(X86_CR4_PAE | X86_CR4_LA57), %r13d\narch/x86/kernel/relocate_kernel_64.S:205:\tALTERNATIVE \"\", __stringify(orl $X86_CR4_MCE, %r13d), X86_FEATURE_TDX_GUEST\narch/x86/kernel/relocate_kernel_64.S-206-\tmovq\t%r13, %cr4\n--\ndrivers/virt/coco/tdx-guest/tdx-guest.c=518=static const struct x86_cpu_id tdx_guest_ids[] = {\ndrivers/virt/coco/tdx-guest/tdx-guest.c:519:\tX86_MATCH_FEATURE(X86_FEATURE_TDX_GUEST, NULL),\ndrivers/virt/coco/tdx-guest/tdx-guest.c-520-\t{}\n--\ntools/arch/x86/include/asm/cpufeatures.h-229-#define X86_FEATURE_VCPUPREEMPT\t\t( 8*32+21) /* PV vcpu_is_preempted function */\ntools/arch/x86/include/asm/cpufeatures.h:230:#define X86_FEATURE_TDX_GUEST\t\t( 8*32+22) /* \"tdx_guest\" Intel Trust Domain Extensions Guest */\ntools/arch/x86/include/asm/cpufeatures.h-231-\n"
}

17/2 2026/10/15 19:13 llm patch-evaluator
1m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 246023
							output: 44
							thoughts: 88
						

Thoughts:
Okay, let's break this down.

**Investigating the TDX Guest Feature Flag**

Right, so I need to understand how the `X86_FEATURE_TDX_GUEST` flag is being set within the x86 architecture, specifically for TDX guests. The first thing that jumps out is that it appears this is handled in `arch/x86/coco/tdx/tdx.c`. My instinct is to trace the execution, so I'll check `tdx_early_init`, as that's where the function is called. Looks like `setup_force_cpu_cap(X86_FEATURE_TDX_GUEST)` is being used to set the feature. Now, I need to know what conditions or checks are occurring within that `tdx_early_init` function itself. I need to see if there are any prerequisite steps that must be done before setting that flag. Let's dig deeper into that early initialization routine.



18/2 2026/10/15 19:14 tool read-file
0m Args:
{
  "File": "arch/x86/coco/tdx/tdx.c",
  "FirstLine": 1110,
  "LineCount": 40
}

Results:
{
  "Contents": "1110:\t}\n1111:\t\n1112:\tvoid __init tdx_early_init(void)\n1113:\t{\n1114:\t\tu64 cc_mask;\n1115:\t\tu32 eax, sig[3];\n1116:\t\n1117:\t\tcpuid_count(TDX_CPUID_LEAF_ID, 0, \u0026eax, \u0026sig[0], \u0026sig[2],  \u0026sig[1]);\n1118:\t\n1119:\t\tif (memcmp(TDX_IDENT, sig, sizeof(sig)))\n1120:\t\t\treturn;\n1121:\t\n1122:\t\tsetup_force_cpu_cap(X86_FEATURE_TDX_GUEST);\n1123:\t\n1124:\t\t/* TSC is the only reliable clock in TDX guest */\n1125:\t\tsetup_force_cpu_cap(X86_FEATURE_TSC_RELIABLE);\n1126:\t\n1127:\t\tcc_vendor = CC_VENDOR_INTEL;\n1128:\t\n1129:\t\t/* Configure the TD */\n1130:\t\ttdx_setup(\u0026cc_mask);\n1131:\t\n1132:\t\tcc_set_mask(cc_mask);\n1133:\t\n1134:\t\t/*\n1135:\t\t * All bits above GPA width are reserved and kernel treats shared bit\n1136:\t\t * as flag, not as part of physical address.\n1137:\t\t *\n1138:\t\t * Adjust physical mask to only cover valid GPA bits.\n1139:\t\t */\n1140:\t\tphysical_mask \u0026= cc_mask - 1;\n1141:\t\n1142:\t\t/*\n1143:\t\t * The kernel mapping should match the TDX metadata for the page.\n1144:\t\t * load_unaligned_zeropad() can touch memory *adjacent* to that which is\n1145:\t\t * owned by the caller and can catch even _momentary_ mismatches.  Bad\n1146:\t\t * things happen on mismatch:\n1147:\t\t *\n1148:\t\t *   - Private mapping =\u003e Shared Page  == Guest shutdown\n1149:\t         *   - Shared mapping  =\u003e Private Page == Recoverable #VE\n"
}

19/2 2026/10/15 19:14 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 246967
							output: 36
							thoughts: 2261
						

Thoughts:
**TDX Guest Unreachability Analysis**

Okay, here's the breakdown. This code is clearly checking for an Intel TDX Trust Domain environment with that `cpuid_count` check. Specifically, it's looking for the TDX signature, and if it doesn't find it, it bails.  Since I'm in a standard environment (QEMU or GCE), that `X86_FEATURE_TDX_GUEST` flag isn't set, so the TDX path is dead on arrival.

I then went digging for any other clues about how this TDX code might be activated and confirmed the `tdx_guest` driver checks.  It specifically calls `x86_match_cpu(tdx_guest_ids)`. It's explicitly designed to *not* load in a standard QEMU environment. The `tdx_guest_init` function returns `-ENODEV` when the CPU doesn't match the required TDX features.

I looked at the attestation framework and CTLV framework because they appear to be related, and they have TDX-specific code, but I couldn't find any other attestation providers. There's only one, `providers/tdx.c`. The `core/` module doesn't do anything on its own. It's the provider that does the work. These providers call `ctlv_create()` with `ctlv_attestation_tdx_family`. I confirmed the absence of alternative providers or device creation in the `attestation` framework.

Then, I went back to the fuzzing philosophy. Reachability is key. Since this TDX code path is triggered *only* in a TDX environment, it's structurally unreachable in my standard setup.  TDX requires specific hardware (Intel Xeon with TDX support) and specialized QEMU builds with TDX emulation support. Standard QEMU doesn't emulate the TDX environment, and the CPU ID checks always fail.

I need to confirm if userspace can create a CTLV device or otherwise trigger `ctlv_create`. I checked `drivers/ctlv/` for any sysfs, ioctl, netlink, or configfs interface for creating devices, and found nothing. I reviewed the code in `core.c` and confirmed that no device is created during module initialization. It only registers the class.  You can't just `mknod /dev/ctlv0` and expect it to work! The driver uses a dynamic major number allocation. Even if you *could* guess the major number and create the device node, the VFS will fail because `cdev_device_add` was never called, and so the kernel cannot find the cdev and will return `-ENXIO`. The `ctlv_create` function, the device creator, is never called.

I also checked for any TSM integration, just to be sure, and found nothing. So, in summary: This TDX code is fundamentally unreachable in a standard QEMU or GCE environment. It's safe to mark this patch as non-fuzzable, based on the reachability criteria.



20/2 2026/10/15 19:14 tool grepper
0m Error:
no matches

Args:
{
  "Expression": "tsm",
  "PathPrefixes": [
    "drivers/attestation/",
    "drivers/ctlv/"
  ]
}

Results:
{
  "error": "no matches"
}

21/2 2026/10/15 19:14 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 249946
							output: 22
							thoughts: 181
						

Thoughts:
Okay, let's break this down.

**Investigating the Absence of TSM in Attestation Drivers**

First, I need to confirm something. The `drivers/attestation` directory *doesn't* appear to directly interact with `tsm`, which is strange. I can see it does document using `<linux/tdx-guest.h>`, but it explicitly states the provider doesn't call the TDX misc ioctl, configfs TSM-report, or TSM-MR sysfs frontends. This feels like an important point to clarify, so let's dig deeper.

My immediate next thought is, where else might `ctlv_create` be used?  I remember seeing that function called somewhere, probably in relation to TDX attestation.

Right, so I ran a quick `grepper` and it looks like `ctlv_create` appears in only two places:  `drivers/attestation/providers/tdx.c` and `drivers/ctlv/core.c`. This is good, I have narrowed down its scope.

Hmm, this still feels incomplete. I need to make sure I'm not missing anything. Specifically, I'm going to look for other ways that `tdx_guest` could be instantiated, just to make sure I'm not missing any other potential integration points. Let's search the kernel for `tdx_guest_client_register`. That should help me figure this out.



22/2 2026/10/15 19:14 tool grepper
0m Args:
{
  "Expression": "tdx_guest_client_register"
}

Results:
{
  "Output": "drivers/attestation/providers/tdx.c=261=static int __init attestation_tdx_init_module(void)\ndrivers/attestation/providers/tdx.c-262-{\ndrivers/attestation/providers/tdx.c:263:\treturn tdx_guest_client_register(\u0026attestation_tdx_client);\ndrivers/attestation/providers/tdx.c-264-}\n--\ndrivers/virt/coco/tdx-guest/tdx-guest.c=556=static void tdx_guest_client_detach(void)\n--\ndrivers/virt/coco/tdx-guest/tdx-guest.c-565-\ndrivers/virt/coco/tdx-guest/tdx-guest.c:566:int tdx_guest_client_register(const struct tdx_guest_client *client)\ndrivers/virt/coco/tdx-guest/tdx-guest.c-567-{\n--\ndrivers/virt/coco/tdx-guest/tdx-guest.c-580-}\ndrivers/virt/coco/tdx-guest/tdx-guest.c:581:EXPORT_SYMBOL_NS_GPL(tdx_guest_client_register, \"TDX_GUEST\");\ndrivers/virt/coco/tdx-guest/tdx-guest.c-582-\n--\ninclude/linux/tdx-guest.h=55=struct tdx_guest_client {\n--\ninclude/linux/tdx-guest.h-61-/**\ninclude/linux/tdx-guest.h:62: * tdx_guest_client_register - Register one native TDX service consumer\ninclude/linux/tdx-guest.h-63- * @client: Immutable add/remove callback pair\n--\ninclude/linux/tdx-guest.h-66- */\ninclude/linux/tdx-guest.h:67:int tdx_guest_client_register(const struct tdx_guest_client *client);\ninclude/linux/tdx-guest.h-68-\n--\ninclude/linux/tdx-guest.h-70- * tdx_guest_client_unregister - Unregister a native TDX service consumer\ninclude/linux/tdx-guest.h:71: * @client: Descriptor passed to tdx_guest_client_register()\ninclude/linux/tdx-guest.h-72- */\n"
}

23/2 2026/10/15 19:14 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 251050
							output: 29
							thoughts: 785
						

Thoughts:
**Analyzing TDX Guest Initialization**

Okay, let's dive into this. I'm starting by looking at `tdx-guest.c`, specifically the `tdx_guest_client_register()` function. It's straightforward: check for null pointers, grab the `client_lock`, ensure there isn't an existing client, register the new client, and then call `tdx_guest_client_attach()`. The interesting part is what happens within `tdx_guest_client_attach()`.

Aha, so it checks `tdx_service_ready`. If it's false, the `tdx_client->add()` function doesn't get called and it returns 0! Now, when is `tdx_service_ready` set? I remember from other work, the `tdx_guest_init` function. Right, it sets `tdx_service_ready` *after* checking `x86_match_cpu(tdx_guest_ids)`. And that check is the initial gatekeeper: If it fails, the function returns with `-ENODEV` which is expected when not in a TDX guest, because the `tdx_service_ready` is false.

Wait a second… here's the thought. Can this ever be true in QEMU? Specifically, can QEMU emulate `X86_FEATURE_TDX_GUEST`? That's the key. I need to understand what `X86_FEATURE_TDX_GUEST` actually means and how it's set. 

Okay, I need to check `arch/x86/coco/tdx/tdx.c` and see where this flag is set. Ah, in `tdx_early_init`: there's a `cpuid_count` call that extracts a signature, and based on that signature, `setup_force_cpu_cap(X86_FEATURE_TDX_GUEST)` is called. But what's that signature, exactly? Let me find what `TDX_IDENT` and `TDX_CPUID_LEAF_ID` are defined as to understand what's going on with the CPUIID calls.



24/2 2026/10/15 19:14 tool grepper
0m Args:
{
  "Expression": "TDX_CPUID_LEAF_ID|TDX_IDENT"
}

Results:
{
  "Output": "arch/x86/boot/compressed/mem.c=15=static bool early_is_tdx_guest(void)\n--\narch/x86/boot/compressed/mem.c-25-\narch/x86/boot/compressed/mem.c:26:\t\tcpuid_count(TDX_CPUID_LEAF_ID, 0, \u0026eax,\narch/x86/boot/compressed/mem.c-27-\t\t\t    \u0026sig[0], \u0026sig[2],  \u0026sig[1]);\narch/x86/boot/compressed/mem.c:28:\t\tis_tdx = !memcmp(TDX_IDENT, sig, sizeof(sig));\narch/x86/boot/compressed/mem.c-29-\t\tonce = true;\n--\narch/x86/boot/compressed/tdx.c=64=void early_tdx_detect(void)\n--\narch/x86/boot/compressed/tdx.c-67-\narch/x86/boot/compressed/tdx.c:68:\tcpuid_count(TDX_CPUID_LEAF_ID, 0, \u0026eax, \u0026sig[0], \u0026sig[2],  \u0026sig[1]);\narch/x86/boot/compressed/tdx.c-69-\narch/x86/boot/compressed/tdx.c:70:\tif (memcmp(TDX_IDENT, sig, sizeof(sig)))\narch/x86/boot/compressed/tdx.c-71-\t\treturn;\n--\narch/x86/coco/tdx/tdx.c=1112=void __init tdx_early_init(void)\n--\narch/x86/coco/tdx/tdx.c-1116-\narch/x86/coco/tdx/tdx.c:1117:\tcpuid_count(TDX_CPUID_LEAF_ID, 0, \u0026eax, \u0026sig[0], \u0026sig[2],  \u0026sig[1]);\narch/x86/coco/tdx/tdx.c-1118-\narch/x86/coco/tdx/tdx.c:1119:\tif (memcmp(TDX_IDENT, sig, sizeof(sig)))\narch/x86/coco/tdx/tdx.c-1120-\t\treturn;\n--\narch/x86/include/asm/shared/tdx.h-10-\narch/x86/include/asm/shared/tdx.h:11:#define TDX_CPUID_LEAF_ID\t0x21\narch/x86/include/asm/shared/tdx.h:12:#define TDX_IDENT\t\t\"IntelTDX    \"\narch/x86/include/asm/shared/tdx.h-13-\n"
}

25/2 2026/10/15 19:14 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 253053
							output: 18
							thoughts: 2578
						

Thoughts:
**Analysis of Code Reachability for Fuzzing**

Okay, so I've been tasked with assessing if this code is worth fuzzing. I need to figure out if syzkaller's QEMU or GCE environments can *actually* reach and execute it. My initial thought is that it might be problematic because the code seems related to Intel TDX, a specialized hardware feature.

I see that `tdx_setup` and related functions, like those using TDCALLs (`tdg_mr_report`, `tdcall(TDG_VM_RD, ...)`), are clearly tied to TDX guest environments. These calls configure private memory and handle virtual exceptions, so they will fault immediately if run without the appropriate TDX hardware support (SEAM / TDCALL). The crucial `X86_FEATURE_TDX_GUEST` can *only* be set when the system boots as a TDX guest *on* a host with Intel TDX support. That's a huge red flag.

The triage instructions are clear. "REACHABILITY IS THE PRIMARY GATE." If the code is structurally unreachable, *it MUST NOT be fuzzed*.  The instructions specifically mention "Structurally unreachable hardware" like vendor-specific PCIe switches, and they require physical ASIC/PCIe cards not emulated in standard QEMU.  I'm interpreting that this might include the TDX features.

Now, let's break down this patch series. It introduces a CTLV subsystem, an attestation subsystem, and a TDX provider and guest client registration. The key is to see if any of these pieces *can* be used in a standard virtualized environment.

The function `ctlv_create()` registers the CTLV character device (`/dev/ctlv0`, etc.). The only caller of `ctlv_create()` is `attestation_tdx_add()`. `attestation_tdx_add()` is *only* called by `tdx_guest_client_attach()` in `drivers/virt/coco/tdx-guest/tdx-guest.c`. However, `tdx_guest_init()` guards itself with `if (!x86_match_cpu(tdx_guest_ids)) return -ENODEV;` which checks for `X86_FEATURE_TDX_GUEST`.

Here's the problem: standard virtualized environments (QEMU or GCE) do *not* have `X86_FEATURE_TDX_GUEST` because they aren't running as Intel TDX guests.  TDX requires specialized hardware and KVM TDX host support. So `tdx_guest_init()` will *always* fail with `-ENODEV`, no TDX client gets attached, `attestation_tdx_add()` is never called, `ctlv_create()` is never called, and no `/dev/ctlv*` devices are ever created.  Therefore, no CTLV processing, parsing, validation, blob handling, event handling, or attestation logic can *ever* be reached by syzkaller.  All of this code is effectively unreachable.

I've checked the initialization of the CTLV and attestation core modules. `ctlv_module_init` registers a chrdev region and a class, and `attestation_module_init` does nothing. But the important thing is that user-space won't be able to open any of the ctlv devices because the chrdev is never really registered except through the tdg client attach function. User space would then need to try and call an open function, but it wouldn't exist!

I've also checked `drivers/virt/coco/tdx-guest/tdx-guest.c` and found no surprises.  The guard is still there. This is specific to Intel's x86_64 TDX confidential computing hardware, which is *not* emulated in standard environments.

I've reviewed the architecture.  This *requires* Intel hardware with TDX enabled, running in a Trust Domain guest. That rules out pretty much every syzkaller instance. Even if we could launch QEMU with TDX support, syzkaller launches regular QEMU commands. No specialized hardware, SEAM loader, or TDX module will be available.  GCE standard VMs are *not* Intel TDX VMs either.

I've gone over the triage instructions again.  The code clearly falls under "Structurally unreachable hardware" as it requires physical ASICs not emulated.

I've also scanned `Documentation/driver-api/ctlv.rst`, but it explicitly says it's example code. No `ctlv-example` exists in the kernel, so no mock driver exists that can be used.

**Conclusion:**  Given all this, the CTLV


26/2 2026/10/15 19:15 tool grepper
0m Args:
{
  "Expression": "ctlv_example"
}

Results:
{
  "Output": "Documentation/driver-api/ctlv.rst=150=The parent implementation opens the physical nest and delegates its members:\n--\nDocumentation/driver-api/ctlv.rst-153-\nDocumentation/driver-api/ctlv.rst:154:    if (ctlv_example_device_details_start(reply, \u0026details)) {\nDocumentation/driver-api/ctlv.rst-155-            ret = ctlv_stub_fill(ctx, request_details, \u0026details);\n--\nDocumentation/driver-api/ctlv.rst=161=The generated child callback fills it:\n--\nDocumentation/driver-api/ctlv.rst-164-\nDocumentation/driver-api/ctlv.rst:165:    int ctlv_example_vendor_details_extension_fill(\nDocumentation/driver-api/ctlv.rst-166-                            void *priv, struct ctlv_op_ctx *ctx,\n--\nDocumentation/driver-api/ctlv.rst-169-    {\nDocumentation/driver-api/ctlv.rst:170:            ctlv_example_vendor_vendor_serial_put(nest,\nDocumentation/driver-api/ctlv.rst-171-                                                   example_serial(priv));\n--\nDocumentation/driver-api/ctlv.rst=182=information:\n--\nDocumentation/driver-api/ctlv.rst-185-\nDocumentation/driver-api/ctlv.rst:186:    struct ctlv_example_vendor_init_info info = {\nDocumentation/driver-api/ctlv.rst-187-            .dev = dev,\n--\nDocumentation/driver-api/ctlv.rst-190-\nDocumentation/driver-api/ctlv.rst:191:    ctlvdev = ctlv_create(dev, \u0026ctlv_example_vendor_ctlv_family, \u0026info);\nDocumentation/driver-api/ctlv.rst-192-    if (IS_ERR(ctlvdev))\n--\nDocumentation/driver-api/ctlv.rst=196=direct parent. A typical provider descriptor is static and immutable:\n--\nDocumentation/driver-api/ctlv.rst-199-\nDocumentation/driver-api/ctlv.rst:200:    static const struct ctlv_example_provider example_provider = {\nDocumentation/driver-api/ctlv.rst-201-            .name = \"vendor-example\",\n--\nDocumentation/driver-api/ctlv.rst-204-\nDocumentation/driver-api/ctlv.rst:205:    const void *ctlv_example_vendor_pre_init(const void *init_info)\nDocumentation/driver-api/ctlv.rst-206-    {\n--\nDocumentation/driver-api/ctlv.rst=264=write only declared replies:\n--\nDocumentation/driver-api/ctlv.rst-267-\nDocumentation/driver-api/ctlv.rst:268:    int ctlv_example_item_set_action(void *priv, struct ctlv_op_ctx *ctx,\nDocumentation/driver-api/ctlv.rst-269-                                     const struct ctlv_cursor *request,\n--\nDocumentation/driver-api/ctlv.rst-271-    {\nDocumentation/driver-api/ctlv.rst:272:            u64 index = ctlv_example_item_index_get(request);\nDocumentation/driver-api/ctlv.rst-273-\n--\nDocumentation/driver-api/ctlv.rst=283=Query\n--\nDocumentation/driver-api/ctlv.rst-287-\nDocumentation/driver-api/ctlv.rst:288:    int ctlv_example_items_dump_query(void *priv, struct ctlv_op_ctx *ctx,\nDocumentation/driver-api/ctlv.rst-289-                                      const struct ctlv_cursor *request,\n--\nDocumentation/driver-api/ctlv.rst-291-    {\nDocumentation/driver-api/ctlv.rst:292:            struct ctlv_example *example = priv;\nDocumentation/driver-api/ctlv.rst-293-            u64 generation = READ_ONCE(example-\u003egeneration);\n--\nDocumentation/driver-api/ctlv.rst-300-            for (; i \u003c example-\u003eitems_count; i++) {\nDocumentation/driver-api/ctlv.rst:301:                    if (!ctlv_example_list_item_start(reply, \u0026item))\nDocumentation/driver-api/ctlv.rst-302-                            return ctlv_op_query_more(ctx, generation, i + 1);\nDocumentation/driver-api/ctlv.rst:303:                    ctlv_example_item_index_put(\u0026item, i);\nDocumentation/driver-api/ctlv.rst-304-                    ctlv_nest_end(\u0026item);\n--\nDocumentation/driver-api/ctlv.rst=326=Optional and dynamic operations are separate choices:\n--\nDocumentation/driver-api/ctlv.rst-330-    /* During init: publish this optional operation on this device. */\nDocumentation/driver-api/ctlv.rst:331:    ctlv_example_item_set_provide(ctlvdev);\nDocumentation/driver-api/ctlv.rst-332-\nDocumentation/driver-api/ctlv.rst-333-    /* At runtime: temporarily refuse a published dynamic operation. */\nDocumentation/driver-api/ctlv.rst:334:    ctlv_example_items_dump_disable(ctlvdev);\nDocumentation/driver-api/ctlv.rst:335:    ctlv_example_items_dump_enable(ctlvdev);\nDocumentation/driver-api/ctlv.rst-336-\n--\nDocumentation/driver-api/ctlv.rst=345=that received its request and release every successful resolve before return:\n--\nDocumentation/driver-api/ctlv.rst-348-\nDocumentation/driver-api/ctlv.rst:349:    blob = ctlv_example_item_data_resolve(ctx, request);\nDocumentation/driver-api/ctlv.rst-350-    if (IS_ERR(blob))\n--\nDocumentation/driver-api/ctlv.rst=360=Events\n--\nDocumentation/driver-api/ctlv.rst-364-\nDocumentation/driver-api/ctlv.rst:365:    ctx = ctlv_example_item_changed_create(ctlvdev, \u0026event, GFP_KERNEL);\nDocumentation/driver-api/ctlv.rst-366-    if (IS_ERR(ctx))\nDocumentation/driver-api/ctlv.rst-367-            return PTR_ERR(ctx);\nDocumentation/driver-api/ctlv.rst:368:    ctlv_example_item_index_put(event, index);\nDocumentation/driver-api/ctlv.rst-369-    return ctlv_event_emit(ctx);\n--\nDocumentation/driver-api/ctlv.rst=382=must commit its invalidation and explicitly report the missing notification:\n--\nDocumentation/driver-api/ctlv.rst-388-\nDocumentation/driver-api/ctlv.rst:389:    ctx = ctlv_example_thing_happened_create(ctlvdev, \u0026event, GFP_ATOMIC);\nDocumentation/driver-api/ctlv.rst-390-    if (IS_ERR(ctx)) {\n--\nDocumentation/driver-api/ctlv.rst-395-    }\nDocumentation/driver-api/ctlv.rst:396:    ctlv_example_generation_put(event, priv-\u003egeneration);\nDocumentation/driver-api/ctlv.rst-397-    ctlv_op_emit(ctx);\n"
}

27/2 2026/10/15 19:15 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 258592
							output: 251
							thoughts: 4032
						

Thoughts:
**Analysis of CTLV/Attestation Patch Reachability**

Okay, here's my thought process on this patch. First, I noticed `ctlv-example` is only documented, and no C code exists for a working example. Let's check `tools/ctlv/`, it's just Python scripts and generators, not drivers, and there are no self-tests added. The diff touches the documentation, kernel headers, and also the `drivers/ctlv/`, `drivers/attestation/`, and `drivers/virt/coco/tdx-guest/` directories. Time to verify if anything can *actually* reach these new additions.

My plan: trace the execution path. Starting from the system boot, `ctlv_module_init` runs and sets up a character device region and sysfs class. No device is created. `attestation_module_init` returns 0. The `attestation_tdx_init_module` runs, it calls the `tdx_guest_client_register()` and calls `tdx_guest_client_attach()` which is only called if `tdx_service_ready` is true which is not the case because `tdx_guest_init` runs which checks for `X86_FEATURE_TDX_GUEST`, which in standard virtualized environments is not set.

Because that check fails, `tdx_guest_init()` returns `-ENODEV`, and thus never sets `tdx_service_ready` to true, and no device is ever created, and the attestation part is never initialized. Thus, `/dev/ctlv0` doesn't exist. Attempting to create one and open it will fail. The `ctlv_file_open` and related file operations are never called. The `ctlv` class in sysfs does exist but has no attributes, so nothing to read/write. Netlink is not implemented, and no syscalls are added. The bottom line: these drivers are completely inaccessible.

Could any other driver call `ctlv_create()`? I've grepped across the entire kernel, and no. Nothing else calls it.

Now, let's see if this falls under any negative criteria. All the modified code is structurally unreachable because it depends on Intel TDX guest environment. That environment requires specialized hardware that isn't emulated in standard QEMU. It also needs the TDX feature which is disabled in standard QEMU.

But are CTLV and Attestation core subsystems? No, CTLV is a framework for character devices. This is not a memory management, locking, BPF, networking, VFS, or syscall change, and it's not a driver reachable via a virtual bus. This is a framework that will be used by TDX.

Reachability is the primary gate. If the code is unreachable, it MUST NOT be fuzzed, regardless of logic or assertions. This is a core statement, and it's in capital letters for emphasis.

Can *any* part of the modified code execute in standard environments? `ctlv_module_init` runs basic boilerplate, `attestation_module_init` returns 0, and `attestation_tdx_init_module` does some initial setup but all setup is conditional on being a TDX guest. Since we are not a TDX guest, the subsequent calls to register a client fail, no device is ever created or registered. User space cannot interact with the code at all. `drivers/ctlv/`, `drivers/attestation/`, and `drivers/virt/coco/tdx-guest/` are completely unreachable. Could someone run syzkaller inside an Intel TDX guest? No, the fuzzing target is standard QEMU or GCE VMs. This is a "structurally unreachable hardware" situation.

But what about the future? What if the patch author future-proofed CTLV? Right now, there are *no* other consumers, no other drivers. Let's double-check the Kconfig and Makefiles. The CTLV and Attestation drivers are configured, but everything is only reachable via `/dev/ctlv*`. Everything is unreachable in a standard QEMU or GCE environment.

So, is there any reason `WorthFuzzing` could be true? No. This code is unreachable due to the required hardware.

Thus, WorthFuzzing is false. Reasoning: clear, concise explanation describing why it's structurally unreachable. FocusSymbols and EnableConfigs are empty arrays.

Let's verify. I've re-read the instructions and verified against the code. The patch is unreachable. The reasoning is solid. I'm ready to call `set-results`.



28/2 2026/10/15 19:16 tool set-results
0m Args:
{
  "EnableConfigs": [],
  "FocusSymbols": [],
  "Reasoning": "The patch series introduces the CTLV subsystem (character device TLV UAPI transport), an Attestation subsystem, and an Intel TDX attestation provider. The only provider implemented for CTLV/Attestation that calls ctlv_create() to instantiate character devices (/dev/ctlv*) is the TDX attestation provider. However, the TDX provider depends on the TDX guest driver (drivers/virt/coco/tdx-guest/tdx-guest.c), which strictly requires Intel Trust Domain Extensions hardware support (X86_FEATURE_TDX_GUEST) and exits with -ENODEV in tdx_guest_init() when running in standard virtualized environments (standard QEMU or GCE). Because no TDX hardware is present, tdx_guest_client_attach() is never called, ctlv_create() is never invoked, and no CTLV character devices can ever be created or opened by userspace. Consequently, all newly added CTLV and attestation operational logic is structurally unreachable in standard fuzzing environments.",
  "WorthFuzzing": false
}

Results:
{
  "EnableConfigs": null,
  "FocusSymbols": [],
  "Reasoning": "The patch series introduces the CTLV subsystem (character device TLV UAPI transport), an Attestation subsystem, and an Intel TDX attestation provider. The only provider implemented for CTLV/Attestation that calls ctlv_create() to instantiate character devices (/dev/ctlv*) is the TDX attestation provider. However, the TDX provider depends on the TDX guest driver (drivers/virt/coco/tdx-guest/tdx-guest.c), which strictly requires Intel Trust Domain Extensions hardware support (X86_FEATURE_TDX_GUEST) and exits with -ENODEV in tdx_guest_init() when running in standard virtualized environments (standard QEMU or GCE). Because no TDX hardware is present, tdx_guest_client_attach() is never called, ctlv_create() is never invoked, and no CTLV character devices can ever be created or opened by userspace. Consequently, all newly added CTLV and attestation operational logic is structurally unreachable in standard fuzzing environments.",
  "WorthFuzzing": false
}

29/1 2026/10/15 19:16 action If
0m Args:
{
  "WorthFuzzing": false
}

Results:
null

LLM Calls Summary:
Total Calls Total Tokens Avg Tokens Total Duration (Seconds) Avg Duration (Seconds)
Tool Calls Summary:
Total Calls Total Duration (Seconds) Avg Duration (Seconds)