요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.
1. 요약·해설
원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.
2. 영어 원문 전체
번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.
원문 전체 펼치기
======================================
Pulse Width Modulation (PWM) interface
======================================
This provides an overview about the Linux PWM interface
PWMs are commonly used for controlling LEDs, fans or vibrators in
cell phones. PWMs with a fixed purpose have no need implementing
the Linux PWM API (although they could). However, PWMs are often
found as discrete devices on SoCs which have no fixed purpose. It's
up to the board designer to connect them to LEDs or fans. To provide
this kind of flexibility the generic PWM API exists.
Identifying PWMs
----------------
Users of the legacy PWM API use unique IDs to refer to PWM devices.
Instead of referring to a PWM device via its unique ID, board setup code
should instead register a static mapping that can be used to match PWM
consumers to providers, as given in the following example::
static struct pwm_lookup board_pwm_lookup[] = {
PWM_LOOKUP("tegra-pwm", 0, "pwm-backlight", NULL,
50000, PWM_POLARITY_NORMAL),
};
static void __init board_init(void)
{
...
pwm_add_table(board_pwm_lookup, ARRAY_SIZE(board_pwm_lookup));
...
}
Using PWMs
----------
Consumers use the pwm_get() function and pass to it the consumer device or a
consumer name. pwm_put() is used to free the PWM device. Managed variants of
the getter, devm_pwm_get() and devm_fwnode_pwm_get(), also exist.
After being requested, a PWM has to be configured using::
int pwm_apply_might_sleep(struct pwm_device *pwm, struct pwm_state *state);
This API controls both the PWM period/duty_cycle config and the
enable/disable state.
PWM devices can be used from atomic context, if the PWM does not sleep. You
can check if this the case with::
bool pwm_might_sleep(struct pwm_device *pwm);
If false, the PWM can also be configured from atomic context with::
int pwm_apply_atomic(struct pwm_device *pwm, struct pwm_state *state);
As a consumer, don't rely on the output's state for a disabled PWM. If it's
easily possible, drivers are supposed to emit the inactive state, but some
drivers cannot. If you rely on getting the inactive state, use .duty_cycle=0,
.enabled=true.
There is also a usage_power setting: If set, the PWM driver is only required to
maintain the power output but has more freedom regarding signal form.
If supported by the driver, the signal can be optimized, for example to improve
EMI by phase shifting the individual channels of a chip.
The pwm_config(), pwm_enable() and pwm_disable() functions are just wrappers
around pwm_apply_might_sleep() and should not be used if the user wants to change
several parameter at once. For example, if you see pwm_config() and
pwm_{enable,disable}() calls in the same function, this probably means you
should switch to pwm_apply_might_sleep().
The PWM user API also allows one to query the PWM state that was passed to the
last invocation of pwm_apply_might_sleep() using pwm_get_state(). Note this is
different to what the driver has actually implemented if the request cannot be
satisfied exactly with the hardware in use. There is currently no way for
consumers to get the actually implemented settings.
In addition to the PWM state, the PWM API also exposes PWM arguments, which
are the reference PWM config one should use on this PWM.
PWM arguments are usually platform-specific and allows the PWM user to only
care about dutycycle relatively to the full period (like, duty = 50% of the
period). struct pwm_args contains 2 fields (period and polarity) and should
be used to set the initial PWM config (usually done in the probe function
of the PWM user). PWM arguments are retrieved with pwm_get_args().
All consumers should really be reconfiguring the PWM upon resume as
appropriate. This is the only way to ensure that everything is resumed in
the proper order.
Using PWMs with the sysfs interface
-----------------------------------
If CONFIG_SYSFS is enabled in your kernel configuration a simple sysfs
interface is provided to use the PWMs from userspace. It is exposed at
/sys/class/pwm/. Each probed PWM controller/chip will be exported as
pwmchipN, where N is the base of the PWM chip. Inside the directory you
will find:
npwm
The number of PWM channels this chip supports (read-only).
export
Exports a PWM channel for use with sysfs (write-only).
unexport
Unexports a PWM channel from sysfs (write-only).
The PWM channels are numbered using a per-chip index from 0 to npwm-1.
When a PWM channel is exported a pwmX directory will be created in the
pwmchipN directory it is associated with, where X is the number of the
channel that was exported. The following properties will then be available:
period
The total period of the PWM signal (read/write).
Value is in nanoseconds and is the sum of the active and inactive
time of the PWM.
duty_cycle
The active time of the PWM signal (read/write).
Value is in nanoseconds and must be less than or equal to the period.
polarity
Changes the polarity of the PWM signal (read/write).
Writes to this property only work if the PWM chip supports changing
the polarity.
Value is the string "normal" or "inversed".
enable
Enable/disable the PWM signal (read/write).
- 0 - disabled
- 1 - enabled
Implementing a PWM driver
-------------------------
Currently there are two ways to implement pwm drivers. Traditionally
there only has been the barebone API meaning that each driver has
to implement the pwm_*() functions itself. This means that it's impossible
to have multiple PWM drivers in the system. For this reason it's mandatory
for new drivers to use the generic PWM framework.
A new PWM controller/chip can be allocated using pwmchip_alloc(), then
registered using pwmchip_add() and removed again with pwmchip_remove(). To undo
pwmchip_alloc() use pwmchip_put(). pwmchip_add() takes a filled in struct
pwm_chip as argument which provides a description of the PWM chip, the number
of PWM devices provided by the chip and the chip-specific implementation of the
supported PWM operations to the framework.
When implementing polarity support in a PWM driver, make sure to respect the
signal conventions in the PWM framework. By definition, normal polarity
characterizes a signal starts high for the duration of the duty cycle and
goes low for the remainder of the period. Conversely, a signal with inversed
polarity starts low for the duration of the duty cycle and goes high for the
remainder of the period.
Drivers are encouraged to implement ->apply() instead of the legacy
->enable(), ->disable() and ->config() methods. Doing that should provide
atomicity in the PWM config workflow, which is required when the PWM controls
a critical device (like a regulator).
The implementation of ->get_state() (a method used to retrieve initial PWM
state) is also encouraged for the same reason: letting the PWM user know
about the current PWM state would allow him to avoid glitches.
Drivers should not implement any power management. In other words,
consumers should implement it as described in the "Using PWMs" section.
Locking
-------
The PWM core list manipulations are protected by a mutex, so pwm_get()
and pwm_put() may not be called from an atomic context.
Most functions in the PWM consumer API might sleep and so must not be called
from atomic context. The notable exception is pwm_apply_atomic() which has the
same semantics as pwm_apply_might_sleep() but can be called from atomic context.
(The price for that is that it doesn't work for all PWM devices, use
pwm_might_sleep() to check if a given PWM supports atomic operation.
Locking in the PWM core ensures that callbacks related to a single chip are
serialized.
Helpers
-------
Currently a PWM can only be configured with period_ns and duty_ns. For several
use cases freq_hz and duty_percent might be better. Instead of calculating
this in your driver please consider adding appropriate helpers to the framework.
3. 한국어 전문 번역
영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.
Linux PWM interface 개요
1-13이 문서는 Linux PWM(Pulse Width Modulation) interface의 개요를 제공합니다. PWM은 휴대전화의 LED, fan, vibrator 등을 제어하는 데 흔히 사용됩니다.
용도가 고정된 PWM은 Linux PWM API를 반드시 구현할 필요가 없습니다. 반면 SoC에 독립된 장치로 들어 있는 PWM은 고정 용도가 없고 board designer가 LED나 fan 같은 consumer에 연결합니다. 이러한 board별 연결 유연성을 제공하기 위해 generic PWM API가 존재합니다.
======================================
Pulse Width Modulation (PWM) interface
======================================
This provides an overview about the Linux PWM interface
PWMs are commonly used for controlling LEDs, fans or vibrators in
cell phones. PWMs with a fixed purpose have no need implementing
the Linux PWM API (although they could). However, PWMs are often
found as discrete devices on SoCs which have no fixed purpose. It's
up to the board designer to connect them to LEDs or fans. To provide
this kind of flexibility the generic PWM API exists.
PWM 식별과 static mapping
14-34Legacy PWM API 사용자는 unique ID로 PWM device를 참조합니다. 새 board setup code는 unique ID를 직접 넘기는 대신 PWM consumer와 provider를 연결하는 static mapping을 등록해야 합니다.
예제의 `struct pwm_lookup board_pwm_lookup[]`는 provider `tegra-pwm`의 channel 0을 consumer `pwm-backlight`에 연결하고, 기준 period 50000과 `PWM_POLARITY_NORMAL`을 지정합니다.
Board 초기화 함수는 `pwm_add_table(board_pwm_lookup, ARRAY_SIZE(board_pwm_lookup))`를 호출해 mapping table을 등록합니다. 이후 consumer는 전역 숫자 ID가 아니라 device 관계를 통해 알맞은 PWM을 찾습니다.
Board mapping이 provider channel과 consumer를 연결합니다.
Identifying PWMs
----------------
Users of the legacy PWM API use unique IDs to refer to PWM devices.
Instead of referring to a PWM device via its unique ID, board setup code
should instead register a static mapping that can be used to match PWM
consumers to providers, as given in the following example::
static struct pwm_lookup board_pwm_lookup[] = {
PWM_LOOKUP("tegra-pwm", 0, "pwm-backlight", NULL,
50000, PWM_POLARITY_NORMAL),
};
static void __init board_init(void)
{
...
pwm_add_table(board_pwm_lookup, ARRAY_SIZE(board_pwm_lookup));
...
}
Consumer 요청과 sleep·atomic 적용
35-57Consumer는 consumer device 또는 consumer name을 `pwm_get()`에 전달해 PWM을 얻고 `pwm_put()`으로 해제합니다. Managed getter로 `devm_pwm_get()`과 `devm_fwnode_pwm_get()`도 제공됩니다.
요청한 PWM은 `pwm_apply_might_sleep(struct pwm_device *pwm, struct pwm_state *state)`로 설정합니다. 이 API는 period와 `duty_cycle`뿐 아니라 enable/disable state까지 한 번에 제어합니다.
PWM이 sleep하지 않는 장치라면 atomic context에서도 사용할 수 있습니다. `pwm_might_sleep()`이 `false`인지 확인한 뒤 `pwm_apply_atomic()`으로 같은 state를 적용합니다.
Using PWMs
----------
Consumers use the pwm_get() function and pass to it the consumer device or a
consumer name. pwm_put() is used to free the PWM device. Managed variants of
the getter, devm_pwm_get() and devm_fwnode_pwm_get(), also exist.
After being requested, a PWM has to be configured using::
int pwm_apply_might_sleep(struct pwm_device *pwm, struct pwm_state *state);
This API controls both the PWM period/duty_cycle config and the
enable/disable state.
PWM devices can be used from atomic context, if the PWM does not sleep. You
can check if this the case with::
bool pwm_might_sleep(struct pwm_device *pwm);
If false, the PWM can also be configured from atomic context with::
int pwm_apply_atomic(struct pwm_device *pwm, struct pwm_state *state);
Disabled 출력, `usage_power`, 요청 state 의미
58-79Consumer는 disabled PWM의 실제 output state에 의존하면 안 됩니다. 가능하면 driver가 inactive state를 출력해야 하지만 일부 hardware는 이를 보장할 수 없습니다. 반드시 inactive output이 필요하면 `.duty_cycle = 0`, `.enabled = true`를 사용합니다.
`usage_power`를 설정하면 driver는 power output만 유지하면 되고 signal waveform은 더 자유롭게 선택할 수 있습니다. Driver가 지원한다면 chip의 개별 channel을 phase shift해 EMI를 줄이는 식으로 signal을 최적화할 수 있습니다.
`pwm_config()`, `pwm_enable()`, `pwm_disable()`은 `pwm_apply_might_sleep()`의 wrapper입니다. 여러 parameter를 함께 바꿔야 할 때는 wrapper를 연속 호출하지 말고 `pwm_apply_might_sleep()` 한 번으로 전환해야 합니다.
`pwm_get_state()`는 마지막 `pwm_apply_might_sleep()` 호출에 전달된 요청 state를 반환합니다. Hardware가 요청을 정확히 만족하지 못했다면 실제 구현 state와 다를 수 있으며, 현재 consumer가 실제 hardware setting을 조회할 방법은 없습니다.
As a consumer, don't rely on the output's state for a disabled PWM. If it's
easily possible, drivers are supposed to emit the inactive state, but some
drivers cannot. If you rely on getting the inactive state, use .duty_cycle=0,
.enabled=true.
There is also a usage_power setting: If set, the PWM driver is only required to
maintain the power output but has more freedom regarding signal form.
If supported by the driver, the signal can be optimized, for example to improve
EMI by phase shifting the individual channels of a chip.
The pwm_config(), pwm_enable() and pwm_disable() functions are just wrappers
around pwm_apply_might_sleep() and should not be used if the user wants to change
several parameter at once. For example, if you see pwm_config() and
pwm_{enable,disable}() calls in the same function, this probably means you
should switch to pwm_apply_might_sleep().
The PWM user API also allows one to query the PWM state that was passed to the
last invocation of pwm_apply_might_sleep() using pwm_get_state(). Note this is
different to what the driver has actually implemented if the request cannot be
satisfied exactly with the hardware in use. There is currently no way for
consumers to get the actually implemented settings.
PWM arguments와 resume 재설정
80-91PWM API는 현재 state 외에 이 PWM에서 기준으로 삼을 reference configuration인 PWM arguments도 제공합니다. 이 값은 보통 platform별로 정해지며, consumer가 전체 period에 대한 상대 duty cycle만 고려하도록 돕습니다. 예를 들어 duty를 period의 50%로 표현할 수 있습니다.
`struct pwm_args`에는 `period`와 `polarity` 두 field가 있습니다. PWM consumer의 probe function에서 초기 PWM configuration을 정할 때 사용하며 `pwm_get_args()`로 가져옵니다.
모든 consumer는 resume 시점에 필요한 PWM configuration을 다시 적용해야 합니다. 그래야 device resume 순서에 맞춰 각 PWM이 올바르게 복원됩니다.
Platform reference arguments를 consumer state로 바꾸고 resume 때 다시 적용합니다.
In addition to the PWM state, the PWM API also exposes PWM arguments, which
are the reference PWM config one should use on this PWM.
PWM arguments are usually platform-specific and allows the PWM user to only
care about dutycycle relatively to the full period (like, duty = 50% of the
period). struct pwm_args contains 2 fields (period and polarity) and should
be used to set the initial PWM config (usually done in the probe function
of the PWM user). PWM arguments are retrieved with pwm_get_args().
All consumers should really be reconfiguring the PWM upon resume as
appropriate. This is the only way to ensure that everything is resumed in
the proper order.
Sysfs controller와 channel export
92-110Kernel에서 `CONFIG_SYSFS`가 활성화되면 userspace용 단순 PWM sysfs interface가 `/sys/class/pwm/`에 제공됩니다. Probe된 PWM controller 또는 chip은 `pwmchipN`으로 노출되며, `N`은 PWM chip의 base입니다.
각 `pwmchipN` directory의 `npwm`은 chip이 지원하는 channel 수를 읽기 전용으로 보여 줍니다. 쓰기 전용 `export`는 channel을 sysfs로 내보내고, `unexport`는 다시 제거합니다.
PWM channel 번호는 chip마다 0부터 `npwm - 1`까지의 index를 사용합니다.
Using PWMs with the sysfs interface
-----------------------------------
If CONFIG_SYSFS is enabled in your kernel configuration a simple sysfs
interface is provided to use the PWMs from userspace. It is exposed at
/sys/class/pwm/. Each probed PWM controller/chip will be exported as
pwmchipN, where N is the base of the PWM chip. Inside the directory you
will find:
npwm
The number of PWM channels this chip supports (read-only).
export
Exports a PWM channel for use with sysfs (write-only).
unexport
Unexports a PWM channel from sysfs (write-only).
The PWM channels are numbered using a per-chip index from 0 to npwm-1.
Sysfs channel property
111-136PWM channel을 export하면 연결된 `pwmchipN` 아래에 channel 번호 `X`를 사용한 `pwmX` directory가 만들어집니다. 이 directory에서 signal state를 구성합니다.
`period`는 active time과 inactive time의 합인 전체 PWM period이며 nanosecond 단위의 읽기/쓰기 값입니다. `duty_cycle`은 active time이며 역시 nanosecond 단위이고 `period`보다 클 수 없습니다.
`polarity`는 signal polarity를 바꾸는 읽기/쓰기 속성입니다. PWM chip이 polarity 변경을 지원할 때만 쓰기가 동작하며 값은 `normal` 또는 `inversed`입니다. `enable`에는 `0`을 써서 비활성화하고 `1`을 써서 활성화합니다.
When a PWM channel is exported a pwmX directory will be created in the
pwmchipN directory it is associated with, where X is the number of the
channel that was exported. The following properties will then be available:
period
The total period of the PWM signal (read/write).
Value is in nanoseconds and is the sum of the active and inactive
time of the PWM.
duty_cycle
The active time of the PWM signal (read/write).
Value is in nanoseconds and must be less than or equal to the period.
polarity
Changes the polarity of the PWM signal (read/write).
Writes to this property only work if the PWM chip supports changing
the polarity.
Value is the string "normal" or "inversed".
enable
Enable/disable the PWM signal (read/write).
- 0 - disabled
- 1 - enabled
Generic PWM driver 등록
137-152PWM driver 구현 방식은 전통적인 barebone API와 generic PWM framework 두 가지가 있습니다. Barebone 방식에서는 각 driver가 `pwm_*()` function을 직접 구현하며 system에 여러 PWM driver를 둘 수 없습니다. 따라서 새 driver는 반드시 generic PWM framework를 사용해야 합니다.
새 PWM controller 또는 chip은 `pwmchip_alloc()`으로 할당하고 `pwmchip_add()`로 등록하며 `pwmchip_remove()`로 제거합니다. `pwmchip_alloc()`을 되돌릴 때는 `pwmchip_put()`을 사용합니다.
`pwmchip_add()`에 전달하는 `struct pwm_chip`은 PWM chip 설명, chip이 제공하는 PWM device 수, framework가 호출할 chip-specific PWM operation 구현을 담습니다.
Generic framework에서 chip을 할당, 기술, 등록하고 역순으로 해제합니다.
Implementing a PWM driver
-------------------------
Currently there are two ways to implement pwm drivers. Traditionally
there only has been the barebone API meaning that each driver has
to implement the pwm_*() functions itself. This means that it's impossible
to have multiple PWM drivers in the system. For this reason it's mandatory
for new drivers to use the generic PWM framework.
A new PWM controller/chip can be allocated using pwmchip_alloc(), then
registered using pwmchip_add() and removed again with pwmchip_remove(). To undo
pwmchip_alloc() use pwmchip_put(). pwmchip_add() takes a filled in struct
pwm_chip as argument which provides a description of the PWM chip, the number
of PWM devices provided by the chip and the chip-specific implementation of the
supported PWM operations to the framework.
Polarity convention과 provider operation
153-171PWM driver가 polarity를 지원할 때는 framework의 signal convention을 지켜야 합니다. Normal polarity는 duty cycle 동안 high로 시작하고 period의 나머지 동안 low입니다. Inversed polarity는 duty cycle 동안 low로 시작하고 나머지 동안 high입니다.
Driver는 legacy `->enable()`, `->disable()`, `->config()` 대신 `->apply()`를 구현하는 것이 권장됩니다. 하나의 configuration workflow에 atomicity를 제공하므로 regulator 같은 critical device를 PWM이 제어할 때 필요합니다.
초기 PWM state를 읽는 `->get_state()` 구현도 권장됩니다. Consumer가 현재 state를 알면 불필요한 전환과 glitch를 피할 수 있습니다.
PWM driver 자체는 power management를 구현하지 않아야 합니다. Suspend와 resume에 따른 복원은 앞의 consumer 규칙대로 consumer가 담당합니다.
When implementing polarity support in a PWM driver, make sure to respect the
signal conventions in the PWM framework. By definition, normal polarity
characterizes a signal starts high for the duration of the duty cycle and
goes low for the remainder of the period. Conversely, a signal with inversed
polarity starts low for the duration of the duty cycle and goes high for the
remainder of the period.
Drivers are encouraged to implement ->apply() instead of the legacy
->enable(), ->disable() and ->config() methods. Doing that should provide
atomicity in the PWM config workflow, which is required when the PWM controls
a critical device (like a regulator).
The implementation of ->get_state() (a method used to retrieve initial PWM
state) is also encouraged for the same reason: letting the PWM user know
about the current PWM state would allow him to avoid glitches.
Drivers should not implement any power management. In other words,
consumers should implement it as described in the "Using PWMs" section.
PWM core locking과 atomic context
172-185PWM core list 조작은 mutex로 보호되므로 `pwm_get()`과 `pwm_put()`을 atomic context에서 호출할 수 없습니다. PWM consumer API의 대부분도 sleep할 수 있어 atomic context에서 사용할 수 없습니다.
중요한 예외는 `pwm_apply_atomic()`입니다. `pwm_apply_might_sleep()`과 semantics는 같지만 atomic context에서 호출할 수 있습니다. 대신 모든 PWM device에서 동작하지 않으므로 `pwm_might_sleep()`으로 해당 장치의 atomic operation 지원 여부를 확인해야 합니다.
PWM core의 locking은 하나의 chip과 관련된 callback이 서로 겹치지 않고 serialized되도록 보장합니다.
Locking
-------
The PWM core list manipulations are protected by a mutex, so pwm_get()
and pwm_put() may not be called from an atomic context.
Most functions in the PWM consumer API might sleep and so must not be called
from atomic context. The notable exception is pwm_apply_atomic() which has the
same semantics as pwm_apply_might_sleep() but can be called from atomic context.
(The price for that is that it doesn't work for all PWM devices, use
pwm_might_sleep() to check if a given PWM supports atomic operation.
Locking in the PWM core ensures that callbacks related to a single chip are
serialized.
주파수·백분율 helper 확장
186-191현재 PWM은 `period_ns`와 `duty_ns`로만 설정할 수 있습니다. 일부 use case에서는 `freq_hz`와 `duty_percent`가 더 자연스럽습니다.
이 변환을 각 driver에서 따로 계산하지 말고 framework에 적절한 helper를 추가하는 방식을 고려해야 합니다. 공통 계산을 framework에 모으면 단위 변환과 rounding 정책을 일관되게 유지할 수 있습니다.
Helpers
-------
Currently a PWM can only be configured with period_ns and duty_ns. For several
use cases freq_hz and duty_percent might be better. Instead of calculating
this in your driver please consider adding appropriate helpers to the framework.
요약과 해설
pwm.rst:1-191Generic PWM API는 board별 provider-consumer mapping, 요청 state의 일괄 적용, sysfs channel 제어와 여러 provider의 공존을 지원합니다. Consumer는 실제 hardware state와 요청 state를 구분하고 resume 때 재설정해야 하며, provider는 `->apply()`와 `->get_state()`를 구현하고 polarity·locking convention을 지켜야 합니다.