Documentation/driver-api/thermal/sysfs-api.rst GitHub 원문 ↗

Linux 6.18.37 · Driver API

Generic Thermal Sysfs Driver

Thermal zone·DT sensor·cooling device 등록 API, sysfs와 hwmon tree, exported symbol 및 critical event 처리를 설명하는 한국어 전문 번역입니다.

Source pathDocumentation/driver-api/thermal/sysfs-api.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

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

1. 요약·해설

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

요약·해설

sysfs-api.rst:1-433

Generic thermal sysfs는 sensor와 cooling device를 thermal core에 등록하고 `/sys/class/thermal` 및 hwmon에 상태와 control을 노출합니다. 문서는 lifecycle API, callback, zone·cooling binding, 실제 ACPI tree와 critical shutdown 순서를 함께 설명합니다.

문서 구성
원문 줄핵심 내용
1-30Generic thermal sysfs 목적
31-210Thermal zone과 DT sensor lifecycle API
211-268Cooling device와 zone parameter
269-344Thermal·cooling·hwmon sysfs tree
345-396ACPI thermal zone 구현 예
397-433Exported symbol과 critical event

2. 영어 원문 전체

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

원문 전체 펼치기
1 ===================================
2 Generic Thermal Sysfs driver How To
3 ===================================
4
5 Written by Sujith Thomas <sujith.thomas@intel.com>, Zhang Rui <rui.zhang@intel.com>
6
7 Copyright (c) 2008 Intel Corporation
8
9
10 0. Introduction
11 ===============
12
13 The generic thermal sysfs provides a set of interfaces for thermal zone
14 devices (sensors) and thermal cooling devices (fan, processor...) to register
15 with the thermal management solution and to be a part of it.
16
17 This how-to focuses on enabling new thermal zone and cooling devices to
18 participate in thermal management.
19 This solution is platform independent and any type of thermal zone devices
20 and cooling devices should be able to make use of the infrastructure.
21
22 The main task of the thermal sysfs driver is to expose thermal zone attributes
23 as well as cooling device attributes to the user space.
24 An intelligent thermal management application can make decisions based on
25 inputs from thermal zone attributes (the current temperature and trip point
26 temperature) and throttle appropriate devices.
27
28 - `[0-*]` denotes any positive number starting from 0
29 - `[1-*]` denotes any positive number starting from 1
30
31 1. thermal sysfs driver interface functions
32 ===========================================
33
34 1.1 thermal zone device interface
35 ---------------------------------
36
37 ::
38
39 struct thermal_zone_device *
40 thermal_zone_device_register_with_trips(const char *type,
41 const struct thermal_trip *trips,
42 int num_trips, void *devdata,
43 const struct thermal_zone_device_ops *ops,
44 const struct thermal_zone_params *tzp,
45 unsigned int passive_delay,
46 unsigned int polling_delay)
47
48 This interface function adds a new thermal zone device (sensor) to the
49 /sys/class/thermal folder as `thermal_zone[0-*]`. It tries to bind all the
50 thermal cooling devices registered to it at the same time.
51
52 type:
53 the thermal zone type.
54 trips:
55 the table of trip points for this thermal zone.
56 devdata:
57 device private data
58 ops:
59 thermal zone device call-backs.
60
61 .should_bind:
62 check whether or not a given cooling device should be bound to
63 a given trip point in this thermal zone.
64 .get_temp:
65 get the current temperature of the thermal zone.
66 .set_trips:
67 set the trip points window. Whenever the current temperature
68 is updated, the trip points immediately below and above the
69 current temperature are found.
70 .change_mode:
71 change the mode (enabled/disabled) of the thermal zone.
72 .set_trip_temp:
73 set the temperature of a given trip point.
74 .get_crit_temp:
75 get the critical temperature for this thermal zone.
76 .set_emul_temp:
77 set the emulation temperature which helps in debugging
78 different threshold temperature points.
79 .get_trend:
80 get the trend of most recent zone temperature changes.
81 .hot:
82 hot trip point crossing handler.
83 .critical:
84 critical trip point crossing handler.
85 tzp:
86 thermal zone platform parameters.
87 passive_delay:
88 number of milliseconds to wait between polls when performing passive
89 cooling.
90 polling_delay:
91 number of milliseconds to wait between polls when checking
92 whether trip points have been crossed (0 for interrupt driven systems).
93
94 ::
95
96 void thermal_zone_device_unregister(struct thermal_zone_device *tz)
97
98 This interface function removes the thermal zone device.
99 It deletes the corresponding entry from /sys/class/thermal folder and
100 unbinds all the thermal cooling devices it uses.
101
102 ::
103
104 struct thermal_zone_device
105 *thermal_zone_of_sensor_register(struct device *dev, int sensor_id,
106 void *data,
107 const struct thermal_zone_of_device_ops *ops)
108
109 This interface adds a new sensor to a DT thermal zone.
110 This function will search the list of thermal zones described in
111 device tree and look for the zone that refer to the sensor device
112 pointed by dev->of_node as temperature providers. For the zone
113 pointing to the sensor node, the sensor will be added to the DT
114 thermal zone device.
115
116 The parameters for this interface are:
117
118 dev:
119 Device node of sensor containing valid node pointer in
120 dev->of_node.
121 sensor_id:
122 a sensor identifier, in case the sensor IP has more
123 than one sensors
124 data:
125 a private pointer (owned by the caller) that will be
126 passed back, when a temperature reading is needed.
127 ops:
128 `struct thermal_zone_of_device_ops *`.
129
130 ============== =======================================
131 get_temp a pointer to a function that reads the
132 sensor temperature. This is mandatory
133 callback provided by sensor driver.
134 set_trips a pointer to a function that sets a
135 temperature window. When this window is
136 left the driver must inform the thermal
137 core via thermal_zone_device_update.
138 get_trend a pointer to a function that reads the
139 sensor temperature trend.
140 set_emul_temp a pointer to a function that sets
141 sensor emulated temperature.
142 ============== =======================================
143
144 The thermal zone temperature is provided by the get_temp() function
145 pointer of thermal_zone_of_device_ops. When called, it will
146 have the private pointer @data back.
147
148 It returns error pointer if fails otherwise valid thermal zone device
149 handle. Caller should check the return handle with IS_ERR() for finding
150 whether success or not.
151
152 ::
153
154 void thermal_zone_of_sensor_unregister(struct device *dev,
155 struct thermal_zone_device *tzd)
156
157 This interface unregisters a sensor from a DT thermal zone which was
158 successfully added by interface thermal_zone_of_sensor_register().
159 This function removes the sensor callbacks and private data from the
160 thermal zone device registered with thermal_zone_of_sensor_register()
161 interface. It will also silent the zone by remove the .get_temp() and
162 get_trend() thermal zone device callbacks.
163
164 ::
165
166 struct thermal_zone_device
167 *devm_thermal_zone_of_sensor_register(struct device *dev,
168 int sensor_id,
169 void *data,
170 const struct thermal_zone_of_device_ops *ops)
171
172 This interface is resource managed version of
173 thermal_zone_of_sensor_register().
174
175 All details of thermal_zone_of_sensor_register() described in
176 section 1.1.3 is applicable here.
177
178 The benefit of using this interface to register sensor is that it
179 is not require to explicitly call thermal_zone_of_sensor_unregister()
180 in error path or during driver unbinding as this is done by driver
181 resource manager.
182
183 ::
184
185 void devm_thermal_zone_of_sensor_unregister(struct device *dev,
186 struct thermal_zone_device *tzd)
187
188 This interface is resource managed version of
189 thermal_zone_of_sensor_unregister().
190 All details of thermal_zone_of_sensor_unregister() described in
191 section 1.1.4 is applicable here.
192 Normally this function will not need to be called and the resource
193 management code will ensure that the resource is freed.
194
195 ::
196
197 int thermal_zone_get_slope(struct thermal_zone_device *tz)
198
199 This interface is used to read the slope attribute value
200 for the thermal zone device, which might be useful for platform
201 drivers for temperature calculations.
202
203 ::
204
205 int thermal_zone_get_offset(struct thermal_zone_device *tz)
206
207 This interface is used to read the offset attribute value
208 for the thermal zone device, which might be useful for platform
209 drivers for temperature calculations.
210
211 1.2 thermal cooling device interface
212 ------------------------------------
213
214
215 ::
216
217 struct thermal_cooling_device
218 *thermal_cooling_device_register(char *name,
219 void *devdata, struct thermal_cooling_device_ops *)
220
221 This interface function adds a new thermal cooling device (fan/processor/...)
222 to /sys/class/thermal/ folder as `cooling_device[0-*]`. It tries to bind itself
223 to all the thermal zone devices registered at the same time.
224
225 name:
226 the cooling device name.
227 devdata:
228 device private data.
229 ops:
230 thermal cooling devices call-backs.
231
232 .get_max_state:
233 get the Maximum throttle state of the cooling device.
234 .get_cur_state:
235 get the Currently requested throttle state of the
236 cooling device.
237 .set_cur_state:
238 set the Current throttle state of the cooling device.
239
240 ::
241
242 void thermal_cooling_device_unregister(struct thermal_cooling_device *cdev)
243
244 This interface function removes the thermal cooling device.
245 It deletes the corresponding entry from /sys/class/thermal folder and
246 unbinds itself from all the thermal zone devices using it.
247
248 1.4 Thermal Zone Parameters
249 ---------------------------
250
251 ::
252
253 struct thermal_zone_params
254
255 This structure defines the platform level parameters for a thermal zone.
256 This data, for each thermal zone should come from the platform layer.
257 This is an optional feature where some platforms can choose not to
258 provide this data.
259
260 .governor_name:
261 Name of the thermal governor used for this zone
262 .no_hwmon:
263 a boolean to indicate if the thermal to hwmon sysfs interface
264 is required. when no_hwmon == false, a hwmon sysfs interface
265 will be created. when no_hwmon == true, nothing will be done.
266 In case the thermal_zone_params is NULL, the hwmon interface
267 will be created (for backward compatibility).
268
269 2. sysfs attributes structure
270 =============================
271
272 == ================
273 RO read only value
274 WO write only value
275 RW read/write value
276 == ================
277
278 Thermal sysfs attributes will be represented under /sys/class/thermal.
279 Hwmon sysfs I/F extension is also available under /sys/class/hwmon
280 if hwmon is compiled in or built as a module.
281
282 Thermal zone device sys I/F, created once it's registered::
283
284 /sys/class/thermal/thermal_zone[0-*]:
285 |---type: Type of the thermal zone
286 |---temp: Current temperature
287 |---mode: Working mode of the thermal zone
288 |---policy: Thermal governor used for this zone
289 |---available_policies: Available thermal governors for this zone
290 |---trip_point_[0-*]_temp: Trip point temperature
291 |---trip_point_[0-*]_type: Trip point type
292 |---trip_point_[0-*]_hyst: Hysteresis value for this trip point
293 |---emul_temp: Emulated temperature set node
294 |---sustainable_power: Sustainable dissipatable power
295 |---k_po: Proportional term during temperature overshoot
296 |---k_pu: Proportional term during temperature undershoot
297 |---k_i: PID's integral term in the power allocator gov
298 |---k_d: PID's derivative term in the power allocator
299 |---integral_cutoff: Offset above which errors are accumulated
300 |---slope: Slope constant applied as linear extrapolation
301 |---offset: Offset constant applied as linear extrapolation
302
303 Thermal cooling device sys I/F, created once it's registered::
304
305 /sys/class/thermal/cooling_device[0-*]:
306 |---type: Type of the cooling device(processor/fan/...)
307 |---max_state: Maximum cooling state of the cooling device
308 |---cur_state: Current cooling state of the cooling device
309 |---stats: Directory containing cooling device's statistics
310 |---stats/reset: Writing any value resets the statistics
311 |---stats/time_in_state_ms: Time (msec) spent in various cooling states
312 |---stats/total_trans: Total number of times cooling state is changed
313 |---stats/trans_table: Cooling state transition table
314
315
316 Then next two dynamic attributes are created/removed in pairs. They represent
317 the relationship between a thermal zone and its associated cooling device.
318
319 ::
320
321 /sys/class/thermal/thermal_zone[0-*]:
322 |---cdev[0-*]: [0-*]th cooling device in current thermal zone
323 |---cdev[0-*]_trip_point: Trip point that cdev[0-*] is associated with
324 |---cdev[0-*]_weight: Influence of the cooling device in
325 this thermal zone
326
327 Besides the thermal zone device sysfs I/F and cooling device sysfs I/F,
328 the generic thermal driver also creates a hwmon sysfs I/F for each _type_
329 of thermal zone device. E.g. the generic thermal driver registers one hwmon
330 class device and build the associated hwmon sysfs I/F for all the registered
331 ACPI thermal zones.
332
333 Please read Documentation/ABI/testing/sysfs-class-thermal for thermal
334 zone and cooling device attribute details.
335
336 ::
337
338 /sys/class/hwmon/hwmon[0-*]:
339 |---name: The type of the thermal zone devices
340 |---temp[1-*]_input: The current temperature of thermal zone [1-*]
341 |---temp[1-*]_critical: The critical trip point of thermal zone [1-*]
342
343 Please read Documentation/hwmon/sysfs-interface.rst for additional information.
344
345 3. A simple implementation
346 ==========================
347
348 ACPI thermal zone may support multiple trip points like critical, hot,
349 passive, active. If an ACPI thermal zone supports critical, passive,
350 active[0] and active[1] at the same time, it may register itself as a
351 thermal_zone_device (thermal_zone1) with 4 trip points in all.
352 It has one processor and one fan, which are both registered as
353 thermal_cooling_device. Both are considered to have the same
354 effectiveness in cooling the thermal zone.
355
356 If the processor is listed in _PSL method, and the fan is listed in _AL0
357 method, the sys I/F structure will be built like this::
358
359 /sys/class/thermal:
360 |thermal_zone1:
361 |---type: acpitz
362 |---temp: 37000
363 |---mode: enabled
364 |---policy: step_wise
365 |---available_policies: step_wise fair_share
366 |---trip_point_0_temp: 100000
367 |---trip_point_0_type: critical
368 |---trip_point_1_temp: 80000
369 |---trip_point_1_type: passive
370 |---trip_point_2_temp: 70000
371 |---trip_point_2_type: active0
372 |---trip_point_3_temp: 60000
373 |---trip_point_3_type: active1
374 |---cdev0: --->/sys/class/thermal/cooling_device0
375 |---cdev0_trip_point: 1 /* cdev0 can be used for passive */
376 |---cdev0_weight: 1024
377 |---cdev1: --->/sys/class/thermal/cooling_device3
378 |---cdev1_trip_point: 2 /* cdev1 can be used for active[0]*/
379 |---cdev1_weight: 1024
380
381 |cooling_device0:
382 |---type: Processor
383 |---max_state: 8
384 |---cur_state: 0
385
386 |cooling_device3:
387 |---type: Fan
388 |---max_state: 2
389 |---cur_state: 0
390
391 /sys/class/hwmon:
392 |hwmon0:
393 |---name: acpitz
394 |---temp1_input: 37000
395 |---temp1_crit: 100000
396
397 4. Export Symbol APIs
398 =====================
399
400 4.1. get_tz_trend
401 -----------------
402
403 This function returns the trend of a thermal zone, i.e the rate of change
404 of temperature of the thermal zone. Ideally, the thermal sensor drivers
405 are supposed to implement the callback. If they don't, the thermal
406 framework calculated the trend by comparing the previous and the current
407 temperature values.
408
409 4.2. thermal_cdev_update
410 ------------------------
411
412 This function serves as an arbitrator to set the state of a cooling
413 device. It sets the cooling device to the deepest cooling state if
414 possible.
415
416 5. Critical Events
417 ==================
418
419 On an event of critical trip temperature crossing, the thermal framework
420 will trigger a hardware protection power-off (shutdown) or reboot,
421 depending on configuration.
422
423 At first, the kernel will attempt an orderly power-off or reboot, but
424 accepts a delay after which it proceeds to do a forced power-off or
425 reboot, respectively. If this fails, ``emergency_restart()`` is invoked
426 as last resort.
427
428 The delay should be carefully profiled so as to give adequate time for
429 orderly power-off or reboot.
430
431 If the delay is set to 0, the emergency action will not be supported. So a
432 carefully profiled non-zero positive value is a must for the emergency
433 action to be triggered.
434

