Documentation/driver-api/media/camera-sensor.rst GitHub 원문 ↗

Linux 6.18.37 · Driver API

Writing camera sensor drivers

V4L2 camera sensor driver의 firmware clock, runtime PM, bridge 주도 streaming, control과 orientation 처리 규칙입니다.

Source pathDocumentation/driver-api/media/camera-sensor.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.

1. 요약·해설

원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.

요약과 해설

camera-sensor.rst:1-158

Camera sensor driver는 firmware가 정한 external·link frequency만 사용하고 `devm_v4l2_sensor_clk_get()`으로 ACPI와 DT 차이를 흡수해야 합니다. Device power는 runtime PM으로 관리하며 stream lifecycle에는 resume-and-get과 put을 짝지어야 합니다.

System suspend의 pipeline stream 조정은 bridge driver 책임입니다. Sensor driver는 streaming state 기반 system PM이나 deprecated `.s_power()`를 구현하지 않고, control callback에서는 transition 이후의 실제 runtime PM state를 확인한 뒤 register에 접근해야 합니다.

2. 영어 원문 전체

번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.

원문 전체 펼치기
1 .. SPDX-License-Identifier: GPL-2.0
2
3 .. _media_writing_camera_sensor_drivers:
4
5 Writing camera sensor drivers
6 =============================
7
8 This document covers the in-kernel APIs only. For the best practices on
9 userspace API implementation in camera sensor drivers, please see
10 :ref:`media_using_camera_sensor_drivers`.
11
12 CSI-2, parallel and BT.656 buses
13 --------------------------------
14
15 Please see :ref:`transmitter-receiver`.
16
17 Handling clocks
18 ---------------
19
20 Camera sensors have an internal clock tree including a PLL and a number of
21 divisors. The clock tree is generally configured by the driver based on a few
22 input parameters that are specific to the hardware: the external clock frequency
23 and the link frequency. The two parameters generally are obtained from system
24 firmware. **No other frequencies should be used in any circumstances.**
25
26 The reason why the clock frequencies are so important is that the clock signals
27 come out of the SoC, and in many cases a specific frequency is designed to be
28 used in the system. Using another frequency may cause harmful effects
29 elsewhere. Therefore only the pre-determined frequencies are configurable by the
30 user.
31
32 The external clock frequency shall be retrieved by obtaining the external clock
33 using the ``devm_v4l2_sensor_clk_get()`` helper function, and then getting its
34 frequency with ``clk_get_rate()``. Usage of the helper function guarantees
35 correct behaviour regardless of whether the sensor is integrated in a DT-based
36 or ACPI-based system.
37
38 ACPI
39 ~~~~
40
41 ACPI-based systems typically don't register the sensor external clock with the
42 kernel, but specify the external clock frequency in the ``clock-frequency``
43 _DSD property. The ``devm_v4l2_sensor_clk_get()`` helper creates and returns a
44 fixed clock set at that rate.
45
46 Devicetree
47 ~~~~~~~~~~
48
49 Devicetree-based systems declare the sensor external clock in the device tree
50 and reference it from the sensor node. The preferred way to select the external
51 clock frequency is to use the ``assigned-clocks``, ``assigned-clock-parents``
52 and ``assigned-clock-rates`` properties in the sensor node to set the clock
53 rate. See the `clock device tree bindings
54 <https://github.com/devicetree-org/dt-schema/blob/main/dtschema/schemas/clock/clock.yaml>`_
55 for more information. The ``devm_v4l2_sensor_clk_get()`` helper retrieves and
56 returns that clock.
57
58 This approach has the drawback that there's no guarantee that the frequency
59 hasn't been modified directly or indirectly by another driver, or supported by
60 the board's clock tree to begin with. Changes to the Common Clock Framework API
61 are required to ensure reliability.
62
63 Power management
64 ----------------
65
66 Camera sensors are used in conjunction with other devices to form a camera
67 pipeline. They must obey the rules listed herein to ensure coherent power
68 management over the pipeline.
69
70 Camera sensor drivers are responsible for controlling the power state of the
71 device they otherwise control as well. They shall use runtime PM to manage
72 power states. Runtime PM shall be enabled at probe time and disabled at remove
73 time. Drivers should enable runtime PM autosuspend. Also see
74 :ref:`async sub-device registration <media-registering-async-subdevs>`.
75
76 The runtime PM handlers shall handle clocks, regulators, GPIOs, and other
77 system resources required to power the sensor up and down. For drivers that
78 don't use any of those resources (such as drivers that support ACPI systems
79 only), the runtime PM handlers may be left unimplemented.
80
81 In general, the device shall be powered on at least when its registers are
82 being accessed and when it is streaming. Drivers should use
83 ``pm_runtime_resume_and_get()`` when starting streaming and
84 ``pm_runtime_put()`` or ``pm_runtime_put_autosuspend()`` when stopping
85 streaming. They may power the device up at probe time (for example to read
86 identification registers), but should not keep it powered unconditionally after
87 probe.
88
89 At system suspend time, the whole camera pipeline must stop streaming, and
90 restart when the system is resumed. This requires coordination between the
91 camera sensor and the rest of the camera pipeline. Bridge drivers are
92 responsible for this coordination, and instruct camera sensors to stop and
93 restart streaming by calling the appropriate subdev operations
94 (``.enable_streams()`` or ``.disable_streams()``). Camera sensor drivers shall
95 therefore **not** keep track of the streaming state to stop streaming in the PM
96 suspend handler and restart it in the resume handler. Drivers should in general
97 not implement the system PM handlers.
98
99 Camera sensor drivers shall **not** implement the subdev ``.s_power()``
100 operation, as it is deprecated. While this operation is implemented in some
101 existing drivers as they predate the deprecation, new drivers shall use runtime
102 PM instead. If you feel you need to begin calling ``.s_power()`` from an ISP or
103 a bridge driver, instead add runtime PM support to the sensor driver you are
104 using and drop its ``.s_power()`` handler.
105
106 Please also see :ref:`examples <media-camera-sensor-examples>`.
107
108 Control framework
109 ~~~~~~~~~~~~~~~~~
110
111 ``v4l2_ctrl_handler_setup()`` function may not be used in the device's runtime
112 PM ``runtime_resume`` callback, as it has no way to figure out the power state
113 of the device. This is because the power state of the device is only changed
114 after the power state transition has taken place. The ``s_ctrl`` callback can be
115 used to obtain device's power state after the power state transition:
116
117 .. c:function:: int pm_runtime_get_if_in_use(struct device *dev);
118
119 The function returns a non-zero value if it succeeded getting the power count or
120 runtime PM was disabled, in either of which cases the driver may proceed to
121 access the device.
122
123 Rotation, orientation and flipping
124 ----------------------------------
125
126 Use ``v4l2_fwnode_device_parse()`` to obtain rotation and orientation
127 information from system firmware and ``v4l2_ctrl_new_fwnode_properties()`` to
128 register the appropriate controls.
129
130 .. _media-camera-sensor-examples:
131
132 Example drivers
133 ---------------
134
135 Features implemented by sensor drivers vary, and depending on the set of
136 supported features and other qualities, particular sensor drivers better serve
137 the purpose of an example. The following drivers are known to be good examples:
138
139 .. flat-table:: Example sensor drivers
140 :header-rows: 0
141 :widths: 1 1 1 2
142
143 * - Driver name
144 - File(s)
145 - Driver type
146 - Example topic
147 * - CCS
148 - ``drivers/media/i2c/ccs/``
149 - Freely configurable
150 - Power management (ACPI and DT), UAPI
151 * - imx219
152 - ``drivers/media/i2c/imx219.c``
153 - Register list based
154 - Power management (DT), UAPI, mode selection
155 * - imx319
156 - ``drivers/media/i2c/imx319.c``
157 - Register list based
158 - Power management (ACPI and DT)
159

