# Technical Documentation: raspberrypi/linux

> ℹ️ **Provenance:** Multi-Tier Ingestion · [CodeWiki Reference](https://codewiki.google/github.com/raspberrypi/linux)

### Overview (README.md)

Linux kernel
============

There are several guides for kernel developers and users. These guides can
be rendered in a number of formats, like HTML and PDF. Please read
Documentation/admin-guide/README.rst first.

In order to build the documentation, use ``make htmldocs`` or
``make pdfdocs``.  The formatted documentation can also be read online at:

    https://www.kernel.org/doc/html/latest/

There are various text files in the Documentation/ subdirectory,
several of them using the Restructured Text markup notation.

Please read the Documentation/process/changes.rst file, as it contains the
requirements for building and running the kernel, and information about
the problems which may result by upgrading your kernel.

Build status for rpi-6.12.y:
[](https://github.com/raspberrypi/linux/actions/workflows/kernel-build.yml)
[](https://github.com/raspberrypi/linux/actions/workflows/dtoverlaycheck.yml)

Build status for rpi-6.18.y:
[](https://github.com/raspberrypi/linux/actions/workflows/kernel-build.yml)
[](https://github.com/raspberrypi/linux/actions/workflows/dtoverlaycheck.yml)

---

### Documentation .Renames (`Documentation/.renames.txt`)

80211/cfg80211 driver-api/80211/cfg80211
80211/index driver-api/80211/index
80211/introduction driver-api/80211/introduction
80211/mac80211 driver-api/80211/mac80211
80211/mac80211-advanced driver-api/80211/mac80211-advanced
EDID/howto admin-guide/edid
PCI/picebus-howto PCI/pciebus-howto
RAS/address-translation admin-guide/RAS/address-translation
RAS/error-decoding admin-guide/RAS/error-decoding
RAS/ras admin-guide/RAS/error-decoding
accelerators/ocxl userspace-api/accelerators/ocxl
admin-guide/gpio/sysfs userspace-api/gpio/sysfs
admin-guide/l1tf admin-guide/hw-vuln/l1tf
admin-guide/media/v4l-with-ir admin-guide/media/remote-controller
admin-guide/ras admin-guide/RAS/main
admin-guide/security-bugs process/security-bugs
aoe/aoe admin-guide/aoe/aoe
aoe/examples admin-guide/aoe/examples
aoe/index admin-guide/aoe/index
aoe/todo admin-guide/aoe/todo
arc/arc arch/arc/arc
arc/features arch/arc/features
arc/index arch/arc/index
arch/x86/resctrl filesystems/resctrl
arm/arm arch/arm/arm
arm/booting arch/arm/booting
arm/cluster-pm-race-avoidance arch/arm/cluster-pm-race-avoidance
arm/features arch/arm/features
arm/firmware arch/arm/firmware
arm/google/chromebook-boot-flow arch/arm/google/chromebook-boot-flow
arm/index arch/arm/index
arm/interrupts arch/arm/interrupts
arm/ixp4xx arch/arm/ixp4xx
arm/kernel_mode_neon arch/arm/kernel_mode_neon
arm/kernel_user_helpers arch/arm/kernel_user_helpers
arm/keystone/knav-qmss arch/arm/keystone/knav-qmss
arm/keystone/overview arch/arm/keystone/overview
arm/marvel arch/arm/marvell
arm/marvell arch/arm/marvell
arm/mem_alignment arch/arm/mem_alignment
arm/memory arch/arm/memory
arm/microchip arch/arm/microchip
arm/netwinder arch/arm/netwinder
arm/nwfpe/index arch/arm/nwfpe/index
arm/nwfpe/netwinder-fpe arch/arm/nwfpe/netwinder-fpe
arm/nwfpe/notes arch/arm/nwfpe/notes
arm/nwfpe/nwfpe arch/arm/nwfpe/nwfpe
arm/nwfpe/todo arch/arm/nwfpe/todo
arm/omap/dss arch/arm/omap/dss
arm/omap/index arch/arm/omap/index
arm/omap/omap arch/arm/omap/omap
arm/omap/omap_pm arch/arm/omap/omap_pm
arm/porting arch/arm/porting
arm/pxa/mfp arch/arm/pxa/mfp
arm/sa1100/assabet arch/arm/sa1100/assabet
arm/sa1100/cerf arch/arm/sa1100/cerf
arm/sa1100/index arch/arm/sa1100/index
arm/sa1100/lart arch/arm/sa1100/lart
arm/sa1100/serial_uart arch/arm/sa1100/serial_uart
arm/samsung/bootloader-interface arch/arm/samsung/bootloader-interface
arm/samsung/gpio arch/arm/samsung/gpio
arm/samsung/index arch/arm/samsung/index
arm/samsung/overview arch/arm/samsung/overview
arm/setup arch/arm/setup
arm/spear/overview arch/arm/spear/overview
arm/sti/overview arch/arm/sti/overview
arm/sti/stih407-overview arch/arm/sti/stih407-overview
arm/sti/stih418-overview arch/arm/sti/stih418-overview
arm/stm32/overview arch/arm/stm32/overview
arm/stm32/stm32-dma-mdma-chaining arch/arm/stm32/stm32-dma-mdma-chaining
arm/stm32/stm32f429-overview arch/arm/stm32/stm32f429-overview
arm/stm32/stm32f746-overview arch/arm/stm32/stm32f746-overview
arm/stm32/stm32f769-overview arch/arm/stm32/stm32f769-overview
arm/stm32/stm32h743-overview arch/arm/stm32/stm32h743-overview
arm/stm32/stm32h750-overview arch/arm/stm32/stm32h750-overview
arm/stm32/stm32mp13-overview arch/arm/stm32/stm32mp13-overview
arm/stm32/stm32mp151-overview arch/arm/stm32/stm32mp151-overview
arm/stm32/stm32mp157-overview arch/arm/stm32/stm32mp157-overview
arm/sunxi arch/arm/sunxi
arm/sunxi/clocks arch/arm/sunxi/clocks
arm/swp_emulation arch/arm/swp_emulation
arm/tcm arch/arm/tcm
arm/uefi arch/arm/uefi
arm/vfp/release-notes arch/arm/vfp/release-notes
arm/vlocks arch/arm/vlocks
arm64/acpi_object_usage arch/arm64/acpi_object_usage
arm64/amu arch/arm64/amu
arm64/arm-acpi arch/arm64/arm-acpi
arm64/asymmetric-32bit arch/arm64/asymmetric-32bit
arm64/booting arch/arm64/booting
arm64/cpu-feature-registers arch/arm64/cpu-feature-registers
arm64/elf_hwcaps arch/arm64/elf_hwcaps
arm64/features arch/arm64/features
arm64/hugetlbpage arch/arm64/hugetlbpage
arm64/index arch/arm64/index
arm64/legacy_instructions arch/arm64/legacy_instructions
arm64/memory arch/arm64/memory
arm64/memory-tagging-extension arch/arm64/memory-tagging-extension
arm64/perf arch/arm64/perf
arm64/pointer-authentication arch/arm64/pointer-authentication
arm64/silicon-errata arch/arm64/silicon-errata
arm64/sme arch/arm64/sme
arm64/sve arch/arm64/sve
arm64/tagged-address-abi arch/arm64/tagged-address-abi
arm64/tagged-pointers arch/arm64/tagged-pointers
asm-annotations core-api/asm-annotations
auxdisplay/lcd-panel-cgram admin-guide/lcd-panel-cgram
backlight/lp855x-driver driver-api/backlight/lp855x-driver
blockdev/drbd/data-structure-v9 admin-guide/blockdev/drbd/data-structure-v9
blockdev/drbd/figures admin-guide/blockdev/drbd/figures
blockdev/drbd/index admin-guide/blockdev/drbd/index
blockdev/floppy admin-guide/blockdev/floppy
blockdev/index admin-guide/blockdev/index
blockdev/nbd admin-guide/blockdev/nbd
blockdev/paride admin-guide/blockdev/paride
blockdev/ramdisk admin-guide/blockdev/ramdisk
blockdev/zram admin-guide/blockdev/zram
bpf/README bpf/index
bpf/bpf_lsm bpf/prog_lsm
bpf/instruction-set bpf/standardization/instruction-set
bpf/libbpf/libbpf bpf/libbpf/index
bpf/standardization/linux-notes bpf/linux-notes
bus-devices/ti-gpmc driver-api/memory-devices/ti-gpmc
cgroup-v1/blkio-controller admin-guide/cgroup-v1/blkio-controller
cgroup-v1/cgroups admin-guide/cgroup-v1/cgroups
cgroup-v1/cpuacct admin-guide/cgroup-v1/cpuacct
cgroup-v1/cpusets admin-guide/cgroup-v1/cpusets
cgroup-v1/devices admin-guide/cgroup-v1/devices
cgroup-v1/freezer-subsystem admin-guide/cgroup-v1/freezer-subsystem
cgroup-v1/hugetlb admin-guide/cgroup-v1/hugetlb
cgroup-v1/index admin-guide/cgroup-v1/index
cgroup-v1/memcg_test admin-guide/cgroup-v1/memcg_test
cgroup-v1/memory admin-guide/cgroup-v1/memory
cgroup-v1/net_cls admin-guide/cgroup-v1/net_cls
cgroup-v1/net_prio admin-guide/cgroup-v1/net_prio
cgroup-v1/pids admin-guide/cgroup-v1/pids
cgroup-v1/rdma admin-guide/cgroup-v1/rdma
cma/debugfs admin-guide/mm/cma_debugfs
connector/connector driver-api/connector
console/console driver-api/console
core-api/gcc-plugins kbuild/gcc-plugins
core-api/ioctl driver-api/ioctl
core-api/memory-hotplug-notifier core-api/memory-hotplug
dev-tools/gdb-kernel-debugging process/debugging/gdb-kernel-debugging
dev-tools/kgdb process/debugging/kgdb
dev-tools/tools dev-tools/index
development-process/1.Intro process/1.Intro
development-process/2.Process process/2.Process
development-process/3.Early-stage process/3.Early-stage
development-process/4.Coding process/4.Coding
development-process/5.Posting process/5.Posting
development-process/6.Followthrough process/6.Followthrough
development-process/7.AdvancedTopics process/7.AdvancedTopics
development-process/8.Conclusion process/8.Conclusion
development-process/development-process process/development-process
development-process/index process/index
device-mapper/cache admin-guide/device-mapper/cache
device-mapper/cache-policies admin-guide/device-mapper/cache-policies
device-mapper/delay admin-guide/device-mapper/delay
device-mapper/dm-crypt admin-guide/device-mapper/dm-crypt
device-mapper/dm-flakey admin-guide/device-mapper/dm-flakey
device-mapper/dm-init admin-guide/device-mapper/dm-init
device-mapper/dm-integrity admin-guide/device-mapper/dm-integrity
device-mapper/dm-io admin-guide/device-mapper/dm-io
device-mapper/dm-log admin-guide/device-mapper/dm-log
device-mapper/dm-queue-length admin-guide/device-mapper/dm-queue-length
device-mapper/dm-raid admin-guide/device-mapper/dm-raid
device-mapper/dm-service-time admin-guide/device-mapper/dm-service-time
device-mapper/dm-uevent admin-guide/device-mapper/dm-uevent
device-mapper/dm-zoned admin-guide/device-mapper/dm-zoned
device-mapper/era admin-guide/device-mapper/era
device-mapper/index admin-guide/device-mapper/index
device-mapper/kcopyd admin-guide/device-mapper/kcopyd
device-mapper/linear admin-guide/device-mapper/linear
device-mapper/log-writes admin-guide/device-mapper/log-writes
device-mapper/persistent-data admin-guide/device-mapper/persistent-data
device-mapper/snapshot admin-guide/device-mapper/snapshot
device-mapper/statistics admin-guide/device-mapper/statistics
device-mapper/striped admin-guide/device-mapper/striped
device-mapper/switch admin-guide/device-mapper/switch
device-mapper/thin-provisioning admin-guide/device-mapper/thin-provisioning
device-mapper/unstriped admin-guide/device-mapper/unstriped
device-mapper/verity admin-guide/device-mapper/verity
device-mapper/writecache admin-guide/device-mapper/writecache
device-mapper/zero admin-guide/device-mapper/zero
devicetree/writing-schema devicetree/bindings/writing-schema
driver-api/bt8xxgpio driver-api/gpio/bt8xxgpio
driver-api/cxl/access-coordinates driver-api/cxl/linux/access-coordinates
driver-api/cxl/memory-devices driver-api/cxl/theory-of-operation
driver-api/dcdbas userspace-api/dcdbas
driver-api/dell_rbu admin-guide/dell_rbu
driver-api/edid admin-guide/edid
driver-api/gpio driver-api/gpio/index
driver-api/hte/tegra194-hte driver-api/hte/tegra-hte
driver-api/isapnp userspace-api/isapnp
driver-api/media/drivers/v4l-drivers/zoran driver-api/media/drivers/zoran
driver-api/mtd/intel-spi driver-api/mtd/spi-intel
driver-api/pci driver-api/pci/pci
driver-api/pinctl driver-api/pin-control
driver-api/rapidio admin-guide/rapidio
driver-api/serial/moxa-smartio driver-api/tty/moxa-smartio
driver-api/serial/n_gsm driver-api/tty/n_gsm
driver-api/serial/tty driver-api/tty/tty_ldisc
driver-api/thermal/intel_powerclamp admin-guide/thermal/intel_powerclamp
driver-api/usb driver-api/usb/usb
driver-model/binding driver-api/driver-model/binding
driver-model/bus driver-api/driver-model/bus
driver-model/design-patterns driver-api/driver-model/design-patterns
driver-model/device driver-api/driver-model/device
driver-model/devres driver-api/driver-model/devres
driver-model/driver driver-api/driver-model/driver
driver-model/index driver-api/driver-model/index
driver-model/overview driver-api/driver-model/overview
driver-model/platform driver-api/driver-model/platform
driver-model/porting driver-api/driver-model/porting
early-userspace/buffer-format driver-api/early-userspace/buffer-format
early-userspace/early_userspace_support driver-api/early-userspace/early_userspace_support
early-userspace/index driver-api/early-userspace/index
errseq core-api/errseq
filesystems/binderfs admin-guide/binderfs
filesystems/cifs/cifsd filesystems/smb/ksmbd
filesystems/cifs/cifsroot filesystems/smb/cifsroot
filesystems/cifs/index filesystems/smb/index
filesystems/cifs/ksmbd filesystems/smb/ksmbd
filesystems/ext4/ext4 admin-guide/ext4
filesystems/ext4/ondisk/about filesystems/ext4/about
filesystems/ext4/ondisk/allocators filesystems/ext4/allocators
filesystems/ext4/ondisk/attributes filesystems/ext4/attributes
filesystems/ext4/ondisk/bigalloc filesystems/ext4/bigalloc
filesystems/ext4/ondisk/bitmaps filesystems/ext4/bitmaps
filesystems/ext4/ondisk/blockgroup filesystems/ext4/blockgroup
filesystems/ext4/ondisk/blockmap filesystems/ext4/blockmap
filesystems/ext4/ondisk/blocks filesystems/ext4/blocks
filesystems/ext4/ondisk/checksums filesystems/ext4/checksums
filesystems/ext4/ondisk/directory filesystems/ext4/directory
filesystems/ext4/ondisk/dynamic filesystems/ext4/dynamic
filesystems/ext4/ondisk/eainode filesystems/ext4/eainode
filesystems/ext4/ondisk/globals filesystems/ext4/globals
filesystems/ext4/ondisk/group_descr filesystems/ext4/group_descr
filesystems/ext4/ondisk/ifork filesystems/ext4/ifork
filesystems/ext4/ondisk/inlinedata filesystems/ext4/inlinedata
filesystems/ext4/ondisk/inodes filesystems/ext4/inodes
filesystems/ext4/ondisk/journal filesystems/ext4/journal
filesystems/ext4/ondisk/mmp filesystems/ext4/mmp
filesystems/ext4/ondisk/overview filesystems/ext4/overview
filesystems/ext4/ondisk/special_inodes filesystems/ext4/special_inodes
filesystems/ext4/ondisk/super filesystems/ext4/super
filesystems/sysfs-pci PCI/sysfs-pci
filesystems/sysfs-tagging networking/sysfs-tagging
filesystems/xfs-delayed-logging-design filesystems/xfs/xfs-delayed-logging-design
filesystems/xfs-maintainer-entry-profile filesystems/xfs/xfs-maintainer-entry-profile
filesystems/xfs-online-fsck-design filesystems/xfs/xfs-online-fsck-design
filesystems/xfs-self-describing-metadata filesystems/xfs/xfs-self-describing-metadata
gpio/index admin-guide/gpio/index
gpio/sysfs userspace-api/gpio/sysfs
gpu/amdgpu gpu/amdgpu/index
hte/hte driver-api/hte/hte
hte/index driver-api/hte/index
hte/tegra194-hte driver-api/hte/tegra-hte
input/alps input/devices/alps
input/amijoy input/devices/amijoy
input/appletouch input/devices/appletouch
input/atarikbd input/devices/atarikbd
input/bcm5974 input/devices/bcm5974
input/cma3000_d0x input/devices/cma3000_d0x
input/cs461x input/devices/cs461x
input/edt-ft5x06 input/devices/edt-ft5x06
input/elantech input/devices/elantech
input/iforce-protocol input/devices/iforce-protocol
input/joystick input/joydev/joystick
input/joystick-api input/joydev/joystick-api
input/joystick-parport input/devices/joystick-parport
input/ntrig input/devices/ntrig
input/rotary-encoder input/devices/rotary-encoder
input/sentelic input/devices/sentelic
input/walkera0701 input/devices/walkera0701
input/xpad input/devices/xpad
input/yealink input/devices/yealink
interconnect/interconnect driver-api/interconnect
ioctl/botching-up-ioctls process/botching-up-ioctls
ioctl/cdrom userspace-api/ioctl/cdrom
ioctl/hdio userspace-api/ioctl/hdio
ioctl/index userspace-api/ioctl/index
ioctl/ioctl-decoding userspace-api/ioctl/ioctl-decoding
ioctl/ioctl-number userspace-api/ioctl/ioctl-number
kbuild/namespaces core-api/symbol-namespaces
kdump/index admin-guide/kdump/index
kdump/kdump admin-guide/kdump/kdump
kdump/vmcoreinfo admin-guide/kdump/vmcoreinfo
kernel-documentation doc-guide/kernel-doc
laptops/asus-laptop admin-guide/laptops/asus-laptop
laptops/disk-shock-protection admin-guide/laptops/disk-shock-protection
laptops/index admin-guide/laptops/index
laptops/laptop-mode admin-guide/laptops/laptop-mode
laptops/lg-laptop admin-guide/laptops/lg-laptop
laptops/sony-laptop admin-guide/laptops/sony-laptop
laptops/sonypi admin-guide/laptops/sonypi
laptops/thinkpad-acpi admin-guide/laptops/thinkpad-acpi
laptops/toshiba_haps admin-guide/laptops/toshiba_haps
loongarch/booting arch/loongarch/booting
loongarch/features arch/loongarch/features
loongarch/index arch/loongarch/index
loongarch/introduction arch/loongarch/introduction
loongarch/irq-chip-model arch/loongarch/irq-chip-model
m68k/buddha-driver arch/m68k/buddha-driver
m68k/features arch/m68k/features
m68k/index arch/m68k/index
m68k/kernel-options arch/m68k/kernel-options
md/index driver-api/md/index
md/md-cluster driver-api/md/md-cluster
md/raid5-cache driver-api/md/raid5-cache
md/raid5-ppl driver-api/md/raid5-ppl
media/dvb-drivers/avermedia admin-guide/media/avermedia
media/dvb-drivers/bt8xx admin-guide/media/bt8xx
media/dvb-drivers/ci admin-guide/media/ci
media/dvb-drivers/contributors driver-api/media/drivers/contributors
media/dvb-drivers/dvb-usb driver-api/media/drivers/dvb-usb
media/dvb-drivers/faq admin-guide/media/faq
media/dvb-drivers/frontends driver-api/media/drivers/frontends
media/dvb-drivers/index driver-api/media/drivers/index
media/dvb-drivers/lmedm04 admin-guide/media/lmedm04
media/dvb-drivers/opera-firmware admin-guide/media/opera-firmware
media/dvb-drivers/technisat admin-guide/media/technisat
media/dvb-drivers/ttusb-dec admin-guide/media/ttusb-dec
media/intro userspace-api/media/intro
media/kapi/cec-core driver-api/media/cec-core
media/kapi/dtv-ca driver-api/media/dtv-ca
media/kapi/dtv-common driver-api/media/dtv-common
media/kapi/dtv-core driver-api/media/dtv-core
media/kapi/dtv-demux driver-api/media/dtv-demux
media/kapi/dtv-frontend driver-api/media/dtv-frontend
media/kapi/dtv-net driver-api/media/dtv-net
media/kapi/mc-core driver-api/media/mc-core
media/kapi/rc-core driver-api/media/rc-core
media/kapi/v4l2-async driver-api/media/v4l2-async
media/kapi/v4l2-common driver-api/media/v4l2-common
media/kapi/v4l2-controls driver-api/media/v4l2-controls
media/kapi/v4l2-core driver-api/media/v4l2-core
media/kapi/v4l2-dev driver-api/media/v4l2-dev
media/kapi/v4l2-device driver-api/media/v4l2-device
media/kapi/v4l2-dv-timings driver-api/media/v4l2-dv-timings
media/kapi/v4l2-event driver-api/media/v4l2-event
media/kapi/v4l2-fh driver-api/media/v4l2-fh
media/kapi/v4l2-flash-led-class driver-api/media/v4l2-flash-led-class
media/kapi/v4l2-fwnode driver-api/media/v4l2-fwnode
media/kapi/v4l2-intro driver-api/media/v4l2-intro
media/kapi/v4l2-mc driver-api/media/v4l2-mc
media/kapi/v4l2-mediabus driver-api/media/v4l2-mediabus
media/kapi/v4l2-mem2mem driver-api/media/v4l2-mem2mem
media/kapi/v4l2-rect driver-api/media/v4l2-rect
media/kapi/v4l2-subdev driver-api/media/v4l2-subdev
media/kapi/v4l2-tuner driver-api/media/v4l2-tuner
media/kapi/v4l2-tveeprom driver-api/media/v4l2-tveeprom
media/kapi/v4l2-videobuf2 driver-api/media/v4l2-videobuf2
media/media_kapi driver-api/media/index
media/media_uapi userspace-api/media/index
media/uapi/cec/cec-api userspace-api/media/cec/cec-api
media/uapi/cec/cec-func-close userspace-api/media/cec/cec-func-close
media/uapi/cec/cec-func-ioctl userspace-api/media/cec/cec-func-ioctl
media/uapi/cec/cec-func-open userspace-api/media/cec/cec-func-open
media/uapi/cec/cec-func-poll userspace-api/media/cec/cec-func-poll
media/uapi/cec/cec-funcs userspace-api/media/cec/cec-funcs
media/uapi/cec/cec-header userspace-api/media/cec/cec-header
media/uapi/cec/cec-intro userspace-api/media/cec/cec-intro
media/uapi/cec/cec-ioc-adap-g-caps userspace-api/media/cec/cec-ioc-adap-g-caps
media/uapi/cec/cec-ioc-adap-g-conn-info userspace-api/media/cec/cec-ioc-adap-g-conn-info
media/uapi/cec/cec-ioc-adap-g-log-addrs userspace-api/media/cec/cec-ioc-adap-g-log-addrs
media/uapi/cec/cec-ioc-adap-g-phys-addr userspace-api/media/cec/cec-ioc-adap-g-phys-addr
media/uapi/cec/cec-ioc-dqevent userspace-api/media/cec/cec-ioc-dqevent
media/uapi/cec/cec-ioc-g-mode userspace-api/media/cec/cec-ioc-g-mode
media/uapi/cec/cec-ioc-receive userspace-api/media/cec/cec-ioc-receive
media/uapi/cec/cec-pin-error-inj userspace-api/media/cec/cec-pin-error-inj
media/uapi/dvb/ca userspace-api/media/dvb/ca
media/uapi/dvb/ca-fclose userspace-api/media/dvb/ca-fclose
media/uapi/dvb/ca-fopen userspace-api/media/dvb/ca-fopen
media/uapi/dvb/ca-get-cap userspace-api/media/dvb/ca-get-cap
media/uapi/dvb/ca-get-descr-info userspace-api/media/dvb/ca-get-descr-info
media/uapi/dvb/ca-get-msg userspace-api/media/dvb/ca-get-msg
media/uapi/dvb/ca-get-slot-info userspace-api/media/dvb/ca-get-slot-info
media/uapi/dvb/ca-reset userspace-api/media/dvb/ca-reset
media/uapi/dvb/ca-send-msg userspace-api/media/dvb/ca-send-msg
media/uapi/dvb/ca-set-descr userspace-api/media/dvb/ca-set-descr
media/uapi/dvb/ca_data_types userspace-api/media/dvb/ca_data_types
media/uapi/dvb/ca_function_calls userspace-api/media/dvb/ca_function_calls
media/uapi/dvb/ca_high_level userspace-api/media/dvb/ca_high_level
media/uapi/dvb/demux userspace-api/media/dvb/demux
media/uapi/dvb/dmx-add-pid userspace-api/media/dvb/dmx-add-pid
media/uapi/dvb/dmx-expbuf userspace-api/media/dvb/dmx-expbuf
media/uapi/dvb/dmx-fclose userspace-api/media/dvb/dmx-fclose
media/uapi/dvb/dmx-fopen userspace-api/media/dvb/dmx-fopen
media/uapi/dvb/dmx-fread userspace-api/media/dvb/dmx-fread
media/uapi/dvb/dmx-fwrite userspace-api/media/dvb/dmx-fwrite
media/uapi/dvb/dmx-get-pes-pids userspace-api/media/dvb/dmx-get-pes-pids
media/uapi/dvb/dmx-get-stc userspace-api/media/dvb/dmx-get-stc
media/uapi/dvb/dmx-mmap userspace-api/media/dvb/dmx-mmap
media/uapi/dvb/dmx-munmap userspace-api/media/dvb/dmx-munmap
media/uapi/dvb/dmx-qbuf userspace-api/media/dvb/dmx-qbuf
media/uapi/dvb/dmx-querybuf userspace-api/media/dvb/dmx-querybuf
media/uapi/dvb/dmx-remove-pid userspace-api/media/dvb/dmx-remove-pid
media/uapi/dvb/dmx-reqbufs userspace-api/media/dvb/dmx-reqbufs
media/uapi/dvb/dmx-set-buffer-size userspace-api/media/dvb/dmx-set-buffer-size
media/uapi/dvb/dmx-set-filter userspace-api/media/dvb/dmx-set-filter
media/uapi/dvb/dmx-set-pes-filter userspace-api/media/dvb/dmx-set-pes-filter
media/uapi/dvb/dmx-start userspace-api/media/dvb/dmx-start
media/uapi/dvb/dmx-stop userspace-api/media/dvb/dmx-stop
media/uapi/dvb/dmx_fcalls userspace-api/media/dvb/dmx_fcalls
media/uapi/dvb/dmx_types userspace-api/media/dvb/dmx_types
media/uapi/dvb/dvb-fe-read-status userspace-api/media/dvb/dvb-fe-read-status
media/uapi/dvb/dvb-frontend-event userspace-api/media/dvb/dvb-frontend-event
media/uapi/dvb/dvb-frontend-parameters userspace-api/media/dvb/dvb-frontend-parameters
media/uapi/dvb/dvbapi userspace-api/media/dvb/dvbapi
media/uapi/dvb/dvbproperty userspace-api/media/dvb/dvbproperty
media/uapi/dvb/examples userspace-api/media/dvb/examples
media/uapi/dvb/fe-bandwidth-t userspace-api/media/dvb/fe-bandwidth-t
media/uapi/dvb/fe-diseqc-recv-slave-reply userspace-api/media/dvb/fe-diseqc-recv-slave-reply
media/uapi/dvb/fe-diseqc-reset-overload userspace-api/media/dvb/fe-diseqc-reset-overload
media/uapi/dvb/fe-diseqc-send-burst userspace-api/media/dvb/fe-diseqc-send-burst
media/uapi/dvb/fe-diseqc-send-master-cmd userspace-api/media/dvb/fe-diseqc-send-master-cmd
media/uapi/dvb/fe-dishnetwork-send-legacy-cmd userspace-api/media/dvb/fe-dishnetwork-send-legacy-cmd
media/uapi/dvb/fe-enable-high-lnb-voltage userspace-api/media/dvb/fe-enable-high-lnb-voltage
media/uapi/dvb/fe-get-event userspace-api/media/dvb/fe-get-event
media/uapi/dvb/fe-get-frontend userspace-api/media/dvb/fe-get-frontend
media/uapi/dvb/fe-get-info userspace-api/media/dvb/fe-get-info
media/uapi/dvb/fe-get-property userspace-api/media/dvb/fe-get-property
media/uapi/dvb/fe-read-ber userspace-api/media/dvb/fe-read-ber
media/uapi/dvb/fe-read-signal-strength userspace-api/media/dvb/fe-read-signal-strength
media/uapi/dvb/fe-read-snr userspace-api/media/dvb/fe-read-snr
media/uapi/dvb/fe-read-status userspace-api/media/dvb/fe-read-status
media/uapi/dvb/fe-read-uncorrected-blocks userspace-api/media/dvb/fe-read-uncorrected-blocks
media/uapi/dvb/fe-set-frontend userspace-api/media/dvb/fe-set-frontend
media/uapi/dvb/fe-set-frontend-tune-mode userspace-api/media/dvb/fe-set-frontend-tune-mode
media/uapi/dvb/fe-set-tone userspace-api/media/dvb/fe-set-tone
media/uapi/dvb/fe-set-voltage userspace-api/media/dvb/fe-set-voltage
media/uapi/dvb/fe-type-t userspace-api/media/dvb/fe-type-t
media/uapi/dvb/fe_property_parameters userspace-api/media/dvb/fe_property_parameters
media/uapi/dvb/frontend userspace-api/media/dvb/frontend
media/uapi/dvb/frontend-header userspace-api/media/dvb/frontend-header
media/uapi/dvb/frontend-property-cable-systems userspace-api/media/dvb/frontend-property-cable-systems
media/uapi/dvb/frontend-property-satellite-systems userspace-api/media/dvb/frontend-property-satellite-systems
media/uapi/dvb/frontend-property-terrestrial-systems userspace-api/media/dvb/frontend-property-terrestrial-systems
media/uapi/dvb/frontend-stat-properties userspace-api/media/dvb/frontend-stat-properties
media/uapi/dvb/frontend_f_close userspace-api/media/dvb/frontend_f_close
media/uapi/dvb/frontend_f_open userspace-api/media/dvb/frontend_f_open
media/uapi/dvb/frontend_fcalls userspace-api/media/dvb/frontend_fcalls
media/uapi/dvb/frontend_legacy_api userspace-api/media/dvb/frontend_legacy_api
media/uapi/dvb/frontend_legacy_dvbv3_api userspace-api/media/dvb/frontend_legacy_dvbv3_api
media/uapi/dvb/headers userspace-api/media/dvb/headers
media/uapi/dvb/intro userspace-api/media/dvb/intro
media/uapi/dvb/legacy_dvb_apis userspace-api/media/dvb/legacy_dvb_apis
media/uapi/dvb/net userspace-api/media/dvb/net
media/uapi/dvb/net-add-if userspace-api/media/dvb/net-add-if
media/uapi/dvb/net-get-if userspace-api/media/dvb/net-get-if
media/uapi/dvb/net-remove-if userspace-api/media/dvb/net-remove-if
media/uapi/dvb/net-types userspace-api/media/dvb/net-types
media/uapi/dvb/query-dvb-frontend-info userspace-api/media/dvb/query-dvb-frontend-info
media/uapi/fdl-appendix userspace-api/media/fdl-appendix
media/uapi/gen-errors userspace-api/media/gen-errors
media/uapi/mediactl/media-controller userspace-api/media/mediactl/media-controller
media/uapi/mediactl/media-controller-intro userspace-api/media/mediactl/media-controller-intro
media/uapi/mediactl/media-controller-model userspace-api/media/mediactl/media-controller-model
media/uapi/mediactl/media-func-close userspace-api/media/mediactl/media-func-close
media/uapi/mediactl/media-func-ioctl userspace-api/media/mediactl/media-func-ioctl
media/uapi/mediactl/media-func-open userspace-api/media/mediactl/media-func-open
media/uapi/mediactl/media-funcs userspace-api/media/mediactl/media-funcs
media/uapi/mediactl/media-header userspace-api/media/mediactl/media-header
media/uapi/mediactl/media-ioc-device-info userspace-api/media/mediactl/media-ioc-device-info
media/uapi/mediactl/media-ioc-enum-entities userspace-api/media/mediactl/media-ioc-enum-entities
media/uapi/mediactl/media-ioc-enum-links userspace-api/media/mediactl/media-ioc-enum-links
media/uapi/mediactl/media-ioc-g-topology userspace-api/media/mediactl/media-ioc-g-topology
media/uapi/mediactl/media-ioc-request-alloc userspace-api/media/mediactl/media-ioc-request-alloc
media/uapi/mediactl/media-ioc-setup-link userspace-api/media/mediactl/media-ioc-setup-link
media/uapi/mediactl/media-request-ioc-queue userspace-api/media/mediactl/media-request-ioc-queue
media/uapi/mediactl/media-request-ioc-reinit userspace-api/media/mediactl/media-request-ioc-reinit
media/uapi/mediactl/media-types userspace-api/media/mediactl/media-types
media/uapi/mediactl/request-api userspace-api/media/mediactl/request-api
media/uapi/mediactl/request-func-close userspace-api/media/mediactl/request-func-close
media/uapi/mediactl/request-func-ioctl userspace-api/media/mediactl/request-func-ioctl
media/uapi/mediactl/request-func-poll userspace-api/media/mediactl/request-func-poll
media/uapi/rc/keytable.c userspace-api/media/rc/keytable.c
media/uapi/rc/lirc-dev userspace-api/media/rc/lirc-dev
media/uapi/rc/lirc-dev-intro userspace-api/media/rc/lirc-dev-intro
media/uapi/rc/lirc-func userspace-api/media/rc/lirc-func
media/uapi/rc/lirc-get-features userspace-api/media/rc/lirc-get-features
media/uapi/rc/lirc-get-rec-mode userspace-api/media/rc/lirc-get-rec-mode
media/uapi/rc/lirc-get-rec-resolution userspace-api/media/rc/lirc-get-rec-resolution
media/uapi/rc/lirc-get-send-mode userspace-api/media/rc/lirc-get-send-mode
media/uapi/rc/lirc-get-timeout userspace-api/media/rc/lirc-get-timeout
media/uapi/rc/lirc-header userspace-api/media/rc/lirc-header
media/uapi/rc/lirc-read userspace-api/media/rc/lirc-read
media/uapi/rc/lirc-set-measure-carrier-mode userspace-api/media/rc/lirc-set-measure-carrier-mode
media/uapi/rc/lirc-set-rec-carrier userspace-api/media/rc/lirc-set-rec-carrier
media/uapi/rc/lirc-set-rec-carrier-range userspace-api/media/rc/lirc-set-rec-carrier-range
media/uapi/rc/lirc-set-rec-timeout userspace-api/media/rc/lirc-set-rec-timeout
media/uapi/rc/lirc-set-send-carrier userspace-api/media/rc/lirc-set-send-carrier
media/uapi/rc/lirc-set-send-duty-cycle userspace-api/media/rc/lirc-set-send-duty-cycle
media/uapi/rc/lirc-set-transmitter-mask userspace-api/media/rc/lirc-set-transmitter-mask
media/uapi/rc/lirc-set-wideband-receiver userspace-api/media/rc/lirc-set-wideband-receiver
media/uapi/rc/lirc-write userspace-api/media/rc/lirc-write
media/uapi/rc/rc-intro userspace-api/media/rc/rc-intro
media/uapi/rc/rc-protos userspace-api/media/rc/rc-protos
media/uapi/rc/rc-sysfs-nodes userspace-api/media/rc/rc-sysfs-nodes
media/uapi/rc/rc-table-change userspace-api/media/rc/rc-table-change
media/uapi/rc/rc-tables userspace-api/media/rc/rc-tables
media/uapi/rc/remote_controllers userspace-api/media/rc/remote_controllers
media/uapi/v4l/app-pri userspace-api/media/v4l/app-pri
media/uapi/v4l/audio userspace-api/media/v4l/audio
media/uapi/v4l/biblio userspace-api/media/v4l/biblio
media/uapi/v4l/buffer userspace-api/media/v4l/buffer
media/uapi/v4l/capture-example userspace-api/media/v4l/capture-example
media/uapi/v4l/capture.c userspace-api/media/v4l/capture.c
media/uapi/v4l/colorspaces userspace-api/media/v4l/colorspaces
media/uapi/v4l/colorspaces-defs userspace-api/media/v4l/colorspaces-defs
media/uapi/v4l/colorspaces-details userspace-api/media/v4l/colorspaces-details
media/uapi/v4l/common userspace-api/media/v4l/common
media/uapi/v4l/common-defs userspace-api/media/v4l/common-defs
media/uapi/v4l/compat userspace-api/media/v4l/compat
media/uapi/v4l/control userspace-api/media/v4l/control
media/uapi/v4l/crop userspace-api/media/v4l/crop
media/uapi/v4l/depth-formats userspace-api/media/v4l/depth-formats
media/uapi/v4l/dev-capture userspace-api/media/v4l/dev-capture
media/uapi/v4l/dev-codec userspace-api/media/v4l/dev-mem2mem
media/uapi/v4l/dev-decoder userspace-api/media/v4l/dev-decoder
media/uapi/v4l/dev-event userspace-api/media/v4l/dev-event
media/uapi/v4l/dev-mem2mem userspace-api/media/v4l/dev-mem2mem
media/uapi/v4l/dev-meta userspace-api/media/v4l/dev-meta
media/uapi/v4l/dev-osd userspace-api/media/v4l/dev-osd
media/uapi/v4l/dev-output userspace-api/media/v4l/dev-output
media/uapi/v4l/dev-overlay userspace-api/media/v4l/dev-overlay
media/uapi/v4l/dev-radio userspace-api/media/v4l/dev-radio
media/uapi/v4l/dev-raw-vbi userspace-api/media/v4l/dev-raw-vbi
media/uapi/v4l/dev-rds userspace-api/media/v4l/dev-rds
media/uapi/v4l/dev-sdr userspace-api/media/v4l/dev-sdr
media/uapi/v4l/dev-sliced-vbi userspace-api/media/v4l/dev-sliced-vbi
media/uapi/v4l/dev-stateless-decoder userspace-api/media/v4l/dev-stateless-decoder
media/uapi/v4l/dev-subdev userspace-api/media/v4l/dev-subdev
media/uapi/v4l/dev-touch userspace-api/media/v4l/dev-touch
media/uapi/v4l/devices userspace-api/media/v4l/devices
media/uapi/v4l/diff-v4l userspace-api/media/v4l/diff-v4l
media/uapi/v4l/dmabuf userspace-api/media/v4l/dmabuf
media/uapi/v4l/dv-timings userspace-api/media/v4l/dv-timings
media/uapi/v4l/ext-ctrls-camera userspace-api/media/v4l/ext-ctrls-camera
media/uapi/v4l/ext-ctrls-codec userspace-api/media/v4l/ext-ctrls-codec
media/uapi/v4l/ext-ctrls-detect userspace-api/media/v4l/ext-ctrls-detect
media/uapi/v4l/ext-ctrls-dv userspace-api/media/v4l/ext-ctrls-dv
media/uapi/v4l/ext-ctrls-flash userspace-api/media/v4l/ext-ctrls-flash
media/uapi/v4l/ext-ctrls-fm-rx userspace-api/media/v4l/ext-ctrls-fm-rx
media/uapi/v4l/ext-ctrls-fm-tx userspace-api/media/v4l/ext-ctrls-fm-tx
media/uapi/v4l/ext-ctrls-image-process userspace-api/media/v4l/ext-ctrls-image-process
media/uapi/v4l/ext-ctrls-image-source userspace-api/media/v4l/ext-ctrls-image-source
media/uapi/v4l/ext-ctrls-jpeg userspace-api/media/v4l/ext-ctrls-jpeg
media/uapi/v4l/ext-ctrls-rf-tuner userspace-api/media/v4l/ext-ctrls-rf-tuner
media/uapi/v4l/extended-controls userspace-api/media/v4l/extended-controls
media/uapi/v4l/field-order userspace-api/media/v4l/field-order
media/uapi/v4l/format userspace-api/media/v4l/format
media/uapi/v4l/func-close userspace-api/media/v4l/func-close
media/uapi/v4l/func-ioctl userspace-api/media/v4l/func-ioctl
media/uapi/v4l/func-mmap userspace-api/media/v4l/func-mmap
media/uapi/v4l/func-munmap userspace-api/media/v4l/func-munmap
media/uapi/v4l/func-open userspace-api/media/v4l/func-open
media/uapi/v4l/func-poll userspace-api/media/v4l/func-poll
media/uapi/v4l/func-read userspace-api/media/v4l/func-read
media/uapi/v4l/func-select userspace-api/media/v4l/func-select
media/uapi/v4l/func-write userspace-api/media/v4l/func-write
media/uapi/v4l/hist-v4l2 userspace-api/media/v4l/hist-v4l2
media/uapi/v4l/hsv-formats userspace-api/media/v4l/hsv-formats
media/uapi/v4l/io userspace-api/media/v4l/io
media/uapi/v4l/libv4l userspace-api/media/v4l/libv4l
media/uapi/v4l/libv4l-introduction userspace-api/media/v4l/libv4l-introduction
media/uapi/v4l/meta-formats userspace-api/media/v4l/meta-formats
media/uapi/v4l/mmap userspace-api/media/v4l/mmap
media/uapi/v4l/open userspace-api/media/v4l/open
media/uapi/v4l/pixfmt userspace-api/media/v4l/pixfmt
media/uapi/v4l/pixfmt-002 userspace-api/media/v4l/pixfmt-v4l2
media/uapi/v4l/pixfmt-003 userspace-api/media/v4l/pixfmt-v4l2-mplane
media/uapi/v4l/pixfmt-004 userspace-api/media/v4l/pixfmt-intro
media/uapi/v4l/pixfmt-006 userspace-api/media/v4l/colorspaces-defs
media/uapi/v4l/pixfmt-007 userspace-api/media/v4l/colorspaces-details
media/uapi/v4l/pixfmt-013 userspace-api/media/v4l/pixfmt-compressed
media/uapi/v4l/pixfmt-bayer userspace-api/media/v4l/pixfmt-bayer
media/uapi/v4l/pixfmt-cnf4 userspace-api/media/v4l/pixfmt-cnf4
media/uapi/v4l/pixfmt-compressed userspace-api/media/v4l/pixfmt-compressed
media/uapi/v4l/pixfmt-indexed userspace-api/media/v4l/pixfmt-indexed
media/uapi/v4l/pixfmt-intro userspace-api/media/v4l/pixfmt-intro
media/uapi/v4l/pixfmt-inzi userspace-api/media/v4l/pixfmt-inzi
media/uapi/v4l/pixfmt-m420 userspace-api/media/v4l/pixfmt-m420
media/uapi/v4l/pixfmt-meta-d4xx userspace-api/media/v4l/metafmt-d4xx
media/uapi/v4l/pixfmt-meta-intel-ipu3 userspace-api/media/v4l/metafmt-intel-ipu3
media/uapi/v4l/pixfmt-meta-uvc userspace-api/media/v4l/metafmt-uvc
media/uapi/v4l/pixfmt-meta-vivid userspace-api/media/v4l/metafmt-vivid
media/uapi/v4l/pixfmt-meta-vsp1-hgo userspace-api/media/v4l/metafmt-vsp1-hgo
media/uapi/v4l/pixfmt-meta-vsp1-hgt userspace-api/media/v4l/metafmt-vsp1-hgt
media/uapi/v4l/pixfmt-packed-hsv userspace-api/media/v4l/pixfmt-packed-hsv
media/uapi/v4l/pixfmt-packed-yuv userspace-api/media/v4l/pixfmt-packed-yuv
media/uapi/v4l/pixfmt-reserved userspace-api/media/v4l/pixfmt-reserved
media/uapi/v4l/pixfmt-rgb userspace-api/media/v4l/pixfmt-rgb
media/uapi/v4l/pixfmt-sbggr16 userspace-api/media/v4l/pixfmt-srggb16
media/uapi/v4l/pixfmt-sdr-cs08 userspace-api/media/v4l/pixfmt-sdr-cs08
media/uapi/v4l/pixfmt-sdr-cs14le userspace-api/media/v4l/pixfmt-sdr-cs14le
media/uapi/v4l/pixfmt-sdr-cu08 userspace-api/media/v4l/pixfmt-sdr-cu08
media/uapi/v4l/pixfmt-sdr-cu16le userspace-api/media/v4l/pixfmt-sdr-cu16le
media/uapi/v4l/pixfmt-sdr-pcu16be userspace-api/media/v4l/pixfmt-sdr-pcu16be
media/uapi/v4l/pixfmt-sdr-pcu18be userspace-api/media/v4l/pixfmt-sdr-pcu18be
media/uapi/v4l/pixfmt-sdr-pcu20be userspace-api/media/v4l/pixfmt-sdr-pcu20be
media/uapi/v4l/pixfmt-sdr-ru12le userspace-api/media/v4l/pixfmt-sdr-ru12le
media/uapi/v4l/pixfmt-srggb10 userspace-api/media/v4l/pixfmt-srggb10
media/uapi/v4l/pixfmt-srggb10-ipu3 userspace-api/media/v4l/pixfmt-srggb10-ipu3
media/uapi/v4l/pixfmt-srggb10alaw8 userspace-api/media/v4l/pixfmt-srggb10alaw8
media/uapi/v4l/pixfmt-srggb10dpcm8 userspace-api/media/v4l/pixfmt-srggb10dpcm8
media/uapi/v4l/pixfmt-srggb10p userspace-api/media/v4l/pixfmt-srggb10p
media/uapi/v4l/pixfmt-srggb12 userspace-api/media/v4l/pixfmt-srggb12
media/uapi/v4l/pixfmt-srggb12p userspace-api/media/v4l/pixfmt-srggb12p
media/uapi/v4l/pixfmt-srggb14 userspace-api/media/v4l/pixfmt-srggb14
media/uapi/v4l/pixfmt-srggb14p userspace-api/media/v4l/pixfmt-srggb14p
media/uapi/v4l/pixfmt-srggb16 userspace-api/media/v4l/pixfmt-srggb16
media/uapi/v4l/pixfmt-srggb8 userspace-api/media/v4l/pixfmt-srggb8
media/uapi/v4l/pixfmt-tch-td08 userspace-api/media/v4l/pixfmt-tch-td08
media/uapi/v4l/pixfmt-tch-td16 userspace-api/media/v4l/pixfmt-tch-td16
media/uapi/v4l/pixfmt-tch-tu08 userspace-api/media/v4l/pixfmt-tch-tu08
media/uapi/v4l/pixfmt-tch-tu16 userspace-api/media/v4l/pixfmt-tch-tu16
media/uapi/v4l/pixfmt-uv8 userspace-api/media/v4l/pixfmt-uv8
media/uapi/v4l/pixfmt-v4l2 userspace-api/media/v4l/pixfmt-v4l2
media/uapi/v4l/pixfmt-v4l2-mplane userspace-api/media/v4l/pixfmt-v4l2-mplane
media/uapi/v4l/pixfmt-y12i userspace-api/media/v4l/pixfmt-y12i
media/uapi/v4l/pixfmt-y8i userspace-api/media/v4l/pixfmt-y8i
media/uapi/v4l/pixfmt-z16 userspace-api/media/v4l/pixfmt-z16
media/uapi/v4l/planar-apis userspace-api/media/v4l/planar-apis
media/uapi/v4l/querycap userspace-api/media/v4l/querycap
media/uapi/v4l/rw userspace-api/media/v4l/rw
media/uapi/v4l/sdr-formats userspace-api/media/v4l/sdr-formats
media/uapi/v4l/selection-api userspace-api/media/v4l/selection-api
media/uapi/v4l/selection-api-002 userspace-api/media/v4l/selection-api-intro
media/uapi/v4l/selection-api-003 userspace-api/media/v4l/selection-api-targets
media/uapi/v4l/selection-api-004 userspace-api/media/v4l/selection-api-configuration
media/uapi/v4l/selection-api-005 userspace-api/media/v4l/selection-api-vs-crop-api
media/uapi/v4l/selection-api-006 userspace-api/media/v4l/selection-api-examples
media/uapi/v4l/selection-api-configuration userspace-api/media/v4l/selection-api-configuration
media/uapi/v4l/selection-api-examples userspace-api/media/v4l/selection-api-examples
media/uapi/v4l/selection-api-intro userspace-api/media/v4l/selection-api-intro
media/uapi/v4l/selection-api-targets userspace-api/media/v4l/selection-api-targets
media/uapi/v4l/selection-api-vs-crop-api userspace-api/media/v4l/selection-api-vs-crop-api
media/uapi/v4l/selections-common userspace-api/media/v4l/selections-common
media/uapi/v4l/standard userspace-api/media/v4l/standard
media/uapi/v4l/streaming-par userspace-api/media/v4l/streaming-par
media/uapi/v4l/subdev-formats userspace-api/media/v4l/subdev-formats
media/uapi/v4l/tch-formats userspace-api/media/v4l/tch-formats
media/uapi/v4l/tuner userspace-api/media/v4l/tuner
media/uapi/v4l/user-func userspace-api/media/v4l/user-func
media/uapi/v4l/userp userspace-api/media/v4l/userp
media/uapi/v4l/v4l2 userspace-api/media/v4l/v4l2
media/uapi/v4l/v4l2-selection-flags userspace-api/media/v4l/v4l2-selection-flags
media/uapi/v4l/v4l2-selection-targets userspace-api/media/v4l/v4l2-selection-targets
media/uapi/v4l/v4l2grab-example userspace-api/media/v4l/v4l2grab-example
media/uapi/v4l/v4l2grab.c userspace-api/media/v4l/v4l2grab.c
media/uapi/v4l/video userspace-api/media/v4l/video
media/uapi/v4l/videodev userspace-api/media/v4l/videodev
media/uapi/v4l/vidioc-create-bufs userspace-api/media/v4l/vidioc-create-bufs
media/uapi/v4l/vidioc-cropcap userspace-api/media/v4l/vidioc-cropcap
media/uapi/v4l/vidioc-dbg-g-chip-info userspace-api/media/v4l/vidioc-dbg-g-chip-info
media/uapi/v4l/vidioc-dbg-g-register userspace-api/media/v4l/vidioc-dbg-g-register
media/uapi/v4l/vidioc-decoder-cmd userspace-api/media/v4l/vidioc-decoder-cmd
media/uapi/v4l/vidioc-dqevent userspace-api/media/v4l/vidioc-dqevent
media/uapi/v4l/vidioc-dv-timings-cap userspace-api/media/v4l/vidioc-dv-timings-cap
media/uapi/v4l/vidioc-encoder-cmd userspace-api/media/v4l/vidioc-encoder-cmd
media/uapi/v4l/vidioc-enum-dv-timings userspace-api/media/v4l/vidioc-enum-dv-timings
media/uapi/v4l/vidioc-enum-fmt userspace-api/media/v4l/vidioc-enum-fmt
media/uapi/v4l/vidioc-enum-frameintervals userspace-api/media/v4l/vidioc-enum-frameintervals
media/uapi/v4l/vidioc-enum-framesizes userspace-api/media/v4l/vidioc-enum-framesizes
media/uapi/v4l/vidioc-enum-freq-bands userspace-api/media/v4l/vidioc-enum-freq-bands
media/uapi/v4l/vidioc-enumaudio userspace-api/media/v4l/vidioc-enumaudio
media/uapi/v4l/vidioc-enumaudioout userspace-api/media/v4l/vidioc-enumaudioout
media/uapi/v4l/vidioc-enuminput userspace-api/media/v4l/vidioc-enuminput
media/uapi/v4l/vidioc-enumoutput userspace-api/media/v4l/vidioc-enumoutput
media/uapi/v4l/vidioc-enumstd userspace-api/media/v4l/vidioc-enumstd
media/uapi/v4l/vidioc-expbuf userspace-api/media/v4l/vidioc-expbuf
media/uapi/v4l/vidioc-g-audio userspace-api/media/v4l/vidioc-g-audio
media/uapi/v4l/vidioc-g-audioout userspace-api/media/v4l/vidioc-g-audioout
media/uapi/v4l/vidioc-g-crop userspace-api/media/v4l/vidioc-g-crop
media/uapi/v4l/vidioc-g-ctrl userspace-api/media/v4l/vidioc-g-ctrl
media/uapi/v4l/vidioc-g-dv-timings userspace-api/media/v4l/vidioc-g-dv-timings
media/uapi/v4l/vidioc-g-edid userspace-api/media/v4l/vidioc-g-edid
media/uapi/v4l/vidioc-g-enc-index userspace-api/media/v4l/vidioc-g-enc-index
media/uapi/v4l/vidioc-g-ext-ctrls userspace-api/media/v4l/vidioc-g-ext-ctrls
media/uapi/v4l/vidioc-g-fbuf userspace-api/media/v4l/vidioc-g-fbuf
media/uapi/v4l/vidioc-g-fmt userspace-api/media/v4l/vidioc-g-fmt
media/uapi/v4l/vidioc-g-frequency userspace-api/media/v4l/vidioc-g-frequency
media/uapi/v4l/vidioc-g-input userspace-api/media/v4l/vidioc-g-input
media/uapi/v4l/vidioc-g-jpegcomp userspace-api/media/v4l/vidioc-g-jpegcomp
media/uapi/v4l/vidioc-g-modulator userspace-api/media/v4l/vidioc-g-modulator
media/uapi/v4l/vidioc-g-output userspace-api/media/v4l/vidioc-g-output
media/uapi/v4l/vidioc-g-parm userspace-api/media/v4l/vidioc-g-parm
media/uapi/v4l/vidioc-g-priority userspace-api/media/v4l/vidioc-g-priority
media/uapi/v4l/vidioc-g-selection userspace-api/media/v4l/vidioc-g-selection
media/uapi/v4l/vidioc-g-sliced-vbi-cap userspace-api/media/v4l/vidioc-g-sliced-vbi-cap
media/uapi/v4l/vidioc-g-std userspace-api/media/v4l/vidioc-g-std
media/uapi/v4l/vidioc-g-tuner userspace-api/media/v4l/vidioc-g-tuner
media/uapi/v4l/vidioc-log-status userspace-api/media/v4l/vidioc-log-status
media/uapi/v4l/vidioc-overlay userspace-api/media/v4l/vidioc-overlay
media/uapi/v4l/vidioc-prepare-buf userspace-api/media/v4l/vidioc-prepare-buf
media/uapi/v4l/vidioc-qbuf userspace-api/media/v4l/vidioc-qbuf
media/uapi/v4l/vidioc-query-dv-timings userspace-api/media/v4l/vidioc-query-dv-timings
media/uapi/v4l/vidioc-querybuf userspace-api/media/v4l/vidioc-querybuf
media/uapi/v4l/vidioc-querycap userspace-api/media/v4l/vidioc-querycap
media/uapi/v4l/vidioc-queryctrl userspace-api/media/v4l/vidioc-queryctrl
media/uapi/v4l/vidioc-querystd userspace-api/media/v4l/vidioc-querystd
media/uapi/v4l/vidioc-reqbufs userspace-api/media/v4l/vidioc-reqbufs
media/uapi/v4l/vidioc-s-hw-freq-seek userspace-api/media/v4l/vidioc-s-hw-freq-seek
media/uapi/v4l/vidioc-streamon userspace-api/media/v4l/vidioc-streamon
media/uapi/v4l/vidioc-subdev-enum-frame-interval userspace-api/media/v4l/vidioc-subdev-enum-frame-interval
media/uapi/v4l/vidioc-subdev-enum-frame-size userspace-api/media/v4l/vidioc-subdev-enum-frame-size
media/uapi/v4l/vidioc-subdev-enum-mbus-code userspace-api/media/v4l/vidioc-subdev-enum-mbus-code
media/uapi/v4l/vidioc-subdev-g-crop userspace-api/media/v4l/vidioc-subdev-g-crop
media/uapi/v4l/vidioc-subdev-g-fmt userspace-api/media/v4l/vidioc-subdev-g-fmt
media/uapi/v4l/vidioc-subdev-g-frame-interval userspace-api/media/v4l/vidioc-subdev-g-frame-interval
media/uapi/v4l/vidioc-subdev-g-selection userspace-api/media/v4l/vidioc-subdev-g-selection
media/uapi/v4l/vidioc-subscribe-event userspace-api/media/v4l/vidioc-subscribe-event
media/uapi/v4l/yuv-formats userspace-api/media/v4l/yuv-formats
media/v4l-drivers/au0828-cardlist admin-guide/media/au0828-cardlist
media/v4l-drivers/bttv admin-guide/media/bttv
media/v4l-drivers/bttv-cardlist admin-guide/media/bttv-cardlist
media/v4l-drivers/bttv-devel driver-api/media/drivers/bttv-devel
media/v4l-drivers/cafe_ccic admin-guide/media/cafe_ccic
media/v4l-drivers/cardlist admin-guide/media/cardlist
media/v4l-drivers/cx2341x driver-api/media/drivers/cx2341x-devel
media/v4l-drivers/cx2341x-devel driver-api/media/drivers/cx2341x-devel
media/v4l-drivers/cx2341x-uapi userspace-api/media/drivers/cx2341x-uapi
media/v4l-drivers/cx23885-cardlist admin-guide/media/cx23885-cardlist
media/v4l-drivers/cx88 admin-guide/media/cx88
media/v4l-drivers/cx88-cardlist admin-guide/media/cx88-cardlist
media/v4l-drivers/cx88-devel driver-api/media/drivers/cx88-devel
media/v4l-drivers/em28xx-cardlist admin-guide/media/em28xx-cardlist
media/v4l-drivers/fimc admin-guide/media/fimc
media/v4l-drivers/fimc-devel driver-api/media/drivers/fimc-devel
media/v4l-drivers/fourcc userspace-api/media/v4l/fourcc
media/v4l-drivers/gspca-cardlist admin-guide/media/gspca-cardlist
media/v4l-drivers/imx admin-guide/media/imx
media/v4l-drivers/imx-uapi userspace-api/media/drivers/imx-uapi
media/v4l-drivers/imx7 admin-guide/media/imx7
media/v4l-drivers/index userspace-api/media/drivers/index
media/v4l-drivers/ipu3 admin-guide/media/ipu3
media/v4l-drivers/ivtv admin-guide/media/ivtv
media/v4l-drivers/ivtv-cardlist admin-guide/media/ivtv-cardlist
media/v4l-drivers/max2175 userspace-api/media/drivers/max2175
media/v4l-drivers/omap3isp admin-guide/media/omap3isp
media/v4l-drivers/omap3isp-uapi userspace-api/media/drivers/omap3isp-uapi
media/v4l-drivers/philips admin-guide/media/philips
media/v4l-drivers/pvrusb2 driver-api/media/drivers/pvrusb2
media/v4l-drivers/pxa_camera driver-api/media/drivers/pxa_camera
media/v4l-drivers/qcom_camss admin-guide/media/qcom_camss
media/v4l-drivers/radiotrack driver-api/media/drivers/radiotrack
media/v4l-drivers/rcar-fdp1 admin-guide/media/rcar-fdp1
media/v4l-drivers/saa7134 admin-guide/media/saa7134
media/v4l-drivers/saa7134-cardlist admin-guide/media/saa7134-cardlist
media/v4l-drivers/saa7134-devel driver-api/media/drivers/saa7134-devel
media/v4l-drivers/saa7164-cardlist admin-guide/media/saa7164-cardlist
media/v4l-drivers/sh_mobile_ceu_camera driver-api/media/drivers/sh_mobile_ceu_camera
media/v4l-drivers/si470x admin-guide/media/si470x
media/v4l-drivers/si4713 admin-guide/media/si4713
media/v4l-drivers/si476x admin-guide/media/si476x
media/v4l-drivers/tuner-cardlist admin-guide/media/tuner-cardlist
media/v4l-drivers/tuners driver-api/media/drivers/tuners
media/v4l-drivers/uvcvideo userspace-api/media/drivers/uvcvideo
media/v4l-drivers/v4l-with-ir admin-guide/media/remote-controller
media/v4l-drivers/vimc admin-guide/media/vimc
media/v4l-drivers/vimc-devel driver-api/media/drivers/vimc-devel
media/v4l-drivers/vivid admin-guide/media/vivid
media/v4l-drivers/zoran driver-api/media/drivers/zoran
memory-devices/ti-emif driver-api/memory-devices/ti-emif
mips/booting arch/mips/booting
mips/features arch/mips/features
mips/index arch/mips/index
mips/ingenic-tcu arch/mips/ingenic-tcu
mm/slub admin-guide/mm/slab
mmc/index driver-api/mmc/index
mmc/mmc-async-req driver-api/mmc/mmc-async-req
mmc/mmc-dev-attrs driver-api/mmc/mmc-dev-attrs
mmc/mmc-dev-parts driver-api/mmc/mmc-dev-parts
mmc/mmc-tools driver-api/mmc/mmc-tools
mtd/index driver-api/mtd/index
mtd/intel-spi driver-api/mtd/spi-intel
mtd/nand_ecc driver-api/mtd/nand_ecc
mtd/spi-nor driver-api/mtd/spi-nor
namespaces/compatibility-list admin-guide/namespaces/compatibility-list
namespaces/index admin-guide/namespaces/index
namespaces/resource-control admin-guide/namespaces/resource-control
networking/altera_tse networking/device_drivers/ethernet/altera/altera_tse
networking/baycom networking/device_drivers/hamradio/baycom
networking/bpf_flow_dissector bpf/prog_flow_dissector
networking/cxacru networking/device_drivers/atm/cxacru
networking/defza networking/device_drivers/fddi/defza
networking/device_drivers/3com/3c509 networking/device_drivers/ethernet/3com/3c509
networking/device_drivers/3com/vortex networking/device_drivers/ethernet/3com/vortex
networking/device_drivers/amazon/ena networking/device_drivers/ethernet/amazon/ena
networking/device_drivers/aquantia/atlantic networking/device_drivers/ethernet/aquantia/atlantic
networking/device_drivers/chelsio/cxgb networking/device_drivers/ethernet/chelsio/cxgb
networking/device_drivers/cirrus/cs89x0 networking/device_drivers/ethernet/cirrus/cs89x0
networking/device_drivers/davicom/dm9000 networking/device_drivers/ethernet/davicom/dm9000
networking/device_drivers/dec/dmfe networking/device_drivers/ethernet/dec/dmfe
networking/device_drivers/dlink/dl2k networking/device_drivers/ethernet/dlink/dl2k
networking/device_drivers/freescale/dpaa networking/device_drivers/ethernet/freescale/dpaa
networking/device_drivers/freescale/dpaa2/dpio-driver networking/device_drivers/ethernet/freescale/dpaa2/dpio-driver
networking/device_drivers/freescale/dpaa2/ethernet-driver networking/device_drivers/ethernet/freescale/dpaa2/ethernet-driver
networking/device_drivers/freescale/dpaa2/index networking/device_drivers/ethernet/freescale/dpaa2/index
networking/device_drivers/freescale/dpaa2/mac-phy-support networking/device_drivers/ethernet/freescale/dpaa2/mac-phy-support
networking/device_drivers/freescale/dpaa2/overview networking/device_drivers/ethernet/freescale/dpaa2/overview
networking/device_drivers/freescale/gianfar networking/device_drivers/ethernet/freescale/gianfar
networking/device_drivers/google/gve networking/device_drivers/ethernet/google/gve
networking/device_drivers/intel/e100 networking/device_drivers/ethernet/intel/e100
networking/device_drivers/intel/e1000 networking/device_drivers/ethernet/intel/e1000
networking/device_drivers/intel/e1000e networking/device_drivers/ethernet/intel/e1000e
networking/device_drivers/intel/fm10k networking/device_drivers/ethernet/intel/fm10k
networking/device_drivers/intel/i40e networking/device_drivers/ethernet/intel/i40e
networking/device_drivers/intel/iavf networking/device_drivers/ethernet/intel/iavf
networking/device_drivers/intel/ice networking/device_drivers/ethernet/intel/ice
networking/device_drivers/intel/igb networking/device_drivers/ethernet/intel/igb
networking/device_drivers/intel/igbvf networking/device_drivers/ethernet/intel/igbvf
networking/device_drivers/intel/ipw2100 networking/device_drivers/wifi/intel/ipw2100
networking/device_drivers/intel/ipw2200 networking/device_drivers/wifi/intel/ipw2200
networking/device_drivers/intel/ixgbe networking/device_drivers/ethernet/intel/ixgbe
networking/device_drivers/intel/ixgbevf networking/device_drivers/ethernet/intel/ixgbevf
networking/device_drivers/marvell/octeontx2 networking/device_drivers/ethernet/marvell/octeontx2
networking/device_drivers/microsoft/netvsc networking/device_drivers/ethernet/microsoft/netvsc
networking/device_drivers/neterion/s2io networking/device_drivers/ethernet/neterion/s2io
networking/device_drivers/netronome/nfp networking/device_drivers/ethernet/netronome/nfp
networking/device_drivers/pensando/ionic networking/device_drivers/ethernet/pensando/ionic
networking/device_drivers/qualcomm/rmnet networking/device_drivers/cellular/qualcomm/rmnet
networking/device_drivers/smsc/smc9 networking/device_drivers/ethernet/smsc/smc9
networking/device_drivers/stmicro/stmmac networking/device_drivers/ethernet/stmicro/stmmac
networking/device_drivers/ti/cpsw networking/device_drivers/ethernet/ti/cpsw
networking/device_drivers/ti/cpsw_switchdev networking/device_drivers/ethernet/ti/cpsw_switchdev
networking/device_drivers/ti/tlan networking/device_drivers/ethernet/ti/tlan
networking/devlink-trap networking/devlink/devlink-trap
networking/dpaa2/dpio-driver networking/device_drivers/ethernet/freescale/dpaa2/dpio-driver
networking/dpaa2/ethernet-driver networking/device_drivers/ethernet/freescale/dpaa2/ethernet-driver
networking/dpaa2/index networking/device_drivers/ethernet/freescale/dpaa2/index
networking/dpaa2/overview networking/device_drivers/ethernet/freescale/dpaa2/overview
networking/e100 networking/device_drivers/ethernet/intel/e100
networking/e1000 networking/device_drivers/ethernet/intel/e1000
networking/e1000e networking/device_drivers/ethernet/intel/e1000e
networking/fm10k networking/device_drivers/ethernet/intel/fm10k
networking/fore200e networking/device_drivers/atm/fore200e
networking/hinic networking/device_drivers/ethernet/huawei/hinic
networking/i40e networking/device_drivers/ethernet/intel/i40e
networking/iavf networking/device_drivers/ethernet/intel/iavf
networking/ice networking/device_drivers/ethernet/intel/ice
networking/igb networking/device_drivers/ethernet/intel/igb
networking/igbvf networking/device_drivers/ethernet/intel/igbvf
networking/iphase networking/device_drivers/atm/iphase
networking/ixgbe networking/device_drivers/ethernet/intel/ixgbe
networking/ixgbevf networking/device_drivers/ethernet/intel/ixgbevf
networking/netdev-FAQ process/maintainer-netdev
networking/skfp networking/device_drivers/fddi/skfp
networking/z8530drv networking/device_drivers/hamradio/z8530drv
nfc/index driver-api/nfc/index
nfc/nfc-hci driver-api/nfc/nfc-hci
nfc/nfc-pn544 driver-api/nfc/nfc-pn544
nios2/features arch/nios2/features
nios2/index arch/nios2/index
nios2/nios2 arch/nios2/nios2
nvdimm/btt driver-api/nvdimm/btt
nvdimm/index driver-api/nvdimm/index
nvdimm/nvdimm driver-api/nvdimm/nvdimm
nvdimm/security driver-api/nvdimm/security
nvmem/nvmem driver-api/nvmem
openrisc/features arch/openrisc/features
openrisc/index arch/openrisc/index
openrisc/openrisc_port arch/openrisc/openrisc_port
openrisc/todo arch/openrisc/todo
parisc/debugging arch/parisc/debugging
parisc/features arch/parisc/features
parisc/index arch/parisc/index
parisc/registers arch/parisc/registers
perf/arm-ccn admin-guide/perf/arm-ccn
perf/arm_dsu_pmu admin-guide/perf/arm_dsu_pmu
perf/hisi-pmu admin-guide/perf/hisi-pmu
perf/index admin-guide/perf/index
perf/qcom_l2_pmu admin-guide/perf/qcom_l2_pmu
perf/qcom_l3_pmu admin-guide/perf/qcom_l3_pmu
perf/thunderx2-pmu admin-guide/perf/thunderx2-pmu
perf/xgene-pmu admin-guide/perf/xgene-pmu
phy/samsung-usb2 driver-api/phy/samsung-usb2
powerpc/associativity arch/powerpc/associativity
powerpc/booting arch/powerpc/booting
powerpc/bootwrapper arch/powerpc/bootwrapper
powerpc/cpu_families arch/powerpc/cpu_families
powerpc/cpu_features arch/powerpc/cpu_features
powerpc/dawr-power9 arch/powerpc/dawr-power9
powerpc/dexcr arch/powerpc/dexcr
powerpc/dscr arch/powerpc/dscr
powerpc/eeh-pci-error-recovery arch/powerpc/eeh-pci-error-recovery
powerpc/elf_hwcaps arch/powerpc/elf_hwcaps
powerpc/elfnote arch/powerpc/elfnote
powerpc/features arch/powerpc/features
powerpc/firmware-assisted-dump arch/powerpc/firmware-assisted-dump
powerpc/hvcs arch/powerpc/hvcs
powerpc/imc arch/powerpc/imc
powerpc/index arch/powerpc/index
powerpc/isa-versions arch/powerpc/isa-versions
powerpc/kaslr-booke32 arch/powerpc/kaslr-booke32
powerpc/mpc52xx arch/powerpc/mpc52xx
powerpc/papr_hcalls arch/powerpc/papr_hcalls
powerpc/pci_iov_resource_on_powernv arch/powerpc/pci_iov_resource_on_powernv
powerpc/pmu-ebb arch/powerpc/pmu-ebb
powerpc/ptrace arch/powerpc/ptrace
powerpc/qe_firmware arch/powerpc/qe_firmware
powerpc/syscall64-abi arch/powerpc/syscall64-abi
powerpc/transactional_memory arch/powerpc/transactional_memory
powerpc/ultravisor arch/powerpc/ultravisor
powerpc/vas-api arch/powerpc/vas-api
powerpc/vcpudispatch_stats arch/powerpc/vcpudispatch_stats
powerpc/vmemmap_dedup arch/powerpc/vmemmap_dedup
process/clang-format dev-tools/clang-format
process/magic-number staging/magic-number
process/unaligned-memory-access core-api/unaligned-memory-access
rapidio/index driver-api/rapidio/index
rapidio/mport_cdev driver-api/rapidio/mport_cdev
rapidio/rapidio driver-api/rapidio/rapidio
rapidio/rio_cm driver-api/rapidio/rio_cm
rapidio/sysfs driver-api/rapidio/sysfs
rapidio/tsi721 driver-api/rapidio/tsi721
riscv/acpi arch/riscv/acpi
riscv/boot arch/riscv/boot
riscv/boot-image-header arch/riscv/boot-image-header
riscv/features arch/riscv/features
riscv/hwprobe arch/riscv/hwprobe
riscv/index arch/riscv/index
riscv/patch-acceptance arch/riscv/patch-acceptance
riscv/uabi arch/riscv/uabi
riscv/vector arch/riscv/vector
riscv/vm-layout arch/riscv/vm-layout
s390/3270 arch/s390/3270
s390/cds arch/s390/cds
s390/common_io arch/s390/common_io
s390/driver-model arch/s390/driver-model
s390/features arch/s390/features
s390/index arch/s390/index
s390/monreader arch/s390/monreader
s390/pci arch/s390/pci
s390/qeth arch/s390/qeth
s390/s390dbf arch/s390/s390dbf
s390/text_files arch/s390/text_files
s390/vfio-ap arch/s390/vfio-ap
s390/vfio-ap-locking arch/s390/vfio-ap-locking
s390/vfio-ccw arch/s390/vfio-ccw
s390/zfcpdump arch/s390/zfcpdump
security/LSM security/lsm-development
security/LSM-sctp security/SCTP
serial/driver driver-api/serial/driver
serial/index driver-api/serial/index
serial/moxa-smartio driver-api/tty/moxa-smartio
serial/n_gsm driver-api/tty/n_gsm
serial/serial-iso7816 driver-api/serial/serial-iso7816
serial/serial-rs485 driver-api/serial/serial-rs485
serial/tty driver-api/tty/tty_ldisc
sh/booting arch/sh/booting
sh/features arch/sh/features
sh/index arch/sh/index
sh/new-machine arch/sh/new-machine
sh/register-banks arch/sh/register-banks
sparc/adi arch/sparc/adi
sparc/console arch/sparc/console
sparc/features arch/sparc/features
sparc/index arch/sparc/index
sparc/oradax/oracle-dax arch/sparc/oradax/oracle-dax
staging/kprobes trace/kprobes
sysctl/abi admin-guide/sysctl/abi
sysctl/fs admin-guide/sysctl/fs
sysctl/index admin-guide/sysctl/index
sysctl/kernel admin-guide/sysctl/kernel
sysctl/net admin-guide/sysctl/net
sysctl/sunrpc admin-guide/sysctl/sunrpc
sysctl/user admin-guide/sysctl/user
sysctl/vm admin-guide/sysctl/vm
thermal/cpu-cooling-api driver-api/thermal/cpu-cooling-api
thermal/exynos_thermal driver-api/thermal/exynos_thermal
thermal/exynos_thermal_emulation driver-api/thermal/exynos_thermal_emulation
thermal/index driver-api/thermal/index
thermal/intel_powerclamp admin-guide/thermal/intel_powerclamp
thermal/nouveau_thermal driver-api/thermal/nouveau_thermal
thermal/power_allocator driver-api/thermal/power_allocator
thermal/sysfs-api driver-api/thermal/sysfs-api
thermal/x86_pkg_temperature_thermal driver-api/thermal/x86_pkg_temperature_thermal
tpm/index security/tpm/index
tpm/tpm_vtpm_proxy security/tpm/tpm_vtpm_proxy
trace/coresight trace/coresight/coresight
trace/coresight-cpu-debug trace/coresight/coresight-cpu-debug
trace/rv/da_monitor_synthesis trace/rv/monitor_synthesis
translations/it_IT/admin-guide/security-bugs translations/it_IT/process/security-bugs
translations/it_IT/process/clang-format translations/it_IT/dev-tools/clang-format
translations/it_IT/process/magic-number translations/it_IT/staging/magic-number
translations/it_IT/riscv/patch-acceptance translations/it_IT/arch/riscv/patch-acceptance
translations/ja_JP/howto translations/ja_JP/process/howto
translations/ko_KR/howto translations/ko_KR/process/howto
translations/sp_SP/howto translations/sp_SP/process/howto
translations/sp_SP/submitting-patches translations/sp_SP/process/submitting-patches
translations/zh_CN/admin-guide/security-bugs translations/zh_CN/process/security-bugs
translations/zh_CN/arch translations/zh_CN/arch/index
translations/zh_CN/arm64/amu translations/zh_CN/arch/arm64/amu
translations/zh_CN/arm64/elf_hwcaps translations/zh_CN/arch/arm64/elf_hwcaps
translations/zh_CN/arm64/hugetlbpage translations/zh_CN/arch/arm64/hugetlbpage
translations/zh_CN/arm64/index translations/zh_CN/arch/arm64/index
translations/zh_CN/arm64/perf translations/zh_CN/arch/arm64/perf
translations/zh_CN/coding-style translations/zh_CN/process/coding-style
translations/zh_CN/loongarch/booting translations/zh_CN/arch/loongarch/booting
translations/zh_CN/loongarch/features translations/zh_CN/arch/loongarch/features
translations/zh_CN/loongarch/index translations/zh_CN/arch/loongarch/index
translations/zh_CN/loongarch/introduction translations/zh_CN/arch/loongarch/introduction
translations/zh_CN/loongarch/irq-chip-model translations/zh_CN/arch/loongarch/irq-chip-model
translations/zh_CN/mips/booting translations/zh_CN/arch/mips/booting
translations/zh_CN/mips/features translations/zh_CN/arch/mips/features
translations/zh_CN/mips/index translations/zh_CN/arch/mips/index
translations/zh_CN/mips/ingenic-tcu translations/zh_CN/arch/mips/ingenic-tcu
translations/zh_CN/openrisc/index translations/zh_CN/arch/openrisc/index
translations/zh_CN/openrisc/openrisc_port translations/zh_CN/arch/openrisc/openrisc_port
translations/zh_CN/openrisc/todo translations/zh_CN/arch/openrisc/todo
translations/zh_CN/parisc/debugging translations/zh_CN/arch/parisc/debugging
translations/zh_CN/parisc/index translations/zh_CN/arch/parisc/index
translations/zh_CN/parisc/registers translations/zh_CN/arch/parisc/registers
translations/zh_CN/riscv/boot-image-header translations/zh_CN/arch/riscv/boot-image-header
translations/zh_CN/riscv/index translations/zh_CN/arch/riscv/index
translations/zh_CN/riscv/patch-acceptance translations/zh_CN/arch/riscv/patch-acceptance
translations/zh_CN/riscv/vm-layout translations/zh_CN/arch/riscv/vm-layout
translations/zh_CN/vm/active_mm translations/zh_CN/mm/active_mm
translations/zh_CN/vm/balance translations/zh_CN/mm/balance
translations/zh_CN/vm/damon/api translations/zh_CN/mm/damon/api
translations/zh_CN/vm/damon/design translations/zh_CN/mm/damon/design
translations/zh_CN/vm/damon/faq translations/zh_CN/mm/damon/faq
translations/zh_CN/vm/damon/index translations/zh_CN/mm/damon/index
translations/zh_CN/vm/free_page_reporting translations/zh_CN/mm/free_page_reporting
translations/zh_CN/vm/highmem translations/zh_CN/mm/highmem
translations/zh_CN/vm/hmm translations/zh_CN/mm/hmm
translations/zh_CN/vm/hugetlbfs_reserv translations/zh_CN/mm/hugetlbfs_reserv
translations/zh_CN/vm/hwpoison translations/zh_CN/mm/hwpoison
translations/zh_CN/vm/index translations/zh_CN/mm/index
translations/zh_CN/vm/ksm translations/zh_CN/mm/ksm
translations/zh_CN/vm/memory-model translations/zh_CN/mm/memory-model
translations/zh_CN/vm/mmu_notifier translations/zh_CN/mm/mmu_notifier
translations/zh_CN/vm/numa translations/zh_CN/mm/numa
translations/zh_CN/vm/overcommit-accounting translations/zh_CN/mm/overcommit-accounting
translations/zh_CN/vm/page_frags translations/zh_CN/mm/page_frags
translations/zh_CN/vm/page_owner translations/zh_CN/mm/page_owner
translations/zh_CN/vm/page_table_check translations/zh_CN/mm/page_table_check
translations/zh_CN/vm/remap_file_pages translations/zh_CN/mm/remap_file_pages
translations/zh_CN/vm/split_page_table_lock translations/zh_CN/mm/split_page_table_lock
translations/zh_CN/vm/zsmalloc translations/zh_CN/mm/zsmalloc
translations/zh_TW/arm64/amu translations/zh_TW/arch/arm64/amu
translations/zh_TW/arm64/elf_hwcaps translations/zh_TW/arch/arm64/elf_hwcaps
translations/zh_TW/arm64/hugetlbpage translations/zh_TW/arch/arm64/hugetlbpage
translations/zh_TW/arm64/index translations/zh_TW/arch/arm64/index
translations/zh_TW/arm64/perf translations/zh_TW/arch/arm64/perf
tty/device_drivers/oxsemi-tornado misc-devices/oxsemi-tornado
tty/index driver-api/tty/index
tty/n_tty driver-api/tty/n_tty
tty/tty_buffer driver-api/tty/tty_buffer
tty/tty_driver driver-api/tty/tty_driver
tty/tty_internals driver-api/tty/tty_internals
tty/tty_ldisc driver-api/tty/tty_ldisc
tty/tty_port driver-api/tty/tty_port
tty/tty_struct driver-api/tty/tty_struct
usb/typec driver-api/usb/typec
usb/usb3-debug-port driver-api/usb/usb3-debug-port
userspace-api/media/drivers/st-vgxy61 userspace-api/media/drivers/vgxy61
userspace-api/media/v4l/pixfmt-meta-d4xx userspace-api/media/v4l/metafmt-d4xx
userspace-api/media/v4l/pixfmt-meta-intel-ipu3 userspace-api/media/v4l/metafmt-intel-ipu3
userspace-api/media/v4l/pixfmt-meta-rkisp1 userspace-api/media/v4l/metafmt-rkisp1
userspace-api/media/v4l/pixfmt-meta-uvc userspace-api/media/v4l/metafmt-uvc
userspace-api/media/v4l/pixfmt-meta-vivid userspace-api/media/v4l/metafmt-vivid
userspace-api/media/v4l/pixfmt-meta-vsp1-hgo userspace-api/media/v4l/metafmt-vsp1-hgo
userspace-api/media/v4l/pixfmt-meta-vsp1-hgt userspace-api/media/v4l/metafmt-vsp1-hgt
virt/coco/sevguest virt/coco/sev-guest
virt/kvm/amd-memory-encryption virt/kvm/x86/amd-memory-encryption
virt/kvm/arm/psci virt/kvm/arm/fw-pseudo-registers
virt/kvm/cpuid virt/kvm/x86/cpuid
virt/kvm/hypercalls virt/kvm/x86/hypercalls
virt/kvm/mmu virt/kvm/x86/mmu
virt/kvm/msr virt/kvm/x86/msr
virt/kvm/nested-vmx virt/kvm/x86/nested-vmx
virt/kvm/running-nested-guests virt/kvm/x86/running-nested-guests
virt/kvm/s390-diag virt/kvm/s390/s390-diag
virt/kvm/s390-pv virt/kvm/s390/s390-pv
virt/kvm/s390-pv-boot virt/kvm/s390/s390-pv-boot
virt/kvm/timekeeping virt/kvm/x86/timekeeping
virt/kvm/x86/halt-polling virt/kvm/halt-polling
virtual/index virt/index
virtual/kvm/amd-memory-encryption virt/kvm/x86/amd-memory-encryption
virtual/kvm/cpuid virt/kvm/x86/cpuid
virtual/kvm/index virt/kvm/index
virtual/kvm/vcpu-requests virt/kvm/vcpu-requests
virtual/paravirt_ops virt/paravirt_ops
vm/active_mm mm/active_mm
vm/arch_pgtable_helpers mm/arch_pgtable_helpers
vm/balance mm/balance
vm/bootmem mm/bootmem
vm/damon/api mm/damon/api
vm/damon/design mm/damon/design
vm/damon/faq mm/damon/faq
vm/damon/index mm/damon/index
vm/free_page_reporting mm/free_page_reporting
vm/highmem mm/highmem
vm/hmm mm/hmm
vm/hugetlbfs_reserv mm/hugetlbfs_reserv
vm/hugetlbpage admin-guide/mm/hugetlbpage
vm/hwpoison mm/hwpoison
vm/idle_page_tracking admin-guide/mm/idle_page_tracking
vm/index mm/index
vm/ksm mm/ksm
vm/memory-model mm/memory-model
vm/mmu_notifier mm/mmu_notifier
vm/numa mm/numa
vm/numa_memory_policy admin-guide/mm/numa_memory_policy
vm/oom mm/oom
vm/overcommit-accounting mm/overcommit-accounting
vm/page_allocation mm/page_allocation
vm/page_cache mm/page_cache
vm/page_frags mm/page_frags
vm/page_migration mm/page_migration
vm/page_owner mm/page_owner
vm/page_reclaim mm/page_reclaim
vm/page_table_check mm/page_table_check
vm/page_tables mm/page_tables
vm/pagemap admin-guide/mm/pagemap
vm/physical_memory mm/physical_memory
vm/process_addrs mm/process_addrs
vm/remap_file_pages mm/remap_file_pages
vm/shmfs mm/shmfs
vm/slab mm/slab
vm/slub admin-guide/mm/slab
vm/soft-dirty admin-guide/mm/soft-dirty
vm/split_page_table_lock mm/split_page_table_lock
vm/swap mm/swap
vm/swap_numa admin-guide/mm/swap_numa
vm/transhuge mm/transhuge
vm/unevictable-lru mm/unevictable-lru
vm/userfaultfd admin-guide/mm/userfaultfd
vm/vmalloc mm/vmalloc
vm/vmalloced-kernel-stacks mm/vmalloced-kernel-stacks
vm/vmemmap_dedup mm/vmemmap_dedup
vm/zsmalloc mm/zsmalloc
vm/zswap admin-guide/mm/zswap
watch_queue core-api/watch_queue
x86/amd-memory-encryption arch/x86/amd-memory-encryption
x86/amd_hsmp arch/x86/amd_hsmp
x86/boot arch/x86/boot
x86/booting-dt arch/x86/booting-dt
x86/buslock arch/x86/buslock
x86/cpuinfo arch/x86/cpuinfo
x86/earlyprintk arch/x86/earlyprintk
x86/elf_auxvec arch/x86/elf_auxvec
x86/entry_64 arch/x86/entry_64
x86/exception-tables arch/x86/exception-tables
x86/features arch/x86/features
x86/i386/IO-APIC arch/x86/i386/IO-APIC
x86/i386/index arch/x86/i386/index
x86/ifs arch/x86/ifs
x86/index arch/x86/index
x86/intel-hfi arch/x86/intel-hfi
x86/intel_txt arch/x86/intel_txt
x86/iommu arch/x86/iommu
x86/kernel-stacks arch/x86/kernel-stacks
x86/mds arch/x86/mds
x86/microcode arch/x86/microcode
x86/mtrr arch/x86/mtrr
x86/orc-unwinder arch/x86/orc-unwinder
x86/pat arch/x86/pat
x86/protection-keys core-api/protection-keys
x86/pti arch/x86/pti
x86/resctrl filesystems/resctrl
x86/resctrl_ui filesystems/resctrl
x86/sgx arch/x86/sgx
x86/sva arch/x86/sva
x86/tdx arch/x86/tdx
x86/tlb arch/x86/tlb
x86/topology arch/x86/topology
x86/tsx_async_abort arch/x86/tsx_async_abort
x86/usb-legacy-support arch/x86/usb-legacy-support
x86/x86_64/5level-paging arch/x86/x86_64/5level-paging
x86/x86_64/cpu-hotplug-spec arch/x86/x86_64/cpu-hotplug-spec
x86/x86_64/fake-numa-for-cpusets arch/x86/x86_64/fake-numa-for-cpusets
x86/x86_64/fsgs arch/x86/x86_64/fsgs
x86/x86_64/index arch/x86/x86_64/index
x86/x86_64/machinecheck arch/x86/x86_64/machinecheck
x86/x86_64/mm arch/x86/x86_64/mm
x86/x86_64/uefi arch/x86/x86_64/uefi
x86/xstate arch/x86/xstate
x86/zero-page arch/x86/zero-page
xilinx/eemi driver-api/xilinx/eemi
xilinx/index driver-api/xilinx/index
xtensa/atomctl arch/xtensa/atomctl
xtensa/booting arch/xtensa/booting
xtensa/features arch/xtensa/features
xtensa/index arch/xtensa/index
xtensa/mmu arch/xtensa/mmu

---

### Documentation Atomic Bitops (`Documentation/atomic_bitops.txt`)

=============
Atomic bitops
=============

While our bitmap_{}() functions are non-atomic, we have a number of operations
operating on single bits in a bitmap that are atomic.


API
---

The single bit operations are:

Non-RMW ops:

  test_bit()

RMW atomic operations without return value:

  {set,clear,change}_bit()
  clear_bit_unlock()

RMW atomic operations with return value:

  test_and_{set,clear,change}_bit()
  test_and_set_bit_lock()

Barriers:

  smp_mb__{before,after}_atomic()


All RMW atomic operations have a '__' prefixed variant which is non-atomic.


SEMANTICS
---------

Non-atomic ops:

In particular __clear_bit_unlock() suffers the same issue as atomic_set(),
which is why the generic version maps to clear_bit_unlock(), see atomic_t.txt.


RMW ops:

The test_and_{}_bit() operations return the original value of the bit.


ORDERING
--------

Like with atomic_t, the rule of thumb is:

 - non-RMW operations are unordered;

 - RMW operations that have no return value are unordered;

 - RMW operations that have a return value are fully ordered.

 - RMW operations that are conditional are fully ordered.

Except for a successful test_and_set_bit_lock() which has ACQUIRE semantics,
clear_bit_unlock() which has RELEASE semantics and test_bit_acquire which has
ACQUIRE semantics.

Since a platform only has a single means of achieving atomic operations
the same barriers as for atomic_t are used, see atomic_t.txt.

---

### Documentation Atomic T (`Documentation/atomic_t.txt`)

On atomic types (atomic_t atomic64_t and atomic_long_t).

The atomic type provides an interface to the architecture's means of atomic
RMW operations between CPUs (atomic operations on MMIO are not supported and
can lead to fatal traps on some platforms).

API
---

The 'full' API consists of (atomic64_ and atomic_long_ prefixes omitted for
brevity):

Non-RMW ops:

  atomic_read(), atomic_set()
  atomic_read_acquire(), atomic_set_release()


RMW atomic operations:

Arithmetic:

  atomic_{add,sub,inc,dec}()
  atomic_{add,sub,inc,dec}_return{,_relaxed,_acquire,_release}()
  atomic_fetch_{add,sub,inc,dec}{,_relaxed,_acquire,_release}()


Bitwise:

  atomic_{and,or,xor,andnot}()
  atomic_fetch_{and,or,xor,andnot}{,_relaxed,_acquire,_release}()


Swap:

  atomic_xchg{,_relaxed,_acquire,_release}()
  atomic_cmpxchg{,_relaxed,_acquire,_release}()
  atomic_try_cmpxchg{,_relaxed,_acquire,_release}()


Reference count (but please see refcount_t):

  atomic_add_unless(), atomic_inc_not_zero()
  atomic_sub_and_test(), atomic_dec_and_test()


Misc:

  atomic_inc_and_test(), atomic_add_negative()
  atomic_dec_unless_positive(), atomic_inc_unless_negative()


Barriers:

  smp_mb__{before,after}_atomic()


TYPES (signed vs unsigned)
-----

While atomic_t, atomic_long_t and atomic64_t use int, long and s64
respectively (for hysterical raisins), the kernel uses -fno-strict-overflow
(which implies -fwrapv) and defines signed overflow to behave like
2s-complement.

Therefore, an explicitly unsigned variant of the atomic ops is strictly
unnecessary and we can simply cast, there is no UB.

There was a bug in UBSAN prior to GCC-8 that would generate UB warnings for
signed types.

With this we also conform to the C/C++ _Atomic behaviour and things like
P1236R1.


SEMANTICS
---------

Non-RMW ops:

The non-RMW ops are (typically) regular LOADs and STOREs and are canonically
implemented using READ_ONCE(), WRITE_ONCE(), smp_load_acquire() and
smp_store_release() respectively. Therefore, if you find yourself only using
the Non-RMW operations of atomic_t, you do not in fact need atomic_t at all
and are doing it wrong.

A note for the implementation of atomic_set{}() is that it must not break the
atomicity of the RMW ops. That is:

  C Atomic-RMW-ops-are-atomic-WRT-atomic_set

  {
    atomic_t v = ATOMIC_INIT(1);
  }

  P0(atomic_t *v)
  {
    (void)atomic_add_unless(v, 1, 0);
  }

  P1(atomic_t *v)
  {
    atomic_set(v, 0);
  }

  exists
  (v=2)

In this case we would expect the atomic_set() from CPU1 to either happen
before the atomic_add_unless(), in which case that latter one would no-op, or
_after_ in which case we'd overwrite its result. In no case is "2" a valid
outcome.

This is typically true on 'normal' platforms, where a regular competing STORE
will invalidate a LL/SC or fail a CMPXCHG.

The obvious case where this is not so is when we need to implement atomic ops
with a lock:

  CPU0						CPU1

  atomic_add_unless(v, 1, 0);
    lock();
    ret = READ_ONCE(v->counter); // == 1
						atomic_set(v, 0);
    if (ret != u)				  WRITE_ONCE(v->counter, 0);
      WRITE_ONCE(v->counter, ret + 1);
    unlock();

the typical solution is to then implement atomic_set{}() with atomic_xchg().


RMW ops:

These come in various forms:

 - plain operations without return value: atomic_{}()

 - operations which return the modified value: atomic_{}_return()

   these are limited to the arithmetic operations because those are
   reversible. Bitops are irreversible and therefore the modified value
   is of dubious utility.

 - operations which return the original value: atomic_fetch_{}()

 - swap operations: xchg(), cmpxchg() and try_cmpxchg()

 - misc; the special purpose operations that are commonly used and would,
   given the interface, normally be implemented using (try_)cmpxchg loops but
   are time critical and can, (typically) on LL/SC architectures, be more
   efficiently implemented.

All these operations are SMP atomic; that is, the operations (for a single
atomic variable) can be fully ordered and no intermediate state is lost or
visible.


ORDERING  (go read memory-barriers.txt first)
--------

The rule of thumb:

 - non-RMW operations are unordered;

 - RMW operations that have no return value are unordered;

 - RMW operations that have a return value are fully ordered;

 - RMW operations that are conditional are unordered on FAILURE,
   otherwise the above rules apply.

Except of course when a successful operation has an explicit ordering like:

 {}_relaxed: unordered
 {}_acquire: the R of the RMW (or atomic_read) is an ACQUIRE
 {}_release: the W of the RMW (or atomic_set)  is a  RELEASE

Where 'unordered' is against other memory locations. Address dependencies are
not defeated.  Conditional operations are still unordered on FAILURE.

Fully ordered primitives are ordered against everything prior and everything
subsequent. Therefore a fully ordered primitive is like having an smp_mb()
before and an smp_mb() after the primitive.


The barriers:

  smp_mb__{before,after}_atomic()

only apply to the RMW atomic ops and can be used to augment/upgrade the
ordering inherent to the op. These barriers act almost like a full smp_mb():
smp_mb__before_atomic() orders all earlier accesses against the RMW op
itself and all accesses following it, and smp_mb__after_atomic() orders all
later accesses against the RMW op and all accesses preceding it. However,
accesses between the smp_mb__{before,after}_atomic() and the RMW op are not
ordered, so it is advisable to place the barrier right next to the RMW atomic
op whenever possible.

These helper barriers exist because architectures have varying implicit
ordering on their SMP atomic primitives. For example our TSO architectures
provide full ordered atomics and these barriers are no-ops.

NOTE: when the atomic RmW ops are fully ordered, they should also imply a
compiler barrier.

Thus:

  atomic_fetch_add();

is equivalent to:

  smp_mb__before_atomic();
  atomic_fetch_add_relaxed();
  smp_mb__after_atomic();

However the atomic_fetch_add() might be implemented more efficiently.

Further, while something like:

  smp_mb__before_atomic();
  atomic_dec(&X);

is a 'typical' RELEASE pattern, the barrier is strictly stronger than
a RELEASE because it orders preceding instructions against both the read
and write parts of the atomic_dec(), and against all following instructions
as well. Similarly, something like:

  atomic_inc(&X);
  smp_mb__after_atomic();

is an ACQUIRE pattern (though very much not typical), but again the barrier is
strictly stronger than ACQUIRE. As illustrated:

  C Atomic-RMW+mb__after_atomic-is-stronger-than-acquire

  {
  }

  P0(int *x, atomic_t *y)
  {
    r0 = READ_ONCE(*x);
    smp_rmb();
    r1 = atomic_read(y);
  }

  P1(int *x, atomic_t *y)
  {
    atomic_inc(y);
    smp_mb__after_atomic();
    WRITE_ONCE(*x, 1);
  }

  exists
  (0:r0=1 /\ 0:r1=0)

This should not happen; but a hypothetical atomic_inc_acquire() --
(void)atomic_fetch_inc_acquire() for instance -- would allow the outcome,
because it would not order the W part of the RMW against the following
WRITE_ONCE.  Thus:

  P0			P1

			t = LL.acq *y (0)
			t++;
			*x = 1;
  r0 = *x (1)
  RMB
  r1 = *y (0)
			SC *y, t;

is allowed.


CMPXCHG vs TRY_CMPXCHG
----------------------

  int atomic_cmpxchg(atomic_t *ptr, int old, int new);
  bool atomic_try_cmpxchg(atomic_t *ptr, int *oldp, int new);

Both provide the same functionality, but try_cmpxchg() can lead to more
compact code. The functions relate like:

  bool atomic_try_cmpxchg(atomic_t *ptr, int *oldp, int new)
  {
    int ret, old = *oldp;
    ret = atomic_cmpxchg(ptr, old, new);
    if (ret != old)
      *oldp = ret;
    return ret == old;
  }

and:

  int atomic_cmpxchg(atomic_t *ptr, int old, int new)
  {
    (void)atomic_try_cmpxchg(ptr, &old, new);
    return old;
  }

Usage:

  old = atomic_read(&v);			old = atomic_read(&v);
  for (;;) {					do {
    new = func(old);				  new = func(old);
    tmp = atomic_cmpxchg(&v, old, new);		} while (!atomic_try_cmpxchg(&v, &old, new));
    if (tmp == old)
      break;
    old = tmp;
  }

NB. try_cmpxchg() also generates better code on some platforms (notably x86)
where the function more closely matches the hardware instruction.


FORWARD PROGRESS
----------------

In general strong forward progress is expected of all unconditional atomic
operations -- those in the Arithmetic and Bitwise classes and xchg(). However
a fair amount of code also requires forward progress from the conditional
atomic operations.

Specifically 'simple' cmpxchg() loops are expected to not starve one another
indefinitely. However, this is not evident on LL/SC architectures, because
while an LL/SC architecture 'can/should/must' provide forward progress
guarantees between competing LL/SC sections, such a guarantee does not
transfer to cmpxchg() implemented using LL/SC. Consider:

  old = atomic_read(&v);
  do {
    new = func(old);
  } while (!atomic_try_cmpxchg(&v, &old, new));

which on LL/SC becomes something like:

  old = atomic_read(&v);
  do {
    new = func(old);
  } while (!({
    volatile asm ("1: LL  %[oldval], %[v]\n"
                  "   CMP %[oldval], %[old]\n"
                  "   BNE 2f\n"
                  "   SC  %[new], %[v]\n"
                  "   BNE 1b\n"
                  "2:\n"
                  : [oldval] "=&r" (oldval), [v] "m" (v)
		  : [old] "r" (old), [new] "r" (new)
                  : "memory");
    success = (oldval == old);
    if (!success)
      old = oldval;
    success; }));

However, even the forward branch from the failed compare can cause the LL/SC
to fail on some architectures, let alone whatever the compiler makes of the C
loop body. As a result there is no guarantee what so ever the cacheline
containing @v will stay on the local CPU and progress is made.

Even native CAS architectures can fail to provide forward progress for their
primitive (See Sparc64 for an example).

Such implementations are strongly encouraged to add exponential backoff loops
to a failed CAS in order to ensure some progress. Affected architectures are
also strongly encouraged to inspect/audit the atomic fallbacks, refcount_t and
their locking primitives.

---

### Documentation Index (`Documentation/index.rst`)

.. SPDX-License-Identifier: GPL-2.0

.. _linux_doc:

==============================
The Linux Kernel documentation
==============================

This is the top level of the kernel's documentation tree.  Kernel
documentation, like the kernel itself, is very much a work in progress;
that is especially true as we work to integrate our many scattered
documents into a coherent whole.  Please note that improvements to the
documentation are welcome; join the linux-doc list at vger.kernel.org if
you want to help out.

Working with the development community
======================================

The essential guides for interacting with the kernel's development
community and getting your work upstream.

.. toctree::
   :maxdepth: 1

   Development process <process/development-process>
   Submitting patches <process/submitting-patches>
   Code of conduct <process/code-of-conduct>
   Maintainer handbook <maintainer/index>
   All development-process docs <process/index>


Internal API manuals
====================

Manuals for use by developers working to interface with the rest of the
kernel.

.. toctree::
   :maxdepth: 1

   Core API <core-api/index>
   Driver APIs <driver-api/index>
   Subsystems <subsystem-apis>
   Locking <locking/index>

Development tools and processes
===============================

Various other manuals with useful information for all kernel developers.

.. toctree::
   :maxdepth: 1

   Licensing rules <process/license-rules>
   Writing documentation <doc-guide/index>
   Development tools <dev-tools/index>
   Testing guide <dev-tools/testing-overview>
   Hacking guide <kernel-hacking/index>
   Tracing <trace/index>
   Fault injection <fault-injection/index>
   Livepatching <livepatch/index>
   Rust <rust/index>


User-oriented documentation
===========================

The following manuals are written for *users* of the kernel — those who are
trying to get it to work optimally on a given system and application
developers seeking information on the kernel's user-space APIs.

.. toctree::
   :maxdepth: 1

   Administration <admin-guide/index>
   Build system <kbuild/index>
   Reporting issues <admin-guide/reporting-issues.rst>
   Userspace tools <tools/index>
   Userspace API <userspace-api/index>

See also: the `Linux man pages <https://www.kernel.org/doc/man-pages/>`_,
which are kept separately from the kernel's own documentation.

Firmware-related documentation
==============================
The following holds information on the kernel's expectations regarding the
platform firmware.

.. toctree::
   :maxdepth: 1

   Firmware <firmware-guide/index>
   Firmware and Devicetree <devicetree/index>


Architecture-specific documentation
===================================

.. toctree::
   :maxdepth: 2

   CPU architectures <arch/index>


Other documentation
===================

There are several unsorted documents that don't seem to fit on other parts
of the documentation body, or may require some adjustments and/or conversion
to reStructuredText format, or are simply too old.

.. toctree::
   :maxdepth: 1

   Unsorted documentation <staging/index>


Translations
============

.. toctree::
   :maxdepth: 2

   Translations <translations/index>

Indices and tables
==================

* :ref:`genindex`

---

### Documentation Memory Barriers (`Documentation/memory-barriers.txt`)

============================
			 LINUX KERNEL MEMORY BARRIERS
			 ============================

By: David Howells <dhowells@redhat.com>
    Paul E. McKenney <paulmck@linux.vnet.ibm.com>

Contents:

 (*) Abstract memory access model.

     - Device operations.
     - Guarantees.

 (*) What are memory barriers?

     - Varieties of memory barrier.
     - What may not be assumed about memory barriers?
     - Data dependency barriers.
     - Control dependencies.
     - SMP barrier pairing.
     - Examples of memory barrier sequences.
     - Read memory barriers vs load speculation.
     - Transitivity

 (*) Explicit kernel barriers.

     - Compiler barrier.
     - CPU memory barriers.
     - MMIO write barrier.

 (*) Implicit kernel memory barriers.

     - Locking functions.
     - Interrupt disabling functions.
     - Sleep and wake-up functions.
     - Miscellaneous functions.

 (*) Inter-CPU locking barrier effects.

     - Locks vs memory accesses.
     - Locks vs I/O accesses.

 (*) Where are memory barriers needed?

     - Interprocessor interaction.
     - Atomic operations.
     - Accessing devices.
     - Interrupts.

 (*) Kernel I/O barrier effects.

 (*) Assumed minimum execution ordering model.

 (*) The effects of the cpu cache.

     - Cache coherency.
     - Cache coherency vs DMA.
     - Cache coherency vs MMIO.

 (*) The things CPUs get up to.

     - And then there's the Alpha.

 (*) Example uses.

     - Circular buffers.

 (*) References.


============================
ABSTRACT MEMORY ACCESS MODEL
============================

Consider the following abstract model of the system:

		            :                :
		            :                :
		            :                :
		+-------+   :   +--------+   :   +-------+
		|       |   :   |        |   :   |       |
		|       |   :   |        |   :   |       |
		| CPU 1 |<----->| Memory |<----->| CPU 2 |
		|       |   :   |        |   :   |       |
		|       |   :   |        |   :   |       |
		+-------+   :   +--------+   :   +-------+
		    ^       :       ^        :       ^
		    |       :       |        :       |
		    |       :       |        :       |
		    |       :       v        :       |
		    |       :   +--------+   :       |
		    |       :   |        |   :       |
		    |       :   |        |   :       |
		    +---------->| Device |<----------+
		            :   |        |   :
		            :   |        |   :
		            :   +--------+   :
		            :                :

Each CPU executes a program that generates memory access operations.  In the
abstract CPU, memory operation ordering is very relaxed, and a CPU may actually
perform the memory operations in any order it likes, provided program causality
appears to be maintained.  Similarly, the compiler may also arrange the
instructions it emits in any order it likes, provided it doesn't affect the
apparent operation of the program.

So in the above diagram, the effects of the memory operations performed by a
CPU are perceived by the rest of the system as the operations cross the
interface between the CPU and rest of the system (the dotted lines).


For example, consider the following sequence of events:

	CPU 1		CPU 2
	===============	===============
	{ A == 1; B == 2 }
	A = 3;		x = A;
	B = 4;		y = B;

The set of accesses as seen by the memory system in the middle can be arranged
in 24 different combinations:

	STORE A=3,	STORE B=4,	x=LOAD A->3,	y=LOAD B->4
	STORE A=3,	STORE B=4,	y=LOAD B->4,	x=LOAD A->3
	STORE A=3,	x=LOAD A->3,	STORE B=4,	y=LOAD B->4
	STORE A=3,	x=LOAD A->3,	y=LOAD B->2,	STORE B=4
	STORE A=3,	y=LOAD B->2,	STORE B=4,	x=LOAD A->3
	STORE A=3,	y=LOAD B->2,	x=LOAD A->3,	STORE B=4
	STORE B=4,	STORE A=3,	x=LOAD A->3,	y=LOAD B->4
	STORE B=4, ...
	...

and can thus result in four different combinations of values:

	x == 1, y == 2
	x == 1, y == 4
	x == 3, y == 2
	x == 3, y == 4


Furthermore, the stores committed by a CPU to the memory system may not be
perceived by the loads made by another CPU in the same order as the stores were
committed.


As a further example, consider this sequence of events:

	CPU 1		CPU 2
	===============	===============
	{ A == 1, B == 2, C = 3, P == &A, Q == &C }
	B = 4;		Q = P;
	P = &B		D = *Q;

There is an obvious data dependency here, as the value loaded into D depends on
the address retrieved from P by CPU 2.  At the end of the sequence, any of the
following results are possible:

	(Q == &A) and (D == 1)
	(Q == &B) and (D == 2)
	(Q == &B) and (D == 4)

Note that CPU 2 will never try and load C into D because the CPU will load P
into Q before issuing the load of *Q.


DEVICE OPERATIONS
-----------------

Some devices present their control interfaces as collections of memory
locations, but the order in which the control registers are accessed is very
important.  For instance, imagine an ethernet card with a set of internal
registers that are accessed through an address port register (A) and a data
port register (D).  To read internal register 5, the following code might then
be used:

	*A = 5;
	x = *D;

but this might show up as either of the following two sequences:

	STORE *A = 5, x = LOAD *D
	x = LOAD *D, STORE *A = 5

the second of which will almost certainly result in a malfunction, since it set
the address _after_ attempting to read the register.


GUARANTEES
----------

There are some minimal guarantees that may be expected of a CPU:

 (*) On any given CPU, dependent memory accesses will be issued in order, with
     respect to itself.  This means that for:

	Q = P; D = *Q;

     the CPU will issue the following memory operations:

	Q = LOAD P, D = LOAD *Q

     and always in that order.

 (*) Overlapping loads and stores within a particular CPU will appear to be
     ordered within that CPU.  This means that for:

	a = *X; *X = b;

     the CPU will only issue the following sequence of memory operations:

	a = LOAD *X, STORE *X = b

     And for:

	*X = c; d = *X;

     the CPU will only issue:

	STORE *X = c, d = LOAD *X

     (Loads and stores overlap if they are targeted at overlapping pieces of
     memory).

And there are a number of things that _must_ or _must_not_ be assumed:

 (*) It _must_not_ be assumed that independent loads and stores will be issued
     in the order given.  This means that for:

	X = *A; Y = *B; *D = Z;

     we may get any of the following sequences:

	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

 (*) It _must_ be assumed that overlapping memory accesses may be merged or
     discarded.  This means that for:

	X = *A; Y = *(A + 4);

     we may get any one of the following sequences:

	X = LOAD *A; Y = LOAD *(A + 4);
	Y = LOAD *(A + 4); X = LOAD *A;
	{X, Y} = LOAD {*A, *(A + 4) };

     And for:

	*A = X; Y = *A;

     we may get either of:

	STORE *A = X; Y = LOAD *A;
	STORE *A = Y = X;


=========================
WHAT ARE MEMORY BARRIERS?
=========================

As can be seen above, independent memory operations are effectively performed
in random order, but this can be a problem for CPU-CPU interaction and for I/O.
What is required is some way of intervening to instruct the compiler and the
CPU to restrict the order.

Memory barriers are such interventions.  They impose a perceived partial
ordering over the memory operations on either side of the barrier.

Such enforcement is important because the CPUs and other devices in a system
can use a variety of tricks to improve performance, including reordering,
deferral and combination of memory operations; speculative loads; speculative
branch prediction and various types of caching.  Memory barriers are used to
override or suppress these tricks, allowing the code to sanely control the
interaction of multiple CPUs and/or devices.


VARIETIES OF MEMORY BARRIER
---------------------------

Memory barriers come in four basic varieties:

 (1) Write (or store) memory barriers.

     A write memory barrier gives a guarantee that all the STORE operations
     specified before the barrier will appear to happen before all the STORE
     operations specified after the barrier with respect to the other
     components of the system.

     A write barrier is a partial ordering on stores only; it is not required
     to have any effect on loads.

     A CPU can be viewed as committing a sequence of store operations to the
     memory system as time progresses.  All stores before a write barrier will
     occur in the sequence _before_ all the stores after the write barrier.

     [!] Note that write barriers should normally be paired with read or data
     dependency barriers; see the "SMP barrier pairing" subsection.


 (2) Data dependency barriers.

     A data dependency barrier is a weaker form of read barrier.  In the case
     where two loads are performed such that the second depends on the result
     of the first (eg: the first load retrieves the address to which the second
     load will be directed), a data dependency barrier would be required to
     make sure that the target of the second load is updated before the address
     obtained by the first load is accessed.

     A data dependency barrier is a partial ordering on interdependent loads
     only; it is not required to have any effect on stores, independent loads
     or overlapping loads.

     As mentioned in (1), the other CPUs in the system can be viewed as
     committing sequences of stores to the memory system that the CPU being
     considered can then perceive.  A data dependency barrier issued by the CPU
     under consideration guarantees that for any load preceding it, if that
     load touches one of a sequence of stores from another CPU, then by the
     time the barrier completes, the effects of all the stores prior to that
     touched by the load will be perceptible to any loads issued after the data
     dependency barrier.

     See the "Examples of memory barrier sequences" subsection for diagrams
     showing the ordering constraints.

     [!] Note that the first load really has to have a _data_ dependency and
     not a control dependency.  If the address for the second load is dependent
     on the first load, but the dependency is through a conditional rather than
     actually loading the address itself, then it's a _control_ dependency and
     a full read barrier or better is required.  See the "Control dependencies"
     subsection for more information.

     [!] Note that data dependency barriers should normally be paired with
     write barriers; see the "SMP barrier pairing" subsection.


 (3) Read (or load) memory barriers.

     A read barrier is a data dependency barrier plus a guarantee that all the
     LOAD operations specified before the barrier will appear to happen before
     all the LOAD operations specified after the barrier with respect to the
     other components of the system.

     A read barrier is a partial ordering on loads only; it is not required to
     have any effect on stores.

     Read memory barriers imply data dependency barriers, and so can substitute
     for them.

     [!] Note that read barriers should normally be paired with write barriers;
     see the "SMP barrier pairing" subsection.


 (4) General memory barriers.

     A general memory barrier gives a guarantee that all the LOAD and STORE
     operations specified before the barrier will appear to happen before all
     the LOAD and STORE operations specified after the barrier with respect to
     the other components of the system.

     A general memory barrier is a partial ordering over both loads and stores.

     General memory barriers imply both read and write memory barriers, and so
     can substitute for either.


And a couple of implicit varieties:

 (5) LOCK operations.

     This acts as a one-way permeable barrier.  It guarantees that all memory
     operations after the LOCK operation will appear to happen after the LOCK
     operation with respect to the other components of the system.

     Memory operations that occur before a LOCK operation may appear to happen
     after it completes.

     A LOCK operation should almost always be paired with an UNLOCK operation.


 (6) UNLOCK operations.

     This also acts as a one-way permeable barrier.  It guarantees that all
     memory operations before the UNLOCK operation will appear to happen before
     the UNLOCK operation with respect to the other components of the system.

     Memory operations that occur after an UNLOCK operation may appear to
     happen before it completes.

     LOCK and UNLOCK operations are guaranteed to appear with respect to each
     other strictly in the order specified.

     The use of LOCK and UNLOCK operations generally precludes the need for
     other sorts of memory barrier (but note the exceptions mentioned in the
     subsection "MMIO write barrier").


Memory barriers are only required where there's a possibility of interaction
between two CPUs or between a CPU and a device.  If it can be guaranteed that
there won't be any such interaction in any particular piece of code, then
memory barriers are unnecessary in that piece of code.


Note that these are the _minimum_ guarantees.  Different architectures may give
more substantial guarantees, but they may _not_ be relied upon outside of arch
specific code.


WHAT MAY NOT BE ASSUMED ABOUT MEMORY BARRIERS?
----------------------------------------------

There are certain things that the Linux kernel memory barriers do not guarantee:

 (*) There is no guarantee that any of the memory accesses specified before a
     memory barrier will be _complete_ by the completion of a memory barrier
     instruction; the barrier can be considered to draw a line in that CPU's
     access queue that accesses of the appropriate type may not cross.

 (*) There is no guarantee that issuing a memory barrier on one CPU will have
     any direct effect on another CPU or any other hardware in the system.  The
     indirect effect will be the order in which the second CPU sees the effects
     of the first CPU's accesses occur, but see the next point:

 (*) There is no guarantee that a CPU will see the correct order of effects
     from a second CPU's accesses, even _if_ the second CPU uses a memory
     barrier, unless the first CPU _also_ uses a matching memory barrier (see
     the subsection on "SMP Barrier Pairing").

 (*) There is no guarantee that some intervening piece of off-the-CPU
     hardware[*] will not reorder the memory accesses.  CPU cache coherency
     mechanisms should propagate the indirect effects of a memory barrier
     between CPUs, but might not do so in order.

	[*] For information on bus mastering DMA and coherency please read:

	    Documentation/PCI/pci.txt
	    Documentation/DMA-API-HOWTO.txt
	    Documentation/DMA-API.txt


DATA DEPENDENCY BARRIERS
------------------------

The usage requirements of data dependency barriers are a little subtle, and
it's not always obvious that they're needed.  To illustrate, consider the
following sequence of events:

	CPU 1		CPU 2
	===============	===============
	{ A == 1, B == 2, C = 3, P == &A, Q == &C }
	B = 4;
	<write barrier>
	P = &B
			Q = P;
			D = *Q;

There's a clear data dependency here, and it would seem that by the end of the
sequence, Q must be either &A or &B, and that:

	(Q == &A) implies (D == 1)
	(Q == &B) implies (D == 4)

But!  CPU 2's perception of P may be updated _before_ its perception of B, thus
leading to the following situation:

	(Q == &B) and (D == 2) ????

Whilst this may seem like a failure of coherency or causality maintenance, it
isn't, and this behaviour can be observed on certain real CPUs (such as the DEC
Alpha).

To deal with this, a data dependency barrier or better must be inserted
between the address load and the data load:

	CPU 1		CPU 2
	===============	===============
	{ A == 1, B == 2, C = 3, P == &A, Q == &C }
	B = 4;
	<write barrier>
	P = &B
			Q = P;
			<data dependency barrier>
			D = *Q;

This enforces the occurrence of one of the two implications, and prevents the
third possibility from arising.

[!] Note that this extremely counterintuitive situation arises most easily on
machines with split caches, so that, for example, one cache bank processes
even-numbered cache lines and the other bank processes odd-numbered cache
lines.  The pointer P might be stored in an odd-numbered cache line, and the
variable B might be stored in an even-numbered cache line.  Then, if the
even-numbered bank of the reading CPU's cache is extremely busy while the
odd-numbered bank is idle, one can see the new value of the pointer P (&B),
but the old value of the variable B (2).


Another example of where data dependency barriers might by required is where a
number is read from memory and then used to calculate the index for an array
access:

	CPU 1		CPU 2
	===============	===============
	{ M[0] == 1, M[1] == 2, M[3] = 3, P == 0, Q == 3 }
	M[1] = 4;
	<write barrier>
	P = 1
			Q = P;
			<data dependency barrier>
			D = M[Q];


The data dependency barrier is very important to the RCU system, for example.
See rcu_dereference() in include/linux/rcupdate.h.  This permits the current
target of an RCU'd pointer to be replaced with a new modified target, without
the replacement target appearing to be incompletely initialised.

See also the subsection on "Cache Coherency" for a more thorough example.


CONTROL DEPENDENCIES
--------------------

A control dependency requires a full read memory barrier, not simply a data
dependency barrier to make it work correctly.  Consider the following bit of
code:

	q = &a;
	if (p)
		q = &b;
	<data dependency barrier>
	x = *q;

This will not have the desired effect because there is no actual data
dependency, but rather a control dependency that the CPU may short-circuit by
attempting to predict the outcome in advance.  In such a case what's actually
required is:

	q = &a;
	if (p)
		q = &b;
	<read barrier>
	x = *q;


SMP BARRIER PAIRING
-------------------

When dealing with CPU-CPU interactions, certain types of memory barrier should
always be paired.  A lack of appropriate pairing is almost certainly an error.

A write barrier should always be paired with a data dependency barrier or read
barrier, though a general barrier would also be viable.  Similarly a read
barrier or a data dependency barrier should always be paired with at least an
write barrier, though, again, a general barrier is viable:

	CPU 1		CPU 2
	===============	===============
	a = 1;
	<write barrier>
	b = 2;		x = b;
			<read barrier>
			y = a;

Or:

	CPU 1		CPU 2
	===============	===============================
	a = 1;
	<write barrier>
	b = &a;		x = b;
			<data dependency barrier>
			y = *x;

Basically, the read barrier always has to be there, even though it can be of
the "weaker" type.

[!] Note that the stores before the write barrier would normally be expected to
match the loads after the read barrier or the data dependency barrier, and vice
versa:

	CPU 1                           CPU 2
	===============                 ===============
	a = 1;           }----   --->{  v = c
	b = 2;           }    \ /    {  w = d
	<write barrier>        \        <read barrier>
	c = 3;           }    / \    {  x = a;
	d = 4;           }----   --->{  y = b;


EXAMPLES OF MEMORY BARRIER SEQUENCES
------------------------------------

Firstly, write barriers act as partial orderings on store operations.
Consider the following sequence of events:

	CPU 1
	=======================
	STORE A = 1
	STORE B = 2
	STORE C = 3
	<write barrier>
	STORE D = 4
	STORE E = 5

This sequence of events is committed to the memory coherence system in an order
that the rest of the system might perceive as the unordered set of { STORE A,
STORE B, STORE C } all occurring before the unordered set of { STORE D, STORE E
}:

	+-------+       :      :
	|       |       +------+
	|       |------>| C=3  |     }     /\
	|       |  :    +------+     }-----  \  -----> Events perceptible to
	|       |  :    | A=1  |     }        \/       the rest of the system
	|       |  :    +------+     }
	| CPU 1 |  :    | B=2  |     }
	|       |       +------+     }
	|       |   wwwwwwwwwwwwwwww }   <--- At this point the write barrier
	|       |       +------+     }        requires all stores prior to the
	|       |  :    | E=5  |     }        barrier to be committed before
	|       |  :    +------+     }        further stores may take place
	|       |------>| D=4  |     }
	|       |       +------+
	+-------+       :      :
	                   |
	                   | Sequence in which stores are committed to the
	                   | memory system by CPU 1
	                   V


Secondly, data dependency barriers act as partial orderings on data-dependent
loads.  Consider the following sequence of events:

	CPU 1			CPU 2
	=======================	=======================
		{ B = 7; X = 9; Y = 8; C = &Y }
	STORE A = 1
	STORE B = 2
	<write barrier>
	STORE C = &B		LOAD X
	STORE D = 4		LOAD C (gets &B)
				LOAD *C (reads B)

Without intervention, CPU 2 may perceive the events on CPU 1 in some
effectively random order, despite the write barrier issued by CPU 1:

	+-------+       :      :                :       :
	|       |       +------+                +-------+  | Sequence of update
	|       |------>| B=2  |-----       --->| Y->8  |  | of perception on
	|       |  :    +------+     \          +-------+  | CPU 2
	| CPU 1 |  :    | A=1  |      \     --->| C->&Y |  V
	|       |       +------+       |        +-------+
	|       |   wwwwwwwwwwwwwwww   |        :       :
	|       |       +------+       |        :       :
	|       |  :    | C=&B |---    |        :       :       +-------+
	|       |  :    +------+   \   |        +-------+       |       |
	|       |------>| D=4  |    ----------->| C->&B |------>|       |
	|       |       +------+       |        +-------+       |       |
	+-------+       :      :       |        :       :       |       |
	                               |        :       :       |       |
	                               |        :       :       | CPU 2 |
	                               |        +-------+       |       |
	    Apparently incorrect --->  |        | B->7  |------>|       |
	    perception of B (!)        |        +-------+       |       |
	                               |        :       :       |       |
	                               |        +-------+       |       |
	    The load of X holds --->    \       | X->9  |------>|       |
	    up the maintenance           \      +-------+       |       |
	    of coherence of B             ----->| B->2  |       +-------+
	                                        +-------+
	                                        :       :


In the above example, CPU 2 perceives that B is 7, despite the load of *C
(which would be B) coming after the LOAD of C.

If, however, a data dependency barrier were to be placed between the load of C
and the load of *C (ie: B) on CPU 2:

	CPU 1			CPU 2
	=======================	=======================
		{ B = 7; X = 9; Y = 8; C = &Y }
	STORE A = 1
	STORE B = 2
	<write barrier>
	STORE C = &B		LOAD X
	STORE D = 4		LOAD C (gets &B)
				<data dependency barrier>
				LOAD *C (reads B)

then the following will occur:

	+-------+       :      :                :       :
	|       |       +------+                +-------+
	|       |------>| B=2  |-----       --->| Y->8  |
	|       |  :    +------+     \          +-------+
	| CPU 1 |  :    | A=1  |      \     --->| C->&Y |
	|       |       +------+       |        +-------+
	|       |   wwwwwwwwwwwwwwww   |        :       :
	|       |       +------+       |        :       :
	|       |  :    | C=&B |---    |        :       :       +-------+
	|       |  :    +------+   \   |        +-------+       |       |
	|       |------>| D=4  |    ----------->| C->&B |------>|       |
	|       |       +------+       |        +-------+       |       |
	+-------+       :      :       |        :       :       |       |
	                               |        :       :       |       |
	                               |        :       :       | CPU 2 |
	                               |        +-------+       |       |
	                               |        | X->9  |------>|       |
	                               |        +-------+       |       |
	  Makes sure all effects --->   \   ddddddddddddddddd   |       |
	  prior to the store of C        \      +-------+       |       |
	  are perceptible to              ----->| B->2  |------>|       |
	  subsequent loads                      +-------+       |       |
	                                        :       :       +-------+


And thirdly, a read barrier acts as a partial order on loads.  Consider the
following sequence of events:

	CPU 1			CPU 2
	=======================	=======================
		{ A = 0, B = 9 }
	STORE A=1
	<write barrier>
	STORE B=2
				LOAD B
				LOAD A

Without intervention, CPU 2 may then choose to perceive the events on CPU 1 in
some effectively random order, despite the write barrier issued by CPU 1:

	+-------+       :      :                :       :
	|       |       +------+                +-------+
	|       |------>| A=1  |------      --->| A->0  |
	|       |       +------+      \         +-------+
	| CPU 1 |   wwwwwwwwwwwwwwww   \    --->| B->9  |
	|       |       +------+        |       +-------+
	|       |------>| B=2  |---     |       :       :
	|       |       +------+   \    |       :       :       +-------+
	+-------+       :      :    \   |       +-------+       |       |
	                             ---------->| B->2  |------>|       |
	                                |       +-------+       | CPU 2 |
	                                |       | A->0  |------>|       |
	                                |       +-------+       |       |
	                                |       :       :       +-------+
	                                 \      :       :
	                                  \     +-------+
	                                   ---->| A->1  |
	                                        +-------+
	                                        :       :


If, however, a read barrier were to be placed between the load of B and the
load of A on CPU 2:

	CPU 1			CPU 2
	=======================	=======================
		{ A = 0, B = 9 }
	STORE A=1
	<write barrier>
	STORE B=2
				LOAD B
				<read barrier>
				LOAD A

then the partial ordering imposed by CPU 1 will be perceived correctly by CPU
2:

	+-------+       :      :                :       :
	|       |       +------+                +-------+
	|       |------>| A=1  |------      --->| A->0  |
	|       |       +------+      \         +-------+
	| CPU 1 |   wwwwwwwwwwwwwwww   \    --->| B->9  |
	|       |       +------+        |       +-------+
	|       |------>| B=2  |---     |       :       :
	|       |       +------+   \    |       :       :       +-------+
	+-------+       :      :    \   |       +-------+       |       |
	                             ---------->| B->2  |------>|       |
	                                |       +-------+       | CPU 2 |
	                                |       :       :       |       |
	                                |       :       :       |       |
	  At this point the read ---->   \  rrrrrrrrrrrrrrrrr   |       |
	  barrier causes all effects      \     +-------+       |       |
	  prior to the storage of B        ---->| A->1  |------>|       |
	  to be perceptible to CPU 2            +-------+       |       |
	                                        :       :       +-------+


To illustrate this more completely, consider what could happen if the code
contained a load of A either side of the read barrier:

	CPU 1			CPU 2
	=======================	=======================
		{ A = 0, B = 9 }
	STORE A=1
	<write barrier>
	STORE B=2
				LOAD B
				LOAD A [first load of A]
				<read barrier>
				LOAD A [second load of A]

Even though the two loads of A both occur after the load of B, they may both
come up with different values:

	+-------+       :      :                :       :
	|       |       +------+                +-------+
	|       |------>| A=1  |------      --->| A->0  |
	|       |       +------+      \         +-------+
	| CPU 1 |   wwwwwwwwwwwwwwww   \    --->| B->9  |
	|       |       +------+        |       +-------+
	|       |------>| B=2  |---     |       :       :
	|       |       +------+   \    |       :       :       +-------+
	+-------+       :      :    \   |       +-------+       |       |
	                             ---------->| B->2  |------>|       |
	                                |       +-------+       | CPU 2 |
	                                |       :       :       |       |
	                                |       :       :       |       |
	                                |       +-------+       |       |
	                                |       | A->0  |------>| 1st   |
	                                |       +-------+       |       |
	  At this point the read ---->   \  rrrrrrrrrrrrrrrrr   |       |
	  barrier causes all effects      \     +-------+       |       |
	  prior to the storage of B        ---->| A->1  |------>| 2nd   |
	  to be perceptible to CPU 2            +-------+       |       |
	                                        :       :       +-------+


But it may be that the update to A from CPU 1 becomes perceptible to CPU 2
before the read barrier completes anyway:

	+-------+       :      :                :       :
	|       |       +------+                +-------+
	|       |------>| A=1  |------      --->| A->0  |
	|       |       +------+      \         +-------+
	| CPU 1 |   wwwwwwwwwwwwwwww   \    --->| B->9  |
	|       |       +------+        |       +-------+
	|       |------>| B=2  |---     |       :       :
	|       |       +------+   \    |       :       :       +-------+
	+-------+       :      :    \   |       +-------+       |       |
	                             ---------->| B->2  |------>|       |
	                                |       +-------+       | CPU 2 |
	                                |       :       :       |       |
	                                 \      :       :       |       |
	                                  \     +-------+       |       |
	                                   ---->| A->1  |------>| 1st   |
	                                        +-------+       |       |
	                                    rrrrrrrrrrrrrrrrr   |       |
	                                        +-------+       |       |
	                                        | A->1  |------>| 2nd   |
	                                        +-------+       |       |
	                                        :       :       +-------+


The guarantee is that the second load will always come up with A == 1 if the
load of B came up with B == 2.  No such guarantee exists for the first load of
A; that may come up with either A == 0 or A == 1.


READ MEMORY BARRIERS VS LOAD SPECULATION
----------------------------------------

Many CPUs speculate with loads: that is they see that they will need to load an
item from memory, and they find a time where they're not using the bus for any
other loads, and so do the load in advance - even though they haven't actually
got to that point in the instruction execution flow yet.  This permits the
actual load instruction to potentially complete immediately because the CPU
already has the value to hand.

It may turn out that the CPU didn't actually need the value - perhaps because a
branch circumvented the load - in which case it can discard the value or just
cache it for later use.

Consider:

	CPU 1	   		CPU 2
	=======================	=======================
	 	   		LOAD B
	 	   		DIVIDE		} Divide instructions generally
	 	   		DIVIDE		} take a long time to perform
	 	   		LOAD A

Which might appear as this:

	                                        :       :       +-------+
	                                        +-------+       |       |
	                                    --->| B->2  |------>|       |
	                                        +-------+       | CPU 2 |
	                                        :       :DIVIDE |       |
	                                        +-------+       |       |
	The CPU being busy doing a --->     --->| A->0  |~~~~   |       |
	division speculates on the              +-------+   ~   |       |
	LOAD of A                               :       :   ~   |       |
	                                        :       :DIVIDE |       |
	                                        :       :   ~   |       |
	Once the divisions are complete -->     :       :   ~-->|       |
	the CPU can then perform the            :       :       |       |
	LOAD with immediate effect              :       :       +-------+


Placing a read barrier or a data dependency barrier just before the second
load:

	CPU 1	   		CPU 2
	=======================	=======================
	 	   		LOAD B
	 	   		DIVIDE
	 	   		DIVIDE
				<read barrier>
	 	   		LOAD A

will force any value speculatively obtained to be reconsidered to an extent
dependent on the type of barrier used.  If there was no change made to the
speculated memory location, then the speculated value will just be used:

	                                        :       :       +-------+
	                                        +-------+       |       |
	                                    --->| B->2  |------>|       |
	                                        +-------+       | CPU 2 |
	                                        :       :DIVIDE |       |
	                                        +-------+       |       |
	The CPU being busy doing a --->     --->| A->0  |~~~~   |       |
	division speculates on the              +-------+   ~   |       |
	LOAD of A                               :       :   ~   |       |
	                                        :       :DIVIDE |       |
	                                        :       :   ~   |       |
	                                        :       :   ~   |       |
	                                    rrrrrrrrrrrrrrrr~   |       |
	                                        :       :   ~   |       |
	                                        :       :   ~-->|       |
	                                        :       :       |       |
	                                        :       :       +-------+


but if there was an update or an invalidation from another CPU pending, then
the speculation will be cancelled and the value reloaded:

	                                        :       :       +-------+
	                                        +-------+       |       |
	                                    --->| B->2  |------>|       |
	                                        +-------+       | CPU 2 |
	                                        :       :DIVIDE |       |
	                                        +-------+       |       |
	The CPU being busy doing a --->     --->| A->0  |~~~~   |       |
	division speculates on the              +-------+   ~   |       |
	LOAD of A                               :       :   ~   |       |
	                                        :       :DIVIDE |       |
	                                        :       :   ~   |       |
	                                        :       :   ~   |       |
	                                    rrrrrrrrrrrrrrrrr   |       |
	                                        +-------+       |       |
	The speculation is discarded --->   --->| A->1  |------>|       |
	and an updated value is                 +-------+       |       |
	retrieved                               :       :       +-------+


TRANSITIVITY
------------

Transitivity is a deeply intuitive notion about ordering that is not
always provided by real computer systems.  The following example
demonstrates transitivity (also called "cumulativity"):

	CPU 1			CPU 2			CPU 3
	=======================	=======================	=======================
		{ X = 0, Y = 0 }
	STORE X=1		LOAD X			STORE Y=1
				<general barrier>	<general barrier>
				LOAD Y			LOAD X

Suppose that CPU 2's load from X returns 1 and its load from Y returns 0.
This indicates that CPU 2's load from X in some sense follows CPU 1's
store to X and that CPU 2's load from Y in some sense preceded CPU 3's
store to Y.  The question is then "Can CPU 3's load from X return 0?"

Because CPU 2's load from X in some sense came after CPU 1's store, it
is natural to expect that CPU 3's load from X must therefore return 1.
This expectation is an example of transitivity: if a load executing on
CPU A follows a load from the same variable executing on CPU B, then
CPU A's load must either return the same value that CPU B's load did,
or must return some later value.

In the Linux kernel, use of general memory barriers guarantees
transitivity.  Therefore, in the above example, if CPU 2's load from X
returns 1 and its load from Y returns 0, then CPU 3's load from X must
also return 1.

However, transitivity is -not- guaranteed for read or write barriers.
For example, suppose that CPU 2's general barrier in the above example
is changed to a read barrier as shown below:

	CPU 1			CPU 2			CPU 3
	=======================	=======================	=======================
		{ X = 0, Y = 0 }
	STORE X=1		LOAD X			STORE Y=1
				<read barrier>		<general barrier>
				LOAD Y			LOAD X

This substitution destroys transitivity: in this example, it is perfectly
legal for CPU 2's load from X to return 1, its load from Y to return 0,
and CPU 3's load from X to return 0.

The key point is that although CPU 2's read barrier orders its pair
of loads, it does not guarantee to order CPU 1's store.  Therefore, if
this example runs on a system where CPUs 1 and 2 share a store buffer
or a level of cache, CPU 2 might have early access to CPU 1's writes.
General barriers are therefore required to ensure that all CPUs agree
on the combined order of CPU 1's and CPU 2's accesses.

To reiterate, if your code requires transitivity, use general barriers
throughout.


========================
EXPLICIT KERNEL BARRIERS
========================

The Linux kernel has a variety of different barriers that act at different
levels:

  (*) Compiler barrier.

  (*) CPU memory barriers.

  (*) MMIO write barrier.


COMPILER BARRIER
----------------

The Linux kernel has an explicit compiler barrier function that prevents the
compiler from moving the memory accesses either side of it to the other side:

	barrier();

This is a general barrier - lesser varieties of compiler barrier do not exist.

The compiler barrier has no direct effect on the CPU, which may then reorder
things however it wishes.


CPU MEMORY BARRIERS
-------------------

The Linux kernel has eight basic CPU memory barriers:

	TYPE		MANDATORY		SMP CONDITIONAL
	===============	=======================	===========================
	GENERAL		mb()			smp_mb()
	WRITE		wmb()			smp_wmb()
	READ		rmb()			smp_rmb()
	DATA DEPENDENCY	read_barrier_depends()	smp_read_barrier_depends()


All memory barriers except the data dependency barriers imply a compiler
barrier. Data dependencies do not impose any additional compiler ordering.

Aside: In the case of data dependencies, the compiler would be expected to
issue the loads in the correct order (eg. `a[b]` would have to load the value
of b before loading a[b]), however there is no guarantee in the C specification
that the compiler may not speculate the value of b (eg. is equal to 1) and load
a before b (eg. tmp = a[1]; if (b != 1) tmp = a[b]; ). There is also the
problem of a compiler reloading b after having loaded a[b], thus having a newer
copy of b than a[b]. A consensus has not yet been reached about these problems,
however the ACCESS_ONCE macro is a good place to start looking.

SMP memory barriers are reduced to compiler barriers on uniprocessor compiled
systems because it is assumed that a CPU will appear to be self-consistent,
and will order overlapping accesses correctly with respect to itself.

[!] Note that SMP memory barriers _must_ be used to control the ordering of
references to shared memory on SMP systems, though the use of locking instead
is sufficient.

Mandatory barriers should not be used to control SMP effects, since mandatory
barriers unnecessarily impose overhead on UP systems. They may, however, be
used to control MMIO effects on accesses through relaxed memory I/O windows.
These are required even on non-SMP systems as they affect the order in which
memory operations appear to a device by prohibiting both the compiler and the
CPU from reordering them.


There are some more advanced barrier functions:

 (*) set_mb(var, value)

     This assigns the value to the variable and then inserts a full memory
     barrier after it, depending on the function.  It isn't guaranteed to
     insert anything more than a compiler barrier in a UP compilation.


 (*) smp_mb__before_atomic_dec();
 (*) smp_mb__after_atomic_dec();
 (*) smp_mb__before_atomic_inc();
 (*) smp_mb__after_atomic_inc();

     These are for use with atomic add, subtract, increment and decrement
     functions that don't return a value, especially when used for reference
     counting.  These functions do not imply memory barriers.

     As an example, consider a piece of code that marks an object as being dead
     and then decrements the object's reference count:

	obj->dead = 1;
	smp_mb__before_atomic_dec();
	atomic_dec(&obj->ref_count);

     This makes sure that the death mark on the object is perceived to be set
     *before* the reference counter is decremented.

     See Documentation/atomic_ops.txt for more information.  See the "Atomic
     operations" subsection for information on where to use these.


 (*) smp_mb__before_clear_bit(void);
 (*) smp_mb__after_clear_bit(void);

     These are for use similar to the atomic inc/dec barriers.  These are
     typically used for bitwise unlocking operations, so care must be taken as
     there are no implicit memory barriers here either.

     Consider implementing an unlock operation of some nature by clearing a
     locking bit.  The clear_bit() would then need to be barriered like this:

	smp_mb__before_clear_bit();
	clear_bit( ... );

     This prevents memory operations before the clear leaking to after it.  See
     the subsection on "Locking Functions" with reference to UNLOCK operation
     implications.

     See Documentation/atomic_ops.txt for more information.  See the "Atomic
     operations" subsection for information on where to use these.


MMIO WRITE BARRIER
------------------

The Linux kernel also has a special barrier for use with memory-mapped I/O
writes:

	mmiowb();

This is a variation on the mandatory write barrier that causes writes to weakly
ordered I/O regions to be partially ordered.  Its effects may go beyond the
CPU->Hardware interface and actually affect the hardware at some level.

See the subsection "Locks vs I/O accesses" for more information.


===============================
IMPLICIT KERNEL MEMORY BARRIERS
===============================

Some of the other functions in the linux kernel imply memory barriers, amongst
which are locking and scheduling functions.

This specification is a _minimum_ guarantee; any particular architecture may
provide more substantial guarantees, but these may not be relied upon outside
of arch specific code.


LOCKING FUNCTIONS
-----------------

The Linux kernel has a number of locking constructs:

 (*) spin locks
 (*) R/W spin locks
 (*) mutexes
 (*) semaphores
 (*) R/W semaphores
 (*) RCU

In all cases there are variants on "LOCK" operations and "UNLOCK" operations
for each construct.  These operations all imply certain barriers:

 (1) LOCK operation implication:

     Memory operations issued after the LOCK will be completed after the LOCK
     operation has completed.

     Memory operations issued before the LOCK may be completed after the LOCK
     operation has completed.

 (2) UNLOCK operation implication:

     Memory operations issued before the UNLOCK will be completed before the
     UNLOCK operation has completed.

     Memory operations issued after the UNLOCK may be completed before the
     UNLOCK operation has completed.

 (3) LOCK vs LOCK implication:

     All LOCK operations issued before another LOCK operation will be completed
     before that LOCK operation.

 (4) LOCK vs UNLOCK implication:

     All LOCK operations issued before an UNLOCK operation will be completed
     before the UNLOCK operation.

     All UNLOCK operations issued before a LOCK operation will be completed
     before the LOCK operation.

 (5) Failed conditional LOCK implication:

     Certain variants of the LOCK operation may fail, either due to being
     unable to get the lock immediately, or due to receiving an unblocked
     signal whilst asleep waiting for the lock to become available.  Failed
     locks do not imply any sort of barrier.

Therefore, from (1), (2) and (4) an UNLOCK followed by an unconditional LOCK is
equivalent to a full barrier, but a LOCK followed by an UNLOCK is not.

[!] Note: one of the consequences of LOCKs and UNLOCKs being only one-way
    barriers is that the effects of instructions outside of a critical section
    may seep into the inside of the critical section.

A LOCK followed by an UNLOCK may not be assumed to be full memory barrier
because it is possible for an access preceding the LOCK to happen after the
LOCK, and an access following the UNLOCK to happen before the UNLOCK, and the
two accesses can themselves then cross:

	*A = a;
	LOCK
	UNLOCK
	*B = b;

may occur as:

	LOCK, STORE *B, STORE *A, UNLOCK

Locks and semaphores may not provide any guarantee of ordering on UP compiled
systems, and so cannot be counted on in such a situation to actually achieve
anything at all - especially with respect to I/O accesses - unless combined
with interrupt disabling operations.

See also the section on "Inter-CPU locking barrier effects".


As an example, consider the following:

	*A = a;
	*B = b;
	LOCK
	*C = c;
	*D = d;
	UNLOCK
	*E = e;
	*F = f;

The following sequence of events is acceptable:

	LOCK, {*F,*A}, *E, {*C,*D}, *B, UNLOCK

	[+] Note that {*F,*A} indicates a combined access.

But none of the following are:

	{*F,*A}, *B,	LOCK, *C, *D,	UNLOCK, *E
	*A, *B, *C,	LOCK, *D,	UNLOCK, *E, *F
	*A, *B,		LOCK, *C,	UNLOCK, *D, *E, *F
	*B,		LOCK, *C, *D,	UNLOCK, {*F,*A}, *E



INTERRUPT DISABLING FUNCTIONS
-----------------------------

Functions that disable interrupts (LOCK equivalent) and enable interrupts
(UNLOCK equivalent) will act as compiler barriers only.  So if memory or I/O
barriers are required in such a situation, they must be provided from some
other means.


SLEEP AND WAKE-UP FUNCTIONS
---------------------------

Sleeping and waking on an event flagged in global data can be viewed as an
interaction between two pieces of data: the task state of the task waiting for
the event and the global data used to indicate the event.  To make sure that
these appear to happen in the right order, the primitives to begin the process
of going to sleep, and the primitives to initiate a wake up imply certain
barriers.

Firstly, the sleeper normally follows something like this sequence of events:

	for (;;) {
		set_current_state(TASK_UNINTERRUPTIBLE);
		if (event_indicated)
			break;
		schedule();
	}

A general memory barrier is interpolated automatically by set_current_state()
after it has altered the task state:

	CPU 1
	===============================
	set_current_state();
	  set_mb();
	    STORE current->state
	    <general barrier>
	LOAD event_indicated

set_current_state() may be wrapped by:

	prepare_to_wait();
	prepare_to_wait_exclusive();

which therefore also imply a general memory barrier after setting the state.
The whole sequence above is available in various canned forms, all of which
interpolate the memory barrier in the right place:

	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();


Secondly, code that performs a wake up normally follows something like this:

	event_indicated = 1;
	wake_up(&event_wait_queue);

or:

	event_indicated = 1;
	wake_up_process(event_daemon);

A write memory barrier is implied by wake_up() and co. if and only if they wake
something up.  The barrier occurs before the task state is cleared, and so sits
between the STORE to indicate the event and the STORE to set TASK_RUNNING:

	CPU 1				CPU 2
	===============================	===============================
	set_current_state();		STORE event_indicated
	  set_mb();			wake_up();
	    STORE current->state	  <write barrier>
	    <general barrier>		  STORE current->state
	LOAD event_indicated

The available waker functions include:

	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();


[!] Note that the memory barriers implied by the sleeper and the waker do _not_
order multiple stores before the wake-up with respect to loads of those stored
values after the sleeper has called set_current_state().  For instance, if the
sleeper does:

	set_current_state(TASK_INTERRUPTIBLE);
	if (event_indicated)
		break;
	__set_current_state(TASK_RUNNING);
	do_something(my_data);

and the waker does:

	my_data = value;
	event_indicated = 1;
	wake_up(&event_wait_queue);

there's no guarantee that the change to event_indicated will be perceived by
the sleeper as coming after the change to my_data.  In such a circumstance, the
code on both sides must interpolate its own memory barriers between the
separate data accesses.  Thus the above sleeper ought to do:

	set_current_state(TASK_INTERRUPTIBLE);
	if (event_indicated) {
		smp_rmb();
		do_something(my_data);
	}

and the waker should do:

	my_data = value;
	smp_wmb();
	event_indicated = 1;
	wake_up(&event_wait_queue);


MISCELLANEOUS FUNCTIONS
-----------------------

Other functions that imply barriers:

 (*) schedule() and similar imply full memory barriers.


=================================
INTER-CPU LOCKING BARRIER EFFECTS
=================================

On SMP systems locking primitives give a more substantial form of barrier: one
that does affect memory access ordering on other CPUs, within the context of
conflict on any particular lock.


LOCKS VS MEMORY ACCESSES
------------------------

Consider the following: the system has a pair of spinlocks (M) and (Q), and
three CPUs; then should the following sequence of events occur:

	CPU 1				CPU 2
	===============================	===============================
	*A = a;				*E = e;
	LOCK M				LOCK Q
	*B = b;				*F = f;
	*C = c;				*G = g;
	UNLOCK M			UNLOCK Q
	*D = d;				*H = h;

Then there is no guarantee as to what order CPU 3 will see the accesses to *A
through *H occur in, other than the constraints imposed by the separate locks
on the separate CPUs. It might, for example, see:

	*E, LOCK M, LOCK Q, *G, *C, *F, *A, *B, UNLOCK Q, *D, *H, UNLOCK M

But it won't see any of:

	*B, *C or *D preceding LOCK M
	*A, *B or *C following UNLOCK M
	*F, *G or *H preceding LOCK Q
	*E, *F or *G following UNLOCK Q


However, if the following occurs:

	CPU 1				CPU 2
	===============================	===============================
	*A = a;
	LOCK M		[1]
	*B = b;
	*C = c;
	UNLOCK M	[1]
	*D = d;				*E = e;
					LOCK M		[2]
					*F = f;
					*G = g;
					UNLOCK M	[2]
					*H = h;

CPU 3 might see:

	*E, LOCK M [1], *C, *B, *A, UNLOCK M [1],
		LOCK M [2], *H, *F, *G, UNLOCK M [2], *D

But assuming CPU 1 gets the lock first, CPU 3 won't see any of:

	*B, *C, *D, *F, *G or *H preceding LOCK M [1]
	*A, *B or *C following UNLOCK M [1]
	*F, *G or *H preceding LOCK M [2]
	*A, *B, *C, *E, *F or *G following UNLOCK M [2]


LOCKS VS I/O ACCESSES
---------------------

Under certain circumstances (especially involving NUMA), I/O accesses within
two spinlocked sections on two different CPUs may be seen as interleaved by the
PCI bridge, because the PCI bridge does not necessarily participate in the
cache-coherence protocol, and is therefore incapable of issuing the required
read memory barriers.

For example:

	CPU 1				CPU 2
	===============================	===============================
	spin_lock(Q)
	writel(0, ADDR)
	writel(1, DATA);
	spin_unlock(Q);
					spin_lock(Q);
					writel(4, ADDR);
					writel(5, DATA);
					spin_unlock(Q);

may be seen by the PCI bridge as follows:

	STORE *ADDR = 0, STORE *ADDR = 4, STORE *DATA = 1, STORE *DATA = 5

which would probably cause the hardware to malfunction.


What is necessary here is to intervene with an mmiowb() before dropping the
spinlock, for example:

	CPU 1				CPU 2
	===============================	===============================
	spin_lock(Q)
	writel(0, ADDR)
	writel(1, DATA);
	mmiowb();
	spin_unlock(Q);
					spin_lock(Q);
					writel(4, ADDR);
					writel(5, DATA);
					mmiowb();
					spin_unlock(Q);

this will ensure that the two stores issued on CPU 1 appear at the PCI bridge
before either of the stores issued on CPU 2.


Furthermore, following a store by a load from the same device obviates the need
for the mmiowb(), because the load forces the store to complete before the load
is performed:

	CPU 1				CPU 2
	===============================	===============================
	spin_lock(Q)
	writel(0, ADDR)
	a = readl(DATA);
	spin_unlock(Q);
					spin_lock(Q);
					writel(4, ADDR);
					b = readl(DATA);
					spin_unlock(Q);


See Documentation/DocBook/deviceiobook.tmpl for more information.


=================================
WHERE ARE MEMORY BARRIERS NEEDED?
=================================

Under normal operation, memory operation reordering is generally not going to
be a problem as a single-threaded linear piece of code will still appear to
work correctly, even if it's in an SMP kernel.  There are, however, four
circumstances in which reordering definitely _could_ be a problem:

 (*) Interprocessor interaction.

 (*) Atomic operations.

 (*) Accessing devices.

 (*) Interrupts.


INTERPROCESSOR INTERACTION
--------------------------

When there's a system with more than one processor, more than one CPU in the
system may be working on the same data set at the same time.  This can cause
synchronisation problems, and the usual way of dealing with them is to use
locks.  Locks, however, are quite expensive, and so it may be preferable to
operate without the use of a lock if at all possible.  In such a case
operations that affect both CPUs may have to be carefully ordered to prevent
a malfunction.

Consider, for example, the R/W semaphore slow path.  Here a waiting process is
queued on the semaphore, by virtue of it having a piece of its stack linked to
the semaphore's list of waiting processes:

	struct rw_semaphore {
		...
		spinlock_t lock;
		struct list_head waiters;
	};

	struct rwsem_waiter {
		struct list_head list;
		struct task_struct *task;
	};

To wake up a particular waiter, the up_read() or up_write() functions have to:

 (1) read the next pointer from this waiter's record to know as to where the
     next waiter record is;

 (2) read the pointer to the waiter's task structure;

 (3) clear the task pointer to tell the waiter it has been given the semaphore;

 (4) call wake_up_process() on the task; and

 (5) release the reference held on the waiter's task struct.

In other words, it has to perform this sequence of events:

	LOAD waiter->list.next;
	LOAD waiter->task;
	STORE waiter->task;
	CALL wakeup
	RELEASE task

and if any of these steps occur out of order, then the whole thing may
malfunction.

Once it has queued itself and dropped the semaphore lock, the waiter does not
get the lock again; it instead just waits for its task pointer to be cleared
before proceeding.  Since the record is on the waiter's stack, this means that
if the task pointer is cleared _before_ the next pointer in the list is read,
another CPU might start processing the waiter and might clobber the waiter's
stack before the up*() function has a chance to read the next pointer.

Consider then what might happen to the above sequence of events:

	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 ---

This could be dealt with using the semaphore lock, but then the down_xxx()
function has to needlessly get the spinlock again after being woken up.

The way to deal with this is to insert a general SMP memory barrier:

	LOAD waiter->list.next;
	LOAD waiter->task;
	smp_mb();
	STORE waiter->task;
	CALL wakeup
	RELEASE task

In this case, the barrier makes a guarantee that all memory accesses before the
barrier will appear to happen before all the memory accesses after the barrier
with respect to the other CPUs on the system.  It does _not_ guarantee that all
the memory accesses before the barrier will be complete by the time the barrier
instruction itself is complete.

On a UP system - where this wouldn't be a problem - the smp_mb() is just a
compiler barrier, thus making sure the compiler emits the instructions in the
right order without actually intervening in the CPU.  Since there's only one
CPU, that CPU's dependency ordering logic will take care of everything else.


ATOMIC OPERATIONS
-----------------

Whilst they are technically interprocessor interaction considerations, atomic
operations are noted specially as some of them imply full memory barriers and
some don't, but they're very heavily relied on as a group throughout the
kernel.

Any atomic operation that modifies some state in memory and returns information
about the state (old or new) implies an SMP-conditional general memory barrier
(smp_mb()) on each side of the actual operation (with the exception of
explicit lock operations, described later).  These include:

	xchg();
	cmpxchg();
	atomic_cmpxchg();
	atomic_inc_return();
	atomic_dec_return();
	atomic_add_return();
	atomic_sub_return();
	atomic_inc_and_test();
	atomic_dec_and_test();
	atomic_sub_and_test();
	atomic_add_negative();
	atomic_add_unless();	/* when succeeds (returns 1) */
	test_and_set_bit();
	test_and_clear_bit();
	test_and_change_bit();

These are used for such things as implementing LOCK-class and UNLOCK-class
operations and adjusting reference counters towards object destruction, and as
such the implicit memory barrier effects are necessary.


The following operations are potential problems as they do _not_ imply memory
barriers, but might be used for implementing such things as UNLOCK-class
operations:

	atomic_set();
	set_bit();
	clear_bit();
	change_bit();

With these the appropriate explicit memory barrier should be used if necessary
(smp_mb__before_clear_bit() for instance).


The following also do _not_ imply memory barriers, and so may require explicit
memory barriers under some circumstances (smp_mb__before_atomic_dec() for
instance):

	atomic_add();
	atomic_sub();
	atomic_inc();
	atomic_dec();

If they're used for statistics generation, then they probably don't need memory
barriers, unless there's a coupling between statistical data.

If they're used for reference counting on an object to control its lifetime,
they probably don't need memory barriers because either the reference count
will be adjusted inside a locked section, or the caller will already hold
sufficient references to make the lock, and thus a memory barrier unnecessary.

If they're used for constructing a lock of some description, then they probably
do need memory barriers as a lock primitive generally has to do things in a
specific order.

Basically, each usage case has to be carefully considered as to whether memory
barriers are needed or not.

The following operations are special locking primitives:

	test_and_set_bit_lock();
	clear_bit_unlock();
	__clear_bit_unlock();

These implement LOCK-class and UNLOCK-class operations. These should be used in
preference to other operations when implementing locking primitives, because
their implementations can be optimised on many architectures.

[!] Note that special memory barrier primitives are available for these
situations because on some CPUs the atomic instructions used imply full memory
barriers, and so barrier instructions are superfluous in conjunction with them,
and in such cases the special barrier primitives will be no-ops.

See Documentation/atomic_ops.txt for more information.


ACCESSING DEVICES
-----------------

Many devices can be memory mapped, and so appear to the CPU as if they're just
a set of memory locations.  To control such a device, the driver usually has to
make the right memory accesses in exactly the right order.

However, having a clever CPU or a clever compiler creates a potential problem
in that the carefully sequenced accesses in the driver code won't reach the
device in the requisite order if the CPU or the compiler thinks it is more
efficient to reorder, combine or merge accesses - something that would cause
the device to malfunction.

Inside of the Linux kernel, I/O should be done through the appropriate accessor
routines - such as inb() or writel() - which know how to make such accesses
appropriately sequential.  Whilst this, for the most part, renders the explicit
use of memory barriers unnecessary, there are a couple of situations where they
might be needed:

 (1) On some systems, I/O stores are not strongly ordered across all CPUs, and
     so for _all_ general drivers locks should be used and mmiowb() must be
     issued prior to unlocking the critical section.

 (2) If the accessor functions are used to refer to an I/O memory window with
     relaxed memory access properties, then _mandatory_ memory barriers are
     required to enforce ordering.

See Documentation/DocBook/deviceiobook.tmpl for more information.


INTERRUPTS
----------

A driver may be interrupted by its own interrupt service routine, and thus the
two parts of the driver may interfere with each other's attempts to control or
access the device.

This may be alleviated - at least in part - by disabling local interrupts (a
form of locking), such that the critical operations are all contained within
the interrupt-disabled section in the driver.  Whilst the driver's interrupt
routine is executing, the driver's core may not run on the same CPU, and its
interrupt is not permitted to happen again until the current interrupt has been
handled, thus the interrupt handler does not need to lock against that.

However, consider a driver that was talking to an ethernet card that sports an
address register and a data register.  If that driver's core talks to the card
under interrupt-disablement and then the driver's interrupt handler is invoked:

	LOCAL IRQ DISABLE
	writew(ADDR, 3);
	writew(DATA, y);
	LOCAL IRQ ENABLE
	<interrupt>
	writew(ADDR, 4);
	q = readw(DATA);
	</interrupt>

The store to the data register might happen after the second store to the
address register if ordering rules are sufficiently relaxed:

	STORE *ADDR = 3, STORE *ADDR = 4, STORE *DATA = y, q = LOAD *DATA


If ordering rules are relaxed, it must be assumed that accesses done inside an
interrupt disabled section may leak outside of it and may interleave with
accesses performed in an interrupt - and vice versa - unless implicit or
explicit barriers are used.

Normally this won't be a problem because the I/O accesses done inside such
sections will include synchronous load operations on strictly ordered I/O
registers that form implicit I/O barriers. If this isn't sufficient then an
mmiowb() may need to be used explicitly.


A similar situation may occur between an interrupt routine and two routines
running on separate CPUs that communicate with each other. If such a case is
likely, then interrupt-disabling locks should be used to guarantee ordering.


==========================
KERNEL I/O BARRIER EFFECTS
==========================

When accessing I/O memory, drivers should use the appropriate accessor
functions:

 (*) inX(), outX():

     These are intended to talk to I/O space rather than memory space, but
     that's primarily a CPU-specific concept. The i386 and x86_64 processors do
     indeed have special I/O space access cycles and instructions, but many
     CPUs don't have such a concept.

     The PCI bus, amongst others, defines an I/O space concept which - on such
     CPUs as i386 and x86_64 - readily maps to the CPU's concept of I/O
     space.  However, it may also be mapped as a virtual I/O space in the CPU's
     memory map, particularly on those CPUs that don't support alternate I/O
     spaces.

     Accesses to this space may be fully synchronous (as on i386), but
     intermediary bridges (such as the PCI host bridge) may not fully honour
     that.

     They are guaranteed to be fully ordered with respect to each other.

     They are not guaranteed to be fully ordered with respect to other types of
     memory and I/O operation.

 (*) readX(), writeX():

     Whether these are guaranteed to be fully ordered and uncombined with
     respect to each other on the issuing CPU depends on the characteristics
     defined for the memory window through which they're accessing. On later
     i386 architecture machines, for example, this is controlled by way of the
     MTRR registers.

     Ordinarily, these will be guaranteed to be fully ordered and uncombined,
     provided they're not accessing a prefetchable device.

     However, intermediary hardware (such as a PCI bridge) may indulge in
     deferral if it so wishes; to flush a store, a load from the same location
     is preferred[*], but a load from the same device or from configuration
     space should suffice for PCI.

     [*] NOTE! attempting to load from the same location as was written to may
     	 cause a malfunction - consider the 16550 Rx/Tx serial registers for
     	 example.

     Used with prefetchable I/O memory, an mmiowb() barrier may be required to
     force stores to be ordered.

     Please refer to the PCI specification for more information on interactions
     between PCI transactions.

 (*) readX_relaxed()

     These are similar to readX(), but are not guaranteed to be ordered in any
     way. Be aware that there is no I/O read barrier available.

 (*) ioreadX(), iowriteX()

     These will perform appropriately for the type of access they're actually
     doing, be it inX()/outX() or readX()/writeX().


========================================
ASSUMED MINIMUM EXECUTION ORDERING MODEL
========================================

It has to be assumed that the conceptual CPU is weakly-ordered but that it will
maintain the appearance of program causality with respect to itself.  Some CPUs
(such as i386 or x86_64) are more constrained than others (such as powerpc or
frv), and so the most relaxed case (namely DEC Alpha) must be assumed outside
of arch-specific code.

This means that it must be considered that the CPU will execute its instruction
stream in any order it feels like - or even in parallel - provided that if an
instruction in the stream depends on an earlier instruction, then that
earlier instruction must be sufficiently complete[*] before the later
instruction may proceed; in other words: provided that the appearance of
causality is maintained.

 [*] Some instructions have more than one effect - such as changing the
     condition codes, changing registers or changing memory - and different
     instructions may depend on different effects.

A CPU may also discard any instruction sequence that winds up having no
ultimate effect.  For example, if two adjacent instructions both load an
immediate value into the same register, the first may be discarded.


Similarly, it has to be assumed that compiler might reorder the instruction
stream in any way it sees fit, again provided the appearance of causality is
maintained.


============================
THE EFFECTS OF THE CPU CACHE
============================

The way cached memory operations are perceived across the system is affected to
a certain extent by the caches that lie between CPUs and memory, and by the
memory coherence system that maintains the consistency of state in the system.

As far as the way a CPU interacts with another part of the system through the
caches goes, the memory system has to include the CPU's caches, and memory
barriers for the most part act at the interface between the CPU and its cache
(memory barriers logically act on the dotted line in the following diagram):

	    <--- CPU --->         :       <----------- Memory ----------->
	                          :
	+--------+    +--------+  :   +--------+    +-----------+
	|        |    |        |  :   |        |    |           |    +--------+
	|  CPU   |    | Memory |  :   | CPU    |    |           |    |	      |
	|  Core  |--->| Access |----->| Cache  |<-->|           |    |	      |
	|        |    | Queue  |  :   |        |    |           |--->| Memory |
	|        |    |        |  :   |        |    |           |    |	      |
	+--------+    +--------+  :   +--------+    |           |    | 	      |
	                          :                 | Cache     |    +--------+
	                          :                 | Coherency |
	                          :                 | Mechanism |    +--------+
	+--------+    +--------+  :   +--------+    |           |    |	      |
	|        |    |        |  :   |        |    |           |    |        |
	|  CPU   |    | Memory |  :   | CPU    |    |           |--->| Device |
	|  Core  |--->| Access |----->| Cache  |<-->|           |    | 	      |
	|        |    | Queue  |  :   |        |    |           |    | 	      |
	|        |    |        |  :   |        |    |           |    +--------+
	+--------+    +--------+  :   +--------+    +-----------+
	                          :
	                          :

Although any particular load or store may not actually appear outside of the
CPU that issued it since it may have been satisfied within the CPU's own cache,
it will still appear as if the full memory access had taken place as far as the
other CPUs are concerned since the cache coherency mechanisms will migrate the
cacheline over to the accessing CPU and propagate the effects upon conflict.

The CPU core may execute instructions in any order it deems fit, provided the
expected program causality appears to be maintained.  Some of the instructions
generate load and store operations which then go into the queue of memory
accesses to be performed.  The core may place these in the queue in any order
it wishes, and continue execution until it is forced to wait for an instruction
to complete.

What memory barriers are concerned with is controlling the order in which
accesses cross from the CPU side of things to the memory side of things, and
the order in which the effects are perceived to happen by the other observers
in the system.

[!] Memory barriers are _not_ needed within a given CPU, as CPUs always see
their own loads and stores as if they had happened in program order.

[!] MMIO or other device accesses may bypass the cache system.  This depends on
the properties of the memory window through which devices are accessed and/or
the use of any special device communication instructions the CPU may have.


CACHE COHERENCY
---------------

Life isn't quite as simple as it may appear above, however: for while the
caches are expected to be coherent, there's no guarantee that that coherency
will be ordered.  This means that whilst changes made on one CPU will
eventually become visible on all CPUs, there's no guarantee that they will
become apparent in the same order on those other CPUs.


Consider dealing with a system that has a pair of CPUs (1 & 2), each of which
has a pair of parallel data caches (CPU 1 has A/B, and CPU 2 has C/D):

	            :
	            :                          +--------+
	            :      +---------+         |        |
	+--------+  : +--->| Cache A |<------->|        |
	|        |  : |    +---------+         |        |
	|  CPU 1 |<---+                        |        |
	|        |  : |    +---------+         |        |
	+--------+  : +--->| Cache B |<------->|        |
	            :      +---------+         |        |
	            :                          | Memory |
	            :      +---------+         | System |
	+--------+  : +--->| Cache C |<------->|        |
	|        |  : |    +---------+         |        |
	|  CPU 2 |<---+                        |        |
	|        |  : |    +---------+         |        |
	+--------+  : +--->| Cache D |<------->|        |
	            :      +---------+         |        |
	            :                          +--------+
	            :

Imagine the system has the following properties:

 (*) an odd-numbered cache line may be in cache A, cache C or it may still be
     resident in memory;

 (*) an even-numbered cache line may be in cache B, cache D or it may still be
     resident in memory;

 (*) whilst the CPU core is interrogating one cache, the other cache may be
     making use of the bus to access the rest of the system - perhaps to
     displace a dirty cacheline or to do a speculative load;

 (*) each cache has a queue of operations that need to be applied to that cache
     to maintain coherency with the rest of the system;

 (*) the coherency queue is not flushed by normal loads to lines already
     present in the cache, even though the contents of the queue may
     potentially affect those loads.

Imagine, then, that two writes are made on the first CPU, with a write barrier
between them to guarantee that they will appear to reach that CPU's caches in
the requisite order:

	CPU 1		CPU 2		COMMENT
	===============	===============	=======================================
					u == 0, v == 1 and p == &u, q == &u
	v = 2;
	smp_wmb();			Make sure change to v is visible before
					 change to p
	<A:modify v=2>			v is now in cache A exclusively
	p = &v;
	<B:modify p=&v>			p is now in cache B exclusively

The write memory barrier forces the other CPUs in the system to perceive that
the local CPU's caches have apparently been updated in the correct order.  But
now imagine that the second CPU wants to read those values:

	CPU 1		CPU 2		COMMENT
	===============	===============	=======================================
	...
			q = p;
			x = *q;

The above pair of reads may then fail to happen in the expected order, as the
cacheline holding p may get updated in one of the second CPU's caches whilst
the update to the cacheline holding v is delayed in the other of the second
CPU's caches by some other cache event:

	CPU 1		CPU 2		COMMENT
	===============	===============	=======================================
					u == 0, v == 1 and p == &u, q == &u
	v = 2;
	smp_wmb();
	<A:modify v=2>	<C:busy>
			<C:queue v=2>
	p = &v;		q = p;
			<D:request p>
	<B:modify p=&v>	<D:commit p=&v>
		  	<D:read p>
			x = *q;
			<C:read *q>	Reads from v before v updated in cache
			<C:unbusy>
			<C:commit v=2>

Basically, whilst both cachelines will be updated on CPU 2 eventually, there's
no guarantee that, without intervention, the order of update will be the same
as that committed on CPU 1.


To intervene, we need to interpolate a data dependency barrier or a read
barrier between the loads.  This will force the cache to commit its coherency
queue before processing any further requests:

	CPU 1		CPU 2		COMMENT
	===============	===============	=======================================
					u == 0, v == 1 and p == &u, q == &u
	v = 2;
	smp_wmb();
	<A:modify v=2>	<C:busy>
			<C:queue v=2>
	p = &v;		q = p;
			<D:request p>
	<B:modify p=&v>	<D:commit p=&v>
		  	<D:read p>
			smp_read_barrier_depends()
			<C:unbusy>
			<C:commit v=2>
			x = *q;
			<C:read *q>	Reads from v after v updated in cache


This sort of problem can be encountered on DEC Alpha processors as they have a
split cache that improves performance by making better use of the data bus.
Whilst most CPUs do imply a data dependency barrier on the read when a memory
access depends on a read, not all do, so it may not be relied on.

Other CPUs may also have split caches, but must coordinate between the various
cachelets for normal memory accesses.  The semantics of the Alpha removes the
need for coordination in the absence of memory barriers.


CACHE COHERENCY VS DMA
----------------------

Not all systems maintain cache coherency with respect to devices doing DMA.  In
such cases, a device attempting DMA may obtain stale data from RAM because
dirty cache lines may be resident in the caches of various CPUs, and may not
have been written back to RAM yet.  To deal with this, the appropriate part of
the kernel must flush the overlapping bits of cache on each CPU (and maybe
invalidate them as well).

In addition, the data DMA'd to RAM by a device may be overwritten by dirty
cache lines being written back to RAM from a CPU's cache after the device has
installed its own data, or cache lines present in the CPU's cache may simply
obscure the fact that RAM has been updated, until at such time as the cacheline
is discarded from the CPU's cache and reloaded.  To deal with this, the
appropriate part of the kernel must invalidate the overlapping bits of the
cache on each CPU.

See Documentation/cachetlb.txt for more information on cache management.


CACHE COHERENCY VS MMIO
-----------------------

Memory mapped I/O usually takes place through memory locations that are part of
a window in the CPU's memory space that has different properties assigned than
the usual RAM directed window.

Amongst these properties is usually the fact that such accesses bypass the
caching entirely and go directly to the device buses.  This means MMIO accesses
may, in effect, overtake accesses to cached memory that were emitted earlier.
A memory barrier isn't sufficient in such a case, but rather the cache must be
flushed between the cached memory write and the MMIO access if the two are in
any way dependent.


=========================
THE THINGS CPUS GET UP TO
=========================

A programmer might take it for granted that the CPU will perform memory
operations in exactly the order specified, so that if the CPU is, for example,
given the following piece of code to execute:

	a = *A;
	*B = b;
	c = *C;
	d = *D;
	*E = e;

they would then expect that the CPU will complete the memory operation for each
instruction before moving on to the next one, leading to a definite sequence of
operations as seen by external observers in the system:

	LOAD *A, STORE *B, LOAD *C, LOAD *D, STORE *E.


Reality is, of course, much messier.  With many CPUs and compilers, the above
assumption doesn't hold because:

 (*) loads are more likely to need to be completed immediately to permit
     execution progress, whereas stores can often be deferred without a
     problem;

 (*) loads may be done speculatively, and the result discarded should it prove
     to have been unnecessary;

 (*) loads may be done speculatively, leading to the result having been fetched
     at the wrong time in the expected sequence of events;

 (*) the order of the memory accesses may be rearranged to promote better use
     of the CPU buses and caches;

 (*) loads and stores may be combined to improve performance when talking to
     memory or I/O hardware that can do batched accesses of adjacent locations,
     thus cutting down on transaction setup costs (memory and PCI devices may
     both be able to do this); and

 (*) the CPU's data cache may affect the ordering, and whilst cache-coherency
     mechanisms may alleviate this - once the store has actually hit the cache
     - there's no guarantee that the coherency management will be propagated in
     order to other CPUs.

So what another CPU, say, might actually observe from the above piece of code
is:

	LOAD *A, ..., LOAD {*C,*D}, STORE *E, STORE *B

	(Where "LOAD {*C,*D}" is a combined load)


However, it is guaranteed that a CPU will be self-consistent: it will see its
_own_ accesses appear to be correctly ordered, without the need for a memory
barrier.  For instance with the following code:

	U = *A;
	*A = V;
	*A = W;
	X = *A;
	*A = Y;
	Z = *A;

and assuming no intervention by an external influence, it can be assumed that
the final result will appear to be:

	U == the original value of *A
	X == W
	Z == Y
	*A == Y

The code above may cause the CPU to generate the full sequence of memory
accesses:

	U=LOAD *A, STORE *A=V, STORE *A=W, X=LOAD *A, STORE *A=Y, Z=LOAD *A

in that order, but, without intervention, the sequence may have almost any
combination of elements combined or discarded, provided the program's view of
the world remains consistent.

The compiler may also combine, discard or defer elements of the sequence before
the CPU even sees them.

For instance:

	*A = V;
	*A = W;

may be reduced to:

	*A = W;

since, without a write barrier, it can be assumed that the effect of the
storage of V to *A is lost.  Similarly:

	*A = Y;
	Z = *A;

may, without a memory barrier, be reduced to:

	*A = Y;
	Z = Y;

and the LOAD operation never appear outside of the CPU.


AND THEN THERE'S THE ALPHA
--------------------------

The DEC Alpha CPU is one of the most relaxed CPUs there is.  Not only that,
some versions of the Alpha CPU have a split data cache, permitting them to have
two semantically-related cache lines updated at separate times.  This is where
the data dependency barrier really becomes necessary as this synchronises both
caches with the memory coherence system, thus making it seem like pointer
changes vs new data occur in the right order.

The Alpha defines the Linux kernel's memory barrier model.

See the subsection on "Cache Coherency" above.


============
EXAMPLE USES
============

CIRCULAR BUFFERS
----------------

Memory barriers can be used to implement circular buffering without the need
of a lock to serialise the producer with the consumer.  See:

	Documentation/circular-buffers.txt

for details.


==========
REFERENCES
==========

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

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

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

---

### Documentation Subsystem Apis (`Documentation/subsystem-apis.rst`)

.. SPDX-License-Identifier: GPL-2.0

==============================
Kernel subsystem documentation
==============================

These books get into the details of how specific kernel subsystems work
from the point of view of a kernel developer.  Much of the information here
is taken directly from the kernel source, with supplemental material added
as needed (or at least as we managed to add it — probably *not* all that is
needed).

Core subsystems
---------------

.. toctree::
   :maxdepth: 1

   core-api/index
   driver-api/index
   mm/index
   power/index
   scheduler/index
   timers/index
   locking/index

Human interfaces
----------------

.. toctree::
   :maxdepth: 1

   input/index
   hid/index
   sound/index
   gpu/index
   fb/index
   leds/index

Networking interfaces
---------------------

.. toctree::
   :maxdepth: 1

   networking/index
   netlabel/index
   infiniband/index
   isdn/index
   mhi/index

Storage interfaces
------------------

.. toctree::
   :maxdepth: 1

   filesystems/index
   block/index
   cdrom/index
   scsi/index
   target/index
   nvme/index

Other subsystems
----------------
**Fixme**: much more organizational work is needed here.

.. toctree::
   :maxdepth: 1

   accounting/index
   cpu-freq/index
   edac/index
   fpga/index
   i2c/index
   iio/index
   pcmcia/index
   spi/index
   w1/index
   watchdog/index
   virt/index
   hwmon/index
   accel/index
   security/index
   crypto/index
   bpf/index
   usb/index
   PCI/index
   misc-devices/index
   peci/index
   wmi/index
   tee/index

---

### Documentation PCI Acpi Info (`Documentation/PCI/acpi-info.rst`)

.. SPDX-License-Identifier: GPL-2.0

========================================
ACPI considerations for PCI host bridges
========================================

The general rule is that the ACPI namespace should describe everything the
OS might use unless there's another way for the OS to find it [1, 2].

For example, there's no standard hardware mechanism for enumerating PCI
host bridges, so the ACPI namespace must describe each host bridge, the
method for accessing PCI config space below it, the address space windows
the host bridge forwards to PCI (using _CRS), and the routing of legacy
INTx interrupts (using _PRT).

PCI devices, which are below the host bridge, generally do not need to be
described via ACPI.  The OS can discover them via the standard PCI
enumeration mechanism, using config accesses to discover and identify
devices and read and size their BARs.  However, ACPI may describe PCI
devices if it provides power management or hotplug functionality for them
or if the device has INTx interrupts connected by platform interrupt
controllers and a _PRT is needed to describe those connections.

ACPI resource description is done via _CRS objects of devices in the ACPI
namespace [2].   The _CRS is like a generalized PCI BAR: the OS can read
_CRS and figure out what resource is being consumed even if it doesn't have
a driver for the device [3].  That's important because it means an old OS
can work correctly even on a system with new devices unknown to the OS.
The new devices might not do anything, but the OS can at least make sure no
resources conflict with them.

Static tables like MCFG, HPET, ECDT, etc., are *not* mechanisms for
reserving address space.  The static tables are for things the OS needs to
know early in boot, before it can parse the ACPI namespace.  If a new table
is defined, an old OS needs to operate correctly even though it ignores the
table.  _CRS allows that because it is generic and understood by the old
OS; a static table does not.

If the OS is expected to manage a non-discoverable device described via
ACPI, that device will have a specific _HID/_CID that tells the OS what
driver to bind to it, and the _CRS tells the OS and the driver where the
device's registers are.

PCI host bridges are PNP0A03 or PNP0A08 devices.  Their _CRS should
describe all the address space they consume.  This includes all the windows
they forward down to the PCI bus, as well as registers of the host bridge
itself that are not forwarded to PCI.  The host bridge registers include
things like secondary/subordinate bus registers that determine the bus
range below the bridge, window registers that describe the apertures, etc.
These are all device-specific, non-architected things, so the only way a
PNP0A03/PNP0A08 driver can manage them is via _PRS/_CRS/_SRS, which contain
the device-specific details.  The host bridge registers also include ECAM
space, since it is consumed by the host bridge.

ACPI defines a Consumer/Producer bit to distinguish the bridge registers
("Consumer") from the bridge apertures ("Producer") [4, 5], but early
BIOSes didn't use that bit correctly.  The result is that the current ACPI
spec defines Consumer/Producer only for the Extended Address Space
descriptors; the bit should be ignored in the older QWord/DWord/Word
Address Space descriptors.  Consequently, OSes have to assume all
QWord/DWord/Word descriptors are windows.

Prior to the addition of Extended Address Space descriptors, the failure of
Consumer/Producer meant there was no way to describe bridge registers in
the PNP0A03/PNP0A08 device itself.  The workaround was to describe the
bridge registers (including ECAM space) in PNP0C02 catch-all devices [6].
With the exception of ECAM, the bridge register space is device-specific
anyway, so the generic PNP0A03/PNP0A08 driver (pci_root.c) has no need to
know about it.  

New architectures should be able to use "Consumer" Extended Address Space
descriptors in the PNP0A03 device for bridge registers, including ECAM,
although a strict interpretation of [6] might prohibit this.  Old x86 and
ia64 kernels assume all address space descriptors, including "Consumer"
Extended Address Space ones, are windows, so it would not be safe to
describe bridge registers this way on those architectures.

PNP0C02 "motherboard" devices are basically a catch-all.  There's no
programming model for them other than "don't use these resources for
anything else."  So a PNP0C02 _CRS should claim any address space that is
(1) not claimed by _CRS under any other device object in the ACPI namespace
and (2) should not be assigned by the OS to something else.

The PCIe spec requires the Enhanced Configuration Access Method (ECAM)
unless there's a standard firmware interface for config access, e.g., the
ia64 SAL interface [7].  A host bridge consumes ECAM memory address space
and converts memory accesses into PCI configuration accesses.  The spec
defines the ECAM address space layout and functionality; only the base of
the address space is device-specific.  An ACPI OS learns the base address
from either the static MCFG table or a _CBA method in the PNP0A03 device.

The MCFG table must describe the ECAM space of non-hot pluggable host
bridges [8].  Since MCFG is a static table and can't be updated by hotplug,
a _CBA method in the PNP0A03 device describes the ECAM space of a
hot-pluggable host bridge [9].  Note that for both MCFG and _CBA, the base
address always corresponds to bus 0, even if the bus range below the bridge
(which is reported via _CRS) doesn't start at 0.


[1] ACPI 6.2, sec 6.1:
    For any device that is on a non-enumerable type of bus (for example, an
    ISA bus), OSPM enumerates the devices' identifier(s) and the ACPI
    system firmware must supply an _HID object ... for each device to
    enable OSPM to do that.

[2] ACPI 6.2, sec 3.7:
    The OS enumerates motherboard devices simply by reading through the
    ACPI Namespace looking for devices with hardware IDs.

    Each device enumerated by ACPI includes ACPI-defined objects in the
    ACPI Namespace that report the hardware resources the device could
    occupy [_PRS], an object that reports the resources that are currently
    used by the device [_CRS], and objects for configuring those resources
    [_SRS].  The information is used by the Plug and Play OS (OSPM) to
    configure the devices.

[3] ACPI 6.2, sec 6.2:
    OSPM uses device configuration objects to configure hardware resources
    for devices enumerated via ACPI.  Device configuration objects provide
    information about current and possible resource requirements, the
    relationship between shared resources, and methods for configuring
    hardware resources.

    When OSPM enumerates a device, it calls _PRS to determine the resource
    requirements of the device.  It may also call _CRS to find the current
    resource settings for the device.  Using this information, the Plug and
    Play system determines what resources the device should consume and
    sets those resources by calling the device’s _SRS control method.

    In ACPI, devices can consume resources (for example, legacy keyboards),
    provide resources (for example, a proprietary PCI bridge), or do both.
    Unless otherwise specified, resources for a device are assumed to be
    taken from the nearest matching resource above the device in the device
    hierarchy.

[4] ACPI 6.2, sec 6.4.3.5.1, 2, 3, 4:
    QWord/DWord/Word Address Space Descriptor (.1, .2, .3)
      General Flags: Bit [0] Ignored

    Extended Address Space Descriptor (.4)
      General Flags: Bit [0] Consumer/Producer:

        * 1 – This device consumes this resource
        * 0 – This device produces and consumes this resource

[5] ACPI 6.2, sec 19.6.43:
    ResourceUsage specifies whether the Memory range is consumed by
    this device (ResourceConsumer) or passed on to child devices
    (ResourceProducer).  If nothing is specified, then
    ResourceConsumer is assumed.

[6] PCI Firmware 3.2, sec 4.1.2:
    If the operating system does not natively comprehend reserving the
    MMCFG region, the MMCFG region must be reserved by firmware.  The
    address range reported in the MCFG table or by _CBA method (see Section
    4.1.3) must be reserved by declaring a motherboard resource.  For most
    systems, the motherboard resource would appear at the root of the ACPI
    namespace (under \_SB) in a node with a _HID of EISAID (PNP0C02), and
    the resources in this case should not be claimed in the root PCI bus’s
    _CRS.  The resources can optionally be returned in Int15 E820 or
    EFIGetMemoryMap as reserved memory but must always be reported through
    ACPI as a motherboard resource.

[7] PCI Express 4.0, sec 7.2.2:
    For systems that are PC-compatible, or that do not implement a
    processor-architecture-specific firmware interface standard that allows
    access to the Configuration Space, the ECAM is required as defined in
    this section.

[8] PCI Firmware 3.2, sec 4.1.2:
    The MCFG table is an ACPI table that is used to communicate the base
    addresses corresponding to the non-hot removable PCI Segment Groups
    range within a PCI Segment Group available to the operating system at
    boot. This is required for the PC-compatible systems.

    The MCFG table is only used to communicate the base addresses
    corresponding to the PCI Segment Groups available to the system at
    boot.

[9] PCI Firmware 3.2, sec 4.1.3:
    The _CBA (Memory mapped Configuration Base Address) control method is
    an optional ACPI object that returns the 64-bit memory mapped
    configuration base address for the hot plug capable host bridge. The
    base address returned by _CBA is processor-relative address. The _CBA
    control method evaluates to an Integer.

    This control method appears under a host bridge object. When the _CBA
    method appears under an active host bridge object, the operating system
    evaluates this structure to identify the memory mapped configuration
    base address corresponding to the PCI Segment Group for the bus number
    range specified in _CRS method. An ACPI name space object that contains
    the _CBA method must also contain a corresponding _SEG method.

---

### Documentation PCI Boot Interrupts (`Documentation/PCI/boot-interrupts.rst`)

.. SPDX-License-Identifier: GPL-2.0

===============
Boot Interrupts
===============

:Author: - Sean V Kelley <sean.v.kelley@linux.intel.com>

Overview
========

On PCI Express, interrupts are represented with either MSI or inbound
interrupt messages (Assert_INTx/Deassert_INTx). The integrated IO-APIC in a
given Core IO converts the legacy interrupt messages from PCI Express to
MSI interrupts.  If the IO-APIC is disabled (via the mask bits in the
IO-APIC table entries), the messages are routed to the legacy PCH. This
in-band interrupt mechanism was traditionally necessary for systems that
did not support the IO-APIC and for boot. Intel in the past has used the
term "boot interrupts" to describe this mechanism. Further, the PCI Express
protocol describes this in-band legacy wire-interrupt INTx mechanism for
I/O devices to signal PCI-style level interrupts. The subsequent paragraphs
describe problems with the Core IO handling of INTx message routing to the
PCH and mitigation within BIOS and the OS.


Issue
=====

When in-band legacy INTx messages are forwarded to the PCH, they in turn
trigger a new interrupt for which the OS likely lacks a handler. When an
interrupt goes unhandled over time, they are tracked by the Linux kernel as
Spurious Interrupts. The IRQ will be disabled by the Linux kernel after it
reaches a specific count with the error "nobody cared". This disabled IRQ
now prevents valid usage by an existing interrupt which may happen to share
the IRQ line::

  irq 19: nobody cared (try booting with the "irqpoll" option)
  CPU: 0 PID: 2988 Comm: irq/34-nipalk Tainted: 4.14.87-rt49-02410-g4a640ec-dirty #1
  Hardware name: National Instruments NI PXIe-8880/NI PXIe-8880, BIOS 2.1.5f1 01/09/2020
  Call Trace:

  <IRQ>
   ? dump_stack+0x46/0x5e
   ? __report_bad_irq+0x2e/0xb0
   ? note_interrupt+0x242/0x290
   ? nNIKAL100_memoryRead16+0x8/0x10 [nikal]
   ? handle_irq_event_percpu+0x55/0x70
   ? handle_irq_event+0x4f/0x80
   ? handle_fasteoi_irq+0x81/0x180
   ? handle_irq+0x1c/0x30
   ? do_IRQ+0x41/0xd0
   ? common_interrupt+0x84/0x84
  </IRQ>

  handlers:
  irq_default_primary_handler threaded usb_hcd_irq
  Disabling IRQ #19


Conditions
==========

The use of threaded interrupts is the most likely condition to trigger
this problem today. Threaded interrupts may not be re-enabled after the IRQ
handler wakes. These "one shot" conditions mean that the threaded interrupt
needs to keep the interrupt line masked until the threaded handler has run.
Especially when dealing with high data rate interrupts, the thread needs to
run to completion; otherwise some handlers will end up in stack overflows
since the interrupt of the issuing device is still active.

Affected Chipsets
=================

The legacy interrupt forwarding mechanism exists today in a number of
devices including but not limited to chipsets from AMD/ATI, Broadcom, and
Intel. Changes made through the mitigations below have been applied to
drivers/pci/quirks.c

Starting with ICX there are no longer any IO-APICs in the Core IO's
devices.  IO-APIC is only in the PCH.  Devices connected to the Core IO's
PCIe Root Ports will use native MSI/MSI-X mechanisms.

Mitigations
===========

The mitigations take the form of PCI quirks. The preference has been to
first identify and make use of a means to disable the routing to the PCH.
In such a case a quirk to disable boot interrupt generation can be
added. [1]_

Intel® 6300ESB I/O Controller Hub
  Alternate Base Address Register:
   BIE: Boot Interrupt Enable

	  ==  ===========================
	  0   Boot interrupt is enabled.
	  1   Boot interrupt is disabled.
	  ==  ===========================

Intel® Sandy Bridge through Sky Lake based Xeon servers:
  Coherent Interface Protocol Interrupt Control
   dis_intx_route2pch/dis_intx_route2ich/dis_intx_route2dmi2:
	  When this bit is set. Local INTx messages received from the
	  Intel® Quick Data DMA/PCI Express ports are not routed to legacy
	  PCH - they are either converted into MSI via the integrated IO-APIC
	  (if the IO-APIC mask bit is clear in the appropriate entries)
	  or cause no further action (when mask bit is set)

In the absence of a way to directly disable the routing, another approach
has been to make use of PCI Interrupt pin to INTx routing tables for
purposes of redirecting the interrupt handler to the rerouted interrupt
line by default.  Therefore, on chipsets where this INTx routing cannot be
disabled, the Linux kernel will reroute the valid interrupt to its legacy
interrupt. This redirection of the handler will prevent the occurrence of
the spurious interrupt detection which would ordinarily disable the IRQ
line due to excessive unhandled counts. [2]_

The config option X86_REROUTE_FOR_BROKEN_BOOT_IRQS exists to enable (or
disable) the redirection of the interrupt handler to the PCH interrupt
line. The option can be overridden by either pci=ioapicreroute or
pci=noioapicreroute. [3]_


More Documentation
==================

There is an overview of the legacy interrupt handling in several datasheets
(6300ESB and 6700PXH below). While largely the same, it provides insight
into the evolution of its handling with chipsets.

Example of disabling of the boot interrupt
------------------------------------------

      - Intel® 6300ESB I/O Controller Hub (Document # 300641-004US)
	5.7.3 Boot Interrupt
	https://www.intel.com/content/dam/doc/datasheet/6300esb-io-controller-hub-datasheet.pdf

      - Intel® Xeon® Processor E5-1600/2400/2600/4600 v3 Product Families
	Datasheet - Volume 2: Registers (Document # 330784-003)
	6.6.41 cipintrc Coherent Interface Protocol Interrupt Control
	https://www.intel.com/content/dam/www/public/us/en/documents/datasheets/xeon-e5-v3-datasheet-vol-2.pdf

Example of handler rerouting
----------------------------

      - Intel® 6700PXH 64-bit PCI Hub (Document # 302628)
	2.15.2 PCI Express Legacy INTx Support and Boot Interrupt
	https://www.intel.com/content/dam/doc/datasheet/6700pxh-64-bit-pci-hub-datasheet.pdf


If you have any legacy PCI interrupt questions that aren't answered, email me.

Cheers,
    Sean V Kelley
    sean.v.kelley@linux.intel.com

.. [1] https://lore.kernel.org/r/12131949181903-git-send-email-sassmann@suse.de/
.. [2] https://lore.kernel.org/r/12131949182094-git-send-email-sassmann@suse.de/
.. [3] https://lore.kernel.org/r/487C8EA7.6020205@suse.de/

---

### Documentation PCI Index (`Documentation/PCI/index.rst`)

.. SPDX-License-Identifier: GPL-2.0

=================
PCI Bus Subsystem
=================

.. toctree::
   :maxdepth: 2
   :numbered:

   pci
   pciebus-howto
   pci-iov-howto
   msi-howto
   sysfs-pci
   acpi-info
   pci-error-recovery
   pcieaer-howto
   endpoint/index
   controller/index
   boot-interrupts
   tph

---

### Documentation PCI Msi Howto (`Documentation/PCI/msi-howto.rst`)

.. SPDX-License-Identifier: GPL-2.0
.. include:: <isonum.txt>

==========================
The MSI Driver Guide HOWTO
==========================

:Authors: Tom L Nguyen; Martine Silbermann; Matthew Wilcox

:Copyright: 2003, 2008 Intel Corporation

About this guide
================

This guide describes the basics of Message Signaled Interrupts (MSIs),
the advantages of using MSI over traditional interrupt mechanisms, how
to change your driver to use MSI or MSI-X and some basic diagnostics to
try if a device doesn't support MSIs.


What are MSIs?
==============

A Message Signaled Interrupt is a write from the device to a special
address which causes an interrupt to be received by the CPU.

The MSI capability was first specified in PCI 2.2 and was later enhanced
in PCI 3.0 to allow each interrupt to be masked individually.  The MSI-X
capability was also introduced with PCI 3.0.  It supports more interrupts
per device than MSI and allows interrupts to be independently configured.

Devices may support both MSI and MSI-X, but only one can be enabled at
a time.


Why use MSIs?
=============

There are three reasons why using MSIs can give an advantage over
traditional pin-based interrupts.

Pin-based PCI interrupts are often shared amongst several devices.
To support this, the kernel must call each interrupt handler associated
with an interrupt, which leads to reduced performance for the system as
a whole.  MSIs are never shared, so this problem cannot arise.

When a device writes data to memory, then raises a pin-based interrupt,
it is possible that the interrupt may arrive before all the data has
arrived in memory (this becomes more likely with devices behind PCI-PCI
bridges).  In order to ensure that all the data has arrived in memory,
the interrupt handler must read a register on the device which raised
the interrupt.  PCI transaction ordering rules require that all the data
arrive in memory before the value may be returned from the register.
Using MSIs avoids this problem as the interrupt-generating write cannot
pass the data writes, so by the time the interrupt is raised, the driver
knows that all the data has arrived in memory.

PCI devices can only support a single pin-based interrupt per function.
Often drivers have to query the device to find out what event has
occurred, slowing down interrupt handling for the common case.  With
MSIs, a device can support more interrupts, allowing each interrupt
to be specialised to a different purpose.  One possible design gives
infrequent conditions (such as errors) their own interrupt which allows
the driver to handle the normal interrupt handling path more efficiently.
Other possible designs include giving one interrupt to each packet queue
in a network card or each port in a storage controller.


How to use MSIs
===============

PCI devices are initialised to use pin-based interrupts.  The device
driver has to set up the device to use MSI or MSI-X.  Not all machines
support MSIs correctly, and for those machines, the APIs described below
will simply fail and the device will continue to use pin-based interrupts.

Include kernel support for MSIs
-------------------------------

To support MSI or MSI-X, the kernel must be built with the CONFIG_PCI_MSI
option enabled.  This option is only available on some architectures,
and it may depend on some other options also being set.  For example,
on x86, you must also enable X86_UP_APIC or SMP in order to see the
CONFIG_PCI_MSI option.

Using MSI
---------

Most of the hard work is done for the driver in the PCI layer.  The driver
simply has to request that the PCI layer set up the MSI capability for this
device.

To automatically use MSI or MSI-X interrupt vectors, use the following
function::

  int pci_alloc_irq_vectors(struct pci_dev *dev, unsigned int min_vecs,
		unsigned int max_vecs, unsigned int flags);

which allocates up to max_vecs interrupt vectors for a PCI device.  It
returns the number of vectors allocated or a negative error.  If the device
has a requirements for a minimum number of vectors the driver can pass a
min_vecs argument set to this limit, and the PCI core will return -ENOSPC
if it can't meet the minimum number of vectors.

The flags argument is used to specify which type of interrupt can be used
by the device and the driver (PCI_IRQ_INTX, PCI_IRQ_MSI, PCI_IRQ_MSIX).
A convenient short-hand (PCI_IRQ_ALL_TYPES) is also available to ask for
any possible kind of interrupt.  If the PCI_IRQ_AFFINITY flag is set,
pci_alloc_irq_vectors() will spread the interrupts around the available CPUs.

To get the Linux IRQ numbers passed to request_irq() and free_irq() and the
vectors, use the following function::

  int pci_irq_vector(struct pci_dev *dev, unsigned int nr);

Any allocated resources should be freed before removing the device using
the following function::

  void pci_free_irq_vectors(struct pci_dev *dev);

If a device supports both MSI-X and MSI capabilities, this API will use the
MSI-X facilities in preference to the MSI facilities.  MSI-X supports any
number of interrupts between 1 and 2048.  In contrast, MSI is restricted to
a maximum of 32 interrupts (and must be a power of two).  In addition, the
MSI interrupt vectors must be allocated consecutively, so the system might
not be able to allocate as many vectors for MSI as it could for MSI-X.  On
some platforms, MSI interrupts must all be targeted at the same set of CPUs
whereas MSI-X interrupts can all be targeted at different CPUs.

If a device supports neither MSI-X or MSI it will fall back to a single
legacy IRQ vector.

The typical usage of MSI or MSI-X interrupts is to allocate as many vectors
as possible, likely up to the limit supported by the device.  If nvec is
larger than the number supported by the device it will automatically be
capped to the supported limit, so there is no need to query the number of
vectors supported beforehand::

	nvec = pci_alloc_irq_vectors(pdev, 1, nvec, PCI_IRQ_ALL_TYPES)
	if (nvec < 0)
		goto out_err;

If a driver is unable or unwilling to deal with a variable number of MSI
interrupts it can request a particular number of interrupts by passing that
number to pci_alloc_irq_vectors() function as both 'min_vecs' and
'max_vecs' parameters::

	ret = pci_alloc_irq_vectors(pdev, nvec, nvec, PCI_IRQ_ALL_TYPES);
	if (ret < 0)
		goto out_err;

The most notorious example of the request type described above is enabling
the single MSI mode for a device.  It could be done by passing two 1s as
'min_vecs' and 'max_vecs'::

	ret = pci_alloc_irq_vectors(pdev, 1, 1, PCI_IRQ_ALL_TYPES);
	if (ret < 0)
		goto out_err;

Some devices might not support using legacy line interrupts, in which case
the driver can specify that only MSI or MSI-X is acceptable::

	nvec = pci_alloc_irq_vectors(pdev, 1, nvec, PCI_IRQ_MSI | PCI_IRQ_MSIX);
	if (nvec < 0)
		goto out_err;

Legacy APIs
-----------

The following old APIs to enable and disable MSI or MSI-X interrupts should
not be used in new code::

  pci_enable_msi()		/* deprecated */
  pci_disable_msi()		/* deprecated */
  pci_enable_msix_range()	/* deprecated */
  pci_enable_msix_exact()	/* deprecated */
  pci_disable_msix()		/* deprecated */

Additionally there are APIs to provide the number of supported MSI or MSI-X
vectors: pci_msi_vec_count() and pci_msix_vec_count().  In general these
should be avoided in favor of letting pci_alloc_irq_vectors() cap the
number of vectors.  If you have a legitimate special use case for the count
of vectors we might have to revisit that decision and add a
pci_nr_irq_vectors() helper that handles MSI and MSI-X transparently.

Considerations when using MSIs
------------------------------

Spinlocks
~~~~~~~~~

Most device drivers have a per-device spinlock which is taken in the
interrupt handler.  With pin-based interrupts or a single MSI, it is not
necessary to disable interrupts (Linux guarantees the same interrupt will
not be re-entered).  If a device uses multiple interrupts, the driver
must disable interrupts while the lock is held.  If the device sends
a different interrupt, the driver will deadlock trying to recursively
acquire the spinlock.  Such deadlocks can be avoided by using
spin_lock_irqsave() or spin_lock_irq() which disable local interrupts
and acquire the lock (see Documentation/kernel-hacking/locking.rst).

How to tell whether MSI/MSI-X is enabled on a device
----------------------------------------------------

Using 'lspci -v' (as root) may show some devices with "MSI", "Message
Signalled Interrupts" or "MSI-X" capabilities.  Each of these capabilities
has an 'Enable' flag which is followed with either "+" (enabled)
or "-" (disabled).


MSI quirks
==========

Several PCI chipsets or devices are known not to support MSIs.
The PCI stack provides three ways to disable MSIs:

1. globally
2. on all devices behind a specific bridge
3. on a single device

Disabling MSIs globally
-----------------------

Some host chipsets simply don't support MSIs properly.  If we're
lucky, the manufacturer knows this and has indicated it in the ACPI
FADT table.  In this case, Linux automatically disables MSIs.
Some boards don't include this information in the table and so we have
to detect them ourselves.  The complete list of these is found near the
quirk_disable_all_msi() function in drivers/pci/quirks.c.

If you have a board which has problems with MSIs, you can pass pci=nomsi
on the kernel command line to disable MSIs on all devices.  It would be
in your best interests to report the problem to linux-pci@vger.kernel.org
including a full 'lspci -v' so we can add the quirks to the kernel.

Disabling MSIs below a bridge
-----------------------------

Some PCI bridges are not able to route MSIs between buses properly.
In this case, MSIs must be disabled on all devices behind the bridge.

Some bridges allow you to enable MSIs by changing some bits in their
PCI configuration space (especially the Hypertransport chipsets such
as the nVidia nForce and Serverworks HT2000).  As with host chipsets,
Linux mostly knows about them and automatically enables MSIs if it can.
If you have a bridge unknown to Linux, you can enable
MSIs in configuration space using whatever method you know works, then
enable MSIs on that bridge by doing::

       echo 1 > /sys/bus/pci/devices/$bridge/msi_bus

where $bridge is the PCI address of the bridge you've enabled (eg
0000:00:0e.0).

To disable MSIs, echo 0 instead of 1.  Changing this value should be
done with caution as it could break interrupt handling for all devices
below this bridge.

Again, please notify linux-pci@vger.kernel.org of any bridges that need
special handling.

Disabling MSIs on a single device
---------------------------------

Some devices are known to have faulty MSI implementations.  Usually this
is handled in the individual device driver, but occasionally it's necessary
to handle this with a quirk.  Some drivers have an option to disable use
of MSI.  While this is a convenient workaround for the driver author,
it is not good practice, and should not be emulated.

Finding why MSIs are disabled on a device
-----------------------------------------

From the above three sections, you can see that there are many reasons
why MSIs may not be enabled for a given device.  Your first step should
be to examine your dmesg carefully to determine whether MSIs are enabled
for your machine.  You should also check your .config to be sure you
have enabled CONFIG_PCI_MSI.

Then, 'lspci -t' gives the list of bridges above a device. Reading
`/sys/bus/pci/devices/*/msi_bus` will tell you whether MSIs are enabled (1)
or disabled (0).  If 0 is found in any of the msi_bus files belonging
to bridges between the PCI root and the device, MSIs are disabled.

It is also worth checking the device driver to see whether it supports MSIs.
For example, it may contain calls to pci_alloc_irq_vectors() with the
PCI_IRQ_MSI or PCI_IRQ_MSIX flags.


List of device drivers MSI(-X) APIs
===================================

The PCI/MSI subsystem has a dedicated C file for its exported device driver
APIs — `drivers/pci/msi/api.c`. The following functions are exported:

.. kernel-doc:: drivers/pci/msi/api.c
   :export:

---

### Documentation PCI Pci Error Recovery (`Documentation/PCI/pci-error-recovery.rst`)

.. SPDX-License-Identifier: GPL-2.0

==================
PCI Error Recovery
==================


:Authors: - Linas Vepstas <linasvepstas@gmail.com>
          - Richard Lary <rlary@us.ibm.com>
          - Mike Mason <mmlnx@us.ibm.com>


Many PCI bus controllers are able to detect a variety of hardware
PCI errors on the bus, such as parity errors on the data and address
buses, as well as SERR and PERR errors.  Some of the more advanced
chipsets are able to deal with these errors; these include PCIe chipsets,
and the PCI-host bridges found on IBM Power4, Power5 and Power6-based
pSeries boxes. A typical action taken is to disconnect the affected device,
halting all I/O to it.  The goal of a disconnection is to avoid system
corruption; for example, to halt system memory corruption due to DMAs
to "wild" addresses. Typically, a reconnection mechanism is also
offered, so that the affected PCI device(s) are reset and put back
into working condition. The reset phase requires coordination
between the affected device drivers and the PCI controller chip.
This document describes a generic API for notifying device drivers
of a bus disconnection, and then performing error recovery.
This API is currently implemented in the 2.6.16 and later kernels.

Reporting and recovery is performed in several steps. First, when
a PCI hardware error has resulted in a bus disconnect, that event
is reported as soon as possible to all affected device drivers,
including multiple instances of a device driver on multi-function
cards. This allows device drivers to avoid deadlocking in spinloops,
waiting for some i/o-space register to change, when it never will.
It also gives the drivers a chance to defer incoming I/O as
needed.

Next, recovery is performed in several stages. Most of the complexity
is forced by the need to handle multi-function devices, that is,
devices that have multiple device drivers associated with them.
In the first stage, each driver is allowed to indicate what type
of reset it desires, the choices being a simple re-enabling of I/O
or requesting a slot reset.

If any driver requests a slot reset, that is what will be done.

After a reset and/or a re-enabling of I/O, all drivers are
again notified, so that they may then perform any device setup/config
that may be required.  After these have all completed, a final
"resume normal operations" event is sent out.

The biggest reason for choosing a kernel-based implementation rather
than a user-space implementation was the need to deal with bus
disconnects of PCI devices attached to storage media, and, in particular,
disconnects from devices holding the root file system.  If the root
file system is disconnected, a user-space mechanism would have to go
through a large number of contortions to complete recovery. Almost all
of the current Linux file systems are not tolerant of disconnection
from/reconnection to their underlying block device. By contrast,
bus errors are easy to manage in the device driver. Indeed, most
device drivers already handle very similar recovery procedures;
for example, the SCSI-generic layer already provides significant
mechanisms for dealing with SCSI bus errors and SCSI bus resets.


Detailed Design
===============

Design and implementation details below, based on a chain of
public email discussions with Ben Herrenschmidt, circa 5 April 2005.

The error recovery API support is exposed to the driver in the form of
a structure of function pointers pointed to by a new field in struct
pci_driver. A driver that fails to provide the structure is "non-aware",
and the actual recovery steps taken are platform dependent.  The
arch/powerpc implementation will simulate a PCI hotplug remove/add.

This structure has the form::

	struct pci_error_handlers
	{
		int (*error_detected)(struct pci_dev *dev, pci_channel_state_t);
		int (*mmio_enabled)(struct pci_dev *dev);
		int (*slot_reset)(struct pci_dev *dev);
		void (*resume)(struct pci_dev *dev);
		void (*cor_error_detected)(struct pci_dev *dev);
	};

The possible channel states are::

	typedef enum {
		pci_channel_io_normal,  /* I/O channel is in normal state */
		pci_channel_io_frozen,  /* I/O to channel is blocked */
		pci_channel_io_perm_failure, /* PCI card is dead */
	} pci_channel_state_t;

Possible return values are::

	enum pci_ers_result {
		PCI_ERS_RESULT_NONE,        /* no result/none/not supported in device driver */
		PCI_ERS_RESULT_CAN_RECOVER, /* Device driver can recover without slot reset */
		PCI_ERS_RESULT_NEED_RESET,  /* Device driver wants slot to be reset. */
		PCI_ERS_RESULT_DISCONNECT,  /* Device has completely failed, is unrecoverable */
		PCI_ERS_RESULT_RECOVERED,   /* Device driver is fully recovered and operational */
	};

A driver does not have to implement all of these callbacks; however,
if it implements any, it must implement error_detected(). If a callback
is not implemented, the corresponding feature is considered unsupported.
For example, if mmio_enabled() and resume() aren't there, then it
is assumed that the driver does not need these callbacks
for recovery.  Typically a driver will want to know about
a slot_reset().

The actual steps taken by a platform to recover from a PCI error
event will be platform-dependent, but will follow the general
sequence described below.

STEP 0: Error Event
-------------------
A PCI bus error is detected by the PCI hardware.  On powerpc, the slot
is isolated, in that all I/O is blocked: all reads return 0xffffffff,
all writes are ignored.

Similarly, on platforms supporting Downstream Port Containment
(PCIe r7.0 sec 6.2.11), the link to the sub-hierarchy with the
faulting device is disabled. Any device in the sub-hierarchy
becomes inaccessible.

STEP 1: Notification
--------------------
Platform calls the error_detected() callback on every instance of
every driver affected by the error.

At this point, the device might not be accessible anymore, depending on
the platform (the slot will be isolated on powerpc). The driver may
already have "noticed" the error because of a failing I/O, but this
is the proper "synchronization point", that is, it gives the driver
a chance to cleanup, waiting for pending stuff (timers, whatever, etc...)
to complete; it can take semaphores, schedule, etc... everything but
touch the device. Within this function and after it returns, the driver
shouldn't do any new IOs. Called in task context. This is sort of a
"quiesce" point. See note about interrupts at the end of this doc.

All drivers participating in this system must implement this call.
The driver must return one of the following result codes:

  - PCI_ERS_RESULT_RECOVERED
      Driver returns this if it thinks the device is usable despite
      the error and does not need further intervention.
  - PCI_ERS_RESULT_CAN_RECOVER
      Driver returns this if it thinks it might be able to recover
      the HW by just banging IOs or if it wants to be given
      a chance to extract some diagnostic information (see
      mmio_enable, below).
  - PCI_ERS_RESULT_NEED_RESET
      Driver returns this if it can't recover without a
      slot reset.
  - PCI_ERS_RESULT_DISCONNECT
      Driver returns this if it doesn't want to recover at all.

The next step taken will depend on the result codes returned by the
drivers.

If all drivers on the segment/slot return PCI_ERS_RESULT_CAN_RECOVER,
then the platform should re-enable IOs on the slot (or do nothing in
particular, if the platform doesn't isolate slots), and recovery
proceeds to STEP 2 (MMIO Enable).

If any driver requested a slot reset (by returning PCI_ERS_RESULT_NEED_RESET),
then recovery proceeds to STEP 4 (Slot Reset).

If the platform is unable to recover the slot, the next step
is STEP 6 (Permanent Failure).

.. note::

   The current powerpc implementation assumes that a device driver will
   *not* schedule or semaphore in this routine; the current powerpc
   implementation uses one kernel thread to notify all devices;
   thus, if one device sleeps/schedules, all devices are affected.
   Doing better requires complex multi-threaded logic in the error
   recovery implementation (e.g. waiting for all notification threads
   to "join" before proceeding with recovery.)  This seems excessively
   complex and not worth implementing.

   The current powerpc implementation doesn't much care if the device
   attempts I/O at this point, or not.  I/Os will fail, returning
   a value of 0xff on read, and writes will be dropped. If more than
   EEH_MAX_FAILS I/Os are attempted to a frozen adapter, EEH
   assumes that the device driver has gone into an infinite loop
   and prints an error to syslog.  A reboot is then required to
   get the device working again.

STEP 2: MMIO Enabled
--------------------
The platform re-enables MMIO to the device (but typically not the
DMA), and then calls the mmio_enabled() callback on all affected
device drivers.

This is the "early recovery" call. IOs are allowed again, but DMA is
not, with some restrictions. This is NOT a callback for the driver to
start operations again, only to peek/poke at the device, extract diagnostic
information, if any, and eventually do things like trigger a device local
reset or some such, but not restart operations. This callback is made if
all drivers on a segment agree that they can try to recover and if no automatic
link reset was performed by the HW. If the platform can't just re-enable IOs
without a slot reset or a link reset, it will not call this callback, and
instead will have gone directly to STEP 3 (Link Reset) or STEP 4 (Slot Reset).

.. note::

   On platforms supporting Advanced Error Reporting (PCIe r7.0 sec 6.2),
   the faulting device may already be accessible in STEP 1 (Notification).
   Drivers should nevertheless defer accesses to STEP 2 (MMIO Enabled)
   to be compatible with EEH on powerpc and with s390 (where devices are
   inaccessible until STEP 2).

   On platforms supporting Downstream Port Containment, the link to the
   sub-hierarchy with the faulting device is re-enabled in STEP 3 (Link
   Reset). Hence devices in the sub-hierarchy are inaccessible until
   STEP 4 (Slot Reset).

   For errors such as Surprise Down (PCIe r7.0 sec 6.2.7), the device
   may not even be accessible in STEP 4 (Slot Reset). Drivers can detect
   accessibility by checking whether reads from the device return all 1's
   (PCI_POSSIBLE_ERROR()).

.. note::

   The following is proposed; no platform implements this yet:
   Proposal: All I/Os should be done _synchronously_ from within
   this callback, errors triggered by them will be returned via
   the normal pci_check_whatever() API, no new error_detected()
   callback will be issued due to an error happening here. However,
   such an error might cause IOs to be re-blocked for the whole
   segment, and thus invalidate the recovery that other devices
   on the same segment might have done, forcing the whole segment
   into one of the next states, that is, link reset or slot reset.

The driver should return one of the following result codes:
  - PCI_ERS_RESULT_RECOVERED
      Driver returns this if it thinks the device is fully
      functional and thinks it is ready to start
      normal driver operations again. There is no
      guarantee that the driver will actually be
      allowed to proceed, as another driver on the
      same segment might have failed and thus triggered a
      slot reset on platforms that support it.

  - PCI_ERS_RESULT_NEED_RESET
      Driver returns this if it thinks the device is not
      recoverable in its current state and it needs a slot
      reset to proceed.

  - PCI_ERS_RESULT_DISCONNECT
      Same as above. Total failure, no recovery even after
      reset driver dead. (To be defined more precisely)

The next step taken depends on the results returned by the drivers.
If all drivers returned PCI_ERS_RESULT_RECOVERED, then the platform
proceeds to either STEP 3 (Link Reset) or to STEP 5 (Resume Operations).

If any driver returned PCI_ERS_RESULT_NEED_RESET, then the platform
proceeds to STEP 4 (Slot Reset)

STEP 3: Link Reset
------------------
The platform resets the link.  This is a PCIe specific step
and is done whenever a fatal error has been detected that can be
"solved" by resetting the link.

STEP 4: Slot Reset
------------------

In response to a return value of PCI_ERS_RESULT_NEED_RESET, the
platform will perform a slot reset on the requesting PCI device(s).
The actual steps taken by a platform to perform a slot reset
will be platform-dependent. Upon completion of slot reset, the
platform will call the device slot_reset() callback.

Powerpc platforms implement two levels of slot reset:
soft reset(default) and fundamental(optional) reset.

Powerpc soft reset consists of asserting the adapter #RST line and then
restoring the PCI BARs and PCI configuration header to a state
that is equivalent to what it would be after a fresh system
power-on followed by power-on BIOS/system firmware initialization.
Soft reset is also known as hot-reset.

Powerpc fundamental reset is supported by PCIe cards only
and results in device's state machines, hardware logic, port states and
configuration registers to initialize to their default conditions.

For most PCI devices, a soft reset will be sufficient for recovery.
Optional fundamental reset is provided to support a limited number
of PCIe devices for which a soft reset is not sufficient
for recovery.

If the platform supports PCI hotplug, then the reset might be
performed by toggling the slot electrical power off/on.

It is important for the platform to restore the PCI config space
to the "fresh poweron" state, rather than the "last state". After
a slot reset, the device driver will almost always use its standard
device initialization routines, and an unusual config space setup
may result in hung devices, kernel panics, or silent data corruption.

This call gives drivers the chance to re-initialize the hardware
(re-download firmware, etc.).  At this point, the driver may assume
that the card is in a fresh state and is fully functional. The slot
is unfrozen and the driver has full access to PCI config space,
memory mapped I/O space and DMA. Interrupts (Legacy, MSI, or MSI-X)
will also be available.

Drivers should not restart normal I/O processing operations
at this point.  If all device drivers report success on this
callback, the platform will call resume() to complete the sequence,
and let the driver restart normal I/O processing.

A driver can still return a critical failure for this function if
it can't get the device operational after reset.  If the platform
previously tried a soft reset, it might now try a hard reset (power
cycle) and then call slot_reset() again.  If the device still can't
be recovered, there is nothing more that can be done;  the platform
will typically report a "permanent failure" in such a case.  The
device will be considered "dead" in this case.

Drivers for multi-function cards will need to coordinate among
themselves as to which driver instance will perform any "one-shot"
or global device initialization. For example, the Symbios sym53cxx2
driver performs device init only from PCI function 0::

	+       if (PCI_FUNC(pdev->devfn) == 0)
	+               sym_reset_scsi_bus(np, 0);

Result codes:
	- PCI_ERS_RESULT_DISCONNECT
	  Same as above.

Drivers for PCIe cards that require a fundamental reset must
set the needs_freset bit in the pci_dev structure in their probe function.
For example, the QLogic qla2xxx driver sets the needs_freset bit for certain
PCI card types::

	+	/* Set EEH reset type to fundamental if required by hba  */
	+	if (IS_QLA24XX(ha) || IS_QLA25XX(ha) || IS_QLA81XX(ha))
	+		pdev->needs_freset = 1;
	+

Platform proceeds either to STEP 5 (Resume Operations) or STEP 6 (Permanent
Failure).

.. note::

   The current powerpc implementation does not try a power-cycle
   reset if the driver returned PCI_ERS_RESULT_DISCONNECT.
   However, it probably should.


STEP 5: Resume Operations
-------------------------
The platform will call the resume() callback on all affected device
drivers if all drivers on the segment have returned
PCI_ERS_RESULT_RECOVERED from one of the 3 previous callbacks.
The goal of this callback is to tell the driver to restart activity,
that everything is back and running. This callback does not return
a result code.

At this point, if a new error happens, the platform will restart
a new error recovery sequence.

STEP 6: Permanent Failure
-------------------------
A "permanent failure" has occurred, and the platform cannot recover
the device.  The platform will call error_detected() with a
pci_channel_state_t value of pci_channel_io_perm_failure.

The device driver should, at this point, assume the worst. It should
cancel all pending I/O, refuse all new I/O, returning -EIO to
higher layers. The device driver should then clean up all of its
memory and remove itself from kernel operations, much as it would
during system shutdown.

The platform will typically notify the system operator of the
permanent failure in some way.  If the device is hotplug-capable,
the operator will probably want to remove and replace the device.
Note, however, not all failures are truly "permanent". Some are
caused by over-heating, some by a poorly seated card. Many
PCI error events are caused by software bugs, e.g. DMAs to
wild addresses or bogus split transactions due to programming
errors. See the discussion in Documentation/arch/powerpc/eeh-pci-error-recovery.rst
for additional detail on real-life experience of the causes of
software errors.


Conclusion; General Remarks
---------------------------
The way the callbacks are called is platform policy. A platform with
no slot reset capability may want to just "ignore" drivers that can't
recover (disconnect them) and try to let other cards on the same segment
recover. Keep in mind that in most real life cases, though, there will
be only one driver per segment.

Now, a note about interrupts. If you get an interrupt and your
device is dead or has been isolated, there is a problem :)
The current policy is to turn this into a platform policy.
That is, the recovery API only requires that:

 - There is no guarantee that interrupt delivery can proceed from any
   device on the segment starting from the error detection and until the
   slot_reset callback is called, at which point interrupts are expected
   to be fully operational.

 - There is no guarantee that interrupt delivery is stopped, that is,
   a driver that gets an interrupt after detecting an error, or that detects
   an error within the interrupt handler such that it prevents proper
   ack'ing of the interrupt (and thus removal of the source) should just
   return IRQ_NOTHANDLED. It's up to the platform to deal with that
   condition, typically by masking the IRQ source during the duration of
   the error handling. It is expected that the platform "knows" which
   interrupts are routed to error-management capable slots and can deal
   with temporarily disabling that IRQ number during error processing (this
   isn't terribly complex). That means some IRQ latency for other devices
   sharing the interrupt, but there is simply no other way. High end
   platforms aren't supposed to share interrupts between many devices
   anyway :)

.. note::

   Implementation details for the powerpc platform are discussed in
   the file Documentation/arch/powerpc/eeh-pci-error-recovery.rst

   As of this writing, there is a growing list of device drivers with
   patches implementing error recovery. Not all of these patches are in
   mainline yet. These may be used as "examples":

   - drivers/scsi/ipr
   - drivers/scsi/sym53c8xx_2
   - drivers/scsi/qla2xxx
   - drivers/scsi/lpfc
   - drivers/next/bnx2.c
   - drivers/next/e100.c
   - drivers/net/e1000
   - drivers/net/e1000e
   - drivers/net/ixgbe
   - drivers/net/cxgb3
   - drivers/net/s2io.c

   The cor_error_detected() callback is invoked in handle_error_source() when
   the error severity is "correctable". The callback is optional and allows
   additional logging to be done if desired. See example:

   - drivers/cxl/pci.c

The End
-------

---

### Documentation PCI Pci Iov Howto (`Documentation/PCI/pci-iov-howto.rst`)

.. SPDX-License-Identifier: GPL-2.0
.. include:: <isonum.txt>

====================================
PCI Express I/O Virtualization Howto
====================================

:Copyright: |copy| 2009 Intel Corporation
:Authors: - Yu Zhao <yu.zhao@intel.com>
          - Donald Dutile <ddutile@redhat.com>

Overview
========

What is SR-IOV
--------------

Single Root I/O Virtualization (SR-IOV) is a PCI Express Extended
capability which makes one physical device appear as multiple virtual
devices. The physical device is referred to as Physical Function (PF)
while the virtual devices are referred to as Virtual Functions (VF).
Allocation of the VF can be dynamically controlled by the PF via
registers encapsulated in the capability. By default, this feature is
not enabled and the PF behaves as traditional PCIe device. Once it's
turned on, each VF's PCI configuration space can be accessed by its own
Bus, Device and Function Number (Routing ID). And each VF also has PCI
Memory Space, which is used to map its register set. VF device driver
operates on the register set so it can be functional and appear as a
real existing PCI device.

User Guide
==========

How can I enable SR-IOV capability
----------------------------------

Multiple methods are available for SR-IOV enablement.
In the first method, the device driver (PF driver) will control the
enabling and disabling of the capability via API provided by SR-IOV core.
If the hardware has SR-IOV capability, loading its PF driver would
enable it and all VFs associated with the PF.  Some PF drivers require
a module parameter to be set to determine the number of VFs to enable.
In the second method, a write to the sysfs file sriov_numvfs will
enable and disable the VFs associated with a PCIe PF.  This method
enables per-PF, VF enable/disable values versus the first method,
which applies to all PFs of the same device.  Additionally, the
PCI SRIOV core support ensures that enable/disable operations are
valid to reduce duplication in multiple drivers for the same
checks, e.g., check numvfs == 0 if enabling VFs, ensure
numvfs <= totalvfs.
The second method is the recommended method for new/future VF devices.

How can I use the Virtual Functions
-----------------------------------

The VF is treated as hot-plugged PCI devices in the kernel, so they
should be able to work in the same way as real PCI devices. The VF
requires device driver that is same as a normal PCI device's.

Developer Guide
===============

SR-IOV API
----------

To enable SR-IOV capability:

(a) For the first method, in the driver::

	int pci_enable_sriov(struct pci_dev *dev, int nr_virtfn);

'nr_virtfn' is number of VFs to be enabled.

(b) For the second method, from sysfs::

	echo 'nr_virtfn' > \
        /sys/bus/pci/devices/<DOMAIN:BUS:DEVICE.FUNCTION>/sriov_numvfs

To disable SR-IOV capability:

(a) For the first method, in the driver::

	void pci_disable_sriov(struct pci_dev *dev);

(b) For the second method, from sysfs::

	echo  0 > \
        /sys/bus/pci/devices/<DOMAIN:BUS:DEVICE.FUNCTION>/sriov_numvfs

To enable auto probing VFs by a compatible driver on the host, run
command below before enabling SR-IOV capabilities. This is the
default behavior.
::

	echo 1 > \
        /sys/bus/pci/devices/<DOMAIN:BUS:DEVICE.FUNCTION>/sriov_drivers_autoprobe

To disable auto probing VFs by a compatible driver on the host, run
command below before enabling SR-IOV capabilities. Updating this
entry will not affect VFs which are already probed.
::

	echo  0 > \
        /sys/bus/pci/devices/<DOMAIN:BUS:DEVICE.FUNCTION>/sriov_drivers_autoprobe

Usage example
-------------

Following piece of code illustrates the usage of the SR-IOV API.
::

	static int dev_probe(struct pci_dev *dev, const struct pci_device_id *id)
	{
		pci_enable_sriov(dev, NR_VIRTFN);

		...

		return 0;
	}

	static void dev_remove(struct pci_dev *dev)
	{
		pci_disable_sriov(dev);

		...
	}

	static int dev_suspend(struct device *dev)
	{
		...

		return 0;
	}

	static int dev_resume(struct device *dev)
	{
		...

		return 0;
	}

	static void dev_shutdown(struct pci_dev *dev)
	{
		...
	}

	static int dev_sriov_configure(struct pci_dev *dev, int numvfs)
	{
		if (numvfs > 0) {
			...
			pci_enable_sriov(dev, numvfs);
			...
			return numvfs;
		}
		if (numvfs == 0) {
			....
			pci_disable_sriov(dev);
			...
			return 0;
		}
	}

	static struct pci_driver dev_driver = {
		.name =		"SR-IOV Physical Function driver",
		.id_table =	dev_id_table,
		.probe =	dev_probe,
		.remove =	dev_remove,
		.driver.pm =	&dev_pm_ops,
		.shutdown =	dev_shutdown,
		.sriov_configure = dev_sriov_configure,
	};

---

### Documentation PCI Pci (`Documentation/PCI/pci.rst`)

.. SPDX-License-Identifier: GPL-2.0

==============================
How To Write Linux PCI Drivers
==============================

:Authors: - Martin Mares <mj@ucw.cz>
          - Grant Grundler <grundler@parisc-linux.org>

The world of PCI is vast and full of (mostly unpleasant) surprises.
Since each CPU architecture implements different chip-sets and PCI devices
have different requirements (erm, "features"), the result is the PCI support
in the Linux kernel is not as trivial as one would wish. This short paper
tries to introduce all potential driver authors to Linux APIs for
PCI device drivers.

A more complete resource is the third edition of "Linux Device Drivers"
by Jonathan Corbet, Alessandro Rubini, and Greg Kroah-Hartman.
LDD3 is available for free (under Creative Commons License) from:
https://lwn.net/Kernel/LDD3/.

However, keep in mind that all documents are subject to "bit rot".
Refer to the source code if things are not working as described here.

Please send questions/comments/patches about Linux PCI API to the
"Linux PCI" <linux-pci@atrey.karlin.mff.cuni.cz> mailing list.


Structure of PCI drivers
========================
PCI drivers "discover" PCI devices in a system via pci_register_driver().
Actually, it's the other way around. When the PCI generic code discovers
a new device, the driver with a matching "description" will be notified.
Details on this below.

pci_register_driver() leaves most of the probing for devices to
the PCI layer and supports online insertion/removal of devices [thus
supporting hot-pluggable PCI, CardBus, and Express-Card in a single driver].
pci_register_driver() call requires passing in a table of function
pointers and thus dictates the high level structure of a driver.

Once the driver knows about a PCI device and takes ownership, the
driver generally needs to perform the following initialization:

  - Enable the device
  - Request MMIO/IOP resources
  - Set the DMA mask size (for both coherent and streaming DMA)
  - Allocate and initialize shared control data (pci_allocate_coherent())
  - Access device configuration space (if needed)
  - Register IRQ handler (request_irq())
  - Initialize non-PCI (i.e. LAN/SCSI/etc parts of the chip)
  - Enable DMA/processing engines

When done using the device, and perhaps the module needs to be unloaded,
the driver needs to take the following steps:

  - Disable the device from generating IRQs
  - Release the IRQ (free_irq())
  - Stop all DMA activity
  - Release DMA buffers (both streaming and coherent)
  - Unregister from other subsystems (e.g. scsi or netdev)
  - Release MMIO/IOP resources
  - Disable the device

Most of these topics are covered in the following sections.
For the rest look at LDD3 or <linux/pci.h> .

If the PCI subsystem is not configured (CONFIG_PCI is not set), most of
the PCI functions described below are defined as inline functions either
completely empty or just returning an appropriate error codes to avoid
lots of ifdefs in the drivers.


pci_register_driver() call
==========================

PCI device drivers call ``pci_register_driver()`` during their
initialization with a pointer to a structure describing the driver
(``struct pci_driver``):

.. kernel-doc:: include/linux/pci.h
   :functions: pci_driver

The ID table is an array of ``struct pci_device_id`` entries ending with an
all-zero entry.  Definitions with static const are generally preferred.

.. kernel-doc:: include/linux/mod_devicetable.h
   :functions: pci_device_id

Most drivers only need ``PCI_DEVICE()`` or ``PCI_DEVICE_CLASS()`` to set up
a pci_device_id table.

New PCI IDs may be added to a device driver pci_ids table at runtime
as shown below::

  echo "vendor device subvendor subdevice class class_mask driver_data" > \
  /sys/bus/pci/drivers/{driver}/new_id

All fields are passed in as hexadecimal values (no leading 0x).
The vendor and device fields are mandatory, the others are optional. Users
need pass only as many optional fields as necessary:

  - subvendor and subdevice fields default to PCI_ANY_ID (FFFFFFFF)
  - class and classmask fields default to 0
  - driver_data defaults to 0UL.
  - override_only field defaults to 0.

Note that driver_data must match the value used by any of the pci_device_id
entries defined in the driver. This makes the driver_data field mandatory
if all the pci_device_id entries have a non-zero driver_data value.

Once added, the driver probe routine will be invoked for any unclaimed
PCI devices listed in its (newly updated) pci_ids list.

When the driver exits, it just calls pci_unregister_driver() and the PCI layer
automatically calls the remove hook for all devices handled by the driver.


"Attributes" for driver functions/data
--------------------------------------

Please mark the initialization and cleanup functions where appropriate
(the corresponding macros are defined in <linux/init.h>):

	======		=================================================
	__init		Initialization code. Thrown away after the driver
			initializes.
	__exit		Exit code. Ignored for non-modular drivers.
	======		=================================================

Tips on when/where to use the above attributes:
	- The module_init()/module_exit() functions (and all
	  initialization functions called _only_ from these)
	  should be marked __init/__exit.

	- Do not mark the struct pci_driver.

	- Do NOT mark a function if you are not sure which mark to use.
	  Better to not mark the function than mark the function wrong.


How to find PCI devices manually
================================

PCI drivers should have a really good reason for not using the
pci_register_driver() interface to search for PCI devices.
The main reason PCI devices are controlled by multiple drivers
is because one PCI device implements several different HW services.
E.g. combined serial/parallel port/floppy controller.

A manual search may be performed using the following constructs:

Searching by vendor and device ID::

	struct pci_dev *dev = NULL;
	while (dev = pci_get_device(VENDOR_ID, DEVICE_ID, dev))
		configure_device(dev);

Searching by class ID (iterate in a similar way)::

	pci_get_class(CLASS_ID, dev)

Searching by both vendor/device and subsystem vendor/device ID::

	pci_get_subsys(VENDOR_ID,DEVICE_ID, SUBSYS_VENDOR_ID, SUBSYS_DEVICE_ID, dev).

You can use the constant PCI_ANY_ID as a wildcard replacement for
VENDOR_ID or DEVICE_ID.  This allows searching for any device from a
specific vendor, for example.

These functions are hotplug-safe. They increment the reference count on
the pci_dev that they return. You must eventually (possibly at module unload)
decrement the reference count on these devices by calling pci_dev_put().


Device Initialization Steps
===========================

As noted in the introduction, most PCI drivers need the following steps
for device initialization:

  - Enable the device
  - Request MMIO/IOP resources
  - Set the DMA mask size (for both coherent and streaming DMA)
  - Allocate and initialize shared control data (pci_allocate_coherent())
  - Access device configuration space (if needed)
  - Register IRQ handler (request_irq())
  - Initialize non-PCI (i.e. LAN/SCSI/etc parts of the chip)
  - Enable DMA/processing engines.

The driver can access PCI config space registers at any time.
(Well, almost. When running BIST, config space can go away...but
that will just result in a PCI Bus Master Abort and config reads
will return garbage).


Enable the PCI device
---------------------
Before touching any device registers, the driver needs to enable
the PCI device by calling pci_enable_device(). This will:

  - wake up the device if it was in suspended state,
  - allocate I/O and memory regions of the device (if BIOS did not),
  - allocate an IRQ (if BIOS did not).

.. note::
   pci_enable_device() can fail! Check the return value.

.. warning::
   OS BUG: we don't check resource allocations before enabling those
   resources. The sequence would make more sense if we called
   pci_request_resources() before calling pci_enable_device().
   Currently, the device drivers can't detect the bug when two
   devices have been allocated the same range. This is not a common
   problem and unlikely to get fixed soon.

   This has been discussed before but not changed as of 2.6.19:
   https://lore.kernel.org/r/20060302180025.GC28895@flint.arm.linux.org.uk/


pci_set_master() will enable DMA by setting the bus master bit
in the PCI_COMMAND register. It also fixes the latency timer value if
it's set to something bogus by the BIOS.  pci_clear_master() will
disable DMA by clearing the bus master bit.

If the PCI device can use the PCI Memory-Write-Invalidate transaction,
call pci_set_mwi().  This enables the PCI_COMMAND bit for Mem-Wr-Inval
and also ensures that the cache line size register is set correctly.
Check the return value of pci_set_mwi() as not all architectures
or chip-sets may support Memory-Write-Invalidate.  Alternatively,
if Mem-Wr-Inval would be nice to have but is not required, call
pci_try_set_mwi() to have the system do its best effort at enabling
Mem-Wr-Inval.


Request MMIO/IOP resources
--------------------------
Memory (MMIO), and I/O port addresses should NOT be read directly
from the PCI device config space. Use the values in the pci_dev structure
as the PCI "bus address" might have been remapped to a "host physical"
address by the arch/chip-set specific kernel support.

See Documentation/driver-api/io-mapping.rst for how to access device registers
or device memory.

The device driver needs to call pci_request_region() to verify
no other device is already using the same address resource.
Conversely, drivers should call pci_release_region() AFTER
calling pci_disable_device().
The idea is to prevent two devices colliding on the same address range.

.. tip::
   See OS BUG comment above. Currently (2.6.19), The driver can only
   determine MMIO and IO Port resource availability _after_ calling
   pci_enable_device().

Generic flavors of pci_request_region() are request_mem_region()
(for MMIO ranges) and request_region() (for IO Port ranges).
Use these for address resources that are not described by "normal" PCI
BARs.

Also see pci_request_selected_regions() below.


Set the DMA mask size
---------------------
.. note::
   If anything below doesn't make sense, please refer to
   Documentation/core-api/dma-api.rst. This section is just a reminder that
   drivers need to indicate DMA capabilities of the device and is not
   an authoritative source for DMA interfaces.

While all drivers should explicitly indicate the DMA capability
(e.g. 32 or 64 bit) of the PCI bus master, devices with more than
32-bit bus master capability for streaming data need the driver
to "register" this capability by calling dma_set_mask() with
appropriate parameters.  In general this allows more efficient DMA
on systems where System RAM exists above 4G _physical_ address.

Drivers for all PCI-X and PCIe compliant devices must call
dma_set_mask() as they are 64-bit DMA devices.

Similarly, drivers must also "register" this capability if the device
can directly address "coherent memory" in System RAM above 4G physical
address by calling dma_set_coherent_mask().
Again, this includes drivers for all PCI-X and PCIe compliant devices.
Many 64-bit "PCI" devices (before PCI-X) and some PCI-X devices are
64-bit DMA capable for payload ("streaming") data but not control
("coherent") data.


Setup shared control data
-------------------------
Once the DMA masks are set, the driver can allocate "coherent" (a.k.a. shared)
memory.  See Documentation/core-api/dma-api.rst for a full description of
the DMA APIs. This section is just a reminder that it needs to be done
before enabling DMA on the device.


Initialize device registers
---------------------------
Some drivers will need specific "capability" fields programmed
or other "vendor specific" register initialized or reset.
E.g. clearing pending interrupts.


Register IRQ handler
--------------------
While calling request_irq() is the last step described here,
this is often just another intermediate step to initialize a device.
This step can often be deferred until the device is opened for use.

All interrupt handlers for IRQ lines should be registered with IRQF_SHARED
and use the devid to map IRQs to devices (remember that all PCI IRQ lines
can be shared).

request_irq() will associate an interrupt handler and device handle
with an interrupt number. Historically interrupt numbers represent
IRQ lines which run from the PCI device to the Interrupt controller.
With MSI and MSI-X (more below) the interrupt number is a CPU "vector".

request_irq() also enables the interrupt. Make sure the device is
quiesced and does not have any interrupts pending before registering
the interrupt handler.

MSI and MSI-X are PCI capabilities. Both are "Message Signaled Interrupts"
which deliver interrupts to the CPU via a DMA write to a Local APIC.
The fundamental difference between MSI and MSI-X is how multiple
"vectors" get allocated. MSI requires contiguous blocks of vectors
while MSI-X can allocate several individual ones.

MSI capability can be enabled by calling pci_alloc_irq_vectors() with the
PCI_IRQ_MSI and/or PCI_IRQ_MSIX flags before calling request_irq(). This
causes the PCI support to program CPU vector data into the PCI device
capability registers. Many architectures, chip-sets, or BIOSes do NOT
support MSI or MSI-X and a call to pci_alloc_irq_vectors with just
the PCI_IRQ_MSI and PCI_IRQ_MSIX flags will fail, so try to always
specify PCI_IRQ_INTX as well.

Drivers that have different interrupt handlers for MSI/MSI-X and
legacy INTx should chose the right one based on the msi_enabled
and msix_enabled flags in the pci_dev structure after calling
pci_alloc_irq_vectors.

There are (at least) two really good reasons for using MSI:

1) MSI is an exclusive interrupt vector by definition.
   This means the interrupt handler doesn't have to verify
   its device caused the interrupt.

2) MSI avoids DMA/IRQ race conditions. DMA to host memory is guaranteed
   to be visible to the host CPU(s) when the MSI is delivered. This
   is important for both data coherency and avoiding stale control data.
   This guarantee allows the driver to omit MMIO reads to flush
   the DMA stream.

See drivers/infiniband/hw/mthca/ or drivers/net/tg3.c for examples
of MSI/MSI-X usage.


PCI device shutdown
===================

When a PCI device driver is being unloaded, most of the following
steps need to be performed:

  - Disable the device from generating IRQs
  - Release the IRQ (free_irq())
  - Stop all DMA activity
  - Release DMA buffers (both streaming and coherent)
  - Unregister from other subsystems (e.g. scsi or netdev)
  - Disable device from responding to MMIO/IO Port addresses
  - Release MMIO/IO Port resource(s)


Stop IRQs on the device
-----------------------
How to do this is chip/device specific. If it's not done, it opens
the possibility of a "screaming interrupt" if (and only if)
the IRQ is shared with another device.

When the shared IRQ handler is "unhooked", the remaining devices
using the same IRQ line will still need the IRQ enabled. Thus if the
"unhooked" device asserts IRQ line, the system will respond assuming
it was one of the remaining devices asserted the IRQ line. Since none
of the other devices will handle the IRQ, the system will "hang" until
it decides the IRQ isn't going to get handled and masks the IRQ (100,000
iterations later). Once the shared IRQ is masked, the remaining devices
will stop functioning properly. Not a nice situation.

This is another reason to use MSI or MSI-X if it's available.
MSI and MSI-X are defined to be exclusive interrupts and thus
are not susceptible to the "screaming interrupt" problem.


Release the IRQ
---------------
Once the device is quiesced (no more IRQs), one can call free_irq().
This function will return control once any pending IRQs are handled,
"unhook" the drivers IRQ handler from that IRQ, and finally release
the IRQ if no one else is using it.


Stop all DMA activity
---------------------
It's extremely important to stop all DMA operations BEFORE attempting
to deallocate DMA control data. Failure to do so can result in memory
corruption, hangs, and on some chip-sets a hard crash.

Stopping DMA after stopping the IRQs can avoid races where the
IRQ handler might restart DMA engines.

While this step sounds obvious and trivial, several "mature" drivers
didn't get this step right in the past.


Release DMA buffers
-------------------
Once DMA is stopped, clean up streaming DMA first.
I.e. unmap data buffers and return buffers to "upstream"
owners if there is one.

Then clean up "coherent" buffers which contain the control data.

See Documentation/core-api/dma-api.rst for details on unmapping interfaces.


Unregister from other subsystems
--------------------------------
Most low level PCI device drivers support some other subsystem
like USB, ALSA, SCSI, NetDev, Infiniband, etc. Make sure your
driver isn't losing resources from that other subsystem.
If this happens, typically the symptom is an Oops (panic) when
the subsystem attempts to call into a driver that has been unloaded.


Disable Device from responding to MMIO/IO Port addresses
--------------------------------------------------------
io_unmap() MMIO or IO Port resources and then call pci_disable_device().
This is the symmetric opposite of pci_enable_device().
Do not access device registers after calling pci_disable_device().


Release MMIO/IO Port Resource(s)
--------------------------------
Call pci_release_region() to mark the MMIO or IO Port range as available.
Failure to do so usually results in the inability to reload the driver.


How to access PCI config space
==============================

You can use `pci_(read|write)_config_(byte|word|dword)` to access the config
space of a device represented by `struct pci_dev *`. All these functions return
0 when successful or an error code (`PCIBIOS_...`) which can be translated to a
text string by pcibios_strerror. Most drivers expect that accesses to valid PCI
devices don't fail.

If you don't have a struct pci_dev available, you can call
`pci_bus_(read|write)_config_(byte|word|dword)` to access a given device
and function on that bus.

If you access fields in the standard portion of the config header, please
use symbolic names of locations and bits declared in <linux/pci.h>.

If you need to access Extended PCI Capability registers, just call
pci_find_capability() for the particular capability and it will find the
corresponding register block for you.


Other interesting functions
===========================

=============================	================================================
pci_get_domain_bus_and_slot()	Find pci_dev corresponding to given domain,
				bus and slot and number. If the device is
				found, its reference count is increased.
pci_set_power_state()		Set PCI Power Management state (0=D0 ... 3=D3)
pci_find_capability()		Find specified capability in device's capability
				list.
pci_resource_start()		Returns bus start address for a given PCI region
pci_resource_end()		Returns bus end address for a given PCI region
pci_resource_len()		Returns the byte length of a PCI region
pci_set_drvdata()		Set private driver data pointer for a pci_dev
pci_get_drvdata()		Return private driver data pointer for a pci_dev
pci_set_mwi()			Enable Memory-Write-Invalidate transactions.
pci_clear_mwi()			Disable Memory-Write-Invalidate transactions.
=============================	================================================


Miscellaneous hints
===================

When displaying PCI device names to the user (for example when a driver wants
to tell the user what card has it found), please use pci_name(pci_dev).

Always refer to the PCI devices by a pointer to the pci_dev structure.
All PCI layer functions use this identification and it's the only
reasonable one. Don't use bus/slot/function numbers except for very
special purposes -- on systems with multiple primary buses their semantics
can be pretty complex.

Don't try to turn on Fast Back to Back writes in your driver.  All devices
on the bus need to be capable of doing it, so this is something which needs
to be handled by platform and generic code, not individual drivers.


Vendor and device identifications
=================================

Do not add new device or vendor IDs to include/linux/pci_ids.h unless they
are shared across multiple drivers.  You can add private definitions in
your driver if they're helpful, or just use plain hex constants.

The device IDs are arbitrary hex numbers (vendor controlled) and normally used
only in a single location, the pci_device_id table.

Please DO submit new vendor/device IDs to https://pci-ids.ucw.cz/.
There's a mirror of the pci.ids file at https://github.com/pciutils/pciids.


Obsolete functions
==================

There are several functions which you might come across when trying to
port an old driver to the new PCI interface.  They are no longer present
in the kernel as they aren't compatible with hotplug or PCI domains or
having sane locking.

=================	===========================================
pci_find_device()	Superseded by pci_get_device()
pci_find_subsys()	Superseded by pci_get_subsys()
pci_find_slot()		Superseded by pci_get_domain_bus_and_slot()
pci_get_slot()		Superseded by pci_get_domain_bus_and_slot()
=================	===========================================

The alternative is the traditional PCI device driver that walks PCI
device lists. This is still possible but discouraged.


MMIO Space and "Write Posting"
==============================

Converting a driver from using I/O Port space to using MMIO space
often requires some additional changes. Specifically, "write posting"
needs to be handled. Many drivers (e.g. tg3, acenic, sym53c8xx_2)
already do this. I/O Port space guarantees write transactions reach the PCI
device before the CPU can continue. Writes to MMIO space allow the CPU
to continue before the transaction reaches the PCI device. HW weenies
call this "Write Posting" because the write completion is "posted" to
the CPU before the transaction has reached its destination.

Thus, timing sensitive code should add readl() where the CPU is
expected to wait before doing other work.  The classic "bit banging"
sequence works fine for I/O Port space::

       for (i = 8; --i; val >>= 1) {
               outb(val & 1, ioport_reg);      /* write bit */
               udelay(10);
       }

The same sequence for MMIO space should be::

       for (i = 8; --i; val >>= 1) {
               writeb(val & 1, mmio_reg);      /* write bit */
               readb(safe_mmio_reg);           /* flush posted write */
               udelay(10);
       }

It is important that "safe_mmio_reg" not have any side effects that
interferes with the correct operation of the device.

Another case to watch out for is when resetting a PCI device. Use PCI
Configuration space reads to flush the writel(). This will gracefully
handle the PCI master abort on all platforms if the PCI device is
expected to not respond to a readl().  Most x86 platforms will allow
MMIO reads to master abort (a.k.a. "Soft Fail") and return garbage
(e.g. ~0). But many RISC platforms will crash (a.k.a."Hard Fail").

---

### Documentation PCI Pcieaer Howto (`Documentation/PCI/pcieaer-howto.rst`)

.. SPDX-License-Identifier: GPL-2.0
.. include:: <isonum.txt>

===========================================================
The PCI Express Advanced Error Reporting Driver Guide HOWTO
===========================================================

:Authors: - T. Long Nguyen <tom.l.nguyen@intel.com>
          - Yanmin Zhang <yanmin.zhang@intel.com>

:Copyright: |copy| 2006 Intel Corporation

Overview
===========

About this guide
----------------

This guide describes the basics of the PCI Express (PCIe) Advanced Error
Reporting (AER) driver and provides information on how to use it, as
well as how to enable the drivers of Endpoint devices to conform with
the PCIe AER driver.


What is the PCIe AER Driver?
----------------------------

PCIe error signaling can occur on the PCIe link itself
or on behalf of transactions initiated on the link. PCIe
defines two error reporting paradigms: the baseline capability and
the Advanced Error Reporting capability. The baseline capability is
required of all PCIe components providing a minimum defined
set of error reporting requirements. Advanced Error Reporting
capability is implemented with a PCIe Advanced Error Reporting
extended capability structure providing more robust error reporting.

The PCIe AER driver provides the infrastructure to support PCIe Advanced
Error Reporting capability. The PCIe AER driver provides three basic
functions:

  - Gathers the comprehensive error information if errors occurred.
  - Reports error to the users.
  - Performs error recovery actions.

The AER driver only attaches to Root Ports and RCECs that support the PCIe
AER capability.


User Guide
==========

Include the PCIe AER Root Driver into the Linux Kernel
------------------------------------------------------

The PCIe AER driver is a Root Port service driver attached
via the PCIe Port Bus driver. If a user wants to use it, the driver
must be compiled. It is enabled with CONFIG_PCIEAER, which
depends on CONFIG_PCIEPORTBUS.

Load PCIe AER Root Driver
-------------------------

Some systems have AER support in firmware. Enabling Linux AER support at
the same time the firmware handles AER would result in unpredictable
behavior. Therefore, Linux does not handle AER events unless the firmware
grants AER control to the OS via the ACPI _OSC method. See the PCI Firmware
Specification for details regarding _OSC usage.

AER error output
----------------

When a PCIe AER error is captured, an error message will be output to
console. If it's a correctable error, it is output as a warning message.
Otherwise, it is printed as an error. So users could choose different
log level to filter out correctable error messages.

Below shows an example::

  0000:50:00.0: PCIe Bus Error: severity=Uncorrectable (Fatal), type=Transaction Layer, (Requester ID)
  0000:50:00.0:   device [8086:0329] error status/mask=00100000/00000000
  0000:50:00.0:    [20] UnsupReq               (First)
  0000:50:00.0:   TLP Header: 0x04000001 0x00200a03 0x05010000 0x00050100

In the example, 'Requester ID' means the ID of the device that sent
the error message to the Root Port. Please refer to PCIe specs for other
fields.

AER Ratelimits
--------------

Since error messages can be generated for each transaction, we may see
large volumes of errors reported. To prevent spammy devices from flooding
the console/stalling execution, messages are throttled by device and error
type (correctable vs. non-fatal uncorrectable).  Fatal errors, including
DPC errors, are not ratelimited.

AER uses the default ratelimit of DEFAULT_RATELIMIT_BURST (10 events) over
DEFAULT_RATELIMIT_INTERVAL (5 seconds).

Ratelimits are exposed in the form of sysfs attributes and configurable.
See Documentation/ABI/testing/sysfs-bus-pci-devices-aer.

AER Statistics / Counters
-------------------------

When PCIe AER errors are captured, the counters / statistics are also exposed
in the form of sysfs attributes which are documented at
Documentation/ABI/testing/sysfs-bus-pci-devices-aer.

Developer Guide
===============

To enable error recovery, a software driver must provide callbacks.

To support AER better, developers need to understand how AER works.

PCIe errors are classified into two types: correctable errors
and uncorrectable errors. This classification is based on the impact
of those errors, which may result in degraded performance or function
failure.

Correctable errors pose no impacts on the functionality of the
interface. The PCIe protocol can recover without any software
intervention or any loss of data. These errors are detected and
corrected by hardware.

Unlike correctable errors, uncorrectable
errors impact functionality of the interface. Uncorrectable errors
can cause a particular transaction or a particular PCIe link
to be unreliable. Depending on those error conditions, uncorrectable
errors are further classified into non-fatal errors and fatal errors.
Non-fatal errors cause the particular transaction to be unreliable,
but the PCIe link itself is fully functional. Fatal errors, on
the other hand, cause the link to be unreliable.

When PCIe error reporting is enabled, a device will automatically send an
error message to the Root Port above it when it captures
an error. The Root Port, upon receiving an error reporting message,
internally processes and logs the error message in its AER
Capability structure. Error information being logged includes storing
the error reporting agent's Requester ID into the Error Source
Identification Registers and setting the error bits of the Root Error
Status Register accordingly. If AER error reporting is enabled in the Root
Error Command Register, the Root Port generates an interrupt when an
error is detected.

Note that the errors as described above are related to the PCIe
hierarchy and links. These errors do not include any device specific
errors because device specific errors will still get sent directly to
the device driver.

Provide callbacks
-----------------

PCI error-recovery callbacks
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The PCIe AER Root driver uses error callbacks to coordinate
with downstream device drivers associated with a hierarchy in question
when performing error recovery actions.

Data struct pci_driver has a pointer, err_handler, to point to
pci_error_handlers who consists of a couple of callback function
pointers. The AER driver follows the rules defined in
pci-error-recovery.rst except PCIe-specific parts (see
below). Please refer to pci-error-recovery.rst for detailed
definitions of the callbacks.

The sections below specify when to call the error callback functions.

Correctable errors
~~~~~~~~~~~~~~~~~~

Correctable errors pose no impacts on the functionality of
the interface. The PCIe protocol can recover without any
software intervention or any loss of data. These errors do not
require any recovery actions. The AER driver clears the device's
correctable error status register accordingly and logs these errors.

Uncorrectable (non-fatal and fatal) errors
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The AER driver performs a Secondary Bus Reset to recover from
uncorrectable errors. The reset is applied at the port above
the originating device: If the originating device is an Endpoint,
only the Endpoint is reset. If on the other hand the originating
device has subordinate devices, those are all affected by the
reset as well.

If the originating device is a Root Complex Integrated Endpoint,
there's no port above where a Secondary Bus Reset could be applied.
In this case, the AER driver instead applies a Function Level Reset.

If an error message indicates a non-fatal error, performing a reset
at upstream is not required. The AER driver calls error_detected(dev,
pci_channel_io_normal) to all drivers associated within a hierarchy in
question. For example::

  Endpoint <==> Downstream Port B <==> Upstream Port A <==> Root Port

If Upstream Port A captures an AER error, the hierarchy consists of
Downstream Port B and Endpoint.

A driver may return PCI_ERS_RESULT_CAN_RECOVER,
PCI_ERS_RESULT_DISCONNECT, or PCI_ERS_RESULT_NEED_RESET, depending on
whether it can recover without a reset, considers the device unrecoverable
or needs a reset for recovery. If all affected drivers agree that they can
recover without a reset, it is skipped. Should one driver request a reset,
it overrides all other drivers.

If an error message indicates a fatal error, kernel will broadcast
error_detected(dev, pci_channel_io_frozen) to all drivers within
a hierarchy in question. Then, performing a reset at upstream is
necessary. If error_detected returns PCI_ERS_RESULT_CAN_RECOVER
to indicate that recovery without a reset is possible, the error
handling goes to mmio_enabled, but afterwards a reset is still
performed.

In other words, for non-fatal errors, drivers may opt in to a reset.
But for fatal errors, they cannot opt out of a reset, based on the
assumption that the link is unreliable.

Frequently Asked Questions
--------------------------

Q:
  What happens if a PCIe device driver does not provide an
  error recovery handler (pci_driver->err_handler is equal to NULL)?

A:
  The devices attached with the driver won't be recovered.
  The kernel will print out informational messages to identify
  unrecoverable devices.


Software error injection
========================

Debugging PCIe AER error recovery code is quite difficult because it
is hard to trigger real hardware errors. Software based error
injection can be used to fake various kinds of PCIe errors.

First you should enable PCIe AER software error injection in kernel
configuration, that is, following item should be in your .config.

CONFIG_PCIEAER_INJECT=y or CONFIG_PCIEAER_INJECT=m

After reboot with new kernel or insert the module, a device file named
/dev/aer_inject should be created.

Then, you need a user space tool named aer-inject, which can be gotten
from:

    https://github.com/intel/aer-inject.git

More information about aer-inject can be found in the document in
its source code.

---

### Documentation PCI Pciebus Howto (`Documentation/PCI/pciebus-howto.rst`)

.. SPDX-License-Identifier: GPL-2.0
.. include:: <isonum.txt>

===========================================
The PCI Express Port Bus Driver Guide HOWTO
===========================================

:Author: Tom L Nguyen tom.l.nguyen@intel.com 11/03/2004
:Copyright: |copy| 2004 Intel Corporation

About this guide
================

This guide describes the basics of the PCI Express Port Bus driver
and provides information on how to enable the service drivers to
register/unregister with the PCI Express Port Bus Driver.


What is the PCI Express Port Bus Driver
=======================================

A PCI Express Port is a logical PCI-PCI Bridge structure. There
are two types of PCI Express Port: the Root Port and the Switch
Port. The Root Port originates a PCI Express link from a PCI Express
Root Complex and the Switch Port connects PCI Express links to
internal logical PCI buses. The Switch Port, which has its secondary
bus representing the switch's internal routing logic, is called the
switch's Upstream Port. The switch's Downstream Port is bridging from
switch's internal routing bus to a bus representing the downstream
PCI Express link from the PCI Express Switch.

A PCI Express Port can provide up to four distinct functions,
referred to in this document as services, depending on its port type.
PCI Express Port's services include native hotplug support (HP),
power management event support (PME), advanced error reporting
support (AER), and virtual channel support (VC). These services may
be handled by a single complex driver or be individually distributed
and handled by corresponding service drivers.

Why use the PCI Express Port Bus Driver?
========================================

In existing Linux kernels, the Linux Device Driver Model allows a
physical device to be handled by only a single driver. The PCI
Express Port is a PCI-PCI Bridge device with multiple distinct
services. To maintain a clean and simple solution each service
may have its own software service driver. In this case several
service drivers will compete for a single PCI-PCI Bridge device.
For example, if the PCI Express Root Port native hotplug service
driver is loaded first, it claims a PCI-PCI Bridge Root Port. The
kernel therefore does not load other service drivers for that Root
Port. In other words, it is impossible to have multiple service
drivers load and run on a PCI-PCI Bridge device simultaneously
using the current driver model.

To enable multiple service drivers running simultaneously requires
having a PCI Express Port Bus driver, which manages all populated
PCI Express Ports and distributes all provided service requests
to the corresponding service drivers as required. Some key
advantages of using the PCI Express Port Bus driver are listed below:

  - Allow multiple service drivers to run simultaneously on
    a PCI-PCI Bridge Port device.

  - Allow service drivers implemented in an independent
    staged approach.

  - Allow one service driver to run on multiple PCI-PCI Bridge
    Port devices.

  - Manage and distribute resources of a PCI-PCI Bridge Port
    device to requested service drivers.

Configuring the PCI Express Port Bus Driver vs. Service Drivers
===============================================================

Including the PCI Express Port Bus Driver Support into the Kernel
-----------------------------------------------------------------

Including the PCI Express Port Bus driver depends on whether the PCI
Express support is included in the kernel config. The kernel will
automatically include the PCI Express Port Bus driver as a kernel
driver when the PCI Express support is enabled in the kernel.

Enabling Service Driver Support
-------------------------------

PCI device drivers are implemented based on Linux Device Driver Model.
All service drivers are PCI device drivers. As discussed above, it is
impossible to load any service driver once the kernel has loaded the
PCI Express Port Bus Driver. To meet the PCI Express Port Bus Driver
Model requires some minimal changes on existing service drivers that
imposes no impact on the functionality of existing service drivers.

A service driver is required to use the two APIs shown below to
register its service with the PCI Express Port Bus driver (see
section 5.2.1 & 5.2.2). It is important that a service driver
initializes the pcie_port_service_driver data structure, included in
header file /include/linux/pcieport_if.h, before calling these APIs.
Failure to do so will result an identity mismatch, which prevents
the PCI Express Port Bus driver from loading a service driver.

pcie_port_service_register
~~~~~~~~~~~~~~~~~~~~~~~~~~
::

  int pcie_port_service_register(struct pcie_port_service_driver *new)

This API replaces the Linux Driver Model's pci_register_driver API. A
service driver should always calls pcie_port_service_register at
module init. Note that after service driver being loaded, calls
such as pci_enable_device(dev) and pci_set_master(dev) are no longer
necessary since these calls are executed by the PCI Port Bus driver.

pcie_port_service_unregister
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
::

  void pcie_port_service_unregister(struct pcie_port_service_driver *new)

pcie_port_service_unregister replaces the Linux Driver Model's
pci_unregister_driver. It's always called by service driver when a
module exits.

Sample Code
~~~~~~~~~~~

Below is sample service driver code to initialize the port service
driver data structure.
::

  static struct pcie_port_service_id service_id[] = { {
    .vendor = PCI_ANY_ID,
    .device = PCI_ANY_ID,
    .port_type = PCIE_RC_PORT,
    .service_type = PCIE_PORT_SERVICE_AER,
    }, { /* end: all zeroes */ }
  };

  static struct pcie_port_service_driver root_aerdrv = {
    .name		= (char *)device_name,
    .id_table	= service_id,

    .probe		= aerdrv_load,
    .remove		= aerdrv_unload,

    .suspend	= aerdrv_suspend,
    .resume		= aerdrv_resume,
  };

Below is a sample code for registering/unregistering a service
driver.
::

  static int __init aerdrv_service_init(void)
  {
    int retval = 0;

    retval = pcie_port_service_register(&root_aerdrv);
    if (!retval) {
      /*
      * FIX ME
      */
    }
    return retval;
  }

  static void __exit aerdrv_service_exit(void)
  {
    pcie_port_service_unregister(&root_aerdrv);
  }

  module_init(aerdrv_service_init);
  module_exit(aerdrv_service_exit);

Possible Resource Conflicts
===========================

Since all service drivers of a PCI-PCI Bridge Port device are
allowed to run simultaneously, below lists a few of possible resource
conflicts with proposed solutions.

MSI and MSI-X Vector Resource
-----------------------------

Once MSI or MSI-X interrupts are enabled on a device, it stays in this
mode until they are disabled again.  Since service drivers of the same
PCI-PCI Bridge port share the same physical device, if an individual
service driver enables or disables MSI/MSI-X mode it may result
unpredictable behavior.

To avoid this situation all service drivers are not permitted to
switch interrupt mode on its device. The PCI Express Port Bus driver
is responsible for determining the interrupt mode and this should be
transparent to service drivers. Service drivers need to know only
the vector IRQ assigned to the field irq of struct pcie_device, which
is passed in when the PCI Express Port Bus driver probes each service
driver. Service drivers should use (struct pcie_device*)dev->irq to
call request_irq/free_irq. In addition, the interrupt mode is stored
in the field interrupt_mode of struct pcie_device.

PCI Memory/IO Mapped Regions
----------------------------

Service drivers for PCI Express Power Management (PME), Advanced
Error Reporting (AER), Hot-Plug (HP) and Virtual Channel (VC) access
PCI configuration space on the PCI Express port. In all cases the
registers accessed are independent of each other. This patch assumes
that all service drivers will be well behaved and not overwrite
other service driver's configuration settings.

PCI Config Registers
--------------------

Each service driver runs its PCI config operations on its own
capability structure except the PCI Express capability structure,
that is shared between many drivers including the service drivers.
RMW Capability accessors (pcie_capability_clear_and_set_word(),
pcie_capability_set_word(), and pcie_capability_clear_word()) protect
a selected set of PCI Express Capability Registers:

* Link Control Register
* Root Control Register
* Link Control 2 Register

Any change to those registers should be performed using RMW accessors to
avoid problems due to concurrent updates. For the up-to-date list of
protected registers, see pcie_capability_clear_and_set_word().

---

### Documentation PCI Sysfs Pci (`Documentation/PCI/sysfs-pci.rst`)

.. SPDX-License-Identifier: GPL-2.0

============================================
Accessing PCI device resources through sysfs
============================================

sysfs, usually mounted at /sys, provides access to PCI resources on platforms
that support it.  For example, a given bus might look like this::

     /sys/devices/pci0000:17
     |-- 0000:17:00.0
     |   |-- class
     |   |-- config
     |   |-- device
     |   |-- enable
     |   |-- irq
     |   |-- local_cpus
     |   |-- remove
     |   |-- resource
     |   |-- resource0
     |   |-- resource1
     |   |-- resource2
     |   |-- revision
     |   |-- rom
     |   |-- subsystem_device
     |   |-- subsystem_vendor
     |   `-- vendor
     `-- ...

The topmost element describes the PCI domain and bus number.  In this case,
the domain number is 0000 and the bus number is 17 (both values are in hex).
This bus contains a single function device in slot 0.  The domain and bus
numbers are reproduced for convenience.  Under the device directory are several
files, each with their own function.

       =================== =====================================================
       file		   function
       =================== =====================================================
       class		   PCI class (ascii, ro)
       config		   PCI config space (binary, rw)
       device		   PCI device (ascii, ro)
       enable	           Whether the device is enabled (ascii, rw)
       irq		   IRQ number (ascii, ro)
       local_cpus	   nearby CPU mask (cpumask, ro)
       remove		   remove device from kernel's list (ascii, wo)
       resource		   PCI resource host addresses (ascii, ro)
       resource0..N	   PCI resource N, if present (binary, mmap, rw\ [1]_)
       resource0_wc..N_wc  PCI WC map resource N, if prefetchable (binary, mmap)
       revision		   PCI revision (ascii, ro)
       rom		   PCI ROM resource, if present (binary, ro)
       subsystem_device	   PCI subsystem device (ascii, ro)
       subsystem_vendor	   PCI subsystem vendor (ascii, ro)
       vendor		   PCI vendor (ascii, ro)
       =================== =====================================================

::

  ro - read only file
  rw - file is readable and writable
  wo - write only file
  mmap - file is mmapable
  ascii - file contains ascii text
  binary - file contains binary data
  cpumask - file contains a cpumask type

.. [1] rw for IORESOURCE_IO (I/O port) regions only

The read only files are informational, writes to them will be ignored, with
the exception of the 'rom' file.  Writable files can be used to perform
actions on the device (e.g. changing config space, detaching a device).
mmapable files are available via an mmap of the file at offset 0 and can be
used to do actual device programming from userspace.  Note that some platforms
don't support mmapping of certain resources, so be sure to check the return
value from any attempted mmap.  The most notable of these are I/O port
resources, which also provide read/write access.

The 'enable' file provides a counter that indicates how many times the device
has been enabled.  If the 'enable' file currently returns '4', and a '1' is
echoed into it, it will then return '5'.  Echoing a '0' into it will decrease
the count.  Even when it returns to 0, though, some of the initialisation
may not be reversed.

The 'rom' file is special in that it provides read-only access to the device's
ROM file, if available.  It's disabled by default, however, so applications
should write the string "1" to the file to enable it before attempting a read
call, and disable it following the access by writing "0" to the file.  Note
that the device must be enabled for a rom read to return data successfully.
In the event a driver is not bound to the device, it can be enabled using the
'enable' file, documented above.

The 'remove' file is used to remove the PCI device, by writing a non-zero
integer to the file.  This does not involve any kind of hot-plug functionality,
e.g. powering off the device.  The device is removed from the kernel's list of
PCI devices, the sysfs directory for it is removed, and the device will be
removed from any drivers attached to it. Removal of PCI root buses is
disallowed.

Accessing legacy resources through sysfs
----------------------------------------

Legacy I/O port and ISA memory resources are also provided in sysfs if the
underlying platform supports them.  They're located in the PCI class hierarchy,
e.g.::

	/sys/class/pci_bus/0000:17/
	|-- bridge -> ../../../devices/pci0000:17
	|-- cpuaffinity
	|-- legacy_io
	`-- legacy_mem

The legacy_io file is a read/write file that can be used by applications to
do legacy port I/O.  The application should open the file, seek to the desired
port (e.g. 0x3e8) and do a read or a write of 1, 2 or 4 bytes.  The legacy_mem
file should be mmapped with an offset corresponding to the memory offset
desired, e.g. 0xa0000 for the VGA frame buffer.  The application can then
simply dereference the returned pointer (after checking for errors of course)
to access legacy memory space.

Supporting PCI access on new platforms
--------------------------------------

In order to support PCI resource mapping as described above, Linux platform
code should ideally define ARCH_GENERIC_PCI_MMAP_RESOURCE and use the generic
implementation of that functionality. To support the historical interface of
mmap() through files in /proc/bus/pci, platforms may also set HAVE_PCI_MMAP.

Alternatively, platforms which set HAVE_PCI_MMAP may provide their own
implementation of pci_mmap_resource_range() instead of defining
ARCH_GENERIC_PCI_MMAP_RESOURCE.

Platforms which support write-combining maps of PCI resources must define
arch_can_pci_mmap_wc() which shall evaluate to non-zero at runtime when
write-combining is permitted. Platforms which support maps of I/O resources
define arch_can_pci_mmap_io() similarly.

Legacy resources are protected by the HAVE_PCI_LEGACY define.  Platforms
wishing to support legacy functionality should define it and provide
pci_legacy_read, pci_legacy_write and pci_mmap_legacy_page_range functions.

---

### Documentation PCI Tph (`Documentation/PCI/tph.rst`)

.. SPDX-License-Identifier: GPL-2.0


===========
TPH Support
===========

:Copyright: 2024 Advanced Micro Devices, Inc.
:Authors: - Eric van Tassell <eric.vantassell@amd.com>
          - Wei Huang <wei.huang2@amd.com>


Overview
========

TPH (TLP Processing Hints) is a PCIe feature that allows endpoint devices
to provide optimization hints for requests that target memory space.
These hints, in a format called Steering Tags (STs), are embedded in the
requester's TLP headers, enabling the system hardware, such as the Root
Complex, to better manage platform resources for these requests.

For example, on platforms with TPH-based direct data cache injection
support, an endpoint device can include appropriate STs in its DMA
traffic to specify which cache the data should be written to. This allows
the CPU core to have a higher probability of getting data from cache,
potentially improving performance and reducing latency in data
processing.


How to Use TPH
==============

TPH is presented as an optional extended capability in PCIe. The Linux
kernel handles TPH discovery during boot, but it is up to the device
driver to request TPH enablement if it is to be utilized. Once enabled,
the driver uses the provided API to obtain the Steering Tag for the
target memory and to program the ST into the device's ST table.

Enable TPH support in Linux
---------------------------

To support TPH, the kernel must be built with the CONFIG_PCIE_TPH option
enabled.

Manage TPH
----------

To enable TPH for a device, use the following function::

  int pcie_enable_tph(struct pci_dev *pdev, int mode);

This function enables TPH support for device with a specific ST mode.
Current supported modes include:

  * PCI_TPH_ST_NS_MODE - NO ST Mode
  * PCI_TPH_ST_IV_MODE - Interrupt Vector Mode
  * PCI_TPH_ST_DS_MODE - Device Specific Mode

`pcie_enable_tph()` checks whether the requested mode is actually
supported by the device before enabling. The device driver can figure out
which TPH mode is supported and can be properly enabled based on the
return value of `pcie_enable_tph()`.

To disable TPH, use the following function::

  void pcie_disable_tph(struct pci_dev *pdev);

Manage ST
---------

Steering Tags are platform specific. PCIe spec does not specify where STs
are from. Instead PCI Firmware Specification defines an ACPI _DSM method
(see the `Revised _DSM for Cache Locality TPH Features ECN
<https://members.pcisig.com/wg/PCI-SIG/document/15470>`_) for retrieving
STs for a target memory of various properties. This method is what is
supported in this implementation.

To retrieve a Steering Tag for a target memory associated with a specific
CPU, use the following function::

  int pcie_tph_get_cpu_st(struct pci_dev *pdev, enum tph_mem_type type,
                          unsigned int cpu_uid, u16 *tag);

The `type` argument is used to specify the memory type, either volatile
or persistent, of the target memory. The `cpu_uid` argument specifies the
CPU where the memory is associated to.

After the ST value is retrieved, the device driver can use the following
function to write the ST into the device::

  int pcie_tph_set_st_entry(struct pci_dev *pdev, unsigned int index,
                            u16 tag);

The `index` argument is the ST table entry index the ST tag will be
written into. `pcie_tph_set_st_entry()` will figure out the proper
location of ST table, either in the MSI-X table or in the TPH Extended
Capability space, and write the Steering Tag into the ST entry pointed by
the `index` argument.

It is completely up to the driver to decide how to use these TPH
functions. For example a network device driver can use the TPH APIs above
to update the Steering Tag when interrupt affinity of a RX/TX queue has
been changed. Here is a sample code for IRQ affinity notifier:

.. code-block:: c

    static void irq_affinity_notified(struct irq_affinity_notify *notify,
                                      const cpumask_t *mask)
    {
         struct drv_irq *irq;
         unsigned int cpu_id;
         u16 tag;

         irq = container_of(notify, struct drv_irq, affinity_notify);
         cpumask_copy(irq->cpu_mask, mask);

         /* Pick a right CPU as the target - here is just an example */
         cpu_id = cpumask_first(irq->cpu_mask);

         if (pcie_tph_get_cpu_st(irq->pdev, TPH_MEM_TYPE_VM, cpu_id,
                                 &tag))
             return;

         if (pcie_tph_set_st_entry(irq->pdev, irq->msix_nr, tag))
             return;
    }

Disable TPH system-wide
-----------------------

There is a kernel command line option available to control TPH feature:
    * "notph": TPH will be disabled for all endpoint devices.

---

### Documentation RCU NMI RCU (`Documentation/RCU/NMI-RCU.rst`)

.. _NMI_rcu_doc:

Using RCU to Protect Dynamic NMI Handlers
=========================================


Although RCU is usually used to protect read-mostly data structures,
it is possible to use RCU to provide dynamic non-maskable interrupt
handlers, as well as dynamic irq handlers.  This document describes
how to do this, drawing loosely from Zwane Mwaikambo's NMI-timer
work in an old version of "arch/x86/kernel/traps.c".

The relevant pieces of code are listed below, each followed by a
brief explanation::

	static int dummy_nmi_callback(struct pt_regs *regs, int cpu)
	{
		return 0;
	}

The dummy_nmi_callback() function is a "dummy" NMI handler that does
nothing, but returns zero, thus saying that it did nothing, allowing
the NMI handler to take the default machine-specific action::

	static nmi_callback_t nmi_callback = dummy_nmi_callback;

This nmi_callback variable is a global function pointer to the current
NMI handler::

	void do_nmi(struct pt_regs * regs, long error_code)
	{
		int cpu;

		nmi_enter();

		cpu = smp_processor_id();
		++nmi_count(cpu);

		if (!rcu_dereference_sched(nmi_callback)(regs, cpu))
			default_do_nmi(regs);

		nmi_exit();
	}

The do_nmi() function processes each NMI.  It first disables preemption
in the same way that a hardware irq would, then increments the per-CPU
count of NMIs.  It then invokes the NMI handler stored in the nmi_callback
function pointer.  If this handler returns zero, do_nmi() invokes the
default_do_nmi() function to handle a machine-specific NMI.  Finally,
preemption is restored.

In theory, rcu_dereference_sched() is not needed, since this code runs
only on i386, which in theory does not need rcu_dereference_sched()
anyway.  However, in practice it is a good documentation aid, particularly
for anyone attempting to do something similar on Alpha or on systems
with aggressive optimizing compilers.

Quick Quiz:
		Why might the rcu_dereference_sched() be necessary on Alpha, given that the code referenced by the pointer is read-only?

:ref:`Answer to Quick Quiz <answer_quick_quiz_NMI>`

Back to the discussion of NMI and RCU::

	void set_nmi_callback(nmi_callback_t callback)
	{
		rcu_assign_pointer(nmi_callback, callback);
	}

The set_nmi_callback() function registers an NMI handler.  Note that any
data that is to be used by the callback must be initialized up -before-
the call to set_nmi_callback().  On architectures that do not order
writes, the rcu_assign_pointer() ensures that the NMI handler sees the
initialized values::

	void unset_nmi_callback(void)
	{
		rcu_assign_pointer(nmi_callback, dummy_nmi_callback);
	}

This function unregisters an NMI handler, restoring the original
dummy_nmi_handler().  However, there may well be an NMI handler
currently executing on some other CPU.  We therefore cannot free
up any data structures used by the old NMI handler until execution
of it completes on all other CPUs.

One way to accomplish this is via synchronize_rcu(), perhaps as
follows::

	unset_nmi_callback();
	synchronize_rcu();
	kfree(my_nmi_data);

This works because (as of v4.20) synchronize_rcu() blocks until all
CPUs complete any preemption-disabled segments of code that they were
executing.
Since NMI handlers disable preemption, synchronize_rcu() is guaranteed
not to return until all ongoing NMI handlers exit.  It is therefore safe
to free up the handler's data as soon as synchronize_rcu() returns.

Important note: for this to work, the architecture in question must
invoke nmi_enter() and nmi_exit() on NMI entry and exit, respectively.

.. _answer_quick_quiz_NMI:

Answer to Quick Quiz:
	Why might the rcu_dereference_sched() be necessary on Alpha, given that the code referenced by the pointer is read-only?

	The caller to set_nmi_callback() might well have
	initialized some data that is to be used by the new NMI
	handler.  In this case, the rcu_dereference_sched() would
	be needed, because otherwise a CPU that received an NMI
	just after the new handler was set might see the pointer
	to the new NMI handler, but the old pre-initialized
	version of the handler's data.

	This same sad story can happen on other CPUs when using
	a compiler with aggressive pointer-value speculation
	optimizations.  (But please don't!)

	More important, the rcu_dereference_sched() makes it
	clear to someone reading the code that the pointer is
	being protected by RCU-sched.

---

### Documentation RCU RTFP (`Documentation/RCU/RTFP.txt`)

Read the F-ing Papers!


This document describes RCU-related publications, and is followed by
the corresponding bibtex entries.  A number of the publications may
be found at http://www.rdrop.com/users/paulmck/RCU/.

The first thing resembling RCU was published in 1980, when Kung and Lehman
[Kung80] recommended use of a garbage collector to defer destruction
of nodes in a parallel binary search tree in order to simplify its
implementation.  This works well in environments that have garbage
collectors, but most production garbage collectors incur significant
overhead.

In 1982, Manber and Ladner [Manber82,Manber84] recommended deferring
destruction until all threads running at that time have terminated, again
for a parallel binary search tree.  This approach works well in systems
with short-lived threads, such as the K42 research operating system.
However, Linux has long-lived tasks, so more is needed.

In 1986, Hennessy, Osisek, and Seigh [Hennessy89] introduced passive
serialization, which is an RCU-like mechanism that relies on the presence
of "quiescent states" in the VM/XA hypervisor that are guaranteed not
to be referencing the data structure.  However, this mechanism was not
optimized for modern computer systems, which is not surprising given
that these overheads were not so expensive in the mid-80s.  Nonetheless,
passive serialization appears to be the first deferred-destruction
mechanism to be used in production.  Furthermore, the relevant patent
has lapsed, so this approach may be used in non-GPL software, if desired.
(In contrast, implementation of RCU is permitted only in software licensed
under either GPL or LGPL.  Sorry!!!)

In 1990, Pugh [Pugh90] noted that explicitly tracking which threads
were reading a given data structure permitted deferred free to operate
in the presence of non-terminating threads.  However, this explicit
tracking imposes significant read-side overhead, which is undesirable
in read-mostly situations.  This algorithm does take pains to avoid
write-side contention and parallelize the other write-side overheads by
providing a fine-grained locking design, however, it would be interesting
to see how much of the performance advantage reported in 1990 remains
in 2004.

At about this same time, Adams [Adams91] described ``chaotic relaxation'',
where the normal barriers between successive iterations of convergent
numerical algorithms are relaxed, so that iteration $n$ might use
data from iteration $n-1$ or even $n-2$.  This introduces error,
which typically slows convergence and thus increases the number of
iterations required.  However, this increase is sometimes more than made
up for by a reduction in the number of expensive barrier operations,
which are otherwise required to synchronize the threads at the end
of each iteration.  Unfortunately, chaotic relaxation requires highly
structured data, such as the matrices used in scientific programs, and
is thus inapplicable to most data structures in operating-system kernels.

In 1992, Henry (now Alexia) Massalin completed a dissertation advising
parallel programmers to defer processing when feasible to simplify
synchronization.  RCU makes extremely heavy use of this advice.

In 1993, Jacobson [Jacobson93] verbally described what is perhaps the
simplest deferred-free technique: simply waiting a fixed amount of time
before freeing blocks awaiting deferred free.  Jacobson did not describe
any write-side changes he might have made in this work using SGI's Irix
kernel.  Aju John published a similar technique in 1995 [AjuJohn95].
This works well if there is a well-defined upper bound on the length of
time that reading threads can hold references, as there might well be in
hard real-time systems.  However, if this time is exceeded, perhaps due
to preemption, excessive interrupts, or larger-than-anticipated load,
memory corruption can ensue, with no reasonable means of diagnosis.
Jacobson's technique is therefore inappropriate for use in production
operating-system kernels, except when such kernels can provide hard
real-time response guarantees for all operations.

Also in 1995, Pu et al. [Pu95a] applied a technique similar to that of Pugh's
read-side-tracking to permit replugging of algorithms within a commercial
Unix operating system.  However, this replugging permitted only a single
reader at a time.  The following year, this same group of researchers
extended their technique to allow for multiple readers [Cowan96a].
Their approach requires memory barriers (and thus pipeline stalls),
but reduces memory latency, contention, and locking overheads.

1995 also saw the first publication of DYNIX/ptx's RCU mechanism
[Slingwine95], which was optimized for modern CPU architectures,
and was successfully applied to a number of situations within the
DYNIX/ptx kernel.  The corresponding conference paper appeared in 1998
[McKenney98].

In 1999, the Tornado and K42 groups described their "generations"
mechanism, which quite similar to RCU [Gamsa99].  These operating systems
made pervasive use of RCU in place of "existence locks", which greatly
simplifies locking hierarchies.

2001 saw the first RCU presentation involving Linux [McKenney01a]
at OLS.  The resulting abundance of RCU patches was presented the
following year [McKenney02a], and use of RCU in dcache was first
described that same year [Linder02a].

Also in 2002, Michael [Michael02b,Michael02a] presented "hazard-pointer"
techniques that defer the destruction of data structures to simplify
non-blocking synchronization (wait-free synchronization, lock-free
synchronization, and obstruction-free synchronization are all examples of
non-blocking synchronization).  In particular, this technique eliminates
locking, reduces contention, reduces memory latency for readers, and
parallelizes pipeline stalls and memory latency for writers.  However,
these techniques still impose significant read-side overhead in the
form of memory barriers.  Researchers at Sun worked along similar lines
in the same timeframe [HerlihyLM02].  These techniques can be thought
of as inside-out reference counts, where the count is represented by the
number of hazard pointers referencing a given data structure (rather than
the more conventional counter field within the data structure itself).

By the same token, RCU can be thought of as a "bulk reference count",
where some form of reference counter covers all reference by a given CPU
or thread during a set timeframe.  This timeframe is related to, but
not necessarily exactly the same as, an RCU grace period.  In classic
RCU, the reference counter is the per-CPU bit in the "bitmask" field,
and each such bit covers all references that might have been made by
the corresponding CPU during the prior grace period.  Of course, RCU
can be thought of in other terms as well.

In 2003, the K42 group described how RCU could be used to create
hot-pluggable implementations of operating-system functions [Appavoo03a].
Later that year saw a paper describing an RCU implementation of System
V IPC [Arcangeli03], and an introduction to RCU in Linux Journal
[McKenney03a].

2004 has seen a Linux-Journal article on use of RCU in dcache
[McKenney04a], a performance comparison of locking to RCU on several
different CPUs [McKenney04b], a dissertation describing use of RCU in a
number of operating-system kernels [PaulEdwardMcKenneyPhD], a paper
describing how to make RCU safe for soft-realtime applications [Sarma04c],
and a paper describing SELinux performance with RCU [JamesMorris04b].

2005 brought further adaptation of RCU to realtime use, permitting
preemption of RCU realtime critical sections [PaulMcKenney05a,
PaulMcKenney05b].

2006 saw the first best-paper award for an RCU paper [ThomasEHart2006a],
as well as further work on efficient implementations of preemptible
RCU [PaulEMcKenney2006b], but priority-boosting of RCU read-side critical
sections proved elusive.  An RCU implementation permitting general
blocking in read-side critical sections appeared [PaulEMcKenney2006c],
Robert Olsson described an RCU-protected trie-hash combination
[RobertOlsson2006a].

2007 saw the journal version of the award-winning RCU paper from 2006
[ThomasEHart2007a], as well as a paper demonstrating use of Promela
and Spin to mechanically verify an optimization to Oleg Nesterov's
QRCU [PaulEMcKenney2007QRCUspin], a design document describing
preemptible RCU [PaulEMcKenney2007PreemptibleRCU], and the three-part
LWN "What is RCU?" series [PaulEMcKenney2007WhatIsRCUFundamentally,
PaulEMcKenney2008WhatIsRCUUsage, and PaulEMcKenney2008WhatIsRCUAPI].

2008 saw a journal paper on real-time RCU [DinakarGuniguntala2008IBMSysJ],
a history of how Linux changed RCU more than RCU changed Linux
[PaulEMcKenney2008RCUOSR], and a design overview of hierarchical RCU
[PaulEMcKenney2008HierarchicalRCU].

2009 introduced user-level RCU algorithms [PaulEMcKenney2009MaliciousURCU],
which Mathieu Desnoyers is now maintaining [MathieuDesnoyers2009URCU]
[MathieuDesnoyersPhD].  TINY_RCU [PaulEMcKenney2009BloatWatchRCU] made
its appearance, as did expedited RCU [PaulEMcKenney2009expeditedRCU].
The problem of resizeable RCU-protected hash tables may now be on a path
to a solution [JoshTriplett2009RPHash].

Bibtex Entries

@article{Kung80
,author="H. T. Kung and Q. Lehman"
,title="Concurrent Maintenance of Binary Search Trees"
,Year="1980"
,Month="September"
,journal="ACM Transactions on Database Systems"
,volume="5"
,number="3"
,pages="354-382"
}

@techreport{Manber82
,author="Udi Manber and Richard E. Ladner"
,title="Concurrency Control in a Dynamic Search Structure"
,institution="Department of Computer Science, University of Washington"
,address="Seattle, Washington"
,year="1982"
,number="82-01-01"
,month="January"
,pages="28"
}

@article{Manber84
,author="Udi Manber and Richard E. Ladner"
,title="Concurrency Control in a Dynamic Search Structure"
,Year="1984"
,Month="September"
,journal="ACM Transactions on Database Systems"
,volume="9"
,number="3"
,pages="439-455"
}

@techreport{Hennessy89
,author="James P. Hennessy and Damian L. Osisek and Joseph W. {Seigh II}"
,title="Passive Serialization in a Multitasking Environment"
,institution="US Patent and Trademark Office"
,address="Washington, DC"
,year="1989"
,number="US Patent 4,809,168 (lapsed)"
,month="February"
,pages="11"
}

@techreport{Pugh90
,author="William Pugh"
,title="Concurrent Maintenance of Skip Lists"
,institution="Institute of Advanced Computer Science Studies, Department of Computer Science, University of Maryland"
,address="College Park, Maryland"
,year="1990"
,number="CS-TR-2222.1"
,month="June"
}

@Book{Adams91
,Author="Gregory R. Adams"
,title="Concurrent Programming, Principles, and Practices"
,Publisher="Benjamin Cummins"
,Year="1991"
}

@phdthesis{HMassalinPhD
,author="H. Massalin"
,title="Synthesis: An Efficient Implementation of Fundamental Operating
System Services"
,school="Columbia University"
,address="New York, NY"
,year="1992"
,annotation="
	Mondo optimizing compiler.
	Wait-free stuff.
	Good advice: defer work to avoid synchronization.
"
}

@unpublished{Jacobson93
,author="Van Jacobson"
,title="Avoid Read-Side Locking Via Delayed Free"
,year="1993"
,month="September"
,note="Verbal discussion"
}

@Conference{AjuJohn95
,Author="Aju John"
,Title="Dynamic vnodes -- Design and Implementation"
,Booktitle="{USENIX Winter 1995}"
,Publisher="USENIX Association"
,Month="January"
,Year="1995"
,pages="11-23"
,Address="New Orleans, LA"
}

@conference{Pu95a,
Author = "Calton Pu and Tito Autrey and Andrew Black and Charles Consel and
Crispin Cowan and Jon Inouye and Lakshmi Kethana and Jonathan Walpole and
Ke Zhang",
Title = "Optimistic Incremental Specialization: Streamlining a Commercial
Operating System",
Booktitle = "15\textsuperscript{th} ACM Symposium on
Operating Systems Principles (SOSP'95)",
address = "Copper Mountain, CO",
month="December",
year="1995",
pages="314-321",
annotation="
	Uses a replugger, but with a flag to signal when people are
	using the resource at hand.  Only one reader at a time.
"
}

@conference{Cowan96a,
Author = "Crispin Cowan and Tito Autrey and Charles Krasic and
Calton Pu and Jonathan Walpole",
Title = "Fast Concurrent Dynamic Linking for an Adaptive Operating System",
Booktitle = "International Conference on Configurable Distributed Systems
(ICCDS'96)",
address = "Annapolis, MD",
month="May",
year="1996",
pages="108",
isbn="0-8186-7395-8",
annotation="
	Uses a replugger, but with a counter to signal when people are
	using the resource at hand.  Allows multiple readers.
"
}

@techreport{Slingwine95
,author="John D. Slingwine and Paul E. McKenney"
,title="Apparatus and Method for Achieving Reduced Overhead Mutual
Exclusion and Maintaining Coherency in a Multiprocessor System
Utilizing Execution History and Thread Monitoring"
,institution="US Patent and Trademark Office"
,address="Washington, DC"
,year="1995"
,number="US Patent 5,442,758 (contributed under GPL)"
,month="August"
}

@techreport{Slingwine97
,author="John D. Slingwine and Paul E. McKenney"
,title="Method for maintaining data coherency using thread
activity summaries in a multicomputer system"
,institution="US Patent and Trademark Office"
,address="Washington, DC"
,year="1997"
,number="US Patent 5,608,893 (contributed under GPL)"
,month="March"
}

@techreport{Slingwine98
,author="John D. Slingwine and Paul E. McKenney"
,title="Apparatus and method for achieving reduced overhead
mutual exclusion and maintaining coherency in a multiprocessor
system utilizing execution history and thread monitoring"
,institution="US Patent and Trademark Office"
,address="Washington, DC"
,year="1998"
,number="US Patent 5,727,209 (contributed under GPL)"
,month="March"
}

@Conference{McKenney98
,Author="Paul E. McKenney and John D. Slingwine"
,Title="Read-Copy Update: Using Execution History to Solve Concurrency
Problems"
,Booktitle="{Parallel and Distributed Computing and Systems}"
,Month="October"
,Year="1998"
,pages="509-518"
,Address="Las Vegas, NV"
}

@Conference{Gamsa99
,Author="Ben Gamsa and Orran Krieger and Jonathan Appavoo and Michael Stumm"
,Title="Tornado: Maximizing Locality and Concurrency in a Shared Memory
Multiprocessor Operating System"
,Booktitle="{Proceedings of the 3\textsuperscript{rd} Symposium on
Operating System Design and Implementation}"
,Month="February"
,Year="1999"
,pages="87-100"
,Address="New Orleans, LA"
}

@techreport{Slingwine01
,author="John D. Slingwine and Paul E. McKenney"
,title="Apparatus and method for achieving reduced overhead
mutual exclusion and maintaining coherency in a multiprocessor
system utilizing execution history and thread monitoring"
,institution="US Patent and Trademark Office"
,address="Washington, DC"
,year="2001"
,number="US Patent 5,219,690 (contributed under GPL)"
,month="April"
}

@Conference{McKenney01a
,Author="Paul E. McKenney and Jonathan Appavoo and Andi Kleen and
Orran Krieger and Rusty Russell and Dipankar Sarma and Maneesh Soni"
,Title="Read-Copy Update"
,Booktitle="{Ottawa Linux Symposium}"
,Month="July"
,Year="2001"
,note="Available:
\url{http://www.linuxsymposium.org/2001/abstracts/readcopy.php}
\url{http://www.rdrop.com/users/paulmck/rclock/rclock_OLS.2001.05.01c.pdf}
[Viewed June 23, 2004]"
annotation="
Described RCU, and presented some patches implementing and using it in
the Linux kernel.
"
}

@Conference{Linder02a
,Author="Hanna Linder and Dipankar Sarma and Maneesh Soni"
,Title="Scalability of the Directory Entry Cache"
,Booktitle="{Ottawa Linux Symposium}"
,Month="June"
,Year="2002"
,pages="289-300"
}

@Conference{McKenney02a
,Author="Paul E. McKenney and Dipankar Sarma and
Andrea Arcangeli and Andi Kleen and Orran Krieger and Rusty Russell"
,Title="Read-Copy Update"
,Booktitle="{Ottawa Linux Symposium}"
,Month="June"
,Year="2002"
,pages="338-367"
,note="Available:
\url{http://www.linux.org.uk/~ajh/ols2002_proceedings.pdf.gz}
[Viewed June 23, 2004]"
}

@conference{Michael02a
,author="Maged M. Michael"
,title="Safe Memory Reclamation for Dynamic Lock-Free Objects Using Atomic
Reads and Writes"
,Year="2002"
,Month="August"
,booktitle="{Proceedings of the 21\textsuperscript{st} Annual ACM
Symposium on Principles of Distributed Computing}"
,pages="21-30"
,annotation="
	Each thread keeps an array of pointers to items that it is
	currently referencing.	Sort of an inside-out garbage collection
	mechanism, but one that requires the accessing code to explicitly
	state its needs.  Also requires read-side memory barriers on
	most architectures.
"
}

@conference{Michael02b
,author="Maged M. Michael"
,title="High Performance Dynamic Lock-Free Hash Tables and List-Based Sets"
,Year="2002"
,Month="August"
,booktitle="{Proceedings of the 14\textsuperscript{th} Annual ACM
Symposium on Parallel
Algorithms and Architecture}"
,pages="73-82"
,annotation="
	Like the title says...
"
}

@InProceedings{HerlihyLM02
,author={Maurice Herlihy and Victor Luchangco and Mark Moir}
,title="The Repeat Offender Problem: A Mechanism for Supporting Dynamic-Sized,
Lock-Free Data Structures"
,booktitle={Proceedings of 16\textsuperscript{th} International
Symposium on Distributed Computing}
,year=2002
,month="October"
,pages="339-353"
}

@article{Appavoo03a
,author="J. Appavoo and K. Hui and C. A. N. Soules and R. W. Wisniewski and
D. M. {Da Silva} and O. Krieger and M. A. Auslander and D. J. Edelsohn and
B. Gamsa and G. R. Ganger and P. McKenney and M. Ostrowski and
B. Rosenburg and M. Stumm and J. Xenidis"
,title="Enabling Autonomic Behavior in Systems Software With Hot Swapping"
,Year="2003"
,Month="January"
,journal="IBM Systems Journal"
,volume="42"
,number="1"
,pages="60-76"
}

@Conference{Arcangeli03
,Author="Andrea Arcangeli and Mingming Cao and Paul E. McKenney and
Dipankar Sarma"
,Title="Using Read-Copy Update Techniques for {System V IPC} in the
{Linux} 2.5 Kernel"
,Booktitle="Proceedings of the 2003 USENIX Annual Technical Conference
(FREENIX Track)"
,Publisher="USENIX Association"
,year="2003"
,month="June"
,pages="297-310"
}

@article{McKenney03a
,author="Paul E. McKenney"
,title="Using {RCU} in the {Linux} 2.5 Kernel"
,Year="2003"
,Month="October"
,journal="Linux Journal"
,volume="1"
,number="114"
,pages="18-26"
}

@techreport{Friedberg03a
,author="Stuart A. Friedberg"
,title="Lock-Free Wild Card Search Data Structure and Method"
,institution="US Patent and Trademark Office"
,address="Washington, DC"
,year="2003"
,number="US Patent 6,662,184 (contributed under GPL)"
,month="December"
,pages="112"
}

@article{McKenney04a
,author="Paul E. McKenney and Dipankar Sarma and Maneesh Soni"
,title="Scaling dcache with {RCU}"
,Year="2004"
,Month="January"
,journal="Linux Journal"
,volume="1"
,number="118"
,pages="38-46"
}

@Conference{McKenney04b
,Author="Paul E. McKenney"
,Title="{RCU} vs. Locking Performance on Different {CPUs}"
,Booktitle="{linux.conf.au}"
,Month="January"
,Year="2004"
,Address="Adelaide, Australia"
,note="Available:
\url{http://www.linux.org.au/conf/2004/abstracts.html#90}
\url{http://www.rdrop.com/users/paulmck/rclock/lockperf.2004.01.17a.pdf}
[Viewed June 23, 2004]"
}

@phdthesis{PaulEdwardMcKenneyPhD
,author="Paul E. McKenney"
,title="Exploiting Deferred Destruction:
An Analysis of Read-Copy-Update Techniques
in Operating System Kernels"
,school="OGI School of Science and Engineering at
Oregon Health and Sciences University"
,year="2004"
,note="Available:
\url{http://www.rdrop.com/users/paulmck/RCU/RCUdissertation.2004.07.14e1.pdf}
[Viewed October 15, 2004]"
}

@Conference{Sarma04c
,Author="Dipankar Sarma and Paul E. McKenney"
,Title="Making RCU Safe for Deep Sub-Millisecond Response Realtime Applications"
,Booktitle="Proceedings of the 2004 USENIX Annual Technical Conference
(FREENIX Track)"
,Publisher="USENIX Association"
,year="2004"
,month="June"
,pages="182-191"
}

@unpublished{JamesMorris04b
,Author="James Morris"
,Title="Recent Developments in {SELinux} Kernel Performance"
,month="December"
,year="2004"
,note="Available:
\url{http://www.livejournal.com/users/james_morris/2153.html}
[Viewed December 10, 2004]"
}

@unpublished{PaulMcKenney05a
,Author="Paul E. McKenney"
,Title="{[RFC]} {RCU} and {CONFIG\_PREEMPT\_RT} progress"
,month="May"
,year="2005"
,note="Available:
\url{http://lkml.org/lkml/2005/5/9/185}
[Viewed May 13, 2005]"
,annotation="
	First publication of working lock-based deferred free patches
	for the CONFIG_PREEMPT_RT environment.
"
}

@conference{PaulMcKenney05b
,Author="Paul E. McKenney and Dipankar Sarma"
,Title="Towards Hard Realtime Response from the Linux Kernel on SMP Hardware"
,Booktitle="linux.conf.au 2005"
,month="April"
,year="2005"
,address="Canberra, Australia"
,note="Available:
\url{http://www.rdrop.com/users/paulmck/RCU/realtimeRCU.2005.04.23a.pdf}
[Viewed May 13, 2005]"
,annotation="
	Realtime turns into making RCU yet more realtime friendly.
"
}

@conference{ThomasEHart2006a
,Author="Thomas E. Hart and Paul E. McKenney and Angela Demke Brown"
,Title="Making Lockless Synchronization Fast: Performance Implications
of Memory Reclamation"
,Booktitle="20\textsuperscript{th} {IEEE} International Parallel and
Distributed Processing Symposium"
,month="April"
,year="2006"
,day="25-29"
,address="Rhodes, Greece"
,annotation="
	Compares QSBR (AKA "classic RCU"), HPBR, EBR, and lock-free
	reference counting.
"
}

@Conference{PaulEMcKenney2006b
,Author="Paul E. McKenney and Dipankar Sarma and Ingo Molnar and
Suparna Bhattacharya"
,Title="Extending RCU for Realtime and Embedded Workloads"
,Booktitle="{Ottawa Linux Symposium}"
,Month="July"
,Year="2006"
,pages="v2 123-138"
,note="Available:
\url{http://www.linuxsymposium.org/2006/index_2006.php}
\url{http://www.rdrop.com/users/paulmck/RCU/OLSrtRCU.2006.08.11a.pdf}
[Viewed January 1, 2007]"
,annotation="
	Described how to improve the -rt implementation of realtime RCU.
"
}

@unpublished{PaulEMcKenney2006c
,Author="Paul E. McKenney"
,Title="Sleepable {RCU}"
,month="October"
,day="9"
,year="2006"
,note="Available:
\url{http://lwn.net/Articles/202847/}
Revised:
\url{http://www.rdrop.com/users/paulmck/RCU/srcu.2007.01.14a.pdf}
[Viewed August 21, 2006]"
,annotation="
	LWN article introducing SRCU.
"
}

@unpublished{RobertOlsson2006a
,Author="Robert Olsson and Stefan Nilsson"
,Title="{TRASH}: A dynamic {LC}-trie and hash data structure"
,month="August"
,day="18"
,year="2006"
,note="Available:
\url{http://www.nada.kth.se/~snilsson/public/papers/trash/trash.pdf}
[Viewed February 24, 2007]"
,annotation="
	RCU-protected dynamic trie-hash combination.
"
}

@unpublished{ThomasEHart2007a
,Author="Thomas E. Hart and Paul E. McKenney and Angela Demke Brown and Jonathan Walpole"
,Title="Performance of memory reclamation for lockless synchronization"
,journal="J. Parallel Distrib. Comput."
,year="2007"
,note="To appear in J. Parallel Distrib. Comput.
       \url{doi=10.1016/j.jpdc.2007.04.010}"
,annotation={
	Compares QSBR (AKA "classic RCU"), HPBR, EBR, and lock-free
	reference counting.  Journal version of ThomasEHart2006a.
}
}

@unpublished{PaulEMcKenney2007QRCUspin
,Author="Paul E. McKenney"
,Title="Using Promela and Spin to verify parallel algorithms"
,month="August"
,day="1"
,year="2007"
,note="Available:
\url{http://lwn.net/Articles/243851/}
[Viewed September 8, 2007]"
,annotation="
	LWN article describing Promela and spin, and also using Oleg
	Nesterov's QRCU as an example (with Paul McKenney's fastpath).
"
}

@unpublished{PaulEMcKenney2007PreemptibleRCU
,Author="Paul E. McKenney"
,Title="The design of preemptible read-copy-update"
,month="October"
,day="8"
,year="2007"
,note="Available:
\url{http://lwn.net/Articles/253651/}
[Viewed October 25, 2007]"
,annotation="
	LWN article describing the design of preemptible RCU.
"
}

########################################################################
#
#	"What is RCU?" LWN series.
#

@unpublished{PaulEMcKenney2007WhatIsRCUFundamentally
,Author="Paul E. McKenney and Jonathan Walpole"
,Title="What is {RCU}, Fundamentally?"
,month="December"
,day="17"
,year="2007"
,note="Available:
\url{http://lwn.net/Articles/262464/}
[Viewed December 27, 2007]"
,annotation="
	Lays out the three basic components of RCU: (1) publish-subscribe,
	(2) wait for pre-existing readers to complete, and (2) maintain
	multiple versions.
"
}

@unpublished{PaulEMcKenney2008WhatIsRCUUsage
,Author="Paul E. McKenney"
,Title="What is {RCU}? Part 2: Usage"
,month="January"
,day="4"
,year="2008"
,note="Available:
\url{http://lwn.net/Articles/263130/}
[Viewed January 4, 2008]"
,annotation="
	Lays out six uses of RCU:
	1. RCU is a Reader-Writer Lock Replacement
	2. RCU is a Restricted Reference-Counting Mechanism
	3. RCU is a Bulk Reference-Counting Mechanism
	4. RCU is a Poor Man's Garbage Collector
	5. RCU is a Way of Providing Existence Guarantees
	6. RCU is a Way of Waiting for Things to Finish 
"
}

@unpublished{PaulEMcKenney2008WhatIsRCUAPI
,Author="Paul E. McKenney"
,Title="{RCU} part 3: the {RCU} {API}"
,month="January"
,day="17"
,year="2008"
,note="Available:
\url{http://lwn.net/Articles/264090/}
[Viewed January 10, 2008]"
,annotation="
	Gives an overview of the Linux-kernel RCU API and a brief annotated RCU
	bibliography.
"
}

#
#	"What is RCU?" LWN series.
#
########################################################################

@article{DinakarGuniguntala2008IBMSysJ
,author="D. Guniguntala and P. E. McKenney and J. Triplett and J. Walpole"
,title="The read-copy-update mechanism for supporting real-time applications on shared-memory multiprocessor systems with {Linux}"
,Year="2008"
,Month="April"
,journal="IBM Systems Journal"
,volume="47"
,number="2"
,pages="@@-@@"
,annotation="
	RCU, realtime RCU, sleepable RCU, performance.
"
}

@article{PaulEMcKenney2008RCUOSR
,author="Paul E. McKenney and Jonathan Walpole"
,title="Introducing technology into the {Linux} kernel: a case study"
,Year="2008"
,journal="SIGOPS Oper. Syst. Rev."
,volume="42"
,number="5"
,pages="4--17"
,issn="0163-5980"
,doi={http://doi.acm.org/10.1145/1400097.1400099}
,publisher="ACM"
,address="New York, NY, USA"
,annotation={
	Linux changed RCU to a far greater degree than RCU has changed Linux.
}
}

@unpublished{PaulEMcKenney2008HierarchicalRCU
,Author="Paul E. McKenney"
,Title="Hierarchical {RCU}"
,month="November"
,day="3"
,year="2008"
,note="Available:
\url{http://lwn.net/Articles/305782/}
[Viewed November 6, 2008]"
,annotation="
	RCU with combining-tree-based grace-period detection,
	permitting it to handle thousands of CPUs.
"
}

@conference{PaulEMcKenney2009MaliciousURCU
,Author="Paul E. McKenney"
,Title="Using a Malicious User-Level {RCU} to Torture {RCU}-Based Algorithms"
,Booktitle="linux.conf.au 2009"
,month="January"
,year="2009"
,address="Hobart, Australia"
,note="Available:
\url{http://www.rdrop.com/users/paulmck/RCU/urcutorture.2009.01.22a.pdf}
[Viewed February 2, 2009]"
,annotation="
	Realtime RCU and torture-testing RCU uses.
"
}

@unpublished{MathieuDesnoyers2009URCU
,Author="Mathieu Desnoyers"
,Title="[{RFC} git tree] Userspace {RCU} (urcu) for {Linux}"
,month="February"
,day="5"
,year="2009"
,note="Available:
\url{http://lkml.org/lkml/2009/2/5/572}
\url{git://lttng.org/userspace-rcu.git}
[Viewed February 20, 2009]"
,annotation="
	Mathieu Desnoyers's user-space RCU implementation.
	git://lttng.org/userspace-rcu.git
"
}

@unpublished{PaulEMcKenney2009BloatWatchRCU
,Author="Paul E. McKenney"
,Title="{RCU}: The {Bloatwatch} Edition"
,month="March"
,day="17"
,year="2009"
,note="Available:
\url{http://lwn.net/Articles/323929/}
[Viewed March 20, 2009]"
,annotation="
	Uniprocessor assumptions allow simplified RCU implementation.
"
}

@unpublished{PaulEMcKenney2009expeditedRCU
,Author="Paul E. McKenney"
,Title="[{PATCH} -tip 0/3] expedited 'big hammer' {RCU} grace periods"
,month="June"
,day="25"
,year="2009"
,note="Available:
\url{http://lkml.org/lkml/2009/6/25/306}
[Viewed August 16, 2009]"
,annotation="
	First posting of expedited RCU to be accepted into -tip.
"
}

@unpublished{JoshTriplett2009RPHash
,Author="Josh Triplett"
,Title="Scalable concurrent hash tables via relativistic programming"
,month="September"
,year="2009"
,note="Linux Plumbers Conference presentation"
,annotation="
	RP fun with hash tables.
"
}

@phdthesis{MathieuDesnoyersPhD
, title  = "Low-Impact Operating System Tracing"
, author = "Mathieu Desnoyers"
, school = "Ecole Polytechnique de Montr\'{e}al"
, month  = "December"
, year   = 2009
,note="Available:
\url{http://www.lttng.org/pub/thesis/desnoyers-dissertation-2009-12.pdf}
[Viewed December 9, 2009]"
}

---

### Documentation RCU UP (`Documentation/RCU/UP.rst`)

.. _up_doc:

RCU on Uniprocessor Systems
===========================

A common misconception is that, on UP systems, the call_rcu() primitive
may immediately invoke its function.  The basis of this misconception
is that since there is only one CPU, it should not be necessary to
wait for anything else to get done, since there are no other CPUs for
anything else to be happening on.  Although this approach will *sort of*
work a surprising amount of the time, it is a very bad idea in general.
This document presents three examples that demonstrate exactly how bad
an idea this is.

Example 1: softirq Suicide
--------------------------

Suppose that an RCU-based algorithm scans a linked list containing
elements A, B, and C in process context, and can delete elements from
this same list in softirq context.  Suppose that the process-context scan
is referencing element B when it is interrupted by softirq processing,
which deletes element B, and then invokes call_rcu() to free element B
after a grace period.

Now, if call_rcu() were to directly invoke its arguments, then upon return
from softirq, the list scan would find itself referencing a newly freed
element B.  This situation can greatly decrease the life expectancy of
your kernel.

This same problem can occur if call_rcu() is invoked from a hardware
interrupt handler.

Example 2: Function-Call Fatality
---------------------------------

Of course, one could avert the suicide described in the preceding example
by having call_rcu() directly invoke its arguments only if it was called
from process context.  However, this can fail in a similar manner.

Suppose that an RCU-based algorithm again scans a linked list containing
elements A, B, and C in process context, but that it invokes a function
on each element as it is scanned.  Suppose further that this function
deletes element B from the list, then passes it to call_rcu() for deferred
freeing.  This may be a bit unconventional, but it is perfectly legal
RCU usage, since call_rcu() must wait for a grace period to elapse.
Therefore, in this case, allowing call_rcu() to immediately invoke
its arguments would cause it to fail to make the fundamental guarantee
underlying RCU, namely that call_rcu() defers invoking its arguments until
all RCU read-side critical sections currently executing have completed.

Quick Quiz #1:
	Why is it *not* legal to invoke synchronize_rcu() in this case?

:ref:`Answers to Quick Quiz <answer_quick_quiz_up>`

Example 3: Death by Deadlock
----------------------------

Suppose that call_rcu() is invoked while holding a lock, and that the
callback function must acquire this same lock.  In this case, if
call_rcu() were to directly invoke the callback, the result would
be self-deadlock *even if* this invocation occurred from a later
call_rcu() invocation a full grace period later.

In some cases, it would possible to restructure to code so that
the call_rcu() is delayed until after the lock is released.  However,
there are cases where this can be quite ugly:

1.	If a number of items need to be passed to call_rcu() within
	the same critical section, then the code would need to create
	a list of them, then traverse the list once the lock was
	released.

2.	In some cases, the lock will be held across some kernel API,
	so that delaying the call_rcu() until the lock is released
	requires that the data item be passed up via a common API.
	It is far better to guarantee that callbacks are invoked
	with no locks held than to have to modify such APIs to allow
	arbitrary data items to be passed back up through them.

If call_rcu() directly invokes the callback, painful locking restrictions
or API changes would be required.

Quick Quiz #2:
	What locking restriction must RCU callbacks respect?

:ref:`Answers to Quick Quiz <answer_quick_quiz_up>`

It is important to note that userspace RCU implementations *do*
permit call_rcu() to directly invoke callbacks, but only if a full
grace period has elapsed since those callbacks were queued.  This is
the case because some userspace environments are extremely constrained.
Nevertheless, people writing userspace RCU implementations are strongly
encouraged to avoid invoking callbacks from call_rcu(), thus obtaining
the deadlock-avoidance benefits called out above.

Summary
-------

Permitting call_rcu() to immediately invoke its arguments breaks RCU,
even on a UP system.  So do not do it!  Even on a UP system, the RCU
infrastructure *must* respect grace periods, and *must* invoke callbacks
from a known environment in which no locks are held.

Note that it *is* safe for synchronize_rcu() to return immediately on
UP systems, including PREEMPT SMP builds running on UP systems.

Quick Quiz #3:
	Why can't synchronize_rcu() return immediately on UP systems running
	preemptible RCU?

.. _answer_quick_quiz_up:

Answer to Quick Quiz #1:
	Why is it *not* legal to invoke synchronize_rcu() in this case?

	Because the calling function is scanning an RCU-protected linked
	list, and is therefore within an RCU read-side critical section.
	Therefore, the called function has been invoked within an RCU
	read-side critical section, and is not permitted to block.

Answer to Quick Quiz #2:
	What locking restriction must RCU callbacks respect?

	Any lock that is acquired within an RCU callback must be acquired
	elsewhere using an _bh variant of the spinlock primitive.
	For example, if "mylock" is acquired by an RCU callback, then
	a process-context acquisition of this lock must use something
	like spin_lock_bh() to acquire the lock.  Please note that
	it is also OK to use _irq variants of spinlocks, for example,
	spin_lock_irqsave().

	If the process-context code were to simply use spin_lock(),
	then, since RCU callbacks can be invoked from softirq context,
	the callback might be called from a softirq that interrupted
	the process-context critical section.  This would result in
	self-deadlock.

	This restriction might seem gratuitous, since very few RCU
	callbacks acquire locks directly.  However, a great many RCU
	callbacks do acquire locks *indirectly*, for example, via
	the kfree() primitive.

Answer to Quick Quiz #3:
	Why can't synchronize_rcu() return immediately on UP systems
	running preemptible RCU?

	Because some other task might have been preempted in the middle
	of an RCU read-side critical section.  If synchronize_rcu()
	simply immediately returned, it would prematurely signal the
	end of the grace period, which would come as a nasty shock to
	that other thread when it started running again.

---

### Documentation RCU Checklist (`Documentation/RCU/checklist.rst`)

.. SPDX-License-Identifier: GPL-2.0

================================
Review Checklist for RCU Patches
================================


This document contains a checklist for producing and reviewing patches
that make use of RCU.  Violating any of the rules listed below will
result in the same sorts of problems that leaving out a locking primitive
would cause.  This list is based on experiences reviewing such patches
over a rather long period of time, but improvements are always welcome!

0.	Is RCU being applied to a read-mostly situation?  If the data
	structure is updated more than about 10% of the time, then you
	should strongly consider some other approach, unless detailed
	performance measurements show that RCU is nonetheless the right
	tool for the job.  Yes, RCU does reduce read-side overhead by
	increasing write-side overhead, which is exactly why normal uses
	of RCU will do much more reading than updating.

	Another exception is where performance is not an issue, and RCU
	provides a simpler implementation.  An example of this situation
	is the dynamic NMI code in the Linux 2.6 kernel, at least on
	architectures where NMIs are rare.

	Yet another exception is where the low real-time latency of RCU's
	read-side primitives is critically important.

	One final exception is where RCU readers are used to prevent
	the ABA problem (https://en.wikipedia.org/wiki/ABA_problem)
	for lockless updates.  This does result in the mildly
	counter-intuitive situation where rcu_read_lock() and
	rcu_read_unlock() are used to protect updates, however, this
	approach can provide the same simplifications to certain types
	of lockless algorithms that garbage collectors do.

1.	Does the update code have proper mutual exclusion?

	RCU does allow *readers* to run (almost) naked, but *writers* must
	still use some sort of mutual exclusion, such as:

	a.	locking,
	b.	atomic operations, or
	c.	restricting updates to a single task.

	If you choose #b, be prepared to describe how you have handled
	memory barriers on weakly ordered machines (pretty much all of
	them -- even x86 allows later loads to be reordered to precede
	earlier stores), and be prepared to explain why this added
	complexity is worthwhile.  If you choose #c, be prepared to
	explain how this single task does not become a major bottleneck
	on large systems (for example, if the task is updating information
	relating to itself that other tasks can read, there by definition
	can be no bottleneck).	Note that the definition of "large" has
	changed significantly:	Eight CPUs was "large" in the year 2000,
	but a hundred CPUs was unremarkable in 2017.

2.	Do the RCU read-side critical sections make proper use of
	rcu_read_lock() and friends?  These primitives are needed
	to prevent grace periods from ending prematurely, which
	could result in data being unceremoniously freed out from
	under your read-side code, which can greatly increase the
	actuarial risk of your kernel.

	As a rough rule of thumb, any dereference of an RCU-protected
	pointer must be covered by rcu_read_lock(), rcu_read_lock_bh(),
	rcu_read_lock_sched(), or by the appropriate update-side lock.
	Explicit disabling of preemption (preempt_disable(), for example)
	can serve as rcu_read_lock_sched(), but is less readable and
	prevents lockdep from detecting locking issues.  Acquiring a
	raw spinlock also enters an RCU read-side critical section.

	The guard(rcu)() and scoped_guard(rcu) primitives designate
	the remainder of the current scope or the next statement,
	respectively, as the RCU read-side critical section.  Use of
	these guards can be less error-prone than rcu_read_lock(),
	rcu_read_unlock(), and friends.

	Please note that you *cannot* rely on code known to be built
	only in non-preemptible kernels.  Such code can and will break,
	especially in kernels built with CONFIG_PREEMPT_COUNT=y.

	Letting RCU-protected pointers "leak" out of an RCU read-side
	critical section is every bit as bad as letting them leak out
	from under a lock.  Unless, of course, you have arranged some
	other means of protection, such as a lock or a reference count
	*before* letting them out of the RCU read-side critical section.

3.	Does the update code tolerate concurrent accesses?

	The whole point of RCU is to permit readers to run without
	any locks or atomic operations.  This means that readers will
	be running while updates are in progress.  There are a number
	of ways to handle this concurrency, depending on the situation:

	a.	Use the RCU variants of the list and hlist update
		primitives to add, remove, and replace elements on
		an RCU-protected list.	Alternatively, use the other
		RCU-protected data structures that have been added to
		the Linux kernel.

		This is almost always the best approach.

	b.	Proceed as in (a) above, but also maintain per-element
		locks (that are acquired by both readers and writers)
		that guard per-element state.  Fields that the readers
		refrain from accessing can be guarded by some other lock
		acquired only by updaters, if desired.

		This also works quite well.

	c.	Make updates appear atomic to readers.	For example,
		pointer updates to properly aligned fields will
		appear atomic, as will individual atomic primitives.
		Sequences of operations performed under a lock will *not*
		appear to be atomic to RCU readers, nor will sequences
		of multiple atomic primitives.	One alternative is to
		move multiple individual fields to a separate structure,
		thus solving the multiple-field problem by imposing an
		additional level of indirection.

		This can work, but is starting to get a bit tricky.

	d.	Carefully order the updates and the reads so that readers
		see valid data at all phases of the update.  This is often
		more difficult than it sounds, especially given modern
		CPUs' tendency to reorder memory references.  One must
		usually liberally sprinkle memory-ordering operations
		through the code, making it difficult to understand and
		to test.  Where it works, it is better to use things
		like smp_store_release() and smp_load_acquire(), but in
		some cases the smp_mb() full memory barrier is required.

		As noted earlier, it is usually better to group the
		changing data into a separate structure, so that the
		change may be made to appear atomic by updating a pointer
		to reference a new structure containing updated values.

4.	Weakly ordered CPUs pose special challenges.  Almost all CPUs
	are weakly ordered -- even x86 CPUs allow later loads to be
	reordered to precede earlier stores.  RCU code must take all of
	the following measures to prevent memory-corruption problems:

	a.	Readers must maintain proper ordering of their memory
		accesses.  The rcu_dereference() primitive ensures that
		the CPU picks up the pointer before it picks up the data
		that the pointer points to.  This really is necessary
		on Alpha CPUs.

		The rcu_dereference() primitive is also an excellent
		documentation aid, letting the person reading the
		code know exactly which pointers are protected by RCU.
		Please note that compilers can also reorder code, and
		they are becoming increasingly aggressive about doing
		just that.  The rcu_dereference() primitive therefore also
		prevents destructive compiler optimizations.  However,
		with a bit of devious creativity, it is possible to
		mishandle the return value from rcu_dereference().
		Please see rcu_dereference.rst for more information.

		The rcu_dereference() primitive is used by the
		various "_rcu()" list-traversal primitives, such
		as the list_for_each_entry_rcu().  Note that it is
		perfectly legal (if redundant) for update-side code to
		use rcu_dereference() and the "_rcu()" list-traversal
		primitives.  This is particularly useful in code that
		is common to readers and updaters.  However, lockdep
		will complain if you access rcu_dereference() outside
		of an RCU read-side critical section.  See lockdep.rst
		to learn what to do about this.

		Of course, neither rcu_dereference() nor the "_rcu()"
		list-traversal primitives can substitute for a good
		concurrency design coordinating among multiple updaters.

	b.	If the list macros are being used, the list_add_tail_rcu()
		and list_add_rcu() primitives must be used in order
		to prevent weakly ordered machines from misordering
		structure initialization and pointer planting.
		Similarly, if the hlist macros are being used, the
		hlist_add_head_rcu() primitive is required.

	c.	If the list macros are being used, the list_del_rcu()
		primitive must be used to keep list_del()'s pointer
		poisoning from inflicting toxic effects on concurrent
		readers.  Similarly, if the hlist macros are being used,
		the hlist_del_rcu() primitive is required.

		The list_replace_rcu() and hlist_replace_rcu() primitives
		may be used to replace an old structure with a new one
		in their respective types of RCU-protected lists.

	d.	Rules similar to (4b) and (4c) apply to the "hlist_nulls"
		type of RCU-protected linked lists.

	e.	Updates must ensure that initialization of a given
		structure happens before pointers to that structure are
		publicized.  Use the rcu_assign_pointer() primitive
		when publicizing a pointer to a structure that can
		be traversed by an RCU read-side critical section.

5.	If any of call_rcu(), call_srcu(), call_rcu_tasks(), or
	call_rcu_tasks_trace() is used, the callback function may be
	invoked from softirq context, and in any case with bottom halves
	disabled.  In particular, this callback function cannot block.
	If you need the callback to block, run that code in a workqueue
	handler scheduled from the callback.  The queue_rcu_work()
	function does this for you in the case of call_rcu().

6.	Since synchronize_rcu() can block, it cannot be called
	from any sort of irq context.  The same rule applies
	for synchronize_srcu(), synchronize_rcu_expedited(),
	synchronize_srcu_expedited(), synchronize_rcu_tasks(),
	synchronize_rcu_tasks_rude(), and synchronize_rcu_tasks_trace().

	The expedited forms of these primitives have the same semantics
	as the non-expedited forms, but expediting is more CPU intensive.
	Use of the expedited primitives should be restricted to rare
	configuration-change operations that would not normally be
	undertaken while a real-time workload is running.  Note that
	IPI-sensitive real-time workloads can use the rcupdate.rcu_normal
	kernel boot parameter to completely disable expedited grace
	periods, though this might have performance implications.

	In particular, if you find yourself invoking one of the expedited
	primitives repeatedly in a loop, please do everyone a favor:
	Restructure your code so that it batches the updates, allowing
	a single non-expedited primitive to cover the entire batch.
	This will very likely be faster than the loop containing the
	expedited primitive, and will be much much easier on the rest
	of the system, especially to real-time workloads running on the
	rest of the system.  Alternatively, instead use asynchronous
	primitives such as call_rcu().

7.	As of v4.20, a given kernel implements only one RCU flavor, which
	is RCU-sched for PREEMPTION=n and RCU-preempt for PREEMPTION=y.
	If the updater uses call_rcu() or synchronize_rcu(), then
	the corresponding readers may use:  (1) rcu_read_lock() and
	rcu_read_unlock(), (2) any pair of primitives that disables
	and re-enables softirq, for example, rcu_read_lock_bh() and
	rcu_read_unlock_bh(), or (3) any pair of primitives that disables
	and re-enables preemption, for example, rcu_read_lock_sched() and
	rcu_read_unlock_sched().  If the updater uses synchronize_srcu()
	or call_srcu(), then the corresponding readers must use
	srcu_read_lock() and srcu_read_unlock(), and with the same
	srcu_struct.  The rules for the expedited RCU grace-period-wait
	primitives are the same as for their non-expedited counterparts.

	Similarly, it is necessary to correctly use the RCU Tasks flavors:

	a.	If the updater uses synchronize_rcu_tasks() or
		call_rcu_tasks(), then the readers must refrain from
		executing voluntary context switches, that is, from
		blocking.

	b.	If the updater uses call_rcu_tasks_trace()
		or synchronize_rcu_tasks_trace(), then the
		corresponding readers must use rcu_read_lock_trace()
		and rcu_read_unlock_trace().

	c.	If an updater uses synchronize_rcu_tasks_rude(),
		then the corresponding readers must use anything that
		disables preemption, for example, preempt_disable()
		and preempt_enable().

	Mixing things up will result in confusion and broken kernels, and
	has even resulted in an exploitable security issue.  Therefore,
	when using non-obvious pairs of primitives, commenting is
	of course a must.  One example of non-obvious pairing is
	the XDP feature in networking, which calls BPF programs from
	network-driver NAPI (softirq) context.	BPF relies heavily on RCU
	protection for its data structures, but because the BPF program
	invocation happens entirely within a single local_bh_disable()
	section in a NAPI poll cycle, this usage is safe.  The reason
	that this usage is safe is that readers can use anything that
	disables BH when updaters use call_rcu() or synchronize_rcu().

8.	Although synchronize_rcu() is slower than is call_rcu(),
	it usually results in simpler code.  So, unless update
	performance is critically important, the updaters cannot block,
	or the latency of synchronize_rcu() is visible from userspace,
	synchronize_rcu() should be used in preference to call_rcu().
	Furthermore, kfree_rcu() and kvfree_rcu() usually result
	in even simpler code than does synchronize_rcu() without
	synchronize_rcu()'s multi-millisecond latency.	So please take
	advantage of kfree_rcu()'s and kvfree_rcu()'s "fire and forget"
	memory-freeing capabilities where it applies.

	An especially important property of the synchronize_rcu()
	primitive is that it automatically self-limits: if grace periods
	are delayed for whatever reason, then the synchronize_rcu()
	primitive will correspondingly delay updates.  In contrast,
	code using call_rcu() should explicitly limit update rate in
	cases where grace periods are delayed, as failing to do so can
	result in excessive realtime latencies or even OOM conditions.

	Ways of gaining this self-limiting property when using call_rcu(),
	kfree_rcu(), or kvfree_rcu() include:

	a.	Keeping a count of the number of data-structure elements
		used by the RCU-protected data structure, including
		those waiting for a grace period to elapse.  Enforce a
		limit on this number, stalling updates as needed to allow
		previously deferred frees to complete.	Alternatively,
		limit only the number awaiting deferred free rather than
		the total number of elements.

		One way to stall the updates is to acquire the update-side
		mutex.	(Don't try this with a spinlock -- other CPUs
		spinning on the lock could prevent the grace period
		from ever ending.)  Another way to stall the updates
		is for the updates to use a wrapper function around
		the memory allocator, so that this wrapper function
		simulates OOM when there is too much memory awaiting an
		RCU grace period.  There are of course many other
		variations on this theme.

	b.	Limiting update rate.  For example, if updates occur only
		once per hour, then no explicit rate limiting is
		required, unless your system is already badly broken.
		Older versions of the dcache subsystem take this approach,
		guarding updates with a global lock, limiting their rate.

	c.	Trusted update -- if updates can only be done manually by
		superuser or some other trusted user, then it might not
		be necessary to automatically limit them.  The theory
		here is that superuser already has lots of ways to crash
		the machine.

	d.	Periodically invoke rcu_barrier(), permitting a limited
		number of updates per grace period.

	The same cautions apply to call_srcu(), call_rcu_tasks(), and
	call_rcu_tasks_trace().  This is why there is an srcu_barrier(),
	rcu_barrier_tasks(), and rcu_barrier_tasks_trace(), respectively.

	Note that although these primitives do take action to avoid
	memory exhaustion when any given CPU has too many callbacks,
	a determined user or administrator can still exhaust memory.
	This is especially the case if a system with a large number of
	CPUs has been configured to offload all of its RCU callbacks onto
	a single CPU, or if the system has relatively little free memory.

9.	All RCU list-traversal primitives, which include
	rcu_dereference(), list_for_each_entry_rcu(), and
	list_for_each_safe_rcu(), must be either within an RCU read-side
	critical section or must be protected by appropriate update-side
	locks.	RCU read-side critical sections are delimited by
	rcu_read_lock() and rcu_read_unlock(), or by similar primitives
	such as rcu_read_lock_bh() and rcu_read_unlock_bh(), in which
	case the matching rcu_dereference() primitive must be used in
	order to keep lockdep happy, in this case, rcu_dereference_bh().

	The reason that it is permissible to use RCU list-traversal
	primitives when the update-side lock is held is that doing so
	can be quite helpful in reducing code bloat when common code is
	shared between readers and updaters.  Additional primitives
	are provided for this case, as discussed in lockdep.rst.

	One exception to this rule is when data is only ever added to
	the linked data structure, and is never removed during any
	time that readers might be accessing that structure.  In such
	cases, READ_ONCE() may be used in place of rcu_dereference()
	and the read-side markers (rcu_read_lock() and rcu_read_unlock(),
	for example) may be omitted.

10.	Conversely, if you are in an RCU read-side critical section,
	and you don't hold the appropriate update-side lock, you *must*
	use the "_rcu()" variants of the list macros.  Failing to do so
	will break Alpha, cause aggressive compilers to generate bad code,
	and confuse people trying to understand your code.

11.	Any lock acquired by an RCU callback must be acquired elsewhere
	with softirq disabled, e.g., via spin_lock_bh().  Failing to
	disable softirq on a given acquisition of that lock will result
	in deadlock as soon as the RCU softirq handler happens to run
	your RCU callback while interrupting that acquisition's critical
	section.

12.	RCU callbacks can be and are executed in parallel.  In many cases,
	the callback code simply wrappers around kfree(), so that this
	is not an issue (or, more accurately, to the extent that it is
	an issue, the memory-allocator locking handles it).  However,
	if the callbacks do manipulate a shared data structure, they
	must use whatever locking or other synchronization is required
	to safely access and/or modify that data structure.

	Do not assume that RCU callbacks will be executed on the same
	CPU that executed the corresponding call_rcu(), call_srcu(),
	call_rcu_tasks(), or call_rcu_tasks_trace().  For example, if
	a given CPU goes offline while having an RCU callback pending,
	then that RCU callback will execute on some surviving CPU.
	(If this was not the case, a self-spawning RCU callback would
	prevent the victim CPU from ever going offline.)  Furthermore,
	CPUs designated by rcu_nocbs= might well *always* have their
	RCU callbacks executed on some other CPUs, in fact, for some
	real-time workloads, this is the whole point of using the
	rcu_nocbs= kernel boot parameter.

	In addition, do not assume that callbacks queued in a given order
	will be invoked in that order, even if they all are queued on the
	same CPU.  Furthermore, do not assume that same-CPU callbacks will
	be invoked serially.  For example, in recent kernels, CPUs can be
	switched between offloaded and de-offloaded callback invocation,
	and while a given CPU is undergoing such a switch, its callbacks
	might be concurrently invoked by that CPU's softirq handler and
	that CPU's rcuo kthread.  At such times, that CPU's callbacks
	might be executed both concurrently and out of order.

13.	Unlike most flavors of RCU, it *is* permissible to block in an
	SRCU read-side critical section (demarked by srcu_read_lock()
	and srcu_read_unlock()), hence the "SRCU": "sleepable RCU".
	As with RCU, guard(srcu)() and scoped_guard(srcu) forms are
	available, and often provide greater ease of use.  Please note
	that if you don't need to sleep in read-side critical sections,
	you should be using RCU rather than SRCU, because RCU is almost
	always faster and easier to use than is SRCU.

	Also unlike other forms of RCU, explicit initialization and
	cleanup is required either at build time via DEFINE_SRCU()
	or DEFINE_STATIC_SRCU() or at runtime via init_srcu_struct()
	and cleanup_srcu_struct().  These last two are passed a
	"struct srcu_struct" that defines the scope of a given
	SRCU domain.  Once initialized, the srcu_struct is passed
	to srcu_read_lock(), srcu_read_unlock() synchronize_srcu(),
	synchronize_srcu_expedited(), and call_srcu().	A given
	synchronize_srcu() waits only for SRCU read-side critical
	sections governed by srcu_read_lock() and srcu_read_unlock()
	calls that have been passed the same srcu_struct.  This property
	is what makes sleeping read-side critical sections tolerable --
	a given subsystem delays only its own updates, not those of other
	subsystems using SRCU.	Therefore, SRCU is less prone to OOM the
	system than RCU would be if RCU's read-side critical sections
	were permitted to sleep.

	The ability to sleep in read-side critical sections does not
	come for free.	First, corresponding srcu_read_lock() and
	srcu_read_unlock() calls must be passed the same srcu_struct.
	Second, grace-period-detection overhead is amortized only
	over those updates sharing a given srcu_struct, rather than
	being globally amortized as they are for other forms of RCU.
	Therefore, SRCU should be used in preference to rw_semaphore
	only in extremely read-intensive situations, or in situations
	requiring SRCU's read-side deadlock immunity or low read-side
	realtime latency.  You should also consider percpu_rw_semaphore
	when you need lightweight readers.

	SRCU's expedited primitive (synchronize_srcu_expedited())
	never sends IPIs to other CPUs, so it is easier on
	real-time workloads than is synchronize_rcu_expedited().

	It is also permissible to sleep in RCU Tasks Trace read-side
	critical section, which are delimited by rcu_read_lock_trace()
	and rcu_read_unlock_trace().  However, this is a specialized
	flavor of RCU, and you should not use it without first checking
	with its current users.  In most cases, you should instead
	use SRCU.  As with RCU and SRCU, guard(rcu_tasks_trace)() and
	scoped_guard(rcu_tasks_trace) are available, and often provide
	greater ease of use.

	Note that rcu_assign_pointer() relates to SRCU just as it does to
	other forms of RCU, but instead of rcu_dereference() you should
	use srcu_dereference() in order to avoid lockdep splats.

14.	The whole point of call_rcu(), synchronize_rcu(), and friends
	is to wait until all pre-existing readers have finished before
	carrying out some otherwise-destructive operation.  It is
	therefore critically important to *first* remove any path
	that readers can follow that could be affected by the
	destructive operation, and *only then* invoke call_rcu(),
	synchronize_rcu(), or friends.

	Because these primitives only wait for pre-existing readers, it
	is the caller's responsibility to guarantee that any subsequent
	readers will execute safely.

15.	The various RCU read-side primitives do *not* necessarily contain
	memory barriers.  You should therefore plan for the CPU
	and the compiler to freely reorder code into and out of RCU
	read-side critical sections.  It is the responsibility of the
	RCU update-side primitives to deal with this.

	For SRCU readers, you can use smp_mb__after_srcu_read_unlock()
	immediately after an srcu_read_unlock() to get a full barrier.

16.	Use CONFIG_PROVE_LOCKING, CONFIG_DEBUG_OBJECTS_RCU_HEAD, and the
	__rcu sparse checks to validate your RCU code.	These can help
	find problems as follows:

	CONFIG_PROVE_LOCKING:
		check that accesses to RCU-protected data structures
		are carried out under the proper RCU read-side critical
		section, while holding the right combination of locks,
		or whatever other conditions are appropriate.

	CONFIG_DEBUG_OBJECTS_RCU_HEAD:
		check that you don't pass the same object to call_rcu()
		(or friends) before an RCU grace period has elapsed
		since the last time that you passed that same object to
		call_rcu() (or friends).

	CONFIG_RCU_STRICT_GRACE_PERIOD:
		combine with KASAN to check for pointers leaked out
		of RCU read-side critical sections.  This Kconfig
		option is tough on both performance and scalability,
		and so is limited to four-CPU systems.

	__rcu sparse checks:
		tag the pointer to the RCU-protected data structure
		with __rcu, and sparse will warn you if you access that
		pointer without the services of one of the variants
		of rcu_dereference().

	These debugging aids can help you find problems that are
	otherwise extremely difficult to spot.

17.	If you pass a callback function defined within a module
	to one of call_rcu(), call_srcu(), call_rcu_tasks(), or
	call_rcu_tasks_trace(), then it is necessary to wait for all
	pending callbacks to be invoked before unloading that module.
	Note that it is absolutely *not* sufficient to wait for a grace
	period!  For example, synchronize_rcu() implementation is *not*
	guaranteed to wait for callbacks registered on other CPUs via
	call_rcu().  Or even on the current CPU if that CPU recently
	went offline and came back online.

	You instead need to use one of the barrier functions:

	-	call_rcu() -> rcu_barrier()
	-	call_srcu() -> srcu_barrier()
	-	call_rcu_tasks() -> rcu_barrier_tasks()
	-	call_rcu_tasks_trace() -> rcu_barrier_tasks_trace()

	However, these barrier functions are absolutely *not* guaranteed
	to wait for a grace period.  For example, if there are no
	call_rcu() callbacks queued anywhere in the system, rcu_barrier()
	can and will return immediately.

	So if you need to wait for both a grace period and for all
	pre-existing callbacks, you will need to invoke both functions,
	with the pair depending on the flavor of RCU:

	-	Either synchronize_rcu() or synchronize_rcu_expedited(),
		together with rcu_barrier()
	-	Either synchronize_srcu() or synchronize_srcu_expedited(),
		together with and srcu_barrier()
	-	synchronize_rcu_tasks() and rcu_barrier_tasks()
	-	synchronize_tasks_trace() and rcu_barrier_tasks_trace()

	If necessary, you can use something like workqueues to execute
	the requisite pair of functions concurrently.

	See rcubarrier.rst for more information.

---

### Documentation RCU Index (`Documentation/RCU/index.rst`)

.. SPDX-License-Identifier: GPL-2.0

.. _rcu_handbook:

============
RCU Handbook
============

.. toctree::
   :maxdepth: 2

   checklist
   lockdep
   lockdep-splat
   rcubarrier
   rcu_dereference
   whatisRCU
   rcu
   rculist_nulls
   rcuref
   torture
   stallwarn
   listRCU
   NMI-RCU
   UP

   Design/Memory-Ordering/Tree-RCU-Memory-Ordering
   Design/Expedited-Grace-Periods/Expedited-Grace-Periods
   Design/Requirements/Requirements
   Design/Data-Structures/Data-Structures

.. only:: subproject and html

   Indices
   =======

   * :ref:`genindex`

---

### Documentation RCU ListRCU (`Documentation/RCU/listRCU.rst`)

.. _list_rcu_doc:

Using RCU to Protect Read-Mostly Linked Lists
=============================================

One of the most common uses of RCU is protecting read-mostly linked lists
(``struct list_head`` in list.h).  One big advantage of this approach is
that all of the required memory ordering is provided by the list macros.
This document describes several list-based RCU use cases.

When iterating a list while holding the rcu_read_lock(), writers may
modify the list.  The reader is guaranteed to see all of the elements
which were added to the list before they acquired the rcu_read_lock()
and are still on the list when they drop the rcu_read_unlock().
Elements which are added to, or removed from the list may or may not
be seen.  If the writer calls list_replace_rcu(), the reader may see
either the old element or the new element; they will not see both,
nor will they see neither.


Example 1: Read-mostly list: Deferred Destruction
-------------------------------------------------

A widely used usecase for RCU lists in the kernel is lockless iteration over
all processes in the system. ``task_struct::tasks`` represents the list node that
links all the processes. The list can be traversed in parallel to any list
additions or removals.

The traversal of the list is done using ``for_each_process()`` which is defined
by the 2 macros::

	#define next_task(p) \
		list_entry_rcu((p)->tasks.next, struct task_struct, tasks)

	#define for_each_process(p) \
		for (p = &init_task ; (p = next_task(p)) != &init_task ; )

The code traversing the list of all processes typically looks like::

	rcu_read_lock();
	for_each_process(p) {
		/* Do something with p */
	}
	rcu_read_unlock();

The simplified and heavily inlined code for removing a process from a
task list is::

	void release_task(struct task_struct *p)
	{
		write_lock(&tasklist_lock);
		list_del_rcu(&p->tasks);
		write_unlock(&tasklist_lock);
		call_rcu(&p->rcu, delayed_put_task_struct);
	}

When a process exits, ``release_task()`` calls ``list_del_rcu(&p->tasks)``
via __exit_signal() and __unhash_process() under ``tasklist_lock``
writer lock protection.  The list_del_rcu() invocation removes
the task from the list of all tasks. The ``tasklist_lock``
prevents concurrent list additions/removals from corrupting the
list. Readers using ``for_each_process()`` are not protected with the
``tasklist_lock``. To prevent readers from noticing changes in the list
pointers, the ``task_struct`` object is freed only after one or more
grace periods elapse, with the help of call_rcu(), which is invoked via
put_task_struct_rcu_user(). This deferring of destruction ensures that
any readers traversing the list will see valid ``p->tasks.next`` pointers
and deletion/freeing can happen in parallel with traversal of the list.
This pattern is also called an **existence lock**, since RCU refrains
from invoking the delayed_put_task_struct() callback function until
all existing readers finish, which guarantees that the ``task_struct``
object in question will remain in existence until after the completion
of all RCU readers that might possibly have a reference to that object.


Example 2: Read-Side Action Taken Outside of Lock: No In-Place Updates
----------------------------------------------------------------------

Some reader-writer locking use cases compute a value while holding
the read-side lock, but continue to use that value after that lock is
released.  These use cases are often good candidates for conversion
to RCU.  One prominent example involves network packet routing.
Because the packet-routing data tracks the state of equipment outside
of the computer, it will at times contain stale data.  Therefore, once
the route has been computed, there is no need to hold the routing table
static during transmission of the packet.  After all, you can hold the
routing table static all you want, but that won't keep the external
Internet from changing, and it is the state of the external Internet
that really matters.  In addition, routing entries are typically added
or deleted, rather than being modified in place.  This is a rare example
of the finite speed of light and the non-zero size of atoms actually
helping make synchronization be lighter weight.

A straightforward example of this type of RCU use case may be found in
the system-call auditing support.  For example, a reader-writer locked
implementation of ``audit_filter_task()`` might be as follows::

	static enum audit_state audit_filter_task(struct task_struct *tsk, char **key)
	{
		struct audit_entry *e;
		enum audit_state   state;

		read_lock(&auditsc_lock);
		/* Note: audit_filter_mutex held by caller. */
		list_for_each_entry(e, &audit_tsklist, list) {
			if (audit_filter_rules(tsk, &e->rule, NULL, &state)) {
				if (state == AUDIT_STATE_RECORD)
					*key = kstrdup(e->rule.filterkey, GFP_ATOMIC);
				read_unlock(&auditsc_lock);
				return state;
			}
		}
		read_unlock(&auditsc_lock);
		return AUDIT_BUILD_CONTEXT;
	}

Here the list is searched under the lock, but the lock is dropped before
the corresponding value is returned.  By the time that this value is acted
on, the list may well have been modified.  This makes sense, since if
you are turning auditing off, it is OK to audit a few extra system calls.

This means that RCU can be easily applied to the read side, as follows::

	static enum audit_state audit_filter_task(struct task_struct *tsk, char **key)
	{
		struct audit_entry *e;
		enum audit_state   state;

		rcu_read_lock();
		/* Note: audit_filter_mutex held by caller. */
		list_for_each_entry_rcu(e, &audit_tsklist, list) {
			if (audit_filter_rules(tsk, &e->rule, NULL, &state)) {
				if (state == AUDIT_STATE_RECORD)
					*key = kstrdup(e->rule.filterkey, GFP_ATOMIC);
				rcu_read_unlock();
				return state;
			}
		}
		rcu_read_unlock();
		return AUDIT_BUILD_CONTEXT;
	}

The read_lock() and read_unlock() calls have become rcu_read_lock()
and rcu_read_unlock(), respectively, and the list_for_each_entry()
has become list_for_each_entry_rcu().  The **_rcu()** list-traversal
primitives add READ_ONCE() and diagnostic checks for incorrect use
outside of an RCU read-side critical section.

The changes to the update side are also straightforward. A reader-writer lock
might be used as follows for deletion and insertion in these simplified
versions of audit_del_rule() and audit_add_rule()::

	static inline int audit_del_rule(struct audit_rule *rule,
					 struct list_head *list)
	{
		struct audit_entry *e;

		write_lock(&auditsc_lock);
		list_for_each_entry(e, list, list) {
			if (!audit_compare_rule(rule, &e->rule)) {
				list_del(&e->list);
				write_unlock(&auditsc_lock);
				return 0;
			}
		}
		write_unlock(&auditsc_lock);
		return -EFAULT;		/* No matching rule */
	}

	static inline int audit_add_rule(struct audit_entry *entry,
					 struct list_head *list)
	{
		write_lock(&auditsc_lock);
		if (entry->rule.flags & AUDIT_PREPEND) {
			entry->rule.flags &= ~AUDIT_PREPEND;
			list_add(&entry->list, list);
		} else {
			list_add_tail(&entry->list, list);
		}
		write_unlock(&auditsc_lock);
		return 0;
	}

Following are the RCU equivalents for these two functions::

	static inline int audit_del_rule(struct audit_rule *rule,
					 struct list_head *list)
	{
		struct audit_entry *e;

		/* No need to use the _rcu iterator here, since this is the only
		 * deletion routine. */
		list_for_each_entry(e, list, list) {
			if (!audit_compare_rule(rule, &e->rule)) {
				list_del_rcu(&e->list);
				call_rcu(&e->rcu, audit_free_rule);
				return 0;
			}
		}
		return -EFAULT;		/* No matching rule */
	}

	static inline int audit_add_rule(struct audit_entry *entry,
					 struct list_head *list)
	{
		if (entry->rule.flags & AUDIT_PREPEND) {
			entry->rule.flags &= ~AUDIT_PREPEND;
			list_add_rcu(&entry->list, list);
		} else {
			list_add_tail_rcu(&entry->list, list);
		}
		return 0;
	}

Normally, the write_lock() and write_unlock() would be replaced by a
spin_lock() and a spin_unlock(). But in this case, all callers hold
``audit_filter_mutex``, so no additional locking is required. The
auditsc_lock can therefore be eliminated, since use of RCU eliminates the
need for writers to exclude readers.

The list_del(), list_add(), and list_add_tail() primitives have been
replaced by list_del_rcu(), list_add_rcu(), and list_add_tail_rcu().
The **_rcu()** list-manipulation primitives add memory barriers that are
needed on weakly ordered CPUs.  The list_del_rcu() primitive omits the
pointer poisoning debug-assist code that would otherwise cause concurrent
readers to fail spectacularly.

So, when readers can tolerate stale data and when entries are either added or
deleted, without in-place modification, it is very easy to use RCU!


Example 3: Handling In-Place Updates
------------------------------------

The system-call auditing code does not update auditing rules in place.  However,
if it did, the reader-writer-locked code to do so might look as follows
(assuming only ``field_count`` is updated, otherwise, the added fields would
need to be filled in)::

	static inline int audit_upd_rule(struct audit_rule *rule,
					 struct list_head *list,
					 __u32 newaction,
					 __u32 newfield_count)
	{
		struct audit_entry *e;
		struct audit_entry *ne;

		write_lock(&auditsc_lock);
		/* Note: audit_filter_mutex held by caller. */
		list_for_each_entry(e, list, list) {
			if (!audit_compare_rule(rule, &e->rule)) {
				e->rule.action = newaction;
				e->rule.field_count = newfield_count;
				write_unlock(&auditsc_lock);
				return 0;
			}
		}
		write_unlock(&auditsc_lock);
		return -EFAULT;		/* No matching rule */
	}

The RCU version creates a copy, updates the copy, then replaces the old
entry with the newly updated entry.  This sequence of actions, allowing
concurrent reads while making a copy to perform an update, is what gives
RCU (*read-copy update*) its name.

The RCU version of audit_upd_rule() is as follows::

	static inline int audit_upd_rule(struct audit_rule *rule,
					 struct list_head *list,
					 __u32 newaction,
					 __u32 newfield_count)
	{
		struct audit_entry *e;
		struct audit_entry *ne;

		list_for_each_entry(e, list, list) {
			if (!audit_compare_rule(rule, &e->rule)) {
				ne = kmalloc(sizeof(*entry), GFP_ATOMIC);
				if (ne == NULL)
					return -ENOMEM;
				audit_copy_rule(&ne->rule, &e->rule);
				ne->rule.action = newaction;
				ne->rule.field_count = newfield_count;
				list_replace_rcu(&e->list, &ne->list);
				call_rcu(&e->rcu, audit_free_rule);
				return 0;
			}
		}
		return -EFAULT;		/* No matching rule */
	}

Again, this assumes that the caller holds ``audit_filter_mutex``.  Normally, the
writer lock would become a spinlock in this sort of code.

The update_lsm_rule() does something very similar, for those who would
prefer to look at real Linux-kernel code.

Another use of this pattern can be found in the openswitch driver's *connection
tracking table* code in ``ct_limit_set()``.  The table holds connection tracking
entries and has a limit on the maximum entries.  There is one such table
per-zone and hence one *limit* per zone.  The zones are mapped to their limits
through a hashtable using an RCU-managed hlist for the hash chains. When a new
limit is set, a new limit object is allocated and ``ct_limit_set()`` is called
to replace the old limit object with the new one using list_replace_rcu().
The old limit object is then freed after a grace period using kfree_rcu().


Example 4: Eliminating Stale Data
---------------------------------

The auditing example above tolerates stale data, as do most algorithms
that are tracking external state.  After all, given there is a delay
from the time the external state changes before Linux becomes aware
of the change, and so as noted earlier, a small quantity of additional
RCU-induced staleness is generally not a problem.

However, there are many examples where stale data cannot be tolerated.
One example in the Linux kernel is the System V IPC (see the shm_lock()
function in ipc/shm.c).  This code checks a *deleted* flag under a
per-entry spinlock, and, if the *deleted* flag is set, pretends that the
entry does not exist.  For this to be helpful, the search function must
return holding the per-entry spinlock, as shm_lock() does in fact do.

.. _quick_quiz:

Quick Quiz:
	For the deleted-flag technique to be helpful, why is it necessary
	to hold the per-entry lock while returning from the search function?

:ref:`Answer to Quick Quiz <quick_quiz_answer>`

If the system-call audit module were to ever need to reject stale data, one way
to accomplish this would be to add a ``deleted`` flag and a ``lock`` spinlock to the
``audit_entry`` structure, and modify audit_filter_task() as follows::

	static struct audit_entry *audit_filter_task(struct task_struct *tsk, char **key)
	{
		struct audit_entry *e;
		enum audit_state   state;

		rcu_read_lock();
		list_for_each_entry_rcu(e, &audit_tsklist, list) {
			if (audit_filter_rules(tsk, &e->rule, NULL, &state)) {
				spin_lock(&e->lock);
				if (e->deleted) {
					spin_unlock(&e->lock);
					rcu_read_unlock();
					return NULL;
				}
				rcu_read_unlock();
				if (state == AUDIT_STATE_RECORD)
					*key = kstrdup(e->rule.filterkey, GFP_ATOMIC);
				/* As long as e->lock is held, e is valid and
				 * its value is not stale */
				return e;
			}
		}
		rcu_read_unlock();
		return NULL;
	}

The ``audit_del_rule()`` function would need to set the ``deleted`` flag under the
spinlock as follows::

	static inline int audit_del_rule(struct audit_rule *rule,
					 struct list_head *list)
	{
		struct audit_entry *e;

		/* No need to use the _rcu iterator here, since this
		 * is the only deletion routine. */
		list_for_each_entry(e, list, list) {
			if (!audit_compare_rule(rule, &e->rule)) {
				spin_lock(&e->lock);
				list_del_rcu(&e->list);
				e->deleted = 1;
				spin_unlock(&e->lock);
				call_rcu(&e->rcu, audit_free_rule);
				return 0;
			}
		}
		return -EFAULT;		/* No matching rule */
	}

This too assumes that the caller holds ``audit_filter_mutex``.

Note that this example assumes that entries are only added and deleted.
Additional mechanism is required to deal correctly with the update-in-place
performed by audit_upd_rule().  For one thing, audit_upd_rule() would
need to hold the locks of both the old ``audit_entry`` and its replacement
while executing the list_replace_rcu().


Example 5: Skipping Stale Objects
---------------------------------

For some use cases, reader performance can be improved by skipping
stale objects during read-side list traversal, where stale objects
are those that will be removed and destroyed after one or more grace
periods. One such example can be found in the timerfd subsystem. When a
``CLOCK_REALTIME`` clock is reprogrammed (for example due to setting
of the system time) then all programmed ``timerfds`` that depend on
this clock get triggered and processes waiting on them are awakened in
advance of their scheduled expiry. To facilitate this, all such timers
are added to an RCU-managed ``cancel_list`` when they are setup in
``timerfd_setup_cancel()``::

	static void timerfd_setup_cancel(struct timerfd_ctx *ctx, int flags)
	{
		spin_lock(&ctx->cancel_lock);
		if ((ctx->clockid == CLOCK_REALTIME ||
		     ctx->clockid == CLOCK_REALTIME_ALARM) &&
		    (flags & TFD_TIMER_ABSTIME) && (flags & TFD_TIMER_CANCEL_ON_SET)) {
			if (!ctx->might_cancel) {
				ctx->might_cancel = true;
				spin_lock(&cancel_lock);
				list_add_rcu(&ctx->clist, &cancel_list);
				spin_unlock(&cancel_lock);
			}
		} else {
			__timerfd_remove_cancel(ctx);
		}
		spin_unlock(&ctx->cancel_lock);
	}

When a timerfd is freed (fd is closed), then the ``might_cancel``
flag of the timerfd object is cleared, the object removed from the
``cancel_list`` and destroyed, as shown in this simplified and inlined
version of timerfd_release()::

	int timerfd_release(struct inode *inode, struct file *file)
	{
		struct timerfd_ctx *ctx = file->private_data;

		spin_lock(&ctx->cancel_lock);
		if (ctx->might_cancel) {
			ctx->might_cancel = false;
			spin_lock(&cancel_lock);
			list_del_rcu(&ctx->clist);
			spin_unlock(&cancel_lock);
		}
		spin_unlock(&ctx->cancel_lock);

		if (isalarm(ctx))
			alarm_cancel(&ctx->t.alarm);
		else
			hrtimer_cancel(&ctx->t.tmr);
		kfree_rcu(ctx, rcu);
		return 0;
	}

If the ``CLOCK_REALTIME`` clock is set, for example by a time server, the
hrtimer framework calls ``timerfd_clock_was_set()`` which walks the
``cancel_list`` and wakes up processes waiting on the timerfd. While iterating
the ``cancel_list``, the ``might_cancel`` flag is consulted to skip stale
objects::

	void timerfd_clock_was_set(void)
	{
		ktime_t moffs = ktime_mono_to_real(0);
		struct timerfd_ctx *ctx;
		unsigned long flags;

		rcu_read_lock();
		list_for_each_entry_rcu(ctx, &cancel_list, clist) {
			if (!ctx->might_cancel)
				continue;
			spin_lock_irqsave(&ctx->wqh.lock, flags);
			if (ctx->moffs != moffs) {
				ctx->moffs = KTIME_MAX;
				ctx->ticks++;
				wake_up_locked_poll(&ctx->wqh, EPOLLIN);
			}
			spin_unlock_irqrestore(&ctx->wqh.lock, flags);
		}
		rcu_read_unlock();
	}

The key point is that because RCU-protected traversal of the
``cancel_list`` happens concurrently with object addition and removal,
sometimes the traversal can access an object that has been removed from
the list. In this example, a flag is used to skip such objects.


Summary
-------

Read-mostly list-based data structures that can tolerate stale data are
the most amenable to use of RCU.  The simplest case is where entries are
either added or deleted from the data structure (or atomically modified
in place), but non-atomic in-place modifications can be handled by making
a copy, updating the copy, then replacing the original with the copy.
If stale data cannot be tolerated, then a *deleted* flag may be used
in conjunction with a per-entry spinlock in order to allow the search
function to reject newly deleted data.

.. _quick_quiz_answer:

Answer to Quick Quiz:
	For the deleted-flag technique to be helpful, why is it necessary
	to hold the per-entry lock while returning from the search function?

	If the search function drops the per-entry lock before returning,
	then the caller will be processing stale data in any case.  If it
	is really OK to be processing stale data, then you don't need a
	*deleted* flag.  If processing stale data really is a problem,
	then you need to hold the per-entry lock across all of the code
	that uses the value that was returned.

:ref:`Back to Quick Quiz <quick_quiz>`

---

### Documentation RCU Lockdep Splat (`Documentation/RCU/lockdep-splat.rst`)

.. SPDX-License-Identifier: GPL-2.0

=================
Lockdep-RCU Splat
=================

Lockdep-RCU was added to the Linux kernel in early 2010
(http://lwn.net/Articles/371986/).  This facility checks for some common
misuses of the RCU API, most notably using one of the rcu_dereference()
family to access an RCU-protected pointer without the proper protection.
When such misuse is detected, an lockdep-RCU splat is emitted.

The usual cause of a lockdep-RCU splat is someone accessing an
RCU-protected data structure without either (1) being in the right kind of
RCU read-side critical section or (2) holding the right update-side lock.
This problem can therefore be serious: it might result in random memory
overwriting or worse.  There can of course be false positives, this
being the real world and all that.

So let's look at an example RCU lockdep splat from 3.0-rc5, one that
has long since been fixed::

    =============================
    WARNING: suspicious RCU usage
    -----------------------------
    block/cfq-iosched.c:2776 suspicious rcu_dereference_protected() usage!

other info that might help us debug this::

    rcu_scheduler_active = 1, debug_locks = 0
    3 locks held by scsi_scan_6/1552:
    #0:  (&shost->scan_mutex){+.+.}, at: [<ffffffff8145efca>]
    scsi_scan_host_selected+0x5a/0x150
    #1:  (&eq->sysfs_lock){+.+.}, at: [<ffffffff812a5032>]
    elevator_exit+0x22/0x60
    #2:  (&(&q->__queue_lock)->rlock){-.-.}, at: [<ffffffff812b6233>]
    cfq_exit_queue+0x43/0x190

    stack backtrace:
    Pid: 1552, comm: scsi_scan_6 Not tainted 3.0.0-rc5 #17
    Call Trace:
    [<ffffffff810abb9b>] lockdep_rcu_dereference+0xbb/0xc0
    [<ffffffff812b6139>] __cfq_exit_single_io_context+0xe9/0x120
    [<ffffffff812b626c>] cfq_exit_queue+0x7c/0x190
    [<ffffffff812a5046>] elevator_exit+0x36/0x60
    [<ffffffff812a802a>] blk_cleanup_queue+0x4a/0x60
    [<ffffffff8145cc09>] scsi_free_queue+0x9/0x10
    [<ffffffff81460944>] __scsi_remove_device+0x84/0xd0
    [<ffffffff8145dca3>] scsi_probe_and_add_lun+0x353/0xb10
    [<ffffffff817da069>] ? error_exit+0x29/0xb0
    [<ffffffff817d98ed>] ? _raw_spin_unlock_irqrestore+0x3d/0x80
    [<ffffffff8145e722>] __scsi_scan_target+0x112/0x680
    [<ffffffff812c690d>] ? trace_hardirqs_off_thunk+0x3a/0x3c
    [<ffffffff817da069>] ? error_exit+0x29/0xb0
    [<ffffffff812bcc60>] ? kobject_del+0x40/0x40
    [<ffffffff8145ed16>] scsi_scan_channel+0x86/0xb0
    [<ffffffff8145f0b0>] scsi_scan_host_selected+0x140/0x150
    [<ffffffff8145f149>] do_scsi_scan_host+0x89/0x90
    [<ffffffff8145f170>] do_scan_async+0x20/0x160
    [<ffffffff8145f150>] ? do_scsi_scan_host+0x90/0x90
    [<ffffffff810975b6>] kthread+0xa6/0xb0
    [<ffffffff817db154>] kernel_thread_helper+0x4/0x10
    [<ffffffff81066430>] ? finish_task_switch+0x80/0x110
    [<ffffffff817d9c04>] ? retint_restore_args+0xe/0xe
    [<ffffffff81097510>] ? __kthread_init_worker+0x70/0x70
    [<ffffffff817db150>] ? gs_change+0xb/0xb

Line 2776 of block/cfq-iosched.c in v3.0-rc5 is as follows::

	if (rcu_dereference(ioc->ioc_data) == cic) {

This form says that it must be in a plain vanilla RCU read-side critical
section, but the "other info" list above shows that this is not the
case.  Instead, we hold three locks, one of which might be RCU related.
And maybe that lock really does protect this reference.  If so, the fix
is to inform RCU, perhaps by changing __cfq_exit_single_io_context() to
take the struct request_queue "q" from cfq_exit_queue() as an argument,
which would permit us to invoke rcu_dereference_protected as follows::

	if (rcu_dereference_protected(ioc->ioc_data,
				      lockdep_is_held(&q->queue_lock)) == cic) {

With this change, there would be no lockdep-RCU splat emitted if this
code was invoked either from within an RCU read-side critical section
or with the ->queue_lock held.  In particular, this would have suppressed
the above lockdep-RCU splat because ->queue_lock is held (see #2 in the
list above).

On the other hand, perhaps we really do need an RCU read-side critical
section.  In this case, the critical section must span the use of the
return value from rcu_dereference(), or at least until there is some
reference count incremented or some such.  One way to handle this is to
add rcu_read_lock() and rcu_read_unlock() as follows::

	rcu_read_lock();
	if (rcu_dereference(ioc->ioc_data) == cic) {
		spin_lock(&ioc->lock);
		rcu_assign_pointer(ioc->ioc_data, NULL);
		spin_unlock(&ioc->lock);
	}
	rcu_read_unlock();

With this change, the rcu_dereference() is always within an RCU
read-side critical section, which again would have suppressed the
above lockdep-RCU splat.

But in this particular case, we don't actually dereference the pointer
returned from rcu_dereference().  Instead, that pointer is just compared
to the cic pointer, which means that the rcu_dereference() can be replaced
by rcu_access_pointer() as follows::

	if (rcu_access_pointer(ioc->ioc_data) == cic) {

Because it is legal to invoke rcu_access_pointer() without protection,
this change would also suppress the above lockdep-RCU splat.

---

### Documentation RCU Lockdep (`Documentation/RCU/lockdep.rst`)

.. SPDX-License-Identifier: GPL-2.0

========================
RCU and lockdep checking
========================

All flavors of RCU have lockdep checking available, so that lockdep is
aware of when each task enters and leaves any flavor of RCU read-side
critical section.  Each flavor of RCU is tracked separately (but note
that this is not the case in 2.6.32 and earlier).  This allows lockdep's
tracking to include RCU state, which can sometimes help when debugging
deadlocks and the like.

In addition, RCU provides the following primitives that check lockdep's
state::

	rcu_read_lock_held() for normal RCU.
	rcu_read_lock_bh_held() for RCU-bh.
	rcu_read_lock_sched_held() for RCU-sched.
	rcu_read_lock_any_held() for any of normal RCU, RCU-bh, and RCU-sched.
	srcu_read_lock_held() for SRCU.
	rcu_read_lock_trace_held() for RCU Tasks Trace.

These functions are conservative, and will therefore return 1 if they
aren't certain (for example, if CONFIG_DEBUG_LOCK_ALLOC is not set).
This prevents things like WARN_ON(!rcu_read_lock_held()) from giving false
positives when lockdep is disabled.

In addition, a separate kernel config parameter CONFIG_PROVE_RCU enables
checking of rcu_dereference() primitives:

	rcu_dereference(p):
		Check for RCU read-side critical section.
	rcu_dereference_bh(p):
		Check for RCU-bh read-side critical section.
	rcu_dereference_sched(p):
		Check for RCU-sched read-side critical section.
	srcu_dereference(p, sp):
		Check for SRCU read-side critical section.
	rcu_dereference_check(p, c):
		Use explicit check expression "c" along with
		rcu_read_lock_held().  This is useful in code that is
		invoked by both RCU readers and updaters.
	rcu_dereference_bh_check(p, c):
		Use explicit check expression "c" along with
		rcu_read_lock_bh_held().  This is useful in code that
		is invoked by both RCU-bh readers and updaters.
	rcu_dereference_sched_check(p, c):
		Use explicit check expression "c" along with
		rcu_read_lock_sched_held().  This is useful in code that
		is invoked by both RCU-sched readers and updaters.
	srcu_dereference_check(p, c):
		Use explicit check expression "c" along with
		srcu_read_lock_held().  This is useful in code that
		is invoked by both SRCU readers and updaters.
	rcu_dereference_raw(p):
		Don't check.  (Use sparingly, if at all.)
	rcu_dereference_raw_check(p):
		Don't do lockdep at all.  (Use sparingly, if at all.)
	rcu_dereference_protected(p, c):
		Use explicit check expression "c", and omit all barriers
		and compiler constraints.  This is useful when the data
		structure cannot change, for example, in code that is
		invoked only by updaters.
	rcu_access_pointer(p):
		Return the value of the pointer and omit all barriers,
		but retain the compiler constraints that prevent duplicating
		or coalescing.  This is useful when testing the
		value of the pointer itself, for example, against NULL.

The rcu_dereference_check() check expression can be any boolean
expression, but would normally include a lockdep expression.  For a
moderately ornate example, consider the following::

	file = rcu_dereference_check(fdt->fd[fd],
				     lockdep_is_held(&files->file_lock) ||
				     atomic_read(&files->count) == 1);

This expression picks up the pointer "fdt->fd[fd]" in an RCU-safe manner,
and, if CONFIG_PROVE_RCU is configured, verifies that this expression
is used in:

1.	An RCU read-side critical section (implicit), or
2.	with files->file_lock held, or
3.	on an unshared files_struct.

In case (1), the pointer is picked up in an RCU-safe manner for vanilla
RCU read-side critical sections, in case (2) the ->file_lock prevents
any change from taking place, and finally, in case (3) the current task
is the only task accessing the file_struct, again preventing any change
from taking place.  If the above statement was invoked only from updater
code, it could instead be written as follows::

	file = rcu_dereference_protected(fdt->fd[fd],
					 lockdep_is_held(&files->file_lock) ||
					 atomic_read(&files->count) == 1);

This would verify cases #2 and #3 above, and furthermore lockdep would
complain even if this was used in an RCU read-side critical section unless
one of these two cases held.  Because rcu_dereference_protected() omits
all barriers and compiler constraints, it generates better code than do
the other flavors of rcu_dereference().  On the other hand, it is illegal
to use rcu_dereference_protected() if either the RCU-protected pointer
or the RCU-protected data that it points to can change concurrently.

Like rcu_dereference(), when lockdep is enabled, RCU list and hlist
traversal primitives check for being called from within an RCU read-side
critical section.  However, a lockdep expression can be passed to them
as an additional optional argument.  With this lockdep expression, these
traversal primitives will complain only if the lockdep expression is
false and they are called from outside any RCU read-side critical section.

For example, the workqueue for_each_pwq() macro is intended to be used
either within an RCU read-side critical section or with wq->mutex held.
It is thus implemented as follows::

	#define for_each_pwq(pwq, wq)
		list_for_each_entry_rcu((pwq), &(wq)->pwqs, pwqs_node,
					lock_is_held(&(wq->mutex).dep_map))

---

### Documentation RCU Rcu (`Documentation/RCU/rcu.rst`)

.. _rcu_doc:

RCU Concepts
============

The basic idea behind RCU (read-copy update) is to split destructive
operations into two parts, one that prevents anyone from seeing the data
item being destroyed, and one that actually carries out the destruction.
A "grace period" must elapse between the two parts, and this grace period
must be long enough that any readers accessing the item being deleted have
since dropped their references.  For example, an RCU-protected deletion
from a linked list would first remove the item from the list, wait for
a grace period to elapse, then free the element.  See listRCU.rst for more
information on using RCU with linked lists.

Frequently Asked Questions
--------------------------

- Why would anyone want to use RCU?

  The advantage of RCU's two-part approach is that RCU readers need
  not acquire any locks, perform any atomic instructions, write to
  shared memory, or (on CPUs other than Alpha) execute any memory
  barriers.  The fact that these operations are quite expensive
  on modern CPUs is what gives RCU its performance advantages
  in read-mostly situations.  The fact that RCU readers need not
  acquire locks can also greatly simplify deadlock-avoidance code.

- How can the updater tell when a grace period has completed
  if the RCU readers give no indication when they are done?

  Just as with spinlocks, RCU readers are not permitted to
  block, switch to user-mode execution, or enter the idle loop.
  Therefore, as soon as a CPU is seen passing through any of these
  three states, we know that that CPU has exited any previous RCU
  read-side critical sections.  So, if we remove an item from a
  linked list, and then wait until all CPUs have switched context,
  executed in user mode, or executed in the idle loop, we can
  safely free up that item.

  Preemptible variants of RCU (CONFIG_PREEMPT_RCU) get the
  same effect, but require that the readers manipulate CPU-local
  counters.  These counters allow limited types of blocking within
  RCU read-side critical sections.  SRCU also uses CPU-local
  counters, and permits general blocking within RCU read-side
  critical sections.  These variants of RCU detect grace periods
  by sampling these counters.

- If I am running on a uniprocessor kernel, which can only do one
  thing at a time, why should I wait for a grace period?

  See UP.rst for more information.

- How can I see where RCU is currently used in the Linux kernel?

  Search for "rcu_read_lock", "rcu_read_unlock", "call_rcu",
  "rcu_read_lock_bh", "rcu_read_unlock_bh", "srcu_read_lock",
  "srcu_read_unlock", "synchronize_rcu", "synchronize_net",
  "synchronize_srcu", and the other RCU primitives.  Or grab one
  of the cscope databases from:

  (http://www.rdrop.com/users/paulmck/RCU/linuxusage/rculocktab.html).

- What guidelines should I follow when writing code that uses RCU?

  See checklist.rst.

- Why the name "RCU"?

  "RCU" stands for "read-copy update".
  listRCU.rst has more information on where this name came from, search
  for "read-copy update" to find it.

- I hear that RCU is patented?  What is with that?

  Yes, it is.  There are several known patents related to RCU,
  search for the string "Patent" in Documentation/RCU/RTFP.txt to find them.
  Of these, one was allowed to lapse by the assignee, and the
  others have been contributed to the Linux kernel under GPL.
  Many (but not all) have long since expired.
  There are now also LGPL implementations of user-level RCU
  available (https://liburcu.org/).

- I hear that RCU needs work in order to support realtime kernels?

  Realtime-friendly RCU are enabled via the CONFIG_PREEMPTION
  kernel configuration parameter.

- Where can I find more information on RCU?

  See the Documentation/RCU/RTFP.txt file.
  Or point your browser at (https://docs.google.com/document/d/1X0lThx8OK0ZgLMqVoXiR4ZrGURHrXK6NyLRbeXe3Xac/edit)
  or (https://docs.google.com/document/d/1GCdQC8SDbb54W1shjEXqGZ0Rq8a6kIeYutdSIajfpLA/edit?usp=sharing).

---

### Documentation RCU Rcu Dereference (`Documentation/RCU/rcu_dereference.rst`)

.. _rcu_dereference_doc:

PROPER CARE AND FEEDING OF RETURN VALUES FROM rcu_dereference()
===============================================================

Proper care and feeding of address and data dependencies is critically
important to correct use of things like RCU.  To this end, the pointers
returned from the rcu_dereference() family of primitives carry address and
data dependencies.  These dependencies extend from the rcu_dereference()
macro's load of the pointer to the later use of that pointer to compute
either the address of a later memory access (representing an address
dependency) or the value written by a later memory access (representing
a data dependency).

Most of the time, these dependencies are preserved, permitting you to
freely use values from rcu_dereference().  For example, dereferencing
(prefix "*"), field selection ("->"), assignment ("="), address-of
("&"), casts, and addition or subtraction of constants all work quite
naturally and safely.  However, because current compilers do not take
either address or data dependencies into account it is still possible
to get into trouble.

Follow these rules to preserve the address and data dependencies emanating
from your calls to rcu_dereference() and friends, thus keeping your RCU
readers working properly:

-	You must use one of the rcu_dereference() family of primitives
	to load an RCU-protected pointer, otherwise CONFIG_PROVE_RCU
	will complain.  Worse yet, your code can see random memory-corruption
	bugs due to games that compilers and DEC Alpha can play.
	Without one of the rcu_dereference() primitives, compilers
	can reload the value, and won't your code have fun with two
	different values for a single pointer!  Without rcu_dereference(),
	DEC Alpha can load a pointer, dereference that pointer, and
	return data preceding initialization that preceded the store
	of the pointer.  (As noted later, in recent kernels READ_ONCE()
	also prevents DEC Alpha from playing these tricks.)

	In addition, the volatile cast in rcu_dereference() prevents the
	compiler from deducing the resulting pointer value.  Please see
	the section entitled "EXAMPLE WHERE THE COMPILER KNOWS TOO MUCH"
	for an example where the compiler can in fact deduce the exact
	value of the pointer, and thus cause misordering.

-	In the special case where data is added but is never removed
	while readers are accessing the structure, READ_ONCE() may be used
	instead of rcu_dereference().  In this case, use of READ_ONCE()
	takes on the role of the lockless_dereference() primitive that
	was removed in v4.15.

-	You are only permitted to use rcu_dereference() on pointer values.
	The compiler simply knows too much about integral values to
	trust it to carry dependencies through integer operations.
	There are a very few exceptions, namely that you can temporarily
	cast the pointer to uintptr_t in order to:

	-	Set bits and clear bits down in the must-be-zero low-order
		bits of that pointer.  This clearly means that the pointer
		must have alignment constraints, for example, this does
		*not* work in general for char* pointers.

	-	XOR bits to translate pointers, as is done in some
		classic buddy-allocator algorithms.

	It is important to cast the value back to pointer before
	doing much of anything else with it.

-	Avoid cancellation when using the "+" and "-" infix arithmetic
	operators.  For example, for a given variable "x", avoid
	"(x-(uintptr_t)x)" for char* pointers.	The compiler is within its
	rights to substitute zero for this sort of expression, so that
	subsequent accesses no longer depend on the rcu_dereference(),
	again possibly resulting in bugs due to misordering.

	Of course, if "p" is a pointer from rcu_dereference(), and "a"
	and "b" are integers that happen to be equal, the expression
	"p+a-b" is safe because its value still necessarily depends on
	the rcu_dereference(), thus maintaining proper ordering.

-	If you are using RCU to protect JITed functions, so that the
	"()" function-invocation operator is applied to a value obtained
	(directly or indirectly) from rcu_dereference(), you may need to
	interact directly with the hardware to flush instruction caches.
	This issue arises on some systems when a newly JITed function is
	using the same memory that was used by an earlier JITed function.

-	Do not use the results from relational operators ("==", "!=",
	">", ">=", "<", or "<=") when dereferencing.  For example,
	the following (quite strange) code is buggy::

		int *p;
		int *q;

		...

		p = rcu_dereference(gp)
		q = &global_q;
		q += p > &oom_p;
		r1 = *q;  /* BUGGY!!! */

	As before, the reason this is buggy is that relational operators
	are often compiled using branches.  And as before, although
	weak-memory machines such as ARM or PowerPC do order stores
	after such branches, but can speculate loads, which can again
	result in misordering bugs.

-	Be very careful about comparing pointers obtained from
	rcu_dereference() against non-NULL values.  As Linus Torvalds
	explained, if the two pointers are equal, the compiler could
	substitute the pointer you are comparing against for the pointer
	obtained from rcu_dereference().  For example::

		p = rcu_dereference(gp);
		if (p == &default_struct)
			do_default(p->a);

	Because the compiler now knows that the value of "p" is exactly
	the address of the variable "default_struct", it is free to
	transform this code into the following::

		p = rcu_dereference(gp);
		if (p == &default_struct)
			do_default(default_struct.a);

	On ARM and Power hardware, the load from "default_struct.a"
	can now be speculated, such that it might happen before the
	rcu_dereference().  This could result in bugs due to misordering.

	However, comparisons are OK in the following cases:

	-	The comparison was against the NULL pointer.  If the
		compiler knows that the pointer is NULL, you had better
		not be dereferencing it anyway.  If the comparison is
		non-equal, the compiler is none the wiser.  Therefore,
		it is safe to compare pointers from rcu_dereference()
		against NULL pointers.

	-	The pointer is never dereferenced after being compared.
		Since there are no subsequent dereferences, the compiler
		cannot use anything it learned from the comparison
		to reorder the non-existent subsequent dereferences.
		This sort of comparison occurs frequently when scanning
		RCU-protected circular linked lists.

		Note that if the pointer comparison is done outside
		of an RCU read-side critical section, and the pointer
		is never dereferenced, rcu_access_pointer() should be
		used in place of rcu_dereference().  In most cases,
		it is best to avoid accidental dereferences by testing
		the rcu_access_pointer() return value directly, without
		assigning it to a variable.

		Within an RCU read-side critical section, there is little
		reason to use rcu_access_pointer().

	-	The comparison is against a pointer that references memory
		that was initialized "a long time ago."  The reason
		this is safe is that even if misordering occurs, the
		misordering will not affect the accesses that follow
		the comparison.  So exactly how long ago is "a long
		time ago"?  Here are some possibilities:

		-	Compile time.

		-	Boot time.

		-	Module-init time for module code.

		-	Prior to kthread creation for kthread code.

		-	During some prior acquisition of the lock that
			we now hold.

		-	Before mod_timer() time for a timer handler.

		There are many other possibilities involving the Linux
		kernel's wide array of primitives that cause code to
		be invoked at a later time.

	-	The pointer being compared against also came from
		rcu_dereference().  In this case, both pointers depend
		on one rcu_dereference() or another, so you get proper
		ordering either way.

		That said, this situation can make certain RCU usage
		bugs more likely to happen.  Which can be a good thing,
		at least if they happen during testing.  An example
		of such an RCU usage bug is shown in the section titled
		"EXAMPLE OF AMPLIFIED RCU-USAGE BUG".

	-	All of the accesses following the comparison are stores,
		so that a control dependency preserves the needed ordering.
		That said, it is easy to get control dependencies wrong.
		Please see the "CONTROL DEPENDENCIES" section of
		Documentation/memory-barriers.txt for more details.

	-	The pointers are not equal *and* the compiler does
		not have enough information to deduce the value of the
		pointer.  Note that the volatile cast in rcu_dereference()
		will normally prevent the compiler from knowing too much.

		However, please note that if the compiler knows that the
		pointer takes on only one of two values, a not-equal
		comparison will provide exactly the information that the
		compiler needs to deduce the value of the pointer.

-	Disable any value-speculation optimizations that your compiler
	might provide, especially if you are making use of feedback-based
	optimizations that take data collected from prior runs.  Such
	value-speculation optimizations reorder operations by design.

	There is one exception to this rule:  Value-speculation
	optimizations that leverage the branch-prediction hardware are
	safe on strongly ordered systems (such as x86), but not on weakly
	ordered systems (such as ARM or Power).  Choose your compiler
	command-line options wisely!


EXAMPLE OF AMPLIFIED RCU-USAGE BUG
----------------------------------

Because updaters can run concurrently with RCU readers, RCU readers can
see stale and/or inconsistent values.  If RCU readers need fresh or
consistent values, which they sometimes do, they need to take proper
precautions.  To see this, consider the following code fragment::

	struct foo {
		int a;
		int b;
		int c;
	};
	struct foo *gp1;
	struct foo *gp2;

	void updater(void)
	{
		struct foo *p;

		p = kmalloc(...);
		if (p == NULL)
			deal_with_it();
		p->a = 42;  /* Each field in its own cache line. */
		p->b = 43;
		p->c = 44;
		rcu_assign_pointer(gp1, p);
		p->b = 143;
		p->c = 144;
		rcu_assign_pointer(gp2, p);
	}

	void reader(void)
	{
		struct foo *p;
		struct foo *q;
		int r1, r2;

		rcu_read_lock();
		p = rcu_dereference(gp2);
		if (p == NULL)
			return;
		r1 = p->b;  /* Guaranteed to get 143. */
		q = rcu_dereference(gp1);  /* Guaranteed non-NULL. */
		if (p == q) {
			/* The compiler decides that q->c is same as p->c. */
			r2 = p->c; /* Could get 44 on weakly order system. */
		} else {
			r2 = p->c - r1; /* Unconditional access to p->c. */
		}
		rcu_read_unlock();
		do_something_with(r1, r2);
	}

You might be surprised that the outcome (r1 == 143 && r2 == 44) is possible,
but you should not be.  After all, the updater might have been invoked
a second time between the time reader() loaded into "r1" and the time
that it loaded into "r2".  The fact that this same result can occur due
to some reordering from the compiler and CPUs is beside the point.

But suppose that the reader needs a consistent view?

Then one approach is to use locking, for example, as follows::

	struct foo {
		int a;
		int b;
		int c;
		spinlock_t lock;
	};
	struct foo *gp1;
	struct foo *gp2;

	void updater(void)
	{
		struct foo *p;

		p = kmalloc(...);
		if (p == NULL)
			deal_with_it();
		spin_lock(&p->lock);
		p->a = 42;  /* Each field in its own cache line. */
		p->b = 43;
		p->c = 44;
		spin_unlock(&p->lock);
		rcu_assign_pointer(gp1, p);
		spin_lock(&p->lock);
		p->b = 143;
		p->c = 144;
		spin_unlock(&p->lock);
		rcu_assign_pointer(gp2, p);
	}

	void reader(void)
	{
		struct foo *p;
		struct foo *q;
		int r1, r2;

		rcu_read_lock();
		p = rcu_dereference(gp2);
		if (p == NULL)
			return;
		spin_lock(&p->lock);
		r1 = p->b;  /* Guaranteed to get 143. */
		q = rcu_dereference(gp1);  /* Guaranteed non-NULL. */
		if (p == q) {
			/* The compiler decides that q->c is same as p->c. */
			r2 = p->c; /* Locking guarantees r2 == 144. */
		} else {
			spin_lock(&q->lock);
			r2 = q->c - r1;
			spin_unlock(&q->lock);
		}
		rcu_read_unlock();
		spin_unlock(&p->lock);
		do_something_with(r1, r2);
	}

As always, use the right tool for the job!


EXAMPLE WHERE THE COMPILER KNOWS TOO MUCH
-----------------------------------------

If a pointer obtained from rcu_dereference() compares not-equal to some
other pointer, the compiler normally has no clue what the value of the
first pointer might be.  This lack of knowledge prevents the compiler
from carrying out optimizations that otherwise might destroy the ordering
guarantees that RCU depends on.  And the volatile cast in rcu_dereference()
should prevent the compiler from guessing the value.

But without rcu_dereference(), the compiler knows more than you might
expect.  Consider the following code fragment::

	struct foo {
		int a;
		int b;
	};
	static struct foo variable1;
	static struct foo variable2;
	static struct foo *gp = &variable1;

	void updater(void)
	{
		initialize_foo(&variable2);
		rcu_assign_pointer(gp, &variable2);
		/*
		 * The above is the only store to gp in this translation unit,
		 * and the address of gp is not exported in any way.
		 */
	}

	int reader(void)
	{
		struct foo *p;

		p = gp;
		barrier();
		if (p == &variable1)
			return p->a; /* Must be variable1.a. */
		else
			return p->b; /* Must be variable2.b. */
	}

Because the compiler can see all stores to "gp", it knows that the only
possible values of "gp" are "variable1" on the one hand and "variable2"
on the other.  The comparison in reader() therefore tells the compiler
the exact value of "p" even in the not-equals case.  This allows the
compiler to make the return values independent of the load from "gp",
in turn destroying the ordering between this load and the loads of the
return values.  This can result in "p->b" returning pre-initialization
garbage values on weakly ordered systems.

In short, rcu_dereference() is *not* optional when you are going to
dereference the resulting pointer.


WHICH MEMBER OF THE rcu_dereference() FAMILY SHOULD YOU USE?
------------------------------------------------------------

First, please avoid using rcu_dereference_raw() and also please avoid
using rcu_dereference_check() and rcu_dereference_protected() with a
second argument with a constant value of 1 (or true, for that matter).
With that caution out of the way, here is some guidance for which
member of the rcu_dereference() to use in various situations:

1.	If the access needs to be within an RCU read-side critical
	section, use rcu_dereference().  With the new consolidated
	RCU flavors, an RCU read-side critical section is entered
	using rcu_read_lock(), anything that disables bottom halves,
	anything that disables interrupts, or anything that disables
	preemption.  Please note that spinlock critical sections
	are also implied RCU read-side critical sections, even when
	they are preemptible, as they are in kernels built with
	CONFIG_PREEMPT_RT=y.

2.	If the access might be within an RCU read-side critical section
	on the one hand, or protected by (say) my_lock on the other,
	use rcu_dereference_check(), for example::

		p1 = rcu_dereference_check(p->rcu_protected_pointer,
					   lockdep_is_held(&my_lock));


3.	If the access might be within an RCU read-side critical section
	on the one hand, or protected by either my_lock or your_lock on
	the other, again use rcu_dereference_check(), for example::

		p1 = rcu_dereference_check(p->rcu_protected_pointer,
					   lockdep_is_held(&my_lock) ||
					   lockdep_is_held(&your_lock));

4.	If the access is on the update side, so that it is always protected
	by my_lock, use rcu_dereference_protected()::

		p1 = rcu_dereference_protected(p->rcu_protected_pointer,
					       lockdep_is_held(&my_lock));

	This can be extended to handle multiple locks as in #3 above,
	and both can be extended to check other conditions as well.

5.	If the protection is supplied by the caller, and is thus unknown
	to this code, that is the rare case when rcu_dereference_raw()
	is appropriate.  In addition, rcu_dereference_raw() might be
	appropriate when the lockdep expression would be excessively
	complex, except that a better approach in that case might be to
	take a long hard look at your synchronization design.  Still,
	there are data-locking cases where any one of a very large number
	of locks or reference counters suffices to protect the pointer,
	so rcu_dereference_raw() does have its place.

	However, its place is probably quite a bit smaller than one
	might expect given the number of uses in the current kernel.
	Ditto for its synonym, rcu_dereference_check( ... , 1), and
	its close relative, rcu_dereference_protected(... , 1).


SPARSE CHECKING OF RCU-PROTECTED POINTERS
-----------------------------------------

The sparse static-analysis tool checks for non-RCU access to RCU-protected
pointers, which can result in "interesting" bugs due to compiler
optimizations involving invented loads and perhaps also load tearing.
For example, suppose someone mistakenly does something like this::

	p = q->rcu_protected_pointer;
	do_something_with(p->a);
	do_something_else_with(p->b);

If register pressure is high, the compiler might optimize "p" out
of existence, transforming the code to something like this::

	do_something_with(q->rcu_protected_pointer->a);
	do_something_else_with(q->rcu_protected_pointer->b);

This could fatally disappoint your code if q->rcu_protected_pointer
changed in the meantime.  Nor is this a theoretical problem:  Exactly
this sort of bug cost Paul E. McKenney (and several of his innocent
colleagues) a three-day weekend back in the early 1990s.

Load tearing could of course result in dereferencing a mashup of a pair
of pointers, which also might fatally disappoint your code.

These problems could have been avoided simply by making the code instead
read as follows::

	p = rcu_dereference(q->rcu_protected_pointer);
	do_something_with(p->a);
	do_something_else_with(p->b);

Unfortunately, these sorts of bugs can be extremely hard to spot during
review.  This is where the sparse tool comes into play, along with the
"__rcu" marker.  If you mark a pointer declaration, whether in a structure
or as a formal parameter, with "__rcu", which tells sparse to complain if
this pointer is accessed directly.  It will also cause sparse to complain
if a pointer not marked with "__rcu" is accessed using rcu_dereference()
and friends.  For example, ->rcu_protected_pointer might be declared as
follows::

	struct foo __rcu *rcu_protected_pointer;

Use of "__rcu" is opt-in.  If you choose not to use it, then you should
ignore the sparse warnings.

---

### Documentation RCU Rcubarrier (`Documentation/RCU/rcubarrier.rst`)

.. _rcu_barrier:

RCU and Unloadable Modules
==========================

[Originally published in LWN Jan. 14, 2007: http://lwn.net/Articles/217484/]

RCU updaters sometimes use call_rcu() to initiate an asynchronous wait for
a grace period to elapse.  This primitive takes a pointer to an rcu_head
struct placed within the RCU-protected data structure and another pointer
to a function that may be invoked later to free that structure. Code to
delete an element p from the linked list from IRQ context might then be
as follows::

	list_del_rcu(p);
	call_rcu(&p->rcu, p_callback);

Since call_rcu() never blocks, this code can safely be used from within
IRQ context. The function p_callback() might be defined as follows::

	static void p_callback(struct rcu_head *rp)
	{
		struct pstruct *p = container_of(rp, struct pstruct, rcu);

		kfree(p);
	}


Unloading Modules That Use call_rcu()
-------------------------------------

But what if the p_callback() function is defined in an unloadable module?

If we unload the module while some RCU callbacks are pending,
the CPUs executing these callbacks are going to be severely
disappointed when they are later invoked, as fancifully depicted at
http://lwn.net/images/ns/kernel/rcu-drop.jpg.

We could try placing a synchronize_rcu() in the module-exit code path,
but this is not sufficient. Although synchronize_rcu() does wait for a
grace period to elapse, it does not wait for the callbacks to complete.

One might be tempted to try several back-to-back synchronize_rcu()
calls, but this is still not guaranteed to work. If there is a very
heavy RCU-callback load, then some of the callbacks might be deferred in
order to allow other processing to proceed. For but one example, such
deferral is required in realtime kernels in order to avoid excessive
scheduling latencies.


rcu_barrier()
-------------

This situation can be handled by the rcu_barrier() primitive.  Rather
than waiting for a grace period to elapse, rcu_barrier() waits for all
outstanding RCU callbacks to complete.  Please note that rcu_barrier()
does **not** imply synchronize_rcu(), in particular, if there are no RCU
callbacks queued anywhere, rcu_barrier() is within its rights to return
immediately, without waiting for anything, let alone a grace period.

Pseudo-code using rcu_barrier() is as follows:

   1. Prevent any new RCU callbacks from being posted.
   2. Execute rcu_barrier().
   3. Allow the module to be unloaded.

There is also an srcu_barrier() function for SRCU, and you of course
must match the flavor of srcu_barrier() with that of call_srcu().
If your module uses multiple srcu_struct structures, then it must also
use multiple invocations of srcu_barrier() when unloading that module.
For example, if it uses call_rcu(), call_srcu() on srcu_struct_1, and
call_srcu() on srcu_struct_2, then the following three lines of code
will be required when unloading::

  1  rcu_barrier();
  2  srcu_barrier(&srcu_struct_1);
  3  srcu_barrier(&srcu_struct_2);

If latency is of the essence, workqueues could be used to run these
three functions concurrently.

An ancient version of the rcutorture module makes use of rcu_barrier()
in its exit function as follows::

  1  static void
  2  rcu_torture_cleanup(void)
  3  {
  4    int i;
  5
  6    fullstop = 1;
  7    if (shuffler_task != NULL) {
  8      VERBOSE_PRINTK_STRING("Stopping rcu_torture_shuffle task");
  9      kthread_stop(shuffler_task);
 10    }
 11    shuffler_task = NULL;
 12
 13    if (writer_task != NULL) {
 14      VERBOSE_PRINTK_STRING("Stopping rcu_torture_writer task");
 15      kthread_stop(writer_task);
 16    }
 17    writer_task = NULL;
 18
 19    if (reader_tasks != NULL) {
 20      for (i = 0; i < nrealreaders; i++) {
 21        if (reader_tasks[i] != NULL) {
 22          VERBOSE_PRINTK_STRING(
 23            "Stopping rcu_torture_reader task");
 24          kthread_stop(reader_tasks[i]);
 25        }
 26        reader_tasks[i] = NULL;
 27      }
 28      kfree(reader_tasks);
 29      reader_tasks = NULL;
 30    }
 31    rcu_torture_current = NULL;
 32
 33    if (fakewriter_tasks != NULL) {
 34      for (i = 0; i < nfakewriters; i++) {
 35        if (fakewriter_tasks[i] != NULL) {
 36          VERBOSE_PRINTK_STRING(
 37            "Stopping rcu_torture_fakewriter task");
 38          kthread_stop(fakewriter_tasks[i]);
 39        }
 40        fakewriter_tasks[i] = NULL;
 41      }
 42      kfree(fakewriter_tasks);
 43      fakewriter_tasks = NULL;
 44    }
 45
 46    if (stats_task != NULL) {
 47      VERBOSE_PRINTK_STRING("Stopping rcu_torture_stats task");
 48      kthread_stop(stats_task);
 49    }
 50    stats_task = NULL;
 51
 52    /* Wait for all RCU callbacks to fire. */
 53    rcu_barrier();
 54
 55    rcu_torture_stats_print(); /* -After- the stats thread is stopped! */
 56
 57    if (cur_ops->cleanup != NULL)
 58      cur_ops->cleanup();
 59    if (atomic_read(&n_rcu_torture_error))
 60      rcu_torture_print_module_parms("End of test: FAILURE");
 61    else
 62      rcu_torture_print_module_parms("End of test: SUCCESS");
 63  }

Line 6 sets a global variable that prevents any RCU callbacks from
re-posting themselves. This will not be necessary in most cases, since
RCU callbacks rarely include calls to call_rcu(). However, the rcutorture
module is an exception to this rule, and therefore needs to set this
global variable.

Lines 7-50 stop all the kernel tasks associated with the rcutorture
module. Therefore, once execution reaches line 53, no more rcutorture
RCU callbacks will be posted. The rcu_barrier() call on line 53 waits
for any pre-existing callbacks to complete.

Then lines 55-62 print status and do operation-specific cleanup, and
then return, permitting the module-unload operation to be completed.

.. _rcubarrier_quiz_1:

Quick Quiz #1:
	Is there any other situation where rcu_barrier() might
	be required?

:ref:`Answer to Quick Quiz #1 <answer_rcubarrier_quiz_1>`

Your module might have additional complications. For example, if your
module invokes call_rcu() from timers, you will need to first refrain
from posting new timers, cancel (or wait for) all the already-posted
timers, and only then invoke rcu_barrier() to wait for any remaining
RCU callbacks to complete.

Of course, if your module uses call_rcu(), you will need to invoke
rcu_barrier() before unloading.  Similarly, if your module uses
call_srcu(), you will need to invoke srcu_barrier() before unloading,
and on the same srcu_struct structure.  If your module uses call_rcu()
**and** call_srcu(), then (as noted above) you will need to invoke
rcu_barrier() **and** srcu_barrier().


Implementing rcu_barrier()
--------------------------

Dipankar Sarma's implementation of rcu_barrier() makes use of the fact
that RCU callbacks are never reordered once queued on one of the per-CPU
queues. His implementation queues an RCU callback on each of the per-CPU
callback queues, and then waits until they have all started executing, at
which point, all earlier RCU callbacks are guaranteed to have completed.

The original code for rcu_barrier() was roughly as follows::

  1  void rcu_barrier(void)
  2  {
  3    BUG_ON(in_interrupt());
  4    /* Take cpucontrol mutex to protect against CPU hotplug */
  5    mutex_lock(&rcu_barrier_mutex);
  6    init_completion(&rcu_barrier_completion);
  7    atomic_set(&rcu_barrier_cpu_count, 1);
  8    on_each_cpu(rcu_barrier_func, NULL, 0, 1);
  9    if (atomic_dec_and_test(&rcu_barrier_cpu_count))
 10      complete(&rcu_barrier_completion);
 11    wait_for_completion(&rcu_barrier_completion);
 12    mutex_unlock(&rcu_barrier_mutex);
 13  }

Line 3 verifies that the caller is in process context, and lines 5 and 12
use rcu_barrier_mutex to ensure that only one rcu_barrier() is using the
global completion and counters at a time, which are initialized on lines
6 and 7. Line 8 causes each CPU to invoke rcu_barrier_func(), which is
shown below. Note that the final "1" in on_each_cpu()'s argument list
ensures that all the calls to rcu_barrier_func() will have completed
before on_each_cpu() returns. Line 9 removes the initial count from
rcu_barrier_cpu_count, and if this count is now zero, line 10 finalizes
the completion, which prevents line 11 from blocking.  Either way,
line 11 then waits (if needed) for the completion.

.. _rcubarrier_quiz_2:

Quick Quiz #2:
	Why doesn't line 8 initialize rcu_barrier_cpu_count to zero,
	thereby avoiding the need for lines 9 and 10?

:ref:`Answer to Quick Quiz #2 <answer_rcubarrier_quiz_2>`

This code was rewritten in 2008 and several times thereafter, but this
still gives the general idea.

The rcu_barrier_func() runs on each CPU, where it invokes call_rcu()
to post an RCU callback, as follows::

  1  static void rcu_barrier_func(void *notused)
  2  {
  3    int cpu = smp_processor_id();
  4    struct rcu_data *rdp = &per_cpu(rcu_data, cpu);
  5    struct rcu_head *head;
  6
  7    head = &rdp->barrier;
  8    atomic_inc(&rcu_barrier_cpu_count);
  9    call_rcu(head, rcu_barrier_callback);
 10  }

Lines 3 and 4 locate RCU's internal per-CPU rcu_data structure,
which contains the struct rcu_head that needed for the later call to
call_rcu(). Line 7 picks up a pointer to this struct rcu_head, and line
8 increments the global counter. This counter will later be decremented
by the callback. Line 9 then registers the rcu_barrier_callback() on
the current CPU's queue.

The rcu_barrier_callback() function simply atomically decrements the
rcu_barrier_cpu_count variable and finalizes the completion when it
reaches zero, as follows::

  1  static void rcu_barrier_callback(struct rcu_head *notused)
  2  {
  3    if (atomic_dec_and_test(&rcu_barrier_cpu_count))
  4      complete(&rcu_barrier_completion);
  5  }

.. _rcubarrier_quiz_3:

Quick Quiz #3:
	What happens if CPU 0's rcu_barrier_func() executes
	immediately (thus incrementing rcu_barrier_cpu_count to the
	value one), but the other CPU's rcu_barrier_func() invocations
	are delayed for a full grace period? Couldn't this result in
	rcu_barrier() returning prematurely?

:ref:`Answer to Quick Quiz #3 <answer_rcubarrier_quiz_3>`

The current rcu_barrier() implementation is more complex, due to the need
to avoid disturbing idle CPUs (especially on battery-powered systems)
and the need to minimally disturb non-idle CPUs in real-time systems.
In addition, a great many optimizations have been applied.  However,
the code above illustrates the concepts.


rcu_barrier() Summary
---------------------

The rcu_barrier() primitive is used relatively infrequently, since most
code using RCU is in the core kernel rather than in modules. However, if
you are using RCU from an unloadable module, you need to use rcu_barrier()
so that your module may be safely unloaded.


Answers to Quick Quizzes
------------------------

.. _answer_rcubarrier_quiz_1:

Quick Quiz #1:
	Is there any other situation where rcu_barrier() might
	be required?

Answer:
	Interestingly enough, rcu_barrier() was not originally
	implemented for module unloading. Nikita Danilov was using
	RCU in a filesystem, which resulted in a similar situation at
	filesystem-unmount time. Dipankar Sarma coded up rcu_barrier()
	in response, so that Nikita could invoke it during the
	filesystem-unmount process.

	Much later, yours truly hit the RCU module-unload problem when
	implementing rcutorture, and found that rcu_barrier() solves
	this problem as well.

:ref:`Back to Quick Quiz #1 <rcubarrier_quiz_1>`

.. _answer_rcubarrier_quiz_2:

Quick Quiz #2:
	Why doesn't line 8 initialize rcu_barrier_cpu_count to zero,
	thereby avoiding the need for lines 9 and 10?

Answer:
	Suppose that the on_each_cpu() function shown on line 8 was
	delayed, so that CPU 0's rcu_barrier_func() executed and
	the corresponding grace period elapsed, all before CPU 1's
	rcu_barrier_func() started executing.  This would result in
	rcu_barrier_cpu_count being decremented to zero, so that line
	11's wait_for_completion() would return immediately, failing to
	wait for CPU 1's callbacks to be invoked.

	Note that this was not a problem when the rcu_barrier() code
	was first added back in 2005.  This is because on_each_cpu()
	disables preemption, which acted as an RCU read-side critical
	section, thus preventing CPU 0's grace period from completing
	until on_each_cpu() had dealt with all of the CPUs.

	However, with the RCU flavor consolidation around v4.20, this
	possibility was once again ruled out, because the consolidated
	RCU once again waits on nonpreemptible regions of code.

	Nevertheless, that extra count might still be a good idea.
	Relying on these sort of accidents of implementation can result
	in later surprise bugs when the implementation changes.

:ref:`Back to Quick Quiz #2 <rcubarrier_quiz_2>`

.. _answer_rcubarrier_quiz_3:

Quick Quiz #3:
	What happens if CPU 0's rcu_barrier_func() executes
	immediately (thus incrementing rcu_barrier_cpu_count to the
	value one), but the other CPU's rcu_barrier_func() invocations
	are delayed for a full grace period? Couldn't this result in
	rcu_barrier() returning prematurely?

Answer:
	This cannot happen. The reason is that on_each_cpu() has its last
	argument, the wait flag, set to "1". This flag is passed through
	to smp_call_function() and further to smp_call_function_on_cpu(),
	causing this latter to spin until the cross-CPU invocation of
	rcu_barrier_func() has completed. This by itself would prevent
	a grace period from completing on non-CONFIG_PREEMPTION kernels,
	since each CPU must undergo a context switch (or other quiescent
	state) before the grace period can complete. However, this is
	of no use in CONFIG_PREEMPTION kernels.

	Therefore, on_each_cpu() disables preemption across its call
	to smp_call_function() and also across the local call to
	rcu_barrier_func(). Because recent RCU implementations treat
	preemption-disabled regions of code as RCU read-side critical
	sections, this prevents grace periods from completing. This
	means that all CPUs have executed rcu_barrier_func() before
	the first rcu_barrier_callback() can possibly execute, in turn
	preventing rcu_barrier_cpu_count from prematurely reaching zero.

	But if on_each_cpu() ever decides to forgo disabling preemption,
	as might well happen due to real-time latency considerations,
	initializing rcu_barrier_cpu_count to one will save the day.

:ref:`Back to Quick Quiz #3 <rcubarrier_quiz_3>`

---

### Documentation RCU Rculist Nulls (`Documentation/RCU/rculist_nulls.rst`)

.. SPDX-License-Identifier: GPL-2.0

=================================================
Using RCU hlist_nulls to protect list and objects
=================================================

This section describes how to use hlist_nulls to
protect read-mostly linked lists and
objects using SLAB_TYPESAFE_BY_RCU allocations.

Please read the basics in listRCU.rst.

Using 'nulls'
=============

Using special makers (called 'nulls') is a convenient way
to solve following problem.

Without 'nulls', a typical RCU linked list managing objects which are
allocated with SLAB_TYPESAFE_BY_RCU kmem_cache can use the following
algorithms.  Following examples assume 'obj' is a pointer to such
objects, which is having below type.

::

  struct object {
    struct hlist_node obj_node;
    atomic_t refcnt;
    unsigned int key;
  };

1) Lookup algorithm
-------------------

::

  begin:
  rcu_read_lock();
  obj = lockless_lookup(key);
  if (obj) {
    if (!try_get_ref(obj)) { // might fail for free objects
      rcu_read_unlock();
      goto begin;
    }
    /*
    * Because a writer could delete object, and a writer could
    * reuse these object before the RCU grace period, we
    * must check key after getting the reference on object
    */
    if (obj->key != key) { // not the object we expected
      put_ref(obj);
      rcu_read_unlock();
      goto begin;
    }
  }
  rcu_read_unlock();

Beware that lockless_lookup(key) cannot use traditional hlist_for_each_entry_rcu()
but a version with an additional memory barrier (smp_rmb())

::

  lockless_lookup(key)
  {
    struct hlist_node *node, *next;
    for (pos = rcu_dereference((head)->first);
         pos && ({ next = pos->next; smp_rmb(); prefetch(next); 1; }) &&
         ({ obj = hlist_entry(pos, typeof(*obj), obj_node); 1; });
         pos = rcu_dereference(next))
      if (obj->key == key)
        return obj;
    return NULL;
  }

And note the traditional hlist_for_each_entry_rcu() misses this smp_rmb()::

  struct hlist_node *node;
  for (pos = rcu_dereference((head)->first);
       pos && ({ prefetch(pos->next); 1; }) &&
       ({ obj = hlist_entry(pos, typeof(*obj), obj_node); 1; });
       pos = rcu_dereference(pos->next))
    if (obj->key == key)
      return obj;
  return NULL;

Quoting Corey Minyard::

  "If the object is moved from one list to another list in-between the
  time the hash is calculated and the next field is accessed, and the
  object has moved to the end of a new list, the traversal will not
  complete properly on the list it should have, since the object will
  be on the end of the new list and there's not a way to tell it's on a
  new list and restart the list traversal. I think that this can be
  solved by pre-fetching the "next" field (with proper barriers) before
  checking the key."

2) Insertion algorithm
----------------------

We need to make sure a reader cannot read the new 'obj->obj_node.next' value
and previous value of 'obj->key'. Otherwise, an item could be deleted
from a chain, and inserted into another chain. If new chain was empty
before the move, 'next' pointer is NULL, and lockless reader can not
detect the fact that it missed following items in original chain.

::

  /*
   * Please note that new inserts are done at the head of list,
   * not in the middle or end.
   */
  obj = kmem_cache_alloc(...);
  lock_chain(); // typically a spin_lock()
  obj->key = key;
  atomic_set_release(&obj->refcnt, 1); // key before refcnt
  hlist_add_head_rcu(&obj->obj_node, list);
  unlock_chain(); // typically a spin_unlock()


3) Removal algorithm
--------------------

Nothing special here, we can use a standard RCU hlist deletion.
But thanks to SLAB_TYPESAFE_BY_RCU, beware a deleted object can be reused
very very fast (before the end of RCU grace period)

::

  if (put_last_reference_on(obj) {
    lock_chain(); // typically a spin_lock()
    hlist_del_init_rcu(&obj->obj_node);
    unlock_chain(); // typically a spin_unlock()
    kmem_cache_free(cachep, obj);
  }



--------------------------------------------------------------------------

Avoiding extra smp_rmb()
========================

With hlist_nulls we can avoid extra smp_rmb() in lockless_lookup().

For example, if we choose to store the slot number as the 'nulls'
end-of-list marker for each slot of the hash table, we can detect
a race (some writer did a delete and/or a move of an object
to another chain) checking the final 'nulls' value if
the lookup met the end of chain. If final 'nulls' value
is not the slot number, then we must restart the lookup at
the beginning. If the object was moved to the same chain,
then the reader doesn't care: It might occasionally
scan the list again without harm.

Note that using hlist_nulls means the type of 'obj_node' field of
'struct object' becomes 'struct hlist_nulls_node'.


1) lookup algorithm
-------------------

::

  head = &table[slot];
  begin:
  rcu_read_lock();
  hlist_nulls_for_each_entry_rcu(obj, node, head, obj_node) {
    if (obj->key == key) {
      if (!try_get_ref(obj)) { // might fail for free objects
	rcu_read_unlock();
        goto begin;
      }
      if (obj->key != key) { // not the object we expected
        put_ref(obj);
	rcu_read_unlock();
        goto begin;
      }
      goto out;
    }
  }

  // If the nulls value we got at the end of this lookup is
  // not the expected one, we must restart lookup.
  // We probably met an item that was moved to another chain.
  if (get_nulls_value(node) != slot) {
    put_ref(obj);
    rcu_read_unlock();
    goto begin;
  }
  obj = NULL;

  out:
  rcu_read_unlock();

2) Insert algorithm
-------------------

Same to the above one, but uses hlist_nulls_add_head_rcu() instead of
hlist_add_head_rcu().

::

  /*
   * Please note that new inserts are done at the head of list,
   * not in the middle or end.
   */
  obj = kmem_cache_alloc(cachep);
  lock_chain(); // typically a spin_lock()
  obj->key = key;
  atomic_set_release(&obj->refcnt, 1); // key before refcnt
  /*
   * insert obj in RCU way (readers might be traversing chain)
   */
  hlist_nulls_add_head_rcu(&obj->obj_node, list);
  unlock_chain(); // typically a spin_unlock()

---

### Documentation RCU Rcuref (`Documentation/RCU/rcuref.rst`)

.. SPDX-License-Identifier: GPL-2.0

====================================================================
Reference-count design for elements of lists/arrays protected by RCU
====================================================================


Please note that the percpu-ref feature is likely your first
stop if you need to combine reference counts and RCU.  Please see
include/linux/percpu-refcount.h for more information.  However, in
those unusual cases where percpu-ref would consume too much memory,
please read on.

------------------------------------------------------------------------

Reference counting on elements of lists which are protected by traditional
reader/writer spinlocks or semaphores are straightforward:

CODE LISTING A::

    1.					    2.
    add()				    search_and_reference()
    {					    {
	alloc_object				read_lock(&list_lock);
	...					search_for_element
	atomic_set(&el->rc, 1);			atomic_inc(&el->rc);
	write_lock(&list_lock);			 ...
	add_element				read_unlock(&list_lock);
	...					...
	write_unlock(&list_lock);	   }
    }

    3.					    4.
    release_referenced()		    delete()
    {					    {
	...					write_lock(&list_lock);
	if(atomic_dec_and_test(&el->rc))	...
	    kfree(el);
	...					remove_element
    }						write_unlock(&list_lock);
						...
						if (atomic_dec_and_test(&el->rc))
						    kfree(el);
						...
					    }

If this list/array is made lock free using RCU as in changing the
write_lock() in add() and delete() to spin_lock() and changing read_lock()
in search_and_reference() to rcu_read_lock(), the atomic_inc() in
search_and_reference() could potentially hold reference to an element which
has already been deleted from the list/array.  Use atomic_inc_not_zero()
in this scenario as follows:

CODE LISTING B::

    1.					    2.
    add()				    search_and_reference()
    {					    {
	alloc_object				rcu_read_lock();
	...					search_for_element
	atomic_set(&el->rc, 1);			if (!atomic_inc_not_zero(&el->rc)) {
	spin_lock(&list_lock);			    rcu_read_unlock();
						    return FAIL;
	add_element				}
	...					...
	spin_unlock(&list_lock);		rcu_read_unlock();
    }					    }
    3.					    4.
    release_referenced()		    delete()
    {					    {
	...					spin_lock(&list_lock);
	if (atomic_dec_and_test(&el->rc))	...
	    call_rcu(&el->head, el_free);	remove_element
	...					spin_unlock(&list_lock);
    }						...
						if (atomic_dec_and_test(&el->rc))
						    call_rcu(&el->head, el_free);
						...
					    }

Sometimes, a reference to the element needs to be obtained in the
update (write) stream.	In such cases, atomic_inc_not_zero() might be
overkill, since we hold the update-side spinlock.  One might instead
use atomic_inc() in such cases.

It is not always convenient to deal with "FAIL" in the
search_and_reference() code path.  In such cases, the
atomic_dec_and_test() may be moved from delete() to el_free()
as follows:

CODE LISTING C::

    1.					    2.
    add()				    search_and_reference()
    {					    {
	alloc_object				rcu_read_lock();
	...					search_for_element
	atomic_set(&el->rc, 1);			atomic_inc(&el->rc);
	spin_lock(&list_lock);			...

	add_element				rcu_read_unlock();
	...				    }
	spin_unlock(&list_lock);	    4.
    }					    delete()
    3.					    {
    release_referenced()			spin_lock(&list_lock);
    {						...
	...					remove_element
	if (atomic_dec_and_test(&el->rc))	spin_unlock(&list_lock);
	    kfree(el);				...
	...					call_rcu(&el->head, el_free);
    }						...
    5.					    }
    void el_free(struct rcu_head *rhp)
    {
	release_referenced();
    }

The key point is that the initial reference added by add() is not removed
until after a grace period has elapsed following removal.  This means that
search_and_reference() cannot find this element, which means that the value
of el->rc cannot increase.  Thus, once it reaches zero, there are no
readers that can or ever will be able to reference the element.	 The
element can therefore safely be freed.	This in turn guarantees that if
any reader finds the element, that reader may safely acquire a reference
without checking the value of the reference counter.

A clear advantage of the RCU-based pattern in listing C over the one
in listing B is that any call to search_and_reference() that locates
a given object will succeed in obtaining a reference to that object,
even given a concurrent invocation of delete() for that same object.
Similarly, a clear advantage of both listings B and C over listing A is
that a call to delete() is not delayed even if there are an arbitrarily
large number of calls to search_and_reference() searching for the same
object that delete() was invoked on.  Instead, all that is delayed is
the eventual invocation of kfree(), which is usually not a problem on
modern computer systems, even the small ones.

In cases where delete() can sleep, synchronize_rcu() can be called from
delete(), so that el_free() can be subsumed into delete as follows::

    4.
    delete()
    {
	spin_lock(&list_lock);
	...
	remove_element
	spin_unlock(&list_lock);
	...
	synchronize_rcu();
	if (atomic_dec_and_test(&el->rc))
	    kfree(el);
	...
    }

As additional examples in the kernel, the pattern in listing C is used by
reference counting of struct pid, while the pattern in listing B is used by
struct posix_acl.

---

### Documentation RCU Stallwarn (`Documentation/RCU/stallwarn.rst`)

.. SPDX-License-Identifier: GPL-2.0

==============================
Using RCU's CPU Stall Detector
==============================

This document first discusses what sorts of issues RCU's CPU stall
detector can locate, and then discusses kernel parameters and Kconfig
options that can be used to fine-tune the detector's operation.  Finally,
this document explains the stall detector's "splat" format.


What Causes RCU CPU Stall Warnings?
===================================

So your kernel printed an RCU CPU stall warning.  The next question is
"What caused it?"  The following problems can result in RCU CPU stall
warnings:

-	A CPU looping in an RCU read-side critical section.

-	A CPU looping with interrupts disabled.

-	A CPU looping with preemption disabled.

-	A CPU looping with bottom halves disabled.

-	For !CONFIG_PREEMPTION kernels, a CPU looping anywhere in the
	kernel without potentially invoking schedule().  If the looping
	in the kernel is really expected and desirable behavior, you
	might need to add some calls to cond_resched().

-	Booting Linux using a console connection that is too slow to
	keep up with the boot-time console-message rate.  For example,
	a 115Kbaud serial console can be *way* too slow to keep up
	with boot-time message rates, and will frequently result in
	RCU CPU stall warning messages.  Especially if you have added
	debug printk()s.

-	Anything that prevents RCU's grace-period kthreads from running.
	This can result in the "All QSes seen" console-log message.
	This message will include information on when the kthread last
	ran and how often it should be expected to run.  It can also
	result in the ``rcu_.*kthread starved for`` console-log message,
	which will include additional debugging information.

-	A CPU-bound real-time task in a CONFIG_PREEMPTION kernel, which might
	happen to preempt a low-priority task in the middle of an RCU
	read-side critical section.   This is especially damaging if
	that low-priority task is not permitted to run on any other CPU,
	in which case the next RCU grace period can never complete, which
	will eventually cause the system to run out of memory and hang.
	While the system is in the process of running itself out of
	memory, you might see stall-warning messages.

-	A CPU-bound real-time task in a CONFIG_PREEMPT_RT kernel that
	is running at a higher priority than the RCU softirq threads.
	This will prevent RCU callbacks from ever being invoked,
	and in a CONFIG_PREEMPT_RCU kernel will further prevent
	RCU grace periods from ever completing.  Either way, the
	system will eventually run out of memory and hang.  In the
	CONFIG_PREEMPT_RCU case, you might see stall-warning
	messages.

	You can use the rcutree.kthread_prio kernel boot parameter to
	increase the scheduling priority of RCU's kthreads, which can
	help avoid this problem.  However, please note that doing this
	can increase your system's context-switch rate and thus degrade
	performance.

-	A periodic interrupt whose handler takes longer than the time
	interval between successive pairs of interrupts.  This can
	prevent RCU's kthreads and softirq handlers from running.
	Note that certain high-overhead debugging options, for example
	the function_graph tracer, can result in interrupt handler taking
	considerably longer than normal, which can in turn result in
	RCU CPU stall warnings.

-	Testing a workload on a fast system, tuning the stall-warning
	timeout down to just barely avoid RCU CPU stall warnings, and then
	running the same workload with the same stall-warning timeout on a
	slow system.  Note that thermal throttling and on-demand governors
	can cause a single system to be sometimes fast and sometimes slow!

-	A hardware or software issue shuts off the scheduler-clock
	interrupt on a CPU that is not in dyntick-idle mode.  This
	problem really has happened, and seems to be most likely to
	result in RCU CPU stall warnings for CONFIG_NO_HZ_COMMON=n kernels.

-	A hardware or software issue that prevents time-based wakeups
	from occurring.  These issues can range from misconfigured or
	buggy timer hardware through bugs in the interrupt or exception
	path (whether hardware, firmware, or software) through bugs
	in Linux's timer subsystem through bugs in the scheduler, and,
	yes, even including bugs in RCU itself.  It can also result in
	the ``rcu_.*timer wakeup didn't happen for`` console-log message,
	which will include additional debugging information.

-	A timer issue causes time to appear to jump forward, so that RCU
	believes that the RCU CPU stall-warning timeout has been exceeded
	when in fact much less time has passed.  This could be due to
	timer hardware bugs, timer driver bugs, or even corruption of
	the "jiffies" global variable.	These sorts of timer hardware
	and driver bugs are not uncommon when testing new hardware.

-	A low-level kernel issue that either fails to invoke one of the
	variants of rcu_eqs_enter(true), rcu_eqs_exit(true), ct_idle_enter(),
	ct_idle_exit(), ct_irq_enter(), or ct_irq_exit() on the one
	hand, or that invokes one of them too many times on the other.
	Historically, the most frequent issue has been an omission
	of either irq_enter() or irq_exit(), which in turn invoke
	ct_irq_enter() or ct_irq_exit(), respectively.  Building your
	kernel with CONFIG_RCU_EQS_DEBUG=y can help track down these types
	of issues, which sometimes arise in architecture-specific code.

-	A bug in the RCU implementation.

-	A hardware failure.  This is quite unlikely, but is not at all
	uncommon in large datacenter.  In one memorable case some decades
	back, a CPU failed in a running system, becoming unresponsive,
	but not causing an immediate crash.  This resulted in a series
	of RCU CPU stall warnings, eventually leading to the realization
	that the CPU had failed.

The RCU, RCU-sched, RCU-tasks, and RCU-tasks-trace implementations have
CPU stall warning.  Note that SRCU does *not* have CPU stall warnings.
Please note that RCU only detects CPU stalls when there is a grace period
in progress.  No grace period, no CPU stall warnings.

To diagnose the cause of the stall, inspect the stack traces.
The offending function will usually be near the top of the stack.
If you have a series of stall warnings from a single extended stall,
comparing the stack traces can often help determine where the stall
is occurring, which will usually be in the function nearest the top of
that portion of the stack which remains the same from trace to trace.
If you can reliably trigger the stall, ftrace can be quite helpful.

RCU bugs can often be debugged with the help of CONFIG_RCU_TRACE
and with RCU's event tracing.  For information on RCU's event tracing,
see include/trace/events/rcu.h.


Fine-Tuning the RCU CPU Stall Detector
======================================

The rcuupdate.rcu_cpu_stall_suppress module parameter disables RCU's
CPU stall detector, which detects conditions that unduly delay RCU grace
periods.  This module parameter enables CPU stall detection by default,
but may be overridden via boot-time parameter or at runtime via sysfs.
The stall detector's idea of what constitutes "unduly delayed" is
controlled by a set of kernel configuration variables and cpp macros:

CONFIG_RCU_CPU_STALL_TIMEOUT
----------------------------

	This kernel configuration parameter defines the period of time
	that RCU will wait from the beginning of a grace period until it
	issues an RCU CPU stall warning.  This time period is normally
	21 seconds.

	This configuration parameter may be changed at runtime via the
	/sys/module/rcupdate/parameters/rcu_cpu_stall_timeout, however
	this parameter is checked only at the beginning of a cycle.
	So if you are 10 seconds into a 40-second stall, setting this
	sysfs parameter to (say) five will shorten the timeout for the
	*next* stall, or the following warning for the current stall
	(assuming the stall lasts long enough).  It will not affect the
	timing of the next warning for the current stall.

	Stall-warning messages may be enabled and disabled completely via
	/sys/module/rcupdate/parameters/rcu_cpu_stall_suppress.

CONFIG_RCU_EXP_CPU_STALL_TIMEOUT
--------------------------------

	Same as the CONFIG_RCU_CPU_STALL_TIMEOUT parameter but only for
	the expedited grace period. This parameter defines the period
	of time that RCU will wait from the beginning of an expedited
	grace period until it issues an RCU CPU stall warning. This time
	period is normally 20 milliseconds on Android devices.	A zero
	value causes the CONFIG_RCU_CPU_STALL_TIMEOUT value to be used,
	after conversion to milliseconds.

	This configuration parameter may be changed at runtime via the
	/sys/module/rcupdate/parameters/rcu_exp_cpu_stall_timeout, however
	this parameter is checked only at the beginning of a cycle. If you
	are in a current stall cycle, setting it to a new value will change
	the timeout for the -next- stall.

	Stall-warning messages may be enabled and disabled completely via
	/sys/module/rcupdate/parameters/rcu_cpu_stall_suppress.

RCU_STALL_DELAY_DELTA
---------------------

	Although the lockdep facility is extremely useful, it does add
	some overhead.  Therefore, under CONFIG_PROVE_RCU, the
	RCU_STALL_DELAY_DELTA macro allows five extra seconds before
	giving an RCU CPU stall warning message.  (This is a cpp
	macro, not a kernel configuration parameter.)

RCU_STALL_RAT_DELAY
-------------------

	The CPU stall detector tries to make the offending CPU print its
	own warnings, as this often gives better-quality stack traces.
	However, if the offending CPU does not detect its own stall in
	the number of jiffies specified by RCU_STALL_RAT_DELAY, then
	some other CPU will complain.  This delay is normally set to
	two jiffies.  (This is a cpp macro, not a kernel configuration
	parameter.)

rcupdate.rcu_task_stall_timeout
-------------------------------

	This boot/sysfs parameter controls the RCU-tasks and
	RCU-tasks-trace stall warning intervals.  A value of zero or less
	suppresses RCU-tasks stall warnings.  A positive value sets the
	stall-warning interval in seconds.  An RCU-tasks stall warning
	starts with the line:

		INFO: rcu_tasks detected stalls on tasks:

	And continues with the output of sched_show_task() for each
	task stalling the current RCU-tasks grace period.

	An RCU-tasks-trace stall warning starts (and continues) similarly:

		INFO: rcu_tasks_trace detected stalls on tasks


Interpreting RCU's CPU Stall-Detector "Splats"
==============================================

For non-RCU-tasks flavors of RCU, when a CPU detects that some other
CPU is stalling, it will print a message similar to the following::

	INFO: rcu_sched detected stalls on CPUs/tasks:
	2-...: (3 GPs behind) idle=06c/0/0 softirq=1453/1455 fqs=0
	16-...: (0 ticks this GP) idle=81c/0/0 softirq=764/764 fqs=0
	(detected by 32, t=2603 jiffies, g=7075, q=625)

This message indicates that CPU 32 detected that CPUs 2 and 16 were both
causing stalls, and that the stall was affecting RCU-sched.  This message
will normally be followed by stack dumps for each CPU.  Please note that
PREEMPT_RCU builds can be stalled by tasks as well as by CPUs, and that
the tasks will be indicated by PID, for example, "P3421".  It is even
possible for an rcu_state stall to be caused by both CPUs *and* tasks,
in which case the offending CPUs and tasks will all be called out in the list.
In some cases, CPUs will detect themselves stalling, which will result
in a self-detected stall.

CPU 2's "(3 GPs behind)" indicates that this CPU has not interacted with
the RCU core for the past three grace periods.  In contrast, CPU 16's "(0
ticks this GP)" indicates that this CPU has not taken any scheduling-clock
interrupts during the current stalled grace period.

The "idle=" portion of the message prints the dyntick-idle state.
The hex number before the first "/" is the low-order 16 bits of the
dynticks counter, which will have an even-numbered value if the CPU
is in dyntick-idle mode and an odd-numbered value otherwise.  The hex
number between the two "/"s is the value of the nesting, which will be
a small non-negative number if in the idle loop (as shown above) and a
very large positive number otherwise.  The number following the final
"/" is the NMI nesting, which will be a small non-negative number.

The "softirq=" portion of the message tracks the number of RCU softirq
handlers that the stalled CPU has executed.  The number before the "/"
is the number that had executed since boot at the time that this CPU
last noted the beginning of a grace period, which might be the current
(stalled) grace period, or it might be some earlier grace period (for
example, if the CPU might have been in dyntick-idle mode for an extended
time period).  The number after the "/" is the number that have executed
since boot until the current time.  If this latter number stays constant
across repeated stall-warning messages, it is possible that RCU's softirq
handlers are no longer able to execute on this CPU.  This can happen if
the stalled CPU is spinning with interrupts are disabled, or, in -rt
kernels, if a high-priority process is starving RCU's softirq handler.

The "fqs=" shows the number of force-quiescent-state idle/offline
detection passes that the grace-period kthread has made across this
CPU since the last time that this CPU noted the beginning of a grace
period.

The "detected by" line indicates which CPU detected the stall (in this
case, CPU 32), how many jiffies have elapsed since the start of the grace
period (in this case 2603), the grace-period sequence number (7075), and
an estimate of the total number of RCU callbacks queued across all CPUs
(625 in this case).

If the grace period ends just as the stall warning starts printing,
there will be a spurious stall-warning message, which will include
the following::

	INFO: Stall ended before state dump start

This is rare, but does happen from time to time in real life.  It is also
possible for a zero-jiffy stall to be flagged in this case, depending
on how the stall warning and the grace-period initialization happen to
interact.  Please note that it is not possible to entirely eliminate this
sort of false positive without resorting to things like stop_machine(),
which is overkill for this sort of problem.

If all CPUs and tasks have passed through quiescent states, but the
grace period has nevertheless failed to end, the stall-warning splat
will include something like the following::

	All QSes seen, last rcu_preempt kthread activity 23807 (4297905177-4297881370), jiffies_till_next_fqs=3, root ->qsmask 0x0

The "23807" indicates that it has been more than 23 thousand jiffies
since the grace-period kthread ran.  The "jiffies_till_next_fqs"
indicates how frequently that kthread should run, giving the number
of jiffies between force-quiescent-state scans, in this case three,
which is way less than 23807.  Finally, the root rcu_node structure's
->qsmask field is printed, which will normally be zero.

If the relevant grace-period kthread has been unable to run prior to
the stall warning, as was the case in the "All QSes seen" line above,
the following additional line is printed::

	rcu_sched kthread starved for 23807 jiffies! g7075 f0x0 RCU_GP_WAIT_FQS(3) ->state=0x1 ->cpu=5
	Unless rcu_sched kthread gets sufficient CPU time, OOM is now expected behavior.

Starving the grace-period kthreads of CPU time can of course result
in RCU CPU stall warnings even when all CPUs and tasks have passed
through the required quiescent states.  The "g" number shows the current
grace-period sequence number, the "f" precedes the ->gp_flags command
to the grace-period kthread, the "RCU_GP_WAIT_FQS" indicates that the
kthread is waiting for a short timeout, the "state" precedes value of the
task_struct ->state field, and the "cpu" indicates that the grace-period
kthread last ran on CPU 5.

If the relevant grace-period kthread does not wake from FQS wait in a
reasonable time, then the following additional line is printed::

	kthread timer wakeup didn't happen for 23804 jiffies! g7076 f0x0 RCU_GP_WAIT_FQS(5) ->state=0x402

The "23804" indicates that kthread's timer expired more than 23 thousand
jiffies ago.  The rest of the line has meaning similar to the kthread
starvation case.

Additionally, the following line is printed::

	Possible timer handling issue on cpu=4 timer-softirq=11142

Here "cpu" indicates that the grace-period kthread last ran on CPU 4,
where it queued the fqs timer.  The number following the "timer-softirq"
is the current ``TIMER_SOFTIRQ`` count on cpu 4.  If this value does not
change on successive RCU CPU stall warnings, there is further reason to
suspect a timer problem.

These messages are usually followed by stack dumps of the CPUs and tasks
involved in the stall.  These stack traces can help you locate the cause
of the stall, keeping in mind that the CPU detecting the stall will have
an interrupt frame that is mainly devoted to detecting the stall.


Multiple Warnings From One Stall
================================

If a stall lasts long enough, multiple stall-warning messages will
be printed for it.  The second and subsequent messages are printed at
longer intervals, so that the time between (say) the first and second
message will be about three times the interval between the beginning
of the stall and the first message.  It can be helpful to compare the
stack dumps for the different messages for the same stalled grace period.


Stall Warnings for Expedited Grace Periods
==========================================

If an expedited grace period detects a stall, it will place a message
like the following in dmesg::

	INFO: rcu_sched detected expedited stalls on CPUs/tasks: { 7-... } 21119 jiffies s: 73 root: 0x2/.

This indicates that CPU 7 has failed to respond to a reschedule IPI.
The three periods (".") following the CPU number indicate that the CPU
is online (otherwise the first period would instead have been "O"),
that the CPU was online at the beginning of the expedited grace period
(otherwise the second period would have instead been "o"), and that
the CPU has been online at least once since boot (otherwise, the third
period would instead have been "N").  The number before the "jiffies"
indicates that the expedited grace period has been going on for 21,119
jiffies.  The number following the "s:" indicates that the expedited
grace-period sequence counter is 73.  The fact that this last value is
odd indicates that an expedited grace period is in flight.  The number
following "root:" is a bitmask that indicates which children of the root
rcu_node structure correspond to CPUs and/or tasks that are blocking the
current expedited grace period.  If the tree had more than one level,
additional hex numbers would be printed for the states of the other
rcu_node structures in the tree.

As with normal grace periods, PREEMPT_RCU builds can be stalled by
tasks as well as by CPUs, and that the tasks will be indicated by PID,
for example, "P3421".

It is entirely possible to see stall warnings from normal and from
expedited grace periods at about the same time during the same run.

RCU_CPU_STALL_CPUTIME
=====================

In kernels built with CONFIG_RCU_CPU_STALL_CPUTIME=y or booted with
rcupdate.rcu_cpu_stall_cputime=1, the following additional information
is supplied with each RCU CPU stall warning::

  rcu:          hardirqs   softirqs   csw/system
  rcu:  number:      624         45            0
  rcu: cputime:       69          1         2425   ==> 2500(ms)

These statistics are collected during the sampling period. The values
in row "number:" are the number of hard interrupts, number of soft
interrupts, and number of context switches on the stalled CPU. The
first three values in row "cputime:" indicate the CPU time in
milliseconds consumed by hard interrupts, soft interrupts, and tasks
on the stalled CPU.  The last number is the measurement interval, again
in milliseconds.  Because user-mode tasks normally do not cause RCU CPU
stalls, these tasks are typically kernel tasks, which is why only the
system CPU time are considered.

The sampling period is shown as follows::

  |<------------first timeout---------->|<-----second timeout----->|
  |<--half timeout-->|<--half timeout-->|                          |
  |                  |<--first period-->|                          |
  |                  |<-----------second sampling period---------->|
  |                  |                  |                          |
             snapshot time point    1st-stall                  2nd-stall

The following describes four typical scenarios:

1. A CPU looping with interrupts disabled.

   ::

     rcu:          hardirqs   softirqs   csw/system
     rcu:  number:        0          0            0
     rcu: cputime:        0          0            0   ==> 2500(ms)

   Because interrupts have been disabled throughout the measurement
   interval, there are no interrupts and no context switches.
   Furthermore, because CPU time consumption was measured using interrupt
   handlers, the system CPU consumption is misleadingly measured as zero.
   This scenario will normally also have "(0 ticks this GP)" printed on
   this CPU's summary line.

2. A CPU looping with bottom halves disabled.

   This is similar to the previous example, but with non-zero number of
   and CPU time consumed by hard interrupts, along with non-zero CPU
   time consumed by in-kernel execution::

     rcu:          hardirqs   softirqs   csw/system
     rcu:  number:      624          0            0
     rcu: cputime:       49          0         2446   ==> 2500(ms)

   The fact that there are zero softirqs gives a hint that these were
   disabled, perhaps via local_bh_disable().  It is of course possible
   that there were no softirqs, perhaps because all events that would
   result in softirq execution are confined to other CPUs.  In this case,
   the diagnosis should continue as shown in the next example.

3. A CPU looping with preemption disabled.

   Here, only the number of context switches is zero::

     rcu:          hardirqs   softirqs   csw/system
     rcu:  number:      624         45            0
     rcu: cputime:       69          1         2425   ==> 2500(ms)

   This situation hints that the stalled CPU was looping with preemption
   disabled.

4. No looping, but massive hard and soft interrupts.

   ::

     rcu:          hardirqs   softirqs   csw/system
     rcu:  number:       xx         xx            0
     rcu: cputime:       xx         xx            0   ==> 2500(ms)

   Here, the number and CPU time of hard interrupts are all non-zero,
   but the number of context switches and the in-kernel CPU time consumed
   are zero. The number and cputime of soft interrupts will usually be
   non-zero, but could be zero, for example, if the CPU was spinning
   within a single hard interrupt handler.

   If this type of RCU CPU stall warning can be reproduced, you can
   narrow it down by looking at /proc/interrupts or by writing code to
   trace each interrupt, for example, by referring to show_interrupts().

---

### Documentation RCU Torture (`Documentation/RCU/torture.rst`)

.. SPDX-License-Identifier: GPL-2.0

==========================
RCU Torture Test Operation
==========================


CONFIG_RCU_TORTURE_TEST
=======================

The CONFIG_RCU_TORTURE_TEST config option is available for all RCU
implementations.  It creates an rcutorture kernel module that can
be loaded to run a torture test.  The test periodically outputs
status messages via printk(), which can be examined via the dmesg
command (perhaps grepping for "torture").  The test is started
when the module is loaded, and stops when the module is unloaded.

Module parameters are prefixed by "rcutorture." in
Documentation/admin-guide/kernel-parameters.txt.

Output
======

The statistics output is as follows::

	rcu-torture:--- Start of test: nreaders=16 nfakewriters=4 stat_interval=30 verbose=0 test_no_idle_hz=1 shuffle_interval=3 stutter=5 irqreader=1 fqs_duration=0 fqs_holdoff=0 fqs_stutter=3 test_boost=1/0 test_boost_interval=7 test_boost_duration=4
	rcu-torture: rtc:           (null) ver: 155441 tfle: 0 rta: 155441 rtaf: 8884 rtf: 155440 rtmbe: 0 rtbe: 0 rtbke: 0 rtbre: 0 rtbf: 0 rtb: 0 nt: 3055767
	rcu-torture: Reader Pipe:  727860534 34213 0 0 0 0 0 0 0 0 0
	rcu-torture: Reader Batch:  727877838 17003 0 0 0 0 0 0 0 0 0
	rcu-torture: Free-Block Circulation:  155440 155440 155440 155440 155440 155440 155440 155440 155440 155440 0
	rcu-torture:--- End of test: SUCCESS: nreaders=16 nfakewriters=4 stat_interval=30 verbose=0 test_no_idle_hz=1 shuffle_interval=3 stutter=5 irqreader=1 fqs_duration=0 fqs_holdoff=0 fqs_stutter=3 test_boost=1/0 test_boost_interval=7 test_boost_duration=4

The command "dmesg | grep torture:" will extract this information on
most systems.  On more esoteric configurations, it may be necessary to
use other commands to access the output of the printk()s used by
the RCU torture test.  The printk()s use KERN_ALERT, so they should
be evident.  ;-)

The first and last lines show the rcutorture module parameters, and the
last line shows either "SUCCESS" or "FAILURE", based on rcutorture's
automatic determination as to whether RCU operated correctly.

The entries are as follows:

*	"rtc": The hexadecimal address of the structure currently visible
	to readers.

*	"ver": The number of times since boot that the RCU writer task
	has changed the structure visible to readers.

*	"tfle": If non-zero, indicates that the "torture freelist"
	containing structures to be placed into the "rtc" area is empty.
	This condition is important, since it can fool you into thinking
	that RCU is working when it is not.  :-/

*	"rta": Number of structures allocated from the torture freelist.

*	"rtaf": Number of allocations from the torture freelist that have
	failed due to the list being empty.  It is not unusual for this
	to be non-zero, but it is bad for it to be a large fraction of
	the value indicated by "rta".

*	"rtf": Number of frees into the torture freelist.

*	"rtmbe": A non-zero value indicates that rcutorture believes that
	rcu_assign_pointer() and rcu_dereference() are not working
	correctly.  This value should be zero.

*	"rtbe": A non-zero value indicates that one of the rcu_barrier()
	family of functions is not working correctly.

*	"rtbke": rcutorture was unable to create the real-time kthreads
	used to force RCU priority inversion.  This value should be zero.

*	"rtbre": Although rcutorture successfully created the kthreads
	used to force RCU priority inversion, it was unable to set them
	to the real-time priority level of 1.  This value should be zero.

*	"rtbf": The number of times that RCU priority boosting failed
	to resolve RCU priority inversion.

*	"rtb": The number of times that rcutorture attempted to force
	an RCU priority inversion condition.  If you are testing RCU
	priority boosting via the "test_boost" module parameter, this
	value should be non-zero.

*	"nt": The number of times rcutorture ran RCU read-side code from
	within a timer handler.  This value should be non-zero only
	if you specified the "irqreader" module parameter.

*	"Reader Pipe": Histogram of "ages" of structures seen by readers.
	If any entries past the first two are non-zero, RCU is broken.
	And rcutorture prints the error flag string "!!!" to make sure
	you notice.  The age of a newly allocated structure is zero,
	it becomes one when removed from reader visibility, and is
	incremented once per grace period subsequently -- and is freed
	after passing through (RCU_TORTURE_PIPE_LEN-2) grace periods.

	The output displayed above was taken from a correctly working
	RCU.  If you want to see what it looks like when broken, break
	it yourself.  ;-)

*	"Reader Batch": Another histogram of "ages" of structures seen
	by readers, but in terms of counter flips (or batches) rather
	than in terms of grace periods.  The legal number of non-zero
	entries is again two.  The reason for this separate view is that
	it is sometimes easier to get the third entry to show up in the
	"Reader Batch" list than in the "Reader Pipe" list.

*	"Free-Block Circulation": Shows the number of torture structures
	that have reached a given point in the pipeline.  The first element
	should closely correspond to the number of structures allocated,
	the second to the number that have been removed from reader view,
	and all but the last remaining to the corresponding number of
	passes through a grace period.  The last entry should be zero,
	as it is only incremented if a torture structure's counter
	somehow gets incremented farther than it should.

Different implementations of RCU can provide implementation-specific
additional information.  For example, Tree SRCU provides the following
additional line::

	srcud-torture: Tree SRCU per-CPU(idx=0): 0(35,-21) 1(-4,24) 2(1,1) 3(-26,20) 4(28,-47) 5(-9,4) 6(-10,14) 7(-14,11) T(1,6)

This line shows the per-CPU counter state, in this case for Tree SRCU
using a dynamically allocated srcu_struct (hence "srcud-" rather than
"srcu-").  The numbers in parentheses are the values of the "old" and
"current" counters for the corresponding CPU.  The "idx" value maps the
"old" and "current" values to the underlying array, and is useful for
debugging.  The final "T" entry contains the totals of the counters.

Usage on Specific Kernel Builds
===============================

It is sometimes desirable to torture RCU on a specific kernel build,
for example, when preparing to put that kernel build into production.
In that case, the kernel should be built with CONFIG_RCU_TORTURE_TEST=m
so that the test can be started using modprobe and terminated using rmmod.

For example, the following script may be used to torture RCU::

	#!/bin/sh

	modprobe rcutorture
	sleep 3600
	rmmod rcutorture
	dmesg | grep torture:

The output can be manually inspected for the error flag of "!!!".
One could of course create a more elaborate script that automatically
checked for such errors.  The "rmmod" command forces a "SUCCESS",
"FAILURE", or "RCU_HOTPLUG" indication to be printk()ed.  The first
two are self-explanatory, while the last indicates that while there
were no RCU failures, CPU-hotplug problems were detected.


Usage on Mainline Kernels
=========================

When using rcutorture to test changes to RCU itself, it is often
necessary to build a number of kernels in order to test that change
across a broad range of combinations of the relevant Kconfig options
and of the relevant kernel boot parameters.  In this situation, use
of modprobe and rmmod can be quite time-consuming and error-prone.

Therefore, the tools/testing/selftests/rcutorture/bin/kvm.sh
script is available for mainline testing for x86, arm64, and
powerpc.  By default, it will run the series of tests specified by
tools/testing/selftests/rcutorture/configs/rcu/CFLIST, with each test
running for 30 minutes within a guest OS using a minimal userspace
supplied by an automatically generated initrd.  After the tests are
complete, the resulting build products and console output are analyzed
for errors and the results of the runs are summarized.

On larger systems, rcutorture testing can be accelerated by passing the
--cpus argument to kvm.sh.  For example, on a 64-CPU system, "--cpus 43"
would use up to 43 CPUs to run tests concurrently, which as of v5.4 would
complete all the scenarios in two batches, reducing the time to complete
from about eight hours to about one hour (not counting the time to build
the sixteen kernels).  The "--dryrun sched" argument will not run tests,
but rather tell you how the tests would be scheduled into batches.  This
can be useful when working out how many CPUs to specify in the --cpus
argument.

Not all changes require that all scenarios be run.  For example, a change
to Tree SRCU might run only the SRCU-N and SRCU-P scenarios using the
--configs argument to kvm.sh as follows:  "--configs 'SRCU-N SRCU-P'".
Large systems can run multiple copies of the full set of scenarios,
for example, a system with 448 hardware threads can run five instances
of the full set concurrently.  To make this happen::

	kvm.sh --cpus 448 --configs '5*CFLIST'

Alternatively, such a system can run 56 concurrent instances of a single
eight-CPU scenario::

	kvm.sh --cpus 448 --configs '56*TREE04'

Or 28 concurrent instances of each of two eight-CPU scenarios::

	kvm.sh --cpus 448 --configs '28*TREE03 28*TREE04'

Of course, each concurrent instance will use memory, which can be
limited using the --memory argument, which defaults to 512M.  Small
values for memory may require disabling the callback-flooding tests
using the --bootargs parameter discussed below.

Sometimes additional debugging is useful, and in such cases the --kconfig
parameter to kvm.sh may be used, for example, ``--kconfig 'CONFIG_RCU_EQS_DEBUG=y'``.
In addition, there are the --gdb, --kasan, and --kcsan parameters.
Note that --gdb limits you to one scenario per kvm.sh run and requires
that you have another window open from which to run ``gdb`` as instructed
by the script.

Kernel boot arguments can also be supplied, for example, to control
rcutorture's module parameters.  For example, to test a change to RCU's
CPU stall-warning code, use "--bootargs 'rcutorture.stall_cpu=30'".
This will of course result in the scripting reporting a failure, namely
the resulting RCU CPU stall warning.  As noted above, reducing memory may
require disabling rcutorture's callback-flooding tests::

	kvm.sh --cpus 448 --configs '56*TREE04' --memory 128M \
		--bootargs 'rcutorture.fwd_progress=0'

Sometimes all that is needed is a full set of kernel builds.  This is
what the --buildonly parameter does.

The --duration parameter can override the default run time of 30 minutes.
For example, ``--duration 2d`` would run for two days, ``--duration 3h``
would run for three hours, ``--duration 5m`` would run for five minutes,
and ``--duration 45s`` would run for 45 seconds.  This last can be useful
for tracking down rare boot-time failures.

Finally, the --trust-make parameter allows each kernel build to reuse what
it can from the previous kernel build.  Please note that without the
--trust-make parameter, your tags files may be demolished.

There are additional more arcane arguments that are documented in the
source code of the kvm.sh script.

If a run contains failures, the number of buildtime and runtime failures
is listed at the end of the kvm.sh output, which you really should redirect
to a file.  The build products and console output of each run is kept in
tools/testing/selftests/rcutorture/res in timestamped directories.  A
given directory can be supplied to kvm-find-errors.sh in order to have
it cycle you through summaries of errors and full error logs.  For example::

	tools/testing/selftests/rcutorture/bin/kvm-find-errors.sh \
		tools/testing/selftests/rcutorture/res/2020.01.20-15.54.23

However, it is often more convenient to access the files directly.
Files pertaining to all scenarios in a run reside in the top-level
directory (2020.01.20-15.54.23 in the example above), while per-scenario
files reside in a subdirectory named after the scenario (for example,
"TREE04").  If a given scenario ran more than once (as in "--configs
'56*TREE04'" above), the directories corresponding to the second and
subsequent runs of that scenario include a sequence number, for example,
"TREE04.2", "TREE04.3", and so on.

The most frequently used file in the top-level directory is testid.txt.
If the test ran in a git repository, then this file contains the commit
that was tested and any uncommitted changes in diff format.

The most frequently used files in each per-scenario-run directory are:

.config:
	This file contains the Kconfig options.

Make.out:
	This contains build output for a specific scenario.

console.log:
	This contains the console output for a specific scenario.
	This file may be examined once the kernel has booted, but
	it might not exist if the build failed.

vmlinux:
	This contains the kernel, which can be useful with tools like
	objdump and gdb.

A number of additional files are available, but are less frequently used.
Many are intended for debugging of rcutorture itself or of its scripting.

As of v5.4, a successful run with the default set of scenarios produces
the following summary at the end of the run on a 12-CPU system::

    SRCU-N ------- 804233 GPs (148.932/s) [srcu: g10008272 f0x0 ]
    SRCU-P ------- 202320 GPs (37.4667/s) [srcud: g1809476 f0x0 ]
    SRCU-t ------- 1122086 GPs (207.794/s) [srcu: g0 f0x0 ]
    SRCU-u ------- 1111285 GPs (205.794/s) [srcud: g1 f0x0 ]
    TASKS01 ------- 19666 GPs (3.64185/s) [tasks: g0 f0x0 ]
    TASKS02 ------- 20541 GPs (3.80389/s) [tasks: g0 f0x0 ]
    TASKS03 ------- 19416 GPs (3.59556/s) [tasks: g0 f0x0 ]
    TINY01 ------- 836134 GPs (154.84/s) [rcu: g0 f0x0 ] n_max_cbs: 34198
    TINY02 ------- 850371 GPs (157.476/s) [rcu: g0 f0x0 ] n_max_cbs: 2631
    TREE01 ------- 162625 GPs (30.1157/s) [rcu: g1124169 f0x0 ]
    TREE02 ------- 333003 GPs (61.6672/s) [rcu: g2647753 f0x0 ] n_max_cbs: 35844
    TREE03 ------- 306623 GPs (56.782/s) [rcu: g2975325 f0x0 ] n_max_cbs: 1496497
    CPU count limited from 16 to 12
    TREE04 ------- 246149 GPs (45.5831/s) [rcu: g1695737 f0x0 ] n_max_cbs: 434961
    TREE05 ------- 314603 GPs (58.2598/s) [rcu: g2257741 f0x2 ] n_max_cbs: 193997
    TREE07 ------- 167347 GPs (30.9902/s) [rcu: g1079021 f0x0 ] n_max_cbs: 478732
    CPU count limited from 16 to 12
    TREE09 ------- 752238 GPs (139.303/s) [rcu: g13075057 f0x0 ] n_max_cbs: 99011


Repeated Runs
=============

Suppose that you are chasing down a rare boot-time failure.  Although you
could use kvm.sh, doing so will rebuild the kernel on each run.  If you
need (say) 1,000 runs to have confidence that you have fixed the bug,
these pointless rebuilds can become extremely annoying.

This is why kvm-again.sh exists.

Suppose that a previous kvm.sh run left its output in this directory::

	tools/testing/selftests/rcutorture/res/2022.11.03-11.26.28

Then this run can be re-run without rebuilding as follow::

	kvm-again.sh tools/testing/selftests/rcutorture/res/2022.11.03-11.26.28

A few of the original run's kvm.sh parameters may be overridden, perhaps
most notably --duration and --bootargs.  For example::

	kvm-again.sh tools/testing/selftests/rcutorture/res/2022.11.03-11.26.28 \
		--duration 45s

would re-run the previous test, but for only 45 seconds, thus facilitating
tracking down the aforementioned rare boot-time failure.


Distributed Runs
================

Although kvm.sh is quite useful, its testing is confined to a single
system.  It is not all that hard to use your favorite framework to cause
(say) 5 instances of kvm.sh to run on your 5 systems, but this will very
likely unnecessarily rebuild kernels.  In addition, manually distributing
the desired rcutorture scenarios across the available systems can be
painstaking and error-prone.

And this is why the kvm-remote.sh script exists.

If the following command works::

	ssh system0 date

and if it also works for system1, system2, system3, system4, and system5,
and all of these systems have 64 CPUs, you can type::

	kvm-remote.sh "system0 system1 system2 system3 system4 system5" \
		--cpus 64 --duration 8h --configs "5*CFLIST"

This will build each default scenario's kernel on the local system, then
spread each of five instances of each scenario over the systems listed,
running each scenario for eight hours.  At the end of the runs, the
results will be gathered, recorded, and printed.  Most of the parameters
that kvm.sh will accept can be passed to kvm-remote.sh, but the list of
systems must come first.

The kvm.sh ``--dryrun scenarios`` argument is useful for working out
how many scenarios may be run in one batch across a group of systems.

You can also re-run a previous remote run in a manner similar to kvm.sh::

	kvm-remote.sh "system0 system1 system2 system3 system4 system5" \
		tools/testing/selftests/rcutorture/res/2022.11.03-11.26.28-remote \
		--duration 24h

In this case, most of the kvm-again.sh parameters may be supplied following
the pathname of the old run-results directory.

---

### Documentation RCU WhatisRCU (`Documentation/RCU/whatisRCU.rst`)

.. _whatisrcu_doc:

What is RCU?  --  "Read, Copy, Update"
======================================

Please note that the "What is RCU?" LWN series is an excellent place
to start learning about RCU:

| 1.	What is RCU, Fundamentally?  https://lwn.net/Articles/262464/
| 2.	What is RCU? Part 2: Usage   https://lwn.net/Articles/263130/
| 3.	RCU part 3: the RCU API      https://lwn.net/Articles/264090/
| 4.	The RCU API, 2010 Edition    https://lwn.net/Articles/418853/
| 	2010 Big API Table           https://lwn.net/Articles/419086/
| 5.	The RCU API, 2014 Edition    https://lwn.net/Articles/609904/
|	2014 Big API Table           https://lwn.net/Articles/609973/
| 6.	The RCU API, 2019 Edition    https://lwn.net/Articles/777036/
|	2019 Big API Table           https://lwn.net/Articles/777165/
| 7.	The RCU API, 2024 Edition    https://lwn.net/Articles/988638/
|       2024 Background Information  https://lwn.net/Articles/988641/
|	2024 Big API Table           https://lwn.net/Articles/988666/

For those preferring video:

| 1.	Unraveling RCU Mysteries: Fundamentals          https://www.linuxfoundation.org/webinars/unraveling-rcu-usage-mysteries
| 2.	Unraveling RCU Mysteries: Additional Use Cases  https://www.linuxfoundation.org/webinars/unraveling-rcu-usage-mysteries-additional-use-cases


What is RCU?

RCU is a synchronization mechanism that was added to the Linux kernel
during the 2.5 development effort that is optimized for read-mostly
situations.  Although RCU is actually quite simple, making effective use
of it requires you to think differently about your code.  Another part
of the problem is the mistaken assumption that there is "one true way" to
describe and to use RCU.  Instead, the experience has been that different
people must take different paths to arrive at an understanding of RCU,
depending on their experiences and use cases.  This document provides
several different paths, as follows:

:ref:`1.	RCU OVERVIEW <1_whatisRCU>`

:ref:`2.	WHAT IS RCU'S CORE API? <2_whatisRCU>`

:ref:`3.	WHAT ARE SOME EXAMPLE USES OF CORE RCU API? <3_whatisRCU>`

:ref:`4.	WHAT IF MY UPDATING THREAD CANNOT BLOCK? <4_whatisRCU>`

:ref:`5.	WHAT ARE SOME SIMPLE IMPLEMENTATIONS OF RCU? <5_whatisRCU>`

:ref:`6.	ANALOGY WITH READER-WRITER LOCKING <6_whatisRCU>`

:ref:`7.	ANALOGY WITH REFERENCE COUNTING <7_whatisRCU>`

:ref:`8.	FULL LIST OF RCU APIs <8_whatisRCU>`

:ref:`9.	ANSWERS TO QUICK QUIZZES <9_whatisRCU>`

People who prefer starting with a conceptual overview should focus on
Section 1, though most readers will profit by reading this section at
some point.  People who prefer to start with an API that they can then
experiment with should focus on Section 2.  People who prefer to start
with example uses should focus on Sections 3 and 4.  People who need to
understand the RCU implementation should focus on Section 5, then dive
into the kernel source code.  People who reason best by analogy should
focus on Section 6 and 7.  Section 8 serves as an index to the docbook
API documentation, and Section 9 is the traditional answer key.

So, start with the section that makes the most sense to you and your
preferred method of learning.  If you need to know everything about
everything, feel free to read the whole thing -- but if you are really
that type of person, you have perused the source code and will therefore
never need this document anyway.  ;-)

.. _1_whatisRCU:

1.  RCU OVERVIEW
----------------

The basic idea behind RCU is to split updates into "removal" and
"reclamation" phases.  The removal phase removes references to data items
within a data structure (possibly by replacing them with references to
new versions of these data items), and can run concurrently with readers.
The reason that it is safe to run the removal phase concurrently with
readers is the semantics of modern CPUs guarantee that readers will see
either the old or the new version of the data structure rather than a
partially updated reference.  The reclamation phase does the work of reclaiming
(e.g., freeing) the data items removed from the data structure during the
removal phase.  Because reclaiming data items can disrupt any readers
concurrently referencing those data items, the reclamation phase must
not start until readers no longer hold references to those data items.

Splitting the update into removal and reclamation phases permits the
updater to perform the removal phase immediately, and to defer the
reclamation phase until all readers active during the removal phase have
completed, either by blocking until they finish or by registering a
callback that is invoked after they finish.  Only readers that are active
during the removal phase need be considered, because any reader starting
after the removal phase will be unable to gain a reference to the removed
data items, and therefore cannot be disrupted by the reclamation phase.

So the typical RCU update sequence goes something like the following:

a.	Remove pointers to a data structure, so that subsequent
	readers cannot gain a reference to it.

b.	Wait for all previous readers to complete their RCU read-side
	critical sections.

c.	At this point, there cannot be any readers who hold references
	to the data structure, so it now may safely be reclaimed
	(e.g., kfree()d).

Step (b) above is the key idea underlying RCU's deferred destruction.
The ability to wait until all readers are done allows RCU readers to
use much lighter-weight synchronization, in some cases, absolutely no
synchronization at all.  In contrast, in more conventional lock-based
schemes, readers must use heavy-weight synchronization in order to
prevent an updater from deleting the data structure out from under them.
This is because lock-based updaters typically update data items in place,
and must therefore exclude readers.  In contrast, RCU-based updaters
typically take advantage of the fact that writes to single aligned
pointers are atomic on modern CPUs, allowing atomic insertion, removal,
and replacement of data items in a linked structure without disrupting
readers.  Concurrent RCU readers can then continue accessing the old
versions, and can dispense with the atomic operations, memory barriers,
and communications cache misses that are so expensive on present-day
SMP computer systems, even in absence of lock contention.

In the three-step procedure shown above, the updater is performing both
the removal and the reclamation step, but it is often helpful for an
entirely different thread to do the reclamation, as is in fact the case
in the Linux kernel's directory-entry cache (dcache).  Even if the same
thread performs both the update step (step (a) above) and the reclamation
step (step (c) above), it is often helpful to think of them separately.
For example, RCU readers and updaters need not communicate at all,
but RCU provides implicit low-overhead communication between readers
and reclaimers, namely, in step (b) above.

So how the heck can a reclaimer tell when a reader is done, given
that readers are not doing any sort of synchronization operations???
Read on to learn about how RCU's API makes this easy.

.. _2_whatisRCU:

2.  WHAT IS RCU'S CORE API?
---------------------------

The core RCU API is quite small:

a.	rcu_read_lock()
b.	rcu_read_unlock()
c.	synchronize_rcu() / call_rcu()
d.	rcu_assign_pointer()
e.	rcu_dereference()

There are many other members of the RCU API, but the rest can be
expressed in terms of these five, though most implementations instead
express synchronize_rcu() in terms of the call_rcu() callback API.

The five core RCU APIs are described below, the other 18 will be enumerated
later.  See the kernel docbook documentation for more info, or look directly
at the function header comments.

rcu_read_lock()
^^^^^^^^^^^^^^^
	void rcu_read_lock(void);

	This temporal primitive is used by a reader to inform the
	reclaimer that the reader is entering an RCU read-side critical
	section.  It is illegal to block while in an RCU read-side
	critical section, though kernels built with CONFIG_PREEMPT_RCU
	can preempt RCU read-side critical sections.  Any RCU-protected
	data structure accessed during an RCU read-side critical section
	is guaranteed to remain unreclaimed for the full duration of that
	critical section.  Reference counts may be used in conjunction
	with RCU to maintain longer-term references to data structures.

	Note that anything that disables bottom halves, preemption,
	or interrupts also enters an RCU read-side critical section.
	Acquiring a spinlock also enters an RCU read-side critical
	sections, even for spinlocks that do not disable preemption,
	as is the case in kernels built with CONFIG_PREEMPT_RT=y.
	Sleeplocks do *not* enter RCU read-side critical sections.

rcu_read_unlock()
^^^^^^^^^^^^^^^^^
	void rcu_read_unlock(void);

	This temporal primitives is used by a reader to inform the
	reclaimer that the reader is exiting an RCU read-side critical
	section.  Anything that enables bottom halves, preemption,
	or interrupts also exits an RCU read-side critical section.
	Releasing a spinlock also exits an RCU read-side critical section.

	Note that RCU read-side critical sections may be nested and/or
	overlapping.

synchronize_rcu()
^^^^^^^^^^^^^^^^^
	void synchronize_rcu(void);

	This temporal primitive marks the end of updater code and the
	beginning of reclaimer code.  It does this by blocking until
	all pre-existing RCU read-side critical sections on all CPUs
	have completed.  Note that synchronize_rcu() will **not**
	necessarily wait for any subsequent RCU read-side critical
	sections to complete.  For example, consider the following
	sequence of events::

	         CPU 0                  CPU 1                 CPU 2
	     ----------------- ------------------------- ---------------
	 1.  rcu_read_lock()
	 2.                    enters synchronize_rcu()
	 3.                                               rcu_read_lock()
	 4.  rcu_read_unlock()
	 5.                     exits synchronize_rcu()
	 6.                                              rcu_read_unlock()

	To reiterate, synchronize_rcu() waits only for ongoing RCU
	read-side critical sections to complete, not necessarily for
	any that begin after synchronize_rcu() is invoked.

	Of course, synchronize_rcu() does not necessarily return
	**immediately** after the last pre-existing RCU read-side critical
	section completes.  For one thing, there might well be scheduling
	delays.  For another thing, many RCU implementations process
	requests in batches in order to improve efficiencies, which can
	further delay synchronize_rcu().

	Since synchronize_rcu() is the API that must figure out when
	readers are done, its implementation is key to RCU.  For RCU
	to be useful in all but the most read-intensive situations,
	synchronize_rcu()'s overhead must also be quite small.

	The call_rcu() API is an asynchronous callback form of
	synchronize_rcu(), and is described in more detail in a later
	section.  Instead of blocking, it registers a function and
	argument which are invoked after all ongoing RCU read-side
	critical sections have completed.  This callback variant is
	particularly useful in situations where it is illegal to block
	or where update-side performance is critically important.

	However, the call_rcu() API should not be used lightly, as use
	of the synchronize_rcu() API generally results in simpler code.
	In addition, the synchronize_rcu() API has the nice property
	of automatically limiting update rate should grace periods
	be delayed.  This property results in system resilience in face
	of denial-of-service attacks.  Code using call_rcu() should limit
	update rate in order to gain this same sort of resilience.  See
	checklist.rst for some approaches to limiting the update rate.

rcu_assign_pointer()
^^^^^^^^^^^^^^^^^^^^
	void rcu_assign_pointer(p, typeof(p) v);

	Yes, rcu_assign_pointer() **is** implemented as a macro, though
	it would be cool to be able to declare a function in this manner.
	(And there has been some discussion of adding overloaded functions
	to the C language, so who knows?)

	The updater uses this spatial macro to assign a new value to an
	RCU-protected pointer, in order to safely communicate the change
	in value from the updater to the reader.  This is a spatial (as
	opposed to temporal) macro.  It does not evaluate to an rvalue,
	but it does provide any compiler directives and memory-barrier
	instructions required for a given compile or CPU architecture.
	Its ordering properties are that of a store-release operation,
	that is, any prior loads and stores required to initialize the
	structure are ordered before the store that publishes the pointer
	to that structure.

	Perhaps just as important, rcu_assign_pointer() serves to document
	(1) which pointers are protected by RCU and (2) the point at which
	a given structure becomes accessible to other CPUs.  That said,
	rcu_assign_pointer() is most frequently used indirectly, via
	the _rcu list-manipulation primitives such as list_add_rcu().

rcu_dereference()
^^^^^^^^^^^^^^^^^
	typeof(p) rcu_dereference(p);

	Like rcu_assign_pointer(), rcu_dereference() must be implemented
	as a macro.

	The reader uses the spatial rcu_dereference() macro to fetch
	an RCU-protected pointer, which returns a value that may
	then be safely dereferenced.  Note that rcu_dereference()
	does not actually dereference the pointer, instead, it
	protects the pointer for later dereferencing.  It also
	executes any needed memory-barrier instructions for a given
	CPU architecture.  Currently, only Alpha needs memory barriers
	within rcu_dereference() -- on other CPUs, it compiles to a
	volatile load.	However, no mainstream C compilers respect
	address dependencies, so rcu_dereference() uses volatile casts,
	which, in combination with the coding guidelines listed in
	rcu_dereference.rst, prevent current compilers from breaking
	these dependencies.

	Common coding practice uses rcu_dereference() to copy an
	RCU-protected pointer to a local variable, then dereferences
	this local variable, for example as follows::

		p = rcu_dereference(head.next);
		return p->data;

	However, in this case, one could just as easily combine these
	into one statement::

		return rcu_dereference(head.next)->data;

	If you are going to be fetching multiple fields from the
	RCU-protected structure, using the local variable is of
	course preferred.  Repeated rcu_dereference() calls look
	ugly, do not guarantee that the same pointer will be returned
	if an update happened while in the critical section, and incur
	unnecessary overhead on Alpha CPUs.

	Note that the value returned by rcu_dereference() is valid
	only within the enclosing RCU read-side critical section [1]_.
	For example, the following is **not** legal::

		rcu_read_lock();
		p = rcu_dereference(head.next);
		rcu_read_unlock();
		x = p->address;	/* BUG!!! */
		rcu_read_lock();
		y = p->data;	/* BUG!!! */
		rcu_read_unlock();

	Holding a reference from one RCU read-side critical section
	to another is just as illegal as holding a reference from
	one lock-based critical section to another!  Similarly,
	using a reference outside of the critical section in which
	it was acquired is just as illegal as doing so with normal
	locking.

	As with rcu_assign_pointer(), an important function of
	rcu_dereference() is to document which pointers are protected by
	RCU, in particular, flagging a pointer that is subject to changing
	at any time, including immediately after the rcu_dereference().
	And, again like rcu_assign_pointer(), rcu_dereference() is
	typically used indirectly, via the _rcu list-manipulation
	primitives, such as list_for_each_entry_rcu() [2]_.

.. 	[1] The variant rcu_dereference_protected() can be used outside
	of an RCU read-side critical section as long as the usage is
	protected by locks acquired by the update-side code.  This variant
	avoids the lockdep warning that would happen when using (for
	example) rcu_dereference() without rcu_read_lock() protection.
	Using rcu_dereference_protected() also has the advantage
	of permitting compiler optimizations that rcu_dereference()
	must prohibit.	The rcu_dereference_protected() variant takes
	a lockdep expression to indicate which locks must be acquired
	by the caller. If the indicated protection is not provided,
	a lockdep splat is emitted.  See Design/Requirements/Requirements.rst
	and the API's code comments for more details and example usage.

.. 	[2] If the list_for_each_entry_rcu() instance might be used by
	update-side code as well as by RCU readers, then an additional
	lockdep expression can be added to its list of arguments.
	For example, given an additional "lock_is_held(&mylock)" argument,
	the RCU lockdep code would complain only if this instance was
	invoked outside of an RCU read-side critical section and without
	the protection of mylock.

The following diagram shows how each API communicates among the
reader, updater, and reclaimer.
::


	    rcu_assign_pointer()
	                            +--------+
	    +---------------------->| reader |---------+
	    |                       +--------+         |
	    |                           |              |
	    |                           |              | Protect:
	    |                           |              | rcu_read_lock()
	    |                           |              | rcu_read_unlock()
	    |        rcu_dereference()  |              |
	    +---------+                 |              |
	    | updater |<----------------+              |
	    +---------+                                V
	    |                                    +-----------+
	    +----------------------------------->| reclaimer |
	                                         +-----------+
	      Defer:
	      synchronize_rcu() & call_rcu()


The RCU infrastructure observes the temporal sequence of rcu_read_lock(),
rcu_read_unlock(), synchronize_rcu(), and call_rcu() invocations in
order to determine when (1) synchronize_rcu() invocations may return
to their callers and (2) call_rcu() callbacks may be invoked.  Efficient
implementations of the RCU infrastructure make heavy use of batching in
order to amortize their overhead over many uses of the corresponding APIs.
The rcu_assign_pointer() and rcu_dereference() invocations communicate
spatial changes via stores to and loads from the RCU-protected pointer in
question.

There are at least three flavors of RCU usage in the Linux kernel. The diagram
above shows the most common one. On the updater side, the rcu_assign_pointer(),
synchronize_rcu() and call_rcu() primitives used are the same for all three
flavors. However for protection (on the reader side), the primitives used vary
depending on the flavor:

a.	rcu_read_lock() / rcu_read_unlock()
	rcu_dereference()

b.	rcu_read_lock_bh() / rcu_read_unlock_bh()
	local_bh_disable() / local_bh_enable()
	rcu_dereference_bh()

c.	rcu_read_lock_sched() / rcu_read_unlock_sched()
	preempt_disable() / preempt_enable()
	local_irq_save() / local_irq_restore()
	hardirq enter / hardirq exit
	NMI enter / NMI exit
	rcu_dereference_sched()

These three flavors are used as follows:

a.	RCU applied to normal data structures.

b.	RCU applied to networking data structures that may be subjected
	to remote denial-of-service attacks.

c.	RCU applied to scheduler and interrupt/NMI-handler tasks.

Again, most uses will be of (a).  The (b) and (c) cases are important
for specialized uses, but are relatively uncommon.  The SRCU, RCU-Tasks,
RCU-Tasks-Rude, and RCU-Tasks-Trace have similar relationships among
their assorted primitives.

.. _3_whatisRCU:

3.  WHAT ARE SOME EXAMPLE USES OF CORE RCU API?
-----------------------------------------------

This section shows a simple use of the core RCU API to protect a
global pointer to a dynamically allocated structure.  More-typical
uses of RCU may be found in listRCU.rst and NMI-RCU.rst.
::

	struct foo {
		int a;
		char b;
		long c;
	};
	DEFINE_SPINLOCK(foo_mutex);

	struct foo __rcu *gbl_foo;

	/*
	 * Create a new struct foo that is the same as the one currently
	 * pointed to by gbl_foo, except that field "a" is replaced
	 * with "new_a".  Points gbl_foo to the new structure, and
	 * frees up the old structure after a grace period.
	 *
	 * Uses rcu_assign_pointer() to ensure that concurrent readers
	 * see the initialized version of the new structure.
	 *
	 * Uses synchronize_rcu() to ensure that any readers that might
	 * have references to the old structure complete before freeing
	 * the old structure.
	 */
	void foo_update_a(int new_a)
	{
		struct foo *new_fp;
		struct foo *old_fp;

		new_fp = kmalloc(sizeof(*new_fp), GFP_KERNEL);
		spin_lock(&foo_mutex);
		old_fp = rcu_dereference_protected(gbl_foo, lockdep_is_held(&foo_mutex));
		*new_fp = *old_fp;
		new_fp->a = new_a;
		rcu_assign_pointer(gbl_foo, new_fp);
		spin_unlock(&foo_mutex);
		synchronize_rcu();
		kfree(old_fp);
	}

	/*
	 * Return the value of field "a" of the current gbl_foo
	 * structure.  Use rcu_read_lock() and rcu_read_unlock()
	 * to ensure that the structure does not get deleted out
	 * from under us, and use rcu_dereference() to ensure that
	 * we see the initialized version of the structure (important
	 * for DEC Alpha and for people reading the code).
	 */
	int foo_get_a(void)
	{
		int retval;

		rcu_read_lock();
		retval = rcu_dereference(gbl_foo)->a;
		rcu_read_unlock();
		return retval;
	}

So, to sum up:

-	Use rcu_read_lock() and rcu_read_unlock() to guard RCU
	read-side critical sections.

-	Within an RCU read-side critical section, use rcu_dereference()
	to dereference RCU-protected pointers.

-	Use some solid design (such as locks or semaphores) to
	keep concurrent updates from interfering with each other.

-	Use rcu_assign_pointer() to update an RCU-protected pointer.
	This primitive protects concurrent readers from the updater,
	**not** concurrent updates from each other!  You therefore still
	need to use locking (or something similar) to keep concurrent
	rcu_assign_pointer() primitives from interfering with each other.

-	Use synchronize_rcu() **after** removing a data element from an
	RCU-protected data structure, but **before** reclaiming/freeing
	the data element, in order to wait for the completion of all
	RCU read-side critical sections that might be referencing that
	data item.

See checklist.rst for additional rules to follow when using RCU.
And again, more-typical uses of RCU may be found in listRCU.rst
and NMI-RCU.rst.

.. _4_whatisRCU:

4.  WHAT IF MY UPDATING THREAD CANNOT BLOCK?
--------------------------------------------

In the example above, foo_update_a() blocks until a grace period elapses.
This is quite simple, but in some cases one cannot afford to wait so
long -- there might be other high-priority work to be done.

In such cases, one uses call_rcu() rather than synchronize_rcu().
The call_rcu() API is as follows::

	void call_rcu(struct rcu_head *head, rcu_callback_t func);

This function invokes func(head) after a grace period has elapsed.
This invocation might happen from either softirq or process context,
so the function is not permitted to block.  The foo struct needs to
have an rcu_head structure added, perhaps as follows::

	struct foo {
		int a;
		char b;
		long c;
		struct rcu_head rcu;
	};

The foo_update_a() function might then be written as follows::

	/*
	 * Create a new struct foo that is the same as the one currently
	 * pointed to by gbl_foo, except that field "a" is replaced
	 * with "new_a".  Points gbl_foo to the new structure, and
	 * frees up the old structure after a grace period.
	 *
	 * Uses rcu_assign_pointer() to ensure that concurrent readers
	 * see the initialized version of the new structure.
	 *
	 * Uses call_rcu() to ensure that any readers that might have
	 * references to the old structure complete before freeing the
	 * old structure.
	 */
	void foo_update_a(int new_a)
	{
		struct foo *new_fp;
		struct foo *old_fp;

		new_fp = kmalloc(sizeof(*new_fp), GFP_KERNEL);
		spin_lock(&foo_mutex);
		old_fp = rcu_dereference_protected(gbl_foo, lockdep_is_held(&foo_mutex));
		*new_fp = *old_fp;
		new_fp->a = new_a;
		rcu_assign_pointer(gbl_foo, new_fp);
		spin_unlock(&foo_mutex);
		call_rcu(&old_fp->rcu, foo_reclaim);
	}

The foo_reclaim() function might appear as follows::

	void foo_reclaim(struct rcu_head *rp)
	{
		struct foo *fp = container_of(rp, struct foo, rcu);

		foo_cleanup(fp->a);

		kfree(fp);
	}

The container_of() primitive is a macro that, given a pointer into a
struct, the type of the struct, and the pointed-to field within the
struct, returns a pointer to the beginning of the struct.

The use of call_rcu() permits the caller of foo_update_a() to
immediately regain control, without needing to worry further about the
old version of the newly updated element.  It also clearly shows the
RCU distinction between updater, namely foo_update_a(), and reclaimer,
namely foo_reclaim().

The summary of advice is the same as for the previous section, except
that we are now using call_rcu() rather than synchronize_rcu():

-	Use call_rcu() **after** removing a data element from an
	RCU-protected data structure in order to register a callback
	function that will be invoked after the completion of all RCU
	read-side critical sections that might be referencing that
	data item.

If the callback for call_rcu() is not doing anything more than calling
kfree() on the structure, you can use kfree_rcu() instead of call_rcu()
to avoid having to write your own callback::

	kfree_rcu(old_fp, rcu);

If the occasional sleep is permitted, the single-argument form may
be used, omitting the rcu_head structure from struct foo.

	kfree_rcu_mightsleep(old_fp);

This variant almost never blocks, but might do so by invoking
synchronize_rcu() in response to memory-allocation failure.

Again, see checklist.rst for additional rules governing the use of RCU.

.. _5_whatisRCU:

5.  WHAT ARE SOME SIMPLE IMPLEMENTATIONS OF RCU?
------------------------------------------------

One of the nice things about RCU is that it has extremely simple "toy"
implementations that are a good first step towards understanding the
production-quality implementations in the Linux kernel.  This section
presents two such "toy" implementations of RCU, one that is implemented
in terms of familiar locking primitives, and another that more closely
resembles "classic" RCU.  Both are way too simple for real-world use,
lacking both functionality and performance.  However, they are useful
in getting a feel for how RCU works.  See kernel/rcu/update.c for a
production-quality implementation, and see:

	https://docs.google.com/document/d/1X0lThx8OK0ZgLMqVoXiR4ZrGURHrXK6NyLRbeXe3Xac/edit

for papers describing the Linux kernel RCU implementation.  The OLS'01
and OLS'02 papers are a good introduction, and the dissertation provides
more details on the current implementation as of early 2004.


5A.  "TOY" IMPLEMENTATION #1: LOCKING
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This section presents a "toy" RCU implementation that is based on
familiar locking primitives.  Its overhead makes it a non-starter for
real-life use, as does its lack of scalability.  It is also unsuitable
for realtime use, since it allows scheduling latency to "bleed" from
one read-side critical section to another.  It also assumes recursive
reader-writer locks:  If you try this with non-recursive locks, and
you allow nested rcu_read_lock() calls, you can deadlock.

However, it is probably the easiest implementation to relate to, so is
a good starting point.

It is extremely simple::

	static DEFINE_RWLOCK(rcu_gp_mutex);

	void rcu_read_lock(void)
	{
		read_lock(&rcu_gp_mutex);
	}

	void rcu_read_unlock(void)
	{
		read_unlock(&rcu_gp_mutex);
	}

	void synchronize_rcu(void)
	{
		write_lock(&rcu_gp_mutex);
		smp_mb__after_spinlock();
		write_unlock(&rcu_gp_mutex);
	}

[You can ignore rcu_assign_pointer() and rcu_dereference() without missing
much.  But here are simplified versions anyway.  And whatever you do,
don't forget about them when submitting patches making use of RCU!]::

	#define rcu_assign_pointer(p, v) \
	({ \
		smp_store_release(&(p), (v)); \
	})

	#define rcu_dereference(p) \
	({ \
		typeof(p) _________p1 = READ_ONCE(p); \
		(_________p1); \
	})


The rcu_read_lock() and rcu_read_unlock() primitive read-acquire
and release a global reader-writer lock.  The synchronize_rcu()
primitive write-acquires this same lock, then releases it.  This means
that once synchronize_rcu() exits, all RCU read-side critical sections
that were in progress before synchronize_rcu() was called are guaranteed
to have completed -- there is no way that synchronize_rcu() would have
been able to write-acquire the lock otherwise.  The smp_mb__after_spinlock()
promotes synchronize_rcu() to a full memory barrier in compliance with
the "Memory-Barrier Guarantees" listed in:

	Design/Requirements/Requirements.rst

It is possible to nest rcu_read_lock(), since reader-writer locks may
be recursively acquired.  Note also that rcu_read_lock() is immune
from deadlock (an important property of RCU).  The reason for this is
that the only thing that can block rcu_read_lock() is a synchronize_rcu().
But synchronize_rcu() does not acquire any locks while holding rcu_gp_mutex,
so there can be no deadlock cycle.

.. _quiz_1:

Quick Quiz #1:
		Why is this argument naive?  How could a deadlock
		occur when using this algorithm in a real-world Linux
		kernel?  How could this deadlock be avoided?

:ref:`Answers to Quick Quiz <9_whatisRCU>`

5B.  "TOY" EXAMPLE #2: CLASSIC RCU
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This section presents a "toy" RCU implementation that is based on
"classic RCU".  It is also short on performance (but only for updates) and
on features such as hotplug CPU and the ability to run in CONFIG_PREEMPTION
kernels.  The definitions of rcu_dereference() and rcu_assign_pointer()
are the same as those shown in the preceding section, so they are omitted.
::

	void rcu_read_lock(void) { }

	void rcu_read_unlock(void) { }

	void synchronize_rcu(void)
	{
		int cpu;

		for_each_possible_cpu(cpu)
			run_on(cpu);
	}

Note that rcu_read_lock() and rcu_read_unlock() do absolutely nothing.
This is the great strength of classic RCU in a non-preemptive kernel:
read-side overhead is precisely zero, at least on non-Alpha CPUs.
And there is absolutely no way that rcu_read_lock() can possibly
participate in a deadlock cycle!

The implementation of synchronize_rcu() simply schedules itself on each
CPU in turn.  The run_on() primitive can be implemented straightforwardly
in terms of the sched_setaffinity() primitive.  Of course, a somewhat less
"toy" implementation would restore the affinity upon completion rather
than just leaving all tasks running on the last CPU, but when I said
"toy", I meant **toy**!

So how the heck is this supposed to work???

Remember that it is illegal to block while in an RCU read-side critical
section.  Therefore, if a given CPU executes a context switch, we know
that it must have completed all preceding RCU read-side critical sections.
Once **all** CPUs have executed a context switch, then **all** preceding
RCU read-side critical sections will have completed.

So, suppose that we remove a data item from its structure and then invoke
synchronize_rcu().  Once synchronize_rcu() returns, we are guaranteed
that there are no RCU read-side critical sections holding a reference
to that data item, so we can safely reclaim it.

.. _quiz_2:

Quick Quiz #2:
		Give an example where Classic RCU's read-side
		overhead is **negative**.

:ref:`Answers to Quick Quiz <9_whatisRCU>`

.. _quiz_3:

Quick Quiz #3:
		If it is illegal to block in an RCU read-side
		critical section, what the heck do you do in
		CONFIG_PREEMPT_RT, where normal spinlocks can block???

:ref:`Answers to Quick Quiz <9_whatisRCU>`

.. _6_whatisRCU:

6.  ANALOGY WITH READER-WRITER LOCKING
--------------------------------------

Although RCU can be used in many different ways, a very common use of
RCU is analogous to reader-writer locking.  The following unified
diff shows how closely related RCU and reader-writer locking can be.
::

	@@ -5,5 +5,5 @@ struct el {
	 	int data;
	 	/* Other data fields */
	 };
	-rwlock_t listmutex;
	+spinlock_t listmutex;
	 struct el head;

	@@ -13,15 +14,15 @@
		struct list_head *lp;
		struct el *p;

	-	read_lock(&listmutex);
	-	list_for_each_entry(p, head, lp) {
	+	rcu_read_lock();
	+	list_for_each_entry_rcu(p, head, lp) {
			if (p->key == key) {
				*result = p->data;
	-			read_unlock(&listmutex);
	+			rcu_read_unlock();
				return 1;
			}
		}
	-	read_unlock(&listmutex);
	+	rcu_read_unlock();
		return 0;
	 }

	@@ -29,15 +30,16 @@
	 {
		struct el *p;

	-	write_lock(&listmutex);
	+	spin_lock(&listmutex);
		list_for_each_entry(p, head, lp) {
			if (p->key == key) {
	-			list_del(&p->list);
	-			write_unlock(&listmutex);
	+			list_del_rcu(&p->list);
	+			spin_unlock(&listmutex);
	+			synchronize_rcu();
				kfree(p);
				return 1;
			}
		}
	-	write_unlock(&listmutex);
	+	spin_unlock(&listmutex);
		return 0;
	 }

Or, for those who prefer a side-by-side listing::

 1 struct el {                          1 struct el {
 2   struct list_head list;             2   struct list_head list;
 3   long key;                          3   long key;
 4   spinlock_t mutex;                  4   spinlock_t mutex;
 5   int data;                          5   int data;
 6   /* Other data fields */            6   /* Other data fields */
 7 };                                   7 };
 8 rwlock_t listmutex;                  8 spinlock_t listmutex;
 9 struct el head;                      9 struct el head;

::

  1 int search(long key, int *result)    1 int search(long key, int *result)
  2 {                                    2 {
  3   struct list_head *lp;              3   struct list_head *lp;
  4   struct el *p;                      4   struct el *p;
  5                                      5
  6   read_lock(&listmutex);             6   rcu_read_lock();
  7   list_for_each_entry(p, head, lp) { 7   list_for_each_entry_rcu(p, head, lp) {
  8     if (p->key == key) {             8     if (p->key == key) {
  9       *result = p->data;             9       *result = p->data;
 10       read_unlock(&listmutex);      10       rcu_read_unlock();
 11       return 1;                     11       return 1;
 12     }                               12     }
 13   }                                 13   }
 14   read_unlock(&listmutex);          14   rcu_read_unlock();
 15   return 0;                         15   return 0;
 16 }                                   16 }

::

  1 int delete(long key)                 1 int delete(long key)
  2 {                                    2 {
  3   struct el *p;                      3   struct el *p;
  4                                      4
  5   write_lock(&listmutex);            5   spin_lock(&listmutex);
  6   list_for_each_entry(p, head, lp) { 6   list_for_each_entry(p, head, lp) {
  7     if (p->key == key) {             7     if (p->key == key) {
  8       list_del(&p->list);            8       list_del_rcu(&p->list);
  9       write_unlock(&listmutex);      9       spin_unlock(&listmutex);
                                        10       synchronize_rcu();
 10       kfree(p);                     11       kfree(p);
 11       return 1;                     12       return 1;
 12     }                               13     }
 13   }                                 14   }
 14   write_unlock(&listmutex);         15   spin_unlock(&listmutex);
 15   return 0;                         16   return 0;
 16 }                                   17 }

Either way, the differences are quite small.  Read-side locking moves
to rcu_read_lock() and rcu_read_unlock, update-side locking moves from
a reader-writer lock to a simple spinlock, and a synchronize_rcu()
precedes the kfree().

However, there is one potential catch: the read-side and update-side
critical sections can now run concurrently.  In many cases, this will
not be a problem, but it is necessary to check carefully regardless.
For example, if multiple independent list updates must be seen as
a single atomic update, converting to RCU will require special care.

Also, the presence of synchronize_rcu() means that the RCU version of
delete() can now block.  If this is a problem, there is a callback-based
mechanism that never blocks, namely call_rcu() or kfree_rcu(), that can
be used in place of synchronize_rcu().

.. _7_whatisRCU:

7.  ANALOGY WITH REFERENCE COUNTING
-----------------------------------

The reader-writer analogy (illustrated by the previous section) is not
always the best way to think about using RCU.  Another helpful analogy
considers RCU an effective reference count on everything which is
protected by RCU.

A reference count typically does not prevent the referenced object's
values from changing, but does prevent changes to type -- particularly the
gross change of type that happens when that object's memory is freed and
re-allocated for some other purpose.  Once a type-safe reference to the
object is obtained, some other mechanism is needed to ensure consistent
access to the data in the object.  This could involve taking a spinlock,
but with RCU the typical approach is to perform reads with SMP-aware
operations such as smp_load_acquire(), to perform updates with atomic
read-modify-write operations, and to provide the necessary ordering.
RCU provides a number of support functions that embed the required
operations and ordering, such as the list_for_each_entry_rcu() macro
used in the previous section.

A more focused view of the reference counting behavior is that,
between rcu_read_lock() and rcu_read_unlock(), any reference taken with
rcu_dereference() on a pointer marked as ``__rcu`` can be treated as
though a reference-count on that object has been temporarily increased.
This prevents the object from changing type.  Exactly what this means
will depend on normal expectations of objects of that type, but it
typically includes that spinlocks can still be safely locked, normal
reference counters can be safely manipulated, and ``__rcu`` pointers
can be safely dereferenced.

Some operations that one might expect to see on an object for
which an RCU reference is held include:

 - Copying out data that is guaranteed to be stable by the object's type.
 - Using kref_get_unless_zero() or similar to get a longer-term
   reference.  This may fail of course.
 - Acquiring a spinlock in the object, and checking if the object still
   is the expected object and if so, manipulating it freely.

The understanding that RCU provides a reference that only prevents a
change of type is particularly visible with objects allocated from a
slab cache marked ``SLAB_TYPESAFE_BY_RCU``.  RCU operations may yield a
reference to an object from such a cache that has been concurrently freed
and the memory reallocated to a completely different object, though of
the same type.  In this case RCU doesn't even protect the identity of the
object from changing, only its type.  So the object found may not be the
one expected, but it will be one where it is safe to take a reference
(and then potentially acquiring a spinlock), allowing subsequent code
to check whether the identity matches expectations.  It is tempting
to simply acquire the spinlock without first taking the reference, but
unfortunately any spinlock in a ``SLAB_TYPESAFE_BY_RCU`` object must be
initialized after each and every call to kmem_cache_alloc(), which renders
reference-free spinlock acquisition completely unsafe.  Therefore, when
using ``SLAB_TYPESAFE_BY_RCU``, make proper use of a reference counter.
If using refcount_t, the specialized refcount_{add|inc}_not_zero_acquire()
and refcount_set_release() APIs should be used to ensure correct operation
ordering when verifying object identity and when initializing newly
allocated objects. Acquire fence in refcount_{add|inc}_not_zero_acquire()
ensures that identity checks happen *after* reference count is taken.
refcount_set_release() should be called after a newly allocated object is
fully initialized and release fence ensures that new values are visible
*before* refcount can be successfully taken by other users. Once
refcount_set_release() is called, the object should be considered visible
by other tasks.
(Those willing to initialize their locks in a kmem_cache constructor
may also use locking, including cache-friendly sequence locking.)

With traditional reference counting -- such as that implemented by the
kref library in Linux -- there is typically code that runs when the last
reference to an object is dropped.  With kref, this is the function
passed to kref_put().  When RCU is being used, such finalization code
must not be run until all ``__rcu`` pointers referencing the object have
been updated, and then a grace period has passed.  Every remaining
globally visible pointer to the object must be considered to be a
potential counted reference, and the finalization code is typically run
using call_rcu() only after all those pointers have been changed.

To see how to choose between these two analogies -- of RCU as a
reader-writer lock and RCU as a reference counting system -- it is useful
to reflect on the scale of the thing being protected.  The reader-writer
lock analogy looks at larger multi-part objects such as a linked list
and shows how RCU can facilitate concurrency while elements are added
to, and removed from, the list.  The reference-count analogy looks at
the individual objects and looks at how they can be accessed safely
within whatever whole they are a part of.

.. _8_whatisRCU:

8.  FULL LIST OF RCU APIs
-------------------------

The RCU APIs are documented in docbook-format header comments in the
Linux-kernel source code, but it helps to have a full list of the
APIs, since there does not appear to be a way to categorize them
in docbook.  Here is the list, by category.

RCU list traversal::

	list_entry_rcu
	list_entry_lockless
	list_first_entry_rcu
	list_first_or_null_rcu
	list_tail_rcu
	list_next_rcu
	list_next_or_null_rcu
	list_for_each_entry_rcu
	list_for_each_entry_continue_rcu
	list_for_each_entry_from_rcu
	list_for_each_entry_lockless
	hlist_first_rcu
	hlist_next_rcu
	hlist_pprev_rcu
	hlist_for_each_entry_rcu
	hlist_for_each_entry_rcu_notrace
	hlist_for_each_entry_rcu_bh
	hlist_for_each_entry_from_rcu
	hlist_for_each_entry_continue_rcu
	hlist_for_each_entry_continue_rcu_bh
	hlist_nulls_first_rcu
	hlist_nulls_next_rcu
	hlist_nulls_for_each_entry_rcu
	hlist_nulls_for_each_entry_safe
	hlist_bl_first_rcu
	hlist_bl_for_each_entry_rcu

RCU pointer/list update::

	rcu_assign_pointer
	rcu_replace_pointer
	INIT_LIST_HEAD_RCU
	list_add_rcu
	list_add_tail_rcu
	list_del_rcu
	list_replace_rcu
	list_splice_init_rcu
	list_splice_tail_init_rcu
	hlist_add_behind_rcu
	hlist_add_before_rcu
	hlist_add_head_rcu
	hlist_add_tail_rcu
	hlist_del_rcu
	hlist_del_init_rcu
	hlist_replace_rcu
	hlist_nulls_del_init_rcu
	hlist_nulls_del_rcu
	hlist_nulls_add_head_rcu
	hlist_nulls_add_tail_rcu
	hlist_nulls_add_fake
	hlists_swap_heads_rcu
	hlist_bl_add_head_rcu
	hlist_bl_del_rcu
	hlist_bl_set_first_rcu

RCU::

	Critical sections		Grace period		Barrier

	rcu_read_lock			synchronize_net		rcu_barrier
	rcu_read_unlock			synchronize_rcu
	guard(rcu)()			synchronize_rcu_expedited
	scoped_guard(rcu)		synchronize_rcu_mult
	rcu_dereference			call_rcu
	rcu_dereference_check		call_rcu_hurry
	rcu_dereference_protected	kfree_rcu
	rcu_read_lock_held		kvfree_rcu
	rcu_read_lock_any_held		kfree_rcu_mightsleep
	rcu_pointer_handoff		cond_synchronize_rcu
	unrcu_pointer			cond_synchronize_rcu_full
					cond_synchronize_rcu_expedited
					cond_synchronize_rcu_expedited_full
					get_completed_synchronize_rcu
					get_completed_synchronize_rcu_full
					get_state_synchronize_rcu
					get_state_synchronize_rcu_full
					poll_state_synchronize_rcu
					poll_state_synchronize_rcu_full
					same_state_synchronize_rcu
					same_state_synchronize_rcu_full
					start_poll_synchronize_rcu
					start_poll_synchronize_rcu_full
					start_poll_synchronize_rcu_expedited
					start_poll_synchronize_rcu_expedited_full

bh::

	Critical sections	Grace period		Barrier

	rcu_read_lock_bh	[Same as RCU]		[Same as RCU]
	rcu_read_unlock_bh
	[local_bh_disable]
	[and friends]
	rcu_dereference_bh
	rcu_dereference_bh_check
	rcu_dereference_bh_protected
	rcu_read_lock_bh_held

sched::

	Critical sections	Grace period		Barrier

	rcu_read_lock_sched	[Same as RCU]		[Same as RCU]
	rcu_read_unlock_sched
	[preempt_disable]
	[and friends]
	rcu_read_lock_sched_notrace
	rcu_read_unlock_sched_notrace
	rcu_dereference_sched
	rcu_dereference_sched_check
	rcu_dereference_sched_protected
	rcu_read_lock_sched_held


RCU: Initialization/cleanup/ordering::

	RCU_INIT_POINTER
	RCU_INITIALIZER
	RCU_POINTER_INITIALIZER
	init_rcu_head
	destroy_rcu_head
	init_rcu_head_on_stack
	destroy_rcu_head_on_stack
	SLAB_TYPESAFE_BY_RCU


RCU: Quiescents states and control::

	cond_resched_tasks_rcu_qs
	rcu_all_qs
	rcu_softirq_qs_periodic
	rcu_end_inkernel_boot
	rcu_expedite_gp
	rcu_gp_is_expedited
	rcu_unexpedite_gp
	rcu_cpu_stall_reset
	rcu_head_after_call_rcu
	rcu_is_watching


RCU-sync primitive::

	rcu_sync_is_idle
	rcu_sync_init
	rcu_sync_enter
	rcu_sync_exit
	rcu_sync_dtor


RCU-Tasks::

	Critical sections	Grace period			Barrier

	N/A			call_rcu_tasks			rcu_barrier_tasks
				synchronize_rcu_tasks


RCU-Tasks-Rude::

	Critical sections	Grace period			Barrier

	N/A			synchronize_rcu_tasks_rude	rcu_barrier_tasks_rude
				call_rcu_tasks_rude


RCU-Tasks-Trace::

	Critical sections	Grace period			Barrier

	rcu_read_lock_trace	call_rcu_tasks_trace		rcu_barrier_tasks_trace
	rcu_read_unlock_trace	synchronize_rcu_tasks_trace
	guard(rcu_tasks_trace)()
	scoped_guard(rcu_tasks_trace)


SRCU list traversal::
	list_for_each_entry_srcu
	hlist_for_each_entry_srcu


SRCU::

	Critical sections		Grace period		Barrier

	srcu_read_lock			call_srcu		srcu_barrier
	srcu_read_unlock		synchronize_srcu
	srcu_read_lock_fast		synchronize_srcu_expedited
	srcu_read_unlock_fast		get_state_synchronize_srcu
	srcu_read_lock_nmisafe		start_poll_synchronize_srcu
	srcu_read_unlock_nmisafe	start_poll_synchronize_srcu_expedited
	srcu_read_lock_notrace		poll_state_synchronize_srcu
	srcu_read_unlock_notrace
	srcu_down_read
	srcu_up_read
	srcu_down_read_fast
	srcu_up_read_fast
	guard(srcu)()
	scoped_guard(srcu)
	srcu_read_lock_held
	srcu_dereference
	srcu_dereference_check
	srcu_dereference_notrace
	srcu_read_lock_held


SRCU: Initialization/cleanup/ordering::

	DEFINE_SRCU
	DEFINE_STATIC_SRCU
	init_srcu_struct
	cleanup_srcu_struct
	smp_mb__after_srcu_read_unlock

All: lockdep-checked RCU utility APIs::

	RCU_LOCKDEP_WARN
	rcu_sleep_check

All: Unchecked RCU-protected pointer access::

	rcu_dereference_raw

All: Unchecked RCU-protected pointer access with dereferencing prohibited::

	rcu_access_pointer

See the comment headers in the source code (or the docbook generated
from them) for more information.

However, given that there are no fewer than four families of RCU APIs
in the Linux kernel, how do you choose which one to use?  The following
list can be helpful:

a.	Will readers need to block?  If so, you need SRCU.

b.	Will readers need to block and are you doing tracing, for
	example, ftrace or BPF?  If so, you need RCU-tasks,
	RCU-tasks-rude, and/or RCU-tasks-trace.

c.	What about the -rt patchset?  If readers would need to block in
	an non-rt kernel, you need SRCU.  If readers would block when
	acquiring spinlocks in a -rt kernel, but not in a non-rt kernel,
	SRCU is not necessary.	(The -rt patchset turns spinlocks into
	sleeplocks, hence this distinction.)

d.	Do you need to treat NMI handlers, hardirq handlers,
	and code segments with preemption disabled (whether
	via preempt_disable(), local_irq_save(), local_bh_disable(),
	or some other mechanism) as if they were explicit RCU readers?
	If so, RCU-sched readers are the only choice that will work
	for you, but since about v4.20 you use can use the vanilla RCU
	update primitives.

e.	Do you need RCU grace periods to complete even in the face of
	softirq monopolization of one or more of the CPUs?  For example,
	is your code subject to network-based denial-of-service attacks?
	If so, you should disable softirq across your readers, for
	example, by using rcu_read_lock_bh().  Since about v4.20 you
	use can use the vanilla RCU update primitives.

f.	Is your workload too update-intensive for normal use of
	RCU, but inappropriate for other synchronization mechanisms?
	If so, consider SLAB_TYPESAFE_BY_RCU (which was originally
	named SLAB_DESTROY_BY_RCU).  But please be careful!

g.	Do you need read-side critical sections that are respected even
	on CPUs that are deep in the idle loop, during entry to or exit
	from user-mode execution, or on an offlined CPU?  If so, SRCU
	and RCU Tasks Trace are the only choices that will work for you,
	with SRCU being strongly preferred in almost all cases.

h.	Otherwise, use RCU.

Of course, this all assumes that you have determined that RCU is in fact
the right tool for your job.

.. _9_whatisRCU:

9.  ANSWERS TO QUICK QUIZZES
----------------------------

Quick Quiz #1:
		Why is this argument naive?  How could a deadlock
		occur when using this algorithm in a real-world Linux
		kernel?  [Referring to the lock-based "toy" RCU
		algorithm.]

Answer:
		Consider the following sequence of events:

		1.	CPU 0 acquires some unrelated lock, call it
			"problematic_lock", disabling irq via
			spin_lock_irqsave().

		2.	CPU 1 enters synchronize_rcu(), write-acquiring
			rcu_gp_mutex.

		3.	CPU 0 enters rcu_read_lock(), but must wait
			because CPU 1 holds rcu_gp_mutex.

		4.	CPU 1 is interrupted, and the irq handler
			attempts to acquire problematic_lock.

		The system is now deadlocked.

		One way to avoid this deadlock is to use an approach like
		that of CONFIG_PREEMPT_RT, where all normal spinlocks
		become blocking locks, and all irq handlers execute in
		the context of special tasks.  In this case, in step 4
		above, the irq handler would block, allowing CPU 1 to
		release rcu_gp_mutex, avoiding the deadlock.

		Even in the absence of deadlock, this RCU implementation
		allows latency to "bleed" from readers to other
		readers through synchronize_rcu().  To see this,
		consider task A in an RCU read-side critical section
		(thus read-holding rcu_gp_mutex), task B blocked
		attempting to write-acquire rcu_gp_mutex, and
		task C blocked in rcu_read_lock() attempting to
		read_acquire rcu_gp_mutex.  Task A's RCU read-side
		latency is holding up task C, albeit indirectly via
		task B.

		Realtime RCU implementations therefore use a counter-based
		approach where tasks in RCU read-side critical sections
		cannot be blocked by tasks executing synchronize_rcu().

:ref:`Back to Quick Quiz #1 <quiz_1>`

Quick Quiz #2:
		Give an example where Classic RCU's read-side
		overhead is **negative**.

Answer:
		Imagine a single-CPU system with a non-CONFIG_PREEMPTION
		kernel where a routing table is used by process-context
		code, but can be updated by irq-context code (for example,
		by an "ICMP REDIRECT" packet).	The usual way of handling
		this would be to have the process-context code disable
		interrupts while searching the routing table.  Use of
		RCU allows such interrupt-disabling to be dispensed with.
		Thus, without RCU, you pay the cost of disabling interrupts,
		and with RCU you don't.

		One can argue that the overhead of RCU in this
		case is negative with respect to the single-CPU
		interrupt-disabling approach.  Others might argue that
		the overhead of RCU is merely zero, and that replacing
		the positive overhead of the interrupt-disabling scheme
		with the zero-overhead RCU scheme does not constitute
		negative overhead.

		In real life, of course, things are more complex.  But
		even the theoretical possibility of negative overhead for
		a synchronization primitive is a bit unexpected.  ;-)

:ref:`Back to Quick Quiz #2 <quiz_2>`

Quick Quiz #3:
		If it is illegal to block in an RCU read-side
		critical section, what the heck do you do in
		CONFIG_PREEMPT_RT, where normal spinlocks can block???

Answer:
		Just as CONFIG_PREEMPT_RT permits preemption of spinlock
		critical sections, it permits preemption of RCU
		read-side critical sections.  It also permits
		spinlocks blocking while in RCU read-side critical
		sections.

		Why the apparent inconsistency?  Because it is
		possible to use priority boosting to keep the RCU
		grace periods short if need be (for example, if running
		short of memory).  In contrast, if blocking waiting
		for (say) network reception, there is no way to know
		what should be boosted.  Especially given that the
		process we need to boost might well be a human being
		who just went out for a pizza or something.  And although
		a computer-operated cattle prod might arouse serious
		interest, it might also provoke serious objections.
		Besides, how does the computer know what pizza parlor
		the human being went to???

:ref:`Back to Quick Quiz #3 <quiz_3>`

ACKNOWLEDGEMENTS

My thanks to the people who helped make this human-readable, including
Jon Walpole, Josh Triplett, Serge Hallyn, Suzanne Wood, and Alan Stern.


For more information, see http://www.rdrop.com/users/paulmck/RCU.

---

### Documentation Accel Index (`Documentation/accel/index.rst`)

.. SPDX-License-Identifier: GPL-2.0

====================
Compute Accelerators
====================

.. toctree::
   :maxdepth: 1

   introduction
   amdxdna/index
   qaic/index
   rocket/index

.. only::  subproject and html

   Indices
   =======

   * :ref:`genindex`

---

### Documentation Accel Introduction (`Documentation/accel/introduction.rst`)

.. SPDX-License-Identifier: GPL-2.0

============
Introduction
============

The Linux compute accelerators subsystem is designed to expose compute
accelerators in a common way to user-space and provide a common set of
functionality.

These devices can be either stand-alone ASICs or IP blocks inside an SoC/GPU.
Although these devices are typically designed to accelerate
Machine-Learning (ML) and/or Deep-Learning (DL) computations, the accel layer
is not limited to handling these types of accelerators.

Typically, a compute accelerator will belong to one of the following
categories:

- Edge AI - doing inference at an edge device. It can be an embedded ASIC/FPGA,
  or an IP inside a SoC (e.g. laptop web camera). These devices
  are typically configured using registers and can work with or without DMA.

- Inference data-center - single/multi user devices in a large server. This
  type of device can be stand-alone or an IP inside a SoC or a GPU. It will
  have on-board DRAM (to hold the DL topology), DMA engines and
  command submission queues (either kernel or user-space queues).
  It might also have an MMU to manage multiple users and might also enable
  virtualization (SR-IOV) to support multiple VMs on the same device. In
  addition, these devices will usually have some tools, such as profiler and
  debugger.

- Training data-center - Similar to Inference data-center cards, but typically
  have more computational power and memory b/w (e.g. HBM) and will likely have
  a method of scaling-up/out, i.e. connecting to other training cards inside
  the server or in other servers, respectively.

All these devices typically have different runtime user-space software stacks,
that are tailored-made to their h/w. In addition, they will also probably
include a compiler to generate programs to their custom-made computational
engines. Typically, the common layer in user-space will be the DL frameworks,
such as PyTorch and TensorFlow.

Sharing code with DRM
=====================

Because this type of devices can be an IP inside GPUs or have similar
characteristics as those of GPUs, the accel subsystem will use the
DRM subsystem's code and functionality. i.e. the accel core code will
be part of the DRM subsystem and an accel device will be a new type of DRM
device.

This will allow us to leverage the extensive DRM code-base and
collaborate with DRM developers that have experience with this type of
devices. In addition, new features that will be added for the accelerator
drivers can be of use to GPU drivers as well.

Differentiation from GPUs
=========================

Because we want to prevent the extensive user-space graphic software stack
from trying to use an accelerator as a GPU, the compute accelerators will be
differentiated from GPUs by using a new major number and new device char files.

Furthermore, the drivers will be located in a separate place in the kernel
tree - drivers/accel/.

The accelerator devices will be exposed to the user space with the dedicated
261 major number and will have the following convention:

- device char files - /dev/accel/accel\*
- sysfs             - /sys/class/accel/accel\*/
- debugfs           - /sys/kernel/debug/accel/\*/

Getting Started
===============

First, read the DRM documentation at Documentation/gpu/index.rst.
Not only it will explain how to write a new DRM driver but it will also
contain all the information on how to contribute, the Code Of Conduct and
what is the coding style/documentation. All of that is the same for the
accel subsystem.

Second, make sure the kernel is configured with CONFIG_DRM_ACCEL.

To expose your device as an accelerator, two changes are needed to
be done in your driver (as opposed to a standard DRM driver):

- Add the DRIVER_COMPUTE_ACCEL feature flag in your drm_driver's
  driver_features field. It is important to note that this driver feature is
  mutually exclusive with DRIVER_RENDER and DRIVER_MODESET. Devices that want
  to expose both graphics and compute device char files should be handled by
  two drivers that are connected using the auxiliary bus framework.

- Change the open callback in your driver fops structure to accel_open().
  Alternatively, your driver can use DEFINE_DRM_ACCEL_FOPS macro to easily
  set the correct function operations pointers structure.

External References
===================

email threads
-------------

* `Initial discussion on the New subsystem for acceleration devices <https://lore.kernel.org/lkml/CAFCwf11=9qpNAepL7NL+YAV_QO=Wv6pnWPhKHKAepK3fNn+2Dg@mail.gmail.com/>`_ - Oded Gabbay (2022)
* `patch-set to add the new subsystem <https://lore.kernel.org/lkml/20221022214622.18042-1-ogabbay@kernel.org/>`_ - Oded Gabbay (2022)

Conference talks
----------------

* `LPC 2022 Accelerators BOF outcomes summary <https://airlied.blogspot.com/2022/09/accelerators-bof-outcomes-summary.html>`_ - Dave Airlie (2022)

---

### Documentation Accounting Cgroupstats (`Documentation/accounting/cgroupstats.rst`)

==================
Control Groupstats
==================

Control Groupstats is inspired by the discussion at
https://lore.kernel.org/r/461CF883.2030308@sw.ru and implements per cgroup statistics as
suggested by Andrew Morton in https://lore.kernel.org/r/20070411114927.1277d7c9.akpm@linux-foundation.org.

Per cgroup statistics infrastructure re-uses code from the taskstats
interface. A new set of cgroup operations are registered with commands
and attributes specific to cgroups. It should be very easy to
extend per cgroup statistics, by adding members to the cgroupstats
structure.

The current model for cgroupstats is a pull, a push model (to post
statistics on interesting events), should be very easy to add. Currently
user space requests for statistics by passing the cgroup path.
Statistics about the state of all the tasks in the cgroup is returned to
user space.

NOTE: We currently rely on delay accounting for extracting information
about tasks blocked on I/O. If CONFIG_TASK_DELAY_ACCT is disabled, this
information will not be available.

To extract cgroup statistics a utility very similar to getdelays.c
has been developed, the sample output of the utility is shown below::

  ~/balbir/cgroupstats # ./getdelays  -C "/sys/fs/cgroup/a"
  sleeping 1, blocked 0, running 1, stopped 0, uninterruptible 0
  ~/balbir/cgroupstats # ./getdelays  -C "/sys/fs/cgroup"
  sleeping 155, blocked 0, running 1, stopped 0, uninterruptible 2

---

### Documentation Accounting Delay Accounting (`Documentation/accounting/delay-accounting.rst`)

================
Delay accounting
================

Tasks encounter delays in execution when they wait
for some kernel resource to become available e.g. a
runnable task may wait for a free CPU to run on.

The per-task delay accounting functionality measures
the delays experienced by a task while

a) waiting for a CPU (while being runnable)
b) completion of synchronous block I/O initiated by the task
c) swapping in pages
d) memory reclaim
e) thrashing
f) direct compact
g) write-protect copy
h) IRQ/SOFTIRQ

and makes these statistics available to userspace through
the taskstats interface.

Such delays provide feedback for setting a task's cpu priority,
io priority and rss limit values appropriately. Long delays for
important tasks could be a trigger for raising its corresponding priority.

The functionality, through its use of the taskstats interface, also provides
delay statistics aggregated for all tasks (or threads) belonging to a
thread group (corresponding to a traditional Unix process). This is a commonly
needed aggregation that is more efficiently done by the kernel.

Userspace utilities, particularly resource management applications, can also
aggregate delay statistics into arbitrary groups. To enable this, delay
statistics of a task are available both during its lifetime as well as on its
exit, ensuring continuous and complete monitoring can be done.


Interface
---------

Delay accounting uses the taskstats interface which is described
in detail in a separate document in this directory. Taskstats returns a
generic data structure to userspace corresponding to per-pid and per-tgid
statistics. The delay accounting functionality populates specific fields of
this structure. See

     include/uapi/linux/taskstats.h

for a description of the fields pertaining to delay accounting.
It will generally be in the form of counters returning the cumulative
delay seen for cpu, sync block I/O, swapin, memory reclaim, thrash page
cache, direct compact, write-protect copy, IRQ/SOFTIRQ etc.

Taking the difference of two successive readings of a given
counter (say cpu_delay_total) for a task will give the delay
experienced by the task waiting for the corresponding resource
in that interval.

When a task exits, records containing the per-task statistics
are sent to userspace without requiring a command. If it is the last exiting
task of a thread group, the per-tgid statistics are also sent. More details
are given in the taskstats interface description.

The getdelays.c userspace utility in tools/accounting directory allows simple
commands to be run and the corresponding delay statistics to be displayed. It
also serves as an example of using the taskstats interface.

Usage
-----

Compile the kernel with::

	CONFIG_TASK_DELAY_ACCT=y
	CONFIG_TASKSTATS=y

Delay accounting is disabled by default at boot up.
To enable, add::

   delayacct

to the kernel boot options. The rest of the instructions below assume this has
been done. Alternatively, use sysctl kernel.task_delayacct to switch the state
at runtime. Note however that only tasks started after enabling it will have
delayacct information.

After the system has booted up, use a utility
similar to  getdelays.c to access the delays
seen by a given task or a task group (tgid).
The utility also allows a given command to be
executed and the corresponding delays to be
seen.

General format of the getdelays command::

	getdelays [-dilv] [-t tgid] [-p pid]

Get delays, since system boot, for pid 10::

	# ./getdelays -d -p 10
	(output similar to next case)

Get sum and peak of delays, since system boot, for all pids with tgid 242::

	bash-4.4# ./getdelays -d -t 242
	print delayacct stats ON
	TGID    242


	CPU         count     real total  virtual total    delay total  delay average      delay max      delay min
	               39      156000000      156576579        2111069          0.054ms     0.212296ms     0.031307ms
	IO          count    delay total  delay average      delay max      delay min
	                0              0          0.000ms     0.000000ms     0.000000ms
	SWAP        count    delay total  delay average      delay max      delay min
	                0              0          0.000ms     0.000000ms     0.000000ms
	RECLAIM     count    delay total  delay average      delay max      delay min
	                0              0          0.000ms     0.000000ms     0.000000ms
	THRASHING   count    delay total  delay average      delay max      delay min
	                0              0          0.000ms     0.000000ms     0.000000ms
	COMPACT     count    delay total  delay average      delay max      delay min
	                0              0          0.000ms     0.000000ms     0.000000ms
	WPCOPY      count    delay total  delay average      delay max      delay min
	              156       11215873          0.072ms     0.207403ms     0.033913ms
	IRQ         count    delay total  delay average      delay max      delay min
	                0              0          0.000ms     0.000000ms     0.000000ms

Get IO accounting for pid 1, it works only with -p::

	# ./getdelays -i -p 1
	printing IO accounting
	linuxrc: read=65536, write=0, cancelled_write=0

The above command can be used with -v to get more debug information.

After the system starts, use `delaytop` to get the system-wide delay information,
which includes system-wide PSI information and Top-N high-latency tasks.
Note: PSI support requires `CONFIG_PSI=y` and `psi=1` for full functionality.

`delaytop` is an interactive tool for monitoring system pressure and task delays.
It supports multiple sorting options, display modes, and real-time keyboard controls.

Basic usage with default settings (sorts by CPU delay, shows top 20 tasks, refreshes every 2 seconds)::

	bash# ./delaytop
	System Pressure Information: (avg10/avg60vg300/total)
	CPU some:       0.0%/   0.0%/   0.0%/  106137(ms)
	CPU full:       0.0%/   0.0%/   0.0%/       0(ms)
	Memory full:    0.0%/   0.0%/   0.0%/       0(ms)
	Memory some:    0.0%/   0.0%/   0.0%/       0(ms)
	IO full:        0.0%/   0.0%/   0.0%/    2240(ms)
	IO some:        0.0%/   0.0%/   0.0%/    2783(ms)
	IRQ full:       0.0%/   0.0%/   0.0%/       0(ms)
	[o]sort [M]memverbose [q]quit
	Top 20 processes (sorted by cpu delay):
		PID      TGID  COMMAND           CPU(ms)   IO(ms)  IRQ(ms)  MEM(ms)
	------------------------------------------------------------------------
		110       110  kworker/15:0H-s   27.91     0.00     0.00     0.00
		57        57  cpuhp/7            3.18     0.00     0.00     0.00
		99        99  cpuhp/14           2.97     0.00     0.00     0.00
		51        51  cpuhp/6            0.90     0.00     0.00     0.00
		44        44  kworker/4:0H-sy    0.80     0.00     0.00     0.00
		60        60  ksoftirqd/7        0.74     0.00     0.00     0.00
		76        76  idle_inject/10     0.31     0.00     0.00     0.00
		100       100  idle_inject/14     0.30     0.00     0.00     0.00
		1309      1309  systemsettings     0.29     0.00     0.00     0.00
		45        45  cpuhp/5            0.22     0.00     0.00     0.00
		63        63  cpuhp/8            0.20     0.00     0.00     0.00
		87        87  cpuhp/12           0.18     0.00     0.00     0.00
		93        93  cpuhp/13           0.17     0.00     0.00     0.00
		1265      1265  acpid              0.17     0.00     0.00     0.00
		1552      1552  sshd               0.17     0.00     0.00     0.00
		2584      2584  sddm-helper        0.16     0.00     0.00     0.00
		1284      1284  rtkit-daemon       0.15     0.00     0.00     0.00
		1326      1326  nde-netfilter      0.14     0.00     0.00     0.00
		27        27  cpuhp/2            0.13     0.00     0.00     0.00
		631       631  kworker/11:2-rc    0.11     0.00     0.00     0.00

Interactive keyboard controls during runtime::

	o - Select sort field (CPU, IO, IRQ, Memory, etc.)
	M - Toggle display mode (Default/Memory Verbose)
	q - Quit

Available sort fields(use -s/--sort or interactive command)::

	cpu(c)       - CPU delay
	blkio(i)     - I/O delay
	irq(q)       - IRQ delay
	mem(m)       - Total memory delay
	swapin(s)    - Swapin delay (memory verbose mode only)
	freepages(r) - Freepages reclaim delay (memory verbose mode only)
	thrashing(t) - Thrashing delay (memory verbose mode only)
	compact(p)   - Compaction delay (memory verbose mode only)
	wpcopy(w)    - Write page copy delay (memory verbose mode only)

Advanced usage examples::

	# ./delaytop -s blkio
	Sorted by IO delay

	# ./delaytop -s mem -M
	Sorted by memory delay in memory verbose mode

	# ./delaytop -p pid
	Print delayacct stats

	# ./delaytop -P num
	Display the top N tasks

	# ./delaytop -n num
	Set delaytop refresh frequency (num times)

	# ./delaytop -d secs
	Specify refresh interval as secs

---

### Documentation Accounting Index (`Documentation/accounting/index.rst`)

.. SPDX-License-Identifier: GPL-2.0

==========
Accounting
==========

.. toctree::
   :maxdepth: 1

   cgroupstats
   delay-accounting
   psi
   taskstats
   taskstats-struct

---

### Documentation Accounting Psi (`Documentation/accounting/psi.rst`)

.. _psi:

================================
PSI - Pressure Stall Information
================================

:Date: April, 2018
:Author: Johannes Weiner <hannes@cmpxchg.org>

When CPU, memory or IO devices are contended, workloads experience
latency spikes, throughput losses, and run the risk of OOM kills.

Without an accurate measure of such contention, users are forced to
either play it safe and under-utilize their hardware resources, or
roll the dice and frequently suffer the disruptions resulting from
excessive overcommit.

The psi feature identifies and quantifies the disruptions caused by
such resource crunches and the time impact it has on complex workloads
or even entire systems.

Having an accurate measure of productivity losses caused by resource
scarcity aids users in sizing workloads to hardware--or provisioning
hardware according to workload demand.

As psi aggregates this information in realtime, systems can be managed
dynamically using techniques such as load shedding, migrating jobs to
other systems or data centers, or strategically pausing or killing low
priority or restartable batch jobs.

This allows maximizing hardware utilization without sacrificing
workload health or risking major disruptions such as OOM kills.

Pressure interface
==================

Pressure information for each resource is exported through the
respective file in /proc/pressure/ -- cpu, memory, and io.

The format is as such::

	some avg10=0.00 avg60=0.00 avg300=0.00 total=0
	full avg10=0.00 avg60=0.00 avg300=0.00 total=0

The "some" line indicates the share of time in which at least some
tasks are stalled on a given resource.

The "full" line indicates the share of time in which all non-idle
tasks are stalled on a given resource simultaneously. In this state
actual CPU cycles are going to waste, and a workload that spends
extended time in this state is considered to be thrashing. This has
severe impact on performance, and it's useful to distinguish this
situation from a state where some tasks are stalled but the CPU is
still doing productive work. As such, time spent in this subset of the
stall state is tracked separately and exported in the "full" averages.

CPU full is undefined at the system level, but has been reported
since 5.13, so it is set to zero for backward compatibility.

The ratios (in %) are tracked as recent trends over ten, sixty, and
three hundred second windows, which gives insight into short term events
as well as medium and long term trends. The total absolute stall time
(in us) is tracked and exported as well, to allow detection of latency
spikes which wouldn't necessarily make a dent in the time averages,
or to average trends over custom time frames.

Monitoring for pressure thresholds
==================================

Users can register triggers and use poll() to be woken up when resource
pressure exceeds certain thresholds.

A trigger describes the maximum cumulative stall time over a specific
time window, e.g. 100ms of total stall time within any 500ms window to
generate a wakeup event.

To register a trigger user has to open psi interface file under
/proc/pressure/ representing the resource to be monitored and write the
desired threshold and time window. The open file descriptor should be
used to wait for trigger events using select(), poll() or epoll().
The following format is used::

	<some|full> <stall amount in us> <time window in us>

For example writing "some 150000 1000000" into /proc/pressure/memory
would add 150ms threshold for partial memory stall measured within
1sec time window. Writing "full 50000 1000000" into /proc/pressure/io
would add 50ms threshold for full io stall measured within 1sec time window.

Triggers can be set on more than one psi metric and more than one trigger
for the same psi metric can be specified. However for each trigger a separate
file descriptor is required to be able to poll it separately from others,
therefore for each trigger a separate open() syscall should be made even
when opening the same psi interface file. Write operations to a file descriptor
with an already existing psi trigger will fail with EBUSY.

Monitors activate only when system enters stall state for the monitored
psi metric and deactivates upon exit from the stall state. While system is
in the stall state psi signal growth is monitored at a rate of 10 times per
tracking window.

The kernel accepts window sizes ranging from 500ms to 10s, therefore min
monitoring update interval is 50ms and max is 1s. Min limit is set to
prevent overly frequent polling. Max limit is chosen as a high enough number
after which monitors are most likely not needed and psi averages can be used
instead.

Unprivileged users can also create monitors, with the only limitation that the
window size must be a multiple of 2s, in order to prevent excessive resource
usage.

When activated, psi monitor stays active for at least the duration of one
tracking window to avoid repeated activations/deactivations when system is
bouncing in and out of the stall state.

Notifications to the userspace are rate-limited to one per tracking window.

The trigger will de-register when the file descriptor used to define the
trigger  is closed.

Userspace monitor usage example
===============================

::

  #include <errno.h>
  #include <fcntl.h>
  #include <stdio.h>
  #include <poll.h>
  #include <string.h>
  #include <unistd.h>

  /*
   * Monitor memory partial stall with 1s tracking window size
   * and 150ms threshold.
   */
  int main() {
	const char trig[] = "some 150000 1000000";
	struct pollfd fds;
	int n;

	fds.fd = open("/proc/pressure/memory", O_RDWR | O_NONBLOCK);
	if (fds.fd < 0) {
		printf("/proc/pressure/memory open error: %s\n",
			strerror(errno));
		return 1;
	}
	fds.events = POLLPRI;

	if (write(fds.fd, trig, strlen(trig) + 1) < 0) {
		printf("/proc/pressure/memory write error: %s\n",
			strerror(errno));
		return 1;
	}

	printf("waiting for events...\n");
	while (1) {
		n = poll(&fds, 1, -1);
		if (n < 0) {
			printf("poll error: %s\n", strerror(errno));
			return 1;
		}
		if (fds.revents & POLLERR) {
			printf("got POLLERR, event source is gone\n");
			return 0;
		}
		if (fds.revents & POLLPRI) {
			printf("event triggered!\n");
		} else {
			printf("unknown event received: 0x%x\n", fds.revents);
			return 1;
		}
	}

	return 0;
  }

Cgroup2 interface
=================

In a system with a CONFIG_CGROUPS=y kernel and the cgroup2 filesystem
mounted, pressure stall information is also tracked for tasks grouped
into cgroups. Each subdirectory in the cgroupfs mountpoint contains
cpu.pressure, memory.pressure, and io.pressure files; the format is
the same as the /proc/pressure/ files.

Per-cgroup psi monitors can be specified and used the same way as
system-wide ones.

---

### Documentation Accounting Taskstats Struct (`Documentation/accounting/taskstats-struct.rst`)

====================
The struct taskstats
====================

This document contains an explanation of the struct taskstats fields.

There are three different groups of fields in the struct taskstats:

1) Common and basic accounting fields
    If CONFIG_TASKSTATS is set, the taskstats interface is enabled and
    the common fields and basic accounting fields are collected for
    delivery at do_exit() of a task.
2) Delay accounting fields
    These fields are placed between::

	/* Delay accounting fields start */

    and::

	/* Delay accounting fields end */

    Their values are collected if CONFIG_TASK_DELAY_ACCT is set.
3) Extended accounting fields
    These fields are placed between::

	/* Extended accounting fields start */

    and::

	/* Extended accounting fields end */

    Their values are collected if CONFIG_TASK_XACCT is set.

4) Per-task and per-thread context switch count statistics

5) Time accounting for SMT machines

6) Extended delay accounting fields for memory reclaim

Future extension should add fields to the end of the taskstats struct, and
should not change the relative position of each field within the struct.

::

  struct taskstats {

1) Common and basic accounting fields::

	/* The version number of this struct. This field is always set to
	 * TASKSTATS_VERSION, which is defined in <linux/taskstats.h>.
	 * Each time the struct is changed, the value should be incremented.
	 */
	__u16	version;

	/* The exit code of a task. */
	__u32	ac_exitcode;		/* Exit status */

	/* The accounting flags of a task as defined in <linux/acct.h>
	 * Defined values are AFORK, ASU, ACOMPAT, ACORE, and AXSIG.
	 */
	__u8	ac_flag;		/* Record flags */

	/* The value of task_nice() of a task. */
	__u8	ac_nice;		/* task_nice */

	/* The name of the command that started this task. */
	char	ac_comm[TS_COMM_LEN];	/* Command name */

	/* The scheduling discipline as set in task->policy field. */
	__u8	ac_sched;		/* Scheduling discipline */

	__u8	ac_pad[3];
	__u32	ac_uid;			/* User ID */
	__u32	ac_gid;			/* Group ID */
	__u32	ac_pid;			/* Process ID */
	__u32	ac_ppid;		/* Parent process ID */

	/* The time when a task begins, in [secs] since 1970. */
	__u32	ac_btime;		/* Begin time [sec since 1970] */

	/* The elapsed time of a task, in [usec]. */
	__u64	ac_etime;		/* Elapsed time [usec] */

	/* The user CPU time of a task, in [usec]. */
	__u64	ac_utime;		/* User CPU time [usec] */

	/* The system CPU time of a task, in [usec]. */
	__u64	ac_stime;		/* System CPU time [usec] */

	/* The minor page fault count of a task, as set in task->min_flt. */
	__u64	ac_minflt;		/* Minor Page Fault Count */

	/* The major page fault count of a task, as set in task->maj_flt. */
	__u64	ac_majflt;		/* Major Page Fault Count */


2) Delay accounting fields::

	/* Delay accounting fields start
	 *
	 * All values, until the comment "Delay accounting fields end" are
	 * available only if delay accounting is enabled, even though the last
	 * few fields are not delays
	 *
	 * xxx_count is the number of delay values recorded
	 * xxx_delay_total is the corresponding cumulative delay in nanoseconds
	 *
	 * xxx_delay_total wraps around to zero on overflow
	 * xxx_count incremented regardless of overflow
	 */

	/* Delay waiting for cpu, while runnable
	 * count, delay_total NOT updated atomically
	 */
	__u64	cpu_count;
	__u64	cpu_delay_total;

	/* Following four fields atomically updated using task->delays->lock */

	/* Delay waiting for synchronous block I/O to complete
	 * does not account for delays in I/O submission
	 */
	__u64	blkio_count;
	__u64	blkio_delay_total;

	/* Delay waiting for page fault I/O (swap in only) */
	__u64	swapin_count;
	__u64	swapin_delay_total;

	/* cpu "wall-clock" running time
	 * On some architectures, value will adjust for cpu time stolen
	 * from the kernel in involuntary waits due to virtualization.
	 * Value is cumulative, in nanoseconds, without a corresponding count
	 * and wraps around to zero silently on overflow
	 */
	__u64	cpu_run_real_total;

	/* cpu "virtual" running time
	 * Uses time intervals seen by the kernel i.e. no adjustment
	 * for kernel's involuntary waits due to virtualization.
	 * Value is cumulative, in nanoseconds, without a corresponding count
	 * and wraps around to zero silently on overflow
	 */
	__u64	cpu_run_virtual_total;
	/* Delay accounting fields end */
	/* version 1 ends here */


3) Extended accounting fields::

	/* Extended accounting fields start */

	/* Accumulated RSS usage in duration of a task, in MBytes-usecs.
	 * The current rss usage is added to this counter every time
	 * a tick is charged to a task's system time. So, at the end we
	 * will have memory usage multiplied by system time. Thus an
	 * average usage per system time unit can be calculated.
	 */
	__u64	coremem;		/* accumulated RSS usage in MB-usec */

	/* Accumulated virtual memory usage in duration of a task.
	 * Same as acct_rss_mem1 above except that we keep track of VM usage.
	 */
	__u64	virtmem;		/* accumulated VM usage in MB-usec */

	/* High watermark of RSS usage in duration of a task, in KBytes. */
	__u64	hiwater_rss;		/* High-watermark of RSS usage */

	/* High watermark of VM  usage in duration of a task, in KBytes. */
	__u64	hiwater_vm;		/* High-water virtual memory usage */

	/* The following four fields are I/O statistics of a task. */
	__u64	read_char;		/* bytes read */
	__u64	write_char;		/* bytes written */
	__u64	read_syscalls;		/* read syscalls */
	__u64	write_syscalls;		/* write syscalls */

	/* Extended accounting fields end */

4) Per-task and per-thread statistics::

	__u64	nvcsw;			/* Context voluntary switch counter */
	__u64	nivcsw;			/* Context involuntary switch counter */

5) Time accounting for SMT machines::

	__u64	ac_utimescaled;		/* utime scaled on frequency etc */
	__u64	ac_stimescaled;		/* stime scaled on frequency etc */
	__u64	cpu_scaled_run_real_total; /* scaled cpu_run_real_total */

6) Extended delay accounting fields for memory reclaim::

	/* Delay waiting for memory reclaim */
	__u64	freepages_count;
	__u64	freepages_delay_total;

::

  }

---

### Documentation Accounting Taskstats (`Documentation/accounting/taskstats.rst`)

=============================
Per-task statistics interface
=============================


Taskstats is a netlink-based interface for sending per-task and
per-process statistics from the kernel to userspace.

Taskstats was designed for the following benefits:

- efficiently provide statistics during lifetime of a task and on its exit
- unified interface for multiple accounting subsystems
- extensibility for use by future accounting patches

Terminology
-----------

"pid", "tid" and "task" are used interchangeably and refer to the standard
Linux task defined by struct task_struct.  per-pid stats are the same as
per-task stats.

"tgid", "process" and "thread group" are used interchangeably and refer to the
tasks that share an mm_struct i.e. the traditional Unix process. Despite the
use of tgid, there is no special treatment for the task that is thread group
leader - a process is deemed alive as long as it has any task belonging to it.

Usage
-----

To get statistics during a task's lifetime, userspace opens a unicast netlink
socket (NETLINK_GENERIC family) and sends commands specifying a pid or a tgid.
The response contains statistics for a task (if pid is specified) or the sum of
statistics for all tasks of the process (if tgid is specified).

To obtain statistics for tasks which are exiting, the userspace listener
sends a register command and specifies a cpumask. Whenever a task exits on
one of the cpus in the cpumask, its per-pid statistics are sent to the
registered listener. Using cpumasks allows the data received by one listener
to be limited and assists in flow control over the netlink interface and is
explained in more detail below.

If the exiting task is the last thread exiting its thread group,
an additional record containing the per-tgid stats is also sent to userspace.
The latter contains the sum of per-pid stats for all threads in the thread
group, both past and present.

getdelays.c is a simple utility demonstrating usage of the taskstats interface
for reporting delay accounting statistics. Users can register cpumasks,
send commands and process responses, listen for per-tid/tgid exit data,
write the data received to a file and do basic flow control by increasing
receive buffer sizes.

Interface
---------

The user-kernel interface is encapsulated in include/linux/taskstats.h

To avoid this documentation becoming obsolete as the interface evolves, only
an outline of the current version is given. taskstats.h always overrides the
description here.

struct taskstats is the common accounting structure for both per-pid and
per-tgid data. It is versioned and can be extended by each accounting subsystem
that is added to the kernel. The fields and their semantics are defined in the
taskstats.h file.

The data exchanged between user and kernel space is a netlink message belonging
to the NETLINK_GENERIC family and using the netlink attributes interface.
The messages are in the format::

    +----------+- - -+-------------+-------------------+
    | nlmsghdr | Pad |  genlmsghdr | taskstats payload |
    +----------+- - -+-------------+-------------------+


The taskstats payload is one of the following three kinds:

1. Commands: Sent from user to kernel. Commands to get data on
a pid/tgid consist of one attribute, of type TASKSTATS_CMD_ATTR_PID/TGID,
containing a u32 pid or tgid in the attribute payload. The pid/tgid denotes
the task/process for which userspace wants statistics.

Commands to register/deregister interest in exit data from a set of cpus
consist of one attribute, of type
TASKSTATS_CMD_ATTR_REGISTER/DEREGISTER_CPUMASK and contain a cpumask in the
attribute payload. The cpumask is specified as an ascii string of
comma-separated cpu ranges e.g. to listen to exit data from cpus 1,2,3,5,7,8
the cpumask would be "1-3,5,7-8". If userspace forgets to deregister interest
in cpus before closing the listening socket, the kernel cleans up its interest
set over time. However, for the sake of efficiency, an explicit deregistration
is advisable.

2. Response for a command: sent from the kernel in response to a userspace
command. The payload is a series of three attributes of type:

a) TASKSTATS_TYPE_AGGR_PID/TGID : attribute containing no payload but indicates
a pid/tgid will be followed by some stats.

b) TASKSTATS_TYPE_PID/TGID: attribute whose payload is the pid/tgid whose stats
are being returned.

c) TASKSTATS_TYPE_STATS: attribute with a struct taskstats as payload. The
same structure is used for both per-pid and per-tgid stats.

3. New message sent by kernel whenever a task exits. The payload consists of a
   series of attributes of the following type:

a) TASKSTATS_TYPE_AGGR_PID: indicates next two attributes will be pid+stats
b) TASKSTATS_TYPE_PID: contains exiting task's pid
c) TASKSTATS_TYPE_STATS: contains the exiting task's per-pid stats
d) TASKSTATS_TYPE_AGGR_TGID: indicates next two attributes will be tgid+stats
e) TASKSTATS_TYPE_TGID: contains tgid of process to which task belongs
f) TASKSTATS_TYPE_STATS: contains the per-tgid stats for exiting task's process


per-tgid stats
--------------

Taskstats provides per-process stats, in addition to per-task stats, since
resource management is often done at a process granularity and aggregating task
stats in userspace alone is inefficient and potentially inaccurate (due to lack
of atomicity).

However, maintaining per-process, in addition to per-task stats, within the
kernel has space and time overheads. To address this, the taskstats code
accumulates each exiting task's statistics into a process-wide data structure.
When the last task of a process exits, the process level data accumulated also
gets sent to userspace (along with the per-task data).

When a user queries to get per-tgid data, the sum of all other live threads in
the group is added up and added to the accumulated total for previously exited
threads of the same thread group.

Extending taskstats
-------------------

There are two ways to extend the taskstats interface to export more
per-task/process stats as patches to collect them get added to the kernel
in future:

1. Adding more fields to the end of the existing struct taskstats. Backward
   compatibility is ensured by the version number within the
   structure. Userspace will use only the fields of the struct that correspond
   to the version its using.

2. Defining separate statistic structs and using the netlink attributes
   interface to return them. Since userspace processes each netlink attribute
   independently, it can always ignore attributes whose type it does not
   understand (because it is using an older version of the interface).


Choosing between 1. and 2. is a matter of trading off flexibility and
overhead. If only a few fields need to be added, then 1. is the preferable
path since the kernel and userspace don't need to incur the overhead of
processing new netlink attributes. But if the new fields expand the existing
struct too much, requiring disparate userspace accounting utilities to
unnecessarily receive large structures whose fields are of no interest, then
extending the attributes structure would be worthwhile.

Flow control for taskstats
--------------------------

When the rate of task exits becomes large, a listener may not be able to keep
up with the kernel's rate of sending per-tid/tgid exit data leading to data
loss. This possibility gets compounded when the taskstats structure gets
extended and the number of cpus grows large.

To avoid losing statistics, userspace should do one or more of the following:

- increase the receive buffer sizes for the netlink sockets opened by
  listeners to receive exit data.

- create more listeners and reduce the number of cpus being listened to by
  each listener. In the extreme case, there could be one listener for each cpu.
  Users may also consider setting the cpu affinity of the listener to the subset
  of cpus to which it listens, especially if they are listening to just one cpu.

Despite these measures, if the userspace receives ENOBUFS error messages
indicated overflow of receive buffers, it should take measures to handle the
loss of data.

---

### Documentation Admin Guide README (`Documentation/admin-guide/README.rst`)

.. _readme:

Linux kernel release 6.x <http://kernel.org/>
=============================================

These are the release notes for Linux version 6.  Read them carefully,
as they tell you what this is all about, explain how to install the
kernel, and what to do if something goes wrong.

What is Linux?
--------------

  Linux is a clone of the operating system Unix, written from scratch by
  Linus Torvalds with assistance from a loosely-knit team of hackers across
  the Net. It aims towards POSIX and Single UNIX Specification compliance.

  It has all the features you would expect in a modern fully-fledged Unix,
  including true multitasking, virtual memory, shared libraries, demand
  loading, shared copy-on-write executables, proper memory management,
  and multistack networking including IPv4 and IPv6.

  It is distributed under the GNU General Public License v2 - see the
  accompanying COPYING file for more details.

On what hardware does it run?
-----------------------------

  Although originally developed first for 32-bit x86-based PCs (386 or higher),
  today Linux also runs on (at least) the Compaq Alpha AXP, Sun SPARC and
  UltraSPARC, Motorola 68000, PowerPC, PowerPC64, ARM, Hitachi SuperH, Cell,
  IBM S/390, MIPS, HP PA-RISC, Intel IA-64, DEC VAX, AMD x86-64 Xtensa, and
  ARC architectures.

  Linux is easily portable to most general-purpose 32- or 64-bit architectures
  as long as they have a paged memory management unit (PMMU) and a port of the
  GNU C compiler (gcc) (part of The GNU Compiler Collection, GCC). Linux has
  also been ported to a number of architectures without a PMMU, although
  functionality is then obviously somewhat limited.
  Linux has also been ported to itself. You can now run the kernel as a
  userspace application - this is called UserMode Linux (UML).

Documentation
-------------

 - There is a lot of documentation available both in electronic form on
   the Internet and in books, both Linux-specific and pertaining to
   general UNIX questions.  I'd recommend looking into the documentation
   subdirectories on any Linux FTP site for the LDP (Linux Documentation
   Project) books.  This README is not meant to be documentation on the
   system: there are much better sources available.

 - There are various README files in the Documentation/ subdirectory:
   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
   your kernel.

Installing the kernel source
----------------------------

 - If you install the full sources, put the kernel tarball in a
   directory where you have permissions (e.g. your home directory) and
   unpack it::

     xz -cd linux-6.x.tar.xz | tar xvf -

   Replace "X" with the version number of the latest kernel.

   Do NOT use the /usr/src/linux area! This area has a (usually
   incomplete) set of kernel headers that are used by the library header
   files.  They should match the library, and not get messed up by
   whatever the kernel-du-jour happens to be.

 - You can also upgrade between 6.x releases by patching.  Patches are
   distributed in the xz format.  To install by patching, get all the
   newer patch files, enter the top level directory of the kernel source
   (linux-6.x) and execute::

     xz -cd ../patch-6.x.xz | patch -p1

   Replace "x" for all versions bigger than the version "x" of your current
   source tree, **in_order**, and you should be ok.  You may want to remove
   the backup files (some-file-name~ or some-file-name.orig), and make sure
   that there are no failed patches (some-file-name# or some-file-name.rej).
   If there are, either you or I have made a mistake.

   Unlike patches for the 6.x kernels, patches for the 6.x.y kernels
   (also known as the -stable kernels) are not incremental but instead apply
   directly to the base 6.x kernel.  For example, if your base kernel is 6.0
   and you want to apply the 6.0.3 patch, you must not first apply the 6.0.1
   and 6.0.2 patches. Similarly, if you are running kernel version 6.0.2 and
   want to jump to 6.0.3, you must first reverse the 6.0.2 patch (that is,
   patch -R) **before** applying the 6.0.3 patch. You can read more on this in
   :ref:`Documentation/process/applying-patches.rst <applying_patches>`.

   Alternatively, the script patch-kernel can be used to automate this
   process.  It determines the current kernel version and applies any
   patches found::

     linux/scripts/patch-kernel linux

   The first argument in the command above is the location of the
   kernel source.  Patches are applied from the current directory, but
   an alternative directory can be specified as the second argument.

 - Make sure you have no stale .o files and dependencies lying around::

     cd linux
     make mrproper

   You should now have the sources correctly installed.

Software requirements
---------------------

   Compiling and running the 6.x kernels requires up-to-date
   versions of various software packages.  Consult
   :ref:`Documentation/process/changes.rst <changes>` for the minimum version numbers
   required and how to get updates for these packages.  Beware that using
   excessively old versions of these packages can cause indirect
   errors that are very difficult to track down, so don't assume that
   you can just update packages when obvious problems arise during
   build or operation.

Build directory for the kernel
------------------------------

   When compiling the kernel, all output files will per default be
   stored together with the kernel source code.
   Using the option ``make O=output/dir`` allows you to specify an alternate
   place for the output files (including .config).
   Example::

     kernel source code: /usr/src/linux-6.x
     build directory:    /home/name/build/kernel

   To configure and build the kernel, use::

     cd /usr/src/linux-6.x
     make O=/home/name/build/kernel menuconfig
     make O=/home/name/build/kernel
     sudo make O=/home/name/build/kernel modules_install install

   Please note: If the ``O=output/dir`` option is used, then it must be
   used for all invocations of make.

Configuring the kernel
----------------------

   Do not skip this step even if you are only upgrading one minor
   version.  New configuration options are added in each release, and
   odd problems will turn up if the configuration files are not set up
   as expected.  If you want to carry your existing configuration to a
   new version with minimal work, use ``make oldconfig``, which will
   only ask you for the answers to new questions.

 - Alternative configuration commands are::

     "make config"      Plain text interface.

     "make menuconfig"  Text based color menus, radiolists & dialogs.

     "make nconfig"     Enhanced text based color menus.

     "make xconfig"     Qt based configuration tool.

     "make gconfig"     GTK based configuration tool.

     "make oldconfig"   Default all questions based on the contents of
                        your existing ./.config file and asking about
                        new config symbols.

     "make olddefconfig"
                        Like above, but sets new symbols to their default
                        values without prompting.

     "make defconfig"   Create a ./.config file by using the default
                        symbol values from either arch/$ARCH/configs/defconfig
                        or arch/$ARCH/configs/${PLATFORM}_defconfig,
                        depending on the architecture.

     "make ${PLATFORM}_defconfig"
                        Create a ./.config file by using the default
                        symbol values from
                        arch/$ARCH/configs/${PLATFORM}_defconfig.
                        Use "make help" to get a list of all available
                        platforms of your architecture.

     "make allyesconfig"
                        Create a ./.config file by setting symbol
                        values to 'y' as much as possible.

     "make allmodconfig"
                        Create a ./.config file by setting symbol
                        values to 'm' as much as possible.

     "make allnoconfig" Create a ./.config file by setting symbol
                        values to 'n' as much as possible.

     "make randconfig"  Create a ./.config file by setting symbol
                        values to random values.

     "make localmodconfig" Create a config based on current config and
                           loaded modules (lsmod). Disables any module
                           option that is not needed for the loaded modules.

                           To create a localmodconfig for another machine,
                           store the lsmod of that machine into a file
                           and pass it in as a LSMOD parameter.

                           Also, you can preserve modules in certain folders
                           or kconfig files by specifying their paths in
                           parameter LMC_KEEP.

                   target$ lsmod > /tmp/mylsmod
                   target$ scp /tmp/mylsmod host:/tmp

                   host$ make LSMOD=/tmp/mylsmod \
                           LMC_KEEP="drivers/usb:drivers/gpu:fs" \
                           localmodconfig

                           The above also works when cross compiling.

     "make localyesconfig" Similar to localmodconfig, except it will convert
                           all module options to built in (=y) options. You can
                           also preserve modules by LMC_KEEP.

     "make kvm_guest.config"   Enable additional options for kvm guest kernel
                               support.

     "make xen.config"   Enable additional options for xen dom0 guest kernel
                         support.

     "make tinyconfig"  Configure the tiniest possible kernel.

   You can find more information on using the Linux kernel config tools
   in Documentation/kbuild/kconfig.rst.

 - NOTES on ``make config``:

    - Having unnecessary drivers will make the kernel bigger, and can
      under some circumstances lead to problems: probing for a
      nonexistent controller card may confuse your other controllers.

    - A kernel with math-emulation compiled in will still use the
      coprocessor if one is present: the math emulation will just
      never get used in that case.  The kernel will be slightly larger,
      but will work on different machines regardless of whether they
      have a math coprocessor or not.

    - The "kernel hacking" configuration details usually result in a
      bigger or slower kernel (or both), and can even make the kernel
      less stable by configuring some routines to actively try to
      break bad code to find kernel problems (kmalloc()).  Thus you
      should probably answer 'n' to the questions for "development",
      "experimental", or "debugging" features.

Compiling the kernel
--------------------

 - Make sure you have at least gcc 8.1 available.
   For more information, refer to :ref:`Documentation/process/changes.rst <changes>`.

 - Do a ``make`` to create a compressed kernel image. It is also possible to do
   ``make install`` if you have lilo installed or if your distribution has an
   install script recognised by the kernel's installer. Most popular
   distributions will have a recognized install script. You may want to
   check your distribution's setup first.

   To do the actual install, you have to be root, but none of the normal
   build should require that. Don't take the name of root in vain.

 - If you configured any of the parts of the kernel as ``modules``, you
   will also have to do ``make modules_install``.

 - Verbose kernel compile/build output:

   Normally, the kernel build system runs in a fairly quiet mode (but not
   totally silent).  However, sometimes you or other kernel developers need
   to see compile, link, or other commands exactly as they are executed.
   For this, use "verbose" build mode.  This is done by passing
   ``V=1`` to the ``make`` command, e.g.::

     make V=1 all

   To have the build system also tell the reason for the rebuild of each
   target, use ``V=2``.  The default is ``V=0``.

 - Keep a backup kernel handy in case something goes wrong.  This is
   especially true for the development releases, since each new release
   contains new code which has not been debugged.  Make sure you keep a
   backup of the modules corresponding to that kernel, as well.  If you
   are installing a new kernel with the same version number as your
   working kernel, make a backup of your modules directory before you
   do a ``make modules_install``.

   Alternatively, before compiling, use the kernel config option
   "LOCALVERSION" to append a unique suffix to the regular kernel version.
   LOCALVERSION can be set in the "General Setup" menu.

 - In order to boot your new kernel, you'll need to copy the kernel
   image (e.g. .../linux/arch/x86/boot/bzImage after compilation)
   to the place where your regular bootable kernel is found.

 - Booting a kernel directly from a storage device without the assistance
   of a bootloader such as LILO or GRUB, is no longer supported in BIOS
   (non-EFI systems). On UEFI/EFI systems, however, you can use EFISTUB
   which allows the motherboard to boot directly to the kernel.
   On modern workstations and desktops, it's generally recommended to use a
   bootloader as difficulties can arise with multiple kernels and secure boot.
   For more details on EFISTUB,
   see "Documentation/admin-guide/efi-stub.rst".

 - It's important to note that as of 2016 LILO (LInux LOader) is no longer in
   active development, though as it was extremely popular, it often comes up
   in documentation. Popular alternatives include GRUB2, rEFInd, Syslinux,
   systemd-boot, or EFISTUB. For various reasons, it's not recommended to use
   software that's no longer in active development.

 - Chances are your distribution includes an install script and running
   ``make install`` will be all that's needed. Should that not be the case
   you'll have to identify your bootloader and reference its documentation or
   configure your EFI.

Legacy LILO Instructions
------------------------


 - If you use LILO the kernel images are specified in the file /etc/lilo.conf.
   The kernel image file is usually /vmlinuz, /boot/vmlinuz, /bzImage or
   /boot/bzImage. To use the new kernel, save a copy of the old image and copy
   the new image over the old one. Then, you MUST RERUN LILO to update the
   loading map! If you don't, you won't be able to boot the new kernel image.

 - Reinstalling LILO is usually a matter of running /sbin/lilo. You may wish
   to edit /etc/lilo.conf to specify an entry for your old kernel image
   (say, /vmlinux.old) in case the new one does not work. See the LILO docs
   for more information.

 - After reinstalling LILO, you should be all set. Shutdown the system,
   reboot, and enjoy!

 - If you ever need to change the default root device, video mode, etc. in the
   kernel image, use your bootloader's boot options where appropriate. No need
   to recompile the kernel to change these parameters.

 - Reboot with the new kernel and enjoy.


If something goes wrong
-----------------------

If you have problems that seem to be due to kernel bugs, please follow the
instructions at 'Documentation/admin-guide/reporting-issues.rst'.

Hints on understanding kernel bug reports are in
'Documentation/admin-guide/bug-hunting.rst'. More on debugging the kernel
with gdb is in 'Documentation/process/debugging/gdb-kernel-debugging.rst' and
'Documentation/process/debugging/kgdb.rst'.

---

### Documentation Admin Guide Abi Obsolete Files (`Documentation/admin-guide/abi-obsolete-files.rst`)

.. SPDX-License-Identifier: GPL-2.0

Obsolete ABI Files
==================

.. kernel-abi:: obsolete
   :no-symbols:

---

### Documentation Admin Guide Abi Obsolete (`Documentation/admin-guide/abi-obsolete.rst`)

.. SPDX-License-Identifier: GPL-2.0

ABI obsolete symbols
====================

Documents interfaces that are still remaining in the kernel, but are
marked to be removed at some later point in time.

The description of the interface will document the reason why it is
obsolete and when it can be expected to be removed.

.. kernel-abi:: obsolete
   :no-files:

---

### Documentation Admin Guide Abi Removed Files (`Documentation/admin-guide/abi-removed-files.rst`)

.. SPDX-License-Identifier: GPL-2.0

Removed ABI Files
=================

.. kernel-abi:: removed
   :no-symbols:

---

### Documentation Admin Guide Abi Removed (`Documentation/admin-guide/abi-removed.rst`)

.. SPDX-License-Identifier: GPL-2.0

ABI removed symbols
===================

.. kernel-abi:: removed
   :no-files:

---

### Documentation Admin Guide Abi Stable Files (`Documentation/admin-guide/abi-stable-files.rst`)

.. SPDX-License-Identifier: GPL-2.0

Stable ABI Files
================

.. kernel-abi:: stable
   :no-symbols:

---

### Documentation Admin Guide Abi Stable (`Documentation/admin-guide/abi-stable.rst`)

.. SPDX-License-Identifier: GPL-2.0

ABI stable symbols
==================

Documents the interfaces that the developer has defined to be stable.

Userspace programs are free to use these interfaces with no
restrictions, and backward compatibility for them will be guaranteed
for at least 2 years.

Most interfaces (like syscalls) are expected to never change and always
be available.

.. kernel-abi:: stable
   :no-files:

---

### Documentation Admin Guide Abi Testing Files (`Documentation/admin-guide/abi-testing-files.rst`)

.. SPDX-License-Identifier: GPL-2.0

Testing ABI Files
=================

.. kernel-abi:: testing
   :no-symbols:

---

### Documentation Admin Guide Abi Testing (`Documentation/admin-guide/abi-testing.rst`)

.. SPDX-License-Identifier: GPL-2.0

ABI testing symbols
===================

Documents interfaces that are felt to be stable,
as the main development of this interface has been completed.

The interface can be changed to add new features, but the
current interface will not break by doing this, unless grave
errors or security problems are found in them.

Userspace programs can start to rely on these interfaces, but they must
be aware of changes that can occur before these interfaces move to
be marked stable.

Programs that use these interfaces are strongly encouraged to add their
name to the description of these interfaces, so that the kernel
developers can easily notify them if any changes occur.

.. kernel-abi:: testing
   :no-files:

---

### Documentation Admin Guide Abi (`Documentation/admin-guide/abi.rst`)

.. SPDX-License-Identifier: GPL-2.0

=====================
Linux ABI description
=====================

.. kernel-abi:: README

ABI symbols
-----------

.. toctree::
   :maxdepth: 2

   abi-stable
   abi-testing
   abi-obsolete
   abi-removed

ABI files
---------

.. toctree::
   :maxdepth: 2

   abi-stable-files
   abi-testing-files
   abi-obsolete-files
   abi-removed-files

---

### Documentation Admin Guide Bcache (`Documentation/admin-guide/bcache.rst`)

============================
A block layer cache (bcache)
============================

Say you've got a big slow raid 6, and an ssd or three. Wouldn't it be
nice if you could use them as cache... Hence bcache.

The bcache wiki can be found at:
  https://bcache.evilpiepirate.org

This is the git repository of bcache-tools:
  https://git.kernel.org/pub/scm/linux/kernel/git/colyli/bcache-tools.git/

The latest bcache kernel code can be found from mainline Linux kernel:
  https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/

It's designed around the performance characteristics of SSDs - it only allocates
in erase block sized buckets, and it uses a hybrid btree/log to track cached
extents (which can be anywhere from a single sector to the bucket size). It's
designed to avoid random writes at all costs; it fills up an erase block
sequentially, then issues a discard before reusing it.

Both writethrough and writeback caching are supported. Writeback defaults to
off, but can be switched on and off arbitrarily at runtime. Bcache goes to
great lengths to protect your data - it reliably handles unclean shutdown. (It
doesn't even have a notion of a clean shutdown; bcache simply doesn't return
writes as completed until they're on stable storage).

Writeback caching can use most of the cache for buffering writes - writing
dirty data to the backing device is always done sequentially, scanning from the
start to the end of the index.

Since random IO is what SSDs excel at, there generally won't be much benefit
to caching large sequential IO. Bcache detects sequential IO and skips it;
it also keeps a rolling average of the IO sizes per task, and as long as the
average is above the cutoff it will skip all IO from that task - instead of
caching the first 512k after every seek. Backups and large file copies should
thus entirely bypass the cache.

In the event of a data IO error on the flash it will try to recover by reading
from disk or invalidating cache entries.  For unrecoverable errors (meta data
or dirty data), caching is automatically disabled; if dirty data was present
in the cache it first disables writeback caching and waits for all dirty data
to be flushed.

Getting started:
You'll need bcache util from the bcache-tools repository. Both the cache device
and backing device must be formatted before use::

  bcache make -B /dev/sdb
  bcache make -C /dev/sdc

`bcache make` has the ability to format multiple devices at the same time - if
you format your backing devices and cache device at the same time, you won't
have to manually attach::

  bcache make -B /dev/sda /dev/sdb -C /dev/sdc

If your bcache-tools is not updated to latest version and does not have the
unified `bcache` utility, you may use the legacy `make-bcache` utility to format
bcache device with same -B and -C parameters.

bcache-tools now ships udev rules, and bcache devices are known to the kernel
immediately.  Without udev, you can manually register devices like this::

  echo /dev/sdb > /sys/fs/bcache/register
  echo /dev/sdc > /sys/fs/bcache/register

Registering the backing device makes the bcache device show up in /dev; you can
now format it and use it as normal. But the first time using a new bcache
device, it'll be running in passthrough mode until you attach it to a cache.
If you are thinking about using bcache later, it is recommended to setup all your
slow devices as bcache backing devices without a cache, and you can choose to add
a caching device later.
See 'ATTACHING' section below.

The devices show up as::

  /dev/bcache<N>

As well as (with udev)::

  /dev/bcache/by-uuid/<uuid>
  /dev/bcache/by-label/<label>

To get started::

  mkfs.ext4 /dev/bcache0
  mount /dev/bcache0 /mnt

You can control bcache devices through sysfs at /sys/block/bcache<N>/bcache .
You can also control them through /sys/fs//bcache/<cset-uuid>/ .

Cache devices are managed as sets; multiple caches per set isn't supported yet
but will allow for mirroring of metadata and dirty data in the future. Your new
cache set shows up as /sys/fs/bcache/<UUID>

Attaching
---------

After your cache device and backing device are registered, the backing device
must be attached to your cache set to enable caching. Attaching a backing
device to a cache set is done thusly, with the UUID of the cache set in
/sys/fs/bcache::

  echo <CSET-UUID> > /sys/block/bcache0/bcache/attach

This only has to be done once. The next time you reboot, just reregister all
your bcache devices. If a backing device has data in a cache somewhere, the
/dev/bcache<N> device won't be created until the cache shows up - particularly
important if you have writeback caching turned on.

If you're booting up and your cache device is gone and never coming back, you
can force run the backing device::

  echo 1 > /sys/block/sdb/bcache/running

(You need to use /sys/block/sdb (or whatever your backing device is called), not
/sys/block/bcache0, because bcache0 doesn't exist yet. If you're using a
partition, the bcache directory would be at /sys/block/sdb/sdb2/bcache)

The backing device will still use that cache set if it shows up in the future,
but all the cached data will be invalidated. If there was dirty data in the
cache, don't expect the filesystem to be recoverable - you will have massive
filesystem corruption, though ext4's fsck does work miracles.

Error Handling
--------------

Bcache tries to transparently handle IO errors to/from the cache device without
affecting normal operation; if it sees too many errors (the threshold is
configurable, and defaults to 0) it shuts down the cache device and switches all
the backing devices to passthrough mode.

 - For reads from the cache, if they error we just retry the read from the
   backing device.

 - For writethrough writes, if the write to the cache errors we just switch to
   invalidating the data at that lba in the cache (i.e. the same thing we do for
   a write that bypasses the cache)

 - For writeback writes, we currently pass that error back up to the
   filesystem/userspace. This could be improved - we could retry it as a write
   that skips the cache so we don't have to error the write.

 - When we detach, we first try to flush any dirty data (if we were running in
   writeback mode). It currently doesn't do anything intelligent if it fails to
   read some of the dirty data, though.


Howto/cookbook
--------------

A) Starting a bcache with a missing caching device

If registering the backing device doesn't help, it's already there, you just need
to force it to run without the cache::

	host:~# echo /dev/sdb1 > /sys/fs/bcache/register
	[  119.844831] bcache: register_bcache() error opening /dev/sdb1: device already registered

Next, you try to register your caching device if it's present. However
if it's absent, or registration fails for some reason, you can still
start your bcache without its cache, like so::

	host:/sys/block/sdb/sdb1/bcache# echo 1 > running

Note that this may cause data loss if you were running in writeback mode.


B) Bcache does not find its cache::

	host:/sys/block/md5/bcache# echo 0226553a-37cf-41d5-b3ce-8b1e944543a8 > attach
	[ 1933.455082] bcache: bch_cached_dev_attach() Couldn't find uuid for md5 in set
	[ 1933.478179] bcache: __cached_dev_store() Can't attach 0226553a-37cf-41d5-b3ce-8b1e944543a8
	[ 1933.478179] : cache set not found

In this case, the caching device was simply not registered at boot
or disappeared and came back, and needs to be (re-)registered::

	host:/sys/block/md5/bcache# echo /dev/sdh2 > /sys/fs/bcache/register


C) Corrupt bcache crashes the kernel at device registration time:

This should never happen.  If it does happen, then you have found a bug!
Please report it to the bcache development list: linux-bcache@vger.kernel.org

Be sure to provide as much information that you can including kernel dmesg
output if available so that we may assist.


D) Recovering data without bcache:

If bcache is not available in the kernel, a filesystem on the backing
device is still available at an 8KiB offset. So either via a loopdev
of the backing device created with --offset 8K, or any value defined by
--data-offset when you originally formatted bcache with `bcache make`.

For example::

	losetup -o 8192 /dev/loop0 /dev/your_bcache_backing_dev

This should present your unmodified backing device data in /dev/loop0

If your cache is in writethrough mode, then you can safely discard the
cache device without losing data.


E) Wiping a cache device

::

	host:~# wipefs -a /dev/sdh2
	16 bytes were erased at offset 0x1018 (bcache)
	they were: c6 85 73 f6 4e 1a 45 ca 82 65 f5 7f 48 ba 6d 81

After you boot back with bcache enabled, you recreate the cache and attach it::

	host:~# bcache make -C /dev/sdh2
	UUID:                   7be7e175-8f4c-4f99-94b2-9c904d227045
	Set UUID:               5bc072a8-ab17-446d-9744-e247949913c1
	version:                0
	nbuckets:               106874
	block_size:             1
	bucket_size:            1024
	nr_in_set:              1
	nr_this_dev:            0
	first_bucket:           1
	[  650.511912] bcache: run_cache_set() invalidating existing data
	[  650.549228] bcache: register_cache() registered cache device sdh2

start backing device with missing cache::

	host:/sys/block/md5/bcache# echo 1 > running

attach new cache::

	host:/sys/block/md5/bcache# echo 5bc072a8-ab17-446d-9744-e247949913c1 > attach
	[  865.276616] bcache: bch_cached_dev_attach() Caching md5 as bcache0 on set 5bc072a8-ab17-446d-9744-e247949913c1


F) Remove or replace a caching device::

	host:/sys/block/sda/sda7/bcache# echo 1 > detach
	[  695.872542] bcache: cached_dev_detach_finish() Caching disabled for sda7

	host:~# wipefs -a /dev/nvme0n1p4
	wipefs: error: /dev/nvme0n1p4: probing initialization failed: Device or resource busy
	Ooops, it's disabled, but not unregistered, so it's still protected

We need to go and unregister it::

	host:/sys/fs/bcache/b7ba27a1-2398-4649-8ae3-0959f57ba128# ls -l cache0
	lrwxrwxrwx 1 root root 0 Feb 25 18:33 cache0 -> ../../../devices/pci0000:00/0000:00:1d.0/0000:70:00.0/nvme/nvme0/nvme0n1/nvme0n1p4/bcache/
	host:/sys/fs/bcache/b7ba27a1-2398-4649-8ae3-0959f57ba128# echo 1 > stop
	kernel: [  917.041908] bcache: cache_set_free() Cache set b7ba27a1-2398-4649-8ae3-0959f57ba128 unregistered

Now we can wipe it::

	host:~# wipefs -a /dev/nvme0n1p4
	/dev/nvme0n1p4: 16 bytes were erased at offset 0x00001018 (bcache): c6 85 73 f6 4e 1a 45 ca 82 65 f5 7f 48 ba 6d 81


G) dm-crypt and bcache

First setup bcache unencrypted and then install dmcrypt on top of
/dev/bcache<N> This will work faster than if you dmcrypt both the backing
and caching devices and then install bcache on top. [benchmarks?]


H) Stop/free a registered bcache to wipe and/or recreate it

Suppose that you need to free up all bcache references so that you can
fdisk run and re-register a changed partition table, which won't work
if there are any active backing or caching devices left on it:

1) Is it present in /dev/bcache* ? (there are times where it won't be)

   If so, it's easy::

	host:/sys/block/bcache0/bcache# echo 1 > stop

2) But if your backing device is gone, this won't work::

	host:/sys/block/bcache0# cd bcache
	bash: cd: bcache: No such file or directory

   In this case, you may have to unregister the dmcrypt block device that
   references this bcache to free it up::

	host:~# dmsetup remove oldds1
	bcache: bcache_device_free() bcache0 stopped
	bcache: cache_set_free() Cache set 5bc072a8-ab17-446d-9744-e247949913c1 unregistered

   This causes the backing bcache to be removed from /sys/fs/bcache and
   then it can be reused.  This would be true of any block device stacking
   where bcache is a lower device.

3) In other cases, you can also look in /sys/fs/bcache/::

	host:/sys/fs/bcache# ls -l */{cache?,bdev?}
	lrwxrwxrwx 1 root root 0 Mar  5 09:39 0226553a-37cf-41d5-b3ce-8b1e944543a8/bdev1 -> ../../../devices/virtual/block/dm-1/bcache/
	lrwxrwxrwx 1 root root 0 Mar  5 09:39 0226553a-37cf-41d5-b3ce-8b1e944543a8/cache0 -> ../../../devices/virtual/block/dm-4/bcache/
	lrwxrwxrwx 1 root root 0 Mar  5 09:39 5bc072a8-ab17-446d-9744-e247949913c1/cache0 -> ../../../devices/pci0000:00/0000:00:01.0/0000:01:00.0/ata10/host9/target9:0:0/9:0:0:0/block/sdl/sdl2/bcache/

   The device names will show which UUID is relevant, cd in that directory
   and stop the cache::

	host:/sys/fs/bcache/5bc072a8-ab17-446d-9744-e247949913c1# echo 1 > stop

   This will free up bcache references and let you reuse the partition for
   other purposes.



Troubleshooting performance
---------------------------

Bcache has a bunch of config options and tunables. The defaults are intended to
be reasonable for typical desktop and server workloads, but they're not what you
want for getting the best possible numbers when benchmarking.

 - Backing device alignment

   The default metadata size in bcache is 8k.  If your backing device is
   RAID based, then be sure to align this by a multiple of your stride
   width using `bcache make --data-offset`. If you intend to expand your
   disk array in the future, then multiply a series of primes by your
   raid stripe size to get the disk multiples that you would like.

   For example:  If you have a 64k stripe size, then the following offset
   would provide alignment for many common RAID5 data spindle counts::

	64k * 2*2*2*3*3*5*7 bytes = 161280k

   That space is wasted, but for only 157.5MB you can grow your RAID 5
   volume to the following data-spindle counts without re-aligning::

	3,4,5,6,7,8,9,10,12,14,15,18,20,21 ...

 - Bad write performance

   If write performance is not what you expected, you probably wanted to be
   running in writeback mode, which isn't the default (not due to a lack of
   maturity, but simply because in writeback mode you'll lose data if something
   happens to your SSD)::

	# echo writeback > /sys/block/bcache0/bcache/cache_mode

 - Bad performance, or traffic not going to the SSD that you'd expect

   By default, bcache doesn't cache everything. It tries to skip sequential IO -
   because you really want to be caching the random IO, and if you copy a 10
   gigabyte file you probably don't want that pushing 10 gigabytes of randomly
   accessed data out of your cache.

   But if you want to benchmark reads from cache, and you start out with fio
   writing an 8 gigabyte test file - so you want to disable that::

	# echo 0 > /sys/block/bcache0/bcache/sequential_cutoff

   To set it back to the default (4 mb), do::

	# echo 4M > /sys/block/bcache0/bcache/sequential_cutoff

 - Traffic's still going to the spindle/still getting cache misses

   In the real world, SSDs don't always keep up with disks - particularly with
   slower SSDs, many disks being cached by one SSD, or mostly sequential IO. So
   you want to avoid being bottlenecked by the SSD and having it slow everything
   down.

   To avoid that bcache tracks latency to the cache device, and gradually
   throttles traffic if the latency exceeds a threshold (it does this by
   cranking down the sequential bypass).

   You can disable this if you need to by setting the thresholds to 0::

	# echo 0 > /sys/fs/bcache/<cache set>/congested_read_threshold_us
	# echo 0 > /sys/fs/bcache/<cache set>/congested_write_threshold_us

   The default is 2000 us (2 milliseconds) for reads, and 20000 for writes.

 - Still getting cache misses, of the same data

   One last issue that sometimes trips people up is actually an old bug, due to
   the way cache coherency is handled for cache misses. If a btree node is full,
   a cache miss won't be able to insert a key for the new data and the data
   won't be written to the cache.

   In practice this isn't an issue because as soon as a write comes along it'll
   cause the btree node to be split, and you need almost no write traffic for
   this to not show up enough to be noticeable (especially since bcache's btree
   nodes are huge and index large regions of the device). But when you're
   benchmarking, if you're trying to warm the cache by reading a bunch of data
   and there's no other traffic - that can be a problem.

   Solution: warm the cache by doing writes, or use the testing branch (there's
   a fix for the issue there).


Sysfs - backing device
----------------------

Available at /sys/block/<bdev>/bcache, /sys/block/bcache*/bcache and
(if attached) /sys/fs/bcache/<cset-uuid>/bdev*

attach
  Echo the UUID of a cache set to this file to enable caching.

cache_mode
  Can be one of either writethrough, writeback, writearound or none.

clear_stats
  Writing to this file resets the running total stats (not the day/hour/5 minute
  decaying versions).

detach
  Write to this file to detach from a cache set. If there is dirty data in the
  cache, it will be flushed first.

dirty_data
  Amount of dirty data for this backing device in the cache. Continuously
  updated unlike the cache set's version, but may be slightly off.

label
  Name of underlying device.

readahead
  Size of readahead that should be performed.  Defaults to 0.  If set to e.g.
  1M, it will round cache miss reads up to that size, but without overlapping
  existing cache entries.

running
  1 if bcache is running (i.e. whether the /dev/bcache device exists, whether
  it's in passthrough mode or caching).

sequential_cutoff
  A sequential IO will bypass the cache once it passes this threshold; the
  most recent 128 IOs are tracked so sequential IO can be detected even when
  it isn't all done at once.

sequential_merge
  If non zero, bcache keeps a list of the last 128 requests submitted to compare
  against all new requests to determine which new requests are sequential
  continuations of previous requests for the purpose of determining sequential
  cutoff. This is necessary if the sequential cutoff value is greater than the
  maximum acceptable sequential size for any single request.

state
  The backing device can be in one of four different states:

  no cache: Has never been attached to a cache set.

  clean: Part of a cache set, and there is no cached dirty data.

  dirty: Part of a cache set, and there is cached dirty data.

  inconsistent: The backing device was forcibly run by the user when there was
  dirty data cached but the cache set was unavailable; whatever data was on the
  backing device has likely been corrupted.

stop
  Write to this file to shut down the bcache device and close the backing
  device.

writeback_delay
  When dirty data is written to the cache and it previously did not contain
  any, waits some number of seconds before initiating writeback. Defaults to
  30.

writeback_percent
  If nonzero, bcache tries to keep around this percentage of the cache dirty by
  throttling background writeback and using a PD controller to smoothly adjust
  the rate.

writeback_rate
  Rate in sectors per second - if writeback_percent is nonzero, background
  writeback is throttled to this rate. Continuously adjusted by bcache but may
  also be set by the user.

writeback_running
  If off, writeback of dirty data will not take place at all. Dirty data will
  still be added to the cache until it is mostly full; only meant for
  benchmarking. Defaults to on.

Sysfs - backing device stats
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

There are directories with these numbers for a running total, as well as
versions that decay over the past day, hour and 5 minutes; they're also
aggregated in the cache set directory as well.

bypassed
  Amount of IO (both reads and writes) that has bypassed the cache

cache_hits, cache_misses, cache_hit_ratio
  Hits and misses are counted per individual IO as bcache sees them; a
  partial hit is counted as a miss.

cache_bypass_hits, cache_bypass_misses
  Hits and misses for IO that is intended to skip the cache are still counted,
  but broken out here.

cache_miss_collisions
  Counts instances where data was going to be inserted into the cache from a
  cache miss, but raced with a write and data was already present (usually 0
  since the synchronization for cache misses was rewritten)

Sysfs - cache set
~~~~~~~~~~~~~~~~~

Available at /sys/fs/bcache/<cset-uuid>

average_key_size
  Average data per key in the btree.

bdev<0..n>
  Symlink to each of the attached backing devices.

block_size
  Block size of the cache devices.

btree_cache_size
  Amount of memory currently used by the btree cache

bucket_size
  Size of buckets

cache<0..n>
  Symlink to each of the cache devices comprising this cache set.

cache_available_percent
  Percentage of cache device which doesn't contain dirty data, and could
  potentially be used for writeback.  This doesn't mean this space isn't used
  for clean cached data; the unused statistic (in priority_stats) is typically
  much lower.

clear_stats
  Clears the statistics associated with this cache

dirty_data
  Amount of dirty data is in the cache (updated when garbage collection runs).

flash_vol_create
  Echoing a size to this file (in human readable units, k/M/G) creates a thinly
  provisioned volume backed by the cache set.

io_error_halflife, io_error_limit
  These determines how many errors we accept before disabling the cache.
  Each error is decayed by the half life (in # ios).  If the decaying count
  reaches io_error_limit dirty data is written out and the cache is disabled.

journal_delay_ms
  Journal writes will delay for up to this many milliseconds, unless a cache
  flush happens sooner. Defaults to 100.

root_usage_percent
  Percentage of the root btree node in use.  If this gets too high the node
  will split, increasing the tree depth.

stop
  Write to this file to shut down the cache set - waits until all attached
  backing devices have been shut down.

tree_depth
  Depth of the btree (A single node btree has depth 0).

unregister
  Detaches all backing devices and closes the cache devices; if dirty data is
  present it will disable writeback caching and wait for it to be flushed.

Sysfs - cache set internal
~~~~~~~~~~~~~~~~~~~~~~~~~~

This directory also exposes timings for a number of internal operations, with
separate files for average duration, average frequency, last occurrence and max
duration: garbage collection, btree read, btree node sorts and btree splits.

active_journal_entries
  Number of journal entries that are newer than the index.

btree_nodes
  Total nodes in the btree.

btree_used_percent
  Average fraction of btree in use.

bset_tree_stats
  Statistics about the auxiliary search trees

btree_cache_max_chain
  Longest chain in the btree node cache's hash table

cache_read_races
  Counts instances where while data was being read from the cache, the bucket
  was reused and invalidated - i.e. where the pointer was stale after the read
  completed. When this occurs the data is reread from the backing device.

trigger_gc
  Writing to this file forces garbage collection to run.

Sysfs - Cache device
~~~~~~~~~~~~~~~~~~~~

Available at /sys/block/<cdev>/bcache

block_size
  Minimum granularity of writes - should match hardware sector size.

btree_written
  Sum of all btree writes, in (kilo/mega/giga) bytes

bucket_size
  Size of buckets

cache_replacement_policy
  One of either lru, fifo or random.

discard
  Boolean; if on a discard/TRIM will be issued to each bucket before it is
  reused. Defaults to off, since SATA TRIM is an unqueued command (and thus
  slow).

freelist_percent
  Size of the freelist as a percentage of nbuckets. Can be written to to
  increase the number of buckets kept on the freelist, which lets you
  artificially reduce the size of the cache at runtime. Mostly for testing
  purposes (i.e. testing how different size caches affect your hit rate), but
  since buckets are discarded when they move on to the freelist will also make
  the SSD's garbage collection easier by effectively giving it more reserved
  space.

io_errors
  Number of errors that have occurred, decayed by io_error_halflife.

metadata_written
  Sum of all non data writes (btree writes and all other metadata).

nbuckets
  Total buckets in this cache

priority_stats
  Statistics about how recently data in the cache has been accessed.
  This can reveal your working set size.  Unused is the percentage of
  the cache that doesn't contain any data.  Metadata is bcache's
  metadata overhead.  Average is the average priority of cache buckets.
  Next is a list of quantiles with the priority threshold of each.

written
  Sum of all data that has been written to the cache; comparison with
  btree_written gives the amount of write inflation in bcache.

---

### Documentation Admin Guide Binderfs (`Documentation/admin-guide/binderfs.rst`)

.. SPDX-License-Identifier: GPL-2.0

The Android binderfs Filesystem
===============================

Android binderfs is a filesystem for the Android binder IPC mechanism.  It
allows to dynamically add and remove binder devices at runtime.  Binder devices
located in a new binderfs instance are independent of binder devices located in
other binderfs instances.  Mounting a new binderfs instance makes it possible
to get a set of private binder devices.

Mounting binderfs
-----------------

Android binderfs can be mounted with::

  mkdir /dev/binderfs
  mount -t binder binder /dev/binderfs

at which point a new instance of binderfs will show up at ``/dev/binderfs``.
In a fresh instance of binderfs no binder devices will be present.  There will
only be a ``binder-control`` device which serves as the request handler for
binderfs. Mounting another binderfs instance at a different location will
create a new and separate instance from all other binderfs mounts.  This is
identical to the behavior of e.g. ``devpts`` and ``tmpfs``. The Android
binderfs filesystem can be mounted in user namespaces.

Options
-------
max
  binderfs instances can be mounted with a limit on the number of binder
  devices that can be allocated. The ``max=<count>`` mount option serves as
  a per-instance limit. If ``max=<count>`` is set then only ``<count>`` number
  of binder devices can be allocated in this binderfs instance.

stats
  Using ``stats=global`` enables global binder statistics.
  ``stats=global`` is only available for a binderfs instance mounted in the
  initial user namespace. An attempt to use the option to mount a binderfs
  instance in another user namespace will return a permission error.

Allocating binder Devices
-------------------------

.. _ioctl: http://man7.org/linux/man-pages/man2/ioctl.2.html

To allocate a new binder device in a binderfs instance a request needs to be
sent through the ``binder-control`` device node.  A request is sent in the form
of an `ioctl() <ioctl_>`_.

What a program needs to do is to open the ``binder-control`` device node and
send a ``BINDER_CTL_ADD`` request to the kernel.  Users of binderfs need to
tell the kernel which name the new binder device should get.  By default a name
can only contain up to ``BINDERFS_MAX_NAME`` chars including the terminating
zero byte.

Once the request is made via an `ioctl() <ioctl_>`_ passing a ``struct
binder_device`` with the name to the kernel it will allocate a new binder
device and return the major and minor number of the new device in the struct
(This is necessary because binderfs allocates a major device number
dynamically.).  After the `ioctl() <ioctl_>`_ returns there will be a new
binder device located under /dev/binderfs with the chosen name.

Deleting binder Devices
-----------------------

.. _unlink: http://man7.org/linux/man-pages/man2/unlink.2.html
.. _rm: http://man7.org/linux/man-pages/man1/rm.1.html

Binderfs binder devices can be deleted via `unlink() <unlink_>`_.  This means
that the `rm() <rm_>`_ tool can be used to delete them. Note that the
``binder-control`` device cannot be deleted since this would make the binderfs
instance unusable.  The ``binder-control`` device will be deleted when the
binderfs instance is unmounted and all references to it have been dropped.

Binder features
---------------

Assuming an instance of binderfs has been mounted at ``/dev/binderfs``, the
features supported by the binder driver can be located under
``/dev/binderfs/features/``. The presence of individual files can be tested
to determine whether a particular feature is supported by the driver.

Example::

        cat /dev/binderfs/features/oneway_spam_detection
        1

---

### Documentation Admin Guide Binfmt Misc (`Documentation/admin-guide/binfmt-misc.rst`)

Kernel Support for miscellaneous Binary Formats (binfmt_misc)
=============================================================

This Kernel feature allows you to invoke almost (for restrictions see below)
every program by simply typing its name in the shell.
This includes for example compiled Java(TM), Python or Emacs programs.

To achieve this you must tell binfmt_misc which interpreter has to be invoked
with which binary. Binfmt_misc recognises the binary-type by matching some bytes
at the beginning of the file with a magic byte sequence (masking out specified
bits) you have supplied. Binfmt_misc can also recognise a filename extension
aka ``.com`` or ``.exe``.

First you must mount binfmt_misc::

	mount binfmt_misc -t binfmt_misc /proc/sys/fs/binfmt_misc

To actually register a new binary type, you have to set up a string looking like
``:name:type:offset:magic:mask:interpreter:flags`` (where you can choose the
``:`` upon your needs) and echo it to ``/proc/sys/fs/binfmt_misc/register``.

Here is what the fields mean:

- ``name``
   is an identifier string. A new /proc file will be created with this
   name below ``/proc/sys/fs/binfmt_misc``; cannot contain slashes ``/`` for
   obvious reasons.
- ``type``
   is the type of recognition. Give ``M`` for magic and ``E`` for extension.
- ``offset``
   is the offset of the magic/mask in the file, counted in bytes. This
   defaults to 0 if you omit it (i.e. you write ``:name:type::magic...``).
   Ignored when using filename extension matching.
- ``magic``
   is the byte sequence binfmt_misc is matching for. The magic string
   may contain hex-encoded characters like ``\x0a`` or ``\xA4``. Note that you
   must escape any NUL bytes; parsing halts at the first one. In a shell
   environment you might have to write ``\\x0a`` to prevent the shell from
   eating your ``\``.
   If you chose filename extension matching, this is the extension to be
   recognised (without the ``.``, the ``\x0a`` specials are not allowed).
   Extension    matching is case sensitive, and slashes ``/`` are not allowed!
- ``mask``
   is an (optional, defaults to all 0xff) mask. You can mask out some
   bits from matching by supplying a string like magic and as long as magic.
   The mask is anded with the byte sequence of the file. Note that you must
   escape any NUL bytes; parsing halts at the first one. Ignored when using
   filename extension matching.
- ``interpreter``
   is the program that should be invoked with the binary as first
   argument (specify the full path)
- ``flags``
   is an optional field that controls several aspects of the invocation
   of the interpreter. It is a string of capital letters, each controls a
   certain aspect. The following flags are supported:

      ``P`` - preserve-argv[0]
            Legacy behavior of binfmt_misc is to overwrite
            the original argv[0] with the full path to the binary. When this
            flag is included, binfmt_misc will add an argument to the argument
            vector for this purpose, thus preserving the original ``argv[0]``.
            e.g. If your interp is set to ``/bin/foo`` and you run ``blah``
            (which is in ``/usr/local/bin``), then the kernel will execute
            ``/bin/foo`` with ``argv[]`` set to ``["/bin/foo", "/usr/local/bin/blah", "blah"]``.  The interp has to be aware of this so it can
            execute ``/usr/local/bin/blah``
            with ``argv[]`` set to ``["blah"]``.
      ``O`` - open-binary
	    Legacy behavior of binfmt_misc is to pass the full path
            of the binary to the interpreter as an argument. When this flag is
            included, binfmt_misc will open the file for reading and pass its
            descriptor as an argument, instead of the full path, thus allowing
            the interpreter to execute non-readable binaries. This feature
            should be used with care - the interpreter has to be trusted not to
            emit the contents of the non-readable binary.
      ``C`` - credentials
            Currently, the behavior of binfmt_misc is to calculate
            the credentials and security token of the new process according to
            the interpreter. When this flag is included, these attributes are
            calculated according to the binary. It also implies the ``O`` flag.
            This feature should be used with care as the interpreter
            will run with root permissions when a setuid binary owned by root
            is run with binfmt_misc.
      ``F`` - fix binary
            The usual behaviour of binfmt_misc is to spawn the
	    binary lazily when the misc format file is invoked.  However,
	    this doesn't work very well in the face of mount namespaces and
	    changeroots, so the ``F`` mode opens the binary as soon as the
	    emulation is installed and uses the opened image to spawn the
	    emulator, meaning it is always available once installed,
	    regardless of how the environment changes.


There are some restrictions:

 - the whole register string may not exceed 1920 characters
 - the magic must reside in the first 128 bytes of the file, i.e.
   offset+size(magic) has to be less than 128
 - the interpreter string may not exceed 127 characters

To use binfmt_misc you have to mount it first. You can mount it with
``mount -t binfmt_misc none /proc/sys/fs/binfmt_misc`` command, or you can add
a line ``none  /proc/sys/fs/binfmt_misc binfmt_misc defaults 0 0`` to your
``/etc/fstab`` so it auto mounts on boot.

You may want to add the binary formats in one of your ``/etc/rc`` scripts during
boot-up. Read the manual of your init program to figure out how to do this
right.

Think about the order of adding entries! Later added entries are matched first!


A few examples (assumed you are in ``/proc/sys/fs/binfmt_misc``):

- enable support for em86 (like binfmt_em86, for Alpha AXP only)::

    echo ':i386:M::\x7fELF\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x03:\xff\xff\xff\xff\xff\xfe\xfe\xff\xff\xff\xff\xff\xff\xff\xff\xff\xfb\xff\xff:/bin/em86:' > register
    echo ':i486:M::\x7fELF\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x06:\xff\xff\xff\xff\xff\xfe\xfe\xff\xff\xff\xff\xff\xff\xff\xff\xff\xfb\xff\xff:/bin/em86:' > register

- enable support for packed DOS applications (pre-configured dosemu hdimages)::

    echo ':DEXE:M::\x0eDEX::/usr/bin/dosexec:' > register

- enable support for Windows executables using wine::

    echo ':DOSWin:M::MZ::/usr/local/bin/wine:' > register

For java support see Documentation/admin-guide/java.rst


You can enable/disable binfmt_misc or one binary type by echoing 0 (to disable)
or 1 (to enable) to ``/proc/sys/fs/binfmt_misc/status`` or
``/proc/.../the_name``.
Catting the file tells you the current status of ``binfmt_misc/the_entry``.

You can remove one entry or all entries by echoing -1 to ``/proc/.../the_name``
or ``/proc/sys/fs/binfmt_misc/status``.


Hints
-----

If you want to pass special arguments to your interpreter, you can
write a wrapper script for it.
See :doc:`Documentation/admin-guide/java.rst <./java>` for an example.

Your interpreter should NOT look in the PATH for the filename; the kernel
passes it the full filename (or the file descriptor) to use.  Using ``$PATH`` can
cause unexpected behaviour and can be a security hazard.


Richard Günther <rguenth@tat.physik.uni-tuebingen.de>

---

### Documentation Admin Guide Bootconfig (`Documentation/admin-guide/bootconfig.rst`)

.. SPDX-License-Identifier: GPL-2.0

.. _bootconfig:

==================
Boot Configuration
==================

:Author: Masami Hiramatsu <mhiramat@kernel.org>

Overview
========

The boot configuration expands the current kernel command line to support
additional key-value data when booting the kernel in an efficient way.
This allows administrators to pass a structured-Key config file.

Config File Syntax
==================

The boot config syntax is a simple structured key-value. Each key consists
of dot-connected-words, and key and value are connected by ``=``. The value
has to be terminated by semi-colon (``;``) or newline (``\n``).
For array value, array entries are separated by comma (``,``). ::

  KEY[.WORD[...]] = VALUE[, VALUE2[...]][;]

Unlike the kernel command line syntax, spaces are OK around the comma and ``=``.

Each key word must contain only alphabets, numbers, dash (``-``) or underscore
(``_``). And each value only contains printable characters or spaces except
for delimiters such as semi-colon (``;``), new-line (``\n``), comma (``,``),
hash (``#``) and closing brace (``}``).

If you want to use those delimiters in a value, you can use either double-
quotes (``"VALUE"``) or single-quotes (``'VALUE'``) to quote it. Note that
you can not escape these quotes.

There can be a key which doesn't have value or has an empty value. Those keys
are used for checking if the key exists or not (like a boolean).

Key-Value Syntax
----------------

The boot config file syntax allows user to merge partially same word keys
by brace. For example::

 foo.bar.baz = value1
 foo.bar.qux.quux = value2

These can be written also in::

 foo.bar {
    baz = value1
    qux.quux = value2
 }

Or more shorter, written as following::

 foo.bar { baz = value1; qux.quux = value2 }

In both styles, same key words are automatically merged when parsing it
at boot time. So you can append similar trees or key-values.

Same-key Values
---------------

It is prohibited that two or more values or arrays share a same-key.
For example,::

 foo = bar, baz
 foo = qux  # !ERROR! we can not re-define same key

If you want to update the value, you must use the override operator
``:=`` explicitly. For example::

 foo = bar, baz
 foo := qux

then, the ``qux`` is assigned to ``foo`` key. This is useful for
overriding the default value by adding (partial) custom bootconfigs
without parsing the default bootconfig.

If you want to append the value to existing key as an array member,
you can use ``+=`` operator. For example::

 foo = bar, baz
 foo += qux

In this case, the key ``foo`` has ``bar``, ``baz`` and ``qux``.

Moreover, sub-keys and a value can coexist under a parent key.
For example, following config is allowed.::

 foo = value1
 foo.bar = value2
 foo := value3 # This will update foo's value.

Note, since there is no syntax to put a raw value directly under a
structured key, you have to define it outside of the brace. For example::

 foo {
     bar = value1
     bar {
         baz = value2
         qux = value3
     }
 }

Also, the order of the value node under a key is fixed. If there
are a value and subkeys, the value is always the first child node
of the key. Thus if user specifies subkeys first, e.g.::

 foo.bar = value1
 foo = value2

In the program (and /proc/bootconfig), it will be shown as below::

 foo = value2
 foo.bar = value1

Comments
--------

The config syntax accepts shell-script style comments. The comments starting
with hash ("#") until newline ("\n") will be ignored.

::

 # comment line
 foo = value # value is set to foo.
 bar = 1, # 1st element
       2, # 2nd element
       3  # 3rd element

This is parsed as below::

 foo = value
 bar = 1, 2, 3

Note that you can not put a comment between value and delimiter(``,`` or
``;``). This means following config has a syntax error ::

 key = 1 # comment
       ,2


/proc/bootconfig
================

/proc/bootconfig is a user-space interface of the boot config.
Unlike /proc/cmdline, this file shows the key-value style list.
Each key-value pair is shown in each line with following style::

 KEY[.WORDS...] = "[VALUE]"[,"VALUE2"...]


Boot Kernel With a Boot Config
==============================

There are two options to boot the kernel with bootconfig: attaching the
bootconfig to the initrd image or embedding it in the kernel itself.

Attaching a Boot Config to Initrd
---------------------------------

Since the boot configuration file is loaded with initrd by default,
it will be added to the end of the initrd (initramfs) image file with
padding, size, checksum and 12-byte magic word as below.

[initrd][bootconfig][padding][size(le32)][checksum(le32)][#BOOTCONFIG\n]

The size and checksum fields are unsigned 32bit little endian value.

When the boot configuration is added to the initrd image, the total
file size is aligned to 4 bytes. To fill the gap, null characters
(``\0``) will be added. Thus the ``size`` is the length of the bootconfig
file + padding bytes.

The Linux kernel decodes the last part of the initrd image in memory to
get the boot configuration data.
Because of this "piggyback" method, there is no need to change or
update the boot loader and the kernel image itself as long as the boot
loader passes the correct initrd file size. If by any chance, the boot
loader passes a longer size, the kernel fails to find the bootconfig data.

To do this operation, Linux kernel provides ``bootconfig`` command under
tools/bootconfig, which allows admin to apply or delete the config file
to/from initrd image. You can build it by the following command::

 # make -C tools/bootconfig

To add your boot config file to initrd image, run bootconfig as below
(Old data is removed automatically if exists)::

 # tools/bootconfig/bootconfig -a your-config /boot/initrd.img-X.Y.Z

To remove the config from the image, you can use -d option as below::

 # tools/bootconfig/bootconfig -d /boot/initrd.img-X.Y.Z

Then add "bootconfig" on the normal kernel command line to tell the
kernel to look for the bootconfig at the end of the initrd file.
Alternatively, build your kernel with the ``CONFIG_BOOT_CONFIG_FORCE``
Kconfig option selected.

Embedding a Boot Config into Kernel
-----------------------------------

If you can not use initrd, you can also embed the bootconfig file in the
kernel by Kconfig options. In this case, you need to recompile the kernel
with the following configs::

 CONFIG_BOOT_CONFIG_EMBED=y
 CONFIG_BOOT_CONFIG_EMBED_FILE="/PATH/TO/BOOTCONFIG/FILE"

``CONFIG_BOOT_CONFIG_EMBED_FILE`` requires an absolute path or a relative
path to the bootconfig file from source tree or object tree.
The kernel will embed it as the default bootconfig.

Just as when attaching the bootconfig to the initrd, you need ``bootconfig``
option on the kernel command line to enable the embedded bootconfig, or,
alternatively, build your kernel with the ``CONFIG_BOOT_CONFIG_FORCE``
Kconfig option selected.

Note that even if you set this option, you can override the embedded
bootconfig by another bootconfig which attached to the initrd.

Kernel parameters via Boot Config
=================================

In addition to the kernel command line, the boot config can be used for
passing the kernel parameters. All the key-value pairs under ``kernel``
key will be passed to kernel cmdline directly. Moreover, the key-value
pairs under ``init`` will be passed to init process via the cmdline.
The parameters are concatenated with user-given kernel cmdline string
as the following order, so that the command line parameter can override
bootconfig parameters (this depends on how the subsystem handles parameters
but in general, earlier parameter will be overwritten by later one.)::

 [bootconfig params][cmdline params] -- [bootconfig init params][cmdline init params]

Here is an example of the bootconfig file for kernel/init parameters.::

 kernel {
   root = 01234567-89ab-cdef-0123-456789abcd
 }
 init {
  splash
 }

This will be copied into the kernel cmdline string as the following::

 root="01234567-89ab-cdef-0123-456789abcd" -- splash

If user gives some other command line like,::

 ro bootconfig -- quiet

The final kernel cmdline will be the following::

 root="01234567-89ab-cdef-0123-456789abcd" ro bootconfig -- splash quiet


Config File Limitation
======================

Currently the maximum config size is 32KB and the total key-words (not
key-value entries) must be under 1024 nodes.
Note: this is not the number of entries but nodes, an entry must consume
more than 2 nodes (a key-word and a value). So theoretically, it will be
up to 512 key-value pairs. If keys contains 3 words in average, it can
contain 256 key-value pairs. In most cases, the number of config items
will be under 100 entries and smaller than 8KB, so it would be enough.
If the node number exceeds 1024, parser returns an error even if the file
size is smaller than 32KB. (Note that this maximum size is not including
the padding null characters.)
Anyway, since bootconfig command verifies it when appending a boot config
to initrd image, user can notice it before boot.


Bootconfig APIs
===============

User can query or loop on key-value pairs, also it is possible to find
a root (prefix) key node and find key-values under that node.

If you have a key string, you can query the value directly with the key
using xbc_find_value(). If you want to know what keys exist in the boot
config, you can use xbc_for_each_key_value() to iterate key-value pairs.
Note that you need to use xbc_array_for_each_value() for accessing
each array's value, e.g.::

 vnode = NULL;
 xbc_find_value("key.word", &vnode);
 if (vnode && xbc_node_is_array(vnode))
    xbc_array_for_each_value(vnode, value) {
      printk("%s ", value);
    }

If you want to focus on keys which have a prefix string, you can use
xbc_find_node() to find a node by the prefix string, and iterate
keys under the prefix node with xbc_node_for_each_key_value().

But the most typical usage is to get the named value under prefix
or get the named array under prefix as below::

 root = xbc_find_node("key.prefix");
 value = xbc_node_find_value(root, "option", &vnode);
 ...
 xbc_node_for_each_array_value(root, "array-option", value, anode) {
    ...
 }

This accesses a value of "key.prefix.option" and an array of
"key.prefix.array-option".

Locking is not needed, since after initialization, the config becomes
read-only. All data and keys must be copied if you need to modify it.


Functions and structures
========================

.. kernel-doc:: include/linux/bootconfig.h
.. kernel-doc:: lib/bootconfig.c

---

### Documentation Admin Guide Braille Console (`Documentation/admin-guide/braille-console.rst`)

Linux Braille Console
=====================

To get early boot messages on a braille device (before userspace screen
readers can start), you first need to compile the support for the usual serial
console (see :ref:`Documentation/admin-guide/serial-console.rst <serial_console>`), and
for braille device
(in :menuselection:`Device Drivers --> Accessibility support --> Console on braille device`).

Then you need to specify a ``console=brl``, option on the kernel command line, the
format is::

	console=brl,serial_options...

where ``serial_options...`` are the same as described in
:ref:`Documentation/admin-guide/serial-console.rst <serial_console>`.

So for instance you can use ``console=brl,ttyS0`` if the braille device is connected to the first serial port, and ``console=brl,ttyS0,115200`` to
override the baud rate to 115200, etc.

By default, the braille device will just show the last kernel message (console
mode).  To review previous messages, press the Insert key to switch to the VT
review mode.  In review mode, the arrow keys permit to browse in the VT content,
`PAGE-UP`/`PAGE-DOWN` keys go at the top/bottom of the screen, and
the `HOME` key goes back
to the cursor, hence providing very basic screen reviewing facility.

Sound feedback can be obtained by adding the ``braille_console.sound=1`` kernel
parameter.

For simplicity, only one braille console can be enabled, other uses of
``console=brl,...`` will be discarded.  Also note that it does not interfere with
the console selection mechanism described in
:ref:`Documentation/admin-guide/serial-console.rst <serial_console>`.

For now, only the VisioBraille device is supported.

Samuel Thibault <samuel.thibault@ens-lyon.org>

---

### Documentation Admin Guide Btmrvl (`Documentation/admin-guide/btmrvl.rst`)

=============
btmrvl driver
=============

All commands are used via debugfs interface.

Set/get driver configurations
=============================

Path:	/debug/btmrvl/config/

gpiogap=[n], hscfgcmd
	These commands are used to configure the host sleep parameters::
	bit 8:0  -- Gap
	bit 16:8 -- GPIO

	where GPIO is the pin number of GPIO used to wake up the host.
	It could be any valid GPIO pin# (e.g. 0-7) or 0xff (SDIO interface
	wakeup will be used instead).

	where Gap is the gap in milli seconds between wakeup signal and
	wakeup event, or 0xff for special host sleep setting.

	Usage::

		# Use SDIO interface to wake up the host and set GAP to 0x80:
		echo 0xff80 > /debug/btmrvl/config/gpiogap
		echo 1 > /debug/btmrvl/config/hscfgcmd

		# Use GPIO pin #3 to wake up the host and set GAP to 0xff:
		echo 0x03ff >  /debug/btmrvl/config/gpiogap
		echo 1 > /debug/btmrvl/config/hscfgcmd

psmode=[n], pscmd
	These commands are used to enable/disable auto sleep mode

	where the option is::

			1 	-- Enable auto sleep mode
			0 	-- Disable auto sleep mode

	Usage::

		# Enable auto sleep mode
		echo 1 > /debug/btmrvl/config/psmode
		echo 1 > /debug/btmrvl/config/pscmd

		# Disable auto sleep mode
		echo 0 > /debug/btmrvl/config/psmode
		echo 1 > /debug/btmrvl/config/pscmd


hsmode=[n], hscmd
	These commands are used to enable host sleep or wake up firmware

	where the option is::

			1	-- Enable host sleep
			0	-- Wake up firmware

	Usage::

		# Enable host sleep
		echo 1 > /debug/btmrvl/config/hsmode
		echo 1 > /debug/btmrvl/config/hscmd

		# Wake up firmware
		echo 0 > /debug/btmrvl/config/hsmode
		echo 1 > /debug/btmrvl/config/hscmd


Get driver status
=================

Path:	/debug/btmrvl/status/

Usage::

	cat /debug/btmrvl/status/<args>

where the args are:

curpsmode
	This command displays current auto sleep status.

psstate
	This command display the power save state.

hsstate
	This command display the host sleep state.

txdnldrdy
	This command displays the value of Tx download ready flag.

Issuing a raw hci command
=========================

Use hcitool to issue raw hci command, refer to hcitool manual

Usage::

	Hcitool cmd <ogf> <ocf> [Parameters]

Interface Control Command::

	hcitool cmd 0x3f 0x5b 0xf5 0x01 0x00    --Enable All interface
	hcitool cmd 0x3f 0x5b 0xf5 0x01 0x01    --Enable Wlan interface
	hcitool cmd 0x3f 0x5b 0xf5 0x01 0x02    --Enable BT interface
	hcitool cmd 0x3f 0x5b 0xf5 0x00 0x00    --Disable All interface
	hcitool cmd 0x3f 0x5b 0xf5 0x00 0x01    --Disable Wlan interface
	hcitool cmd 0x3f 0x5b 0xf5 0x00 0x02    --Disable BT interface

SD8688 firmware
===============

Images:

- /lib/firmware/sd8688_helper.bin
- /lib/firmware/sd8688.bin


The images can be downloaded from:

git.infradead.org/users/dwmw2/linux-firmware.git/libertas/

---

### Documentation Admin Guide Bug Bisect (`Documentation/admin-guide/bug-bisect.rst`)

.. SPDX-License-Identifier: (GPL-2.0+ OR CC-BY-4.0)
.. [see the bottom of this file for redistribution information]

======================
Bisecting a regression
======================

This document describes how to use a ``git bisect`` to find the source code
change that broke something -- for example when some functionality stopped
working after upgrading from Linux 6.0 to 6.1.

The text focuses on the gist of the process. If you are new to bisecting the
kernel, better follow Documentation/admin-guide/verify-bugs-and-bisect-regressions.rst
instead: it depicts everything from start to finish while covering multiple
aspects even kernel developers occasionally forget. This includes detecting
situations early where a bisection would be a waste of time, as nobody would
care about the result -- for example, because the problem happens after the
kernel marked itself as 'tainted', occurs in an abandoned version, was already
fixed, or is caused by a .config change you or your Linux distributor performed.

Finding the change causing a kernel issue using a bisection
===========================================================

*Note: the following process assumes you prepared everything for a bisection.
This includes having a Git clone with the appropriate sources, installing the
software required to build and install kernels, as well as a .config file stored
in a safe place (the following example assumes '~/prepared_kernel_.config') to
use as pristine base at each bisection step; ideally, you have also worked out
a fully reliable and straight-forward way to reproduce the regression, too.*

* Preparation: start the bisection and tell Git about the points in the history
  you consider to be working and broken, which Git calls 'good' and 'bad'::

     git bisect start
     git bisect good v6.0
     git bisect bad v6.1

  Instead of Git tags like 'v6.0' and 'v6.1' you can specify commit-ids, too.

1. Copy your prepared .config into the build directory and adjust it to the
   needs of the codebase Git checked out for testing::

     cp ~/prepared_kernel_.config .config
     make olddefconfig

2. Now build, install, and boot a kernel. This might fail for unrelated reasons,
   for example, when a compile error happens at the current stage of the
   bisection a later change resolves. In such cases run ``git bisect skip`` and
   go back to step 1.

3. Check if the functionality that regressed works in the kernel you just built.

   If it works, execute::

     git bisect good

   If it is broken, run::

     git bisect bad

   Note, getting this wrong just once will send the rest of the bisection
   totally off course. To prevent having to start anew later you thus want to
   ensure what you tell Git is correct; it is thus often wise to spend a few
   minutes more on testing in case your reproducer is unreliable.

   After issuing one of these two commands, Git will usually check out another
   bisection point and print something like 'Bisecting: 675 revisions left to
   test after this (roughly 10 steps)'. In that case go back to step 1.

   If Git instead prints something like 'cafecaca0c0dacafecaca0c0dacafecaca0c0da
   is the first bad commit', then you have finished the bisection. In that case
   move to the next point below. Note, right after displaying that line Git will
   show some details about the culprit including its patch description; this can
   easily fill your terminal, so you might need to scroll up to see the message
   mentioning the culprit's commit-id.

   In case you missed Git's output, you can always run ``git bisect log`` to
   print the status: it will show how many steps remain or mention the result of
   the bisection.

* Recommended complementary task: put the bisection log and the current .config
  file aside for the bug report; furthermore tell Git to reset the sources to
  the state before the bisection::

     git bisect log > ~/bisection-log
     cp .config ~/bisection-config-culprit
     git bisect reset

* Recommended optional task: try reverting the culprit on top of the latest
  codebase and check if that fixes your bug; if that is the case, it validates
  the bisection and enables developers to resolve the regression through a
  revert.

  To try this, update your clone and check out latest mainline. Then tell Git
  to revert the change by specifying its commit-id::

     git revert --no-edit cafec0cacaca0

  Git might reject this, for example when the bisection landed on a merge
  commit. In that case, abandon the attempt. Do the same, if Git fails to revert
  the culprit on its own because later changes depend on it -- at least unless
  you bisected a stable or longterm kernel series, in which case you want to
  check out its latest codebase and try a revert there.

  If a revert succeeds, build and test another kernel to check if reverting
  resolved your regression.

With that the process is complete. Now report the regression as described by
Documentation/admin-guide/reporting-issues.rst.

Bisecting linux-next
--------------------

If you face a problem only happening in linux-next, bisect between the
linux-next branches 'stable' and 'master'. The following commands will start
the process for a linux-next tree you added as a remote called 'next'::

  git bisect start
  git bisect good next/stable
  git bisect bad next/master

The 'stable' branch refers to the state of linux-mainline that the current
linux-next release (found in the 'master' branch) is based on -- the former
thus should be free of any problems that show up in -next, but not in Linus'
tree.

This will bisect across a wide range of changes, some of which you might have
used in earlier linux-next releases without problems. Sadly there is no simple
way to avoid checking them: bisecting from one linux-next release to a later
one (say between 'next-20241020' and 'next-20241021') is impossible, as they
share no common history.

Additional reading material
---------------------------

* The `man page for 'git bisect' <https://git-scm.com/docs/git-bisect>`_ and
  `fighting regressions with 'git bisect' <https://git-scm.com/docs/git-bisect-lk2009.html>`_
  in the Git documentation.
* `Working with git bisect <https://nathanchance.dev/posts/working-with-git-bisect/>`_
  from kernel developer Nathan Chancellor.
* `Using Git bisect to figure out when brokenness was introduced <http://webchick.net/node/99>`_.
* `Fully automated bisecting with 'git bisect run' <https://lwn.net/Articles/317154>`_.

..
   end-of-content
..
   This document is maintained by Thorsten Leemhuis <linux@leemhuis.info>. If
   you spot a typo or small mistake, feel free to let him know directly and
   he'll fix it. You are free to do the same in a mostly informal way if you
   want to contribute changes to the text -- but for copyright reasons please CC
   linux-doc@vger.kernel.org and 'sign-off' your contribution as
   Documentation/process/submitting-patches.rst explains in the section 'Sign
   your work - the Developer's Certificate of Origin'.
..
   This text is available under GPL-2.0+ or CC-BY-4.0, as stated at the top
   of the file. If you want to distribute this text under CC-BY-4.0 only,
   please use 'The Linux kernel development community' for author attribution
   and link this as source:
   https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/plain/Documentation/admin-guide/bug-bisect.rst

..
   Note: Only the content of this RST file as found in the Linux kernel sources
   is available under CC-BY-4.0, as versions of this text that were processed
   (for example by the kernel's build system) might contain content taken from
   files which use a more restrictive license.

---

### Documentation Admin Guide Bug Hunting (`Documentation/admin-guide/bug-hunting.rst`)

Bug hunting
===========

Kernel bug reports often come with a stack dump like the one below::

	------------[ cut here ]------------
	WARNING: CPU: 1 PID: 28102 at kernel/module.c:1108 module_put+0x57/0x70
	Modules linked in: dvb_usb_gp8psk(-) dvb_usb dvb_core nvidia_drm(PO) nvidia_modeset(PO) snd_hda_codec_hdmi snd_hda_intel snd_hda_codec snd_hwdep snd_hda_core snd_pcm snd_timer snd soundcore nvidia(PO) [last unloaded: rc_core]
	CPU: 1 PID: 28102 Comm: rmmod Tainted: P        WC O 4.8.4-build.1 #1
	Hardware name: MSI MS-7309/MS-7309, BIOS V1.12 02/23/2009
	 00000000 c12ba080 00000000 00000000 c103ed6a c1616014 00000001 00006dc6
	 c1615862 00000454 c109e8a7 c109e8a7 00000009 ffffffff 00000000 f13f6a10
	 f5f5a600 c103ee33 00000009 00000000 00000000 c109e8a7 f80ca4d0 c109f617
	Call Trace:
	 [<c12ba080>] ? dump_stack+0x44/0x64
	 [<c103ed6a>] ? __warn+0xfa/0x120
	 [<c109e8a7>] ? module_put+0x57/0x70
	 [<c109e8a7>] ? module_put+0x57/0x70
	 [<c103ee33>] ? warn_slowpath_null+0x23/0x30
	 [<c109e8a7>] ? module_put+0x57/0x70
	 [<f80ca4d0>] ? gp8psk_fe_set_frontend+0x460/0x460 [dvb_usb_gp8psk]
	 [<c109f617>] ? symbol_put_addr+0x27/0x50
	 [<f80bc9ca>] ? dvb_usb_adapter_frontend_exit+0x3a/0x70 [dvb_usb]
	 [<f80bb3bf>] ? dvb_usb_exit+0x2f/0xd0 [dvb_usb]
	 [<c13d03bc>] ? usb_disable_endpoint+0x7c/0xb0
	 [<f80bb48a>] ? dvb_usb_device_exit+0x2a/0x50 [dvb_usb]
	 [<c13d2882>] ? usb_unbind_interface+0x62/0x250
	 [<c136b514>] ? __pm_runtime_idle+0x44/0x70
	 [<c13620d8>] ? __device_release_driver+0x78/0x120
	 [<c1362907>] ? driver_detach+0x87/0x90
	 [<c1361c48>] ? bus_remove_driver+0x38/0x90
	 [<c13d1c18>] ? usb_deregister+0x58/0xb0
	 [<c109fbb0>] ? SyS_delete_module+0x130/0x1f0
	 [<c1055654>] ? task_work_run+0x64/0x80
	 [<c1000fa5>] ? exit_to_usermode_loop+0x85/0x90
	 [<c10013f0>] ? do_fast_syscall_32+0x80/0x130
	 [<c1549f43>] ? sysenter_past_esp+0x40/0x6a
	---[ end trace 6ebc60ef3981792f ]---

Such stack traces provide enough information to identify the line inside the
Kernel's source code where the bug happened. Depending on the severity of
the issue, it may also contain the word **Oops**, as on this one::

	BUG: unable to handle kernel NULL pointer dereference at   (null)
	IP: [<c06969d4>] iret_exc+0x7d0/0xa59
	*pdpt = 000000002258a001 *pde = 0000000000000000
	Oops: 0002 [#1] PREEMPT SMP
	...

Despite being an **Oops** or some other sort of stack trace, the offended
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`.

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
annotated with "+", and "being unloaded" is annotated with "-".


Where is the Oops message is located?
-------------------------------------

Normally the Oops text is read from the kernel buffers by klogd and
handed to ``syslogd`` which writes it to a syslog file, typically
``/var/log/messages`` (depends on ``/etc/syslog.conf``). On systems with
systemd, it may also be stored by the ``journald`` daemon, and accessed
by running ``journalctl`` command.

Sometimes ``klogd`` dies, in which case you can run ``dmesg > file`` to
read the data from the kernel buffers and save it.  Or you can
``cat /proc/kmsg > file``, however you have to break in to stop the transfer,
since ``kmsg`` is a "never ending file".

If the machine has crashed so badly that you cannot enter commands or
the disk is not available then you have three options:

(1) Hand copy the text from the screen and type it in after the machine
    has restarted.  Messy but it is the only option if you have not
    planned for a crash. Alternatively, you can take a picture of
    the screen with a digital camera - not nice, but better than
    nothing.  If the messages scroll off the top of the console, you
    may find that booting with a higher resolution (e.g., ``vga=791``)
    will allow you to read more of the text. (Caveat: This needs ``vesafb``,
    so won't help for 'early' oopses.)

(2) Boot with a serial console (see
    :ref:`Documentation/admin-guide/serial-console.rst <serial_console>`),
    run a null modem to a second machine and capture the output there
    using your favourite communication program.  Minicom works well.

(3) Use Kdump (see Documentation/admin-guide/kdump/kdump.rst),
    extract the kernel ring buffer from old memory with using dmesg
    gdbmacro in Documentation/admin-guide/kdump/gdbmacros.txt.

Finding the bug's location
--------------------------

Reporting a bug works best if you point the location of the bug at the
Kernel source file. There are two methods for doing that. Usually, using
``gdb`` is easier, but the Kernel should be pre-compiled with debug info.

gdb
^^^

The GNU debugger (``gdb``) is the best way to figure out the exact file and line
number of the OOPS from the ``vmlinux`` file.

The usage of gdb works best on a kernel compiled with ``CONFIG_DEBUG_INFO``.
This can be set by running::

  $ ./scripts/config -d COMPILE_TEST -e DEBUG_KERNEL -e DEBUG_INFO

On a kernel compiled with ``CONFIG_DEBUG_INFO``, you can simply copy the
EIP value from the OOPS::

 EIP:    0060:[<c021e50e>]    Not tainted VLI

And use GDB to translate that to human-readable form::

  $ gdb vmlinux
  (gdb) l *0xc021e50e

If you don't have ``CONFIG_DEBUG_INFO`` enabled, you use the function
offset from the OOPS::

 EIP is at vt_ioctl+0xda8/0x1482

And recompile the kernel with ``CONFIG_DEBUG_INFO`` enabled::

  $ ./scripts/config -d COMPILE_TEST -e DEBUG_KERNEL -e DEBUG_INFO
  $ make vmlinux
  $ gdb vmlinux
  (gdb) l *vt_ioctl+0xda8
  0x1888 is in vt_ioctl (drivers/tty/vt/vt_ioctl.c:293).
  288	{
  289		struct vc_data *vc = NULL;
  290		int ret = 0;
  291
  292		console_lock();
  293		if (VT_BUSY(vc_num))
  294			ret = -EBUSY;
  295		else if (vc_num)
  296			vc = vc_deallocate(vc_num);
  297		console_unlock();

or, if you want to be more verbose::

  (gdb) p vt_ioctl
  $1 = {int (struct tty_struct *, unsigned int, unsigned long)} 0xae0 <vt_ioctl>
  (gdb) l *0xae0+0xda8

You could, instead, use the object file::

  $ make drivers/tty/
  $ gdb drivers/tty/vt/vt_ioctl.o
  (gdb) l *vt_ioctl+0xda8

If you have a call trace, such as::

     Call Trace:
      [<ffffffff8802c8e9>] :jbd:log_wait_commit+0xa3/0xf5
      [<ffffffff810482d9>] autoremove_wake_function+0x0/0x2e
      [<ffffffff8802770b>] :jbd:journal_stop+0x1be/0x1ee
      ...

this shows the problem likely is in the :jbd: module. You can load that module
in gdb and list the relevant code::

  $ gdb fs/jbd/jbd.ko
  (gdb) l *log_wait_commit+0xa3

.. note::

     You can also do the same for any function call at the stack trace,
     like this one::

	 [<f80bc9ca>] ? dvb_usb_adapter_frontend_exit+0x3a/0x70 [dvb_usb]

     The position where the above call happened can be seen with::

	$ gdb drivers/media/usb/dvb-usb/dvb-usb.o
	(gdb) l *dvb_usb_adapter_frontend_exit+0x3a

objdump
^^^^^^^

To debug a kernel, use objdump and look for the hex offset from the crash
output to find the valid line of code/assembler. Without debug symbols, you
will see the assembler code for the routine shown, but if your kernel has
debug symbols the C code will also be available. (Debug symbols can be enabled
in the kernel hacking menu of the menu configuration.) For example::

    $ objdump -r -S -l --disassemble net/ipv4/tcp.o

.. note::

   You need to be at the top level of the kernel tree for this to pick up
   your C files.

If you don't have access to the source code you can still debug some crash
dumps using the following method (example crash dump output as shown by
Dave Miller)::

     EIP is at 	+0x14/0x4c0
      ...
     Code: 44 24 04 e8 6f 05 00 00 e9 e8 fe ff ff 8d 76 00 8d bc 27 00 00
     00 00 55 57  56 53 81 ec bc 00 00 00 8b ac 24 d0 00 00 00 8b 5d 08
     <8b> 83 3c 01 00 00 89 44  24 14 8b 45 28 85 c0 89 44 24 18 0f 85

     Put the bytes into a "foo.s" file like this:

            .text
            .globl foo
     foo:
            .byte  .... /* bytes from Code: part of OOPS dump */

     Compile it with "gcc -c -o foo.o foo.s" then look at the output of
     "objdump --disassemble foo.o".

     Output:

     ip_queue_xmit:
         push       %ebp
         push       %edi
         push       %esi
         push       %ebx
         sub        $0xbc, %esp
         mov        0xd0(%esp), %ebp        ! %ebp = arg0 (skb)
         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
on what CPU architecture is being debugged.

Reporting the bug
-----------------

Once you find where the bug happened, by inspecting its location,
you could either try to fix it yourself or report it upstream.

In order to report it upstream, you should identify the bug tracker, if any, or
mailing list used for the development of the affected code. This can be done by
using the ``get_maintainer.pl`` script.

For example, if you find a bug at the gspca's sonixj.c file, you can get
its maintainers with::

	$ ./scripts/get_maintainer.pl --bug -f drivers/media/usb/gspca/sonixj.c
	Hans Verkuil <hverkuil@kernel.org> (odd fixer:GSPCA USB WEBCAM DRIVER,commit_signer:1/1=100%)
	Mauro Carvalho Chehab <mchehab@kernel.org> (maintainer:MEDIA INPUT INFRASTRUCTURE (V4L/DVB),commit_signer:1/1=100%)
	Tejun Heo <tj@kernel.org> (commit_signer:1/1=100%)
	Bhaktipriya Shridhar <bhaktipriya96@gmail.com> (commit_signer:1/1=100%,authored:1/1=100%,added_lines:4/4=100%,removed_lines:9/9=100%)
	linux-media@vger.kernel.org (open list:GSPCA USB WEBCAM DRIVER)
	linux-kernel@vger.kernel.org (open list)

Please notice that it will point to:

- The last developers that touched the source code (if this is done inside
  a git tree). On the above example, Tejun and Bhaktipriya (in this
  specific case, none really involved on the development of this file);
- The driver maintainer (Hans Verkuil);
- The subsystem maintainer (Mauro Carvalho Chehab);
- The driver and/or subsystem mailing list (linux-media@vger.kernel.org);
- The Linux Kernel mailing list (linux-kernel@vger.kernel.org);
- The bug reporting URIs for the driver/subsystem (none in the above example).

If the listing contains bug reporting URIs at the end, please prefer them over
email. Otherwise, please report bugs to the mailing list used for the
development of the code (linux-media ML) copying the driver maintainer (Hans).

If you are totally stumped as to whom to send the report, and
``get_maintainer.pl`` didn't provide you anything useful, send it to
linux-kernel@vger.kernel.org.

Thanks for your help in making Linux as stable as humanly possible.

Fixing the bug
--------------

If you know programming, you could help us by not only reporting the bug,
but also providing us with a solution. After all, open source is about
sharing what you do and don't you want to be recognised for your genius?

If you decide to take this way, once you have worked out a fix please submit
it upstream.

Please do read
:ref:`Documentation/process/submitting-patches.rst <submittingpatches>` though
to help your code get accepted.


---------------------------------------------------------------------------

Notes on Oops tracing with ``klogd``
------------------------------------

In order to help Linus and the other kernel developers there has been
substantial support incorporated into ``klogd`` for processing protection
faults.  In order to have full support for address resolution at least
version 1.3-pl3 of the ``sysklogd`` package should be used.

When a protection fault occurs the ``klogd`` daemon automatically
translates important addresses in the kernel log messages to their
symbolic equivalents.  This translated kernel message is then
forwarded through whatever reporting mechanism ``klogd`` is using.  The
protection fault message can be simply cut out of the message files
and forwarded to the kernel developers.

Two types of address resolution are performed by ``klogd``.  The first is
static translation and the second is dynamic translation.
Static translation uses the System.map file.
In order to do static translation the ``klogd`` daemon
must be able to find a system map file at daemon initialization time.
See the klogd man page for information on how ``klogd`` searches for map
files.

Dynamic address translation is important when kernel loadable modules
are being used.  Since memory for kernel modules is allocated from the
kernel's dynamic memory pools there are no fixed locations for either
the start of the module or for functions and symbols in the module.

The kernel supports system calls which allow a program to determine
which modules are loaded and their location in memory.  Using these
system calls the klogd daemon builds a symbol table which can be used
to debug a protection fault which occurs in a loadable kernel module.

At the very minimum klogd will provide the name of the module which
generated the protection fault.  There may be additional symbolic
information available if the developer of the loadable module chose to
export symbol information from the module.

Since the kernel module environment can be dynamic there must be a
mechanism for notifying the ``klogd`` daemon when a change in module
environment occurs.  There are command line options available which
allow klogd to signal the currently executing daemon that symbol
information should be refreshed.  See the ``klogd`` manual page for more
information.

A patch is included with the sysklogd distribution which modifies the
``modules-2.0.0`` package to automatically signal klogd whenever a module
is loaded or unloaded.  Applying this patch provides essentially
seamless support for debugging protection faults which occur with
kernel loadable modules.

The following is an example of a protection fault in a loadable module
processed by ``klogd``::

	Aug 29 09:51:01 blizard kernel: Unable to handle kernel paging request at virtual address f15e97cc
	Aug 29 09:51:01 blizard kernel: current->tss.cr3 = 0062d000, %cr3 = 0062d000
	Aug 29 09:51:01 blizard kernel: *pde = 00000000
	Aug 29 09:51:01 blizard kernel: Oops: 0002
	Aug 29 09:51:01 blizard kernel: CPU:    0
	Aug 29 09:51:01 blizard kernel: EIP:    0010:[oops:_oops+16/3868]
	Aug 29 09:51:01 blizard kernel: EFLAGS: 00010212
	Aug 29 09:51:01 blizard kernel: eax: 315e97cc   ebx: 003a6f80   ecx: 001be77b   edx: 00237c0c
	Aug 29 09:51:01 blizard kernel: esi: 00000000   edi: bffffdb3   ebp: 00589f90   esp: 00589f8c
	Aug 29 09:51:01 blizard kernel: ds: 0018   es: 0018   fs: 002b   gs: 002b   ss: 0018
	Aug 29 09:51:01 blizard kernel: Process oops_test (pid: 3374, process nr: 21, stackpage=00589000)
	Aug 29 09:51:01 blizard kernel: Stack: 315e97cc 00589f98 0100b0b4 bffffed4 0012e38e 00240c64 003a6f80 00000001
	Aug 29 09:51:01 blizard kernel:        00000000 00237810 bfffff00 0010a7fa 00000003 00000001 00000000 bfffff00
	Aug 29 09:51:01 blizard kernel:        bffffdb3 bffffed4 ffffffda 0000002b 0007002b 0000002b 0000002b 00000036
	Aug 29 09:51:01 blizard kernel: Call Trace: [oops:_oops_ioctl+48/80] [_sys_ioctl+254/272] [_system_call+82/128]
	Aug 29 09:51:01 blizard kernel: Code: c7 00 05 00 00 00 eb 08 90 90 90 90 90 90 90 90 89 ec 5d c3

---

### Documentation Admin Guide Cgroup V2 (`Documentation/admin-guide/cgroup-v2.rst`)

.. _cgroup-v2:

================
Control Group v2
================

:Date: October, 2015
:Author: Tejun Heo <tj@kernel.org>

This is the authoritative documentation on the design, interface and
conventions of cgroup v2.  It describes all userland-visible aspects
of cgroup including core and specific controller behaviors.  All
future changes must be reflected in this document.  Documentation for
v1 is available under :ref:`Documentation/admin-guide/cgroup-v1/index.rst <cgroup-v1>`.

.. CONTENTS

   [Whenever any new section is added to this document, please also add
    an entry here.]

   1. Introduction
     1-1. Terminology
     1-2. What is cgroup?
   2. Basic Operations
     2-1. Mounting
     2-2. Organizing Processes and Threads
       2-2-1. Processes
       2-2-2. Threads
     2-3. [Un]populated Notification
     2-4. Controlling Controllers
       2-4-1. Availability
       2-4-2. Enabling and Disabling
       2-4-3. Top-down Constraint
       2-4-4. No Internal Process Constraint
     2-5. Delegation
       2-5-1. Model of Delegation
       2-5-2. Delegation Containment
     2-6. Guidelines
       2-6-1. Organize Once and Control
       2-6-2. Avoid Name Collisions
   3. Resource Distribution Models
     3-1. Weights
     3-2. Limits
     3-3. Protections
     3-4. Allocations
   4. Interface Files
     4-1. Format
     4-2. Conventions
     4-3. Core Interface Files
   5. Controllers
     5-1. CPU
       5-1-1. CPU Interface Files
     5-2. Memory
       5-2-1. Memory Interface Files
       5-2-2. Usage Guidelines
       5-2-3. Memory Ownership
     5-3. IO
       5-3-1. IO Interface Files
       5-3-2. Writeback
       5-3-3. IO Latency
         5-3-3-1. How IO Latency Throttling Works
         5-3-3-2. IO Latency Interface Files
       5-3-4. IO Priority
     5-4. PID
       5-4-1. PID Interface Files
     5-5. Cpuset
       5.5-1. Cpuset Interface Files
     5-6. Device controller
     5-7. RDMA
       5-7-1. RDMA Interface Files
     5-8. DMEM
       5-8-1. DMEM Interface Files
     5-9. HugeTLB
       5.9-1. HugeTLB Interface Files
     5-10. Misc
       5.10-1 Misc Interface Files
       5.10-2 Migration and Ownership
     5-11. Others
       5-11-1. perf_event
     5-N. Non-normative information
       5-N-1. CPU controller root cgroup process behaviour
       5-N-2. IO controller root cgroup process behaviour
   6. Namespace
     6-1. Basics
     6-2. The Root and Views
     6-3. Migration and setns(2)
     6-4. Interaction with Other Namespaces
   P. Information on Kernel Programming
     P-1. Filesystem Support for Writeback
   D. Deprecated v1 Core Features
   R. Issues with v1 and Rationales for v2
     R-1. Multiple Hierarchies
     R-2. Thread Granularity
     R-3. Competition Between Inner Nodes and Threads
     R-4. Other Interface Issues
     R-5. Controller Issues and Remedies
       R-5-1. Memory


Introduction
============

Terminology
-----------

"cgroup" stands for "control group" and is never capitalized.  The
singular form is used to designate the whole feature and also as a
qualifier as in "cgroup controllers".  When explicitly referring to
multiple individual control groups, the plural form "cgroups" is used.


What is cgroup?
---------------

cgroup is a mechanism to organize processes hierarchically and
distribute system resources along the hierarchy in a controlled and
configurable manner.

cgroup is largely composed of two parts - the core and controllers.
cgroup core is primarily responsible for hierarchically organizing
processes.  A cgroup controller is usually responsible for
distributing a specific type of system resource along the hierarchy
although there are utility controllers which serve purposes other than
resource distribution.

cgroups form a tree structure and every process in the system belongs
to one and only one cgroup.  All threads of a process belong to the
same cgroup.  On creation, all processes are put in the cgroup that
the parent process belongs to at the time.  A process can be migrated
to another cgroup.  Migration of a process doesn't affect already
existing descendant processes.

Following certain structural constraints, controllers may be enabled or
disabled selectively on a cgroup.  All controller behaviors are
hierarchical - if a controller is enabled on a cgroup, it affects all
processes which belong to the cgroups consisting the inclusive
sub-hierarchy of the cgroup.  When a controller is enabled on a nested
cgroup, it always restricts the resource distribution further.  The
restrictions set closer to the root in the hierarchy can not be
overridden from further away.


Basic Operations
================

Mounting
--------

Unlike v1, cgroup v2 has only single hierarchy.  The cgroup v2
hierarchy can be mounted with the following mount command::

  # mount -t cgroup2 none $MOUNT_POINT

cgroup2 filesystem has the magic number 0x63677270 ("cgrp").  All
controllers which support v2 and are not bound to a v1 hierarchy are
automatically bound to the v2 hierarchy and show up at the root.
Controllers which are not in active use in the v2 hierarchy can be
bound to other hierarchies.  This allows mixing v2 hierarchy with the
legacy v1 multiple hierarchies in a fully backward compatible way.

A controller can be moved across hierarchies only after the controller
is no longer referenced in its current hierarchy.  Because per-cgroup
controller states are destroyed asynchronously and controllers may
have lingering references, a controller may not show up immediately on
the v2 hierarchy after the final umount of the previous hierarchy.
Similarly, a controller should be fully disabled to be moved out of
the unified hierarchy and it may take some time for the disabled
controller to become available for other hierarchies; furthermore, due
to inter-controller dependencies, other controllers may need to be
disabled too.

While useful for development and manual configurations, moving
controllers dynamically between the v2 and other hierarchies is
strongly discouraged for production use.  It is recommended to decide
the hierarchies and controller associations before starting using the
controllers after system boot.

During transition to v2, system management software might still
automount the v1 cgroup filesystem and so hijack all controllers
during boot, before manual intervention is possible. To make testing
and experimenting easier, the kernel parameter cgroup_no_v1= allows
disabling controllers in v1 and make them always available in v2.

cgroup v2 currently supports the following mount options.

  nsdelegate
	Consider cgroup namespaces as delegation boundaries.  This
	option is system wide and can only be set on mount or modified
	through remount from the init namespace.  The mount option is
	ignored on non-init namespace mounts.  Please refer to the
	Delegation section for details.

  favordynmods
        Reduce the latencies of dynamic cgroup modifications such as
        task migrations and controller on/offs at the cost of making
        hot path operations such as forks and exits more expensive.
        The static usage pattern of creating a cgroup, enabling
        controllers, and then seeding it with CLONE_INTO_CGROUP is
        not affected by this option.

  memory_localevents
        Only populate memory.events with data for the current cgroup,
        and not any subtrees. This is legacy behaviour, the default
        behaviour without this option is to include subtree counts.
        This option is system wide and can only be set on mount or
        modified through remount from the init namespace. The mount
        option is ignored on non-init namespace mounts.

  memory_recursiveprot
        Recursively apply memory.min and memory.low protection to
        entire subtrees, without requiring explicit downward
        propagation into leaf cgroups.  This allows protecting entire
        subtrees from one another, while retaining free competition
        within those subtrees.  This should have been the default
        behavior but is a mount-option to avoid regressing setups
        relying on the original semantics (e.g. specifying bogusly
        high 'bypass' protection values at higher tree levels).

  memory_hugetlb_accounting
        Count HugeTLB memory usage towards the cgroup's overall
        memory usage for the memory controller (for the purpose of
        statistics reporting and memory protetion). This is a new
        behavior that could regress existing setups, so it must be
        explicitly opted in with this mount option.

        A few caveats to keep in mind:

        * There is no HugeTLB pool management involved in the memory
          controller. The pre-allocated pool does not belong to anyone.
          Specifically, when a new HugeTLB folio is allocated to
          the pool, it is not accounted for from the perspective of the
          memory controller. It is only charged to a cgroup when it is
          actually used (for e.g at page fault time). Host memory
          overcommit management has to consider this when configuring
          hard limits. In general, HugeTLB pool management should be
          done via other mechanisms (such as the HugeTLB controller).
        * Failure to charge a HugeTLB folio to the memory controller
          results in SIGBUS. This could happen even if the HugeTLB pool
          still has pages available (but the cgroup limit is hit and
          reclaim attempt fails).
        * Charging HugeTLB memory towards the memory controller affects
          memory protection and reclaim dynamics. Any userspace tuning
          (of low, min limits for e.g) needs to take this into account.
        * HugeTLB pages utilized while this option is not selected
          will not be tracked by the memory controller (even if cgroup
          v2 is remounted later on).

  pids_localevents
        The option restores v1-like behavior of pids.events:max, that is only
        local (inside cgroup proper) fork failures are counted. Without this
        option pids.events.max represents any pids.max enforcemnt across
        cgroup's subtree.



Organizing Processes and Threads
--------------------------------

Processes
~~~~~~~~~

Initially, only the root cgroup exists to which all processes belong.
A child cgroup can be created by creating a sub-directory::

  # mkdir $CGROUP_NAME

A given cgroup may have multiple child cgroups forming a tree
structure.  Each cgroup has a read-writable interface file
"cgroup.procs".  When read, it lists the PIDs of all processes which
belong to the cgroup one-per-line.  The PIDs are not ordered and the
same PID may show up more than once if the process got moved to
another cgroup and then back or the PID got recycled while reading.

A process can be migrated into a cgroup by writing its PID to the
target cgroup's "cgroup.procs" file.  Only one process can be migrated
on a single write(2) call.  If a process is composed of multiple
threads, writing the PID of any thread migrates all threads of the
process.

When a process forks a child process, the new process is born into the
cgroup that the forking process belongs to at the time of the
operation.  After exit, a process stays associated with the cgroup
that it belonged to at the time of exit until it's reaped; however, a
zombie process does not appear in "cgroup.procs" and thus can't be
moved to another cgroup.

A cgroup which doesn't have any children or live processes can be
destroyed by removing the directory.  Note that a cgroup which doesn't
have any children and is associated only with zombie processes is
considered empty and can be removed::

  # rmdir $CGROUP_NAME

"/proc/$PID/cgroup" lists a process's cgroup membership.  If legacy
cgroup is in use in the system, this file may contain multiple lines,
one for each hierarchy.  The entry for cgroup v2 is always in the
format "0::$PATH"::

  # cat /proc/842/cgroup
  ...
  0::/test-cgroup/test-cgroup-nested

If the process becomes a zombie and the cgroup it was associated with
is removed subsequently, " (deleted)" is appended to the path::

  # cat /proc/842/cgroup
  ...
  0::/test-cgroup/test-cgroup-nested (deleted)


Threads
~~~~~~~

cgroup v2 supports thread granularity for a subset of controllers to
support use cases requiring hierarchical resource distribution across
the threads of a group of processes.  By default, all threads of a
process belong to the same cgroup, which also serves as the resource
domain to host resource consumptions which are not specific to a
process or thread.  The thread mode allows threads to be spread across
a subtree while still maintaining the common resource domain for them.

Controllers which support thread mode are called threaded controllers.
The ones which don't are called domain controllers.

Marking a cgroup threaded makes it join the resource domain of its
parent as a threaded cgroup.  The parent may be another threaded
cgroup whose resource domain is further up in the hierarchy.  The root
of a threaded subtree, that is, the nearest ancestor which is not
threaded, is called threaded domain or thread root interchangeably and
serves as the resource domain for the entire subtree.

Inside a threaded subtree, threads of a process can be put in
different cgroups and are not subject to the no internal process
constraint - threaded controllers can be enabled on non-leaf cgroups
whether they have threads in them or not.

As the threaded domain cgroup hosts all the domain resource
consumptions of the subtree, it is considered to have internal
resource consumptions whether there are processes in it or not and
can't have populated child cgroups which aren't threaded.  Because the
root cgroup is not subject to no internal process constraint, it can
serve both as a threaded domain and a parent to domain cgroups.

The current operation mode or type of the cgroup is shown in the
"cgroup.type" file which indicates whether the cgroup is a normal
domain, a domain which is serving as the domain of a threaded subtree,
or a threaded cgroup.

On creation, a cgroup is always a domain cgroup and can be made
threaded by writing "threaded" to the "cgroup.type" file.  The
operation is single direction::

  # echo threaded > cgroup.type

Once threaded, the cgroup can't be made a domain again.  To enable the
thread mode, the following conditions must be met.

- As the cgroup will join the parent's resource domain.  The parent
  must either be a valid (threaded) domain or a threaded cgroup.

- When the parent is an unthreaded domain, it must not have any domain
  controllers enabled or populated domain children.  The root is
  exempt from this requirement.

Topology-wise, a cgroup can be in an invalid state.  Please consider
the following topology::

  A (threaded domain) - B (threaded) - C (domain, just created)

C is created as a domain but isn't connected to a parent which can
host child domains.  C can't be used until it is turned into a
threaded cgroup.  "cgroup.type" file will report "domain (invalid)" in
these cases.  Operations which fail due to invalid topology use
EOPNOTSUPP as the errno.

A domain cgroup is turned into a threaded domain when one of its child
cgroup becomes threaded or threaded controllers are enabled in the
"cgroup.subtree_control" file while there are processes in the cgroup.
A threaded domain reverts to a normal domain when the conditions
clear.

When read, "cgroup.threads" contains the list of the thread IDs of all
threads in the cgroup.  Except that the operations are per-thread
instead of per-process, "cgroup.threads" has the same format and
behaves the same way as "cgroup.procs".  While "cgroup.threads" can be
written to in any cgroup, as it can only move threads inside the same
threaded domain, its operations are confined inside each threaded
subtree.

The threaded domain cgroup serves as the resource domain for the whole
subtree, and, while the threads can be scattered across the subtree,
all the processes are considered to be in the threaded domain cgroup.
"cgroup.procs" in a threaded domain cgroup contains the PIDs of all
processes in the subtree and is not readable in the subtree proper.
However, "cgroup.procs" can be written to from anywhere in the subtree
to migrate all threads of the matching process to the cgroup.

Only threaded controllers can be enabled in a threaded subtree.  When
a threaded controller is enabled inside a threaded subtree, it only
accounts for and controls resource consumptions associated with the
threads in the cgroup and its descendants.  All consumptions which
aren't tied to a specific thread belong to the threaded domain cgroup.

Because a threaded subtree is exempt from no internal process
constraint, a threaded controller must be able to handle competition
between threads in a non-leaf cgroup and its child cgroups.  Each
threaded controller defines how such competitions are handled.

Currently, the following controllers are threaded and can be enabled
in a threaded cgroup::

- cpu
- cpuset
- perf_event
- pids

[Un]populated Notification
--------------------------

Each non-root cgroup has a "cgroup.events" file which contains
"populated" field indicating whether the cgroup's sub-hierarchy has
live processes in it.  Its value is 0 if there is no live process in
the cgroup and its descendants; otherwise, 1.  poll and [id]notify
events are triggered when the value changes.  This can be used, for
example, to start a clean-up operation after all processes of a given
sub-hierarchy have exited.  The populated state updates and
notifications are recursive.  Consider the following sub-hierarchy
where the numbers in the parentheses represent the numbers of processes
in each cgroup::

  A(4) - B(0) - C(1)
              \ D(0)

A, B and C's "populated" fields would be 1 while D's 0.  After the one
process in C exits, B and C's "populated" fields would flip to "0" and
file modified events will be generated on the "cgroup.events" files of
both cgroups.


Controlling Controllers
-----------------------

Availability
~~~~~~~~~~~~

A controller is available in a cgroup when it is supported by the kernel (i.e.,
compiled in, not disabled and not attached to a v1 hierarchy) and listed in the
"cgroup.controllers" file. Availability means the controller's interface files
are exposed in the cgroup’s directory, allowing the distribution of the target
resource to be observed or controlled within that cgroup.

Enabling and Disabling
~~~~~~~~~~~~~~~~~~~~~~

Each cgroup has a "cgroup.controllers" file which lists all
controllers available for the cgroup to enable::

  # cat cgroup.controllers
  cpu io memory

No controller is enabled by default.  Controllers can be enabled and
disabled by writing to the "cgroup.subtree_control" file::

  # echo "+cpu +memory -io" > cgroup.subtree_control

Only controllers which are listed in "cgroup.controllers" can be
enabled.  When multiple operations are specified as above, either they
all succeed or fail.  If multiple operations on the same controller
are specified, the last one is effective.

Enabling a controller in a cgroup indicates that the distribution of
the target resource across its immediate children will be controlled.
Consider the following sub-hierarchy.  The enabled controllers are
listed in parentheses::

  A(cpu,memory) - B(memory) - C()
                            \ D()

As A has "cpu" and "memory" enabled, A will control the distribution
of CPU cycles and memory to its children, in this case, B.  As B has
"memory" enabled but not "CPU", C and D will compete freely on CPU
cycles but their division of memory available to B will be controlled.

As a controller regulates the distribution of the target resource to
the cgroup's children, enabling it creates the controller's interface
files in the child cgroups.  In the above example, enabling "cpu" on B
would create the "cpu." prefixed controller interface files in C and
D.  Likewise, disabling "memory" from B would remove the "memory."
prefixed controller interface files from C and D.  This means that the
controller interface files - anything which doesn't start with
"cgroup." are owned by the parent rather than the cgroup itself.


Top-down Constraint
~~~~~~~~~~~~~~~~~~~

Resources are distributed top-down and a cgroup can further distribute
a resource only if the resource has been distributed to it from the
parent.  This means that all non-root "cgroup.subtree_control" files
can only contain controllers which are enabled in the parent's
"cgroup.subtree_control" file.  A controller can be enabled only if
the parent has the controller enabled and a controller can't be
disabled if one or more children have it enabled.


No Internal Process Constraint
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Non-root cgroups can distribute domain resources to their children
only when they don't have any processes of their own.  In other words,
only domain cgroups which don't contain any processes can have domain
controllers enabled in their "cgroup.subtree_control" files.

This guarantees that, when a domain controller is looking at the part
of the hierarchy which has it enabled, processes are always only on
the leaves.  This rules out situations where child cgroups compete
against internal processes of the parent.

The root cgroup is exempt from this restriction.  Root contains
processes and anonymous resource consumption which can't be associated
with any other cgroups and requires special treatment from most
controllers.  How resource consumption in the root cgroup is governed
is up to each controller (for more information on this topic please
refer to the Non-normative information section in the Controllers
chapter).

Note that the restriction doesn't get in the way if there is no
enabled controller in the cgroup's "cgroup.subtree_control".  This is
important as otherwise it wouldn't be possible to create children of a
populated cgroup.  To control resource distribution of a cgroup, the
cgroup must create children and transfer all its processes to the
children before enabling controllers in its "cgroup.subtree_control"
file.


Delegation
----------

Model of Delegation
~~~~~~~~~~~~~~~~~~~

A cgroup can be delegated in two ways.  First, to a less privileged
user by granting write access of the directory and its "cgroup.procs",
"cgroup.threads" and "cgroup.subtree_control" files to the user.
Second, if the "nsdelegate" mount option is set, automatically to a
cgroup namespace on namespace creation.

Because the resource control interface files in a given directory
control the distribution of the parent's resources, the delegatee
shouldn't be allowed to write to them.  For the first method, this is
achieved by not granting access to these files.  For the second, files
outside the namespace should be hidden from the delegatee by the means
of at least mount namespacing, and the kernel rejects writes to all
files on a namespace root from inside the cgroup namespace, except for
those files listed in "/sys/kernel/cgroup/delegate" (including
"cgroup.procs", "cgroup.threads", "cgroup.subtree_control", etc.).

The end results are equivalent for both delegation types.  Once
delegated, the user can build sub-hierarchy under the directory,
organize processes inside it as it sees fit and further distribute the
resources it received from the parent.  The limits and other settings
of all resource controllers are hierarchical and regardless of what
happens in the delegated sub-hierarchy, nothing can escape the
resource restrictions imposed by the parent.

Currently, cgroup doesn't impose any restrictions on the number of
cgroups in or nesting depth of a delegated sub-hierarchy; however,
this may be limited explicitly in the future.


Delegation Containment
~~~~~~~~~~~~~~~~~~~~~~

A delegated sub-hierarchy is contained in the sense that processes
can't be moved into or out of the sub-hierarchy by the delegatee.

For delegations to a less privileged user, this is achieved by
requiring the following conditions for a process with a non-root euid
to migrate a target process into a cgroup by writing its PID to the
"cgroup.procs" file.

- The writer must have write access to the "cgroup.procs" file.

- The writer must have write access to the "cgroup.procs" file of the
  common ancestor of the source and destination cgroups.

The above two constraints ensure that while a delegatee may migrate
processes around freely in the delegated sub-hierarchy it can't pull
in from or push out to outside the sub-hierarchy.

For an example, let's assume cgroups C0 and C1 have been delegated to
user U0 who created C00, C01 under C0 and C10 under C1 as follows and
all processes under C0 and C1 belong to U0::

  ~~~~~~~~~~~~~ - C0 - C00
  ~ cgroup    ~      \ C01
  ~ hierarchy ~
  ~~~~~~~~~~~~~ - C1 - C10

Let's also say U0 wants to write the PID of a process which is
currently in C10 into "C00/cgroup.procs".  U0 has write access to the
file; however, the common ancestor of the source cgroup C10 and the
destination cgroup C00 is above the points of delegation and U0 would
not have write access to its "cgroup.procs" files and thus the write
will be denied with -EACCES.

For delegations to namespaces, containment is achieved by requiring
that both the source and destination cgroups are reachable from the
namespace of the process which is attempting the migration.  If either
is not reachable, the migration is rejected with -ENOENT.


Guidelines
----------

Organize Once and Control
~~~~~~~~~~~~~~~~~~~~~~~~~

Migrating a process across cgroups is a relatively expensive operation
and stateful resources such as memory are not moved together with the
process.  This is an explicit design decision as there often exist
inherent trade-offs between migration and various hot paths in terms
of synchronization cost.

As such, migrating processes across cgroups frequently as a means to
apply different resource restrictions is discouraged.  A workload
should be assigned to a cgroup according to the system's logical and
resource structure once on start-up.  Dynamic adjustments to resource
distribution can be made by changing controller configuration through
the interface files.


Avoid Name Collisions
~~~~~~~~~~~~~~~~~~~~~

Interface files for a cgroup and its children cgroups occupy the same
directory and it is possible to create children cgroups which collide
with interface files.

All cgroup core interface files are prefixed with "cgroup." and each
controller's interface files are prefixed with the controller name and
a dot.  A controller's name is composed of lower case alphabets and
'_'s but never begins with an '_' so it can be used as the prefix
character for collision avoidance.  Also, interface file names won't
start or end with terms which are often used in categorizing workloads
such as job, service, slice, unit or workload.

cgroup doesn't do anything to prevent name collisions and it's the
user's responsibility to avoid them.


Resource Distribution Models
============================

cgroup controllers implement several resource distribution schemes
depending on the resource type and expected use cases.  This section
describes major schemes in use along with their expected behaviors.


Weights
-------

A parent's resource is distributed by adding up the weights of all
active children and giving each the fraction matching the ratio of its
weight against the sum.  As only children which can make use of the
resource at the moment participate in the distribution, this is
work-conserving.  Due to the dynamic nature, this model is usually
used for stateless resources.

All weights are in the range [1, 10000] with the default at 100.  This
allows symmetric multiplicative biases in both directions at fine
enough granularity while staying in the intuitive range.

As long as the weight is in range, all configuration combinations are
valid and there is no reason to reject configuration changes or
process migrations.

"cpu.weight" proportionally distributes CPU cycles to active children
and is an example of this type.


.. _cgroupv2-limits-distributor:

Limits
------

A child can only consume up to the configured amount of the resource.
Limits can be over-committed - the sum of the limits of children can
exceed the amount of resource available to the parent.

Limits are in the range [0, max] and defaults to "max", which is noop.

As limits can be over-committed, all configuration combinations are
valid and there is no reason to reject configuration changes or
process migrations.

"io.max" limits the maximum BPS and/or IOPS that a cgroup can consume
on an IO device and is an example of this type.

.. _cgroupv2-protections-distributor:

Protections
-----------

A cgroup is protected up to the configured amount of the resource
as long as the usages of all its ancestors are under their
protected levels.  Protections can be hard guarantees or best effort
soft boundaries.  Protections can also be over-committed in which case
only up to the amount available to the parent is protected among
children.

Protections are in the range [0, max] and defaults to 0, which is
noop.

As protections can be over-committed, all configuration combinations
are valid and there is no reason to reject configuration changes or
process migrations.

"memory.low" implements best-effort memory protection and is an
example of this type.


Allocations
-----------

A cgroup is exclusively allocated a certain amount of a finite
resource.  Allocations can't be over-committed - the sum of the
allocations of children can not exceed the amount of resource
available to the parent.

Allocations are in the range [0, max] and defaults to 0, which is no
resource.

As allocations can't be over-committed, some configuration
combinations are invalid and should be rejected.  Also, if the
resource is mandatory for execution of processes, process migrations
may be rejected.

"cpu.rt.max" hard-allocates realtime slices and is an example of this
type.


Interface Files
===============

Format
------

All interface files should be in one of the following formats whenever
possible::

  New-line separated values
  (when only one value can be written at once)

	VAL0\n
	VAL1\n
	...

  Space separated values
  (when read-only or multiple values can be written at once)

	VAL0 VAL1 ...\n

  Flat keyed

	KEY0 VAL0\n
	KEY1 VAL1\n
	...

  Nested keyed

	KEY0 SUB_KEY0=VAL00 SUB_KEY1=VAL01...
	KEY1 SUB_KEY0=VAL10 SUB_KEY1=VAL11...
	...

For a writable file, the format for writing should generally match
reading; however, controllers may allow omitting later fields or
implement restricted shortcuts for most common use cases.

For both flat and nested keyed files, only the values for a single key
can be written at a time.  For nested keyed files, the sub key pairs
may be specified in any order and not all pairs have to be specified.


Conventions
-----------

- Settings for a single feature should be contained in a single file.

- The root cgroup should be exempt from resource control and thus
  shouldn't have resource control interface files.

- The default time unit is microseconds.  If a different unit is ever
  used, an explicit unit suffix must be present.

- A parts-per quantity should use a percentage decimal with at least
  two digit fractional part - e.g. 13.40.

- If a controller implements weight based resource distribution, its
  interface file should be named "weight" and have the range [1,
  10000] with 100 as the default.  The values are chosen to allow
  enough and symmetric bias in both directions while keeping it
  intuitive (the default is 100%).

- If a controller implements an absolute resource guarantee and/or
  limit, the interface files should be named "min" and "max"
  respectively.  If a controller implements best effort resource
  guarantee and/or limit, the interface files should be named "low"
  and "high" respectively.

  In the above four control files, the special token "max" should be
  used to represent upward infinity for both reading and writing.

- If a setting has a configurable default value and keyed specific
  overrides, the default entry should be keyed with "default" and
  appear as the first entry in the file.

  The default value can be updated by writing either "default $VAL" or
  "$VAL".

  When writing to update a specific override, "default" can be used as
  the value to indicate removal of the override.  Override entries
  with "default" as the value must not appear when read.

  For example, a setting which is keyed by major:minor device numbers
  with integer values may look like the following::

    # cat cgroup-example-interface-file
    default 150
    8:0 300

  The default value can be updated by::

    # echo 125 > cgroup-example-interface-file

  or::

    # echo "default 125" > cgroup-example-interface-file

  An override can be set by::

    # echo "8:16 170" > cgroup-example-interface-file

  and cleared by::

    # echo "8:0 default" > cgroup-example-interface-file
    # cat cgroup-example-interface-file
    default 125
    8:16 170

- For events which are not very high frequency, an interface file
  "events" should be created which lists event key value pairs.
  Whenever a notifiable event happens, file modified event should be
  generated on the file.


Core Interface Files
--------------------

All cgroup core files are prefixed with "cgroup."

  cgroup.type
	A read-write single value file which exists on non-root
	cgroups.

	When read, it indicates the current type of the cgroup, which
	can be one of the following values.

	- "domain" : A normal valid domain cgroup.

	- "domain threaded" : A threaded domain cgroup which is
          serving as the root of a threaded subtree.

	- "domain invalid" : A cgroup which is in an invalid state.
	  It can't be populated or have controllers enabled.  It may
	  be allowed to become a threaded cgroup.

	- "threaded" : A threaded cgroup which is a member of a
          threaded subtree.

	A cgroup can be turned into a threaded cgroup by writing
	"threaded" to this file.

  cgroup.procs
	A read-write new-line separated values file which exists on
	all cgroups.

	When read, it lists the PIDs of all processes which belong to
	the cgroup one-per-line.  The PIDs are not ordered and the
	same PID may show up more than once if the process got moved
	to another cgroup and then back or the PID got recycled while
	reading.

	A PID can be written to migrate the process associated with
	the PID to the cgroup.  The writer should match all of the
	following conditions.

	- It must have write access to the "cgroup.procs" file.

	- It must have write access to the "cgroup.procs" file of the
	  common ancestor of the source and destination cgroups.

	When delegating a sub-hierarchy, write access to this file
	should be granted along with the containing directory.

	In a threaded cgroup, reading this file fails with EOPNOTSUPP
	as all the processes belong to the thread root.  Writing is
	supported and moves every thread of the process to the cgroup.

  cgroup.threads
	A read-write new-line separated values file which exists on
	all cgroups.

	When read, it lists the TIDs of all threads which belong to
	the cgroup one-per-line.  The TIDs are not ordered and the
	same TID may show up more than once if the thread got moved to
	another cgroup and then back or the TID got recycled while
	reading.

	A TID can be written to migrate the thread associated with the
	TID to the cgroup.  The writer should match all of the
	following conditions.

	- It must have write access to the "cgroup.threads" file.

	- The cgroup that the thread is currently in must be in the
          same resource domain as the destination cgroup.

	- It must have write access to the "cgroup.procs" file of the
	  common ancestor of the source and destination cgroups.

	When delegating a sub-hierarchy, write access to this file
	should be granted along with the containing directory.

  cgroup.controllers
	A read-only space separated values file which exists on all
	cgroups.

	It shows space separated list of all controllers available to
	the cgroup.  The controllers are not ordered.

  cgroup.subtree_control
	A read-write space separated values file which exists on all
	cgroups.  Starts out empty.

	When read, it shows space separated list of the controllers
	which are enabled to control resource distribution from the
	cgroup to its children.

	Space separated list of controllers prefixed with '+' or '-'
	can be written to enable or disable controllers.  A controller
	name prefixed with '+' enables the controller and '-'
	disables.  If a controller appears more than once on the list,
	the last one is effective.  When multiple enable and disable
	operations are specified, either all succeed or all fail.

  cgroup.events
	A read-only flat-keyed file which exists on non-root cgroups.
	The following entries are defined.  Unless specified
	otherwise, a value change in this file generates a file
	modified event.

	  populated
		1 if the cgroup or its descendants contains any live
		processes; otherwise, 0.
	  frozen
		1 if the cgroup is frozen; otherwise, 0.

  cgroup.max.descendants
	A read-write single value files.  The default is "max".

	Maximum allowed number of descent cgroups.
	If the actual number of descendants is equal or larger,
	an attempt to create a new cgroup in the hierarchy will fail.

  cgroup.max.depth
	A read-write single value files.  The default is "max".

	Maximum allowed descent depth below the current cgroup.
	If the actual descent depth is equal or larger,
	an attempt to create a new child cgroup will fail.

  cgroup.stat
	A read-only flat-keyed file with the following entries:

	  nr_descendants
		Total number of visible descendant cgroups.

	  nr_dying_descendants
		Total number of dying descendant cgroups. A cgroup becomes
		dying after being deleted by a user. The cgroup will remain
		in dying state for some time undefined time (which can depend
		on system load) before being completely destroyed.

		A process can't enter a dying cgroup under any circumstances,
		a dying cgroup can't revive.

		A dying cgroup can consume system resources not exceeding
		limits, which were active at the moment of cgroup deletion.

	  nr_subsys_<cgroup_subsys>
		Total number of live cgroup subsystems (e.g memory
		cgroup) at and beneath the current cgroup.

	  nr_dying_subsys_<cgroup_subsys>
		Total number of dying cgroup subsystems (e.g. memory
		cgroup) at and beneath the current cgroup.

  cgroup.stat.local
	A read-only flat-keyed file which exists in non-root cgroups.
	The following entry is defined:

	  frozen_usec
		Cumulative time that this cgroup has spent between freezing and
		thawing, regardless of whether by self or ancestor groups.
		NB: (not) reaching "frozen" state is not accounted here.

		Using the following ASCII representation of a cgroup's freezer
		state, ::

			       1    _____
			frozen 0 __/     \__
			          ab    cd

		the duration being measured is the span between a and c.

  cgroup.freeze
	A read-write single value file which exists on non-root cgroups.
	Allowed values are "0" and "1". The default is "0".

	Writing "1" to the file causes freezing of the cgroup and all
	descendant cgroups. This means that all belonging processes will
	be stopped and will not run until the cgroup will be explicitly
	unfrozen. Freezing of the cgroup may take some time; when this action
	is completed, the "frozen" value in the cgroup.events control file
	will be updated to "1" and the corresponding notification will be
	issued.

	A cgroup can be frozen either by its own settings, or by settings
	of any ancestor cgroups. If any of ancestor cgroups is frozen, the
	cgroup will remain frozen.

	Processes in the frozen cgroup can be killed by a fatal signal.
	They also can enter and leave a frozen cgroup: either by an explicit
	move by a user, or if freezing of the cgroup races with fork().
	If a process is moved to a frozen cgroup, it stops. If a process is
	moved out of a frozen cgroup, it becomes running.

	Frozen status of a cgroup doesn't affect any cgroup tree operations:
	it's possible to delete a frozen (and empty) cgroup, as well as
	create new sub-cgroups.

  cgroup.kill
	A write-only single value file which exists in non-root cgroups.
	The only allowed value is "1".

	Writing "1" to the file causes the cgroup and all descendant cgroups to
	be killed. This means that all processes located in the affected cgroup
	tree will be killed via SIGKILL.

	Killing a cgroup tree will deal with concurrent forks appropriately and
	is protected against migrations.

	In a threaded cgroup, writing this file fails with EOPNOTSUPP as
	killing cgroups is a process directed operation, i.e. it affects
	the whole thread-group.

  cgroup.pressure
	A read-write single value file that allowed values are "0" and "1".
	The default is "1".

	Writing "0" to the file will disable the cgroup PSI accounting.
	Writing "1" to the file will re-enable the cgroup PSI accounting.

	This control attribute is not hierarchical, so disable or enable PSI
	accounting in a cgroup does not affect PSI accounting in descendants
	and doesn't need pass enablement via ancestors from root.

	The reason this control attribute exists is that PSI accounts stalls for
	each cgroup separately and aggregates it at each level of the hierarchy.
	This may cause non-negligible overhead for some workloads when under
	deep level of the hierarchy, in which case this control attribute can
	be used to disable PSI accounting in the non-leaf cgroups.

  irq.pressure
	A read-write nested-keyed file.

	Shows pressure stall information for IRQ/SOFTIRQ. See
	:ref:`Documentation/accounting/psi.rst <psi>` for details.

Controllers
===========

.. _cgroup-v2-cpu:

CPU
---

The "cpu" controllers regulates distribution of CPU cycles.  This
controller implements weight and absolute bandwidth limit models for
normal scheduling policy and absolute bandwidth allocation model for
realtime scheduling policy.

In all the above models, cycles distribution is defined only on a temporal
base and it does not account for the frequency at which tasks are executed.
The (optional) utilization clamping support allows to hint the schedutil
cpufreq governor about the minimum desired frequency which should always be
provided by a CPU, as well as the maximum desired frequency, which should not
be exceeded by a CPU.

WARNING: cgroup2 cpu controller doesn't yet support the (bandwidth) control of
realtime processes. For a kernel built with the CONFIG_RT_GROUP_SCHED option
enabled for group scheduling of realtime processes, the cpu controller can only
be enabled when all RT processes are in the root cgroup. Be aware that system
management software may already have placed RT processes into non-root cgroups
during the system boot process, and these processes may need to be moved to the
root cgroup before the cpu controller can be enabled with a
CONFIG_RT_GROUP_SCHED enabled kernel.

With CONFIG_RT_GROUP_SCHED disabled, this limitation does not apply and some of
the interface files either affect realtime processes or account for them. See
the following section for details. Only the cpu controller is affected by
CONFIG_RT_GROUP_SCHED. Other controllers can be used for the resource control of
realtime processes irrespective of CONFIG_RT_GROUP_SCHED.


CPU Interface Files
~~~~~~~~~~~~~~~~~~~

The interaction of a process with the cpu controller depends on its scheduling
policy and the underlying scheduler. From the point of view of the cpu controller,
processes can be categorized as follows:

* Processes under the fair-class scheduler
* Processes under a BPF scheduler with the ``cgroup_set_weight`` callback
* Everything else: ``SCHED_{FIFO,RR,DEADLINE}`` and processes under a BPF scheduler
  without the ``cgroup_set_weight`` callback

For details on when a process is under the fair-class scheduler or a BPF scheduler,
check out :ref:`Documentation/scheduler/sched-ext.rst <sched-ext>`.

For each of the following interface files, the above categories
will be referred to. All time durations are in microseconds.

  cpu.stat
	A read-only flat-keyed file.
	This file exists whether the controller is enabled or not.

	It always reports the following three stats, which account for all the
	processes in the cgroup:

	- usage_usec
	- user_usec
	- system_usec

	and the following five when the controller is enabled, which account for
	only the processes under the fair-class scheduler:

	- nr_periods
	- nr_throttled
	- throttled_usec
	- nr_bursts
	- burst_usec

  cpu.weight
	A read-write single value file which exists on non-root
	cgroups.  The default is "100".

	For non idle groups (cpu.idle = 0), the weight is in the
	range [1, 10000].

	If the cgroup has been configured to be SCHED_IDLE (cpu.idle = 1),
	then the weight will show as a 0.

	This file affects only processes under the fair-class scheduler and a BPF
	scheduler with the ``cgroup_set_weight`` callback depending on what the
	callback actually does.

  cpu.weight.nice
	A read-write single value file which exists on non-root
	cgroups.  The default is "0".

	The nice value is in the range [-20, 19].

	This interface file is an alternative interface for
	"cpu.weight" and allows reading and setting weight using the
	same values used by nice(2).  Because the range is smaller and
	granularity is coarser for the nice values, the read value is
	the closest approximation of the current weight.

	This file affects only processes under the fair-class scheduler and a BPF
	scheduler with the ``cgroup_set_weight`` callback depending on what the
	callback actually does.

  cpu.max
	A read-write two value file which exists on non-root cgroups.
	The default is "max 100000".

	The maximum bandwidth limit.  It's in the following format::

	  $MAX $PERIOD

	which indicates that the group may consume up to $MAX in each
	$PERIOD duration.  "max" for $MAX indicates no limit.  If only
	one number is written, $MAX is updated.

	This file affects only processes under the fair-class scheduler.

  cpu.max.burst
	A read-write single value file which exists on non-root
	cgroups.  The default is "0".

	The burst in the range [0, $MAX].

	This file affects only processes under the fair-class scheduler.

  cpu.pressure
	A read-write nested-keyed file.

	Shows pressure stall information for CPU. See
	:ref:`Documentation/accounting/psi.rst <psi>` for details.

	This file accounts for all the processes in the cgroup.

  cpu.uclamp.min
	A read-write single value file which exists on non-root cgroups.
	The default is "0", i.e. no utilization boosting.

	The requested minimum utilization (protection) as a percentage
	rational number, e.g. 12.34 for 12.34%.

	This interface allows reading and setting minimum utilization clamp
	values similar to the sched_setattr(2). This minimum utilization
	value is used to clamp the task specific minimum utilization clamp,
	including those of realtime processes.

	The requested minimum utilization (protection) is always capped by
	the current value for the maximum utilization (limit), i.e.
	`cpu.uclamp.max`.

	This file affects all the processes in the cgroup.

  cpu.uclamp.max
	A read-write single value file which exists on non-root cgroups.
	The default is "max". i.e. no utilization capping

	The requested maximum utilization (limit) as a percentage rational
	number, e.g. 98.76 for 98.76%.

	This interface allows reading and setting maximum utilization clamp
	values similar to the sched_setattr(2). This maximum utilization
	value is used to clamp the task specific maximum utilization clamp,
	including those of realtime processes.

	This file affects all the processes in the cgroup.

  cpu.idle
	A read-write single value file which exists on non-root cgroups.
	The default is 0.

	This is the cgroup analog of the per-task SCHED_IDLE sched policy.
	Setting this value to a 1 will make the scheduling policy of the
	cgroup SCHED_IDLE. The threads inside the cgroup will retain their
	own relative priorities, but the cgroup itself will be treated as
	very low priority relative to its peers.

	This file affects only processes under the fair-class scheduler.

Memory
------

The "memory" controller regulates distribution of memory.  Memory is
stateful and implements both limit and protection models.  Due to the
intertwining between memory usage and reclaim pressure and the
stateful nature of memory, the distribution model is relatively
complex.

While not completely water-tight, all major memory usages by a given
cgroup are tracked so that the total memory consumption can be
accounted and controlled to a reasonable extent.  Currently, the
following types of memory usages are tracked.

- Userland memory - page cache and anonymous memory.

- Kernel data structures such as dentries and inodes.

- TCP socket buffers.

The above list may expand in the future for better coverage.


Memory Interface Files
~~~~~~~~~~~~~~~~~~~~~~

All memory amounts are in bytes.  If a value which is not aligned to
PAGE_SIZE is written, the value may be rounded up to the closest
PAGE_SIZE multiple when read back.

  memory.current
	A read-only single value file which exists on non-root
	cgroups.

	The total amount of memory currently being used by the cgroup
	and its descendants.

  memory.min
	A read-write single value file which exists on non-root
	cgroups.  The default is "0".

	Hard memory protection.  If the memory usage of a cgroup
	is within its effective min boundary, the cgroup's memory
	won't be reclaimed under any conditions. If there is no
	unprotected reclaimable memory available, OOM killer
	is invoked. Above the effective min boundary (or
	effective low boundary if it is higher), pages are reclaimed
	proportionally to the overage, reducing reclaim pressure for
	smaller overages.

	Effective min boundary is limited by memory.min values of
	all ancestor cgroups. If there is memory.min overcommitment
	(child cgroup or cgroups are requiring more protected memory
	than parent will allow), then each child cgroup will get
	the part of parent's protection proportional to its
	actual memory usage below memory.min.

	Putting more memory than generally available under this
	protection is discouraged and may lead to constant OOMs.

	If a memory cgroup is not populated with processes,
	its memory.min is ignored.

  memory.low
	A read-write single value file which exists on non-root
	cgroups.  The default is "0".

	Best-effort memory protection.  If the memory usage of a
	cgroup is within its effective low boundary, the cgroup's
	memory won't be reclaimed unless there is no reclaimable
	memory available in unprotected cgroups.
	Above the effective low	boundary (or 
	effective min boundary if it is higher), pages are reclaimed
	proportionally to the overage, reducing reclaim pressure for
	smaller overages.

	Effective low boundary is limited by memory.low values of
	all ancestor cgroups. If there is memory.low overcommitment
	(child cgroup or cgroups are requiring more protected memory
	than parent will allow), then each child cgroup will get
	the part of parent's protection proportional to its
	actual memory usage below memory.low.

	Putting more memory than generally available under this
	protection is discouraged.

  memory.high
	A read-write single value file which exists on non-root
	cgroups.  The default is "max".

	Memory usage throttle limit.  If a cgroup's usage goes
	over the high boundary, the processes of the cgroup are
	throttled and put under heavy reclaim pressure.

	Going over the high limit never invokes the OOM killer and
	under extreme conditions the limit may be breached. The high
	limit should be used in scenarios where an external process
	monitors the limited cgroup to alleviate heavy reclaim
	pressure.

	If memory.high is opened with O_NONBLOCK then the synchronous
	reclaim is bypassed. This is useful for admin processes that
	need to dynamically adjust the job's memory limits without
	expending their own CPU resources on memory reclamation. The
	job will trigger the reclaim and/or get throttled on its
	next charge request.

	Please note that with O_NONBLOCK, there is a chance that the
	target memory cgroup may take indefinite amount of time to
	reduce usage below the limit due to delayed charge request or
	busy-hitting its memory to slow down reclaim.

  memory.max
	A read-write single value file which exists on non-root
	cgroups.  The default is "max".

	Memory usage hard limit.  This is the main mechanism to limit
	memory usage of a cgroup.  If a cgroup's memory usage reaches
	this limit and can't be reduced, the OOM killer is invoked in
	the cgroup. Under certain circumstances, the usage may go
	over the limit temporarily.

	In default configuration regular 0-order allocations always
	succeed unless OOM killer chooses current task as a victim.

	Some kinds of allocations don't invoke the OOM killer.
	Caller could retry them differently, return into userspace
	as -ENOMEM or silently ignore in cases like disk readahead.

	If memory.max is opened with O_NONBLOCK, then the synchronous
	reclaim and oom-kill are bypassed. This is useful for admin
	processes that need to dynamically adjust the job's memory limits
	without expending their own CPU resources on memory reclamation.
	The job will trigger the reclaim and/or oom-kill on its next
	charge request.

	Please note that with O_NONBLOCK, there is a chance that the
	target memory cgroup may take indefinite amount of time to
	reduce usage below the limit due to delayed charge request or
	busy-hitting its memory to slow down reclaim.

  memory.reclaim
	A write-only nested-keyed file which exists for all cgroups.

	This is a simple interface to trigger memory reclaim in the
	target cgroup.

	Example::

	  echo "1G" > memory.reclaim

	Please note that the kernel can over or under reclaim from
	the target cgroup. If less bytes are reclaimed than the
	specified amount, -EAGAIN is returned.

	Please note that the proactive reclaim (triggered by this
	interface) is not meant to indicate memory pressure on the
	memory cgroup. Therefore socket memory balancing triggered by
	the memory reclaim normally is not exercised in this case.
	This means that the networking layer will not adapt based on
	reclaim induced by memory.reclaim.

The following nested keys are defined.

	  ==========            ================================
	  swappiness            Swappiness value to reclaim with
	  ==========            ================================

	Specifying a swappiness value instructs the kernel to perform
	the reclaim with that swappiness value. Note that this has the
	same semantics as vm.swappiness applied to memcg reclaim with
	all the existing limitations and potential future extensions.

	The valid range for swappiness is [0-200, max], setting
	swappiness=max exclusively reclaims anonymous memory.

  memory.peak
	A read-write single value file which exists on non-root cgroups.

	The max memory usage recorded for the cgroup and its descendants since
	either the creation of the cgroup or the most recent reset for that FD.

	A write of any non-empty string to this file resets it to the
	current memory usage for subsequent reads through the same
	file descriptor.

  memory.oom.group
	A read-write single value file which exists on non-root
	cgroups.  The default value is "0".

	Determines whether the cgroup should be treated as
	an indivisible workload by the OOM killer. If set,
	all tasks belonging to the cgroup or to its descendants
	(if the memory cgroup is not a leaf cgroup) are killed
	together or not at all. This can be used to avoid
	partial kills to guarantee workload integrity.

	Tasks with the OOM protection (oom_score_adj set to -1000)
	are treated as an exception and are never killed.

	If the OOM killer is invoked in a cgroup, it's not going
	to kill any tasks outside of this cgroup, regardless
	memory.oom.group values of ancestor cgroups.

  memory.events
	A read-only flat-keyed file which exists on non-root cgroups.
	The following entries are defined.  Unless specified
	otherwise, a value change in this file generates a file
	modified event.

	Note that all fields in this file are hierarchical and the
	file modified event can be generated due to an event down the
	hierarchy. For the local events at the cgroup level see
	memory.events.local.

	  low
		The number of times the cgroup is reclaimed due to
		high memory pressure even though its usage is under
		the low boundary.  This usually indicates that the low
		boundary is over-committed.

	  high
		The number of times processes of the cgroup are
		throttled and routed to perform direct memory reclaim
		because the high memory boundary was exceeded.  For a
		cgroup whose memory usage is capped by the high limit
		rather than global memory pressure, this event's
		occurrences are expected.

	  max
		The number of times the cgroup's memory usage was
		about to go over the max boundary.  If direct reclaim
		fails to bring it down, the cgroup goes to OOM state.

	  oom
		The number of time the cgroup's memory usage was
		reached the limit and allocation was about to fail.

		This event is not raised if the OOM killer is not
		considered as an option, e.g. for failed high-order
		allocations or if caller asked to not retry attempts.

	  oom_kill
		The number of processes belonging to this cgroup
		killed by any kind of OOM killer.

          oom_group_kill
                The number of times a group OOM has occurred.

  memory.events.local
	Similar to memory.events but the fields in the file are local
	to the cgroup i.e. not hierarchical. The file modified event
	generated on this file reflects only the local events.

  memory.stat
	A read-only flat-keyed file which exists on non-root cgroups.

	This breaks down the cgroup's memory footprint into different
	types of memory, type-specific details, and other information
	on the state and past events of the memory management system.

	All memory amounts are in bytes.

	The entries are ordered to be human readable, and new entries
	can show up in the middle. Don't rely on items remaining in a
	fixed position; use the keys to look up specific values!

	If the entry has no per-node counter (or not show in the
	memory.numa_stat). We use 'npn' (non-per-node) as the tag
	to indicate that it will not show in the memory.numa_stat.

	  anon
		Amount of memory used in anonymous mappings such as
		brk(), sbrk(), and mmap(MAP_ANONYMOUS). Note that
		some kernel configurations might account complete larger
		allocations (e.g., THP) if only some, but not all the
		memory of such an allocation is mapped anymore.

	  file
		Amount of memory used to cache filesystem data,
		including tmpfs and shared memory.

	  kernel (npn)
		Amount of total kernel memory, including
		(kernel_stack, pagetables, percpu, vmalloc, slab) in
		addition to other kernel memory use cases.

	  kernel_stack
		Amount of memory allocated to kernel stacks.

	  pagetables
                Amount of memory allocated for page tables.

	  sec_pagetables
		Amount of memory allocated for secondary page tables,
		this currently includes KVM mmu allocations on x86
		and arm64 and IOMMU page tables.

	  percpu (npn)
		Amount of memory used for storing per-cpu kernel
		data structures.

	  sock (npn)
		Amount of memory used in network transmission buffers

	  vmalloc (npn)
		Amount of memory used for vmap backed memory.

	  shmem
		Amount of cached filesystem data that is swap-backed,
		such as tmpfs, shm segments, shared anonymous mmap()s

	  zswap
		Amount of memory consumed by the zswap compression backend.

	  zswapped
		Amount of application memory swapped out to zswap.

	  file_mapped
		Amount of cached filesystem data mapped with mmap(). Note
		that some kernel configurations might account complete
		larger allocations (e.g., THP) if only some, but not
		not all the memory of such an allocation is mapped.

	  file_dirty
		Amount of cached filesystem data that was modified but
		not yet written back to disk

	  file_writeback
		Amount of cached filesystem data that was modified and
		is currently being written back to disk

	  swapcached
		Amount of swap cached in memory. The swapcache is accounted
		against both memory and swap usage.

	  anon_thp
		Amount of memory used in anonymous mappings backed by
		transparent hugepages

	  file_thp
		Amount of cached filesystem data backed by transparent
		hugepages

	  shmem_thp
		Amount of shm, tmpfs, shared anonymous mmap()s backed by
		transparent hugepages

	  inactive_anon, active_anon, inactive_file, active_file, unevictable
		Amount of memory, swap-backed and filesystem-backed,
		on the internal memory management lists used by the
		page reclaim algorithm.

		As these represent internal list state (eg. shmem pages are on anon
		memory management lists), inactive_foo + active_foo may not be equal to
		the value for the foo counter, since the foo counter is type-based, not
		list-based.

	  slab_reclaimable
		Part of "slab" that might be reclaimed, such as
		dentries and inodes.

	  slab_unreclaimable
		Part of "slab" that cannot be reclaimed on memory
		pressure.

	  slab (npn)
		Amount of memory used for storing in-kernel data
		structures.

	  workingset_refault_anon
		Number of refaults of previously evicted anonymous pages.

	  workingset_refault_file
		Number of refaults of previously evicted file pages.

	  workingset_activate_anon
		Number of refaulted anonymous pages that were immediately
		activated.

	  workingset_activate_file
		Number of refaulted file pages that were immediately activated.

	  workingset_restore_anon
		Number of restored anonymous pages which have been detected as
		an active workingset before they got reclaimed.

	  workingset_restore_file
		Number of restored file pages which have been detected as an
		active workingset before they got reclaimed.

	  workingset_nodereclaim
		Number of times a shadow node has been reclaimed

	  pswpin (npn)
		Number of pages swapped into memory

	  pswpout (npn)
		Number of pages swapped out of memory

	  pgscan (npn)
		Amount of scanned pages (in an inactive LRU list)

	  pgsteal (npn)
		Amount of reclaimed pages

	  pgscan_kswapd (npn)
		Amount of scanned pages by kswapd (in an inactive LRU list)

	  pgscan_direct (npn)
		Amount of scanned pages directly  (in an inactive LRU list)

	  pgscan_khugepaged (npn)
		Amount of scanned pages by khugepaged  (in an inactive LRU list)

	  pgscan_proactive (npn)
		Amount of scanned pages proactively (in an inactive LRU list)

	  pgsteal_kswapd (npn)
		Amount of reclaimed pages by kswapd

	  pgsteal_direct (npn)
		Amount of reclaimed pages directly

	  pgsteal_khugepaged (npn)
		Amount of reclaimed pages by khugepaged

	  pgsteal_proactive (npn)
		Amount of reclaimed pages proactively

	  pgfault (npn)
		Total number of page faults incurred

	  pgmajfault (npn)
		Number of major page faults incurred

	  pgrefill (npn)
		Amount of scanned pages (in an active LRU list)

	  pgactivate (npn)
		Amount of pages moved to the active LRU list

	  pgdeactivate (npn)
		Amount of pages moved to the inactive LRU list

	  pglazyfree (npn)
		Amount of pages postponed to be freed under memory pressure

	  pglazyfreed (npn)
		Amount of reclaimed lazyfree pages

	  swpin_zero
		Number of pages swapped into memory and filled with zero, where I/O
		was optimized out because the page content was detected to be zero
		during swapout.

	  swpout_zero
		Number of zero-filled pages swapped out with I/O skipped due to the
		content being detected as zero.

	  zswpin
		Number of pages moved in to memory from zswap.

	  zswpout
		Number of pages moved out of memory to zswap.

	  zswpwb
		Number of pages written from zswap to swap.

	  thp_fault_alloc (npn)
		Number of transparent hugepages which were allocated to satisfy
		a page fault. This counter is not present when CONFIG_TRANSPARENT_HUGEPAGE
                is not set.

	  thp_collapse_alloc (npn)
		Number of transparent hugepages which were allocated to allow
		collapsing an existing range of pages. This counter is not
		present when CONFIG_TRANSPARENT_HUGEPAGE is not set.

	  thp_swpout (npn)
		Number of transparent hugepages which are swapout in one piece
		without splitting.

	  thp_swpout_fallback (npn)
		Number of transparent hugepages which were split before swapout.
		Usually because failed to allocate some continuous swap space
		for the huge page.

	  numa_pages_migrated (npn)
		Number of pages migrated by NUMA balancing.

	  numa_pte_updates (npn)
		Number of pages whose page table entries are modified by
		NUMA balancing to produce NUMA hinting faults on access.

	  numa_hint_faults (npn)
		Number of NUMA hinting faults.

	  pgdemote_kswapd
		Number of pages demoted by kswapd.

	  pgdemote_direct
		Number of pages demoted directly.

	  pgdemote_khugepaged
		Number of pages demoted by khugepaged.

	  pgdemote_proactive
		Number of pages demoted by proactively.

	  hugetlb
		Amount of memory used by hugetlb pages. This metric only shows
		up if hugetlb usage is accounted for in memory.current (i.e.
		cgroup is mounted with the memory_hugetlb_accounting option).

  memory.numa_stat
	A read-only nested-keyed file which exists on non-root cgroups.

	This breaks down the cgroup's memory footprint into different
	types of memory, type-specific details, and other information
	per node on the state of the memory management system.

	This is useful for providing visibility into the NUMA locality
	information within an memcg since the pages are allowed to be
	allocated from any physical node. One of the use case is evaluating
	application performance by combining this information with the
	application's CPU allocation.

	All memory amounts are in bytes.

	The output format of memory.numa_stat is::

	  type N0=<bytes in node 0> N1=<bytes in node 1> ...

	The entries are ordered to be human readable, and new entries
	can show up in the middle. Don't rely on items remaining in a
	fixed position; use the keys to look up specific values!

	The entries can refer to the memory.stat.

  memory.swap.current
	A read-only single value file which exists on non-root
	cgroups.

	The total amount of swap currently being used by the cgroup
	and its descendants.

  memory.swap.high
	A read-write single value file which exists on non-root
	cgroups.  The default is "max".

	Swap usage throttle limit.  If a cgroup's swap usage exceeds
	this limit, all its further allocations will be throttled to
	allow userspace to implement custom out-of-memory procedures.

	This limit marks a point of no return for the cgroup. It is NOT
	designed to manage the amount of swapping a workload does
	during regular operation. Compare to memory.swap.max, which
	prohibits swapping past a set amount, but lets the cgroup
	continue unimpeded as long as other memory can be reclaimed.

	Healthy workloads are not expected to reach this limit.

  memory.swap.peak
	A read-write single value file which exists on non-root cgroups.

	The max swap usage recorded for the cgroup and its descendants since
	the creation of the cgroup or the most recent reset for that FD.

	A write of any non-empty string to this file resets it to the
	current memory usage for subsequent reads through the same
	file descriptor.

  memory.swap.max
	A read-write single value file which exists on non-root
	cgroups.  The default is "max".

	Swap usage hard limit.  If a cgroup's swap usage reaches this
	limit, anonymous memory of the cgroup will not be swapped out.

  memory.swap.events
	A read-only flat-keyed file which exists on non-root cgroups.
	The following entries are defined.  Unless specified
	otherwise, a value change in this file generates a file
	modified event.

	  high
		The number of times the cgroup's swap usage was over
		the high threshold.

	  max
		The number of times the cgroup's swap usage was about
		to go over the max boundary and swap allocation
		failed.

	  fail
		The number of times swap allocation failed either
		because of running out of swap system-wide or max
		limit.

	When reduced under the current usage, the existing swap
	entries are reclaimed gradually and the swap usage may stay
	higher than the limit for an extended period of time.  This
	reduces the impact on the workload and memory management.

  memory.zswap.current
	A read-only single value file which exists on non-root
	cgroups.

	The total amount of memory consumed by the zswap compression
	backend.

  memory.zswap.max
	A read-write single value file which exists on non-root
	cgroups.  The default is "max".

	Zswap usage hard limit. If a cgroup's zswap pool reaches this
	limit, it will refuse to take any more stores before existing
	entries fault back in or are written out to disk.

  memory.zswap.writeback
	A read-write single value file. The default value is "1".
	Note that this setting is hierarchical, i.e. the writeback would be
	implicitly disabled for child cgroups if the upper hierarchy
	does so.

	When this is set to 0, all swapping attempts to swapping devices
	are disabled. This included both zswap writebacks, and swapping due
	to zswap store failures. If the zswap store failures are recurring
	(for e.g if the pages are incompressible), users can observe
	reclaim inefficiency after disabling writeback (because the same
	pages might be rejected again and again).

	Note that this is subtly different from setting memory.swap.max to
	0, as it still allows for pages to be written to the zswap pool.
	This setting has no effect if zswap is disabled, and swapping
	is allowed unless memory.swap.max is set to 0.

  memory.pressure
	A read-only nested-keyed file.

	Shows pressure stall information for memory. See
	:ref:`Documentation/accounting/psi.rst <psi>` for details.


Usage Guidelines
~~~~~~~~~~~~~~~~

"memory.high" is the main mechanism to control memory usage.
Over-committing on high limit (sum of high limits > available memory)
and letting global memory pressure to distribute memory according to
usage is a viable strategy.

Because breach of the high limit doesn't trigger the OOM killer but
throttles the offending cgroup, a management agent has ample
opportunities to monitor and take appropriate actions such as granting
more memory or terminating the workload.

Determining whether a cgroup has enough memory is not trivial as
memory usage doesn't indicate whether the workload can benefit from
more memory.  For example, a workload which writes data received from
network to a file can use all available memory but can also operate as
performant with a small amount of memory.  A measure of memory
pressure - how much the workload is being impacted due to lack of
memory - is necessary to determine whether a workload needs more
memory; unfortunately, memory pressure monitoring mechanism isn't
implemented yet.


Memory Ownership
~~~~~~~~~~~~~~~~

A memory area is charged to the cgroup which instantiated it and stays
charged to the cgroup until the area is released.  Migrating a process
to a different cgroup doesn't move the memory usages that it
instantiated while in the previous cgroup to the new cgroup.

A memory area may be used by processes belonging to different cgroups.
To which cgroup the area will be charged is in-deterministic; however,
over time, the memory area is likely to end up in a cgroup which has
enough memory allowance to avoid high reclaim pressure.

If a cgroup sweeps a considerable amount of memory which is expected
to be accessed repeatedly by other cgroups, it may make sense to use
POSIX_FADV_DONTNEED to relinquish the ownership of memory areas
belonging to the affected files to ensure correct memory ownership.


IO
--

The "io" controller regulates the distribution of IO resources.  This
controller implements both weight based and absolute bandwidth or IOPS
limit distribution; however, weight based distribution is available
only if cfq-iosched is in use and neither scheme is available for
blk-mq devices.


IO Interface Files
~~~~~~~~~~~~~~~~~~

  io.stat
	A read-only nested-keyed file.

	Lines are keyed by $MAJ:$MIN device numbers and not ordered.
	The following nested keys are defined.

	  ======	=====================
	  rbytes	Bytes read
	  wbytes	Bytes written
	  rios		Number of read IOs
	  wios		Number of write IOs
	  dbytes	Bytes discarded
	  dios		Number of discard IOs
	  ======	=====================

	An example read output follows::

	  8:16 rbytes=1459200 wbytes=314773504 rios=192 wios=353 dbytes=0 dios=0
	  8:0 rbytes=90430464 wbytes=299008000 rios=8950 wios=1252 dbytes=50331648 dios=3021

  io.cost.qos
	A read-write nested-keyed file which exists only on the root
	cgroup.

	This file configures the Quality of Service of the IO cost
	model based controller (CONFIG_BLK_CGROUP_IOCOST) which
	currently implements "io.weight" proportional control.  Lines
	are keyed by $MAJ:$MIN device numbers and not ordered.  The
	line for a given device is populated on the first write for
	the device on "io.cost.qos" or "io.cost.model".  The following
	nested keys are defined.

	  ======	=====================================
	  enable	Weight-based control enable
	  ctrl		"auto" or "user"
	  rpct		Read latency percentile    [0, 100]
	  rlat		Read latency threshold
	  wpct		Write latency percentile   [0, 100]
	  wlat		Write latency threshold
	  min		Minimum scaling percentage [1, 10000]
	  max		Maximum scaling percentage [1, 10000]
	  ======	=====================================

	The controller is disabled by default and can be enabled by
	setting "enable" to 1.  "rpct" and "wpct" parameters default
	to zero and the controller uses internal device saturation
	state to adjust the overall IO rate between "min" and "max".

	When a better control quality is needed, latency QoS
	parameters can be configured.  For example::

	  8:16 enable=1 ctrl=auto rpct=95.00 rlat=75000 wpct=95.00 wlat=150000 min=50.00 max=150.0

	shows that on sdb, the controller is enabled, will consider
	the device saturated if the 95th percentile of read completion
	latencies is above 75ms or write 150ms, and adjust the overall
	IO issue rate between 50% and 150% accordingly.

	The lower the saturation point, the better the latency QoS at
	the cost of aggregate bandwidth.  The narrower the allowed
	adjustment range between "min" and "max", the more conformant
	to the cost model the IO behavior.  Note that the IO issue
	base rate may be far off from 100% and setting "min" and "max"
	blindly can lead to a significant loss of device capacity or
	control quality.  "min" and "max" are useful for regulating
	devices which show wide temporary behavior changes - e.g. a
	ssd which accepts writes at the line speed for a while and
	then completely stalls for multiple seconds.

	When "ctrl" is "auto", the parameters are controlled by the
	kernel and may change automatically.  Setting "ctrl" to "user"
	or setting any of the percentile and latency parameters puts
	it into "user" mode and disables the automatic changes.  The
	automatic mode can be restored by setting "ctrl" to "auto".

  io.cost.model
	A read-write nested-keyed file which exists only on the root
	cgroup.

	This file configures the cost model of the IO cost model based
	controller (CONFIG_BLK_CGROUP_IOCOST) which currently
	implements "io.weight" proportional control.  Lines are keyed
	by $MAJ:$MIN device numbers and not ordered.  The line for a
	given device is populated on the first write for the device on
	"io.cost.qos" or "io.cost.model".  The following nested keys
	are defined.

	  =====		================================
	  ctrl		"auto" or "user"
	  model		The cost model in use - "linear"
	  =====		================================

	When "ctrl" is "auto", the kernel may change all parameters
	dynamically.  When "ctrl" is set to "user" or any other
	parameters are written to, "ctrl" become "user" and the
	automatic changes are disabled.

	When "model" is "linear", the following model parameters are
	defined.

	  =============	========================================
	  [r|w]bps	The maximum sequential IO throughput
	  [r|w]seqiops	The maximum 4k sequential IOs per second
	  [r|w]randiops	The maximum 4k random IOs per second
	  =============	========================================

	From the above, the builtin linear model determines the base
	costs of a sequential and random IO and the cost coefficient
	for the IO size.  While simple, this model can cover most
	common device classes acceptably.

	The IO cost model isn't expected to be accurate in absolute
	sense and is scaled to the device behavior dynamically.

	If needed, tools/cgroup/iocost_coef_gen.py can be used to
	generate device-specific coefficients.

  io.weight
	A read-write flat-keyed file which exists on non-root cgroups.
	The default is "default 100".

	The first line is the default weight applied to devices
	without specific override.  The rest are overrides keyed by
	$MAJ:$MIN device numbers and not ordered.  The weights are in
	the range [1, 10000] and specifies the relative amount IO time
	the cgroup can use in relation to its siblings.

	The default weight can be updated by writing either "default
	$WEIGHT" or simply "$WEIGHT".  Overrides can be set by writing
	"$MAJ:$MIN $WEIGHT" and unset by writing "$MAJ:$MIN default".

	An example read output follows::

	  default 100
	  8:16 200
	  8:0 50

  io.max
	A read-write nested-keyed file which exists on non-root
	cgroups.

	BPS and IOPS based IO limit.  Lines are keyed by $MAJ:$MIN
	device numbers and not ordered.  The following nested keys are
	defined.

	  =====		==================================
	  rbps		Max read bytes per second
	  wbps		Max write bytes per second
	  riops		Max read IO operations per second
	  wiops		Max write IO operations per second
	  =====		==================================

	When writing, any number of nested key-value pairs can be
	specified in any order.  "max" can be specified as the value
	to remove a specific limit.  If the same key is specified
	multiple times, the outcome is undefined.

	BPS and IOPS are measured in each IO direction and IOs are
	delayed if limit is reached.  Temporary bursts are allowed.

	Setting read limit at 2M BPS and write at 120 IOPS for 8:16::

	  echo "8:16 rbps=2097152 wiops=120" > io.max

	Reading returns the following::

	  8:16 rbps=2097152 wbps=max riops=max wiops=120

	Write IOPS limit can be removed by writing the following::

	  echo "8:16 wiops=max" > io.max

	Reading now returns the following::

	  8:16 rbps=2097152 wbps=max riops=max wiops=max

  io.pressure
	A read-only nested-keyed file.

	Shows pressure stall information for IO. See
	:ref:`Documentation/accounting/psi.rst <psi>` for details.


Writeback
~~~~~~~~~

Page cache is dirtied through buffered writes and shared mmaps and
written asynchronously to the backing filesystem by the writeback
mechanism.  Writeback sits between the memory and IO domains and
regulates the proportion of dirty memory by balancing dirtying and
write IOs.

The io controller, in conjunction with the memory controller,
implements control of page cache writeback IOs.  The memory controller
defines the memory domain that dirty memory ratio is calculated and
maintained for and the io controller defines the io domain which
writes out dirty pages for the memory domain.  Both system-wide and
per-cgroup dirty memory states are examined and the more restrictive
of the two is enforced.

cgroup writeback requires explicit support from the underlying
filesystem.  Currently, cgroup writeback is implemented on ext2, ext4,
btrfs, f2fs, and xfs.  On other filesystems, all writeback IOs are 
attributed to the root cgroup.

There are inherent differences in memory and writeback management
which affects how cgroup ownership is tracked.  Memory is tracked per
page while writeback per inode.  For the purpose of writeback, an
inode is assigned to a cgroup and all IO requests to write dirty pages
from the inode are attributed to that cgroup.

As cgroup ownership for memory is tracked per page, there can be pages
which are associated with different cgroups than the one the inode is
associated with.  These are called foreign pages.  The writeback
constantly keeps track of foreign pages and, if a particular foreign
cgroup becomes the majority over a certain period of time, switches
the ownership of the inode to that cgroup.

While this model is enough for most use cases where a given inode is
mostly dirtied by a single cgroup even when the main writing cgroup
changes over time, use cases where multiple cgroups write to a single
inode simultaneously are not supported well.  In such circumstances, a
significant portion of IOs are likely to be attributed incorrectly.
As memory controller assigns page ownership on the first use and
doesn't update it until the page is released, even if writeback
strictly follows page ownership, multiple cgroups dirtying overlapping
areas wouldn't work as expected.  It's recommended to avoid such usage
patterns.

The sysctl knobs which affect writeback behavior are applied to cgroup
writeback as follows.

  vm.dirty_background_ratio, vm.dirty_ratio
	These ratios apply the same to cgroup writeback with the
	amount of available memory capped by limits imposed by the
	memory controller and system-wide clean memory.

  vm.dirty_background_bytes, vm.dirty_bytes
	For cgroup writeback, this is calculated into ratio against
	total available memory and applied the same way as
	vm.dirty[_background]_ratio.


IO Latency
~~~~~~~~~~

This is a cgroup v2 controller for IO workload protection.  You provide a group
with a latency target, and if the average latency exceeds that target the
controller will throttle any peers that have a lower latency target than the
protected workload.

The limits are only applied at the peer level in the hierarchy.  This means that
in the diagram below, only groups A, B, and C will influence each other, and
groups D and F will influence each other.  Group G will influence nobody::

			[root]
		/	   |		\
		A	   B		C
	       /  \        |
	      D    F	   G


So the ideal way to configure this is to set io.latency in groups A, B, and C.
Generally you do not want to set a value lower than the latency your device
supports.  Experiment to find the value that works best for your workload.
Start at higher than the expected latency for your device and watch the
avg_lat value in io.stat for your workload group to get an idea of the
latency you see during normal operation.  Use the avg_lat value as a basis for
your real setting, setting at 10-15% higher than the value in io.stat.

How IO Latency Throttling Works
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

io.latency is work conserving; so as long as everybody is meeting their latency
target the controller doesn't do anything.  Once a group starts missing its
target it begins throttling any peer group that has a higher target than itself.
This throttling takes 2 forms:

- Queue depth throttling.  This is the number of outstanding IO's a group is
  allowed to have.  We will clamp down relatively quickly, starting at no limit
  and going all the way down to 1 IO at a time.

- Artificial delay induction.  There are certain types of IO that cannot be
  throttled without possibly adversely affecting higher priority groups.  This
  includes swapping and metadata IO.  These types of IO are allowed to occur
  normally, however they are "charged" to the originating group.  If the
  originating group is being throttled you will see the use_delay and delay
  fields in io.stat increase.  The delay value is how many microseconds that are
  being added to any process that runs in this group.  Because this number can
  grow quite large if there is a lot of swapping or metadata IO occurring we
  limit the individual delay events to 1 second at a time.

Once the victimized group starts meeting its latency target again it will start
unthrottling any peer groups that were throttled previously.  If the victimized
group simply stops doing IO the global counter will unthrottle appropriately.

IO Latency Interface Files
~~~~~~~~~~~~~~~~~~~~~~~~~~

  io.latency
	This takes a similar format as the other controllers.

		"MAJOR:MINOR target=<target time in microseconds>"

  io.stat
	If the controller is enabled you will see extra stats in io.stat in
	addition to the normal ones.

	  depth
		This is the current queue depth for the group.

	  avg_lat
		This is an exponential moving average with a decay rate of 1/exp
		bound by the sampling interval.  The decay rate interval can be
		calculated by multiplying the win value in io.stat by the
		corresponding number of samples based on the win value.

	  win
		The sampling window size in milliseconds.  This is the minimum
		duration of time between evaluation events.  Windows only elapse
		with IO activity.  Idle periods extend the most recent window.

IO Priority
~~~~~~~~~~~

A single attribute controls the behavior of the I/O priority cgroup policy,
namely the io.prio.class attribute. The following values are accepted for
that attribute:

  no-change
	Do not modify the I/O priority class.

  promote-to-rt
	For requests that have a non-RT I/O priority class, change it into RT.
	Also change the priority level of these requests to 4. Do not modify
	the I/O priority of requests that have priority class RT.

  restrict-to-be
	For requests that do not have an I/O priority class or that have I/O
	priority class RT, change it into BE. Also change the priority level
	of these requests to 0. Do not modify the I/O priority class of
	requests that have priority class IDLE.

  idle
	Change the I/O priority class of all requests into IDLE, the lowest
	I/O priority class.

  none-to-rt
	Deprecated. Just an alias for promote-to-rt.

The following numerical values are associated with the I/O priority policies:

+----------------+---+
| no-change      | 0 |
+----------------+---+
| promote-to-rt  | 1 |
+----------------+---+
| restrict-to-be | 2 |
+----------------+---+
| idle           | 3 |
+----------------+---+

The numerical value that corresponds to each I/O priority class is as follows:

+-------------------------------+---+
| IOPRIO_CLASS_NONE             | 0 |
+-------------------------------+---+
| IOPRIO_CLASS_RT (real-time)   | 1 |
+-------------------------------+---+
| IOPRIO_CLASS_BE (best effort) | 2 |
+-------------------------------+---+
| IOPRIO_CLASS_IDLE             | 3 |
+-------------------------------+---+

The algorithm to set the I/O priority class for a request is as follows:

- If I/O priority class policy is promote-to-rt, change the request I/O
  priority class to IOPRIO_CLASS_RT and change the request I/O priority
  level to 4.
- If I/O priority class policy is not promote-to-rt, translate the I/O priority
  class policy into a number, then change the request I/O priority class
  into the maximum of the I/O priority class policy number and the numerical
  I/O priority class.

PID
---

The process number controller is used to allow a cgroup to stop any
new tasks from being fork()'d or clone()'d after a specified limit is
reached.

The number of tasks in a cgroup can be exhausted in ways which other
controllers cannot prevent, thus warranting its own controller.  For
example, a fork bomb is likely to exhaust the number of tasks before
hitting memory restrictions.

Note that PIDs used in this controller refer to TIDs, process IDs as
used by the kernel.


PID Interface Files
~~~~~~~~~~~~~~~~~~~

  pids.max
	A read-write single value file which exists on non-root
	cgroups.  The default is "max".

	Hard limit of number of processes.

  pids.current
	A read-only single value file which exists on non-root cgroups.

	The number of processes currently in the cgroup and its
	descendants.

  pids.peak
	A read-only single value file which exists on non-root cgroups.

	The maximum value that the number of processes in the cgroup and its
	descendants has ever reached.

  pids.events
	A read-only flat-keyed file which exists on non-root cgroups. Unless
	specified otherwise, a value change in this file generates a file
	modified event. The following entries are defined.

	  max
		The number of times the cgroup's total number of processes hit the pids.max
		limit (see also pids_localevents).

  pids.events.local
	Similar to pids.events but the fields in the file are local
	to the cgroup i.e. not hierarchical. The file modified event
	generated on this file reflects only the local events.

Organisational operations are not blocked by cgroup policies, so it is
possible to have pids.current > pids.max.  This can be done by either
setting the limit to be smaller than pids.current, or attaching enough
processes to the cgroup such that pids.current is larger than
pids.max.  However, it is not possible to violate a cgroup PID policy
through fork() or clone(). These will return -EAGAIN if the creation
of a new process would cause a cgroup policy to be violated.


Cpuset
------

The "cpuset" controller provides a mechanism for constraining
the CPU and memory node placement of tasks to only the resources
specified in the cpuset interface files in a task's current cgroup.
This is especially valuable on large NUMA systems where placing jobs
on properly sized subsets of the systems with careful processor and
memory placement to reduce cross-node memory access and contention
can improve overall system performance.

The "cpuset" controller is hierarchical.  That means the controller
cannot use CPUs or memory nodes not allowed in its parent.


Cpuset Interface Files
~~~~~~~~~~~~~~~~~~~~~~

  cpuset.cpus
	A read-write multiple values file which exists on non-root
	cpuset-enabled cgroups.

	It lists the requested CPUs to be used by tasks within this
	cgroup.  The actual list of CPUs to be granted, however, is
	subjected to constraints imposed by its parent and can differ
	from the requested CPUs.

	The CPU numbers are comma-separated numbers or ranges.
	For example::

	  # cat cpuset.cpus
	  0-4,6,8-10

	An empty value indicates that the cgroup is using the same
	setting as the nearest cgroup ancestor with a non-empty
	"cpuset.cpus" or all the available CPUs if none is found.

	The value of "cpuset.cpus" stays constant until the next update
	and won't be affected by any CPU hotplug events.

  cpuset.cpus.effective
	A read-only multiple values file which exists on all
	cpuset-enabled cgroups.

	It lists the onlined CPUs that are actually granted to this
	cgroup by its parent.  These CPUs are allowed to be used by
	tasks within the current cgroup.

	If "cpuset.cpus" is empty, the "cpuset.cpus.effective" file shows
	all the CPUs from the parent cgroup that can be available to
	be used by this cgroup.  Otherwise, it should be a subset of
	"cpuset.cpus" unless none of the CPUs listed in "cpuset.cpus"
	can be granted.  In this case, it will be treated just like an
	empty "cpuset.cpus".

	Its value will be affected by CPU hotplug events.

  cpuset.mems
	A read-write multiple values file which exists on non-root
	cpuset-enabled cgroups.

	It lists the requested memory nodes to be used by tasks within
	this cgroup.  The actual list of memory nodes granted, however,
	is subjected to constraints imposed by its parent and can differ
	from the requested memory nodes.

	The memory node numbers are comma-separated numbers or ranges.
	For example::

	  # cat cpuset.mems
	  0-1,3

	An empty value indicates that the cgroup is using the same
	setting as the nearest cgroup ancestor with a non-empty
	"cpuset.mems" or all the available memory nodes if none
	is found.

	The value of "cpuset.mems" stays constant until the next update
	and won't be affected by any memory nodes hotplug events.

	Setting a non-empty value to "cpuset.mems" causes memory of
	tasks within the cgroup to be migrated to the designated nodes if
	they are currently using memory outside of the designated nodes.

	There is a cost for this memory migration.  The migration
	may not be complete and some memory pages may be left behind.
	So it is recommended that "cpuset.mems" should be set properly
	before spawning new tasks into the cpuset.  Even if there is
	a need to change "cpuset.mems" with active tasks, it shouldn't
	be done frequently.

  cpuset.mems.effective
	A read-only multiple values file which exists on all
	cpuset-enabled cgroups.

	It lists the onlined memory nodes that are actually granted to
	this cgroup by its parent. These memory nodes are allowed to
	be used by tasks within the current cgroup.

	If "cpuset.mems" is empty, it shows all the memory nodes from the
	parent cgroup that will be available to be used by this cgroup.
	Otherwise, it should be a subset of "cpuset.mems" unless none of
	the memory nodes listed in "cpuset.mems" can be granted.  In this
	case, it will be treated just like an empty "cpuset.mems".

	Its value will be affected by memory nodes hotplug events.

  cpuset.cpus.exclusive
	A read-write multiple values file which exists on non-root
	cpuset-enabled cgroups.

	It lists all the exclusive CPUs that are allowed to be used
	to create a new cpuset partition.  Its value is not used
	unless the cgroup becomes a valid partition root.  See the
	"cpuset.cpus.partition" section below for a description of what
	a cpuset partition is.

	When the cgroup becomes a partition root, the actual exclusive
	CPUs that are allocated to that partition are listed in
	"cpuset.cpus.exclusive.effective" which may be different
	from "cpuset.cpus.exclusive".  If "cpuset.cpus.exclusive"
	has previously been set, "cpuset.cpus.exclusive.effective"
	is always a subset of it.

	Users can manually set it to a value that is different from
	"cpuset.cpus".	One constraint in setting it is that the list of
	CPUs must be exclusive with respect to "cpuset.cpus.exclusive"
	and "cpuset.cpus.exclusive.effective" of its siblings.	Another
	constraint is that it cannot be a superset of "cpuset.cpus"
	of its sibling in order to leave at least one CPU available to
	that sibling when the exclusive CPUs are taken away.

	For a parent cgroup, any one of its exclusive CPUs can only
	be distributed to at most one of its child cgroups.  Having an
	exclusive CPU appearing in two or more of its child cgroups is
	not allowed (the exclusivity rule).  A value that violates the
	exclusivity rule will be rejected with a write error.

	The root cgroup is a partition root and all its available CPUs
	are in its exclusive CPU set.

  cpuset.cpus.exclusive.effective
	A read-only multiple values file which exists on all non-root
	cpuset-enabled cgroups.

	This file shows the effective set of exclusive CPUs that
	can be used to create a partition root.  The content
	of this file will always be a subset of its parent's
	"cpuset.cpus.exclusive.effective" if its parent is not the root
	cgroup.  It will also be a subset of "cpuset.cpus.exclusive"
	if it is set.  If "cpuset.cpus.exclusive" is not set, it is
	treated to have an implicit value of "cpuset.cpus" in the
	formation of local partition.

  cpuset.cpus.isolated
	A read-only and root cgroup only multiple values file.

	This file shows the set of all isolated CPUs used in existing
	isolated partitions. It will be empty if no isolated partition
	is created.

  cpuset.cpus.partition
	A read-write single value file which exists on non-root
	cpuset-enabled cgroups.  This flag is owned by the parent cgroup
	and is not delegatable.

	It accepts only the following input values when written to.

	  ==========	=====================================
	  "member"	Non-root member of a partition
	  "root"	Partition root
	  "isolated"	Partition root without load balancing
	  ==========	=====================================

	A cpuset partition is a collection of cpuset-enabled cgroups with
	a partition root at the top of the hierarchy and its descendants
	except those that are separate partition roots themselves and
	their descendants.  A partition has exclusive access to the
	set of exclusive CPUs allocated to it.	Other cgroups outside
	of that partition cannot use any CPUs in that set.

	There are two types of partitions - local and remote.  A local
	partition is one whose parent cgroup is also a valid partition
	root.  A remote partition is one whose parent cgroup is not a
	valid partition root itself.  Writing to "cpuset.cpus.exclusive"
	is optional for the creation of a local partition as its
	"cpuset.cpus.exclusive" file will assume an implicit value that
	is the same as "cpuset.cpus" if it is not set.	Writing the
	proper "cpuset.cpus.exclusive" values down the cgroup hierarchy
	before the target partition root is mandatory for the creation
	of a remote partition.

	Currently, a remote partition cannot be created under a local
	partition.  All the ancestors of a remote partition root except
	the root cgroup cannot be a partition root.

	The root cgroup is always a partition root and its state cannot
	be changed.  All other non-root cgroups start out as "member".

	When set to "root", the current cgroup is the root of a new
	partition or scheduling domain.  The set of exclusive CPUs is
	determined by the value of its "cpuset.cpus.exclusive.effective".

	When set to "isolated", the CPUs in that partition will be in
	an isolated state without any load balancing from the scheduler
	and excluded from the unbound workqueues.  Tasks placed in such
	a partition with multiple CPUs should be carefully distributed
	and bound to each of the individual CPUs for optimal performance.

	A partition root ("root" or "isolated") can be in one of the
	two possible states - valid or invalid.  An invalid partition
	root is in a degraded state where some state information may
	be retained, but behaves more like a "member".

	All possible state transitions among "member", "root" and
	"isolated" are allowed.

	On read, the "cpuset.cpus.partition" file can show the following
	values.

	  =============================	=====================================
	  "member"			Non-root member of a partition
	  "root"			Partition root
	  "isolated"			Partition root without load balancing
	  "root invalid (<reason>)"	Invalid partition root
	  "isolated invalid (<reason>)"	Invalid isolated partition root
	  =============================	=====================================

	In the case of an invalid partition root, a descriptive string on
	why the partition is invalid is included within parentheses.

	For a local partition root to be valid, the following conditions
	must be met.

	1) The parent cgroup is a valid partition root.
	2) The "cpuset.cpus.exclusive.effective" file cannot be empty,
	   though it may contain offline CPUs.
	3) The "cpuset.cpus.effective" cannot be empty unless there is
	   no task associated with this partition.

	For a remote partition root to be valid, all the above conditions
	except the first one must be met.

	External events like hotplug or changes to "cpuset.cpus" or
	"cpuset.cpus.exclusive" can cause a valid partition root to
	become invalid and vice versa.	Note that a task cannot be
	moved to a cgroup with empty "cpuset.cpus.effective".

	A valid non-root parent partition may distribute out all its CPUs
	to its child local partitions when there is no task associated
	with it.

	Care must be taken to change a valid partition root to "member"
	as all its child local partitions, if present, will become
	invalid causing disruption to tasks running in those child
	partitions. These inactivated partitions could be recovered if
	their parent is switched back to a partition root with a proper
	value in "cpuset.cpus" or "cpuset.cpus.exclusive".

	Poll and inotify events are triggered whenever the state of
	"cpuset.cpus.partition" changes.  That includes changes caused
	by write to "cpuset.cpus.partition", cpu hotplug or other
	changes that modify the validity status of the partition.
	This will allow user space agents to monitor unexpected changes
	to "cpuset.cpus.partition" without the need to do continuous
	polling.

	A user can pre-configure certain CPUs to an isolated state
	with load balancing disabled at boot time with the "isolcpus"
	kernel boot command line option.  If those CPUs are to be put
	into a partition, they have to be used in an isolated partition.


Device controller
-----------------

Device controller manages access to device files. It includes both
creation of new device files (using mknod), and access to the
existing device files.

Cgroup v2 device controller has no interface files and is implemented
on top of cgroup BPF. To control access to device files, a user may
create bpf programs of type BPF_PROG_TYPE_CGROUP_DEVICE and attach
them to cgroups with BPF_CGROUP_DEVICE flag. On an attempt to access a
device file, corresponding BPF programs will be executed, and depending
on the return value the attempt will succeed or fail with -EPERM.

A BPF_PROG_TYPE_CGROUP_DEVICE program takes a pointer to the
bpf_cgroup_dev_ctx structure, which describes the device access attempt:
access type (mknod/read/write) and device (type, major and minor numbers).
If the program returns 0, the attempt fails with -EPERM, otherwise it
succeeds.

An example of BPF_PROG_TYPE_CGROUP_DEVICE program may be found in
tools/testing/selftests/bpf/progs/dev_cgroup.c in the kernel source tree.


RDMA
----

The "rdma" controller regulates the distribution and accounting of
RDMA resources.

RDMA Interface Files
~~~~~~~~~~~~~~~~~~~~

  rdma.max
	A readwrite nested-keyed file that exists for all the cgroups
	except root that describes current configured resource limit
	for a RDMA/IB device.

	Lines are keyed by device name and are not ordered.
	Each line contains space separated resource name and its configured
	limit that can be distributed.

	The following nested keys are defined.

	  ==========	=============================
	  hca_handle	Maximum number of HCA Handles
	  hca_object 	Maximum number of HCA Objects
	  ==========	=============================

	An example for mlx4 and ocrdma device follows::

	  mlx4_0 hca_handle=2 hca_object=2000
	  ocrdma1 hca_handle=3 hca_object=max

  rdma.current
	A read-only file that describes current resource usage.
	It exists for all the cgroup except root.

	An example for mlx4 and ocrdma device follows::

	  mlx4_0 hca_handle=1 hca_object=20
	  ocrdma1 hca_handle=1 hca_object=23

DMEM
----

The "dmem" controller regulates the distribution and accounting of
device memory regions. Because each memory region may have its own page size,
which does not have to be equal to the system page size, the units are always bytes.

DMEM Interface Files
~~~~~~~~~~~~~~~~~~~~

  dmem.max, dmem.min, dmem.low
	A readwrite nested-keyed file that exists for all the cgroups
	except root that describes current configured resource limit
	for a region.

	An example for xe follows::

	  drm/0000:03:00.0/vram0 1073741824
	  drm/0000:03:00.0/stolen max

	The semantics are the same as for the memory cgroup controller, and are
	calculated in the same way.

  dmem.capacity
	A read-only file that describes maximum region capacity.
	It only exists on the root cgroup. Not all memory can be
	allocated by cgroups, as the kernel reserves some for
	internal use.

	An example for xe follows::

	  drm/0000:03:00.0/vram0 8514437120
	  drm/0000:03:00.0/stolen 67108864

  dmem.current
	A read-only file that describes current resource usage.
	It exists for all the cgroup except root.

	An example for xe follows::

	  drm/0000:03:00.0/vram0 12550144
	  drm/0000:03:00.0/stolen 8650752

HugeTLB
-------

The HugeTLB controller allows to limit the HugeTLB usage per control group and
enforces the controller limit during page fault.

HugeTLB Interface Files
~~~~~~~~~~~~~~~~~~~~~~~

  hugetlb.<hugepagesize>.current
	Show current usage for "hugepagesize" hugetlb.  It exists for all
	the cgroup except root.

  hugetlb.<hugepagesize>.max
	Set/show the hard limit of "hugepagesize" hugetlb usage.
	The default value is "max".  It exists for all the cgroup except root.

  hugetlb.<hugepagesize>.events
	A read-only flat-keyed file which exists on non-root cgroups.

	  max
		The number of allocation failure due to HugeTLB limit

  hugetlb.<hugepagesize>.events.local
	Similar to hugetlb.<hugepagesize>.events but the fields in the file
	are local to the cgroup i.e. not hierarchical. The file modified event
	generated on this file reflects only the local events.

  hugetlb.<hugepagesize>.numa_stat
	Similar to memory.numa_stat, it shows the numa information of the
        hugetlb pages of <hugepagesize> in this cgroup.  Only active in
        use hugetlb pages are included.  The per-node values are in bytes.

Misc
----

The Miscellaneous cgroup provides the resource limiting and tracking
mechanism for the scalar resources which cannot be abstracted like the other
cgroup resources. Controller is enabled by the CONFIG_CGROUP_MISC config
option.

A resource can be added to the controller via enum misc_res_type{} in the
include/linux/misc_cgroup.h file and the corresponding name via misc_res_name[]
in the kernel/cgroup/misc.c file. Provider of the resource must set its
capacity prior to using the resource by calling misc_cg_set_capacity().

Once a capacity is set then the resource usage can be updated using charge and
uncharge APIs. All of the APIs to interact with misc controller are in
include/linux/misc_cgroup.h.

Misc Interface Files
~~~~~~~~~~~~~~~~~~~~

Miscellaneous controller provides 3 interface files. If two misc resources (res_a and res_b) are registered then:

  misc.capacity
        A read-only flat-keyed file shown only in the root cgroup.  It shows
        miscellaneous scalar resources available on the platform along with
        their quantities::

	  $ cat misc.capacity
	  res_a 50
	  res_b 10

  misc.current
        A read-only flat-keyed file shown in the all cgroups.  It shows
        the current usage of the resources in the cgroup and its children.::

	  $ cat misc.current
	  res_a 3
	  res_b 0

  misc.peak
        A read-only flat-keyed file shown in all cgroups.  It shows the
        historical maximum usage of the resources in the cgroup and its
        children.::

	  $ cat misc.peak
	  res_a 10
	  res_b 8

  misc.max
        A read-write flat-keyed file shown in the non root cgroups. Allowed
        maximum usage of the resources in the cgroup and its children.::

	  $ cat misc.max
	  res_a max
	  res_b 4

	Limit can be set by::

	  # echo res_a 1 > misc.max

	Limit can be set to max by::

	  # echo res_a max > misc.max

        Limits can be set higher than the capacity value in the misc.capacity
        file.

  misc.events
	A read-only flat-keyed file which exists on non-root cgroups. The
	following entries are defined. Unless specified otherwise, a value
	change in this file generates a file modified event. All fields in
	this file are hierarchical.

	  max
		The number of times the cgroup's resource usage was
		about to go over the max boundary.

  misc.events.local
        Similar to misc.events but the fields in the file are local to the
        cgroup i.e. not hierarchical. The file modified event generated on
        this file reflects only the local events.

Migration and Ownership
~~~~~~~~~~~~~~~~~~~~~~~

A miscellaneous scalar resource is charged to the cgroup in which it is used
first, and stays charged to that cgroup until that resource is freed. Migrating
a process to a different cgroup does not move the charge to the destination
cgroup where the process has moved.

Others
------

perf_event
~~~~~~~~~~

perf_event controller, if not mounted on a legacy hierarchy, is
automatically enabled on the v2 hierarchy so that perf events can
always be filtered by cgroup v2 path.  The controller can still be
moved to a legacy hierarchy after v2 hierarchy is populated.


Non-normative information
-------------------------

This section contains information that isn't considered to be a part of
the stable kernel API and so is subject to change.


CPU controller root cgroup process behaviour
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

When distributing CPU cycles in the root cgroup each thread in this
cgroup is treated as if it was hosted in a separate child cgroup of the
root cgroup. This child cgroup weight is dependent on its thread nice
level.

For details of this mapping see sched_prio_to_weight array in
kernel/sched/core.c file (values from this array should be scaled
appropriately so the neutral - nice 0 - value is 100 instead of 1024).


IO controller root cgroup process behaviour
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Root cgroup processes are hosted in an implicit leaf child node.
When distributing IO resources this implicit child node is taken into
account as if it was a normal child cgroup of the root cgroup with a
weight value of 200.


Namespace
=========

Basics
------

cgroup namespace provides a mechanism to virtualize the view of the
"/proc/$PID/cgroup" file and cgroup mounts.  The CLONE_NEWCGROUP clone
flag can be used with clone(2) and unshare(2) to create a new cgroup
namespace.  The process running inside the cgroup namespace will have
its "/proc/$PID/cgroup" output restricted to cgroupns root.  The
cgroupns root is the cgroup of the process at the time of creation of
the cgroup namespace.

Without cgroup namespace, the "/proc/$PID/cgroup" file shows the
complete path of the cgroup of a process.  In a container setup where
a set of cgroups and namespaces are intended to isolate processes the
"/proc/$PID/cgroup" file may leak potential system level information
to the isolated processes.  For example::

  # cat /proc/self/cgroup
  0::/batchjobs/container_id1

The path '/batchjobs/container_id1' can be considered as system-data
and undesirable to expose to the isolated processes.  cgroup namespace
can be used to restrict visibility of this path.  For example, before
creating a cgroup namespace, one would see::

  # ls -l /proc/self/ns/cgroup
  lrwxrwxrwx 1 root root 0 2014-07-15 10:37 /proc/self/ns/cgroup -> cgroup:[4026531835]
  # cat /proc/self/cgroup
  0::/batchjobs/container_id1

After unsharing a new namespace, the view changes::

  # ls -l /proc/self/ns/cgroup
  lrwxrwxrwx 1 root root 0 2014-07-15 10:35 /proc/self/ns/cgroup -> cgroup:[4026532183]
  # cat /proc/self/cgroup
  0::/

When some thread from a multi-threaded process unshares its cgroup
namespace, the new cgroupns gets applied to the entire process (all
the threads).  This is natural for the v2 hierarchy; however, for the
legacy hierarchies, this may be unexpected.

A cgroup namespace is alive as long as there are processes inside or
mounts pinning it.  When the last usage goes away, the cgroup
namespace is destroyed.  The cgroupns root and the actual cgroups
remain.


The Root and Views
------------------

The 'cgroupns root' for a cgroup namespace is the cgroup in which the
process calling unshare(2) is running.  For example, if a process in
/batchjobs/container_id1 cgroup calls unshare, cgroup
/batchjobs/container_id1 becomes the cgroupns root.  For the
init_cgroup_ns, this is the real root ('/') cgroup.

The cgroupns root cgroup does not change even if the namespace creator
process later moves to a different cgroup::

  # ~/unshare -c # unshare cgroupns in some cgroup
  # cat /proc/self/cgroup
  0::/
  # mkdir sub_cgrp_1
  # echo 0 > sub_cgrp_1/cgroup.procs
  # cat /proc/self/cgroup
  0::/sub_cgrp_1

Each process gets its namespace-specific view of "/proc/$PID/cgroup"

Processes running inside the cgroup namespace will be able to see
cgroup paths (in /proc/self/cgroup) only inside their root cgroup.
From within an unshared cgroupns::

  # sleep 100000 &
  [1] 7353
  # echo 7353 > sub_cgrp_1/cgroup.procs
  # cat /proc/7353/cgroup
  0::/sub_cgrp_1

From the initial cgroup namespace, the real cgroup path will be
visible::

  $ cat /proc/7353/cgroup
  0::/batchjobs/container_id1/sub_cgrp_1

From a sibling cgroup namespace (that is, a namespace rooted at a
different cgroup), the cgroup path relative to its own cgroup
namespace root will be shown.  For instance, if PID 7353's cgroup
namespace root is at '/batchjobs/container_id2', then it will see::

  # cat /proc/7353/cgroup
  0::/../container_id2/sub_cgrp_1

Note that the relative path always starts with '/' to indicate that
its relative to the cgroup namespace root of the caller.


Migration and setns(2)
----------------------

Processes inside a cgroup namespace can move into and out of the
namespace root if they have proper access to external cgroups.  For
example, from inside a namespace with cgroupns root at
/batchjobs/container_id1, and assuming that the global hierarchy is
still accessible inside cgroupns::

  # cat /proc/7353/cgroup
  0::/sub_cgrp_1
  # echo 7353 > batchjobs/container_id2/cgroup.procs
  # cat /proc/7353/cgroup
  0::/../container_id2

Note that this kind of setup is not encouraged.  A task inside cgroup
namespace should only be exposed to its own cgroupns hierarchy.

setns(2) to another cgroup namespace is allowed when:

(a) the process has CAP_SYS_ADMIN against its current user namespace
(b) the process has CAP_SYS_ADMIN against the target cgroup
    namespace's userns

No implicit cgroup changes happen with attaching to another cgroup
namespace.  It is expected that the someone moves the attaching
process under the target cgroup namespace root.


Interaction with Other Namespaces
---------------------------------

Namespace specific cgroup hierarchy can be mounted by a process
running inside a non-init cgroup namespace::

  # mount -t cgroup2 none $MOUNT_POINT

This will mount the unified cgroup hierarchy with cgroupns root as the
filesystem root.  The process needs CAP_SYS_ADMIN against its user and
mount namespaces.

The virtualization of /proc/self/cgroup file combined with restricting
the view of cgroup hierarchy by namespace-private cgroupfs mount
provides a properly isolated cgroup view inside the container.


Information on Kernel Programming
=================================

This section contains kernel programming information in the areas
where interacting with cgroup is necessary.  cgroup core and
controllers are not covered.


Filesystem Support for Writeback
--------------------------------

A filesystem can support cgroup writeback by updating
address_space_operations->writepages() to annotate bio's using the
following two functions.

  wbc_init_bio(@wbc, @bio)
	Should be called for each bio carrying writeback data and
	associates the bio with the inode's owner cgroup and the
	corresponding request queue.  This must be called after
	a queue (device) has been associated with the bio and
	before submission.

  wbc_account_cgroup_owner(@wbc, @folio, @bytes)
	Should be called for each data segment being written out.
	While this function doesn't care exactly when it's called
	during the writeback session, it's the easiest and most
	natural to call it as data segments are added to a bio.

With writeback bio's annotated, cgroup support can be enabled per
super_block by setting SB_I_CGROUPWB in ->s_iflags.  This allows for
selective disabling of cgroup writeback support which is helpful when
certain filesystem features, e.g. journaled data mode, are
incompatible.

wbc_init_bio() binds the specified bio to its cgroup.  Depending on
the configuration, the bio may be executed at a lower priority and if
the writeback session is holding shared resources, e.g. a journal
entry, may lead to priority inversion.  There is no one easy solution
for the problem.  Filesystems can try to work around specific problem
cases by skipping wbc_init_bio() and using bio_associate_blkg()
directly.


Deprecated v1 Core Features
===========================

- Multiple hierarchies including named ones are not supported.

- All v1 mount options are not supported.

- The "tasks" file is removed and "cgroup.procs" is not sorted.

- "cgroup.clone_children" is removed.

- /proc/cgroups is meaningless for v2.  Use "cgroup.controllers" or
  "cgroup.stat" files at the root instead.


Issues with v1 and Rationales for v2
====================================

Multiple Hierarchies
--------------------

cgroup v1 allowed an arbitrary number of hierarchies and each
hierarchy could host any number of controllers.  While this seemed to
provide a high level of flexibility, it wasn't useful in practice.

For example, as there is only one instance of each controller, utility
type controllers such as freezer which can be useful in all
hierarchies could only be used in one.  The issue is exacerbated by
the fact that controllers couldn't be moved to another hierarchy once
hierarchies were populated.  Another issue was that all controllers
bound to a hierarchy were forced to have exactly the same view of the
hierarchy.  It wasn't possible to vary the granularity depending on
the specific controller.

In practice, these issues heavily limited which controllers could be
put on the same hierarchy and most configurations resorted to putting
each controller on its own hierarchy.  Only closely related ones, such
as the cpu and cpuacct controllers, made sense to be put on the same
hierarchy.  This often meant that userland ended up managing multiple
similar hierarchies repeating the same steps on each hierarchy
whenever a hierarchy management operation was necessary.

Furthermore, support for multiple hierarchies came at a steep cost.
It greatly complicated cgroup core implementation but more importantly
the support for multiple hierarchies restricted how cgroup could be
used in general and what controllers was able to do.

There was no limit on how many hierarchies there might be, which meant
that a thread's cgroup membership couldn't be described in finite
length.  The key might contain any number of entries and was unlimited
in length, which made it highly awkward to manipulate and led to
addition of controllers which existed only to identify membership,
which in turn exacerbated the original problem of proliferating number
of hierarchies.

Also, as a controller couldn't have any expectation regarding the
topologies of hierarchies other controllers might be on, each
controller had to assume that all other controllers were attached to
completely orthogonal hierarchies.  This made it impossible, or at
least very cumbersome, for controllers to cooperate with each other.

In most use cases, putting controllers on hierarchies which are
completely orthogonal to each other isn't necessary.  What usually is
called for is the ability to have differing levels of granularity
depending on the specific controller.  In other words, hierarchy may
be collapsed from leaf towards root when viewed from specific
controllers.  For example, a given configuration might not care about
how memory is distributed beyond a certain level while still wanting
to control how CPU cycles are distributed.


Thread Granularity
------------------

cgroup v1 allowed threads of a process to belong to different cgroups.
This didn't make sense for some controllers and those controllers
ended up implementing different ways to ignore such situations but
much more importantly it blurred the line between API exposed to
individual applications and system management interface.

Generally, in-process knowledge is available only to the process
itself; thus, unlike service-level organization of processes,
categorizing threads of a process requires active participation from
the application which owns the target process.

cgroup v1 had an ambiguously defined delegation model which got abused
in combination with thread granularity.  cgroups were delegated to
individual applications so that they can create and manage their own
sub-hierarchies and control resource distributions along them.  This
effectively raised cgroup to the status of a syscall-like API exposed
to lay programs.

First of all, cgroup has a fundamentally inadequate interface to be
exposed this way.  For a process to access its own knobs, it has to
extract the path on the target hierarchy from /proc/self/cgroup,
construct the path by appending the name of the knob to the path, open
and then read and/or write to it.  This is not only extremely clunky
and unusual but also inherently racy.  There is no conventional way to
define transaction across the required steps and nothing can guarantee
that the process would actually be operating on its own sub-hierarchy.

cgroup controllers implemented a number of knobs which would never be
accepted as public APIs because they were just adding control knobs to
system-management pseudo filesystem.  cgroup ended up with interface
knobs which were not properly abstracted or refined and directly
revealed kernel internal details.  These knobs got exposed to
individual applications through the ill-defined delegation mechanism
effectively abusing cgroup as a shortcut to implementing public APIs
without going through the required scrutiny.

This was painful for both userland and kernel.  Userland ended up with
misbehaving and poorly abstracted interfaces and kernel exposing and
locked into constructs inadvertently.


Competition Between Inner Nodes and Threads
-------------------------------------------

cgroup v1 allowed threads to be in any cgroups which created an
interesting problem where threads belonging to a parent cgroup and its
children cgroups competed for resources.  This was nasty as two
different types of entities competed and there was no obvious way to
settle it.  Different controllers did different things.

The cpu controller considered threads and cgroups as equivalents and
mapped nice levels to cgroup weights.  This worked for some cases but
fell flat when children wanted to be allocated specific ratios of CPU
cycles and the number of internal threads fluctuated - the ratios
constantly changed as the number of competing entities fluctuated.
There also were other issues.  The mapping from nice level to weight
wasn't obvious or universal, and there were various other knobs which
simply weren't available for threads.

The io controller implicitly created a hidden leaf node for each
cgroup to host the threads.  The hidden leaf had its own copies of all
the knobs with ``leaf_`` prefixed.  While this allowed equivalent
control over internal threads, it was with serious drawbacks.  It
always added an extra layer of nesting which wouldn't be necessary
otherwise, made the interface messy and significantly complicated the
implementation.

The memory controller didn't have a way to control what happened
between internal tasks and child cgroups and the behavior was not
clearly defined.  There were attempts to add ad-hoc behaviors and
knobs to tailor the behavior to specific workloads which would have
led to problems extremely difficult to resolve in the long term.

Multiple controllers struggled with internal tasks and came up with
different ways to deal with it; unfortunately, all the approaches were
severely flawed and, furthermore, the widely different behaviors
made cgroup as a whole highly inconsistent.

This clearly is a problem which needs to be addressed from cgroup core
in a uniform way.


Other Interface Issues
----------------------

cgroup v1 grew without oversight and developed a large number of
idiosyncrasies and inconsistencies.  One issue on the cgroup core side
was how an empty cgroup was notified - a userland helper binary was
forked and executed for each event.  The event delivery wasn't
recursive or delegatable.  The limitations of the mechanism also led
to in-kernel event delivery filtering mechanism further complicating
the interface.

Controller interfaces were problematic too.  An extreme example is
controllers completely ignoring hierarchical organization and treating
all cgroups as if they were all located directly under the root
cgroup.  Some controllers exposed a large amount of inconsistent
implementation details to userland.

There also was no consistency across controllers.  When a new cgroup
was created, some controllers defaulted to not imposing extra
restrictions while others disallowed any resource usage until
explicitly configured.  Configuration knobs for the same type of
control used widely differing naming schemes and formats.  Statistics
and information knobs were named arbitrarily and used different
formats and units even in the same controller.

cgroup v2 establishes common conventions where appropriate and updates
controllers so that they expose minimal and consistent interfaces.


Controller Issues and Remedies
------------------------------

Memory
~~~~~~

The original lower boundary, the soft limit, is defined as a limit
that is per default unset.  As a result, the set of cgroups that
global reclaim prefers is opt-in, rather than opt-out.  The costs for
optimizing these mostly negative lookups are so high that the
implementation, despite its enormous size, does not even provide the
basic desirable behavior.  First off, the soft limit has no
hierarchical meaning.  All configured groups are organized in a global
rbtree and treated like equal peers, regardless where they are located
in the hierarchy.  This makes subtree delegation impossible.  Second,
the soft limit reclaim pass is so aggressive that it not just
introduces high allocation latencies into the system, but also impacts
system performance due to overreclaim, to the point where the feature
becomes self-defeating.

The memory.low boundary on the other hand is a top-down allocated
reserve.  A cgroup enjoys reclaim protection when it's within its
effective low, which makes delegation of subtrees possible. It also
enjoys having reclaim pressure proportional to its overage when
above its effective low.

The original high boundary, the hard limit, is defined as a strict
limit that can not budge, even if the OOM killer has to be called.
But this generally goes against the goal of making the most out of the
available memory.  The memory consumption of workloads varies during
runtime, and that requires users to overcommit.  But doing that with a
strict upper limit requires either a fairly accurate prediction of the
working set size or adding slack to the limit.  Since working set size
estimation is hard and error prone, and getting it wrong results in
OOM kills, most users tend to err on the side of a looser limit and
end up wasting precious resources.

The memory.high boundary on the other hand can be set much more
conservatively.  When hit, it throttles allocations by forcing them
into direct reclaim to work off the excess, but it never invokes the
OOM killer.  As a result, a high boundary that is chosen too
aggressively will not terminate the processes, but instead it will
lead to gradual performance degradation.  The user can monitor this
and make corrections until the minimal memory footprint that still
gives acceptable performance is found.

In extreme cases, with many concurrent allocations and a complete
breakdown of reclaim progress within the group, the high boundary can
be exceeded.  But even then it's mostly better to satisfy the
allocation from the slack available in other groups or the rest of the
system than killing the group.  Otherwise, memory.max is there to
limit this type of spillover and ultimately contain buggy or even
malicious applications.

Setting the original memory.limit_in_bytes below the current usage was
subject to a race condition, where concurrent charges could cause the
limit setting to fail. memory.max on the other hand will first set the
limit to prevent new charges, and then reclaim and OOM kill until the
new limit is met - or the task writing to memory.max is killed.

The combined memory+swap accounting and limiting is replaced by real
control over swap space.

The main argument for a combined memory+swap facility in the original
cgroup design was that global or parental pressure would always be
able to swap all anonymous memory of a child group, regardless of the
child's own (possibly untrusted) configuration.  However, untrusted
groups can sabotage swapping by other means - such as referencing its
anonymous memory in a tight loop - and an admin can not assume full
swappability when overcommitting untrusted jobs.

For trusted jobs, on the other hand, a combined counter is not an
intuitive userspace interface, and it flies in the face of the idea
that cgroup controllers should account and limit specific physical
resources.  Swap space is a resource like all others in the system,
and that's why unified hierarchy allows distributing it separately.

---

### Documentation Admin Guide Clearing Warn Once (`Documentation/admin-guide/clearing-warn-once.rst`)

Clearing WARN_ONCE
------------------

WARN_ONCE / WARN_ON_ONCE / printk_once only emit a message once.

echo 1 > /sys/kernel/debug/clear_warn_once

clears the state and allows the warnings to print once again.
This can be useful after test suite runs to reproduce problems.

---

### Documentation Admin Guide Cpu Load (`Documentation/admin-guide/cpu-load.rst`)

========
CPU load
========

Linux exports various bits of information via ``/proc/stat`` and
``/proc/uptime`` that userland tools, such as top(1), use to calculate
the average time system spent in a particular state, for example::

    $ iostat
    Linux 2.6.18.3-exp (linmac)     02/20/2007

    avg-cpu:  %user   %nice %system %iowait  %steal   %idle
              10.01    0.00    2.92    5.44    0.00   81.63

    ...

Here the system thinks that over the default sampling period the
system spent 10.01% of the time doing work in user space, 2.92% in the
kernel, and was overall 81.63% of the time idle.

In most cases the ``/proc/stat``	 information reflects the reality quite
closely, however due to the nature of how/when the kernel collects
this data sometimes it can not be trusted at all.

So how is this information collected?  Whenever timer interrupt is
signalled the kernel looks what kind of task was running at this
moment and increments the counter that corresponds to this tasks
kind/state.  The problem with this is that the system could have
switched between various states multiple times between two timer
interrupts yet the counter is incremented only for the last state.


Example
-------

If we imagine the system with one task that periodically burns cycles
in the following manner::

     time line between two timer interrupts
    |--------------------------------------|
     ^                                    ^
     |_ something begins working          |
                                          |_ something goes to sleep
                                         (only to be awaken quite soon)

In the above situation the system will be 0% loaded according to the
``/proc/stat`` (since the timer interrupt will always happen when the
system is executing the idle handler), but in reality the load is
closer to 99%.

One can imagine many more situations where this behavior of the kernel
will lead to quite erratic information inside ``/proc/stat``::


	/* gcc -o hog smallhog.c */
	#include <time.h>
	#include <limits.h>
	#include <signal.h>
	#include <sys/time.h>
	#define HIST 10

	static volatile sig_atomic_t stop;

	static void sighandler(int signr)
	{
		(void) signr;
		stop = 1;
	}

	static unsigned long hog (unsigned long niters)
	{
		stop = 0;
		while (!stop && --niters);
		return niters;
	}

	int main (void)
	{
		int i;
		struct itimerval it = {
			.it_interval = { .tv_sec = 0, .tv_usec = 1 },
			.it_value    = { .tv_sec = 0, .tv_usec = 1 } };
		sigset_t set;
		unsigned long v[HIST];
		double tmp = 0.0;
		unsigned long n;
		signal(SIGALRM, &sighandler);
		setitimer(ITIMER_REAL, &it, NULL);

		hog (ULONG_MAX);
		for (i = 0; i < HIST; ++i) v[i] = ULONG_MAX - hog(ULONG_MAX);
		for (i = 0; i < HIST; ++i) tmp += v[i];
		tmp /= HIST;
		n = tmp - (tmp / 3.0);

		sigemptyset(&set);
		sigaddset(&set, SIGALRM);

		for (;;) {
			hog(n);
			sigwait(&set, &i);
		}
		return 0;
	}


References
----------

- https://lore.kernel.org/r/loom.20070212T063225-663@post.gmane.org
- Documentation/filesystems/proc.rst (1.8)


Thanks
------

Con Kolivas, Pavel Machek

---

### Documentation Admin Guide Cputopology (`Documentation/admin-guide/cputopology.rst`)

===========================================
How CPU topology info is exported via sysfs
===========================================

CPU topology info is exported via sysfs. Items (attributes) are similar
to /proc/cpuinfo output of some architectures. They reside in
/sys/devices/system/cpu/cpuX/topology/. Please refer to the ABI file:
Documentation/ABI/stable/sysfs-devices-system-cpu.

Architecture-neutral, drivers/base/topology.c, exports these attributes.
However the die, cluster, book, and drawer hierarchy related sysfs files will
only be created if an architecture provides the related macros as described
below.

For an architecture to support this feature, it must define some of
these macros in include/asm-XXX/topology.h::

	#define topology_physical_package_id(cpu)
	#define topology_die_id(cpu)
	#define topology_cluster_id(cpu)
	#define topology_core_id(cpu)
	#define topology_book_id(cpu)
	#define topology_drawer_id(cpu)
	#define topology_sibling_cpumask(cpu)
	#define topology_core_cpumask(cpu)
	#define topology_cluster_cpumask(cpu)
	#define topology_die_cpumask(cpu)
	#define topology_book_cpumask(cpu)
	#define topology_drawer_cpumask(cpu)

The type of ``**_id macros`` is int.
The type of ``**_cpumask macros`` is ``(const) struct cpumask *``. The latter
correspond with appropriate ``**_siblings`` sysfs attributes (except for
topology_sibling_cpumask() which corresponds with thread_siblings).

To be consistent on all architectures, include/linux/topology.h
provides default definitions for any of the above macros that are
not defined by include/asm-XXX/topology.h:

1) topology_physical_package_id: -1
2) topology_die_id: -1
3) topology_cluster_id: -1
4) topology_core_id: 0
5) topology_book_id: -1
6) topology_drawer_id: -1
7) topology_sibling_cpumask: just the given CPU
8) topology_core_cpumask: just the given CPU
9) topology_cluster_cpumask: just the given CPU
10) topology_die_cpumask: just the given CPU
11) topology_book_cpumask:  just the given CPU
12) topology_drawer_cpumask: just the given CPU

Additionally, CPU topology information is provided under
/sys/devices/system/cpu and includes these files.  The internal
source for the output is in brackets ("[]").

    =========== ==========================================================
    kernel_max: the maximum CPU index allowed by the kernel configuration.
		[NR_CPUS-1]

    offline:	CPUs that are not online because they have been
		HOTPLUGGED off or exceed the limit of CPUs allowed by the
		kernel configuration (kernel_max above).
		[~cpu_online_mask + cpus >= NR_CPUS]

    online:	CPUs that are online and being scheduled [cpu_online_mask]

    possible:	CPUs that have been allocated resources and can be
		brought online if they are present. [cpu_possible_mask]

    present:	CPUs that have been identified as being present in the
		system. [cpu_present_mask]
    =========== ==========================================================

The format for the above output is compatible with cpulist_parse()
[see <linux/cpumask.h>].  Some examples follow.

In this example, there are 64 CPUs in the system but cpus 32-63 exceed
the kernel max which is limited to 0..31 by the NR_CPUS config option
being 32.  Note also that CPUs 2 and 4-31 are not online but could be
brought online as they are both present and possible::

     kernel_max: 31
        offline: 2,4-31,32-63
         online: 0-1,3
       possible: 0-31
        present: 0-31

In this example, the NR_CPUS config option is 128, but the kernel was
started with possible_cpus=144.  There are 4 CPUs in the system and cpu2
was manually taken offline (and is the only CPU that can be brought
online.)::

     kernel_max: 127
        offline: 2,4-127,128-143
         online: 0-1,3
       possible: 0-127
        present: 0-3

See Documentation/core-api/cpu_hotplug.rst for the possible_cpus=NUM
kernel start parameter as well as more information on the various cpumasks.

---

### Documentation Admin Guide Dell Rbu (`Documentation/admin-guide/dell_rbu.rst`)

=========================================
Dell Remote BIOS Update driver (dell_rbu)
=========================================

Purpose
=======

Document demonstrating the use of the Dell Remote BIOS Update driver
for updating BIOS images on Dell servers and desktops.

Scope
=====

This document discusses the functionality of the rbu driver only.
It does not cover the support needed from applications to enable the BIOS to
update itself with the image downloaded in to the memory.

Overview
========

This driver works with Dell OpenManage or Dell Update Packages for updating
the BIOS on Dell servers (starting from servers sold since 1999), desktops
and notebooks (starting from those sold in 2005).

Please go to  http://support.dell.com register and you can find info on
OpenManage and Dell Update packages (DUP).

Libsmbios can also be used to update BIOS on Dell systems go to
https://linux.dell.com/libsmbios/ for details.

Dell_RBU driver supports BIOS update using the monolithic image and packetized
image methods. In case of monolithic the driver allocates a contiguous chunk
of physical pages having the BIOS image. In case of packetized the app
using the driver breaks the image in to packets of fixed sizes and the driver
would place each packet in contiguous physical memory. The driver also
maintains a link list of packets for reading them back.

If the dell_rbu driver is unloaded all the allocated memory is freed.

The rbu driver needs to have an application (as mentioned above) which will
inform the BIOS to enable the update in the next system reboot.

The user should not unload the rbu driver after downloading the BIOS image
or updating.

The driver load creates the following directories under the /sys file system::

	/sys/class/firmware/dell_rbu/loading
	/sys/class/firmware/dell_rbu/data
	/sys/devices/platform/dell_rbu/image_type
	/sys/devices/platform/dell_rbu/data
	/sys/devices/platform/dell_rbu/packet_size

The driver supports two types of update mechanism; monolithic and packetized.
These update mechanism depends upon the BIOS currently running on the system.
Most of the Dell systems support a monolithic update where the BIOS image is
copied to a single contiguous block of physical memory.

In case of packet mechanism the single memory can be broken in smaller chunks
of contiguous memory and the BIOS image is scattered in these packets.

By default the driver uses monolithic memory for the update type. This can be
changed to packets during the driver load time by specifying the load
parameter image_type=packet.  This can also be changed later as below::

	echo packet > /sys/devices/platform/dell_rbu/image_type

In packet update mode the packet size has to be given before any packets can
be downloaded. It is done as below::

	echo XXXX > /sys/devices/platform/dell_rbu/packet_size

In the packet update mechanism, the user needs to create a new file having
packets of data arranged back to back. It can be done as follows:
The user creates packets header, gets the chunk of the BIOS image and
places it next to the packetheader; now, the packetheader + BIOS image chunk
added together should match the specified packet_size. This makes one
packet, the user needs to create more such packets out of the entire BIOS
image file and then arrange all these packets back to back in to one single
file.

This file is then copied to /sys/class/firmware/dell_rbu/data.
Once this file gets to the driver, the driver extracts packet_size data from
the file and spreads it across the physical memory in contiguous packet_sized
space.

This method makes sure that all the packets get to the driver in a single operation.

In monolithic update the user simply get the BIOS image (.hdr file) and copies
to the data file as is without any change to the BIOS image itself.

Do the steps below to download the BIOS image.

1) echo 1 > /sys/class/firmware/dell_rbu/loading
2) cp bios_image.hdr /sys/class/firmware/dell_rbu/data
3) echo 0 > /sys/class/firmware/dell_rbu/loading

The /sys/class/firmware/dell_rbu/ entries will remain till the following is
done.

::

	echo -1 > /sys/class/firmware/dell_rbu/loading

Until this step is completed the driver cannot be unloaded.

Also echoing either mono, packet or init in to image_type will free up the
memory allocated by the driver.

If a user by accident executes steps 1 and 3 above without executing step 2;
it will make the /sys/class/firmware/dell_rbu/ entries disappear.

The entries can be recreated by doing the following::

	echo init > /sys/devices/platform/dell_rbu/image_type

.. note:: echoing init in image_type does not change its original value.

Also the driver provides /sys/devices/platform/dell_rbu/data readonly file to
read back the image downloaded.

.. note::

   After updating the BIOS image a user mode application needs to execute
   code which sends the BIOS update request to the BIOS. So on the next reboot
   the BIOS knows about the new image downloaded and it updates itself.
   Also don't unload the rbu driver if the image has to be updated.

---

### Documentation Admin Guide Devices (`Documentation/admin-guide/devices.rst`)

.. _admin_devices:

Linux allocated devices (4.x+ version)
======================================

This list is the Linux Device List, the official registry of allocated
device numbers and ``/dev`` directory nodes for the Linux operating
system.

The version of this document at lanana.org is no longer maintained.  This
version in the mainline Linux kernel is the master document.  Updates
shall be sent as patches to the kernel maintainers (see the
:ref:`Documentation/process/submitting-patches.rst <submittingpatches>` document).
Specifically explore the sections titled "CHAR and MISC DRIVERS", and
"BLOCK LAYER" in the MAINTAINERS file to find the right maintainers
to involve for character and block devices.

This document is included by reference into the Filesystem Hierarchy
Standard (FHS).	 The FHS is available from https://www.pathname.com/fhs/.

Allocations marked (68k/Amiga) apply to Linux/68k on the Amiga
platform only.	Allocations marked (68k/Atari) apply to Linux/68k on
the Atari platform only.

This document is in the public domain.	The authors requests, however,
that semantically altered versions are not distributed without
permission of the authors, assuming the authors can be contacted without
an unreasonable effort.


.. attention::

  DEVICE DRIVERS AUTHORS PLEASE READ THIS

  Linux now has extensive support for dynamic allocation of device numbering
  and can use ``sysfs`` and ``udev`` (``systemd``) to handle the naming needs.
  There are still some exceptions in the serial and boot device area. Before
  asking   for a device number make sure you actually need one.

  To have a major number allocated, or a minor number in situations
  where that applies (e.g. busmice), please submit a patch and send to
  the authors as indicated above.

  Keep the description of the device *in the same format
  as this list*. The reason for this is that it is the only way we have
  found to ensure we have all the requisite information to publish your
  device and avoid conflicts.

  Finally, sometimes we have to play "namespace police."  Please don't be
  offended.  We often get submissions for ``/dev`` names that would be bound
  to cause conflicts down the road.  We are trying to avoid getting in a
  situation where we would have to suffer an incompatible forward
  change.  Therefore, please consult with us **before** you make your
  device names and numbers in any way public, at least to the point
  where it would be at all difficult to get them changed.

  Your cooperation is appreciated.

.. include:: devices.txt
   :literal:

Additional ``/dev/`` directory entries
--------------------------------------

This section details additional entries that should or may exist in
the /dev directory.  It is preferred that symbolic links use the same
form (absolute or relative) as is indicated here.  Links are
classified as "hard" or "symbolic" depending on the preferred type of
link; if possible, the indicated type of link should be used.

Compulsory links
++++++++++++++++

These links should exist on all systems:

=============== =============== =============== ===============================
/dev/fd		/proc/self/fd	symbolic	File descriptors
/dev/stdin	fd/0		symbolic	stdin file descriptor
/dev/stdout	fd/1		symbolic	stdout file descriptor
/dev/stderr	fd/2		symbolic	stderr file descriptor
/dev/nfsd	socksys		symbolic	Required by iBCS-2
/dev/X0R	null		symbolic	Required by iBCS-2
=============== =============== =============== ===============================

Note: ``/dev/X0R`` is <letter X>-<digit 0>-<letter R>.

Recommended links
+++++++++++++++++

It is recommended that these links exist on all systems:


=============== =============== =============== ===============================
/dev/core	/proc/kcore	symbolic	Backward compatibility
/dev/ramdisk	ram0		symbolic	Backward compatibility
/dev/ftape	qft0		symbolic	Backward compatibility
/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
=============== =============== =============== ===============================

Locally defined links
+++++++++++++++++++++

The following links may be established locally to conform to the
configuration of the system.  This is merely a tabulation of existing
practice, and does not constitute a recommendation.  However, if they
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
/dev/swap	swap device	symbolic	Current swap device
=============== =============== =============== ===============================

``/dev/modem`` should not be used for a modem which supports dialin as
well as dialout, as it tends to cause lock file problems.  If it
exists, ``/dev/modem`` should point to the appropriate primary TTY device
(the use of the alternate callout devices is deprecated).

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/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``).

Sockets and pipes
+++++++++++++++++

Non-transient sockets and named pipes may exist in /dev.  Common entries are:

=============== =============== ===============================================
/dev/printer	socket		lpd local socket
/dev/log	socket		syslog local socket
/dev/gpmdata	socket		gpm mouse multiplexer
=============== =============== ===============================================

Mount points
++++++++++++

The following names are reserved for mounting special filesystems
under /dev.  These special filesystems provide kernel interfaces that
cannot be provided with standard device nodes.

=============== =============== ===============================================
/dev/pts	devpts		PTY slave filesystem
/dev/shm	tmpfs		POSIX shared memory maintenance access
=============== =============== ===============================================

Terminal devices
----------------

Terminal, or TTY devices are a special class of character devices.  A
terminal device is any device that could act as a controlling terminal
for a session; this includes virtual consoles, serial ports, and
pseudoterminals (PTYs).

All terminal devices share a common set of capabilities known as line
disciplines; these include the common terminal line discipline as well
as SLIP and PPP modes.

All terminal devices are named similarly; this section explains the
naming and use of the various types of TTYs.  Note that the naming
conventions include several historical warts; some of these are
Linux-specific, some were inherited from other systems, and some
reflect Linux outgrowing a borrowed convention.

A hash mark (``#``) in a device name is used here to indicate a decimal
number without leading zeroes.

Virtual consoles and the console device
+++++++++++++++++++++++++++++++++++++++

Virtual consoles are full-screen terminal displays on the system video
monitor.  Virtual consoles are named ``/dev/tty#``, with numbering
starting at ``/dev/tty1``; ``/dev/tty0`` is the current virtual console.
``/dev/tty0`` is the device that should be used to access the system video
card on those architectures for which the frame buffer devices
(``/dev/fb*``) are not applicable. Do not use ``/dev/console``
for this purpose.

The console device, ``/dev/console``, is the device to which system
messages should be sent, and on which logins should be permitted in
single-user mode.  Starting with Linux 2.1.71, ``/dev/console`` is managed
by the kernel; for previous versions it should be a symbolic link to
either ``/dev/tty0``, a specific virtual console such as ``/dev/tty1``, or to
a serial port primary (``tty*``, not ``cu*``) device, depending on the
configuration of the system.

Serial ports
++++++++++++

Serial ports are RS-232 serial ports and any device which simulates
one, either in hardware (such as internal modems) or in software (such
as the ISDN driver.)  Under Linux, each serial ports has two device
names, the primary or callin device and the alternate or callout one.
Each kind of device is indicated by a different letter.	 For any
letter X, the names of the devices are ``/dev/ttyX#`` and ``/dev/cux#``,
respectively; for historical reasons, ``/dev/ttyS#`` and ``/dev/ttyC#``
correspond to ``/dev/cua#`` and ``/dev/cub#``. In the future, it should be
expected that multiple letters will be used; all letters will be upper
case for the "tty" device (e.g. ``/dev/ttyDP#``) and lower case for the
"cu" device (e.g. ``/dev/cudp#``).

The names ``/dev/ttyQ#`` and ``/dev/cuq#`` are reserved for local use.

The alternate devices provide for kernel-based exclusion and somewhat
different defaults than the primary devices.  Their main purpose is to
allow the use of serial ports with programs with no inherent or broken
support for serial ports.  Their use is deprecated, and they may be
removed from a future version of Linux.

Arbitration of serial ports is provided by the use of lock files with
the names ``/var/lock/LCK..ttyX#``. The contents of the lock file should
be the PID of the locking process as an ASCII number.

It is common practice to install links such as /dev/modem
which point to serial ports.  In order to ensure proper locking in the
presence of these links, it is recommended that software chase
symlinks and lock all possible names; additionally, it is recommended
that a lock file be installed with the corresponding alternate
device.	 In order to avoid deadlocks, it is recommended that the locks
are acquired in the following order, and released in the reverse:

	1. The symbolic link name, if any (``/var/lock/LCK..modem``)
	2. The "tty" name (``/var/lock/LCK..ttyS2``)
	3. The alternate device name (``/var/lock/LCK..cua2``)

In the case of nested symbolic links, the lock files should be
installed in the order the symlinks are resolved.

Under no circumstances should an application hold a lock while waiting
for another to be released.  In addition, applications which attempt
to create lock files for the corresponding alternate device names
should take into account the possibility of being used on a non-serial
port TTY, for which no alternate device would exist.

Pseudoterminals (PTYs)
++++++++++++++++++++++

Pseudoterminals, or PTYs, are used to create login sessions or provide
other capabilities requiring a TTY line discipline (including SLIP or
PPP capability) to arbitrary data-generation processes.	 Each PTY has
a master side, named ``/dev/pty[p-za-e][0-9a-f]``, and a slave side, named
``/dev/tty[p-za-e][0-9a-f]``.  The kernel arbitrates the use of PTYs by
allowing each master side to be opened only once.

Once the master side has been opened, the corresponding slave device
can be used in the same manner as any TTY device.  The master and
slave devices are connected by the kernel, generating the equivalent
of a bidirectional pipe with TTY capabilities.

Recent versions of the Linux kernels and GNU libc contain support for
the System V/Unix98 naming scheme for PTYs, which assigns a common
device, ``/dev/ptmx``, to all the masters (opening it will automatically
give you a previously unassigned PTY) and a subdirectory, ``/dev/pts``,
for the slaves; the slaves are named with decimal integers (``/dev/pts/#``
in our notation).  This removes the problem of exhausting the
namespace and enables the kernel to automatically create the device
nodes for the slaves on demand using the "devpts" filesystem.

---

### Documentation Admin Guide Devices (`Documentation/admin-guide/devices.txt`)

0		Unnamed devices (e.g. non-device mounts)
		  0 = reserved as null device number
		See block major 144, 145, 146 for expansion areas.

   1 char	Memory devices
		  1 = /dev/mem		Physical memory access
		  2 = /dev/kmem		OBSOLETE - replaced by /proc/kcore
		  3 = /dev/null		Null device
		  4 = /dev/port		I/O port access
		  5 = /dev/zero		Null byte source
		  6 = /dev/core		OBSOLETE - replaced by /proc/kcore
		  7 = /dev/full		Returns ENOSPC on write
		  8 = /dev/random	Nondeterministic random number gen.
		  9 = /dev/urandom	Faster, less secure random number gen.
		 10 = /dev/aio		Asynchronous I/O notification interface
		 11 = /dev/kmsg		Writes to this come out as printk's, reads
					export the buffered printk records.
		 12 = /dev/oldmem	OBSOLETE - replaced by /proc/vmcore

   1 block	RAM disk
		  0 = /dev/ram0		First RAM disk
		  1 = /dev/ram1		Second RAM disk
		    ...
		250 = /dev/initrd	Initial RAM disk

		Older kernels had /dev/ramdisk (1, 1) here.
		/dev/initrd refers to a RAM disk which was preloaded
		by the boot loader; newer kernels use /dev/ram0 for
		the initrd.

   2 char	Pseudo-TTY masters
		  0 = /dev/ptyp0	First PTY master
		  1 = /dev/ptyp1	Second PTY master
		    ...
		255 = /dev/ptyef	256th PTY master

		Pseudo-tty's are named as follows:
		* Masters are "pty", slaves are "tty";
		* the fourth letter is one of pqrstuvwxyzabcde indicating
		  the 1st through 16th series of 16 pseudo-ttys each, and
		* the fifth letter is one of 0123456789abcdef indicating
		  the position within the series.

		These are the old-style (BSD) PTY devices; Unix98
		devices are on major 128 and above and use the PTY
		master multiplex (/dev/ptmx) to acquire a PTY on
		demand.

   2 block	Floppy disks
		  0 = /dev/fd0		Controller 0, drive 0, autodetect
		  1 = /dev/fd1		Controller 0, drive 1, autodetect
		  2 = /dev/fd2		Controller 0, drive 2, autodetect
		  3 = /dev/fd3		Controller 0, drive 3, autodetect
		128 = /dev/fd4		Controller 1, drive 0, autodetect
		129 = /dev/fd5		Controller 1, drive 1, autodetect
		130 = /dev/fd6		Controller 1, drive 2, autodetect
		131 = /dev/fd7		Controller 1, drive 3, autodetect

		To specify format, add to the autodetect device number:
		  0 = /dev/fd?		Autodetect format
		  4 = /dev/fd?d360	5.25"  360K in a 360K  drive(1)
		 20 = /dev/fd?h360	5.25"  360K in a 1200K drive(1)
		 48 = /dev/fd?h410	5.25"  410K in a 1200K drive
		 64 = /dev/fd?h420	5.25"  420K in a 1200K drive
		 24 = /dev/fd?h720	5.25"  720K in a 1200K drive
		 80 = /dev/fd?h880	5.25"  880K in a 1200K drive(1)
		  8 = /dev/fd?h1200	5.25" 1200K in a 1200K drive(1)
		 40 = /dev/fd?h1440	5.25" 1440K in a 1200K drive(1)
		 56 = /dev/fd?h1476	5.25" 1476K in a 1200K drive
		 72 = /dev/fd?h1494	5.25" 1494K in a 1200K drive
		 92 = /dev/fd?h1600	5.25" 1600K in a 1200K drive(1)

		 12 = /dev/fd?u360	3.5"   360K Double Density(2)
		 16 = /dev/fd?u720	3.5"   720K Double Density(1)
		120 = /dev/fd?u800	3.5"   800K Double Density(2)
		 52 = /dev/fd?u820	3.5"   820K Double Density
		 68 = /dev/fd?u830	3.5"   830K Double Density
		 84 = /dev/fd?u1040	3.5"  1040K Double Density(1)
		 88 = /dev/fd?u1120	3.5"  1120K Double Density(1)
		 28 = /dev/fd?u1440	3.5"  1440K High Density(1)
		124 = /dev/fd?u1600	3.5"  1600K High Density(1)
		 44 = /dev/fd?u1680	3.5"  1680K High Density(3)
		 60 = /dev/fd?u1722	3.5"  1722K High Density
		 76 = /dev/fd?u1743	3.5"  1743K High Density
		 96 = /dev/fd?u1760	3.5"  1760K High Density
		116 = /dev/fd?u1840	3.5"  1840K High Density(3)
		100 = /dev/fd?u1920	3.5"  1920K High Density(1)
		 32 = /dev/fd?u2880	3.5"  2880K Extra Density(1)
		104 = /dev/fd?u3200	3.5"  3200K Extra Density
		108 = /dev/fd?u3520	3.5"  3520K Extra Density
		112 = /dev/fd?u3840	3.5"  3840K Extra Density(1)

		 36 = /dev/fd?CompaQ	Compaq 2880K drive; obsolete?

		(1) Autodetectable format
		(2) Autodetectable format in a Double Density (720K) drive only
		(3) Autodetectable format in a High Density (1440K) drive only

		NOTE: The letter in the device name (d, q, h or u)
		signifies the type of drive: 5.25" Double Density (d),
		5.25" Quad Density (q), 5.25" High Density (h) or 3.5"
		(any model, u).	 The use of the capital letters D, H
		and E for the 3.5" models have been deprecated, since
		the drive type is insignificant for these devices.

   3 char	Pseudo-TTY slaves
		  0 = /dev/ttyp0	First PTY slave
		  1 = /dev/ttyp1	Second PTY slave
		    ...
		255 = /dev/ttyef	256th PTY slave

		These are the old-style (BSD) PTY devices; Unix98
		devices are on major 136 and above.

   3 block	First MFM, RLL and IDE hard disk/CD-ROM interface
		  0 = /dev/hda		Master: whole disk (or CD-ROM)
		 64 = /dev/hdb		Slave: whole disk (or CD-ROM)

		For partitions, add to the whole disk device number:
		  0 = /dev/hd?		Whole disk
		  1 = /dev/hd?1		First partition
		  2 = /dev/hd?2		Second partition
		    ...
		 63 = /dev/hd?63	63rd partition

		For Linux/i386, partitions 1-4 are the primary
		partitions, and 5 and above are logical partitions.
		Other versions of Linux use partitioning schemes
		appropriate to their respective architectures.

   4 char	TTY devices
		  0 = /dev/tty0		Current virtual console

		  1 = /dev/tty1		First virtual console
		    ...
		 63 = /dev/tty63	63rd virtual console
		 64 = /dev/ttyS0	First UART serial port
		    ...
		255 = /dev/ttyS191	192nd UART serial port

		UART serial ports refer to 8250/16450/16550 series devices.

		Older versions of the Linux kernel used this major
		number for BSD PTY devices.  As of Linux 2.1.115, this
		is no longer supported.	 Use major numbers 2 and 3.

   4 block	Aliases for dynamically allocated major devices to be used
		when its not possible to create the real device nodes
		because the root filesystem is mounted read-only.

		   0 = /dev/root

   5 char	Alternate TTY devices
		  0 = /dev/tty		Current TTY device
		  1 = /dev/console	System console
		  2 = /dev/ptmx		PTY master multiplex
		  3 = /dev/ttyprintk	User messages via printk TTY device
		 64 = /dev/cua0		Callout device for ttyS0
		    ...
		255 = /dev/cua191	Callout device for ttyS191

		(5,1) is /dev/console starting with Linux 2.1.71.  See
		the section on terminal devices for more information
		on /dev/console.

   6 char	Parallel printer devices
		  0 = /dev/lp0		Parallel printer on parport0
		  1 = /dev/lp1		Parallel printer on parport1
		    ...

		Current Linux kernels no longer have a fixed mapping
		between parallel ports and I/O addresses.  Instead,
		they are redirected through the parport multiplex layer.

   7 char	Virtual console capture devices
		  0 = /dev/vcs		Current vc text (glyph) contents
		  1 = /dev/vcs1		tty1 text (glyph) contents
		    ...
		 63 = /dev/vcs63	tty63 text (glyph) contents
		 64 = /dev/vcsu		Current vc text (unicode) contents
		65 = /dev/vcsu1		tty1 text (unicode) contents
		    ...
		127 = /dev/vcsu63	tty63 text (unicode) contents
		128 = /dev/vcsa		Current vc text/attribute (glyph) contents
		129 = /dev/vcsa1	tty1 text/attribute (glyph) contents
		    ...
		191 = /dev/vcsa63	tty63 text/attribute (glyph) contents

		NOTE: These devices permit both read and write access.

   7 block	Loopback devices
		  0 = /dev/loop0	First loop device
		  1 = /dev/loop1	Second loop device
		    ...

		The loop devices are used to mount filesystems not
		associated with block devices.	The binding to the
		loop devices is handled by mount(8) or losetup(8).

   8 block	SCSI disk devices (0-15)
		  0 = /dev/sda		First SCSI disk whole disk
		 16 = /dev/sdb		Second SCSI disk whole disk
		 32 = /dev/sdc		Third SCSI disk whole disk
		    ...
		240 = /dev/sdp		Sixteenth SCSI disk whole disk

		Partitions are handled in the same way as for IDE
		disks (see major number 3) except that the limit on
		partitions is 15.

   9 char	SCSI tape devices
		  0 = /dev/st0		First SCSI tape, mode 0
		  1 = /dev/st1		Second SCSI tape, mode 0
		    ...
		 32 = /dev/st0l		First SCSI tape, mode 1
		 33 = /dev/st1l		Second SCSI tape, mode 1
		    ...
		 64 = /dev/st0m		First SCSI tape, mode 2
		 65 = /dev/st1m		Second SCSI tape, mode 2
		    ...
		 96 = /dev/st0a		First SCSI tape, mode 3
		 97 = /dev/st1a		Second SCSI tape, mode 3
		      ...
		128 = /dev/nst0		First SCSI tape, mode 0, no rewind
		129 = /dev/nst1		Second SCSI tape, mode 0, no rewind
		    ...
		160 = /dev/nst0l	First SCSI tape, mode 1, no rewind
		161 = /dev/nst1l	Second SCSI tape, mode 1, no rewind
		    ...
		192 = /dev/nst0m	First SCSI tape, mode 2, no rewind
		193 = /dev/nst1m	Second SCSI tape, mode 2, no rewind
		    ...
		224 = /dev/nst0a	First SCSI tape, mode 3, no rewind
		225 = /dev/nst1a	Second SCSI tape, mode 3, no rewind
		    ...

		"No rewind" refers to the omission of the default
		automatic rewind on device close.  The MTREW or MTOFFL
		ioctl()'s can be used to rewind the tape regardless of
		the device used to access it.

   9 block	Metadisk (RAID) devices
		  0 = /dev/md0		First metadisk group
		  1 = /dev/md1		Second metadisk group
		    ...

		The metadisk driver is used to span a
		filesystem across multiple physical disks.

  10 char	Non-serial mice, misc features
		  0 = /dev/logibm	Logitech bus mouse
		  1 = /dev/psaux	PS/2-style mouse port
		  2 = /dev/inportbm	Microsoft Inport bus mouse
		  3 = /dev/atibm	ATI XL bus mouse
		  4 = /dev/jbm		J-mouse
		  4 = /dev/amigamouse	Amiga mouse (68k/Amiga)
		  5 = /dev/atarimouse	Atari mouse
		  6 = /dev/sunmouse	Sun mouse
		  7 = /dev/amigamouse1	Second Amiga mouse
		  8 = /dev/smouse	Simple serial mouse driver
		  9 = /dev/pc110pad	IBM PC-110 digitizer pad
		 10 = /dev/adbmouse	Apple Desktop Bus mouse
		 11 = /dev/vrtpanel	Vr41xx embedded touch panel
		 13 = /dev/vpcmouse	Connectix Virtual PC Mouse
		 14 = /dev/touchscreen/ucb1x00  UCB 1x00 touchscreen
		 15 = /dev/touchscreen/mk712	MK712 touchscreen
		128 = /dev/beep		Fancy beep device
		129 =
		130 = /dev/watchdog	Watchdog timer port
		131 = /dev/temperature	Machine internal temperature
		132 = /dev/hwtrap	Hardware fault trap
		133 = /dev/exttrp	External device trap
		134 = /dev/apm_bios	Advanced Power Management BIOS
		135 = /dev/rtc		Real Time Clock
		137 = /dev/vhci		Bluetooth virtual HCI driver
		139 = /dev/openprom	SPARC OpenBoot PROM
		140 = /dev/relay8	Berkshire Products Octal relay card
		141 = /dev/relay16	Berkshire Products ISO-16 relay card
		142 =
		143 = /dev/pciconf	PCI configuration space
		144 = /dev/nvram	Non-volatile configuration RAM
		145 = /dev/hfmodem	Soundcard shortwave modem control
		146 = /dev/graphics	Linux/SGI graphics device
		147 = /dev/opengl	Linux/SGI OpenGL pipe
		148 = /dev/gfx		Linux/SGI graphics effects device
		149 = /dev/input/mouse	Linux/SGI Irix emulation mouse
		150 = /dev/input/keyboard Linux/SGI Irix emulation keyboard
		151 = /dev/led		Front panel LEDs
		152 = /dev/kpoll	Kernel Poll Driver
		153 = /dev/mergemem	Memory merge device
		154 = /dev/pmu		Macintosh PowerBook power manager
		155 =
		156 = /dev/lcd		Front panel LCD display
		157 = /dev/ac		Applicom Intl Profibus card
		158 = /dev/nwbutton	Netwinder external button
		159 = /dev/nwdebug	Netwinder debug interface
		160 = /dev/nwflash	Netwinder flash memory
		161 = /dev/userdma	User-space DMA access
		162 = /dev/smbus	System Management Bus
		163 = /dev/lik		Logitech Internet Keyboard
		164 = /dev/ipmo		Intel Intelligent Platform Management
		165 = /dev/vmmon	VMware virtual machine monitor
		166 = /dev/i2o/ctl	I2O configuration manager
		167 = /dev/specialix_sxctl Specialix serial control
		168 = /dev/tcldrv	Technology Concepts serial control
		169 = /dev/specialix_rioctl Specialix RIO serial control
		170 = /dev/thinkpad/thinkpad	IBM Thinkpad devices
		171 = /dev/srripc	QNX4 API IPC manager
		172 = /dev/usemaclone	Semaphore clone device
		173 = /dev/ipmikcs	Intelligent Platform Management
		174 = /dev/uctrl	SPARCbook 3 microcontroller
		175 = /dev/agpgart	AGP Graphics Address Remapping Table
		176 = /dev/gtrsc	Gorgy Timing radio clock
		177 = /dev/cbm		Serial CBM bus
		178 = /dev/jsflash	JavaStation OS flash SIMM
		179 = /dev/xsvc		High-speed shared-mem/semaphore service
		180 = /dev/vrbuttons	Vr41xx button input device
		181 = /dev/toshiba	Toshiba laptop SMM support
		182 = /dev/perfctr	Performance-monitoring counters
		183 = /dev/hwrng	Generic random number generator
		184 = /dev/cpu/microcode CPU microcode update interface
		186 = /dev/atomicps	Atomic snapshot of process state data
		187 = /dev/irnet	IrNET device
		188 = /dev/smbusbios	SMBus BIOS
		189 = /dev/ussp_ctl	User space serial port control
		190 = /dev/crash	Mission Critical Linux crash dump facility
		191 = /dev/pcl181	<information missing>
		192 = /dev/nas_xbus	NAS xbus LCD/buttons access
		193 = /dev/d7s		SPARC 7-segment display
		194 = /dev/zkshim	Zero-Knowledge network shim control
		195 = /dev/elographics/e2201	Elographics touchscreen E271-2201
		196 = /dev/vfio/vfio	VFIO userspace driver interface
		197 = /dev/pxa3xx-gcu	PXA3xx graphics controller unit driver
		198 = /dev/sexec	Signed executable interface
		199 = /dev/scanners/cuecat :CueCat barcode scanner
		200 = /dev/net/tun	TAP/TUN network device
		201 = /dev/button/gulpb	Transmeta GULP-B buttons
		202 = /dev/emd/ctl	Enhanced Metadisk RAID (EMD) control
		203 = /dev/cuse		Cuse (character device in user-space)
		204 = /dev/video/em8300		EM8300 DVD decoder control
		205 = /dev/video/em8300_mv	EM8300 DVD decoder video
		206 = /dev/video/em8300_ma	EM8300 DVD decoder audio
		207 = /dev/video/em8300_sp	EM8300 DVD decoder subpicture
		208 = /dev/compaq/cpqphpc	Compaq PCI Hot Plug Controller
		209 = /dev/compaq/cpqrid	Compaq Remote Insight Driver
		210 = /dev/impi/bt	IMPI coprocessor block transfer
		211 = /dev/impi/smic	IMPI coprocessor stream interface
		212 = /dev/watchdogs/0	First watchdog device
		213 = /dev/watchdogs/1	Second watchdog device
		214 = /dev/watchdogs/2	Third watchdog device
		215 = /dev/watchdogs/3	Fourth watchdog device
		216 = /dev/fujitsu/apanel	Fujitsu/Siemens application panel
		217 = /dev/ni/natmotn		National Instruments Motion
		218 = /dev/kchuid	Inter-process chuid control
		219 = /dev/modems/mwave	MWave modem firmware upload
		220 = /dev/mptctl	Message passing technology (MPT) control
		221 = /dev/mvista/hssdsi	Montavista PICMG hot swap system driver
		222 = /dev/mvista/hasi		Montavista PICMG high availability
		223 = /dev/input/uinput		User level driver support for input
		224 = /dev/tpm		TCPA TPM driver
		225 = /dev/pps		Pulse Per Second driver
		226 = /dev/systrace	Systrace device
		227 = /dev/mcelog	X86_64 Machine Check Exception driver
		228 = /dev/hpet		HPET driver
		229 = /dev/fuse		Fuse (virtual filesystem in user-space)
		230 = /dev/midishare	MidiShare driver
		231 = /dev/snapshot	System memory snapshot device
		232 = /dev/kvm		Kernel-based virtual machine (hardware virtualization extensions)
		233 = /dev/kmview	View-OS A process with a view
		234 = /dev/btrfs-control	Btrfs control device
		235 = /dev/autofs	Autofs control device
		236 = /dev/mapper/control	Device-Mapper control device
		237 = /dev/loop-control Loopback control device
		238 = /dev/vhost-net	Host kernel accelerator for virtio net
		239 = /dev/uhid		User-space I/O driver support for HID subsystem
		240 = /dev/userio	Serio driver testing device
		241 = /dev/vhost-vsock	Host kernel driver for virtio vsock
		242 = /dev/rfkill	Turning off radio transmissions (rfkill)

		243-254			Reserved for local use
		255			Reserved for MISC_DYNAMIC_MINOR

  11 char	Raw keyboard device	(Linux/SPARC only)
		  0 = /dev/kbd		Raw keyboard device

  11 char	Serial Mux device	(Linux/PA-RISC only)
		  0 = /dev/ttyB0	First mux port
		  1 = /dev/ttyB1	Second mux port
		    ...

  11 block	SCSI CD-ROM devices
		  0 = /dev/scd0		First SCSI CD-ROM
		  1 = /dev/scd1		Second SCSI CD-ROM
		    ...

		The prefix /dev/sr (instead of /dev/scd) has been deprecated.

  12 char	QIC-02 tape
		  2 = /dev/ntpqic11	QIC-11, no rewind-on-close
		  3 = /dev/tpqic11	QIC-11, rewind-on-close
		  4 = /dev/ntpqic24	QIC-24, no rewind-on-close
		  5 = /dev/tpqic24	QIC-24, rewind-on-close
		  6 = /dev/ntpqic120	QIC-120, no rewind-on-close
		  7 = /dev/tpqic120	QIC-120, rewind-on-close
		  8 = /dev/ntpqic150	QIC-150, no rewind-on-close
		  9 = /dev/tpqic150	QIC-150, rewind-on-close

		The device names specified are proposed -- if there
		are "standard" names for these devices, please let me know.

  12 block

  13 char	Input core
		  0 = /dev/input/js0	First joystick
		  1 = /dev/input/js1	Second joystick
		    ...
		 32 = /dev/input/mouse0	First mouse
		 33 = /dev/input/mouse1	Second mouse
		    ...
		 63 = /dev/input/mice	Unified mouse
		 64 = /dev/input/event0	First event queue
		 65 = /dev/input/event1	Second event queue
		    ...

		Each device type has 5 bits (32 minors).

  13 block	Previously used for the XT disk (/dev/xdN)
		Deleted in kernel v3.9.

  14 char	Open Sound System (OSS)
		  0 = /dev/mixer	Mixer control
		  1 = /dev/sequencer	Audio sequencer
		  2 = /dev/midi00	First MIDI port
		  3 = /dev/dsp		Digital audio
		  4 = /dev/audio	Sun-compatible digital audio
		  6 =
		  7 = /dev/audioctl	SPARC audio control device
		  8 = /dev/sequencer2	Sequencer -- alternate device
		 16 = /dev/mixer1	Second soundcard mixer control
		 17 = /dev/patmgr0	Sequencer patch manager
		 18 = /dev/midi01	Second MIDI port
		 19 = /dev/dsp1		Second soundcard digital audio
		 20 = /dev/audio1	Second soundcard Sun digital audio
		 33 = /dev/patmgr1	Sequencer patch manager
		 34 = /dev/midi02	Third MIDI port
		 50 = /dev/midi03	Fourth MIDI port

  14 block

  15 char	Joystick
		  0 = /dev/js0		First analog joystick
		  1 = /dev/js1		Second analog joystick
		    ...
		128 = /dev/djs0		First digital joystick
		129 = /dev/djs1		Second digital joystick
		    ...
  15 block	Sony CDU-31A/CDU-33A CD-ROM
		  0 = /dev/sonycd	Sony CDU-31a CD-ROM

  16 char	Non-SCSI scanners
		  0 = /dev/gs4500	Genius 4500 handheld scanner

  16 block	GoldStar CD-ROM
		  0 = /dev/gscd		GoldStar CD-ROM

  17 char	OBSOLETE (was Chase serial card)
		  0 = /dev/ttyH0	First Chase port
		  1 = /dev/ttyH1	Second Chase port
		    ...
  17 block	Optics Storage CD-ROM
		  0 = /dev/optcd	Optics Storage CD-ROM

  18 char	OBSOLETE (was Chase serial card - alternate devices)
		  0 = /dev/cuh0		Callout device for ttyH0
		  1 = /dev/cuh1		Callout device for ttyH1
		    ...
  18 block	Sanyo CD-ROM
		  0 = /dev/sjcd		Sanyo CD-ROM

  19 block	"Double" compressed disk
		  0 = /dev/double0	First compressed disk
		    ...
		  7 = /dev/double7	Eighth compressed disk
		128 = /dev/cdouble0	Mirror of first compressed disk
		    ...
		135 = /dev/cdouble7	Mirror of eighth compressed disk

		See the Double documentation for the meaning of the
		mirror devices.

  20 block	Hitachi CD-ROM (under development)
		  0 = /dev/hitcd	Hitachi CD-ROM

  21 char	Generic SCSI access
		  0 = /dev/sg0		First generic SCSI device
		  1 = /dev/sg1		Second generic SCSI device
		    ...

		Most distributions name these /dev/sga, /dev/sgb...;
		this sets an unnecessary limit of 26 SCSI devices in
		the system and is counter to standard Linux
		device-naming practice.

  21 block	Acorn MFM hard drive interface
		  0 = /dev/mfma		First MFM drive whole disk
		 64 = /dev/mfmb		Second MFM drive whole disk

		This device is used on the ARM-based Acorn RiscPC.
		Partitions are handled the same way as for IDE disks
		(see major number 3).

  22 char	Digiboard serial card
		  0 = /dev/ttyD0	First Digiboard port
		  1 = /dev/ttyD1	Second Digiboard port
		    ...
  22 block	Second IDE hard disk/CD-ROM interface
		  0 = /dev/hdc		Master: whole disk (or CD-ROM)
		 64 = /dev/hdd		Slave: whole disk (or CD-ROM)

		Partitions are handled the same way as for the first
		interface (see major number 3).

  23 char	Digiboard serial card - alternate devices
		  0 = /dev/cud0		Callout device for ttyD0
		  1 = /dev/cud1		Callout device for ttyD1
		      ...
  23 block	Mitsumi proprietary CD-ROM
		  0 = /dev/mcd		Mitsumi CD-ROM

  24 char	Stallion serial card
		  0 = /dev/ttyE0	Stallion port 0 card 0
		  1 = /dev/ttyE1	Stallion port 1 card 0
		    ...
		 64 = /dev/ttyE64	Stallion port 0 card 1
		 65 = /dev/ttyE65	Stallion port 1 card 1
		      ...
		128 = /dev/ttyE128	Stallion port 0 card 2
		129 = /dev/ttyE129	Stallion port 1 card 2
		    ...
		192 = /dev/ttyE192	Stallion port 0 card 3
		193 = /dev/ttyE193	Stallion port 1 card 3
		    ...
  24 block	Sony CDU-535 CD-ROM
		  0 = /dev/cdu535	Sony CDU-535 CD-ROM

  25 char	Stallion serial card - alternate devices
		  0 = /dev/cue0		Callout device for ttyE0
		  1 = /dev/cue1		Callout device for ttyE1
		    ...
		 64 = /dev/cue64	Callout device for ttyE64
		 65 = /dev/cue65	Callout device for ttyE65
		    ...
		128 = /dev/cue128	Callout device for ttyE128
		129 = /dev/cue129	Callout device for ttyE129
		    ...
		192 = /dev/cue192	Callout device for ttyE192
		193 = /dev/cue193	Callout device for ttyE193
		      ...
  25 block	First Matsushita (Panasonic/SoundBlaster) CD-ROM
		  0 = /dev/sbpcd0	Panasonic CD-ROM controller 0 unit 0
		  1 = /dev/sbpcd1	Panasonic CD-ROM controller 0 unit 1
		  2 = /dev/sbpcd2	Panasonic CD-ROM controller 0 unit 2
		  3 = /dev/sbpcd3	Panasonic CD-ROM controller 0 unit 3

  26 char

  26 block	Second Matsushita (Panasonic/SoundBlaster) CD-ROM
		  0 = /dev/sbpcd4	Panasonic CD-ROM controller 1 unit 0
		  1 = /dev/sbpcd5	Panasonic CD-ROM controller 1 unit 1
		  2 = /dev/sbpcd6	Panasonic CD-ROM controller 1 unit 2
		  3 = /dev/sbpcd7	Panasonic CD-ROM controller 1 unit 3

  27 char	QIC-117 tape
		  0 = /dev/qft0		Unit 0, rewind-on-close
		  1 = /dev/qft1		Unit 1, rewind-on-close
		  2 = /dev/qft2		Unit 2, rewind-on-close
		  3 = /dev/qft3		Unit 3, rewind-on-close
		  4 = /dev/nqft0	Unit 0, no rewind-on-close
		  5 = /dev/nqft1	Unit 1, no rewind-on-close
		  6 = /dev/nqft2	Unit 2, no rewind-on-close
		  7 = /dev/nqft3	Unit 3, no rewind-on-close
		 16 = /dev/zqft0	Unit 0, rewind-on-close, compression
		 17 = /dev/zqft1	Unit 1, rewind-on-close, compression
		 18 = /dev/zqft2	Unit 2, rewind-on-close, compression
		 19 = /dev/zqft3	Unit 3, rewind-on-close, compression
		 20 = /dev/nzqft0	Unit 0, no rewind-on-close, compression
		 21 = /dev/nzqft1	Unit 1, no rewind-on-close, compression
		 22 = /dev/nzqft2	Unit 2, no rewind-on-close, compression
		 23 = /dev/nzqft3	Unit 3, no rewind-on-close, compression
		 32 = /dev/rawqft0	Unit 0, rewind-on-close, no file marks
		 33 = /dev/rawqft1	Unit 1, rewind-on-close, no file marks
		 34 = /dev/rawqft2	Unit 2, rewind-on-close, no file marks
		 35 = /dev/rawqft3	Unit 3, rewind-on-close, no file marks
		 36 = /dev/nrawqft0	Unit 0, no rewind-on-close, no file marks
		 37 = /dev/nrawqft1	Unit 1, no rewind-on-close, no file marks
		 38 = /dev/nrawqft2	Unit 2, no rewind-on-close, no file marks
		 39 = /dev/nrawqft3	Unit 3, no rewind-on-close, no file marks

  27 block	Third Matsushita (Panasonic/SoundBlaster) CD-ROM
		  0 = /dev/sbpcd8	Panasonic CD-ROM controller 2 unit 0
		  1 = /dev/sbpcd9	Panasonic CD-ROM controller 2 unit 1
		  2 = /dev/sbpcd10	Panasonic CD-ROM controller 2 unit 2
		  3 = /dev/sbpcd11	Panasonic CD-ROM controller 2 unit 3

  28 char	Stallion serial card - card programming
		  0 = /dev/staliomem0	First Stallion card I/O memory
		  1 = /dev/staliomem1	Second Stallion card I/O memory
		  2 = /dev/staliomem2	Third Stallion card I/O memory
		  3 = /dev/staliomem3	Fourth Stallion card I/O memory

  28 char	Atari SLM ACSI laser printer (68k/Atari)
		  0 = /dev/slm0		First SLM laser printer
		  1 = /dev/slm1		Second SLM laser printer
		    ...
  28 block	Fourth Matsushita (Panasonic/SoundBlaster) CD-ROM
		  0 = /dev/sbpcd12	Panasonic CD-ROM controller 3 unit 0
		  1 = /dev/sbpcd13	Panasonic CD-ROM controller 3 unit 1
		  2 = /dev/sbpcd14	Panasonic CD-ROM controller 3 unit 2
		  3 = /dev/sbpcd15	Panasonic CD-ROM controller 3 unit 3

  28 block	ACSI disk (68k/Atari)
		  0 = /dev/ada		First ACSI disk whole disk
		 16 = /dev/adb		Second ACSI disk whole disk
		 32 = /dev/adc		Third ACSI disk whole disk
		    ...
		240 = /dev/adp		16th ACSI disk whole disk

		Partitions are handled in the same way as for IDE
		disks (see major number 3) except that the limit on
		partitions is 15, like SCSI.

  29 char	Universal frame buffer
		  0 = /dev/fb0		First frame buffer
		  1 = /dev/fb1		Second frame buffer
		    ...
		 31 = /dev/fb31		32nd frame buffer

  29 block	Aztech/Orchid/Okano/Wearnes CD-ROM
		  0 = /dev/aztcd	Aztech CD-ROM

  30 char	iBCS-2 compatibility devices
		  0 = /dev/socksys	Socket access
		  1 = /dev/spx		SVR3 local X interface
		 32 = /dev/inet/ip	Network access
		 33 = /dev/inet/icmp
		 34 = /dev/inet/ggp
		 35 = /dev/inet/ipip
		 36 = /dev/inet/tcp
		 37 = /dev/inet/egp
		 38 = /dev/inet/pup
		 39 = /dev/inet/udp
		 40 = /dev/inet/idp
		 41 = /dev/inet/rawip

		Additionally, iBCS-2 requires the following links:

		/dev/ip -> /dev/inet/ip
		/dev/icmp -> /dev/inet/icmp
		/dev/ggp -> /dev/inet/ggp
		/dev/ipip -> /dev/inet/ipip
		/dev/tcp -> /dev/inet/tcp
		/dev/egp -> /dev/inet/egp
		/dev/pup -> /dev/inet/pup
		/dev/udp -> /dev/inet/udp
		/dev/idp -> /dev/inet/idp
		/dev/rawip -> /dev/inet/rawip
		/dev/inet/arp -> /dev/inet/udp
		/dev/inet/rip -> /dev/inet/udp
		/dev/nfsd -> /dev/socksys
		/dev/X0R -> /dev/null (? apparently not required ?)

  30 block	Philips LMS CM-205 CD-ROM
		  0 = /dev/cm205cd	Philips LMS CM-205 CD-ROM

		/dev/lmscd is an older name for this device.  This
		driver does not work with the CM-205MS CD-ROM.

  31 char	MPU-401 MIDI
		  0 = /dev/mpu401data	MPU-401 data port
		  1 = /dev/mpu401stat	MPU-401 status port

  31 block	ROM/flash memory card
		  0 = /dev/rom0		First ROM card (rw)
		      ...
		  7 = /dev/rom7		Eighth ROM card (rw)
		  8 = /dev/rrom0	First ROM card (ro)
		    ...
		 15 = /dev/rrom7	Eighth ROM card (ro)
		 16 = /dev/flash0	First flash memory card (rw)
		    ...
		 23 = /dev/flash7	Eighth flash memory card (rw)
		 24 = /dev/rflash0	First flash memory card (ro)
		    ...
		 31 = /dev/rflash7	Eighth flash memory card (ro)

		The read-write (rw) devices support back-caching
		written data in RAM, as well as writing to flash RAM
		devices.  The read-only devices (ro) support reading
		only.

  32 char	Specialix serial card
		  0 = /dev/ttyX0	First Specialix port
		  1 = /dev/ttyX1	Second Specialix port
		    ...
  32 block	Philips LMS CM-206 CD-ROM
		  0 = /dev/cm206cd	Philips LMS CM-206 CD-ROM

  33 char	Specialix serial card - alternate devices
		  0 = /dev/cux0		Callout device for ttyX0
		  1 = /dev/cux1		Callout device for ttyX1
		    ...
  33 block	Third IDE hard disk/CD-ROM interface
		  0 = /dev/hde		Master: whole disk (or CD-ROM)
		 64 = /dev/hdf		Slave: whole disk (or CD-ROM)

		Partitions are handled the same way as for the first
		interface (see major number 3).

  34 char	Z8530 HDLC driver
		  0 = /dev/scc0		First Z8530, first port
		  1 = /dev/scc1		First Z8530, second port
		  2 = /dev/scc2		Second Z8530, first port
		  3 = /dev/scc3		Second Z8530, second port
		    ...

		In a previous version these devices were named
		/dev/sc1 for /dev/scc0, /dev/sc2 for /dev/scc1, and so
		on.

  34 block	Fourth IDE hard disk/CD-ROM interface
		  0 = /dev/hdg		Master: whole disk (or CD-ROM)
		 64 = /dev/hdh		Slave: whole disk (or CD-ROM)

		Partitions are handled the same way as for the first
		interface (see major number 3).

  35 char	tclmidi MIDI driver
		  0 = /dev/midi0	First MIDI port, kernel timed
		  1 = /dev/midi1	Second MIDI port, kernel timed
		  2 = /dev/midi2	Third MIDI port, kernel timed
		  3 = /dev/midi3	Fourth MIDI port, kernel timed
		 64 = /dev/rmidi0	First MIDI port, untimed
		 65 = /dev/rmidi1	Second MIDI port, untimed
		 66 = /dev/rmidi2	Third MIDI port, untimed
		 67 = /dev/rmidi3	Fourth MIDI port, untimed
		128 = /dev/smpte0	First MIDI port, SMPTE timed
		129 = /dev/smpte1	Second MIDI port, SMPTE timed
		130 = /dev/smpte2	Third MIDI port, SMPTE timed
		131 = /dev/smpte3	Fourth MIDI port, SMPTE timed

  35 block	Slow memory ramdisk
		  0 = /dev/slram	Slow memory ramdisk

  36 char	Netlink support
		  0 = /dev/route	Routing, device updates, kernel to user
		  1 = /dev/skip		enSKIP security cache control
		  3 = /dev/fwmonitor	Firewall packet copies
		 16 = /dev/tap0		First Ethertap device
		    ...
		 31 = /dev/tap15	16th Ethertap device

  36 block	OBSOLETE (was MCA ESDI hard disk)

  37 char	IDE tape
		  0 = /dev/ht0		First IDE tape
		  1 = /dev/ht1		Second IDE tape
		    ...
		128 = /dev/nht0		First IDE tape, no rewind-on-close
		129 = /dev/nht1		Second IDE tape, no rewind-on-close
		    ...

		Currently, only one IDE tape drive is supported.

  37 block	Zorro II ramdisk
		  0 = /dev/z2ram	Zorro II ramdisk

  38 char	Myricom PCI Myrinet board
		  0 = /dev/mlanai0	First Myrinet board
		  1 = /dev/mlanai1	Second Myrinet board
		    ...

		This device is used for status query, board control
		and "user level packet I/O."  This board is also
		accessible as a standard networking "eth" device.

  38 block	OBSOLETE (was Linux/AP+)

  39 char	ML-16P experimental I/O board
		  0 = /dev/ml16pa-a0	First card, first analog channel
		  1 = /dev/ml16pa-a1	First card, second analog channel
		    ...
		 15 = /dev/ml16pa-a15	First card, 16th analog channel
		 16 = /dev/ml16pa-d	First card, digital lines
		 17 = /dev/ml16pa-c0	First card, first counter/timer
		 18 = /dev/ml16pa-c1	First card, second counter/timer
		 19 = /dev/ml16pa-c2	First card, third counter/timer
		 32 = /dev/ml16pb-a0	Second card, first analog channel
		 33 = /dev/ml16pb-a1	Second card, second analog channel
		    ...
		 47 = /dev/ml16pb-a15	Second card, 16th analog channel
		 48 = /dev/ml16pb-d	Second card, digital lines
		 49 = /dev/ml16pb-c0	Second card, first counter/timer
		 50 = /dev/ml16pb-c1	Second card, second counter/timer
		 51 = /dev/ml16pb-c2	Second card, third counter/timer
		      ...
  39 block

  40 char

  40 block

  41 char	Yet Another Micro Monitor
		  0 = /dev/yamm		Yet Another Micro Monitor

  41 block

  42 char	Demo/sample use

  42 block	Demo/sample use

		This number is intended for use in sample code, as
		well as a general "example" device number.  It
		should never be used for a device driver that is being
		distributed; either obtain an official number or use
		the local/experimental range.  The sudden addition or
		removal of a driver with this number should not cause
		ill effects to the system (bugs excepted.)

		IN PARTICULAR, ANY DISTRIBUTION WHICH CONTAINS A
		DEVICE DRIVER USING MAJOR NUMBER 42 IS NONCOMPLIANT.

  43 char	isdn4linux virtual modem
		  0 = /dev/ttyI0	First virtual modem
		    ...
		 63 = /dev/ttyI63	64th virtual modem

  43 block	Network block devices
		  0 = /dev/nb0		First network block device
		  1 = /dev/nb1		Second network block device
		    ...

		Network Block Device is somehow similar to loopback
		devices: If you read from it, it sends packet across
		network asking server for data. If you write to it, it
		sends packet telling server to write. It could be used
		to mounting filesystems over the net, swapping over
		the net, implementing block device in userland etc.

  44 char	isdn4linux virtual modem - alternate devices
		  0 = /dev/cui0		Callout device for ttyI0
		    ...
		 63 = /dev/cui63	Callout device for ttyI63

  44 block	Flash Translation Layer (FTL) filesystems
		  0 = /dev/ftla		FTL on first Memory Technology Device
		 16 = /dev/ftlb		FTL on second Memory Technology Device
		 32 = /dev/ftlc		FTL on third Memory Technology Device
		    ...
		240 = /dev/ftlp		FTL on 16th Memory Technology Device

		Partitions are handled in the same way as for IDE
		disks (see major number 3) except that the partition
		limit is 15 rather than 63 per disk (same as SCSI.)

  45 char	isdn4linux ISDN BRI driver
		  0 = /dev/isdn0	First virtual B channel raw data
		    ...
		 63 = /dev/isdn63	64th virtual B channel raw data
		 64 = /dev/isdnctrl0	First channel control/debug
		    ...
		127 = /dev/isdnctrl63	64th channel control/debug

		128 = /dev/ippp0	First SyncPPP device
		    ...
		191 = /dev/ippp63	64th SyncPPP device

		255 = /dev/isdninfo	ISDN monitor interface

  45 block	Parallel port IDE disk devices
		  0 = /dev/pda		First parallel port IDE disk
		 16 = /dev/pdb		Second parallel port IDE disk
		 32 = /dev/pdc		Third parallel port IDE disk
		 48 = /dev/pdd		Fourth parallel port IDE disk

		Partitions are handled in the same way as for IDE
		disks (see major number 3) except that the partition
		limit is 15 rather than 63 per disk.

  46 char	Comtrol Rocketport serial card
		  0 = /dev/ttyR0	First Rocketport port
		  1 = /dev/ttyR1	Second Rocketport port
		    ...
  46 block	Parallel port ATAPI CD-ROM devices
		  0 = /dev/pcd0		First parallel port ATAPI CD-ROM
		  1 = /dev/pcd1		Second parallel port ATAPI CD-ROM
		  2 = /dev/pcd2		Third parallel port ATAPI CD-ROM
		  3 = /dev/pcd3		Fourth parallel port ATAPI CD-ROM

  47 char	Comtrol Rocketport serial card - alternate devices
		  0 = /dev/cur0		Callout device for ttyR0
		  1 = /dev/cur1		Callout device for ttyR1
		    ...
  47 block	Parallel port ATAPI disk devices
		  0 = /dev/pf0		First parallel port ATAPI disk
		  1 = /dev/pf1		Second parallel port ATAPI disk
		  2 = /dev/pf2		Third parallel port ATAPI disk
		  3 = /dev/pf3		Fourth parallel port ATAPI disk

		This driver is intended for floppy disks and similar
		devices and hence does not support partitioning.

  48 char	SDL RISCom serial card
		  0 = /dev/ttyL0	First RISCom port
		  1 = /dev/ttyL1	Second RISCom port
		    ...
  48 block	Mylex DAC960 PCI RAID controller; first controller
		  0 = /dev/rd/c0d0	First disk, whole disk
		  8 = /dev/rd/c0d1	Second disk, whole disk
		    ...
		248 = /dev/rd/c0d31	32nd disk, whole disk

		For partitions add:
		  0 = /dev/rd/c?d?	Whole disk
		  1 = /dev/rd/c?d?p1	First partition
		    ...
		  7 = /dev/rd/c?d?p7	Seventh partition

  49 char	SDL RISCom serial card - alternate devices
		  0 = /dev/cul0		Callout device for ttyL0
		  1 = /dev/cul1		Callout device for ttyL1
		    ...
  49 block	Mylex DAC960 PCI RAID controller; second controller
		  0 = /dev/rd/c1d0	First disk, whole disk
		  8 = /dev/rd/c1d1	Second disk, whole disk
		    ...
		248 = /dev/rd/c1d31	32nd disk, whole disk

		Partitions are handled as for major 48.

  50 char	Reserved for GLINT

  50 block	Mylex DAC960 PCI RAID controller; third controller
		  0 = /dev/rd/c2d0	First disk, whole disk
		  8 = /dev/rd/c2d1	Second disk, whole disk
		    ...
		248 = /dev/rd/c2d31	32nd disk, whole disk

  51 char	Baycom radio modem OR Radio Tech BIM-XXX-RS232 radio modem
		  0 = /dev/bc0		First Baycom radio modem
		  1 = /dev/bc1		Second Baycom radio modem
		    ...
  51 block	Mylex DAC960 PCI RAID controller; fourth controller
		  0 = /dev/rd/c3d0	First disk, whole disk
		  8 = /dev/rd/c3d1	Second disk, whole disk
		    ...
		248 = /dev/rd/c3d31	32nd disk, whole disk

		Partitions are handled as for major 48.

  52 char	Spellcaster DataComm/BRI ISDN card
		  0 = /dev/dcbri0	First DataComm card
		  1 = /dev/dcbri1	Second DataComm card
		  2 = /dev/dcbri2	Third DataComm card
		  3 = /dev/dcbri3	Fourth DataComm card

  52 block	Mylex DAC960 PCI RAID controller; fifth controller
		  0 = /dev/rd/c4d0	First disk, whole disk
		  8 = /dev/rd/c4d1	Second disk, whole disk
		    ...
		248 = /dev/rd/c4d31	32nd disk, whole disk

		Partitions are handled as for major 48.

  53 char	BDM interface for remote debugging MC683xx microcontrollers
		  0 = /dev/pd_bdm0	PD BDM interface on lp0
		  1 = /dev/pd_bdm1	PD BDM interface on lp1
		  2 = /dev/pd_bdm2	PD BDM interface on lp2
		  4 = /dev/icd_bdm0	ICD BDM interface on lp0
		  5 = /dev/icd_bdm1	ICD BDM interface on lp1
		  6 = /dev/icd_bdm2	ICD BDM interface on lp2

		This device is used for the interfacing to the MC683xx
		microcontrollers via Background Debug Mode by use of a
		Parallel Port interface. PD is the Motorola Public
		Domain Interface and ICD is the commercial interface
		by P&E.

  53 block	Mylex DAC960 PCI RAID controller; sixth controller
		  0 = /dev/rd/c5d0	First disk, whole disk
		  8 = /dev/rd/c5d1	Second disk, whole disk
		    ...
		248 = /dev/rd/c5d31	32nd disk, whole disk

		Partitions are handled as for major 48.

  54 char	Electrocardiognosis Holter serial card
		  0 = /dev/holter0	First Holter port
		  1 = /dev/holter1	Second Holter port
		  2 = /dev/holter2	Third Holter port

		A custom serial card used by Electrocardiognosis SRL
		<mseritan@ottonel.pub.ro> to transfer data from Holter
		24-hour heart monitoring equipment.

  54 block	Mylex DAC960 PCI RAID controller; seventh controller
		  0 = /dev/rd/c6d0	First disk, whole disk
		  8 = /dev/rd/c6d1	Second disk, whole disk
		    ...
		248 = /dev/rd/c6d31	32nd disk, whole disk

		Partitions are handled as for major 48.

  55 char	DSP56001 digital signal processor
		  0 = /dev/dsp56k	First DSP56001

  55 block	Mylex DAC960 PCI RAID controller; eighth controller
		  0 = /dev/rd/c7d0	First disk, whole disk
		  8 = /dev/rd/c7d1	Second disk, whole disk
		    ...
		248 = /dev/rd/c7d31	32nd disk, whole disk

		Partitions are handled as for major 48.

  56 char	Apple Desktop Bus
		  0 = /dev/adb		ADB bus control

		Additional devices will be added to this number, all
		starting with /dev/adb.

  56 block	Fifth IDE hard disk/CD-ROM interface
		  0 = /dev/hdi		Master: whole disk (or CD-ROM)
		 64 = /dev/hdj		Slave: whole disk (or CD-ROM)

		Partitions are handled the same way as for the first
		interface (see major number 3).

  57 char	Hayes ESP serial card
		  0 = /dev/ttyP0	First ESP port
		  1 = /dev/ttyP1	Second ESP port
		    ...

  57 block	Sixth IDE hard disk/CD-ROM interface
		  0 = /dev/hdk		Master: whole disk (or CD-ROM)
		 64 = /dev/hdl		Slave: whole disk (or CD-ROM)

		Partitions are handled the same way as for the first
		interface (see major number 3).

  58 char	Hayes ESP serial card - alternate devices
		  0 = /dev/cup0		Callout device for ttyP0
		  1 = /dev/cup1		Callout device for ttyP1
		    ...

  58 block	Reserved for logical volume manager

  59 char	sf firewall package
		  0 = /dev/firewall	Communication with sf kernel module

  59 block	Generic PDA filesystem device
		  0 = /dev/pda0		First PDA device
		  1 = /dev/pda1		Second PDA device
		    ...

		The pda devices are used to mount filesystems on
		remote pda's (basically slow handheld machines with
		proprietary OS's and limited memory and storage
		running small fs translation drivers) through serial /
		IRDA / parallel links.

		NAMING CONFLICT -- PROPOSED REVISED NAME /dev/rpda0 etc

  60-63 char	LOCAL/EXPERIMENTAL USE

  60-63 block	LOCAL/EXPERIMENTAL USE
		Allocated for local/experimental use.  For devices not
		assigned official numbers, these ranges should be
		used in order to avoid conflicting with future assignments.

  64 char	ENskip kernel encryption package
		  0 = /dev/enskip	Communication with ENskip kernel module

  64 block	Scramdisk/DriveCrypt encrypted devices
		  0 = /dev/scramdisk/master    Master node for ioctls
		  1 = /dev/scramdisk/1         First encrypted device
		  2 = /dev/scramdisk/2         Second encrypted device
		  ...
		255 = /dev/scramdisk/255       255th encrypted device

		The filename of the encrypted container and the passwords
		are sent via ioctls (using the sdmount tool) to the master
		node which then activates them via one of the
		/dev/scramdisk/x nodes for loop mounting (all handled
		through the sdmount tool).

		Requested by: andy@scramdisklinux.org

  65 char	Sundance "plink" Transputer boards (obsolete, unused)
		  0 = /dev/plink0	First plink device
		  1 = /dev/plink1	Second plink device
		  2 = /dev/plink2	Third plink device
		  3 = /dev/plink3	Fourth plink device
		 64 = /dev/rplink0	First plink device, raw
		 65 = /dev/rplink1	Second plink device, raw
		 66 = /dev/rplink2	Third plink device, raw
		 67 = /dev/rplink3	Fourth plink device, raw
		128 = /dev/plink0d	First plink device, debug
		129 = /dev/plink1d	Second plink device, debug
		130 = /dev/plink2d	Third plink device, debug
		131 = /dev/plink3d	Fourth plink device, debug
		192 = /dev/rplink0d	First plink device, raw, debug
		193 = /dev/rplink1d	Second plink device, raw, debug
		194 = /dev/rplink2d	Third plink device, raw, debug
		195 = /dev/rplink3d	Fourth plink device, raw, debug

		This is a commercial driver; contact James Howes
		<jth@prosig.demon.co.uk> for information.

  65 block	SCSI disk devices (16-31)
		  0 = /dev/sdq		17th SCSI disk whole disk
		 16 = /dev/sdr		18th SCSI disk whole disk
		 32 = /dev/sds		19th SCSI disk whole disk
		    ...
		240 = /dev/sdaf		32nd SCSI disk whole disk

		Partitions are handled in the same way as for IDE
		disks (see major number 3) except that the limit on
		partitions is 15.

  66 char	YARC PowerPC PCI coprocessor card
		  0 = /dev/yppcpci0	First YARC card
		  1 = /dev/yppcpci1	Second YARC card
		    ...

  66 block	SCSI disk devices (32-47)
		  0 = /dev/sdag		33th SCSI disk whole disk
		 16 = /dev/sdah		34th SCSI disk whole disk
		 32 = /dev/sdai		35th SCSI disk whole disk
		    ...
		240 = /dev/sdav		48nd SCSI disk whole disk

		Partitions are handled in the same way as for IDE
		disks (see major number 3) except that the limit on
		partitions is 15.

  67 char	Coda network file system
		  0 = /dev/cfs0		Coda cache manager

		See http://www.coda.cs.cmu.edu for information about Coda.

  67 block	SCSI disk devices (48-63)
		  0 = /dev/sdaw		49th SCSI disk whole disk
		 16 = /dev/sdax		50th SCSI disk whole disk
		 32 = /dev/sday		51st SCSI disk whole disk
		    ...
		240 = /dev/sdbl		64th SCSI disk whole disk

		Partitions are handled in the same way as for IDE
		disks (see major number 3) except that the limit on
		partitions is 15.

  68 char	CAPI 2.0 interface
		  0 = /dev/capi20	Control device
		  1 = /dev/capi20.00	First CAPI 2.0 application
		  2 = /dev/capi20.01	Second CAPI 2.0 application
		    ...
		 20 = /dev/capi20.19	19th CAPI 2.0 application

		ISDN CAPI 2.0 driver for use with CAPI 2.0
		applications; currently supports the AVM B1 card.

  68 block	SCSI disk devices (64-79)
		  0 = /dev/sdbm		65th SCSI disk whole disk
		 16 = /dev/sdbn		66th SCSI disk whole disk
		 32 = /dev/sdbo		67th SCSI disk whole disk
		    ...
		240 = /dev/sdcb		80th SCSI disk whole disk

		Partitions are handled in the same way as for IDE
		disks (see major number 3) except that the limit on
		partitions is 15.

  69 char	MA16 numeric accelerator card
		  0 = /dev/ma16		Board memory access

  69 block	SCSI disk devices (80-95)
		  0 = /dev/sdcc		81st SCSI disk whole disk
		 16 = /dev/sdcd		82nd SCSI disk whole disk
		 32 = /dev/sdce		83th SCSI disk whole disk
		    ...
		240 = /dev/sdcr		96th SCSI disk whole disk

		Partitions are handled in the same way as for IDE
		disks (see major number 3) except that the limit on
		partitions is 15.

  70 char	SpellCaster Protocol Services Interface
		  0 = /dev/apscfg	Configuration interface
		  1 = /dev/apsauth	Authentication interface
		  2 = /dev/apslog	Logging interface
		  3 = /dev/apsdbg	Debugging interface
		 64 = /dev/apsisdn	ISDN command interface
		 65 = /dev/apsasync	Async command interface
		128 = /dev/apsmon	Monitor interface

  70 block	SCSI disk devices (96-111)
		  0 = /dev/sdcs		97th SCSI disk whole disk
		 16 = /dev/sdct		98th SCSI disk whole disk
		 32 = /dev/sdcu		99th SCSI disk whole disk
		    ...
		240 = /dev/sddh		112nd SCSI disk whole disk

		Partitions are handled in the same way as for IDE
		disks (see major number 3) except that the limit on
		partitions is 15.

  71 char	Computone IntelliPort II serial card
		  0 = /dev/ttyF0	IntelliPort II board 0, port 0
		  1 = /dev/ttyF1	IntelliPort II board 0, port 1
		    ...
		 63 = /dev/ttyF63	IntelliPort II board 0, port 63
		 64 = /dev/ttyF64	IntelliPort II board 1, port 0
		 65 = /dev/ttyF65	IntelliPort II board 1, port 1
		    ...
		127 = /dev/ttyF127	IntelliPort II board 1, port 63
		128 = /dev/ttyF128	IntelliPort II board 2, port 0
		129 = /dev/ttyF129	IntelliPort II board 2, port 1
		    ...
		191 = /dev/ttyF191	IntelliPort II board 2, port 63
		192 = /dev/ttyF192	IntelliPort II board 3, port 0
		193 = /dev/ttyF193	IntelliPort II board 3, port 1
		    ...
		255 = /dev/ttyF255	IntelliPort II board 3, port 63

  71 block	SCSI disk devices (112-127)
		  0 = /dev/sddi		113th SCSI disk whole disk
		 16 = /dev/sddj		114th SCSI disk whole disk
		 32 = /dev/sddk		115th SCSI disk whole disk
		    ...
		240 = /dev/sddx		128th SCSI disk whole disk

		Partitions are handled in the same way as for IDE
		disks (see major number 3) except that the limit on
		partitions is 15.

  72 char	Computone IntelliPort II serial card - alternate devices
		  0 = /dev/cuf0		Callout device for ttyF0
		  1 = /dev/cuf1		Callout device for ttyF1
		    ...
		 63 = /dev/cuf63	Callout device for ttyF63
		 64 = /dev/cuf64	Callout device for ttyF64
		 65 = /dev/cuf65	Callout device for ttyF65
		    ...
		127 = /dev/cuf127	Callout device for ttyF127
		128 = /dev/cuf128	Callout device for ttyF128
		129 = /dev/cuf129	Callout device for ttyF129
		    ...
		191 = /dev/cuf191	Callout device for ttyF191
		192 = /dev/cuf192	Callout device for ttyF192
		193 = /dev/cuf193	Callout device for ttyF193
		    ...
		255 = /dev/cuf255	Callout device for ttyF255

  72 block	Compaq Intelligent Drive Array, first controller
		  0 = /dev/ida/c0d0	First logical drive whole disk
		 16 = /dev/ida/c0d1	Second logical drive whole disk
		    ...
		240 = /dev/ida/c0d15	16th logical drive whole disk

		Partitions are handled the same way as for Mylex
		DAC960 (see major number 48) except that the limit on
		partitions is 15.

  73 char	Computone IntelliPort II serial card - control devices
		  0 = /dev/ip2ipl0	Loadware device for board 0
		  1 = /dev/ip2stat0	Status device for board 0
		  4 = /dev/ip2ipl1	Loadware device for board 1
		  5 = /dev/ip2stat1	Status device for board 1
		  8 = /dev/ip2ipl2	Loadware device for board 2
		  9 = /dev/ip2stat2	Status device for board 2
		 12 = /dev/ip2ipl3	Loadware device for board 3
		 13 = /dev/ip2stat3	Status device for board 3

  73 block	Compaq Intelligent Drive Array, second controller
		  0 = /dev/ida/c1d0	First logical drive whole disk
		 16 = /dev/ida/c1d1	Second logical drive whole disk
		    ...
		240 = /dev/ida/c1d15	16th logical drive whole disk

		Partitions are handled the same way as for Mylex
		DAC960 (see major number 48) except that the limit on
		partitions is 15.

  74 char	SCI bridge
		  0 = /dev/SCI/0	SCI device 0
		  1 = /dev/SCI/1	SCI device 1
		    ...

		Currently for Dolphin Interconnect Solutions' PCI-SCI
		bridge.

  74 block	Compaq Intelligent Drive Array, third controller
		  0 = /dev/ida/c2d0	First logical drive whole disk
		 16 = /dev/ida/c2d1	Second logical drive whole disk
		    ...
		240 = /dev/ida/c2d15	16th logical drive whole disk

		Partitions are handled the same way as for Mylex
		DAC960 (see major number 48) except that the limit on
		partitions is 15.

  75 char	Specialix IO8+ serial card
		  0 = /dev/ttyW0	First IO8+ port, first card
		  1 = /dev/ttyW1	Second IO8+ port, first card
		    ...
		  8 = /dev/ttyW8	First IO8+ port, second card
		    ...

  75 block	Compaq Intelligent Drive Array, fourth controller
		  0 = /dev/ida/c3d0	First logical drive whole disk
		 16 = /dev/ida/c3d1	Second logical drive whole disk
		    ...
		240 = /dev/ida/c3d15	16th logical drive whole disk

		Partitions are handled the same way as for Mylex
		DAC960 (see major number 48) except that the limit on
		partitions is 15.

  76 char	Specialix IO8+ serial card - alternate devices
		  0 = /dev/cuw0		Callout device for ttyW0
		  1 = /dev/cuw1		Callout device for ttyW1
		    ...
		  8 = /dev/cuw8		Callout device for ttyW8
		    ...

  76 block	Compaq Intelligent Drive Array, fifth controller
		  0 = /dev/ida/c4d0	First logical drive whole disk
		 16 = /dev/ida/c4d1	Second logical drive whole disk
		    ...
		240 = /dev/ida/c4d15	16th logical drive whole disk

		Partitions are handled the same way as for Mylex
		DAC960 (see major number 48) except that the limit on
		partitions is 15.


  77 char	ComScire Quantum Noise Generator
		  0 = /dev/qng		ComScire Quantum Noise Generator

  77 block	Compaq Intelligent Drive Array, sixth controller
		  0 = /dev/ida/c5d0	First logical drive whole disk
		 16 = /dev/ida/c5d1	Second logical drive whole disk
		    ...
		240 = /dev/ida/c5d15	16th logical drive whole disk

		Partitions are handled the same way as for Mylex
		DAC960 (see major number 48) except that the limit on
		partitions is 15.

  78 char	PAM Software's multimodem boards
		  0 = /dev/ttyM0	First PAM modem
		  1 = /dev/ttyM1	Second PAM modem
		    ...

  78 block	Compaq Intelligent Drive Array, seventh controller
		  0 = /dev/ida/c6d0	First logical drive whole disk
		 16 = /dev/ida/c6d1	Second logical drive whole disk
		    ...
		240 = /dev/ida/c6d15	16th logical drive whole disk

		Partitions are handled the same way as for Mylex
		DAC960 (see major number 48) except that the limit on
		partitions is 15.

  79 char	PAM Software's multimodem boards - alternate devices
		  0 = /dev/cum0		Callout device for ttyM0
		  1 = /dev/cum1		Callout device for ttyM1
		    ...

  79 block	Compaq Intelligent Drive Array, eighth controller
		  0 = /dev/ida/c7d0	First logical drive whole disk
		 16 = /dev/ida/c7d1	Second logical drive whole disk
		    ...
		240 = /dev/ida/c715	16th logical drive whole disk

		Partitions are handled the same way as for Mylex
		DAC960 (see major number 48) except that the limit on
		partitions is 15.

  80 char	Photometrics AT200 CCD camera
		  0 = /dev/at200	Photometrics AT200 CCD camera

  80 block	I2O hard disk
		  0 = /dev/i2o/hda	First I2O hard disk, whole disk
		 16 = /dev/i2o/hdb	Second I2O hard disk, whole disk
		    ...
		240 = /dev/i2o/hdp	16th I2O hard disk, whole disk

		Partitions are handled in the same way as for IDE
		disks (see major number 3) except that the limit on
		partitions is 15.

  81 char	video4linux
		  0 = /dev/video0	Video capture/overlay device
		    ...
		 63 = /dev/video63	Video capture/overlay device
		 64 = /dev/radio0	Radio device
		    ...
		127 = /dev/radio63	Radio device
		128 = /dev/swradio0	Software Defined Radio device
		    ...
		191 = /dev/swradio63	Software Defined Radio device
		224 = /dev/vbi0		Vertical blank interrupt
		    ...
		255 = /dev/vbi31	Vertical blank interrupt

		Minor numbers are allocated dynamically unless
		CONFIG_VIDEO_FIXED_MINOR_RANGES (default n)
		configuration option is set.

  81 block	I2O hard disk
		  0 = /dev/i2o/hdq	17th I2O hard disk, whole disk
		 16 = /dev/i2o/hdr	18th I2O hard disk, whole disk
		    ...
		240 = /dev/i2o/hdaf	32nd I2O hard disk, whole disk

		Partitions are handled in the same way as for IDE
		disks (see major number 3) except that the limit on
		partitions is 15.

  82 char	WiNRADiO communications receiver card
		  0 = /dev/winradio0	First WiNRADiO card
		  1 = /dev/winradio1	Second WiNRADiO card
		    ...

		The driver and documentation may be obtained from
		https://www.winradio.com/

  82 block	I2O hard disk
		  0 = /dev/i2o/hdag	33rd I2O hard disk, whole disk
		 16 = /dev/i2o/hdah	34th I2O hard disk, whole disk
		    ...
		240 = /dev/i2o/hdav	48th I2O hard disk, whole disk

		Partitions are handled in the same way as for IDE
		disks (see major number 3) except that the limit on
		partitions is 15.

  83 char	Matrox mga_vid video driver
		 0 = /dev/mga_vid0	1st video card
		 1 = /dev/mga_vid1	2nd video card
		 2 = /dev/mga_vid2	3rd video card
		  ...
		15 = /dev/mga_vid15	16th video card

  83 block	I2O hard disk
		  0 = /dev/i2o/hdaw	49th I2O hard disk, whole disk
		 16 = /dev/i2o/hdax	50th I2O hard disk, whole disk
		    ...
		240 = /dev/i2o/hdbl	64th I2O hard disk, whole disk

		Partitions are handled in the same way as for IDE
		disks (see major number 3) except that the limit on
		partitions is 15.

  84 char	Ikon 1011[57] Versatec Greensheet Interface
		  0 = /dev/ihcp0	First Greensheet port
		  1 = /dev/ihcp1	Second Greensheet port

  84 block	I2O hard disk
		  0 = /dev/i2o/hdbm	65th I2O hard disk, whole disk
		 16 = /dev/i2o/hdbn	66th I2O hard disk, whole disk
		    ...
		240 = /dev/i2o/hdcb	80th I2O hard disk, whole disk

		Partitions are handled in the same way as for IDE
		disks (see major number 3) except that the limit on
		partitions is 15.

  85 char	Linux/SGI shared memory input queue
		  0 = /dev/shmiq	Master shared input queue
		  1 = /dev/qcntl0	First device pushed
		  2 = /dev/qcntl1	Second device pushed
		    ...

  85 block	I2O hard disk
		  0 = /dev/i2o/hdcc	81st I2O hard disk, whole disk
		 16 = /dev/i2o/hdcd	82nd I2O hard disk, whole disk
		    ...
		240 = /dev/i2o/hdcr	96th I2O hard disk, whole disk

		Partitions are handled in the same way as for IDE
		disks (see major number 3) except that the limit on
		partitions is 15.

  86 char	SCSI media changer
		  0 = /dev/sch0		First SCSI media changer
		  1 = /dev/sch1		Second SCSI media changer
		    ...

  86 block	I2O hard disk
		  0 = /dev/i2o/hdcs	97th I2O hard disk, whole disk
		 16 = /dev/i2o/hdct	98th I2O hard disk, whole disk
		    ...
		240 = /dev/i2o/hddh	112th I2O hard disk, whole disk

		Partitions are handled in the same way as for IDE
		disks (see major number 3) except that the limit on
		partitions is 15.

  87 char	Sony Control-A1 stereo control bus
		  0 = /dev/controla0	First device on chain
		  1 = /dev/controla1	Second device on chain
		    ...

  87 block	I2O hard disk
		  0 = /dev/i2o/hddi	113rd I2O hard disk, whole disk
		 16 = /dev/i2o/hddj	114th I2O hard disk, whole disk
		    ...
		240 = /dev/i2o/hddx	128th I2O hard disk, whole disk

		Partitions are handled in the same way as for IDE
		disks (see major number 3) except that the limit on
		partitions is 15.

  88 char	COMX synchronous serial card
		  0 = /dev/comx0	COMX channel 0
		  1 = /dev/comx1	COMX channel 1
		    ...

  88 block	Seventh IDE hard disk/CD-ROM interface
		  0 = /dev/hdm		Master: whole disk (or CD-ROM)
		 64 = /dev/hdn		Slave: whole disk (or CD-ROM)

		Partitions are handled the same way as for the first
		interface (see major number 3).

  89 char	I2C bus interface
		  0 = /dev/i2c-0	First I2C adapter
		  1 = /dev/i2c-1	Second I2C adapter
		    ...

  89 block	Eighth IDE hard disk/CD-ROM interface
		  0 = /dev/hdo		Master: whole disk (or CD-ROM)
		 64 = /dev/hdp		Slave: whole disk (or CD-ROM)

		Partitions are handled the same way as for the first
		interface (see major number 3).

  90 char	Memory Technology Device (RAM, ROM, Flash)
		  0 = /dev/mtd0		First MTD (rw)
		  1 = /dev/mtdr0	First MTD (ro)
		    ...
		 30 = /dev/mtd15	16th MTD (rw)
		 31 = /dev/mtdr15	16th MTD (ro)

  90 block	Ninth IDE hard disk/CD-ROM interface
		  0 = /dev/hdq		Master: whole disk (or CD-ROM)
		 64 = /dev/hdr		Slave: whole disk (or CD-ROM)

		Partitions are handled the same way as for the first
		interface (see major number 3).

  91 char	CAN-Bus devices
		  0 = /dev/can0		First CAN-Bus controller
		  1 = /dev/can1		Second CAN-Bus controller
		    ...

  91 block	Tenth IDE hard disk/CD-ROM interface
		  0 = /dev/hds		Master: whole disk (or CD-ROM)
		 64 = /dev/hdt		Slave: whole disk (or CD-ROM)

		Partitions are handled the same way as for the first
		interface (see major number 3).

  92 char	Reserved for ith Kommunikationstechnik MIC ISDN card

  92 block	PPDD encrypted disk driver
		  0 = /dev/ppdd0	First encrypted disk
		  1 = /dev/ppdd1	Second encrypted disk
		    ...

		Partitions are handled in the same way as for IDE
		disks (see major number 3) except that the limit on
		partitions is 15.

  93 char

  93 block	NAND Flash Translation Layer filesystem
		  0 = /dev/nftla	First NFTL layer
		 16 = /dev/nftlb	Second NFTL layer
		    ...
		240 = /dev/nftlp	16th NTFL layer

  94 char

  94 block	IBM S/390 DASD block storage
		  0 = /dev/dasda First DASD device, major
		  1 = /dev/dasda1 First DASD device, block 1
		  2 = /dev/dasda2 First DASD device, block 2
		  3 = /dev/dasda3 First DASD device, block 3
		  4 = /dev/dasdb Second DASD device, major
		  5 = /dev/dasdb1 Second DASD device, block 1
		  6 = /dev/dasdb2 Second DASD device, block 2
		  7 = /dev/dasdb3 Second DASD device, block 3
		    ...

  95 char	IP filter
		  0 = /dev/ipl		Filter control device/log file
		  1 = /dev/ipnat	NAT control device/log file
		  2 = /dev/ipstate	State information log file
		  3 = /dev/ipauth	Authentication control device/log file
		    ...

  96 char	Parallel port ATAPI tape devices
		  0 = /dev/pt0		First parallel port ATAPI tape
		  1 = /dev/pt1		Second parallel port ATAPI tape
		    ...
		128 = /dev/npt0		First p.p. ATAPI tape, no rewind
		129 = /dev/npt1		Second p.p. ATAPI tape, no rewind
		    ...

  96 block	Inverse NAND Flash Translation Layer
		  0 = /dev/inftla First INFTL layer
		 16 = /dev/inftlb Second INFTL layer
		    ...
		240 = /dev/inftlp	16th INTFL layer

  97 char	Parallel port generic ATAPI interface
		  0 = /dev/pg0		First parallel port ATAPI device
		  1 = /dev/pg1		Second parallel port ATAPI device
		  2 = /dev/pg2		Third parallel port ATAPI device
		  3 = /dev/pg3		Fourth parallel port ATAPI device

		These devices support the same API as the generic SCSI
		devices.

  98 char	Control and Measurement Device (comedi)
		  0 = /dev/comedi0	First comedi device
		  1 = /dev/comedi1	Second comedi device
		    ...
		 47 = /dev/comedi47	48th comedi device

		Minors 48 to 255 are reserved for comedi subdevices with
		pathnames of the form "/dev/comediX_subdY", where "X" is the
		minor number of the associated comedi device and "Y" is the
		subdevice number.  These subdevice minors are assigned
		dynamically, so there is no fixed mapping from subdevice
		pathnames to minor numbers.

		See https://www.comedi.org/ for information about the Comedi
		project.

  98 block	User-mode virtual block device
		  0 = /dev/ubda		First user-mode block device
		 16 = /dev/ubdb		Second user-mode block device
		    ...

		Partitions are handled in the same way as for IDE
		disks (see major number 3) except that the limit on
		partitions is 15.

		This device is used by the user-mode virtual kernel port.

  99 char	Raw parallel ports
		  0 = /dev/parport0	First parallel port
		  1 = /dev/parport1	Second parallel port
		    ...

  99 block	JavaStation flash disk
		  0 = /dev/jsfd		JavaStation flash disk

 100 char	Telephony for Linux
		  0 = /dev/phone0	First telephony device
		  1 = /dev/phone1	Second telephony device
		    ...

 101 char	Motorola DSP 56xxx board
		  0 = /dev/mdspstat	Status information
		  1 = /dev/mdsp1	First DSP board I/O controls
		    ...
		 16 = /dev/mdsp16	16th DSP board I/O controls

 101 block	AMI HyperDisk RAID controller
		  0 = /dev/amiraid/ar0	First array whole disk
		 16 = /dev/amiraid/ar1	Second array whole disk
		    ...
		240 = /dev/amiraid/ar15	16th array whole disk

		For each device, partitions are added as:
		  0 = /dev/amiraid/ar?	  Whole disk
		  1 = /dev/amiraid/ar?p1  First partition
		  2 = /dev/amiraid/ar?p2  Second partition
		    ...
		 15 = /dev/amiraid/ar?p15 15th partition

 102 char

 102 block	Compressed block device
		  0 = /dev/cbd/a	First compressed block device, whole device
		 16 = /dev/cbd/b	Second compressed block device, whole device
		    ...
		240 = /dev/cbd/p	16th compressed block device, whole device

		Partitions are handled in the same way as for IDE
		disks (see major number 3) except that the limit on
		partitions is 15.

 103 char	Arla network file system
		  0 = /dev/nnpfs0	First NNPFS device
		  1 = /dev/nnpfs1	Second NNPFS device

		Arla is a free clone of the Andrew File System, AFS.
		The NNPFS device gives user mode filesystem
		implementations a kernel presence for caching and easy
		mounting.  For more information about the project,
		write to <arla-drinkers@stacken.kth.se> or see
		https://www.stacken.kth.se/project/arla/

 103 block	Audit device
		  0 = /dev/audit	Audit device

 104 char	Flash BIOS support

 104 block	Compaq Next Generation Drive Array, first controller
		  0 = /dev/cciss/c0d0	First logical drive, whole disk
		 16 = /dev/cciss/c0d1	Second logical drive, whole disk
		    ...
		240 = /dev/cciss/c0d15	16th logical drive, whole disk

		Partitions are handled the same way as for Mylex
		DAC960 (see major number 48) except that the limit on
		partitions is 15.

 105 char	Comtrol VS-1000 serial controller
		  0 = /dev/ttyV0	First VS-1000 port
		  1 = /dev/ttyV1	Second VS-1000 port
		    ...

 105 block	Compaq Next Generation Drive Array, second controller
		  0 = /dev/cciss/c1d0	First logical drive, whole disk
		 16 = /dev/cciss/c1d1	Second logical drive, whole disk
		    ...
		240 = /dev/cciss/c1d15	16th logical drive, whole disk

		Partitions are handled the same way as for Mylex
		DAC960 (see major number 48) except that the limit on
		partitions is 15.

 106 char	Comtrol VS-1000 serial controller - alternate devices
		  0 = /dev/cuv0		First VS-1000 port
		  1 = /dev/cuv1		Second VS-1000 port
		    ...

 106 block	Compaq Next Generation Drive Array, third controller
		  0 = /dev/cciss/c2d0	First logical drive, whole disk
		 16 = /dev/cciss/c2d1	Second logical drive, whole disk
		    ...
		240 = /dev/cciss/c2d15	16th logical drive, whole disk

		Partitions are handled the same way as for Mylex
		DAC960 (see major number 48) except that the limit on
		partitions is 15.

 107 char	3Dfx Voodoo Graphics device
		  0 = /dev/3dfx		Primary 3Dfx graphics device

 107 block	Compaq Next Generation Drive Array, fourth controller
		  0 = /dev/cciss/c3d0	First logical drive, whole disk
		 16 = /dev/cciss/c3d1	Second logical drive, whole disk
		    ...
		240 = /dev/cciss/c3d15	16th logical drive, whole disk

		Partitions are handled the same way as for Mylex
		DAC960 (see major number 48) except that the limit on
		partitions is 15.

 108 char	Device independent PPP interface
		  0 = /dev/ppp		Device independent PPP interface

 108 block	Compaq Next Generation Drive Array, fifth controller
		  0 = /dev/cciss/c4d0	First logical drive, whole disk
		 16 = /dev/cciss/c4d1	Second logical drive, whole disk
		    ...
		240 = /dev/cciss/c4d15	16th logical drive, whole disk

		Partitions are handled the same way as for Mylex
		DAC960 (see major number 48) except that the limit on
		partitions is 15.

 109 char	Reserved for logical volume manager

 109 block	Compaq Next Generation Drive Array, sixth controller
		  0 = /dev/cciss/c5d0	First logical drive, whole disk
		 16 = /dev/cciss/c5d1	Second logical drive, whole disk
		    ...
		240 = /dev/cciss/c5d15	16th logical drive, whole disk

		Partitions are handled the same way as for Mylex
		DAC960 (see major number 48) except that the limit on
		partitions is 15.

 110 char	miroMEDIA Surround board
		  0 = /dev/srnd0	First miroMEDIA Surround board
		  1 = /dev/srnd1	Second miroMEDIA Surround board
		    ...

 110 block	Compaq Next Generation Drive Array, seventh controller
		  0 = /dev/cciss/c6d0	First logical drive, whole disk
		 16 = /dev/cciss/c6d1	Second logical drive, whole disk
		    ...
		240 = /dev/cciss/c6d15	16th logical drive, whole disk

		Partitions are handled the same way as for Mylex
		DAC960 (see major number 48) except that the limit on
		partitions is 15.

 111 char

 111 block	Compaq Next Generation Drive Array, eighth controller
		  0 = /dev/cciss/c7d0	First logical drive, whole disk
		 16 = /dev/cciss/c7d1	Second logical drive, whole disk
		    ...
		240 = /dev/cciss/c7d15	16th logical drive, whole disk

		Partitions are handled the same way as for Mylex
		DAC960 (see major number 48) except that the limit on
		partitions is 15.

 112 char	ISI serial card
		  0 = /dev/ttyM0	First ISI port
		  1 = /dev/ttyM1	Second ISI port
		    ...

		There is currently a device-naming conflict between
		these and PAM multimodems (major 78).

 112 block	IBM iSeries virtual disk
		  0 = /dev/iseries/vda	First virtual disk, whole disk
		  8 = /dev/iseries/vdb	Second virtual disk, whole disk
		    ...
		200 = /dev/iseries/vdz	26th virtual disk, whole disk
		208 = /dev/iseries/vdaa	27th virtual disk, whole disk
		    ...
		248 = /dev/iseries/vdaf	32nd virtual disk, whole disk

		Partitions are handled in the same way as for IDE
		disks (see major number 3) except that the limit on
		partitions is 7.

 113 char	ISI serial card - alternate devices
		  0 = /dev/cum0		Callout device for ttyM0
		  1 = /dev/cum1		Callout device for ttyM1
		    ...

 113 block	IBM iSeries virtual CD-ROM
		  0 = /dev/iseries/vcda	First virtual CD-ROM
		  1 = /dev/iseries/vcdb	Second virtual CD-ROM
		    ...

 114 char	Picture Elements ISE board
		  0 = /dev/ise0		First ISE board
		  1 = /dev/ise1		Second ISE board
		    ...
		128 = /dev/isex0	Control node for first ISE board
		129 = /dev/isex1	Control node for second ISE board
		    ...

		The ISE board is an embedded computer, optimized for
		image processing. The /dev/iseN nodes are the general
		I/O access to the board, the /dev/isex0 nodes command
		nodes used to control the board.

 114 block       IDE BIOS powered software RAID interfaces such as the
		Promise Fastrak

		   0 = /dev/ataraid/d0
		   1 = /dev/ataraid/d0p1
		   2 = /dev/ataraid/d0p2
		  ...
		  16 = /dev/ataraid/d1
		  17 = /dev/ataraid/d1p1
		  18 = /dev/ataraid/d1p2
		  ...
		 255 = /dev/ataraid/d15p15

		Partitions are handled in the same way as for IDE
		disks (see major number 3) except that the limit on
		partitions is 15.

 115 char	TI link cable devices (115 was formerly the console driver speaker)
		  0 = /dev/tipar0    Parallel cable on first parallel port
		  ...
		  7 = /dev/tipar7    Parallel cable on seventh parallel port

		  8 = /dev/tiser0    Serial cable on first serial port
		  ...
		 15 = /dev/tiser7    Serial cable on seventh serial port

		 16 = /dev/tiusb0    First USB cable
		  ...
		 47 = /dev/tiusb31   32nd USB cable

 115 block       NetWare (NWFS) Devices (0-255)

		The NWFS (NetWare) devices are used to present a
		collection of NetWare Mirror Groups or NetWare
		Partitions as a logical storage segment for
		use in mounting NetWare volumes.  A maximum of
		 256 NetWare volumes can be supported in a single
		machine.

		http://cgfa.telepac.pt/ftp2/kernel.org/linux/kernel/people/jmerkey/nwfs/

		 0 = /dev/nwfs/v0    First NetWare (NWFS) Logical Volume
		 1 = /dev/nwfs/v1    Second NetWare (NWFS) Logical Volume
		 2 = /dev/nwfs/v2    Third NetWare (NWFS) Logical Volume
		      ...
		 255 = /dev/nwfs/v255    Last NetWare (NWFS) Logical Volume

 116 char	Advanced Linux Sound Driver (ALSA)

 116 block       MicroMemory battery backed RAM adapter (NVRAM)
		Supports 16 boards, 15 partitions each.
		Requested by neilb at cse.unsw.edu.au.

		 0 = /dev/umem/d0      Whole of first board
		 1 = /dev/umem/d0p1    First partition of first board
		 2 = /dev/umem/d0p2    Second partition of first board
		15 = /dev/umem/d0p15   15th partition of first board

		16 = /dev/umem/d1      Whole of second board
		17 = /dev/umem/d1p1    First partition of second board
		    ...
		255= /dev/umem/d15p15  15th partition of 16th board.

 117 char	[REMOVED] COSA/SRP synchronous serial card
		  0 = /dev/cosa0c0	1st board, 1st channel
		  1 = /dev/cosa0c1	1st board, 2nd channel
		    ...
		 16 = /dev/cosa1c0	2nd board, 1st channel
		 17 = /dev/cosa1c1	2nd board, 2nd channel
		    ...

 117 block       Enterprise Volume Management System (EVMS)

		The EVMS driver uses a layered, plug-in model to provide
		unparalleled flexibility and extensibility in managing
		storage.  This allows for easy expansion or customization
		of various levels of volume management.  Requested by
		Mark Peloquin (peloquin at us.ibm.com).

		Note: EVMS populates and manages all the devnodes in
		/dev/evms.

		http://sf.net/projects/evms

		   0 = /dev/evms/block_device   EVMS block device
		   1 = /dev/evms/legacyname1    First EVMS legacy device
		   2 = /dev/evms/legacyname2    Second EVMS legacy device
		    ...
		    Both ranges can grow (down or up) until they meet.
		    ...
		 254 = /dev/evms/EVMSname2      Second EVMS native device
		 255 = /dev/evms/EVMSname1      First EVMS native device

		Note: legacyname(s) are derived from the normal legacy
		device names.  For example, /dev/hda5 would become
		/dev/evms/hda5.

 118 char	IBM Cryptographic Accelerator
		  0 = /dev/ica	Virtual interface to all IBM Crypto Accelerators
		  1 = /dev/ica0	IBMCA Device 0
		  2 = /dev/ica1	IBMCA Device 1
		    ...

 119 char	VMware virtual network control
		  0 = /dev/vnet0	1st virtual network
		  1 = /dev/vnet1	2nd virtual network
		    ...

 120-127 char	LOCAL/EXPERIMENTAL USE

 120-127 block	LOCAL/EXPERIMENTAL USE
		Allocated for local/experimental use.  For devices not
		assigned official numbers, these ranges should be
		used in order to avoid conflicting with future assignments.

 128-135 char	Unix98 PTY masters

		These devices should not have corresponding device
		nodes; instead they should be accessed through the
		/dev/ptmx cloning interface.

 128 block       SCSI disk devices (128-143)
		   0 = /dev/sddy         129th SCSI disk whole disk
		  16 = /dev/sddz         130th SCSI disk whole disk
		  32 = /dev/sdea         131th SCSI disk whole disk
		    ...
		 240 = /dev/sden         144th SCSI disk whole disk

		Partitions are handled in the same way as for IDE
		disks (see major number 3) except that the limit on
		partitions is 15.

 129 block       SCSI disk devices (144-159)
		   0 = /dev/sdeo         145th SCSI disk whole disk
		  16 = /dev/sdep         146th SCSI disk whole disk
		  32 = /dev/sdeq         147th SCSI disk whole disk
		    ...
		 240 = /dev/sdfd         160th SCSI disk whole disk

		Partitions are handled in the same way as for IDE
		disks (see major number 3) except that the limit on
		partitions is 15.

 130 char 	(Misc devices)

 130 block       SCSI disk devices (160-175)
		   0 = /dev/sdfe         161st SCSI disk whole disk
		  16 = /dev/sdff         162nd SCSI disk whole disk
		  32 = /dev/sdfg         163rd SCSI disk whole disk
		    ...
		 240 = /dev/sdft         176th SCSI disk whole disk

		Partitions are handled in the same way as for IDE
		disks (see major number 3) except that the limit on
		partitions is 15.

 131 block       SCSI disk devices (176-191)
		   0 = /dev/sdfu         177th SCSI disk whole disk
		  16 = /dev/sdfv         178th SCSI disk whole disk
		  32 = /dev/sdfw         179th SCSI disk whole disk
		    ...
		 240 = /dev/sdgj         192nd SCSI disk whole disk

		Partitions are handled in the same way as for IDE
		disks (see major number 3) except that the limit on
		partitions is 15.

 132 block       SCSI disk devices (192-207)
		   0 = /dev/sdgk         193rd SCSI disk whole disk
		  16 = /dev/sdgl         194th SCSI disk whole disk
		  32 = /dev/sdgm         195th SCSI disk whole disk
		    ...
		 240 = /dev/sdgz         208th SCSI disk whole disk

		Partitions are handled in the same way as for IDE
		disks (see major number 3) except that the limit on
		partitions is 15.

 133 block       SCSI disk devices (208-223)
		   0 = /dev/sdha         209th SCSI disk whole disk
		  16 = /dev/sdhb         210th SCSI disk whole disk
		  32 = /dev/sdhc         211th SCSI disk whole disk
		    ...
		 240 = /dev/sdhp         224th SCSI disk whole disk

		Partitions are handled in the same way as for IDE
		disks (see major number 3) except that the limit on
		partitions is 15.

 134 block       SCSI disk devices (224-239)
		   0 = /dev/sdhq         225th SCSI disk whole disk
		  16 = /dev/sdhr         226th SCSI disk whole disk
		  32 = /dev/sdhs         227th SCSI disk whole disk
		    ...
		 240 = /dev/sdif         240th SCSI disk whole disk

		Partitions are handled in the same way as for IDE
		disks (see major number 3) except that the limit on
		partitions is 15.

 135 block       SCSI disk devices (240-255)
		   0 = /dev/sdig         241st SCSI disk whole disk
		  16 = /dev/sdih         242nd SCSI disk whole disk
		  32 = /dev/sdih         243rd SCSI disk whole disk
		    ...
		 240 = /dev/sdiv         256th SCSI disk whole disk

		Partitions are handled in the same way as for IDE
		disks (see major number 3) except that the limit on
		partitions is 15.

 136-143 char	Unix98 PTY slaves
		  0 = /dev/pts/0	First Unix98 pseudo-TTY
		  1 = /dev/pts/1	Second Unix98 pseudo-TTY
		    ...

		These device nodes are automatically generated with
		the proper permissions and modes by mounting the
		devpts filesystem onto /dev/pts with the appropriate
		mount options (distribution dependent, however, on
		*most* distributions the appropriate options are
		"mode=0620,gid=<gid of the "tty" group>".)

 136 block	Mylex DAC960 PCI RAID controller; ninth controller
		  0 = /dev/rd/c8d0	First disk, whole disk
		  8 = /dev/rd/c8d1	Second disk, whole disk
		    ...
		248 = /dev/rd/c8d31	32nd disk, whole disk

		Partitions are handled as for major 48.

 137 block	Mylex DAC960 PCI RAID controller; tenth controller
		  0 = /dev/rd/c9d0	First disk, whole disk
		  8 = /dev/rd/c9d1	Second disk, whole disk
		    ...
		248 = /dev/rd/c9d31	32nd disk, whole disk

		Partitions are handled as for major 48.

 138 block	Mylex DAC960 PCI RAID controller; eleventh controller
		  0 = /dev/rd/c10d0	First disk, whole disk
		  8 = /dev/rd/c10d1	Second disk, whole disk
		    ...
		248 = /dev/rd/c10d31	32nd disk, whole disk

		Partitions are handled as for major 48.

 139 block	Mylex DAC960 PCI RAID controller; twelfth controller
		  0 = /dev/rd/c11d0	First disk, whole disk
		  8 = /dev/rd/c11d1	Second disk, whole disk
		    ...
		248 = /dev/rd/c11d31	32nd disk, whole disk

		Partitions are handled as for major 48.

 140 block	Mylex DAC960 PCI RAID controller; thirteenth controller
		  0 = /dev/rd/c12d0	First disk, whole disk
		  8 = /dev/rd/c12d1	Second disk, whole disk
		    ...
		248 = /dev/rd/c12d31	32nd disk, whole disk

		Partitions are handled as for major 48.

 141 block	Mylex DAC960 PCI RAID controller; fourteenth controller
		  0 = /dev/rd/c13d0	First disk, whole disk
		  8 = /dev/rd/c13d1	Second disk, whole disk
		    ...
		248 = /dev/rd/c13d31	32nd disk, whole disk

		Partitions are handled as for major 48.

 142 block	Mylex DAC960 PCI RAID controller; fifteenth controller
		  0 = /dev/rd/c14d0	First disk, whole disk
		  8 = /dev/rd/c14d1	Second disk, whole disk
		    ...
		248 = /dev/rd/c14d31	32nd disk, whole disk

		Partitions are handled as for major 48.

 143 block	Mylex DAC960 PCI RAID controller; sixteenth controller
		  0 = /dev/rd/c15d0	First disk, whole disk
		  8 = /dev/rd/c15d1	Second disk, whole disk
		    ...
		248 = /dev/rd/c15d31	32nd disk, whole disk

		Partitions are handled as for major 48.

 144 char	Encapsulated PPP
		  0 = /dev/pppox0	First PPP over Ethernet
		    ...
		 63 = /dev/pppox63	64th PPP over Ethernet

		This is primarily used for ADSL.

		The SST 5136-DN DeviceNet interface driver has been
		relocated to major 183 due to an unfortunate conflict.

 144 block	Expansion Area #1 for more non-device (e.g. NFS) mounts
		  0 = mounted device 256
		255 = mounted device 511

 145 char	SAM9407-based soundcard
		  0 = /dev/sam0_mixer
		  1 = /dev/sam0_sequencer
		  2 = /dev/sam0_midi00
		  3 = /dev/sam0_dsp
		  4 = /dev/sam0_audio
		  6 = /dev/sam0_sndstat
		 18 = /dev/sam0_midi01
		 34 = /dev/sam0_midi02
		 50 = /dev/sam0_midi03
		 64 = /dev/sam1_mixer
		    ...
		128 = /dev/sam2_mixer
		    ...
		192 = /dev/sam3_mixer
		    ...

		Device functions match OSS, but offer a number of
		addons, which are sam9407 specific.  OSS can be
		operated simultaneously, taking care of the codec.

 145 block	Expansion Area #2 for more non-device (e.g. NFS) mounts
		  0 = mounted device 512
		255 = mounted device 767

 146 char	SYSTRAM SCRAMNet mirrored-memory network
		  0 = /dev/scramnet0	First SCRAMNet device
		  1 = /dev/scramnet1	Second SCRAMNet device
		    ...

 146 block	Expansion Area #3 for more non-device (e.g. NFS) mounts
		  0 = mounted device 768
		255 = mounted device 1023

 147 char	Aureal Semiconductor Vortex Audio device
		  0 = /dev/aureal0	First Aureal Vortex
		  1 = /dev/aureal1	Second Aureal Vortex
		    ...

 147 block	Distributed Replicated Block Device (DRBD)
		  0 = /dev/drbd0	First DRBD device
		  1 = /dev/drbd1	Second DRBD device
		    ...

 148 char	Technology Concepts serial card
		  0 = /dev/ttyT0	First TCL port
		  1 = /dev/ttyT1	Second TCL port
		    ...

 149 char	Technology Concepts serial card - alternate devices
		  0 = /dev/cut0		Callout device for ttyT0
		  1 = /dev/cut0		Callout device for ttyT1
		    ...

 150 char	Real-Time Linux FIFOs
		  0 = /dev/rtf0		First RTLinux FIFO
		  1 = /dev/rtf1		Second RTLinux FIFO
		    ...

 151 char	DPT I2O SmartRaid V controller
		  0 = /dev/dpti0	First DPT I2O adapter
		  1 = /dev/dpti1	Second DPT I2O adapter
		    ...

 152 char	EtherDrive Control Device
		  0 = /dev/etherd/ctl	Connect/Disconnect an EtherDrive
		  1 = /dev/etherd/err	Monitor errors
		  2 = /dev/etherd/raw	Raw AoE packet monitor

 152 block	EtherDrive Block Devices
		  0 = /dev/etherd/0	EtherDrive 0
		    ...
		255 = /dev/etherd/255	EtherDrive 255

 153 char	SPI Bus Interface (sometimes referred to as MicroWire)
		  0 = /dev/spi0		First SPI device on the bus
		  1 = /dev/spi1		Second SPI device on the bus
		    ...
		 15 = /dev/spi15	Sixteenth SPI device on the bus

 153 block	Enhanced Metadisk RAID (EMD) storage units
		  0 = /dev/emd/0	First unit
		  1 = /dev/emd/0p1	Partition 1 on First unit
		  2 = /dev/emd/0p2	Partition 2 on First unit
		    ...
		 15 = /dev/emd/0p15	Partition 15 on First unit

		 16 = /dev/emd/1	Second unit
		 32 = /dev/emd/2	Third unit
		    ...
		240 = /dev/emd/15	Sixteenth unit

		Partitions are handled in the same way as for IDE
		disks (see major number 3) except that the limit on
		partitions is 15.

 154 char	Specialix RIO serial card
		  0 = /dev/ttySR0	First RIO port
		    ...
		255 = /dev/ttySR255	256th RIO port

 155 char	Specialix RIO serial card - alternate devices
		  0 = /dev/cusr0	Callout device for ttySR0
		    ...
		255 = /dev/cusr255	Callout device for ttySR255

 156 char	Specialix RIO serial card
		  0 = /dev/ttySR256	257th RIO port
		    ...
		255 = /dev/ttySR511	512th RIO port

 157 char	Specialix RIO serial card - alternate devices
		  0 = /dev/cusr256	Callout device for ttySR256
		    ...
		255 = /dev/cusr511	Callout device for ttySR511

 158 char	Dialogic GammaLink fax driver
		  0 = /dev/gfax0	GammaLink channel 0
		  1 = /dev/gfax1	GammaLink channel 1
		    ...

 159 char	RESERVED

 159 block	RESERVED

 160 char	General Purpose Instrument Bus (GPIB)
		  0 = /dev/gpib0	First GPIB bus
		  1 = /dev/gpib1	Second GPIB bus
		    ...

 160 block       Carmel 8-port SATA Disks on First Controller
		  0 = /dev/carmel/0     SATA disk 0 whole disk
		  1 = /dev/carmel/0p1   SATA disk 0 partition 1
		    ...
		 31 = /dev/carmel/0p31  SATA disk 0 partition 31

		 32 = /dev/carmel/1     SATA disk 1 whole disk
		 64 = /dev/carmel/2     SATA disk 2 whole disk
		    ...
		224 = /dev/carmel/7     SATA disk 7 whole disk

		Partitions are handled in the same way as for IDE
		disks (see major number 3) except that the limit on
		partitions is 31.

 161 char	IrCOMM devices (IrDA serial/parallel emulation)
		  0 = /dev/ircomm0	First IrCOMM device
		  1 = /dev/ircomm1	Second IrCOMM device
		    ...
		 16 = /dev/irlpt0	First IrLPT device
		 17 = /dev/irlpt1	Second IrLPT device
		    ...

 161 block       Carmel 8-port SATA Disks on Second Controller
		  0 = /dev/carmel/8     SATA disk 8 whole disk
		  1 = /dev/carmel/8p1   SATA disk 8 partition 1
		    ...
		 31 = /dev/carmel/8p31  SATA disk 8 partition 31

		 32 = /dev/carmel/9     SATA disk 9 whole disk
		 64 = /dev/carmel/10    SATA disk 10 whole disk
		    ...
		224 = /dev/carmel/15    SATA disk 15 whole disk

		Partitions are handled in the same way as for IDE
		disks (see major number 3) except that the limit on
		partitions is 31.

 162 char	Used for (now removed) raw block device interface

 163 char

 164 char	Chase Research AT/PCI-Fast serial card
		  0 = /dev/ttyCH0	AT/PCI-Fast board 0, port 0
		    ...
		 15 = /dev/ttyCH15	AT/PCI-Fast board 0, port 15
		 16 = /dev/ttyCH16	AT/PCI-Fast board 1, port 0
		    ...
		 31 = /dev/ttyCH31	AT/PCI-Fast board 1, port 15
		 32 = /dev/ttyCH32	AT/PCI-Fast board 2, port 0
		    ...
		 47 = /dev/ttyCH47	AT/PCI-Fast board 2, port 15
		 48 = /dev/ttyCH48	AT/PCI-Fast board 3, port 0
		    ...
		 63 = /dev/ttyCH63	AT/PCI-Fast board 3, port 15

 165 char	Chase Research AT/PCI-Fast serial card - alternate devices
		  0 = /dev/cuch0	Callout device for ttyCH0
		    ...
		 63 = /dev/cuch63	Callout device for ttyCH63

 166 char	ACM USB modems
		  0 = /dev/ttyACM0	First ACM modem
		  1 = /dev/ttyACM1	Second ACM modem
		    ...

 167 char	ACM USB modems - alternate devices
		  0 = /dev/cuacm0	Callout device for ttyACM0
		  1 = /dev/cuacm1	Callout device for ttyACM1
		    ...

 168 char	Eracom CSA7000 PCI encryption adaptor
		  0 = /dev/ecsa0	First CSA7000
		  1 = /dev/ecsa1	Second CSA7000
		    ...

 169 char	Eracom CSA8000 PCI encryption adaptor
		  0 = /dev/ecsa8-0	First CSA8000
		  1 = /dev/ecsa8-1	Second CSA8000
		    ...

 170 char	AMI MegaRAC remote access controller
		  0 = /dev/megarac0	First MegaRAC card
		  1 = /dev/megarac1	Second MegaRAC card
		    ...

 171 char	Reserved for IEEE 1394 (Firewire)

 172 char	Moxa Intellio serial card
		  0 = /dev/ttyMX0	First Moxa port
		  1 = /dev/ttyMX1	Second Moxa port
		    ...
		127 = /dev/ttyMX127	128th Moxa port
		128 = /dev/moxactl	Moxa control port

 173 char	Moxa Intellio serial card - alternate devices
		  0 = /dev/cumx0	Callout device for ttyMX0
		  1 = /dev/cumx1	Callout device for ttyMX1
		    ...
		127 = /dev/cumx127	Callout device for ttyMX127

 174 char	SmartIO serial card
		  0 = /dev/ttySI0	First SmartIO port
		  1 = /dev/ttySI1	Second SmartIO port
		    ...

 175 char	SmartIO serial card - alternate devices
		  0 = /dev/cusi0	Callout device for ttySI0
		  1 = /dev/cusi1	Callout device for ttySI1
		    ...

 176 char	nCipher nFast PCI crypto accelerator
		  0 = /dev/nfastpci0	First nFast PCI device
		  1 = /dev/nfastpci1	First nFast PCI device
		    ...

 177 char	TI PCILynx memory spaces
		  0 = /dev/pcilynx/aux0	 AUX space of first PCILynx card
		    ...
		 15 = /dev/pcilynx/aux15 AUX space of 16th PCILynx card
		 16 = /dev/pcilynx/rom0	 ROM space of first PCILynx card
		    ...
		 31 = /dev/pcilynx/rom15 ROM space of 16th PCILynx card
		 32 = /dev/pcilynx/ram0	 RAM space of first PCILynx card
		    ...
		 47 = /dev/pcilynx/ram15 RAM space of 16th PCILynx card

 178 char	Giganet cLAN1xxx virtual interface adapter
		  0 = /dev/clanvi0	First cLAN adapter
		  1 = /dev/clanvi1	Second cLAN adapter
		    ...

 179 block       MMC block devices
		  0 = /dev/mmcblk0      First SD/MMC card
		  1 = /dev/mmcblk0p1    First partition on first MMC card
		  8 = /dev/mmcblk1      Second SD/MMC card
		    ...

		The start of next SD/MMC card can be configured with
		CONFIG_MMC_BLOCK_MINORS, or overridden at boot/modprobe
		time using the mmcblk.perdev_minors option. That would
		bump the offset between each card to be the configured
		value instead of the default 8.

 179 char	CCube DVXChip-based PCI products
		  0 = /dev/dvxirq0	First DVX device
		  1 = /dev/dvxirq1	Second DVX device
		    ...

 180 char	USB devices
		  0 = /dev/usb/lp0	First USB printer
		    ...
		 15 = /dev/usb/lp15	16th USB printer
		 48 = /dev/usb/scanner0	First USB scanner
		    ...
		 63 = /dev/usb/scanner15 16th USB scanner
		 64 = /dev/usb/rio500	Diamond Rio 500
		 65 = /dev/usb/usblcd	USBLCD Interface (info@usblcd.de)
		 66 = /dev/usb/cpad0	Synaptics cPad (mouse/LCD)
		 96 = /dev/usb/hiddev0	1st USB HID device
		    ...
		111 = /dev/usb/hiddev15	16th USB HID device
		112 = /dev/usb/auer0	1st auerswald ISDN device
		    ...
		127 = /dev/usb/auer15	16th auerswald ISDN device
		128 = /dev/usb/brlvgr0	First Braille Voyager device
		    ...
		131 = /dev/usb/brlvgr3	Fourth Braille Voyager device
		132 = /dev/usb/idmouse	ID Mouse (fingerprint scanner) device
		133 = /dev/usb/sisusbvga1	First SiSUSB VGA device
		    ...
		140 = /dev/usb/sisusbvga8	Eighth SISUSB VGA device
		144 = /dev/usb/lcd	USB LCD device
		160 = /dev/usb/legousbtower0	1st USB Legotower device
		    ...
		175 = /dev/usb/legousbtower15	16th USB Legotower device
		176 = /dev/usb/usbtmc1	First USB TMC device
		   ...
		191 = /dev/usb/usbtmc16	16th USB TMC device
		192 = /dev/usb/yurex1	First USB Yurex device
		   ...
		209 = /dev/usb/yurex16	16th USB Yurex device

 180 block	USB block devices
		  0 = /dev/uba		First USB block device
		  8 = /dev/ubb		Second USB block device
		 16 = /dev/ubc		Third USB block device
		    ...

 181 char	Conrad Electronic parallel port radio clocks
		  0 = /dev/pcfclock0	First Conrad radio clock
		  1 = /dev/pcfclock1	Second Conrad radio clock
		    ...

 182 char	Picture Elements THR2 binarizer
		  0 = /dev/pethr0	First THR2 board
		  1 = /dev/pethr1	Second THR2 board
		    ...

 183 char	SST 5136-DN DeviceNet interface
		  0 = /dev/ss5136dn0	First DeviceNet interface
		  1 = /dev/ss5136dn1	Second DeviceNet interface
		    ...

		This device used to be assigned to major number 144.
		It had to be moved due to an unfortunate conflict.

 184 char	Picture Elements' video simulator/sender
		  0 = /dev/pevss0	First sender board
		  1 = /dev/pevss1	Second sender board
		    ...

 185 char	InterMezzo high availability file system
		  0 = /dev/intermezzo0	First cache manager
		  1 = /dev/intermezzo1	Second cache manager
		    ...

		See http://web.archive.org/web/20080115195241/
		http://inter-mezzo.org/index.html

 186 char	Object-based storage control device
		  0 = /dev/obd0		First obd control device
		  1 = /dev/obd1		Second obd control device
		    ...

		See ftp://ftp.lustre.org/pub/obd for code and information.

 187 char	DESkey hardware encryption device
		  0 = /dev/deskey0	First DES key
		  1 = /dev/deskey1	Second DES key
		    ...

 188 char	USB serial converters
		  0 = /dev/ttyUSB0	First USB serial converter
		  1 = /dev/ttyUSB1	Second USB serial converter
		    ...

 189 char	USB serial converters - alternate devices
		  0 = /dev/cuusb0	Callout device for ttyUSB0
		  1 = /dev/cuusb1	Callout device for ttyUSB1
		    ...

 190 char	Kansas City tracker/tuner card
		  0 = /dev/kctt0	First KCT/T card
		  1 = /dev/kctt1	Second KCT/T card
		    ...

 191 char	Reserved for PCMCIA

 192 char	Kernel profiling interface
		  0 = /dev/profile	Profiling control device
		  1 = /dev/profile0	Profiling device for CPU 0
		  2 = /dev/profile1	Profiling device for CPU 1
		    ...

 193 char	Kernel event-tracing interface
		  0 = /dev/trace	Tracing control device
		  1 = /dev/trace0	Tracing device for CPU 0
		  2 = /dev/trace1	Tracing device for CPU 1
		    ...

 194 char	linVideoStreams (LINVS)
		  0 = /dev/mvideo/status0	Video compression status
		  1 = /dev/mvideo/stream0	Video stream
		  2 = /dev/mvideo/frame0	Single compressed frame
		  3 = /dev/mvideo/rawframe0	Raw uncompressed frame
		  4 = /dev/mvideo/codec0	Direct codec access
		  5 = /dev/mvideo/video4linux0	Video4Linux compatibility

		 16 = /dev/mvideo/status1	Second device
		    ...
		 32 = /dev/mvideo/status2	Third device
		    ...
		    ...
		240 = /dev/mvideo/status15	16th device
		    ...

 195 char	Nvidia graphics devices
		  0 = /dev/nvidia0		First Nvidia card
		  1 = /dev/nvidia1		Second Nvidia card
		    ...
		255 = /dev/nvidiactl		Nvidia card control device

 196 char	Tormenta T1 card
		  0 = /dev/tor/0		Master control channel for all cards
		  1 = /dev/tor/1		First DS0
		  2 = /dev/tor/2		Second DS0
		    ...
		 48 = /dev/tor/48		48th DS0
		 49 = /dev/tor/49		First pseudo-channel
		 50 = /dev/tor/50		Second pseudo-channel
		    ...

 197 char	OpenTNF tracing facility
		  0 = /dev/tnf/t0		Trace 0 data extraction
		  1 = /dev/tnf/t1		Trace 1 data extraction
		    ...
		128 = /dev/tnf/status		Tracing facility status
		130 = /dev/tnf/trace		Tracing device

 198 char	Total Impact TPMP2 quad coprocessor PCI card
		  0 = /dev/tpmp2/0		First card
		  1 = /dev/tpmp2/1		Second card
		    ...

 199 char	Veritas volume manager (VxVM) volumes
		  0 = /dev/vx/rdsk/*/*		First volume
		  1 = /dev/vx/rdsk/*/*		Second volume
		    ...

 199 block	Veritas volume manager (VxVM) volumes
		  0 = /dev/vx/dsk/*/*		First volume
		  1 = /dev/vx/dsk/*/*		Second volume
		    ...

		The namespace in these directories is maintained by
		the user space VxVM software.

 200 char	Veritas VxVM configuration interface
		   0 = /dev/vx/config		Configuration access node
		   1 = /dev/vx/trace		Volume i/o trace access node
		   2 = /dev/vx/iod		Volume i/o daemon access node
		   3 = /dev/vx/info		Volume information access node
		   4 = /dev/vx/task		Volume tasks access node
		   5 = /dev/vx/taskmon		Volume tasks monitor daemon

 201 char	Veritas VxVM dynamic multipathing driver
		  0 = /dev/vx/rdmp/*		First multipath device
		  1 = /dev/vx/rdmp/*		Second multipath device
		    ...
 201 block	Veritas VxVM dynamic multipathing driver
		  0 = /dev/vx/dmp/*		First multipath device
		  1 = /dev/vx/dmp/*		Second multipath device
		    ...

		The namespace in these directories is maintained by
		the user space VxVM software.

 202 char	CPU model-specific registers
		  0 = /dev/cpu/0/msr		MSRs on CPU 0
		  1 = /dev/cpu/1/msr		MSRs on CPU 1
		    ...

 202 block	Xen Virtual Block Device
		  0 = /dev/xvda       First Xen VBD whole disk
		  16 = /dev/xvdb      Second Xen VBD whole disk
		  32 = /dev/xvdc      Third Xen VBD whole disk
		    ...
		  240 = /dev/xvdp     Sixteenth Xen VBD whole disk

		Partitions are handled in the same way as for IDE
		disks (see major number 3) except that the limit on
		partitions is 15.

 203 char	CPU CPUID information
		  0 = /dev/cpu/0/cpuid		CPUID on CPU 0
		  1 = /dev/cpu/1/cpuid		CPUID on CPU 1
		    ...

 204 char	Low-density serial ports
		  0 = /dev/ttyLU0		LinkUp Systems L72xx UART - port 0
		  1 = /dev/ttyLU1		LinkUp Systems L72xx UART - port 1
		  2 = /dev/ttyLU2		LinkUp Systems L72xx UART - port 2
		  3 = /dev/ttyLU3		LinkUp Systems L72xx UART - port 3
		  4 = /dev/ttyFB0		Intel Footbridge (ARM)
		  5 = /dev/ttySA0		StrongARM builtin serial port 0
		  6 = /dev/ttySA1		StrongARM builtin serial port 1
		  7 = /dev/ttySA2		StrongARM builtin serial port 2
		  8 = /dev/ttySC0		SCI serial port (SuperH) - port 0
		  9 = /dev/ttySC1		SCI serial port (SuperH) - port 1
		 10 = /dev/ttySC2		SCI serial port (SuperH) - port 2
		 11 = /dev/ttySC3		SCI serial port (SuperH) - port 3
		 12 = /dev/ttyFW0		Firmware console - port 0
		 13 = /dev/ttyFW1		Firmware console - port 1
		 14 = /dev/ttyFW2		Firmware console - port 2
		 15 = /dev/ttyFW3		Firmware console - port 3
		 16 = /dev/ttyAM0		ARM "AMBA" serial port 0
		    ...
		 31 = /dev/ttyAM15		ARM "AMBA" serial port 15
		 32 = /dev/ttyDB0		DataBooster serial port 0
		    ...
		 39 = /dev/ttyDB7		DataBooster serial port 7
		 40 = /dev/ttySG0		SGI Altix console port
		 41 = /dev/ttySMX0		Motorola i.MX - port 0
		 42 = /dev/ttySMX1		Motorola i.MX - port 1
		 43 = /dev/ttySMX2		Motorola i.MX - port 2
		 44 = /dev/ttyMM0		Marvell MPSC - port 0 (obsolete unused)
		 45 = /dev/ttyMM1		Marvell MPSC - port 1 (obsolete unused)
		 46 = /dev/ttyCPM0		PPC CPM (SCC or SMC) - port 0
		    ...
		 51 = /dev/ttyCPM5		PPC CPM (SCC or SMC) - port 5
		 82 = /dev/ttyVR0		NEC VR4100 series SIU
		 83 = /dev/ttyVR1		NEC VR4100 series DSIU
		 148 = /dev/ttyPSC0		PPC PSC - port 0
		    ...
		 153 = /dev/ttyPSC5		PPC PSC - port 5
		 154 = /dev/ttyAT0		ATMEL serial port 0
		    ...
		 169 = /dev/ttyAT15		ATMEL serial port 15
		 170 = /dev/ttyNX0		Hilscher netX serial port 0
		    ...
		 185 = /dev/ttyNX15		Hilscher netX serial port 15
		 186 = /dev/ttyJ0		JTAG1 DCC protocol based serial port emulation

		 If maximum number of uartlite serial ports is more than 4, then the driver
		 uses dynamic allocation instead of static allocation for major number.
		 187 = /dev/ttyUL0		Xilinx uartlite - port 0
		    ...
		 190 = /dev/ttyUL3		Xilinx uartlite - port 3
		 191 = /dev/xvc0		Xen virtual console - port 0
		 192 = /dev/ttyPZ0		pmac_zilog - port 0
		    ...
		 195 = /dev/ttyPZ3		pmac_zilog - port 3
		 196 = /dev/ttyTX0		TX39/49 serial port 0
		    ...
		 204 = /dev/ttyTX7		TX39/49 serial port 7
		 205 = /dev/ttySC0		SC26xx serial port 0
		 206 = /dev/ttySC1		SC26xx serial port 1
		 207 = /dev/ttySC2		SC26xx serial port 2
		 208 = /dev/ttySC3		SC26xx serial port 3
		 209 = /dev/ttyMAX0		MAX3100 serial port 0
		 210 = /dev/ttyMAX1		MAX3100 serial port 1
		 211 = /dev/ttyMAX2		MAX3100 serial port 2
		 212 = /dev/ttyMAX3		MAX3100 serial port 3

 205 char	Low-density serial ports (alternate device)
		  0 = /dev/culu0		Callout device for ttyLU0
		  1 = /dev/culu1		Callout device for ttyLU1
		  2 = /dev/culu2		Callout device for ttyLU2
		  3 = /dev/culu3		Callout device for ttyLU3
		  4 = /dev/cufb0		Callout device for ttyFB0
		  5 = /dev/cusa0		Callout device for ttySA0
		  6 = /dev/cusa1		Callout device for ttySA1
		  7 = /dev/cusa2		Callout device for ttySA2
		  8 = /dev/cusc0		Callout device for ttySC0
		  9 = /dev/cusc1		Callout device for ttySC1
		 10 = /dev/cusc2		Callout device for ttySC2
		 11 = /dev/cusc3		Callout device for ttySC3
		 12 = /dev/cufw0		Callout device for ttyFW0
		 13 = /dev/cufw1		Callout device for ttyFW1
		 14 = /dev/cufw2		Callout device for ttyFW2
		 15 = /dev/cufw3		Callout device for ttyFW3
		 16 = /dev/cuam0		Callout device for ttyAM0
		    ...
		 31 = /dev/cuam15		Callout device for ttyAM15
		 32 = /dev/cudb0		Callout device for ttyDB0
		    ...
		 39 = /dev/cudb7		Callout device for ttyDB7
		 40 = /dev/cusg0		Callout device for ttySG0
		 41 = /dev/ttycusmx0		Callout device for ttySMX0
		 42 = /dev/ttycusmx1		Callout device for ttySMX1
		 43 = /dev/ttycusmx2		Callout device for ttySMX2
		 46 = /dev/cucpm0		Callout device for ttyCPM0
		    ...
		 51 = /dev/cucpm5		Callout device for ttyCPM5
		 82 = /dev/cuvr0		Callout device for ttyVR0
		 83 = /dev/cuvr1		Callout device for ttyVR1

 206 char	OnStream SC-x0 tape devices
		  0 = /dev/osst0		First OnStream SCSI tape, mode 0
		  1 = /dev/osst1		Second OnStream SCSI tape, mode 0
		    ...
		 32 = /dev/osst0l		First OnStream SCSI tape, mode 1
		 33 = /dev/osst1l		Second OnStream SCSI tape, mode 1
		    ...
		 64 = /dev/osst0m		First OnStream SCSI tape, mode 2
		 65 = /dev/osst1m		Second OnStream SCSI tape, mode 2
		    ...
		 96 = /dev/osst0a		First OnStream SCSI tape, mode 3
		 97 = /dev/osst1a		Second OnStream SCSI tape, mode 3
		    ...
		128 = /dev/nosst0		No rewind version of /dev/osst0
		129 = /dev/nosst1		No rewind version of /dev/osst1
		    ...
		160 = /dev/nosst0l		No rewind version of /dev/osst0l
		161 = /dev/nosst1l		No rewind version of /dev/osst1l
		    ...
		192 = /dev/nosst0m		No rewind version of /dev/osst0m
		193 = /dev/nosst1m		No rewind version of /dev/osst1m
		    ...
		224 = /dev/nosst0a		No rewind version of /dev/osst0a
		225 = /dev/nosst1a		No rewind version of /dev/osst1a
		    ...

		The OnStream SC-x0 SCSI tapes do not support the
		standard SCSI SASD command set and therefore need
		their own driver "osst". Note that the IDE, USB (and
		maybe ParPort) versions may be driven via ide-scsi or
		usb-storage SCSI emulation and this osst device and
		driver as well.  The ADR-x0 drives are QIC-157
		compliant and don't need osst.

 207 char	Compaq ProLiant health feature indicate
		  0 = /dev/cpqhealth/cpqw	Redirector interface
		  1 = /dev/cpqhealth/crom	EISA CROM
		  2 = /dev/cpqhealth/cdt	Data Table
		  3 = /dev/cpqhealth/cevt	Event Log
		  4 = /dev/cpqhealth/casr	Automatic Server Recovery
		  5 = /dev/cpqhealth/cecc	ECC Memory
		  6 = /dev/cpqhealth/cmca	Machine Check Architecture
		  7 = /dev/cpqhealth/ccsm	Deprecated CDT
		  8 = /dev/cpqhealth/cnmi	NMI Handling
		  9 = /dev/cpqhealth/css	Sideshow Management
		 10 = /dev/cpqhealth/cram	CMOS interface
		 11 = /dev/cpqhealth/cpci	PCI IRQ interface

 208 char	User space serial ports
		  0 = /dev/ttyU0		First user space serial port
		  1 = /dev/ttyU1		Second user space serial port
		    ...

 209 char	User space serial ports (alternate devices)
		  0 = /dev/cuu0			Callout device for ttyU0
		  1 = /dev/cuu1			Callout device for ttyU1
		    ...

 210 char	SBE, Inc. sync/async serial card
		  0 = /dev/sbei/wxcfg0		Configuration device for board 0
		  1 = /dev/sbei/dld0		Download device for board 0
		  2 = /dev/sbei/wan00		WAN device, port 0, board 0
		  3 = /dev/sbei/wan01		WAN device, port 1, board 0
		  4 = /dev/sbei/wan02		WAN device, port 2, board 0
		  5 = /dev/sbei/wan03		WAN device, port 3, board 0
		  6 = /dev/sbei/wanc00		WAN clone device, port 0, board 0
		  7 = /dev/sbei/wanc01		WAN clone device, port 1, board 0
		  8 = /dev/sbei/wanc02		WAN clone device, port 2, board 0
		  9 = /dev/sbei/wanc03		WAN clone device, port 3, board 0
		 10 = /dev/sbei/wxcfg1		Configuration device for board 1
		 11 = /dev/sbei/dld1		Download device for board 1
		 12 = /dev/sbei/wan10		WAN device, port 0, board 1
		 13 = /dev/sbei/wan11		WAN device, port 1, board 1
		 14 = /dev/sbei/wan12		WAN device, port 2, board 1
		 15 = /dev/sbei/wan13		WAN device, port 3, board 1
		 16 = /dev/sbei/wanc10		WAN clone device, port 0, board 1
		 17 = /dev/sbei/wanc11		WAN clone device, port 1, board 1
		 18 = /dev/sbei/wanc12		WAN clone device, port 2, board 1
		 19 = /dev/sbei/wanc13		WAN clone device, port 3, board 1
		    ...

		Yes, each board is really spaced 10 (decimal) apart.

 211 char	Addinum CPCI1500 digital I/O card
		  0 = /dev/addinum/cpci1500/0	First CPCI1500 card
		  1 = /dev/addinum/cpci1500/1	Second CPCI1500 card
		    ...

 212 char	LinuxTV.org DVB driver subsystem
		  0 = /dev/dvb/adapter0/video0    first video decoder of first card
		  1 = /dev/dvb/adapter0/audio0    first audio decoder of first card
		  2 = /dev/dvb/adapter0/sec0      (obsolete/unused)
		  3 = /dev/dvb/adapter0/frontend0 first frontend device of first card
		  4 = /dev/dvb/adapter0/demux0    first demux device of first card
		  5 = /dev/dvb/adapter0/dvr0      first digital video recoder device of first card
		  6 = /dev/dvb/adapter0/ca0       first common access port of first card
		  7 = /dev/dvb/adapter0/net0      first network device of first card
		  8 = /dev/dvb/adapter0/osd0      first on-screen-display device of first card
		  9 = /dev/dvb/adapter0/video1    second video decoder of first card
		    ...
		 64 = /dev/dvb/adapter1/video0    first video decoder of second card
		    ...
		128 = /dev/dvb/adapter2/video0    first video decoder of third card
		    ...
		196 = /dev/dvb/adapter3/video0    first video decoder of fourth card

 216 char	Bluetooth RFCOMM TTY devices
		  0 = /dev/rfcomm0		First Bluetooth RFCOMM TTY device
		  1 = /dev/rfcomm1		Second Bluetooth RFCOMM TTY device
		    ...

 217 char	Bluetooth RFCOMM TTY devices (alternate devices)
		  0 = /dev/curf0		Callout device for rfcomm0
		  1 = /dev/curf1		Callout device for rfcomm1
		    ...

 218 char	The Logical Company bus Unibus/Qbus adapters
		  0 = /dev/logicalco/bci/0	First bus adapter
		  1 = /dev/logicalco/bci/1	First bus adapter
		    ...

 219 char	The Logical Company DCI-1300 digital I/O card
		  0 = /dev/logicalco/dci1300/0	First DCI-1300 card
		  1 = /dev/logicalco/dci1300/1	Second DCI-1300 card
		    ...

 220 char	Myricom Myrinet "GM" board
		  0 = /dev/myricom/gm0		First Myrinet GM board
		  1 = /dev/myricom/gmp0		First board "root access"
		  2 = /dev/myricom/gm1		Second Myrinet GM board
		  3 = /dev/myricom/gmp1		Second board "root access"
		    ...

 221 char	VME bus
		  0 = /dev/bus/vme/m0		First master image
		  1 = /dev/bus/vme/m1		Second master image
		  2 = /dev/bus/vme/m2		Third master image
		  3 = /dev/bus/vme/m3		Fourth master image
		  4 = /dev/bus/vme/s0		First slave image
		  5 = /dev/bus/vme/s1		Second slave image
		  6 = /dev/bus/vme/s2		Third slave image
		  7 = /dev/bus/vme/s3		Fourth slave image
		  8 = /dev/bus/vme/ctl		Control

		It is expected that all VME bus drivers will use the
		same interface.  For interface documentation see
		http://www.vmelinux.org/.

 224 char	A2232 serial card
		  0 = /dev/ttyY0		First A2232 port
		  1 = /dev/ttyY1		Second A2232 port
		    ...

 225 char	A2232 serial card (alternate devices)
		  0 = /dev/cuy0			Callout device for ttyY0
		  1 = /dev/cuy1			Callout device for ttyY1
		    ...

 226 char	Direct Rendering Infrastructure (DRI)
		  0 = /dev/dri/card0		First graphics card
		  1 = /dev/dri/card1		Second graphics card
		    ...

 227 char	IBM 3270 terminal Unix tty access
		  1 = /dev/3270/tty1		First 3270 terminal
		  2 = /dev/3270/tty2		Seconds 3270 terminal
		    ...

 228 char	IBM 3270 terminal block-mode access
		  0 = /dev/3270/tub		Controlling interface
		  1 = /dev/3270/tub1		First 3270 terminal
		  2 = /dev/3270/tub2		Second 3270 terminal
		    ...

 229 char	IBM iSeries/pSeries virtual console
		  0 = /dev/hvc0			First console port
		  1 = /dev/hvc1			Second console port
		    ...

 230 char	IBM iSeries virtual tape
		  0 = /dev/iseries/vt0		First virtual tape, mode 0
		  1 = /dev/iseries/vt1		Second virtual tape, mode 0
		    ...
		 32 = /dev/iseries/vt0l		First virtual tape, mode 1
		 33 = /dev/iseries/vt1l		Second virtual tape, mode 1
		    ...
		 64 = /dev/iseries/vt0m		First virtual tape, mode 2
		 65 = /dev/iseries/vt1m		Second virtual tape, mode 2
		    ...
		 96 = /dev/iseries/vt0a		First virtual tape, mode 3
		 97 = /dev/iseries/vt1a		Second virtual tape, mode 3
		      ...
		128 = /dev/iseries/nvt0		First virtual tape, mode 0, no rewind
		129 = /dev/iseries/nvt1		Second virtual tape, mode 0, no rewind
		    ...
		160 = /dev/iseries/nvt0l	First virtual tape, mode 1, no rewind
		161 = /dev/iseries/nvt1l	Second virtual tape, mode 1, no rewind
		    ...
		192 = /dev/iseries/nvt0m	First virtual tape, mode 2, no rewind
		193 = /dev/iseries/nvt1m	Second virtual tape, mode 2, no rewind
		    ...
		224 = /dev/iseries/nvt0a	First virtual tape, mode 3, no rewind
		225 = /dev/iseries/nvt1a	Second virtual tape, mode 3, no rewind
		    ...

		"No rewind" refers to the omission of the default
		automatic rewind on device close.  The MTREW or MTOFFL
		ioctl()'s can be used to rewind the tape regardless of
		the device used to access it.

 231 char	InfiniBand
		0 = /dev/infiniband/umad0
		1 = /dev/infiniband/umad1
		  ...
		63 = /dev/infiniband/umad63    63rd InfiniBandMad device
		64 = /dev/infiniband/issm0     First InfiniBand IsSM device
		65 = /dev/infiniband/issm1     Second InfiniBand IsSM device
		  ...
		127 = /dev/infiniband/issm63    63rd InfiniBand IsSM device
		192 = /dev/infiniband/uverbs0   First InfiniBand verbs device
		193 = /dev/infiniband/uverbs1   Second InfiniBand verbs device
		  ...
		223 = /dev/infiniband/uverbs31  31st InfiniBand verbs device

 232 char	Biometric Devices
		0 = /dev/biometric/sensor0/fingerprint	first fingerprint sensor on first device
		1 = /dev/biometric/sensor0/iris		first iris sensor on first device
		2 = /dev/biometric/sensor0/retina	first retina sensor on first device
		3 = /dev/biometric/sensor0/voiceprint	first voiceprint sensor on first device
		4 = /dev/biometric/sensor0/facial	first facial sensor on first device
		5 = /dev/biometric/sensor0/hand		first hand sensor on first device
		  ...
		10 = /dev/biometric/sensor1/fingerprint	first fingerprint sensor on second device
		  ...
		20 = /dev/biometric/sensor2/fingerprint	first fingerprint sensor on third device
		  ...

 233 char	PathScale InfiniPath interconnect
		0 = /dev/ipath        Primary device for programs (any unit)
		1 = /dev/ipath0       Access specifically to unit 0
		2 = /dev/ipath1       Access specifically to unit 1
		  ...
		4 = /dev/ipath3       Access specifically to unit 3
		129 = /dev/ipath_sma    Device used by Subnet Management Agent
		130 = /dev/ipath_diag   Device used by diagnostics programs

 234-254	char	RESERVED FOR DYNAMIC ASSIGNMENT
		Character devices that request a dynamic allocation of major number will
		take numbers starting from 254 and downward.

 240-254 block	LOCAL/EXPERIMENTAL USE
		Allocated for local/experimental use.  For devices not
		assigned official numbers, these ranges should be
		used in order to avoid conflicting with future assignments.

 255 char	RESERVED

 255 block	RESERVED

		This major is reserved to assist the expansion to a
		larger number space.  No device nodes with this major
		should ever be created on the filesystem.
		(This is probably not true anymore, but I'll leave it
		for now /Torben)

 ---LARGE MAJORS!!!!!---

 256 char	Equinox SST multi-port serial boards
		   0 = /dev/ttyEQ0	First serial port on first Equinox SST board
		 127 = /dev/ttyEQ127	Last serial port on first Equinox SST board
		 128 = /dev/ttyEQ128	First serial port on second Equinox SST board
		  ...
		1027 = /dev/ttyEQ1027	Last serial port on eighth Equinox SST board

 256 block	Resident Flash Disk Flash Translation Layer
		  0 = /dev/rfda		First RFD FTL layer
		 16 = /dev/rfdb		Second RFD FTL layer
		  ...
		240 = /dev/rfdp		16th RFD FTL layer

 257 char	Phoenix Technologies Cryptographic Services Driver
		  0 = /dev/ptlsec	Crypto Services Driver

 257 block	SSFDC Flash Translation Layer filesystem
		  0 = /dev/ssfdca	First SSFDC layer
		  8 = /dev/ssfdcb	Second SSFDC layer
		 16 = /dev/ssfdcc	Third SSFDC layer
		 24 = /dev/ssfdcd	4th SSFDC layer
		 32 = /dev/ssfdce	5th SSFDC layer
		 40 = /dev/ssfdcf	6th SSFDC layer
		 48 = /dev/ssfdcg	7th SSFDC layer
		 56 = /dev/ssfdch	8th SSFDC layer

 258 block	ROM/Flash read-only translation layer
		  0 = /dev/blockrom0	First ROM card's translation layer interface
		  1 = /dev/blockrom1	Second ROM card's translation layer interface
		  ...

 259 block	Block Extended Major
		  Used dynamically to hold additional partition minor
		  numbers and allow large numbers of partitions per device

 259 char	FPGA configuration interfaces
		  0 = /dev/icap0	First Xilinx internal configuration
		  1 = /dev/icap1	Second Xilinx internal configuration

 260 char	OSD (Object-based-device) SCSI Device
		  0 = /dev/osd0		First OSD Device
		  1 = /dev/osd1		Second OSD Device
		  ...
		  255 = /dev/osd255	256th OSD Device

 261 char	Compute Acceleration Devices
		  0 = /dev/accel/accel0	First acceleration device
		  1 = /dev/accel/accel1	Second acceleration device
		    ...

 384-511 char	RESERVED FOR DYNAMIC ASSIGNMENT
		Character devices that request a dynamic allocation of major
		number will take numbers starting from 511 and downward,
		once the 234-254 range is full.

---

### Documentation Admin Guide Dynamic Debug Howto (`Documentation/admin-guide/dynamic-debug-howto.rst`)

Dynamic debug
+++++++++++++


Introduction
============

Dynamic debug allows you to dynamically enable/disable kernel
debug-print code to obtain additional kernel information.

If ``/proc/dynamic_debug/control`` exists, your kernel has dynamic
debug.  You'll need root access (sudo su) to use this.

Dynamic debug provides:

 * a Catalog of all *prdbgs* in your kernel.
   ``cat /proc/dynamic_debug/control`` to see them.

 * a Simple query/command language to alter *prdbgs* by selecting on
   any combination of 0 or 1 of:

   - source filename
   - function name
   - line number (including ranges of line numbers)
   - module name
   - format string
   - class name (as known/declared by each module)

NOTE: To actually get the debug-print output on the console, you may
need to adjust the kernel ``loglevel=``, or use ``ignore_loglevel``.
Read about these kernel parameters in
Documentation/admin-guide/kernel-parameters.rst.

Viewing Dynamic Debug Behaviour
===============================

You can view the currently configured behaviour in the *prdbg* catalog::

  :#> head -n7 /proc/dynamic_debug/control
  # filename:lineno [module]function flags format
  init/main.c:1179 [main]initcall_blacklist =_ "blacklisting initcall %s\012
  init/main.c:1218 [main]initcall_blacklisted =_ "initcall %s blacklisted\012"
  init/main.c:1424 [main]run_init_process =_ "  with arguments:\012"
  init/main.c:1426 [main]run_init_process =_ "    %s\012"
  init/main.c:1427 [main]run_init_process =_ "  with environment:\012"
  init/main.c:1429 [main]run_init_process =_ "    %s\012"

The 3rd space-delimited column shows the current flags, preceded by
a ``=`` for easy use with grep/cut. ``=p`` shows enabled callsites.

Controlling dynamic debug Behaviour
===================================

The behaviour of *prdbg* sites are controlled by writing
query/commands to the control file.  Example::

  # grease the interface
  :#> alias ddcmd='echo $* > /proc/dynamic_debug/control'

  :#> ddcmd '-p; module main func run* +p'
  :#> grep =p /proc/dynamic_debug/control
  init/main.c:1424 [main]run_init_process =p "  with arguments:\012"
  init/main.c:1426 [main]run_init_process =p "    %s\012"
  init/main.c:1427 [main]run_init_process =p "  with environment:\012"
  init/main.c:1429 [main]run_init_process =p "    %s\012"

Error messages go to console/syslog::

  :#> ddcmd mode foo +p
  dyndbg: unknown keyword "mode"
  dyndbg: query parse failed
  bash: echo: write error: Invalid argument

If debugfs is also enabled and mounted, ``dynamic_debug/control`` is
also under the mount-dir, typically ``/sys/kernel/debug/``.

Command Language Reference
==========================

At the basic lexical level, a command is a sequence of words separated
by spaces or tabs.  So these are all equivalent::

  :#> ddcmd file svcsock.c line 1603 +p
  :#> ddcmd "file svcsock.c line 1603 +p"
  :#> ddcmd '  file   svcsock.c     line  1603 +p  '

Command submissions are bounded by a write() system call.
Multiple commands can be written together, separated by ``;`` or ``\n``::

  :#> ddcmd "func pnpacpi_get_resources +p; func pnp_assign_mem +p"
  :#> ddcmd <<"EOC"
  func pnpacpi_get_resources +p
  func pnp_assign_mem +p
  EOC
  :#> cat query-batch-file > /proc/dynamic_debug/control

You can also use wildcards in each query term. The match rule supports
``*`` (matches zero or more characters) and ``?`` (matches exactly one
character). For example, you can match all usb drivers::

  :#> ddcmd file "drivers/usb/*" +p	# "" to suppress shell expansion

Syntactically, a command is pairs of keyword values, followed by a
flags change or setting::

  command ::= match-spec* flags-spec

The match-spec's select *prdbgs* from the catalog, upon which to apply
the flags-spec, all constraints are ANDed together.  An absent keyword
is the same as keyword "*".


A match specification is a keyword, which selects the attribute of
the callsite to be compared, and a value to compare against.  Possible
keywords are:::

  match-spec ::= 'func' string |
		 'file' string |
		 'module' string |
		 'format' string |
		 'class' string |
		 'line' line-range

  line-range ::= lineno |
		 '-'lineno |
		 lineno'-' |
		 lineno'-'lineno

  lineno ::= unsigned-int

.. note::

  ``line-range`` cannot contain space, e.g.
  "1-30" is valid range but "1 - 30" is not.


The meanings of each keyword are:

func
    The given string is compared against the function name
    of each callsite.  Example::

	func svc_tcp_accept
	func *recv*		# in rfcomm, bluetooth, ping, tcp

file
    The given string is compared against either the src-root relative
    pathname, or the basename of the source file of each callsite.
    Examples::

	file svcsock.c
	file kernel/freezer.c	# ie column 1 of control file
	file drivers/usb/*	# all callsites under it
	file inode.c:start_*	# parse :tail as a func (above)
	file inode.c:1-100	# parse :tail as a line-range (above)

module
    The given string is compared against the module name
    of each callsite.  The module name is the string as
    seen in ``lsmod``, i.e. without the directory or the ``.ko``
    suffix and with ``-`` changed to ``_``.  Examples::

	module sunrpc
	module nfsd
	module drm*	# both drm, drm_kms_helper

format
    The given string is searched for in the dynamic debug format
    string.  Note that the string does not need to match the
    entire format, only some part.  Whitespace and other
    special characters can be escaped using C octal character
    escape ``\ooo`` notation, e.g. the space character is ``\040``.
    Alternatively, the string can be enclosed in double quote
    characters (``"``) or single quote characters (``'``).
    Examples::

	format svcrdma:         // many of the NFS/RDMA server pr_debugs
	format readahead        // some pr_debugs in the readahead cache
	format nfsd:\040SETATTR // one way to match a format with whitespace
	format "nfsd: SETATTR"  // a neater way to match a format with whitespace
	format 'nfsd: SETATTR'  // yet another way to match a format with whitespace

class
    The given class_name is validated against each module, which may
    have declared a list of known class_names.  If the class_name is
    found for a module, callsite & class matching and adjustment
    proceeds.  Examples::

	class DRM_UT_KMS	# a DRM.debug category
	class JUNK		# silent non-match
	// class TLD_*		# NOTICE: no wildcard in class names

line
    The given line number or range of line numbers is compared
    against the line number of each ``pr_debug()`` callsite.  A single
    line number matches the callsite line number exactly.  A
    range of line numbers matches any callsite between the first
    and last line number inclusive.  An empty first number means
    the first line in the file, an empty last line number means the
    last line number in the file.  Examples::

	line 1603           // exactly line 1603
	line 1600-1605      // the six lines from line 1600 to line 1605
	line -1605          // the 1605 lines from line 1 to line 1605
	line 1600-          // all lines from line 1600 to the end of the file

The flags specification comprises a change operation followed
by one or more flag characters.  The change operation is one
of the characters::

  -    remove the given flags
  +    add the given flags
  =    set the flags to the given flags

The flags are::

  p    enables the pr_debug() callsite.
  _    enables no flags.

  Decorator flags add to the message-prefix, in order:
  t    Include thread ID, or <intr>
  m    Include module name
  f    Include the function name
  s    Include the source file name
  l    Include line number

For ``print_hex_dump_debug()`` and ``print_hex_dump_bytes()``, only
the ``p`` flag has meaning, other flags are ignored.

Note the regexp ``^[-+=][fslmpt_]+$`` matches a flags specification.
To clear all flags at once, use ``=_`` or ``-fslmpt``.


Debug messages during Boot Process
==================================

To activate debug messages for core code and built-in modules during
the boot process, even before userspace and debugfs exists, use
``dyndbg="QUERY"`` or ``module.dyndbg="QUERY"``.  QUERY follows
the syntax described above, but must not exceed 1023 characters.  Your
bootloader may impose lower limits.

These ``dyndbg`` params are processed just after the ddebug tables are
processed, as part of the early_initcall.  Thus you can enable debug
messages in all code run after this early_initcall via this boot
parameter.

On an x86 system for example ACPI enablement is a subsys_initcall and::

   dyndbg="file ec.c +p"

will show early Embedded Controller transactions during ACPI setup if
your machine (typically a laptop) has an Embedded Controller.
PCI (or other devices) initialization also is a hot candidate for using
this boot parameter for debugging purposes.

If ``foo`` module is not built-in, ``foo.dyndbg`` will still be processed at
boot time, without effect, but will be reprocessed when module is
loaded later. Bare ``dyndbg=`` is only processed at boot.


Debug Messages at Module Initialization Time
============================================

When ``modprobe foo`` is called, modprobe scans ``/proc/cmdline`` for
``foo.params``, strips ``foo.``, and passes them to the kernel along with
params given in modprobe args or ``/etc/modprobe.d/*.conf`` files,
in the following order:

1. parameters given via ``/etc/modprobe.d/*.conf``::

	options foo dyndbg=+pt
	options foo dyndbg # defaults to +p

2. ``foo.dyndbg`` as given in boot args, ``foo.`` is stripped and passed::

	foo.dyndbg=" func bar +p; func buz +mp"

3. args to modprobe::

	modprobe foo dyndbg==pmf # override previous settings

These ``dyndbg`` queries are applied in order, with last having final say.
This allows boot args to override or modify those from ``/etc/modprobe.d``
(sensible, since 1 is system wide, 2 is kernel or boot specific), and
modprobe args to override both.

In the ``foo.dyndbg="QUERY"`` form, the query must exclude ``module foo``.
``foo`` is extracted from the param-name, and applied to each query in
``QUERY``, and only 1 match-spec of each type is allowed.

The ``dyndbg`` option is a "fake" module parameter, which means:

- modules do not need to define it explicitly
- every module gets it tacitly, whether they use pr_debug or not
- it doesn't appear in ``/sys/module/$module/parameters/``
  To see it, grep the control file, or inspect ``/proc/cmdline.``

For ``CONFIG_DYNAMIC_DEBUG`` kernels, any settings given at boot-time (or
enabled by ``-DDEBUG`` flag during compilation) can be disabled later via
the debugfs interface if the debug messages are no longer needed::

   echo "module module_name -p" > /proc/dynamic_debug/control

Examples
========

::

  // enable the message at line 1603 of file svcsock.c
  :#> ddcmd 'file svcsock.c line 1603 +p'

  // enable all the messages in file svcsock.c
  :#> ddcmd 'file svcsock.c +p'

  // enable all the messages in the NFS server module
  :#> ddcmd 'module nfsd +p'

  // enable all 12 messages in the function svc_process()
  :#> ddcmd 'func svc_process +p'

  // disable all 12 messages in the function svc_process()
  :#> ddcmd 'func svc_process -p'

  // enable messages for NFS calls READ, READLINK, READDIR and READDIR+.
  :#> ddcmd 'format "nfsd: READ" +p'

  // enable messages in files of which the paths include string "usb"
  :#> ddcmd 'file *usb* +p'

  // enable all messages
  :#> ddcmd '+p'

  // add module, function to all enabled messages
  :#> ddcmd '+mf'

  // boot-args example, with newlines and comments for readability
  Kernel command line: ...
    // see what's going on in dyndbg=value processing
    dynamic_debug.verbose=3
    // enable pr_debugs in the btrfs module (can be builtin or loadable)
    btrfs.dyndbg="+p"
    // enable pr_debugs in all files under init/
    // and the function parse_one, #cmt is stripped
    dyndbg="file init/* +p #cmt ; func parse_one +p"
    // enable pr_debugs in 2 functions in a module loaded later
    pc87360.dyndbg="func pc87360_init_device +p; func pc87360_find +p"

Kernel Configuration
====================

Dynamic Debug is enabled via kernel config items::

  CONFIG_DYNAMIC_DEBUG=y	# build catalog, enables CORE
  CONFIG_DYNAMIC_DEBUG_CORE=y	# enable mechanics only, skip catalog

If you do not want to enable dynamic debug globally (i.e. in some embedded
system), you may set ``CONFIG_DYNAMIC_DEBUG_CORE`` as basic support of dynamic
debug and add ``ccflags := -DDYNAMIC_DEBUG_MODULE`` into the Makefile of any
modules which you'd like to dynamically debug later.


Kernel *prdbg* API
==================

The following functions are cataloged and controllable when dynamic
debug is enabled::

  pr_debug()
  dev_dbg()
  print_hex_dump_debug()
  print_hex_dump_bytes()

Otherwise, they are off by default; ``ccflags += -DDEBUG`` or
``#define DEBUG`` in a source file will enable them appropriately.

If ``CONFIG_DYNAMIC_DEBUG`` is not set, ``print_hex_dump_debug()`` is
just a shortcut for ``print_hex_dump(KERN_DEBUG)``.

For ``print_hex_dump_debug()``/``print_hex_dump_bytes()``, format string is
its ``prefix_str`` argument, if it is constant string; or ``hexdump``
in case ``prefix_str`` is built dynamically.

---

### Documentation Admin Guide Edid (`Documentation/admin-guide/edid.rst`)

.. SPDX-License-Identifier: GPL-2.0

====
EDID
====

In the good old days when graphics parameters were configured explicitly
in a file called xorg.conf, even broken hardware could be managed.

Today, with the advent of Kernel Mode Setting, a graphics board is
either correctly working because all components follow the standards -
or the computer is unusable, because the screen remains dark after
booting or it displays the wrong area. Cases when this happens are:

- The graphics board does not recognize the monitor.
- The graphics board is unable to detect any EDID data.
- The graphics board incorrectly forwards EDID data to the driver.
- The monitor sends no or bogus EDID data.
- A KVM sends its own EDID data instead of querying the connected monitor.

Adding the kernel parameter "nomodeset" helps in most cases, but causes
restrictions later on.

As a remedy for such situations, the kernel configuration item
CONFIG_DRM_LOAD_EDID_FIRMWARE was introduced. It allows to provide an
individually prepared or corrected EDID data set in the /lib/firmware
directory from where it is loaded via the firmware interface.

---

### Documentation Admin Guide Efi Stub (`Documentation/admin-guide/efi-stub.rst`)

=================
The EFI Boot Stub
=================

On the x86 and ARM platforms, a kernel zImage/bzImage can masquerade
as a PE/COFF image, thereby convincing EFI firmware loaders to load
it as an EFI executable. The code that modifies the bzImage header,
along with the EFI-specific entry point that the firmware loader
jumps to are collectively known as the "EFI boot stub", and live in
arch/x86/boot/header.S and drivers/firmware/efi/libstub/x86-stub.c,
respectively. For ARM the EFI stub is implemented in
arch/arm/boot/compressed/efi-header.S and
drivers/firmware/efi/libstub/arm32-stub.c. EFI stub code that is shared
between architectures is in drivers/firmware/efi/libstub.

For arm64, there is no compressed kernel support, so the Image itself
masquerades as a PE/COFF image and the EFI stub is linked into the
kernel. The arm64 EFI stub lives in drivers/firmware/efi/libstub/arm64.c
and drivers/firmware/efi/libstub/arm64-stub.c.

By using the EFI boot stub it's possible to boot a Linux kernel
without the use of a conventional EFI boot loader, such as grub or
elilo. Since the EFI boot stub performs the jobs of a boot loader, in
a certain sense it *IS* the boot loader.

The EFI boot stub is enabled with the CONFIG_EFI_STUB kernel option.


How to install bzImage.efi
--------------------------

The bzImage located in arch/x86/boot/bzImage must be copied to the EFI
System Partition (ESP) and renamed with the extension ".efi". Without
the extension the EFI firmware loader will refuse to execute it. It's
not possible to execute bzImage.efi from the usual Linux file systems
because EFI firmware doesn't have support for them. For ARM the
arch/arm/boot/zImage should be copied to the system partition, and it
may not need to be renamed. Similarly for arm64, arch/arm64/boot/Image
should be copied but not necessarily renamed.


Passing kernel parameters from the EFI shell
--------------------------------------------

Arguments to the kernel can be passed after bzImage.efi, e.g.::

	fs0:> bzImage.efi console=ttyS0 root=/dev/sda4


The "initrd=" option
--------------------

Like most boot loaders, the EFI stub allows the user to specify
multiple initrd files using the "initrd=" option. This is the only EFI
stub-specific command line parameter, everything else is passed to the
kernel when it boots.

The path to the initrd file must be an absolute path from the
beginning of the ESP, relative path names do not work. Also, the path
is an EFI-style path and directory elements must be separated with
backslashes (\). For example, given the following directory layout::

  fs0:>
	Kernels\
			bzImage.efi
			initrd-large.img

	Ramdisks\
			initrd-small.img
			initrd-medium.img

to boot with the initrd-large.img file if the current working
directory is fs0:\Kernels, the following command must be used::

	fs0:\Kernels> bzImage.efi initrd=\Kernels\initrd-large.img

Notice how bzImage.efi can be specified with a relative path. That's
because the image we're executing is interpreted by the EFI shell,
which understands relative paths, whereas the rest of the command line
is passed to bzImage.efi.


The "dtb=" option
-----------------

For the ARM and arm64 architectures, a device tree must be provided to
the kernel. Normally firmware shall supply the device tree via the
EFI CONFIGURATION TABLE. However, the "dtb=" command line option can
be used to override the firmware supplied device tree, or to supply
one when firmware is unable to.

Please note: Firmware adds runtime configuration information to the
device tree before booting the kernel. If dtb= is used to override
the device tree, then any runtime data provided by firmware will be
lost. The dtb= option should only be used either as a debug tool, or
as a last resort when a device tree is not provided in the EFI
CONFIGURATION TABLE.

"dtb=" is processed in the same manner as the "initrd=" option that is
described above.

---

### Documentation Admin Guide Ext4 (`Documentation/admin-guide/ext4.rst`)

.. SPDX-License-Identifier: GPL-2.0

========================
ext4 General Information
========================

Ext4 is an advanced level of the ext3 filesystem which incorporates
scalability and reliability enhancements for supporting large filesystems
(64 bit) in keeping with increasing disk capacities and state-of-the-art
feature requirements.

Mailing list:	linux-ext4@vger.kernel.org
Web site:	http://ext4.wiki.kernel.org


Quick usage instructions
========================

Note: More extensive information for getting started with ext4 can be
found at the ext4 wiki site at the URL:
http://ext4.wiki.kernel.org/index.php/Ext4_Howto

  - The latest version of e2fsprogs can be found at:

    https://www.kernel.org/pub/linux/kernel/people/tytso/e2fsprogs/

	or

    http://sourceforge.net/project/showfiles.php?group_id=2406

	or grab the latest git repository from:

   https://git.kernel.org/pub/scm/fs/ext2/e2fsprogs.git

  - Create a new filesystem using the ext4 filesystem type:

        # mke2fs -t ext4 /dev/hda1

    Or to configure an existing ext3 filesystem to support extents:

	# tune2fs -O extents /dev/hda1

    If the filesystem was created with 128 byte inodes, it can be
    converted to use 256 byte for greater efficiency via:

        # tune2fs -I 256 /dev/hda1

  - Mounting:

	# mount -t ext4 /dev/hda1 /wherever

  - When comparing performance with other filesystems, it's always
    important to try multiple workloads; very often a subtle change in a
    workload parameter can completely change the ranking of which
    filesystems do well compared to others.  When comparing versus ext3,
    note that ext4 enables write barriers by default, while ext3 does
    not enable write barriers by default.  So it is useful to use
    explicitly specify whether barriers are enabled or not when via the
    '-o barriers=[0|1]' mount option for both ext3 and ext4 filesystems
    for a fair comparison.  When tuning ext3 for best benchmark numbers,
    it is often worthwhile to try changing the data journaling mode; '-o
    data=writeback' can be faster for some workloads.  (Note however that
    running mounted with data=writeback can potentially leave stale data
    exposed in recently written files in case of an unclean shutdown,
    which could be a security exposure in some situations.)  Configuring
    the filesystem with a large journal can also be helpful for
    metadata-intensive workloads.

Features
========

Currently Available
-------------------

* ability to use filesystems > 16TB (e2fsprogs support not available yet)
* extent format reduces metadata overhead (RAM, IO for access, transactions)
* extent format more robust in face of on-disk corruption due to magics,
* internal redundancy in tree
* improved file allocation (multi-block alloc)
* lift 32000 subdirectory limit imposed by i_links_count[1]
* nsec timestamps for mtime, atime, ctime, create time
* inode version field on disk (NFSv4, Lustre)
* reduced e2fsck time via uninit_bg feature
* journal checksumming for robustness, performance
* persistent file preallocation (e.g for streaming media, databases)
* ability to pack bitmaps and inode tables into larger virtual groups via the
  flex_bg feature
* large file support
* inode allocation using large virtual block groups via flex_bg
* delayed allocation
* large block (up to pagesize) support
* efficient new ordered mode in JBD2 and ext4 (avoid using buffer head to force
  the ordering)
* Case-insensitive file name lookups
* file-based encryption support (fscrypt)
* file-based verity support (fsverity)

[1] Filesystems with a block size of 1k may see a limit imposed by the
directory hash tree having a maximum depth of two.

case-insensitive file name lookups
======================================================

The case-insensitive file name lookup feature is supported on a
per-directory basis, allowing the user to mix case-insensitive and
case-sensitive directories in the same filesystem.  It is enabled by
flipping the +F inode attribute of an empty directory.  The
case-insensitive string match operation is only defined when we know how
text in encoded in a byte sequence.  For that reason, in order to enable
case-insensitive directories, the filesystem must have the
casefold feature, which stores the filesystem-wide encoding
model used.  By default, the charset adopted is the latest version of
Unicode (12.1.0, by the time of this writing), encoded in the UTF-8
form.  The comparison algorithm is implemented by normalizing the
strings to the Canonical decomposition form, as defined by Unicode,
followed by a byte per byte comparison.

The case-awareness is name-preserving on the disk, meaning that the file
name provided by userspace is a byte-per-byte match to what is actually
written in the disk.  The Unicode normalization format used by the
kernel is thus an internal representation, and not exposed to the
userspace nor to the disk, with the important exception of disk hashes,
used on large case-insensitive directories with DX feature.  On DX
directories, the hash must be calculated using the casefolded version of
the filename, meaning that the normalization format used actually has an
impact on where the directory entry is stored.

When we change from viewing filenames as opaque byte sequences to seeing
them as encoded strings we need to address what happens when a program
tries to create a file with an invalid name.  The Unicode subsystem
within the kernel leaves the decision of what to do in this case to the
filesystem, which select its preferred behavior by enabling/disabling
the strict mode.  When Ext4 encounters one of those strings and the
filesystem did not require strict mode, it falls back to considering the
entire string as an opaque byte sequence, which still allows the user to
operate on that file, but the case-insensitive lookups won't work.

Options
=======

When mounting an ext4 filesystem, the following option are accepted:
(*) == default

  ro
        Mount filesystem read only. Note that ext4 will replay the journal (and
        thus write to the partition) even when mounted "read only". The mount
        options "ro,noload" can be used to prevent writes to the filesystem.

  journal_checksum
        Enable checksumming of the journal transactions.  This will allow the
        recovery code in e2fsck and the kernel to detect corruption in the
        kernel.  It is a compatible change and will be ignored by older
        kernels.

  journal_async_commit
        Commit block can be written to disk without waiting for descriptor
        blocks. If enabled older kernels cannot mount the device. This will
        enable 'journal_checksum' internally.

  journal_path=path, journal_dev=devnum
        When the external journal device's major/minor numbers have changed,
        these options allow the user to specify the new journal location.  The
        journal device is identified through either its new major/minor numbers
        encoded in devnum, or via a path to the device.

  norecovery, noload
        Don't load the journal on mounting.  Note that if the filesystem was
        not unmounted cleanly, skipping the journal replay will lead to the
        filesystem containing inconsistencies that can lead to any number of
        problems.

  data=journal
        All data are committed into the journal prior to being written into the
        main file system.  Enabling this mode will disable delayed allocation
        and O_DIRECT support.

  data=ordered	(*)
        All data are forced directly out to the main file system prior to its
        metadata being committed to the journal.

  data=writeback
        Data ordering is not preserved, data may be written into the main file
        system after its metadata has been committed to the journal.

  commit=nrsec	(*)
        This setting limits the maximum age of the running transaction to
        'nrsec' seconds.  The default value is 5 seconds.  This means that if
        you lose your power, you will lose as much as the latest 5 seconds of
        metadata changes (your filesystem will not be damaged though, thanks
        to the journaling). This default value (or any low value) will hurt
        performance, but it's good for data-safety.  Setting it to 0 will have
        the same effect as leaving it at the default (5 seconds).  Setting it
        to very large values will improve performance.  Note that due to
        delayed allocation even older data can be lost on power failure since
        writeback of those data begins only after time set in
        /proc/sys/vm/dirty_expire_centisecs.

  barrier=<0|1(*)>, barrier(*), nobarrier
        This enables/disables the use of write barriers in the jbd code.
        barrier=0 disables, barrier=1 enables.  This also requires an IO stack
        which can support barriers, and if jbd gets an error on a barrier
        write, it will disable again with a warning.  Write barriers enforce
        proper on-disk ordering of journal commits, making volatile disk write
        caches safe to use, at some performance penalty.  If your disks are
        battery-backed in one way or another, disabling barriers may safely
        improve performance.  The mount options "barrier" and "nobarrier" can
        also be used to enable or disable barriers, for consistency with other
        ext4 mount options.

  inode_readahead_blks=n
        This tuning parameter controls the maximum number of inode table blocks
        that ext4's inode table readahead algorithm will pre-read into the
        buffer cache.  The default value is 32 blocks.

  bsddf	(*)
        Make 'df' act like BSD.

  minixdf
        Make 'df' act like Minix.

  debug
        Extra debugging information is sent to syslog.

  abort
        Simulate the effects of calling ext4_abort() for debugging purposes.
        This is normally used while remounting a filesystem which is already
        mounted.

  errors=remount-ro
        Remount the filesystem read-only on an error.

  errors=continue
        Keep going on a filesystem error.

  errors=panic
        Panic and halt the machine if an error occurs.  (These mount options
        override the errors behavior specified in the superblock, which can be
        configured using tune2fs)

  data_err=ignore(*)
        Just print an error message if an error occurs in a file data buffer.

  data_err=abort
        Abort the journal if an error occurs in a file data buffer.

  grpid | bsdgroups
        New objects have the group ID of their parent.

  nogrpid (*) | sysvgroups
        New objects have the group ID of their creator.

  resgid=n
        The group ID which may use the reserved blocks.

  resuid=n
        The user ID which may use the reserved blocks.

  sb=
        Use alternate superblock at this location.

  quota, noquota, grpquota, usrquota
        These options are ignored by the filesystem. They are used only by
        quota tools to recognize volumes where quota should be turned on. See
        documentation in the quota-tools package for more details
        (http://sourceforge.net/projects/linuxquota).

  jqfmt=<quota type>, usrjquota=<file>, grpjquota=<file>
        These options tell filesystem details about quota so that quota
        information can be properly updated during journal replay. They replace
        the above quota options. See documentation in the quota-tools package
        for more details (http://sourceforge.net/projects/linuxquota).

  stripe=n
        Number of filesystem blocks that mballoc will try to use for allocation
        size and alignment. For RAID5/6 systems this should be the number of
        data disks *  RAID chunk size in file system blocks.

  delalloc	(*)
        Defer block allocation until just before ext4 writes out the block(s)
        in question.  This allows ext4 to better allocation decisions more
        efficiently.

  nodelalloc
        Disable delayed allocation.  Blocks are allocated when the data is
        copied from userspace to the page cache, either via the write(2) system
        call or when an mmap'ed page which was previously unallocated is
        written for the first time.

  max_batch_time=usec
        Maximum amount of time ext4 should wait for additional filesystem
        operations to be batch together with a synchronous write operation.
        Since a synchronous write operation is going to force a commit and then
        a wait for the I/O complete, it doesn't cost much, and can be a huge
        throughput win, we wait for a small amount of time to see if any other
        transactions can piggyback on the synchronous write.   The algorithm
        used is designed to automatically tune for the speed of the disk, by
        measuring the amount of time (on average) that it takes to finish
        committing a transaction.  Call this time the "commit time".  If the
        time that the transaction has been running is less than the commit
        time, ext4 will try sleeping for the commit time to see if other
        operations will join the transaction.   The commit time is capped by
        the max_batch_time, which defaults to 15000us (15ms).   This
        optimization can be turned off entirely by setting max_batch_time to 0.

  min_batch_time=usec
        This parameter sets the commit time (as described above) to be at least
        min_batch_time.  It defaults to zero microseconds.  Increasing this
        parameter may improve the throughput of multi-threaded, synchronous
        workloads on very fast disks, at the cost of increasing latency.

  journal_ioprio=prio
        The I/O priority (from 0 to 7, where 0 is the highest priority) which
        should be used for I/O operations submitted by kjournald2 during a
        commit operation.  This defaults to 3, which is a slightly higher
        priority than the default I/O priority.

  auto_da_alloc(*), noauto_da_alloc
        Many broken applications don't use fsync() when replacing existing
        files via patterns such as fd = open("foo.new")/write(fd,..)/close(fd)/
        rename("foo.new", "foo"), or worse yet, fd = open("foo",
        O_TRUNC)/write(fd,..)/close(fd).  If auto_da_alloc is enabled, ext4
        will detect the replace-via-rename and replace-via-truncate patterns
        and force that any delayed allocation blocks are allocated such that at
        the next journal commit, in the default data=ordered mode, the data
        blocks of the new file are forced to disk before the rename() operation
        is committed.  This provides roughly the same level of guarantees as
        ext3, and avoids the "zero-length" problem that can happen when a
        system crashes before the delayed allocation blocks are forced to disk.

  noinit_itable
        Do not initialize any uninitialized inode table blocks in the
        background.  This feature may be used by installation CD's so that the
        install process can complete as quickly as possible; the inode table
        initialization process would then be deferred until the next time the
        file system is unmounted.

  init_itable=n
        The lazy itable init code will wait n times the number of milliseconds
        it took to zero out the previous block group's inode table.  This
        minimizes the impact on the system performance while file system's
        inode table is being initialized.

  discard, nodiscard(*)
        Controls whether ext4 should issue discard/TRIM commands to the
        underlying block device when blocks are freed.  This is useful for SSD
        devices and sparse/thinly-provisioned LUNs, but it is off by default
        until sufficient testing has been done.

  nouid32
        Disables 32-bit UIDs and GIDs.  This is for interoperability  with
        older kernels which only store and expect 16-bit values.

  block_validity(*), noblock_validity
        These options enable or disable the in-kernel facility for tracking
        filesystem metadata blocks within internal data structures.  This
        allows multi- block allocator and other routines to notice bugs or
        corrupted allocation bitmaps which cause blocks to be allocated which
        overlap with filesystem metadata blocks.

  dioread_lock, dioread_nolock
        Controls whether or not ext4 should use the DIO read locking. If the
        dioread_nolock option is specified ext4 will allocate uninitialized
        extent before buffer write and convert the extent to initialized after
        IO completes. This approach allows ext4 code to avoid using inode
        mutex, which improves scalability on high speed storages. However this
        does not work with data journaling and dioread_nolock option will be
        ignored with kernel warning. Note that dioread_nolock code path is only
        used for extent-based files.  Because of the restrictions this options
        comprises it is off by default (e.g. dioread_lock).

  max_dir_size_kb=n
        This limits the size of directories so that any attempt to expand them
        beyond the specified limit in kilobytes will cause an ENOSPC error.
        This is useful in memory constrained environments, where a very large
        directory can cause severe performance problems or even provoke the Out
        Of Memory killer.  (For example, if there is only 512mb memory
        available, a 176mb directory may seriously cramp the system's style.)

  i_version
        Enable 64-bit inode version support. This option is off by default.

  dax
        Use direct access (no page cache).  See
        Documentation/filesystems/dax.rst.  Note that this option is
        incompatible with data=journal.

  inlinecrypt
        When possible, encrypt/decrypt the contents of encrypted files using the
        blk-crypto framework rather than filesystem-layer encryption. This
        allows the use of inline encryption hardware. The on-disk format is
        unaffected. For more details, see
        Documentation/block/inline-encryption.rst.

Data Mode
=========
There are 3 different data modes:

* writeback mode

  In data=writeback mode, ext4 does not journal data at all.  This mode provides
  a similar level of journaling as that of XFS and JFS in its default
  mode - metadata journaling.  A crash+recovery can cause incorrect data to
  appear in files which were written shortly before the crash.  This mode will
  typically provide the best ext4 performance.

* ordered mode

  In data=ordered mode, ext4 only officially journals metadata, but it logically
  groups metadata information related to data changes with the data blocks into
  a single unit called a transaction.  When it's time to write the new metadata
  out to disk, the associated data blocks are written first.  In general, this
  mode performs slightly slower than writeback but significantly faster than
  journal mode.

* journal mode

  data=journal mode provides full data and metadata journaling.  All new data is
  written to the journal first, and then to its final location.  In the event of
  a crash, the journal can be replayed, bringing both data and metadata into a
  consistent state.  This mode is the slowest except when data needs to be read
  from and written to disk at the same time where it outperforms all others
  modes.  Enabling this mode will disable delayed allocation and O_DIRECT
  support.

/proc entries
=============

Information about mounted ext4 file systems can be found in
/proc/fs/ext4.  Each mounted filesystem will have a directory in
/proc/fs/ext4 based on its device name (i.e., /proc/fs/ext4/hdc or
/proc/fs/ext4/dm-0).   The files in each per-device directory are shown
in table below.

Files in /proc/fs/ext4/<devname>

  mb_groups
        details of multiblock allocator buddy cache of free blocks

/sys entries
============

Information about mounted ext4 file systems can be found in
/sys/fs/ext4.  Each mounted filesystem will have a directory in
/sys/fs/ext4 based on its device name (i.e., /sys/fs/ext4/hdc or
/sys/fs/ext4/dm-0).   The files in each per-device directory are shown
in table below.

Files in /sys/fs/ext4/<devname>:

(see also Documentation/ABI/testing/sysfs-fs-ext4)

  delayed_allocation_blocks
        This file is read-only and shows the number of blocks that are dirty in
        the page cache, but which do not have their location in the filesystem
        allocated yet.

  inode_goal
        Tuning parameter which (if non-zero) controls the goal inode used by
        the inode allocator in preference to all other allocation heuristics.
        This is intended for debugging use only, and should be 0 on production
        systems.

  inode_readahead_blks
        Tuning parameter which controls the maximum number of inode table
        blocks that ext4's inode table readahead algorithm will pre-read into
        the buffer cache.

  lifetime_write_kbytes
        This file is read-only and shows the number of kilobytes of data that
        have been written to this filesystem since it was created.

  max_writeback_mb_bump
        The maximum number of megabytes the writeback code will try to write
        out before move on to another inode.

  mb_group_prealloc
        The multiblock allocator will round up allocation requests to a
        multiple of this tuning parameter if the stripe size is not set in the
        ext4 superblock

  mb_max_to_scan
        The maximum number of extents the multiblock allocator will search to
        find the best extent.

  mb_min_to_scan
        The minimum number of extents the multiblock allocator will search to
        find the best extent.

  mb_order2_req
        Tuning parameter which controls the minimum size for requests (as a
        power of 2) where the buddy cache is used.

  mb_stats
        Controls whether the multiblock allocator should collect statistics,
        which are shown during the unmount. 1 means to collect statistics, 0
        means not to collect statistics.

  mb_stream_req
        Files which have fewer blocks than this tunable parameter will have
        their blocks allocated out of a block group specific preallocation
        pool, so that small files are packed closely together.  Each large file
        will have its blocks allocated out of its own unique preallocation
        pool.

  session_write_kbytes
        This file is read-only and shows the number of kilobytes of data that
        have been written to this filesystem since it was mounted.

  reserved_clusters
        This is RW file and contains number of reserved clusters in the file
        system which will be used in the specific situations to avoid costly
        zeroout, unexpected ENOSPC, or possible data loss. The default is 2% or
        4096 clusters, whichever is smaller and this can be changed however it
        can never exceed number of clusters in the file system. If there is not
        enough space for the reserved space when mounting the file mount will
        _not_ fail.

Ioctls
======

Ext4 implements various ioctls which can be used by applications to access
ext4-specific functionality. An incomplete list of these ioctls is shown in the
table below. This list includes truly ext4-specific ioctls (``EXT4_IOC_*``) as
well as ioctls that may have been ext4-specific originally but are now supported
by some other filesystem(s) too (``FS_IOC_*``).

Table of Ext4 ioctls

  FS_IOC_GETFLAGS
        Get additional attributes associated with inode.  The ioctl argument is
        an integer bitfield, with bit values described in ext4.h.

  FS_IOC_SETFLAGS
        Set additional attributes associated with inode.  The ioctl argument is
        an integer bitfield, with bit values described in ext4.h.

  EXT4_IOC_GETVERSION, EXT4_IOC_GETVERSION_OLD
        Get the inode i_generation number stored for each inode. The
        i_generation number is normally changed only when new inode is created
        and it is particularly useful for network filesystems. The '_OLD'
        version of this ioctl is an alias for FS_IOC_GETVERSION.

  EXT4_IOC_SETVERSION, EXT4_IOC_SETVERSION_OLD
        Set the inode i_generation number stored for each inode. The '_OLD'
        version of this ioctl is an alias for FS_IOC_SETVERSION.

  EXT4_IOC_GROUP_EXTEND
        This ioctl has the same purpose as the resize mount option. It allows
        to resize filesystem to the end of the last existing block group,
        further resize has to be done with resize2fs, either online, or
        offline. The argument points to the unsigned logn number representing
        the filesystem new block count.

  EXT4_IOC_MOVE_EXT
        Move the block extents from orig_fd (the one this ioctl is pointing to)
        to the donor_fd (the one specified in move_extent structure passed as
        an argument to this ioctl). Then, exchange inode metadata between
        orig_fd and donor_fd.  This is especially useful for online
        defragmentation, because the allocator has the opportunity to allocate
        moved blocks better, ideally into one contiguous extent.

  EXT4_IOC_GROUP_ADD
        Add a new group descriptor to an existing or new group descriptor
        block. The new group descriptor is described by ext4_new_group_input
        structure, which is passed as an argument to this ioctl. This is
        especially useful in conjunction with EXT4_IOC_GROUP_EXTEND, which
        allows online resize of the filesystem to the end of the last existing
        block group.  Those two ioctls combined is used in userspace online
        resize tool (e.g. resize2fs).

  EXT4_IOC_MIGRATE
        This ioctl operates on the filesystem itself.  It converts (migrates)
        ext3 indirect block mapped inode to ext4 extent mapped inode by walking
        through indirect block mapping of the original inode and converting
        contiguous block ranges into ext4 extents of the temporary inode. Then,
        inodes are swapped. This ioctl might help, when migrating from ext3 to
        ext4 filesystem, however suggestion is to create fresh ext4 filesystem
        and copy data from the backup. Note, that filesystem has to support
        extents for this ioctl to work.

  EXT4_IOC_ALLOC_DA_BLKS
        Force all of the delay allocated blocks to be allocated to preserve
        application-expected ext3 behaviour. Note that this will also start
        triggering a write of the data blocks, but this behaviour may change in
        the future as it is not necessary and has been done this way only for
        sake of simplicity.

  EXT4_IOC_RESIZE_FS
        Resize the filesystem to a new size.  The number of blocks of resized
        filesystem is passed in via 64 bit integer argument.  The kernel
        allocates bitmaps and inode table, the userspace tool thus just passes
        the new number of blocks.

  EXT4_IOC_SWAP_BOOT
        Swap i_blocks and associated attributes (like i_blocks, i_size,
        i_flags, ...) from the specified inode with inode EXT4_BOOT_LOADER_INO
        (#5). This is typically used to store a boot loader in a secure part of
        the filesystem, where it can't be changed by a normal user by accident.
        The data blocks of the previous boot loader will be associated with the
        given inode.

References
==========

kernel source:	<file:fs/ext4/>
		<file:fs/jbd2/>

programs:	http://e2fsprogs.sourceforge.net/

useful links:	https://fedoraproject.org/wiki/ext3-devel
		http://www.bullopensource.org/ext4/
		http://ext4.wiki.kernel.org/index.php/Main_Page
		https://fedoraproject.org/wiki/Features/Ext4

---

### Documentation Admin Guide Filesystem Monitoring (`Documentation/admin-guide/filesystem-monitoring.rst`)

.. SPDX-License-Identifier: GPL-2.0

====================================
File system Monitoring with fanotify
====================================

File system Error Reporting
===========================

Fanotify supports the FAN_FS_ERROR event type for file system-wide error
reporting.  It is meant to be used by file system health monitoring
daemons, which listen for these events and take actions (notify
sysadmin, start recovery) when a file system problem is detected.

By design, a FAN_FS_ERROR notification exposes sufficient information
for a monitoring tool to know a problem in the file system has happened.
It doesn't necessarily provide a user space application with semantics
to verify an IO operation was successfully executed.  That is out of
scope for this feature.  Instead, it is only meant as a framework for
early file system problem detection and reporting recovery tools.

When a file system operation fails, it is common for dozens of kernel
errors to cascade after the initial failure, hiding the original failure
log, which is usually the most useful debug data to troubleshoot the
problem.  For this reason, FAN_FS_ERROR tries to report only the first
error that occurred for a file system since the last notification, and
it simply counts additional errors.  This ensures that the most
important pieces of information are never lost.

FAN_FS_ERROR requires the fanotify group to be setup with the
FAN_REPORT_FID flag.

At the time of this writing, the only file system that emits FAN_FS_ERROR
notifications is Ext4.

A FAN_FS_ERROR Notification has the following format::

  ::

     [ Notification Metadata (Mandatory) ]
     [ Generic Error Record  (Mandatory) ]
     [ FID record            (Mandatory) ]

The order of records is not guaranteed, and new records might be added
in the future.  Therefore, applications must not rely on the order and
must be prepared to skip over unknown records. Please refer to
``samples/fanotify/fs-monitor.c`` for an example parser.

Generic error record
--------------------

The generic error record provides enough information for a file system
agnostic tool to learn about a problem in the file system, without
providing any additional details about the problem.  This record is
identified by ``struct fanotify_event_info_header.info_type`` being set
to FAN_EVENT_INFO_TYPE_ERROR.

  ::

     struct fanotify_event_info_error {
          struct fanotify_event_info_header hdr;
         __s32 error;
         __u32 error_count;
     };

The `error` field identifies the type of error using errno values.
`error_count` tracks the number of errors that occurred and were
suppressed to preserve the original error information, since the last
notification.

FID record
----------

The FID record can be used to uniquely identify the inode that triggered
the error through the combination of fsid and file handle.  A file system
specific application can use that information to attempt a recovery
procedure.  Errors that are not related to an inode are reported with an
empty file handle of type FILEID_INVALID.

---

### Documentation Admin Guide Hw Random (`Documentation/admin-guide/hw_random.rst`)

=================================
Hardware random number generators
=================================

Introduction
============

The hw_random framework is software that makes use of a
special hardware feature on your CPU or motherboard,
a Random Number Generator (RNG).  The software has two parts:
a core providing the /dev/hwrng character device and its
sysfs support, plus a hardware-specific driver that plugs
into that core.

To make the most effective use of these mechanisms, you
should download the support software as well.  Download the
latest version of the "rng-tools" package from:

	https://github.com/nhorman/rng-tools

Those tools use /dev/hwrng to fill the kernel entropy pool,
which is used internally and exported by the /dev/urandom and
/dev/random special files.

Theory of operation
===================

CHARACTER DEVICE.  Using the standard open()
and read() system calls, you can read random data from
the hardware RNG device.  This data is NOT CHECKED by any
fitness tests, and could potentially be bogus (if the
hardware is faulty or has been tampered with).  Data is only
output if the hardware "has-data" flag is set, but nevertheless
a security-conscious person would run fitness tests on the
data before assuming it is truly random.

The rng-tools package uses such tests in "rngd", and lets you
run them by hand with a "rngtest" utility.

/dev/hwrng is char device major 10, minor 183.

CLASS DEVICE.  There is a /sys/class/misc/hw_random node with
two unique attributes, "rng_available" and "rng_current".  The
"rng_available" attribute lists the hardware-specific drivers
available, while "rng_current" lists the one which is currently
connected to /dev/hwrng.  If your system has more than one
RNG available, you may change the one used by writing a name from
the list in "rng_available" into "rng_current".

==========================================================================


Hardware driver for Intel/AMD/VIA Random Number Generators (RNG)
	- Copyright 2000,2001 Jeff Garzik <jgarzik@pobox.com>
	- Copyright 2000,2001 Philipp Rumpf <prumpf@mandrakesoft.com>


About the Intel RNG hardware, from the firmware hub datasheet
=============================================================

The Firmware Hub integrates a Random Number Generator (RNG)
using thermal noise generated from inherently random quantum
mechanical properties of silicon. When not generating new random
bits the RNG circuitry will enter a low power state. Intel will
provide a binary software driver to give third party software
access to our RNG for use as a security feature. At this time,
the RNG is only to be used with a system in an OS-present state.

Intel RNG Driver notes
======================

FIXME: support poll(2)

.. note::

	request_mem_region was removed, for three reasons:

	1) Only one RNG is supported by this driver;
	2) The location used by the RNG is a fixed location in
	   MMIO-addressable memory;
	3) users with properly working BIOS e820 handling will always
	   have the region in which the RNG is located reserved, so
	   request_mem_region calls always fail for proper setups.
	   However, for people who use mem=XX, BIOS e820 information is
	   **not** in /proc/iomem, and request_mem_region(RNG_ADDR) can
	   succeed.

Driver details
==============

Based on:
	Intel 82802AB/82802AC Firmware Hub (FWH) Datasheet
	May 1999 Order Number: 290658-002 R

Intel 82802 Firmware Hub:
	Random Number Generator
	Programmer's Reference Manual
	December 1999 Order Number: 298029-001 R

Intel 82802 Firmware HUB Random Number Generator Driver
	Copyright (c) 2000 Matt Sottek <msottek@quiknet.com>

Special thanks to Matt Sottek.  I did the "guts", he
did the "brains" and all the testing.

---

### Documentation Admin Guide Index (`Documentation/admin-guide/index.rst`)

=================================================
The Linux kernel user's and administrator's guide
=================================================

The following is a collection of user-oriented documents that have been
added to the kernel over time.  There is, as yet, little overall order or
organization here — this material was not written to be a single, coherent
document!  With luck things will improve quickly over time.

General guides to kernel administration
---------------------------------------

This initial section contains overall information, including the README
file describing the kernel as a whole, documentation on kernel parameters,
etc.

.. toctree::
   :maxdepth: 1

   README
   devices

   features

A big part of the kernel's administrative interface is the /proc and sysfs
virtual filesystems; these documents describe how to interact with tem

.. toctree::
   :maxdepth: 1

   sysfs-rules
   sysctl/index
   cputopology
   abi

Security-related documentation:

.. toctree::
   :maxdepth: 1

   hw-vuln/index
   LSM/index
   perf-security

Booting the kernel
------------------

.. toctree::
   :maxdepth: 1

   bootconfig
   kernel-parameters
   efi-stub
   initrd


Tracking down and identifying problems
--------------------------------------

Here is a set of documents aimed at users who are trying to track down
problems and bugs in particular.

.. toctree::
   :maxdepth: 1

   reporting-issues
   reporting-regressions
   quickly-build-trimmed-linux
   verify-bugs-and-bisect-regressions
   bug-hunting
   bug-bisect
   tainted-kernels
   ramoops
   dynamic-debug-howto
   init
   kdump/index
   perf/index
   pstore-blk
   clearing-warn-once
   kernel-per-CPU-kthreads
   lockup-watchdogs
   RAS/index
   sysrq


Core-kernel subsystems
----------------------

These documents describe core-kernel administration interfaces that are
likely to be of interest on almost any system.

.. toctree::
   :maxdepth: 1

   cgroup-v2
   cgroup-v1/index
   cpu-load
   mm/index
   module-signing
   namespaces/index
   numastat
   pm/index
   syscall-user-dispatch

Support for non-native binary formats.  Note that some of these
documents are ... old ...

.. toctree::
   :maxdepth: 1

   binfmt-misc
   java
   mono


Block-layer and filesystem administration
-----------------------------------------

.. toctree::
   :maxdepth: 1

   bcache
   binderfs
   blockdev/index
   cifs/index
   device-mapper/index
   ext4
   filesystem-monitoring
   nfs/index
   iostats
   jfs
   md
   ufs
   xfs

Device-specific guides
----------------------

How to configure your hardware within your Linux system.

.. toctree::
   :maxdepth: 1

   acpi/index
   aoe/index
   auxdisplay/index
   braille-console
   btmrvl
   dell_rbu
   edid
   gpio/index
   hw_random
   laptops/index
   lcd-panel-cgram
   media/index
   nvme-multipath
   parport
   pnp
   rapidio
   rtc
   serial-console
   svga
   thermal/index
   thunderbolt
   vga-softcursor
   video-output

Workload analysis
-----------------

This is the beginning of a section with information of interest to
application developers and system integrators doing analysis of the
Linux kernel for safety critical applications. Documents supporting
analysis of kernel interactions with applications, and key kernel
subsystems expectations will be found here.

.. toctree::
   :maxdepth: 1

   workload-tracing

Everything else
---------------

A few hard-to-categorize and generally obsolete documents.

.. toctree::
   :maxdepth: 1

   ldm
   unicode

.. only::  subproject and html

   Indices
   =======

   * :ref:`genindex`

---

### Documentation Admin Guide Init (`Documentation/admin-guide/init.rst`)

Explaining the "No working init found." boot hang message
=========================================================
:Authors: Andreas Mohr <andi at lisas period de>
          Cristian Souza <cristianmsbr at gmail period com>

This document provides some high-level reasons for failure
(listed roughly in order of execution) to load the init binary.

1) **Unable to mount root FS**: Set "debug" kernel parameter (in bootloader
   config file or CONFIG_CMDLINE) to get more detailed kernel messages.

2) **init binary doesn't exist on rootfs**: Make sure you have the correct
   root FS type (and ``root=`` kernel parameter points to the correct
   partition), required drivers such as storage hardware (such as SCSI or
   USB!) and filesystem (ext3, jffs2, etc.) are builtin (alternatively as
   modules, to be pre-loaded by an initrd).

3) **Broken console device**: Possibly a conflict in ``console= setup``
   --> initial console unavailable. E.g. some serial consoles are unreliable
   due to serial IRQ issues (e.g. missing interrupt-based configuration).
   Try using a different ``console= device`` or e.g. ``netconsole=``.

4) **Binary exists but dependencies not available**: E.g. required library
   dependencies of the init binary such as ``/lib/ld-linux.so.2`` missing or
   broken. Use ``readelf -d <INIT>|grep NEEDED`` to find out which libraries
   are required.

5) **Binary cannot be loaded**: Make sure the binary's architecture matches
   your hardware. E.g. i386 vs. x86_64 mismatch, or trying to load x86 on ARM
   hardware. In case you tried loading a non-binary file here (shell script?),
   you should make sure that the script specifies an interpreter in its
   shebang header line (``#!/...``) that is fully working (including its
   library dependencies). And before tackling scripts, better first test a
   simple non-script binary such as ``/bin/sh`` and confirm its successful
   execution. To find out more, add code ``to init/main.c`` to display
   kernel_execve()s return values.

Please extend this explanation whenever you find new failure causes
(after all loading the init binary is a CRITICAL and hard transition step
which needs to be made as painless as possible), then submit a patch to LKML.
Further TODOs:

- Implement the various ``run_init_process()`` invocations via a struct array
  which can then store the ``kernel_execve()`` result value and on failure
  log it all by iterating over **all** results (very important usability fix).
- Try to make the implementation itself more helpful in general, e.g. by
  providing additional error messages at affected places.

---

### Documentation Admin Guide Initrd (`Documentation/admin-guide/initrd.rst`)

Using the initial RAM disk (initrd)
===================================

Written 1996,2000 by Werner Almesberger <werner.almesberger@epfl.ch> and
Hans Lermen <lermen@fgan.de>


initrd provides the capability to load a RAM disk by the boot loader.
This RAM disk can then be mounted as the root file system and programs
can be run from it. Afterwards, a new root file system can be mounted
from a different device. The previous root (from initrd) is then moved
to a directory and can be subsequently unmounted.

initrd is mainly designed to allow system startup to occur in two phases,
where the kernel comes up with a minimum set of compiled-in drivers, and
where additional modules are loaded from initrd.

This document gives a brief overview of the use of initrd. A more detailed
discussion of the boot process can be found in [#f1]_.


Operation
---------

When using initrd, the system typically boots as follows:

  1) the boot loader loads the kernel and the initial RAM disk
  2) the kernel converts initrd into a "normal" RAM disk and
     frees the memory used by initrd
  3) if the root device is not ``/dev/ram0``, the old (deprecated)
     change_root procedure is followed. see the "Obsolete root change
     mechanism" section below.
  4) root device is mounted. if it is ``/dev/ram0``, the initrd image is
     then mounted as root
  5) /sbin/init is executed (this can be any valid executable, including
     shell scripts; it is run with uid 0 and can do basically everything
     init can do).
  6) init mounts the "real" root file system
  7) init places the root file system at the root directory using the
     pivot_root system call
  8) init execs the ``/sbin/init`` on the new root filesystem, performing
     the usual boot sequence
  9) the initrd file system is removed

Note that changing the root directory does not involve unmounting it.
It is therefore possible to leave processes running on initrd during that
procedure. Also note that file systems mounted under initrd continue to
be accessible.


Boot command-line options
-------------------------

initrd adds the following new options::

  initrd=<path>    (e.g. LOADLIN)

    Loads the specified file as the initial RAM disk. When using LILO, you
    have to specify the RAM disk image file in /etc/lilo.conf, using the
    INITRD configuration variable.

  noinitrd

    initrd data is preserved but it is not converted to a RAM disk and
    the "normal" root file system is mounted. initrd data can be read
    from /dev/initrd. Note that the data in initrd can have any structure
    in this case and doesn't necessarily have to be a file system image.
    This option is used mainly for debugging.

    Note: /dev/initrd is read-only and it can only be used once. As soon
    as the last process has closed it, all data is freed and /dev/initrd
    can't be opened anymore.

  root=/dev/ram0

    initrd is mounted as root, and the normal boot procedure is followed,
    with the RAM disk mounted as root.

Compressed cpio images
----------------------

Recent kernels have support for populating a ramdisk from a compressed cpio
archive. On such systems, the creation of a ramdisk image doesn't need to
involve special block devices or loopbacks; you merely create a directory on
disk with the desired initrd content, cd to that directory, and run (as an
example)::

	find . | cpio --quiet -H newc -o | gzip -9 -n > /boot/imagefile.img

Examining the contents of an existing image file is just as simple::

	mkdir /tmp/imagefile
	cd /tmp/imagefile
	gzip -cd /boot/imagefile.img | cpio -imd --quiet

Installation
------------

First, a directory for the initrd file system has to be created on the
"normal" root file system, e.g.::

	# mkdir /initrd

The name is not relevant. More details can be found on the
:manpage:`pivot_root(2)` man page.

If the root file system is created during the boot procedure (i.e. if
you're building an install floppy), the root file system creation
procedure should create the ``/initrd`` directory.

If initrd will not be mounted in some cases, its content is still
accessible if the following device has been created::

	# mknod /dev/initrd b 1 250
	# chmod 400 /dev/initrd

Second, the kernel has to be compiled with RAM disk support and with
support for the initial RAM disk enabled. Also, at least all components
needed to execute programs from initrd (e.g. executable format and file
system) must be compiled into the kernel.

Third, you have to create the RAM disk image. This is done by creating a
file system on a block device, copying files to it as needed, and then
copying the content of the block device to the initrd file. With recent
kernels, at least three types of devices are suitable for that:

 - a floppy disk (works everywhere but it's painfully slow)
 - a RAM disk (fast, but allocates physical memory)
 - a loopback device (the most elegant solution)

We'll describe the loopback device method:

 1) make sure loopback block devices are configured into the kernel
 2) create an empty file system of the appropriate size, e.g.::

	# dd if=/dev/zero of=initrd bs=300k count=1
	# mke2fs -F -m0 initrd

    (if space is critical, you may want to use the Minix FS instead of Ext2)
 3) mount the file system, e.g.::

	# mount -t ext2 -o loop initrd /mnt

 4) create the console device::

    # mkdir /mnt/dev
    # mknod /mnt/dev/console c 5 1

 5) copy all the files that are needed to properly use the initrd
    environment. Don't forget the most important file, ``/sbin/init``

    .. note:: ``/sbin/init`` permissions must include "x" (execute).

 6) correct operation the initrd environment can frequently be tested
    even without rebooting with the command::

	# chroot /mnt /sbin/init

    This is of course limited to initrds that do not interfere with the
    general system state (e.g. by reconfiguring network interfaces,
    overwriting mounted devices, trying to start already running demons,
    etc. Note however that it is usually possible to use pivot_root in
    such a chroot'ed initrd environment.)
 7) unmount the file system::

	# umount /mnt

 8) the initrd is now in the file "initrd". Optionally, it can now be
    compressed::

	# gzip -9 initrd

For experimenting with initrd, you may want to take a rescue floppy and
only add a symbolic link from ``/sbin/init`` to ``/bin/sh``. Alternatively, you
can try the experimental newlib environment [#f2]_ to create a small
initrd.

Finally, you have to boot the kernel and load initrd. Almost all Linux
boot loaders support initrd. Since the boot process is still compatible
with an older mechanism, the following boot command line parameters
have to be given::

  root=/dev/ram0 rw

(rw is only necessary if writing to the initrd file system.)

With LOADLIN, you simply execute::

     LOADLIN <kernel> initrd=<disk_image>

e.g.::

	LOADLIN C:\LINUX\BZIMAGE initrd=C:\LINUX\INITRD.GZ root=/dev/ram0 rw

With LILO, you add the option ``INITRD=<path>`` to either the global section
or to the section of the respective kernel in ``/etc/lilo.conf``, and pass
the options using APPEND, e.g.::

  image = /bzImage
    initrd = /boot/initrd.gz
    append = "root=/dev/ram0 rw"

and run ``/sbin/lilo``

For other boot loaders, please refer to the respective documentation.

Now you can boot and enjoy using initrd.


Changing the root device
------------------------

When finished with its duties, init typically changes the root device
and proceeds with starting the Linux system on the "real" root device.

The procedure involves the following steps:
 - mounting the new root file system
 - turning it into the root file system
 - removing all accesses to the old (initrd) root file system
 - unmounting the initrd file system and de-allocating the RAM disk

Mounting the new root file system is easy: it just needs to be mounted on
a directory under the current root. Example::

	# mkdir /new-root
	# mount -o ro /dev/hda1 /new-root

The root change is accomplished with the pivot_root system call, which
is also available via the ``pivot_root`` utility (see :manpage:`pivot_root(8)`
man page; ``pivot_root`` is distributed with util-linux version 2.10h or higher
[#f3]_). ``pivot_root`` moves the current root to a directory under the new
root, and puts the new root at its place. The directory for the old root
must exist before calling ``pivot_root``. Example::

	# cd /new-root
	# mkdir initrd
	# pivot_root . initrd

Now, the init process may still access the old root via its
executable, shared libraries, standard input/output/error, and its
current root directory. All these references are dropped by the
following command::

	# exec chroot . what-follows <dev/console >dev/console 2>&1

Where what-follows is a program under the new root, e.g. ``/sbin/init``
If the new root file system will be used with udev and has no valid
``/dev`` directory, udev must be initialized before invoking chroot in order
to provide ``/dev/console``.

Note: implementation details of pivot_root may change with time. In order
to ensure compatibility, the following points should be observed:

 - before calling pivot_root, the current directory of the invoking
   process should point to the new root directory
 - use . as the first argument, and the _relative_ path of the directory
   for the old root as the second argument
 - a chroot program must be available under the old and the new root
 - chroot to the new root afterwards
 - use relative paths for dev/console in the exec command

Now, the initrd can be unmounted and the memory allocated by the RAM
disk can be freed::

	# umount /initrd
	# blockdev --flushbufs /dev/ram0

It is also possible to use initrd with an NFS-mounted root, see the
:manpage:`pivot_root(8)` man page for details.


Usage scenarios
---------------

The main motivation for implementing initrd was to allow for modular
kernel configuration at system installation. The procedure would work
as follows:

  1) system boots from floppy or other media with a minimal kernel
     (e.g. support for RAM disks, initrd, a.out, and the Ext2 FS) and
     loads initrd
  2) ``/sbin/init`` determines what is needed to (1) mount the "real" root FS
     (i.e. device type, device drivers, file system) and (2) the
     distribution media (e.g. CD-ROM, network, tape, ...). This can be
     done by asking the user, by auto-probing, or by using a hybrid
     approach.
  3) ``/sbin/init`` loads the necessary kernel modules
  4) ``/sbin/init`` creates and populates the root file system (this doesn't
     have to be a very usable system yet)
  5) ``/sbin/init`` invokes ``pivot_root`` to change the root file system and
     execs - via chroot - a program that continues the installation
  6) the boot loader is installed
  7) the boot loader is configured to load an initrd with the set of
     modules that was used to bring up the system (e.g. ``/initrd`` can be
     modified, then unmounted, and finally, the image is written from
     ``/dev/ram0`` or ``/dev/rd/0`` to a file)
  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
normal system operation without requiring the use of a bloated "generic"
kernel or re-compiling or re-linking the kernel.

A second scenario is for installations where Linux runs on systems with
different hardware configurations in a single administrative domain. In
such cases, it is desirable to generate only a small set of kernels
(ideally only one) and to keep the system-specific part of configuration
information as small as possible. In this case, a common initrd could be
generated with all the necessary modules. Then, only ``/sbin/init`` or a file
read by it would have to be different.

A third scenario is more convenient recovery disks, because information
like the location of the root FS partition doesn't have to be provided at
boot time, but the system loaded from initrd can invoke a user-friendly
dialog and it can also perform some sanity checks (or even some form of
auto-detection).

Last not least, CD-ROM distributors may use it for better installation
from CD, e.g. by using a boot floppy and bootstrapping a bigger RAM disk
via initrd from CD; or by booting via a loader like ``LOADLIN`` or directly
from the CD-ROM, and loading the RAM disk from CD without need of
floppies.


Obsolete root change mechanism
------------------------------

The following mechanism was used before the introduction of pivot_root.
Current kernels still support it, but you should _not_ rely on its
continued availability.

It works by mounting the "real" root device (i.e. the one set with rdev
in the kernel image or with root=... at the boot command line) as the
root file system when linuxrc exits. The initrd file system is then
unmounted, or, if it is still busy, moved to a directory ``/initrd``, if
such a directory exists on the new root file system.

In order to use this mechanism, you do not have to specify the boot
command options root, init, or rw. (If specified, they will affect
the real root file system, not the initrd environment.)

If /proc is mounted, the "real" root device can be changed from within
linuxrc by writing the number of the new root FS device to the special
file /proc/sys/kernel/real-root-dev, e.g.::

  # echo 0x301 >/proc/sys/kernel/real-root-dev

Note that the mechanism is incompatible with NFS and similar file
systems.

This old, deprecated mechanism is commonly called ``change_root``, while
the new, supported mechanism is called ``pivot_root``.


Mixed change_root and pivot_root mechanism
------------------------------------------

In case you did not want to use ``root=/dev/ram0`` to trigger the pivot_root
mechanism, you may create both ``/linuxrc`` and ``/sbin/init`` in your initrd
image.

``/linuxrc`` would contain only the following::

	#! /bin/sh
	mount -n -t proc proc /proc
	echo 0x0100 >/proc/sys/kernel/real-root-dev
	umount -n /proc

Once linuxrc exited, the kernel would mount again your initrd as root,
this time executing ``/sbin/init``. Again, it would be the duty of this init
to build the right environment (maybe using the ``root= device`` passed on
the cmdline) before the final execution of the real ``/sbin/init``.


Resources
---------

.. [#f1] Almesberger, Werner; "Booting Linux: The History and the Future"
    https://www.almesberger.net/cv/papers/ols2k-9.ps.gz
.. [#f2] newlib package (experimental), with initrd example
    https://www.sourceware.org/newlib/
.. [#f3] util-linux: Miscellaneous utilities for Linux
    https://www.kernel.org/pub/linux/utils/util-linux/

---

### Documentation Admin Guide Iostats (`Documentation/admin-guide/iostats.rst`)

=====================
I/O statistics fields
=====================

The kernel exposes disk statistics via ``/proc/diskstats`` and
``/sys/block/<device>/stat``. These stats are usually accessed via tools
such as ``sar`` and ``iostat``.

Here are examples using a disk with two partitions::

   /proc/diskstats:
     259       0 nvme0n1 255999 814 12369153 47919 996852 81 36123024 425995 0 301795 580470 0 0 0 0 60602 106555
     259       1 nvme0n1p1 492 813 17572 96 848 81 108288 210 0 76 307 0 0 0 0 0 0
     259       2 nvme0n1p2 255401 1 12343477 47799 996004 0 36014736 425784 0 344336 473584 0 0 0 0 0 0

   /sys/block/nvme0n1/stat:
     255999 814 12369153 47919 996858 81 36123056 426009 0 301809 580491 0 0 0 0 60605 106562

   /sys/block/nvme0n1/nvme0n1p1/stat:
     492 813 17572 96 848 81 108288 210 0 76 307 0 0 0 0 0 0

Both files contain the same 17 statistics. ``/sys/block/<device>/stat``
contains the fields for ``<device>``. In ``/proc/diskstats`` the fields
are prefixed with the major and minor device numbers and the device
name. In the example above, the first stat value for ``nvme0n1`` is
255999 in both files.

The sysfs ``stat`` file is efficient for monitoring a small, known set
of disks. If you're tracking a large number of devices,
``/proc/diskstats`` is often the better choice since it avoids the
overhead of opening and closing multiple files for each snapshot.

All fields are cumulative, monotonic counters, except for field 9, which
resets to zero as I/Os complete. The remaining fields reset at boot, on
device reattachment or reinitialization, or when the underlying counter
overflows. Applications reading these counters should detect and handle
resets when comparing stat snapshots.

Each set of stats only applies to the indicated device; if you want
system-wide stats you'll have to find all the devices and sum them all up.

Field  1 -- # of reads completed (unsigned long)
    This is the total number of reads completed successfully.

Field  2 -- # of reads merged, field 6 -- # of writes merged (unsigned long)
    Reads and writes which are adjacent to each other may be merged for
    efficiency.  Thus two 4K reads may become one 8K read before it is
    ultimately handed to the disk, and so it will be counted (and queued)
    as only one I/O.  This field lets you know how often this was done.

Field  3 -- # of sectors read (unsigned long)
    This is the total number of sectors read successfully.

Field  4 -- # of milliseconds spent reading (unsigned int)
    This is the total number of milliseconds spent by all reads (as
    measured from blk_mq_alloc_request() to __blk_mq_end_request()).

Field  5 -- # of writes completed (unsigned long)
    This is the total number of writes completed successfully.

Field  6 -- # of writes merged  (unsigned long)
    See the description of field 2.

Field  7 -- # of sectors written (unsigned long)
    This is the total number of sectors written successfully.

Field  8 -- # of milliseconds spent writing (unsigned int)
    This is the total number of milliseconds spent by all writes (as
    measured from blk_mq_alloc_request() to __blk_mq_end_request()).

Field  9 -- # of I/Os currently in progress (unsigned int)
    The only field that should go to zero. Incremented as requests are
    given to appropriate struct request_queue and decremented as they finish.

Field 10 -- # of milliseconds spent doing I/Os (unsigned int)
    This field increases so long as field 9 is nonzero.

    Since 5.0 this field counts jiffies when at least one request was
    started or completed. If request runs more than 2 jiffies then some
    I/O time might be not accounted in case of concurrent requests.

Field 11 -- weighted # of milliseconds spent doing I/Os (unsigned int)
    This field is incremented at each I/O start, I/O completion, I/O
    merge, or read of these stats by the number of I/Os in progress
    (field 9) times the number of milliseconds spent doing I/O since the
    last update of this field.  This can provide an easy measure of both
    I/O completion time and the backlog that may be accumulating.

Field 12 -- # of discards completed (unsigned long)
    This is the total number of discards completed successfully.

Field 13 -- # of discards merged (unsigned long)
    See the description of field 2

Field 14 -- # of sectors discarded (unsigned long)
    This is the total number of sectors discarded successfully.

Field 15 -- # of milliseconds spent discarding (unsigned int)
    This is the total number of milliseconds spent by all discards (as
    measured from blk_mq_alloc_request() to __blk_mq_end_request()).

Field 16 -- # of flush requests completed
    This is the total number of flush requests completed successfully.

    Block layer combines flush requests and executes at most one at a time.
    This counts flush requests executed by disk. Not tracked for partitions.

Field 17 -- # of milliseconds spent flushing
    This is the total number of milliseconds spent by all flush requests.

To avoid introducing performance bottlenecks, no locks are held while
modifying these counters.  This implies that minor inaccuracies may be
introduced when changes collide, so (for instance) adding up all the
read I/Os issued per partition should equal those made to the disks ...
but due to the lack of locking it may only be very close.

In 2.6+, there are counters for each CPU, which make the lack of locking
almost a non-issue.  When the statistics are read, the per-CPU counters
are summed (possibly overflowing the unsigned long variable they are
summed to) and the result given to the user.  There is no convenient
user interface for accessing the per-CPU counters themselves.

Since 4.19 request times are measured with nanoseconds precision and
truncated to milliseconds before showing in this interface.

Disks vs Partitions
-------------------

There were significant changes between 2.4 and 2.6+ in the I/O subsystem.
As a result, some statistic information disappeared. The translation from
a disk address relative to a partition to the disk address relative to
the host disk happens much earlier.  All merges and timings now happen
at the disk level rather than at both the disk and partition level as
in 2.4.  Consequently, you'll see a different statistics output on 2.6+ for
partitions from that for disks.  There are only *four* fields available
for partitions on 2.6+ machines.  This is reflected in the examples above.

Field  1 -- # of reads issued
    This is the total number of reads issued to this partition.

Field  2 -- # of sectors read
    This is the total number of sectors requested to be read from this
    partition.

Field  3 -- # of writes issued
    This is the total number of writes issued to this partition.

Field  4 -- # of sectors written
    This is the total number of sectors requested to be written to
    this partition.

Note that since the address is translated to a disk-relative one, and no
record of the partition-relative address is kept, the subsequent success
or failure of the read cannot be attributed to the partition.  In other
words, the number of reads for partitions is counted slightly before time
of queuing for partitions, and at completion for whole disks.  This is
a subtle distinction that is probably uninteresting for most cases.

More significant is the error induced by counting the numbers of
reads/writes before merges for partitions and after for disks. Since a
typical workload usually contains a lot of successive and adjacent requests,
the number of reads/writes issued can be several times higher than the
number of reads/writes completed.

In 2.6.25, the full statistic set is again available for partitions and
disk and partition statistics are consistent again. Since we still don't
keep record of the partition-relative address, an operation is attributed to
the partition which contains the first sector of the request after the
eventual merges. As requests can be merged across partition, this could lead
to some (probably insignificant) inaccuracy.

Additional notes
----------------

In 2.6+, sysfs is not mounted by default.  If your distribution of
Linux hasn't added it already, here's the line you'll want to add to
your ``/etc/fstab``::

	none /sys sysfs defaults 0 0


In 2.6+, all disk statistics were removed from ``/proc/stat``.  In 2.4, they
appear in both ``/proc/partitions`` and ``/proc/stat``, although the ones in
``/proc/stat`` take a very different format from those in ``/proc/partitions``
(see proc(5), if your system has it.)

-- ricklind@us.ibm.com

---

### Documentation Admin Guide Java (`Documentation/admin-guide/java.rst`)

Java(tm) Binary Kernel Support for Linux v1.03
----------------------------------------------

Linux beats them ALL! While all other OS's are TALKING about direct
support of Java Binaries in the OS, Linux is doing it!

You can execute Java applications and Java Applets just like any
other program after you have done the following:

1) You MUST FIRST install the Java Developers Kit for Linux.
   The Java on Linux HOWTO gives the details on getting and
   installing this. This HOWTO can be found at:

	ftp://sunsite.unc.edu/pub/Linux/docs/HOWTO/Java-HOWTO

   You should also set up a reasonable CLASSPATH environment
   variable to use Java applications that make use of any
   nonstandard classes (not included in the same directory
   as the application itself).

2) You have to compile BINFMT_MISC either as a module or into
   the kernel (``CONFIG_BINFMT_MISC``) and set it up properly.
   If you choose to compile it as a module, you will have
   to insert it manually with modprobe/insmod, as kmod
   cannot easily be supported with binfmt_misc.
   Read the file 'binfmt_misc.txt' in this directory to know
   more about the configuration process.

3) Add the following configuration items to binfmt_misc
   (you should really have read ``binfmt_misc.txt`` now):
   support for Java applications::

     ':Java:M::\xca\xfe\xba\xbe::/usr/local/bin/javawrapper:'

   support for executable Jar files::

     ':ExecutableJAR:E::jar::/usr/local/bin/jarwrapper:'

   support for Java Applets::

     ':Applet:E::html::/usr/bin/appletviewer:'

   or the following, if you want to be more selective::

     ':Applet:M::`` in the first line
   (``<`` has to be the first character!) to let this work!

   For the compiled Java programs you need a wrapper script like the
   following (this is because Java is broken in case of the filename
   handling), again fix the path names, both in the script and in the
   above given configuration string.

   You, too, need the little program after the script. Compile like::

	gcc -O2 -o javaclassname javaclassname.c

   and stick it to ``/usr/local/bin``.

   Both the javawrapper shellscript and the javaclassname program
   were supplied by Colin J. Watson <cjw44@cam.ac.uk>.

Javawrapper shell script:

.. code-block:: sh

  #!/bin/bash
  # /usr/local/bin/javawrapper - the wrapper for binfmt_misc/java

  if [ -z "$1" ]; then
	exec 1>&2
	echo Usage: $0 class-file
	exit 1
  fi

  CLASS=$1
  FQCLASS=`/usr/local/bin/javaclassname $1`
  FQCLASSN=`echo $FQCLASS | sed -e 's/^.*\.\([^.]*\)$/\1/'`
  FQCLASSP=`echo $FQCLASS | sed -e 's-\.-/-g' -e 's-^[^/]*$--' -e 's-/[^/]*$--'`

  # for example:
  # CLASS=Test.class
  # FQCLASS=foo.bar.Test
  # FQCLASSN=Test
  # FQCLASSP=foo/bar

  unset CLASSBASE

  declare -i LINKLEVEL=0

  while :; do
	if [ "`basename $CLASS .class`" == "$FQCLASSN" ]; then
		# See if this directory works straight off
		cd -L `dirname $CLASS`
		CLASSDIR=$PWD
		cd $OLDPWD
		if echo $CLASSDIR | grep -q "$FQCLASSP$"; then
			CLASSBASE=`echo $CLASSDIR | sed -e "s.$FQCLASSP$.."`
			break;
		fi
		# Try dereferencing the directory name
		cd -P `dirname $CLASS`
		CLASSDIR=$PWD
		cd $OLDPWD
		if echo $CLASSDIR | grep -q "$FQCLASSP$"; then
			CLASSBASE=`echo $CLASSDIR | sed -e "s.$FQCLASSP$.."`
			break;
		fi
		# If no other possible filename exists
		if [ ! -L $CLASS ]; then
			exec 1>&2
			echo $0:
			echo "  $CLASS should be in a" \
			     "directory tree called $FQCLASSP"
			exit 1
		fi
	fi
	if [ ! -L $CLASS ]; then break; fi
	# Go down one more level of symbolic links
	let LINKLEVEL+=1
	if [ $LINKLEVEL -gt 5 ]; then
		exec 1>&2
		echo $0:
		echo "  Too many symbolic links encountered"
		exit 1
	fi
	CLASS=`ls --color=no -l $CLASS | sed -e 's/^.* \([^ ]*\)$/\1/'`
  done

  if [ -z "$CLASSBASE" ]; then
	if [ -z "$FQCLASSP" ]; then
		GOODNAME=$FQCLASSN.class
	else
		GOODNAME=$FQCLASSP/$FQCLASSN.class
	fi
	exec 1>&2
	echo $0:
	echo "  $FQCLASS should be in a file called $GOODNAME"
	exit 1
  fi

  if ! echo $CLASSPATH | grep -q "^\(.*:\)*$CLASSBASE\(:.*\)*"; then
	# class is not in CLASSPATH, so prepend dir of class to CLASSPATH
	if [ -z "${CLASSPATH}" ] ; then
		export CLASSPATH=$CLASSBASE
	else
		export CLASSPATH=$CLASSBASE:$CLASSPATH
	fi
  fi

  shift
  /usr/bin/java $FQCLASS "$@"

javaclassname.c:

.. code-block:: c

  /* javaclassname.c
   *
   * Extracts the class name from a Java class file; intended for use in a Java
   * wrapper of the type supported by the binfmt_misc option in the Linux kernel.
   *
   * Copyright (C) 1999 Colin J. Watson <cjw44@cam.ac.uk>.
   *
   * This program is free software; you can redistribute it and/or modify
   * it under the terms of the GNU General Public License as published by
   * the Free Software Foundation; either version 2 of the License, or
   * (at your option) any later version.
   *
   * This program is distributed in the hope that it will be useful,
   * but WITHOUT ANY WARRANTY; without even the implied warranty of
   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   * GNU General Public License for more details.
   *
   * You should have received a copy of the GNU General Public License
   * along with this program; if not, write to the Free Software
   * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   */

  #include <stdlib.h>
  #include <stdio.h>
  #include <stdarg.h>
  #include <sys/types.h>

  /* From Sun's Java VM Specification, as tag entries in the constant pool. */

  #define CP_UTF8 1
  #define CP_INTEGER 3
  #define CP_FLOAT 4
  #define CP_LONG 5
  #define CP_DOUBLE 6
  #define CP_CLASS 7
  #define CP_STRING 8
  #define CP_FIELDREF 9
  #define CP_METHODREF 10
  #define CP_INTERFACEMETHODREF 11
  #define CP_NAMEANDTYPE 12
  #define CP_METHODHANDLE 15
  #define CP_METHODTYPE 16
  #define CP_INVOKEDYNAMIC 18

  /* Define some commonly used error messages */

  #define seek_error() error("%s: Cannot seek\n", program)
  #define corrupt_error() error("%s: Class file corrupt\n", program)
  #define eof_error() error("%s: Unexpected end of file\n", program)
  #define utf8_error() error("%s: Only ASCII 1-255 supported\n", program);

  char *program;

  long *pool;

  u_int8_t read_8(FILE *classfile);
  u_int16_t read_16(FILE *classfile);
  void skip_constant(FILE *classfile, u_int16_t *cur);
  void error(const char *format, ...);
  int main(int argc, char **argv);

  /* Reads in an unsigned 8-bit integer. */
  u_int8_t read_8(FILE *classfile)
  {
	int b = fgetc(classfile);
	if(b == EOF)
		eof_error();
	return (u_int8_t)b;
  }

  /* Reads in an unsigned 16-bit integer. */
  u_int16_t read_16(FILE *classfile)
  {
	int b1, b2;
	b1 = fgetc(classfile);
	if(b1 == EOF)
		eof_error();
	b2 = fgetc(classfile);
	if(b2 == EOF)
		eof_error();
	return (u_int16_t)((b1 << 8) | b2);
  }

  /* Reads in a value from the constant pool. */
  void skip_constant(FILE *classfile, u_int16_t *cur)
  {
	u_int16_t len;
	int seekerr = 1;
	pool[*cur] = ftell(classfile);
	switch(read_8(classfile))
	{
	case CP_UTF8:
		len = read_16(classfile);
		seekerr = fseek(classfile, len, SEEK_CUR);
		break;
	case CP_CLASS:
	case CP_STRING:
	case CP_METHODTYPE:
		seekerr = fseek(classfile, 2, SEEK_CUR);
		break;
	case CP_METHODHANDLE:
		seekerr = fseek(classfile, 3, SEEK_CUR);
		break;
	case CP_INTEGER:
	case CP_FLOAT:
	case CP_FIELDREF:
	case CP_METHODREF:
	case CP_INTERFACEMETHODREF:
	case CP_NAMEANDTYPE:
	case CP_INVOKEDYNAMIC:
		seekerr = fseek(classfile, 4, SEEK_CUR);
		break;
	case CP_LONG:
	case CP_DOUBLE:
		seekerr = fseek(classfile, 8, SEEK_CUR);
		++(*cur);
		break;
	default:
		corrupt_error();
	}
	if(seekerr)
		seek_error();
  }

  void error(const char *format, ...)
  {
	va_list ap;
	va_start(ap, format);
	vfprintf(stderr, format, ap);
	va_end(ap);
	exit(1);
  }

  int main(int argc, char **argv)
  {
	FILE *classfile;
	u_int16_t cp_count, i, this_class, classinfo_ptr;
	u_int8_t length;

	program = argv[0];

	if(!argv[1])
		error("%s: Missing input file\n", program);
	classfile = fopen(argv[1], "rb");
	if(!classfile)
		error("%s: Error opening %s\n", program, argv[1]);

	if(fseek(classfile, 8, SEEK_SET))  /* skip magic and version numbers */
		seek_error();
	cp_count = read_16(classfile);
	pool = calloc(cp_count, sizeof(long));
	if(!pool)
		error("%s: Out of memory for constant pool\n", program);

	for(i = 1; i < cp_count; ++i)
		skip_constant(classfile, &i);
	if(fseek(classfile, 2, SEEK_CUR))	/* skip access flags */
		seek_error();

	this_class = read_16(classfile);
	if(this_class < 1 || this_class >= cp_count)
		corrupt_error();
	if(!pool[this_class] || pool[this_class] == -1)
		corrupt_error();
	if(fseek(classfile, pool[this_class] + 1, SEEK_SET))
		seek_error();

	classinfo_ptr = read_16(classfile);
	if(classinfo_ptr < 1 || classinfo_ptr >= cp_count)
		corrupt_error();
	if(!pool[classinfo_ptr] || pool[classinfo_ptr] == -1)
		corrupt_error();
	if(fseek(classfile, pool[classinfo_ptr] + 1, SEEK_SET))
		seek_error();

	length = read_16(classfile);
	for(i = 0; i < length; ++i)
	{
		u_int8_t x = read_8(classfile);
		if((x & 0x80) || !x)
		{
			if((x & 0xE0) == 0xC0)
			{
				u_int8_t y = read_8(classfile);
				if((y & 0xC0) == 0x80)
				{
					int c = ((x & 0x1f) << 6) + (y & 0x3f);
					if(c) putchar(c);
					else utf8_error();
				}
				else utf8_error();
			}
			else utf8_error();
		}
		else if(x == '/') putchar('.');
		else putchar(x);
	}
	putchar('\n');
	free(pool);
	fclose(classfile);
	return 0;
  }

jarwrapper::

  #!/bin/bash
  # /usr/local/java/bin/jarwrapper - the wrapper for binfmt_misc/jar

  java -jar $1


Now simply ``chmod +x`` the ``.class``, ``.jar`` and/or ``.html`` files you
want to execute.

To add a Java program to your path best put a symbolic link to the main
.class file into /usr/bin (or another place you like) omitting the .class
extension. The directory containing the original .class file will be
added to your CLASSPATH during execution.


To test your new setup, enter in the following simple Java app, and name
it "HelloWorld.java":

.. code-block:: java

	class HelloWorld {
		public static void main(String args[]) {
			System.out.println("Hello World!");
		}
	}

Now compile the application with::

	javac HelloWorld.java

Set the executable permissions of the binary file, with::

	chmod 755 HelloWorld.class

And then execute it::

	./HelloWorld.class


To execute Java Jar files, simple chmod the ``*.jar`` files to include
the execution bit, then just do::

       ./Application.jar


To execute Java Applets, simple chmod the ``*.html`` files to include
the execution bit, then just do::

	./Applet.html


originally by Brian A. Lantz, brian@lantz.com
heavily edited for binfmt_misc by Richard Günther
new scripts by Colin J. Watson <cjw44@cam.ac.uk>
added executable Jar file support by Kurt Huwig <kurt@iku-netz.de>

---

### Documentation Admin Guide Jfs (`Documentation/admin-guide/jfs.rst`)

===========================================
IBM's Journaled File System (JFS) for Linux
===========================================

JFS Homepage:  http://jfs.sourceforge.net/

The following mount options are supported:

(*) == default

iocharset=name
                Character set to use for converting from Unicode to
		ASCII.  The default is to do no conversion.  Use
		iocharset=utf8 for UTF-8 translations.  This requires
		CONFIG_NLS_UTF8 to be set in the kernel .config file.
		iocharset=none specifies the default behavior explicitly.

resize=value
                Resize the volume to <value> blocks.  JFS only supports
		growing a volume, not shrinking it.  This option is only
		valid during a remount, when the volume is mounted
		read-write.  The resize keyword with no value will grow
		the volume to the full size of the partition.

nointegrity
                Do not write to the journal.  The primary use of this option
		is to allow for higher performance when restoring a volume
		from backup media.  The integrity of the volume is not
		guaranteed if the system abnormally abends.

integrity(*)
                Commit metadata changes to the journal.  Use this option to
		remount a volume where the nointegrity option was
		previously specified in order to restore normal behavior.

errors=continue
                        Keep going on a filesystem error.
errors=remount-ro(*)
                        Remount the filesystem read-only on an error.
errors=panic
                        Panic and halt the machine if an error occurs.

uid=value
                Override on-disk uid with specified value
gid=value
                Override on-disk gid with specified value
umask=value
                Override on-disk umask with specified octal value. For
                directories, the execute bit will be set if the corresponding
		read bit is set.

discard=minlen, discard/nodiscard(*)
                This enables/disables the use of discard/TRIM commands.
		The discard/TRIM commands are sent to the underlying
                block device when blocks are freed. This is useful for SSD
                devices and sparse/thinly-provisioned LUNs.  The FITRIM ioctl
		command is also available together with the nodiscard option.
		The value of minlen specifies the minimum blockcount, when
		a TRIM command to the block device is considered useful.
		When no value is given to the discard option, it defaults to
		64 blocks, which means 256KiB in JFS.
		The minlen value of discard overrides the minlen value given
		on an FITRIM ioctl().

The JFS mailing list can be subscribed to by using the link labeled
"Mail list Subscribe" at our web page http://jfs.sourceforge.net/

---

### Documentation Admin Guide Kernel Parameters (`Documentation/admin-guide/kernel-parameters.rst`)

.. SPDX-License-Identifier: GPL-2.0

.. _kernelparameters:

The kernel's command-line parameters
====================================

The following is a consolidated list of the kernel parameters as implemented
by the __setup(), early_param(), core_param() and module_param() macros
and sorted into English Dictionary order (defined as ignoring all
punctuation and sorting digits before letters in a case insensitive
manner), and with descriptions where known.

The kernel parses parameters from the kernel command line up to "``--``";
if it doesn't recognize a parameter and it doesn't contain a '.', the
parameter gets passed to init: parameters with '=' go into init's
environment, others are passed as command line arguments to init.
Everything after "``--``" is passed as an argument to init.

Module parameters can be specified in two ways: via the kernel command
line with a module name prefix, or via modprobe, e.g.::

	(kernel command line) usbcore.blinkenlights=1
	(modprobe command line) modprobe usbcore blinkenlights=1

Parameters for modules which are built into the kernel need to be
specified on the kernel command line.  modprobe looks through the
kernel command line (/proc/cmdline) and collects module parameters
when it loads a module, so the kernel command line can be used for
loadable modules too.

This document may not be entirely up to date and comprehensive. The command
"modinfo -p ${modulename}" shows a current list of all parameters of a loadable
module. Loadable modules, after being loaded into the running kernel, also
reveal their parameters in /sys/module/${modulename}/parameters/. Some of these
parameters may be changed at runtime by the command
``echo -n ${value} > /sys/module/${modulename}/parameters/${parm}``.

Special handling
----------------

Hyphens (dashes) and underscores are equivalent in parameter names, so::

	log_buf_len=1M print-fatal-signals=1

can also be entered as::

	log-buf-len=1M print_fatal_signals=1

Double-quotes can be used to protect spaces in values, e.g.::

	param="spaces in here"

cpu lists
~~~~~~~~~

Some kernel parameters take a list of CPUs as a value, e.g.  isolcpus,
nohz_full, irqaffinity, rcu_nocbs.  The format of this list is:

	<cpu number>,...,<cpu number>

or

	<cpu number>-<cpu number>
	(must be a positive range in ascending order)

or a mixture

<cpu number>,...,<cpu number>-<cpu number>

Note that for the special case of a range one can split the range into equal
sized groups and for each group use some amount from the beginning of that
group:

	<cpu number>-<cpu number>:<used size>/<group size>

For example one can add to the command line following parameter:

	isolcpus=1,2,10-20,100-2000:2/25

where the final item represents CPUs 100,101,125,126,150,151,...

The value "N" can be used to represent the numerically last CPU on the system,
i.e "foo_cpus=16-N" would be equivalent to "16-31" on a 32 core system.

Keep in mind that "N" is dynamic, so if system changes cause the bitmap width
to change, such as less cores in the CPU list, then N and any ranges using N
will also change.  Use the same on a small 4 core system, and "16-N" becomes
"16-3" and now the same boot input will be flagged as invalid (start > end).

The special case-tolerant group name "all" has a meaning of selecting all CPUs,
so that "nohz_full=all" is the equivalent of "nohz_full=0-N".

The semantics of "N" and "all" is supported on a level of bitmaps and holds for
all users of bitmap_parselist().

Metric suffixes
~~~~~~~~~~~~~~~

The [KMG] suffix is commonly described after a number of kernel
parameter values. 'K', 'M', 'G', 'T', 'P', and 'E' suffixes are allowed.
These letters represent the _binary_ multipliers 'Kilo', 'Mega', 'Giga',
'Tera', 'Peta', and 'Exa', equaling 2^10, 2^20, 2^30, 2^40, 2^50, and
2^60 bytes respectively. Such letter suffixes can also be entirely omitted.

Kernel Build Options
--------------------

The parameters listed below are only valid if certain kernel build options
were enabled and if respective hardware is present. This list should be kept
in alphabetical order. The text in square brackets at the beginning
of each description states the restrictions within which a parameter
is applicable::

	ACPI	ACPI support is enabled.
	AGP	AGP (Accelerated Graphics Port) is enabled.
	ALSA	ALSA sound support is enabled.
	APIC	APIC support is enabled.
	APM	Advanced Power Management support is enabled.
	APPARMOR AppArmor support is enabled.
	ARM	ARM architecture is enabled.
	ARM64	ARM64 architecture is enabled.
	AX25	Appropriate AX.25 support is enabled.
	CLK	Common clock infrastructure is enabled.
	CMA	Contiguous Memory Area support is enabled.
	DRM	Direct Rendering Management support is enabled.
	DYNAMIC_DEBUG Build in debug messages and enable them at runtime
	EARLY	Parameter processed too early to be embedded in initrd.
	EDD	BIOS Enhanced Disk Drive Services (EDD) is enabled
	EFI	EFI Partitioning (GPT) is enabled
	EVM	Extended Verification Module
	FB	The frame buffer device is enabled.
	FTRACE	Function tracing enabled.
	GCOV	GCOV profiling is enabled.
	HIBERNATION HIBERNATION is enabled.
	HW	Appropriate hardware is enabled.
	HYPER_V HYPERV support is enabled.
	IMA     Integrity measurement architecture is enabled.
	IP_PNP	IP DHCP, BOOTP, or RARP is enabled.
	IPV6	IPv6 support is enabled.
	ISAPNP	ISA PnP code is enabled.
	ISDN	Appropriate ISDN support is enabled.
	ISOL	CPU Isolation is enabled.
	JOY	Appropriate joystick support is enabled.
	KGDB	Kernel debugger support is enabled.
	KVM	Kernel Virtual Machine support is enabled.
	LIBATA  Libata driver is enabled
	LOONGARCH LoongArch architecture is enabled.
	LOOP	Loopback device support is enabled.
	LP	Printer support is enabled.
	M68k	M68k architecture is enabled.
			These options have more detailed description inside of
			Documentation/arch/m68k/kernel-options.rst.
	MDA	MDA console support is enabled.
	MIPS	MIPS architecture is enabled.
	MOUSE	Appropriate mouse support is enabled.
	MSI	Message Signaled Interrupts (PCI).
	MTD	MTD (Memory Technology Device) support is enabled.
	NET	Appropriate network support is enabled.
	NFS	Appropriate NFS support is enabled.
	NUMA	NUMA support is enabled.
	OF	Devicetree is enabled.
	PARISC	The PA-RISC architecture is enabled.
	PCI	PCI bus support is enabled.
	PCIE	PCI Express support is enabled.
	PCMCIA	The PCMCIA subsystem is enabled.
	PNP	Plug & Play support is enabled.
	PPC	PowerPC architecture is enabled.
	PPT	Parallel port support is enabled.
	PS2	Appropriate PS/2 support is enabled.
	PV_OPS	A paravirtualized kernel is enabled.
	RAM	RAM disk support is enabled.
	RDT	Intel Resource Director Technology.
	RISCV	RISCV architecture is enabled.
	S390	S390 architecture is enabled.
	SCSI	Appropriate SCSI support is enabled.
			A lot of drivers have their options described inside
			the Documentation/scsi/ sub-directory.
        SDW     SoundWire support is enabled.
	SECURITY Different security models are enabled.
	SELINUX SELinux support is enabled.
	SERIAL	Serial support is enabled.
	SH	SuperH architecture is enabled.
	SMP	The kernel is an SMP kernel.
	SPARC	Sparc architecture is enabled.
	SUSPEND	System suspend states are enabled.
	SWSUSP	Software suspend (hibernation) is enabled.
	TPM	TPM drivers are enabled.
	UMS	USB Mass Storage support is enabled.
	USB	USB support is enabled.
	USBHID	USB Human Interface Device support is enabled.
	V4L	Video For Linux support is enabled.
	VGA	The VGA console has been enabled.
	VMMIO   Driver for memory mapped virtio devices is enabled.
	VT	Virtual terminal support is enabled.
	WDT	Watchdog support is enabled.
	X86-32	X86-32, aka i386 architecture is enabled.
	X86-64	X86-64 architecture is enabled.
	X86	Either 32-bit or 64-bit x86 (same as X86-32+X86-64)
	X86_UV	SGI UV support is enabled.
	XEN	Xen support is enabled
	XTENSA	xtensa architecture is enabled.

In addition, the following text indicates that the option::

	BOOT	Is a boot loader parameter.
	BUGS=	Relates to possible processor bugs on the said processor.
	KNL	Is a kernel start-up parameter.

Parameters denoted with BOOT are actually interpreted by the boot
loader, and have no meaning to the kernel directly.
Do not modify the syntax of boot loader parameters without extreme
need or coordination with <Documentation/arch/x86/boot.rst>.

There are also arch-specific kernel-parameters not documented here.

Note that ALL kernel parameters listed below are CASE SENSITIVE, and that
a trailing = on the name of any parameter states that the parameter will
be entered as an environment variable, whereas its absence indicates that
it will appear as a kernel argument readable via /proc/cmdline by programs
running once the system is up.

The number of kernel parameters is not limited, but the length of the
complete command line (parameters including spaces etc.) is limited to
a fixed number of characters. This limit depends on the architecture
and is between 256 and 4096 characters. It is defined in the file
./include/uapi/asm-generic/setup.h as COMMAND_LINE_SIZE.

.. include:: kernel-parameters.txt
   :literal:

---

### Documentation Admin Guide Kernel Parameters (`Documentation/admin-guide/kernel-parameters.txt`)

accept_memory=  [MM]
			Format: { eager | lazy }
			default: lazy
			By default, unaccepted memory is accepted lazily to
			avoid prolonged boot times. The lazy option will add
			some runtime overhead until all memory is eventually
			accepted. In most cases the overhead is negligible.
			For some workloads or for debugging purposes
			accept_memory=eager can be used to accept all memory
			at once during boot.

	acpi=		[HW,ACPI,X86,ARM64,RISCV64,EARLY]
			Advanced Configuration and Power Interface
			Format: { force | on | off | strict | noirq | rsdt |
				  copy_dsdt | nospcr }
			force -- enable ACPI if default was off
			on -- enable ACPI but allow fallback to DT [arm64,riscv64]
			off -- disable ACPI if default was on
			noirq -- do not use ACPI for IRQ routing
			strict -- Be less tolerant of platforms that are not
				strictly ACPI specification compliant.
			rsdt -- prefer RSDT over (default) XSDT
			copy_dsdt -- copy DSDT to memory
			nocmcff -- Disable firmware first mode for corrected
			errors. This disables parsing the HEST CMC error
			source to check if firmware has set the FF flag. This
			may result in duplicate corrected error reports.
			nospcr -- disable console in ACPI SPCR table as
				default _serial_ console on ARM64
			For ARM64, ONLY "acpi=off", "acpi=on", "acpi=force" or
			"acpi=nospcr" are available
			For RISCV64, ONLY "acpi=off", "acpi=on" or "acpi=force"
			are available

			See also Documentation/power/runtime_pm.rst, pci=noacpi

	acpi_apic_instance=	[ACPI,IOAPIC,EARLY]
			Format: <int>
			2: use 2nd APIC table, if available
			1,0: use 1st APIC table
			default: 0

	acpi_backlight=	[HW,ACPI]
			{ vendor | video | native | none }
			If set to vendor, prefer vendor-specific driver
			(e.g. thinkpad_acpi, sony_acpi, etc.) instead
			of the ACPI video.ko driver.
			If set to video, use the ACPI video.ko driver.
			If set to native, use the device's native backlight mode.
			If set to none, disable the ACPI backlight interface.

	acpi_force_32bit_fadt_addr [ACPI,EARLY]
			force FADT to use 32 bit addresses rather than the
			64 bit X_* addresses. Some firmware have broken 64
			bit addresses for force ACPI ignore these and use
			the older legacy 32 bit addresses.

	acpica_no_return_repair [HW, ACPI]
			Disable AML predefined validation mechanism
			This mechanism can repair the evaluation result to make
			the return objects more ACPI specification compliant.
			This option is useful for developers to identify the
			root cause of an AML interpreter issue when the issue
			has something to do with the repair mechanism.

	acpi.debug_layer=	[HW,ACPI,ACPI_DEBUG]
	acpi.debug_level=	[HW,ACPI,ACPI_DEBUG]
			Format: <int>
			CONFIG_ACPI_DEBUG must be enabled to produce any ACPI
			debug output.  Bits in debug_layer correspond to a
			_COMPONENT in an ACPI source file, e.g.,
			    #define _COMPONENT ACPI_EVENTS
			Bits in debug_level correspond to a level in
			ACPI_DEBUG_PRINT statements, e.g.,
			    ACPI_DEBUG_PRINT((ACPI_DB_INFO, ...
			The debug_level mask defaults to "info".  See
			Documentation/firmware-guide/acpi/debug.rst for more information about
			debug layers and levels.

			Enable processor driver info messages:
			    acpi.debug_layer=0x20000000
			Enable AML "Debug" output, i.e., stores to the Debug
			object while interpreting AML:
			    acpi.debug_layer=0xffffffff acpi.debug_level=0x2
			Enable all messages related to ACPI hardware:
			    acpi.debug_layer=0x2 acpi.debug_level=0xffffffff

			Some values produce so much output that the system is
			unusable.  The "log_buf_len" parameter may be useful
			if you need to capture more output.

	acpi_enforce_resources=	[ACPI]
			{ strict | lax | no }
			Check for resource conflicts between native drivers
			and ACPI OperationRegions (SystemIO and SystemMemory
			only). IO ports and memory declared in ACPI might be
			used by the ACPI subsystem in arbitrary AML code and
			can interfere with legacy drivers.
			strict (default): access to resources claimed by ACPI
			is denied; legacy drivers trying to access reserved
			resources will fail to bind to device using them.
			lax: access to resources claimed by ACPI is allowed;
			legacy drivers trying to access reserved resources
			will bind successfully but a warning message is logged.
			no: ACPI OperationRegions are not marked as reserved,
			no further checks are performed.

	acpi_force_table_verification	[HW,ACPI,EARLY]
			Enable table checksum verification during early stage.
			By default, this is disabled due to x86 early mapping
			size limitation.

	acpi_irq_balance [HW,ACPI]
			ACPI will balance active IRQs
			default in APIC mode

	acpi_irq_nobalance [HW,ACPI]
			ACPI will not move active IRQs (default)
			default in PIC mode

	acpi_irq_isa=	[HW,ACPI] If irq_balance, mark listed IRQs used by ISA
			Format: <irq>,<irq>...

	acpi_irq_pci=	[HW,ACPI] If irq_balance, clear listed IRQs for
			use by PCI
			Format: <irq>,<irq>...

	acpi_mask_gpe=	[HW,ACPI]
			Due to the existence of _Lxx/_Exx, some GPEs triggered
			by unsupported hardware/firmware features can result in
			GPE floodings that cannot be automatically disabled by
			the GPE dispatcher.
			This facility can be used to prevent such uncontrolled
			GPE floodings.
			Format: <byte> or <bitmap-list>

	acpi_no_auto_serialize	[HW,ACPI]
			Disable auto-serialization of AML methods
			AML control methods that contain the opcodes to create
			named objects will be marked as "Serialized" by the
			auto-serialization feature.
			This feature is enabled by default.
			This option allows to turn off the feature.

	acpi_no_memhotplug [ACPI] Disable memory hotplug.  Useful for kdump
			   kernels.

	acpi_no_static_ssdt	[HW,ACPI,EARLY]
			Disable installation of static SSDTs at early boot time
			By default, SSDTs contained in the RSDT/XSDT will be
			installed automatically and they will appear under
			/sys/firmware/acpi/tables.
			This option turns off this feature.
			Note that specifying this option does not affect
			dynamic table installation which will install SSDT
			tables to /sys/firmware/acpi/tables/dynamic.

	acpi_no_watchdog	[HW,ACPI,WDT]
			Ignore the ACPI-based watchdog interface (WDAT) and let
			a native driver control the watchdog device instead.

	acpi_rsdp=	[ACPI,EFI,KEXEC,EARLY]
			Pass the RSDP address to the kernel, mostly used
			on machines running EFI runtime service to boot the
			second kernel for kdump.

	acpi_os_name=	[HW,ACPI] Tell ACPI BIOS the name of the OS
			Format: To spoof as Windows 98: ="Microsoft Windows"

	acpi_rev_override [ACPI] Override the _REV object to return 5 (instead
			of 2 which is mandated by ACPI 6) as the supported ACPI
			specification revision (when using this switch, it may
			be necessary to carry out a cold reboot _twice_ in a
			row to make it take effect on the platform firmware).

	acpi_osi=	[HW,ACPI] Modify list of supported OS interface strings
			acpi_osi="string1"	# add string1
			acpi_osi="!string2"	# remove string2
			acpi_osi=!*		# remove all strings
			acpi_osi=!		# disable all built-in OS vendor
						  strings
			acpi_osi=!!		# enable all built-in OS vendor
						  strings
			acpi_osi=		# disable all strings

			'acpi_osi=!' can be used in combination with single or
			multiple 'acpi_osi="string1"' to support specific OS
			vendor string(s).  Note that such command can only
			affect the default state of the OS vendor strings, thus
			it cannot affect the default state of the feature group
			strings and the current state of the OS vendor strings,
			specifying it multiple times through kernel command line
			is meaningless.  This command is useful when one do not
			care about the state of the feature group strings which
			should be controlled by the OSPM.
			Examples:
			  1. 'acpi_osi=! acpi_osi="Windows 2000"' is equivalent
			     to 'acpi_osi="Windows 2000" acpi_osi=!', they all
			     can make '_OSI("Windows 2000")' TRUE.

			'acpi_osi=' cannot be used in combination with other
			'acpi_osi=' command lines, the _OSI method will not
			exist in the ACPI namespace.  NOTE that such command can
			only affect the _OSI support state, thus specifying it
			multiple times through kernel command line is also
			meaningless.
			Examples:
			  1. 'acpi_osi=' can make 'CondRefOf(_OSI, Local1)'
			     FALSE.

			'acpi_osi=!*' can be used in combination with single or
			multiple 'acpi_osi="string1"' to support specific
			string(s).  Note that such command can affect the
			current state of both the OS vendor strings and the
			feature group strings, thus specifying it multiple times
			through kernel command line is meaningful.  But it may
			still not able to affect the final state of a string if
			there are quirks related to this string.  This command
			is useful when one want to control the state of the
			feature group strings to debug BIOS issues related to
			the OSPM features.
			Examples:
			  1. 'acpi_osi="Module Device" acpi_osi=!*' can make
			     '_OSI("Module Device")' FALSE.
			  2. 'acpi_osi=!* acpi_osi="Module Device"' can make
			     '_OSI("Module Device")' TRUE.
			  3. 'acpi_osi=! acpi_osi=!* acpi_osi="Windows 2000"' is
			     equivalent to
			     'acpi_osi=!* acpi_osi=! acpi_osi="Windows 2000"'
			     and
			     'acpi_osi=!* acpi_osi="Windows 2000" acpi_osi=!',
			     they all will make '_OSI("Windows 2000")' TRUE.

	acpi_pm_good	[X86]
			Override the pmtimer bug detection: force the kernel
			to assume that this machine's pmtimer latches its value
			and always returns good values.

	acpi_sci=	[HW,ACPI,EARLY] ACPI System Control Interrupt trigger mode
			Format: { level | edge | high | low }

	acpi_skip_timer_override [HW,ACPI,EARLY]
			Recognize and ignore IRQ0/pin2 Interrupt Override.
			For broken nForce2 BIOS resulting in XT-PIC timer.

	acpi_sleep=	[HW,ACPI] Sleep options
			Format: { s3_bios, s3_mode, s3_beep, s4_hwsig,
				  s4_nohwsig, old_ordering, nonvs,
				  sci_force_enable, nobl }
			See Documentation/power/video.rst for information on
			s3_bios and s3_mode.
			s3_beep is for debugging; it makes the PC's speaker beep
			as soon as the kernel's real-mode entry point is called.
			s4_hwsig causes the kernel to check the ACPI hardware
			signature during resume from hibernation, and gracefully
			refuse to resume if it has changed. This complies with
			the ACPI specification but not with reality, since
			Windows does not do this and many laptops do change it
			on docking. So the default behaviour is to allow resume
			and simply warn when the signature changes, unless the
			s4_hwsig option is enabled.
			s4_nohwsig prevents ACPI hardware signature from being
			used (or even warned about) during resume.
			old_ordering causes the ACPI 1.0 ordering of the _PTS
			control method, with respect to putting devices into
			low power states, to be enforced (the ACPI 2.0 ordering
			of _PTS is used by default).
			nonvs prevents the kernel from saving/restoring the
			ACPI NVS memory during suspend/hibernation and resume.
			sci_force_enable causes the kernel to set SCI_EN directly
			on resume from S1/S3 (which is against the ACPI spec,
			but some broken systems don't work without it).
			nobl causes the internal blacklist of systems known to
			behave incorrectly in some ways with respect to system
			suspend and resume to be ignored (use wisely).

	acpi_use_timer_override [HW,ACPI,EARLY]
			Use timer override. For some broken Nvidia NF5 boards
			that require a timer override, but don't have HPET

	add_efi_memmap	[EFI,X86,EARLY] Include EFI memory map in
			kernel's map of available physical RAM.

	agp=		[AGP]
			{ off | try_unsupported }
			off: disable AGP support
			try_unsupported: try to drive unsupported chipsets
				(may crash computer or cause data corruption)

	ALSA		[HW,ALSA]
			See Documentation/sound/alsa-configuration.rst

	alignment=	[KNL,ARM]
			Allow the default userspace alignment fault handler
			behaviour to be specified.  Bit 0 enables warnings,
			bit 1 enables fixups, and bit 2 sends a segfault.

	align_va_addr=	[X86-64]
			Align virtual addresses by clearing slice [14:12] when
			allocating a VMA at process creation time. This option
			gives you up to 3% performance improvement on AMD F15h
			machines (where it is enabled by default) for a
			CPU-intensive style benchmark, and it can vary highly in
			a microbenchmark depending on workload and compiler.

			32: only for 32-bit processes
			64: only for 64-bit processes
			on: enable for both 32- and 64-bit processes
			off: disable for both 32- and 64-bit processes

	alloc_snapshot	[FTRACE]
			Allocate the ftrace snapshot buffer on boot up when the
			main buffer is allocated. This is handy if debugging
			and you need to use tracing_snapshot() on boot up, and
			do not want to use tracing_snapshot_alloc() as it needs
			to be done where GFP_KERNEL allocations are allowed.

	allow_mismatched_32bit_el0 [ARM64,EARLY]
			Allow execve() of 32-bit applications and setting of the
			PER_LINUX32 personality on systems where only a strict
			subset of the CPUs support 32-bit EL0. When this
			parameter is present, the set of CPUs supporting 32-bit
			EL0 is indicated by /sys/devices/system/cpu/aarch32_el0
			and hot-unplug operations may be restricted.

			See Documentation/arch/arm64/asymmetric-32bit.rst for more
			information.

	amd_iommu=	[HW,X86-64]
			Pass parameters to the AMD IOMMU driver in the system.
			Possible values are:
			fullflush - Deprecated, equivalent to iommu.strict=1
			off	  - do not initialize any AMD IOMMU found in
				    the system
			force_isolation - Force device isolation for all
					  devices. The IOMMU driver is not
					  allowed anymore to lift isolation
					  requirements as needed. This option
					  does not override iommu=pt
			force_enable    - Force enable the IOMMU on platforms known
				          to be buggy with IOMMU enabled. Use this
				          option with care.
			pgtbl_v1        - Use v1 page table for DMA-API (Default).
			pgtbl_v2        - Use v2 page table for DMA-API.
			irtcachedis     - Disable Interrupt Remapping Table (IRT) caching.
			nohugepages     - Limit page-sizes used for v1 page-tables
				          to 4 KiB.
			v2_pgsizes_only - Limit page-sizes used for v1 page-tables
				          to 4KiB/2Mib/1GiB.


	amd_iommu_dump=	[HW,X86-64]
			Enable AMD IOMMU driver option to dump the ACPI table
			for AMD IOMMU. With this option enabled, AMD IOMMU
			driver will print ACPI tables for AMD IOMMU during
			IOMMU initialization.

	amd_iommu_intr=	[HW,X86-64]
			Specifies one of the following AMD IOMMU interrupt
			remapping modes:
			legacy     - Use legacy interrupt remapping mode.
			vapic      - Use virtual APIC mode, which allows IOMMU
			             to inject interrupts directly into guest.
			             This mode requires kvm-amd.avic=1.
			             (Default when IOMMU HW support is present.)

	amd_pstate=	[X86,EARLY]
			disable
			  Do not enable amd_pstate as the default
			  scaling driver for the supported processors
			passive
			  Use amd_pstate with passive mode as a scaling driver.
			  In this mode autonomous selection is disabled.
			  Driver requests a desired performance level and platform
			  tries to match the same performance level if it is
			  satisfied by guaranteed performance level.
			active
			  Use amd_pstate_epp driver instance as the scaling driver,
			  driver provides a hint to the hardware if software wants
			  to bias toward performance (0x0) or energy efficiency (0xff)
			  to the CPPC firmware. then CPPC power algorithm will
			  calculate the runtime workload and adjust the realtime cores
			  frequency.
			guided
			  Activate guided autonomous mode. Driver requests minimum and
			  maximum performance level and the platform autonomously
			  selects a performance level in this range and appropriate
			  to the current workload.

	amd_prefcore=
			[X86]
			disable
			  Disable amd-pstate preferred core.

	amijoy.map=	[HW,JOY] Amiga joystick support
			Map of devices attached to JOY0DAT and JOY1DAT
			Format: <a>,<b>
			See also Documentation/input/joydev/joystick.rst

	analog.map=	[HW,JOY] Analog joystick and gamepad support
			Specifies type or capabilities of an analog joystick
			connected to one of 16 gameports
			Format: <type1>,<type2>,..<type16>

	apc=		[HW,SPARC]
			Power management functions (SPARCstation-4/5 + deriv.)
			Format: noidle
			Disable APC CPU standby support. SPARCstation-Fox does
			not play well with APC CPU idle - disable it if you have
			APC and your system crashes randomly.

	apic		[APIC,X86-64] Use IO-APIC. Default.

	apic=		[APIC,X86,EARLY] Advanced Programmable Interrupt Controller
			Change the output verbosity while booting
			Format: { quiet (default) | verbose | debug }
			Change the amount of debugging information output
			when initialising the APIC and IO-APIC components.

	apic_extnmi=	[APIC,X86,EARLY] External NMI delivery setting
			Format: { bsp (default) | all | none }
			bsp:  External NMI is delivered only to CPU 0
			all:  External NMIs are broadcast to all CPUs as a
			      backup of CPU 0
			none: External NMI is masked for all CPUs. This is
			      useful so that a dump capture kernel won't be
			      shot down by NMI

	apicpmtimer	Do APIC timer calibration using the pmtimer. Implies
			apicmaintimer. Useful when your PIT timer is totally
			broken.

	autoconf=	[IPV6]
			See Documentation/networking/ipv6.rst.

	apm=		[APM] Advanced Power Management
			See header of arch/x86/kernel/apm_32.c.

	apparmor=	[APPARMOR] Disable or enable AppArmor at boot time
			Format: { "0" | "1" }
			See security/apparmor/Kconfig help text
			0 -- disable.
			1 -- enable.
			Default value is set via kernel config option.

	arcrimi=	[HW,NET] ARCnet - "RIM I" (entirely mem-mapped) cards
			Format: <io>,<irq>,<nodeID>

	arm64.no32bit_el0 [ARM64] Unconditionally disable the execution of
			32 bit applications.

	arm64.nobti	[ARM64] Unconditionally disable Branch Target
			Identification support

	arm64.nogcs	[ARM64] Unconditionally disable Guarded Control Stack
			support

	arm64.nomops	[ARM64] Unconditionally disable Memory Copy and Memory
			Set instructions support

	arm64.nompam	[ARM64] Unconditionally disable Memory Partitioning And
			Monitoring support

	arm64.nomte	[ARM64] Unconditionally disable Memory Tagging Extension
			support

	arm64.nopauth	[ARM64] Unconditionally disable Pointer Authentication
			support

	arm64.nosme	[ARM64] Unconditionally disable Scalable Matrix
			Extension support

	arm64.nosve	[ARM64] Unconditionally disable Scalable Vector
			Extension support

	ataflop=	[HW,M68k]

	atarimouse=	[HW,MOUSE] Atari Mouse

	atkbd.extra=	[HW] Enable extra LEDs and keys on IBM RapidAccess,
			EzKey and similar keyboards

	atkbd.reset=	[HW] Reset keyboard during initialization

	atkbd.set=	[HW] Select keyboard code set
			Format: <int> (2 = AT (default), 3 = PS/2)

	atkbd.scroll=	[HW] Enable scroll wheel on MS Office and similar
			keyboards

	atkbd.softraw=	[HW] Choose between synthetic and real raw mode
			Format: <bool> (0 = real, 1 = synthetic (default))

	atkbd.softrepeat= [HW]
			Use software keyboard repeat

	audit=		[KNL] Enable the audit sub-system
			Format: { "0" | "1" | "off" | "on" }
			0 | off - kernel audit is disabled and can not be
			    enabled until the next reboot
			unset - kernel audit is initialized but disabled and
			    will be fully enabled by the userspace auditd.
			1 | on - kernel audit is initialized and partially
			    enabled, storing at most audit_backlog_limit
			    messages in RAM until it is fully enabled by the
			    userspace auditd.
			Default: unset

	audit_backlog_limit= [KNL] Set the audit queue size limit.
			Format: <int> (must be >=0)
			Default: 64

	bau=		[X86_UV] Enable the BAU on SGI UV.  The default
			behavior is to disable the BAU (i.e. bau=0).
			Format: { "0" | "1" }
			0 - Disable the BAU.
			1 - Enable the BAU.
			unset - Disable the BAU.

	baycom_epp=	[HW,AX25]
			Format: <io>,<mode>

	baycom_par=	[HW,AX25] BayCom Parallel Port AX.25 Modem
			Format: <io>,<mode>
			See header of drivers/net/hamradio/baycom_par.c.

	baycom_ser_fdx=	[HW,AX25]
			BayCom Serial Port AX.25 Modem (Full Duplex Mode)
			Format: <io>,<irq>,<mode>[,<baud>]
			See header of drivers/net/hamradio/baycom_ser_fdx.c.

	baycom_ser_hdx=	[HW,AX25]
			BayCom Serial Port AX.25 Modem (Half Duplex Mode)
			Format: <io>,<irq>,<mode>
			See header of drivers/net/hamradio/baycom_ser_hdx.c.

	bdev_allow_write_mounted=
			Format: <bool>
			Control the ability to open a mounted block device
			for writing, i.e., allow / disallow writes that bypass
			the FS. This was implemented as a means to prevent
			fuzzers from crashing the kernel by overwriting the
			metadata underneath a mounted FS without its awareness.
			This also prevents destructive formatting of mounted
			filesystems by naive storage tooling that don't use
			O_EXCL. Default is Y and can be changed through the
			Kconfig option CONFIG_BLK_DEV_WRITE_MOUNTED.

	bert_disable	[ACPI]
			Disable BERT OS support on buggy BIOSes.

	bgrt_disable	[ACPI,X86,EARLY]
			Disable BGRT to avoid flickering OEM logo.

	blkdevparts=	Manual partition parsing of block device(s) for
			embedded devices based on command line input.
			See Documentation/block/cmdline-partition.rst

	boot_delay=	[KNL,EARLY]
			Milliseconds to delay each printk during boot.
			Only works if CONFIG_BOOT_PRINTK_DELAY is enabled,
			and you may also have to specify "lpj=".  Boot_delay
			values larger than 10 seconds (10000) are assumed
			erroneous and ignored.
			Format: integer

	bootconfig	[KNL,EARLY]
			Extended command line options can be added to an initrd
			and this will cause the kernel to look for it.

			See Documentation/admin-guide/bootconfig.rst

	bttv.card=	[HW,V4L] bttv (bt848 + bt878 based grabber cards)
	bttv.radio=	Most important insmod options are available as
			kernel args too.
	bttv.pll=	See Documentation/admin-guide/media/bttv.rst
	bttv.tuner=

	bulk_remove=off	[PPC]  This parameter disables the use of the pSeries
			firmware feature for flushing multiple hpte entries
			at a time.

	c101=		[NET] Moxa C101 synchronous serial card

	cachesize=	[BUGS=X86-32] Override level 2 CPU cache size detection.
			Sometimes CPU hardware bugs make them report the cache
			size incorrectly. The kernel will attempt work arounds
			to fix known problems, but for some CPUs it is not
			possible to determine what the correct size should be.
			This option provides an override for these situations.

	carrier_timeout=
			[NET] Specifies amount of time (in seconds) that
			the kernel should wait for a network carrier. By default
			it waits 120 seconds.

	ca_keys=	[KEYS] This parameter identifies a specific key(s) on
			the system trusted keyring to be used for certificate
			trust validation.
			format: { id:<keyid> | builtin }

	cca=		[MIPS,EARLY] Override the kernel pages' cache coherency
			algorithm.  Accepted values range from 0 to 7
			inclusive. See arch/mips/include/asm/pgtable-bits.h
			for platform specific values (SB1, Loongson3 and
			others).

	ccw_timeout_log	[S390]
			See Documentation/arch/s390/common_io.rst for details.

	cfi=		[X86-64] Set Control Flow Integrity checking features
			when CONFIG_FINEIBT is enabled.
			Format: feature[,feature...]
			Default: auto

			auto:	  Use FineIBT if IBT available, otherwise kCFI.
				  Under FineIBT, enable "paranoid" mode when
				  FRED is not available.
			off:	  Turn off CFI checking.
			kcfi:	  Use kCFI (disable FineIBT).
			fineibt:  Use FineIBT (even if IBT not available).
			norand:   Do not re-randomize CFI hashes.
			paranoid: Add caller hash checking under FineIBT.
			bhi:	  Enable register poisoning to stop speculation
				  across FineIBT. (Disabled by default.)
			warn:	  Do not enforce CFI checking: warn only.
			debug:    Report CFI initialization details.

	cgroup_disable=	[KNL] Disable a particular controller or optional feature
			Format: {name of the controller(s) or feature(s) to disable}
			The effects of cgroup_disable=foo are:
			- foo isn't auto-mounted if you mount all cgroups in
			  a single hierarchy
			- foo isn't visible as an individually mountable
			  subsystem
			- if foo is an optional feature then the feature is
			  disabled and corresponding cgroup files are not
			  created
			{Currently only "memory" controller deal with this and
			cut the overhead, others just disable the usage. So
			only cgroup_disable=memory is actually worthy}
			Specifying "pressure" disables per-cgroup pressure
			stall information accounting feature

	cgroup_no_v1=	[KNL] Disable cgroup controllers and named hierarchies in v1
			Format: { { controller | "all" | "named" }
			          [,{ controller | "all" | "named" }...] }
			Like cgroup_disable, but only applies to cgroup v1;
			the blacklisted controllers remain available in cgroup2.
			"all" blacklists all controllers and "named" disables
			named mounts. Specifying both "all" and "named" disables
			all v1 hierarchies.

	cgroup_v1_proc=	[KNL] Show also missing controllers in /proc/cgroups
			Format: { "true" | "false" }
			/proc/cgroups lists only v1 controllers by default.
			This compatibility option enables listing also v2
			controllers (whose v1 code is not compiled!), so that
			semi-legacy software can check this file to decide
			about usage of v2 (sic) controllers.

	cgroup_favordynmods= [KNL] Enable or Disable favordynmods.
			Format: { "true" | "false" }
			Defaults to the value of CONFIG_CGROUP_FAVOR_DYNMODS.

	cgroup.memory=	[KNL] Pass options to the cgroup memory controller.
			Format: <string>
			nosocket -- Disable socket memory accounting.
			nokmem -- Disable kernel memory accounting.
			nobpf -- Disable BPF memory accounting.

	checkreqprot=	[SELINUX] Set initial checkreqprot flag value.
			Format: { "0" | "1" }
			See security/selinux/Kconfig help text.
			0 -- check protection applied by kernel (includes
				any implied execute protection).
			1 -- check protection requested by application.
			Default value is set via a kernel config option.
			Value can be changed at runtime via
				/sys/fs/selinux/checkreqprot.
			Setting checkreqprot to 1 is deprecated.

	cio_ignore=	[S390]
			See Documentation/arch/s390/common_io.rst for details.

	clearcpuid=X[,X...] [X86]
			Disable CPUID feature X for the kernel. See
			arch/x86/include/asm/cpufeatures.h for the valid bit
			numbers X. Note the Linux-specific bits are not necessarily
			stable over kernel options, but the vendor-specific
			ones should be.
			X can also be a string as appearing in the flags: line
			in /proc/cpuinfo which does not have the above
			instability issue. However, not all features have names
			in /proc/cpuinfo.
			Note that using this option will taint your kernel.
			Also note that user programs calling CPUID directly
			or using the feature without checking anything
			will still see it. This just prevents it from
			being used by the kernel or shown in /proc/cpuinfo.
			Also note the kernel might malfunction if you disable
			some critical bits.

	clk_ignore_unused
			[CLK]
			Prevents the clock framework from automatically gating
			clocks that have not been explicitly enabled by a Linux
			device driver but are enabled in hardware at reset or
			by the bootloader/firmware. Note that this does not
			force such clocks to be always-on nor does it reserve
			those clocks in any way. This parameter is useful for
			debug and development, but should not be needed on a
			platform with proper driver support.  For more
			information, see Documentation/driver-api/clk.rst.

	clock=		[BUGS=X86-32, HW] gettimeofday clocksource override.
			[Deprecated]
			Forces specified clocksource (if available) to be used
			when calculating gettimeofday(). If specified
			clocksource is not available, it defaults to PIT.
			Format: { pit | tsc | cyclone | pmtmr }

	clocksource=	Override the default clocksource
			Format: <string>
			Override the default clocksource and use the clocksource
			with the name specified.
			Some clocksource names to choose from, depending on
			the platform:
			[all] jiffies (this is the base, fallback clocksource)
			[ACPI] acpi_pm
			[ARM] imx_timer1,OSTS,netx_timer,mpu_timer2,
				pxa_timer,timer3,32k_counter,timer0_1
			[X86-32] pit,hpet,tsc;
				scx200_hrt on Geode; cyclone on IBM x440
			[MIPS] MIPS
			[PARISC] cr16
			[S390] tod
			[SH] SuperH
			[SPARC64] tick
			[X86-64] hpet,tsc

	clocksource.arm_arch_timer.evtstrm=
			[ARM,ARM64,EARLY]
			Format: <bool>
			Enable/disable the eventstream feature of the ARM
			architected timer so that code using WFE-based polling
			loops can be debugged more effectively on production
			systems.

	clocksource.verify_n_cpus= [KNL]
			Limit the number of CPUs checked for clocksources
			marked with CLOCK_SOURCE_VERIFY_PERCPU that
			are marked unstable due to excessive skew.
			A negative value says to check all CPUs, while
			zero says not to check any.  Values larger than
			nr_cpu_ids are silently truncated to nr_cpu_ids.
			The actual CPUs are chosen randomly, with
			no replacement if the same CPU is chosen twice.

	clocksource-wdtest.holdoff= [KNL]
			Set the time in seconds that the clocksource
			watchdog test waits before commencing its tests.
			Defaults to zero when built as a module and to
			10 seconds when built into the kernel.

	cma=nn[MG]@[start[MG][-end[MG]]]
			[KNL,CMA,EARLY]
			Sets the size of kernel global memory area for
			contiguous memory allocations and optionally the
			placement constraint by the physical address range of
			memory allocations. A value of 0 disables CMA
			altogether. For more information, see
			kernel/dma/contiguous.c

	cma_pernuma=nn[MG]
			[KNL,CMA,EARLY]
			Sets the size of kernel per-numa memory area for
			contiguous memory allocations. A value of 0 disables
			per-numa CMA altogether. And If this option is not
			specified, the default value is 0.
			With per-numa CMA enabled, DMA users on node nid will
			first try to allocate buffer from the pernuma area
			which is located in node nid, if the allocation fails,
			they will fallback to the global default memory area.

	numa_cma=<node>:nn[MG][,<node>:nn[MG]]
			[KNL,CMA,EARLY]
			Sets the size of kernel numa memory area for
			contiguous memory allocations. It will reserve CMA
			area for the specified node.

			With numa CMA enabled, DMA users on node nid will
			first try to allocate buffer from the numa area
			which is located in node nid, if the allocation fails,
			they will fallback to the global default memory area.

	cmo_free_hint=	[PPC] Format: { yes | no }
			Specify whether pages are marked as being inactive
			when they are freed.  This is used in CMO environments
			to determine OS memory pressure for page stealing by
			a hypervisor.
			Default: yes

	coherent_pool=nn[KMG]	[ARM,KNL,EARLY]
			Sets the size of memory pool for coherent, atomic dma
			allocations, by default set to 256K.

	com20020=	[HW,NET] ARCnet - COM20020 chipset
			Format:
			<io>[,<irq>[,<nodeID>[,<backplane>[,<ckp>[,<timeout>]]]]]

	com90io=	[HW,NET] ARCnet - COM90xx chipset (IO-mapped buffers)
			Format: <io>[,<irq>]

	com90xx=	[HW,NET]
			ARCnet - COM90xx chipset (memory-mapped buffers)
			Format: <io>[,<irq>[,<memstart>]]

	condev=		[HW,S390] console device
	conmode=

	con3215_drop=	[S390,EARLY] 3215 console drop mode.
			Format: y|n|Y|N|1|0
			When set to true, drop data on the 3215 console when
			the console buffer is full. In this case the
			operator using a 3270 terminal emulator (for example
			x3270) does not have to enter the clear key for the
			console output to advance and the kernel to continue.
			This leads to a much faster boot time when a 3270
			terminal emulator is active. If no 3270 terminal
			emulator is used, this parameter has no effect.

	console=	[KNL] Output console device and options.

		tty<n>	Use the virtual console device <n>.

		ttyS<n>[,options]
		ttyUSB0[,options]
			Use the specified serial port.  The options are of
			the form "bbbbpnf", where "bbbb" is the baud rate,
			"p" is parity ("n", "o", or "e"), "n" is number of
			bits, and "f" is flow control ("r" for RTS or
			omit it).  Default is "9600n8".

			See Documentation/admin-guide/serial-console.rst for more
			information.  See
			Documentation/networking/netconsole.rst for an
			alternative.

		<DEVNAME>:<n>.<n>[,options]
			Use the specified serial port on the serial core bus.
			The addressing uses DEVNAME of the physical serial port
			device, followed by the serial core controller instance,
			and the serial port instance. The options are the same
			as documented for the ttyS addressing above.

			The mapping of the serial ports to the tty instances
			can be viewed with:

			$ ls -d /sys/bus/serial-base/devices/*:*.*/tty/*
			/sys/bus/serial-base/devices/00:04:0.0/tty/ttyS0

			In the above example, the console can be addressed with
			console=00:04:0.0. Note that a console addressed this
			way will only get added when the related device driver
			is ready. The use of an earlycon parameter in addition to
			the console may be desired for console output early on.

		uart[8250],io,<addr>[,options]
		uart[8250],mmio,<addr>[,options]
		uart[8250],mmio16,<addr>[,options]
		uart[8250],mmio32,<addr>[,options]
		uart[8250],0x<addr>[,options]
			Start an early, polled-mode console on the 8250/16550
			UART at the specified I/O port or MMIO address,
			switching to the matching ttyS device later.
			MMIO inter-register address stride is either 8-bit
			(mmio), 16-bit (mmio16), or 32-bit (mmio32).
			If none of [io|mmio|mmio16|mmio32], <addr> is assumed
			to be equivalent to 'mmio'. 'options' are specified in
			the same format described for ttyS above; if unspecified,
			the h/w is not re-initialized.

		hvc<n>	Use the hypervisor console device <n>. This is for
			both Xen and PowerPC hypervisors.

		{ null | "" }
			Use to disable console output, i.e., to have kernel
			console messages discarded.
			This must be the only console= parameter used on the
			kernel command line.

		If the device connected to the port is not a TTY but a braille
		device, prepend "brl," before the device type, for instance
			console=brl,ttyS0
		For now, only VisioBraille is supported.

	console_msg_format=
			[KNL] Change console messages format
		default
			By default we print messages on consoles in
			"[time stamp] text\n" format (time stamp may not be
			printed, depending on CONFIG_PRINTK_TIME or
			`printk_time' param).
		syslog
			Switch to syslog format: "<%u>[time stamp] text\n"
			IOW, each message will have a facility and loglevel
			prefix. The format is similar to one used by syslog()
			syscall, or to executing "dmesg -S --raw" or to reading
			from /proc/kmsg.

	consoleblank=	[KNL] The console blank (screen saver) timeout in
			seconds. A value of 0 disables the blank timer.
			Defaults to 0.

	coredump_filter=
			[KNL] Change the default value for
			/proc/<pid>/coredump_filter.
			See also Documentation/filesystems/proc.rst.

	coresight_cpu_debug.enable
			[ARM,ARM64]
			Format: <bool>
			Enable/disable the CPU sampling based debugging.
			0: default value, disable debugging
			1: enable debugging at boot time

	cpcihp_generic=	[HW,PCI] Generic port I/O CompactPCI driver
			Format:
			<first_slot>,<last_slot>,<port>,<enum_bit>[,<debug>]

	cpuidle.off=1	[CPU_IDLE]
			disable the cpuidle sub-system

	cpuidle.governor=
			[CPU_IDLE] Name of the cpuidle governor to use.

	cpufreq.off=1	[CPU_FREQ]
			disable the cpufreq sub-system

	cpufreq.default_governor=
			[CPU_FREQ] Name of the default cpufreq governor or
			policy to use. This governor must be registered in the
			kernel before the cpufreq driver probes.

	cpu_init_udelay=N
			[X86,EARLY] Delay for N microsec between assert and de-assert
			of APIC INIT to start processors.  This delay occurs
			on every CPU online, such as boot, and resume from suspend.
			Default: 10000

	cpuhp.parallel=
			[SMP] Enable/disable parallel bringup of secondary CPUs
			Format: <bool>
			Default is enabled if CONFIG_HOTPLUG_PARALLEL=y. Otherwise
			the parameter has no effect.

	crash_kexec_post_notifiers
			Only jump to kdump kernel after running the panic
			notifiers and dumping kmsg. This option increases
			the risks of a kdump failure, since some panic
			notifiers can make the crashed kernel more unstable.
			In configurations where kdump may not be reliable,
			running the panic notifiers could allow collecting
			more data on dmesg, like stack traces from other CPUS
			or extra data dumped by panic_print. Note that some
			configurations enable this option unconditionally,
			like Hyper-V, PowerPC (fadump) and AMD SEV-SNP.

	crashkernel=size[KMG][@offset[KMG]]
			[KNL,EARLY] Using kexec, Linux can switch to a 'crash kernel'
			upon panic. This parameter reserves the physical
			memory region [offset, offset + size] for that kernel
			image. If '@offset' is omitted, then a suitable offset
			is selected automatically.
			[KNL, X86-64, ARM64, RISCV, LoongArch] Select a region
			under 4G first, and fall back to reserve region above
			4G when '@offset' hasn't been specified.
			See Documentation/admin-guide/kdump/kdump.rst for further details.

	crashkernel=range1:size1[,range2:size2,...][@offset]
			[KNL] Same as above, but depends on the memory
			in the running system. The syntax of range is
			start-[end] where start and end are both
			a memory unit (amount[KMG]). See also
			Documentation/admin-guide/kdump/kdump.rst for an example.

	crashkernel=size[KMG],high
			[KNL, X86-64, ARM64, RISCV, LoongArch] range could be
			above 4G.
			Allow kernel to allocate physical memory region from top,
			so could be above 4G if system have more than 4G ram
			installed. Otherwise memory region will be allocated
			below 4G, if available.
			It will be ignored if crashkernel=X is specified.
	crashkernel=size[KMG],low
			[KNL, X86-64, ARM64, RISCV, LoongArch] range under 4G.
			When crashkernel=X,high is passed, kernel could allocate
			physical memory region above 4G, that cause second kernel
			crash on system that require some amount of low memory,
			e.g. swiotlb requires at least 64M+32K low memory, also
			enough extra low memory is needed to make sure DMA buffers
			for 32-bit devices won't run out. Kernel would try to allocate
			default	size of memory below 4G automatically. The default
			size is	platform dependent.
			  --> x86: max(swiotlb_size_or_default() + 8MiB, 256MiB)
			  --> arm64: 128MiB
			  --> riscv: 128MiB
			  --> loongarch: 128MiB
			This one lets the user specify own low range under 4G
			for second kernel instead.
			0: to disable low allocation.
			It will be ignored when crashkernel=X,high is not used
			or memory reserved is below 4G.
	crashkernel=size[KMG],cma
			[KNL, X86] Reserve additional crash kernel memory from
			CMA. This reservation is usable by the first system's
			userspace memory and kernel movable allocations (memory
			balloon, zswap). Pages allocated from this memory range
			will not be included in the vmcore so this should not
			be used if dumping of userspace memory is intended and
			it has to be expected that some movable kernel pages
			may be missing from the dump.

			A standard crashkernel reservation, as described above,
			is still needed to hold the crash kernel and initrd.

			This option increases the risk of a kdump failure: DMA
			transfers configured by the first kernel may end up
			corrupting the second kernel's memory.

			This reservation method is intended for systems that
			can't afford to sacrifice enough memory for standard
			crashkernel reservation and where less reliable and
			possibly incomplete kdump is preferable to no kdump at
			all.

	cryptomgr.notests
			[KNL] Disable crypto self-tests

	cs89x0_dma=	[HW,NET]
			Format: <dma>

	cs89x0_media=	[HW,NET]
			Format: { rj45 | aui | bnc }

	csdlock_debug=	[KNL] Enable or disable debug add-ons of cross-CPU
			function call handling. When switched on,
			additional debug data is printed to the console
			in case a hanging CPU is detected, and that
			CPU is pinged again in order to try to resolve
			the hang situation.  The default value of this
			option depends on the CSD_LOCK_WAIT_DEBUG_DEFAULT
			Kconfig option.

	dasd=		[HW,NET]
			See header of drivers/s390/block/dasd_devmap.c.

	db9.dev[2|3]=	[HW,JOY] Multisystem joystick support via parallel port
			(one device per port)
			Format: <port#>,<type>
			See also Documentation/input/devices/joystick-parport.rst

	debug		[KNL,EARLY] Enable kernel debugging (events log level).

	debug_boot_weak_hash
			[KNL,EARLY] Enable printing [hashed] pointers early in the
			boot sequence.  If enabled, we use a weak hash instead
			of siphash to hash pointers.  Use this option if you are
			seeing instances of '(___ptrval___)') and need to see a
			value (hashed pointer) instead. Cryptographically
			insecure, please do not use on production kernels.

	debug_locks_verbose=
			[KNL] verbose locking self-tests
			Format: <int>
			Print debugging info while doing the locking API
			self-tests.
			Bitmask for the various LOCKTYPE_ tests. Defaults to 0
			(no extra messages), setting it to -1 (all bits set)
			will print _a_lot_ more information - normally only
			useful to lockdep developers.

	debug_objects	[KNL,EARLY] Enable object debugging

	debug_guardpage_minorder=
			[KNL,EARLY] When CONFIG_DEBUG_PAGEALLOC is set, this
			parameter allows control of the order of pages that will
			be intentionally kept free (and hence protected) by the
			buddy allocator. Bigger value increase the probability
			of catching random memory corruption, but reduce the
			amount of memory for normal system use. The maximum
			possible value is MAX_PAGE_ORDER/2.  Setting this
			parameter to 1 or 2 should be enough to identify most
			random memory corruption problems caused by bugs in
			kernel or driver code when a CPU writes to (or reads
			from) a random memory location. Note that there exists
			a class of memory corruptions problems caused by buggy
			H/W or F/W or by drivers badly programming DMA
			(basically when memory is written at bus level and the
			CPU MMU is bypassed) which are not detectable by
			CONFIG_DEBUG_PAGEALLOC, hence this option will not
			help tracking down these problems.

	debug_pagealloc=
			[KNL,EARLY] When CONFIG_DEBUG_PAGEALLOC is set, this parameter
			enables the feature at boot time. By default, it is
			disabled and the system will work mostly the same as a
			kernel built without CONFIG_DEBUG_PAGEALLOC.
			Note: to get most of debug_pagealloc error reports, it's
			useful to also enable the page_owner functionality.
			on: enable the feature

	debugfs=    	[KNL,EARLY] This parameter enables what is exposed to
			userspace and debugfs internal clients.
			Format: { on, no-mount, off }
			on: 	All functions are enabled.
			no-mount:
				Filesystem is not registered but kernel clients can
			        access APIs and a crashkernel can be used to read
				its content. There is nothing to mount.
			off: 	Filesystem is not registered and clients
			        get a -EPERM as result when trying to register files
				or directories within debugfs.
				This is equivalent of the runtime functionality if
				debugfs was not enabled in the kernel at all.
			Default value is set in build-time with a kernel configuration.

	debugpat	[X86] Enable PAT debugging

	default_hugepagesz=
			[HW] The size of the default HugeTLB page. This is
			the size represented by the legacy /proc/ hugepages
			APIs.  In addition, this is the default hugetlb size
			used for shmget(), mmap() and mounting hugetlbfs
			filesystems.  If not specified, defaults to the
			architecture's default huge page size.  Huge page
			sizes are architecture dependent.  See also
			Documentation/admin-guide/mm/hugetlbpage.rst.
			Format: size[KMG]

	deferred_probe_timeout=
			[KNL] Debugging option to set a timeout in seconds for
			deferred probe to give up waiting on dependencies to
			probe. Only specific dependencies (subsystems or
			drivers) that have opted in will be ignored. A timeout
			of 0 will timeout at the end of initcalls. If the time
			out hasn't expired, it'll be restarted by each
			successful driver registration. This option will also
			dump out devices still on the deferred probe list after
			retrying.

	delayacct	[KNL] Enable per-task delay accounting

	dell_smm_hwmon.ignore_dmi=
			[HW] Continue probing hardware even if DMI data
			indicates that the driver is running on unsupported
			hardware.

	dell_smm_hwmon.force=
			[HW] Activate driver even if SMM BIOS signature does
			not match list of supported models and enable otherwise
			blacklisted features.

	dell_smm_hwmon.power_status=
			[HW] Report power status in /proc/i8k
			(disabled by default).

	dell_smm_hwmon.restricted=
			[HW] Allow controlling fans only if SYS_ADMIN
			capability is set.

	dell_smm_hwmon.fan_mult=
			[HW] Factor to multiply fan speed with.

	dell_smm_hwmon.fan_max=
			[HW] Maximum configurable fan speed.

	dfltcc=		[HW,S390]
			Format: { on | off | def_only | inf_only | always }
			on:       s390 zlib hardware support for compression on
			          level 1 and decompression (default)
			off:      No s390 zlib hardware support
			def_only: s390 zlib hardware support for deflate
			          only (compression on level 1)
			inf_only: s390 zlib hardware support for inflate
			          only (decompression)
			always:   Same as 'on' but ignores the selected compression
			          level always using hardware support (used for debugging)

	dhash_entries=	[KNL]
			Set number of hash buckets for dentry cache.

	disable_1tb_segments [PPC,EARLY]
			Disables the use of 1TB hash page table segments. This
			causes the kernel to fall back to 256MB segments which
			can be useful when debugging issues that require an SLB
			miss to occur.

	disable=	[IPV6]
			See Documentation/networking/ipv6.rst.

	disable_radix	[PPC,EARLY]
			Disable RADIX MMU mode on POWER9

	disable_tlbie	[PPC]
			Disable TLBIE instruction. Currently does not work
			with KVM, with HASH MMU, or with coherent accelerators.

	disable_ddw	[PPC/PSERIES,EARLY]
			Disable Dynamic DMA Window support. Use this
			to workaround buggy firmware.

	disable_ipv6=	[IPV6]
			See Documentation/networking/ipv6.rst.

	disable_mtrr_cleanup [X86,EARLY]
			The kernel tries to adjust MTRR layout from continuous
			to discrete, to make X server driver able to add WB
			entry later. This parameter disables that.

	disable_mtrr_trim [X86, Intel and AMD only,EARLY]
			By default the kernel will trim any uncacheable
			memory out of your available memory pool based on
			MTRR settings.  This parameter disables that behavior,
			possibly causing your machine to run very slowly.

	disable_timer_pin_1 [X86,EARLY]
			Disable PIN 1 of APIC timer
			Can be useful to work around chipset bugs.

	dis_ucode_ldr	[X86] Disable the microcode loader.

	dma_debug=off	If the kernel is compiled with DMA_API_DEBUG support,
			this option disables the debugging code at boot.

	dma_debug_entries=<number>
			This option allows to tune the number of preallocated
			entries for DMA-API debugging code. One entry is
			required per DMA-API allocation. Use this if the
			DMA-API debugging code disables itself because the
			architectural default is too low.

	dma_debug_driver=<driver_name>
			With this option the DMA-API debugging driver
			filter feature can be enabled at boot time. Just
			pass the driver to filter for as the parameter.
			The filter can be disabled or changed to another
			driver later using sysfs.

	reg_file_data_sampling=
			[X86] Controls mitigation for Register File Data
			Sampling (RFDS) vulnerability. RFDS is a CPU
			vulnerability which may allow userspace to infer
			kernel data values previously stored in floating point
			registers, vector registers, or integer registers.
			RFDS only affects Intel Atom processors.

			on:	Turns ON the mitigation.
			off:	Turns OFF the mitigation.

			This parameter overrides the compile time default set
			by CONFIG_MITIGATION_RFDS. Mitigation cannot be
			disabled when other VERW based mitigations (like MDS)
			are enabled. In order to disable RFDS mitigation all
			VERW based mitigations need to be disabled.

			For details see:
			Documentation/admin-guide/hw-vuln/reg-file-data-sampling.rst

	driver_async_probe=  [KNL]
			List of driver names to be probed asynchronously. *
			matches with all driver names. If * is specified, the
			rest of the listed driver names are those that will NOT
			match the *.
			Format: <driver_name1>,<driver_name2>...

	drm.edid_firmware=[<connector>:]<file>[,[<connector>:]<file>]
			Broken monitors, graphic adapters, KVMs and EDIDless
			panels may send no or incorrect EDID data sets.
			This parameter allows to specify an EDID data sets
			in the /lib/firmware directory that are used instead.
			An EDID data set will only be used for a particular
			connector, if its name and a colon are prepended to
			the EDID name. Each connector may use a unique EDID
			data set by separating the files with a comma. An EDID
			data set with no connector name will be used for
			any connectors not explicitly specified.

	dscc4.setup=	[NET]

	dt_cpu_ftrs=	[PPC,EARLY]
			Format: {"off" | "known"}
			Control how the dt_cpu_ftrs device-tree binding is
			used for CPU feature discovery and setup (if it
			exists).
			off: Do not use it, fall back to legacy cpu table.
			known: Do not pass through unknown features to guests
			or userspace, only those that the kernel is aware of.

	dump_apple_properties	[X86]
			Dump name and content of EFI device properties on
			x86 Macs.  Useful for driver authors to determine
			what data is available or for reverse-engineering.

	dyndbg[="val"]		[KNL,DYNAMIC_DEBUG]
	<module>.dyndbg[="val"]
			Enable debug messages at boot time.  See
			Documentation/admin-guide/dynamic-debug-howto.rst
			for details.

	early_ioremap_debug [KNL,EARLY]
			Enable debug messages in early_ioremap support. This
			is useful for tracking down temporary early mappings
			which are not unmapped.

	earlycon=	[KNL,EARLY] Output early console device and options.

			When used with no options, the early console is
			determined by stdout-path property in device tree's
			chosen node or the ACPI SPCR table if supported by
			the platform.

		cdns,<addr>[,options]
			Start an early, polled-mode console on a Cadence
			(xuartps) serial port at the specified address. Only
			supported option is baud rate. If baud rate is not
			specified, the serial port must already be setup and
			configured.

		uart[8250],io,<addr>[,options[,uartclk]]
		uart[8250],mmio,<addr>[,options[,uartclk]]
		uart[8250],mmio32,<addr>[,options[,uartclk]]
		uart[8250],mmio32be,<addr>[,options[,uartclk]]
		uart[8250],0x<addr>[,options]
			Start an early, polled-mode console on the 8250/16550
			UART at the specified I/O port or MMIO address.
			MMIO inter-register address stride is either 8-bit
			(mmio) or 32-bit (mmio32 or mmio32be).
			If none of [io|mmio|mmio32|mmio32be], <addr> is assumed
			to be equivalent to 'mmio'. 'options' are specified
			in the same format described for "console=ttyS<n>"; if
			unspecified, the h/w is not initialized. 'uartclk' is
			the uart clock frequency; if unspecified, it is set
			to 'BASE_BAUD' * 16.

		pl011,<addr>
		pl011,mmio32,<addr>
			Start an early, polled-mode console on a pl011 serial
			port at the specified address. The pl011 serial port
			must already be setup and configured. Options are not
			yet supported.  If 'mmio32' is specified, then only
			the driver will use only 32-bit accessors to read/write
			the device registers.

		liteuart,<addr>
			Start an early console on a litex serial port at the
			specified address. The serial port must already be
			setup and configured. Options are not yet supported.

		meson,<addr>
			Start an early, polled-mode console on a meson serial
			port at the specified address. The serial port must
			already be setup and configured. Options are not yet
			supported.

		msm_serial,<addr>
			Start an early, polled-mode console on an msm serial
			port at the specified address. The serial port
			must already be setup and configured. Options are not
			yet supported.

		msm_serial_dm,<addr>
			Start an early, polled-mode console on an msm serial
			dm port at the specified address. The serial port
			must already be setup and configured. Options are not
			yet supported.

		owl,<addr>
			Start an early, polled-mode console on a serial port
			of an Actions Semi SoC, such as S500 or S900, at the
			specified address. The serial port must already be
			setup and configured. Options are not yet supported.

		rda,<addr>
			Start an early, polled-mode console on a serial port
			of an RDA Micro SoC, such as RDA8810PL, at the
			specified address. The serial port must already be
			setup and configured. Options are not yet supported.

		sbi
			Use RISC-V SBI (Supervisor Binary Interface) for early
			console.

		smh	Use ARM semihosting calls for early console.

		s3c2410,<addr>
		s3c2412,<addr>
		s3c2440,<addr>
		s3c6400,<addr>
		s5pv210,<addr>
		exynos4210,<addr>
			Use early console provided by serial driver available
			on Samsung SoCs, requires selecting proper type and
			a correct base address of the selected UART port. The
			serial port must already be setup and configured.
			Options are not yet supported.

		lantiq,<addr>
			Start an early, polled-mode console on a lantiq serial
			(lqasc) port at the specified address. The serial port
			must already be setup and configured. Options are not
			yet supported.

		lpuart,<addr>
		lpuart32,<addr>
			Use early console provided by Freescale LP UART driver
			found on Freescale Vybrid and QorIQ LS1021A processors.
			A valid base address must be provided, and the serial
			port must already be setup and configured.

		ec_imx21,<addr>
		ec_imx6q,<addr>
			Start an early, polled-mode, output-only console on the
			Freescale i.MX UART at the specified address. The UART
			must already be setup and configured.

		ar3700_uart,<addr>
			Start an early, polled-mode console on the
			Armada 3700 serial port at the specified
			address. The serial port must already be setup
			and configured. Options are not yet supported.

		qcom_geni,<addr>
			Start an early, polled-mode console on a Qualcomm
			Generic Interface (GENI) based serial port at the
			specified address. The serial port must already be
			setup and configured. Options are not yet supported.

		efifb,[options]
			Start an early, unaccelerated console on the EFI
			memory mapped framebuffer (if available). On cache
			coherent non-x86 systems that use system memory for
			the framebuffer, pass the 'ram' option so that it is
			mapped with the correct attributes.

		linflex,<addr>
			Use early console provided by Freescale LINFlexD UART
			serial driver for NXP S32V234 SoCs. A valid base
			address must be provided, and the serial port must
			already be setup and configured.

	earlyprintk=	[X86,SH,ARM,M68k,S390,UM,EARLY]
			earlyprintk=vga
			earlyprintk=sclp
			earlyprintk=xen
			earlyprintk=serial[,ttySn[,baudrate]]
			earlyprintk=serial[,0x...[,baudrate]]
			earlyprintk=ttySn[,baudrate]
			earlyprintk=dbgp[debugController#]
			earlyprintk=mmio32,membase[,{nocfg|baudrate}]
			earlyprintk=pciserial[,force],bus:device.function[,{nocfg|baudrate}]
			earlyprintk=xdbc[xhciController#]
			earlyprintk=bios

			earlyprintk is useful when the kernel crashes before
			the normal console is initialized. It is not enabled by
			default because it has some cosmetic problems.

			Use "nocfg" to skip UART configuration, assume
			BIOS/firmware has configured UART correctly.

			Append ",keep" to not disable it when the real console
			takes over.

			Only one of vga, serial, or usb debug port can
			be used at a time.

			Currently only ttyS0 and ttyS1 may be specified by
			name.  Other I/O ports may be explicitly specified
			on some architectures (x86 and arm at least) by
			replacing ttySn with an I/O port address, like this:
				earlyprintk=serial,0x1008,115200
			You can find the port for a given device in
			/proc/tty/driver/serial:
				2: uart:ST16650V2 port:00001008 irq:18 ...

			Interaction with the standard serial driver is not
			very good.

			The VGA output is eventually overwritten by
			the real console.

			The xen option can only be used in Xen domains.

			The sclp output can only be used on s390.

			The bios output can only be used on SuperH.

			The optional "force" to "pciserial" enables use of a
			PCI device even when its classcode is not of the
			UART class.

	edac_report=	[HW,EDAC] Control how to report EDAC event
			Format: {"on" | "off" | "force"}
			on: enable EDAC to report H/W event. May be overridden
			by other higher priority error reporting module.
			off: disable H/W event reporting through EDAC.
			force: enforce the use of EDAC to report H/W event.
			default: on.

	edd=		[EDD]
			Format: {"off" | "on" | "skip[mbr]"}

	efi=		[EFI,EARLY]
			Format: { "debug", "disable_early_pci_dma",
				  "nochunk", "noruntime", "nosoftreserve",
				  "novamap", "no_disable_early_pci_dma" }
			debug: enable misc debug output.
			disable_early_pci_dma: disable the busmaster bit on all
			PCI bridges while in the EFI boot stub.
			nochunk: disable reading files in "chunks" in the EFI
			boot stub, as chunking can cause problems with some
			firmware implementations.
			noruntime : disable EFI runtime services support
			nosoftreserve: The EFI_MEMORY_SP (Specific Purpose)
			attribute may cause the kernel to reserve the
			memory range for a memory mapping driver to
			claim. Specify efi=nosoftreserve to disable this
			reservation and treat the memory by its base type
			(i.e. EFI_CONVENTIONAL_MEMORY / "System RAM").
			novamap: do not call SetVirtualAddressMap().
			no_disable_early_pci_dma: Leave the busmaster bit set
			on all PCI bridges while in the EFI boot stub

	efi_no_storage_paranoia [EFI,X86,EARLY]
			Using this parameter you can use more than 50% of
			your efi variable storage. Use this parameter only if
			you are really sure that your UEFI does sane gc and
			fulfills the spec otherwise your board may brick.

	efivar_ssdt=	[EFI; X86] Name of an EFI variable that contains an SSDT
			that is to be dynamically loaded by Linux. If there are
			multiple variables with the same name but with different
			vendor GUIDs, all of them will be loaded. See
			Documentation/admin-guide/acpi/ssdt-overlays.rst for details.


	eisa_irq_edge=	[PARISC,HW]
			See header of drivers/parisc/eisa.c.

	ekgdboc=	[X86,KGDB,EARLY] Allow early kernel console debugging
			Format: ekgdboc=kbd

			This is designed to be used in conjunction with
			the boot argument: earlyprintk=vga

			This parameter works in place of the kgdboc parameter
			but can only be used if the backing tty is available
			very early in the boot process. For early debugging
			via a serial port see kgdboc_earlycon instead.

	elanfreq=	[X86-32]
			See comment before function elanfreq_setup() in
			arch/x86/kernel/cpu/cpufreq/elanfreq.c.

	elfcorehdr=[size[KMG]@]offset[KMG] [PPC,SH,X86,S390,EARLY]
			Specifies physical address of start of kernel core
			image elf header and optionally the size. Generally
			kexec loader will pass this option to capture kernel.
			See Documentation/admin-guide/kdump/kdump.rst for details.

	enable_mtrr_cleanup [X86,EARLY]
			The kernel tries to adjust MTRR layout from continuous
			to discrete, to make X server driver able to add WB
			entry later. This parameter enables that.

	enable_timer_pin_1 [X86]
			Enable PIN 1 of APIC timer
			Can be useful to work around chipset bugs
			(in particular on some ATI chipsets).
			The kernel tries to set a reasonable default.

	enforcing=	[SELINUX] Set initial enforcing status.
			Format: {"0" | "1"}
			See security/selinux/Kconfig help text.
			0 -- permissive (log only, no denials).
			1 -- enforcing (deny and log).
			Default value is 0.
			Value can be changed at runtime via
			/sys/fs/selinux/enforce.

	erst_disable	[ACPI]
			Disable Error Record Serialization Table (ERST)
			support.

	ether=		[HW,NET] Ethernet cards parameters
			This option is obsoleted by the "netdev=" option, which
			has equivalent usage. See its documentation for details.

	evm=		[EVM]
			Format: { "fix" }
			Permit 'security.evm' to be updated regardless of
			current integrity status.

	early_page_ext [KNL,EARLY] Enforces page_ext initialization to earlier
			stages so cover more early boot allocations.
			Please note that as side effect some optimizations
			might be disabled to achieve that (e.g. parallelized
			memory initialization is disabled) so the boot process
			might take longer, especially on systems with a lot of
			memory. Available with CONFIG_PAGE_EXTENSION=y.

	failslab=
	fail_usercopy=
	fail_page_alloc=
	fail_skb_realloc=
	fail_make_request=[KNL]
			General fault injection mechanism.
			Format: <interval>,<probability>,<space>,<times>
			See also Documentation/fault-injection/.

	fb_tunnels=	[NET]
			Format: { initns | none }
			See Documentation/admin-guide/sysctl/net.rst for
			fb_tunnels_only_for_init_ns

	floppy=		[HW]
			See Documentation/admin-guide/blockdev/floppy.rst.

	forcepae	[X86-32]
			Forcefully enable Physical Address Extension (PAE).
			Many Pentium M systems disable PAE but may have a
			functionally usable PAE implementation.
			Warning: use of this parameter will taint the kernel
			and may cause unknown problems.

	fred=		[X86-64]
			Enable/disable Flexible Return and Event Delivery.
			Format: { on | off }
			on: enable FRED when it's present.
			off: disable FRED, the default setting.

	ftrace=[tracer]
			[FTRACE] will set and start the specified tracer
			as early as possible in order to facilitate early
			boot debugging.

	ftrace_boot_snapshot
			[FTRACE] On boot up, a snapshot will be taken of the
			ftrace ring buffer that can be read at:
			/sys/kernel/tracing/snapshot.
			This is useful if you need tracing information from kernel
			boot up that is likely to be overridden by user space
			start up functionality.

			Optionally, the snapshot can also be defined for a tracing
			instance that was created by the trace_instance= command
			line parameter.

			trace_instance=foo,sched_switch ftrace_boot_snapshot=foo

			The above will cause the "foo" tracing instance to trigger
			a snapshot at the end of boot up.

	ftrace_dump_on_oops[=2(orig_cpu) | =<instance>][,<instance> |
			  ,<instance>=2(orig_cpu)]
			[FTRACE] will dump the trace buffers on oops.
			If no parameter is passed, ftrace will dump global
			buffers of all CPUs, if you pass 2 or orig_cpu, it
			will dump only the buffer of the CPU that triggered
			the oops, or the specific instance will be dumped if
			its name is passed. Multiple instance dump is also
			supported, and instances are separated by commas. Each
			instance supports only dump on CPU that triggered the
			oops by passing 2 or orig_cpu to it.

			ftrace_dump_on_oops=foo=orig_cpu

			The above will dump only the buffer of "foo" instance
			on CPU that triggered the oops.

			ftrace_dump_on_oops,foo,bar=orig_cpu

			The above will dump global buffer on all CPUs, the
			buffer of "foo" instance on all CPUs and the buffer
			of "bar" instance on CPU that triggered the oops.

	ftrace_filter=[function-list]
			[FTRACE] Limit the functions traced by the function
			tracer at boot up. function-list is a comma-separated
			list of functions. This list can be changed at run
			time by the set_ftrace_filter file in the debugfs
			tracing directory.

	ftrace_notrace=[function-list]
			[FTRACE] Do not trace the functions specified in
			function-list. This list can be changed at run time
			by the set_ftrace_notrace file in the debugfs
			tracing directory.

	ftrace_graph_filter=[function-list]
			[FTRACE] Limit the top level callers functions traced
			by the function graph tracer at boot up.
			function-list is a comma-separated list of functions
			that can be changed at run time by the
			set_graph_function file in the debugfs tracing directory.

	ftrace_graph_notrace=[function-list]
			[FTRACE] Do not trace from the functions specified in
			function-list.  This list is a comma-separated list of
			functions that can be changed at run time by the
			set_graph_notrace file in the debugfs tracing directory.

	ftrace_graph_max_depth=<uint>
			[FTRACE] Used with the function graph tracer. This is
			the max depth it will trace into a function. This value
			can be changed at run time by the max_graph_depth file
			in the tracefs tracing directory. default: 0 (no limit)

	fw_devlink=	[KNL,EARLY] Create device links between consumer and supplier
			devices by scanning the firmware to infer the
			consumer/supplier relationships. This feature is
			especially useful when drivers are loaded as modules as
			it ensures proper ordering of tasks like device probing
			(suppliers first, then consumers), supplier boot state
			clean up (only after all consumers have probed),
			suspend/resume & runtime PM (consumers first, then
			suppliers).
			Format: { off | permissive | on | rpm }
			off --	Don't create device links from firmware info.
			permissive -- Create device links from firmware info
				but use it only for ordering boot state clean
				up (sync_state() calls).
			on -- 	Create device links from firmware info and use it
				to enforce probe and suspend/resume ordering.
			rpm --	Like "on", but also use to order runtime PM.

	fw_devlink.strict=<bool>
			[KNL,EARLY] Treat all inferred dependencies as mandatory
			dependencies. This only applies for fw_devlink=on|rpm.
			Format: <bool>

	fw_devlink.sync_state =
			[KNL,EARLY] When all devices that could probe have finished
			probing, this parameter controls what to do with
			devices that haven't yet received their sync_state()
			calls.
			Format: { strict | timeout }
			strict -- Default. Continue waiting on consumers to
				probe successfully.
			timeout -- Give up waiting on consumers and call
				sync_state() on any devices that haven't yet
				received their sync_state() calls after
				deferred_probe_timeout has expired or by
				late_initcall() if !CONFIG_MODULES.

	gamecon.map[2|3]=
			[HW,JOY] Multisystem joystick and NES/SNES/PSX pad
			support via parallel port (up to 5 devices per port)
			Format: <port#>,<pad1>,<pad2>,<pad3>,<pad4>,<pad5>
			See also Documentation/input/devices/joystick-parport.rst

	gamma=		[HW,DRM]

	gart_fix_e820=	[X86-64,EARLY] disable the fix e820 for K8 GART
			Format: off | on
			default: on

	gather_data_sampling=
			[X86,INTEL,EARLY] Control the Gather Data Sampling (GDS)
			mitigation.

			Gather Data Sampling is a hardware vulnerability which
			allows unprivileged speculative access to data which was
			previously stored in vector registers.

			This issue is mitigated by default in updated microcode.
			The mitigation may have a performance impact but can be
			disabled. On systems without the microcode mitigation
			disabling AVX serves as a mitigation.

			force:	Disable AVX to mitigate systems without
				microcode mitigation. No effect if the microcode
				mitigation is present. Known to cause crashes in
				userspace with buggy AVX enumeration.

			off:	Disable GDS mitigation.

	gbpages		[X86] Use GB pages for kernel direct mappings.

	gcov_persist=	[GCOV] When non-zero (default), profiling data for
			kernel modules is saved and remains accessible via
			debugfs, even when the module is unloaded/reloaded.
			When zero, profiling data is discarded and associated
			debugfs files are removed at module unload time.

	goldfish	[X86] Enable the goldfish android emulator platform.
			Don't use this when you are not running on the
			android emulator

	gpio-mockup.gpio_mockup_ranges
			[HW] Sets the ranges of gpiochip of for this device.
			Format: <start1>,<end1>,<start2>,<end2>...
	gpio-mockup.gpio_mockup_named_lines
			[HW] Let the driver know GPIO lines should be named.

	gpt		[EFI] Forces disk with valid GPT signature but
			invalid Protective MBR to be treated as GPT. If the
			primary GPT is corrupted, it enables the backup/alternate
			GPT to be used instead.

	grcan.enable0=	[HW] Configuration of physical interface 0. Determines
			the "Enable 0" bit of the configuration register.
			Format: 0 | 1
			Default: 0
	grcan.enable1=	[HW] Configuration of physical interface 1. Determines
			the "Enable 0" bit of the configuration register.
			Format: 0 | 1
			Default: 0
	grcan.select=	[HW] Select which physical interface to use.
			Format: 0 | 1
			Default: 0
	grcan.txsize=	[HW] Sets the size of the tx buffer.
			Format: <unsigned int> such that (txsize & ~0x1fffc0) == 0.
			Default: 1024
	grcan.rxsize=	[HW] Sets the size of the rx buffer.
			Format: <unsigned int> such that (rxsize & ~0x1fffc0) == 0.
			Default: 1024

	hardened_usercopy=
			[KNL] Under CONFIG_HARDENED_USERCOPY, whether
			hardening is enabled for this boot. Hardened
			usercopy checking is used to protect the kernel
			from reading or writing beyond known memory
			allocation boundaries as a proactive defense
			against bounds-checking flaws in the kernel's
			copy_to_user()/copy_from_user() interface.
			The default is determined by
			CONFIG_HARDENED_USERCOPY_DEFAULT_ON.
		on	Perform hardened usercopy checks.
		off	Disable hardened usercopy checks.

	hardlockup_all_cpu_backtrace=
			[KNL] Should the hard-lockup detector generate
			backtraces on all cpus.
			Format: 0 | 1

	hash_pointers=
			[KNL,EARLY]
			By default, when pointers are printed to the console
			or buffers via the %p format string, that pointer is
			"hashed", i.e. obscured by hashing the pointer value.
			This is a security feature that hides actual kernel
			addresses from unprivileged users, but it also makes
			debugging the kernel more difficult since unequal
			pointers can no longer be compared. The choices are:
			Format: { auto | always | never }
			Default: auto

			auto   - Hash pointers unless slab_debug is enabled.
			always - Always hash pointers (even if slab_debug is
				 enabled).
			never  - Never hash pointers. This option should only
				 be specified when debugging the kernel. Do
				 not use on production kernels. The boot
				 param "no_hash_pointers" is an alias for
				 this mode.

	hashdist=	[KNL,NUMA] Large hashes allocated during boot
			are distributed across NUMA nodes.  Defaults on
			for 64-bit NUMA, off otherwise.
			Format: 0 | 1 (for off | on)

	hd=		[EIDE] (E)IDE hard drive subsystem geometry
			Format: <cyl>,<head>,<sect>

	hest_disable	[ACPI]
			Disable Hardware Error Source Table (HEST) support;
			corresponding firmware-first mode error processing
			logic will be disabled.

	hibernate=	[HIBERNATION]
		noresume	Don't check if there's a hibernation image
				present during boot.
		nocompress	Don't compress/decompress hibernation images.
		no		Disable hibernation and resume.
		protect_image	Turn on image protection during restoration
				(that will set all pages holding image data
				during restoration read-only).

	hibernate.compressor= 	[HIBERNATION] Compression algorithm to be
				used with hibernation.
				Format: { lzo | lz4 }
				Default: lzo

				lzo: Select LZO compression algorithm to
				compress/decompress hibernation image.

				lz4: Select LZ4 compression algorithm to
				compress/decompress hibernation image.

	hibernate.pm_test_delay=
			[HIBERNATION]
			Sets the number of seconds to remain in a hibernation test
			mode before resuming the system (see
			/sys/power/pm_test). Only available when CONFIG_PM_DEBUG
			is set. Default value is 5.

	highmem=nn[KMG]	[KNL,BOOT,EARLY] forces the highmem zone to have an exact
			size of <nn>. This works even on boxes that have no
			highmem otherwise. This also works to reduce highmem
			size on bigger boxes.

	highres=	[KNL] Enable/disable high resolution timer mode.
			Valid parameters: "on", "off"
			Default: "on"

	hlt		[BUGS=ARM,SH]

	hostname=	[KNL,EARLY] Set the hostname (aka UTS nodename).
			Format: <string>
			This allows setting the system's hostname during early
			startup. This sets the name returned by gethostname.
			Using this parameter to set the hostname makes it
			possible to ensure the hostname is correctly set before
			any userspace processes run, avoiding the possibility
			that a process may call gethostname before the hostname
			has been explicitly set, resulting in the calling
			process getting an incorrect result. The string must
			not exceed the maximum allowed hostname length (usually
			64 characters) and will be truncated otherwise.

	hpet=		[X86-32,HPET] option to control HPET usage
			Format: { enable (default) | disable | force |
				verbose }
			disable: disable HPET and use PIT instead
			force: allow force enabled of undocumented chips (ICH4,
				VIA, nVidia)
			verbose: show contents of HPET registers during setup

	hpet_mmap=	[X86, HPET_MMAP] Allow userspace to mmap HPET
			registers.  Default set by CONFIG_HPET_MMAP_DEFAULT.

	hugepages=	[HW,EARLY] Number of HugeTLB pages to allocate at boot.
			If this follows hugepagesz (below), it specifies
			the number of pages of hugepagesz to be allocated.
			If this is the first HugeTLB parameter on the command
			line, it specifies the number of pages to allocate for
			the default huge page size. If using node format, the
			number of pages to allocate per-node can be specified.
			See also Documentation/admin-guide/mm/hugetlbpage.rst.
			Format: <integer> or (node format)
				<node>:<integer>[,<node>:<integer>]

	hugepagesz=
			[HW,EARLY] The size of the HugeTLB pages.  This is
			used in conjunction with hugepages (above) to
			allocate huge pages of a specific size at boot. The
			pair hugepagesz=X hugepages=Y can be specified once
			for each supported huge page size. Huge page sizes
			are architecture dependent. See also
			Documentation/admin-guide/mm/hugetlbpage.rst.
			Format: size[KMG]

	hugepage_alloc_threads=
			[HW] The number of threads that should be used to
			allocate hugepages during boot. This option can be
			used to improve system bootup time when allocating
			a large amount of huge pages.
			The default value is 25% of the available hardware threads.

			Note that this parameter only applies to non-gigantic huge pages.

	hugetlb_cma=	[HW,CMA,EARLY] The size of a CMA area used for allocation
			of gigantic hugepages. Or using node format, the size
			of a CMA area per node can be specified.
			Format: nn[KMGTPE] or (node format)
				<node>:nn[KMGTPE][,<node>:nn[KMGTPE]]

			Reserve a CMA area of given size and allocate gigantic
			hugepages using the CMA allocator. If enabled, the
			boot-time allocation of gigantic hugepages is skipped.

	hugetlb_cma_only=
			[HW,CMA,EARLY] When allocating new HugeTLB pages, only
			try to allocate from the CMA areas.

			This option does nothing if hugetlb_cma= is not also
			specified.

	hugetlb_free_vmemmap=
			[KNL] Requires CONFIG_HUGETLB_PAGE_OPTIMIZE_VMEMMAP
			enabled.
			Control if HugeTLB Vmemmap Optimization (HVO) is enabled.
			Allows heavy hugetlb users to free up some more
			memory (7 * PAGE_SIZE for each 2MB hugetlb page).
			Format: { on | off (default) }

			on: enable HVO
			off: disable HVO

			Built with CONFIG_HUGETLB_PAGE_OPTIMIZE_VMEMMAP_DEFAULT_ON=y,
			the default is on.

			Note that the vmemmap pages may be allocated from the added
			memory block itself when memory_hotplug.memmap_on_memory is
			enabled, those vmemmap pages cannot be optimized even if this
			feature is enabled.  Other vmemmap pages not allocated from
			the added memory block itself do not be affected.

	hung_task_panic=
			[KNL] Should the hung task detector generate panics.
			Format: 0 | 1

			A value of 1 instructs the kernel to panic when a
			hung task is detected. The default value is controlled
			by the CONFIG_BOOTPARAM_HUNG_TASK_PANIC build-time
			option. The value selected by this boot parameter can
			be changed later by the kernel.hung_task_panic sysctl.

	hvc_iucv=	[S390]	Number of z/VM IUCV hypervisor console (HVC)
				terminal devices. Valid values: 0..8
	hvc_iucv_allow=	[S390]	Comma-separated list of z/VM user IDs.
				If specified, z/VM IUCV HVC accepts connections
				from listed z/VM user IDs only.

	hv_nopvspin	[X86,HYPER_V,EARLY]
			Disables the paravirt spinlock optimizations
			which allow the hypervisor to 'idle' the guest
			on lock contention.

	hw_protection=	[HW]
			Format: reboot | shutdown

			Hardware protection action taken on critical events like
			overtemperature or imminent voltage loss.

	i2c_bus=	[HW]	Override the default board specific I2C bus speed
				or register an additional I2C bus that is not
				registered from board initialization code.
				Format:
				<bus_id>,<clkrate>

	i2c_touchscreen_props= [HW,ACPI,X86]
			Set device-properties for ACPI-enumerated I2C-attached
			touchscreen, to e.g. fix coordinates of upside-down
			mounted touchscreens. If you need this option please
			submit a drivers/platform/x86/touchscreen_dmi.c patch
			adding a DMI quirk for this.

			Format:
			<ACPI_HW_ID>:<prop_name>=<val>[:prop_name=val][:...]
			Where <val> is one of:
			Omit "=<val>" entirely	Set a boolean device-property
			Unsigned number		Set a u32 device-property
			Anything else		Set a string device-property

			Examples (split over multiple lines):
			i2c_touchscreen_props=GDIX1001:touchscreen-inverted-x:
			touchscreen-inverted-y

			i2c_touchscreen_props=MSSL1680:touchscreen-size-x=1920:
			touchscreen-size-y=1080:touchscreen-inverted-y:
			firmware-name=gsl1680-vendor-model.fw:silead,home-button

	i8042.debug	[HW] Toggle i8042 debug mode
	i8042.unmask_kbd_data
			[HW] Enable printing of interrupt data from the KBD port
			     (disabled by default, and as a pre-condition
			     requires that i8042.debug=1 be enabled)
	i8042.direct	[HW] Put keyboard port into non-translated mode
	i8042.dumbkbd	[HW] Pretend that controller can only read data from
			     keyboard and cannot control its state
			     (Don't attempt to blink the leds)
	i8042.noaux	[HW] Don't check for auxiliary (== mouse) port
	i8042.nokbd	[HW] Don't check/create keyboard port
	i8042.noloop	[HW] Disable the AUX Loopback command while probing
			     for the AUX port
	i8042.nomux	[HW] Don't check presence of an active multiplexing
			     controller
	i8042.nopnp	[HW] Don't use ACPIPnP / PnPBIOS to discover KBD/AUX
			     controllers
	i8042.notimeout	[HW] Ignore timeout condition signalled by controller
	i8042.reset	[HW] Reset the controller during init, cleanup and
			     suspend-to-ram transitions, only during s2r
			     transitions, or never reset
			Format: { 1 | Y | y | 0 | N | n }
			1, Y, y: always reset controller
			0, N, n: don't ever reset controller
			Default: only on s2r transitions on x86; most other
			architectures force reset to be always executed
	i8042.unlock	[HW] Unlock (ignore) the keylock
	i8042.kbdreset	[HW] Reset device connected to KBD port
	i8042.probe_defer
			[HW] Allow deferred probing upon i8042 probe errors

	i810=		[HW,DRM]

	i915.invert_brightness=
			[DRM] Invert the sense of the variable that is used to
			set the brightness of the panel backlight. Normally a
			brightness value of 0 indicates backlight switched off,
			and the maximum of the brightness value sets the backlight
			to maximum brightness. If this parameter is set to 0
			(default) and the machine requires it, or this parameter
			is set to 1, a brightness value of 0 sets the backlight
			to maximum brightness, and the maximum of the brightness
			value switches the backlight off.
			-1 -- never invert brightness
			 0 -- machine default
			 1 -- force brightness inversion

	ia32_emulation=	[X86-64]
			Format: <bool>
			When true, allows loading 32-bit programs and executing 32-bit
			syscalls, essentially overriding IA32_EMULATION_DEFAULT_DISABLED at
			boot time. When false, unconditionally disables IA32 emulation.

	icn=		[HW,ISDN]
			Format: <io>[,<membase>[,<icn_id>[,<icn_id2>]]]


	idle=		[X86,EARLY]
			Format: idle=poll, idle=halt, idle=nomwait

			idle=poll:  Don't do power saving in the idle loop
			using HLT, but poll for rescheduling event. This will
			make the CPUs eat a lot more power, but may be useful
			to get slightly better performance in multiprocessor
			benchmarks. It also makes some profiling using
			performance counters more accurate.  Please note that
			on systems with MONITOR/MWAIT support (like Intel
			EM64T CPUs) this option has no performance advantage
			over the normal idle loop.  It may also interact badly
			with hyperthreading.

			idle=halt: Halt is forced to be used for CPU idle.
			In such case C2/C3 won't be used again.

			idle=nomwait: Disable mwait for CPU C-states

	idxd.sva=	[HW]
			Format: <bool>
			Allow force disabling of Shared Virtual Memory (SVA)
			support for the idxd driver. By default it is set to
			true (1).

	idxd.tc_override= [HW]
			Format: <bool>
			Allow override of default traffic class configuration
			for the device. By default it is set to false (0).

	ieee754=	[MIPS] Select IEEE Std 754 conformance mode
			Format: { strict | legacy | 2008 | relaxed | emulated }
			Default: strict

			Choose which programs will be accepted for execution
			based on the IEEE 754 NaN encoding(s) supported by
			the FPU and the NaN encoding requested with the value
			of an ELF file header flag individually set by each
			binary.  Hardware implementations are permitted to
			support either or both of the legacy and the 2008 NaN
			encoding mode.

			Available settings are as follows:
			strict	accept binaries that request a NaN encoding
				supported by the FPU
			legacy	only accept legacy-NaN binaries, if supported
				by the FPU
			2008	only accept 2008-NaN binaries, if supported
				by the FPU
			relaxed	accept any binaries regardless of whether
				supported by the FPU
			emulated accept any binaries but enable FPU emulator
				if binary mode is unsupported by the FPU.

			The FPU emulator is always able to support both NaN
			encodings, so if no FPU hardware is present or it has
			been disabled with 'nofpu', then the settings of
			'legacy' and '2008' strap the emulator accordingly,
			'relaxed' straps the emulator for both legacy-NaN and
			2008-NaN, whereas 'strict' enables legacy-NaN only on
			legacy processors and both NaN encodings on MIPS32 or
			MIPS64 CPUs.

			The setting for ABS.fmt/NEG.fmt instruction execution
			mode generally follows that for the NaN encoding,
			except where unsupported by hardware.

	ignore_loglevel	[KNL,EARLY]
			Ignore loglevel setting - this will print /all/
			kernel messages to the console. Useful for debugging.
			We also add it as printk module parameter, so users
			could change it dynamically, usually by
			/sys/module/printk/parameters/ignore_loglevel.

	ignore_rlimit_data
			Ignore RLIMIT_DATA setting for data mappings,
			print warning at first misuse.  Can be changed via
			/sys/module/kernel/parameters/ignore_rlimit_data.

	ihash_entries=	[KNL]
			Set number of hash buckets for inode cache.

	ima_appraise=	[IMA] appraise integrity measurements
			Format: { "off" | "enforce" | "fix" | "log" }
			default: "enforce"

	ima_appraise_tcb [IMA] Deprecated.  Use ima_policy= instead.
			The builtin appraise policy appraises all files
			owned by uid=0.

	ima_canonical_fmt [IMA]
			Use the canonical format for the binary runtime
			measurements, instead of host native format.

	ima_hash=	[IMA]
			Format: { md5 | sha1 | rmd160 | sha256 | sha384
				   | sha512 | ... }
			default: "sha1"

			The list of supported hash algorithms is defined
			in crypto/hash_info.h.

	ima_policy=	[IMA]
			The builtin policies to load during IMA setup.
			Format: "tcb | appraise_tcb | secure_boot |
				 fail_securely | critical_data"

			The "tcb" policy measures all programs exec'd, files
			mmap'd for exec, and all files opened with the read
			mode bit set by either the effective uid (euid=0) or
			uid=0.

			The "appraise_tcb" policy appraises the integrity of
			all files owned by root.

			The "secure_boot" policy appraises the integrity
			of files (eg. kexec kernel image, kernel modules,
			firmware, policy, etc) based on file signatures.

			The "fail_securely" policy forces file signature
			verification failure also on privileged mounted
			filesystems with the SB_I_UNVERIFIABLE_SIGNATURE
			flag.

			The "critical_data" policy measures kernel integrity
			critical data.

	ima_tcb		[IMA] Deprecated.  Use ima_policy= instead.
			Load a policy which meets the needs of the Trusted
			Computing Base.  This means IMA will measure all
			programs exec'd, files mmap'd for exec, and all files
			opened for read by uid=0.

	ima_template=	[IMA]
			Select one of defined IMA measurements template formats.
			Formats: { "ima" | "ima-ng" | "ima-ngv2" | "ima-sig" |
				   "ima-sigv2" }
			Default: "ima-ng"

	ima_template_fmt=
			[IMA] Define a custom template format.
			Format: { "field1|...|fieldN" }

	ima.ahash_minsize= [IMA] Minimum file size for asynchronous hash usage
			Format: <min_file_size>
			Set the minimal file size for using asynchronous hash.
			If left unspecified, ahash usage is disabled.

			ahash performance varies for different data sizes on
			different crypto accelerators. This option can be used
			to achieve the best performance for a particular HW.

	ima.ahash_bufsize= [IMA] Asynchronous hash buffer size
			Format: <bufsize>
			Set hashing buffer size. Default: 4k.

			ahash performance varies for different chunk sizes on
			different crypto accelerators. This option can be used
			to achieve best performance for particular HW.

	ima=		[IMA] Enable or disable IMA
			Format: { "off" | "on" }
			Default: "on"
			Note that disabling IMA is limited to kdump kernel.

	indirect_target_selection= [X86,Intel] Mitigation control for Indirect
			Target Selection(ITS) bug in Intel CPUs. Updated
			microcode is also required for a fix in IBPB.

			on:     Enable mitigation (default).
			off:    Disable mitigation.
			force:	Force the ITS bug and deploy default
				mitigation.
			vmexit: Only deploy mitigation if CPU is affected by
				guest/host isolation part of ITS.
			stuff:	Deploy RSB-fill mitigation when retpoline is
				also deployed. Otherwise, deploy the default
				mitigation.

			For details see:
			Documentation/admin-guide/hw-vuln/indirect-target-selection.rst

	init=		[KNL]
			Format: <full_path>
			Run specified binary instead of /sbin/init as init
			process.

	initcall_debug	[KNL] Trace initcalls as they are executed.  Useful
			for working out where the kernel is dying during
			startup.

	initcall_blacklist=  [KNL] Do not execute a comma-separated list of
			initcall functions.  Useful for debugging built-in
			modules and initcalls.

	initramfs_async= [KNL]
			Format: <bool>
			Default: 1
			This parameter controls whether the initramfs
			image is unpacked asynchronously, concurrently
			with devices being probed and
			initialized. This should normally just work,
			but as a debugging aid, one can get the
			historical behaviour of the initramfs
			unpacking being completed before device_ and
			late_ initcalls.

	initrd=		[BOOT,EARLY] Specify the location of the initial ramdisk

	initrdmem=	[KNL,EARLY] Specify a physical address and size from which to
			load the initrd. If an initrd is compiled in or
			specified in the bootparams, it takes priority over this
			setting.
			Format: ss[KMG],nn[KMG]
			Default is 0, 0

	init_on_alloc=	[MM,EARLY] Fill newly allocated pages and heap objects with
			zeroes.
			Format: 0 | 1
			Default set by CONFIG_INIT_ON_ALLOC_DEFAULT_ON.

	init_on_free=	[MM,EARLY] Fill freed pages and heap objects with zeroes.
			Format: 0 | 1
			Default set by CONFIG_INIT_ON_FREE_DEFAULT_ON.

	init_pkru=	[X86] Specify the default memory protection keys rights
			register contents for all processes.  0x55555554 by
			default (disallow access to all but pkey 0).  Can
			override in debugfs after boot.

	inport.irq=	[HW] Inport (ATI XL and Microsoft) busmouse driver
			Format: <irq>

	int_pln_enable	[X86] Enable power limit notification interrupt

	integrity_audit=[IMA]
			Format: { "0" | "1" }
			0 -- basic integrity auditing messages. (Default)
			1 -- additional integrity auditing messages.

	intel_iommu=	[DMAR] Intel IOMMU driver (DMAR) option
		on
			Enable intel iommu driver.
		off
			Disable intel iommu driver.
		igfx_off [Default Off]
			By default, gfx is mapped as normal device. If a gfx
			device has a dedicated DMAR unit, the DMAR unit is
			bypassed by not enabling DMAR with this option. In
			this case, gfx device will use physical address for
			DMA.
		strict [Default Off]
			Deprecated, equivalent to iommu.strict=1.
		sp_off [Default Off]
			By default, super page will be supported if Intel IOMMU
			has the capability. With this option, super page will
			not be supported.
		sm_on
			Enable the Intel IOMMU scalable mode if the hardware
			advertises that it has support for the scalable mode
			translation.
		sm_off
			Disallow use of the Intel IOMMU scalable mode.
		tboot_noforce [Default Off]
			Do not force the Intel IOMMU enabled under tboot.
			By default, tboot will force Intel IOMMU on, which
			could harm performance of some high-throughput
			devices like 40GBit network cards, even if identity
			mapping is enabled.
			Note that using this option lowers the security
			provided by tboot because it makes the system
			vulnerable to DMA attacks.

	intel_idle.max_cstate=	[KNL,HW,ACPI,X86]
			0	disables intel_idle and fall back on acpi_idle.
			1 to 9	specify maximum depth of C-state.

	intel_pstate=	[X86,EARLY]
			disable
			  Do not enable intel_pstate as the default
			  scaling driver for the supported processors
                        active
                          Use intel_pstate driver to bypass the scaling
                          governors layer of cpufreq and provides it own
                          algorithms for p-state selection. There are two
                          P-state selection algorithms provided by
                          intel_pstate in the active mode: powersave and
                          performance.  The way they both operate depends
                          on whether or not the hardware managed P-states
                          (HWP) feature has been enabled in the processor
                          and possibly on the processor model.
			passive
			  Use intel_pstate as a scaling driver, but configure it
			  to work with generic cpufreq governors (instead of
			  enabling its internal governor).  This mode cannot be
			  used along with the hardware-managed P-states (HWP)
			  feature.
			force
			  Enable intel_pstate on systems that prohibit it by default
			  in favor of acpi-cpufreq. Forcing the intel_pstate driver
			  instead of acpi-cpufreq may disable platform features, such
			  as thermal controls and power capping, that rely on ACPI
			  P-States information being indicated to OSPM and therefore
			  should be used with caution. This option does not work with
			  processors that aren't supported by the intel_pstate driver
			  or on platforms that use pcc-cpufreq instead of acpi-cpufreq.
			no_hwp
			  Do not enable hardware P state control (HWP)
			  if available.
			hwp_only
			  Only load intel_pstate on systems which support
			  hardware P state control (HWP) if available.
			support_acpi_ppc
			  Enforce ACPI _PPC performance limits. If the Fixed ACPI
			  Description Table, specifies preferred power management
			  profile as "Enterprise Server" or "Performance Server",
			  then this feature is turned on by default.
			per_cpu_perf_limits
			  Allow per-logical-CPU P-State performance control limits using
			  cpufreq sysfs interface
			no_cas
			  Do not enable capacity-aware scheduling (CAS) on
			  hybrid systems

	intremap=	[X86-64,Intel-IOMMU,EARLY]
			on	enable Interrupt Remapping (default)
			off	disable Interrupt Remapping
			nosid	disable Source ID checking
			no_x2apic_optout
				BIOS x2APIC opt-out request will be ignored
			nopost	disable Interrupt Posting
			posted_msi
				enable MSIs delivered as posted interrupts

	iomem=		Disable strict checking of access to MMIO memory
		strict	regions from userspace.
		relaxed

	iommu=		[X86,EARLY]

		off
			Don't initialize and use any kind of IOMMU.

		force
			Force the use of the hardware IOMMU even when
			it is not actually needed (e.g. because < 3 GB
			memory).

		noforce
			Don't force hardware IOMMU usage when it is not
			needed. (default).

		biomerge
		panic
		nopanic
		merge
		nomerge

		soft
			Use software bounce buffering (SWIOTLB) (default for
			Intel machines). This can be used to prevent the usage
			of an available hardware IOMMU.

			[X86]
		pt
			[X86]
		nopt
			[PPC/POWERNV]
		nobypass
			Disable IOMMU bypass, using IOMMU for PCI devices.

		[X86]
		AMD Gart HW IOMMU-specific options:

		<size>
			Set the size of the remapping area in bytes.

		allowed
			Overwrite iommu off workarounds for specific chipsets

		fullflush
			Flush IOMMU on each allocation (default).

		nofullflush
			Don't use IOMMU fullflush.

		memaper[=<order>]
			Allocate an own aperture over RAM with size
			32MB<<order.  (default: order=1, i.e. 64MB)

		merge
			Do scatter-gather (SG) merging. Implies "force"
			(experimental).

		nomerge
			Don't do scatter-gather (SG) merging.

		noaperture
			Ask the IOMMU not to touch the aperture for AGP.

		noagp
			Don't initialize the AGP driver and use full aperture.

		panic
			Always panic when IOMMU overflows.

	iommu.forcedac=	[ARM64,X86,EARLY] Control IOVA allocation for PCI devices.
			Format: { "0" | "1" }
			0 - Try to allocate a 32-bit DMA address first, before
			  falling back to the full range if needed.
			1 - Allocate directly from the full usable range,
			  forcing Dual Address Cycle for PCI cards supporting
			  greater than 32-bit addressing.

	iommu.strict=	[ARM64,X86,S390,EARLY] Configure TLB invalidation behaviour
			Format: { "0" | "1" }
			0 - Lazy mode.
			  Request that DMA unmap operations use deferred
			  invalidation of hardware TLBs, for increased
			  throughput at the cost of reduced device isolation.
			  Will fall back to strict mode if not supported by
			  the relevant IOMMU driver.
			1 - Strict mode.
			  DMA unmap operations invalidate IOMMU hardware TLBs
			  synchronously.
			unset - Use value of CONFIG_IOMMU_DEFAULT_DMA_{LAZY,STRICT}.
			Note: on x86, strict mode specified via one of the
			legacy driver-specific options takes precedence.

	iommu.passthrough=
			[ARM64,X86,EARLY] Configure DMA to bypass the IOMMU by default.
			Format: { "0" | "1" }
			0 - Use IOMMU translation for DMA.
			1 - Bypass the IOMMU for DMA.
			unset - Use value of CONFIG_IOMMU_DEFAULT_PASSTHROUGH.

	io7=		[HW] IO7 for Marvel-based Alpha systems
			See comment before marvel_specify_io7 in
			arch/alpha/kernel/core_marvel.c.

	io_delay=	[X86,EARLY] I/O delay method
		0x80
			Standard port 0x80 based delay
		0xed
			Alternate port 0xed based delay (needed on some systems)
		udelay
			Simple two microseconds delay
		none
			No delay

	ip=		[IP_PNP]
			See Documentation/admin-guide/nfs/nfsroot.rst.

	ipcmni_extend	[KNL,EARLY] Extend the maximum number of unique System V
			IPC identifiers from 32,768 to 16,777,216.

	ipe.enforce=	[IPE]
			Format: <bool>
			Determine whether IPE starts in permissive (0) or
			enforce (1) mode. The default is enforce.

	ipe.success_audit=
			[IPE]
			Format: <bool>
			Start IPE with success auditing enabled, emitting
			an audit event when a binary is allowed. The default
			is 0.

	irqaffinity=	[SMP] Set the default irq affinity mask
			The argument is a cpu list, as described above.

	irqchip.gicv2_force_probe=
			[ARM,ARM64,EARLY]
			Format: <bool>
			Force the kernel to look for the second 4kB page
			of a GICv2 controller even if the memory range
			exposed by the device tree is too small.

	irqchip.gicv3_nolpi=
			[ARM,ARM64,EARLY]
			Force the kernel to ignore the availability of
			LPIs (and by consequence ITSs). Intended for system
			that use the kernel as a bootloader, and thus want
			to let secondary kernels in charge of setting up
			LPIs.

	irqchip.gicv3_pseudo_nmi= [ARM64,EARLY]
			Enables support for pseudo-NMIs in the kernel. This
			requires the kernel to be built with
			CONFIG_ARM64_PSEUDO_NMI.

	irqchip.riscv_imsic_noipi
			[RISC-V,EARLY]
			Force the kernel to not use IMSIC software injected MSIs
			as IPIs. Intended for system where IMSIC is trap-n-emulated,
			and thus want to reduce MMIO traps when triggering IPIs
			to multiple harts.

	irqfixup	[HW]
			When an interrupt is not handled search all handlers
			for it. Intended to get systems with badly broken
			firmware running.

	irqhandler.duration_warn_us= [KNL]
			Warn if an IRQ handler exceeds the specified duration
			threshold in microseconds. Useful for identifying
			long-running IRQs in the system.

	irqpoll		[HW]
			When an interrupt is not handled search all handlers
			for it. Also check all handlers each timer
			interrupt. Intended to get systems with badly broken
			firmware running.

	isapnp=		[ISAPNP]
			Format: <RDP>,<reset>,<pci_scan>,<verbosity>

	isolcpus=	[KNL,SMP,ISOL] Isolate a given set of CPUs from disturbance.
			[Deprecated - use cpusets instead]
			Format: [flag-list,]<cpu-list>

			Specify one or more CPUs to isolate from disturbances
			specified in the flag list (default: domain):

			nohz
			  Disable the tick when a single task runs as well as
			  disabling other kernel noises like having RCU callbacks
			  offloaded. This is equivalent to the nohz_full parameter.

			  A residual 1Hz tick is offloaded to workqueues, which you
			  need to affine to housekeeping through the global
			  workqueue's affinity configured via the
			  /sys/devices/virtual/workqueue/cpumask sysfs file, or
			  by using the 'domain' flag described below.

			  NOTE: by default the global workqueue runs on all CPUs,
			  so to protect individual CPUs the 'cpumask' file has to
			  be configured manually after bootup.

			domain
			  Isolate from the general SMP balancing and scheduling
			  algorithms. Note that performing domain isolation this way
			  is irreversible: it's not possible to bring back a CPU to
			  the domains once isolated through isolcpus. It's strongly
			  advised to use cpusets instead to disable scheduler load
			  balancing through the "cpuset.sched_load_balance" file.
			  It offers a much more flexible interface where CPUs can
			  move in and out of an isolated set anytime.

			  You can move a process onto or off an "isolated" CPU via
			  the CPU affinity syscalls or cpuset.
			  <cpu number> begins at 0 and the maximum value is
			  "number of CPUs in system - 1".

			managed_irq

			  Isolate from being targeted by managed interrupts
			  which have an interrupt mask containing isolated
			  CPUs. The affinity of managed interrupts is
			  handled by the kernel and cannot be changed via
			  the /proc/irq/* interfaces.

			  This isolation is best effort and only effective
			  if the automatically assigned interrupt mask of a
			  device queue contains isolated and housekeeping
			  CPUs. If housekeeping CPUs are online then such
			  interrupts are directed to the housekeeping CPU
			  so that IO submitted on the housekeeping CPU
			  cannot disturb the isolated CPU.

			  If a queue's affinity mask contains only isolated
			  CPUs then this parameter has no effect on the
			  interrupt routing decision, though interrupts are
			  only delivered when tasks running on those
			  isolated CPUs submit IO. IO submitted on
			  housekeeping CPUs has no influence on those
			  queues.

			The format of <cpu-list> is described above.

	iucv=		[HW,NET]

	ivrs_ioapic	[HW,X86-64]
			Provide an override to the IOAPIC-ID<->DEVICE-ID
			mapping provided in the IVRS ACPI table.
			By default, PCI segment is 0, and can be omitted.

			For example, to map IOAPIC-ID decimal 10 to
			PCI segment 0x1 and PCI device 00:14.0,
			write the parameter as:
				ivrs_ioapic=10@0001:00:14.0

			Deprecated formats:
			* To map IOAPIC-ID decimal 10 to PCI device 00:14.0
			  write the parameter as:
				ivrs_ioapic[10]=00:14.0
			* To map IOAPIC-ID decimal 10 to PCI segment 0x1 and
			  PCI device 00:14.0 write the parameter as:
				ivrs_ioapic[10]=0001:00:14.0

	ivrs_hpet	[HW,X86-64]
			Provide an override to the HPET-ID<->DEVICE-ID
			mapping provided in the IVRS ACPI table.
			By default, PCI segment is 0, and can be omitted.

			For example, to map HPET-ID decimal 10 to
			PCI segment 0x1 and PCI device 00:14.0,
			write the parameter as:
				ivrs_hpet=10@0001:00:14.0

			Deprecated formats:
			* To map HPET-ID decimal 0 to PCI device 00:14.0
			  write the parameter as:
				ivrs_hpet[0]=00:14.0
			* To map HPET-ID decimal 10 to PCI segment 0x1 and
			  PCI device 00:14.0 write the parameter as:
				ivrs_ioapic[10]=0001:00:14.0

	ivrs_acpihid	[HW,X86-64]
			Provide an override to the ACPI-HID:UID<->DEVICE-ID
			mapping provided in the IVRS ACPI table.
			By default, PCI segment is 0, and can be omitted.

			For example, to map UART-HID:UID AMD0020:0 to
			PCI segment 0x1 and PCI device ID 00:14.5,
			write the parameter as:
				ivrs_acpihid=AMD0020:0@0001:00:14.5

			Deprecated formats:
			* To map UART-HID:UID AMD0020:0 to PCI segment is 0,
			  PCI device ID 00:14.5, write the parameter as:
				ivrs_acpihid[00:14.5]=AMD0020:0
			* To map UART-HID:UID AMD0020:0 to PCI segment 0x1 and
			  PCI device ID 00:14.5, write the parameter as:
				ivrs_acpihid[0001:00:14.5]=AMD0020:0

	js=		[HW,JOY] Analog joystick
			See Documentation/input/joydev/joystick.rst.

	kasan_multi_shot
			[KNL] Enforce KASAN (Kernel Address Sanitizer) to print
			report on every invalid memory access. Without this
			parameter KASAN will print report only for the first
			invalid access.

	keep_bootcon	[KNL,EARLY]
			Do not unregister boot console at start. This is only
			useful for debugging when something happens in the window
			between unregistering the boot console and initializing
			the real console.

	keepinitrd	[HW,ARM] See retain_initrd.

	kernelcore=	[KNL,X86,PPC,EARLY]
			Format: nn[KMGTPE] | nn% | "mirror"
			This parameter specifies the amount of memory usable by
			the kernel for non-movable allocations.  The requested
			amount is spread evenly throughout all nodes in the
			system as ZONE_NORMAL.  The remaining memory is used for
			movable memory in its own zone, ZONE_MOVABLE.  In the
			event, a node is too small to have both ZONE_NORMAL and
			ZONE_MOVABLE, kernelcore memory will take priority and
			other nodes will have a larger ZONE_MOVABLE.

			ZONE_MOVABLE is used for the allocation of pages that
			may be reclaimed or moved by the page migration
			subsystem.  Note that allocations like PTEs-from-HighMem
			still use the HighMem zone if it exists, and the Normal
			zone if it does not.

			It is possible to specify the exact amount of memory in
			the form of "nn[KMGTPE]", a percentage of total system
			memory in the form of "nn%", or "mirror".  If "mirror"
			option is specified, mirrored (reliable) memory is used
			for non-movable allocations and remaining memory is used
			for Movable pages.  "nn[KMGTPE]", "nn%", and "mirror"
			are exclusive, so you cannot specify multiple forms.

	kgdbdbgp=	[KGDB,HW,EARLY] kgdb over EHCI usb debug port.
			Format: <Controller#>[,poll interval]
			The controller # is the number of the ehci usb debug
			port as it is probed via PCI.  The poll interval is
			optional and is the number seconds in between
			each poll cycle to the debug port in case you need
			the functionality for interrupting the kernel with
			gdb or control-c on the dbgp connection.  When
			not using this parameter you use sysrq-g to break into
			the kernel debugger.

	kgdboc=		[KGDB,HW] kgdb over consoles.
			Requires a tty driver that supports console polling,
			or a supported polling keyboard driver (non-usb).
			 Serial only format: <serial_device>[,baud]
			 keyboard only format: kbd
			 keyboard and serial format: kbd,<serial_device>[,baud]
			Optional Kernel mode setting:
			 kms, kbd format: kms,kbd
			 kms, kbd and serial format: kms,kbd,<ser_dev>[,baud]

	kgdboc_earlycon=	[KGDB,HW,EARLY]
			If the boot console provides the ability to read
			characters and can work in polling mode, you can use
			this parameter to tell kgdb to use it as a backend
			until the normal console is registered. Intended to
			be used together with the kgdboc parameter which
			specifies the normal console to transition to.

			The name of the early console should be specified
			as the value of this parameter. Note that the name of
			the early console might be different than the tty
			name passed to kgdboc. It's OK to leave the value
			blank and the first boot console that implements
			read() will be picked.

	kgdbwait	[KGDB,EARLY] Stop kernel execution and enter the
			kernel debugger at the earliest opportunity.

	kho=		[KEXEC,EARLY]
			Format: { "0" | "1" | "off" | "on" | "y" | "n" }
			Enables or disables Kexec HandOver.
			"0" | "off" | "n" - kexec handover is disabled
			"1" | "on" | "y" - kexec handover is enabled

	kho_scratch=	[KEXEC,EARLY]
			Format: ll[KMG],mm[KMG],nn[KMG] | nn%
			Defines the size of the KHO scratch region. The KHO
			scratch regions are physically contiguous memory
			ranges that can only be used for non-kernel
			allocations. That way, even when memory is heavily
			fragmented with handed over memory, the kexeced
			kernel will always have enough contiguous ranges to
			bootstrap itself.

			It is possible to specify the exact amount of
			memory in the form of "ll[KMG],mm[KMG],nn[KMG]"
			where the first parameter defines the size of a low
			memory scratch area, the second parameter defines
			the size of a global scratch area and the third
			parameter defines the size of additional per-node
			scratch areas.  The form "nn%" defines scale factor
			(in percents) of memory that was used during boot.

	kmac=		[MIPS] Korina ethernet MAC address.
			Configure the RouterBoard 532 series on-chip
			Ethernet adapter MAC address.

	kmemleak=	[KNL,EARLY] Boot-time kmemleak enable/disable
			Valid arguments: on, off
			Default: on
			Built with CONFIG_DEBUG_KMEMLEAK_DEFAULT_OFF=y,
			the default is off.

	kprobe_event=[probe-list]
			[FTRACE] Add kprobe events and enable at boot time.
			The probe-list is a semicolon delimited list of probe
			definitions. Each definition is same as kprobe_events
			interface, but the parameters are comma delimited.
			For example, to add a kprobe event on vfs_read with
			arg1 and arg2, add to the command line;

			      kprobe_event=p,vfs_read,$arg1,$arg2

			See also Documentation/trace/kprobetrace.rst "Kernel
			Boot Parameter" section.

	kpti=		[ARM64,EARLY] Control page table isolation of
			user and kernel address spaces.
			Default: enabled on cores which need mitigation.
			0: force disabled
			1: force enabled

	kunit.enable=	[KUNIT] Enable executing KUnit tests. Requires
			CONFIG_KUNIT to be set to be fully enabled. The
			default value can be overridden via
			KUNIT_DEFAULT_ENABLED.
			Default is 1 (enabled)

	kvm.ignore_msrs=[KVM] Ignore guest accesses to unhandled MSRs.
			Default is 0 (don't ignore, but inject #GP)

	kvm.eager_page_split=
			[KVM,X86] Controls whether or not KVM will try to
			proactively split all huge pages during dirty logging.
			Eager page splitting reduces interruptions to vCPU
			execution by eliminating the write-protection faults
			and MMU lock contention that would otherwise be
			required to split huge pages lazily.

			VM workloads that rarely perform writes or that write
			only to a small region of VM memory may benefit from
			disabling eager page splitting to allow huge pages to
			still be used for reads.

			The behavior of eager page splitting depends on whether
			KVM_DIRTY_LOG_INITIALLY_SET is enabled or disabled. If
			disabled, all huge pages in a memslot will be eagerly
			split when dirty logging is enabled on that memslot. If
			enabled, eager page splitting will be performed during
			the KVM_CLEAR_DIRTY ioctl, and only for the pages being
			cleared.

			Eager page splitting is only supported when kvm.tdp_mmu=Y.

			Default is Y (on).

	kvm.enable_virt_at_load=[KVM,ARM64,LOONGARCH,MIPS,RISCV,X86]
			If enabled, KVM will enable virtualization in hardware
			when KVM is loaded, and disable virtualization when KVM
			is unloaded (if KVM is built as a module).

			If disabled, KVM will dynamically enable and disable
			virtualization on-demand when creating and destroying
			VMs, i.e. on the 0=>1 and 1=>0 transitions of the
			number of VMs.

			Enabling virtualization at module load avoids potential
			latency for creation of the 0=>1 VM, as KVM serializes
			virtualization enabling across all online CPUs.  The
			"cost" of enabling virtualization when KVM is loaded,
			is that doing so may interfere with using out-of-tree
			hypervisors that want to "own" virtualization hardware.

	kvm.enable_vmware_backdoor=[KVM] Support VMware backdoor PV interface.
				   Default is false (don't support).

	kvm.nx_huge_pages=
			[KVM] Controls the software workaround for the
			X86_BUG_ITLB_MULTIHIT bug.
			force	: Always deploy workaround.
			off	: Never deploy workaround.
			auto    : Deploy workaround based on the presence of
				  X86_BUG_ITLB_MULTIHIT.

			Default is 'auto'.

			If the software workaround is enabled for the host,
			guests do need not to enable it for nested guests.

	kvm.nx_huge_pages_recovery_ratio=
			[KVM] Controls how many 4KiB pages are periodically zapped
			back to huge pages.  0 disables the recovery, otherwise if
			the value is N KVM will zap 1/Nth of the 4KiB pages every
			period (see below).  The default is 60.

	kvm.nx_huge_pages_recovery_period_ms=
			[KVM] Controls the time period at which KVM zaps 4KiB pages
			back to huge pages. If the value is a non-zero N, KVM will
			zap a portion (see ratio above) of the pages every N msecs.
			If the value is 0 (the default), KVM will pick a period based
			on the ratio, such that a page is zapped after 1 hour on average.

	kvm-amd.nested=	[KVM,AMD] Control nested virtualization feature in
			KVM/SVM. Default is 1 (enabled).

	kvm-amd.npt=	[KVM,AMD] Control KVM's use of Nested Page Tables,
			a.k.a. Two-Dimensional Page Tables. Default is 1
			(enabled). Disable by KVM if hardware lacks support
			for NPT.

	kvm-amd.ciphertext_hiding_asids=
			[KVM,AMD] Ciphertext hiding prevents disallowed accesses
			to SNP private memory from reading ciphertext.  Instead,
			reads will see constant default values (0xff).

			If ciphertext hiding is enabled, the joint SEV-ES and
			SEV-SNP ASID space is partitioned into separate SEV-ES
			and SEV-SNP ASID ranges, with the SEV-SNP range being
			[1..max_snp_asid] and the SEV-ES range being
			(max_snp_asid..min_sev_asid), where min_sev_asid is
			enumerated by CPUID.0x.8000_001F[EDX].

			A non-zero value enables SEV-SNP ciphertext hiding and
			adjusts the ASID ranges for SEV-ES and SEV-SNP guests.
			KVM caps the number of SEV-SNP ASIDs at the maximum
			possible value, e.g. specifying -1u will assign all
			joint SEV-ES and SEV-SNP ASIDs to SEV-SNP.  Note,
			assigning all joint ASIDs to SEV-SNP, i.e. configuring
			max_snp_asid == min_sev_asid-1, will effectively make
			SEV-ES unusable.

	kvm-arm.mode=
			[KVM,ARM,EARLY] Select one of KVM/arm64's modes of
			operation.

			none: Forcefully disable KVM.

			nvhe: Standard nVHE-based mode, without support for
			      protected guests.

			protected: Mode with support for guests whose state is
				   kept private from the host, using VHE or
				   nVHE depending on HW support.

			nested: VHE-based mode with support for nested
				virtualization. Requires at least ARMv8.4
				hardware (with FEAT_NV2).

			Defaults to VHE/nVHE based on hardware support. Setting
			mode to "protected" will disable kexec and hibernation
			for the host. To force nVHE on VHE hardware, add
			"arm64_sw.hvhe=0 id_aa64mmfr1.vh=0" to the
			command-line.
			"nested" is experimental and should be used with
			extreme caution.

	kvm-arm.vgic_v3_group0_trap=
			[KVM,ARM,EARLY] Trap guest accesses to GICv3 group-0
			system registers

	kvm-arm.vgic_v3_group1_trap=
			[KVM,ARM,EARLY] Trap guest accesses to GICv3 group-1
			system registers

	kvm-arm.vgic_v3_common_trap=
			[KVM,ARM,EARLY] Trap guest accesses to GICv3 common
			system registers

	kvm-arm.vgic_v4_enable=
			[KVM,ARM,EARLY] Allow use of GICv4 for direct
			injection of LPIs.

	kvm-arm.wfe_trap_policy=
			[KVM,ARM] Control when to set WFE instruction trap for
			KVM VMs. Traps are allowed but not guaranteed by the
			CPU architecture.

			trap: set WFE instruction trap

			notrap: clear WFE instruction trap

	kvm-arm.wfi_trap_policy=
			[KVM,ARM] Control when to set WFI instruction trap for
			KVM VMs. Traps are allowed but not guaranteed by the
			CPU architecture.

			trap: set WFI instruction trap

			notrap: clear WFI instruction trap

	kvm_cma_resv_ratio=n [PPC,EARLY]
			Reserves given percentage from system memory area for
			contiguous memory allocation for KVM hash pagetable
			allocation.
			By default it reserves 5% of total system memory.
			Format: <integer>
			Default: 5

	kvm-intel.ept=	[KVM,Intel] Control KVM's use of Extended Page Tables,
			a.k.a. Two-Dimensional Page Tables.  Default is 1
			(enabled). Disable by KVM if hardware lacks support
			for EPT.

	kvm-intel.emulate_invalid_guest_state=
			[KVM,Intel] Control whether to emulate invalid guest
			state. Ignored if kvm-intel.enable_unrestricted_guest=1,
			as guest state is never invalid for unrestricted
			guests. This param doesn't apply to nested guests (L2),
			as KVM never emulates invalid L2 guest state.
			Default is 1 (enabled).

	kvm-intel.flexpriority=
			[KVM,Intel] Control KVM's use of FlexPriority feature
			(TPR shadow). Default is 1 (enabled). Disable by KVM if
			hardware lacks support for it.

	kvm-intel.nested=
			[KVM,Intel] Control nested virtualization feature in
			KVM/VMX. Default is 1 (enabled).

	kvm-intel.unrestricted_guest=
			[KVM,Intel] Control KVM's use of unrestricted guest
			feature (virtualized real and unpaged mode). Default
			is 1 (enabled). Disable by KVM if EPT is disabled or
			hardware lacks support for it.

	kvm-intel.vmentry_l1d_flush=[KVM,Intel] Mitigation for L1 Terminal Fault
			CVE-2018-3620.

			Valid arguments: never, cond, always

			always: L1D cache flush on every VMENTER.
			cond:	Flush L1D on VMENTER only when the code between
				VMEXIT and VMENTER can leak host memory.
			never:	Disables the mitigation

			Default is cond (do L1 cache flush in specific instances)

	kvm-intel.vpid=	[KVM,Intel] Control KVM's use of Virtual Processor
			Identification feature (tagged TLBs). Default is 1
			(enabled). Disable by KVM if hardware lacks support
			for it.

	l1d_flush=	[X86,INTEL,EARLY]
			Control mitigation for L1D based snooping vulnerability.

			Certain CPUs are vulnerable to an exploit against CPU
			internal buffers which can forward information to a
			disclosure gadget under certain conditions.

			In vulnerable processors, the speculatively
			forwarded data can be used in a cache side channel
			attack, to access data to which the attacker does
			not have direct access.

			This parameter controls the mitigation. The
			options are:

			on         - enable the interface for the mitigation

	l1tf=           [X86,EARLY] Control mitigation of the L1TF vulnerability on
			      affected CPUs

			The kernel PTE inversion protection is unconditionally
			enabled and cannot be disabled.

			full
				Provides all available mitigations for the
				L1TF vulnerability. Disables SMT and
				enables all mitigations in the
				hypervisors, i.e. unconditional L1D flush.

				SMT control and L1D flush control via the
				sysfs interface is still possible after
				boot.  Hypervisors will issue a warning
				when the first VM is started in a
				potentially insecure configuration,
				i.e. SMT enabled or L1D flush disabled.

			full,force
				Same as 'full', but disables SMT and L1D
				flush runtime control. Implies the
				'nosmt=force' command line option.
				(i.e. sysfs control of SMT is disabled.)

			flush
				Leaves SMT enabled and enables the default
				hypervisor mitigation, i.e. conditional
				L1D flush.

				SMT control and L1D flush control via the
				sysfs interface is still possible after
				boot.  Hypervisors will issue a warning
				when the first VM is started in a
				potentially insecure configuration,
				i.e. SMT enabled or L1D flush disabled.

			flush,nosmt

				Disables SMT and enables the default
				hypervisor mitigation.

				SMT control and L1D flush control via the
				sysfs interface is still possible after
				boot.  Hypervisors will issue a warning
				when the first VM is started in a
				potentially insecure configuration,
				i.e. SMT enabled or L1D flush disabled.

			flush,nowarn
				Same as 'flush', but hypervisors will not
				warn when a VM is started in a potentially
				insecure configuration.

			off
				Disables hypervisor mitigations and doesn't
				emit any warnings.
				It also drops the swap size and available
				RAM limit restriction on both hypervisor and
				bare metal.

			Default is 'flush'.

			For details see: Documentation/admin-guide/hw-vuln/l1tf.rst

	l2cr=		[PPC]

	l3cr=		[PPC]

	lapic		[X86-32,APIC,EARLY] Enable the local APIC even if BIOS
			disabled it.

	lapic=		[X86,APIC] Do not use TSC deadline
			value for LAPIC timer one-shot implementation. Default
			back to the programmable timer unit in the LAPIC.
			Format: notscdeadline

	lapic_timer_c2_ok	[X86,APIC,EARLY] trust the local apic timer
			in C2 power state.

	libata.dma=	[LIBATA] DMA control
			libata.dma=0	  Disable all PATA and SATA DMA
			libata.dma=1	  PATA and SATA Disk DMA only
			libata.dma=2	  ATAPI (CDROM) DMA only
			libata.dma=4	  Compact Flash DMA only
			Combinations also work, so libata.dma=3 enables DMA
			for disks and CDROMs, but not CFs.

	libata.ignore_hpa=	[LIBATA] Ignore HPA limit
			libata.ignore_hpa=0	  keep BIOS limits (default)
			libata.ignore_hpa=1	  ignore limits, using full disk

	libata.noacpi	[LIBATA] Disables use of ACPI in libata suspend/resume
			when set.
			Format: <int>

	libata.force=	[LIBATA] Force configurations.  The format is a comma-
			separated list of "[ID:]VAL" where ID is PORT[.DEVICE].
			PORT and DEVICE are decimal numbers matching port, link
			or device.  Basically, it matches the ATA ID string
			printed on console by libata.  If the whole ID part is
			omitted, the last PORT and DEVICE values are used.  If
			ID hasn't been specified yet, the configuration applies
			to all ports, links and devices.

			If only DEVICE is omitted, the parameter applies to
			the port and all links and devices behind it.  DEVICE
			number of 0 either selects the first device or the
			first fan-out link behind PMP device.  It does not
			select the host link.  DEVICE number of 15 selects the
			host link and device attached to it.

			The VAL specifies the configuration to force.  As long
			as there is no ambiguity, shortcut notation is allowed.
			For example, both 1.5 and 1.5G would work for 1.5Gbps.
			The following configurations can be forced.

			* Cable type: 40c, 80c, short40c, unk, ign or sata.
			  Any ID with matching PORT is used.

			* SATA link speed limit: 1.5Gbps or 3.0Gbps.

			* Transfer mode: pio[0-7], mwdma[0-4] and udma[0-7].
			  udma[/][16,25,33,44,66,100,133] notation is also
			  allowed.

			* nohrst, nosrst, norst: suppress hard, soft and both
			  resets.

			* rstonce: only attempt one reset during hot-unplug
			  link recovery.

			* [no]dbdelay: Enable or disable the extra 200ms delay
			  before debouncing a link PHY and device presence
			  detection.

			* [no]ncq: Turn on or off NCQ.

			* [no]ncqtrim: Enable or disable queued DSM TRIM.

			* [no]ncqati: Enable or disable NCQ trim on ATI chipset.

			* [no]trim: Enable or disable (unqueued) TRIM.

			* trim_zero: Indicate that TRIM command zeroes data.

			* max_trim_128m: Set 128M maximum trim size limit.

			* [no]dma: Turn on or off DMA transfers.

			* atapi_dmadir: Enable ATAPI DMADIR bridge support.

			* atapi_mod16_dma: Enable the use of ATAPI DMA for
			  commands that are not a multiple of 16 bytes.

			* [no]dmalog: Enable or disable the use of the
			  READ LOG DMA EXT command to access logs.

			* [no]iddevlog: Enable or disable access to the
			  identify device data log.

			* [no]logdir: Enable or disable access to the general
			  purpose log directory.

			* max_sec_128: Set transfer size limit to 128 sectors.

			* max_sec_1024: Set or clear transfer size limit to
			  1024 sectors.

			* max_sec_lba48: Set or clear transfer size limit to
			  65535 sectors.

			* external: Mark port as external (hotplug-capable).

			* [no]lpm: Enable or disable link power management.

			* [no]setxfer: Indicate if transfer speed mode setting
			  should be skipped.

			* [no]fua: Disable or enable FUA (Force Unit Access)
			  support for devices supporting this feature.

			* dump_id: Dump IDENTIFY data.

			* disable: Disable this device.

			If there are multiple matching configurations changing
			the same attribute, the last one is used.

	load_ramdisk=	[RAM] [Deprecated]

	lockd.nlm_grace_period=P  [NFS] Assign grace period.
			Format: <integer>

	lockd.nlm_tcpport=N	[NFS] Assign TCP port.
			Format: <integer>

	lockd.nlm_timeout=T	[NFS] Assign timeout value.
			Format: <integer>

	lockd.nlm_udpport=M	[NFS] Assign UDP port.
			Format: <integer>

	lockdown=	[SECURITY,EARLY]
			{ integrity | confidentiality }
			Enable the kernel lockdown feature. If set to
			integrity, kernel features that allow userland to
			modify the running kernel are disabled. If set to
			confidentiality, kernel features that allow userland
			to extract confidential information from the kernel
			are also disabled.

	locktorture.acq_writer_lim= [KNL]
			Set the time limit in jiffies for a lock
			acquisition.  Acquisitions exceeding this limit
			will result in a splat once they do complete.

	locktorture.bind_readers= [KNL]
			Specify the list of CPUs to which the readers are
			to be bound.

	locktorture.bind_writers= [KNL]
			Specify the list of CPUs to which the writers are
			to be bound.

	locktorture.call_rcu_chains= [KNL]
			Specify the number of self-propagating call_rcu()
			chains to set up.  These are used to ensure that
			there is a high probability of an RCU grace period
			in progress at any given time.	Defaults to 0,
			which disables these call_rcu() chains.

	locktorture.long_hold= [KNL]
			Specify the duration in milliseconds for the
			occasional long-duration lock hold time.  Defaults
			to 100 milliseconds.  Select 0 to disable.

	locktorture.nested_locks= [KNL]
			Specify the maximum lock nesting depth that
			locktorture is to exercise, up to a limit of 8
			(MAX_NESTED_LOCKS).  Specify zero to disable.
			Note that this parameter is ineffective on types
			of locks that do not support nested acquisition.

	locktorture.nreaders_stress= [KNL]
			Set the number of locking read-acquisition kthreads.
			Defaults to being automatically set based on the
			number of online CPUs.

	locktorture.nwriters_stress= [KNL]
			Set the number of locking write-acquisition kthreads.

	locktorture.onoff_holdoff= [KNL]
			Set time (s) after boot for CPU-hotplug testing.

	locktorture.onoff_interval= [KNL]
			Set time (s) between CPU-hotplug operations, or
			zero to disable CPU-hotplug testing.

	locktorture.rt_boost= [KNL]
			Do periodic testing of real-time lock priority
			boosting.  Select 0 to disable, 1 to boost
			only rt_mutex, and 2 to boost unconditionally.
			Defaults to 2, which might seem to be an
			odd choice, but which should be harmless for
			non-real-time spinlocks, due to their disabling
			of preemption.	Note that non-realtime mutexes
			disable boosting.

	locktorture.rt_boost_factor= [KNL]
			Number that determines how often and for how
			long priority boosting is exercised.  This is
			scaled down by the number of writers, so that the
			number of boosts per unit time remains roughly
			constant as the number of writers increases.
			On the other hand, the duration of each boost
			increases with the number of writers.

	locktorture.shuffle_interval= [KNL]
			Set task-shuffle interval (jiffies).  Shuffling
			tasks allows some CPUs to go into dyntick-idle
			mode during the locktorture test.

	locktorture.shutdown_secs= [KNL]
			Set time (s) after boot system shutdown.  This
			is useful for hands-off automated testing.

	locktorture.stat_interval= [KNL]
			Time (s) between statistics printk()s.

	locktorture.stutter= [KNL]
			Time (s) to stutter testing, for example,
			specifying five seconds causes the test to run for
			five seconds, wait for five seconds, and so on.
			This tests the locking primitive's ability to
			transition abruptly to and from idle.

	locktorture.torture_type= [KNL]
			Specify the locking implementation to test.

	locktorture.verbose= [KNL]
			Enable additional printk() statements.

	locktorture.writer_fifo= [KNL]
			Run the write-side locktorture kthreads at
			sched_set_fifo() real-time priority.

	logibm.irq=	[HW,MOUSE] Logitech Bus Mouse Driver
			Format: <irq>

	loglevel=	[KNL,EARLY]
			All Kernel Messages with a loglevel smaller than the
			console loglevel will be printed to the console. It can
			also be changed with klogd or other programs. The
			loglevels are defined as follows:

			0 (KERN_EMERG)		system is unusable
			1 (KERN_ALERT)		action must be taken immediately
			2 (KERN_CRIT)		critical conditions
			3 (KERN_ERR)		error conditions
			4 (KERN_WARNING)	warning conditions
			5 (KERN_NOTICE)		normal but significant condition
			6 (KERN_INFO)		informational
			7 (KERN_DEBUG)		debug-level messages

	log_buf_len=n[KMG] [KNL,EARLY]
			Sets the size of the printk ring buffer, in bytes.
			n must be a power of two and greater than the
			minimal size. The minimal size is defined by
			LOG_BUF_SHIFT kernel config parameter. There
			is also CONFIG_LOG_CPU_MAX_BUF_SHIFT config
			parameter that allows to increase the default size
			depending on the number of CPUs. See init/Kconfig
			for more details.

	logo.nologo	[FB] Disables display of the built-in Linux logo.
			This may be used to provide more screen space for
			kernel log messages and is useful when debugging
			kernel boot problems.

	lp=0		[LP]	Specify parallel ports to use, e.g,
	lp=port[,port...]	lp=none,parport0 (lp0 not configured, lp1 uses
	lp=reset		first parallel port). 'lp=0' disables the
	lp=auto			printer driver. 'lp=reset' (which can be
				specified in addition to the ports) causes
				attached printers to be reset. Using
				lp=port1,port2,... specifies the parallel ports
				to associate lp devices with, starting with
				lp0. A port specification may be 'none' to skip
				that lp device, or a parport name such as
				'parport0'. Specifying 'lp=auto' instead of a
				port specification list means that device IDs
				from each port should be examined, to see if
				an IEEE 1284-compliant printer is attached; if
				so, the driver will manage that printer.
				See also header of drivers/char/lp.c.

	lpj=n		[KNL]
			Sets loops_per_jiffy to given constant, thus avoiding
			time-consuming boot-time autodetection (up to 250 ms per
			CPU). 0 enables autodetection (default). To determine
			the correct value for your kernel, boot with normal
			autodetection and see what value is printed. Note that
			on SMP systems the preset will be applied to all CPUs,
			which is likely to cause problems if your CPUs need
			significantly divergent settings. An incorrect value
			will cause delays in the kernel to be wrong, leading to
			unpredictable I/O errors and other breakage. Although
			unlikely, in the extreme case this might damage your
			hardware.

	lsm.debug	[SECURITY] Enable LSM initialization debugging output.

	lsm=lsm1,...,lsmN
			[SECURITY] Choose order of LSM initialization. This
			overrides CONFIG_LSM, and the "security=" parameter.

	machtype=	[Loongson] Share the same kernel image file between
			different yeeloong laptops.
			Example: machtype=lemote-yeeloong-2f-7inch

	maxcpus=	[SMP,EARLY] Maximum number of processors that an SMP kernel
			will bring up during bootup.  maxcpus=n : n >= 0 limits
			the kernel to bring up 'n' processors. Surely after
			bootup you can bring up the other plugged cpu by executing
			"echo 1 > /sys/devices/system/cpu/cpuX/online". So maxcpus
			only takes effect during system bootup.
			While n=0 is a special case, it is equivalent to "nosmp",
			which also disables the IO APIC.

	max_loop=	[LOOP] The number of loop block devices that get
	(loop.max_loop)	unconditionally pre-created at init time. The default
			number is configured by BLK_DEV_LOOP_MIN_COUNT. Instead
			of statically allocating a predefined number, loop
			devices can be requested on-demand with the
			/dev/loop-control interface.

	mce=		[X86-{32,64}]

			Please see Documentation/arch/x86/x86_64/machinecheck.rst for sysfs runtime tunables.

		off
			disable machine check

		no_cmci
			disable CMCI(Corrected Machine Check Interrupt) that
			Intel processor supports.  Usually this disablement is
			not recommended, but it might be handy if your
			hardware is misbehaving.

			Note that you'll get more problems without CMCI than
			with due to the shared banks, i.e. you might get
			duplicated error logs.

		dont_log_ce
			don't make logs for corrected errors.  All events
			reported as corrected are silently cleared by OS. This
			option will be useful if you have no interest in any
			of corrected errors.

		ignore_ce
			disable features for corrected errors, e.g.
			polling timer and CMCI.  All events reported as
			corrected are not cleared by OS and remained in its
			error banks.

			Usually this disablement is not recommended, however
			if there is an agent checking/clearing corrected
			errors (e.g. BIOS or hardware monitoring
			applications), conflicting with OS's error handling,
			and you cannot deactivate the agent, then this option
			will be a help.

		no_lmce
			do not opt-in to Local MCE delivery. Use legacy method
			to broadcast MCEs.

		bootlog
			enable logging of machine checks left over from
			booting. Disabled by default on AMD Fam10h and older
			because some BIOS leave bogus ones.

			If your BIOS doesn't do that it's a good idea to
			enable though to make sure you log even machine check
			events that result in a reboot. On Intel systems it is
			enabled by default.

		nobootlog
			disable boot machine check logging.

		monarchtimeout (number)
			sets the time in us to wait for other CPUs on machine
			checks. 0 to disable.

		bios_cmci_threshold
			don't overwrite the bios-set CMCI threshold. This boot
			option prevents Linux from overwriting the CMCI
			threshold set by the bios.  Without this option, Linux
			always sets the CMCI threshold to 1. Enabling this may
			make memory predictive failure analysis less effective
			if the bios sets thresholds for memory errors since we
			will not see details for all errors.

		recovery
			force-enable recoverable machine check code paths

			Everything else is in sysfs now.


	md=		[HW] RAID subsystems devices and level
			See Documentation/admin-guide/md.rst.

	mdacon=		[MDA]
			Format: <first>,<last>
			Specifies range of consoles to be captured by the MDA.

	mds=		[X86,INTEL,EARLY]
			Control mitigation for the Micro-architectural Data
			Sampling (MDS) vulnerability.

			Certain CPUs are vulnerable to an exploit against CPU
			internal buffers which can forward information to a
			disclosure gadget under certain conditions.

			In vulnerable processors, the speculatively
			forwarded data can be used in a cache side channel
			attack, to access data to which the attacker does
			not have direct access.

			This parameter controls the MDS mitigation. The
			options are:

			full       - Enable MDS mitigation on vulnerable CPUs
			full,nosmt - Enable MDS mitigation and disable
				     SMT on vulnerable CPUs
			off        - Unconditionally disable MDS mitigation

			On TAA-affected machines, mds=off can be prevented by
			an active TAA mitigation as both vulnerabilities are
			mitigated with the same mechanism so in order to disable
			this mitigation, you need to specify tsx_async_abort=off
			too.

			Not specifying this option is equivalent to
			mds=full.

			For details see: Documentation/admin-guide/hw-vuln/mds.rst

	mem=nn[KMG]	[HEXAGON,EARLY] Set the memory size.
			Must be specified, otherwise memory size will be 0.

	mem=nn[KMG]	[KNL,BOOT,EARLY] Force usage of a specific amount
			of memory Amount of memory to be used in cases
			as follows:

			1 for test;
			2 when the kernel is not able to see the whole system memory;
			3 memory that lies after 'mem=' boundary is excluded from
			 the hypervisor, then assigned to KVM guests.
			4 to limit the memory available for kdump kernel.

			[ARC,MICROBLAZE] - the limit applies only to low memory,
			high memory is not affected.

			[ARM64] - only limits memory covered by the linear
			mapping. The NOMAP regions are not affected.

			[X86] Work as limiting max address. Use together
			with memmap= to avoid physical address space collisions.
			Without memmap= PCI devices could be placed at addresses
			belonging to unused RAM.

			Note that this only takes effects during boot time since
			in above case 3, memory may need be hot added after boot
			if system memory of hypervisor is not sufficient.

	mem=nn[KMG]@ss[KMG]
			[ARM,MIPS,EARLY] - override the memory layout
			reported by firmware.
			Define a memory region of size nn[KMG] starting at
			ss[KMG].
			Multiple different regions can be specified with
			multiple mem= parameters on the command line.

	mem=nopentium	[BUGS=X86-32] Disable usage of 4MB pages for kernel
			memory.

	memblock=debug	[KNL,EARLY] Enable memblock debug messages.

	memchunk=nn[KMG]
			[KNL,SH] Allow user to override the default size for
			per-device physically contiguous DMA buffers.

	memhp_default_state=online/offline/online_kernel/online_movable
			[KNL] Set the initial state for the memory hotplug
			onlining policy. If not specified, the default value is
			set according to the
			CONFIG_MHP_DEFAULT_ONLINE_TYPE kernel config
			options.
			See Documentation/admin-guide/mm/memory-hotplug.rst.

	memmap=exactmap	[KNL,X86,EARLY] Enable setting of an exact
			E820 memory map, as specified by the user.
			Such memmap=exactmap lines can be constructed based on
			BIOS output or other requirements. See the memmap=nn@ss
			option description.

	memmap=nn[KMG]@ss[KMG]
			[KNL, X86,MIPS,XTENSA,EARLY] Force usage of a specific region of memory.
			Region of memory to be used is from ss to ss+nn.
			If @ss[KMG] is omitted, it is equivalent to mem=nn[KMG],
			which limits max address to nn[KMG].
			Multiple different regions can be specified,
			comma delimited.
			Example:
				memmap=100M@2G,100M#3G,1G!1024G

	memmap=nn[KMG]#ss[KMG]
			[KNL,ACPI,EARLY] Mark specific memory as ACPI data.
			Region of memory to be marked is from ss to ss+nn.

	memmap=nn[KMG]$ss[KMG]
			[KNL,ACPI,EARLY] Mark specific memory as reserved.
			Region of memory to be reserved is from ss to ss+nn.
			Example: Exclude memory from 0x18690000-0x1869ffff
			         memmap=64K$0x18690000
			         or
			         memmap=0x10000$0x18690000
			Some bootloaders may need an escape character before '$',
			like Grub2, otherwise '$' and the following number
			will be eaten.

	memmap=nn[KMG]!ss[KMG,EARLY]
			[KNL,X86] Mark specific memory as protected.
			Region of memory to be used, from ss to ss+nn.
			The memory region may be marked as e820 type 12 (0xc)
			and is NVDIMM or ADR memory.

	memmap=<size>%<offset>-<oldtype>+<newtype>
			[KNL,ACPI,EARLY] Convert memory within the specified region
			from <oldtype> to <newtype>. If "-<oldtype>" is left
			out, the whole region will be marked as <newtype>,
			even if previously unavailable. If "+<newtype>" is left
			out, matching memory will be removed. Types are
			specified as e820 types, e.g., 1 = RAM, 2 = reserved,
			3 = ACPI, 12 = PRAM.

	memory_corruption_check=0/1 [X86,EARLY]
			Some BIOSes seem to corrupt the first 64k of
			memory when doing things like suspend/resume.
			Setting this option will scan the memory
			looking for corruption.  Enabling this will
			both detect corruption and prevent the kernel
			from using the memory being corrupted.
			However, it's intended as a diagnostic tool; if
			repeatable BIOS-originated corruption always
			affects the same memory, you can use memmap=
			to prevent the kernel from using that memory.

	memory_corruption_check_size=size [X86,EARLY]
			By default it checks for corruption in the low
			64k, making this memory unavailable for normal
			use.  Use this parameter to scan for
			corruption in more or less memory.

	memory_corruption_check_period=seconds [X86,EARLY]
			By default it checks for corruption every 60
			seconds.  Use this parameter to check at some
			other rate.  0 disables periodic checking.

	memory_hotplug.memmap_on_memory
			[KNL,X86,ARM] Boolean flag to enable this feature.
			Format: {on | off (default)}
			When enabled, runtime hotplugged memory will
			allocate its internal metadata (struct pages,
			those vmemmap pages cannot be optimized even
			if hugetlb_free_vmemmap is enabled) from the
			hotadded memory which will allow to hotadd a
			lot of memory without requiring additional
			memory to do so.
			This feature is disabled by default because it
			has some implication on large (e.g. GB)
			allocations in some configurations (e.g. small
			memory blocks).
			The state of the flag can be read in
			/sys/module/memory_hotplug/parameters/memmap_on_memory.
			Note that even when enabled, there are a few cases where
			the feature is not effective.

	memtest=	[KNL,X86,ARM,M68K,PPC,RISCV,EARLY] Enable memtest
			Format: <integer>
			default : 0 <disable>
			Specifies the number of memtest passes to be
			performed. Each pass selects another test
			pattern from a given set of patterns. Memtest
			fills the memory with this pattern, validates
			memory contents and reserves bad memory
			regions that are detected.

	mem_encrypt=	[X86-64] AMD Secure Memory Encryption (SME) control
			Valid arguments: on, off
			Default: off
			mem_encrypt=on:		Activate SME
			mem_encrypt=off:	Do not activate SME

			Refer to Documentation/virt/kvm/x86/amd-memory-encryption.rst
			for details on when memory encryption can be activated.

	mem_sleep_default=	[SUSPEND] Default system suspend mode:
			s2idle  - Suspend-To-Idle
			shallow - Power-On Suspend or equivalent (if supported)
			deep    - Suspend-To-RAM or equivalent (if supported)
			See Documentation/admin-guide/pm/sleep-states.rst.

	mfgptfix	[X86-32] Fix MFGPT timers on AMD Geode platforms when
			the BIOS has incorrectly applied a workaround. TinyBIOS
			version 0.98 is known to be affected, 0.99 fixes the
			problem by letting the user disable the workaround.

	mga=		[HW,DRM]

	microcode=      [X86] Control the behavior of the microcode loader.
	                Available options, comma separated:

			base_rev=X - with <X> with format: <u32>
			Set the base microcode revision of each thread when in
			debug mode.

			dis_ucode_ldr: disable the microcode loader

			force_minrev:
			Enable or disable the microcode minimal revision
			enforcement for the runtime microcode loader.

	mini2440=	[ARM,HW,KNL]
			Format:[0..2][b][c][t]
			Default: "0tb"
			MINI2440 configuration specification:
			0 - The attached screen is the 3.5" TFT
			1 - The attached screen is the 7" TFT
			2 - The VGA Shield is attached (1024x768)
			Leaving out the screen size parameter will not load
			the TFT driver, and the framebuffer will be left
			unconfigured.
			b - Enable backlight. The TFT backlight pin will be
			linked to the kernel VESA blanking code and a GPIO
			LED. This parameter is not necessary when using the
			VGA shield.
			c - Enable the s3c camera interface.
			t - Reserved for enabling touchscreen support. The
			touchscreen support is not enabled in the mainstream
			kernel as of 2.6.30, a preliminary port can be found
			in the "bleeding edge" mini2440 support kernel at
			https://repo.or.cz/w/linux-2.6/mini2440.git

	mitigations=
			[X86,PPC,S390,ARM64,EARLY] Control optional mitigations for
			CPU vulnerabilities.  This is a set of curated,
			arch-independent options, each of which is an
			aggregation of existing arch-specific options.

			Note, "mitigations" is supported if and only if the
			kernel was built with CPU_MITIGATIONS=y.

			off
				Disable all optional CPU mitigations.  This
				improves system performance, but it may also
				expose users to several CPU vulnerabilities.
				Equivalent to: if nokaslr then kpti=0 [ARM64]
					       gather_data_sampling=off [X86]
					       indirect_target_selection=off [X86]
					       kvm.nx_huge_pages=off [X86]
					       l1tf=off [X86]
					       mds=off [X86]
					       mmio_stale_data=off [X86]
					       no_entry_flush [PPC]
					       no_uaccess_flush [PPC]
					       nobp=0 [S390]
					       nopti [X86,PPC]
					       nospectre_bhb [ARM64]
					       nospectre_v1 [X86,PPC]
					       nospectre_v2 [X86,PPC,S390,ARM64]
					       reg_file_data_sampling=off [X86]
					       retbleed=off [X86]
					       spec_rstack_overflow=off [X86]
					       spec_store_bypass_disable=off [X86,PPC]
					       spectre_bhi=off [X86]
					       spectre_v2_user=off [X86]
					       srbds=off [X86,INTEL]
					       ssbd=force-off [ARM64]
					       tsx_async_abort=off [X86]
					       vmscape=off [X86]

				Exceptions:
					       This does not have any effect on
					       kvm.nx_huge_pages when
					       kvm.nx_huge_pages=force.

			auto (default)
				Mitigate all CPU vulnerabilities, but leave SMT
				enabled, even if it's vulnerable.  This is for
				users who don't want to be surprised by SMT
				getting disabled across kernel upgrades, or who
				have other ways of avoiding SMT-based attacks.
				Equivalent to: (default behavior)

			auto,nosmt
				Mitigate all CPU vulnerabilities, disabling SMT
				if needed.  This is for users who always want to
				be fully mitigated, even if it means losing SMT.
				Equivalent to: l1tf=flush,nosmt [X86]
					       mds=full,nosmt [X86]
					       tsx_async_abort=full,nosmt [X86]
					       mmio_stale_data=full,nosmt [X86]
					       retbleed=auto,nosmt [X86]

			[X86] After one of the above options, additionally
			supports attack-vector based controls as documented in
			Documentation/admin-guide/hw-vuln/attack_vector_controls.rst

	mminit_loglevel=
			[KNL,EARLY] When CONFIG_DEBUG_MEMORY_INIT is set, this
			parameter allows control of the logging verbosity for
			the additional memory initialisation checks. A value
			of 0 disables mminit logging and a level of 4 will
			log everything. Information is printed at KERN_DEBUG
			so loglevel=8 may also need to be specified.

	mmio_stale_data=
			[X86,INTEL,EARLY] Control mitigation for the Processor
			MMIO Stale Data vulnerabilities.

			Processor MMIO Stale Data is a class of
			vulnerabilities that may expose data after an MMIO
			operation. Exposed data could originate or end in
			the same CPU buffers as affected by MDS and TAA.
			Therefore, similar to MDS and TAA, the mitigation
			is to clear the affected CPU buffers.

			This parameter controls the mitigation. The
			options are:

			full       - Enable mitigation on vulnerable CPUs

			full,nosmt - Enable mitigation and disable SMT on
				     vulnerable CPUs.

			off        - Unconditionally disable mitigation

			On MDS or TAA affected machines,
			mmio_stale_data=off can be prevented by an active
			MDS or TAA mitigation as these vulnerabilities are
			mitigated with the same mechanism so in order to
			disable this mitigation, you need to specify
			mds=off and tsx_async_abort=off too.

			Not specifying this option is equivalent to
			mmio_stale_data=full.

			For details see:
			Documentation/admin-guide/hw-vuln/processor_mmio_stale_data.rst

	<module>.async_probe[=<bool>] [KNL]
			If no <bool> value is specified or if the value
			specified is not a valid <bool>, enable asynchronous
			probe on this module.  Otherwise, enable/disable
			asynchronous probe on this module as indicated by the
			<bool> value. See also: module.async_probe

	module.async_probe=<bool>
			[KNL] When set to true, modules will use async probing
			by default. To enable/disable async probing for a
			specific module, use the module specific control that
			is documented under <module>.async_probe. When both
			module.async_probe and <module>.async_probe are
			specified, <module>.async_probe takes precedence for
			the specific module.

	module.enable_dups_trace
			[KNL] When CONFIG_MODULE_DEBUG_AUTOLOAD_DUPS is set,
			this means that duplicate request_module() calls will
			trigger a WARN_ON() instead of a pr_warn(). Note that
			if MODULE_DEBUG_AUTOLOAD_DUPS_TRACE is set, WARN_ON()s
			will always be issued and this option does nothing.
	module.sig_enforce
			[KNL] When CONFIG_MODULE_SIG is set, this means that
			modules without (valid) signatures will fail to load.
			Note that if CONFIG_MODULE_SIG_FORCE is set, that
			is always true, so this option does nothing.

	module_blacklist=  [KNL] Do not load a comma-separated list of
			modules.  Useful for debugging problem modules.

	mousedev.tap_time=
			[MOUSE] Maximum time between finger touching and
			leaving touchpad surface for touch to be considered
			a tap and be reported as a left button click (for
			touchpads working in absolute mode only).
			Format: <msecs>
	mousedev.xres=	[MOUSE] Horizontal screen resolution, used for devices
			reporting absolute coordinates, such as tablets
	mousedev.yres=	[MOUSE] Vertical screen resolution, used for devices
			reporting absolute coordinates, such as tablets

	movablecore=	[KNL,X86,PPC,EARLY]
			Format: nn[KMGTPE] | nn%
			This parameter is the complement to kernelcore=, it
			specifies the amount of memory used for migratable
			allocations.  If both kernelcore and movablecore is
			specified, then kernelcore will be at *least* the
			specified value but may be more.  If movablecore on its
			own is specified, the administrator must be careful
			that the amount of memory usable for all allocations
			is not too small.

	movable_node	[KNL,EARLY] Boot-time switch to make hotplugable memory
			NUMA nodes to be movable. This means that the memory
			of such nodes will be usable only for movable
			allocations which rules out almost all kernel
			allocations. Use with caution!

	MTD_Partition=	[MTD]
			Format: <name>,<region-number>,<size>,<offset>

	MTD_Region=	[MTD] Format:
			<name>,<region-number>[,<base>,<size>,<buswidth>,<altbuswidth>]

	mtdparts=	[MTD]
			See drivers/mtd/parsers/cmdlinepart.c

	mtouchusb.raw_coordinates=
			[HW] Make the MicroTouch USB driver use raw coordinates
			('y', default) or cooked coordinates ('n')

	mtrr=debug	[X86,EARLY]
			Enable printing debug information related to MTRR
			registers at boot time.

	mtrr_chunk_size=nn[KMG,X86,EARLY]
			used for mtrr cleanup. It is largest continuous chunk
			that could hold holes aka. UC entries.

	mtrr_gran_size=nn[KMG,X86,EARLY]
			Used for mtrr cleanup. It is granularity of mtrr block.
			Default is 1.
			Large value could prevent small alignment from
			using up MTRRs.

	mtrr_spare_reg_nr=n [X86,EARLY]
			Format: <integer>
			Range: 0,7 : spare reg number
			Default : 1
			Used for mtrr cleanup. It is spare mtrr entries number.
			Set to 2 or more if your graphical card needs more.

	multitce=off	[PPC]  This parameter disables the use of the pSeries
			firmware feature for updating multiple TCE entries
			at a time.

	n2=		[NET] SDL Inc. RISCom/N2 synchronous serial card

	netdev=		[NET] Network devices parameters
			Format: <irq>,<io>,<mem_start>,<mem_end>,<name>
			Note that mem_start is often overloaded to mean
			something different and driver-specific.
			This usage is only documented in each driver source
			file if at all.

	netpoll.carrier_timeout=
			[NET] Specifies amount of time (in seconds) that
			netpoll should wait for a carrier. By default netpoll
			waits 4 seconds.

	nf_conntrack.acct=
			[NETFILTER] Enable connection tracking flow accounting
			0 to disable accounting
			1 to enable accounting
			Default value is 0.

	nfs.cache_getent=
			[NFS] sets the pathname to the program which is used
			to update the NFS client cache entries.

	nfs.cache_getent_timeout=
			[NFS] sets the timeout after which an attempt to
			update a cache entry is deemed to have failed.

	nfs.callback_nr_threads=
			[NFSv4] set the total number of threads that the
			NFS client will assign to service NFSv4 callback
			requests.

	nfs.callback_tcpport=
			[NFS] set the TCP port on which the NFSv4 callback
			channel should listen.

	nfs.delay_retrans=
			[NFS] specifies the number of times the NFSv4 client
			retries the request before returning an EAGAIN error,
			after a reply of NFS4ERR_DELAY from the server.
			Only applies if the softerr mount option is enabled,
			and the specified value is >= 0.

	nfs.enable_ino64=
			[NFS] enable 64-bit inode numbers.
			If zero, the NFS client will fake up a 32-bit inode
			number for the readdir() and stat() syscalls instead
			of returning the full 64-bit number.
			The default is to return 64-bit inode numbers.

	nfs.idmap_cache_timeout=
			[NFS] set the maximum lifetime for idmapper cache
			entries.

	nfs.max_session_cb_slots=
			[NFSv4.1] Sets the maximum number of session
			slots the client will assign to the callback
			channel. This determines the maximum number of
			callbacks the client will process in parallel for
			a particular server.

	nfs.max_session_slots=
			[NFSv4.1] Sets the maximum number of session slots
			the client will attempt to negotiate with the server.
			This limits the number of simultaneous RPC requests
			that the client can send to the NFSv4.1 server.
			Note that there is little point in setting this
			value higher than the max_tcp_slot_table_limit.

	nfs.nfs4_disable_idmapping=
			[NFSv4] When set to the default of '1', this option
			ensures that both the RPC level authentication
			scheme and the NFS level operations agree to use
			numeric uids/gids if the mount is using the
			'sec=sys' security flavour. In effect it is
			disabling idmapping, which can make migration from
			legacy NFSv2/v3 systems to NFSv4 easier.
			Servers that do not support this mode of operation
			will be autodetected by the client, and it will fall
			back to using the idmapper.
			To turn off this behaviour, set the value to '0'.

	nfs.nfs4_unique_id=
			[NFS4] Specify an additional fixed unique ident-
			ification string that NFSv4 clients can insert into
			their nfs_client_id4 string.  This is typically a
			UUID that is generated at system install time.

	nfs.recover_lost_locks=
			[NFSv4] Attempt to recover locks that were lost due
			to a lease timeout on the server. Please note that
			doing this risks data corruption, since there are
			no guarantees that the file will remain unchanged
			after the locks are lost.
			If you want to enable the kernel legacy behaviour of
			attempting to recover these locks, then set this
			parameter to '1'.
			The default parameter value of '0' causes the kernel
			not to attempt recovery of lost locks.

	nfs.send_implementation_id=
			[NFSv4.1] Send client implementation identification
			information in exchange_id requests.
			If zero, no implementation identification information
			will be sent.
			The default is to send the implementation identification
			information.

	nfs4.layoutstats_timer=
			[NFSv4.2] Change the rate at which the kernel sends
			layoutstats to the pNFS metadata server.

			Setting this to value to 0 causes the kernel to use
			whatever value is the default set by the layout
			driver. A non-zero value sets the minimum interval
			in seconds between layoutstats transmissions.

	nfsd.inter_copy_offload_enable=
			[NFSv4.2] When set to 1, the server will support
			server-to-server copies for which this server is
			the destination of the copy.

	nfsd.nfs4_disable_idmapping=
			[NFSv4] When set to the default of '1', the NFSv4
			server will return only numeric uids and gids to
			clients using auth_sys, and will accept numeric uids
			and gids from such clients.  This is intended to ease
			migration from NFSv2/v3.

	nfsd.nfsd4_ssc_umount_timeout=
			[NFSv4.2] When used as the destination of a
			server-to-server copy, knfsd temporarily mounts
			the source server.  It caches the mount in case
			it will be needed again, and discards it if not
			used for the number of milliseconds specified by
			this parameter.

	nfsaddrs=	[NFS] Deprecated.  Use ip= instead.
			See Documentation/admin-guide/nfs/nfsroot.rst.

	nfsroot=	[NFS] nfs root filesystem for disk-less boxes.
			See Documentation/admin-guide/nfs/nfsroot.rst.

	nfsrootdebug	[NFS] enable nfsroot debugging messages.
			See Documentation/admin-guide/nfs/nfsroot.rst.

	nmi_backtrace.backtrace_idle [KNL]
			Dump stacks even of idle CPUs in response to an
			NMI stack-backtrace request.

	nmi_debug=	[KNL,SH] Specify one or more actions to take
			when a NMI is triggered.
			Format: [state][,regs][,debounce][,die]

	nmi_watchdog=	[KNL,BUGS=X86] Debugging features for SMP kernels
			Format: [panic,][nopanic,][rNNN,][num]
			Valid num: 0 or 1
			0 - turn hardlockup detector in nmi_watchdog off
			1 - turn hardlockup detector in nmi_watchdog on
			rNNN - configure the watchdog with raw perf event 0xNNN

			When panic is specified, panic when an NMI watchdog
			timeout occurs (or 'nopanic' to not panic on an NMI
			watchdog, if CONFIG_BOOTPARAM_HARDLOCKUP_PANIC is set)
			To disable both hard and soft lockup detectors,
			please see 'nowatchdog'.
			This is useful when you use a panic=... timeout and
			need the box quickly up again.

			These settings can be accessed at runtime via
			the nmi_watchdog and hardlockup_panic sysctls.

	no387		[BUGS=X86-32] Tells the kernel to use the 387 maths
			emulation library even if a 387 maths coprocessor
			is present.

	no4lvl		[RISCV,EARLY] Disable 4-level and 5-level paging modes.
			Forces kernel to use 3-level paging instead.

	no5lvl		[X86-64,RISCV,EARLY] Disable 5-level paging mode. Forces
			kernel to use 4-level paging instead.

	noalign		[KNL,ARM]

	noapic		[SMP,APIC,EARLY] Tells the kernel to not make use of any
			IOAPICs that may be present in the system.

	noapictimer	[APIC,X86] Don't set up the APIC timer

	noautogroup	Disable scheduler automatic task group creation.

	nocache		[ARM,EARLY]

	no_console_suspend
			[HW] Never suspend the console
			Disable suspending of consoles during suspend and
			hibernate operations.  Once disabled, debugging
			messages can reach various consoles while the rest
			of the system is being put to sleep (ie, while
			debugging driver suspend/resume hooks).  This may
			not work reliably with all consoles, but is known
			to work with serial and VGA consoles.
			To facilitate more flexible debugging, we also add
			console_suspend, a printk module parameter to control
			it. Users could use console_suspend (usually
			/sys/module/printk/parameters/console_suspend) to
			turn on/off it dynamically.

	no_debug_objects
			[KNL,EARLY] Disable object debugging

	nodsp		[SH] Disable hardware DSP at boot time.

	noefi		[EFI,EARLY] Disable EFI runtime services support.

	no_entry_flush  [PPC,EARLY] Don't flush the L1-D cache when entering the kernel.

	noexec32	[X86-64]
			This affects only 32-bit executables.
			noexec32=on: enable non-executable mappings (default)
				read doesn't imply executable mappings
			noexec32=off: disable non-executable mappings
				read implies executable mappings

	no_file_caps	Tells the kernel not to honor file capabilities.  The
			only way then for a file to be executed with privilege
			is to be setuid root or executed by root.

	nofpu		[MIPS,SH] Disable hardware FPU at boot time.

	nofsgsbase	[X86] Disables FSGSBASE instructions.

	nofxsr		[BUGS=X86-32] Disables x86 floating point extended
			register save and restore. The kernel will only save
			legacy floating-point registers on task switch.

	nogbpages	[X86] Do not use GB pages for kernel direct mappings.

	no_hash_pointers
			[KNL,EARLY]
			Alias for "hash_pointers=never".

	nohibernate	[HIBERNATION] Disable hibernation and resume.

	nohlt		[ARM,ARM64,MICROBLAZE,MIPS,PPC,RISCV,SH] Forces the kernel to
			busy wait in do_idle() and not use the arch_cpu_idle()
			implementation; requires CONFIG_GENERIC_IDLE_POLL_SETUP
			to be effective. This is useful on platforms where the
			sleep(SH) or wfi(ARM,ARM64) instructions do not work
			correctly or when doing power measurements to evaluate
			the impact of the sleep instructions. This is also
			useful when using JTAG debugger.

	nohpet		[X86] Don't use the HPET timer.

	nohugeiomap	[KNL,X86,PPC,ARM64,EARLY] Disable kernel huge I/O mappings.

	nohugevmalloc	[KNL,X86,PPC,ARM64,EARLY] Disable kernel huge vmalloc mappings.

	nohz=		[KNL] Boottime enable/disable dynamic ticks
			Valid arguments: on, off
			Default: on

	nohz_full=	[KNL,BOOT,SMP,ISOL]
			The argument is a cpu list, as described above.
			In kernels built with CONFIG_NO_HZ_FULL=y, set
			the specified list of CPUs whose tick will be stopped
			whenever possible. The boot CPU will be forced outside
			the range to maintain the timekeeping.  Any CPUs
			in this list will have their RCU callbacks offloaded,
			just as if they had also been called out in the
			rcu_nocbs= boot parameter.

			Note that this argument takes precedence over
			the CONFIG_RCU_NOCB_CPU_DEFAULT_ALL option.

	noinitrd	[RAM] Tells the kernel not to load any configured
			initial RAM disk.

	nointremap	[X86-64,Intel-IOMMU,EARLY] Do not enable interrupt
			remapping.
			[Deprecated - use intremap=off]

	noinvpcid	[X86,EARLY] Disable the INVPCID cpu feature.

	noiotrap	[SH] Disables trapped I/O port accesses.

	noirqdebug	[X86-32] Disables the code which attempts to detect and
			disable unhandled interrupt sources.

	noisapnp	[ISAPNP] Disables ISA PnP code.

	nokaslr		[KNL,EARLY]
			When CONFIG_RANDOMIZE_BASE is set, this disables
			kernel and module base offset ASLR (Address Space
			Layout Randomization).

	no-kvmapf	[X86,KVM,EARLY] Disable paravirtualized asynchronous page
			fault handling.

	no-kvmclock	[X86,KVM,EARLY] Disable paravirtualized KVM clock driver

	nolapic		[X86-32,APIC,EARLY] Do not enable or use the local APIC.

	nolapic_timer	[X86-32,APIC,EARLY] Do not use the local APIC timer.

	nomce		[X86-32] Disable Machine Check Exception

	nomfgpt		[X86-32] Disable Multi-Function General Purpose
			Timer usage (for AMD Geode machines).

	nomodeset	Disable kernel modesetting. Most systems' firmware
			sets up a display mode and provides framebuffer memory
			for output. With nomodeset, DRM and fbdev drivers will
			not load if they could possibly displace the pre-
			initialized output. Only the system framebuffer will
			be available for use. The respective drivers will not
			perform display-mode changes or accelerated rendering.

			Useful as error fallback, or for testing and debugging.

	nomodule	Disable module load

	nonmi_ipi	[X86] Disable using NMI IPIs during panic/reboot to
			shutdown the other cpus.  Instead use the REBOOT_VECTOR
			irq.

	nopat		[X86,EARLY] Disable PAT (page attribute table extension of
			pagetables) support.

	nopcid		[X86-64,EARLY] Disable the PCID cpu feature.

	nopku		[X86] Disable Memory Protection Keys CPU feature found
			in some Intel CPUs.

	nopti		[X86-64,EARLY]
			Equivalent to pti=off

	nopv=		[X86,XEN,KVM,HYPER_V,VMWARE,EARLY]
			Disables the PV optimizations forcing the guest to run
			as generic guest with no PV drivers. Currently support
			XEN HVM, KVM, HYPER_V and VMWARE guest.

	nopvspin	[X86,XEN,KVM,EARLY]
			Disables the qspinlock slow path using PV optimizations
			which allow the hypervisor to 'idle' the guest on lock
			contention.

	norandmaps	Don't use address space randomization.  Equivalent to
			echo 0 > /proc/sys/kernel/randomize_va_space

	noreplace-smp	[X86-32,SMP] Don't replace SMP instructions
			with UP alternatives

	noresume	[SWSUSP] Disables resume and restores original swap
			space.

	no-scroll	[VGA] Disables scrollback.
			This is required for the Braillex ib80-piezo Braille
			reader made by F.H. Papenmeier (Germany).

	nosgx		[X86-64,SGX,EARLY] Disables Intel SGX kernel support.

	nosmap		[PPC,EARLY]
			Disable SMAP (Supervisor Mode Access Prevention)
			even if it is supported by processor.

	nosmep		[PPC64s,EARLY]
			Disable SMEP (Supervisor Mode Execution Prevention)
			even if it is supported by processor.

	nosmp		[SMP,EARLY] Tells an SMP kernel to act as a UP kernel,
			and disable the IO APIC.  legacy for "maxcpus=0".

	nosmt		[KNL,MIPS,PPC,EARLY] Disable symmetric multithreading (SMT).
			Equivalent to smt=1.

			[KNL,X86,PPC,S390] Disable symmetric multithreading (SMT).
			nosmt=force: Force disable SMT, cannot be undone
				     via the sysfs control file.

	nosoftlockup	[KNL] Disable the soft-lockup detector.

	nospec_store_bypass_disable
			[HW,EARLY] Disable all mitigations for the Speculative
			Store Bypass vulnerability

	nospectre_bhb	[ARM64,EARLY] Disable all mitigations for Spectre-BHB (branch
			history injection) vulnerability. System may allow data leaks
			with this option.

	nospectre_v1	[X86,PPC,EARLY] Disable mitigations for Spectre Variant 1
			(bounds check bypass). With this option data leaks are
			possible in the system.

	nospectre_v2	[X86,PPC_E500,ARM64,EARLY] Disable all mitigations
			for the Spectre variant 2 (indirect branch
			prediction) vulnerability. System may allow data
			leaks with this option.

	no-steal-acc	[X86,PV_OPS,ARM64,PPC/PSERIES,RISCV,LOONGARCH,EARLY]
			Disable paravirtualized steal time accounting. steal time
			is computed, but won't influence scheduler behaviour

	nosync		[HW,M68K] Disables sync negotiation for all devices.

	no_timer_check	[X86,APIC] Disables the code which tests for broken
			timer IRQ sources, i.e., the IO-APIC timer. This can
			work around problems with incorrect timer
			initialization on some boards.

	no_uaccess_flush
	                [PPC,EARLY] Don't flush the L1-D cache after accessing user data.

	novmcoredd	[KNL,KDUMP]
			Disable device dump. Device dump allows drivers to
			append dump data to vmcore so you can collect driver
			specified debug info.  Drivers can append the data
			without any limit and this data is stored in memory,
			so this may cause significant memory stress.  Disabling
			device dump can help save memory but the driver debug
			data will be no longer available.  This parameter
			is only available when CONFIG_PROC_VMCORE_DEVICE_DUMP
			is set.

	no-vmw-sched-clock
			[X86,PV_OPS,EARLY] Disable paravirtualized VMware
			scheduler clock and use the default one.

	nowatchdog	[KNL] Disable both lockup detectors, i.e.
			soft-lockup and NMI watchdog (hard-lockup).

	nowb		[ARM,EARLY]

	nox2apic	[X86-64,APIC,EARLY] Do not enable x2APIC mode.

			NOTE: this parameter will be ignored on systems with the
			LEGACY_XAPIC_DISABLED bit set in the
			IA32_XAPIC_DISABLE_STATUS MSR.

	noxsave		[BUGS=X86] Disables x86 extended register state save
			and restore using xsave. The kernel will fallback to
			enabling legacy floating-point and sse state.

	noxsaveopt	[X86] Disables xsaveopt used in saving x86 extended
			register states. The kernel will fall back to use
			xsave to save the states. By using this parameter,
			performance of saving the states is degraded because
			xsave doesn't support modified optimization while
			xsaveopt supports it on xsaveopt enabled systems.

	noxsaves	[X86] Disables xsaves and xrstors used in saving and
			restoring x86 extended register state in compacted
			form of xsave area. The kernel will fall back to use
			xsaveopt and xrstor to save and restore the states
			in standard form of xsave area. By using this
			parameter, xsave area per process might occupy more
			memory on xsaves enabled systems.

	nr_cpus=	[SMP,EARLY] Maximum number of processors that an SMP kernel
			could support.  nr_cpus=n : n >= 1 limits the kernel to
			support 'n' processors. It could be larger than the
			number of already plugged CPU during bootup, later in
			runtime you can physically add extra cpu until it reaches
			n. So during boot up some boot time memory for per-cpu
			variables need be pre-allocated for later physical cpu
			hot plugging.

	nr_uarts=	[SERIAL] maximum number of UARTs to be registered.

	numa=off 	[KNL, ARM64, PPC, RISCV, SPARC, X86, EARLY]
			Disable NUMA, Only set up a single NUMA node
			spanning all memory.

	numa=fake=<size>[MG]
			[KNL, ARM64, RISCV, X86, EARLY]
			If given as a memory unit, fills all system RAM with
			nodes of size interleaved over physical nodes.

	numa=fake=<N>
			[KNL, ARM64, RISCV, X86, EARLY]
			If given as an integer, fills all system RAM with N
			fake nodes interleaved over physical nodes.

	numa=fake=<N>U
			[KNL, ARM64, RISCV, X86, EARLY]
			If given as an integer followed by 'U', it will
			divide each physical node into N emulated nodes.

	numa=noacpi	[X86] Don't parse the SRAT table for NUMA setup

	numa=nohmat	[X86] Don't parse the HMAT table for NUMA setup, or
			soft-reserved memory partitioning.

	numa_balancing=	[KNL,ARM64,PPC,RISCV,S390,X86] Enable or disable automatic
			NUMA balancing.
			Allowed values are enable and disable

	numa_zonelist_order= [KNL, BOOT] Select zonelist order for NUMA.
			'node', 'default' can be specified
			This can be set from sysctl after boot.
			See Documentation/admin-guide/sysctl/vm.rst for details.

	ohci1394_dma=early	[HW,EARLY] enable debugging via the ohci1394 driver.
			See Documentation/core-api/debugging-via-ohci1394.rst for more
			info.

	olpc_ec_timeout= [OLPC] ms delay when issuing EC commands
			Rather than timing out after 20 ms if an EC
			command is not properly ACKed, override the length
			of the timeout.  We have interrupts disabled while
			waiting for the ACK, so if this is set too high
			interrupts *may* be lost!

	omap_mux=	[OMAP] Override bootloader pin multiplexing.
			Format: <mux_mode0.mode_name=value>...
			For example, to override I2C bus2:
			omap_mux=i2c2_scl.i2c2_scl=0x100,i2c2_sda.i2c2_sda=0x100

	onenand.bdry=	[HW,MTD] Flex-OneNAND Boundary Configuration

			Format: [die0_boundary][,die0_lock][,die1_boundary][,die1_lock]

			boundary - index of last SLC block on Flex-OneNAND.
				   The remaining blocks are configured as MLC blocks.
			lock	 - Configure if Flex-OneNAND boundary should be locked.
				   Once locked, the boundary cannot be changed.
				   1 indicates lock status, 0 indicates unlock status.

	oops=panic	[KNL,EARLY]
			Always panic on oopses. Default is to just kill the
			process, but there is a small probability of
			deadlocking the machine.
			This will also cause panics on machine check exceptions.
			Useful together with panic=30 to trigger a reboot.

	page_alloc.shuffle=
			[KNL] Boolean flag to control whether the page allocator
			should randomize its free lists. This parameter can be
			used to enable/disable page randomization. The state of
			the flag can be read from sysfs at:
			/sys/module/page_alloc/parameters/shuffle.
			This parameter is only available if CONFIG_SHUFFLE_PAGE_ALLOCATOR=y.

	page_owner=	[KNL,EARLY] Boot-time page_owner enabling option.
			Storage of the information about who allocated
			each page is disabled in default. With this switch,
			we can turn it on.
			on: enable the feature

	page_poison=	[KNL,EARLY] Boot-time parameter changing the state of
			poisoning on the buddy allocator, available with
			CONFIG_PAGE_POISONING=y.
			off: turn off poisoning (default)
			on: turn on poisoning

	page_reporting.page_reporting_order=
			[KNL] Minimal page reporting order
			Format: <integer>
			Adjust the minimal page reporting order. The page
			reporting is disabled when it exceeds MAX_PAGE_ORDER.

	panic=		[KNL] Kernel behaviour on panic: delay <timeout>
			timeout > 0: seconds before rebooting
			timeout = 0: wait forever
			timeout < 0: reboot immediately
			Format: <timeout>

	panic_on_taint=	[KNL,EARLY]
			Bitmask for conditionally calling panic() in add_taint()
			Format: <hex>[,nousertaint]
			Hexadecimal bitmask representing the set of TAINT flags
			that will cause the kernel to panic when add_taint() is
			called with any of the flags in this set.
			The optional switch "nousertaint" can be utilized to
			prevent userspace forced crashes by writing to sysctl
			/proc/sys/kernel/tainted any flagset matching with the
			bitmask set on panic_on_taint.
			See Documentation/admin-guide/tainted-kernels.rst for
			extra details on the taint flags that users can pick
			to compose the bitmask to assign to panic_on_taint.

	panic_on_warn=1	panic() instead of WARN().  Useful to cause kdump
			on a WARN().

	panic_print=	Bitmask for printing system info when panic happens.
			User can chose combination of the following bits:
			bit 0: print all tasks info
			bit 1: print system memory info
			bit 2: print timer info
			bit 3: print locks info if CONFIG_LOCKDEP is on
			bit 4: print ftrace buffer
			bit 5: replay all kernel messages on consoles at the end of panic
			bit 6: print all CPUs backtrace (if available in the arch)
			bit 7: print only tasks in uninterruptible (blocked) state
			*Be aware* that this option may print a _lot_ of lines,
			so there are risks of losing older messages in the log.
			Use this option carefully, maybe worth to setup a
			bigger log buffer with "log_buf_len" along with this.

	panic_sys_info= A comma separated list of extra information to be dumped
                        on panic.
                        Format: val[,val...]
                        Where @val can be any of the following:

                        tasks:          print all tasks info
                        mem:            print system memory info
			timers:         print timers info
                        locks:          print locks info if CONFIG_LOCKDEP is on
                        ftrace:         print ftrace buffer
                        all_bt:         print all CPUs backtrace (if available in the arch)
                        blocked_tasks:  print only tasks in uninterruptible (blocked) state

                        This is a human readable alternative to the 'panic_print' option.

	panic_console_replay
			When panic happens, replay all kernel messages on
			consoles at the end of panic.

	parkbd.port=	[HW] Parallel port number the keyboard adapter is
			connected to, default is 0.
			Format: <parport#>
	parkbd.mode=	[HW] Parallel port keyboard adapter mode of operation,
			0 for XT, 1 for AT (default is AT).
			Format: <mode>

	parport=	[HW,PPT] Specify parallel ports. 0 disables.
			Format: { 0 | auto | 0xBBB[,IRQ[,DMA]] }
			Use 'auto' to force the driver to use any
			IRQ/DMA settings detected (the default is to
			ignore detected IRQ/DMA settings because of
			possible conflicts). You can specify the base
			address, IRQ, and DMA settings; IRQ and DMA
			should be numbers, or 'auto' (for using detected
			settings on that particular port), or 'nofifo'
			(to avoid using a FIFO even if it is detected).
			Parallel ports are assigned in the order they
			are specified on the command line, starting
			with parport0.

	parport_init_mode=	[HW,PPT]
			Configure VIA parallel port to operate in
			a specific mode. This is necessary on Pegasos
			computer where firmware has no options for setting
			up parallel port mode and sets it to spp.
			Currently this function knows 686a and 8231 chips.
			Format: [spp|ps2|epp|ecp|ecpepp]

	pata_legacy.all=	[HW,LIBATA]
			Format: <int>
			Set to non-zero to probe primary and secondary ISA
			port ranges on PCI systems where no PCI PATA device
			has been found at either range.  Disabled by default.

	pata_legacy.autospeed=	[HW,LIBATA]
			Format: <int>
			Set to non-zero if a chip is present that snoops speed
			changes.  Disabled by default.

	pata_legacy.ht6560a=	[HW,LIBATA]
			Format: <int>
			Set to 1, 2, or 3 for HT 6560A on the primary channel,
			the secondary channel, or both channels respectively.
			Disabled by default.

	pata_legacy.ht6560b=	[HW,LIBATA]
			Format: <int>
			Set to 1, 2, or 3 for HT 6560B on the primary channel,
			the secondary channel, or both channels respectively.
			Disabled by default.

	pata_legacy.iordy_mask=	[HW,LIBATA]
			Format: <int>
			IORDY enable mask.  Set individual bits to allow IORDY
			for the respective channel.  Bit 0 is for the first
			legacy channel handled by this driver, bit 1 is for
			the second channel, and so on.  The sequence will often
			correspond to the primary legacy channel, the secondary
			legacy channel, and so on, but the handling of a PCI
			bus and the use of other driver options may interfere
			with the sequence.  By default IORDY is allowed across
			all channels.

	pata_legacy.opti82c46x=	[HW,LIBATA]
			Format: <int>
			Set to 1, 2, or 3 for Opti 82c611A on the primary
			channel, the secondary channel, or both channels
			respectively.  Disabled by default.

	pata_legacy.opti82c611a=	[HW,LIBATA]
			Format: <int>
			Set to 1, 2, or 3 for Opti 82c465MV on the primary
			channel, the secondary channel, or both channels
			respectively.  Disabled by default.

	pata_legacy.pio_mask=	[HW,LIBATA]
			Format: <int>
			PIO mode mask for autospeed devices.  Set individual
			bits to allow the use of the respective PIO modes.
			Bit 0 is for mode 0, bit 1 is for mode 1, and so on.
			All modes allowed by default.

	pata_legacy.probe_all=	[HW,LIBATA]
			Format: <int>
			Set to non-zero to probe tertiary and further ISA
			port ranges on PCI systems.  Disabled by default.

	pata_legacy.probe_mask=	[HW,LIBATA]
			Format: <int>
			Probe mask for legacy ISA PATA ports.  Depending on
			platform configuration and the use of other driver
			options up to 6 legacy ports are supported: 0x1f0,
			0x170, 0x1e8, 0x168, 0x1e0, 0x160, however probing
			of individual ports can be disabled by setting the
			corresponding bits in the mask to 1.  Bit 0 is for
			the first port in the list above (0x1f0), and so on.
			By default all supported ports are probed.

	pata_legacy.qdi=	[HW,LIBATA]
			Format: <int>
			Set to non-zero to probe QDI controllers.  By default
			set to 1 if CONFIG_PATA_QDI_MODULE, 0 otherwise.

	pata_legacy.winbond=	[HW,LIBATA]
			Format: <int>
			Set to non-zero to probe Winbond controllers.  Use
			the standard I/O port (0x130) if 1, otherwise the
			value given is the I/O port to use (typically 0x1b0).
			By default set to 1 if CONFIG_PATA_WINBOND_VLB_MODULE,
			0 otherwise.

	pata_platform.pio_mask=	[HW,LIBATA]
			Format: <int>
			Supported PIO mode mask.  Set individual bits to allow
			the use of the respective PIO modes.  Bit 0 is for
			mode 0, bit 1 is for mode 1, and so on.  Mode 0 only
			allowed by default.

	pause_on_oops=<int>
			Halt all CPUs after the first oops has been printed for
			the specified number of seconds.  This is to be used if
			your oopses keep scrolling off the screen.

	pcbit=		[HW,ISDN]

	pci=option[,option...]	[PCI,EARLY] various PCI subsystem options.

				Some options herein operate on a specific device
				or a set of devices (<pci_dev>). These are
				specified in one of the following formats:

				[<domain>:]<bus>:<dev>.<func>[/<dev>.<func>]*
				pci:<vendor>:<device>[:<subvendor>:<subdevice>]

				Note: the first format specifies a PCI
				bus/device/function address which may change
				if new hardware is inserted, if motherboard
				firmware changes, or due to changes caused
				by other kernel parameters. If the
				domain is left unspecified, it is
				taken to be zero. Optionally, a path
				to a device through multiple device/function
				addresses can be specified after the base
				address (this is more robust against
				renumbering issues).  The second format
				selects devices using IDs from the
				configuration space which may match multiple
				devices in the system.

		earlydump	dump PCI config space before the kernel
				changes anything
		off		[X86] don't probe for the PCI bus
		bios		[X86-32] force use of PCI BIOS, don't access
				the hardware directly. Use this if your machine
				has a non-standard PCI host bridge.
		nobios		[X86-32] disallow use of PCI BIOS, only direct
				hardware access methods are allowed. Use this
				if you experience crashes upon bootup and you
				suspect they are caused by the BIOS.
		conf1		[X86] Force use of PCI Configuration Access
				Mechanism 1 (config address in IO port 0xCF8,
				data in IO port 0xCFC, both 32-bit).
		conf2		[X86] Force use of PCI Configuration Access
				Mechanism 2 (IO port 0xCF8 is an 8-bit port for
				the function, IO port 0xCFA, also 8-bit, sets
				bus number. The config space is then accessed
				through ports 0xC000-0xCFFF).
				See http://wiki.osdev.org/PCI for more info
				on the configuration access mechanisms.
		noaer		[PCIE] If the PCIEAER kernel config parameter is
				enabled, this kernel boot option can be used to
				disable the use of PCIE advanced error reporting.
		nodomains	[PCI] Disable support for multiple PCI
				root domains (aka PCI segments, in ACPI-speak).
		nommconf	[X86] Disable use of MMCONFIG for PCI
				Configuration
		check_enable_amd_mmconf [X86] check for and enable
				properly configured MMIO access to PCI
				config space on AMD family 10h CPU
		nomsi		[MSI] If the PCI_MSI kernel config parameter is
				enabled, this kernel boot option can be used to
				disable the use of MSI interrupts system-wide.
		noioapicquirk	[APIC] Disable all boot interrupt quirks.
				Safety option to keep boot IRQs enabled. This
				should never be necessary.
		ioapicreroute	[APIC] Enable rerouting of boot IRQs to the
				primary IO-APIC for bridges that cannot disable
				boot IRQs. This fixes a source of spurious IRQs
				when the system masks IRQs.
		noioapicreroute	[APIC] Disable workaround that uses the
				boot IRQ equivalent of an IRQ that connects to
				a chipset where boot IRQs cannot be disabled.
				The opposite of ioapicreroute.
		biosirq		[X86-32] Use PCI BIOS calls to get the interrupt
				routing table. These calls are known to be buggy
				on several machines and they hang the machine
				when used, but on other computers it's the only
				way to get the interrupt routing table. Try
				this option if the kernel is unable to allocate
				IRQs or discover secondary PCI buses on your
				motherboard.
		rom		[X86] Assign address space to expansion ROMs.
				Use with caution as certain devices share
				address decoders between ROMs and other
				resources.
		norom		[X86] Do not assign address space to
				expansion ROMs that do not already have
				BIOS assigned address ranges.
		nobar		[X86] Do not assign address space to the
				BARs that weren't assigned by the BIOS.
		irqmask=0xMMMM	[X86] Set a bit mask of IRQs allowed to be
				assigned automatically to PCI devices. You can
				make the kernel exclude IRQs of your ISA cards
				this way.
		pirqaddr=0xAAAAA	[X86] Specify the physical address
				of the PIRQ table (normally generated
				by the BIOS) if it is outside the
				F0000h-100000h range.
		lastbus=N	[X86] Scan all buses thru bus #N. Can be
				useful if the kernel is unable to find your
				secondary buses and you want to tell it
				explicitly which ones they are.
		assign-busses	[X86] Always assign all PCI bus
				numbers ourselves, overriding
				whatever the firmware may have done.
		usepirqmask	[X86] Honor the possible IRQ mask stored
				in the BIOS $PIR table. This is needed on
				some systems with broken BIOSes, notably
				some HP Pavilion N5400 and Omnibook XE3
				notebooks. This will have no effect if ACPI
				IRQ routing is enabled.
		noacpi		[X86] Do not use ACPI for IRQ routing
				or for PCI scanning.
		use_crs		[X86] Use PCI host bridge window information
				from ACPI.  On BIOSes from 2008 or later, this
				is enabled by default.  If you need to use this,
				please report a bug.
		nocrs		[X86] Ignore PCI host bridge windows from ACPI.
				If you need to use this, please report a bug.
		use_e820	[X86] Use E820 reservations to exclude parts of
				PCI host bridge windows. This is a workaround
				for BIOS defects in host bridge _CRS methods.
				If you need to use this, please report a bug to
				<linux-pci@vger.kernel.org>.
		no_e820		[X86] Ignore E820 reservations for PCI host
				bridge windows. This is the default on modern
				hardware. If you need to use this, please report
				a bug to <linux-pci@vger.kernel.org>.
		routeirq	Do IRQ routing for all PCI devices.
				This is normally done in pci_enable_device(),
				so this option is a temporary workaround
				for broken drivers that don't call it.
		skip_isa_align	[X86] do not align io start addr, so can
				handle more pci cards
		noearly		[X86] Don't do any early type 1 scanning.
				This might help on some broken boards which
				machine check when some devices' config space
				is read. But various workarounds are disabled
				and some IOMMU drivers will not work.
		bfsort		Sort PCI devices into breadth-first order.
				This sorting is done to get a device
				order compatible with older (<= 2.4) kernels.
		nobfsort	Don't sort PCI devices into breadth-first order.
		pcie_bus_tune_off	Disable PCIe MPS (Max Payload Size)
				tuning and use the BIOS-configured MPS defaults.
		pcie_bus_safe	Set every device's MPS to the largest value
				supported by all devices below the root complex.
		pcie_bus_perf	Set device MPS to the largest allowable MPS
				based on its parent bus. Also set MRRS (Max
				Read Request Size) to the largest supported
				value (no larger than the MPS that the device
				or bus can support) for best performance.
		pcie_bus_peer2peer	Set every device's MPS to 128B, which
				every device is guaranteed to support. This
				configuration allows peer-to-peer DMA between
				any pair of devices, possibly at the cost of
				reduced performance.  This also guarantees
				that hot-added devices will work.
		cbiosize=nn[KMG]	The fixed amount of bus space which is
				reserved for the CardBus bridge's IO window.
				The default value is 256 bytes.
		cbmemsize=nn[KMG]	The fixed amount of bus space which is
				reserved for the CardBus bridge's memory
				window. The default value is 64 megabytes.
		resource_alignment=
				Format:
				[<order of align>@]<pci_dev>[; ...]
				Specifies alignment and device to reassign
				aligned memory resources. How to
				specify the device is described above.
				If <order of align> is not specified,
				PAGE_SIZE is used as alignment.
				A PCI-PCI bridge can be specified if resource
				windows need to be expanded.
				To specify the alignment for several
				instances of a device, the PCI vendor,
				device, subvendor, and subdevice may be
				specified, e.g., 12@pci:8086:9c22:103c:198f
				for 4096-byte alignment.
		ecrc=		Enable/disable PCIe ECRC (transaction layer
				end-to-end CRC checking). Only effective if
				OS has native AER control (either granted by
				ACPI _OSC or forced via "pcie_ports=native")
				bios: Use BIOS/firmware settings. This is the
				the default.
				off: Turn ECRC off
				on: Turn ECRC on.
		hpiosize=nn[KMG]	The fixed amount of bus space which is
				reserved for hotplug bridge's IO window.
				Default size is 256 bytes.
		hpmmiosize=nn[KMG]	The fixed amount of bus space which is
				reserved for hotplug bridge's MMIO window.
				Default size is 2 megabytes.
		hpmmioprefsize=nn[KMG]	The fixed amount of bus space which is
				reserved for hotplug bridge's MMIO_PREF window.
				Default size is 2 megabytes.
		hpmemsize=nn[KMG]	The fixed amount of bus space which is
				reserved for hotplug bridge's MMIO and
				MMIO_PREF window.
				Default size is 2 megabytes.
		hpbussize=nn	The minimum amount of additional bus numbers
				reserved for buses below a hotplug bridge.
				Default is 1.
		realloc=	Enable/disable reallocating PCI bridge resources
				if allocations done by BIOS are too small to
				accommodate resources required by all child
				devices.
				off: Turn realloc off
				on: Turn realloc on
		realloc		same as realloc=on
		noari		do not use PCIe ARI.
		noats		[PCIE, Intel-IOMMU, AMD-IOMMU]
				do not use PCIe ATS (and IOMMU device IOTLB).
		pcie_scan_all	Scan all possible PCIe devices.  Otherwise we
				only look for one device below a PCIe downstream
				port.
		big_root_window	Try to add a big 64bit memory window to the PCIe
				root complex on AMD CPUs. Some GFX hardware
				can resize a BAR to allow access to all VRAM.
				Adding the window is slightly risky (it may
				conflict with unreported devices), so this
				taints the kernel.
		disable_acs_redir=<pci_dev>[; ...]
				Specify one or more PCI devices (in the format
				specified above) separated by semicolons.
				Each device specified will have the PCI ACS
				redirect capabilities forced off which will
				allow P2P traffic between devices through
				bridges without forcing it upstream. Note:
				this removes isolation between devices and
				may put more devices in an IOMMU group.
		config_acs=
				Format:
				<ACS flags>@<pci_dev>[; ...]
				Specify one or more PCI devices (in the format
				specified above) optionally prepended with flags
				and separated by semicolons. The respective
				capabilities will be enabled, disabled or
				unchanged based on what is specified in
				flags.

				ACS Flags is defined as follows:
				  bit-0 : ACS Source Validation
				  bit-1 : ACS Translation Blocking
				  bit-2 : ACS P2P Request Redirect
				  bit-3 : ACS P2P Completion Redirect
				  bit-4 : ACS Upstream Forwarding
				  bit-5 : ACS P2P Egress Control
				  bit-6 : ACS Direct Translated P2P
				Each bit can be marked as:
				  '0' – force disabled
				  '1' – force enabled
				  'x' – unchanged
				For example,
				  pci=config_acs=10x@pci:0:0
				would configure all devices that support
				ACS to enable P2P Request Redirect, disable
				Translation Blocking, and leave Source
				Validation unchanged from whatever power-up
				or firmware set it to.

				Note: this may remove isolation between devices
				and may put more devices in an IOMMU group.
		force_floating	[S390] Force usage of floating interrupts.
		nomio		[S390] Do not use MIO instructions.
		norid		[S390] ignore the RID field and force use of
				one PCI domain per PCI function
		notph		[PCIE] If the PCIE_TPH kernel config parameter
				is enabled, this kernel boot option can be used
				to disable PCIe TLP Processing Hints support
				system-wide.

	pcie_aspm=	[PCIE] Forcibly enable or ignore PCIe Active State Power
			Management.
		off	Don't touch ASPM configuration at all.  Leave any
			configuration done by firmware unchanged.
		force	Enable ASPM even on devices that claim not to support it.
			WARNING: Forcing ASPM on may cause system lockups.

	pcie_ports=	[PCIE] PCIe port services handling:
		native	Use native PCIe services (PME, AER, DPC, PCIe hotplug)
			even if the platform doesn't give the OS permission to
			use them.  This may cause conflicts if the platform
			also tries to use these services.
		dpc-native	Use native PCIe service for DPC only.  May
				cause conflicts if firmware uses AER or DPC.
		compat	Disable native PCIe services (PME, AER, DPC, PCIe
			hotplug).

	pcie_port_pm=	[PCIE] PCIe port power management handling:
		off	Disable power management of all PCIe ports
		force	Forcibly enable power management of all PCIe ports

	pcie_pme=	[PCIE,PM] Native PCIe PME signaling options:
		nomsi	Do not use MSI for native PCIe PME signaling (this makes
			all PCIe root ports use INTx for all services).

	pcmv=		[HW,PCMCIA] BadgePAD 4

	pd_ignore_unused
			[PM]
			Keep all power-domains already enabled by bootloader on,
			even if no driver has claimed them. This is useful
			for debug and development, but should not be
			needed on a platform with proper driver support.

	pdcchassis=	[PARISC,HW] Disable/Enable PDC Chassis Status codes at
			boot time.
			Format: { 0 | 1 }
			See arch/parisc/kernel/pdc_chassis.c

	percpu_alloc=	[MM,EARLY]
			Select which percpu first chunk allocator to use.
			Currently supported values are "embed" and "page".
			Archs may support subset or none of the	selections.
			See comments in mm/percpu.c for details on each
			allocator.  This parameter is primarily	for debugging
			and performance comparison.

	pirq=		[SMP,APIC] Manual mp-table setup
			See Documentation/arch/x86/i386/IO-APIC.rst.

	plip=		[PPT,NET] Parallel port network link
			Format: { parport<nr> | timid | 0 }
			See also Documentation/admin-guide/parport.rst.

	pmtmr=		[X86] Manual setup of pmtmr I/O Port.
			Override pmtimer IOPort with a hex value.
			e.g. pmtmr=0x508

	pmu_override=	[PPC] Override the PMU.
			This option takes over the PMU facility, so it is no
			longer usable by perf. Setting this option starts the
			PMU counters by setting MMCR0 to 0 (the FC bit is
			cleared). If a number is given, then MMCR1 is set to
			that number, otherwise (e.g., 'pmu_override=on'), MMCR1
			remains 0.

	pm_async=	[PM]
			Format: off
			This parameter sets the initial value of the
			/sys/power/pm_async sysfs knob at boot time.
			If set to "off", disables asynchronous suspend and
			resume of devices during system-wide power transitions.
			This can be useful on platforms where device
			dependencies are not well-defined, or for debugging
			power management issues. Asynchronous operations are
			enabled by default.


	pm_debug_messages	[SUSPEND,KNL]
			Enable suspend/resume debug messages during boot up.

	pnp.debug=1	[PNP]
			Enable PNP debug messages (depends on the
			CONFIG_PNP_DEBUG_MESSAGES option).  Change at run-time
			via /sys/module/pnp/parameters/debug.  We always show
			current resource usage; turning this on also shows
			possible settings and some assignment information.

	pnpacpi=	[ACPI]
			{ off }

	pnpbios=	[ISAPNP]
			{ on | off | curr | res | no-curr | no-res }

	pnp_reserve_irq=
			[ISAPNP] Exclude IRQs for the autoconfiguration

	pnp_reserve_dma=
			[ISAPNP] Exclude DMAs for the autoconfiguration

	pnp_reserve_io=	[ISAPNP] Exclude I/O ports for the autoconfiguration
			Ranges are in pairs (I/O port base and size).

	pnp_reserve_mem=
			[ISAPNP] Exclude memory regions for the
			autoconfiguration.
			Ranges are in pairs (memory base and size).

	ports=		[IP_VS_FTP] IPVS ftp helper module
			Default is 21.
			Up to 8 (IP_VS_APP_MAX_PORTS) ports
			may be specified.
			Format: <port>,<port>....

	possible_cpus=  [SMP,S390,X86]
			Format: <unsigned int>
			Set the number of possible CPUs, overriding the
			regular discovery mechanisms (such as ACPI/FW, etc).

	powersave=off	[PPC] This option disables power saving features.
			It specifically disables cpuidle and sets the
			platform machine description specific power_save
			function to NULL. On Idle the CPU just reduces
			execution priority.

	ppc_strict_facility_enable
			[PPC,ENABLE] This option catches any kernel floating point,
			Altivec, VSX and SPE outside of regions specifically
			allowed (eg kernel_enable_fpu()/kernel_disable_fpu()).
			There is some performance impact when enabling this.

	ppc_tm=		[PPC,EARLY]
			Format: {"off"}
			Disable Hardware Transactional Memory

	preempt=	[KNL]
			Select preemption mode if you have CONFIG_PREEMPT_DYNAMIC
			none - Limited to cond_resched() calls
			voluntary - Limited to cond_resched() and might_sleep() calls
			full - Any section that isn't explicitly preempt disabled
			       can be preempted anytime.  Tasks will also yield
			       contended spinlocks (if the critical section isn't
			       explicitly preempt disabled beyond the lock itself).
			lazy - Scheduler controlled. Similar to full but instead
			       of preempting the task immediately, the task gets
			       one HZ tick time to yield itself before the
			       preemption will be forced. One preemption is when the
			       task returns to user space.

	print-fatal-signals=
			[KNL] debug: print fatal signals

			If enabled, warn about various signal handling
			related application anomalies: too many signals,
			too many POSIX.1 timers, fatal signals causing a
			coredump - etc.

			If you hit the warning due to signal overflow,
			you might want to try "ulimit -i unlimited".

			default: off.

	printk.always_kmsg_dump=
			Trigger kmsg_dump for cases other than kernel oops or
			panics
			Format: <bool>  (1/Y/y=enable, 0/N/n=disable)
			default: disabled

	printk.console_no_auto_verbose=
			Disable console loglevel raise on oops, panic
			or lockdep-detected issues (only if lock debug is on).
			With an exception to setups with low baudrate on
			serial console, keeping this 0 is a good choice
			in order to provide more debug information.
			Format: <bool>
			default: 0 (auto_verbose is enabled)

	printk.debug_non_panic_cpus=
			Allows storing messages from non-panic CPUs into
			the printk log buffer during panic(). They are
			flushed to consoles by the panic-CPU on
			a best-effort basis.
			Format: <bool> (1/Y/y=enable, 0/N/n=disable)
			Default: disabled

	printk.devkmsg={on,off,ratelimit}
			Control writing to /dev/kmsg.
			on - unlimited logging to /dev/kmsg from userspace
			off - logging to /dev/kmsg disabled
			ratelimit - ratelimit the logging
			Default: ratelimit

	printk.time=	Show timing data prefixed to each printk message line
			Format: <bool>  (1/Y/y=enable, 0/N/n=disable)

	proc_mem.force_override= [KNL]
			Format: {always | ptrace | never}
			Traditionally /proc/pid/mem allows memory permissions to be
			overridden without restrictions. This option may be set to
			restrict that. Can be one of:
			- 'always': traditional behavior always allows mem overrides.
			- 'ptrace': only allow mem overrides for active ptracers.
			- 'never':  never allow mem overrides.
			If not specified, default is the CONFIG_PROC_MEM_* choice.

	processor.max_cstate=	[HW,ACPI]
			Limit processor to maximum C-state
			max_cstate=9 overrides any DMI blacklist limit.

	processor.nocst	[HW,ACPI]
			Ignore the _CST method to determine C-states,
			instead using the legacy FADT method

	profile=	[KNL] Enable kernel profiling via /proc/profile
			Format: [<profiletype>,]<number>
			Param: <profiletype>: "schedule" or "kvm"
				[defaults to kernel profiling]
			Param: "schedule" - profile schedule points.
			Param: "kvm" - profile VM exits.
			Param: <number> - step/bucket size as a power of 2 for
				statistical time based profiling.

	prompt_ramdisk=	[RAM] [Deprecated]

	prot_virt=	[S390] enable hosting protected virtual machines
			isolated from the hypervisor (if hardware supports
			that). If enabled, the default kernel base address
			might be overridden even when Kernel Address Space
			Layout Randomization is disabled.
			Format: <bool>

	psi=		[KNL] Enable or disable pressure stall information
			tracking.
			Format: <bool>

	psmouse.proto=	[HW,MOUSE] Highest PS2 mouse protocol extension to
			probe for; one of (bare|imps|exps|lifebook|any).
	psmouse.rate=	[HW,MOUSE] Set desired mouse report rate, in reports
			per second.
	psmouse.resetafter=	[HW,MOUSE]
			Try to reset the device after so many bad packets
			(0 = never).
	psmouse.resolution=
			[HW,MOUSE] Set desired mouse resolution, in dpi.
	psmouse.smartscroll=
			[HW,MOUSE] Controls Logitech smartscroll autorepeat.
			0 = disabled, 1 = enabled (default).

	pstore.backend=	Specify the name of the pstore backend to use

	pti=		[X86-64] Control Page Table Isolation of user and
			kernel address spaces.  Disabling this feature
			removes hardening, but improves performance of
			system calls and interrupts.

			on   - unconditionally enable
			off  - unconditionally disable
			auto - kernel detects whether your CPU model is
			       vulnerable to issues that PTI mitigates

			Not specifying this option is equivalent to pti=auto.

	pty.legacy_count=
			[KNL] Number of legacy pty's. Overwrites compiled-in
			default number.

	quiet		[KNL,EARLY] Disable most log messages

	r128=		[HW,DRM]

	radix_hcall_invalidate=on  [PPC/PSERIES]
			Disable RADIX GTSE feature and use hcall for TLB
			invalidate.

	raid=		[HW,RAID]
			See Documentation/admin-guide/md.rst.

	ramdisk_size=	[RAM] Sizes of RAM disks in kilobytes
			See Documentation/admin-guide/blockdev/ramdisk.rst.

	ramdisk_start=	[RAM] RAM disk image start address

	random.trust_cpu=off
			[KNL,EARLY] Disable trusting the use of the CPU's
			random number generator (if available) to
			initialize the kernel's RNG.

	random.trust_bootloader=off
			[KNL,EARLY] Disable trusting the use of the a seed
			passed by the bootloader (if available) to
			initialize the kernel's RNG.

	randomize_kstack_offset=
			[KNL,EARLY] Enable or disable kernel stack offset
			randomization, which provides roughly 5 bits of
			entropy, frustrating memory corruption attacks
			that depend on stack address determinism or
			cross-syscall address exposures. This is only
			available on architectures that have defined
			CONFIG_HAVE_ARCH_RANDOMIZE_KSTACK_OFFSET.
			Format: <bool>  (1/Y/y=enable, 0/N/n=disable)
			Default is CONFIG_RANDOMIZE_KSTACK_OFFSET_DEFAULT.

	ras=option[,option,...]	[KNL] RAS-specific options

		cec_disable	[X86]
				Disable the Correctable Errors Collector,
				see CONFIG_RAS_CEC help text.

	rcu_nocbs[=cpu-list]
			[KNL] The optional argument is a cpu list,
			as described above.

			In kernels built with CONFIG_RCU_NOCB_CPU=y,
			enable the no-callback CPU mode, which prevents
			such CPUs' callbacks from being invoked in
			softirq context.  Invocation of such CPUs' RCU
			callbacks will instead be offloaded to "rcuox/N"
			kthreads created for that purpose, where "x" is
			"p" for RCU-preempt, "s" for RCU-sched, and "g"
			for the kthreads that mediate grace periods; and
			"N" is the CPU number. This reduces OS jitter on
			the offloaded CPUs, which can be useful for HPC
			and real-time workloads.  It can also improve
			energy efficiency for asymmetric multiprocessors.

			If a cpulist is passed as an argument, the specified
			list of	CPUs is set to no-callback mode from boot.

			Otherwise, if the '=' sign and the cpulist
			arguments are omitted, no CPU will be set to
			no-callback mode from boot but the mode may be
			toggled at runtime via cpusets.

			Note that this argument takes precedence over
			the CONFIG_RCU_NOCB_CPU_DEFAULT_ALL option.

	rcu_nocb_poll	[KNL]
			Rather than requiring that offloaded CPUs
			(specified by rcu_nocbs= above) explicitly
			awaken the corresponding "rcuoN" kthreads,
			make these kthreads poll for callbacks.
			This improves the real-time response for the
			offloaded CPUs by relieving them of the need to
			wake up the corresponding kthread, but degrades
			energy efficiency by requiring that the kthreads
			periodically wake up to do the polling.

	rcutree.blimit=	[KNL]
			Set maximum number of finished RCU callbacks to
			process in one batch.

	rcutree.csd_lock_suppress_rcu_stall=	[KNL]
			Do only a one-line RCU CPU stall warning when
			there is an ongoing too-long CSD-lock wait.

	rcutree.do_rcu_barrier=	[KNL]
			Request a call to rcu_barrier().  This is
			throttled so that userspace tests can safely
			hammer on the sysfs variable if they so choose.
			If triggered before the RCU grace-period machinery
			is fully active, this will error out with EAGAIN.

	rcutree.dump_tree=	[KNL]
			Dump the structure of the rcu_node combining tree
			out at early boot.  This is used for diagnostic
			purposes, to verify correct tree setup.

	rcutree.gp_cleanup_delay=	[KNL]
			Set the number of jiffies to delay each step of
			RCU grace-period cleanup.

	rcutree.gp_init_delay=	[KNL]
			Set the number of jiffies to delay each step of
			RCU grace-period initialization.

	rcutree.gp_preinit_delay=	[KNL]
			Set the number of jiffies to delay each step of
			RCU grace-period pre-initialization, that is,
			the propagation of recent CPU-hotplug changes up
			the rcu_node combining tree.

	rcutree.jiffies_till_first_fqs= [KNL]
			Set delay from grace-period initialization to
			first attempt to force quiescent states.
			Units are jiffies, minimum value is zero,
			and maximum value is HZ.

	rcutree.jiffies_till_next_fqs= [KNL]
			Set delay between subsequent attempts to force
			quiescent states.  Units are jiffies, minimum
			value is one, and maximum value is HZ.

	rcutree.jiffies_till_sched_qs= [KNL]
			Set required age in jiffies for a
			given grace period before RCU starts
			soliciting quiescent-state help from
			rcu_note_context_switch() and cond_resched().
			If not specified, the kernel will calculate
			a value based on the most recent settings
			of rcutree.jiffies_till_first_fqs
			and rcutree.jiffies_till_next_fqs.
			This calculated value may be viewed in
			rcutree.jiffies_to_sched_qs.  Any attempt to set
			rcutree.jiffies_to_sched_qs will be cheerfully
			overwritten.

	rcutree.kthread_prio= 	 [KNL,BOOT]
			Set the SCHED_FIFO priority of the RCU per-CPU
			kthreads (rcuc/N). This value is also used for
			the priority of the RCU boost threads (rcub/N)
			and for the RCU grace-period kthreads (rcu_bh,
			rcu_preempt, and rcu_sched). If RCU_BOOST is
			set, valid values are 1-99 and the default is 1
			(the least-favored priority).  Otherwise, when
			RCU_BOOST is not set, valid values are 0-99 and
			the default is zero (non-realtime operation).
			When RCU_NOCB_CPU is set, also adjust the
			priority of NOCB callback kthreads.

	rcutree.nocb_nobypass_lim_per_jiffy= [KNL]
			On callback-offloaded (rcu_nocbs) CPUs,
			RCU reduces the lock contention that would
			otherwise be caused by callback floods through
			use of the ->nocb_bypass list.	However, in the
			common non-flooded case, RCU queues directly to
			the main ->cblist in order to avoid the extra
			overhead of the ->nocb_bypass list and its lock.
			But if there are too many callbacks queued during
			a single jiffy, RCU pre-queues the callbacks into
			the ->nocb_bypass queue.  The definition of "too
			many" is supplied by this kernel boot parameter.

	rcutree.nohz_full_patience_delay= [KNL]
			On callback-offloaded (rcu_nocbs) CPUs, avoid
			disturbing RCU unless the grace period has
			reached the specified age in milliseconds.
			Defaults to zero.  Large values will be capped
			at five seconds.  All values will be rounded down
			to the nearest value representable by jiffies.

	rcutree.qhimark= [KNL]
			Set threshold of queued RCU callbacks beyond which
			batch limiting is disabled.

	rcutree.qlowmark= [KNL]
			Set threshold of queued RCU callbacks below which
			batch limiting is re-enabled.

	rcutree.qovld= [KNL]
			Set threshold of queued RCU callbacks beyond which
			RCU's force-quiescent-state scan will aggressively
			enlist help from cond_resched() and sched IPIs to
			help CPUs more quickly reach quiescent states.
			Set to less than zero to make this be set based
			on rcutree.qhimark at boot time and to zero to
			disable more aggressive help enlistment.

	rcutree.rcu_delay_page_cache_fill_msec= [KNL]
			Set the page-cache refill delay (in milliseconds)
			in response to low-memory conditions.  The range
			of permitted values is in the range 0:100000.

	rcutree.rcu_divisor= [KNL]
			Set the shift-right count to use to compute
			the callback-invocation batch limit bl from
			the number of callbacks queued on this CPU.
			The result will be bounded below by the value of
			the rcutree.blimit kernel parameter.  Every bl
			callbacks, the softirq handler will exit in
			order to allow the CPU to do other work.

			Please note that this callback-invocation batch
			limit applies only to non-offloaded callback
			invocation.  Offloaded callbacks are instead
			invoked in the context of an rcuoc kthread, which
			scheduler will preempt as it does any other task.

	rcutree.rcu_fanout_exact= [KNL]
			Disable autobalancing of the rcu_node combining
			tree.  This is used by rcutorture, and might
			possibly be useful for architectures having high
			cache-to-cache transfer latencies.

	rcutree.rcu_fanout_leaf= [KNL]
			Change the number of CPUs assigned to each
			leaf rcu_node structure.  Useful for very
			large systems, which will choose the value 64,
			and for NUMA systems with large remote-access
			latencies, which will choose a value aligned
			with the appropriate hardware boundaries.

	rcutree.rcu_min_cached_objs= [KNL]
			Minimum number of objects which are cached and
			maintained per one CPU. Object size is equal
			to PAGE_SIZE. The cache allows to reduce the
			pressure to page allocator, also it makes the
			whole algorithm to behave better in low memory
			condition.

	rcutree.rcu_nocb_gp_stride= [KNL]
			Set the number of NOCB callback kthreads in
			each group, which defaults to the square root
			of the number of CPUs.	Larger numbers reduce
			the wakeup overhead on the global grace-period
			kthread, but increases that same overhead on
			each group's NOCB grace-period kthread.

	rcutree.rcu_kick_kthreads= [KNL]
			Cause the grace-period kthread to get an extra
			wake_up() if it sleeps three times longer than
			it should at force-quiescent-state time.
			This wake_up() will be accompanied by a
			WARN_ONCE() splat and an ftrace_dump().

	rcutree.rcu_resched_ns= [KNL]
			Limit the time spend invoking a batch of RCU
			callbacks to the specified number of nanoseconds.
			By default, this limit is checked only once
			every 32 callbacks in order to limit the pain
			inflicted by local_clock() overhead.

	rcutree.rcu_unlock_delay= [KNL]
			In CONFIG_RCU_STRICT_GRACE_PERIOD=y kernels,
			this specifies an rcu_read_unlock()-time delay
			in microseconds.  This defaults to zero.
			Larger delays increase the probability of
			catching RCU pointer leaks, that is, buggy use
			of RCU-protected pointers after the relevant
			rcu_read_unlock() has completed.

	rcutree.sysrq_rcu= [KNL]
			Commandeer a sysrq key to dump out Tree RCU's
			rcu_node tree with an eye towards determining
			why a new grace period has not yet started.

	rcutree.use_softirq=	[KNL]
			If set to zero, move all RCU_SOFTIRQ processing to
			per-CPU rcuc kthreads.  Defaults to a non-zero
			value, meaning that RCU_SOFTIRQ is used by default.
			Specify rcutree.use_softirq=0 to use rcuc kthreads.

			But note that CONFIG_PREEMPT_RT=y kernels disable
			this kernel boot parameter, forcibly setting it
			to zero.

	rcutree.enable_rcu_lazy= [KNL]
			To save power, batch RCU callbacks and flush after
			delay, memory pressure or callback list growing too
			big.

	rcutree.rcu_normal_wake_from_gp= [KNL]
			Reduces a latency of synchronize_rcu() call. This approach
			maintains its own track of synchronize_rcu() callers, so it
			does not interact with regular callbacks because it does not
			use a call_rcu[_hurry]() path. Please note, this is for a
			normal grace period.

			How to enable it:

			echo 1 > /sys/module/rcutree/parameters/rcu_normal_wake_from_gp
			or pass a boot parameter "rcutree.rcu_normal_wake_from_gp=1"

			Default is 1 if num_possible_cpus() <= 16 and it is not explicitly
			disabled by the boot parameter passing 0.

	rcuscale.gp_async= [KNL]
			Measure performance of asynchronous
			grace-period primitives such as call_rcu().

	rcuscale.gp_async_max= [KNL]
			Specify the maximum number of outstanding
			callbacks per writer thread.  When a writer
			thread exceeds this limit, it invokes the
			corresponding flavor of rcu_barrier() to allow
			previously posted callbacks to drain.

	rcuscale.gp_exp= [KNL]
			Measure performance of expedited synchronous
			grace-period primitives.

	rcuscale.holdoff= [KNL]
			Set test-start holdoff period.  The purpose of
			this parameter is to delay the start of the
			test until boot completes in order to avoid
			interference.

	rcuscale.kfree_by_call_rcu= [KNL]
			In kernels built with CONFIG_RCU_LAZY=y, test
			call_rcu() instead of kfree_rcu().

	rcuscale.kfree_mult= [KNL]
			Instead of allocating an object of size kfree_obj,
			allocate one of kfree_mult * sizeof(kfree_obj).
			Defaults to 1.

	rcuscale.kfree_rcu_test= [KNL]
			Set to measure performance of kfree_rcu() flooding.

	rcuscale.kfree_rcu_test_double= [KNL]
			Test the double-argument variant of kfree_rcu().
			If this parameter has the same value as
			rcuscale.kfree_rcu_test_single, both the single-
			and double-argument variants are tested.

	rcuscale.kfree_rcu_test_single= [KNL]
			Test the single-argument variant of kfree_rcu().
			If this parameter has the same value as
			rcuscale.kfree_rcu_test_double, both the single-
			and double-argument variants are tested.

	rcuscale.kfree_nthreads= [KNL]
			The number of threads running loops of kfree_rcu().

	rcuscale.kfree_alloc_num= [KNL]
			Number of allocations and frees done in an iteration.

	rcuscale.kfree_loops= [KNL]
			Number of loops doing rcuscale.kfree_alloc_num number
			of allocations and frees.

	rcuscale.minruntime= [KNL]
			Set the minimum test run time in seconds.  This
			does not affect the data-collection interval,
			but instead allows better measurement of things
			like CPU consumption.

	rcuscale.nreaders= [KNL]
			Set number of RCU readers.  The value -1 selects
			N, where N is the number of CPUs.  A value
			"n" less than -1 selects N-n+1, where N is again
			the number of CPUs.  For example, -2 selects N
			(the number of CPUs), -3 selects N+1, and so on.
			A value of "n" less than or equal to -N selects
			a single reader.

	rcuscale.nwriters= [KNL]
			Set number of RCU writers.  The values operate
			the same as for rcuscale.nreaders.
			N, where N is the number of CPUs

	rcuscale.scale_type= [KNL]
			Specify the RCU implementation to test.

	rcuscale.shutdown= [KNL]
			Shut the system down after performance tests
			complete.  This is useful for hands-off automated
			testing.

	rcuscale.verbose= [KNL]
			Enable additional printk() statements.

	rcuscale.writer_holdoff= [KNL]
			Write-side holdoff between grace periods,
			in microseconds.  The default of zero says
			no holdoff.

	rcuscale.writer_holdoff_jiffies= [KNL]
			Additional write-side holdoff between grace
			periods, but in jiffies.  The default of zero
			says no holdoff.

	rcutorture.fqs_duration= [KNL]
			Set duration of force_quiescent_state bursts
			in microseconds.

	rcutorture.fqs_holdoff= [KNL]
			Set holdoff time within force_quiescent_state bursts
			in microseconds.

	rcutorture.fqs_stutter= [KNL]
			Set wait time between force_quiescent_state bursts
			in seconds.

	rcutorture.fwd_progress= [KNL]
			Specifies the number of kthreads to be used
			for  RCU grace-period forward-progress testing
			for the types of RCU supporting this notion.
			Defaults to 1 kthread, values less than zero or
			greater than the number of CPUs cause the number
			of CPUs to be used.

	rcutorture.fwd_progress_div= [KNL]
			Specify the fraction of a CPU-stall-warning
			period to do tight-loop forward-progress testing.

	rcutorture.fwd_progress_holdoff= [KNL]
			Number of seconds to wait between successive
			forward-progress tests.

	rcutorture.fwd_progress_need_resched= [KNL]
			Enclose cond_resched() calls within checks for
			need_resched() during tight-loop forward-progress
			testing.

	rcutorture.gp_cond= [KNL]
			Use conditional/asynchronous update-side
			normal-grace-period primitives, if available.

	rcutorture.gp_cond_exp= [KNL]
			Use conditional/asynchronous update-side
			expedited-grace-period primitives, if available.

	rcutorture.gp_cond_full= [KNL]
			Use conditional/asynchronous update-side
			normal-grace-period primitives that also take
			concurrent expedited grace periods into account,
			if available.

	rcutorture.gp_cond_exp_full= [KNL]
			Use conditional/asynchronous update-side
			expedited-grace-period primitives that also take
			concurrent normal grace periods into account,
			if available.

	rcutorture.gp_cond_wi= [KNL]
			Nominal wait interval for normal conditional
			grace periods (specified by rcutorture's
			gp_cond and gp_cond_full module parameters),
			in microseconds.  The actual wait interval will
			be randomly selected to nanosecond granularity up
			to this wait interval.	Defaults to 16 jiffies,
			for example, 16,000 microseconds on a system
			with HZ=1000.

	rcutorture.gp_cond_wi_exp= [KNL]
			Nominal wait interval for expedited conditional
			grace periods (specified by rcutorture's
			gp_cond_exp and gp_cond_exp_full module
			parameters), in microseconds.  The actual wait
			interval will be randomly selected to nanosecond
			granularity up to this wait interval.  Defaults to
			128 microseconds.

	rcutorture.gp_exp= [KNL]
			Use expedited update-side primitives, if available.

	rcutorture.gp_normal= [KNL]
			Use normal (non-expedited) asynchronous
			update-side primitives, if available.

	rcutorture.gp_poll= [KNL]
			Use polled update-side normal-grace-period
			primitives, if available.

	rcutorture.gp_poll_exp= [KNL]
			Use polled update-side expedited-grace-period
			primitives, if available.

	rcutorture.gp_poll_full= [KNL]
			Use polled update-side normal-grace-period
			primitives that also take concurrent expedited
			grace periods into account, if available.

	rcutorture.gp_poll_exp_full= [KNL]
			Use polled update-side expedited-grace-period
			primitives that also take concurrent normal
			grace periods into account, if available.

	rcutorture.gp_poll_wi= [KNL]
			Nominal wait interval for normal conditional
			grace periods (specified by rcutorture's
			gp_poll and gp_poll_full module parameters),
			in microseconds.  The actual wait interval will
			be randomly selected to nanosecond granularity up
			to this wait interval.	Defaults to 16 jiffies,
			for example, 16,000 microseconds on a system
			with HZ=1000.

	rcutorture.gp_poll_wi_exp= [KNL]
			Nominal wait interval for expedited conditional
			grace periods (specified by rcutorture's
			gp_poll_exp and gp_poll_exp_full module
			parameters), in microseconds.  The actual wait
			interval will be randomly selected to nanosecond
			granularity up to this wait interval.  Defaults to
			128 microseconds.

	rcutorture.gp_sync= [KNL]
			Use normal (non-expedited) synchronous
			update-side primitives, if available.  If all
			of rcutorture.gp_cond=, rcutorture.gp_exp=,
			rcutorture.gp_normal=, and rcutorture.gp_sync=
			are zero, rcutorture acts as if is interpreted
			they are all non-zero.

	rcutorture.gpwrap_lag= [KNL]
			Enable grace-period wrap lag testing. Setting
			to false prevents the gpwrap lag test from
			running. Default is true.

	rcutorture.gpwrap_lag_gps= [KNL]
			Set the value for grace-period wrap lag during
			active lag testing periods. This controls how many
			grace periods differences we tolerate between
			rdp and rnp's gp_seq before setting overflow flag.
			The default is always set to 8.

	rcutorture.gpwrap_lag_cycle_mins= [KNL]
			Set the total cycle duration for gpwrap lag
			testing in minutes. This is the total time for
			one complete cycle of active and inactive
			testing periods. Default is 30 minutes.

	rcutorture.gpwrap_lag_active_mins= [KNL]
			Set the duration for which gpwrap lag is active
			within each cycle, in minutes. During this time,
			the grace-period wrap lag will be set to the
			value specified by gpwrap_lag_gps. Default is
			5 minutes.

	rcutorture.irqreader= [KNL]
			Run RCU readers from irq handlers, or, more
			accurately, from a timer handler.  Not all RCU
			flavors take kindly to this sort of thing.

	rcutorture.leakpointer= [KNL]
			Leak an RCU-protected pointer out of the reader.
			This can of course result in splats, and is
			intended to test the ability of things like
			CONFIG_RCU_STRICT_GRACE_PERIOD=y to detect
			such leaks.

	rcutorture.n_barrier_cbs= [KNL]
			Set callbacks/threads for rcu_barrier() testing.

	rcutorture.nfakewriters= [KNL]
			Set number of concurrent RCU writers.  These just
			stress RCU, they don't participate in the actual
			test, hence the "fake".

	rcutorture.nocbs_nthreads= [KNL]
			Set number of RCU callback-offload togglers.
			Zero (the default) disables toggling.

	rcutorture.nocbs_toggle= [KNL]
			Set the delay in milliseconds between successive
			callback-offload toggling attempts.

	rcutorture.nreaders= [KNL]
			Set number of RCU readers.  The value -1 selects
			N-1, where N is the number of CPUs.  A value
			"n" less than -1 selects N-n-2, where N is again
			the number of CPUs.  For example, -2 selects N
			(the number of CPUs), -3 selects N+1, and so on.

	rcutorture.object_debug= [KNL]
			Enable debug-object double-call_rcu() testing.

	rcutorture.onoff_holdoff= [KNL]
			Set time (s) after boot for CPU-hotplug testing.

	rcutorture.onoff_interval= [KNL]
			Set time (jiffies) between CPU-hotplug operations,
			or zero to disable CPU-hotplug testing.

	rcutorture.preempt_duration= [KNL]
			Set duration (in milliseconds) of preemptions
			by a high-priority FIFO real-time task.  Set to
			zero (the default) to disable.	The CPUs to
			preempt are selected randomly from the set that
			are online at a given point in time.  Races with
			CPUs going offline are ignored, with that attempt
			at preemption skipped.

	rcutorture.preempt_interval= [KNL]
			Set interval (in milliseconds, defaulting to one
			second) between preemptions by a high-priority
			FIFO real-time task.  This delay is mediated
			by an hrtimer and is further fuzzed to avoid
			inadvertent synchronizations.

	rcutorture.read_exit_burst= [KNL]
			The number of times in a given read-then-exit
			episode that a set of read-then-exit kthreads
			is spawned.

	rcutorture.read_exit_delay= [KNL]
			The delay, in seconds, between successive
			read-then-exit testing episodes.

	rcutorture.reader_flavor= [KNL]
			A bit mask indicating which readers to use.
			If there is more than one bit set, the readers
			are entered from low-order bit up, and are
			exited in the opposite order.  For SRCU, the
			0x1 bit is normal readers, 0x2 NMI-safe readers,
			and 0x4 light-weight readers.

	rcutorture.shuffle_interval= [KNL]
			Set task-shuffle interval (s).  Shuffling tasks
			allows some CPUs to go into dyntick-idle mode
			during the rcutorture test.

	rcutorture.shutdown_secs= [KNL]
			Set time (s) after boot system shutdown.  This
			is useful for hands-off automated testing.

	rcutorture.stall_cpu= [KNL]
			Duration of CPU stall (s) to test RCU CPU stall
			warnings, zero to disable.

	rcutorture.stall_cpu_block= [KNL]
			Sleep while stalling if set.  This will result
			in warnings from preemptible RCU in addition to
			any other stall-related activity.  Note that
			in kernels built with CONFIG_PREEMPTION=n and
			CONFIG_PREEMPT_COUNT=y, this parameter will
			cause the CPU to pass through a quiescent state.
			Given CONFIG_PREEMPTION=n, this will suppress
			RCU CPU stall warnings, but will instead result
			in scheduling-while-atomic splats.

			Use of this module parameter results in splats.


	rcutorture.stall_cpu_holdoff= [KNL]
			Time to wait (s) after boot before inducing stall.

	rcutorture.stall_cpu_irqsoff= [KNL]
			Disable interrupts while stalling if set, but only
			on the first stall in the set.

	rcutorture.stall_cpu_repeat= [KNL]
			Number of times to repeat the stall sequence,
			so that rcutorture.stall_cpu_repeat=3 will result
			in four stall sequences.

	rcutorture.stall_gp_kthread= [KNL]
			Duration (s) of forced sleep within RCU
			grace-period kthread to test RCU CPU stall
			warnings, zero to disable.  If both stall_cpu
			and stall_gp_kthread are specified, the
			kthread is starved first, then the CPU.

	rcutorture.stat_interval= [KNL]
			Time (s) between statistics printk()s.

	rcutorture.stutter= [KNL]
			Time (s) to stutter testing, for example, specifying
			five seconds causes the test to run for five seconds,
			wait for five seconds, and so on.  This tests RCU's
			ability to transition abruptly to and from idle.

	rcutorture.test_boost= [KNL]
			Test RCU priority boosting?  0=no, 1=maybe, 2=yes.
			"Maybe" means test if the RCU implementation
			under test support RCU priority boosting.

	rcutorture.test_boost_duration= [KNL]
			Duration (s) of each individual boost test.

	rcutorture.test_boost_holdoff= [KNL]
			Holdoff time (s) from start of test to the start
			of RCU priority-boost testing.	Defaults to zero,
			that is, no holdoff.

	rcutorture.test_boost_interval= [KNL]
			Interval (s) between each boost test.

	rcutorture.test_no_idle_hz= [KNL]
			Test RCU's dyntick-idle handling.  See also the
			rcutorture.shuffle_interval parameter.

	rcutorture.torture_type= [KNL]
			Specify the RCU implementation to test.

	rcutorture.verbose= [KNL]
			Enable additional printk() statements.

	rcupdate.rcu_cpu_stall_ftrace_dump= [KNL]
			Dump ftrace buffer after reporting RCU CPU
			stall warning.

	rcupdate.rcu_cpu_stall_notifiers= [KNL]
			Provide RCU CPU stall notifiers, but see the
			warnings in the RCU_CPU_STALL_NOTIFIER Kconfig
			option's help text.  TL;DR:  You almost certainly
			do not want rcupdate.rcu_cpu_stall_notifiers.

	rcupdate.rcu_cpu_stall_suppress= [KNL]
			Suppress RCU CPU stall warning messages.

	rcupdate.rcu_cpu_stall_suppress_at_boot= [KNL]
			Suppress RCU CPU stall warning messages and
			rcutorture writer stall warnings that occur
			during early boot, that is, during the time
			before the init task is spawned.

	rcupdate.rcu_cpu_stall_timeout= [KNL]
			Set timeout for RCU CPU stall warning messages.
			The value is in seconds and the maximum allowed
			value is 300 seconds.

	rcupdate.rcu_exp_cpu_stall_timeout= [KNL]
			Set timeout for expedited RCU CPU stall warning
			messages.  The value is in milliseconds
			and the maximum allowed value is 21000
			milliseconds. Please note that this value is
			adjusted to an arch timer tick resolution.
			Setting this to zero causes the value from
			rcupdate.rcu_cpu_stall_timeout to be used (after
			conversion from seconds to milliseconds).

	rcupdate.rcu_cpu_stall_cputime= [KNL]
			Provide statistics on the cputime and count of
			interrupts and tasks during the sampling period. For
			multiple continuous RCU stalls, all sampling periods
			begin at half of the first RCU stall timeout.

	rcupdate.rcu_exp_stall_task_details= [KNL]
			Print stack dumps of any tasks blocking the
			current expedited RCU grace period during an
			expedited RCU CPU stall warning.

	rcupdate.rcu_expedited= [KNL]
			Use expedited grace-period primitives, for
			example, synchronize_rcu_expedited() instead
			of synchronize_rcu().  This reduces latency,
			but can increase CPU utilization, degrade
			real-time latency, and degrade energy efficiency.
			No effect on CONFIG_TINY_RCU kernels.

	rcupdate.rcu_normal= [KNL]
			Use only normal grace-period primitives,
			for example, synchronize_rcu() instead of
			synchronize_rcu_expedited().  This improves
			real-time latency, CPU utilization, and
			energy efficiency, but can expose users to
			increased grace-period latency.  This parameter
			overrides rcupdate.rcu_expedited.  No effect on
			CONFIG_TINY_RCU kernels.

	rcupdate.rcu_normal_after_boot= [KNL]
			Once boot has completed (that is, after
			rcu_end_inkernel_boot() has been invoked), use
			only normal grace-period primitives.  No effect
			on CONFIG_TINY_RCU kernels.

			But note that CONFIG_PREEMPT_RT=y kernels enables
			this kernel boot parameter, forcibly setting
			it to the value one, that is, converting any
			post-boot attempt at an expedited RCU grace
			period to instead use normal non-expedited
			grace-period processing.

	rcupdate.rcu_task_collapse_lim= [KNL]
			Set the maximum number of callbacks present
			at the beginning of a grace period that allows
			the RCU Tasks flavors to collapse back to using
			a single callback queue.  This switching only
			occurs when rcupdate.rcu_task_enqueue_lim is
			set to the default value of -1.

	rcupdate.rcu_task_contend_lim= [KNL]
			Set the minimum number of callback-queuing-time
			lock-contention events per jiffy required to
			cause the RCU Tasks flavors to switch to per-CPU
			callback queuing.  This switching only occurs
			when rcupdate.rcu_task_enqueue_lim is set to
			the default value of -1.

	rcupdate.rcu_task_enqueue_lim= [KNL]
			Set the number of callback queues to use for the
			RCU Tasks family of RCU flavors.  The default
			of -1 allows this to be automatically (and
			dynamically) adjusted.	This parameter is intended
			for use in testing.

	rcupdate.rcu_task_ipi_delay= [KNL]
			Set time in jiffies during which RCU tasks will
			avoid sending IPIs, starting with the beginning
			of a given grace period.  Setting a large
			number avoids disturbing real-time workloads,
			but lengthens grace periods.

	rcupdate.rcu_task_lazy_lim= [KNL]
			Number of callbacks on a given CPU that will
			cancel laziness on that CPU.  Use -1 to disable
			cancellation of laziness, but be advised that
			doing so increases the danger of OOM due to
			callback flooding.

	rcupdate.rcu_task_stall_info= [KNL]
			Set initial timeout in jiffies for RCU task stall
			informational messages, which give some indication
			of the problem for those not patient enough to
			wait for ten minutes.  Informational messages are
			only printed prior to the stall-warning message
			for a given grace period. Disable with a value
			less than or equal to zero.  Defaults to ten
			seconds.  A change in value does not take effect
			until the beginning of the next grace period.

	rcupdate.rcu_task_stall_info_mult= [KNL]
			Multiplier for time interval between successive
			RCU task stall informational messages for a given
			RCU tasks grace period.  This value is clamped
			to one through ten, inclusive.	It defaults to
			the value three, so that the first informational
			message is printed 10 seconds into the grace
			period, the second at 40 seconds, the third at
			160 seconds, and then the stall warning at 600
			seconds would prevent a fourth at 640 seconds.

	rcupdate.rcu_task_stall_timeout= [KNL]
			Set timeout in jiffies for RCU task stall
			warning messages.  Disable with a value less
			than or equal to zero.	Defaults to ten minutes.
			A change in value does not take effect until
			the beginning of the next grace period.

	rcupdate.rcu_tasks_lazy_ms= [KNL]
			Set timeout in milliseconds RCU Tasks asynchronous
			callback batching for call_rcu_tasks().
			A negative value will take the default.  A value
			of zero will disable batching.	Batching is
			always disabled for synchronize_rcu_tasks().

	rcupdate.rcu_tasks_trace_lazy_ms= [KNL]
			Set timeout in milliseconds RCU Tasks
			Trace asynchronous callback batching for
			call_rcu_tasks_trace().  A negative value
			will take the default.	A value of zero will
			disable batching.  Batching is always disabled
			for synchronize_rcu_tasks_trace().

	rcupdate.rcu_self_test= [KNL]
			Run the RCU early boot self tests

	rdinit=		[KNL]
			Format: <full_path>
			Run specified binary instead of /init from the ramdisk,
			used for early userspace startup. See initrd.

	rdrand=		[X86,EARLY]
			force - Override the decision by the kernel to hide the
				advertisement of RDRAND support (this affects
				certain AMD processors because of buggy BIOS
				support, specifically around the suspend/resume
				path).

	rdt=		[HW,X86,RDT]
			Turn on/off individual RDT features. List is:
			cmt, mbmtotal, mbmlocal, l3cat, l3cdp, l2cat, l2cdp,
			mba, smba, bmec, abmc.
			E.g. to turn on cmt and turn off mba use:
				rdt=cmt,!mba

	reboot=		[KNL]
			Format (x86 or x86_64):
				[w[arm] | c[old] | h[ard] | s[oft] | g[pio]] | d[efault] \
				[[,]s[mp]#### \
				[[,]b[ios] | a[cpi] | k[bd] | t[riple] | e[fi] | p[ci]] \
				[[,]f[orce]
			Where reboot_mode is one of warm (soft) or cold (hard) or gpio
					(prefix with 'panic_' to set mode for panic
					reboot only),
			      reboot_type is one of bios, acpi, kbd, triple, efi, or pci,
			      reboot_force is either force or not specified,
			      reboot_cpu is s[mp]#### with #### being the processor
					to be used for rebooting.

		acpi
			Use the ACPI RESET_REG in the FADT. If ACPI is not
			configured or the ACPI reset does not work, the reboot
			path attempts the reset using the keyboard controller.

		bios
			Use the CPU reboot vector for warm reset

		cold
			Set the cold reboot flag

		default
			There are some built-in platform specific "quirks"
			- you may see: "reboot: <name> series board detected.
			Selecting <type> for reboots." In the case where you
			think the quirk is in error (e.g. you have newer BIOS,
			or newer board) using this option will ignore the
			built-in quirk table, and use the generic default
			reboot actions.

		efi
			Use efi reset_system runtime service. If EFI is not
			configured or the EFI reset does not work, the reboot
			path attempts the reset using the keyboard controller.

		force
			Don't stop other CPUs on reboot. This can make reboot
			more reliable in some cases.

		kbd
			Use the keyboard controller. cold reset (default)

		pci
			Use a write to the PCI config space register 0xcf9 to
			trigger reboot.

		triple
			Force a triple fault (init)

		warm
			Don't set the cold reboot flag

			Using warm reset will be much faster especially on big
			memory systems because the BIOS will not go through
			the memory check.  Disadvantage is that not all
			hardware will be completely reinitialized on reboot so
			there may be boot problems on some systems.


	refscale.holdoff= [KNL]
			Set test-start holdoff period.  The purpose of
			this parameter is to delay the start of the
			test until boot completes in order to avoid
			interference.

	refscale.lookup_instances= [KNL]
			Number of data elements to use for the forms of
			SLAB_TYPESAFE_BY_RCU testing.  A negative number
			is negated and multiplied by nr_cpu_ids, while
			zero specifies nr_cpu_ids.

	refscale.loops= [KNL]
			Set the number of loops over the synchronization
			primitive under test.  Increasing this number
			reduces noise due to loop start/end overhead,
			but the default has already reduced the per-pass
			noise to a handful of picoseconds on ca. 2020
			x86 laptops.

	refscale.nreaders= [KNL]
			Set number of readers.  The default value of -1
			selects N, where N is roughly 75% of the number
			of CPUs.  A value of zero is an interesting choice.

	refscale.nruns= [KNL]
			Set number of runs, each of which is dumped onto
			the console log.

	refscale.readdelay= [KNL]
			Set the read-side critical-section duration,
			measured in microseconds.

	refscale.scale_type= [KNL]
			Specify the read-protection implementation to test.

	refscale.shutdown= [KNL]
			Shut down the system at the end of the performance
			test.  This defaults to 1 (shut it down) when
			refscale is built into the kernel and to 0 (leave
			it running) when refscale is built as a module.

	refscale.verbose= [KNL]
			Enable additional printk() statements.

	refscale.verbose_batched= [KNL]
			Batch the additional printk() statements.  If zero
			(the default) or negative, print everything.  Otherwise,
			print every Nth verbose statement, where N is the value
			specified.

	regulator_ignore_unused
			[REGULATOR]
			Prevents regulator framework from disabling regulators
			that are unused, due no driver claiming them. This may
			be useful for debug and development, but should not be
			needed on a platform with proper driver support.

	relax_domain_level=
			[KNL, SMP] Set scheduler's default relax_domain_level.
			See Documentation/admin-guide/cgroup-v1/cpusets.rst.

	reserve=	[KNL,BUGS] Force kernel to ignore I/O ports or memory
			Format: <base1>,<size1>[,<base2>,<size2>,...]
			Reserve I/O ports or memory so the kernel won't use
			them.  If <base> is less than 0x10000, the region
			is assumed to be I/O ports; otherwise it is memory.

	reserve_mem=	[RAM]
			Format: nn[KMG]:<align>:<label>
			Reserve physical memory and label it with a name that
			other subsystems can use to access it. This is typically
			used for systems that do not wipe the RAM, and this command
			line will try to reserve the same physical memory on
			soft reboots. Note, it is not guaranteed to be the same
			location. For example, if anything about the system changes
			or if booting a different kernel. It can also fail if KASLR
			places the kernel at the location of where the RAM reservation
			was from a previous boot, the new reservation will be at a
			different location.
			Any subsystem using this feature must add a way to verify
			that the contents of the physical memory is from a previous
			boot, as there may be cases where the memory will not be
			located at the same location.

			The format is size:align:label for example, to request
			12 megabytes of 4096 alignment for ramoops:

			reserve_mem=12M:4096:oops ramoops.mem_name=oops

	reservetop=	[X86-32,EARLY]
			Format: nn[KMG]
			Reserves a hole at the top of the kernel virtual
			address space.

	reset_devices	[KNL] Force drivers to reset the underlying device
			during initialization.

	resume=		[SWSUSP]
			Specify the partition device for software suspend
			Format:
			{/dev/<dev> | PARTUUID=<uuid> | <int>:<int> | <hex>}

	resume_offset=	[SWSUSP]
			Specify the offset from the beginning of the partition
			given by "resume=" at which the swap header is located,
			in <PAGE_SIZE> units (needed only for swap files).
			See  Documentation/power/swsusp-and-swap-files.rst

	resumedelay=	[HIBERNATION] Delay (in seconds) to pause before attempting to
			read the resume files

	resumewait	[HIBERNATION] Wait (indefinitely) for resume device to show up.
			Useful for devices that are detected asynchronously
			(e.g. USB and MMC devices).

	retain_initrd	[RAM] Keep initrd memory after extraction. After boot, it will
			be accessible via /sys/firmware/initrd.

	retbleed=	[X86] Control mitigation of RETBleed (Arbitrary
			Speculative Code Execution with Return Instructions)
			vulnerability.

			AMD-based UNRET and IBPB mitigations alone do not stop
			sibling threads from influencing the predictions of other
			sibling threads. For that reason, STIBP is used on pro-
			cessors that support it, and mitigate SMT on processors
			that don't.

			off          - no mitigation
			auto         - automatically select a migitation
			auto,nosmt   - automatically select a mitigation,
				       disabling SMT if necessary for
				       the full mitigation (only on Zen1
				       and older without STIBP).
			ibpb         - On AMD, mitigate short speculation
				       windows on basic block boundaries too.
				       Safe, highest perf impact. It also
				       enables STIBP if present. Not suitable
				       on Intel.
			ibpb,nosmt   - Like "ibpb" above but will disable SMT
				       when STIBP is not available. This is
				       the alternative for systems which do not
				       have STIBP.
			unret        - Force enable untrained return thunks,
				       only effective on AMD f15h-f17h based
				       systems.
			unret,nosmt  - Like unret, but will disable SMT when STIBP
				       is not available. This is the alternative for
				       systems which do not have STIBP.

			Selecting 'auto' will choose a mitigation method at run
			time according to the CPU.

			Not specifying this option is equivalent to retbleed=auto.

	rfkill.default_state=
		0	"airplane mode".  All wifi, bluetooth, wimax, gps, fm,
			etc. communication is blocked by default.
		1	Unblocked.

	rfkill.master_switch_mode=
		0	The "airplane mode" button does nothing.
		1	The "airplane mode" button toggles between everything
			blocked and the previous configuration.
		2	The "airplane mode" button toggles between everything
			blocked and everything unblocked.

	ring3mwait=disable
			[KNL] Disable ring 3 MONITOR/MWAIT feature on supported
			CPUs.

	riscv_isa_fallback [RISCV,EARLY]
			When CONFIG_RISCV_ISA_FALLBACK is not enabled, permit
			falling back to detecting extension support by parsing
			"riscv,isa" property on devicetree systems when the
			replacement properties are not found. See the Kconfig
			entry for RISCV_ISA_FALLBACK.

	ro		[KNL] Mount root device read-only on boot

	rodata=		[KNL,EARLY]
		on	Mark read-only kernel memory as read-only (default).
		off	Leave read-only kernel memory writable for debugging.
		noalias	Mark read-only kernel memory as read-only but retain
			writable aliases in the direct map for regions outside
			of the kernel image. [arm64]

	rockchip.usb_uart
			[EARLY]
			Enable the uart passthrough on the designated usb port
			on Rockchip SoCs. When active, the signals of the
			debug-uart get routed to the D+ and D- pins of the usb
			port and the regular usb controller gets disabled.

	root=		[KNL] Root filesystem
			Usually this is a block device specifier of some kind,
			see the early_lookup_bdev comment in
			block/early-lookup.c for details.
			Alternatively this can be "ram" for the legacy initial
			ramdisk, "nfs" and "cifs" for root on a network file
			system, or "mtd" and "ubi" for mounting from raw flash.

	rootdelay=	[KNL] Delay (in seconds) to pause before attempting to
			mount the root filesystem

	rootflags=	[KNL] Set root filesystem mount option string

	initramfs_options= [KNL]
                        Specify mount options for for the initramfs mount.

	rootfstype=	[KNL] Set root filesystem type

	rootwait	[KNL] Wait (indefinitely) for root device to show up.
			Useful for devices that are detected asynchronously
			(e.g. USB and MMC devices).

	rootwait=	[KNL] Maximum time (in seconds) to wait for root device
			to show up before attempting to mount the root
			filesystem.

	rproc_mem=nn[KMG][@address]
			[KNL,ARM,CMA] Remoteproc physical memory block.
			Memory area to be used by remote processor image,
			managed by CMA.

	rt_group_sched=	[KNL] Enable or disable SCHED_RR/FIFO group scheduling
			when CONFIG_RT_GROUP_SCHED=y. Defaults to
			!CONFIG_RT_GROUP_SCHED_DEFAULT_DISABLED.
			Format: <bool>

	rw		[KNL] Mount root device read-write on boot

	S		[KNL] Run init in single mode

	s390_iommu=	[HW,S390]
			Set s390 IOTLB flushing mode
		strict
			With strict flushing every unmap operation will result
			in an IOTLB flush. Default is lazy flushing before
			reuse, which is faster. Deprecated, equivalent to
			iommu.strict=1.

	s390_iommu_aperture=	[KNL,S390]
			Specifies the size of the per device DMA address space
			accessible through the DMA and IOMMU APIs as a decimal
			factor of the size of main memory.
			The default is 1 meaning that one can concurrently use
			as many DMA addresses as physical memory is installed,
			if supported by hardware, and thus map all of memory
			once. With a value of 2 one can map all of memory twice
			and so on. As a special case a factor of 0 imposes no
			restrictions other than those given by hardware at the
			cost of significant additional memory use for tables.

	sa1100ir	[NET]
			See drivers/net/irda/sa1100_ir.c.

	sched_proxy_exec= [KNL]
			Enables or disables "proxy execution" style
			solution to mutex-based priority inversion.
			Format: <bool>

	sched_verbose	[KNL,EARLY] Enables verbose scheduler debug messages.

	schedstats=	[KNL,X86] Enable or disable scheduled statistics.
			Allowed values are enable and disable. This feature
			incurs a small amount of overhead in the scheduler
			but is useful for debugging and performance tuning.

	sched_thermal_decay_shift=
			[Deprecated]
			[KNL, SMP] Set a decay shift for scheduler thermal
			pressure signal. Thermal pressure signal follows the
			default decay period of other scheduler pelt
			signals(usually 32 ms but configurable). Setting
			sched_thermal_decay_shift will left shift the decay
			period for the thermal pressure signal by the shift
			value.
			i.e. with the default pelt decay period of 32 ms
			sched_thermal_decay_shift   thermal pressure decay pr
				1			64 ms
				2			128 ms
			and so on.
			Format: integer between 0 and 10
			Default is 0.

	scftorture.holdoff= [KNL]
			Number of seconds to hold off before starting
			test.  Defaults to zero for module insertion and
			to 10 seconds for built-in smp_call_function()
			tests.

	scftorture.longwait= [KNL]
			Request ridiculously long waits randomly selected
			up to the chosen limit in seconds.  Zero (the
			default) disables this feature.  Please note
			that requesting even small non-zero numbers of
			seconds can result in RCU CPU stall warnings,
			softlockup complaints, and so on.

	scftorture.nthreads= [KNL]
			Number of kthreads to spawn to invoke the
			smp_call_function() family of functions.
			The default of -1 specifies a number of kthreads
			equal to the number of CPUs.

	scftorture.onoff_holdoff= [KNL]
			Number seconds to wait after the start of the
			test before initiating CPU-hotplug operations.

	scftorture.onoff_interval= [KNL]
			Number seconds to wait between successive
			CPU-hotplug operations.  Specifying zero (which
			is the default) disables CPU-hotplug operations.

	scftorture.shutdown_secs= [KNL]
			The number of seconds following the start of the
			test after which to shut down the system.  The
			default of zero avoids shutting down the system.
			Non-zero values are useful for automated tests.

	scftorture.stat_interval= [KNL]
			The number of seconds between outputting the
			current test statistics to the console.  A value
			of zero disables statistics output.

	scftorture.stutter_cpus= [KNL]
			The number of jiffies to wait between each change
			to the set of CPUs under test.

	scftorture.use_cpus_read_lock= [KNL]
			Use use_cpus_read_lock() instead of the default
			preempt_disable() to disable CPU hotplug
			while invoking one of the smp_call_function*()
			functions.

	scftorture.verbose= [KNL]
			Enable additional printk() statements.

	scftorture.weight_single= [KNL]
			The probability weighting to use for the
			smp_call_function_single() function with a zero
			"wait" parameter.  A value of -1 selects the
			default if all other weights are -1.  However,
			if at least one weight has some other value, a
			value of -1 will instead select a weight of zero.

	scftorture.weight_single_wait= [KNL]
			The probability weighting to use for the
			smp_call_function_single() function with a
			non-zero "wait" parameter.  See weight_single.

	scftorture.weight_many= [KNL]
			The probability weighting to use for the
			smp_call_function_many() function with a zero
			"wait" parameter.  See weight_single.
			Note well that setting a high probability for
			this weighting can place serious IPI load
			on the system.

	scftorture.weight_many_wait= [KNL]
			The probability weighting to use for the
			smp_call_function_many() function with a
			non-zero "wait" parameter.  See weight_single
			and weight_many.

	scftorture.weight_all= [KNL]
			The probability weighting to use for the
			smp_call_function_all() function with a zero
			"wait" parameter.  See weight_single and
			weight_many.

	scftorture.weight_all_wait= [KNL]
			The probability weighting to use for the
			smp_call_function_all() function with a
			non-zero "wait" parameter.  See weight_single
			and weight_many.

	sdw_mclk_divider=[SDW]
			Specify the MCLK divider for Intel SoundWire buses in
			case the BIOS does not provide the clock rate properly.

	skew_tick=	[KNL,EARLY] Offset the periodic timer tick per cpu to mitigate
			xtime_lock contention on larger systems, and/or RCU lock
			contention on all systems with CONFIG_MAXSMP set.
			Format: { "0" | "1" }
			0 -- disable. (may be 1 via CONFIG_CMDLINE="skew_tick=1"
			1 -- enable.
			Note: increases power consumption, thus should only be
			enabled if running jitter sensitive (HPC/RT) workloads.

	security=	[SECURITY] Choose a legacy "major" security module to
			enable at boot. This has been deprecated by the
			"lsm=" parameter.

	selinux=	[SELINUX] Disable or enable SELinux at boot time.
			Format: { "0" | "1" }
			See security/selinux/Kconfig help text.
			0 -- disable.
			1 -- enable.
			Default value is 1.

	serialnumber	[BUGS=X86-32]

	sev=option[,option...] [X86-64]

		debug
			Enable debug messages.

		nosnp
			Do not enable SEV-SNP (applies to host/hypervisor
			only). Setting 'nosnp' avoids the RMP check overhead
			in memory accesses when users do not want to run
			SEV-SNP guests.

	shapers=	[NET]
			Maximal number of shapers.

	show_lapic=	[APIC,X86] Advanced Programmable Interrupt Controller
			Limit apic dumping. The parameter defines the maximal
			number of local apics being dumped. Also it is possible
			to set it to "all" by meaning -- no limit here.
			Format: { 1 (default) | 2 | ... | all }.
			The parameter valid if only apic=debug or
			apic=verbose is specified.
			Example: apic=debug show_lapic=all

	slab_debug[=options[,slabs][;[options[,slabs]]...]	[MM]
			Enabling slab_debug allows one to determine the
			culprit if slab objects become corrupted. Enabling
			slab_debug can create guard zones around objects and
			may poison objects when not in use. Also tracks the
			last alloc / free. For more information see
			Documentation/admin-guide/mm/slab.rst.
			(slub_debug legacy name also accepted for now)

			Using this option implies the "no_hash_pointers"
			option which can be undone by adding the
			"hash_pointers=always" option.

	slab_max_order= [MM]
			Determines the maximum allowed order for slabs.
			A high setting may cause OOMs due to memory
			fragmentation. For more information see
			Documentation/admin-guide/mm/slab.rst.
			(slub_max_order legacy name also accepted for now)

	slab_merge	[MM]
			Enable merging of slabs with similar size when the
			kernel is built without CONFIG_SLAB_MERGE_DEFAULT.
			(slub_merge legacy name also accepted for now)

	slab_min_objects=	[MM]
			The minimum number of objects per slab. SLUB will
			increase the slab order up to slab_max_order to
			generate a sufficiently large slab able to contain
			the number of objects indicated. The higher the number
			of objects the smaller the overhead of tracking slabs
			and the less frequently locks need to be acquired.
			For more information see
			Documentation/admin-guide/mm/slab.rst.
			(slub_min_objects legacy name also accepted for now)

	slab_min_order=	[MM]
			Determines the minimum page order for slabs. Must be
			lower or equal to slab_max_order. For more information see
			Documentation/admin-guide/mm/slab.rst.
			(slub_min_order legacy name also accepted for now)

	slab_nomerge	[MM]
			Disable merging of slabs with similar size. May be
			necessary if there is some reason to distinguish
			allocs to different slabs, especially in hardened
			environments where the risk of heap overflows and
			layout control by attackers can usually be
			frustrated by disabling merging. This will reduce
			most of the exposure of a heap attack to a single
			cache (risks via metadata attacks are mostly
			unchanged). Debug options disable merging on their
			own.
			For more information see
			Documentation/admin-guide/mm/slab.rst.
			(slub_nomerge legacy name also accepted for now)

	slab_strict_numa	[MM]
			Support memory policies on a per object level
			in the slab allocator. The default is for memory
			policies to be applied at the folio level when
			a new folio is needed or a partial folio is
			retrieved from the lists. Increases overhead
			in the slab fastpaths but gains more accurate
			NUMA kernel object placement which helps with slow
			interconnects in NUMA systems.

	slram=		[HW,MTD]

	smart2=		[HW]
			Format: <io1>[,<io2>[,...,<io8>]]

	smp.csd_lock_timeout= [KNL]
			Specify the period of time in milliseconds
			that smp_call_function() and friends will wait
			for a CPU to release the CSD lock.  This is
			useful when diagnosing bugs involving CPUs
			disabling interrupts for extended periods
			of time.  Defaults to 5,000 milliseconds, and
			setting a value of zero disables this feature.
			This feature may be more efficiently disabled
			using the csdlock_debug- kernel parameter.

	smp.panic_on_ipistall= [KNL]
			If a csd_lock_timeout extends for more than
			the specified number of milliseconds, panic the
			system.  By default, let CSD-lock acquisition
			take as long as they take.  Specifying 300,000
			for this value provides a 5-minute timeout.

	smsc-ircc2.nopnp	[HW] Don't use PNP to discover SMC devices
	smsc-ircc2.ircc_cfg=	[HW] Device configuration I/O port
	smsc-ircc2.ircc_sir=	[HW] SIR base I/O port
	smsc-ircc2.ircc_fir=	[HW] FIR base I/O port
	smsc-ircc2.ircc_irq=	[HW] IRQ line
	smsc-ircc2.ircc_dma=	[HW] DMA channel
	smsc-ircc2.ircc_transceiver= [HW] Transceiver type:
				0: Toshiba Satellite 1800 (GP data pin select)
				1: Fast pin select (default)
				2: ATC IRMode

	smt=		[KNL,MIPS,S390,EARLY] Set the maximum number of threads
			(logical CPUs) to use per physical CPU on systems
			capable of symmetric multithreading (SMT). Will
			be capped to the actual hardware limit.
			Format: <integer>
			Default: -1 (no limit)

	softlockup_panic=
			[KNL] Should the soft-lockup detector generate panics.
			Format: 0 | 1

			A value of 1 instructs the soft-lockup detector
			to panic the machine when a soft-lockup occurs. It is
			also controlled by the kernel.softlockup_panic sysctl
			and CONFIG_BOOTPARAM_SOFTLOCKUP_PANIC, which is the
			respective build-time switch to that functionality.

	softlockup_all_cpu_backtrace=
			[KNL] Should the soft-lockup detector generate
			backtraces on all cpus.
			Format: 0 | 1

	sonypi.*=	[HW] Sony Programmable I/O Control Device driver
			See Documentation/admin-guide/laptops/sonypi.rst

	spectre_bhi=	[X86] Control mitigation of Branch History Injection
			(BHI) vulnerability.  This setting affects the
			deployment of the HW BHI control and the SW BHB
			clearing sequence.

			on     - (default) Enable the HW or SW mitigation as
				 needed.  This protects the kernel from
				 both syscalls and VMs.
			vmexit - On systems which don't have the HW mitigation
				 available, enable the SW mitigation on vmexit
				 ONLY.  On such systems, the host kernel is
				 protected from VM-originated BHI attacks, but
				 may still be vulnerable to syscall attacks.
			off    - Disable the mitigation.

	spectre_v2=	[X86,EARLY] Control mitigation of Spectre variant 2
			(indirect branch speculation) vulnerability.
			The default operation protects the kernel from
			user space attacks.

			on   - unconditionally enable, implies
			       spectre_v2_user=on
			off  - unconditionally disable, implies
			       spectre_v2_user=off
			auto - kernel detects whether your CPU model is
			       vulnerable

			Selecting 'on' will, and 'auto' may, choose a
			mitigation method at run time according to the
			CPU, the available microcode, the setting of the
			CONFIG_MITIGATION_RETPOLINE configuration option,
			and the compiler with which the kernel was built.

			Selecting 'on' will also enable the mitigation
			against user space to user space task attacks.
			Selecting specific mitigation does not force enable
			user mitigations.

			Selecting 'off' will disable both the kernel and
			the user space protections.

			Specific mitigations can also be selected manually:

			retpoline	  - replace indirect branches
			retpoline,generic - Retpolines
			retpoline,lfence  - LFENCE; indirect branch
			retpoline,amd     - alias for retpoline,lfence
			eibrs		  - Enhanced/Auto IBRS
			eibrs,retpoline   - Enhanced/Auto IBRS + Retpolines
			eibrs,lfence      - Enhanced/Auto IBRS + LFENCE
			ibrs		  - use IBRS to protect kernel

			Not specifying this option is equivalent to
			spectre_v2=auto.

	spectre_v2_user=
			[X86] Control mitigation of Spectre variant 2
		        (indirect branch speculation) vulnerability between
		        user space tasks

			on	- Unconditionally enable mitigations. Is
				  enforced by spectre_v2=on

			off     - Unconditionally disable mitigations. Is
				  enforced by spectre_v2=off

			prctl   - Indirect branch speculation is enabled,
				  but mitigation can be enabled via prctl
				  per thread.  The mitigation control state
				  is inherited on fork.

			prctl,ibpb
				- Like "prctl" above, but only STIBP is
				  controlled per thread. IBPB is issued
				  always when switching between different user
				  space processes.

			seccomp
				- Same as "prctl" above, but all seccomp
				  threads will enable the mitigation unless
				  they explicitly opt out.

			seccomp,ibpb
				- Like "seccomp" above, but only STIBP is
				  controlled per thread. IBPB is issued
				  always when switching between different
				  user space processes.

			auto    - Kernel selects the mitigation depending on
				  the available CPU features and vulnerability.

			Default mitigation: "prctl"

			Not specifying this option is equivalent to
			spectre_v2_user=auto.

	spec_rstack_overflow=
			[X86,EARLY] Control RAS overflow mitigation on AMD Zen CPUs

			off		- Disable mitigation
			microcode	- Enable microcode mitigation only
			safe-ret	- Enable sw-only safe RET mitigation (default)
			ibpb		- Enable mitigation by issuing IBPB on
					  kernel entry
			ibpb-vmexit	- Issue IBPB only on VMEXIT
					  (cloud-specific mitigation)

	spec_store_bypass_disable=
			[HW,EARLY] Control Speculative Store Bypass (SSB) Disable mitigation
			(Speculative Store Bypass vulnerability)

			Certain CPUs are vulnerable to an exploit against a
			a common industry wide performance optimization known
			as "Speculative Store Bypass" in which recent stores
			to the same memory location may not be observed by
			later loads during speculative execution. The idea
			is that such stores are unlikely and that they can
			be detected prior to instruction retirement at the
			end of a particular speculation execution window.

			In vulnerable processors, the speculatively forwarded
			store can be used in a cache side channel attack, for
			example to read memory to which the attacker does not
			directly have access (e.g. inside sandboxed code).

			This parameter controls whether the Speculative Store
			Bypass optimization is used.

			On x86 the options are:

			on      - Unconditionally disable Speculative Store Bypass
			off     - Unconditionally enable Speculative Store Bypass
			auto    - Kernel detects whether the CPU model contains an
				  implementation of Speculative Store Bypass and
				  picks the most appropriate mitigation. If the
				  CPU is not vulnerable, "off" is selected. If the
				  CPU is vulnerable the default mitigation is
				  architecture and Kconfig dependent. See below.
			prctl   - Control Speculative Store Bypass per thread
				  via prctl. Speculative Store Bypass is enabled
				  for a process by default. The state of the control
				  is inherited on fork.
			seccomp - Same as "prctl" above, but all seccomp threads
				  will disable SSB unless they explicitly opt out.

			Default mitigations:
			X86:	"prctl"

			On powerpc the options are:

			on,auto - On Power8 and Power9 insert a store-forwarding
				  barrier on kernel entry and exit. On Power7
				  perform a software flush on kernel entry and
				  exit.
			off	- No action.

			Not specifying this option is equivalent to
			spec_store_bypass_disable=auto.

	split_lock_detect=
			[X86] Enable split lock detection or bus lock detection

			When enabled (and if hardware support is present), atomic
			instructions that access data across cache line
			boundaries will result in an alignment check exception
			for split lock detection or a debug exception for
			bus lock detection.

			off	- not enabled

			warn	- the kernel will emit rate-limited warnings
				  about applications triggering the #AC
				  exception or the #DB exception. This mode is
				  the default on CPUs that support split lock
				  detection or bus lock detection. Default
				  behavior is by #AC if both features are
				  enabled in hardware.

			fatal	- the kernel will send SIGBUS to applications
				  that trigger the #AC exception or the #DB
				  exception. Default behavior is by #AC if
				  both features are enabled in hardware.

			ratelimit:N -
				  Set system wide rate limit to N bus locks
				  per second for bus lock detection.
				  0 < N <= 1000.

				  N/A for split lock detection.


			If an #AC exception is hit in the kernel or in
			firmware (i.e. not while executing in user mode)
			the kernel will oops in either "warn" or "fatal"
			mode.

			#DB exception for bus lock is triggered only when
			CPL > 0.

	srbds=		[X86,INTEL,EARLY]
			Control the Special Register Buffer Data Sampling
			(SRBDS) mitigation.

			Certain CPUs are vulnerable to an MDS-like
			exploit which can leak bits from the random
			number generator.

			By default, this issue is mitigated by
			microcode.  However, the microcode fix can cause
			the RDRAND and RDSEED instructions to become
			much slower.  Among other effects, this will
			result in reduced throughput from /dev/urandom.

			The microcode mitigation can be disabled with
			the following option:

			off:    Disable mitigation and remove
				performance impact to RDRAND and RDSEED

	srcutree.big_cpu_lim [KNL]
			Specifies the number of CPUs constituting a
			large system, such that srcu_struct structures
			should immediately allocate an srcu_node array.
			This kernel-boot parameter defaults to 128,
			but takes effect only when the low-order four
			bits of srcutree.convert_to_big is equal to 3
			(decide at boot).

	srcutree.convert_to_big [KNL]
			Specifies under what conditions an SRCU tree
			srcu_struct structure will be converted to big
			form, that is, with an rcu_node tree:

				   0:  Never.
				   1:  At init_srcu_struct() time.
				   2:  When rcutorture decides to.
				   3:  Decide at boot time (default).
				0x1X:  Above plus if high contention.

			Either way, the srcu_node tree will be sized based
			on the actual runtime number of CPUs (nr_cpu_ids)
			instead of the compile-time CONFIG_NR_CPUS.

	srcutree.counter_wrap_check [KNL]
			Specifies how frequently to check for
			grace-period sequence counter wrap for the
			srcu_data structure's ->srcu_gp_seq_needed field.
			The greater the number of bits set in this kernel
			parameter, the less frequently counter wrap will
			be checked for.  Note that the bottom two bits
			are ignored.

	srcutree.exp_holdoff [KNL]
			Specifies how many nanoseconds must elapse
			since the end of the last SRCU grace period for
			a given srcu_struct until the next normal SRCU
			grace period will be considered for automatic
			expediting.  Set to zero to disable automatic
			expediting.

	srcutree.srcu_max_nodelay [KNL]
			Specifies the number of no-delay instances
			per jiffy for which the SRCU grace period
			worker thread will be rescheduled with zero
			delay. Beyond this limit, worker thread will
			be rescheduled with a sleep delay of one jiffy.

	srcutree.srcu_max_nodelay_phase [KNL]
			Specifies the per-grace-period phase, number of
			non-sleeping polls of readers. Beyond this limit,
			grace period worker thread will be rescheduled
			with a sleep delay of one jiffy, between each
			rescan of the readers, for a grace period phase.

	srcutree.srcu_retry_check_delay [KNL]
			Specifies number of microseconds of non-sleeping
			delay between each non-sleeping poll of readers.

	srcutree.small_contention_lim [KNL]
			Specifies the number of update-side contention
			events per jiffy will be tolerated before
			initiating a conversion of an srcu_struct
			structure to big form.	Note that the value of
			srcutree.convert_to_big must have the 0x10 bit
			set for contention-based conversions to occur.

	ssbd=		[ARM64,HW,EARLY]
			Speculative Store Bypass Disable control

			On CPUs that are vulnerable to the Speculative
			Store Bypass vulnerability and offer a
			firmware based mitigation, this parameter
			indicates how the mitigation should be used:

			force-on:  Unconditionally enable mitigation for
				   for both kernel and userspace
			force-off: Unconditionally disable mitigation for
				   for both kernel and userspace
			kernel:    Always enable mitigation in the
				   kernel, and offer a prctl interface
				   to allow userspace to register its
				   interest in being mitigated too.

	stack_guard_gap=	[MM]
			override the default stack gap protection. The value
			is in page units and it defines how many pages prior
			to (for stacks growing down) resp. after (for stacks
			growing up) the main stack are reserved for no other
			mapping. Default value is 256 pages.

	stack_depot_disable= [KNL,EARLY]
			Setting this to true through kernel command line will
			disable the stack depot thereby saving the static memory
			consumed by the stack hash table. By default this is set
			to false.

	stack_depot_max_pools= [KNL,EARLY]
			Specify the maximum number of pools to use for storing
			stack traces. Pools are allocated on-demand up to this
			limit. Default value is 8191 pools.

	stacktrace	[FTRACE]
			Enabled the stack tracer on boot up.

	stacktrace_filter=[function-list]
			[FTRACE] Limit the functions that the stack tracer
			will trace at boot up. function-list is a comma-separated
			list of functions. This list can be changed at run
			time by the stack_trace_filter file in the debugfs
			tracing directory. Note, this enables stack tracing
			and the stacktrace above is not needed.

	sti=		[PARISC,HW]
			Format: <num>
			Set the STI (builtin display/keyboard on the HP-PARISC
			machines) console (graphic card) which should be used
			as the initial boot-console.
			See also comment in drivers/video/console/sticore.c.

	sti_font=	[HW]
			See comment in drivers/video/console/sticore.c.

	stifb=		[HW]
			Format: bpp:<bpp1>[:<bpp2>[:<bpp3>...]]

        strict_sas_size=
			[X86]
			Format: <bool>
			Enable or disable strict sigaltstack size checks
			against the required signal frame size which
			depends on the supported FPU features. This can
			be used to filter out binaries which have
			not yet been made aware of AT_MINSIGSTKSZ.

	stress_hpt	[PPC,EARLY]
			Limits the number of kernel HPT entries in the hash
			page table to increase the rate of hash page table
			faults on kernel addresses.

	stress_slb	[PPC,EARLY]
			Limits the number of kernel SLB entries, and flushes
			them frequently to increase the rate of SLB faults
			on kernel addresses.

	sunrpc.min_resvport=
	sunrpc.max_resvport=
			[NFS,SUNRPC]
			SunRPC servers often require that client requests
			originate from a privileged port (i.e. a port in the
			range 0 < portnr < 1024).
			An administrator who wishes to reserve some of these
			ports for other uses may adjust the range that the
			kernel's sunrpc client considers to be privileged
			using these two parameters to set the minimum and
			maximum port values.

	sunrpc.svc_rpc_per_connection_limit=
			[NFS,SUNRPC]
			Limit the number of requests that the server will
			process in parallel from a single connection.
			The default value is 0 (no limit).

	sunrpc.pool_mode=
			[NFS]
			Control how the NFS server code allocates CPUs to
			service thread pools.  Depending on how many NICs
			you have and where their interrupts are bound, this
			option will affect which CPUs will do NFS serving.
			Note: this parameter cannot be changed while the
			NFS server is running.

			auto	    the server chooses an appropriate mode
				    automatically using heuristics
			global	    a single global pool contains all CPUs
			percpu	    one pool for each CPU
			pernode	    one pool for each NUMA node (equivalent
				    to global on non-NUMA machines)

	sunrpc.tcp_slot_table_entries=
	sunrpc.udp_slot_table_entries=
			[NFS,SUNRPC]
			Sets the upper limit on the number of simultaneous
			RPC calls that can be sent from the client to a
			server. Increasing these values may allow you to
			improve throughput, but will also increase the
			amount of memory reserved for use by the client.

	suspend.pm_test_delay=
			[SUSPEND]
			Sets the number of seconds to remain in a suspend test
			mode before resuming the system (see
			/sys/power/pm_test). Only available when CONFIG_PM_DEBUG
			is set. Default value is 5.

	svm=		[PPC]
			Format: { on | off | y | n | 1 | 0 }
			This parameter controls use of the Protected
			Execution Facility on pSeries.

	swiotlb=	[ARM,PPC,MIPS,X86,S390,EARLY]
			Format: { <int> [,<int>] | force | noforce }
			<int> -- Number of I/O TLB slabs
			<int> -- Second integer after comma. Number of swiotlb
				 areas with their own lock. Will be rounded up
				 to a power of 2.
			force -- force using of bounce buffers even if they
			         wouldn't be automatically used by the kernel
			noforce -- Never use bounce buffers (for debugging)

	switches=	[HW,M68k,EARLY]

	sysctl.*=	[KNL]
			Set a sysctl parameter, right before loading the init
			process, as if the value was written to the respective
			/proc/sys/... file. Both '.' and '/' are recognized as
			separators. Unrecognized parameters and invalid values
			are reported in the kernel log. Sysctls registered
			later by a loaded module cannot be set this way.
			Example: sysctl.vm.swappiness=40

	sysrq_always_enabled
			[KNL]
			Ignore sysrq setting - this boot parameter will
			neutralize any effect of /proc/sys/kernel/sysrq.
			Useful for debugging.

	tcpmhash_entries= [KNL,NET]
			Set the number of tcp_metrics_hash slots.
			Default value is 8192 or 16384 depending on total
			ram pages. This is used to specify the TCP metrics
			cache size. See Documentation/networking/ip-sysctl.rst
			"tcp_no_metrics_save" section for more details.

	tdfx=		[HW,DRM]

	test_suspend=	[SUSPEND]
			Format: { "mem" | "standby" | "freeze" }[,N]
			Specify "mem" (for Suspend-to-RAM) or "standby" (for
			standby suspend) or "freeze" (for suspend type freeze)
			as the system sleep state during system startup with
			the optional capability to repeat N number of times.
			The system is woken from this state using a
			wakeup-capable RTC alarm.

	thash_entries=	[KNL,NET]
			Set number of hash buckets for TCP connection

	thermal.act=	[HW,ACPI]
			-1: disable all active trip points in all thermal zones
			<degrees C>: override all lowest active trip points

	thermal.crt=	[HW,ACPI]
			-1: disable all critical trip points in all thermal zones
			<degrees C>: override all critical trip points

	thermal.off=	[HW,ACPI]
			1: disable ACPI thermal control

	thermal.psv=	[HW,ACPI]
			-1: disable all passive trip points
			<degrees C>: override all passive trip points to this
			value

	thermal.tzp=	[HW,ACPI]
			Specify global default ACPI thermal zone polling rate
			<deci-seconds>: poll all this frequency
			0: no polling (default)

	thp_anon=	[KNL]
			Format: <size>[KMG],<size>[KMG]:<state>;<size>[KMG]-<size>[KMG]:<state>
			state is one of "always", "madvise", "never" or "inherit".
			Control the default behavior of the system with respect
			to anonymous transparent hugepages.
			Can be used multiple times for multiple anon THP sizes.
			See Documentation/admin-guide/mm/transhuge.rst for more
			details.

	threadirqs	[KNL,EARLY]
			Force threading of all interrupt handlers except those
			marked explicitly IRQF_NO_THREAD.

	thp_shmem=	[KNL]
			Format: <size>[KMG],<size>[KMG]:<policy>;<size>[KMG]-<size>[KMG]:<policy>
			Control the default policy of each hugepage size for the
			internal shmem mount. <policy> is one of policies available
			for the shmem mount ("always", "inherit", "never", "within_size",
			and "advise").
			It can be used multiple times for multiple shmem THP sizes.
			See Documentation/admin-guide/mm/transhuge.rst for more
			details.

	tlbi=		[X86-64]
			Format: {ipi}
			ipi: switch to IPI-based TLB flushing

	topology=	[S390,EARLY]
			Format: {off | on}
			Specify if the kernel should make use of the cpu
			topology information if the hardware supports this.
			The scheduler will make use of this information and
			e.g. base its process migration decisions on it.
			Default is on.

	torture.disable_onoff_at_boot= [KNL]
			Prevent the CPU-hotplug component of torturing
			until after init has spawned.

	torture.ftrace_dump_at_shutdown= [KNL]
			Dump the ftrace buffer at torture-test shutdown,
			even if there were no errors.  This can be a
			very costly operation when many torture tests
			are running concurrently, especially on systems
			with rotating-rust storage.

	torture.verbose_sleep_frequency= [KNL]
			Specifies how many verbose printk()s should be
			emitted between each sleep.  The default of zero
			disables verbose-printk() sleeping.

	torture.verbose_sleep_duration= [KNL]
			Duration of each verbose-printk() sleep in jiffies.

	tpm.disable_pcr_integrity= [HW,TPM]
			Do not protect PCR registers from unintended physical
			access, or interposers in the bus by the means of
			having an integrity protected session wrapped around
			TPM2_PCR_Extend command. Consider this in a situation
			where TPM is heavily utilized by IMA, thus protection
			causing a major performance hit, and the space where
			machines are deployed is by other means guarded.

	tpm_crb_ffa.busy_timeout_ms= [ARM64,TPM]
			Maximum time in milliseconds to retry sending a message
			to the TPM service before giving up. This parameter controls
			how long the system will continue retrying when the TPM
			service is busy.
			Format: <unsigned int>
			Default: 2000 (2 seconds)

	tpm_suspend_pcr=[HW,TPM]
			Format: integer pcr id
			Specify that at suspend time, the tpm driver
			should extend the specified pcr with zeros,
			as a workaround for some chips which fail to
			flush the last written pcr on TPM_SaveState.
			This will guarantee that all the other pcrs
			are saved.

	tpm_tis.interrupts= [HW,TPM]
			Enable interrupts for the MMIO based physical layer
			for the FIFO interface. By default it is set to false
			(0). For more information about TPM hardware interfaces
			defined by Trusted Computing Group (TCG) see
			https://trustedcomputinggroup.org/resource/pc-client-platform-tpm-profile-ptp-specification/

	tp_printk	[FTRACE]
			Have the tracepoints sent to printk as well as the
			tracing ring buffer. This is useful for early boot up
			where the system hangs or reboots and does not give the
			option for reading the tracing buffer or performing a
			ftrace_dump_on_oops.

			To turn off having tracepoints sent to printk,
			 echo 0 > /proc/sys/kernel/tracepoint_printk
			Note, echoing 1 into this file without the
			tp_printk kernel cmdline option has no effect.

			The tp_printk_stop_on_boot (see below) can also be used
			to stop the printing of events to console at
			late_initcall_sync.

			** CAUTION **

			Having tracepoints sent to printk() and activating high
			frequency tracepoints such as irq or sched, can cause
			the system to live lock.

	tp_printk_stop_on_boot [FTRACE]
			When tp_printk (above) is set, it can cause a lot of noise
			on the console. It may be useful to only include the
			printing of events during boot up, as user space may
			make the system inoperable.

			This command line option will stop the printing of events
			to console at the late_initcall_sync() time frame.

	trace_buf_size=nn[KMG]
			[FTRACE] will set tracing buffer size on each cpu.

	trace_clock=	[FTRACE] Set the clock used for tracing events
			at boot up.
			local - Use the per CPU time stamp counter
				(converted into nanoseconds). Fast, but
				depending on the architecture, may not be
				in sync between CPUs.
			global - Event time stamps are synchronized across
				CPUs. May be slower than the local clock,
				but better for some race conditions.
			counter - Simple counting of events (1, 2, ..)
				note, some counts may be skipped due to the
				infrastructure grabbing the clock more than
				once per event.
			uptime - Use jiffies as the time stamp.
			perf - Use the same clock that perf uses.
			mono - Use ktime_get_mono_fast_ns() for time stamps.
			mono_raw - Use ktime_get_raw_fast_ns() for time
				stamps.
			boot - Use ktime_get_boot_fast_ns() for time stamps.
			Architectures may add more clocks. See
			Documentation/trace/ftrace.rst for more details.

	trace_event=[event-list]
			[FTRACE] Set and start specified trace events in order
			to facilitate early boot debugging. The event-list is a
			comma-separated list of trace events to enable. See
			also Documentation/trace/events.rst

			To enable modules, use :mod: keyword:

			trace_event=:mod:<module>

			The value before :mod: will only enable specific events
			that are part of the module. See the above mentioned
			document for more information.

	trace_instance=[instance-info]
			[FTRACE] Create a ring buffer instance early in boot up.
			This will be listed in:

				/sys/kernel/tracing/instances

			Events can be enabled at the time the instance is created
			via:

				trace_instance=<name>,<system1>:<event1>,<system2>:<event2>

			Note, the "<system*>:" portion is optional if the event is
			unique.

				trace_instance=foo,sched:sched_switch,irq_handler_entry,initcall

			will enable the "sched_switch" event (note, the "sched:" is optional, and
			the same thing would happen if it was left off). The irq_handler_entry
			event, and all events under the "initcall" system.

			Flags can be added to the instance to modify its behavior when it is
			created. The flags are separated by '^'.

			The available flags are:

			    traceoff	- Have the tracing instance tracing disabled after it is created.
			    traceprintk	- Have trace_printk() write into this trace instance
					  (note, "printk" and "trace_printk" can also be used)

				trace_instance=foo^traceoff^traceprintk,sched,irq

			The flags must come before the defined events.

			If memory has been reserved (see memmap for x86), the instance
			can use that memory:

				memmap=12M$0x284500000 trace_instance=boot_map@0x284500000:12M

			The above will create a "boot_map" instance that uses the physical
			memory at 0x284500000 that is 12Megs. The per CPU buffers of that
			instance will be split up accordingly.

			Alternatively, the memory can be reserved by the reserve_mem option:

				reserve_mem=12M:4096:trace trace_instance=boot_map@trace

			This will reserve 12 megabytes at boot up with a 4096 byte alignment
			and place the ring buffer in this memory. Note that due to KASLR, the
			memory may not be the same location each time, which will not preserve
			the buffer content.

			Also note that the layout of the ring buffer data may change between
			kernel versions where the validator will fail and reset the ring buffer
			if the layout is not the same as the previous kernel.

			If the ring buffer is used for persistent bootups and has events enabled,
			it is recommend to disable tracing so that events from a previous boot do not
			mix with events of the current boot (unless you are debugging a random crash
			at boot up).

				reserve_mem=12M:4096:trace trace_instance=boot_map^traceoff^traceprintk@trace,sched,irq

			Note, saving the trace buffer across reboots does require that the system
			is set up to not wipe memory. For instance, CONFIG_RESET_ATTACK_MITIGATION
			can force a memory reset on boot which will clear any trace that was stored.
			This is just one of many ways that can clear memory. Make sure your system
			keeps the content of memory across reboots before relying on this option.

			NB: Both the mapped address and size must be page aligned for the architecture.

			See also Documentation/trace/debugging.rst


	trace_options=[option-list]
			[FTRACE] Enable or disable tracer options at boot.
			The option-list is a comma delimited list of options
			that can be enabled or disabled just as if you were
			to echo the option name into

			    /sys/kernel/tracing/trace_options

			For example, to enable stacktrace option (to dump the
			stack trace of each event), add to the command line:

			      trace_options=stacktrace

			See also Documentation/trace/ftrace.rst "trace options"
			section.

	trace_trigger=[trigger-list]
			[FTRACE] Add an event trigger on specific events.
			Set a trigger on top of a specific event, with an optional
			filter.

			The format is "trace_trigger=<event>.<trigger>[ if <filter>],..."
			Where more than one trigger may be specified that are comma delimited.

			For example:

			  trace_trigger="sched_switch.stacktrace if prev_state == 2"

			The above will enable the "stacktrace" trigger on the "sched_switch"
			event but only trigger it if the "prev_state" of the "sched_switch"
			event is "2" (TASK_UNINTERRUPTIBLE).

			See also "Event triggers" in Documentation/trace/events.rst


	traceoff_after_boot
			[FTRACE] Sometimes tracing is used to debug issues
			during the boot process. Since the trace buffer has a
			limited amount of storage, it may be prudent to
			disable tracing after the boot is finished, otherwise
			the critical information may be overwritten.  With this
			option, the main tracing buffer will be turned off at
			the end of the boot process.

	traceoff_on_warning
			[FTRACE] enable this option to disable tracing when a
			warning is hit. This turns off "tracing_on". Tracing can
			be enabled again by echoing '1' into the "tracing_on"
			file located in /sys/kernel/tracing/

			This option is useful, as it disables the trace before
			the WARNING dump is called, which prevents the trace to
			be filled with content caused by the warning output.

			This option can also be set at run time via the sysctl
			option:  kernel/traceoff_on_warning

	transparent_hugepage=
			[KNL]
			Format: [always|madvise|never]
			Can be used to control the default behavior of the system
			with respect to transparent hugepages.
			See Documentation/admin-guide/mm/transhuge.rst
			for more details.

	transparent_hugepage_shmem= [KNL]
			Format: [always|within_size|advise|never|deny|force]
			Can be used to control the hugepage allocation policy for
			the internal shmem mount.
			See Documentation/admin-guide/mm/transhuge.rst
			for more details.

	transparent_hugepage_tmpfs= [KNL]
			Format: [always|within_size|advise|never]
			Can be used to control the default hugepage allocation policy
			for the tmpfs mount.
			See Documentation/admin-guide/mm/transhuge.rst
			for more details.

	trusted.source=	[KEYS]
			Format: <string>
			This parameter identifies the trust source as a backend
			for trusted keys implementation. Supported trust
			sources:
			- "tpm"
			- "tee"
			- "caam"
			- "dcp"
			If not specified then it defaults to iterating through
			the trust source list starting with TPM and assigns the
			first trust source as a backend which is initialized
			successfully during iteration.

	trusted.rng=	[KEYS]
			Format: <string>
			The RNG used to generate key material for trusted keys.
			Can be one of:
			- "kernel"
			- the same value as trusted.source: "tpm" or "tee"
			- "default"
			If not specified, "default" is used. In this case,
			the RNG's choice is left to each individual trust source.

	trusted.dcp_use_otp_key
			This is intended to be used in combination with
			trusted.source=dcp and will select the DCP OTP key
			instead of the DCP UNIQUE key blob encryption.

	trusted.dcp_skip_zk_test
			This is intended to be used in combination with
			trusted.source=dcp and will disable the check if the
			blob key is all zeros. This is helpful for situations where
			having this key zero'ed is acceptable. E.g. in testing
			scenarios.

	tsa=		[X86] Control mitigation for Transient Scheduler
			Attacks on AMD CPUs. Search the following in your
			favourite search engine for more details:

			"Technical guidance for mitigating transient scheduler
			attacks".

			off		- disable the mitigation
			on		- enable the mitigation (default)
			user		- mitigate only user/kernel transitions
			vm		- mitigate only guest/host transitions


	tsc=		Disable clocksource stability checks for TSC.
			Format: <string>
			[x86] reliable: mark tsc clocksource as reliable, this
			disables clocksource verification at runtime, as well
			as the stability checks done at bootup.	Used to enable
			high-resolution timer mode on older hardware, and in
			virtualized environment.
			[x86] noirqtime: Do not use TSC to do irq accounting.
			Used to run time disable IRQ_TIME_ACCOUNTING on any
			platforms where RDTSC is slow and this accounting
			can add overhead.
			[x86] unstable: mark the TSC clocksource as unstable, this
			marks the TSC unconditionally unstable at bootup and
			avoids any further wobbles once the TSC watchdog notices.
			[x86] nowatchdog: disable clocksource watchdog. Used
			in situations with strict latency requirements (where
			interruptions from clocksource watchdog are not
			acceptable).
			[x86] recalibrate: force recalibration against a HW timer
			(HPET or PM timer) on systems whose TSC frequency was
			obtained from HW or FW using either an MSR or CPUID(0x15).
			Warn if the difference is more than 500 ppm.
			[x86] watchdog: Use TSC as the watchdog clocksource with
			which to check other HW timers (HPET or PM timer), but
			only on systems where TSC has been deemed trustworthy.
			This will be suppressed by an earlier tsc=nowatchdog and
			can be overridden by a later tsc=nowatchdog.  A console
			message will flag any such suppression or overriding.

	tsc_early_khz=  [X86,EARLY] Skip early TSC calibration and use the given
			value instead. Useful when the early TSC frequency discovery
			procedure is not reliable, such as on overclocked systems
			with CPUID.16h support and partial CPUID.15h support.
			Format: <unsigned int>

	tsx=		[X86] Control Transactional Synchronization
			Extensions (TSX) feature in Intel processors that
			support TSX control.

			This parameter controls the TSX feature. The options are:

			on	- Enable TSX on the system. Although there are
				mitigations for all known security vulnerabilities,
				TSX has been known to be an accelerator for
				several previous speculation-related CVEs, and
				so there may be unknown	security risks associated
				with leaving it enabled.

			off	- Disable TSX on the system. (Note that this
				option takes effect only on newer CPUs which are
				not vulnerable to MDS, i.e., have
				MSR_IA32_ARCH_CAPABILITIES.MDS_NO=1 and which get
				the new IA32_TSX_CTRL MSR through a microcode
				update. This new MSR allows for the reliable
				deactivation of the TSX functionality.)

			auto	- Disable TSX if X86_BUG_TAA is present,
				  otherwise enable TSX on the system.

			Not specifying this option is equivalent to tsx=off.

			See Documentation/admin-guide/hw-vuln/tsx_async_abort.rst
			for more details.

	tsx_async_abort= [X86,INTEL,EARLY] Control mitigation for the TSX Async
			Abort (TAA) vulnerability.

			Similar to Micro-architectural Data Sampling (MDS)
			certain CPUs that support Transactional
			Synchronization Extensions (TSX) are vulnerable to an
			exploit against CPU internal buffers which can forward
			information to a disclosure gadget under certain
			conditions.

			In vulnerable processors, the speculatively forwarded
			data can be used in a cache side channel attack, to
			access data to which the attacker does not have direct
			access.

			This parameter controls the TAA mitigation.  The
			options are:

			full       - Enable TAA mitigation on vulnerable CPUs
				     if TSX is enabled.

			full,nosmt - Enable TAA mitigation and disable SMT on
				     vulnerable CPUs. If TSX is disabled, SMT
				     is not disabled because CPU is not
				     vulnerable to cross-thread TAA attacks.
			off        - Unconditionally disable TAA mitigation

			On MDS-affected machines, tsx_async_abort=off can be
			prevented by an active MDS mitigation as both vulnerabilities
			are mitigated with the same mechanism so in order to disable
			this mitigation, you need to specify mds=off too.

			Not specifying this option is equivalent to
			tsx_async_abort=full.  On CPUs which are MDS affected
			and deploy MDS mitigation, TAA mitigation is not
			required and doesn't provide any additional
			mitigation.

			For details see:
			Documentation/admin-guide/hw-vuln/tsx_async_abort.rst

	turbografx.map[2|3]=	[HW,JOY]
			TurboGraFX parallel port interface
			Format:
			<port#>,<js1>,<js2>,<js3>,<js4>,<js5>,<js6>,<js7>
			See also Documentation/input/devices/joystick-parport.rst

	udbg-immortal	[PPC] When debugging early kernel crashes that
			happen after console_init() and before a proper
			console driver takes over, this boot options might
			help "seeing" what's going on.

	uhash_entries=	[KNL,NET]
			Set number of hash buckets for UDP/UDP-Lite connections

	uhci-hcd.ignore_oc=
			[USB] Ignore overcurrent events (default N).
			Some badly-designed motherboards generate lots of
			bogus events, for ports that aren't wired to
			anything.  Set this parameter to avoid log spamming.
			Note that genuine overcurrent events won't be
			reported either.

	unaligned_scalar_speed=
			[RISCV]
			Format: {slow | fast | unsupported}
			Allow skipping scalar unaligned access speed tests. This
			is useful for testing alternative code paths and to skip
			the tests in environments where they run too slowly. All
			CPUs must have the same scalar unaligned access speed.

	unaligned_vector_speed=
			[RISCV]
			Format: {slow | fast | unsupported}
			Allow skipping vector unaligned access speed tests. This
			is useful for testing alternative code paths and to skip
			the tests in environments where they run too slowly. All
			CPUs must have the same vector unaligned access speed.

	unknown_nmi_panic
			[X86] Cause panic on unknown NMI.

	unwind_debug	[X86-64,EARLY]
			Enable unwinder debug output.  This can be
			useful for debugging certain unwinder error
			conditions, including corrupt stacks and
			bad/missing unwinder metadata.

	usbcore.authorized_default=
			[USB] Default USB device authorization:
			(default -1 = authorized (same as 1),
			0 = not authorized, 1 = authorized, 2 = authorized
			if device connected to internal port)

	usbcore.autosuspend=
			[USB] The autosuspend time delay (in seconds) used
			for newly-detected USB devices (default 2).  This
			is the time required before an idle device will be
			autosuspended.  Devices for which the delay is set
			to a negative value won't be autosuspended at all.

	usbcore.usbfs_snoop=
			[USB] Set to log all usbfs traffic (default 0 = off).

	usbcore.usbfs_snoop_max=
			[USB] Maximum number of bytes to snoop in each URB
			(default = 65536).

	usbcore.blinkenlights=
			[USB] Set to cycle leds on hubs (default 0 = off).

	usbcore.old_scheme_first=
			[USB] Start with the old device initialization
			scheme (default 0 = off).

	usbcore.usbfs_memory_mb=
			[USB] Memory limit (in MB) for buffers allocated by
			usbfs (default = 16, 0 = max = 2047).

	usbcore.use_both_schemes=
			[USB] Try the other device initialization scheme
			if the first one fails (default 1 = enabled).

	usbcore.initial_descriptor_timeout=
			[USB] Specifies timeout for the initial 64-byte
			USB_REQ_GET_DESCRIPTOR request in milliseconds
			(default 5000 = 5.0 seconds).

	usbcore.nousb	[USB] Disable the USB subsystem

	usbcore.quirks=
			[USB] A list of quirk entries to augment the built-in
			usb core quirk list. List entries are separated by
			commas. Each entry has the form
			VendorID:ProductID:Flags. The IDs are 4-digit hex
			numbers and Flags is a set of letters. Each letter
			will change the built-in quirk; setting it if it is
			clear and clearing it if it is set. The letters have
			the following meanings:
				a = USB_QUIRK_STRING_FETCH_255 (string
					descriptors must not be fetched using
					a 255-byte read);
				b = USB_QUIRK_RESET_RESUME (device can't resume
					correctly so reset it instead);
				c = USB_QUIRK_NO_SET_INTF (device can't handle
					Set-Interface requests);
				d = USB_QUIRK_CONFIG_INTF_STRINGS (device can't
					handle its Configuration or Interface
					strings);
				e = USB_QUIRK_RESET (device can't be reset
					(e.g morph devices), don't use reset);
				f = USB_QUIRK_HONOR_BNUMINTERFACES (device has
					more interface descriptions than the
					bNumInterfaces count, and can't handle
					talking to these interfaces);
				g = USB_QUIRK_DELAY_INIT (device needs a pause
					during initialization, after we read
					the device descriptor);
				h = USB_QUIRK_LINEAR_UFRAME_INTR_BINTERVAL (For
					high speed and super speed interrupt
					endpoints, the USB 2.0 and USB 3.0 spec
					require the interval in microframes (1
					microframe = 125 microseconds) to be
					calculated as interval = 2 ^
					(bInterval-1).
					Devices with this quirk report their
					bInterval as the result of this
					calculation instead of the exponent
					variable used in the calculation);
				i = USB_QUIRK_DEVICE_QUALIFIER (device can't
					handle device_qualifier descriptor
					requests);
				j = USB_QUIRK_IGNORE_REMOTE_WAKEUP (device
					generates spurious wakeup, ignore
					remote wakeup capability);
				k = USB_QUIRK_NO_LPM (device can't handle Link
					Power Management);
				l = USB_QUIRK_LINEAR_FRAME_INTR_BINTERVAL
					(Device reports its bInterval as linear
					frames instead of the USB 2.0
					calculation);
				m = USB_QUIRK_DISCONNECT_SUSPEND (Device needs
					to be disconnected before suspend to
					prevent spurious wakeup);
				n = USB_QUIRK_DELAY_CTRL_MSG (Device needs a
					pause after every control message);
				o = USB_QUIRK_HUB_SLOW_RESET (Hub needs extra
					delay after resetting its port);
				p = USB_QUIRK_SHORT_SET_ADDRESS_REQ_TIMEOUT
					(Reduce timeout of the SET_ADDRESS
					request from 5000 ms to 500 ms);
				q = USB_QUIRK_FORCE_ONE_CONFIG (Device
					claims zero configurations,
					forcing to 1);
				r = USB_QUIRK_WINDOWS_CONFIG_REQ_SIZE (Device
					fails during initialization when asked for
					9-bytes configuration descriptor request.
					Ask for 255-bytes request instead to mirror
					Windows' behavior);
			Example: quirks=0781:5580:bk,0a5c:5834:gij

	usbhid.mousepoll=
			[USBHID] The interval which mice are to be polled at.

	usbhid.jspoll=
			[USBHID] The interval which joysticks are to be polled at.

	usbhid.kbpoll=
			[USBHID] The interval which keyboards are to be polled at.

	usb-storage.delay_use=
			[UMS] The delay in seconds before a new device is
			scanned for Logical Units (default 1).
			Optionally the delay in milliseconds if the value has
			suffix with "ms".
			Example: delay_use=2567ms

	usb-storage.quirks=
			[UMS] A list of quirks entries to supplement or
			override the built-in unusual_devs list.  List
			entries are separated by commas.  Each entry has
			the form VID:PID:Flags where VID and PID are Vendor
			and Product ID values (4-digit hex numbers) and
			Flags is a set of characters, each corresponding
			to a common usb-storage quirk flag as follows:
				a = SANE_SENSE (collect more than 18 bytes
					of sense data, not on uas);
				b = BAD_SENSE (don't collect more than 18
					bytes of sense data, not on uas);
				c = FIX_CAPACITY (decrease the reported
					device capacity by one sector);
				d = NO_READ_DISC_INFO (don't use
					READ_DISC_INFO command, not on uas);
				e = NO_READ_CAPACITY_16 (don't use
					READ_CAPACITY_16 command);
				f = NO_REPORT_OPCODES (don't use report opcodes
					command, uas only);
				g = MAX_SECTORS_240 (don't transfer more than
					240 sectors at a time, uas only);
				h = CAPACITY_HEURISTICS (decrease the
					reported device capacity by one
					sector if the number is odd);
				i = IGNORE_DEVICE (don't bind to this
					device);
				j = NO_REPORT_LUNS (don't use report luns
					command, uas only);
				k = NO_SAME (do not use WRITE_SAME, uas only)
				l = NOT_LOCKABLE (don't try to lock and
					unlock ejectable media, not on uas);
				m = MAX_SECTORS_64 (don't transfer more
					than 64 sectors = 32 KB at a time,
					not on uas);
				n = INITIAL_READ10 (force a retry of the
					initial READ(10) command, not on uas);
				o = CAPACITY_OK (accept the capacity
					reported by the device, not on uas);
				p = WRITE_CACHE (the device cache is ON
					by default, not on uas);
				r = IGNORE_RESIDUE (the device reports
					bogus residue values, not on uas);
				s = SINGLE_LUN (the device has only one
					Logical Unit);
				t = NO_ATA_1X (don't allow ATA(12) and ATA(16)
					commands, uas only);
				u = IGNORE_UAS (don't bind to the uas driver);
				w = NO_WP_DETECT (don't test whether the
					medium is write-protected).
				y = ALWAYS_SYNC (issue a SYNCHRONIZE_CACHE
					even if the device claims no cache,
					not on uas)
			Example: quirks=0419:aaf5:rl,0421:0433:rc

	user_debug=	[KNL,ARM]
			Format: <int>
			See arch/arm/Kconfig.debug help text.
				 1 - undefined instruction events
				 2 - system calls
				 4 - invalid data aborts
				 8 - SIGSEGV faults
				16 - SIGBUS faults
			Example: user_debug=31

	vdso=		[X86,SH,SPARC]
			On X86_32, this is an alias for vdso32=.  Otherwise:

			vdso=1: enable VDSO (the default)
			vdso=0: disable VDSO mapping

	vdso32=		[X86] Control the 32-bit vDSO
			vdso32=1: enable 32-bit VDSO
			vdso32=0 or vdso32=2: disable 32-bit VDSO

			See the help text for CONFIG_COMPAT_VDSO for more
			details.  If CONFIG_COMPAT_VDSO is set, the default is
			vdso32=0; otherwise, the default is vdso32=1.

			For compatibility with older kernels, vdso32=2 is an
			alias for vdso32=0.

			Try vdso32=0 if you encounter an error that says:
			dl_main: Assertion `(void *) ph->p_vaddr == _rtld_local._dl_sysinfo_dso' failed!

	video=		[FB,EARLY] Frame buffer configuration
			See Documentation/fb/modedb.rst.

	video.brightness_switch_enabled= [ACPI]
			Format: [0|1]
			If set to 1, on receiving an ACPI notify event
			generated by hotkey, video driver will adjust brightness
			level and then send out the event to user space through
			the allocated input device. If set to 0, video driver
			will only send out the event without touching backlight
			brightness level.
			default: 1

	virtio_mmio.device=
			[VMMIO] Memory mapped virtio (platform) device.

				<size>@<baseaddr>:<irq>[:<id>]
			where:
				<size>     := size (can use standard suffixes
						like K, M and G)
				<baseaddr> := physical base address
				<irq>      := interrupt number (as passed to
						request_irq())
				<id>       := (optional) platform device id
			example:
				virtio_mmio.device=1K@0x100b0000:48:7

			Can be used multiple times for multiple devices.

	vga=		[BOOT,X86-32] Select a particular video mode
			See Documentation/arch/x86/boot.rst and
			Documentation/admin-guide/svga.rst.
			Use vga=ask for menu.
			This is actually a boot loader parameter; the value is
			passed to the kernel using a special protocol.

	vm_debug[=options]	[KNL] Available with CONFIG_DEBUG_VM=y.
			May slow down system boot speed, especially when
			enabled on systems with a large amount of memory.
			All options are enabled by default, and this
			interface is meant to allow for selectively
			enabling or disabling specific virtual memory
			debugging features.

			Available options are:
			  P	Enable page structure init time poisoning
			  -	Disable all of the above options

	vmalloc=nn[KMG]	[KNL,BOOT,EARLY] Forces the vmalloc area to have an
			exact size of <nn>. This can be used to increase
			the minimum size (128MB on x86, arm32 platforms).
			It can also be used to decrease the size and leave more room
			for directly mapped kernel RAM. Note that this parameter does
			not exist on many other platforms (including arm64, alpha,
			loongarch, arc, csky, hexagon, microblaze, mips, nios2, openrisc,
			parisc, m64k, powerpc, riscv, sh, um, xtensa, s390, sparc).

	vmcp_cma=nn[MG]	[KNL,S390,EARLY]
			Sets the memory size reserved for contiguous memory
			allocations for the vmcp device driver.

	vmhalt=		[KNL,S390] Perform z/VM CP command after system halt.
			Format: <command>

	vmpanic=	[KNL,S390] Perform z/VM CP command after kernel panic.
			Format: <command>

	vmpoff=		[KNL,S390] Perform z/VM CP command after power off.
			Format: <command>

	vmscape=	[X86] Controls mitigation for VMscape attacks.
			VMscape attacks can leak information from a userspace
			hypervisor to a guest via speculative side-channels.

			off		- disable the mitigation
			ibpb		- use Indirect Branch Prediction Barrier
					  (IBPB) mitigation (default)
			force		- force vulnerability detection even on
					  unaffected processors

	vsyscall=	[X86-64,EARLY]
			Controls the behavior of vsyscalls (i.e. calls to
			fixed addresses of 0xffffffffff600x00 from legacy
			code).  Most statically-linked binaries and older
			versions of glibc use these calls.  Because these
			functions are at fixed addresses, they make nice
			targets for exploits that can control RIP.

			emulate     Vsyscalls turn into traps and are emulated
			            reasonably safely.  The vsyscall page is
				    readable.

			xonly       [default] Vsyscalls turn into traps and are
			            emulated reasonably safely.  The vsyscall
				    page is not readable.

			none        Vsyscalls don't work at all.  This makes
			            them quite hard to use for exploits but
			            might break your system.

	vt.color=	[VT] Default text color.
			Format: 0xYX, X = foreground, Y = background.
			Default: 0x07 = light gray on black.

	vt.cur_default=	[VT] Default cursor shape.
			Format: 0xCCBBAA, where AA, BB, and CC are the same as
			the parameters of the <Esc>[?A;B;Cc escape sequence;
			see vga-softcursor.rst. Default: 2 = underline.

	vt.default_blu=	[VT]
			Format: <blue0>,<blue1>,<blue2>,...,<blue15>
			Change the default blue palette of the console.
			This is a 16-member array composed of values
			ranging from 0-255.

	vt.default_grn=	[VT]
			Format: <green0>,<green1>,<green2>,...,<green15>
			Change the default green palette of the console.
			This is a 16-member array composed of values
			ranging from 0-255.

	vt.default_red=	[VT]
			Format: <red0>,<red1>,<red2>,...,<red15>
			Change the default red palette of the console.
			This is a 16-member array composed of values
			ranging from 0-255.

	vt.default_utf8=
			[VT]
			Format=<0|1>
			Set system-wide default UTF-8 mode for all tty's.
			Default is 1, i.e. UTF-8 mode is enabled for all
			newly opened terminals.

	vt.global_cursor_default=
			[VT]
			Format=<-1|0|1>
			Set system-wide default for whether a cursor
			is shown on new VTs. Default is -1,
			i.e. cursors will be created by default unless
			overridden by individual drivers. 0 will hide
			cursors, 1 will display them.

	vt.italic=	[VT] Default color for italic text; 0-15.
			Default: 2 = green.

	vt.underline=	[VT] Default color for underlined text; 0-15.
			Default: 3 = cyan.

	watchdog timers	[HW,WDT] For information on watchdog timers,
			see Documentation/watchdog/watchdog-parameters.rst
			or other driver-specific files in the
			Documentation/watchdog/ directory.

	watchdog_thresh=
			[KNL]
			Set the hard lockup detector stall duration
			threshold in seconds. The soft lockup detector
			threshold is set to twice the value. A value of 0
			disables both lockup detectors. Default is 10
			seconds.

	workqueue.unbound_cpus=
			[KNL,SMP] Specify to constrain one or some CPUs
			to use in unbound workqueues.
			Format: <cpu-list>
			By default, all online CPUs are available for
			unbound workqueues.

	workqueue.watchdog_thresh=
			If CONFIG_WQ_WATCHDOG is configured, workqueue can
			warn stall conditions and dump internal state to
			help debugging.  0 disables workqueue stall
			detection; otherwise, it's the stall threshold
			duration in seconds.  The default value is 30 and
			it can be updated at runtime by writing to the
			corresponding sysfs file.

	workqueue.panic_on_stall=<uint>
			Panic when workqueue stall is detected by
			CONFIG_WQ_WATCHDOG. It sets the number times of the
			stall to trigger panic.

			The default is 0, which disables the panic on stall.

	workqueue.cpu_intensive_thresh_us=
			Per-cpu work items which run for longer than this
			threshold are automatically considered CPU intensive
			and excluded from concurrency management to prevent
			them from noticeably delaying other per-cpu work
			items. Default is 10000 (10ms).

			If CONFIG_WQ_CPU_INTENSIVE_REPORT is set, the kernel
			will report the work functions which violate this
			threshold repeatedly. They are likely good
			candidates for using WQ_UNBOUND workqueues instead.

	workqueue.cpu_intensive_warning_thresh=<uint>
			If CONFIG_WQ_CPU_INTENSIVE_REPORT is set, the kernel
			will report the work functions which violate the
			intensive_threshold_us repeatedly. In order to prevent
			spurious warnings, start printing only after a work
			function has violated this threshold number of times.

			The default is 4 times. 0 disables the warning.

	workqueue.power_efficient
			Per-cpu workqueues are generally preferred because
			they show better performance thanks to cache
			locality; unfortunately, per-cpu workqueues tend to
			be more power hungry than unbound workqueues.

			Enabling this makes the per-cpu workqueues which
			were observed to contribute significantly to power
			consumption unbound, leading to measurably lower
			power usage at the cost of small performance
			overhead.

			The default value of this parameter is determined by
			the config option CONFIG_WQ_POWER_EFFICIENT_DEFAULT.

        workqueue.default_affinity_scope=
			Select the default affinity scope to use for unbound
			workqueues. Can be one of "cpu", "smt", "cache",
			"numa" and "system". Default is "cache". For more
			information, see the Affinity Scopes section in
			Documentation/core-api/workqueue.rst.

			This can be changed after boot by writing to the
			matching /sys/module/workqueue/parameters file. All
			workqueues with the "default" affinity scope will be
			updated accordingly.

	workqueue.debug_force_rr_cpu
			Workqueue used to implicitly guarantee that work
			items queued without explicit CPU specified are put
			on the local CPU.  This guarantee is no longer true
			and while local CPU is still preferred work items
			may be put on foreign CPUs.  This debug option
			forces round-robin CPU selection to flush out
			usages which depend on the now broken guarantee.
			When enabled, memory and cache locality will be
			impacted.

	writecombine=	[LOONGARCH,EARLY] Control the MAT (Memory Access
			Type) of ioremap_wc().

			on   - Enable writecombine, use WUC for ioremap_wc()
			off  - Disable writecombine, use SUC for ioremap_wc()

	x2apic_phys	[X86-64,APIC,EARLY] Use x2apic physical mode instead of
			default x2apic cluster mode on platforms
			supporting x2apic.

	xen_512gb_limit		[KNL,X86-64,XEN]
			Restricts the kernel running paravirtualized under Xen
			to use only up to 512 GB of RAM. The reason to do so is
			crash analysis tools and Xen tools for doing domain
			save/restore/migration must be enabled to handle larger
			domains.

	xen_emul_unplug=		[HW,X86,XEN,EARLY]
			Unplug Xen emulated devices
			Format: [unplug0,][unplug1]
			ide-disks -- unplug primary master IDE devices
			aux-ide-disks -- unplug non-primary-master IDE devices
			nics -- unplug network devices
			all -- unplug all emulated devices (NICs and IDE disks)
			unnecessary -- unplugging emulated devices is
				unnecessary even if the host did not respond to
				the unplug protocol
			never -- do not unplug even if version check succeeds

	xen_legacy_crash	[X86,XEN,EARLY]
			Crash from Xen panic notifier, without executing late
			panic() code such as dumping handler.

	xen_mc_debug	[X86,XEN,EARLY]
			Enable multicall debugging when running as a Xen PV guest.
			Enabling this feature will reduce performance a little
			bit, so it should only be enabled for obtaining extended
			debug data in case of multicall errors.

	xen_msr_safe=	[X86,XEN,EARLY]
			Format: <bool>
			Select whether to always use non-faulting (safe) MSR
			access functions when running as Xen PV guest. The
			default value is controlled by CONFIG_XEN_PV_MSR_SAFE.

	xen_nopv	[X86]
			Disables the PV optimizations forcing the HVM guest to
			run as generic HVM guest with no PV drivers.
			This option is obsoleted by the "nopv" option, which
			has equivalent effect for XEN platform.

	xen_no_vector_callback
			[KNL,X86,XEN,EARLY] Disable the vector callback for Xen
			event channel interrupts.

	xen_scrub_pages=	[XEN]
			Boolean option to control scrubbing pages before giving them back
			to Xen, for use by other domains. Can be also changed at runtime
			with /sys/devices/system/xen_memory/xen_memory0/scrub_pages.
			Default value controlled with CONFIG_XEN_SCRUB_PAGES_DEFAULT.

	xen_timer_slop=	[X86-64,XEN,EARLY]
			Set the timer slop (in nanoseconds) for the virtual Xen
			timers (default is 100000). This adjusts the minimum
			delta of virtualized Xen timers, where lower values
			improve timer resolution at the expense of processing
			more timer interrupts.

	xen.balloon_boot_timeout= [XEN]
			The time (in seconds) to wait before giving up to boot
			in case initial ballooning fails to free enough memory.
			Applies only when running as HVM or PVH guest and
			started with less memory configured than allowed at
			max. Default is 180.

	xen.event_eoi_delay=	[XEN]
			How long to delay EOI handling in case of event
			storms (jiffies). Default is 10.

	xen.event_loop_timeout=	[XEN]
			After which time (jiffies) the event handling loop
			should start to delay EOI handling. Default is 2.

	xen.fifo_events=	[XEN]
			Boolean parameter to disable using fifo event handling
			even if available. Normally fifo event handling is
			preferred over the 2-level event handling, as it is
			fairer and the number of possible event channels is
			much higher. Default is on (use fifo events).

	xirc2ps_cs=	[NET,PCMCIA]
			Format:
			<irq>,<irq_mask>,<io>,<full_duplex>,<do_sound>,<lockup_hack>[,<irq2>[,<irq3>[,<irq4>]]]

	xive=		[PPC]
			By default on POWER9 and above, the kernel will
			natively use the XIVE interrupt controller. This option
			allows the fallback firmware mode to be used:

			off       Fallback to firmware control of XIVE interrupt
				  controller on both pseries and powernv
				  platforms. Only useful on POWER9 and above.

	xive.store-eoi=off	[PPC]
			By default on POWER10 and above, the kernel will use
			stores for EOI handling when the XIVE interrupt mode
			is active. This option allows the XIVE driver to use
			loads instead, as on POWER9.

	xhci-hcd.quirks		[USB,KNL]
			A hex value specifying bitmask with supplemental xhci
			host controller quirks. Meaning of each bit can be
			consulted in header drivers/usb/host/xhci.h.

	xmon		[PPC,EARLY]
			Format: { early | on | rw | ro | off }
			Controls if xmon debugger is enabled. Default is off.
			Passing only "xmon" is equivalent to "xmon=early".
			early	Call xmon as early as possible on boot; xmon
				debugger is called from setup_arch().
			on	xmon debugger hooks will be installed so xmon
				is only called on a kernel crash. Default mode,
				i.e. either "ro" or "rw" mode, is controlled
				with CONFIG_XMON_DEFAULT_RO_MODE.
			rw	xmon debugger hooks will be installed so xmon
				is called only on a kernel crash, mode is write,
				meaning SPR registers, memory and, other data
				can be written using xmon commands.
			ro 	same as "rw" option above but SPR registers,
				memory, and other data can't be written using
				xmon commands.
			off	xmon is disabled.

---

### Documentation Admin Guide Kernel Per CPU Kthreads (`Documentation/admin-guide/kernel-per-CPU-kthreads.rst`)

==========================================
Reducing OS jitter due to per-cpu kthreads
==========================================

This document lists per-CPU kthreads in the Linux kernel and presents
options to control their OS jitter.  Note that non-per-CPU kthreads are
not listed here.  To reduce OS jitter from non-per-CPU kthreads, bind
them to a "housekeeping" CPU dedicated to such work.

References
==========

-	Documentation/core-api/irq/irq-affinity.rst:  Binding interrupts to sets of CPUs.

-	Documentation/admin-guide/cgroup-v1:  Using cgroups to bind tasks to sets of CPUs.

-	man taskset:  Using the taskset command to bind tasks to sets
	of CPUs.

-	man sched_setaffinity:  Using the sched_setaffinity() system
	call to bind tasks to sets of CPUs.

-	/sys/devices/system/cpu/cpuN/online:  Control CPU N's hotplug state,
	writing "0" to offline and "1" to online.

-	In order to locate kernel-generated OS jitter on CPU N:

		cd /sys/kernel/tracing
		echo 1 > max_graph_depth # Increase the "1" for more detail
		echo function_graph > current_tracer
		# run workload
		cat per_cpu/cpuN/trace

kthreads
========

Name:
  ehca_comp/%u

Purpose:
  Periodically process Infiniband-related work.

To reduce its OS jitter, do any of the following:

1.	Don't use eHCA Infiniband hardware, instead choosing hardware
	that does not require per-CPU kthreads.  This will prevent these
	kthreads from being created in the first place.  (This will
	work for most people, as this hardware, though important, is
	relatively old and is produced in relatively low unit volumes.)
2.	Do all eHCA-Infiniband-related work on other CPUs, including
	interrupts.
3.	Rework the eHCA driver so that its per-CPU kthreads are
	provisioned only on selected CPUs.


Name:
  irq/%d-%s

Purpose:
  Handle threaded interrupts.

To reduce its OS jitter, do the following:

1.	Use irq affinity to force the irq threads to execute on
	some other CPU.

Name:
  kcmtpd_ctr_%d

Purpose:
  Handle Bluetooth work.

To reduce its OS jitter, do one of the following:

1.	Don't use Bluetooth, in which case these kthreads won't be
	created in the first place.
2.	Use irq affinity to force Bluetooth-related interrupts to
	occur on some other CPU and furthermore initiate all
	Bluetooth activity on some other CPU.

Name:
  ksoftirqd/%u

Purpose:
  Execute softirq handlers when threaded or when under heavy load.

To reduce its OS jitter, each softirq vector must be handled
separately as follows:

TIMER_SOFTIRQ
-------------

Do all of the following:

1.	To the extent possible, keep the CPU out of the kernel when it
	is non-idle, for example, by avoiding system calls and by forcing
	both kernel threads and interrupts to execute elsewhere.
2.	Build with CONFIG_HOTPLUG_CPU=y.  After boot completes, force
	the CPU offline, then bring it back online.  This forces
	recurring timers to migrate elsewhere.	If you are concerned
	with multiple CPUs, force them all offline before bringing the
	first one back online.  Once you have onlined the CPUs in question,
	do not offline any other CPUs, because doing so could force the
	timer back onto one of the CPUs in question.

NET_TX_SOFTIRQ and NET_RX_SOFTIRQ
---------------------------------

Do all of the following:

1.	Force networking interrupts onto other CPUs.
2.	Initiate any network I/O on other CPUs.
3.	Once your application has started, prevent CPU-hotplug operations
	from being initiated from tasks that might run on the CPU to
	be de-jittered.  (It is OK to force this CPU offline and then
	bring it back online before you start your application.)

BLOCK_SOFTIRQ
-------------

Do all of the following:

1.	Force block-device interrupts onto some other CPU.
2.	Initiate any block I/O on other CPUs.
3.	Once your application has started, prevent CPU-hotplug operations
	from being initiated from tasks that might run on the CPU to
	be de-jittered.  (It is OK to force this CPU offline and then
	bring it back online before you start your application.)

IRQ_POLL_SOFTIRQ
----------------

Do all of the following:

1.	Force block-device interrupts onto some other CPU.
2.	Initiate any block I/O and block-I/O polling on other CPUs.
3.	Once your application has started, prevent CPU-hotplug operations
	from being initiated from tasks that might run on the CPU to
	be de-jittered.  (It is OK to force this CPU offline and then
	bring it back online before you start your application.)

TASKLET_SOFTIRQ
---------------

Do one or more of the following:

1.	Avoid use of drivers that use tasklets.  (Such drivers will contain
	calls to things like tasklet_schedule().)
2.	Convert all drivers that you must use from tasklets to workqueues.
3.	Force interrupts for drivers using tasklets onto other CPUs,
	and also do I/O involving these drivers on other CPUs.

SCHED_SOFTIRQ
-------------

Do all of the following:

1.	Avoid sending scheduler IPIs to the CPU to be de-jittered,
	for example, ensure that at most one runnable kthread is present
	on that CPU.  If a thread that expects to run on the de-jittered
	CPU awakens, the scheduler will send an IPI that can result in
	a subsequent SCHED_SOFTIRQ.
2.	CONFIG_NO_HZ_FULL=y and ensure that the CPU to be de-jittered
	is marked as an adaptive-ticks CPU using the "nohz_full="
	boot parameter.  This reduces the number of scheduler-clock
	interrupts that the de-jittered CPU receives, minimizing its
	chances of being selected to do the load balancing work that
	runs in SCHED_SOFTIRQ context.
3.	To the extent possible, keep the CPU out of the kernel when it
	is non-idle, for example, by avoiding system calls and by
	forcing both kernel threads and interrupts to execute elsewhere.
	This further reduces the number of scheduler-clock interrupts
	received by the de-jittered CPU.

HRTIMER_SOFTIRQ
---------------

Do all of the following:

1.	To the extent possible, keep the CPU out of the kernel when it
	is non-idle.  For example, avoid system calls and force both
	kernel threads and interrupts to execute elsewhere.
2.	Build with CONFIG_HOTPLUG_CPU=y.  Once boot completes, force the
	CPU offline, then bring it back online.  This forces recurring
	timers to migrate elsewhere.  If you are concerned with multiple
	CPUs, force them all offline before bringing the first one
	back online.  Once you have onlined the CPUs in question, do not
	offline any other CPUs, because doing so could force the timer
	back onto one of the CPUs in question.

RCU_SOFTIRQ
-----------

Do at least one of the following:

1.	Offload callbacks and keep the CPU in either dyntick-idle or
	adaptive-ticks state by doing all of the following:

	a.	CONFIG_NO_HZ_FULL=y and ensure that the CPU to be
		de-jittered is marked as an adaptive-ticks CPU using the
		"nohz_full=" boot parameter.  Bind the rcuo kthreads to
		housekeeping CPUs, which can tolerate OS jitter.
	b.	To the extent possible, keep the CPU out of the kernel
		when it is non-idle, for example, by avoiding system
		calls and by forcing both kernel threads and interrupts
		to execute elsewhere.

2.	Enable RCU to do its processing remotely via dyntick-idle by
	doing all of the following:

	a.	Build with CONFIG_NO_HZ=y.
	b.	Ensure that the CPU goes idle frequently, allowing other
		CPUs to detect that it has passed through an RCU quiescent
		state.	If the kernel is built with CONFIG_NO_HZ_FULL=y,
		userspace execution also allows other CPUs to detect that
		the CPU in question has passed through a quiescent state.
	c.	To the extent possible, keep the CPU out of the kernel
		when it is non-idle, for example, by avoiding system
		calls and by forcing both kernel threads and interrupts
		to execute elsewhere.

Name:
  kworker/%u:%d%s (cpu, id, priority)

Purpose:
  Execute workqueue requests

To reduce its OS jitter, do any of the following:

1.	Run your workload at a real-time priority, which will allow
	preempting the kworker daemons.
2.	A given workqueue can be made visible in the sysfs filesystem
	by passing the WQ_SYSFS to that workqueue's alloc_workqueue().
	Such a workqueue can be confined to a given subset of the
	CPUs using the ``/sys/devices/virtual/workqueue/*/cpumask`` sysfs
	files.	The set of WQ_SYSFS workqueues can be displayed using
	"ls /sys/devices/virtual/workqueue".  That said, the workqueues
	maintainer would like to caution people against indiscriminately
	sprinkling WQ_SYSFS across all the workqueues.	The reason for
	caution is that it is easy to add WQ_SYSFS, but because sysfs is
	part of the formal user/kernel API, it can be nearly impossible
	to remove it, even if its addition was a mistake.
3.	Do any of the following needed to avoid jitter that your
	application cannot tolerate:

	a.	Avoid using oprofile, thus avoiding OS jitter from
		wq_sync_buffer().
	b.	Limit your CPU frequency so that a CPU-frequency
		governor is not required, possibly enlisting the aid of
		special heatsinks or other cooling technologies.  If done
		correctly, and if you CPU architecture permits, you should
		be able to build your kernel with CONFIG_CPU_FREQ=n to
		avoid the CPU-frequency governor periodically running
		on each CPU, including cs_dbs_timer() and od_dbs_timer().

		WARNING:  Please check your CPU specifications to
		make sure that this is safe on your particular system.
	c.	As of v3.18, Christoph Lameter's on-demand vmstat workers
		commit prevents OS jitter due to vmstat_update() on
		CONFIG_SMP=y systems.  Before v3.18, is not possible
		to entirely get rid of the OS jitter, but you can
		decrease its frequency by writing a large value to
		/proc/sys/vm/stat_interval.  The default value is HZ,
		for an interval of one second.	Of course, larger values
		will make your virtual-memory statistics update more
		slowly.  Of course, you can also run your workload at
		a real-time priority, thus preempting vmstat_update(),
		but if your workload is CPU-bound, this is a bad idea.
		However, there is an RFC patch from Christoph Lameter
		(based on an earlier one from Gilad Ben-Yossef) that
		reduces or even eliminates vmstat overhead for some
		workloads at https://lore.kernel.org/r/00000140e9dfd6bd-40db3d4f-c1be-434f-8132-7820f81bb586-000000@email.amazonses.com.
	d.	If running on high-end powerpc servers, build with
		CONFIG_PPC_RTAS_DAEMON=n.  This prevents the RTAS
		daemon from running on each CPU every second or so.
		(This will require editing Kconfig files and will defeat
		this platform's RAS functionality.)  This avoids jitter
		due to the rtas_event_scan() function.
		WARNING:  Please check your CPU specifications to
		make sure that this is safe on your particular system.
	e.	If running on PowerMAC, build your kernel with
		CONFIG_PMAC_RACKMETER=n to disable the CPU-meter,
		avoiding OS jitter from rackmeter_do_timer().

Name:
  rcuc/%u

Purpose:
  Execute RCU callbacks in CONFIG_RCU_BOOST=y kernels.

To reduce its OS jitter, do at least one of the following:

1.	Build the kernel with CONFIG_PREEMPT=n.  This prevents these
	kthreads from being created in the first place, and also obviates
	the need for RCU priority boosting.  This approach is feasible
	for workloads that do not require high degrees of responsiveness.
2.	Build the kernel with CONFIG_RCU_BOOST=n.  This prevents these
	kthreads from being created in the first place.  This approach
	is feasible only if your workload never requires RCU priority
	boosting, for example, if you ensure frequent idle time on all
	CPUs that might execute within the kernel.
3.	Build with CONFIG_RCU_NOCB_CPU=y and boot with the rcu_nocbs=
	boot parameter offloading RCU callbacks from all CPUs susceptible
	to OS jitter.  This approach prevents the rcuc/%u kthreads from
	having any work to do, so that they are never awakened.
4.	Ensure that the CPU never enters the kernel, and, in particular,
	avoid initiating any CPU hotplug operations on this CPU.  This is
	another way of preventing any callbacks from being queued on the
	CPU, again preventing the rcuc/%u kthreads from having any work
	to do.

Name:
  rcuop/%d, rcuos/%d, and rcuog/%d

Purpose:
  Offload RCU callbacks from the corresponding CPU.

To reduce its OS jitter, do at least one of the following:

1.	Use affinity, cgroups, or other mechanism to force these kthreads
	to execute on some other CPU.
2.	Build with CONFIG_RCU_NOCB_CPU=n, which will prevent these
	kthreads from being created in the first place.  However, please
	note that this will not eliminate OS jitter, but will instead
	shift it to RCU_SOFTIRQ.

---

### Documentation Admin Guide Lcd Panel Cgram (`Documentation/admin-guide/lcd-panel-cgram.rst`)

======================================
Parallel port LCD/Keypad Panel support
======================================

Some LCDs allow you to define up to 8 characters, mapped to ASCII
characters 0 to 7. The escape code to define a new character is
'\e[LG' followed by one digit from 0 to 7, representing the character
number, and up to 8 couples of hex digits terminated by a semi-colon
(';'). Each couple of digits represents a line, with 1-bits for each
illuminated pixel with LSB on the right. Lines are numbered from the
top of the character to the bottom. On a 5x7 matrix, only the 5 lower
bits of the 7 first bytes are used for each character. If the string
is incomplete, only complete lines will be redefined. Here are some
examples::

  printf "\e[LG0010101050D1F0C04;"  => 0 = [enter]
  printf "\e[LG1040E1F0000000000;"  => 1 = [up]
  printf "\e[LG2000000001F0E0400;"  => 2 = [down]
  printf "\e[LG3040E1F001F0E0400;"  => 3 = [up-down]
  printf "\e[LG40002060E1E0E0602;"  => 4 = [left]
  printf "\e[LG500080C0E0F0E0C08;"  => 5 = [right]
  printf "\e[LG60016051516141400;"  => 6 = "IP"

  printf "\e[LG00103071F1F070301;"  => big speaker
  printf "\e[LG00002061E1E060200;"  => small speaker

Willy

---

### Documentation Admin Guide Ldm (`Documentation/admin-guide/ldm.rst`)

==========================================
LDM - Logical Disk Manager (Dynamic Disks)
==========================================

:Author: Originally Written by FlatCap - Richard Russon <ldm@flatcap.org>.
:Last Updated: Anton Altaparmakov on 30 March 2007 for Windows Vista.

Overview
--------

Windows 2000, XP, and Vista use a new partitioning scheme.  It is a complete
replacement for the MSDOS style partitions.  It stores its information in a
1MiB journalled database at the end of the physical disk.  The size of
partitions is limited only by disk space.  The maximum number of partitions is
nearly 2000.

Any partitions created under the LDM are called "Dynamic Disks".  There are no
longer any primary or extended partitions.  Normal MSDOS style partitions are
now known as Basic Disks.

If you wish to use Spanned, Striped, Mirrored or RAID 5 Volumes, you must use
Dynamic Disks.  The journalling allows Windows to make changes to these
partitions and filesystems without the need to reboot.

Once the LDM driver has divided up the disk, you can use the MD driver to
assemble any multi-partition volumes, e.g.  Stripes, RAID5.

To prevent legacy applications from repartitioning the disk, the LDM creates a
dummy MSDOS partition containing one disk-sized partition.  This is what is
supported with the Linux LDM driver.

A newer approach that has been implemented with Vista is to put LDM on top of a
GPT label disk.  This is not supported by the Linux LDM driver yet.


Example
-------

Below we have a 50MiB disk, divided into seven partitions.

.. note::

   The missing 1MiB at the end of the disk is where the LDM database is
   stored.

+-------++--------------+---------+-----++--------------+---------+----+
|Device || Offset Bytes | Sectors | MiB || Size   Bytes | Sectors | MiB|
+=======++==============+=========+=====++==============+=========+====+
|hda    ||            0 |       0 |   0 ||     52428800 |  102400 |  50|
+-------++--------------+---------+-----++--------------+---------+----+
|hda1   ||     51380224 |  100352 |  49 ||      1048576 |    2048 |   1|
+-------++--------------+---------+-----++--------------+---------+----+
|hda2   ||        16384 |      32 |   0 ||      6979584 |   13632 |   6|
+-------++--------------+---------+-----++--------------+---------+----+
|hda3   ||      6995968 |   13664 |   6 ||     10485760 |   20480 |  10|
+-------++--------------+---------+-----++--------------+---------+----+
|hda4   ||     17481728 |   34144 |  16 ||      4194304 |    8192 |   4|
+-------++--------------+---------+-----++--------------+---------+----+
|hda5   ||     21676032 |   42336 |  20 ||      5242880 |   10240 |   5|
+-------++--------------+---------+-----++--------------+---------+----+
|hda6   ||     26918912 |   52576 |  25 ||     10485760 |   20480 |  10|
+-------++--------------+---------+-----++--------------+---------+----+
|hda7   ||     37404672 |   73056 |  35 ||     13959168 |   27264 |  13|
+-------++--------------+---------+-----++--------------+---------+----+

The LDM Database may not store the partitions in the order that they appear on
disk, but the driver will sort them.

When Linux boots, you will see something like::

  hda: 102400 sectors w/32KiB Cache, CHS=50/64/32
  hda: [LDM] hda1 hda2 hda3 hda4 hda5 hda6 hda7


Compiling LDM Support
---------------------

To enable LDM, choose the following two options: 

  - "Advanced partition selection" CONFIG_PARTITION_ADVANCED
  - "Windows Logical Disk Manager (Dynamic Disk) support" CONFIG_LDM_PARTITION

If you believe the driver isn't working as it should, you can enable the extra
debugging code.  This will produce a LOT of output.  The option is:

  - "Windows LDM extra logging" CONFIG_LDM_DEBUG

N.B. The partition code cannot be compiled as a module.

As with all the partition code, if the driver doesn't see signs of its type of
partition, it will pass control to another driver, so there is no harm in
enabling it.

If you have Dynamic Disks but don't enable the driver, then all you will see
is a dummy MSDOS partition filling the whole disk.  You won't be able to mount
any of the volumes on the disk.


Booting
-------

If you enable LDM support, then lilo is capable of booting from any of the
discovered partitions.  However, grub does not understand the LDM partitioning
and cannot boot from a Dynamic Disk.


More Documentation
------------------

There is an Overview of the LDM together with complete Technical Documentation.
It is available for download.

  http://www.linux-ntfs.org/

If you have any LDM questions that aren't answered in the documentation, email
me.

Cheers,
    FlatCap - Richard Russon
    ldm@flatcap.org

---

### Documentation Admin Guide Lockup Watchdogs (`Documentation/admin-guide/lockup-watchdogs.rst`)

===============================================================
Softlockup detector and hardlockup detector (aka nmi_watchdog)
===============================================================

The Linux kernel can act as a watchdog to detect both soft and hard
lockups.

A 'softlockup' is defined as a bug that causes the kernel to loop in
kernel mode for more than 20 seconds (see "Implementation" below for
details), without giving other tasks a chance to run. The current
stack trace is displayed upon detection and, by default, the system
will stay locked up. Alternatively, the kernel can be configured to
panic; a sysctl, "kernel.softlockup_panic", a kernel parameter,
"softlockup_panic" (see "Documentation/admin-guide/kernel-parameters.rst" for
details), and a compile option, "BOOTPARAM_SOFTLOCKUP_PANIC", are
provided for this.

A 'hardlockup' is defined as a bug that causes the CPU to loop in
kernel mode for more than 10 seconds (see "Implementation" below for
details), without letting other interrupts have a chance to run.
Similarly to the softlockup case, the current stack trace is displayed
upon detection and the system will stay locked up unless the default
behavior is changed, which can be done through a sysctl,
'hardlockup_panic', a compile time knob, "BOOTPARAM_HARDLOCKUP_PANIC",
and a kernel parameter, "nmi_watchdog"
(see "Documentation/admin-guide/kernel-parameters.rst" for details).

The panic option can be used in combination with panic_timeout (this
timeout is set through the confusingly named "kernel.panic" sysctl),
to cause the system to reboot automatically after a specified amount
of time.

Implementation
==============

The soft and hard lockup detectors are built on top of the hrtimer and
perf subsystems, respectively. A direct consequence of this is that,
in principle, they should work in any architecture where these
subsystems are present.

A periodic hrtimer runs to generate interrupts and kick the watchdog
job. An NMI perf event is generated every "watchdog_thresh"
(compile-time initialized to 10 and configurable through sysctl of the
same name) seconds to check for hardlockups. If any CPU in the system
does not receive any hrtimer interrupt during that time the
'hardlockup detector' (the handler for the NMI perf event) will
generate a kernel warning or call panic, depending on the
configuration.

The watchdog job runs in a stop scheduling thread that updates a
timestamp every time it is scheduled. If that timestamp is not updated
for 2*watchdog_thresh seconds (the softlockup threshold) the
'softlockup detector' (coded inside the hrtimer callback function)
will dump useful debug information to the system log, after which it
will call panic if it was instructed to do so or resume execution of
other kernel code.

The period of the hrtimer is 2*watchdog_thresh/5, which means it has
two or three chances to generate an interrupt before the hardlockup
detector kicks in.

As explained above, a kernel knob is provided that allows
administrators to configure the period of the hrtimer and the perf
event. The right value for a particular environment is a trade-off
between fast response to lockups and detection overhead.

By default, the watchdog runs on all online cores.  However, on a
kernel configured with NO_HZ_FULL, by default the watchdog runs only
on the housekeeping cores, not the cores specified in the "nohz_full"
boot argument.  If we allowed the watchdog to run by default on
the "nohz_full" cores, we would have to run timer ticks to activate
the scheduler, which would prevent the "nohz_full" functionality
from protecting the user code on those cores from the kernel.
Of course, disabling it by default on the nohz_full cores means that
when those cores do enter the kernel, by default we will not be
able to detect if they lock up.  However, allowing the watchdog
to continue to run on the housekeeping (non-tickless) cores means
that we will continue to detect lockups properly on those cores.

In either case, the set of cores excluded from running the watchdog
may be adjusted via the kernel.watchdog_cpumask sysctl.  For
nohz_full cores, this may be useful for debugging a case where the
kernel seems to be hanging on the nohz_full cores.

---

### Documentation Admin Guide Md (`Documentation/admin-guide/md.rst`)

RAID arrays
===========

Boot time assembly of RAID arrays
---------------------------------

Tools that manage md devices can be found at
   https://www.kernel.org/pub/linux/utils/raid/


You can boot with your md device with the following kernel command
lines:

for old raid arrays without persistent superblocks::

  md=<md device no.>,<raid level>,<chunk size factor>,<fault level>,dev0,dev1,...,devn

for raid arrays with persistent superblocks::

  md=<md device no.>,dev0,dev1,...,devn

or, to assemble a partitionable array::

  md=d<md device no.>,dev0,dev1,...,devn

``md device no.``
+++++++++++++++++

The number of the md device

================= =========
``md device no.`` device
================= =========
              0		md0
	      1		md1
	      2		md2
	      3		md3
	      4		md4
================= =========

``raid level``
++++++++++++++

level of the RAID array

=============== =============
``raid level``  level
=============== =============
-1		linear mode
0		striped mode
=============== =============

other modes are only supported with persistent super blocks

``chunk size factor``
+++++++++++++++++++++

(raid-0 and raid-1 only)

Set  the chunk size as 4k << n.

``fault level``
+++++++++++++++

Totally ignored

``dev0`` to ``devn``
++++++++++++++++++++

e.g. ``/dev/hda1``, ``/dev/hdc1``, ``/dev/sda1``, ``/dev/sdb1``

A possible loadlin line (Harald Hoyer <HarryH@Royal.Net>)  looks like this::

	e:\loadlin\loadlin e:\zimage root=/dev/md0 md=0,0,4,0,/dev/hdb2,/dev/hdc3 ro


Boot time autodetection of RAID arrays
--------------------------------------

When md is compiled into the kernel (not as module), partitions of
type 0xfd are scanned and automatically assembled into RAID arrays.
This autodetection may be suppressed with the kernel parameter
``raid=noautodetect``.  As of kernel 2.6.9, only drives with a type 0
superblock can be autodetected and run at boot time.

The kernel parameter ``raid=partitionable`` (or ``raid=part``) means
that all auto-detected arrays are assembled as partitionable.

Boot time assembly of degraded/dirty arrays
-------------------------------------------

If a raid5 or raid6 array is both dirty and degraded, it could have
undetectable data corruption.  This is because the fact that it is
``dirty`` means that the parity cannot be trusted, and the fact that it
is degraded means that some datablocks are missing and cannot reliably
be reconstructed (due to no parity).

For this reason, md will normally refuse to start such an array.  This
requires the sysadmin to take action to explicitly start the array
despite possible corruption.  This is normally done with::

   mdadm --assemble --force ....

This option is not really available if the array has the root
filesystem on it.  In order to support this booting from such an
array, md supports a module parameter ``start_dirty_degraded`` which,
when set to 1, bypassed the checks and will allows dirty degraded
arrays to be started.

So, to boot with a root filesystem of a dirty degraded raid 5 or 6, use::

   md-mod.start_dirty_degraded=1


Superblock formats
------------------

The md driver can support a variety of different superblock formats.
Currently, it supports superblock formats ``0.90.0`` and the ``md-1`` format
introduced in the 2.5 development series.

The kernel will autodetect which format superblock is being used.

Superblock format ``0`` is treated differently to others for legacy
reasons - it is the original superblock format.


General Rules - apply for all superblock formats
------------------------------------------------

An array is ``created`` by writing appropriate superblocks to all
devices.

It is ``assembled`` by associating each of these devices with an
particular md virtual device.  Once it is completely assembled, it can
be accessed.

An array should be created by a user-space tool.  This will write
superblocks to all devices.  It will usually mark the array as
``unclean``, or with some devices missing so that the kernel md driver
can create appropriate redundancy (copying in raid 1, parity
calculation in raid 4/5).

When an array is assembled, it is first initialized with the
SET_ARRAY_INFO ioctl.  This contains, in particular, a major and minor
version number.  The major version number selects which superblock
format is to be used.  The minor number might be used to tune handling
of the format, such as suggesting where on each device to look for the
superblock.

Then each device is added using the ADD_NEW_DISK ioctl.  This
provides, in particular, a major and minor number identifying the
device to add.

The array is started with the RUN_ARRAY ioctl.

Once started, new devices can be added.  They should have an
appropriate superblock written to them, and then be passed in with
ADD_NEW_DISK.

Devices that have failed or are not yet active can be detached from an
array using HOT_REMOVE_DISK.


Specific Rules that apply to format-0 super block arrays, and arrays with no superblock (non-persistent)
--------------------------------------------------------------------------------------------------------

An array can be ``created`` by describing the array (level, chunksize
etc) in a SET_ARRAY_INFO ioctl.  This must have ``major_version==0`` and
``raid_disks != 0``.

Then uninitialized devices can be added with ADD_NEW_DISK.  The
structure passed to ADD_NEW_DISK must specify the state of the device
and its role in the array.

Once started with RUN_ARRAY, uninitialized spares can be added with
HOT_ADD_DISK.


MD devices in sysfs
-------------------

md devices appear in sysfs (``/sys``) as regular block devices,
e.g.::

   /sys/block/md0

Each ``md`` device will contain a subdirectory called ``md`` which
contains further md-specific information about the device.

All md devices contain:

  level
     a text file indicating the ``raid level``. e.g. raid0, raid1,
     raid5, linear, multipath, faulty.
     If no raid level has been set yet (array is still being
     assembled), the value will reflect whatever has been written
     to it, which may be a name like the above, or may be a number
     such as ``0``, ``5``, etc.

  raid_disks
     a text file with a simple number indicating the number of devices
     in a fully functional array.  If this is not yet known, the file
     will be empty.  If an array is being resized this will contain
     the new number of devices.
     Some raid levels allow this value to be set while the array is
     active.  This will reconfigure the array.   Otherwise it can only
     be set while assembling an array.
     A change to this attribute will not be permitted if it would
     reduce the size of the array.  To reduce the number of drives
     in an e.g. raid5, the array size must first be reduced by
     setting the ``array_size`` attribute.

  chunk_size
     This is the size in bytes for ``chunks`` and is only relevant to
     raid levels that involve striping (0,4,5,6,10). The address space
     of the array is conceptually divided into chunks and consecutive
     chunks are striped onto neighbouring devices.
     The size should be at least PAGE_SIZE (4k) and should be a power
     of 2.  This can only be set while assembling an array

  layout
     The ``layout`` for the array for the particular level.  This is
     simply a number that is interpreted differently by different
     levels.  It can be written while assembling an array.

  array_size
     This can be used to artificially constrain the available space in
     the array to be less than is actually available on the combined
     devices.  Writing a number (in Kilobytes) which is less than
     the available size will set the size.  Any reconfiguration of the
     array (e.g. adding devices) will not cause the size to change.
     Writing the word ``default`` will cause the effective size of the
     array to be whatever size is actually available based on
     ``level``, ``chunk_size`` and ``component_size``.

     This can be used to reduce the size of the array before reducing
     the number of devices in a raid4/5/6, or to support external
     metadata formats which mandate such clipping.

  reshape_position
     This is either ``none`` or a sector number within the devices of
     the array where ``reshape`` is up to.  If this is set, the three
     attributes mentioned above (raid_disks, chunk_size, layout) can
     potentially have 2 values, an old and a new value.  If these
     values differ, reading the attribute returns::

        new (old)

     and writing will effect the ``new`` value, leaving the ``old``
     unchanged.

  component_size
     For arrays with data redundancy (i.e. not raid0, linear, faulty,
     multipath), all components must be the same size - or at least
     there must a size that they all provide space for.  This is a key
     part or the geometry of the array.  It is measured in sectors
     and can be read from here.  Writing to this value may resize
     the array if the personality supports it (raid1, raid5, raid6),
     and if the component drives are large enough.

  metadata_version
     This indicates the format that is being used to record metadata
     about the array.  It can be 0.90 (traditional format), 1.0, 1.1,
     1.2 (newer format in varying locations) or ``none`` indicating that
     the kernel isn't managing metadata at all.
     Alternately it can be ``external:`` followed by a string which
     is set by user-space.  This indicates that metadata is managed
     by a user-space program.  Any device failure or other event that
     requires a metadata update will cause array activity to be
     suspended until the event is acknowledged.

  resync_start
     The point at which resync should start.  If no resync is needed,
     this will be a very large number (or ``none`` since 2.6.30-rc1).  At
     array creation it will default to 0, though starting the array as
     ``clean`` will set it much larger.

  new_dev
     This file can be written but not read.  The value written should
     be a block device number as major:minor.  e.g. 8:0
     This will cause that device to be attached to the array, if it is
     available.  It will then appear at md/dev-XXX (depending on the
     name of the device) and further configuration is then possible.

  safe_mode_delay
     When an md array has seen no write requests for a certain period
     of time, it will be marked as ``clean``.  When another write
     request arrives, the array is marked as ``dirty`` before the write
     commences.  This is known as ``safe_mode``.
     The ``certain period`` is controlled by this file which stores the
     period as a number of seconds.  The default is 200msec (0.200).
     Writing a value of 0 disables safemode.

  array_state
     This file contains a single word which describes the current
     state of the array.  In many cases, the state can be set by
     writing the word for the desired state, however some states
     cannot be explicitly set, and some transitions are not allowed.

     Select/poll works on this file.  All changes except between
     Active_idle and active (which can be frequent and are not
     very interesting) are notified.  active->active_idle is
     reported if the metadata is externally managed.

     clear
         No devices, no size, no level

         Writing is equivalent to STOP_ARRAY ioctl

     inactive
         May have some settings, but array is not active
         all IO results in error

         When written, doesn't tear down array, but just stops it

     suspended (not supported yet)
         All IO requests will block. The array can be reconfigured.

         Writing this, if accepted, will block until array is quiescent

     readonly
         no resync can happen.  no superblocks get written.

         Write requests fail

     read-auto
         like readonly, but behaves like ``clean`` on a write request.

     clean
         no pending writes, but otherwise active.

         When written to inactive array, starts without resync

         If a write request arrives then
         if metadata is known, mark ``dirty`` and switch to ``active``.
         if not known, block and switch to write-pending

         If written to an active array that has pending writes, then fails.
     active
         fully active: IO and resync can be happening.
         When written to inactive array, starts with resync

     write-pending
         clean, but writes are blocked waiting for ``active`` to be written.

     active-idle
         like active, but no writes have been seen for a while (safe_mode_delay).

  consistency_policy
     This indicates how the array maintains consistency in case of unexpected
     shutdown. It can be:

     none
       Array has no redundancy information, e.g. raid0, linear.

     resync
       Full resync is performed and all redundancy is regenerated when the
       array is started after unclean shutdown.

     bitmap
       Resync assisted by a write-intent bitmap.

     journal
       For raid4/5/6, journal device is used to log transactions and replay
       after unclean shutdown.

     ppl
       For raid5 only, Partial Parity Log is used to close the write hole and
       eliminate resync.

     The accepted values when writing to this file are ``ppl`` and ``resync``,
     used to enable and disable PPL.

  uuid
     This indicates the UUID of the array in the following format:
     xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

  bitmap_type
     [RW] When read, this file will display the current and available
     bitmap for this array. The currently active bitmap will be enclosed
     in [] brackets. Writing an bitmap name or ID to this file will switch
     control of this array to that new bitmap. Note that writing a new
     bitmap for created array is forbidden.

     none
         No bitmap
     bitmap
         The default internal bitmap
     llbitmap
         The lockless internal bitmap

If bitmap_type is not none, then additional bitmap attributes bitmap/xxx or
llbitmap/xxx will be created after md device KOBJ_CHANGE event.

If bitmap_type is bitmap, then the md device will also contain:

  bitmap/location
     This indicates where the write-intent bitmap for the array is
     stored.

     It can be one of ``none``, ``file`` or ``[+-]N``.
     ``file`` may later be extended to ``file:/file/name``
     ``[+-]N`` means that many sectors from the start of the metadata.

     This is replicated on all devices.  For arrays with externally
     managed metadata, the offset is from the beginning of the
     device.

  bitmap/chunksize
     The size, in bytes, of the chunk which will be represented by a
     single bit.  For RAID456, it is a portion of an individual
     device. For RAID10, it is a portion of the array.  For RAID1, it
     is both (they come to the same thing).

  bitmap/time_base
     The time, in seconds, between looking for bits in the bitmap to
     be cleared. In the current implementation, a bit will be cleared
     between 2 and 3 times ``time_base`` after all the covered blocks
     are known to be in-sync.

  bitmap/backlog
     When write-mostly devices are active in a RAID1, write requests
     to those devices proceed in the background - the filesystem (or
     other user of the device) does not have to wait for them.
     ``backlog`` sets a limit on the number of concurrent background
     writes.  If there are more than this, new writes will by
     synchronous.

  bitmap/metadata
     This can be either ``internal`` or ``external``.

     ``internal``
       is the default and means the metadata for the bitmap
       is stored in the first 256 bytes of the allocated space and is
       managed by the md module.

     ``external``
       means that bitmap metadata is managed externally to
       the kernel (i.e. by some userspace program)

  bitmap/can_clear
     This is either ``true`` or ``false``.  If ``true``, then bits in the
     bitmap will be cleared when the corresponding blocks are thought
     to be in-sync.  If ``false``, bits will never be cleared.
     This is automatically set to ``false`` if a write happens on a
     degraded array, or if the array becomes degraded during a write.
     When metadata is managed externally, it should be set to true
     once the array becomes non-degraded, and this fact has been
     recorded in the metadata.

If bitmap_type is llbitmap, then the md device will also contain:

  llbitmap/bits
     This is read-only, show status of bitmap bits, the number of each
     value.

  llbitmap/metadata
     This is read-only, show bitmap metadata, include chunksize, chunkshift,
     chunks, offset and daemon_sleep.

  llbitmap/daemon_sleep
     This is read-write, time in seconds that daemon function will be
     triggered to clear dirty bits.

  llbitmap/barrier_idle
     This is read-write, time in seconds that page barrier will be idled,
     means dirty bits in the page will be cleared.

As component devices are added to an md array, they appear in the ``md``
directory as new directories named::

      dev-XXX

where ``XXX`` is a name that the kernel knows for the device, e.g. hdb1.
Each directory contains:

      block
        a symlink to the block device in /sys/block, e.g.::

	     /sys/block/md0/md/dev-hdb1/block -> ../../../../block/hdb/hdb1

      super
        A file containing an image of the superblock read from, or
        written to, that device.

      state
	A file recording the current state of the device in the array
	which can be a comma separated list of:

	      faulty
			device has been kicked from active use due to
			a detected fault, or it has unacknowledged bad
			blocks

	      in_sync
			device is a fully in-sync member of the array

	      writemostly
			device will only be subject to read
			requests if there are no other options.

			This applies only to raid1 arrays.

	      blocked
			device has failed, and the failure hasn't been
			acknowledged yet by the metadata handler.

			Writes that would write to this device if
			it were not faulty are blocked.

	      spare
			device is working, but not a full member.

			This includes spares that are in the process
			of being recovered to

	      write_error
			device has ever seen a write error.

	      want_replacement
			device is (mostly) working but probably
			should be replaced, either due to errors or
			due to user request.

	      replacement
			device is a replacement for another active
			device with same raid_disk.


	This list may grow in future.

	This can be written to.

	Writing ``faulty``  simulates a failure on the device.

	Writing ``remove`` removes the device from the array.

	Writing ``writemostly`` sets the writemostly flag.

	Writing ``-writemostly`` clears the writemostly flag.

	Writing ``blocked`` sets the ``blocked`` flag.

	Writing ``-blocked`` clears the ``blocked`` flags and allows writes
	to complete and possibly simulates an error.

	Writing ``in_sync`` sets the in_sync flag.

	Writing ``write_error`` sets writeerrorseen flag.

	Writing ``-write_error`` clears writeerrorseen flag.

	Writing ``want_replacement`` is allowed at any time except to a
	replacement device or a spare.  It sets the flag.

	Writing ``-want_replacement`` is allowed at any time.  It clears
	the flag.

	Writing ``replacement`` or ``-replacement`` is only allowed before
	starting the array.  It sets or clears the flag.


	This file responds to select/poll. Any change to ``faulty``
	or ``blocked`` causes an event.

      errors
	An approximate count of read errors that have been detected on
	this device but have not caused the device to be evicted from
	the array (either because they were corrected or because they
	happened while the array was read-only).  When using version-1
	metadata, this value persists across restarts of the array.

	This value can be written while assembling an array thus
	providing an ongoing count for arrays with metadata managed by
	userspace.

      slot
        This gives the role that the device has in the array.  It will
	either be ``none`` if the device is not active in the array
        (i.e. is a spare or has failed) or an integer less than the
	``raid_disks`` number for the array indicating which position
	it currently fills.  This can only be set while assembling an
	array.  A device for which this is set is assumed to be working.

      offset
        This gives the location in the device (in sectors from the
        start) where data from the array will be stored.  Any part of
        the device before this offset is not touched, unless it is
        used for storing metadata (Formats 1.1 and 1.2).

      size
        The amount of the device, after the offset, that can be used
        for storage of data.  This will normally be the same as the
	component_size.  This can be written while assembling an
        array.  If a value less than the current component_size is
        written, it will be rejected.

      recovery_start
        When the device is not ``in_sync``, this records the number of
	sectors from the start of the device which are known to be
	correct.  This is normally zero, but during a recovery
	operation it will steadily increase, and if the recovery is
	interrupted, restoring this value can cause recovery to
	avoid repeating the earlier blocks.  With v1.x metadata, this
	value is saved and restored automatically.

	This can be set whenever the device is not an active member of
	the array, either before the array is activated, or before
	the ``slot`` is set.

	Setting this to ``none`` is equivalent to setting ``in_sync``.
	Setting to any other value also clears the ``in_sync`` flag.

      bad_blocks
	This gives the list of all known bad blocks in the form of
	start address and length (in sectors respectively). If output
	is too big to fit in a page, it will be truncated. Writing
	``sector length`` to this file adds new acknowledged (i.e.
	recorded to disk safely) bad blocks.

      unacknowledged_bad_blocks
	This gives the list of known-but-not-yet-saved-to-disk bad
	blocks in the same form of ``bad_blocks``. If output is too big
	to fit in a page, it will be truncated. Writing to this file
	adds bad blocks without acknowledging them. This is largely
	for testing.

      ppl_sector, ppl_size
        Location and size (in sectors) of the space used for Partial Parity Log
        on this device.


An active md device will also contain an entry for each active device
in the array.  These are named::

    rdNN

where ``NN`` is the position in the array, starting from 0.
So for a 3 drive array there will be rd0, rd1, rd2.
These are symbolic links to the appropriate ``dev-XXX`` entry.
Thus, for example::

       cat /sys/block/md*/md/rd*/state

will show ``in_sync`` on every line.



Active md devices for levels that support data redundancy (1,4,5,6,10)
also have

   sync_action
     a text file that can be used to monitor and control the rebuild
     process.  It contains one word which can be one of:

       resync
		redundancy is being recalculated after unclean
                shutdown or creation

       recover
		a hot spare is being built to replace a
		failed/missing device

       idle
		nothing is happening
       check
		A full check of redundancy was requested and is
                happening.  This reads all blocks and checks
                them. A repair may also happen for some raid
                levels.

       repair
		A full check and repair is happening.  This is
		similar to ``resync``, but was requested by the
                user, and the write-intent bitmap is NOT used to
		optimise the process.

      This file is writable, and each of the strings that could be
      read are meaningful for writing.

	``idle`` will stop an active resync/recovery etc.  There is no
	guarantee that another resync/recovery may not be automatically
	started again, though some event will be needed to trigger
	this.

	``resync`` or ``recovery`` can be used to restart the
        corresponding operation if it was stopped with ``idle``.

	``check`` and ``repair`` will start the appropriate process
	providing the current state is ``idle``.

      This file responds to select/poll.  Any important change in the value
      triggers a poll event.  Sometimes the value will briefly be
      ``recover`` if a recovery seems to be needed, but cannot be
      achieved. In that case, the transition to ``recover`` isn't
      notified, but the transition away is.

   degraded
      This contains a count of the number of devices by which the
      arrays is degraded.  So an optimal array will show ``0``.  A
      single failed/missing drive will show ``1``, etc.

      This file responds to select/poll, any increase or decrease
      in the count of missing devices will trigger an event.

   mismatch_count
      When performing ``check`` and ``repair``, and possibly when
      performing ``resync``, md will count the number of errors that are
      found.  The count in ``mismatch_cnt`` is the number of sectors
      that were re-written, or (for ``check``) would have been
      re-written.  As most raid levels work in units of pages rather
      than sectors, this may be larger than the number of actual errors
      by a factor of the number of sectors in a page.

   bitmap_set_bits
      If the array has a write-intent bitmap, then writing to this
      attribute can set bits in the bitmap, indicating that a resync
      would need to check the corresponding blocks. Either individual
      numbers or start-end pairs can be written.  Multiple numbers
      can be separated by a space.

      Note that the numbers are ``bit`` numbers, not ``block`` numbers.
      They should be scaled by the bitmap_chunksize.

   sync_speed_min, sync_speed_max
     This are similar to ``/proc/sys/dev/raid/speed_limit_{min,max}``
     however they only apply to the particular array.

     If no value has been written to these, or if the word ``system``
     is written, then the system-wide value is used.  If a value,
     in kibibytes-per-second is written, then it is used.

     When the files are read, they show the currently active value
     followed by ``(local)`` or ``(system)`` depending on whether it is
     a locally set or system-wide value.

   sync_completed
     This shows the number of sectors that have been completed of
     whatever the current sync_action is, followed by the number of
     sectors in total that could need to be processed.  The two
     numbers are separated by a ``/``  thus effectively showing one
     value, a fraction of the process that is complete.

     A ``select`` on this attribute will return when resync completes,
     when it reaches the current sync_max (below) and possibly at
     other times.

   sync_speed
     This shows the current actual speed, in K/sec, of the current
     sync_action.  It is averaged over the last 30 seconds.

   suspend_lo, suspend_hi
     The two values, given as numbers of sectors, indicate a range
     within the array where IO will be blocked.  This is currently
     only supported for raid4/5/6.

   sync_min, sync_max
     The two values, given as numbers of sectors, indicate a range
     within the array where ``check``/``repair`` will operate. Must be
     a multiple of chunk_size. When it reaches ``sync_max`` it will
     pause, rather than complete.
     You can use ``select`` or ``poll`` on ``sync_completed`` to wait for
     that number to reach sync_max.  Then you can either increase
     ``sync_max``, or can write ``idle`` to ``sync_action``.

     The value of ``max`` for ``sync_max`` effectively disables the limit.
     When a resync is active, the value can only ever be increased,
     never decreased.
     The value of ``0`` is the minimum for ``sync_min``.



Each active md device may also have attributes specific to the
personality module that manages it.
These are specific to the implementation of the module and could
change substantially if the implementation changes.

These currently include:

  stripe_cache_size  (currently raid5 only)
      number of entries in the stripe cache.  This is writable, but
      there are upper and lower limits (32768, 17).  Default is 256.

  strip_cache_active (currently raid5 only)
      number of active entries in the stripe cache

  preread_bypass_threshold (currently raid5 only)
      number of times a stripe requiring preread will be bypassed by
      a stripe that does not require preread.  For fairness defaults
      to 1.  Setting this to 0 disables bypass accounting and
      requires preread stripes to wait until all full-width stripe-
      writes are complete.  Valid values are 0 to stripe_cache_size.

  journal_mode (currently raid5 only)
      The cache mode for raid5. raid5 could include an extra disk for
      caching. The mode can be "write-through" or "write-back". The
      default is "write-through".

  ppl_write_hint
      NVMe stream ID to be set for each PPL write request.

---

### Documentation Admin Guide Module Signing (`Documentation/admin-guide/module-signing.rst`)

Kernel module signing facility
------------------------------

.. CONTENTS
..
.. - Overview.
.. - Configuring module signing.
.. - Generating signing keys.
.. - Public keys in the kernel.
.. - Manually signing modules.
.. - Signed modules and stripping.
.. - Loading signed modules.
.. - Non-valid signatures and unsigned modules.
.. - Administering/protecting the private key.


========
Overview
========

The kernel module signing facility cryptographically signs modules during
installation and then checks the signature upon loading the module.  This
allows increased kernel security by disallowing the loading of unsigned modules
or modules signed with an invalid key.  Module signing increases security by
making it harder to load a malicious module into the kernel.  The module
signature checking is done by the kernel so that it is not necessary to have
trusted userspace bits.

This facility uses X.509 ITU-T standard certificates to encode the public keys
involved.  The signatures are not themselves encoded in any industrial standard
type.  The built-in facility currently only supports the RSA & NIST P-384 ECDSA
public key signing standard (though it is pluggable and permits others to be
used).  The possible hash algorithms that can be used are SHA-2 and SHA-3 of
sizes 256, 384, and 512 (the algorithm is selected by data in the signature).


==========================
Configuring module signing
==========================

The module signing facility is enabled by going to the
:menuselection:`Enable Loadable Module Support` section of
the kernel configuration and turning on::

	CONFIG_MODULE_SIG	"Module signature verification"

This has a number of options available:

 (1) :menuselection:`Require modules to be validly signed`
     (``CONFIG_MODULE_SIG_FORCE``)

     This specifies how the kernel should deal with a module that has a
     signature for which the key is not known or a module that is unsigned.

     If this is off (ie. "permissive"), then modules for which the key is not
     available and modules that are unsigned are permitted, but the kernel will
     be marked as being tainted, and the concerned modules will be marked as
     tainted, shown with the character 'E'.

     If this is on (ie. "restrictive"), only modules that have a valid
     signature that can be verified by a public key in the kernel's possession
     will be loaded.  All other modules will generate an error.

     Irrespective of the setting here, if the module has a signature block that
     cannot be parsed, it will be rejected out of hand.


 (2) :menuselection:`Automatically sign all modules`
     (``CONFIG_MODULE_SIG_ALL``)

     If this is on then modules will be automatically signed during the
     modules_install phase of a build.  If this is off, then the modules must
     be signed manually using::

	scripts/sign-file


 (3) :menuselection:`Which hash algorithm should modules be signed with?`

     This presents a choice of which hash algorithm the installation phase will
     sign the modules with:

        =============================== ==========================================
	``CONFIG_MODULE_SIG_SHA256``	:menuselection:`Sign modules with SHA-256`
	``CONFIG_MODULE_SIG_SHA384``	:menuselection:`Sign modules with SHA-384`
	``CONFIG_MODULE_SIG_SHA512``	:menuselection:`Sign modules with SHA-512`
	``CONFIG_MODULE_SIG_SHA3_256``	:menuselection:`Sign modules with SHA3-256`
	``CONFIG_MODULE_SIG_SHA3_384``	:menuselection:`Sign modules with SHA3-384`
	``CONFIG_MODULE_SIG_SHA3_512``	:menuselection:`Sign modules with SHA3-512`
        =============================== ==========================================

     The algorithm selected here will also be built into the kernel (rather
     than being a module) so that modules signed with that algorithm can have
     their signatures checked without causing a dependency loop.


 (4) :menuselection:`File name or PKCS#11 URI of module signing key`
     (``CONFIG_MODULE_SIG_KEY``)

     Setting this option to something other than its default of
     ``certs/signing_key.pem`` will disable the autogeneration of signing keys
     and allow the kernel modules to be signed with a key of your choosing.
     The string provided should identify a file containing both a private key
     and its corresponding X.509 certificate in PEM form, or — on systems where
     the OpenSSL ENGINE_pkcs11 is functional — a PKCS#11 URI as defined by
     RFC7512. In the latter case, the PKCS#11 URI should reference both a
     certificate and a private key.

     If the PEM file containing the private key is encrypted, or if the
     PKCS#11 token requires a PIN, this can be provided at build time by
     means of the ``KBUILD_SIGN_PIN`` variable.


 (5) :menuselection:`Additional X.509 keys for default system keyring`
     (``CONFIG_SYSTEM_TRUSTED_KEYS``)

     This option can be set to the filename of a PEM-encoded file containing
     additional certificates which will be included in the system keyring by
     default.

Note that enabling module signing adds a dependency on the OpenSSL devel
packages to the kernel build processes for the tool that does the signing.


=======================
Generating signing keys
=======================

Cryptographic keypairs are required to generate and check signatures.  A
private key is used to generate a signature and the corresponding public key is
used to check it.  The private key is only needed during the build, after which
it can be deleted or stored securely.  The public key gets built into the
kernel so that it can be used to check the signatures as the modules are
loaded.

Under normal conditions, when ``CONFIG_MODULE_SIG_KEY`` is unchanged from its
default, the kernel build will automatically generate a new keypair using
openssl if one does not exist in the file::

	certs/signing_key.pem

during the building of vmlinux (the public part of the key needs to be built
into vmlinux) using parameters in the::

	certs/x509.genkey

file (which is also generated if it does not already exist).

One can select between RSA (``MODULE_SIG_KEY_TYPE_RSA``) and ECDSA
(``MODULE_SIG_KEY_TYPE_ECDSA``) to generate either RSA 4k or NIST
P-384 keypair.

It is strongly recommended that you provide your own x509.genkey file.

Most notably, in the x509.genkey file, the req_distinguished_name section
should be altered from the default::

	[ req_distinguished_name ]
	#O = Unspecified company
	CN = Build time autogenerated kernel key
	#emailAddress = unspecified.user@unspecified.company

The generated RSA key size can also be set with::

	[ req ]
	default_bits = 4096


It is also possible to manually generate the key private/public files using the
x509.genkey key generation configuration file in the root node of the Linux
kernel sources tree and the openssl command.  The following is an example to
generate the public/private key files::

	openssl req -new -nodes -utf8 -sha256 -days 36500 -batch -x509 \
	   -config x509.genkey -outform PEM -out kernel_key.pem \
	   -keyout kernel_key.pem

The full pathname for the resulting kernel_key.pem file can then be specified
in the ``CONFIG_MODULE_SIG_KEY`` option, and the certificate and key therein will
be used instead of an autogenerated keypair.


=========================
Public keys in the kernel
=========================

The kernel contains a ring of public keys that can be viewed by root.  They're
in a keyring called ".builtin_trusted_keys" that can be seen by::

	[root@deneb ~]# cat /proc/keys
	...
	223c7853 I------     1 perm 1f030000     0     0 keyring   .builtin_trusted_keys: 1
	302d2d52 I------     1 perm 1f010000     0     0 asymmetri Fedora kernel signing key: d69a84e6bce3d216b979e9505b3e3ef9a7118079: X509.RSA a7118079 []
	...

Beyond the public key generated specifically for module signing, additional
trusted certificates can be provided in a PEM-encoded file referenced by the
``CONFIG_SYSTEM_TRUSTED_KEYS`` configuration option.

Further, the architecture code may take public keys from a hardware store and
add those in also (e.g. from the UEFI key database).

Finally, it is possible to add additional public keys by doing::

	keyctl padd asymmetric "" [.builtin_trusted_keys-ID] <[key-file]

e.g.::

	keyctl padd asymmetric "" 0x223c7853 <my_public_key.x509

Note, however, that the kernel will only permit keys to be added to
``.builtin_trusted_keys`` **if** the new key's X.509 wrapper is validly signed by a key
that is already resident in the ``.builtin_trusted_keys`` at the time the key was added.


========================
Manually signing modules
========================

To manually sign a module, use the scripts/sign-file tool available in
the Linux kernel source tree.  The script requires 4 arguments:

	1.  The hash algorithm (e.g., sha256)
	2.  The private key filename or PKCS#11 URI
	3.  The public key filename
	4.  The kernel module to be signed

The following is an example to sign a kernel module::

	scripts/sign-file sha512 kernel-signkey.priv \
		kernel-signkey.x509 module.ko

The hash algorithm used does not have to match the one configured, but if it
doesn't, you should make sure that hash algorithm is either built into the
kernel or can be loaded without requiring itself.

If the private key requires a passphrase or PIN, it can be provided in the
$KBUILD_SIGN_PIN environment variable.


============================
Signed modules and stripping
============================

A signed module has a digital signature simply appended at the end.  The string
``~Module signature appended~.`` at the end of the module's file confirms that a
signature is present but it does not confirm that the signature is valid!

Signed modules are BRITTLE as the signature is outside of the defined ELF
container.  Thus they MAY NOT be stripped once the signature is computed and
attached.  Note the entire module is the signed payload, including any and all
debug information present at the time of signing.


======================
Loading signed modules
======================

Modules are loaded with insmod, modprobe, ``init_module()`` or
``finit_module()``, exactly as for unsigned modules as no processing is
done in userspace.  The signature checking is all done within the kernel.


=========================================
Non-valid signatures and unsigned modules
=========================================

If ``CONFIG_MODULE_SIG_FORCE`` is enabled or module.sig_enforce=1 is supplied on
the kernel command line, the kernel will only load validly signed modules
for which it has a public key.   Otherwise, it will also load modules that are
unsigned.   Any module for which the kernel has a key, but which proves to have
a signature mismatch will not be permitted to load.

Any module that has an unparsable signature will be rejected.


=========================================
Administering/protecting the private key
=========================================

Since the private key is used to sign modules, viruses and malware could use
the private key to sign modules and compromise the operating system.  The
private key must be either destroyed or moved to a secure location and not kept
in the root node of the kernel source tree.

If you use the same private key to sign modules for multiple kernel
configurations, you must ensure that the module version information is
sufficient to prevent loading a module into a different kernel.  Either
set ``CONFIG_MODVERSIONS=y`` or ensure that each configuration has a different
kernel release string by changing ``EXTRAVERSION`` or ``CONFIG_LOCALVERSION``.

---

### Documentation Admin Guide Mono (`Documentation/admin-guide/mono.rst`)

Mono(tm) Binary Kernel Support for Linux
-----------------------------------------

To configure Linux to automatically execute Mono-based .NET binaries
(in the form of .exe files) without the need to use the mono CLR
wrapper, you can use the BINFMT_MISC kernel support.

This will allow you to execute Mono-based .NET binaries just like any
other program after you have done the following:

1) You MUST FIRST install the Mono CLR support, either by downloading
   a binary package, a source tarball or by installing from Git. Binary
   packages for several distributions can be found at:

	https://www.mono-project.com/download/

   Instructions for compiling Mono can be found at:

	https://www.mono-project.com/docs/compiling-mono/linux/

   Once the Mono CLR support has been installed, just check that
   ``/usr/bin/mono`` (which could be located elsewhere, for example
   ``/usr/local/bin/mono``) is working.

2) You have to compile BINFMT_MISC either as a module or into
   the kernel (``CONFIG_BINFMT_MISC``) and set it up properly.
   If you choose to compile it as a module, you will have
   to insert it manually with modprobe/insmod, as kmod
   cannot be easily supported with binfmt_misc.
   Read the file ``binfmt_misc.txt`` in this directory to know
   more about the configuration process.

3) Add the following entries to ``/etc/rc.local`` or similar script
   to be run at system startup:

   .. code-block:: sh

    # Insert BINFMT_MISC module into the kernel
    if [ ! -e /proc/sys/fs/binfmt_misc/register ]; then
        /sbin/modprobe binfmt_misc
	# Some distributions, like Fedora Core, perform
	# the following command automatically when the
	# binfmt_misc module is loaded into the kernel
	# or during normal boot up (systemd-based systems).
	# Thus, it is possible that the following line
	# is not needed at all.
	mount -t binfmt_misc none /proc/sys/fs/binfmt_misc
    fi

    # Register support for .NET CLR binaries
    if [ -e /proc/sys/fs/binfmt_misc/register ]; then
	# Replace /usr/bin/mono with the correct pathname to
	# the Mono CLR runtime (usually /usr/local/bin/mono
	# when compiling from sources or CVS).
        echo ':CLR:M::MZ::/usr/bin/mono:' > /proc/sys/fs/binfmt_misc/register
    else
        echo "No binfmt_misc support"
        exit 1
    fi

4) Check that ``.exe`` binaries can be ran without the need of a
   wrapper script, simply by launching the ``.exe`` file directly
   from a command prompt, for example::

	/usr/bin/xsd.exe

   .. note::

      If this fails with a permission denied error, check
      that the ``.exe`` file has execute permissions.

---

### Documentation Admin Guide Numastat (`Documentation/admin-guide/numastat.rst`)

===============================
Numa policy hit/miss statistics
===============================

/sys/devices/system/node/node*/numastat

All units are pages. Hugepages have separate counters.

The numa_hit, numa_miss and numa_foreign counters reflect how well processes
are able to allocate memory from nodes they prefer. If they succeed, numa_hit
is incremented on the preferred node, otherwise numa_foreign is incremented on
the preferred node and numa_miss on the node where allocation succeeded.

Usually preferred node is the one local to the CPU where the process executes,
but restrictions such as mempolicies can change that, so there are also two
counters based on CPU local node. local_node is similar to numa_hit and is
incremented on allocation from a node by CPU on the same node. other_node is
similar to numa_miss and is incremented on the node where allocation succeeds
from a CPU from a different node. Note there is no counter analogical to
numa_foreign.

In more detail:

=============== ============================================================
numa_hit	A process wanted to allocate memory from this node,
		and succeeded.

numa_miss	A process wanted to allocate memory from another node,
		but ended up with memory from this node.

numa_foreign	A process wanted to allocate on this node,
		but ended up with memory from another node.

local_node	A process ran on this node's CPU,
		and got memory from this node.

other_node	A process ran on a different node's CPU
		and got memory from this node.

interleave_hit 	Interleaving wanted to allocate from this node
		and succeeded.
=============== ============================================================

For easier reading you can use the numastat utility from the numactl package
(http://oss.sgi.com/projects/libnuma/). Note that it only works
well right now on machines with a small number of CPUs.

Note that on systems with memoryless nodes (where a node has CPUs but no
memory) the numa_hit, numa_miss and numa_foreign statistics can be skewed
heavily. In the current kernel implementation, if a process prefers a
memoryless node (i.e.  because it is running on one of its local CPU), the
implementation actually treats one of the nearest nodes with memory as the
preferred node. As a result, such allocation will not increase the numa_foreign
counter on the memoryless node, and will skew the numa_hit, numa_miss and
numa_foreign statistics of the nearest node.

---

### Documentation Admin Guide Nvme Multipath (`Documentation/admin-guide/nvme-multipath.rst`)

.. SPDX-License-Identifier: GPL-2.0

====================
Linux NVMe multipath
====================

This document describes NVMe multipath and its path selection policies supported
by the Linux NVMe host driver.


Introduction
============

The NVMe multipath feature in Linux integrates namespaces with the same
identifier into a single block device. Using multipath enhances the reliability
and stability of I/O access while improving bandwidth performance. When a user
sends I/O to this merged block device, the multipath mechanism selects one of
the underlying block devices (paths) according to the configured policy.
Different policies result in different path selections.


Policies
========

All policies follow the ANA (Asymmetric Namespace Access) mechanism, meaning
that when an optimized path is available, it will be chosen over a non-optimized
one. Current the NVMe multipath policies include numa(default), round-robin and
queue-depth.

To set the desired policy (e.g., round-robin), use one of the following methods:
   1. echo -n "round-robin" > /sys/module/nvme_core/parameters/iopolicy
   2. or add the "nvme_core.iopolicy=round-robin" to cmdline.


NUMA
----

The NUMA policy selects the path closest to the NUMA node of the current CPU for
I/O distribution. This policy maintains the nearest paths to each NUMA node
based on network interface connections.

When to use the NUMA policy:
  1. Multi-core Systems: Optimizes memory access in multi-core and
     multi-processor systems, especially under NUMA architecture.
  2. High Affinity Workloads: Binds I/O processing to the CPU to reduce
     communication and data transfer delays across nodes.


Round-Robin
-----------

The round-robin policy distributes I/O requests evenly across all paths to
enhance throughput and resource utilization. Each I/O operation is sent to the
next path in sequence.

When to use the round-robin policy:
  1. Balanced Workloads: Effective for balanced and predictable workloads with
     similar I/O size and type.
  2. Homogeneous Path Performance: Utilizes all paths efficiently when
     performance characteristics (e.g., latency, bandwidth) are similar.


Queue-Depth
-----------

The queue-depth policy manages I/O requests based on the current queue depth
of each path, selecting the path with the least number of in-flight I/Os.

When to use the queue-depth policy:
  1. High load with small I/Os: Effectively balances load across paths when
     the load is high, and I/O operations consist of small, relatively
     fixed-sized requests.

---

### Documentation Admin Guide Parport (`Documentation/admin-guide/parport.rst`)

Parport
+++++++

The ``parport`` code provides parallel-port support under Linux.  This
includes the ability to share one port between multiple device
drivers.

You can pass parameters to the ``parport`` code to override its automatic
detection of your hardware.  This is particularly useful if you want
to use IRQs, since in general these can't be autoprobed successfully.
By default IRQs are not used even if they **can** be probed.  This is
because there are a lot of people using the same IRQ for their
parallel port and a sound card or network card.

The ``parport`` code is split into two parts: generic (which deals with
port-sharing) and architecture-dependent (which deals with actually
using the port).


Parport as modules
==================

If you load the `parport`` code as a module, say::

	# insmod parport

to load the generic ``parport`` code.  You then must load the
architecture-dependent code with (for example)::

	# insmod parport_pc io=0x3bc,0x378,0x278 irq=none,7,auto

to tell the ``parport`` code that you want three PC-style ports, one at
0x3bc with no IRQ, one at 0x378 using IRQ 7, and one at 0x278 with an
auto-detected IRQ.  Currently, PC-style (``parport_pc``), Sun ``bpp``,
Amiga, Atari, and MFC3 hardware is supported.

PCI parallel I/O card support comes from ``parport_pc``.  Base I/O
addresses should not be specified for supported PCI cards since they
are automatically detected.


modprobe
--------

If you use modprobe , you will find it useful to add lines as below to a
configuration file in /etc/modprobe.d/ directory::

	alias parport_lowlevel parport_pc
	options parport_pc io=0x378,0x278 irq=7,auto

modprobe will load ``parport_pc`` (with the options ``io=0x378,0x278 irq=7,auto``)
whenever a parallel port device driver (such as ``lp``) is loaded.

Note that these are example lines only!  You shouldn't in general need
to specify any options to ``parport_pc`` in order to be able to use a
parallel port.


Parport probe [optional]
------------------------

In 2.2 kernels there was a module called ``parport_probe``, which was used
for collecting IEEE 1284 device ID information.  This has now been
enhanced and now lives with the IEEE 1284 support.  When a parallel
port is detected, the devices that are connected to it are analysed,
and information is logged like this::

	parport0: Printer, BJC-210 (Canon)

The probe information is available from files in ``/proc/sys/dev/parport/``.


Parport linked into the kernel statically
=========================================

If you compile the ``parport`` code into the kernel, then you can use
kernel boot parameters to get the same effect.  Add something like the
following to your LILO command line::

	parport=0x3bc parport=0x378,7 parport=0x278,auto,nofifo

You can have many ``parport=...`` statements, one for each port you want
to add.  Adding ``parport=0`` to the kernel command-line will disable
parport support entirely.  Adding ``parport=auto`` to the kernel
command-line will make ``parport`` use any IRQ lines or DMA channels that
it auto-detects.


Files in /proc
==============

If you have configured the ``/proc`` filesystem into your kernel, you will
see a new directory entry: ``/proc/sys/dev/parport``.  In there will be a
directory entry for each parallel port for which parport is
configured.  In each of those directories are a collection of files
describing that parallel port.

The ``/proc/sys/dev/parport`` directory tree looks like::

	parport
	|-- default
	|   |-- spintime
	|   `-- timeslice
	|-- parport0
	|   |-- autoprobe
	|   |-- autoprobe0
	|   |-- autoprobe1
	|   |-- autoprobe2
	|   |-- autoprobe3
	|   |-- devices
	|   |   |-- active
	|   |   `-- lp
	|   |       `-- timeslice
	|   |-- base-addr
	|   |-- irq
	|   |-- dma
	|   |-- modes
	|   `-- spintime
	`-- parport1
	|-- autoprobe
	|-- autoprobe0
	|-- autoprobe1
	|-- autoprobe2
	|-- autoprobe3
	|-- devices
	|   |-- active
	|   `-- ppa
	|       `-- timeslice
	|-- base-addr
	|-- irq
	|-- dma
	|-- modes
	`-- spintime

.. tabularcolumns:: |p{4.0cm}|p{13.5cm}|

=======================	=======================================================
File			Contents
=======================	=======================================================
``devices/active``	A list of the device drivers using that port.  A "+"
			will appear by the name of the device currently using
			the port (it might not appear against any).  The
			string "none" means that there are no device drivers
			using that port.

``base-addr``		Parallel port's base address, or addresses if the port
			has more than one in which case they are separated
			with tabs.  These values might not have any sensible
			meaning for some ports.

``irq``			Parallel port's IRQ, or -1 if none is being used.

``dma``			Parallel port's DMA channel, or -1 if none is being
			used.

``modes``		Parallel port's hardware modes, comma-separated,
			meaning:

			- PCSPP
				PC-style SPP registers are available.

			- TRISTATE
				Port is bidirectional.

			- COMPAT
				Hardware acceleration for printers is
				available and will be used.

			- EPP
				Hardware acceleration for EPP protocol
				is available and will be used.

			- ECP
				Hardware acceleration for ECP protocol
				is available and will be used.

			- DMA
				DMA is available and will be used.

			Note that the current implementation will only take
			advantage of COMPAT and ECP modes if it has an IRQ
			line to use.

``autoprobe``		Any IEEE-1284 device ID information that has been
			acquired from the (non-IEEE 1284.3) device.

``autoprobe[0-3]``	IEEE 1284 device ID information retrieved from
			daisy-chain devices that conform to IEEE 1284.3.

``spintime``		The number of microseconds to busy-loop while waiting
			for the peripheral to respond.  You might find that
			adjusting this improves performance, depending on your
			peripherals.  This is a port-wide setting, i.e. it
			applies to all devices on a particular port.

``timeslice``		The number of milliseconds that a device driver is
			allowed to keep a port claimed for.  This is advisory,
			and driver can ignore it if it must.

``default/*``		The defaults for spintime and timeslice. When a new
			port is	registered, it picks up the default spintime.
			When a new device is registered, it picks up the
			default timeslice.
=======================	=======================================================

Device drivers
==============

Once the parport code is initialised, you can attach device drivers to
specific ports.  Normally this happens automatically; if the lp driver
is loaded it will create one lp device for each port found.  You can
override this, though, by using parameters either when you load the lp
driver::

	# insmod lp parport=0,2

or on the LILO command line::

	lp=parport0 lp=parport2

Both the above examples would inform lp that you want ``/dev/lp0`` to be
the first parallel port, and /dev/lp1 to be the **third** parallel port,
with no lp device associated with the second port (parport1).  Note
that this is different to the way older kernels worked; there used to
be a static association between the I/O port address and the device
name, so ``/dev/lp0`` was always the port at 0x3bc.  This is no longer the
case - if you only have one port, it will default to being ``/dev/lp0``,
regardless of base address.

Also:

 * If you selected the IEEE 1284 support at compile time, you can say
   ``lp=auto`` on the kernel command line, and lp will create devices
   only for those ports that seem to have printers attached.

 * If you give PLIP the ``timid`` parameter, either with ``plip=timid`` on
   the command line, or with ``insmod plip timid=1`` when using modules,
   it will avoid any ports that seem to be in use by other devices.

 * IRQ autoprobing works only for a few port types at the moment.

Reporting printer problems with parport
=======================================

If you are having problems printing, please go through these steps to
try to narrow down where the problem area is.

When reporting problems with parport, really you need to give all of
the messages that ``parport_pc`` spits out when it initialises.  There are
several code paths:

- polling
- interrupt-driven, protocol in software
- interrupt-driven, protocol in hardware using PIO
- interrupt-driven, protocol in hardware using DMA

The kernel messages that ``parport_pc`` logs give an indication of which
code path is being used. (They could be a lot better actually..)

For normal printer protocol, having IEEE 1284 modes enabled or not
should not make a difference.

To turn off the 'protocol in hardware' code paths, disable
``CONFIG_PARPORT_PC_FIFO``.  Note that when they are enabled they are not
necessarily **used**; it depends on whether the hardware is available,
enabled by the BIOS, and detected by the driver.

So, to start with, disable ``CONFIG_PARPORT_PC_FIFO``, and load ``parport_pc``
with ``irq=none``. See if printing works then.  It really should,
because this is the simplest code path.

If that works fine, try with ``io=0x378 irq=7`` (adjust for your
hardware), to make it use interrupt-driven in-software protocol.

If **that** works fine, then one of the hardware modes isn't working
right.  Enable ``CONFIG_FIFO`` (no, it isn't a module option,
and yes, it should be), set the port to ECP mode in the BIOS and note
the DMA channel, and try with::

    io=0x378 irq=7 dma=none (for PIO)
    io=0x378 irq=7 dma=3 (for DMA)

----------

philb@gnu.org
tim@cyberelk.net

---

### Documentation Admin Guide Perf Security (`Documentation/admin-guide/perf-security.rst`)

.. _perf_security:

Perf events and tool security
=============================

Overview
--------

Usage of Performance Counters for Linux (perf_events) [1]_ , [2]_ , [3]_
can impose a considerable risk of leaking sensitive data accessed by
monitored processes. The data leakage is possible both in scenarios of
direct usage of perf_events system call API [2]_ and over data files
generated by Perf tool user mode utility (Perf) [3]_ , [4]_ . The risk
depends on the nature of data that perf_events performance monitoring
units (PMU) [2]_ and Perf collect and expose for performance analysis.
Collected system and performance data may be split into several
categories:

1. System hardware and software configuration data, for example: a CPU
   model and its cache configuration, an amount of available memory and
   its topology, used kernel and Perf versions, performance monitoring
   setup including experiment time, events configuration, Perf command
   line parameters, etc.

2. User and kernel module paths and their load addresses with sizes,
   process and thread names with their PIDs and TIDs, timestamps for
   captured hardware and software events.

3. Content of kernel software counters (e.g., for context switches, page
   faults, CPU migrations), architectural hardware performance counters
   (PMC) [8]_ and machine specific registers (MSR) [9]_ that provide
   execution metrics for various monitored parts of the system (e.g.,
   memory controller (IMC), interconnect (QPI/UPI) or peripheral (PCIe)
   uncore counters) without direct attribution to any execution context
   state.

4. Content of architectural execution context registers (e.g., RIP, RSP,
   RBP on x86_64), process user and kernel space memory addresses and
   data, content of various architectural MSRs that capture data from
   this category.

Data that belong to the fourth category can potentially contain
sensitive process data. If PMUs in some monitoring modes capture values
of execution context registers or data from process memory then access
to such monitoring modes requires to be ordered and secured properly.
So, perf_events performance monitoring and observability operations are
the subject for security access control management [5]_ .

perf_events access control
-------------------------------

To perform security checks, the Linux implementation splits processes
into two categories [6]_ : a) privileged processes (whose effective user
ID is 0, referred to as superuser or root), and b) unprivileged
processes (whose effective UID is nonzero). Privileged processes bypass
all kernel security permission checks so perf_events performance
monitoring is fully available to privileged processes without access,
scope and resource restrictions.

Unprivileged processes are subject to a full security permission check
based on the process's credentials [5]_ (usually: effective UID,
effective GID, and supplementary group list).

Linux divides the privileges traditionally associated with superuser
into distinct units, known as capabilities [6]_ , which can be
independently enabled and disabled on per-thread basis for processes and
files of unprivileged users.

Unprivileged processes with enabled CAP_PERFMON capability are treated
as privileged processes with respect to perf_events performance
monitoring and observability operations, thus, bypass *scope* permissions
checks in the kernel. CAP_PERFMON implements the principle of least
privilege [13]_ (POSIX 1003.1e: 2.2.2.39) for performance monitoring and
observability operations in the kernel and provides a secure approach to
performance monitoring and observability in the system.

For backward compatibility reasons the access to perf_events monitoring and
observability operations is also open for CAP_SYS_ADMIN privileged
processes but CAP_SYS_ADMIN usage for secure monitoring and observability
use cases is discouraged with respect to the CAP_PERFMON capability.
If system audit records [14]_ for a process using perf_events system call
API contain denial records of acquiring both CAP_PERFMON and CAP_SYS_ADMIN
capabilities then providing the process with CAP_PERFMON capability singly
is recommended as the preferred secure approach to resolve double access
denial logging related to usage of performance monitoring and observability.

Prior Linux v5.9 unprivileged processes using perf_events system call
are also subject for PTRACE_MODE_READ_REALCREDS ptrace access mode check
[7]_ , whose outcome determines whether monitoring is permitted.
So unprivileged processes provided with CAP_SYS_PTRACE capability are
effectively permitted to pass the check. Starting from Linux v5.9
CAP_SYS_PTRACE capability is not required and CAP_PERFMON is enough to
be provided for processes to make performance monitoring and observability
operations.

Other capabilities being granted to unprivileged processes can
effectively enable capturing of additional data required for later
performance analysis of monitored processes or a system. For example,
CAP_SYSLOG capability permits reading kernel space memory addresses from
/proc/kallsyms file.

Privileged Perf users groups
---------------------------------

Mechanisms of capabilities, privileged capability-dumb files [6]_,
file system ACLs [10]_ and sudo [15]_ utility can be used to create
dedicated groups of privileged Perf users who are permitted to execute
performance monitoring and observability without limits. The following
steps can be taken to create such groups of privileged Perf users.

1. Create perf_users group of privileged Perf users, assign perf_users
   group to Perf tool executable and limit access to the executable for
   other users in the system who are not in the perf_users group:

::

   # groupadd perf_users
   # ls -alhF
   -rwxr-xr-x  2 root root  11M Oct 19 15:12 perf
   # chgrp perf_users perf
   # ls -alhF
   -rwxr-xr-x  2 root perf_users  11M Oct 19 15:12 perf
   # chmod o-rwx perf
   # ls -alhF
   -rwxr-x---  2 root perf_users  11M Oct 19 15:12 perf

2. Assign the required capabilities to the Perf tool executable file and
   enable members of perf_users group with monitoring and observability
   privileges [6]_ :

::

   # setcap "cap_perfmon,cap_sys_ptrace,cap_syslog=ep" perf
   # setcap -v "cap_perfmon,cap_sys_ptrace,cap_syslog=ep" perf
   perf: OK
   # getcap perf
   perf = cap_sys_ptrace,cap_syslog,cap_perfmon+ep

If the libcap [16]_ installed doesn't yet support "cap_perfmon", use "38" instead,
i.e.:

::

   # setcap "38,cap_ipc_lock,cap_sys_ptrace,cap_syslog=ep" perf

Note that you may need to have 'cap_ipc_lock' in the mix for tools such as
'perf top', alternatively use 'perf top -m N', to reduce the memory that
it uses for the perf ring buffer, see the memory allocation section below.

Using a libcap without support for CAP_PERFMON will make cap_get_flag(caps, 38,
CAP_EFFECTIVE, &val) fail, which will lead the default event to be 'cycles:u',
so as a workaround explicitly ask for the 'cycles' event, i.e.:

::

  # perf top -e cycles

To get kernel and user samples with a perf binary with just CAP_PERFMON.

As a result, members of perf_users group are capable of conducting
performance monitoring and observability by using functionality of the
configured Perf tool executable that, when executes, passes perf_events
subsystem scope checks.

In case Perf tool executable can't be assigned required capabilities (e.g.
file system is mounted with nosuid option or extended attributes are
not supported by the file system) then creation of the capabilities
privileged environment, naturally shell, is possible. The shell provides
inherent processes with CAP_PERFMON and other required capabilities so that
performance monitoring and observability operations are available in the
environment without limits. Access to the environment can be open via sudo
utility for members of perf_users group only. In order to create such
environment:

1. Create shell script that uses capsh utility [16]_ to assign CAP_PERFMON
   and other required capabilities into ambient capability set of the shell
   process, lock the process security bits after enabling SECBIT_NO_SETUID_FIXUP,
   SECBIT_NOROOT and SECBIT_NO_CAP_AMBIENT_RAISE bits and then change
   the process identity to sudo caller of the script who should essentially
   be a member of perf_users group:

::

   # ls -alh /usr/local/bin/perf.shell
   -rwxr-xr-x. 1 root root 83 Oct 13 23:57 /usr/local/bin/perf.shell
   # cat /usr/local/bin/perf.shell
   exec /usr/sbin/capsh --iab=^cap_perfmon --secbits=239 --user=$SUDO_USER -- -l

2. Extend sudo policy at /etc/sudoers file with a rule for perf_users group:

::

   # grep perf_users /etc/sudoers
   %perf_users    ALL=/usr/local/bin/perf.shell

3. Check that members of perf_users group have access to the privileged
   shell and have CAP_PERFMON and other required capabilities enabled
   in permitted, effective and ambient capability sets of an inherent process:

::

  $ id
  uid=1003(capsh_test) gid=1004(capsh_test) groups=1004(capsh_test),1000(perf_users) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
  $ sudo perf.shell
  [sudo] password for capsh_test:
  $ grep Cap /proc/self/status
  CapInh:        0000004000000000
  CapPrm:        0000004000000000
  CapEff:        0000004000000000
  CapBnd:        000000ffffffffff
  CapAmb:        0000004000000000
  $ capsh --decode=0000004000000000
  0x0000004000000000=cap_perfmon

As a result, members of perf_users group have access to the privileged
environment where they can use tools employing performance monitoring APIs
governed by CAP_PERFMON Linux capability.

This specific access control management is only available to superuser
or root running processes with CAP_SETPCAP, CAP_SETFCAP [6]_
capabilities.

Unprivileged users
-----------------------------------

perf_events *scope* and *access* control for unprivileged processes
is governed by perf_event_paranoid [2]_ setting:

-1:
     Impose no *scope* and *access* restrictions on using perf_events
     performance monitoring. Per-user per-cpu perf_event_mlock_kb [2]_
     locking limit is ignored when allocating memory buffers for storing
     performance data. This is the least secure mode since allowed
     monitored *scope* is maximized and no perf_events specific limits
     are imposed on *resources* allocated for performance monitoring.

>=0:
     *scope* includes per-process and system wide performance monitoring
     but excludes raw tracepoints and ftrace function tracepoints
     monitoring. CPU and system events happened when executing either in
     user or in kernel space can be monitored and captured for later
     analysis. Per-user per-cpu perf_event_mlock_kb locking limit is
     imposed but ignored for unprivileged processes with CAP_IPC_LOCK
     [6]_ capability.

>=1:
     *scope* includes per-process performance monitoring only and
     excludes system wide performance monitoring. CPU and system events
     happened when executing either in user or in kernel space can be
     monitored and captured for later analysis. Per-user per-cpu
     perf_event_mlock_kb locking limit is imposed but ignored for
     unprivileged processes with CAP_IPC_LOCK capability.

>=2:
     *scope* includes per-process performance monitoring only. CPU and
     system events happened when executing in user space only can be
     monitored and captured for later analysis. Per-user per-cpu
     perf_event_mlock_kb locking limit is imposed but ignored for
     unprivileged processes with CAP_IPC_LOCK capability.

Resource control
---------------------------------

Open file descriptors
+++++++++++++++++++++

The perf_events system call API [2]_ allocates file descriptors for
every configured PMU event. Open file descriptors are a per-process
accountable resource governed by the RLIMIT_NOFILE [11]_ limit
(ulimit -n), which is usually derived from the login shell process. When
configuring Perf collection for a long list of events on a large server
system, this limit can be easily hit preventing required monitoring
configuration. RLIMIT_NOFILE limit can be increased on per-user basis
modifying content of the limits.conf file [12]_ . Ordinarily, a Perf
sampling session (perf record) requires an amount of open perf_event
file descriptors that is not less than the number of monitored events
multiplied by the number of monitored CPUs.

Memory allocation
+++++++++++++++++

The amount of memory available to user processes for capturing
performance monitoring data is governed by the perf_event_mlock_kb [2]_
setting. This perf_event specific resource setting defines overall
per-cpu limits of memory allowed for mapping by the user processes to
execute performance monitoring. The setting essentially extends the
RLIMIT_MEMLOCK [11]_ limit, but only for memory regions mapped
specifically for capturing monitored performance events and related data.

For example, if a machine has eight cores and perf_event_mlock_kb limit
is set to 516 KiB, then a user process is provided with 516 KiB * 8 =
4128 KiB of memory above the RLIMIT_MEMLOCK limit (ulimit -l) for
perf_event mmap buffers. In particular, this means that, if the user
wants to start two or more performance monitoring processes, the user is
required to manually distribute the available 4128 KiB between the
monitoring processes, for example, using the --mmap-pages Perf record
mode option. Otherwise, the first started performance monitoring process
allocates all available 4128 KiB and the other processes will fail to
proceed due to the lack of memory.

RLIMIT_MEMLOCK and perf_event_mlock_kb resource constraints are ignored
for processes with the CAP_IPC_LOCK capability. Thus, perf_events/Perf
privileged users can be provided with memory above the constraints for
perf_events/Perf performance monitoring purpose by providing the Perf
executable with CAP_IPC_LOCK capability.

Bibliography
------------

.. [1] `<https://lwn.net/Articles/337493/>`_
.. [2] `<http://man7.org/linux/man-pages/man2/perf_event_open.2.html>`_
.. [3] `<http://web.eece.maine.edu/~vweaver/projects/perf_events/>`_
.. [4] `<https://perf.wiki.kernel.org/index.php/Main_Page>`_
.. [5] `<https://www.kernel.org/doc/html/latest/security/credentials.html>`_
.. [6] `<http://man7.org/linux/man-pages/man7/capabilities.7.html>`_
.. [7] `<http://man7.org/linux/man-pages/man2/ptrace.2.html>`_
.. [8] `<https://en.wikipedia.org/wiki/Hardware_performance_counter>`_
.. [9] `<https://en.wikipedia.org/wiki/Model-specific_register>`_
.. [10] `<http://man7.org/linux/man-pages/man5/acl.5.html>`_
.. [11] `<http://man7.org/linux/man-pages/man2/getrlimit.2.html>`_
.. [12] `<http://man7.org/linux/man-pages/man5/limits.conf.5.html>`_
.. [13] `<https://sites.google.com/site/fullycapable>`_
.. [14] `<http://man7.org/linux/man-pages/man8/auditd.8.html>`_
.. [15] `<https://man7.org/linux/man-pages/man8/sudo.8.html>`_
.. [16] `<https://git.kernel.org/pub/scm/libs/libcap/libcap.git/>`_

---

### Documentation Admin Guide Pnp (`Documentation/admin-guide/pnp.rst`)

=================================
Linux Plug and Play Documentation
=================================

:Author: Adam Belay <ambx1@neo.rr.com>
:Last updated: Oct. 16, 2002


Overview
--------

Plug and Play provides a means of detecting and setting resources for legacy or
otherwise unconfigurable devices.  The Linux Plug and Play Layer provides these 
services to compatible drivers.


The User Interface
------------------

The Linux Plug and Play user interface provides a means to activate PnP devices
for legacy and user level drivers that do not support Linux Plug and Play.  The 
user interface is integrated into sysfs.

In addition to the standard sysfs file the following are created in each
device's directory:
- id - displays a list of support EISA IDs
- options - displays possible resource configurations
- resources - displays currently allocated resources and allows resource changes

activating a device
^^^^^^^^^^^^^^^^^^^

::

	# echo "auto" > resources

this will invoke the automatic resource config system to activate the device

manually activating a device
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

::

	# echo "manual <depnum> <mode>" > resources

	<depnum> - the configuration number
	<mode> - static or dynamic
		 static = for next boot
		 dynamic = now

disabling a device
^^^^^^^^^^^^^^^^^^

::

	# echo "disable" > resources


EXAMPLE:

Suppose you need to activate the floppy disk controller.

1. change to the proper directory, in my case it is
   /driver/bus/pnp/devices/00:0f::

	# cd /driver/bus/pnp/devices/00:0f
	# cat name
	PC standard floppy disk controller

2. check if the device is already active::

	# cat resources
	DISABLED

  - Notice the string "DISABLED".  This means the device is not active.

3. check the device's possible configurations (optional)::

	# cat options
	Dependent: 01 - Priority acceptable
	    port 0x3f0-0x3f0, align 0x7, size 0x6, 16-bit address decoding
	    port 0x3f7-0x3f7, align 0x0, size 0x1, 16-bit address decoding
	    irq 6
	    dma 2 8-bit compatible
	Dependent: 02 - Priority acceptable
	    port 0x370-0x370, align 0x7, size 0x6, 16-bit address decoding
	    port 0x377-0x377, align 0x0, size 0x1, 16-bit address decoding
	    irq 6
	    dma 2 8-bit compatible

4. now activate the device::

	# echo "auto" > resources

5. finally check if the device is active::

	# cat resources
	io 0x3f0-0x3f5
	io 0x3f7-0x3f7
	irq 6
	dma 2

also there are a series of kernel parameters::

	pnp_reserve_irq=irq1[,irq2] ....
	pnp_reserve_dma=dma1[,dma2] ....
	pnp_reserve_io=io1,size1[,io2,size2] ....
	pnp_reserve_mem=mem1,size1[,mem2,size2] ....



The Unified Plug and Play Layer
-------------------------------

All Plug and Play drivers, protocols, and services meet at a central location
called the Plug and Play Layer.  This layer is responsible for the exchange of 
information between PnP drivers and PnP protocols.  Thus it automatically 
forwards commands to the proper protocol.  This makes writing PnP drivers 
significantly easier.

The following functions are available from the Plug and Play Layer:

pnp_get_protocol
  increments the number of uses by one

pnp_put_protocol
  deincrements the number of uses by one

pnp_register_protocol
  use this to register a new PnP protocol

pnp_register_driver
  adds a PnP driver to the Plug and Play Layer

  this includes driver model integration
  returns zero for success or a negative error number for failure; count
  calls to the .add() method if you need to know how many devices bind to
  the driver

pnp_unregister_driver
  removes a PnP driver from the Plug and Play Layer



Plug and Play Protocols
-----------------------

This section contains information for PnP protocol developers.

The following Protocols are currently available in the computing world:

- PNPBIOS:
    used for system devices such as serial and parallel ports.
- ISAPNP:
    provides PnP support for the ISA bus
- ACPI:
    among its many uses, ACPI provides information about system level
    devices.

It is meant to replace the PNPBIOS.  It is not currently supported by Linux
Plug and Play but it is planned to be in the near future.


Requirements for a Linux PnP protocol:
1. the protocol must use EISA IDs
2. the protocol must inform the PnP Layer of a device's current configuration

- the ability to set resources is optional but preferred.

The following are PnP protocol related functions:

pnp_add_device
  use this function to add a PnP device to the PnP layer

  only call this function when all wanted values are set in the pnp_dev
  structure

pnp_init_device
  call this to initialize the PnP structure

pnp_remove_device
  call this to remove a device from the Plug and Play Layer.
  it will fail if the device is still in use.
  automatically will free mem used by the device and related structures

pnp_add_id
  adds an EISA ID to the list of supported IDs for the specified device

For more information consult the source of a protocol such as
/drivers/pnp/pnpbios/core.c.



Linux Plug and Play Drivers
---------------------------

This section contains information for Linux PnP driver developers.

The New Way
^^^^^^^^^^^

1. first make a list of supported EISA IDS

   ex::

	static const struct pnp_id pnp_dev_table[] = {
		/* Standard LPT Printer Port */
		{.id = "PNP0400", .driver_data = 0},
		/* ECP Printer Port */
		{.id = "PNP0401", .driver_data = 0},
		{.id = ""}
	};

   Please note that the character 'X' can be used as a wild card in the function
   portion (last four characters).

   ex::

	/* Unknown PnP modems */
	{	"PNPCXXX",		UNKNOWN_DEV	},

   Supported PnP card IDs can optionally be defined.
   ex::

	static const struct pnp_id pnp_card_table[] = {
		{	"ANYDEVS",		0	},
		{	"",			0	}
	};

2. Optionally define probe and remove functions.  It may make sense not to
   define these functions if the driver already has a reliable method of detecting
   the resources, such as the parport_pc driver.

   ex::

	static int
	serial_pnp_probe(struct pnp_dev * dev, const struct pnp_id *card_id, const
			struct pnp_id *dev_id)
	{
	. . .

   ex::

	static void serial_pnp_remove(struct pnp_dev * dev)
	{
	. . .

   consult /drivers/serial/8250_pnp.c for more information.

3. create a driver structure

   ex::

	static struct pnp_driver serial_pnp_driver = {
		.name		= "serial",
		.card_id_table	= pnp_card_table,
		.id_table	= pnp_dev_table,
		.probe		= serial_pnp_probe,
		.remove		= serial_pnp_remove,
	};

   * name and id_table cannot be NULL.

4. register the driver

   ex::

	static int __init serial8250_pnp_init(void)
	{
		return pnp_register_driver(&serial_pnp_driver);
	}

The Old Way
^^^^^^^^^^^

A series of compatibility functions have been created to make it easy to convert
ISAPNP drivers.  They should serve as a temporary solution only.

They are as follows::

	struct pnp_dev *pnp_find_dev(struct pnp_card *card,
				     unsigned short vendor,
				     unsigned short function,
				     struct pnp_dev *from)

---

### Documentation Admin Guide Pstore Blk (`Documentation/admin-guide/pstore-blk.rst`)

.. SPDX-License-Identifier: GPL-2.0

pstore block oops/panic logger
==============================

Introduction
------------

pstore block (pstore/blk) is an oops/panic logger that writes its logs to a
block device and non-block device before the system crashes. You can get
these log files by mounting pstore filesystem like::

    mount -t pstore pstore /sys/fs/pstore


pstore block concepts
---------------------

pstore/blk provides efficient configuration method for pstore/blk, which
divides all configurations into two parts, configurations for user and
configurations for driver.

Configurations for user determine how pstore/blk works, such as pmsg_size,
kmsg_size and so on. All of them support both Kconfig and module parameters,
but module parameters have priority over Kconfig.

Configurations for driver are all about block device and non-block device,
such as total_size of block device and read/write operations.

Configurations for user
-----------------------

All of these configurations support both Kconfig and module parameters, but
module parameters have priority over Kconfig.

Here is an example for module parameters::

        pstore_blk.blkdev=/dev/mmcblk0p7 pstore_blk.kmsg_size=64 best_effort=y

The detail of each configurations may be of interest to you.

blkdev
~~~~~~

The block device to use. Most of the time, it is a partition of block device.
It's required for pstore/blk. It is also used for MTD device.

When pstore/blk is built as a module, "blkdev" accepts the following variants:

1. /dev/<disk_name> represents the device number of disk
#. /dev/<disk_name><decimal> represents the device number of partition - device
   number of disk plus the partition number
#. /dev/<disk_name>p<decimal> - same as the above; this form is used when disk
   name of partitioned disk ends with a digit.

When pstore/blk is built into the kernel, "blkdev" accepts the following variants:

#. <hex_major><hex_minor> device number in hexadecimal representation,
   with no leading 0x, for example b302.
#. PARTUUID=00112233-4455-6677-8899-AABBCCDDEEFF represents the unique id of
   a partition if the partition table provides it. The UUID may be either an
   EFI/GPT UUID, or refer to an MSDOS partition using the format SSSSSSSS-PP,
   where SSSSSSSS is a zero-filled hex representation of the 32-bit
   "NT disk signature", and PP is a zero-filled hex representation of the
   1-based partition number.
#. PARTUUID=<UUID>/PARTNROFF=<int> to select a partition in relation to a
   partition with a known unique id.
#. <major>:<minor> major and minor number of the device separated by a colon.

It accepts the following variants for MTD device:

1. <device name> MTD device name. "pstore" is recommended.
#. <device number> MTD device number.

kmsg_size
~~~~~~~~~

The chunk size in KB for oops/panic front-end. It **MUST** be a multiple of 4.
It's optional if you do not care about the oops/panic log.

There are multiple chunks for oops/panic front-end depending on the remaining
space except other pstore front-ends.

pstore/blk will log to oops/panic chunks one by one, and always overwrite the
oldest chunk if there is no more free chunk.

pmsg_size
~~~~~~~~~

The chunk size in KB for pmsg front-end. It **MUST** be a multiple of 4.
It's optional if you do not care about the pmsg log.

Unlike oops/panic front-end, there is only one chunk for pmsg front-end.

Pmsg is a user space accessible pstore object. Writes to */dev/pmsg0* are
appended to the chunk. On reboot the contents are available in
*/sys/fs/pstore/pmsg-pstore-blk-0*.

console_size
~~~~~~~~~~~~

The chunk size in KB for console front-end.  It **MUST** be a multiple of 4.
It's optional if you do not care about the console log.

Similar to pmsg front-end, there is only one chunk for console front-end.

All log of console will be appended to the chunk. On reboot the contents are
available in */sys/fs/pstore/console-pstore-blk-0*.

ftrace_size
~~~~~~~~~~~

The chunk size in KB for ftrace front-end. It **MUST** be a multiple of 4.
It's optional if you do not care about the ftrace log.

Similar to oops front-end, there are multiple chunks for ftrace front-end
depending on the count of cpu processors. Each chunk size is equal to
ftrace_size / processors_count.

All log of ftrace will be appended to the chunk. On reboot the contents are
combined and available in */sys/fs/pstore/ftrace-pstore-blk-0*.

Persistent function tracing might be useful for debugging software or hardware
related hangs. Here is an example of usage::

 # mount -t pstore pstore /sys/fs/pstore
 # mount -t debugfs debugfs /sys/kernel/debug/
 # echo 1 > /sys/kernel/debug/pstore/record_ftrace
 # reboot -f
 [...]
 # mount -t pstore pstore /sys/fs/pstore
 # tail /sys/fs/pstore/ftrace-pstore-blk-0
 CPU:0 ts:5914676 c0063828  c0063b94  call_cpuidle <- cpu_startup_entry+0x1b8/0x1e0
 CPU:0 ts:5914678 c039ecdc  c006385c  cpuidle_enter_state <- call_cpuidle+0x44/0x48
 CPU:0 ts:5914680 c039e9a0  c039ecf0  cpuidle_enter_freeze <- cpuidle_enter_state+0x304/0x314
 CPU:0 ts:5914681 c0063870  c039ea30  sched_idle_set_state <- cpuidle_enter_state+0x44/0x314
 CPU:1 ts:5916720 c0160f59  c015ee04  kernfs_unmap_bin_file <- __kernfs_remove+0x140/0x204
 CPU:1 ts:5916721 c05ca625  c015ee0c  __mutex_lock_slowpath <- __kernfs_remove+0x148/0x204
 CPU:1 ts:5916723 c05c813d  c05ca630  yield_to <- __mutex_lock_slowpath+0x314/0x358
 CPU:1 ts:5916724 c05ca2d1  c05ca638  __ww_mutex_lock <- __mutex_lock_slowpath+0x31c/0x358

max_reason
~~~~~~~~~~

Limiting which kinds of kmsg dumps are stored can be controlled via
the ``max_reason`` value, as defined in include/linux/kmsg_dump.h's
``enum kmsg_dump_reason``. For example, to store both Oopses and Panics,
``max_reason`` should be set to 2 (KMSG_DUMP_OOPS), to store only Panics
``max_reason`` should be set to 1 (KMSG_DUMP_PANIC). Setting this to 0
(KMSG_DUMP_UNDEF), means the reason filtering will be controlled by the
``printk.always_kmsg_dump`` boot param: if unset, it'll be KMSG_DUMP_OOPS,
otherwise KMSG_DUMP_MAX.

Configurations for driver
-------------------------

A device driver uses ``register_pstore_device`` with
``struct pstore_device_info`` to register to pstore/blk.

.. kernel-doc:: fs/pstore/blk.c
   :export:

Compression and header
----------------------

Block device is large enough for uncompressed oops data. Actually we do not
recommend data compression because pstore/blk will insert some information into
the first line of oops/panic data. For example::

        Panic: Total 16 times

It means that it's OOPS|Panic for the 16th time since the first booting.
Sometimes the number of occurrences of oops|panic since the first booting is
important to judge whether the system is stable.

The following line is inserted by pstore filesystem. For example::

        Oops#2 Part1

It means that it's OOPS for the 2nd time on the last boot.

Reading the data
----------------

The dump data can be read from the pstore filesystem. The format for these
files is ``dmesg-pstore-blk-[N]`` for oops/panic front-end,
``pmsg-pstore-blk-0`` for pmsg front-end and so on.  The timestamp of the
dump file records the trigger time. To delete a stored record from block
device, simply unlink the respective pstore file.

Attentions in panic read/write APIs
-----------------------------------

If on panic, the kernel is not going to run for much longer, the tasks will not
be scheduled and most kernel resources will be out of service. It
looks like a single-threaded program running on a single-core computer.

The following points require special attention for panic read/write APIs:

1. Can **NOT** allocate any memory.
   If you need memory, just allocate while the block driver is initializing
   rather than waiting until the panic.
#. Must be polled, **NOT** interrupt driven.
   No task schedule any more. The block driver should delay to ensure the write
   succeeds, but NOT sleep.
#. Can **NOT** take any lock.
   There is no other task, nor any shared resource; you are safe to break all
   locks.
#. Just use CPU to transfer.
   Do not use DMA to transfer unless you are sure that DMA will not keep lock.
#. Control registers directly.
   Please control registers directly rather than use Linux kernel resources.
   Do I/O map while initializing rather than wait until a panic occurs.
#. Reset your block device and controller if necessary.
   If you are not sure of the state of your block device and controller when
   a panic occurs, you are safe to stop and reset them.

pstore/blk supports psblk_blkdev_info(), which is defined in
*linux/pstore_blk.h*, to get information of using block device, such as the
device number, sector count and start sector of the whole disk.

pstore block internals
----------------------

For developer reference, here are all the important structures and APIs:

.. kernel-doc:: fs/pstore/zone.c
   :internal:

.. kernel-doc:: include/linux/pstore_zone.h
   :internal:

.. kernel-doc:: include/linux/pstore_blk.h
   :internal:

---

### Documentation Admin Guide Quickly Build Trimmed Linux (`Documentation/admin-guide/quickly-build-trimmed-linux.rst`)

.. SPDX-License-Identifier: (GPL-2.0+ OR CC-BY-4.0)
.. [see the bottom of this file for redistribution information]

===========================================
How to quickly build a trimmed Linux kernel
===========================================

This guide explains how to swiftly build Linux kernels that are ideal for
testing purposes, but perfectly fine for day-to-day use, too.

The essence of the process (aka 'TL;DR')
========================================

*[If you are new to compiling Linux, ignore this TLDR and head over to the next
section below: it contains a step-by-step guide, which is more detailed, but
still brief and easy to follow; that guide and its accompanying reference
section also mention alternatives, pitfalls, and additional aspects, all of
which might be relevant for you.]*

If your system uses techniques like Secure Boot, prepare it to permit starting
self-compiled Linux kernels; install compilers and everything else needed for
building Linux; make sure to have 12 Gigabyte free space in your home directory.
Now run the following commands to download fresh Linux mainline sources, which
you then use to configure, build and install your own kernel::

    git clone --depth 1 -b master \
      https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git ~/linux/
    cd ~/linux/
    # Hint: if you want to apply patches, do it at this point. See below for details.
    # Hint: it's recommended to tag your build at this point. See below for details.
    yes "" | make localmodconfig
    # Hint: at this point you might want to adjust the build configuration; you'll
    #   have to, if you are running Debian. See below for details.
    make -j $(nproc --all)
    # Note: on many commodity distributions the next command suffices, but on Arch
    #   Linux, its derivatives, and some others it does not. See below for details.
    command -v installkernel && sudo make modules_install install
    reboot

If you later want to build a newer mainline snapshot, use these commands::

    cd ~/linux/
    git fetch --depth 1 origin
    # Note: the next command will discard any changes you did to the code:
    git checkout --force --detach origin/master
    # Reminder: if you want to (re)apply patches, do it at this point.
    # Reminder: you might want to add or modify a build tag at this point.
    make olddefconfig
    make -j $(nproc --all)
    # Reminder: the next command on some distributions does not suffice.
    command -v installkernel && sudo make modules_install install
    reboot

Step-by-step guide
==================

Compiling your own Linux kernel is easy in principle. There are various ways to
do it. Which of them actually work and is the best depends on the circumstances.

This guide describes a way perfectly suited for those who want to quickly
install Linux from sources without being bothered by complicated details; the
goal is to cover everything typically needed on mainstream Linux distributions
running on commodity PC or server hardware.

The described approach is great for testing purposes, for example to try a
proposed fix or to check if a problem was already fixed in the latest codebase.
Nonetheless, kernels built this way are also totally fine for day-to-day use
while at the same time being easy to keep up to date.

The following steps describe the important aspects of the process; a
comprehensive reference section later explains each of them in more detail. It
sometimes also describes alternative approaches, pitfalls, as well as errors
that might occur at a particular point -- and how to then get things rolling
again.

..
   Note: if you see this note, you are reading the text's source file. You
   might want to switch to a rendered version, as it makes it a lot easier to
   quickly look something up in the reference section and afterwards jump back
   to where you left off. Find a the latest rendered version here:
   https://docs.kernel.org/admin-guide/quickly-build-trimmed-linux.html

.. _backup_sbs:

 * Create a fresh backup and put system repair and restore tools at hand, just
   to be prepared for the unlikely case of something going sideways.

   [:ref:`details<backup>`]

.. _secureboot_sbs:

 * On platforms with 'Secure Boot' or similar techniques, prepare everything to
   ensure the system will permit your self-compiled kernel to boot later. The
   quickest and easiest way to achieve this on commodity x86 systems is to
   disable such techniques in the BIOS setup utility; alternatively, remove
   their restrictions through a process initiated by
   ``mokutil --disable-validation``.

   [:ref:`details<secureboot>`]

.. _buildrequires_sbs:

 * Install all software required to build a Linux kernel. Often you will need:
   'bc', 'binutils' ('ld' et al.), 'bison', 'flex', 'gcc', 'git', 'openssl',
   'pahole', 'perl', and the development headers for 'libelf' and 'openssl'. The
   reference section shows how to quickly install those on various popular Linux
   distributions.

   [:ref:`details<buildrequires>`]

.. _diskspace_sbs:

 * Ensure to have enough free space for building and installing Linux. For the
   latter 150 Megabyte in /lib/ and 100 in /boot/ are a safe bet. For storing
   sources and build artifacts 12 Gigabyte in your home directory should
   typically suffice. If you have less available, be sure to check the reference
   section for the step that explains adjusting your kernels build
   configuration: it mentions a trick that reduce the amount of required space
   in /home/ to around 4 Gigabyte.

   [:ref:`details<diskspace>`]

.. _sources_sbs:

 * Retrieve the sources of the Linux version you intend to build; then change
   into the directory holding them, as all further commands in this guide are
   meant to be executed from there.

   *[Note: the following paragraphs describe how to retrieve the sources by
   partially cloning the Linux stable git repository. This is called a shallow
   clone. The reference section explains two alternatives:* :ref:`packaged
   archives<sources_archive>` *and* :ref:`a full git clone<sources_full>` *;
   prefer the latter, if downloading a lot of data does not bother you, as that
   will avoid some* :ref:`peculiar characteristics of shallow clones the
   reference section explains<sources_shallow>` *.]*

   First, execute the following command to retrieve a fresh mainline codebase::

     git clone --no-checkout --depth 1 -b master \
       https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git ~/linux/
     cd ~/linux/

   If you want to access recent mainline releases and pre-releases, deepen you
   clone's history to the oldest mainline version you are interested in::

     git fetch --shallow-exclude=v6.0 origin

   In case you want to access a stable/longterm release (say v6.1.5), simply add
   the branch holding that series; afterwards fetch the history at least up to
   the mainline version that started the series (v6.1)::

     git remote set-branches --add origin linux-6.1.y
     git fetch --shallow-exclude=v6.0 origin

   Now checkout the code you are interested in. If you just performed the
   initial clone, you will be able to check out a fresh mainline codebase, which
   is ideal for checking whether developers already fixed an issue::

      git checkout --detach origin/master

   If you deepened your clone, you instead of ``origin/master`` can specify the
   version you deepened to (``v6.0`` above); later releases like ``v6.1`` and
   pre-release like ``v6.2-rc1`` will work, too. Stable or longterm versions
   like ``v6.1.5`` work just the same, if you added the appropriate
   stable/longterm branch as described.

   [:ref:`details<sources>`]

.. _patching_sbs:

 * In case you want to apply a kernel patch, do so now. Often a command like
   this will do the trick::

     patch -p1 < ../proposed-fix.patch

   If the ``-p1`` is actually needed, depends on how the patch was created; in
   case it does not apply thus try without it.

   If you cloned the sources with git and anything goes sideways, run ``git
   reset --hard`` to undo any changes to the sources.

   [:ref:`details<patching>`]

.. _tagging_sbs:

 * If you patched your kernel or have one of the same version installed already,
   better add a unique tag to the one you are about to build::

     echo "-proposed_fix" > localversion

   Running ``uname -r`` under your kernel later will then print something like
   '6.1-rc4-proposed_fix'.

   [:ref:`details<tagging>`]

 .. _configuration_sbs:

 * Create the build configuration for your kernel based on an existing
   configuration.

   If you already prepared such a '.config' file yourself, copy it to
   ~/linux/ and run ``make olddefconfig``.

   Use the same command, if your distribution or somebody else already tailored
   your running kernel to your or your hardware's needs: the make target
   'olddefconfig' will then try to use that kernel's .config as base.

   Using this make target is fine for everybody else, too -- but you often can
   save a lot of time by using this command instead::

     yes "" | make localmodconfig

   This will try to pick your distribution's kernel as base, but then disable
   modules for any features apparently superfluous for your setup. This will
   reduce the compile time enormously, especially if you are running an
   universal kernel from a commodity Linux distribution.

   There is a catch: 'localmodconfig' is likely to disable kernel features you
   did not use since you booted your Linux -- like drivers for currently
   disconnected peripherals or a virtualization software not haven't used yet.
   You can reduce or nearly eliminate that risk with tricks the reference
   section outlines; but when building a kernel just for quick testing purposes
   it is often negligible if such features are missing. But you should keep that
   aspect in mind when using a kernel built with this make target, as it might
   be the reason why something you only use occasionally stopped working.

   [:ref:`details<configuration>`]

.. _configmods_sbs:

 * Check if you might want to or have to adjust some kernel configuration
   options:

  * Evaluate how you want to handle debug symbols. Enable them, if you later
    might need to decode a stack trace found for example in a 'panic', 'Oops',
    'warning', or 'BUG'; on the other hand disable them, if you are short on
    storage space or prefer a smaller kernel binary. See the reference section
    for details on how to do either. If neither applies, it will likely be fine
    to simply not bother with this. [:ref:`details<configmods_debugsymbols>`]

  * Are you running Debian? Then to avoid known problems by performing
    additional adjustments explained in the reference section.
    [:ref:`details<configmods_distros>`].

  * If you want to influence the other aspects of the configuration, do so now
    by using make targets like 'menuconfig' or 'xconfig'.
    [:ref:`details<configmods_individual>`].

.. _build_sbs:

 * Build the image and the modules of your kernel::

     make -j $(nproc --all)

   If you want your kernel packaged up as deb, rpm, or tar file, see the
   reference section for alternatives.

   [:ref:`details<build>`]

.. _install_sbs:

 * Now install your kernel::

     command -v installkernel && sudo make modules_install install

   Often all left for you to do afterwards is a ``reboot``, as many commodity
   Linux distributions will then create an initramfs (also known as initrd) and
   an entry for your kernel in your bootloader's configuration; but on some
   distributions you have to take care of these two steps manually for reasons
   the reference section explains.

   On a few distributions like Arch Linux and its derivatives the above command
   does nothing at all; in that case you have to manually install your kernel,
   as outlined in the reference section.

   If you are running an immutable Linux distribution, check its documentation
   and the web to find out how to install your own kernel there.

   [:ref:`details<install>`]

.. _another_sbs:

 * To later build another kernel you need similar steps, but sometimes slightly
   different commands.

   First, switch back into the sources tree::

      cd ~/linux/

   In case you want to build a version from a stable/longterm series you have
   not used yet (say 6.2.y), tell git to track it::

      git remote set-branches --add origin linux-6.2.y

   Now fetch the latest upstream changes; you again need to specify the earliest
   version you care about, as git otherwise might retrieve the entire commit
   history::

     git fetch --shallow-exclude=v6.0 origin

   Now switch to the version you are interested in -- but be aware the command
   used here will discard any modifications you performed, as they would
   conflict with the sources you want to checkout::

     git checkout --force --detach origin/master

   At this point you might want to patch the sources again or set/modify a build
   tag, as explained earlier. Afterwards adjust the build configuration to the
   new codebase using olddefconfig, which will now adjust the configuration file
   you prepared earlier using localmodconfig  (~/linux/.config) for your next
   kernel::

     # reminder: if you want to apply patches, do it at this point
     # reminder: you might want to update your build tag at this point
     make olddefconfig

   Now build your kernel::

     make -j $(nproc --all)

   Afterwards install the kernel as outlined above::

     command -v installkernel && sudo make modules_install install

   [:ref:`details<another>`]

.. _uninstall_sbs:

 * Your kernel is easy to remove later, as its parts are only stored in two
   places and clearly identifiable by the kernel's release name. Just ensure to
   not delete the kernel you are running, as that might render your system
   unbootable.

   Start by deleting the directory holding your kernel's modules, which is named
   after its release name -- '6.0.1-foobar' in the following example::

     sudo rm -rf /lib/modules/6.0.1-foobar

   Now try the following command, which on some distributions will delete all
   other kernel files installed while also removing the kernel's entry from the
   bootloader configuration::

     command -v kernel-install && sudo kernel-install -v remove 6.0.1-foobar

   If that command does not output anything or fails, see the reference section;
   do the same if any files named '*6.0.1-foobar*' remain in /boot/.

   [:ref:`details<uninstall>`]

.. _submit_improvements_qbtl:

Did you run into trouble following any of the above steps that is not cleared up
by the reference section below? Or do you have ideas how to improve the text?
Then please take a moment of your time and let the maintainer of this document
know by email (Thorsten Leemhuis <linux@leemhuis.info>), ideally while CCing the
Linux docs mailing list (linux-doc@vger.kernel.org). Such feedback is vital to
improve this document further, which is in everybody's interest, as it will
enable more people to master the task described here.

Reference section for the step-by-step guide
============================================

This section holds additional information for each of the steps in the above
guide.

.. _backup:

Prepare for emergencies
-----------------------

   *Create a fresh backup and put system repair and restore tools at hand*
   [:ref:`... <backup_sbs>`]

Remember, you are dealing with computers, which sometimes do unexpected things
-- especially if you fiddle with crucial parts like the kernel of an operating
system. That's what you are about to do in this process. Hence, better prepare
for something going sideways, even if that should not happen.

[:ref:`back to step-by-step guide <backup_sbs>`]

.. _secureboot:

Dealing with techniques like Secure Boot
----------------------------------------

   *On platforms with 'Secure Boot' or similar techniques, prepare everything to
   ensure the system will permit your self-compiled kernel to boot later.*
   [:ref:`... <secureboot_sbs>`]

Many modern systems allow only certain operating systems to start; they thus by
default will reject booting self-compiled kernels.

You ideally deal with this by making your platform trust your self-built kernels
with the help of a certificate and signing. How to do that is not described
here, as it requires various steps that would take the text too far away from
its purpose; 'Documentation/admin-guide/module-signing.rst' and various web
sides already explain this in more detail.

Temporarily disabling solutions like Secure Boot is another way to make your own
Linux boot. On commodity x86 systems it is possible to do this in the BIOS Setup
utility; the steps to do so are not described here, as they greatly vary between
machines.

On mainstream x86 Linux distributions there is a third and universal option:
disable all Secure Boot restrictions for your Linux environment. You can
initiate this process by running ``mokutil --disable-validation``; this will
tell you to create a one-time password, which is safe to write down. Now
restart; right after your BIOS performed all self-tests the bootloader Shim will
show a blue box with a message 'Press any key to perform MOK management'. Hit
some key before the countdown exposes. This will open a menu and choose 'Change
Secure Boot state' there. Shim's 'MokManager' will now ask you to enter three
randomly chosen characters from the one-time password specified earlier. Once
you provided them, confirm that you really want to disable the validation.
Afterwards, permit MokManager to reboot the machine.

[:ref:`back to step-by-step guide <secureboot_sbs>`]

.. _buildrequires:

Install build requirements
--------------------------

   *Install all software required to build a Linux kernel.*
   [:ref:`...<buildrequires_sbs>`]

The kernel is pretty stand-alone, but besides tools like the compiler you will
sometimes need a few libraries to build one. How to install everything needed
depends on your Linux distribution and the configuration of the kernel you are
about to build.

Here are a few examples what you typically need on some mainstream
distributions:

 * Debian, Ubuntu, and derivatives::

     sudo apt install bc binutils bison dwarves flex gcc git make openssl \
       pahole perl-base libssl-dev libelf-dev

 * Fedora and derivatives::

     sudo dnf install binutils /usr/include/{libelf.h,openssl/pkcs7.h} \
       /usr/bin/{bc,bison,flex,gcc,git,openssl,make,perl,pahole}

 * openSUSE and derivatives::

     sudo zypper install bc binutils bison dwarves flex gcc git make perl-base \
       openssl openssl-devel libelf-dev

In case you wonder why these lists include openssl and its development headers:
they are needed for the Secure Boot support, which many distributions enable in
their kernel configuration for x86 machines.

Sometimes you will need tools for compression formats like bzip2, gzip, lz4,
lzma, lzo, xz, or zstd as well.

You might need additional libraries and their development headers in case you
perform tasks not covered in this guide. For example, zlib will be needed when
building kernel tools from the tools/ directory; adjusting the build
configuration with make targets like 'menuconfig' or 'xconfig' will require
development headers for ncurses or Qt5.

[:ref:`back to step-by-step guide <buildrequires_sbs>`]

.. _diskspace:

Space requirements
------------------

   *Ensure to have enough free space for building and installing Linux.*
   [:ref:`... <diskspace_sbs>`]

The numbers mentioned are rough estimates with a big extra charge to be on the
safe side, so often you will need less.

If you have space constraints, remember to read the reference section when you
reach the :ref:`section about configuration adjustments' <configmods>`, as
ensuring debug symbols are disabled will reduce the consumed disk space by quite
a few gigabytes.

[:ref:`back to step-by-step guide <diskspace_sbs>`]


.. _sources:

Download the sources
--------------------

  *Retrieve the sources of the Linux version you intend to build.*
  [:ref:`...<sources_sbs>`]

The step-by-step guide outlines how to retrieve Linux' sources using a shallow
git clone. There is :ref:`more to tell about this method<sources_shallow>` and
two alternate ways worth describing: :ref:`packaged archives<sources_archive>`
and :ref:`a full git clone<sources_full>`. And the aspects ':ref:`wouldn't it
be wiser to use a proper pre-release than the latest mainline code
<sources_snapshot>`' and ':ref:`how to get an even fresher mainline codebase
<sources_fresher>`' need elaboration, too.

Note, to keep things simple the commands used in this guide store the build
artifacts in the source tree. If you prefer to separate them, simply add
something like ``O=~/linux-builddir/`` to all make calls; also adjust the path
in all commands that add files or modify any generated (like your '.config').

[:ref:`back to step-by-step guide <sources_sbs>`]

.. _sources_shallow:

Noteworthy characteristics of shallow clones
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The step-by-step guide uses a shallow clone, as it is the best solution for most
of this document's target audience. There are a few aspects of this approach
worth mentioning:

 * This document in most places uses ``git fetch`` with ``--shallow-exclude=``
   to specify the earliest version you care about (or to be precise: its git
   tag). You alternatively can use the parameter ``--shallow-since=`` to specify
   an absolute (say ``'2023-07-15'``) or relative (``'12 months'``) date to
   define the depth of the history you want to download. As a second
   alternative, you can also specify a certain depth explicitly with a parameter
   like ``--depth=1``, unless you add branches for stable/longterm kernels.

 * When running ``git fetch``, remember to always specify the oldest version,
   the time you care about, or an explicit depth as shown in the step-by-step
   guide. Otherwise you will risk downloading nearly the entire git history,
   which will consume quite a bit of time and bandwidth while also stressing the
   servers.

   Note, you do not have to use the same version or date all the time. But when
   you change it over time, git will deepen or flatten the history to the
   specified point. That allows you to retrieve versions you initially thought
   you did not need -- or it will discard the sources of older versions, for
   example in case you want to free up some disk space. The latter will happen
   automatically when using ``--shallow-since=`` or
   ``--depth=``.

 * Be warned, when deepening your clone you might encounter an error like
   'fatal: error in object: unshallow cafecaca0c0dacafecaca0c0dacafecaca0c0da'.
   In that case run ``git repack -d`` and try again``

 * In case you want to revert changes from a certain version (say Linux 6.3) or
   perform a bisection (v6.2..v6.3), better tell ``git fetch`` to retrieve
   objects up to three versions earlier (e.g. 6.0): ``git describe`` will then
   be able to describe most commits just like it would in a full git clone.

[:ref:`back to step-by-step guide <sources_sbs>`] [:ref:`back to section intro <sources>`]

.. _sources_archive:

Downloading the sources using a packages archive
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

People new to compiling Linux often assume downloading an archive via the
front-page of https://kernel.org is the best approach to retrieve Linux'
sources. It actually can be, if you are certain to build just one particular
kernel version without changing any code. Thing is: you might be sure this will
be the case, but in practice it often will turn out to be a wrong assumption.

That's because when reporting or debugging an issue developers will often ask to
give another version a try. They also might suggest temporarily undoing a commit
with ``git revert`` or might provide various patches to try. Sometimes reporters
will also be asked to use ``git bisect`` to find the change causing a problem.
These things rely on git or are a lot easier and quicker to handle with it.

A shallow clone also does not add any significant overhead. For example, when
you use ``git clone --depth=1`` to create a shallow clone of the latest mainline
codebase git will only retrieve a little more data than downloading the latest
mainline pre-release (aka 'rc') via the front-page of kernel.org would.

A shallow clone therefore is often the better choice. If you nevertheless want
to use a packaged source archive, download one via kernel.org; afterwards
extract its content to some directory and change to the subdirectory created
during extraction. The rest of the step-by-step guide will work just fine, apart
from things that rely on git -- but this mainly concerns the section on
successive builds of other versions.

[:ref:`back to step-by-step guide <sources_sbs>`] [:ref:`back to section intro <sources>`]

.. _sources_full:

Downloading the sources using a full git clone
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

If downloading and storing a lot of data (~4,4 Gigabyte as of early 2023) is
nothing that bothers you, instead of a shallow clone perform a full git clone
instead. You then will avoid the specialties mentioned above and will have all
versions and individual commits at hand at any time::

    curl -L \
      https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/clone.bundle \
      -o linux-stable.git.bundle
    git clone linux-stable.git.bundle ~/linux/
    rm linux-stable.git.bundle
    cd ~/linux/
    git remote set-url origin \
      https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git
    git fetch origin
    git checkout --detach origin/master

[:ref:`back to step-by-step guide <sources_sbs>`] [:ref:`back to section intro <sources>`]

.. _sources_snapshot:

Proper pre-releases (RCs) vs. latest mainline
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

When cloning the sources using git and checking out origin/master, you often
will retrieve a codebase that is somewhere between the latest and the next
release or pre-release. This almost always is the code you want when giving
mainline a shot: pre-releases like v6.1-rc5 are in no way special, as they do
not get any significant extra testing before being published.

There is one exception: you might want to stick to the latest mainline release
(say v6.1) before its successor's first pre-release (v6.2-rc1) is out. That is
because compiler errors and other problems are more likely to occur during this
time, as mainline then is in its 'merge window': a usually two week long phase,
in which the bulk of the changes for the next release is merged.

[:ref:`back to step-by-step guide <sources_sbs>`] [:ref:`back to section intro <sources>`]

.. _sources_fresher:

Avoiding the mainline lag
~~~~~~~~~~~~~~~~~~~~~~~~~

The explanations for both the shallow clone and the full clone both retrieve the
code from the Linux stable git repository. That makes things simpler for this
document's audience, as it allows easy access to both mainline and
stable/longterm releases. This approach has just one downside:

Changes merged into the mainline repository are only synced to the master branch
of the Linux stable repository  every few hours. This lag most of the time is
not something to worry about; but in case you really need the latest code, just
add the mainline repo as additional remote and checkout the code from there::

    git remote add mainline \
      https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
    git fetch mainline
    git checkout --detach mainline/master

When doing this with a shallow clone, remember to call ``git fetch`` with one
of the parameters described earlier to limit the depth.

[:ref:`back to step-by-step guide <sources_sbs>`] [:ref:`back to section intro <sources>`]

.. _patching:

Patch the sources (optional)
----------------------------

  *In case you want to apply a kernel patch, do so now.*
  [:ref:`...<patching_sbs>`]

This is the point where you might want to patch your kernel -- for example when
a developer proposed a fix and asked you to check if it helps. The step-by-step
guide already explains everything crucial here.

[:ref:`back to step-by-step guide <patching_sbs>`]

.. _tagging:

Tagging this kernel build (optional, often wise)
------------------------------------------------

  *If you patched your kernel or already have that kernel version installed,
  better tag your kernel by extending its release name:*
  [:ref:`...<tagging_sbs>`]

Tagging your kernel will help avoid confusion later, especially when you patched
your kernel. Adding an individual tag will also ensure the kernel's image and
its modules are installed in parallel to any existing kernels.

There are various ways to add such a tag. The step-by-step guide realizes one by
creating a 'localversion' file in your build directory from which the kernel
build scripts will automatically pick up the tag. You can later change that file
to use a different tag in subsequent builds or simply remove that file to dump
the tag.

[:ref:`back to step-by-step guide <tagging_sbs>`]

.. _configuration:

Define the build configuration for your kernel
----------------------------------------------

  *Create the build configuration for your kernel based on an existing
  configuration.* [:ref:`... <configuration_sbs>`]

There are various aspects for this steps that require a more careful
explanation:

Pitfalls when using another configuration file as base
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Make targets like localmodconfig and olddefconfig share a few common snares you
want to be aware of:

 * These targets will reuse a kernel build configuration in your build directory
   (e.g. '~/linux/.config'), if one exists. In case you want to start from
   scratch you thus need to delete it.

 * The make targets try to find the configuration for your running kernel
   automatically, but might choose poorly. A line like '# using defaults found
   in /boot/config-6.0.7-250.fc36.x86_64' or 'using config:
   '/boot/config-6.0.7-250.fc36.x86_64' tells you which file they picked. If
   that is not the intended one, simply store it as '~/linux/.config'
   before using these make targets.

 * Unexpected things might happen if you try to use a config file prepared for
   one kernel (say v6.0) on an older generation (say v5.15). In that case you
   might want to use a configuration as base which your distribution utilized
   when they used that or an slightly older kernel version.

Influencing the configuration
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The make target olddefconfig and the ``yes "" |`` used when utilizing
localmodconfig will set any undefined build options to their default value. This
among others will disable many kernel features that were introduced after your
base kernel was released.

If you want to set these configurations options manually, use ``oldconfig``
instead of ``olddefconfig`` or omit the ``yes "" |`` when utilizing
localmodconfig. Then for each undefined configuration option you will be asked
how to proceed. In case you are unsure what to answer, simply hit 'enter' to
apply the default value.

Big pitfall when using localmodconfig
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

As explained briefly in the step-by-step guide already: with localmodconfig it
can easily happen that your self-built kernel will lack modules for tasks you
did not perform before utilizing this make target. That's because those tasks
require kernel modules that are normally autoloaded when you perform that task
for the first time; if you didn't perform that task at least once before using
localmodconfig, the latter will thus assume these modules are superfluous and
disable them.

You can try to avoid this by performing typical tasks that often will autoload
additional kernel modules: start a VM, establish VPN connections, loop-mount a
CD/DVD ISO, mount network shares (CIFS, NFS, ...), and connect all external
devices (2FA keys, headsets, webcams, ...) as well as storage devices with file
systems you otherwise do not utilize (btrfs, ext4, FAT, NTFS, XFS, ...). But it
is hard to think of everything that might be needed -- even kernel developers
often forget one thing or another at this point.

Do not let that risk bother you, especially when compiling a kernel only for
testing purposes: everything typically crucial will be there. And if you forget
something important you can turn on a missing feature later and quickly run the
commands to compile and install a better kernel.

But if you plan to build and use self-built kernels regularly, you might want to
reduce the risk by recording which modules your system loads over the course of
a few weeks. You can automate this with `modprobed-db
<https://github.com/graysky2/modprobed-db>`_. Afterwards use ``LSMOD=<path>`` to
point localmodconfig to the list of modules modprobed-db noticed being used::

    yes "" | make LSMOD="${HOME}"/.config/modprobed.db localmodconfig

Remote building with localmodconfig
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

If you want to use localmodconfig to build a kernel for another machine, run
``lsmod > lsmod_foo-machine`` on it and transfer that file to your build host.
Now point the build scripts to the file like this: ``yes "" | make
LSMOD=~/lsmod_foo-machine localmodconfig``. Note, in this case
you likely want to copy a base kernel configuration from the other machine over
as well and place it as .config in your build directory.

[:ref:`back to step-by-step guide <configuration_sbs>`]

.. _configmods:

Adjust build configuration
--------------------------

   *Check if you might want to or have to adjust some kernel configuration
   options:*

Depending on your needs you at this point might want or have to adjust some
kernel configuration options.

.. _configmods_debugsymbols:

Debug symbols
~~~~~~~~~~~~~

   *Evaluate how you want to handle debug symbols.*
   [:ref:`...<configmods_sbs>`]

Most users do not need to care about this, it's often fine to leave everything
as it is; but you should take a closer look at this, if you might need to decode
a stack trace or want to reduce space consumption.

Having debug symbols available can be important when your kernel throws a
'panic', 'Oops', 'warning', or 'BUG' later when running, as then you will be
able to find the exact place where the problem occurred in the code. But
collecting and embedding the needed debug information takes time and consumes
quite a bit of space: in late 2022 the build artifacts for a typical x86 kernel
configured with localmodconfig consumed around 5 Gigabyte of space with debug
symbols, but less than 1 when they were disabled. The resulting kernel image and
the modules are bigger as well, which increases load times.

Hence, if you want a small kernel and are unlikely to decode a stack trace
later, you might want to disable debug symbols to avoid above downsides::

    ./scripts/config --file .config -d DEBUG_INFO \
      -d DEBUG_INFO_DWARF_TOOLCHAIN_DEFAULT -d DEBUG_INFO_DWARF4 \
      -d DEBUG_INFO_DWARF5 -e CONFIG_DEBUG_INFO_NONE
    make olddefconfig

You on the other hand definitely want to enable them, if there is a decent
chance that you need to decode a stack trace later (as explained by 'Decode
failure messages' in Documentation/admin-guide/tainted-kernels.rst in more
detail)::

    ./scripts/config --file .config -d DEBUG_INFO_NONE -e DEBUG_KERNEL
      -e DEBUG_INFO -e DEBUG_INFO_DWARF_TOOLCHAIN_DEFAULT -e KALLSYMS -e KALLSYMS_ALL
    make olddefconfig

Note, many mainstream distributions enable debug symbols in their kernel
configurations -- make targets like localmodconfig and olddefconfig thus will
often pick that setting up.

[:ref:`back to step-by-step guide <configmods_sbs>`]

.. _configmods_distros:

Distro specific adjustments
~~~~~~~~~~~~~~~~~~~~~~~~~~~

   *Are you running* [:ref:`... <configmods_sbs>`]

The following sections help you to avoid build problems that are known to occur
when following this guide on a few commodity distributions.

**Debian:**

 * Remove a stale reference to a certificate file that would cause your build to
   fail::

    ./scripts/config --file .config --set-str SYSTEM_TRUSTED_KEYS ''

   Alternatively, download the needed certificate and make that configuration
   option point to it, as `the Debian handbook explains in more detail
   <https://debian-handbook.info/browse/stable/sect.kernel-compilation.html>`_
   -- or generate your own, as explained in
   Documentation/admin-guide/module-signing.rst.

[:ref:`back to step-by-step guide <configmods_sbs>`]

.. _configmods_individual:

Individual adjustments
~~~~~~~~~~~~~~~~~~~~~~

   *If you want to influence the other aspects of the configuration, do so
   now* [:ref:`... <configmods_sbs>`]

You at this point can use a command like ``make menuconfig`` to enable or
disable certain features using a text-based user interface; to use a graphical
configuration utilize, use the make target ``xconfig`` or ``gconfig`` instead.
All of them require development libraries from toolkits they are based on
(ncurses, Qt5, Gtk2); an error message will tell you if something required is
missing.

[:ref:`back to step-by-step guide <configmods_sbs>`]

.. _build:

Build your kernel
-----------------

  *Build the image and the modules of your kernel* [:ref:`... <build_sbs>`]

A lot can go wrong at this stage, but the instructions below will help you help
yourself. Another subsection explains how to directly package your kernel up as
deb, rpm or tar file.

Dealing with build errors
~~~~~~~~~~~~~~~~~~~~~~~~~

When a build error occurs, it might be caused by some aspect of your machine's
setup that often can be fixed quickly; other times though the problem lies in
the code and can only be fixed by a developer. A close examination of the
failure messages coupled with some research on the internet will often tell you
which of the two it is. To perform such an investigation, restart the build
process like this::

    make V=1

The ``V=1`` activates verbose output, which might be needed to see the actual
error. To make it easier to spot, this command also omits the ``-j $(nproc
--all)`` used earlier to utilize every CPU core in the system for the job -- but
this parallelism also results in some clutter when failures occur.

After a few seconds the build process should run into the error again. Now try
to find the most crucial line describing the problem. Then search the internet
for the most important and non-generic section of that line (say 4 to 8 words);
avoid or remove anything that looks remotely system-specific, like your username
or local path names like ``/home/username/linux/``. First try your regular
internet search engine with that string, afterwards search Linux kernel mailing
lists via `lore.kernel.org/all/ <https://lore.kernel.org/all/>`_.

This most of the time will find something that will explain what is wrong; quite
often one of the hits will provide a solution for your problem, too. If you
do not find anything that matches your problem, try again from a different angle
by modifying your search terms or using another line from the error messages.

In the end, most trouble you are to run into has likely been encountered and
reported by others already. That includes issues where the cause is not your
system, but lies the code. If you run into one of those, you might thus find a
solution (e.g. a patch) or workaround for your problem, too.

Package your kernel up
~~~~~~~~~~~~~~~~~~~~~~

The step-by-step guide uses the default make targets (e.g. 'bzImage' and
'modules' on x86) to build the image and the modules of your kernel, which later
steps of the guide then install. You instead can also directly build everything
and directly package it up by using one of the following targets:

 * ``make -j $(nproc --all) bindeb-pkg`` to generate a deb package

 * ``make -j $(nproc --all) binrpm-pkg`` to generate a rpm package

 * ``make -j $(nproc --all) tarbz2-pkg`` to generate a bz2 compressed tarball

This is just a selection of available make targets for this purpose, see
``make help`` for others. You can also use these targets after running
``make -j $(nproc --all)``, as they will pick up everything already built.

If you employ the targets to generate deb or rpm packages, ignore the
step-by-step guide's instructions on installing and removing your kernel;
instead install and remove the packages using the package utility for the format
(e.g. dpkg and rpm) or a package management utility build on top of them (apt,
aptitude, dnf/yum, zypper, ...). Be aware that the packages generated using
these two make targets are designed to work on various distributions utilizing
those formats, they thus will sometimes behave differently than your
distribution's kernel packages.

[:ref:`back to step-by-step guide <build_sbs>`]

.. _install:

Install your kernel
-------------------

  *Now install your kernel* [:ref:`... <install_sbs>`]

What you need to do after executing the command in the step-by-step guide
depends on the existence and the implementation of an ``installkernel``
executable. Many commodity Linux distributions ship such a kernel installer in
``/sbin/`` that does everything needed, hence there is nothing left for you
except rebooting. But some distributions contain an installkernel that does
only part of the job -- and a few lack it completely and leave all the work to
you.

If ``installkernel`` is found, the kernel's build system will delegate the
actual installation of your kernel's image and related files to this executable.
On almost all Linux distributions it will store the image as '/boot/vmlinuz-
<your kernel's release name>' and put a 'System.map-<your kernel's release
name>' alongside it. Your kernel will thus be installed in parallel to any
existing ones, unless you already have one with exactly the same release name.

Installkernel on many distributions will afterwards generate an 'initramfs'
(often also called 'initrd'), which commodity distributions rely on for booting;
hence be sure to keep the order of the two make targets used in the step-by-step
guide, as things will go sideways if you install your kernel's image before its
modules. Often installkernel will then add your kernel to the bootloader
configuration, too. You have to take care of one or both of these tasks
yourself, if your distributions installkernel doesn't handle them.

A few distributions like Arch Linux and its derivatives totally lack an
installkernel executable. On those just install the modules using the kernel's
build system and then install the image and the System.map file manually::

     sudo make modules_install
     sudo install -m 0600 $(make -s image_name) /boot/vmlinuz-$(make -s kernelrelease)
     sudo install -m 0600 System.map /boot/System.map-$(make -s kernelrelease)

If your distribution boots with the help of an initramfs, now generate one for
your kernel using the tools your distribution provides for this process.
Afterwards add your kernel to your bootloader configuration and reboot.

[:ref:`back to step-by-step guide <install_sbs>`]

.. _another:

Another round later
-------------------

  *To later build another kernel you need similar, but sometimes slightly
  different commands* [:ref:`... <another_sbs>`]

The process to build later kernels is similar, but at some points slightly
different. You for example do not want to use 'localmodconfig' for succeeding
kernel builds, as you already created a trimmed down configuration you want to
use from now on. Hence instead just use ``oldconfig`` or ``olddefconfig`` to
adjust your build configurations to the needs of the kernel version you are
about to build.

If you created a shallow-clone with git, remember what the :ref:`section that
explained the setup described in more detail <sources>`: you need to use a
slightly different ``git fetch`` command and when switching to another series
need to add an additional remote branch.

[:ref:`back to step-by-step guide <another_sbs>`]

.. _uninstall:

Uninstall the kernel later
--------------------------

  *All parts of your installed kernel are identifiable by its release name and
  thus easy to remove later.* [:ref:`... <uninstall_sbs>`]

Do not worry installing your kernel manually and thus bypassing your
distribution's packaging system will totally mess up your machine: all parts of
your kernel are easy to remove later, as files are stored in two places only and
normally identifiable by the kernel's release name.

One of the two places is a directory in /lib/modules/, which holds the modules
for each installed kernel. This directory is named after the kernel's release
name; hence, to remove all modules for one of your kernels, simply remove its
modules directory in /lib/modules/.

The other place is /boot/, where typically one to five files will be placed
during installation of a kernel. All of them usually contain the release name in
their file name, but how many files and their name depends somewhat on your
distribution's installkernel executable (:ref:`see above <install>`) and its
initramfs generator. On some distributions the ``kernel-install`` command
mentioned in the step-by-step guide will remove all of these files for you --
and the entry for your kernel in the bootloader configuration at the same time,
too. On others you have to take care of these steps yourself. The following
command should interactively remove the two main files of a kernel with the
release name '6.0.1-foobar'::

    rm -i /boot/{System.map,vmlinuz}-6.0.1-foobar

Now remove the belonging initramfs, which often will be called something like
``/boot/initramfs-6.0.1-foobar.img`` or ``/boot/initrd.img-6.0.1-foobar``.
Afterwards check for other files in /boot/ that have '6.0.1-foobar' in their
name and delete them as well. Now remove the kernel from your bootloader's
configuration.

Note, be very careful with wildcards like '*' when deleting files or directories
for kernels manually: you might accidentally remove files of a 6.0.11 kernel
when all you want is to remove 6.0 or 6.0.1.

[:ref:`back to step-by-step guide <uninstall_sbs>`]

.. _faq:

FAQ
===

Why does this 'how-to' not work on my system?
---------------------------------------------

As initially stated, this guide is 'designed to cover everything typically
needed [to build a kernel] on mainstream Linux distributions running on
commodity PC or server hardware'. The outlined approach despite this should work
on many other setups as well. But trying to cover every possible use-case in one
guide would defeat its purpose, as without such a focus you would need dozens or
hundreds of constructs along the lines of 'in case you are having <insert
machine or distro>, you at this point have to do <this and that>
<instead|additionally>'. Each of which would make the text longer, more
complicated, and harder to follow.

That being said: this of course is a balancing act. Hence, if you think an
additional use-case is worth describing, suggest it to the maintainers of this
document, as :ref:`described above <submit_improvements_qbtl>`.


..
   end-of-content
..
   This document is maintained by Thorsten Leemhuis <linux@leemhuis.info>. If
   you spot a typo or small mistake, feel free to let him know directly and
   he'll fix it. You are free to do the same in a mostly informal way if you
   want to contribute changes to the text -- but for copyright reasons please CC
   linux-doc@vger.kernel.org and 'sign-off' your contribution as
   Documentation/process/submitting-patches.rst explains in the section 'Sign
   your work - the Developer's Certificate of Origin'.
..
   This text is available under GPL-2.0+ or CC-BY-4.0, as stated at the top
   of the file. If you want to distribute this text under CC-BY-4.0 only,
   please use 'The Linux kernel development community' for author attribution
   and link this as source:
   https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/plain/Documentation/admin-guide/quickly-build-trimmed-linux.rst
..
   Note: Only the content of this RST file as found in the Linux kernel sources
   is available under CC-BY-4.0, as versions of this text that were processed
   (for example by the kernel's build system) might contain content taken from
   files which use a more restrictive license.

---

### Documentation Admin Guide Ramoops (`Documentation/admin-guide/ramoops.rst`)

Ramoops oops/panic logger
=========================

Sergiu Iordache <sergiu@chromium.org>

Updated: 10 Feb 2021

Introduction
------------

Ramoops is an oops/panic logger that writes its logs to RAM before the system
crashes. It works by logging oopses and panics in a circular buffer. Ramoops
needs a system with persistent RAM so that the content of that area can
survive after a restart.

Ramoops concepts
----------------

Ramoops uses a predefined memory area to store the dump. The start and size
and type of the memory area are set using three variables:

  * ``mem_address`` for the start
  * ``mem_size`` for the size. The memory size will be rounded down to a
    power of two.
  * ``mem_type`` to specify if the memory type (default is pgprot_writecombine).
  * ``mem_name`` to specify a memory region defined by ``reserve_mem`` command
    line parameter.

Typically the default value of ``mem_type=0`` should be used as that sets the pstore
mapping to pgprot_writecombine. Setting ``mem_type=1`` attempts to use
``pgprot_noncached``, which only works on some platforms. This is because pstore
depends on atomic operations. At least on ARM, pgprot_noncached causes the
memory to be mapped strongly ordered, and atomic operations on strongly ordered
memory are implementation defined, and won't work on many ARMs such as omaps.
Setting ``mem_type=2`` attempts to treat the memory region as normal memory,
which enables full cache on it. This can improve the performance.

The memory area is divided into ``record_size`` chunks (also rounded down to
power of two) and each kmesg dump writes a ``record_size`` chunk of
information.

Limiting which kinds of kmsg dumps are stored can be controlled via
the ``max_reason`` value, as defined in include/linux/kmsg_dump.h's
``enum kmsg_dump_reason``. For example, to store both Oopses and Panics,
``max_reason`` should be set to 2 (KMSG_DUMP_OOPS), to store only Panics
``max_reason`` should be set to 1 (KMSG_DUMP_PANIC). Setting this to 0
(KMSG_DUMP_UNDEF), means the reason filtering will be controlled by the
``printk.always_kmsg_dump`` boot param: if unset, it'll be KMSG_DUMP_OOPS,
otherwise KMSG_DUMP_MAX.

The module uses a counter to record multiple dumps but the counter gets reset
on restart (i.e. new dumps after the restart will overwrite old ones).

Ramoops also supports software ECC protection of persistent memory regions.
This might be useful when a hardware reset was used to bring the machine back
to life (i.e. a watchdog triggered). In such cases, RAM may be somewhat
corrupt, but usually it is restorable.

Setting the parameters
----------------------

Setting the ramoops parameters can be done in several different manners:

 A. Use the module parameters (which have the names of the variables described
 as before). For quick debugging, you can also reserve parts of memory during
 boot and then use the reserved memory for ramoops. For example, assuming a
 machine with > 128 MB of memory, the following kernel command line will tell
 the kernel to use only the first 128 MB of memory, and place ECC-protected
 ramoops region at 128 MB boundary::

	mem=128M ramoops.mem_address=0x8000000 ramoops.ecc=1

 B. Use Device Tree bindings, as described in
 ``Documentation/devicetree/bindings/reserved-memory/ramoops.yaml``.
 For example::

	reserved-memory {
		#address-cells = <2>;
		#size-cells = <2>;
		ranges;

		ramoops@8f000000 {
			compatible = "ramoops";
			reg = <0 0x8f000000 0 0x100000>;
			record-size = <0x4000>;
			console-size = <0x4000>;
		};
	};

 C. Use a platform device and set the platform data. The parameters can then
 be set through that platform data. An example of doing that is:

 .. code-block:: c

  #include <linux/pstore_ram.h>
  [...]

  static struct ramoops_platform_data ramoops_data = {
        .mem_size               = <...>,
        .mem_address            = <...>,
        .mem_type               = <...>,
        .record_size            = <...>,
        .max_reason             = <...>,
        .ecc                    = <...>,
  };

  static struct platform_device ramoops_dev = {
        .name = "ramoops",
        .dev = {
                .platform_data = &ramoops_data,
        },
  };

  [... inside a function ...]
  int ret;

  ret = platform_device_register(&ramoops_dev);
  if (ret) {
	printk(KERN_ERR "unable to register platform device\n");
	return ret;
  }

 D. Using a region of memory reserved via ``reserve_mem`` command line
    parameter. The address and size will be defined by the ``reserve_mem``
    parameter. Note, that ``reserve_mem`` may not always allocate memory
    in the same location, and cannot be relied upon. Testing will need
    to be done, and it may not work on every machine, nor every kernel.
    Consider this a "best effort" approach. The ``reserve_mem`` option
    takes a size, alignment and name as arguments. The name is used
    to map the memory to a label that can be retrieved by ramoops.

	reserve_mem=2M:4096:oops  ramoops.mem_name=oops

You can specify either RAM memory or peripheral devices' memory. However, when
specifying RAM, be sure to reserve the memory by issuing memblock_reserve()
very early in the architecture code, e.g.::

	#include <linux/memblock.h>

	memblock_reserve(ramoops_data.mem_address, ramoops_data.mem_size);

Dump format
-----------

The data dump begins with a header, currently defined as ``====`` followed by a
timestamp and a new line. The dump then continues with the actual data.

Reading the data
----------------

The dump data can be read from the pstore filesystem. The format for these
files is ``dmesg-ramoops-N``, where N is the record number in memory. To delete
a stored record from RAM, simply unlink the respective pstore file.

Persistent function tracing
---------------------------

Persistent function tracing might be useful for debugging software or hardware
related hangs. The functions call chain log is stored in a ``ftrace-ramoops``
file. Here is an example of usage::

 # mount -t debugfs debugfs /sys/kernel/debug/
 # echo 1 > /sys/kernel/debug/pstore/record_ftrace
 # reboot -f
 [...]
 # mount -t pstore pstore /mnt/
 # tail /mnt/ftrace-ramoops
 0 ffffffff8101ea64  ffffffff8101bcda  native_apic_mem_read <- disconnect_bsp_APIC+0x6a/0xc0
 0 ffffffff8101ea44  ffffffff8101bcf6  native_apic_mem_write <- disconnect_bsp_APIC+0x86/0xc0
 0 ffffffff81020084  ffffffff8101a4b5  hpet_disable <- native_machine_shutdown+0x75/0x90
 0 ffffffff81005f94  ffffffff8101a4bb  iommu_shutdown_noop <- native_machine_shutdown+0x7b/0x90
 0 ffffffff8101a6a1  ffffffff8101a437  native_machine_emergency_restart <- native_machine_restart+0x37/0x40
 0 ffffffff811f9876  ffffffff8101a73a  acpi_reboot <- native_machine_emergency_restart+0xaa/0x1e0
 0 ffffffff8101a514  ffffffff8101a772  mach_reboot_fixups <- native_machine_emergency_restart+0xe2/0x1e0
 0 ffffffff811d9c54  ffffffff8101a7a0  __const_udelay <- native_machine_emergency_restart+0x110/0x1e0
 0 ffffffff811d9c34  ffffffff811d9c80  __delay <- __const_udelay+0x30/0x40
 0 ffffffff811d9d14  ffffffff811d9c3f  delay_tsc <- __delay+0xf/0x20

---

### Documentation Admin Guide Rapidio (`Documentation/admin-guide/rapidio.rst`)

=======================
RapidIO Subsystem Guide
=======================

:Author: Matt Porter

Introduction
============

RapidIO is a high speed switched fabric interconnect with features aimed
at the embedded market. RapidIO provides support for memory-mapped I/O
as well as message-based transactions over the switched fabric network.
RapidIO has a standardized discovery mechanism not unlike the PCI bus
standard that allows simple detection of devices in a network.

This documentation is provided for developers intending to support
RapidIO on new architectures, write new drivers, or to understand the
subsystem internals.

Known Bugs and Limitations
==========================

Bugs
----

None. ;)

Limitations
-----------

1. Access/management of RapidIO memory regions is not supported

2. Multiple host enumeration is not supported

RapidIO driver interface
========================

Drivers are provided a set of calls in order to interface with the
subsystem to gather info on devices, request/map memory region
resources, and manage mailboxes/doorbells.

Functions
---------

.. kernel-doc:: include/linux/rio_drv.h
   :internal:

.. kernel-doc:: drivers/rapidio/rio-driver.c
   :export:

.. kernel-doc:: drivers/rapidio/rio.c
   :export:

Internals
=========

This chapter contains the autogenerated documentation of the RapidIO
subsystem.

Structures
----------

.. kernel-doc:: include/linux/rio.h
   :internal:

Enumeration and Discovery
-------------------------

.. kernel-doc:: drivers/rapidio/rio-scan.c
   :internal:

Driver functionality
--------------------

.. kernel-doc:: drivers/rapidio/rio.c
   :internal:

.. kernel-doc:: drivers/rapidio/rio-access.c
   :internal:

Device model support
--------------------

.. kernel-doc:: drivers/rapidio/rio-driver.c
   :internal:

PPC32 support
-------------

.. kernel-doc:: arch/powerpc/sysdev/fsl_rio.c
   :internal:

Credits
=======

The following people have contributed to the RapidIO subsystem directly
or indirectly:

1. Matt Porter\ mporter@kernel.crashing.org

2. Randy Vinson\ rvinson@mvista.com

3. Dan Malek\ dan@embeddedalley.com

The following people have contributed to this document:

1. Matt Porter\ mporter@kernel.crashing.org

---

### Documentation Admin Guide Reporting Issues (`Documentation/admin-guide/reporting-issues.rst`)

.. SPDX-License-Identifier: (GPL-2.0+ OR CC-BY-4.0)
.. See the bottom of this file for additional redistribution information.

Reporting issues
++++++++++++++++


The short guide (aka TL;DR)
===========================

Are you facing a regression with vanilla kernels from the same stable or
longterm series? One still supported? Then search the `LKML
<https://lore.kernel.org/lkml/>`_ and the `Linux stable mailing list
<https://lore.kernel.org/stable/>`_ archives for matching reports to join. If
you don't find any, install `the latest release from that series
<https://kernel.org/>`_. If it still shows the issue, report it to the stable
mailing list (stable@vger.kernel.org) and CC the regressions list
(regressions@lists.linux.dev); ideally also CC the maintainer and the mailing
list for the subsystem in question.

In all other cases try your best guess which kernel part might be causing the
issue. Check the :ref:`MAINTAINERS <maintainers>` file for how its developers
expect to be told about problems, which most of the time will be by email with a
mailing list in CC. Check the destination's archives for matching reports;
search the `LKML <https://lore.kernel.org/lkml/>`_ and the web, too. If you
don't find any to join, install `the latest mainline kernel
<https://kernel.org/>`_. If the issue is present there, send a report.

The issue was fixed there, but you would like to see it resolved in a still
supported stable or longterm series as well? Then install its latest release.
If it shows the problem, search for the change that fixed it in mainline and
check if backporting is in the works or was discarded; if it's neither, ask
those who handled the change for it.

**General remarks**: When installing and testing a kernel as outlined above,
ensure it's vanilla (IOW: not patched and not using add-on modules). Also make
sure it's built and running in a healthy environment and not already tainted
before the issue occurs.

If you are facing multiple issues with the Linux kernel at once, report each
separately. While writing your report, include all information relevant to the
issue, like the kernel and the distro used. In case of a regression, CC the
regressions mailing list (regressions@lists.linux.dev) to your report. Also try
to pinpoint the culprit with a bisection; if you succeed, include its
commit-id and CC everyone in the sign-off-by chain.

Once the report is out, answer any questions that come up and help where you
can. That includes keeping the ball rolling by occasionally retesting with newer
releases and sending a status update afterwards.

Step-by-step guide how to report issues to the kernel maintainers
=================================================================

The above TL;DR outlines roughly how to report issues to the Linux kernel
developers. It might be all that's needed for people already familiar with
reporting issues to Free/Libre & Open Source Software (FLOSS) projects. For
everyone else there is this section. It is more detailed and uses a
step-by-step approach. It still tries to be brief for readability and leaves
out a lot of details; those are described below the step-by-step guide in a
reference section, which explains each of the steps in more detail.

Note: this section covers a few more aspects than the TL;DR and does things in
a slightly different order. That's in your interest, to make sure you notice
early if an issue that looks like a Linux kernel problem is actually caused by
something else. These steps thus help to ensure the time you invest in this
process won't feel wasted in the end:

 * Are you facing an issue with a Linux kernel a hardware or software vendor
   provided? Then in almost all cases you are better off to stop reading this
   document and reporting the issue to your vendor instead, unless you are
   willing to install the latest Linux version yourself. Be aware the latter
   will often be needed anyway to hunt down and fix issues.

 * Perform a rough search for existing reports with your favorite internet
   search engine; additionally, check the archives of the `Linux Kernel Mailing
   List (LKML) <https://lore.kernel.org/lkml/>`_. If you find matching reports,
   join the discussion instead of sending a new one.

 * See if the issue you are dealing with qualifies as regression, security
   issue, or a really severe problem: those are 'issues of high priority' that
   need special handling in some steps that are about to follow.

 * Make sure it's not the kernel's surroundings that are causing the issue
   you face.

 * Create a fresh backup and put system repair and restore tools at hand.

 * Ensure your system does not enhance its kernels by building additional
   kernel modules on-the-fly, which solutions like DKMS might be doing locally
   without your knowledge.

 * Check if your kernel was 'tainted' when the issue occurred, as the event
   that made the kernel set this flag might be causing the issue you face.

 * Write down coarsely how to reproduce the issue. If you deal with multiple
   issues at once, create separate notes for each of them and make sure they
   work independently on a freshly booted system. That's needed, as each issue
   needs to get reported to the kernel developers separately, unless they are
   strongly entangled.

 * If you are facing a regression within a stable or longterm version line
   (say something broke when updating from 5.10.4 to 5.10.5), scroll down to
   'Dealing with regressions within a stable and longterm kernel line'.

 * Locate the driver or kernel subsystem that seems to be causing the issue.
   Find out how and where its developers expect reports. Note: most of the
   time this won't be bugzilla.kernel.org, as issues typically need to be sent
   by mail to a maintainer and a public mailing list.

 * Search the archives of the bug tracker or mailing list in question
   thoroughly for reports that might match your issue. If you find anything,
   join the discussion instead of sending a new report.

After these preparations you'll now enter the main part:

 * Unless you are already running the latest 'mainline' Linux kernel, better
   go and install it for the reporting process. Testing and reporting with
   the latest 'stable' Linux can be an acceptable alternative in some
   situations; during the merge window that actually might be even the best
   approach, but in that development phase it can be an even better idea to
   suspend your efforts for a few days anyway. Whatever version you choose,
   ideally use a 'vanilla' build. Ignoring these advices will dramatically
   increase the risk your report will be rejected or ignored.

 * Ensure the kernel you just installed does not 'taint' itself when
   running.

 * Reproduce the issue with the kernel you just installed. If it doesn't show
   up there, scroll down to the instructions for issues only happening with
   stable and longterm kernels.

 * Optimize your notes: try to find and write the most straightforward way to
   reproduce your issue. Make sure the end result has all the important
   details, and at the same time is easy to read and understand for others
   that hear about it for the first time. And if you learned something in this
   process, consider searching again for existing reports about the issue.

 * If your failure involves a 'panic', 'Oops', 'warning', or 'BUG', consider
   decoding the kernel log to find the line of code that triggered the error.

 * If your problem is a regression, try to narrow down when the issue was
   introduced as much as possible.

 * Start to compile the report by writing a detailed description about the
   issue. Always mention a few things: the latest kernel version you installed
   for reproducing, the Linux Distribution used, and your notes on how to
   reproduce the issue. Ideally, make the kernel's build configuration
   (.config) and the output from ``dmesg`` available somewhere on the net and
   link to it. Include or upload all other information that might be relevant,
   like the output/screenshot of an Oops or the output from ``lspci``. Once
   you wrote this main part, insert a normal length paragraph on top of it
   outlining the issue and the impact quickly. On top of this add one sentence
   that briefly describes the problem and gets people to read on. Now give the
   thing a descriptive title or subject that yet again is shorter. Then you're
   ready to send or file the report like the MAINTAINERS file told you, unless
   you are dealing with one of those 'issues of high priority': they need
   special care which is explained in 'Special handling for high priority
   issues' below.

 * Wait for reactions and keep the thing rolling until you can accept the
   outcome in one way or the other. Thus react publicly and in a timely manner
   to any inquiries. Test proposed fixes. Do proactive testing: retest with at
   least every first release candidate (RC) of a new mainline version and
   report your results. Send friendly reminders if things stall. And try to
   help yourself, if you don't get any help or if it's unsatisfying.


Reporting regressions within a stable and longterm kernel line
--------------------------------------------------------------

This subsection is for you, if you followed above process and got sent here at
the point about regression within a stable or longterm kernel version line. You
face one of those if something breaks when updating from 5.10.4 to 5.10.5 (a
switch from 5.9.15 to 5.10.5 does not qualify). The developers want to fix such
regressions as quickly as possible, hence there is a streamlined process to
report them:

 * Check if the kernel developers still maintain the Linux kernel version
   line you care about: go to the  `front page of kernel.org
   <https://kernel.org/>`_ and make sure it mentions
   the latest release of the particular version line without an '[EOL]' tag.

 * Check the archives of the `Linux stable mailing list
   <https://lore.kernel.org/stable/>`_ for existing reports.

 * Install the latest release from the particular version line as a vanilla
   kernel. Ensure this kernel is not tainted and still shows the problem, as
   the issue might have already been fixed there. If you first noticed the
   problem with a vendor kernel, check a vanilla build of the last version
   known to work performs fine as well.

 * Send a short problem report to the Linux stable mailing list
   (stable@vger.kernel.org) and CC the Linux regressions mailing list
   (regressions@lists.linux.dev); if you suspect the cause in a particular
   subsystem, CC its maintainer and its mailing list. Roughly describe the
   issue and ideally explain how to reproduce it. Mention the first version
   that shows the problem and the last version that's working fine. Then
   wait for further instructions.

The reference section below explains each of these steps in more detail.


Reporting issues only occurring in older kernel version lines
-------------------------------------------------------------

This subsection is for you, if you tried the latest mainline kernel as outlined
above, but failed to reproduce your issue there; at the same time you want to
see the issue fixed in a still supported stable or longterm series or vendor
kernels regularly rebased on those. If that is the case, follow these steps:

 * Prepare yourself for the possibility that going through the next few steps
   might not get the issue solved in older releases: the fix might be too big
   or risky to get backported there.

 * Perform the first three steps in the section "Dealing with regressions
   within a stable and longterm kernel line" above.

 * Search the Linux kernel version control system for the change that fixed
   the issue in mainline, as its commit message might tell you if the fix is
   scheduled for backporting already. If you don't find anything that way,
   search the appropriate mailing lists for posts that discuss such an issue
   or peer-review possible fixes; then check the discussions if the fix was
   deemed unsuitable for backporting. If backporting was not considered at
   all, join the newest discussion, asking if it's in the cards.

 * One of the former steps should lead to a solution. If that doesn't work
   out, ask the maintainers for the subsystem that seems to be causing the
   issue for advice; CC the mailing list for the particular subsystem as well
   as the stable mailing list.

The reference section below explains each of these steps in more detail.


Reference section: Reporting issues to the kernel maintainers
=============================================================

The detailed guides above outline all the major steps in brief fashion, which
should be enough for most people. But sometimes there are situations where even
experienced users might wonder how to actually do one of those steps. That's
what this section is for, as it will provide a lot more details on each of the
above steps. Consider this as reference documentation: it's possible to read it
from top to bottom. But it's mainly meant to skim over and a place to look up
details how to actually perform those steps.

A few words of general advice before digging into the details:

 * The Linux kernel developers are well aware this process is complicated and
   demands more than other FLOSS projects. We'd love to make it simpler. But
   that would require work in various places as well as some infrastructure,
   which would need constant maintenance; nobody has stepped up to do that
   work, so that's just how things are for now.

 * A warranty or support contract with some vendor doesn't entitle you to
   request fixes from developers in the upstream Linux kernel community: such
   contracts are completely outside the scope of the Linux kernel, its
   development community, and this document. That's why you can't demand
   anything such a contract guarantees in this context, not even if the
   developer handling the issue works for the vendor in question. If you want
   to claim your rights, use the vendor's support channel instead. When doing
   so, you might want to mention you'd like to see the issue fixed in the
   upstream Linux kernel; motivate them by saying it's the only way to ensure
   the fix in the end will get incorporated in all Linux distributions.

 * If you never reported an issue to a FLOSS project before you should consider
   reading `How to Report Bugs Effectively
   <https://www.chiark.greenend.org.uk/~sgtatham/bugs.html>`_, `How To Ask
   Questions The Smart Way
   <http://www.catb.org/esr/faqs/smart-questions.html>`_, and `How to ask good
   questions <https://jvns.ca/blog/good-questions/>`_.

With that off the table, find below the details on how to properly report
issues to the Linux kernel developers.


Make sure you're using the upstream Linux kernel
------------------------------------------------

   *Are you facing an issue with a Linux kernel a hardware or software vendor
   provided? Then in almost all cases you are better off to stop reading this
   document and reporting the issue to your vendor instead, unless you are
   willing to install the latest Linux version yourself. Be aware the latter
   will often be needed anyway to hunt down and fix issues.*

Like most programmers, Linux kernel developers don't like to spend time dealing
with reports for issues that don't even happen with their current code. It's
just a waste everybody's time, especially yours. Unfortunately such situations
easily happen when it comes to the kernel and often leads to frustration on both
sides. That's because almost all Linux-based kernels pre-installed on devices
(Computers, Laptops, Smartphones, Routers, …) and most shipped by Linux
distributors are quite distant from the official Linux kernel as distributed by
kernel.org: these kernels from these vendors are often ancient from the point of
Linux development or heavily modified, often both.

Most of these vendor kernels are quite unsuitable for reporting issues to the
Linux kernel developers: an issue you face with one of them might have been
fixed by the Linux kernel developers months or years ago already; additionally,
the modifications and enhancements by the vendor might be causing the issue you
face, even if they look small or totally unrelated. That's why you should report
issues with these kernels to the vendor. Its developers should look into the
report and, in case it turns out to be an upstream issue, fix it directly
upstream or forward the report there. In practice that often does not work out
or might not what you want. You thus might want to consider circumventing the
vendor by installing the very latest Linux kernel core yourself. If that's an
option for you move ahead in this process, as a later step in this guide will
explain how to do that once it rules out other potential causes for your issue.

Note, the previous paragraph is starting with the word 'most', as sometimes
developers in fact are willing to handle reports about issues occurring with
vendor kernels. If they do in the end highly depends on the developers and the
issue in question. Your chances are quite good if the distributor applied only
small modifications to a kernel based on a recent Linux version; that for
example often holds true for the mainline kernels shipped by Debian GNU/Linux
Sid or Fedora Rawhide. Some developers will also accept reports about issues
with kernels from distributions shipping the latest stable kernel, as long as
it's only slightly modified; that for example is often the case for Arch Linux,
regular Fedora releases, and openSUSE Tumbleweed. But keep in mind, you better
want to use a mainline Linux and avoid using a stable kernel for this
process, as outlined in the section 'Install a fresh kernel for testing' in more
detail.

Obviously you are free to ignore all this advice and report problems with an old
or heavily modified vendor kernel to the upstream Linux developers. But note,
those often get rejected or ignored, so consider yourself warned. But it's still
better than not reporting the issue at all: sometimes such reports directly or
indirectly will help to get the issue fixed over time.


Search for existing reports, first run
--------------------------------------

   *Perform a rough search for existing reports with your favorite internet
   search engine; additionally, check the archives of the Linux Kernel Mailing
   List (LKML). If you find matching reports, join the discussion instead of
   sending a new one.*

Reporting an issue that someone else already brought forward is often a waste of
time for everyone involved, especially you as the reporter. So it's in your own
interest to thoroughly check if somebody reported the issue already. At this
step of the process it's okay to just perform a rough search: a later step will
tell you to perform a more detailed search once you know where your issue needs
to be reported to. Nevertheless, do not hurry with this step of the reporting
process, it can save you time and trouble.

Simply search the internet with your favorite search engine first. Afterwards,
search the `Linux Kernel Mailing List (LKML) archives
<https://lore.kernel.org/lkml/>`_.

If you get flooded with results consider telling your search engine to limit
search timeframe to the past month or year. And wherever you search, make sure
to use good search terms; vary them a few times, too. While doing so try to
look at the issue from the perspective of someone else: that will help you to
come up with other words to use as search terms. Also make sure not to use too
many search terms at once. Remember to search with and without information like
the name of the kernel driver or the name of the affected hardware component.
But its exact brand name (say 'ASUS Red Devil Radeon RX 5700 XT Gaming OC')
often is not much helpful, as it is too specific. Instead try search terms like
the model line (Radeon 5700 or Radeon 5000) and the code name of the main chip
('Navi' or 'Navi10') with and without its manufacturer ('AMD').

In case you find an existing report about your issue, join the discussion, as
you might be able to provide valuable additional information. That can be
important even when a fix is prepared or in its final stages already, as
developers might look for people that can provide additional information or
test a proposed fix. Jump to the section 'Duties after the report went out' for
details on how to get properly involved.

Note, searching `bugzilla.kernel.org <https://bugzilla.kernel.org/>`_ might also
be a good idea, as that might provide valuable insights or turn up matching
reports. If you find the latter, just keep in mind: most subsystems expect
reports in different places, as described below in the section "Check where you
need to report your issue". The developers that should take care of the issue
thus might not even be aware of the bugzilla ticket. Hence, check the ticket if
the issue already got reported as outlined in this document and if not consider
doing so.


Issue of high priority?
-----------------------

    *See if the issue you are dealing with qualifies as regression, security
    issue, or a really severe problem: those are 'issues of high priority' that
    need special handling in some steps that are about to follow.*

Linus Torvalds and the leading Linux kernel developers want to see some issues
fixed as soon as possible, hence there are 'issues of high priority' that get
handled slightly differently in the reporting process. Three type of cases
qualify: regressions, security issues, and really severe problems.

You deal with a regression if some application or practical use case running
fine with one Linux kernel works worse or not at all with a newer version
compiled using a similar configuration. The document
Documentation/admin-guide/reporting-regressions.rst explains this in more
detail. It also provides a good deal of other information about regressions you
might want to be aware of; it for example explains how to add your issue to the
list of tracked regressions, to ensure it won't fall through the cracks.

What qualifies as security issue is left to your judgment. Consider reading
Documentation/process/security-bugs.rst before proceeding, as it
provides additional details how to best handle security issues.

An issue is a 'really severe problem' when something totally unacceptably bad
happens. That's for example the case when a Linux kernel corrupts the data it's
handling or damages hardware it's running on. You're also dealing with a severe
issue when the kernel suddenly stops working with an error message ('kernel
panic') or without any farewell note at all. Note: do not confuse a 'panic' (a
fatal error where the kernel stop itself) with a 'Oops' (a recoverable error),
as the kernel remains running after the latter.


Ensure a healthy environment
----------------------------

    *Make sure it's not the kernel's surroundings that are causing the issue
    you face.*

Problems that look a lot like a kernel issue are sometimes caused by build or
runtime environment. It's hard to rule out that problem completely, but you
should minimize it:

 * Use proven tools when building your kernel, as bugs in the compiler or the
   binutils can cause the resulting kernel to misbehave.

 * Ensure your computer components run within their design specifications;
   that's especially important for the main processor, the main memory, and the
   motherboard. Therefore, stop undervolting or overclocking when facing a
   potential kernel issue.

 * Try to make sure it's not faulty hardware that is causing your issue. Bad
   main memory for example can result in a multitude of issues that will
   manifest itself in problems looking like kernel issues.

 * If you're dealing with a filesystem issue, you might want to check the file
   system in question with ``fsck``, as it might be damaged in a way that leads
   to unexpected kernel behavior.

 * When dealing with a regression, make sure it's not something else that
   changed in parallel to updating the kernel. The problem for example might be
   caused by other software that was updated at the same time. It can also
   happen that a hardware component coincidentally just broke when you rebooted
   into a new kernel for the first time. Updating the systems BIOS or changing
   something in the BIOS Setup can also lead to problems that on look a lot
   like a kernel regression.


Prepare for emergencies
-----------------------

    *Create a fresh backup and put system repair and restore tools at hand.*

Reminder, you are dealing with computers, which sometimes do unexpected things,
especially if you fiddle with crucial parts like the kernel of its operating
system. That's what you are about to do in this process. Thus, make sure to
create a fresh backup; also ensure you have all tools at hand to repair or
reinstall the operating system as well as everything you need to restore the
backup.


Make sure your kernel doesn't get enhanced
------------------------------------------

    *Ensure your system does not enhance its kernels by building additional
    kernel modules on-the-fly, which solutions like DKMS might be doing locally
    without your knowledge.*

The risk your issue report gets ignored or rejected dramatically increases if
your kernel gets enhanced in any way. That's why you should remove or disable
mechanisms like akmods and DKMS: those build add-on kernel modules
automatically, for example when you install a new Linux kernel or boot it for
the first time. Also remove any modules they might have installed. Then reboot
before proceeding.

Note, you might not be aware that your system is using one of these solutions:
they often get set up silently when you install Nvidia's proprietary graphics
driver, VirtualBox, or other software that requires a some support from a
module not part of the Linux kernel. That why your might need to uninstall the
packages with such software to get rid of any 3rd party kernel module.


Check 'taint' flag
------------------

    *Check if your kernel was 'tainted' when the issue occurred, as the event
    that made the kernel set this flag might be causing the issue you face.*

The kernel marks itself with a 'taint' flag when something happens that might
lead to follow-up errors that look totally unrelated. The issue you face might
be such an error if your kernel is tainted. That's why it's in your interest to
rule this out early before investing more time into this process. This is the
only reason why this step is here, as this process later will tell you to
install the latest mainline kernel; you will need to check the taint flag again
then, as that's when it matters because it's the kernel the report will focus
on.

On a running system is easy to check if the kernel tainted itself: if ``cat
/proc/sys/kernel/tainted`` returns '0' then the kernel is not tainted and
everything is fine. Checking that file is impossible in some situations; that's
why the kernel also mentions the taint status when it reports an internal
problem (a 'kernel bug'), a recoverable error (a 'kernel Oops') or a
non-recoverable error before halting operation (a 'kernel panic'). Look near
the top of the error messages printed when one of these occurs and search for a
line starting with 'CPU:'. It should end with 'Not tainted' if the kernel was
not tainted when it noticed the problem; it was tainted if you see 'Tainted:'
followed by a few spaces and some letters.

If your kernel is tainted, study Documentation/admin-guide/tainted-kernels.rst
to find out why. Try to eliminate the reason. Often it's caused by one these
three things:

 1. A recoverable error (a 'kernel Oops') occurred and the kernel tainted
    itself, as the kernel knows it might misbehave in strange ways after that
    point. In that case check your kernel or system log and look for a section
    that starts with this::

       Oops: 0000 [#1] SMP

    That's the first Oops since boot-up, as the '#1' between the brackets shows.
    Every Oops and any other problem that happens after that point might be a
    follow-up problem to that first Oops, even if both look totally unrelated.
    Rule this out by getting rid of the cause for the first Oops and reproducing
    the issue afterwards. Sometimes simply restarting will be enough, sometimes
    a change to the configuration followed by a reboot can eliminate the Oops.
    But don't invest too much time into this at this point of the process, as
    the cause for the Oops might already be fixed in the newer Linux kernel
    version you are going to install later in this process.

 2. Your system uses a software that installs its own kernel modules, for
    example Nvidia's proprietary graphics driver or VirtualBox. The kernel
    taints itself when it loads such module from external sources (even if
    they are Open Source): they sometimes cause errors in unrelated kernel
    areas and thus might be causing the issue you face. You therefore have to
    prevent those modules from loading when you want to report an issue to the
    Linux kernel developers. Most of the time the easiest way to do that is:
    temporarily uninstall such software including any modules they might have
    installed. Afterwards reboot.

 3. The kernel also taints itself when it's loading a module that resides in
    the staging tree of the Linux kernel source. That's a special area for
    code (mostly drivers) that does not yet fulfill the normal Linux kernel
    quality standards. When you report an issue with such a module it's
    obviously okay if the kernel is tainted; just make sure the module in
    question is the only reason for the taint. If the issue happens in an
    unrelated area reboot and temporarily block the module from being loaded
    by specifying ``foo.blacklist=1`` as kernel parameter (replace 'foo' with
    the name of the module in question).


Document how to reproduce issue
-------------------------------

    *Write down coarsely how to reproduce the issue. If you deal with multiple
    issues at once, create separate notes for each of them and make sure they
    work independently on a freshly booted system. That's needed, as each issue
    needs to get reported to the kernel developers separately, unless they are
    strongly entangled.*

If you deal with multiple issues at once, you'll have to report each of them
separately, as they might be handled by different developers. Describing
various issues in one report also makes it quite difficult for others to tear
it apart. Hence, only combine issues in one report if they are very strongly
entangled.

Additionally, during the reporting process you will have to test if the issue
happens with other kernel versions. Therefore, it will make your work easier if
you know exactly how to reproduce an issue quickly on a freshly booted system.

Note: it's often fruitless to report issues that only happened once, as they
might be caused by a bit flip due to cosmic radiation. That's why you should
try to rule that out by reproducing the issue before going further. Feel free
to ignore this advice if you are experienced enough to tell a one-time error
due to faulty hardware apart from a kernel issue that rarely happens and thus
is hard to reproduce.


Regression in stable or longterm kernel?
----------------------------------------

    *If you are facing a regression within a stable or longterm version line
    (say something broke when updating from 5.10.4 to 5.10.5), scroll down to
    'Dealing with regressions within a stable and longterm kernel line'.*

Regression within a stable and longterm kernel version line are something the
Linux developers want to fix badly, as such issues are even more unwanted than
regression in the main development branch, as they can quickly affect a lot of
people. The developers thus want to learn about such issues as quickly as
possible, hence there is a streamlined process to report them. Note,
regressions with newer kernel version line (say something broke when switching
from 5.9.15 to 5.10.5) do not qualify.


Check where you need to report your issue
-----------------------------------------

    *Locate the driver or kernel subsystem that seems to be causing the issue.
    Find out how and where its developers expect reports. Note: most of the
    time this won't be bugzilla.kernel.org, as issues typically need to be sent
    by mail to a maintainer and a public mailing list.*

It's crucial to send your report to the right people, as the Linux kernel is a
big project and most of its developers are only familiar with a small subset of
it. Quite a few programmers for example only care for just one driver, for
example one for a WiFi chip; its developer likely will only have small or no
knowledge about the internals of remote or unrelated "subsystems", like the TCP
stack, the PCIe/PCI subsystem, memory management or file systems.

Problem is: the Linux kernel lacks a central bug tracker where you can simply
file your issue and make it reach the developers that need to know about it.
That's why you have to find the right place and way to report issues yourself.
You can do that with the help of a script (see below), but it mainly targets
kernel developers and experts. For everybody else the MAINTAINERS file is the
better place.

How to read the MAINTAINERS file
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To illustrate how to use the :ref:`MAINTAINERS <maintainers>` file, let's assume
the WiFi in your Laptop suddenly misbehaves after updating the kernel. In that
case it's likely an issue in the WiFi driver. Obviously it could also be some
code it builds upon, but unless you suspect something like that stick to the
driver. If it's really something else, the driver's developers will get the
right people involved.

Sadly, there is no way to check which code is driving a particular hardware
component that is both universal and easy.

In case of a problem with the WiFi driver you for example might want to look at
the output of ``lspci -k``, as it lists devices on the PCI/PCIe bus and the
kernel module driving it::

       [user@something ~]$ lspci -k
       [...]
       3a:00.0 Network controller: Qualcomm Atheros QCA6174 802.11ac Wireless Network Adapter (rev 32)
         Subsystem: Bigfoot Networks, Inc. Device 1535
         Kernel driver in use: ath10k_pci
         Kernel modules: ath10k_pci
       [...]

But this approach won't work if your WiFi chip is connected over USB or some
other internal bus. In those cases you might want to check your WiFi manager or
the output of ``ip link``. Look for the name of the problematic network
interface, which might be something like 'wlp58s0'. This name can be used like
this to find the module driving it::

       [user@something ~]$ realpath --relative-to=/sys/module/ /sys/class/net/wlp58s0/device/driver/module
       ath10k_pci

In case tricks like these don't bring you any further, try to search the
internet on how to narrow down the driver or subsystem in question. And if you
are unsure which it is: just try your best guess, somebody will help you if you
guessed poorly.

Once you know the driver or subsystem, you want to search for it in the
MAINTAINERS file. In the case of 'ath10k_pci' you won't find anything, as the
name is too specific. Sometimes you will need to search on the net for help;
but before doing so, try a somewhat shorted or modified name when searching the
MAINTAINERS file, as then you might find something like this::

       QUALCOMM ATHEROS ATH10K WIRELESS DRIVER
       Mail:          A. Some Human <shuman@example.com>
       Mailing list:  ath10k@lists.infradead.org
       Status:        Supported
       Web-page:      https://wireless.wiki.kernel.org/en/users/Drivers/ath10k
       SCM:           git git://git.kernel.org/pub/scm/linux/kernel/git/kvalo/ath.git
       Files:         drivers/net/wireless/ath/ath10k/

Note: the line description will be abbreviations, if you read the plain
MAINTAINERS file found in the root of the Linux source tree. 'Mail:' for
example will be 'M:', 'Mailing list:' will be 'L', and 'Status:' will be 'S:'.
A section near the top of the file explains these and other abbreviations.

First look at the line 'Status'. Ideally it should be 'Supported' or
'Maintained'. If it states 'Obsolete' then you are using some outdated approach
that was replaced by a newer solution you need to switch to. Sometimes the code
only has someone who provides 'Odd Fixes' when feeling motivated. And with
'Orphan' you are totally out of luck, as nobody takes care of the code anymore.
That only leaves these options: arrange yourself to live with the issue, fix it
yourself, or find a programmer somewhere willing to fix it.

After checking the status, look for a line starting with 'bugs:': it will tell
you where to find a subsystem specific bug tracker to file your issue. The
example above does not have such a line. That is the case for most sections, as
Linux kernel development is completely driven by mail. Very few subsystems use
a bug tracker, and only some of those rely on bugzilla.kernel.org.

In this and many other cases you thus have to look for lines starting with
'Mail:' instead. Those mention the name and the email addresses for the
maintainers of the particular code. Also look for a line starting with 'Mailing
list:', which tells you the public mailing list where the code is developed.
Your report later needs to go by mail to those addresses. Additionally, for all
issue reports sent by email, make sure to add the Linux Kernel Mailing List
(LKML) <linux-kernel@vger.kernel.org> to CC. Don't omit either of the mailing
lists when sending your issue report by mail later! Maintainers are busy people
and might leave some work for other developers on the subsystem specific list;
and LKML is important to have one place where all issue reports can be found.


Finding the maintainers with the help of a script
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

For people that have the Linux sources at hand there is a second option to find
the proper place to report: the script 'scripts/get_maintainer.pl' which tries
to find all people to contact. It queries the MAINTAINERS file and needs to be
called with a path to the source code in question. For drivers compiled as
module if often can be found with a command like this::

       $ modinfo ath10k_pci | grep filename | sed 's!/lib/modules/.*/kernel/!!; s!filename:!!; s!\.ko\(\|\.xz\)!!'
       drivers/net/wireless/ath/ath10k/ath10k_pci.ko

Pass parts of this to the script::

       $ ./scripts/get_maintainer.pl -f drivers/net/wireless/ath/ath10k*
       Some Human <shuman@example.com> (supporter:QUALCOMM ATHEROS ATH10K WIRELESS DRIVER)
       Another S. Human <asomehuman@example.com> (maintainer:NETWORKING DRIVERS)
       ath10k@lists.infradead.org (open list:QUALCOMM ATHEROS ATH10K WIRELESS DRIVER)
       linux-wireless@vger.kernel.org (open list:NETWORKING DRIVERS (WIRELESS))
       netdev@vger.kernel.org (open list:NETWORKING DRIVERS)
       linux-kernel@vger.kernel.org (open list)

Don't sent your report to all of them. Send it to the maintainers, which the
script calls "supporter:"; additionally CC the most specific mailing list for
the code as well as the Linux Kernel Mailing List (LKML). In this case you thus
would need to send the report to 'Some Human <shuman@example.com>' with
'ath10k@lists.infradead.org' and 'linux-kernel@vger.kernel.org' in CC.

Note: in case you cloned the Linux sources with git you might want to call
``get_maintainer.pl`` a second time with ``--git``. The script then will look
at the commit history to find which people recently worked on the code in
question, as they might be able to help. But use these results with care, as it
can easily send you in a wrong direction. That for example happens quickly in
areas rarely changed (like old or unmaintained drivers): sometimes such code is
modified during tree-wide cleanups by developers that do not care about the
particular driver at all.


Search for existing reports, second run
---------------------------------------

    *Search the archives of the bug tracker or mailing list in question
    thoroughly for reports that might match your issue. If you find anything,
    join the discussion instead of sending a new report.*

As mentioned earlier already: reporting an issue that someone else already
brought forward is often a waste of time for everyone involved, especially you
as the reporter. That's why you should search for existing report again, now
that you know where they need to be reported to. If it's mailing list, you will
often find its archives on `lore.kernel.org <https://lore.kernel.org/>`_.

But some list are hosted in different places. That for example is the case for
the ath10k WiFi driver used as example in the previous step. But you'll often
find the archives for these lists easily on the net. Searching for 'archive
ath10k@lists.infradead.org' for example will lead you to the `Info page for the
ath10k mailing list <https://lists.infradead.org/mailman/listinfo/ath10k>`_,
which at the top links to its
`list archives <https://lists.infradead.org/pipermail/ath10k/>`_. Sadly this and
quite a few other lists miss a way to search the archives. In those cases use a
regular internet search engine and add something like
'site:lists.infradead.org/pipermail/ath10k/' to your search terms, which limits
the results to the archives at that URL.

It's also wise to check the internet, LKML and maybe bugzilla.kernel.org again
at this point. If your report needs to be filed in a bug tracker, you may want
to check the mailing list archives for the subsystem as well, as someone might
have reported it only there.

For details how to search and what to do if you find matching reports see
"Search for existing reports, first run" above.

Do not hurry with this step of the reporting process: spending 30 to 60 minutes
or even more time can save you and others quite a lot of time and trouble.


Install a fresh kernel for testing
----------------------------------

    *Unless you are already running the latest 'mainline' Linux kernel, better
    go and install it for the reporting process. Testing and reporting with
    the latest 'stable' Linux can be an acceptable alternative in some
    situations; during the merge window that actually might be even the best
    approach, but in that development phase it can be an even better idea to
    suspend your efforts for a few days anyway. Whatever version you choose,
    ideally use a 'vanilla' built. Ignoring these advices will dramatically
    increase the risk your report will be rejected or ignored.*

As mentioned in the detailed explanation for the first step already: Like most
programmers, Linux kernel developers don't like to spend time dealing with
reports for issues that don't even happen with the current code. It's just a
waste everybody's time, especially yours. That's why it's in everybody's
interest that you confirm the issue still exists with the latest upstream code
before reporting it. You are free to ignore this advice, but as outlined
earlier: doing so dramatically increases the risk that your issue report might
get rejected or simply ignored.

In the scope of the kernel "latest upstream" normally means:

 * Install a mainline kernel; the latest stable kernel can be an option, but
   most of the time is better avoided. Longterm kernels (sometimes called 'LTS
   kernels') are unsuitable at this point of the process. The next subsection
   explains all of this in more detail.

 * The over next subsection describes way to obtain and install such a kernel.
   It also outlines that using a pre-compiled kernel are fine, but better are
   vanilla, which means: it was built using Linux sources taken straight `from
   kernel.org <https://kernel.org/>`_ and not modified or enhanced in any way.

Choosing the right version for testing
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Head over to `kernel.org <https://kernel.org/>`_ to find out which version you
want to use for testing. Ignore the big yellow button that says 'Latest release'
and look a little lower at the table. At its top you'll see a line starting with
mainline, which most of the time will point to a pre-release with a version
number like '5.8-rc2'. If that's the case, you'll want to use this mainline
kernel for testing, as that where all fixes have to be applied first. Do not let
that 'rc' scare you, these 'development kernels' are pretty reliable — and you
made a backup, as you were instructed above, didn't you?

In about two out of every nine to ten weeks, mainline might point you to a
proper release with a version number like '5.7'. If that happens, consider
suspending the reporting process until the first pre-release of the next
version (5.8-rc1) shows up on kernel.org. That's because the Linux development
cycle then is in its two-week long 'merge window'. The bulk of the changes and
all intrusive ones get merged for the next release during this time. It's a bit
more risky to use mainline during this period. Kernel developers are also often
quite busy then and might have no spare time to deal with issue reports. It's
also quite possible that one of the many changes applied during the merge
window fixes the issue you face; that's why you soon would have to retest with
a newer kernel version anyway, as outlined below in the section 'Duties after
the report went out'.

That's why it might make sense to wait till the merge window is over. But don't
to that if you're dealing with something that shouldn't wait. In that case
consider obtaining the latest mainline kernel via git (see below) or use the
latest stable version offered on kernel.org. Using that is also acceptable in
case mainline for some reason does currently not work for you. An in general:
using it for reproducing the issue is also better than not reporting it issue
at all.

Better avoid using the latest stable kernel outside merge windows, as all fixes
must be applied to mainline first. That's why checking the latest mainline
kernel is so important: any issue you want to see fixed in older version lines
needs to be fixed in mainline first before it can get backported, which can
take a few days or weeks. Another reason: the fix you hope for might be too
hard or risky for backporting; reporting the issue again hence is unlikely to
change anything.

These aspects are also why longterm kernels (sometimes called "LTS kernels")
are unsuitable for this part of the reporting process: they are to distant from
the current code. Hence go and test mainline first and follow the process
further: if the issue doesn't occur with mainline it will guide you how to get
it fixed in older version lines, if that's in the cards for the fix in question.

How to obtain a fresh Linux kernel
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

**Using a pre-compiled kernel**: This is often the quickest, easiest, and safest
way for testing — especially is you are unfamiliar with the Linux kernel. The
problem: most of those shipped by distributors or add-on repositories are build
from modified Linux sources. They are thus not vanilla and therefore often
unsuitable for testing and issue reporting: the changes might cause the issue
you face or influence it somehow.

But you are in luck if you are using a popular Linux distribution: for quite a
few of them you'll find repositories on the net that contain packages with the
latest mainline or stable Linux built as vanilla kernel. It's totally okay to
use these, just make sure from the repository's description they are vanilla or
at least close to it. Additionally ensure the packages contain the latest
versions as offered on kernel.org. The packages are likely unsuitable if they
are older than a week, as new mainline and stable kernels typically get released
at least once a week.

Please note that you might need to build your own kernel manually later: that's
sometimes needed for debugging or testing fixes, as described later in this
document. Also be aware that pre-compiled kernels might lack debug symbols that
are needed to decode messages the kernel prints when a panic, Oops, warning, or
BUG occurs; if you plan to decode those, you might be better off compiling a
kernel yourself (see the end of this subsection and the section titled 'Decode
failure messages' for details).

**Using git**: Developers and experienced Linux users familiar with git are
often best served by obtaining the latest Linux kernel sources straight from the
`official development repository on kernel.org
<https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/>`_.
Those are likely a bit ahead of the latest mainline pre-release. Don't worry
about it: they are as reliable as a proper pre-release, unless the kernel's
development cycle is currently in the middle of a merge window. But even then
they are quite reliable.

**Conventional**: People unfamiliar with git are often best served by
downloading the sources as tarball from `kernel.org <https://kernel.org/>`_.

How to actually build a kernel is not described here, as many websites explain
the necessary steps already. If you are new to it, consider following one of
those how-to's that suggest to use ``make localmodconfig``, as that tries to
pick up the configuration of your current kernel and then tries to adjust it
somewhat for your system. That does not make the resulting kernel any better,
but quicker to compile.

Note: If you are dealing with a panic, Oops, warning, or BUG from the kernel,
please try to enable CONFIG_KALLSYMS when configuring your kernel.
Additionally, enable CONFIG_DEBUG_KERNEL and CONFIG_DEBUG_INFO, too; the
latter is the relevant one of those two, but can only be reached if you enable
the former. Be aware CONFIG_DEBUG_INFO increases the storage space required to
build a kernel by quite a bit. But that's worth it, as these options will allow
you later to pinpoint the exact line of code that triggers your issue. The
section 'Decode failure messages' below explains this in more detail.

But keep in mind: Always keep a record of the issue encountered in case it is
hard to reproduce. Sending an undecoded report is better than not reporting
the issue at all.


Check 'taint' flag
------------------

    *Ensure the kernel you just installed does not 'taint' itself when
    running.*

As outlined above in more detail already: the kernel sets a 'taint' flag when
something happens that can lead to follow-up errors that look totally
unrelated. That's why you need to check if the kernel you just installed does
not set this flag. And if it does, you in almost all the cases needs to
eliminate the reason for it before you reporting issues that occur with it. See
the section above for details how to do that.


Reproduce issue with the fresh kernel
-------------------------------------

    *Reproduce the issue with the kernel you just installed. If it doesn't show
    up there, scroll down to the instructions for issues only happening with
    stable and longterm kernels.*

Check if the issue occurs with the fresh Linux kernel version you just
installed. If it was fixed there already, consider sticking with this version
line and abandoning your plan to report the issue. But keep in mind that other
users might still be plagued by it, as long as it's not fixed in either stable
and longterm version from kernel.org (and thus vendor kernels derived from
those). If you prefer to use one of those or just want to help their users,
head over to the section "Details about reporting issues only occurring in
older kernel version lines" below.


Optimize description to reproduce issue
---------------------------------------

    *Optimize your notes: try to find and write the most straightforward way to
    reproduce your issue. Make sure the end result has all the important
    details, and at the same time is easy to read and understand for others
    that hear about it for the first time. And if you learned something in this
    process, consider searching again for existing reports about the issue.*

An unnecessarily complex report will make it hard for others to understand your
report. Thus try to find a reproducer that's straight forward to describe and
thus easy to understand in written form. Include all important details, but at
the same time try to keep it as short as possible.

In this in the previous steps you likely have learned a thing or two about the
issue you face. Use this knowledge and search again for existing reports
instead you can join.


Decode failure messages
-----------------------

    *If your failure involves a 'panic', 'Oops', 'warning', or 'BUG', consider
    decoding the kernel log to find the line of code that triggered the error.*

When the kernel detects an internal problem, it will log some information about
the executed code. This makes it possible to pinpoint the exact line in the
source code that triggered the issue and shows how it was called. But that only
works if you enabled CONFIG_DEBUG_INFO and CONFIG_KALLSYMS when configuring
your kernel. If you did so, consider to decode the information from the
kernel's log. That will make it a lot easier to understand what lead to the
'panic', 'Oops', 'warning', or 'BUG', which increases the chances that someone
can provide a fix.

Decoding can be done with a script you find in the Linux source tree. If you
are running a kernel you compiled yourself earlier, call it like this::

       [user@something ~]$ sudo dmesg | ./linux-5.10.5/scripts/decode_stacktrace.sh ./linux-5.10.5/vmlinux

If you are running a packaged vanilla kernel, you will likely have to install
the corresponding packages with debug symbols. Then call the script (which you
might need to get from the Linux sources if your distro does not package it)
like this::

       [user@something ~]$ sudo dmesg | ./linux-5.10.5/scripts/decode_stacktrace.sh \
        /usr/lib/debug/lib/modules/5.10.10-4.1.x86_64/vmlinux /usr/src/kernels/5.10.10-4.1.x86_64/

The script will work on log lines like the following, which show the address of
the code the kernel was executing when the error occurred::

       [   68.387301] RIP: 0010:test_module_init+0x5/0xffa [test_module]

Once decoded, these lines will look like this::

       [   68.387301] RIP: 0010:test_module_init (/home/username/linux-5.10.5/test-module/test-module.c:16) test_module

In this case the executed code was built from the file
'~/linux-5.10.5/test-module/test-module.c' and the error occurred by the
instructions found in line '16'.

The script will similarly decode the addresses mentioned in the section
starting with 'Call trace', which show the path to the function where the
problem occurred. Additionally, the script will show the assembler output for
the code section the kernel was executing.

Note, if you can't get this to work, simply skip this step and mention the
reason for it in the report. If you're lucky, it might not be needed. And if it
is, someone might help you to get things going. Also be aware this is just one
of several ways to decode kernel stack traces. Sometimes different steps will
be required to retrieve the relevant details. Don't worry about that, if that's
needed in your case, developers will tell you what to do.


Special care for regressions
----------------------------

    *If your problem is a regression, try to narrow down when the issue was
    introduced as much as possible.*

Linux lead developer Linus Torvalds insists that the Linux kernel never
worsens, that's why he deems regressions as unacceptable and wants to see them
fixed quickly. That's why changes that introduced a regression are often
promptly reverted if the issue they cause can't get solved quickly any other
way. Reporting a regression is thus a bit like playing a kind of trump card to
get something quickly fixed. But for that to happen the change that's causing
the regression needs to be known. Normally it's up to the reporter to track
down the culprit, as maintainers often won't have the time or setup at hand to
reproduce it themselves.

To find the change there is a process called 'bisection' which the document
Documentation/admin-guide/bug-bisect.rst describes in detail. That process
will often require you to build about ten to twenty kernel images, trying to
reproduce the issue with each of them before building the next. Yes, that takes
some time, but don't worry, it works a lot quicker than most people assume.
Thanks to a 'binary search' this will lead you to the one commit in the source
code management system that's causing the regression. Once you find it, search
the net for the subject of the change, its commit id and the shortened commit id
(the first 12 characters of the commit id). This will lead you to existing
reports about it, if there are any.

Note, a bisection needs a bit of know-how, which not everyone has, and quite a
bit of effort, which not everyone is willing to invest. Nevertheless, it's
highly recommended performing a bisection yourself. If you really can't or
don't want to go down that route at least find out which mainline kernel
introduced the regression. If something for example breaks when switching from
5.5.15 to 5.8.4, then try at least all the mainline releases in that area (5.6,
5.7 and 5.8) to check when it first showed up. Unless you're trying to find a
regression in a stable or longterm kernel, avoid testing versions which number
has three sections (5.6.12, 5.7.8), as that makes the outcome hard to
interpret, which might render your testing useless. Once you found the major
version which introduced the regression, feel free to move on in the reporting
process. But keep in mind: it depends on the issue at hand if the developers
will be able to help without knowing the culprit. Sometimes they might
recognize from the report want went wrong and can fix it; other times they will
be unable to help unless you perform a bisection.

When dealing with regressions make sure the issue you face is really caused by
the kernel and not by something else, as outlined above already.

In the whole process keep in mind: an issue only qualifies as regression if the
older and the newer kernel got built with a similar configuration. This can be
achieved by using ``make olddefconfig``, as explained in more detail by
Documentation/admin-guide/reporting-regressions.rst; that document also
provides a good deal of other information about regressions you might want to be
aware of.


Write and send the report
-------------------------

    *Start to compile the report by writing a detailed description about the
    issue. Always mention a few things: the latest kernel version you installed
    for reproducing, the Linux Distribution used, and your notes on how to
    reproduce the issue. Ideally, make the kernel's build configuration
    (.config) and the output from ``dmesg`` available somewhere on the net and
    link to it. Include or upload all other information that might be relevant,
    like the output/screenshot of an Oops or the output from ``lspci``. Once
    you wrote this main part, insert a normal length paragraph on top of it
    outlining the issue and the impact quickly. On top of this add one sentence
    that briefly describes the problem and gets people to read on. Now give the
    thing a descriptive title or subject that yet again is shorter. Then you're
    ready to send or file the report like the MAINTAINERS file told you, unless
    you are dealing with one of those 'issues of high priority': they need
    special care which is explained in 'Special handling for high priority
    issues' below.*

Now that you have prepared everything it's time to write your report. How to do
that is partly explained by the three documents linked to in the preface above.
That's why this text will only mention a few of the essentials as well as
things specific to the Linux kernel.

There is one thing that fits both categories: the most crucial parts of your
report are the title/subject, the first sentence, and the first paragraph.
Developers often get quite a lot of mail. They thus often just take a few
seconds to skim a mail before deciding to move on or look closer. Thus: the
better the top section of your report, the higher are the chances that someone
will look into it and help you. And that is why you should ignore them for now
and write the detailed report first. ;-)

Things each report should mention
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Describe in detail how your issue happens with the fresh vanilla kernel you
installed. Try to include the step-by-step instructions you wrote and optimized
earlier that outline how you and ideally others can reproduce the issue; in
those rare cases where that's impossible try to describe what you did to
trigger it.

Also include all the relevant information others might need to understand the
issue and its environment. What's actually needed depends a lot on the issue,
but there are some things you should include always:

 * the output from ``cat /proc/version``, which contains the Linux kernel
   version number and the compiler it was built with.

 * the Linux distribution the machine is running (``hostnamectl | grep
   "Operating System"``)

 * the architecture of the CPU and the operating system (``uname -mi``)

 * if you are dealing with a regression and performed a bisection, mention the
   subject and the commit-id of the change that is causing it.

In a lot of cases it's also wise to make two more things available to those
that read your report:

 * the configuration used for building your Linux kernel (the '.config' file)

 * the kernel's messages that you get from ``dmesg`` written to a file. Make
   sure that it starts with a line like 'Linux version 5.8-1
   (foobar@example.com) (gcc (GCC) 10.2.1, GNU ld version 2.34) #1 SMP Mon Aug
   3 14:54:37 UTC 2020' If it's missing, then important messages from the first
   boot phase already got discarded. In this case instead consider using
   ``journalctl -b 0 -k``; alternatively you can also reboot, reproduce the
   issue and call ``dmesg`` right afterwards.

These two files are big, that's why it's a bad idea to put them directly into
your report. If you are filing the issue in a bug tracker then attach them to
the ticket. If you report the issue by mail do not attach them, as that makes
the mail too large; instead do one of these things:

 * Upload the files somewhere public (your website, a public file paste
   service, a ticket created just for this purpose on `bugzilla.kernel.org
   <https://bugzilla.kernel.org/>`_, ...) and include a link to them in your
   report. Ideally use something where the files stay available for years, as
   they could be useful to someone many years from now; this for example can
   happen if five or ten years from now a developer works on some code that was
   changed just to fix your issue.

 * Put the files aside and mention you will send them later in individual
   replies to your own mail. Just remember to actually do that once the report
   went out. ;-)

Things that might be wise to provide
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Depending on the issue you might need to add more background data. Here are a
few suggestions what often is good to provide:

 * If you are dealing with a 'warning', an 'OOPS' or a 'panic' from the kernel,
   include it. If you can't copy'n'paste it, try to capture a netconsole trace
   or at least take a picture of the screen.

 * If the issue might be related to your computer hardware, mention what kind
   of system you use. If you for example have problems with your graphics card,
   mention its manufacturer, the card's model, and what chip is uses. If it's a
   laptop mention its name, but try to make sure it's meaningful. 'Dell XPS 13'
   for example is not, because it might be the one from 2012; that one looks
   not that different from the one sold today, but apart from that the two have
   nothing in common. Hence, in such cases add the exact model number, which
   for example are '9380' or '7390' for XPS 13 models introduced during 2019.
   Names like 'Lenovo Thinkpad T590' are also somewhat ambiguous: there are
   variants of this laptop with and without a dedicated graphics chip, so try
   to find the exact model name or specify the main components.

 * Mention the relevant software in use. If you have problems with loading
   modules, you want to mention the versions of kmod, systemd, and udev in use.
   If one of the DRM drivers misbehaves, you want to state the versions of
   libdrm and Mesa; also specify your Wayland compositor or the X-Server and
   its driver. If you have a filesystem issue, mention the version of
   corresponding filesystem utilities (e2fsprogs, btrfs-progs, xfsprogs, ...).

 * Gather additional information from the kernel that might be of interest. The
   output from ``lspci -nn`` will for example help others to identify what
   hardware you use. If you have a problem with hardware you even might want to
   make the output from ``sudo lspci -vvv`` available, as that provides
   insights how the components were configured. For some issues it might be
   good to include the contents of files like ``/proc/cpuinfo``,
   ``/proc/ioports``, ``/proc/iomem``, ``/proc/modules``, or
   ``/proc/scsi/scsi``. Some subsystem also offer tools to collect relevant
   information. One such tool is ``alsa-info.sh`` `which the audio/sound
   subsystem developers provide <https://www.alsa-project.org/wiki/AlsaInfo>`_.

Those examples should give your some ideas of what data might be wise to
attach, but you have to think yourself what will be helpful for others to know.
Don't worry too much about forgetting something, as developers will ask for
additional details they need. But making everything important available from
the start increases the chance someone will take a closer look.


The important part: the head of your report
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Now that you have the detailed part of the report prepared let's get to the
most important section: the first few sentences. Thus go to the top, add
something like 'The detailed description:' before the part you just wrote and
insert two newlines at the top. Now write one normal length paragraph that
describes the issue roughly. Leave out all boring details and focus on the
crucial parts readers need to know to understand what this is all about; if you
think this bug affects a lot of users, mention this to get people interested.

Once you did that insert two more lines at the top and write a one sentence
summary that explains quickly what the report is about. After that you have to
get even more abstract and write an even shorter subject/title for the report.

Now that you have written this part take some time to optimize it, as it is the
most important parts of your report: a lot of people will only read this before
they decide if reading the rest is time well spent.

Now send or file the report like the :ref:`MAINTAINERS <maintainers>` file told
you, unless it's one of those 'issues of high priority' outlined earlier: in
that case please read the next subsection first before sending the report on
its way.

Special handling for high priority issues
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Reports for high priority issues need special handling.

**Severe issues**: make sure the subject or ticket title as well as the first
paragraph makes the severeness obvious.

**Regressions**: make the report's subject start with '[REGRESSION]'.

In case you performed a successful bisection, use the title of the change that
introduced the regression as the second part of your subject. Make the report
also mention the commit id of the culprit. In case of an unsuccessful bisection,
make your report mention the latest tested version that's working fine (say 5.7)
and the oldest where the issue occurs (say 5.8-rc1).

When sending the report by mail, CC the Linux regressions mailing list
(regressions@lists.linux.dev). In case the report needs to be filed to some web
tracker, proceed to do so. Once filed, forward the report by mail to the
regressions list; CC the maintainer and the mailing list for the subsystem in
question. Make sure to inline the forwarded report, hence do not attach it.
Also add a short note at the top where you mention the URL to the ticket.

When mailing or forwarding the report, in case of a successful bisection add the
author of the culprit to the recipients; also CC everyone in the signed-off-by
chain, which you find at the end of its commit message.

**Security issues**: for these issues your will have to evaluate if a
short-term risk to other users would arise if details were publicly disclosed.
If that's not the case simply proceed with reporting the issue as described.
For issues that bear such a risk you will need to adjust the reporting process
slightly:

 * If the MAINTAINERS file instructed you to report the issue by mail, do not
   CC any public mailing lists.

 * If you were supposed to file the issue in a bug tracker make sure to mark
   the ticket as 'private' or 'security issue'. If the bug tracker does not
   offer a way to keep reports private, forget about it and send your report as
   a private mail to the maintainers instead.

In both cases make sure to also mail your report to the addresses the
MAINTAINERS file lists in the section 'security contact'. Ideally directly CC
them when sending the report by mail. If you filed it in a bug tracker, forward
the report's text to these addresses; but on top of it put a small note where
you mention that you filed it with a link to the ticket.

See Documentation/process/security-bugs.rst for more information.


Duties after the report went out
--------------------------------

    *Wait for reactions and keep the thing rolling until you can accept the
    outcome in one way or the other. Thus react publicly and in a timely manner
    to any inquiries. Test proposed fixes. Do proactive testing: retest with at
    least every first release candidate (RC) of a new mainline version and
    report your results. Send friendly reminders if things stall. And try to
    help yourself, if you don't get any help or if it's unsatisfying.*

If your report was good and you are really lucky then one of the developers
might immediately spot what's causing the issue; they then might write a patch
to fix it, test it, and send it straight for integration in mainline while
tagging it for later backport to stable and longterm kernels that need it. Then
all you need to do is reply with a 'Thank you very much' and switch to a version
with the fix once it gets released.

But this ideal scenario rarely happens. That's why the job is only starting
once you got the report out. What you'll have to do depends on the situations,
but often it will be the things listed below. But before digging into the
details, here are a few important things you need to keep in mind for this part
of the process.


General advice for further interactions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

**Always reply in public**: When you filed the issue in a bug tracker, always
reply there and do not contact any of the developers privately about it. For
mailed reports always use the 'Reply-all' function when replying to any mails
you receive. That includes mails with any additional data you might want to add
to your report: go to your mail applications 'Sent' folder and use 'reply-all'
on your mail with the report. This approach will make sure the public mailing
list(s) and everyone else that gets involved over time stays in the loop; it
also keeps the mail thread intact, which among others is really important for
mailing lists to group all related mails together.

There are just two situations where a comment in a bug tracker or a 'Reply-all'
is unsuitable:

 * Someone tells you to send something privately.

 * You were told to send something, but noticed it contains sensitive
   information that needs to be kept private. In that case it's okay to send it
   in private to the developer that asked for it. But note in the ticket or a
   mail that you did that, so everyone else knows you honored the request.

**Do research before asking for clarifications or help**: In this part of the
process someone might tell you to do something that requires a skill you might
not have mastered yet. For example, you might be asked to use some test tools
you never have heard of yet; or you might be asked to apply a patch to the
Linux kernel sources to test if it helps. In some cases it will be fine sending
a reply asking for instructions how to do that. But before going that route try
to find the answer own your own by searching the internet; alternatively
consider asking in other places for advice. For example ask a friend or post
about it to a chatroom or forum you normally hang out.

**Be patient**: If you are really lucky you might get a reply to your report
within a few hours. But most of the time it will take longer, as maintainers
are scattered around the globe and thus might be in a different time zone – one
where they already enjoy their night away from keyboard.

In general, kernel developers will take one to five business days to respond to
reports. Sometimes it will take longer, as they might be busy with the merge
windows, other work, visiting developer conferences, or simply enjoying a long
summer holiday.

The 'issues of high priority' (see above for an explanation) are an exception
here: maintainers should address them as soon as possible; that's why you
should wait a week at maximum (or just two days if it's something urgent)
before sending a friendly reminder.

Sometimes the maintainer might not be responding in a timely manner; other
times there might be disagreements, for example if an issue qualifies as
regression or not. In such cases raise your concerns on the mailing list and
ask others for public or private replies how to move on. If that fails, it
might be appropriate to get a higher authority involved. In case of a WiFi
driver that would be the wireless maintainers; if there are no higher level
maintainers or all else fails, it might be one of those rare situations where
it's okay to get Linus Torvalds involved.

**Proactive testing**: Every time the first pre-release (the 'rc1') of a new
mainline kernel version gets released, go and check if the issue is fixed there
or if anything of importance changed. Mention the outcome in the ticket or in a
mail you sent as reply to your report (make sure it has all those in the CC
that up to that point participated in the discussion). This will show your
commitment and that you are willing to help. It also tells developers if the
issue persists and makes sure they do not forget about it. A few other
occasional retests (for example with rc3, rc5 and the final) are also a good
idea, but only report your results if something relevant changed or if you are
writing something anyway.

With all these general things off the table let's get into the details of how
to help to get issues resolved once they were reported.

Inquires and testing request
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Here are your duties in case you got replies to your report:

**Check who you deal with**: Most of the time it will be the maintainer or a
developer of the particular code area that will respond to your report. But as
issues are normally reported in public it could be anyone that's replying —
including people that want to help, but in the end might guide you totally off
track with their questions or requests. That rarely happens, but it's one of
many reasons why it's wise to quickly run an internet search to see who you're
interacting with. By doing this you also get aware if your report was heard by
the right people, as a reminder to the maintainer (see below) might be in order
later if discussion fades out without leading to a satisfying solution for the
issue.

**Inquiries for data**: Often you will be asked to test something or provide
additional details. Try to provide the requested information soon, as you have
the attention of someone that might help and risk losing it the longer you
wait; that outcome is even likely if you do not provide the information within
a few business days.

**Requests for testing**: When you are asked to test a diagnostic patch or a
possible fix, try to test it in timely manner, too. But do it properly and make
sure to not rush it: mixing things up can happen easily and can lead to a lot
of confusion for everyone involved. A common mistake for example is thinking a
proposed patch with a fix was applied, but in fact wasn't. Things like that
happen even to experienced testers occasionally, but they most of the time will
notice when the kernel with the fix behaves just as one without it.

What to do when nothing of substance happens
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Some reports will not get any reaction from the responsible Linux kernel
developers; or a discussion around the issue evolved, but faded out with
nothing of substance coming out of it.

In these cases wait two (better: three) weeks before sending a friendly
reminder: maybe the maintainer was just away from keyboard for a while when
your report arrived or had something more important to take care of. When
writing the reminder, kindly ask if anything else from your side is needed to
get the ball running somehow. If the report got out by mail, do that in the
first lines of a mail that is a reply to your initial mail (see above) which
includes a full quote of the original report below: that's on of those few
situations where such a 'TOFU' (Text Over, Fullquote Under) is the right
approach, as then all the recipients will have the details at hand immediately
in the proper order.

After the reminder wait three more weeks for replies. If you still don't get a
proper reaction, you first should reconsider your approach. Did you maybe try
to reach out to the wrong people? Was the report maybe offensive or so
confusing that people decided to completely stay away from it? The best way to
rule out such factors: show the report to one or two people familiar with FLOSS
issue reporting and ask for their opinion. Also ask them for their advice how
to move forward. That might mean: prepare a better report and make those people
review it before you send it out. Such an approach is totally fine; just
mention that this is the second and improved report on the issue and include a
link to the first report.

If the report was proper you can send a second reminder; in it ask for advice
why the report did not get any replies. A good moment for this second reminder
mail is shortly after the first pre-release (the 'rc1') of a new Linux kernel
version got published, as you should retest and provide a status update at that
point anyway (see above).

If the second reminder again results in no reaction within a week, try to
contact a higher-level maintainer asking for advice: even busy maintainers by
then should at least have sent some kind of acknowledgment.

Remember to prepare yourself for a disappointment: maintainers ideally should
react somehow to every issue report, but they are only obliged to fix those
'issues of high priority' outlined earlier. So don't be too devastating if you
get a reply along the lines of 'thanks for the report, I have more important
issues to deal with currently and won't have time to look into this for the
foreseeable future'.

It's also possible that after some discussion in the bug tracker or on a list
nothing happens anymore and reminders don't help to motivate anyone to work out
a fix. Such situations can be devastating, but is within the cards when it
comes to Linux kernel development. This and several other reasons for not
getting help are explained in 'Why some issues won't get any reaction or remain
unfixed after being reported' near the end of this document.

Don't get devastated if you don't find any help or if the issue in the end does
not get solved: the Linux kernel is FLOSS and thus you can still help yourself.
You for example could try to find others that are affected and team up with
them to get the issue resolved. Such a team could prepare a fresh report
together that mentions how many you are and why this is something that in your
option should get fixed. Maybe together you can also narrow down the root cause
or the change that introduced a regression, which often makes developing a fix
easier. And with a bit of luck there might be someone in the team that knows a
bit about programming and might be able to write a fix.


Reference for "Reporting regressions within a stable and longterm kernel line"
------------------------------------------------------------------------------

This subsection provides details for the steps you need to perform if you face
a regression within a stable and longterm kernel line.

Make sure the particular version line still gets support
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    *Check if the kernel developers still maintain the Linux kernel version
    line you care about: go to the front page of kernel.org and make sure it
    mentions the latest release of the particular version line without an
    '[EOL]' tag.*

Most kernel version lines only get supported for about three months, as
maintaining them longer is quite a lot of work. Hence, only one per year is
chosen and gets supported for at least two years (often six). That's why you
need to check if the kernel developers still support the version line you care
for.

Note, if kernel.org lists two stable version lines on the front page, you
should consider switching to the newer one and forget about the older one:
support for it is likely to be abandoned soon. Then it will get a "end-of-life"
(EOL) stamp. Version lines that reached that point still get mentioned on the
kernel.org front page for a week or two, but are unsuitable for testing and
reporting.

Search stable mailing list
~~~~~~~~~~~~~~~~~~~~~~~~~~

    *Check the archives of the Linux stable mailing list for existing reports.*

Maybe the issue you face is already known and was fixed or is about to. Hence,
`search the archives of the Linux stable mailing list
<https://lore.kernel.org/stable/>`_ for reports about an issue like yours. If
you find any matches, consider joining the discussion, unless the fix is
already finished and scheduled to get applied soon.

Reproduce issue with the newest release
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    *Install the latest release from the particular version line as a vanilla
    kernel. Ensure this kernel is not tainted and still shows the problem, as
    the issue might have already been fixed there. If you first noticed the
    problem with a vendor kernel, check a vanilla build of the last version
    known to work performs fine as well.*

Before investing any more time in this process you want to check if the issue
was already fixed in the latest release of version line you're interested in.
This kernel needs to be vanilla and shouldn't be tainted before the issue
happens, as detailed outlined already above in the section "Install a fresh
kernel for testing".

Did you first notice the regression with a vendor kernel? Then changes the
vendor applied might be interfering. You need to rule that out by performing
a recheck. Say something broke when you updated from 5.10.4-vendor.42 to
5.10.5-vendor.43. Then after testing the latest 5.10 release as outlined in
the previous paragraph check if a vanilla build of Linux 5.10.4 works fine as
well. If things are broken there, the issue does not qualify as upstream
regression and you need switch back to the main step-by-step guide to report
the issue.

Report the regression
~~~~~~~~~~~~~~~~~~~~~

    *Send a short problem report to the Linux stable mailing list
    (stable@vger.kernel.org) and CC the Linux regressions mailing list
    (regressions@lists.linux.dev); if you suspect the cause in a particular
    subsystem, CC its maintainer and its mailing list. Roughly describe the
    issue and ideally explain how to reproduce it. Mention the first version
    that shows the problem and the last version that's working fine. Then
    wait for further instructions.*

When reporting a regression that happens within a stable or longterm kernel
line (say when updating from 5.10.4 to 5.10.5) a brief report is enough for
the start to get the issue reported quickly. Hence a rough description to the
stable and regressions mailing list is all it takes; but in case you suspect
the cause in a particular subsystem, CC its maintainers and its mailing list
as well, because that will speed things up.

And note, it helps developers a great deal if you can specify the exact version
that introduced the problem. Hence if possible within a reasonable time frame,
try to find that version using vanilla kernels. Let's assume something broke when
your distributor released a update from Linux kernel 5.10.5 to 5.10.8. Then as
instructed above go and check the latest kernel from that version line, say
5.10.9. If it shows the problem, try a vanilla 5.10.5 to ensure that no patches
the distributor applied interfere. If the issue doesn't manifest itself there,
try 5.10.7 and then (depending on the outcome) 5.10.8 or 5.10.6 to find the
first version where things broke. Mention it in the report and state that 5.10.9
is still broken.

What the previous paragraph outlines is basically a rough manual 'bisection'.
Once your report is out your might get asked to do a proper one, as it allows to
pinpoint the exact change that causes the issue (which then can easily get
reverted to fix the issue quickly). Hence consider to do a proper bisection
right away if time permits. See the section 'Special care for regressions' and
the document Documentation/admin-guide/bug-bisect.rst for details how to
perform one. In case of a successful bisection add the author of the culprit to
the recipients; also CC everyone in the signed-off-by chain, which you find at
the end of its commit message.


Reference for "Reporting issues only occurring in older kernel version lines"
-----------------------------------------------------------------------------

This section provides details for the steps you need to take if you could not
reproduce your issue with a mainline kernel, but want to see it fixed in older
version lines (aka stable and longterm kernels).

Some fixes are too complex
~~~~~~~~~~~~~~~~~~~~~~~~~~

    *Prepare yourself for the possibility that going through the next few steps
    might not get the issue solved in older releases: the fix might be too big
    or risky to get backported there.*

Even small and seemingly obvious code-changes sometimes introduce new and
totally unexpected problems. The maintainers of the stable and longterm kernels
are very aware of that and thus only apply changes to these kernels that are
within rules outlined in Documentation/process/stable-kernel-rules.rst.

Complex or risky changes for example do not qualify and thus only get applied
to mainline. Other fixes are easy to get backported to the newest stable and
longterm kernels, but too risky to integrate into older ones. So be aware the
fix you are hoping for might be one of those that won't be backported to the
version line your care about. In that case you'll have no other choice then to
live with the issue or switch to a newer Linux version, unless you want to
patch the fix into your kernels yourself.

Common preparations
~~~~~~~~~~~~~~~~~~~

    *Perform the first three steps in the section "Reporting issues only
    occurring in older kernel version lines" above.*

You need to carry out a few steps already described in another section of this
guide. Those steps will let you:

 * Check if the kernel developers still maintain the Linux kernel version line
   you care about.

 * Search the Linux stable mailing list for exiting reports.

 * Check with the latest release.


Check code history and search for existing discussions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    *Search the Linux kernel version control system for the change that fixed
    the issue in mainline, as its commit message might tell you if the fix is
    scheduled for backporting already. If you don't find anything that way,
    search the appropriate mailing lists for posts that discuss such an issue
    or peer-review possible fixes; then check the discussions if the fix was
    deemed unsuitable for backporting. If backporting was not considered at
    all, join the newest discussion, asking if it's in the cards.*

In a lot of cases the issue you deal with will have happened with mainline, but
got fixed there. The commit that fixed it would need to get backported as well
to get the issue solved. That's why you want to search for it or any
discussions abound it.

 * First try to find the fix in the Git repository that holds the Linux kernel
   sources. You can do this with the web interfaces `on kernel.org
   <https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/>`_
   or its mirror `on GitHub <https://github.com/torvalds/linux>`_; if you have
   a local clone you alternatively can search on the command line with ``git
   log --grep=<pattern>``.

   If you find the fix, look if the commit message near the end contains a
   'stable tag' that looks like this:

          Cc: <stable@vger.kernel.org> # 5.4+

   If that's case the developer marked the fix safe for backporting to version
   line 5.4 and later. Most of the time it's getting applied there within two
   weeks, but sometimes it takes a bit longer.

 * If the commit doesn't tell you anything or if you can't find the fix, look
   again for discussions about the issue. Search the net with your favorite
   internet search engine as well as the archives for the `Linux kernel
   developers mailing list <https://lore.kernel.org/lkml/>`_. Also read the
   section `Locate kernel area that causes the issue` above and follow the
   instructions to find the subsystem in question: its bug tracker or mailing
   list archive might have the answer you are looking for.

 * If you see a proposed fix, search for it in the version control system as
   outlined above, as the commit might tell you if a backport can be expected.

   * Check the discussions for any indicators the fix might be too risky to get
     backported to the version line you care about. If that's the case you have
     to live with the issue or switch to the kernel version line where the fix
     got applied.

   * If the fix doesn't contain a stable tag and backporting was not discussed,
     join the discussion: mention the version where you face the issue and that
     you would like to see it fixed, if suitable.


Ask for advice
~~~~~~~~~~~~~~

    *One of the former steps should lead to a solution. If that doesn't work
    out, ask the maintainers for the subsystem that seems to be causing the
    issue for advice; CC the mailing list for the particular subsystem as well
    as the stable mailing list.*

If the previous three steps didn't get you closer to a solution there is only
one option left: ask for advice. Do that in a mail you sent to the maintainers
for the subsystem where the issue seems to have its roots; CC the mailing list
for the subsystem as well as the stable mailing list (stable@vger.kernel.org).


Why some issues won't get any reaction or remain unfixed after being reported
=============================================================================

When reporting a problem to the Linux developers, be aware only 'issues of high
priority' (regressions, security issues, severe problems) are definitely going
to get resolved. The maintainers or if all else fails Linus Torvalds himself
will make sure of that. They and the other kernel developers will fix a lot of
other issues as well. But be aware that sometimes they can't or won't help; and
sometimes there isn't even anyone to send a report to.

This is best explained with kernel developers that contribute to the Linux
kernel in their spare time. Quite a few of the drivers in the kernel were
written by such programmers, often because they simply wanted to make their
hardware usable on their favorite operating system.

These programmers most of the time will happily fix problems other people
report. But nobody can force them to do, as they are contributing voluntarily.

Then there are situations where such developers really want to fix an issue,
but can't: sometimes they lack hardware programming documentation to do so.
This often happens when the publicly available docs are superficial or the
driver was written with the help of reverse engineering.

Sooner or later spare time developers will also stop caring for the driver.
Maybe their test hardware broke, got replaced by something more fancy, or is so
old that it's something you don't find much outside of computer museums
anymore. Sometimes developer stops caring for their code and Linux at all, as
something different in their life became way more important. In some cases
nobody is willing to take over the job as maintainer – and nobody can be forced
to, as contributing to the Linux kernel is done on a voluntary basis. Abandoned
drivers nevertheless remain in the kernel: they are still useful for people and
removing would be a regression.

The situation is not that different with developers that are paid for their
work on the Linux kernel. Those contribute most changes these days. But their
employers sooner or later also stop caring for their code or make its
programmer focus on other things. Hardware vendors for example earn their money
mainly by selling new hardware; quite a few of them hence are not investing
much time and energy in maintaining a Linux kernel driver for something they
stopped selling years ago. Enterprise Linux distributors often care for a
longer time period, but in new versions often leave support for old and rare
hardware aside to limit the scope. Often spare time contributors take over once
a company orphans some code, but as mentioned above: sooner or later they will
leave the code behind, too.

Priorities are another reason why some issues are not fixed, as maintainers
quite often are forced to set those, as time to work on Linux is limited.
That's true for spare time or the time employers grant their developers to
spend on maintenance work on the upstream kernel. Sometimes maintainers also
get overwhelmed with reports, even if a driver is working nearly perfectly. To
not get completely stuck, the programmer thus might have no other choice than
to prioritize issue reports and reject some of them.

But don't worry too much about all of this, a lot of drivers have active
maintainers who are quite interested in fixing as many issues as possible.


Closing words
=============

Compared with other Free/Libre & Open Source Software it's hard to report
issues to the Linux kernel developers: the length and complexity of this
document and the implications between the lines illustrate that. But that's how
it is for now. The main author of this text hopes documenting the state of the
art will lay some groundwork to improve the situation over time.


..
   end-of-content
..
   This document is maintained by Thorsten Leemhuis <linux@leemhuis.info>. If
   you spot a typo or small mistake, feel free to let him know directly and
   he'll fix it. You are free to do the same in a mostly informal way if you
   want to contribute changes to the text, but for copyright reasons please CC
   linux-doc@vger.kernel.org and "sign-off" your contribution as
   Documentation/process/submitting-patches.rst outlines in the section "Sign
   your work - the Developer's Certificate of Origin".
..
   This text is available under GPL-2.0+ or CC-BY-4.0, as stated at the top
   of the file. If you want to distribute this text under CC-BY-4.0 only,
   please use "The Linux kernel developers" for author attribution and link
   this as source:
   https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/plain/Documentation/admin-guide/reporting-issues.rst
..
   Note: Only the content of this RST file as found in the Linux kernel sources
   is available under CC-BY-4.0, as versions of this text that were processed
   (for example by the kernel's build system) might contain content taken from
   files which use a more restrictive license.

---

### Documentation Admin Guide Reporting Regressions (`Documentation/admin-guide/reporting-regressions.rst`)

.. SPDX-License-Identifier: (GPL-2.0+ OR CC-BY-4.0)
.. [see the bottom of this file for redistribution information]

Reporting regressions
+++++++++++++++++++++

"*We don't cause regressions*" is the first rule of Linux kernel development;
Linux founder and lead developer Linus Torvalds established it himself and
ensures it's obeyed.

This document describes what the rule means for users and how the Linux kernel's
development model ensures to address all reported regressions; aspects relevant
for kernel developers are left to Documentation/process/handling-regressions.rst.


The important bits (aka "TL;DR")
================================

#. It's a regression if something running fine with one Linux kernel works worse
   or not at all with a newer version. Note, the newer kernel has to be compiled
   using a similar configuration; the detailed explanations below describes this
   and other fine print in more detail.

#. Report your issue as outlined in Documentation/admin-guide/reporting-issues.rst,
   it already covers all aspects important for regressions and repeated
   below for convenience. Two of them are important: start your report's subject
   with "[REGRESSION]" and CC or forward it to `the regression mailing list
   <https://lore.kernel.org/regressions/>`_ (regressions@lists.linux.dev).

#. Optional, but recommended: when sending or forwarding your report, make the
   Linux kernel regression tracking bot "regzbot" track the issue by specifying
   when the regression started like this::

       #regzbot introduced: v5.13..v5.14-rc1


All the details on Linux kernel regressions relevant for users
==============================================================


The important basics
--------------------


What is a "regression" and what is the "no regressions" rule?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

It's a regression if some application or practical use case running fine with
one Linux kernel works worse or not at all with a newer version compiled using a
similar configuration. The "no regressions" rule forbids this to take place; if
it happens by accident, developers that caused it are expected to quickly fix
the issue.

It thus is a regression when a WiFi driver from Linux 5.13 works fine, but with
5.14 doesn't work at all, works significantly slower, or misbehaves somehow.
It's also a regression if a perfectly working application suddenly shows erratic
behavior with a newer kernel version; such issues can be caused by changes in
procfs, sysfs, or one of the many other interfaces Linux provides to userland
software. But keep in mind, as mentioned earlier: 5.14 in this example needs to
be built from a configuration similar to the one from 5.13. This can be achieved
using ``make olddefconfig``, as explained in more detail below.

Note the "practical use case" in the first sentence of this section: developers
despite the "no regressions" rule are free to change any aspect of the kernel
and even APIs or ABIs to userland, as long as no existing application or use
case breaks.

Also be aware the "no regressions" rule covers only interfaces the kernel
provides to the userland. It thus does not apply to kernel-internal interfaces
like the module API, which some externally developed drivers use to hook into
the kernel.

How do I report a regression?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Just report the issue as outlined in
Documentation/admin-guide/reporting-issues.rst, it already describes the
important points. The following aspects outlined there are especially relevant
for regressions:

 * When checking for existing reports to join, also search the `archives of the
   Linux regressions mailing list <https://lore.kernel.org/regressions/>`_ and
   `regzbot's web-interface <https://linux-regtracking.leemhuis.info/regzbot/>`_.

 * Start your report's subject with "[REGRESSION]".

 * In your report, clearly mention the last kernel version that worked fine and
   the first broken one. Ideally try to find the exact change causing the
   regression using a bisection, as explained below in more detail.

 * Remember to let the Linux regressions mailing list
   (regressions@lists.linux.dev) know about your report:

   * If you report the regression by mail, CC the regressions list.

   * If you report your regression to some bug tracker, forward the submitted
     report by mail to the regressions list while CCing the maintainer and the
     mailing list for the subsystem in question.

   If it's a regression within a stable or longterm series (e.g.
   v5.15.3..v5.15.5), remember to CC the `Linux stable mailing list
   <https://lore.kernel.org/stable/>`_ (stable@vger.kernel.org).

  In case you performed a successful bisection, add everyone to the CC the
  culprit's commit message mentions in lines starting with "Signed-off-by:".

When CCing for forwarding your report to the list, consider directly telling the
aforementioned Linux kernel regression tracking bot about your report. To do
that, include a paragraph like this in your mail::

       #regzbot introduced: v5.13..v5.14-rc1

Regzbot will then consider your mail a report for a regression introduced in the
specified version range. In above case Linux v5.13 still worked fine and Linux
v5.14-rc1 was the first version where you encountered the issue. If you
performed a bisection to find the commit that caused the regression, specify the
culprit's commit-id instead::

       #regzbot introduced: 1f2e3d4c5d

Placing such a "regzbot command" is in your interest, as it will ensure the
report won't fall through the cracks unnoticed. If you omit this, the Linux
kernel's regressions tracker will take care of telling regzbot about your
regression, as long as you send a copy to the regressions mailing lists. But the
regression tracker is just one human which sometimes has to rest or occasionally
might even enjoy some time away from computers (as crazy as that might sound).
Relying on this person thus will result in an unnecessary delay before the
regressions becomes mentioned `on the list of tracked and unresolved Linux
kernel regressions <https://linux-regtracking.leemhuis.info/regzbot/>`_ and the
weekly regression reports sent by regzbot. Such delays can result in Linus
Torvalds being unaware of important regressions when deciding between "continue
development or call this finished and release the final?".

Are really all regressions fixed?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Nearly all of them are, as long as the change causing the regression (the
"culprit commit") is reliably identified. Some regressions can be fixed without
this, but often it's required.

Who needs to find the root cause of a regression?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Developers of the affected code area should try to locate the culprit on their
own. But for them that's often impossible to do with reasonable effort, as quite
a lot of issues only occur in a particular environment outside the developer's
reach -- for example, a specific hardware platform, firmware, Linux distro,
system's configuration, or application. That's why in the end it's often up to
the reporter to locate the culprit commit; sometimes users might even need to
run additional tests afterwards to pinpoint the exact root cause. Developers
should offer advice and reasonably help where they can, to make this process
relatively easy and achievable for typical users.

How can I find the culprit?
~~~~~~~~~~~~~~~~~~~~~~~~~~~

Perform a bisection, as roughly outlined in
Documentation/admin-guide/reporting-issues.rst and described in more detail by
Documentation/admin-guide/bug-bisect.rst. It might sound like a lot of work, but
in many cases finds the culprit relatively quickly. If it's hard or
time-consuming to reliably reproduce the issue, consider teaming up with other
affected users to narrow down the search range together.

Who can I ask for advice when it comes to regressions?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Send a mail to the regressions mailing list (regressions@lists.linux.dev) while
CCing the Linux kernel's regression tracker (regressions@leemhuis.info); if the
issue might better be dealt with in private, feel free to omit the list.


Additional details about regressions
------------------------------------


What is the goal of the "no regressions" rule?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Users should feel safe when updating kernel versions and not have to worry
something might break. This is in the interest of the kernel developers to make
updating attractive: they don't want users to stay on stable or longterm Linux
series that are either abandoned or more than one and a half years old. That's
in everybody's interest, as `those series might have known bugs, security
issues, or other problematic aspects already fixed in later versions
<http://www.kroah.com/log/blog/2018/08/24/what-stable-kernel-should-i-use/>`_.
Additionally, the kernel developers want to make it simple and appealing for
users to test the latest pre-release or regular release. That's also in
everybody's interest, as it's a lot easier to track down and fix problems, if
they are reported shortly after being introduced.

Is the "no regressions" rule really adhered in practice?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

It's taken really seriously, as can be seen by many mailing list posts from
Linux creator and lead developer Linus Torvalds, some of which are quoted in
Documentation/process/handling-regressions.rst.

Exceptions to this rule are extremely rare; in the past developers almost always
turned out to be wrong when they assumed a particular situation was warranting
an exception.

Who ensures the "no regressions" rule is actually followed?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The subsystem maintainers should take care of that, which are watched and
supported by the tree maintainers -- e.g. Linus Torvalds for mainline and
Greg Kroah-Hartman et al. for various stable/longterm series.

All of them are helped by people trying to ensure no regression report falls
through the cracks. One of them is Thorsten Leemhuis, who's currently acting as
the Linux kernel's "regressions tracker"; to facilitate this work he relies on
regzbot, the Linux kernel regression tracking bot. That's why you want to bring
your report on the radar of these people by CCing or forwarding each report to
the regressions mailing list, ideally with a "regzbot command" in your mail to
get it tracked immediately.

How quickly are regressions normally fixed?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Developers should fix any reported regression as quickly as possible, to provide
affected users with a solution in a timely manner and prevent more users from
running into the issue; nevertheless developers need to take enough time and
care to ensure regression fixes do not cause additional damage.

The answer thus depends on various factors like the impact of a regression, its
age, or the Linux series in which it occurs. In the end though, most regressions
should be fixed within two weeks.

Is it a regression, if the issue can be avoided by updating some software?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Almost always: yes. If a developer tells you otherwise, ask the regression
tracker for advice as outlined above.

Is it a regression, if a newer kernel works slower or consumes more energy?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Yes, but the difference has to be significant. A five percent slow-down in a
micro-benchmark thus is unlikely to qualify as regression, unless it also
influences the results of a broad benchmark by more than one percent. If in
doubt, ask for advice.

Is it a regression, if an external kernel module breaks when updating Linux?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

No, as the "no regression" rule is about interfaces and services the Linux
kernel provides to the userland. It thus does not cover building or running
externally developed kernel modules, as they run in kernel-space and hook into
the kernel using internal interfaces occasionally changed.

How are regressions handled that are caused by security fixes?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

In extremely rare situations security issues can't be fixed without causing
regressions; those fixes are given way, as they are the lesser evil in the end.
Luckily this middling almost always can be avoided, as key developers for the
affected area and often Linus Torvalds himself try very hard to fix security
issues without causing regressions.

If you nevertheless face such a case, check the mailing list archives if people
tried their best to avoid the regression. If not, report it; if in doubt, ask
for advice as outlined above.

What happens if fixing a regression is impossible without causing another?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Sadly these things happen, but luckily not very often; if they occur, expert
developers of the affected code area should look into the issue to find a fix
that avoids regressions or at least their impact. If you run into such a
situation, do what was outlined already for regressions caused by security
fixes: check earlier discussions if people already tried their best and ask for
advice if in doubt.

A quick note while at it: these situations could be avoided, if people would
regularly give mainline pre-releases (say v5.15-rc1 or -rc3) from each
development cycle a test run. This is best explained by imagining a change
integrated between Linux v5.14 and v5.15-rc1 which causes a regression, but at
the same time is a hard requirement for some other improvement applied for
5.15-rc1. All these changes often can simply be reverted and the regression thus
solved, if someone finds and reports it before 5.15 is released. A few days or
weeks later this solution can become impossible, as some software might have
started to rely on aspects introduced by one of the follow-up changes: reverting
all changes would then cause a regression for users of said software and thus is
out of the question.

Is it a regression, if some feature I relied on was removed months ago?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

It is, but often it's hard to fix such regressions due to the aspects outlined
in the previous section. It hence needs to be dealt with on a case-by-case
basis. This is another reason why it's in everybody's interest to regularly test
mainline pre-releases.

Does the "no regression" rule apply if I seem to be the only affected person?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

It does, but only for practical usage: the Linux developers want to be free to
remove support for hardware only to be found in attics and museums anymore.

Note, sometimes regressions can't be avoided to make progress -- and the latter
is needed to prevent Linux from stagnation. Hence, if only very few users seem
to be affected by a regression, it for the greater good might be in their and
everyone else's interest to lettings things pass. Especially if there is an
easy way to circumvent the regression somehow, for example by updating some
software or using a kernel parameter created just for this purpose.

Does the regression rule apply for code in the staging tree as well?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Not according to the `help text for the configuration option covering all
staging code <https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/drivers/staging/Kconfig>`_,
which since its early days states::

       Please note that these drivers are under heavy development, may or
       may not work, and may contain userspace interfaces that most likely
       will be changed in the near future.

The staging developers nevertheless often adhere to the "no regressions" rule,
but sometimes bend it to make progress. That's for example why some users had to
deal with (often negligible) regressions when a WiFi driver from the staging
tree was replaced by a totally different one written from scratch.

Why do later versions have to be "compiled with a similar configuration"?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Because the Linux kernel developers sometimes integrate changes known to cause
regressions, but make them optional and disable them in the kernel's default
configuration. This trick allows progress, as the "no regressions" rule
otherwise would lead to stagnation.

Consider for example a new security feature blocking access to some kernel
interfaces often abused by malware, which at the same time are required to run a
few rarely used applications. The outlined approach makes both camps happy:
people using these applications can leave the new security feature off, while
everyone else can enable it without running into trouble.

How to create a configuration similar to the one of an older kernel?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Start your machine with a known-good kernel and configure the newer Linux
version with ``make olddefconfig``. This makes the kernel's build scripts pick
up the configuration file (the ".config" file) from the running kernel as base
for the new one you are about to compile; afterwards they set all new
configuration options to their default value, which should disable new features
that might cause regressions.

Can I report a regression I found with pre-compiled vanilla kernels?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

You need to ensure the newer kernel was compiled with a similar configuration
file as the older one (see above), as those that built them might have enabled
some known-to-be incompatible feature for the newer kernel. If in doubt, report
the matter to the kernel's provider and ask for advice.


More about regression tracking with "regzbot"
---------------------------------------------

What is regression tracking and why should I care about it?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Rules like "no regressions" need someone to ensure they are followed, otherwise
they are broken either accidentally or on purpose. History has shown this to be
true for Linux kernel development as well. That's why Thorsten Leemhuis, the
Linux Kernel's regression tracker, and some people try to ensure all regression
are fixed by keeping an eye on them until they are resolved. Neither of them are
paid for this, that's why the work is done on a best effort basis.

Why and how are Linux kernel regressions tracked using a bot?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Tracking regressions completely manually has proven to be quite hard due to the
distributed and loosely structured nature of Linux kernel development process.
That's why the Linux kernel's regression tracker developed regzbot to facilitate
the work, with the long term goal to automate regression tracking as much as
possible for everyone involved.

Regzbot works by watching for replies to reports of tracked regressions.
Additionally, it's looking out for posted or committed patches referencing such
reports with "Link:" tags; replies to such patch postings are tracked as well.
Combined this data provides good insights into the current state of the fixing
process.

How to see which regressions regzbot tracks currently?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Check out `regzbot's web-interface <https://linux-regtracking.leemhuis.info/regzbot/>`_.

What kind of issues are supposed to be tracked by regzbot?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The bot is meant to track regressions, hence please don't involve regzbot for
regular issues. But it's okay for the Linux kernel's regression tracker if you
involve regzbot to track severe issues, like reports about hangs, corrupted
data, or internal errors (Panic, Oops, BUG(), warning, ...).

How to change aspects of a tracked regression?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

By using a 'regzbot command' in a direct or indirect reply to the mail with the
report. The easiest way to do that: find the report in your "Sent" folder or the
mailing list archive and reply to it using your mailer's "Reply-all" function.
In that mail, use one of the following commands in a stand-alone paragraph (IOW:
use blank lines to separate one or multiple of these commands from the rest of
the mail's text).

 * Update when the regression started to happen, for example after performing a
   bisection::

       #regzbot introduced: 1f2e3d4c5d

 * Set or update the title::

       #regzbot title: foo

 * Monitor a discussion or bugzilla.kernel.org ticket where additions aspects of
   the issue or a fix are discussed:::

       #regzbot monitor: https://lore.kernel.org/r/30th.anniversary.repost@klaava.Helsinki.FI/
       #regzbot monitor: https://bugzilla.kernel.org/show_bug.cgi?id=123456789

 * Point to a place with further details of interest, like a mailing list post
   or a ticket in a bug tracker that are slightly related, but about a different
   topic::

       #regzbot link: https://bugzilla.kernel.org/show_bug.cgi?id=123456789

 * Mark a regression as invalid::

       #regzbot invalid: wasn't a regression, problem has always existed

Regzbot supports a few other commands primarily used by developers or people
tracking regressions. They and more details about the aforementioned regzbot
commands can be found in the `getting started guide
<https://gitlab.com/knurd42/regzbot/-/blob/main/docs/getting_started.md>`_ and
the `reference documentation <https://gitlab.com/knurd42/regzbot/-/blob/main/docs/reference.md>`_
for regzbot.

..
   end-of-content
..
   This text is available under GPL-2.0+ or CC-BY-4.0, as stated at the top
   of the file. If you want to distribute this text under CC-BY-4.0 only,
   please use "The Linux kernel developers" for author attribution and link
   this as source:
   https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/plain/Documentation/admin-guide/reporting-regressions.rst
..
   Note: Only the content of this RST file as found in the Linux kernel sources
   is available under CC-BY-4.0, as versions of this text that were processed
   (for example by the kernel's build system) might contain content taken from
   files which use a more restrictive license.

---

### Documentation Admin Guide Rtc (`Documentation/admin-guide/rtc.rst`)

=======================================
Real Time Clock (RTC) Drivers for Linux
=======================================

When Linux developers talk about a "Real Time Clock", they usually mean
something that tracks wall clock time and is battery backed so that it
works even with system power off.  Such clocks will normally not track
the local time zone or daylight savings time -- unless they dual boot
with MS-Windows -- but will instead be set to Coordinated Universal Time
(UTC, formerly "Greenwich Mean Time").

The newest non-PC hardware tends to just count seconds, like the time(2)
system call reports, but RTCs also very commonly represent time using
the Gregorian calendar and 24 hour time, as reported by gmtime(3).

Linux has two largely-compatible userspace RTC API families you may
need to know about:

    *	/dev/rtc ... is the RTC provided by PC compatible systems,
	so it's not very portable to non-x86 systems.

    *	/dev/rtc0, /dev/rtc1 ... are part of a framework that's
	supported by a wide variety of RTC chips on all systems.

Programmers need to understand that the PC/AT functionality is not
always available, and some systems can do much more.  That is, the
RTCs use the same API to make requests in both RTC frameworks (using
different filenames of course), but the hardware may not offer the
same functionality.  For example, not every RTC is hooked up to an
IRQ, so they can't all issue alarms; and where standard PC RTCs can
only issue an alarm up to 24 hours in the future, other hardware may
be able to schedule one any time in the upcoming century.


Old PC/AT-Compatible driver:  /dev/rtc
--------------------------------------

All PCs (even Alpha machines) have a Real Time Clock built into them.
Usually they are built into the chipset of the computer, but some may
actually have a Motorola MC146818 (or clone) on the board. This is the
clock that keeps the date and time while your computer is turned off.

ACPI has standardized that MC146818 functionality, and extended it in
a few ways (enabling longer alarm periods, and wake-from-hibernate).
That functionality is NOT exposed in the old driver.

However it can also be used to generate signals from a slow 2Hz to a
relatively fast 8192Hz, in increments of powers of two. These signals
are reported by interrupt number 8. (Oh! So *that* is what IRQ 8 is
for...) It can also function as a 24hr alarm, raising IRQ 8 when the
alarm goes off. The alarm can also be programmed to only check any
subset of the three programmable values, meaning that it could be set to
ring on the 30th second of the 30th minute of every hour, for example.
The clock can also be set to generate an interrupt upon every clock
update, thus generating a 1Hz signal.

The interrupts are reported via /dev/rtc (major 10, minor 135, read only
character device) in the form of an unsigned long. The low byte contains
the type of interrupt (update-done, alarm-rang, or periodic) that was
raised, and the remaining bytes contain the number of interrupts since
the last read.  Status information is reported through the pseudo-file
/proc/driver/rtc if the /proc filesystem was enabled.  The driver has
built in locking so that only one process is allowed to have the /dev/rtc
interface open at a time.

A user process can monitor these interrupts by doing a read(2) or a
select(2) on /dev/rtc -- either will block/stop the user process until
the next interrupt is received. This is useful for things like
reasonably high frequency data acquisition where one doesn't want to
burn up 100% CPU by polling gettimeofday etc. etc.

At high frequencies, or under high loads, the user process should check
the number of interrupts received since the last read to determine if
there has been any interrupt "pileup" so to speak. Just for reference, a
typical 486-33 running a tight read loop on /dev/rtc will start to suffer
occasional interrupt pileup (i.e. > 1 IRQ event since last read) for
frequencies above 1024Hz. So you really should check the high bytes
of the value you read, especially at frequencies above that of the
normal timer interrupt, which is 100Hz.

Programming and/or enabling interrupt frequencies greater than 64Hz is
only allowed by root. This is perhaps a bit conservative, but we don't want
an evil user generating lots of IRQs on a slow 386sx-16, where it might have
a negative impact on performance. This 64Hz limit can be changed by writing
a different value to /proc/sys/dev/rtc/max-user-freq. Note that the
interrupt handler is only a few lines of code to minimize any possibility
of this effect.

Also, if the kernel time is synchronized with an external source, the 
kernel will write the time back to the CMOS clock every 11 minutes. In 
the process of doing this, the kernel briefly turns off RTC periodic 
interrupts, so be aware of this if you are doing serious work. If you
don't synchronize the kernel time with an external source (via ntp or
whatever) then the kernel will keep its hands off the RTC, allowing you
exclusive access to the device for your applications.

The alarm and/or interrupt frequency are programmed into the RTC via
various ioctl(2) calls as listed in ./include/linux/rtc.h
Rather than write 50 pages describing the ioctl() and so on, it is
perhaps more useful to include a small test program that demonstrates
how to use them, and demonstrates the features of the driver. This is
probably a lot more useful to people interested in writing applications
that will be using this driver.  See the code at the end of this document.

(The original /dev/rtc driver was written by Paul Gortmaker.)


New portable "RTC Class" drivers:  /dev/rtcN
--------------------------------------------

Because Linux supports many non-ACPI and non-PC platforms, some of which
have more than one RTC style clock, it needed a more portable solution
than expecting a single battery-backed MC146818 clone on every system.
Accordingly, a new "RTC Class" framework has been defined.  It offers
three different userspace interfaces:

    *	/dev/rtcN ... much the same as the older /dev/rtc interface

    *	/sys/class/rtc/rtcN ... sysfs attributes support readonly
	access to some RTC attributes.

    *	/proc/driver/rtc ... the system clock RTC may expose itself
	using a procfs interface. If there is no RTC for the system clock,
	rtc0 is used by default. More information is (currently) shown
	here than through sysfs.

The RTC Class framework supports a wide variety of RTCs, ranging from those
integrated into embeddable system-on-chip (SOC) processors to discrete chips
using I2C, SPI, or some other bus to communicate with the host CPU.  There's
even support for PC-style RTCs ... including the features exposed on newer PCs
through ACPI.

The new framework also removes the "one RTC per system" restriction.  For
example, maybe the low-power battery-backed RTC is a discrete I2C chip, but
a high functionality RTC is integrated into the SOC.  That system might read
the system clock from the discrete RTC, but use the integrated one for all
other tasks, because of its greater functionality.

Check out tools/testing/selftests/rtc/rtctest.c for an example usage of the
ioctl interface.

---

--- METRICS ---
- Files Extracted: 100
- Estimated Token Budget: ~404670 tokens
- Canonical Reference: https://codewiki.google/github.com/raspberrypi/linux