3. 한국어 전문 번역

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

Generic thermal sysfs 소개

1-30

이 문서는 Sujith Thomas와 Zhang Rui가 작성한 Generic Thermal Sysfs driver 사용 안내서이며 Copyright는 2008 Intel Corporation에 있습니다.

Generic thermal sysfs는 thermal zone device(sensor)와 thermal cooling device(fan, processor 등)가 thermal management solution에 등록되어 참여할 수 있는 interface를 제공합니다.

이 안내서는 새 thermal zone과 cooling device를 thermal management에 참여시키는 방법에 초점을 둡니다. Infrastructure는 platform-independent이므로 어떤 유형의 thermal zone과 cooling device도 사용할 수 있어야 합니다.

Thermal sysfs driver의 주된 일은 thermal zone 및 cooling device attribute를 user space에 노출하는 것입니다. Intelligent thermal application은 current temperature와 trip point temperature를 읽어 적절한 device를 throttle할 수 있습니다.

표기에서 `[0-*]`는 0부터 시작하는 임의의 양수 번호를, `[1-*]`는 1부터 시작하는 임의의 양수 번호를 뜻합니다.

Generic thermal management 경로
Thermal zone devices (sensors)Generic thermal framework
Cooling devices (fan, processor)Generic thermal framework
Generic thermal framework`/sys/class/thermal` attributes
Thermal zone inputsUser-space thermal manager
User-space thermal managerThrottle appropriate cooling devices