3. 한국어 전문 번역

영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.

Camera sensor driver 작성 범위

1-11

이 문서는 GPL-2.0 SPDX license를 사용하며 `media_writing_camera_sensor_drivers` reference target을 정의합니다.

설명 범위는 in-kernel API입니다. Camera sensor driver의 userspace API 구현 best practice는 `media_using_camera_sensor_drivers` 문서를 참조합니다.

Camera sensor 문서 경계
영역참조
In-kernel sensor API현재 문서
Userspace API best practicemedia_using_camera_sensor_drivers
LicenseGPL-2.0

Kernel driver 구현과 userspace API 지침을 분리합니다.

CSI-2, parallel, BT.656 bus

12-16

CSI-2, parallel, BT.656 bus에 관한 지침은 `transmitter-receiver` 문서를 참조합니다.

Sensor bus 참조
Camera sensor driverCSI-2 / parallel / BT.656transmitter-receiver 문서Bus transmitter·receiver API 적용

세 bus type 모두 transmitter-receiver 지침으로 연결됩니다.

Clock 처리 원칙

17-37

Camera sensor에는 PLL과 여러 divisor를 포함한 internal clock tree가 있습니다. Driver는 hardware별 input parameter인 external clock frequency와 link frequency를 바탕으로 이 tree를 설정하며, 두 값은 보통 system firmware에서 얻습니다.

어떤 상황에서도 이 둘 이외의 frequency를 사용해서는 안 됩니다. Clock signal은 SoC 밖으로 나오고 system이 특정 frequency를 전제로 설계되는 경우가 많아 다른 값을 쓰면 다른 부분에 해로운 영향을 줄 수 있습니다. 따라서 user가 설정할 수 있는 값도 미리 정해진 frequency로 제한합니다.

