← Documents Documentation/userspace-api/gpio/sysfs.rst GitHub 원문 ↗

Linux 6.18.37 · Userspace API

Userspace용 GPIO sysfs 인터페이스

폐기된 GPIO sysfs ABI의 export, gpioN 속성, edge poll, gpiochip 정보와 kernel export 함수를 설명합니다.

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

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

1. 요약·해설

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

요약·해설

sysfs.rst:1-171

폐기된 GPIO sysfs ABI의 export, gpioN 속성, edge poll, gpiochip 정보와 kernel export 함수를 설명합니다.

원문의 경로, 함수명, symbol, 문서 링크, 표와 줄 좌표를 보존해 전문 번역했습니다.

2. 영어 원문 전체

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

원문 전체 펼치기
1 GPIO Sysfs Interface for Userspace
2 ==================================
3
4 .. warning::
5 This API is obsoleted by the chardev.rst and the ABI documentation has
6 been moved to Documentation/ABI/obsolete/sysfs-gpio.
7
8 New developments should use the chardev.rst, and existing developments are
9 encouraged to migrate as soon as possible, as this API will be removed
10 in the future.
11
12 This interface will continue to be maintained for the migration period,
13 but new features will only be added to the new API.
14
15 The obsolete sysfs ABI
16 ----------------------
17 Platforms which use the "gpiolib" implementors framework may choose to
18 configure a sysfs user interface to GPIOs. This is different from the
19 debugfs interface, since it provides control over GPIO direction and
20 value instead of just showing a gpio state summary. Plus, it could be
21 present on production systems without debugging support.
22
23 Given appropriate hardware documentation for the system, userspace could
24 know for example that GPIO #23 controls the write protect line used to
25 protect boot loader segments in flash memory. System upgrade procedures
26 may need to temporarily remove that protection, first importing a GPIO,
27 then changing its output state, then updating the code before re-enabling
28 the write protection. In normal use, GPIO #23 would never be touched,
29 and the kernel would have no need to know about it.
30
31 Again depending on appropriate hardware documentation, on some systems
32 userspace GPIO can be used to determine system configuration data that
33 standard kernels won't know about. And for some tasks, simple userspace
34 GPIO drivers could be all that the system really needs.
35
36 .. note::
37 Do NOT abuse sysfs to control hardware that has proper kernel drivers.
38 Please read Documentation/driver-api/gpio/drivers-on-gpio.rst
39 to avoid reinventing kernel wheels in userspace.
40
41 I MEAN IT. REALLY.
42
43 Paths in Sysfs
44 --------------
45 There are three kinds of entries in /sys/class/gpio:
46
47 - Control interfaces used to get userspace control over GPIOs;
48
49 - GPIOs themselves; and
50
51 - GPIO controllers ("gpio_chip" instances).
52
53 That's in addition to standard files including the "device" symlink.
54
55 The control interfaces are write-only:
56
57 /sys/class/gpio/
58
59 "export" ...
60 Userspace may ask the kernel to export control of
61 a GPIO to userspace by writing its number to this file.
62
63 Example: "echo 19 > export" will create a "gpio19" node
64 for GPIO #19, if that's not requested by kernel code.
65
66 "unexport" ...
67 Reverses the effect of exporting to userspace.
68
69 Example: "echo 19 > unexport" will remove a "gpio19"
70 node exported using the "export" file.
71
72 GPIO signals have paths like /sys/class/gpio/gpio42/ (for GPIO #42)
73 and have the following read/write attributes:
74
75 /sys/class/gpio/gpioN/
76
77 "direction" ...
78 reads as either "in" or "out". This value may
79 normally be written. Writing as "out" defaults to
80 initializing the value as low. To ensure glitch free
81 operation, values "low" and "high" may be written to
82 configure the GPIO as an output with that initial value.
83
84 Note that this attribute *will not exist* if the kernel
85 doesn't support changing the direction of a GPIO, or
86 it was exported by kernel code that didn't explicitly
87 allow userspace to reconfigure this GPIO's direction.
88
89 "value" ...
90 reads as either 0 (inactive) or 1 (active). If the GPIO
91 is configured as an output, this value may be written;
92 any nonzero value is treated as active.
93
94 If the pin can be configured as interrupt-generating interrupt
95 and if it has been configured to generate interrupts (see the
96 description of "edge"), you can poll(2) on that file and
97 poll(2) will return whenever the interrupt was triggered. If
98 you use poll(2), set the events POLLPRI and POLLERR. If you
99 use select(2), set the file descriptor in exceptfds. After
100 poll(2) returns, use pread(2) to read the value at offset
101 zero. Alternatively, either lseek(2) to the beginning of the
102 sysfs file and read the new value or close the file and
103 re-open it to read the value.
104
105 "edge" ...
106 reads as either "none", "rising", "falling", or
107 "both". Write these strings to select the signal edge(s)
108 that will make poll(2) on the "value" file return.
109
110 This file exists only if the pin can be configured as an
111 interrupt generating input pin.
112
113 "active_low" ...
114 reads as either 0 (false) or 1 (true). Write
115 any nonzero value to invert the value attribute both
116 for reading and writing. Existing and subsequent
117 poll(2) support configuration via the edge attribute
118 for "rising" and "falling" edges will follow this
119 setting.
120
121 GPIO controllers have paths like /sys/class/gpio/gpiochip42/ (for the
122 controller implementing GPIOs starting at #42) and have the following
123 read-only attributes:
124
125 /sys/class/gpio/gpiochipN/
126
127 "base" ...
128 same as N, the first GPIO managed by this chip
129
130 "label" ...
131 provided for diagnostics (not always unique)
132
133 "ngpio" ...
134 how many GPIOs this manages (N to N + ngpio - 1)
135
136 Board documentation should in most cases cover what GPIOs are used for
137 what purposes. However, those numbers are not always stable; GPIOs on
138 a daughtercard might be different depending on the base board being used,
139 or other cards in the stack. In such cases, you may need to use the
140 gpiochip nodes (possibly in conjunction with schematics) to determine
141 the correct GPIO number to use for a given signal.
142
143
144 Exporting from Kernel code
145 --------------------------
146 Kernel code can explicitly manage exports of GPIOs which have already been
147 requested using gpio_request()::
148
149 /* export the GPIO to userspace */
150 int gpiod_export(struct gpio_desc *desc, bool direction_may_change);
151
152 /* reverse gpiod_export() */
153 void gpiod_unexport(struct gpio_desc *desc);
154
155 /* create a sysfs link to an exported GPIO node */
156 int gpiod_export_link(struct device *dev, const char *name,
157 struct gpio_desc *desc);
158
159 After a kernel driver requests a GPIO, it may only be made available in
160 the sysfs interface by gpiod_export(). The driver can control whether the
161 signal direction may change. This helps drivers prevent userspace code
162 from accidentally clobbering important system state.
163
164 This explicit exporting can help with debugging (by making some kinds
165 of experiments easier), or can provide an always-there interface that's
166 suitable for documenting as part of a board support package.
167
168 After the GPIO has been exported, gpiod_export_link() allows creating
169 symlinks from elsewhere in sysfs to the GPIO sysfs node. Drivers can
170 use this to provide the interface under their own device in sysfs with
171 a descriptive name.
172

3. 한국어 전문 번역

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

폐기 경고와 이전 지침

1-14

GPIO sysfs API는 `chardev.rst`의 character device API로 대체되었으며 ABI 명세는 `Documentation/ABI/obsolete/sysfs-gpio`로 이동했습니다.

새 개발은 character device API를 사용해야 합니다. 기존 개발도 이 API가 향후 제거될 예정이므로 가능한 빨리 이전하는 것이 권장됩니다.

이전 기간에는 sysfs 인터페이스를 유지보수하지만 새 기능은 새 character device API에만 추가됩니다. 따라서 이 문서는 신규 설계 지침이 아니라 레거시 동작의 보존 설명입니다.

GPIO API 상태
항목설명
sysfs ABI폐기됨, 이전 기간에만 유지보수
ABI 원문 위치Documentation/ABI/obsolete/sysfs-gpio
Character device API새 개발과 새 기능의 기준
기존 프로그램가능한 빠른 이전 권장

유지보수와 기능 개발의 경계를 분명히 합니다.

GPIO Sysfs Interface for Userspace
==================================

.. warning::
   This API is obsoleted by the chardev.rst and the ABI documentation has
   been moved to Documentation/ABI/obsolete/sysfs-gpio.

   New developments should use the chardev.rst, and existing developments are
   encouraged to migrate as soon as possible, as this API will be removed
   in the future.

   This interface will continue to be maintained for the migration period,
   but new features will only be added to the new API.

구형 sysfs ABI의 목적과 사용 한계

15-42

`gpiolib` 구현 프레임워크를 사용하는 platform은 선택적으로 GPIO sysfs userspace 인터페이스를 구성할 수 있습니다. 상태 요약만 표시하는 debugfs와 달리, sysfs는 GPIO 방향과 값을 제어하며 debugging 지원이 없는 production system에도 존재할 수 있습니다.

정확한 hardware 문서가 있다면 userspace는 특정 전역 GPIO 번호의 용도를 알고 export한 뒤 방향과 출력 값을 조작할 수 있습니다. 예를 들어 firmware update 동안 flash write-protect line을 잠시 해제하고 작업 뒤 다시 활성화하는 절차가 가능합니다.

Kernel이 알 수 없는 board configuration을 GPIO 입력으로 읽거나 아주 단순한 userspace GPIO driver를 만드는 용도로도 쓰였습니다. 그러나 올바른 kernel driver가 존재하는 hardware를 sysfs에서 직접 제어해서는 안 됩니다.

원문은 `Documentation/driver-api/gpio/drivers-on-gpio.rst`를 읽고 kernel 기능을 userspace에서 재구현하지 말라고 강하게 경고합니다. 이 제한은 장치 소유권, 동시성, 전원 관리와 오류 복구를 kernel driver가 책임져야 하기 때문입니다.

레거시 sysfs GPIO 사용 판단
대상 hardware의 kernel driver 확인Driver가 있으면 해당 subsystem API 사용없고 board 문서가 정확한지 확인레거시 호환 필요 여부 확인가능하면 character device API로 이전

기존 시스템이라도 kernel driver 우선 원칙을 적용합니다.

sysfs와 debugfs
항목설명
sysfs GPIO방향과 값 제어, production에 존재 가능
debugfs GPIO상태 요약과 debugging 중심
적절한 kernel driversysfs 직접 제어보다 우선
필수 전제정확한 hardware와 board 문서

두 파일시스템의 목적은 서로 다릅니다.

The obsolete sysfs ABI
----------------------
Platforms which use the "gpiolib" implementors framework may choose to
configure a sysfs user interface to GPIOs. This is different from the
debugfs interface, since it provides control over GPIO direction and
value instead of just showing a gpio state summary. Plus, it could be
present on production systems without debugging support.

Given appropriate hardware documentation for the system, userspace could
know for example that GPIO #23 controls the write protect line used to
protect boot loader segments in flash memory. System upgrade procedures
may need to temporarily remove that protection, first importing a GPIO,
then changing its output state, then updating the code before re-enabling
the write protection. In normal use, GPIO #23 would never be touched,
and the kernel would have no need to know about it.

Again depending on appropriate hardware documentation, on some systems
userspace GPIO can be used to determine system configuration data that
standard kernels won't know about. And for some tasks, simple userspace
GPIO drivers could be all that the system really needs.

.. note::
   Do NOT abuse sysfs to control hardware that has proper kernel drivers.
   Please read Documentation/driver-api/gpio/drivers-on-gpio.rst
   to avoid reinventing kernel wheels in userspace.

   I MEAN IT. REALLY.

/sys/class/gpio와 export 제어

43-70

`/sys/class/gpio`에는 userspace 제어를 획득하는 control interface, export된 개별 GPIO, GPIO controller인 `gpio_chip` instance의 세 종류 항목이 있습니다. 표준 `device` symlink 같은 공통 sysfs 파일도 함께 존재합니다.

Write-only `export` 파일에 GPIO 번호를 쓰면 kernel code가 이미 요청하지 않은 GPIO를 userspace에 export합니다. 예를 들어 `echo 19 > export`는 `/sys/class/gpio/gpio19` node를 만듭니다.

Write-only `unexport` 파일은 그 동작을 되돌립니다. `echo 19 > unexport`는 `export`로 만든 `gpio19` node를 제거합니다.

/sys/class/gpio 항목
항목설명
exportGPIO 번호를 받아 gpioN node 생성
unexportexport된 gpioN node 제거
gpioN/개별 GPIO 방향·값·edge 속성
gpiochipN/GPIO controller 정보
device표준 sysfs device symlink

제어 파일과 생성되는 객체 node를 구분합니다.

GPIO 19 export 수명
echo 19 > exportKernel 요청 충돌 확인/sys/class/gpio/gpio19 생성속성으로 제어echo 19 > unexportgpio19 node 제거

전역 번호를 userspace node로 노출하고 다시 회수합니다.

Paths in Sysfs
--------------
There are three kinds of entries in /sys/class/gpio:

   -	Control interfaces used to get userspace control over GPIOs;

   -	GPIOs themselves; and

   -	GPIO controllers ("gpio_chip" instances).

That's in addition to standard files including the "device" symlink.

The control interfaces are write-only:

    /sys/class/gpio/

	"export" ...
		Userspace may ask the kernel to export control of
		a GPIO to userspace by writing its number to this file.

		Example:  "echo 19 > export" will create a "gpio19" node
		for GPIO #19, if that's not requested by kernel code.

	"unexport" ...
		Reverses the effect of exporting to userspace.

		Example:  "echo 19 > unexport" will remove a "gpio19"
		node exported using the "export" file.

gpioN의 direction, value, edge, active_low

71-120

개별 signal은 `/sys/class/gpio/gpioN/` 경로에 나타납니다. `direction`은 `in` 또는 `out`을 읽고 쓸 수 있습니다. `out`은 초기 값을 low로 설정하며, glitch를 피하려면 `low` 또는 `high`를 직접 써서 출력 방향과 초기 값을 한 번에 구성합니다.

Kernel이 방향 변경을 지원하지 않거나 kernel code가 export하면서 userspace 방향 변경을 명시적으로 허용하지 않았다면 `direction` 파일은 존재하지 않습니다.

`value`는 inactive 0 또는 active 1을 읽습니다. 출력 GPIO에서는 쓸 수도 있고 0이 아닌 값은 active로 처리됩니다. Interrupt 입력과 `edge`가 구성된 경우 `value` 파일을 `poll(2)`할 수 있습니다.

`poll(2)`에서는 `POLLPRI | POLLERR`를 요청하고 `select(2)`에서는 descriptor를 `exceptfds`에 둡니다. 알림 뒤에는 `pread(2)`로 offset 0을 읽거나, `lseek(2)`로 처음으로 이동한 뒤 읽거나, 파일을 닫고 다시 열어 새 값을 읽습니다.

`edge`는 `none`, `rising`, `falling`, `both` 중 하나이며 어떤 signal edge가 `value`의 `poll(2)`을 깨울지 정합니다. Interrupt 생성 입력으로 구성할 수 있는 pin에서만 이 파일이 존재합니다.

`active_low`는 0 또는 1입니다. 0이 아닌 값을 쓰면 읽기와 쓰기 모두에서 `value`의 논리 극성을 뒤집습니다. 이미 설정된 edge와 이후 설정할 rising/falling의 `poll(2)` 동작도 이 논리 극성을 따릅니다.

gpioN 속성
항목설명
directionin/out 읽기·쓰기, low/high로 glitch 없는 초기화
value0 inactive, 1 active; 출력에서는 쓰기 가능
edgenone/rising/falling/both; interrupt 입력만
active_low0/1; value와 edge의 논리 극성 반전
direction 없음Hardware 또는 export 정책이 변경을 금지
value pollPOLLPRI | POLLERR 또는 select exceptfds

각 파일의 값, 쓰기 가능 여부와 제약을 요약합니다.

sysfs edge 알림 읽기
edge에 rising/falling/both 기록value fd에서 POLLPRI | POLLERR로 pollInterrupt 발생과 poll 반환pread(fd, ..., 0) 수행또는 lseek(0) 후 read새 논리 value 처리

알림 후 파일 offset을 다시 0으로 맞춰 값을 읽습니다.


GPIO signals have paths like /sys/class/gpio/gpio42/ (for GPIO #42)
and have the following read/write attributes:

    /sys/class/gpio/gpioN/

	"direction" ...
		reads as either "in" or "out". This value may
		normally be written. Writing as "out" defaults to
		initializing the value as low. To ensure glitch free
		operation, values "low" and "high" may be written to
		configure the GPIO as an output with that initial value.

		Note that this attribute *will not exist* if the kernel
		doesn't support changing the direction of a GPIO, or
		it was exported by kernel code that didn't explicitly
		allow userspace to reconfigure this GPIO's direction.

	"value" ...
		reads as either 0 (inactive) or 1 (active). If the GPIO
		is configured as an output, this value may be written;
		any nonzero value is treated as active.

		If the pin can be configured as interrupt-generating interrupt
		and if it has been configured to generate interrupts (see the
		description of "edge"), you can poll(2) on that file and
		poll(2) will return whenever the interrupt was triggered. If
		you use poll(2), set the events POLLPRI and POLLERR. If you
		use select(2), set the file descriptor in exceptfds. After
		poll(2) returns, use pread(2) to read the value at offset
		zero. Alternatively, either lseek(2) to the beginning of the
		sysfs file and read the new value or close the file and
		re-open it to read the value.

	"edge" ...
		reads as either "none", "rising", "falling", or
		"both". Write these strings to select the signal edge(s)
		that will make poll(2) on the "value" file return.

		This file exists only if the pin can be configured as an
		interrupt generating input pin.

	"active_low" ...
		reads as either 0 (false) or 1 (true). Write
		any nonzero value to invert the value attribute both
		for reading and writing. Existing and subsequent
		poll(2) support configuration via the edge attribute
		for "rising" and "falling" edges will follow this
		setting.

gpiochipN controller 속성과 번호 찾기

121-143

GPIO controller는 `/sys/class/gpio/gpiochipN/` 경로를 사용하며 N은 이 chip이 관리하는 첫 전역 GPIO 번호입니다. 속성은 모두 read-only입니다.

`base`는 N과 같은 첫 GPIO 번호, `label`은 진단용 이름으로 유일하지 않을 수 있으며, `ngpio`는 controller가 관리하는 GPIO 개수입니다. 따라서 번호 범위는 N부터 `N + ngpio - 1`까지입니다.

GPIO 전역 번호는 daughtercard, base board, card stack 구성에 따라 안정적이지 않을 수 있습니다. 이 경우 board 문서와 schematic, `gpiochip` node 정보를 함께 사용해 원하는 signal의 올바른 번호를 찾아야 합니다.

gpiochipN 속성
항목설명
base첫 전역 GPIO 번호 N
label진단용 controller label, 유일하지 않을 수 있음
ngpio관리하는 GPIO 개수
번호 범위N .. N + ngpio - 1
속성 접근모두 read-only

Controller의 전역 번호 범위와 진단 정보를 제공합니다.

GPIO controllers have paths like /sys/class/gpio/gpiochip42/ (for the
controller implementing GPIOs starting at #42) and have the following
read-only attributes:

    /sys/class/gpio/gpiochipN/

	"base" ...
		same as N, the first GPIO managed by this chip

	"label" ...
		provided for diagnostics (not always unique)

	"ngpio" ...
		how many GPIOs this manages (N to N + ngpio - 1)

Board documentation should in most cases cover what GPIOs are used for
what purposes. However, those numbers are not always stable; GPIOs on
a daughtercard might be different depending on the base board being used,
or other cards in the stack. In such cases, you may need to use the
gpiochip nodes (possibly in conjunction with schematics) to determine
the correct GPIO number to use for a given signal.

Kernel code의 export 관리

144-171

Kernel driver는 먼저 `gpio_request()`로 GPIO를 요청한 뒤 `gpiod_export(struct gpio_desc *desc, bool direction_may_change)`로 sysfs에 노출할 수 있습니다. `direction_may_change`로 userspace의 방향 변경 허용 여부를 제어합니다.

`gpiod_unexport(struct gpio_desc *desc)`는 export를 되돌립니다. `gpiod_export_link(struct device *dev, const char *name, struct gpio_desc *desc)`는 다른 sysfs 위치에서 export된 GPIO node로 가는 symlink를 만듭니다.

명시적 export는 중요한 system state를 userspace가 실수로 손상하지 못하도록 driver가 방향 정책을 제한하면서 debugging 실험이나 board support package의 상시 interface를 제공할 수 있게 합니다.

Export 뒤 driver는 자신의 device 아래에 설명적인 이름의 symlink를 만들어 전역 `gpioN` 번호보다 의미 있는 접근 경로를 제공할 수 있습니다.

Kernel GPIO sysfs export 함수
항목설명
gpio_request()Kernel driver가 GPIO 소유권 요청
gpiod_export()요청된 GPIO를 sysfs에 노출
direction_may_changeUserspace 방향 변경 허용 여부
gpiod_export_link()다른 sysfs 위치에 설명적 symlink 생성
gpiod_unexport()sysfs 노출 회수

요청, 노출, link, 회수의 역할을 구분합니다.

Kernel 관리 export
gpio_request()로 GPIO 요청gpiod_export()로 node 생성방향 변경 정책 적용필요하면 gpiod_export_link() 생성Userspace가 제한된 범위에서 사용gpiod_unexport()로 회수

Driver가 소유권과 정책을 유지한 채 userspace node를 제공합니다.

Exporting from Kernel code
--------------------------
Kernel code can explicitly manage exports of GPIOs which have already been
requested using gpio_request()::

	/* export the GPIO to userspace */
	int gpiod_export(struct gpio_desc *desc, bool direction_may_change);

	/* reverse gpiod_export() */
	void gpiod_unexport(struct gpio_desc *desc);

	/* create a sysfs link to an exported GPIO node */
	int gpiod_export_link(struct device *dev, const char *name,
		      struct gpio_desc *desc);

After a kernel driver requests a GPIO, it may only be made available in
the sysfs interface by gpiod_export(). The driver can control whether the
signal direction may change. This helps drivers prevent userspace code
from accidentally clobbering important system state.

This explicit exporting can help with debugging (by making some kinds
of experiments easier), or can provide an always-there interface that's
suitable for documenting as part of a board support package.

After the GPIO has been exported, gpiod_export_link() allows creating
symlinks from elsewhere in sysfs to the GPIO sysfs node. Drivers can
use this to provide the interface under their own device in sysfs with
a descriptive name.