Sensor와 cooling device가 thermal core 및 user space에 연결되는 구조입니다.

===================================
Generic Thermal Sysfs driver How To
===================================

Written by Sujith Thomas <sujith.thomas@intel.com>, Zhang Rui <rui.zhang@intel.com>

Copyright (c)  2008 Intel Corporation


0. Introduction
===============

The generic thermal sysfs provides a set of interfaces for thermal zone
devices (sensors) and thermal cooling devices (fan, processor...) to register
with the thermal management solution and to be a part of it.

This how-to focuses on enabling new thermal zone and cooling devices to
participate in thermal management.
This solution is platform independent and any type of thermal zone devices
and cooling devices should be able to make use of the infrastructure.

The main task of the thermal sysfs driver is to expose thermal zone attributes
as well as cooling device attributes to the user space.
An intelligent thermal management application can make decisions based on
inputs from thermal zone attributes (the current temperature and trip point
temperature) and throttle appropriate devices.

- `[0-*]`        denotes any positive number starting from 0
- `[1-*]`        denotes any positive number starting from 1

Thermal zone device 등록과 해제

31-100

`thermal_zone_device_register_with_trips()`는 새 thermal zone device(sensor)를 `/sys/class/thermal/thermal_zone[0-*]`로 추가하고, 동시에 등록된 모든 thermal cooling device를 bind하려고 시도합니다.