External clock은 `devm_v4l2_sensor_clk_get()` helper로 얻고 `clk_get_rate()`로 frequency를 읽어야 합니다. 이 helper를 사용하면 sensor가 DT 기반 system에 있든 ACPI 기반 system에 있든 올바르게 동작합니다.

Sensor clock 설정
System firmwareExternal clock frequencyLink frequencyDriver가 PLL·divisor 계산Sensor internal clock tree 설정

Firmware가 정한 두 parameter만으로 internal PLL·divisor를 구성합니다.

Clock 안전 규칙
항목규칙
External clock 획득devm_v4l2_sensor_clk_get()
Rate 조회clk_get_rate()
Link frequencySystem firmware 값 사용
임의 frequency어떤 경우에도 사용 금지
이유SoC·board의 다른 clock user에 harmful effect 가능

허용되는 source와 금지되는 선택입니다.

ACPI system의 external clock

38-45

ACPI 기반 system은 보통 sensor external clock을 kernel에 등록하지 않고 `_DSD`의 `clock-frequency` property로 frequency를 지정합니다. `devm_v4l2_sensor_clk_get()`은 그 rate로 설정한 fixed clock을 만들어 반환합니다.

ACPI clock 획득
ACPI _DSDclock-frequency propertydevm_v4l2_sensor_clk_get()해당 rate의 fixed clock 생성Sensor driver에 반환

등록된 hardware clock 대신 _DSD frequency로 fixed clock을 구성합니다.

Devicetree system의 external clock

46-62

Devicetree 기반 system은 sensor external clock을 device tree에 선언하고 sensor node에서 reference합니다. 권장 방식은 sensor node의 `assigned-clocks`, `assigned-clock-parents`, `assigned-clock-rates` property로 clock rate를 선택하는 것입니다.

자세한 내용은 `clock device tree bindings <https://github.com/devicetree-org/dt-schema/blob/main/dtschema/schemas/clock/clock.yaml>`를 참조합니다. `devm_v4l2_sensor_clk_get()`은 이 clock을 가져와 반환합니다.

이 방식에는 다른 driver가 frequency를 직접 또는 간접적으로 바꾸지 않았다는 보장이 없고, board clock tree가 애초에 해당 frequency를 지원하는지도 보장하지 못한다는 단점이 있습니다. 신뢰성을 보장하려면 Common Clock Framework API 변경이 필요합니다.

Devicetree clock 경로
DT에 external clock 선언Sensor node가 clock referenceassigned-clocks / parents / ratesdevm_v4l2_sensor_clk_get()Sensor driver에 clock 반환CCF 변경 없이는 다른 driver의 rate 변경 위험 존재

Sensor node의 assigned-clock property가 external clock rate를 정합니다.

Camera pipeline의 runtime PM

63-80

Camera sensor는 다른 device와 함께 camera pipeline을 구성하므로 pipeline 전체에서 일관된 power management를 보장하기 위해 이 문서의 규칙을 따라야 합니다.

Sensor driver는 자신이 제어하는 device의 power state도 책임집니다. Runtime PM으로 power state를 관리하고 probe 때 enable, remove 때 disable해야 하며 runtime PM autosuspend 사용을 권장합니다. 비동기 sub-device 등록은 `media-registering-async-subdevs`를 참조합니다.

Runtime PM handler는 sensor power on/off에 필요한 clock, regulator, GPIO와 기타 system resource를 처리해야 합니다. ACPI-only driver처럼 이런 resource를 전혀 사용하지 않는다면 handler를 구현하지 않아도 됩니다.

Sensor runtime PM lifecycle
ProbeRuntime PM enableAutosuspend enable 권장Streaming·register access 때 resumeIdle 때 put/autosuspendRemoveRuntime PM disable

Driver lifetime과 autosuspend 경계를 정리했습니다.

Register access와 streaming power coordination

81-107

일반적으로 register를 access할 때와 streaming 중에는 device가 최소한 power-on 상태여야 합니다. Streaming 시작에는 `pm_runtime_resume_and_get()`, 중지에는 `pm_runtime_put()` 또는 `pm_runtime_put_autosuspend()`를 사용합니다.

Probe 때 identification register를 읽기 위해 device를 켤 수는 있지만 probe 이후까지 무조건 켜 둬서는 안 됩니다.

System suspend 때는 camera pipeline 전체가 streaming을 멈추고 resume 때 다시 시작해야 합니다. Sensor와 나머지 pipeline의 coordination은 bridge driver 책임입니다. Bridge는 `.enable_streams()` 또는 `.disable_streams()` subdev operation으로 sensor에 stop·restart를 지시합니다.

