diff options
| author | Linus Torvalds <torvalds@linux-foundation.org> | 2026-02-09 20:53:18 -0800 |
|---|---|---|
| committer | Linus Torvalds <torvalds@linux-foundation.org> | 2026-02-09 20:53:18 -0800 |
| commit | 72c395024dac5e215136cbff793455f065603b06 (patch) | |
| tree | 4c7bb2eaab08e2e827607effdedcb42f808e496c | |
| parent | 0c61526621ec1916527d6f6226d8a466340cca22 (diff) | |
| parent | 0a83293322fde69f1fb4722bd3c79c2d52eef436 (diff) | |
Merge tag 'docs-7.0' of git://git.kernel.org/pub/scm/linux/kernel/git/docs/linux
Pull documentation updates from Jonathan Corbet:
"A slightly calmer cycle for docs this time around, though there is
still a fair amount going on, including:
- Some signs of life on the long-moribund Japanese translation
- Documentation on policies around the use of generative tools for
patch submissions, and a separate document intended for consumption
by generative tools
- The completion of the move of the documentation tools to
tools/docs. For now we're leaving a /scripts/kernel-doc symlink
behind to avoid breaking scripts
- Ongoing build-system work includes the incorporation of
documentation in Python code, better support for documenting
variables, and lots of improvements and fixes
- Automatic linking of man-page references -- cat(1), for example --
to the online pages in the HTML build
...and the usual array of typo fixes and such"
* tag 'docs-7.0' of git://git.kernel.org/pub/scm/linux/kernel/git/docs/linux: (107 commits)
doc: development-process: add notice on testing
tools: sphinx-build-wrapper: improve its help message
docs: sphinx-build-wrapper: allow -v override -q
docs: kdoc: Fix pdfdocs build for tools
docs: ja_JP: process: translate 'Obtain a current source tree'
docs: fix 're-use' -> 'reuse' in documentation
docs: ioctl-number: fix a typo in ioctl-number.rst
docs: filesystems: ensure proc pid substitutable is complete
docs: automarkup.py: Skip common English words as C identifiers
Documentation: use a source-read extension for the index link boilerplate
docs: parse_features: make documentation more consistent
docs: add parse_features module documentation
docs: jobserver: do some documentation improvements
docs: add jobserver module documentation
docs: kabi: helpers: add documentation for each "enum" value
docs: kabi: helpers: add helper for debug bits 7 and 8
docs: kabi: system_symbols: end docstring phrases with a dot
docs: python: abi_regex: do some improvements at documentation
docs: python: abi_parser: do some improvements at documentation
docs: add kabi modules documentation
...
227 files changed, 1806 insertions, 4378 deletions
@@ -695,7 +695,7 @@ S: USA N: Chih-Jen Chang E: chihjenc@scf.usc.edu E: chihjen@iis.sinica.edu.tw -D: IGMP(Internet Group Management Protocol) version 2 +D: IGMP (Internet Group Management Protocol) version 2 S: 3F, 65 Tajen street S: Tamsui town, Taipei county, S: Taiwan 251 @@ -1997,7 +1997,7 @@ E: bkaindl@netway.at E: edv@bartelt.via.at D: Author of a menu based configuration tool, kmenu, which D: is the predecessor of 'make menuconfig' and 'make xconfig'. -D: digiboard driver update(modularisation work and 2.1.x upd) +D: digiboard driver update (modularisation work and 2.1.x upd) S: Tallak 95 S: 8103 Rein S: Austria @@ -3613,7 +3613,7 @@ S: Finland N: Deepak Saxena E: dsaxena@plexity.net D: I2O kernel layer (config, block, core, pci, net). I2O disk support for LILO -D: XScale(IOP, IXP) porting and other random ARM bits +D: XScale (IOP, IXP) porting and other random ARM bits S: Portland, OR N: Eric Schenk @@ -3990,7 +3990,7 @@ S: D-50968 Köln N: Tsu-Sheng Tsao E: tsusheng@scf.usc.edu -D: IGMP(Internet Group Management Protocol) version 2 +D: IGMP (Internet Group Management Protocol) version 2 S: 2F 14 ALY 31 LN 166 SEC 1 SHIH-PEI RD S: Taipei S: Taiwan 112 diff --git a/Documentation/ABI/testing/pstore b/Documentation/ABI/testing/pstore index d3cff4a7ee10..dfe2d9801c3a 100644 --- a/Documentation/ABI/testing/pstore +++ b/Documentation/ABI/testing/pstore @@ -26,7 +26,7 @@ Description: Generic interface to platform dependent persistent storage. Once the information in a file has been read, removing the file will signal to the underlying persistent storage - device that it can reclaim the space for later re-use:: + device that it can reclaim the space for later reuse:: $ rm /sys/fs/pstore/dmesg-erst-1 diff --git a/Documentation/Makefile b/Documentation/Makefile index e96ac6dcac4f..377a449656c8 100644 --- a/Documentation/Makefile +++ b/Documentation/Makefile @@ -98,7 +98,8 @@ dochelp: @echo ' cleandocs - clean all generated files' @echo @echo ' make SPHINXDIRS="s1 s2" [target] Generate only docs of folder s1, s2' - @echo ' top level values for SPHINXDIRS are: $(_SPHINXDIRS)' + @echo ' top level values for SPHINXDIRS are:' + @echo '$(_SPHINXDIRS)' | fmt -s -w 75 -g 75 | sed 's/^/ /' @echo ' you may also use a subdirectory like SPHINXDIRS=userspace-api/media,' @echo ' provided that there is an index.rst file at the subdirectory.' @echo diff --git a/Documentation/RCU/index.rst b/Documentation/RCU/index.rst index ef26c78507d3..035871687ee2 100644 --- a/Documentation/RCU/index.rst +++ b/Documentation/RCU/index.rst @@ -28,10 +28,3 @@ RCU Handbook Design/Expedited-Grace-Periods/Expedited-Grace-Periods Design/Requirements/Requirements Design/Data-Structures/Data-Structures - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/accel/index.rst b/Documentation/accel/index.rst index d8fa332d60a8..cbc7d4c3876a 100644 --- a/Documentation/accel/index.rst +++ b/Documentation/accel/index.rst @@ -11,10 +11,3 @@ Compute Accelerators amdxdna/index qaic/index rocket/index - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/admin-guide/README.rst b/Documentation/admin-guide/README.rst index 05301f03b717..77fec1de6dc8 100644 --- a/Documentation/admin-guide/README.rst +++ b/Documentation/admin-guide/README.rst @@ -53,7 +53,7 @@ Documentation these typically contain kernel-specific installation notes for some drivers for example. Please read the :ref:`Documentation/process/changes.rst <changes>` file, as it - contains information about the problems, which may result by upgrading + contains information about the problems which may result from upgrading your kernel. Installing the kernel source diff --git a/Documentation/admin-guide/aoe/index.rst b/Documentation/admin-guide/aoe/index.rst index d71c5df15922..564354bbce57 100644 --- a/Documentation/admin-guide/aoe/index.rst +++ b/Documentation/admin-guide/aoe/index.rst @@ -8,10 +8,3 @@ ATA over Ethernet (AoE) aoe todo examples - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/admin-guide/auxdisplay/index.rst b/Documentation/admin-guide/auxdisplay/index.rst index e466f0595248..31eae08255fd 100644 --- a/Documentation/admin-guide/auxdisplay/index.rst +++ b/Documentation/admin-guide/auxdisplay/index.rst @@ -7,10 +7,3 @@ Auxiliary Display Support ks0108.rst cfag12864b.rst - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/admin-guide/bug-hunting.rst b/Documentation/admin-guide/bug-hunting.rst index 7da0504388ec..3901b43c96df 100644 --- a/Documentation/admin-guide/bug-hunting.rst +++ b/Documentation/admin-guide/bug-hunting.rst @@ -52,14 +52,14 @@ line is usually required to identify and handle the bug. Along this chapter, we'll refer to "Oops" for all kinds of stack traces that need to be analyzed. If the kernel is compiled with ``CONFIG_DEBUG_INFO``, you can enhance the -quality of the stack trace by using file:`scripts/decode_stacktrace.sh`. +quality of the stack trace by using ``scripts/decode_stacktrace.sh``. Modules linked in ----------------- Modules that are tainted or are being loaded or unloaded are marked with "(...)", where the taint flags are described in -file:`Documentation/admin-guide/tainted-kernels.rst`, "being loaded" is +Documentation/admin-guide/tainted-kernels.rst, "being loaded" is annotated with "+", and "being unloaded" is annotated with "-". @@ -235,7 +235,7 @@ Dave Miller):: mov 0x8(%ebp), %ebx ! %ebx = skb->sk mov 0x13c(%ebx), %eax ! %eax = inet_sk(sk)->opt -file:`scripts/decodecode` can be used to automate most of this, depending +``scripts/decodecode`` can be used to automate most of this, depending on what CPU architecture is being debugged. Reporting the bug diff --git a/Documentation/admin-guide/cgroup-v1/hugetlb.rst b/Documentation/admin-guide/cgroup-v1/hugetlb.rst index 493a8e386700..b5f3873b7d3a 100644 --- a/Documentation/admin-guide/cgroup-v1/hugetlb.rst +++ b/Documentation/admin-guide/cgroup-v1/hugetlb.rst @@ -77,7 +77,7 @@ control group and enforces the limit during page fault. Since HugeTLB doesn't support page reclaim, enforcing the limit at page fault time implies that, the application will get SIGBUS signal if it tries to fault in HugeTLB pages beyond its limit. Therefore the application needs to know exactly how many -HugeTLB pages it uses before hand, and the sysadmin needs to make sure that +HugeTLB pages it uses beforehand, and the sysadmin needs to make sure that there are enough available on the machine for all the users to avoid processes getting SIGBUS. @@ -91,23 +91,23 @@ getting SIGBUS. hugetlb.<hugepagesize>.rsvd.usage_in_bytes hugetlb.<hugepagesize>.rsvd.failcnt -The HugeTLB controller allows to limit the HugeTLB reservations per control +The HugeTLB controller allows limiting the HugeTLB reservations per control group and enforces the controller limit at reservation time and at the fault of HugeTLB memory for which no reservation exists. Since reservation limits are -enforced at reservation time (on mmap or shget), reservation limits never causes -the application to get SIGBUS signal if the memory was reserved before hand. For +enforced at reservation time (on mmap or shget), reservation limits never cause +the application to get SIGBUS signal if the memory was reserved beforehand. For MAP_NORESERVE allocations, the reservation limit behaves the same as the fault limit, enforcing memory usage at fault time and causing the application to receive a SIGBUS if it's crossing its limit. Reservation limits are superior to page fault limits described above, since reservation limits are enforced at reservation time (on mmap or shget), and -never causes the application to get SIGBUS signal if the memory was reserved -before hand. This allows for easier fallback to alternatives such as +never cause the application to get SIGBUS signal if the memory was reserved +beforehand. This allows for easier fallback to alternatives such as non-HugeTLB memory for example. In the case of page fault accounting, it's very -hard to avoid processes getting SIGBUS since the sysadmin needs precisely know -the HugeTLB usage of all the tasks in the system and make sure there is enough -pages to satisfy all requests. Avoiding tasks getting SIGBUS on overcommited +hard to avoid processes getting SIGBUS since the sysadmin needs to precisely know +the HugeTLB usage of all the tasks in the system and make sure there are enough +pages to satisfy all requests. Avoiding tasks getting SIGBUS on overcommitted systems is practically impossible with page fault accounting. diff --git a/Documentation/admin-guide/cgroup-v1/index.rst b/Documentation/admin-guide/cgroup-v1/index.rst index 99fbc8a64ba9..14897a8d32b3 100644 --- a/Documentation/admin-guide/cgroup-v1/index.rst +++ b/Documentation/admin-guide/cgroup-v1/index.rst @@ -22,10 +22,3 @@ Control Groups version 1 net_prio pids rdma - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/admin-guide/cgroup-v2.rst b/Documentation/admin-guide/cgroup-v2.rst index 7f5b59d95fce..098d6831b3c0 100644 --- a/Documentation/admin-guide/cgroup-v2.rst +++ b/Documentation/admin-guide/cgroup-v2.rst @@ -2816,7 +2816,7 @@ DMEM Interface Files HugeTLB ------- -The HugeTLB controller allows to limit the HugeTLB usage per control group and +The HugeTLB controller allows limiting the HugeTLB usage per control group and enforces the controller limit during page fault. HugeTLB Interface Files diff --git a/Documentation/admin-guide/cifs/index.rst b/Documentation/admin-guide/cifs/index.rst index fad5268635f5..58ab58a71a82 100644 --- a/Documentation/admin-guide/cifs/index.rst +++ b/Documentation/admin-guide/cifs/index.rst @@ -12,10 +12,3 @@ CIFS todo changes authors - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/admin-guide/device-mapper/index.rst b/Documentation/admin-guide/device-mapper/index.rst index f1c1f4b824ba..030d854628ac 100644 --- a/Documentation/admin-guide/device-mapper/index.rst +++ b/Documentation/admin-guide/device-mapper/index.rst @@ -40,10 +40,3 @@ Device Mapper verity writecache zero - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/admin-guide/devices.rst b/Documentation/admin-guide/devices.rst index e3776d77374b..b103ba52776a 100644 --- a/Documentation/admin-guide/devices.rst +++ b/Documentation/admin-guide/devices.rst @@ -97,9 +97,12 @@ It is recommended that these links exist on all systems: /dev/bttv0 video0 symbolic Backward compatibility /dev/radio radio0 symbolic Backward compatibility /dev/i2o* /dev/i2o/* symbolic Backward compatibility -/dev/scd? sr? hard Alternate SCSI CD-ROM name =============== =============== =============== =============================== +Suggested earlier ``/dev/scd?`` alternative names for ``/dev/sr?`` +CD-ROM and other optical drives (using SCSI commands) were removed +in ``udev`` version 174 that was released in 2011. + Locally defined links +++++++++++++++++++++ @@ -112,7 +115,6 @@ exist, they should have the following uses. /dev/mouse mouse port symbolic Current mouse device /dev/tape tape device symbolic Current tape device /dev/cdrom CD-ROM device symbolic Current CD-ROM device -/dev/cdwriter CD-writer symbolic Current CD-writer device /dev/scanner scanner symbolic Current scanner device /dev/modem modem port symbolic Current dialout device /dev/root root device symbolic Current root filesystem @@ -126,8 +128,8 @@ exists, ``/dev/modem`` should point to the appropriate primary TTY device For SCSI devices, ``/dev/tape`` and ``/dev/cdrom`` should point to the *cooked* devices (``/dev/st*`` and ``/dev/sr*``, respectively), whereas -``/dev/cdwriter`` and /dev/scanner should point to the appropriate generic -SCSI devices (/dev/sg*). +``/dev/scanner`` should point to the appropriate generic +SCSI device (``/dev/sg*``). ``/dev/mouse`` may point to a primary serial TTY device, a hardware mouse device, or a socket for a mouse driver program (e.g. ``/dev/gpmdata``). diff --git a/Documentation/admin-guide/devices.txt b/Documentation/admin-guide/devices.txt index 94c98be1329a..c480f230aa4a 100644 --- a/Documentation/admin-guide/devices.txt +++ b/Documentation/admin-guide/devices.txt @@ -389,11 +389,11 @@ ... 11 block SCSI CD-ROM devices - 0 = /dev/scd0 First SCSI CD-ROM - 1 = /dev/scd1 Second SCSI CD-ROM + 0 = /dev/sr0 First SCSI CD-ROM + 1 = /dev/sr1 Second SCSI CD-ROM ... - The prefix /dev/sr (instead of /dev/scd) has been deprecated. + In the past the prefix /dev/scd (instead of /dev/sr) was used and even recommended. 12 char QIC-02 tape 2 = /dev/ntpqic11 QIC-11, no rewind-on-close diff --git a/Documentation/admin-guide/gpio/index.rst b/Documentation/admin-guide/gpio/index.rst index 712f379731cb..082646851029 100644 --- a/Documentation/admin-guide/gpio/index.rst +++ b/Documentation/admin-guide/gpio/index.rst @@ -12,10 +12,3 @@ GPIO gpio-sim gpio-virtuser Obsolete APIs <obsolete> - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/admin-guide/index.rst b/Documentation/admin-guide/index.rst index 259d79fbeb94..b734f8a2a2c4 100644 --- a/Documentation/admin-guide/index.rst +++ b/Documentation/admin-guide/index.rst @@ -189,10 +189,3 @@ A few hard-to-categorize and generally obsolete documents. ldm unicode - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/admin-guide/initrd.rst b/Documentation/admin-guide/initrd.rst index 67bbad8806e8..6c1660a4c5cc 100644 --- a/Documentation/admin-guide/initrd.rst +++ b/Documentation/admin-guide/initrd.rst @@ -297,7 +297,7 @@ as follows: 8) now the system is bootable and additional installation tasks can be performed -The key role of initrd here is to re-use the configuration data during +The key role of initrd here is to reuse the configuration data during normal system operation without requiring the use of a bloated "generic" kernel or re-compiling or re-linking the kernel. diff --git a/Documentation/admin-guide/kdump/index.rst b/Documentation/admin-guide/kdump/index.rst index 8e2ebd0383cd..cf5d7c868b74 100644 --- a/Documentation/admin-guide/kdump/index.rst +++ b/Documentation/admin-guide/kdump/index.rst @@ -11,10 +11,3 @@ information. kdump vmcoreinfo - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/admin-guide/kdump/kdump.rst b/Documentation/admin-guide/kdump/kdump.rst index 7b011eb116a7..7587caadbae1 100644 --- a/Documentation/admin-guide/kdump/kdump.rst +++ b/Documentation/admin-guide/kdump/kdump.rst @@ -591,7 +591,7 @@ with /sys/kernel/config/crash_dm_crypt_keys for setup, cat /sys/kernel/config/crash_dm_crypt_keys/count 2 - # To support CPU/memory hot-plugging, re-use keys already saved to reserved + # To support CPU/memory hot-plugging, reuse keys already saved to reserved # memory echo true > /sys/kernel/config/crash_dm_crypt_key/reuse diff --git a/Documentation/admin-guide/kernel-parameters.txt b/Documentation/admin-guide/kernel-parameters.txt index 74740815d61f..fc18080365ff 100644 --- a/Documentation/admin-guide/kernel-parameters.txt +++ b/Documentation/admin-guide/kernel-parameters.txt @@ -1969,6 +1969,9 @@ Kernel parameters param "no_hash_pointers" is an alias for this mode. + For controlling hashing dynamically at runtime, + use the "kernel.kptr_restrict" sysctl instead. + hashdist= [KNL,NUMA] Large hashes allocated during boot are distributed across NUMA nodes. Defaults on for 64-bit NUMA, off otherwise. @@ -4036,6 +4039,7 @@ Kernel parameters spectre_v2_user=off [X86] srbds=off [X86,INTEL] ssbd=force-off [ARM64] + tsa=off [X86,AMD] tsx_async_abort=off [X86] vmscape=off [X86] diff --git a/Documentation/admin-guide/mm/nommu-mmap.rst b/Documentation/admin-guide/mm/nommu-mmap.rst index 530fed08de2c..8a1949b3690f 100644 --- a/Documentation/admin-guide/mm/nommu-mmap.rst +++ b/Documentation/admin-guide/mm/nommu-mmap.rst @@ -38,7 +38,7 @@ and it's also much more restricted in the latter case: In the no-MMU case: - - If one exists, the kernel will re-use an existing mapping to the + - If one exists, the kernel will reuse an existing mapping to the same segment of the same file if that has compatible permissions, even if this was created by another process. diff --git a/Documentation/admin-guide/sysctl/kernel.rst b/Documentation/admin-guide/sysctl/kernel.rst index bb577fac76a0..9aed74e65cf4 100644 --- a/Documentation/admin-guide/sysctl/kernel.rst +++ b/Documentation/admin-guide/sysctl/kernel.rst @@ -591,6 +591,9 @@ if leaking kernel pointer values to unprivileged users is a concern. When ``kptr_restrict`` is set to 2, kernel pointers printed using %pK will be replaced with 0s regardless of privileges. +For disabling these security restrictions early at boot time (and once +for all), use the ``hash_pointers`` boot parameter instead. + softlockup_sys_info & hardlockup_sys_info ========================================= A comma separated list of extra system information to be dumped when diff --git a/Documentation/arch/arc/index.rst b/Documentation/arch/arc/index.rst index 7b098d4a5e3e..10bf8c2701bf 100644 --- a/Documentation/arch/arc/index.rst +++ b/Documentation/arch/arc/index.rst @@ -8,10 +8,3 @@ ARC architecture arc features - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/arch/arm/index.rst b/Documentation/arch/arm/index.rst index fd43502ae924..afe17db294c4 100644 --- a/Documentation/arch/arm/index.rst +++ b/Documentation/arch/arm/index.rst @@ -75,11 +75,3 @@ SoC-specific documents sti/overview vfp/release-notes - - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/arch/arm/keystone/knav-qmss.rst b/Documentation/arch/arm/keystone/knav-qmss.rst index 7f7638d80b42..f9a77eb462b2 100644 --- a/Documentation/arch/arm/keystone/knav-qmss.rst +++ b/Documentation/arch/arm/keystone/knav-qmss.rst @@ -39,7 +39,7 @@ CPPI/QMSS Low Level Driver document (docs/CPPI_QMSS_LLD_SDS.pdf) at git://git.ti.com/keystone-rtos/qmss-lld.git -k2_qmss_pdsp_acc48_k2_le_1_0_0_9.bin firmware supports upto 48 accumulator +k2_qmss_pdsp_acc48_k2_le_1_0_0_9.bin firmware supports up to 48 accumulator channels. This firmware is available under ti-keystone folder of firmware.git at diff --git a/Documentation/arch/arm/keystone/overview.rst b/Documentation/arch/arm/keystone/overview.rst index cd90298c493c..bf791b2fc43f 100644 --- a/Documentation/arch/arm/keystone/overview.rst +++ b/Documentation/arch/arm/keystone/overview.rst @@ -65,7 +65,7 @@ specified through DTS. Following are the DTS used: The device tree documentation for the keystone machines are located at - Documentation/devicetree/bindings/arm/keystone/keystone.txt + Documentation/devicetree/bindings/arm/ti/ti,keystone.yaml Document Author --------------- diff --git a/Documentation/arch/arm64/arm-acpi.rst b/Documentation/arch/arm64/arm-acpi.rst index e59e4505d0d9..e74c8ab71429 100644 --- a/Documentation/arch/arm64/arm-acpi.rst +++ b/Documentation/arch/arm64/arm-acpi.rst @@ -306,9 +306,9 @@ that looks like this: Name(KEY0, "value0"). An ACPI device driver would then retrieve the value of the property by evaluating the KEY0 object. However, using Name() this way has multiple problems: (1) ACPI limits names ("KEY0") to four characters unlike DT; (2) there is no industry -wide registry that maintains a list of names, minimizing re-use; (3) +wide registry that maintains a list of names, minimizing reuse; (3) there is also no registry for the definition of property values ("value0"), -again making re-use difficult; and (4) how does one maintain backward +again making reuse difficult; and (4) how does one maintain backward compatibility as new hardware comes out? The _DSD method was created to solve precisely these sorts of problems; Linux drivers should ALWAYS use the _DSD method for device properties and nothing else. diff --git a/Documentation/arch/arm64/index.rst b/Documentation/arch/arm64/index.rst index 6a012c98bdcd..af52edc8c0ac 100644 --- a/Documentation/arch/arm64/index.rst +++ b/Documentation/arch/arm64/index.rst @@ -33,10 +33,3 @@ ARM64 Architecture tagged-pointers features - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/arch/loongarch/index.rst b/Documentation/arch/loongarch/index.rst index c779bfa00c05..df590b117240 100644 --- a/Documentation/arch/loongarch/index.rst +++ b/Documentation/arch/loongarch/index.rst @@ -13,10 +13,3 @@ LoongArch Architecture irq-chip-model features - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/arch/m68k/index.rst b/Documentation/arch/m68k/index.rst index 0f890dbb5fe2..c334026e0ae1 100644 --- a/Documentation/arch/m68k/index.rst +++ b/Documentation/arch/m68k/index.rst @@ -11,10 +11,3 @@ m68k Architecture buddha-driver features - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/arch/mips/index.rst b/Documentation/arch/mips/index.rst index 037f85a08fe3..703e195b933d 100644 --- a/Documentation/arch/mips/index.rst +++ b/Documentation/arch/mips/index.rst @@ -12,10 +12,3 @@ MIPS-specific Documentation ingenic-tcu features - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/arch/openrisc/index.rst b/Documentation/arch/openrisc/index.rst index 6879f998b87a..79fe8b0c2c41 100644 --- a/Documentation/arch/openrisc/index.rst +++ b/Documentation/arch/openrisc/index.rst @@ -11,10 +11,3 @@ OpenRISC Architecture todo features - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/arch/parisc/index.rst b/Documentation/arch/parisc/index.rst index 240685751825..15ccc787fd4f 100644 --- a/Documentation/arch/parisc/index.rst +++ b/Documentation/arch/parisc/index.rst @@ -11,10 +11,3 @@ PA-RISC Architecture registers features - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/arch/powerpc/index.rst b/Documentation/arch/powerpc/index.rst index 1be2ee3f0361..40419bea8e10 100644 --- a/Documentation/arch/powerpc/index.rst +++ b/Documentation/arch/powerpc/index.rst @@ -40,10 +40,3 @@ powerpc vpa-dtl features - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/arch/riscv/index.rst b/Documentation/arch/riscv/index.rst index eecf347ce849..830fde0c8aa3 100644 --- a/Documentation/arch/riscv/index.rst +++ b/Documentation/arch/riscv/index.rst @@ -16,10 +16,3 @@ RISC-V architecture cmodx features - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/arch/s390/driver-model.rst b/Documentation/arch/s390/driver-model.rst index e7488f02bb78..14f801e0d793 100644 --- a/Documentation/arch/s390/driver-model.rst +++ b/Documentation/arch/s390/driver-model.rst @@ -279,7 +279,7 @@ status - Can be 'online' or 'offline'. Piping 'on' or 'off' sets the chpid logically online/offline. Piping 'on' to an online chpid triggers path reprobing for all devices - the chpid connects to. This can be used to force the kernel to re-use + the chpid connects to. This can be used to force the kernel to reuse a channel path the user knows to be online, but the machine hasn't created a machine check for. diff --git a/Documentation/arch/s390/index.rst b/Documentation/arch/s390/index.rst index e75a6e5d2505..769434f0625b 100644 --- a/Documentation/arch/s390/index.rst +++ b/Documentation/arch/s390/index.rst @@ -22,10 +22,3 @@ s390 Architecture text_files features - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/arch/x86/shstk.rst b/Documentation/arch/x86/shstk.rst index 60260e809baf..30b4e4f362ba 100644 --- a/Documentation/arch/x86/shstk.rst +++ b/Documentation/arch/x86/shstk.rst @@ -165,7 +165,7 @@ in the page fault error code. When a task forks a child, its shadow stack PTEs are copied and both the parent's and the child's shadow stack PTEs are cleared of the dirty bit. Upon the next shadow stack access, the resulting shadow stack page fault -is handled by page copy/re-use. +is handled by page copy/reuse. When a pthread child is created, the kernel allocates a new shadow stack for the new thread. New shadow stack creation behaves like mmap() with respect diff --git a/Documentation/bpf/index.rst b/Documentation/bpf/index.rst index 0bb5cb8157f1..0d5c6f659266 100644 --- a/Documentation/bpf/index.rst +++ b/Documentation/bpf/index.rst @@ -34,12 +34,5 @@ that goes into great technical depth about the BPF Architecture. other redirect -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` - .. Links: .. _BPF and XDP Reference Guide: https://docs.cilium.io/en/latest/bpf/ diff --git a/Documentation/cdrom/index.rst b/Documentation/cdrom/index.rst index 3ac4f716612f..50050e219910 100644 --- a/Documentation/cdrom/index.rst +++ b/Documentation/cdrom/index.rst @@ -8,10 +8,3 @@ CD-ROM :maxdepth: 1 cdrom-standard - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/conf.py b/Documentation/conf.py index 1ea2ae5c6276..679861503a25 100644 --- a/Documentation/conf.py +++ b/Documentation/conf.py @@ -13,10 +13,15 @@ from textwrap import dedent import sphinx -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath("sphinx")) +# Location of Documentation/ directory +kern_doc_dir = os.path.dirname(os.path.abspath(__file__)) + +# Add location of Sphinx extensions +sys.path.insert(0, os.path.join(kern_doc_dir, "sphinx")) + +# Allow sphinx.ext.autodoc to document files at tools and scripts +sys.path.append(os.path.join(kern_doc_dir, "..", "tools")) +sys.path.append(os.path.join(kern_doc_dir, "..", "scripts")) # Minimal supported version needs_sphinx = "3.4.3" @@ -32,15 +37,12 @@ else: # Include patterns that don't contain directory names, in glob format include_patterns = ["**.rst"] -# Location of Documentation/ directory -doctree = os.path.abspath(".") - # Exclude of patterns that don't contain directory names, in glob format. exclude_patterns = [] # List of patterns that contain directory names in glob format. dyn_include_patterns = [] -dyn_exclude_patterns = ["output"] +dyn_exclude_patterns = ["output", "sphinx-includes"] # Currently, only netlink/specs has a parser for yaml. # Prefer using include patterns if available, as it is faster @@ -51,6 +53,9 @@ else: dyn_exclude_patterns.append("devicetree/bindings/**.yaml") dyn_exclude_patterns.append("core-api/kho/bindings/**.yaml") +# Link to man pages +manpages_url = 'https://man7.org/linux/man-pages/man{section}/{page}.{section}.html' + # Properly handle directory patterns and LaTeX docs # ------------------------------------------------- @@ -70,7 +75,7 @@ def config_init(app, config): # setup include_patterns dynamically if has_include_patterns: for p in dyn_include_patterns: - full = os.path.join(doctree, p) + full = os.path.join(kern_doc_dir, p) rel_path = os.path.relpath(full, start=app.srcdir) if rel_path.startswith("../"): @@ -80,7 +85,7 @@ def config_init(app, config): # setup exclude_patterns dynamically for p in dyn_exclude_patterns: - full = os.path.join(doctree, p) + full = os.path.join(kern_doc_dir, p) rel_path = os.path.relpath(full, start=app.srcdir) if rel_path.startswith("../"): @@ -92,7 +97,7 @@ def config_init(app, config): # of the app.srcdir. Add them here # Handle the case where SPHINXDIRS is used - if not os.path.samefile(doctree, app.srcdir): + if not os.path.samefile(kern_doc_dir, app.srcdir): # Add a tag to mark that the build is actually a subproject tags.add("subproject") @@ -151,6 +156,7 @@ extensions = [ "maintainers_include", "parser_yaml", "rstFlatTable", + "sphinx.ext.autodoc", "sphinx.ext.autosectionlabel", "sphinx.ext.ifconfig", "translations", @@ -579,13 +585,32 @@ pdf_documents = [ ("kernel-documentation", "Kernel", "Kernel", "J. Random Bozo"), ] -# kernel-doc extension configuration for running Sphinx directly (e.g. by Read -# the Docs). In a normal build, these are supplied from the Makefile via command -# line arguments. -kerneldoc_bin = "../scripts/kernel-doc.py" kerneldoc_srctree = ".." +# Add index link at the end of the root document for SPHINXDIRS builds. +def add_subproject_index(app, docname, content): + # Only care about root documents + if docname != master_doc: + return + + # Add the index link at the root of translations, but not at the root of + # individual translations. They have their own language specific links. + rel = os.path.relpath(app.srcdir, start=kern_doc_dir).split('/') + if rel[0] == 'translations' and len(rel) > 1: + return + + # Only add the link for SPHINXDIRS HTML builds + if not app.builder.tags.has('subproject') or not app.builder.tags.has('html'): + return + + # The include directive needs a relative path from the srcdir + rel = os.path.relpath(os.path.join(kern_doc_dir, 'sphinx-includes/subproject-index.rst'), + start=app.srcdir) + + content[0] += f'\n.. include:: {rel}\n\n' + def setup(app): """Patterns need to be updated at init time on older Sphinx versions""" app.connect('config-inited', config_init) + app.connect('source-read', add_subproject_index) diff --git a/Documentation/core-api/index.rst b/Documentation/core-api/index.rst index 79fe7735692e..13769d5c40bf 100644 --- a/Documentation/core-api/index.rst +++ b/Documentation/core-api/index.rst @@ -141,10 +141,3 @@ Documents that don't fit elsewhere or which have yet to be categorized. librs liveupdate netlink - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/core-api/kho/index.rst b/Documentation/core-api/kho/index.rst index 0c63b0c5c143..51ea41c6a20d 100644 --- a/Documentation/core-api/kho/index.rst +++ b/Documentation/core-api/kho/index.rst @@ -9,5 +9,3 @@ Kexec Handover Subsystem concepts fdt - -.. only:: subproject and html diff --git a/Documentation/core-api/kobject.rst b/Documentation/core-api/kobject.rst index 7310247310a0..5f6c61bc03bf 100644 --- a/Documentation/core-api/kobject.rst +++ b/Documentation/core-api/kobject.rst @@ -78,7 +78,7 @@ just a matter of using the kobj member. Code that works with kobjects will often have the opposite problem, however: given a struct kobject pointer, what is the pointer to the containing structure? You must avoid tricks (such as assuming that the kobject is at the beginning of the structure) -and, instead, use the container_of() macro, found in ``<linux/kernel.h>``:: +and, instead, use the container_of() macro, found in ``<linux/container_of.h>``:: container_of(ptr, type, member) diff --git a/Documentation/core-api/real-time/architecture-porting.rst b/Documentation/core-api/real-time/architecture-porting.rst index d822fac29922..c90a426d8062 100644 --- a/Documentation/core-api/real-time/architecture-porting.rst +++ b/Documentation/core-api/real-time/architecture-porting.rst @@ -35,7 +35,8 @@ POSIX CPU timers and KVM POSIX CPU timers must expire from thread context rather than directly within the timer interrupt. This behavior is enabled by setting the configuration option CONFIG_HAVE_POSIX_CPU_TIMERS_TASK_WORK. - When KVM is enabled, CONFIG_KVM_XFER_TO_GUEST_WORK must also be set to ensure + When virtualization support, such as KVM, is enabled, + CONFIG_VIRT_XFER_TO_GUEST_WORK must also be set to ensure that any pending work, such as POSIX timer expiration, is handled before transitioning into guest mode. diff --git a/Documentation/core-api/real-time/hardware.rst b/Documentation/core-api/real-time/hardware.rst new file mode 100644 index 000000000000..19f9bb3786e0 --- /dev/null +++ b/Documentation/core-api/real-time/hardware.rst @@ -0,0 +1,132 @@ +.. SPDX-License-Identifier: GPL-2.0 + +==================== +Considering hardware +==================== + +:Author: Sebastian Andrzej Siewior <bigeasy@linutronix.de> + +The way a workload is handled can be influenced by the hardware it runs on. +Key components include the CPU, memory, and the buses that connect them. +These resources are shared among all applications on the system. +As a result, heavy utilization of one resource by a single application +can affect the deterministic handling of workloads in other applications. + +Below is a brief overview. + +System memory and cache +----------------------- + +Main memory and the associated caches are the most common shared resources among +tasks in a system. One task can dominate the available caches, forcing another +task to wait until a cache line is written back to main memory before it can +proceed. The impact of this contention varies based on write patterns and the +size of the caches available. Larger caches may reduce stalls because more lines +can be buffered before being written back. Conversely, certain write patterns +may trigger the cache controller to flush many lines at once, causing +applications to stall until the operation completes. + +This issue can be partly mitigated if applications do not share the same CPU +cache. The kernel is aware of the cache topology and exports this information to +user space. Tools such as **lstopo** from the Portable Hardware Locality (hwloc) +project (https://www.open-mpi.org/projects/hwloc/) can visualize the hierarchy. + +Avoiding shared L2 or L3 caches is not always possible. Even when cache sharing +is minimized, bottlenecks can still occur when accessing system memory. Memory +is used not only by the CPU but also by peripheral devices via DMA, such as +graphics cards or network adapters. + +In some cases, cache and memory bottlenecks can be controlled if the hardware +provides the necessary support. On x86 systems, Intel offers Cache Allocation +Technology (CAT), which enables cache partitioning among applications and +provides control over the interconnect. AMD provides similar functionality under +Platform Quality of Service (PQoS). On Arm64, the equivalent is Memory +System Resource Partitioning and Monitoring (MPAM). + +These features can be configured through the Linux Resource Control interface. +For details, see Documentation/filesystems/resctrl.rst. + +The perf tool can be used to monitor cache behavior. It can analyze +cache misses of an application and compare how they change under +different workloads on a neighboring CPU. Even more powerful, the perf +c2c tool can help identify cache-to-cache issues, where multiple CPU +cores repeatedly access and modify data on the same cache line. + +Hardware buses +-------------- + +Real-time systems often need to access hardware directly to perform their work. +Any latency in this process is undesirable, as it can affect the outcome of the +task. For example, on an I/O bus, a changed output may not become immediately +visible but instead appear with variable delay depending on the latency of the +bus used for communication. + +A bus such as PCI is relatively simple because register accesses are routed +directly to the connected device. In the worst case, a read operation stalls the +CPU until the device responds. + +A bus such as USB is more complex, involving multiple layers. A register read +or write is wrapped in a USB Request Block (URB), which is then sent by the +USB host controller to the device. Timing and latency are influenced by the +underlying USB bus. Requests cannot be sent immediately; they must align with +the next frame boundary according to the endpoint type and the host controller's +scheduling rules. This can introduce delays and additional latency. For example, +a network device connected via USB may still deliver sufficient throughput, but +the added latency when sending or receiving packets may fail to meet the +requirements of certain real-time use cases. + +Additional restrictions on bus latency can arise from power management. For +instance, PCIe with Active State Power Management (ASPM) enabled can suspend +the link between the device and the host. While this behavior is beneficial for +power savings, it delays device access and adds latency to responses. This issue +is not limited to PCIe; internal buses within a System-on-Chip (SoC) can also be +affected by power management mechanisms. + +Virtualization +-------------- + +In a virtualized environment such as KVM, each guest CPU is represented as a +thread on the host. If such a thread runs with real-time priority, the system +should be tested to confirm it can sustain this behavior over extended periods. +Because of its priority, the thread will not be preempted by lower-priority +threads (such as SCHED_OTHER), which may then receive no CPU time. This can +cause problems if a lower-priority thread is pinned to a CPU already occupied by +a real-time task and unable to make progress. Even if a CPU has been isolated, +the system may still (accidentally) start a per‑CPU thread on that CPU. +Ensuring that a guest CPU goes idle is difficult, as it requires avoiding both +task scheduling and interrupt handling. Furthermore, if the guest CPU does go +idle but the guest system is booted with the option **idle=poll**, the guest +CPU will never enter an idle state and will instead spin until an event +arrives. + +Device handling introduces additional considerations. Emulated PCI devices or +VirtIO devices require a counterpart on the host to complete requests. This +adds latency because the host must intercept and either process the request +directly or schedule a thread for its completion. These delays can be avoided if +the required PCI device is passed directly through to the guest. Some devices, +such as networking or storage controllers, support the PCIe SR-IOV feature. +SR-IOV allows a single PCIe device to be divided into multiple virtual functions, +which can then be assigned to different guests. + +Networking +---------- + +For low-latency networking, the full networking stack may be undesirable, as it +can introduce additional sources of delay. In this context, XDP can be used +as a shortcut to bypass much of the stack while still relying on the kernel's +network driver. + +The requirements are that the network driver must support XDP- preferably using +an "skb pool" and that the application must use an XDP socket. Additional +configuration may involve BPF filters, tuning networking queues, or configuring +qdiscs for time-based transmission. These techniques are often +applied in Time-Sensitive Networking (TSN) environments. + +Documenting all required steps exceeds the scope of this text. For detailed +guidance, see the TSN documentation at https://tsn.readthedocs.io. + +Another useful resource is the Linux Real-Time Communication Testbench +https://github.com/Linutronix/RTC-Testbench. +The goal of this project is to validate real-time network communication. It can +be thought of as a "cyclictest" for networking and also serves as a starting +point for application development. diff --git a/Documentation/core-api/real-time/index.rst b/Documentation/core-api/real-time/index.rst index 7e14c4ea3d59..f08d2395a22c 100644 --- a/Documentation/core-api/real-time/index.rst +++ b/Documentation/core-api/real-time/index.rst @@ -13,4 +13,5 @@ the required changes compared to a non-PREEMPT_RT configuration. theory differences + hardware architecture-porting diff --git a/Documentation/dev-tools/checkpatch.rst b/Documentation/dev-tools/checkpatch.rst index deb3f67a633c..ca475805df4c 100644 --- a/Documentation/dev-tools/checkpatch.rst +++ b/Documentation/dev-tools/checkpatch.rst @@ -753,7 +753,7 @@ Macros, Attributes and Symbols sizeof(foo)/sizeof(foo[0]) for finding number of elements in an array. - The macro is defined in include/linux/kernel.h:: + The macro is defined in include/linux/array_size.h:: #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) diff --git a/Documentation/dev-tools/clang-format.rst b/Documentation/dev-tools/clang-format.rst index 1d089a847c1b..6c8a0df5a00c 100644 --- a/Documentation/dev-tools/clang-format.rst +++ b/Documentation/dev-tools/clang-format.rst @@ -88,7 +88,7 @@ Reformatting blocks of code By using an integration with your text editor, you can reformat arbitrary blocks (selections) of code with a single keystroke. This is specially -useful when moving code around, for complex code that is deeply intended, +useful when moving code around, for complex code that is deeply indented, for multi-line macros (and aligning their backslashes), etc. Remember that you can always tweak the changes afterwards in those cases diff --git a/Documentation/dev-tools/index.rst b/Documentation/dev-tools/index.rst index 4b8425e348ab..4fc9d15f91d0 100644 --- a/Documentation/dev-tools/index.rst +++ b/Documentation/dev-tools/index.rst @@ -38,11 +38,3 @@ Documentation/process/debugging/index.rst gpio-sloppy-logic-analyzer autofdo propeller - - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/doc-guide/index.rst b/Documentation/doc-guide/index.rst index 24d058faa75c..f078baddf0b7 100644 --- a/Documentation/doc-guide/index.rst +++ b/Documentation/doc-guide/index.rst @@ -13,10 +13,3 @@ How to write kernel documentation contributing maintainer-profile checktransupdate - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/doc-guide/kernel-doc.rst b/Documentation/doc-guide/kernel-doc.rst index fd89a6d56ea9..8d2c09fb36e4 100644 --- a/Documentation/doc-guide/kernel-doc.rst +++ b/Documentation/doc-guide/kernel-doc.rst @@ -54,13 +54,16 @@ Running the ``kernel-doc`` tool with increased verbosity and without actual output generation may be used to verify proper formatting of the documentation comments. For example:: - scripts/kernel-doc -v -none drivers/foo/bar.c + tools/docs/kernel-doc -v -none drivers/foo/bar.c -The documentation format is verified by the kernel build when it is -requested to perform extra gcc checks:: +The documentation format of ``.c`` files is also verified by the kernel build +when it is requested to perform extra gcc checks:: make W=n +However, the above command does not verify header files. These should be checked +separately using ``kernel-doc``. + Function documentation ---------------------- @@ -174,7 +177,8 @@ named ``Return`` (or ``Returns``). Structure, union, and enumeration documentation ----------------------------------------------- -The general format of a struct, union, and enum kernel-doc comment is:: +The general format of a ``struct``, ``union``, and ``enum`` kernel-doc +comment is:: /** * struct struct_name - Brief description. @@ -187,8 +191,8 @@ The general format of a struct, union, and enum kernel-doc comment is:: */ You can replace the ``struct`` in the above example with ``union`` or -``enum`` to describe unions or enums. ``member`` is used to mean struct -and union member names as well as enumerations in an enum. +``enum`` to describe unions or enums. ``member`` is used to mean ``struct`` +and ``union`` member names as well as enumerations in an ``enum``. The brief description following the structure name may span multiple lines, and ends with a member description, a blank comment line, or the @@ -201,7 +205,7 @@ Members of structs, unions and enums should be documented the same way as function parameters; they immediately succeed the short description and may be multi-line. -Inside a struct or union description, you can use the ``private:`` and +Inside a ``struct`` or ``union`` description, you can use the ``private:`` and ``public:`` comment tags. Structure fields that are inside a ``private:`` area are not listed in the generated output documentation. @@ -273,11 +277,11 @@ It is possible to document nested structs and unions, like:: .. note:: - #) When documenting nested structs or unions, if the struct/union ``foo`` - is named, the member ``bar`` inside it should be documented as + #) When documenting nested structs or unions, if the ``struct``/``union`` + ``foo`` is named, the member ``bar`` inside it should be documented as ``@foo.bar:`` - #) When the nested struct/union is anonymous, the member ``bar`` in it - should be documented as ``@bar:`` + #) When the nested ``struct``/``union`` is anonymous, the member ``bar`` in + it should be documented as ``@bar:`` In-line member documentation comments ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -319,7 +323,7 @@ on a line of their own, like all other kernel-doc comments:: Typedef documentation --------------------- -The general format of a typedef kernel-doc comment is:: +The general format of a ``typedef`` kernel-doc comment is:: /** * typedef type_name - Brief description. @@ -341,6 +345,18 @@ Typedefs with function prototypes can also be documented:: */ typedef void (*type_name)(struct v4l2_ctrl *arg1, void *arg2); +Variables documentation +----------------------- + +The general format of a kernel-doc variable comment is:: + + /** + * var var_name - Brief description. + * + * Description of the var_name variable. + */ + extern int var_name; + Object-like macro documentation ------------------------------- @@ -349,7 +365,7 @@ differentiated by whether the macro name is immediately followed by a left parenthesis ('(') for function-like macros or not followed by one for object-like macros. -Function-like macros are handled like functions by ``scripts/kernel-doc``. +Function-like macros are handled like functions by ``tools/docs/kernel-doc``. They may have a parameter list. Object-like macros have do not have a parameter list. @@ -432,8 +448,8 @@ Domain`_ references. Typedef reference. ``&struct_name->member`` or ``&struct_name.member`` - Structure or union member reference. The cross-reference will be to the struct - or union definition, not the member directly. + ``struct`` or ``union`` member reference. The cross-reference will be to the + ``struct`` or ``union`` definition, not the member directly. ``&name`` A generic type reference. Prefer using the full reference described above @@ -462,14 +478,18 @@ through the following syntax:: For further details, please refer to the `Sphinx C Domain`_ documentation. +.. note:: + Variables aren't automatically cross referenced. For those, you need to + explicitly add a C domain cross-reference. + Overview documentation comments ------------------------------- To facilitate having source code and comments close together, you can include kernel-doc documentation blocks that are free-form comments instead of being -kernel-doc for functions, structures, unions, enums, or typedefs. This could be -used for something like a theory of operation for a driver or library code, for -example. +kernel-doc for functions, structures, unions, enums, typedefs or variables. +This could be used for something like a theory of operation for a driver or +library code, for example. This is done by using a ``DOC:`` section keyword with a section title. @@ -537,7 +557,8 @@ identifiers: *[ function/type ...]* Include documentation for each *function* and *type* in *source*. If no *function* is specified, the documentation for all functions and types in the *source* will be included. - *type* can be a struct, union, enum, or typedef identifier. + *type* can be a ``struct``, ``union``, ``enum``, ``typedef`` or ``var`` + identifier. Examples:: @@ -575,8 +596,8 @@ from the source file. The kernel-doc extension is included in the kernel source tree, at ``Documentation/sphinx/kerneldoc.py``. Internally, it uses the -``scripts/kernel-doc`` script to extract the documentation comments from the -source. +``tools/docs/kernel-doc`` script to extract the documentation comments from +the source. .. _kernel_doc: diff --git a/Documentation/driver-api/80211/index.rst b/Documentation/driver-api/80211/index.rst index af210859d3e1..62305e9c3113 100644 --- a/Documentation/driver-api/80211/index.rst +++ b/Documentation/driver-api/80211/index.rst @@ -8,10 +8,3 @@ Linux 802.11 Driver Developer's Guide cfg80211 mac80211 mac80211-advanced - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/driver-api/basics.rst b/Documentation/driver-api/basics.rst index 5e9f7aee71a7..8b6a5888cb11 100644 --- a/Documentation/driver-api/basics.rst +++ b/Documentation/driver-api/basics.rst @@ -114,10 +114,25 @@ Kernel objects manipulation Kernel utility functions ------------------------ -.. kernel-doc:: include/linux/kernel.h +.. kernel-doc:: include/linux/array_size.h + :internal: + +.. kernel-doc:: include/linux/container_of.h + :internal: + +.. kernel-doc:: include/linux/kstrtox.h :internal: :no-identifiers: kstrtol kstrtoul +.. kernel-doc:: include/linux/stddef.h + :internal: + +.. kernel-doc:: include/linux/util_macros.h + :internal: + +.. kernel-doc:: include/linux/wordpart.h + :internal: + .. kernel-doc:: kernel/printk/printk.c :export: :no-identifiers: printk diff --git a/Documentation/driver-api/coco/index.rst b/Documentation/driver-api/coco/index.rst index af9f08ca0cfd..783c8b033547 100644 --- a/Documentation/driver-api/coco/index.rst +++ b/Documentation/driver-api/coco/index.rst @@ -8,5 +8,3 @@ Confidential Computing :maxdepth: 1 measurement-registers - -.. only:: subproject and html diff --git a/Documentation/driver-api/crypto/iaa/index.rst b/Documentation/driver-api/crypto/iaa/index.rst index aa6837e27264..463f7da569c5 100644 --- a/Documentation/driver-api/crypto/iaa/index.rst +++ b/Documentation/driver-api/crypto/iaa/index.rst @@ -11,10 +11,3 @@ API. :maxdepth: 1 iaa-crypto - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/driver-api/crypto/index.rst b/Documentation/driver-api/crypto/index.rst index fb9709b98bea..bba669014cb2 100644 --- a/Documentation/driver-api/crypto/index.rst +++ b/Documentation/driver-api/crypto/index.rst @@ -11,10 +11,3 @@ configuration. :maxdepth: 1 iaa/index - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/driver-api/cxl/index.rst b/Documentation/driver-api/cxl/index.rst index c1106a68b67c..ec8aae9ec0d4 100644 --- a/Documentation/driver-api/cxl/index.rst +++ b/Documentation/driver-api/cxl/index.rst @@ -50,5 +50,3 @@ that have impacts on each other. The docs here break up configurations steps. allocation/page-allocator allocation/reclaim allocation/hugepages.rst - -.. only:: subproject and html diff --git a/Documentation/driver-api/dmaengine/index.rst b/Documentation/driver-api/dmaengine/index.rst index bdc45d8b4cfb..e74677c664ac 100644 --- a/Documentation/driver-api/dmaengine/index.rst +++ b/Documentation/driver-api/dmaengine/index.rst @@ -46,10 +46,3 @@ This book adds some notes about PXA DMA :maxdepth: 1 pxa_dma - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/driver-api/driver-model/binding.rst b/Documentation/driver-api/driver-model/binding.rst index 7ea1d7a41e1d..d1d311a4011f 100644 --- a/Documentation/driver-api/driver-model/binding.rst +++ b/Documentation/driver-api/driver-model/binding.rst @@ -53,9 +53,12 @@ class's register_dev callback. Driver ~~~~~~ -When a driver is attached to a device, the device is inserted into the -driver's list of devices. - +When a driver is attached to a device, the driver's probe() function is +called. Within probe(), the driver initializes the device and allocates +and initializes per-device data structures. This per-device state is +associated with the device object for as long as the driver remains bound +to it. Conceptually, this per-device data together with the binding to +the device can be thought of as an instance of the driver. sysfs ~~~~~ diff --git a/Documentation/driver-api/driver-model/design-patterns.rst b/Documentation/driver-api/driver-model/design-patterns.rst index 41eb8f41f7dd..965b2b93be6f 100644 --- a/Documentation/driver-api/driver-model/design-patterns.rst +++ b/Documentation/driver-api/driver-model/design-patterns.rst @@ -103,7 +103,7 @@ The design pattern is the same for an hrtimer or something similar that will return a single argument which is a pointer to a struct member in the callback. -container_of() is a macro defined in <linux/kernel.h> +container_of() is a macro defined in <linux/container_of.h> What container_of() does is to obtain a pointer to the containing struct from a pointer to a member by a simple subtraction using the offsetof() macro from diff --git a/Documentation/driver-api/driver-model/index.rst b/Documentation/driver-api/driver-model/index.rst index 4831bdd92e5c..abeb4b36636b 100644 --- a/Documentation/driver-api/driver-model/index.rst +++ b/Documentation/driver-api/driver-model/index.rst @@ -14,10 +14,3 @@ Driver Model overview platform porting - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/driver-api/early-userspace/index.rst b/Documentation/driver-api/early-userspace/index.rst index 149c1822f06d..ff459471258f 100644 --- a/Documentation/driver-api/early-userspace/index.rst +++ b/Documentation/driver-api/early-userspace/index.rst @@ -9,10 +9,3 @@ Early Userspace early_userspace_support buffer-format - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/driver-api/firmware/index.rst b/Documentation/driver-api/firmware/index.rst index 9d2c19dc8e36..86a3dd4bc3f8 100644 --- a/Documentation/driver-api/firmware/index.rst +++ b/Documentation/driver-api/firmware/index.rst @@ -10,10 +10,3 @@ Linux Firmware API request_firmware fw_upload other_interfaces - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/driver-api/index.rst b/Documentation/driver-api/index.rst index 1833e6a0687e..eaf7161ff957 100644 --- a/Documentation/driver-api/index.rst +++ b/Documentation/driver-api/index.rst @@ -149,10 +149,3 @@ Subsystem-specific APIs wmi xilinx/index zorro - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/driver-api/mailbox.rst b/Documentation/driver-api/mailbox.rst index 0ed95009cc30..463dd032b96c 100644 --- a/Documentation/driver-api/mailbox.rst +++ b/Documentation/driver-api/mailbox.rst @@ -27,7 +27,7 @@ Controller Driver (See include/linux/mailbox_controller.h) Allocate mbox_controller and the array of mbox_chan. -Populate mbox_chan_ops, except peek_data() all are mandatory. +Populate mbox_chan_ops, except flush() and peek_data() all are mandatory. The controller driver might know a message has been consumed by the remote by getting an IRQ or polling some hardware flag or it can never know (the client knows by way of the protocol). diff --git a/Documentation/driver-api/memory-devices/index.rst b/Documentation/driver-api/memory-devices/index.rst index 28101458cda5..3b6308113611 100644 --- a/Documentation/driver-api/memory-devices/index.rst +++ b/Documentation/driver-api/memory-devices/index.rst @@ -9,10 +9,3 @@ Memory Controller drivers ti-emif ti-gpmc - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/driver-api/pci/index.rst b/Documentation/driver-api/pci/index.rst index 9e1b801d0f74..1abfbecf6ce6 100644 --- a/Documentation/driver-api/pci/index.rst +++ b/Documentation/driver-api/pci/index.rst @@ -11,10 +11,3 @@ The Linux PCI driver implementer's API guide pci p2pdma tsm - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/driver-api/phy/index.rst b/Documentation/driver-api/phy/index.rst index 69ba1216de72..579cfe3b7b82 100644 --- a/Documentation/driver-api/phy/index.rst +++ b/Documentation/driver-api/phy/index.rst @@ -8,11 +8,3 @@ Generic PHY Framework phy samsung-usb2 - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` - diff --git a/Documentation/driver-api/phy/phy.rst b/Documentation/driver-api/phy/phy.rst index 719a2b3fd2ab..0865c2e94eec 100644 --- a/Documentation/driver-api/phy/phy.rst +++ b/Documentation/driver-api/phy/phy.rst @@ -19,7 +19,7 @@ PHY. Other peripherals that use PHY include Wireless LAN, Ethernet, SATA etc. The intention of creating this framework is to bring the PHY drivers spread -all over the Linux kernel to drivers/phy to increase code re-use and for +all over the Linux kernel to drivers/phy to increase code reuse and for better code maintainability. This framework will be of use only to devices that use external PHY (PHY diff --git a/Documentation/driver-api/pm/index.rst b/Documentation/driver-api/pm/index.rst index c2a9ef8d115c..4d6c32e32a72 100644 --- a/Documentation/driver-api/pm/index.rst +++ b/Documentation/driver-api/pm/index.rst @@ -10,10 +10,3 @@ CPU and Device Power Management devices notifiers types - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/driver-api/serial/index.rst b/Documentation/driver-api/serial/index.rst index 03a55b987a1d..610744df5e8d 100644 --- a/Documentation/driver-api/serial/index.rst +++ b/Documentation/driver-api/serial/index.rst @@ -18,10 +18,3 @@ Serial drivers serial-iso7816 serial-rs485 - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/driver-api/soundwire/index.rst b/Documentation/driver-api/soundwire/index.rst index ef8d90dfbdde..f7abf4a95be7 100644 --- a/Documentation/driver-api/soundwire/index.rst +++ b/Documentation/driver-api/soundwire/index.rst @@ -11,10 +11,3 @@ SoundWire Documentation locking bra bra_cadence - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/driver-api/surface_aggregator/clients/index.rst b/Documentation/driver-api/surface_aggregator/clients/index.rst index 30160513afa5..c32313b8f3b7 100644 --- a/Documentation/driver-api/surface_aggregator/clients/index.rst +++ b/Documentation/driver-api/surface_aggregator/clients/index.rst @@ -14,10 +14,3 @@ on how to write client drivers. cdev dtx san - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/driver-api/surface_aggregator/index.rst b/Documentation/driver-api/surface_aggregator/index.rst index 6f3e1094904d..f0128fe59a32 100644 --- a/Documentation/driver-api/surface_aggregator/index.rst +++ b/Documentation/driver-api/surface_aggregator/index.rst @@ -12,10 +12,3 @@ Surface System Aggregator Module (SSAM) clients/index ssh internal - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/driver-api/tty/tty_ldisc.rst b/Documentation/driver-api/tty/tty_ldisc.rst index 5144751be804..d034e117c232 100644 --- a/Documentation/driver-api/tty/tty_ldisc.rst +++ b/Documentation/driver-api/tty/tty_ldisc.rst @@ -18,7 +18,7 @@ Registration Line disciplines are registered with tty_register_ldisc() passing the ldisc structure. At the point of registration the discipline must be ready to use and it is possible it will get used before the call returns success. If the call -returns an error then it won’t get called. Do not re-use ldisc numbers as they +returns an error then it won’t get called. Do not reuse ldisc numbers as they are part of the userspace ABI and writing over an existing ldisc will cause demons to eat your computer. You must not re-register over the top of the line discipline even with the same data or your computer again will be eaten by diff --git a/Documentation/driver-api/usb/gadget.rst b/Documentation/driver-api/usb/gadget.rst index 09396edd6131..6f0c67885392 100644 --- a/Documentation/driver-api/usb/gadget.rst +++ b/Documentation/driver-api/usb/gadget.rst @@ -459,7 +459,7 @@ Linux-USB host side driver stack, or as a peripheral, using this ``gadget`` framework. To do that, the system software relies on small additions to those programming interfaces, and on a new internal component (here called an "OTG Controller") affecting which driver stack -connects to the OTG port. In each role, the system can re-use the +connects to the OTG port. In each role, the system can reuse the existing pool of hardware-neutral drivers, layered on top of the controller driver interfaces (:c:type:`usb_bus` or :c:type:`usb_gadget`). Such drivers need at most minor changes, and most of the calls added to diff --git a/Documentation/driver-api/usb/index.rst b/Documentation/driver-api/usb/index.rst index fcb24d0500d9..a32819963b99 100644 --- a/Documentation/driver-api/usb/index.rst +++ b/Documentation/driver-api/usb/index.rst @@ -22,10 +22,3 @@ Linux USB API typec typec_bus usb3-debug-port - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/driver-api/xilinx/index.rst b/Documentation/driver-api/xilinx/index.rst index 13f7589ed442..c95bda55da6f 100644 --- a/Documentation/driver-api/xilinx/index.rst +++ b/Documentation/driver-api/xilinx/index.rst @@ -7,10 +7,3 @@ Xilinx FPGA :maxdepth: 1 eemi - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/fault-injection/index.rst b/Documentation/fault-injection/index.rst index a6ea1d190222..2a9e30b4202c 100644 --- a/Documentation/fault-injection/index.rst +++ b/Documentation/fault-injection/index.rst @@ -11,10 +11,3 @@ Fault-injection notifier-error-inject nvme-fault-injection provoke-crashes - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/fb/index.rst b/Documentation/fb/index.rst index e2f7488b6e2e..fe9ca3570941 100644 --- a/Documentation/fb/index.rst +++ b/Documentation/fb/index.rst @@ -50,10 +50,3 @@ Driver documentation vesafb viafb vt8623fb - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/filesystems/api-summary.rst b/Documentation/filesystems/api-summary.rst index cc5cc7f3fbd8..bd7e3d5db581 100644 --- a/Documentation/filesystems/api-summary.rst +++ b/Documentation/filesystems/api-summary.rst @@ -56,6 +56,9 @@ Other Functions .. kernel-doc:: fs/namei.c :export: +.. kernel-doc:: fs/open.c + :export: + .. kernel-doc:: block/bio.c :export: diff --git a/Documentation/filesystems/erofs.rst b/Documentation/filesystems/erofs.rst index d6b3693eba60..fe06308e546c 100644 --- a/Documentation/filesystems/erofs.rst +++ b/Documentation/filesystems/erofs.rst @@ -162,7 +162,7 @@ to be as simple as possible:: 0 +1K All data areas should be aligned with the block size, but metadata areas -may not. All metadatas can be now observed in two different spaces (views): +may not. All metadata can be now observed in two different spaces (views): 1. Inode metadata space diff --git a/Documentation/filesystems/proc.rst b/Documentation/filesystems/proc.rst index 8256e857e2d7..b0c0d1b45b99 100644 --- a/Documentation/filesystems/proc.rst +++ b/Documentation/filesystems/proc.rst @@ -48,7 +48,7 @@ fixes/update part 1.1 Stefani Seibold <stefani@seibold.net> June 9 2009 3.11 /proc/<pid>/patch_state - Livepatch patch operation state 3.12 /proc/<pid>/arch_status - Task architecture specific information 3.13 /proc/<pid>/fd - List of symlinks to open files - 3.14 /proc/<pid/ksm_stat - Information about the process's ksm status. + 3.14 /proc/<pid>/ksm_stat - Information about the process's ksm status. 4 Configuring procfs 4.1 Mount options @@ -2289,8 +2289,8 @@ The number of open files for the process is stored in 'size' member of stat() output for /proc/<pid>/fd for fast access. ------------------------------------------------------- -3.14 /proc/<pid/ksm_stat - Information about the process's ksm status ---------------------------------------------------------------------- +3.14 /proc/<pid>/ksm_stat - Information about the process's ksm status +---------------------------------------------------------------------- When CONFIG_KSM is enabled, each process has this file which displays the information of ksm merging status. diff --git a/Documentation/filesystems/relay.rst b/Documentation/filesystems/relay.rst index 301ff4c6e6c6..dd6b52612b1d 100644 --- a/Documentation/filesystems/relay.rst +++ b/Documentation/filesystems/relay.rst @@ -452,7 +452,7 @@ closed. Misc ---- -Some applications may want to keep a channel around and re-use it +Some applications may want to keep a channel around and reuse it rather than open and close a new channel for each use. relay_reset() can be used for this purpose - it resets a channel to its initial state without reallocating channel buffer memory or destroying diff --git a/Documentation/filesystems/resctrl.rst b/Documentation/filesystems/resctrl.rst index 8c8ce678148a..5b27321f2313 100644 --- a/Documentation/filesystems/resctrl.rst +++ b/Documentation/filesystems/resctrl.rst @@ -482,7 +482,7 @@ with the following files: "max_threshold_occupancy": Read/write file provides the largest value (in bytes) at which a previously used LLC_occupancy - counter can be considered for re-use. + counter can be considered for reuse. Finally, in the top level of the "info" directory there is a file named "last_cmd_status". This is reset with every "command" issued diff --git a/Documentation/filesystems/spufs/spu_create.rst b/Documentation/filesystems/spufs/spu_create.rst index 83108c099696..c1f1d857f911 100644 --- a/Documentation/filesystems/spufs/spu_create.rst +++ b/Documentation/filesystems/spufs/spu_create.rst @@ -113,8 +113,8 @@ Files Conforming to ============= - This call is Linux specific and only implemented by the ppc64 architec- - ture. Programs using this system call are not portable. + This call is Linux specific and only implemented by the ppc64 + architecture. Programs using this system call are not portable. Bugs diff --git a/Documentation/filesystems/spufs/spu_run.rst b/Documentation/filesystems/spufs/spu_run.rst index 7fdb1c31cb91..c5fb416296a9 100644 --- a/Documentation/filesystems/spufs/spu_run.rst +++ b/Documentation/filesystems/spufs/spu_run.rst @@ -120,8 +120,8 @@ Notes Conforming to ============= - This call is Linux specific and only implemented by the ppc64 architec- - ture. Programs using this system call are not portable. + This call is Linux specific and only implemented by the ppc64 + architecture. Programs using this system call are not portable. Bugs diff --git a/Documentation/firmware-guide/acpi/DSD-properties-rules.rst b/Documentation/firmware-guide/acpi/DSD-properties-rules.rst index 70442bc2521e..98a350250df9 100644 --- a/Documentation/firmware-guide/acpi/DSD-properties-rules.rst +++ b/Documentation/firmware-guide/acpi/DSD-properties-rules.rst @@ -89,7 +89,7 @@ In those cases, however, the above validity considerations must be taken into account in the first place and returning invalid property sets from _DSD must be avoided. For this reason, it may not be possible to make _DSD return a property set following the given DT binding literally and completely. Still, for the -sake of code re-use, it may make sense to provide as much of the configuration +sake of code reuse, it may make sense to provide as much of the configuration data as possible in the form of device properties and complement that with an ACPI-specific mechanism suitable for the use case at hand. diff --git a/Documentation/firmware-guide/acpi/enumeration.rst b/Documentation/firmware-guide/acpi/enumeration.rst index 0165b09c0957..168c43012fb1 100644 --- a/Documentation/firmware-guide/acpi/enumeration.rst +++ b/Documentation/firmware-guide/acpi/enumeration.rst @@ -12,7 +12,7 @@ In addition we are starting to see peripherals integrated in the SoC/Chipset to appear only in ACPI namespace. These are typically devices that are accessed through memory-mapped registers. -In order to support this and re-use the existing drivers as much as +In order to support this and reuse the existing drivers as much as possible we decided to do following: - Devices that have no bus connector resource are represented as diff --git a/Documentation/fpga/index.rst b/Documentation/fpga/index.rst index 43c968871d99..c5a876165dab 100644 --- a/Documentation/fpga/index.rst +++ b/Documentation/fpga/index.rst @@ -8,10 +8,3 @@ FPGA :maxdepth: 1 dfl - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/gpu/drivers.rst b/Documentation/gpu/drivers.rst index 78b80be17f21..2e13e0ad7e88 100644 --- a/Documentation/gpu/drivers.rst +++ b/Documentation/gpu/drivers.rst @@ -26,10 +26,3 @@ GPU Driver Documentation panthor zynqmp nova/index - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/gpu/index.rst b/Documentation/gpu/index.rst index 7dcb15850afd..2fafa1f35ef3 100644 --- a/Documentation/gpu/index.rst +++ b/Documentation/gpu/index.rst @@ -22,10 +22,3 @@ GPU Driver Developer's Guide implementation_guidelines todo rfc/index - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/hwmon/index.rst b/Documentation/hwmon/index.rst index 85d7a686883e..fc9d39b098ef 100644 --- a/Documentation/hwmon/index.rst +++ b/Documentation/hwmon/index.rst @@ -281,10 +281,3 @@ Hardware Monitoring Kernel Drivers xdpe12284 xdpe152c4 zl6100 - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/i2c/index.rst b/Documentation/i2c/index.rst index 2b213d4ce89c..ccf13718ce70 100644 --- a/Documentation/i2c/index.rst +++ b/Documentation/i2c/index.rst @@ -66,10 +66,3 @@ Legacy documentation :maxdepth: 1 old-module-parameters - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/infiniband/index.rst b/Documentation/infiniband/index.rst index 5b4c24125f66..c11049d25703 100644 --- a/Documentation/infiniband/index.rst +++ b/Documentation/infiniband/index.rst @@ -15,10 +15,3 @@ InfiniBand ucaps user_mad user_verbs - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/input/devices/index.rst b/Documentation/input/devices/index.rst index 95a453782bad..6de4365ad288 100644 --- a/Documentation/input/devices/index.rst +++ b/Documentation/input/devices/index.rst @@ -10,10 +10,3 @@ Linux kernel, their protocols, and driver details. :glob: * - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/input/gamepad.rst b/Documentation/input/gamepad.rst index 0c918b6f288b..ddc65fa36f11 100644 --- a/Documentation/input/gamepad.rst +++ b/Documentation/input/gamepad.rst @@ -79,7 +79,7 @@ change the mappings so you can advise users to set these. All new gamepads are supposed to comply with this mapping. Please report any bugs, if they don't. -There are a lot of less-featured/less-powerful devices out there, which re-use +There are a lot of less-featured/less-powerful devices out there, which reuse the buttons from this protocol. However, they try to do this in a compatible fashion. For example, the "Nintendo Wii Nunchuk" provides two trigger buttons and one analog stick. It reports them as if it were a gamepad with only one diff --git a/Documentation/input/index.rst b/Documentation/input/index.rst index 35581cd18e91..fbde5bc9f641 100644 --- a/Documentation/input/index.rst +++ b/Documentation/input/index.rst @@ -10,10 +10,3 @@ Contents: input_uapi input_kapi devices/index - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/input/input.rst b/Documentation/input/input.rst index d9a6de87d02d..7bbda39d8ac2 100644 --- a/Documentation/input/input.rst +++ b/Documentation/input/input.rst @@ -278,4 +278,4 @@ list is in include/uapi/linux/input-event-codes.h. EV_REL, absolute new value for EV_ABS (joysticks ...), or 0 for EV_KEY for release, 1 for keypress and 2 for autorepeat. -See :ref:`input-event-codes` for more information about various even codes. +See :ref:`input-event-codes` for more information about various event codes. diff --git a/Documentation/isdn/index.rst b/Documentation/isdn/index.rst index 9622939fa526..d1125a16a746 100644 --- a/Documentation/isdn/index.rst +++ b/Documentation/isdn/index.rst @@ -12,10 +12,3 @@ ISDN m_isdn credits - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/kbuild/index.rst b/Documentation/kbuild/index.rst index 3731ab22bfe7..f46233be82b9 100644 --- a/Documentation/kbuild/index.rst +++ b/Documentation/kbuild/index.rst @@ -24,10 +24,3 @@ Kernel Build System gendwarfksyms bash-completion - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/kbuild/kbuild.rst b/Documentation/kbuild/kbuild.rst index 82826b0332df..5a9013bacfb7 100644 --- a/Documentation/kbuild/kbuild.rst +++ b/Documentation/kbuild/kbuild.rst @@ -180,7 +180,7 @@ architecture. KDOCFLAGS --------- Specify extra (warning/error) flags for kernel-doc checks during the build, -see scripts/kernel-doc for which flags are supported. Note that this doesn't +see tools/docs/kernel-doc for which flags are supported. Note that this doesn't (currently) apply to documentation builds. ARCH diff --git a/Documentation/kbuild/kconfig-language.rst b/Documentation/kbuild/kconfig-language.rst index abce88f15d7c..7067ec3f0011 100644 --- a/Documentation/kbuild/kconfig-language.rst +++ b/Documentation/kbuild/kconfig-language.rst @@ -216,7 +216,7 @@ applicable everywhere (see syntax). - numerical ranges: "range" <symbol> <symbol> ["if" <expr>] - This allows to limit the range of possible input values for int + This allows limiting the range of possible input values for int and hex symbols. The user can only input a value which is larger than or equal to the first symbol and smaller than or equal to the second symbol. diff --git a/Documentation/kbuild/makefiles.rst b/Documentation/kbuild/makefiles.rst index 8aef3650c1f3..24a4708d26e8 100644 --- a/Documentation/kbuild/makefiles.rst +++ b/Documentation/kbuild/makefiles.rst @@ -1264,7 +1264,7 @@ Add prerequisites to archheaders -------------------------------- The archheaders: rule is used to generate header files that -may be installed into user space by ``make header_install``. +may be installed into user space by ``make headers_install``. It is run before ``make archprepare`` when run on the architecture itself. diff --git a/Documentation/kernel-hacking/hacking.rst b/Documentation/kernel-hacking/hacking.rst index 0042776a9e17..ef527bdc5f8d 100644 --- a/Documentation/kernel-hacking/hacking.rst +++ b/Documentation/kernel-hacking/hacking.rst @@ -49,7 +49,7 @@ User Context User context is when you are coming in from a system call or other trap: like userspace, you can be preempted by more important tasks and by -interrupts. You can sleep, by calling :c:func:`schedule()`. +interrupts. You can sleep by calling schedule(). .. note:: @@ -57,13 +57,13 @@ interrupts. You can sleep, by calling :c:func:`schedule()`. operations on the block device layer. In user context, the ``current`` pointer (indicating the task we are -currently executing) is valid, and :c:func:`in_interrupt()` +currently executing) is valid, and in_interrupt() (``include/linux/preempt.h``) is false. .. warning:: Beware that if you have preemption or softirqs disabled (see below), - :c:func:`in_interrupt()` will return a false positive. + in_interrupt() will return a false positive. Hardware Interrupts (Hard IRQs) ------------------------------- @@ -115,7 +115,7 @@ time, although different tasklets can run simultaneously. 'tasks'. You can tell you are in a softirq (or tasklet) using the -:c:func:`in_softirq()` macro (``include/linux/preempt.h``). +in_softirq() macro (``include/linux/preempt.h``). .. warning:: @@ -171,7 +171,7 @@ in every architecture's ``include/asm/unistd.h`` and Linus. If all your routine does is read or write some parameter, consider -implementing a :c:func:`sysfs()` interface instead. +implementing a sysfs() interface instead. Inside the ioctl you're in user context to a process. When a error occurs you return a negated errno (see @@ -230,12 +230,12 @@ Really. Common Routines =============== -:c:func:`printk()` ------------------- +printk() +-------- Defined in ``include/linux/printk.h`` -:c:func:`printk()` feeds kernel messages to the console, dmesg, and +printk() feeds kernel messages to the console, dmesg, and the syslog daemon. It is useful for debugging and reporting errors, and can be used inside interrupt context, but use with caution: a machine which has its console flooded with printk messages is unusable. It uses @@ -253,7 +253,7 @@ address use:: printk(KERN_INFO "my ip: %pI4\n", &ipaddress); -:c:func:`printk()` internally uses a 1K buffer and does not catch +printk() internally uses a 1K buffer and does not catch overruns. Make sure that will be enough. .. note:: @@ -267,26 +267,26 @@ overruns. Make sure that will be enough. on top of its printf function: "Printf should not be used for chit-chat". You should follow that advice. -:c:func:`copy_to_user()` / :c:func:`copy_from_user()` / :c:func:`get_user()` / :c:func:`put_user()` ---------------------------------------------------------------------------------------------------- +copy_to_user() / copy_from_user() / get_user() / put_user() +----------------------------------------------------------- Defined in ``include/linux/uaccess.h`` / ``asm/uaccess.h`` **[SLEEPS]** -:c:func:`put_user()` and :c:func:`get_user()` are used to get +put_user() and get_user() are used to get and put single values (such as an int, char, or long) from and to userspace. A pointer into userspace should never be simply dereferenced: data should be copied using these routines. Both return ``-EFAULT`` or 0. -:c:func:`copy_to_user()` and :c:func:`copy_from_user()` are +copy_to_user() and copy_from_user() are more general: they copy an arbitrary amount of data to and from userspace. .. warning:: - Unlike :c:func:`put_user()` and :c:func:`get_user()`, they + Unlike put_user() and get_user(), they return the amount of uncopied data (ie. 0 still means success). [Yes, this objectionable interface makes me cringe. The flamewar comes @@ -296,8 +296,8 @@ The functions may sleep implicitly. This should never be called outside user context (it makes no sense), with interrupts disabled, or a spinlock held. -:c:func:`kmalloc()`/:c:func:`kfree()` -------------------------------------- +kmalloc()/kfree() +----------------- Defined in ``include/linux/slab.h`` @@ -305,7 +305,7 @@ Defined in ``include/linux/slab.h`` These routines are used to dynamically request pointer-aligned chunks of memory, like malloc and free do in userspace, but -:c:func:`kmalloc()` takes an extra flag word. Important values: +kmalloc() takes an extra flag word. Important values: ``GFP_KERNEL`` May sleep and swap to free memory. Only allowed in user context, but @@ -326,27 +326,27 @@ interrupt context without ``GFP_ATOMIC``. You should really fix that. Run, don't walk. If you are allocating at least ``PAGE_SIZE`` (``asm/page.h`` or -``asm/page_types.h``) bytes, consider using :c:func:`__get_free_pages()` +``asm/page_types.h``) bytes, consider using __get_free_pages() (``include/linux/gfp.h``). It takes an order argument (0 for page sized, 1 for double page, 2 for four pages etc.) and the same memory priority flag word as above. If you are allocating more than a page worth of bytes you can use -:c:func:`vmalloc()`. It'll allocate virtual memory in the kernel +vmalloc(). It'll allocate virtual memory in the kernel map. This block is not contiguous in physical memory, but the MMU makes it look like it is for you (so it'll only look contiguous to the CPUs, not to external device drivers). If you really need large physically contiguous memory for some weird device, you have a problem: it is poorly supported in Linux because after some time memory fragmentation in a running kernel makes it hard. The best way is to allocate the block -early in the boot process via the :c:func:`alloc_bootmem()` +early in the boot process via the alloc_bootmem() routine. Before inventing your own cache of often-used objects consider using a slab cache in ``include/linux/slab.h`` -:c:macro:`current` ------------------- +current +------- Defined in ``include/asm/current.h`` @@ -355,48 +355,48 @@ task structure, so is only valid in user context. For example, when a process makes a system call, this will point to the task structure of the calling process. It is **not NULL** in interrupt context. -:c:func:`mdelay()`/:c:func:`udelay()` -------------------------------------- +mdelay()/udelay() +----------------- Defined in ``include/asm/delay.h`` / ``include/linux/delay.h`` -The :c:func:`udelay()` and :c:func:`ndelay()` functions can be +The udelay() and ndelay() functions can be used for small pauses. Do not use large values with them as you risk -overflow - the helper function :c:func:`mdelay()` is useful here, or -consider :c:func:`msleep()`. +overflow - the helper function mdelay() is useful here, or +consider msleep(). -:c:func:`cpu_to_be32()`/:c:func:`be32_to_cpu()`/:c:func:`cpu_to_le32()`/:c:func:`le32_to_cpu()` ------------------------------------------------------------------------------------------------ +cpu_to_be32()/be32_to_cpu()/cpu_to_le32()/le32_to_cpu() +------------------------------------------------------- Defined in ``include/asm/byteorder.h`` -The :c:func:`cpu_to_be32()` family (where the "32" can be replaced +The cpu_to_be32() family (where the "32" can be replaced by 64 or 16, and the "be" can be replaced by "le") are the general way to do endian conversions in the kernel: they return the converted value. All variations supply the reverse as well: -:c:func:`be32_to_cpu()`, etc. +be32_to_cpu(), etc. There are two major variations of these functions: the pointer -variation, such as :c:func:`cpu_to_be32p()`, which take a pointer +variation, such as cpu_to_be32p(), which take a pointer to the given type, and return the converted value. The other variation -is the "in-situ" family, such as :c:func:`cpu_to_be32s()`, which +is the "in-situ" family, such as cpu_to_be32s(), which convert value referred to by the pointer, and return void. -:c:func:`local_irq_save()`/:c:func:`local_irq_restore()` --------------------------------------------------------- +local_irq_save()/local_irq_restore() +------------------------------------ Defined in ``include/linux/irqflags.h`` These routines disable hard interrupts on the local CPU, and restore them. They are reentrant; saving the previous state in their one ``unsigned long flags`` argument. If you know that interrupts are -enabled, you can simply use :c:func:`local_irq_disable()` and -:c:func:`local_irq_enable()`. +enabled, you can simply use local_irq_disable() and +local_irq_enable(). .. _local_bh_disable: -:c:func:`local_bh_disable()`/:c:func:`local_bh_enable()` --------------------------------------------------------- +local_bh_disable()/local_bh_enable() +------------------------------------ Defined in ``include/linux/bottom_half.h`` @@ -406,15 +406,15 @@ them. They are reentrant; if soft interrupts were disabled before, they will still be disabled after this pair of functions has been called. They prevent softirqs and tasklets from running on the current CPU. -:c:func:`smp_processor_id()` ----------------------------- +smp_processor_id() +------------------ Defined in ``include/linux/smp.h`` -:c:func:`get_cpu()` disables preemption (so you won't suddenly get +get_cpu() disables preemption (so you won't suddenly get moved to another CPU) and returns the current processor number, between 0 and ``NR_CPUS``. Note that the CPU numbers are not necessarily -continuous. You return it again with :c:func:`put_cpu()` when you +continuous. You return it again with put_cpu() when you are done. If you know you cannot be preempted by another task (ie. you are in @@ -433,25 +433,25 @@ initialization. ``__exit`` is used to declare a function which is only required on exit: the function will be dropped if this file is not compiled as a module. See the header file for use. Note that it makes no sense for a function marked with ``__init`` to be exported to modules -with :c:func:`EXPORT_SYMBOL()` or :c:func:`EXPORT_SYMBOL_GPL()`- this +with EXPORT_SYMBOL() or EXPORT_SYMBOL_GPL()- this will break. -:c:func:`__initcall()`/:c:func:`module_init()` ----------------------------------------------- +__initcall()/module_init() +-------------------------- Defined in ``include/linux/init.h`` / ``include/linux/module.h`` Many parts of the kernel are well served as a module (dynamically-loadable parts of the kernel). Using the -:c:func:`module_init()` and :c:func:`module_exit()` macros it +module_init() and module_exit() macros it is easy to write code without #ifdefs which can operate both as a module or built into the kernel. -The :c:func:`module_init()` macro defines which function is to be +The module_init() macro defines which function is to be called at module insertion time (if the file is compiled as a module), or at boot time: if the file is not compiled as a module the -:c:func:`module_init()` macro becomes equivalent to -:c:func:`__initcall()`, which through linker magic ensures that +module_init() macro becomes equivalent to +__initcall(), which through linker magic ensures that the function is called on boot. The function can return a negative error number to cause module loading @@ -459,9 +459,8 @@ to fail (unfortunately, this has no effect if the module is compiled into the kernel). This function is called in user context with interrupts enabled, so it can sleep. -:c:func:`module_exit()` ------------------------ - +module_exit() +------------- Defined in ``include/linux/module.h`` @@ -474,18 +473,18 @@ it returns. Note that this macro is optional: if it is not present, your module will not be removable (except for 'rmmod -f'). -:c:func:`try_module_get()`/:c:func:`module_put()` -------------------------------------------------- +try_module_get()/module_put() +----------------------------- Defined in ``include/linux/module.h`` These manipulate the module usage count, to protect against removal (a module also can't be removed if another module uses one of its exported symbols: see below). Before calling into module code, you should call -:c:func:`try_module_get()` on that module: if it fails, then the +try_module_get() on that module: if it fails, then the module is being removed and you should act as if it wasn't there. Otherwise, you can safely enter the module, and call -:c:func:`module_put()` when you're finished. +module_put() when you're finished. Most registerable structures have an owner field, such as in the :c:type:`struct file_operations <file_operations>` structure. @@ -506,8 +505,8 @@ Declaring --------- You declare a ``wait_queue_head_t`` using the -:c:func:`DECLARE_WAIT_QUEUE_HEAD()` macro, or using the -:c:func:`init_waitqueue_head()` routine in your initialization +DECLARE_WAIT_QUEUE_HEAD() macro, or using the +init_waitqueue_head() routine in your initialization code. Queuing @@ -515,16 +514,16 @@ Queuing Placing yourself in the waitqueue is fairly complex, because you must put yourself in the queue before checking the condition. There is a -macro to do this: :c:func:`wait_event_interruptible()` +macro to do this: wait_event_interruptible() (``include/linux/wait.h``) The first argument is the wait queue head, and the second is an expression which is evaluated; the macro returns 0 when this expression is true, or ``-ERESTARTSYS`` if a signal is received. The -:c:func:`wait_event()` version ignores signals. +wait_event() version ignores signals. Waking Up Queued Tasks ---------------------- -Call :c:func:`wake_up()` (``include/linux/wait.h``), which will wake +Call wake_up() (``include/linux/wait.h``), which will wake up every process in the queue. The exception is if one has ``TASK_EXCLUSIVE`` set, in which case the remainder of the queue will not be woken. There are other variants of this basic function available @@ -537,10 +536,10 @@ Certain operations are guaranteed atomic on all platforms. The first class of operations work on :c:type:`atomic_t` (``include/asm/atomic.h``); this contains a signed integer (at least 32 bits long), and you must use these functions to manipulate or read :c:type:`atomic_t` variables. -:c:func:`atomic_read()` and :c:func:`atomic_set()` get and set -the counter, :c:func:`atomic_add()`, :c:func:`atomic_sub()`, -:c:func:`atomic_inc()`, :c:func:`atomic_dec()`, and -:c:func:`atomic_dec_and_test()` (returns true if it was +atomic_read() and atomic_set() get and set +the counter, atomic_add(), atomic_sub(), +atomic_inc(), atomic_dec(), and +atomic_dec_and_test() (returns true if it was decremented to zero). Yes. It returns true (i.e. != 0) if the atomic variable is zero. @@ -551,11 +550,11 @@ should not be used unnecessarily. The second class of atomic operations is atomic bit operations on an ``unsigned long``, defined in ``include/linux/bitops.h``. These operations generally take a pointer to the bit pattern, and a bit -number: 0 is the least significant bit. :c:func:`set_bit()`, -:c:func:`clear_bit()` and :c:func:`change_bit()` set, clear, -and flip the given bit. :c:func:`test_and_set_bit()`, -:c:func:`test_and_clear_bit()` and -:c:func:`test_and_change_bit()` do the same thing, except return +number: 0 is the least significant bit. set_bit(), +clear_bit() and change_bit() set, clear, +and flip the given bit. test_and_set_bit(), +test_and_clear_bit() and +test_and_change_bit() do the same thing, except return true if the bit was previously set; these are particularly useful for atomically setting flags. @@ -572,42 +571,42 @@ be used anywhere in the kernel). However, for modules, a special exported symbol table is kept which limits the entry points to the kernel proper. Modules can also export symbols. -:c:func:`EXPORT_SYMBOL()` -------------------------- +EXPORT_SYMBOL() +--------------- Defined in ``include/linux/export.h`` This is the classic method of exporting a symbol: dynamically loaded modules will be able to use the symbol as normal. -:c:func:`EXPORT_SYMBOL_GPL()` ------------------------------ +EXPORT_SYMBOL_GPL() +------------------- Defined in ``include/linux/export.h`` -Similar to :c:func:`EXPORT_SYMBOL()` except that the symbols -exported by :c:func:`EXPORT_SYMBOL_GPL()` can only be seen by -modules with a :c:func:`MODULE_LICENSE()` that specifies a GPLv2 +Similar to EXPORT_SYMBOL() except that the symbols +exported by EXPORT_SYMBOL_GPL() can only be seen by +modules with a MODULE_LICENSE() that specifies a GPLv2 compatible license. It implies that the function is considered an internal implementation issue, and not really an interface. Some maintainers and developers may however require EXPORT_SYMBOL_GPL() when adding any new APIs or functionality. -:c:func:`EXPORT_SYMBOL_NS()` ----------------------------- +EXPORT_SYMBOL_NS() +------------------ Defined in ``include/linux/export.h`` -This is the variant of `EXPORT_SYMBOL()` that allows specifying a symbol +This is the variant of EXPORT_SYMBOL() that allows specifying a symbol namespace. Symbol Namespaces are documented in Documentation/core-api/symbol-namespaces.rst -:c:func:`EXPORT_SYMBOL_NS_GPL()` --------------------------------- +EXPORT_SYMBOL_NS_GPL() +---------------------- Defined in ``include/linux/export.h`` -This is the variant of `EXPORT_SYMBOL_GPL()` that allows specifying a symbol +This is the variant of EXPORT_SYMBOL_GPL() that allows specifying a symbol namespace. Symbol Namespaces are documented in Documentation/core-api/symbol-namespaces.rst @@ -621,7 +620,7 @@ There used to be three sets of linked-list routines in the kernel headers, but this one is the winner. If you don't have some particular pressing need for a single list, it's a good choice. -In particular, :c:func:`list_for_each_entry()` is useful. +In particular, list_for_each_entry() is useful. Return Conventions ------------------ @@ -631,9 +630,9 @@ and return 0 for success, and a negative error number (eg. ``-EFAULT``) for failure. This can be unintuitive at first, but it's fairly widespread in the kernel. -Using :c:func:`ERR_PTR()` (``include/linux/err.h``) to encode a -negative error number into a pointer, and :c:func:`IS_ERR()` and -:c:func:`PTR_ERR()` to get it back out again: avoids a separate +Using ERR_PTR() (``include/linux/err.h``) to encode a +negative error number into a pointer, and IS_ERR() and +PTR_ERR() to get it back out again: avoids a separate pointer parameter for the error number. Icky, but in a good way. Breaking Compilation @@ -736,7 +735,7 @@ make a neat patch, there's administrative work to be done: - Usually you want a configuration option for your kernel hack. Edit ``Kconfig`` in the appropriate directory. The Config language is simple to use by cut and paste, and there's complete documentation in - ``Documentation/kbuild/kconfig-language.rst``. + Documentation/kbuild/kconfig-language.rst. In your description of the option, make sure you address both the expert user and the user who knows nothing about your feature. @@ -746,7 +745,7 @@ make a neat patch, there's administrative work to be done: - Edit the ``Makefile``: the CONFIG variables are exported here so you can usually just add a "obj-$(CONFIG_xxx) += xxx.o" line. The syntax - is documented in ``Documentation/kbuild/makefiles.rst``. + is documented in Documentation/kbuild/makefiles.rst. - Put yourself in ``CREDITS`` if you consider what you've done noteworthy, usually beyond a single file (your name should be at the @@ -755,7 +754,7 @@ make a neat patch, there's administrative work to be done: it implies a more-than-passing commitment to some part of the code. - Finally, don't forget to read - ``Documentation/process/submitting-patches.rst`` + Documentation/process/submitting-patches.rst. Kernel Cantrips =============== @@ -824,7 +823,7 @@ Thanks Thanks to Andi Kleen for the idea, answering my questions, fixing my mistakes, filling content, etc. Philipp Rumpf for more spelling and clarity fixes, and some excellent non-obvious points. Werner Almesberger -for giving me a great summary of :c:func:`disable_irq()`, and Jes +for giving me a great summary of disable_irq(), and Jes Sorensen and Andrea Arcangeli added caveats. Michael Elizabeth Chastain for checking and adding to the Configure section. Telsa Gwynne for teaching me DocBook. diff --git a/Documentation/livepatch/index.rst b/Documentation/livepatch/index.rst index cebf1c71d4a5..d2e7aa0f7f89 100644 --- a/Documentation/livepatch/index.rst +++ b/Documentation/livepatch/index.rst @@ -15,10 +15,3 @@ Kernel Livepatching system-state reliable-stacktrace api - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/locking/index.rst b/Documentation/locking/index.rst index 6a9ea96c8bcb..9278d95b7dcb 100644 --- a/Documentation/locking/index.rst +++ b/Documentation/locking/index.rst @@ -24,10 +24,3 @@ Locking percpu-rw-semaphore robust-futexes robust-futex-ABI - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/mhi/index.rst b/Documentation/mhi/index.rst index 1d8dec302780..0aa00482aa2e 100644 --- a/Documentation/mhi/index.rst +++ b/Documentation/mhi/index.rst @@ -9,10 +9,3 @@ MHI mhi topology - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/netlabel/index.rst b/Documentation/netlabel/index.rst index 984e1b191b12..bb6ba7d5c200 100644 --- a/Documentation/netlabel/index.rst +++ b/Documentation/netlabel/index.rst @@ -12,10 +12,3 @@ NetLabel lsm_interface draft_ietf - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/networking/device_drivers/atm/index.rst b/Documentation/networking/device_drivers/atm/index.rst index 7b593f031a60..724552ca0be4 100644 --- a/Documentation/networking/device_drivers/atm/index.rst +++ b/Documentation/networking/device_drivers/atm/index.rst @@ -11,10 +11,3 @@ Contents: cxacru fore200e iphase - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/networking/device_drivers/can/index.rst b/Documentation/networking/device_drivers/can/index.rst index 6a8a4f74fa26..af4369989522 100644 --- a/Documentation/networking/device_drivers/can/index.rst +++ b/Documentation/networking/device_drivers/can/index.rst @@ -13,10 +13,3 @@ Contents: can327 ctu/ctucanfd-driver freescale/flexcan - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/networking/device_drivers/cellular/index.rst b/Documentation/networking/device_drivers/cellular/index.rst index fc1812d3fc70..9690c3ba08ef 100644 --- a/Documentation/networking/device_drivers/cellular/index.rst +++ b/Documentation/networking/device_drivers/cellular/index.rst @@ -9,10 +9,3 @@ Contents: :maxdepth: 2 qualcomm/rmnet - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/networking/device_drivers/ethernet/index.rst b/Documentation/networking/device_drivers/ethernet/index.rst index bcc02355f828..142ac0bf781b 100644 --- a/Documentation/networking/device_drivers/ethernet/index.rst +++ b/Documentation/networking/device_drivers/ethernet/index.rst @@ -64,10 +64,3 @@ Contents: wangxun/txgbevf wangxun/ngbe wangxun/ngbevf - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/networking/device_drivers/ethernet/mellanox/mlx5/index.rst b/Documentation/networking/device_drivers/ethernet/mellanox/mlx5/index.rst index 581a91caa579..56f3966de3f0 100644 --- a/Documentation/networking/device_drivers/ethernet/mellanox/mlx5/index.rst +++ b/Documentation/networking/device_drivers/ethernet/mellanox/mlx5/index.rst @@ -16,10 +16,3 @@ Contents: switchdev tracepoints counters - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/networking/device_drivers/fddi/index.rst b/Documentation/networking/device_drivers/fddi/index.rst index 0b75294e6c8b..c7cf2347e215 100644 --- a/Documentation/networking/device_drivers/fddi/index.rst +++ b/Documentation/networking/device_drivers/fddi/index.rst @@ -10,10 +10,3 @@ Contents: defza skfp - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/networking/device_drivers/hamradio/index.rst b/Documentation/networking/device_drivers/hamradio/index.rst index 7e731732057b..6af481c5b020 100644 --- a/Documentation/networking/device_drivers/hamradio/index.rst +++ b/Documentation/networking/device_drivers/hamradio/index.rst @@ -10,10 +10,3 @@ Contents: baycom z8530drv - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/networking/device_drivers/index.rst b/Documentation/networking/device_drivers/index.rst index a254af25b7ef..1df51c9f7827 100644 --- a/Documentation/networking/device_drivers/index.rst +++ b/Documentation/networking/device_drivers/index.rst @@ -16,10 +16,3 @@ Contents: hamradio/index wifi/index wwan/index - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/networking/device_drivers/wifi/index.rst b/Documentation/networking/device_drivers/wifi/index.rst index fb394f5de4a9..29ba9ea64b25 100644 --- a/Documentation/networking/device_drivers/wifi/index.rst +++ b/Documentation/networking/device_drivers/wifi/index.rst @@ -10,10 +10,3 @@ Contents: intel/ipw2100 intel/ipw2200 - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/networking/device_drivers/wwan/index.rst b/Documentation/networking/device_drivers/wwan/index.rst index 370d8264d5dc..b768ae89f723 100644 --- a/Documentation/networking/device_drivers/wwan/index.rst +++ b/Documentation/networking/device_drivers/wwan/index.rst @@ -10,10 +10,3 @@ Contents: iosm t7xx - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/networking/diagnostic/index.rst b/Documentation/networking/diagnostic/index.rst index 86488aa46b48..592263a2713a 100644 --- a/Documentation/networking/diagnostic/index.rst +++ b/Documentation/networking/diagnostic/index.rst @@ -8,10 +8,3 @@ Networking Diagnostics :maxdepth: 2 twisted_pair_layer1_diagnostics.rst - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/networking/index.rst b/Documentation/networking/index.rst index 75db2251649b..0f72de94b881 100644 --- a/Documentation/networking/index.rst +++ b/Documentation/networking/index.rst @@ -134,10 +134,3 @@ Contents: xfrm/index xdp-rx-metadata xsk-tx-metadata - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/pcmcia/index.rst b/Documentation/pcmcia/index.rst index 8067236c51ab..89c004816140 100644 --- a/Documentation/pcmcia/index.rst +++ b/Documentation/pcmcia/index.rst @@ -11,10 +11,3 @@ PCMCIA devicetable locking driver-changes - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/peci/index.rst b/Documentation/peci/index.rst index 930e75217c33..1443c31a0d18 100644 --- a/Documentation/peci/index.rst +++ b/Documentation/peci/index.rst @@ -7,10 +7,3 @@ PECI Subsystem .. toctree:: peci - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/power/index.rst b/Documentation/power/index.rst index ea70633d9ce6..b4581e4ae785 100644 --- a/Documentation/power/index.rst +++ b/Documentation/power/index.rst @@ -38,10 +38,3 @@ Power Management regulator/machine regulator/overview regulator/regulator - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/process/1.Intro.rst b/Documentation/process/1.Intro.rst index 25ca49f7ae4d..2c93caea069f 100644 --- a/Documentation/process/1.Intro.rst +++ b/Documentation/process/1.Intro.rst @@ -194,7 +194,7 @@ include: are cloudy at best; quite a few kernel copyright holders believe that most binary-only modules are derived products of the kernel and that, as a result, their distribution is a violation of the GNU General Public - license (about which more will be said below). Your author is not a + License (about which more will be said below). Your author is not a lawyer, and nothing in this document can possibly be considered to be legal advice. The true legal status of closed-source modules can only be determined by the courts. But the uncertainty which haunts those modules diff --git a/Documentation/process/2.Process.rst b/Documentation/process/2.Process.rst index 7bd41838a546..57fa8cac58a6 100644 --- a/Documentation/process/2.Process.rst +++ b/Documentation/process/2.Process.rst @@ -3,7 +3,7 @@ How the development process works ================================= -Linux kernel development in the early 1990's was a pretty loose affair, +Linux kernel development in the early 1990s was a pretty loose affair, with relatively small numbers of users and developers involved. With a user base in the millions and with some 2,000 developers involved over the course of one year, the kernel has since had to evolve a number of diff --git a/Documentation/process/4.Coding.rst b/Documentation/process/4.Coding.rst index 80bcc1cabc23..c0f57d0c4f73 100644 --- a/Documentation/process/4.Coding.rst +++ b/Documentation/process/4.Coding.rst @@ -160,12 +160,12 @@ irrelevant. Locking ******* -In May, 2006, the "Devicescape" networking stack was, with great +In May 2006, the "Devicescape" networking stack was, with great fanfare, released under the GPL and made available for inclusion in the mainline kernel. This donation was welcome news; support for wireless networking in Linux was considered substandard at best, and the Devicescape stack offered the promise of fixing that situation. Yet, this code did not -actually make it into the mainline until June, 2007 (2.6.22). What +actually make it into the mainline until June 2007 (2.6.22). What happened? This code showed a number of signs of having been developed behind @@ -204,7 +204,7 @@ regression in the first place. It is often argued that a regression can be justified if it causes things to work for more people than it creates problems for. Why not make a change if it brings new functionality to ten systems for each one it -breaks? The best answer to this question was expressed by Linus in July, +breaks? The best answer to this question was expressed by Linus in July 2007: :: diff --git a/Documentation/process/5.Posting.rst b/Documentation/process/5.Posting.rst index 9999bcbdccc9..07d7dbed13ec 100644 --- a/Documentation/process/5.Posting.rst +++ b/Documentation/process/5.Posting.rst @@ -40,7 +40,12 @@ sending patches to the development community. These include: - Test the code to the extent that you can. Make use of the kernel's debugging tools, ensure that the kernel will build with all reasonable combinations of configuration options, use cross-compilers to build for - different architectures, etc. + different architectures, etc. Add tests, likely using an existing + testing framework like KUnit, and include them as a separate member + of your series (see the next section for more about patch series). + Note that this may be mandatory when affecting some subsystems. For + example, library functions (resides under lib/) are extensively used + almost everywhere and expected to be tested appropriately. - Make sure your code is compliant with the kernel coding style guidelines. diff --git a/Documentation/process/7.AdvancedTopics.rst b/Documentation/process/7.AdvancedTopics.rst index 43291704338e..185651d87f2a 100644 --- a/Documentation/process/7.AdvancedTopics.rst +++ b/Documentation/process/7.AdvancedTopics.rst @@ -53,7 +53,7 @@ When you are ready to start putting up git trees for others to look at, you will, of course, need a server that can be pulled from. Setting up such a server with git-daemon is relatively straightforward if you have a system which is accessible to the Internet. Otherwise, free, public hosting sites -(Github, for example) are starting to appear on the net. Established +(GitHub, for example) are starting to appear on the net. Established developers can get an account on kernel.org, but those are not easy to come by; see https://kernel.org/faq/ for more information. diff --git a/Documentation/process/adding-syscalls.rst b/Documentation/process/adding-syscalls.rst index fc0b0bbcd34d..91fc88681b1e 100644 --- a/Documentation/process/adding-syscalls.rst +++ b/Documentation/process/adding-syscalls.rst @@ -111,13 +111,13 @@ should use a file descriptor as the handle for that object -- don't invent a new type of userspace object handle when the kernel already has mechanisms and well-defined semantics for using file descriptors. -If your new :manpage:`xyzzy(2)` system call does return a new file descriptor, +If your new xyzzy(2) system call does return a new file descriptor, then the flags argument should include a value that is equivalent to setting ``O_CLOEXEC`` on the new FD. This makes it possible for userspace to close the timing window between ``xyzzy()`` and calling ``fcntl(fd, F_SETFD, FD_CLOEXEC)``, where an unexpected ``fork()`` and ``execve()`` in another thread could leak a descriptor to -the exec'ed program. (However, resist the temptation to re-use the actual value +the exec'ed program. (However, resist the temptation to reuse the actual value of the ``O_CLOEXEC`` constant, as it is architecture-specific and is part of a numbering space of ``O_*`` flags that is fairly full.) @@ -127,18 +127,18 @@ descriptor. Making a file descriptor ready for reading or writing is the normal way for the kernel to indicate to userspace that an event has occurred on the corresponding kernel object. -If your new :manpage:`xyzzy(2)` system call involves a filename argument:: +If your new xyzzy(2) system call involves a filename argument:: int sys_xyzzy(const char __user *path, ..., unsigned int flags); -you should also consider whether an :manpage:`xyzzyat(2)` version is more appropriate:: +you should also consider whether an xyzzyat(2) version is more appropriate:: int sys_xyzzyat(int dfd, const char __user *path, ..., unsigned int flags); This allows more flexibility for how userspace specifies the file in question; in particular it allows userspace to request the functionality for an already-opened file descriptor using the ``AT_EMPTY_PATH`` flag, effectively -giving an :manpage:`fxyzzy(3)` operation for free:: +giving an fxyzzy(3) operation for free:: - xyzzyat(AT_FDCWD, path, ..., 0) is equivalent to xyzzy(path,...) - xyzzyat(fd, "", ..., AT_EMPTY_PATH) is equivalent to fxyzzy(fd, ...) @@ -147,11 +147,11 @@ giving an :manpage:`fxyzzy(3)` operation for free:: :manpage:`openat(2)` man page; for an example of AT_EMPTY_PATH, see the :manpage:`fstatat(2)` man page.) -If your new :manpage:`xyzzy(2)` system call involves a parameter describing an +If your new xyzzy(2) system call involves a parameter describing an offset within a file, make its type ``loff_t`` so that 64-bit offsets can be supported even on 32-bit architectures. -If your new :manpage:`xyzzy(2)` system call involves privileged functionality, +If your new xyzzy(2) system call involves privileged functionality, it needs to be governed by the appropriate Linux capability bit (checked with a call to ``capable()``), as described in the :manpage:`capabilities(7)` man page. Choose an existing capability bit that governs related functionality, @@ -160,7 +160,7 @@ under the same bit, as this goes against capabilities' purpose of splitting the power of root. In particular, avoid adding new uses of the already overly-general ``CAP_SYS_ADMIN`` capability. -If your new :manpage:`xyzzy(2)` system call manipulates a process other than +If your new xyzzy(2) system call manipulates a process other than the calling process, it should be restricted (using a call to ``ptrace_may_access()``) so that only a calling process with the same permissions as the target process, or with the necessary capabilities, can @@ -196,7 +196,7 @@ be cc'ed to linux-api@vger.kernel.org. Generic System Call Implementation ---------------------------------- -The main entry point for your new :manpage:`xyzzy(2)` system call will be called +The main entry point for your new xyzzy(2) system call will be called ``sys_xyzzy()``, but you add this entry point with the appropriate ``SYSCALL_DEFINEn()`` macro rather than explicitly. The 'n' indicates the number of arguments to the system call, and the macro takes the system call name @@ -459,7 +459,7 @@ the compatibility wrapper:: ... 555 x32 xyzzy __x32_compat_sys_xyzzy -If no pointers are involved, then it is preferable to re-use the 64-bit system +If no pointers are involved, then it is preferable to reuse the 64-bit system call for the x32 ABI (and consequently the entry in arch/x86/entry/syscalls/syscall_64.tbl is unchanged). diff --git a/Documentation/process/changes.rst b/Documentation/process/changes.rst index 62951cdb13ad..0cf97dbab29d 100644 --- a/Documentation/process/changes.rst +++ b/Documentation/process/changes.rst @@ -218,7 +218,7 @@ DevFS has been obsoleted in favour of udev Linux documentation for functions is transitioning to inline documentation via specially-formatted comments near their definitions in the source. These comments can be combined with ReST -files the Documentation/ directory to make enriched documentation, which can +files in the Documentation/ directory to make enriched documentation, which can then be converted to PostScript, HTML, LaTex, ePUB and PDF files. In order to convert from ReST format to a format of your choice, you'll need Sphinx. diff --git a/Documentation/process/coding-assistants.rst b/Documentation/process/coding-assistants.rst new file mode 100644 index 000000000000..899f4459c52d --- /dev/null +++ b/Documentation/process/coding-assistants.rst @@ -0,0 +1,59 @@ +.. SPDX-License-Identifier: GPL-2.0 + +.. _coding_assistants: + +AI Coding Assistants +++++++++++++++++++++ + +This document provides guidance for AI tools and developers using AI +assistance when contributing to the Linux kernel. + +AI tools helping with Linux kernel development should follow the standard +kernel development process: + +* Documentation/process/development-process.rst +* Documentation/process/coding-style.rst +* Documentation/process/submitting-patches.rst + +Licensing and Legal Requirements +================================ + +All contributions must comply with the kernel's licensing requirements: + +* All code must be compatible with GPL-2.0-only +* Use appropriate SPDX license identifiers +* See Documentation/process/license-rules.rst for details + +Signed-off-by and Developer Certificate of Origin +================================================= + +AI agents MUST NOT add Signed-off-by tags. Only humans can legally +certify the Developer Certificate of Origin (DCO). The human submitter +is responsible for: + +* Reviewing all AI-generated code +* Ensuring compliance with licensing requirements +* Adding their own Signed-off-by tag to certify the DCO +* Taking full responsibility for the contribution + +Attribution +=========== + +When AI tools contribute to kernel development, proper attribution +helps track the evolving role of AI in the development process. +Contributions should include an Assisted-by tag in the following format:: + + Assisted-by: AGENT_NAME:MODEL_VERSION [TOOL1] [TOOL2] + +Where: + +* ``AGENT_NAME`` is the name of the AI tool or framework +* ``MODEL_VERSION`` is the specific model version used +* ``[TOOL1] [TOOL2]`` are optional specialized analysis tools used + (e.g., coccinelle, sparse, smatch, clang-tidy) + +Basic development tools (git, gcc, make, editors) should not be listed. + +Example:: + + Assisted-by: Claude:claude-3-opus coccinelle sparse diff --git a/Documentation/process/coding-style.rst b/Documentation/process/coding-style.rst index 2969ca378dbb..35b381230f6e 100644 --- a/Documentation/process/coding-style.rst +++ b/Documentation/process/coding-style.rst @@ -614,7 +614,7 @@ it. When commenting the kernel API functions, please use the kernel-doc format. See the files at :ref:`Documentation/doc-guide/ <doc_guide>` and -``scripts/kernel-doc`` for details. Note that the danger of over-commenting +``tools/docs/kernel-doc`` for details. Note that the danger of over-commenting applies to kernel-doc comments all the same. Do not add boilerplate kernel-doc which simply reiterates what's obvious from the signature of the function. @@ -1070,7 +1070,7 @@ readability. 18) Don't re-invent the kernel macros ------------------------------------- -The header file include/linux/kernel.h contains a number of macros that +There are many header files in include/linux/ that contain a number of macros that you should use, rather than explicitly coding some variant of them yourself. For example, if you need to calculate the length of an array, take advantage of the macro @@ -1079,14 +1079,18 @@ of the macro #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) +which is defined in array_size.h. + Similarly, if you need to calculate the size of some structure member, use .. code-block:: c #define sizeof_field(t, f) (sizeof(((t*)0)->f)) -There are also min() and max() macros that do strict type checking if you -need them. Feel free to peruse that header file to see what else is already +which is defined in stddef.h. + +There are also min() and max() macros defined in minmax.h that do strict type checking +if you need them. Feel free to peruse the header files to see what else is already defined that you shouldn't reproduce in your code. diff --git a/Documentation/process/debugging/index.rst b/Documentation/process/debugging/index.rst index 387d33d16f5e..357243e184e1 100644 --- a/Documentation/process/debugging/index.rst +++ b/Documentation/process/debugging/index.rst @@ -15,8 +15,6 @@ general guides kgdb userspace_debugging_guide -.. only:: subproject and html - subsystem specific guides ------------------------- @@ -25,13 +23,6 @@ subsystem specific guides media_specific_debugging_guide -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` - General debugging advice ======================== diff --git a/Documentation/process/debugging/kgdb.rst b/Documentation/process/debugging/kgdb.rst index b29b0aac2717..f2c57de7992f 100644 --- a/Documentation/process/debugging/kgdb.rst +++ b/Documentation/process/debugging/kgdb.rst @@ -380,6 +380,13 @@ virtual address where the kernel image is mapped and confuses gdb which resolves addresses of kernel symbols from the symbol table of vmlinux. +Kernel parameter: ``rodata`` +---------------------------- + +``CONFIG_STRICT_KERNEL_RWX`` is turned on by default and is not +visible to menuconfig on some architectures (arm64 for example), +you can pass ``rodata=off`` to the kernel in this case. + Using kdb ========= diff --git a/Documentation/process/email-clients.rst b/Documentation/process/email-clients.rst index 84a2450bb6ec..b5377630a648 100644 --- a/Documentation/process/email-clients.rst +++ b/Documentation/process/email-clients.rst @@ -324,7 +324,14 @@ To beat some sense out of the internal editor, do this: - Set ``mailnews.send_plaintext_flowed`` to ``false`` - - Set ``mailnews.wraplength`` from ``72`` to ``0`` + - Set ``mailnews.wraplength`` from ``72`` to ``0`` **or** install the + "Toggle Line Wrap" extension + + https://github.com/jan-kiszka/togglelinewrap + + https://addons.thunderbird.net/thunderbird/addon/toggle-line-wrap + + to control this registry on the fly. - Don't write HTML messages! Go to the main window :menuselection:`Main Menu-->Account Settings-->youracc@server.something-->Composition & Addressing`! diff --git a/Documentation/process/generated-content.rst b/Documentation/process/generated-content.rst new file mode 100644 index 000000000000..08621e50a462 --- /dev/null +++ b/Documentation/process/generated-content.rst @@ -0,0 +1,109 @@ +============================================ +Kernel Guidelines for Tool-Generated Content +============================================ + +Purpose +======= + +Kernel contributors have been using tooling to generate contributions +for a long time. These tools can increase the volume of contributions. +At the same time, reviewer and maintainer bandwidth is a scarce +resource. Understanding which portions of a contribution come from +humans versus tools is helpful to maintain those resources and keep +kernel development healthy. + +The goal here is to clarify community expectations around tools. This +lets everyone become more productive while also maintaining high +degrees of trust between submitters and reviewers. + +Out of Scope +============ + +These guidelines do not apply to tools that make trivial tweaks to +preexisting content. Nor do they pertain to tooling that helps with +menial tasks. Some examples: + + - Spelling and grammar fix ups, like rephrasing to imperative voice + - Typing aids like identifier completion, common boilerplate or + trivial pattern completion + - Purely mechanical transformations like variable renaming + - Reformatting, like running Lindent, ``clang-format`` or + ``rust-fmt`` + +Even whenever your tool use is out of scope, you should still always +consider if it would help reviewing your contribution if the reviewer +knows about the tool that you used. + +In Scope +======== + +These guidelines apply when a meaningful amount of content in a kernel +contribution was not written by a person in the Signed-off-by chain, +but was instead created by a tool. + +Detection of a problem and testing the fix for it is also part of the +development process; if a tool was used to find a problem addressed by +a change, that should be noted in the changelog. This not only gives +credit where it is due, it also helps fellow developers find out about +these tools. + +Some examples: + - Any tool-suggested fix such as ``checkpatch.pl --fix`` + - Coccinelle scripts + - A chatbot generated a new function in your patch to sort list entries. + - A .c file in the patch was originally generated by a coding + assistant but cleaned up by hand. + - The changelog was generated by handing the patch to a generative AI + tool and asking it to write the changelog. + - The changelog was translated from another language. + +If in doubt, choose transparency and assume these guidelines apply to +your contribution. + +Guidelines +========== + +First, read the Developer's Certificate of Origin: +Documentation/process/submitting-patches.rst. Its rules are simple +and have been in place for a long time. They have covered many +tool-generated contributions. Ensure that you understand your entire +submission and are prepared to respond to review comments. + +Second, when making a contribution, be transparent about the origin of +content in cover letters and changelogs. You can be more transparent +by adding information like this: + + - What tools were used? + - The input to the tools you used, like the Coccinelle source script. + - If code was largely generated from a single or short set of + prompts, include those prompts. For longer sessions, include a + summary of the prompts and the nature of resulting assistance. + - Which portions of the content were affected by that tool? + - How is the submission tested and what tools were used to test the + fix? + +As with all contributions, individual maintainers have discretion to +choose how they handle the contribution. For example, they might: + + - Treat it just like any other contribution. + - Reject it outright. + - Treat the contribution specially, for example, asking for extra + testing, reviewing with extra scrutiny, or reviewing at a lower + priority than human-generated content. + - Ask for some other special steps, like asking the contributor to + elaborate on how the tool or model was trained. + - Ask the submitter to explain in more detail about the contribution + so that the maintainer can be assured that the submitter fully + understands how the code works. + - Suggest a better prompt instead of suggesting specific code changes. + +If tools permit you to generate a contribution automatically, expect +additional scrutiny in proportion to how much of it was generated. + +As with the output of any tooling, the result may be incorrect or +inappropriate. You are expected to understand and to be able to defend +everything you submit. If you are unable to do so, then do not submit +the resulting changes. + +If you do so anyway, maintainers are entitled to reject your series +without detailed review. diff --git a/Documentation/process/index.rst b/Documentation/process/index.rst index 492b808a6977..dbd6ea16aca7 100644 --- a/Documentation/process/index.rst +++ b/Documentation/process/index.rst @@ -68,6 +68,8 @@ beyond). stable-kernel-rules management-style researcher-guidelines + generated-content + coding-assistants conclave Dealing with bugs @@ -109,10 +111,3 @@ developers: kernel-docs deprecated - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/process/maintainer-pgp-guide.rst b/Documentation/process/maintainer-pgp-guide.rst index b6919bf606c3..2e4da3de25d4 100644 --- a/Documentation/process/maintainer-pgp-guide.rst +++ b/Documentation/process/maintainer-pgp-guide.rst @@ -405,8 +405,8 @@ geographical region, and open/proprietary hardware considerations. .. note:: - If you are listed in MAINTAINERS or have an account at kernel.org, - you `qualify for a free Nitrokey Start`_ courtesy of The Linux + If you are listed in an `M:` entry in MAINTAINERS or have an account at + kernel.org, you `qualify for a free Nitrokey Start`_ courtesy of The Linux Foundation. .. _`Nitrokey Start`: https://www.nitrokey.com/products/nitrokeys diff --git a/Documentation/process/security-bugs.rst b/Documentation/process/security-bugs.rst index 84657e7d2e5b..c0cf93e11565 100644 --- a/Documentation/process/security-bugs.rst +++ b/Documentation/process/security-bugs.rst @@ -33,12 +33,16 @@ that can speed up the process considerably. It is possible that the security team will bring in extra help from area maintainers to understand and fix the security vulnerability. -Please send plain text emails without attachments where possible. +Please send **plain text** emails without attachments where possible. It is much harder to have a context-quoted discussion about a complex issue if all the details are hidden away in attachments. Think of it like a :doc:`regular patch submission <../process/submitting-patches>` (even if you don't have a patch yet): describe the problem and impact, list reproduction steps, and follow it with a proposed fix, all in plain text. +Markdown, HTML and RST formatted reports are particularly frowned upon since +they're quite hard to read for humans and encourage to use dedicated viewers, +sometimes online, which by definition is not acceptable for a confidential +security report. Disclosure and embargoed information ------------------------------------ diff --git a/Documentation/process/submitting-patches.rst b/Documentation/process/submitting-patches.rst index 9a509f1a6873..e69d19ad658f 100644 --- a/Documentation/process/submitting-patches.rst +++ b/Documentation/process/submitting-patches.rst @@ -805,7 +805,8 @@ not part of the changelog which gets committed to the git tree. It is additional information for the reviewers. If it's placed above the commit tags, it needs manual interaction to remove it. If it is below the separator line, it gets automatically stripped off when applying the -patch:: +patch. If available, adding links to previous versions of the patch (e.g., +lore.kernel.org archive link) is recommended to help reviewers:: <commit message> ... @@ -814,6 +815,9 @@ patch:: V2 -> V3: Removed redundant helper function V1 -> V2: Cleaned up coding style and addressed review comments + v2: https://lore.kernel.org/bar + v1: https://lore.kernel.org/foo + path/to/file | 5+++-- ... diff --git a/Documentation/rust/index.rst b/Documentation/rust/index.rst index ec62001c7d8c..7a31843cd4a3 100644 --- a/Documentation/rust/index.rst +++ b/Documentation/rust/index.rst @@ -58,10 +58,3 @@ more details. You can also find learning materials for Rust in its section in :doc:`../process/kernel-docs`. - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/scheduler/index.rst b/Documentation/scheduler/index.rst index 5dd53e47bc0c..17ce8d76befc 100644 --- a/Documentation/scheduler/index.rst +++ b/Documentation/scheduler/index.rst @@ -25,10 +25,3 @@ Scheduler sched-debug text_files - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/scsi/ChangeLog.sym53c8xx b/Documentation/scsi/ChangeLog.sym53c8xx index 3435227a2bed..07bf2433d64f 100644 --- a/Documentation/scsi/ChangeLog.sym53c8xx +++ b/Documentation/scsi/ChangeLog.sym53c8xx @@ -2,9 +2,9 @@ Sat May 12 12:00 2001 Gerard Roudier (groudier@club-internet.fr) * version sym53c8xx-1.7.3c - Ensure LEDC bit in GPCNTL is cleared when reading the NVRAM. Fix sent by Stig Telfer <stig@api-networks.com>. - - Backport from SYM-2 the work-around that allows to support - hardwares that fail PCI parity checking. - - Check that we received at least 8 bytes of INQUIRY response + - Backport from SYM-2 the work-around that allows to support + hardware that fails PCI parity checking. + - Check that we received at least 8 bytes of INQUIRY response for byte 7, that contains device capabilities, to be valid. - Define scsi_set_pci_device() as nil for kernel < 2.4.4. - + A couple of minor changes. diff --git a/Documentation/scsi/link_power_management_policy.rst b/Documentation/scsi/link_power_management_policy.rst index 64288dcf10f6..e350892cc2f3 100644 --- a/Documentation/scsi/link_power_management_policy.rst +++ b/Documentation/scsi/link_power_management_policy.rst @@ -5,13 +5,13 @@ Link Power Managent Policy ========================== This parameter allows the user to set the link (interface) power management. -There are 3 possible options: +There are 6 possible options: -===================== ===================================================== +====================== ===================================================== Value Effect -===================== ===================================================== -min_power Tell the controller to try to make the link use the - least possible power when possible. This may +====================== ===================================================== +min_power Enable slumber mode(no partial mode) for the link to + use the least possible power when possible. This may sacrifice some performance due to increased latency when coming out of lower power states. @@ -22,4 +22,15 @@ max_performance Generally, this means no power management. Tell medium_power Tell the controller to enter a lower power state when possible, but do not enter the lowest power state, thus improving latency over min_power setting. -===================== ===================================================== + +keep_firmware_settings Do not change the current firmware settings for + Power management. This is the default setting. + +med_power_with_dipm Same as medium_power, but additionally with + Device-initiated power management(DIPM) enabled, + as Intel Rapid Storage Technology(IRST) does. + +min_power_with_partial Same as min_power, but additionally with partial + power state enabled, which may improve performance + over min_power setting. +====================== ===================================================== diff --git a/Documentation/sound/hd-audio/notes.rst b/Documentation/sound/hd-audio/notes.rst index f81e94d8f145..6993bfa159b4 100644 --- a/Documentation/sound/hd-audio/notes.rst +++ b/Documentation/sound/hd-audio/notes.rst @@ -191,7 +191,7 @@ model is found in the white-list, the driver assumes the static configuration of that preset with the correct pin setup, etc. Thus, if you have a newer machine with a slightly different PCI SSID (or codec SSID) from the existing one, you may have a good chance to -re-use the same model. You can pass the ``model`` option to specify the +reuse the same model. You can pass the ``model`` option to specify the preset model instead of PCI (and codec-) SSID look-up. What ``model`` option values are available depends on the codec chip. diff --git a/Documentation/sound/index.rst b/Documentation/sound/index.rst index 51cd736f65b5..c075ca6e11eb 100644 --- a/Documentation/sound/index.rst +++ b/Documentation/sound/index.rst @@ -15,10 +15,3 @@ Sound Subsystem Documentation cards/index codecs/index utimers - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/sphinx-includes/subproject-index.rst b/Documentation/sphinx-includes/subproject-index.rst new file mode 100644 index 000000000000..efffdb5fb017 --- /dev/null +++ b/Documentation/sphinx-includes/subproject-index.rst @@ -0,0 +1,7 @@ +.. SPDX-License-Identifier: GPL-2.0 +.. This file is included in subproject root documents in conf.py + +Indices +======= + +* :ref:`genindex` diff --git a/Documentation/sphinx-static/custom.css b/Documentation/sphinx-static/custom.css index 06cedbae095c..db24f4344e6c 100644 --- a/Documentation/sphinx-static/custom.css +++ b/Documentation/sphinx-static/custom.css @@ -20,7 +20,7 @@ div.sphinxsidebar { font-size: inherit; overflow-y: auto; } /* Tweak document margins and don't force width */ div.document { - margin: 20px 10px 0 10px; + margin: 20px 10px 0 10px; width: auto; } @@ -30,6 +30,9 @@ img.logo { margin-bottom: 20px; } +/* The default is to use -1em, wich makes it override text */ +li { text-indent: 0em; } + /* * Parameters for the display of function prototypes and such included * from C source files. @@ -41,6 +44,15 @@ dt.sig-object { font-size: larger; } div.kernelindent { margin-left: 2em; margin-right: 4em; } /* + * Parameters for the display of function prototypes and such included + * from Python source files. + */ +dl.py { margin-top: 2em; background-color: #ecf0f3; } +dl.py.class { margin-left: 2em; text-indent: -2em; padding-left: 2em; } +dl.py.method, dl.py.attribute { margin-left: 2em; text-indent: -2em; } +dl.py li, pre { text-indent: 0em; padding-left: 0 !important; } + +/* * Tweaks for our local TOC */ div.kerneltoc li.toctree-l1 { font-size: smaller; @@ -151,3 +163,9 @@ div.sphinxsidebar a:hover { text-decoration: underline; text-underline-offset: 0.3em; } + +a.manpage { + font-style: normal; + font-weight: bold; + font-family: "Courier New", Courier, monospace; +} diff --git a/Documentation/sphinx/automarkup.py b/Documentation/sphinx/automarkup.py index 1d9dada40a74..c2227ab0a891 100644 --- a/Documentation/sphinx/automarkup.py +++ b/Documentation/sphinx/automarkup.py @@ -46,6 +46,12 @@ RE_namespace = re.compile(r'^\s*..\s*c:namespace::\s*(\S+)\s*$') # Skipnames = [ 'for', 'if', 'register', 'sizeof', 'struct', 'unsigned' ] +# +# Common English words that should not be recognized as C identifiers +# when following struct/union/enum/typedef keywords. +# Example: "a simple struct that" in workqueue.rst should not be marked as code. +# +Skipidentifiers = [ 'that', 'which', 'where', 'whose' ] # # Many places in the docs refer to common system calls. It is @@ -163,6 +169,10 @@ def markup_c_ref(docname, app, match): if c_namespace: possible_targets.insert(0, c_namespace + "." + base_target) + # Skip common English words that match identifier pattern but are not C code. + if base_target in Skipidentifiers: + return target_text + if base_target not in Skipnames: for target in possible_targets: if not (match.re == RE_function and target in Skipfuncs): diff --git a/Documentation/sphinx/kerneldoc.py b/Documentation/sphinx/kerneldoc.py index d8cdf068ef35..c1cadb4eb099 100644 --- a/Documentation/sphinx/kerneldoc.py +++ b/Documentation/sphinx/kerneldoc.py @@ -47,6 +47,10 @@ sys.path.insert(0, os.path.join(srctree, "tools/lib/python")) from kdoc.kdoc_files import KernelFiles from kdoc.kdoc_output import RestFormat +# Used when verbose is active to show how to reproduce kernel-doc +# issues via command line +kerneldoc_bin = "tools/docs/kernel-doc" + __version__ = '1.0' kfiles = None logger = logging.getLogger(__name__) @@ -95,7 +99,7 @@ class KernelDocDirective(Directive): def handle_args(self): env = self.state.document.settings.env - cmd = [env.config.kerneldoc_bin, '-rst', '-enable-lineno'] + cmd = [kerneldoc_bin, '-rst', '-enable-lineno'] filename = env.config.kerneldoc_srctree + '/' + self.arguments[0] @@ -190,35 +194,7 @@ class KernelDocDirective(Directive): return cmd - def run_cmd(self, cmd): - """ - Execute an external kernel-doc command. - """ - - env = self.state.document.settings.env - node = nodes.section() - - p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - out, err = p.communicate() - - out, err = codecs.decode(out, 'utf-8'), codecs.decode(err, 'utf-8') - - if p.returncode != 0: - sys.stderr.write(err) - - logger.warning("kernel-doc '%s' failed with return code %d" - % (" ".join(cmd), p.returncode)) - return [nodes.error(None, nodes.paragraph(text = "kernel-doc missing"))] - elif env.config.kerneldoc_verbosity > 0: - sys.stderr.write(err) - - filenames = self.parse_args["file_list"] - for filename in filenames: - self.parse_msg(filename, node, out, cmd) - - return node.children - - def parse_msg(self, filename, node, out, cmd): + def parse_msg(self, filename, node, out): """ Handles a kernel-doc output for a given file """ @@ -244,7 +220,7 @@ class KernelDocDirective(Directive): self.do_parse(result, node) - def run_kdoc(self, cmd, kfiles): + def run_kdoc(self, kfiles): """ Execute kernel-doc classes directly instead of running as a separate command. @@ -258,23 +234,17 @@ class KernelDocDirective(Directive): filenames = self.parse_args["file_list"] for filename, out in kfiles.msg(**self.msg_args, filenames=filenames): - self.parse_msg(filename, node, out, cmd) + self.parse_msg(filename, node, out) return node.children def run(self): - global kfiles - cmd = self.handle_args() if self.verbose >= 1: logger.info(cmd_str(cmd)) try: - if kfiles: - return self.run_kdoc(cmd, kfiles) - else: - return self.run_cmd(cmd) - + return self.run_kdoc(kfiles) except Exception as e: # pylint: disable=W0703 logger.warning("kernel-doc '%s' processing failed with: %s" % (cmd_str(cmd), pformat(e))) @@ -286,19 +256,11 @@ class KernelDocDirective(Directive): def setup_kfiles(app): global kfiles - - kerneldoc_bin = app.env.config.kerneldoc_bin - - if kerneldoc_bin and kerneldoc_bin.endswith("kernel-doc.py"): - print("Using Python kernel-doc") - out_style = RestFormat() - kfiles = KernelFiles(out_style=out_style, logger=logger) - else: - print(f"Using {kerneldoc_bin}") + out_style = RestFormat() + kfiles = KernelFiles(out_style=out_style, logger=logger) def setup(app): - app.add_config_value('kerneldoc_bin', None, 'env') app.add_config_value('kerneldoc_srctree', None, 'env') app.add_config_value('kerneldoc_verbosity', 1, 'env') diff --git a/Documentation/spi/index.rst b/Documentation/spi/index.rst index 824ce42ed4f0..20d4a4185ab9 100644 --- a/Documentation/spi/index.rst +++ b/Documentation/spi/index.rst @@ -12,10 +12,3 @@ Serial Peripheral Interface (SPI) butterfly spi-lm70llp spi-sc18is602 - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/staging/rpmsg.rst b/Documentation/staging/rpmsg.rst index 40282cca86ca..42bac1149d9d 100644 --- a/Documentation/staging/rpmsg.rst +++ b/Documentation/staging/rpmsg.rst @@ -224,9 +224,12 @@ content to the console. :: - #include <linux/kernel.h> + #include <linux/dev_printk.h> + #include <linux/mod_devicetable.h> #include <linux/module.h> + #include <linux/printk.h> #include <linux/rpmsg.h> + #include <linux/types.h> static void rpmsg_sample_cb(struct rpmsg_channel *rpdev, void *data, int len, void *priv, u32 src) @@ -244,7 +247,7 @@ content to the console. /* send a message on our channel */ err = rpmsg_send(rpdev->ept, "hello!", 6); if (err) { - pr_err("rpmsg_send failed: %d\n", err); + dev_err(&rpdev->dev, "rpmsg_send failed: %d\n", err); return err; } diff --git a/Documentation/target/index.rst b/Documentation/target/index.rst index 4b24f81f747e..51fa8ebc652e 100644 --- a/Documentation/target/index.rst +++ b/Documentation/target/index.rst @@ -10,10 +10,3 @@ TCM Virtual Device tcmu-design tcm_mod_builder scripts - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/tee/index.rst b/Documentation/tee/index.rst index 62afb7ee9b52..10c3cecde85d 100644 --- a/Documentation/tee/index.rst +++ b/Documentation/tee/index.rst @@ -12,10 +12,3 @@ TEE Subsystem amd-tee ts-tee qtee - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/timers/index.rst b/Documentation/timers/index.rst index 4e88116e4dcf..c8352756b480 100644 --- a/Documentation/timers/index.rst +++ b/Documentation/timers/index.rst @@ -13,10 +13,3 @@ Timers no_hz timekeeping delay_sleep_functions - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/tools/feat.rst b/Documentation/tools/feat.rst new file mode 100644 index 000000000000..021560eb6e6a --- /dev/null +++ b/Documentation/tools/feat.rst @@ -0,0 +1,10 @@ +.. SPDX-License-Identifier: GPL-2.0 + +==================================== +Documentation features parser module +==================================== + +.. automodule:: lib.python.feat.parse_features + :members: + :show-inheritance: + :undoc-members: diff --git a/Documentation/tools/index.rst b/Documentation/tools/index.rst index 80488e290e10..5f2f63bcb284 100644 --- a/Documentation/tools/index.rst +++ b/Documentation/tools/index.rst @@ -12,10 +12,4 @@ more additions are needed here: rtla/index rv/index - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` + python diff --git a/Documentation/tools/jobserver.rst b/Documentation/tools/jobserver.rst new file mode 100644 index 000000000000..31eaf25a8481 --- /dev/null +++ b/Documentation/tools/jobserver.rst @@ -0,0 +1,10 @@ +.. SPDX-License-Identifier: GPL-2.0 + +================= +Job server module +================= + +.. automodule:: lib.python.jobserver + :members: + :show-inheritance: + :undoc-members: diff --git a/Documentation/tools/kabi.rst b/Documentation/tools/kabi.rst new file mode 100644 index 000000000000..92812a20fcf7 --- /dev/null +++ b/Documentation/tools/kabi.rst @@ -0,0 +1,13 @@ +.. SPDX-License-Identifier: GPL-2.0 + +===================================== +Kernel ABI documentation tool modules +===================================== + +.. toctree:: + :maxdepth: 2 + + kabi_parser + kabi_regex + kabi_symbols + kabi_helpers diff --git a/Documentation/tools/kabi_helpers.rst b/Documentation/tools/kabi_helpers.rst new file mode 100644 index 000000000000..5c6ec6081500 --- /dev/null +++ b/Documentation/tools/kabi_helpers.rst @@ -0,0 +1,11 @@ +.. SPDX-License-Identifier: GPL-2.0 + +================= +Ancillary classes +================= + +.. automodule:: lib.python.abi.helpers + :members: + :member-order: bysource + :show-inheritance: + :undoc-members: diff --git a/Documentation/tools/kabi_parser.rst b/Documentation/tools/kabi_parser.rst new file mode 100644 index 000000000000..95826da21b3d --- /dev/null +++ b/Documentation/tools/kabi_parser.rst @@ -0,0 +1,10 @@ +.. SPDX-License-Identifier: GPL-2.0 + +===================================== +Kernel ABI documentation parser class +===================================== + +.. automodule:: lib.python.abi.abi_parser + :members: + :show-inheritance: + :undoc-members: diff --git a/Documentation/tools/kabi_regex.rst b/Documentation/tools/kabi_regex.rst new file mode 100644 index 000000000000..bfc3a0d91c47 --- /dev/null +++ b/Documentation/tools/kabi_regex.rst @@ -0,0 +1,10 @@ +.. SPDX-License-Identifier: GPL-2.0 + +============================= +ABI regex search symbol class +============================= + +.. automodule:: lib.python.abi.abi_regex + :members: + :show-inheritance: + :undoc-members: diff --git a/Documentation/tools/kabi_symbols.rst b/Documentation/tools/kabi_symbols.rst new file mode 100644 index 000000000000..c75a9380f89f --- /dev/null +++ b/Documentation/tools/kabi_symbols.rst @@ -0,0 +1,10 @@ +.. SPDX-License-Identifier: GPL-2.0 + +========================================= +System ABI documentation validation class +========================================= + +.. automodule:: lib.python.abi.system_symbols + :members: + :show-inheritance: + :undoc-members: diff --git a/Documentation/tools/kdoc.rst b/Documentation/tools/kdoc.rst new file mode 100644 index 000000000000..e51ba159d8c4 --- /dev/null +++ b/Documentation/tools/kdoc.rst @@ -0,0 +1,12 @@ +.. SPDX-License-Identifier: GPL-2.0 + +================== +Kernel-doc modules +================== + +.. toctree:: + :maxdepth: 2 + + kdoc_parser + kdoc_output + kdoc_ancillary diff --git a/Documentation/tools/kdoc_ancillary.rst b/Documentation/tools/kdoc_ancillary.rst new file mode 100644 index 000000000000..3950d0a3f104 --- /dev/null +++ b/Documentation/tools/kdoc_ancillary.rst @@ -0,0 +1,46 @@ +.. SPDX-License-Identifier: GPL-2.0 + +================= +Ancillary classes +================= + +Argparse formatter class +======================== + +.. automodule:: lib.python.kdoc.enrich_formatter + :members: + :show-inheritance: + :undoc-members: + +Regular expression class handler +================================ + +.. automodule:: lib.python.kdoc.kdoc_re + :members: + :show-inheritance: + :undoc-members: + + +Chinese, Japanese and Korean variable fonts handler +=================================================== + +.. automodule:: lib.python.kdoc.latex_fonts + :members: + :show-inheritance: + :undoc-members: + +Kernel C file include logic +=========================== + +.. automodule:: lib.python.kdoc.parse_data_structs + :members: + :show-inheritance: + :undoc-members: + +Python version ancillary methods +================================ + +.. automodule:: lib.python.kdoc.python_version + :members: + :show-inheritance: + :undoc-members: diff --git a/Documentation/tools/kdoc_output.rst b/Documentation/tools/kdoc_output.rst new file mode 100644 index 000000000000..08fd271ec556 --- /dev/null +++ b/Documentation/tools/kdoc_output.rst @@ -0,0 +1,14 @@ +.. SPDX-License-Identifier: GPL-2.0 + +======================= +Kernel-doc output stage +======================= + +Output handler for man pages and ReST +===================================== + +.. automodule:: lib.python.kdoc.kdoc_output + :members: + :show-inheritance: + :undoc-members: + diff --git a/Documentation/tools/kdoc_parser.rst b/Documentation/tools/kdoc_parser.rst new file mode 100644 index 000000000000..03ee54a1b1cc --- /dev/null +++ b/Documentation/tools/kdoc_parser.rst @@ -0,0 +1,29 @@ +.. SPDX-License-Identifier: GPL-2.0 + +======================= +Kernel-doc parser stage +======================= + +File handler classes +==================== + +.. automodule:: lib.python.kdoc.kdoc_files + :members: + :show-inheritance: + :undoc-members: + +Parsed item data class +====================== + +.. automodule:: lib.python.kdoc.kdoc_item + :members: + :show-inheritance: + :undoc-members: + +Parser classes and methods +========================== + +.. automodule:: lib.python.kdoc.kdoc_parser + :members: + :show-inheritance: + :undoc-members: diff --git a/Documentation/tools/python.rst b/Documentation/tools/python.rst new file mode 100644 index 000000000000..1444c1816735 --- /dev/null +++ b/Documentation/tools/python.rst @@ -0,0 +1,13 @@ +.. SPDX-License-Identifier: GPL-2.0 + +================ +Python libraries +================ + +.. toctree:: + :maxdepth: 4 + + jobserver + feat + kdoc + kabi diff --git a/Documentation/tools/rtla/index.rst b/Documentation/tools/rtla/index.rst index 05d2652e4072..7664d6d0cb27 100644 --- a/Documentation/tools/rtla/index.rst +++ b/Documentation/tools/rtla/index.rst @@ -18,10 +18,3 @@ behavior on specific hardware. rtla-timerlat-hist rtla-timerlat-top rtla-hwnoise - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/tools/rv/index.rst b/Documentation/tools/rv/index.rst index 64ba2efe2e85..fd42b0017d07 100644 --- a/Documentation/tools/rv/index.rst +++ b/Documentation/tools/rv/index.rst @@ -16,10 +16,3 @@ Runtime verification (rv) tool rv-mon-wip rv-mon-wwnr rv-mon-sched - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/trace/fprobe.rst b/Documentation/trace/fprobe.rst index 06b0edad0179..95998b189ae3 100644 --- a/Documentation/trace/fprobe.rst +++ b/Documentation/trace/fprobe.rst @@ -79,7 +79,7 @@ The above is defined by including the header:: Same as ftrace, the registered callbacks will start being called some time after the register_fprobe() is called and before it returns. See -:file:`Documentation/trace/ftrace.rst`. +Documentation/trace/ftrace.rst. Also, the unregister_fprobe() will guarantee that both enter and exit handlers are no longer being called by functions after unregister_fprobe() diff --git a/Documentation/trace/ftrace-uses.rst b/Documentation/trace/ftrace-uses.rst index e225cc46b71e..a9701add27c5 100644 --- a/Documentation/trace/ftrace-uses.rst +++ b/Documentation/trace/ftrace-uses.rst @@ -253,7 +253,7 @@ If @buf is NULL and reset is set, all functions will be enabled for tracing. The @buf can also be a glob expression to enable all functions that match a specific pattern. -See Filter Commands in :file:`Documentation/trace/ftrace.rst`. +See Filter Commands in Documentation/trace/ftrace.rst. To just trace the schedule function: diff --git a/Documentation/trace/index.rst b/Documentation/trace/index.rst index b4a429dc4f7a..cfd8128ac56d 100644 --- a/Documentation/trace/index.rst +++ b/Documentation/trace/index.rst @@ -95,10 +95,3 @@ Additional Resources For more details, refer to the respective documentation of each tracing tool and framework. - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/trace/rv/da_monitor_instrumentation.rst b/Documentation/trace/rv/da_monitor_instrumentation.rst index 6c67c7b57811..9eff38a4ad1f 100644 --- a/Documentation/trace/rv/da_monitor_instrumentation.rst +++ b/Documentation/trace/rv/da_monitor_instrumentation.rst @@ -162,10 +162,10 @@ For example, from the wip sample model:: The probes then need to be detached at the disable phase. -[1] The wip model is presented in:: +[1] The wip model is presented in: Documentation/trace/rv/deterministic_automata.rst -The wip monitor is presented in:: +The wip monitor is presented in: - Documentation/trace/rv/da_monitor_synthesis.rst + Documentation/trace/rv/monitor_synthesis.rst diff --git a/Documentation/translations/it_IT/doc-guide/kernel-doc.rst b/Documentation/translations/it_IT/doc-guide/kernel-doc.rst index aa0e31d353d6..bac959b8b7b9 100644 --- a/Documentation/translations/it_IT/doc-guide/kernel-doc.rst +++ b/Documentation/translations/it_IT/doc-guide/kernel-doc.rst @@ -80,7 +80,7 @@ Al fine di verificare che i commenti siano formattati correttamente, potete eseguire il programma ``kernel-doc`` con un livello di verbosità alto e senza che questo produca alcuna documentazione. Per esempio:: - scripts/kernel-doc -v -none drivers/foo/bar.c + tools/docs/kernel-doc -v -none drivers/foo/bar.c Il formato della documentazione è verificato della procedura di generazione del kernel quando viene richiesto di effettuare dei controlli extra con GCC:: @@ -378,7 +378,7 @@ distinguono in base al fatto che il nome della macro simile a funzione sia immediatamente seguito da una parentesi sinistra ('(') mentre in quelle simili a oggetti no. -Le macro simili a funzioni sono gestite come funzioni da ``scripts/kernel-doc``. +Le macro simili a funzioni sono gestite come funzioni da ``tools/docs/kernel-doc``. Possono avere un elenco di parametri. Le macro simili a oggetti non hanno un elenco di parametri. @@ -595,7 +595,7 @@ documentazione presenti nel file sorgente (*source*). L'estensione kernel-doc fa parte dei sorgenti del kernel, la si può trovare in ``Documentation/sphinx/kerneldoc.py``. Internamente, viene utilizzato -lo script ``scripts/kernel-doc`` per estrarre i commenti di documentazione +lo script ``tools/docs/kernel-doc`` per estrarre i commenti di documentazione dai file sorgenti. Come utilizzare kernel-doc per generare pagine man @@ -604,4 +604,4 @@ Come utilizzare kernel-doc per generare pagine man Se volete utilizzare kernel-doc solo per generare delle pagine man, potete farlo direttamente dai sorgenti del kernel:: - $ scripts/kernel-doc -man $(git grep -l '/\*\*' -- :^Documentation :^tools) | scripts/split-man.pl /tmp/man + $ tools/docs/kernel-doc -man $(git grep -l '/\*\*' -- :^Documentation :^tools) | scripts/split-man.pl /tmp/man diff --git a/Documentation/translations/it_IT/process/adding-syscalls.rst b/Documentation/translations/it_IT/process/adding-syscalls.rst index df8c652d004b..c4ed6dbf5f05 100644 --- a/Documentation/translations/it_IT/process/adding-syscalls.rst +++ b/Documentation/translations/it_IT/process/adding-syscalls.rst @@ -124,7 +124,7 @@ descrittore di file per accesso all'oggetto - non inventatevi nuovi tipi di accesso da spazio utente quando il kernel ha già dei meccanismi e una semantica ben definita per utilizzare i descrittori di file. -Se la vostra nuova chiamata di sistema :manpage:`xyzzy(2)` ritorna un nuovo +Se la vostra nuova chiamata di sistema xyzzy(2) ritorna un nuovo descrittore di file, allora l'argomento *flags* dovrebbe includere un valore equivalente a ``O_CLOEXEC`` per i nuovi descrittori. Questo rende possibile, nello spazio utente, la chiusura della finestra temporale fra le chiamate a @@ -140,13 +140,13 @@ della famiglia di :manpage:`poll(2)`. Rendere un descrittore di file pronto per la lettura o la scrittura è il tipico modo del kernel per notificare lo spazio utente circa un evento associato all'oggetto del kernel. -Se la vostra nuova chiamata di sistema :manpage:`xyzzy(2)` ha un argomento +Se la vostra nuova chiamata di sistema xyzzy(2) ha un argomento che è il percorso ad un file:: int sys_xyzzy(const char __user *path, ..., unsigned int flags); dovreste anche considerare se non sia più appropriata una versione -:manpage:`xyzzyat(2)`:: +`xyzzyat(2)`:: int sys_xyzzyat(int dfd, const char __user *path, ..., unsigned int flags); @@ -154,7 +154,7 @@ Questo permette più flessibilità su come lo spazio utente specificherà il fil in questione; in particolare, permette allo spazio utente di richiedere la funzionalità su un descrittore di file già aperto utilizzando il *flag* ``AT_EMPTY_PATH``, in pratica otterremmo gratuitamente l'operazione -:manpage:`fxyzzy(3)`:: +fxyzzy(3):: - xyzzyat(AT_FDCWD, path, ..., 0) is equivalent to xyzzy(path,...) - xyzzyat(fd, "", ..., AT_EMPTY_PATH) is equivalent to fxyzzy(fd, ...) @@ -163,12 +163,12 @@ funzionalità su un descrittore di file già aperto utilizzando il *flag* man :manpage:`openat(2)`; per un esempio di AT_EMPTY_PATH, leggere la pagina man :manpage:`fstatat(2)`). -Se la vostra nuova chiamata di sistema :manpage:`xyzzy(2)` prevede un parametro +Se la vostra nuova chiamata di sistema xyzzy(2) prevede un parametro per descrivere uno scostamento all'interno di un file, usate ``loff_t`` come tipo cosicché scostamenti a 64-bit potranno essere supportati anche su architetture a 32-bit. -Se la vostra nuova chiamata di sistema :manpage:`xyzzy(2)` prevede l'uso di +Se la vostra nuova chiamata di sistema xyzzy(2) prevede l'uso di funzioni riservate, allora dev'essere gestita da un opportuno bit di privilegio (verificato con una chiamata a ``capable()``), come descritto nella pagina man :manpage:`capabilities(7)`. Scegliete un bit di privilegio già esistente per @@ -178,7 +178,7 @@ principio di *capabilities* di separare i poteri di root. In particolare, evitate di aggiungere nuovi usi al fin-troppo-generico privilegio ``CAP_SYS_ADMIN``. -Se la vostra nuova chiamata di sistema :manpage:`xyzzy(2)` manipola altri +Se la vostra nuova chiamata di sistema xyzzy(2) manipola altri processi oltre a quello chiamato, allora dovrebbe essere limitata (usando la chiamata ``ptrace_may_access()``) di modo che solo un processo chiamante con gli stessi permessi del processo in oggetto, o con i necessari privilegi, @@ -219,7 +219,7 @@ Implementazione di chiamate di sistema generiche ------------------------------------------------ Il principale punto d'accesso alla vostra nuova chiamata di sistema -:manpage:`xyzzy(2)` verrà chiamato ``sys_xyzzy()``; ma, piuttosto che in modo +`xyzzy(2)` verrà chiamato ``sys_xyzzy()``; ma, piuttosto che in modo esplicito, lo aggiungerete tramite la macro ``SYSCALL_DEFINEn``. La 'n' indica il numero di argomenti della chiamata di sistema; la macro ha come argomento il nome della chiamata di sistema, seguito dalle coppie (tipo, nome) diff --git a/Documentation/translations/ja_JP/index.rst b/Documentation/translations/ja_JP/index.rst index 4159b417bfdd..5d47d588e368 100644 --- a/Documentation/translations/ja_JP/index.rst +++ b/Documentation/translations/ja_JP/index.rst @@ -13,6 +13,7 @@ disclaimer-ja_JP process/howto + process/submitting-patches process/submit-checklist .. raw:: latex diff --git a/Documentation/translations/ja_JP/process/howto.rst b/Documentation/translations/ja_JP/process/howto.rst index 5e307f90982c..8ab47fc710fc 100644 --- a/Documentation/translations/ja_JP/process/howto.rst +++ b/Documentation/translations/ja_JP/process/howto.rst @@ -49,7 +49,7 @@ Linux カーネル開発のやり方 カーネルは GNU C と GNU ツールチェインを使って書かれています。カーネル は ISO C11 仕様に準拠して書く一方で、標準には無い言語拡張を多く使って -います。カーネルは標準 C ライブラリに依存しない、C 言語非依存環境です。 +います。カーネルは標準 C ライブラリに依存しない、自立した C 環境です。 そのため、C の標準の中で使えないものもあります。特に任意の long long の除算や浮動小数点は使えません。カーネルがツールチェインや C 言語拡張 に置いている前提がどうなっているのかわかりにくいことが時々あり、また、 @@ -61,7 +61,7 @@ info ページ( info gcc )を見てください。 発手順について高度な標準を持つ、多様な人の集まりです。地理的に分散した 大規模なチームに対してもっともうまくいくとわかったことをベースにしなが ら、これらの標準は長い時間をかけて築かれてきました。これらはきちんと文 -書化されていますから、事前にこれらの標準について事前にできるだけたくさ +書化されていますから、これらの標準について事前にできるだけたくさ ん学んでください。また皆があなたやあなたの会社のやり方に合わせてくれる と思わないでください。 @@ -363,7 +363,7 @@ linux-next の実行テストを行う冒険好きなテスターは大いに歓 あなたのハッキングのスキルを訓練する最高の方法のひとつに、他人がレポー トしたバグを修正することがあります。あなたがカーネルをより安定化させる -こに寄与するということだけでなく、あなたは 現実の問題を修正することを +ことに寄与するということだけでなく、あなたは 現実の問題を修正することを 学び、自分のスキルも強化でき、また他の開発者があなたの存在に気がつきま す。バグを修正することは、多くの開発者の中から自分が功績をあげる最善の 道です、なぜなら多くの人は他人のバグの修正に時間を浪費することを好まな diff --git a/Documentation/translations/ja_JP/process/submit-checklist.rst b/Documentation/translations/ja_JP/process/submit-checklist.rst index fb3b9e3bd8ee..c118b853c44a 100644 --- a/Documentation/translations/ja_JP/process/submit-checklist.rst +++ b/Documentation/translations/ja_JP/process/submit-checklist.rst @@ -52,7 +52,7 @@ Kconfig 変更のレビュー 1) 新規の、もしくは変更された ``CONFIG`` オプションについて、それが関係する コンフィグメニューへの悪影響がない。また、 Documentation/kbuild/kconfig-language.rst の - "Menu attibutes: default value" に記載の例外条件を満たす場合を除き、 + "Menu attributes: default value" に記載の例外条件を満たす場合を除き、 そのデフォルトが無効になっている。 2) 新規の ``Kconfig`` オプションにヘルプテキストがある。 @@ -75,7 +75,7 @@ Kconfig 変更のレビュー 4) 新規モジュール・パラメータが、すべて ``MODULE_PARM_DESC()`` によって記述 されている。 -5) 新規ユーザースペース・インターフェースが、すべて ``Documentaion/ABI/`` +5) 新規ユーザースペース・インターフェースが、すべて ``Documentation/ABI/`` 以下に記載されている。詳しくは、 Documentation/admin-guide/abi.rst (もしくは ``Documentation/ABI/README``) を参照。 ユーザースペース・インターフェースを変更するパッチは、 diff --git a/Documentation/translations/ja_JP/process/submitting-patches.rst b/Documentation/translations/ja_JP/process/submitting-patches.rst new file mode 100644 index 000000000000..d61583399ef4 --- /dev/null +++ b/Documentation/translations/ja_JP/process/submitting-patches.rst @@ -0,0 +1,56 @@ +.. _jp_process_submitting_patches: + +パッチの投稿: カーネルにコードを入れるための必須ガイド +====================================================== + +.. note:: + + このドキュメントは :ref:`Documentation/process/submitting-patches.rst <submittingpatches>` の日本語訳です。 + + 免責事項: :ref:`translations_ja_JP_disclaimer` + +.. warning:: + + **UNDER CONSTRUCTION!!** + + この文書は翻訳更新の作業中です。最新の内容は原文を参照してください。 + +Linux カーネルへ変更を投稿したい個人や企業にとって、もし「仕組み」に +慣れていなければ、そのプロセスは時に気後れするものでしょう。 +このテキストは、あなたの変更が受け入れられる可能性を大きく高めるための +提案を集めたものです。 + +この文書には、比較的簡潔な形式で多数の提案が含まれています。 +カーネル開発プロセスの仕組みに関する詳細は +Documentation/process/development-process.rst を参照してください。 +また、コードを投稿する前に確認すべき項目の一覧として +Documentation/process/submit-checklist.rst を読んでください。 +デバイスツリーバインディングのパッチについては、 +Documentation/devicetree/bindings/submitting-patches.rst を読んでください。 + +この文書は、パッチ作成に ``git`` を使う前提で書かれています。 +もし ``git`` に不慣れであれば、使い方を学ぶことを強く勧めます。 +それにより、カーネル開発者として、また一般的にも、あなたの作業は +ずっと楽になるでしょう。 + +いくつかのサブシステムやメンテナツリーには、各々のワークフローや +期待事項に関する追加情報があります。次を参照してください: +:ref:`Documentation/process/maintainer-handbooks.rst <maintainer_handbooks_main>`. + +現在のソースツリーを入手する +---------------------------- + +もし手元に最新のカーネルソースのリポジトリがなければ、``git`` を使って取得して +ください。まずは mainline のリポジトリから始めるのがよいでしょう。これは +次のようにして取得できます:: + + git clone git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git + +ただし、直接 mainline のツリーを対象に作業すればよいとは限らないことに注意 +してください。多くのサブシステムのメンテナはそれぞれ独自のツリーを運用しており、 +そのツリーに対して作成されたパッチを見たいと考えています。該当サブシステムの +ツリーは MAINTAINERS ファイル内の **T:** エントリを参照して見つけてください。 +そこに掲載されていない場合は、メンテナに問い合わせてください。 + +変更内容を説明する +------------------ diff --git a/Documentation/translations/ko_KR/core-api/wrappers/memory-barriers.rst b/Documentation/translations/ko_KR/core-api/wrappers/memory-barriers.rst deleted file mode 100644 index 526ae534dd86..000000000000 --- a/Documentation/translations/ko_KR/core-api/wrappers/memory-barriers.rst +++ /dev/null @@ -1,18 +0,0 @@ -.. SPDX-License-Identifier: GPL-2.0 - This is a simple wrapper to bring memory-barriers.txt into the RST world - until such a time as that file can be converted directly. - -========================= -리눅스 커널 메모리 배리어 -========================= - -.. raw:: latex - - \footnotesize - -.. include:: ../../memory-barriers.txt - :literal: - -.. raw:: latex - - \normalsize diff --git a/Documentation/translations/ko_KR/index.rst b/Documentation/translations/ko_KR/index.rst index a20772f9d61c..b788462d08e4 100644 --- a/Documentation/translations/ko_KR/index.rst +++ b/Documentation/translations/ko_KR/index.rst @@ -12,7 +12,6 @@ :maxdepth: 1 process/howto - core-api/wrappers/memory-barriers.rst .. raw:: latex diff --git a/Documentation/translations/ko_KR/memory-barriers.txt b/Documentation/translations/ko_KR/memory-barriers.txt deleted file mode 100644 index 7165927a708e..000000000000 --- a/Documentation/translations/ko_KR/memory-barriers.txt +++ /dev/null @@ -1,2952 +0,0 @@ -NOTE: -This is a version of Documentation/memory-barriers.txt translated into Korean. -This document is maintained by SeongJae Park <sj@kernel.org>. -If you find any difference between this document and the original file or -a problem with the translation, please contact the maintainer of this file. - -Please also note that the purpose of this file is to be easier to -read for non English (read: Korean) speakers and is not intended as -a fork. So if you have any comments or updates for this file please -update the original English file first. The English version is -definitive, and readers should look there if they have any doubt. - -================================= -이 문서는 -Documentation/memory-barriers.txt -의 한글 번역입니다. - -역자: 박성재 <sj@kernel.org> -================================= - - - ========================= - 리눅스 커널 메모리 배리어 - ========================= - -저자: David Howells <dhowells@redhat.com> - Paul E. McKenney <paulmck@linux.ibm.com> - Will Deacon <will.deacon@arm.com> - Peter Zijlstra <peterz@infradead.org> - -======== -면책조항 -======== - -이 문서는 명세서가 아닙니다; 이 문서는 완벽하지 않은데, 간결성을 위해 의도된 -부분도 있고, 의도하진 않았지만 사람에 의해 쓰였다보니 불완전한 부분도 있습니다. -이 문서는 리눅스에서 제공하는 다양한 메모리 배리어들을 사용하기 위한 -안내서입니다만, 뭔가 이상하다 싶으면 (그런게 많을 겁니다) 질문을 부탁드립니다. -일부 이상한 점들은 공식적인 메모리 일관성 모델과 tools/memory-model/ 에 있는 -관련 문서를 참고해서 해결될 수 있을 겁니다. 그러나, 이 메모리 모델조차도 그 -관리자들의 의견의 집합으로 봐야지, 절대 옳은 예언자로 신봉해선 안될 겁니다. - -다시 말하지만, 이 문서는 리눅스가 하드웨어에 기대하는 사항에 대한 명세서가 -아닙니다. - -이 문서의 목적은 두가지입니다: - - (1) 어떤 특정 배리어에 대해 기대할 수 있는 최소한의 기능을 명세하기 위해서, - 그리고 - - (2) 사용 가능한 배리어들에 대해 어떻게 사용해야 하는지에 대한 안내를 제공하기 - 위해서. - -어떤 아키텍쳐는 특정한 배리어들에 대해서는 여기서 이야기하는 최소한의 -요구사항들보다 많은 기능을 제공할 수도 있습니다만, 여기서 이야기하는 -요구사항들을 충족하지 않는 아키텍쳐가 있다면 그 아키텍쳐가 잘못된 것이란 점을 -알아두시기 바랍니다. - -또한, 특정 아키텍쳐에서 일부 배리어는 해당 아키텍쳐의 특수한 동작 방식으로 인해 -해당 배리어의 명시적 사용이 불필요해서 no-op 이 될수도 있음을 알아두시기 -바랍니다. - -역자: 본 번역 역시 완벽하지 않은데, 이 역시 부분적으로는 의도된 것이기도 -합니다. 여타 기술 문서들이 그렇듯 완벽한 이해를 위해서는 번역문과 원문을 함께 -읽으시되 번역문을 하나의 가이드로 활용하시길 추천드리며, 발견되는 오역 등에 -대해서는 언제든 의견을 부탁드립니다. 과한 번역으로 인한 오해를 최소화하기 위해 -애매한 부분이 있을 경우에는 어색함이 있더라도 원래의 용어를 차용합니다. - - -===== -목차: -===== - - (*) 추상 메모리 액세스 모델. - - - 디바이스 오퍼레이션. - - 보장사항. - - (*) 메모리 배리어란 무엇인가? - - - 메모리 배리어의 종류. - - 메모리 배리어에 대해 가정해선 안될 것. - - 주소 데이터 의존성 배리어 (역사적). - - 컨트롤 의존성. - - SMP 배리어 짝맞추기. - - 메모리 배리어 시퀀스의 예. - - 읽기 메모리 배리어 vs 로드 예측. - - Multicopy 원자성. - - (*) 명시적 커널 배리어. - - - 컴파일러 배리어. - - CPU 메모리 배리어. - - (*) 암묵적 커널 메모리 배리어. - - - 락 Acquisition 함수. - - 인터럽트 비활성화 함수. - - 슬립과 웨이크업 함수. - - 그외의 함수들. - - (*) CPU 간 ACQUIRING 배리어의 효과. - - - Acquire vs 메모리 액세스. - - (*) 메모리 배리어가 필요한 곳 - - - 프로세서간 상호 작용. - - 어토믹 오퍼레이션. - - 디바이스 액세스. - - 인터럽트. - - (*) 커널 I/O 배리어의 효과. - - (*) 가정되는 가장 완화된 실행 순서 모델. - - (*) CPU 캐시의 영향. - - - 캐시 일관성. - - 캐시 일관성 vs DMA. - - 캐시 일관성 vs MMIO. - - (*) CPU 들이 저지르는 일들. - - - 그리고, Alpha 가 있다. - - 가상 머신 게스트. - - (*) 사용 예. - - - 순환식 버퍼. - - (*) 참고 문헌. - - -======================= -추상 메모리 액세스 모델 -======================= - -다음과 같이 추상화된 시스템 모델을 생각해 봅시다: - - : : - : : - : : - +-------+ : +--------+ : +-------+ - | | : | | : | | - | | : | | : | | - | CPU 1 |<----->| Memory |<----->| CPU 2 | - | | : | | : | | - | | : | | : | | - +-------+ : +--------+ : +-------+ - ^ : ^ : ^ - | : | : | - | : | : | - | : v : | - | : +--------+ : | - | : | | : | - | : | | : | - +---------->| Device |<----------+ - : | | : - : | | : - : +--------+ : - : : - -프로그램은 여러 메모리 액세스 오퍼레이션을 발생시키고, 각각의 CPU 는 그런 -프로그램들을 실행합니다. 추상화된 CPU 모델에서 메모리 오퍼레이션들의 순서는 -매우 완화되어 있고, CPU 는 프로그램이 인과관계를 어기지 않는 상태로 관리된다고 -보일 수만 있다면 메모리 오퍼레이션을 자신이 원하는 어떤 순서대로든 재배치해 -동작시킬 수 있습니다. 비슷하게, 컴파일러 또한 프로그램의 정상적 동작을 해치지 -않는 한도 내에서는 어떤 순서로든 자신이 원하는 대로 인스트럭션을 재배치 할 수 -있습니다. - -따라서 위의 다이어그램에서 한 CPU가 동작시키는 메모리 오퍼레이션이 만들어내는 -변화는 해당 오퍼레이션이 CPU 와 시스템의 다른 부분들 사이의 인터페이스(점선)를 -지나가면서 시스템의 나머지 부분들에 인지됩니다. - - -예를 들어, 다음의 일련의 이벤트들을 생각해 봅시다: - - CPU 1 CPU 2 - =============== =============== - { A == 1; B == 2 } - A = 3; x = B; - B = 4; y = A; - -다이어그램의 가운데에 위치한 메모리 시스템에 보여지게 되는 액세스들은 다음의 총 -24개의 조합으로 재구성될 수 있습니다: - - STORE A=3, STORE B=4, y=LOAD A->3, x=LOAD B->4 - STORE A=3, STORE B=4, x=LOAD B->4, y=LOAD A->3 - STORE A=3, y=LOAD A->3, STORE B=4, x=LOAD B->4 - STORE A=3, y=LOAD A->3, x=LOAD B->2, STORE B=4 - STORE A=3, x=LOAD B->2, STORE B=4, y=LOAD A->3 - STORE A=3, x=LOAD B->2, y=LOAD A->3, STORE B=4 - STORE B=4, STORE A=3, y=LOAD A->3, x=LOAD B->4 - STORE B=4, ... - ... - -따라서 다음의 네가지 조합의 값들이 나올 수 있습니다: - - x == 2, y == 1 - x == 2, y == 3 - x == 4, y == 1 - x == 4, y == 3 - - -한발 더 나아가서, 한 CPU 가 메모리 시스템에 반영한 스토어 오퍼레이션들의 결과는 -다른 CPU 에서의 로드 오퍼레이션을 통해 인지되는데, 이 때 스토어가 반영된 순서와 -다른 순서로 인지될 수도 있습니다. - - -예로, 아래의 일련의 이벤트들을 생각해 봅시다: - - CPU 1 CPU 2 - =============== =============== - { A == 1, B == 2, C == 3, P == &A, Q == &C } - B = 4; Q = P; - P = &B D = *Q; - -D 로 읽혀지는 값은 CPU 2 에서 P 로부터 읽혀진 주소값에 의존적이기 때문에 여기엔 -분명한 주소 의존성이 있습니다. 하지만 이 이벤트들의 실행 결과로는 아래의 -결과들이 모두 나타날 수 있습니다: - - (Q == &A) and (D == 1) - (Q == &B) and (D == 2) - (Q == &B) and (D == 4) - -CPU 2 는 *Q 의 로드를 요청하기 전에 P 를 Q 에 넣기 때문에 D 에 C 를 집어넣는 -일은 없음을 알아두세요. - - -디바이스 오퍼레이션 -------------------- - -일부 디바이스는 자신의 컨트롤 인터페이스를 메모리의 특정 영역으로 매핑해서 -제공하는데(Memory mapped I/O), 해당 컨트롤 레지스터에 접근하는 순서는 매우 -중요합니다. 예를 들어, 어드레스 포트 레지스터 (A) 와 데이터 포트 레지스터 (D) -를 통해 접근되는 내부 레지스터 집합을 갖는 이더넷 카드를 생각해 봅시다. 내부의 -5번 레지스터를 읽기 위해 다음의 코드가 사용될 수 있습니다: - - *A = 5; - x = *D; - -하지만, 이건 다음의 두 조합 중 하나로 만들어질 수 있습니다: - - STORE *A = 5, x = LOAD *D - x = LOAD *D, STORE *A = 5 - -두번째 조합은 데이터를 읽어온 _후에_ 주소를 설정하므로, 오동작을 일으킬 겁니다. - - -보장사항 --------- - -CPU 에게 기대할 수 있는 최소한의 보장사항 몇가지가 있습니다: - - (*) 어떤 CPU 든, 의존성이 존재하는 메모리 액세스들은 해당 CPU 자신에게 - 있어서는 순서대로 메모리 시스템에 수행 요청됩니다. 즉, 다음에 대해서: - - Q = READ_ONCE(P); D = READ_ONCE(*Q); - - CPU 는 다음과 같은 메모리 오퍼레이션 시퀀스를 수행 요청합니다: - - Q = LOAD P, D = LOAD *Q - - 그리고 그 시퀀스 내에서의 순서는 항상 지켜집니다. 하지만, DEC Alpha 에서 - READ_ONCE() 는 메모리 배리어 명령도 내게 되어 있어서, DEC Alpha CPU 는 - 다음과 같은 메모리 오퍼레이션들을 내놓게 됩니다: - - Q = LOAD P, MEMORY_BARRIER, D = LOAD *Q, MEMORY_BARRIER - - DEC Alpha 에서 수행되든 아니든, READ_ONCE() 는 컴파일러로부터의 악영향 - 또한 제거합니다. - - (*) 특정 CPU 내에서 겹치는 영역의 메모리에 행해지는 로드와 스토어 들은 해당 - CPU 안에서는 순서가 바뀌지 않은 것으로 보여집니다. 즉, 다음에 대해서: - - a = READ_ONCE(*X); WRITE_ONCE(*X, b); - - CPU 는 다음의 메모리 오퍼레이션 시퀀스만을 메모리에 요청할 겁니다: - - a = LOAD *X, STORE *X = b - - 그리고 다음에 대해서는: - - WRITE_ONCE(*X, c); d = READ_ONCE(*X); - - CPU 는 다음의 수행 요청만을 만들어 냅니다: - - STORE *X = c, d = LOAD *X - - (로드 오퍼레이션과 스토어 오퍼레이션이 겹치는 메모리 영역에 대해 - 수행된다면 해당 오퍼레이션들은 겹친다고 표현됩니다). - -그리고 _반드시_ 또는 _절대로_ 가정하거나 가정하지 말아야 하는 것들이 있습니다: - - (*) 컴파일러가 READ_ONCE() 나 WRITE_ONCE() 로 보호되지 않은 메모리 액세스를 - 당신이 원하는 대로 할 것이라는 가정은 _절대로_ 해선 안됩니다. 그것들이 - 없다면, 컴파일러는 컴파일러 배리어 섹션에서 다루게 될, 모든 "창의적인" - 변경들을 만들어낼 권한을 갖게 됩니다. - - (*) 개별적인 로드와 스토어들이 주어진 순서대로 요청될 것이라는 가정은 _절대로_ - 하지 말아야 합니다. 이 말은 곧: - - X = *A; Y = *B; *D = Z; - - 는 다음의 것들 중 어느 것으로든 만들어질 수 있다는 의미입니다: - - X = LOAD *A, Y = LOAD *B, STORE *D = Z - X = LOAD *A, STORE *D = Z, Y = LOAD *B - Y = LOAD *B, X = LOAD *A, STORE *D = Z - Y = LOAD *B, STORE *D = Z, X = LOAD *A - STORE *D = Z, X = LOAD *A, Y = LOAD *B - STORE *D = Z, Y = LOAD *B, X = LOAD *A - - (*) 겹치는 메모리 액세스들은 합쳐지거나 버려질 수 있음을 _반드시_ 가정해야 - 합니다. 다음의 코드는: - - X = *A; Y = *(A + 4); - - 다음의 것들 중 뭐든 될 수 있습니다: - - X = LOAD *A; Y = LOAD *(A + 4); - Y = LOAD *(A + 4); X = LOAD *A; - {X, Y} = LOAD {*A, *(A + 4) }; - - 그리고: - - *A = X; *(A + 4) = Y; - - 는 다음 중 뭐든 될 수 있습니다: - - STORE *A = X; STORE *(A + 4) = Y; - STORE *(A + 4) = Y; STORE *A = X; - STORE {*A, *(A + 4) } = {X, Y}; - -그리고 보장사항에 반대되는 것들(anti-guarantees)이 있습니다: - - (*) 이 보장사항들은 bitfield 에는 적용되지 않는데, 컴파일러들은 bitfield 를 - 수정하는 코드를 생성할 때 원자성 없는(non-atomic) 읽고-수정하고-쓰는 - 인스트럭션들의 조합을 만드는 경우가 많기 때문입니다. 병렬 알고리즘의 - 동기화에 bitfield 를 사용하려 하지 마십시오. - - (*) bitfield 들이 여러 락으로 보호되는 경우라 하더라도, 하나의 bitfield 의 - 모든 필드들은 하나의 락으로 보호되어야 합니다. 만약 한 bitfield 의 두 - 필드가 서로 다른 락으로 보호된다면, 컴파일러의 원자성 없는 - 읽고-수정하고-쓰는 인스트럭션 조합은 한 필드에의 업데이트가 근처의 - 필드에도 영향을 끼치게 할 수 있습니다. - - (*) 이 보장사항들은 적절하게 정렬되고 크기가 잡힌 스칼라 변수들에 대해서만 - 적용됩니다. "적절하게 크기가 잡힌" 이라함은 현재로써는 "char", "short", - "int" 그리고 "long" 과 같은 크기의 변수들을 의미합니다. "적절하게 정렬된" - 은 자연스런 정렬을 의미하는데, 따라서 "char" 에 대해서는 아무 제약이 없고, - "short" 에 대해서는 2바이트 정렬을, "int" 에는 4바이트 정렬을, 그리고 - "long" 에 대해서는 32-bit 시스템인지 64-bit 시스템인지에 따라 4바이트 또는 - 8바이트 정렬을 의미합니다. 이 보장사항들은 C11 표준에서 소개되었으므로, - C11 전의 오래된 컴파일러(예를 들어, gcc 4.6) 를 사용할 때엔 주의하시기 - 바랍니다. 표준에 이 보장사항들은 "memory location" 을 정의하는 3.14 - 섹션에 다음과 같이 설명되어 있습니다: - (역자: 인용문이므로 번역하지 않습니다) - - memory location - either an object of scalar type, or a maximal sequence - of adjacent bit-fields all having nonzero width - - NOTE 1: Two threads of execution can update and access - separate memory locations without interfering with - each other. - - NOTE 2: A bit-field and an adjacent non-bit-field member - are in separate memory locations. The same applies - to two bit-fields, if one is declared inside a nested - structure declaration and the other is not, or if the two - are separated by a zero-length bit-field declaration, - or if they are separated by a non-bit-field member - declaration. It is not safe to concurrently update two - bit-fields in the same structure if all members declared - between them are also bit-fields, no matter what the - sizes of those intervening bit-fields happen to be. - - -========================= -메모리 배리어란 무엇인가? -========================= - -앞에서 봤듯이, 상호간 의존성이 없는 메모리 오퍼레이션들은 실제로는 무작위적 -순서로 수행될 수 있으며, 이는 CPU 와 CPU 간의 상호작용이나 I/O 에 문제가 될 수 -있습니다. 따라서 컴파일러와 CPU 가 순서를 바꾸는데 제약을 걸 수 있도록 개입할 -수 있는 어떤 방법이 필요합니다. - -메모리 배리어는 그런 개입 수단입니다. 메모리 배리어는 배리어를 사이에 둔 앞과 -뒤 양측의 메모리 오퍼레이션들 간에 부분적 순서가 존재하도록 하는 효과를 줍니다. - -시스템의 CPU 들과 여러 디바이스들은 성능을 올리기 위해 명령어 재배치, 실행 -유예, 메모리 오퍼레이션들의 조합, 예측적 로드(speculative load), 브랜치 -예측(speculative branch prediction), 다양한 종류의 캐싱(caching) 등의 다양한 -트릭을 사용할 수 있기 때문에 이런 강제력은 중요합니다. 메모리 배리어들은 이런 -트릭들을 무효로 하거나 억제하는 목적으로 사용되어져서 코드가 여러 CPU 와 -디바이스들 간의 상호작용을 정상적으로 제어할 수 있게 해줍니다. - - -메모리 배리어의 종류 --------------------- - -메모리 배리어는 네개의 기본 타입으로 분류됩니다: - - (1) 쓰기 (또는 스토어) 메모리 배리어. - - 쓰기 메모리 배리어는 시스템의 다른 컴포넌트들에 해당 배리어보다 앞서 - 명시된 모든 STORE 오퍼레이션들이 해당 배리어 뒤에 명시된 모든 STORE - 오퍼레이션들보다 먼저 수행된 것으로 보일 것을 보장합니다. - - 쓰기 배리어는 스토어 오퍼레이션들에 대한 부분적 순서 세우기입니다; 로드 - 오퍼레이션들에 대해서는 어떤 영향도 끼치지 않습니다. - - CPU 는 시간의 흐름에 따라 메모리 시스템에 일련의 스토어 오퍼레이션들을 - 하나씩 요청해 집어넣습니다. 쓰기 배리어 앞의 모든 스토어 오퍼레이션들은 - 쓰기 배리어 뒤의 모든 스토어 오퍼레이션들보다 _앞서_ 수행될 겁니다. - - [!] 쓰기 배리어들은 읽기 또는 주소 의존성 배리어와 함께 짝을 맞춰 - 사용되어야만 함을 알아두세요; "SMP 배리어 짝맞추기" 서브섹션을 참고하세요. - - - (2) 주소 의존성 배리어 (역사적). - - 주소 의존성 배리어는 읽기 배리어의 보다 완화된 형태입니다. 두개의 로드 - 오퍼레이션이 있고 두번째 것이 첫번째 것의 결과에 의존하고 있을 때(예: - 두번째 로드가 참조할 주소를 첫번째 로드가 읽는 경우), 두번째 로드가 읽어올 - 데이터는 첫번째 로드에 의해 그 주소가 얻어진 뒤에 업데이트 됨을 보장하기 - 위해서 주소 의존성 배리어가 필요할 수 있습니다. - - 주소 의존성 배리어는 상호 의존적인 로드 오퍼레이션들 사이의 부분적 순서 - 세우기입니다; 스토어 오퍼레이션들이나 독립적인 로드들, 또는 중복되는 - 로드들에 대해서는 어떤 영향도 끼치지 않습니다. - - (1) 에서 언급했듯이, 시스템의 CPU 들은 메모리 시스템에 일련의 스토어 - 오퍼레이션들을 던져 넣고 있으며, 거기에 관심이 있는 다른 CPU 는 그 - 오퍼레이션들을 메모리 시스템이 실행한 결과를 인지할 수 있습니다. 이처럼 - 다른 CPU 의 스토어 오퍼레이션의 결과에 관심을 두고 있는 CPU 가 수행 요청한 - 주소 의존성 배리어는, 배리어 앞의 어떤 로드 오퍼레이션이 다른 CPU 에서 - 던져 넣은 스토어 오퍼레이션과 같은 영역을 향했다면, 그런 스토어 - 오퍼레이션들이 만들어내는 결과가 주소 의존성 배리어 뒤의 로드 - 오퍼레이션들에게는 보일 것을 보장합니다. - - 이 순서 세우기 제약에 대한 그림을 보기 위해선 "메모리 배리어 시퀀스의 예" - 서브섹션을 참고하시기 바랍니다. - - [!] 첫번째 로드는 반드시 _주소_ 의존성을 가져야지 컨트롤 의존성을 가져야 - 하는게 아님을 알아두십시오. 만약 두번째 로드를 위한 주소가 첫번째 로드에 - 의존적이지만 그 의존성은 조건적이지 그 주소 자체를 가져오는게 아니라면, - 그것은 _컨트롤_ 의존성이고, 이 경우에는 읽기 배리어나 그보다 강력한 - 무언가가 필요합니다. 더 자세한 내용을 위해서는 "컨트롤 의존성" 서브섹션을 - 참고하시기 바랍니다. - - [!] 주소 의존성 배리어는 보통 쓰기 배리어들과 함께 짝을 맞춰 사용되어야 - 합니다; "SMP 배리어 짝맞추기" 서브섹션을 참고하세요. - - [!] 커널 v5.9 릴리즈에서 명시적 주소 의존성 배리어를 위한 커널 API 들이 - 삭제되었습니다. 오늘날에는 공유된 변수들의 로드를 표시하는 READ_ONCE() 나 - rcu_dereference() 와 같은 API 들은 묵시적으로 주소 의존성 배리어를 제공합니다. - - - (3) 읽기 (또는 로드) 메모리 배리어. - - 읽기 배리어는 주소 의존성 배리어 기능의 보장사항에 더해서 배리어보다 앞서 - 명시된 모든 LOAD 오퍼레이션들이 배리어 뒤에 명시되는 모든 LOAD - 오퍼레이션들보다 먼저 행해진 것으로 시스템의 다른 컴포넌트들에 보여질 것을 - 보장합니다. - - 읽기 배리어는 로드 오퍼레이션에 행해지는 부분적 순서 세우기입니다; 스토어 - 오퍼레이션에 대해서는 어떤 영향도 끼치지 않습니다. - - 읽기 메모리 배리어는 주소 의존성 배리어를 내장하므로 주소 의존성 배리어를 - 대신할 수 있습니다. - - [!] 읽기 배리어는 일반적으로 쓰기 배리어들과 함께 짝을 맞춰 사용되어야 - 합니다; "SMP 배리어 짝맞추기" 서브섹션을 참고하세요. - - - (4) 범용 메모리 배리어. - - 범용(general) 메모리 배리어는 배리어보다 앞서 명시된 모든 LOAD 와 STORE - 오퍼레이션들이 배리어 뒤에 명시된 모든 LOAD 와 STORE 오퍼레이션들보다 - 먼저 수행된 것으로 시스템의 나머지 컴포넌트들에 보이게 됨을 보장합니다. - - 범용 메모리 배리어는 로드와 스토어 모두에 대한 부분적 순서 세우기입니다. - - 범용 메모리 배리어는 읽기 메모리 배리어, 쓰기 메모리 배리어 모두를 - 내장하므로, 두 배리어를 모두 대신할 수 있습니다. - - -그리고 두개의 명시적이지 않은 타입이 있습니다: - - (5) ACQUIRE 오퍼레이션. - - 이 타입의 오퍼레이션은 단방향의 투과성 배리어처럼 동작합니다. ACQUIRE - 오퍼레이션 뒤의 모든 메모리 오퍼레이션들이 ACQUIRE 오퍼레이션 후에 - 일어난 것으로 시스템의 나머지 컴포넌트들에 보이게 될 것이 보장됩니다. - LOCK 오퍼레이션과 smp_load_acquire(), smp_cond_load_acquire() 오퍼레이션도 - ACQUIRE 오퍼레이션에 포함됩니다. - - ACQUIRE 오퍼레이션 앞의 메모리 오퍼레이션들은 ACQUIRE 오퍼레이션 완료 후에 - 수행된 것처럼 보일 수 있습니다. - - ACQUIRE 오퍼레이션은 거의 항상 RELEASE 오퍼레이션과 짝을 지어 사용되어야 - 합니다. - - - (6) RELEASE 오퍼레이션. - - 이 타입의 오퍼레이션들도 단방향 투과성 배리어처럼 동작합니다. RELEASE - 오퍼레이션 앞의 모든 메모리 오퍼레이션들은 RELEASE 오퍼레이션 전에 완료된 - 것으로 시스템의 다른 컴포넌트들에 보여질 것이 보장됩니다. UNLOCK 류의 - 오퍼레이션들과 smp_store_release() 오퍼레이션도 RELEASE 오퍼레이션의 - 일종입니다. - - RELEASE 오퍼레이션 뒤의 메모리 오퍼레이션들은 RELEASE 오퍼레이션이 - 완료되기 전에 행해진 것처럼 보일 수 있습니다. - - ACQUIRE 와 RELEASE 오퍼레이션의 사용은 일반적으로 다른 메모리 배리어의 - 필요성을 없앱니다. 또한, RELEASE+ACQUIRE 조합은 범용 메모리 배리어처럼 - 동작할 것을 보장하지 -않습니다-. 하지만, 어떤 변수에 대한 RELEASE - 오퍼레이션을 앞서는 메모리 액세스들의 수행 결과는 이 RELEASE 오퍼레이션을 - 뒤이어 같은 변수에 대해 수행된 ACQUIRE 오퍼레이션을 뒤따르는 메모리 - 액세스에는 보여질 것이 보장됩니다. 다르게 말하자면, 주어진 변수의 - 크리티컬 섹션에서는, 해당 변수에 대한 앞의 크리티컬 섹션에서의 모든 - 액세스들이 완료되었을 것을 보장합니다. - - 즉, ACQUIRE 는 최소한의 "취득" 동작처럼, 그리고 RELEASE 는 최소한의 "공개" - 처럼 동작한다는 의미입니다. - -atomic_t.txt 에 설명된 어토믹 오퍼레이션들 중 일부는 완전히 순서잡힌 것들과 -(배리어를 사용하지 않는) 완화된 순서의 것들 외에 ACQUIRE 와 RELEASE 부류의 -것들도 존재합니다. 로드와 스토어를 모두 수행하는 조합된 어토믹 오퍼레이션에서, -ACQUIRE 는 해당 오퍼레이션의 로드 부분에만 적용되고 RELEASE 는 해당 -오퍼레이션의 스토어 부분에만 적용됩니다. - -메모리 배리어들은 두 CPU 간, 또는 CPU 와 디바이스 간에 상호작용의 가능성이 있을 -때에만 필요합니다. 만약 어떤 코드에 그런 상호작용이 없을 것이 보장된다면, 해당 -코드에서는 메모리 배리어를 사용할 필요가 없습니다. - - -이것들은 _최소한의_ 보장사항들임을 알아두세요. 다른 아키텍쳐에서는 더 강력한 -보장사항을 제공할 수도 있습니다만, 그런 보장사항은 아키텍쳐 종속적 코드 이외의 -부분에서는 신뢰되지 _않을_ 겁니다. - - -메모리 배리어에 대해 가정해선 안될 것 -------------------------------------- - -리눅스 커널 메모리 배리어들이 보장하지 않는 것들이 있습니다: - - (*) 메모리 배리어 앞에서 명시된 어떤 메모리 액세스도 메모리 배리어 명령의 수행 - 완료 시점까지 _완료_ 될 것이란 보장은 없습니다; 배리어가 하는 일은 CPU 의 - 액세스 큐에 특정 타입의 액세스들은 넘을 수 없는 선을 긋는 것으로 생각될 수 - 있습니다. - - (*) 한 CPU 에서 메모리 배리어를 수행하는게 시스템의 다른 CPU 나 하드웨어에 - 어떤 직접적인 영향을 끼친다는 보장은 존재하지 않습니다. 배리어 수행이 - 만드는 간접적 영향은 두번째 CPU 가 첫번째 CPU 의 액세스들의 결과를 - 바라보는 순서가 됩니다만, 다음 항목을 보세요: - - (*) 첫번째 CPU 가 두번째 CPU 의 메모리 액세스들의 결과를 바라볼 때, _설령_ - 두번째 CPU 가 메모리 배리어를 사용한다 해도, 첫번째 CPU _또한_ 그에 맞는 - 메모리 배리어를 사용하지 않는다면 ("SMP 배리어 짝맞추기" 서브섹션을 - 참고하세요) 그 결과가 올바른 순서로 보여진다는 보장은 없습니다. - - (*) CPU 바깥의 하드웨어[*] 가 메모리 액세스들의 순서를 바꾸지 않는다는 보장은 - 존재하지 않습니다. CPU 캐시 일관성 메커니즘은 메모리 배리어의 간접적 - 영향을 CPU 사이에 전파하긴 하지만, 순서대로 전파하지는 않을 수 있습니다. - - [*] 버스 마스터링 DMA 와 일관성에 대해서는 다음을 참고하시기 바랍니다: - - Documentation/driver-api/pci/pci.rst - Documentation/core-api/dma-api-howto.rst - Documentation/core-api/dma-api.rst - - -주소 의존성 배리어 (역사적) ---------------------------- - -리눅스 커널 v4.15 기준으로, smp_mb() 가 DEC Alpha 용 READ_ONCE() 코드에 -추가되었는데, 이는 이 섹션에 주의를 기울여야 하는 사람들은 DEC Alpha 아키텍쳐 -전용 코드를 만드는 사람들과 READ_ONCE() 자체를 만드는 사람들 뿐임을 의미합니다. -그런 분들을 위해, 그리고 역사에 관심 있는 분들을 위해, 여기 주소 의존성 -배리어에 대한 이야기를 적습니다. - -[!] 주소 의존성은 로드에서 로드로와 로드에서 스토어로의 관계들 모두에서 -나타나지만, 주소 의존성 배리어는 로드에서 스토어로의 상황에서는 필요하지 -않습니다. - -주소 의존성 배리어의 사용에 있어 지켜야 하는 사항들은 약간 미묘하고, 데이터 -의존성 배리어가 사용되어야 하는 상황도 항상 명백하지는 않습니다. 설명을 위해 -다음의 이벤트 시퀀스를 생각해 봅시다: - - CPU 1 CPU 2 - =============== =============== - { A == 1, B == 2, C == 3, P == &A, Q == &C } - B = 4; - <쓰기 배리어> - WRITE_ONCE(P, &B) - Q = READ_ONCE_OLD(P); - D = *Q; - -[!] READ_ONCE_OLD() 는 4.15 커널 전의 버전에서의, 주소 의존성 배리어를 내포하지 -않는 READ_ONCE() 에 해당합니다. - -여기엔 분명한 주소 의존성이 존재하므로, 이 시퀀스가 끝났을 때 Q 는 &A 또는 &B -일 것이고, 따라서: - - (Q == &A) 는 (D == 1) 를, - (Q == &B) 는 (D == 4) 를 의미합니다. - -하지만! CPU 2 는 B 의 업데이트를 인식하기 전에 P 의 업데이트를 인식할 수 있고, -따라서 다음의 결과가 가능합니다: - - (Q == &B) and (D == 2) ???? - -이런 결과는 일관성이나 인과 관계 유지가 실패한 것처럼 보일 수도 있겠지만, -그렇지 않습니다, 그리고 이 현상은 (DEC Alpha 와 같은) 여러 CPU 에서 실제로 -발견될 수 있습니다. - -이 문제 상황을 제대로 해결하기 위해, READ_ONCE() 는 커널 v4.15 릴리즈 부터 -묵시적 주소 의존성 배리어를 제공합니다: - - CPU 1 CPU 2 - =============== =============== - { A == 1, B == 2, C == 3, P == &A, Q == &C } - B = 4; - <쓰기 배리어> - WRITE_ONCE(P, &B); - Q = READ_ONCE(P); - <묵시적 주소 의존성 배리어> - D = *Q; - -이 변경은 앞의 처음 두가지 결과 중 하나만이 발생할 수 있고, 세번째의 결과는 -발생할 수 없도록 합니다. - - -[!] 이 상당히 반직관적인 상황은 분리된 캐시를 가지는 기계들에서 가장 잘 -발생하는데, 예를 들면 한 캐시 뱅크는 짝수 번호의 캐시 라인들을 처리하고, 다른 -뱅크는 홀수 번호의 캐시 라인들을 처리하는 경우임을 알아두시기 바랍니다. 포인터 -P 는 짝수 번호 캐시 라인에 저장되어 있고, 변수 B 는 홀수 번호 캐시 라인에 -저장되어 있을 수 있습니다. 여기서 값을 읽어오는 CPU 의 캐시의 홀수 번호 처리 -뱅크는 열심히 일감을 처리중인 반면 홀수 번호 처리 뱅크는 할 일 없이 한가한 -중이라면 포인터 P (&B) 의 새로운 값과 변수 B 의 기존 값 (2) 를 볼 수 있습니다. - - -의존적 쓰기들의 순서를 맞추는데에는 주소 의존성 배리어가 필요치 않은데, 이는 -리눅스 커널이 지원하는 CPU 들은 (1) 쓰기가 정말로 일어날지, (2) 쓰기가 어디에 -이루어질지, 그리고 (3) 쓰여질 값을 확실히 알기 전까지는 쓰기를 수행하지 않기 -때문입니다. 하지만 "컨트롤 의존성" 섹션과 -Documentation/RCU/rcu_dereference.rst 파일을 주의 깊게 읽어 주시기 바랍니다: -컴파일러는 매우 창의적인 많은 방법으로 종속성을 깰 수 있습니다. - - CPU 1 CPU 2 - =============== =============== - { A == 1, B == 2, C = 3, P == &A, Q == &C } - B = 4; - <쓰기 배리어> - WRITE_ONCE(P, &B); - Q = READ_ONCE_OLD(P); - WRITE_ONCE(*Q, 5); - -따라서, Q 로의 읽기와 *Q 로의 쓰기 사이에는 주소 의존성 배리어가 필요치 -않습니다. 달리 말하면, 오늘날의 READ_ONCE() 의 묵시적 주소 의존성 배리어가 -없더라도 다음 결과는 생기지 않습니다: - - (Q == &B) && (B == 4) - -이런 패턴은 드물게 사용되어야 함을 알아 두시기 바랍니다. 무엇보다도, 의존성 -순서 규칙의 의도는 쓰기 작업을 -예방- 해서 그로 인해 발생하는 비싼 캐시 미스도 -없애려는 것입니다. 이 패턴은 드물게 발생하는 에러 조건 같은것들을 기록하는데 -사용될 수 있으며, CPU의 자연적인 순서 보장이 그런 기록들을 사라지지 않게 -해줍니다. - - -주소 의존성에 의해 제공되는 이 순서규칙은 이를 포함하고 있는 CPU 에 -지역적임을 알아두시기 바랍니다. 더 많은 정보를 위해선 "Multicopy 원자성" -섹션을 참고하세요. - - -주소 의존성 배리어는 매우 중요한데, 예를 들어 RCU 시스템에서 그렇습니다. -include/linux/rcupdate.h 의 rcu_assign_pointer() 와 rcu_dereference() 를 -참고하세요. 이것들은 RCU 로 관리되는 포인터의 타겟을 현재 타겟에서 수정된 -새로운 타겟으로 바꾸는 작업에서 새로 수정된 타겟이 초기화가 완료되지 않은 채로 -보여지는 일이 일어나지 않게 해줍니다. - -더 많은 예를 위해선 "캐시 일관성" 서브섹션을 참고하세요. - - -컨트롤 의존성 -------------- - -현재의 컴파일러들은 컨트롤 의존성을 이해하고 있지 않기 때문에 컨트롤 의존성은 -약간 다루기 어려울 수 있습니다. 이 섹션의 목적은 여러분이 컴파일러의 무시로 -인해 여러분의 코드가 망가지는 걸 막을 수 있도록 돕는겁니다. - -로드-로드 컨트롤 의존성은 (묵시적인) 주소 의존성 배리어만으로는 정확히 동작할 -수가 없어서 읽기 메모리 배리어를 필요로 합니다. 아래의 코드를 봅시다: - - q = READ_ONCE(a); - <묵시적 주소 의존성 배리어> - if (q) { - /* BUG: No address dependency!!! */ - p = READ_ONCE(b); - } - -이 코드는 원하는 대로의 효과를 내지 못할 수 있는데, 이 코드에는 주소 의존성이 -아니라 컨트롤 의존성이 존재하기 때문으로, 이런 상황에서 CPU 는 실행 속도를 더 -빠르게 하기 위해 분기 조건의 결과를 예측하고 코드를 재배치 할 수 있어서 다른 -CPU 는 b 로부터의 로드 오퍼레이션이 a 로부터의 로드 오퍼레이션보다 먼저 발생한 -걸로 인식할 수 있습니다. 여기에 정말로 필요했던 건 다음과 같습니다: - - q = READ_ONCE(a); - if (q) { - <읽기 배리어> - p = READ_ONCE(b); - } - -하지만, 스토어 오퍼레이션은 예측적으로 수행되지 않습니다. 즉, 다음 예에서와 -같이 로드-스토어 컨트롤 의존성이 존재하는 경우에는 순서가 -지켜진다-는 -의미입니다. - - q = READ_ONCE(a); - if (q) { - WRITE_ONCE(b, 1); - } - -컨트롤 의존성은 보통 다른 타입의 배리어들과 짝을 맞춰 사용됩니다. 그렇다곤 -하나, READ_ONCE() 도 WRITE_ONCE() 도 선택사항이 아니라 필수사항임을 부디 -명심하세요! READ_ONCE() 가 없다면, 컴파일러는 'a' 로부터의 로드를 'a' 로부터의 -또다른 로드와 조합할 수 있습니다. WRITE_ONCE() 가 없다면, 컴파일러는 'b' 로의 -스토어를 'b' 로의 또라느 스토어들과 조합할 수 있습니다. 두 경우 모두 순서에 -있어 상당히 비직관적인 결과를 초래할 수 있습니다. - -이걸로 끝이 아닌게, 컴파일러가 변수 'a' 의 값이 항상 0이 아니라고 증명할 수 -있다면, 앞의 예에서 "if" 문을 없애서 다음과 같이 최적화 할 수도 있습니다: - - q = a; - b = 1; /* BUG: Compiler and CPU can both reorder!!! */ - -그러니 READ_ONCE() 를 반드시 사용하세요. - -다음과 같이 "if" 문의 양갈래 브랜치에 모두 존재하는 동일한 스토어에 대해 순서를 -강제하고 싶은 경우가 있을 수 있습니다: - - q = READ_ONCE(a); - if (q) { - barrier(); - WRITE_ONCE(b, 1); - do_something(); - } else { - barrier(); - WRITE_ONCE(b, 1); - do_something_else(); - } - -안타깝게도, 현재의 컴파일러들은 높은 최적화 레벨에서는 이걸 다음과 같이 -바꿔버립니다: - - q = READ_ONCE(a); - barrier(); - WRITE_ONCE(b, 1); /* BUG: No ordering vs. load from a!!! */ - if (q) { - /* WRITE_ONCE(b, 1); -- moved up, BUG!!! */ - do_something(); - } else { - /* WRITE_ONCE(b, 1); -- moved up, BUG!!! */ - do_something_else(); - } - -이제 'a' 에서의 로드와 'b' 로의 스토어 사이에는 조건적 관계가 없기 때문에 CPU -는 이들의 순서를 바꿀 수 있게 됩니다: 이런 경우에 조건적 관계는 반드시 -필요한데, 모든 컴파일러 최적화가 이루어지고 난 후의 어셈블리 코드에서도 -마찬가지입니다. 따라서, 이 예에서 순서를 지키기 위해서는 smp_store_release() -와 같은 명시적 메모리 배리어가 필요합니다: - - q = READ_ONCE(a); - if (q) { - smp_store_release(&b, 1); - do_something(); - } else { - smp_store_release(&b, 1); - do_something_else(); - } - -반면에 명시적 메모리 배리어가 없다면, 이런 경우의 순서는 스토어 오퍼레이션들이 -서로 다를 때에만 보장되는데, 예를 들면 다음과 같은 경우입니다: - - q = READ_ONCE(a); - if (q) { - WRITE_ONCE(b, 1); - do_something(); - } else { - WRITE_ONCE(b, 2); - do_something_else(); - } - -처음의 READ_ONCE() 는 컴파일러가 'a' 의 값을 증명해내는 것을 막기 위해 여전히 -필요합니다. - -또한, 로컬 변수 'q' 를 가지고 하는 일에 대해 주의해야 하는데, 그러지 않으면 -컴파일러는 그 값을 추측하고 또다시 필요한 조건관계를 없애버릴 수 있습니다. -예를 들면: - - q = READ_ONCE(a); - if (q % MAX) { - WRITE_ONCE(b, 1); - do_something(); - } else { - WRITE_ONCE(b, 2); - do_something_else(); - } - -만약 MAX 가 1 로 정의된 상수라면, 컴파일러는 (q % MAX) 는 0이란 것을 알아채고, -위의 코드를 아래와 같이 바꿔버릴 수 있습니다: - - q = READ_ONCE(a); - WRITE_ONCE(b, 2); - do_something_else(); - -이렇게 되면, CPU 는 변수 'a' 로부터의 로드와 변수 'b' 로의 스토어 사이의 순서를 -지켜줄 필요가 없어집니다. barrier() 를 추가해 해결해 보고 싶겠지만, 그건 -도움이 안됩니다. 조건 관계는 사라졌고, barrier() 는 이를 되돌리지 못합니다. -따라서, 이 순서를 지켜야 한다면, MAX 가 1 보다 크다는 것을, 다음과 같은 방법을 -사용해 분명히 해야 합니다: - - q = READ_ONCE(a); - BUILD_BUG_ON(MAX <= 1); /* Order load from a with store to b. */ - if (q % MAX) { - WRITE_ONCE(b, 1); - do_something(); - } else { - WRITE_ONCE(b, 2); - do_something_else(); - } - -'b' 로의 스토어들은 여전히 서로 다름을 알아두세요. 만약 그것들이 동일하면, -앞에서 이야기했듯, 컴파일러가 그 스토어 오퍼레이션들을 'if' 문 바깥으로 -끄집어낼 수 있습니다. - -또한 이진 조건문 평가에 너무 의존하지 않도록 조심해야 합니다. 다음의 예를 -봅시다: - - q = READ_ONCE(a); - if (q || 1 > 0) - WRITE_ONCE(b, 1); - -첫번째 조건만으로는 브랜치 조건 전체를 거짓으로 만들 수 없고 두번째 조건은 항상 -참이기 때문에, 컴파일러는 이 예를 다음과 같이 바꿔서 컨트롤 의존성을 없애버릴 -수 있습니다: - - q = READ_ONCE(a); - WRITE_ONCE(b, 1); - -이 예는 컴파일러가 코드를 추측으로 수정할 수 없도록 분명히 해야 한다는 점을 -강조합니다. 조금 더 일반적으로 말해서, READ_ONCE() 는 컴파일러에게 주어진 로드 -오퍼레이션을 위한 코드를 정말로 만들도록 하지만, 컴파일러가 그렇게 만들어진 -코드의 수행 결과를 사용하도록 강제하지는 않습니다. - -또한, 컨트롤 의존성은 if 문의 then 절과 else 절에 대해서만 적용됩니다. 상세히 -말해서, 컨트롤 의존성은 if 문을 뒤따르는 코드에는 적용되지 않습니다: - - q = READ_ONCE(a); - if (q) { - WRITE_ONCE(b, 1); - } else { - WRITE_ONCE(b, 2); - } - WRITE_ONCE(c, 1); /* BUG: No ordering against the read from 'a'. */ - -컴파일러는 volatile 타입에 대한 액세스를 재배치 할 수 없고 이 조건 하의 'b' -로의 쓰기를 재배치 할 수 없기 때문에 여기에 순서 규칙이 존재한다고 주장하고 -싶을 겁니다. 불행히도 이 경우에, 컴파일러는 다음의 가상의 pseudo-assembly 언어 -코드처럼 'b' 로의 두개의 쓰기 오퍼레이션을 conditional-move 인스트럭션으로 -번역할 수 있습니다: - - ld r1,a - cmp r1,$0 - cmov,ne r4,$1 - cmov,eq r4,$2 - st r4,b - st $1,c - -완화된 순서 규칙의 CPU 는 'a' 로부터의 로드와 'c' 로의 스토어 사이에 어떤 -종류의 의존성도 갖지 않을 겁니다. 이 컨트롤 의존성은 두개의 cmov 인스트럭션과 -거기에 의존하는 스토어 에게만 적용될 겁니다. 짧게 말하자면, 컨트롤 의존성은 -주어진 if 문의 then 절과 else 절에게만 (그리고 이 두 절 내에서 호출되는 -함수들에게까지) 적용되지, 이 if 문을 뒤따르는 코드에는 적용되지 않습니다. - - -컨트롤 의존성에 의해 제공되는 이 순서규칙은 이를 포함하고 있는 CPU 에 -지역적입니다. 더 많은 정보를 위해선 "Multicopy 원자성" 섹션을 참고하세요. - - -요약하자면: - - (*) 컨트롤 의존성은 앞의 로드들을 뒤의 스토어들에 대해 순서를 맞춰줍니다. - 하지만, 그 외의 어떤 순서도 보장하지 -않습니다-: 앞의 로드와 뒤의 로드들 - 사이에도, 앞의 스토어와 뒤의 스토어들 사이에도요. 이런 다른 형태의 - 순서가 필요하다면 smp_rmb() 나 smp_wmb()를, 또는, 앞의 스토어들과 뒤의 - 로드들 사이의 순서를 위해서는 smp_mb() 를 사용하세요. - - (*) "if" 문의 양갈래 브랜치가 같은 변수에의 동일한 스토어로 시작한다면, 그 - 스토어들은 각 스토어 앞에 smp_mb() 를 넣거나 smp_store_release() 를 - 사용해서 스토어를 하는 식으로 순서를 맞춰줘야 합니다. 이 문제를 해결하기 - 위해 "if" 문의 양갈래 브랜치의 시작 지점에 barrier() 를 넣는 것만으로는 - 충분한 해결이 되지 않는데, 이는 앞의 예에서 본것과 같이, 컴파일러의 - 최적화는 barrier() 가 의미하는 바를 지키면서도 컨트롤 의존성을 손상시킬 - 수 있기 때문이라는 점을 부디 알아두시기 바랍니다. - - (*) 컨트롤 의존성은 앞의 로드와 뒤의 스토어 사이에 최소 하나의, 실행 - 시점에서의 조건관계를 필요로 하며, 이 조건관계는 앞의 로드와 관계되어야 - 합니다. 만약 컴파일러가 조건 관계를 최적화로 없앨수 있다면, 순서도 - 최적화로 없애버렸을 겁니다. READ_ONCE() 와 WRITE_ONCE() 의 주의 깊은 - 사용은 주어진 조건 관계를 유지하는데 도움이 될 수 있습니다. - - (*) 컨트롤 의존성을 위해선 컴파일러가 조건관계를 없애버리는 것을 막아야 - 합니다. 주의 깊은 READ_ONCE() 나 atomic{,64}_read() 의 사용이 컨트롤 - 의존성이 사라지지 않게 하는데 도움을 줄 수 있습니다. 더 많은 정보를 - 위해선 "컴파일러 배리어" 섹션을 참고하시기 바랍니다. - - (*) 컨트롤 의존성은 컨트롤 의존성을 갖는 if 문의 then 절과 else 절과 이 두 절 - 내에서 호출되는 함수들에만 적용됩니다. 컨트롤 의존성은 컨트롤 의존성을 - 갖는 if 문을 뒤따르는 코드에는 적용되지 -않습니다-. - - (*) 컨트롤 의존성은 보통 다른 타입의 배리어들과 짝을 맞춰 사용됩니다. - - (*) 컨트롤 의존성은 multicopy 원자성을 제공하지 -않습니다-. 모든 CPU 들이 - 특정 스토어를 동시에 보길 원한다면, smp_mb() 를 사용하세요. - - (*) 컴파일러는 컨트롤 의존성을 이해하고 있지 않습니다. 따라서 컴파일러가 - 여러분의 코드를 망가뜨리지 않도록 하는건 여러분이 해야 하는 일입니다. - - -SMP 배리어 짝맞추기 --------------------- - -CPU 간 상호작용을 다룰 때에 일부 타입의 메모리 배리어는 항상 짝을 맞춰 -사용되어야 합니다. 적절하게 짝을 맞추지 않은 코드는 사실상 에러에 가깝습니다. - -범용 배리어들은 범용 배리어끼리도 짝을 맞추지만 multicopy 원자성이 없는 -대부분의 다른 타입의 배리어들과도 짝을 맞춥니다. ACQUIRE 배리어는 RELEASE -배리어와 짝을 맞춥니다만, 둘 다 범용 배리어를 포함해 다른 배리어들과도 짝을 -맞출 수 있습니다. 쓰기 배리어는 주소 의존성 배리어나 컨트롤 의존성, ACQUIRE -배리어, RELEASE 배리어, 읽기 배리어, 또는 범용 배리어와 짝을 맞춥니다. -비슷하게 읽기 배리어나 컨트롤 의존성, 또는 주소 의존성 배리어는 쓰기 배리어나 -ACQUIRE 배리어, RELEASE 배리어, 또는 범용 배리어와 짝을 맞추는데, 다음과 -같습니다: - - CPU 1 CPU 2 - =============== =============== - WRITE_ONCE(a, 1); - <쓰기 배리어> - WRITE_ONCE(b, 2); x = READ_ONCE(b); - <읽기 배리어> - y = READ_ONCE(a); - -또는: - - CPU 1 CPU 2 - =============== =============================== - a = 1; - <쓰기 배리어> - WRITE_ONCE(b, &a); x = READ_ONCE(b); - <묵시적 주소 의존성 배리어> - y = *x; - -또는: - - CPU 1 CPU 2 - =============== =============================== - r1 = READ_ONCE(y); - <범용 배리어> - WRITE_ONCE(x, 1); if (r2 = READ_ONCE(x)) { - <묵시적 컨트롤 의존성> - WRITE_ONCE(y, 1); - } - - assert(r1 == 0 || r2 == 0); - -기본적으로, 여기서의 읽기 배리어는 "더 완화된" 타입일 순 있어도 항상 존재해야 -합니다. - -[!] 쓰기 배리어 앞의 스토어 오퍼레이션은 일반적으로 읽기 배리어나 주소 의존성 -배리어 뒤의 로드 오퍼레이션과 매치될 것이고, 반대도 마찬가지입니다: - - CPU 1 CPU 2 - =================== =================== - WRITE_ONCE(a, 1); }---- --->{ v = READ_ONCE(c); - WRITE_ONCE(b, 2); } \ / { w = READ_ONCE(d); - <쓰기 배리어> \ <읽기 배리어> - WRITE_ONCE(c, 3); } / \ { x = READ_ONCE(a); - WRITE_ONCE(d, 4); }---- --->{ y = READ_ONCE(b); - - -메모리 배리어 시퀀스의 예 -------------------------- - -첫째, 쓰기 배리어는 스토어 오퍼레이션들의 부분적 순서 세우기로 동작합니다. -아래의 이벤트 시퀀스를 보세요: - - CPU 1 - ======================= - STORE A = 1 - STORE B = 2 - STORE C = 3 - <쓰기 배리어> - STORE D = 4 - STORE E = 5 - -이 이벤트 시퀀스는 메모리 일관성 시스템에 원소끼리의 순서가 존재하지 않는 집합 -{ STORE A, STORE B, STORE C } 가 역시 원소끼리의 순서가 존재하지 않는 집합 -{ STORE D, STORE E } 보다 먼저 일어난 것으로 시스템의 나머지 요소들에 보이도록 -전달됩니다: - - +-------+ : : - | | +------+ - | |------>| C=3 | } /\ - | | : +------+ }----- \ -----> 시스템의 나머지 요소에 - | | : | A=1 | } \/ 보여질 수 있는 이벤트들 - | | : +------+ } - | CPU 1 | : | B=2 | } - | | +------+ } - | | wwwwwwwwwwwwwwww } <--- 여기서 쓰기 배리어는 배리어 앞의 - | | +------+ } 모든 스토어가 배리어 뒤의 스토어 - | | : | E=5 | } 전에 메모리 시스템에 전달되도록 - | | : +------+ } 합니다 - | |------>| D=4 | } - | | +------+ - +-------+ : : - | - | CPU 1 에 의해 메모리 시스템에 전달되는 - | 일련의 스토어 오퍼레이션들 - V - - -둘째, 주소 의존성 배리어는 데이터 의존적 로드 오퍼레이션들의 부분적 순서 -세우기로 동작합니다. 다음 일련의 이벤트들을 보세요: - - CPU 1 CPU 2 - ======================= ======================= - { B = 7; X = 9; Y = 8; C = &Y } - STORE A = 1 - STORE B = 2 - <쓰기 배리어> - STORE C = &B LOAD X - STORE D = 4 LOAD C (gets &B) - LOAD *C (reads B) - -여기에 별다른 개입이 없다면, CPU 1 의 쓰기 배리어에도 불구하고 CPU 2 는 CPU 1 -의 이벤트들을 완전히 무작위적 순서로 인지하게 됩니다: - - +-------+ : : : : - | | +------+ +-------+ | CPU 2 에 인지되는 - | |------>| B=2 |----- --->| Y->8 | | 업데이트 이벤트 - | | : +------+ \ +-------+ | 시퀀스 - | CPU 1 | : | A=1 | \ --->| C->&Y | V - | | +------+ | +-------+ - | | wwwwwwwwwwwwwwww | : : - | | +------+ | : : - | | : | C=&B |--- | : : +-------+ - | | : +------+ \ | +-------+ | | - | |------>| D=4 | ----------->| C->&B |------>| | - | | +------+ | +-------+ | | - +-------+ : : | : : | | - | : : | | - | : : | CPU 2 | - | +-------+ | | - 분명히 잘못된 ---> | | B->7 |------>| | - B 의 값 인지 (!) | +-------+ | | - | : : | | - | +-------+ | | - X 의 로드가 B 의 ---> \ | X->9 |------>| | - 일관성 유지를 \ +-------+ | | - 지연시킴 ----->| B->2 | +-------+ - +-------+ - : : - - -앞의 예에서, CPU 2 는 (B 의 값이 될) *C 의 값 읽기가 C 의 LOAD 뒤에 이어짐에도 -B 가 7 이라는 결과를 얻습니다. - -하지만, 만약 주소 의존성 배리어가 C 의 로드와 *C (즉, B) 의 로드 사이에 -있었다면: - - CPU 1 CPU 2 - ======================= ======================= - { B = 7; X = 9; Y = 8; C = &Y } - STORE A = 1 - STORE B = 2 - <쓰기 배리어> - STORE C = &B LOAD X - STORE D = 4 LOAD C (gets &B) - <주소 의존성 배리어> - LOAD *C (reads B) - -다음과 같이 됩니다: - - +-------+ : : : : - | | +------+ +-------+ - | |------>| B=2 |----- --->| Y->8 | - | | : +------+ \ +-------+ - | CPU 1 | : | A=1 | \ --->| C->&Y | - | | +------+ | +-------+ - | | wwwwwwwwwwwwwwww | : : - | | +------+ | : : - | | : | C=&B |--- | : : +-------+ - | | : +------+ \ | +-------+ | | - | |------>| D=4 | ----------->| C->&B |------>| | - | | +------+ | +-------+ | | - +-------+ : : | : : | | - | : : | | - | : : | CPU 2 | - | +-------+ | | - | | X->9 |------>| | - | +-------+ | | - C 로의 스토어 앞의 ---> \ aaaaaaaaaaaaaaaaa | | - 모든 이벤트 결과가 \ +-------+ | | - 뒤의 로드에게 ----->| B->2 |------>| | - 보이게 강제한다 +-------+ | | - : : +-------+ - - -셋째, 읽기 배리어는 로드 오퍼레이션들에의 부분적 순서 세우기로 동작합니다. -아래의 일련의 이벤트를 봅시다: - - CPU 1 CPU 2 - ======================= ======================= - { A = 0, B = 9 } - STORE A=1 - <쓰기 배리어> - STORE B=2 - LOAD B - LOAD A - -CPU 1 은 쓰기 배리어를 쳤지만, 별다른 개입이 없다면 CPU 2 는 CPU 1 에서 행해진 -이벤트의 결과를 무작위적 순서로 인지하게 됩니다. - - +-------+ : : : : - | | +------+ +-------+ - | |------>| A=1 |------ --->| A->0 | - | | +------+ \ +-------+ - | CPU 1 | wwwwwwwwwwwwwwww \ --->| B->9 | - | | +------+ | +-------+ - | |------>| B=2 |--- | : : - | | +------+ \ | : : +-------+ - +-------+ : : \ | +-------+ | | - ---------->| B->2 |------>| | - | +-------+ | CPU 2 | - | | A->0 |------>| | - | +-------+ | | - | : : +-------+ - \ : : - \ +-------+ - ---->| A->1 | - +-------+ - : : - - -하지만, 만약 읽기 배리어가 B 의 로드와 A 의 로드 사이에 존재한다면: - - CPU 1 CPU 2 - ======================= ======================= - { A = 0, B = 9 } - STORE A=1 - <쓰기 배리어> - STORE B=2 - LOAD B - <읽기 배리어> - LOAD A - -CPU 1 에 의해 만들어진 부분적 순서가 CPU 2 에도 그대로 인지됩니다: - - +-------+ : : : : - | | +------+ +-------+ - | |------>| A=1 |------ --->| A->0 | - | | +------+ \ +-------+ - | CPU 1 | wwwwwwwwwwwwwwww \ --->| B->9 | - | | +------+ | +-------+ - | |------>| B=2 |--- | : : - | | +------+ \ | : : +-------+ - +-------+ : : \ | +-------+ | | - ---------->| B->2 |------>| | - | +-------+ | CPU 2 | - | : : | | - | : : | | - 여기서 읽기 배리어는 ----> \ rrrrrrrrrrrrrrrrr | | - B 로의 스토어 전의 \ +-------+ | | - 모든 결과를 CPU 2 에 ---->| A->1 |------>| | - 보이도록 한다 +-------+ | | - : : +-------+ - - -더 완벽한 설명을 위해, A 의 로드가 읽기 배리어 앞과 뒤에 있으면 어떻게 될지 -생각해 봅시다: - - CPU 1 CPU 2 - ======================= ======================= - { A = 0, B = 9 } - STORE A=1 - <쓰기 배리어> - STORE B=2 - LOAD B - LOAD A [first load of A] - <읽기 배리어> - LOAD A [second load of A] - -A 의 로드 두개가 모두 B 의 로드 뒤에 있지만, 서로 다른 값을 얻어올 수 -있습니다: - - +-------+ : : : : - | | +------+ +-------+ - | |------>| A=1 |------ --->| A->0 | - | | +------+ \ +-------+ - | CPU 1 | wwwwwwwwwwwwwwww \ --->| B->9 | - | | +------+ | +-------+ - | |------>| B=2 |--- | : : - | | +------+ \ | : : +-------+ - +-------+ : : \ | +-------+ | | - ---------->| B->2 |------>| | - | +-------+ | CPU 2 | - | : : | | - | : : | | - | +-------+ | | - | | A->0 |------>| 1st | - | +-------+ | | - 여기서 읽기 배리어는 ----> \ rrrrrrrrrrrrrrrrr | | - B 로의 스토어 전의 \ +-------+ | | - 모든 결과를 CPU 2 에 ---->| A->1 |------>| 2nd | - 보이도록 한다 +-------+ | | - : : +-------+ - - -하지만 CPU 1 에서의 A 업데이트는 읽기 배리어가 완료되기 전에도 보일 수도 -있긴 합니다: - - +-------+ : : : : - | | +------+ +-------+ - | |------>| A=1 |------ --->| A->0 | - | | +------+ \ +-------+ - | CPU 1 | wwwwwwwwwwwwwwww \ --->| B->9 | - | | +------+ | +-------+ - | |------>| B=2 |--- | : : - | | +------+ \ | : : +-------+ - +-------+ : : \ | +-------+ | | - ---------->| B->2 |------>| | - | +-------+ | CPU 2 | - | : : | | - \ : : | | - \ +-------+ | | - ---->| A->1 |------>| 1st | - +-------+ | | - rrrrrrrrrrrrrrrrr | | - +-------+ | | - | A->1 |------>| 2nd | - +-------+ | | - : : +-------+ - - -여기서 보장되는 건, 만약 B 의 로드가 B == 2 라는 결과를 봤다면, A 에의 두번째 -로드는 항상 A == 1 을 보게 될 것이라는 겁니다. A 에의 첫번째 로드에는 그런 -보장이 없습니다; A == 0 이거나 A == 1 이거나 둘 중 하나의 결과를 보게 될겁니다. - - -읽기 메모리 배리어 VS 로드 예측 -------------------------------- - -많은 CPU들이 로드를 예측적으로 (speculatively) 합니다: 어떤 데이터를 메모리에서 -로드해야 하게 될지 예측을 했다면, 해당 데이터를 로드하는 인스트럭션을 실제로는 -아직 만나지 않았더라도 다른 로드 작업이 없어 버스 (bus) 가 아무 일도 하고 있지 -않다면, 그 데이터를 로드합니다. 이후에 실제 로드 인스트럭션이 실행되면 CPU 가 -이미 그 값을 가지고 있기 때문에 그 로드 인스트럭션은 즉시 완료됩니다. - -해당 CPU 는 실제로는 그 값이 필요치 않았다는 사실이 나중에 드러날 수도 있는데 - -해당 로드 인스트럭션이 브랜치로 우회되거나 했을 수 있겠죠 - , 그렇게 되면 앞서 -읽어둔 값을 버리거나 나중의 사용을 위해 캐시에 넣어둘 수 있습니다. - -다음을 생각해 봅시다: - - CPU 1 CPU 2 - ======================= ======================= - LOAD B - DIVIDE } 나누기 명령은 일반적으로 - DIVIDE } 긴 시간을 필요로 합니다 - LOAD A - -는 이렇게 될 수 있습니다: - - : : +-------+ - +-------+ | | - --->| B->2 |------>| | - +-------+ | CPU 2 | - : :DIVIDE | | - +-------+ | | - 나누기 하느라 바쁜 ---> --->| A->0 |~~~~ | | - CPU 는 A 의 LOAD 를 +-------+ ~ | | - 예측해서 수행한다 : : ~ | | - : :DIVIDE | | - : : ~ | | - 나누기가 끝나면 ---> ---> : : ~-->| | - CPU 는 해당 LOAD 를 : : | | - 즉각 완료한다 : : +-------+ - - -읽기 배리어나 주소 의존성 배리어를 두번째 로드 직전에 놓는다면: - - CPU 1 CPU 2 - ======================= ======================= - LOAD B - DIVIDE - DIVIDE - <읽기 배리어> - LOAD A - -예측으로 얻어진 값은 사용된 배리어의 타입에 따라서 해당 값이 옳은지 검토되게 -됩니다. 만약 해당 메모리 영역에 변화가 없었다면, 예측으로 얻어두었던 값이 -사용됩니다: - - : : +-------+ - +-------+ | | - --->| B->2 |------>| | - +-------+ | CPU 2 | - : :DIVIDE | | - +-------+ | | - 나누기 하느라 바쁜 ---> --->| A->0 |~~~~ | | - CPU 는 A 의 LOAD 를 +-------+ ~ | | - 예측한다 : : ~ | | - : :DIVIDE | | - : : ~ | | - : : ~ | | - rrrrrrrrrrrrrrrr~ | | - : : ~ | | - : : ~-->| | - : : | | - : : +-------+ - - -하지만 다른 CPU 에서 업데이트나 무효화가 있었다면, 그 예측은 무효화되고 그 값은 -다시 읽혀집니다: - - : : +-------+ - +-------+ | | - --->| B->2 |------>| | - +-------+ | CPU 2 | - : :DIVIDE | | - +-------+ | | - 나누기 하느라 바쁜 ---> --->| A->0 |~~~~ | | - CPU 는 A 의 LOAD 를 +-------+ ~ | | - 예측한다 : : ~ | | - : :DIVIDE | | - : : ~ | | - : : ~ | | - rrrrrrrrrrrrrrrrr | | - +-------+ | | - 예측성 동작은 무효화 되고 ---> --->| A->1 |------>| | - 업데이트된 값이 다시 읽혀진다 +-------+ | | - : : +-------+ - - -MULTICOPY 원자성 ----------------- - -Multicopy 원자성은 실제의 컴퓨터 시스템에서 항상 제공되지는 않는, 순서 맞추기에 -대한 상당히 직관적인 개념으로, 특정 스토어가 모든 CPU 들에게 동시에 보여지게 -됨을, 달리 말하자면 모든 CPU 들이 모든 스토어들이 보여지는 순서를 동의하게 되는 -것입니다. 하지만, 완전한 multicopy 원자성의 사용은 가치있는 하드웨어 -최적화들을 무능하게 만들어버릴 수 있어서, 보다 완화된 형태의 ``다른 multicopy -원자성'' 라는 이름의, 특정 스토어가 모든 -다른- CPU 들에게는 동시에 보여지게 -하는 보장을 대신 제공합니다. 이 문서의 뒷부분들은 이 완화된 형태에 대해 논하게 -됩니다만, 단순히 ``multicopy 원자성'' 이라고 부르겠습니다. - -다음의 예가 multicopy 원자성을 보입니다: - - CPU 1 CPU 2 CPU 3 - ======================= ======================= ======================= - { X = 0, Y = 0 } - STORE X=1 r1=LOAD X (reads 1) LOAD Y (reads 1) - <범용 배리어> <읽기 배리어> - STORE Y=r1 LOAD X - -CPU 2 의 Y 로의 스토어에 사용되는 X 로드의 결과가 1 이었고 CPU 3 의 Y 로드가 -1을 리턴했다고 해봅시다. 이는 CPU 1 의 X 로의 스토어가 CPU 2 의 X 로부터의 -로드를 앞서고 CPU 2 의 Y 로의 스토어가 CPU 3 의 Y 로부터의 로드를 앞섬을 -의미합니다. 또한, 여기서의 메모리 배리어들은 CPU 2 가 자신의 로드를 자신의 -스토어 전에 수행하고, CPU 3 가 Y 로부터의 로드를 X 로부터의 로드 전에 수행함을 -보장합니다. 그럼 "CPU 3 의 X 로부터의 로드는 0 을 리턴할 수 있을까요?" - -CPU 3 의 X 로드가 CPU 2 의 로드보다 뒤에 이루어졌으므로, CPU 3 의 X 로부터의 -로드는 1 을 리턴한다고 예상하는게 당연합니다. 이런 예상은 multicopy -원자성으로부터 나옵니다: CPU B 에서 수행된 로드가 CPU A 의 같은 변수로부터의 -로드를 뒤따른다면 (그리고 CPU A 가 자신이 읽은 값으로 먼저 해당 변수에 스토어 -하지 않았다면) multicopy 원자성을 제공하는 시스템에서는, CPU B 의 로드가 CPU A -의 로드와 같은 값 또는 그 나중 값을 리턴해야만 합니다. 하지만, 리눅스 커널은 -시스템들이 multicopy 원자성을 제공할 것을 요구하지 않습니다. - -앞의 범용 메모리 배리어의 사용은 모든 multicopy 원자성의 부족을 보상해줍니다. -앞의 예에서, CPU 2 의 X 로부터의 로드가 1 을 리턴했고 CPU 3 의 Y 로부터의 -로드가 1 을 리턴했다면, CPU 3 의 X 로부터의 로드는 1을 리턴해야만 합니다. - -하지만, 의존성, 읽기 배리어, 쓰기 배리어는 항상 non-multicopy 원자성을 보상해 -주지는 않습니다. 예를 들어, CPU 2 의 범용 배리어가 앞의 예에서 사라져서 -아래처럼 데이터 의존성만 남게 되었다고 해봅시다: - - CPU 1 CPU 2 CPU 3 - ======================= ======================= ======================= - { X = 0, Y = 0 } - STORE X=1 r1=LOAD X (reads 1) LOAD Y (reads 1) - <데이터 의존성> <읽기 배리어> - STORE Y=r1 LOAD X (reads 0) - -이 변화는 non-multicopy 원자성이 만연하게 합니다: 이 예에서, CPU 2 의 X -로부터의 로드가 1을 리턴하고, CPU 3 의 Y 로부터의 로드가 1 을 리턴하는데, CPU 3 -의 X 로부터의 로드가 0 을 리턴하는게 완전히 합법적입니다. - -핵심은, CPU 2 의 데이터 의존성이 자신의 로드와 스토어를 순서짓지만, CPU 1 의 -스토어에 대한 순서는 보장하지 않는다는 것입니다. 따라서, 이 예제가 CPU 1 과 -CPU 2 가 스토어 버퍼나 한 수준의 캐시를 공유하는, multicopy 원자성을 제공하지 -않는 시스템에서 수행된다면 CPU 2 는 CPU 1 의 쓰기에 이른 접근을 할 수도 -있습니다. 따라서, 모든 CPU 들이 여러 접근들의 조합된 순서에 대해서 동의하게 -하기 위해서는 범용 배리어가 필요합니다. - -범용 배리어는 non-multicopy 원자성만 보상할 수 있는게 아니라, -모든- CPU 들이 --모든- 오퍼레이션들의 순서를 동일하게 인식하게 하는 추가적인 순서 보장을 -만들어냅니다. 반대로, release-acquire 짝의 연결은 이런 추가적인 순서는 -제공하지 않는데, 해당 연결에 들어있는 CPU 들만이 메모리 접근의 조합된 순서에 -대해 동의할 것으로 보장됨을 의미합니다. 예를 들어, 존경스런 Herman Hollerith -의 코드를 C 코드로 변환하면: - - int u, v, x, y, z; - - void cpu0(void) - { - r0 = smp_load_acquire(&x); - WRITE_ONCE(u, 1); - smp_store_release(&y, 1); - } - - void cpu1(void) - { - r1 = smp_load_acquire(&y); - r4 = READ_ONCE(v); - r5 = READ_ONCE(u); - smp_store_release(&z, 1); - } - - void cpu2(void) - { - r2 = smp_load_acquire(&z); - smp_store_release(&x, 1); - } - - void cpu3(void) - { - WRITE_ONCE(v, 1); - smp_mb(); - r3 = READ_ONCE(u); - } - -cpu0(), cpu1(), 그리고 cpu2() 는 smp_store_release()/smp_load_acquire() 쌍의 -연결에 참여되어 있으므로, 다음과 같은 결과는 나오지 않을 겁니다: - - r0 == 1 && r1 == 1 && r2 == 1 - -더 나아가서, cpu0() 와 cpu1() 사이의 release-acquire 관계로 인해, cpu1() 은 -cpu0() 의 쓰기를 봐야만 하므로, 다음과 같은 결과도 없을 겁니다: - - r1 == 1 && r5 == 0 - -하지만, release-acquire 에 의해 제공되는 순서는 해당 연결에 동참한 CPU 들에만 -적용되므로 cpu3() 에, 적어도 스토어들 외에는 적용되지 않습니다. 따라서, 다음과 -같은 결과가 가능합니다: - - r0 == 0 && r1 == 1 && r2 == 1 && r3 == 0 && r4 == 0 - -비슷하게, 다음과 같은 결과도 가능합니다: - - r0 == 0 && r1 == 1 && r2 == 1 && r3 == 0 && r4 == 0 && r5 == 1 - -cpu0(), cpu1(), 그리고 cpu2() 는 그들의 읽기와 쓰기를 순서대로 보게 되지만, -release-acquire 체인에 관여되지 않은 CPU 들은 그 순서에 이견을 가질 수 -있습니다. 이런 이견은 smp_load_acquire() 와 smp_store_release() 의 구현에 -사용되는 완화된 메모리 배리어 인스트럭션들은 항상 배리어 앞의 스토어들을 뒤의 -로드들에 앞세울 필요는 없다는 사실에서 기인합니다. 이 말은 cpu3() 는 cpu0() 의 -u 로의 스토어를 cpu1() 의 v 로부터의 로드 뒤에 일어난 것으로 볼 수 있다는 -뜻입니다, cpu0() 와 cpu1() 은 이 두 오퍼레이션이 의도된 순서대로 일어났음에 -모두 동의하는데도 말입니다. - -하지만, smp_load_acquire() 는 마술이 아님을 명심하시기 바랍니다. 구체적으로, -이 함수는 단순히 순서 규칙을 지키며 인자로부터의 읽기를 수행합니다. 이것은 -어떤 특정한 값이 읽힐 것인지는 보장하지 -않습니다-. 따라서, 다음과 같은 결과도 -가능합니다: - - r0 == 0 && r1 == 0 && r2 == 0 && r5 == 0 - -이런 결과는 어떤 것도 재배치 되지 않는, 순차적 일관성을 가진 가상의 -시스템에서도 일어날 수 있음을 기억해 두시기 바랍니다. - -다시 말하지만, 당신의 코드가 모든 오퍼레이션들의 완전한 순서를 필요로 한다면, -범용 배리어를 사용하십시오. - - -================== -명시적 커널 배리어 -================== - -리눅스 커널은 서로 다른 단계에서 동작하는 다양한 배리어들을 가지고 있습니다: - - (*) 컴파일러 배리어. - - (*) CPU 메모리 배리어. - - -컴파일러 배리어 ---------------- - -리눅스 커널은 컴파일러가 메모리 액세스를 재배치 하는 것을 막아주는 명시적인 -컴파일러 배리어를 가지고 있습니다: - - barrier(); - -이건 범용 배리어입니다 -- barrier() 의 읽기-읽기 나 쓰기-쓰기 변종은 없습니다. -하지만, READ_ONCE() 와 WRITE_ONCE() 는 특정 액세스들에 대해서만 동작하는 -barrier() 의 완화된 형태로 볼 수 있습니다. - -barrier() 함수는 다음과 같은 효과를 갖습니다: - - (*) 컴파일러가 barrier() 뒤의 액세스들이 barrier() 앞의 액세스보다 앞으로 - 재배치되지 못하게 합니다. 예를 들어, 인터럽트 핸들러 코드와 인터럽트 당한 - 코드 사이의 통신을 신중히 하기 위해 사용될 수 있습니다. - - (*) 루프에서, 컴파일러가 루프 조건에 사용된 변수를 매 이터레이션마다 - 메모리에서 로드하지 않아도 되도록 최적화 하는걸 방지합니다. - -READ_ONCE() 와 WRITE_ONCE() 함수는 싱글 쓰레드 코드에서는 문제 없지만 동시성이 -있는 코드에서는 문제가 될 수 있는 모든 최적화를 막습니다. 이런 류의 최적화에 -대한 예를 몇가지 들어보면 다음과 같습니다: - - (*) 컴파일러는 같은 변수에 대한 로드와 스토어를 재배치 할 수 있고, 어떤 - 경우에는 CPU가 같은 변수로부터의 로드들을 재배치할 수도 있습니다. 이는 - 다음의 코드가: - - a[0] = x; - a[1] = x; - - x 의 예전 값이 a[1] 에, 새 값이 a[0] 에 있게 할 수 있다는 뜻입니다. - 컴파일러와 CPU가 이런 일을 못하게 하려면 다음과 같이 해야 합니다: - - a[0] = READ_ONCE(x); - a[1] = READ_ONCE(x); - - 즉, READ_ONCE() 와 WRITE_ONCE() 는 여러 CPU 에서 하나의 변수에 가해지는 - 액세스들에 캐시 일관성을 제공합니다. - - (*) 컴파일러는 같은 변수에 대한 연속적인 로드들을 병합할 수 있습니다. 그런 - 병합 작업으로 컴파일러는 다음의 코드를: - - while (tmp = a) - do_something_with(tmp); - - 다음과 같이, 싱글 쓰레드 코드에서는 말이 되지만 개발자의 의도와 전혀 맞지 - 않는 방향으로 "최적화" 할 수 있습니다: - - if (tmp = a) - for (;;) - do_something_with(tmp); - - 컴파일러가 이런 짓을 하지 못하게 하려면 READ_ONCE() 를 사용하세요: - - while (tmp = READ_ONCE(a)) - do_something_with(tmp); - - (*) 예컨대 레지스터 사용량이 많아 컴파일러가 모든 데이터를 레지스터에 담을 수 - 없는 경우, 컴파일러는 변수를 다시 로드할 수 있습니다. 따라서 컴파일러는 - 앞의 예에서 변수 'tmp' 사용을 최적화로 없애버릴 수 있습니다: - - while (tmp = a) - do_something_with(tmp); - - 이 코드는 다음과 같이 싱글 쓰레드에서는 완벽하지만 동시성이 존재하는 - 경우엔 치명적인 코드로 바뀔 수 있습니다: - - while (a) - do_something_with(a); - - 예를 들어, 최적화된 이 코드는 변수 a 가 다른 CPU 에 의해 "while" 문과 - do_something_with() 호출 사이에 바뀌어 do_something_with() 에 0을 넘길 - 수도 있습니다. - - 이번에도, 컴파일러가 그런 짓을 하는걸 막기 위해 READ_ONCE() 를 사용하세요: - - while (tmp = READ_ONCE(a)) - do_something_with(tmp); - - 레지스터가 부족한 상황을 겪는 경우, 컴파일러는 tmp 를 스택에 저장해둘 수도 - 있습니다. 컴파일러가 변수를 다시 읽어들이는건 이렇게 저장해두고 후에 다시 - 읽어들이는데 드는 오버헤드 때문입니다. 그렇게 하는게 싱글 쓰레드 - 코드에서는 안전하므로, 안전하지 않은 경우에는 컴파일러에게 직접 알려줘야 - 합니다. - - (*) 컴파일러는 그 값이 무엇일지 알고 있다면 로드를 아예 안할 수도 있습니다. - 예를 들어, 다음의 코드는 변수 'a' 의 값이 항상 0임을 증명할 수 있다면: - - while (tmp = a) - do_something_with(tmp); - - 이렇게 최적화 되어버릴 수 있습니다: - - do { } while (0); - - 이 변환은 싱글 쓰레드 코드에서는 도움이 되는데 로드와 브랜치를 제거했기 - 때문입니다. 문제는 컴파일러가 'a' 의 값을 업데이트 하는건 현재의 CPU 하나 - 뿐이라는 가정 위에서 증명을 했다는데 있습니다. 만약 변수 'a' 가 공유되어 - 있다면, 컴파일러의 증명은 틀린 것이 될겁니다. 컴파일러는 그 자신이 - 생각하는 것만큼 많은 것을 알고 있지 못함을 컴파일러에게 알리기 위해 - READ_ONCE() 를 사용하세요: - - while (tmp = READ_ONCE(a)) - do_something_with(tmp); - - 하지만 컴파일러는 READ_ONCE() 뒤에 나오는 값에 대해서도 눈길을 두고 있음을 - 기억하세요. 예를 들어, 다음의 코드에서 MAX 는 전처리기 매크로로, 1의 값을 - 갖는다고 해봅시다: - - while ((tmp = READ_ONCE(a)) % MAX) - do_something_with(tmp); - - 이렇게 되면 컴파일러는 MAX 를 가지고 수행되는 "%" 오퍼레이터의 결과가 항상 - 0이라는 것을 알게 되고, 컴파일러가 코드를 실질적으로는 존재하지 않는 - 것처럼 최적화 하는 것이 허용되어 버립니다. ('a' 변수의 로드는 여전히 - 행해질 겁니다.) - - (*) 비슷하게, 컴파일러는 변수가 저장하려 하는 값을 이미 가지고 있다는 것을 - 알면 스토어 자체를 제거할 수 있습니다. 이번에도, 컴파일러는 현재의 CPU - 만이 그 변수에 값을 쓰는 오로지 하나의 존재라고 생각하여 공유된 변수에 - 대해서는 잘못된 일을 하게 됩니다. 예를 들어, 다음과 같은 경우가 있을 수 - 있습니다: - - a = 0; - ... 변수 a 에 스토어를 하지 않는 코드 ... - a = 0; - - 컴파일러는 변수 'a' 의 값은 이미 0이라는 것을 알고, 따라서 두번째 스토어를 - 삭제할 겁니다. 만약 다른 CPU 가 그 사이 변수 'a' 에 다른 값을 썼다면 - 황당한 결과가 나올 겁니다. - - 컴파일러가 그런 잘못된 추측을 하지 않도록 WRITE_ONCE() 를 사용하세요: - - WRITE_ONCE(a, 0); - ... 변수 a 에 스토어를 하지 않는 코드 ... - WRITE_ONCE(a, 0); - - (*) 컴파일러는 하지 말라고 하지 않으면 메모리 액세스들을 재배치 할 수 - 있습니다. 예를 들어, 다음의 프로세스 레벨 코드와 인터럽트 핸들러 사이의 - 상호작용을 생각해 봅시다: - - void process_level(void) - { - msg = get_message(); - flag = true; - } - - void interrupt_handler(void) - { - if (flag) - process_message(msg); - } - - 이 코드에는 컴파일러가 process_level() 을 다음과 같이 변환하는 것을 막을 - 수단이 없고, 이런 변환은 싱글쓰레드에서라면 실제로 훌륭한 선택일 수 - 있습니다: - - void process_level(void) - { - flag = true; - msg = get_message(); - } - - 이 두개의 문장 사이에 인터럽트가 발생한다면, interrupt_handler() 는 의미를 - 알 수 없는 메세지를 받을 수도 있습니다. 이걸 막기 위해 다음과 같이 - WRITE_ONCE() 를 사용하세요: - - void process_level(void) - { - WRITE_ONCE(msg, get_message()); - WRITE_ONCE(flag, true); - } - - void interrupt_handler(void) - { - if (READ_ONCE(flag)) - process_message(READ_ONCE(msg)); - } - - interrupt_handler() 안에서도 중첩된 인터럽트나 NMI 와 같이 인터럽트 핸들러 - 역시 'flag' 와 'msg' 에 접근하는 또다른 무언가에 인터럽트 될 수 있다면 - READ_ONCE() 와 WRITE_ONCE() 를 사용해야 함을 기억해 두세요. 만약 그런 - 가능성이 없다면, interrupt_handler() 안에서는 문서화 목적이 아니라면 - READ_ONCE() 와 WRITE_ONCE() 는 필요치 않습니다. (근래의 리눅스 커널에서 - 중첩된 인터럽트는 보통 잘 일어나지 않음도 기억해 두세요, 실제로, 어떤 - 인터럽트 핸들러가 인터럽트가 활성화된 채로 리턴하면 WARN_ONCE() 가 - 실행됩니다.) - - 컴파일러는 READ_ONCE() 와 WRITE_ONCE() 뒤의 READ_ONCE() 나 WRITE_ONCE(), - barrier(), 또는 비슷한 것들을 담고 있지 않은 코드를 움직일 수 있을 것으로 - 가정되어야 합니다. - - 이 효과는 barrier() 를 통해서도 만들 수 있지만, READ_ONCE() 와 - WRITE_ONCE() 가 좀 더 안목 높은 선택입니다: READ_ONCE() 와 WRITE_ONCE()는 - 컴파일러에 주어진 메모리 영역에 대해서만 최적화 가능성을 포기하도록 - 하지만, barrier() 는 컴파일러가 지금까지 기계의 레지스터에 캐시해 놓은 - 모든 메모리 영역의 값을 버려야 하게 하기 때문입니다. 물론, 컴파일러는 - READ_ONCE() 와 WRITE_ONCE() 가 일어난 순서도 지켜줍니다, CPU 는 당연히 - 그 순서를 지킬 의무가 없지만요. - - (*) 컴파일러는 다음의 예에서와 같이 변수에의 스토어를 날조해낼 수도 있습니다: - - if (a) - b = a; - else - b = 42; - - 컴파일러는 아래와 같은 최적화로 브랜치를 줄일 겁니다: - - b = 42; - if (a) - b = a; - - 싱글 쓰레드 코드에서 이 최적화는 안전할 뿐 아니라 브랜치 갯수를 - 줄여줍니다. 하지만 안타깝게도, 동시성이 있는 코드에서는 이 최적화는 다른 - CPU 가 'b' 를 로드할 때, -- 'a' 가 0이 아닌데도 -- 가짜인 값, 42를 보게 - 되는 경우를 가능하게 합니다. 이걸 방지하기 위해 WRITE_ONCE() 를 - 사용하세요: - - if (a) - WRITE_ONCE(b, a); - else - WRITE_ONCE(b, 42); - - 컴파일러는 로드를 만들어낼 수도 있습니다. 일반적으로는 문제를 일으키지 - 않지만, 캐시 라인 바운싱을 일으켜 성능과 확장성을 떨어뜨릴 수 있습니다. - 날조된 로드를 막기 위해선 READ_ONCE() 를 사용하세요. - - (*) 정렬된 메모리 주소에 위치한, 한번의 메모리 참조 인스트럭션으로 액세스 - 가능한 크기의 데이터는 하나의 큰 액세스가 여러개의 작은 액세스들로 - 대체되는 "로드 티어링(load tearing)" 과 "스토어 티어링(store tearing)" 을 - 방지합니다. 예를 들어, 주어진 아키텍쳐가 7-bit imeediate field 를 갖는 - 16-bit 스토어 인스트럭션을 제공한다면, 컴파일러는 다음의 32-bit 스토어를 - 구현하는데에 두개의 16-bit store-immediate 명령을 사용하려 할겁니다: - - p = 0x00010002; - - 스토어 할 상수를 만들고 그 값을 스토어 하기 위해 두개가 넘는 인스트럭션을 - 사용하게 되는, 이런 종류의 최적화를 GCC 는 실제로 함을 부디 알아 두십시오. - 이 최적화는 싱글 쓰레드 코드에서는 성공적인 최적화 입니다. 실제로, 근래에 - 발생한 (그리고 고쳐진) 버그는 GCC 가 volatile 스토어에 비정상적으로 이 - 최적화를 사용하게 했습니다. 그런 버그가 없다면, 다음의 예에서 - WRITE_ONCE() 의 사용은 스토어 티어링을 방지합니다: - - WRITE_ONCE(p, 0x00010002); - - Packed 구조체의 사용 역시 다음의 예처럼 로드 / 스토어 티어링을 유발할 수 - 있습니다: - - struct __attribute__((__packed__)) foo { - short a; - int b; - short c; - }; - struct foo foo1, foo2; - ... - - foo2.a = foo1.a; - foo2.b = foo1.b; - foo2.c = foo1.c; - - READ_ONCE() 나 WRITE_ONCE() 도 없고 volatile 마킹도 없기 때문에, - 컴파일러는 이 세개의 대입문을 두개의 32-bit 로드와 두개의 32-bit 스토어로 - 변환할 수 있습니다. 이는 'foo1.b' 의 값의 로드 티어링과 'foo2.b' 의 - 스토어 티어링을 초래할 겁니다. 이 예에서도 READ_ONCE() 와 WRITE_ONCE() - 가 티어링을 막을 수 있습니다: - - foo2.a = foo1.a; - WRITE_ONCE(foo2.b, READ_ONCE(foo1.b)); - foo2.c = foo1.c; - -그렇지만, volatile 로 마크된 변수에 대해서는 READ_ONCE() 와 WRITE_ONCE() 가 -필요치 않습니다. 예를 들어, 'jiffies' 는 volatile 로 마크되어 있기 때문에, -READ_ONCE(jiffies) 라고 할 필요가 없습니다. READ_ONCE() 와 WRITE_ONCE() 가 -실은 volatile 캐스팅으로 구현되어 있어서 인자가 이미 volatile 로 마크되어 -있다면 또다른 효과를 내지는 않기 때문입니다. - -이 컴파일러 배리어들은 CPU 에는 직접적 효과를 전혀 만들지 않기 때문에, 결국은 -재배치가 일어날 수도 있음을 부디 기억해 두십시오. - - -CPU 메모리 배리어 ------------------ - -리눅스 커널은 다음의 일곱개 기본 CPU 메모리 배리어를 가지고 있습니다: - - TYPE MANDATORY SMP CONDITIONAL - =============== ======================= =============== - 범용 mb() smp_mb() - 쓰기 wmb() smp_wmb() - 읽기 rmb() smp_rmb() - 주소 의존성 READ_ONCE() - - -주소 의존성 배리어를 제외한 모든 메모리 배리어는 컴파일러 배리어를 포함합니다. -주소 의존성은 컴파일러에의 추가적인 순서 보장을 포함하지 않습니다. - -방백: 주소 의존성이 있는 경우, 컴파일러는 해당 로드를 올바른 순서로 일으킬 -것으로 (예: `a[b]` 는 a[b] 를 로드 하기 전에 b 의 값을 먼저 로드한다) -기대되지만, C 언어 사양에는 컴파일러가 b 의 값을 추측 (예: 1 과 같음) 해서 -b 로드 전에 a 로드를 하는 코드 (예: tmp = a[1]; if (b != 1) tmp = a[b]; ) 를 -만들지 않아야 한다는 내용 같은 건 없습니다. 또한 컴파일러는 a[b] 를 로드한 -후에 b 를 또다시 로드할 수도 있어서, a[b] 보다 최신 버전의 b 값을 가질 수도 -있습니다. 이런 문제들의 해결책에 대한 의견 일치는 아직 없습니다만, 일단 -READ_ONCE() 매크로부터 보기 시작하는게 좋은 시작이 될겁니다. - -SMP 메모리 배리어들은 유니프로세서로 컴파일된 시스템에서는 컴파일러 배리어로 -바뀌는데, 하나의 CPU 는 스스로 일관성을 유지하고, 겹치는 액세스들 역시 올바른 -순서로 행해질 것으로 생각되기 때문입니다. 하지만, 아래의 "Virtual Machine -Guests" 서브섹션을 참고하십시오. - -[!] SMP 시스템에서 공유메모리로의 접근들을 순서 세워야 할 때, SMP 메모리 -배리어는 _반드시_ 사용되어야 함을 기억하세요, 그대신 락을 사용하는 것으로도 -충분하긴 하지만 말이죠. - -Mandatory 배리어들은 SMP 시스템에서도 UP 시스템에서도 SMP 효과만 통제하기에는 -불필요한 오버헤드를 갖기 때문에 SMP 효과만 통제하면 되는 곳에는 사용되지 않아야 -합니다. 하지만, 느슨한 순서 규칙의 메모리 I/O 윈도우를 통한 MMIO 의 효과를 -통제할 때에는 mandatory 배리어들이 사용될 수 있습니다. 이 배리어들은 -컴파일러와 CPU 모두 재배치를 못하도록 함으로써 메모리 오퍼레이션들이 디바이스에 -보여지는 순서에도 영향을 주기 때문에, SMP 가 아닌 시스템이라 할지라도 필요할 수 -있습니다. - - -일부 고급 배리어 함수들도 있습니다: - - (*) smp_store_mb(var, value) - - 이 함수는 특정 변수에 특정 값을 대입하고 범용 메모리 배리어를 칩니다. - UP 컴파일에서는 컴파일러 배리어보다 더한 것을 친다고는 보장되지 않습니다. - - - (*) smp_mb__before_atomic(); - (*) smp_mb__after_atomic(); - - 이것들은 메모리 배리어를 내포하지 않는 어토믹 RMW 함수를 사용하지만 코드에 - 메모리 배리어가 필요한 경우를 위한 것들입니다. 메모리 배리어를 내포하지 - 않는 어토믹 RMW 함수들의 예로는 더하기, 빼기, (실패한) 조건적 - 오퍼레이션들, _relaxed 함수들이 있으며, atomic_read 나 atomic_set 은 이에 - 해당되지 않습니다. 메모리 배리어가 필요해지는 흔한 예로는 어토믹 - 오퍼레이션을 사용해 레퍼런스 카운트를 수정하는 경우를 들 수 있습니다. - - 이것들은 또한 (set_bit 과 clear_bit 같은) 메모리 배리어를 내포하지 않는 - 어토믹 RMW bitop 함수들을 위해서도 사용될 수 있습니다. - - 한 예로, 객체 하나를 무효한 것으로 표시하고 그 객체의 레퍼런스 카운트를 - 감소시키는 다음 코드를 보세요: - - obj->dead = 1; - smp_mb__before_atomic(); - atomic_dec(&obj->ref_count); - - 이 코드는 객체의 업데이트된 death 마크가 레퍼런스 카운터 감소 동작 - *전에* 보일 것을 보장합니다. - - 더 많은 정보를 위해선 Documentation/atomic_{t,bitops}.txt 문서를 - 참고하세요. - - - (*) dma_wmb(); - (*) dma_rmb(); - (*) dma_mb(); - - 이것들은 CPU 와 DMA 가능한 디바이스에서 모두 액세스 가능한 공유 메모리의 - 읽기, 쓰기 작업들의 순서를 보장하기 위해 consistent memory 에서 사용하기 - 위한 것들입니다. - - 예를 들어, 디바이스와 메모리를 공유하며, 디스크립터 상태 값을 사용해 - 디스크립터가 디바이스에 속해 있는지 아니면 CPU 에 속해 있는지 표시하고, - 공지용 초인종(doorbell) 을 사용해 업데이트된 디스크립터가 디바이스에 사용 - 가능해졌음을 공지하는 디바이스 드라이버를 생각해 봅시다: - - if (desc->status != DEVICE_OWN) { - /* 디스크립터를 소유하기 전에는 데이터를 읽지 않음 */ - dma_rmb(); - - /* 데이터를 읽고 씀 */ - read_data = desc->data; - desc->data = write_data; - - /* 상태 업데이트 전 수정사항을 반영 */ - dma_wmb(); - - /* 소유권을 수정 */ - desc->status = DEVICE_OWN; - - /* 업데이트된 디스크립터의 디바이스에 공지 */ - writel(DESC_NOTIFY, doorbell); - } - - dma_rmb() 는 디스크립터로부터 데이터를 읽어오기 전에 디바이스가 소유권을 - 내려놓았을 것을 보장하고, dma_wmb() 는 디바이스가 자신이 소유권을 다시 - 가졌음을 보기 전에 디스크립터에 데이터가 쓰였을 것을 보장합니다. dma_mb() - 는 dma_rmb() 와 dma_wmb() 를 모두 내포합니다. 참고로, writel() 을 - 사용하면 캐시 일관성이 있는 메모리 (cache coherent memory) 쓰기가 MMIO - 영역에의 쓰기 전에 완료되었을 것을 보장하므로 writel() 앞에 wmb() 를 - 실행할 필요가 없음을 알아두시기 바랍니다. writel() 보다 비용이 저렴한 - writel_relaxed() 는 이런 보장을 제공하지 않으므로 여기선 사용되지 않아야 - 합니다. - - writel_relaxed() 와 같은 완화된 I/O 접근자들에 대한 자세한 내용을 위해서는 - "커널 I/O 배리어의 효과" 섹션을, consistent memory 에 대한 자세한 내용을 - 위해선 Documentation/core-api/dma-api.rst 문서를 참고하세요. - - (*) pmem_wmb(); - - 이것은 persistent memory 를 위한 것으로, persistent 저장소에 가해진 변경 - 사항이 플랫폼 연속성 도메인에 도달했을 것을 보장하기 위한 것입니다. - - 예를 들어, 임시적이지 않은 pmem 영역으로의 쓰기 후, 우리는 쓰기가 플랫폼 - 연속성 도메인에 도달했을 것을 보장하기 위해 pmem_wmb() 를 사용합니다. - 이는 쓰기가 뒤따르는 instruction 들이 유발하는 어떠한 데이터 액세스나 - 데이터 전송의 시작 전에 persistent 저장소를 업데이트 했을 것을 보장합니다. - 이는 wmb() 에 의해 이뤄지는 순서 규칙을 포함합니다. - - Persistent memory 에서의 로드를 위해선 현재의 읽기 메모리 배리어로도 읽기 - 순서를 보장하는데 충분합니다. - - (*) io_stop_wc(); - - 쓰기와 결합된 특성을 갖는 메모리 액세스의 경우 (예: ioremap_wc() 에 의해 - 리턴되는 것들), CPU 는 앞의 액세스들이 뒤따르는 것들과 병합되게끔 기다릴 - 수 있습니다. io_stop_wc() 는 그런 기다림이 성능에 영향을 끼칠 수 있을 때, - 이 매크로 앞의 쓰기-결합된 메모리 액세스들이 매크로 뒤의 것들과 병합되는 - 것을 방지하기 위해 사용될 수 있습니다. - -========================= -암묵적 커널 메모리 배리어 -========================= - -리눅스 커널의 일부 함수들은 메모리 배리어를 내장하고 있는데, 락(lock)과 -스케쥴링 관련 함수들이 대부분입니다. - -여기선 _최소한의_ 보장을 설명합니다; 특정 아키텍쳐에서는 이 설명보다 더 많은 -보장을 제공할 수도 있습니다만 해당 아키텍쳐에 종속적인 코드 외의 부분에서는 -그런 보장을 기대해선 안될겁니다. - - -락 ACQUISITION 함수 -------------------- - -리눅스 커널은 다양한 락 구성체를 가지고 있습니다: - - (*) 스핀 락 - (*) R/W 스핀 락 - (*) 뮤텍스 - (*) 세마포어 - (*) R/W 세마포어 - -각 구성체마다 모든 경우에 "ACQUIRE" 오퍼레이션과 "RELEASE" 오퍼레이션의 변종이 -존재합니다. 이 오퍼레이션들은 모두 적절한 배리어를 내포하고 있습니다: - - (1) ACQUIRE 오퍼레이션의 영향: - - ACQUIRE 뒤에서 요청된 메모리 오퍼레이션은 ACQUIRE 오퍼레이션이 완료된 - 뒤에 완료됩니다. - - ACQUIRE 앞에서 요청된 메모리 오퍼레이션은 ACQUIRE 오퍼레이션이 완료된 후에 - 완료될 수 있습니다. - - (2) RELEASE 오퍼레이션의 영향: - - RELEASE 앞에서 요청된 메모리 오퍼레이션은 RELEASE 오퍼레이션이 완료되기 - 전에 완료됩니다. - - RELEASE 뒤에서 요청된 메모리 오퍼레이션은 RELEASE 오퍼레이션 완료 전에 - 완료될 수 있습니다. - - (3) ACQUIRE vs ACQUIRE 영향: - - 어떤 ACQUIRE 오퍼레이션보다 앞에서 요청된 모든 ACQUIRE 오퍼레이션은 그 - ACQUIRE 오퍼레이션 전에 완료됩니다. - - (4) ACQUIRE vs RELEASE implication: - - 어떤 RELEASE 오퍼레이션보다 앞서 요청된 ACQUIRE 오퍼레이션은 그 RELEASE - 오퍼레이션보다 먼저 완료됩니다. - - (5) 실패한 조건적 ACQUIRE 영향: - - ACQUIRE 오퍼레이션의 일부 락(lock) 변종은 락이 곧바로 획득하기에는 - 불가능한 상태이거나 락이 획득 가능해지도록 기다리는 도중 시그널을 받거나 - 해서 실패할 수 있습니다. 실패한 락은 어떤 배리어도 내포하지 않습니다. - -[!] 참고: 락 ACQUIRE 와 RELEASE 가 단방향 배리어여서 나타나는 현상 중 하나는 -크리티컬 섹션 바깥의 인스트럭션의 영향이 크리티컬 섹션 내부로도 들어올 수 -있다는 것입니다. - -RELEASE 후에 요청되는 ACQUIRE 는 전체 메모리 배리어라 여겨지면 안되는데, -ACQUIRE 앞의 액세스가 ACQUIRE 후에 수행될 수 있고, RELEASE 후의 액세스가 -RELEASE 전에 수행될 수도 있으며, 그 두개의 액세스가 서로를 지나칠 수도 있기 -때문입니다: - - *A = a; - ACQUIRE M - RELEASE M - *B = b; - -는 다음과 같이 될 수도 있습니다: - - ACQUIRE M, STORE *B, STORE *A, RELEASE M - -ACQUIRE 와 RELEASE 가 락 획득과 해제라면, 그리고 락의 ACQUIRE 와 RELEASE 가 -같은 락 변수에 대한 것이라면, 해당 락을 쥐고 있지 않은 다른 CPU 의 시야에는 -이와 같은 재배치가 일어나는 것으로 보일 수 있습니다. 요약하자면, ACQUIRE 에 -이어 RELEASE 오퍼레이션을 순차적으로 실행하는 행위가 전체 메모리 배리어로 -생각되어선 -안됩니다-. - -비슷하게, 앞의 반대 케이스인 RELEASE 와 ACQUIRE 두개 오퍼레이션의 순차적 실행 -역시 전체 메모리 배리어를 내포하지 않습니다. 따라서, RELEASE, ACQUIRE 로 -규정되는 크리티컬 섹션의 CPU 수행은 RELEASE 와 ACQUIRE 를 가로지를 수 있으므로, -다음과 같은 코드는: - - *A = a; - RELEASE M - ACQUIRE N - *B = b; - -다음과 같이 수행될 수 있습니다: - - ACQUIRE N, STORE *B, STORE *A, RELEASE M - -이런 재배치는 데드락을 일으킬 수도 있을 것처럼 보일 수 있습니다. 하지만, 그런 -데드락의 조짐이 있다면 RELEASE 는 단순히 완료될 것이므로 데드락은 존재할 수 -없습니다. - - 이게 어떻게 올바른 동작을 할 수 있을까요? - - 우리가 이야기 하고 있는건 재배치를 하는 CPU 에 대한 이야기이지, - 컴파일러에 대한 것이 아니란 점이 핵심입니다. 컴파일러 (또는, 개발자) - 가 오퍼레이션들을 이렇게 재배치하면, 데드락이 일어날 수 -있습-니다. - - 하지만 CPU 가 오퍼레이션들을 재배치 했다는걸 생각해 보세요. 이 예에서, - 어셈블리 코드 상으로는 언락이 락을 앞서게 되어 있습니다. CPU 가 이를 - 재배치해서 뒤의 락 오퍼레이션을 먼저 실행하게 됩니다. 만약 데드락이 - 존재한다면, 이 락 오퍼레이션은 그저 스핀을 하며 계속해서 락을 - 시도합니다 (또는, 한참 후에겠지만, 잠듭니다). CPU 는 언젠가는 - (어셈블리 코드에서는 락을 앞서는) 언락 오퍼레이션을 실행하는데, 이 언락 - 오퍼레이션이 잠재적 데드락을 해결하고, 락 오퍼레이션도 뒤이어 성공하게 - 됩니다. - - 하지만 만약 락이 잠을 자는 타입이었다면요? 그런 경우에 코드는 - 스케쥴러로 들어가려 할 거고, 여기서 결국은 메모리 배리어를 만나게 - 되는데, 이 메모리 배리어는 앞의 언락 오퍼레이션이 완료되도록 만들고, - 데드락은 이번에도 해결됩니다. 잠을 자는 행위와 언락 사이의 경주 상황 - (race) 도 있을 수 있겠습니다만, 락 관련 기능들은 그런 경주 상황을 모든 - 경우에 제대로 해결할 수 있어야 합니다. - -락과 세마포어는 UP 컴파일된 시스템에서의 순서에 대해 보장을 하지 않기 때문에, -그런 상황에서 인터럽트 비활성화 오퍼레이션과 함께가 아니라면 어떤 일에도 - 특히 -I/O 액세스와 관련해서는 - 제대로 사용될 수 없을 겁니다. - -"CPU 간 ACQUIRING 배리어 효과" 섹션도 참고하시기 바랍니다. - - -예를 들어, 다음과 같은 코드를 생각해 봅시다: - - *A = a; - *B = b; - ACQUIRE - *C = c; - *D = d; - RELEASE - *E = e; - *F = f; - -여기선 다음의 이벤트 시퀀스가 생길 수 있습니다: - - ACQUIRE, {*F,*A}, *E, {*C,*D}, *B, RELEASE - - [+] {*F,*A} 는 조합된 액세스를 의미합니다. - -하지만 다음과 같은 건 불가능하죠: - - {*F,*A}, *B, ACQUIRE, *C, *D, RELEASE, *E - *A, *B, *C, ACQUIRE, *D, RELEASE, *E, *F - *A, *B, ACQUIRE, *C, RELEASE, *D, *E, *F - *B, ACQUIRE, *C, *D, RELEASE, {*F,*A}, *E - - - -인터럽트 비활성화 함수 ----------------------- - -인터럽트를 비활성화 하는 함수 (ACQUIRE 와 동일) 와 인터럽트를 활성화 하는 함수 -(RELEASE 와 동일) 는 컴파일러 배리어처럼만 동작합니다. 따라서, 별도의 메모리 -배리어나 I/O 배리어가 필요한 상황이라면 그 배리어들은 인터럽트 비활성화 함수 -외의 방법으로 제공되어야만 합니다. - - -슬립과 웨이크업 함수 --------------------- - -글로벌 데이터에 표시된 이벤트에 의해 프로세스를 잠에 빠트리는 것과 깨우는 것은 -해당 이벤트를 기다리는 태스크의 태스크 상태와 그 이벤트를 알리기 위해 사용되는 -글로벌 데이터, 두 데이터간의 상호작용으로 볼 수 있습니다. 이것이 옳은 순서대로 -일어남을 분명히 하기 위해, 프로세스를 잠에 들게 하는 기능과 깨우는 기능은 -몇가지 배리어를 내포합니다. - -먼저, 잠을 재우는 쪽은 일반적으로 다음과 같은 이벤트 시퀀스를 따릅니다: - - for (;;) { - set_current_state(TASK_UNINTERRUPTIBLE); - if (event_indicated) - break; - schedule(); - } - -set_current_state() 에 의해, 태스크 상태가 바뀐 후 범용 메모리 배리어가 -자동으로 삽입됩니다: - - CPU 1 - =============================== - set_current_state(); - smp_store_mb(); - STORE current->state - <범용 배리어> - LOAD event_indicated - -set_current_state() 는 다음의 것들로 감싸질 수도 있습니다: - - prepare_to_wait(); - prepare_to_wait_exclusive(); - -이것들 역시 상태를 설정한 후 범용 메모리 배리어를 삽입합니다. -앞의 전체 시퀀스는 다음과 같은 함수들로 한번에 수행 가능한데, 이것들은 모두 -올바른 장소에 메모리 배리어를 삽입합니다: - - wait_event(); - wait_event_interruptible(); - wait_event_interruptible_exclusive(); - wait_event_interruptible_timeout(); - wait_event_killable(); - wait_event_timeout(); - wait_on_bit(); - wait_on_bit_lock(); - - -두번째로, 깨우기를 수행하는 코드는 일반적으로 다음과 같을 겁니다: - - event_indicated = 1; - wake_up(&event_wait_queue); - -또는: - - event_indicated = 1; - wake_up_process(event_daemon); - -wake_up() 이 무언가를 깨우게 되면, 이 함수는 범용 메모리 배리어를 수행합니다. -이 함수가 아무것도 깨우지 않는다면 메모리 배리어는 수행될 수도, 수행되지 않을 -수도 있습니다; 이 경우에 메모리 배리어를 수행할 거라 오해해선 안됩니다. 이 -배리어는 태스크 상태가 접근되기 전에 수행되는데, 자세히 말하면 이 이벤트를 -알리기 위한 STORE 와 TASK_RUNNING 으로 상태를 쓰는 STORE 사이에 수행됩니다: - - CPU 1 (Sleeper) CPU 2 (Waker) - =============================== =============================== - set_current_state(); STORE event_indicated - smp_store_mb(); wake_up(); - STORE current->state ... - <범용 배리어> <범용 배리어> - LOAD event_indicated if ((LOAD task->state) & TASK_NORMAL) - STORE task->state - -여기서 "task" 는 깨어나지는 쓰레드이고 CPU 1 의 "current" 와 같습니다. - -반복하지만, wake_up() 이 무언가를 정말 깨운다면 범용 메모리 배리어가 수행될 -것이 보장되지만, 그렇지 않다면 그런 보장이 없습니다. 이걸 이해하기 위해, X 와 -Y 는 모두 0 으로 초기화 되어 있다는 가정 하에 아래의 이벤트 시퀀스를 생각해 -봅시다: - - CPU 1 CPU 2 - =============================== =============================== - X = 1; Y = 1; - smp_mb(); wake_up(); - LOAD Y LOAD X - -정말로 깨우기가 행해졌다면, 두 로드 중 (최소한) 하나는 1 을 보게 됩니다. -반면에, 실제 깨우기가 행해지지 않았다면, 두 로드 모두 0을 볼 수도 있습니다. - -wake_up_process() 는 항상 범용 메모리 배리어를 수행합니다. 이 배리어 역시 -태스크 상태가 접근되기 전에 수행됩니다. 특히, 앞의 예제 코드에서 wake_up() 이 -wake_up_process() 로 대체된다면 두 로드 중 하나는 1을 볼 것이 보장됩니다. - -사용 가능한 깨우기류 함수들로 다음과 같은 것들이 있습니다: - - complete(); - wake_up(); - wake_up_all(); - wake_up_bit(); - wake_up_interruptible(); - wake_up_interruptible_all(); - wake_up_interruptible_nr(); - wake_up_interruptible_poll(); - wake_up_interruptible_sync(); - wake_up_interruptible_sync_poll(); - wake_up_locked(); - wake_up_locked_poll(); - wake_up_nr(); - wake_up_poll(); - wake_up_process(); - -메모리 순서규칙 관점에서, 이 함수들은 모두 wake_up() 과 같거나 보다 강한 순서 -보장을 제공합니다. - -[!] 잠재우는 코드와 깨우는 코드에 내포되는 메모리 배리어들은 깨우기 전에 -이루어진 스토어를 잠재우는 코드가 set_current_state() 를 호출한 후에 행하는 -로드에 대해 순서를 맞추지 _않는다는_ 점을 기억하세요. 예를 들어, 잠재우는 -코드가 다음과 같고: - - set_current_state(TASK_INTERRUPTIBLE); - if (event_indicated) - break; - __set_current_state(TASK_RUNNING); - do_something(my_data); - -깨우는 코드는 다음과 같다면: - - my_data = value; - event_indicated = 1; - wake_up(&event_wait_queue); - -event_indecated 에의 변경이 잠재우는 코드에게 my_data 에의 변경 후에 이루어진 -것으로 인지될 것이라는 보장이 없습니다. 이런 경우에는 양쪽 코드 모두 각각의 -데이터 액세스 사이에 메모리 배리어를 직접 쳐야 합니다. 따라서 앞의 재우는 -코드는 다음과 같이: - - set_current_state(TASK_INTERRUPTIBLE); - if (event_indicated) { - smp_rmb(); - do_something(my_data); - } - -그리고 깨우는 코드는 다음과 같이 되어야 합니다: - - my_data = value; - smp_wmb(); - event_indicated = 1; - wake_up(&event_wait_queue); - - -그외의 함수들 -------------- - -그외의 배리어를 내포하는 함수들은 다음과 같습니다: - - (*) schedule() 과 그 유사한 것들이 완전한 메모리 배리어를 내포합니다. - - -============================== -CPU 간 ACQUIRING 배리어의 효과 -============================== - -SMP 시스템에서의 락 기능들은 더욱 강력한 형태의 배리어를 제공합니다: 이 -배리어는 동일한 락을 사용하는 다른 CPU 들의 메모리 액세스 순서에도 영향을 -끼칩니다. - - -ACQUIRE VS 메모리 액세스 ------------------------- - -다음의 예를 생각해 봅시다: 시스템은 두개의 스핀락 (M) 과 (Q), 그리고 세개의 CPU -를 가지고 있습니다; 여기에 다음의 이벤트 시퀀스가 발생합니다: - - CPU 1 CPU 2 - =============================== =============================== - WRITE_ONCE(*A, a); WRITE_ONCE(*E, e); - ACQUIRE M ACQUIRE Q - WRITE_ONCE(*B, b); WRITE_ONCE(*F, f); - WRITE_ONCE(*C, c); WRITE_ONCE(*G, g); - RELEASE M RELEASE Q - WRITE_ONCE(*D, d); WRITE_ONCE(*H, h); - -*A 로의 액세스부터 *H 로의 액세스까지가 어떤 순서로 CPU 3 에게 보여질지에 -대해서는 각 CPU 에서의 락 사용에 의해 내포되어 있는 제약을 제외하고는 어떤 -보장도 존재하지 않습니다. 예를 들어, CPU 3 에게 다음과 같은 순서로 보여지는 -것이 가능합니다: - - *E, ACQUIRE M, ACQUIRE Q, *G, *C, *F, *A, *B, RELEASE Q, *D, *H, RELEASE M - -하지만 다음과 같이 보이지는 않을 겁니다: - - *B, *C or *D preceding ACQUIRE M - *A, *B or *C following RELEASE M - *F, *G or *H preceding ACQUIRE Q - *E, *F or *G following RELEASE Q - - -========================= -메모리 배리어가 필요한 곳 -========================= - -설령 SMP 커널을 사용하더라도 싱글 쓰레드로 동작하는 코드는 올바르게 동작하는 -것으로 보여질 것이기 때문에, 평범한 시스템 운영중에 메모리 오퍼레이션 재배치는 -일반적으로 문제가 되지 않습니다. 하지만, 재배치가 문제가 _될 수 있는_ 네가지 -환경이 있습니다: - - (*) 프로세서간 상호 작용. - - (*) 어토믹 오퍼레이션. - - (*) 디바이스 액세스. - - (*) 인터럽트. - - -프로세서간 상호 작용 --------------------- - -두개 이상의 프로세서를 가진 시스템이 있다면, 시스템의 두개 이상의 CPU 는 동시에 -같은 데이터에 대한 작업을 할 수 있습니다. 이는 동기화 문제를 일으킬 수 있고, -이 문제를 해결하는 일반적 방법은 락을 사용하는 것입니다. 하지만, 락은 상당히 -비용이 비싸서 가능하면 락을 사용하지 않고 일을 처리하는 것이 낫습니다. 이런 -경우, 두 CPU 모두에 영향을 끼치는 오퍼레이션들은 오동작을 막기 위해 신중하게 -순서가 맞춰져야 합니다. - -예를 들어, R/W 세마포어의 느린 수행경로 (slow path) 를 생각해 봅시다. -세마포어를 위해 대기를 하는 하나의 프로세스가 자신의 스택 중 일부를 이 -세마포어의 대기 프로세스 리스트에 링크한 채로 있습니다: - - struct rw_semaphore { - ... - spinlock_t lock; - struct list_head waiters; - }; - - struct rwsem_waiter { - struct list_head list; - struct task_struct *task; - }; - -특정 대기 상태 프로세스를 깨우기 위해, up_read() 나 up_write() 함수는 다음과 -같은 일을 합니다: - - (1) 다음 대기 상태 프로세스 레코드는 어디있는지 알기 위해 이 대기 상태 - 프로세스 레코드의 next 포인터를 읽습니다; - - (2) 이 대기 상태 프로세스의 task 구조체로의 포인터를 읽습니다; - - (3) 이 대기 상태 프로세스가 세마포어를 획득했음을 알리기 위해 task - 포인터를 초기화 합니다; - - (4) 해당 태스크에 대해 wake_up_process() 를 호출합니다; 그리고 - - (5) 해당 대기 상태 프로세스의 task 구조체를 잡고 있던 레퍼런스를 해제합니다. - -달리 말하자면, 다음 이벤트 시퀀스를 수행해야 합니다: - - LOAD waiter->list.next; - LOAD waiter->task; - STORE waiter->task; - CALL wakeup - RELEASE task - -그리고 이 이벤트들이 다른 순서로 수행된다면, 오동작이 일어날 수 있습니다. - -한번 세마포어의 대기줄에 들어갔고 세마포어 락을 놓았다면, 해당 대기 프로세스는 -락을 다시는 잡지 않습니다; 대신 자신의 task 포인터가 초기화 되길 기다립니다. -그 레코드는 대기 프로세스의 스택에 있기 때문에, 리스트의 next 포인터가 읽혀지기 -_전에_ task 포인터가 지워진다면, 다른 CPU 는 해당 대기 프로세스를 시작해 버리고 -up*() 함수가 next 포인터를 읽기 전에 대기 프로세스의 스택을 마구 건드릴 수 -있습니다. - -그렇게 되면 위의 이벤트 시퀀스에 어떤 일이 일어나는지 생각해 보죠: - - CPU 1 CPU 2 - =============================== =============================== - down_xxx() - Queue waiter - Sleep - up_yyy() - LOAD waiter->task; - STORE waiter->task; - Woken up by other event - <preempt> - Resume processing - down_xxx() returns - call foo() - foo() clobbers *waiter - </preempt> - LOAD waiter->list.next; - --- OOPS --- - -이 문제는 세마포어 락의 사용으로 해결될 수도 있겠지만, 그렇게 되면 깨어난 후에 -down_xxx() 함수가 불필요하게 스핀락을 또다시 얻어야만 합니다. - -이 문제를 해결하는 방법은 범용 SMP 메모리 배리어를 추가하는 겁니다: - - LOAD waiter->list.next; - LOAD waiter->task; - smp_mb(); - STORE waiter->task; - CALL wakeup - RELEASE task - -이 경우에, 배리어는 시스템의 나머지 CPU 들에게 모든 배리어 앞의 메모리 액세스가 -배리어 뒤의 메모리 액세스보다 앞서 일어난 것으로 보이게 만듭니다. 배리어 앞의 -메모리 액세스들이 배리어 명령 자체가 완료되는 시점까지 완료된다고는 보장하지 -_않습니다_. - -(이게 문제가 되지 않을) 단일 프로세서 시스템에서 smp_mb() 는 실제로는 그저 -컴파일러가 CPU 안에서의 순서를 바꾸거나 하지 않고 주어진 순서대로 명령을 -내리도록 하는 컴파일러 배리어일 뿐입니다. 오직 하나의 CPU 만 있으니, CPU 의 -의존성 순서 로직이 그 외의 모든것을 알아서 처리할 겁니다. - - -어토믹 오퍼레이션 ------------------ - -어토믹 오퍼레이션은 기술적으로 프로세서간 상호작용으로 분류되며 그 중 일부는 -전체 메모리 배리어를 내포하고 또 일부는 내포하지 않지만, 커널에서 상당히 -의존적으로 사용하는 기능 중 하나입니다. - -더 많은 내용을 위해선 Documentation/atomic_t.txt 를 참고하세요. - - -디바이스 액세스 ---------------- - -많은 디바이스가 메모리 매핑 기법으로 제어될 수 있는데, 그렇게 제어되는 -디바이스는 CPU 에는 단지 특정 메모리 영역의 집합처럼 보이게 됩니다. 드라이버는 -그런 디바이스를 제어하기 위해 정확히 올바른 순서로 올바른 메모리 액세스를 -만들어야 합니다. - -하지만, 액세스들을 재배치 하거나 조합하거나 병합하는게 더 효율적이라 판단하는 -영리한 CPU 나 컴파일러들을 사용하면 드라이버 코드의 조심스럽게 순서 맞춰진 -액세스들이 디바이스에는 요청된 순서대로 도착하지 못하게 할 수 있는 - 디바이스가 -오동작을 하게 할 - 잠재적 문제가 생길 수 있습니다. - -리눅스 커널 내부에서, I/O 는 어떻게 액세스들을 적절히 순차적이게 만들 수 있는지 -알고 있는, - inb() 나 writel() 과 같은 - 적절한 액세스 루틴을 통해 이루어져야만 -합니다. 이것들은 대부분의 경우에는 명시적 메모리 배리어 와 함께 사용될 필요가 -없습니다만, 완화된 메모리 액세스 속성으로 I/O 메모리 윈도우로의 참조를 위해 -액세스 함수가 사용된다면 순서를 강제하기 위해 _mandatory_ 메모리 배리어가 -필요합니다. - -더 많은 정보를 위해선 Documentation/driver-api/device-io.rst 를 참고하십시오. - - -인터럽트 --------- - -드라이버는 자신의 인터럽트 서비스 루틴에 의해 인터럽트 당할 수 있기 때문에 -드라이버의 이 두 부분은 서로의 디바이스 제어 또는 액세스 부분과 상호 간섭할 수 -있습니다. - -스스로에게 인터럽트 당하는 걸 불가능하게 하고, 드라이버의 크리티컬한 -오퍼레이션들을 모두 인터럽트가 불가능하게 된 영역에 집어넣거나 하는 방법 (락의 -한 형태) 으로 이런 상호 간섭을 - 최소한 부분적으로라도 - 줄일 수 있습니다. -드라이버의 인터럽트 루틴이 실행 중인 동안, 해당 드라이버의 코어는 같은 CPU 에서 -수행되지 않을 것이며, 현재의 인터럽트가 처리되는 중에는 또다시 인터럽트가 -일어나지 못하도록 되어 있으니 인터럽트 핸들러는 그에 대해서는 락을 잡지 않아도 -됩니다. - -하지만, 어드레스 레지스터와 데이터 레지스터를 갖는 이더넷 카드를 다루는 -드라이버를 생각해 봅시다. 만약 이 드라이버의 코어가 인터럽트를 비활성화시킨 -채로 이더넷 카드와 대화하고 드라이버의 인터럽트 핸들러가 호출되었다면: - - LOCAL IRQ DISABLE - writew(ADDR, 3); - writew(DATA, y); - LOCAL IRQ ENABLE - <interrupt> - writew(ADDR, 4); - q = readw(DATA); - </interrupt> - -만약 순서 규칙이 충분히 완화되어 있다면 데이터 레지스터에의 스토어는 어드레스 -레지스터에 두번째로 행해지는 스토어 뒤에 일어날 수도 있습니다: - - STORE *ADDR = 3, STORE *ADDR = 4, STORE *DATA = y, q = LOAD *DATA - - -만약 순서 규칙이 충분히 완화되어 있고 묵시적으로든 명시적으로든 배리어가 -사용되지 않았다면 인터럽트 비활성화 섹션에서 일어난 액세스가 바깥으로 새어서 -인터럽트 내에서 일어난 액세스와 섞일 수 있다고 - 그리고 그 반대도 - 가정해야만 -합니다. - -그런 영역 안에서 일어나는 I/O 액세스는 묵시적 I/O 배리어를 형성하는, 엄격한 -순서 규칙의 I/O 레지스터로의 로드 오퍼레이션을 포함하기 때문에 일반적으로는 -문제가 되지 않습니다. - - -하나의 인터럽트 루틴과 별도의 CPU 에서 수행중이며 서로 통신을 하는 두 루틴 -사이에도 비슷한 상황이 일어날 수 있습니다. 만약 그런 경우가 발생할 가능성이 -있다면, 순서를 보장하기 위해 인터럽트 비활성화 락이 사용되어져야만 합니다. - - -====================== -커널 I/O 배리어의 효과 -====================== - -I/O 액세스를 통한 주변장치와의 통신은 아키텍쳐와 기기에 매우 종속적입니다. -따라서, 본질적으로 이식성이 없는 드라이버는 가능한 가장 적은 오버헤드로 -동기화를 하기 위해 각자의 타겟 시스템의 특정 동작에 의존할 겁니다. 다양한 -아키텍쳐와 버스 구현에 이식성을 가지려 하는 드라이버를 위해, 커널은 다양한 -정도의 순서 보장을 제공하는 일련의 액세스 함수를 제공합니다. - - (*) readX(), writeX(): - - readX() 와 writeX() MMIO 액세스 함수는 접근되는 주변장치로의 포인터를 - __iomem * 패러미터로 받습니다. 디폴트 I/O 기능으로 매핑되는 포인터 - (예: ioremap() 으로 반환되는 것) 의 순서 보장은 다음과 같습니다: - - 1. 같은 주변장치로의 모든 readX() 와 writeX() 액세스는 각자에 대해 - 순서지어집니다. 이는 같은 CPU 쓰레드에 의한 특정 디바이스로의 MMIO - 레지스터 액세스가 프로그램 순서대로 도착할 것을 보장합니다. - - 2. 한 스핀락을 잡은 CPU 쓰레드에 의한 writeX() 는 같은 스핀락을 나중에 - 잡은 다른 CPU 쓰레드에 의해 같은 주변장치를 향해 호출된 writeX() - 앞으로 순서지어집니다. 이는 스핀락을 잡은 채 특정 디바이스를 향해 - 호출된 MMIO 레지스터 쓰기는 해당 락의 획득에 일관적인 순서로 도달할 - 것을 보장합니다. - - 3. 특정 주변장치를 향한 특정 CPU 쓰레드의 writeX() 는 먼저 해당 - 쓰레드로 전파되는, 또는 해당 쓰레드에 의해 요청된 모든 앞선 메모리 - 쓰기가 완료되기 전까지 먼저 기다립니다. 이는 dma_alloc_coherent() - 를 통해 할당된 전송용 DMA 버퍼로의 해당 CPU 의 쓰기가 이 CPU 가 이 - 전송을 시작시키기 위해 MMIO 컨트롤 레지스터에 쓰기를 할 때 DMA - 엔진에 보여질 것을 보장합니다. - - 4. 특정 CPU 쓰레드에 의한 주변장치로의 readX() 는 같은 쓰레드에 의한 - 모든 뒤따르는 메모리 읽기가 시작되기 전에 완료됩니다. 이는 - dma_alloc_coherent() 를 통해 할당된 수신용 DMA 버퍼로부터의 CPU 의 - 읽기는 이 DMA 수신의 완료를 표시하는 DMA 엔진의 MMIO 상태 레지스터 - 읽기 후에는 오염된 데이터를 읽지 않을 것을 보장합니다. - - 5. CPU 에 의한 주변장치로의 readX() 는 모든 뒤따르는 delay() 루프가 - 수행을 시작하기 전에 완료됩니다. 이는 CPU 의 특정 - 주변장치로의 두개의 MMIO 레지스터 쓰기가 행해지는데 첫번째 쓰기가 - readX() 를 통해 곧바로 읽어졌고 이어 두번째 writeX() 전에 udelay(1) - 이 호출되었다면 이 두개의 쓰기는 최소 1us 의 간격을 두고 행해질 것을 - 보장합니다: - - writel(42, DEVICE_REGISTER_0); // 디바이스에 도착함... - readl(DEVICE_REGISTER_0); - udelay(1); - writel(42, DEVICE_REGISTER_1); // ...이것보다 최소 1us 전에. - - 디폴트가 아닌 기능을 통해 얻어지는 __iomem 포인터 (예: ioremap_wc() 를 - 통해 리턴되는 것) 의 순서 속성은 실제 아키텍쳐에 의존적이어서 이런 - 종류의 매핑으로의 액세스는 앞서 설명된 보장사항에 의존할 수 없습니다. - - (*) readX_relaxed(), writeX_relaxed() - - 이것들은 readX() 와 writeX() 랑 비슷하지만, 더 완화된 메모리 순서 - 보장을 제공합니다. 구체적으로, 이것들은 일반적 메모리 액세스나 delay() - 루프 (예:앞의 2-5 항목) 에 대해 순서를 보장하지 않습니다만 디폴트 I/O - 기능으로 매핑된 __iomem 포인터에 대해 동작할 때, 같은 CPU 쓰레드에 의한 - 같은 주변장치로의 액세스에는 순서가 맞춰질 것이 보장됩니다. - - (*) readsX(), writesX(): - - readsX() 와 writesX() MMIO 액세스 함수는 DMA 를 수행하는데 적절치 않은, - 주변장치 내의 메모리 매핑된 레지스터 기반 FIFO 로의 액세스를 위해 - 설계되었습니다. 따라서, 이 기능들은 앞서 설명된 readX_relaxed() 와 - writeX_relaxed() 의 순서 보장만을 제공합니다. - - (*) inX(), outX(): - - inX() 와 outX() 액세스 함수는 일부 아키텍쳐 (특히 x86) 에서는 특수한 - 명령어를 필요로 하며 포트에 매핑되는, 과거의 유산인 I/O 주변장치로의 - 접근을 위해 만들어졌습니다. - - 많은 CPU 아키텍쳐가 결국은 이런 주변장치를 내부의 가상 메모리 매핑을 - 통해 접근하기 때문에, inX() 와 outX() 가 제공하는 이식성 있는 순서 - 보장은 디폴트 I/O 기능을 통한 매핑을 접근할 때의 readX() 와 writeX() 에 - 의해 제공되는 것과 각각 동일합니다. - - 디바이스 드라이버는 outX() 가 리턴하기 전에 해당 I/O 주변장치로부터의 - 완료 응답을 기다리는 쓰기 트랜잭션을 만들어 낸다고 기대할 수도 - 있습니다. 이는 모든 아키텍쳐에서 보장되지는 않고, 따라서 이식성 있는 - 순서 규칙의 일부분이 아닙니다. - - (*) insX(), outsX(): - - 앞에서와 같이, insX() 와 outsX() 액세스 함수는 디폴트 I/O 기능을 통한 - 매핑을 접근할 때 각각 readX() 와 writeX() 와 같은 순서 보장을 - 제공합니다. - - (*) ioreadX(), iowriteX() - - 이것들은 inX()/outX() 나 readX()/writeX() 처럼 실제로 수행하는 액세스의 - 종류에 따라 적절하게 수행될 것입니다. - -String 액세스 함수 (insX(), outsX(), readsX() 그리고 writesX()) 의 예외를 -제외하고는, 앞의 모든 것이 아랫단의 주변장치가 little-endian 이라 가정하며, -따라서 big-endian 아키텍쳐에서는 byte-swapping 오퍼레이션을 수행합니다. - - -=================================== -가정되는 가장 완화된 실행 순서 모델 -=================================== - -컨셉적으로 CPU 는 주어진 프로그램에 대해 프로그램 그 자체에는 인과성 (program -causality) 을 지키는 것처럼 보이게 하지만 일반적으로는 순서를 거의 지켜주지 -않는다고 가정되어야만 합니다. (i386 이나 x86_64 같은) 일부 CPU 들은 코드 -재배치에 (powerpc 나 frv 와 같은) 다른 것들에 비해 강한 제약을 갖지만, 아키텍쳐 -종속적 코드 이외의 코드에서는 순서에 대한 제약이 가장 완화된 경우 (DEC Alpha) -를 가정해야 합니다. - -이 말은, CPU 에게 주어지는 인스트럭션 스트림 내의 한 인스트럭션이 앞의 -인스트럭션에 종속적이라면 앞의 인스트럭션은 뒤의 종속적 인스트럭션이 실행되기 -전에 완료[*]될 수 있어야 한다는 제약 (달리 말해서, 인과성이 지켜지는 것으로 -보이게 함) 외에는 자신이 원하는 순서대로 - 심지어 병렬적으로도 - 그 스트림을 -실행할 수 있음을 의미합니다 - - [*] 일부 인스트럭션은 하나 이상의 영향 - 조건 코드를 바꾼다던지, 레지스터나 - 메모리를 바꾼다던지 - 을 만들어내며, 다른 인스트럭션은 다른 효과에 - 종속적일 수 있습니다. - -CPU 는 최종적으로 아무 효과도 만들지 않는 인스트럭션 시퀀스는 없애버릴 수도 -있습니다. 예를 들어, 만약 두개의 연속되는 인스트럭션이 둘 다 같은 레지스터에 -직접적인 값 (immediate value) 을 집어넣는다면, 첫번째 인스트럭션은 버려질 수도 -있습니다. - - -비슷하게, 컴파일러 역시 프로그램의 인과성만 지켜준다면 인스트럭션 스트림을 -자신이 보기에 올바르다 생각되는대로 재배치 할 수 있습니다. - - -=============== -CPU 캐시의 영향 -=============== - -캐시된 메모리 오퍼레이션들이 시스템 전체에 어떻게 인지되는지는 CPU 와 메모리 -사이에 존재하는 캐시들, 그리고 시스템 상태의 일관성을 관리하는 메모리 일관성 -시스템에 상당 부분 영향을 받습니다. - -한 CPU 가 시스템의 다른 부분들과 캐시를 통해 상호작용한다면, 메모리 시스템은 -CPU 의 캐시들을 포함해야 하며, CPU 와 CPU 자신의 캐시 사이에서의 동작을 위한 -메모리 배리어를 가져야 합니다. (메모리 배리어는 논리적으로는 다음 그림의 -점선에서 동작합니다): - - <--- CPU ---> : <----------- Memory -----------> - : - +--------+ +--------+ : +--------+ +-----------+ - | | | | : | | | | +--------+ - | CPU | | Memory | : | CPU | | | | | - | Core |--->| Access |----->| Cache |<-->| | | | - | | | Queue | : | | | |--->| Memory | - | | | | : | | | | | | - +--------+ +--------+ : +--------+ | | | | - : | Cache | +--------+ - : | Coherency | - : | Mechanism | +--------+ - +--------+ +--------+ : +--------+ | | | | - | | | | : | | | | | | - | CPU | | Memory | : | CPU | | |--->| Device | - | Core |--->| Access |----->| Cache |<-->| | | | - | | | Queue | : | | | | | | - | | | | : | | | | +--------+ - +--------+ +--------+ : +--------+ +-----------+ - : - : - -특정 로드나 스토어는 해당 오퍼레이션을 요청한 CPU 의 캐시 내에서 동작을 완료할 -수도 있기 때문에 해당 CPU 의 바깥에는 보이지 않을 수 있지만, 다른 CPU 가 관심을 -갖는다면 캐시 일관성 메커니즘이 해당 캐시라인을 해당 CPU 에게 전달하고, 해당 -메모리 영역에 대한 오퍼레이션이 발생할 때마다 그 영향을 전파시키기 때문에, 해당 -오퍼레이션은 메모리에 실제로 액세스를 한것처럼 나타날 것입니다. - -CPU 코어는 프로그램의 인과성이 유지된다고만 여겨진다면 인스트럭션들을 어떤 -순서로든 재배치해서 수행할 수 있습니다. 일부 인스트럭션들은 로드나 스토어 -오퍼레이션을 만드는데 이 오퍼레이션들은 이후 수행될 메모리 액세스 큐에 들어가게 -됩니다. 코어는 이 오퍼레이션들을 해당 큐에 어떤 순서로든 원하는대로 넣을 수 -있고, 다른 인스트럭션의 완료를 기다리도록 강제되기 전까지는 수행을 계속합니다. - -메모리 배리어가 하는 일은 CPU 쪽에서 메모리 쪽으로 넘어가는 액세스들의 순서, -그리고 그 액세스의 결과가 시스템의 다른 관찰자들에게 인지되는 순서를 제어하는 -것입니다. - -[!] CPU 들은 항상 그들 자신의 로드와 스토어는 프로그램 순서대로 일어난 것으로 -보기 때문에, 주어진 CPU 내에서는 메모리 배리어를 사용할 필요가 _없습니다_. - -[!] MMIO 나 다른 디바이스 액세스들은 캐시 시스템을 우회할 수도 있습니다. 우회 -여부는 디바이스가 액세스 되는 메모리 윈도우의 특성에 의해 결정될 수도 있고, CPU -가 가지고 있을 수 있는 특수한 디바이스 통신 인스트럭션의 사용에 의해서 결정될 -수도 있습니다. - - -캐시 일관성 VS DMA ------------------- - -모든 시스템이 DMA 를 하는 디바이스에 대해서까지 캐시 일관성을 유지하지는 -않습니다. 그런 경우, DMA 를 시도하는 디바이스는 RAM 으로부터 잘못된 데이터를 -읽을 수 있는데, 더티 캐시 라인이 CPU 의 캐시에 머무르고 있고, 바뀐 값이 아직 -RAM 에 써지지 않았을 수 있기 때문입니다. 이 문제를 해결하기 위해선, 커널의 -적절한 부분에서 각 CPU 캐시의 문제되는 비트들을 플러시 (flush) 시켜야만 합니다 -(그리고 그것들을 무효화 - invalidation - 시킬 수도 있겠죠). - -또한, 디바이스에 의해 RAM 에 DMA 로 쓰여진 값은 디바이스가 쓰기를 완료한 후에 -CPU 의 캐시에서 RAM 으로 쓰여지는 더티 캐시 라인에 의해 덮어써질 수도 있고, CPU -의 캐시에 존재하는 캐시 라인이 해당 캐시에서 삭제되고 다시 값을 읽어들이기 -전까지는 RAM 이 업데이트 되었다는 사실 자체가 숨겨져 버릴 수도 있습니다. 이 -문제를 해결하기 위해선, 커널의 적절한 부분에서 각 CPU 의 캐시 안의 문제가 되는 -비트들을 무효화 시켜야 합니다. - -캐시 관리에 대한 더 많은 정보를 위해선 Documentation/core-api/cachetlb.rst 를 -참고하세요. - - -캐시 일관성 VS MMIO -------------------- - -Memory mapped I/O 는 일반적으로 CPU 의 메모리 공간 내의 한 윈도우의 특정 부분 -내의 메모리 지역에 이루어지는데, 이 윈도우는 일반적인, RAM 으로 향하는 -윈도우와는 다른 특성을 갖습니다. - -그런 특성 가운데 하나는, 일반적으로 그런 액세스는 캐시를 완전히 우회하고 -디바이스 버스로 곧바로 향한다는 것입니다. 이 말은 MMIO 액세스는 먼저 -시작되어서 캐시에서 완료된 메모리 액세스를 추월할 수 있다는 뜻입니다. 이런 -경우엔 메모리 배리어만으로는 충분치 않고, 만약 캐시된 메모리 쓰기 오퍼레이션과 -MMIO 액세스가 어떤 방식으로든 의존적이라면 해당 캐시는 두 오퍼레이션 사이에 -비워져(flush)야만 합니다. - - -====================== -CPU 들이 저지르는 일들 -====================== - -프로그래머는 CPU 가 메모리 오퍼레이션들을 정확히 요청한대로 수행해 줄 것이라고 -생각하는데, 예를 들어 다음과 같은 코드를 CPU 에게 넘긴다면: - - a = READ_ONCE(*A); - WRITE_ONCE(*B, b); - c = READ_ONCE(*C); - d = READ_ONCE(*D); - WRITE_ONCE(*E, e); - -CPU 는 다음 인스트럭션을 처리하기 전에 현재의 인스트럭션을 위한 메모리 -오퍼레이션을 완료할 것이라 생각하고, 따라서 시스템 외부에서 관찰하기에도 정해진 -순서대로 오퍼레이션이 수행될 것으로 예상합니다: - - LOAD *A, STORE *B, LOAD *C, LOAD *D, STORE *E. - - -당연하지만, 실제로는 훨씬 엉망입니다. 많은 CPU 와 컴파일러에서 앞의 가정은 -성립하지 못하는데 그 이유는 다음과 같습니다: - - (*) 로드 오퍼레이션들은 실행을 계속 해나가기 위해 곧바로 완료될 필요가 있는 - 경우가 많은 반면, 스토어 오퍼레이션들은 종종 별다른 문제 없이 유예될 수 - 있습니다; - - (*) 로드 오퍼레이션들은 예측적으로 수행될 수 있으며, 필요없는 로드였다고 - 증명된 예측적 로드의 결과는 버려집니다; - - (*) 로드 오퍼레이션들은 예측적으로 수행될 수 있으므로, 예상된 이벤트의 - 시퀀스와 다른 시간에 로드가 이뤄질 수 있습니다; - - (*) 메모리 액세스 순서는 CPU 버스와 캐시를 좀 더 잘 사용할 수 있도록 재배치 - 될 수 있습니다; - - (*) 로드와 스토어는 인접한 위치에의 액세스들을 일괄적으로 처리할 수 있는 - 메모리나 I/O 하드웨어 (메모리와 PCI 디바이스 둘 다 이게 가능할 수 - 있습니다) 에 대해 요청되는 경우, 개별 오퍼레이션을 위한 트랜잭션 설정 - 비용을 아끼기 위해 조합되어 실행될 수 있습니다; 그리고 - - (*) 해당 CPU 의 데이터 캐시가 순서에 영향을 끼칠 수도 있고, 캐시 일관성 - 메커니즘이 - 스토어가 실제로 캐시에 도달한다면 - 이 문제를 완화시킬 수는 - 있지만 이 일관성 관리가 다른 CPU 들에도 같은 순서로 전달된다는 보장은 - 없습니다. - -따라서, 앞의 코드에 대해 다른 CPU 가 보는 결과는 다음과 같을 수 있습니다: - - LOAD *A, ..., LOAD {*C,*D}, STORE *E, STORE *B - - ("LOAD {*C,*D}" 는 조합된 로드입니다) - - -하지만, CPU 는 스스로는 일관적일 것을 보장합니다: CPU _자신_ 의 액세스들은 -자신에게는 메모리 배리어가 없음에도 불구하고 정확히 순서 세워진 것으로 보여질 -것입니다. 예를 들어 다음의 코드가 주어졌다면: - - U = READ_ONCE(*A); - WRITE_ONCE(*A, V); - WRITE_ONCE(*A, W); - X = READ_ONCE(*A); - WRITE_ONCE(*A, Y); - Z = READ_ONCE(*A); - -그리고 외부의 영향에 의한 간섭이 없다고 가정하면, 최종 결과는 다음과 같이 -나타날 것이라고 예상될 수 있습니다: - - U == *A 의 최초 값 - X == W - Z == Y - *A == Y - -앞의 코드는 CPU 가 다음의 메모리 액세스 시퀀스를 만들도록 할겁니다: - - U=LOAD *A, STORE *A=V, STORE *A=W, X=LOAD *A, STORE *A=Y, Z=LOAD *A - -하지만, 별다른 개입이 없고 프로그램의 시야에 이 세상이 여전히 일관적이라고 -보인다는 보장만 지켜진다면 이 시퀀스는 어떤 조합으로든 재구성될 수 있으며, 각 -액세스들은 합쳐지거나 버려질 수 있습니다. 일부 아키텍쳐에서 CPU 는 같은 위치에 -대한 연속적인 로드 오퍼레이션들을 재배치 할 수 있기 때문에 앞의 예에서의 -READ_ONCE() 와 WRITE_ONCE() 는 반드시 존재해야 함을 알아두세요. 그런 종류의 -아키텍쳐에서 READ_ONCE() 와 WRITE_ONCE() 는 이 문제를 막기 위해 필요한 일을 -뭐가 됐든지 하게 되는데, 예를 들어 Itanium 에서는 READ_ONCE() 와 WRITE_ONCE() -가 사용하는 volatile 캐스팅은 GCC 가 그런 재배치를 방지하는 특수 인스트럭션인 -ld.acq 와 stl.rel 인스트럭션을 각각 만들어 내도록 합니다. - -컴파일러 역시 이 시퀀스의 액세스들을 CPU 가 보기도 전에 합치거나 버리거나 뒤로 -미뤄버릴 수 있습니다. - -예를 들어: - - *A = V; - *A = W; - -는 다음과 같이 변형될 수 있습니다: - - *A = W; - -따라서, 쓰기 배리어나 WRITE_ONCE() 가 없다면 *A 로의 V 값의 저장의 효과는 -사라진다고 가정될 수 있습니다. 비슷하게: - - *A = Y; - Z = *A; - -는, 메모리 배리어나 READ_ONCE() 와 WRITE_ONCE() 없이는 다음과 같이 변형될 수 -있습니다: - - *A = Y; - Z = Y; - -그리고 이 LOAD 오퍼레이션은 CPU 바깥에는 아예 보이지 않습니다. - - -그리고, ALPHA 가 있다 ---------------------- - -DEC Alpha CPU 는 가장 완화된 메모리 순서의 CPU 중 하나입니다. 뿐만 아니라, -Alpha CPU 의 일부 버전은 분할된 데이터 캐시를 가지고 있어서, 의미적으로 -관계되어 있는 두개의 캐시 라인이 서로 다른 시간에 업데이트 되는게 가능합니다. -이게 주소 의존성 배리어가 정말 필요해지는 부분인데, 주소 의존성 배리어는 메모리 -일관성 시스템과 함께 두개의 캐시를 동기화 시켜서, 포인터 변경과 새로운 데이터의 -발견을 올바른 순서로 일어나게 하기 때문입니다. - -리눅스 커널의 메모리 배리어 모델은 Alpha 에 기초해서 정의되었습니다만, v4.15 -부터는 Alpha 용 READ_ONCE() 코드 내에 smp_mb() 가 추가되어서 메모리 모델로의 -Alpha 의 영향력이 크게 줄어들었습니다. - - -가상 머신 게스트 ----------------- - -가상 머신에서 동작하는 게스트들은 게스트 자체는 SMP 지원 없이 컴파일 되었다 -해도 SMP 영향을 받을 수 있습니다. 이건 UP 커널을 사용하면서 SMP 호스트와 -결부되어 발생하는 부작용입니다. 이 경우에는 mandatory 배리어를 사용해서 문제를 -해결할 수 있겠지만 그런 해결은 대부분의 경우 최적의 해결책이 아닙니다. - -이 문제를 완벽하게 해결하기 위해, 로우 레벨의 virt_mb() 등의 매크로를 사용할 수 -있습니다. 이것들은 SMP 가 활성화 되어 있다면 smp_mb() 등과 동일한 효과를 -갖습니다만, SMP 와 SMP 아닌 시스템 모두에 대해 동일한 코드를 만들어냅니다. -예를 들어, 가상 머신 게스트들은 (SMP 일 수 있는) 호스트와 동기화를 할 때에는 -smp_mb() 가 아니라 virt_mb() 를 사용해야 합니다. - -이것들은 smp_mb() 류의 것들과 모든 부분에서 동일하며, 특히, MMIO 의 영향에 -대해서는 간여하지 않습니다: MMIO 의 영향을 제어하려면, mandatory 배리어를 -사용하시기 바랍니다. - - -======= -사용 예 -======= - -순환식 버퍼 ------------ - -메모리 배리어는 순환식 버퍼를 생성자(producer)와 소비자(consumer) 사이의 -동기화에 락을 사용하지 않고 구현하는데에 사용될 수 있습니다. 더 자세한 내용을 -위해선 다음을 참고하세요: - - Documentation/core-api/circular-buffers.rst - - -========= -참고 문헌 -========= - -Alpha AXP Architecture Reference Manual, Second Edition (Sites & Witek, -Digital Press) - Chapter 5.2: Physical Address Space Characteristics - Chapter 5.4: Caches and Write Buffers - Chapter 5.5: Data Sharing - Chapter 5.6: Read/Write Ordering - -AMD64 Architecture Programmer's Manual Volume 2: System Programming - Chapter 7.1: Memory-Access Ordering - Chapter 7.4: Buffering and Combining Memory Writes - -ARM Architecture Reference Manual (ARMv8, for ARMv8-A architecture profile) - Chapter B2: The AArch64 Application Level Memory Model - -IA-32 Intel Architecture Software Developer's Manual, Volume 3: -System Programming Guide - Chapter 7.1: Locked Atomic Operations - Chapter 7.2: Memory Ordering - Chapter 7.4: Serializing Instructions - -The SPARC Architecture Manual, Version 9 - Chapter 8: Memory Models - Appendix D: Formal Specification of the Memory Models - Appendix J: Programming with the Memory Models - -Storage in the PowerPC (Stone and Fitzgerald) - -UltraSPARC Programmer Reference Manual - Chapter 5: Memory Accesses and Cacheability - Chapter 15: Sparc-V9 Memory Models - -UltraSPARC III Cu User's Manual - Chapter 9: Memory Models - -UltraSPARC IIIi Processor User's Manual - Chapter 8: Memory Models - -UltraSPARC Architecture 2005 - Chapter 9: Memory - Appendix D: Formal Specifications of the Memory Models - -UltraSPARC T1 Supplement to the UltraSPARC Architecture 2005 - Chapter 8: Memory Models - Appendix F: Caches and Cache Coherency - -Solaris Internals, Core Kernel Architecture, p63-68: - Chapter 3.3: Hardware Considerations for Locks and - Synchronization - -Unix Systems for Modern Architectures, Symmetric Multiprocessing and Caching -for Kernel Programmers: - Chapter 13: Other Memory Models - -Intel Itanium Architecture Software Developer's Manual: Volume 1: - Section 2.6: Speculation - Section 4.4: Memory Access diff --git a/Documentation/translations/sp_SP/process/adding-syscalls.rst b/Documentation/translations/sp_SP/process/adding-syscalls.rst index f21504c612b2..5f7445b62637 100644 --- a/Documentation/translations/sp_SP/process/adding-syscalls.rst +++ b/Documentation/translations/sp_SP/process/adding-syscalls.rst @@ -128,7 +128,7 @@ manipulador de ese objeto -- no invente un nuevo tipo de objeto manipulador userspace cuando el kernel ya tiene mecanismos y semánticas bien definidas para usar los descriptores de archivos. -Si su nueva llamada a sistema :manpage:`xyzzy(2)` retorna un nuevo +Si su nueva llamada a sistema xyzzy(2) retorna un nuevo descriptor de archivo, entonces el argumento flag debe incluir un valor que sea equivalente a definir ``O_CLOEXEC`` en el nuevo FD. Esto hace posible al userspace acortar la brecha de tiempo entre ``xyzzy()`` y la llamada a @@ -145,12 +145,12 @@ archivo listo para leer o escribir es la forma normal para que el kernel indique al espacio de usuario que un evento ha ocurrido en el correspondiente objeto del kernel. -Si su nueva llamada de sistema :manpage:`xyzzy(2)` involucra algún nombre +Si su nueva llamada de sistema xyzzy(2) involucra algún nombre de archivo como argumento:: int sys_xyzzy(const char __user *path, ..., unsigned int flags); -debería considerar también si una versión :manpage:`xyzzyat(2)` es mas +debería considerar también si una versión xyzzyat(2) es mas apropiada:: int sys_xyzzyat(int dfd, const char __user *path, ..., unsigned int flags); @@ -158,7 +158,7 @@ apropiada:: Esto permite más flexibilidad en como el userspace especifica el archivo en cuestión; en particular esto permite al userspace pedir la funcionalidad a un descriptor de archivo ya abierto usando el flag ``AT_EMPTY_PATH``, -efectivamente dando una operación :manpage:`fxyzzy(3)` gratis:: +efectivamente dando una operación fxyzzy(3) gratis:: - xyzzyat(AT_FDCWD, path, ..., 0) es equivalente a xyzzy(path, ...) - xyzzyat(fd, "", ..., AT_EMPTY_PATH) es equivalente a fxyzzy(fd, ...) @@ -167,12 +167,12 @@ efectivamente dando una operación :manpage:`fxyzzy(3)` gratis:: revise el man page :manpage:`openat(2)`; para un ejemplo de AT_EMPTY_PATH, mire el man page :manpage:`fstatat(2)` manpage.) -Si su nueva llamada de sistema :manpage:`xyzzy(2)` involucra un parámetro +Si su nueva llamada de sistema xyzzy(2) involucra un parámetro describiendo un describiendo un movimiento dentro de un archivo, ponga de tipo ``loff_t`` para que movimientos de 64-bit puedan ser soportados incluso en arquitecturas de 32-bit. -Si su nueva llamada de sistema :manpage:`xyzzy` involucra una +Si su nueva llamada de sistema xyzzy(2) involucra una funcionalidad privilegiada, esta necesita ser gobernada por la capability bit linux apropiada (revisado con una llamada a ``capable()``), como se describe en el man page :manpage:`capabilities(7)`. Elija una parte de @@ -182,7 +182,7 @@ misma sección, ya que va en contra de los propósitos de las capabilities de dividir el poder del usuario root. En particular, evite agregar nuevos usos de la capacidad ya demasiado general de la capabilities ``CAP_SYS_ADMIN``. -Si su nueva llamada de sistema :manpage:`xyzzy(2)` manipula un proceso que +Si su nueva llamada de sistema xyzzy(2) manipula un proceso que no es el proceso invocado, este debería ser restringido (usando una llamada a ``ptrace_may_access()``) de forma que el único proceso con los mismos permisos del proceso objetivo, o con las capacidades (capabilities) @@ -221,7 +221,7 @@ kernel, debería siempre ser copiado a linux-api@vger.kernel.org. Implementation de Llamada de Sistema Generica --------------------------------------------- -La entrada principal a su nueva llamada de sistema :manpage:`xyzzy(2)` será +La entrada principal a su nueva llamada de sistema xyzzy(2) será llamada ``sys_xyzzy()``, pero incluya este punto de entrada con la macro ``SYSCALL_DEFINEn()`` apropiada en vez de explicitamente. El 'n' indica el numero de argumentos de la llamada de sistema, y la macro toma el nombre de diff --git a/Documentation/translations/sp_SP/process/coding-style.rst b/Documentation/translations/sp_SP/process/coding-style.rst index 025223be9706..7d63aa8426e6 100644 --- a/Documentation/translations/sp_SP/process/coding-style.rst +++ b/Documentation/translations/sp_SP/process/coding-style.rst @@ -633,7 +633,7 @@ posiblemente POR QUÉ hace esto. Al comentar las funciones de la API del kernel, utilice el formato kernel-doc. Consulte los archivos en :ref:`Documentation/doc-guide/ <doc_guide>` -y ``scripts/kernel-doc`` para más detalles. +y ``tools/docs/kernel-doc`` para más detalles. El estilo preferido para comentarios largos (de varias líneas) es: diff --git a/Documentation/translations/zh_CN/doc-guide/kernel-doc.rst b/Documentation/translations/zh_CN/doc-guide/kernel-doc.rst index ccfb9b8329c2..fb2bbaaa85c1 100644 --- a/Documentation/translations/zh_CN/doc-guide/kernel-doc.rst +++ b/Documentation/translations/zh_CN/doc-guide/kernel-doc.rst @@ -43,7 +43,7 @@ kernel-doc注释用 ``/**`` 作为开始标记。 ``kernel-doc`` 工具将提取 用详细模式和不生成实际输出来运行 ``kernel-doc`` 工具,可以验证文档注释的格式 是否正确。例如:: - scripts/kernel-doc -v -none drivers/foo/bar.c + tools/docs/kernel-doc -v -none drivers/foo/bar.c 当请求执行额外的gcc检查时,内核构建将验证文档格式:: @@ -473,7 +473,7 @@ doc: *title* 如果没有选项,kernel-doc指令将包含源文件中的所有文档注释。 kernel-doc扩展包含在内核源代码树中,位于 ``Documentation/sphinx/kerneldoc.py`` 。 -在内部,它使用 ``scripts/kernel-doc`` 脚本从源代码中提取文档注释。 +在内部,它使用 ``tools/docs/kernel-doc`` 脚本从源代码中提取文档注释。 .. _kernel_doc_zh: @@ -482,18 +482,18 @@ kernel-doc扩展包含在内核源代码树中,位于 ``Documentation/sphinx/k 如果您只想使用kernel-doc生成手册页,可以从内核git树这样做:: - $ scripts/kernel-doc -man \ + $ tools/docs/kernel-doc -man \ $(git grep -l '/\*\*' -- :^Documentation :^tools) \ | scripts/split-man.pl /tmp/man 一些旧版本的git不支持路径排除语法的某些变体。 以下命令之一可能适用于这些版本:: - $ scripts/kernel-doc -man \ + $ tools/docs/kernel-doc -man \ $(git grep -l '/\*\*' -- . ':!Documentation' ':!tools') \ | scripts/split-man.pl /tmp/man - $ scripts/kernel-doc -man \ + $ tools/docs/kernel-doc -man \ $(git grep -l '/\*\*' -- . ":(exclude)Documentation" ":(exclude)tools") \ | scripts/split-man.pl /tmp/man diff --git a/Documentation/translations/zh_CN/kbuild/kbuild.rst b/Documentation/translations/zh_CN/kbuild/kbuild.rst index 57f5cf5b2cdd..a477b4b08958 100644 --- a/Documentation/translations/zh_CN/kbuild/kbuild.rst +++ b/Documentation/translations/zh_CN/kbuild/kbuild.rst @@ -174,7 +174,7 @@ UTS_MACHINE 变量(在某些架构中还包括内核配置)来猜测正确 KDOCFLAGS --------- 指定在构建过程中用于 kernel-doc 检查的额外(警告/错误)标志,查看 -scripts/kernel-doc 了解支持的标志。请注意,这目前不适用于文档构建。 +tools/docs/kernel-doc 了解支持的标志。请注意,这目前不适用于文档构建。 ARCH ---- diff --git a/Documentation/translations/zh_CN/process/coding-style.rst b/Documentation/translations/zh_CN/process/coding-style.rst index 0484d0c65c25..5a342a024c01 100644 --- a/Documentation/translations/zh_CN/process/coding-style.rst +++ b/Documentation/translations/zh_CN/process/coding-style.rst @@ -545,7 +545,7 @@ Linux 里这是提倡的做法,因为这样可以很简单的给读者提供 也可以加上它做这些事情的原因。 当注释内核 API 函数时,请使用 kernel-doc 格式。详见 -Documentation/translations/zh_CN/doc-guide/index.rst 和 scripts/kernel-doc 。 +Documentation/translations/zh_CN/doc-guide/index.rst 和 tools/docs/kernel-doc 。 长 (多行) 注释的首选风格是: diff --git a/Documentation/translations/zh_TW/process/coding-style.rst b/Documentation/translations/zh_TW/process/coding-style.rst index 311c6f6bad0b..e2ba97b3d8bb 100644 --- a/Documentation/translations/zh_TW/process/coding-style.rst +++ b/Documentation/translations/zh_TW/process/coding-style.rst @@ -548,7 +548,7 @@ Linux 裏這是提倡的做法,因爲這樣可以很簡單的給讀者提供 也可以加上它做這些事情的原因。 當註釋內核 API 函數時,請使用 kernel-doc 格式。詳見 -Documentation/translations/zh_CN/doc-guide/index.rst 和 scripts/kernel-doc 。 +Documentation/translations/zh_CN/doc-guide/index.rst 和 tools/docs/kernel-doc 。 長 (多行) 註釋的首選風格是: diff --git a/Documentation/usb/index.rst b/Documentation/usb/index.rst index 826492c813ac..605233febd7a 100644 --- a/Documentation/usb/index.rst +++ b/Documentation/usb/index.rst @@ -31,10 +31,3 @@ USB support usb-help text_files - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/userspace-api/gpio/index.rst b/Documentation/userspace-api/gpio/index.rst index f258de4ef370..ac9c6ff9875c 100644 --- a/Documentation/userspace-api/gpio/index.rst +++ b/Documentation/userspace-api/gpio/index.rst @@ -9,10 +9,3 @@ GPIO Character Device Userspace API <chardev> Obsolete Userspace APIs <obsolete> - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/userspace-api/index.rst b/Documentation/userspace-api/index.rst index 8a61ac4c1bf1..6f0235ecc572 100644 --- a/Documentation/userspace-api/index.rst +++ b/Documentation/userspace-api/index.rst @@ -68,10 +68,3 @@ Everything else futex2 perf_ring_buffer ntsync - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/userspace-api/ioctl/ioctl-number.rst b/Documentation/userspace-api/ioctl/ioctl-number.rst index 7232b3544cec..b5c6447455fd 100644 --- a/Documentation/userspace-api/ioctl/ioctl-number.rst +++ b/Documentation/userspace-api/ioctl/ioctl-number.rst @@ -15,7 +15,7 @@ macros defined in <linux/ioctl.h>: ====== =========================== _IO none _IOW write (read from userspace) - _IOR read (write to userpace) + _IOR read (write to userspace) _IOWR write and read ====== =========================== diff --git a/Documentation/virt/index.rst b/Documentation/virt/index.rst index 7fb55ae08598..c1f0bbc37315 100644 --- a/Documentation/virt/index.rst +++ b/Documentation/virt/index.rst @@ -16,10 +16,3 @@ Virtualization Support coco/sev-guest coco/tdx-guest hyperv/index - -.. only:: html and subproject - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/w1/index.rst b/Documentation/w1/index.rst index 156279f17553..2e7bd8afea84 100644 --- a/Documentation/w1/index.rst +++ b/Documentation/w1/index.rst @@ -12,10 +12,3 @@ w1-netlink.rst masters/index slaves/index - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/watchdog/index.rst b/Documentation/watchdog/index.rst index 4603f2511f58..1cea24681e6b 100644 --- a/Documentation/watchdog/index.rst +++ b/Documentation/watchdog/index.rst @@ -16,10 +16,3 @@ Watchdog Support watchdog-pm wdt convert_drivers_to_kernel_api - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/wmi/devices/index.rst b/Documentation/wmi/devices/index.rst index c08735a9d7df..b0a9b4229add 100644 --- a/Documentation/wmi/devices/index.rst +++ b/Documentation/wmi/devices/index.rst @@ -13,10 +13,3 @@ the Linux kernel, their protocols and driver details. :glob: * - -.. only:: subproject and html - - Indices - ======= - - * :ref:`genindex` diff --git a/Documentation/wmi/index.rst b/Documentation/wmi/index.rst index fec4b6ae97b3..56016078fc79 100644 --- a/Documentation/wmi/index.rst +++ b/Documentation/wmi/index.rst @@ -10,11 +10,3 @@ WMI Subsystem acpi-interface driver-development-guide devices/index - -.. only:: subproject and html - - - Indices - ======= - - * :ref:`genindex` diff --git a/MAINTAINERS b/MAINTAINERS index 5d371f76daf1..fcf39de76838 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -7528,12 +7528,12 @@ F: include/linux/dmi.h DOCUMENTATION M: Jonathan Corbet <corbet@lwn.net> +R: Shuah Khan <skhan@linuxfoundation.org> L: linux-doc@vger.kernel.org S: Maintained P: Documentation/doc-guide/maintainer-profile.rst T: git git://git.lwn.net/linux.git docs-next F: Documentation/ -F: scripts/kernel-doc* F: tools/lib/python/* F: tools/docs/ F: tools/net/ynl/pyynl/lib/doc_generator.py @@ -7550,6 +7550,7 @@ X: Documentation/userspace-api/media/ DOCUMENTATION PROCESS M: Jonathan Corbet <corbet@lwn.net> +R: Shuah Khan <skhan@linuxfoundation.org> L: workflows@vger.kernel.org S: Maintained F: Documentation/dev-tools/ @@ -7570,7 +7571,6 @@ M: Mauro Carvalho Chehab <mchehab@kernel.org> L: linux-doc@vger.kernel.org S: Maintained F: Documentation/sphinx/ -F: scripts/kernel-doc* F: tools/lib/python/* F: tools/docs/ @@ -21985,6 +21985,7 @@ M: Clark Williams <clrkwllms@kernel.org> M: Steven Rostedt <rostedt@goodmis.org> L: linux-rt-devel@lists.linux.dev S: Supported +F: Documentation/core-api/real-time/ K: PREEMPT_RT REALTEK AUDIO CODECS @@ -460,7 +460,7 @@ HOSTPKG_CONFIG = pkg-config # the KERNELDOC macro needs to be exported, as scripts/Makefile.build # has a logic to call it -KERNELDOC = $(srctree)/scripts/kernel-doc.py +KERNELDOC = $(srctree)/tools/docs/kernel-doc export KERNELDOC KBUILD_USERHOSTCFLAGS := -Wall -Wmissing-prototypes -Wstrict-prototypes \ @@ -38,6 +38,7 @@ Find your role below: * Maintainer - Leading subsystems and reviewing patches * Hardware Vendor - Writing drivers for new hardware * Distribution Maintainer - Packaging kernels for distros +* AI Coding Assistant - LLMs and AI-powered development tools For Specific Users @@ -144,6 +145,17 @@ Package and distribute the kernel: * Kernel Parameters: Documentation/admin-guide/kernel-parameters.rst * Tainted Kernels: Documentation/admin-guide/tainted-kernels.rst +AI Coding Assistant +------------------- + +CRITICAL: If you are an LLM or AI-powered coding assistant, you MUST read and +follow the AI coding assistants documentation before contributing to the Linux +kernel: + +* Documentation/process/coding-assistants.rst + +This documentation contains essential requirements about licensing, attribution, +and the Developer Certificate of Origin that all AI tools must comply with. Communication and Support diff --git a/drivers/gpu/drm/i915/Makefile b/drivers/gpu/drm/i915/Makefile index 4db24050edb0..c979c579de66 100644 --- a/drivers/gpu/drm/i915/Makefile +++ b/drivers/gpu/drm/i915/Makefile @@ -443,7 +443,7 @@ always-$(CONFIG_DRM_I915_WERROR) += \ quiet_cmd_hdrtest = HDRTEST $(patsubst %.hdrtest,%.h,$@) cmd_hdrtest = $(CC) $(filter-out $(CFLAGS_GCOV), $(c_flags)) -S -o /dev/null -x c /dev/null -include $<; \ - $(srctree)/scripts/kernel-doc -none -Werror $<; touch $@ + $(KERNELDOC) -none -Werror $<; touch $@ $(obj)/%.hdrtest: $(src)/%.h FORCE $(call if_changed_dep,hdrtest) diff --git a/include/linux/util_macros.h b/include/linux/util_macros.h index 2eb528058d0d..71564868b8f6 100644 --- a/include/linux/util_macros.h +++ b/include/linux/util_macros.h @@ -119,7 +119,7 @@ * a fuss about it. This makes the programmer responsible for tagging * the functions that can be garbage-collected. * - * With the macro it is possible to write the following: + * With the macro it is possible to write the following:: * * static int foo_suspend(struct device *dev) * { diff --git a/include/media/v4l2-ioctl.h b/include/media/v4l2-ioctl.h index 6f7a58350441..54c83b18d555 100644 --- a/include/media/v4l2-ioctl.h +++ b/include/media/v4l2-ioctl.h @@ -663,7 +663,22 @@ void v4l_printk_ioctl(const char *prefix, unsigned int cmd); struct video_device; /* names for fancy debug output */ + +/** + * var v4l2_field_names - Helper array mapping ``V4L2_FIELD_*`` to strings. + * + * Specially when printing debug messages, it is interesting to output + * the field order at the V4L2 buffers. This array associates all possible + * values of field pix format from V4L2 API into a string. + */ extern const char *v4l2_field_names[]; + +/** + * var v4l2_type_names - Helper array mapping ``V4L2_BUF_TYPE_*`` to strings. + * + * When printing debug messages, it is interesting to output the V4L2 buffer + * type number with a name that represents its content. + */ extern const char *v4l2_type_names[]; #ifdef CONFIG_COMPAT diff --git a/scripts/kernel-doc b/scripts/kernel-doc index 3b6ef807791a..9cc1459ffcdb 120000 --- a/scripts/kernel-doc +++ b/scripts/kernel-doc @@ -1 +1 @@ -kernel-doc.py
\ No newline at end of file +../tools/docs/kernel-doc
\ No newline at end of file diff --git a/tools/docs/find-unused-docs.sh b/tools/docs/find-unused-docs.sh index 05552dbda5bc..53514c759dc1 100755 --- a/tools/docs/find-unused-docs.sh +++ b/tools/docs/find-unused-docs.sh @@ -28,7 +28,7 @@ if ! [ -d "$1" ]; then fi cd "$( dirname "${BASH_SOURCE[0]}" )" -cd .. +cd ../.. cd Documentation/ @@ -54,7 +54,7 @@ for file in `find $1 -name '*.c'`; do if [[ ${FILES_INCLUDED[$file]+_} ]]; then continue; fi - str=$(PYTHONDONTWRITEBYTECODE=1 scripts/kernel-doc -export "$file" 2>/dev/null) + str=$(PYTHONDONTWRITEBYTECODE=1 tools/docs/kernel-doc -export "$file" 2>/dev/null) if [[ -n "$str" ]]; then echo "$file" fi diff --git a/scripts/kernel-doc.py b/tools/docs/kernel-doc index 7a1eaf986bcd..aed09f9a54dd 100755 --- a/scripts/kernel-doc.py +++ b/tools/docs/kernel-doc @@ -3,16 +3,16 @@ # Copyright(c) 2025: Mauro Carvalho Chehab <mchehab@kernel.org>. # # pylint: disable=C0103,R0912,R0914,R0915 - +# # NOTE: While kernel-doc requires at least version 3.6 to run, the # command line should work with Python 3.2+ (tested with 3.4). # The rationale is that it shall fail gracefully during Kernel # compilation with older Kernel versions. Due to that: # - encoding line is needed here; -# - no f-strings can be used on this file. -# - the libraries that require newer versions can only be included -# after Python version is checked. - +# - f-strings cannot be used in this file. +# - libraries that require newer versions can only be included +# after the Python version has been checked. +# # Converted from the kernel-doc script originally written in Perl # under GPLv2, copyrighted since 1998 by the following authors: # @@ -88,16 +88,13 @@ # Yujie Liu <yujie.liu@intel.com> """ -kernel_doc -========== - -Print formatted kernel documentation to stdout +Print formatted kernel documentation to stdout. Read C language source or header FILEs, extract embedded documentation comments, and print formatted documentation to standard output. -The documentation comments are identified by the "/**" +The documentation comments are identified by the ``/**`` opening comment mark. See Documentation/doc-guide/kernel-doc.rst for the @@ -111,11 +108,13 @@ import sys # Import Python modules -LIB_DIR = "../tools/lib/python" +LIB_DIR = "../lib/python" SRC_DIR = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.join(SRC_DIR, LIB_DIR)) +WERROR_RETURN_CODE = 3 + DESC = """ Read C language source or header FILEs, extract embedded documentation comments, and print formatted documentation to standard output. @@ -132,13 +131,13 @@ May be used multiple times. """ EXPORT_DESC = """ -Only output documentation for the symbols that have been +Only output documentation for symbols that have been exported using EXPORT_SYMBOL() and related macros in any input FILE or -export-file FILE. """ INTERNAL_DESC = """ -Only output documentation for the symbols that have NOT been +Only output documentation for symbols that have NOT been exported using EXPORT_SYMBOL() and related macros in any input FILE or -export-file FILE. """ @@ -161,28 +160,49 @@ Header and C source files to be parsed. """ WARN_CONTENTS_BEFORE_SECTIONS_DESC = """ -Warns if there are contents before sections (deprecated). +Warn if there are contents before sections (deprecated). This option is kept just for backward-compatibility, but it does nothing, neither here nor at the original Perl script. """ +EPILOG = """ +The return value is: + +- 0: success or Python version is not compatible with +kernel-doc. If -Werror is not used, it will also +return 0 if there are issues at kernel-doc markups; + +- 1: an abnormal condition happened; + +- 2: argparse issued an error; + +- 3: When -Werror is used, it means that one or more unfiltered parse + warnings happened. +""" class MsgFormatter(logging.Formatter): - """Helper class to format warnings on a similar way to kernel-doc.pl""" + """ + Helper class to capitalize errors and warnings, the same way + the venerable (now retired) kernel-doc.pl used to do. + """ def format(self, record): record.levelname = record.levelname.capitalize() return logging.Formatter.format(self, record) def main(): - """Main program""" + """ + Main program. + + """ parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter, - description=DESC) + description=DESC, epilog=EPILOG) + # # Normal arguments - + # parser.add_argument("-v", "-verbose", "--verbose", action="store_true", help="Verbose output, more warnings and other information.") @@ -197,8 +217,9 @@ def main(): action="store_true", help="Enable line number output (only in ReST mode)") + # # Arguments to control the warning behavior - + # parser.add_argument("-Wreturn", "--wreturn", action="store_true", help="Warns about the lack of a return markup on functions.") @@ -219,8 +240,9 @@ def main(): parser.add_argument("-export-file", "--export-file", action='append', help=EXPORT_FILE_DESC) + # # Output format mutually-exclusive group - + # out_group = parser.add_argument_group("Output format selection (mutually exclusive)") out_fmt = out_group.add_mutually_exclusive_group() @@ -232,8 +254,9 @@ def main(): out_fmt.add_argument("-N", "-none", "--none", action="store_true", help="Do not output documentation, only warnings.") + # # Output selection mutually-exclusive group - + # sel_group = parser.add_argument_group("Output selection (mutually exclusive)") sel_mut = sel_group.add_mutually_exclusive_group() @@ -246,12 +269,14 @@ def main(): sel_mut.add_argument("-s", "-function", "--symbol", action='append', help=FUNCTION_DESC) + # # Those are valid for all 3 types of filter + # parser.add_argument("-n", "-nosymbol", "--nosymbol", action='append', help=NOSYMBOL_DESC) parser.add_argument("-D", "-no-doc-sections", "--no-doc-sections", - action='store_true', help="Don't outputt DOC sections") + action='store_true', help="Don't output DOC sections") parser.add_argument("files", metavar="FILE", nargs="+", help=FILES_DESC) @@ -279,11 +304,13 @@ def main(): python_ver = sys.version_info[:2] if python_ver < (3,6): - # Depending on Kernel configuration, kernel-doc --none is called at + # + # Depending on the Kernel configuration, kernel-doc --none is called at # build time. As we don't want to break compilation due to the # usage of an old Python version, return 0 here. + # if args.none: - logger.error("Python 3.6 or later is required by kernel-doc. skipping checks") + logger.error("Python 3.6 or later is required by kernel-doc. Skipping checks") sys.exit(0) sys.exit("Python 3.6 or later is required by kernel-doc. Aborting.") @@ -291,7 +318,9 @@ def main(): if python_ver < (3,7): logger.warning("Python 3.7 or later is required for correct results") - # Import kernel-doc libraries only after checking Python version + # + # Import kernel-doc libraries only after checking the Python version + # from kdoc.kdoc_files import KernelFiles # pylint: disable=C0415 from kdoc.kdoc_output import RestFormat, ManFormat # pylint: disable=C0415 @@ -323,17 +352,15 @@ def main(): if args.werror: print("%s warnings as errors" % error_count) # pylint: disable=C0209 - sys.exit(error_count) + sys.exit(WERROR_RETURN_CODE) if args.verbose: print("%s errors" % error_count) # pylint: disable=C0209 - if args.none: - sys.exit(0) - - sys.exit(error_count) - + sys.exit(0) +# # Call main method +# if __name__ == "__main__": main() diff --git a/tools/docs/sphinx-build-wrapper b/tools/docs/sphinx-build-wrapper index 7a5fcef25429..b7c149dff06b 100755 --- a/tools/docs/sphinx-build-wrapper +++ b/tools/docs/sphinx-build-wrapper @@ -119,16 +119,17 @@ class SphinxBuilder: return path - def check_rust(self): + def check_rust(self, sphinxdirs): """ Checks if Rust is enabled """ - self.rustdoc = False - config = os.path.join(self.srctree, ".config") + if not {'.', 'rust'}.intersection(sphinxdirs): + return False + if not os.path.isfile(config): - return + return False re_rust = re.compile(r"CONFIG_RUST=(m|y)") @@ -136,11 +137,13 @@ class SphinxBuilder: with open(config, "r", encoding="utf-8") as fp: for line in fp: if re_rust.match(line): - self.rustdoc = True - return + return True except OSError as e: print(f"Failed to open {config}", file=sys.stderr) + return False + + return False def get_sphinx_extra_opts(self, n_jobs): """ @@ -165,6 +168,7 @@ class SphinxBuilder: parser = argparse.ArgumentParser() parser.add_argument('-j', '--jobs', type=int) parser.add_argument('-q', '--quiet', action='store_true') + parser.add_argument('-v', '--verbose', default=0, action='count') # # Other sphinx-build arguments go as-is, so place them @@ -176,10 +180,14 @@ class SphinxBuilder: # Build a list of sphinx args, honoring verbosity here if specified # - verbose = self.verbose sphinx_args, self.sphinxopts = parser.parse_known_args(sphinxopts) + + verbose = sphinx_args.verbose + if self.verbose: + verbose += 1 + if sphinx_args.quiet is True: - verbose = False + verbose = 0 # # If the user explicitly sets "-j" at command line, use it. @@ -192,8 +200,11 @@ class SphinxBuilder: else: self.n_jobs = None - if not verbose: + if verbose < 1: self.sphinxopts += ["-q"] + else: + for i in range(1, sphinx_args.verbose): + self.sphinxopts += ["-v"] def __init__(self, builddir, venv=None, verbose=False, n_jobs=None, interactive=None): @@ -246,7 +257,7 @@ class SphinxBuilder: # self.sphinxbuild = os.environ.get("SPHINXBUILD", "sphinx-build") self.kerneldoc = self.get_path(os.environ.get("KERNELDOC", - "scripts/kernel-doc.py")) + "tools/docs/kernel-doc")) self.builddir = self.get_path(builddir, use_cwd=True, abs_path=True) # @@ -259,8 +270,6 @@ class SphinxBuilder: self.get_sphinx_extra_opts(n_jobs) - self.check_rust() - # # If venv command line argument is specified, run Sphinx from venv # @@ -352,23 +361,6 @@ class SphinxBuilder: except (OSError, IOError) as e: print(f"Warning: Failed to copy CSS: {e}", file=sys.stderr) - if self.rustdoc: - print("Building rust docs") - if "MAKE" in self.env: - cmd = [self.env["MAKE"]] - else: - cmd = ["make", "LLVM=1"] - - cmd += [ "rustdoc"] - if self.verbose: - print(" ".join(cmd)) - - try: - subprocess.run(cmd, check=True) - except subprocess.CalledProcessError as e: - print(f"Ignored errors when building rustdoc: {e}. Is RUST enabled?", - file=sys.stderr) - def build_pdf_file(self, latex_cmd, from_dir, path): """Builds a single pdf file using latex_cmd""" try: @@ -689,6 +681,19 @@ class SphinxBuilder: if kerneldoc.startswith(self.srctree): kerneldoc = os.path.relpath(kerneldoc, self.srctree) + if not sphinxdirs: + sphinxdirs = os.environ.get("SPHINXDIRS", ".") + + # + # sphinxdirs can be a list or a whitespace-separated string + # + sphinxdirs_list = [] + for sphinxdir in sphinxdirs: + if isinstance(sphinxdir, list): + sphinxdirs_list += sphinxdir + else: + sphinxdirs_list += sphinxdir.split() + args = [ "-b", builder, "-c", docs_dir ] if builder == "latex": @@ -697,12 +702,10 @@ class SphinxBuilder: args.extend(["-D", f"latex_elements.papersize={paper}paper"]) - if self.rustdoc: + rustdoc = self.check_rust(sphinxdirs_list) + if rustdoc: args.extend(["-t", "rustdoc"]) - if not sphinxdirs: - sphinxdirs = os.environ.get("SPHINXDIRS", ".") - # # The sphinx-build tool has a bug: internally, it tries to set # locale with locale.setlocale(locale.LC_ALL, ''). This causes a @@ -714,16 +717,6 @@ class SphinxBuilder: self.env["LC_ALL"] = "C" # - # sphinxdirs can be a list or a whitespace-separated string - # - sphinxdirs_list = [] - for sphinxdir in sphinxdirs: - if isinstance(sphinxdir, list): - sphinxdirs_list += sphinxdir - else: - sphinxdirs_list += sphinxdir.split() - - # # Step 1: Build each directory in separate. # # This is not the best way of handling it, as cross-references between @@ -750,7 +743,6 @@ class SphinxBuilder: build_args = args + [ "-d", doctree_dir, - "-D", f"kerneldoc_bin={kerneldoc}", "-D", f"version={self.kernelversion}", "-D", f"release={self.kernelrelease}", "-D", f"kerneldoc_srctree={self.srctree}", @@ -786,6 +778,23 @@ class SphinxBuilder: elif target == "infodocs": self.handle_info(output_dirs) + if rustdoc and target in ["htmldocs", "epubdocs"]: + print("Building rust docs") + if "MAKE" in self.env: + cmd = [self.env["MAKE"]] + else: + cmd = ["make", "LLVM=1"] + + cmd += [ "rustdoc"] + if self.verbose: + print(" ".join(cmd)) + + try: + subprocess.run(cmd, check=True) + except subprocess.CalledProcessError as e: + print(f"Ignored errors when building rustdoc: {e}. Is RUST enabled?", + file=sys.stderr) + def jobs_type(value): """ Handle valid values for -j. Accepts Sphinx "-jauto", plus a number @@ -805,20 +814,42 @@ def jobs_type(value): except ValueError: raise argparse.ArgumentTypeError(f"Must be 'auto' or positive integer, got {value}") # pylint: disable=W0707 +EPILOG=""" +Besides the command line arguments, several environment variables affect its +default behavior, meant to be used when called via Kernel Makefile: + +- KERNELVERSION: Kernel major version +- KERNELRELEASE: Kernel release +- KBUILD_VERBOSE: Contains the value of "make V=[0|1] variable. + When V=0 (KBUILD_VERBOSE=0), sets verbose level to "-q". +- SPHINXBUILD: Documentation build tool (default: "sphinx-build"). +- SPHINXOPTS: Extra options pased to SPHINXBUILD + (default: "-j auto" and "-q" if KBUILD_VERBOSE=0). + The "-v" flag can be used to increase verbosity. + If V=0, the first "-v" will drop "-q". +- PYTHON3: Python command to run SPHINXBUILD +- PDFLATEX: LaTeX PDF engine. (default: "xelatex") +- LATEXOPTS: Optional set of command line arguments to the LaTeX engine +- srctree: Location of the Kernel root directory (default: "."). + +""" + def main(): """ Main function. The only mandatory argument is the target. If not specified, the other arguments will use default values if not specified at os.environ. """ - parser = argparse.ArgumentParser(description="Kernel documentation builder") + parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter, + description=__doc__, + epilog=EPILOG) parser.add_argument("target", choices=list(TARGETS.keys()), help="Documentation target to build") parser.add_argument("--sphinxdirs", nargs="+", help="Specific directories to build") parser.add_argument("--builddir", default="output", - help="Sphinx configuration file") + help="Sphinx configuration file (default: %(default)s)") parser.add_argument("--theme", help="Sphinx theme to use") @@ -834,7 +865,7 @@ def main(): help="place build in verbose mode") parser.add_argument('-j', '--jobs', type=jobs_type, - help="Sets number of jobs to use with sphinx-build") + help="Sets number of jobs to use with sphinx-build(default: auto)") parser.add_argument('-i', '--interactive', action='store_true', help="Change latex default to run in interactive mode") diff --git a/tools/lib/python/abi/abi_parser.py b/tools/lib/python/abi/abi_parser.py index 9b8db70067ef..d7bb20ef3acc 100644 --- a/tools/lib/python/abi/abi_parser.py +++ b/tools/lib/python/abi/abi_parser.py @@ -21,14 +21,17 @@ from abi.helpers import AbiDebug, ABI_DIR class AbiParser: - """Main class to parse ABI files""" + """Main class to parse ABI files.""" + #: Valid tags at Documentation/ABI. TAGS = r"(what|where|date|kernelversion|contact|description|users)" + + #: ABI elements that will auto-generate cross-references. XREF = r"(?:^|\s|\()(\/(?:sys|config|proc|dev|kvd)\/[^,.:;\)\s]+)(?:[,.:;\)\s]|\Z)" def __init__(self, directory, logger=None, enable_lineno=False, show_warnings=True, debug=0): - """Stores arguments for the class and initialize class vars""" + """Stores arguments for the class and initialize class vars.""" self.directory = directory self.enable_lineno = enable_lineno @@ -65,7 +68,7 @@ class AbiParser: self.re_xref_node = re.compile(self.XREF) def warn(self, fdata, msg, extra=None): - """Displays a parse error if warning is enabled""" + """Displays a parse error if warning is enabled.""" if not self.show_warnings: return @@ -77,7 +80,7 @@ class AbiParser: self.log.warning(msg) def add_symbol(self, what, fname, ln=None, xref=None): - """Create a reference table describing where each 'what' is located""" + """Create a reference table describing where each 'what' is located.""" if what not in self.what_symbols: self.what_symbols[what] = {"file": {}} @@ -92,7 +95,7 @@ class AbiParser: self.what_symbols[what]["xref"] = xref def _parse_line(self, fdata, line): - """Parse a single line of an ABI file""" + """Parse a single line of an ABI file.""" new_what = False new_tag = False @@ -264,7 +267,7 @@ class AbiParser: self.warn(fdata, "Unexpected content", line) def parse_readme(self, nametag, fname): - """Parse ABI README file""" + """Parse ABI README file.""" nametag["what"] = ["Introduction"] nametag["path"] = "README" @@ -282,7 +285,7 @@ class AbiParser: nametag["description"] += line def parse_file(self, fname, path, basename): - """Parse a single file""" + """Parse a single file.""" ref = f"abi_file_{path}_{basename}" ref = self.re_unprintable.sub("_", ref).strip("_") @@ -348,7 +351,7 @@ class AbiParser: self.add_symbol(what=w, fname=fname, xref=fdata.key) def _parse_abi(self, root=None): - """Internal function to parse documentation ABI recursively""" + """Internal function to parse documentation ABI recursively.""" if not root: root = self.directory @@ -377,7 +380,7 @@ class AbiParser: self.parse_file(name, path, basename) def parse_abi(self, root=None): - """Parse documentation ABI""" + """Parse documentation ABI.""" self._parse_abi(root) @@ -385,7 +388,7 @@ class AbiParser: self.log.debug(pformat(self.data)) def desc_txt(self, desc): - """Print description as found inside ABI files""" + """Print description as found inside ABI files.""" desc = desc.strip(" \t\n") @@ -393,7 +396,7 @@ class AbiParser: def xref(self, fname): """ - Converts a Documentation/ABI + basename into a ReST cross-reference + Converts a Documentation/ABI + basename into a ReST cross-reference. """ xref = self.file_refs.get(fname) @@ -403,7 +406,7 @@ class AbiParser: return xref def desc_rst(self, desc): - """Enrich ReST output by creating cross-references""" + """Enrich ReST output by creating cross-references.""" # Remove title markups from the description # Having titles inside ABI files will only work if extra @@ -459,7 +462,7 @@ class AbiParser: def doc(self, output_in_txt=False, show_symbols=True, show_file=True, filter_path=None): - """Print ABI at stdout""" + """Print ABI at stdout.""" part = None for key, v in sorted(self.data.items(), @@ -549,7 +552,7 @@ class AbiParser: yield (msg, file_ref[0][0], ln) def check_issues(self): - """Warn about duplicated ABI entries""" + """Warn about duplicated ABI entries.""" for what, v in self.what_symbols.items(): files = v.get("file") @@ -575,7 +578,7 @@ class AbiParser: self.log.warning("%s is defined %d times: %s", what, len(f), "; ".join(f)) def search_symbols(self, expr): - """ Searches for ABI symbols """ + """ Searches for ABI symbols.""" regex = re.compile(expr, re.I) diff --git a/tools/lib/python/abi/abi_regex.py b/tools/lib/python/abi/abi_regex.py index d5553206de3c..d0c5e3ede6b5 100644 --- a/tools/lib/python/abi/abi_regex.py +++ b/tools/lib/python/abi/abi_regex.py @@ -16,10 +16,22 @@ from abi.abi_parser import AbiParser from abi.helpers import AbiDebug class AbiRegex(AbiParser): - """Extends AbiParser to search ABI nodes with regular expressions""" + """ + Extends AbiParser to search ABI nodes with regular expressions. - # Escape only ASCII visible characters + There some optimizations here to allow a quick symbol search: + instead of trying to place all symbols altogether an doing linear + search which is very time consuming, create a tree with one depth, + grouping similar symbols altogether. + + Yet, sometimes a full search will be needed, so we have a special branch + on such group tree where other symbols are placed. + """ + + #: Escape only ASCII visible characters. escape_symbols = r"([\x21-\x29\x2b-\x2d\x3a-\x40\x5c\x60\x7b-\x7e])" + + #: Special group for other nodes. leave_others = "others" # Tuples with regular expressions to be compiled and replacement data @@ -88,13 +100,15 @@ class AbiRegex(AbiParser): # Recover plus characters (re.compile(r"\xf7"), "+"), ] + + #: Regex to check if the symbol name has a number on it. re_has_num = re.compile(r"\\d") - # Symbol name after escape_chars that are considered a devnode basename + #: Symbol name after escape_chars that are considered a devnode basename. re_symbol_name = re.compile(r"(\w|\\[\.\-\:])+$") - # List of popular group names to be skipped to minimize regex group size - # Use AbiDebug.SUBGROUP_SIZE to detect those + #: List of popular group names to be skipped to minimize regex group size + #: Use AbiDebug.SUBGROUP_SIZE to detect those. skip_names = set(["devices", "hwmon"]) def regex_append(self, what, new): @@ -148,7 +162,7 @@ class AbiRegex(AbiParser): def get_regexes(self, what): """ Given an ABI devnode, return a list of all regular expressions that - may match it, based on the sub-groups created by regex_append() + may match it, based on the sub-groups created by regex_append(). """ re_list = [] diff --git a/tools/lib/python/abi/helpers.py b/tools/lib/python/abi/helpers.py index 639b23e4ca33..2a378d780d3c 100644 --- a/tools/lib/python/abi/helpers.py +++ b/tools/lib/python/abi/helpers.py @@ -13,26 +13,28 @@ ABI_DIR = "Documentation/ABI/" class AbiDebug: """Debug levels""" - WHAT_PARSING = 1 - WHAT_OPEN = 2 - DUMP_ABI_STRUCTS = 4 - UNDEFINED = 8 - REGEX = 16 - SUBGROUP_MAP = 32 - SUBGROUP_DICT = 64 - SUBGROUP_SIZE = 128 - GRAPH = 256 - + WHAT_PARSING = 1 #: Enable debug parsing logic. + WHAT_OPEN = 2 #: Enable debug messages on file open. + DUMP_ABI_STRUCTS = 4 #: Enable debug for ABI parse data. + UNDEFINED = 8 #: Enable extra undefined symbol data. + REGEX = 16 #: Enable debug for what to regex conversion. + SUBGROUP_MAP = 32 #: Enable debug for symbol regex subgroups + SUBGROUP_DICT = 64 #: Enable debug for sysfs graph tree variable. + SUBGROUP_SIZE = 128 #: Enable debug of search groups. + GRAPH = 256 #: Display ref tree graph for undefined symbols. +#: Helper messages for each debug variable DEBUG_HELP = """ -1 - enable debug parsing logic -2 - enable debug messages on file open -4 - enable debug for ABI parse data -8 - enable extra debug information to identify troubles - with ABI symbols found at the local machine that - weren't found on ABI documentation (used only for - undefined subcommand) -16 - enable debug for what to regex conversion -32 - enable debug for symbol regex subgroups -64 - enable debug for sysfs graph tree variable +1 - enable debug parsing logic +2 - enable debug messages on file open +4 - enable debug for ABI parse data +8 - enable extra debug information to identify troubles + with ABI symbols found at the local machine that + weren't found on ABI documentation (used only for + undefined subcommand) +16 - enable debug for what to regex conversion +32 - enable debug for symbol regex subgroups +64 - enable debug for sysfs graph tree variable +128 - enable debug of search groups +256 - enable displaying refrence tree graphs for undefined symbols. """ diff --git a/tools/lib/python/abi/system_symbols.py b/tools/lib/python/abi/system_symbols.py index 4a2554da217b..7bbefd274ea2 100644 --- a/tools/lib/python/abi/system_symbols.py +++ b/tools/lib/python/abi/system_symbols.py @@ -18,11 +18,11 @@ from random import shuffle from abi.helpers import AbiDebug class SystemSymbols: - """Stores arguments for the class and initialize class vars""" + """Stores arguments for the class and initialize class vars.""" def graph_add_file(self, path, link=None): """ - add a file path to the sysfs graph stored at self.root + add a file path to the sysfs graph stored at self.root. """ if path in self.files: @@ -43,7 +43,7 @@ class SystemSymbols: self.files.add(path) def print_graph(self, root_prefix="", root=None, level=0): - """Prints a reference tree graph using UTF-8 characters""" + """Prints a reference tree graph using UTF-8 characters.""" if not root: root = self.root @@ -173,7 +173,7 @@ class SystemSymbols: self._walk(sysfs) def check_file(self, refs, found): - """Check missing ABI symbols for a given sysfs file""" + """Check missing ABI symbols for a given sysfs file.""" res_list = [] @@ -214,7 +214,7 @@ class SystemSymbols: return res_list def _ref_interactor(self, root): - """Recursive function to interact over the sysfs tree""" + """Recursive function to interact over the sysfs tree.""" for k, v in root.items(): if isinstance(v, dict): @@ -232,7 +232,7 @@ class SystemSymbols: def get_fileref(self, all_refs, chunk_size): - """Interactor to group refs into chunks""" + """Interactor to group refs into chunks.""" n = 0 refs = [] @@ -250,7 +250,7 @@ class SystemSymbols: def check_undefined_symbols(self, max_workers=None, chunk_size=50, found=None, dry_run=None): - """Seach ABI for sysfs symbols missing documentation""" + """Seach ABI for sysfs symbols missing documentation.""" self.abi.parse_abi() diff --git a/tools/lib/python/feat/parse_features.py b/tools/lib/python/feat/parse_features.py index b88c04d3e2fe..41a51d9d6f62 100755 --- a/tools/lib/python/feat/parse_features.py +++ b/tools/lib/python/feat/parse_features.py @@ -21,14 +21,25 @@ class ParseFeature: from it. """ + #: feature header string. h_name = "Feature" + + #: Kernel config header string. h_kconfig = "Kconfig" + + #: description header string. h_description = "Description" + + #: subsystem header string. h_subsys = "Subsystem" + + #: status header string. h_status = "Status" + + #: architecture header string. h_arch = "Architecture" - # Sort order for status. Others will be mapped at the end. + #: Sort order for status. Others will be mapped at the end. status_map = { "ok": 0, "TODO": 1, @@ -40,7 +51,7 @@ class ParseFeature: def __init__(self, prefix, debug=0, enable_fname=False): """ - Sets internal variables + Sets internal variables. """ self.prefix = prefix @@ -63,11 +74,13 @@ class ParseFeature: self.msg = "" def emit(self, msg="", end="\n"): + """Helper function to append a new message for feature output.""" + self.msg += msg + end def parse_error(self, fname, ln, msg, data=None): """ - Displays an error message, printing file name and line + Displays an error message, printing file name and line. """ if ln: @@ -82,7 +95,7 @@ class ParseFeature: print("", file=sys.stderr) def parse_feat_file(self, fname): - """Parses a single arch-support.txt feature file""" + """Parses a single arch-support.txt feature file.""" if os.path.isdir(fname): return @@ -204,7 +217,7 @@ class ParseFeature: self.max_size_arch_with_header = self.max_size_arch + len(self.h_arch) def parse(self): - """Parses all arch-support.txt feature files inside self.prefix""" + """Parses all arch-support.txt feature files inside self.prefix.""" path = os.path.expanduser(self.prefix) @@ -281,7 +294,7 @@ class ParseFeature: def output_feature(self, feat): """ - Output a feature on all architectures + Output a feature on all architectures. """ title = f"Feature {feat}" @@ -331,7 +344,7 @@ class ParseFeature: def matrix_lines(self, desc_size, max_size_status, header): """ - Helper function to split element tables at the output matrix + Helper function to split element tables at the output matrix. """ if header: diff --git a/tools/lib/python/jobserver.py b/tools/lib/python/jobserver.py index a24f30ef4fa8..aba22c33393d 100755 --- a/tools/lib/python/jobserver.py +++ b/tools/lib/python/jobserver.py @@ -11,20 +11,23 @@ Interacts with the POSIX jobserver during the Kernel build time. A "normal" jobserver task, like the one initiated by a make subrocess would do: - open read/write file descriptors to communicate with the job server; - - ask for one slot by calling: + - ask for one slot by calling:: + claim = os.read(reader, 1) - - when the job finshes, call: + + - when the job finshes, call:: + os.write(writer, b"+") # os.write(writer, claim) Here, the goal is different: This script aims to get the remaining number of slots available, using all of them to run a command which handle tasks in parallel. To to that, it has a loop that ends only after there are no slots left. It then increments the number by one, in order to allow a -call equivalent to make -j$((claim+1)), e.g. having a parent make creating +call equivalent to ``make -j$((claim+1))``, e.g. having a parent make creating $claim child to do the actual work. The end goal here is to keep the total number of build tasks under the -limit established by the initial make -j$n_proc call. +limit established by the initial ``make -j$n_proc`` call. See: https://www.gnu.org/software/make/manual/html_node/POSIX-Jobserver.html#POSIX-Jobserver @@ -35,18 +38,22 @@ import os import subprocess import sys +def warn(text, *args): + print(f'WARNING: {text}', *args, file = sys.stderr) + class JobserverExec: """ Claim all slots from make using POSIX Jobserver. The main methods here are: + - open(): reserves all slots; - close(): method returns all used slots back to make; - - run(): executes a command setting PARALLELISM=<available slots jobs + 1> + - run(): executes a command setting PARALLELISM=<available slots jobs + 1>. """ def __init__(self): - """Initialize internal vars""" + """Initialize internal vars.""" self.claim = 0 self.jobs = b"" self.reader = None @@ -54,66 +61,105 @@ class JobserverExec: self.is_open = False def open(self): - """Reserve all available slots to be claimed later on""" + """Reserve all available slots to be claimed later on.""" if self.is_open: return - - try: - # Fetch the make environment options. - flags = os.environ["MAKEFLAGS"] - # Look for "--jobserver=R,W" - # Note that GNU Make has used --jobserver-fds and --jobserver-auth - # so this handles all of them. - opts = [x for x in flags.split(" ") if x.startswith("--jobserver")] - - # Parse out R,W file descriptor numbers and set them nonblocking. - # If the MAKEFLAGS variable contains multiple instances of the - # --jobserver-auth= option, the last one is relevant. - fds = opts[-1].split("=", 1)[1] - - # Starting with GNU Make 4.4, named pipes are used for reader - # and writer. - # Example argument: --jobserver-auth=fifo:/tmp/GMfifo8134 - _, _, path = fds.partition("fifo:") - - if path: + self.is_open = True # We only try once + self.claim = None + # + # Check the make flags for "--jobserver=R,W" + # Note that GNU Make has used --jobserver-fds and --jobserver-auth + # so this handles all of them. + # + flags = os.environ.get('MAKEFLAGS', '') + opts = [x for x in flags.split(" ") if x.startswith("--jobserver")] + if not opts: + return + # + # Separate out the provided file descriptors + # + split_opt = opts[-1].split('=', 1) + if len(split_opt) != 2: + warn('unparseable option:', opts[-1]) + return + fds = split_opt[1] + # + # As of GNU Make 4.4, we'll be looking for a named pipe + # identified as fifo:path + # + if fds.startswith('fifo:'): + path = fds[len('fifo:'):] + try: self.reader = os.open(path, os.O_RDONLY | os.O_NONBLOCK) self.writer = os.open(path, os.O_WRONLY) - else: - self.reader, self.writer = [int(x) for x in fds.split(",", 1)] + except (OSError, IOError): + warn('unable to open jobserver pipe', path) + return + # + # Otherwise look for integer file-descriptor numbers. + # + else: + split_fds = fds.split(',') + if len(split_fds) != 2: + warn('malformed jobserver file descriptors:', fds) + return + try: + self.reader = int(split_fds[0]) + self.writer = int(split_fds[1]) + except ValueError: + warn('non-integer jobserver file-descriptors:', fds) + return + try: + # # Open a private copy of reader to avoid setting nonblocking # on an unexpecting process with the same reader fd. - self.reader = os.open("/proc/self/fd/%d" % (self.reader), + # + self.reader = os.open(f"/proc/self/fd/{self.reader}", os.O_RDONLY | os.O_NONBLOCK) - - # Read out as many jobserver slots as possible - while True: - try: - slot = os.read(self.reader, 8) - self.jobs += slot - except (OSError, IOError) as e: - if e.errno == errno.EWOULDBLOCK: - # Stop at the end of the jobserver queue. - break - # If something went wrong, give back the jobs. - if self.jobs: - os.write(self.writer, self.jobs) - raise e - - # Add a bump for our caller's reserveration, since we're just going - # to sit here blocked on our child. - self.claim = len(self.jobs) + 1 - - except (KeyError, IndexError, ValueError, OSError, IOError): - # Any missing environment strings or bad fds should result in just - # not being parallel. - self.claim = None - - self.is_open = True + except (IOError, OSError) as e: + warn('Unable to reopen jobserver read-side pipe:', repr(e)) + return + # + # OK, we have the channel to the job server; read out as many jobserver + # slots as possible. + # + while True: + try: + slot = os.read(self.reader, 8) + if not slot: + # + # Something went wrong. Clear self.jobs to avoid writing + # weirdness back to the jobserver and give up. + self.jobs = b"" + warn("unexpected empty token from jobserver;" + " possible invalid '--jobserver-auth=' setting") + self.claim = None + return + except (OSError, IOError) as e: + # + # If there is nothing more to read then we are done. + # + if e.errno == errno.EWOULDBLOCK: + break + # + # Anything else says that something went weird; give back + # the jobs and give up. + # + if self.jobs: + os.write(self.writer, self.jobs) + self.claim = None + warn('error reading from jobserver pipe', repr(e)) + return + self.jobs += slot + # + # Add a bump for our caller's reserveration, since we're just going + # to sit here blocked on our child. + # + self.claim = len(self.jobs) + 1 def close(self): - """Return all reserved slots to Jobserver""" + """Return all reserved slots to Jobserver.""" if not self.is_open: return diff --git a/tools/lib/python/kdoc/enrich_formatter.py b/tools/lib/python/kdoc/enrich_formatter.py index bb171567a4ca..d1be4e5e1962 100644 --- a/tools/lib/python/kdoc/enrich_formatter.py +++ b/tools/lib/python/kdoc/enrich_formatter.py @@ -26,12 +26,16 @@ class EnrichFormatter(argparse.HelpFormatter): and how they're used at the __doc__ description. """ def __init__(self, *args, **kwargs): - """Initialize class and check if is TTY""" + """ + Initialize class and check if is TTY. + """ super().__init__(*args, **kwargs) self._tty = sys.stdout.isatty() def enrich_text(self, text): - """Handle ReST markups (currently, only ``foo``)""" + r""" + Handle ReST markups (currently, only \`\`text\`\` markups). + """ if self._tty and text: # Replace ``text`` with ANSI SGR (bold) return re.sub(r'\`\`(.+?)\`\`', @@ -39,12 +43,16 @@ class EnrichFormatter(argparse.HelpFormatter): return text def _fill_text(self, text, width, indent): - """Enrich descriptions with markups on it""" + """ + Enrich descriptions with markups on it. + """ enriched = self.enrich_text(text) return "\n".join(indent + line for line in enriched.splitlines()) def _format_usage(self, usage, actions, groups, prefix): - """Enrich positional arguments at usage: line""" + """ + Enrich positional arguments at usage: line. + """ prog = self._prog parts = [] @@ -63,7 +71,9 @@ class EnrichFormatter(argparse.HelpFormatter): return usage_text def _format_action_invocation(self, action): - """Enrich argument names""" + """ + Enrich argument names. + """ if not action.option_strings: return self.enrich_text(f"``{action.dest.upper()}``") diff --git a/tools/lib/python/kdoc/kdoc_files.py b/tools/lib/python/kdoc/kdoc_files.py index bfe02baf1606..022487ea2cc6 100644 --- a/tools/lib/python/kdoc/kdoc_files.py +++ b/tools/lib/python/kdoc/kdoc_files.py @@ -5,7 +5,8 @@ # pylint: disable=R0903,R0913,R0914,R0917 """ -Parse lernel-doc tags on multiple kernel source files. +Classes for navigating through the files that kernel-doc needs to handle +to generate documentation. """ import argparse @@ -43,7 +44,7 @@ class GlobSourceFiles: self.srctree = srctree def _parse_dir(self, dirname): - """Internal function to parse files recursively""" + """Internal function to parse files recursively.""" with os.scandir(dirname) as obj: for entry in obj: @@ -65,7 +66,7 @@ class GlobSourceFiles: def parse_files(self, file_list, file_not_found_cb): """ Define an iterator to parse all source files from file_list, - handling directories if any + handling directories if any. """ if not file_list: @@ -91,18 +92,18 @@ class KernelFiles(): There are two type of parsers defined here: - self.parse_file(): parses both kernel-doc markups and - EXPORT_SYMBOL* macros; - - self.process_export_file(): parses only EXPORT_SYMBOL* macros. + ``EXPORT_SYMBOL*`` macros; + - self.process_export_file(): parses only ``EXPORT_SYMBOL*`` macros. """ def warning(self, msg): - """Ancillary routine to output a warning and increment error count""" + """Ancillary routine to output a warning and increment error count.""" self.config.log.warning(msg) self.errors += 1 def error(self, msg): - """Ancillary routine to output an error and increment error count""" + """Ancillary routine to output an error and increment error count.""" self.config.log.error(msg) self.errors += 1 @@ -128,7 +129,7 @@ class KernelFiles(): def process_export_file(self, fname): """ - Parses EXPORT_SYMBOL* macros from a single Kernel source file. + Parses ``EXPORT_SYMBOL*`` macros from a single Kernel source file. """ # Prevent parsing the same file twice if results are cached @@ -157,7 +158,7 @@ class KernelFiles(): wcontents_before_sections=False, logger=None): """ - Initialize startup variables and parse all files + Initialize startup variables and parse all files. """ if not verbose: @@ -213,7 +214,7 @@ class KernelFiles(): def parse(self, file_list, export_file=None): """ - Parse all files + Parse all files. """ glob = GlobSourceFiles(srctree=self.config.src_tree) @@ -242,7 +243,7 @@ class KernelFiles(): filenames=None, export_file=None): """ Interacts over the kernel-doc results and output messages, - returning kernel-doc markups on each interaction + returning kernel-doc markups on each interaction. """ self.out_style.set_config(self.config) diff --git a/tools/lib/python/kdoc/kdoc_item.py b/tools/lib/python/kdoc/kdoc_item.py index 19805301cb2c..2b8a93f79716 100644 --- a/tools/lib/python/kdoc/kdoc_item.py +++ b/tools/lib/python/kdoc/kdoc_item.py @@ -4,7 +4,16 @@ # then pass into the output modules. # +""" +Data class to store a kernel-doc Item. +""" + class KdocItem: + """ + A class that will, eventually, encapsulate all of the parsed data that we + then pass into the output modules. + """ + def __init__(self, name, fname, type, start_line, **other_stuff): self.name = name self.fname = fname @@ -24,6 +33,9 @@ class KdocItem: self.other_stuff = other_stuff def get(self, key, default = None): + """ + Get a value from optional keys. + """ return self.other_stuff.get(key, default) def __getitem__(self, key): @@ -33,10 +45,16 @@ class KdocItem: # Tracking of section and parameter information. # def set_sections(self, sections, start_lines): + """ + Set sections and start lines. + """ self.sections = sections self.section_start_lines = start_lines def set_params(self, names, descs, types, starts): + """ + Set parameter list: names, descriptions, types and start lines. + """ self.parameterlist = names self.parameterdescs = descs self.parametertypes = types diff --git a/tools/lib/python/kdoc/kdoc_output.py b/tools/lib/python/kdoc/kdoc_output.py index b1aaa7fc3604..4210b91dde5f 100644 --- a/tools/lib/python/kdoc/kdoc_output.py +++ b/tools/lib/python/kdoc/kdoc_output.py @@ -5,14 +5,16 @@ # pylint: disable=C0301,R0902,R0911,R0912,R0913,R0914,R0915,R0917 """ -Implement output filters to print kernel-doc documentation. +Classes to implement output filters to print kernel-doc documentation. -The implementation uses a virtual base class (OutputFormat) which +The implementation uses a virtual base class ``OutputFormat``. It contains dispatches to virtual methods, and some code to filter out output messages. The actual implementation is done on one separate class per each type -of output. Currently, there are output classes for ReST and man/troff. +of output, e.g. ``RestFormat`` and ``ManFormat`` classes. + +Currently, there are output classes for ReST and man/troff. """ import os @@ -54,16 +56,19 @@ class OutputFormat: """ # output mode. - OUTPUT_ALL = 0 # output all symbols and doc sections - OUTPUT_INCLUDE = 1 # output only specified symbols - OUTPUT_EXPORTED = 2 # output exported symbols - OUTPUT_INTERNAL = 3 # output non-exported symbols + OUTPUT_ALL = 0 #: Output all symbols and doc sections. + OUTPUT_INCLUDE = 1 #: Output only specified symbols. + OUTPUT_EXPORTED = 2 #: Output exported symbols. + OUTPUT_INTERNAL = 3 #: Output non-exported symbols. - # Virtual member to be overridden at the inherited classes + #: Highlights to be used in ReST format. highlights = [] + #: Blank line character. + blankline = "" + def __init__(self): - """Declare internal vars and set mode to OUTPUT_ALL""" + """Declare internal vars and set mode to ``OUTPUT_ALL``.""" self.out_mode = self.OUTPUT_ALL self.enable_lineno = None @@ -128,7 +133,7 @@ class OutputFormat: self.config.warning(log_msg) def check_doc(self, name, args): - """Check if DOC should be output""" + """Check if DOC should be output.""" if self.no_doc_sections: return False @@ -177,7 +182,7 @@ class OutputFormat: def msg(self, fname, name, args): """ - Handles a single entry from kernel-doc parser + Handles a single entry from kernel-doc parser. """ self.data = "" @@ -199,6 +204,10 @@ class OutputFormat: self.out_enum(fname, name, args) return self.data + if dtype == "var": + self.out_var(fname, name, args) + return self.data + if dtype == "typedef": self.out_typedef(fname, name, args) return self.data @@ -216,27 +225,31 @@ class OutputFormat: # Virtual methods to be overridden by inherited classes # At the base class, those do nothing. def set_symbols(self, symbols): - """Get a list of all symbols from kernel_doc""" + """Get a list of all symbols from kernel_doc.""" def out_doc(self, fname, name, args): - """Outputs a DOC block""" + """Outputs a DOC block.""" def out_function(self, fname, name, args): - """Outputs a function""" + """Outputs a function.""" def out_enum(self, fname, name, args): - """Outputs an enum""" + """Outputs an enum.""" + + def out_var(self, fname, name, args): + """Outputs a variable.""" def out_typedef(self, fname, name, args): - """Outputs a typedef""" + """Outputs a typedef.""" def out_struct(self, fname, name, args): - """Outputs a struct""" + """Outputs a struct.""" class RestFormat(OutputFormat): - """Consts and functions used by ReST output""" + """Consts and functions used by ReST output.""" + #: Highlights to be used in ReST format highlights = [ (type_constant, r"``\1``"), (type_constant2, r"``\1``"), @@ -256,9 +269,13 @@ class RestFormat(OutputFormat): (type_fallback, r":c:type:`\1`"), (type_param_ref, r"**\1\2**") ] + blankline = "\n" + #: Sphinx literal block regex. sphinx_literal = KernRe(r'^[^.].*::$', cache=False) + + #: Sphinx code block regex. sphinx_cblock = KernRe(r'^\.\.\ +code-block::', cache=False) def __init__(self): @@ -273,7 +290,7 @@ class RestFormat(OutputFormat): self.lineprefix = "" def print_lineno(self, ln): - """Outputs a line number""" + """Outputs a line number.""" if self.enable_lineno and ln is not None: ln += 1 @@ -282,7 +299,7 @@ class RestFormat(OutputFormat): def output_highlight(self, args): """ Outputs a C symbol that may require being converted to ReST using - the self.highlights variable + the self.highlights variable. """ input_text = args @@ -472,6 +489,25 @@ class RestFormat(OutputFormat): self.lineprefix = oldprefix self.out_section(args) + def out_var(self, fname, name, args): + oldprefix = self.lineprefix + ln = args.declaration_start_line + full_proto = args.other_stuff["full_proto"] + + self.lineprefix = " " + + self.data += f"\n\n.. c:macro:: {name}\n\n{self.lineprefix}``{full_proto}``\n\n" + + self.print_lineno(ln) + self.output_highlight(args.get('purpose', '')) + self.data += "\n" + + if args.other_stuff["default_val"]: + self.data += f'{self.lineprefix}**Initialization**\n\n' + self.output_highlight(f'default: ``{args.other_stuff["default_val"]}``') + + self.out_section(args) + def out_typedef(self, fname, name, args): oldprefix = self.lineprefix @@ -544,7 +580,7 @@ class RestFormat(OutputFormat): class ManFormat(OutputFormat): - """Consts and functions used by man pages output""" + """Consts and functions used by man pages output.""" highlights = ( (type_constant, r"\1"), @@ -561,6 +597,7 @@ class ManFormat(OutputFormat): ) blankline = "" + #: Allowed timestamp formats. date_formats = [ "%a %b %d %H:%M:%S %Z %Y", "%a %b %d %H:%M:%S %Y", @@ -627,7 +664,7 @@ class ManFormat(OutputFormat): self.symbols = symbols def out_tail(self, fname, name, args): - """Adds a tail for all man pages""" + """Adds a tail for all man pages.""" # SEE ALSO section self.data += f'.SH "SEE ALSO"' + "\n.PP\n" @@ -663,7 +700,7 @@ class ManFormat(OutputFormat): def output_highlight(self, block): """ Outputs a C symbol that may require being highlighted with - self.highlights variable using troff syntax + self.highlights variable using troff syntax. """ contents = self.highlight_block(block) @@ -694,7 +731,6 @@ class ManFormat(OutputFormat): self.output_highlight(text) def out_function(self, fname, name, args): - """output function in man""" out_name = self.arg_name(args, name) @@ -773,6 +809,26 @@ class ManFormat(OutputFormat): self.data += f'.SH "{section}"' + "\n" self.output_highlight(text) + def out_var(self, fname, name, args): + out_name = self.arg_name(args, name) + full_proto = args.other_stuff["full_proto"] + + self.data += f'.TH "{self.modulename}" 9 "{out_name}" "{self.man_date}" "API Manual" LINUX' + "\n" + + self.data += ".SH NAME\n" + self.data += f"{name} \\- {args['purpose']}\n" + + self.data += ".SH SYNOPSIS\n" + self.data += f"{full_proto}\n" + + if args.other_stuff["default_val"]: + self.data += f'.SH "Initialization"' + "\n" + self.output_highlight(f'default: {args.other_stuff["default_val"]}') + + for section, text in args.sections.items(): + self.data += f'.SH "{section}"' + "\n" + self.output_highlight(text) + def out_typedef(self, fname, name, args): module = self.modulename purpose = args.get('purpose') diff --git a/tools/lib/python/kdoc/kdoc_parser.py b/tools/lib/python/kdoc/kdoc_parser.py index 500aafc50032..fd57944ae907 100644 --- a/tools/lib/python/kdoc/kdoc_parser.py +++ b/tools/lib/python/kdoc/kdoc_parser.py @@ -5,11 +5,8 @@ # pylint: disable=C0301,C0302,R0904,R0912,R0913,R0914,R0915,R0917,R1702 """ -kdoc_parser -=========== - -Read a C language source or header FILE and extract embedded -documentation comments +Classes and functions related to reading a C language source or header FILE +and extract embedded documentation comments from it. """ import sys @@ -53,7 +50,7 @@ doc_content = doc_com_body + KernRe(r'(.*)', cache=False) doc_inline_start = KernRe(r'^\s*/\*\*\s*$', cache=False) doc_inline_sect = KernRe(r'\s*\*\s*(@\s*[\w][\w\.]*\s*):(.*)', cache=False) doc_inline_end = KernRe(r'^\s*\*/\s*$', cache=False) -doc_inline_oneline = KernRe(r'^\s*/\*\*\s*(@[\w\s]+):\s*(.*)\s*\*/\s*$', cache=False) +doc_inline_oneline = KernRe(r'^\s*/\*\*\s*(@\s*[\w][\w\.]*\s*):\s*(.*)\s*\*/\s*$', cache=False) export_symbol = KernRe(r'^\s*EXPORT_SYMBOL(_GPL)?\s*\(\s*(\w+)\s*\)\s*', cache=False) export_symbol_ns = KernRe(r'^\s*EXPORT_SYMBOL_NS(_GPL)?\s*\(\s*(\w+)\s*,\s*"\S+"\)\s*', cache=False) @@ -64,7 +61,7 @@ type_param = KernRe(r"@(\w*((\.\w+)|(->\w+))*(\.\.\.)?)", cache=False) # Tests for the beginning of a kerneldoc block in its various forms. # doc_block = doc_com + KernRe(r'DOC:\s*(.*)?', cache=False) -doc_begin_data = KernRe(r"^\s*\*?\s*(struct|union|enum|typedef)\b\s*(\w*)", cache = False) +doc_begin_data = KernRe(r"^\s*\*?\s*(struct|union|enum|typedef|var)\b\s*(\w*)", cache = False) doc_begin_func = KernRe(str(doc_com) + # initial " * ' r"(?:\w+\s*\*\s*)?" + # type (not captured) r'(?:define\s+)?' + # possible "define" (not captured) @@ -195,25 +192,28 @@ function_xforms = [ ] # -# Apply a set of transforms to a block of text. +# Ancillary functions # + def apply_transforms(xforms, text): + """ + Apply a set of transforms to a block of text. + """ for search, subst in xforms: text = search.sub(subst, text) return text -# -# A little helper to get rid of excess white space -# multi_space = KernRe(r'\s\s+') def trim_whitespace(s): + """ + A little helper to get rid of excess white space. + """ return multi_space.sub(' ', s.strip()) -# -# Remove struct/enum members that have been marked "private". -# def trim_private_members(text): - # + """ + Remove ``struct``/``enum`` members that have been marked "private". + """ # First look for a "public:" block that ends a private region, then # handle the "private until the end" case. # @@ -226,20 +226,21 @@ def trim_private_members(text): class state: """ - State machine enums + States used by the parser's state machine. """ # Parser states - NORMAL = 0 # normal code - NAME = 1 # looking for function name - DECLARATION = 2 # We have seen a declaration which might not be done - BODY = 3 # the body of the comment - SPECIAL_SECTION = 4 # doc section ending with a blank line - PROTO = 5 # scanning prototype - DOCBLOCK = 6 # documentation block - INLINE_NAME = 7 # gathering doc outside main block - INLINE_TEXT = 8 # reading the body of inline docs - + NORMAL = 0 #: Normal code. + NAME = 1 #: Looking for function name. + DECLARATION = 2 #: We have seen a declaration which might not be done. + BODY = 3 #: The body of the comment. + SPECIAL_SECTION = 4 #: Doc section ending with a blank line. + PROTO = 5 #: Scanning prototype. + DOCBLOCK = 6 #: Documentation block. + INLINE_NAME = 7 #: Gathering doc outside main block. + INLINE_TEXT = 8 #: Reading the body of inline docs. + + #: Names for each parser state. name = [ "NORMAL", "NAME", @@ -253,9 +254,12 @@ class state: ] -SECTION_DEFAULT = "Description" # default section +SECTION_DEFAULT = "Description" #: Default section. class KernelEntry: + """ + Encapsulates a Kernel documentation entry. + """ def __init__(self, config, fname, ln): self.config = config @@ -288,14 +292,16 @@ class KernelEntry: # Management of section contents # def add_text(self, text): + """Add a new text to the entry contents list.""" self._contents.append(text) def contents(self): + """Returns a string with all content texts that were added.""" return '\n'.join(self._contents) + '\n' # TODO: rename to emit_message after removal of kernel-doc.pl def emit_msg(self, ln, msg, *, warning=True): - """Emit a message""" + """Emit a message.""" log_msg = f"{self.fname}:{ln} {msg}" @@ -309,10 +315,10 @@ class KernelEntry: self.warnings.append(log_msg) return - # - # Begin a new section. - # def begin_section(self, line_no, title = SECTION_DEFAULT, dump = False): + """ + Begin a new section. + """ if dump: self.dump_section(start_new = True) self.section = title @@ -366,11 +372,13 @@ class KernelDoc: documentation comments. """ - # Section names - + #: Name of context section. section_context = "Context" + + #: Name of return section. section_return = "Return" + #: String to write when a parameter is not described. undescribed = "-- undescribed --" def __init__(self, config, fname): @@ -416,7 +424,7 @@ class KernelDoc: def dump_section(self, start_new=True): """ - Dumps section contents to arrays/hashes intended for that purpose. + Dump section contents to arrays/hashes intended for that purpose. """ if self.entry: @@ -425,9 +433,9 @@ class KernelDoc: # TODO: rename it to store_declaration after removal of kernel-doc.pl def output_declaration(self, dtype, name, **args): """ - Stores the entry into an entry array. + Store the entry into an entry array. - The actual output and output filters will be handled elsewhere + The actual output and output filters will be handled elsewhere. """ item = KdocItem(name, self.fname, dtype, @@ -448,18 +456,37 @@ class KernelDoc: self.config.log.debug("Output: %s:%s = %s", dtype, name, pformat(args)) + def emit_unused_warnings(self): + """ + When the parser fails to produce a valid entry, it places some + warnings under `entry.warnings` that will be discarded when resetting + the state. + + Ensure that those warnings are not lost. + + .. note:: + + Because we are calling `config.warning()` here, those + warnings are not filtered by the `-W` parameters: they will all + be produced even when `-Wreturn`, `-Wshort-desc`, and/or + `-Wcontents-before-sections` are used. + + Allowing those warnings to be filtered is complex, because it + would require storing them in a buffer and then filtering them + during the output step of the code, depending on the + selected symbols. + """ + if self.entry and self.entry not in self.entries: + for log_msg in self.entry.warnings: + self.config.warning(log_msg) + def reset_state(self, ln): """ Ancillary routine to create a new entry. It initializes all variables used by the state machine. """ - # - # Flush the warnings out before we proceed further - # - if self.entry and self.entry not in self.entries: - for log_msg in self.entry.warnings: - self.config.log.warning(log_msg) + self.emit_unused_warnings() self.entry = KernelEntry(self.config, self.fname, ln) @@ -663,10 +690,12 @@ class KernelDoc: self.emit_msg(ln, f"No description found for return value of '{declaration_name}'") - # - # Split apart a structure prototype; returns (struct|union, name, members) or None - # def split_struct_proto(self, proto): + """ + Split apart a structure prototype; returns (struct|union, name, + members) or ``None``. + """ + type_pattern = r'(struct|union)' qualifiers = [ "__attribute__", @@ -685,21 +714,26 @@ class KernelDoc: if r.search(proto): return (r.group(1), r.group(3), r.group(2)) return None - # - # Rewrite the members of a structure or union for easier formatting later on. - # Among other things, this function will turn a member like: - # - # struct { inner_members; } foo; - # - # into: - # - # struct foo; inner_members; - # + def rewrite_struct_members(self, members): + """ + Process ``struct``/``union`` members from the most deeply nested + outward. + + Rewrite the members of a ``struct`` or ``union`` for easier formatting + later on. Among other things, this function will turn a member like:: + + struct { inner_members; } foo; + + into:: + + struct foo; inner_members; + """ + # - # Process struct/union members from the most deeply nested outward. The - # trick is in the ^{ below - it prevents a match of an outer struct/union - # until the inner one has been munged (removing the "{" in the process). + # The trick is in the ``^{`` below - it prevents a match of an outer + # ``struct``/``union`` until the inner one has been munged + # (removing the ``{`` in the process). # struct_members = KernRe(r'(struct|union)' # 0: declaration type r'([^\{\};]+)' # 1: possible name @@ -777,11 +811,12 @@ class KernelDoc: tuples = struct_members.findall(members) return members - # - # Format the struct declaration into a standard form for inclusion in the - # resulting docs. - # def format_struct_decl(self, declaration): + """ + Format the ``struct`` declaration into a standard form for inclusion + in the resulting docs. + """ + # # Insert newlines, get rid of extra spaces. # @@ -815,7 +850,7 @@ class KernelDoc: def dump_struct(self, ln, proto): """ - Store an entry for a struct or union + Store an entry for a ``struct`` or ``union`` """ # # Do the basic parse to get the pieces of the declaration. @@ -857,7 +892,7 @@ class KernelDoc: def dump_enum(self, ln, proto): """ - Stores an enum inside self.entries array. + Store an ``enum`` inside self.entries array. """ # # Strip preprocessor directives. Note that this depends on the @@ -927,9 +962,84 @@ class KernelDoc: self.output_declaration('enum', declaration_name, purpose=self.entry.declaration_purpose) + def dump_var(self, ln, proto): + """ + Store variables that are part of kAPI. + """ + VAR_ATTRIBS = [ + "extern", + ] + OPTIONAL_VAR_ATTR = "^(?:" + "|".join(VAR_ATTRIBS) + ")?" + + sub_prefixes = [ + (KernRe(r"__read_mostly"), ""), + (KernRe(r"__ro_after_init"), ""), + (KernRe(r"(?://.*)$"), ""), + (KernRe(r"(?:/\*.*\*/)"), ""), + (KernRe(r";$"), ""), + (KernRe(r"=.*"), ""), + ] + + # + # Store the full prototype before modifying it + # + full_proto = proto + declaration_name = None + + # + # Handle macro definitions + # + macro_prefixes = [ + KernRe(r"DEFINE_[\w_]+\s*\(([\w_]+)\)"), + ] + + for r in macro_prefixes: + match = r.search(proto) + if match: + declaration_name = match.group(1) + break + + # + # Drop comments and macros to have a pure C prototype + # + if not declaration_name: + for r, sub in sub_prefixes: + proto = r.sub(sub, proto) + + proto = proto.rstrip() + + # + # Variable name is at the end of the declaration + # + + default_val = None + + r= KernRe(OPTIONAL_VAR_ATTR + r"\w.*\s+(?:\*+)?([\w_]+)\s*[\d\]\[]*\s*(=.*)?") + if r.match(proto): + if not declaration_name: + declaration_name = r.group(1) + + default_val = r.group(2) + else: + r= KernRe(OPTIONAL_VAR_ATTR + r"(?:\w.*)?\s+(?:\*+)?(?:[\w_]+)\s*[\d\]\[]*\s*(=.*)?") + if r.match(proto): + default_val = r.group(1) + + if not declaration_name: + self.emit_msg(ln,f"{proto}: can't parse variable") + return + + if default_val: + default_val = default_val.lstrip("=").strip() + + self.output_declaration("var", declaration_name, + full_proto=full_proto, + default_val=default_val, + purpose=self.entry.declaration_purpose) + def dump_declaration(self, ln, prototype): """ - Stores a data declaration inside self.entries array. + Store a data declaration inside self.entries array. """ if self.entry.decl_type == "enum": @@ -938,13 +1048,15 @@ class KernelDoc: self.dump_typedef(ln, prototype) elif self.entry.decl_type in ["union", "struct"]: self.dump_struct(ln, prototype) + elif self.entry.decl_type == "var": + self.dump_var(ln, prototype) else: # This would be a bug self.emit_message(ln, f'Unknown declaration type: {self.entry.decl_type}') def dump_function(self, ln, prototype): """ - Stores a function or function macro inside self.entries array. + Store a function or function macro inside self.entries array. """ found = func_macro = False @@ -1045,7 +1157,7 @@ class KernelDoc: def dump_typedef(self, ln, proto): """ - Stores a typedef inside self.entries array. + Store a ``typedef`` inside self.entries array. """ # # We start by looking for function typedefs. @@ -1099,7 +1211,7 @@ class KernelDoc: @staticmethod def process_export(function_set, line): """ - process EXPORT_SYMBOL* tags + process ``EXPORT_SYMBOL*`` tags This method doesn't use any variable from the class, so declare it with a staticmethod decorator. @@ -1130,7 +1242,7 @@ class KernelDoc: def process_normal(self, ln, line): """ - STATE_NORMAL: looking for the /** to begin everything. + STATE_NORMAL: looking for the ``/**`` to begin everything. """ if not doc_start.match(line): @@ -1220,10 +1332,10 @@ class KernelDoc: else: self.emit_msg(ln, f"Cannot find identifier on line:\n{line}") - # - # Helper function to determine if a new section is being started. - # def is_new_section(self, ln, line): + """ + Helper function to determine if a new section is being started. + """ if doc_sect.search(line): self.state = state.BODY # @@ -1255,10 +1367,10 @@ class KernelDoc: return True return False - # - # Helper function to detect (and effect) the end of a kerneldoc comment. - # def is_comment_end(self, ln, line): + """ + Helper function to detect (and effect) the end of a kerneldoc comment. + """ if doc_end.search(line): self.dump_section() @@ -1277,7 +1389,7 @@ class KernelDoc: def process_decl(self, ln, line): """ - STATE_DECLARATION: We've seen the beginning of a declaration + STATE_DECLARATION: We've seen the beginning of a declaration. """ if self.is_new_section(ln, line) or self.is_comment_end(ln, line): return @@ -1306,7 +1418,7 @@ class KernelDoc: def process_special(self, ln, line): """ - STATE_SPECIAL_SECTION: a section ending with a blank line + STATE_SPECIAL_SECTION: a section ending with a blank line. """ # # If we have hit a blank line (only the " * " marker), then this @@ -1396,7 +1508,7 @@ class KernelDoc: def syscall_munge(self, ln, proto): # pylint: disable=W0613 """ - Handle syscall definitions + Handle syscall definitions. """ is_void = False @@ -1435,7 +1547,7 @@ class KernelDoc: def tracepoint_munge(self, ln, proto): """ - Handle tracepoint definitions + Handle tracepoint definitions. """ tracepointname = None @@ -1471,7 +1583,7 @@ class KernelDoc: return proto def process_proto_function(self, ln, line): - """Ancillary routine to process a function prototype""" + """Ancillary routine to process a function prototype.""" # strip C99-style comments to end of line line = KernRe(r"//.*$", re.S).sub('', line) @@ -1516,7 +1628,9 @@ class KernelDoc: self.reset_state(ln) def process_proto_type(self, ln, line): - """Ancillary routine to process a type""" + """ + Ancillary routine to process a type. + """ # Strip C99-style comments and surrounding whitespace line = KernRe(r"//.*$", re.S).sub('', line).strip() @@ -1570,7 +1684,7 @@ class KernelDoc: self.process_proto_type(ln, line) def process_docblock(self, ln, line): - """STATE_DOCBLOCK: within a DOC: block.""" + """STATE_DOCBLOCK: within a ``DOC:`` block.""" if doc_end.search(line): self.dump_section() @@ -1582,7 +1696,7 @@ class KernelDoc: def parse_export(self): """ - Parses EXPORT_SYMBOL* macros from a single Kernel source file. + Parses ``EXPORT_SYMBOL*`` macros from a single Kernel source file. """ export_table = set() @@ -1599,10 +1713,7 @@ class KernelDoc: return export_table - # - # The state/action table telling us which function to invoke in - # each state. - # + #: The state/action table telling us which function to invoke in each state. state_actions = { state.NORMAL: process_normal, state.NAME: process_name, @@ -1664,6 +1775,8 @@ class KernelDoc: # Hand this line to the appropriate state handler self.state_actions[self.state](self, ln, line) + self.emit_unused_warnings() + except OSError: self.config.log.error(f"Error: Cannot open file {self.fname}") diff --git a/tools/lib/python/kdoc/kdoc_re.py b/tools/lib/python/kdoc/kdoc_re.py index 2dfa1bf83d64..0bf9e01cdc57 100644 --- a/tools/lib/python/kdoc/kdoc_re.py +++ b/tools/lib/python/kdoc/kdoc_re.py @@ -51,6 +51,9 @@ class KernRe: """ return self.regex.pattern + def __repr__(self): + return f're.compile("{self.regex.pattern}")' + def __add__(self, other): """ Allows adding two regular expressions into one. @@ -61,7 +64,7 @@ class KernRe: def match(self, string): """ - Handles a re.match storing its results + Handles a re.match storing its results. """ self.last_match = self.regex.match(string) @@ -69,7 +72,7 @@ class KernRe: def search(self, string): """ - Handles a re.search storing its results + Handles a re.search storing its results. """ self.last_match = self.regex.search(string) @@ -77,28 +80,28 @@ class KernRe: def findall(self, string): """ - Alias to re.findall + Alias to re.findall. """ return self.regex.findall(string) def split(self, string): """ - Alias to re.split + Alias to re.split. """ return self.regex.split(string) def sub(self, sub, string, count=0): """ - Alias to re.sub + Alias to re.sub. """ return self.regex.sub(sub, string, count=count) def group(self, num): """ - Returns the group results of the last match + Returns the group results of the last match. """ return self.last_match.group(num) @@ -110,7 +113,7 @@ class NestedMatch: even harder on Python with its normal re module, as there are several advanced regular expressions that are missing. - This is the case of this pattern: + This is the case of this pattern:: '\\bSTRUCT_GROUP(\\(((?:(?>[^)(]+)|(?1))*)\\))[^;]*;' @@ -121,6 +124,7 @@ class NestedMatch: replace nested expressions. The original approach was suggested by: + https://stackoverflow.com/questions/5454322/python-how-to-match-nested-parentheses-with-regex Although I re-implemented it to make it more generic and match 3 types @@ -224,14 +228,18 @@ class NestedMatch: yield line[t[0]:t[2]] def sub(self, regex, sub, line, count=0): - """ + r""" This is similar to re.sub: It matches a regex that it is followed by a delimiter, replacing occurrences only if all delimiters are paired. - if r'\1' is used, it works just like re: it places there the - matched paired data with the delimiter stripped. + if the sub argument contains:: + + r'\1' + + it will work just like re: it places there the matched paired data + with the delimiter stripped. If count is different than zero, it will replace at most count items. diff --git a/tools/lib/python/kdoc/latex_fonts.py b/tools/lib/python/kdoc/latex_fonts.py index 29317f8006ea..1d04cbda169f 100755 --- a/tools/lib/python/kdoc/latex_fonts.py +++ b/tools/lib/python/kdoc/latex_fonts.py @@ -5,12 +5,13 @@ # Ported to Python by (c) Mauro Carvalho Chehab, 2025 """ -Detect problematic Noto CJK variable fonts. +Detect problematic Noto CJK variable fonts +========================================== -For "make pdfdocs", reports of build errors of translations.pdf started -arriving early 2024 [1, 2]. It turned out that Fedora and openSUSE -tumbleweed have started deploying variable-font [3] format of "Noto CJK" -fonts [4, 5]. For PDF, a LaTeX package named xeCJK is used for CJK +For ``make pdfdocs``, reports of build errors of translations.pdf started +arriving early 2024 [1]_ [2]_. It turned out that Fedora and openSUSE +tumbleweed have started deploying variable-font [3]_ format of "Noto CJK" +fonts [4]_ [5]_. For PDF, a LaTeX package named xeCJK is used for CJK (Chinese, Japanese, Korean) pages. xeCJK requires XeLaTeX/XeTeX, which does not (and likely never will) understand variable fonts for historical reasons. @@ -25,68 +26,77 @@ This script is invoked from the error path of "make pdfdocs" and emits suggestions if variable-font files of "Noto CJK" fonts are in the list of fonts accessible from XeTeX. -References: -[1]: https://lore.kernel.org/r/8734tqsrt7.fsf@meer.lwn.net/ -[2]: https://lore.kernel.org/r/1708585803.600323099@f111.i.mail.ru/ -[3]: https://en.wikipedia.org/wiki/Variable_font -[4]: https://fedoraproject.org/wiki/Changes/Noto_CJK_Variable_Fonts -[5]: https://build.opensuse.org/request/show/1157217 +.. [1] https://lore.kernel.org/r/8734tqsrt7.fsf@meer.lwn.net/ +.. [2] https://lore.kernel.org/r/1708585803.600323099@f111.i.mail.ru/ +.. [3] https://en.wikipedia.org/wiki/Variable_font +.. [4] https://fedoraproject.org/wiki/Changes/Noto_CJK_Variable_Fonts +.. [5] https://build.opensuse.org/request/show/1157217 -#=========================================================================== Workarounds for building translations.pdf -#=========================================================================== +----------------------------------------- * Denylist "variable font" Noto CJK fonts. + - Create $HOME/deny-vf/fontconfig/fonts.conf from template below, with tweaks if necessary. Remove leading "". + - Path of fontconfig/fonts.conf can be overridden by setting an env variable FONTS_CONF_DENY_VF. - * Template: ------------------------------------------------------------------ -<?xml version="1.0"?> -<!DOCTYPE fontconfig SYSTEM "urn:fontconfig:fonts.dtd"> -<fontconfig> -<!-- - Ignore variable-font glob (not to break xetex) ---> - <selectfont> - <rejectfont> - <!-- - for Fedora - --> - <glob>/usr/share/fonts/google-noto-*-cjk-vf-fonts</glob> - <!-- - for openSUSE tumbleweed - --> - <glob>/usr/share/fonts/truetype/Noto*CJK*-VF.otf</glob> - </rejectfont> - </selectfont> -</fontconfig> ------------------------------------------------------------------ + * Template:: + + <?xml version="1.0"?> + <!DOCTYPE fontconfig SYSTEM "urn:fontconfig:fonts.dtd"> + <fontconfig> + <!-- + Ignore variable-font glob (not to break xetex) + --> + <selectfont> + <rejectfont> + <!-- + for Fedora + --> + <glob>/usr/share/fonts/google-noto-*-cjk-vf-fonts</glob> + <!-- + for openSUSE tumbleweed + --> + <glob>/usr/share/fonts/truetype/Noto*CJK*-VF.otf</glob> + </rejectfont> + </selectfont> + </fontconfig> The denylisting is activated for "make pdfdocs". * For skipping CJK pages in PDF + - Uninstall texlive-xecjk. Denylisting is not needed in this case. * For printing CJK pages in PDF + - Need non-variable "Noto CJK" fonts. + * Fedora + - google-noto-sans-cjk-fonts - google-noto-serif-cjk-fonts + * openSUSE tumbleweed + - Non-variable "Noto CJK" fonts are not available as distro packages as of April, 2024. Fetch a set of font files from upstream Noto CJK Font released at: + https://github.com/notofonts/noto-cjk/tree/main/Sans#super-otc + and at: + https://github.com/notofonts/noto-cjk/tree/main/Serif#super-otc - , then uncompress and deploy them. + + then uncompress and deploy them. - Remember to update fontconfig cache by running fc-cache. -!!! Caution !!! +.. caution:: Uninstalling "variable font" packages can be dangerous. They might be depended upon by other packages important for your work. Denylisting should be less invasive, as it is effective only while @@ -115,10 +125,15 @@ class LatexFontChecker: self.re_cjk = re.compile(r"([^:]+):\s*Noto\s+(Sans|Sans Mono|Serif) CJK") def description(self): + """ + Returns module description. + """ return __doc__ def get_noto_cjk_vf_fonts(self): - """Get Noto CJK fonts""" + """ + Get Noto CJK fonts. + """ cjk_fonts = set() cmd = ["fc-list", ":", "file", "family", "variable"] @@ -143,7 +158,9 @@ class LatexFontChecker: return sorted(cjk_fonts) def check(self): - """Check for problems with CJK fonts""" + """ + Check for problems with CJK fonts. + """ fonts = textwrap.indent("\n".join(self.get_noto_cjk_vf_fonts()), " ") if not fonts: diff --git a/tools/lib/python/kdoc/parse_data_structs.py b/tools/lib/python/kdoc/parse_data_structs.py index 25361996cd20..9941cd19032e 100755 --- a/tools/lib/python/kdoc/parse_data_structs.py +++ b/tools/lib/python/kdoc/parse_data_structs.py @@ -9,12 +9,12 @@ Parse a source file or header, creating ReStructured Text cross references. It accepts an optional file to change the default symbol reference or to suppress symbols from the output. -It is capable of identifying defines, functions, structs, typedefs, -enums and enum symbols and create cross-references for all of them. +It is capable of identifying ``define``, function, ``struct``, ``typedef``, +``enum`` and ``enum`` symbols and create cross-references for all of them. It is also capable of distinguish #define used for specifying a Linux ioctl. -The optional rules file contains a set of rules like: +The optional rules file contains a set of rules like:: ignore ioctl VIDIOC_ENUM_FMT replace ioctl VIDIOC_DQBUF vidioc_qbuf @@ -34,8 +34,8 @@ class ParseDataStructs: It is meant to allow having a more comprehensive documentation, where uAPI headers will create cross-reference links to the code. - It is capable of identifying defines, functions, structs, typedefs, - enums and enum symbols and create cross-references for all of them. + It is capable of identifying ``define``, function, ``struct``, ``typedef``, + ``enum`` and ``enum`` symbols and create cross-references for all of them. It is also capable of distinguish #define used for specifying a Linux ioctl. @@ -43,13 +43,13 @@ class ParseDataStructs: allows parsing an exception file. Such file contains a set of rules using the syntax below: - 1. Ignore rules: + 1. Ignore rules:: ignore <type> <symbol>` Removes the symbol from reference generation. - 2. Replace rules: + 2. Replace rules:: replace <type> <old_symbol> <new_reference> @@ -58,22 +58,22 @@ class ParseDataStructs: - A simple symbol name; - A full Sphinx reference. - 3. Namespace rules + 3. Namespace rules:: namespace <namespace> Sets C namespace to be used during cross-reference generation. Can be overridden by replace rules. - On ignore and replace rules, <type> can be: - - ioctl: for defines that end with _IO*, e.g. ioctl definitions - - define: for other defines - - symbol: for symbols defined within enums; - - typedef: for typedefs; - - enum: for the name of a non-anonymous enum; - - struct: for structs. + On ignore and replace rules, ``<type>`` can be: + - ``ioctl``: for defines that end with ``_IO*``, e.g. ioctl definitions + - ``define``: for other defines + - ``symbol``: for symbols defined within enums; + - ``typedef``: for typedefs; + - ``enum``: for the name of a non-anonymous enum; + - ``struct``: for structs. - Examples: + Examples:: ignore define __LINUX_MEDIA_H ignore ioctl VIDIOC_ENUM_FMT @@ -83,13 +83,15 @@ class ParseDataStructs: namespace MC """ - # Parser regexes with multiple ways to capture enums and structs + #: Parser regex with multiple ways to capture enums. RE_ENUMS = [ re.compile(r"^\s*enum\s+([\w_]+)\s*\{"), re.compile(r"^\s*enum\s+([\w_]+)\s*$"), re.compile(r"^\s*typedef\s*enum\s+([\w_]+)\s*\{"), re.compile(r"^\s*typedef\s*enum\s+([\w_]+)\s*$"), ] + + #: Parser regex with multiple ways to capture structs. RE_STRUCTS = [ re.compile(r"^\s*struct\s+([_\w][\w\d_]+)\s*\{"), re.compile(r"^\s*struct\s+([_\w][\w\d_]+)$"), @@ -97,11 +99,13 @@ class ParseDataStructs: re.compile(r"^\s*typedef\s*struct\s+([_\w][\w\d_]+)$"), ] - # FIXME: the original code was written a long time before Sphinx C + # NOTE: the original code was written a long time before Sphinx C # domain to have multiple namespaces. To avoid to much turn at the # existing hyperlinks, the code kept using "c:type" instead of the # right types. To change that, we need to change the types not only # here, but also at the uAPI media documentation. + + #: Dictionary containing C type identifiers to be transformed. DEF_SYMBOL_TYPES = { "ioctl": { "prefix": "\\ ", @@ -158,6 +162,10 @@ class ParseDataStructs: self.symbols[symbol_type] = {} def read_exceptions(self, fname: str): + """ + Read an optional exceptions file, used to override defaults. + """ + if not fname: return @@ -242,9 +250,9 @@ class ParseDataStructs: def store_type(self, ln, symbol_type: str, symbol: str, ref_name: str = None, replace_underscores: bool = True): """ - Stores a new symbol at self.symbols under symbol_type. + Store a new symbol at self.symbols under symbol_type. - By default, underscores are replaced by "-" + By default, underscores are replaced by ``-``. """ defs = self.DEF_SYMBOL_TYPES[symbol_type] @@ -276,12 +284,16 @@ class ParseDataStructs: self.symbols[symbol_type][symbol] = (f"{prefix}{ref_link}{suffix}", ln) def store_line(self, line): - """Stores a line at self.data, properly indented""" + """ + Store a line at self.data, properly indented. + """ line = " " + line.expandtabs() self.data += line.rstrip(" ") def parse_file(self, file_in: str, exceptions: str = None): - """Reads a C source file and get identifiers""" + """ + Read a C source file and get identifiers. + """ self.data = "" is_enum = False is_comment = False @@ -433,7 +445,7 @@ class ParseDataStructs: def gen_toc(self): """ - Create a list of symbols to be part of a TOC contents table + Create a list of symbols to be part of a TOC contents table. """ text = [] @@ -464,6 +476,10 @@ class ParseDataStructs: return "\n".join(text) def write_output(self, file_in: str, file_out: str, toc: bool): + """ + Write a ReST output file. + """ + title = os.path.basename(file_in) if toc: diff --git a/tools/lib/python/kdoc/python_version.py b/tools/lib/python/kdoc/python_version.py index e83088013db2..4ddb7ead5f56 100644 --- a/tools/lib/python/kdoc/python_version.py +++ b/tools/lib/python/kdoc/python_version.py @@ -33,21 +33,31 @@ class PythonVersion: """ def __init__(self, version): - """Ïnitialize self.version tuple from a version string""" + """ + Ïnitialize self.version tuple from a version string. + """ self.version = self.parse_version(version) @staticmethod def parse_version(version): - """Convert a major.minor.patch version into a tuple""" + """ + Convert a major.minor.patch version into a tuple. + """ return tuple(int(x) for x in version.split(".")) @staticmethod def ver_str(version): - """Returns a version tuple as major.minor.patch""" + """ + Returns a version tuple as major.minor.patch. + """ return ".".join([str(x) for x in version]) @staticmethod def cmd_print(cmd, max_len=80): + """ + Outputs a command line, repecting maximum width. + """ + cmd_line = [] for w in cmd: @@ -66,7 +76,9 @@ class PythonVersion: return "\n ".join(cmd_line) def __str__(self): - """Returns a version tuple as major.minor.patch from self.version""" + """ + Return a version tuple as major.minor.patch from self.version. + """ return self.ver_str(self.version) @staticmethod |