`type`은 thermal zone type, `trips`는 trip point table, `devdata`는 device private data, `ops`는 thermal zone callback, `tzp`는 platform parameter입니다. `passive_delay`는 passive cooling poll 사이의 millisecond, `polling_delay`는 trip crossing 확인 poll 사이의 millisecond이며 interrupt-driven system에서는 0입니다.

`.should_bind`는 cooling device를 특정 trip point에 bind할지 검사하고, `.get_temp`는 current temperature를 얻습니다. `.set_trips`는 current temperature 바로 아래와 위의 trip point를 찾아 trip window를 설정합니다.

`.change_mode`는 zone의 enabled/disabled mode를 바꾸고, `.set_trip_temp`는 특정 trip point temperature를 설정하며, `.get_crit_temp`는 critical temperature를 얻습니다.

`.set_emul_temp`는 threshold debugging용 emulation temperature를 설정하고, `.get_trend`는 최근 zone temperature 변화 추세를 얻습니다. `.hot`과 `.critical`은 각각 해당 trip point crossing handler입니다.

`thermal_zone_device_unregister()`는 thermal zone device를 제거하고 `/sys/class/thermal` entry를 삭제하며 사용하던 모든 cooling device의 binding을 해제합니다.

thermal_zone_device_ops와 등록 parameter
항목역할
`type`, `trips`, `devdata`Zone type, trip table, private data
`.should_bind`Cooling device와 trip point binding 여부
`.get_temp` / `.get_trend`Current temperature / 최근 변화 추세
`.set_trips` / `.set_trip_temp`Trip window / 특정 trip temperature 설정
`.change_mode`Zone enabled/disabled 변경
`.get_crit_temp`Critical temperature 조회
`.set_emul_temp`Debugging용 emulated temperature 설정
`.hot` / `.critical`Hot / critical crossing handler
`passive_delay` / `polling_delay`Passive / trip checking poll 간격, ms

1. thermal sysfs driver interface functions
===========================================

1.1 thermal zone device interface
---------------------------------

    ::

        struct thermal_zone_device *
        thermal_zone_device_register_with_trips(const char *type,
                                        const struct thermal_trip *trips,
                                        int num_trips, void *devdata,
                                        const struct thermal_zone_device_ops *ops,
                                        const struct thermal_zone_params *tzp,
                                        unsigned int passive_delay,
                                        unsigned int polling_delay)

    This interface function adds a new thermal zone device (sensor) to the
    /sys/class/thermal folder as `thermal_zone[0-*]`. It tries to bind all the
    thermal cooling devices registered to it at the same time.

    type:
        the thermal zone type.
    trips:
        the table of trip points for this thermal zone.
    devdata:
        device private data
    ops:
        thermal zone device call-backs.

        .should_bind:
                check whether or not a given cooling device should be bound to
                a given trip point in this thermal zone.
        .get_temp:
                get the current temperature of the thermal zone.
        .set_trips:
                set the trip points window. Whenever the current temperature
                is updated, the trip points immediately below and above the
                current temperature are found.
        .change_mode:
                change the mode (enabled/disabled) of the thermal zone.
        .set_trip_temp:
                set the temperature of a given trip point.
        .get_crit_temp:
                get the critical temperature for this thermal zone.
        .set_emul_temp:
                set the emulation temperature which helps in debugging
                different threshold temperature points.
        .get_trend:
                get the trend of most recent zone temperature changes.
        .hot:
                hot trip point crossing handler.
        .critical:
                critical trip point crossing handler.
    tzp:
        thermal zone platform parameters.
    passive_delay:
        number of milliseconds to wait between polls when performing passive
        cooling.
    polling_delay:
        number of milliseconds to wait between polls when checking
        whether trip points have been crossed (0 for interrupt driven systems).

    ::

        void thermal_zone_device_unregister(struct thermal_zone_device *tz)

    This interface function removes the thermal zone device.
    It deletes the corresponding entry from /sys/class/thermal folder and
    unbinds all the thermal cooling devices it uses.