따라서 sensor driver는 PM suspend handler에서 stream을 멈추고 resume handler에서 다시 시작하기 위해 streaming state를 직접 추적해서는 안 됩니다. 일반적으로 system PM handler를 구현하지 않아야 합니다.

새 sensor driver는 deprecated된 subdev `.s_power()` operation을 구현해서는 안 되고 runtime PM을 사용해야 합니다. ISP나 bridge에서 `.s_power()` 호출이 필요하다고 느껴진다면 sensor driver에 runtime PM을 추가하고 기존 `.s_power()` handler를 제거해야 합니다. 관련 예시는 `media-camera-sensor-examples`를 참조합니다.

Streaming power sequence
Bridge가 stream 시작 요청Sensor: pm_runtime_resume_and_get().enable_streams()StreamingBridge가 .disable_streams() 호출Sensor: pm_runtime_put() 또는 put_autosuspend()

Stream operation과 runtime PM reference가 짝을 이룹니다.

Power management 책임 분리
주체해야 할 일하지 말아야 할 일
Bridge driverSystem suspend/resume 때 pipeline stream 조정Sensor power state 직접 구현
Sensor driverRuntime PM으로 resource와 device power 관리Streaming state로 system PM 재시작
새 sensor driverresume_and_get / put 사용deprecated .s_power() 구현

Bridge와 sensor driver가 맡아야 할 역할입니다.

Control framework와 runtime_resume 제한

108-122

`v4l2_ctrl_handler_setup()`은 device runtime PM의 `runtime_resume` callback에서 사용하면 안 됩니다. Power state는 transition이 끝난 뒤에야 바뀌므로 이 function은 device의 현재 power state를 알아낼 방법이 없습니다.

Power transition 뒤에는 `s_ctrl` callback에서 다음 function으로 device power state를 확인할 수 있습니다.

.. c:function:: int pm_runtime_get_if_in_use(struct device *dev);

`pm_runtime_get_if_in_use()`가 power count 획득에 성공했거나 runtime PM이 disabled이면 non-zero를 반환합니다. 두 경우 모두 driver는 device access를 진행할 수 있습니다.

Control callback의 safe register access
Control updates_ctrl callbackpm_runtime_get_if_in_use(dev)Non-zero?예: device register access아니오: powered-off이므로 access 생략획득한 PM reference 반환

Power transition 이후 s_ctrl에서만 in-use 상태를 확인합니다.

Rotation, orientation, flipping

123-131

System firmware에서 rotation과 orientation 정보를 얻을 때는 `v4l2_fwnode_device_parse()`를 사용합니다. 대응 control을 등록할 때는 `v4l2_ctrl_new_fwnode_properties()`를 사용합니다.

이후 example section이 참조할 `media-camera-sensor-examples` target을 정의합니다.

Firmware orientation control 등록
System firmware의 rotation·orientationv4l2_fwnode_device_parse()Parsed fwnode propertiesv4l2_ctrl_new_fwnode_properties()Rotation·orientation·flip control 등록

Firmware property를 V4L2 control로 변환합니다.

Example sensor drivers

132-158

Sensor driver마다 구현 feature와 품질이 달라 example로 적합한 주제도 다릅니다. 문서가 좋은 예시로 제시하는 driver는 CCS, imx219, imx319입니다.

CCS는 `drivers/media/i2c/ccs/`의 freely configurable driver이며 ACPI·DT power management와 UAPI 예시입니다. imx219는 `drivers/media/i2c/imx219.c`의 register-list 기반 driver로 DT power management, UAPI, mode selection을 보여 줍니다. imx319는 `drivers/media/i2c/imx319.c`의 register-list 기반 driver로 ACPI·DT power management 예시입니다.

.. flat-table:: Example sensor drivers
    :header-rows: 0
    :widths:      1 1 1 2

    * - Driver name
      - File(s)
      - Driver type
      - Example topic
    * - CCS
      - ``drivers/media/i2c/ccs/``
      - Freely configurable
      - Power management (ACPI and DT), UAPI
    * - imx219
      - ``drivers/media/i2c/imx219.c``
      - Register list based
      - Power management (DT), UAPI, mode selection
    * - imx319
      - ``drivers/media/i2c/imx319.c``
      - Register list based
      - Power management (ACPI and DT)
Example camera sensor driver
DriverSource pathTypeExample topic
CCSdrivers/media/i2c/ccs/Freely configurablePower management (ACPI and DT), UAPI
imx219drivers/media/i2c/imx219.cRegister list basedPower management (DT), UAPI, mode selection
imx319drivers/media/i2c/imx319.cRegister list basedPower management (ACPI and DT)

원문의 flat-table을 검색 가능한 구조로 다시 구성했습니다.