使用 json-schema 编写 Devicetree 绑定

Devicetree 绑定是使用 json-schema 词汇表编写的。Schema 文件是用 YAML 的 JSON 兼容子集编写的。之所以使用 YAML 而不是 JSON,是因为 YAML 被认为更具可读性,并且具有一些优点,例如允许注释(以 ‘#’ 为前缀)。

另请参见 带注释的 Schema 示例

Schema 内容

每个 schema 文档都是一个结构化的 json-schema,由一组顶层属性定义。通常,每个文件定义一个绑定。所使用的顶层 json-schema 属性包括

$id

一个 json-schema 唯一标识符字符串。该字符串必须是通常包含绑定文件名和路径的有效 URI。对于 DT schema,它必须以 “http://devicetree.org/schemas/” 开头。该 URL 用于构建对 schema 的 “$ref” 属性中指定的其他文件的引用。带有前导 ‘/’ 的 $ref 值将在其前面加上主机名。仅带有相对路径或文件名的 $ref 值将在其前面加上当前 schema 文件的 ‘$id’ 值的主机名和路径组件。即使对于本地文件,也会使用 URL,但在这些位置实际上可能没有文件存在。

$schema

指示该 schema 文件遵循的元架构(meta-schema)。

title

对绑定 schema 中描述的硬件的一行描述。

maintainers

一个 DT 特定的属性。包含此绑定维护者的电子邮件地址列表。

描述

可选。包含有关此硬件的任何详细信息的多行文本块。它应包含诸如块或设备的功能、设备符合的标准以及指向获取更多信息的数据手册的链接等内容。

YAML 格式有几个用于定义文本块格式的选项。这些选项由键后面的指示符字符控制(例如 “description: |”)。应该使用块所需的最小格式。格式控制不仅会影响 YAML 是否能被正确解析,而且在将文本块渲染为其他形式时也很重要。选项如下。

没有任何指示符时的默认值是流式(flowed)、纯标量(plain scalar)样式,其中会剥离单行换行符和前导空白字符。段落由空行(即双换行符)分隔。此样式中不能包含 “: ”,否则会被解释为键。任何 “ #” 序列都将被解释为注释。对字符还有其他限制。大多数限制是关于第一个字符可以是什么。

第二种样式是折叠式(folded),由 “>” 字符指示。除了在双换行符处保持换行外,折叠样式还保持超出第一行缩进的前导空白。缩进行的换行符也会被保持。

第三种样式是原样式(literal),由 “|” 字符指示。原样式保持所有换行符和空白字符(超出第一行缩进的部分)。

以上并非对 YAML 文本块的完整描述。有关多行 YAML 文本块的更多详细信息,可以在线查阅

https://yaml-multiline.info/

https://www.yaml.info/learn/quote.html

select

可选。用于匹配节点以应用 schema 的 json-schema。默认情况下,如果没有 ‘select’,节点将根据其可能兼容的字符串值(compatible-string)或节点名称进行匹配。大多数 bindings 应该不需要 select。

allOf

可选。要包含的其他 schema 的列表。这用于包含此绑定所遵循的其他 schema。这可能是针对特定类别设备(例如 I2C 或 SPI 控制器)的 schema。

properties

一组定义绑定所有 DT 属性的子 schema。具体的 schema 语法取决于属性是已知的、通用属性(例如 ‘interrupts’)还是绑定/供应商特定属性。

属性还可以定义一个子 DT 节点,其下定义了子属性。

有关属性部分的更多详细信息,请参阅“属性 Schema”部分。

patternProperties

可选。类似于 ‘properties’,但名称是正则表达式。

required

来自 ‘properties’ 部分且必须始终存在的 DT 属性列表。

additionalProperties / unevaluatedProperties

控制 schema 如何验证未被此 schema 的 ‘properties’ 或 ‘patternProperties’ 匹配的属性的关键字。每个 schema 的顶层部分应该有且仅有其中一个关键字,即 additionalProperties 或 unevaluatedProperties。嵌套节点(即作为对象的属性)也应该有一个。

  • additionalProperties: false

    最常见的情况,即未引用其他附加 schema,或者此绑定允许来自其他引用的 schema 的属性子集。

  • unevaluatedProperties: false

    当此绑定引用了其所有属性都应被允许的其他 schema 时使用。

  • additionalProperties: true
    • 顶层部分:罕见情况,用于实现一组通用属性的 schema。此类 schema 应该被其他 schema 引用,然后其他 schema 使用 ‘unevaluatedProperties: false’。通常是总线或通用部分 schema。

    • 嵌套节点:当仅列出嵌套节点的预期 compatible,并且存在另一个与该 compatible 匹配且以上述两种情况之一(‘false’)结尾的 schema 时。

examples

可选。一个或多个仅实现此绑定的 DTS 片段的列表。示例不应包含不相关的设备节点,例如提供者绑定中的消费端(consumer)节点、由 phandle 引用的其他节点。注意:YAML 不允许前导制表符(tab),因此必须改用空格。

除非另有说明,上述所有 schema 属性都是必需的。

属性 Schema

schema 的 ‘properties’ 部分包含绑定的所有 DT 属性。每个属性都包含一组使用该属性的 json-schema 词汇表的约束。属性 schema 用于验证 DT 文件。

对于通用属性,只需定义通用绑定 schema 未涵盖的其他约束,例如多少个值是有效的,或者哪些可能的值是有效的。

供应商特定属性通常需要更详细的 schema。除布尔属性外,它们应引用 schemas/types.yaml 中的类型。始终需要 “description” 属性。

Devicetree schema 与 dtc 生成的 YAML 编码的 DT 数据并不完全匹配。它们被简化以使其更紧凑并避免大量样板代码。工具会处理 schema 文件以生成用于验证的最终 schema。目前工具有 2 种转换操作。

json-schema 中数组的默认值是大小可变的,并且允许比显式定义的更多的条目。这可以通过定义 ‘minItems’、‘maxItems’ 和 ‘additionalItems’ 来限制。然而,对于 DeviceTree Schema,在大多数情况下需要固定大小,因此这些属性是根据 ‘items’ 列表中的条目数添加的。

即使只有一个值存在,YAML Devicetree 格式也会使所有字符串值成为数组、标量值成为矩阵(为了定义分组)。schema 中的单个条目会被修正以匹配此编码。

当绑定覆盖在某些属性上有所不同的多个相似设备时,应为每个设备约束这些属性。这通常意味着

  • 在顶层 ‘properties’ 中定义具有最广泛约束的属性。

  • 在 ‘if:then:’ 块中,进一步收窄这些属性的约束。

  • 不要在 ‘if:then:’ 块中定义属性(注意 ‘additionalItems’ 也不允许这样做)。

编码风格

使用 YAML 编码风格(两空格缩进)。对于 schema 中的 DTS 示例,首选四空格缩进。

按照 Devicetree 源码 (DTS) 编码风格 中的风格,以相同的顺序将条目放置在 ‘properties’ 和 ‘required’ 部分中。

测试

依赖项

必须安装 DT schema 项目,以便验证 DT schema 绑定文档并使用 DT schema 验证 DTS 文件。可以使用 pip 安装 DT schema 项目

pip3 install dtschema

请注意,安装 ‘dtschema’ 需要先安装 ‘swig’ 和 Python 开发文件。在 Debian/Ubuntu 系统上

apt install swig python3-dev

将安装几个可执行文件(dt-doc-validate, dt-mk-schema, dt-validate)。确保它们在你的 PATH 中(默认情况下为 ~/.local/bin)。

还建议安装 yamllint(如果存在,dtschema 会使用它)。

运行检查

必须使用元架构(meta-schema,即 schema 的 schema)验证 DT schema 绑定文档,以确保它们既是有效的 json-schema 又是有效的绑定 schema。可以使用 dt_binding_check 目标验证所有 DT 绑定文档

make dt_binding_check

或者验证单个 schema 及其示例

make sram/sram.yaml

为了对 DT 源文件执行验证,请使用 dtbs_check 目标

make dtbs_check

请注意,dtbs_check 将跳过任何带有错误的绑定 schema 文件。必须使用 dt_binding_check 来获取绑定 schema 文件中的所有验证错误。

可以在单个命令中同时运行这两者

make dt_binding_check dtbs_check

也可以通过将 DT_SCHEMA_FILES 变量设置为 1 个或多个特定的 schema 文件或模式(固定字符串的部分匹配),将上述命令的运行与匹配的 schema 文件的子集结合起来。每个文件或模式应用 ‘:’ 分隔。

make dt_binding_check DT_SCHEMA_FILES=trivial-devices.yaml
make dt_binding_check DT_SCHEMA_FILES=trivial-devices.yaml:rtc.yaml
make dt_binding_check DT_SCHEMA_FILES=/gpio/
make dtbs_check DT_SCHEMA_FILES=trivial-devices.yaml

json-schema 资源

JSON-Schema 规范

使用 JSON Schema 一书

带注释的 Schema 示例

也可以作为单独的文件获取:example-schema.yaml

# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)
# Copyright 2018 Linaro Ltd.
%YAML 1.2
---
# All the top-level keys are standard json-schema keywords except for
# 'maintainers' and 'select'

# $id is a unique identifier based on the filename. There may or may not be a
# file present at the URL.
$id: http://devicetree.org/schemas/example-schema.yaml#
# $schema is the meta-schema this schema should be validated with.
$schema: http://devicetree.org/meta-schemas/core.yaml#

title: An Example Device

maintainers:
  - Rob Herring <robh@kernel.org>

description: |
  A more detailed multi-line description of the binding.

  Details about the hardware device and any links to datasheets can go here.

  Literal blocks are marked with the '|' at the beginning. The end is marked by
  indentation less than the first line of the literal block. Lines also cannot
  begin with a tab character.

select: false
  # 'select' is a schema applied to a DT node to determine if this binding
  # schema should be applied to the node. It is optional and by default the
  # possible compatible strings are extracted and used to match.

  # In this case, a 'false' schema will never match.

properties:
  # A dictionary of DT properties for this binding schema
  compatible:
    # More complicated schema can use oneOf (XOR), anyOf (OR), or allOf (AND)
    # to handle different conditions.
    # In this case, it's needed to handle a variable number of values as there
    # isn't another way to express a constraint of the last string value.
    # The boolean schema must be a list of schemas.
    oneOf:
      - items:
          # items is a list of possible values for the property. The number of
          # values is determined by the number of elements in the list.
          # Order in lists is significant, order in dicts is not
          # Must be one of the 1st enums followed by the 2nd enum
          #
          # Each element in items should be 'enum' or 'const'
          - enum:
              - vendor,soc4-ip
              - vendor,soc3-ip
              - vendor,soc2-ip
          - const: vendor,soc1-ip
        # additionalItems being false is implied
        # minItems/maxItems equal to 2 is implied
      - items:
          # 'const' is just a special case of an enum with a single possible value
          - const: vendor,soc1-ip

  reg:
    # The core schema already checks that reg values are numbers, so device
    # specific schema don't need to do those checks.
    # The description of each element defines the order and implicitly defines
    # the number of reg entries.
    items:
      - description: core registers
      - description: aux registers
    # minItems/maxItems equal to 2 is implied

  reg-names:
    # The core schema enforces this (*-names) is a string array
    items:
      - const: core
      - const: aux

  clocks:
    # Cases that have only a single entry just need to express that with maxItems
    maxItems: 1
    description: bus clock. A description is only needed for a single item if
      there's something unique to add.
      The items should have a fixed order, so pattern matching names are
      discouraged.

  clock-names:
    # For single-entry lists in clocks, resets etc., the xxx-names often do not
    # bring any value, especially if they copy the IP block name.  In such case
    # just skip the xxx-names.
    items:
      - const: bus

  interrupts:
    # Either 1 or 2 interrupts can be present
    minItems: 1
    items:
      - description: tx or combined interrupt
      - description: rx interrupt
    description:
      A variable number of interrupts warrants a description of what conditions
      affect the number of interrupts. Otherwise, descriptions on standard
      properties are not necessary.
      The items should have a fixed order, so pattern matching names are
      discouraged.

  interrupt-names:
    # minItems must be specified here because the default would be 2
    minItems: 1
    items:
      - const: tx irq
      - const: rx irq

  # Property names starting with '#' must be quoted
  '#interrupt-cells':
    # A simple case where the value must always be '2'.
    # The core schema handles that this must be a single integer.
    const: 2

  interrupt-controller: true
    # The core checks this is a boolean, so just have to list it here to be
    # valid for this binding.

  clock-frequency:
    # The type is set in the core schema. Per-device schema only need to set
    # constraints on the possible values.
    minimum: 100
    maximum: 400000
    # The value that should be used if the property is not present
    default: 200

  foo-gpios:
    maxItems: 1
    description: A connection of the 'foo' gpio line.

  # *-supply is always a single phandle, so nothing more to define.
  foo-supply: true

  # Vendor-specific properties
  #
  # Vendor-specific properties have slightly different schema requirements than
  # common properties. They must have at least a type definition and
  # 'description'.
  vendor,int-property:
    description: Vendor-specific properties must have a description
    $ref: /schemas/types.yaml#/definitions/uint32
    enum: [2, 4, 6, 8, 10]

  vendor,bool-property:
    description: Vendor-specific properties must have a description. Boolean
      properties are one case where the json-schema 'type' keyword can be used
      directly.
    type: boolean

  vendor,string-array-property:
    description: Vendor-specific properties should reference a type in the
      core schema.
    $ref: /schemas/types.yaml#/definitions/string-array
    items:
      - enum: [foo, bar]
      - enum: [baz, boo]

  vendor,property-in-standard-units-microvolt:
    description: Vendor-specific properties having a standard unit suffix
      don't need a type.
    enum: [ 100, 200, 300 ]

  vendor,int-array-variable-length-and-constrained-values:
    description: Array might define what type of elements might be used (e.g.
      their range).
    $ref: /schemas/types.yaml#/definitions/uint32-array
    minItems: 2
    maxItems: 3
    items:
      minimum: 0
      maximum: 8

  child-node:
    description: Child nodes are just another property from a json-schema
      perspective.
    type: object  # DT nodes are json objects
    # Child nodes also need additionalProperties or unevaluatedProperties, where
    # 'false' should be used in most cases (see 'child-node-with-own-schema'
    # below).
    additionalProperties: false
    properties:
      vendor,a-child-node-property:
        description: Child node properties have all the same schema
          requirements.
        type: boolean

    required:
      - vendor,a-child-node-property

  child-node-with-own-schema:
    description: |
      Child node with their own compatible and device schema which ends in
      'additionalProperties: false' or 'unevaluatedProperties: false' can
      mention only the compatible and use here 'additionalProperties: true'.
    type: object
    additionalProperties: true
    properties:
      compatible:
        const: vendor,sub-device

# Describe the relationship between different properties
dependencies:
  # 'vendor,bool-property' is only allowed when 'vendor,string-array-property'
  # is present
  vendor,bool-property: [ 'vendor,string-array-property' ]
  # Expressing 2 properties in both orders means all of the set of properties
  # must be present or none of them.
  vendor,string-array-property: [ 'vendor,bool-property' ]

required:
  - compatible
  - reg
  - interrupts
  - interrupt-controller

# if/then schema can be used to handle conditions on a property affecting
# another property. A typical case is a specific 'compatible' value changes the
# constraints on other properties.
#
# For multiple 'if' schema, group them under an 'allOf'.
#
# If the conditionals become too unwieldy, then it may be better to just split
# the binding into separate schema documents.
allOf:
  - if:
      properties:
        compatible:
          contains:
            const: vendor,soc2-ip
    then:
      required:
        - foo-supply
    else:
      # If otherwise the property is not allowed:
      properties:
        foo-supply: false
  # Altering schema depending on presence of properties is usually done by
  # dependencies (see above), however some adjustments might require if:
  - if:
      required:
        - vendor,bool-property
    then:
      properties:
        vendor,int-property:
          enum: [2, 4, 6]

# Ideally, the schema should have this line otherwise any other properties
# present are allowed. There's a few common properties such as 'status' and
# 'pinctrl-*' which are added automatically by the tooling.
#
# This can't be used in cases where another schema is referenced
# (i.e. allOf: [{$ref: ...}]).
# If and only if another schema is referenced and arbitrary children nodes can
# appear, "unevaluatedProperties: false" could be used.  A typical example is
# an I2C controller where no name pattern matching for children can be added.
additionalProperties: false

examples:
  # Examples are now compiled with dtc and validated against the schemas
  #
  # Examples have a default #address-cells and #size-cells value of 1. This can
  # be overridden or an appropriate parent bus node should be shown (such as on
  # i2c buses).
  #
  # Any includes used have to be explicitly included. Use 4-space indentation.
  - |
    node@1000 {
        compatible = "vendor,soc4-ip", "vendor,soc1-ip";
        reg = <0x1000 0x80>,
              <0x3000 0x80>;
        reg-names = "core", "aux";
        interrupts = <10>;
        interrupt-controller;
        #interrupt-cells = <2>;
    };