Device Tree thermal sensor 등록

101-150

`thermal_zone_of_sensor_register()`는 새 sensor를 DT thermal zone에 추가합니다. Device tree에 기술된 thermal zone 목록에서 `dev->of_node`가 temperature provider로 참조되는 zone을 찾아 sensor를 해당 DT thermal zone device에 연결합니다.

`dev`는 유효한 `dev->of_node` pointer를 가진 sensor device node입니다. `sensor_id`는 sensor IP에 sensor가 여러 개 있을 때 쓰는 identifier입니다. `data`는 caller 소유 private pointer이며 temperature reading callback에 다시 전달됩니다. `ops`는 `struct thermal_zone_of_device_ops *`입니다.

필수 callback `get_temp`는 sensor temperature를 읽습니다. `set_trips`는 temperature window를 설정하고, window를 벗어나면 driver가 `thermal_zone_device_update`로 thermal core에 알려야 합니다.

선택 callback `get_trend`는 sensor temperature trend를 읽고 `set_emul_temp`는 emulated temperature를 설정합니다. Thermal zone temperature는 `thermal_zone_of_device_ops.get_temp()`로 제공되며 호출 시 private `@data`가 돌아옵니다.

실패하면 error pointer, 성공하면 유효한 thermal zone device handle을 반환합니다. Caller는 `IS_ERR()`로 성공 여부를 검사해야 합니다.

thermal_zone_of_sensor_register()
Parameter 또는 callback요구사항
`dev`유효한 `dev->of_node`를 가진 sensor device
`sensor_id`여러 sensor가 있을 때 identifier
`data`Callback에 반환되는 caller-owned private pointer
`get_temp`필수, sensor temperature 읽기
`set_trips`Temperature window 설정, 이탈 시 core update
`get_trend`Temperature trend 읽기
`set_emul_temp`Emulated temperature 설정
반환값Error pointer 또는 valid thermal zone handle, `IS_ERR()` 검사


::

   struct thermal_zone_device
   *thermal_zone_of_sensor_register(struct device *dev, int sensor_id,
                        void *data,
                        const struct thermal_zone_of_device_ops *ops)

This interface adds a new sensor to a DT thermal zone.
This function will search the list of thermal zones described in
device tree and look for the zone that refer to the sensor device
pointed by dev->of_node as temperature providers. For the zone
pointing to the sensor node, the sensor will be added to the DT
thermal zone device.

The parameters for this interface are:

dev:
                Device node of sensor containing valid node pointer in
                dev->of_node.
sensor_id:
                a sensor identifier, in case the sensor IP has more
                than one sensors
data:
                a private pointer (owned by the caller) that will be
                passed back, when a temperature reading is needed.
ops:
                `struct thermal_zone_of_device_ops *`.

                ==============  =======================================
                get_temp        a pointer to a function that reads the
                                sensor temperature. This is mandatory
                                callback provided by sensor driver.
                set_trips        a pointer to a function that sets a
                                temperature window. When this window is
                                left the driver must inform the thermal
                                core via thermal_zone_device_update.
                get_trend         a pointer to a function that reads the
                                sensor temperature trend.
                set_emul_temp        a pointer to a function that sets
                                sensor emulated temperature.
                ==============  =======================================

The thermal zone temperature is provided by the get_temp() function
pointer of thermal_zone_of_device_ops. When called, it will
have the private pointer @data back.

It returns error pointer if fails otherwise valid thermal zone device
handle. Caller should check the return handle with IS_ERR() for finding
whether success or not.

DT sensor 해제, devm 등록과 slope·offset

151-210

`thermal_zone_of_sensor_unregister()`는 `thermal_zone_of_sensor_register()`로 추가한 sensor를 DT thermal zone에서 해제합니다. Sensor callback과 private data를 제거하고 `.get_temp()` 및 `get_trend()` callback을 제거해 zone을 비활성 상태로 만듭니다.

`devm_thermal_zone_of_sensor_register()`는 register function의 resource-managed version입니다. Error path나 driver unbinding에서 `thermal_zone_of_sensor_unregister()`를 명시적으로 호출할 필요가 없고 driver resource manager가 처리합니다.

`devm_thermal_zone_of_sensor_unregister()`는 unregister function의 resource-managed version입니다. 일반적으로 직접 호출할 필요 없이 resource management code가 해제를 보장합니다.

`thermal_zone_get_slope()`와 `thermal_zone_get_offset()`은 thermal zone의 slope 및 offset attribute를 읽습니다. Platform driver가 temperature 계산에 사용할 수 있습니다.

DT thermal sensor lifecycle API
API동작
`thermal_zone_of_sensor_unregister()`Sensor callback과 private data 제거
`devm_thermal_zone_of_sensor_register()`Resource-managed sensor 등록
`devm_thermal_zone_of_sensor_unregister()`Resource-managed sensor 해제, 보통 직접 호출 불필요
`thermal_zone_get_slope()`Temperature 계산용 slope 조회
`thermal_zone_get_offset()`Temperature 계산용 offset 조회


::

    void thermal_zone_of_sensor_unregister(struct device *dev,
                                           struct thermal_zone_device *tzd)

This interface unregisters a sensor from a DT thermal zone which was
successfully added by interface thermal_zone_of_sensor_register().
This function removes the sensor callbacks and private data from the
thermal zone device registered with thermal_zone_of_sensor_register()
interface. It will also silent the zone by remove the .get_temp() and
get_trend() thermal zone device callbacks.

::

  struct thermal_zone_device
  *devm_thermal_zone_of_sensor_register(struct device *dev,
                        int sensor_id,
                        void *data,
                        const struct thermal_zone_of_device_ops *ops)

This interface is resource managed version of
thermal_zone_of_sensor_register().

All details of thermal_zone_of_sensor_register() described in
section 1.1.3 is applicable here.

The benefit of using this interface to register sensor is that it
is not require to explicitly call thermal_zone_of_sensor_unregister()
in error path or during driver unbinding as this is done by driver
resource manager.

::

        void devm_thermal_zone_of_sensor_unregister(struct device *dev,
                                        struct thermal_zone_device *tzd)

This interface is resource managed version of
thermal_zone_of_sensor_unregister().
All details of thermal_zone_of_sensor_unregister() described in
section 1.1.4 is applicable here.
Normally this function will not need to be called and the resource
management code will ensure that the resource is freed.

::

        int thermal_zone_get_slope(struct thermal_zone_device *tz)

This interface is used to read the slope attribute value
for the thermal zone device, which might be useful for platform
drivers for temperature calculations.

::

        int thermal_zone_get_offset(struct thermal_zone_device *tz)

This interface is used to read the offset attribute value
for the thermal zone device, which might be useful for platform
drivers for temperature calculations.

Thermal cooling device interface

211-247

`thermal_cooling_device_register()`는 새 thermal cooling device(fan, processor 등)를 `/sys/class/thermal/cooling_device[0-*]`로 추가하고 동시에 등록된 모든 thermal zone device에 자신을 bind하려고 시도합니다.

`name`은 cooling device name, `devdata`는 private data, `ops`는 callback입니다. `.get_max_state`는 maximum throttle state, `.get_cur_state`는 현재 요청된 throttle state를 얻고 `.set_cur_state`는 current throttle state를 설정합니다.

`thermal_cooling_device_unregister()`는 cooling device를 제거하고 `/sys/class/thermal` entry를 삭제하며 이를 사용하는 모든 thermal zone에서 binding을 해제합니다.

thermal_cooling_device interface
항목역할
`name` / `devdata`Cooling device name / private data
`.get_max_state`Maximum throttle state 조회
`.get_cur_state`현재 요청된 throttle state 조회
`.set_cur_state`Current throttle state 설정
`thermal_cooling_device_unregister()`Sysfs entry 삭제와 모든 zone binding 해제

1.2 thermal cooling device interface
------------------------------------


    ::

        struct thermal_cooling_device
        *thermal_cooling_device_register(char *name,
                        void *devdata, struct thermal_cooling_device_ops *)

    This interface function adds a new thermal cooling device (fan/processor/...)
    to /sys/class/thermal/ folder as `cooling_device[0-*]`. It tries to bind itself
    to all the thermal zone devices registered at the same time.

    name:
        the cooling device name.
    devdata:
        device private data.
    ops:
        thermal cooling devices call-backs.

        .get_max_state:
                get the Maximum throttle state of the cooling device.
        .get_cur_state:
                get the Currently requested throttle state of the
                cooling device.
        .set_cur_state:
                set the Current throttle state of the cooling device.

    ::

        void thermal_cooling_device_unregister(struct thermal_cooling_device *cdev)

    This interface function removes the thermal cooling device.
    It deletes the corresponding entry from /sys/class/thermal folder and
    unbinds itself from all the thermal zone devices using it.

Thermal Zone Parameters

248-268

`struct thermal_zone_params`는 thermal zone의 platform-level parameter를 정의합니다. 각 zone의 data는 platform layer에서 와야 하지만 optional이므로 제공하지 않는 platform도 있습니다.

`.governor_name`은 이 zone에서 사용하는 thermal governor 이름입니다.

`.no_hwmon`은 thermal-to-hwmon sysfs interface 생성 여부입니다. `false`면 hwmon interface를 만들고 `true`면 만들지 않습니다. `thermal_zone_params`가 `NULL`이면 backward compatibility를 위해 hwmon interface를 생성합니다.

struct thermal_zone_params
Member의미
`.governor_name`Zone에 사용할 thermal governor name
`.no_hwmon = false`Hwmon sysfs interface 생성
`.no_hwmon = true`Hwmon interface 생성 안 함
`thermal_zone_params = NULL`Backward compatibility로 hwmon interface 생성

1.4 Thermal Zone Parameters
---------------------------

    ::

        struct thermal_zone_params

    This structure defines the platform level parameters for a thermal zone.
    This data, for each thermal zone should come from the platform layer.
    This is an optional feature where some platforms can choose not to
    provide this data.

    .governor_name:
               Name of the thermal governor used for this zone
    .no_hwmon:
               a boolean to indicate if the thermal to hwmon sysfs interface
               is required. when no_hwmon == false, a hwmon sysfs interface
               will be created. when no_hwmon == true, nothing will be done.
               In case the thermal_zone_params is NULL, the hwmon interface
               will be created (for backward compatibility).

Thermal zone과 cooling device sysfs tree

269-315

속성 권한 표기에서 `RO`는 read-only, `WO`는 write-only, `RW`는 read/write입니다. Thermal sysfs attribute는 `/sys/class/thermal` 아래에 있고, hwmon이 built-in 또는 module로 compile되면 `/sys/class/hwmon`에도 확장 interface가 있습니다.

등록된 thermal zone에는 type, current temperature, mode, policy, available policy와 각 trip point의 temperature·type·hysteresis가 생성됩니다. `emul_temp`는 emulated temperature 설정 node입니다.

Power allocator 관련 `sustainable_power`, `k_po`, `k_pu`, `k_i`, `k_d`, `integral_cutoff`와 linear extrapolation용 `slope`, `offset`도 thermal zone attribute로 제공됩니다.

등록된 cooling device에는 type, maximum/current state와 statistics directory가 있습니다. Statistics는 reset, state별 체류 시간(ms), total transition count, transition table을 제공합니다.

Thermal sysfs 기본 속성
객체속성의미
`thermal_zone[0-*]``type`, `temp`, `mode`Zone type, current temperature, working mode
Thermal zone`policy`, `available_policies`현재 및 사용 가능한 governor
Thermal zone`trip_point_[0-*]_{temp,type,hyst}`Trip temperature, type, hysteresis
Thermal zone`emul_temp`Emulated temperature 설정
Thermal zone`sustainable_power`, `k_po`, `k_pu`, `k_i`, `k_d`, `integral_cutoff`Power allocator tunable
Thermal zone`slope`, `offset`Linear extrapolation constant
`cooling_device[0-*]``type`, `max_state`, `cur_state`Cooling type와 state
Cooling device`stats/reset`, `time_in_state_ms`, `total_trans`, `trans_table`Cooling statistics

2. sysfs attributes structure
=============================

==        ================
RO        read only value
WO        write only value
RW        read/write value
==        ================

Thermal sysfs attributes will be represented under /sys/class/thermal.
Hwmon sysfs I/F extension is also available under /sys/class/hwmon
if hwmon is compiled in or built as a module.

Thermal zone device sys I/F, created once it's registered::

  /sys/class/thermal/thermal_zone[0-*]:
    |---type:                        Type of the thermal zone
    |---temp:                        Current temperature
    |---mode:                        Working mode of the thermal zone
    |---policy:                        Thermal governor used for this zone
    |---available_policies:        Available thermal governors for this zone
    |---trip_point_[0-*]_temp:        Trip point temperature
    |---trip_point_[0-*]_type:        Trip point type
    |---trip_point_[0-*]_hyst:        Hysteresis value for this trip point
    |---emul_temp:                Emulated temperature set node
    |---sustainable_power:      Sustainable dissipatable power
    |---k_po:                   Proportional term during temperature overshoot
    |---k_pu:                   Proportional term during temperature undershoot
    |---k_i:                    PID's integral term in the power allocator gov
    |---k_d:                    PID's derivative term in the power allocator
    |---integral_cutoff:        Offset above which errors are accumulated
    |---slope:                  Slope constant applied as linear extrapolation
    |---offset:                 Offset constant applied as linear extrapolation

Thermal cooling device sys I/F, created once it's registered::

  /sys/class/thermal/cooling_device[0-*]:
    |---type:                        Type of the cooling device(processor/fan/...)
    |---max_state:                Maximum cooling state of the cooling device
    |---cur_state:                Current cooling state of the cooling device
    |---stats:                        Directory containing cooling device's statistics
    |---stats/reset:                Writing any value resets the statistics
    |---stats/time_in_state_ms:        Time (msec) spent in various cooling states
    |---stats/total_trans:        Total number of times cooling state is changed
    |---stats/trans_table:        Cooling state transition table

Zone·cooling 관계와 hwmon interface

316-344

두 dynamic attribute는 pair로 생성·제거되며 thermal zone과 연결된 cooling device의 관계를 표현합니다. `cdev[0-*]`는 현재 zone의 cooling device, `cdev[0-*]_trip_point`는 연결된 trip point, `cdev[0-*]_weight`는 이 zone에서의 영향도입니다.

Generic thermal driver는 thermal zone device 및 cooling device sysfs 외에도 thermal zone device의 각 `_type_`별 hwmon interface를 만듭니다. 예를 들어 등록된 모든 ACPI thermal zone을 위해 hwmon class device 하나와 관련 sysfs interface를 구성합니다.

Hwmon tree의 `name`은 thermal zone type, `temp[1-*]_input`은 current temperature, `temp[1-*]_critical`은 critical trip point입니다. 자세한 thermal attribute는 `Documentation/ABI/testing/sysfs-class-thermal`, hwmon 정보는 `Documentation/hwmon/sysfs-interface.rst`를 참조합니다.

Thermal zone, cooling device와 hwmon 관계
`thermal_zoneN/cdevM``cooling_deviceM`
`thermal_zoneN/cdevM_trip_point`Associated trip point
`thermal_zoneN/cdevM_weight`Cooling influence in this zone
Thermal zones sharing one `_type_``hwmonN/name`
Thermal zone temperatures`hwmonN/temp[1-*]_input` and `_critical`

원문의 dynamic attribute 및 hwmon ASCII tree를 관계 흐름도로 재구성했습니다.

Then next two dynamic attributes are created/removed in pairs. They represent
the relationship between a thermal zone and its associated cooling device.

::

  /sys/class/thermal/thermal_zone[0-*]:
    |---cdev[0-*]:                [0-*]th cooling device in current thermal zone
    |---cdev[0-*]_trip_point:        Trip point that cdev[0-*] is associated with
    |---cdev[0-*]_weight:       Influence of the cooling device in
                                this thermal zone

Besides the thermal zone device sysfs I/F and cooling device sysfs I/F,
the generic thermal driver also creates a hwmon sysfs I/F for each _type_
of thermal zone device. E.g. the generic thermal driver registers one hwmon
class device and build the associated hwmon sysfs I/F for all the registered
ACPI thermal zones.

Please read Documentation/ABI/testing/sysfs-class-thermal for thermal
zone and cooling device attribute details.

::

  /sys/class/hwmon/hwmon[0-*]:
    |---name:                        The type of the thermal zone devices
    |---temp[1-*]_input:        The current temperature of thermal zone [1-*]
    |---temp[1-*]_critical:        The critical trip point of thermal zone [1-*]

Please read Documentation/hwmon/sysfs-interface.rst for additional information.

ACPI thermal zone 구현 예

345-396

ACPI thermal zone은 critical, hot, passive, active 같은 여러 trip point를 지원할 수 있습니다. 예제 zone은 critical, passive, active[0], active[1]을 지원해 4개 trip point의 `thermal_zone1`로 등록됩니다.

Processor 하나와 fan 하나가 각각 `thermal_cooling_device`로 등록되며 zone 냉각 효과는 동일하다고 간주합니다. Processor가 `_PSL` method에, fan이 `_AL0` method에 나열된 구성입니다.

예제 `thermal_zone1`은 `acpitz`, 37000 milli degree, enabled, `step_wise` policy입니다. Critical 100000, passive 80000, active0 70000, active1 60000의 trip point를 가집니다.

`cdev0` processor는 passive trip point 1에 weight 1024로 연결되고, `cdev1` fan은 active[0] trip point 2에 weight 1024로 연결됩니다. Processor maximum state는 8, fan maximum state는 2이며 둘의 current state는 0입니다.

같은 zone은 `/sys/class/hwmon/hwmon0`에서 name `acpitz`, `temp1_input` 37000, `temp1_crit` 100000으로 나타납니다.

ACPI thermal sysfs 예제
객체주요 값연결
`thermal_zone1``acpitz`, temp 37000, enabled, `step_wise`4 trip points
Trip 0 / 1critical 100000 / passive 80000Processor는 trip 1
Trip 2 / 3active0 70000 / active1 60000Fan은 trip 2
`cooling_device0`Processor, max 8, current 0Weight 1024
`cooling_device3`Fan, max 2, current 0Weight 1024
`hwmon0``acpitz`, input 37000, crit 100000Thermal zone의 hwmon 표현

원문의 `/sys/class/thermal` 및 `/sys/class/hwmon` ASCII tree를 값과 연결 관계가 같은 표로 재구성했습니다.

3. A simple implementation
==========================

ACPI thermal zone may support multiple trip points like critical, hot,
passive, active. If an ACPI thermal zone supports critical, passive,
active[0] and active[1] at the same time, it may register itself as a
thermal_zone_device (thermal_zone1) with 4 trip points in all.
It has one processor and one fan, which are both registered as
thermal_cooling_device. Both are considered to have the same
effectiveness in cooling the thermal zone.

If the processor is listed in _PSL method, and the fan is listed in _AL0
method, the sys I/F structure will be built like this::

 /sys/class/thermal:
  |thermal_zone1:
    |---type:                        acpitz
    |---temp:                        37000
    |---mode:                        enabled
    |---policy:                        step_wise
    |---available_policies:        step_wise fair_share
    |---trip_point_0_temp:        100000
    |---trip_point_0_type:        critical
    |---trip_point_1_temp:        80000
    |---trip_point_1_type:        passive
    |---trip_point_2_temp:        70000
    |---trip_point_2_type:        active0
    |---trip_point_3_temp:        60000
    |---trip_point_3_type:        active1
    |---cdev0:                        --->/sys/class/thermal/cooling_device0
    |---cdev0_trip_point:        1        /* cdev0 can be used for passive */
    |---cdev0_weight:           1024
    |---cdev1:                        --->/sys/class/thermal/cooling_device3
    |---cdev1_trip_point:        2        /* cdev1 can be used for active[0]*/
    |---cdev1_weight:           1024

  |cooling_device0:
    |---type:                        Processor
    |---max_state:                8
    |---cur_state:                0

  |cooling_device3:
    |---type:                        Fan
    |---max_state:                2
    |---cur_state:                0

 /sys/class/hwmon:
  |hwmon0:
    |---name:                        acpitz
    |---temp1_input:                37000
    |---temp1_crit:                100000

Export Symbol API

397-415

`get_tz_trend`는 thermal zone temperature의 변화율인 trend를 반환합니다. 이상적으로 thermal sensor driver가 callback을 구현해야 하지만, 구현하지 않으면 thermal framework가 previous와 current temperature를 비교해 trend를 계산합니다.

`thermal_cdev_update`는 cooling device state를 설정하는 arbitrator입니다. 가능하면 cooling device를 가장 깊은 cooling state로 설정합니다.

Thermal exported symbol
Symbol역할
`get_tz_trend`Zone temperature 변화율 반환, callback이 없으면 framework가 계산
`thermal_cdev_update`Cooling state 조정, 가능하면 deepest state 설정

4. Export Symbol APIs
=====================

4.1. get_tz_trend
-----------------

This function returns the trend of a thermal zone, i.e the rate of change
of temperature of the thermal zone. Ideally, the thermal sensor drivers
are supposed to implement the callback. If they don't, the thermal
framework calculated the trend by comparing the previous and the current
temperature values.

4.2. thermal_cdev_update
------------------------

This function serves as an arbitrator to set the state of a cooling
device. It sets the cooling device to the deepest cooling state if
possible.

Critical event와 emergency action

416-433

Critical trip temperature를 넘으면 thermal framework는 configuration에 따라 hardware protection power-off(shutdown) 또는 reboot를 trigger합니다.

Kernel은 먼저 orderly power-off 또는 reboot를 시도하고, 설정된 delay 후 각각 forced power-off 또는 reboot를 수행합니다. 이것도 실패하면 최후 수단으로 `emergency_restart()`를 호출합니다.

Delay는 orderly action에 충분한 시간을 주도록 신중하게 측정해야 합니다. Delay가 0이면 emergency action이 지원되지 않으므로, emergency action을 trigger하려면 검증한 0보다 큰 값을 반드시 설정해야 합니다.

Critical thermal event 처리
Critical trip temperature crossingOrderly power-off or reboot
Configured non-zero delay expiresForced power-off or reboot
Forced action fails`emergency_restart()`
Delay = 0Emergency action not supported

Critical trip crossing 이후 orderly action부터 최후 수단까지의 순서입니다.

5. Critical Events
==================

On an event of critical trip temperature crossing, the thermal framework
will trigger a hardware protection power-off (shutdown) or reboot,
depending on configuration.

At first, the kernel will attempt an orderly power-off or reboot, but
accepts a delay after which it proceeds to do a forced power-off or
reboot, respectively. If this fails, ``emergency_restart()`` is invoked
as last resort.

The delay should be carefully profiled so as to give adequate time for
orderly power-off or reboot.

If the delay is set to 0, the emergency action will not be supported. So a
carefully profiled non-zero positive value is a must for the emergency
action to be triggered.