aboutsummaryrefslogtreecommitdiffstats
path: root/Documentation/driver-api
diff options
context:
space:
mode:
Diffstat (limited to 'Documentation/driver-api')
-rw-r--r--Documentation/driver-api/80211/cfg80211.rst392
-rw-r--r--Documentation/driver-api/80211/mac80211-advanced.rst151
-rw-r--r--Documentation/driver-api/80211/mac80211.rst148
-rw-r--r--Documentation/driver-api/acpi/linuxized-acpica.rst8
-rw-r--r--Documentation/driver-api/aperture.rst13
-rw-r--r--Documentation/driver-api/auxiliary_bus.rst50
-rw-r--r--Documentation/driver-api/basics.rst47
-rw-r--r--Documentation/driver-api/clk.rst5
-rw-r--r--Documentation/driver-api/connector.rst7
-rw-r--r--Documentation/driver-api/crypto/iaa/iaa-crypto.rst824
-rw-r--r--Documentation/driver-api/crypto/iaa/index.rst20
-rw-r--r--Documentation/driver-api/crypto/index.rst20
-rw-r--r--Documentation/driver-api/cxl/index.rst12
-rw-r--r--Documentation/driver-api/cxl/memory-devices.rst383
-rw-r--r--Documentation/driver-api/dcdbas.rst99
-rw-r--r--Documentation/driver-api/device-io.rst388
-rw-r--r--Documentation/driver-api/device_connection.rst43
-rw-r--r--Documentation/driver-api/device_link.rst13
-rw-r--r--Documentation/driver-api/dma-buf.rst256
-rw-r--r--Documentation/driver-api/dmaengine/client.rst12
-rw-r--r--Documentation/driver-api/dmaengine/dmatest.rst19
-rw-r--r--Documentation/driver-api/dmaengine/provider.rst93
-rw-r--r--Documentation/driver-api/dpll.rst551
-rw-r--r--Documentation/driver-api/driver-model/bus.rst4
-rw-r--r--Documentation/driver-api/driver-model/class.rst149
-rw-r--r--Documentation/driver-api/driver-model/device.rst27
-rw-r--r--Documentation/driver-api/driver-model/devres.rst84
-rw-r--r--Documentation/driver-api/driver-model/driver.rst30
-rw-r--r--Documentation/driver-api/driver-model/index.rst1
-rw-r--r--Documentation/driver-api/driver-model/overview.rst2
-rw-r--r--Documentation/driver-api/driver-model/platform.rst2
-rw-r--r--Documentation/driver-api/early-userspace/early_userspace_support.rst12
-rw-r--r--Documentation/driver-api/edac.rst120
-rw-r--r--Documentation/driver-api/eisa.rst2
-rw-r--r--Documentation/driver-api/firewire.rst4
-rw-r--r--Documentation/driver-api/firmware/built-in-fw.rst2
-rw-r--r--Documentation/driver-api/firmware/core.rst1
-rw-r--r--Documentation/driver-api/firmware/direct-fs-lookup.rst2
-rw-r--r--Documentation/driver-api/firmware/fallback-mechanisms.rst1
-rw-r--r--Documentation/driver-api/firmware/firmware-usage-guidelines.rst44
-rw-r--r--Documentation/driver-api/firmware/firmware_cache.rst2
-rw-r--r--Documentation/driver-api/firmware/fw_search_path.rst9
-rw-r--r--Documentation/driver-api/firmware/fw_upload.rst127
-rw-r--r--Documentation/driver-api/firmware/index.rst1
-rw-r--r--Documentation/driver-api/firmware/other_interfaces.rst6
-rw-r--r--Documentation/driver-api/firmware/request_firmware.rst2
-rw-r--r--Documentation/driver-api/fpga/fpga-bridge.rst12
-rw-r--r--Documentation/driver-api/fpga/fpga-mgr.rst73
-rw-r--r--Documentation/driver-api/fpga/fpga-programming.rst18
-rw-r--r--Documentation/driver-api/fpga/fpga-region.rst32
-rw-r--r--Documentation/driver-api/generic-counter.rst375
-rw-r--r--Documentation/driver-api/gpio/board.rst38
-rw-r--r--Documentation/driver-api/gpio/consumer.rst47
-rw-r--r--Documentation/driver-api/gpio/driver.rst265
-rw-r--r--Documentation/driver-api/gpio/drivers-on-gpio.rst13
-rw-r--r--Documentation/driver-api/gpio/intro.rst16
-rw-r--r--Documentation/driver-api/gpio/legacy.rst78
-rw-r--r--Documentation/driver-api/gpio/using-gpio.rst6
-rw-r--r--Documentation/driver-api/hsi.rst4
-rw-r--r--Documentation/driver-api/hte/hte.rst79
-rw-r--r--Documentation/driver-api/hte/index.rst22
-rw-r--r--Documentation/driver-api/hte/tegra-hte.rst47
-rw-r--r--Documentation/driver-api/i3c/protocol.rst6
-rw-r--r--Documentation/driver-api/iio/buffers.rst19
-rw-r--r--Documentation/driver-api/iio/core.rst22
-rw-r--r--Documentation/driver-api/iio/hw-consumer.rst2
-rw-r--r--Documentation/driver-api/iio/triggered-buffers.rst2
-rw-r--r--Documentation/driver-api/iio/triggers.rst6
-rw-r--r--Documentation/driver-api/index.rst41
-rw-r--r--Documentation/driver-api/infiniband.rst3
-rw-r--r--Documentation/driver-api/infrastructure.rst22
-rw-r--r--Documentation/driver-api/input.rst9
-rw-r--r--Documentation/driver-api/interconnect.rst25
-rw-r--r--Documentation/driver-api/io-mapping.rst96
-rw-r--r--Documentation/driver-api/ioctl.rst10
-rw-r--r--Documentation/driver-api/ipmi.rst810
-rw-r--r--Documentation/driver-api/isa.rst2
-rw-r--r--Documentation/driver-api/isapnp.rst15
-rw-r--r--Documentation/driver-api/libata.rst51
-rw-r--r--Documentation/driver-api/lightnvm-pblk.rst21
-rw-r--r--Documentation/driver-api/mailbox.rst129
-rw-r--r--Documentation/driver-api/md/md-cluster.rst2
-rw-r--r--Documentation/driver-api/md/raid5-cache.rst2
-rw-r--r--Documentation/driver-api/media/camera-sensor.rst148
-rw-r--r--Documentation/driver-api/media/cec-core.rst502
-rw-r--r--Documentation/driver-api/media/drivers/bttv-devel.rst116
-rw-r--r--Documentation/driver-api/media/drivers/ccs/ccs-regs.asc1041
-rw-r--r--Documentation/driver-api/media/drivers/ccs/ccs.rst125
-rwxr-xr-xDocumentation/driver-api/media/drivers/ccs/mk-ccs-regs480
-rw-r--r--Documentation/driver-api/media/drivers/contributors.rst131
-rw-r--r--Documentation/driver-api/media/drivers/cx2341x-devel.rst3685
-rw-r--r--Documentation/driver-api/media/drivers/cx88-devel.rst113
-rw-r--r--Documentation/driver-api/media/drivers/dvb-usb.rst357
-rw-r--r--Documentation/driver-api/media/drivers/fimc-devel.rst33
-rw-r--r--Documentation/driver-api/media/drivers/frontends.rst32
-rw-r--r--Documentation/driver-api/media/drivers/index.rst40
-rw-r--r--Documentation/driver-api/media/drivers/pvrusb2.rst202
-rw-r--r--Documentation/driver-api/media/drivers/pxa_camera.rst194
-rw-r--r--Documentation/driver-api/media/drivers/radiotrack.rst168
-rw-r--r--Documentation/driver-api/media/drivers/rkisp1.rst43
-rw-r--r--Documentation/driver-api/media/drivers/saa7134-devel.rst67
-rw-r--r--Documentation/driver-api/media/drivers/sh_mobile_ceu_camera.rst142
-rw-r--r--Documentation/driver-api/media/drivers/tuners.rst133
-rw-r--r--Documentation/driver-api/media/drivers/vidtv.rst513
-rw-r--r--Documentation/driver-api/media/drivers/vimc-devel.rst15
-rw-r--r--Documentation/driver-api/media/drivers/zoran.rst575
-rw-r--r--Documentation/driver-api/media/dtv-ca.rst6
-rw-r--r--Documentation/driver-api/media/dtv-common.rst53
-rw-r--r--Documentation/driver-api/media/dtv-core.rst39
-rw-r--r--Documentation/driver-api/media/dtv-demux.rst84
-rw-r--r--Documentation/driver-api/media/dtv-frontend.rst445
-rw-r--r--Documentation/driver-api/media/dtv-net.rst6
-rw-r--r--Documentation/driver-api/media/index.rst54
-rw-r--r--Documentation/driver-api/media/maintainer-entry-profile.rst206
-rw-r--r--Documentation/driver-api/media/mc-core.rst326
-rw-r--r--Documentation/driver-api/media/rc-core.rst88
-rw-r--r--Documentation/driver-api/media/tx-rx.rst134
-rw-r--r--Documentation/driver-api/media/v4l2-async.rst5
-rw-r--r--Documentation/driver-api/media/v4l2-cci.rst5
-rw-r--r--Documentation/driver-api/media/v4l2-common.rst8
-rw-r--r--Documentation/driver-api/media/v4l2-controls.rst823
-rw-r--r--Documentation/driver-api/media/v4l2-core.rst28
-rw-r--r--Documentation/driver-api/media/v4l2-dev.rst367
-rw-r--r--Documentation/driver-api/media/v4l2-device.rst146
-rw-r--r--Documentation/driver-api/media/v4l2-dv-timings.rst6
-rw-r--r--Documentation/driver-api/media/v4l2-event.rst181
-rw-r--r--Documentation/driver-api/media/v4l2-fh.rst141
-rw-r--r--Documentation/driver-api/media/v4l2-flash-led-class.rst6
-rw-r--r--Documentation/driver-api/media/v4l2-fwnode.rst5
-rw-r--r--Documentation/driver-api/media/v4l2-intro.rst76
-rw-r--r--Documentation/driver-api/media/v4l2-mc.rst6
-rw-r--r--Documentation/driver-api/media/v4l2-mediabus.rst6
-rw-r--r--Documentation/driver-api/media/v4l2-mem2mem.rst6
-rw-r--r--Documentation/driver-api/media/v4l2-rect.rst6
-rw-r--r--Documentation/driver-api/media/v4l2-subdev.rst644
-rw-r--r--Documentation/driver-api/media/v4l2-tuner.rst8
-rw-r--r--Documentation/driver-api/media/v4l2-tveeprom.rst6
-rw-r--r--Documentation/driver-api/media/v4l2-videobuf2.rst12
-rw-r--r--Documentation/driver-api/mei/index.rst7
-rw-r--r--Documentation/driver-api/mei/mei.rst39
-rw-r--r--Documentation/driver-api/mei/nfc.rst2
-rw-r--r--Documentation/driver-api/memory-devices/ti-gpmc.rst2
-rw-r--r--Documentation/driver-api/men-chameleon-bus.rst12
-rw-r--r--Documentation/driver-api/miscellaneous.rst5
-rw-r--r--Documentation/driver-api/mmc/mmc-tools.rst4
-rw-r--r--Documentation/driver-api/mtd/index.rst2
-rw-r--r--Documentation/driver-api/mtd/nand_ecc.rst2
-rw-r--r--Documentation/driver-api/mtd/spi-intel.rst (renamed from Documentation/driver-api/mtd/intel-spi.rst)12
-rw-r--r--Documentation/driver-api/mtd/spi-nor.rst263
-rw-r--r--Documentation/driver-api/mtdnand.rst9
-rw-r--r--Documentation/driver-api/nfc/nfc-hci.rst4
-rw-r--r--Documentation/driver-api/ntb.rst6
-rw-r--r--Documentation/driver-api/nvdimm/firmware-activate.rst86
-rw-r--r--Documentation/driver-api/nvdimm/index.rst1
-rw-r--r--Documentation/driver-api/nvdimm/nvdimm.rst422
-rw-r--r--Documentation/driver-api/nvdimm/security.rst4
-rw-r--r--Documentation/driver-api/nvmem.rst51
-rw-r--r--Documentation/driver-api/pci/index.rst5
-rw-r--r--Documentation/driver-api/pci/p2pdma.rst16
-rw-r--r--Documentation/driver-api/pci/pci.rst2
-rw-r--r--Documentation/driver-api/phy/phy.rst49
-rw-r--r--Documentation/driver-api/pin-control.rst (renamed from Documentation/driver-api/pinctl.rst)533
-rw-r--r--Documentation/driver-api/pldmfw/driver-ops.rst56
-rw-r--r--Documentation/driver-api/pldmfw/file-format.rst203
-rw-r--r--Documentation/driver-api/pldmfw/index.rst72
-rw-r--r--Documentation/driver-api/pm/cpuidle.rst70
-rw-r--r--Documentation/driver-api/pm/devices.rst233
-rw-r--r--Documentation/driver-api/pps.rst16
-rw-r--r--Documentation/driver-api/pti_intel_mid.rst108
-rw-r--r--Documentation/driver-api/ptp.rst41
-rw-r--r--Documentation/driver-api/pwm.rst50
-rw-r--r--Documentation/driver-api/rapidio/rapidio.rst4
-rw-r--r--Documentation/driver-api/regulator.rst4
-rw-r--r--Documentation/driver-api/reset.rst221
-rw-r--r--Documentation/driver-api/s390-drivers.rst4
-rw-r--r--Documentation/driver-api/serial/cyclades_z.rst11
-rw-r--r--Documentation/driver-api/serial/driver.rst485
-rw-r--r--Documentation/driver-api/serial/index.rst5
-rw-r--r--Documentation/driver-api/serial/moxa-smartio.rst615
-rw-r--r--Documentation/driver-api/serial/n_gsm.rst100
-rw-r--r--Documentation/driver-api/serial/rocket.rst185
-rw-r--r--Documentation/driver-api/serial/serial-rs485.rst58
-rw-r--r--Documentation/driver-api/serial/tty.rst328
-rw-r--r--Documentation/driver-api/smsc_ece1099.rst60
-rw-r--r--Documentation/driver-api/sound.rst54
-rw-r--r--Documentation/driver-api/soundwire/stream.rst104
-rw-r--r--Documentation/driver-api/soundwire/summary.rst7
-rw-r--r--Documentation/driver-api/spi.rst4
-rw-r--r--Documentation/driver-api/surface_aggregator/client-api.rst38
-rw-r--r--Documentation/driver-api/surface_aggregator/client.rst397
-rw-r--r--Documentation/driver-api/surface_aggregator/clients/cdev.rst204
-rw-r--r--Documentation/driver-api/surface_aggregator/clients/dtx.rst718
-rw-r--r--Documentation/driver-api/surface_aggregator/clients/index.rst23
-rw-r--r--Documentation/driver-api/surface_aggregator/clients/san.rst44
-rw-r--r--Documentation/driver-api/surface_aggregator/index.rst21
-rw-r--r--Documentation/driver-api/surface_aggregator/internal-api.rst67
-rw-r--r--Documentation/driver-api/surface_aggregator/internal.rst578
-rw-r--r--Documentation/driver-api/surface_aggregator/overview.rst79
-rw-r--r--Documentation/driver-api/surface_aggregator/ssh.rst346
-rw-r--r--Documentation/driver-api/target.rst12
-rw-r--r--Documentation/driver-api/tee.rst66
-rw-r--r--Documentation/driver-api/thermal/cpu-idle-cooling.rst17
-rw-r--r--Documentation/driver-api/thermal/index.rst3
-rw-r--r--Documentation/driver-api/thermal/intel_dptf.rst381
-rw-r--r--Documentation/driver-api/thermal/intel_powerclamp.rst320
-rw-r--r--Documentation/driver-api/thermal/nouveau_thermal.rst4
-rw-r--r--Documentation/driver-api/thermal/power_allocator.rst12
-rw-r--r--Documentation/driver-api/thermal/sysfs-api.rst319
-rw-r--r--Documentation/driver-api/tty/index.rst74
-rw-r--r--Documentation/driver-api/tty/moxa-smartio.rst197
-rw-r--r--Documentation/driver-api/tty/n_gsm.rst192
-rw-r--r--Documentation/driver-api/tty/n_tty.rst22
-rw-r--r--Documentation/driver-api/tty/tty_buffer.rst49
-rw-r--r--Documentation/driver-api/tty/tty_driver.rst128
-rw-r--r--Documentation/driver-api/tty/tty_internals.rst31
-rw-r--r--Documentation/driver-api/tty/tty_ioctl.rst10
-rw-r--r--Documentation/driver-api/tty/tty_ldisc.rst85
-rw-r--r--Documentation/driver-api/tty/tty_port.rst70
-rw-r--r--Documentation/driver-api/tty/tty_struct.rst81
-rw-r--r--Documentation/driver-api/uio-howto.rst2
-rw-r--r--Documentation/driver-api/usb/URB.rst4
-rw-r--r--Documentation/driver-api/usb/bulk-streams.rst4
-rw-r--r--Documentation/driver-api/usb/dma.rst54
-rw-r--r--Documentation/driver-api/usb/dwc3.rst2
-rw-r--r--Documentation/driver-api/usb/error-codes.rst3
-rw-r--r--Documentation/driver-api/usb/gadget.rst10
-rw-r--r--Documentation/driver-api/usb/hotplug.rst2
-rw-r--r--Documentation/driver-api/usb/typec_bus.rst8
-rw-r--r--Documentation/driver-api/usb/usb.rst25
-rw-r--r--Documentation/driver-api/usb/usb3-debug-port.rst2
-rw-r--r--Documentation/driver-api/usb/writing_musb_glue_layer.rst6
-rw-r--r--Documentation/driver-api/usb/writing_usb_driver.rst49
-rw-r--r--Documentation/driver-api/vfio-mediated-device.rst203
-rw-r--r--Documentation/driver-api/vfio-pci-device-specific-driver-acceptance.rst35
-rw-r--r--Documentation/driver-api/vfio.rst245
-rw-r--r--Documentation/driver-api/virtio/index.rst11
-rw-r--r--Documentation/driver-api/virtio/virtio.rst145
-rw-r--r--Documentation/driver-api/virtio/writing_virtio_drivers.rst197
-rw-r--r--Documentation/driver-api/vme.rst4
-rw-r--r--Documentation/driver-api/wbrf.rst78
-rw-r--r--Documentation/driver-api/wmi.rst21
-rw-r--r--Documentation/driver-api/xilinx/eemi.rst31
-rw-r--r--Documentation/driver-api/xillybus.rst2
243 files changed, 24526 insertions, 5236 deletions
diff --git a/Documentation/driver-api/80211/cfg80211.rst b/Documentation/driver-api/80211/cfg80211.rst
index eeab91b59457..836f609c3f75 100644
--- a/Documentation/driver-api/80211/cfg80211.rst
+++ b/Documentation/driver-api/80211/cfg80211.rst
@@ -12,79 +12,32 @@ Device registration
:doc: Device registration
.. kernel-doc:: include/net/cfg80211.h
- :functions: ieee80211_channel_flags
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: ieee80211_channel
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: ieee80211_rate_flags
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: ieee80211_rate
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: ieee80211_sta_ht_cap
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: ieee80211_supported_band
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_signal_type
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: wiphy_params_flags
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: wiphy_flags
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: wiphy
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: wireless_dev
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: wiphy_new
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: wiphy_read_of_freq_limits
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: wiphy_register
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: wiphy_unregister
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: wiphy_free
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: wiphy_name
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: wiphy_dev
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: wiphy_priv
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: priv_to_wiphy
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: set_wiphy_dev
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: wdev_priv
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: ieee80211_iface_limit
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: ieee80211_iface_combination
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_check_combinations
+ :functions:
+ ieee80211_channel_flags
+ ieee80211_channel
+ ieee80211_rate_flags
+ ieee80211_rate
+ ieee80211_sta_ht_cap
+ ieee80211_supported_band
+ cfg80211_signal_type
+ wiphy_params_flags
+ wiphy_flags
+ wiphy
+ wireless_dev
+ wiphy_new
+ wiphy_read_of_freq_limits
+ wiphy_register
+ wiphy_unregister
+ wiphy_free
+ wiphy_name
+ wiphy_dev
+ wiphy_priv
+ priv_to_wiphy
+ set_wiphy_dev
+ wdev_priv
+ ieee80211_iface_limit
+ ieee80211_iface_combination
+ cfg80211_check_combinations
Actions and configuration
=========================
@@ -93,139 +46,52 @@ Actions and configuration
:doc: Actions and configuration
.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_ops
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: vif_params
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: key_params
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: survey_info_flags
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: survey_info
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_beacon_data
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_ap_settings
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: station_parameters
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: rate_info_flags
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: rate_info
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: station_info
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: monitor_flags
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: mpath_info_flags
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: mpath_info
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: bss_parameters
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: ieee80211_txq_params
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_crypto_settings
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_auth_request
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_assoc_request
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_deauth_request
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_disassoc_request
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_ibss_params
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_connect_params
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_pmksa
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_rx_mlme_mgmt
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_auth_timeout
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_rx_assoc_resp
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_assoc_timeout
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_tx_mlme_mgmt
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_ibss_joined
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_connect_resp_params
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_connect_done
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_connect_result
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_connect_bss
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_connect_timeout
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_roamed
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_disconnected
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_ready_on_channel
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_remain_on_channel_expired
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_new_sta
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_rx_mgmt
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_mgmt_tx_status
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_cqm_rssi_notify
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_cqm_pktloss_notify
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_michael_mic_failure
+ :functions:
+ cfg80211_ops
+ vif_params
+ key_params
+ survey_info_flags
+ survey_info
+ cfg80211_beacon_data
+ cfg80211_ap_settings
+ station_parameters
+ rate_info_flags
+ rate_info
+ station_info
+ monitor_flags
+ mpath_info_flags
+ mpath_info
+ bss_parameters
+ ieee80211_txq_params
+ cfg80211_crypto_settings
+ cfg80211_auth_request
+ cfg80211_assoc_request
+ cfg80211_deauth_request
+ cfg80211_disassoc_request
+ cfg80211_ibss_params
+ cfg80211_connect_params
+ cfg80211_pmksa
+ cfg80211_rx_mlme_mgmt
+ cfg80211_auth_timeout
+ cfg80211_rx_assoc_resp
+ cfg80211_assoc_timeout
+ cfg80211_tx_mlme_mgmt
+ cfg80211_ibss_joined
+ cfg80211_connect_resp_params
+ cfg80211_connect_done
+ cfg80211_connect_result
+ cfg80211_connect_bss
+ cfg80211_connect_timeout
+ cfg80211_roamed
+ cfg80211_disconnected
+ cfg80211_ready_on_channel
+ cfg80211_remain_on_channel_expired
+ cfg80211_new_sta
+ cfg80211_rx_mgmt
+ cfg80211_mgmt_tx_status
+ cfg80211_cqm_rssi_notify
+ cfg80211_cqm_pktloss_notify
+ cfg80211_michael_mic_failure
Scanning and BSS list handling
==============================
@@ -234,34 +100,17 @@ Scanning and BSS list handling
:doc: Scanning and BSS list handling
.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_ssid
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_scan_request
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_scan_done
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_bss
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_inform_bss
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_inform_bss_frame_data
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_inform_bss_data
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_unlink_bss
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_find_ie
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: ieee80211_bss_get_ie
+ :functions:
+ cfg80211_ssid
+ cfg80211_scan_request
+ cfg80211_scan_done
+ cfg80211_bss
+ cfg80211_inform_bss
+ cfg80211_inform_bss_frame_data
+ cfg80211_inform_bss_data
+ cfg80211_unlink_bss
+ cfg80211_find_ie
+ ieee80211_bss_get_ie
Utility functions
=================
@@ -270,25 +119,14 @@ Utility functions
:doc: Utility functions
.. kernel-doc:: include/net/cfg80211.h
- :functions: ieee80211_channel_to_frequency
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: ieee80211_frequency_to_channel
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: ieee80211_get_channel
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: ieee80211_get_response_rate
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: ieee80211_hdrlen
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: ieee80211_get_hdrlen_from_skb
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: ieee80211_radiotap_iterator
+ :functions:
+ ieee80211_channel_to_frequency
+ ieee80211_frequency_to_channel
+ ieee80211_get_channel
+ ieee80211_get_response_rate
+ ieee80211_hdrlen
+ ieee80211_get_hdrlen_from_skb
+ ieee80211_radiotap_iterator
Data path helpers
=================
@@ -297,13 +135,10 @@ Data path helpers
:doc: Data path helpers
.. kernel-doc:: include/net/cfg80211.h
- :functions: ieee80211_data_to_8023
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: ieee80211_amsdu_to_8023s
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_classify8021d
+ :functions:
+ ieee80211_data_to_8023
+ ieee80211_amsdu_to_8023s
+ cfg80211_classify8021d
Regulatory enforcement infrastructure
=====================================
@@ -312,13 +147,10 @@ Regulatory enforcement infrastructure
:doc: Regulatory enforcement infrastructure
.. kernel-doc:: include/net/cfg80211.h
- :functions: regulatory_hint
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: wiphy_apply_custom_regulatory
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: freq_reg_info
+ :functions:
+ regulatory_hint
+ wiphy_apply_custom_regulatory
+ freq_reg_info
RFkill integration
==================
@@ -327,13 +159,10 @@ RFkill integration
:doc: RFkill integration
.. kernel-doc:: include/net/cfg80211.h
- :functions: wiphy_rfkill_set_hw_state
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: wiphy_rfkill_start_polling
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: wiphy_rfkill_stop_polling
+ :functions:
+ wiphy_rfkill_set_hw_state
+ wiphy_rfkill_start_polling
+ wiphy_rfkill_stop_polling
Test mode
=========
@@ -342,13 +171,8 @@ Test mode
:doc: Test mode
.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_testmode_alloc_reply_skb
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_testmode_reply
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_testmode_alloc_event_skb
-
-.. kernel-doc:: include/net/cfg80211.h
- :functions: cfg80211_testmode_event
+ :functions:
+ cfg80211_testmode_alloc_reply_skb
+ cfg80211_testmode_reply
+ cfg80211_testmode_alloc_event_skb
+ cfg80211_testmode_event
diff --git a/Documentation/driver-api/80211/mac80211-advanced.rst b/Documentation/driver-api/80211/mac80211-advanced.rst
index 24cb64b3b715..f8df7b3af8f5 100644
--- a/Documentation/driver-api/80211/mac80211-advanced.rst
+++ b/Documentation/driver-api/80211/mac80211-advanced.rst
@@ -15,25 +15,14 @@ appropriate trigger, which will then be triggered appropriately by
mac80211.
.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_get_tx_led_name
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_get_rx_led_name
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_get_assoc_led_name
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_get_radio_led_name
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_tpt_blink
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_tpt_led_trigger_flags
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_create_tpt_led_trigger
+ :functions:
+ ieee80211_get_tx_led_name
+ ieee80211_get_rx_led_name
+ ieee80211_get_assoc_led_name
+ ieee80211_get_radio_led_name
+ ieee80211_tpt_blink
+ ieee80211_tpt_led_trigger_flags
+ ieee80211_create_tpt_led_trigger
Hardware crypto acceleration
============================
@@ -42,22 +31,13 @@ Hardware crypto acceleration
:doc: Hardware crypto acceleration
.. kernel-doc:: include/net/mac80211.h
- :functions: set_key_cmd
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_key_conf
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_key_flags
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_get_tkip_p1k
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_get_tkip_p1k_iv
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_get_tkip_p2k
+ :functions:
+ set_key_cmd
+ ieee80211_key_conf
+ ieee80211_key_flags
+ ieee80211_get_tkip_p1k
+ ieee80211_get_tkip_p1k_iv
+ ieee80211_get_tkip_p2k
Powersave support
=================
@@ -99,28 +79,15 @@ support for powersaving clients
:doc: AP support for powersaving clients
.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_get_buffered_bc
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_beacon_get
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_sta_eosp
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_frame_release_type
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_sta_ps_transition
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_sta_ps_transition_ni
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_sta_set_buffered
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_sta_block_awake
+ :functions:
+ ieee80211_get_buffered_bc
+ ieee80211_beacon_get
+ ieee80211_sta_eosp
+ ieee80211_frame_release_type
+ ieee80211_sta_ps_transition
+ ieee80211_sta_ps_transition_ni
+ ieee80211_sta_set_buffered
+ ieee80211_sta_block_awake
Supporting multiple virtual interfaces
======================================
@@ -134,10 +101,9 @@ addresses here, note which configurations are supported by mac80211, add
notes about supporting hw crypto with it.
.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_iterate_active_interfaces
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_iterate_active_interfaces_atomic
+ :functions:
+ ieee80211_iterate_active_interfaces
+ ieee80211_iterate_active_interfaces_atomic
Station handling
================
@@ -145,16 +111,11 @@ Station handling
TODO
.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_sta
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: sta_notify_cmd
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_find_sta
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_find_sta_by_ifaddr
+ :functions:
+ ieee80211_sta
+ sta_notify_cmd
+ ieee80211_find_sta
+ ieee80211_find_sta_by_ifaddr
Hardware scan offload
=====================
@@ -193,10 +154,9 @@ Spatial Multiplexing Powersave (SMPS)
:doc: Spatial multiplexing power save
.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_request_smps
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_smps_mode
+ :functions:
+ ieee80211_request_smps
+ ieee80211_smps_mode
TBD
@@ -209,22 +169,13 @@ Rate Control API
TBD
.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_start_tx_ba_session
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_start_tx_ba_cb_irqsafe
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_stop_tx_ba_session
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_stop_tx_ba_cb_irqsafe
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_rate_control_changed
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_tx_rate_control
+ :functions:
+ ieee80211_start_tx_ba_session
+ ieee80211_start_tx_ba_cb_irqsafe
+ ieee80211_stop_tx_ba_session
+ ieee80211_stop_tx_ba_cb_irqsafe
+ ieee80211_rate_control_changed
+ ieee80211_tx_rate_control
TBD
@@ -261,10 +212,9 @@ Programming information
-----------------------
.. kernel-doc:: net/mac80211/sta_info.h
- :functions: sta_info
-
-.. kernel-doc:: net/mac80211/sta_info.h
- :functions: ieee80211_sta_info_flags
+ :functions:
+ sta_info
+ ieee80211_sta_info_flags
STA information lifetime rules
------------------------------
@@ -276,13 +226,10 @@ Aggregation Functions
=====================
.. kernel-doc:: net/mac80211/sta_info.h
- :functions: sta_ampdu_mlme
-
-.. kernel-doc:: net/mac80211/sta_info.h
- :functions: tid_ampdu_tx
-
-.. kernel-doc:: net/mac80211/sta_info.h
- :functions: tid_ampdu_rx
+ :functions:
+ sta_ampdu_mlme
+ tid_ampdu_tx
+ tid_ampdu_rx
Synchronisation Functions
=========================
diff --git a/Documentation/driver-api/80211/mac80211.rst b/Documentation/driver-api/80211/mac80211.rst
index eab40bcf3987..e38a220401f5 100644
--- a/Documentation/driver-api/80211/mac80211.rst
+++ b/Documentation/driver-api/80211/mac80211.rst
@@ -30,31 +30,16 @@ Finally, a discussion of hardware capabilities should be done with
references to other parts of the book.
.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_hw
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_hw_flags
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: SET_IEEE80211_DEV
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: SET_IEEE80211_PERM_ADDR
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_ops
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_alloc_hw
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_register_hw
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_unregister_hw
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_free_hw
+ :functions:
+ ieee80211_hw
+ ieee80211_hw_flags
+ SET_IEEE80211_DEV
+ SET_IEEE80211_PERM_ADDR
+ ieee80211_ops
+ ieee80211_alloc_hw
+ ieee80211_register_hw
+ ieee80211_unregister_hw
+ ieee80211_free_hw
PHY configuration
=================
@@ -65,10 +50,9 @@ This chapter should describe PHY handling including start/stop callbacks
and the various structures used.
.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_conf
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_conf_flags
+ :functions:
+ ieee80211_conf
+ ieee80211_conf_flags
Virtual interfaces
==================
@@ -123,79 +107,32 @@ functions/definitions
---------------------
.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_rx_status
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: mac80211_rx_encoding_flags
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: mac80211_rx_flags
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: mac80211_tx_info_flags
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: mac80211_tx_control_flags
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: mac80211_rate_control_flags
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_tx_rate
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_tx_info
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_tx_info_clear_status
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_rx
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_rx_ni
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_rx_irqsafe
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_tx_status
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_tx_status_ni
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_tx_status_irqsafe
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_rts_get
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_rts_duration
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_ctstoself_get
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_ctstoself_duration
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_generic_frame_duration
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_wake_queue
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_stop_queue
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_wake_queues
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_stop_queues
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_queue_stopped
+ :functions:
+ ieee80211_rx_status
+ mac80211_rx_encoding_flags
+ mac80211_rx_flags
+ mac80211_tx_info_flags
+ mac80211_tx_control_flags
+ mac80211_rate_control_flags
+ ieee80211_tx_rate
+ ieee80211_tx_info
+ ieee80211_tx_info_clear_status
+ ieee80211_rx
+ ieee80211_rx_ni
+ ieee80211_rx_irqsafe
+ ieee80211_tx_status_skb
+ ieee80211_tx_status_ni
+ ieee80211_tx_status_irqsafe
+ ieee80211_rts_get
+ ieee80211_rts_duration
+ ieee80211_ctstoself_get
+ ieee80211_ctstoself_duration
+ ieee80211_generic_frame_duration
+ ieee80211_wake_queue
+ ieee80211_stop_queue
+ ieee80211_wake_queues
+ ieee80211_stop_queues
+ ieee80211_queue_stopped
Frame filtering
===============
@@ -213,7 +150,6 @@ The mac80211 workqueue
:doc: mac80211 workqueue
.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_queue_work
-
-.. kernel-doc:: include/net/mac80211.h
- :functions: ieee80211_queue_delayed_work
+ :functions:
+ ieee80211_queue_work
+ ieee80211_queue_delayed_work
diff --git a/Documentation/driver-api/acpi/linuxized-acpica.rst b/Documentation/driver-api/acpi/linuxized-acpica.rst
index 0ca8f1538519..cc234353d2c4 100644
--- a/Documentation/driver-api/acpi/linuxized-acpica.rst
+++ b/Documentation/driver-api/acpi/linuxized-acpica.rst
@@ -175,9 +175,9 @@ illustrated in the following figure::
B. acpica / master - "master" branch of the git repository at
<https://github.com/acpica/acpica.git>.
C. linux-pm / linux-next - "linux-next" branch of the git repository at
- <http://git.kernel.org/pub/scm/linux/kernel/git/rafael/linux-pm.git>.
+ <https://git.kernel.org/pub/scm/linux/kernel/git/rafael/linux-pm.git>.
D. linux / master - "master" branch of the git repository at
- <http://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git>.
+ <https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git>.
Before the linuxized ACPICA patches are sent to the Linux ACPI community
for review, there is a quality assurance build test process to reduce
@@ -274,6 +274,6 @@ before they become available from the ACPICA release process.
a diff file indicating the state of the current divergences::
# git clone https://github.com/acpica/acpica
- # git clone http://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
+ # git clone https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
# cd acpica
- # generate/linux/divergences.sh -s ../linux
+ # generate/linux/divergence.sh -s ../linux
diff --git a/Documentation/driver-api/aperture.rst b/Documentation/driver-api/aperture.rst
new file mode 100644
index 000000000000..d173f4e7a7d9
--- /dev/null
+++ b/Documentation/driver-api/aperture.rst
@@ -0,0 +1,13 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+Managing Ownership of the Framebuffer Aperture
+==============================================
+
+.. kernel-doc:: drivers/video/aperture.c
+ :doc: overview
+
+.. kernel-doc:: include/linux/aperture.h
+ :internal:
+
+.. kernel-doc:: drivers/video/aperture.c
+ :export:
diff --git a/Documentation/driver-api/auxiliary_bus.rst b/Documentation/driver-api/auxiliary_bus.rst
new file mode 100644
index 000000000000..cec84908fbc0
--- /dev/null
+++ b/Documentation/driver-api/auxiliary_bus.rst
@@ -0,0 +1,50 @@
+.. SPDX-License-Identifier: GPL-2.0-only
+
+.. _auxiliary_bus:
+
+=============
+Auxiliary Bus
+=============
+
+.. kernel-doc:: drivers/base/auxiliary.c
+ :doc: PURPOSE
+
+When Should the Auxiliary Bus Be Used
+=====================================
+
+.. kernel-doc:: drivers/base/auxiliary.c
+ :doc: USAGE
+
+
+Auxiliary Device Creation
+=========================
+
+.. kernel-doc:: include/linux/auxiliary_bus.h
+ :identifiers: auxiliary_device
+
+.. kernel-doc:: drivers/base/auxiliary.c
+ :identifiers: auxiliary_device_init __auxiliary_device_add
+ auxiliary_find_device
+
+Auxiliary Device Memory Model and Lifespan
+------------------------------------------
+
+.. kernel-doc:: include/linux/auxiliary_bus.h
+ :doc: DEVICE_LIFESPAN
+
+
+Auxiliary Drivers
+=================
+
+.. kernel-doc:: include/linux/auxiliary_bus.h
+ :identifiers: auxiliary_driver module_auxiliary_driver
+
+.. kernel-doc:: drivers/base/auxiliary.c
+ :identifiers: __auxiliary_driver_register auxiliary_driver_unregister
+
+Example Usage
+=============
+
+.. kernel-doc:: drivers/base/auxiliary.c
+ :doc: EXAMPLE
+
diff --git a/Documentation/driver-api/basics.rst b/Documentation/driver-api/basics.rst
index 1ba88c7b3984..d78b7c328ff7 100644
--- a/Documentation/driver-api/basics.rst
+++ b/Documentation/driver-api/basics.rst
@@ -12,9 +12,11 @@ Driver device table
.. kernel-doc:: include/linux/mod_devicetable.h
:internal:
+ :no-identifiers: pci_device_id
-Delaying, scheduling, and timer routines
-----------------------------------------
+
+Delaying and scheduling routines
+--------------------------------
.. kernel-doc:: include/linux/sched.h
:internal:
@@ -31,16 +33,16 @@ Delaying, scheduling, and timer routines
.. kernel-doc:: include/linux/completion.h
:internal:
-.. kernel-doc:: kernel/time/timer.c
- :export:
+Time and timer routines
+-----------------------
-Wait queues and Wake events
----------------------------
-
-.. kernel-doc:: include/linux/wait.h
+.. kernel-doc:: include/linux/jiffies.h
:internal:
-.. kernel-doc:: kernel/sched/wait.c
+.. kernel-doc:: kernel/time/time.c
+ :export:
+
+.. kernel-doc:: kernel/time/timer.c
:export:
High-resolution timers
@@ -55,13 +57,13 @@ High-resolution timers
.. kernel-doc:: kernel/time/hrtimer.c
:export:
-Workqueues and Kevents
-----------------------
+Wait queues and Wake events
+---------------------------
-.. kernel-doc:: include/linux/workqueue.h
+.. kernel-doc:: include/linux/wait.h
:internal:
-.. kernel-doc:: kernel/workqueue.c
+.. kernel-doc:: kernel/sched/wait.c
:export:
Internal Functions
@@ -91,7 +93,13 @@ Reference counting
Atomics
-------
-.. kernel-doc:: arch/x86/include/asm/atomic.h
+.. kernel-doc:: include/linux/atomic/atomic-instrumented.h
+ :internal:
+
+.. kernel-doc:: include/linux/atomic/atomic-arch-fallback.h
+ :internal:
+
+.. kernel-doc:: include/linux/atomic/atomic-long.h
:internal:
Kernel objects manipulation
@@ -105,22 +113,15 @@ Kernel utility functions
.. kernel-doc:: include/linux/kernel.h
:internal:
+ :no-identifiers: kstrtol kstrtoul
.. kernel-doc:: kernel/printk/printk.c
:export:
+ :no-identifiers: printk
.. kernel-doc:: kernel/panic.c
:export:
-.. kernel-doc:: kernel/rcu/tree.c
- :export:
-
-.. kernel-doc:: kernel/rcu/update.c
- :export:
-
-.. kernel-doc:: include/linux/overflow.h
- :internal:
-
Device Resource Management
--------------------------
diff --git a/Documentation/driver-api/clk.rst b/Documentation/driver-api/clk.rst
index 3cad45d14187..93bab5336dfd 100644
--- a/Documentation/driver-api/clk.rst
+++ b/Documentation/driver-api/clk.rst
@@ -258,6 +258,11 @@ clocks properly but rely on them being on from the bootloader, bypassing
the disabling means that the driver will remain functional while the issues
are sorted out.
+You can see which clocks have been disabled by booting your kernel with these
+parameters::
+
+ tp_printk trace_event=clk:clk_disable
+
To bypass this disabling, include "clk_ignore_unused" in the bootargs to the
kernel.
diff --git a/Documentation/driver-api/connector.rst b/Documentation/driver-api/connector.rst
index c100c7482289..631b84a48aa5 100644
--- a/Documentation/driver-api/connector.rst
+++ b/Documentation/driver-api/connector.rst
@@ -25,8 +25,8 @@ handling, etc... The Connector driver allows any kernelspace agents to use
netlink based networking for inter-process communication in a significantly
easier way::
- int cn_add_callback(struct cb_id *id, char *name, void (*callback) (struct cn_msg *, struct netlink_skb_parms *));
- void cn_netlink_send_multi(struct cn_msg *msg, u16 len, u32 portid, u32 __group, int gfp_mask);
+ int cn_add_callback(const struct cb_id *id, char *name, void (*callback) (struct cn_msg *, struct netlink_skb_parms *));
+ void cn_netlink_send_mult(struct cn_msg *msg, u16 len, u32 portid, u32 __group, int gfp_mask);
void cn_netlink_send(struct cn_msg *msg, u32 portid, u32 __group, int gfp_mask);
struct cb_id
@@ -48,7 +48,8 @@ be dereferenced to `struct cn_msg *`::
__u32 seq;
__u32 ack;
- __u32 len; /* Length of the following data */
+ __u16 len; /* Length of the following data */
+ __u16 flags;
__u8 data[0];
};
diff --git a/Documentation/driver-api/crypto/iaa/iaa-crypto.rst b/Documentation/driver-api/crypto/iaa/iaa-crypto.rst
new file mode 100644
index 000000000000..de587cf9cbed
--- /dev/null
+++ b/Documentation/driver-api/crypto/iaa/iaa-crypto.rst
@@ -0,0 +1,824 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+=========================================
+IAA Compression Accelerator Crypto Driver
+=========================================
+
+Tom Zanussi <tom.zanussi@linux.intel.com>
+
+The IAA crypto driver supports compression/decompression compatible
+with the DEFLATE compression standard described in RFC 1951, which is
+the compression/decompression algorithm exported by this module.
+
+The IAA hardware spec can be found here:
+
+ https://cdrdv2.intel.com/v1/dl/getContent/721858
+
+The iaa_crypto driver is designed to work as a layer underneath
+higher-level compression devices such as zswap.
+
+Users can select IAA compress/decompress acceleration by specifying
+one of the supported IAA compression algorithms in whatever facility
+allows compression algorithms to be selected.
+
+For example, a zswap device can select the IAA 'fixed' mode
+represented by selecting the 'deflate-iaa' crypto compression
+algorithm::
+
+ # echo deflate-iaa > /sys/module/zswap/parameters/compressor
+
+This will tell zswap to use the IAA 'fixed' compression mode for all
+compresses and decompresses.
+
+Currently, there is only one compression modes available, 'fixed'
+mode.
+
+The 'fixed' compression mode implements the compression scheme
+specified by RFC 1951 and is given the crypto algorithm name
+'deflate-iaa'. (Because the IAA hardware has a 4k history-window
+limitation, only buffers <= 4k, or that have been compressed using a
+<= 4k history window, are technically compliant with the deflate spec,
+which allows for a window of up to 32k. Because of this limitation,
+the IAA fixed mode deflate algorithm is given its own algorithm name
+rather than simply 'deflate').
+
+
+Config options and other setup
+==============================
+
+The IAA crypto driver is available via menuconfig using the following
+path::
+
+ Cryptographic API -> Hardware crypto devices -> Support for Intel(R) IAA Compression Accelerator
+
+In the configuration file the option called CONFIG_CRYPTO_DEV_IAA_CRYPTO.
+
+The IAA crypto driver also supports statistics, which are available
+via menuconfig using the following path::
+
+ Cryptographic API -> Hardware crypto devices -> Support for Intel(R) IAA Compression -> Enable Intel(R) IAA Compression Accelerator Statistics
+
+In the configuration file the option called CONFIG_CRYPTO_DEV_IAA_CRYPTO_STATS.
+
+The following config options should also be enabled::
+
+ CONFIG_IRQ_REMAP=y
+ CONFIG_INTEL_IOMMU=y
+ CONFIG_INTEL_IOMMU_SVM=y
+ CONFIG_PCI_ATS=y
+ CONFIG_PCI_PRI=y
+ CONFIG_PCI_PASID=y
+ CONFIG_INTEL_IDXD=m
+ CONFIG_INTEL_IDXD_SVM=y
+
+IAA is one of the first Intel accelerator IPs that can work in
+conjunction with the Intel IOMMU. There are multiple modes that exist
+for testing. Based on IOMMU configuration, there are 3 modes::
+
+ - Scalable
+ - Legacy
+ - No IOMMU
+
+
+Scalable mode
+-------------
+
+Scalable mode supports Shared Virtual Memory (SVM or SVA). It is
+entered when using the kernel boot commandline::
+
+ intel_iommu=on,sm_on
+
+with VT-d turned on in BIOS.
+
+With scalable mode, both shared and dedicated workqueues are available
+for use.
+
+For scalable mode, the following BIOS settings should be enabled::
+
+ Socket Configuration > IIO Configuration > Intel VT for Directed I/O (VT-d) > Intel VT for Directed I/O
+
+ Socket Configuration > IIO Configuration > PCIe ENQCMD > ENQCMDS
+
+
+Legacy mode
+-----------
+
+Legacy mode is entered when using the kernel boot commandline::
+
+ intel_iommu=off
+
+or VT-d is not turned on in BIOS.
+
+If you have booted into Linux and not sure if VT-d is on, do a "dmesg
+| grep -i dmar". If you don't see a number of DMAR devices enumerated,
+most likely VT-d is not on.
+
+With legacy mode, only dedicated workqueues are available for use.
+
+
+No IOMMU mode
+-------------
+
+No IOMMU mode is entered when using the kernel boot commandline::
+
+ iommu=off.
+
+With no IOMMU mode, only dedicated workqueues are available for use.
+
+
+Usage
+=====
+
+accel-config
+------------
+
+When loaded, the iaa_crypto driver automatically creates a default
+configuration and enables it, and assigns default driver attributes.
+If a different configuration or set of driver attributes is required,
+the user must first disable the IAA devices and workqueues, reset the
+configuration, and then re-register the deflate-iaa algorithm with the
+crypto subsystem by removing and reinserting the iaa_crypto module.
+
+The :ref:`iaa_disable_script` in the 'Use Cases'
+section below can be used to disable the default configuration.
+
+See :ref:`iaa_default_config` below for details of the default
+configuration.
+
+More likely than not, however, and because of the complexity and
+configurability of the accelerator devices, the user will want to
+configure the device and manually enable the desired devices and
+workqueues.
+
+The userspace tool to help doing that is called accel-config. Using
+accel-config to configure device or loading a previously saved config
+is highly recommended. The device can be controlled via sysfs
+directly but comes with the warning that you should do this ONLY if
+you know exactly what you are doing. The following sections will not
+cover the sysfs interface but assumes you will be using accel-config.
+
+The :ref:`iaa_sysfs_config` section in the appendix below can be
+consulted for the sysfs interface details if interested.
+
+The accel-config tool along with instructions for building it can be
+found here:
+
+ https://github.com/intel/idxd-config/#readme
+
+Typical usage
+-------------
+
+In order for the iaa_crypto module to actually do any
+compression/decompression work on behalf of a facility, one or more
+IAA workqueues need to be bound to the iaa_crypto driver.
+
+For instance, here's an example of configuring an IAA workqueue and
+binding it to the iaa_crypto driver (note that device names are
+specified as 'iax' rather than 'iaa' - this is because upstream still
+has the old 'iax' device naming in place) ::
+
+ # configure wq1.0
+
+ accel-config config-wq --group-id=0 --mode=dedicated --type=kernel --name="iaa_crypto" --device_name="crypto" iax1/wq1.0
+
+ # enable IAA device iax1
+
+ accel-config enable-device iax1
+
+ # enable wq1.0 on IAX device iax1
+
+ accel-config enable-wq iax1/wq1.0
+
+Whenever a new workqueue is bound to or unbound from the iaa_crypto
+driver, the available workqueues are 'rebalanced' such that work
+submitted from a particular CPU is given to the most appropriate
+workqueue available. Current best practice is to configure and bind
+at least one workqueue for each IAA device, but as long as there is at
+least one workqueue configured and bound to any IAA device in the
+system, the iaa_crypto driver will work, albeit most likely not as
+efficiently.
+
+The IAA crypto algorigthms is operational and compression and
+decompression operations are fully enabled following the successful
+binding of the first IAA workqueue to the iaa_crypto driver.
+
+Similarly, the IAA crypto algorithm is not operational and compression
+and decompression operations are disabled following the unbinding of
+the last IAA worqueue to the iaa_crypto driver.
+
+As a result, the IAA crypto algorithms and thus the IAA hardware are
+only available when one or more workques are bound to the iaa_crypto
+driver.
+
+When there are no IAA workqueues bound to the driver, the IAA crypto
+algorithms can be unregistered by removing the module.
+
+
+Driver attributes
+-----------------
+
+There are a couple user-configurable driver attributes that can be
+used to configure various modes of operation. They're listed below,
+along with their default values. To set any of these attributes, echo
+the appropriate values to the attribute file located under
+/sys/bus/dsa/drivers/crypto/
+
+The attribute settings at the time the IAA algorithms are registered
+are captured in each algorithm's crypto_ctx and used for all compresses
+and decompresses when using that algorithm.
+
+The available attributes are:
+
+ - verify_compress
+
+ Toggle compression verification. If set, each compress will be
+ internally decompressed and the contents verified, returning error
+ codes if unsuccessful. This can be toggled with 0/1::
+
+ echo 0 > /sys/bus/dsa/drivers/crypto/verify_compress
+
+ The default setting is '1' - verify all compresses.
+
+ - sync_mode
+
+ Select mode to be used to wait for completion of each compresses
+ and decompress operation.
+
+ The crypto async interface support implemented by iaa_crypto
+ provides an implementation that satisfies the interface but does
+ so in a synchronous manner - it fills and submits the IDXD
+ descriptor and then loops around waiting for it to complete before
+ returning. This isn't a problem at the moment, since all existing
+ callers (e.g. zswap) wrap any asynchronous callees in a
+ synchronous wrapper anyway.
+
+ The iaa_crypto driver does however provide true asynchronous
+ support for callers that can make use of it. In this mode, it
+ fills and submits the IDXD descriptor, then returns immediately
+ with -EINPROGRESS. The caller can then either poll for completion
+ itself, which requires specific code in the caller which currently
+ nothing in the upstream kernel implements, or go to sleep and wait
+ for an interrupt signaling completion. This latter mode is
+ supported by current users in the kernel such as zswap via
+ synchronous wrappers. Although it is supported this mode is
+ significantly slower than the synchronous mode that does the
+ polling in the iaa_crypto driver previously mentioned.
+
+ This mode can be enabled by writing 'async_irq' to the sync_mode
+ iaa_crypto driver attribute::
+
+ echo async_irq > /sys/bus/dsa/drivers/crypto/sync_mode
+
+ Async mode without interrupts (caller must poll) can be enabled by
+ writing 'async' to it::
+
+ echo async > /sys/bus/dsa/drivers/crypto/sync_mode
+
+ The mode that does the polling in the iaa_crypto driver can be
+ enabled by writing 'sync' to it::
+
+ echo sync > /sys/bus/dsa/drivers/crypto/sync_mode
+
+ The default mode is 'sync'.
+
+.. _iaa_default_config:
+
+IAA Default Configuration
+-------------------------
+
+When the iaa_crypto driver is loaded, each IAA device has a single
+work queue configured for it, with the following attributes::
+
+ mode "dedicated"
+ threshold 0
+ size Total WQ Size from WQCAP
+ priority 10
+ type IDXD_WQT_KERNEL
+ group 0
+ name "iaa_crypto"
+ driver_name "crypto"
+
+The devices and workqueues are also enabled and therefore the driver
+is ready to be used without any additional configuration.
+
+The default driver attributes in effect when the driver is loaded are::
+
+ sync_mode "sync"
+ verify_compress 1
+
+In order to change either the device/work queue or driver attributes,
+the enabled devices and workqueues must first be disabled. In order
+to have the new configuration applied to the deflate-iaa crypto
+algorithm, it needs to be re-registered by removing and reinserting
+the iaa_crypto module. The :ref:`iaa_disable_script` in the 'Use
+Cases' section below can be used to disable the default configuration.
+
+Statistics
+==========
+
+If the optional debugfs statistics support is enabled, the IAA crypto
+driver will generate statistics which can be accessed in debugfs at::
+
+ # ls -al /sys/kernel/debug/iaa-crypto/
+ total 0
+ drwxr-xr-x 2 root root 0 Mar 3 09:35 .
+ drwx------ 47 root root 0 Mar 3 09:35 ..
+ -rw-r--r-- 1 root root 0 Mar 3 09:35 max_acomp_delay_ns
+ -rw-r--r-- 1 root root 0 Mar 3 09:35 max_adecomp_delay_ns
+ -rw-r--r-- 1 root root 0 Mar 3 09:35 max_comp_delay_ns
+ -rw-r--r-- 1 root root 0 Mar 3 09:35 max_decomp_delay_ns
+ -rw-r--r-- 1 root root 0 Mar 3 09:35 stats_reset
+ -rw-r--r-- 1 root root 0 Mar 3 09:35 total_comp_bytes_out
+ -rw-r--r-- 1 root root 0 Mar 3 09:35 total_comp_calls
+ -rw-r--r-- 1 root root 0 Mar 3 09:35 total_decomp_bytes_in
+ -rw-r--r-- 1 root root 0 Mar 3 09:35 total_decomp_calls
+ -rw-r--r-- 1 root root 0 Mar 3 09:35 wq_stats
+
+Most of the above statisticss are self-explanatory. The wq_stats file
+shows per-wq stats, a set for each iaa device and wq in addition to
+some global stats::
+
+ # cat wq_stats
+ global stats:
+ total_comp_calls: 100
+ total_decomp_calls: 100
+ total_comp_bytes_out: 22800
+ total_decomp_bytes_in: 22800
+ total_completion_einval_errors: 0
+ total_completion_timeout_errors: 0
+ total_completion_comp_buf_overflow_errors: 0
+
+ iaa device:
+ id: 1
+ n_wqs: 1
+ comp_calls: 0
+ comp_bytes: 0
+ decomp_calls: 0
+ decomp_bytes: 0
+ wqs:
+ name: iaa_crypto
+ comp_calls: 0
+ comp_bytes: 0
+ decomp_calls: 0
+ decomp_bytes: 0
+
+ iaa device:
+ id: 3
+ n_wqs: 1
+ comp_calls: 0
+ comp_bytes: 0
+ decomp_calls: 0
+ decomp_bytes: 0
+ wqs:
+ name: iaa_crypto
+ comp_calls: 0
+ comp_bytes: 0
+ decomp_calls: 0
+ decomp_bytes: 0
+
+ iaa device:
+ id: 5
+ n_wqs: 1
+ comp_calls: 100
+ comp_bytes: 22800
+ decomp_calls: 100
+ decomp_bytes: 22800
+ wqs:
+ name: iaa_crypto
+ comp_calls: 100
+ comp_bytes: 22800
+ decomp_calls: 100
+ decomp_bytes: 22800
+
+Writing 0 to 'stats_reset' resets all the stats, including the
+per-device and per-wq stats::
+
+ # echo 0 > stats_reset
+ # cat wq_stats
+ global stats:
+ total_comp_calls: 0
+ total_decomp_calls: 0
+ total_comp_bytes_out: 0
+ total_decomp_bytes_in: 0
+ total_completion_einval_errors: 0
+ total_completion_timeout_errors: 0
+ total_completion_comp_buf_overflow_errors: 0
+ ...
+
+
+Use cases
+=========
+
+Simple zswap test
+-----------------
+
+For this example, the kernel should be configured according to the
+dedicated mode options described above, and zswap should be enabled as
+well::
+
+ CONFIG_ZSWAP=y
+
+This is a simple test that uses iaa_compress as the compressor for a
+swap (zswap) device. It sets up the zswap device and then uses the
+memory_memadvise program listed below to forcibly swap out and in a
+specified number of pages, demonstrating both compress and decompress.
+
+The zswap test expects the work queues for each IAA device on the
+system to be configured properly as a kernel workqueue with a
+workqueue driver_name of "crypto".
+
+The first step is to make sure the iaa_crypto module is loaded::
+
+ modprobe iaa_crypto
+
+If the IAA devices and workqueues haven't previously been disabled and
+reconfigured, then the default configuration should be in place and no
+further IAA configuration is necessary. See :ref:`iaa_default_config`
+below for details of the default configuration.
+
+If the default configuration is in place, you should see the iaa
+devices and wq0s enabled::
+
+ # cat /sys/bus/dsa/devices/iax1/state
+ enabled
+ # cat /sys/bus/dsa/devices/iax1/wq1.0/state
+ enabled
+
+To demonstrate that the following steps work as expected, these
+commands can be used to enable debug output::
+
+ # echo -n 'module iaa_crypto +p' > /sys/kernel/debug/dynamic_debug/control
+ # echo -n 'module idxd +p' > /sys/kernel/debug/dynamic_debug/control
+
+Use the following commands to enable zswap::
+
+ # echo 0 > /sys/module/zswap/parameters/enabled
+ # echo 50 > /sys/module/zswap/parameters/max_pool_percent
+ # echo deflate-iaa > /sys/module/zswap/parameters/compressor
+ # echo zsmalloc > /sys/module/zswap/parameters/zpool
+ # echo 1 > /sys/module/zswap/parameters/enabled
+ # echo 0 > /sys/module/zswap/parameters/same_filled_pages_enabled
+ # echo 100 > /proc/sys/vm/swappiness
+ # echo never > /sys/kernel/mm/transparent_hugepage/enabled
+ # echo 1 > /proc/sys/vm/overcommit_memory
+
+Now you can now run the zswap workload you want to measure. For
+example, using the memory_memadvise code below, the following command
+will swap in and out 100 pages::
+
+ ./memory_madvise 100
+
+ Allocating 100 pages to swap in/out
+ Swapping out 100 pages
+ Swapping in 100 pages
+ Swapped out and in 100 pages
+
+You should see something like the following in the dmesg output::
+
+ [ 404.202972] idxd 0000:e7:02.0: iaa_comp_acompress: dma_map_sg, src_addr 223925c000, nr_sgs 1, req->src 00000000ee7cb5e6, req->slen 4096, sg_dma_len(sg) 4096
+ [ 404.202973] idxd 0000:e7:02.0: iaa_comp_acompress: dma_map_sg, dst_addr 21dadf8000, nr_sgs 1, req->dst 000000008d6acea8, req->dlen 4096, sg_dma_len(sg) 8192
+ [ 404.202975] idxd 0000:e7:02.0: iaa_compress: desc->src1_addr 223925c000, desc->src1_size 4096, desc->dst_addr 21dadf8000, desc->max_dst_size 4096, desc->src2_addr 2203543000, desc->src2_size 1568
+ [ 404.202981] idxd 0000:e7:02.0: iaa_compress_verify: (verify) desc->src1_addr 21dadf8000, desc->src1_size 228, desc->dst_addr 223925c000, desc->max_dst_size 4096, desc->src2_addr 0, desc->src2_size 0
+ ...
+
+Now that basic functionality has been demonstrated, the defaults can
+be erased and replaced with a different configuration. To do that,
+first disable zswap::
+
+ # echo lzo > /sys/module/zswap/parameters/compressor
+ # swapoff -a
+ # echo 0 > /sys/module/zswap/parameters/accept_threshold_percent
+ # echo 0 > /sys/module/zswap/parameters/max_pool_percent
+ # echo 0 > /sys/module/zswap/parameters/enabled
+ # echo 0 > /sys/module/zswap/parameters/enabled
+
+Then run the :ref:`iaa_disable_script` in the 'Use Cases' section
+below to disable the default configuration.
+
+Finally turn swap back on::
+
+ # swapon -a
+
+Following all that the IAA device(s) can now be re-configured and
+enabled as desired for further testing. Below is one example.
+
+The zswap test expects the work queues for each IAA device on the
+system to be configured properly as a kernel workqueue with a
+workqueue driver_name of "crypto".
+
+The below script automatically does that::
+
+ #!/bin/bash
+
+ echo "IAA devices:"
+ lspci -d:0cfe
+ echo "# IAA devices:"
+ lspci -d:0cfe | wc -l
+
+ #
+ # count iaa instances
+ #
+ iaa_dev_id="0cfe"
+ num_iaa=$(lspci -d:${iaa_dev_id} | wc -l)
+ echo "Found ${num_iaa} IAA instances"
+
+ #
+ # disable iaa wqs and devices
+ #
+ echo "Disable IAA"
+
+ for ((i = 1; i < ${num_iaa} * 2; i += 2)); do
+ echo disable wq iax${i}/wq${i}.0
+ accel-config disable-wq iax${i}/wq${i}.0
+ echo disable iaa iax${i}
+ accel-config disable-device iax${i}
+ done
+
+ echo "End Disable IAA"
+
+ #
+ # configure iaa wqs and devices
+ #
+ echo "Configure IAA"
+ for ((i = 1; i < ${num_iaa} * 2; i += 2)); do
+ accel-config config-wq --group-id=0 --mode=dedicated --size=128 --priority=10 --type=kernel --name="iaa_crypto" --driver_name="crypto" iax${i}/wq${i}
+ done
+
+ echo "End Configure IAA"
+
+ #
+ # enable iaa wqs and devices
+ #
+ echo "Enable IAA"
+
+ for ((i = 1; i < ${num_iaa} * 2; i += 2)); do
+ echo enable iaa iaa${i}
+ accel-config enable-device iaa${i}
+ echo enable wq iaa${i}/wq${i}.0
+ accel-config enable-wq iaa${i}/wq${i}.0
+ done
+
+ echo "End Enable IAA"
+
+When the workqueues are bound to the iaa_crypto driver, you should
+see something similar to the following in dmesg output if you've
+enabled debug output (echo -n 'module iaa_crypto +p' >
+/sys/kernel/debug/dynamic_debug/control)::
+
+ [ 60.752344] idxd 0000:f6:02.0: add_iaa_wq: added wq 000000004068d14d to iaa 00000000c9585ba2, n_wq 1
+ [ 60.752346] iaa_crypto: rebalance_wq_table: nr_nodes=2, nr_cpus 160, nr_iaa 8, cpus_per_iaa 20
+ [ 60.752347] iaa_crypto: rebalance_wq_table: iaa=0
+ [ 60.752349] idxd 0000:6a:02.0: request_iaa_wq: getting wq from iaa_device 0000000042d7bc52 (0)
+ [ 60.752350] idxd 0000:6a:02.0: request_iaa_wq: returning unused wq 00000000c8bb4452 (0) from iaa device 0000000042d7bc52 (0)
+ [ 60.752352] iaa_crypto: rebalance_wq_table: assigned wq for cpu=0, node=0 = wq 00000000c8bb4452
+ [ 60.752354] iaa_crypto: rebalance_wq_table: iaa=0
+ [ 60.752355] idxd 0000:6a:02.0: request_iaa_wq: getting wq from iaa_device 0000000042d7bc52 (0)
+ [ 60.752356] idxd 0000:6a:02.0: request_iaa_wq: returning unused wq 00000000c8bb4452 (0) from iaa device 0000000042d7bc52 (0)
+ [ 60.752358] iaa_crypto: rebalance_wq_table: assigned wq for cpu=1, node=0 = wq 00000000c8bb4452
+ [ 60.752359] iaa_crypto: rebalance_wq_table: iaa=0
+ [ 60.752360] idxd 0000:6a:02.0: request_iaa_wq: getting wq from iaa_device 0000000042d7bc52 (0)
+ [ 60.752361] idxd 0000:6a:02.0: request_iaa_wq: returning unused wq 00000000c8bb4452 (0) from iaa device 0000000042d7bc52 (0)
+ [ 60.752362] iaa_crypto: rebalance_wq_table: assigned wq for cpu=2, node=0 = wq 00000000c8bb4452
+ [ 60.752364] iaa_crypto: rebalance_wq_table: iaa=0
+ .
+ .
+ .
+
+Once the workqueues and devices have been enabled, the IAA crypto
+algorithms are enabled and available. When the IAA crypto algorithms
+have been successfully enabled, you should see the following dmesg
+output::
+
+ [ 64.893759] iaa_crypto: iaa_crypto_enable: iaa_crypto now ENABLED
+
+Now run the following zswap-specific setup commands to have zswap use
+the 'fixed' compression mode::
+
+ echo 0 > /sys/module/zswap/parameters/enabled
+ echo 50 > /sys/module/zswap/parameters/max_pool_percent
+ echo deflate-iaa > /sys/module/zswap/parameters/compressor
+ echo zsmalloc > /sys/module/zswap/parameters/zpool
+ echo 1 > /sys/module/zswap/parameters/enabled
+ echo 0 > /sys/module/zswap/parameters/same_filled_pages_enabled
+
+ echo 100 > /proc/sys/vm/swappiness
+ echo never > /sys/kernel/mm/transparent_hugepage/enabled
+ echo 1 > /proc/sys/vm/overcommit_memory
+
+Finally, you can now run the zswap workload you want to measure. For
+example, using the code below, the following command will swap in and
+out 100 pages::
+
+ ./memory_madvise 100
+
+ Allocating 100 pages to swap in/out
+ Swapping out 100 pages
+ Swapping in 100 pages
+ Swapped out and in 100 pages
+
+You should see something like the following in the dmesg output if
+you've enabled debug output (echo -n 'module iaa_crypto +p' >
+/sys/kernel/debug/dynamic_debug/control)::
+
+ [ 404.202972] idxd 0000:e7:02.0: iaa_comp_acompress: dma_map_sg, src_addr 223925c000, nr_sgs 1, req->src 00000000ee7cb5e6, req->slen 4096, sg_dma_len(sg) 4096
+ [ 404.202973] idxd 0000:e7:02.0: iaa_comp_acompress: dma_map_sg, dst_addr 21dadf8000, nr_sgs 1, req->dst 000000008d6acea8, req->dlen 4096, sg_dma_len(sg) 8192
+ [ 404.202975] idxd 0000:e7:02.0: iaa_compress: desc->src1_addr 223925c000, desc->src1_size 4096, desc->dst_addr 21dadf8000, desc->max_dst_size 4096, desc->src2_addr 2203543000, desc->src2_size 1568
+ [ 404.202981] idxd 0000:e7:02.0: iaa_compress_verify: (verify) desc->src1_addr 21dadf8000, desc->src1_size 228, desc->dst_addr 223925c000, desc->max_dst_size 4096, desc->src2_addr 0, desc->src2_size 0
+ [ 409.203227] idxd 0000:e7:02.0: iaa_comp_adecompress: dma_map_sg, src_addr 21ddd8b100, nr_sgs 1, req->src 0000000084adab64, req->slen 228, sg_dma_len(sg) 228
+ [ 409.203235] idxd 0000:e7:02.0: iaa_comp_adecompress: dma_map_sg, dst_addr 21ee3dc000, nr_sgs 1, req->dst 000000004e2990d0, req->dlen 4096, sg_dma_len(sg) 4096
+ [ 409.203239] idxd 0000:e7:02.0: iaa_decompress: desc->src1_addr 21ddd8b100, desc->src1_size 228, desc->dst_addr 21ee3dc000, desc->max_dst_size 4096, desc->src2_addr 0, desc->src2_size 0
+ [ 409.203254] idxd 0000:e7:02.0: iaa_comp_adecompress: dma_map_sg, src_addr 21ddd8b100, nr_sgs 1, req->src 0000000084adab64, req->slen 228, sg_dma_len(sg) 228
+ [ 409.203256] idxd 0000:e7:02.0: iaa_comp_adecompress: dma_map_sg, dst_addr 21f1551000, nr_sgs 1, req->dst 000000004e2990d0, req->dlen 4096, sg_dma_len(sg) 4096
+ [ 409.203257] idxd 0000:e7:02.0: iaa_decompress: desc->src1_addr 21ddd8b100, desc->src1_size 228, desc->dst_addr 21f1551000, desc->max_dst_size 4096, desc->src2_addr 0, desc->src2_size 0
+
+In order to unregister the IAA crypto algorithms, and register new
+ones using different parameters, any users of the current algorithm
+should be stopped and the IAA workqueues and devices disabled.
+
+In the case of zswap, remove the IAA crypto algorithm as the
+compressor and turn off swap (to remove all references to
+iaa_crypto)::
+
+ echo lzo > /sys/module/zswap/parameters/compressor
+ swapoff -a
+
+ echo 0 > /sys/module/zswap/parameters/accept_threshold_percent
+ echo 0 > /sys/module/zswap/parameters/max_pool_percent
+ echo 0 > /sys/module/zswap/parameters/enabled
+
+Once zswap is disabled and no longer using iaa_crypto, the IAA wqs and
+devices can be disabled.
+
+.. _iaa_disable_script:
+
+IAA disable script
+------------------
+
+The below script automatically does that::
+
+ #!/bin/bash
+
+ echo "IAA devices:"
+ lspci -d:0cfe
+ echo "# IAA devices:"
+ lspci -d:0cfe | wc -l
+
+ #
+ # count iaa instances
+ #
+ iaa_dev_id="0cfe"
+ num_iaa=$(lspci -d:${iaa_dev_id} | wc -l)
+ echo "Found ${num_iaa} IAA instances"
+
+ #
+ # disable iaa wqs and devices
+ #
+ echo "Disable IAA"
+
+ for ((i = 1; i < ${num_iaa} * 2; i += 2)); do
+ echo disable wq iax${i}/wq${i}.0
+ accel-config disable-wq iax${i}/wq${i}.0
+ echo disable iaa iax${i}
+ accel-config disable-device iax${i}
+ done
+
+ echo "End Disable IAA"
+
+Finally, at this point the iaa_crypto module can be removed, which
+will unregister the current IAA crypto algorithms::
+
+ rmmod iaa_crypto
+
+
+memory_madvise.c (gcc -o memory_memadvise memory_madvise.c)::
+
+ #include <stdio.h>
+ #include <stdlib.h>
+ #include <string.h>
+ #include <unistd.h>
+ #include <sys/mman.h>
+ #include <linux/mman.h>
+
+ #ifndef MADV_PAGEOUT
+ #define MADV_PAGEOUT 21 /* force pages out immediately */
+ #endif
+
+ #define PG_SZ 4096
+
+ int main(int argc, char **argv)
+ {
+ int i, nr_pages = 1;
+ int64_t *dump_ptr;
+ char *addr, *a;
+ int loop = 1;
+
+ if (argc > 1)
+ nr_pages = atoi(argv[1]);
+
+ printf("Allocating %d pages to swap in/out\n", nr_pages);
+
+ /* allocate pages */
+ addr = mmap(NULL, nr_pages * PG_SZ, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
+ *addr = 1;
+
+ /* initialize data in page to all '*' chars */
+ memset(addr, '*', nr_pages * PG_SZ);
+
+ printf("Swapping out %d pages\n", nr_pages);
+
+ /* Tell kernel to swap it out */
+ madvise(addr, nr_pages * PG_SZ, MADV_PAGEOUT);
+
+ while (loop > 0) {
+ /* Wait for swap out to finish */
+ sleep(5);
+
+ a = addr;
+
+ printf("Swapping in %d pages\n", nr_pages);
+
+ /* Access the page ... this will swap it back in again */
+ for (i = 0; i < nr_pages; i++) {
+ if (a[0] != '*') {
+ printf("Bad data from decompress!!!!!\n");
+
+ dump_ptr = (int64_t *)a;
+ for (int j = 0; j < 100; j++) {
+ printf(" page %d data: %#llx\n", i, *dump_ptr);
+ dump_ptr++;
+ }
+ }
+
+ a += PG_SZ;
+ }
+
+ loop --;
+ }
+
+ printf("Swapped out and in %d pages\n", nr_pages);
+
+Appendix
+========
+
+.. _iaa_sysfs_config:
+
+IAA sysfs config interface
+--------------------------
+
+Below is a description of the IAA sysfs interface, which as mentioned
+in the main document, should only be used if you know exactly what you
+are doing. Even then, there's no compelling reason to use it directly
+since accel-config can do everything the sysfs interface can and in
+fact accel-config is based on it under the covers.
+
+The 'IAA config path' is /sys/bus/dsa/devices and contains
+subdirectories representing each IAA device, workqueue, engine, and
+group. Note that in the sysfs interface, the IAA devices are actually
+named using iax e.g. iax1, iax3, etc. (Note that IAA devices are the
+odd-numbered devices; the even-numbered devices are DSA devices and
+can be ignored for IAA).
+
+The 'IAA device bind path' is /sys/bus/dsa/drivers/idxd/bind and is
+the file that is written to enable an IAA device.
+
+The 'IAA workqueue bind path' is /sys/bus/dsa/drivers/crypto/bind and
+is the file that is written to enable an IAA workqueue.
+
+Similarly /sys/bus/dsa/drivers/idxd/unbind and
+/sys/bus/dsa/drivers/crypto/unbind are used to disable IAA devices and
+workqueues.
+
+The basic sequence of commands needed to set up the IAA devices and
+workqueues is:
+
+For each device::
+ 1) Disable any workqueues enabled on the device. For example to
+ disable workques 0 and 1 on IAA device 3::
+
+ # echo wq3.0 > /sys/bus/dsa/drivers/crypto/unbind
+ # echo wq3.1 > /sys/bus/dsa/drivers/crypto/unbind
+
+ 2) Disable the device. For example to disable IAA device 3::
+
+ # echo iax3 > /sys/bus/dsa/drivers/idxd/unbind
+
+ 3) configure the desired workqueues. For example, to configure
+ workqueue 3 on IAA device 3::
+
+ # echo dedicated > /sys/bus/dsa/devices/iax3/wq3.3/mode
+ # echo 128 > /sys/bus/dsa/devices/iax3/wq3.3/size
+ # echo 0 > /sys/bus/dsa/devices/iax3/wq3.3/group_id
+ # echo 10 > /sys/bus/dsa/devices/iax3/wq3.3/priority
+ # echo "kernel" > /sys/bus/dsa/devices/iax3/wq3.3/type
+ # echo "iaa_crypto" > /sys/bus/dsa/devices/iax3/wq3.3/name
+ # echo "crypto" > /sys/bus/dsa/devices/iax3/wq3.3/driver_name
+
+ 4) Enable the device. For example to enable IAA device 3::
+
+ # echo iax3 > /sys/bus/dsa/drivers/idxd/bind
+
+ 5) Enable the desired workqueues on the device. For example to
+ enable workques 0 and 1 on IAA device 3::
+
+ # echo wq3.0 > /sys/bus/dsa/drivers/crypto/bind
+ # echo wq3.1 > /sys/bus/dsa/drivers/crypto/bind
diff --git a/Documentation/driver-api/crypto/iaa/index.rst b/Documentation/driver-api/crypto/iaa/index.rst
new file mode 100644
index 000000000000..aa6837e27264
--- /dev/null
+++ b/Documentation/driver-api/crypto/iaa/index.rst
@@ -0,0 +1,20 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+=================================
+IAA (Intel Analytics Accelerator)
+=================================
+
+IAA provides hardware compression and decompression via the crypto
+API.
+
+.. toctree::
+ :maxdepth: 1
+
+ iaa-crypto
+
+.. only:: subproject and html
+
+ Indices
+ =======
+
+ * :ref:`genindex`
diff --git a/Documentation/driver-api/crypto/index.rst b/Documentation/driver-api/crypto/index.rst
new file mode 100644
index 000000000000..fb9709b98bea
--- /dev/null
+++ b/Documentation/driver-api/crypto/index.rst
@@ -0,0 +1,20 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+==============
+Crypto Drivers
+==============
+
+Documentation for crypto drivers that may need more involved setup and
+configuration.
+
+.. toctree::
+ :maxdepth: 1
+
+ iaa/index
+
+.. only:: subproject and html
+
+ Indices
+ =======
+
+ * :ref:`genindex`
diff --git a/Documentation/driver-api/cxl/index.rst b/Documentation/driver-api/cxl/index.rst
new file mode 100644
index 000000000000..036e49553542
--- /dev/null
+++ b/Documentation/driver-api/cxl/index.rst
@@ -0,0 +1,12 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+====================
+Compute Express Link
+====================
+
+.. toctree::
+ :maxdepth: 1
+
+ memory-devices
+
+.. only:: subproject and html
diff --git a/Documentation/driver-api/cxl/memory-devices.rst b/Documentation/driver-api/cxl/memory-devices.rst
new file mode 100644
index 000000000000..5149ecdc53c7
--- /dev/null
+++ b/Documentation/driver-api/cxl/memory-devices.rst
@@ -0,0 +1,383 @@
+.. SPDX-License-Identifier: GPL-2.0
+.. include:: <isonum.txt>
+
+===================================
+Compute Express Link Memory Devices
+===================================
+
+A Compute Express Link Memory Device is a CXL component that implements the
+CXL.mem protocol. It contains some amount of volatile memory, persistent memory,
+or both. It is enumerated as a PCI device for configuration and passing
+messages over an MMIO mailbox. Its contribution to the System Physical
+Address space is handled via HDM (Host Managed Device Memory) decoders
+that optionally define a device's contribution to an interleaved address
+range across multiple devices underneath a host-bridge or interleaved
+across host-bridges.
+
+CXL Bus: Theory of Operation
+============================
+Similar to how a RAID driver takes disk objects and assembles them into a new
+logical device, the CXL subsystem is tasked to take PCIe and ACPI objects and
+assemble them into a CXL.mem decode topology. The need for runtime configuration
+of the CXL.mem topology is also similar to RAID in that different environments
+with the same hardware configuration may decide to assemble the topology in
+contrasting ways. One may choose performance (RAID0) striping memory across
+multiple Host Bridges and endpoints while another may opt for fault tolerance
+and disable any striping in the CXL.mem topology.
+
+Platform firmware enumerates a menu of interleave options at the "CXL root port"
+(Linux term for the top of the CXL decode topology). From there, PCIe topology
+dictates which endpoints can participate in which Host Bridge decode regimes.
+Each PCIe Switch in the path between the root and an endpoint introduces a point
+at which the interleave can be split. For example platform firmware may say at a
+given range only decodes to 1 one Host Bridge, but that Host Bridge may in turn
+interleave cycles across multiple Root Ports. An intervening Switch between a
+port and an endpoint may interleave cycles across multiple Downstream Switch
+Ports, etc.
+
+Here is a sample listing of a CXL topology defined by 'cxl_test'. The 'cxl_test'
+module generates an emulated CXL topology of 2 Host Bridges each with 2 Root
+Ports. Each of those Root Ports are connected to 2-way switches with endpoints
+connected to those downstream ports for a total of 8 endpoints::
+
+ # cxl list -BEMPu -b cxl_test
+ {
+ "bus":"root3",
+ "provider":"cxl_test",
+ "ports:root3":[
+ {
+ "port":"port5",
+ "host":"cxl_host_bridge.1",
+ "ports:port5":[
+ {
+ "port":"port8",
+ "host":"cxl_switch_uport.1",
+ "endpoints:port8":[
+ {
+ "endpoint":"endpoint9",
+ "host":"mem2",
+ "memdev":{
+ "memdev":"mem2",
+ "pmem_size":"256.00 MiB (268.44 MB)",
+ "ram_size":"256.00 MiB (268.44 MB)",
+ "serial":"0x1",
+ "numa_node":1,
+ "host":"cxl_mem.1"
+ }
+ },
+ {
+ "endpoint":"endpoint15",
+ "host":"mem6",
+ "memdev":{
+ "memdev":"mem6",
+ "pmem_size":"256.00 MiB (268.44 MB)",
+ "ram_size":"256.00 MiB (268.44 MB)",
+ "serial":"0x5",
+ "numa_node":1,
+ "host":"cxl_mem.5"
+ }
+ }
+ ]
+ },
+ {
+ "port":"port12",
+ "host":"cxl_switch_uport.3",
+ "endpoints:port12":[
+ {
+ "endpoint":"endpoint17",
+ "host":"mem8",
+ "memdev":{
+ "memdev":"mem8",
+ "pmem_size":"256.00 MiB (268.44 MB)",
+ "ram_size":"256.00 MiB (268.44 MB)",
+ "serial":"0x7",
+ "numa_node":1,
+ "host":"cxl_mem.7"
+ }
+ },
+ {
+ "endpoint":"endpoint13",
+ "host":"mem4",
+ "memdev":{
+ "memdev":"mem4",
+ "pmem_size":"256.00 MiB (268.44 MB)",
+ "ram_size":"256.00 MiB (268.44 MB)",
+ "serial":"0x3",
+ "numa_node":1,
+ "host":"cxl_mem.3"
+ }
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "port":"port4",
+ "host":"cxl_host_bridge.0",
+ "ports:port4":[
+ {
+ "port":"port6",
+ "host":"cxl_switch_uport.0",
+ "endpoints:port6":[
+ {
+ "endpoint":"endpoint7",
+ "host":"mem1",
+ "memdev":{
+ "memdev":"mem1",
+ "pmem_size":"256.00 MiB (268.44 MB)",
+ "ram_size":"256.00 MiB (268.44 MB)",
+ "serial":"0",
+ "numa_node":0,
+ "host":"cxl_mem.0"
+ }
+ },
+ {
+ "endpoint":"endpoint14",
+ "host":"mem5",
+ "memdev":{
+ "memdev":"mem5",
+ "pmem_size":"256.00 MiB (268.44 MB)",
+ "ram_size":"256.00 MiB (268.44 MB)",
+ "serial":"0x4",
+ "numa_node":0,
+ "host":"cxl_mem.4"
+ }
+ }
+ ]
+ },
+ {
+ "port":"port10",
+ "host":"cxl_switch_uport.2",
+ "endpoints:port10":[
+ {
+ "endpoint":"endpoint16",
+ "host":"mem7",
+ "memdev":{
+ "memdev":"mem7",
+ "pmem_size":"256.00 MiB (268.44 MB)",
+ "ram_size":"256.00 MiB (268.44 MB)",
+ "serial":"0x6",
+ "numa_node":0,
+ "host":"cxl_mem.6"
+ }
+ },
+ {
+ "endpoint":"endpoint11",
+ "host":"mem3",
+ "memdev":{
+ "memdev":"mem3",
+ "pmem_size":"256.00 MiB (268.44 MB)",
+ "ram_size":"256.00 MiB (268.44 MB)",
+ "serial":"0x2",
+ "numa_node":0,
+ "host":"cxl_mem.2"
+ }
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+
+In that listing each "root", "port", and "endpoint" object correspond a kernel
+'struct cxl_port' object. A 'cxl_port' is a device that can decode CXL.mem to
+its descendants. So "root" claims non-PCIe enumerable platform decode ranges and
+decodes them to "ports", "ports" decode to "endpoints", and "endpoints"
+represent the decode from SPA (System Physical Address) to DPA (Device Physical
+Address).
+
+Continuing the RAID analogy, disks have both topology metadata and on device
+metadata that determine RAID set assembly. CXL Port topology and CXL Port link
+status is metadata for CXL.mem set assembly. The CXL Port topology is enumerated
+by the arrival of a CXL.mem device. I.e. unless and until the PCIe core attaches
+the cxl_pci driver to a CXL Memory Expander there is no role for CXL Port
+objects. Conversely for hot-unplug / removal scenarios, there is no need for
+the Linux PCI core to tear down switch-level CXL resources because the endpoint
+->remove() event cleans up the port data that was established to support that
+Memory Expander.
+
+The port metadata and potential decode schemes that a give memory device may
+participate can be determined via a command like::
+
+ # cxl list -BDMu -d root -m mem3
+ {
+ "bus":"root3",
+ "provider":"cxl_test",
+ "decoders:root3":[
+ {
+ "decoder":"decoder3.1",
+ "resource":"0x8030000000",
+ "size":"512.00 MiB (536.87 MB)",
+ "volatile_capable":true,
+ "nr_targets":2
+ },
+ {
+ "decoder":"decoder3.3",
+ "resource":"0x8060000000",
+ "size":"512.00 MiB (536.87 MB)",
+ "pmem_capable":true,
+ "nr_targets":2
+ },
+ {
+ "decoder":"decoder3.0",
+ "resource":"0x8020000000",
+ "size":"256.00 MiB (268.44 MB)",
+ "volatile_capable":true,
+ "nr_targets":1
+ },
+ {
+ "decoder":"decoder3.2",
+ "resource":"0x8050000000",
+ "size":"256.00 MiB (268.44 MB)",
+ "pmem_capable":true,
+ "nr_targets":1
+ }
+ ],
+ "memdevs:root3":[
+ {
+ "memdev":"mem3",
+ "pmem_size":"256.00 MiB (268.44 MB)",
+ "ram_size":"256.00 MiB (268.44 MB)",
+ "serial":"0x2",
+ "numa_node":0,
+ "host":"cxl_mem.2"
+ }
+ ]
+ }
+
+...which queries the CXL topology to ask "given CXL Memory Expander with a kernel
+device name of 'mem3' which platform level decode ranges may this device
+participate". A given expander can participate in multiple CXL.mem interleave
+sets simultaneously depending on how many decoder resource it has. In this
+example mem3 can participate in one or more of a PMEM interleave that spans to
+Host Bridges, a PMEM interleave that targets a single Host Bridge, a Volatile
+memory interleave that spans 2 Host Bridges, and a Volatile memory interleave
+that only targets a single Host Bridge.
+
+Conversely the memory devices that can participate in a given platform level
+decode scheme can be determined via a command like the following::
+
+ # cxl list -MDu -d 3.2
+ [
+ {
+ "memdevs":[
+ {
+ "memdev":"mem1",
+ "pmem_size":"256.00 MiB (268.44 MB)",
+ "ram_size":"256.00 MiB (268.44 MB)",
+ "serial":"0",
+ "numa_node":0,
+ "host":"cxl_mem.0"
+ },
+ {
+ "memdev":"mem5",
+ "pmem_size":"256.00 MiB (268.44 MB)",
+ "ram_size":"256.00 MiB (268.44 MB)",
+ "serial":"0x4",
+ "numa_node":0,
+ "host":"cxl_mem.4"
+ },
+ {
+ "memdev":"mem7",
+ "pmem_size":"256.00 MiB (268.44 MB)",
+ "ram_size":"256.00 MiB (268.44 MB)",
+ "serial":"0x6",
+ "numa_node":0,
+ "host":"cxl_mem.6"
+ },
+ {
+ "memdev":"mem3",
+ "pmem_size":"256.00 MiB (268.44 MB)",
+ "ram_size":"256.00 MiB (268.44 MB)",
+ "serial":"0x2",
+ "numa_node":0,
+ "host":"cxl_mem.2"
+ }
+ ]
+ },
+ {
+ "root decoders":[
+ {
+ "decoder":"decoder3.2",
+ "resource":"0x8050000000",
+ "size":"256.00 MiB (268.44 MB)",
+ "pmem_capable":true,
+ "nr_targets":1
+ }
+ ]
+ }
+ ]
+
+...where the naming scheme for decoders is "decoder<port_id>.<instance_id>".
+
+Driver Infrastructure
+=====================
+
+This section covers the driver infrastructure for a CXL memory device.
+
+CXL Memory Device
+-----------------
+
+.. kernel-doc:: drivers/cxl/pci.c
+ :doc: cxl pci
+
+.. kernel-doc:: drivers/cxl/pci.c
+ :internal:
+
+.. kernel-doc:: drivers/cxl/mem.c
+ :doc: cxl mem
+
+CXL Port
+--------
+.. kernel-doc:: drivers/cxl/port.c
+ :doc: cxl port
+
+CXL Core
+--------
+.. kernel-doc:: drivers/cxl/cxl.h
+ :doc: cxl objects
+
+.. kernel-doc:: drivers/cxl/cxl.h
+ :internal:
+
+.. kernel-doc:: drivers/cxl/core/port.c
+ :doc: cxl core
+
+.. kernel-doc:: drivers/cxl/core/port.c
+ :identifiers:
+
+.. kernel-doc:: drivers/cxl/core/pci.c
+ :doc: cxl core pci
+
+.. kernel-doc:: drivers/cxl/core/pci.c
+ :identifiers:
+
+.. kernel-doc:: drivers/cxl/core/pmem.c
+ :doc: cxl pmem
+
+.. kernel-doc:: drivers/cxl/core/regs.c
+ :doc: cxl registers
+
+.. kernel-doc:: drivers/cxl/core/mbox.c
+ :doc: cxl mbox
+
+CXL Regions
+-----------
+.. kernel-doc:: drivers/cxl/core/region.c
+ :doc: cxl core region
+
+.. kernel-doc:: drivers/cxl/core/region.c
+ :identifiers:
+
+External Interfaces
+===================
+
+CXL IOCTL Interface
+-------------------
+
+.. kernel-doc:: include/uapi/linux/cxl_mem.h
+ :doc: UAPI
+
+.. kernel-doc:: include/uapi/linux/cxl_mem.h
+ :internal:
diff --git a/Documentation/driver-api/dcdbas.rst b/Documentation/driver-api/dcdbas.rst
deleted file mode 100644
index 309cc57a7c1c..000000000000
--- a/Documentation/driver-api/dcdbas.rst
+++ /dev/null
@@ -1,99 +0,0 @@
-===================================
-Dell Systems Management Base Driver
-===================================
-
-Overview
-========
-
-The Dell Systems Management Base Driver provides a sysfs interface for
-systems management software such as Dell OpenManage to perform system
-management interrupts and host control actions (system power cycle or
-power off after OS shutdown) on certain Dell systems.
-
-Dell OpenManage requires this driver on the following Dell PowerEdge systems:
-300, 1300, 1400, 400SC, 500SC, 1500SC, 1550, 600SC, 1600SC, 650, 1655MC,
-700, and 750. Other Dell software such as the open source libsmbios project
-is expected to make use of this driver, and it may include the use of this
-driver on other Dell systems.
-
-The Dell libsmbios project aims towards providing access to as much BIOS
-information as possible. See http://linux.dell.com/libsmbios/main/ for
-more information about the libsmbios project.
-
-
-System Management Interrupt
-===========================
-
-On some Dell systems, systems management software must access certain
-management information via a system management interrupt (SMI). The SMI data
-buffer must reside in 32-bit address space, and the physical address of the
-buffer is required for the SMI. The driver maintains the memory required for
-the SMI and provides a way for the application to generate the SMI.
-The driver creates the following sysfs entries for systems management
-software to perform these system management interrupts::
-
- /sys/devices/platform/dcdbas/smi_data
- /sys/devices/platform/dcdbas/smi_data_buf_phys_addr
- /sys/devices/platform/dcdbas/smi_data_buf_size
- /sys/devices/platform/dcdbas/smi_request
-
-Systems management software must perform the following steps to execute
-a SMI using this driver:
-
-1) Lock smi_data.
-2) Write system management command to smi_data.
-3) Write "1" to smi_request to generate a calling interface SMI or
- "2" to generate a raw SMI.
-4) Read system management command response from smi_data.
-5) Unlock smi_data.
-
-
-Host Control Action
-===================
-
-Dell OpenManage supports a host control feature that allows the administrator
-to perform a power cycle or power off of the system after the OS has finished
-shutting down. On some Dell systems, this host control feature requires that
-a driver perform a SMI after the OS has finished shutting down.
-
-The driver creates the following sysfs entries for systems management software
-to schedule the driver to perform a power cycle or power off host control
-action after the system has finished shutting down:
-
-/sys/devices/platform/dcdbas/host_control_action
-/sys/devices/platform/dcdbas/host_control_smi_type
-/sys/devices/platform/dcdbas/host_control_on_shutdown
-
-Dell OpenManage performs the following steps to execute a power cycle or
-power off host control action using this driver:
-
-1) Write host control action to be performed to host_control_action.
-2) Write type of SMI that driver needs to perform to host_control_smi_type.
-3) Write "1" to host_control_on_shutdown to enable host control action.
-4) Initiate OS shutdown.
- (Driver will perform host control SMI when it is notified that the OS
- has finished shutting down.)
-
-
-Host Control SMI Type
-=====================
-
-The following table shows the value to write to host_control_smi_type to
-perform a power cycle or power off host control action:
-
-=================== =====================
-PowerEdge System Host Control SMI Type
-=================== =====================
- 300 HC_SMITYPE_TYPE1
- 1300 HC_SMITYPE_TYPE1
- 1400 HC_SMITYPE_TYPE2
- 500SC HC_SMITYPE_TYPE2
- 1500SC HC_SMITYPE_TYPE2
- 1550 HC_SMITYPE_TYPE2
- 600SC HC_SMITYPE_TYPE2
- 1600SC HC_SMITYPE_TYPE2
- 650 HC_SMITYPE_TYPE2
- 1655MC HC_SMITYPE_TYPE2
- 700 HC_SMITYPE_TYPE3
- 750 HC_SMITYPE_TYPE3
-=================== =====================
diff --git a/Documentation/driver-api/device-io.rst b/Documentation/driver-api/device-io.rst
index 0e389378f71d..d55384b106bd 100644
--- a/Documentation/driver-api/device-io.rst
+++ b/Documentation/driver-api/device-io.rst
@@ -36,14 +36,14 @@ are starting with one. Physical addresses are of type unsigned long.
This address should not be used directly. Instead, to get an address
suitable for passing to the accessor functions described below, you
-should call :c:func:`ioremap()`. An address suitable for accessing
+should call ioremap(). An address suitable for accessing
the device will be returned to you.
After you've finished using the device (say, in your module's exit
-routine), call :c:func:`iounmap()` in order to return the address
+routine), call iounmap() in order to return the address
space to the kernel. Most architectures allocate new address space each
-time you call :c:func:`ioremap()`, and they can run out unless you
-call :c:func:`iounmap()`.
+time you call ioremap(), and they can run out unless you
+call iounmap().
Accessing the device
--------------------
@@ -60,8 +60,8 @@ readb_relaxed(), readw_relaxed(), readl_relaxed(), readq_relaxed(),
writeb(), writew(), writel() and writeq().
Some devices (such as framebuffers) would like to use larger transfers than
-8 bytes at a time. For these devices, the :c:func:`memcpy_toio()`,
-:c:func:`memcpy_fromio()` and :c:func:`memset_io()` functions are
+8 bytes at a time. For these devices, the memcpy_toio(),
+memcpy_fromio() and memset_io() functions are
provided. Do not use memset or memcpy on IO addresses; they are not
guaranteed to copy data in order.
@@ -135,17 +135,383 @@ Accessing Port Space
Accesses to this space are provided through a set of functions which
allow 8-bit, 16-bit and 32-bit accesses; also known as byte, word and
-long. These functions are :c:func:`inb()`, :c:func:`inw()`,
-:c:func:`inl()`, :c:func:`outb()`, :c:func:`outw()` and
-:c:func:`outl()`.
+long. These functions are inb(), inw(),
+inl(), outb(), outw() and
+outl().
Some variants are provided for these functions. Some devices require
that accesses to their ports are slowed down. This functionality is
provided by appending a ``_p`` to the end of the function.
-There are also equivalents to memcpy. The :c:func:`ins()` and
-:c:func:`outs()` functions copy bytes, words or longs to the given
+There are also equivalents to memcpy. The ins() and
+outs() functions copy bytes, words or longs to the given
port.
+__iomem pointer tokens
+======================
+
+The data type for an MMIO address is an ``__iomem`` qualified pointer, such as
+``void __iomem *reg``. On most architectures it is a regular pointer that
+points to a virtual memory address and can be offset or dereferenced, but in
+portable code, it must only be passed from and to functions that explicitly
+operated on an ``__iomem`` token, in particular the ioremap() and
+readl()/writel() functions. The 'sparse' semantic code checker can be used to
+verify that this is done correctly.
+
+While on most architectures, ioremap() creates a page table entry for an
+uncached virtual address pointing to the physical MMIO address, some
+architectures require special instructions for MMIO, and the ``__iomem`` pointer
+just encodes the physical address or an offsettable cookie that is interpreted
+by readl()/writel().
+
+Differences between I/O access functions
+========================================
+
+readq(), readl(), readw(), readb(), writeq(), writel(), writew(), writeb()
+
+ These are the most generic accessors, providing serialization against other
+ MMIO accesses and DMA accesses as well as fixed endianness for accessing
+ little-endian PCI devices and on-chip peripherals. Portable device drivers
+ should generally use these for any access to ``__iomem`` pointers.
+
+ Note that posted writes are not strictly ordered against a spinlock, see
+ Documentation/driver-api/io_ordering.rst.
+
+readq_relaxed(), readl_relaxed(), readw_relaxed(), readb_relaxed(),
+writeq_relaxed(), writel_relaxed(), writew_relaxed(), writeb_relaxed()
+
+ On architectures that require an expensive barrier for serializing against
+ DMA, these "relaxed" versions of the MMIO accessors only serialize against
+ each other, but contain a less expensive barrier operation. A device driver
+ might use these in a particularly performance sensitive fast path, with a
+ comment that explains why the usage in a specific location is safe without
+ the extra barriers.
+
+ See memory-barriers.txt for a more detailed discussion on the precise ordering
+ guarantees of the non-relaxed and relaxed versions.
+
+ioread64(), ioread32(), ioread16(), ioread8(),
+iowrite64(), iowrite32(), iowrite16(), iowrite8()
+
+ These are an alternative to the normal readl()/writel() functions, with almost
+ identical behavior, but they can also operate on ``__iomem`` tokens returned
+ for mapping PCI I/O space with pci_iomap() or ioport_map(). On architectures
+ that require special instructions for I/O port access, this adds a small
+ overhead for an indirect function call implemented in lib/iomap.c, while on
+ other architectures, these are simply aliases.
+
+ioread64be(), ioread32be(), ioread16be()
+iowrite64be(), iowrite32be(), iowrite16be()
+
+ These behave in the same way as the ioread32()/iowrite32() family, but with
+ reversed byte order, for accessing devices with big-endian MMIO registers.
+ Device drivers that can operate on either big-endian or little-endian
+ registers may have to implement a custom wrapper function that picks one or
+ the other depending on which device was found.
+
+ Note: On some architectures, the normal readl()/writel() functions
+ traditionally assume that devices are the same endianness as the CPU, while
+ using a hardware byte-reverse on the PCI bus when running a big-endian kernel.
+ Drivers that use readl()/writel() this way are generally not portable, but
+ tend to be limited to a particular SoC.
+
+hi_lo_readq(), lo_hi_readq(), hi_lo_readq_relaxed(), lo_hi_readq_relaxed(),
+ioread64_lo_hi(), ioread64_hi_lo(), ioread64be_lo_hi(), ioread64be_hi_lo(),
+hi_lo_writeq(), lo_hi_writeq(), hi_lo_writeq_relaxed(), lo_hi_writeq_relaxed(),
+iowrite64_lo_hi(), iowrite64_hi_lo(), iowrite64be_lo_hi(), iowrite64be_hi_lo()
+
+ Some device drivers have 64-bit registers that cannot be accessed atomically
+ on 32-bit architectures but allow two consecutive 32-bit accesses instead.
+ Since it depends on the particular device which of the two halves has to be
+ accessed first, a helper is provided for each combination of 64-bit accessors
+ with either low/high or high/low word ordering. A device driver must include
+ either <linux/io-64-nonatomic-lo-hi.h> or <linux/io-64-nonatomic-hi-lo.h> to
+ get the function definitions along with helpers that redirect the normal
+ readq()/writeq() to them on architectures that do not provide 64-bit access
+ natively.
+
+__raw_readq(), __raw_readl(), __raw_readw(), __raw_readb(),
+__raw_writeq(), __raw_writel(), __raw_writew(), __raw_writeb()
+
+ These are low-level MMIO accessors without barriers or byteorder changes and
+ architecture specific behavior. Accesses are usually atomic in the sense that
+ a four-byte __raw_readl() does not get split into individual byte loads, but
+ multiple consecutive accesses can be combined on the bus. In portable code, it
+ is only safe to use these to access memory behind a device bus but not MMIO
+ registers, as there are no ordering guarantees with regard to other MMIO
+ accesses or even spinlocks. The byte order is generally the same as for normal
+ memory, so unlike the other functions, these can be used to copy data between
+ kernel memory and device memory.
+
+inl(), inw(), inb(), outl(), outw(), outb()
+
+ PCI I/O port resources traditionally require separate helpers as they are
+ implemented using special instructions on the x86 architecture. On most other
+ architectures, these are mapped to readl()/writel() style accessors
+ internally, usually pointing to a fixed area in virtual memory. Instead of an
+ ``__iomem`` pointer, the address is a 32-bit integer token to identify a port
+ number. PCI requires I/O port access to be non-posted, meaning that an outb()
+ must complete before the following code executes, while a normal writeb() may
+ still be in progress. On architectures that correctly implement this, I/O port
+ access is therefore ordered against spinlocks. Many non-x86 PCI host bridge
+ implementations and CPU architectures however fail to implement non-posted I/O
+ space on PCI, so they can end up being posted on such hardware.
+
+ In some architectures, the I/O port number space has a 1:1 mapping to
+ ``__iomem`` pointers, but this is not recommended and device drivers should
+ not rely on that for portability. Similarly, an I/O port number as described
+ in a PCI base address register may not correspond to the port number as seen
+ by a device driver. Portable drivers need to read the port number for the
+ resource provided by the kernel.
+
+ There are no direct 64-bit I/O port accessors, but pci_iomap() in combination
+ with ioread64/iowrite64 can be used instead.
+
+inl_p(), inw_p(), inb_p(), outl_p(), outw_p(), outb_p()
+
+ On ISA devices that require specific timing, the _p versions of the I/O
+ accessors add a small delay. On architectures that do not have ISA buses,
+ these are aliases to the normal inb/outb helpers.
+
+readsq, readsl, readsw, readsb
+writesq, writesl, writesw, writesb
+ioread64_rep, ioread32_rep, ioread16_rep, ioread8_rep
+iowrite64_rep, iowrite32_rep, iowrite16_rep, iowrite8_rep
+insl, insw, insb, outsl, outsw, outsb
+
+ These are helpers that access the same address multiple times, usually to copy
+ data between kernel memory byte stream and a FIFO buffer. Unlike the normal
+ MMIO accessors, these do not perform a byteswap on big-endian kernels, so the
+ first byte in the FIFO register corresponds to the first byte in the memory
+ buffer regardless of the architecture.
+
+Device memory mapping modes
+===========================
+
+Some architectures support multiple modes for mapping device memory.
+ioremap_*() variants provide a common abstraction around these
+architecture-specific modes, with a shared set of semantics.
+
+ioremap() is the most common mapping type, and is applicable to typical device
+memory (e.g. I/O registers). Other modes can offer weaker or stronger
+guarantees, if supported by the architecture. From most to least common, they
+are as follows:
+
+ioremap()
+---------
+
+The default mode, suitable for most memory-mapped devices, e.g. control
+registers. Memory mapped using ioremap() has the following characteristics:
+
+* Uncached - CPU-side caches are bypassed, and all reads and writes are handled
+ directly by the device
+* No speculative operations - the CPU may not issue a read or write to this
+ memory, unless the instruction that does so has been reached in committed
+ program flow.
+* No reordering - The CPU may not reorder accesses to this memory mapping with
+ respect to each other. On some architectures, this relies on barriers in
+ readl_relaxed()/writel_relaxed().
+* No repetition - The CPU may not issue multiple reads or writes for a single
+ program instruction.
+* No write-combining - Each I/O operation results in one discrete read or write
+ being issued to the device, and multiple writes are not combined into larger
+ writes. This may or may not be enforced when using __raw I/O accessors or
+ pointer dereferences.
+* Non-executable - The CPU is not allowed to speculate instruction execution
+ from this memory (it probably goes without saying, but you're also not
+ allowed to jump into device memory).
+
+On many platforms and buses (e.g. PCI), writes issued through ioremap()
+mappings are posted, which means that the CPU does not wait for the write to
+actually reach the target device before retiring the write instruction.
+
+On many platforms, I/O accesses must be aligned with respect to the access
+size; failure to do so will result in an exception or unpredictable results.
+
+ioremap_wc()
+------------
+
+Maps I/O memory as normal memory with write combining. Unlike ioremap(),
+
+* The CPU may speculatively issue reads from the device that the program
+ didn't actually execute, and may choose to basically read whatever it wants.
+* The CPU may reorder operations as long as the result is consistent from the
+ program's point of view.
+* The CPU may write to the same location multiple times, even when the program
+ issued a single write.
+* The CPU may combine several writes into a single larger write.
+
+This mode is typically used for video framebuffers, where it can increase
+performance of writes. It can also be used for other blocks of memory in
+devices (e.g. buffers or shared memory), but care must be taken as accesses are
+not guaranteed to be ordered with respect to normal ioremap() MMIO register
+accesses without explicit barriers.
+
+On a PCI bus, it is usually safe to use ioremap_wc() on MMIO areas marked as
+``IORESOURCE_PREFETCH``, but it may not be used on those without the flag.
+For on-chip devices, there is no corresponding flag, but a driver can use
+ioremap_wc() on a device that is known to be safe.
+
+ioremap_wt()
+------------
+
+Maps I/O memory as normal memory with write-through caching. Like ioremap_wc(),
+but also,
+
+* The CPU may cache writes issued to and reads from the device, and serve reads
+ from that cache.
+
+This mode is sometimes used for video framebuffers, where drivers still expect
+writes to reach the device in a timely manner (and not be stuck in the CPU
+cache), but reads may be served from the cache for efficiency. However, it is
+rarely useful these days, as framebuffer drivers usually perform writes only,
+for which ioremap_wc() is more efficient (as it doesn't needlessly trash the
+cache). Most drivers should not use this.
+
+ioremap_np()
+------------
+
+Like ioremap(), but explicitly requests non-posted write semantics. On some
+architectures and buses, ioremap() mappings have posted write semantics, which
+means that writes can appear to "complete" from the point of view of the
+CPU before the written data actually arrives at the target device. Writes are
+still ordered with respect to other writes and reads from the same device, but
+due to the posted write semantics, this is not the case with respect to other
+devices. ioremap_np() explicitly requests non-posted semantics, which means
+that the write instruction will not appear to complete until the device has
+received (and to some platform-specific extent acknowledged) the written data.
+
+This mapping mode primarily exists to cater for platforms with bus fabrics that
+require this particular mapping mode to work correctly. These platforms set the
+``IORESOURCE_MEM_NONPOSTED`` flag for a resource that requires ioremap_np()
+semantics and portable drivers should use an abstraction that automatically
+selects it where appropriate (see the `Higher-level ioremap abstractions`_
+section below).
+
+The bare ioremap_np() is only available on some architectures; on others, it
+always returns NULL. Drivers should not normally use it, unless they are
+platform-specific or they derive benefit from non-posted writes where
+supported, and can fall back to ioremap() otherwise. The normal approach to
+ensure posted write completion is to do a dummy read after a write as
+explained in `Accessing the device`_, which works with ioremap() on all
+platforms.
+
+ioremap_np() should never be used for PCI drivers. PCI memory space writes are
+always posted, even on architectures that otherwise implement ioremap_np().
+Using ioremap_np() for PCI BARs will at best result in posted write semantics,
+and at worst result in complete breakage.
+
+Note that non-posted write semantics are orthogonal to CPU-side ordering
+guarantees. A CPU may still choose to issue other reads or writes before a
+non-posted write instruction retires. See the previous section on MMIO access
+functions for details on the CPU side of things.
+
+ioremap_uc()
+------------
+
+ioremap_uc() is only meaningful on old x86-32 systems with the PAT extension,
+and on ia64 with its slightly unconventional ioremap() behavior, everywhere
+elss ioremap_uc() defaults to return NULL.
+
+
+Portable drivers should avoid the use of ioremap_uc(), use ioremap() instead.
+
+ioremap_cache()
+---------------
+
+ioremap_cache() effectively maps I/O memory as normal RAM. CPU write-back
+caches can be used, and the CPU is free to treat the device as if it were a
+block of RAM. This should never be used for device memory which has side
+effects of any kind, or which does not return the data previously written on
+read.
+
+It should also not be used for actual RAM, as the returned pointer is an
+``__iomem`` token. memremap() can be used for mapping normal RAM that is outside
+of the linear kernel memory area to a regular pointer.
+
+Portable drivers should avoid the use of ioremap_cache().
+
+Architecture example
+--------------------
+
+Here is how the above modes map to memory attribute settings on the ARM64
+architecture:
+
++------------------------+--------------------------------------------+
+| API | Memory region type and cacheability |
++------------------------+--------------------------------------------+
+| ioremap_np() | Device-nGnRnE |
++------------------------+--------------------------------------------+
+| ioremap() | Device-nGnRE |
++------------------------+--------------------------------------------+
+| ioremap_uc() | (not implemented) |
++------------------------+--------------------------------------------+
+| ioremap_wc() | Normal-Non Cacheable |
++------------------------+--------------------------------------------+
+| ioremap_wt() | (not implemented; fallback to ioremap) |
++------------------------+--------------------------------------------+
+| ioremap_cache() | Normal-Write-Back Cacheable |
++------------------------+--------------------------------------------+
+
+Higher-level ioremap abstractions
+=================================
+
+Instead of using the above raw ioremap() modes, drivers are encouraged to use
+higher-level APIs. These APIs may implement platform-specific logic to
+automatically choose an appropriate ioremap mode on any given bus, allowing for
+a platform-agnostic driver to work on those platforms without any special
+cases. At the time of this writing, the following ioremap() wrappers have such
+logic:
+
+devm_ioremap_resource()
+
+ Can automatically select ioremap_np() over ioremap() according to platform
+ requirements, if the ``IORESOURCE_MEM_NONPOSTED`` flag is set on the struct
+ resource. Uses devres to automatically unmap the resource when the driver
+ probe() function fails or a device in unbound from its driver.
+
+ Documented in Documentation/driver-api/driver-model/devres.rst.
+
+of_address_to_resource()
+
+ Automatically sets the ``IORESOURCE_MEM_NONPOSTED`` flag for platforms that
+ require non-posted writes for certain buses (see the nonposted-mmio and
+ posted-mmio device tree properties).
+
+of_iomap()
+
+ Maps the resource described in a ``reg`` property in the device tree, doing
+ all required translations. Automatically selects ioremap_np() according to
+ platform requirements, as above.
+
+pci_ioremap_bar(), pci_ioremap_wc_bar()
+
+ Maps the resource described in a PCI base address without having to extract
+ the physical address first.
+
+pci_iomap(), pci_iomap_wc()
+
+ Like pci_ioremap_bar()/pci_ioremap_bar(), but also works on I/O space when
+ used together with ioread32()/iowrite32() and similar accessors
+
+pcim_iomap()
+
+ Like pci_iomap(), but uses devres to automatically unmap the resource when
+ the driver probe() function fails or a device in unbound from its driver
+
+ Documented in Documentation/driver-api/driver-model/devres.rst.
+
+Not using these wrappers may make drivers unusable on certain platforms with
+stricter rules for mapping I/O memory.
+
+Generalizing Access to System and I/O Memory
+============================================
+
+.. kernel-doc:: include/linux/iosys-map.h
+ :doc: overview
+
+.. kernel-doc:: include/linux/iosys-map.h
+ :internal:
+
Public Functions Provided
=========================
diff --git a/Documentation/driver-api/device_connection.rst b/Documentation/driver-api/device_connection.rst
deleted file mode 100644
index ba364224c349..000000000000
--- a/Documentation/driver-api/device_connection.rst
+++ /dev/null
@@ -1,43 +0,0 @@
-==================
-Device connections
-==================
-
-Introduction
-------------
-
-Devices often have connections to other devices that are outside of the direct
-child/parent relationship. A serial or network communication controller, which
-could be a PCI device, may need to be able to get a reference to its PHY
-component, which could be attached for example to the I2C bus. Some device
-drivers need to be able to control the clocks or the GPIOs for their devices,
-and so on.
-
-Device connections are generic descriptions of any type of connection between
-two separate devices.
-
-Device connections alone do not create a dependency between the two devices.
-They are only descriptions which are not tied to either of the devices directly.
-A dependency between the two devices exists only if one of the two endpoint
-devices requests a reference to the other. The descriptions themselves can be
-defined in firmware (not yet supported) or they can be built-in.
-
-Usage
------
-
-Device connections should exist before device ``->probe`` callback is called for
-either endpoint device in the description. If the connections are defined in
-firmware, this is not a problem. It should be considered if the connection
-descriptions are "built-in", and need to be added separately.
-
-The connection description consists of the names of the two devices with the
-connection, i.e. the endpoints, and unique identifier for the connection which
-is needed if there are multiple connections between the two devices.
-
-After a description exists, the devices in it can request reference to the other
-endpoint device, or they can request the description itself.
-
-API
----
-
-.. kernel-doc:: drivers/base/devcon.c
- :functions: device_connection_find_match device_connection_find device_connection_add device_connection_remove
diff --git a/Documentation/driver-api/device_link.rst b/Documentation/driver-api/device_link.rst
index bc2d89af88ce..ee913ae16371 100644
--- a/Documentation/driver-api/device_link.rst
+++ b/Documentation/driver-api/device_link.rst
@@ -1,7 +1,3 @@
-.. |struct dev_pm_domain| replace:: :c:type:`struct dev_pm_domain <dev_pm_domain>`
-.. |struct generic_pm_domain| replace:: :c:type:`struct generic_pm_domain <generic_pm_domain>`
-
-
.. _device_link:
============
@@ -166,7 +162,7 @@ Examples
is the same as if the MMU was the parent of the master device.
The fact that both devices share the same power domain would normally
- suggest usage of a |struct dev_pm_domain| or |struct generic_pm_domain|,
+ suggest usage of a struct dev_pm_domain or struct generic_pm_domain,
however these are not independent devices that happen to share a power
switch, but rather the MMU device serves the busmaster device and is
useless without it. A device link creates a synthetic hierarchical
@@ -202,7 +198,7 @@ Examples
Alternatives
============
-* A |struct dev_pm_domain| can be used to override the bus,
+* A struct dev_pm_domain can be used to override the bus,
class or device type callbacks. It is intended for devices sharing
a single on/off switch, however it does not guarantee a specific
suspend/resume ordering, this needs to be implemented separately.
@@ -211,7 +207,7 @@ Alternatives
suspended. Furthermore it cannot be used to enforce a specific shutdown
ordering or a driver presence dependency.
-* A |struct generic_pm_domain| is a lot more heavyweight than a
+* A struct generic_pm_domain is a lot more heavyweight than a
device link and does not allow for shutdown ordering or driver presence
dependencies. It also cannot be used on ACPI systems.
@@ -321,5 +317,4 @@ State machine
API
===
-.. kernel-doc:: drivers/base/core.c
- :functions: device_link_add device_link_del device_link_remove
+See device_link_add(), device_link_del() and device_link_remove().
diff --git a/Documentation/driver-api/dma-buf.rst b/Documentation/driver-api/dma-buf.rst
index c78db28519f7..0c153d79ccc4 100644
--- a/Documentation/driver-api/dma-buf.rst
+++ b/Documentation/driver-api/dma-buf.rst
@@ -1,18 +1,34 @@
-Buffer Sharing and Synchronization
-==================================
+Buffer Sharing and Synchronization (dma-buf)
+============================================
The dma-buf subsystem provides the framework for sharing buffers for
hardware (DMA) access across multiple device drivers and subsystems, and
for synchronizing asynchronous hardware access.
-This is used, for example, by drm "prime" multi-GPU support, but is of
-course not limited to GPU use cases.
+As an example, it is used extensively by the DRM subsystem to exchange
+buffers between processes, contexts, library APIs within the same
+process, and also to exchange buffers with other subsystems such as
+V4L2.
+
+This document describes the way in which kernel subsystems can use and
+interact with the three main primitives offered by dma-buf:
+
+ - dma-buf, representing a sg_table and exposed to userspace as a file
+ descriptor to allow passing between processes, subsystems, devices,
+ etc;
+ - dma-fence, providing a mechanism to signal when an asynchronous
+ hardware operation has completed; and
+ - dma-resv, which manages a set of dma-fences for a particular dma-buf
+ allowing implicit (kernel-ordered) synchronization of work to
+ preserve the illusion of coherent access
+
+
+Userspace API principles and use
+--------------------------------
+
+For more details on how to design your subsystem's API for dma-buf use, please
+see Documentation/userspace-api/dma-buf-alloc-exchange.rst.
-The three main components of this are: (1) dma-buf, representing a
-sg_table and exposed to userspace as a file descriptor to allow passing
-between devices, (2) fence, which provides a mechanism to signal when
-one device as finished access, and (3) reservation, which manages the
-shared or exclusive fence(s) associated with the buffer.
Shared DMA Buffers
------------------
@@ -31,7 +47,7 @@ The exporter
- implements and manages operations in :c:type:`struct dma_buf_ops
<dma_buf_ops>` for the buffer,
- allows other users to share the buffer by using dma_buf sharing APIs,
- - manages the details of buffer allocation, wrapped int a :c:type:`struct
+ - manages the details of buffer allocation, wrapped in a :c:type:`struct
dma_buf <dma_buf>`,
- decides about the actual backing storage where this allocation happens,
- and takes care of any migration of scatterlist - for all (shared) users of
@@ -85,9 +101,12 @@ consider though:
- Memory mapping the contents of the DMA buffer is also supported. See the
discussion below on `CPU Access to DMA Buffer Objects`_ for the full details.
-- The DMA buffer FD is also pollable, see `Fence Poll Support`_ below for
+- The DMA buffer FD is also pollable, see `Implicit Fence Poll Support`_ below for
details.
+- The DMA buffer FD also supports a few dma-buf-specific ioctls, see
+ `DMA Buffer ioctls`_ below for details.
+
Basic Operation and Device DMA Access
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -100,11 +119,27 @@ CPU Access to DMA Buffer Objects
.. kernel-doc:: drivers/dma-buf/dma-buf.c
:doc: cpu access
-Fence Poll Support
+Implicit Fence Poll Support
+~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+.. kernel-doc:: drivers/dma-buf/dma-buf.c
+ :doc: implicit fence polling
+
+DMA-BUF statistics
~~~~~~~~~~~~~~~~~~
+.. kernel-doc:: drivers/dma-buf/dma-buf-sysfs-stats.c
+ :doc: overview
+
+DMA Buffer ioctls
+~~~~~~~~~~~~~~~~~
+
+.. kernel-doc:: include/uapi/linux/dma-buf.h
+
+DMA-BUF locking convention
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. kernel-doc:: drivers/dma-buf/dma-buf.c
- :doc: fence polling
+ :doc: locking convention
Kernel Functions and Structures Reference
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -133,6 +168,24 @@ DMA Fences
.. kernel-doc:: drivers/dma-buf/dma-fence.c
:doc: DMA fences overview
+DMA Fence Cross-Driver Contract
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+.. kernel-doc:: drivers/dma-buf/dma-fence.c
+ :doc: fence cross-driver contract
+
+DMA Fence Signalling Annotations
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+.. kernel-doc:: drivers/dma-buf/dma-fence.c
+ :doc: fence signalling annotation
+
+DMA Fence Deadline Hints
+~~~~~~~~~~~~~~~~~~~~~~~~
+
+.. kernel-doc:: drivers/dma-buf/dma-fence.c
+ :doc: deadline hints
+
DMA Fences Functions Reference
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -142,12 +195,6 @@ DMA Fences Functions Reference
.. kernel-doc:: include/linux/dma-fence.h
:internal:
-Seqno Hardware Fences
-~~~~~~~~~~~~~~~~~~~~~
-
-.. kernel-doc:: include/linux/seqno-fence.h
- :internal:
-
DMA Fence Array
~~~~~~~~~~~~~~~
@@ -157,8 +204,23 @@ DMA Fence Array
.. kernel-doc:: include/linux/dma-fence-array.h
:internal:
-DMA Fence uABI/Sync File
-~~~~~~~~~~~~~~~~~~~~~~~~
+DMA Fence Chain
+~~~~~~~~~~~~~~~
+
+.. kernel-doc:: drivers/dma-buf/dma-fence-chain.c
+ :export:
+
+.. kernel-doc:: include/linux/dma-fence-chain.h
+ :internal:
+
+DMA Fence unwrap
+~~~~~~~~~~~~~~~~
+
+.. kernel-doc:: include/linux/dma-fence-unwrap.h
+ :internal:
+
+DMA Fence Sync File
+~~~~~~~~~~~~~~~~~~~
.. kernel-doc:: drivers/dma-buf/sync_file.c
:export:
@@ -166,3 +228,155 @@ DMA Fence uABI/Sync File
.. kernel-doc:: include/linux/sync_file.h
:internal:
+DMA Fence Sync File uABI
+~~~~~~~~~~~~~~~~~~~~~~~~
+
+.. kernel-doc:: include/uapi/linux/sync_file.h
+ :internal:
+
+Indefinite DMA Fences
+~~~~~~~~~~~~~~~~~~~~~
+
+At various times struct dma_fence with an indefinite time until dma_fence_wait()
+finishes have been proposed. Examples include:
+
+* Future fences, used in HWC1 to signal when a buffer isn't used by the display
+ any longer, and created with the screen update that makes the buffer visible.
+ The time this fence completes is entirely under userspace's control.
+
+* Proxy fences, proposed to handle &drm_syncobj for which the fence has not yet
+ been set. Used to asynchronously delay command submission.
+
+* Userspace fences or gpu futexes, fine-grained locking within a command buffer
+ that userspace uses for synchronization across engines or with the CPU, which
+ are then imported as a DMA fence for integration into existing winsys
+ protocols.
+
+* Long-running compute command buffers, while still using traditional end of
+ batch DMA fences for memory management instead of context preemption DMA
+ fences which get reattached when the compute job is rescheduled.
+
+Common to all these schemes is that userspace controls the dependencies of these
+fences and controls when they fire. Mixing indefinite fences with normal
+in-kernel DMA fences does not work, even when a fallback timeout is included to
+protect against malicious userspace:
+
+* Only the kernel knows about all DMA fence dependencies, userspace is not aware
+ of dependencies injected due to memory management or scheduler decisions.
+
+* Only userspace knows about all dependencies in indefinite fences and when
+ exactly they will complete, the kernel has no visibility.
+
+Furthermore the kernel has to be able to hold up userspace command submission
+for memory management needs, which means we must support indefinite fences being
+dependent upon DMA fences. If the kernel also support indefinite fences in the
+kernel like a DMA fence, like any of the above proposal would, there is the
+potential for deadlocks.
+
+.. kernel-render:: DOT
+ :alt: Indefinite Fencing Dependency Cycle
+ :caption: Indefinite Fencing Dependency Cycle
+
+ digraph "Fencing Cycle" {
+ node [shape=box bgcolor=grey style=filled]
+ kernel [label="Kernel DMA Fences"]
+ userspace [label="userspace controlled fences"]
+ kernel -> userspace [label="memory management"]
+ userspace -> kernel [label="Future fence, fence proxy, ..."]
+
+ { rank=same; kernel userspace }
+ }
+
+This means that the kernel might accidentally create deadlocks
+through memory management dependencies which userspace is unaware of, which
+randomly hangs workloads until the timeout kicks in. Workloads, which from
+userspace's perspective, do not contain a deadlock. In such a mixed fencing
+architecture there is no single entity with knowledge of all dependencies.
+Therefore preventing such deadlocks from within the kernel is not possible.
+
+The only solution to avoid dependencies loops is by not allowing indefinite
+fences in the kernel. This means:
+
+* No future fences, proxy fences or userspace fences imported as DMA fences,
+ with or without a timeout.
+
+* No DMA fences that signal end of batchbuffer for command submission where
+ userspace is allowed to use userspace fencing or long running compute
+ workloads. This also means no implicit fencing for shared buffers in these
+ cases.
+
+Recoverable Hardware Page Faults Implications
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Modern hardware supports recoverable page faults, which has a lot of
+implications for DMA fences.
+
+First, a pending page fault obviously holds up the work that's running on the
+accelerator and a memory allocation is usually required to resolve the fault.
+But memory allocations are not allowed to gate completion of DMA fences, which
+means any workload using recoverable page faults cannot use DMA fences for
+synchronization. Synchronization fences controlled by userspace must be used
+instead.
+
+On GPUs this poses a problem, because current desktop compositor protocols on
+Linux rely on DMA fences, which means without an entirely new userspace stack
+built on top of userspace fences, they cannot benefit from recoverable page
+faults. Specifically this means implicit synchronization will not be possible.
+The exception is when page faults are only used as migration hints and never to
+on-demand fill a memory request. For now this means recoverable page
+faults on GPUs are limited to pure compute workloads.
+
+Furthermore GPUs usually have shared resources between the 3D rendering and
+compute side, like compute units or command submission engines. If both a 3D
+job with a DMA fence and a compute workload using recoverable page faults are
+pending they could deadlock:
+
+- The 3D workload might need to wait for the compute job to finish and release
+ hardware resources first.
+
+- The compute workload might be stuck in a page fault, because the memory
+ allocation is waiting for the DMA fence of the 3D workload to complete.
+
+There are a few options to prevent this problem, one of which drivers need to
+ensure:
+
+- Compute workloads can always be preempted, even when a page fault is pending
+ and not yet repaired. Not all hardware supports this.
+
+- DMA fence workloads and workloads which need page fault handling have
+ independent hardware resources to guarantee forward progress. This could be
+ achieved through e.g. through dedicated engines and minimal compute unit
+ reservations for DMA fence workloads.
+
+- The reservation approach could be further refined by only reserving the
+ hardware resources for DMA fence workloads when they are in-flight. This must
+ cover the time from when the DMA fence is visible to other threads up to
+ moment when fence is completed through dma_fence_signal().
+
+- As a last resort, if the hardware provides no useful reservation mechanics,
+ all workloads must be flushed from the GPU when switching between jobs
+ requiring DMA fences or jobs requiring page fault handling: This means all DMA
+ fences must complete before a compute job with page fault handling can be
+ inserted into the scheduler queue. And vice versa, before a DMA fence can be
+ made visible anywhere in the system, all compute workloads must be preempted
+ to guarantee all pending GPU page faults are flushed.
+
+- Only a fairly theoretical option would be to untangle these dependencies when
+ allocating memory to repair hardware page faults, either through separate
+ memory blocks or runtime tracking of the full dependency graph of all DMA
+ fences. This results very wide impact on the kernel, since resolving the page
+ on the CPU side can itself involve a page fault. It is much more feasible and
+ robust to limit the impact of handling hardware page faults to the specific
+ driver.
+
+Note that workloads that run on independent hardware like copy engines or other
+GPUs do not have any impact. This allows us to keep using DMA fences internally
+in the kernel even for resolving hardware page faults, e.g. by using copy
+engines to clear or copy memory needed to resolve the page fault.
+
+In some ways this page fault problem is a special case of the `Infinite DMA
+Fences` discussions: Infinite fences from compute workloads are allowed to
+depend on DMA fences, but not the other way around. And not even the page fault
+problem is new, because some other CPU thread in userspace might
+hit a page fault which holds up a userspace fence - supporting page faults on
+GPUs doesn't anything fundamentally new.
diff --git a/Documentation/driver-api/dmaengine/client.rst b/Documentation/driver-api/dmaengine/client.rst
index 2104830a99ae..ecf139f73da4 100644
--- a/Documentation/driver-api/dmaengine/client.rst
+++ b/Documentation/driver-api/dmaengine/client.rst
@@ -5,7 +5,7 @@ DMA Engine API Guide
Vinod Koul <vinod dot koul at intel.com>
.. note:: For DMA Engine usage in async_tx please see:
- ``Documentation/crypto/async-tx-api.txt``
+ ``Documentation/crypto/async-tx-api.rst``
Below is a guide to device driver writers on how to use the Slave-DMA API of the
@@ -86,7 +86,9 @@ The details of these operations are:
- interleaved_dma: This is common to Slave as well as M2M clients. For slave
address of devices' fifo could be already known to the driver.
Various types of operations could be expressed by setting
- appropriate values to the 'dma_interleaved_template' members.
+ appropriate values to the 'dma_interleaved_template' members. Cyclic
+ interleaved DMA transfers are also possible if supported by the channel by
+ setting the DMA_PREP_REPEAT transfer flag.
A non-NULL return of this transfer API represents a "descriptor" for
the given transaction.
@@ -118,7 +120,9 @@ The details of these operations are:
.. code-block:: c
- nr_sg = dma_map_sg(chan->device->dev, sgl, sg_len);
+ struct device *dma_dev = dmaengine_get_dma_device(chan);
+
+ nr_sg = dma_map_sg(dma_dev, sgl, sg_len);
if (nr_sg == 0)
/* error */
@@ -171,7 +175,7 @@ The details of these operations are:
driver can ask for the pointer, maximum size and the currently used size of
the metadata and can directly update or read it.
- Becasue the DMA driver manages the memory area containing the metadata,
+ Because the DMA driver manages the memory area containing the metadata,
clients must make sure that they do not try to access or get the pointer
after their transfer completion callback has run for the descriptor.
If no completion callback has been defined for the transfer, then the
diff --git a/Documentation/driver-api/dmaengine/dmatest.rst b/Documentation/driver-api/dmaengine/dmatest.rst
index ee268d445d38..e2a63cefd783 100644
--- a/Documentation/driver-api/dmaengine/dmatest.rst
+++ b/Documentation/driver-api/dmaengine/dmatest.rst
@@ -6,6 +6,16 @@ Andy Shevchenko <andriy.shevchenko@linux.intel.com>
This small document introduces how to test DMA drivers using dmatest module.
+The dmatest module tests DMA memcpy, memset, XOR and RAID6 P+Q operations using
+various lengths and various offsets into the source and destination buffers. It
+will initialize both buffers with a repeatable pattern and verify that the DMA
+engine copies the requested region and nothing more. It will also verify that
+the bytes aren't swapped around, and that the source buffer isn't modified.
+
+The dmatest module can be configured to test a specific channel. It can also
+test multiple channels at the same time, and it can start multiple threads
+competing for the same channel.
+
.. note::
The test suite works only on the channels that have at least one
capability of the following: DMA_MEMCPY (memory-to-memory), DMA_MEMSET
@@ -79,7 +89,7 @@ The following command returns the state of the test. ::
% cat /sys/module/dmatest/parameters/run
-To wait for test completion userpace can poll 'run' until it is false, or use
+To wait for test completion userspace can poll 'run' until it is false, or use
the wait parameter. Specifying 'wait=1' when loading the module causes module
initialization to pause until a test run has completed, while reading
/sys/module/dmatest/parameters/wait waits for any running test to complete
@@ -143,13 +153,14 @@ Part 5 - Handling channel allocation
Allocating Channels
-------------------
-Channels are required to be configured prior to starting the test run.
-Attempting to run the test without configuring the channels will fail.
+Channels do not need to be configured prior to starting a test run. Attempting
+to run the test without configuring the channels will result in testing any
+channels that are available.
Example::
% echo 1 > /sys/module/dmatest/parameters/run
- dmatest: Could not start test, no channels configured
+ dmatest: No channels configured, continue with any
Channels are registered using the "channel" parameter. Channels can be requested by their
name, once requested, the channel is registered and a pending thread is added to the test list.
diff --git a/Documentation/driver-api/dmaengine/provider.rst b/Documentation/driver-api/dmaengine/provider.rst
index 56e5833e8a07..ceac2a300e32 100644
--- a/Documentation/driver-api/dmaengine/provider.rst
+++ b/Documentation/driver-api/dmaengine/provider.rst
@@ -95,7 +95,7 @@ accommodates that API in some cases, and made some design choices to
ensure that it stayed compatible.
For more information on the Async TX API, please look the relevant
-documentation file in Documentation/crypto/async-tx-api.txt.
+documentation file in Documentation/crypto/async-tx-api.rst.
DMAEngine APIs
==============
@@ -162,6 +162,19 @@ Currently, the types available are:
- The device is able to do memory to memory copies
+ - No matter what the overall size of the combined chunks for source and
+ destination is, only as many bytes as the smallest of the two will be
+ transmitted. That means the number and size of the scatter-gather buffers in
+ both lists need not be the same, and that the operation functionally is
+ equivalent to a ``strncpy`` where the ``count`` argument equals the smallest
+ total size of the two scatter-gather list buffers.
+
+ - It's usually used for copying pixel data between host memory and
+ memory-mapped GPU device memory, such as found on modern PCI video graphics
+ cards. The most immediate example is the OpenGL API function
+ ``glReadPielx()``, which might require a verbatim copy of a huge framebuffer
+ from local device memory onto host memory.
+
- DMA_XOR
- The device is able to perform XOR operations on memory areas
@@ -183,6 +196,12 @@ Currently, the types available are:
- The device is able to perform parity check using RAID6 P+Q
algorithm against a memory buffer.
+- DMA_MEMSET
+
+ - The device is able to fill memory with the provided pattern
+
+ - The pattern is treated as a single byte signed value.
+
- DMA_INTERRUPT
- The device is able to trigger a dummy transfer that will
@@ -239,6 +258,43 @@ Currently, the types available are:
want to transfer a portion of uncompressed data directly to the
display to print it
+- DMA_COMPLETION_NO_ORDER
+
+ - The device does not support in order completion.
+
+ - The driver should return DMA_OUT_OF_ORDER for device_tx_status if
+ the device is setting this capability.
+
+ - All cookie tracking and checking API should be treated as invalid if
+ the device exports this capability.
+
+ - At this point, this is incompatible with polling option for dmatest.
+
+ - If this cap is set, the user is recommended to provide an unique
+ identifier for each descriptor sent to the DMA device in order to
+ properly track the completion.
+
+- DMA_REPEAT
+
+ - The device supports repeated transfers. A repeated transfer, indicated by
+ the DMA_PREP_REPEAT transfer flag, is similar to a cyclic transfer in that
+ it gets automatically repeated when it ends, but can additionally be
+ replaced by the client.
+
+ - This feature is limited to interleaved transfers, this flag should thus not
+ be set if the DMA_INTERLEAVE flag isn't set. This limitation is based on
+ the current needs of DMA clients, support for additional transfer types
+ should be added in the future if and when the need arises.
+
+- DMA_LOAD_EOT
+
+ - The device supports replacing repeated transfers at end of transfer (EOT)
+ by queuing a new transfer with the DMA_PREP_LOAD_EOT flag set.
+
+ - Support for replacing a currently running transfer at another point (such
+ as end of burst instead of end of transfer) will be added in the future
+ based on DMA clients needs, if and when the need arises.
+
These various types will also affect how the source and destination
addresses change over time.
@@ -397,7 +453,10 @@ supported.
- Should use dma_set_residue to report it
- In the case of a cyclic transfer, it should only take into
- account the current period.
+ account the total size of the cyclic buffer.
+
+ - Should return DMA_OUT_OF_ORDER if the device does not support in order
+ completion and is completing the operation out of order.
- This function can be called in an interrupt context.
@@ -488,7 +547,7 @@ dma_cookie_t
DMA_CTRL_ACK
- If clear, the descriptor cannot be reused by provider until the
- client acknowledges receipt, i.e. has has a chance to establish any
+ client acknowledges receipt, i.e. has a chance to establish any
dependency chains
- This can be acked by invoking async_tx_ack()
@@ -531,6 +590,34 @@ DMA_CTRL_REUSE
writes for which the descriptor should be in different format from
normal data descriptors.
+- DMA_PREP_REPEAT
+
+ - If set, the transfer will be automatically repeated when it ends until a
+ new transfer is queued on the same channel with the DMA_PREP_LOAD_EOT flag.
+ If the next transfer to be queued on the channel does not have the
+ DMA_PREP_LOAD_EOT flag set, the current transfer will be repeated until the
+ client terminates all transfers.
+
+ - This flag is only supported if the channel reports the DMA_REPEAT
+ capability.
+
+- DMA_PREP_LOAD_EOT
+
+ - If set, the transfer will replace the transfer currently being executed at
+ the end of the transfer.
+
+ - This is the default behaviour for non-repeated transfers, specifying
+ DMA_PREP_LOAD_EOT for non-repeated transfers will thus make no difference.
+
+ - When using repeated transfers, DMA clients will usually need to set the
+ DMA_PREP_LOAD_EOT flag on all transfers, otherwise the channel will keep
+ repeating the last repeated transfer and ignore the new transfers being
+ queued. Failure to set DMA_PREP_LOAD_EOT will appear as if the channel was
+ stuck on the previous transfer.
+
+ - This flag is only supported if the channel reports the DMA_LOAD_EOT
+ capability.
+
General Design Notes
====================
diff --git a/Documentation/driver-api/dpll.rst b/Documentation/driver-api/dpll.rst
new file mode 100644
index 000000000000..ea8d16600e16
--- /dev/null
+++ b/Documentation/driver-api/dpll.rst
@@ -0,0 +1,551 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+===============================
+The Linux kernel dpll subsystem
+===============================
+
+DPLL
+====
+
+PLL - Phase Locked Loop is an electronic circuit which syntonizes clock
+signal of a device with an external clock signal. Effectively enabling
+device to run on the same clock signal beat as provided on a PLL input.
+
+DPLL - Digital Phase Locked Loop is an integrated circuit which in
+addition to plain PLL behavior incorporates a digital phase detector
+and may have digital divider in the loop. As a result, the frequency on
+DPLL's input and output may be configurable.
+
+Subsystem
+=========
+
+The main purpose of dpll subsystem is to provide general interface
+to configure devices that use any kind of Digital PLL and could use
+different sources of input signal to synchronize to, as well as
+different types of outputs.
+The main interface is NETLINK_GENERIC based protocol with an event
+monitoring multicast group defined.
+
+Device object
+=============
+
+Single dpll device object means single Digital PLL circuit and bunch of
+connected pins.
+It reports the supported modes of operation and current status to the
+user in response to the `do` request of netlink command
+``DPLL_CMD_DEVICE_GET`` and list of dplls registered in the subsystem
+with `dump` netlink request of the same command.
+Changing the configuration of dpll device is done with `do` request of
+netlink ``DPLL_CMD_DEVICE_SET`` command.
+A device handle is ``DPLL_A_ID``, it shall be provided to get or set
+configuration of particular device in the system. It can be obtained
+with a ``DPLL_CMD_DEVICE_GET`` `dump` request or
+a ``DPLL_CMD_DEVICE_ID_GET`` `do` request, where the one must provide
+attributes that result in single device match.
+
+Pin object
+==========
+
+A pin is amorphic object which represents either input or output, it
+could be internal component of the device, as well as externally
+connected.
+The number of pins per dpll vary, but usually multiple pins shall be
+provided for a single dpll device.
+Pin's properties, capabilities and status is provided to the user in
+response to `do` request of netlink ``DPLL_CMD_PIN_GET`` command.
+It is also possible to list all the pins that were registered in the
+system with `dump` request of ``DPLL_CMD_PIN_GET`` command.
+Configuration of a pin can be changed by `do` request of netlink
+``DPLL_CMD_PIN_SET`` command.
+Pin handle is a ``DPLL_A_PIN_ID``, it shall be provided to get or set
+configuration of particular pin in the system. It can be obtained with
+``DPLL_CMD_PIN_GET`` `dump` request or ``DPLL_CMD_PIN_ID_GET`` `do`
+request, where user provides attributes that result in single pin match.
+
+Pin selection
+=============
+
+In general, selected pin (the one which signal is driving the dpll
+device) can be obtained from ``DPLL_A_PIN_STATE`` attribute, and only
+one pin shall be in ``DPLL_PIN_STATE_CONNECTED`` state for any dpll
+device.
+
+Pin selection can be done either manually or automatically, depending
+on hardware capabilities and active dpll device work mode
+(``DPLL_A_MODE`` attribute). The consequence is that there are
+differences for each mode in terms of available pin states, as well as
+for the states the user can request for a dpll device.
+
+In manual mode (``DPLL_MODE_MANUAL``) the user can request or receive
+one of following pin states:
+
+- ``DPLL_PIN_STATE_CONNECTED`` - the pin is used to drive dpll device
+- ``DPLL_PIN_STATE_DISCONNECTED`` - the pin is not used to drive dpll
+ device
+
+In automatic mode (``DPLL_MODE_AUTOMATIC``) the user can request or
+receive one of following pin states:
+
+- ``DPLL_PIN_STATE_SELECTABLE`` - the pin shall be considered as valid
+ input for automatic selection algorithm
+- ``DPLL_PIN_STATE_DISCONNECTED`` - the pin shall be not considered as
+ a valid input for automatic selection algorithm
+
+In automatic mode (``DPLL_MODE_AUTOMATIC``) the user can only receive
+pin state ``DPLL_PIN_STATE_CONNECTED`` once automatic selection
+algorithm locks a dpll device with one of the inputs.
+
+Shared pins
+===========
+
+A single pin object can be attached to multiple dpll devices.
+Then there are two groups of configuration knobs:
+
+1) Set on a pin - the configuration affects all dpll devices pin is
+ registered to (i.e., ``DPLL_A_PIN_FREQUENCY``),
+2) Set on a pin-dpll tuple - the configuration affects only selected
+ dpll device (i.e., ``DPLL_A_PIN_PRIO``, ``DPLL_A_PIN_STATE``,
+ ``DPLL_A_PIN_DIRECTION``).
+
+MUX-type pins
+=============
+
+A pin can be MUX-type, it aggregates child pins and serves as a pin
+multiplexer. One or more pins are registered with MUX-type instead of
+being directly registered to a dpll device.
+Pins registered with a MUX-type pin provide user with additional nested
+attribute ``DPLL_A_PIN_PARENT_PIN`` for each parent they were registered
+with.
+If a pin was registered with multiple parent pins, they behave like a
+multiple output multiplexer. In this case output of a
+``DPLL_CMD_PIN_GET`` would contain multiple pin-parent nested
+attributes with current state related to each parent, like::
+
+ 'pin': [{{
+ 'clock-id': 282574471561216,
+ 'module-name': 'ice',
+ 'capabilities': 4,
+ 'id': 13,
+ 'parent-pin': [
+ {'parent-id': 2, 'state': 'connected'},
+ {'parent-id': 3, 'state': 'disconnected'}
+ ],
+ 'type': 'synce-eth-port'
+ }}]
+
+Only one child pin can provide its signal to the parent MUX-type pin at
+a time, the selection is done by requesting change of a child pin state
+on desired parent, with the use of ``DPLL_A_PIN_PARENT`` nested
+attribute. Example of netlink `set state on parent pin` message format:
+
+ ========================== =============================================
+ ``DPLL_A_PIN_ID`` child pin id
+ ``DPLL_A_PIN_PARENT_PIN`` nested attribute for requesting configuration
+ related to parent pin
+ ``DPLL_A_PIN_PARENT_ID`` parent pin id
+ ``DPLL_A_PIN_STATE`` requested pin state on parent
+ ========================== =============================================
+
+Pin priority
+============
+
+Some devices might offer a capability of automatic pin selection mode
+(enum value ``DPLL_MODE_AUTOMATIC`` of ``DPLL_A_MODE`` attribute).
+Usually, automatic selection is performed on the hardware level, which
+means only pins directly connected to the dpll can be used for automatic
+input pin selection.
+In automatic selection mode, the user cannot manually select a input
+pin for the device, instead the user shall provide all directly
+connected pins with a priority ``DPLL_A_PIN_PRIO``, the device would
+pick a highest priority valid signal and use it to control the DPLL
+device. Example of netlink `set priority on parent pin` message format:
+
+ ============================ =============================================
+ ``DPLL_A_PIN_ID`` configured pin id
+ ``DPLL_A_PIN_PARENT_DEVICE`` nested attribute for requesting configuration
+ related to parent dpll device
+ ``DPLL_A_PIN_PARENT_ID`` parent dpll device id
+ ``DPLL_A_PIN_PRIO`` requested pin prio on parent dpll
+ ============================ =============================================
+
+Child pin of MUX-type pin is not capable of automatic input pin selection,
+in order to configure active input of a MUX-type pin, the user needs to
+request desired pin state of the child pin on the parent pin,
+as described in the ``MUX-type pins`` chapter.
+
+Phase offset measurement and adjustment
+========================================
+
+Device may provide ability to measure a phase difference between signals
+on a pin and its parent dpll device. If pin-dpll phase offset measurement
+is supported, it shall be provided with ``DPLL_A_PIN_PHASE_OFFSET``
+attribute for each parent dpll device.
+
+Device may also provide ability to adjust a signal phase on a pin.
+If pin phase adjustment is supported, minimal and maximal values that pin
+handle shall be provide to the user on ``DPLL_CMD_PIN_GET`` respond
+with ``DPLL_A_PIN_PHASE_ADJUST_MIN`` and ``DPLL_A_PIN_PHASE_ADJUST_MAX``
+attributes. Configured phase adjust value is provided with
+``DPLL_A_PIN_PHASE_ADJUST`` attribute of a pin, and value change can be
+requested with the same attribute with ``DPLL_CMD_PIN_SET`` command.
+
+ =============================== ======================================
+ ``DPLL_A_PIN_ID`` configured pin id
+ ``DPLL_A_PIN_PHASE_ADJUST_MIN`` attr minimum value of phase adjustment
+ ``DPLL_A_PIN_PHASE_ADJUST_MAX`` attr maximum value of phase adjustment
+ ``DPLL_A_PIN_PHASE_ADJUST`` attr configured value of phase
+ adjustment on parent dpll device
+ ``DPLL_A_PIN_PARENT_DEVICE`` nested attribute for requesting
+ configuration on given parent dpll
+ device
+ ``DPLL_A_PIN_PARENT_ID`` parent dpll device id
+ ``DPLL_A_PIN_PHASE_OFFSET`` attr measured phase difference
+ between a pin and parent dpll device
+ =============================== ======================================
+
+All phase related values are provided in pico seconds, which represents
+time difference between signals phase. The negative value means that
+phase of signal on pin is earlier in time than dpll's signal. Positive
+value means that phase of signal on pin is later in time than signal of
+a dpll.
+
+Phase adjust (also min and max) values are integers, but measured phase
+offset values are fractional with 3-digit decimal places and shell be
+divided with ``DPLL_PIN_PHASE_OFFSET_DIVIDER`` to get integer part and
+modulo divided to get fractional part.
+
+Configuration commands group
+============================
+
+Configuration commands are used to get information about registered
+dpll devices (and pins), as well as set configuration of device or pins.
+As dpll devices must be abstracted and reflect real hardware,
+there is no way to add new dpll device via netlink from user space and
+each device should be registered by its driver.
+
+All netlink commands require ``GENL_ADMIN_PERM``. This is to prevent
+any spamming/DoS from unauthorized userspace applications.
+
+List of netlink commands with possible attributes
+=================================================
+
+Constants identifying command types for dpll device uses a
+``DPLL_CMD_`` prefix and suffix according to command purpose.
+The dpll device related attributes use a ``DPLL_A_`` prefix and
+suffix according to attribute purpose.
+
+ ==================================== =================================
+ ``DPLL_CMD_DEVICE_ID_GET`` command to get device ID
+ ``DPLL_A_MODULE_NAME`` attr module name of registerer
+ ``DPLL_A_CLOCK_ID`` attr Unique Clock Identifier
+ (EUI-64), as defined by the
+ IEEE 1588 standard
+ ``DPLL_A_TYPE`` attr type of dpll device
+ ==================================== =================================
+
+ ==================================== =================================
+ ``DPLL_CMD_DEVICE_GET`` command to get device info or
+ dump list of available devices
+ ``DPLL_A_ID`` attr unique dpll device ID
+ ``DPLL_A_MODULE_NAME`` attr module name of registerer
+ ``DPLL_A_CLOCK_ID`` attr Unique Clock Identifier
+ (EUI-64), as defined by the
+ IEEE 1588 standard
+ ``DPLL_A_MODE`` attr selection mode
+ ``DPLL_A_MODE_SUPPORTED`` attr available selection modes
+ ``DPLL_A_LOCK_STATUS`` attr dpll device lock status
+ ``DPLL_A_TEMP`` attr device temperature info
+ ``DPLL_A_TYPE`` attr type of dpll device
+ ==================================== =================================
+
+ ==================================== =================================
+ ``DPLL_CMD_DEVICE_SET`` command to set dpll device config
+ ``DPLL_A_ID`` attr internal dpll device index
+ ``DPLL_A_MODE`` attr selection mode to configure
+ ==================================== =================================
+
+Constants identifying command types for pins uses a
+``DPLL_CMD_PIN_`` prefix and suffix according to command purpose.
+The pin related attributes use a ``DPLL_A_PIN_`` prefix and suffix
+according to attribute purpose.
+
+ ==================================== =================================
+ ``DPLL_CMD_PIN_ID_GET`` command to get pin ID
+ ``DPLL_A_PIN_MODULE_NAME`` attr module name of registerer
+ ``DPLL_A_PIN_CLOCK_ID`` attr Unique Clock Identifier
+ (EUI-64), as defined by the
+ IEEE 1588 standard
+ ``DPLL_A_PIN_BOARD_LABEL`` attr pin board label provided
+ by registerer
+ ``DPLL_A_PIN_PANEL_LABEL`` attr pin panel label provided
+ by registerer
+ ``DPLL_A_PIN_PACKAGE_LABEL`` attr pin package label provided
+ by registerer
+ ``DPLL_A_PIN_TYPE`` attr type of a pin
+ ==================================== =================================
+
+ ==================================== ==================================
+ ``DPLL_CMD_PIN_GET`` command to get pin info or dump
+ list of available pins
+ ``DPLL_A_PIN_ID`` attr unique a pin ID
+ ``DPLL_A_PIN_MODULE_NAME`` attr module name of registerer
+ ``DPLL_A_PIN_CLOCK_ID`` attr Unique Clock Identifier
+ (EUI-64), as defined by the
+ IEEE 1588 standard
+ ``DPLL_A_PIN_BOARD_LABEL`` attr pin board label provided
+ by registerer
+ ``DPLL_A_PIN_PANEL_LABEL`` attr pin panel label provided
+ by registerer
+ ``DPLL_A_PIN_PACKAGE_LABEL`` attr pin package label provided
+ by registerer
+ ``DPLL_A_PIN_TYPE`` attr type of a pin
+ ``DPLL_A_PIN_FREQUENCY`` attr current frequency of a pin
+ ``DPLL_A_PIN_FREQUENCY_SUPPORTED`` nested attr provides supported
+ frequencies
+ ``DPLL_A_PIN_ANY_FREQUENCY_MIN`` attr minimum value of frequency
+ ``DPLL_A_PIN_ANY_FREQUENCY_MAX`` attr maximum value of frequency
+ ``DPLL_A_PIN_PHASE_ADJUST_MIN`` attr minimum value of phase
+ adjustment
+ ``DPLL_A_PIN_PHASE_ADJUST_MAX`` attr maximum value of phase
+ adjustment
+ ``DPLL_A_PIN_PHASE_ADJUST`` attr configured value of phase
+ adjustment on parent device
+ ``DPLL_A_PIN_PARENT_DEVICE`` nested attr for each parent device
+ the pin is connected with
+ ``DPLL_A_PIN_PARENT_ID`` attr parent dpll device id
+ ``DPLL_A_PIN_PRIO`` attr priority of pin on the
+ dpll device
+ ``DPLL_A_PIN_STATE`` attr state of pin on the parent
+ dpll device
+ ``DPLL_A_PIN_DIRECTION`` attr direction of a pin on the
+ parent dpll device
+ ``DPLL_A_PIN_PHASE_OFFSET`` attr measured phase difference
+ between a pin and parent dpll
+ ``DPLL_A_PIN_PARENT_PIN`` nested attr for each parent pin
+ the pin is connected with
+ ``DPLL_A_PIN_PARENT_ID`` attr parent pin id
+ ``DPLL_A_PIN_STATE`` attr state of pin on the parent
+ pin
+ ``DPLL_A_PIN_CAPABILITIES`` attr bitmask of pin capabilities
+ ==================================== ==================================
+
+ ==================================== =================================
+ ``DPLL_CMD_PIN_SET`` command to set pins configuration
+ ``DPLL_A_PIN_ID`` attr unique a pin ID
+ ``DPLL_A_PIN_FREQUENCY`` attr requested frequency of a pin
+ ``DPLL_A_PIN_PHASE_ADJUST`` attr requested value of phase
+ adjustment on parent device
+ ``DPLL_A_PIN_PARENT_DEVICE`` nested attr for each parent dpll
+ device configuration request
+ ``DPLL_A_PIN_PARENT_ID`` attr parent dpll device id
+ ``DPLL_A_PIN_DIRECTION`` attr requested direction of a pin
+ ``DPLL_A_PIN_PRIO`` attr requested priority of pin on
+ the dpll device
+ ``DPLL_A_PIN_STATE`` attr requested state of pin on
+ the dpll device
+ ``DPLL_A_PIN_PARENT_PIN`` nested attr for each parent pin
+ configuration request
+ ``DPLL_A_PIN_PARENT_ID`` attr parent pin id
+ ``DPLL_A_PIN_STATE`` attr requested state of pin on
+ parent pin
+ ==================================== =================================
+
+Netlink dump requests
+=====================
+
+The ``DPLL_CMD_DEVICE_GET`` and ``DPLL_CMD_PIN_GET`` commands are
+capable of dump type netlink requests, in which case the response is in
+the same format as for their ``do`` request, but every device or pin
+registered in the system is returned.
+
+SET commands format
+===================
+
+``DPLL_CMD_DEVICE_SET`` - to target a dpll device, the user provides
+``DPLL_A_ID``, which is unique identifier of dpll device in the system,
+as well as parameter being configured (``DPLL_A_MODE``).
+
+``DPLL_CMD_PIN_SET`` - to target a pin user must provide a
+``DPLL_A_PIN_ID``, which is unique identifier of a pin in the system.
+Also configured pin parameters must be added.
+If ``DPLL_A_PIN_FREQUENCY`` is configured, this affects all the dpll
+devices that are connected with the pin, that is why frequency attribute
+shall not be enclosed in ``DPLL_A_PIN_PARENT_DEVICE``.
+Other attributes: ``DPLL_A_PIN_PRIO``, ``DPLL_A_PIN_STATE`` or
+``DPLL_A_PIN_DIRECTION`` must be enclosed in
+``DPLL_A_PIN_PARENT_DEVICE`` as their configuration relates to only one
+of parent dplls, targeted by ``DPLL_A_PIN_PARENT_ID`` attribute which is
+also required inside that nest.
+For MUX-type pins the ``DPLL_A_PIN_STATE`` attribute is configured in
+similar way, by enclosing required state in ``DPLL_A_PIN_PARENT_PIN``
+nested attribute and targeted parent pin id in ``DPLL_A_PIN_PARENT_ID``.
+
+In general, it is possible to configure multiple parameters at once, but
+internally each parameter change will be invoked separately, where order
+of configuration is not guaranteed by any means.
+
+Configuration pre-defined enums
+===============================
+
+.. kernel-doc:: include/uapi/linux/dpll.h
+
+Notifications
+=============
+
+dpll device can provide notifications regarding status changes of the
+device, i.e. lock status changes, input/output changes or other alarms.
+There is one multicast group that is used to notify user-space apps via
+netlink socket: ``DPLL_MCGRP_MONITOR``
+
+Notifications messages:
+
+ ============================== =====================================
+ ``DPLL_CMD_DEVICE_CREATE_NTF`` dpll device was created
+ ``DPLL_CMD_DEVICE_DELETE_NTF`` dpll device was deleted
+ ``DPLL_CMD_DEVICE_CHANGE_NTF`` dpll device has changed
+ ``DPLL_CMD_PIN_CREATE_NTF`` dpll pin was created
+ ``DPLL_CMD_PIN_DELETE_NTF`` dpll pin was deleted
+ ``DPLL_CMD_PIN_CHANGE_NTF`` dpll pin has changed
+ ============================== =====================================
+
+Events format is the same as for the corresponding get command.
+Format of ``DPLL_CMD_DEVICE_`` events is the same as response of
+``DPLL_CMD_DEVICE_GET``.
+Format of ``DPLL_CMD_PIN_`` events is same as response of
+``DPLL_CMD_PIN_GET``.
+
+Device driver implementation
+============================
+
+Device is allocated by dpll_device_get() call. Second call with the
+same arguments will not create new object but provides pointer to
+previously created device for given arguments, it also increases
+refcount of that object.
+Device is deallocated by dpll_device_put() call, which first
+decreases the refcount, once refcount is cleared the object is
+destroyed.
+
+Device should implement set of operations and register device via
+dpll_device_register() at which point it becomes available to the
+users. Multiple driver instances can obtain reference to it with
+dpll_device_get(), as well as register dpll device with their own
+ops and priv.
+
+The pins are allocated separately with dpll_pin_get(), it works
+similarly to dpll_device_get(). Function first creates object and then
+for each call with the same arguments only the object refcount
+increases. Also dpll_pin_put() works similarly to dpll_device_put().
+
+A pin can be registered with parent dpll device or parent pin, depending
+on hardware needs. Each registration requires registerer to provide set
+of pin callbacks, and private data pointer for calling them:
+
+- dpll_pin_register() - register pin with a dpll device,
+- dpll_pin_on_pin_register() - register pin with another MUX type pin.
+
+Notifications of adding or removing dpll devices are created within
+subsystem itself.
+Notifications about registering/deregistering pins are also invoked by
+the subsystem.
+Notifications about status changes either of dpll device or a pin are
+invoked in two ways:
+
+- after successful change was requested on dpll subsystem, the subsystem
+ calls corresponding notification,
+- requested by device driver with dpll_device_change_ntf() or
+ dpll_pin_change_ntf() when driver informs about the status change.
+
+The device driver using dpll interface is not required to implement all
+the callback operation. Nevertheless, there are few required to be
+implemented.
+Required dpll device level callback operations:
+
+- ``.mode_get``,
+- ``.lock_status_get``.
+
+Required pin level callback operations:
+
+- ``.state_on_dpll_get`` (pins registered with dpll device),
+- ``.state_on_pin_get`` (pins registered with parent pin),
+- ``.direction_get``.
+
+Every other operation handler is checked for existence and
+``-EOPNOTSUPP`` is returned in case of absence of specific handler.
+
+The simplest implementation is in the OCP TimeCard driver. The ops
+structures are defined like this:
+
+.. code-block:: c
+
+ static const struct dpll_device_ops dpll_ops = {
+ .lock_status_get = ptp_ocp_dpll_lock_status_get,
+ .mode_get = ptp_ocp_dpll_mode_get,
+ .mode_supported = ptp_ocp_dpll_mode_supported,
+ };
+
+ static const struct dpll_pin_ops dpll_pins_ops = {
+ .frequency_get = ptp_ocp_dpll_frequency_get,
+ .frequency_set = ptp_ocp_dpll_frequency_set,
+ .direction_get = ptp_ocp_dpll_direction_get,
+ .direction_set = ptp_ocp_dpll_direction_set,
+ .state_on_dpll_get = ptp_ocp_dpll_state_get,
+ };
+
+The registration part is then looks like this part:
+
+.. code-block:: c
+
+ clkid = pci_get_dsn(pdev);
+ bp->dpll = dpll_device_get(clkid, 0, THIS_MODULE);
+ if (IS_ERR(bp->dpll)) {
+ err = PTR_ERR(bp->dpll);
+ dev_err(&pdev->dev, "dpll_device_alloc failed\n");
+ goto out;
+ }
+
+ err = dpll_device_register(bp->dpll, DPLL_TYPE_PPS, &dpll_ops, bp);
+ if (err)
+ goto out;
+
+ for (i = 0; i < OCP_SMA_NUM; i++) {
+ bp->sma[i].dpll_pin = dpll_pin_get(clkid, i, THIS_MODULE, &bp->sma[i].dpll_prop);
+ if (IS_ERR(bp->sma[i].dpll_pin)) {
+ err = PTR_ERR(bp->dpll);
+ goto out_dpll;
+ }
+
+ err = dpll_pin_register(bp->dpll, bp->sma[i].dpll_pin, &dpll_pins_ops,
+ &bp->sma[i]);
+ if (err) {
+ dpll_pin_put(bp->sma[i].dpll_pin);
+ goto out_dpll;
+ }
+ }
+
+In the error path we have to rewind every allocation in the reverse order:
+
+.. code-block:: c
+
+ while (i) {
+ --i;
+ dpll_pin_unregister(bp->dpll, bp->sma[i].dpll_pin, &dpll_pins_ops, &bp->sma[i]);
+ dpll_pin_put(bp->sma[i].dpll_pin);
+ }
+ dpll_device_put(bp->dpll);
+
+More complex example can be found in Intel's ICE driver or nVidia's mlx5 driver.
+
+SyncE enablement
+================
+For SyncE enablement it is required to allow control over dpll device
+for a software application which monitors and configures the inputs of
+dpll device in response to current state of a dpll device and its
+inputs.
+In such scenario, dpll device input signal shall be also configurable
+to drive dpll with signal recovered from the PHY netdevice.
+This is done by exposing a pin to the netdevice - attaching pin to the
+netdevice itself with
+``dpll_netdev_pin_set(struct net_device *dev, struct dpll_pin *dpll_pin)``.
+Exposed pin id handle ``DPLL_A_PIN_ID`` is then identifiable by the user
+as it is attached to rtnetlink respond to get ``RTM_NEWLINK`` command in
+nested attribute ``IFLA_DPLL_PIN``.
diff --git a/Documentation/driver-api/driver-model/bus.rst b/Documentation/driver-api/driver-model/bus.rst
index 016b15a6e8ea..9709ab62a468 100644
--- a/Documentation/driver-api/driver-model/bus.rst
+++ b/Documentation/driver-api/driver-model/bus.rst
@@ -125,8 +125,8 @@ Exporting Attributes
struct bus_attribute {
struct attribute attr;
- ssize_t (*show)(struct bus_type *, char * buf);
- ssize_t (*store)(struct bus_type *, const char * buf, size_t count);
+ ssize_t (*show)(const struct bus_type *, char * buf);
+ ssize_t (*store)(const struct bus_type *, const char * buf, size_t count);
};
Bus drivers can export attributes using the BUS_ATTR_RW macro that works
diff --git a/Documentation/driver-api/driver-model/class.rst b/Documentation/driver-api/driver-model/class.rst
deleted file mode 100644
index fff55b80e86a..000000000000
--- a/Documentation/driver-api/driver-model/class.rst
+++ /dev/null
@@ -1,149 +0,0 @@
-==============
-Device Classes
-==============
-
-Introduction
-~~~~~~~~~~~~
-A device class describes a type of device, like an audio or network
-device. The following device classes have been identified:
-
-<Insert List of Device Classes Here>
-
-
-Each device class defines a set of semantics and a programming interface
-that devices of that class adhere to. Device drivers are the
-implementation of that programming interface for a particular device on
-a particular bus.
-
-Device classes are agnostic with respect to what bus a device resides
-on.
-
-
-Programming Interface
-~~~~~~~~~~~~~~~~~~~~~
-The device class structure looks like::
-
-
- typedef int (*devclass_add)(struct device *);
- typedef void (*devclass_remove)(struct device *);
-
-See the kerneldoc for the struct class.
-
-A typical device class definition would look like::
-
- struct device_class input_devclass = {
- .name = "input",
- .add_device = input_add_device,
- .remove_device = input_remove_device,
- };
-
-Each device class structure should be exported in a header file so it
-can be used by drivers, extensions and interfaces.
-
-Device classes are registered and unregistered with the core using::
-
- int devclass_register(struct device_class * cls);
- void devclass_unregister(struct device_class * cls);
-
-
-Devices
-~~~~~~~
-As devices are bound to drivers, they are added to the device class
-that the driver belongs to. Before the driver model core, this would
-typically happen during the driver's probe() callback, once the device
-has been initialized. It now happens after the probe() callback
-finishes from the core.
-
-The device is enumerated in the class. Each time a device is added to
-the class, the class's devnum field is incremented and assigned to the
-device. The field is never decremented, so if the device is removed
-from the class and re-added, it will receive a different enumerated
-value.
-
-The class is allowed to create a class-specific structure for the
-device and store it in the device's class_data pointer.
-
-There is no list of devices in the device class. Each driver has a
-list of devices that it supports. The device class has a list of
-drivers of that particular class. To access all of the devices in the
-class, iterate over the device lists of each driver in the class.
-
-
-Device Drivers
-~~~~~~~~~~~~~~
-Device drivers are added to device classes when they are registered
-with the core. A driver specifies the class it belongs to by setting
-the struct device_driver::devclass field.
-
-
-sysfs directory structure
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-There is a top-level sysfs directory named 'class'.
-
-Each class gets a directory in the class directory, along with two
-default subdirectories::
-
- class/
- `-- input
- |-- devices
- `-- drivers
-
-
-Drivers registered with the class get a symlink in the drivers/ directory
-that points to the driver's directory (under its bus directory)::
-
- class/
- `-- input
- |-- devices
- `-- drivers
- `-- usb:usb_mouse -> ../../../bus/drivers/usb_mouse/
-
-
-Each device gets a symlink in the devices/ directory that points to the
-device's directory in the physical hierarchy::
-
- class/
- `-- input
- |-- devices
- | `-- 1 -> ../../../root/pci0/00:1f.0/usb_bus/00:1f.2-1:0/
- `-- drivers
-
-
-Exporting Attributes
-~~~~~~~~~~~~~~~~~~~~
-
-::
-
- struct devclass_attribute {
- struct attribute attr;
- ssize_t (*show)(struct device_class *, char * buf, size_t count, loff_t off);
- ssize_t (*store)(struct device_class *, const char * buf, size_t count, loff_t off);
- };
-
-Class drivers can export attributes using the DEVCLASS_ATTR macro that works
-similarly to the DEVICE_ATTR macro for devices. For example, a definition
-like this::
-
- static DEVCLASS_ATTR(debug,0644,show_debug,store_debug);
-
-is equivalent to declaring::
-
- static devclass_attribute devclass_attr_debug;
-
-The bus driver can add and remove the attribute from the class's
-sysfs directory using::
-
- int devclass_create_file(struct device_class *, struct devclass_attribute *);
- void devclass_remove_file(struct device_class *, struct devclass_attribute *);
-
-In the example above, the file will be named 'debug' in placed in the
-class's directory in sysfs.
-
-
-Interfaces
-~~~~~~~~~~
-There may exist multiple mechanisms for accessing the same device of a
-particular class type. Device interfaces describe these mechanisms.
-
-When a device is added to a device class, the core attempts to add it
-to every interface that is registered with the device class.
diff --git a/Documentation/driver-api/driver-model/device.rst b/Documentation/driver-api/driver-model/device.rst
index 2b868d49d349..0833be568b06 100644
--- a/Documentation/driver-api/driver-model/device.rst
+++ b/Documentation/driver-api/driver-model/device.rst
@@ -50,10 +50,10 @@ Attributes
Attributes of devices can be exported by a device driver through sysfs.
-Please see Documentation/filesystems/sysfs.txt for more information
+Please see Documentation/filesystems/sysfs.rst for more information
on how sysfs works.
-As explained in Documentation/kobject.txt, device attributes must be
+As explained in Documentation/core-api/kobject.rst, device attributes must be
created before the KOBJ_ADD uevent is generated. The only way to realize
that is by defining an attribute group.
@@ -63,8 +63,14 @@ Attributes are declared using a macro called DEVICE_ATTR::
Example:::
- static DEVICE_ATTR(type, 0444, show_type, NULL);
- static DEVICE_ATTR(power, 0644, show_power, store_power);
+ static DEVICE_ATTR(type, 0444, type_show, NULL);
+ static DEVICE_ATTR(power, 0644, power_show, power_store);
+
+Helper macros are available for common values of mode, so the above examples
+can be simplified to:::
+
+ static DEVICE_ATTR_RO(type);
+ static DEVICE_ATTR_RW(power);
This declares two structures of type struct device_attribute with respective
names 'dev_attr_type' and 'dev_attr_power'. These two attributes can be
@@ -76,19 +82,24 @@ organized as follows into a group::
NULL,
};
- static struct attribute_group dev_attr_group = {
+ static struct attribute_group dev_group = {
.attrs = dev_attrs,
};
- static const struct attribute_group *dev_attr_groups[] = {
- &dev_attr_group,
+ static const struct attribute_group *dev_groups[] = {
+ &dev_group,
NULL,
};
+A helper macro is available for the common case of a single group, so the
+above two structures can be declared using:::
+
+ ATTRIBUTE_GROUPS(dev);
+
This array of groups can then be associated with a device by setting the
group pointer in struct device before device_register() is invoked::
- dev->groups = dev_attr_groups;
+ dev->groups = dev_groups;
device_register(dev);
The device_register() function will use the 'groups' pointer to create the
diff --git a/Documentation/driver-api/driver-model/devres.rst b/Documentation/driver-api/driver-model/devres.rst
index 46c13780994c..c5f99d834ec5 100644
--- a/Documentation/driver-api/driver-model/devres.rst
+++ b/Documentation/driver-api/driver-model/devres.rst
@@ -249,7 +249,7 @@ CLOCK
devm_clk_bulk_get()
devm_clk_bulk_get_all()
devm_clk_bulk_get_optional()
- devm_get_clk_from_childl()
+ devm_get_clk_from_child()
devm_clk_hw_register()
devm_of_clk_add_hw_provider()
devm_clk_hw_register_clkdev()
@@ -263,7 +263,7 @@ DMA
dmam_pool_destroy()
DRM
- devm_drm_dev_init()
+ devm_drm_dev_alloc()
GPIO
devm_gpiod_get()
@@ -277,28 +277,26 @@ GPIO
devm_gpiochip_add_data()
devm_gpio_request()
devm_gpio_request_one()
- devm_gpio_free()
I2C
+ devm_i2c_add_adapter()
devm_i2c_new_dummy_device()
IIO
devm_iio_device_alloc()
- devm_iio_device_free()
devm_iio_device_register()
- devm_iio_device_unregister()
- devm_iio_kfifo_allocate()
- devm_iio_kfifo_free()
+ devm_iio_dmaengine_buffer_setup()
+ devm_iio_kfifo_buffer_setup()
+ devm_iio_kfifo_buffer_setup_ext()
+ devm_iio_map_array_register()
devm_iio_triggered_buffer_setup()
- devm_iio_triggered_buffer_cleanup()
+ devm_iio_triggered_buffer_setup_ext()
devm_iio_trigger_alloc()
- devm_iio_trigger_free()
devm_iio_trigger_register()
- devm_iio_trigger_unregister()
devm_iio_channel_get()
- devm_iio_channel_release()
devm_iio_channel_get_all()
- devm_iio_channel_release_all()
+ devm_iio_hw_consumer_alloc()
+ devm_fwnode_iio_channel_get_by_name()
INPUT
devm_input_allocate_device()
@@ -308,6 +306,7 @@ IO region
devm_release_region()
devm_release_resource()
devm_request_mem_region()
+ devm_request_free_mem_region()
devm_request_region()
devm_request_resource()
@@ -320,13 +319,11 @@ IOMAP
devm_ioremap_resource() : checks resource, requests memory region, ioremaps
devm_ioremap_resource_wc()
devm_platform_ioremap_resource() : calls devm_ioremap_resource() for platform device
- devm_platform_ioremap_resource_wc()
devm_platform_ioremap_resource_byname()
+ devm_platform_get_and_ioremap_resource()
devm_iounmap()
- pcim_iomap()
- pcim_iomap_regions() : do request_region() and iomap() on multiple BARs
- pcim_iomap_table() : array of mapped addresses indexed by BAR
- pcim_iounmap()
+
+ Note: For the PCI devices the specific pcim_*() functions may be used, see below.
IRQ
devm_free_irq()
@@ -340,16 +337,20 @@ IRQ
devm_irq_alloc_descs_from()
devm_irq_alloc_generic_chip()
devm_irq_setup_generic_chip()
- devm_irq_sim_init()
+ devm_irq_domain_create_sim()
LED
devm_led_classdev_register()
+ devm_led_classdev_register_ext()
devm_led_classdev_unregister()
+ devm_led_trigger_register()
+ devm_of_led_get()
MDIO
devm_mdiobus_alloc()
devm_mdiobus_alloc_size()
- devm_mdiobus_free()
+ devm_mdiobus_register()
+ devm_of_mdiobus_register()
MEM
devm_free_pages()
@@ -360,7 +361,10 @@ MEM
devm_kmalloc()
devm_kmalloc_array()
devm_kmemdup()
+ devm_krealloc()
+ devm_krealloc_array()
devm_kstrdup()
+ devm_kstrdup_const()
devm_kvasprintf()
devm_kzalloc()
@@ -371,6 +375,12 @@ MUX
devm_mux_chip_alloc()
devm_mux_chip_register()
devm_mux_control_get()
+ devm_mux_state_get()
+
+NET
+ devm_alloc_etherdev()
+ devm_alloc_etherdev_mqs()
+ devm_register_netdev()
PER-CPU MEM
devm_alloc_percpu()
@@ -380,17 +390,29 @@ PCI
devm_pci_alloc_host_bridge() : managed PCI host bridge allocation
devm_pci_remap_cfgspace() : ioremap PCI configuration space
devm_pci_remap_cfg_resource() : ioremap PCI configuration space resource
+
pcim_enable_device() : after success, all PCI ops become managed
+ pcim_iomap() : do iomap() on a single BAR
+ pcim_iomap_regions() : do request_region() and iomap() on multiple BARs
+ pcim_iomap_regions_request_all() : do request_region() on all and iomap() on multiple BARs
+ pcim_iomap_table() : array of mapped addresses indexed by BAR
+ pcim_iounmap() : do iounmap() on a single BAR
+ pcim_iounmap_regions() : do iounmap() and release_region() on multiple BARs
pcim_pin_device() : keep PCI device enabled after release
+ pcim_set_mwi() : enable Memory-Write-Invalidate PCI transaction
PHY
devm_usb_get_phy()
+ devm_usb_get_phy_by_node()
+ devm_usb_get_phy_by_phandle()
devm_usb_put_phy()
PINCTRL
devm_pinctrl_get()
devm_pinctrl_put()
+ devm_pinctrl_get_select()
devm_pinctrl_register()
+ devm_pinctrl_register_and_init()
devm_pinctrl_unregister()
POWER
@@ -398,26 +420,48 @@ POWER
devm_reboot_mode_unregister()
PWM
+ devm_pwmchip_add()
devm_pwm_get()
- devm_pwm_put()
+ devm_fwnode_pwm_get()
REGULATOR
+ devm_regulator_bulk_register_supply_alias()
devm_regulator_bulk_get()
+ devm_regulator_bulk_get_const()
+ devm_regulator_bulk_get_enable()
+ devm_regulator_bulk_put()
devm_regulator_get()
+ devm_regulator_get_enable()
+ devm_regulator_get_enable_optional()
+ devm_regulator_get_exclusive()
+ devm_regulator_get_optional()
+ devm_regulator_irq_helper()
devm_regulator_put()
devm_regulator_register()
+ devm_regulator_register_notifier()
+ devm_regulator_register_supply_alias()
+ devm_regulator_unregister_notifier()
RESET
devm_reset_control_get()
devm_reset_controller_register()
+RTC
+ devm_rtc_device_register()
+ devm_rtc_allocate_device()
+ devm_rtc_register_device()
+ devm_rtc_nvmem_register()
+
SERDEV
devm_serdev_device_open()
SLAVE DMA ENGINE
devm_acpi_dma_controller_register()
+ devm_acpi_dma_controller_free()
SPI
+ devm_spi_alloc_master()
+ devm_spi_alloc_slave()
devm_spi_register_master()
WATCHDOG
diff --git a/Documentation/driver-api/driver-model/driver.rst b/Documentation/driver-api/driver-model/driver.rst
index 63887b813005..06f818b1d622 100644
--- a/Documentation/driver-api/driver-model/driver.rst
+++ b/Documentation/driver-api/driver-model/driver.rst
@@ -4,7 +4,6 @@ Device Drivers
See the kerneldoc for the struct device_driver.
-
Allocation
~~~~~~~~~~
@@ -167,9 +166,26 @@ the driver to that device.
A driver's probe() may return a negative errno value to indicate that
the driver did not bind to this device, in which case it should have
-released all resources it allocated::
+released all resources it allocated.
+
+Optionally, probe() may return -EPROBE_DEFER if the driver depends on
+resources that are not yet available (e.g., supplied by a driver that
+hasn't initialized yet). The driver core will put the device onto the
+deferred probe list and will try to call it again later. If a driver
+must defer, it should return -EPROBE_DEFER as early as possible to
+reduce the amount of time spent on setup work that will need to be
+unwound and reexecuted at a later time.
+
+.. warning::
+ -EPROBE_DEFER must not be returned if probe() has already created
+ child devices, even if those child devices are removed again
+ in a cleanup path. If -EPROBE_DEFER is returned after a child
+ device has been registered, it may result in an infinite loop of
+ .probe() calls to the same driver.
+
+::
- void (*sync_state)(struct device *dev);
+ void (*sync_state) (struct device *dev);
sync_state is called only once for a device. It's called when all the consumer
devices of the device have successfully probed. The list of consumers of the
@@ -224,11 +240,15 @@ not. It should free any resources allocated specifically for the
device; i.e. anything in the device's driver_data field.
If the device is still present, it should quiesce the device and place
-it into a supported low-power state::
+it into a supported low-power state.
+
+::
int (*suspend) (struct device *dev, pm_message_t state);
-suspend is called to put the device in a low power state::
+suspend is called to put the device in a low power state.
+
+::
int (*resume) (struct device *dev);
diff --git a/Documentation/driver-api/driver-model/index.rst b/Documentation/driver-api/driver-model/index.rst
index 755016422269..4831bdd92e5c 100644
--- a/Documentation/driver-api/driver-model/index.rst
+++ b/Documentation/driver-api/driver-model/index.rst
@@ -7,7 +7,6 @@ Driver Model
binding
bus
- class
design-patterns
device
devres
diff --git a/Documentation/driver-api/driver-model/overview.rst b/Documentation/driver-api/driver-model/overview.rst
index d4d1e9b40e0c..e98d0ab4a9b6 100644
--- a/Documentation/driver-api/driver-model/overview.rst
+++ b/Documentation/driver-api/driver-model/overview.rst
@@ -121,4 +121,4 @@ device-specific data or tunable interfaces.
More information about the sysfs directory layout can be found in
the other documents in this directory and in the file
-Documentation/filesystems/sysfs.txt.
+Documentation/filesystems/sysfs.rst.
diff --git a/Documentation/driver-api/driver-model/platform.rst b/Documentation/driver-api/driver-model/platform.rst
index 334dd4071ae4..1fe5c6c6199c 100644
--- a/Documentation/driver-api/driver-model/platform.rst
+++ b/Documentation/driver-api/driver-model/platform.rst
@@ -108,7 +108,7 @@ field to hold additional information.
Embedded systems frequently need one or more clocks for platform devices,
which are normally kept off until they're actively needed (to save power).
-System setup also associates those clocks with the device, so that that
+System setup also associates those clocks with the device, so that
calls to clk_get(&pdev->dev, clock_name) return them as needed.
diff --git a/Documentation/driver-api/early-userspace/early_userspace_support.rst b/Documentation/driver-api/early-userspace/early_userspace_support.rst
index 3deefb34046b..61bdeac1bae5 100644
--- a/Documentation/driver-api/early-userspace/early_userspace_support.rst
+++ b/Documentation/driver-api/early-userspace/early_userspace_support.rst
@@ -69,17 +69,17 @@ early userspace image can be built by an unprivileged user.
As a technical note, when directories and files are specified, the
entire CONFIG_INITRAMFS_SOURCE is passed to
-usr/gen_initramfs_list.sh. This means that CONFIG_INITRAMFS_SOURCE
+usr/gen_initramfs.sh. This means that CONFIG_INITRAMFS_SOURCE
can really be interpreted as any legal argument to
-gen_initramfs_list.sh. If a directory is specified as an argument then
+gen_initramfs.sh. If a directory is specified as an argument then
the contents are scanned, uid/gid translation is performed, and
usr/gen_init_cpio file directives are output. If a directory is
-specified as an argument to usr/gen_initramfs_list.sh then the
+specified as an argument to usr/gen_initramfs.sh then the
contents of the file are simply copied to the output. All of the output
directives from directory scanning and file contents copying are
processed by usr/gen_init_cpio.
-See also 'usr/gen_initramfs_list.sh -h'.
+See also 'usr/gen_initramfs.sh -h'.
Where's this all leading?
=========================
@@ -92,7 +92,7 @@ You can obtain somewhat infrequent snapshots of klibc from
https://www.kernel.org/pub/linux/libs/klibc/
For active users, you are better off using the klibc git
-repository, at http://git.kernel.org/?p=libs/klibc/klibc.git
+repository, at https://git.kernel.org/?p=libs/klibc/klibc.git
The standalone klibc distribution currently provides three components,
in addition to the klibc library:
@@ -122,7 +122,7 @@ and a number of other utilities, so you can replace kinit and build
custom initramfs images that meet your needs exactly.
For questions and help, you can sign up for the early userspace
-mailing list at http://www.zytor.com/mailman/listinfo/klibc
+mailing list at https://www.zytor.com/mailman/listinfo/klibc
How does it work?
=================
diff --git a/Documentation/driver-api/edac.rst b/Documentation/driver-api/edac.rst
index b8c742aa0a71..f4f044b95c4f 100644
--- a/Documentation/driver-api/edac.rst
+++ b/Documentation/driver-api/edac.rst
@@ -106,6 +106,16 @@ will occupy those chip-select rows.
This term is avoided because it is unclear when needing to distinguish
between chip-select rows and socket sets.
+* High Bandwidth Memory (HBM)
+
+HBM is a new memory type with low power consumption and ultra-wide
+communication lanes. It uses vertically stacked memory chips (DRAM dies)
+interconnected by microscopic wires called "through-silicon vias," or
+TSVs.
+
+Several stacks of HBM chips connect to the CPU or GPU through an ultra-fast
+interconnect called the "interposer". Therefore, HBM's characteristics
+are nearly indistinguishable from on-chip integrated RAM.
Memory Controllers
------------------
@@ -176,3 +186,113 @@ nodes::
the L1 and L2 directories would be "edac_device_block's"
.. kernel-doc:: drivers/edac/edac_device.h
+
+
+Heterogeneous system support
+----------------------------
+
+An AMD heterogeneous system is built by connecting the data fabrics of
+both CPUs and GPUs via custom xGMI links. Thus, the data fabric on the
+GPU nodes can be accessed the same way as the data fabric on CPU nodes.
+
+The MI200 accelerators are data center GPUs. They have 2 data fabrics,
+and each GPU data fabric contains four Unified Memory Controllers (UMC).
+Each UMC contains eight channels. Each UMC channel controls one 128-bit
+HBM2e (2GB) channel (equivalent to 8 X 2GB ranks). This creates a total
+of 4096-bits of DRAM data bus.
+
+While the UMC is interfacing a 16GB (8high X 2GB DRAM) HBM stack, each UMC
+channel is interfacing 2GB of DRAM (represented as rank).
+
+Memory controllers on AMD GPU nodes can be represented in EDAC thusly:
+
+ GPU DF / GPU Node -> EDAC MC
+ GPU UMC -> EDAC CSROW
+ GPU UMC channel -> EDAC CHANNEL
+
+For example: a heterogeneous system with 1 AMD CPU is connected to
+4 MI200 (Aldebaran) GPUs using xGMI.
+
+Some more heterogeneous hardware details:
+
+- The CPU UMC (Unified Memory Controller) is mostly the same as the GPU UMC.
+ They have chip selects (csrows) and channels. However, the layouts are different
+ for performance, physical layout, or other reasons.
+- CPU UMCs use 1 channel, In this case UMC = EDAC channel. This follows the
+ marketing speak. CPU has X memory channels, etc.
+- CPU UMCs use up to 4 chip selects, So UMC chip select = EDAC CSROW.
+- GPU UMCs use 1 chip select, So UMC = EDAC CSROW.
+- GPU UMCs use 8 channels, So UMC channel = EDAC channel.
+
+The EDAC subsystem provides a mechanism to handle AMD heterogeneous
+systems by calling system specific ops for both CPUs and GPUs.
+
+AMD GPU nodes are enumerated in sequential order based on the PCI
+hierarchy, and the first GPU node is assumed to have a Node ID value
+following those of the CPU nodes after latter are fully populated::
+
+ $ ls /sys/devices/system/edac/mc/
+ mc0 - CPU MC node 0
+ mc1 |
+ mc2 |- GPU card[0] => node 0(mc1), node 1(mc2)
+ mc3 |
+ mc4 |- GPU card[1] => node 0(mc3), node 1(mc4)
+ mc5 |
+ mc6 |- GPU card[2] => node 0(mc5), node 1(mc6)
+ mc7 |
+ mc8 |- GPU card[3] => node 0(mc7), node 1(mc8)
+
+For example, a heterogeneous system with one AMD CPU is connected to
+four MI200 (Aldebaran) GPUs using xGMI. This topology can be represented
+via the following sysfs entries::
+
+ /sys/devices/system/edac/mc/..
+
+ CPU # CPU node
+ ├── mc 0
+
+ GPU Nodes are enumerated sequentially after CPU nodes have been populated
+ GPU card 1 # Each MI200 GPU has 2 nodes/mcs
+ ├── mc 1 # GPU node 0 == mc1, Each MC node has 4 UMCs/CSROWs
+ │   ├── csrow 0 # UMC 0
+ │   │   ├── channel 0 # Each UMC has 8 channels
+ │   │   ├── channel 1 # size of each channel is 2 GB, so each UMC has 16 GB
+ │   │   ├── channel 2
+ │   │   ├── channel 3
+ │   │   ├── channel 4
+ │   │   ├── channel 5
+ │   │   ├── channel 6
+ │   │   ├── channel 7
+ │   ├── csrow 1 # UMC 1
+ │   │   ├── channel 0
+ │   │   ├── ..
+ │   │   ├── channel 7
+ │   ├── .. ..
+ │   ├── csrow 3 # UMC 3
+ │   │   ├── channel 0
+ │   │   ├── ..
+ │   │   ├── channel 7
+ │   ├── rank 0
+ │   ├── .. ..
+ │   ├── rank 31 # total 32 ranks/dimms from 4 UMCs
+ ├
+ ├── mc 2 # GPU node 1 == mc2
+ │   ├── .. # each GPU has total 64 GB
+
+ GPU card 2
+ ├── mc 3
+ │   ├── ..
+ ├── mc 4
+ │   ├── ..
+
+ GPU card 3
+ ├── mc 5
+ │   ├── ..
+ ├── mc 6
+ │   ├── ..
+
+ GPU card 4
+ ├── mc 7
+ │   ├── ..
+ ├── mc 8
+ │   ├── ..
diff --git a/Documentation/driver-api/eisa.rst b/Documentation/driver-api/eisa.rst
index c07565ba57da..3eac11b7eb01 100644
--- a/Documentation/driver-api/eisa.rst
+++ b/Documentation/driver-api/eisa.rst
@@ -189,7 +189,7 @@ eisa_bus.enable_dev
initialize the device in such conditions.
eisa_bus.disable_dev
- A comma-separated list of slots to be enabled, even if the firmware
+ A comma-separated list of slots to be disabled, even if the firmware
set the card as enabled. The driver won't be called to handle this
device.
diff --git a/Documentation/driver-api/firewire.rst b/Documentation/driver-api/firewire.rst
index 94a2d7f01d99..d3cfa73cbb2b 100644
--- a/Documentation/driver-api/firewire.rst
+++ b/Documentation/driver-api/firewire.rst
@@ -19,7 +19,7 @@ of kernel interfaces is available via exported symbols in `firewire-core` module
Firewire char device data structures
====================================
-.. include:: /ABI/stable/firewire-cdev
+.. include:: ../ABI/stable/firewire-cdev
:literal:
.. kernel-doc:: include/uapi/linux/firewire-cdev.h
@@ -28,7 +28,7 @@ Firewire char device data structures
Firewire device probing and sysfs interfaces
============================================
-.. include:: /ABI/stable/sysfs-bus-firewire
+.. include:: ../ABI/stable/sysfs-bus-firewire
:literal:
.. kernel-doc:: drivers/firewire/core-device.c
diff --git a/Documentation/driver-api/firmware/built-in-fw.rst b/Documentation/driver-api/firmware/built-in-fw.rst
index 396cdf591ac5..bc1c961bace1 100644
--- a/Documentation/driver-api/firmware/built-in-fw.rst
+++ b/Documentation/driver-api/firmware/built-in-fw.rst
@@ -28,6 +28,6 @@ able to make use of built-in firmware:
* Some firmware files may be really large in size. The remote-proc subsystem
is an example subsystem which deals with these sorts of firmware
* The firmware may need to be scraped out from some device specific location
- dynamically, an example is calibration data for for some WiFi chipsets. This
+ dynamically, an example is calibration data for some WiFi chipsets. This
calibration data can be unique per sold device.
diff --git a/Documentation/driver-api/firmware/core.rst b/Documentation/driver-api/firmware/core.rst
index 1d1688cbc078..803cd574bbd7 100644
--- a/Documentation/driver-api/firmware/core.rst
+++ b/Documentation/driver-api/firmware/core.rst
@@ -13,4 +13,5 @@ documents these features.
direct-fs-lookup
fallback-mechanisms
lookup-order
+ firmware-usage-guidelines
diff --git a/Documentation/driver-api/firmware/direct-fs-lookup.rst b/Documentation/driver-api/firmware/direct-fs-lookup.rst
index 82b4d585a213..e04353d1b06b 100644
--- a/Documentation/driver-api/firmware/direct-fs-lookup.rst
+++ b/Documentation/driver-api/firmware/direct-fs-lookup.rst
@@ -24,7 +24,7 @@ available. Stuffing the firmware into initramfs resolves this race issue,
however note that using initrd does not suffice to address the same race.
There are circumstances that justify not wanting to include firmware into
-initramfs, such as dealing with large firmware firmware files for the
+initramfs, such as dealing with large firmware files for the
remote-proc subsystem. For such cases using a userspace fallback mechanism
is currently the only viable solution as only userspace can know for sure
when the real rootfs is ready and mounted.
diff --git a/Documentation/driver-api/firmware/fallback-mechanisms.rst b/Documentation/driver-api/firmware/fallback-mechanisms.rst
index 036383dad6d6..5f04c3bcdf0c 100644
--- a/Documentation/driver-api/firmware/fallback-mechanisms.rst
+++ b/Documentation/driver-api/firmware/fallback-mechanisms.rst
@@ -42,6 +42,7 @@ fallback mechanism:
supported for request_firmware_into_buf().
* Firmware is not accessible through typical means:
+
* It cannot be installed into the root filesystem
* The firmware provides very unique device specific data tailored for
the unit gathered with local information. An example is calibration
diff --git a/Documentation/driver-api/firmware/firmware-usage-guidelines.rst b/Documentation/driver-api/firmware/firmware-usage-guidelines.rst
new file mode 100644
index 000000000000..fdcfce42c6d2
--- /dev/null
+++ b/Documentation/driver-api/firmware/firmware-usage-guidelines.rst
@@ -0,0 +1,44 @@
+===================
+Firmware Guidelines
+===================
+
+Users switching to a newer kernel should *not* have to install newer
+firmware files to keep their hardware working. At the same time updated
+firmware files must not cause any regressions for users of older kernel
+releases.
+
+Drivers that use firmware from linux-firmware should follow the rules in
+this guide. (Where there is limited control of the firmware,
+i.e. company doesn't support Linux, firmwares sourced from misc places,
+then of course these rules will not apply strictly.)
+
+* Firmware files shall be designed in a way that it allows checking for
+ firmware ABI version changes. It is recommended that firmware files be
+ versioned with at least a major/minor version. It is suggested that
+ the firmware files in linux-firmware be named with some device
+ specific name, and just the major version. The firmware version should
+ be stored in the firmware header, or as an exception, as part of the
+ firmware file name, in order to let the driver detact any non-ABI
+ fixes/changes. The firmware files in linux-firmware should be
+ overwritten with the newest compatible major version. Newer major
+ version firmware shall remain compatible with all kernels that load
+ that major number.
+
+* If the kernel support for the hardware is normally inactive, or the
+ hardware isn't available for public consumption, this can
+ be ignored, until the first kernel release that enables that hardware.
+ This means no major version bumps without the kernel retaining
+ backwards compatibility for the older major versions. Minor version
+ bumps should not introduce new features that newer kernels depend on
+ non-optionally.
+
+* If a security fix needs lockstep firmware and kernel fixes in order to
+ be successful, then all supported major versions in the linux-firmware
+ repo that are required by currently supported stable/LTS kernels,
+ should be updated with the security fix. The kernel patches should
+ detect if the firmware is new enough to declare if the security issue
+ is fixed. All communications around security fixes should point at
+ both the firmware and kernel fixes. If a security fix requires
+ deprecating old major versions, then this should only be done as a
+ last option, and be stated clearly in all communications.
+
diff --git a/Documentation/driver-api/firmware/firmware_cache.rst b/Documentation/driver-api/firmware/firmware_cache.rst
index c2e69d9c6bf1..417b9e8347f0 100644
--- a/Documentation/driver-api/firmware/firmware_cache.rst
+++ b/Documentation/driver-api/firmware/firmware_cache.rst
@@ -27,7 +27,7 @@ Some implementation details about the firmware cache setup:
uses all synchronous call except :c:func:`request_firmware_into_buf`.
* If an asynchronous call is used the firmware cache is only set up for a
- device if if the second argument (uevent) to request_firmware_nowait() is
+ device if the second argument (uevent) to request_firmware_nowait() is
true. When uevent is true it requests that a kobject uevent be sent to
userspace for the firmware request through the sysfs fallback mechanism
if the firmware file is not found.
diff --git a/Documentation/driver-api/firmware/fw_search_path.rst b/Documentation/driver-api/firmware/fw_search_path.rst
index a360f1009fa3..d7cb1e8f0076 100644
--- a/Documentation/driver-api/firmware/fw_search_path.rst
+++ b/Documentation/driver-api/firmware/fw_search_path.rst
@@ -22,5 +22,10 @@ can use the file:
* /sys/module/firmware_class/parameters/path
-You would echo into it your custom path and firmware requested will be
-searched for there first.
+You would echo into it your custom path and firmware requested will be searched
+for there first. Be aware that newline characters will be taken into account
+and may not produce the intended effects. For instance you might want to use:
+
+echo -n /path/to/script > /sys/module/firmware_class/parameters/path
+
+to ensure that your script is being used.
diff --git a/Documentation/driver-api/firmware/fw_upload.rst b/Documentation/driver-api/firmware/fw_upload.rst
new file mode 100644
index 000000000000..edf1d0c5e7c3
--- /dev/null
+++ b/Documentation/driver-api/firmware/fw_upload.rst
@@ -0,0 +1,127 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+===================
+Firmware Upload API
+===================
+
+A device driver that registers with the firmware loader will expose
+persistent sysfs nodes to enable users to initiate firmware updates for
+that device. It is the responsibility of the device driver and/or the
+device itself to perform any validation on the data received. Firmware
+upload uses the same *loading* and *data* sysfs files described in the
+documentation for firmware fallback. It also adds additional sysfs files
+to provide status on the transfer of the firmware image to the device.
+
+Register for firmware upload
+============================
+
+A device driver registers for firmware upload by calling
+firmware_upload_register(). Among the parameter list is a name to
+identify the device under /sys/class/firmware. A user may initiate a
+firmware upload by echoing a 1 to the *loading* sysfs file for the target
+device. Next, the user writes the firmware image to the *data* sysfs
+file. After writing the firmware data, the user echos 0 to the *loading*
+sysfs file to signal completion. Echoing 0 to *loading* also triggers the
+transfer of the firmware to the lower-lever device driver in the context
+of a kernel worker thread.
+
+To use the firmware upload API, write a driver that implements a set of
+ops. The probe function calls firmware_upload_register() and the remove
+function calls firmware_upload_unregister() such as::
+
+ static const struct fw_upload_ops m10bmc_ops = {
+ .prepare = m10bmc_sec_prepare,
+ .write = m10bmc_sec_write,
+ .poll_complete = m10bmc_sec_poll_complete,
+ .cancel = m10bmc_sec_cancel,
+ .cleanup = m10bmc_sec_cleanup,
+ };
+
+ static int m10bmc_sec_probe(struct platform_device *pdev)
+ {
+ const char *fw_name, *truncate;
+ struct m10bmc_sec *sec;
+ struct fw_upload *fwl;
+ unsigned int len;
+
+ sec = devm_kzalloc(&pdev->dev, sizeof(*sec), GFP_KERNEL);
+ if (!sec)
+ return -ENOMEM;
+
+ sec->dev = &pdev->dev;
+ sec->m10bmc = dev_get_drvdata(pdev->dev.parent);
+ dev_set_drvdata(&pdev->dev, sec);
+
+ fw_name = dev_name(sec->dev);
+ truncate = strstr(fw_name, ".auto");
+ len = (truncate) ? truncate - fw_name : strlen(fw_name);
+ sec->fw_name = kmemdup_nul(fw_name, len, GFP_KERNEL);
+
+ fwl = firmware_upload_register(THIS_MODULE, sec->dev, sec->fw_name,
+ &m10bmc_ops, sec);
+ if (IS_ERR(fwl)) {
+ dev_err(sec->dev, "Firmware Upload driver failed to start\n");
+ kfree(sec->fw_name);
+ return PTR_ERR(fwl);
+ }
+
+ sec->fwl = fwl;
+ return 0;
+ }
+
+ static int m10bmc_sec_remove(struct platform_device *pdev)
+ {
+ struct m10bmc_sec *sec = dev_get_drvdata(&pdev->dev);
+
+ firmware_upload_unregister(sec->fwl);
+ kfree(sec->fw_name);
+ return 0;
+ }
+
+firmware_upload_register
+------------------------
+.. kernel-doc:: drivers/base/firmware_loader/sysfs_upload.c
+ :identifiers: firmware_upload_register
+
+firmware_upload_unregister
+--------------------------
+.. kernel-doc:: drivers/base/firmware_loader/sysfs_upload.c
+ :identifiers: firmware_upload_unregister
+
+Firmware Upload Ops
+-------------------
+.. kernel-doc:: include/linux/firmware.h
+ :identifiers: fw_upload_ops
+
+Firmware Upload Progress Codes
+------------------------------
+The following progress codes are used internally by the firmware loader.
+Corresponding strings are reported through the status sysfs node that
+is described below and are documented in the ABI documentation.
+
+.. kernel-doc:: drivers/base/firmware_loader/sysfs_upload.h
+ :identifiers: fw_upload_prog
+
+Firmware Upload Error Codes
+---------------------------
+The following error codes may be returned by the driver ops in case of
+failure:
+
+.. kernel-doc:: include/linux/firmware.h
+ :identifiers: fw_upload_err
+
+Sysfs Attributes
+================
+
+In addition to the *loading* and *data* sysfs files, there are additional
+sysfs files to monitor the status of the data transfer to the target
+device and to determine the final pass/fail status of the transfer.
+Depending on the device and the size of the firmware image, a firmware
+update could take milliseconds or minutes.
+
+The additional sysfs files are:
+
+* status - provides an indication of the progress of a firmware update
+* error - provides error information for a failed firmware update
+* remaining_size - tracks the data transfer portion of an update
+* cancel - echo 1 to this file to cancel the update
diff --git a/Documentation/driver-api/firmware/index.rst b/Documentation/driver-api/firmware/index.rst
index 57415d657173..9d2c19dc8e36 100644
--- a/Documentation/driver-api/firmware/index.rst
+++ b/Documentation/driver-api/firmware/index.rst
@@ -8,6 +8,7 @@ Linux Firmware API
core
efi/index
request_firmware
+ fw_upload
other_interfaces
.. only:: subproject and html
diff --git a/Documentation/driver-api/firmware/other_interfaces.rst b/Documentation/driver-api/firmware/other_interfaces.rst
index b81794e0cfbb..06ac89adaafb 100644
--- a/Documentation/driver-api/firmware/other_interfaces.rst
+++ b/Documentation/driver-api/firmware/other_interfaces.rst
@@ -13,6 +13,12 @@ EDD Interfaces
.. kernel-doc:: drivers/firmware/edd.c
:internal:
+Generic System Framebuffers Interface
+-------------------------------------
+
+.. kernel-doc:: drivers/firmware/sysfb.c
+ :export:
+
Intel Stratix10 SoC Service Layer
---------------------------------
Some features of the Intel Stratix10 SoC require a level of privilege
diff --git a/Documentation/driver-api/firmware/request_firmware.rst b/Documentation/driver-api/firmware/request_firmware.rst
index cd076462d235..0d6ea0329995 100644
--- a/Documentation/driver-api/firmware/request_firmware.rst
+++ b/Documentation/driver-api/firmware/request_firmware.rst
@@ -76,5 +76,5 @@ firmware. For example if you used request_firmware() and it returns,
the driver has the firmware image accessible in fw_entry->{data,size}.
If something went wrong request_firmware() returns non-zero and fw_entry
is set to NULL. Once your driver is done with processing the firmware it
-can call call release_firmware(fw_entry) to release the firmware image
+can call release_firmware(fw_entry) to release the firmware image
and any related resource.
diff --git a/Documentation/driver-api/fpga/fpga-bridge.rst b/Documentation/driver-api/fpga/fpga-bridge.rst
index 71c5a40da320..604208534095 100644
--- a/Documentation/driver-api/fpga/fpga-bridge.rst
+++ b/Documentation/driver-api/fpga/fpga-bridge.rst
@@ -4,11 +4,10 @@ FPGA Bridge
API to implement a new FPGA bridge
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-* struct :c:type:`fpga_bridge` — The FPGA Bridge structure
-* struct :c:type:`fpga_bridge_ops` — Low level Bridge driver ops
-* :c:func:`devm_fpga_bridge_create()` — Allocate and init a bridge struct
-* :c:func:`fpga_bridge_register()` — Register a bridge
-* :c:func:`fpga_bridge_unregister()` — Unregister a bridge
+* struct fpga_bridge - The FPGA Bridge structure
+* struct fpga_bridge_ops - Low level Bridge driver ops
+* fpga_bridge_register() - Create and register a bridge
+* fpga_bridge_unregister() - Unregister a bridge
.. kernel-doc:: include/linux/fpga/fpga-bridge.h
:functions: fpga_bridge
@@ -17,9 +16,6 @@ API to implement a new FPGA bridge
:functions: fpga_bridge_ops
.. kernel-doc:: drivers/fpga/fpga-bridge.c
- :functions: devm_fpga_bridge_create
-
-.. kernel-doc:: drivers/fpga/fpga-bridge.c
:functions: fpga_bridge_register
.. kernel-doc:: drivers/fpga/fpga-bridge.c
diff --git a/Documentation/driver-api/fpga/fpga-mgr.rst b/Documentation/driver-api/fpga/fpga-mgr.rst
index 576f1945eacd..49c0a9512653 100644
--- a/Documentation/driver-api/fpga/fpga-mgr.rst
+++ b/Documentation/driver-api/fpga/fpga-mgr.rst
@@ -24,7 +24,7 @@ How to support a new FPGA device
--------------------------------
To add another FPGA manager, write a driver that implements a set of ops. The
-probe function calls fpga_mgr_register(), such as::
+probe function calls fpga_mgr_register() or fpga_mgr_register_full(), such as::
static const struct fpga_manager_ops socfpga_fpga_ops = {
.write_init = socfpga_fpga_ops_configure_init,
@@ -49,14 +49,14 @@ probe function calls fpga_mgr_register(), such as::
* them in priv
*/
- mgr = devm_fpga_mgr_create(dev, "Altera SOCFPGA FPGA Manager",
- &socfpga_fpga_ops, priv);
- if (!mgr)
- return -ENOMEM;
+ mgr = fpga_mgr_register(dev, "Altera SOCFPGA FPGA Manager",
+ &socfpga_fpga_ops, priv);
+ if (IS_ERR(mgr))
+ return PTR_ERR(mgr);
platform_set_drvdata(pdev, mgr);
- return fpga_mgr_register(mgr);
+ return 0;
}
static int socfpga_fpga_remove(struct platform_device *pdev)
@@ -68,18 +68,38 @@ probe function calls fpga_mgr_register(), such as::
return 0;
}
+Alternatively, the probe function could call one of the resource managed
+register functions, devm_fpga_mgr_register() or devm_fpga_mgr_register_full().
+When these functions are used, the parameter syntax is the same, but the call
+to fpga_mgr_unregister() should be removed. In the above example, the
+socfpga_fpga_remove() function would not be required.
The ops will implement whatever device specific register writes are needed to
do the programming sequence for this particular FPGA. These ops return 0 for
success or negative error codes otherwise.
The programming sequence is::
- 1. .write_init
- 2. .write or .write_sg (may be called once or multiple times)
- 3. .write_complete
-
-The .write_init function will prepare the FPGA to receive the image data. The
-buffer passed into .write_init will be at most .initial_header_size bytes long;
+ 1. .parse_header (optional, may be called once or multiple times)
+ 2. .write_init
+ 3. .write or .write_sg (may be called once or multiple times)
+ 4. .write_complete
+
+The .parse_header function will set header_size and data_size to
+struct fpga_image_info. Before parse_header call, header_size is initialized
+with initial_header_size. If flag skip_header of fpga_manager_ops is true,
+.write function will get image buffer starting at header_size offset from the
+beginning. If data_size is set, .write function will get data_size bytes of
+the image buffer, otherwise .write will get data up to the end of image buffer.
+This will not affect .write_sg, .write_sg will still get whole image in
+sg_table form. If FPGA image is already mapped as a single contiguous buffer,
+whole buffer will be passed into .parse_header. If image is in scatter-gather
+form, core code will buffer up at least .initial_header_size before the first
+call of .parse_header, if it is not enough, .parse_header should set desired
+size into info->header_size and return -EAGAIN, then it will be called again
+with greater part of image buffer on the input.
+
+The .write_init function will prepare the FPGA to receive the image data. The
+buffer passed into .write_init will be at least info->header_size bytes long;
if the whole bitstream is not immediately available then the core code will
buffer up at least this much before starting.
@@ -101,12 +121,18 @@ in state.
API for implementing a new FPGA Manager driver
----------------------------------------------
-* ``fpga_mgr_states`` — Values for :c:member:`fpga_manager->state`.
-* struct :c:type:`fpga_manager` — the FPGA manager struct
-* struct :c:type:`fpga_manager_ops` — Low level FPGA manager driver ops
-* :c:func:`devm_fpga_mgr_create` — Allocate and init a manager struct
-* :c:func:`fpga_mgr_register` — Register an FPGA manager
-* :c:func:`fpga_mgr_unregister` — Unregister an FPGA manager
+* ``fpga_mgr_states`` - Values for :c:expr:`fpga_manager->state`.
+* struct fpga_manager - the FPGA manager struct
+* struct fpga_manager_ops - Low level FPGA manager driver ops
+* struct fpga_manager_info - Parameter structure for fpga_mgr_register_full()
+* fpga_mgr_register_full() - Create and register an FPGA manager using the
+ fpga_mgr_info structure to provide the full flexibility of options
+* fpga_mgr_register() - Create and register an FPGA manager using standard
+ arguments
+* devm_fpga_mgr_register_full() - Resource managed version of
+ fpga_mgr_register_full()
+* devm_fpga_mgr_register() - Resource managed version of fpga_mgr_register()
+* fpga_mgr_unregister() - Unregister an FPGA manager
.. kernel-doc:: include/linux/fpga/fpga-mgr.h
:functions: fpga_mgr_states
@@ -117,11 +143,20 @@ API for implementing a new FPGA Manager driver
.. kernel-doc:: include/linux/fpga/fpga-mgr.h
:functions: fpga_manager_ops
+.. kernel-doc:: include/linux/fpga/fpga-mgr.h
+ :functions: fpga_manager_info
+
.. kernel-doc:: drivers/fpga/fpga-mgr.c
- :functions: devm_fpga_mgr_create
+ :functions: fpga_mgr_register_full
.. kernel-doc:: drivers/fpga/fpga-mgr.c
:functions: fpga_mgr_register
.. kernel-doc:: drivers/fpga/fpga-mgr.c
+ :functions: devm_fpga_mgr_register_full
+
+.. kernel-doc:: drivers/fpga/fpga-mgr.c
+ :functions: devm_fpga_mgr_register
+
+.. kernel-doc:: drivers/fpga/fpga-mgr.c
:functions: fpga_mgr_unregister
diff --git a/Documentation/driver-api/fpga/fpga-programming.rst b/Documentation/driver-api/fpga/fpga-programming.rst
index b5484df6ff0f..fb4da4240e96 100644
--- a/Documentation/driver-api/fpga/fpga-programming.rst
+++ b/Documentation/driver-api/fpga/fpga-programming.rst
@@ -6,22 +6,22 @@ Overview
The in-kernel API for FPGA programming is a combination of APIs from
FPGA manager, bridge, and regions. The actual function used to
-trigger FPGA programming is :c:func:`fpga_region_program_fpga()`.
+trigger FPGA programming is fpga_region_program_fpga().
-:c:func:`fpga_region_program_fpga()` uses functionality supplied by
+fpga_region_program_fpga() uses functionality supplied by
the FPGA manager and bridges. It will:
* lock the region's mutex
* lock the mutex of the region's FPGA manager
* build a list of FPGA bridges if a method has been specified to do so
* disable the bridges
- * program the FPGA using info passed in :c:member:`fpga_region->info`.
+ * program the FPGA using info passed in :c:expr:`fpga_region->info`.
* re-enable the bridges
* release the locks
The struct fpga_image_info specifies what FPGA image to program. It is
-allocated/freed by :c:func:`fpga_image_info_alloc()` and freed with
-:c:func:`fpga_image_info_free()`
+allocated/freed by fpga_image_info_alloc() and freed with
+fpga_image_info_free()
How to program an FPGA using a region
-------------------------------------
@@ -84,10 +84,10 @@ will generate that list. Here's some sample code of what to do next::
API for programming an FPGA
---------------------------
-* :c:func:`fpga_region_program_fpga` — Program an FPGA
-* :c:type:`fpga_image_info` — Specifies what FPGA image to program
-* :c:func:`fpga_image_info_alloc()` — Allocate an FPGA image info struct
-* :c:func:`fpga_image_info_free()` — Free an FPGA image info struct
+* fpga_region_program_fpga() - Program an FPGA
+* fpga_image_info() - Specifies what FPGA image to program
+* fpga_image_info_alloc() - Allocate an FPGA image info struct
+* fpga_image_info_free() - Free an FPGA image info struct
.. kernel-doc:: drivers/fpga/fpga-region.c
:functions: fpga_region_program_fpga
diff --git a/Documentation/driver-api/fpga/fpga-region.rst b/Documentation/driver-api/fpga/fpga-region.rst
index 0529b2d2231a..dc55d60a0b4a 100644
--- a/Documentation/driver-api/fpga/fpga-region.rst
+++ b/Documentation/driver-api/fpga/fpga-region.rst
@@ -45,38 +45,44 @@ An example of usage can be seen in the probe function of [#f2]_.
API to add a new FPGA region
----------------------------
-* struct :c:type:`fpga_region` — The FPGA region struct
-* :c:func:`devm_fpga_region_create` — Allocate and init a region struct
-* :c:func:`fpga_region_register` — Register an FPGA region
-* :c:func:`fpga_region_unregister` — Unregister an FPGA region
+* struct fpga_region - The FPGA region struct
+* struct fpga_region_info - Parameter structure for fpga_region_register_full()
+* fpga_region_register_full() - Create and register an FPGA region using the
+ fpga_region_info structure to provide the full flexibility of options
+* fpga_region_register() - Create and register an FPGA region using standard
+ arguments
+* fpga_region_unregister() - Unregister an FPGA region
The FPGA region's probe function will need to get a reference to the FPGA
Manager it will be using to do the programming. This usually would happen
during the region's probe function.
-* :c:func:`fpga_mgr_get` — Get a reference to an FPGA manager, raise ref count
-* :c:func:`of_fpga_mgr_get` — Get a reference to an FPGA manager, raise ref count,
+* fpga_mgr_get() - Get a reference to an FPGA manager, raise ref count
+* of_fpga_mgr_get() - Get a reference to an FPGA manager, raise ref count,
given a device node.
-* :c:func:`fpga_mgr_put` — Put an FPGA manager
+* fpga_mgr_put() - Put an FPGA manager
The FPGA region will need to specify which bridges to control while programming
the FPGA. The region driver can build a list of bridges during probe time
-(:c:member:`fpga_region->bridge_list`) or it can have a function that creates
+(:c:expr:`fpga_region->bridge_list`) or it can have a function that creates
the list of bridges to program just before programming
-(:c:member:`fpga_region->get_bridges`). The FPGA bridge framework supplies the
+(:c:expr:`fpga_region->get_bridges`). The FPGA bridge framework supplies the
following APIs to handle building or tearing down that list.
-* :c:func:`fpga_bridge_get_to_list` — Get a ref of an FPGA bridge, add it to a
+* fpga_bridge_get_to_list() - Get a ref of an FPGA bridge, add it to a
list
-* :c:func:`of_fpga_bridge_get_to_list` — Get a ref of an FPGA bridge, add it to a
+* of_fpga_bridge_get_to_list() - Get a ref of an FPGA bridge, add it to a
list, given a device node
-* :c:func:`fpga_bridges_put` — Given a list of bridges, put them
+* fpga_bridges_put() - Given a list of bridges, put them
.. kernel-doc:: include/linux/fpga/fpga-region.h
:functions: fpga_region
+.. kernel-doc:: include/linux/fpga/fpga-region.h
+ :functions: fpga_region_info
+
.. kernel-doc:: drivers/fpga/fpga-region.c
- :functions: devm_fpga_region_create
+ :functions: fpga_region_register_full
.. kernel-doc:: drivers/fpga/fpga-region.c
:functions: fpga_region_register
diff --git a/Documentation/driver-api/generic-counter.rst b/Documentation/driver-api/generic-counter.rst
index e622f8f6e56a..71ccc30e586b 100644
--- a/Documentation/driver-api/generic-counter.rst
+++ b/Documentation/driver-api/generic-counter.rst
@@ -223,19 +223,6 @@ whether an input line is differential or single-ended) and instead focus
on the core idea of what the data and process represent (e.g. position
as interpreted from quadrature encoding data).
-Userspace Interface
-===================
-
-Several sysfs attributes are generated by the Generic Counter interface,
-and reside under the /sys/bus/counter/devices/counterX directory, where
-counterX refers to the respective counter device. Please see
-Documentation/ABI/testing/sysfs-bus-counter for detailed
-information on each Generic Counter interface sysfs attribute.
-
-Through these sysfs attributes, programs and scripts may interact with
-the Generic Counter paradigm Counts, Signals, and Synapses of respective
-counter devices.
-
Driver API
==========
@@ -247,11 +234,14 @@ for defining a counter device.
.. kernel-doc:: include/linux/counter.h
:internal:
-.. kernel-doc:: drivers/counter/counter.c
+.. kernel-doc:: drivers/counter/counter-core.c
+ :export:
+
+.. kernel-doc:: drivers/counter/counter-chrdev.c
:export:
-Implementation
-==============
+Driver Implementation
+=====================
To support a counter device, a driver must first allocate the available
Counter Signals via counter_signal structures. These Signals should
@@ -262,30 +252,66 @@ the system.
Counter Counts may be allocated via counter_count structures, and
respective Counter Signal associations (Synapses) made via
counter_synapse structures. Associated counter_synapse structures are
-stored as an array and set to the the synapses array member of the
+stored as an array and set to the synapses array member of the
respective counter_count structure. These counter_count structures are
set to the counts array member of an allocated counter_device structure
before the Counter is registered to the system.
-Driver callbacks should be provided to the counter_device structure via
-a constant counter_ops structure in order to communicate with the
-device: to read and write various Signals and Counts, and to set and get
-the "action mode" and "function mode" for various Synapses and Counts
-respectively.
-
-A defined counter_device structure may be registered to the system by
-passing it to the counter_register function, and unregistered by passing
-it to the counter_unregister function. Similarly, the
-devm_counter_register and devm_counter_unregister functions may be used
-if device memory-managed registration is desired.
-
-Extension sysfs attributes can be created for auxiliary functionality
-and data by passing in defined counter_device_ext, counter_count_ext,
-and counter_signal_ext structures. In these cases, the
-counter_device_ext structure is used for global/miscellaneous exposure
-and configuration of the respective Counter device, while the
-counter_count_ext and counter_signal_ext structures allow for auxiliary
-exposure and configuration of a specific Count or Signal respectively.
+Driver callbacks must be provided to the counter_device structure in
+order to communicate with the device: to read and write various Signals
+and Counts, and to set and get the "action mode" and "function mode" for
+various Synapses and Counts respectively.
+
+A counter_device structure is allocated using counter_alloc() and then
+registered to the system by passing it to the counter_add() function, and
+unregistered by passing it to the counter_unregister function. There are
+device managed variants of these functions: devm_counter_alloc() and
+devm_counter_add().
+
+The struct counter_comp structure is used to define counter extensions
+for Signals, Synapses, and Counts.
+
+The "type" member specifies the type of high-level data (e.g. BOOL,
+COUNT_DIRECTION, etc.) handled by this extension. The "``*_read``" and
+"``*_write``" members can then be set by the counter device driver with
+callbacks to handle that data using native C data types (i.e. u8, u64,
+etc.).
+
+Convenience macros such as ``COUNTER_COMP_COUNT_U64`` are provided for
+use by driver authors. In particular, driver authors are expected to use
+the provided macros for standard Counter subsystem attributes in order
+to maintain a consistent interface for userspace. For example, a counter
+device driver may define several standard attributes like so::
+
+ struct counter_comp count_ext[] = {
+ COUNTER_COMP_DIRECTION(count_direction_read),
+ COUNTER_COMP_ENABLE(count_enable_read, count_enable_write),
+ COUNTER_COMP_CEILING(count_ceiling_read, count_ceiling_write),
+ };
+
+This makes it simple to see, add, and modify the attributes that are
+supported by this driver ("direction", "enable", and "ceiling") and to
+maintain this code without getting lost in a web of struct braces.
+
+Callbacks must match the function type expected for the respective
+component or extension. These function types are defined in the struct
+counter_comp structure as the "``*_read``" and "``*_write``" union
+members.
+
+The corresponding callback prototypes for the extensions mentioned in
+the previous example above would be::
+
+ int count_direction_read(struct counter_device *counter,
+ struct counter_count *count,
+ enum counter_count_direction *direction);
+ int count_enable_read(struct counter_device *counter,
+ struct counter_count *count, u8 *enable);
+ int count_enable_write(struct counter_device *counter,
+ struct counter_count *count, u8 enable);
+ int count_ceiling_read(struct counter_device *counter,
+ struct counter_count *count, u64 *ceiling);
+ int count_ceiling_write(struct counter_device *counter,
+ struct counter_count *count, u64 ceiling);
Determining the type of extension to create is a matter of scope.
@@ -307,58 +333,241 @@ Determining the type of extension to create is a matter of scope.
* Device extensions are attributes that expose information/control
non-specific to a particular Count or Signal. This is where you would
- put your global features or other miscellanous functionality.
+ put your global features or other miscellaneous functionality.
For example, if your device has an overtemp sensor, you can report the
chip overheated via a device extension called "error_overtemp":
/sys/bus/counter/devices/counterX/error_overtemp
-Architecture
-============
-
-When the Generic Counter interface counter module is loaded, the
-counter_init function is called which registers a bus_type named
-"counter" to the system. Subsequently, when the module is unloaded, the
-counter_exit function is called which unregisters the bus_type named
-"counter" from the system.
+Subsystem Architecture
+======================
+
+Counter drivers pass and take data natively (i.e. ``u8``, ``u64``, etc.)
+and the shared counter module handles the translation between the sysfs
+interface. This guarantees a standard userspace interface for all
+counter drivers, and enables a Generic Counter chrdev interface via a
+generalized device driver ABI.
+
+A high-level view of how a count value is passed down from a counter
+driver is exemplified by the following. The driver callbacks are first
+registered to the Counter core component for use by the Counter
+userspace interface components::
+
+ Driver callbacks registration:
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ +----------------------------+
+ | Counter device driver |
+ +----------------------------+
+ | Processes data from device |
+ +----------------------------+
+ |
+ -------------------
+ / driver callbacks /
+ -------------------
+ |
+ V
+ +----------------------+
+ | Counter core |
+ +----------------------+
+ | Routes device driver |
+ | callbacks to the |
+ | userspace interfaces |
+ +----------------------+
+ |
+ -------------------
+ / driver callbacks /
+ -------------------
+ |
+ +---------------+---------------+
+ | |
+ V V
+ +--------------------+ +---------------------+
+ | Counter sysfs | | Counter chrdev |
+ +--------------------+ +---------------------+
+ | Translates to the | | Translates to the |
+ | standard Counter | | standard Counter |
+ | sysfs output | | character device |
+ +--------------------+ +---------------------+
+
+Thereafter, data can be transferred directly between the Counter device
+driver and Counter userspace interface::
+
+ Count data request:
+ ~~~~~~~~~~~~~~~~~~~
+ ----------------------
+ / Counter device \
+ +----------------------+
+ | Count register: 0x28 |
+ +----------------------+
+ |
+ -----------------
+ / raw count data /
+ -----------------
+ |
+ V
+ +----------------------------+
+ | Counter device driver |
+ +----------------------------+
+ | Processes data from device |
+ |----------------------------|
+ | Type: u64 |
+ | Value: 42 |
+ +----------------------------+
+ |
+ ----------
+ / u64 /
+ ----------
+ |
+ +---------------+---------------+
+ | |
+ V V
+ +--------------------+ +---------------------+
+ | Counter sysfs | | Counter chrdev |
+ +--------------------+ +---------------------+
+ | Translates to the | | Translates to the |
+ | standard Counter | | standard Counter |
+ | sysfs output | | character device |
+ |--------------------| |---------------------|
+ | Type: const char * | | Type: u64 |
+ | Value: "42" | | Value: 42 |
+ +--------------------+ +---------------------+
+ | |
+ --------------- -----------------------
+ / const char * / / struct counter_event /
+ --------------- -----------------------
+ | |
+ | V
+ | +-----------+
+ | | read |
+ | +-----------+
+ | \ Count: 42 /
+ | -----------
+ |
+ V
+ +--------------------------------------------------+
+ | `/sys/bus/counter/devices/counterX/countY/count` |
+ +--------------------------------------------------+
+ \ Count: "42" /
+ --------------------------------------------------
+
+There are four primary components involved:
+
+Counter device driver
+---------------------
+Communicates with the hardware device to read/write data; e.g. counter
+drivers for quadrature encoders, timers, etc.
+
+Counter core
+------------
+Registers the counter device driver to the system so that the respective
+callbacks are called during userspace interaction.
+
+Counter sysfs
+-------------
+Translates counter data to the standard Counter sysfs interface format
+and vice versa.
+
+Please refer to the ``Documentation/ABI/testing/sysfs-bus-counter`` file
+for a detailed breakdown of the available Generic Counter interface
+sysfs attributes.
+
+Counter chrdev
+--------------
+Translates Counter events to the standard Counter character device; data
+is transferred via standard character device read calls, while Counter
+events are configured via ioctl calls.
+
+Sysfs Interface
+===============
-Counter devices are registered to the system via the counter_register
-function, and later removed via the counter_unregister function. The
-counter_register function establishes a unique ID for the Counter
-device and creates a respective sysfs directory, where X is the
-mentioned unique ID:
-
- /sys/bus/counter/devices/counterX
-
-Sysfs attributes are created within the counterX directory to expose
-functionality, configurations, and data relating to the Counts, Signals,
-and Synapses of the Counter device, as well as options and information
-for the Counter device itself.
-
-Each Signal has a directory created to house its relevant sysfs
-attributes, where Y is the unique ID of the respective Signal:
-
- /sys/bus/counter/devices/counterX/signalY
-
-Similarly, each Count has a directory created to house its relevant
-sysfs attributes, where Y is the unique ID of the respective Count:
-
- /sys/bus/counter/devices/counterX/countY
-
-For a more detailed breakdown of the available Generic Counter interface
-sysfs attributes, please refer to the
-Documentation/ABI/testing/sysfs-bus-counter file.
+Several sysfs attributes are generated by the Generic Counter interface,
+and reside under the ``/sys/bus/counter/devices/counterX`` directory,
+where ``X`` is to the respective counter device id. Please see
+``Documentation/ABI/testing/sysfs-bus-counter`` for detailed information
+on each Generic Counter interface sysfs attribute.
-The Signals and Counts associated with the Counter device are registered
-to the system as well by the counter_register function. The
-signal_read/signal_write driver callbacks are associated with their
-respective Signal attributes, while the count_read/count_write and
-function_get/function_set driver callbacks are associated with their
-respective Count attributes; similarly, the same is true for the
-action_get/action_set driver callbacks and their respective Synapse
-attributes. If a driver callback is left undefined, then the respective
-read/write permission is left disabled for the relevant attributes.
+Through these sysfs attributes, programs and scripts may interact with
+the Generic Counter paradigm Counts, Signals, and Synapses of respective
+counter devices.
-Similarly, extension sysfs attributes are created for the defined
-counter_device_ext, counter_count_ext, and counter_signal_ext
-structures that are passed in.
+Counter Character Device
+========================
+
+Counter character device nodes are created under the ``/dev`` directory
+as ``counterX``, where ``X`` is the respective counter device id.
+Defines for the standard Counter data types are exposed via the
+userspace ``include/uapi/linux/counter.h`` file.
+
+Counter events
+--------------
+Counter device drivers can support Counter events by utilizing the
+``counter_push_event`` function::
+
+ void counter_push_event(struct counter_device *const counter, const u8 event,
+ const u8 channel);
+
+The event id is specified by the ``event`` parameter; the event channel
+id is specified by the ``channel`` parameter. When this function is
+called, the Counter data associated with the respective event is
+gathered, and a ``struct counter_event`` is generated for each datum and
+pushed to userspace.
+
+Counter events can be configured by users to report various Counter
+data of interest. This can be conceptualized as a list of Counter
+component read calls to perform. For example:
+
+ +------------------------+------------------------+
+ | COUNTER_EVENT_OVERFLOW | COUNTER_EVENT_INDEX |
+ +========================+========================+
+ | Channel 0 | Channel 0 |
+ +------------------------+------------------------+
+ | * Count 0 | * Signal 0 |
+ | * Count 1 | * Signal 0 Extension 0 |
+ | * Signal 3 | * Extension 4 |
+ | * Count 4 Extension 2 +------------------------+
+ | * Signal 5 Extension 0 | Channel 1 |
+ | +------------------------+
+ | | * Signal 4 |
+ | | * Signal 4 Extension 0 |
+ | | * Count 7 |
+ +------------------------+------------------------+
+
+When ``counter_push_event(counter, COUNTER_EVENT_INDEX, 1)`` is called
+for example, it will go down the list for the ``COUNTER_EVENT_INDEX``
+event channel 1 and execute the read callbacks for Signal 4, Signal 4
+Extension 0, and Count 7 -- the data returned for each is pushed to a
+kfifo as a ``struct counter_event``, which userspace can retrieve via a
+standard read operation on the respective character device node.
+
+Userspace
+---------
+Userspace applications can configure Counter events via ioctl operations
+on the Counter character device node. There following ioctl codes are
+supported and provided by the ``linux/counter.h`` userspace header file:
+
+* :c:macro:`COUNTER_ADD_WATCH_IOCTL`
+
+* :c:macro:`COUNTER_ENABLE_EVENTS_IOCTL`
+
+* :c:macro:`COUNTER_DISABLE_EVENTS_IOCTL`
+
+To configure events to gather Counter data, users first populate a
+``struct counter_watch`` with the relevant event id, event channel id,
+and the information for the desired Counter component from which to
+read, and then pass it via the ``COUNTER_ADD_WATCH_IOCTL`` ioctl
+command.
+
+Note that an event can be watched without gathering Counter data by
+setting the ``component.type`` member equal to
+``COUNTER_COMPONENT_NONE``. With this configuration the Counter
+character device will simply populate the event timestamps for those
+respective ``struct counter_event`` elements and ignore the component
+value.
+
+The ``COUNTER_ADD_WATCH_IOCTL`` command will buffer these Counter
+watches. When ready, the ``COUNTER_ENABLE_EVENTS_IOCTL`` ioctl command
+may be used to activate these Counter watches.
+
+Userspace applications can then execute a ``read`` operation (optionally
+calling ``poll`` first) on the Counter character device node to retrieve
+``struct counter_event`` elements with the desired data.
diff --git a/Documentation/driver-api/gpio/board.rst b/Documentation/driver-api/gpio/board.rst
index ce91518bf9f4..b33aa04f213f 100644
--- a/Documentation/driver-api/gpio/board.rst
+++ b/Documentation/driver-api/gpio/board.rst
@@ -6,7 +6,7 @@ This document explains how GPIOs can be assigned to given devices and functions.
Note that it only applies to the new descriptor-based interface. For a
description of the deprecated integer-based GPIO interface please refer to
-gpio-legacy.txt (actually, there is no real mapping possible with the old
+legacy.rst (actually, there is no real mapping possible with the old
interface; you just fetch an integer from somewhere and request the
corresponding GPIO).
@@ -71,14 +71,14 @@ with the help of _DSD (Device Specific Data), introduced in ACPI 5.1::
Device (FOO) {
Name (_CRS, ResourceTemplate () {
- GpioIo (Exclusive, ..., IoRestrictionOutputOnly,
- "\\_SB.GPI0") {15} // red
- GpioIo (Exclusive, ..., IoRestrictionOutputOnly,
- "\\_SB.GPI0") {16} // green
- GpioIo (Exclusive, ..., IoRestrictionOutputOnly,
- "\\_SB.GPI0") {17} // blue
- GpioIo (Exclusive, ..., IoRestrictionOutputOnly,
- "\\_SB.GPI0") {1} // power
+ GpioIo (Exclusive, PullUp, 0, 0, IoRestrictionOutputOnly,
+ "\\_SB.GPI0", 0, ResourceConsumer) { 15 } // red
+ GpioIo (Exclusive, PullUp, 0, 0, IoRestrictionOutputOnly,
+ "\\_SB.GPI0", 0, ResourceConsumer) { 16 } // green
+ GpioIo (Exclusive, PullUp, 0, 0, IoRestrictionOutputOnly,
+ "\\_SB.GPI0", 0, ResourceConsumer) { 17 } // blue
+ GpioIo (Exclusive, PullNone, 0, 0, IoRestrictionOutputOnly,
+ "\\_SB.GPI0", 0, ResourceConsumer) { 1 } // power
})
Name (_DSD, Package () {
@@ -92,10 +92,7 @@ with the help of _DSD (Device Specific Data), introduced in ACPI 5.1::
^FOO, 2, 0, 1,
}
},
- Package () {
- "power-gpios",
- Package () {^FOO, 3, 0, 0},
- },
+ Package () { "power-gpios", Package () { ^FOO, 3, 0, 0 } },
}
})
}
@@ -113,13 +110,15 @@ files that desire to do so need to include the following header::
GPIOs are mapped by the means of tables of lookups, containing instances of the
gpiod_lookup structure. Two macros are defined to help declaring such mappings::
- GPIO_LOOKUP(chip_label, chip_hwnum, con_id, flags)
- GPIO_LOOKUP_IDX(chip_label, chip_hwnum, con_id, idx, flags)
+ GPIO_LOOKUP(key, chip_hwnum, con_id, flags)
+ GPIO_LOOKUP_IDX(key, chip_hwnum, con_id, idx, flags)
where
- - chip_label is the label of the gpiod_chip instance providing the GPIO
- - chip_hwnum is the hardware number of the GPIO within the chip
+ - key is either the label of the gpiod_chip instance providing the GPIO, or
+ the GPIO line name
+ - chip_hwnum is the hardware number of the GPIO within the chip, or U16_MAX
+ to indicate that key is a GPIO line name
- con_id is the name of the GPIO function from the device point of view. It
can be NULL, in which case it will match any function.
- idx is the index of the GPIO within the function.
@@ -135,7 +134,10 @@ where
In the future, these flags might be extended to support more properties.
-Note that GPIO_LOOKUP() is just a shortcut to GPIO_LOOKUP_IDX() where idx = 0.
+Note that:
+ 1. GPIO line names are not guaranteed to be globally unique, so the first
+ match found will be used.
+ 2. GPIO_LOOKUP() is just a shortcut to GPIO_LOOKUP_IDX() where idx = 0.
A lookup table can then be defined as follows, with an empty entry defining its
end. The 'dev_id' field of the table is the identifier of the device that will
diff --git a/Documentation/driver-api/gpio/consumer.rst b/Documentation/driver-api/gpio/consumer.rst
index 423492d125b9..3e588b9d678c 100644
--- a/Documentation/driver-api/gpio/consumer.rst
+++ b/Documentation/driver-api/gpio/consumer.rst
@@ -4,7 +4,7 @@ GPIO Descriptor Consumer Interface
This document describes the consumer interface of the GPIO framework. Note that
it describes the new descriptor-based interface. For a description of the
-deprecated integer-based GPIO interface please refer to gpio-legacy.txt.
+deprecated integer-based GPIO interface please refer to legacy.rst.
Guidelines for GPIOs consumers
@@ -12,7 +12,7 @@ Guidelines for GPIOs consumers
Drivers that can't work without standard GPIO calls should have Kconfig entries
that depend on GPIOLIB or select GPIOLIB. The functions that allow a driver to
-obtain and use GPIOs are available by including the following file:
+obtain and use GPIOs are available by including the following file::
#include <linux/gpio/consumer.h>
@@ -29,6 +29,10 @@ warnings. These stubs are used for two use cases:
will use it under other compile-time configurations. In this case the
consumer must make sure not to call into these functions, or the user will
be met with console warnings that may be perceived as intimidating.
+ Combining truly optional GPIOLIB usage with calls to
+ ``[devm_]gpiod_get_optional()`` is a *bad idea*, and will result in weird
+ error messages. Use the ordinary getter functions with optional GPIOLIB:
+ some open coding of error handling should be expected when you do this.
All the functions that work with the descriptor-based GPIO interface are
prefixed with ``gpiod_``. The ``gpio_`` prefix is used for the legacy
@@ -72,9 +76,13 @@ for the GPIO. Values can be:
* GPIOD_OUT_HIGH_OPEN_DRAIN same as GPIOD_OUT_HIGH but also enforce the line
to be electrically used with open drain.
+Note that the initial value is *logical* and the physical line level depends on
+whether the line is configured active high or active low (see
+:ref:`active_low_semantics`).
+
The two last flags are used for use cases where open drain is mandatory, such
as I2C: if the line is not already configured as open drain in the mappings
-(see board.txt), then open drain will be enforced anyway and a warning will be
+(see board.rst), then open drain will be enforced anyway and a warning will be
printed that the board configuration needs to be updated to match the use case.
Both functions return either a valid GPIO descriptor, or an error code checkable
@@ -110,7 +118,7 @@ For a function using multiple GPIOs all of those can be obtained with one call::
This function returns a struct gpio_descs which contains an array of
descriptors. It also contains a pointer to a gpiolib private structure which,
-if passed back to get/set array functions, may speed up I/O proocessing::
+if passed back to get/set array functions, may speed up I/O processing::
struct gpio_descs {
struct gpio_array *info;
@@ -252,6 +260,8 @@ that can't be accessed from hardIRQ handlers, these calls act the same as the
spinlock-safe calls.
+.. _active_low_semantics:
+
The active low and open drain semantics
---------------------------------------
As a consumer should not have to care about the physical line level, all of the
@@ -264,7 +274,7 @@ driven.
The same is applicable for open drain or open source output lines: those do not
actively drive their output high (open drain) or low (open source), they just
switch their output to a high impedance value. The consumer should not need to
-care. (For details read about open drain in driver.txt.)
+care. (For details read about open drain in driver.rst.)
With this, all the gpiod_set_(array)_value_xxx() functions interpret the
parameter "value" as "asserted" ("1") or "de-asserted" ("0"). The physical line
@@ -309,9 +319,11 @@ work on the raw line value::
void gpiod_set_raw_value_cansleep(struct gpio_desc *desc, int value)
int gpiod_direction_output_raw(struct gpio_desc *desc, int value)
-The active low state of a GPIO can also be queried using the following call::
+The active low state of a GPIO can also be queried and toggled using the
+following calls::
int gpiod_is_active_low(const struct gpio_desc *desc)
+ void gpiod_toggle_active_low(struct gpio_desc *desc)
Note that these functions should only be used with great moderation; a driver
should not have to care about the physical line level or open drain semantics.
@@ -361,12 +373,13 @@ corresponding chip driver. In that case a significantly improved performance
can be expected. If simultaneous access is not possible the GPIOs will be
accessed sequentially.
-The functions take three arguments:
+The functions take four arguments:
+
* array_size - the number of array elements
* desc_array - an array of GPIO descriptors
* array_info - optional information obtained from gpiod_get_array()
* value_bitmap - a bitmap to store the GPIOs' values (get) or
- a bitmap of values to assign to the GPIOs (set)
+ a bitmap of values to assign to the GPIOs (set)
The descriptor array can be obtained using the gpiod_get_array() function
or one of its variants. If the group of descriptors returned by that function
@@ -440,18 +453,20 @@ For details refer to Documentation/firmware-guide/acpi/gpio-properties.rst
Interacting With the Legacy GPIO Subsystem
==========================================
-Many kernel subsystems still handle GPIOs using the legacy integer-based
-interface. Although it is strongly encouraged to upgrade them to the safer
-descriptor-based API, the following two functions allow you to convert a GPIO
-descriptor into the GPIO integer namespace and vice-versa::
+Many kernel subsystems and drivers still handle GPIOs using the legacy
+integer-based interface. It is strongly recommended to update these to the new
+gpiod interface. For cases where both interfaces need to be used, the following
+two functions allow to convert a GPIO descriptor into the GPIO integer namespace
+and vice-versa::
int desc_to_gpio(const struct gpio_desc *desc)
struct gpio_desc *gpio_to_desc(unsigned gpio)
-The GPIO number returned by desc_to_gpio() can be safely used as long as the
-GPIO descriptor has not been freed. All the same, a GPIO number passed to
-gpio_to_desc() must have been properly acquired, and usage of the returned GPIO
-descriptor is only possible after the GPIO number has been released.
+The GPIO number returned by desc_to_gpio() can safely be used as a parameter of
+the gpio\_*() functions for as long as the GPIO descriptor `desc` is not freed.
+All the same, a GPIO number passed to gpio_to_desc() must first be properly
+acquired using e.g. gpio_request_one(), and the returned GPIO descriptor is only
+considered valid until that GPIO number is released using gpio_free().
Freeing a GPIO obtained by one API with the other API is forbidden and an
unchecked error.
diff --git a/Documentation/driver-api/gpio/driver.rst b/Documentation/driver-api/gpio/driver.rst
index 9809f593c0ab..bf6319cc531b 100644
--- a/Documentation/driver-api/gpio/driver.rst
+++ b/Documentation/driver-api/gpio/driver.rst
@@ -119,7 +119,7 @@ GPIO lines with debounce support
Debouncing is a configuration set to a pin indicating that it is connected to
a mechanical switch or button, or similar that may bounce. Bouncing means the
line is pulled high/low quickly at very short intervals for mechanical
-reasons. This can result in the value being unstable or irqs fireing repeatedly
+reasons. This can result in the value being unstable or irqs firing repeatedly
unless the line is debounced.
Debouncing in practice involves setting up a timer when something happens on
@@ -218,10 +218,10 @@ not support open drain/open source in hardware, the GPIO library will instead
use a trick: when a line is set as output, if the line is flagged as open
drain, and the IN output value is low, it will be driven low as usual. But
if the IN output value is set to high, it will instead *NOT* be driven high,
-instead it will be switched to input, as input mode is high impedance, thus
-achieveing an "open drain emulation" of sorts: electrically the behaviour will
-be identical, with the exception of possible hardware glitches when switching
-the mode of the line.
+instead it will be switched to input, as input mode is an equivalent to
+high impedance, thus achieving an "open drain emulation" of sorts: electrically
+the behaviour will be identical, with the exception of possible hardware glitches
+when switching the mode of the line.
For open source configuration the same principle is used, just that instead
of actively driving the line low, it is set to input.
@@ -342,12 +342,12 @@ Cascaded GPIO irqchips usually fall in one of three categories:
forced to a thread. The "fake?" raw lock can be used to work around this
problem::
- raw_spinlock_t wa_lock;
- static irqreturn_t omap_gpio_irq_handler(int irq, void *gpiobank)
- unsigned long wa_lock_flags;
- raw_spin_lock_irqsave(&bank->wa_lock, wa_lock_flags);
- generic_handle_irq(irq_find_mapping(bank->chip.irq.domain, bit));
- raw_spin_unlock_irqrestore(&bank->wa_lock, wa_lock_flags);
+ raw_spinlock_t wa_lock;
+ static irqreturn_t omap_gpio_irq_handler(int irq, void *gpiobank)
+ unsigned long wa_lock_flags;
+ raw_spin_lock_irqsave(&bank->wa_lock, wa_lock_flags);
+ generic_handle_irq(irq_find_mapping(bank->chip.irq.domain, bit));
+ raw_spin_unlock_irqrestore(&bank->wa_lock, wa_lock_flags);
- GENERIC CHAINED GPIO IRQCHIPS: these are the same as "CHAINED GPIO irqchips",
but chained IRQ handlers are not used. Instead GPIO IRQs dispatching is
@@ -416,30 +416,69 @@ The preferred way to set up the helpers is to fill in the
struct gpio_irq_chip inside struct gpio_chip before adding the gpio_chip.
If you do this, the additional irq_chip will be set up by gpiolib at the
same time as setting up the rest of the GPIO functionality. The following
-is a typical example of a cascaded interrupt handler using gpio_irq_chip:
+is a typical example of a chained cascaded interrupt handler using
+the gpio_irq_chip. Note how the mask/unmask (or disable/enable) functions
+call into the core gpiolib code:
.. code-block:: c
- /* Typical state container with dynamic irqchip */
+ /* Typical state container */
struct my_gpio {
struct gpio_chip gc;
- struct irq_chip irq;
+ };
+
+ static void my_gpio_mask_irq(struct irq_data *d)
+ {
+ struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
+ irq_hw_number_t hwirq = irqd_to_hwirq(d);
+
+ /*
+ * Perform any necessary action to mask the interrupt,
+ * and then call into the core code to synchronise the
+ * state.
+ */
+
+ gpiochip_disable_irq(gc, hwirq);
+ }
+
+ static void my_gpio_unmask_irq(struct irq_data *d)
+ {
+ struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
+ irq_hw_number_t hwirq = irqd_to_hwirq(d);
+
+ gpiochip_enable_irq(gc, hwirq);
+
+ /*
+ * Perform any necessary action to unmask the interrupt,
+ * after having called into the core code to synchronise
+ * the state.
+ */
+ }
+
+ /*
+ * Statically populate the irqchip. Note that it is made const
+ * (further indicated by the IRQCHIP_IMMUTABLE flag), and that
+ * the GPIOCHIP_IRQ_RESOURCE_HELPER macro adds some extra
+ * callbacks to the structure.
+ */
+ static const struct irq_chip my_gpio_irq_chip = {
+ .name = "my_gpio_irq",
+ .irq_ack = my_gpio_ack_irq,
+ .irq_mask = my_gpio_mask_irq,
+ .irq_unmask = my_gpio_unmask_irq,
+ .irq_set_type = my_gpio_set_irq_type,
+ .flags = IRQCHIP_IMMUTABLE,
+ /* Provide the gpio resource callbacks */
+ GPIOCHIP_IRQ_RESOURCE_HELPERS,
};
int irq; /* from platform etc */
struct my_gpio *g;
struct gpio_irq_chip *girq;
- /* Set up the irqchip dynamically */
- g->irq.name = "my_gpio_irq";
- g->irq.irq_ack = my_gpio_ack_irq;
- g->irq.irq_mask = my_gpio_mask_irq;
- g->irq.irq_unmask = my_gpio_unmask_irq;
- g->irq.irq_set_type = my_gpio_set_irq_type;
-
/* Get a pointer to the gpio_irq_chip */
girq = &g->gc.irq;
- girq->chip = &g->irq;
+ gpio_irq_chip_set_chip(girq, &my_gpio_irq_chip);
girq->parent_handler = ftgpio_gpio_irq_handler;
girq->num_parents = 1;
girq->parents = devm_kcalloc(dev, 1, sizeof(*girq->parents),
@@ -452,7 +491,83 @@ is a typical example of a cascaded interrupt handler using gpio_irq_chip:
return devm_gpiochip_add_data(dev, &g->gc, g);
-The helper support using hierarchical interrupt controllers as well.
+The helper supports using threaded interrupts as well. Then you just request
+the interrupt separately and go with it:
+
+.. code-block:: c
+
+ /* Typical state container */
+ struct my_gpio {
+ struct gpio_chip gc;
+ };
+
+ static void my_gpio_mask_irq(struct irq_data *d)
+ {
+ struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
+ irq_hw_number_t hwirq = irqd_to_hwirq(d);
+
+ /*
+ * Perform any necessary action to mask the interrupt,
+ * and then call into the core code to synchronise the
+ * state.
+ */
+
+ gpiochip_disable_irq(gc, hwirq);
+ }
+
+ static void my_gpio_unmask_irq(struct irq_data *d)
+ {
+ struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
+ irq_hw_number_t hwirq = irqd_to_hwirq(d);
+
+ gpiochip_enable_irq(gc, hwirq);
+
+ /*
+ * Perform any necessary action to unmask the interrupt,
+ * after having called into the core code to synchronise
+ * the state.
+ */
+ }
+
+ /*
+ * Statically populate the irqchip. Note that it is made const
+ * (further indicated by the IRQCHIP_IMMUTABLE flag), and that
+ * the GPIOCHIP_IRQ_RESOURCE_HELPER macro adds some extra
+ * callbacks to the structure.
+ */
+ static const struct irq_chip my_gpio_irq_chip = {
+ .name = "my_gpio_irq",
+ .irq_ack = my_gpio_ack_irq,
+ .irq_mask = my_gpio_mask_irq,
+ .irq_unmask = my_gpio_unmask_irq,
+ .irq_set_type = my_gpio_set_irq_type,
+ .flags = IRQCHIP_IMMUTABLE,
+ /* Provide the gpio resource callbacks */
+ GPIOCHIP_IRQ_RESOURCE_HELPERS,
+ };
+
+ int irq; /* from platform etc */
+ struct my_gpio *g;
+ struct gpio_irq_chip *girq;
+
+ ret = devm_request_threaded_irq(dev, irq, NULL,
+ irq_thread_fn, IRQF_ONESHOT, "my-chip", g);
+ if (ret < 0)
+ return ret;
+
+ /* Get a pointer to the gpio_irq_chip */
+ girq = &g->gc.irq;
+ gpio_irq_chip_set_chip(girq, &my_gpio_irq_chip);
+ /* This will let us handle the parent IRQ in the driver */
+ girq->parent_handler = NULL;
+ girq->num_parents = 0;
+ girq->parents = NULL;
+ girq->default_type = IRQ_TYPE_NONE;
+ girq->handler = handle_bad_irq;
+
+ return devm_gpiochip_add_data(dev, &g->gc, g);
+
+The helper supports using hierarchical interrupt controllers as well.
In this case the typical set-up will look like this:
.. code-block:: c
@@ -460,24 +575,63 @@ In this case the typical set-up will look like this:
/* Typical state container with dynamic irqchip */
struct my_gpio {
struct gpio_chip gc;
- struct irq_chip irq;
struct fwnode_handle *fwnode;
};
- int irq; /* from platform etc */
+ static void my_gpio_mask_irq(struct irq_data *d)
+ {
+ struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
+ irq_hw_number_t hwirq = irqd_to_hwirq(d);
+
+ /*
+ * Perform any necessary action to mask the interrupt,
+ * and then call into the core code to synchronise the
+ * state.
+ */
+
+ gpiochip_disable_irq(gc, hwirq);
+ irq_mask_mask_parent(d);
+ }
+
+ static void my_gpio_unmask_irq(struct irq_data *d)
+ {
+ struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
+ irq_hw_number_t hwirq = irqd_to_hwirq(d);
+
+ gpiochip_enable_irq(gc, hwirq);
+
+ /*
+ * Perform any necessary action to unmask the interrupt,
+ * after having called into the core code to synchronise
+ * the state.
+ */
+
+ irq_mask_unmask_parent(d);
+ }
+
+ /*
+ * Statically populate the irqchip. Note that it is made const
+ * (further indicated by the IRQCHIP_IMMUTABLE flag), and that
+ * the GPIOCHIP_IRQ_RESOURCE_HELPER macro adds some extra
+ * callbacks to the structure.
+ */
+ static const struct irq_chip my_gpio_irq_chip = {
+ .name = "my_gpio_irq",
+ .irq_ack = my_gpio_ack_irq,
+ .irq_mask = my_gpio_mask_irq,
+ .irq_unmask = my_gpio_unmask_irq,
+ .irq_set_type = my_gpio_set_irq_type,
+ .flags = IRQCHIP_IMMUTABLE,
+ /* Provide the gpio resource callbacks */
+ GPIOCHIP_IRQ_RESOURCE_HELPERS,
+ };
+
struct my_gpio *g;
struct gpio_irq_chip *girq;
- /* Set up the irqchip dynamically */
- g->irq.name = "my_gpio_irq";
- g->irq.irq_ack = my_gpio_ack_irq;
- g->irq.irq_mask = my_gpio_mask_irq;
- g->irq.irq_unmask = my_gpio_unmask_irq;
- g->irq.irq_set_type = my_gpio_set_irq_type;
-
/* Get a pointer to the gpio_irq_chip */
girq = &g->gc.irq;
- girq->chip = &g->irq;
+ gpio_irq_chip_set_chip(girq, &my_gpio_irq_chip);
girq->default_type = IRQ_TYPE_NONE;
girq->handler = handle_bad_irq;
girq->fwnode = g->fwnode;
@@ -488,37 +642,18 @@ In this case the typical set-up will look like this:
As you can see pretty similar, but you do not supply a parent handler for
the IRQ, instead a parent irqdomain, an fwnode for the hardware and
-a funcion .child_to_parent_hwirq() that has the purpose of looking up
+a function .child_to_parent_hwirq() that has the purpose of looking up
the parent hardware irq from a child (i.e. this gpio chip) hardware irq.
As always it is good to look at examples in the kernel tree for advice
on how to find the required pieces.
-The old way of adding irqchips to gpiochips after registration is also still
-available but we try to move away from this:
-
-- DEPRECATED: gpiochip_irqchip_add(): adds a chained cascaded irqchip to a
- gpiochip. It will pass the struct gpio_chip* for the chip to all IRQ
- callbacks, so the callbacks need to embed the gpio_chip in its state
- container and obtain a pointer to the container using container_of().
- (See Documentation/driver-api/driver-model/design-patterns.rst)
-
-- gpiochip_irqchip_add_nested(): adds a nested cascaded irqchip to a gpiochip,
- as discussed above regarding different types of cascaded irqchips. The
- cascaded irq has to be handled by a threaded interrupt handler.
- Apart from that it works exactly like the chained irqchip.
-
-- gpiochip_set_nested_irqchip(): sets up a nested cascaded irq handler for a
- gpio_chip from a parent IRQ. As the parent IRQ has usually been
- explicitly requested by the driver, this does very little more than
- mark all the child IRQs as having the other IRQ as parent.
-
If there is a need to exclude certain GPIO lines from the IRQ domain handled by
these helpers, we can set .irq.need_valid_mask of the gpiochip before
devm_gpiochip_add_data() or gpiochip_add_data() is called. This allocates an
.irq.valid_mask with as many bits set as there are GPIO lines in the chip, each
bit representing line 0..n-1. Drivers can exclude GPIO lines by clearing bits
-from this mask. The mask must be filled in before gpiochip_irqchip_add() or
-gpiochip_irqchip_add_nested() is called.
+from this mask. The mask can be filled in the init_valid_mask() callback
+that is part of the struct gpio_irq_chip.
To use the helpers please keep the following in mind:
@@ -526,13 +661,10 @@ To use the helpers please keep the following in mind:
the irqchip can initialize. E.g. .dev and .can_sleep shall be set up
properly.
-- Nominally set all handlers to handle_bad_irq() in the setup call and pass
- handle_bad_irq() as flow handler parameter in gpiochip_irqchip_add() if it is
- expected for GPIO driver that irqchip .set_type() callback will be called
- before using/enabling each GPIO IRQ. Then set the handler to
- handle_level_irq() and/or handle_edge_irq() in the irqchip .set_type()
- callback depending on what your controller supports and what is requested
- by the consumer.
+- Nominally set gpio_irq_chip.handler to handle_bad_irq. Then, if your irqchip
+ is cascaded, set the handler to handle_level_irq() and/or handle_edge_irq()
+ in the irqchip .set_type() callback depending on what your controller
+ supports and what is requested by the consumer.
Locking IRQ usage
@@ -587,8 +719,9 @@ When implementing an irqchip inside a GPIO driver, these two functions should
typically be called in the .irq_disable() and .irq_enable() callbacks from the
irqchip.
-When using the gpiolib irqchip helpers, these callbacks are automatically
-assigned.
+When IRQCHIP_IMMUTABLE is not advertised by the irqchip, these callbacks
+are automatically assigned. This behaviour is deprecated and on its way
+to be removed from the kernel.
Real-Time compliance for GPIO IRQ chips
@@ -619,8 +752,8 @@ compliance:
level and edge IRQs
* [1] http://www.spinics.net/lists/linux-omap/msg120425.html
-* [2] https://lkml.org/lkml/2015/9/25/494
-* [3] https://lkml.org/lkml/2015/9/25/495
+* [2] https://lore.kernel.org/r/1443209283-20781-2-git-send-email-grygorii.strashko@ti.com
+* [3] https://lore.kernel.org/r/1443209283-20781-3-git-send-email-grygorii.strashko@ti.com
Requesting self-owned GPIO pins
diff --git a/Documentation/driver-api/gpio/drivers-on-gpio.rst b/Documentation/driver-api/gpio/drivers-on-gpio.rst
index 820b403d50f6..af632d764ac6 100644
--- a/Documentation/driver-api/gpio/drivers-on-gpio.rst
+++ b/Documentation/driver-api/gpio/drivers-on-gpio.rst
@@ -89,6 +89,19 @@ hardware descriptions such as device tree or ACPI:
Consumer Electronics Control bus using only GPIO. It is used to communicate
with devices on the HDMI bus.
+- gpio-charger: drivers/power/supply/gpio-charger.c is used if you need to do
+ battery charging and all you have to go by to check the presence of the
+ AC charger or more complex tasks such as indicating charging status using
+ nothing but GPIO lines, this driver provides that and also a clearly defined
+ way to pass the charging parameters from hardware descriptions such as the
+ device tree.
+
+- gpio-mux: drivers/mux/gpio.c is used for controlling a multiplexer using
+ n GPIO lines such that you can mux in 2^n different devices by activating
+ different GPIO lines. Often the GPIOs are on a SoC and the devices are
+ some SoC-external entities, such as different components on a PCB that
+ can be selectively enabled.
+
Apart from this there are special GPIO drivers in subsystems like MMC/SD to
read card detect and write protect GPIO lines, and in the TTY serial subsystem
to emulate MCTRL (modem control) signals CTS/RTS by using two GPIO lines. The
diff --git a/Documentation/driver-api/gpio/intro.rst b/Documentation/driver-api/gpio/intro.rst
index 74591489d0b5..c9c19243b97f 100644
--- a/Documentation/driver-api/gpio/intro.rst
+++ b/Documentation/driver-api/gpio/intro.rst
@@ -14,12 +14,12 @@ Due to the history of GPIO interfaces in the kernel, there are two different
ways to obtain and use GPIOs:
- The descriptor-based interface is the preferred way to manipulate GPIOs,
- and is described by all the files in this directory excepted gpio-legacy.txt.
+ and is described by all the files in this directory excepted legacy.rst.
- The legacy integer-based interface which is considered deprecated (but still
- usable for compatibility reasons) is documented in gpio-legacy.txt.
+ usable for compatibility reasons) is documented in legacy.rst.
The remainder of this document applies to the new descriptor-based interface.
-gpio-legacy.txt contains the same information applied to the legacy
+legacy.rst contains the same information applied to the legacy
integer-based interface.
@@ -27,7 +27,7 @@ What is a GPIO?
===============
A "General Purpose Input/Output" (GPIO) is a flexible software-controlled
-digital signal. They are provided from many kinds of chip, and are familiar
+digital signal. They are provided from many kinds of chips, and are familiar
to Linux developers working with embedded and custom hardware. Each GPIO
represents a bit connected to a particular pin, or "ball" on Ball Grid Array
(BGA) packages. Board schematics show which external hardware connects to
@@ -106,11 +106,11 @@ don't. When you need open drain signaling but your hardware doesn't directly
support it, there's a common idiom you can use to emulate it with any GPIO pin
that can be used as either an input or an output:
- LOW: gpiod_direction_output(gpio, 0) ... this drives the signal and overrides
- the pullup.
+ **LOW**: ``gpiod_direction_output(gpio, 0)`` ... this drives the signal and
+ overrides the pullup.
- HIGH: gpiod_direction_input(gpio) ... this turns off the output, so the pullup
- (or some other device) controls the signal.
+ **HIGH**: ``gpiod_direction_input(gpio)`` ... this turns off the output, so
+ the pullup (or some other device) controls the signal.
The same logic can be applied to emulate open source signaling, by driving the
high signal and configuring the GPIO as input for low. This open drain/open
diff --git a/Documentation/driver-api/gpio/legacy.rst b/Documentation/driver-api/gpio/legacy.rst
index 9bc34ba697d9..b6505914791c 100644
--- a/Documentation/driver-api/gpio/legacy.rst
+++ b/Documentation/driver-api/gpio/legacy.rst
@@ -165,8 +165,7 @@ Most GPIO controllers can be accessed with memory read/write instructions.
Those don't need to sleep, and can safely be done from inside hard
(nonthreaded) IRQ handlers and similar contexts.
-Use the following calls to access such GPIOs,
-for which gpio_cansleep() will always return false (see below)::
+Use the following calls to access such GPIOs::
/* GPIO INPUT: return zero or nonzero */
int gpio_get_value(unsigned gpio);
@@ -200,13 +199,6 @@ Some GPIO controllers must be accessed using message based busses like I2C
or SPI. Commands to read or write those GPIO values require waiting to
get to the head of a queue to transmit a command and get its response.
This requires sleeping, which can't be done from inside IRQ handlers.
-
-Platforms that support this type of GPIO distinguish them from other GPIOs
-by returning nonzero from this call (which requires a valid GPIO number,
-which should have been previously allocated with gpio_request)::
-
- int gpio_cansleep(unsigned gpio);
-
To access such GPIOs, a different set of accessors is defined::
/* GPIO INPUT: return zero or nonzero, might sleep */
@@ -215,7 +207,6 @@ To access such GPIOs, a different set of accessors is defined::
/* GPIO OUTPUT, might sleep */
void gpio_set_value_cansleep(unsigned gpio, int value);
-
Accessing such GPIOs requires a context which may sleep, for example
a threaded IRQ handler, and those accessors must be used instead of
spinlock-safe accessors without the cansleep() name suffix.
@@ -238,8 +229,6 @@ setup or driver probe/teardown code, so this is an easy constraint.)::
## gpio_free_array()
gpio_free()
- gpio_set_debounce()
-
Claiming and Releasing GPIOs
@@ -321,11 +310,6 @@ where 'flags' is currently defined to specify the following properties:
* GPIOF_INIT_LOW - as output, set initial level to LOW
* GPIOF_INIT_HIGH - as output, set initial level to HIGH
- * GPIOF_OPEN_DRAIN - gpio pin is open drain type.
- * GPIOF_OPEN_SOURCE - gpio pin is open source type.
-
- * GPIOF_EXPORT_DIR_FIXED - export gpio to sysfs, keep direction
- * GPIOF_EXPORT_DIR_CHANGEABLE - also export, allow changing direction
since GPIOF_INIT_* are only valid when configured as output, so group valid
combinations as:
@@ -334,20 +318,6 @@ combinations as:
* GPIOF_OUT_INIT_LOW - configured as output, initial level LOW
* GPIOF_OUT_INIT_HIGH - configured as output, initial level HIGH
-When setting the flag as GPIOF_OPEN_DRAIN then it will assume that pins is
-open drain type. Such pins will not be driven to 1 in output mode. It is
-require to connect pull-up on such pins. By enabling this flag, gpio lib will
-make the direction to input when it is asked to set value of 1 in output mode
-to make the pin HIGH. The pin is make to LOW by driving value 0 in output mode.
-
-When setting the flag as GPIOF_OPEN_SOURCE then it will assume that pins is
-open source type. Such pins will not be driven to 0 in output mode. It is
-require to connect pull-down on such pin. By enabling this flag, gpio lib will
-make the direction to input when it is asked to set value of 0 in output mode
-to make the pin LOW. The pin is make to HIGH by driving value 1 in output mode.
-
-In the future, these flags can be extended to support more properties.
-
Further more, to ease the claim/release of multiple GPIOs, 'struct gpio' is
introduced to encapsulate all three fields as::
@@ -387,9 +357,6 @@ map between them using calls like::
/* map GPIO numbers to IRQ numbers */
int gpio_to_irq(unsigned gpio);
- /* map IRQ numbers to GPIO numbers (avoid using this) */
- int irq_to_gpio(unsigned irq);
-
Those return either the corresponding number in the other namespace, or
else a negative errno code if the mapping can't be done. (For example,
some GPIOs can't be used as IRQs.) It is an unchecked error to use a GPIO
@@ -405,11 +372,6 @@ devices, by the board-specific initialization code. Note that IRQ trigger
options are part of the IRQ interface, e.g. IRQF_TRIGGER_FALLING, as are
system wakeup capabilities.
-Non-error values returned from irq_to_gpio() would most commonly be used
-with gpio_get_value(), for example to initialize or update driver state
-when the IRQ is edge-triggered. Note that some platforms don't support
-this reverse mapping, so you should avoid using it.
-
Emulating Open Drain Signals
----------------------------
@@ -461,7 +423,7 @@ pin controller?
This is done by registering "ranges" of pins, which are essentially
cross-reference tables. These are described in
-Documentation/driver-api/pinctl.rst
+Documentation/driver-api/pin-control.rst
While the pin allocation is totally managed by the pinctrl subsystem,
gpio (under gpiolib) is still maintained by gpio drivers. It may happen
@@ -558,11 +520,6 @@ Platform Support
To force-enable this framework, a platform's Kconfig will "select" GPIOLIB,
else it is up to the user to configure support for GPIO.
-It may also provide a custom value for ARCH_NR_GPIOS, so that it better
-reflects the number of GPIOs in actual use on that platform, without
-wasting static table space. (It should count both built-in/SoC GPIOs and
-also ones on GPIO expanders.
-
If neither of these options are selected, the platform does not support
GPIOs through GPIO-lib and the code cannot be enabled by the user.
@@ -571,7 +528,6 @@ code, which always dispatches through the gpio_chip::
#define gpio_get_value __gpio_get_value
#define gpio_set_value __gpio_set_value
- #define gpio_cansleep __gpio_cansleep
Fancier implementations could instead define those as inline functions with
logic optimizing access to specific SOC-based GPIOs. For example, if the
@@ -729,36 +685,6 @@ gpiochip nodes (possibly in conjunction with schematics) to determine
the correct GPIO number to use for a given signal.
-Exporting from Kernel code
---------------------------
-Kernel code can explicitly manage exports of GPIOs which have already been
-requested using gpio_request()::
-
- /* export the GPIO to userspace */
- int gpio_export(unsigned gpio, bool direction_may_change);
-
- /* reverse gpio_export() */
- void gpio_unexport();
-
- /* create a sysfs link to an exported GPIO node */
- int gpio_export_link(struct device *dev, const char *name,
- unsigned gpio)
-
-After a kernel driver requests a GPIO, it may only be made available in
-the sysfs interface by gpio_export(). The driver can control whether the
-signal direction may change. This helps drivers prevent userspace code
-from accidentally clobbering important system state.
-
-This explicit exporting can help with debugging (by making some kinds
-of experiments easier), or can provide an always-there interface that's
-suitable for documenting as part of a board support package.
-
-After the GPIO has been exported, gpio_export_link() allows creating
-symlinks from elsewhere in sysfs to the GPIO sysfs node. Drivers can
-use this to provide the interface under their own device in sysfs with
-a descriptive name.
-
-
API Reference
=============
diff --git a/Documentation/driver-api/gpio/using-gpio.rst b/Documentation/driver-api/gpio/using-gpio.rst
index dda069444032..894d88855d73 100644
--- a/Documentation/driver-api/gpio/using-gpio.rst
+++ b/Documentation/driver-api/gpio/using-gpio.rst
@@ -9,13 +9,13 @@ with them.
For examples of already existing generic drivers that will also be good
examples for any other kernel drivers you want to author, refer to
-:doc:`drivers-on-gpio`
+Documentation/driver-api/gpio/drivers-on-gpio.rst
For any kind of mass produced system you want to support, such as servers,
laptops, phones, tablets, routers, and any consumer or office or business goods
using appropriate kernel drivers is paramount. Submit your code for inclusion
in the upstream Linux kernel when you feel it is mature enough and you will get
-help to refine it, see :doc:`../../process/submitting-patches`.
+help to refine it, see Documentation/process/submitting-patches.rst.
In Linux GPIO lines also have a userspace ABI.
@@ -44,7 +44,7 @@ These devices will appear on the system as ``/dev/gpiochip0`` thru
found in the kernel tree ``tools/gpio`` subdirectory.
For structured and managed applications, we recommend that you make use of the
-libgpiod_ library. This provides helper abstractions, command line utlities
+libgpiod_ library. This provides helper abstractions, command line utilities
and arbitration for multiple simultaneous consumers on the same GPIO chip.
.. _libgpiod: https://git.kernel.org/pub/scm/libs/libgpiod/libgpiod.git/
diff --git a/Documentation/driver-api/hsi.rst b/Documentation/driver-api/hsi.rst
index f9cec02b72a1..01b6bebfbd1a 100644
--- a/Documentation/driver-api/hsi.rst
+++ b/Documentation/driver-api/hsi.rst
@@ -4,7 +4,7 @@ High Speed Synchronous Serial Interface (HSI)
Introduction
---------------
-High Speed Syncronous Interface (HSI) is a fullduplex, low latency protocol,
+High Speed Synchronous Interface (HSI) is a full duplex, low latency protocol,
that is optimized for die-level interconnect between an Application Processor
and a Baseband chipset. It has been specified by the MIPI alliance in 2003 and
implemented by multiple vendors since then.
@@ -52,7 +52,7 @@ hsi-char Device
------------------
Each port automatically registers a generic client driver called hsi_char,
-which provides a charecter device for userspace representing the HSI port.
+which provides a character device for userspace representing the HSI port.
It can be used to communicate via HSI from userspace. Userspace may
configure the hsi_char device using the following ioctl commands:
diff --git a/Documentation/driver-api/hte/hte.rst b/Documentation/driver-api/hte/hte.rst
new file mode 100644
index 000000000000..153f3233c100
--- /dev/null
+++ b/Documentation/driver-api/hte/hte.rst
@@ -0,0 +1,79 @@
+.. SPDX-License-Identifier: GPL-2.0+
+
+============================================
+The Linux Hardware Timestamping Engine (HTE)
+============================================
+
+:Author: Dipen Patel
+
+Introduction
+------------
+
+Certain devices have built in hardware timestamping engines which can
+monitor sets of system signals, lines, buses etc... in realtime for state
+change; upon detecting the change they can automatically store the timestamp at
+the moment of occurrence. Such functionality may help achieve better accuracy
+in obtaining timestamps than using software counterparts i.e. ktime and
+friends.
+
+This document describes the API that can be used by hardware timestamping
+engine provider and consumer drivers that want to use the hardware timestamping
+engine (HTE) framework. Both consumers and providers must include
+``#include <linux/hte.h>``.
+
+The HTE framework APIs for the providers
+----------------------------------------
+
+.. kernel-doc:: drivers/hte/hte.c
+ :functions: devm_hte_register_chip hte_push_ts_ns
+
+The HTE framework APIs for the consumers
+----------------------------------------
+
+.. kernel-doc:: drivers/hte/hte.c
+ :functions: hte_init_line_attr hte_ts_get hte_ts_put devm_hte_request_ts_ns hte_request_ts_ns hte_enable_ts hte_disable_ts of_hte_req_count hte_get_clk_src_info
+
+The HTE framework public structures
+-----------------------------------
+.. kernel-doc:: include/linux/hte.h
+
+More on the HTE timestamp data
+------------------------------
+The ``struct hte_ts_data`` is used to pass timestamp details between the
+consumers and the providers. It expresses timestamp data in nanoseconds in
+u64. An example of the typical timestamp data life cycle, for the GPIO line is
+as follows::
+
+ - Monitors GPIO line change.
+ - Detects the state change on GPIO line.
+ - Converts timestamps in nanoseconds.
+ - Stores GPIO raw level in raw_level variable if the provider has that
+ hardware capability.
+ - Pushes this hte_ts_data object to HTE subsystem.
+ - HTE subsystem increments seq counter and invokes consumer provided callback.
+ Based on callback return value, the HTE core invokes secondary callback in
+ the thread context.
+
+HTE subsystem debugfs attributes
+--------------------------------
+HTE subsystem creates debugfs attributes at ``/sys/kernel/debug/hte/``.
+It also creates line/signal-related debugfs attributes at
+``/sys/kernel/debug/hte/<provider>/<label or line id>/``. Note that these
+attributes are read-only.
+
+`ts_requested`
+ The total number of entities requested from the given provider,
+ where entity is specified by the provider and could represent
+ lines, GPIO, chip signals, buses etc...
+ The attribute will be available at
+ ``/sys/kernel/debug/hte/<provider>/``.
+
+`total_ts`
+ The total number of entities supported by the provider.
+ The attribute will be available at
+ ``/sys/kernel/debug/hte/<provider>/``.
+
+`dropped_timestamps`
+ The dropped timestamps for a given line.
+ The attribute will be available at
+ ``/sys/kernel/debug/hte/<provider>/<label or line id>/``.
diff --git a/Documentation/driver-api/hte/index.rst b/Documentation/driver-api/hte/index.rst
new file mode 100644
index 000000000000..29011de9a4b8
--- /dev/null
+++ b/Documentation/driver-api/hte/index.rst
@@ -0,0 +1,22 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+============================================
+The Linux Hardware Timestamping Engine (HTE)
+============================================
+
+The HTE Subsystem
+=================
+
+.. toctree::
+ :maxdepth: 1
+
+ hte
+
+HTE Tegra Provider
+==================
+
+.. toctree::
+ :maxdepth: 1
+
+ tegra-hte
+
diff --git a/Documentation/driver-api/hte/tegra-hte.rst b/Documentation/driver-api/hte/tegra-hte.rst
new file mode 100644
index 000000000000..85e654772782
--- /dev/null
+++ b/Documentation/driver-api/hte/tegra-hte.rst
@@ -0,0 +1,47 @@
+.. SPDX-License-Identifier: GPL-2.0+
+
+HTE Kernel provider driver
+==========================
+
+Description
+-----------
+The Nvidia tegra HTE provider also known as GTE (Generic Timestamping Engine)
+driver implements two GTE instances: 1) GPIO GTE and 2) LIC
+(Legacy Interrupt Controller) IRQ GTE. Both GTE instances get the timestamp
+from the system counter TSC which has 31.25MHz clock rate, and the driver
+converts clock tick rate to nanoseconds before storing it as timestamp value.
+
+GPIO GTE
+--------
+
+This GTE instance timestamps GPIO in real time. For that to happen GPIO
+needs to be configured as input. Only the always on (AON) GPIO controller
+instance supports timestamping GPIOs in real time as it is tightly coupled with
+the GPIO GTE. To support this, GPIOLIB adds two optional APIs as mentioned
+below. The GPIO GTE code supports both kernel and userspace consumers. The
+kernel space consumers can directly talk to HTE subsystem while userspace
+consumers timestamp requests go through GPIOLIB CDEV framework to HTE
+subsystem. The hte devicetree binding described at
+``Documentation/devicetree/bindings/timestamp`` provides an example of how a
+consumer can request an GPIO line.
+
+See gpiod_enable_hw_timestamp_ns() and gpiod_disable_hw_timestamp_ns().
+
+For userspace consumers, GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE flag must be
+specified during IOCTL calls. Refer to ``tools/gpio/gpio-event-mon.c``, which
+returns the timestamp in nanoseconds.
+
+LIC (Legacy Interrupt Controller) IRQ GTE
+-----------------------------------------
+
+This GTE instance timestamps LIC IRQ lines in real time. The hte devicetree
+binding described at ``Documentation/devicetree/bindings/timestamp``
+provides an example of how a consumer can request an IRQ line. Since it is a
+one-to-one mapping with IRQ GTE provider, consumers can simply specify the IRQ
+number that they are interested in. There is no userspace consumer support for
+this GTE instance in the HTE framework.
+
+The provider source code of both IRQ and GPIO GTE instances is located at
+``drivers/hte/hte-tegra194.c``. The test driver
+``drivers/hte/hte-tegra194-test.c`` demonstrates HTE API usage for both IRQ
+and GPIO GTE.
diff --git a/Documentation/driver-api/i3c/protocol.rst b/Documentation/driver-api/i3c/protocol.rst
index dae3b6d32c6b..23a0b93c62b1 100644
--- a/Documentation/driver-api/i3c/protocol.rst
+++ b/Documentation/driver-api/i3c/protocol.rst
@@ -14,7 +14,7 @@ collisions are prevented, ...) please have a look at the I3C specification.
This document is just a brief introduction to the I3C protocol and the concepts
it brings to the table. If you need more information, please refer to the MIPI
I3C specification (can be downloaded here
-http://resources.mipi.org/mipi-i3c-v1-download).
+https://resources.mipi.org/mipi-i3c-v1-download).
Introduction
============
@@ -71,8 +71,8 @@ During DAA, each I3C device reports 3 important things:
related capabilities
* DCR: Device Characteristic Register. This 8-bit register describes the
functionalities provided by the device
-* Provisional ID: A 48-bit unique identifier. On a given bus there should be no
- Provisional ID collision, otherwise the discovery mechanism may fail.
+* Provisioned ID: A 48-bit unique identifier. On a given bus there should be no
+ Provisioned ID collision, otherwise the discovery mechanism may fail.
I3C slave events
================
diff --git a/Documentation/driver-api/iio/buffers.rst b/Documentation/driver-api/iio/buffers.rst
index e9036ef9f8f4..e83026aebe97 100644
--- a/Documentation/driver-api/iio/buffers.rst
+++ b/Documentation/driver-api/iio/buffers.rst
@@ -2,7 +2,7 @@
Buffers
=======
-* struct :c:type:`iio_buffer` — general buffer structure
+* struct iio_buffer — general buffer structure
* :c:func:`iio_validate_scan_mask_onehot` — Validates that exactly one channel
is selected
* :c:func:`iio_buffer_get` — Grab a reference to the buffer
@@ -28,24 +28,26 @@ IIO buffer setup
The meta information associated with a channel reading placed in a buffer is
called a scan element. The important bits configuring scan elements are
exposed to userspace applications via the
-:file:`/sys/bus/iio/iio:device{X}/scan_elements/*` directory. This file contains
+:file:`/sys/bus/iio/iio:device{X}/scan_elements/` directory. This directory contains
attributes of the following form:
* :file:`enable`, used for enabling a channel. If and only if its attribute
is non *zero*, then a triggered capture will contain data samples for this
channel.
+* :file:`index`, the scan_index of the channel.
* :file:`type`, description of the scan element data storage within the buffer
and hence the form in which it is read from user space.
- Format is [be|le]:[s|u]bits/storagebitsXrepeat[>>shift] .
+ Format is [be|le]:[s|u]bits/storagebits[Xrepeat][>>shift] .
+
* *be* or *le*, specifies big or little endian.
* *s* or *u*, specifies if signed (2's complement) or unsigned.
* *bits*, is the number of valid data bits.
* *storagebits*, is the number of bits (after padding) that it occupies in the
- buffer.
- * *shift*, if specified, is the shift that needs to be applied prior to
- masking out unused bits.
+ buffer.
* *repeat*, specifies the number of bits/storagebits repetitions. When the
- repeat element is 0 or 1, then the repeat value is omitted.
+ repeat element is 0 or 1, then the repeat value is omitted.
+ * *shift*, if specified, is the shift that needs to be applied prior to
+ masking out unused bits.
For example, a driver for a 3-axis accelerometer with 12 bit resolution where
data is stored in two 8-bits registers as follows::
@@ -88,7 +90,7 @@ fields in iio_chan_spec definition::
The driver implementing the accelerometer described above will have the
following channel definition::
- struct struct iio_chan_spec accel_channels[] = {
+ struct iio_chan_spec accel_channels[] = {
{
.type = IIO_ACCEL,
.modified = 1,
@@ -122,4 +124,3 @@ More details
.. kernel-doc:: include/linux/iio/buffer.h
.. kernel-doc:: drivers/iio/industrialio-buffer.c
:export:
-
diff --git a/Documentation/driver-api/iio/core.rst b/Documentation/driver-api/iio/core.rst
index b0bc0c028cc5..715cf29482a1 100644
--- a/Documentation/driver-api/iio/core.rst
+++ b/Documentation/driver-api/iio/core.rst
@@ -10,11 +10,11 @@ applications manipulating sensors. The implementation can be found under
Industrial I/O Devices
----------------------
-* struct :c:type:`iio_dev` - industrial I/O device
-* :c:func:`iio_device_alloc()` - allocate an :c:type:`iio_dev` from a driver
-* :c:func:`iio_device_free()` - free an :c:type:`iio_dev` from a driver
-* :c:func:`iio_device_register()` - register a device with the IIO subsystem
-* :c:func:`iio_device_unregister()` - unregister a device from the IIO
+* struct iio_dev - industrial I/O device
+* iio_device_alloc() - allocate an :c:type:`iio_dev` from a driver
+* iio_device_free() - free an :c:type:`iio_dev` from a driver
+* iio_device_register() - register a device with the IIO subsystem
+* iio_device_unregister() - unregister a device from the IIO
subsystem
An IIO device usually corresponds to a single hardware sensor and it
@@ -34,17 +34,17 @@ A typical IIO driver will register itself as an :doc:`I2C <../i2c>` or
At probe:
-1. Call :c:func:`iio_device_alloc()`, which allocates memory for an IIO device.
+1. Call iio_device_alloc(), which allocates memory for an IIO device.
2. Initialize IIO device fields with driver specific information (e.g.
device name, device channels).
-3. Call :c:func:`iio_device_register()`, this registers the device with the
+3. Call iio_device_register(), this registers the device with the
IIO core. After this call the device is ready to accept requests from user
space applications.
At remove, we free the resources allocated in probe in reverse order:
-1. :c:func:`iio_device_unregister()`, unregister the device from the IIO core.
-2. :c:func:`iio_device_free()`, free the memory allocated for the IIO device.
+1. iio_device_unregister(), unregister the device from the IIO core.
+2. iio_device_free(), free the memory allocated for the IIO device.
IIO device sysfs interface
==========================
@@ -66,7 +66,7 @@ Common attributes are:
IIO device channels
===================
-struct :c:type:`iio_chan_spec` - specification of a single channel
+struct iio_chan_spec - specification of a single channel
An IIO device channel is a representation of a data channel. An IIO device can
have one or multiple channels. For example:
@@ -77,7 +77,7 @@ have one or multiple channels. For example:
* an accelerometer can have up to 3 channels representing acceleration on X, Y
and Z axes.
-An IIO channel is described by the struct :c:type:`iio_chan_spec`.
+An IIO channel is described by the struct iio_chan_spec.
A thermometer driver for the temperature sensor in the example above would
have to describe its channel as follows::
diff --git a/Documentation/driver-api/iio/hw-consumer.rst b/Documentation/driver-api/iio/hw-consumer.rst
index 819fb9edc005..76133a3796f2 100644
--- a/Documentation/driver-api/iio/hw-consumer.rst
+++ b/Documentation/driver-api/iio/hw-consumer.rst
@@ -8,7 +8,7 @@ software buffer for data. The implementation can be found under
:file:`drivers/iio/buffer/hw-consumer.c`
-* struct :c:type:`iio_hw_consumer` — Hardware consumer structure
+* struct iio_hw_consumer — Hardware consumer structure
* :c:func:`iio_hw_consumer_alloc` — Allocate IIO hardware consumer
* :c:func:`iio_hw_consumer_free` — Free IIO hardware consumer
* :c:func:`iio_hw_consumer_enable` — Enable IIO hardware consumer
diff --git a/Documentation/driver-api/iio/triggered-buffers.rst b/Documentation/driver-api/iio/triggered-buffers.rst
index 0db12660cc90..417555dbbdf4 100644
--- a/Documentation/driver-api/iio/triggered-buffers.rst
+++ b/Documentation/driver-api/iio/triggered-buffers.rst
@@ -10,7 +10,7 @@ IIO triggered buffer setup
* :c:func:`iio_triggered_buffer_setup` — Setup triggered buffer and pollfunc
* :c:func:`iio_triggered_buffer_cleanup` — Free resources allocated by
:c:func:`iio_triggered_buffer_setup`
-* struct :c:type:`iio_buffer_setup_ops` — buffer setup related callbacks
+* struct iio_buffer_setup_ops — buffer setup related callbacks
A typical triggered buffer setup looks like this::
diff --git a/Documentation/driver-api/iio/triggers.rst b/Documentation/driver-api/iio/triggers.rst
index 5c2156de6284..288625e40672 100644
--- a/Documentation/driver-api/iio/triggers.rst
+++ b/Documentation/driver-api/iio/triggers.rst
@@ -2,11 +2,9 @@
Triggers
========
-* struct :c:type:`iio_trigger` — industrial I/O trigger device
+* struct iio_trigger — industrial I/O trigger device
* :c:func:`devm_iio_trigger_alloc` — Resource-managed iio_trigger_alloc
-* :c:func:`devm_iio_trigger_free` — Resource-managed iio_trigger_free
* :c:func:`devm_iio_trigger_register` — Resource-managed iio_trigger_register
-* :c:func:`devm_iio_trigger_unregister` — Resource-managed
iio_trigger_unregister
* :c:func:`iio_trigger_validate_own_device` — Check if a trigger and IIO
device belong to the same device
@@ -65,7 +63,7 @@ Let's see a simple example of how to setup a trigger to be used by a driver::
IIO trigger ops
===============
-* struct :c:type:`iio_trigger_ops` — operations structure for an iio_trigger.
+* struct iio_trigger_ops — operations structure for an iio_trigger.
Notice that a trigger has a set of operations attached:
diff --git a/Documentation/driver-api/index.rst b/Documentation/driver-api/index.rst
index d4e78cb3ef4d..eba851605388 100644
--- a/Documentation/driver-api/index.rst
+++ b/Documentation/driver-api/index.rst
@@ -1,17 +1,16 @@
-========================================
-The Linux driver implementer's API guide
-========================================
+.. SPDX-License-Identifier: GPL-2.0
+
+==============================
+Driver implementer's API guide
+==============================
The kernel offers a wide variety of interfaces to support the development
of device drivers. This document is an only somewhat organized collection
of some of those interfaces — it will hopefully get better over time! The
available subsections can be seen below.
-.. class:: toc-title
-
- Table of contents
-
.. toctree::
+ :caption: Table of contents
:maxdepth: 2
driver-model/index
@@ -22,23 +21,25 @@ available subsections can be seen below.
pm/index
clk
device-io
- device_connection
dma-buf
device_link
component
message-based
infiniband
- sound
+ aperture
frame-buffer
regulator
+ reset
iio/index
input
usb/index
firewire
pci/index
+ cxl/index
spi
i2c
ipmb
+ ipmi
i3c/index
interconnect
devfreq
@@ -47,6 +48,7 @@ available subsections can be seen below.
scsi
libata
target
+ mailbox
mtdnand
miscellaneous
mei/index
@@ -60,9 +62,10 @@ available subsections can be seen below.
80211/index
uio-howto
firmware/index
- pinctl
+ pin-control
gpio/index
md/index
+ media/index
misc_devices
nfc/index
dmaengine/index
@@ -71,18 +74,15 @@ available subsections can be seen below.
thermal/index
fpga/index
acpi/index
+ auxiliary_bus
backlight/lp855x-driver.rst
connector
console
- dcdbas
eisa
- ipmb
isa
- isapnp
io-mapping
io_ordering
generic-counter
- lightnvm-pblk
memory-devices/index
men-chameleon-bus
ntb
@@ -91,19 +91,28 @@ available subsections can be seen below.
pps
ptp
phy/index
- pti_intel_mid
pwm
+ pldmfw/index
rfkill
serial/index
sm501
- smsc_ece1099
+ surface_aggregator/index
switchtec
sync_file
+ tty/index
vfio-mediated-device
vfio
+ vfio-pci-device-specific-driver-acceptance
+ virtio/index
xilinx/index
xillybus
zorro
+ hte/index
+ wmi
+ dpll
+ wbrf
+ crypto/index
+ tee
.. only:: subproject and html
diff --git a/Documentation/driver-api/infiniband.rst b/Documentation/driver-api/infiniband.rst
index 1a3116f32ff0..30e142ccbee9 100644
--- a/Documentation/driver-api/infiniband.rst
+++ b/Documentation/driver-api/infiniband.rst
@@ -37,9 +37,6 @@ InfiniBand core interfaces
.. kernel-doc:: drivers/infiniband/core/ud_header.c
:export:
-.. kernel-doc:: drivers/infiniband/core/fmr_pool.c
- :export:
-
.. kernel-doc:: drivers/infiniband/core/umem.c
:export:
diff --git a/Documentation/driver-api/infrastructure.rst b/Documentation/driver-api/infrastructure.rst
index 06d98c4526df..3d52dfdfa9fd 100644
--- a/Documentation/driver-api/infrastructure.rst
+++ b/Documentation/driver-api/infrastructure.rst
@@ -6,6 +6,16 @@ The Basic Device Driver-Model Structures
.. kernel-doc:: include/linux/device.h
:internal:
+ :no-identifiers: device_link_state
+
+.. kernel-doc:: include/linux/device/bus.h
+ :identifiers: bus_type bus_notifier_event
+
+.. kernel-doc:: include/linux/device/class.h
+ :identifiers: class
+
+.. kernel-doc:: include/linux/device/driver.h
+ :identifiers: probe_type device_driver
Device Drivers Base
-------------------
@@ -13,6 +23,9 @@ Device Drivers Base
.. kernel-doc:: drivers/base/init.c
:internal:
+.. kernel-doc:: include/linux/device/driver.h
+ :no-identifiers: probe_type device_driver
+
.. kernel-doc:: drivers/base/driver.c
:export:
@@ -22,15 +35,15 @@ Device Drivers Base
.. kernel-doc:: drivers/base/syscore.c
:export:
+.. kernel-doc:: include/linux/device/class.h
+ :no-identifiers: class
+
.. kernel-doc:: drivers/base/class.c
:export:
.. kernel-doc:: drivers/base/node.c
:internal:
-.. kernel-doc:: drivers/base/firmware_loader/main.c
- :export:
-
.. kernel-doc:: drivers/base/transport_class.c
:export:
@@ -43,6 +56,9 @@ Device Drivers Base
.. kernel-doc:: drivers/base/platform.c
:export:
+.. kernel-doc:: include/linux/device/bus.h
+ :no-identifiers: bus_type bus_notifier_event
+
.. kernel-doc:: drivers/base/bus.c
:export:
diff --git a/Documentation/driver-api/input.rst b/Documentation/driver-api/input.rst
index d05bf58fa83e..4bbb26ae2a89 100644
--- a/Documentation/driver-api/input.rst
+++ b/Documentation/driver-api/input.rst
@@ -25,15 +25,6 @@ Multitouch Library
.. kernel-doc:: drivers/input/input-mt.c
:export:
-Polled input devices
---------------------
-
-.. kernel-doc:: include/linux/input-polldev.h
- :internal:
-
-.. kernel-doc:: drivers/input/input-polldev.c
- :export:
-
Matrix keyboards/keypads
------------------------
diff --git a/Documentation/driver-api/interconnect.rst b/Documentation/driver-api/interconnect.rst
index 5ed4f57a6bac..a92d0f277a1f 100644
--- a/Documentation/driver-api/interconnect.rst
+++ b/Documentation/driver-api/interconnect.rst
@@ -113,3 +113,28 @@ through dot to generate diagrams in many graphical formats::
$ cat /sys/kernel/debug/interconnect/interconnect_graph | \
dot -Tsvg > interconnect_graph.svg
+
+The ``test-client`` directory provides interfaces for issuing BW requests to
+any arbitrary path. Note that for safety reasons, this feature is disabled by
+default without a Kconfig to enable it. Enabling it requires code changes to
+``#define INTERCONNECT_ALLOW_WRITE_DEBUGFS``. Example usage::
+
+ cd /sys/kernel/debug/interconnect/test-client/
+
+ # Configure node endpoints for the path from CPU to DDR on
+ # qcom/sm8550.
+ echo chm_apps > src_node
+ echo ebi > dst_node
+
+ # Get path between src_node and dst_node. This is only
+ # necessary after updating the node endpoints.
+ echo 1 > get
+
+ # Set desired BW to 1GBps avg and 2GBps peak.
+ echo 1000000 > avg_bw
+ echo 2000000 > peak_bw
+
+ # Vote for avg_bw and peak_bw on the latest path from "get".
+ # Voting for multiple paths is possible by repeating this
+ # process for different nodes endpoints.
+ echo 1 > commit
diff --git a/Documentation/driver-api/io-mapping.rst b/Documentation/driver-api/io-mapping.rst
index a966239f04e4..7274204b0435 100644
--- a/Documentation/driver-api/io-mapping.rst
+++ b/Documentation/driver-api/io-mapping.rst
@@ -20,78 +20,72 @@ A mapping object is created during driver initialization using::
mappable, while 'size' indicates how large a mapping region to
enable. Both are in bytes.
-This _wc variant provides a mapping which may only be used
-with the io_mapping_map_atomic_wc or io_mapping_map_wc.
+This _wc variant provides a mapping which may only be used with
+io_mapping_map_atomic_wc(), io_mapping_map_local_wc() or
+io_mapping_map_wc().
-With this mapping object, individual pages can be mapped either atomically
-or not, depending on the necessary scheduling environment. Of course, atomic
-maps are more efficient::
+With this mapping object, individual pages can be mapped either temporarily
+or long term, depending on the requirements. Of course, temporary maps are
+more efficient. They come in two flavours::
+
+ void *io_mapping_map_local_wc(struct io_mapping *mapping,
+ unsigned long offset)
void *io_mapping_map_atomic_wc(struct io_mapping *mapping,
unsigned long offset)
-'offset' is the offset within the defined mapping region.
-Accessing addresses beyond the region specified in the
-creation function yields undefined results. Using an offset
-which is not page aligned yields an undefined result. The
-return value points to a single page in CPU address space.
+'offset' is the offset within the defined mapping region. Accessing
+addresses beyond the region specified in the creation function yields
+undefined results. Using an offset which is not page aligned yields an
+undefined result. The return value points to a single page in CPU address
+space.
-This _wc variant returns a write-combining map to the
-page and may only be used with mappings created by
-io_mapping_create_wc
+This _wc variant returns a write-combining map to the page and may only be
+used with mappings created by io_mapping_create_wc()
-Note that the task may not sleep while holding this page
-mapped.
+Temporary mappings are only valid in the context of the caller. The mapping
+is not guaranteed to be globally visible.
-::
+io_mapping_map_local_wc() has a side effect on X86 32bit as it disables
+migration to make the mapping code work. No caller can rely on this side
+effect.
- void io_mapping_unmap_atomic(void *vaddr)
+io_mapping_map_atomic_wc() has the side effect of disabling preemption and
+pagefaults. Don't use in new code. Use io_mapping_map_local_wc() instead.
+
+Nested mappings need to be undone in reverse order because the mapping
+code uses a stack for keeping track of them::
-'vaddr' must be the value returned by the last
-io_mapping_map_atomic_wc call. This unmaps the specified
-page and allows the task to sleep once again.
+ addr1 = io_mapping_map_local_wc(map1, offset1);
+ addr2 = io_mapping_map_local_wc(map2, offset2);
+ ...
+ io_mapping_unmap_local(addr2);
+ io_mapping_unmap_local(addr1);
+
+The mappings are released with::
+
+ void io_mapping_unmap_local(void *vaddr)
+ void io_mapping_unmap_atomic(void *vaddr)
-If you need to sleep while holding the lock, you can use the non-atomic
-variant, although they may be significantly slower.
+'vaddr' must be the value returned by the last io_mapping_map_local_wc() or
+io_mapping_map_atomic_wc() call. This unmaps the specified mapping and
+undoes the side effects of the mapping functions.
-::
+If you need to sleep while holding a mapping, you can use the regular
+variant, although this may be significantly slower::
void *io_mapping_map_wc(struct io_mapping *mapping,
unsigned long offset)
-This works like io_mapping_map_atomic_wc except it allows
-the task to sleep while holding the page mapped.
+This works like io_mapping_map_atomic/local_wc() except it has no side
+effects and the pointer is globally visible.
-
-::
+The mappings are released with::
void io_mapping_unmap(void *vaddr)
-This works like io_mapping_unmap_atomic, except it is used
-for pages mapped with io_mapping_map_wc.
+Use for pages mapped with io_mapping_map_wc().
At driver close time, the io_mapping object must be freed::
void io_mapping_free(struct io_mapping *mapping)
-
-Current Implementation
-======================
-
-The initial implementation of these functions uses existing mapping
-mechanisms and so provides only an abstraction layer and no new
-functionality.
-
-On 64-bit processors, io_mapping_create_wc calls ioremap_wc for the whole
-range, creating a permanent kernel-visible mapping to the resource. The
-map_atomic and map functions add the requested offset to the base of the
-virtual address returned by ioremap_wc.
-
-On 32-bit processors with HIGHMEM defined, io_mapping_map_atomic_wc uses
-kmap_atomic_pfn to map the specified page in an atomic fashion;
-kmap_atomic_pfn isn't really supposed to be used with device pages, but it
-provides an efficient mapping for this usage.
-
-On 32-bit processors without HIGHMEM defined, io_mapping_map_atomic_wc and
-io_mapping_map_wc both use ioremap_wc, a terribly inefficient function which
-performs an IPI to inform all processors about the new mapping. This results
-in a significant performance penalty.
diff --git a/Documentation/driver-api/ioctl.rst b/Documentation/driver-api/ioctl.rst
index c455db0e1627..35795f6a151a 100644
--- a/Documentation/driver-api/ioctl.rst
+++ b/Documentation/driver-api/ioctl.rst
@@ -25,16 +25,16 @@ ioctl commands that follow modern conventions: ``_IO``, ``_IOR``,
with the correct parameters:
_IO/_IOR/_IOW/_IOWR
- The macro name specifies how the argument will be used.  It may be a
+ The macro name specifies how the argument will be used. It may be a
pointer to data to be passed into the kernel (_IOW), out of the kernel
- (_IOR), or both (_IOWR).  _IO can indicate either commands with no
+ (_IOR), or both (_IOWR). _IO can indicate either commands with no
argument or those passing an integer value instead of a pointer.
It is recommended to only use _IO for commands without arguments,
and use pointers for passing data.
type
An 8-bit number, often a character literal, specific to a subsystem
- or driver, and listed in :doc:`../userspace-api/ioctl/ioctl-number`
+ or driver, and listed in Documentation/userspace-api/ioctl/ioctl-number.rst
nr
An 8-bit number identifying the specific command, unique for a give
@@ -200,10 +200,10 @@ cause an information leak, which can be used to defeat kernel address
space layout randomization (KASLR), helping in an attack.
For this reason (and for compat support) it is best to avoid any
-implicit padding in data structures.  Where there is implicit padding
+implicit padding in data structures. Where there is implicit padding
in an existing structure, kernel drivers must be careful to fully
initialize an instance of the structure before copying it to user
-space.  This is usually done by calling memset() before assigning to
+space. This is usually done by calling memset() before assigning to
individual members.
Subsystem abstractions
diff --git a/Documentation/driver-api/ipmi.rst b/Documentation/driver-api/ipmi.rst
new file mode 100644
index 000000000000..e224e47b6b09
--- /dev/null
+++ b/Documentation/driver-api/ipmi.rst
@@ -0,0 +1,810 @@
+=====================
+The Linux IPMI Driver
+=====================
+
+:Author: Corey Minyard <minyard@mvista.com> / <minyard@acm.org>
+
+The Intelligent Platform Management Interface, or IPMI, is a
+standard for controlling intelligent devices that monitor a system.
+It provides for dynamic discovery of sensors in the system and the
+ability to monitor the sensors and be informed when the sensor's
+values change or go outside certain boundaries. It also has a
+standardized database for field-replaceable units (FRUs) and a watchdog
+timer.
+
+To use this, you need an interface to an IPMI controller in your
+system (called a Baseboard Management Controller, or BMC) and
+management software that can use the IPMI system.
+
+This document describes how to use the IPMI driver for Linux. If you
+are not familiar with IPMI itself, see the web site at
+https://www.intel.com/design/servers/ipmi/index.htm. IPMI is a big
+subject and I can't cover it all here!
+
+Configuration
+-------------
+
+The Linux IPMI driver is modular, which means you have to pick several
+things to have it work right depending on your hardware. Most of
+these are available in the 'Character Devices' menu then the IPMI
+menu.
+
+No matter what, you must pick 'IPMI top-level message handler' to use
+IPMI. What you do beyond that depends on your needs and hardware.
+
+The message handler does not provide any user-level interfaces.
+Kernel code (like the watchdog) can still use it. If you need access
+from userland, you need to select 'Device interface for IPMI' if you
+want access through a device driver.
+
+The driver interface depends on your hardware. If your system
+properly provides the SMBIOS info for IPMI, the driver will detect it
+and just work. If you have a board with a standard interface (These
+will generally be either "KCS", "SMIC", or "BT", consult your hardware
+manual), choose the 'IPMI SI handler' option. A driver also exists
+for direct I2C access to the IPMI management controller. Some boards
+support this, but it is unknown if it will work on every board. For
+this, choose 'IPMI SMBus handler', but be ready to try to do some
+figuring to see if it will work on your system if the SMBIOS/APCI
+information is wrong or not present. It is fairly safe to have both
+these enabled and let the drivers auto-detect what is present.
+
+You should generally enable ACPI on your system, as systems with IPMI
+can have ACPI tables describing them.
+
+If you have a standard interface and the board manufacturer has done
+their job correctly, the IPMI controller should be automatically
+detected (via ACPI or SMBIOS tables) and should just work. Sadly,
+many boards do not have this information. The driver attempts
+standard defaults, but they may not work. If you fall into this
+situation, you need to read the section below named 'The SI Driver' or
+"The SMBus Driver" on how to hand-configure your system.
+
+IPMI defines a standard watchdog timer. You can enable this with the
+'IPMI Watchdog Timer' config option. If you compile the driver into
+the kernel, then via a kernel command-line option you can have the
+watchdog timer start as soon as it initializes. It also have a lot
+of other options, see the 'Watchdog' section below for more details.
+Note that you can also have the watchdog continue to run if it is
+closed (by default it is disabled on close). Go into the 'Watchdog
+Cards' menu, enable 'Watchdog Timer Support', and enable the option
+'Disable watchdog shutdown on close'.
+
+IPMI systems can often be powered off using IPMI commands. Select
+'IPMI Poweroff' to do this. The driver will auto-detect if the system
+can be powered off by IPMI. It is safe to enable this even if your
+system doesn't support this option. This works on ATCA systems, the
+Radisys CPI1 card, and any IPMI system that supports standard chassis
+management commands.
+
+If you want the driver to put an event into the event log on a panic,
+enable the 'Generate a panic event to all BMCs on a panic' option. If
+you want the whole panic string put into the event log using OEM
+events, enable the 'Generate OEM events containing the panic string'
+option. You can also enable these dynamically by setting the module
+parameter named "panic_op" in the ipmi_msghandler module to "event"
+or "string". Setting that parameter to "none" disables this function.
+
+Basic Design
+------------
+
+The Linux IPMI driver is designed to be very modular and flexible, you
+only need to take the pieces you need and you can use it in many
+different ways. Because of that, it's broken into many chunks of
+code. These chunks (by module name) are:
+
+ipmi_msghandler - This is the central piece of software for the IPMI
+system. It handles all messages, message timing, and responses. The
+IPMI users tie into this, and the IPMI physical interfaces (called
+System Management Interfaces, or SMIs) also tie in here. This
+provides the kernelland interface for IPMI, but does not provide an
+interface for use by application processes.
+
+ipmi_devintf - This provides a userland IOCTL interface for the IPMI
+driver, each open file for this device ties in to the message handler
+as an IPMI user.
+
+ipmi_si - A driver for various system interfaces. This supports KCS,
+SMIC, and BT interfaces. Unless you have an SMBus interface or your
+own custom interface, you probably need to use this.
+
+ipmi_ssif - A driver for accessing BMCs on the SMBus. It uses the
+I2C kernel driver's SMBus interfaces to send and receive IPMI messages
+over the SMBus.
+
+ipmi_powernv - A driver for access BMCs on POWERNV systems.
+
+ipmi_watchdog - IPMI requires systems to have a very capable watchdog
+timer. This driver implements the standard Linux watchdog timer
+interface on top of the IPMI message handler.
+
+ipmi_poweroff - Some systems support the ability to be turned off via
+IPMI commands.
+
+bt-bmc - This is not part of the main driver, but instead a driver for
+accessing a BMC-side interface of a BT interface. It is used on BMCs
+running Linux to provide an interface to the host.
+
+These are all individually selectable via configuration options.
+
+Much documentation for the interface is in the include files. The
+IPMI include files are:
+
+linux/ipmi.h - Contains the user interface and IOCTL interface for IPMI.
+
+linux/ipmi_smi.h - Contains the interface for system management interfaces
+(things that interface to IPMI controllers) to use.
+
+linux/ipmi_msgdefs.h - General definitions for base IPMI messaging.
+
+
+Addressing
+----------
+
+The IPMI addressing works much like IP addresses, you have an overlay
+to handle the different address types. The overlay is::
+
+ struct ipmi_addr
+ {
+ int addr_type;
+ short channel;
+ char data[IPMI_MAX_ADDR_SIZE];
+ };
+
+The addr_type determines what the address really is. The driver
+currently understands two different types of addresses.
+
+"System Interface" addresses are defined as::
+
+ struct ipmi_system_interface_addr
+ {
+ int addr_type;
+ short channel;
+ };
+
+and the type is IPMI_SYSTEM_INTERFACE_ADDR_TYPE. This is used for talking
+straight to the BMC on the current card. The channel must be
+IPMI_BMC_CHANNEL.
+
+Messages that are destined to go out on the IPMB bus going through the
+BMC use the IPMI_IPMB_ADDR_TYPE address type. The format is::
+
+ struct ipmi_ipmb_addr
+ {
+ int addr_type;
+ short channel;
+ unsigned char slave_addr;
+ unsigned char lun;
+ };
+
+The "channel" here is generally zero, but some devices support more
+than one channel, it corresponds to the channel as defined in the IPMI
+spec.
+
+There is also an IPMB direct address for a situation where the sender
+is directly on an IPMB bus and doesn't have to go through the BMC.
+You can send messages to a specific management controller (MC) on the
+IPMB using the IPMI_IPMB_DIRECT_ADDR_TYPE with the following format::
+
+ struct ipmi_ipmb_direct_addr
+ {
+ int addr_type;
+ short channel;
+ unsigned char slave_addr;
+ unsigned char rq_lun;
+ unsigned char rs_lun;
+ };
+
+The channel is always zero. You can also receive commands from other
+MCs that you have registered to handle and respond to them, so you can
+use this to implement a management controller on a bus..
+
+Messages
+--------
+
+Messages are defined as::
+
+ struct ipmi_msg
+ {
+ unsigned char netfn;
+ unsigned char lun;
+ unsigned char cmd;
+ unsigned char *data;
+ int data_len;
+ };
+
+The driver takes care of adding/stripping the header information. The
+data portion is just the data to be send (do NOT put addressing info
+here) or the response. Note that the completion code of a response is
+the first item in "data", it is not stripped out because that is how
+all the messages are defined in the spec (and thus makes counting the
+offsets a little easier :-).
+
+When using the IOCTL interface from userland, you must provide a block
+of data for "data", fill it, and set data_len to the length of the
+block of data, even when receiving messages. Otherwise the driver
+will have no place to put the message.
+
+Messages coming up from the message handler in kernelland will come in
+as::
+
+ struct ipmi_recv_msg
+ {
+ struct list_head link;
+
+ /* The type of message as defined in the "Receive Types"
+ defines above. */
+ int recv_type;
+
+ ipmi_user_t *user;
+ struct ipmi_addr addr;
+ long msgid;
+ struct ipmi_msg msg;
+
+ /* Call this when done with the message. It will presumably free
+ the message and do any other necessary cleanup. */
+ void (*done)(struct ipmi_recv_msg *msg);
+
+ /* Place-holder for the data, don't make any assumptions about
+ the size or existence of this, since it may change. */
+ unsigned char msg_data[IPMI_MAX_MSG_LENGTH];
+ };
+
+You should look at the receive type and handle the message
+appropriately.
+
+
+The Upper Layer Interface (Message Handler)
+-------------------------------------------
+
+The upper layer of the interface provides the users with a consistent
+view of the IPMI interfaces. It allows multiple SMI interfaces to be
+addressed (because some boards actually have multiple BMCs on them)
+and the user should not have to care what type of SMI is below them.
+
+
+Watching For Interfaces
+^^^^^^^^^^^^^^^^^^^^^^^
+
+When your code comes up, the IPMI driver may or may not have detected
+if IPMI devices exist. So you might have to defer your setup until
+the device is detected, or you might be able to do it immediately.
+To handle this, and to allow for discovery, you register an SMI
+watcher with ipmi_smi_watcher_register() to iterate over interfaces
+and tell you when they come and go.
+
+
+Creating the User
+^^^^^^^^^^^^^^^^^
+
+To use the message handler, you must first create a user using
+ipmi_create_user. The interface number specifies which SMI you want
+to connect to, and you must supply callback functions to be called
+when data comes in. The callback function can run at interrupt level,
+so be careful using the callbacks. This also allows to you pass in a
+piece of data, the handler_data, that will be passed back to you on
+all calls.
+
+Once you are done, call ipmi_destroy_user() to get rid of the user.
+
+From userland, opening the device automatically creates a user, and
+closing the device automatically destroys the user.
+
+
+Messaging
+^^^^^^^^^
+
+To send a message from kernel-land, the ipmi_request_settime() call does
+pretty much all message handling. Most of the parameter are
+self-explanatory. However, it takes a "msgid" parameter. This is NOT
+the sequence number of messages. It is simply a long value that is
+passed back when the response for the message is returned. You may
+use it for anything you like.
+
+Responses come back in the function pointed to by the ipmi_recv_hndl
+field of the "handler" that you passed in to ipmi_create_user().
+Remember again, these may be running at interrupt level. Remember to
+look at the receive type, too.
+
+From userland, you fill out an ipmi_req_t structure and use the
+IPMICTL_SEND_COMMAND ioctl. For incoming stuff, you can use select()
+or poll() to wait for messages to come in. However, you cannot use
+read() to get them, you must call the IPMICTL_RECEIVE_MSG with the
+ipmi_recv_t structure to actually get the message. Remember that you
+must supply a pointer to a block of data in the msg.data field, and
+you must fill in the msg.data_len field with the size of the data.
+This gives the receiver a place to actually put the message.
+
+If the message cannot fit into the data you provide, you will get an
+EMSGSIZE error and the driver will leave the data in the receive
+queue. If you want to get it and have it truncate the message, us
+the IPMICTL_RECEIVE_MSG_TRUNC ioctl.
+
+When you send a command (which is defined by the lowest-order bit of
+the netfn per the IPMI spec) on the IPMB bus, the driver will
+automatically assign the sequence number to the command and save the
+command. If the response is not receive in the IPMI-specified 5
+seconds, it will generate a response automatically saying the command
+timed out. If an unsolicited response comes in (if it was after 5
+seconds, for instance), that response will be ignored.
+
+In kernelland, after you receive a message and are done with it, you
+MUST call ipmi_free_recv_msg() on it, or you will leak messages. Note
+that you should NEVER mess with the "done" field of a message, that is
+required to properly clean up the message.
+
+Note that when sending, there is an ipmi_request_supply_msgs() call
+that lets you supply the smi and receive message. This is useful for
+pieces of code that need to work even if the system is out of buffers
+(the watchdog timer uses this, for instance). You supply your own
+buffer and own free routines. This is not recommended for normal use,
+though, since it is tricky to manage your own buffers.
+
+
+Events and Incoming Commands
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The driver takes care of polling for IPMI events and receiving
+commands (commands are messages that are not responses, they are
+commands that other things on the IPMB bus have sent you). To receive
+these, you must register for them, they will not automatically be sent
+to you.
+
+To receive events, you must call ipmi_set_gets_events() and set the
+"val" to non-zero. Any events that have been received by the driver
+since startup will immediately be delivered to the first user that
+registers for events. After that, if multiple users are registered
+for events, they will all receive all events that come in.
+
+For receiving commands, you have to individually register commands you
+want to receive. Call ipmi_register_for_cmd() and supply the netfn
+and command name for each command you want to receive. You also
+specify a bitmask of the channels you want to receive the command from
+(or use IPMI_CHAN_ALL for all channels if you don't care). Only one
+user may be registered for each netfn/cmd/channel, but different users
+may register for different commands, or the same command if the
+channel bitmasks do not overlap.
+
+To respond to a received command, set the response bit in the returned
+netfn, use the address from the received message, and use the same
+msgid that you got in the receive message.
+
+From userland, equivalent IOCTLs are provided to do these functions.
+
+
+The Lower Layer (SMI) Interface
+-------------------------------
+
+As mentioned before, multiple SMI interfaces may be registered to the
+message handler, each of these is assigned an interface number when
+they register with the message handler. They are generally assigned
+in the order they register, although if an SMI unregisters and then
+another one registers, all bets are off.
+
+The ipmi_smi.h defines the interface for management interfaces, see
+that for more details.
+
+
+The SI Driver
+-------------
+
+The SI driver allows KCS, BT, and SMIC interfaces to be configured
+in the system. It discovers interfaces through a host of different
+methods, depending on the system.
+
+You can specify up to four interfaces on the module load line and
+control some module parameters::
+
+ modprobe ipmi_si.o type=<type1>,<type2>....
+ ports=<port1>,<port2>... addrs=<addr1>,<addr2>...
+ irqs=<irq1>,<irq2>...
+ regspacings=<sp1>,<sp2>,... regsizes=<size1>,<size2>,...
+ regshifts=<shift1>,<shift2>,...
+ slave_addrs=<addr1>,<addr2>,...
+ force_kipmid=<enable1>,<enable2>,...
+ kipmid_max_busy_us=<ustime1>,<ustime2>,...
+ unload_when_empty=[0|1]
+ trydmi=[0|1] tryacpi=[0|1]
+ tryplatform=[0|1] trypci=[0|1]
+
+Each of these except try... items is a list, the first item for the
+first interface, second item for the second interface, etc.
+
+The si_type may be either "kcs", "smic", or "bt". If you leave it blank, it
+defaults to "kcs".
+
+If you specify addrs as non-zero for an interface, the driver will
+use the memory address given as the address of the device. This
+overrides si_ports.
+
+If you specify ports as non-zero for an interface, the driver will
+use the I/O port given as the device address.
+
+If you specify irqs as non-zero for an interface, the driver will
+attempt to use the given interrupt for the device.
+
+The other try... items disable discovery by their corresponding
+names. These are all enabled by default, set them to zero to disable
+them. The tryplatform disables openfirmware.
+
+The next three parameters have to do with register layout. The
+registers used by the interfaces may not appear at successive
+locations and they may not be in 8-bit registers. These parameters
+allow the layout of the data in the registers to be more precisely
+specified.
+
+The regspacings parameter give the number of bytes between successive
+register start addresses. For instance, if the regspacing is set to 4
+and the start address is 0xca2, then the address for the second
+register would be 0xca6. This defaults to 1.
+
+The regsizes parameter gives the size of a register, in bytes. The
+data used by IPMI is 8-bits wide, but it may be inside a larger
+register. This parameter allows the read and write type to specified.
+It may be 1, 2, 4, or 8. The default is 1.
+
+Since the register size may be larger than 32 bits, the IPMI data may not
+be in the lower 8 bits. The regshifts parameter give the amount to shift
+the data to get to the actual IPMI data.
+
+The slave_addrs specifies the IPMI address of the local BMC. This is
+usually 0x20 and the driver defaults to that, but in case it's not, it
+can be specified when the driver starts up.
+
+The force_ipmid parameter forcefully enables (if set to 1) or disables
+(if set to 0) the kernel IPMI daemon. Normally this is auto-detected
+by the driver, but systems with broken interrupts might need an enable,
+or users that don't want the daemon (don't need the performance, don't
+want the CPU hit) can disable it.
+
+If unload_when_empty is set to 1, the driver will be unloaded if it
+doesn't find any interfaces or all the interfaces fail to work. The
+default is one. Setting to 0 is useful with the hotmod, but is
+obviously only useful for modules.
+
+When compiled into the kernel, the parameters can be specified on the
+kernel command line as::
+
+ ipmi_si.type=<type1>,<type2>...
+ ipmi_si.ports=<port1>,<port2>... ipmi_si.addrs=<addr1>,<addr2>...
+ ipmi_si.irqs=<irq1>,<irq2>...
+ ipmi_si.regspacings=<sp1>,<sp2>,...
+ ipmi_si.regsizes=<size1>,<size2>,...
+ ipmi_si.regshifts=<shift1>,<shift2>,...
+ ipmi_si.slave_addrs=<addr1>,<addr2>,...
+ ipmi_si.force_kipmid=<enable1>,<enable2>,...
+ ipmi_si.kipmid_max_busy_us=<ustime1>,<ustime2>,...
+
+It works the same as the module parameters of the same names.
+
+If your IPMI interface does not support interrupts and is a KCS or
+SMIC interface, the IPMI driver will start a kernel thread for the
+interface to help speed things up. This is a low-priority kernel
+thread that constantly polls the IPMI driver while an IPMI operation
+is in progress. The force_kipmid module parameter will all the user to
+force this thread on or off. If you force it off and don't have
+interrupts, the driver will run VERY slowly. Don't blame me,
+these interfaces suck.
+
+Unfortunately, this thread can use a lot of CPU depending on the
+interface's performance. This can waste a lot of CPU and cause
+various issues with detecting idle CPU and using extra power. To
+avoid this, the kipmid_max_busy_us sets the maximum amount of time, in
+microseconds, that kipmid will spin before sleeping for a tick. This
+value sets a balance between performance and CPU waste and needs to be
+tuned to your needs. Maybe, someday, auto-tuning will be added, but
+that's not a simple thing and even the auto-tuning would need to be
+tuned to the user's desired performance.
+
+The driver supports a hot add and remove of interfaces. This way,
+interfaces can be added or removed after the kernel is up and running.
+This is done using /sys/modules/ipmi_si/parameters/hotmod, which is a
+write-only parameter. You write a string to this interface. The string
+has the format::
+
+ <op1>[:op2[:op3...]]
+
+The "op"s are::
+
+ add|remove,kcs|bt|smic,mem|i/o,<address>[,<opt1>[,<opt2>[,...]]]
+
+You can specify more than one interface on the line. The "opt"s are::
+
+ rsp=<regspacing>
+ rsi=<regsize>
+ rsh=<regshift>
+ irq=<irq>
+ ipmb=<ipmb slave addr>
+
+and these have the same meanings as discussed above. Note that you
+can also use this on the kernel command line for a more compact format
+for specifying an interface. Note that when removing an interface,
+only the first three parameters (si type, address type, and address)
+are used for the comparison. Any options are ignored for removing.
+
+The SMBus Driver (SSIF)
+-----------------------
+
+The SMBus driver allows up to 4 SMBus devices to be configured in the
+system. By default, the driver will only register with something it
+finds in DMI or ACPI tables. You can change this
+at module load time (for a module) with::
+
+ modprobe ipmi_ssif.o
+ addr=<i2caddr1>[,<i2caddr2>[,...]]
+ adapter=<adapter1>[,<adapter2>[...]]
+ dbg=<flags1>,<flags2>...
+ slave_addrs=<addr1>,<addr2>,...
+ tryacpi=[0|1] trydmi=[0|1]
+ [dbg_probe=1]
+ alerts_broken
+
+The addresses are normal I2C addresses. The adapter is the string
+name of the adapter, as shown in /sys/class/i2c-adapter/i2c-<n>/name.
+It is *NOT* i2c-<n> itself. Also, the comparison is done ignoring
+spaces, so if the name is "This is an I2C chip" you can say
+adapter_name=ThisisanI2cchip. This is because it's hard to pass in
+spaces in kernel parameters.
+
+The debug flags are bit flags for each BMC found, they are:
+IPMI messages: 1, driver state: 2, timing: 4, I2C probe: 8
+
+The tryxxx parameters can be used to disable detecting interfaces
+from various sources.
+
+Setting dbg_probe to 1 will enable debugging of the probing and
+detection process for BMCs on the SMBusses.
+
+The slave_addrs specifies the IPMI address of the local BMC. This is
+usually 0x20 and the driver defaults to that, but in case it's not, it
+can be specified when the driver starts up.
+
+alerts_broken does not enable SMBus alert for SSIF. Otherwise SMBus
+alert will be enabled on supported hardware.
+
+Discovering the IPMI compliant BMC on the SMBus can cause devices on
+the I2C bus to fail. The SMBus driver writes a "Get Device ID" IPMI
+message as a block write to the I2C bus and waits for a response.
+This action can be detrimental to some I2C devices. It is highly
+recommended that the known I2C address be given to the SMBus driver in
+the smb_addr parameter unless you have DMI or ACPI data to tell the
+driver what to use.
+
+When compiled into the kernel, the addresses can be specified on the
+kernel command line as::
+
+ ipmb_ssif.addr=<i2caddr1>[,<i2caddr2>[...]]
+ ipmi_ssif.adapter=<adapter1>[,<adapter2>[...]]
+ ipmi_ssif.dbg=<flags1>[,<flags2>[...]]
+ ipmi_ssif.dbg_probe=1
+ ipmi_ssif.slave_addrs=<addr1>[,<addr2>[...]]
+ ipmi_ssif.tryacpi=[0|1] ipmi_ssif.trydmi=[0|1]
+
+These are the same options as on the module command line.
+
+The I2C driver does not support non-blocking access or polling, so
+this driver cannod to IPMI panic events, extend the watchdog at panic
+time, or other panic-related IPMI functions without special kernel
+patches and driver modifications. You can get those at the openipmi
+web page.
+
+The driver supports a hot add and remove of interfaces through the I2C
+sysfs interface.
+
+The IPMI IPMB Driver
+--------------------
+
+This driver is for supporting a system that sits on an IPMB bus; it
+allows the interface to look like a normal IPMI interface. Sending
+system interface addressed messages to it will cause the message to go
+to the registered BMC on the system (default at IPMI address 0x20).
+
+It also allows you to directly address other MCs on the bus using the
+ipmb direct addressing. You can receive commands from other MCs on
+the bus and they will be handled through the normal received command
+mechanism described above.
+
+Parameters are::
+
+ ipmi_ipmb.bmcaddr=<address to use for system interface addresses messages>
+ ipmi_ipmb.retry_time_ms=<Time between retries on IPMB>
+ ipmi_ipmb.max_retries=<Number of times to retry a message>
+
+Loading the module will not result in the driver automatcially
+starting unless there is device tree information setting it up. If
+you want to instantiate one of these by hand, do::
+
+ echo ipmi-ipmb <addr> > /sys/class/i2c-dev/i2c-<n>/device/new_device
+
+Note that the address you give here is the I2C address, not the IPMI
+address. So if you want your MC address to be 0x60, you put 0x30
+here. See the I2C driver info for more details.
+
+Command bridging to other IPMB busses through this interface does not
+work. The receive message queue is not implemented, by design. There
+is only one receive message queue on a BMC, and that is meant for the
+host drivers, not something on the IPMB bus.
+
+A BMC may have multiple IPMB busses, which bus your device sits on
+depends on how the system is wired. You can fetch the channels with
+"ipmitool channel info <n>" where <n> is the channel, with the
+channels being 0-7 and try the IPMB channels.
+
+Other Pieces
+------------
+
+Get the detailed info related with the IPMI device
+--------------------------------------------------
+
+Some users need more detailed information about a device, like where
+the address came from or the raw base device for the IPMI interface.
+You can use the IPMI smi_watcher to catch the IPMI interfaces as they
+come or go, and to grab the information, you can use the function
+ipmi_get_smi_info(), which returns the following structure::
+
+ struct ipmi_smi_info {
+ enum ipmi_addr_src addr_src;
+ struct device *dev;
+ union {
+ struct {
+ void *acpi_handle;
+ } acpi_info;
+ } addr_info;
+ };
+
+Currently special info for only for SI_ACPI address sources is
+returned. Others may be added as necessary.
+
+Note that the dev pointer is included in the above structure, and
+assuming ipmi_smi_get_info returns success, you must call put_device
+on the dev pointer.
+
+
+Watchdog
+--------
+
+A watchdog timer is provided that implements the Linux-standard
+watchdog timer interface. It has three module parameters that can be
+used to control it::
+
+ modprobe ipmi_watchdog timeout=<t> pretimeout=<t> action=<action type>
+ preaction=<preaction type> preop=<preop type> start_now=x
+ nowayout=x ifnum_to_use=n panic_wdt_timeout=<t>
+
+ifnum_to_use specifies which interface the watchdog timer should use.
+The default is -1, which means to pick the first one registered.
+
+The timeout is the number of seconds to the action, and the pretimeout
+is the amount of seconds before the reset that the pre-timeout panic will
+occur (if pretimeout is zero, then pretimeout will not be enabled). Note
+that the pretimeout is the time before the final timeout. So if the
+timeout is 50 seconds and the pretimeout is 10 seconds, then the pretimeout
+will occur in 40 second (10 seconds before the timeout). The panic_wdt_timeout
+is the value of timeout which is set on kernel panic, in order to let actions
+such as kdump to occur during panic.
+
+The action may be "reset", "power_cycle", or "power_off", and
+specifies what to do when the timer times out, and defaults to
+"reset".
+
+The preaction may be "pre_smi" for an indication through the SMI
+interface, "pre_int" for an indication through the SMI with an
+interrupts, and "pre_nmi" for a NMI on a preaction. This is how
+the driver is informed of the pretimeout.
+
+The preop may be set to "preop_none" for no operation on a pretimeout,
+"preop_panic" to set the preoperation to panic, or "preop_give_data"
+to provide data to read from the watchdog device when the pretimeout
+occurs. A "pre_nmi" setting CANNOT be used with "preop_give_data"
+because you can't do data operations from an NMI.
+
+When preop is set to "preop_give_data", one byte comes ready to read
+on the device when the pretimeout occurs. Select and fasync work on
+the device, as well.
+
+If start_now is set to 1, the watchdog timer will start running as
+soon as the driver is loaded.
+
+If nowayout is set to 1, the watchdog timer will not stop when the
+watchdog device is closed. The default value of nowayout is true
+if the CONFIG_WATCHDOG_NOWAYOUT option is enabled, or false if not.
+
+When compiled into the kernel, the kernel command line is available
+for configuring the watchdog::
+
+ ipmi_watchdog.timeout=<t> ipmi_watchdog.pretimeout=<t>
+ ipmi_watchdog.action=<action type>
+ ipmi_watchdog.preaction=<preaction type>
+ ipmi_watchdog.preop=<preop type>
+ ipmi_watchdog.start_now=x
+ ipmi_watchdog.nowayout=x
+ ipmi_watchdog.panic_wdt_timeout=<t>
+
+The options are the same as the module parameter options.
+
+The watchdog will panic and start a 120 second reset timeout if it
+gets a pre-action. During a panic or a reboot, the watchdog will
+start a 120 timer if it is running to make sure the reboot occurs.
+
+Note that if you use the NMI preaction for the watchdog, you MUST NOT
+use the nmi watchdog. There is no reasonable way to tell if an NMI
+comes from the IPMI controller, so it must assume that if it gets an
+otherwise unhandled NMI, it must be from IPMI and it will panic
+immediately.
+
+Once you open the watchdog timer, you must write a 'V' character to the
+device to close it, or the timer will not stop. This is a new semantic
+for the driver, but makes it consistent with the rest of the watchdog
+drivers in Linux.
+
+
+Panic Timeouts
+--------------
+
+The OpenIPMI driver supports the ability to put semi-custom and custom
+events in the system event log if a panic occurs. if you enable the
+'Generate a panic event to all BMCs on a panic' option, you will get
+one event on a panic in a standard IPMI event format. If you enable
+the 'Generate OEM events containing the panic string' option, you will
+also get a bunch of OEM events holding the panic string.
+
+
+The field settings of the events are:
+
+* Generator ID: 0x21 (kernel)
+* EvM Rev: 0x03 (this event is formatting in IPMI 1.0 format)
+* Sensor Type: 0x20 (OS critical stop sensor)
+* Sensor #: The first byte of the panic string (0 if no panic string)
+* Event Dir | Event Type: 0x6f (Assertion, sensor-specific event info)
+* Event Data 1: 0xa1 (Runtime stop in OEM bytes 2 and 3)
+* Event data 2: second byte of panic string
+* Event data 3: third byte of panic string
+
+See the IPMI spec for the details of the event layout. This event is
+always sent to the local management controller. It will handle routing
+the message to the right place
+
+Other OEM events have the following format:
+
+* Record ID (bytes 0-1): Set by the SEL.
+* Record type (byte 2): 0xf0 (OEM non-timestamped)
+* byte 3: The slave address of the card saving the panic
+* byte 4: A sequence number (starting at zero)
+ The rest of the bytes (11 bytes) are the panic string. If the panic string
+ is longer than 11 bytes, multiple messages will be sent with increasing
+ sequence numbers.
+
+Because you cannot send OEM events using the standard interface, this
+function will attempt to find an SEL and add the events there. It
+will first query the capabilities of the local management controller.
+If it has an SEL, then they will be stored in the SEL of the local
+management controller. If not, and the local management controller is
+an event generator, the event receiver from the local management
+controller will be queried and the events sent to the SEL on that
+device. Otherwise, the events go nowhere since there is nowhere to
+send them.
+
+
+Poweroff
+--------
+
+If the poweroff capability is selected, the IPMI driver will install
+a shutdown function into the standard poweroff function pointer. This
+is in the ipmi_poweroff module. When the system requests a powerdown,
+it will send the proper IPMI commands to do this. This is supported on
+several platforms.
+
+There is a module parameter named "poweroff_powercycle" that may
+either be zero (do a power down) or non-zero (do a power cycle, power
+the system off, then power it on in a few seconds). Setting
+ipmi_poweroff.poweroff_control=x will do the same thing on the kernel
+command line. The parameter is also available via the proc filesystem
+in /proc/sys/dev/ipmi/poweroff_powercycle. Note that if the system
+does not support power cycling, it will always do the power off.
+
+The "ifnum_to_use" parameter specifies which interface the poweroff
+code should use. The default is -1, which means to pick the first one
+registered.
+
+Note that if you have ACPI enabled, the system will prefer using ACPI to
+power off.
diff --git a/Documentation/driver-api/isa.rst b/Documentation/driver-api/isa.rst
index def4a7b690b5..3df1b1696524 100644
--- a/Documentation/driver-api/isa.rst
+++ b/Documentation/driver-api/isa.rst
@@ -100,7 +100,7 @@ I believe platform_data is available for this, but if rather not, moving
the isa_driver pointer to the private struct isa_dev is ofcourse fine as
well.
-Then, if the the driver did not provide a .match, it matches. If it did,
+Then, if the driver did not provide a .match, it matches. If it did,
the driver match() method is called to determine a match.
If it did **not** match, dev->platform_data is reset to indicate this to
diff --git a/Documentation/driver-api/isapnp.rst b/Documentation/driver-api/isapnp.rst
deleted file mode 100644
index 8d0840ac847b..000000000000
--- a/Documentation/driver-api/isapnp.rst
+++ /dev/null
@@ -1,15 +0,0 @@
-==========================================================
-ISA Plug & Play support by Jaroslav Kysela <perex@suse.cz>
-==========================================================
-
-Interface /proc/isapnp
-======================
-
-The interface has been removed. See pnp.txt for more details.
-
-Interface /proc/bus/isapnp
-==========================
-
-This directory allows access to ISA PnP cards and logical devices.
-The regular files contain the contents of ISA PnP registers for
-a logical device.
diff --git a/Documentation/driver-api/libata.rst b/Documentation/driver-api/libata.rst
index e2f87b82b074..5da27a749246 100644
--- a/Documentation/driver-api/libata.rst
+++ b/Documentation/driver-api/libata.rst
@@ -32,22 +32,6 @@ register blocks.
:c:type:`struct ata_port_operations <ata_port_operations>`
----------------------------------------------------------
-Disable ATA port
-~~~~~~~~~~~~~~~~
-
-::
-
- void (*port_disable) (struct ata_port *);
-
-
-Called from :c:func:`ata_bus_probe` error path, as well as when unregistering
-from the SCSI module (rmmod, hot unplug). This function should do
-whatever needs to be done to take the port out of use. In most cases,
-:c:func:`ata_port_disable` can be used as this hook.
-
-Called from :c:func:`ata_bus_probe` on a failed probe. Called from
-:c:func:`ata_scsi_release`.
-
Post-IDENTIFY device configuration
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -274,14 +258,6 @@ Exception and probe handling (EH)
::
- void (*eng_timeout) (struct ata_port *ap);
- void (*phy_reset) (struct ata_port *ap);
-
-
-Deprecated. Use ``->error_handler()`` instead.
-
-::
-
void (*freeze) (struct ata_port *ap);
void (*thaw) (struct ata_port *ap);
@@ -364,8 +340,7 @@ SATA phy read/write
u32 val);
-Read and write standard SATA phy registers. Currently only used if
-``->phy_reset`` hook called the :c:func:`sata_phy_reset` helper function.
+Read and write standard SATA phy registers.
sc_reg is one of SCR_STATUS, SCR_CONTROL, SCR_ERROR, or SCR_ACTIVE.
Init and shutdown
@@ -424,12 +399,6 @@ How commands are issued
-----------------------
Internal commands
- First, qc is allocated and initialized using :c:func:`ata_qc_new_init`.
- Although :c:func:`ata_qc_new_init` doesn't implement any wait or retry
- mechanism when qc is not available, internal commands are currently
- issued only during initialization and error recovery, so no other
- command is active and allocation is guaranteed to succeed.
-
Once allocated qc's taskfile is initialized for the command to be
executed. qc currently has two mechanisms to notify completion. One
is via ``qc->complete_fn()`` callback and the other is completion
@@ -447,11 +416,6 @@ SCSI commands
translated. No qc is involved in processing a simulated scmd. The
result is computed right away and the scmd is completed.
- For a translated scmd, :c:func:`ata_qc_new_init` is invoked to allocate a
- qc and the scmd is translated into the qc. SCSI midlayer's
- completion notification function pointer is stored into
- ``qc->scsidone``.
-
``qc->complete_fn()`` callback is used for completion notification. ATA
commands use :c:func:`ata_scsi_qc_complete` while ATAPI commands use
:c:func:`atapi_qc_complete`. Both functions end up calling ``qc->scsidone``
@@ -508,7 +472,7 @@ also complete commands.
2. ATA_QCFLAG_ACTIVE is cleared from qc->flags.
-3. :c:func:`qc->complete_fn` callback is invoked. If the return value of the
+3. :c:expr:`qc->complete_fn` callback is invoked. If the return value of the
callback is not zero. Completion is short circuited and
:c:func:`ata_qc_complete` returns.
@@ -547,13 +511,12 @@ to return without deallocating the qc. This leads us to
:c:func:`ata_scsi_error` is the current ``transportt->eh_strategy_handler()``
for libata. As discussed above, this will be entered in two cases -
-timeout and ATAPI error completion. This function calls low level libata
-driver's :c:func:`eng_timeout` callback, the standard callback for which is
-:c:func:`ata_eng_timeout`. It checks if a qc is active and calls
-:c:func:`ata_qc_timeout` on the qc if so. Actual error handling occurs in
-:c:func:`ata_qc_timeout`.
+timeout and ATAPI error completion. This function will check if a qc is active
+and has not failed yet. Such a qc will be marked with AC_ERR_TIMEOUT such that
+EH will know to handle it later. Then it calls low level libata driver's
+:c:func:`error_handler` callback.
-If EH is invoked for timeout, :c:func:`ata_qc_timeout` stops BMDMA and
+When the :c:func:`error_handler` callback is invoked it stops BMDMA and
completes the qc. Note that as we're currently in EH, we cannot call
scsi_done. As described in SCSI EH doc, a recovered scmd should be
either retried with :c:func:`scsi_queue_insert` or finished with
diff --git a/Documentation/driver-api/lightnvm-pblk.rst b/Documentation/driver-api/lightnvm-pblk.rst
deleted file mode 100644
index 1040ed1cec81..000000000000
--- a/Documentation/driver-api/lightnvm-pblk.rst
+++ /dev/null
@@ -1,21 +0,0 @@
-pblk: Physical Block Device Target
-==================================
-
-pblk implements a fully associative, host-based FTL that exposes a traditional
-block I/O interface. Its primary responsibilities are:
-
- - Map logical addresses onto physical addresses (4KB granularity) in a
- logical-to-physical (L2P) table.
- - Maintain the integrity and consistency of the L2P table as well as its
- recovery from normal tear down and power outage.
- - Deal with controller- and media-specific constrains.
- - Handle I/O errors.
- - Implement garbage collection.
- - Maintain consistency across the I/O stack during synchronization points.
-
-For more information please refer to:
-
- http://lightnvm.io
-
-which maintains updated FAQs, manual pages, technical documentation, tools,
-contacts, etc.
diff --git a/Documentation/driver-api/mailbox.rst b/Documentation/driver-api/mailbox.rst
new file mode 100644
index 000000000000..0ed95009cc30
--- /dev/null
+++ b/Documentation/driver-api/mailbox.rst
@@ -0,0 +1,129 @@
+============================
+The Common Mailbox Framework
+============================
+
+:Author: Jassi Brar <jaswinder.singh@linaro.org>
+
+This document aims to help developers write client and controller
+drivers for the API. But before we start, let us note that the
+client (especially) and controller drivers are likely going to be
+very platform specific because the remote firmware is likely to be
+proprietary and implement non-standard protocol. So even if two
+platforms employ, say, PL320 controller, the client drivers can't
+be shared across them. Even the PL320 driver might need to accommodate
+some platform specific quirks. So the API is meant mainly to avoid
+similar copies of code written for each platform. Having said that,
+nothing prevents the remote f/w to also be Linux based and use the
+same api there. However none of that helps us locally because we only
+ever deal at client's protocol level.
+
+Some of the choices made during implementation are the result of this
+peculiarity of this "common" framework.
+
+
+
+Controller Driver (See include/linux/mailbox_controller.h)
+==========================================================
+
+
+Allocate mbox_controller and the array of mbox_chan.
+Populate mbox_chan_ops, except peek_data() all are mandatory.
+The controller driver might know a message has been consumed
+by the remote by getting an IRQ or polling some hardware flag
+or it can never know (the client knows by way of the protocol).
+The method in order of preference is IRQ -> Poll -> None, which
+the controller driver should set via 'txdone_irq' or 'txdone_poll'
+or neither.
+
+
+Client Driver (See include/linux/mailbox_client.h)
+==================================================
+
+
+The client might want to operate in blocking mode (synchronously
+send a message through before returning) or non-blocking/async mode (submit
+a message and a callback function to the API and return immediately).
+
+::
+
+ struct demo_client {
+ struct mbox_client cl;
+ struct mbox_chan *mbox;
+ struct completion c;
+ bool async;
+ /* ... */
+ };
+
+ /*
+ * This is the handler for data received from remote. The behaviour is purely
+ * dependent upon the protocol. This is just an example.
+ */
+ static void message_from_remote(struct mbox_client *cl, void *mssg)
+ {
+ struct demo_client *dc = container_of(cl, struct demo_client, cl);
+ if (dc->async) {
+ if (is_an_ack(mssg)) {
+ /* An ACK to our last sample sent */
+ return; /* Or do something else here */
+ } else { /* A new message from remote */
+ queue_req(mssg);
+ }
+ } else {
+ /* Remote f/w sends only ACK packets on this channel */
+ return;
+ }
+ }
+
+ static void sample_sent(struct mbox_client *cl, void *mssg, int r)
+ {
+ struct demo_client *dc = container_of(cl, struct demo_client, cl);
+ complete(&dc->c);
+ }
+
+ static void client_demo(struct platform_device *pdev)
+ {
+ struct demo_client *dc_sync, *dc_async;
+ /* The controller already knows async_pkt and sync_pkt */
+ struct async_pkt ap;
+ struct sync_pkt sp;
+
+ dc_sync = kzalloc(sizeof(*dc_sync), GFP_KERNEL);
+ dc_async = kzalloc(sizeof(*dc_async), GFP_KERNEL);
+
+ /* Populate non-blocking mode client */
+ dc_async->cl.dev = &pdev->dev;
+ dc_async->cl.rx_callback = message_from_remote;
+ dc_async->cl.tx_done = sample_sent;
+ dc_async->cl.tx_block = false;
+ dc_async->cl.tx_tout = 0; /* doesn't matter here */
+ dc_async->cl.knows_txdone = false; /* depending upon protocol */
+ dc_async->async = true;
+ init_completion(&dc_async->c);
+
+ /* Populate blocking mode client */
+ dc_sync->cl.dev = &pdev->dev;
+ dc_sync->cl.rx_callback = message_from_remote;
+ dc_sync->cl.tx_done = NULL; /* operate in blocking mode */
+ dc_sync->cl.tx_block = true;
+ dc_sync->cl.tx_tout = 500; /* by half a second */
+ dc_sync->cl.knows_txdone = false; /* depending upon protocol */
+ dc_sync->async = false;
+
+ /* ASync mailbox is listed second in 'mboxes' property */
+ dc_async->mbox = mbox_request_channel(&dc_async->cl, 1);
+ /* Populate data packet */
+ /* ap.xxx = 123; etc */
+ /* Send async message to remote */
+ mbox_send_message(dc_async->mbox, &ap);
+
+ /* Sync mailbox is listed first in 'mboxes' property */
+ dc_sync->mbox = mbox_request_channel(&dc_sync->cl, 0);
+ /* Populate data packet */
+ /* sp.abc = 123; etc */
+ /* Send message to remote in blocking mode */
+ mbox_send_message(dc_sync->mbox, &sp);
+ /* At this point 'sp' has been sent */
+
+ /* Now wait for async chan to be done */
+ wait_for_completion(&dc_async->c);
+ }
diff --git a/Documentation/driver-api/md/md-cluster.rst b/Documentation/driver-api/md/md-cluster.rst
index 96eb52cec7eb..e93f35e0e157 100644
--- a/Documentation/driver-api/md/md-cluster.rst
+++ b/Documentation/driver-api/md/md-cluster.rst
@@ -65,7 +65,7 @@ There are three groups of locks for managing the device:
2.3 new-device management
-------------------------
- A single lock: "no-new-dev" is used to co-ordinate the addition of
+ A single lock: "no-new-dev" is used to coordinate the addition of
new devices - this must be synchronized across the array.
Normally all nodes hold a concurrent-read lock on this device.
diff --git a/Documentation/driver-api/md/raid5-cache.rst b/Documentation/driver-api/md/raid5-cache.rst
index d7a15f44a7c3..5f947cbc2e78 100644
--- a/Documentation/driver-api/md/raid5-cache.rst
+++ b/Documentation/driver-api/md/raid5-cache.rst
@@ -81,7 +81,7 @@ The write-through and write-back cache use the same disk format. The cache disk
is organized as a simple write log. The log consists of 'meta data' and 'data'
pairs. The meta data describes the data. It also includes checksum and sequence
ID for recovery identification. Data can be IO data and parity data. Data is
-checksumed too. The checksum is stored in the meta data ahead of the data. The
+checksummed too. The checksum is stored in the meta data ahead of the data. The
checksum is an optimization because MD can write meta and data freely without
worry about the order. MD superblock has a field pointed to the valid meta data
of log head.
diff --git a/Documentation/driver-api/media/camera-sensor.rst b/Documentation/driver-api/media/camera-sensor.rst
new file mode 100644
index 000000000000..b4920b34cebc
--- /dev/null
+++ b/Documentation/driver-api/media/camera-sensor.rst
@@ -0,0 +1,148 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+.. _media_writing_camera_sensor_drivers:
+
+Writing camera sensor drivers
+=============================
+
+This document covers the in-kernel APIs only. For the best practices on
+userspace API implementation in camera sensor drivers, please see
+:ref:`media_using_camera_sensor_drivers`.
+
+CSI-2, parallel and BT.656 buses
+--------------------------------
+
+Please see :ref:`transmitter-receiver`.
+
+Handling clocks
+---------------
+
+Camera sensors have an internal clock tree including a PLL and a number of
+divisors. The clock tree is generally configured by the driver based on a few
+input parameters that are specific to the hardware: the external clock frequency
+and the link frequency. The two parameters generally are obtained from system
+firmware. **No other frequencies should be used in any circumstances.**
+
+The reason why the clock frequencies are so important is that the clock signals
+come out of the SoC, and in many cases a specific frequency is designed to be
+used in the system. Using another frequency may cause harmful effects
+elsewhere. Therefore only the pre-determined frequencies are configurable by the
+user.
+
+ACPI
+~~~~
+
+Read the ``clock-frequency`` _DSD property to denote the frequency. The driver
+can rely on this frequency being used.
+
+Devicetree
+~~~~~~~~~~
+
+The preferred way to achieve this is using ``assigned-clocks``,
+``assigned-clock-parents`` and ``assigned-clock-rates`` properties. See the
+`clock device tree bindings
+<https://github.com/devicetree-org/dt-schema/blob/main/dtschema/schemas/clock/clock.yaml>`_
+for more information. The driver then gets the frequency using
+``clk_get_rate()``.
+
+This approach has the drawback that there's no guarantee that the frequency
+hasn't been modified directly or indirectly by another driver, or supported by
+the board's clock tree to begin with. Changes to the Common Clock Framework API
+are required to ensure reliability.
+
+Power management
+----------------
+
+Camera sensors are used in conjunction with other devices to form a camera
+pipeline. They must obey the rules listed herein to ensure coherent power
+management over the pipeline.
+
+Camera sensor drivers are responsible for controlling the power state of the
+device they otherwise control as well. They shall use runtime PM to manage
+power states. Runtime PM shall be enabled at probe time and disabled at remove
+time. Drivers should enable runtime PM autosuspend. Also see
+:ref:`async sub-device registration <media-registering-async-subdevs>`.
+
+The runtime PM handlers shall handle clocks, regulators, GPIOs, and other
+system resources required to power the sensor up and down. For drivers that
+don't use any of those resources (such as drivers that support ACPI systems
+only), the runtime PM handlers may be left unimplemented.
+
+In general, the device shall be powered on at least when its registers are
+being accessed and when it is streaming. Drivers should use
+``pm_runtime_resume_and_get()`` when starting streaming and
+``pm_runtime_put()`` or ``pm_runtime_put_autosuspend()`` when stopping
+streaming. They may power the device up at probe time (for example to read
+identification registers), but should not keep it powered unconditionally after
+probe.
+
+At system suspend time, the whole camera pipeline must stop streaming, and
+restart when the system is resumed. This requires coordination between the
+camera sensor and the rest of the camera pipeline. Bridge drivers are
+responsible for this coordination, and instruct camera sensors to stop and
+restart streaming by calling the appropriate subdev operations
+(``.s_stream()``, ``.enable_streams()`` or ``.disable_streams()``). Camera
+sensor drivers shall therefore **not** keep track of the streaming state to
+stop streaming in the PM suspend handler and restart it in the resume handler.
+Drivers should in general not implement the system PM handlers.
+
+Camera sensor drivers shall **not** implement the subdev ``.s_power()``
+operation, as it is deprecated. While this operation is implemented in some
+existing drivers as they predate the deprecation, new drivers shall use runtime
+PM instead. If you feel you need to begin calling ``.s_power()`` from an ISP or
+a bridge driver, instead add runtime PM support to the sensor driver you are
+using and drop its ``.s_power()`` handler.
+
+Please also see :ref:`examples <media-camera-sensor-examples>`.
+
+Control framework
+~~~~~~~~~~~~~~~~~
+
+``v4l2_ctrl_handler_setup()`` function may not be used in the device's runtime
+PM ``runtime_resume`` callback, as it has no way to figure out the power state
+of the device. This is because the power state of the device is only changed
+after the power state transition has taken place. The ``s_ctrl`` callback can be
+used to obtain device's power state after the power state transition:
+
+.. c:function:: int pm_runtime_get_if_in_use(struct device *dev);
+
+The function returns a non-zero value if it succeeded getting the power count or
+runtime PM was disabled, in either of which cases the driver may proceed to
+access the device.
+
+Rotation, orientation and flipping
+----------------------------------
+
+Use ``v4l2_fwnode_device_parse()`` to obtain rotation and orientation
+information from system firmware and ``v4l2_ctrl_new_fwnode_properties()`` to
+register the appropriate controls.
+
+.. _media-camera-sensor-examples:
+
+Example drivers
+---------------
+
+Features implemented by sensor drivers vary, and depending on the set of
+supported features and other qualities, particular sensor drivers better serve
+the purpose of an example. The following drivers are known to be good examples:
+
+.. flat-table:: Example sensor drivers
+ :header-rows: 0
+ :widths: 1 1 1 2
+
+ * - Driver name
+ - File(s)
+ - Driver type
+ - Example topic
+ * - CCS
+ - ``drivers/media/i2c/ccs/``
+ - Freely configurable
+ - Power management (ACPI and DT), UAPI
+ * - imx219
+ - ``drivers/media/i2c/imx219.c``
+ - Register list based
+ - Power management (DT), UAPI, mode selection
+ * - imx319
+ - ``drivers/media/i2c/imx319.c``
+ - Register list based
+ - Power management (ACPI and DT)
diff --git a/Documentation/driver-api/media/cec-core.rst b/Documentation/driver-api/media/cec-core.rst
new file mode 100644
index 000000000000..f1ffdec388f3
--- /dev/null
+++ b/Documentation/driver-api/media/cec-core.rst
@@ -0,0 +1,502 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+CEC Kernel Support
+==================
+
+The CEC framework provides a unified kernel interface for use with HDMI CEC
+hardware. It is designed to handle a multiple types of hardware (receivers,
+transmitters, USB dongles). The framework also gives the option to decide
+what to do in the kernel driver and what should be handled by userspace
+applications. In addition it integrates the remote control passthrough
+feature into the kernel's remote control framework.
+
+
+The CEC Protocol
+----------------
+
+The CEC protocol enables consumer electronic devices to communicate with each
+other through the HDMI connection. The protocol uses logical addresses in the
+communication. The logical address is strictly connected with the functionality
+provided by the device. The TV acting as the communication hub is always
+assigned address 0. The physical address is determined by the physical
+connection between devices.
+
+The CEC framework described here is up to date with the CEC 2.0 specification.
+It is documented in the HDMI 1.4 specification with the new 2.0 bits documented
+in the HDMI 2.0 specification. But for most of the features the freely available
+HDMI 1.3a specification is sufficient:
+
+https://www.hdmi.org/spec/index
+
+
+CEC Adapter Interface
+---------------------
+
+The struct cec_adapter represents the CEC adapter hardware. It is created by
+calling cec_allocate_adapter() and deleted by calling cec_delete_adapter():
+
+.. c:function::
+ struct cec_adapter *cec_allocate_adapter(const struct cec_adap_ops *ops, \
+ void *priv, const char *name, \
+ u32 caps, u8 available_las);
+
+.. c:function::
+ void cec_delete_adapter(struct cec_adapter *adap);
+
+To create an adapter you need to pass the following information:
+
+ops:
+ adapter operations which are called by the CEC framework and that you
+ have to implement.
+
+priv:
+ will be stored in adap->priv and can be used by the adapter ops.
+ Use cec_get_drvdata(adap) to get the priv pointer.
+
+name:
+ the name of the CEC adapter. Note: this name will be copied.
+
+caps:
+ capabilities of the CEC adapter. These capabilities determine the
+ capabilities of the hardware and which parts are to be handled
+ by userspace and which parts are handled by kernelspace. The
+ capabilities are returned by CEC_ADAP_G_CAPS.
+
+available_las:
+ the number of simultaneous logical addresses that this
+ adapter can handle. Must be 1 <= available_las <= CEC_MAX_LOG_ADDRS.
+
+To obtain the priv pointer use this helper function:
+
+.. c:function::
+ void *cec_get_drvdata(const struct cec_adapter *adap);
+
+To register the /dev/cecX device node and the remote control device (if
+CEC_CAP_RC is set) you call:
+
+.. c:function::
+ int cec_register_adapter(struct cec_adapter *adap, \
+ struct device *parent);
+
+where parent is the parent device.
+
+To unregister the devices call:
+
+.. c:function::
+ void cec_unregister_adapter(struct cec_adapter *adap);
+
+Note: if cec_register_adapter() fails, then call cec_delete_adapter() to
+clean up. But if cec_register_adapter() succeeded, then only call
+cec_unregister_adapter() to clean up, never cec_delete_adapter(). The
+unregister function will delete the adapter automatically once the last user
+of that /dev/cecX device has closed its file handle.
+
+
+Implementing the Low-Level CEC Adapter
+--------------------------------------
+
+The following low-level adapter operations have to be implemented in
+your driver:
+
+.. c:struct:: cec_adap_ops
+
+.. code-block:: none
+
+ struct cec_adap_ops
+ {
+ /* Low-level callbacks */
+ int (*adap_enable)(struct cec_adapter *adap, bool enable);
+ int (*adap_monitor_all_enable)(struct cec_adapter *adap, bool enable);
+ int (*adap_monitor_pin_enable)(struct cec_adapter *adap, bool enable);
+ int (*adap_log_addr)(struct cec_adapter *adap, u8 logical_addr);
+ void (*adap_unconfigured)(struct cec_adapter *adap);
+ int (*adap_transmit)(struct cec_adapter *adap, u8 attempts,
+ u32 signal_free_time, struct cec_msg *msg);
+ void (*adap_nb_transmit_canceled)(struct cec_adapter *adap,
+ const struct cec_msg *msg);
+ void (*adap_status)(struct cec_adapter *adap, struct seq_file *file);
+ void (*adap_free)(struct cec_adapter *adap);
+
+ /* Error injection callbacks */
+ ...
+
+ /* High-level callback */
+ ...
+ };
+
+These low-level ops deal with various aspects of controlling the CEC adapter
+hardware. They are all called with the mutex adap->lock held.
+
+
+To enable/disable the hardware::
+
+ int (*adap_enable)(struct cec_adapter *adap, bool enable);
+
+This callback enables or disables the CEC hardware. Enabling the CEC hardware
+means powering it up in a state where no logical addresses are claimed. The
+physical address will always be valid if CEC_CAP_NEEDS_HPD is set. If that
+capability is not set, then the physical address can change while the CEC
+hardware is enabled. CEC drivers should not set CEC_CAP_NEEDS_HPD unless
+the hardware design requires that as this will make it impossible to wake
+up displays that pull the HPD low when in standby mode. The initial
+state of the CEC adapter after calling cec_allocate_adapter() is disabled.
+
+Note that adap_enable must return 0 if enable is false.
+
+
+To enable/disable the 'monitor all' mode::
+
+ int (*adap_monitor_all_enable)(struct cec_adapter *adap, bool enable);
+
+If enabled, then the adapter should be put in a mode to also monitor messages
+that are not for us. Not all hardware supports this and this function is only
+called if the CEC_CAP_MONITOR_ALL capability is set. This callback is optional
+(some hardware may always be in 'monitor all' mode).
+
+Note that adap_monitor_all_enable must return 0 if enable is false.
+
+
+To enable/disable the 'monitor pin' mode::
+
+ int (*adap_monitor_pin_enable)(struct cec_adapter *adap, bool enable);
+
+If enabled, then the adapter should be put in a mode to also monitor CEC pin
+changes. Not all hardware supports this and this function is only called if
+the CEC_CAP_MONITOR_PIN capability is set. This callback is optional
+(some hardware may always be in 'monitor pin' mode).
+
+Note that adap_monitor_pin_enable must return 0 if enable is false.
+
+
+To program a new logical address::
+
+ int (*adap_log_addr)(struct cec_adapter *adap, u8 logical_addr);
+
+If logical_addr == CEC_LOG_ADDR_INVALID then all programmed logical addresses
+are to be erased. Otherwise the given logical address should be programmed.
+If the maximum number of available logical addresses is exceeded, then it
+should return -ENXIO. Once a logical address is programmed the CEC hardware
+can receive directed messages to that address.
+
+Note that adap_log_addr must return 0 if logical_addr is CEC_LOG_ADDR_INVALID.
+
+
+Called when the adapter is unconfigured::
+
+ void (*adap_unconfigured)(struct cec_adapter *adap);
+
+The adapter is unconfigured. If the driver has to take specific actions after
+unconfiguration, then that can be done through this optional callback.
+
+
+To transmit a new message::
+
+ int (*adap_transmit)(struct cec_adapter *adap, u8 attempts,
+ u32 signal_free_time, struct cec_msg *msg);
+
+This transmits a new message. The attempts argument is the suggested number of
+attempts for the transmit.
+
+The signal_free_time is the number of data bit periods that the adapter should
+wait when the line is free before attempting to send a message. This value
+depends on whether this transmit is a retry, a message from a new initiator or
+a new message for the same initiator. Most hardware will handle this
+automatically, but in some cases this information is needed.
+
+The CEC_FREE_TIME_TO_USEC macro can be used to convert signal_free_time to
+microseconds (one data bit period is 2.4 ms).
+
+
+To pass on the result of a canceled non-blocking transmit::
+
+ void (*adap_nb_transmit_canceled)(struct cec_adapter *adap,
+ const struct cec_msg *msg);
+
+This optional callback can be used to obtain the result of a canceled
+non-blocking transmit with sequence number msg->sequence. This is
+called if the transmit was aborted, the transmit timed out (i.e. the
+hardware never signaled that the transmit finished), or the transmit
+was successful, but the wait for the expected reply was either aborted
+or it timed out.
+
+
+To log the current CEC hardware status::
+
+ void (*adap_status)(struct cec_adapter *adap, struct seq_file *file);
+
+This optional callback can be used to show the status of the CEC hardware.
+The status is available through debugfs: cat /sys/kernel/debug/cec/cecX/status
+
+To free any resources when the adapter is deleted::
+
+ void (*adap_free)(struct cec_adapter *adap);
+
+This optional callback can be used to free any resources that might have been
+allocated by the driver. It's called from cec_delete_adapter.
+
+
+Your adapter driver will also have to react to events (typically interrupt
+driven) by calling into the framework in the following situations:
+
+When a transmit finished (successfully or otherwise)::
+
+ void cec_transmit_done(struct cec_adapter *adap, u8 status,
+ u8 arb_lost_cnt, u8 nack_cnt, u8 low_drive_cnt,
+ u8 error_cnt);
+
+or::
+
+ void cec_transmit_attempt_done(struct cec_adapter *adap, u8 status);
+
+The status can be one of:
+
+CEC_TX_STATUS_OK:
+ the transmit was successful.
+
+CEC_TX_STATUS_ARB_LOST:
+ arbitration was lost: another CEC initiator
+ took control of the CEC line and you lost the arbitration.
+
+CEC_TX_STATUS_NACK:
+ the message was nacked (for a directed message) or
+ acked (for a broadcast message). A retransmission is needed.
+
+CEC_TX_STATUS_LOW_DRIVE:
+ low drive was detected on the CEC bus. This indicates that
+ a follower detected an error on the bus and requested a
+ retransmission.
+
+CEC_TX_STATUS_ERROR:
+ some unspecified error occurred: this can be one of ARB_LOST
+ or LOW_DRIVE if the hardware cannot differentiate or something
+ else entirely. Some hardware only supports OK and FAIL as the
+ result of a transmit, i.e. there is no way to differentiate
+ between the different possible errors. In that case map FAIL
+ to CEC_TX_STATUS_NACK and not to CEC_TX_STATUS_ERROR.
+
+CEC_TX_STATUS_MAX_RETRIES:
+ could not transmit the message after trying multiple times.
+ Should only be set by the driver if it has hardware support for
+ retrying messages. If set, then the framework assumes that it
+ doesn't have to make another attempt to transmit the message
+ since the hardware did that already.
+
+The hardware must be able to differentiate between OK, NACK and 'something
+else'.
+
+The \*_cnt arguments are the number of error conditions that were seen.
+This may be 0 if no information is available. Drivers that do not support
+hardware retry can just set the counter corresponding to the transmit error
+to 1, if the hardware does support retry then either set these counters to
+0 if the hardware provides no feedback of which errors occurred and how many
+times, or fill in the correct values as reported by the hardware.
+
+Be aware that calling these functions can immediately start a new transmit
+if there is one pending in the queue. So make sure that the hardware is in
+a state where new transmits can be started *before* calling these functions.
+
+The cec_transmit_attempt_done() function is a helper for cases where the
+hardware never retries, so the transmit is always for just a single
+attempt. It will call cec_transmit_done() in turn, filling in 1 for the
+count argument corresponding to the status. Or all 0 if the status was OK.
+
+When a CEC message was received:
+
+.. c:function::
+ void cec_received_msg(struct cec_adapter *adap, struct cec_msg *msg);
+
+Speaks for itself.
+
+Implementing the interrupt handler
+----------------------------------
+
+Typically the CEC hardware provides interrupts that signal when a transmit
+finished and whether it was successful or not, and it provides and interrupt
+when a CEC message was received.
+
+The CEC driver should always process the transmit interrupts first before
+handling the receive interrupt. The framework expects to see the cec_transmit_done
+call before the cec_received_msg call, otherwise it can get confused if the
+received message was in reply to the transmitted message.
+
+Optional: Implementing Error Injection Support
+----------------------------------------------
+
+If the CEC adapter supports Error Injection functionality, then that can
+be exposed through the Error Injection callbacks:
+
+.. code-block:: none
+
+ struct cec_adap_ops {
+ /* Low-level callbacks */
+ ...
+
+ /* Error injection callbacks */
+ int (*error_inj_show)(struct cec_adapter *adap, struct seq_file *sf);
+ bool (*error_inj_parse_line)(struct cec_adapter *adap, char *line);
+
+ /* High-level CEC message callback */
+ ...
+ };
+
+If both callbacks are set, then an ``error-inj`` file will appear in debugfs.
+The basic syntax is as follows:
+
+Leading spaces/tabs are ignored. If the next character is a ``#`` or the end of the
+line was reached, then the whole line is ignored. Otherwise a command is expected.
+
+This basic parsing is done in the CEC Framework. It is up to the driver to decide
+what commands to implement. The only requirement is that the command ``clear`` without
+any arguments must be implemented and that it will remove all current error injection
+commands.
+
+This ensures that you can always do ``echo clear >error-inj`` to clear any error
+injections without having to know the details of the driver-specific commands.
+
+Note that the output of ``error-inj`` shall be valid as input to ``error-inj``.
+So this must work:
+
+.. code-block:: none
+
+ $ cat error-inj >einj.txt
+ $ cat einj.txt >error-inj
+
+The first callback is called when this file is read and it should show the
+current error injection state::
+
+ int (*error_inj_show)(struct cec_adapter *adap, struct seq_file *sf);
+
+It is recommended that it starts with a comment block with basic usage
+information. It returns 0 for success and an error otherwise.
+
+The second callback will parse commands written to the ``error-inj`` file::
+
+ bool (*error_inj_parse_line)(struct cec_adapter *adap, char *line);
+
+The ``line`` argument points to the start of the command. Any leading
+spaces or tabs have already been skipped. It is a single line only (so there
+are no embedded newlines) and it is 0-terminated. The callback is free to
+modify the contents of the buffer. It is only called for lines containing a
+command, so this callback is never called for empty lines or comment lines.
+
+Return true if the command was valid or false if there were syntax errors.
+
+Implementing the High-Level CEC Adapter
+---------------------------------------
+
+The low-level operations drive the hardware, the high-level operations are
+CEC protocol driven. The high-level callbacks are called without the adap->lock
+mutex being held. The following high-level callbacks are available:
+
+.. code-block:: none
+
+ struct cec_adap_ops {
+ /* Low-level callbacks */
+ ...
+
+ /* Error injection callbacks */
+ ...
+
+ /* High-level CEC message callback */
+ void (*configured)(struct cec_adapter *adap);
+ int (*received)(struct cec_adapter *adap, struct cec_msg *msg);
+ };
+
+Called when the adapter is configured::
+
+ void (*configured)(struct cec_adapter *adap);
+
+The adapter is fully configured, i.e. all logical addresses have been
+successfully claimed. If the driver has to take specific actions after
+configuration, then that can be done through this optional callback.
+
+
+The received() callback allows the driver to optionally handle a newly
+received CEC message::
+
+ int (*received)(struct cec_adapter *adap, struct cec_msg *msg);
+
+If the driver wants to process a CEC message, then it can implement this
+callback. If it doesn't want to handle this message, then it should return
+-ENOMSG, otherwise the CEC framework assumes it processed this message and
+it will not do anything with it.
+
+
+CEC framework functions
+-----------------------
+
+CEC Adapter drivers can call the following CEC framework functions:
+
+.. c:function::
+ int cec_transmit_msg(struct cec_adapter *adap, struct cec_msg *msg, \
+ bool block);
+
+Transmit a CEC message. If block is true, then wait until the message has been
+transmitted, otherwise just queue it and return.
+
+.. c:function::
+ void cec_s_phys_addr(struct cec_adapter *adap, u16 phys_addr, bool block);
+
+Change the physical address. This function will set adap->phys_addr and
+send an event if it has changed. If cec_s_log_addrs() has been called and
+the physical address has become valid, then the CEC framework will start
+claiming the logical addresses. If block is true, then this function won't
+return until this process has finished.
+
+When the physical address is set to a valid value the CEC adapter will
+be enabled (see the adap_enable op). When it is set to CEC_PHYS_ADDR_INVALID,
+then the CEC adapter will be disabled. If you change a valid physical address
+to another valid physical address, then this function will first set the
+address to CEC_PHYS_ADDR_INVALID before enabling the new physical address.
+
+.. c:function::
+ void cec_s_phys_addr_from_edid(struct cec_adapter *adap, \
+ const struct edid *edid);
+
+A helper function that extracts the physical address from the edid struct
+and calls cec_s_phys_addr() with that address, or CEC_PHYS_ADDR_INVALID
+if the EDID did not contain a physical address or edid was a NULL pointer.
+
+.. c:function::
+ int cec_s_log_addrs(struct cec_adapter *adap, \
+ struct cec_log_addrs *log_addrs, bool block);
+
+Claim the CEC logical addresses. Should never be called if CEC_CAP_LOG_ADDRS
+is set. If block is true, then wait until the logical addresses have been
+claimed, otherwise just queue it and return. To unconfigure all logical
+addresses call this function with log_addrs set to NULL or with
+log_addrs->num_log_addrs set to 0. The block argument is ignored when
+unconfiguring. This function will just return if the physical address is
+invalid. Once the physical address becomes valid, then the framework will
+attempt to claim these logical addresses.
+
+CEC Pin framework
+-----------------
+
+Most CEC hardware operates on full CEC messages where the software provides
+the message and the hardware handles the low-level CEC protocol. But some
+hardware only drives the CEC pin and software has to handle the low-level
+CEC protocol. The CEC pin framework was created to handle such devices.
+
+Note that due to the close-to-realtime requirements it can never be guaranteed
+to work 100%. This framework uses highres timers internally, but if a
+timer goes off too late by more than 300 microseconds wrong results can
+occur. In reality it appears to be fairly reliable.
+
+One advantage of this low-level implementation is that it can be used as
+a cheap CEC analyser, especially if interrupts can be used to detect
+CEC pin transitions from low to high or vice versa.
+
+.. kernel-doc:: include/media/cec-pin.h
+
+CEC Notifier framework
+----------------------
+
+Most drm HDMI implementations have an integrated CEC implementation and no
+notifier support is needed. But some have independent CEC implementations
+that have their own driver. This could be an IP block for an SoC or a
+completely separate chip that deals with the CEC pin. For those cases a
+drm driver can install a notifier and use the notifier to inform the
+CEC driver about changes in the physical address.
+
+.. kernel-doc:: include/media/cec-notifier.h
diff --git a/Documentation/driver-api/media/drivers/bttv-devel.rst b/Documentation/driver-api/media/drivers/bttv-devel.rst
new file mode 100644
index 000000000000..0885a04563a9
--- /dev/null
+++ b/Documentation/driver-api/media/drivers/bttv-devel.rst
@@ -0,0 +1,116 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+The bttv driver
+===============
+
+bttv and sound mini howto
+-------------------------
+
+There are a lot of different bt848/849/878/879 based boards available.
+Making video work often is not a big deal, because this is handled
+completely by the bt8xx chip, which is common on all boards. But
+sound is handled in slightly different ways on each board.
+
+To handle the grabber boards correctly, there is a array tvcards[] in
+bttv-cards.c, which holds the information required for each board.
+Sound will work only, if the correct entry is used (for video it often
+makes no difference). The bttv driver prints a line to the kernel
+log, telling which card type is used. Like this one::
+
+ bttv0: model: BT848(Hauppauge old) [autodetected]
+
+You should verify this is correct. If it isn't, you have to pass the
+correct board type as insmod argument, ``insmod bttv card=2`` for
+example. The file Documentation/admin-guide/media/bttv-cardlist.rst has a list
+of valid arguments for card.
+
+If your card isn't listed there, you might check the source code for
+new entries which are not listed yet. If there isn't one for your
+card, you can check if one of the existing entries does work for you
+(just trial and error...).
+
+Some boards have an extra processor for sound to do stereo decoding
+and other nice features. The msp34xx chips are used by Hauppauge for
+example. If your board has one, you might have to load a helper
+module like ``msp3400`` to make sound work. If there isn't one for the
+chip used on your board: Bad luck. Start writing a new one. Well,
+you might want to check the video4linux mailing list archive first...
+
+Of course you need a correctly installed soundcard unless you have the
+speakers connected directly to the grabber board. Hint: check the
+mixer settings too. ALSA for example has everything muted by default.
+
+
+How sound works in detail
+~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Still doesn't work? Looks like some driver hacking is required.
+Below is a do-it-yourself description for you.
+
+The bt8xx chips have 32 general purpose pins, and registers to control
+these pins. One register is the output enable register
+(``BT848_GPIO_OUT_EN``), it says which pins are actively driven by the
+bt848 chip. Another one is the data register (``BT848_GPIO_DATA``), where
+you can get/set the status if these pins. They can be used for input
+and output.
+
+Most grabber board vendors use these pins to control an external chip
+which does the sound routing. But every board is a little different.
+These pins are also used by some companies to drive remote control
+receiver chips. Some boards use the i2c bus instead of the gpio pins
+to connect the mux chip.
+
+As mentioned above, there is a array which holds the required
+information for each known board. You basically have to create a new
+line for your board. The important fields are these two::
+
+ struct tvcard
+ {
+ [ ... ]
+ u32 gpiomask;
+ u32 audiomux[6]; /* Tuner, Radio, external, internal, mute, stereo */
+ };
+
+gpiomask specifies which pins are used to control the audio mux chip.
+The corresponding bits in the output enable register
+(``BT848_GPIO_OUT_EN``) will be set as these pins must be driven by the
+bt848 chip.
+
+The ``audiomux[]`` array holds the data values for the different inputs
+(i.e. which pins must be high/low for tuner/mute/...). This will be
+written to the data register (``BT848_GPIO_DATA``) to switch the audio
+mux.
+
+
+What you have to do is figure out the correct values for gpiomask and
+the audiomux array. If you have Windows and the drivers four your
+card installed, you might to check out if you can read these registers
+values used by the windows driver. A tool to do this is available
+from http://btwincap.sourceforge.net/download.html.
+
+You might also dig around in the ``*.ini`` files of the Windows applications.
+You can have a look at the board to see which of the gpio pins are
+connected at all and then start trial-and-error ...
+
+
+Starting with release 0.7.41 bttv has a number of insmod options to
+make the gpio debugging easier:
+
+ ================= ==============================================
+ bttv_gpio=0/1 enable/disable gpio debug messages
+ gpiomask=n set the gpiomask value
+ audiomux=i,j,... set the values of the audiomux array
+ audioall=a set the values of the audiomux array (one
+ value for all array elements, useful to check
+ out which effect the particular value has).
+ ================= ==============================================
+
+The messages printed with ``bttv_gpio=1`` look like this::
+
+ bttv0: gpio: en=00000027, out=00000024 in=00ffffd8 [audio: off]
+
+ en = output _en_able register (BT848_GPIO_OUT_EN)
+ out = _out_put bits of the data register (BT848_GPIO_DATA),
+ i.e. BT848_GPIO_DATA & BT848_GPIO_OUT_EN
+ in = _in_put bits of the data register,
+ i.e. BT848_GPIO_DATA & ~BT848_GPIO_OUT_EN
diff --git a/Documentation/driver-api/media/drivers/ccs/ccs-regs.asc b/Documentation/driver-api/media/drivers/ccs/ccs-regs.asc
new file mode 100644
index 000000000000..bbf9213c3388
--- /dev/null
+++ b/Documentation/driver-api/media/drivers/ccs/ccs-regs.asc
@@ -0,0 +1,1041 @@
+# SPDX-License-Identifier: GPL-2.0-only OR BSD-3-Clause
+# Copyright (C) 2019--2020 Intel Corporation
+
+# register rflags
+# - f field LSB MSB rflags
+# - e enum value # after a field
+# - e enum value [LSB MSB]
+# - b bool bit
+# - l arg name min max elsize [discontig...]
+#
+# rflags
+# 8, 16, 32 register bits (default is 8)
+# v1.1 defined in version 1.1
+# f formula
+# float_ireal iReal or IEEE 754; 32 bits
+# ireal unsigned iReal
+
+# general status registers
+module_model_id 0x0000 16
+module_revision_number_major 0x0002 8
+frame_count 0x0005 8
+pixel_order 0x0006 8
+- e GRBG 0
+- e RGGB 1
+- e BGGR 2
+- e GBRG 3
+MIPI_CCS_version 0x0007 8
+- e v1_0 0x10
+- e v1_1 0x11
+- f major 4 7
+- f minor 0 3
+data_pedestal 0x0008 16
+module_manufacturer_id 0x000e 16
+module_revision_number_minor 0x0010 8
+module_date_year 0x0012 8
+module_date_month 0x0013 8
+module_date_day 0x0014 8
+module_date_phase 0x0015 8
+- f 0 2
+- e ts 0
+- e es 1
+- e cs 2
+- e mp 3
+sensor_model_id 0x0016 16
+sensor_revision_number 0x0018 8
+sensor_firmware_version 0x001a 8
+serial_number 0x001c 32
+sensor_manufacturer_id 0x0020 16
+sensor_revision_number_16 0x0022 16
+
+# frame format description registers
+frame_format_model_type 0x0040 8
+- e 2-byte 1
+- e 4-byte 2
+frame_format_model_subtype 0x0041 8
+- f rows 0 3
+- f columns 4 7
+frame_format_descriptor(n) 0x0042 16 f
+- l n 0 14 2
+- f pixels 0 11
+- f pcode 12 15
+- e embedded 1
+- e dummy_pixel 2
+- e black_pixel 3
+- e dark_pixel 4
+- e visible_pixel 5
+- e manuf_specific_0 8
+- e manuf_specific_1 9
+- e manuf_specific_2 10
+- e manuf_specific_3 11
+- e manuf_specific_4 12
+- e manuf_specific_5 13
+- e manuf_specific_6 14
+frame_format_descriptor_4(n) 0x0060 32 f
+- l n 0 7 4
+- f pixels 0 15
+- f pcode 28 31
+- e embedded 1
+- e dummy_pixel 2
+- e black_pixel 3
+- e dark_pixel 4
+- e visible_pixel 5
+- e manuf_specific_0 8
+- e manuf_specific_1 9
+- e manuf_specific_2 10
+- e manuf_specific_3 11
+- e manuf_specific_4 12
+- e manuf_specific_5 13
+- e manuf_specific_6 14
+
+# analog gain description registers
+analog_gain_capability 0x0080 16
+- e global 0
+- e alternate_global 2
+analog_gain_code_min 0x0084 16
+analog_gain_code_max 0x0086 16
+analog_gain_code_step 0x0088 16
+analog_gain_type 0x008a 16
+analog_gain_m0 0x008c 16
+analog_gain_c0 0x008e 16
+analog_gain_m1 0x0090 16
+analog_gain_c1 0x0092 16
+analog_linear_gain_min 0x0094 16 v1.1
+analog_linear_gain_max 0x0096 16 v1.1
+analog_linear_gain_step_size 0x0098 16 v1.1
+analog_exponential_gain_min 0x009a 16 v1.1
+analog_exponential_gain_max 0x009c 16 v1.1
+analog_exponential_gain_step_size 0x009e 16 v1.1
+
+# data format description registers
+data_format_model_type 0x00c0 8
+- e normal 1
+- e extended 2
+data_format_model_subtype 0x00c1 8
+- f rows 0 3
+- f columns 4 7
+data_format_descriptor(n) 0x00c2 16 f
+- l n 0 15 2
+- f compressed 0 7
+- f uncompressed 8 15
+
+# general set-up registers
+mode_select 0x0100 8
+- e software_standby 0
+- e streaming 1
+image_orientation 0x0101 8
+- b horizontal_mirror 0
+- b vertical_flip 1
+software_reset 0x0103 8
+- e off 0
+- e on 1
+grouped_parameter_hold 0x0104 8
+mask_corrupted_frames 0x0105 8
+- e allow 0
+- e mask 1
+fast_standby_ctrl 0x0106 8
+- e complete_frames 0
+- e frame_truncation 1
+CCI_address_ctrl 0x0107 8
+2nd_CCI_if_ctrl 0x0108 8
+- b enable 0
+- b ack 1
+2nd_CCI_address_ctrl 0x0109 8
+CSI_channel_identifier 0x0110 8
+CSI_signaling_mode 0x0111 8
+- e csi_2_dphy 2
+- e csi_2_cphy 3
+CSI_data_format 0x0112 16
+CSI_lane_mode 0x0114 8
+DPCM_Frame_DT 0x011d 8
+Bottom_embedded_data_DT 0x011e 8
+Bottom_embedded_data_VC 0x011f 8
+
+gain_mode 0x0120 8
+- e global 0
+- e alternate 1
+ADC_bit_depth 0x0121 8
+emb_data_ctrl 0x0122 v1.1
+- b raw8_packing_for_raw16 0
+- b raw10_packing_for_raw20 1
+- b raw12_packing_for_raw24 2
+
+GPIO_TRIG_mode 0x0130 8
+extclk_frequency_mhz 0x0136 16 ireal
+temp_sensor_ctrl 0x0138 8
+- b enable 0
+temp_sensor_mode 0x0139 8
+temp_sensor_output 0x013a 8
+
+# integration time registers
+fine_integration_time 0x0200 16
+coarse_integration_time 0x0202 16
+
+# analog gain registers
+analog_gain_code_global 0x0204 16
+analog_linear_gain_global 0x0206 16 v1.1
+analog_exponential_gain_global 0x0208 16 v1.1
+
+# digital gain registers
+digital_gain_global 0x020e 16
+
+# hdr control registers
+Short_analog_gain_global 0x0216 16
+Short_digital_gain_global 0x0218 16
+
+HDR_mode 0x0220 8
+- b enabled 0
+- b separate_analog_gain 1
+- b upscaling 2
+- b reset_sync 3
+- b timing_mode 4
+- b exposure_ctrl_direct 5
+- b separate_digital_gain 6
+HDR_resolution_reduction 0x0221 8
+- f row 0 3
+- f column 4 7
+Exposure_ratio 0x0222 8
+HDR_internal_bit_depth 0x0223 8
+Direct_short_integration_time 0x0224 16
+Short_analog_linear_gain_global 0x0226 16 v1.1
+Short_analog_exponential_gain_global 0x0228 16 v1.1
+
+# clock set-up registers
+vt_pix_clk_div 0x0300 16
+vt_sys_clk_div 0x0302 16
+pre_pll_clk_div 0x0304 16
+#vt_pre_pll_clk_div 0x0304 16
+pll_multiplier 0x0306 16
+#vt_pll_multiplier 0x0306 16
+op_pix_clk_div 0x0308 16
+op_sys_clk_div 0x030a 16
+op_pre_pll_clk_div 0x030c 16
+op_pll_multiplier 0x030e 16
+pll_mode 0x0310 8
+- f 0 0
+- e single 0
+- e dual 1
+op_pix_clk_div_rev 0x0312 16 v1.1
+op_sys_clk_div_rev 0x0314 16 v1.1
+
+# frame timing registers
+frame_length_lines 0x0340 16
+line_length_pck 0x0342 16
+
+# image size registers
+x_addr_start 0x0344 16
+y_addr_start 0x0346 16
+x_addr_end 0x0348 16
+y_addr_end 0x034a 16
+x_output_size 0x034c 16
+y_output_size 0x034e 16
+
+# timing mode registers
+Frame_length_ctrl 0x0350 8
+- b automatic 0
+Timing_mode_ctrl 0x0352 8
+- b manual_readout 0
+- b delayed_exposure 1
+Start_readout_rs 0x0353 8
+- b manual_readout_start 0
+Frame_margin 0x0354 16
+
+# sub-sampling registers
+x_even_inc 0x0380 16
+x_odd_inc 0x0382 16
+y_even_inc 0x0384 16
+y_odd_inc 0x0386 16
+
+# monochrome readout registers
+monochrome_en 0x0390 v1.1
+- e enabled 0
+
+# image scaling registers
+Scaling_mode 0x0400 16
+- e no_scaling 0
+- e horizontal 1
+scale_m 0x0404 16
+scale_n 0x0406 16
+digital_crop_x_offset 0x0408 16
+digital_crop_y_offset 0x040a 16
+digital_crop_image_width 0x040c 16
+digital_crop_image_height 0x040e 16
+
+# image compression registers
+compression_mode 0x0500 16
+- e none 0
+- e dpcm_pcm_simple 1
+
+# test pattern registers
+test_pattern_mode 0x0600 16
+- e none 0
+- e solid_color 1
+- e color_bars 2
+- e fade_to_grey 3
+- e pn9 4
+- e color_tile 5
+test_data_red 0x0602 16
+test_data_greenR 0x0604 16
+test_data_blue 0x0606 16
+test_data_greenB 0x0608 16
+value_step_size_smooth 0x060a 8
+value_step_size_quantised 0x060b 8
+
+# phy configuration registers
+tclk_post 0x0800 8
+ths_prepare 0x0801 8
+ths_zero_min 0x0802 8
+ths_trail 0x0803 8
+tclk_trail_min 0x0804 8
+tclk_prepare 0x0805 8
+tclk_zero 0x0806 8
+tlpx 0x0807 8
+phy_ctrl 0x0808 8
+- e auto 0
+- e UI 1
+- e manual 2
+tclk_post_ex 0x080a 16
+ths_prepare_ex 0x080c 16
+ths_zero_min_ex 0x080e 16
+ths_trail_ex 0x0810 16
+tclk_trail_min_ex 0x0812 16
+tclk_prepare_ex 0x0814 16
+tclk_zero_ex 0x0816 16
+tlpx_ex 0x0818 16
+
+# link rate register
+requested_link_rate 0x0820 32 u16.16
+
+# equalization control registers
+DPHY_equalization_mode 0x0824 8 v1.1
+- b eq2 0
+PHY_equalization_ctrl 0x0825 8 v1.1
+- b enable 0
+
+# d-phy preamble control registers
+DPHY_preamble_ctrl 0x0826 8 v1.1
+- b enable 0
+DPHY_preamble_length 0x0826 8 v1.1
+
+# d-phy spread spectrum control registers
+PHY_SSC_ctrl 0x0828 8 v1.1
+- b enable 0
+
+# manual lp control register
+manual_LP_ctrl 0x0829 8 v1.1
+- b enable 0
+
+# additional phy configuration registers
+twakeup 0x082a v1.1
+tinit 0x082b v1.1
+ths_exit 0x082c v1.1
+ths_exit_ex 0x082e 16 v1.1
+
+# phy calibration configuration registers
+PHY_periodic_calibration_ctrl 0x0830 8
+- b frame_blanking 0
+PHY_periodic_calibration_interval 0x0831 8
+PHY_init_calibration_ctrl 0x0832 8
+- b stream_start 0
+DPHY_calibration_mode 0x0833 8 v1.1
+- b also_alternate 0
+CPHY_calibration_mode 0x0834 8 v1.1
+- e format_1 0
+- e format_2 1
+- e format_3 2
+t3_calpreamble_length 0x0835 8 v1.1
+t3_calpreamble_length_per 0x0836 8 v1.1
+t3_calaltseq_length 0x0837 8 v1.1
+t3_calaltseq_length_per 0x0838 8 v1.1
+FM2_init_seed 0x083a 16 v1.1
+t3_caludefseq_length 0x083c 16 v1.1
+t3_caludefseq_length_per 0x083e 16 v1.1
+
+# c-phy manual control registers
+TGR_Preamble_Length 0x0841 8
+- b preamable_prog_seq 7
+- f begin_preamble_length 0 5
+TGR_Post_Length 0x0842 8
+- f post_length 0 4
+TGR_Preamble_Prog_Sequence(n2) 0x0843
+- l n2 0 6 1
+- f symbol_n_1 3 5
+- f symbol_n 0 2
+t3_prepare 0x084e 16
+t3_lpx 0x0850 16
+
+# alps control register
+ALPS_ctrl 0x085a 8
+- b lvlp_dphy 0
+- b lvlp_cphy 1
+- b alp_cphy 2
+
+# lrte control registers
+TX_REG_CSI_EPD_EN_SSP_cphy 0x0860 16
+TX_REG_CSI_EPD_OP_SLP_cphy 0x0862 16
+TX_REG_CSI_EPD_EN_SSP_dphy 0x0864 16
+TX_REG_CSI_EPD_OP_SLP_dphy 0x0866 16
+TX_REG_CSI_EPD_MISC_OPTION_cphy 0x0868 v1.1
+TX_REG_CSI_EPD_MISC_OPTION_dphy 0x0869 v1.1
+
+# scrambling control registers
+Scrambling_ctrl 0x0870
+- b enabled 0
+- f 2 3
+- e 1_seed_cphy 0
+- e 4_seed_cphy 3
+lane_seed_value(seed, lane) 0x0872 16
+- l seed 0 3 0x10
+- l lane 0 7 0x2
+
+# usl control registers
+TX_USL_REV_ENTRY 0x08c0 16 v1.1
+TX_USL_REV_Clock_Counter 0x08c2 16 v1.1
+TX_USL_REV_LP_Counter 0x08c4 16 v1.1
+TX_USL_REV_Frame_Counter 0x08c6 16 v1.1
+TX_USL_REV_Chronological_Timer 0x08c8 16 v1.1
+TX_USL_FWD_ENTRY 0x08ca 16 v1.1
+TX_USL_GPIO 0x08cc 16 v1.1
+TX_USL_Operation 0x08ce 16 v1.1
+- b reset 0
+TX_USL_ALP_ctrl 0x08d0 16 v1.1
+- b clock_pause 0
+TX_USL_APP_BTA_ACK_TIMEOUT 0x08d2 16 v1.1
+TX_USL_SNS_BTA_ACK_TIMEOUT 0x08d2 16 v1.1
+USL_Clock_Mode_d_ctrl 0x08d2 v1.1
+- b cont_clock_standby 0
+- b cont_clock_vblank 1
+- b cont_clock_hblank 2
+
+# binning configuration registers
+binning_mode 0x0900 8
+binning_type 0x0901 8
+binning_weighting 0x0902 8
+
+# data transfer interface registers
+data_transfer_if_1_ctrl 0x0a00 8
+- b enable 0
+- b write 1
+- b clear_error 2
+data_transfer_if_1_status 0x0a01 8
+- b read_if_ready 0
+- b write_if_ready 1
+- b data_corrupted 2
+- b improper_if_usage 3
+data_transfer_if_1_page_select 0x0a02 8
+data_transfer_if_1_data(p) 0x0a04 8 f
+- l p 0 63 1
+
+# image processing and sensor correction configuration registers
+shading_correction_en 0x0b00 8
+- b enable 0
+luminance_correction_level 0x0b01 8
+green_imbalance_filter_en 0x0b02 8
+- b enable 0
+mapped_defect_correct_en 0x0b05 8
+- b enable 0
+single_defect_correct_en 0x0b06 8
+- b enable 0
+dynamic_couplet_correct_en 0x0b08 8
+- b enable 0
+combined_defect_correct_en 0x0b0a 8
+- b enable 0
+module_specific_correction_en 0x0b0c 8
+- b enable 0
+dynamic_triplet_defect_correct_en 0x0b13 8
+- b enable 0
+NF_ctrl 0x0b15 8
+- b luma 0
+- b chroma 1
+- b combined 2
+
+# optical black pixel readout registers
+OB_readout_control 0x0b30 8
+- b enable 0
+- b interleaving 1
+OB_virtual_channel 0x0b31 8
+OB_DT 0x0b32 8
+OB_data_format 0x0b33 8
+
+# color temperature feedback registers
+color_temperature 0x0b8c 16
+absolute_gain_greenr 0x0b8e 16
+absolute_gain_red 0x0b90 16
+absolute_gain_blue 0x0b92 16
+absolute_gain_greenb 0x0b94 16
+
+# cfa conversion registers
+CFA_conversion_ctrl 0x0ba0 v1.1
+- b bayer_conversion_enable 0
+
+# flash strobe and sa strobe control registers
+flash_strobe_adjustment 0x0c12 8
+flash_strobe_start_point 0x0c14 16
+tflash_strobe_delay_rs_ctrl 0x0c16 16
+tflash_strobe_width_high_rs_ctrl 0x0c18 16
+flash_mode_rs 0x0c1a 8
+- b continuous 0
+- b truncate 1
+- b async 3
+flash_trigger_rs 0x0c1b 8
+flash_status 0x0c1c 8
+- b retimed 0
+sa_strobe_mode 0x0c1d 8
+- b continuous 0
+- b truncate 1
+- b async 3
+- b adjust_edge 4
+sa_strobe_start_point 0x0c1e 16
+tsa_strobe_delay_ctrl 0x0c20 16
+tsa_strobe_width_ctrl 0x0c22 16
+sa_strobe_trigger 0x0c24 8
+sa_strobe_status 0x0c25 8
+- b retimed 0
+tSA_strobe_re_delay_ctrl 0x0c30 16
+tSA_strobe_fe_delay_ctrl 0x0c32 16
+
+# pdaf control registers
+PDAF_ctrl 0x0d00 16
+- b enable 0
+- b processed 1
+- b interleaved 2
+- b visible_pdaf_correction 3
+PDAF_VC 0x0d02 8
+PDAF_DT 0x0d03 8
+pd_x_addr_start 0x0d04 16
+pd_y_addr_start 0x0d06 16
+pd_x_addr_end 0x0d08 16
+pd_y_addr_end 0x0d0a 16
+
+# bracketing interface configuration registers
+bracketing_LUT_ctrl 0x0e00 8
+bracketing_LUT_mode 0x0e01 8
+- b continue_streaming 0
+- b loop_mode 1
+bracketing_LUT_entry_ctrl 0x0e02 8
+bracketing_LUT_frame(n) 0x0e10 v1.1 f
+- l n 0 0xef 1
+
+# integration time and gain parameter limit registers
+integration_time_capability 0x1000 16
+- b fine 0
+coarse_integration_time_min 0x1004 16
+coarse_integration_time_max_margin 0x1006 16
+fine_integration_time_min 0x1008 16
+fine_integration_time_max_margin 0x100a 16
+
+# digital gain parameter limit registers
+digital_gain_capability 0x1081
+- e none 0
+- e global 2
+digital_gain_min 0x1084 16
+digital_gain_max 0x1086 16
+digital_gain_step_size 0x1088 16
+
+# data pedestal capability registers
+Pedestal_capability 0x10e0 8 v1.1
+
+# adc capability registers
+ADC_capability 0x10f0 8
+- b bit_depth_ctrl 0
+ADC_bit_depth_capability 0x10f4 32 v1.1
+
+# video timing parameter limit registers
+min_ext_clk_freq_mhz 0x1100 32 float_ireal
+max_ext_clk_freq_mhz 0x1104 32 float_ireal
+min_pre_pll_clk_div 0x1108 16
+# min_vt_pre_pll_clk_div 0x1108 16
+max_pre_pll_clk_div 0x110a 16
+# max_vt_pre_pll_clk_div 0x110a 16
+min_pll_ip_clk_freq_mhz 0x110c 32 float_ireal
+# min_vt_pll_ip_clk_freq_mhz 0x110c 32 float_ireal
+max_pll_ip_clk_freq_mhz 0x1110 32 float_ireal
+# max_vt_pll_ip_clk_freq_mhz 0x1110 32 float_ireal
+min_pll_multiplier 0x1114 16
+# min_vt_pll_multiplier 0x1114 16
+max_pll_multiplier 0x1116 16
+# max_vt_pll_multiplier 0x1116 16
+min_pll_op_clk_freq_mhz 0x1118 32 float_ireal
+max_pll_op_clk_freq_mhz 0x111c 32 float_ireal
+
+# video timing set-up capability registers
+min_vt_sys_clk_div 0x1120 16
+max_vt_sys_clk_div 0x1122 16
+min_vt_sys_clk_freq_mhz 0x1124 32 float_ireal
+max_vt_sys_clk_freq_mhz 0x1128 32 float_ireal
+min_vt_pix_clk_freq_mhz 0x112c 32 float_ireal
+max_vt_pix_clk_freq_mhz 0x1130 32 float_ireal
+min_vt_pix_clk_div 0x1134 16
+max_vt_pix_clk_div 0x1136 16
+clock_calculation 0x1138
+- b lane_speed 0
+- b link_decoupled 1
+- b dual_pll_op_sys_ddr 2
+- b dual_pll_op_pix_ddr 3
+num_of_vt_lanes 0x1139
+num_of_op_lanes 0x113a
+op_bits_per_lane 0x113b 8 v1.1
+
+# frame timing parameter limits
+min_frame_length_lines 0x1140 16
+max_frame_length_lines 0x1142 16
+min_line_length_pck 0x1144 16
+max_line_length_pck 0x1146 16
+min_line_blanking_pck 0x1148 16
+min_frame_blanking_lines 0x114a 16
+min_line_length_pck_step_size 0x114c
+timing_mode_capability 0x114d
+- b auto_frame_length 0
+- b rolling_shutter_manual_readout 2
+- b delayed_exposure_start 3
+- b manual_exposure_embedded_data 4
+frame_margin_max_value 0x114e 16
+frame_margin_min_value 0x1150
+gain_delay_type 0x1151
+- e fixed 0
+- e variable 1
+
+# output clock set-up capability registers
+min_op_sys_clk_div 0x1160 16
+max_op_sys_clk_div 0x1162 16
+min_op_sys_clk_freq_mhz 0x1164 32 float_ireal
+max_op_sys_clk_freq_mhz 0x1168 32 float_ireal
+min_op_pix_clk_div 0x116c 16
+max_op_pix_clk_div 0x116e 16
+min_op_pix_clk_freq_mhz 0x1170 32 float_ireal
+max_op_pix_clk_freq_mhz 0x1174 32 float_ireal
+
+# image size parameter limit registers
+x_addr_min 0x1180 16
+y_addr_min 0x1182 16
+x_addr_max 0x1184 16
+y_addr_max 0x1186 16
+min_x_output_size 0x1188 16
+min_y_output_size 0x118a 16
+max_x_output_size 0x118c 16
+max_y_output_size 0x118e 16
+
+x_addr_start_div_constant 0x1190 v1.1
+y_addr_start_div_constant 0x1191 v1.1
+x_addr_end_div_constant 0x1192 v1.1
+y_addr_end_div_constant 0x1193 v1.1
+x_size_div 0x1194 v1.1
+y_size_div 0x1195 v1.1
+x_output_div 0x1196 v1.1
+y_output_div 0x1197 v1.1
+non_flexible_resolution_support 0x1198 v1.1
+- b new_pix_addr 0
+- b new_output_res 1
+- b output_crop_no_pad 2
+- b output_size_lane_dep 3
+
+min_op_pre_pll_clk_div 0x11a0 16
+max_op_pre_pll_clk_div 0x11a2 16
+min_op_pll_ip_clk_freq_mhz 0x11a4 32 float_ireal
+max_op_pll_ip_clk_freq_mhz 0x11a8 32 float_ireal
+min_op_pll_multiplier 0x11ac 16
+max_op_pll_multiplier 0x11ae 16
+min_op_pll_op_clk_freq_mhz 0x11b0 32 float_ireal
+max_op_pll_op_clk_freq_mhz 0x11b4 32 float_ireal
+clock_tree_pll_capability 0x11b8 8
+- b dual_pll 0
+- b single_pll 1
+- b ext_divider 2
+- b flexible_op_pix_clk_div 3
+clock_capa_type_capability 0x11b9 v1.1
+- b ireal 0
+
+# sub-sampling parameters limit registers
+min_even_inc 0x11c0 16
+min_odd_inc 0x11c2 16
+max_even_inc 0x11c4 16
+max_odd_inc 0x11c6 16
+aux_subsamp_capability 0x11c8 v1.1
+- b factor_power_of_2 1
+aux_subsamp_mono_capability 0x11c9 v1.1
+- b factor_power_of_2 1
+monochrome_capability 0x11ca v1.1
+- e inc_odd 0
+- e inc_even 1
+pixel_readout_capability 0x11cb v1.1
+- e bayer 0
+- e monochrome 1
+- e bayer_and_mono 2
+min_even_inc_mono 0x11cc 16 v1.1
+max_even_inc_mono 0x11ce 16 v1.1
+min_odd_inc_mono 0x11d0 16 v1.1
+max_odd_inc_mono 0x11d2 16 v1.1
+min_even_inc_bc2 0x11d4 16 v1.1
+max_even_inc_bc2 0x11d6 16 v1.1
+min_odd_inc_bc2 0x11d8 16 v1.1
+max_odd_inc_bc2 0x11da 16 v1.1
+min_even_inc_mono_bc2 0x11dc 16 v1.1
+max_even_inc_mono_bc2 0x11de 16 v1.1
+min_odd_inc_mono_bc2 0x11f0 16 v1.1
+max_odd_inc_mono_bc2 0x11f2 16 v1.1
+
+# image scaling limit parameters
+scaling_capability 0x1200 16
+- e none 0
+- e horizontal 1
+- e reserved 2
+scaler_m_min 0x1204 16
+scaler_m_max 0x1206 16
+scaler_n_min 0x1208 16
+scaler_n_max 0x120a 16
+digital_crop_capability 0x120e
+- e none 0
+- e input_crop 1
+
+# hdr limit registers
+hdr_capability_1 0x1210
+- b 2x2_binning 0
+- b combined_analog_gain 1
+- b separate_analog_gain 2
+- b upscaling 3
+- b reset_sync 4
+- b direct_short_exp_timing 5
+- b direct_short_exp_synthesis 6
+min_hdr_bit_depth 0x1211
+hdr_resolution_sub_types 0x1212
+hdr_resolution_sub_type(n) 0x1213
+- l n 0 1 1
+- f row 0 3
+- f column 4 7
+hdr_capability_2 0x121b
+- b combined_digital_gain 0
+- b separate_digital_gain 1
+- b timing_mode 3
+- b synthesis_mode 4
+max_hdr_bit_depth 0x121c
+
+# usl capability register
+usl_support_capability 0x1230 v1.1
+- b clock_tree 0
+- b rev_clock_tree 1
+- b rev_clock_calc 2
+usl_clock_mode_d_capability 0x1231 v1.1
+- b cont_clock_standby 0
+- b cont_clock_vblank 1
+- b cont_clock_hblank 2
+- b noncont_clock_standby 3
+- b noncont_clock_vblank 4
+- b noncont_clock_hblank 5
+min_op_sys_clk_div_rev 0x1234 v1.1
+max_op_sys_clk_div_rev 0x1236 v1.1
+min_op_pix_clk_div_rev 0x1238 v1.1
+max_op_pix_clk_div_rev 0x123a v1.1
+min_op_sys_clk_freq_rev_mhz 0x123c 32 v1.1 float_ireal
+max_op_sys_clk_freq_rev_mhz 0x1240 32 v1.1 float_ireal
+min_op_pix_clk_freq_rev_mhz 0x1244 32 v1.1 float_ireal
+max_op_pix_clk_freq_rev_mhz 0x1248 32 v1.1 float_ireal
+max_bitrate_rev_d_mode_mbps 0x124c 32 v1.1 ireal
+max_symrate_rev_c_mode_msps 0x1250 32 v1.1 ireal
+
+# image compression capability registers
+compression_capability 0x1300
+- b dpcm_pcm_simple 0
+
+# test mode capability registers
+test_mode_capability 0x1310 16
+- b solid_color 0
+- b color_bars 1
+- b fade_to_grey 2
+- b pn9 3
+- b color_tile 5
+pn9_data_format1 0x1312
+pn9_data_format2 0x1313
+pn9_data_format3 0x1314
+pn9_data_format4 0x1315
+pn9_misc_capability 0x1316
+- f num_pixels 0 2
+- b compression 3
+test_pattern_capability 0x1317 v1.1
+- b no_repeat 1
+pattern_size_div_m1 0x1318 v1.1
+
+# fifo capability registers
+fifo_support_capability 0x1502
+- e none 0
+- e derating 1
+- e derating_overrating 2
+
+# csi-2 capability registers
+phy_ctrl_capability 0x1600
+- b auto_phy_ctl 0
+- b ui_phy_ctl 1
+- b dphy_time_ui_reg_1_ctl 2
+- b dphy_time_ui_reg_2_ctl 3
+- b dphy_time_ctl 4
+- b dphy_ext_time_ui_reg_1_ctl 5
+- b dphy_ext_time_ui_reg_2_ctl 6
+- b dphy_ext_time_ctl 7
+csi_dphy_lane_mode_capability 0x1601
+- b 1_lane 0
+- b 2_lane 1
+- b 3_lane 2
+- b 4_lane 3
+- b 5_lane 4
+- b 6_lane 5
+- b 7_lane 6
+- b 8_lane 7
+csi_signaling_mode_capability 0x1602
+- b csi_dphy 2
+- b csi_cphy 3
+fast_standby_capability 0x1603
+- e no_frame_truncation 0
+- e frame_truncation 1
+csi_address_control_capability 0x1604
+- b cci_addr_change 0
+- b 2nd_cci_addr 1
+- b sw_changeable_2nd_cci_addr 2
+data_type_capability 0x1605
+- b dpcm_programmable 0
+- b bottom_embedded_dt_programmable 1
+- b bottom_embedded_vc_programmable 2
+- b ext_vc_range 3
+csi_cphy_lane_mode_capability 0x1606
+- b 1_lane 0
+- b 2_lane 1
+- b 3_lane 2
+- b 4_lane 3
+- b 5_lane 4
+- b 6_lane 5
+- b 7_lane 6
+- b 8_lane 7
+emb_data_capability 0x1607 v1.1
+- b two_bytes_per_raw16 0
+- b two_bytes_per_raw20 1
+- b two_bytes_per_raw24 2
+- b no_one_byte_per_raw16 3
+- b no_one_byte_per_raw20 4
+- b no_one_byte_per_raw24 5
+max_per_lane_bitrate_lane_d_mode_mbps(n) 0x1608 32 ireal
+- l n 0 7 4 4,0x32
+temp_sensor_capability 0x1618
+- b supported 0
+- b CCS_format 1
+- b reset_0x80 2
+max_per_lane_bitrate_lane_c_mode_mbps(n) 0x161a 32 ireal
+- l n 0 7 4 4,0x30
+dphy_equalization_capability 0x162b
+- b equalization_ctrl 0
+- b eq1 1
+- b eq2 2
+cphy_equalization_capability 0x162c
+- b equalization_ctrl 0
+dphy_preamble_capability 0x162d
+- b preamble_seq_ctrl 0
+dphy_ssc_capability 0x162e
+- b supported 0
+cphy_calibration_capability 0x162f
+- b manual 0
+- b manual_streaming 1
+- b format_1_ctrl 2
+- b format_2_ctrl 3
+- b format_3_ctrl 4
+dphy_calibration_capability 0x1630
+- b manual 0
+- b manual_streaming 1
+- b alternate_seq 2
+phy_ctrl_capability_2 0x1631
+- b tgr_length 0
+- b tgr_preamble_prog_seq 1
+- b extra_cphy_manual_timing 2
+- b clock_based_manual_cdphy 3
+- b clock_based_manual_dphy 4
+- b clock_based_manual_cphy 5
+- b manual_lp_dphy 6
+- b manual_lp_cphy 7
+lrte_cphy_capability 0x1632
+- b pdq_short 0
+- b spacer_short 1
+- b pdq_long 2
+- b spacer_long 3
+- b spacer_no_pdq 4
+lrte_dphy_capability 0x1633
+- b pdq_short_opt1 0
+- b spacer_short_opt1 1
+- b pdq_long_opt1 2
+- b spacer_long_opt1 3
+- b spacer_short_opt2 4
+- b spacer_long_opt2 5
+- b spacer_no_pdq_opt1 6
+- b spacer_variable_opt2 7
+alps_capability_dphy 0x1634
+- e lvlp_not_supported 0 0x3
+- e lvlp_supported 1 0x3
+- e controllable_lvlp 2 0x3
+alps_capability_cphy 0x1635
+- e lvlp_not_supported 0 0x3
+- e lvlp_supported 1 0x3
+- e controllable_lvlp 2 0x3
+- e alp_not_supported 0xc 0xc
+- e alp_supported 0xd 0xc
+- e controllable_alp 0xe 0xc
+scrambling_capability 0x1636
+- b scrambling_supported 0
+- f max_seeds_per_lane_c 1 2
+- e 1 0
+- e 4 3
+- f num_seed_regs 3 5
+- e 0 0
+- e 1 1
+- e 4 4
+- b num_seed_per_lane 6
+dphy_manual_constant 0x1637
+cphy_manual_constant 0x1638
+CSI2_interface_capability_misc 0x1639 v1.1
+- b eotp_short_pkt_opt2 0
+PHY_ctrl_capability_3 0x165c v1.1
+- b dphy_timing_not_multiple 0
+- b dphy_min_timing_value_1 1
+- b twakeup_supported 2
+- b tinit_supported 3
+- b ths_exit_supported 4
+- b cphy_timing_not_multiple 5
+- b cphy_min_timing_value_1 6
+dphy_sf 0x165d v1.1
+cphy_sf 0x165e v1.1
+- f twakeup 0 3
+- f tinit 4 7
+dphy_limits_1 0x165f v1.1
+- f ths_prepare 0 3
+- f ths_zero 4 7
+dphy_limits_2 0x1660 v1.1
+- f ths_trail 0 3
+- f tclk_trail_min 4 7
+dphy_limits_3 0x1661 v1.1
+- f tclk_prepare 0 3
+- f tclk_zero 4 7
+dphy_limits_4 0x1662 v1.1
+- f tclk_post 0 3
+- f tlpx 4 7
+dphy_limits_5 0x1663 v1.1
+- f ths_exit 0 3
+- f twakeup 4 7
+dphy_limits_6 0x1664 v1.1
+- f tinit 0 3
+cphy_limits_1 0x1665 v1.1
+- f t3_prepare_max 0 3
+- f t3_lpx_max 4 7
+cphy_limits_2 0x1666 v1.1
+- f ths_exit_max 0 3
+- f twakeup_max 4 7
+cphy_limits_3 0x1667 v1.1
+- f tinit_max 0 3
+
+# binning capability registers
+min_frame_length_lines_bin 0x1700 16
+max_frame_length_lines_bin 0x1702 16
+min_line_length_pck_bin 0x1704 16
+max_line_length_pck_bin 0x1706 16
+min_line_blanking_pck_bin 0x1708 16
+fine_integration_time_min_bin 0x170a 16
+fine_integration_time_max_margin_bin 0x170c 16
+binning_capability 0x1710
+- e unsupported 0
+- e binning_then_subsampling 1
+- e subsampling_then_binning 2
+binning_weighting_capability 0x1711
+- b averaged 0
+- b summed 1
+- b bayer_corrected 2
+- b module_specific_weight 3
+binning_sub_types 0x1712
+binning_sub_type(n) 0x1713
+- l n 0 63 1
+- f row 0 3
+- f column 4 7
+binning_weighting_mono_capability 0x1771 v1.1
+- b averaged 0
+- b summed 1
+- b bayer_corrected 2
+- b module_specific_weight 3
+binning_sub_types_mono 0x1772 v1.1
+binning_sub_type_mono(n) 0x1773 v1.1 f
+- l n 0 63 1
+
+# data transfer interface capability registers
+data_transfer_if_capability 0x1800
+- b supported 0
+- b polling 2
+
+# sensor correction capability registers
+shading_correction_capability 0x1900
+- b color_shading 0
+- b luminance_correction 1
+green_imbalance_capability 0x1901
+- b supported 0
+module_specific_correction_capability 0x1903
+defect_correction_capability 0x1904 16
+- b mapped_defect 0
+- b dynamic_couplet 2
+- b dynamic_single 5
+- b combined_dynamic 8
+defect_correction_capability_2 0x1906 16
+- b dynamic_triplet 3
+nf_capability 0x1908
+- b luma 0
+- b chroma 1
+- b combined 2
+
+# optical black readout capability registers
+ob_readout_capability 0x1980
+- b controllable_readout 0
+- b visible_pixel_readout 1
+- b different_vc_readout 2
+- b different_dt_readout 3
+- b prog_data_format 4
+
+# color feedback capability registers
+color_feedback_capability 0x1987
+- b kelvin 0
+- b awb_gain 1
+
+# cfa pattern capability registers
+CFA_pattern_capability 0x1990 v1.1
+- e bayer 0
+- e monochrome 1
+- e 4x4_quad_bayer 2
+- e vendor_specific 3
+CFA_pattern_conversion_capability 0x1991 v1.1
+- b bayer 0
+
+# timer capability registers
+flash_mode_capability 0x1a02
+- b single_strobe 0
+sa_strobe_mode_capability 0x1a03
+- b fixed_width 0
+- b edge_ctrl 1
+
+# soft reset capability registers
+reset_max_delay 0x1a10 v1.1
+reset_min_time 0x1a11 v1.1
+
+# pdaf capability registers
+pdaf_capability_1 0x1b80
+- b supported 0
+- b processed_bottom_embedded 1
+- b processed_interleaved 2
+- b raw_bottom_embedded 3
+- b raw_interleaved 4
+- b visible_pdaf_correction 5
+- b vc_interleaving 6
+- b dt_interleaving 7
+pdaf_capability_2 0x1b81
+- b ROI 0
+- b after_digital_crop 1
+- b ctrl_retimed 2
+
+# bracketing interface capability registers
+bracketing_lut_capability_1 0x1c00
+- b coarse_integration 0
+- b global_analog_gain 1
+- b flash 4
+- b global_digital_gain 5
+- b alternate_global_analog_gain 6
+bracketing_lut_capability_2 0x1c01
+- b single_bracketing_mode 0
+- b looped_bracketing_mode 1
+bracketing_lut_size 0x1c02
diff --git a/Documentation/driver-api/media/drivers/ccs/ccs.rst b/Documentation/driver-api/media/drivers/ccs/ccs.rst
new file mode 100644
index 000000000000..776eec72bc80
--- /dev/null
+++ b/Documentation/driver-api/media/drivers/ccs/ccs.rst
@@ -0,0 +1,125 @@
+.. SPDX-License-Identifier: GPL-2.0-only OR BSD-3-Clause
+
+.. include:: <isonum.txt>
+
+MIPI CCS camera sensor driver
+=============================
+
+The MIPI CCS camera sensor driver is a generic driver for `MIPI CCS
+<https://www.mipi.org/specifications/camera-command-set>`_ compliant
+camera sensors. It exposes three sub-devices representing the pixel array,
+the binner and the scaler.
+
+As the capabilities of individual devices vary, the driver exposes
+interfaces based on the capabilities that exist in hardware.
+
+Pixel Array sub-device
+----------------------
+
+The pixel array sub-device represents the camera sensor's pixel matrix, as well
+as analogue crop functionality present in many compliant devices. The analogue
+crop is configured using the ``V4L2_SEL_TGT_CROP`` on the source pad (0) of the
+entity. The size of the pixel matrix can be obtained by getting the
+``V4L2_SEL_TGT_NATIVE_SIZE`` target.
+
+Binner
+------
+
+The binner sub-device represents the binning functionality on the sensor. For
+that purpose, selection target ``V4L2_SEL_TGT_COMPOSE`` is supported on the
+sink pad (0).
+
+Additionally, if a device has no scaler or digital crop functionality, the
+source pad (1) exposes another digital crop selection rectangle that can only
+crop at the end of the lines and frames.
+
+Scaler
+------
+
+The scaler sub-device represents the digital crop and scaling functionality of
+the sensor. The V4L2 selection target ``V4L2_SEL_TGT_CROP`` is used to
+configure the digital crop on the sink pad (0) when digital crop is supported.
+Scaling is configured using selection target ``V4L2_SEL_TGT_COMPOSE`` on the
+sink pad (0) as well.
+
+Additionally, if the scaler sub-device exists, its source pad (1) exposes
+another digital crop selection rectangle that can only crop at the end of the
+lines and frames.
+
+Digital and analogue crop
+-------------------------
+
+Digital crop functionality is referred to as cropping that effectively works by
+dropping some data on the floor. Analogue crop, on the other hand, means that
+the cropped information is never retrieved. In case of camera sensors, the
+analogue data is never read from the pixel matrix that are outside the
+configured selection rectangle that designates crop. The difference has an
+effect in device timing and likely also in power consumption.
+
+CCS static data
+---------------
+
+The MIPI CCS driver supports CCS static data for all compliant devices,
+including not just those compliant with CCS 1.1 but also CCS 1.0 and SMIA(++).
+For CCS the file names are formed as
+
+ ccs/ccs-sensor-vvvv-mmmm-rrrr.fw (sensor) and
+ ccs/ccs-module-vvvv-mmmm-rrrr.fw (module).
+
+For SMIA++ compliant devices the corresponding file names are
+
+ ccs/smiapp-sensor-vv-mmmm-rr.fw (sensor) and
+ ccs/smiapp-module-vv-mmmm-rrrr.fw (module).
+
+For SMIA (non-++) compliant devices the static data file name is
+
+ ccs/smia-sensor-vv-mmmm-rr.fw (sensor).
+
+vvvv or vv denotes MIPI and SMIA manufacturer IDs respectively, mmmm model ID
+and rrrr or rr revision number.
+
+CCS tools
+~~~~~~~~~
+
+`CCS tools <https://github.com/MIPI-Alliance/ccs-tools/>`_ is a set of
+tools for working with CCS static data files. CCS tools includes a
+definition of the human-readable CCS static data YAML format and includes a
+program to convert it to a binary.
+
+Register definition generator
+-----------------------------
+
+The ccs-regs.asc file contains MIPI CCS register definitions that are used
+to produce C source code files for definitions that can be better used by
+programs written in C language. As there are many dependencies between the
+produced files, please do not modify them manually as it's error-prone and
+in vain, but instead change the script producing them.
+
+Usage
+~~~~~
+
+Conventionally the script is called this way to update the CCS driver
+definitions:
+
+.. code-block:: none
+
+ $ Documentation/driver-api/media/drivers/ccs/mk-ccs-regs -k \
+ -e drivers/media/i2c/ccs/ccs-regs.h \
+ -L drivers/media/i2c/ccs/ccs-limits.h \
+ -l drivers/media/i2c/ccs/ccs-limits.c \
+ -c Documentation/driver-api/media/drivers/ccs/ccs-regs.asc
+
+CCS PLL calculator
+==================
+
+The CCS PLL calculator is used to compute the PLL configuration, given sensor's
+capabilities as well as board configuration and user specified configuration. As
+the configuration space that encompasses all these configurations is vast, the
+PLL calculator isn't entirely trivial. Yet it is relatively simple to use for a
+driver.
+
+The PLL model implemented by the PLL calculator corresponds to MIPI CCS 1.1.
+
+.. kernel-doc:: drivers/media/i2c/ccs-pll.h
+
+**Copyright** |copy| 2020 Intel Corporation
diff --git a/Documentation/driver-api/media/drivers/ccs/mk-ccs-regs b/Documentation/driver-api/media/drivers/ccs/mk-ccs-regs
new file mode 100755
index 000000000000..3d3152b45821
--- /dev/null
+++ b/Documentation/driver-api/media/drivers/ccs/mk-ccs-regs
@@ -0,0 +1,480 @@
+#!/usr/bin/perl -w
+# SPDX-License-Identifier: GPL-2.0-only OR BSD-3-Clause
+# Copyright (C) 2019--2020 Intel Corporation
+
+use Getopt::Long qw(:config no_ignore_case);
+use File::Basename;
+
+my $ccsregs = "ccs-regs.asc";
+my $header;
+my $regarray;
+my $limitc;
+my $limith;
+my $kernel;
+my $help;
+
+GetOptions("ccsregs|c=s" => \$ccsregs,
+ "header|e=s" => \$header,
+ "regarray|r=s" => \$regarray,
+ "limitc|l=s" => \$limitc,
+ "limith|L=s" => \$limith,
+ "kernel|k" => \$kernel,
+ "help|h" => \$help) or die "can't parse options";
+
+$help = 1 if ! defined $header || ! defined $limitc || ! defined $limith;
+
+if (defined $help) {
+ print <<EOH
+$0 - Create CCS register definitions for C
+
+usage: $0 -c ccs-regs.asc -e header -r regarray -l limit-c -L limit-header [-k]
+
+ -c ccs register file
+ -e header file name
+ -r register description array file name
+ -l limit and capability array file name
+ -L limit and capability header file name
+ -k generate files for kernel space consumption
+EOH
+ ;
+ exit 0;
+}
+
+my $lh_hdr = ! defined $kernel
+ ? '#include "ccs-os.h"' . "\n"
+ : "#include <linux/bits.h>\n#include <linux/types.h>\n";
+my $uint32_t = ! defined $kernel ? 'uint32_t' : 'u32';
+my $uint16_t = ! defined $kernel ? 'uint16_t' : 'u16';
+
+open(my $R, "< $ccsregs") or die "can't open $ccsregs";
+
+open(my $H, "> $header") or die "can't open $header";
+my $A;
+if (defined $regarray) {
+ open($A, "> $regarray") or die "can't open $regarray";
+}
+open(my $LC, "> $limitc") or die "can't open $limitc";
+open(my $LH, "> $limith") or die "can't open $limith";
+
+my %this;
+
+sub is_limit_reg($) {
+ my $addr = hex $_[0];
+
+ return 0 if $addr < 0x40; # weed out status registers
+ return 0 if $addr >= 0x100 && $addr < 0xfff; # weed out configuration registers
+
+ return 1;
+}
+
+my $uc_header = basename uc $header;
+$uc_header =~ s/[^A-Z0-9]/_/g;
+
+my $copyright = "/* Copyright (C) 2019--2020 Intel Corporation */\n";
+my $license = "SPDX-License-Identifier: GPL-2.0-only OR BSD-3-Clause";
+my $note = "/*\n * Generated by $0;\n * do not modify.\n */\n";
+
+for my $fh ($A, $LC) {
+ print $fh "// $license\n$copyright$note\n" if defined $fh;
+}
+
+for my $fh ($H, $LH) {
+ print $fh "/* $license */\n$copyright$note\n";
+}
+
+print $H <<EOF
+#ifndef __${uc_header}__
+#define __${uc_header}__
+
+EOF
+ ;
+
+print $H <<EOF
+#include <linux/bits.h>
+
+#include <media/v4l2-cci.h>
+
+EOF
+ if defined $kernel;
+
+print $H "#define CCS_FL_BASE " .
+ (defined $kernel ? "CCI_REG_PRIVATE_SHIFT" : 16) . "\n";
+
+my $flag = -1;
+my $all_flags;
+
+sub bit_def($) {
+ my $bit = shift @_;
+
+ if (defined $kernel) {
+ return "BIT$bit" if $bit =~ /^\(.*\)$/;
+ return "BIT($bit)";
+ }
+ return "(1U << $bit)";
+}
+
+sub flag_str($$) {
+ my ($flag, $check) = @_;
+
+ $$flag++;
+
+ my $flag_str = !$$flag ? "CCS_FL_BASE" : "(CCS_FL_BASE + $$flag)";
+
+ $flag_str = bit_def($flag_str);
+
+ $$check .= " | " if defined $$check;
+
+ $$check .= $flag_str;
+
+ return $flag_str;
+}
+
+if (! defined $kernel) {
+ print $H "#define CCS_FL_16BIT " . flag_str(\$flag, \$all_flags) . "\n";
+ print $H "#define CCS_FL_32BIT " . flag_str(\$flag, \$all_flags) . "\n";
+}
+
+print $H "#define CCS_FL_FLOAT_IREAL " . flag_str(\$flag, \$all_flags) . "\n";
+print $H "#define CCS_FL_IREAL " . flag_str(\$flag, \$all_flags) . "\n";
+print $H "#define CCS_BUILD_BUG \\
+ BUILD_BUG_ON(~CCI_REG_PRIVATE_MASK & ($all_flags))\n"
+ if defined $kernel;
+
+print $H <<EOF
+
+#define CCS_R_ADDR(r) ((r) & 0xffff)
+
+EOF
+ if ! defined $kernel;
+
+print $A <<EOF
+#include <stdint.h>
+#include <stdio.h>
+#include "ccs-extra.h"
+#include "ccs-regs.h"
+
+EOF
+ if defined $A;
+
+my $uc_limith = basename uc $limith;
+$uc_limith =~ s/[^A-Z0-9]/_/g;
+
+print $LH <<EOF
+#ifndef __${uc_limith}__
+#define __${uc_limith}__
+
+$lh_hdr
+struct ccs_limit {
+ $uint32_t reg;
+ $uint16_t size;
+ $uint16_t flags;
+ const char *name;
+};
+
+EOF
+ ;
+print $LH "#define CCS_L_FL_SAME_REG " . bit_def(0) . "\n\n";
+
+print $LH <<EOF
+extern const struct ccs_limit ccs_limits[];
+
+EOF
+ ;
+
+print $LC <<EOF
+#include "ccs-limits.h"
+#include "ccs-regs.h"
+
+const struct ccs_limit ccs_limits[] = {
+EOF
+ ;
+
+my $limitcount = 0;
+my $argdescs;
+my $reglist = "const struct ccs_reg_desc ccs_reg_desc[] = {\n";
+
+sub name_split($$) {
+ my ($name, $addr) = @_;
+ my $args;
+
+ $name =~ /([^\(]+?)(\(.*)/;
+ ($name, $args) = ($1, $2);
+ $args = [split /,\s*/, $args];
+ foreach my $t (@$args) {
+ $t =~ s/[\(\)]//g;
+ $t =~ s/\//\\\//g;
+ }
+
+ return ($name, $addr, $args);
+}
+
+sub tabconv($) {
+ $_ = shift;
+
+ my @l = split "\n", $_;
+
+ map {
+ s/ {8,8}/\t/g;
+ s/\t\K +//;
+ } @l;
+
+ return (join "\n", @l) . "\n";
+}
+
+sub elem_bits(@) {
+ my @flags = @_;
+
+ return 16 if grep /^16$/, @flags;
+ return 32 if grep /^32$/, @flags;
+ return 8;
+}
+
+sub arr_size($) {
+ my $this = $_[0];
+ my $size = $this->{elsize};
+ my $h = $this->{argparams};
+
+ foreach my $arg (@{$this->{args}}) {
+ my $apref = $h->{$arg};
+
+ $size *= $apref->{max} - $apref->{min} + 1;
+ }
+
+ return $size;
+}
+
+sub print_args($$$) {
+ my ($this, $postfix, $is_same_reg) = @_;
+ my ($args, $argparams, $name) =
+ ($this->{args}, $this->{argparams}, $this->{name});
+ my $varname = "ccs_reg_arg_" . (lc $name) . $postfix;
+ my @mins;
+ my @sorted_args = @{$this->{sorted_args}};
+ my $lim_arg;
+ my $size = arr_size($this);
+
+ $argdescs .= "static const struct ccs_reg_arg " . $varname . "[] = {\n";
+
+ foreach my $sorted_arg (@sorted_args) {
+ push @mins, $argparams->{$sorted_arg}->{min};
+ }
+
+ foreach my $sorted_arg (@sorted_args) {
+ my $h = $argparams->{$sorted_arg};
+
+ $argdescs .= "\t{ \"$sorted_arg\", $h->{min}, $h->{max}, $h->{elsize} },\n";
+
+ $lim_arg .= defined $lim_arg ? ", $h->{min}" : "$h->{min}";
+ }
+
+ $argdescs .= "};\n\n";
+
+ $reglist .= "\t{ CCS_R_" . (uc $name) . "(" . (join ",", (@mins)) .
+ "), $size, sizeof($varname) / sizeof(*$varname)," .
+ " \"" . (lc $name) . "\", $varname },\n";
+
+ print $LC tabconv sprintf "\t{ CCS_R_" . (uc $name) . "($lim_arg), " .
+ $size . ", " . ($is_same_reg ? "CCS_L_FL_SAME_REG" : "0") .
+ ", \"$name" . (defined $this->{discontig} ? " $lim_arg" : "") . "\" },\n"
+ if is_limit_reg $this->{base_addr};
+}
+
+my $hdr_data;
+
+while (<$R>) {
+ chop;
+ s/^\s*//;
+ next if /^[#;]/ || /^$/;
+ if (s/^-\s*//) {
+ if (s/^b\s*//) {
+ my ($bit, $addr) = split /\t+/;
+ $bit = uc $bit;
+ $hdr_data .= sprintf "#define %-62s %s", "CCS_" . (uc ${this{name}}) ."_$bit", bit_def($addr) . "\n";
+ } elsif (s/^f\s*//) {
+ s/[,\.-]/_/g;
+ my @a = split /\s+/;
+ my ($msb, $lsb, $this_field) = reverse @a;
+ @a = ( { "name" => "SHIFT", "addr" => $lsb, "fmt" => "%uU", },
+ { "name" => "MASK", "addr" => (1 << ($msb + 1)) - 1 - ((1 << $lsb) - 1), "fmt" => "0x%" . join(".", ($this{"elsize"} >> 2) x 2) . "x" } );
+ $this{"field"} = $this_field;
+ foreach my $ar (@a) {
+ #print $ar->{fmt}."\n";
+ $hdr_data .= sprintf "#define %-62s " . $ar->{"fmt"} . "\n", "CCS_" . (uc $this{"name"}) . (defined $this_field ? "_" . uc $this_field : "") . "_" . $ar->{"name"}, $ar->{"addr"} . "\n";
+ }
+ } elsif (s/^e\s*//) {
+ s/[,\.-]/_/g;
+ my ($enum, $addr) = split /\s+/;
+ $enum = uc $enum;
+ $hdr_data .= sprintf "#define %-62s %s", "CCS_" . (uc ${this{name}}) . (defined $this{"field"} ? "_" . uc $this{"field"} : "") ."_$enum", $addr . ($addr =~ /0x/i ? "" : "U") . "\n";
+ } elsif (s/^l\s*//) {
+ my ($arg, $min, $max, $elsize, @discontig) = split /\s+/;
+ my $size;
+
+ foreach my $num ($min, $max) {
+ $num = hex $num if $num =~ /0x/i;
+ }
+
+ $hdr_data .= sprintf "#define %-62s %s", "CCS_LIM_" . (uc ${this{name}} . "_MIN_$arg"), $min . ($min =~ /0x/i ? "" : "U") . "\n";
+ $hdr_data .= sprintf "#define %-62s %s", "CCS_LIM_" . (uc ${this{name}} . "_MAX_$arg"), $max . ($max =~ /0x/i ? "" : "U") . "\n";
+
+ my $h = $this{argparams};
+
+ $h->{$arg} = { "min" => $min,
+ "max" => $max,
+ "elsize" => $elsize =~ /^0x/ ? hex $elsize : $elsize,
+ "discontig" => \@discontig };
+
+ $this{discontig} = $arg if @discontig;
+
+ next if $#{$this{args}} + 1 != scalar keys %{$this{argparams}};
+
+ my $reg_formula = "$this{addr}";
+ my $lim_formula;
+
+ chop $reg_formula;
+
+ $reg_formula = "(" . $reg_formula if $this{flagstring} ne "";
+
+ foreach my $arg (@{$this{args}}) {
+ my $d = $h->{$arg}->{discontig};
+ my $times = $h->{$arg}->{elsize} != 1 ?
+ " * " . $h->{$arg}->{elsize} : "";
+
+ if (@$d) {
+ my ($lim, $offset) = split /,/, $d->[0];
+
+ $reg_formula .= " + (($arg) < $lim ? ($arg)$times : $offset + (($arg) - $lim)$times)";
+ } else {
+ $reg_formula .= " + ($arg)$times";
+ }
+
+ $lim_formula .= (defined $lim_formula ? " + " : "") . "($arg)$times";
+ }
+
+ $reg_formula .= ")";
+ $lim_formula =~ s/^\(([a-z0-9]+)\)$/$1/i;
+
+ print $H tabconv sprintf("#define %-62s %s", "CCS_R_" . (uc $this{name}) .
+ $this{arglist}, $reg_formula .
+ (($this{flagstring} eq "") ? "" :
+ " | " . $this{flagstring} . ")") . "\n");
+
+ print $H tabconv $hdr_data;
+ undef $hdr_data;
+
+ # Sort arguments in descending order by size
+ @{$this{sorted_args}} = sort {
+ $h->{$a}->{elsize} <= $h->{$b}->{elsize}
+ } @{$this{args}};
+
+ if (defined $this{discontig}) {
+ my $da = $this{argparams}->{$this{discontig}};
+ my ($first_discontig) = split /,/, $da->{discontig}->[0];
+ my $max = $da->{max};
+
+ $da->{max} = $first_discontig - 1;
+ print_args(\%this, "", 0);
+
+ $da->{min} = $da->{max} + 1;
+ $da->{max} = $max;
+ print_args(\%this, $first_discontig, 1);
+ } else {
+ print_args(\%this, "", 0);
+ }
+
+ next unless is_limit_reg $this{base_addr};
+
+ print $LH tabconv sprintf "#define %-63s%s\n",
+ "CCS_L_" . (uc $this{name}) . "_OFFSET(" .
+ (join ", ", @{$this{args}}) . ")", "($lim_formula)";
+ }
+
+ if (! @{$this{args}}) {
+ print $H tabconv($hdr_data);
+ undef $hdr_data;
+ }
+
+ next;
+ }
+
+ my ($name, $addr, @flags) = split /\t+/, $_;
+ my $args = [];
+
+ my $sp;
+
+ ($name, $addr, $args) = name_split($name, $addr) if /\(.*\)/;
+
+ $name =~ s/[,\.-]/_/g;
+
+ my $flagstring = "";
+ my $bits = elem_bits(@flags);
+ if (! defined $kernel) {
+ $flagstring .= "| CCS_FL_16BIT " if $bits == 16;
+ $flagstring .= "| CCS_FL_32BIT " if $bits == 32;
+ }
+ $flagstring .= "| CCS_FL_FLOAT_IREAL " if grep /^float_ireal$/, @flags;
+ $flagstring .= "| CCS_FL_IREAL " if grep /^ireal$/, @flags;
+ $flagstring =~ s/^\| //;
+ $flagstring =~ s/ $//;
+ $flagstring = "($flagstring)" if $flagstring =~ /\|/;
+ my $base_addr = $addr;
+ $addr = "CCI_REG$bits($addr)" if defined $kernel;
+
+ if ($flagstring ne "" && !@$args) {
+ $addr = "($addr | $flagstring)";
+ $flagstring = "";
+ }
+
+ my $arglist = @$args ? "(" . (join ", ", @$args) . ")" : "";
+ $hdr_data .= sprintf "#define %-62s %s\n", "CCS_R_" . (uc $name), $addr
+ if !@$args;
+
+ $name =~ s/\(.*//;
+
+ %this = ( name => $name,
+ addr => $addr,
+ flagstring => $flagstring,
+ base_addr => $base_addr,
+ argparams => {},
+ args => $args,
+ arglist => $arglist,
+ elsize => $bits / 8,
+ );
+
+ if (!@$args) {
+ $reglist .= "\t{ CCS_R_" . (uc $name) . ", 1, 0, \"" . (lc $name) . "\", NULL },\n";
+ print $H tabconv $hdr_data;
+ undef $hdr_data;
+
+ print $LC tabconv sprintf "\t{ CCS_R_" . (uc $name) . ", " .
+ $this{elsize} . ", 0, \"$name\" },\n"
+ if is_limit_reg $this{base_addr};
+ }
+
+ print $LH tabconv sprintf "#define %-63s%s\n",
+ "CCS_L_" . (uc $this{name}), $limitcount++
+ if is_limit_reg $this{base_addr};
+}
+
+if (defined $A) {
+ print $A $argdescs, $reglist;
+
+ print $A "\t{ 0 }\n";
+
+ print $A "};\n";
+}
+
+print $H "\n#endif /* __${uc_header}__ */\n";
+
+print $LH tabconv sprintf "#define %-63s%s\n", "CCS_L_LAST", $limitcount;
+
+print $LH "\n#endif /* __${uc_limith}__ */\n";
+
+print $LC "\t{ 0 } /* Guardian */\n";
+print $LC "};\n";
+
+close($R);
+close($H);
+close($A) if defined $A;
+close($LC);
+close($LH);
diff --git a/Documentation/driver-api/media/drivers/contributors.rst b/Documentation/driver-api/media/drivers/contributors.rst
new file mode 100644
index 000000000000..f23b6e6faf46
--- /dev/null
+++ b/Documentation/driver-api/media/drivers/contributors.rst
@@ -0,0 +1,131 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+Contributors
+============
+
+.. note::
+
+ This documentation is outdated. There are several other DVB contributors
+ that aren't listed below.
+
+Thanks go to the following people for patches and contributions:
+
+- Michael Hunold <m.hunold@gmx.de>
+
+ - for the initial saa7146 driver and its recent overhaul
+
+- Christian Theiss
+
+ - for his work on the initial Linux DVB driver
+
+- Marcus Metzler <mocm@metzlerbros.de> and
+ Ralph Metzler <rjkm@metzlerbros.de>
+
+ - for their continuing work on the DVB driver
+
+- Michael Holzt <kju@debian.org>
+
+ - for his contributions to the dvb-net driver
+
+- Diego Picciani <d.picciani@novacomp.it>
+
+ - for CyberLogin for Linux which allows logging onto EON
+ (in case you are wondering where CyberLogin is, EON changed its login
+ procedure and CyberLogin is no longer used.)
+
+- Martin Schaller <martin@smurf.franken.de>
+
+ - for patching the cable card decoder driver
+
+- Klaus Schmidinger <Klaus.Schmidinger@cadsoft.de>
+
+ - for various fixes regarding tuning, OSD and CI stuff and his work on VDR
+
+- Steve Brown <sbrown@cortland.com>
+
+ - for his AFC kernel thread
+
+- Christoph Martin <martin@uni-mainz.de>
+
+ - for his LIRC infrared handler
+
+- Andreas Oberritter <obi@linuxtv.org>,
+ Dennis Noermann <dennis.noermann@noernet.de>,
+ Felix Domke <tmbinc@elitedvb.net>,
+ Florian Schirmer <jolt@tuxbox.org>,
+ Ronny Strutz <3des@elitedvb.de>,
+ Wolfram Joost <dbox2@frokaschwei.de>
+ and all the other dbox2 people
+
+ - for many bugfixes in the generic DVB Core, frontend drivers and
+ their work on the dbox2 port of the DVB driver
+
+- Oliver Endriss <o.endriss@gmx.de>
+
+ - for many bugfixes
+
+- Andrew de Quincey <adq_dvb@lidskialf.net>
+
+ - for the tda1004x frontend driver, and various bugfixes
+
+- Peter Schildmann <peter.schildmann@web.de>
+
+ - for the driver for the Technisat SkyStar2 PCI DVB card
+
+- Vadim Catana <skystar@moldova.cc>,
+ Roberto Ragusa <r.ragusa@libero.it> and
+ Augusto Cardoso <augusto@carhil.net>
+
+ - for all the work for the FlexCopII chipset by B2C2,Inc.
+
+- Davor Emard <emard@softhome.net>
+
+ - for his work on the budget drivers, the demux code,
+ the module unloading problems, ...
+
+- Hans-Frieder Vogt <hfvogt@arcor.de>
+
+ - for his work on calculating and checking the crc's for the
+ TechnoTrend/Hauppauge DEC driver firmware
+
+- Michael Dreher <michael@5dot1.de> and
+ Andreas 'randy' Weinberger
+
+ - for the support of the Fujitsu-Siemens Activy budget DVB-S
+
+- Kenneth Aafløy <ke-aa@frisurf.no>
+
+ - for adding support for Typhoon DVB-S budget card
+
+- Ernst Peinlich <e.peinlich@inode.at>
+
+ - for tuning/DiSEqC support for the DEC 3000-s
+
+- Peter Beutner <p.beutner@gmx.net>
+
+ - for the IR code for the ttusb-dec driver
+
+- Wilson Michaels <wilsonmichaels@earthlink.net>
+
+ - for the lgdt330x frontend driver, and various bugfixes
+
+- Michael Krufky <mkrufky@linuxtv.org>
+
+ - for maintaining v4l/dvb inter-tree dependencies
+
+- Taylor Jacob <rtjacob@earthlink.net>
+
+ - for the nxt2002 frontend driver
+
+- Jean-Francois Thibert <jeanfrancois@sagetv.com>
+
+ - for the nxt2004 frontend driver
+
+- Kirk Lapray <kirk.lapray@gmail.com>
+
+ - for the or51211 and or51132 frontend drivers, and
+ for merging the nxt2002 and nxt2004 modules into a
+ single nxt200x frontend driver.
+
+(If you think you should be in this list, but you are not, drop a
+line to the DVB mailing list)
diff --git a/Documentation/driver-api/media/drivers/cx2341x-devel.rst b/Documentation/driver-api/media/drivers/cx2341x-devel.rst
new file mode 100644
index 000000000000..97699df6ea2e
--- /dev/null
+++ b/Documentation/driver-api/media/drivers/cx2341x-devel.rst
@@ -0,0 +1,3685 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+The cx2341x driver
+==================
+
+Memory at cx2341x chips
+-----------------------
+
+This section describes the cx2341x memory map and documents some of the
+register space.
+
+.. note:: the memory long words are little-endian ('intel format').
+
+.. warning::
+
+ This information was figured out from searching through the memory
+ and registers, this information may not be correct and is certainly
+ not complete, and was not derived from anything more than searching
+ through the memory space with commands like:
+
+ .. code-block:: none
+
+ ivtvctl -O min=0x02000000,max=0x020000ff
+
+ So take this as is, I'm always searching for more stuff, it's a large
+ register space :-).
+
+Memory Map
+~~~~~~~~~~
+
+The cx2341x exposes its entire 64M memory space to the PCI host via the PCI BAR0
+(Base Address Register 0). The addresses here are offsets relative to the
+address held in BAR0.
+
+.. code-block:: none
+
+ 0x00000000-0x00ffffff Encoder memory space
+ 0x00000000-0x0003ffff Encode.rom
+ ???-??? MPEG buffer(s)
+ ???-??? Raw video capture buffer(s)
+ ???-??? Raw audio capture buffer(s)
+ ???-??? Display buffers (6 or 9)
+
+ 0x01000000-0x01ffffff Decoder memory space
+ 0x01000000-0x0103ffff Decode.rom
+ ???-??? MPEG buffers(s)
+ 0x0114b000-0x0115afff Audio.rom (deprecated?)
+
+ 0x02000000-0x0200ffff Register Space
+
+Registers
+~~~~~~~~~
+
+The registers occupy the 64k space starting at the 0x02000000 offset from BAR0.
+All of these registers are 32 bits wide.
+
+.. code-block:: none
+
+ DMA Registers 0x000-0xff:
+
+ 0x00 - Control:
+ 0=reset/cancel, 1=read, 2=write, 4=stop
+ 0x04 - DMA status:
+ 1=read busy, 2=write busy, 4=read error, 8=write error, 16=link list error
+ 0x08 - pci DMA pointer for read link list
+ 0x0c - pci DMA pointer for write link list
+ 0x10 - read/write DMA enable:
+ 1=read enable, 2=write enable
+ 0x14 - always 0xffffffff, if set any lower instability occurs, 0x00 crashes
+ 0x18 - ??
+ 0x1c - always 0x20 or 32, smaller values slow down DMA transactions
+ 0x20 - always value of 0x780a010a
+ 0x24-0x3c - usually just random values???
+ 0x40 - Interrupt status
+ 0x44 - Write a bit here and shows up in Interrupt status 0x40
+ 0x48 - Interrupt Mask
+ 0x4C - always value of 0xfffdffff,
+ if changed to 0xffffffff DMA write interrupts break.
+ 0x50 - always 0xffffffff
+ 0x54 - always 0xffffffff (0x4c, 0x50, 0x54 seem like interrupt masks, are
+ 3 processors on chip, Java ones, VPU, SPU, APU, maybe these are the
+ interrupt masks???).
+ 0x60-0x7C - random values
+ 0x80 - first write linked list reg, for Encoder Memory addr
+ 0x84 - first write linked list reg, for pci memory addr
+ 0x88 - first write linked list reg, for length of buffer in memory addr
+ (|0x80000000 or this for last link)
+ 0x8c-0xdc - rest of write linked list reg, 8 sets of 3 total, DMA goes here
+ from linked list addr in reg 0x0c, firmware must push through or
+ something.
+ 0xe0 - first (and only) read linked list reg, for pci memory addr
+ 0xe4 - first (and only) read linked list reg, for Decoder memory addr
+ 0xe8 - first (and only) read linked list reg, for length of buffer
+ 0xec-0xff - Nothing seems to be in these registers, 0xec-f4 are 0x00000000.
+
+Memory locations for Encoder Buffers 0x700-0x7ff:
+
+These registers show offsets of memory locations pertaining to each
+buffer area used for encoding, have to shift them by <<1 first.
+
+- 0x07F8: Encoder SDRAM refresh
+- 0x07FC: Encoder SDRAM pre-charge
+
+Memory locations for Decoder Buffers 0x800-0x8ff:
+
+These registers show offsets of memory locations pertaining to each
+buffer area used for decoding, have to shift them by <<1 first.
+
+- 0x08F8: Decoder SDRAM refresh
+- 0x08FC: Decoder SDRAM pre-charge
+
+Other memory locations:
+
+- 0x2800: Video Display Module control
+- 0x2D00: AO (audio output?) control
+- 0x2D24: Bytes Flushed
+- 0x7000: LSB I2C write clock bit (inverted)
+- 0x7004: LSB I2C write data bit (inverted)
+- 0x7008: LSB I2C read clock bit
+- 0x700c: LSB I2C read data bit
+- 0x9008: GPIO get input state
+- 0x900c: GPIO set output state
+- 0x9020: GPIO direction (Bit7 (GPIO 0..7) - 0:input, 1:output)
+- 0x9050: SPU control
+- 0x9054: Reset HW blocks
+- 0x9058: VPU control
+- 0xA018: Bit6: interrupt pending?
+- 0xA064: APU command
+
+
+Interrupt Status Register
+~~~~~~~~~~~~~~~~~~~~~~~~~
+
+The definition of the bits in the interrupt status register 0x0040, and the
+interrupt mask 0x0048. If a bit is cleared in the mask, then we want our ISR to
+execute.
+
+- bit 31 Encoder Start Capture
+- bit 30 Encoder EOS
+- bit 29 Encoder VBI capture
+- bit 28 Encoder Video Input Module reset event
+- bit 27 Encoder DMA complete
+- bit 24 Decoder audio mode change detection event (through event notification)
+- bit 22 Decoder data request
+- bit 20 Decoder DMA complete
+- bit 19 Decoder VBI re-insertion
+- bit 18 Decoder DMA err (linked-list bad)
+
+Missing documentation
+---------------------
+
+- Encoder API post(?)
+- Decoder API post(?)
+- Decoder VTRACE event
+
+
+The cx2341x firmware upload
+---------------------------
+
+This document describes how to upload the cx2341x firmware to the card.
+
+How to find
+~~~~~~~~~~~
+
+See the web pages of the various projects that uses this chip for information
+on how to obtain the firmware.
+
+The firmware stored in a Windows driver can be detected as follows:
+
+- Each firmware image is 256k bytes.
+- The 1st 32-bit word of the Encoder image is 0x0000da7
+- The 1st 32-bit word of the Decoder image is 0x00003a7
+- The 2nd 32-bit word of both images is 0xaa55bb66
+
+How to load
+~~~~~~~~~~~
+
+- Issue the FWapi command to stop the encoder if it is running. Wait for the
+ command to complete.
+- Issue the FWapi command to stop the decoder if it is running. Wait for the
+ command to complete.
+- Issue the I2C command to the digitizer to stop emitting VSYNC events.
+- Issue the FWapi command to halt the encoder's firmware.
+- Sleep for 10ms.
+- Issue the FWapi command to halt the decoder's firmware.
+- Sleep for 10ms.
+- Write 0x00000000 to register 0x2800 to stop the Video Display Module.
+- Write 0x00000005 to register 0x2D00 to stop the AO (audio output?).
+- Write 0x00000000 to register 0xA064 to ping? the APU.
+- Write 0xFFFFFFFE to register 0x9058 to stop the VPU.
+- Write 0xFFFFFFFF to register 0x9054 to reset the HW blocks.
+- Write 0x00000001 to register 0x9050 to stop the SPU.
+- Sleep for 10ms.
+- Write 0x0000001A to register 0x07FC to init the Encoder SDRAM's pre-charge.
+- Write 0x80000640 to register 0x07F8 to init the Encoder SDRAM's refresh to 1us.
+- Write 0x0000001A to register 0x08FC to init the Decoder SDRAM's pre-charge.
+- Write 0x80000640 to register 0x08F8 to init the Decoder SDRAM's refresh to 1us.
+- Sleep for 512ms. (600ms is recommended)
+- Transfer the encoder's firmware image to offset 0 in Encoder memory space.
+- Transfer the decoder's firmware image to offset 0 in Decoder memory space.
+- Use a read-modify-write operation to Clear bit 0 of register 0x9050 to
+ re-enable the SPU.
+- Sleep for 1 second.
+- Use a read-modify-write operation to Clear bits 3 and 0 of register 0x9058
+ to re-enable the VPU.
+- Sleep for 1 second.
+- Issue status API commands to both firmware images to verify.
+
+
+How to call the firmware API
+----------------------------
+
+The preferred calling convention is known as the firmware mailbox. The
+mailboxes are basically a fixed length array that serves as the call-stack.
+
+Firmware mailboxes can be located by searching the encoder and decoder memory
+for a 16 byte signature. That signature will be located on a 256-byte boundary.
+
+Signature:
+
+.. code-block:: none
+
+ 0x78, 0x56, 0x34, 0x12, 0x12, 0x78, 0x56, 0x34,
+ 0x34, 0x12, 0x78, 0x56, 0x56, 0x34, 0x12, 0x78
+
+The firmware implements 20 mailboxes of 20 32-bit words. The first 10 are
+reserved for API calls. The second 10 are used by the firmware for event
+notification.
+
+ ====== =================
+ Index Name
+ ====== =================
+ 0 Flags
+ 1 Command
+ 2 Return value
+ 3 Timeout
+ 4-19 Parameter/Result
+ ====== =================
+
+
+The flags are defined in the following table. The direction is from the
+perspective of the firmware.
+
+ ==== ========== ============================================
+ Bit Direction Purpose
+ ==== ========== ============================================
+ 2 O Firmware has processed the command.
+ 1 I Driver has finished setting the parameters.
+ 0 I Driver is using this mailbox.
+ ==== ========== ============================================
+
+The command is a 32-bit enumerator. The API specifics may be found in this
+chapter.
+
+The return value is a 32-bit enumerator. Only two values are currently defined:
+
+- 0=success
+- -1=command undefined.
+
+There are 16 parameters/results 32-bit fields. The driver populates these fields
+with values for all the parameters required by the call. The driver overwrites
+these fields with result values returned by the call.
+
+The timeout value protects the card from a hung driver thread. If the driver
+doesn't handle the completed call within the timeout specified, the firmware
+will reset that mailbox.
+
+To make an API call, the driver iterates over each mailbox looking for the
+first one available (bit 0 has been cleared). The driver sets that bit, fills
+in the command enumerator, the timeout value and any required parameters. The
+driver then sets the parameter ready bit (bit 1). The firmware scans the
+mailboxes for pending commands, processes them, sets the result code, populates
+the result value array with that call's return values and sets the call
+complete bit (bit 2). Once bit 2 is set, the driver should retrieve the results
+and clear all the flags. If the driver does not perform this task within the
+time set in the timeout register, the firmware will reset that mailbox.
+
+Event notifications are sent from the firmware to the host. The host tells the
+firmware which events it is interested in via an API call. That call tells the
+firmware which notification mailbox to use. The firmware signals the host via
+an interrupt. Only the 16 Results fields are used, the Flags, Command, Return
+value and Timeout words are not used.
+
+
+OSD firmware API description
+----------------------------
+
+.. note:: this API is part of the decoder firmware, so it's cx23415 only.
+
+
+
+CX2341X_OSD_GET_FRAMEBUFFER
+~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 65/0x41
+
+Description
+^^^^^^^^^^^
+
+Return base and length of contiguous OSD memory.
+
+Result[0]
+^^^^^^^^^
+
+OSD base address
+
+Result[1]
+^^^^^^^^^
+
+OSD length
+
+
+
+CX2341X_OSD_GET_PIXEL_FORMAT
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 66/0x42
+
+Description
+^^^^^^^^^^^
+
+Query OSD format
+
+Result[0]
+^^^^^^^^^
+
+0=8bit index
+1=16bit RGB 5:6:5
+2=16bit ARGB 1:5:5:5
+3=16bit ARGB 1:4:4:4
+4=32bit ARGB 8:8:8:8
+
+
+
+CX2341X_OSD_SET_PIXEL_FORMAT
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 67/0x43
+
+Description
+^^^^^^^^^^^
+
+Assign pixel format
+
+Param[0]
+^^^^^^^^
+
+- 0=8bit index
+- 1=16bit RGB 5:6:5
+- 2=16bit ARGB 1:5:5:5
+- 3=16bit ARGB 1:4:4:4
+- 4=32bit ARGB 8:8:8:8
+
+
+
+CX2341X_OSD_GET_STATE
+~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 68/0x44
+
+Description
+^^^^^^^^^^^
+
+Query OSD state
+
+Result[0]
+^^^^^^^^^
+
+- Bit 0 0=off, 1=on
+- Bits 1:2 alpha control
+- Bits 3:5 pixel format
+
+
+
+CX2341X_OSD_SET_STATE
+~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 69/0x45
+
+Description
+^^^^^^^^^^^
+
+OSD switch
+
+Param[0]
+^^^^^^^^
+
+0=off, 1=on
+
+
+
+CX2341X_OSD_GET_OSD_COORDS
+~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 70/0x46
+
+Description
+^^^^^^^^^^^
+
+Retrieve coordinates of OSD area blended with video
+
+Result[0]
+^^^^^^^^^
+
+OSD buffer address
+
+Result[1]
+^^^^^^^^^
+
+Stride in pixels
+
+Result[2]
+^^^^^^^^^
+
+Lines in OSD buffer
+
+Result[3]
+^^^^^^^^^
+
+Horizontal offset in buffer
+
+Result[4]
+^^^^^^^^^
+
+Vertical offset in buffer
+
+
+
+CX2341X_OSD_SET_OSD_COORDS
+~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 71/0x47
+
+Description
+^^^^^^^^^^^
+
+Assign the coordinates of the OSD area to blend with video
+
+Param[0]
+^^^^^^^^
+
+buffer address
+
+Param[1]
+^^^^^^^^
+
+buffer stride in pixels
+
+Param[2]
+^^^^^^^^
+
+lines in buffer
+
+Param[3]
+^^^^^^^^
+
+horizontal offset
+
+Param[4]
+^^^^^^^^
+
+vertical offset
+
+
+
+CX2341X_OSD_GET_SCREEN_COORDS
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 72/0x48
+
+Description
+^^^^^^^^^^^
+
+Retrieve OSD screen area coordinates
+
+Result[0]
+^^^^^^^^^
+
+top left horizontal offset
+
+Result[1]
+^^^^^^^^^
+
+top left vertical offset
+
+Result[2]
+^^^^^^^^^
+
+bottom right horizontal offset
+
+Result[3]
+^^^^^^^^^
+
+bottom right vertical offset
+
+
+
+CX2341X_OSD_SET_SCREEN_COORDS
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 73/0x49
+
+Description
+^^^^^^^^^^^
+
+Assign the coordinates of the screen area to blend with video
+
+Param[0]
+^^^^^^^^
+
+top left horizontal offset
+
+Param[1]
+^^^^^^^^
+
+top left vertical offset
+
+Param[2]
+^^^^^^^^
+
+bottom left horizontal offset
+
+Param[3]
+^^^^^^^^
+
+bottom left vertical offset
+
+
+
+CX2341X_OSD_GET_GLOBAL_ALPHA
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 74/0x4A
+
+Description
+^^^^^^^^^^^
+
+Retrieve OSD global alpha
+
+Result[0]
+^^^^^^^^^
+
+global alpha: 0=off, 1=on
+
+Result[1]
+^^^^^^^^^
+
+bits 0:7 global alpha
+
+
+
+CX2341X_OSD_SET_GLOBAL_ALPHA
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 75/0x4B
+
+Description
+^^^^^^^^^^^
+
+Update global alpha
+
+Param[0]
+^^^^^^^^
+
+global alpha: 0=off, 1=on
+
+Param[1]
+^^^^^^^^
+
+global alpha (8 bits)
+
+Param[2]
+^^^^^^^^
+
+local alpha: 0=on, 1=off
+
+
+
+CX2341X_OSD_SET_BLEND_COORDS
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 78/0x4C
+
+Description
+^^^^^^^^^^^
+
+Move start of blending area within display buffer
+
+Param[0]
+^^^^^^^^
+
+horizontal offset in buffer
+
+Param[1]
+^^^^^^^^
+
+vertical offset in buffer
+
+
+
+CX2341X_OSD_GET_FLICKER_STATE
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 79/0x4F
+
+Description
+^^^^^^^^^^^
+
+Retrieve flicker reduction module state
+
+Result[0]
+^^^^^^^^^
+
+flicker state: 0=off, 1=on
+
+
+
+CX2341X_OSD_SET_FLICKER_STATE
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 80/0x50
+
+Description
+^^^^^^^^^^^
+
+Set flicker reduction module state
+
+Param[0]
+^^^^^^^^
+
+State: 0=off, 1=on
+
+
+
+CX2341X_OSD_BLT_COPY
+~~~~~~~~~~~~~~~~~~~~
+
+Enum: 82/0x52
+
+Description
+^^^^^^^^^^^
+
+BLT copy
+
+Param[0]
+^^^^^^^^
+
+.. code-block:: none
+
+ '0000' zero
+ '0001' ~destination AND ~source
+ '0010' ~destination AND source
+ '0011' ~destination
+ '0100' destination AND ~source
+ '0101' ~source
+ '0110' destination XOR source
+ '0111' ~destination OR ~source
+ '1000' ~destination AND ~source
+ '1001' destination XNOR source
+ '1010' source
+ '1011' ~destination OR source
+ '1100' destination
+ '1101' destination OR ~source
+ '1110' destination OR source
+ '1111' one
+
+
+Param[1]
+^^^^^^^^
+
+Resulting alpha blending
+
+- '01' source_alpha
+- '10' destination_alpha
+- '11' source_alpha*destination_alpha+1
+ (zero if both source and destination alpha are zero)
+
+Param[2]
+^^^^^^^^
+
+.. code-block:: none
+
+ '00' output_pixel = source_pixel
+
+ '01' if source_alpha=0:
+ output_pixel = destination_pixel
+ if 256 > source_alpha > 1:
+ output_pixel = ((source_alpha + 1)*source_pixel +
+ (255 - source_alpha)*destination_pixel)/256
+
+ '10' if destination_alpha=0:
+ output_pixel = source_pixel
+ if 255 > destination_alpha > 0:
+ output_pixel = ((255 - destination_alpha)*source_pixel +
+ (destination_alpha + 1)*destination_pixel)/256
+
+ '11' if source_alpha=0:
+ source_temp = 0
+ if source_alpha=255:
+ source_temp = source_pixel*256
+ if 255 > source_alpha > 0:
+ source_temp = source_pixel*(source_alpha + 1)
+ if destination_alpha=0:
+ destination_temp = 0
+ if destination_alpha=255:
+ destination_temp = destination_pixel*256
+ if 255 > destination_alpha > 0:
+ destination_temp = destination_pixel*(destination_alpha + 1)
+ output_pixel = (source_temp + destination_temp)/256
+
+Param[3]
+^^^^^^^^
+
+width
+
+Param[4]
+^^^^^^^^
+
+height
+
+Param[5]
+^^^^^^^^
+
+destination pixel mask
+
+Param[6]
+^^^^^^^^
+
+destination rectangle start address
+
+Param[7]
+^^^^^^^^
+
+destination stride in dwords
+
+Param[8]
+^^^^^^^^
+
+source stride in dwords
+
+Param[9]
+^^^^^^^^
+
+source rectangle start address
+
+
+
+CX2341X_OSD_BLT_FILL
+~~~~~~~~~~~~~~~~~~~~
+
+Enum: 83/0x53
+
+Description
+^^^^^^^^^^^
+
+BLT fill color
+
+Param[0]
+^^^^^^^^
+
+Same as Param[0] on API 0x52
+
+Param[1]
+^^^^^^^^
+
+Same as Param[1] on API 0x52
+
+Param[2]
+^^^^^^^^
+
+Same as Param[2] on API 0x52
+
+Param[3]
+^^^^^^^^
+
+width
+
+Param[4]
+^^^^^^^^
+
+height
+
+Param[5]
+^^^^^^^^
+
+destination pixel mask
+
+Param[6]
+^^^^^^^^
+
+destination rectangle start address
+
+Param[7]
+^^^^^^^^
+
+destination stride in dwords
+
+Param[8]
+^^^^^^^^
+
+color fill value
+
+
+
+CX2341X_OSD_BLT_TEXT
+~~~~~~~~~~~~~~~~~~~~
+
+Enum: 84/0x54
+
+Description
+^^^^^^^^^^^
+
+BLT for 8 bit alpha text source
+
+Param[0]
+^^^^^^^^
+
+Same as Param[0] on API 0x52
+
+Param[1]
+^^^^^^^^
+
+Same as Param[1] on API 0x52
+
+Param[2]
+^^^^^^^^
+
+Same as Param[2] on API 0x52
+
+Param[3]
+^^^^^^^^
+
+width
+
+Param[4]
+^^^^^^^^
+
+height
+
+Param[5]
+^^^^^^^^
+
+destination pixel mask
+
+Param[6]
+^^^^^^^^
+
+destination rectangle start address
+
+Param[7]
+^^^^^^^^
+
+destination stride in dwords
+
+Param[8]
+^^^^^^^^
+
+source stride in dwords
+
+Param[9]
+^^^^^^^^
+
+source rectangle start address
+
+Param[10]
+^^^^^^^^^
+
+color fill value
+
+
+
+CX2341X_OSD_SET_FRAMEBUFFER_WINDOW
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 86/0x56
+
+Description
+^^^^^^^^^^^
+
+Positions the main output window on the screen. The coordinates must be
+such that the entire window fits on the screen.
+
+Param[0]
+^^^^^^^^
+
+window width
+
+Param[1]
+^^^^^^^^
+
+window height
+
+Param[2]
+^^^^^^^^
+
+top left window corner horizontal offset
+
+Param[3]
+^^^^^^^^
+
+top left window corner vertical offset
+
+
+
+CX2341X_OSD_SET_CHROMA_KEY
+~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 96/0x60
+
+Description
+^^^^^^^^^^^
+
+Chroma key switch and color
+
+Param[0]
+^^^^^^^^
+
+state: 0=off, 1=on
+
+Param[1]
+^^^^^^^^
+
+color
+
+
+
+CX2341X_OSD_GET_ALPHA_CONTENT_INDEX
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 97/0x61
+
+Description
+^^^^^^^^^^^
+
+Retrieve alpha content index
+
+Result[0]
+^^^^^^^^^
+
+alpha content index, Range 0:15
+
+
+
+CX2341X_OSD_SET_ALPHA_CONTENT_INDEX
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 98/0x62
+
+Description
+^^^^^^^^^^^
+
+Assign alpha content index
+
+Param[0]
+^^^^^^^^
+
+alpha content index, range 0:15
+
+
+Encoder firmware API description
+--------------------------------
+
+CX2341X_ENC_PING_FW
+~~~~~~~~~~~~~~~~~~~
+
+Enum: 128/0x80
+
+Description
+^^^^^^^^^^^
+
+Does nothing. Can be used to check if the firmware is responding.
+
+
+
+CX2341X_ENC_START_CAPTURE
+~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 129/0x81
+
+Description
+^^^^^^^^^^^
+
+Commences the capture of video, audio and/or VBI data. All encoding
+parameters must be initialized prior to this API call. Captures frames
+continuously or until a predefined number of frames have been captured.
+
+Param[0]
+^^^^^^^^
+
+Capture stream type:
+
+ - 0=MPEG
+ - 1=Raw
+ - 2=Raw passthrough
+ - 3=VBI
+
+
+Param[1]
+^^^^^^^^
+
+Bitmask:
+
+ - Bit 0 when set, captures YUV
+ - Bit 1 when set, captures PCM audio
+ - Bit 2 when set, captures VBI (same as param[0]=3)
+ - Bit 3 when set, the capture destination is the decoder
+ (same as param[0]=2)
+ - Bit 4 when set, the capture destination is the host
+
+.. note:: this parameter is only meaningful for RAW capture type.
+
+
+
+CX2341X_ENC_STOP_CAPTURE
+~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 130/0x82
+
+Description
+^^^^^^^^^^^
+
+Ends a capture in progress
+
+Param[0]
+^^^^^^^^
+
+- 0=stop at end of GOP (generates IRQ)
+- 1=stop immediate (no IRQ)
+
+Param[1]
+^^^^^^^^
+
+Stream type to stop, see param[0] of API 0x81
+
+Param[2]
+^^^^^^^^
+
+Subtype, see param[1] of API 0x81
+
+
+
+CX2341X_ENC_SET_AUDIO_ID
+~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 137/0x89
+
+Description
+^^^^^^^^^^^
+
+Assigns the transport stream ID of the encoded audio stream
+
+Param[0]
+^^^^^^^^
+
+Audio Stream ID
+
+
+
+CX2341X_ENC_SET_VIDEO_ID
+~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 139/0x8B
+
+Description
+^^^^^^^^^^^
+
+Set video transport stream ID
+
+Param[0]
+^^^^^^^^
+
+Video stream ID
+
+
+
+CX2341X_ENC_SET_PCR_ID
+~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 141/0x8D
+
+Description
+^^^^^^^^^^^
+
+Assigns the transport stream ID for PCR packets
+
+Param[0]
+^^^^^^^^
+
+PCR Stream ID
+
+
+
+CX2341X_ENC_SET_FRAME_RATE
+~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 143/0x8F
+
+Description
+^^^^^^^^^^^
+
+Set video frames per second. Change occurs at start of new GOP.
+
+Param[0]
+^^^^^^^^
+
+- 0=30fps
+- 1=25fps
+
+
+
+CX2341X_ENC_SET_FRAME_SIZE
+~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 145/0x91
+
+Description
+^^^^^^^^^^^
+
+Select video stream encoding resolution.
+
+Param[0]
+^^^^^^^^
+
+Height in lines. Default 480
+
+Param[1]
+^^^^^^^^
+
+Width in pixels. Default 720
+
+
+
+CX2341X_ENC_SET_BIT_RATE
+~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 149/0x95
+
+Description
+^^^^^^^^^^^
+
+Assign average video stream bitrate.
+
+Param[0]
+^^^^^^^^
+
+0=variable bitrate, 1=constant bitrate
+
+Param[1]
+^^^^^^^^
+
+bitrate in bits per second
+
+Param[2]
+^^^^^^^^
+
+peak bitrate in bits per second, divided by 400
+
+Param[3]
+^^^^^^^^
+
+Mux bitrate in bits per second, divided by 400. May be 0 (default).
+
+Param[4]
+^^^^^^^^
+
+Rate Control VBR Padding
+
+Param[5]
+^^^^^^^^
+
+VBV Buffer used by encoder
+
+.. note::
+
+ #) Param\[3\] and Param\[4\] seem to be always 0
+ #) Param\[5\] doesn't seem to be used.
+
+
+
+CX2341X_ENC_SET_GOP_PROPERTIES
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 151/0x97
+
+Description
+^^^^^^^^^^^
+
+Setup the GOP structure
+
+Param[0]
+^^^^^^^^
+
+GOP size (maximum is 34)
+
+Param[1]
+^^^^^^^^
+
+Number of B frames between the I and P frame, plus 1.
+For example: IBBPBBPBBPBB --> GOP size: 12, number of B frames: 2+1 = 3
+
+.. note::
+
+ GOP size must be a multiple of (B-frames + 1).
+
+
+
+CX2341X_ENC_SET_ASPECT_RATIO
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 153/0x99
+
+Description
+^^^^^^^^^^^
+
+Sets the encoding aspect ratio. Changes in the aspect ratio take effect
+at the start of the next GOP.
+
+Param[0]
+^^^^^^^^
+
+- '0000' forbidden
+- '0001' 1:1 square
+- '0010' 4:3
+- '0011' 16:9
+- '0100' 2.21:1
+- '0101' to '1111' reserved
+
+
+
+CX2341X_ENC_SET_DNR_FILTER_MODE
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 155/0x9B
+
+Description
+^^^^^^^^^^^
+
+Assign Dynamic Noise Reduction operating mode
+
+Param[0]
+^^^^^^^^
+
+Bit0: Spatial filter, set=auto, clear=manual
+Bit1: Temporal filter, set=auto, clear=manual
+
+Param[1]
+^^^^^^^^
+
+Median filter:
+
+- 0=Disabled
+- 1=Horizontal
+- 2=Vertical
+- 3=Horiz/Vert
+- 4=Diagonal
+
+
+
+CX2341X_ENC_SET_DNR_FILTER_PROPS
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 157/0x9D
+
+Description
+^^^^^^^^^^^
+
+These Dynamic Noise Reduction filter values are only meaningful when
+the respective filter is set to "manual" (See API 0x9B)
+
+Param[0]
+^^^^^^^^
+
+Spatial filter: default 0, range 0:15
+
+Param[1]
+^^^^^^^^
+
+Temporal filter: default 0, range 0:31
+
+
+
+CX2341X_ENC_SET_CORING_LEVELS
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 159/0x9F
+
+Description
+^^^^^^^^^^^
+
+Assign Dynamic Noise Reduction median filter properties.
+
+Param[0]
+^^^^^^^^
+
+Threshold above which the luminance median filter is enabled.
+Default: 0, range 0:255
+
+Param[1]
+^^^^^^^^
+
+Threshold below which the luminance median filter is enabled.
+Default: 255, range 0:255
+
+Param[2]
+^^^^^^^^
+
+Threshold above which the chrominance median filter is enabled.
+Default: 0, range 0:255
+
+Param[3]
+^^^^^^^^
+
+Threshold below which the chrominance median filter is enabled.
+Default: 255, range 0:255
+
+
+
+CX2341X_ENC_SET_SPATIAL_FILTER_TYPE
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 161/0xA1
+
+Description
+^^^^^^^^^^^
+
+Assign spatial prefilter parameters
+
+Param[0]
+^^^^^^^^
+
+Luminance filter
+
+- 0=Off
+- 1=1D Horizontal
+- 2=1D Vertical
+- 3=2D H/V Separable (default)
+- 4=2D Symmetric non-separable
+
+Param[1]
+^^^^^^^^
+
+Chrominance filter
+
+- 0=Off
+- 1=1D Horizontal (default)
+
+
+
+CX2341X_ENC_SET_VBI_LINE
+~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 183/0xB7
+
+Description
+^^^^^^^^^^^
+
+Selects VBI line number.
+
+Param[0]
+^^^^^^^^
+
+- Bits 0:4 line number
+- Bit 31 0=top_field, 1=bottom_field
+- Bits 0:31 all set specifies "all lines"
+
+Param[1]
+^^^^^^^^
+
+VBI line information features: 0=disabled, 1=enabled
+
+Param[2]
+^^^^^^^^
+
+Slicing: 0=None, 1=Closed Caption
+Almost certainly not implemented. Set to 0.
+
+Param[3]
+^^^^^^^^
+
+Luminance samples in this line.
+Almost certainly not implemented. Set to 0.
+
+Param[4]
+^^^^^^^^
+
+Chrominance samples in this line
+Almost certainly not implemented. Set to 0.
+
+
+
+CX2341X_ENC_SET_STREAM_TYPE
+~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 185/0xB9
+
+Description
+^^^^^^^^^^^
+
+Assign stream type
+
+.. note::
+
+ Transport stream is not working in recent firmwares.
+ And in older firmwares the timestamps in the TS seem to be
+ unreliable.
+
+Param[0]
+^^^^^^^^
+
+- 0=Program stream
+- 1=Transport stream
+- 2=MPEG1 stream
+- 3=PES A/V stream
+- 5=PES Video stream
+- 7=PES Audio stream
+- 10=DVD stream
+- 11=VCD stream
+- 12=SVCD stream
+- 13=DVD_S1 stream
+- 14=DVD_S2 stream
+
+
+
+CX2341X_ENC_SET_OUTPUT_PORT
+~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 187/0xBB
+
+Description
+^^^^^^^^^^^
+
+Assign stream output port. Normally 0 when the data is copied through
+the PCI bus (DMA), and 1 when the data is streamed to another chip
+(pvrusb and cx88-blackbird).
+
+Param[0]
+^^^^^^^^
+
+- 0=Memory (default)
+- 1=Streaming
+- 2=Serial
+
+Param[1]
+^^^^^^^^
+
+Unknown, but leaving this to 0 seems to work best. Indications are that
+this might have to do with USB support, although passing anything but 0
+only breaks things.
+
+
+
+CX2341X_ENC_SET_AUDIO_PROPERTIES
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 189/0xBD
+
+Description
+^^^^^^^^^^^
+
+Set audio stream properties, may be called while encoding is in progress.
+
+.. note::
+
+ All bitfields are consistent with ISO11172 documentation except
+ bits 2:3 which ISO docs define as:
+
+ - '11' Layer I
+ - '10' Layer II
+ - '01' Layer III
+ - '00' Undefined
+
+ This discrepancy may indicate a possible error in the documentation.
+ Testing indicated that only Layer II is actually working, and that
+ the minimum bitrate should be 192 kbps.
+
+Param[0]
+^^^^^^^^
+
+Bitmask:
+
+.. code-block:: none
+
+ 0:1 '00' 44.1Khz
+ '01' 48Khz
+ '10' 32Khz
+ '11' reserved
+
+ 2:3 '01'=Layer I
+ '10'=Layer II
+
+ 4:7 Bitrate:
+ Index | Layer I | Layer II
+ ------+-------------+------------
+ '0000' | free format | free format
+ '0001' | 32 kbit/s | 32 kbit/s
+ '0010' | 64 kbit/s | 48 kbit/s
+ '0011' | 96 kbit/s | 56 kbit/s
+ '0100' | 128 kbit/s | 64 kbit/s
+ '0101' | 160 kbit/s | 80 kbit/s
+ '0110' | 192 kbit/s | 96 kbit/s
+ '0111' | 224 kbit/s | 112 kbit/s
+ '1000' | 256 kbit/s | 128 kbit/s
+ '1001' | 288 kbit/s | 160 kbit/s
+ '1010' | 320 kbit/s | 192 kbit/s
+ '1011' | 352 kbit/s | 224 kbit/s
+ '1100' | 384 kbit/s | 256 kbit/s
+ '1101' | 416 kbit/s | 320 kbit/s
+ '1110' | 448 kbit/s | 384 kbit/s
+
+ .. note::
+
+ For Layer II, not all combinations of total bitrate
+ and mode are allowed. See ISO11172-3 3-Annex B,
+ Table 3-B.2
+
+ 8:9 '00'=Stereo
+ '01'=JointStereo
+ '10'=Dual
+ '11'=Mono
+
+ .. note::
+
+ The cx23415 cannot decode Joint Stereo properly.
+
+ 10:11 Mode Extension used in joint_stereo mode.
+ In Layer I and II they indicate which subbands are in
+ intensity_stereo. All other subbands are coded in stereo.
+ '00' subbands 4-31 in intensity_stereo, bound==4
+ '01' subbands 8-31 in intensity_stereo, bound==8
+ '10' subbands 12-31 in intensity_stereo, bound==12
+ '11' subbands 16-31 in intensity_stereo, bound==16
+
+ 12:13 Emphasis:
+ '00' None
+ '01' 50/15uS
+ '10' reserved
+ '11' CCITT J.17
+
+ 14 CRC:
+ '0' off
+ '1' on
+
+ 15 Copyright:
+ '0' off
+ '1' on
+
+ 16 Generation:
+ '0' copy
+ '1' original
+
+
+
+CX2341X_ENC_HALT_FW
+~~~~~~~~~~~~~~~~~~~
+
+Enum: 195/0xC3
+
+Description
+^^^^^^^^^^^
+
+The firmware is halted and no further API calls are serviced until the
+firmware is uploaded again.
+
+
+
+CX2341X_ENC_GET_VERSION
+~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 196/0xC4
+
+Description
+^^^^^^^^^^^
+
+Returns the version of the encoder firmware.
+
+Result[0]
+^^^^^^^^^
+
+Version bitmask:
+- Bits 0:15 build
+- Bits 16:23 minor
+- Bits 24:31 major
+
+
+
+CX2341X_ENC_SET_GOP_CLOSURE
+~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 197/0xC5
+
+Description
+^^^^^^^^^^^
+
+Assigns the GOP open/close property.
+
+Param[0]
+^^^^^^^^
+
+- 0=Open
+- 1=Closed
+
+
+
+CX2341X_ENC_GET_SEQ_END
+~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 198/0xC6
+
+Description
+^^^^^^^^^^^
+
+Obtains the sequence end code of the encoder's buffer. When a capture
+is started a number of interrupts are still generated, the last of
+which will have Result[0] set to 1 and Result[1] will contain the size
+of the buffer.
+
+Result[0]
+^^^^^^^^^
+
+State of the transfer (1 if last buffer)
+
+Result[1]
+^^^^^^^^^
+
+If Result[0] is 1, this contains the size of the last buffer, undefined
+otherwise.
+
+
+
+CX2341X_ENC_SET_PGM_INDEX_INFO
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 199/0xC7
+
+Description
+^^^^^^^^^^^
+
+Sets the Program Index Information.
+The information is stored as follows:
+
+.. code-block:: c
+
+ struct info {
+ u32 length; // Length of this frame
+ u32 offset_low; // Offset in the file of the
+ u32 offset_high; // start of this frame
+ u32 mask1; // Bits 0-2 are the type mask:
+ // 1=I, 2=P, 4=B
+ // 0=End of Program Index, other fields
+ // are invalid.
+ u32 pts; // The PTS of the frame
+ u32 mask2; // Bit 0 is bit 32 of the pts.
+ };
+ u32 table_ptr;
+ struct info index[400];
+
+The table_ptr is the encoder memory address in the table were
+*new* entries will be written.
+
+.. note:: This is a ringbuffer, so the table_ptr will wraparound.
+
+Param[0]
+^^^^^^^^
+
+Picture Mask:
+- 0=No index capture
+- 1=I frames
+- 3=I,P frames
+- 7=I,P,B frames
+
+(Seems to be ignored, it always indexes I, P and B frames)
+
+Param[1]
+^^^^^^^^
+
+Elements requested (up to 400)
+
+Result[0]
+^^^^^^^^^
+
+Offset in the encoder memory of the start of the table.
+
+Result[1]
+^^^^^^^^^
+
+Number of allocated elements up to a maximum of Param[1]
+
+
+
+CX2341X_ENC_SET_VBI_CONFIG
+~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 200/0xC8
+
+Description
+^^^^^^^^^^^
+
+Configure VBI settings
+
+Param[0]
+^^^^^^^^
+
+Bitmap:
+
+.. code-block:: none
+
+ 0 Mode '0' Sliced, '1' Raw
+ 1:3 Insertion:
+ '000' insert in extension & user data
+ '001' insert in private packets
+ '010' separate stream and user data
+ '111' separate stream and private data
+ 8:15 Stream ID (normally 0xBD)
+
+Param[1]
+^^^^^^^^
+
+Frames per interrupt (max 8). Only valid in raw mode.
+
+Param[2]
+^^^^^^^^
+
+Total raw VBI frames. Only valid in raw mode.
+
+Param[3]
+^^^^^^^^
+
+Start codes
+
+Param[4]
+^^^^^^^^
+
+Stop codes
+
+Param[5]
+^^^^^^^^
+
+Lines per frame
+
+Param[6]
+^^^^^^^^
+
+Byte per line
+
+Result[0]
+^^^^^^^^^
+
+Observed frames per interrupt in raw mode only. Rage 1 to Param[1]
+
+Result[1]
+^^^^^^^^^
+
+Observed number of frames in raw mode. Range 1 to Param[2]
+
+Result[2]
+^^^^^^^^^
+
+Memory offset to start or raw VBI data
+
+
+
+CX2341X_ENC_SET_DMA_BLOCK_SIZE
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 201/0xC9
+
+Description
+^^^^^^^^^^^
+
+Set DMA transfer block size
+
+Param[0]
+^^^^^^^^
+
+DMA transfer block size in bytes or frames. When unit is bytes,
+supported block sizes are 2^7, 2^8 and 2^9 bytes.
+
+Param[1]
+^^^^^^^^
+
+Unit: 0=bytes, 1=frames
+
+
+
+CX2341X_ENC_GET_PREV_DMA_INFO_MB_10
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 202/0xCA
+
+Description
+^^^^^^^^^^^
+
+Returns information on the previous DMA transfer in conjunction with
+bit 27 of the interrupt mask. Uses mailbox 10.
+
+Result[0]
+^^^^^^^^^
+
+Type of stream
+
+Result[1]
+^^^^^^^^^
+
+Address Offset
+
+Result[2]
+^^^^^^^^^
+
+Maximum size of transfer
+
+
+
+CX2341X_ENC_GET_PREV_DMA_INFO_MB_9
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 203/0xCB
+
+Description
+^^^^^^^^^^^
+
+Returns information on the previous DMA transfer in conjunction with
+bit 27 or 18 of the interrupt mask. Uses mailbox 9.
+
+Result[0]
+^^^^^^^^^
+
+Status bits:
+- 0 read completed
+- 1 write completed
+- 2 DMA read error
+- 3 DMA write error
+- 4 Scatter-Gather array error
+
+Result[1]
+^^^^^^^^^
+
+DMA type
+
+Result[2]
+^^^^^^^^^
+
+Presentation Time Stamp bits 0..31
+
+Result[3]
+^^^^^^^^^
+
+Presentation Time Stamp bit 32
+
+
+
+CX2341X_ENC_SCHED_DMA_TO_HOST
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 204/0xCC
+
+Description
+^^^^^^^^^^^
+
+Setup DMA to host operation
+
+Param[0]
+^^^^^^^^
+
+Memory address of link list
+
+Param[1]
+^^^^^^^^
+
+Length of link list (wtf: what units ???)
+
+Param[2]
+^^^^^^^^
+
+DMA type (0=MPEG)
+
+
+
+CX2341X_ENC_INITIALIZE_INPUT
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 205/0xCD
+
+Description
+^^^^^^^^^^^
+
+Initializes the video input
+
+
+
+CX2341X_ENC_SET_FRAME_DROP_RATE
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 208/0xD0
+
+Description
+^^^^^^^^^^^
+
+For each frame captured, skip specified number of frames.
+
+Param[0]
+^^^^^^^^
+
+Number of frames to skip
+
+
+
+CX2341X_ENC_PAUSE_ENCODER
+~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 210/0xD2
+
+Description
+^^^^^^^^^^^
+
+During a pause condition, all frames are dropped instead of being encoded.
+
+Param[0]
+^^^^^^^^
+
+- 0=Pause encoding
+- 1=Continue encoding
+
+
+
+CX2341X_ENC_REFRESH_INPUT
+~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 211/0xD3
+
+Description
+^^^^^^^^^^^
+
+Refreshes the video input
+
+
+
+CX2341X_ENC_SET_COPYRIGHT
+~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 212/0xD4
+
+Description
+^^^^^^^^^^^
+
+Sets stream copyright property
+
+Param[0]
+^^^^^^^^
+
+
+- 0=Stream is not copyrighted
+- 1=Stream is copyrighted
+
+
+
+CX2341X_ENC_SET_EVENT_NOTIFICATION
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 213/0xD5
+
+Description
+^^^^^^^^^^^
+
+Setup firmware to notify the host about a particular event. Host must
+unmask the interrupt bit.
+
+Param[0]
+^^^^^^^^
+
+Event (0=refresh encoder input)
+
+Param[1]
+^^^^^^^^
+
+Notification 0=disabled 1=enabled
+
+Param[2]
+^^^^^^^^
+
+Interrupt bit
+
+Param[3]
+^^^^^^^^
+
+Mailbox slot, -1 if no mailbox required.
+
+
+
+CX2341X_ENC_SET_NUM_VSYNC_LINES
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 214/0xD6
+
+Description
+^^^^^^^^^^^
+
+Depending on the analog video decoder used, this assigns the number
+of lines for field 1 and 2.
+
+Param[0]
+^^^^^^^^
+
+Field 1 number of lines:
+- 0x00EF for SAA7114
+- 0x00F0 for SAA7115
+- 0x0105 for Micronas
+
+Param[1]
+^^^^^^^^
+
+Field 2 number of lines:
+- 0x00EF for SAA7114
+- 0x00F0 for SAA7115
+- 0x0106 for Micronas
+
+
+
+CX2341X_ENC_SET_PLACEHOLDER
+~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 215/0xD7
+
+Description
+^^^^^^^^^^^
+
+Provides a mechanism of inserting custom user data in the MPEG stream.
+
+Param[0]
+^^^^^^^^
+
+- 0=extension & user data
+- 1=private packet with stream ID 0xBD
+
+Param[1]
+^^^^^^^^
+
+Rate at which to insert data, in units of frames (for private packet)
+or GOPs (for ext. & user data)
+
+Param[2]
+^^^^^^^^
+
+Number of data DWORDs (below) to insert
+
+Param[3]
+^^^^^^^^
+
+Custom data 0
+
+Param[4]
+^^^^^^^^
+
+Custom data 1
+
+Param[5]
+^^^^^^^^
+
+Custom data 2
+
+Param[6]
+^^^^^^^^
+
+Custom data 3
+
+Param[7]
+^^^^^^^^
+
+Custom data 4
+
+Param[8]
+^^^^^^^^
+
+Custom data 5
+
+Param[9]
+^^^^^^^^
+
+Custom data 6
+
+Param[10]
+^^^^^^^^^
+
+Custom data 7
+
+Param[11]
+^^^^^^^^^
+
+Custom data 8
+
+
+
+CX2341X_ENC_MUTE_VIDEO
+~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 217/0xD9
+
+Description
+^^^^^^^^^^^
+
+Video muting
+
+Param[0]
+^^^^^^^^
+
+Bit usage:
+
+.. code-block:: none
+
+ 0 '0'=video not muted
+ '1'=video muted, creates frames with the YUV color defined below
+ 1:7 Unused
+ 8:15 V chrominance information
+ 16:23 U chrominance information
+ 24:31 Y luminance information
+
+
+
+CX2341X_ENC_MUTE_AUDIO
+~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 218/0xDA
+
+Description
+^^^^^^^^^^^
+
+Audio muting
+
+Param[0]
+^^^^^^^^
+
+- 0=audio not muted
+- 1=audio muted (produces silent mpeg audio stream)
+
+
+
+CX2341X_ENC_SET_VERT_CROP_LINE
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 219/0xDB
+
+Description
+^^^^^^^^^^^
+
+Something to do with 'Vertical Crop Line'
+
+Param[0]
+^^^^^^^^
+
+If saa7114 and raw VBI capture and 60 Hz, then set to 10001.
+Else 0.
+
+
+
+CX2341X_ENC_MISC
+~~~~~~~~~~~~~~~~
+
+Enum: 220/0xDC
+
+Description
+^^^^^^^^^^^
+
+Miscellaneous actions. Not known for 100% what it does. It's really a
+sort of ioctl call. The first parameter is a command number, the second
+the value.
+
+Param[0]
+^^^^^^^^
+
+Command number:
+
+.. code-block:: none
+
+ 1=set initial SCR value when starting encoding (works).
+ 2=set quality mode (apparently some test setting).
+ 3=setup advanced VIM protection handling.
+ Always 1 for the cx23416 and 0 for cx23415.
+ 4=generate DVD compatible PTS timestamps
+ 5=USB flush mode
+ 6=something to do with the quantization matrix
+ 7=set navigation pack insertion for DVD: adds 0xbf (private stream 2)
+ packets to the MPEG. The size of these packets is 2048 bytes (including
+ the header of 6 bytes: 0x000001bf + length). The payload is zeroed and
+ it is up to the application to fill them in. These packets are apparently
+ inserted every four frames.
+ 8=enable scene change detection (seems to be a failure)
+ 9=set history parameters of the video input module
+ 10=set input field order of VIM
+ 11=set quantization matrix
+ 12=reset audio interface after channel change or input switch (has no argument).
+ Needed for the cx2584x, not needed for the mspx4xx, but it doesn't seem to
+ do any harm calling it regardless.
+ 13=set audio volume delay
+ 14=set audio delay
+
+
+Param[1]
+^^^^^^^^
+
+Command value.
+
+Decoder firmware API description
+--------------------------------
+
+.. note:: this API is part of the decoder firmware, so it's cx23415 only.
+
+
+
+CX2341X_DEC_PING_FW
+~~~~~~~~~~~~~~~~~~~
+
+Enum: 0/0x00
+
+Description
+^^^^^^^^^^^
+
+This API call does nothing. It may be used to check if the firmware
+is responding.
+
+
+
+CX2341X_DEC_START_PLAYBACK
+~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 1/0x01
+
+Description
+^^^^^^^^^^^
+
+Begin or resume playback.
+
+Param[0]
+^^^^^^^^
+
+0 based frame number in GOP to begin playback from.
+
+Param[1]
+^^^^^^^^
+
+Specifies the number of muted audio frames to play before normal
+audio resumes. (This is not implemented in the firmware, leave at 0)
+
+
+
+CX2341X_DEC_STOP_PLAYBACK
+~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 2/0x02
+
+Description
+^^^^^^^^^^^
+
+Ends playback and clears all decoder buffers. If PTS is not zero,
+playback stops at specified PTS.
+
+Param[0]
+^^^^^^^^
+
+Display 0=last frame, 1=black
+
+.. note::
+
+ this takes effect immediately, so if you want to wait for a PTS,
+ then use '0', otherwise the screen goes to black at once.
+ You can call this later (even if there is no playback) with a 1 value
+ to set the screen to black.
+
+Param[1]
+^^^^^^^^
+
+PTS low
+
+Param[2]
+^^^^^^^^
+
+PTS high
+
+
+
+CX2341X_DEC_SET_PLAYBACK_SPEED
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 3/0x03
+
+Description
+^^^^^^^^^^^
+
+Playback stream at speed other than normal. There are two modes of
+operation:
+
+ - Smooth: host transfers entire stream and firmware drops unused
+ frames.
+ - Coarse: host drops frames based on indexing as required to achieve
+ desired speed.
+
+Param[0]
+^^^^^^^^
+
+.. code-block:: none
+
+ Bitmap:
+ 0:7 0 normal
+ 1 fast only "1.5 times"
+ n nX fast, 1/nX slow
+ 30 Framedrop:
+ '0' during 1.5 times play, every other B frame is dropped
+ '1' during 1.5 times play, stream is unchanged (bitrate
+ must not exceed 8mbps)
+ 31 Speed:
+ '0' slow
+ '1' fast
+
+.. note::
+
+ n is limited to 2. Anything higher does not result in
+ faster playback. Instead the host should start dropping frames.
+
+Param[1]
+^^^^^^^^
+
+Direction: 0=forward, 1=reverse
+
+.. note::
+
+ to make reverse playback work you have to write full GOPs in
+ reverse order.
+
+Param[2]
+^^^^^^^^
+
+.. code-block:: none
+
+ Picture mask:
+ 1=I frames
+ 3=I, P frames
+ 7=I, P, B frames
+
+Param[3]
+^^^^^^^^
+
+B frames per GOP (for reverse play only)
+
+.. note::
+
+ for reverse playback the Picture Mask should be set to I or I, P.
+ Adding B frames to the mask will result in corrupt video. This field
+ has to be set to the correct value in order to keep the timing correct.
+
+Param[4]
+^^^^^^^^
+
+Mute audio: 0=disable, 1=enable
+
+Param[5]
+^^^^^^^^
+
+Display 0=frame, 1=field
+
+Param[6]
+^^^^^^^^
+
+Specifies the number of muted audio frames to play before normal audio
+resumes. (Not implemented in the firmware, leave at 0)
+
+
+
+CX2341X_DEC_STEP_VIDEO
+~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 5/0x05
+
+Description
+^^^^^^^^^^^
+
+Each call to this API steps the playback to the next unit defined below
+in the current playback direction.
+
+Param[0]
+^^^^^^^^
+
+0=frame, 1=top field, 2=bottom field
+
+
+
+CX2341X_DEC_SET_DMA_BLOCK_SIZE
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 8/0x08
+
+Description
+^^^^^^^^^^^
+
+Set DMA transfer block size. Counterpart to API 0xC9
+
+Param[0]
+^^^^^^^^
+
+DMA transfer block size in bytes. A different size may be specified
+when issuing the DMA transfer command.
+
+
+
+CX2341X_DEC_GET_XFER_INFO
+~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 9/0x09
+
+Description
+^^^^^^^^^^^
+
+This API call may be used to detect an end of stream condition.
+
+Result[0]
+^^^^^^^^^
+
+Stream type
+
+Result[1]
+^^^^^^^^^
+
+Address offset
+
+Result[2]
+^^^^^^^^^
+
+Maximum bytes to transfer
+
+Result[3]
+^^^^^^^^^
+
+Buffer fullness
+
+
+
+CX2341X_DEC_GET_DMA_STATUS
+~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 10/0x0A
+
+Description
+^^^^^^^^^^^
+
+Status of the last DMA transfer
+
+Result[0]
+^^^^^^^^^
+
+Bit 1 set means transfer complete
+Bit 2 set means DMA error
+Bit 3 set means linked list error
+
+Result[1]
+^^^^^^^^^
+
+DMA type: 0=MPEG, 1=OSD, 2=YUV
+
+
+
+CX2341X_DEC_SCHED_DMA_FROM_HOST
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 11/0x0B
+
+Description
+^^^^^^^^^^^
+
+Setup DMA from host operation. Counterpart to API 0xCC
+
+Param[0]
+^^^^^^^^
+
+Memory address of link list
+
+Param[1]
+^^^^^^^^
+
+Total # of bytes to transfer
+
+Param[2]
+^^^^^^^^
+
+DMA type (0=MPEG, 1=OSD, 2=YUV)
+
+
+
+CX2341X_DEC_PAUSE_PLAYBACK
+~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 13/0x0D
+
+Description
+^^^^^^^^^^^
+
+Freeze playback immediately. In this mode, when internal buffers are
+full, no more data will be accepted and data request IRQs will be
+masked.
+
+Param[0]
+^^^^^^^^
+
+Display: 0=last frame, 1=black
+
+
+
+CX2341X_DEC_HALT_FW
+~~~~~~~~~~~~~~~~~~~
+
+Enum: 14/0x0E
+
+Description
+^^^^^^^^^^^
+
+The firmware is halted and no further API calls are serviced until
+the firmware is uploaded again.
+
+
+
+CX2341X_DEC_SET_STANDARD
+~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 16/0x10
+
+Description
+^^^^^^^^^^^
+
+Selects display standard
+
+Param[0]
+^^^^^^^^
+
+0=NTSC, 1=PAL
+
+
+
+CX2341X_DEC_GET_VERSION
+~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 17/0x11
+
+Description
+^^^^^^^^^^^
+
+Returns decoder firmware version information
+
+Result[0]
+^^^^^^^^^
+
+Version bitmask:
+ - Bits 0:15 build
+ - Bits 16:23 minor
+ - Bits 24:31 major
+
+
+
+CX2341X_DEC_SET_STREAM_INPUT
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 20/0x14
+
+Description
+^^^^^^^^^^^
+
+Select decoder stream input port
+
+Param[0]
+^^^^^^^^
+
+0=memory (default), 1=streaming
+
+
+
+CX2341X_DEC_GET_TIMING_INFO
+~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 21/0x15
+
+Description
+^^^^^^^^^^^
+
+Returns timing information from start of playback
+
+Result[0]
+^^^^^^^^^
+
+Frame count by decode order
+
+Result[1]
+^^^^^^^^^
+
+Video PTS bits 0:31 by display order
+
+Result[2]
+^^^^^^^^^
+
+Video PTS bit 32 by display order
+
+Result[3]
+^^^^^^^^^
+
+SCR bits 0:31 by display order
+
+Result[4]
+^^^^^^^^^
+
+SCR bit 32 by display order
+
+
+
+CX2341X_DEC_SET_AUDIO_MODE
+~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 22/0x16
+
+Description
+^^^^^^^^^^^
+
+Select audio mode
+
+Param[0]
+^^^^^^^^
+
+Dual mono mode action
+ 0=Stereo, 1=Left, 2=Right, 3=Mono, 4=Swap, -1=Unchanged
+
+Param[1]
+^^^^^^^^
+
+Stereo mode action:
+ 0=Stereo, 1=Left, 2=Right, 3=Mono, 4=Swap, -1=Unchanged
+
+
+
+CX2341X_DEC_SET_EVENT_NOTIFICATION
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 23/0x17
+
+Description
+^^^^^^^^^^^
+
+Setup firmware to notify the host about a particular event.
+Counterpart to API 0xD5
+
+Param[0]
+^^^^^^^^
+
+Event:
+ - 0=Audio mode change between mono, (joint) stereo and dual channel.
+ - 3=Decoder started
+ - 4=Unknown: goes off 10-15 times per second while decoding.
+ - 5=Some sync event: goes off once per frame.
+
+Param[1]
+^^^^^^^^
+
+Notification 0=disabled, 1=enabled
+
+Param[2]
+^^^^^^^^
+
+Interrupt bit
+
+Param[3]
+^^^^^^^^
+
+Mailbox slot, -1 if no mailbox required.
+
+
+
+CX2341X_DEC_SET_DISPLAY_BUFFERS
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 24/0x18
+
+Description
+^^^^^^^^^^^
+
+Number of display buffers. To decode all frames in reverse playback you
+must use nine buffers.
+
+Param[0]
+^^^^^^^^
+
+0=six buffers, 1=nine buffers
+
+
+
+CX2341X_DEC_EXTRACT_VBI
+~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 25/0x19
+
+Description
+^^^^^^^^^^^
+
+Extracts VBI data
+
+Param[0]
+^^^^^^^^
+
+0=extract from extension & user data, 1=extract from private packets
+
+Result[0]
+^^^^^^^^^
+
+VBI table location
+
+Result[1]
+^^^^^^^^^
+
+VBI table size
+
+
+
+CX2341X_DEC_SET_DECODER_SOURCE
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 26/0x1A
+
+Description
+^^^^^^^^^^^
+
+Selects decoder source. Ensure that the parameters passed to this
+API match the encoder settings.
+
+Param[0]
+^^^^^^^^
+
+Mode: 0=MPEG from host, 1=YUV from encoder, 2=YUV from host
+
+Param[1]
+^^^^^^^^
+
+YUV picture width
+
+Param[2]
+^^^^^^^^
+
+YUV picture height
+
+Param[3]
+^^^^^^^^
+
+Bitmap: see Param[0] of API 0xBD
+
+
+
+CX2341X_DEC_SET_PREBUFFERING
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Enum: 30/0x1E
+
+Description
+^^^^^^^^^^^
+
+Decoder prebuffering, when enabled up to 128KB are buffered for
+streams <8mpbs or 640KB for streams >8mbps
+
+Param[0]
+^^^^^^^^
+
+0=off, 1=on
+
+PVR350 Video decoder registers 0x02002800 -> 0x02002B00
+-------------------------------------------------------
+
+Author: Ian Armstrong <ian@iarmst.demon.co.uk>
+
+Version: v0.4
+
+Date: 12 March 2007
+
+
+This list has been worked out through trial and error. There will be mistakes
+and omissions. Some registers have no obvious effect so it's hard to say what
+they do, while others interact with each other, or require a certain load
+sequence. Horizontal filter setup is one example, with six registers working
+in unison and requiring a certain load sequence to correctly configure. The
+indexed colour palette is much easier to set at just two registers, but again
+it requires a certain load sequence.
+
+Some registers are fussy about what they are set to. Load in a bad value & the
+decoder will fail. A firmware reload will often recover, but sometimes a reset
+is required. For registers containing size information, setting them to 0 is
+generally a bad idea. For other control registers i.e. 2878, you'll only find
+out what values are bad when it hangs.
+
+.. code-block:: none
+
+ --------------------------------------------------------------------------------
+ 2800
+ bit 0
+ Decoder enable
+ 0 = disable
+ 1 = enable
+ --------------------------------------------------------------------------------
+ 2804
+ bits 0:31
+ Decoder horizontal Y alias register 1
+ ---------------
+ 2808
+ bits 0:31
+ Decoder horizontal Y alias register 2
+ ---------------
+ 280C
+ bits 0:31
+ Decoder horizontal Y alias register 3
+ ---------------
+ 2810
+ bits 0:31
+ Decoder horizontal Y alias register 4
+ ---------------
+ 2814
+ bits 0:31
+ Decoder horizontal Y alias register 5
+ ---------------
+ 2818
+ bits 0:31
+ Decoder horizontal Y alias trigger
+
+ These six registers control the horizontal aliasing filter for the Y plane.
+ The first five registers must all be loaded before accessing the trigger
+ (2818), as this register actually clocks the data through for the first
+ five.
+
+ To correctly program set the filter, this whole procedure must be done 16
+ times. The actual register contents are copied from a lookup-table in the
+ firmware which contains 4 different filter settings.
+
+ --------------------------------------------------------------------------------
+ 281C
+ bits 0:31
+ Decoder horizontal UV alias register 1
+ ---------------
+ 2820
+ bits 0:31
+ Decoder horizontal UV alias register 2
+ ---------------
+ 2824
+ bits 0:31
+ Decoder horizontal UV alias register 3
+ ---------------
+ 2828
+ bits 0:31
+ Decoder horizontal UV alias register 4
+ ---------------
+ 282C
+ bits 0:31
+ Decoder horizontal UV alias register 5
+ ---------------
+ 2830
+ bits 0:31
+ Decoder horizontal UV alias trigger
+
+ These six registers control the horizontal aliasing for the UV plane.
+ Operation is the same as the Y filter, with 2830 being the trigger
+ register.
+
+ --------------------------------------------------------------------------------
+ 2834
+ bits 0:15
+ Decoder Y source width in pixels
+
+ bits 16:31
+ Decoder Y destination width in pixels
+ ---------------
+ 2838
+ bits 0:15
+ Decoder UV source width in pixels
+
+ bits 16:31
+ Decoder UV destination width in pixels
+
+ NOTE: For both registers, the resulting image must be fully visible on
+ screen. If the image exceeds the right edge both the source and destination
+ size must be adjusted to reflect the visible portion. For the source width,
+ you must take into account the scaling when calculating the new value.
+ --------------------------------------------------------------------------------
+
+ 283C
+ bits 0:31
+ Decoder Y horizontal scaling
+ Normally = Reg 2854 >> 2
+ ---------------
+ 2840
+ bits 0:31
+ Decoder ?? unknown - horizontal scaling
+ Usually 0x00080514
+ ---------------
+ 2844
+ bits 0:31
+ Decoder UV horizontal scaling
+ Normally = Reg 2854 >> 2
+ ---------------
+ 2848
+ bits 0:31
+ Decoder ?? unknown - horizontal scaling
+ Usually 0x00100514
+ ---------------
+ 284C
+ bits 0:31
+ Decoder ?? unknown - Y plane
+ Usually 0x00200020
+ ---------------
+ 2850
+ bits 0:31
+ Decoder ?? unknown - UV plane
+ Usually 0x00200020
+ ---------------
+ 2854
+ bits 0:31
+ Decoder 'master' value for horizontal scaling
+ ---------------
+ 2858
+ bits 0:31
+ Decoder ?? unknown
+ Usually 0
+ ---------------
+ 285C
+ bits 0:31
+ Decoder ?? unknown
+ Normally = Reg 2854 >> 1
+ ---------------
+ 2860
+ bits 0:31
+ Decoder ?? unknown
+ Usually 0
+ ---------------
+ 2864
+ bits 0:31
+ Decoder ?? unknown
+ Normally = Reg 2854 >> 1
+ ---------------
+ 2868
+ bits 0:31
+ Decoder ?? unknown
+ Usually 0
+
+ Most of these registers either control horizontal scaling, or appear linked
+ to it in some way. Register 2854 contains the 'master' value & the other
+ registers can be calculated from that one. You must also remember to
+ correctly set the divider in Reg 2874.
+
+ To enlarge:
+ Reg 2854 = (source_width * 0x00200000) / destination_width
+ Reg 2874 = No divide
+
+ To reduce from full size down to half size:
+ Reg 2854 = (source_width/2 * 0x00200000) / destination width
+ Reg 2874 = Divide by 2
+
+ To reduce from half size down to quarter size:
+ Reg 2854 = (source_width/4 * 0x00200000) / destination width
+ Reg 2874 = Divide by 4
+
+ The result is always rounded up.
+
+ --------------------------------------------------------------------------------
+ 286C
+ bits 0:15
+ Decoder horizontal Y buffer offset
+
+ bits 15:31
+ Decoder horizontal UV buffer offset
+
+ Offset into the video image buffer. If the offset is gradually incremented,
+ the on screen image will move left & wrap around higher up on the right.
+
+ --------------------------------------------------------------------------------
+ 2870
+ bits 0:15
+ Decoder horizontal Y output offset
+
+ bits 16:31
+ Decoder horizontal UV output offset
+
+ Offsets the actual video output. Controls output alignment of the Y & UV
+ planes. The higher the value, the greater the shift to the left. Use
+ reg 2890 to move the image right.
+
+ --------------------------------------------------------------------------------
+ 2874
+ bits 0:1
+ Decoder horizontal Y output size divider
+ 00 = No divide
+ 01 = Divide by 2
+ 10 = Divide by 3
+
+ bits 4:5
+ Decoder horizontal UV output size divider
+ 00 = No divide
+ 01 = Divide by 2
+ 10 = Divide by 3
+
+ bit 8
+ Decoder ?? unknown
+ 0 = Normal
+ 1 = Affects video output levels
+
+ bit 16
+ Decoder ?? unknown
+ 0 = Normal
+ 1 = Disable horizontal filter
+
+ --------------------------------------------------------------------------------
+ 2878
+ bit 0
+ ?? unknown
+
+ bit 1
+ osd on/off
+ 0 = osd off
+ 1 = osd on
+
+ bit 2
+ Decoder + osd video timing
+ 0 = NTSC
+ 1 = PAL
+
+ bits 3:4
+ ?? unknown
+
+ bit 5
+ Decoder + osd
+ Swaps upper & lower fields
+
+ --------------------------------------------------------------------------------
+ 287C
+ bits 0:10
+ Decoder & osd ?? unknown
+ Moves entire screen horizontally. Starts at 0x005 with the screen
+ shifted heavily to the right. Incrementing in steps of 0x004 will
+ gradually shift the screen to the left.
+
+ bits 11:31
+ ?? unknown
+
+ Normally contents are 0x00101111 (NTSC) or 0x1010111d (PAL)
+
+ --------------------------------------------------------------------------------
+ 2880 -------- ?? unknown
+ 2884 -------- ?? unknown
+ --------------------------------------------------------------------------------
+ 2888
+ bit 0
+ Decoder + osd ?? unknown
+ 0 = Normal
+ 1 = Misaligned fields (Correctable through 289C & 28A4)
+
+ bit 4
+ ?? unknown
+
+ bit 8
+ ?? unknown
+
+ Warning: Bad values will require a firmware reload to recover.
+ Known to be bad are 0x000,0x011,0x100,0x111
+ --------------------------------------------------------------------------------
+ 288C
+ bits 0:15
+ osd ?? unknown
+ Appears to affect the osd position stability. The higher the value the
+ more unstable it becomes. Decoder output remains stable.
+
+ bits 16:31
+ osd ?? unknown
+ Same as bits 0:15
+
+ --------------------------------------------------------------------------------
+ 2890
+ bits 0:11
+ Decoder output horizontal offset.
+
+ Horizontal offset moves the video image right. A small left shift is
+ possible, but it's better to use reg 2870 for that due to its greater
+ range.
+
+ NOTE: Video corruption will occur if video window is shifted off the right
+ edge. To avoid this read the notes for 2834 & 2838.
+ --------------------------------------------------------------------------------
+ 2894
+ bits 0:23
+ Decoder output video surround colour.
+
+ Contains the colour (in yuv) used to fill the screen when the video is
+ running in a window.
+ --------------------------------------------------------------------------------
+ 2898
+ bits 0:23
+ Decoder video window colour
+ Contains the colour (in yuv) used to fill the video window when the
+ video is turned off.
+
+ bit 24
+ Decoder video output
+ 0 = Video on
+ 1 = Video off
+
+ bit 28
+ Decoder plane order
+ 0 = Y,UV
+ 1 = UV,Y
+
+ bit 29
+ Decoder second plane byte order
+ 0 = Normal (UV)
+ 1 = Swapped (VU)
+
+ In normal usage, the first plane is Y & the second plane is UV. Though the
+ order of the planes can be swapped, only the byte order of the second plane
+ can be swapped. This isn't much use for the Y plane, but can be useful for
+ the UV plane.
+
+ --------------------------------------------------------------------------------
+ 289C
+ bits 0:15
+ Decoder vertical field offset 1
+
+ bits 16:31
+ Decoder vertical field offset 2
+
+ Controls field output vertical alignment. The higher the number, the lower
+ the image on screen. Known starting values are 0x011E0017 (NTSC) &
+ 0x01500017 (PAL)
+ --------------------------------------------------------------------------------
+ 28A0
+ bits 0:15
+ Decoder & osd width in pixels
+
+ bits 16:31
+ Decoder & osd height in pixels
+
+ All output from the decoder & osd are disabled beyond this area. Decoder
+ output will simply go black outside of this region. If the osd tries to
+ exceed this area it will become corrupt.
+ --------------------------------------------------------------------------------
+ 28A4
+ bits 0:11
+ osd left shift.
+
+ Has a range of 0x770->0x7FF. With the exception of 0, any value outside of
+ this range corrupts the osd.
+ --------------------------------------------------------------------------------
+ 28A8
+ bits 0:15
+ osd vertical field offset 1
+
+ bits 16:31
+ osd vertical field offset 2
+
+ Controls field output vertical alignment. The higher the number, the lower
+ the image on screen. Known starting values are 0x011E0017 (NTSC) &
+ 0x01500017 (PAL)
+ --------------------------------------------------------------------------------
+ 28AC -------- ?? unknown
+ |
+ V
+ 28BC -------- ?? unknown
+ --------------------------------------------------------------------------------
+ 28C0
+ bit 0
+ Current output field
+ 0 = first field
+ 1 = second field
+
+ bits 16:31
+ Current scanline
+ The scanline counts from the top line of the first field
+ through to the last line of the second field.
+ --------------------------------------------------------------------------------
+ 28C4 -------- ?? unknown
+ |
+ V
+ 28F8 -------- ?? unknown
+ --------------------------------------------------------------------------------
+ 28FC
+ bit 0
+ ?? unknown
+ 0 = Normal
+ 1 = Breaks decoder & osd output
+ --------------------------------------------------------------------------------
+ 2900
+ bits 0:31
+ Decoder vertical Y alias register 1
+ ---------------
+ 2904
+ bits 0:31
+ Decoder vertical Y alias register 2
+ ---------------
+ 2908
+ bits 0:31
+ Decoder vertical Y alias trigger
+
+ These three registers control the vertical aliasing filter for the Y plane.
+ Operation is similar to the horizontal Y filter (2804). The only real
+ difference is that there are only two registers to set before accessing
+ the trigger register (2908). As for the horizontal filter, the values are
+ taken from a lookup table in the firmware, and the procedure must be
+ repeated 16 times to fully program the filter.
+ --------------------------------------------------------------------------------
+ 290C
+ bits 0:31
+ Decoder vertical UV alias register 1
+ ---------------
+ 2910
+ bits 0:31
+ Decoder vertical UV alias register 2
+ ---------------
+ 2914
+ bits 0:31
+ Decoder vertical UV alias trigger
+
+ These three registers control the vertical aliasing filter for the UV
+ plane. Operation is the same as the Y filter, with 2914 being the trigger.
+ --------------------------------------------------------------------------------
+ 2918
+ bits 0:15
+ Decoder Y source height in pixels
+
+ bits 16:31
+ Decoder Y destination height in pixels
+ ---------------
+ 291C
+ bits 0:15
+ Decoder UV source height in pixels divided by 2
+
+ bits 16:31
+ Decoder UV destination height in pixels
+
+ NOTE: For both registers, the resulting image must be fully visible on
+ screen. If the image exceeds the bottom edge both the source and
+ destination size must be adjusted to reflect the visible portion. For the
+ source height, you must take into account the scaling when calculating the
+ new value.
+ --------------------------------------------------------------------------------
+ 2920
+ bits 0:31
+ Decoder Y vertical scaling
+ Normally = Reg 2930 >> 2
+ ---------------
+ 2924
+ bits 0:31
+ Decoder Y vertical scaling
+ Normally = Reg 2920 + 0x514
+ ---------------
+ 2928
+ bits 0:31
+ Decoder UV vertical scaling
+ When enlarging = Reg 2930 >> 2
+ When reducing = Reg 2930 >> 3
+ ---------------
+ 292C
+ bits 0:31
+ Decoder UV vertical scaling
+ Normally = Reg 2928 + 0x514
+ ---------------
+ 2930
+ bits 0:31
+ Decoder 'master' value for vertical scaling
+ ---------------
+ 2934
+ bits 0:31
+ Decoder ?? unknown - Y vertical scaling
+ ---------------
+ 2938
+ bits 0:31
+ Decoder Y vertical scaling
+ Normally = Reg 2930
+ ---------------
+ 293C
+ bits 0:31
+ Decoder ?? unknown - Y vertical scaling
+ ---------------
+ 2940
+ bits 0:31
+ Decoder UV vertical scaling
+ When enlarging = Reg 2930 >> 1
+ When reducing = Reg 2930
+ ---------------
+ 2944
+ bits 0:31
+ Decoder ?? unknown - UV vertical scaling
+ ---------------
+ 2948
+ bits 0:31
+ Decoder UV vertical scaling
+ Normally = Reg 2940
+ ---------------
+ 294C
+ bits 0:31
+ Decoder ?? unknown - UV vertical scaling
+
+ Most of these registers either control vertical scaling, or appear linked
+ to it in some way. Register 2930 contains the 'master' value & all other
+ registers can be calculated from that one. You must also remember to
+ correctly set the divider in Reg 296C
+
+ To enlarge:
+ Reg 2930 = (source_height * 0x00200000) / destination_height
+ Reg 296C = No divide
+
+ To reduce from full size down to half size:
+ Reg 2930 = (source_height/2 * 0x00200000) / destination height
+ Reg 296C = Divide by 2
+
+ To reduce from half down to quarter.
+ Reg 2930 = (source_height/4 * 0x00200000) / destination height
+ Reg 296C = Divide by 4
+
+ --------------------------------------------------------------------------------
+ 2950
+ bits 0:15
+ Decoder Y line index into display buffer, first field
+
+ bits 16:31
+ Decoder Y vertical line skip, first field
+ --------------------------------------------------------------------------------
+ 2954
+ bits 0:15
+ Decoder Y line index into display buffer, second field
+
+ bits 16:31
+ Decoder Y vertical line skip, second field
+ --------------------------------------------------------------------------------
+ 2958
+ bits 0:15
+ Decoder UV line index into display buffer, first field
+
+ bits 16:31
+ Decoder UV vertical line skip, first field
+ --------------------------------------------------------------------------------
+ 295C
+ bits 0:15
+ Decoder UV line index into display buffer, second field
+
+ bits 16:31
+ Decoder UV vertical line skip, second field
+ --------------------------------------------------------------------------------
+ 2960
+ bits 0:15
+ Decoder destination height minus 1
+
+ bits 16:31
+ Decoder destination height divided by 2
+ --------------------------------------------------------------------------------
+ 2964
+ bits 0:15
+ Decoder Y vertical offset, second field
+
+ bits 16:31
+ Decoder Y vertical offset, first field
+
+ These two registers shift the Y plane up. The higher the number, the
+ greater the shift.
+ --------------------------------------------------------------------------------
+ 2968
+ bits 0:15
+ Decoder UV vertical offset, second field
+
+ bits 16:31
+ Decoder UV vertical offset, first field
+
+ These two registers shift the UV plane up. The higher the number, the
+ greater the shift.
+ --------------------------------------------------------------------------------
+ 296C
+ bits 0:1
+ Decoder vertical Y output size divider
+ 00 = No divide
+ 01 = Divide by 2
+ 10 = Divide by 4
+
+ bits 8:9
+ Decoder vertical UV output size divider
+ 00 = No divide
+ 01 = Divide by 2
+ 10 = Divide by 4
+ --------------------------------------------------------------------------------
+ 2970
+ bit 0
+ Decoder ?? unknown
+ 0 = Normal
+ 1 = Affect video output levels
+
+ bit 16
+ Decoder ?? unknown
+ 0 = Normal
+ 1 = Disable vertical filter
+
+ --------------------------------------------------------------------------------
+ 2974 -------- ?? unknown
+ |
+ V
+ 29EF -------- ?? unknown
+ --------------------------------------------------------------------------------
+ 2A00
+ bits 0:2
+ osd colour mode
+ 000 = 8 bit indexed
+ 001 = 16 bit (565)
+ 010 = 15 bit (555)
+ 011 = 12 bit (444)
+ 100 = 32 bit (8888)
+
+ bits 4:5
+ osd display bpp
+ 01 = 8 bit
+ 10 = 16 bit
+ 11 = 32 bit
+
+ bit 8
+ osd global alpha
+ 0 = Off
+ 1 = On
+
+ bit 9
+ osd local alpha
+ 0 = Off
+ 1 = On
+
+ bit 10
+ osd colour key
+ 0 = Off
+ 1 = On
+
+ bit 11
+ osd ?? unknown
+ Must be 1
+
+ bit 13
+ osd colour space
+ 0 = ARGB
+ 1 = AYVU
+
+ bits 16:31
+ osd ?? unknown
+ Must be 0x001B (some kind of buffer pointer ?)
+
+ When the bits-per-pixel is set to 8, the colour mode is ignored and
+ assumed to be 8 bit indexed. For 16 & 32 bits-per-pixel the colour depth
+ is honoured, and when using a colour depth that requires fewer bytes than
+ allocated the extra bytes are used as padding. So for a 32 bpp with 8 bit
+ index colour, there are 3 padding bytes per pixel. It's also possible to
+ select 16bpp with a 32 bit colour mode. This results in the pixel width
+ being doubled, but the color key will not work as expected in this mode.
+
+ Colour key is as it suggests. You designate a colour which will become
+ completely transparent. When using 565, 555 or 444 colour modes, the
+ colour key is always 16 bits wide. The colour to key on is set in Reg 2A18.
+
+ Local alpha works differently depending on the colour mode. For 32bpp & 8
+ bit indexed, local alpha is a per-pixel 256 step transparency, with 0 being
+ transparent and 255 being solid. For the 16bpp modes 555 & 444, the unused
+ bit(s) act as a simple transparency switch, with 0 being solid & 1 being
+ fully transparent. There is no local alpha support for 16bit 565.
+
+ Global alpha is a 256 step transparency that applies to the entire osd,
+ with 0 being transparent & 255 being solid.
+
+ It's possible to combine colour key, local alpha & global alpha.
+ --------------------------------------------------------------------------------
+ 2A04
+ bits 0:15
+ osd x coord for left edge
+
+ bits 16:31
+ osd y coord for top edge
+ ---------------
+ 2A08
+ bits 0:15
+ osd x coord for right edge
+
+ bits 16:31
+ osd y coord for bottom edge
+
+ For both registers, (0,0) = top left corner of the display area. These
+ registers do not control the osd size, only where it's positioned & how
+ much is visible. The visible osd area cannot exceed the right edge of the
+ display, otherwise the osd will become corrupt. See reg 2A10 for
+ setting osd width.
+ --------------------------------------------------------------------------------
+ 2A0C
+ bits 0:31
+ osd buffer index
+
+ An index into the osd buffer. Slowly incrementing this moves the osd left,
+ wrapping around onto the right edge
+ --------------------------------------------------------------------------------
+ 2A10
+ bits 0:11
+ osd buffer 32 bit word width
+
+ Contains the width of the osd measured in 32 bit words. This means that all
+ colour modes are restricted to a byte width which is divisible by 4.
+ --------------------------------------------------------------------------------
+ 2A14
+ bits 0:15
+ osd height in pixels
+
+ bits 16:32
+ osd line index into buffer
+ osd will start displaying from this line.
+ --------------------------------------------------------------------------------
+ 2A18
+ bits 0:31
+ osd colour key
+
+ Contains the colour value which will be transparent.
+ --------------------------------------------------------------------------------
+ 2A1C
+ bits 0:7
+ osd global alpha
+
+ Contains the global alpha value (equiv ivtvfbctl --alpha XX)
+ --------------------------------------------------------------------------------
+ 2A20 -------- ?? unknown
+ |
+ V
+ 2A2C -------- ?? unknown
+ --------------------------------------------------------------------------------
+ 2A30
+ bits 0:7
+ osd colour to change in indexed palette
+ ---------------
+ 2A34
+ bits 0:31
+ osd colour for indexed palette
+
+ To set the new palette, first load the index of the colour to change into
+ 2A30, then load the new colour into 2A34. The full palette is 256 colours,
+ so the index range is 0x00-0xFF
+ --------------------------------------------------------------------------------
+ 2A38 -------- ?? unknown
+ 2A3C -------- ?? unknown
+ --------------------------------------------------------------------------------
+ 2A40
+ bits 0:31
+ osd ?? unknown
+
+ Affects overall brightness, wrapping around to black
+ --------------------------------------------------------------------------------
+ 2A44
+ bits 0:31
+ osd ?? unknown
+
+ Green tint
+ --------------------------------------------------------------------------------
+ 2A48
+ bits 0:31
+ osd ?? unknown
+
+ Red tint
+ --------------------------------------------------------------------------------
+ 2A4C
+ bits 0:31
+ osd ?? unknown
+
+ Affects overall brightness, wrapping around to black
+ --------------------------------------------------------------------------------
+ 2A50
+ bits 0:31
+ osd ?? unknown
+
+ Colour shift
+ --------------------------------------------------------------------------------
+ 2A54
+ bits 0:31
+ osd ?? unknown
+
+ Colour shift
+ --------------------------------------------------------------------------------
+ 2A58 -------- ?? unknown
+ |
+ V
+ 2AFC -------- ?? unknown
+ --------------------------------------------------------------------------------
+ 2B00
+ bit 0
+ osd filter control
+ 0 = filter off
+ 1 = filter on
+
+ bits 1:4
+ osd ?? unknown
+
+ --------------------------------------------------------------------------------
+
+The cx231xx DMA engine
+----------------------
+
+
+This page describes the structures and procedures used by the cx2341x DMA
+engine.
+
+Introduction
+~~~~~~~~~~~~
+
+The cx2341x PCI interface is busmaster capable. This means it has a DMA
+engine to efficiently transfer large volumes of data between the card and main
+memory without requiring help from a CPU. Like most hardware, it must operate
+on contiguous physical memory. This is difficult to come by in large quantities
+on virtual memory machines.
+
+Therefore, it also supports a technique called "scatter-gather". The card can
+transfer multiple buffers in one operation. Instead of allocating one large
+contiguous buffer, the driver can allocate several smaller buffers.
+
+In practice, I've seen the average transfer to be roughly 80K, but transfers
+above 128K were not uncommon, particularly at startup. The 128K figure is
+important, because that is the largest block that the kernel can normally
+allocate. Even still, 128K blocks are hard to come by, so the driver writer is
+urged to choose a smaller block size and learn the scatter-gather technique.
+
+Mailbox #10 is reserved for DMA transfer information.
+
+Note: the hardware expects little-endian data ('intel format').
+
+Flow
+~~~~
+
+This section describes, in general, the order of events when handling DMA
+transfers. Detailed information follows this section.
+
+- The card raises the Encoder interrupt.
+- The driver reads the transfer type, offset and size from Mailbox #10.
+- The driver constructs the scatter-gather array from enough free dma buffers
+ to cover the size.
+- The driver schedules the DMA transfer via the ScheduleDMAtoHost API call.
+- The card raises the DMA Complete interrupt.
+- The driver checks the DMA status register for any errors.
+- The driver post-processes the newly transferred buffers.
+
+NOTE! It is possible that the Encoder and DMA Complete interrupts get raised
+simultaneously. (End of the last, start of the next, etc.)
+
+Mailbox #10
+~~~~~~~~~~~
+
+The Flags, Command, Return Value and Timeout fields are ignored.
+
+- Name: Mailbox #10
+- Results[0]: Type: 0: MPEG.
+- Results[1]: Offset: The position relative to the card's memory space.
+- Results[2]: Size: The exact number of bytes to transfer.
+
+My speculation is that since the StartCapture API has a capture type of "RAW"
+available, that the type field will have other values that correspond to YUV
+and PCM data.
+
+Scatter-Gather Array
+~~~~~~~~~~~~~~~~~~~~
+
+The scatter-gather array is a contiguously allocated block of memory that
+tells the card the source and destination of each data-block to transfer.
+Card "addresses" are derived from the offset supplied by Mailbox #10. Host
+addresses are the physical memory location of the target DMA buffer.
+
+Each S-G array element is a struct of three 32-bit words. The first word is
+the source address, the second is the destination address. Both take up the
+entire 32 bits. The lowest 18 bits of the third word is the transfer byte
+count. The high-bit of the third word is the "last" flag. The last-flag tells
+the card to raise the DMA_DONE interrupt. From hard personal experience, if
+you forget to set this bit, the card will still "work" but the stream will
+most likely get corrupted.
+
+The transfer count must be a multiple of 256. Therefore, the driver will need
+to track how much data in the target buffer is valid and deal with it
+accordingly.
+
+Array Element:
+
+- 32-bit Source Address
+- 32-bit Destination Address
+- 14-bit reserved (high bit is the last flag)
+- 18-bit byte count
+
+DMA Transfer Status
+~~~~~~~~~~~~~~~~~~~
+
+Register 0x0004 holds the DMA Transfer Status:
+
+- bit 0: read completed
+- bit 1: write completed
+- bit 2: DMA read error
+- bit 3: DMA write error
+- bit 4: Scatter-Gather array error
diff --git a/Documentation/driver-api/media/drivers/cx88-devel.rst b/Documentation/driver-api/media/drivers/cx88-devel.rst
new file mode 100644
index 000000000000..cfe7c03f4930
--- /dev/null
+++ b/Documentation/driver-api/media/drivers/cx88-devel.rst
@@ -0,0 +1,113 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+The cx88 driver
+===============
+
+Author: Gerd Hoffmann
+
+Documentation missing at the cx88 datasheet
+-------------------------------------------
+
+MO_OUTPUT_FORMAT (0x310164)
+
+.. code-block:: none
+
+ Previous default from DScaler: 0x1c1f0008
+ Digit 8: 31-28
+ 28: PREVREMOD = 1
+
+ Digit 7: 27-24 (0xc = 12 = b1100 )
+ 27: COMBALT = 1
+ 26: PAL_INV_PHASE
+ (DScaler apparently set this to 1, resulted in sucky picture)
+
+ Digits 6,5: 23-16
+ 25-16: COMB_RANGE = 0x1f [default] (9 bits -> max 512)
+
+ Digit 4: 15-12
+ 15: DISIFX = 0
+ 14: INVCBF = 0
+ 13: DISADAPT = 0
+ 12: NARROWADAPT = 0
+
+ Digit 3: 11-8
+ 11: FORCE2H
+ 10: FORCEREMD
+ 9: NCHROMAEN
+ 8: NREMODEN
+
+ Digit 2: 7-4
+ 7-6: YCORE
+ 5-4: CCORE
+
+ Digit 1: 3-0
+ 3: RANGE = 1
+ 2: HACTEXT
+ 1: HSFMT
+
+0x47 is the sync byte for MPEG-2 transport stream packets.
+Datasheet incorrectly states to use 47 decimal. 188 is the length.
+All DVB compliant frontends output packets with this start code.
+
+Hauppauge WinTV cx88 IR information
+-----------------------------------
+
+The controls for the mux are GPIO [0,1] for source, and GPIO 2 for muting.
+
+====== ======== =================================================
+GPIO0 GPIO1
+====== ======== =================================================
+ 0 0 TV Audio
+ 1 0 FM radio
+ 0 1 Line-In
+ 1 1 Mono tuner bypass or CD passthru (tuner specific)
+====== ======== =================================================
+
+GPIO 16(I believe) is tied to the IR port (if present).
+
+
+From the data sheet:
+
+- Register 24'h20004 PCI Interrupt Status
+
+ - bit [18] IR_SMP_INT Set when 32 input samples have been collected over
+ - gpio[16] pin into GP_SAMPLE register.
+
+What's missing from the data sheet:
+
+- Setup 4KHz sampling rate (roughly 2x oversampled; good enough for our RC5
+ compat remote)
+- set register 0x35C050 to 0xa80a80
+- enable sampling
+- set register 0x35C054 to 0x5
+- enable the IRQ bit 18 in the interrupt mask register (and
+ provide for a handler)
+
+GP_SAMPLE register is at 0x35C058
+
+Bits are then right shifted into the GP_SAMPLE register at the specified
+rate; you get an interrupt when a full DWORD is received.
+You need to recover the actual RC5 bits out of the (oversampled) IR sensor
+bits. (Hint: look for the 0/1and 1/0 crossings of the RC5 bi-phase data) An
+actual raw RC5 code will span 2-3 DWORDS, depending on the actual alignment.
+
+I'm pretty sure when no IR signal is present the receiver is always in a
+marking state(1); but stray light, etc can cause intermittent noise values
+as well. Remember, this is a free running sample of the IR receiver state
+over time, so don't assume any sample starts at any particular place.
+
+Additional info
+~~~~~~~~~~~~~~~
+
+This data sheet (google search) seems to have a lovely description of the
+RC5 basics:
+http://www.atmel.com/dyn/resources/prod_documents/doc2817.pdf
+
+This document has more data:
+http://www.nenya.be/beor/electronics/rc5.htm
+
+This document has a how to decode a bi-phase data stream:
+http://www.ee.washington.edu/circuit_archive/text/ir_decode.txt
+
+This document has still more info:
+http://www.xs4all.nl/~sbp/knowledge/ir/rc5.htm
diff --git a/Documentation/driver-api/media/drivers/dvb-usb.rst b/Documentation/driver-api/media/drivers/dvb-usb.rst
new file mode 100644
index 000000000000..b2d5d9e62b30
--- /dev/null
+++ b/Documentation/driver-api/media/drivers/dvb-usb.rst
@@ -0,0 +1,357 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+Idea behind the dvb-usb-framework
+=================================
+
+.. note::
+
+ #) This documentation is outdated. Please check at the DVB wiki
+ at https://linuxtv.org/wiki for more updated info.
+
+ #) **deprecated:** Newer DVB USB drivers should use the dvb-usb-v2 framework.
+
+In March 2005 I got the new Twinhan USB2.0 DVB-T device. They provided specs
+and a firmware.
+
+Quite keen I wanted to put the driver (with some quirks of course) into dibusb.
+After reading some specs and doing some USB snooping, it realized, that the
+dibusb-driver would be a complete mess afterwards. So I decided to do it in a
+different way: With the help of a dvb-usb-framework.
+
+The framework provides generic functions (mostly kernel API calls), such as:
+
+- Transport Stream URB handling in conjunction with dvb-demux-feed-control
+ (bulk and isoc are supported)
+- registering the device for the DVB-API
+- registering an I2C-adapter if applicable
+- remote-control/input-device handling
+- firmware requesting and loading (currently just for the Cypress USB
+ controllers)
+- other functions/methods which can be shared by several drivers (such as
+ functions for bulk-control-commands)
+- TODO: a I2C-chunker. It creates device-specific chunks of register-accesses
+ depending on length of a register and the number of values that can be
+ multi-written and multi-read.
+
+The source code of the particular DVB USB devices does just the communication
+with the device via the bus. The connection between the DVB-API-functionality
+is done via callbacks, assigned in a static device-description (struct
+dvb_usb_device) each device-driver has to have.
+
+For an example have a look in drivers/media/usb/dvb-usb/vp7045*.
+
+Objective is to migrate all the usb-devices (dibusb, cinergyT2, maybe the
+ttusb; flexcop-usb already benefits from the generic flexcop-device) to use
+the dvb-usb-lib.
+
+TODO: dynamic enabling and disabling of the pid-filter in regard to number of
+feeds requested.
+
+Supported devices
+-----------------
+
+See the LinuxTV DVB Wiki at https://linuxtv.org for a complete list of
+cards/drivers/firmwares:
+https://linuxtv.org/wiki/index.php/DVB_USB
+
+0. History & News:
+
+ 2005-06-30
+
+ - added support for WideView WT-220U (Thanks to Steve Chang)
+
+ 2005-05-30
+
+ - added basic isochronous support to the dvb-usb-framework
+ - added support for Conexant Hybrid reference design and Nebula
+ DigiTV USB
+
+ 2005-04-17
+
+ - all dibusb devices ported to make use of the dvb-usb-framework
+
+ 2005-04-02
+
+ - re-enabled and improved remote control code.
+
+ 2005-03-31
+
+ - ported the Yakumo/Hama/Typhoon DVB-T USB2.0 device to dvb-usb.
+
+ 2005-03-30
+
+ - first commit of the dvb-usb-module based on the dibusb-source.
+ First device is a new driver for the
+ TwinhanDTV Alpha / MagicBox II USB2.0-only DVB-T device.
+ - (change from dvb-dibusb to dvb-usb)
+
+ 2005-03-28
+
+ - added support for the AVerMedia AverTV DVB-T USB2.0 device
+ (Thanks to Glen Harris and Jiun-Kuei Jung, AVerMedia)
+
+ 2005-03-14
+
+ - added support for the Typhoon/Yakumo/HAMA DVB-T mobile USB2.0
+
+ 2005-02-11
+
+ - added support for the KWorld/ADSTech Instant DVB-T USB2.0.
+ Thanks a lot to Joachim von Caron
+
+ 2005-02-02
+ - added support for the Hauppauge Win-TV Nova-T USB2
+
+ 2005-01-31
+ - distorted streaming is gone for USB1.1 devices
+
+ 2005-01-13
+
+ - moved the mirrored pid_filter_table back to dvb-dibusb
+ first almost working version for HanfTek UMT-010
+ found out, that Yakumo/HAMA/Typhoon are predecessors of the HanfTek UMT-010
+
+ 2005-01-10
+
+ - refactoring completed, now everything is very delightful
+
+ - tuner quirks for some weird devices (Artec T1 AN2235 device has sometimes a
+ Panasonic Tuner assembled). Tunerprobing implemented.
+ Thanks a lot to Gunnar Wittich.
+
+ 2004-12-29
+
+ - after several days of struggling around bug of no returning URBs fixed.
+
+ 2004-12-26
+
+ - refactored the dibusb-driver, split into separate files
+ - i2c-probing enabled
+
+ 2004-12-06
+
+ - possibility for demod i2c-address probing
+ - new usb IDs (Compro, Artec)
+
+ 2004-11-23
+
+ - merged changes from DiB3000MC_ver2.1
+ - revised the debugging
+ - possibility to deliver the complete TS for USB2.0
+
+ 2004-11-21
+
+ - first working version of the dib3000mc/p frontend driver.
+
+ 2004-11-12
+
+ - added additional remote control keys. Thanks to Uwe Hanke.
+
+ 2004-11-07
+
+ - added remote control support. Thanks to David Matthews.
+
+ 2004-11-05
+
+ - added support for a new devices (Grandtec/Avermedia/Artec)
+ - merged my changes (for dib3000mb/dibusb) to the FE_REFACTORING, because it became HEAD
+ - moved transfer control (pid filter, fifo control) from usb driver to frontend, it seems
+ better settled there (added xfer_ops-struct)
+ - created a common files for frontends (mc/p/mb)
+
+ 2004-09-28
+
+ - added support for a new device (Unknown, vendor ID is Hyper-Paltek)
+
+ 2004-09-20
+
+ - added support for a new device (Compro DVB-U2000), thanks
+ to Amaury Demol for reporting
+ - changed usb TS transfer method (several urbs, stopping transfer
+ before setting a new pid)
+
+ 2004-09-13
+
+ - added support for a new device (Artec T1 USB TVBOX), thanks
+ to Christian Motschke for reporting
+
+ 2004-09-05
+
+ - released the dibusb device and dib3000mb-frontend driver
+ (old news for vp7041.c)
+
+ 2004-07-15
+
+ - found out, by accident, that the device has a TUA6010XS for PLL
+
+ 2004-07-12
+
+ - figured out, that the driver should also work with the
+ CTS Portable (Chinese Television System)
+
+ 2004-07-08
+
+ - firmware-extraction-2.422-problem solved, driver is now working
+ properly with firmware extracted from 2.422
+ - #if for 2.6.4 (dvb), compile issue
+ - changed firmware handling, see vp7041.txt sec 1.1
+
+ 2004-07-02
+
+ - some tuner modifications, v0.1, cleanups, first public
+
+ 2004-06-28
+
+ - now using the dvb_dmx_swfilter_packets, everything runs fine now
+
+ 2004-06-27
+
+ - able to watch and switching channels (pre-alpha)
+ - no section filtering yet
+
+ 2004-06-06
+
+ - first TS received, but kernel oops :/
+
+ 2004-05-14
+
+ - firmware loader is working
+
+ 2004-05-11
+
+ - start writing the driver
+
+How to use?
+-----------
+
+Firmware
+~~~~~~~~
+
+Most of the USB drivers need to download a firmware to the device before start
+working.
+
+Have a look at the Wikipage for the DVB-USB-drivers to find out, which firmware
+you need for your device:
+
+https://linuxtv.org/wiki/index.php/DVB_USB
+
+Compiling
+~~~~~~~~~
+
+Since the driver is in the linux kernel, activating the driver in
+your favorite config-environment should sufficient. I recommend
+to compile the driver as module. Hotplug does the rest.
+
+If you use dvb-kernel enter the build-2.6 directory run 'make' and 'insmod.sh
+load' afterwards.
+
+Loading the drivers
+~~~~~~~~~~~~~~~~~~~
+
+Hotplug is able to load the driver, when it is needed (because you plugged
+in the device).
+
+If you want to enable debug output, you have to load the driver manually and
+from within the dvb-kernel cvs repository.
+
+first have a look, which debug level are available:
+
+.. code-block:: none
+
+ # modinfo dvb-usb
+ # modinfo dvb-usb-vp7045
+
+ etc.
+
+.. code-block:: none
+
+ modprobe dvb-usb debug=<level>
+ modprobe dvb-usb-vp7045 debug=<level>
+ etc.
+
+should do the trick.
+
+When the driver is loaded successfully, the firmware file was in
+the right place and the device is connected, the "Power"-LED should be
+turned on.
+
+At this point you should be able to start a dvb-capable application. I'm use
+(t|s)zap, mplayer and dvbscan to test the basics. VDR-xine provides the
+long-term test scenario.
+
+Known problems and bugs
+-----------------------
+
+- Don't remove the USB device while running an DVB application, your system
+ will go crazy or die most likely.
+
+Adding support for devices
+~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+TODO
+
+USB1.1 Bandwidth limitation
+~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+A lot of the currently supported devices are USB1.1 and thus they have a
+maximum bandwidth of about 5-6 MBit/s when connected to a USB2.0 hub.
+This is not enough for receiving the complete transport stream of a
+DVB-T channel (which is about 16 MBit/s). Normally this is not a
+problem, if you only want to watch TV (this does not apply for HDTV),
+but watching a channel while recording another channel on the same
+frequency simply does not work very well. This applies to all USB1.1
+DVB-T devices, not just the dvb-usb-devices)
+
+The bug, where the TS is distorted by a heavy usage of the device is gone
+definitely. All dvb-usb-devices I was using (Twinhan, Kworld, DiBcom) are
+working like charm now with VDR. Sometimes I even was able to record a channel
+and watch another one.
+
+Comments
+~~~~~~~~
+
+Patches, comments and suggestions are very very welcome.
+
+3. Acknowledgements
+-------------------
+
+ Amaury Demol (Amaury.Demol@parrot.com) and Francois Kanounnikoff from DiBcom for
+ providing specs, code and help, on which the dvb-dibusb, dib3000mb and
+ dib3000mc are based.
+
+ David Matthews for identifying a new device type (Artec T1 with AN2235)
+ and for extending dibusb with remote control event handling. Thank you.
+
+ Alex Woods for frequently answering question about usb and dvb
+ stuff, a big thank you.
+
+ Bernd Wagner for helping with huge bug reports and discussions.
+
+ Gunnar Wittich and Joachim von Caron for their trust for providing
+ root-shells on their machines to implement support for new devices.
+
+ Allan Third and Michael Hutchinson for their help to write the Nebula
+ digitv-driver.
+
+ Glen Harris for bringing up, that there is a new dibusb-device and Jiun-Kuei
+ Jung from AVerMedia who kindly provided a special firmware to get the device
+ up and running in Linux.
+
+ Jennifer Chen, Jeff and Jack from Twinhan for kindly supporting by
+ writing the vp7045-driver.
+
+ Steve Chang from WideView for providing information for new devices and
+ firmware files.
+
+ Michael Paxton for submitting remote control keymaps.
+
+ Some guys on the linux-dvb mailing list for encouraging me.
+
+ Peter Schildmann >peter.schildmann-nospam-at-web.de< for his
+ user-level firmware loader, which saves a lot of time
+ (when writing the vp7041 driver)
+
+ Ulf Hermenau for helping me out with traditional chinese.
+
+ André Smoktun and Christian Frömmel for supporting me with
+ hardware and listening to my problems very patiently.
diff --git a/Documentation/driver-api/media/drivers/fimc-devel.rst b/Documentation/driver-api/media/drivers/fimc-devel.rst
new file mode 100644
index 000000000000..4c6b7c8be19f
--- /dev/null
+++ b/Documentation/driver-api/media/drivers/fimc-devel.rst
@@ -0,0 +1,33 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+.. include:: <isonum.txt>
+
+The Samsung S5P/EXYNOS4 FIMC driver
+===================================
+
+Copyright |copy| 2012 - 2013 Samsung Electronics Co., Ltd.
+
+Files partitioning
+------------------
+
+- media device driver
+
+ drivers/media/platform/samsung/exynos4-is/media-dev.[ch]
+
+- camera capture video device driver
+
+ drivers/media/platform/samsung/exynos4-is/fimc-capture.c
+
+- MIPI-CSI2 receiver subdev
+
+ drivers/media/platform/samsung/exynos4-is/mipi-csis.[ch]
+
+- video post-processor (mem-to-mem)
+
+ drivers/media/platform/samsung/exynos4-is/fimc-core.c
+
+- common files
+
+ drivers/media/platform/samsung/exynos4-is/fimc-core.h
+ drivers/media/platform/samsung/exynos4-is/fimc-reg.h
+ drivers/media/platform/samsung/exynos4-is/regs-fimc.h
diff --git a/Documentation/driver-api/media/drivers/frontends.rst b/Documentation/driver-api/media/drivers/frontends.rst
new file mode 100644
index 000000000000..7b8336ece681
--- /dev/null
+++ b/Documentation/driver-api/media/drivers/frontends.rst
@@ -0,0 +1,32 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+****************
+Frontend drivers
+****************
+
+Frontend attach headers
+***********************
+
+.. Keep it on alphabetic order
+
+.. kernel-doc:: drivers/media/dvb-frontends/a8293.h
+.. kernel-doc:: drivers/media/dvb-frontends/af9013.h
+.. kernel-doc:: drivers/media/dvb-frontends/ascot2e.h
+.. kernel-doc:: drivers/media/dvb-frontends/cxd2820r.h
+.. kernel-doc:: drivers/media/dvb-frontends/drxk.h
+.. kernel-doc:: drivers/media/dvb-frontends/dvb-pll.h
+.. kernel-doc:: drivers/media/dvb-frontends/helene.h
+.. kernel-doc:: drivers/media/dvb-frontends/horus3a.h
+.. kernel-doc:: drivers/media/dvb-frontends/ix2505v.h
+.. kernel-doc:: drivers/media/dvb-frontends/m88ds3103.h
+.. kernel-doc:: drivers/media/dvb-frontends/mb86a20s.h
+.. kernel-doc:: drivers/media/dvb-frontends/mn88472.h
+.. kernel-doc:: drivers/media/dvb-frontends/rtl2830.h
+.. kernel-doc:: drivers/media/dvb-frontends/rtl2832.h
+.. kernel-doc:: drivers/media/dvb-frontends/rtl2832_sdr.h
+.. kernel-doc:: drivers/media/dvb-frontends/stb6000.h
+.. kernel-doc:: drivers/media/dvb-frontends/tda10071.h
+.. kernel-doc:: drivers/media/dvb-frontends/tda826x.h
+.. kernel-doc:: drivers/media/dvb-frontends/zd1301_demod.h
+.. kernel-doc:: drivers/media/dvb-frontends/zl10036.h
+
diff --git a/Documentation/driver-api/media/drivers/index.rst b/Documentation/driver-api/media/drivers/index.rst
new file mode 100644
index 000000000000..c4123a16b5f9
--- /dev/null
+++ b/Documentation/driver-api/media/drivers/index.rst
@@ -0,0 +1,40 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+.. include:: <isonum.txt>
+
+===================================
+Media driver-specific documentation
+===================================
+
+Video4Linux (V4L) drivers
+=========================
+
+.. toctree::
+ :maxdepth: 5
+
+ bttv-devel
+ cx2341x-devel
+ cx88-devel
+ fimc-devel
+ pvrusb2
+ pxa_camera
+ radiotrack
+ rkisp1
+ saa7134-devel
+ sh_mobile_ceu_camera
+ tuners
+ vimc-devel
+ zoran
+ ccs/ccs
+
+
+Digital TV drivers
+==================
+
+.. toctree::
+ :maxdepth: 5
+
+ dvb-usb
+ frontends
+ vidtv
+ contributors
diff --git a/Documentation/driver-api/media/drivers/pvrusb2.rst b/Documentation/driver-api/media/drivers/pvrusb2.rst
new file mode 100644
index 000000000000..cbd9359c247a
--- /dev/null
+++ b/Documentation/driver-api/media/drivers/pvrusb2.rst
@@ -0,0 +1,202 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+The pvrusb2 driver
+==================
+
+Author: Mike Isely <isely@pobox.com>
+
+Background
+----------
+
+This driver is intended for the "Hauppauge WinTV PVR USB 2.0", which
+is a USB 2.0 hosted TV Tuner. This driver is a work in progress.
+Its history started with the reverse-engineering effort by Björn
+Danielsson <pvrusb2@dax.nu> whose web page can be found here:
+http://pvrusb2.dax.nu/
+
+From there Aurelien Alleaume <slts@free.fr> began an effort to
+create a video4linux compatible driver. I began with Aurelien's
+last known snapshot and evolved the driver to the state it is in
+here.
+
+More information on this driver can be found at:
+https://www.isely.net/pvrusb2.html
+
+
+This driver has a strong separation of layers. They are very
+roughly:
+
+1. Low level wire-protocol implementation with the device.
+
+2. I2C adaptor implementation and corresponding I2C client drivers
+ implemented elsewhere in V4L.
+
+3. High level hardware driver implementation which coordinates all
+ activities that ensure correct operation of the device.
+
+4. A "context" layer which manages instancing of driver, setup,
+ tear-down, arbitration, and interaction with high level
+ interfaces appropriately as devices are hotplugged in the
+ system.
+
+5. High level interfaces which glue the driver to various published
+ Linux APIs (V4L, sysfs, maybe DVB in the future).
+
+The most important shearing layer is between the top 2 layers. A
+lot of work went into the driver to ensure that any kind of
+conceivable API can be laid on top of the core driver. (Yes, the
+driver internally leverages V4L to do its work but that really has
+nothing to do with the API published by the driver to the outside
+world.) The architecture allows for different APIs to
+simultaneously access the driver. I have a strong sense of fairness
+about APIs and also feel that it is a good design principle to keep
+implementation and interface isolated from each other. Thus while
+right now the V4L high level interface is the most complete, the
+sysfs high level interface will work equally well for similar
+functions, and there's no reason I see right now why it shouldn't be
+possible to produce a DVB high level interface that can sit right
+alongside V4L.
+
+Building
+--------
+
+To build these modules essentially amounts to just running "Make",
+but you need the kernel source tree nearby and you will likely also
+want to set a few controlling environment variables first in order
+to link things up with that source tree. Please see the Makefile
+here for comments that explain how to do that.
+
+Source file list / functional overview
+--------------------------------------
+
+(Note: The term "module" used below generally refers to loosely
+defined functional units within the pvrusb2 driver and bears no
+relation to the Linux kernel's concept of a loadable module.)
+
+pvrusb2-audio.[ch] - This is glue logic that resides between this
+ driver and the msp3400.ko I2C client driver (which is found
+ elsewhere in V4L).
+
+pvrusb2-context.[ch] - This module implements the context for an
+ instance of the driver. Everything else eventually ties back to
+ or is otherwise instanced within the data structures implemented
+ here. Hotplugging is ultimately coordinated here. All high level
+ interfaces tie into the driver through this module. This module
+ helps arbitrate each interface's access to the actual driver core,
+ and is designed to allow concurrent access through multiple
+ instances of multiple interfaces (thus you can for example change
+ the tuner's frequency through sysfs while simultaneously streaming
+ video through V4L out to an instance of mplayer).
+
+pvrusb2-debug.h - This header defines a printk() wrapper and a mask
+ of debugging bit definitions for the various kinds of debug
+ messages that can be enabled within the driver.
+
+pvrusb2-debugifc.[ch] - This module implements a crude command line
+ oriented debug interface into the driver. Aside from being part
+ of the process for implementing manual firmware extraction (see
+ the pvrusb2 web site mentioned earlier), probably I'm the only one
+ who has ever used this. It is mainly a debugging aid.
+
+pvrusb2-eeprom.[ch] - This is glue logic that resides between this
+ driver the tveeprom.ko module, which is itself implemented
+ elsewhere in V4L.
+
+pvrusb2-encoder.[ch] - This module implements all protocol needed to
+ interact with the Conexant mpeg2 encoder chip within the pvrusb2
+ device. It is a crude echo of corresponding logic in ivtv,
+ however the design goals (strict isolation) and physical layer
+ (proxy through USB instead of PCI) are enough different that this
+ implementation had to be completely different.
+
+pvrusb2-hdw-internal.h - This header defines the core data structure
+ in the driver used to track ALL internal state related to control
+ of the hardware. Nobody outside of the core hardware-handling
+ modules should have any business using this header. All external
+ access to the driver should be through one of the high level
+ interfaces (e.g. V4L, sysfs, etc), and in fact even those high
+ level interfaces are restricted to the API defined in
+ pvrusb2-hdw.h and NOT this header.
+
+pvrusb2-hdw.h - This header defines the full internal API for
+ controlling the hardware. High level interfaces (e.g. V4L, sysfs)
+ will work through here.
+
+pvrusb2-hdw.c - This module implements all the various bits of logic
+ that handle overall control of a specific pvrusb2 device.
+ (Policy, instantiation, and arbitration of pvrusb2 devices fall
+ within the jurisdiction of pvrusb-context not here).
+
+pvrusb2-i2c-chips-\*.c - These modules implement the glue logic to
+ tie together and configure various I2C modules as they attach to
+ the I2C bus. There are two versions of this file. The "v4l2"
+ version is intended to be used in-tree alongside V4L, where we
+ implement just the logic that makes sense for a pure V4L
+ environment. The "all" version is intended for use outside of
+ V4L, where we might encounter other possibly "challenging" modules
+ from ivtv or older kernel snapshots (or even the support modules
+ in the standalone snapshot).
+
+pvrusb2-i2c-cmd-v4l1.[ch] - This module implements generic V4L1
+ compatible commands to the I2C modules. It is here where state
+ changes inside the pvrusb2 driver are translated into V4L1
+ commands that are in turn send to the various I2C modules.
+
+pvrusb2-i2c-cmd-v4l2.[ch] - This module implements generic V4L2
+ compatible commands to the I2C modules. It is here where state
+ changes inside the pvrusb2 driver are translated into V4L2
+ commands that are in turn send to the various I2C modules.
+
+pvrusb2-i2c-core.[ch] - This module provides an implementation of a
+ kernel-friendly I2C adaptor driver, through which other external
+ I2C client drivers (e.g. msp3400, tuner, lirc) may connect and
+ operate corresponding chips within the pvrusb2 device. It is
+ through here that other V4L modules can reach into this driver to
+ operate specific pieces (and those modules are in turn driven by
+ glue logic which is coordinated by pvrusb2-hdw, doled out by
+ pvrusb2-context, and then ultimately made available to users
+ through one of the high level interfaces).
+
+pvrusb2-io.[ch] - This module implements a very low level ring of
+ transfer buffers, required in order to stream data from the
+ device. This module is *very* low level. It only operates the
+ buffers and makes no attempt to define any policy or mechanism for
+ how such buffers might be used.
+
+pvrusb2-ioread.[ch] - This module layers on top of pvrusb2-io.[ch]
+ to provide a streaming API usable by a read() system call style of
+ I/O. Right now this is the only layer on top of pvrusb2-io.[ch],
+ however the underlying architecture here was intended to allow for
+ other styles of I/O to be implemented with additional modules, like
+ mmap()'ed buffers or something even more exotic.
+
+pvrusb2-main.c - This is the top level of the driver. Module level
+ and USB core entry points are here. This is our "main".
+
+pvrusb2-sysfs.[ch] - This is the high level interface which ties the
+ pvrusb2 driver into sysfs. Through this interface you can do
+ everything with the driver except actually stream data.
+
+pvrusb2-tuner.[ch] - This is glue logic that resides between this
+ driver and the tuner.ko I2C client driver (which is found
+ elsewhere in V4L).
+
+pvrusb2-util.h - This header defines some common macros used
+ throughout the driver. These macros are not really specific to
+ the driver, but they had to go somewhere.
+
+pvrusb2-v4l2.[ch] - This is the high level interface which ties the
+ pvrusb2 driver into video4linux. It is through here that V4L
+ applications can open and operate the driver in the usual V4L
+ ways. Note that **ALL** V4L functionality is published only
+ through here and nowhere else.
+
+pvrusb2-video-\*.[ch] - This is glue logic that resides between this
+ driver and the saa711x.ko I2C client driver (which is found
+ elsewhere in V4L). Note that saa711x.ko used to be known as
+ saa7115.ko in ivtv. There are two versions of this; one is
+ selected depending on the particular saa711[5x].ko that is found.
+
+pvrusb2.h - This header contains compile time tunable parameters
+ (and at the moment the driver has very little that needs to be
+ tuned).
diff --git a/Documentation/driver-api/media/drivers/pxa_camera.rst b/Documentation/driver-api/media/drivers/pxa_camera.rst
new file mode 100644
index 000000000000..46919919baac
--- /dev/null
+++ b/Documentation/driver-api/media/drivers/pxa_camera.rst
@@ -0,0 +1,194 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+PXA-Camera Host Driver
+======================
+
+Author: Robert Jarzmik <robert.jarzmik@free.fr>
+
+Constraints
+-----------
+
+a) Image size for YUV422P format
+ All YUV422P images are enforced to have width x height % 16 = 0.
+ This is due to DMA constraints, which transfers only planes of 8 byte
+ multiples.
+
+
+Global video workflow
+---------------------
+
+a) QCI stopped
+ Initially, the QCI interface is stopped.
+ When a buffer is queued, start_streaming is called and the QCI starts.
+
+b) QCI started
+ More buffers can be queued while the QCI is started without halting the
+ capture. The new buffers are "appended" at the tail of the DMA chain, and
+ smoothly captured one frame after the other.
+
+ Once a buffer is filled in the QCI interface, it is marked as "DONE" and
+ removed from the active buffers list. It can be then requeud or dequeued by
+ userland application.
+
+ Once the last buffer is filled in, the QCI interface stops.
+
+c) Capture global finite state machine schema
+
+.. code-block:: none
+
+ +----+ +---+ +----+
+ | DQ | | Q | | DQ |
+ | v | v | v
+ +-----------+ +------------------------+
+ | STOP | | Wait for capture start |
+ +-----------+ Q +------------------------+
+ +-> | QCI: stop | ------------------> | QCI: run | <------------+
+ | | DMA: stop | | DMA: stop | |
+ | +-----------+ +-----> +------------------------+ |
+ | / | |
+ | / +---+ +----+ | |
+ |capture list empty / | Q | | DQ | | QCI Irq EOF |
+ | / | v | v v |
+ | +--------------------+ +----------------------+ |
+ | | DMA hotlink missed | | Capture running | |
+ | +--------------------+ +----------------------+ |
+ | | QCI: run | +-----> | QCI: run | <-+ |
+ | | DMA: stop | / | DMA: run | | |
+ | +--------------------+ / +----------------------+ | Other |
+ | ^ /DMA still | | channels |
+ | | capture list / running | DMA Irq End | not |
+ | | not empty / | | finished |
+ | | / v | yet |
+ | +----------------------+ +----------------------+ | |
+ | | Videobuf released | | Channel completed | | |
+ | +----------------------+ +----------------------+ | |
+ +-- | QCI: run | | QCI: run | --+ |
+ | DMA: run | | DMA: run | |
+ +----------------------+ +----------------------+ |
+ ^ / | |
+ | no overrun / | overrun |
+ | / v |
+ +--------------------+ / +----------------------+ |
+ | Frame completed | / | Frame overran | |
+ +--------------------+ <-----+ +----------------------+ restart frame |
+ | QCI: run | | QCI: stop | --------------+
+ | DMA: run | | DMA: stop |
+ +--------------------+ +----------------------+
+
+ Legend: - each box is a FSM state
+ - each arrow is the condition to transition to another state
+ - an arrow with a comment is a mandatory transition (no condition)
+ - arrow "Q" means : a buffer was enqueued
+ - arrow "DQ" means : a buffer was dequeued
+ - "QCI: stop" means the QCI interface is not enabled
+ - "DMA: stop" means all 3 DMA channels are stopped
+ - "DMA: run" means at least 1 DMA channel is still running
+
+DMA usage
+---------
+
+a) DMA flow
+ - first buffer queued for capture
+ Once a first buffer is queued for capture, the QCI is started, but data
+ transfer is not started. On "End Of Frame" interrupt, the irq handler
+ starts the DMA chain.
+ - capture of one videobuffer
+ The DMA chain starts transferring data into videobuffer RAM pages.
+ When all pages are transferred, the DMA irq is raised on "ENDINTR" status
+ - finishing one videobuffer
+ The DMA irq handler marks the videobuffer as "done", and removes it from
+ the active running queue
+ Meanwhile, the next videobuffer (if there is one), is transferred by DMA
+ - finishing the last videobuffer
+ On the DMA irq of the last videobuffer, the QCI is stopped.
+
+b) DMA prepared buffer will have this structure
+
+.. code-block:: none
+
+ +------------+-----+---------------+-----------------+
+ | desc-sg[0] | ... | desc-sg[last] | finisher/linker |
+ +------------+-----+---------------+-----------------+
+
+This structure is pointed by dma->sg_cpu.
+The descriptors are used as follows:
+
+- desc-sg[i]: i-th descriptor, transferring the i-th sg
+ element to the video buffer scatter gather
+- finisher: has ddadr=DADDR_STOP, dcmd=ENDIRQEN
+- linker: has ddadr= desc-sg[0] of next video buffer, dcmd=0
+
+For the next schema, let's assume d0=desc-sg[0] .. dN=desc-sg[N],
+"f" stands for finisher and "l" for linker.
+A typical running chain is :
+
+.. code-block:: none
+
+ Videobuffer 1 Videobuffer 2
+ +---------+----+---+ +----+----+----+---+
+ | d0 | .. | dN | l | | d0 | .. | dN | f |
+ +---------+----+-|-+ ^----+----+----+---+
+ | |
+ +----+
+
+After the chaining is finished, the chain looks like :
+
+.. code-block:: none
+
+ Videobuffer 1 Videobuffer 2 Videobuffer 3
+ +---------+----+---+ +----+----+----+---+ +----+----+----+---+
+ | d0 | .. | dN | l | | d0 | .. | dN | l | | d0 | .. | dN | f |
+ +---------+----+-|-+ ^----+----+----+-|-+ ^----+----+----+---+
+ | | | |
+ +----+ +----+
+ new_link
+
+c) DMA hot chaining timeslice issue
+
+As DMA chaining is done while DMA _is_ running, the linking may be done
+while the DMA jumps from one Videobuffer to another. On the schema, that
+would be a problem if the following sequence is encountered :
+
+- DMA chain is Videobuffer1 + Videobuffer2
+- pxa_videobuf_queue() is called to queue Videobuffer3
+- DMA controller finishes Videobuffer2, and DMA stops
+
+.. code-block:: none
+
+ =>
+ Videobuffer 1 Videobuffer 2
+ +---------+----+---+ +----+----+----+---+
+ | d0 | .. | dN | l | | d0 | .. | dN | f |
+ +---------+----+-|-+ ^----+----+----+-^-+
+ | | |
+ +----+ +-- DMA DDADR loads DDADR_STOP
+
+- pxa_dma_add_tail_buf() is called, the Videobuffer2 "finisher" is
+ replaced by a "linker" to Videobuffer3 (creation of new_link)
+- pxa_videobuf_queue() finishes
+- the DMA irq handler is called, which terminates Videobuffer2
+- Videobuffer3 capture is not scheduled on DMA chain (as it stopped !!!)
+
+.. code-block:: none
+
+ Videobuffer 1 Videobuffer 2 Videobuffer 3
+ +---------+----+---+ +----+----+----+---+ +----+----+----+---+
+ | d0 | .. | dN | l | | d0 | .. | dN | l | | d0 | .. | dN | f |
+ +---------+----+-|-+ ^----+----+----+-|-+ ^----+----+----+---+
+ | | | |
+ +----+ +----+
+ new_link
+ DMA DDADR still is DDADR_STOP
+
+- pxa_camera_check_link_miss() is called
+ This checks if the DMA is finished and a buffer is still on the
+ pcdev->capture list. If that's the case, the capture will be restarted,
+ and Videobuffer3 is scheduled on DMA chain.
+- the DMA irq handler finishes
+
+.. note::
+
+ If DMA stops just after pxa_camera_check_link_miss() reads DDADR()
+ value, we have the guarantee that the DMA irq handler will be called back
+ when the DMA will finish the buffer, and pxa_camera_check_link_miss() will
+ be called again, to reschedule Videobuffer3.
diff --git a/Documentation/driver-api/media/drivers/radiotrack.rst b/Documentation/driver-api/media/drivers/radiotrack.rst
new file mode 100644
index 000000000000..a85cb6205db8
--- /dev/null
+++ b/Documentation/driver-api/media/drivers/radiotrack.rst
@@ -0,0 +1,168 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+The Radiotrack radio driver
+===========================
+
+Author: Stephen M. Benoit <benoits@servicepro.com>
+
+Date: Dec 14, 1996
+
+ACKNOWLEDGMENTS
+----------------
+
+This document was made based on 'C' code for Linux from Gideon le Grange
+(legrang@active.co.za or legrang@cs.sun.ac.za) in 1994, and elaborations from
+Frans Brinkman (brinkman@esd.nl) in 1996. The results reported here are from
+experiments that the author performed on his own setup, so your mileage may
+vary... I make no guarantees, claims or warranties to the suitability or
+validity of this information. No other documentation on the AIMS
+Lab (http://www.aimslab.com/) RadioTrack card was made available to the
+author. This document is offered in the hopes that it might help users who
+want to use the RadioTrack card in an environment other than MS Windows.
+
+WHY THIS DOCUMENT?
+------------------
+
+I have a RadioTrack card from back when I ran an MS-Windows platform. After
+converting to Linux, I found Gideon le Grange's command-line software for
+running the card, and found that it was good! Frans Brinkman made a
+comfortable X-windows interface, and added a scanning feature. For hack
+value, I wanted to see if the tuner could be tuned beyond the usual FM radio
+broadcast band, so I could pick up the audio carriers from North American
+broadcast TV channels, situated just below and above the 87.0-109.0 MHz range.
+I did not get much success, but I learned about programming ioports under
+Linux and gained some insights about the hardware design used for the card.
+
+So, without further delay, here are the details.
+
+
+PHYSICAL DESCRIPTION
+--------------------
+
+The RadioTrack card is an ISA 8-bit FM radio card. The radio frequency (RF)
+input is simply an antenna lead, and the output is a power audio signal
+available through a miniature phone plug. Its RF frequencies of operation are
+more or less limited from 87.0 to 109.0 MHz (the commercial FM broadcast
+band). Although the registers can be programmed to request frequencies beyond
+these limits, experiments did not give promising results. The variable
+frequency oscillator (VFO) that demodulates the intermediate frequency (IF)
+signal probably has a small range of useful frequencies, and wraps around or
+gets clipped beyond the limits mentioned above.
+
+
+CONTROLLING THE CARD WITH IOPORT
+--------------------------------
+
+The RadioTrack (base) ioport is configurable for 0x30c or 0x20c. Only one
+ioport seems to be involved. The ioport decoding circuitry must be pretty
+simple, as individual ioport bits are directly matched to specific functions
+(or blocks) of the radio card. This way, many functions can be changed in
+parallel with one write to the ioport. The only feedback available through
+the ioports appears to be the "Stereo Detect" bit.
+
+The bits of the ioport are arranged as follows:
+
+.. code-block:: none
+
+ MSb LSb
+ +------+------+------+--------+--------+-------+---------+--------+
+ | VolA | VolB | ???? | Stereo | Radio | TuneA | TuneB | Tune |
+ | (+) | (-) | | Detect | Audio | (bit) | (latch) | Update |
+ | | | | Enable | Enable | | | Enable |
+ +------+------+------+--------+--------+-------+---------+--------+
+
+
+==== ==== =================================
+VolA VolB Description
+==== ==== =================================
+0 0 audio mute
+0 1 volume + (some delay required)
+1 0 volume - (some delay required)
+1 1 stay at present volume
+==== ==== =================================
+
+==================== ===========
+Stereo Detect Enable Description
+==================== ===========
+0 No Detect
+1 Detect
+==================== ===========
+
+Results available by reading ioport >60 msec after last port write.
+
+ 0xff ==> no stereo detected, 0xfd ==> stereo detected.
+
+============================= =============================
+Radio to Audio (path) Enable Description
+============================= =============================
+0 Disable path (silence)
+1 Enable path (audio produced)
+============================= =============================
+
+===== ===== ==================
+TuneA TuneB Description
+===== ===== ==================
+0 0 "zero" bit phase 1
+0 1 "zero" bit phase 2
+1 0 "one" bit phase 1
+1 1 "one" bit phase 2
+===== ===== ==================
+
+
+24-bit code, where bits = (freq*40) + 10486188.
+The Most Significant 11 bits must be 1010 xxxx 0x0 to be valid.
+The bits are shifted in LSb first.
+
+================== ===========================
+Tune Update Enable Description
+================== ===========================
+0 Tuner held constant
+1 Tuner updating in progress
+================== ===========================
+
+
+PROGRAMMING EXAMPLES
+--------------------
+
+.. code-block:: none
+
+ Default: BASE <-- 0xc8 (current volume, no stereo detect,
+ radio enable, tuner adjust disable)
+
+ Card Off: BASE <-- 0x00 (audio mute, no stereo detect,
+ radio disable, tuner adjust disable)
+
+ Card On: BASE <-- 0x00 (see "Card Off", clears any unfinished business)
+ BASE <-- 0xc8 (see "Default")
+
+ Volume Down: BASE <-- 0x48 (volume down, no stereo detect,
+ radio enable, tuner adjust disable)
+ wait 10 msec
+ BASE <-- 0xc8 (see "Default")
+
+ Volume Up: BASE <-- 0x88 (volume up, no stereo detect,
+ radio enable, tuner adjust disable)
+ wait 10 msec
+ BASE <-- 0xc8 (see "Default")
+
+ Check Stereo: BASE <-- 0xd8 (current volume, stereo detect,
+ radio enable, tuner adjust disable)
+ wait 100 msec
+ x <-- BASE (read ioport)
+ BASE <-- 0xc8 (see "Default")
+
+ x=0xff ==> "not stereo", x=0xfd ==> "stereo detected"
+
+ Set Frequency: code = (freq*40) + 10486188
+ foreach of the 24 bits in code,
+ (from Least to Most Significant):
+ to write a "zero" bit,
+ BASE <-- 0x01 (audio mute, no stereo detect, radio
+ disable, "zero" bit phase 1, tuner adjust)
+ BASE <-- 0x03 (audio mute, no stereo detect, radio
+ disable, "zero" bit phase 2, tuner adjust)
+ to write a "one" bit,
+ BASE <-- 0x05 (audio mute, no stereo detect, radio
+ disable, "one" bit phase 1, tuner adjust)
+ BASE <-- 0x07 (audio mute, no stereo detect, radio
+ disable, "one" bit phase 2, tuner adjust)
diff --git a/Documentation/driver-api/media/drivers/rkisp1.rst b/Documentation/driver-api/media/drivers/rkisp1.rst
new file mode 100644
index 000000000000..ea336958a3af
--- /dev/null
+++ b/Documentation/driver-api/media/drivers/rkisp1.rst
@@ -0,0 +1,43 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+The Rockchip Image Signal Processor Driver (rkisp1)
+===================================================
+
+Versions and their differences
+------------------------------
+
+The rkisp1 block underwent some changes between SoC implementations.
+The vendor designates them as:
+
+- V10: used at least in rk3288 and rk3399
+- V11: declared in the original vendor code, but not used
+- V12: used at least in rk3326 and px30
+- V13: used at least in rk1808
+- V20: used in rk3568 and beyond
+
+Right now the kernel supports rkisp1 implementations based
+on V10 and V12 variants. V11 does not seem to be actually used
+and V13 will need some more additions but isn't researched yet,
+especially as it seems to be limited to the rk1808 which hasn't
+reached much market spread.
+
+V20 on the other hand will probably be used in future SoCs and
+has seen really big changes in the vendor kernel, so will need
+quite a bit of research.
+
+Changes from V10 to V12
+-----------------------
+
+- V12 supports a new CSI-host implementation but can still
+ also use the same implementation from V10
+- The module for lens shading correction got changed
+ from 12bit to 13bit width
+- The AWB and AEC modules got replaced to support finer
+ grained data collection
+
+Changes from V12 to V13
+-----------------------
+
+The list for V13 is incomplete and needs further investigation.
+
+- V13 does not support the old CSI-host implementation anymore
diff --git a/Documentation/driver-api/media/drivers/saa7134-devel.rst b/Documentation/driver-api/media/drivers/saa7134-devel.rst
new file mode 100644
index 000000000000..167fd729bc8c
--- /dev/null
+++ b/Documentation/driver-api/media/drivers/saa7134-devel.rst
@@ -0,0 +1,67 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+The saa7134 driver
+==================
+
+Author Gerd Hoffmann
+
+
+Card Variations:
+----------------
+
+Cards can use either of these two crystals (xtal):
+
+- 32.11 MHz -> .audio_clock=0x187de7
+- 24.576MHz -> .audio_clock=0x200000 (xtal * .audio_clock = 51539600)
+
+Some details about 30/34/35:
+
+- saa7130 - low-price chip, doesn't have mute, that is why all those
+ cards should have .mute field defined in their tuner structure.
+
+- saa7134 - usual chip
+
+- saa7133/35 - saa7135 is probably a marketing decision, since all those
+ chips identifies itself as 33 on pci.
+
+LifeView GPIOs
+--------------
+
+This section was authored by: Peter Missel <peter.missel@onlinehome.de>
+
+- LifeView FlyTV Platinum FM (LR214WF)
+
+ - GP27 MDT2005 PB4 pin 10
+ - GP26 MDT2005 PB3 pin 9
+ - GP25 MDT2005 PB2 pin 8
+ - GP23 MDT2005 PB1 pin 7
+ - GP22 MDT2005 PB0 pin 6
+ - GP21 MDT2005 PB5 pin 11
+ - GP20 MDT2005 PB6 pin 12
+ - GP19 MDT2005 PB7 pin 13
+ - nc MDT2005 PA3 pin 2
+ - Remote MDT2005 PA2 pin 1
+ - GP18 MDT2005 PA1 pin 18
+ - nc MDT2005 PA0 pin 17 strap low
+ - GP17 Strap "GP7"=High
+ - GP16 Strap "GP6"=High
+
+ - 0=Radio 1=TV
+ - Drives SA630D ENCH1 and HEF4052 A1 pinsto do FM radio through
+ SIF input
+
+ - GP15 nc
+ - GP14 nc
+ - GP13 nc
+ - GP12 Strap "GP5" = High
+ - GP11 Strap "GP4" = High
+ - GP10 Strap "GP3" = High
+ - GP09 Strap "GP2" = Low
+ - GP08 Strap "GP1" = Low
+ - GP07.00 nc
+
+Credits
+-------
+
+andrew.stevens@philips.com + werner.leeb@philips.com for providing
+saa7134 hardware specs and sample board.
diff --git a/Documentation/driver-api/media/drivers/sh_mobile_ceu_camera.rst b/Documentation/driver-api/media/drivers/sh_mobile_ceu_camera.rst
new file mode 100644
index 000000000000..822fcb8368ae
--- /dev/null
+++ b/Documentation/driver-api/media/drivers/sh_mobile_ceu_camera.rst
@@ -0,0 +1,142 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+Cropping and Scaling algorithm, used in the sh_mobile_ceu_camera driver
+=======================================================================
+
+Author: Guennadi Liakhovetski <g.liakhovetski@gmx.de>
+
+Terminology
+-----------
+
+sensor scales: horizontal and vertical scales, configured by the sensor driver
+host scales: -"- host driver
+combined scales: sensor_scale * host_scale
+
+
+Generic scaling / cropping scheme
+---------------------------------
+
+.. code-block:: none
+
+ -1--
+ |
+ -2-- -\
+ | --\
+ | --\
+ +-5-- . -- -3-- -\
+ | `... -\
+ | `... -4-- . - -7..
+ | `.
+ | `. .6--
+ |
+ | . .6'-
+ | .´
+ | ... -4'- .´
+ | ...´ - -7'.
+ +-5'- .´ -/
+ | -- -3'- -/
+ | --/
+ | --/
+ -2'- -/
+ |
+ |
+ -1'-
+
+In the above chart minuses and slashes represent "real" data amounts, points and
+accents represent "useful" data, basically, CEU scaled and cropped output,
+mapped back onto the client's source plane.
+
+Such a configuration can be produced by user requests:
+
+S_CROP(left / top = (5) - (1), width / height = (5') - (5))
+S_FMT(width / height = (6') - (6))
+
+Here:
+
+(1) to (1') - whole max width or height
+(1) to (2) - sensor cropped left or top
+(2) to (2') - sensor cropped width or height
+(3) to (3') - sensor scale
+(3) to (4) - CEU cropped left or top
+(4) to (4') - CEU cropped width or height
+(5) to (5') - reverse sensor scale applied to CEU cropped width or height
+(2) to (5) - reverse sensor scale applied to CEU cropped left or top
+(6) to (6') - CEU scale - user window
+
+
+S_FMT
+-----
+
+Do not touch input rectangle - it is already optimal.
+
+1. Calculate current sensor scales:
+
+ scale_s = ((2') - (2)) / ((3') - (3))
+
+2. Calculate "effective" input crop (sensor subwindow) - CEU crop scaled back at
+current sensor scales onto input window - this is user S_CROP:
+
+ width_u = (5') - (5) = ((4') - (4)) * scale_s
+
+3. Calculate new combined scales from "effective" input window to requested user
+window:
+
+ scale_comb = width_u / ((6') - (6))
+
+4. Calculate sensor output window by applying combined scales to real input
+window:
+
+ width_s_out = ((7') - (7)) = ((2') - (2)) / scale_comb
+
+5. Apply iterative sensor S_FMT for sensor output window.
+
+ subdev->video_ops->s_fmt(.width = width_s_out)
+
+6. Retrieve sensor output window (g_fmt)
+
+7. Calculate new sensor scales:
+
+ scale_s_new = ((3')_new - (3)_new) / ((2') - (2))
+
+8. Calculate new CEU crop - apply sensor scales to previously calculated
+"effective" crop:
+
+ width_ceu = (4')_new - (4)_new = width_u / scale_s_new
+ left_ceu = (4)_new - (3)_new = ((5) - (2)) / scale_s_new
+
+9. Use CEU cropping to crop to the new window:
+
+ ceu_crop(.width = width_ceu, .left = left_ceu)
+
+10. Use CEU scaling to scale to the requested user window:
+
+ scale_ceu = width_ceu / width
+
+
+S_CROP
+------
+
+The :ref:`V4L2 crop API <crop-scale>` says:
+
+"...specification does not define an origin or units. However by convention
+drivers should horizontally count unscaled samples relative to 0H."
+
+We choose to follow the advise and interpret cropping units as client input
+pixels.
+
+Cropping is performed in the following 6 steps:
+
+1. Request exactly user rectangle from the sensor.
+
+2. If smaller - iterate until a larger one is obtained. Result: sensor cropped
+ to 2 : 2', target crop 5 : 5', current output format 6' - 6.
+
+3. In the previous step the sensor has tried to preserve its output frame as
+ good as possible, but it could have changed. Retrieve it again.
+
+4. Sensor scaled to 3 : 3'. Sensor's scale is (2' - 2) / (3' - 3). Calculate
+ intermediate window: 4' - 4 = (5' - 5) * (3' - 3) / (2' - 2)
+
+5. Calculate and apply host scale = (6' - 6) / (4' - 4)
+
+6. Calculate and apply host crop: 6 - 7 = (5 - 2) * (6' - 6) / (5' - 5)
diff --git a/Documentation/driver-api/media/drivers/tuners.rst b/Documentation/driver-api/media/drivers/tuners.rst
new file mode 100644
index 000000000000..d7924141c544
--- /dev/null
+++ b/Documentation/driver-api/media/drivers/tuners.rst
@@ -0,0 +1,133 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+Tuner drivers
+=============
+
+Simple tuner Programming
+------------------------
+
+There are some flavors of Tuner programming APIs.
+These differ mainly by the bandswitch byte.
+
+- L= LG_API (VHF_LO=0x01, VHF_HI=0x02, UHF=0x08, radio=0x04)
+- P= PHILIPS_API (VHF_LO=0xA0, VHF_HI=0x90, UHF=0x30, radio=0x04)
+- T= TEMIC_API (VHF_LO=0x02, VHF_HI=0x04, UHF=0x01)
+- A= ALPS_API (VHF_LO=0x14, VHF_HI=0x12, UHF=0x11)
+- M= PHILIPS_MK3 (VHF_LO=0x01, VHF_HI=0x02, UHF=0x04, radio=0x19)
+
+Tuner Manufacturers
+-------------------
+
+- Samsung Tuner identification: (e.g. TCPM9091PD27)
+
+.. code-block:: none
+
+ TCP [ABCJLMNQ] 90[89][125] [DP] [ACD] 27 [ABCD]
+ [ABCJLMNQ]:
+ A= BG+DK
+ B= BG
+ C= I+DK
+ J= NTSC-Japan
+ L= Secam LL
+ M= BG+I+DK
+ N= NTSC
+ Q= BG+I+DK+LL
+ [89]: ?
+ [125]:
+ 2: No FM
+ 5: With FM
+ [DP]:
+ D= NTSC
+ P= PAL
+ [ACD]:
+ A= F-connector
+ C= Phono connector
+ D= Din Jack
+ [ABCD]:
+ 3-wire/I2C tuning, 2-band/3-band
+
+These Tuners are PHILIPS_API compatible.
+
+Philips Tuner identification: (e.g. FM1216MF)
+
+.. code-block:: none
+
+ F[IRMQ]12[1345]6{MF|ME|MP}
+ F[IRMQ]:
+ FI12x6: Tuner Series
+ FR12x6: Tuner + Radio IF
+ FM12x6: Tuner + FM
+ FQ12x6: special
+ FMR12x6: special
+ TD15xx: Digital Tuner ATSC
+ 12[1345]6:
+ 1216: PAL BG
+ 1236: NTSC
+ 1246: PAL I
+ 1256: Pal DK
+ {MF|ME|MP}
+ MF: BG LL w/ Secam (Multi France)
+ ME: BG DK I LL (Multi Europe)
+ MP: BG DK I (Multi PAL)
+ MR: BG DK M (?)
+ MG: BG DKI M (?)
+ MK2 series PHILIPS_API, most tuners are compatible to this one !
+ MK3 series introduced in 2002 w/ PHILIPS_MK3_API
+
+Temic Tuner identification: (.e.g 4006FH5)
+
+.. code-block:: none
+
+ 4[01][0136][269]F[HYNR]5
+ 40x2: Tuner (5V/33V), TEMIC_API.
+ 40x6: Tuner 5V
+ 41xx: Tuner compact
+ 40x9: Tuner+FM compact
+ [0136]
+ xx0x: PAL BG
+ xx1x: Pal DK, Secam LL
+ xx3x: NTSC
+ xx6x: PAL I
+ F[HYNR]5
+ FH5: Pal BG
+ FY5: others
+ FN5: multistandard
+ FR5: w/ FM radio
+ 3X xxxx: order number with specific connector
+ Note: Only 40x2 series has TEMIC_API, all newer tuners have PHILIPS_API.
+
+LG Innotek Tuner:
+
+- TPI8NSR11 : NTSC J/M (TPI8NSR01 w/FM) (P,210/497)
+- TPI8PSB11 : PAL B/G (TPI8PSB01 w/FM) (P,170/450)
+- TAPC-I701 : PAL I (TAPC-I001 w/FM) (P,170/450)
+- TPI8PSB12 : PAL D/K+B/G (TPI8PSB02 w/FM) (P,170/450)
+- TAPC-H701P: NTSC_JP (TAPC-H001P w/FM) (L,170/450)
+- TAPC-G701P: PAL B/G (TAPC-G001P w/FM) (L,170/450)
+- TAPC-W701P: PAL I (TAPC-W001P w/FM) (L,170/450)
+- TAPC-Q703P: PAL D/K (TAPC-Q001P w/FM) (L,170/450)
+- TAPC-Q704P: PAL D/K+I (L,170/450)
+- TAPC-G702P: PAL D/K+B/G (L,170/450)
+
+- TADC-H002F: NTSC (L,175/410?; 2-B, C-W+11, W+12-69)
+- TADC-M201D: PAL D/K+B/G+I (L,143/425) (sound control at I2C address 0xc8)
+- TADC-T003F: NTSC Taiwan (L,175/410?; 2-B, C-W+11, W+12-69)
+
+Suffix:
+ - P= Standard phono female socket
+ - D= IEC female socket
+ - F= F-connector
+
+Other Tuners:
+
+- TCL2002MB-1 : PAL BG + DK =TUNER_LG_PAL_NEW_TAPC
+- TCL2002MB-1F: PAL BG + DK w/FM =PHILIPS_PAL
+- TCL2002MI-2 : PAL I = ??
+
+ALPS Tuners:
+
+- Most are LG_API compatible
+- TSCH6 has ALPS_API (TSCH5 ?)
+- TSBE1 has extra API 05,02,08 Control_byte=0xCB Source:[#f1]_
+
+.. [#f1] conexant100029b-PCI-Decoder-ApplicationNote.pdf
diff --git a/Documentation/driver-api/media/drivers/vidtv.rst b/Documentation/driver-api/media/drivers/vidtv.rst
new file mode 100644
index 000000000000..54f269f478d3
--- /dev/null
+++ b/Documentation/driver-api/media/drivers/vidtv.rst
@@ -0,0 +1,513 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+================================
+vidtv: Virtual Digital TV driver
+================================
+
+Author: Daniel W. S. Almeida <dwlsalmeida@gmail.com>, June 2020.
+
+Background
+----------
+
+Vidtv is a virtual DVB driver that aims to serve as a reference for driver
+writers by serving as a template. It also validates the existing media DVB
+APIs, thus helping userspace application writers.
+
+Currently, it consists of:
+
+- A fake tuner driver, which will report a bad signal quality if the chosen
+ frequency is too far away from a table of valid frequencies for a
+ particular delivery system.
+
+- A fake demod driver, which will constantly poll the fake signal quality
+ returned by the tuner, simulating a device that can lose/reacquire a lock
+ on the signal depending on the CNR levels.
+
+- A fake bridge driver, which is the module responsible for modprobing the
+ fake tuner and demod modules and implementing the demux logic. This module
+ takes parameters at initialization that will dictate how the simulation
+ behaves.
+
+- Code responsible for encoding a valid MPEG Transport Stream, which is then
+ passed to the bridge driver. This fake stream contains some hardcoded content.
+ For now, we have a single, audio-only channel containing a single MPEG
+ Elementary Stream, which in turn contains a SMPTE 302m encoded sine-wave.
+ Note that this particular encoder was chosen because it is the easiest
+ way to encode PCM audio data in a MPEG Transport Stream.
+
+Building vidtv
+--------------
+vidtv is a test driver and thus is **not** enabled by default when
+compiling the kernel.
+
+In order to enable compilation of vidtv:
+
+- Enable **DVB_TEST_DRIVERS**, then
+- Enable **DVB_VIDTV**
+
+When compiled as a module, expect the following .ko files:
+
+- dvb_vidtv_tuner.ko
+
+- dvb_vidtv_demod.ko
+
+- dvb_vidtv_bridge.ko
+
+Running vidtv
+-------------
+When compiled as a module, run::
+
+ modprobe vidtv
+
+That's it! The bridge driver will initialize the tuner and demod drivers as
+part of its own initialization.
+
+By default, it will accept the following frequencies:
+
+ - 474 MHz for DVB-T/T2/C;
+ - 11,362 GHz for DVB-S/S2.
+
+For satellite systems, the driver simulates an universal extended
+LNBf, with frequencies at Ku-Band, ranging from 10.7 GHz to 12.75 GHz.
+
+You can optionally define some command-line arguments to vidtv.
+
+Command-line arguments to vidtv
+-------------------------------
+Below is a list of all arguments that can be supplied to vidtv:
+
+drop_tslock_prob_on_low_snr
+ Probability of losing the TS lock if the signal quality is bad.
+ This probability be used by the fake demodulator driver to
+ eventually return a status of 0 when the signal quality is not
+ good.
+
+recover_tslock_prob_on_good_snr:
+ Probability recovering the TS lock when the signal improves. This
+ probability be used by the fake demodulator driver to eventually
+ return a status of 0x1f when/if the signal quality improves.
+
+mock_power_up_delay_msec
+ Simulate a power up delay. Default: 0.
+
+mock_tune_delay_msec
+ Simulate a tune delay. Default 0.
+
+vidtv_valid_dvb_t_freqs
+ Valid DVB-T frequencies to simulate, in Hz.
+
+vidtv_valid_dvb_c_freqs
+ Valid DVB-C frequencies to simulate, in Hz.
+
+vidtv_valid_dvb_s_freqs
+ Valid DVB-S/S2 frequencies to simulate at Ku-Band, in kHz.
+
+max_frequency_shift_hz,
+ Maximum shift in HZ allowed when tuning in a channel.
+
+si_period_msec
+ How often to send SI packets. Default: 40ms.
+
+pcr_period_msec
+ How often to send PCR packets. Default: 40ms.
+
+mux_rate_kbytes_sec
+ Attempt to maintain this bit rate by inserting TS null packets, if
+ necessary. Default: 4096.
+
+pcr_pid,
+ PCR PID for all channels. Default: 0x200.
+
+mux_buf_sz_pkts,
+ Size for the mux buffer in multiples of 188 bytes.
+
+vidtv internal structure
+------------------------
+The kernel modules are split in the following way:
+
+vidtv_tuner.[ch]
+ Implements a fake tuner DVB driver.
+
+vidtv_demod.[ch]
+ Implements a fake demodulator DVB driver.
+
+vidtv_bridge.[ch]
+ Implements a bridge driver.
+
+The MPEG related code is split in the following way:
+
+vidtv_ts.[ch]
+ Code to work with MPEG TS packets, such as TS headers, adaptation
+ fields, PCR packets and NULL packets.
+
+vidtv_psi.[ch]
+ This is the PSI generator. PSI packets contain general information
+ about a MPEG Transport Stream. A PSI generator is needed so
+ userspace apps can retrieve information about the Transport Stream
+ and eventually tune into a (dummy) channel.
+
+ Because the generator is implemented in a separate file, it can be
+ reused elsewhere in the media subsystem.
+
+ Currently vidtv supports working with 5 PSI tables: PAT, PMT,
+ SDT, NIT and EIT.
+
+ The specification for PAT and PMT can be found in *ISO 13818-1:
+ Systems*, while the specification for the SDT, NIT, EIT can be found in *ETSI
+ EN 300 468: Specification for Service Information (SI) in DVB
+ systems*.
+
+ It isn't strictly necessary, but using a real TS file helps when
+ debugging PSI tables. Vidtv currently tries to replicate the PSI
+ structure found in this file: `TS1Globo.ts
+ <https://tsduck.io/streams/brazil-isdb-tb/TS1globo.ts>`_.
+
+ A good way to visualize the structure of streams is by using
+ `DVBInspector <https://sourceforge.net/projects/dvbinspector/>`_.
+
+vidtv_pes.[ch]
+ Implements the PES logic to convert encoder data into MPEG TS
+ packets. These can then be fed into a TS multiplexer and eventually
+ into userspace.
+
+vidtv_encoder.h
+ An interface for vidtv encoders. New encoders can be added to this
+ driver by implementing the calls in this file.
+
+vidtv_s302m.[ch]
+ Implements a S302M encoder to make it possible to insert PCM audio
+ data in the generated MPEG Transport Stream. The relevant
+ specification is available online as *SMPTE 302M-2007: Television -
+ Mapping of AES3 Data into MPEG-2 Transport Stream*.
+
+
+ The resulting MPEG Elementary Stream is conveyed in a private
+ stream with a S302M registration descriptor attached.
+
+ This shall enable passing an audio signal into userspace so it can
+ be decoded and played by media software. The corresponding decoder
+ in ffmpeg is located in 'libavcodec/s302m.c' and is experimental.
+
+vidtv_channel.[ch]
+ Implements a 'channel' abstraction.
+
+ When vidtv boots, it will create some hardcoded channels:
+
+ #. Their services will be concatenated to populate the SDT.
+
+ #. Their programs will be concatenated to populate the PAT
+
+ #. Their events will be concatenated to populate the EIT
+
+ #. For each program in the PAT, a PMT section will be created
+
+ #. The PMT section for a channel will be assigned its streams.
+
+ #. Every stream will have its corresponding encoder polled in a
+ loop to produce TS packets.
+ These packets may be interleaved by the muxer and then delivered
+ to the bridge.
+
+vidtv_mux.[ch]
+ Implements a MPEG TS mux, loosely based on the ffmpeg
+ implementation in "libavcodec/mpegtsenc.c"
+
+ The muxer runs a loop which is responsible for:
+
+ #. Keeping track of the amount of time elapsed since the last
+ iteration.
+
+ #. Polling encoders in order to fetch 'elapsed_time' worth of data.
+
+ #. Inserting PSI and/or PCR packets, if needed.
+
+ #. Padding the resulting stream with NULL packets if
+ necessary in order to maintain the chosen bit rate.
+
+ #. Delivering the resulting TS packets to the bridge
+ driver so it can pass them to the demux.
+
+Testing vidtv with v4l-utils
+----------------------------
+
+Using the tools in v4l-utils is a great way to test and inspect the output of
+vidtv. It is hosted here: `v4l-utils Documentation
+<https://linuxtv.org/wiki/index.php/V4l-utils>`_.
+
+From its webpage::
+
+ The v4l-utils are a series of packages for handling media devices.
+
+ It is hosted at http://git.linuxtv.org/v4l-utils.git, and packaged
+ on most distributions.
+
+ It provides a series of libraries and utilities to be used to
+ control several aspect of the media boards.
+
+
+Start by installing v4l-utils and then modprobing vidtv::
+
+ modprobe dvb_vidtv_bridge
+
+If the driver is OK, it should load and its probing code will run. This will
+pull in the tuner and demod drivers.
+
+Using dvb-fe-tool
+~~~~~~~~~~~~~~~~~
+
+The first step to check whether the demod loaded successfully is to run::
+
+ $ dvb-fe-tool
+ Device Dummy demod for DVB-T/T2/C/S/S2 (/dev/dvb/adapter0/frontend0) capabilities:
+ CAN_FEC_1_2
+ CAN_FEC_2_3
+ CAN_FEC_3_4
+ CAN_FEC_4_5
+ CAN_FEC_5_6
+ CAN_FEC_6_7
+ CAN_FEC_7_8
+ CAN_FEC_8_9
+ CAN_FEC_AUTO
+ CAN_GUARD_INTERVAL_AUTO
+ CAN_HIERARCHY_AUTO
+ CAN_INVERSION_AUTO
+ CAN_QAM_16
+ CAN_QAM_32
+ CAN_QAM_64
+ CAN_QAM_128
+ CAN_QAM_256
+ CAN_QAM_AUTO
+ CAN_QPSK
+ CAN_TRANSMISSION_MODE_AUTO
+ DVB API Version 5.11, Current v5 delivery system: DVBC/ANNEX_A
+ Supported delivery systems:
+ DVBT
+ DVBT2
+ [DVBC/ANNEX_A]
+ DVBS
+ DVBS2
+ Frequency range for the current standard:
+ From: 51.0 MHz
+ To: 2.15 GHz
+ Step: 62.5 kHz
+ Tolerance: 29.5 MHz
+ Symbol rate ranges for the current standard:
+ From: 1.00 MBauds
+ To: 45.0 MBauds
+
+This should return what is currently set up at the demod struct, i.e.::
+
+ static const struct dvb_frontend_ops vidtv_demod_ops = {
+ .delsys = {
+ SYS_DVBT,
+ SYS_DVBT2,
+ SYS_DVBC_ANNEX_A,
+ SYS_DVBS,
+ SYS_DVBS2,
+ },
+
+ .info = {
+ .name = "Dummy demod for DVB-T/T2/C/S/S2",
+ .frequency_min_hz = 51 * MHz,
+ .frequency_max_hz = 2150 * MHz,
+ .frequency_stepsize_hz = 62500,
+ .frequency_tolerance_hz = 29500 * kHz,
+ .symbol_rate_min = 1000000,
+ .symbol_rate_max = 45000000,
+
+ .caps = FE_CAN_FEC_1_2 |
+ FE_CAN_FEC_2_3 |
+ FE_CAN_FEC_3_4 |
+ FE_CAN_FEC_4_5 |
+ FE_CAN_FEC_5_6 |
+ FE_CAN_FEC_6_7 |
+ FE_CAN_FEC_7_8 |
+ FE_CAN_FEC_8_9 |
+ FE_CAN_QAM_16 |
+ FE_CAN_QAM_64 |
+ FE_CAN_QAM_32 |
+ FE_CAN_QAM_128 |
+ FE_CAN_QAM_256 |
+ FE_CAN_QAM_AUTO |
+ FE_CAN_QPSK |
+ FE_CAN_FEC_AUTO |
+ FE_CAN_INVERSION_AUTO |
+ FE_CAN_TRANSMISSION_MODE_AUTO |
+ FE_CAN_GUARD_INTERVAL_AUTO |
+ FE_CAN_HIERARCHY_AUTO,
+ }
+
+ ....
+
+For more information on dvb-fe-tools check its online documentation here:
+`dvb-fe-tool Documentation
+<https://www.linuxtv.org/wiki/index.php/Dvb-fe-tool>`_.
+
+Using dvb-scan
+~~~~~~~~~~~~~~
+
+In order to tune into a channel and read the PSI tables, we can use dvb-scan.
+
+For this, one should provide a configuration file known as a 'scan file',
+here's an example::
+
+ [Channel]
+ FREQUENCY = 474000000
+ MODULATION = QAM/AUTO
+ SYMBOL_RATE = 6940000
+ INNER_FEC = AUTO
+ DELIVERY_SYSTEM = DVBC/ANNEX_A
+
+.. note::
+ The parameters depend on the video standard you're testing.
+
+.. note::
+ Vidtv is a fake driver and does not validate much of the information
+ in the scan file. Just specifying 'FREQUENCY' and 'DELIVERY_SYSTEM'
+ should be enough for DVB-T/DVB-T2. For DVB-S/DVB-C however, you
+ should also provide 'SYMBOL_RATE'.
+
+You can browse scan tables online here: `dvb-scan-tables
+<https://git.linuxtv.org/dtv-scan-tables.git>`_.
+
+Assuming this channel is named 'channel.conf', you can then run::
+
+ $ dvbv5-scan channel.conf
+ dvbv5-scan ~/vidtv.conf
+ ERROR command BANDWIDTH_HZ (5) not found during retrieve
+ Cannot calc frequency shift. Either bandwidth/symbol-rate is unavailable (yet).
+ Scanning frequency #1 330000000
+ (0x00) Signal= -68.00dBm
+ Scanning frequency #2 474000000
+ Lock (0x1f) Signal= -34.45dBm C/N= 33.74dB UCB= 0
+ Service Beethoven, provider LinuxTV.org: digital television
+
+For more information on dvb-scan, check its documentation online here:
+`dvb-scan Documentation <https://www.linuxtv.org/wiki/index.php/Dvbscan>`_.
+
+Using dvb-zap
+~~~~~~~~~~~~~
+
+dvbv5-zap is a command line tool that can be used to record MPEG-TS to disk. The
+typical use is to tune into a channel and put it into record mode. The example
+below - which is taken from the documentation - illustrates that\ [1]_::
+
+ $ dvbv5-zap -c dvb_channel.conf "beethoven" -o music.ts -P -t 10
+ using demux 'dvb0.demux0'
+ reading channels from file 'dvb_channel.conf'
+ tuning to 474000000 Hz
+ pass all PID's to TS
+ dvb_set_pesfilter 8192
+ dvb_dev_set_bufsize: buffer set to 6160384
+ Lock (0x1f) Quality= Good Signal= -34.66dBm C/N= 33.41dB UCB= 0 postBER= 0 preBER= 1.05x10^-3 PER= 0
+ Lock (0x1f) Quality= Good Signal= -34.57dBm C/N= 33.46dB UCB= 0 postBER= 0 preBER= 1.05x10^-3 PER= 0
+ Record to file 'music.ts' started
+ received 24587768 bytes (2401 Kbytes/sec)
+ Lock (0x1f) Quality= Good Signal= -34.42dBm C/N= 33.89dB UCB= 0 postBER= 0 preBER= 2.44x10^-3 PER= 0
+
+.. [1] In this example, it records 10 seconds with all program ID's stored
+ at the music.ts file.
+
+
+The channel can be watched by playing the contents of the stream with some
+player that recognizes the MPEG-TS format, such as ``mplayer`` or ``vlc``.
+
+By playing the contents of the stream one can visually inspect the workings of
+vidtv, e.g., to play a recorded TS file with::
+
+ $ mplayer music.ts
+
+or, alternatively, running this command on one terminal::
+
+ $ dvbv5-zap -c dvb_channel.conf "beethoven" -P -r &
+
+And, on a second terminal, playing the contents from DVR interface with::
+
+ $ mplayer /dev/dvb/adapter0/dvr0
+
+For more information on dvb-zap check its online documentation here:
+`dvb-zap Documentation
+<https://www.linuxtv.org/wiki/index.php/Dvbv5-zap>`_.
+See also: `zap <https://www.linuxtv.org/wiki/index.php/Zap>`_.
+
+
+What can still be improved in vidtv
+-----------------------------------
+
+Add *debugfs* integration
+~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Although frontend drivers provide DVBv5 statistics via the .read_status
+call, a nice addition would be to make additional statistics available to
+userspace via debugfs, which is a simple-to-use, RAM-based filesystem
+specifically designed for debug purposes.
+
+The logic for this would be implemented on a separate file so as not to
+pollute the frontend driver. These statistics are driver-specific and can
+be useful during tests.
+
+The Siano driver is one example of a driver using
+debugfs to convey driver-specific statistics to userspace and it can be
+used as a reference.
+
+This should be further enabled and disabled via a Kconfig
+option for convenience.
+
+Add a way to test video
+~~~~~~~~~~~~~~~~~~~~~~~
+
+Currently, vidtv can only encode PCM audio. It would be great to implement
+a barebones version of MPEG-2 video encoding so we can also test video. The
+first place to look into is *ISO 13818-2: Information technology — Generic
+coding of moving pictures and associated audio information — Part 2: Video*,
+which covers the encoding of compressed video in MPEG Transport Streams.
+
+This might optionally use the Video4Linux2 Test Pattern Generator, v4l2-tpg,
+which resides at::
+
+ drivers/media/common/v4l2-tpg/
+
+
+Add white noise simulation
+~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+The vidtv tuner already has code to identify whether the chosen frequency
+is too far away from a table of valid frequencies. For now, this means that
+the demodulator can eventually lose the lock on the signal, since the tuner will
+report a bad signal quality.
+
+A nice addition is to simulate some noise when the signal quality is bad by:
+
+- Randomly dropping some TS packets. This will trigger a continuity error if the
+ continuity counter is updated but the packet is not passed on to the demux.
+
+- Updating the error statistics accordingly (e.g. BER, etc).
+
+- Simulating some noise in the encoded data.
+
+Functions and structs used within vidtv
+---------------------------------------
+
+.. kernel-doc:: drivers/media/test-drivers/vidtv/vidtv_bridge.h
+
+.. kernel-doc:: drivers/media/test-drivers/vidtv/vidtv_channel.h
+
+.. kernel-doc:: drivers/media/test-drivers/vidtv/vidtv_demod.h
+
+.. kernel-doc:: drivers/media/test-drivers/vidtv/vidtv_encoder.h
+
+.. kernel-doc:: drivers/media/test-drivers/vidtv/vidtv_mux.h
+
+.. kernel-doc:: drivers/media/test-drivers/vidtv/vidtv_pes.h
+
+.. kernel-doc:: drivers/media/test-drivers/vidtv/vidtv_psi.h
+
+.. kernel-doc:: drivers/media/test-drivers/vidtv/vidtv_s302m.h
+
+.. kernel-doc:: drivers/media/test-drivers/vidtv/vidtv_ts.h
+
+.. kernel-doc:: drivers/media/test-drivers/vidtv/vidtv_tuner.h
+
+.. kernel-doc:: drivers/media/test-drivers/vidtv/vidtv_common.c
+
+.. kernel-doc:: drivers/media/test-drivers/vidtv/vidtv_tuner.c
diff --git a/Documentation/driver-api/media/drivers/vimc-devel.rst b/Documentation/driver-api/media/drivers/vimc-devel.rst
new file mode 100644
index 000000000000..9e984f914b13
--- /dev/null
+++ b/Documentation/driver-api/media/drivers/vimc-devel.rst
@@ -0,0 +1,15 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+The Virtual Media Controller Driver (vimc)
+==========================================
+
+Source code documentation
+-------------------------
+
+vimc-streamer
+~~~~~~~~~~~~~
+
+.. kernel-doc:: drivers/media/test-drivers/vimc/vimc-streamer.h
+ :internal:
+
+.. kernel-doc:: drivers/media/test-drivers/vimc/vimc-streamer.c
diff --git a/Documentation/driver-api/media/drivers/zoran.rst b/Documentation/driver-api/media/drivers/zoran.rst
new file mode 100644
index 000000000000..b205e10c3154
--- /dev/null
+++ b/Documentation/driver-api/media/drivers/zoran.rst
@@ -0,0 +1,575 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+The Zoran driver
+================
+
+unified zoran driver (zr360x7, zoran, buz, dc10(+), dc30(+), lml33)
+
+website: http://mjpeg.sourceforge.net/driver-zoran/
+
+
+Frequently Asked Questions
+--------------------------
+
+What cards are supported
+------------------------
+
+Iomega Buz, Linux Media Labs LML33/LML33R10, Pinnacle/Miro
+DC10/DC10+/DC30/DC30+ and related boards (available under various names).
+
+Iomega Buz
+~~~~~~~~~~
+
+* Zoran zr36067 PCI controller
+* Zoran zr36060 MJPEG codec
+* Philips saa7111 TV decoder
+* Philips saa7185 TV encoder
+
+Drivers to use: videodev, i2c-core, i2c-algo-bit,
+videocodec, saa7111, saa7185, zr36060, zr36067
+
+Inputs/outputs: Composite and S-video
+
+Norms: PAL, SECAM (720x576 @ 25 fps), NTSC (720x480 @ 29.97 fps)
+
+Card number: 7
+
+AverMedia 6 Eyes AVS6EYES
+~~~~~~~~~~~~~~~~~~~~~~~~~
+
+* Zoran zr36067 PCI controller
+* Zoran zr36060 MJPEG codec
+* Samsung ks0127 TV decoder
+* Conexant bt866 TV encoder
+
+Drivers to use: videodev, i2c-core, i2c-algo-bit,
+videocodec, ks0127, bt866, zr36060, zr36067
+
+Inputs/outputs:
+ Six physical inputs. 1-6 are composite,
+ 1-2, 3-4, 5-6 doubles as S-video,
+ 1-3 triples as component.
+ One composite output.
+
+Norms: PAL, SECAM (720x576 @ 25 fps), NTSC (720x480 @ 29.97 fps)
+
+Card number: 8
+
+.. note::
+
+ Not autodetected, card=8 is necessary.
+
+Linux Media Labs LML33
+~~~~~~~~~~~~~~~~~~~~~~
+
+* Zoran zr36067 PCI controller
+* Zoran zr36060 MJPEG codec
+* Brooktree bt819 TV decoder
+* Brooktree bt856 TV encoder
+
+Drivers to use: videodev, i2c-core, i2c-algo-bit,
+videocodec, bt819, bt856, zr36060, zr36067
+
+Inputs/outputs: Composite and S-video
+
+Norms: PAL (720x576 @ 25 fps), NTSC (720x480 @ 29.97 fps)
+
+Card number: 5
+
+Linux Media Labs LML33R10
+~~~~~~~~~~~~~~~~~~~~~~~~~
+
+* Zoran zr36067 PCI controller
+* Zoran zr36060 MJPEG codec
+* Philips saa7114 TV decoder
+* Analog Devices adv7170 TV encoder
+
+Drivers to use: videodev, i2c-core, i2c-algo-bit,
+videocodec, saa7114, adv7170, zr36060, zr36067
+
+Inputs/outputs: Composite and S-video
+
+Norms: PAL (720x576 @ 25 fps), NTSC (720x480 @ 29.97 fps)
+
+Card number: 6
+
+Pinnacle/Miro DC10(new)
+~~~~~~~~~~~~~~~~~~~~~~~
+
+* Zoran zr36057 PCI controller
+* Zoran zr36060 MJPEG codec
+* Philips saa7110a TV decoder
+* Analog Devices adv7176 TV encoder
+
+Drivers to use: videodev, i2c-core, i2c-algo-bit,
+videocodec, saa7110, adv7175, zr36060, zr36067
+
+Inputs/outputs: Composite, S-video and Internal
+
+Norms: PAL, SECAM (768x576 @ 25 fps), NTSC (640x480 @ 29.97 fps)
+
+Card number: 1
+
+Pinnacle/Miro DC10+
+~~~~~~~~~~~~~~~~~~~
+
+* Zoran zr36067 PCI controller
+* Zoran zr36060 MJPEG codec
+* Philips saa7110a TV decoder
+* Analog Devices adv7176 TV encoder
+
+Drivers to use: videodev, i2c-core, i2c-algo-bit,
+videocodec, saa7110, adv7175, zr36060, zr36067
+
+Inputs/outputs: Composite, S-video and Internal
+
+Norms: PAL, SECAM (768x576 @ 25 fps), NTSC (640x480 @ 29.97 fps)
+
+Card number: 2
+
+Pinnacle/Miro DC10(old)
+~~~~~~~~~~~~~~~~~~~~~~~
+
+* Zoran zr36057 PCI controller
+* Zoran zr36050 MJPEG codec
+* Zoran zr36016 Video Front End or Fuji md0211 Video Front End (clone?)
+* Micronas vpx3220a TV decoder
+* mse3000 TV encoder or Analog Devices adv7176 TV encoder
+
+Drivers to use: videodev, i2c-core, i2c-algo-bit,
+videocodec, vpx3220, mse3000/adv7175, zr36050, zr36016, zr36067
+
+Inputs/outputs: Composite, S-video and Internal
+
+Norms: PAL, SECAM (768x576 @ 25 fps), NTSC (640x480 @ 29.97 fps)
+
+Card number: 0
+
+Pinnacle/Miro DC30
+~~~~~~~~~~~~~~~~~~
+
+* Zoran zr36057 PCI controller
+* Zoran zr36050 MJPEG codec
+* Zoran zr36016 Video Front End
+* Micronas vpx3225d/vpx3220a/vpx3216b TV decoder
+* Analog Devices adv7176 TV encoder
+
+Drivers to use: videodev, i2c-core, i2c-algo-bit,
+videocodec, vpx3220/vpx3224, adv7175, zr36050, zr36016, zr36067
+
+Inputs/outputs: Composite, S-video and Internal
+
+Norms: PAL, SECAM (768x576 @ 25 fps), NTSC (640x480 @ 29.97 fps)
+
+Card number: 3
+
+Pinnacle/Miro DC30+
+~~~~~~~~~~~~~~~~~~~
+
+* Zoran zr36067 PCI controller
+* Zoran zr36050 MJPEG codec
+* Zoran zr36016 Video Front End
+* Micronas vpx3225d/vpx3220a/vpx3216b TV decoder
+* Analog Devices adv7176 TV encoder
+
+Drivers to use: videodev, i2c-core, i2c-algo-bit,
+videocodec, vpx3220/vpx3224, adv7175, zr36050, zr36015, zr36067
+
+Inputs/outputs: Composite, S-video and Internal
+
+Norms: PAL, SECAM (768x576 @ 25 fps), NTSC (640x480 @ 29.97 fps)
+
+Card number: 4
+
+.. note::
+
+ #) No module for the mse3000 is available yet
+ #) No module for the vpx3224 is available yet
+
+1.1 What the TV decoder can do an what not
+------------------------------------------
+
+The best know TV standards are NTSC/PAL/SECAM. but for decoding a frame that
+information is not enough. There are several formats of the TV standards.
+And not every TV decoder is able to handle every format. Also the every
+combination is supported by the driver. There are currently 11 different
+tv broadcast formats all aver the world.
+
+The CCIR defines parameters needed for broadcasting the signal.
+The CCIR has defined different standards: A,B,D,E,F,G,D,H,I,K,K1,L,M,N,...
+The CCIR says not much about the colorsystem used !!!
+And talking about a colorsystem says not to much about how it is broadcast.
+
+The CCIR standards A,E,F are not used any more.
+
+When you speak about NTSC, you usually mean the standard: CCIR - M using
+the NTSC colorsystem which is used in the USA, Japan, Mexico, Canada
+and a few others.
+
+When you talk about PAL, you usually mean: CCIR - B/G using the PAL
+colorsystem which is used in many Countries.
+
+When you talk about SECAM, you mean: CCIR - L using the SECAM Colorsystem
+which is used in France, and a few others.
+
+There the other version of SECAM, CCIR - D/K is used in Bulgaria, China,
+Slovakai, Hungary, Korea (Rep.), Poland, Rumania and a others.
+
+The CCIR - H uses the PAL colorsystem (sometimes SECAM) and is used in
+Egypt, Libya, Sri Lanka, Syrain Arab. Rep.
+
+The CCIR - I uses the PAL colorsystem, and is used in Great Britain, Hong Kong,
+Ireland, Nigeria, South Africa.
+
+The CCIR - N uses the PAL colorsystem and PAL frame size but the NTSC framerate,
+and is used in Argentinia, Uruguay, an a few others
+
+We do not talk about how the audio is broadcast !
+
+A rather good sites about the TV standards are:
+http://www.sony.jp/support/
+http://info.electronicwerkstatt.de/bereiche/fernsehtechnik/frequenzen_und_normen/Fernsehnormen/
+and http://www.cabl.com/restaurant/channel.html
+
+Other weird things around: NTSC 4.43 is a modificated NTSC, which is mainly
+used in PAL VCR's that are able to play back NTSC. PAL 60 seems to be the same
+as NTSC 4.43 . The Datasheets also talk about NTSC 44, It seems as if it would
+be the same as NTSC 4.43.
+NTSC Combs seems to be a decoder mode where the decoder uses a comb filter
+to split coma and luma instead of a Delay line.
+
+But I did not defiantly find out what NTSC Comb is.
+
+Philips saa7111 TV decoder
+~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+- was introduced in 1997, is used in the BUZ and
+- can handle: PAL B/G/H/I, PAL N, PAL M, NTSC M, NTSC N, NTSC 4.43 and SECAM
+
+Philips saa7110a TV decoder
+~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+- was introduced in 1995, is used in the Pinnacle/Miro DC10(new), DC10+ and
+- can handle: PAL B/G, NTSC M and SECAM
+
+Philips saa7114 TV decoder
+~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+- was introduced in 2000, is used in the LML33R10 and
+- can handle: PAL B/G/D/H/I/N, PAL N, PAL M, NTSC M, NTSC 4.43 and SECAM
+
+Brooktree bt819 TV decoder
+~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+- was introduced in 1996, and is used in the LML33 and
+- can handle: PAL B/D/G/H/I, NTSC M
+
+Micronas vpx3220a TV decoder
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+- was introduced in 1996, is used in the DC30 and DC30+ and
+- can handle: PAL B/G/H/I, PAL N, PAL M, NTSC M, NTSC 44, PAL 60, SECAM,NTSC Comb
+
+Samsung ks0127 TV decoder
+~~~~~~~~~~~~~~~~~~~~~~~~~
+
+- is used in the AVS6EYES card and
+- can handle: NTSC-M/N/44, PAL-M/N/B/G/H/I/D/K/L and SECAM
+
+
+What the TV encoder can do an what not
+--------------------------------------
+
+The TV encoder is doing the "same" as the decoder, but in the other direction.
+You feed them digital data and the generate a Composite or SVHS signal.
+For information about the colorsystems and TV norm take a look in the
+TV decoder section.
+
+Philips saa7185 TV Encoder
+~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+- was introduced in 1996, is used in the BUZ
+- can generate: PAL B/G, NTSC M
+
+Brooktree bt856 TV Encoder
+~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+- was introduced in 1994, is used in the LML33
+- can generate: PAL B/D/G/H/I/N, PAL M, NTSC M, PAL-N (Argentina)
+
+Analog Devices adv7170 TV Encoder
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+- was introduced in 2000, is used in the LML300R10
+- can generate: PAL B/D/G/H/I/N, PAL M, NTSC M, PAL 60
+
+Analog Devices adv7175 TV Encoder
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+- was introduced in 1996, is used in the DC10, DC10+, DC10 old, DC30, DC30+
+- can generate: PAL B/D/G/H/I/N, PAL M, NTSC M
+
+ITT mse3000 TV encoder
+~~~~~~~~~~~~~~~~~~~~~~
+
+- was introduced in 1991, is used in the DC10 old
+- can generate: PAL , NTSC , SECAM
+
+Conexant bt866 TV encoder
+~~~~~~~~~~~~~~~~~~~~~~~~~
+
+- is used in AVS6EYES, and
+- can generate: NTSC/PAL, PAL-M, PAL-N
+
+The adv717x, should be able to produce PAL N. But you find nothing PAL N
+specific in the registers. Seem that you have to reuse a other standard
+to generate PAL N, maybe it would work if you use the PAL M settings.
+
+How do I get this damn thing to work
+------------------------------------
+
+Load zr36067.o. If it can't autodetect your card, use the card=X insmod
+option with X being the card number as given in the previous section.
+To have more than one card, use card=X1[,X2[,X3,[X4[..]]]]
+
+To automate this, add the following to your /etc/modprobe.d/zoran.conf:
+
+options zr36067 card=X1[,X2[,X3[,X4[..]]]]
+alias char-major-81-0 zr36067
+
+One thing to keep in mind is that this doesn't load zr36067.o itself yet. It
+just automates loading. If you start using xawtv, the device won't load on
+some systems, since you're trying to load modules as a user, which is not
+allowed ("permission denied"). A quick workaround is to add 'Load "v4l"' to
+XF86Config-4 when you use X by default, or to run 'v4l-conf -c <device>' in
+one of your startup scripts (normally rc.local) if you don't use X. Both
+make sure that the modules are loaded on startup, under the root account.
+
+What mainboard should I use (or why doesn't my card work)
+---------------------------------------------------------
+
+
+<insert lousy disclaimer here>. In short: good=SiS/Intel, bad=VIA.
+
+Experience tells us that people with a Buz, on average, have more problems
+than users with a DC10+/LML33. Also, it tells us that people owning a VIA-
+based mainboard (ktXXX, MVP3) have more problems than users with a mainboard
+based on a different chipset. Here's some notes from Andrew Stevens:
+
+Here's my experience of using LML33 and Buz on various motherboards:
+
+- VIA MVP3
+ - Forget it. Pointless. Doesn't work.
+- Intel 430FX (Pentium 200)
+ - LML33 perfect, Buz tolerable (3 or 4 frames dropped per movie)
+- Intel 440BX (early stepping)
+ - LML33 tolerable. Buz starting to get annoying (6-10 frames/hour)
+- Intel 440BX (late stepping)
+ - Buz tolerable, LML3 almost perfect (occasional single frame drops)
+- SiS735
+ - LML33 perfect, Buz tolerable.
+- VIA KT133(*)
+ - LML33 starting to get annoying, Buz poor enough that I have up.
+
+- Both 440BX boards were dual CPU versions.
+
+Bernhard Praschinger later added:
+
+- AMD 751
+ - Buz perfect-tolerable
+- AMD 760
+ - Buz perfect-tolerable
+
+In general, people on the user mailinglist won't give you much of a chance
+if you have a VIA-based motherboard. They may be cheap, but sometimes, you'd
+rather want to spend some more money on better boards. In general, VIA
+mainboard's IDE/PCI performance will also suck badly compared to others.
+You'll noticed the DC10+/DC30+ aren't mentioned anywhere in the overview.
+Basically, you can assume that if the Buz works, the LML33 will work too. If
+the LML33 works, the DC10+/DC30+ will work too. They're most tolerant to
+different mainboard chipsets from all of the supported cards.
+
+If you experience timeouts during capture, buy a better mainboard or lower
+the quality/buffersize during capture (see 'Concerning buffer sizes, quality,
+output size etc.'). If it hangs, there's little we can do as of now. Check
+your IRQs and make sure the card has its own interrupts.
+
+Programming interface
+---------------------
+
+This driver conforms to video4linux2. Support for V4L1 and for the custom
+zoran ioctls has been removed in kernel 2.6.38.
+
+For programming example, please, look at lavrec.c and lavplay.c code in
+the MJPEG-tools (http://mjpeg.sf.net/).
+
+Additional notes for software developers:
+
+ The driver returns maxwidth and maxheight parameters according to
+ the current TV standard (norm). Therefore, the software which
+ communicates with the driver and "asks" for these parameters should
+ first set the correct norm. Well, it seems logically correct: TV
+ standard is "more constant" for current country than geometry
+ settings of a variety of TV capture cards which may work in ITU or
+ square pixel format.
+
+Applications
+------------
+
+Applications known to work with this driver:
+
+TV viewing:
+
+* xawtv
+* kwintv
+* probably any TV application that supports video4linux or video4linux2.
+
+MJPEG capture/playback:
+
+* mjpegtools/lavtools (or Linux Video Studio)
+* gstreamer
+* mplayer
+
+General raw capture:
+
+* xawtv
+* gstreamer
+* probably any application that supports video4linux or video4linux2
+
+Video editing:
+
+* Cinelerra
+* MainActor
+* mjpegtools (or Linux Video Studio)
+
+
+Concerning buffer sizes, quality, output size etc.
+--------------------------------------------------
+
+
+The zr36060 can do 1:2 JPEG compression. This is really the theoretical
+maximum that the chipset can reach. The driver can, however, limit compression
+to a maximum (size) of 1:4. The reason for this is that some cards (e.g. Buz)
+can't handle 1:2 compression without stopping capture after only a few minutes.
+With 1:4, it'll mostly work. If you have a Buz, use 'low_bitrate=1' to go into
+1:4 max. compression mode.
+
+100% JPEG quality is thus 1:2 compression in practice. So for a full PAL frame
+(size 720x576). The JPEG fields are stored in YUY2 format, so the size of the
+fields are 720x288x16/2 bits/field (2 fields/frame) = 207360 bytes/field x 2 =
+414720 bytes/frame (add some more bytes for headers and DHT (huffman)/DQT
+(quantization) tables, and you'll get to something like 512kB per frame for
+1:2 compression. For 1:4 compression, you'd have frames of half this size.
+
+Some additional explanation by Martin Samuelsson, which also explains the
+importance of buffer sizes:
+--
+> Hmm, I do not think it is really that way. With the current (downloaded
+> at 18:00 Monday) driver I get that output sizes for 10 sec:
+> -q 50 -b 128 : 24.283.332 Bytes
+> -q 50 -b 256 : 48.442.368
+> -q 25 -b 128 : 24.655.992
+> -q 25 -b 256 : 25.859.820
+
+I woke up, and can't go to sleep again. I'll kill some time explaining why
+this doesn't look strange to me.
+
+Let's do some math using a width of 704 pixels. I'm not sure whether the Buz
+actually use that number or not, but that's not too important right now.
+
+704x288 pixels, one field, is 202752 pixels. Divided by 64 pixels per block;
+3168 blocks per field. Each pixel consist of two bytes; 128 bytes per block;
+1024 bits per block. 100% in the new driver mean 1:2 compression; the maximum
+output becomes 512 bits per block. Actually 510, but 512 is simpler to use
+for calculations.
+
+Let's say that we specify d1q50. We thus want 256 bits per block; times 3168
+becomes 811008 bits; 101376 bytes per field. We're talking raw bits and bytes
+here, so we don't need to do any fancy corrections for bits-per-pixel or such
+things. 101376 bytes per field.
+
+d1 video contains two fields per frame. Those sum up to 202752 bytes per
+frame, and one of those frames goes into each buffer.
+
+But wait a second! -b128 gives 128kB buffers! It's not possible to cram
+202752 bytes of JPEG data into 128kB!
+
+This is what the driver notice and automatically compensate for in your
+examples. Let's do some math using this information:
+
+128kB is 131072 bytes. In this buffer, we want to store two fields, which
+leaves 65536 bytes for each field. Using 3168 blocks per field, we get
+20.68686868... available bytes per block; 165 bits. We can't allow the
+request for 256 bits per block when there's only 165 bits available! The -q50
+option is silently overridden, and the -b128 option takes precedence, leaving
+us with the equivalence of -q32.
+
+This gives us a data rate of 165 bits per block, which, times 3168, sums up
+to 65340 bytes per field, out of the allowed 65536. The current driver has
+another level of rate limiting; it won't accept -q values that fill more than
+6/8 of the specified buffers. (I'm not sure why. "Playing it safe" seem to be
+a safe bet. Personally, I think I would have lowered requested-bits-per-block
+by one, or something like that.) We can't use 165 bits per block, but have to
+lower it again, to 6/8 of the available buffer space: We end up with 124 bits
+per block, the equivalence of -q24. With 128kB buffers, you can't use greater
+than -q24 at -d1. (And PAL, and 704 pixels width...)
+
+The third example is limited to -q24 through the same process. The second
+example, using very similar calculations, is limited to -q48. The only
+example that actually grab at the specified -q value is the last one, which
+is clearly visible, looking at the file size.
+--
+
+Conclusion: the quality of the resulting movie depends on buffer size, quality,
+whether or not you use 'low_bitrate=1' as insmod option for the zr36060.c
+module to do 1:4 instead of 1:2 compression, etc.
+
+If you experience timeouts, lowering the quality/buffersize or using
+'low_bitrate=1 as insmod option for zr36060.o might actually help, as is
+proven by the Buz.
+
+It hangs/crashes/fails/whatevers! Help!
+---------------------------------------
+
+Make sure that the card has its own interrupts (see /proc/interrupts), check
+the output of dmesg at high verbosity (load zr36067.o with debug=2,
+load all other modules with debug=1). Check that your mainboard is favorable
+(see question 2) and if not, test the card in another computer. Also see the
+notes given in question 3 and try lowering quality/buffersize/capturesize
+if recording fails after a period of time.
+
+If all this doesn't help, give a clear description of the problem including
+detailed hardware information (memory+brand, mainboard+chipset+brand, which
+MJPEG card, processor, other PCI cards that might be of interest), give the
+system PnP information (/proc/interrupts, /proc/dma, /proc/devices), and give
+the kernel version, driver version, glibc version, gcc version and any other
+information that might possibly be of interest. Also provide the dmesg output
+at high verbosity. See 'Contacting' on how to contact the developers.
+
+Maintainers/Contacting
+----------------------
+
+Previous maintainers/developers of this driver are
+- Laurent Pinchart <laurent.pinchart@skynet.be>
+- Ronald Bultje rbultje@ronald.bitfreak.net
+- Serguei Miridonov <mirsev@cicese.mx>
+- Wolfgang Scherr <scherr@net4you.net>
+- Dave Perks <dperks@ibm.net>
+- Rainer Johanni <Rainer@Johanni.de>
+
+Driver's License
+----------------
+
+ This driver is distributed under the terms of the General Public License.
+
+ 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.
+
+See http://www.gnu.org/ for more information.
diff --git a/Documentation/driver-api/media/dtv-ca.rst b/Documentation/driver-api/media/dtv-ca.rst
new file mode 100644
index 000000000000..8a09862b428b
--- /dev/null
+++ b/Documentation/driver-api/media/dtv-ca.rst
@@ -0,0 +1,6 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+Digital TV Conditional Access kABI
+----------------------------------
+
+.. kernel-doc:: include/media/dvb_ca_en50221.h
diff --git a/Documentation/driver-api/media/dtv-common.rst b/Documentation/driver-api/media/dtv-common.rst
new file mode 100644
index 000000000000..207a22bcaf4a
--- /dev/null
+++ b/Documentation/driver-api/media/dtv-common.rst
@@ -0,0 +1,53 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+Digital TV Common functions
+---------------------------
+
+DVB devices
+~~~~~~~~~~~
+
+Those functions are responsible for handling the DVB device nodes.
+
+.. kernel-doc:: include/media/dvbdev.h
+
+Digital TV Ring buffer
+~~~~~~~~~~~~~~~~~~~~~~
+
+Those routines implement ring buffers used to handle digital TV data and
+copy it from/to userspace.
+
+.. note::
+
+ 1) For performance reasons read and write routines don't check buffer sizes
+ and/or number of bytes free/available. This has to be done before these
+ routines are called. For example:
+
+ .. code-block:: c
+
+ /* write @buflen: bytes */
+ free = dvb_ringbuffer_free(rbuf);
+ if (free >= buflen)
+ count = dvb_ringbuffer_write(rbuf, buffer, buflen);
+ else
+ /* do something */
+
+ /* read min. 1000, max. @bufsize: bytes */
+ avail = dvb_ringbuffer_avail(rbuf);
+ if (avail >= 1000)
+ count = dvb_ringbuffer_read(rbuf, buffer, min(avail, bufsize));
+ else
+ /* do something */
+
+ 2) If there is exactly one reader and one writer, there is no need
+ to lock read or write operations.
+ Two or more readers must be locked against each other.
+ Flushing the buffer counts as a read operation.
+ Resetting the buffer counts as a read and write operation.
+ Two or more writers must be locked against each other.
+
+.. kernel-doc:: include/media/dvb_ringbuffer.h
+
+Digital TV VB2 handler
+~~~~~~~~~~~~~~~~~~~~~~
+
+.. kernel-doc:: include/media/dvb_vb2.h
diff --git a/Documentation/driver-api/media/dtv-core.rst b/Documentation/driver-api/media/dtv-core.rst
new file mode 100644
index 000000000000..82c5b85ed9b1
--- /dev/null
+++ b/Documentation/driver-api/media/dtv-core.rst
@@ -0,0 +1,39 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+Digital TV (DVB) devices
+------------------------
+
+Digital TV devices are implemented by several different drivers:
+
+- A bridge driver that is responsible to talk with the bus where the other
+ devices are connected (PCI, USB, SPI), bind to the other drivers and
+ implement the digital demux logic (either in software or in hardware);
+
+- Frontend drivers that are usually implemented as two separate drivers:
+
+ - A tuner driver that implements the logic which commands the part of
+ the hardware responsible for tuning into a digital TV transponder or
+ physical channel. The output of a tuner is usually a baseband or
+ Intermediate Frequency (IF) signal;
+
+ - A demodulator driver (a.k.a "demod") that implements the logic which
+ commands the digital TV decoding hardware. The output of a demod is
+ a digital stream, with multiple audio, video and data channels typically
+ multiplexed using MPEG Transport Stream [#f1]_.
+
+On most hardware, the frontend drivers talk with the bridge driver using an
+I2C bus.
+
+.. [#f1] Some standards use TCP/IP for multiplexing data, like DVB-H (an
+ abandoned standard, not used anymore) and ATSC version 3.0 current
+ proposals. Currently, the DVB subsystem doesn't implement those standards.
+
+
+.. toctree::
+ :maxdepth: 1
+
+ dtv-common
+ dtv-frontend
+ dtv-demux
+ dtv-ca
+ dtv-net
diff --git a/Documentation/driver-api/media/dtv-demux.rst b/Documentation/driver-api/media/dtv-demux.rst
new file mode 100644
index 000000000000..144124142622
--- /dev/null
+++ b/Documentation/driver-api/media/dtv-demux.rst
@@ -0,0 +1,84 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+Digital TV Demux kABI
+---------------------
+
+Digital TV Demux
+~~~~~~~~~~~~~~~~
+
+The Kernel Digital TV Demux kABI defines a driver-internal interface for
+registering low-level, hardware specific driver to a hardware independent
+demux layer. It is only of interest for Digital TV device driver writers.
+The header file for this kABI is named ``demux.h`` and located in
+``include/media``.
+
+The demux kABI should be implemented for each demux in the system. It is
+used to select the TS source of a demux and to manage the demux resources.
+When the demux client allocates a resource via the demux kABI, it receives
+a pointer to the kABI of that resource.
+
+Each demux receives its TS input from a DVB front-end or from memory, as
+set via this demux kABI. In a system with more than one front-end, the kABI
+can be used to select one of the DVB front-ends as a TS source for a demux,
+unless this is fixed in the HW platform.
+
+The demux kABI only controls front-ends regarding to their connections with
+demuxes; the kABI used to set the other front-end parameters, such as
+tuning, are defined via the Digital TV Frontend kABI.
+
+The functions that implement the abstract interface demux should be defined
+static or module private and registered to the Demux core for external
+access. It is not necessary to implement every function in the struct
+:c:type:`dmx_demux`. For example, a demux interface might support Section filtering,
+but not PES filtering. The kABI client is expected to check the value of any
+function pointer before calling the function: the value of ``NULL`` means
+that the function is not available.
+
+Whenever the functions of the demux API modify shared data, the
+possibilities of lost update and race condition problems should be
+addressed, e.g. by protecting parts of code with mutexes.
+
+Note that functions called from a bottom half context must not sleep.
+Even a simple memory allocation without using ``GFP_ATOMIC`` can result in a
+kernel thread being put to sleep if swapping is needed. For example, the
+Linux Kernel calls the functions of a network device interface from a
+bottom half context. Thus, if a demux kABI function is called from network
+device code, the function must not sleep.
+
+Demux Callback API
+~~~~~~~~~~~~~~~~~~
+
+This kernel-space API comprises the callback functions that deliver filtered
+data to the demux client. Unlike the other DVB kABIs, these functions are
+provided by the client and called from the demux code.
+
+The function pointers of this abstract interface are not packed into a
+structure as in the other demux APIs, because the callback functions are
+registered and used independent of each other. As an example, it is possible
+for the API client to provide several callback functions for receiving TS
+packets and no callbacks for PES packets or sections.
+
+The functions that implement the callback API need not be re-entrant: when
+a demux driver calls one of these functions, the driver is not allowed to
+call the function again before the original call returns. If a callback is
+triggered by a hardware interrupt, it is recommended to use the Linux
+bottom half mechanism or start a tasklet instead of making the callback
+function call directly from a hardware interrupt.
+
+This mechanism is implemented by :c:func:`dmx_ts_cb()` and :c:func:`dmx_section_cb()`
+callbacks.
+
+Digital TV Demux device registration functions and data structures
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+.. kernel-doc:: include/media/dmxdev.h
+
+High-level Digital TV demux interface
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+.. kernel-doc:: include/media/dvb_demux.h
+
+Driver-internal low-level hardware specific driver demux interface
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+.. kernel-doc:: include/media/demux.h
diff --git a/Documentation/driver-api/media/dtv-frontend.rst b/Documentation/driver-api/media/dtv-frontend.rst
new file mode 100644
index 000000000000..ea43cdb5b0e4
--- /dev/null
+++ b/Documentation/driver-api/media/dtv-frontend.rst
@@ -0,0 +1,445 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+Digital TV Frontend kABI
+------------------------
+
+Digital TV Frontend
+~~~~~~~~~~~~~~~~~~~
+
+The Digital TV Frontend kABI defines a driver-internal interface for
+registering low-level, hardware specific driver to a hardware independent
+frontend layer. It is only of interest for Digital TV device driver writers.
+The header file for this API is named ``dvb_frontend.h`` and located in
+``include/media/``.
+
+Demodulator driver
+^^^^^^^^^^^^^^^^^^
+
+The demodulator driver is responsible for talking with the decoding part of the
+hardware. Such driver should implement :c:type:`dvb_frontend_ops`, which
+tells what type of digital TV standards are supported, and points to a
+series of functions that allow the DVB core to command the hardware via
+the code under ``include/media/dvb_frontend.c``.
+
+A typical example of such struct in a driver ``foo`` is::
+
+ static struct dvb_frontend_ops foo_ops = {
+ .delsys = { SYS_DVBT, SYS_DVBT2, SYS_DVBC_ANNEX_A },
+ .info = {
+ .name = "foo DVB-T/T2/C driver",
+ .caps = FE_CAN_FEC_1_2 |
+ FE_CAN_FEC_2_3 |
+ FE_CAN_FEC_3_4 |
+ FE_CAN_FEC_5_6 |
+ FE_CAN_FEC_7_8 |
+ FE_CAN_FEC_AUTO |
+ FE_CAN_QPSK |
+ FE_CAN_QAM_16 |
+ FE_CAN_QAM_32 |
+ FE_CAN_QAM_64 |
+ FE_CAN_QAM_128 |
+ FE_CAN_QAM_256 |
+ FE_CAN_QAM_AUTO |
+ FE_CAN_TRANSMISSION_MODE_AUTO |
+ FE_CAN_GUARD_INTERVAL_AUTO |
+ FE_CAN_HIERARCHY_AUTO |
+ FE_CAN_MUTE_TS |
+ FE_CAN_2G_MODULATION,
+ .frequency_min = 42000000, /* Hz */
+ .frequency_max = 1002000000, /* Hz */
+ .symbol_rate_min = 870000,
+ .symbol_rate_max = 11700000
+ },
+ .init = foo_init,
+ .sleep = foo_sleep,
+ .release = foo_release,
+ .set_frontend = foo_set_frontend,
+ .get_frontend = foo_get_frontend,
+ .read_status = foo_get_status_and_stats,
+ .tune = foo_tune,
+ .i2c_gate_ctrl = foo_i2c_gate_ctrl,
+ .get_frontend_algo = foo_get_algo,
+ };
+
+A typical example of such struct in a driver ``bar`` meant to be used on
+Satellite TV reception is::
+
+ static const struct dvb_frontend_ops bar_ops = {
+ .delsys = { SYS_DVBS, SYS_DVBS2 },
+ .info = {
+ .name = "Bar DVB-S/S2 demodulator",
+ .frequency_min = 500000, /* KHz */
+ .frequency_max = 2500000, /* KHz */
+ .frequency_stepsize = 0,
+ .symbol_rate_min = 1000000,
+ .symbol_rate_max = 45000000,
+ .symbol_rate_tolerance = 500,
+ .caps = FE_CAN_INVERSION_AUTO |
+ FE_CAN_FEC_AUTO |
+ FE_CAN_QPSK,
+ },
+ .init = bar_init,
+ .sleep = bar_sleep,
+ .release = bar_release,
+ .set_frontend = bar_set_frontend,
+ .get_frontend = bar_get_frontend,
+ .read_status = bar_get_status_and_stats,
+ .i2c_gate_ctrl = bar_i2c_gate_ctrl,
+ .get_frontend_algo = bar_get_algo,
+ .tune = bar_tune,
+
+ /* Satellite-specific */
+ .diseqc_send_master_cmd = bar_send_diseqc_msg,
+ .diseqc_send_burst = bar_send_burst,
+ .set_tone = bar_set_tone,
+ .set_voltage = bar_set_voltage,
+ };
+
+.. note::
+
+ #) For satellite digital TV standards (DVB-S, DVB-S2, ISDB-S), the
+ frequencies are specified in kHz, while, for terrestrial and cable
+ standards, they're specified in Hz. Due to that, if the same frontend
+ supports both types, you'll need to have two separate
+ :c:type:`dvb_frontend_ops` structures, one for each standard.
+ #) The ``.i2c_gate_ctrl`` field is present only when the hardware has
+ allows controlling an I2C gate (either directly of via some GPIO pin),
+ in order to remove the tuner from the I2C bus after a channel is
+ tuned.
+ #) All new drivers should implement the
+ :ref:`DVBv5 statistics <dvbv5_stats>` via ``.read_status``.
+ Yet, there are a number of callbacks meant to get statistics for
+ signal strength, S/N and UCB. Those are there to provide backward
+ compatibility with legacy applications that don't support the DVBv5
+ API. Implementing those callbacks are optional. Those callbacks may be
+ removed in the future, after we have all existing drivers supporting
+ DVBv5 stats.
+ #) Other callbacks are required for satellite TV standards, in order to
+ control LNBf and DiSEqC: ``.diseqc_send_master_cmd``,
+ ``.diseqc_send_burst``, ``.set_tone``, ``.set_voltage``.
+
+.. |delta| unicode:: U+00394
+
+The ``include/media/dvb_frontend.c`` has a kernel thread which is
+responsible for tuning the device. It supports multiple algorithms to
+detect a channel, as defined at enum :c:func:`dvbfe_algo`.
+
+The algorithm to be used is obtained via ``.get_frontend_algo``. If the driver
+doesn't fill its field at struct dvb_frontend_ops, it will default to
+``DVBFE_ALGO_SW``, meaning that the dvb-core will do a zigzag when tuning,
+e. g. it will try first to use the specified center frequency ``f``,
+then, it will do ``f`` + |delta|, ``f`` - |delta|, ``f`` + 2 x |delta|,
+``f`` - 2 x |delta| and so on.
+
+If the hardware has internally a some sort of zigzag algorithm, you should
+define a ``.get_frontend_algo`` function that would return ``DVBFE_ALGO_HW``.
+
+.. note::
+
+ The core frontend support also supports
+ a third type (``DVBFE_ALGO_CUSTOM``), in order to allow the driver to
+ define its own hardware-assisted algorithm. Very few hardware need to
+ use it nowadays. Using ``DVBFE_ALGO_CUSTOM`` require to provide other
+ function callbacks at struct dvb_frontend_ops.
+
+Attaching frontend driver to the bridge driver
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Before using the Digital TV frontend core, the bridge driver should attach
+the frontend demod, tuner and SEC devices and call
+:c:func:`dvb_register_frontend()`,
+in order to register the new frontend at the subsystem. At device
+detach/removal, the bridge driver should call
+:c:func:`dvb_unregister_frontend()` to
+remove the frontend from the core and then :c:func:`dvb_frontend_detach()`
+to free the memory allocated by the frontend drivers.
+
+The drivers should also call :c:func:`dvb_frontend_suspend()` as part of
+their handler for the :c:type:`device_driver`.\ ``suspend()``, and
+:c:func:`dvb_frontend_resume()` as
+part of their handler for :c:type:`device_driver`.\ ``resume()``.
+
+A few other optional functions are provided to handle some special cases.
+
+.. _dvbv5_stats:
+
+Digital TV Frontend statistics
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Introduction
+^^^^^^^^^^^^
+
+Digital TV frontends provide a range of
+:ref:`statistics <frontend-stat-properties>` meant to help tuning the device
+and measuring the quality of service.
+
+For each statistics measurement, the driver should set the type of scale used,
+or ``FE_SCALE_NOT_AVAILABLE`` if the statistics is not available on a given
+time. Drivers should also provide the number of statistics for each type.
+that's usually 1 for most video standards [#f2]_.
+
+Drivers should initialize each statistic counters with length and
+scale at its init code. For example, if the frontend provides signal
+strength, it should have, on its init code::
+
+ struct dtv_frontend_properties *c = &state->fe.dtv_property_cache;
+
+ c->strength.len = 1;
+ c->strength.stat[0].scale = FE_SCALE_NOT_AVAILABLE;
+
+And, when the statistics got updated, set the scale::
+
+ c->strength.stat[0].scale = FE_SCALE_DECIBEL;
+ c->strength.stat[0].uvalue = strength;
+
+.. [#f2] For ISDB-T, it may provide both a global statistics and a per-layer
+ set of statistics. On such cases, len should be equal to 4. The first
+ value corresponds to the global stat; the other ones to each layer, e. g.:
+
+ - c->cnr.stat[0] for global S/N carrier ratio,
+ - c->cnr.stat[1] for Layer A S/N carrier ratio,
+ - c->cnr.stat[2] for layer B S/N carrier ratio,
+ - c->cnr.stat[3] for layer C S/N carrier ratio.
+
+.. note:: Please prefer to use ``FE_SCALE_DECIBEL`` instead of
+ ``FE_SCALE_RELATIVE`` for signal strength and CNR measurements.
+
+Groups of statistics
+^^^^^^^^^^^^^^^^^^^^
+
+There are several groups of statistics currently supported:
+
+Signal strength (:ref:`DTV-STAT-SIGNAL-STRENGTH`)
+ - Measures the signal strength level at the analog part of the tuner or
+ demod.
+
+ - Typically obtained from the gain applied to the tuner and/or frontend
+ in order to detect the carrier. When no carrier is detected, the gain is
+ at the maximum value (so, strength is on its minimal).
+
+ - As the gain is visible through the set of registers that adjust the gain,
+ typically, this statistics is always available [#f3]_.
+
+ - Drivers should try to make it available all the times, as these statistics
+ can be used when adjusting an antenna position and to check for troubles
+ at the cabling.
+
+ .. [#f3] On a few devices, the gain keeps floating if there is no carrier.
+ On such devices, strength report should check first if carrier is
+ detected at the tuner (``FE_HAS_CARRIER``, see :c:type:`fe_status`),
+ and otherwise return the lowest possible value.
+
+Carrier Signal to Noise ratio (:ref:`DTV-STAT-CNR`)
+ - Signal to Noise ratio for the main carrier.
+
+ - Signal to Noise measurement depends on the device. On some hardware, it is
+ available when the main carrier is detected. On those hardware, CNR
+ measurement usually comes from the tuner (e. g. after ``FE_HAS_CARRIER``,
+ see :c:type:`fe_status`).
+
+ On other devices, it requires inner FEC decoding,
+ as the frontend measures it indirectly from other parameters (e. g. after
+ ``FE_HAS_VITERBI``, see :c:type:`fe_status`).
+
+ Having it available after inner FEC is more common.
+
+Bit counts post-FEC (:ref:`DTV-STAT-POST-ERROR-BIT-COUNT` and :ref:`DTV-STAT-POST-TOTAL-BIT-COUNT`)
+ - Those counters measure the number of bits and bit errors after
+ the forward error correction (FEC) on the inner coding block
+ (after Viterbi, LDPC or other inner code).
+
+ - Due to its nature, those statistics depend on full coding lock
+ (e. g. after ``FE_HAS_SYNC`` or after ``FE_HAS_LOCK``,
+ see :c:type:`fe_status`).
+
+Bit counts pre-FEC (:ref:`DTV-STAT-PRE-ERROR-BIT-COUNT` and :ref:`DTV-STAT-PRE-TOTAL-BIT-COUNT`)
+ - Those counters measure the number of bits and bit errors before
+ the forward error correction (FEC) on the inner coding block
+ (before Viterbi, LDPC or other inner code).
+
+ - Not all frontends provide this kind of statistics.
+
+ - Due to its nature, those statistics depend on inner coding lock (e. g.
+ after ``FE_HAS_VITERBI``, see :c:type:`fe_status`).
+
+Block counts (:ref:`DTV-STAT-ERROR-BLOCK-COUNT` and :ref:`DTV-STAT-TOTAL-BLOCK-COUNT`)
+ - Those counters measure the number of blocks and block errors after
+ the forward error correction (FEC) on the inner coding block
+ (before Viterbi, LDPC or other inner code).
+
+ - Due to its nature, those statistics depend on full coding lock
+ (e. g. after ``FE_HAS_SYNC`` or after
+ ``FE_HAS_LOCK``, see :c:type:`fe_status`).
+
+.. note:: All counters should be monotonically increased as they're
+ collected from the hardware.
+
+A typical example of the logic that handle status and statistics is::
+
+ static int foo_get_status_and_stats(struct dvb_frontend *fe)
+ {
+ struct foo_state *state = fe->demodulator_priv;
+ struct dtv_frontend_properties *c = &fe->dtv_property_cache;
+
+ int rc;
+ enum fe_status *status;
+
+ /* Both status and strength are always available */
+ rc = foo_read_status(fe, &status);
+ if (rc < 0)
+ return rc;
+
+ rc = foo_read_strength(fe);
+ if (rc < 0)
+ return rc;
+
+ /* Check if CNR is available */
+ if (!(fe->status & FE_HAS_CARRIER))
+ return 0;
+
+ rc = foo_read_cnr(fe);
+ if (rc < 0)
+ return rc;
+
+ /* Check if pre-BER stats are available */
+ if (!(fe->status & FE_HAS_VITERBI))
+ return 0;
+
+ rc = foo_get_pre_ber(fe);
+ if (rc < 0)
+ return rc;
+
+ /* Check if post-BER stats are available */
+ if (!(fe->status & FE_HAS_SYNC))
+ return 0;
+
+ rc = foo_get_post_ber(fe);
+ if (rc < 0)
+ return rc;
+ }
+
+ static const struct dvb_frontend_ops ops = {
+ /* ... */
+ .read_status = foo_get_status_and_stats,
+ };
+
+Statistics collection
+^^^^^^^^^^^^^^^^^^^^^
+
+On almost all frontend hardware, the bit and byte counts are stored by
+the hardware after a certain amount of time or after the total bit/block
+counter reaches a certain value (usually programmable), for example, on
+every 1000 ms or after receiving 1,000,000 bits.
+
+So, if you read the registers too soon, you'll end by reading the same
+value as in the previous reading, causing the monotonic value to be
+incremented too often.
+
+Drivers should take the responsibility to avoid too often reads. That
+can be done using two approaches:
+
+if the driver have a bit that indicates when a collected data is ready
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+Driver should check such bit before making the statistics available.
+
+An example of such behavior can be found at this code snippet (adapted
+from mb86a20s driver's logic)::
+
+ static int foo_get_pre_ber(struct dvb_frontend *fe)
+ {
+ struct foo_state *state = fe->demodulator_priv;
+ struct dtv_frontend_properties *c = &fe->dtv_property_cache;
+ int rc, bit_error;
+
+ /* Check if the BER measures are already available */
+ rc = foo_read_u8(state, 0x54);
+ if (rc < 0)
+ return rc;
+
+ if (!rc)
+ return 0;
+
+ /* Read Bit Error Count */
+ bit_error = foo_read_u32(state, 0x55);
+ if (bit_error < 0)
+ return bit_error;
+
+ /* Read Total Bit Count */
+ rc = foo_read_u32(state, 0x51);
+ if (rc < 0)
+ return rc;
+
+ c->pre_bit_error.stat[0].scale = FE_SCALE_COUNTER;
+ c->pre_bit_error.stat[0].uvalue += bit_error;
+ c->pre_bit_count.stat[0].scale = FE_SCALE_COUNTER;
+ c->pre_bit_count.stat[0].uvalue += rc;
+
+ return 0;
+ }
+
+If the driver doesn't provide a statistics available check bit
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+A few devices, however, may not provide a way to check if the stats are
+available (or the way to check it is unknown). They may not even provide
+a way to directly read the total number of bits or blocks.
+
+On those devices, the driver need to ensure that it won't be reading from
+the register too often and/or estimate the total number of bits/blocks.
+
+On such drivers, a typical routine to get statistics would be like
+(adapted from dib8000 driver's logic)::
+
+ struct foo_state {
+ /* ... */
+
+ unsigned long per_jiffies_stats;
+ }
+
+ static int foo_get_pre_ber(struct dvb_frontend *fe)
+ {
+ struct foo_state *state = fe->demodulator_priv;
+ struct dtv_frontend_properties *c = &fe->dtv_property_cache;
+ int rc, bit_error;
+ u64 bits;
+
+ /* Check if time for stats was elapsed */
+ if (!time_after(jiffies, state->per_jiffies_stats))
+ return 0;
+
+ /* Next stat should be collected in 1000 ms */
+ state->per_jiffies_stats = jiffies + msecs_to_jiffies(1000);
+
+ /* Read Bit Error Count */
+ bit_error = foo_read_u32(state, 0x55);
+ if (bit_error < 0)
+ return bit_error;
+
+ /*
+ * On this particular frontend, there's no register that
+ * would provide the number of bits per 1000ms sample. So,
+ * some function would calculate it based on DTV properties
+ */
+ bits = get_number_of_bits_per_1000ms(fe);
+
+ c->pre_bit_error.stat[0].scale = FE_SCALE_COUNTER;
+ c->pre_bit_error.stat[0].uvalue += bit_error;
+ c->pre_bit_count.stat[0].scale = FE_SCALE_COUNTER;
+ c->pre_bit_count.stat[0].uvalue += bits;
+
+ return 0;
+ }
+
+Please notice that, on both cases, we're getting the statistics using the
+:c:type:`dvb_frontend_ops` ``.read_status`` callback. The rationale is that
+the frontend core will automatically call this function periodically
+(usually, 3 times per second, when the frontend is locked).
+
+That warrants that we won't miss to collect a counter and increment the
+monotonic stats at the right time.
+
+Digital TV Frontend functions and types
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+.. kernel-doc:: include/media/dvb_frontend.h
diff --git a/Documentation/driver-api/media/dtv-net.rst b/Documentation/driver-api/media/dtv-net.rst
new file mode 100644
index 000000000000..deb6bffe96bb
--- /dev/null
+++ b/Documentation/driver-api/media/dtv-net.rst
@@ -0,0 +1,6 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+Digital TV Network kABI
+-----------------------
+
+.. kernel-doc:: include/media/dvb_net.h
diff --git a/Documentation/driver-api/media/index.rst b/Documentation/driver-api/media/index.rst
new file mode 100644
index 000000000000..d5593182a3f9
--- /dev/null
+++ b/Documentation/driver-api/media/index.rst
@@ -0,0 +1,54 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+.. include:: <isonum.txt>
+
+===================================
+Media subsystem kernel internal API
+===================================
+
+This section contains usage information about media subsystem and
+its supported drivers.
+
+Please see:
+
+Documentation/admin-guide/media/index.rst
+
+ - for usage information about media subsystem and supported drivers;
+
+Documentation/userspace-api/media/index.rst
+
+ - for the userspace APIs used on media devices.
+
+
+.. toctree::
+ :caption: Table of Contents
+ :maxdepth: 5
+ :numbered:
+
+ maintainer-entry-profile
+
+ v4l2-core
+ dtv-core
+ rc-core
+ mc-core
+ cec-core
+ tx-rx
+ camera-sensor
+
+ drivers/index
+
+**Copyright** |copy| 2009-2020 : LinuxTV Developers
+
+::
+
+ This documentation 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.
+
+ For more details see the file COPYING in the source distribution of Linux.
diff --git a/Documentation/driver-api/media/maintainer-entry-profile.rst b/Documentation/driver-api/media/maintainer-entry-profile.rst
new file mode 100644
index 000000000000..ffc712a5f632
--- /dev/null
+++ b/Documentation/driver-api/media/maintainer-entry-profile.rst
@@ -0,0 +1,206 @@
+Media Subsystem Profile
+=======================
+
+Overview
+--------
+
+The media subsystem covers support for a variety of devices: stream
+capture, analog and digital TV streams, cameras, remote controllers, HDMI CEC
+and media pipeline control.
+
+It covers, mainly, the contents of those directories:
+
+ - drivers/media
+ - drivers/staging/media
+ - Documentation/admin-guide/media
+ - Documentation/driver-api/media
+ - Documentation/userspace-api/media
+ - Documentation/devicetree/bindings/media/\ [1]_
+ - include/media
+
+.. [1] Device tree bindings are maintained by the
+ OPEN FIRMWARE AND FLATTENED DEVICE TREE BINDINGS maintainers
+ (see the MAINTAINERS file). So, changes there must be reviewed
+ by them before being merged via the media subsystem's development
+ tree.
+
+Both media userspace and Kernel APIs are documented and the documentation
+must be kept in sync with the API changes. It means that all patches that
+add new features to the subsystem must also bring changes to the
+corresponding API files.
+
+Due to the size and wide scope of the media subsystem, media's
+maintainership model is to have sub-maintainers that have a broad
+knowledge of a specific aspect of the subsystem. It is the sub-maintainers'
+task to review the patches, providing feedback to users if the patches are
+following the subsystem rules and are properly using the media kernel and
+userspace APIs.
+
+Patches for the media subsystem must be sent to the media mailing list
+at linux-media@vger.kernel.org as plain text only e-mail. Emails with
+HTML will be automatically rejected by the mail server. It could be wise
+to also copy the sub-maintainer(s).
+
+Media's workflow is heavily based on Patchwork, meaning that, once a patch
+is submitted, the e-mail will first be accepted by the mailing list
+server, and, after a while, it should appear at:
+
+ - https://patchwork.linuxtv.org/project/linux-media/list/
+
+If it doesn't automatically appear there after a few minutes, then
+probably something went wrong on your submission. Please check if the
+email is in plain text\ [2]_ only and if your emailer is not mangling
+whitespaces before complaining or submitting them again.
+
+You can check if the mailing list server accepted your patch, by looking at:
+
+ - https://lore.kernel.org/linux-media/
+
+.. [2] If your email contains HTML, the mailing list server will simply
+ drop it, without any further notice.
+
+
+Media maintainers
++++++++++++++++++
+
+At the media subsystem, we have a group of senior developers that
+are responsible for doing the code reviews at the drivers (also known as
+sub-maintainers), and another senior developer responsible for the
+subsystem as a whole. For core changes, whenever possible, multiple
+media maintainers do the review.
+
+The media maintainers that work on specific areas of the subsystem are:
+
+- Remote Controllers (infrared):
+ Sean Young <sean@mess.org>
+
+- HDMI CEC:
+ Hans Verkuil <hverkuil@xs4all.nl>
+
+- Media controller drivers:
+ Laurent Pinchart <laurent.pinchart@ideasonboard.com>
+
+- ISP, v4l2-async, v4l2-fwnode, v4l2-flash-led-class and Sensor drivers:
+ Sakari Ailus <sakari.ailus@linux.intel.com>
+
+- V4L2 drivers and core V4L2 frameworks:
+ Hans Verkuil <hverkuil@xs4all.nl>
+
+The subsystem maintainer is:
+ Mauro Carvalho Chehab <mchehab@kernel.org>
+
+Media maintainers may delegate a patch to other media maintainers as needed.
+On such case, checkpatch's ``delegate`` field indicates who's currently
+responsible for reviewing a patch.
+
+Submit Checklist Addendum
+-------------------------
+
+Patches that change the Open Firmware/Device Tree bindings must be
+reviewed by the Device Tree maintainers. So, DT maintainers should be
+Cc:ed when those are submitted via devicetree@vger.kernel.org mailing
+list.
+
+There is a set of compliance tools at https://git.linuxtv.org/v4l-utils.git/
+that should be used in order to check if the drivers are properly
+implementing the media APIs:
+
+==================== =======================================================
+Type Tool
+==================== =======================================================
+V4L2 drivers\ [3]_ ``v4l2-compliance``
+V4L2 virtual drivers ``contrib/test/test-media``
+CEC drivers ``cec-compliance``
+==================== =======================================================
+
+.. [3] The ``v4l2-compliance`` also covers the media controller usage inside
+ V4L2 drivers.
+
+Other compilance tools are under development to check other parts of the
+subsystem.
+
+Those tests need to pass before the patches go upstream.
+
+Also, please notice that we build the Kernel with::
+
+ make CF=-D__CHECK_ENDIAN__ CONFIG_DEBUG_SECTION_MISMATCH=y C=1 W=1 CHECK=check_script
+
+Where the check script is::
+
+ #!/bin/bash
+ /devel/smatch/smatch -p=kernel $@ >&2
+ /devel/sparse/sparse $@ >&2
+
+Be sure to not introduce new warnings on your patches without a
+very good reason.
+
+Style Cleanup Patches
++++++++++++++++++++++
+
+Style cleanups are welcome when they come together with other changes
+at the files where the style changes will affect.
+
+We may accept pure standalone style cleanups, but they should ideally
+be one patch for the whole subsystem (if the cleanup is low volume),
+or at least be grouped per directory. So, for example, if you're doing a
+big cleanup change set at drivers under drivers/media, please send a single
+patch for all drivers under drivers/media/pci, another one for
+drivers/media/usb and so on.
+
+Coding Style Addendum
++++++++++++++++++++++
+
+Media development uses ``checkpatch.pl`` on strict mode to verify the code
+style, e.g.::
+
+ $ ./scripts/checkpatch.pl --strict --max-line-length=80
+
+In principle, patches should follow the coding style rules, but exceptions
+are allowed if there are good reasons. On such case, maintainers and reviewers
+may question about the rationale for not addressing the ``checkpatch.pl``.
+
+Please notice that the goal here is to improve code readability. On
+a few cases, ``checkpatch.pl`` may actually point to something that would
+look worse. So, you should use good sense.
+
+Note that addressing one ``checkpatch.pl`` issue (of any kind) alone may lead
+to having longer lines than 80 characters per line. While this is not
+strictly prohibited, efforts should be made towards staying within 80
+characters per line. This could include using re-factoring code that leads
+to less indentation, shorter variable or function names and last but not
+least, simply wrapping the lines.
+
+In particular, we accept lines with more than 80 columns:
+
+ - on strings, as they shouldn't be broken due to line length limits;
+ - when a function or variable name need to have a big identifier name,
+ which keeps hard to honor the 80 columns limit;
+ - on arithmetic expressions, when breaking lines makes them harder to
+ read;
+ - when they avoid a line to end with an open parenthesis or an open
+ bracket.
+
+Key Cycle Dates
+---------------
+
+New submissions can be sent at any time, but if they intend to hit the
+next merge window they should be sent before -rc5, and ideally stabilized
+in the linux-media branch by -rc6.
+
+Review Cadence
+--------------
+
+Provided that your patch is at https://patchwork.linuxtv.org, it should
+be sooner or later handled, so you don't need to re-submit a patch.
+
+Except for bug fixes, we don't usually add new patches to the development
+tree between -rc6 and the next -rc1.
+
+Please notice that the media subsystem is a high traffic one, so it
+could take a while for us to be able to review your patches. Feel free
+to ping if you don't get a feedback in a couple of weeks or to ask
+other developers to publicly add Reviewed-by and, more importantly,
+``Tested-by:`` tags.
+
+Please note that we expect a detailed description for ``Tested-by:``,
+identifying what boards were used at the test and what it was tested.
diff --git a/Documentation/driver-api/media/mc-core.rst b/Documentation/driver-api/media/mc-core.rst
new file mode 100644
index 000000000000..2456950ce8ff
--- /dev/null
+++ b/Documentation/driver-api/media/mc-core.rst
@@ -0,0 +1,326 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+Media Controller devices
+------------------------
+
+Media Controller
+~~~~~~~~~~~~~~~~
+
+The media controller userspace API is documented in
+:ref:`the Media Controller uAPI book <media_controller>`. This document focus
+on the kernel-side implementation of the media framework.
+
+Abstract media device model
+^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Discovering a device internal topology, and configuring it at runtime, is one
+of the goals of the media framework. To achieve this, hardware devices are
+modelled as an oriented graph of building blocks called entities connected
+through pads.
+
+An entity is a basic media hardware building block. It can correspond to
+a large variety of logical blocks such as physical hardware devices
+(CMOS sensor for instance), logical hardware devices (a building block
+in a System-on-Chip image processing pipeline), DMA channels or physical
+connectors.
+
+A pad is a connection endpoint through which an entity can interact with
+other entities. Data (not restricted to video) produced by an entity
+flows from the entity's output to one or more entity inputs. Pads should
+not be confused with physical pins at chip boundaries.
+
+A link is a point-to-point oriented connection between two pads, either
+on the same entity or on different entities. Data flows from a source
+pad to a sink pad.
+
+Media device
+^^^^^^^^^^^^
+
+A media device is represented by a struct media_device
+instance, defined in ``include/media/media-device.h``.
+Allocation of the structure is handled by the media device driver, usually by
+embedding the :c:type:`media_device` instance in a larger driver-specific
+structure.
+
+Drivers initialise media device instances by calling
+:c:func:`media_device_init()`. After initialising a media device instance, it is
+registered by calling :c:func:`__media_device_register()` via the macro
+``media_device_register()`` and unregistered by calling
+:c:func:`media_device_unregister()`. An initialised media device must be
+eventually cleaned up by calling :c:func:`media_device_cleanup()`.
+
+Note that it is not allowed to unregister a media device instance that was not
+previously registered, or clean up a media device instance that was not
+previously initialised.
+
+Entities
+^^^^^^^^
+
+Entities are represented by a struct media_entity
+instance, defined in ``include/media/media-entity.h``. The structure is usually
+embedded into a higher-level structure, such as
+:c:type:`v4l2_subdev` or :c:type:`video_device`
+instances, although drivers can allocate entities directly.
+
+Drivers initialize entity pads by calling
+:c:func:`media_entity_pads_init()`.
+
+Drivers register entities with a media device by calling
+:c:func:`media_device_register_entity()`
+and unregistered by calling
+:c:func:`media_device_unregister_entity()`.
+
+Interfaces
+^^^^^^^^^^
+
+Interfaces are represented by a
+struct media_interface instance, defined in
+``include/media/media-entity.h``. Currently, only one type of interface is
+defined: a device node. Such interfaces are represented by a
+struct media_intf_devnode.
+
+Drivers initialize and create device node interfaces by calling
+:c:func:`media_devnode_create()`
+and remove them by calling:
+:c:func:`media_devnode_remove()`.
+
+Pads
+^^^^
+Pads are represented by a struct media_pad instance,
+defined in ``include/media/media-entity.h``. Each entity stores its pads in
+a pads array managed by the entity driver. Drivers usually embed the array in
+a driver-specific structure.
+
+Pads are identified by their entity and their 0-based index in the pads
+array.
+
+Both information are stored in the struct media_pad,
+making the struct media_pad pointer the canonical way
+to store and pass link references.
+
+Pads have flags that describe the pad capabilities and state.
+
+``MEDIA_PAD_FL_SINK`` indicates that the pad supports sinking data.
+``MEDIA_PAD_FL_SOURCE`` indicates that the pad supports sourcing data.
+
+.. note::
+
+ One and only one of ``MEDIA_PAD_FL_SINK`` or ``MEDIA_PAD_FL_SOURCE`` must
+ be set for each pad.
+
+Links
+^^^^^
+
+Links are represented by a struct media_link instance,
+defined in ``include/media/media-entity.h``. There are two types of links:
+
+**1. pad to pad links**:
+
+Associate two entities via their PADs. Each entity has a list that points
+to all links originating at or targeting any of its pads.
+A given link is thus stored twice, once in the source entity and once in
+the target entity.
+
+Drivers create pad to pad links by calling:
+:c:func:`media_create_pad_link()` and remove with
+:c:func:`media_entity_remove_links()`.
+
+**2. interface to entity links**:
+
+Associate one interface to a Link.
+
+Drivers create interface to entity links by calling:
+:c:func:`media_create_intf_link()` and remove with
+:c:func:`media_remove_intf_links()`.
+
+.. note::
+
+ Links can only be created after having both ends already created.
+
+Links have flags that describe the link capabilities and state. The
+valid values are described at :c:func:`media_create_pad_link()` and
+:c:func:`media_create_intf_link()`.
+
+Graph traversal
+^^^^^^^^^^^^^^^
+
+The media framework provides APIs to iterate over entities in a graph.
+
+To iterate over all entities belonging to a media device, drivers can use
+the media_device_for_each_entity macro, defined in
+``include/media/media-device.h``.
+
+.. code-block:: c
+
+ struct media_entity *entity;
+
+ media_device_for_each_entity(entity, mdev) {
+ // entity will point to each entity in turn
+ ...
+ }
+
+Drivers might also need to iterate over all entities in a graph that can be
+reached only through enabled links starting at a given entity. The media
+framework provides a depth-first graph traversal API for that purpose.
+
+.. note::
+
+ Graphs with cycles (whether directed or undirected) are **NOT**
+ supported by the graph traversal API. To prevent infinite loops, the graph
+ traversal code limits the maximum depth to ``MEDIA_ENTITY_ENUM_MAX_DEPTH``,
+ currently defined as 16.
+
+Drivers initiate a graph traversal by calling
+:c:func:`media_graph_walk_start()`
+
+The graph structure, provided by the caller, is initialized to start graph
+traversal at the given entity.
+
+Drivers can then retrieve the next entity by calling
+:c:func:`media_graph_walk_next()`
+
+When the graph traversal is complete the function will return ``NULL``.
+
+Graph traversal can be interrupted at any moment. No cleanup function call
+is required and the graph structure can be freed normally.
+
+Helper functions can be used to find a link between two given pads, or a pad
+connected to another pad through an enabled link
+(:c:func:`media_entity_find_link()`, :c:func:`media_pad_remote_pad_first()`,
+:c:func:`media_entity_remote_source_pad_unique()` and
+:c:func:`media_pad_remote_pad_unique()`).
+
+Use count and power handling
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Due to the wide differences between drivers regarding power management
+needs, the media controller does not implement power management. However,
+the struct media_entity includes a ``use_count``
+field that media drivers
+can use to track the number of users of every entity for power management
+needs.
+
+The :c:type:`media_entity<media_entity>`.\ ``use_count`` field is owned by
+media drivers and must not be
+touched by entity drivers. Access to the field must be protected by the
+:c:type:`media_device`.\ ``graph_mutex`` lock.
+
+Links setup
+^^^^^^^^^^^
+
+Link properties can be modified at runtime by calling
+:c:func:`media_entity_setup_link()`.
+
+Pipelines and media streams
+^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+A media stream is a stream of pixels or metadata originating from one or more
+source devices (such as a sensors) and flowing through media entity pads
+towards the final sinks. The stream can be modified on the route by the
+devices (e.g. scaling or pixel format conversions), or it can be split into
+multiple branches, or multiple branches can be merged.
+
+A media pipeline is a set of media streams which are interdependent. This
+interdependency can be caused by the hardware (e.g. configuration of a second
+stream cannot be changed if the first stream has been enabled) or by the driver
+due to the software design. Most commonly a media pipeline consists of a single
+stream which does not branch.
+
+When starting streaming, drivers must notify all entities in the pipeline to
+prevent link states from being modified during streaming by calling
+:c:func:`media_pipeline_start()`.
+
+The function will mark all the pads which are part of the pipeline as streaming.
+
+The struct media_pipeline instance pointed to by the pipe argument will be
+stored in every pad in the pipeline. Drivers should embed the struct
+media_pipeline in higher-level pipeline structures and can then access the
+pipeline through the struct media_pad pipe field.
+
+Calls to :c:func:`media_pipeline_start()` can be nested.
+The pipeline pointer must be identical for all nested calls to the function.
+
+:c:func:`media_pipeline_start()` may return an error. In that case,
+it will clean up any of the changes it did by itself.
+
+When stopping the stream, drivers must notify the entities with
+:c:func:`media_pipeline_stop()`.
+
+If multiple calls to :c:func:`media_pipeline_start()` have been
+made the same number of :c:func:`media_pipeline_stop()` calls
+are required to stop streaming.
+The :c:type:`media_entity`.\ ``pipe`` field is reset to ``NULL`` on the last
+nested stop call.
+
+Link configuration will fail with ``-EBUSY`` by default if either end of the
+link is a streaming entity. Links that can be modified while streaming must
+be marked with the ``MEDIA_LNK_FL_DYNAMIC`` flag.
+
+If other operations need to be disallowed on streaming entities (such as
+changing entities configuration parameters) drivers can explicitly check the
+media_entity stream_count field to find out if an entity is streaming. This
+operation must be done with the media_device graph_mutex held.
+
+Link validation
+^^^^^^^^^^^^^^^
+
+Link validation is performed by :c:func:`media_pipeline_start()`
+for any entity which has sink pads in the pipeline. The
+:c:type:`media_entity`.\ ``link_validate()`` callback is used for that
+purpose. In ``link_validate()`` callback, entity driver should check
+that the properties of the source pad of the connected entity and its own
+sink pad match. It is up to the type of the entity (and in the end, the
+properties of the hardware) what matching actually means.
+
+Subsystems should facilitate link validation by providing subsystem specific
+helper functions to provide easy access for commonly needed information, and
+in the end provide a way to use driver-specific callbacks.
+
+Media Controller Device Allocator API
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+When the media device belongs to more than one driver, the shared media
+device is allocated with the shared struct device as the key for look ups.
+
+The shared media device should stay in registered state until the last
+driver unregisters it. In addition, the media device should be released when
+all the references are released. Each driver gets a reference to the media
+device during probe, when it allocates the media device. If media device is
+already allocated, the allocate API bumps up the refcount and returns the
+existing media device. The driver puts the reference back in its disconnect
+routine when it calls :c:func:`media_device_delete()`.
+
+The media device is unregistered and cleaned up from the kref put handler to
+ensure that the media device stays in registered state until the last driver
+unregisters the media device.
+
+**Driver Usage**
+
+Drivers should use the appropriate media-core routines to manage the shared
+media device life-time handling the two states:
+1. allocate -> register -> delete
+2. get reference to already registered device -> delete
+
+call :c:func:`media_device_delete()` routine to make sure the shared media
+device delete is handled correctly.
+
+**driver probe:**
+Call :c:func:`media_device_usb_allocate()` to allocate or get a reference
+Call :c:func:`media_device_register()`, if media devnode isn't registered
+
+**driver disconnect:**
+Call :c:func:`media_device_delete()` to free the media_device. Freeing is
+handled by the kref put handler.
+
+API Definitions
+^^^^^^^^^^^^^^^
+
+.. kernel-doc:: include/media/media-device.h
+
+.. kernel-doc:: include/media/media-devnode.h
+
+.. kernel-doc:: include/media/media-entity.h
+
+.. kernel-doc:: include/media/media-request.h
+
+.. kernel-doc:: include/media/media-dev-allocator.h
diff --git a/Documentation/driver-api/media/rc-core.rst b/Documentation/driver-api/media/rc-core.rst
new file mode 100644
index 000000000000..53f5e643b6e9
--- /dev/null
+++ b/Documentation/driver-api/media/rc-core.rst
@@ -0,0 +1,88 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+Remote Controller devices
+-------------------------
+
+Remote Controller core
+~~~~~~~~~~~~~~~~~~~~~~
+
+The remote controller core implements infrastructure to receive and send
+remote controller keyboard keystrokes and mouse events.
+
+Every time a key is pressed on a remote controller, a scan code is produced.
+Also, on most hardware, keeping a key pressed for more than a few dozens of
+milliseconds produce a repeat key event. That's somewhat similar to what
+a normal keyboard or mouse is handled internally on Linux\ [#f1]_. So, the
+remote controller core is implemented on the top of the linux input/evdev
+interface.
+
+.. [#f1]
+
+ The main difference is that, on keyboard events, the keyboard controller
+ produces one event for a key press and another one for key release. On
+ infrared-based remote controllers, there's no key release event. Instead,
+ an extra code is produced to indicate key repeats.
+
+However, most of the remote controllers use infrared (IR) to transmit signals.
+As there are several protocols used to modulate infrared signals, one
+important part of the core is dedicated to adjust the driver and the core
+system to support the infrared protocol used by the emitter.
+
+The infrared transmission is done by blinking a infrared emitter using a
+carrier. The carrier can be switched on or off by the IR transmitter
+hardware. When the carrier is switched on, it is called *PULSE*.
+When the carrier is switched off, it is called *SPACE*.
+
+In other words, a typical IR transmission can be viewed as a sequence of
+*PULSE* and *SPACE* events, each with a given duration.
+
+The carrier parameters (frequency, duty cycle) and the intervals for
+*PULSE* and *SPACE* events depend on the protocol.
+For example, the NEC protocol uses a carrier of 38kHz, and transmissions
+start with a 9ms *PULSE* and a 4.5ms SPACE. It then transmits 16 bits of
+scan code, being 8 bits for address (usually it is a fixed number for a
+given remote controller), followed by 8 bits of code. A bit "1" is modulated
+with 560µs *PULSE* followed by 1690µs *SPACE* and a bit "0" is modulated
+with 560µs *PULSE* followed by 560µs *SPACE*.
+
+At receiver, a simple low-pass filter can be used to convert the received
+signal in a sequence of *PULSE/SPACE* events, filtering out the carrier
+frequency. Due to that, the receiver doesn't care about the carrier's
+actual frequency parameters: all it has to do is to measure the amount
+of time it receives *PULSE/SPACE* events.
+So, a simple IR receiver hardware will just provide a sequence of timings
+for those events to the Kernel. The drivers for hardware with such kind of
+receivers are identified by ``RC_DRIVER_IR_RAW``, as defined by
+:c:type:`rc_driver_type`\ [#f2]_. Other hardware come with a
+microcontroller that decode the *PULSE/SPACE* sequence and return scan
+codes to the Kernel. Such kind of receivers are identified
+by ``RC_DRIVER_SCANCODE``.
+
+.. [#f2]
+
+ The RC core also supports devices that have just IR emitters,
+ without any receivers. Right now, all such devices work only in
+ raw TX mode. Such kind of hardware is identified as
+ ``RC_DRIVER_IR_RAW_TX``.
+
+When the RC core receives events produced by ``RC_DRIVER_IR_RAW`` IR
+receivers, it needs to decode the IR protocol, in order to obtain the
+corresponding scan code. The protocols supported by the RC core are
+defined at enum :c:type:`rc_proto`.
+
+When the RC code receives a scan code (either directly, by a driver
+of the type ``RC_DRIVER_SCANCODE``, or via its IR decoders), it needs
+to convert into a Linux input event code. This is done via a mapping
+table.
+
+The Kernel has support for mapping tables available on most media
+devices. It also supports loading a table in runtime, via some
+sysfs nodes. See the :ref:`RC userspace API <Remote_controllers_Intro>`
+for more details.
+
+Remote controller data structures and functions
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. kernel-doc:: include/media/rc-core.h
+
+.. kernel-doc:: include/media/rc-map.h
diff --git a/Documentation/driver-api/media/tx-rx.rst b/Documentation/driver-api/media/tx-rx.rst
new file mode 100644
index 000000000000..29d66a47b56e
--- /dev/null
+++ b/Documentation/driver-api/media/tx-rx.rst
@@ -0,0 +1,134 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+.. _transmitter-receiver:
+
+Pixel data transmitter and receiver drivers
+===========================================
+
+V4L2 supports various devices that transmit and receive pixel data. Examples of
+these devices include a camera sensor, a TV tuner and a parallel, a BT.656 or a
+CSI-2 receiver in an SoC.
+
+Bus types
+---------
+
+The following busses are the most common. This section discusses these two only.
+
+MIPI CSI-2
+^^^^^^^^^^
+
+CSI-2 is a data bus intended for transferring images from cameras to
+the host SoC. It is defined by the `MIPI alliance`_.
+
+.. _`MIPI alliance`: https://www.mipi.org/
+
+Parallel and BT.656
+^^^^^^^^^^^^^^^^^^^
+
+The parallel and `BT.656`_ buses transport one bit of data on each clock cycle
+per data line. The parallel bus uses synchronisation and other additional
+signals whereas BT.656 embeds synchronisation.
+
+.. _`BT.656`: https://en.wikipedia.org/wiki/ITU-R_BT.656
+
+Transmitter drivers
+-------------------
+
+Transmitter drivers generally need to provide the receiver drivers with the
+configuration of the transmitter. What is required depends on the type of the
+bus. These are common for both busses.
+
+Media bus pixel code
+^^^^^^^^^^^^^^^^^^^^
+
+See :ref:`v4l2-mbus-pixelcode`.
+
+Link frequency
+^^^^^^^^^^^^^^
+
+The :ref:`V4L2_CID_LINK_FREQ <v4l2-cid-link-freq>` control is used to tell the
+receiver the frequency of the bus (i.e. it is not the same as the symbol rate).
+
+``.s_stream()`` callback
+^^^^^^^^^^^^^^^^^^^^^^^^
+
+The struct struct v4l2_subdev_video_ops->s_stream() callback is used by the
+receiver driver to control the transmitter driver's streaming state.
+
+
+CSI-2 transmitter drivers
+-------------------------
+
+Pixel rate
+^^^^^^^^^^
+
+The pixel rate on the bus is calculated as follows::
+
+ pixel_rate = link_freq * 2 * nr_of_lanes * 16 / k / bits_per_sample
+
+where
+
+.. list-table:: variables in pixel rate calculation
+ :header-rows: 1
+
+ * - variable or constant
+ - description
+ * - link_freq
+ - The value of the ``V4L2_CID_LINK_FREQ`` integer64 menu item.
+ * - nr_of_lanes
+ - Number of data lanes used on the CSI-2 link. This can
+ be obtained from the OF endpoint configuration.
+ * - 2
+ - Data is transferred on both rising and falling edge of the signal.
+ * - bits_per_sample
+ - Number of bits per sample.
+ * - k
+ - 16 for D-PHY and 7 for C-PHY
+
+.. note::
+
+ The pixel rate calculated this way is **not** the same thing as the
+ pixel rate on the camera sensor's pixel array which is indicated by the
+ :ref:`V4L2_CID_PIXEL_RATE <v4l2-cid-pixel-rate>` control.
+
+LP-11 and LP-111 states
+^^^^^^^^^^^^^^^^^^^^^^^
+
+As part of transitioning to high speed mode, a CSI-2 transmitter typically
+briefly sets the bus to LP-11 or LP-111 state, depending on the PHY. This period
+may be as short as 100 µs, during which the receiver observes this state and
+proceeds its own part of high speed mode transition.
+
+Most receivers are capable of autonomously handling this once the software has
+configured them to do so, but there are receivers which require software
+involvement in observing LP-11 or LP-111 state. 100 µs is a brief period to hit
+in software, especially when there is no interrupt telling something is
+happening.
+
+One way to address this is to configure the transmitter side explicitly to LP-11
+or LP-111 state, which requires support from the transmitter hardware. This is
+not universally available. Many devices return to this state once streaming is
+stopped while the state after power-on is LP-00 or LP-000.
+
+The ``.pre_streamon()`` callback may be used to prepare a transmitter for
+transitioning to streaming state, but not yet start streaming. Similarly, the
+``.post_streamoff()`` callback is used to undo what was done by the
+``.pre_streamon()`` callback. The caller of ``.pre_streamon()`` is thus required
+to call ``.post_streamoff()`` for each successful call of ``.pre_streamon()``.
+
+In the context of CSI-2, the ``.pre_streamon()`` callback is used to transition
+the transmitter to the LP-11 or LP-111 state. This also requires powering on the
+device, so this should be only done when it is needed.
+
+Receiver drivers that do not need explicit LP-11 or LP-111 state setup are
+waived from calling the two callbacks.
+
+Stopping the transmitter
+^^^^^^^^^^^^^^^^^^^^^^^^
+
+A transmitter stops sending the stream of images as a result of
+calling the ``.s_stream()`` callback. Some transmitters may stop the
+stream at a frame boundary whereas others stop immediately,
+effectively leaving the current frame unfinished. The receiver driver
+should not make assumptions either way, but function properly in both
+cases.
diff --git a/Documentation/driver-api/media/v4l2-async.rst b/Documentation/driver-api/media/v4l2-async.rst
new file mode 100644
index 000000000000..3422330b3b1f
--- /dev/null
+++ b/Documentation/driver-api/media/v4l2-async.rst
@@ -0,0 +1,5 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+V4L2 async kAPI
+^^^^^^^^^^^^^^^
+.. kernel-doc:: include/media/v4l2-async.h
diff --git a/Documentation/driver-api/media/v4l2-cci.rst b/Documentation/driver-api/media/v4l2-cci.rst
new file mode 100644
index 000000000000..dd297a40ed20
--- /dev/null
+++ b/Documentation/driver-api/media/v4l2-cci.rst
@@ -0,0 +1,5 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+V4L2 CCI kAPI
+^^^^^^^^^^^^^
+.. kernel-doc:: include/media/v4l2-cci.h
diff --git a/Documentation/driver-api/media/v4l2-common.rst b/Documentation/driver-api/media/v4l2-common.rst
new file mode 100644
index 000000000000..b1e70eb56aa4
--- /dev/null
+++ b/Documentation/driver-api/media/v4l2-common.rst
@@ -0,0 +1,8 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+V4L2 common functions and data structures
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. kernel-doc:: include/media/v4l2-common.h
+
+.. kernel-doc:: include/media/v4l2-ioctl.h
diff --git a/Documentation/driver-api/media/v4l2-controls.rst b/Documentation/driver-api/media/v4l2-controls.rst
new file mode 100644
index 000000000000..b2e91804829b
--- /dev/null
+++ b/Documentation/driver-api/media/v4l2-controls.rst
@@ -0,0 +1,823 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+V4L2 Controls
+=============
+
+Introduction
+------------
+
+The V4L2 control API seems simple enough, but quickly becomes very hard to
+implement correctly in drivers. But much of the code needed to handle controls
+is actually not driver specific and can be moved to the V4L core framework.
+
+After all, the only part that a driver developer is interested in is:
+
+1) How do I add a control?
+2) How do I set the control's value? (i.e. s_ctrl)
+
+And occasionally:
+
+3) How do I get the control's value? (i.e. g_volatile_ctrl)
+4) How do I validate the user's proposed control value? (i.e. try_ctrl)
+
+All the rest is something that can be done centrally.
+
+The control framework was created in order to implement all the rules of the
+V4L2 specification with respect to controls in a central place. And to make
+life as easy as possible for the driver developer.
+
+Note that the control framework relies on the presence of a struct
+:c:type:`v4l2_device` for V4L2 drivers and struct v4l2_subdev for
+sub-device drivers.
+
+
+Objects in the framework
+------------------------
+
+There are two main objects:
+
+The :c:type:`v4l2_ctrl` object describes the control properties and keeps
+track of the control's value (both the current value and the proposed new
+value).
+
+:c:type:`v4l2_ctrl_handler` is the object that keeps track of controls. It
+maintains a list of v4l2_ctrl objects that it owns and another list of
+references to controls, possibly to controls owned by other handlers.
+
+
+Basic usage for V4L2 and sub-device drivers
+-------------------------------------------
+
+1) Prepare the driver:
+
+.. code-block:: c
+
+ #include <media/v4l2-ctrls.h>
+
+1.1) Add the handler to your driver's top-level struct:
+
+For V4L2 drivers:
+
+.. code-block:: c
+
+ struct foo_dev {
+ ...
+ struct v4l2_device v4l2_dev;
+ ...
+ struct v4l2_ctrl_handler ctrl_handler;
+ ...
+ };
+
+For sub-device drivers:
+
+.. code-block:: c
+
+ struct foo_dev {
+ ...
+ struct v4l2_subdev sd;
+ ...
+ struct v4l2_ctrl_handler ctrl_handler;
+ ...
+ };
+
+1.2) Initialize the handler:
+
+.. code-block:: c
+
+ v4l2_ctrl_handler_init(&foo->ctrl_handler, nr_of_controls);
+
+The second argument is a hint telling the function how many controls this
+handler is expected to handle. It will allocate a hashtable based on this
+information. It is a hint only.
+
+1.3) Hook the control handler into the driver:
+
+For V4L2 drivers:
+
+.. code-block:: c
+
+ foo->v4l2_dev.ctrl_handler = &foo->ctrl_handler;
+
+For sub-device drivers:
+
+.. code-block:: c
+
+ foo->sd.ctrl_handler = &foo->ctrl_handler;
+
+1.4) Clean up the handler at the end:
+
+.. code-block:: c
+
+ v4l2_ctrl_handler_free(&foo->ctrl_handler);
+
+
+2) Add controls:
+
+You add non-menu controls by calling :c:func:`v4l2_ctrl_new_std`:
+
+.. code-block:: c
+
+ struct v4l2_ctrl *v4l2_ctrl_new_std(struct v4l2_ctrl_handler *hdl,
+ const struct v4l2_ctrl_ops *ops,
+ u32 id, s32 min, s32 max, u32 step, s32 def);
+
+Menu and integer menu controls are added by calling
+:c:func:`v4l2_ctrl_new_std_menu`:
+
+.. code-block:: c
+
+ struct v4l2_ctrl *v4l2_ctrl_new_std_menu(struct v4l2_ctrl_handler *hdl,
+ const struct v4l2_ctrl_ops *ops,
+ u32 id, s32 max, s32 skip_mask, s32 def);
+
+Menu controls with a driver specific menu are added by calling
+:c:func:`v4l2_ctrl_new_std_menu_items`:
+
+.. code-block:: c
+
+ struct v4l2_ctrl *v4l2_ctrl_new_std_menu_items(
+ struct v4l2_ctrl_handler *hdl,
+ const struct v4l2_ctrl_ops *ops, u32 id, s32 max,
+ s32 skip_mask, s32 def, const char * const *qmenu);
+
+Standard compound controls can be added by calling
+:c:func:`v4l2_ctrl_new_std_compound`:
+
+.. code-block:: c
+
+ struct v4l2_ctrl *v4l2_ctrl_new_std_compound(struct v4l2_ctrl_handler *hdl,
+ const struct v4l2_ctrl_ops *ops, u32 id,
+ const union v4l2_ctrl_ptr p_def);
+
+Integer menu controls with a driver specific menu can be added by calling
+:c:func:`v4l2_ctrl_new_int_menu`:
+
+.. code-block:: c
+
+ struct v4l2_ctrl *v4l2_ctrl_new_int_menu(struct v4l2_ctrl_handler *hdl,
+ const struct v4l2_ctrl_ops *ops,
+ u32 id, s32 max, s32 def, const s64 *qmenu_int);
+
+These functions are typically called right after the
+:c:func:`v4l2_ctrl_handler_init`:
+
+.. code-block:: c
+
+ static const s64 exp_bias_qmenu[] = {
+ -2, -1, 0, 1, 2
+ };
+ static const char * const test_pattern[] = {
+ "Disabled",
+ "Vertical Bars",
+ "Solid Black",
+ "Solid White",
+ };
+
+ v4l2_ctrl_handler_init(&foo->ctrl_handler, nr_of_controls);
+ v4l2_ctrl_new_std(&foo->ctrl_handler, &foo_ctrl_ops,
+ V4L2_CID_BRIGHTNESS, 0, 255, 1, 128);
+ v4l2_ctrl_new_std(&foo->ctrl_handler, &foo_ctrl_ops,
+ V4L2_CID_CONTRAST, 0, 255, 1, 128);
+ v4l2_ctrl_new_std_menu(&foo->ctrl_handler, &foo_ctrl_ops,
+ V4L2_CID_POWER_LINE_FREQUENCY,
+ V4L2_CID_POWER_LINE_FREQUENCY_60HZ, 0,
+ V4L2_CID_POWER_LINE_FREQUENCY_DISABLED);
+ v4l2_ctrl_new_int_menu(&foo->ctrl_handler, &foo_ctrl_ops,
+ V4L2_CID_EXPOSURE_BIAS,
+ ARRAY_SIZE(exp_bias_qmenu) - 1,
+ ARRAY_SIZE(exp_bias_qmenu) / 2 - 1,
+ exp_bias_qmenu);
+ v4l2_ctrl_new_std_menu_items(&foo->ctrl_handler, &foo_ctrl_ops,
+ V4L2_CID_TEST_PATTERN, ARRAY_SIZE(test_pattern) - 1, 0,
+ 0, test_pattern);
+ ...
+ if (foo->ctrl_handler.error) {
+ int err = foo->ctrl_handler.error;
+
+ v4l2_ctrl_handler_free(&foo->ctrl_handler);
+ return err;
+ }
+
+The :c:func:`v4l2_ctrl_new_std` function returns the v4l2_ctrl pointer to
+the new control, but if you do not need to access the pointer outside the
+control ops, then there is no need to store it.
+
+The :c:func:`v4l2_ctrl_new_std` function will fill in most fields based on
+the control ID except for the min, max, step and default values. These are
+passed in the last four arguments. These values are driver specific while
+control attributes like type, name, flags are all global. The control's
+current value will be set to the default value.
+
+The :c:func:`v4l2_ctrl_new_std_menu` function is very similar but it is
+used for menu controls. There is no min argument since that is always 0 for
+menu controls, and instead of a step there is a skip_mask argument: if bit
+X is 1, then menu item X is skipped.
+
+The :c:func:`v4l2_ctrl_new_int_menu` function creates a new standard
+integer menu control with driver-specific items in the menu. It differs
+from v4l2_ctrl_new_std_menu in that it doesn't have the mask argument and
+takes as the last argument an array of signed 64-bit integers that form an
+exact menu item list.
+
+The :c:func:`v4l2_ctrl_new_std_menu_items` function is very similar to
+v4l2_ctrl_new_std_menu but takes an extra parameter qmenu, which is the
+driver specific menu for an otherwise standard menu control. A good example
+for this control is the test pattern control for capture/display/sensors
+devices that have the capability to generate test patterns. These test
+patterns are hardware specific, so the contents of the menu will vary from
+device to device.
+
+Note that if something fails, the function will return NULL or an error and
+set ctrl_handler->error to the error code. If ctrl_handler->error was already
+set, then it will just return and do nothing. This is also true for
+v4l2_ctrl_handler_init if it cannot allocate the internal data structure.
+
+This makes it easy to init the handler and just add all controls and only check
+the error code at the end. Saves a lot of repetitive error checking.
+
+It is recommended to add controls in ascending control ID order: it will be
+a bit faster that way.
+
+3) Optionally force initial control setup:
+
+.. code-block:: c
+
+ v4l2_ctrl_handler_setup(&foo->ctrl_handler);
+
+This will call s_ctrl for all controls unconditionally. Effectively this
+initializes the hardware to the default control values. It is recommended
+that you do this as this ensures that both the internal data structures and
+the hardware are in sync.
+
+4) Finally: implement the :c:type:`v4l2_ctrl_ops`
+
+.. code-block:: c
+
+ static const struct v4l2_ctrl_ops foo_ctrl_ops = {
+ .s_ctrl = foo_s_ctrl,
+ };
+
+Usually all you need is s_ctrl:
+
+.. code-block:: c
+
+ static int foo_s_ctrl(struct v4l2_ctrl *ctrl)
+ {
+ struct foo *state = container_of(ctrl->handler, struct foo, ctrl_handler);
+
+ switch (ctrl->id) {
+ case V4L2_CID_BRIGHTNESS:
+ write_reg(0x123, ctrl->val);
+ break;
+ case V4L2_CID_CONTRAST:
+ write_reg(0x456, ctrl->val);
+ break;
+ }
+ return 0;
+ }
+
+The control ops are called with the v4l2_ctrl pointer as argument.
+The new control value has already been validated, so all you need to do is
+to actually update the hardware registers.
+
+You're done! And this is sufficient for most of the drivers we have. No need
+to do any validation of control values, or implement QUERYCTRL, QUERY_EXT_CTRL
+and QUERYMENU. And G/S_CTRL as well as G/TRY/S_EXT_CTRLS are automatically supported.
+
+
+.. note::
+
+ The remainder sections deal with more advanced controls topics and scenarios.
+ In practice the basic usage as described above is sufficient for most drivers.
+
+
+Inheriting Sub-device Controls
+------------------------------
+
+When a sub-device is registered with a V4L2 driver by calling
+v4l2_device_register_subdev() and the ctrl_handler fields of both v4l2_subdev
+and v4l2_device are set, then the controls of the subdev will become
+automatically available in the V4L2 driver as well. If the subdev driver
+contains controls that already exist in the V4L2 driver, then those will be
+skipped (so a V4L2 driver can always override a subdev control).
+
+What happens here is that v4l2_device_register_subdev() calls
+v4l2_ctrl_add_handler() adding the controls of the subdev to the controls
+of v4l2_device.
+
+
+Accessing Control Values
+------------------------
+
+The following union is used inside the control framework to access control
+values:
+
+.. code-block:: c
+
+ union v4l2_ctrl_ptr {
+ s32 *p_s32;
+ s64 *p_s64;
+ char *p_char;
+ void *p;
+ };
+
+The v4l2_ctrl struct contains these fields that can be used to access both
+current and new values:
+
+.. code-block:: c
+
+ s32 val;
+ struct {
+ s32 val;
+ } cur;
+
+
+ union v4l2_ctrl_ptr p_new;
+ union v4l2_ctrl_ptr p_cur;
+
+If the control has a simple s32 type, then:
+
+.. code-block:: c
+
+ &ctrl->val == ctrl->p_new.p_s32
+ &ctrl->cur.val == ctrl->p_cur.p_s32
+
+For all other types use ctrl->p_cur.p<something>. Basically the val
+and cur.val fields can be considered an alias since these are used so often.
+
+Within the control ops you can freely use these. The val and cur.val speak for
+themselves. The p_char pointers point to character buffers of length
+ctrl->maximum + 1, and are always 0-terminated.
+
+Unless the control is marked volatile the p_cur field points to the
+current cached control value. When you create a new control this value is made
+identical to the default value. After calling v4l2_ctrl_handler_setup() this
+value is passed to the hardware. It is generally a good idea to call this
+function.
+
+Whenever a new value is set that new value is automatically cached. This means
+that most drivers do not need to implement the g_volatile_ctrl() op. The
+exception is for controls that return a volatile register such as a signal
+strength read-out that changes continuously. In that case you will need to
+implement g_volatile_ctrl like this:
+
+.. code-block:: c
+
+ static int foo_g_volatile_ctrl(struct v4l2_ctrl *ctrl)
+ {
+ switch (ctrl->id) {
+ case V4L2_CID_BRIGHTNESS:
+ ctrl->val = read_reg(0x123);
+ break;
+ }
+ }
+
+Note that you use the 'new value' union as well in g_volatile_ctrl. In general
+controls that need to implement g_volatile_ctrl are read-only controls. If they
+are not, a V4L2_EVENT_CTRL_CH_VALUE will not be generated when the control
+changes.
+
+To mark a control as volatile you have to set V4L2_CTRL_FLAG_VOLATILE:
+
+.. code-block:: c
+
+ ctrl = v4l2_ctrl_new_std(&sd->ctrl_handler, ...);
+ if (ctrl)
+ ctrl->flags |= V4L2_CTRL_FLAG_VOLATILE;
+
+For try/s_ctrl the new values (i.e. as passed by the user) are filled in and
+you can modify them in try_ctrl or set them in s_ctrl. The 'cur' union
+contains the current value, which you can use (but not change!) as well.
+
+If s_ctrl returns 0 (OK), then the control framework will copy the new final
+values to the 'cur' union.
+
+While in g_volatile/s/try_ctrl you can access the value of all controls owned
+by the same handler since the handler's lock is held. If you need to access
+the value of controls owned by other handlers, then you have to be very careful
+not to introduce deadlocks.
+
+Outside of the control ops you have to go through to helper functions to get
+or set a single control value safely in your driver:
+
+.. code-block:: c
+
+ s32 v4l2_ctrl_g_ctrl(struct v4l2_ctrl *ctrl);
+ int v4l2_ctrl_s_ctrl(struct v4l2_ctrl *ctrl, s32 val);
+
+These functions go through the control framework just as VIDIOC_G/S_CTRL ioctls
+do. Don't use these inside the control ops g_volatile/s/try_ctrl, though, that
+will result in a deadlock since these helpers lock the handler as well.
+
+You can also take the handler lock yourself:
+
+.. code-block:: c
+
+ mutex_lock(&state->ctrl_handler.lock);
+ pr_info("String value is '%s'\n", ctrl1->p_cur.p_char);
+ pr_info("Integer value is '%s'\n", ctrl2->cur.val);
+ mutex_unlock(&state->ctrl_handler.lock);
+
+
+Menu Controls
+-------------
+
+The v4l2_ctrl struct contains this union:
+
+.. code-block:: c
+
+ union {
+ u32 step;
+ u32 menu_skip_mask;
+ };
+
+For menu controls menu_skip_mask is used. What it does is that it allows you
+to easily exclude certain menu items. This is used in the VIDIOC_QUERYMENU
+implementation where you can return -EINVAL if a certain menu item is not
+present. Note that VIDIOC_QUERYCTRL always returns a step value of 1 for
+menu controls.
+
+A good example is the MPEG Audio Layer II Bitrate menu control where the
+menu is a list of standardized possible bitrates. But in practice hardware
+implementations will only support a subset of those. By setting the skip
+mask you can tell the framework which menu items should be skipped. Setting
+it to 0 means that all menu items are supported.
+
+You set this mask either through the v4l2_ctrl_config struct for a custom
+control, or by calling v4l2_ctrl_new_std_menu().
+
+
+Custom Controls
+---------------
+
+Driver specific controls can be created using v4l2_ctrl_new_custom():
+
+.. code-block:: c
+
+ static const struct v4l2_ctrl_config ctrl_filter = {
+ .ops = &ctrl_custom_ops,
+ .id = V4L2_CID_MPEG_CX2341X_VIDEO_SPATIAL_FILTER,
+ .name = "Spatial Filter",
+ .type = V4L2_CTRL_TYPE_INTEGER,
+ .flags = V4L2_CTRL_FLAG_SLIDER,
+ .max = 15,
+ .step = 1,
+ };
+
+ ctrl = v4l2_ctrl_new_custom(&foo->ctrl_handler, &ctrl_filter, NULL);
+
+The last argument is the priv pointer which can be set to driver-specific
+private data.
+
+The v4l2_ctrl_config struct also has a field to set the is_private flag.
+
+If the name field is not set, then the framework will assume this is a standard
+control and will fill in the name, type and flags fields accordingly.
+
+
+Active and Grabbed Controls
+---------------------------
+
+If you get more complex relationships between controls, then you may have to
+activate and deactivate controls. For example, if the Chroma AGC control is
+on, then the Chroma Gain control is inactive. That is, you may set it, but
+the value will not be used by the hardware as long as the automatic gain
+control is on. Typically user interfaces can disable such input fields.
+
+You can set the 'active' status using v4l2_ctrl_activate(). By default all
+controls are active. Note that the framework does not check for this flag.
+It is meant purely for GUIs. The function is typically called from within
+s_ctrl.
+
+The other flag is the 'grabbed' flag. A grabbed control means that you cannot
+change it because it is in use by some resource. Typical examples are MPEG
+bitrate controls that cannot be changed while capturing is in progress.
+
+If a control is set to 'grabbed' using v4l2_ctrl_grab(), then the framework
+will return -EBUSY if an attempt is made to set this control. The
+v4l2_ctrl_grab() function is typically called from the driver when it
+starts or stops streaming.
+
+
+Control Clusters
+----------------
+
+By default all controls are independent from the others. But in more
+complex scenarios you can get dependencies from one control to another.
+In that case you need to 'cluster' them:
+
+.. code-block:: c
+
+ struct foo {
+ struct v4l2_ctrl_handler ctrl_handler;
+ #define AUDIO_CL_VOLUME (0)
+ #define AUDIO_CL_MUTE (1)
+ struct v4l2_ctrl *audio_cluster[2];
+ ...
+ };
+
+ state->audio_cluster[AUDIO_CL_VOLUME] =
+ v4l2_ctrl_new_std(&state->ctrl_handler, ...);
+ state->audio_cluster[AUDIO_CL_MUTE] =
+ v4l2_ctrl_new_std(&state->ctrl_handler, ...);
+ v4l2_ctrl_cluster(ARRAY_SIZE(state->audio_cluster), state->audio_cluster);
+
+From now on whenever one or more of the controls belonging to the same
+cluster is set (or 'gotten', or 'tried'), only the control ops of the first
+control ('volume' in this example) is called. You effectively create a new
+composite control. Similar to how a 'struct' works in C.
+
+So when s_ctrl is called with V4L2_CID_AUDIO_VOLUME as argument, you should set
+all two controls belonging to the audio_cluster:
+
+.. code-block:: c
+
+ static int foo_s_ctrl(struct v4l2_ctrl *ctrl)
+ {
+ struct foo *state = container_of(ctrl->handler, struct foo, ctrl_handler);
+
+ switch (ctrl->id) {
+ case V4L2_CID_AUDIO_VOLUME: {
+ struct v4l2_ctrl *mute = ctrl->cluster[AUDIO_CL_MUTE];
+
+ write_reg(0x123, mute->val ? 0 : ctrl->val);
+ break;
+ }
+ case V4L2_CID_CONTRAST:
+ write_reg(0x456, ctrl->val);
+ break;
+ }
+ return 0;
+ }
+
+In the example above the following are equivalent for the VOLUME case:
+
+.. code-block:: c
+
+ ctrl == ctrl->cluster[AUDIO_CL_VOLUME] == state->audio_cluster[AUDIO_CL_VOLUME]
+ ctrl->cluster[AUDIO_CL_MUTE] == state->audio_cluster[AUDIO_CL_MUTE]
+
+In practice using cluster arrays like this becomes very tiresome. So instead
+the following equivalent method is used:
+
+.. code-block:: c
+
+ struct {
+ /* audio cluster */
+ struct v4l2_ctrl *volume;
+ struct v4l2_ctrl *mute;
+ };
+
+The anonymous struct is used to clearly 'cluster' these two control pointers,
+but it serves no other purpose. The effect is the same as creating an
+array with two control pointers. So you can just do:
+
+.. code-block:: c
+
+ state->volume = v4l2_ctrl_new_std(&state->ctrl_handler, ...);
+ state->mute = v4l2_ctrl_new_std(&state->ctrl_handler, ...);
+ v4l2_ctrl_cluster(2, &state->volume);
+
+And in foo_s_ctrl you can use these pointers directly: state->mute->val.
+
+Note that controls in a cluster may be NULL. For example, if for some
+reason mute was never added (because the hardware doesn't support that
+particular feature), then mute will be NULL. So in that case we have a
+cluster of 2 controls, of which only 1 is actually instantiated. The
+only restriction is that the first control of the cluster must always be
+present, since that is the 'master' control of the cluster. The master
+control is the one that identifies the cluster and that provides the
+pointer to the v4l2_ctrl_ops struct that is used for that cluster.
+
+Obviously, all controls in the cluster array must be initialized to either
+a valid control or to NULL.
+
+In rare cases you might want to know which controls of a cluster actually
+were set explicitly by the user. For this you can check the 'is_new' flag of
+each control. For example, in the case of a volume/mute cluster the 'is_new'
+flag of the mute control would be set if the user called VIDIOC_S_CTRL for
+mute only. If the user would call VIDIOC_S_EXT_CTRLS for both mute and volume
+controls, then the 'is_new' flag would be 1 for both controls.
+
+The 'is_new' flag is always 1 when called from v4l2_ctrl_handler_setup().
+
+
+Handling autogain/gain-type Controls with Auto Clusters
+-------------------------------------------------------
+
+A common type of control cluster is one that handles 'auto-foo/foo'-type
+controls. Typical examples are autogain/gain, autoexposure/exposure,
+autowhitebalance/red balance/blue balance. In all cases you have one control
+that determines whether another control is handled automatically by the hardware,
+or whether it is under manual control from the user.
+
+If the cluster is in automatic mode, then the manual controls should be
+marked inactive and volatile. When the volatile controls are read the
+g_volatile_ctrl operation should return the value that the hardware's automatic
+mode set up automatically.
+
+If the cluster is put in manual mode, then the manual controls should become
+active again and the volatile flag is cleared (so g_volatile_ctrl is no longer
+called while in manual mode). In addition just before switching to manual mode
+the current values as determined by the auto mode are copied as the new manual
+values.
+
+Finally the V4L2_CTRL_FLAG_UPDATE should be set for the auto control since
+changing that control affects the control flags of the manual controls.
+
+In order to simplify this a special variation of v4l2_ctrl_cluster was
+introduced:
+
+.. code-block:: c
+
+ void v4l2_ctrl_auto_cluster(unsigned ncontrols, struct v4l2_ctrl **controls,
+ u8 manual_val, bool set_volatile);
+
+The first two arguments are identical to v4l2_ctrl_cluster. The third argument
+tells the framework which value switches the cluster into manual mode. The
+last argument will optionally set V4L2_CTRL_FLAG_VOLATILE for the non-auto controls.
+If it is false, then the manual controls are never volatile. You would typically
+use that if the hardware does not give you the option to read back to values as
+determined by the auto mode (e.g. if autogain is on, the hardware doesn't allow
+you to obtain the current gain value).
+
+The first control of the cluster is assumed to be the 'auto' control.
+
+Using this function will ensure that you don't need to handle all the complex
+flag and volatile handling.
+
+
+VIDIOC_LOG_STATUS Support
+-------------------------
+
+This ioctl allow you to dump the current status of a driver to the kernel log.
+The v4l2_ctrl_handler_log_status(ctrl_handler, prefix) can be used to dump the
+value of the controls owned by the given handler to the log. You can supply a
+prefix as well. If the prefix didn't end with a space, then ': ' will be added
+for you.
+
+
+Different Handlers for Different Video Nodes
+--------------------------------------------
+
+Usually the V4L2 driver has just one control handler that is global for
+all video nodes. But you can also specify different control handlers for
+different video nodes. You can do that by manually setting the ctrl_handler
+field of struct video_device.
+
+That is no problem if there are no subdevs involved but if there are, then
+you need to block the automatic merging of subdev controls to the global
+control handler. You do that by simply setting the ctrl_handler field in
+struct v4l2_device to NULL. Now v4l2_device_register_subdev() will no longer
+merge subdev controls.
+
+After each subdev was added, you will then have to call v4l2_ctrl_add_handler
+manually to add the subdev's control handler (sd->ctrl_handler) to the desired
+control handler. This control handler may be specific to the video_device or
+for a subset of video_device's. For example: the radio device nodes only have
+audio controls, while the video and vbi device nodes share the same control
+handler for the audio and video controls.
+
+If you want to have one handler (e.g. for a radio device node) have a subset
+of another handler (e.g. for a video device node), then you should first add
+the controls to the first handler, add the other controls to the second
+handler and finally add the first handler to the second. For example:
+
+.. code-block:: c
+
+ v4l2_ctrl_new_std(&radio_ctrl_handler, &radio_ops, V4L2_CID_AUDIO_VOLUME, ...);
+ v4l2_ctrl_new_std(&radio_ctrl_handler, &radio_ops, V4L2_CID_AUDIO_MUTE, ...);
+ v4l2_ctrl_new_std(&video_ctrl_handler, &video_ops, V4L2_CID_BRIGHTNESS, ...);
+ v4l2_ctrl_new_std(&video_ctrl_handler, &video_ops, V4L2_CID_CONTRAST, ...);
+ v4l2_ctrl_add_handler(&video_ctrl_handler, &radio_ctrl_handler, NULL);
+
+The last argument to v4l2_ctrl_add_handler() is a filter function that allows
+you to filter which controls will be added. Set it to NULL if you want to add
+all controls.
+
+Or you can add specific controls to a handler:
+
+.. code-block:: c
+
+ volume = v4l2_ctrl_new_std(&video_ctrl_handler, &ops, V4L2_CID_AUDIO_VOLUME, ...);
+ v4l2_ctrl_new_std(&video_ctrl_handler, &ops, V4L2_CID_BRIGHTNESS, ...);
+ v4l2_ctrl_new_std(&video_ctrl_handler, &ops, V4L2_CID_CONTRAST, ...);
+
+What you should not do is make two identical controls for two handlers.
+For example:
+
+.. code-block:: c
+
+ v4l2_ctrl_new_std(&radio_ctrl_handler, &radio_ops, V4L2_CID_AUDIO_MUTE, ...);
+ v4l2_ctrl_new_std(&video_ctrl_handler, &video_ops, V4L2_CID_AUDIO_MUTE, ...);
+
+This would be bad since muting the radio would not change the video mute
+control. The rule is to have one control for each hardware 'knob' that you
+can twiddle.
+
+
+Finding Controls
+----------------
+
+Normally you have created the controls yourself and you can store the struct
+v4l2_ctrl pointer into your own struct.
+
+But sometimes you need to find a control from another handler that you do
+not own. For example, if you have to find a volume control from a subdev.
+
+You can do that by calling v4l2_ctrl_find:
+
+.. code-block:: c
+
+ struct v4l2_ctrl *volume;
+
+ volume = v4l2_ctrl_find(sd->ctrl_handler, V4L2_CID_AUDIO_VOLUME);
+
+Since v4l2_ctrl_find will lock the handler you have to be careful where you
+use it. For example, this is not a good idea:
+
+.. code-block:: c
+
+ struct v4l2_ctrl_handler ctrl_handler;
+
+ v4l2_ctrl_new_std(&ctrl_handler, &video_ops, V4L2_CID_BRIGHTNESS, ...);
+ v4l2_ctrl_new_std(&ctrl_handler, &video_ops, V4L2_CID_CONTRAST, ...);
+
+...and in video_ops.s_ctrl:
+
+.. code-block:: c
+
+ case V4L2_CID_BRIGHTNESS:
+ contrast = v4l2_find_ctrl(&ctrl_handler, V4L2_CID_CONTRAST);
+ ...
+
+When s_ctrl is called by the framework the ctrl_handler.lock is already taken, so
+attempting to find another control from the same handler will deadlock.
+
+It is recommended not to use this function from inside the control ops.
+
+
+Preventing Controls inheritance
+-------------------------------
+
+When one control handler is added to another using v4l2_ctrl_add_handler, then
+by default all controls from one are merged to the other. But a subdev might
+have low-level controls that make sense for some advanced embedded system, but
+not when it is used in consumer-level hardware. In that case you want to keep
+those low-level controls local to the subdev. You can do this by simply
+setting the 'is_private' flag of the control to 1:
+
+.. code-block:: c
+
+ static const struct v4l2_ctrl_config ctrl_private = {
+ .ops = &ctrl_custom_ops,
+ .id = V4L2_CID_...,
+ .name = "Some Private Control",
+ .type = V4L2_CTRL_TYPE_INTEGER,
+ .max = 15,
+ .step = 1,
+ .is_private = 1,
+ };
+
+ ctrl = v4l2_ctrl_new_custom(&foo->ctrl_handler, &ctrl_private, NULL);
+
+These controls will now be skipped when v4l2_ctrl_add_handler is called.
+
+
+V4L2_CTRL_TYPE_CTRL_CLASS Controls
+----------------------------------
+
+Controls of this type can be used by GUIs to get the name of the control class.
+A fully featured GUI can make a dialog with multiple tabs with each tab
+containing the controls belonging to a particular control class. The name of
+each tab can be found by querying a special control with ID <control class | 1>.
+
+Drivers do not have to care about this. The framework will automatically add
+a control of this type whenever the first control belonging to a new control
+class is added.
+
+
+Adding Notify Callbacks
+-----------------------
+
+Sometimes the platform or bridge driver needs to be notified when a control
+from a sub-device driver changes. You can set a notify callback by calling
+this function:
+
+.. code-block:: c
+
+ void v4l2_ctrl_notify(struct v4l2_ctrl *ctrl,
+ void (*notify)(struct v4l2_ctrl *ctrl, void *priv), void *priv);
+
+Whenever the give control changes value the notify callback will be called
+with a pointer to the control and the priv pointer that was passed with
+v4l2_ctrl_notify. Note that the control's handler lock is held when the
+notify function is called.
+
+There can be only one notify function per control handler. Any attempt
+to set another notify function will cause a WARN_ON.
+
+v4l2_ctrl functions and data structures
+---------------------------------------
+
+.. kernel-doc:: include/media/v4l2-ctrls.h
diff --git a/Documentation/driver-api/media/v4l2-core.rst b/Documentation/driver-api/media/v4l2-core.rst
new file mode 100644
index 000000000000..58cba831ade5
--- /dev/null
+++ b/Documentation/driver-api/media/v4l2-core.rst
@@ -0,0 +1,28 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+Video4Linux devices
+-------------------
+
+.. toctree::
+ :maxdepth: 1
+
+ v4l2-intro
+ v4l2-dev
+ v4l2-device
+ v4l2-fh
+ v4l2-subdev
+ v4l2-event
+ v4l2-controls
+ v4l2-videobuf2
+ v4l2-dv-timings
+ v4l2-flash-led-class
+ v4l2-mc
+ v4l2-mediabus
+ v4l2-mem2mem
+ v4l2-async
+ v4l2-fwnode
+ v4l2-cci
+ v4l2-rect
+ v4l2-tuner
+ v4l2-common
+ v4l2-tveeprom
diff --git a/Documentation/driver-api/media/v4l2-dev.rst b/Documentation/driver-api/media/v4l2-dev.rst
new file mode 100644
index 000000000000..d5cb19b21a9f
--- /dev/null
+++ b/Documentation/driver-api/media/v4l2-dev.rst
@@ -0,0 +1,367 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+Video device' s internal representation
+=======================================
+
+The actual device nodes in the ``/dev`` directory are created using the
+:c:type:`video_device` struct (``v4l2-dev.h``). This struct can either be
+allocated dynamically or embedded in a larger struct.
+
+To allocate it dynamically use :c:func:`video_device_alloc`:
+
+.. code-block:: c
+
+ struct video_device *vdev = video_device_alloc();
+
+ if (vdev == NULL)
+ return -ENOMEM;
+
+ vdev->release = video_device_release;
+
+If you embed it in a larger struct, then you must set the ``release()``
+callback to your own function:
+
+.. code-block:: c
+
+ struct video_device *vdev = &my_vdev->vdev;
+
+ vdev->release = my_vdev_release;
+
+The ``release()`` callback must be set and it is called when the last user
+of the video device exits.
+
+The default :c:func:`video_device_release` callback currently
+just calls ``kfree`` to free the allocated memory.
+
+There is also a :c:func:`video_device_release_empty` function that does
+nothing (is empty) and should be used if the struct is embedded and there
+is nothing to do when it is released.
+
+You should also set these fields of :c:type:`video_device`:
+
+- :c:type:`video_device`->v4l2_dev: must be set to the :c:type:`v4l2_device`
+ parent device.
+
+- :c:type:`video_device`->name: set to something descriptive and unique.
+
+- :c:type:`video_device`->vfl_dir: set this to ``VFL_DIR_RX`` for capture
+ devices (``VFL_DIR_RX`` has value 0, so this is normally already the
+ default), set to ``VFL_DIR_TX`` for output devices and ``VFL_DIR_M2M`` for mem2mem (codec) devices.
+
+- :c:type:`video_device`->fops: set to the :c:type:`v4l2_file_operations`
+ struct.
+
+- :c:type:`video_device`->ioctl_ops: if you use the :c:type:`v4l2_ioctl_ops`
+ to simplify ioctl maintenance (highly recommended to use this and it might
+ become compulsory in the future!), then set this to your
+ :c:type:`v4l2_ioctl_ops` struct. The :c:type:`video_device`->vfl_type and
+ :c:type:`video_device`->vfl_dir fields are used to disable ops that do not
+ match the type/dir combination. E.g. VBI ops are disabled for non-VBI nodes,
+ and output ops are disabled for a capture device. This makes it possible to
+ provide just one :c:type:`v4l2_ioctl_ops` struct for both vbi and
+ video nodes.
+
+- :c:type:`video_device`->lock: leave to ``NULL`` if you want to do all the
+ locking in the driver. Otherwise you give it a pointer to a struct
+ ``mutex_lock`` and before the :c:type:`video_device`->unlocked_ioctl
+ file operation is called this lock will be taken by the core and released
+ afterwards. See the next section for more details.
+
+- :c:type:`video_device`->queue: a pointer to the struct vb2_queue
+ associated with this device node.
+ If queue is not ``NULL``, and queue->lock is not ``NULL``, then queue->lock
+ is used for the queuing ioctls (``VIDIOC_REQBUFS``, ``CREATE_BUFS``,
+ ``QBUF``, ``DQBUF``, ``QUERYBUF``, ``PREPARE_BUF``, ``STREAMON`` and
+ ``STREAMOFF``) instead of the lock above.
+ That way the :ref:`vb2 <vb2_framework>` queuing framework does not have
+ to wait for other ioctls. This queue pointer is also used by the
+ :ref:`vb2 <vb2_framework>` helper functions to check for
+ queuing ownership (i.e. is the filehandle calling it allowed to do the
+ operation).
+
+- :c:type:`video_device`->prio: keeps track of the priorities. Used to
+ implement ``VIDIOC_G_PRIORITY`` and ``VIDIOC_S_PRIORITY``.
+ If left to ``NULL``, then it will use the struct v4l2_prio_state
+ in :c:type:`v4l2_device`. If you want to have a separate priority state per
+ (group of) device node(s), then you can point it to your own struct
+ :c:type:`v4l2_prio_state`.
+
+- :c:type:`video_device`->dev_parent: you only set this if v4l2_device was
+ registered with ``NULL`` as the parent ``device`` struct. This only happens
+ in cases where one hardware device has multiple PCI devices that all share
+ the same :c:type:`v4l2_device` core.
+
+ The cx88 driver is an example of this: one core :c:type:`v4l2_device` struct,
+ but it is used by both a raw video PCI device (cx8800) and a MPEG PCI device
+ (cx8802). Since the :c:type:`v4l2_device` cannot be associated with two PCI
+ devices at the same time it is setup without a parent device. But when the
+ struct video_device is initialized you **do** know which parent
+ PCI device to use and so you set ``dev_device`` to the correct PCI device.
+
+If you use :c:type:`v4l2_ioctl_ops`, then you should set
+:c:type:`video_device`->unlocked_ioctl to :c:func:`video_ioctl2` in your
+:c:type:`v4l2_file_operations` struct.
+
+In some cases you want to tell the core that a function you had specified in
+your :c:type:`v4l2_ioctl_ops` should be ignored. You can mark such ioctls by
+calling this function before :c:func:`video_register_device` is called:
+
+ :c:func:`v4l2_disable_ioctl <v4l2_disable_ioctl>`
+ (:c:type:`vdev <video_device>`, cmd).
+
+This tends to be needed if based on external factors (e.g. which card is
+being used) you want to turns off certain features in :c:type:`v4l2_ioctl_ops`
+without having to make a new struct.
+
+The :c:type:`v4l2_file_operations` struct is a subset of file_operations.
+The main difference is that the inode argument is omitted since it is never
+used.
+
+If integration with the media framework is needed, you must initialize the
+:c:type:`media_entity` struct embedded in the :c:type:`video_device` struct
+(entity field) by calling :c:func:`media_entity_pads_init`:
+
+.. code-block:: c
+
+ struct media_pad *pad = &my_vdev->pad;
+ int err;
+
+ err = media_entity_pads_init(&vdev->entity, 1, pad);
+
+The pads array must have been previously initialized. There is no need to
+manually set the struct media_entity type and name fields.
+
+A reference to the entity will be automatically acquired/released when the
+video device is opened/closed.
+
+ioctls and locking
+------------------
+
+The V4L core provides optional locking services. The main service is the
+lock field in struct video_device, which is a pointer to a mutex.
+If you set this pointer, then that will be used by unlocked_ioctl to
+serialize all ioctls.
+
+If you are using the :ref:`videobuf2 framework <vb2_framework>`, then there
+is a second lock that you can set: :c:type:`video_device`->queue->lock. If
+set, then this lock will be used instead of :c:type:`video_device`->lock
+to serialize all queuing ioctls (see the previous section
+for the full list of those ioctls).
+
+The advantage of using a different lock for the queuing ioctls is that for some
+drivers (particularly USB drivers) certain commands such as setting controls
+can take a long time, so you want to use a separate lock for the buffer queuing
+ioctls. That way your ``VIDIOC_DQBUF`` doesn't stall because the driver is busy
+changing the e.g. exposure of the webcam.
+
+Of course, you can always do all the locking yourself by leaving both lock
+pointers at ``NULL``.
+
+In the case of :ref:`videobuf2 <vb2_framework>` you will need to implement the
+``wait_prepare()`` and ``wait_finish()`` callbacks to unlock/lock if applicable.
+If you use the ``queue->lock`` pointer, then you can use the helper functions
+:c:func:`vb2_ops_wait_prepare` and :c:func:`vb2_ops_wait_finish`.
+
+The implementation of a hotplug disconnect should also take the lock from
+:c:type:`video_device` before calling v4l2_device_disconnect. If you are also
+using :c:type:`video_device`->queue->lock, then you have to first lock
+:c:type:`video_device`->queue->lock followed by :c:type:`video_device`->lock.
+That way you can be sure no ioctl is running when you call
+:c:func:`v4l2_device_disconnect`.
+
+Video device registration
+-------------------------
+
+Next you register the video device with :c:func:`video_register_device`.
+This will create the character device for you.
+
+.. code-block:: c
+
+ err = video_register_device(vdev, VFL_TYPE_VIDEO, -1);
+ if (err) {
+ video_device_release(vdev); /* or kfree(my_vdev); */
+ return err;
+ }
+
+If the :c:type:`v4l2_device` parent device has a not ``NULL`` mdev field,
+the video device entity will be automatically registered with the media
+device.
+
+Which device is registered depends on the type argument. The following
+types exist:
+
+========================== ==================== ==============================
+:c:type:`vfl_devnode_type` Device name Usage
+========================== ==================== ==============================
+``VFL_TYPE_VIDEO`` ``/dev/videoX`` for video input/output devices
+``VFL_TYPE_VBI`` ``/dev/vbiX`` for vertical blank data (i.e.
+ closed captions, teletext)
+``VFL_TYPE_RADIO`` ``/dev/radioX`` for radio tuners
+``VFL_TYPE_SUBDEV`` ``/dev/v4l-subdevX`` for V4L2 subdevices
+``VFL_TYPE_SDR`` ``/dev/swradioX`` for Software Defined Radio
+ (SDR) tuners
+``VFL_TYPE_TOUCH`` ``/dev/v4l-touchX`` for touch sensors
+========================== ==================== ==============================
+
+The last argument gives you a certain amount of control over the device
+node number used (i.e. the X in ``videoX``). Normally you will pass -1
+to let the v4l2 framework pick the first free number. But sometimes users
+want to select a specific node number. It is common that drivers allow
+the user to select a specific device node number through a driver module
+option. That number is then passed to this function and video_register_device
+will attempt to select that device node number. If that number was already
+in use, then the next free device node number will be selected and it
+will send a warning to the kernel log.
+
+Another use-case is if a driver creates many devices. In that case it can
+be useful to place different video devices in separate ranges. For example,
+video capture devices start at 0, video output devices start at 16.
+So you can use the last argument to specify a minimum device node number
+and the v4l2 framework will try to pick the first free number that is equal
+or higher to what you passed. If that fails, then it will just pick the
+first free number.
+
+Since in this case you do not care about a warning about not being able
+to select the specified device node number, you can call the function
+:c:func:`video_register_device_no_warn` instead.
+
+Whenever a device node is created some attributes are also created for you.
+If you look in ``/sys/class/video4linux`` you see the devices. Go into e.g.
+``video0`` and you will see 'name', 'dev_debug' and 'index' attributes. The
+'name' attribute is the 'name' field of the video_device struct. The
+'dev_debug' attribute can be used to enable core debugging. See the next
+section for more detailed information on this.
+
+The 'index' attribute is the index of the device node: for each call to
+:c:func:`video_register_device()` the index is just increased by 1. The
+first video device node you register always starts with index 0.
+
+Users can setup udev rules that utilize the index attribute to make fancy
+device names (e.g. '``mpegX``' for MPEG video capture device nodes).
+
+After the device was successfully registered, then you can use these fields:
+
+- :c:type:`video_device`->vfl_type: the device type passed to
+ :c:func:`video_register_device`.
+- :c:type:`video_device`->minor: the assigned device minor number.
+- :c:type:`video_device`->num: the device node number (i.e. the X in
+ ``videoX``).
+- :c:type:`video_device`->index: the device index number.
+
+If the registration failed, then you need to call
+:c:func:`video_device_release` to free the allocated :c:type:`video_device`
+struct, or free your own struct if the :c:type:`video_device` was embedded in
+it. The ``vdev->release()`` callback will never be called if the registration
+failed, nor should you ever attempt to unregister the device if the
+registration failed.
+
+video device debugging
+----------------------
+
+The 'dev_debug' attribute that is created for each video, vbi, radio or swradio
+device in ``/sys/class/video4linux/<devX>/`` allows you to enable logging of
+file operations.
+
+It is a bitmask and the following bits can be set:
+
+.. tabularcolumns:: |p{5ex}|L|
+
+===== ================================================================
+Mask Description
+===== ================================================================
+0x01 Log the ioctl name and error code. VIDIOC_(D)QBUF ioctls are
+ only logged if bit 0x08 is also set.
+0x02 Log the ioctl name arguments and error code. VIDIOC_(D)QBUF
+ ioctls are
+ only logged if bit 0x08 is also set.
+0x04 Log the file operations open, release, read, write, mmap and
+ get_unmapped_area. The read and write operations are only
+ logged if bit 0x08 is also set.
+0x08 Log the read and write file operations and the VIDIOC_QBUF and
+ VIDIOC_DQBUF ioctls.
+0x10 Log the poll file operation.
+0x20 Log error and messages in the control operations.
+===== ================================================================
+
+Video device cleanup
+--------------------
+
+When the video device nodes have to be removed, either during the unload
+of the driver or because the USB device was disconnected, then you should
+unregister them with:
+
+ :c:func:`video_unregister_device`
+ (:c:type:`vdev <video_device>`);
+
+This will remove the device nodes from sysfs (causing udev to remove them
+from ``/dev``).
+
+After :c:func:`video_unregister_device` returns no new opens can be done.
+However, in the case of USB devices some application might still have one of
+these device nodes open. So after the unregister all file operations (except
+release, of course) will return an error as well.
+
+When the last user of the video device node exits, then the ``vdev->release()``
+callback is called and you can do the final cleanup there.
+
+Don't forget to cleanup the media entity associated with the video device if
+it has been initialized:
+
+ :c:func:`media_entity_cleanup <media_entity_cleanup>`
+ (&vdev->entity);
+
+This can be done from the release callback.
+
+
+helper functions
+----------------
+
+There are a few useful helper functions:
+
+- file and :c:type:`video_device` private data
+
+You can set/get driver private data in the video_device struct using:
+
+ :c:func:`video_get_drvdata <video_get_drvdata>`
+ (:c:type:`vdev <video_device>`);
+
+ :c:func:`video_set_drvdata <video_set_drvdata>`
+ (:c:type:`vdev <video_device>`);
+
+Note that you can safely call :c:func:`video_set_drvdata` before calling
+:c:func:`video_register_device`.
+
+And this function:
+
+ :c:func:`video_devdata <video_devdata>`
+ (struct file \*file);
+
+returns the video_device belonging to the file struct.
+
+The :c:func:`video_devdata` function combines :c:func:`video_get_drvdata`
+with :c:func:`video_devdata`:
+
+ :c:func:`video_drvdata <video_drvdata>`
+ (struct file \*file);
+
+You can go from a :c:type:`video_device` struct to the v4l2_device struct using:
+
+.. code-block:: c
+
+ struct v4l2_device *v4l2_dev = vdev->v4l2_dev;
+
+- Device node name
+
+The :c:type:`video_device` node kernel name can be retrieved using:
+
+ :c:func:`video_device_node_name <video_device_node_name>`
+ (:c:type:`vdev <video_device>`);
+
+The name is used as a hint by userspace tools such as udev. The function
+should be used where possible instead of accessing the video_device::num and
+video_device::minor fields.
+
+video_device functions and data structures
+------------------------------------------
+
+.. kernel-doc:: include/media/v4l2-dev.h
diff --git a/Documentation/driver-api/media/v4l2-device.rst b/Documentation/driver-api/media/v4l2-device.rst
new file mode 100644
index 000000000000..7bd9c45f551b
--- /dev/null
+++ b/Documentation/driver-api/media/v4l2-device.rst
@@ -0,0 +1,146 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+V4L2 device instance
+--------------------
+
+Each device instance is represented by a struct v4l2_device.
+Very simple devices can just allocate this struct, but most of the time you
+would embed this struct inside a larger struct.
+
+You must register the device instance by calling:
+
+ :c:func:`v4l2_device_register <v4l2_device_register>`
+ (dev, :c:type:`v4l2_dev <v4l2_device>`).
+
+Registration will initialize the :c:type:`v4l2_device` struct. If the
+dev->driver_data field is ``NULL``, it will be linked to
+:c:type:`v4l2_dev <v4l2_device>` argument.
+
+Drivers that want integration with the media device framework need to set
+dev->driver_data manually to point to the driver-specific device structure
+that embed the struct v4l2_device instance. This is achieved by a
+``dev_set_drvdata()`` call before registering the V4L2 device instance.
+They must also set the struct v4l2_device mdev field to point to a
+properly initialized and registered :c:type:`media_device` instance.
+
+If :c:type:`v4l2_dev <v4l2_device>`\ ->name is empty then it will be set to a
+value derived from dev (driver name followed by the bus_id, to be precise).
+If you set it up before calling :c:func:`v4l2_device_register` then it will
+be untouched. If dev is ``NULL``, then you **must** setup
+:c:type:`v4l2_dev <v4l2_device>`\ ->name before calling
+:c:func:`v4l2_device_register`.
+
+You can use :c:func:`v4l2_device_set_name` to set the name based on a driver
+name and a driver-global atomic_t instance. This will generate names like
+``ivtv0``, ``ivtv1``, etc. If the name ends with a digit, then it will insert
+a dash: ``cx18-0``, ``cx18-1``, etc. This function returns the instance number.
+
+The first ``dev`` argument is normally the ``struct device`` pointer of a
+``pci_dev``, ``usb_interface`` or ``platform_device``. It is rare for dev to
+be ``NULL``, but it happens with ISA devices or when one device creates
+multiple PCI devices, thus making it impossible to associate
+:c:type:`v4l2_dev <v4l2_device>` with a particular parent.
+
+You can also supply a ``notify()`` callback that can be called by sub-devices
+to notify you of events. Whether you need to set this depends on the
+sub-device. Any notifications a sub-device supports must be defined in a header
+in ``include/media/subdevice.h``.
+
+V4L2 devices are unregistered by calling:
+
+ :c:func:`v4l2_device_unregister`
+ (:c:type:`v4l2_dev <v4l2_device>`).
+
+If the dev->driver_data field points to :c:type:`v4l2_dev <v4l2_device>`,
+it will be reset to ``NULL``. Unregistering will also automatically unregister
+all subdevs from the device.
+
+If you have a hotpluggable device (e.g. a USB device), then when a disconnect
+happens the parent device becomes invalid. Since :c:type:`v4l2_device` has a
+pointer to that parent device it has to be cleared as well to mark that the
+parent is gone. To do this call:
+
+ :c:func:`v4l2_device_disconnect`
+ (:c:type:`v4l2_dev <v4l2_device>`).
+
+This does *not* unregister the subdevs, so you still need to call the
+:c:func:`v4l2_device_unregister` function for that. If your driver is not
+hotpluggable, then there is no need to call :c:func:`v4l2_device_disconnect`.
+
+Sometimes you need to iterate over all devices registered by a specific
+driver. This is usually the case if multiple device drivers use the same
+hardware. E.g. the ivtvfb driver is a framebuffer driver that uses the ivtv
+hardware. The same is true for alsa drivers for example.
+
+You can iterate over all registered devices as follows:
+
+.. code-block:: c
+
+ static int callback(struct device *dev, void *p)
+ {
+ struct v4l2_device *v4l2_dev = dev_get_drvdata(dev);
+
+ /* test if this device was inited */
+ if (v4l2_dev == NULL)
+ return 0;
+ ...
+ return 0;
+ }
+
+ int iterate(void *p)
+ {
+ struct device_driver *drv;
+ int err;
+
+ /* Find driver 'ivtv' on the PCI bus.
+ pci_bus_type is a global. For USB buses use usb_bus_type. */
+ drv = driver_find("ivtv", &pci_bus_type);
+ /* iterate over all ivtv device instances */
+ err = driver_for_each_device(drv, NULL, p, callback);
+ put_driver(drv);
+ return err;
+ }
+
+Sometimes you need to keep a running counter of the device instance. This is
+commonly used to map a device instance to an index of a module option array.
+
+The recommended approach is as follows:
+
+.. code-block:: c
+
+ static atomic_t drv_instance = ATOMIC_INIT(0);
+
+ static int drv_probe(struct pci_dev *pdev, const struct pci_device_id *pci_id)
+ {
+ ...
+ state->instance = atomic_inc_return(&drv_instance) - 1;
+ }
+
+If you have multiple device nodes then it can be difficult to know when it is
+safe to unregister :c:type:`v4l2_device` for hotpluggable devices. For this
+purpose :c:type:`v4l2_device` has refcounting support. The refcount is
+increased whenever :c:func:`video_register_device` is called and it is
+decreased whenever that device node is released. When the refcount reaches
+zero, then the :c:type:`v4l2_device` release() callback is called. You can
+do your final cleanup there.
+
+If other device nodes (e.g. ALSA) are created, then you can increase and
+decrease the refcount manually as well by calling:
+
+ :c:func:`v4l2_device_get`
+ (:c:type:`v4l2_dev <v4l2_device>`).
+
+or:
+
+ :c:func:`v4l2_device_put`
+ (:c:type:`v4l2_dev <v4l2_device>`).
+
+Since the initial refcount is 1 you also need to call
+:c:func:`v4l2_device_put` in the ``disconnect()`` callback (for USB devices)
+or in the ``remove()`` callback (for e.g. PCI devices), otherwise the refcount
+will never reach 0.
+
+v4l2_device functions and data structures
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. kernel-doc:: include/media/v4l2-device.h
diff --git a/Documentation/driver-api/media/v4l2-dv-timings.rst b/Documentation/driver-api/media/v4l2-dv-timings.rst
new file mode 100644
index 000000000000..b178f931518b
--- /dev/null
+++ b/Documentation/driver-api/media/v4l2-dv-timings.rst
@@ -0,0 +1,6 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+V4L2 DV Timings functions
+^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. kernel-doc:: include/media/v4l2-dv-timings.h
diff --git a/Documentation/driver-api/media/v4l2-event.rst b/Documentation/driver-api/media/v4l2-event.rst
new file mode 100644
index 000000000000..52d4fbc5d819
--- /dev/null
+++ b/Documentation/driver-api/media/v4l2-event.rst
@@ -0,0 +1,181 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+V4L2 events
+-----------
+
+The V4L2 events provide a generic way to pass events to user space.
+The driver must use :c:type:`v4l2_fh` to be able to support V4L2 events.
+
+Events are subscribed per-filehandle. An event specification consists of a
+``type`` and is optionally associated with an object identified through the
+``id`` field. If unused, then the ``id`` is 0. So an event is uniquely
+identified by the ``(type, id)`` tuple.
+
+The :c:type:`v4l2_fh` struct has a list of subscribed events on its
+``subscribed`` field.
+
+When the user subscribes to an event, a :c:type:`v4l2_subscribed_event`
+struct is added to :c:type:`v4l2_fh`\ ``.subscribed``, one for every
+subscribed event.
+
+Each :c:type:`v4l2_subscribed_event` struct ends with a
+:c:type:`v4l2_kevent` ringbuffer, with the size given by the caller
+of :c:func:`v4l2_event_subscribe`. This ringbuffer is used to store any events
+raised by the driver.
+
+So every ``(type, ID)`` event tuple will have its own
+:c:type:`v4l2_kevent` ringbuffer. This guarantees that if a driver is
+generating lots of events of one type in a short time, then that will
+not overwrite events of another type.
+
+But if you get more events of one type than the size of the
+:c:type:`v4l2_kevent` ringbuffer, then the oldest event will be dropped
+and the new one added.
+
+The :c:type:`v4l2_kevent` struct links into the ``available``
+list of the :c:type:`v4l2_fh` struct so :ref:`VIDIOC_DQEVENT` will
+know which event to dequeue first.
+
+Finally, if the event subscription is associated with a particular object
+such as a V4L2 control, then that object needs to know about that as well
+so that an event can be raised by that object. So the ``node`` field can
+be used to link the :c:type:`v4l2_subscribed_event` struct into a list of
+such objects.
+
+So to summarize:
+
+- struct v4l2_fh has two lists: one of the ``subscribed`` events,
+ and one of the ``available`` events.
+
+- struct v4l2_subscribed_event has a ringbuffer of raised
+ (pending) events of that particular type.
+
+- If struct v4l2_subscribed_event is associated with a specific
+ object, then that object will have an internal list of
+ struct v4l2_subscribed_event so it knows who subscribed an
+ event to that object.
+
+Furthermore, the internal struct v4l2_subscribed_event has
+``merge()`` and ``replace()`` callbacks which drivers can set. These
+callbacks are called when a new event is raised and there is no more room.
+
+The ``replace()`` callback allows you to replace the payload of the old event
+with that of the new event, merging any relevant data from the old payload
+into the new payload that replaces it. It is called when this event type has
+a ringbuffer with size is one, i.e. only one event can be stored in the
+ringbuffer.
+
+The ``merge()`` callback allows you to merge the oldest event payload into
+that of the second-oldest event payload. It is called when
+the ringbuffer has size is greater than one.
+
+This way no status information is lost, just the intermediate steps leading
+up to that state.
+
+A good example of these ``replace``/``merge`` callbacks is in v4l2-event.c:
+``ctrls_replace()`` and ``ctrls_merge()`` callbacks for the control event.
+
+.. note::
+ these callbacks can be called from interrupt context, so they must
+ be fast.
+
+In order to queue events to video device, drivers should call:
+
+ :c:func:`v4l2_event_queue <v4l2_event_queue>`
+ (:c:type:`vdev <video_device>`, :c:type:`ev <v4l2_event>`)
+
+The driver's only responsibility is to fill in the type and the data fields.
+The other fields will be filled in by V4L2.
+
+Event subscription
+~~~~~~~~~~~~~~~~~~
+
+Subscribing to an event is via:
+
+ :c:func:`v4l2_event_subscribe <v4l2_event_subscribe>`
+ (:c:type:`fh <v4l2_fh>`, :c:type:`sub <v4l2_event_subscription>` ,
+ elems, :c:type:`ops <v4l2_subscribed_event_ops>`)
+
+
+This function is used to implement :c:type:`video_device`->
+:c:type:`ioctl_ops <v4l2_ioctl_ops>`-> ``vidioc_subscribe_event``,
+but the driver must check first if the driver is able to produce events
+with specified event id, and then should call
+:c:func:`v4l2_event_subscribe` to subscribe the event.
+
+The elems argument is the size of the event queue for this event. If it is 0,
+then the framework will fill in a default value (this depends on the event
+type).
+
+The ops argument allows the driver to specify a number of callbacks:
+
+.. tabularcolumns:: |p{1.5cm}|p{16.0cm}|
+
+======== ==============================================================
+Callback Description
+======== ==============================================================
+add called when a new listener gets added (subscribing to the same
+ event twice will only cause this callback to get called once)
+del called when a listener stops listening
+replace replace event 'old' with event 'new'.
+merge merge event 'old' into event 'new'.
+======== ==============================================================
+
+All 4 callbacks are optional, if you don't want to specify any callbacks
+the ops argument itself maybe ``NULL``.
+
+Unsubscribing an event
+~~~~~~~~~~~~~~~~~~~~~~
+
+Unsubscribing to an event is via:
+
+ :c:func:`v4l2_event_unsubscribe <v4l2_event_unsubscribe>`
+ (:c:type:`fh <v4l2_fh>`, :c:type:`sub <v4l2_event_subscription>`)
+
+This function is used to implement :c:type:`video_device`->
+:c:type:`ioctl_ops <v4l2_ioctl_ops>`-> ``vidioc_unsubscribe_event``.
+A driver may call :c:func:`v4l2_event_unsubscribe` directly unless it
+wants to be involved in unsubscription process.
+
+The special type ``V4L2_EVENT_ALL`` may be used to unsubscribe all events. The
+drivers may want to handle this in a special way.
+
+Check if there's a pending event
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Checking if there's a pending event is via:
+
+ :c:func:`v4l2_event_pending <v4l2_event_pending>`
+ (:c:type:`fh <v4l2_fh>`)
+
+
+This function returns the number of pending events. Useful when implementing
+poll.
+
+How events work
+~~~~~~~~~~~~~~~
+
+Events are delivered to user space through the poll system call. The driver
+can use :c:type:`v4l2_fh`->wait (a wait_queue_head_t) as the argument for
+``poll_wait()``.
+
+There are standard and private events. New standard events must use the
+smallest available event type. The drivers must allocate their events from
+their own class starting from class base. Class base is
+``V4L2_EVENT_PRIVATE_START`` + n * 1000 where n is the lowest available number.
+The first event type in the class is reserved for future use, so the first
+available event type is 'class base + 1'.
+
+An example on how the V4L2 events may be used can be found in the OMAP
+3 ISP driver (``drivers/media/platform/ti/omap3isp``).
+
+A subdev can directly send an event to the :c:type:`v4l2_device` notify
+function with ``V4L2_DEVICE_NOTIFY_EVENT``. This allows the bridge to map
+the subdev that sends the event to the video node(s) associated with the
+subdev that need to be informed about such an event.
+
+V4L2 event functions and data structures
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. kernel-doc:: include/media/v4l2-event.h
+
diff --git a/Documentation/driver-api/media/v4l2-fh.rst b/Documentation/driver-api/media/v4l2-fh.rst
new file mode 100644
index 000000000000..3eeaa8da0c9e
--- /dev/null
+++ b/Documentation/driver-api/media/v4l2-fh.rst
@@ -0,0 +1,141 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+V4L2 File handlers
+------------------
+
+struct v4l2_fh provides a way to easily keep file handle specific
+data that is used by the V4L2 framework.
+
+.. attention::
+ New drivers must use struct v4l2_fh
+ since it is also used to implement priority handling
+ (:ref:`VIDIOC_G_PRIORITY`).
+
+The users of :c:type:`v4l2_fh` (in the V4L2 framework, not the driver) know
+whether a driver uses :c:type:`v4l2_fh` as its ``file->private_data`` pointer
+by testing the ``V4L2_FL_USES_V4L2_FH`` bit in :c:type:`video_device`->flags.
+This bit is set whenever :c:func:`v4l2_fh_init` is called.
+
+struct v4l2_fh is allocated as a part of the driver's own file handle
+structure and ``file->private_data`` is set to it in the driver's ``open()``
+function by the driver.
+
+In many cases the struct v4l2_fh will be embedded in a larger
+structure. In that case you should call:
+
+#) :c:func:`v4l2_fh_init` and :c:func:`v4l2_fh_add` in ``open()``
+#) :c:func:`v4l2_fh_del` and :c:func:`v4l2_fh_exit` in ``release()``
+
+Drivers can extract their own file handle structure by using the container_of
+macro.
+
+Example:
+
+.. code-block:: c
+
+ struct my_fh {
+ int blah;
+ struct v4l2_fh fh;
+ };
+
+ ...
+
+ int my_open(struct file *file)
+ {
+ struct my_fh *my_fh;
+ struct video_device *vfd;
+ int ret;
+
+ ...
+
+ my_fh = kzalloc(sizeof(*my_fh), GFP_KERNEL);
+
+ ...
+
+ v4l2_fh_init(&my_fh->fh, vfd);
+
+ ...
+
+ file->private_data = &my_fh->fh;
+ v4l2_fh_add(&my_fh->fh);
+ return 0;
+ }
+
+ int my_release(struct file *file)
+ {
+ struct v4l2_fh *fh = file->private_data;
+ struct my_fh *my_fh = container_of(fh, struct my_fh, fh);
+
+ ...
+ v4l2_fh_del(&my_fh->fh);
+ v4l2_fh_exit(&my_fh->fh);
+ kfree(my_fh);
+ return 0;
+ }
+
+Below is a short description of the :c:type:`v4l2_fh` functions used:
+
+:c:func:`v4l2_fh_init <v4l2_fh_init>`
+(:c:type:`fh <v4l2_fh>`, :c:type:`vdev <video_device>`)
+
+
+- Initialise the file handle. This **MUST** be performed in the driver's
+ :c:type:`v4l2_file_operations`->open() handler.
+
+
+:c:func:`v4l2_fh_add <v4l2_fh_add>`
+(:c:type:`fh <v4l2_fh>`)
+
+- Add a :c:type:`v4l2_fh` to :c:type:`video_device` file handle list.
+ Must be called once the file handle is completely initialized.
+
+:c:func:`v4l2_fh_del <v4l2_fh_del>`
+(:c:type:`fh <v4l2_fh>`)
+
+- Unassociate the file handle from :c:type:`video_device`. The file handle
+ exit function may now be called.
+
+:c:func:`v4l2_fh_exit <v4l2_fh_exit>`
+(:c:type:`fh <v4l2_fh>`)
+
+- Uninitialise the file handle. After uninitialisation the :c:type:`v4l2_fh`
+ memory can be freed.
+
+
+If struct v4l2_fh is not embedded, then you can use these helper functions:
+
+:c:func:`v4l2_fh_open <v4l2_fh_open>`
+(struct file \*filp)
+
+- This allocates a struct v4l2_fh, initializes it and adds it to
+ the struct video_device associated with the file struct.
+
+:c:func:`v4l2_fh_release <v4l2_fh_release>`
+(struct file \*filp)
+
+- This deletes it from the struct video_device associated with the
+ file struct, uninitialised the :c:type:`v4l2_fh` and frees it.
+
+These two functions can be plugged into the v4l2_file_operation's ``open()``
+and ``release()`` ops.
+
+Several drivers need to do something when the first file handle is opened and
+when the last file handle closes. Two helper functions were added to check
+whether the :c:type:`v4l2_fh` struct is the only open filehandle of the
+associated device node:
+
+:c:func:`v4l2_fh_is_singular <v4l2_fh_is_singular>`
+(:c:type:`fh <v4l2_fh>`)
+
+- Returns 1 if the file handle is the only open file handle, else 0.
+
+:c:func:`v4l2_fh_is_singular_file <v4l2_fh_is_singular_file>`
+(struct file \*filp)
+
+- Same, but it calls v4l2_fh_is_singular with filp->private_data.
+
+
+V4L2 fh functions and data structures
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. kernel-doc:: include/media/v4l2-fh.h
diff --git a/Documentation/driver-api/media/v4l2-flash-led-class.rst b/Documentation/driver-api/media/v4l2-flash-led-class.rst
new file mode 100644
index 000000000000..2aa6bed9b8db
--- /dev/null
+++ b/Documentation/driver-api/media/v4l2-flash-led-class.rst
@@ -0,0 +1,6 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+V4L2 flash functions and data structures
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. kernel-doc:: include/media/v4l2-flash-led-class.h
diff --git a/Documentation/driver-api/media/v4l2-fwnode.rst b/Documentation/driver-api/media/v4l2-fwnode.rst
new file mode 100644
index 000000000000..e313b6cddcd0
--- /dev/null
+++ b/Documentation/driver-api/media/v4l2-fwnode.rst
@@ -0,0 +1,5 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+V4L2 fwnode kAPI
+^^^^^^^^^^^^^^^^
+.. kernel-doc:: include/media/v4l2-fwnode.h
diff --git a/Documentation/driver-api/media/v4l2-intro.rst b/Documentation/driver-api/media/v4l2-intro.rst
new file mode 100644
index 000000000000..4d54fa9d7a12
--- /dev/null
+++ b/Documentation/driver-api/media/v4l2-intro.rst
@@ -0,0 +1,76 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+Introduction
+------------
+
+The V4L2 drivers tend to be very complex due to the complexity of the
+hardware: most devices have multiple ICs, export multiple device nodes in
+/dev, and create also non-V4L2 devices such as DVB, ALSA, FB, I2C and input
+(IR) devices.
+
+Especially the fact that V4L2 drivers have to setup supporting ICs to
+do audio/video muxing/encoding/decoding makes it more complex than most.
+Usually these ICs are connected to the main bridge driver through one or
+more I2C buses, but other buses can also be used. Such devices are
+called 'sub-devices'.
+
+For a long time the framework was limited to the video_device struct for
+creating V4L device nodes and video_buf for handling the video buffers
+(note that this document does not discuss the video_buf framework).
+
+This meant that all drivers had to do the setup of device instances and
+connecting to sub-devices themselves. Some of this is quite complicated
+to do right and many drivers never did do it correctly.
+
+There is also a lot of common code that could never be refactored due to
+the lack of a framework.
+
+So this framework sets up the basic building blocks that all drivers
+need and this same framework should make it much easier to refactor
+common code into utility functions shared by all drivers.
+
+A good example to look at as a reference is the v4l2-pci-skeleton.c
+source that is available in samples/v4l/. It is a skeleton driver for
+a PCI capture card, and demonstrates how to use the V4L2 driver
+framework. It can be used as a template for real PCI video capture driver.
+
+Structure of a V4L driver
+-------------------------
+
+All drivers have the following structure:
+
+1) A struct for each device instance containing the device state.
+
+2) A way of initializing and commanding sub-devices (if any).
+
+3) Creating V4L2 device nodes (/dev/videoX, /dev/vbiX and /dev/radioX)
+ and keeping track of device-node specific data.
+
+4) Filehandle-specific structs containing per-filehandle data;
+
+5) video buffer handling.
+
+This is a rough schematic of how it all relates:
+
+.. code-block:: none
+
+ device instances
+ |
+ +-sub-device instances
+ |
+ \-V4L2 device nodes
+ |
+ \-filehandle instances
+
+
+Structure of the V4L2 framework
+-------------------------------
+
+The framework closely resembles the driver structure: it has a v4l2_device
+struct for the device instance data, a v4l2_subdev struct to refer to
+sub-device instances, the video_device struct stores V4L2 device node data
+and the v4l2_fh struct keeps track of filehandle instances.
+
+The V4L2 framework also optionally integrates with the media framework. If a
+driver sets the struct v4l2_device mdev field, sub-devices and video nodes
+will automatically appear in the media framework as entities.
diff --git a/Documentation/driver-api/media/v4l2-mc.rst b/Documentation/driver-api/media/v4l2-mc.rst
new file mode 100644
index 000000000000..0c352ac588b2
--- /dev/null
+++ b/Documentation/driver-api/media/v4l2-mc.rst
@@ -0,0 +1,6 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+V4L2 Media Controller functions and data structures
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. kernel-doc:: include/media/v4l2-mc.h
diff --git a/Documentation/driver-api/media/v4l2-mediabus.rst b/Documentation/driver-api/media/v4l2-mediabus.rst
new file mode 100644
index 000000000000..1f2254cba92d
--- /dev/null
+++ b/Documentation/driver-api/media/v4l2-mediabus.rst
@@ -0,0 +1,6 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+V4L2 Media Bus functions and data structures
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. kernel-doc:: include/media/v4l2-mediabus.h
diff --git a/Documentation/driver-api/media/v4l2-mem2mem.rst b/Documentation/driver-api/media/v4l2-mem2mem.rst
new file mode 100644
index 000000000000..a43b31cc8261
--- /dev/null
+++ b/Documentation/driver-api/media/v4l2-mem2mem.rst
@@ -0,0 +1,6 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+V4L2 Memory to Memory functions and data structures
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. kernel-doc:: include/media/v4l2-mem2mem.h
diff --git a/Documentation/driver-api/media/v4l2-rect.rst b/Documentation/driver-api/media/v4l2-rect.rst
new file mode 100644
index 000000000000..fc315cd84156
--- /dev/null
+++ b/Documentation/driver-api/media/v4l2-rect.rst
@@ -0,0 +1,6 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+V4L2 rect helper functions
+^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. kernel-doc:: include/media/v4l2-rect.h
diff --git a/Documentation/driver-api/media/v4l2-subdev.rst b/Documentation/driver-api/media/v4l2-subdev.rst
new file mode 100644
index 000000000000..1db2ba27c54c
--- /dev/null
+++ b/Documentation/driver-api/media/v4l2-subdev.rst
@@ -0,0 +1,644 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+V4L2 sub-devices
+----------------
+
+Many drivers need to communicate with sub-devices. These devices can do all
+sort of tasks, but most commonly they handle audio and/or video muxing,
+encoding or decoding. For webcams common sub-devices are sensors and camera
+controllers.
+
+Usually these are I2C devices, but not necessarily. In order to provide the
+driver with a consistent interface to these sub-devices the
+:c:type:`v4l2_subdev` struct (v4l2-subdev.h) was created.
+
+Each sub-device driver must have a :c:type:`v4l2_subdev` struct. This struct
+can be stand-alone for simple sub-devices or it might be embedded in a larger
+struct if more state information needs to be stored. Usually there is a
+low-level device struct (e.g. ``i2c_client``) that contains the device data as
+setup by the kernel. It is recommended to store that pointer in the private
+data of :c:type:`v4l2_subdev` using :c:func:`v4l2_set_subdevdata`. That makes
+it easy to go from a :c:type:`v4l2_subdev` to the actual low-level bus-specific
+device data.
+
+You also need a way to go from the low-level struct to :c:type:`v4l2_subdev`.
+For the common i2c_client struct the i2c_set_clientdata() call is used to store
+a :c:type:`v4l2_subdev` pointer, for other buses you may have to use other
+methods.
+
+Bridges might also need to store per-subdev private data, such as a pointer to
+bridge-specific per-subdev private data. The :c:type:`v4l2_subdev` structure
+provides host private data for that purpose that can be accessed with
+:c:func:`v4l2_get_subdev_hostdata` and :c:func:`v4l2_set_subdev_hostdata`.
+
+From the bridge driver perspective, you load the sub-device module and somehow
+obtain the :c:type:`v4l2_subdev` pointer. For i2c devices this is easy: you call
+``i2c_get_clientdata()``. For other buses something similar needs to be done.
+Helper functions exist for sub-devices on an I2C bus that do most of this
+tricky work for you.
+
+Each :c:type:`v4l2_subdev` contains function pointers that sub-device drivers
+can implement (or leave ``NULL`` if it is not applicable). Since sub-devices can
+do so many different things and you do not want to end up with a huge ops struct
+of which only a handful of ops are commonly implemented, the function pointers
+are sorted according to category and each category has its own ops struct.
+
+The top-level ops struct contains pointers to the category ops structs, which
+may be NULL if the subdev driver does not support anything from that category.
+
+It looks like this:
+
+.. code-block:: c
+
+ struct v4l2_subdev_core_ops {
+ int (*log_status)(struct v4l2_subdev *sd);
+ int (*init)(struct v4l2_subdev *sd, u32 val);
+ ...
+ };
+
+ struct v4l2_subdev_tuner_ops {
+ ...
+ };
+
+ struct v4l2_subdev_audio_ops {
+ ...
+ };
+
+ struct v4l2_subdev_video_ops {
+ ...
+ };
+
+ struct v4l2_subdev_pad_ops {
+ ...
+ };
+
+ struct v4l2_subdev_ops {
+ const struct v4l2_subdev_core_ops *core;
+ const struct v4l2_subdev_tuner_ops *tuner;
+ const struct v4l2_subdev_audio_ops *audio;
+ const struct v4l2_subdev_video_ops *video;
+ const struct v4l2_subdev_pad_ops *video;
+ };
+
+The core ops are common to all subdevs, the other categories are implemented
+depending on the sub-device. E.g. a video device is unlikely to support the
+audio ops and vice versa.
+
+This setup limits the number of function pointers while still making it easy
+to add new ops and categories.
+
+A sub-device driver initializes the :c:type:`v4l2_subdev` struct using:
+
+ :c:func:`v4l2_subdev_init <v4l2_subdev_init>`
+ (:c:type:`sd <v4l2_subdev>`, &\ :c:type:`ops <v4l2_subdev_ops>`).
+
+
+Afterwards you need to initialize :c:type:`sd <v4l2_subdev>`->name with a
+unique name and set the module owner. This is done for you if you use the
+i2c helper functions.
+
+If integration with the media framework is needed, you must initialize the
+:c:type:`media_entity` struct embedded in the :c:type:`v4l2_subdev` struct
+(entity field) by calling :c:func:`media_entity_pads_init`, if the entity has
+pads:
+
+.. code-block:: c
+
+ struct media_pad *pads = &my_sd->pads;
+ int err;
+
+ err = media_entity_pads_init(&sd->entity, npads, pads);
+
+The pads array must have been previously initialized. There is no need to
+manually set the struct media_entity function and name fields, but the
+revision field must be initialized if needed.
+
+A reference to the entity will be automatically acquired/released when the
+subdev device node (if any) is opened/closed.
+
+Don't forget to cleanup the media entity before the sub-device is destroyed:
+
+.. code-block:: c
+
+ media_entity_cleanup(&sd->entity);
+
+If a sub-device driver implements sink pads, the subdev driver may set the
+link_validate field in :c:type:`v4l2_subdev_pad_ops` to provide its own link
+validation function. For every link in the pipeline, the link_validate pad
+operation of the sink end of the link is called. In both cases the driver is
+still responsible for validating the correctness of the format configuration
+between sub-devices and video nodes.
+
+If link_validate op is not set, the default function
+:c:func:`v4l2_subdev_link_validate_default` is used instead. This function
+ensures that width, height and the media bus pixel code are equal on both source
+and sink of the link. Subdev drivers are also free to use this function to
+perform the checks mentioned above in addition to their own checks.
+
+Subdev registration
+~~~~~~~~~~~~~~~~~~~
+
+There are currently two ways to register subdevices with the V4L2 core. The
+first (traditional) possibility is to have subdevices registered by bridge
+drivers. This can be done when the bridge driver has the complete information
+about subdevices connected to it and knows exactly when to register them. This
+is typically the case for internal subdevices, like video data processing units
+within SoCs or complex PCI(e) boards, camera sensors in USB cameras or connected
+to SoCs, which pass information about them to bridge drivers, usually in their
+platform data.
+
+There are however also situations where subdevices have to be registered
+asynchronously to bridge devices. An example of such a configuration is a Device
+Tree based system where information about subdevices is made available to the
+system independently from the bridge devices, e.g. when subdevices are defined
+in DT as I2C device nodes. The API used in this second case is described further
+below.
+
+Using one or the other registration method only affects the probing process, the
+run-time bridge-subdevice interaction is in both cases the same.
+
+Registering synchronous sub-devices
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+In the **synchronous** case a device (bridge) driver needs to register the
+:c:type:`v4l2_subdev` with the v4l2_device:
+
+ :c:func:`v4l2_device_register_subdev <v4l2_device_register_subdev>`
+ (:c:type:`v4l2_dev <v4l2_device>`, :c:type:`sd <v4l2_subdev>`).
+
+This can fail if the subdev module disappeared before it could be registered.
+After this function was called successfully the subdev->dev field points to
+the :c:type:`v4l2_device`.
+
+If the v4l2_device parent device has a non-NULL mdev field, the sub-device
+entity will be automatically registered with the media device.
+
+You can unregister a sub-device using:
+
+ :c:func:`v4l2_device_unregister_subdev <v4l2_device_unregister_subdev>`
+ (:c:type:`sd <v4l2_subdev>`).
+
+Afterwards the subdev module can be unloaded and
+:c:type:`sd <v4l2_subdev>`->dev == ``NULL``.
+
+.. _media-registering-async-subdevs:
+
+Registering asynchronous sub-devices
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+In the **asynchronous** case subdevice probing can be invoked independently of
+the bridge driver availability. The subdevice driver then has to verify whether
+all the requirements for a successful probing are satisfied. This can include a
+check for a master clock availability. If any of the conditions aren't satisfied
+the driver might decide to return ``-EPROBE_DEFER`` to request further reprobing
+attempts. Once all conditions are met the subdevice shall be registered using
+the :c:func:`v4l2_async_register_subdev` function. Unregistration is
+performed using the :c:func:`v4l2_async_unregister_subdev` call. Subdevices
+registered this way are stored in a global list of subdevices, ready to be
+picked up by bridge drivers.
+
+Drivers must complete all initialization of the sub-device before
+registering it using :c:func:`v4l2_async_register_subdev`, including
+enabling runtime PM. This is because the sub-device becomes accessible
+as soon as it gets registered.
+
+Asynchronous sub-device notifiers
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Bridge drivers in turn have to register a notifier object. This is performed
+using the :c:func:`v4l2_async_nf_register` call. To unregister the notifier the
+driver has to call :c:func:`v4l2_async_nf_unregister`. Before releasing memory
+of an unregister notifier, it must be cleaned up by calling
+:c:func:`v4l2_async_nf_cleanup`.
+
+Before registering the notifier, bridge drivers must do two things: first, the
+notifier must be initialized using the :c:func:`v4l2_async_nf_init`. Second,
+bridge drivers can then begin to form a list of async connection descriptors
+that the bridge device needs for its
+operation. :c:func:`v4l2_async_nf_add_fwnode`,
+:c:func:`v4l2_async_nf_add_fwnode_remote` and :c:func:`v4l2_async_nf_add_i2c`
+
+Async connection descriptors describe connections to external sub-devices the
+drivers for which are not yet probed. Based on an async connection, a media data
+or ancillary link may be created when the related sub-device becomes
+available. There may be one or more async connections to a given sub-device but
+this is not known at the time of adding the connections to the notifier. Async
+connections are bound as matching async sub-devices are found, one by one.
+
+Asynchronous sub-device notifier for sub-devices
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+A driver that registers an asynchronous sub-device may also register an
+asynchronous notifier. This is called an asynchronous sub-device notifier andthe
+process is similar to that of a bridge driver apart from that the notifier is
+initialised using :c:func:`v4l2_async_subdev_nf_init` instead. A sub-device
+notifier may complete only after the V4L2 device becomes available, i.e. there's
+a path via async sub-devices and notifiers to a notifier that is not an
+asynchronous sub-device notifier.
+
+Asynchronous sub-device registration helper for camera sensor drivers
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+:c:func:`v4l2_async_register_subdev_sensor` is a helper function for sensor
+drivers registering their own async connection, but it also registers a notifier
+and further registers async connections for lens and flash devices found in
+firmware. The notifier for the sub-device is unregistered and cleaned up with
+the async sub-device, using :c:func:`v4l2_async_unregister_subdev`.
+
+Asynchronous sub-device notifier example
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+These functions allocate an async connection descriptor which is of type struct
+:c:type:`v4l2_async_connection` embedded in a driver-specific struct. The &struct
+:c:type:`v4l2_async_connection` shall be the first member of this struct:
+
+.. code-block:: c
+
+ struct my_async_connection {
+ struct v4l2_async_connection asc;
+ ...
+ };
+
+ struct my_async_connection *my_asc;
+ struct fwnode_handle *ep;
+
+ ...
+
+ my_asc = v4l2_async_nf_add_fwnode_remote(&notifier, ep,
+ struct my_async_connection);
+ fwnode_handle_put(ep);
+
+ if (IS_ERR(my_asc))
+ return PTR_ERR(my_asc);
+
+Asynchronous sub-device notifier callbacks
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The V4L2 core will then use these connection descriptors to match asynchronously
+registered subdevices to them. If a match is detected the ``.bound()`` notifier
+callback is called. After all connections have been bound the .complete()
+callback is called. When a connection is removed from the system the
+``.unbind()`` method is called. All three callbacks are optional.
+
+Drivers can store any type of custom data in their driver-specific
+:c:type:`v4l2_async_connection` wrapper. If any of that data requires special
+handling when the structure is freed, drivers must implement the ``.destroy()``
+notifier callback. The framework will call it right before freeing the
+:c:type:`v4l2_async_connection`.
+
+Calling subdev operations
+~~~~~~~~~~~~~~~~~~~~~~~~~
+
+The advantage of using :c:type:`v4l2_subdev` is that it is a generic struct and
+does not contain any knowledge about the underlying hardware. So a driver might
+contain several subdevs that use an I2C bus, but also a subdev that is
+controlled through GPIO pins. This distinction is only relevant when setting
+up the device, but once the subdev is registered it is completely transparent.
+
+Once the subdev has been registered you can call an ops function either
+directly:
+
+.. code-block:: c
+
+ err = sd->ops->core->g_std(sd, &norm);
+
+but it is better and easier to use this macro:
+
+.. code-block:: c
+
+ err = v4l2_subdev_call(sd, core, g_std, &norm);
+
+The macro will do the right ``NULL`` pointer checks and returns ``-ENODEV``
+if :c:type:`sd <v4l2_subdev>` is ``NULL``, ``-ENOIOCTLCMD`` if either
+:c:type:`sd <v4l2_subdev>`->core or :c:type:`sd <v4l2_subdev>`->core->g_std is ``NULL``, or the actual result of the
+:c:type:`sd <v4l2_subdev>`->ops->core->g_std ops.
+
+It is also possible to call all or a subset of the sub-devices:
+
+.. code-block:: c
+
+ v4l2_device_call_all(v4l2_dev, 0, core, g_std, &norm);
+
+Any subdev that does not support this ops is skipped and error results are
+ignored. If you want to check for errors use this:
+
+.. code-block:: c
+
+ err = v4l2_device_call_until_err(v4l2_dev, 0, core, g_std, &norm);
+
+Any error except ``-ENOIOCTLCMD`` will exit the loop with that error. If no
+errors (except ``-ENOIOCTLCMD``) occurred, then 0 is returned.
+
+The second argument to both calls is a group ID. If 0, then all subdevs are
+called. If non-zero, then only those whose group ID match that value will
+be called. Before a bridge driver registers a subdev it can set
+:c:type:`sd <v4l2_subdev>`->grp_id to whatever value it wants (it's 0 by
+default). This value is owned by the bridge driver and the sub-device driver
+will never modify or use it.
+
+The group ID gives the bridge driver more control how callbacks are called.
+For example, there may be multiple audio chips on a board, each capable of
+changing the volume. But usually only one will actually be used when the
+user want to change the volume. You can set the group ID for that subdev to
+e.g. AUDIO_CONTROLLER and specify that as the group ID value when calling
+``v4l2_device_call_all()``. That ensures that it will only go to the subdev
+that needs it.
+
+If the sub-device needs to notify its v4l2_device parent of an event, then
+it can call ``v4l2_subdev_notify(sd, notification, arg)``. This macro checks
+whether there is a ``notify()`` callback defined and returns ``-ENODEV`` if not.
+Otherwise the result of the ``notify()`` call is returned.
+
+V4L2 sub-device userspace API
+-----------------------------
+
+Bridge drivers traditionally expose one or multiple video nodes to userspace,
+and control subdevices through the :c:type:`v4l2_subdev_ops` operations in
+response to video node operations. This hides the complexity of the underlying
+hardware from applications. For complex devices, finer-grained control of the
+device than what the video nodes offer may be required. In those cases, bridge
+drivers that implement :ref:`the media controller API <media_controller>` may
+opt for making the subdevice operations directly accessible from userspace.
+
+Device nodes named ``v4l-subdev``\ *X* can be created in ``/dev`` to access
+sub-devices directly. If a sub-device supports direct userspace configuration
+it must set the ``V4L2_SUBDEV_FL_HAS_DEVNODE`` flag before being registered.
+
+After registering sub-devices, the :c:type:`v4l2_device` driver can create
+device nodes for all registered sub-devices marked with
+``V4L2_SUBDEV_FL_HAS_DEVNODE`` by calling
+:c:func:`v4l2_device_register_subdev_nodes`. Those device nodes will be
+automatically removed when sub-devices are unregistered.
+
+The device node handles a subset of the V4L2 API.
+
+``VIDIOC_QUERYCTRL``,
+``VIDIOC_QUERYMENU``,
+``VIDIOC_G_CTRL``,
+``VIDIOC_S_CTRL``,
+``VIDIOC_G_EXT_CTRLS``,
+``VIDIOC_S_EXT_CTRLS`` and
+``VIDIOC_TRY_EXT_CTRLS``:
+
+ The controls ioctls are identical to the ones defined in V4L2. They
+ behave identically, with the only exception that they deal only with
+ controls implemented in the sub-device. Depending on the driver, those
+ controls can be also be accessed through one (or several) V4L2 device
+ nodes.
+
+``VIDIOC_DQEVENT``,
+``VIDIOC_SUBSCRIBE_EVENT`` and
+``VIDIOC_UNSUBSCRIBE_EVENT``
+
+ The events ioctls are identical to the ones defined in V4L2. They
+ behave identically, with the only exception that they deal only with
+ events generated by the sub-device. Depending on the driver, those
+ events can also be reported by one (or several) V4L2 device nodes.
+
+ Sub-device drivers that want to use events need to set the
+ ``V4L2_SUBDEV_FL_HAS_EVENTS`` :c:type:`v4l2_subdev`.flags before registering
+ the sub-device. After registration events can be queued as usual on the
+ :c:type:`v4l2_subdev`.devnode device node.
+
+ To properly support events, the ``poll()`` file operation is also
+ implemented.
+
+Private ioctls
+
+ All ioctls not in the above list are passed directly to the sub-device
+ driver through the core::ioctl operation.
+
+Read-only sub-device userspace API
+----------------------------------
+
+Bridge drivers that control their connected subdevices through direct calls to
+the kernel API realized by :c:type:`v4l2_subdev_ops` structure do not usually
+want userspace to be able to change the same parameters through the subdevice
+device node and thus do not usually register any.
+
+It is sometimes useful to report to userspace the current subdevice
+configuration through a read-only API, that does not permit applications to
+change to the device parameters but allows interfacing to the subdevice device
+node to inspect them.
+
+For instance, to implement cameras based on computational photography, userspace
+needs to know the detailed camera sensor configuration (in terms of skipping,
+binning, cropping and scaling) for each supported output resolution. To support
+such use cases, bridge drivers may expose the subdevice operations to userspace
+through a read-only API.
+
+To create a read-only device node for all the subdevices registered with the
+``V4L2_SUBDEV_FL_HAS_DEVNODE`` set, the :c:type:`v4l2_device` driver should call
+:c:func:`v4l2_device_register_ro_subdev_nodes`.
+
+Access to the following ioctls for userspace applications is restricted on
+sub-device device nodes registered with
+:c:func:`v4l2_device_register_ro_subdev_nodes`.
+
+``VIDIOC_SUBDEV_S_FMT``,
+``VIDIOC_SUBDEV_S_CROP``,
+``VIDIOC_SUBDEV_S_SELECTION``:
+
+ These ioctls are only allowed on a read-only subdevice device node
+ for the :ref:`V4L2_SUBDEV_FORMAT_TRY <v4l2-subdev-format-whence>`
+ formats and selection rectangles.
+
+``VIDIOC_SUBDEV_S_FRAME_INTERVAL``,
+``VIDIOC_SUBDEV_S_DV_TIMINGS``,
+``VIDIOC_SUBDEV_S_STD``:
+
+ These ioctls are not allowed on a read-only subdevice node.
+
+In case the ioctl is not allowed, or the format to modify is set to
+``V4L2_SUBDEV_FORMAT_ACTIVE``, the core returns a negative error code and
+the errno variable is set to ``-EPERM``.
+
+I2C sub-device drivers
+----------------------
+
+Since these drivers are so common, special helper functions are available to
+ease the use of these drivers (``v4l2-common.h``).
+
+The recommended method of adding :c:type:`v4l2_subdev` support to an I2C driver
+is to embed the :c:type:`v4l2_subdev` struct into the state struct that is
+created for each I2C device instance. Very simple devices have no state
+struct and in that case you can just create a :c:type:`v4l2_subdev` directly.
+
+A typical state struct would look like this (where 'chipname' is replaced by
+the name of the chip):
+
+.. code-block:: c
+
+ struct chipname_state {
+ struct v4l2_subdev sd;
+ ... /* additional state fields */
+ };
+
+Initialize the :c:type:`v4l2_subdev` struct as follows:
+
+.. code-block:: c
+
+ v4l2_i2c_subdev_init(&state->sd, client, subdev_ops);
+
+This function will fill in all the fields of :c:type:`v4l2_subdev` ensure that
+the :c:type:`v4l2_subdev` and i2c_client both point to one another.
+
+You should also add a helper inline function to go from a :c:type:`v4l2_subdev`
+pointer to a chipname_state struct:
+
+.. code-block:: c
+
+ static inline struct chipname_state *to_state(struct v4l2_subdev *sd)
+ {
+ return container_of(sd, struct chipname_state, sd);
+ }
+
+Use this to go from the :c:type:`v4l2_subdev` struct to the ``i2c_client``
+struct:
+
+.. code-block:: c
+
+ struct i2c_client *client = v4l2_get_subdevdata(sd);
+
+And this to go from an ``i2c_client`` to a :c:type:`v4l2_subdev` struct:
+
+.. code-block:: c
+
+ struct v4l2_subdev *sd = i2c_get_clientdata(client);
+
+Make sure to call
+:c:func:`v4l2_device_unregister_subdev`\ (:c:type:`sd <v4l2_subdev>`)
+when the ``remove()`` callback is called. This will unregister the sub-device
+from the bridge driver. It is safe to call this even if the sub-device was
+never registered.
+
+You need to do this because when the bridge driver destroys the i2c adapter
+the ``remove()`` callbacks are called of the i2c devices on that adapter.
+After that the corresponding v4l2_subdev structures are invalid, so they
+have to be unregistered first. Calling
+:c:func:`v4l2_device_unregister_subdev`\ (:c:type:`sd <v4l2_subdev>`)
+from the ``remove()`` callback ensures that this is always done correctly.
+
+
+The bridge driver also has some helper functions it can use:
+
+.. code-block:: c
+
+ struct v4l2_subdev *sd = v4l2_i2c_new_subdev(v4l2_dev, adapter,
+ "module_foo", "chipid", 0x36, NULL);
+
+This loads the given module (can be ``NULL`` if no module needs to be loaded)
+and calls :c:func:`i2c_new_client_device` with the given ``i2c_adapter`` and
+chip/address arguments. If all goes well, then it registers the subdev with
+the v4l2_device.
+
+You can also use the last argument of :c:func:`v4l2_i2c_new_subdev` to pass
+an array of possible I2C addresses that it should probe. These probe addresses
+are only used if the previous argument is 0. A non-zero argument means that you
+know the exact i2c address so in that case no probing will take place.
+
+Both functions return ``NULL`` if something went wrong.
+
+Note that the chipid you pass to :c:func:`v4l2_i2c_new_subdev` is usually
+the same as the module name. It allows you to specify a chip variant, e.g.
+"saa7114" or "saa7115". In general though the i2c driver autodetects this.
+The use of chipid is something that needs to be looked at more closely at a
+later date. It differs between i2c drivers and as such can be confusing.
+To see which chip variants are supported you can look in the i2c driver code
+for the i2c_device_id table. This lists all the possibilities.
+
+There are one more helper function:
+
+:c:func:`v4l2_i2c_new_subdev_board` uses an :c:type:`i2c_board_info` struct
+which is passed to the i2c driver and replaces the irq, platform_data and addr
+arguments.
+
+If the subdev supports the s_config core ops, then that op is called with
+the irq and platform_data arguments after the subdev was setup.
+
+The :c:func:`v4l2_i2c_new_subdev` function will call
+:c:func:`v4l2_i2c_new_subdev_board`, internally filling a
+:c:type:`i2c_board_info` structure using the ``client_type`` and the
+``addr`` to fill it.
+
+Centrally managed subdev active state
+-------------------------------------
+
+Traditionally V4L2 subdev drivers maintained internal state for the active
+device configuration. This is often implemented as e.g. an array of struct
+v4l2_mbus_framefmt, one entry for each pad, and similarly for crop and compose
+rectangles.
+
+In addition to the active configuration, each subdev file handle has a struct
+v4l2_subdev_state, managed by the V4L2 core, which contains the try
+configuration.
+
+To simplify the subdev drivers the V4L2 subdev API now optionally supports a
+centrally managed active configuration represented by
+:c:type:`v4l2_subdev_state`. One instance of state, which contains the active
+device configuration, is stored in the sub-device itself as part of
+the :c:type:`v4l2_subdev` structure, while the core associates a try state to
+each open file handle, to store the try configuration related to that file
+handle.
+
+Sub-device drivers can opt-in and use state to manage their active configuration
+by initializing the subdevice state with a call to v4l2_subdev_init_finalize()
+before registering the sub-device. They must also call v4l2_subdev_cleanup()
+to release all the allocated resources before unregistering the sub-device.
+The core automatically allocates and initializes a state for each open file
+handle to store the try configurations and frees it when closing the file
+handle.
+
+V4L2 sub-device operations that use both the :ref:`ACTIVE and TRY formats
+<v4l2-subdev-format-whence>` receive the correct state to operate on through
+the 'state' parameter. The state must be locked and unlocked by the
+caller by calling :c:func:`v4l2_subdev_lock_state()` and
+:c:func:`v4l2_subdev_unlock_state()`. The caller can do so by calling the subdev
+operation through the :c:func:`v4l2_subdev_call_state_active()` macro.
+
+Operations that do not receive a state parameter implicitly operate on the
+subdevice active state, which drivers can exclusively access by
+calling :c:func:`v4l2_subdev_lock_and_get_active_state()`. The sub-device active
+state must equally be released by calling :c:func:`v4l2_subdev_unlock_state()`.
+
+Drivers must never manually access the state stored in the :c:type:`v4l2_subdev`
+or in the file handle without going through the designated helpers.
+
+While the V4L2 core passes the correct try or active state to the subdevice
+operations, many existing device drivers pass a NULL state when calling
+operations with :c:func:`v4l2_subdev_call()`. This legacy construct causes
+issues with subdevice drivers that let the V4L2 core manage the active state,
+as they expect to receive the appropriate state as a parameter. To help the
+conversion of subdevice drivers to a managed active state without having to
+convert all callers at the same time, an additional wrapper layer has been
+added to v4l2_subdev_call(), which handles the NULL case by getting and locking
+the callee's active state with :c:func:`v4l2_subdev_lock_and_get_active_state()`,
+and unlocking the state after the call.
+
+The whole subdev state is in reality split into three parts: the
+v4l2_subdev_state, subdev controls and subdev driver's internal state. In the
+future these parts should be combined into a single state. For the time being
+we need a way to handle the locking for these parts. This can be accomplished
+by sharing a lock. The v4l2_ctrl_handler already supports this via its 'lock'
+pointer and the same model is used with states. The driver can do the following
+before calling v4l2_subdev_init_finalize():
+
+.. code-block:: c
+
+ sd->ctrl_handler->lock = &priv->mutex;
+ sd->state_lock = &priv->mutex;
+
+This shares the driver's private mutex between the controls and the states.
+
+Streams, multiplexed media pads and internal routing
+----------------------------------------------------
+
+A subdevice driver can implement support for multiplexed streams by setting
+the V4L2_SUBDEV_FL_STREAMS subdev flag and implementing support for
+centrally managed subdev active state, routing and stream based
+configuration.
+
+V4L2 sub-device functions and data structures
+---------------------------------------------
+
+.. kernel-doc:: include/media/v4l2-subdev.h
diff --git a/Documentation/driver-api/media/v4l2-tuner.rst b/Documentation/driver-api/media/v4l2-tuner.rst
new file mode 100644
index 000000000000..e6caa3321566
--- /dev/null
+++ b/Documentation/driver-api/media/v4l2-tuner.rst
@@ -0,0 +1,8 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+Tuner functions and data structures
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. kernel-doc:: include/media/tuner.h
+
+.. kernel-doc:: include/media/tuner-types.h
diff --git a/Documentation/driver-api/media/v4l2-tveeprom.rst b/Documentation/driver-api/media/v4l2-tveeprom.rst
new file mode 100644
index 000000000000..43fb391edaba
--- /dev/null
+++ b/Documentation/driver-api/media/v4l2-tveeprom.rst
@@ -0,0 +1,6 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+Hauppauge TV EEPROM functions and data structures
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. kernel-doc:: include/media/tveeprom.h
diff --git a/Documentation/driver-api/media/v4l2-videobuf2.rst b/Documentation/driver-api/media/v4l2-videobuf2.rst
new file mode 100644
index 000000000000..1044f64ff168
--- /dev/null
+++ b/Documentation/driver-api/media/v4l2-videobuf2.rst
@@ -0,0 +1,12 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+.. _vb2_framework:
+
+V4L2 videobuf2 functions and data structures
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. kernel-doc:: include/media/videobuf2-core.h
+
+.. kernel-doc:: include/media/videobuf2-v4l2.h
+
+.. kernel-doc:: include/media/videobuf2-memops.h
diff --git a/Documentation/driver-api/mei/index.rst b/Documentation/driver-api/mei/index.rst
index 3a22b522ee78..eae6f18f18cf 100644
--- a/Documentation/driver-api/mei/index.rst
+++ b/Documentation/driver-api/mei/index.rst
@@ -9,13 +9,8 @@ Intel(R) Management Engine Interface (Intel(R) MEI)
**Copyright** |copy| 2019 Intel Corporation
-.. only:: html
-
- .. class:: toc-title
-
- Table of Contents
-
.. toctree::
+ :caption: Table of Contents
:maxdepth: 3
mei
diff --git a/Documentation/driver-api/mei/mei.rst b/Documentation/driver-api/mei/mei.rst
index c800d8e5f422..4f2ced4ccdc6 100644
--- a/Documentation/driver-api/mei/mei.rst
+++ b/Documentation/driver-api/mei/mei.rst
@@ -38,10 +38,15 @@ Because some of the Intel ME features can change the system
configuration, the driver by default allows only a privileged
user to access it.
-The session is terminated calling :c:func:`close(int fd)`.
+The session is terminated calling :c:expr:`close(fd)`.
A code snippet for an application communicating with Intel AMTHI client:
+In order to support virtualization or sandboxing a trusted supervisor
+can use :c:macro:`MEI_CONNECT_CLIENT_IOCTL_VTAG` to create
+virtual channels with an Intel ME feature. Not all features support
+virtual channels such client with answer EOPNOTSUPP.
+
.. code-block:: C
struct mei_connect_client_data data;
@@ -110,6 +115,38 @@ Connect to firmware Feature/Client.
data that can be sent or received. (e.g. if MTU=2K, can send
requests up to bytes 2k and received responses up to 2k bytes).
+IOCTL_MEI_CONNECT_CLIENT_VTAG:
+------------------------------
+
+.. code-block:: none
+
+ Usage:
+
+ struct mei_connect_client_data_vtag client_data_vtag;
+
+ ioctl(fd, IOCTL_MEI_CONNECT_CLIENT_VTAG, &client_data_vtag);
+
+ Inputs:
+
+ struct mei_connect_client_data_vtag - contain the following
+ Input field:
+
+ in_client_uuid - GUID of the FW Feature that needs
+ to connect to.
+ vtag - virtual tag [1, 255]
+
+ Outputs:
+ out_client_properties - Client Properties: MTU and Protocol Version.
+
+ Error returns:
+
+ ENOTTY No such client (i.e. wrong GUID) or connection is not allowed.
+ EINVAL Wrong IOCTL Number or tag == 0
+ ENODEV Device or Connection is not initialized or ready.
+ ENOMEM Unable to allocate memory to client internal data.
+ EFAULT Fatal Error (e.g. Unable to access user input data)
+ EBUSY Connection Already Open
+ EOPNOTSUPP Vtag is not supported
IOCTL_MEI_NOTIFY_SET
---------------------
diff --git a/Documentation/driver-api/mei/nfc.rst b/Documentation/driver-api/mei/nfc.rst
index b5b6fc96f85e..8fe8664c28cc 100644
--- a/Documentation/driver-api/mei/nfc.rst
+++ b/Documentation/driver-api/mei/nfc.rst
@@ -3,7 +3,7 @@
MEI NFC
-------
-Some Intel 8 and 9 Serieses chipsets supports NFC devices connected behind
+Some Intel 8 and 9 Series chipsets support NFC devices connected behind
the Intel Management Engine controller.
MEI client bus exposes the NFC chips as NFC phy devices and enables
binding with Microread and NXP PN544 NFC device driver from the Linux NFC
diff --git a/Documentation/driver-api/memory-devices/ti-gpmc.rst b/Documentation/driver-api/memory-devices/ti-gpmc.rst
index 33efcb81f080..b1bb86871ad7 100644
--- a/Documentation/driver-api/memory-devices/ti-gpmc.rst
+++ b/Documentation/driver-api/memory-devices/ti-gpmc.rst
@@ -14,7 +14,7 @@ memory devices like
* Pseudo-SRAM devices
GPMC is found on Texas Instruments SoC's (OMAP based)
-IP details: http://www.ti.com/lit/pdf/spruh73 section 7.1
+IP details: https://www.ti.com/lit/pdf/spruh73 section 7.1
GPMC generic timing calculation:
diff --git a/Documentation/driver-api/men-chameleon-bus.rst b/Documentation/driver-api/men-chameleon-bus.rst
index 1b1f048aa748..6f0b9ee47595 100644
--- a/Documentation/driver-api/men-chameleon-bus.rst
+++ b/Documentation/driver-api/men-chameleon-bus.rst
@@ -18,6 +18,7 @@ MEN Chameleon Bus
4.1 The driver structure
4.2 Probing and attaching
4.3 Initializing the driver
+ 4.4 Using DMA
Introduction
@@ -173,3 +174,14 @@ module at the MCB core::
The module_mcb_driver() macro can be used to reduce the above code::
module_mcb_driver(foo_driver);
+
+Using DMA
+---------
+
+To make use of the kernel's DMA-API's function, you will need to use the
+carrier device's 'struct device'. Fortunately 'struct mcb_device' embeds a
+pointer (->dma_dev) to the carrier's device for DMA purposes::
+
+ ret = dma_set_mask_and_coherent(&mdev->dma_dev, DMA_BIT_MASK(dma_bits));
+ if (rc)
+ /* Handle errors */
diff --git a/Documentation/driver-api/miscellaneous.rst b/Documentation/driver-api/miscellaneous.rst
index 304ffb146cf9..4a5104a368ac 100644
--- a/Documentation/driver-api/miscellaneous.rst
+++ b/Documentation/driver-api/miscellaneous.rst
@@ -16,12 +16,11 @@ Parallel Port Devices
16x50 UART Driver
=================
-.. kernel-doc:: drivers/tty/serial/serial_core.c
- :export:
-
.. kernel-doc:: drivers/tty/serial/8250/8250_core.c
:export:
+See serial/driver.rst for related APIs.
+
Pulse-Width Modulation (PWM)
============================
diff --git a/Documentation/driver-api/mmc/mmc-tools.rst b/Documentation/driver-api/mmc/mmc-tools.rst
index 54406093768b..eee1c2ccfa8f 100644
--- a/Documentation/driver-api/mmc/mmc-tools.rst
+++ b/Documentation/driver-api/mmc/mmc-tools.rst
@@ -2,10 +2,10 @@
MMC tools introduction
======================
-There is one MMC test tools called mmc-utils, which is maintained by Chris Ball,
+There is one MMC test tools called mmc-utils, which is maintained by Ulf Hansson,
you can find it at the below public git repository:
- http://git.kernel.org/cgit/linux/kernel/git/cjb/mmc-utils.git/
+ https://git.kernel.org/pub/scm/utils/mmc/mmc-utils.git
Functions
=========
diff --git a/Documentation/driver-api/mtd/index.rst b/Documentation/driver-api/mtd/index.rst
index 436ba5a851d7..6a4278f409d7 100644
--- a/Documentation/driver-api/mtd/index.rst
+++ b/Documentation/driver-api/mtd/index.rst
@@ -7,6 +7,6 @@ Memory Technology Device (MTD)
.. toctree::
:maxdepth: 1
- intel-spi
+ spi-intel
nand_ecc
spi-nor
diff --git a/Documentation/driver-api/mtd/nand_ecc.rst b/Documentation/driver-api/mtd/nand_ecc.rst
index e8d3c53a5056..74347c14a70b 100644
--- a/Documentation/driver-api/mtd/nand_ecc.rst
+++ b/Documentation/driver-api/mtd/nand_ecc.rst
@@ -5,7 +5,7 @@ NAND Error-correction Code
Introduction
============
-Having looked at the linux mtd/nand driver and more specific at nand_ecc.c
+Having looked at the linux mtd/nand Hamming software ECC engine driver
I felt there was room for optimisation. I bashed the code for a few hours
performing tricks like table lookup removing superfluous code etc.
After that the speed was increased by 35-40%.
diff --git a/Documentation/driver-api/mtd/intel-spi.rst b/Documentation/driver-api/mtd/spi-intel.rst
index 0e6d9cd5388d..df854f20ead1 100644
--- a/Documentation/driver-api/mtd/intel-spi.rst
+++ b/Documentation/driver-api/mtd/spi-intel.rst
@@ -1,5 +1,5 @@
==============================
-Upgrading BIOS using intel-spi
+Upgrading BIOS using spi-intel
==============================
Many Intel CPUs like Baytrail and Braswell include SPI serial flash host
@@ -11,12 +11,12 @@ avoid accidental (or on purpose) overwrite of the content.
Not all manufacturers protect the SPI serial flash, mainly because it
allows upgrading the BIOS image directly from an OS.
-The intel-spi driver makes it possible to read and write the SPI serial
+The spi-intel driver makes it possible to read and write the SPI serial
flash, if certain protection bits are not set and locked. If it finds
any of them set, the whole MTD device is made read-only to prevent
partial overwrites. By default the driver exposes SPI serial flash
contents as read-only but it can be changed from kernel command line,
-passing "intel-spi.writeable=1".
+passing "spi_intel.writeable=1".
Please keep in mind that overwriting the BIOS image on SPI serial flash
might render the machine unbootable and requires special equipment like
@@ -32,7 +32,7 @@ Linux.
serial flash. Distros like Debian and Fedora have this prepackaged with
name "mtd-utils".
- 3) Add "intel-spi.writeable=1" to the kernel command line and reboot
+ 3) Add "spi_intel.writeable=1" to the kernel command line and reboot
the board (you can also reload the driver passing "writeable=1" as
module parameter to modprobe).
@@ -52,7 +52,7 @@ Linux.
16384+0 records out
8388608 bytes (8.4 MB) copied, 10.0269 s, 837 kB/s
- 6) Verify the backup:
+ 6) Verify the backup::
# sha1sum /dev/mtd0ro bios.bak
fdbb011920572ca6c991377c4b418a0502668b73 /dev/mtd0ro
@@ -66,7 +66,7 @@ Linux.
# flash_erase /dev/mtd0 0 0
Erasing 4 Kibyte @ 7ff000 -- 100 % complete
- 8) Once completed without errors you can write the new BIOS image:
+ 8) Once completed without errors you can write the new BIOS image::
# dd if=MNW2MAX1.X64.0092.R01.1605221712.bin of=/dev/mtd0
diff --git a/Documentation/driver-api/mtd/spi-nor.rst b/Documentation/driver-api/mtd/spi-nor.rst
index 1f0437676762..148fa4288760 100644
--- a/Documentation/driver-api/mtd/spi-nor.rst
+++ b/Documentation/driver-api/mtd/spi-nor.rst
@@ -2,65 +2,204 @@
SPI NOR framework
=================
-Part I - Why do we need this framework?
----------------------------------------
-
-SPI bus controllers (drivers/spi/) only deal with streams of bytes; the bus
-controller operates agnostic of the specific device attached. However, some
-controllers (such as Freescale's QuadSPI controller) cannot easily handle
-arbitrary streams of bytes, but rather are designed specifically for SPI NOR.
-
-In particular, Freescale's QuadSPI controller must know the NOR commands to
-find the right LUT sequence. Unfortunately, the SPI subsystem has no notion of
-opcodes, addresses, or data payloads; a SPI controller simply knows to send or
-receive bytes (Tx and Rx). Therefore, we must define a new layering scheme under
-which the controller driver is aware of the opcodes, addressing, and other
-details of the SPI NOR protocol.
-
-Part II - How does the framework work?
---------------------------------------
-
-This framework just adds a new layer between the MTD and the SPI bus driver.
-With this new layer, the SPI NOR controller driver does not depend on the
-m25p80 code anymore.
-
-Before this framework, the layer is like::
-
- MTD
- ------------------------
- m25p80
- ------------------------
- SPI bus driver
- ------------------------
- SPI NOR chip
-
- After this framework, the layer is like:
- MTD
- ------------------------
- SPI NOR framework
- ------------------------
- m25p80
- ------------------------
- SPI bus driver
- ------------------------
- SPI NOR chip
-
- With the SPI NOR controller driver (Freescale QuadSPI), it looks like:
- MTD
- ------------------------
- SPI NOR framework
- ------------------------
- fsl-quadSPI
- ------------------------
- SPI NOR chip
-
-Part III - How can drivers use the framework?
----------------------------------------------
-
-The main API is spi_nor_scan(). Before you call the hook, a driver should
-initialize the necessary fields for spi_nor{}. Please see
-drivers/mtd/spi-nor/spi-nor.c for detail. Please also refer to spi-fsl-qspi.c
-when you want to write a new driver for a SPI NOR controller.
-Another API is spi_nor_restore(), this is used to restore the status of SPI
-flash chip such as addressing mode. Call it whenever detach the driver from
-device or reboot the system.
+How to propose a new flash addition
+-----------------------------------
+
+Most SPI NOR flashes comply with the JEDEC JESD216
+Serial Flash Discoverable Parameter (SFDP) standard. SFDP describes
+the functional and feature capabilities of serial flash devices in a
+standard set of internal read-only parameter tables.
+
+The SPI NOR driver queries the SFDP tables in order to determine the
+flash's parameters and settings. If the flash defines the SFDP tables
+it's likely that you won't need a flash entry at all, and instead
+rely on the generic flash driver which probes the flash solely based
+on its SFDP data. All one has to do is to specify the "jedec,spi-nor"
+compatible in the device tree.
+
+There are cases however where you need to define an explicit flash
+entry. This typically happens when the flash has settings or support
+that is not covered by the SFDP tables (e.g. Block Protection), or
+when the flash contains mangled SFDP data. If the later, one needs
+to implement the ``spi_nor_fixups`` hooks in order to amend the SFDP
+parameters with the correct values.
+
+Minimum testing requirements
+-----------------------------
+
+Do all the tests from below and paste them in the commit's comments
+section, after the ``---`` marker.
+
+1) Specify the controller that you used to test the flash and specify
+ the frequency at which the flash was operated, e.g.::
+
+ This flash is populated on the X board and was tested at Y
+ frequency using the Z (put compatible) SPI controller.
+
+2) Dump the sysfs entries and print the md5/sha1/sha256 SFDP checksum::
+
+ root@1:~# cat /sys/bus/spi/devices/spi0.0/spi-nor/partname
+ sst26vf064b
+ root@1:~# cat /sys/bus/spi/devices/spi0.0/spi-nor/jedec_id
+ bf2643
+ root@1:~# cat /sys/bus/spi/devices/spi0.0/spi-nor/manufacturer
+ sst
+ root@1:~# xxd -p /sys/bus/spi/devices/spi0.0/spi-nor/sfdp
+ 53464450060102ff00060110300000ff81000106000100ffbf0001180002
+ 0001fffffffffffffffffffffffffffffffffd20f1ffffffff0344eb086b
+ 083b80bbfeffffffffff00ffffff440b0c200dd80fd810d820914824806f
+ 1d81ed0f773830b030b0f7ffffff29c25cfff030c080ffffffffffffffff
+ ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
+ ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
+ ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
+ ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
+ ffffffffffffffffffffffffffffffffff0004fff37f0000f57f0000f9ff
+ 7d00f57f0000f37f0000ffffffffffffffffffffffffffffffffffffffff
+ ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
+ ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
+ ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
+ ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
+ ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
+ ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
+ ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
+ ffffbf2643ffb95ffdff30f260f332ff0a122346ff0f19320f1919ffffff
+ ffffffff00669938ff05013506040232b03072428de89888a585c09faf5a
+ ffff06ec060c0003080bffffffffff07ffff0202ff060300fdfd040700fc
+ 0300fefe0202070e
+ root@1:~# sha256sum /sys/bus/spi/devices/spi0.0/spi-nor/sfdp
+ 428f34d0461876f189ac97f93e68a05fa6428c6650b3b7baf736a921e5898ed1 /sys/bus/spi/devices/spi0.0/spi-nor/sfdp
+
+ Please dump the SFDP tables using ``xxd -p``. It enables us to do
+ the reverse operation and convert the hexdump to binary with
+ ``xxd -rp``. Dumping the SFDP data with ``hexdump -Cv`` is accepted,
+ but less desirable.
+
+3) Dump debugfs data::
+
+ root@1:~# cat /sys/kernel/debug/spi-nor/spi0.0/capabilities
+ Supported read modes by the flash
+ 1S-1S-1S
+ opcode 0x03
+ mode cycles 0
+ dummy cycles 0
+ 1S-1S-1S (fast read)
+ opcode 0x0b
+ mode cycles 0
+ dummy cycles 8
+ 1S-1S-2S
+ opcode 0x3b
+ mode cycles 0
+ dummy cycles 8
+ 1S-2S-2S
+ opcode 0xbb
+ mode cycles 4
+ dummy cycles 0
+ 1S-1S-4S
+ opcode 0x6b
+ mode cycles 0
+ dummy cycles 8
+ 1S-4S-4S
+ opcode 0xeb
+ mode cycles 2
+ dummy cycles 4
+ 4S-4S-4S
+ opcode 0x0b
+ mode cycles 2
+ dummy cycles 4
+
+ Supported page program modes by the flash
+ 1S-1S-1S
+ opcode 0x02
+
+ root@1:~# cat /sys/kernel/debug/spi-nor/spi0.0/params
+ name sst26vf064b
+ id bf 26 43 bf 26 43
+ size 8.00 MiB
+ write size 1
+ page size 256
+ address nbytes 3
+ flags HAS_LOCK | HAS_16BIT_SR | SOFT_RESET | SWP_IS_VOLATILE
+
+ opcodes
+ read 0xeb
+ dummy cycles 6
+ erase 0x20
+ program 0x02
+ 8D extension none
+
+ protocols
+ read 1S-4S-4S
+ write 1S-1S-1S
+ register 1S-1S-1S
+
+ erase commands
+ 20 (4.00 KiB) [0]
+ d8 (8.00 KiB) [1]
+ d8 (32.0 KiB) [2]
+ d8 (64.0 KiB) [3]
+ c7 (8.00 MiB)
+
+ sector map
+ region (in hex) | erase mask | flags
+ ------------------+------------+----------
+ 00000000-00007fff | [01 ] |
+ 00008000-0000ffff | [0 2 ] |
+ 00010000-007effff | [0 3] |
+ 007f0000-007f7fff | [0 2 ] |
+ 007f8000-007fffff | [01 ] |
+
+4) Use `mtd-utils <https://git.infradead.org/mtd-utils.git>`__
+ and verify that erase, read and page program operations work fine::
+
+ root@1:~# dd if=/dev/urandom of=./spi_test bs=1M count=2
+ 2+0 records in
+ 2+0 records out
+ 2097152 bytes (2.1 MB, 2.0 MiB) copied, 0.848566 s, 2.5 MB/s
+
+ root@1:~# mtd_debug erase /dev/mtd0 0 2097152
+ Erased 2097152 bytes from address 0x00000000 in flash
+
+ root@1:~# mtd_debug read /dev/mtd0 0 2097152 spi_read
+ Copied 2097152 bytes from address 0x00000000 in flash to spi_read
+
+ root@1:~# hexdump spi_read
+ 0000000 ffff ffff ffff ffff ffff ffff ffff ffff
+ *
+ 0200000
+
+ root@1:~# sha256sum spi_read
+ 4bda3a28f4ffe603c0ec1258c0034d65a1a0d35ab7bd523a834608adabf03cc5 spi_read
+
+ root@1:~# mtd_debug write /dev/mtd0 0 2097152 spi_test
+ Copied 2097152 bytes from spi_test to address 0x00000000 in flash
+
+ root@1:~# mtd_debug read /dev/mtd0 0 2097152 spi_read
+ Copied 2097152 bytes from address 0x00000000 in flash to spi_read
+
+ root@1:~# sha256sum spi*
+ c444216a6ba2a4a66cccd60a0dd062bce4b865dd52b200ef5e21838c4b899ac8 spi_read
+ c444216a6ba2a4a66cccd60a0dd062bce4b865dd52b200ef5e21838c4b899ac8 spi_test
+
+ If the flash comes erased by default and the previous erase was ignored,
+ we won't catch it, thus test the erase again::
+
+ root@1:~# mtd_debug erase /dev/mtd0 0 2097152
+ Erased 2097152 bytes from address 0x00000000 in flash
+
+ root@1:~# mtd_debug read /dev/mtd0 0 2097152 spi_read
+ Copied 2097152 bytes from address 0x00000000 in flash to spi_read
+
+ root@1:~# sha256sum spi*
+ 4bda3a28f4ffe603c0ec1258c0034d65a1a0d35ab7bd523a834608adabf03cc5 spi_read
+ c444216a6ba2a4a66cccd60a0dd062bce4b865dd52b200ef5e21838c4b899ac8 spi_test
+
+ Dump some other relevant data::
+
+ root@1:~# mtd_debug info /dev/mtd0
+ mtd.type = MTD_NORFLASH
+ mtd.flags = MTD_CAP_NORFLASH
+ mtd.size = 8388608 (8M)
+ mtd.erasesize = 4096 (4K)
+ mtd.writesize = 1
+ mtd.oobsize = 0
+ regions = 0
diff --git a/Documentation/driver-api/mtdnand.rst b/Documentation/driver-api/mtdnand.rst
index 55447659b81f..ce77e024c4f1 100644
--- a/Documentation/driver-api/mtdnand.rst
+++ b/Documentation/driver-api/mtdnand.rst
@@ -276,8 +276,10 @@ unregisters the partitions in the MTD layer.
#ifdef MODULE
static void __exit board_cleanup (void)
{
- /* Release resources, unregister device */
- nand_release (mtd_to_nand(board_mtd));
+ /* Unregister device */
+ WARN_ON(mtd_device_unregister(board_mtd));
+ /* Release resources */
+ nand_cleanup(mtd_to_nand(board_mtd));
/* unmap physical address */
iounmap(baseaddr);
@@ -970,9 +972,6 @@ hints" for an explanation.
.. kernel-doc:: drivers/mtd/nand/raw/nand_base.c
:export:
-.. kernel-doc:: drivers/mtd/nand/raw/nand_ecc.c
- :export:
-
Internal Functions Provided
===========================
diff --git a/Documentation/driver-api/nfc/nfc-hci.rst b/Documentation/driver-api/nfc/nfc-hci.rst
index eb8a1a14e919..486aa647c456 100644
--- a/Documentation/driver-api/nfc/nfc-hci.rst
+++ b/Documentation/driver-api/nfc/nfc-hci.rst
@@ -150,7 +150,7 @@ LLC
Communication between the CPU and the chip often requires some link layer
protocol. Those are isolated as modules managed by the HCI layer. There are
-currently two modules : nop (raw transfert) and shdlc.
+currently two modules : nop (raw transfer) and shdlc.
A new llc must implement the following functions::
struct nfc_llc_ops {
@@ -181,7 +181,7 @@ xmit_from_hci():
The llc must be registered with nfc before it can be used. Do that by
calling::
- nfc_llc_register(const char *name, struct nfc_llc_ops *ops);
+ nfc_llc_register(const char *name, const struct nfc_llc_ops *ops);
Again, note that the llc does not handle the physical link. It is thus very
easy to mix any physical link with any llc for a given chip driver.
diff --git a/Documentation/driver-api/ntb.rst b/Documentation/driver-api/ntb.rst
index 87d1372da879..e991d92b8b1d 100644
--- a/Documentation/driver-api/ntb.rst
+++ b/Documentation/driver-api/ntb.rst
@@ -9,7 +9,7 @@ registers and memory translation windows, as well as non common features like
scratchpad and message registers. Scratchpad registers are read-and-writable
registers that are accessible from either side of the device, so that peers can
exchange a small amount of information at a fixed address. Message registers can
-be utilized for the same purpose. Additionally they are provided with with
+be utilized for the same purpose. Additionally they are provided with
special status bits to make sure the information isn't rewritten by another
peer. Doorbell registers provide a way for peers to send interrupt events.
Memory windows allow translated read and write access to the peer memory.
@@ -207,9 +207,9 @@ The MSI test client serves to test and debug the MSI library which
allows for passing MSI interrupts across NTB memory windows. The
test client is interacted with through the debugfs filesystem:
-* *debugfs*/ntb\_tool/*hw*/
+* *debugfs*/ntb\_msi\_test/*hw*/
A directory in debugfs will be created for each
- NTB device probed by the tool. This directory is shortened to *hw*
+ NTB device probed by the msi test. This directory is shortened to *hw*
below.
* *hw*/port
This file describes the local port number
diff --git a/Documentation/driver-api/nvdimm/firmware-activate.rst b/Documentation/driver-api/nvdimm/firmware-activate.rst
new file mode 100644
index 000000000000..7ee7decbbdc3
--- /dev/null
+++ b/Documentation/driver-api/nvdimm/firmware-activate.rst
@@ -0,0 +1,86 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+==================================
+NVDIMM Runtime Firmware Activation
+==================================
+
+Some persistent memory devices run a firmware locally on the device /
+"DIMM" to perform tasks like media management, capacity provisioning,
+and health monitoring. The process of updating that firmware typically
+involves a reboot because it has implications for in-flight memory
+transactions. However, reboots are disruptive and at least the Intel
+persistent memory platform implementation, described by the Intel ACPI
+DSM specification [1], has added support for activating firmware at
+runtime.
+
+A native sysfs interface is implemented in libnvdimm to allow platform
+to advertise and control their local runtime firmware activation
+capability.
+
+The libnvdimm bus object, ndbusX, implements an ndbusX/firmware/activate
+attribute that shows the state of the firmware activation as one of 'idle',
+'armed', 'overflow', and 'busy'.
+
+- idle:
+ No devices are set / armed to activate firmware
+
+- armed:
+ At least one device is armed
+
+- busy:
+ In the busy state armed devices are in the process of transitioning
+ back to idle and completing an activation cycle.
+
+- overflow:
+ If the platform has a concept of incremental work needed to perform
+ the activation it could be the case that too many DIMMs are armed for
+ activation. In that scenario the potential for firmware activation to
+ timeout is indicated by the 'overflow' state.
+
+The 'ndbusX/firmware/activate' property can be written with a value of
+either 'live', or 'quiesce'. A value of 'quiesce' triggers the kernel to
+run firmware activation from within the equivalent of the hibernation
+'freeze' state where drivers and applications are notified to stop their
+modifications of system memory. A value of 'live' attempts
+firmware activation without this hibernation cycle. The
+'ndbusX/firmware/activate' property will be elided completely if no
+firmware activation capability is detected.
+
+Another property 'ndbusX/firmware/capability' indicates a value of
+'live' or 'quiesce', where 'live' indicates that the firmware
+does not require or inflict any quiesce period on the system to update
+firmware. A capability value of 'quiesce' indicates that firmware does
+expect and injects a quiet period for the memory controller, but 'live'
+may still be written to 'ndbusX/firmware/activate' as an override to
+assume the risk of racing firmware update with in-flight device and
+application activity. The 'ndbusX/firmware/capability' property will be
+elided completely if no firmware activation capability is detected.
+
+The libnvdimm memory-device / DIMM object, nmemX, implements
+'nmemX/firmware/activate' and 'nmemX/firmware/result' attributes to
+communicate the per-device firmware activation state. Similar to the
+'ndbusX/firmware/activate' attribute, the 'nmemX/firmware/activate'
+attribute indicates 'idle', 'armed', or 'busy'. The state transitions
+from 'armed' to 'idle' when the system is prepared to activate firmware,
+firmware staged + state set to armed, and 'ndbusX/firmware/activate' is
+triggered. After that activation event the nmemX/firmware/result
+attribute reflects the state of the last activation as one of:
+
+- none:
+ No runtime activation triggered since the last time the device was reset
+
+- success:
+ The last runtime activation completed successfully.
+
+- fail:
+ The last runtime activation failed for device-specific reasons.
+
+- not_staged:
+ The last runtime activation failed due to a sequencing error of the
+ firmware image not being staged.
+
+- need_reset:
+ Runtime firmware activation failed, but the firmware can still be
+ activated via the legacy method of power-cycling the system.
+
+[1]: https://docs.pmem.io/persistent-memory/
diff --git a/Documentation/driver-api/nvdimm/index.rst b/Documentation/driver-api/nvdimm/index.rst
index a4f8f98aeb94..5863bd04f056 100644
--- a/Documentation/driver-api/nvdimm/index.rst
+++ b/Documentation/driver-api/nvdimm/index.rst
@@ -10,3 +10,4 @@ Non-Volatile Memory Device (NVDIMM)
nvdimm
btt
security
+ firmware-activate
diff --git a/Documentation/driver-api/nvdimm/nvdimm.rst b/Documentation/driver-api/nvdimm/nvdimm.rst
index 08f855cbb4e6..ca16b5acbf30 100644
--- a/Documentation/driver-api/nvdimm/nvdimm.rst
+++ b/Documentation/driver-api/nvdimm/nvdimm.rst
@@ -4,7 +4,7 @@ LIBNVDIMM: Non-Volatile Devices
libnvdimm - kernel / libndctl - userspace helper library
-linux-nvdimm@lists.01.org
+nvdimm@lists.linux.dev
Version 13
@@ -14,10 +14,8 @@ Version 13
Overview
Supporting Documents
Git Trees
- LIBNVDIMM PMEM and BLK
- Why BLK?
- PMEM vs BLK
- BLK-REGIONs, PMEM-REGIONs, Atomic Sectors, and DAX
+ LIBNVDIMM PMEM
+ PMEM-REGIONs, Atomic Sectors, and DAX
Example NVDIMM Platform
LIBNVDIMM Kernel Device Model and LIBNDCTL Userspace API
LIBNDCTL: Context
@@ -53,19 +51,12 @@ PMEM:
block device composed of PMEM is capable of DAX. A PMEM address range
may span an interleave of several DIMMs.
-BLK:
- A set of one or more programmable memory mapped apertures provided
- by a DIMM to access its media. This indirection precludes the
- performance benefit of interleaving, but enables DIMM-bounded failure
- modes.
-
DPA:
DIMM Physical Address, is a DIMM-relative offset. With one DIMM in
the system there would be a 1:1 system-physical-address:DPA association.
Once more DIMMs are added a memory controller interleave must be
decoded to determine the DPA associated with a given
- system-physical-address. BLK capacity always has a 1:1 relationship
- with a single-DIMM's DPA range.
+ system-physical-address.
DAX:
File system extensions to bypass the page cache and block layer to
@@ -73,7 +64,7 @@ DAX:
process address space.
DSM:
- Device Specific Method: ACPI method to to control specific
+ Device Specific Method: ACPI method to control specific
device - in this case the firmware.
DCR:
@@ -84,148 +75,79 @@ BTT:
Block Translation Table: Persistent memory is byte addressable.
Existing software may have an expectation that the power-fail-atomicity
of writes is at least one sector, 512 bytes. The BTT is an indirection
- table with atomic update semantics to front a PMEM/BLK block device
+ table with atomic update semantics to front a PMEM block device
driver and present arbitrary atomic sector sizes.
LABEL:
Metadata stored on a DIMM device that partitions and identifies
- (persistently names) storage between PMEM and BLK. It also partitions
- BLK storage to host BTTs with different parameters per BLK-partition.
- Note that traditional partition tables, GPT/MBR, are layered on top of a
- BLK or PMEM device.
+ (persistently names) capacity allocated to different PMEM namespaces. It
+ also indicates whether an address abstraction like a BTT is applied to
+ the namespace. Note that traditional partition tables, GPT/MBR, are
+ layered on top of a PMEM namespace, or an address abstraction like BTT
+ if present, but partition support is deprecated going forward.
Overview
========
-The LIBNVDIMM subsystem provides support for three types of NVDIMMs, namely,
-PMEM, BLK, and NVDIMM devices that can simultaneously support both PMEM
-and BLK mode access. These three modes of operation are described by
-the "NVDIMM Firmware Interface Table" (NFIT) in ACPI 6. While the LIBNVDIMM
-implementation is generic and supports pre-NFIT platforms, it was guided
-by the superset of capabilities need to support this ACPI 6 definition
-for NVDIMM resources. The bulk of the kernel implementation is in place
-to handle the case where DPA accessible via PMEM is aliased with DPA
-accessible via BLK. When that occurs a LABEL is needed to reserve DPA
-for exclusive access via one mode a time.
+The LIBNVDIMM subsystem provides support for PMEM described by platform
+firmware or a device driver. On ACPI based systems the platform firmware
+conveys persistent memory resource via the ACPI NFIT "NVDIMM Firmware
+Interface Table" in ACPI 6. While the LIBNVDIMM subsystem implementation
+is generic and supports pre-NFIT platforms, it was guided by the
+superset of capabilities need to support this ACPI 6 definition for
+NVDIMM resources. The original implementation supported the
+block-window-aperture capability described in the NFIT, but that support
+has since been abandoned and never shipped in a product.
Supporting Documents
--------------------
ACPI 6:
- http://www.uefi.org/sites/default/files/resources/ACPI_6.0.pdf
+ https://www.uefi.org/sites/default/files/resources/ACPI_6.0.pdf
NVDIMM Namespace:
- http://pmem.io/documents/NVDIMM_Namespace_Spec.pdf
+ https://pmem.io/documents/NVDIMM_Namespace_Spec.pdf
DSM Interface Example:
- http://pmem.io/documents/NVDIMM_DSM_Interface_Example.pdf
+ https://pmem.io/documents/NVDIMM_DSM_Interface_Example.pdf
Driver Writer's Guide:
- http://pmem.io/documents/NVDIMM_Driver_Writers_Guide.pdf
+ https://pmem.io/documents/NVDIMM_Driver_Writers_Guide.pdf
Git Trees
---------
LIBNVDIMM:
- https://git.kernel.org/cgit/linux/kernel/git/djbw/nvdimm.git
+ https://git.kernel.org/cgit/linux/kernel/git/nvdimm/nvdimm.git
LIBNDCTL:
https://github.com/pmem/ndctl.git
-PMEM:
- https://github.com/01org/prd
-LIBNVDIMM PMEM and BLK
-======================
+LIBNVDIMM PMEM
+==============
Prior to the arrival of the NFIT, non-volatile memory was described to a
system in various ad-hoc ways. Usually only the bare minimum was
provided, namely, a single system-physical-address range where writes
are expected to be durable after a system power loss. Now, the NFIT
specification standardizes not only the description of PMEM, but also
-BLK and platform message-passing entry points for control and
-configuration.
-
-For each NVDIMM access method (PMEM, BLK), LIBNVDIMM provides a block
-device driver:
-
- 1. PMEM (nd_pmem.ko): Drives a system-physical-address range. This
- range is contiguous in system memory and may be interleaved (hardware
- memory controller striped) across multiple DIMMs. When interleaved the
- platform may optionally provide details of which DIMMs are participating
- in the interleave.
-
- Note that while LIBNVDIMM describes system-physical-address ranges that may
- alias with BLK access as ND_NAMESPACE_PMEM ranges and those without
- alias as ND_NAMESPACE_IO ranges, to the nd_pmem driver there is no
- distinction. The different device-types are an implementation detail
- that userspace can exploit to implement policies like "only interface
- with address ranges from certain DIMMs". It is worth noting that when
- aliasing is present and a DIMM lacks a label, then no block device can
- be created by default as userspace needs to do at least one allocation
- of DPA to the PMEM range. In contrast ND_NAMESPACE_IO ranges, once
- registered, can be immediately attached to nd_pmem.
-
- 2. BLK (nd_blk.ko): This driver performs I/O using a set of platform
- defined apertures. A set of apertures will access just one DIMM.
- Multiple windows (apertures) allow multiple concurrent accesses, much like
- tagged-command-queuing, and would likely be used by different threads or
- different CPUs.
-
- The NFIT specification defines a standard format for a BLK-aperture, but
- the spec also allows for vendor specific layouts, and non-NFIT BLK
- implementations may have other designs for BLK I/O. For this reason
- "nd_blk" calls back into platform-specific code to perform the I/O.
-
- One such implementation is defined in the "Driver Writer's Guide" and "DSM
- Interface Example".
-
-
-Why BLK?
-========
+platform message-passing entry points for control and configuration.
+
+PMEM (nd_pmem.ko): Drives a system-physical-address range. This range is
+contiguous in system memory and may be interleaved (hardware memory controller
+striped) across multiple DIMMs. When interleaved the platform may optionally
+provide details of which DIMMs are participating in the interleave.
+
+It is worth noting that when the labeling capability is detected (a EFI
+namespace label index block is found), then no block device is created
+by default as userspace needs to do at least one allocation of DPA to
+the PMEM range. In contrast ND_NAMESPACE_IO ranges, once registered,
+can be immediately attached to nd_pmem. This latter mode is called
+label-less or "legacy".
+
+PMEM-REGIONs, Atomic Sectors, and DAX
+-------------------------------------
-While PMEM provides direct byte-addressable CPU-load/store access to
-NVDIMM storage, it does not provide the best system RAS (recovery,
-availability, and serviceability) model. An access to a corrupted
-system-physical-address address causes a CPU exception while an access
-to a corrupted address through an BLK-aperture causes that block window
-to raise an error status in a register. The latter is more aligned with
-the standard error model that host-bus-adapter attached disks present.
-
-Also, if an administrator ever wants to replace a memory it is easier to
-service a system at DIMM module boundaries. Compare this to PMEM where
-data could be interleaved in an opaque hardware specific manner across
-several DIMMs.
-
-PMEM vs BLK
------------
-
-BLK-apertures solve these RAS problems, but their presence is also the
-major contributing factor to the complexity of the ND subsystem. They
-complicate the implementation because PMEM and BLK alias in DPA space.
-Any given DIMM's DPA-range may contribute to one or more
-system-physical-address sets of interleaved DIMMs, *and* may also be
-accessed in its entirety through its BLK-aperture. Accessing a DPA
-through a system-physical-address while simultaneously accessing the
-same DPA through a BLK-aperture has undefined results. For this reason,
-DIMMs with this dual interface configuration include a DSM function to
-store/retrieve a LABEL. The LABEL effectively partitions the DPA-space
-into exclusive system-physical-address and BLK-aperture accessible
-regions. For simplicity a DIMM is allowed a PMEM "region" per each
-interleave set in which it is a member. The remaining DPA space can be
-carved into an arbitrary number of BLK devices with discontiguous
-extents.
-
-BLK-REGIONs, PMEM-REGIONs, Atomic Sectors, and DAX
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-
-One of the few
-reasons to allow multiple BLK namespaces per REGION is so that each
-BLK-namespace can be configured with a BTT with unique atomic sector
-sizes. While a PMEM device can host a BTT the LABEL specification does
-not provide for a sector size to be specified for a PMEM namespace.
-
-This is due to the expectation that the primary usage model for PMEM is
-via DAX, and the BTT is incompatible with DAX. However, for the cases
-where an application or filesystem still needs atomic sector update
-guarantees it can register a BTT on a PMEM device or partition. See
+For the cases where an application or filesystem still needs atomic sector
+update guarantees it can register a BTT on a PMEM device or partition. See
LIBNVDIMM/NDCTL: Block Translation Table "btt"
@@ -236,51 +158,40 @@ For the remainder of this document the following diagram will be
referenced for any example sysfs layouts::
- (a) (b) DIMM BLK-REGION
+ (a) (b) DIMM
+-------------------+--------+--------+--------+
- +------+ | pm0.0 | blk2.0 | pm1.0 | blk2.1 | 0 region2
+ +------+ | pm0.0 | free | pm1.0 | free | 0
| imc0 +--+- - - region0- - - +--------+ +--------+
- +--+---+ | pm0.0 | blk3.0 | pm1.0 | blk3.1 | 1 region3
+ +--+---+ | pm0.0 | free | pm1.0 | free | 1
| +-------------------+--------v v--------+
+--+---+ | |
| cpu0 | region1
+--+---+ | |
| +----------------------------^ ^--------+
- +--+---+ | blk4.0 | pm1.0 | blk4.0 | 2 region4
+ +--+---+ | free | pm1.0 | free | 2
| imc1 +--+----------------------------| +--------+
- +------+ | blk5.0 | pm1.0 | blk5.0 | 3 region5
+ +------+ | free | pm1.0 | free | 3
+----------------------------+--------+--------+
In this platform we have four DIMMs and two memory controllers in one
-socket. Each unique interface (BLK or PMEM) to DPA space is identified
-by a region device with a dynamically assigned id (REGION0 - REGION5).
+socket. Each PMEM interleave set is identified by a region device with
+a dynamically assigned id.
1. The first portion of DIMM0 and DIMM1 are interleaved as REGION0. A
single PMEM namespace is created in the REGION0-SPA-range that spans most
of DIMM0 and DIMM1 with a user-specified name of "pm0.0". Some of that
- interleaved system-physical-address range is reclaimed as BLK-aperture
- accessed space starting at DPA-offset (a) into each DIMM. In that
- reclaimed space we create two BLK-aperture "namespaces" from REGION2 and
- REGION3 where "blk2.0" and "blk3.0" are just human readable names that
- could be set to any user-desired name in the LABEL.
+ interleaved system-physical-address range is left free for
+ another PMEM namespace to be defined.
2. In the last portion of DIMM0 and DIMM1 we have an interleaved
system-physical-address range, REGION1, that spans those two DIMMs as
well as DIMM2 and DIMM3. Some of REGION1 is allocated to a PMEM namespace
- named "pm1.0", the rest is reclaimed in 4 BLK-aperture namespaces (for
- each DIMM in the interleave set), "blk2.1", "blk3.1", "blk4.0", and
- "blk5.0".
-
- 3. The portion of DIMM2 and DIMM3 that do not participate in the REGION1
- interleaved system-physical-address range (i.e. the DPA address past
- offset (b) are also included in the "blk4.0" and "blk5.0" namespaces.
- Note, that this example shows that BLK-aperture namespaces don't need to
- be contiguous in DPA-space.
+ named "pm1.0".
This bus is provided by the kernel under the device
- /sys/devices/platform/nfit_test.0 when CONFIG_NFIT_TEST is enabled and
- the nfit_test.ko module is loaded. This not only test LIBNVDIMM but the
- acpi_nfit.ko driver as well.
+ /sys/devices/platform/nfit_test.0 when the nfit_test.ko module from
+ tools/testing/nvdimm is loaded. This module is a unit test for
+ LIBNVDIMM and the acpi_nfit.ko driver.
LIBNVDIMM Kernel Device Model and LIBNDCTL Userspace API
@@ -469,17 +380,14 @@ identified by an "nfit_handle" a 32-bit value where:
LIBNVDIMM/LIBNDCTL: Region
--------------------------
-A generic REGION device is registered for each PMEM range or BLK-aperture
-set. Per the example there are 6 regions: 2 PMEM and 4 BLK-aperture
-sets on the "nfit_test.0" bus. The primary role of regions are to be a
-container of "mappings". A mapping is a tuple of <DIMM,
-DPA-start-offset, length>.
+A generic REGION device is registered for each PMEM interleave-set /
+range. Per the example there are 2 PMEM regions on the "nfit_test.0"
+bus. The primary role of regions are to be a container of "mappings". A
+mapping is a tuple of <DIMM, DPA-start-offset, length>.
-LIBNVDIMM provides a built-in driver for these REGION devices. This driver
-is responsible for reconciling the aliased DPA mappings across all
-regions, parsing the LABEL, if present, and then emitting NAMESPACE
-devices with the resolved/exclusive DPA-boundaries for the nd_pmem or
-nd_blk device driver to consume.
+LIBNVDIMM provides a built-in driver for REGION devices. This driver
+is responsible for all parsing LABELs, if present, and then emitting NAMESPACE
+devices for the nd_pmem driver to consume.
In addition to the generic attributes of "mapping"s, "interleave_ways"
and "size" the REGION device also exports some convenience attributes.
@@ -493,8 +401,6 @@ LIBNVDIMM: region::
struct nd_region *nvdimm_pmem_region_create(struct nvdimm_bus *nvdimm_bus,
struct nd_region_desc *ndr_desc);
- struct nd_region *nvdimm_blk_region_create(struct nvdimm_bus *nvdimm_bus,
- struct nd_region_desc *ndr_desc);
::
@@ -527,8 +433,9 @@ LIBNDCTL: region enumeration example
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Sample region retrieval routines based on NFIT-unique data like
-"spa_index" (interleave set id) for PMEM and "nfit_handle" (dimm id) for
-BLK::
+"spa_index" (interleave set id).
+
+::
static struct ndctl_region *get_pmem_region_by_spa_index(struct ndctl_bus *bus,
unsigned int spa_index)
@@ -544,139 +451,23 @@ BLK::
return NULL;
}
- static struct ndctl_region *get_blk_region_by_dimm_handle(struct ndctl_bus *bus,
- unsigned int handle)
- {
- struct ndctl_region *region;
-
- ndctl_region_foreach(bus, region) {
- struct ndctl_mapping *map;
-
- if (ndctl_region_get_type(region) != ND_DEVICE_REGION_BLOCK)
- continue;
- ndctl_mapping_foreach(region, map) {
- struct ndctl_dimm *dimm = ndctl_mapping_get_dimm(map);
-
- if (ndctl_dimm_get_handle(dimm) == handle)
- return region;
- }
- }
- return NULL;
- }
-
-
-Why Not Encode the Region Type into the Region Name?
-----------------------------------------------------
-
-At first glance it seems since NFIT defines just PMEM and BLK interface
-types that we should simply name REGION devices with something derived
-from those type names. However, the ND subsystem explicitly keeps the
-REGION name generic and expects userspace to always consider the
-region-attributes for four reasons:
-
- 1. There are already more than two REGION and "namespace" types. For
- PMEM there are two subtypes. As mentioned previously we have PMEM where
- the constituent DIMM devices are known and anonymous PMEM. For BLK
- regions the NFIT specification already anticipates vendor specific
- implementations. The exact distinction of what a region contains is in
- the region-attributes not the region-name or the region-devtype.
-
- 2. A region with zero child-namespaces is a possible configuration. For
- example, the NFIT allows for a DCR to be published without a
- corresponding BLK-aperture. This equates to a DIMM that can only accept
- control/configuration messages, but no i/o through a descendant block
- device. Again, this "type" is advertised in the attributes ('mappings'
- == 0) and the name does not tell you much.
-
- 3. What if a third major interface type arises in the future? Outside
- of vendor specific implementations, it's not difficult to envision a
- third class of interface type beyond BLK and PMEM. With a generic name
- for the REGION level of the device-hierarchy old userspace
- implementations can still make sense of new kernel advertised
- region-types. Userspace can always rely on the generic region
- attributes like "mappings", "size", etc and the expected child devices
- named "namespace". This generic format of the device-model hierarchy
- allows the LIBNVDIMM and LIBNDCTL implementations to be more uniform and
- future-proof.
-
- 4. There are more robust mechanisms for determining the major type of a
- region than a device name. See the next section, How Do I Determine the
- Major Type of a Region?
-
-How Do I Determine the Major Type of a Region?
-----------------------------------------------
-
-Outside of the blanket recommendation of "use libndctl", or simply
-looking at the kernel header (/usr/include/linux/ndctl.h) to decode the
-"nstype" integer attribute, here are some other options.
-
-1. module alias lookup
-^^^^^^^^^^^^^^^^^^^^^^
-
- The whole point of region/namespace device type differentiation is to
- decide which block-device driver will attach to a given LIBNVDIMM namespace.
- One can simply use the modalias to lookup the resulting module. It's
- important to note that this method is robust in the presence of a
- vendor-specific driver down the road. If a vendor-specific
- implementation wants to supplant the standard nd_blk driver it can with
- minimal impact to the rest of LIBNVDIMM.
-
- In fact, a vendor may also want to have a vendor-specific region-driver
- (outside of nd_region). For example, if a vendor defined its own LABEL
- format it would need its own region driver to parse that LABEL and emit
- the resulting namespaces. The output from module resolution is more
- accurate than a region-name or region-devtype.
-
-2. udev
-^^^^^^^
-
- The kernel "devtype" is registered in the udev database::
-
- # udevadm info --path=/devices/platform/nfit_test.0/ndbus0/region0
- P: /devices/platform/nfit_test.0/ndbus0/region0
- E: DEVPATH=/devices/platform/nfit_test.0/ndbus0/region0
- E: DEVTYPE=nd_pmem
- E: MODALIAS=nd:t2
- E: SUBSYSTEM=nd
-
- # udevadm info --path=/devices/platform/nfit_test.0/ndbus0/region4
- P: /devices/platform/nfit_test.0/ndbus0/region4
- E: DEVPATH=/devices/platform/nfit_test.0/ndbus0/region4
- E: DEVTYPE=nd_blk
- E: MODALIAS=nd:t3
- E: SUBSYSTEM=nd
-
- ...and is available as a region attribute, but keep in mind that the
- "devtype" does not indicate sub-type variations and scripts should
- really be understanding the other attributes.
-
-3. type specific attributes
-^^^^^^^^^^^^^^^^^^^^^^^^^^^
-
- As it currently stands a BLK-aperture region will never have a
- "nfit/spa_index" attribute, but neither will a non-NFIT PMEM region. A
- BLK region with a "mappings" value of 0 is, as mentioned above, a DIMM
- that does not allow I/O. A PMEM region with a "mappings" value of zero
- is a simple system-physical-address range.
-
LIBNVDIMM/LIBNDCTL: Namespace
-----------------------------
-A REGION, after resolving DPA aliasing and LABEL specified boundaries,
-surfaces one or more "namespace" devices. The arrival of a "namespace"
-device currently triggers either the nd_blk or nd_pmem driver to load
-and register a disk/block device.
+A REGION, after resolving DPA aliasing and LABEL specified boundaries, surfaces
+one or more "namespace" devices. The arrival of a "namespace" device currently
+triggers the nd_pmem driver to load and register a disk/block device.
LIBNVDIMM: namespace
^^^^^^^^^^^^^^^^^^^^
-Here is a sample layout from the three major types of NAMESPACE where
-namespace0.0 represents DIMM-info-backed PMEM (note that it has a 'uuid'
-attribute), namespace2.0 represents a BLK namespace (note it has a
-'sector_size' attribute) that, and namespace6.0 represents an anonymous
-PMEM namespace (note that has no 'uuid' attribute due to not support a
-LABEL)::
+Here is a sample layout from the 2 major types of NAMESPACE where namespace0.0
+represents DIMM-info-backed PMEM (note that it has a 'uuid' attribute), and
+namespace1.0 represents an anonymous PMEM namespace (note that has no 'uuid'
+attribute due to not support a LABEL)
+
+::
/sys/devices/platform/nfit_test.0/ndbus0/region0/namespace0.0
|-- alt_name
@@ -691,20 +482,7 @@ LABEL)::
|-- type
|-- uevent
`-- uuid
- /sys/devices/platform/nfit_test.0/ndbus0/region2/namespace2.0
- |-- alt_name
- |-- devtype
- |-- dpa_extents
- |-- force_raw
- |-- modalias
- |-- numa_node
- |-- sector_size
- |-- size
- |-- subsystem -> ../../../../../../bus/nd
- |-- type
- |-- uevent
- `-- uuid
- /sys/devices/platform/nfit_test.1/ndbus1/region6/namespace6.0
+ /sys/devices/platform/nfit_test.1/ndbus1/region1/namespace1.0
|-- block
| `-- pmem0
|-- devtype
@@ -778,7 +556,7 @@ Why the Term "namespace"?
2. The term originated to describe the sub-devices that can be created
within a NVME controller (see the nvme specification:
- http://www.nvmexpress.org/specifications/), and NFIT namespaces are
+ https://www.nvmexpress.org/specifications/), and NFIT namespaces are
meant to parallel the capabilities and configurability of
NVME-namespaces.
@@ -786,9 +564,9 @@ Why the Term "namespace"?
LIBNVDIMM/LIBNDCTL: Block Translation Table "btt"
-------------------------------------------------
-A BTT (design document: http://pmem.io/2014/09/23/btt.html) is a stacked
-block device driver that fronts either the whole block device or a
-partition of a block device emitted by either a PMEM or BLK NAMESPACE.
+A BTT (design document: https://pmem.io/2014/09/23/btt.html) is a
+personality driver for a namespace that fronts entire namespace as an
+'address abstraction'.
LIBNVDIMM: btt layout
^^^^^^^^^^^^^^^^^^^^^
@@ -815,7 +593,9 @@ LIBNDCTL: btt creation example
Similar to namespaces an idle BTT device is automatically created per
region. Each time this "seed" btt device is configured and enabled a new
seed is created. Creating a BTT configuration involves two steps of
-finding and idle BTT and assigning it to consume a PMEM or BLK namespace::
+finding and idle BTT and assigning it to consume a namespace.
+
+::
static struct ndctl_btt *get_idle_btt(struct ndctl_region *region)
{
@@ -863,25 +643,15 @@ For the given example above, here is the view of the objects as seen by the
LIBNDCTL API::
+---+
- |CTX| +---------+ +--------------+ +---------------+
- +-+-+ +-> REGION0 +---> NAMESPACE0.0 +--> PMEM8 "pm0.0" |
- | | +---------+ +--------------+ +---------------+
- +-------+ | | +---------+ +--------------+ +---------------+
- | DIMM0 <-+ | +-> REGION1 +---> NAMESPACE1.0 +--> PMEM6 "pm1.0" |
- +-------+ | | | +---------+ +--------------+ +---------------+
+ |CTX|
+ +-+-+
+ |
+ +-------+ |
+ | DIMM0 <-+ | +---------+ +--------------+ +---------------+
+ +-------+ | | +-> REGION0 +---> NAMESPACE0.0 +--> PMEM8 "pm0.0" |
| DIMM1 <-+ +-v--+ | +---------+ +--------------+ +---------------+
- +-------+ +-+BUS0+---> REGION2 +-+-> NAMESPACE2.0 +--> ND6 "blk2.0" |
- | DIMM2 <-+ +----+ | +---------+ | +--------------+ +----------------------+
- +-------+ | | +-> NAMESPACE2.1 +--> ND5 "blk2.1" | BTT2 |
- | DIMM3 <-+ | +--------------+ +----------------------+
- +-------+ | +---------+ +--------------+ +---------------+
- +-> REGION3 +-+-> NAMESPACE3.0 +--> ND4 "blk3.0" |
- | +---------+ | +--------------+ +----------------------+
- | +-> NAMESPACE3.1 +--> ND3 "blk3.1" | BTT1 |
- | +--------------+ +----------------------+
- | +---------+ +--------------+ +---------------+
- +-> REGION4 +---> NAMESPACE4.0 +--> ND2 "blk4.0" |
- | +---------+ +--------------+ +---------------+
- | +---------+ +--------------+ +----------------------+
- +-> REGION5 +---> NAMESPACE5.0 +--> ND1 "blk5.0" | BTT0 |
- +---------+ +--------------+ +---------------+------+
+ +-------+ +-+BUS0+-| +---------+ +--------------+ +----------------------+
+ | DIMM2 <-+ +----+ +-> REGION1 +---> NAMESPACE1.0 +--> PMEM6 "pm1.0" | BTT1 |
+ +-------+ | | +---------+ +--------------+ +---------------+------+
+ | DIMM3 <-+
+ +-------+
diff --git a/Documentation/driver-api/nvdimm/security.rst b/Documentation/driver-api/nvdimm/security.rst
index ad9dea099b34..eb3d35e6a95c 100644
--- a/Documentation/driver-api/nvdimm/security.rst
+++ b/Documentation/driver-api/nvdimm/security.rst
@@ -83,7 +83,7 @@ passed in.
6. Freeze
---------
The freeze operation does not require any keys. The security config can be
-frozen by a user with root privelege.
+frozen by a user with root privilege.
7. Disable
----------
@@ -138,6 +138,6 @@ another encrypted-key.
This command is only available when the master security is enabled, indicated
by the extended security status.
-[1]: http://pmem.io/documents/NVDIMM_DSM_Interface-V1.8.pdf
+[1]: https://pmem.io/documents/NVDIMM_DSM_Interface-V1.8.pdf
[2]: http://www.t13.org/documents/UploadedDocuments/docs2006/e05179r4-ACS-SecurityClarifications.pdf
diff --git a/Documentation/driver-api/nvmem.rst b/Documentation/driver-api/nvmem.rst
index 287e86819640..5d9500d21ecc 100644
--- a/Documentation/driver-api/nvmem.rst
+++ b/Documentation/driver-api/nvmem.rst
@@ -26,9 +26,7 @@ was a rather big abstraction leak.
This framework aims at solve these problems. It also introduces DT
representation for consumer devices to go get the data they require (MAC
-Addresses, SoC/Revision ID, part numbers, and so on) from the NVMEMs. This
-framework is based on regmap, so that most of the abstraction available in
-regmap can be reused, across multiple types of buses.
+Addresses, SoC/Revision ID, part numbers, and so on) from the NVMEMs.
NVMEM Providers
+++++++++++++++
@@ -43,25 +41,23 @@ A NVMEM provider can register with NVMEM core by supplying relevant
nvmem configuration to nvmem_register(), on success core would return a valid
nvmem_device pointer.
-nvmem_unregister(nvmem) is used to unregister a previously registered provider.
+nvmem_unregister() is used to unregister a previously registered provider.
-For example, a simple qfprom case::
+For example, a simple nvram case::
- static struct nvmem_config econfig = {
- .name = "qfprom",
- .owner = THIS_MODULE,
- };
-
- static int qfprom_probe(struct platform_device *pdev)
+ static int brcm_nvram_probe(struct platform_device *pdev)
{
+ struct nvmem_config config = {
+ .name = "brcm-nvram",
+ .reg_read = brcm_nvram_read,
+ };
...
- econfig.dev = &pdev->dev;
- nvmem = nvmem_register(&econfig);
- ...
- }
+ config.dev = &pdev->dev;
+ config.priv = priv;
+ config.size = resource_size(res);
-It is mandatory that the NVMEM provider has a regmap associated with its
-struct device. Failure to do would return error code from nvmem_register().
+ devm_nvmem_register(&config);
+ }
Users of board files can define and register nvmem cells using the
nvmem_cell_table struct::
@@ -189,3 +185,24 @@ ex::
=====================
See Documentation/devicetree/bindings/nvmem/nvmem.txt
+
+8. NVMEM layouts
+================
+
+NVMEM layouts are yet another mechanism to create cells. With the device
+tree binding it is possible to specify simple cells by using an offset
+and a length. Sometimes, the cells doesn't have a static offset, but
+the content is still well defined, e.g. tag-length-values. In this case,
+the NVMEM device content has to be first parsed and the cells need to
+be added accordingly. Layouts let you read the content of the NVMEM device
+and let you add cells dynamically.
+
+Another use case for layouts is the post processing of cells. With layouts,
+it is possible to associate a custom post processing hook to a cell. It
+even possible to add this hook to cells not created by the layout itself.
+
+9. Internal kernel API
+======================
+
+.. kernel-doc:: drivers/nvmem/core.c
+ :export:
diff --git a/Documentation/driver-api/pci/index.rst b/Documentation/driver-api/pci/index.rst
index c6cf1fef61ce..a38e475cdbe3 100644
--- a/Documentation/driver-api/pci/index.rst
+++ b/Documentation/driver-api/pci/index.rst
@@ -4,11 +4,8 @@
The Linux PCI driver implementer's API guide
============================================
-.. class:: toc-title
-
- Table of contents
-
.. toctree::
+ :caption: Table of contents
:maxdepth: 2
pci
diff --git a/Documentation/driver-api/pci/p2pdma.rst b/Documentation/driver-api/pci/p2pdma.rst
index 44deb52beeb4..d0b241628cf1 100644
--- a/Documentation/driver-api/pci/p2pdma.rst
+++ b/Documentation/driver-api/pci/p2pdma.rst
@@ -83,19 +83,9 @@ this to include other types of resources like doorbells.
Client Drivers
--------------
-A client driver typically only has to conditionally change its DMA map
-routine to use the mapping function :c:func:`pci_p2pdma_map_sg()` instead
-of the usual :c:func:`dma_map_sg()` function. Memory mapped in this
-way does not need to be unmapped.
-
-The client may also, optionally, make use of
-:c:func:`is_pci_p2pdma_page()` to determine when to use the P2P mapping
-functions and when to use the regular mapping functions. In some
-situations, it may be more appropriate to use a flag to indicate a
-given request is P2P memory and map appropriately. It is important to
-ensure that struct pages that back P2P memory stay out of code that
-does not have support for them as other code may treat the pages as
-regular memory which may not be appropriate.
+A client driver only has to use the mapping API :c:func:`dma_map_sg()`
+and :c:func:`dma_unmap_sg()` functions as usual, and the implementation
+will do the right thing for the P2P capable memory.
Orchestrator Drivers
diff --git a/Documentation/driver-api/pci/pci.rst b/Documentation/driver-api/pci/pci.rst
index ca85e5e78b2c..4843cfad4f60 100644
--- a/Documentation/driver-api/pci/pci.rst
+++ b/Documentation/driver-api/pci/pci.rst
@@ -13,7 +13,7 @@ PCI Support Library
.. kernel-doc:: drivers/pci/search.c
:export:
-.. kernel-doc:: drivers/pci/msi.c
+.. kernel-doc:: drivers/pci/msi/msi.c
:export:
.. kernel-doc:: drivers/pci/bus.c
diff --git a/Documentation/driver-api/phy/phy.rst b/Documentation/driver-api/phy/phy.rst
index 8fc1ce0bb905..81785c084f3e 100644
--- a/Documentation/driver-api/phy/phy.rst
+++ b/Documentation/driver-api/phy/phy.rst
@@ -94,7 +94,8 @@ Inorder to dereference the private data (in phy_ops), the phy provider driver
can use phy_set_drvdata() after creating the PHY and use phy_get_drvdata() in
phy_ops to get back the private data.
-4. Getting a reference to the PHY
+Getting a reference to the PHY
+==============================
Before the controller can make use of the PHY, it has to get a reference to
it. This framework provides the following APIs to get a reference to the PHY.
@@ -102,27 +103,31 @@ it. This framework provides the following APIs to get a reference to the PHY.
::
struct phy *phy_get(struct device *dev, const char *string);
- struct phy *phy_optional_get(struct device *dev, const char *string);
struct phy *devm_phy_get(struct device *dev, const char *string);
struct phy *devm_phy_optional_get(struct device *dev,
const char *string);
+ struct phy *devm_of_phy_get(struct device *dev, struct device_node *np,
+ const char *con_id);
+ struct phy *devm_of_phy_optional_get(struct device *dev,
+ struct device_node *np,
+ const char *con_id);
struct phy *devm_of_phy_get_by_index(struct device *dev,
struct device_node *np,
int index);
-phy_get, phy_optional_get, devm_phy_get and devm_phy_optional_get can
-be used to get the PHY. In the case of dt boot, the string arguments
+phy_get, devm_phy_get and devm_phy_optional_get can be used to get the PHY.
+In the case of dt boot, the string arguments
should contain the phy name as given in the dt data and in the case of
non-dt boot, it should contain the label of the PHY. The two
devm_phy_get associates the device with the PHY using devres on
successful PHY get. On driver detach, release function is invoked on
-the devres data and devres data is freed. phy_optional_get and
-devm_phy_optional_get should be used when the phy is optional. These
-two functions will never return -ENODEV, but instead returns NULL when
-the phy cannot be found.Some generic drivers, such as ehci, may use multiple
-phys and for such drivers referencing phy(s) by name(s) does not make sense. In
-this case, devm_of_phy_get_by_index can be used to get a phy reference based on
-the index.
+the devres data and devres data is freed.
+The _optional_get variants should be used when the phy is optional. These
+functions will never return -ENODEV, but instead return NULL when
+the phy cannot be found.
+Some generic drivers, such as ehci, may use multiple phys. In this case,
+devm_of_phy_get or devm_of_phy_get_by_index can be used to get a phy
+reference based on name or index.
It should be noted that NULL is a valid phy reference. All phy
consumer calls on the NULL phy become NOPs. That is the release calls,
@@ -130,6 +135,28 @@ the phy_init() and phy_exit() calls, and phy_power_on() and
phy_power_off() calls are all NOP when applied to a NULL phy. The NULL
phy is useful in devices for handling optional phy devices.
+Order of API calls
+==================
+
+The general order of calls should be::
+
+ [devm_][of_]phy_get()
+ phy_init()
+ phy_power_on()
+ [phy_set_mode[_ext]()]
+ ...
+ phy_power_off()
+ phy_exit()
+ [[of_]phy_put()]
+
+Some PHY drivers may not implement :c:func:`phy_init` or :c:func:`phy_power_on`,
+but controllers should always call these functions to be compatible with other
+PHYs. Some PHYs may require :c:func:`phy_set_mode <phy_set_mode_ext>`, while
+others may use a default mode (typically configured via devicetree or other
+firmware). For compatibility, you should always call this function if you know
+what mode you will be using. Generally, this function should be called after
+:c:func:`phy_power_on`, although some PHY drivers may allow it at any time.
+
Releasing a reference to the PHY
================================
diff --git a/Documentation/driver-api/pinctl.rst b/Documentation/driver-api/pin-control.rst
index 3d2deaf48841..4639912dc9cc 100644
--- a/Documentation/driver-api/pinctl.rst
+++ b/Documentation/driver-api/pin-control.rst
@@ -11,20 +11,18 @@ This subsystem deals with:
- Multiplexing of pins, pads, fingers (etc) see below for details
- Configuration of pins, pads, fingers (etc), such as software-controlled
- biasing and driving mode specific pins, such as pull-up/down, open drain,
+ biasing and driving mode specific pins, such as pull-up, pull-down, open drain,
load capacitance etc.
Top-level interface
===================
-Definition of PIN CONTROLLER:
+Definitions:
-- A pin controller is a piece of hardware, usually a set of registers, that
+- A PIN CONTROLLER is a piece of hardware, usually a set of registers, that
can control PINs. It may be able to multiplex, bias, set load capacitance,
set drive strength, etc. for individual pins or groups of pins.
-Definition of PIN:
-
- PINS are equal to pads, fingers, balls or whatever packaging input or
output line you want to control and these are denoted by unsigned integers
in the range 0..maxpin. This numberspace is local to each PIN CONTROLLER, so
@@ -57,7 +55,9 @@ Here is an example of a PGA (Pin Grid Array) chip seen from underneath::
1 o o o o o o o o
To register a pin controller and name all the pins on this package we can do
-this in our driver::
+this in our driver:
+
+.. code-block:: c
#include <linux/pinctrl/pinctrl.h>
@@ -78,14 +78,13 @@ this in our driver::
.owner = THIS_MODULE,
};
- int __init foo_probe(void)
+ int __init foo_init(void)
{
int error;
struct pinctrl_dev *pctl;
- error = pinctrl_register_and_init(&foo_desc, <PARENT>,
- NULL, &pctl);
+ error = pinctrl_register_and_init(&foo_desc, <PARENT>, NULL, &pctl);
if (error)
return error;
@@ -95,20 +94,20 @@ this in our driver::
To enable the pinctrl subsystem and the subgroups for PINMUX and PINCONF and
selected drivers, you need to select them from your machine's Kconfig entry,
since these are so tightly integrated with the machines they are used on.
-See for example arch/arm/mach-u300/Kconfig for an example.
+See ``arch/arm/mach-ux500/Kconfig`` for an example.
Pins usually have fancier names than this. You can find these in the datasheet
for your chip. Notice that the core pinctrl.h file provides a fancy macro
-called PINCTRL_PIN() to create the struct entries. As you can see I enumerated
-the pins from 0 in the upper left corner to 63 in the lower right corner.
+called ``PINCTRL_PIN()`` to create the struct entries. As you can see the pins are
+enumerated from 0 in the upper left corner to 63 in the lower right corner.
This enumeration was arbitrarily chosen, in practice you need to think
through your numbering system so that it matches the layout of registers
and such things in your driver, or the code may become complicated. You must
also consider matching of offsets to the GPIO ranges that may be handled by
the pin controller.
-For a padring with 467 pads, as opposed to actual pins, I used an enumeration
-like this, walking around the edge of the chip, which seems to be industry
+For a padding with 467 pads, as opposed to actual pins, the enumeration will
+be like this, walking around the edge of the chip, which seems to be industry
standard too (all these pads had names, too)::
@@ -132,50 +131,38 @@ on { 0, 8, 16, 24 }, and a group of pins dealing with an I2C interface on pins
on { 24, 25 }.
These two groups are presented to the pin control subsystem by implementing
-some generic pinctrl_ops like this::
+some generic ``pinctrl_ops`` like this:
- #include <linux/pinctrl/pinctrl.h>
+.. code-block:: c
- struct foo_group {
- const char *name;
- const unsigned int *pins;
- const unsigned num_pins;
- };
+ #include <linux/pinctrl/pinctrl.h>
static const unsigned int spi0_pins[] = { 0, 8, 16, 24 };
static const unsigned int i2c0_pins[] = { 24, 25 };
- static const struct foo_group foo_groups[] = {
- {
- .name = "spi0_grp",
- .pins = spi0_pins,
- .num_pins = ARRAY_SIZE(spi0_pins),
- },
- {
- .name = "i2c0_grp",
- .pins = i2c0_pins,
- .num_pins = ARRAY_SIZE(i2c0_pins),
- },
+ static const struct pingroup foo_groups[] = {
+ PINCTRL_PINGROUP("spi0_grp", spi0_pins, ARRAY_SIZE(spi0_pins)),
+ PINCTRL_PINGROUP("i2c0_grp", i2c0_pins, ARRAY_SIZE(i2c0_pins)),
};
-
static int foo_get_groups_count(struct pinctrl_dev *pctldev)
{
return ARRAY_SIZE(foo_groups);
}
static const char *foo_get_group_name(struct pinctrl_dev *pctldev,
- unsigned selector)
+ unsigned int selector)
{
return foo_groups[selector].name;
}
- static int foo_get_group_pins(struct pinctrl_dev *pctldev, unsigned selector,
- const unsigned **pins,
- unsigned *num_pins)
+ static int foo_get_group_pins(struct pinctrl_dev *pctldev,
+ unsigned int selector,
+ const unsigned int **pins,
+ unsigned int *npins)
{
- *pins = (unsigned *) foo_groups[selector].pins;
- *num_pins = foo_groups[selector].num_pins;
+ *pins = foo_groups[selector].pins;
+ *npins = foo_groups[selector].npins;
return 0;
}
@@ -185,13 +172,12 @@ some generic pinctrl_ops like this::
.get_group_pins = foo_get_group_pins,
};
-
static struct pinctrl_desc foo_desc = {
- ...
- .pctlops = &foo_pctrl_ops,
+ ...
+ .pctlops = &foo_pctrl_ops,
};
-The pin control subsystem will call the .get_groups_count() function to
+The pin control subsystem will call the ``.get_groups_count()`` function to
determine the total number of legal selectors, then it will call the other functions
to retrieve the name and pins of the group. Maintaining the data structure of
the groups is up to the driver, this is just a simple example - in practice you
@@ -204,59 +190,62 @@ Pin configuration
Pins can sometimes be software-configured in various ways, mostly related
to their electronic properties when used as inputs or outputs. For example you
-may be able to make an output pin high impedance, or "tristate" meaning it is
+may be able to make an output pin high impedance (Hi-Z), or "tristate" meaning it is
effectively disconnected. You may be able to connect an input pin to VDD or GND
using a certain resistor value - pull up and pull down - so that the pin has a
stable value when nothing is driving the rail it is connected to, or when it's
unconnected.
Pin configuration can be programmed by adding configuration entries into the
-mapping table; see section "Board/machine configuration" below.
+mapping table; see section `Board/machine configuration`_ below.
The format and meaning of the configuration parameter, PLATFORM_X_PULL_UP
above, is entirely defined by the pin controller driver.
The pin configuration driver implements callbacks for changing pin
-configuration in the pin controller ops like this::
+configuration in the pin controller ops like this:
+
+.. code-block:: c
- #include <linux/pinctrl/pinctrl.h>
#include <linux/pinctrl/pinconf.h>
+ #include <linux/pinctrl/pinctrl.h>
+
#include "platform_x_pindefs.h"
static int foo_pin_config_get(struct pinctrl_dev *pctldev,
- unsigned offset,
- unsigned long *config)
+ unsigned int offset,
+ unsigned long *config)
{
struct my_conftype conf;
- ... Find setting for pin @ offset ...
+ /* ... Find setting for pin @ offset ... */
*config = (unsigned long) conf;
}
static int foo_pin_config_set(struct pinctrl_dev *pctldev,
- unsigned offset,
- unsigned long config)
+ unsigned int offset,
+ unsigned long config)
{
struct my_conftype *conf = (struct my_conftype *) config;
switch (conf) {
case PLATFORM_X_PULL_UP:
...
- }
+ break;
}
}
- static int foo_pin_config_group_get (struct pinctrl_dev *pctldev,
- unsigned selector,
- unsigned long *config)
+ static int foo_pin_config_group_get(struct pinctrl_dev *pctldev,
+ unsigned selector,
+ unsigned long *config)
{
...
}
- static int foo_pin_config_group_set (struct pinctrl_dev *pctldev,
- unsigned selector,
- unsigned long config)
+ static int foo_pin_config_group_set(struct pinctrl_dev *pctldev,
+ unsigned selector,
+ unsigned long config)
{
...
}
@@ -281,8 +270,8 @@ The GPIO drivers may want to perform operations of various types on the same
physical pins that are also registered as pin controller pins.
First and foremost, the two subsystems can be used as completely orthogonal,
-see the section named "pin control requests from drivers" and
-"drivers needing both pin control and GPIOs" below for details. But in some
+see the section named `Pin control requests from drivers`_ and
+`Drivers needing both pin control and GPIOs`_ below for details. But in some
situations a cross-subsystem mapping between pins and GPIOs is needed.
Since the pin controller subsystem has its pinspace local to the pin controller
@@ -291,7 +280,13 @@ controller handles control of a certain GPIO pin. Since a single pin controller
may be muxing several GPIO ranges (typically SoCs that have one set of pins,
but internally several GPIO silicon blocks, each modelled as a struct
gpio_chip) any number of GPIO ranges can be added to a pin controller instance
-like this::
+like this:
+
+.. code-block:: c
+
+ #include <linux/gpio/driver.h>
+
+ #include <linux/pinctrl/pinctrl.h>
struct gpio_chip chip_a;
struct gpio_chip chip_b;
@@ -302,7 +297,7 @@ like this::
.base = 32,
.pin_base = 32,
.npins = 16,
- .gc = &chip_a;
+ .gc = &chip_a,
};
static struct pinctrl_gpio_range gpio_range_b = {
@@ -314,16 +309,18 @@ like this::
.gc = &chip_b;
};
+ int __init foo_init(void)
{
struct pinctrl_dev *pctl;
...
pinctrl_add_gpio_range(pctl, &gpio_range_a);
pinctrl_add_gpio_range(pctl, &gpio_range_b);
+ ...
}
So this complex system has one pin controller handling two different
GPIO chips. "chip a" has 16 pins and "chip b" has 8 pins. The "chip a" and
-"chip b" have different .pin_base, which means a start pin number of the
+"chip b" have different ``pin_base``, which means a start pin number of the
GPIO range.
The GPIO range of "chip a" starts from the GPIO base of 32 and actual
@@ -331,7 +328,7 @@ pin range also starts from 32. However "chip b" has different starting
offset for the GPIO range and pin range. The GPIO range of "chip b" starts
from GPIO number 48, while the pin range of "chip b" starts from 64.
-We can convert a gpio number to actual pin number using this "pin_base".
+We can convert a gpio number to actual pin number using this ``pin_base``.
They are mapped in the global GPIO pin space at:
chip a:
@@ -343,9 +340,11 @@ chip b:
The above examples assume the mapping between the GPIOs and pins is
linear. If the mapping is sparse or haphazard, an array of arbitrary pin
-numbers can be encoded in the range like this::
+numbers can be encoded in the range like this:
- static const unsigned range_pins[] = { 14, 1, 22, 17, 10, 8, 6, 2 };
+.. code-block:: c
+
+ static const unsigned int range_pins[] = { 14, 1, 22, 17, 10, 8, 6, 2 };
static struct pinctrl_gpio_range gpio_range = {
.name = "chip",
@@ -353,16 +352,17 @@ numbers can be encoded in the range like this::
.base = 32,
.pins = &range_pins,
.npins = ARRAY_SIZE(range_pins),
- .gc = &chip;
+ .gc = &chip,
};
-In this case the pin_base property will be ignored. If the name of a pin
+In this case the ``pin_base`` property will be ignored. If the name of a pin
group is known, the pins and npins elements of the above structure can be
-initialised using the function pinctrl_get_group_pins(), e.g. for pin
-group "foo"::
+initialised using the function ``pinctrl_get_group_pins()``, e.g. for pin
+group "foo":
+
+.. code-block:: c
- pinctrl_get_group_pins(pctl, "foo", &gpio_range.pins,
- &gpio_range.npins);
+ pinctrl_get_group_pins(pctl, "foo", &gpio_range.pins, &gpio_range.npins);
When GPIO-specific functions in the pin control subsystem are called, these
ranges will be used to look up the appropriate pin controller by inspecting
@@ -378,8 +378,8 @@ will get a pin number into its handled number range. Further it is also passed
the range ID value, so that the pin controller knows which range it should
deal with.
-Calling pinctrl_add_gpio_range from pinctrl driver is DEPRECATED. Please see
-section 2.1 of Documentation/devicetree/bindings/gpio/gpio.txt on how to bind
+Calling ``pinctrl_add_gpio_range()`` from pinctrl driver is DEPRECATED. Please see
+section 2.1 of ``Documentation/devicetree/bindings/gpio/gpio.txt`` on how to bind
pinctrl and gpio drivers.
@@ -466,10 +466,10 @@ in your machine configuration. It is inspired by the clk, GPIO and regulator
subsystems, so devices will request their mux setting, but it's also possible
to request a single pin for e.g. GPIO.
-Definitions:
+The conventions are:
- FUNCTIONS can be switched in and out by a driver residing with the pin
- control subsystem in the drivers/pinctrl/* directory of the kernel. The
+ control subsystem in the ``drivers/pinctrl`` directory of the kernel. The
pin control driver knows the possible functions. In the example above you can
identify three pinmux functions, one for spi, one for i2c and one for mmc.
@@ -515,11 +515,13 @@ Definitions:
In the example case we can define that this particular machine shall
use device spi0 with pinmux function fspi0 group gspi0 and i2c0 on function
fi2c0 group gi2c0, on the primary pin controller, we get mappings
- like these::
+ like these:
+
+ .. code-block:: c
{
{"map-spi0", spi0, pinctrl0, fspi0, gspi0},
- {"map-i2c0", i2c0, pinctrl0, fi2c0, gi2c0}
+ {"map-i2c0", i2c0, pinctrl0, fi2c0, gi2c0},
}
Every map must be assigned a state name, pin controller, device and
@@ -569,80 +571,51 @@ is possible to perform the requested mux setting, poke the hardware so that
this happens.
Pinmux drivers are required to supply a few callback functions, some are
-optional. Usually the set_mux() function is implemented, writing values into
+optional. Usually the ``.set_mux()`` function is implemented, writing values into
some certain registers to activate a certain mux setting for a certain pin.
-A simple driver for the above example will work by setting bits 0, 1, 2, 3 or 4
+A simple driver for the above example will work by setting bits 0, 1, 2, 3, 4, or 5
into some register named MUX to select a certain function with a certain
-group of pins would work something like this::
+group of pins would work something like this:
+
+.. code-block:: c
#include <linux/pinctrl/pinctrl.h>
#include <linux/pinctrl/pinmux.h>
- struct foo_group {
- const char *name;
- const unsigned int *pins;
- const unsigned num_pins;
- };
-
- static const unsigned spi0_0_pins[] = { 0, 8, 16, 24 };
- static const unsigned spi0_1_pins[] = { 38, 46, 54, 62 };
- static const unsigned i2c0_pins[] = { 24, 25 };
- static const unsigned mmc0_1_pins[] = { 56, 57 };
- static const unsigned mmc0_2_pins[] = { 58, 59 };
- static const unsigned mmc0_3_pins[] = { 60, 61, 62, 63 };
-
- static const struct foo_group foo_groups[] = {
- {
- .name = "spi0_0_grp",
- .pins = spi0_0_pins,
- .num_pins = ARRAY_SIZE(spi0_0_pins),
- },
- {
- .name = "spi0_1_grp",
- .pins = spi0_1_pins,
- .num_pins = ARRAY_SIZE(spi0_1_pins),
- },
- {
- .name = "i2c0_grp",
- .pins = i2c0_pins,
- .num_pins = ARRAY_SIZE(i2c0_pins),
- },
- {
- .name = "mmc0_1_grp",
- .pins = mmc0_1_pins,
- .num_pins = ARRAY_SIZE(mmc0_1_pins),
- },
- {
- .name = "mmc0_2_grp",
- .pins = mmc0_2_pins,
- .num_pins = ARRAY_SIZE(mmc0_2_pins),
- },
- {
- .name = "mmc0_3_grp",
- .pins = mmc0_3_pins,
- .num_pins = ARRAY_SIZE(mmc0_3_pins),
- },
+ static const unsigned int spi0_0_pins[] = { 0, 8, 16, 24 };
+ static const unsigned int spi0_1_pins[] = { 38, 46, 54, 62 };
+ static const unsigned int i2c0_pins[] = { 24, 25 };
+ static const unsigned int mmc0_1_pins[] = { 56, 57 };
+ static const unsigned int mmc0_2_pins[] = { 58, 59 };
+ static const unsigned int mmc0_3_pins[] = { 60, 61, 62, 63 };
+
+ static const struct pingroup foo_groups[] = {
+ PINCTRL_PINGROUP("spi0_0_grp", spi0_0_pins, ARRAY_SIZE(spi0_0_pins)),
+ PINCTRL_PINGROUP("spi0_1_grp", spi0_1_pins, ARRAY_SIZE(spi0_1_pins)),
+ PINCTRL_PINGROUP("i2c0_grp", i2c0_pins, ARRAY_SIZE(i2c0_pins)),
+ PINCTRL_PINGROUP("mmc0_1_grp", mmc0_1_pins, ARRAY_SIZE(mmc0_1_pins)),
+ PINCTRL_PINGROUP("mmc0_2_grp", mmc0_2_pins, ARRAY_SIZE(mmc0_2_pins)),
+ PINCTRL_PINGROUP("mmc0_3_grp", mmc0_3_pins, ARRAY_SIZE(mmc0_3_pins)),
};
-
static int foo_get_groups_count(struct pinctrl_dev *pctldev)
{
return ARRAY_SIZE(foo_groups);
}
static const char *foo_get_group_name(struct pinctrl_dev *pctldev,
- unsigned selector)
+ unsigned int selector)
{
return foo_groups[selector].name;
}
- static int foo_get_group_pins(struct pinctrl_dev *pctldev, unsigned selector,
- const unsigned ** pins,
- unsigned * num_pins)
+ static int foo_get_group_pins(struct pinctrl_dev *pctldev, unsigned int selector,
+ const unsigned int **pins,
+ unsigned int *npins)
{
- *pins = (unsigned *) foo_groups[selector].pins;
- *num_pins = foo_groups[selector].num_pins;
+ *pins = foo_groups[selector].pins;
+ *npins = foo_groups[selector].npins;
return 0;
}
@@ -652,33 +625,14 @@ group of pins would work something like this::
.get_group_pins = foo_get_group_pins,
};
- struct foo_pmx_func {
- const char *name;
- const char * const *groups;
- const unsigned num_groups;
- };
-
static const char * const spi0_groups[] = { "spi0_0_grp", "spi0_1_grp" };
static const char * const i2c0_groups[] = { "i2c0_grp" };
- static const char * const mmc0_groups[] = { "mmc0_1_grp", "mmc0_2_grp",
- "mmc0_3_grp" };
+ static const char * const mmc0_groups[] = { "mmc0_1_grp", "mmc0_2_grp", "mmc0_3_grp" };
- static const struct foo_pmx_func foo_functions[] = {
- {
- .name = "spi0",
- .groups = spi0_groups,
- .num_groups = ARRAY_SIZE(spi0_groups),
- },
- {
- .name = "i2c0",
- .groups = i2c0_groups,
- .num_groups = ARRAY_SIZE(i2c0_groups),
- },
- {
- .name = "mmc0",
- .groups = mmc0_groups,
- .num_groups = ARRAY_SIZE(mmc0_groups),
- },
+ static const struct pinfunction foo_functions[] = {
+ PINCTRL_PINFUNCTION("spi0", spi0_groups, ARRAY_SIZE(spi0_groups)),
+ PINCTRL_PINFUNCTION("i2c0", i2c0_groups, ARRAY_SIZE(i2c0_groups)),
+ PINCTRL_PINFUNCTION("mmc0", mmc0_groups, ARRAY_SIZE(mmc0_groups)),
};
static int foo_get_functions_count(struct pinctrl_dev *pctldev)
@@ -686,26 +640,26 @@ group of pins would work something like this::
return ARRAY_SIZE(foo_functions);
}
- static const char *foo_get_fname(struct pinctrl_dev *pctldev, unsigned selector)
+ static const char *foo_get_fname(struct pinctrl_dev *pctldev, unsigned int selector)
{
return foo_functions[selector].name;
}
- static int foo_get_groups(struct pinctrl_dev *pctldev, unsigned selector,
- const char * const **groups,
- unsigned * const num_groups)
+ static int foo_get_groups(struct pinctrl_dev *pctldev, unsigned int selector,
+ const char * const **groups,
+ unsigned int * const ngroups)
{
*groups = foo_functions[selector].groups;
- *num_groups = foo_functions[selector].num_groups;
+ *ngroups = foo_functions[selector].ngroups;
return 0;
}
- static int foo_set_mux(struct pinctrl_dev *pctldev, unsigned selector,
- unsigned group)
+ static int foo_set_mux(struct pinctrl_dev *pctldev, unsigned int selector,
+ unsigned int group)
{
- u8 regbit = (1 << selector + group);
+ u8 regbit = BIT(group);
- writeb((readb(MUX)|regbit), MUX);
+ writeb((readb(MUX) | regbit), MUX);
return 0;
}
@@ -724,16 +678,17 @@ group of pins would work something like this::
.pmxops = &foo_pmxops,
};
-In the example activating muxing 0 and 1 at the same time setting bits
-0 and 1, uses one pin in common so they would collide.
+In the example activating muxing 0 and 2 at the same time setting bits
+0 and 2, uses pin 24 in common so they would collide. All the same for
+the muxes 1 and 5, which have pin 62 in common.
The beauty of the pinmux subsystem is that since it keeps track of all
pins and who is using them, it will already have denied an impossible
request like that, so the driver does not need to worry about such
things - when it gets a selector passed in, the pinmux subsystem makes
sure no other device or GPIO assignment is already using the selected
-pins. Thus bits 0 and 1 in the control register will never be set at the
-same time.
+pins. Thus bits 0 and 2, or 1 and 5 in the control register will never
+be set at the same time.
All the above functions are mandatory to implement for a pinmux driver.
@@ -742,18 +697,18 @@ Pin control interaction with the GPIO subsystem
===============================================
Note that the following implies that the use case is to use a certain pin
-from the Linux kernel using the API in <linux/gpio.h> with gpio_request()
+from the Linux kernel using the API in ``<linux/gpio/consumer.h>`` with gpiod_get()
and similar functions. There are cases where you may be using something
that your datasheet calls "GPIO mode", but actually is just an electrical
configuration for a certain device. See the section below named
-"GPIO mode pitfalls" for more details on this scenario.
+`GPIO mode pitfalls`_ for more details on this scenario.
-The public pinmux API contains two functions named pinctrl_gpio_request()
-and pinctrl_gpio_free(). These two functions shall *ONLY* be called from
-gpiolib-based drivers as part of their gpio_request() and
-gpio_free() semantics. Likewise the pinctrl_gpio_direction_[input|output]
-shall only be called from within respective gpio_direction_[input|output]
-gpiolib implementation.
+The public pinmux API contains two functions named ``pinctrl_gpio_request()``
+and ``pinctrl_gpio_free()``. These two functions shall *ONLY* be called from
+gpiolib-based drivers as part of their ``.request()`` and ``.free()`` semantics.
+Likewise the ``pinctrl_gpio_direction_input()`` / ``pinctrl_gpio_direction_output()``
+shall only be called from within respective ``.direction_input()`` /
+``.direction_output()`` gpiolib implementation.
NOTE that platforms and individual drivers shall *NOT* request GPIO pins to be
controlled e.g. muxed in. Instead, implement a proper gpiolib driver and have
@@ -767,8 +722,8 @@ In this case, the function array would become 64 entries for each GPIO
setting and then the device functions.
For this reason there are two functions a pin control driver can implement
-to enable only GPIO on an individual pin: .gpio_request_enable() and
-.gpio_disable_free().
+to enable only GPIO on an individual pin: ``.gpio_request_enable()`` and
+``.gpio_disable_free()``.
This function will pass in the affected GPIO range identified by the pin
controller core, so you know which GPIO pins are being affected by the request
@@ -776,12 +731,12 @@ operation.
If your driver needs to have an indication from the framework of whether the
GPIO pin shall be used for input or output you can implement the
-.gpio_set_direction() function. As described this shall be called from the
+``.gpio_set_direction()`` function. As described this shall be called from the
gpiolib driver and the affected GPIO range, pin offset and desired direction
will be passed along to this function.
Alternatively to using these special functions, it is fully allowed to use
-named functions for each GPIO pin, the pinctrl_gpio_request() will attempt to
+named functions for each GPIO pin, the ``pinctrl_gpio_request()`` will attempt to
obtain the function "gpioN" where "N" is the global GPIO pin number if no
special GPIO-handler is registered.
@@ -794,7 +749,7 @@ is taken to mean different things than what the kernel does, the developer
may be confused by a datasheet talking about a pin being possible to set
into "GPIO mode". It appears that what hardware engineers mean with
"GPIO mode" is not necessarily the use case that is implied in the kernel
-interface <linux/gpio.h>: a pin that you grab from kernel code and then
+interface ``<linux/gpio/consumer.h>``: a pin that you grab from kernel code and then
either listen for input or drive high/low to assert/deassert some
external line.
@@ -805,9 +760,10 @@ for a device.
The GPIO portions of a pin and its relation to a certain pin controller
configuration and muxing logic can be constructed in several ways. Here
-are two examples::
+are two examples.
+
+Example **(A)**::
- (A)
pin config
logic regs
| +- SPI
@@ -836,9 +792,7 @@ simultaneous access to the same pin from GPIO and pin multiplexing
consumers on hardware of this type. The pinctrl driver should set this flag
accordingly.
-::
-
- (B)
+Example **(B)**::
pin config
logic regs
@@ -882,7 +836,7 @@ hardware and shall be put into different subsystems:
Depending on the exact HW register design, some functions exposed by the
GPIO subsystem may call into the pinctrl subsystem in order to
-co-ordinate register settings across HW modules. In particular, this may
+coordinate register settings across HW modules. In particular, this may
be needed for HW with separate GPIO and pin controller HW modules, where
e.g. GPIO direction is determined by a register in the pin controller HW
module rather than the GPIO HW module.
@@ -899,14 +853,14 @@ If you make a 1-to-1 map to the GPIO subsystem for this pin, you may start
to think that you need to come up with something really complex, that the
pin shall be used for UART TX and GPIO at the same time, that you will grab
a pin control handle and set it to a certain state to enable UART TX to be
-muxed in, then twist it over to GPIO mode and use gpio_direction_output()
+muxed in, then twist it over to GPIO mode and use gpiod_direction_output()
to drive it low during sleep, then mux it over to UART TX again when you
-wake up and maybe even gpio_request/gpio_free as part of this cycle. This
+wake up and maybe even gpiod_get() / gpiod_put() as part of this cycle. This
all gets very complicated.
The solution is to not think that what the datasheet calls "GPIO mode"
-has to be handled by the <linux/gpio.h> interface. Instead view this as
-a certain pin config setting. Look in e.g. <linux/pinctrl/pinconf-generic.h>
+has to be handled by the ``<linux/gpio/consumer.h>`` interface. Instead view this as
+a certain pin config setting. Look in e.g. ``<linux/pinctrl/pinconf-generic.h>``
and you find this in the documentation:
PIN_CONFIG_OUTPUT:
@@ -915,7 +869,9 @@ and you find this in the documentation:
So it is perfectly possible to push a pin into "GPIO mode" and drive the
line low as part of the usual pin control map. So for example your UART
-driver may look like this::
+driver may look like this:
+
+.. code-block:: c
#include <linux/pinctrl/consumer.h>
@@ -928,13 +884,13 @@ driver may look like this::
/* Normal mode */
retval = pinctrl_select_state(pinctrl, pins_default);
+
/* Sleep mode */
retval = pinctrl_select_state(pinctrl, pins_sleep);
And your machine configuration may look like this:
---------------------------------------------------
-::
+.. code-block:: c
static unsigned long uart_default_mode[] = {
PIN_CONF_PACKED(PIN_CONFIG_DRIVE_PUSH_PULL, 0),
@@ -946,16 +902,17 @@ And your machine configuration may look like this:
static struct pinctrl_map pinmap[] __initdata = {
PIN_MAP_MUX_GROUP("uart", PINCTRL_STATE_DEFAULT, "pinctrl-foo",
- "u0_group", "u0"),
+ "u0_group", "u0"),
PIN_MAP_CONFIGS_PIN("uart", PINCTRL_STATE_DEFAULT, "pinctrl-foo",
- "UART_TX_PIN", uart_default_mode),
+ "UART_TX_PIN", uart_default_mode),
PIN_MAP_MUX_GROUP("uart", PINCTRL_STATE_SLEEP, "pinctrl-foo",
- "u0_group", "gpio-mode"),
+ "u0_group", "gpio-mode"),
PIN_MAP_CONFIGS_PIN("uart", PINCTRL_STATE_SLEEP, "pinctrl-foo",
- "UART_TX_PIN", uart_sleep_mode),
+ "UART_TX_PIN", uart_sleep_mode),
};
- foo_init(void) {
+ foo_init(void)
+ {
pinctrl_register_mappings(pinmap, ARRAY_SIZE(pinmap));
}
@@ -995,7 +952,9 @@ part of this.
A pin controller configuration for a machine looks pretty much like a simple
regulator configuration, so for the example array above we want to enable i2c
-and spi on the second function mapping::
+and spi on the second function mapping:
+
+.. code-block:: c
#include <linux/pinctrl/machine.h>
@@ -1030,13 +989,17 @@ must match a function provided by the pinmux driver handling this pin range.
As you can see we may have several pin controllers on the system and thus
we need to specify which one of them contains the functions we wish to map.
-You register this pinmux mapping to the pinmux subsystem by simply::
+You register this pinmux mapping to the pinmux subsystem by simply:
+
+.. code-block:: c
ret = pinctrl_register_mappings(mapping, ARRAY_SIZE(mapping));
Since the above construct is pretty common there is a helper macro to make
it even more compact which assumes you want to use pinctrl-foo and position
-0 for mapping, for example::
+0 for mapping, for example:
+
+.. code-block:: c
static struct pinctrl_map mapping[] __initdata = {
PIN_MAP_MUX_GROUP("foo-i2c.o", PINCTRL_STATE_DEFAULT,
@@ -1046,7 +1009,9 @@ it even more compact which assumes you want to use pinctrl-foo and position
The mapping table may also contain pin configuration entries. It's common for
each pin/group to have a number of configuration entries that affect it, so
the table entries for configuration reference an array of config parameters
-and values. An example using the convenience macros is shown below::
+and values. An example using the convenience macros is shown below:
+
+.. code-block:: c
static unsigned long i2c_grp_configs[] = {
FOO_PIN_DRIVEN,
@@ -1073,8 +1038,10 @@ Finally, some devices expect the mapping table to contain certain specific
named states. When running on hardware that doesn't need any pin controller
configuration, the mapping table must still contain those named states, in
order to explicitly indicate that the states were provided and intended to
-be empty. Table entry macro PIN_MAP_DUMMY_STATE serves the purpose of defining
-a named state without causing any pin controller to be programmed::
+be empty. Table entry macro ``PIN_MAP_DUMMY_STATE()`` serves the purpose of defining
+a named state without causing any pin controller to be programmed:
+
+.. code-block:: c
static struct pinctrl_map mapping[] __initdata = {
PIN_MAP_DUMMY_STATE("foo-i2c.0", PINCTRL_STATE_DEFAULT),
@@ -1085,7 +1052,9 @@ Complex mappings
================
As it is possible to map a function to different groups of pins an optional
-.group can be specified like this::
+.group can be specified like this:
+
+.. code-block:: c
...
{
@@ -1107,13 +1076,15 @@ As it is possible to map a function to different groups of pins an optional
...
This example mapping is used to switch between two positions for spi0 at
-runtime, as described further below under the heading "Runtime pinmuxing".
+runtime, as described further below under the heading `Runtime pinmuxing`_.
Further it is possible for one named state to affect the muxing of several
groups of pins, say for example in the mmc0 example above, where you can
additively expand the mmc0 bus from 2 to 4 to 8 pins. If we want to use all
-three groups for a total of 2+2+4 = 8 pins (for an 8-bit MMC bus as is the
-case), we define a mapping like this::
+three groups for a total of 2 + 2 + 4 = 8 pins (for an 8-bit MMC bus as is the
+case), we define a mapping like this:
+
+.. code-block:: c
...
{
@@ -1167,13 +1138,17 @@ case), we define a mapping like this::
...
The result of grabbing this mapping from the device with something like
-this (see next paragraph)::
+this (see next paragraph):
+
+.. code-block:: c
p = devm_pinctrl_get(dev);
s = pinctrl_lookup_state(p, "8bit");
ret = pinctrl_select_state(p, s);
-or more simply::
+or more simply:
+
+.. code-block:: c
p = devm_pinctrl_get_select(dev, "8bit");
@@ -1188,7 +1163,7 @@ Pin control requests from drivers
=================================
When a device driver is about to probe the device core will automatically
-attempt to issue pinctrl_get_select_default() on these devices.
+attempt to issue ``pinctrl_get_select_default()`` on these devices.
This way driver writers do not need to add any of the boilerplate code
of the type found below. However when doing fine-grained state selection
and not using the "default" state, you may have to do some device driver
@@ -1206,12 +1181,14 @@ some cases where a driver needs to e.g. switch between different mux mappings
at runtime this is not possible.
A typical case is if a driver needs to switch bias of pins from normal
-operation and going to sleep, moving from the PINCTRL_STATE_DEFAULT to
-PINCTRL_STATE_SLEEP at runtime, re-biasing or even re-muxing pins to save
+operation and going to sleep, moving from the ``PINCTRL_STATE_DEFAULT`` to
+``PINCTRL_STATE_SLEEP`` at runtime, re-biasing or even re-muxing pins to save
current in sleep mode.
A driver may request a certain control state to be activated, usually just the
-default state like this::
+default state like this:
+
+.. code-block:: c
#include <linux/pinctrl/consumer.h>
@@ -1235,10 +1212,10 @@ default state like this::
foo->s = pinctrl_lookup_state(foo->p, PINCTRL_STATE_DEFAULT);
if (IS_ERR(foo->s)) {
/* FIXME: clean up "foo" here */
- return PTR_ERR(s);
+ return PTR_ERR(foo->s);
}
- ret = pinctrl_select_state(foo->s);
+ ret = pinctrl_select_state(foo->p, foo->s);
if (ret < 0) {
/* FIXME: clean up "foo" here */
return ret;
@@ -1251,49 +1228,49 @@ arrangement on your bus.
The semantics of the pinctrl APIs are:
-- pinctrl_get() is called in process context to obtain a handle to all pinctrl
+- ``pinctrl_get()`` is called in process context to obtain a handle to all pinctrl
information for a given client device. It will allocate a struct from the
kernel memory to hold the pinmux state. All mapping table parsing or similar
slow operations take place within this API.
-- devm_pinctrl_get() is a variant of pinctrl_get() that causes pinctrl_put()
+- ``devm_pinctrl_get()`` is a variant of pinctrl_get() that causes ``pinctrl_put()``
to be called automatically on the retrieved pointer when the associated
device is removed. It is recommended to use this function over plain
- pinctrl_get().
+ ``pinctrl_get()``.
-- pinctrl_lookup_state() is called in process context to obtain a handle to a
+- ``pinctrl_lookup_state()`` is called in process context to obtain a handle to a
specific state for a client device. This operation may be slow, too.
-- pinctrl_select_state() programs pin controller hardware according to the
+- ``pinctrl_select_state()`` programs pin controller hardware according to the
definition of the state as given by the mapping table. In theory, this is a
fast-path operation, since it only involved blasting some register settings
into hardware. However, note that some pin controllers may have their
registers on a slow/IRQ-based bus, so client devices should not assume they
- can call pinctrl_select_state() from non-blocking contexts.
+ can call ``pinctrl_select_state()`` from non-blocking contexts.
-- pinctrl_put() frees all information associated with a pinctrl handle.
+- ``pinctrl_put()`` frees all information associated with a pinctrl handle.
-- devm_pinctrl_put() is a variant of pinctrl_put() that may be used to
- explicitly destroy a pinctrl object returned by devm_pinctrl_get().
+- ``devm_pinctrl_put()`` is a variant of ``pinctrl_put()`` that may be used to
+ explicitly destroy a pinctrl object returned by ``devm_pinctrl_get()``.
However, use of this function will be rare, due to the automatic cleanup
that will occur even without calling it.
- pinctrl_get() must be paired with a plain pinctrl_put().
- pinctrl_get() may not be paired with devm_pinctrl_put().
- devm_pinctrl_get() can optionally be paired with devm_pinctrl_put().
- devm_pinctrl_get() may not be paired with plain pinctrl_put().
+ ``pinctrl_get()`` must be paired with a plain ``pinctrl_put()``.
+ ``pinctrl_get()`` may not be paired with ``devm_pinctrl_put()``.
+ ``devm_pinctrl_get()`` can optionally be paired with ``devm_pinctrl_put()``.
+ ``devm_pinctrl_get()`` may not be paired with plain ``pinctrl_put()``.
Usually the pin control core handled the get/put pair and call out to the
device drivers bookkeeping operations, like checking available functions and
-the associated pins, whereas select_state pass on to the pin controller
+the associated pins, whereas ``pinctrl_select_state()`` pass on to the pin controller
driver which takes care of activating and/or deactivating the mux setting by
quickly poking some registers.
-The pins are allocated for your device when you issue the devm_pinctrl_get()
+The pins are allocated for your device when you issue the ``devm_pinctrl_get()``
call, after this you should be able to see this in the debugfs listing of all
pins.
-NOTE: the pinctrl system will return -EPROBE_DEFER if it cannot find the
+NOTE: the pinctrl system will return ``-EPROBE_DEFER`` if it cannot find the
requested pinctrl handles, for example if the pinctrl driver has not yet
registered. Thus make sure that the error path in your driver gracefully
cleans up and is ready to retry the probing later in the startup process.
@@ -1305,18 +1282,20 @@ Drivers needing both pin control and GPIOs
Again, it is discouraged to let drivers lookup and select pin control states
themselves, but again sometimes this is unavoidable.
-So say that your driver is fetching its resources like this::
+So say that your driver is fetching its resources like this:
+
+.. code-block:: c
#include <linux/pinctrl/consumer.h>
- #include <linux/gpio.h>
+ #include <linux/gpio/consumer.h>
struct pinctrl *pinctrl;
- int gpio;
+ struct gpio_desc *gpio;
pinctrl = devm_pinctrl_get_select_default(&dev);
- gpio = devm_gpio_request(&dev, 14, "foo");
+ gpio = devm_gpiod_get(&dev, "foo");
-Here we first request a certain pin state and then request GPIO 14 to be
+Here we first request a certain pin state and then request GPIO "foo" to be
used. If you're using the subsystems orthogonally like this, you should
nominally always get your pinctrl handle and select the desired pinctrl
state BEFORE requesting the GPIO. This is a semantic convention to avoid
@@ -1331,9 +1310,9 @@ probing, nevertheless orthogonal to the GPIO subsystem.
But there are also situations where it makes sense for the GPIO subsystem
to communicate directly with the pinctrl subsystem, using the latter as a
back-end. This is when the GPIO driver may call out to the functions
-described in the section "Pin control interaction with the GPIO subsystem"
+described in the section `Pin control interaction with the GPIO subsystem`_
above. This only involves per-pin multiplexing, and will be completely
-hidden behind the gpio_*() function namespace. In this case, the driver
+hidden behind the gpiod_*() function namespace. In this case, the driver
need not interact with the pin control subsystem at all.
If a pin control driver and a GPIO driver is dealing with the same pins
@@ -1348,12 +1327,14 @@ System pin control hogging
==========================
Pin control map entries can be hogged by the core when the pin controller
-is registered. This means that the core will attempt to call pinctrl_get(),
-lookup_state() and select_state() on it immediately after the pin control
-device has been registered.
+is registered. This means that the core will attempt to call ``pinctrl_get()``,
+``pinctrl_lookup_state()`` and ``pinctrl_select_state()`` on it immediately after
+the pin control device has been registered.
This occurs for mapping table entries where the client device name is equal
-to the pin controller device name, and the state name is PINCTRL_STATE_DEFAULT::
+to the pin controller device name, and the state name is ``PINCTRL_STATE_DEFAULT``:
+
+.. code-block:: c
{
.dev_name = "pinctrl-foo",
@@ -1365,7 +1346,9 @@ to the pin controller device name, and the state name is PINCTRL_STATE_DEFAULT::
Since it may be common to request the core to hog a few always-applicable
mux settings on the primary pin controller, there is a convenience macro for
-this::
+this:
+
+.. code-block:: c
PIN_MAP_MUX_GROUP_HOG_DEFAULT("pinctrl-foo", NULL /* group */,
"power_func")
@@ -1385,7 +1368,9 @@ function, but with different named in the mapping as described under
This snippet first initializes a state object for both groups (in foo_probe()),
then muxes the function in the pins defined by group A, and finally muxes it in
-on the pins defined by group B::
+on the pins defined by group B:
+
+.. code-block:: c
#include <linux/pinctrl/consumer.h>
@@ -1399,11 +1384,11 @@ on the pins defined by group B::
if (IS_ERR(p))
...
- s1 = pinctrl_lookup_state(foo->p, "pos-A");
+ s1 = pinctrl_lookup_state(p, "pos-A");
if (IS_ERR(s1))
...
- s2 = pinctrl_lookup_state(foo->p, "pos-B");
+ s2 = pinctrl_lookup_state(p, "pos-B");
if (IS_ERR(s2))
...
}
@@ -1411,16 +1396,16 @@ on the pins defined by group B::
foo_switch()
{
/* Enable on position A */
- ret = pinctrl_select_state(s1);
+ ret = pinctrl_select_state(p, s1);
if (ret < 0)
- ...
+ ...
...
/* Enable on position B */
- ret = pinctrl_select_state(s2);
+ ret = pinctrl_select_state(p, s2);
if (ret < 0)
- ...
+ ...
...
}
@@ -1428,3 +1413,43 @@ on the pins defined by group B::
The above has to be done from process context. The reservation of the pins
will be done when the state is activated, so in effect one specific pin
can be used by different functions at different times on a running system.
+
+
+Debugfs files
+=============
+
+These files are created in ``/sys/kernel/debug/pinctrl``:
+
+- ``pinctrl-devices``: prints each pin controller device along with columns to
+ indicate support for pinmux and pinconf
+
+- ``pinctrl-handles``: prints each configured pin controller handle and the
+ corresponding pinmux maps
+
+- ``pinctrl-maps``: prints all pinctrl maps
+
+A sub-directory is created inside of ``/sys/kernel/debug/pinctrl`` for each pin
+controller device containing these files:
+
+- ``pins``: prints a line for each pin registered on the pin controller. The
+ pinctrl driver may add additional information such as register contents.
+
+- ``gpio-ranges``: prints ranges that map gpio lines to pins on the controller
+
+- ``pingroups``: prints all pin groups registered on the pin controller
+
+- ``pinconf-pins``: prints pin config settings for each pin
+
+- ``pinconf-groups``: prints pin config settings per pin group
+
+- ``pinmux-functions``: prints each pin function along with the pin groups that
+ map to the pin function
+
+- ``pinmux-pins``: iterates through all pins and prints mux owner, gpio owner
+ and if the pin is a hog
+
+- ``pinmux-select``: write to this file to activate a pin function for a group:
+
+ .. code-block:: sh
+
+ echo "<group-name function-name>" > pinmux-select
diff --git a/Documentation/driver-api/pldmfw/driver-ops.rst b/Documentation/driver-api/pldmfw/driver-ops.rst
new file mode 100644
index 000000000000..f0654783d3b3
--- /dev/null
+++ b/Documentation/driver-api/pldmfw/driver-ops.rst
@@ -0,0 +1,56 @@
+.. SPDX-License-Identifier: GPL-2.0-only
+
+=========================
+Driver-specific callbacks
+=========================
+
+The ``pldmfw`` module relies on the device driver for implementing device
+specific behavior using the following operations.
+
+``.match_record``
+-----------------
+
+The ``.match_record`` operation is used to determine whether a given PLDM
+record matches the device being updated. This requires comparing the record
+descriptors in the record with information from the device. Many record
+descriptors are defined by the PLDM standard, but it is also allowed for
+devices to implement their own descriptors.
+
+The ``.match_record`` operation should return true if a given record matches
+the device.
+
+``.send_package_data``
+----------------------
+
+The ``.send_package_data`` operation is used to send the device-specific
+package data in a record to the device firmware. If the matching record
+provides package data, ``pldmfw`` will call the ``.send_package_data``
+function with a pointer to the package data and with the package data
+length. The device driver should send this data to firmware.
+
+``.send_component_table``
+-------------------------
+
+The ``.send_component_table`` operation is used to forward component
+information to the device. It is called once for each applicable component,
+that is, for each component indicated by the matching record. The
+device driver should send the component information to the device firmware,
+and wait for a response. The provided transfer flag indicates whether this
+is the first, last, or a middle component, and is expected to be forwarded
+to firmware as part of the component table information. The driver should an
+error in the case when the firmware indicates that the component cannot be
+updated, or return zero if the component can be updated.
+
+``.flash_component``
+--------------------
+
+The ``.flash_component`` operation is used to inform the device driver to
+flash a given component. The driver must perform any steps necessary to send
+the component data to the device.
+
+``.finalize_update``
+--------------------
+
+The ``.finalize_update`` operation is used by the ``pldmfw`` library in
+order to allow the device driver to perform any remaining device specific
+logic needed to finish the update.
diff --git a/Documentation/driver-api/pldmfw/file-format.rst b/Documentation/driver-api/pldmfw/file-format.rst
new file mode 100644
index 000000000000..b7a9cebe09c6
--- /dev/null
+++ b/Documentation/driver-api/pldmfw/file-format.rst
@@ -0,0 +1,203 @@
+.. SPDX-License-Identifier: GPL-2.0-only
+
+==================================
+PLDM Firmware file format overview
+==================================
+
+A PLDM firmware package is a binary file which contains a header that
+describes the contents of the firmware package. This includes an initial
+package header, one or more firmware records, and one or more components
+describing the actual flash contents to program.
+
+This diagram provides an overview of the file format::
+
+ overall file layout
+ +----------------------+
+ | |
+ | Package Header |
+ | |
+ +----------------------+
+ | |
+ | Device Records |
+ | |
+ +----------------------+
+ | |
+ | Component Info |
+ | |
+ +----------------------+
+ | |
+ | Package Header CRC |
+ | |
+ +----------------------+
+ | |
+ | Component Image 1 |
+ | |
+ +----------------------+
+ | |
+ | Component Image 2 |
+ | |
+ +----------------------+
+ | |
+ | ... |
+ | |
+ +----------------------+
+ | |
+ | Component Image N |
+ | |
+ +----------------------+
+
+Package Header
+==============
+
+The package header begins with the UUID of the PLDM file format, and
+contains information about the version of the format that the file uses. It
+also includes the total header size, a release date, the size of the
+component bitmap, and an overall package version.
+
+The following diagram provides an overview of the package header::
+
+ header layout
+ +-------------------------+
+ | PLDM UUID |
+ +-------------------------+
+ | Format Revision |
+ +-------------------------+
+ | Header Size |
+ +-------------------------+
+ | Release Date |
+ +-------------------------+
+ | Component Bitmap Length |
+ +-------------------------+
+ | Package Version Info |
+ +-------------------------+
+
+Device Records
+==============
+
+The device firmware records area starts with a count indicating the total
+number of records in the file, followed by each record. A single device
+record describes what device matches this record. All valid PLDM firmware
+files must contain at least one record, but optionally may contain more than
+one record if they support multiple devices.
+
+Each record will identify the device it supports via TLVs that describe the
+device, such as the PCI device and vendor information. It will also indicate
+which set of components that are used by this device. It is possible that
+only subset of provided components will be used by a given record. A record
+may also optionally contain device-specific package data that will be used
+by the device firmware during the update process.
+
+The following diagram provides an overview of the device record area::
+
+ area layout
+ +---------------+
+ | |
+ | Record Count |
+ | |
+ +---------------+
+ | |
+ | Record 1 |
+ | |
+ +---------------+
+ | |
+ | Record 2 |
+ | |
+ +---------------+
+ | |
+ | ... |
+ | |
+ +---------------+
+ | |
+ | Record N |
+ | |
+ +---------------+
+
+ record layout
+ +-----------------------+
+ | Record Length |
+ +-----------------------+
+ | Descriptor Count |
+ +-----------------------+
+ | Option Flags |
+ +-----------------------+
+ | Version Settings |
+ +-----------------------+
+ | Package Data Length |
+ +-----------------------+
+ | Applicable Components |
+ +-----------------------+
+ | Version String |
+ +-----------------------+
+ | Descriptor TLVs |
+ +-----------------------+
+ | Package Data |
+ +-----------------------+
+
+Component Info
+==============
+
+The component information area begins with a count of the number of
+components. Following this count is a description for each component. The
+component information points to the location in the file where the component
+data is stored, and includes version data used to identify the version of
+the component.
+
+The following diagram provides an overview of the component area::
+
+ area layout
+ +-----------------+
+ | |
+ | Component Count |
+ | |
+ +-----------------+
+ | |
+ | Component 1 |
+ | |
+ +-----------------+
+ | |
+ | Component 2 |
+ | |
+ +-----------------+
+ | |
+ | ... |
+ | |
+ +-----------------+
+ | |
+ | Component N |
+ | |
+ +-----------------+
+
+ component layout
+ +------------------------+
+ | Classification |
+ +------------------------+
+ | Component Identifier |
+ +------------------------+
+ | Comparison Stamp |
+ +------------------------+
+ | Component Options |
+ +------------------------+
+ | Activation Method |
+ +------------------------+
+ | Location Offset |
+ +------------------------+
+ | Component Size |
+ +------------------------+
+ | Component Version Info |
+ +------------------------+
+ | Package Data |
+ +------------------------+
+
+
+Package Header CRC
+==================
+
+Following the component information is a short 4-byte CRC calculated over
+the contents of all of the header information.
+
+Component Images
+================
+
+The component images follow the package header information in the PLDM
+firmware file. Each of these is simply a binary chunk with its start and
+size defined by the matching component structure in the component info area.
diff --git a/Documentation/driver-api/pldmfw/index.rst b/Documentation/driver-api/pldmfw/index.rst
new file mode 100644
index 000000000000..fd871b83f34f
--- /dev/null
+++ b/Documentation/driver-api/pldmfw/index.rst
@@ -0,0 +1,72 @@
+.. SPDX-License-Identifier: GPL-2.0-only
+
+==================================
+PLDM Firmware Flash Update Library
+==================================
+
+``pldmfw`` implements functionality for updating the flash on a device using
+the PLDM for Firmware Update standard
+<https://www.dmtf.org/documents/pmci/pldm-firmware-update-specification-100>.
+
+.. toctree::
+ :maxdepth: 1
+
+ file-format
+ driver-ops
+
+==================================
+Overview of the ``pldmfw`` library
+==================================
+
+The ``pldmfw`` library is intended to be used by device drivers for
+implementing device flash update based on firmware files following the PLDM
+firmware file format.
+
+It is implemented using an ops table that allows device drivers to provide
+the underlying device specific functionality.
+
+``pldmfw`` implements logic to parse the packed binary format of the PLDM
+firmware file into data structures, and then uses the provided function
+operations to determine if the firmware file is a match for the device. If
+so, it sends the record and component data to the firmware using the device
+specific implementations provided by device drivers. Once the device
+firmware indicates that the update may be performed, the firmware data is
+sent to the device for programming.
+
+Parsing the PLDM file
+=====================
+
+The PLDM file format uses packed binary data, with most multi-byte fields
+stored in the Little Endian format. Several pieces of data are variable
+length, including version strings and the number of records and components.
+Due to this, it is not straight forward to index the record, record
+descriptors, or components.
+
+To avoid proliferating access to the packed binary data, the ``pldmfw``
+library parses and extracts this data into simpler structures for ease of
+access.
+
+In order to safely process the firmware file, care is taken to avoid
+unaligned access of multi-byte fields, and to properly convert from Little
+Endian to CPU host format. Additionally the records, descriptors, and
+components are stored in linked lists.
+
+Performing a flash update
+=========================
+
+To perform a flash update, the ``pldmfw`` module performs the following
+steps
+
+1. Parse the firmware file for record and component information
+2. Scan through the records and determine if the device matches any record
+ in the file. The first matched record will be used.
+3. If the matching record provides package data, send this package data to
+ the device.
+4. For each component that the record indicates, send the component data to
+ the device. For each component, the firmware may respond with an
+ indication of whether the update is suitable or not. If any component is
+ not suitable, the update is canceled.
+5. For each component, send the binary data to the device firmware for
+ updating.
+6. After all components are programmed, perform any final device-specific
+ actions to finalize the update.
diff --git a/Documentation/driver-api/pm/cpuidle.rst b/Documentation/driver-api/pm/cpuidle.rst
index 006cf6db40c6..d477208604b8 100644
--- a/Documentation/driver-api/pm/cpuidle.rst
+++ b/Documentation/driver-api/pm/cpuidle.rst
@@ -1,11 +1,6 @@
.. SPDX-License-Identifier: GPL-2.0
.. include:: <isonum.txt>
-.. |struct cpuidle_governor| replace:: :c:type:`struct cpuidle_governor <cpuidle_governor>`
-.. |struct cpuidle_device| replace:: :c:type:`struct cpuidle_device <cpuidle_device>`
-.. |struct cpuidle_driver| replace:: :c:type:`struct cpuidle_driver <cpuidle_driver>`
-.. |struct cpuidle_state| replace:: :c:type:`struct cpuidle_state <cpuidle_state>`
-
========================
CPU Idle Time Management
========================
@@ -54,7 +49,7 @@ platform that the Linux kernel can run on. For this reason, data structures
operated on by them cannot depend on any hardware architecture or platform
design details as well.
-The governor itself is represented by a |struct cpuidle_governor| object
+The governor itself is represented by a struct cpuidle_governor object
containing four callback pointers, :c:member:`enable`, :c:member:`disable`,
:c:member:`select`, :c:member:`reflect`, a :c:member:`rating` field described
below, and a name (string) used for identifying it.
@@ -68,9 +63,8 @@ only one in the list (that is, the list was empty before) or the value of its
governor currently in use, or the name of the new governor was passed to the
kernel as the value of the ``cpuidle.governor=`` command line parameter, the new
governor will be used from that point on (there can be only one ``CPUIdle``
-governor in use at a time). Also, if ``cpuidle_sysfs_switch`` is passed to the
-kernel in the command line, user space can choose the ``CPUIdle`` governor to
-use at run time via ``sysfs``.
+governor in use at a time). Also, user space can choose the ``CPUIdle``
+governor to use at run time via ``sysfs``.
Once registered, ``CPUIdle`` governors cannot be unregistered, so it is not
practical to put them into loadable kernel modules.
@@ -84,11 +78,11 @@ callbacks:
int (*enable) (struct cpuidle_driver *drv, struct cpuidle_device *dev);
The role of this callback is to prepare the governor for handling the
- (logical) CPU represented by the |struct cpuidle_device| object pointed
- to by the ``dev`` argument. The |struct cpuidle_driver| object pointed
+ (logical) CPU represented by the struct cpuidle_device object pointed
+ to by the ``dev`` argument. The struct cpuidle_driver object pointed
to by the ``drv`` argument represents the ``CPUIdle`` driver to be used
with that CPU (among other things, it should contain the list of
- |struct cpuidle_state| objects representing idle states that the
+ struct cpuidle_state objects representing idle states that the
processor holding the given CPU can be asked to enter).
It may fail, in which case it is expected to return a negative error
@@ -103,7 +97,7 @@ callbacks:
void (*disable) (struct cpuidle_driver *drv, struct cpuidle_device *dev);
Called to make the governor stop handling the (logical) CPU represented
- by the |struct cpuidle_device| object pointed to by the ``dev``
+ by the struct cpuidle_device object pointed to by the ``dev``
argument.
It is expected to reverse any changes made by the ``->enable()``
@@ -117,12 +111,12 @@ callbacks:
bool *stop_tick);
Called to select an idle state for the processor holding the (logical)
- CPU represented by the |struct cpuidle_device| object pointed to by the
+ CPU represented by the struct cpuidle_device object pointed to by the
``dev`` argument.
The list of idle states to take into consideration is represented by the
- :c:member:`states` array of |struct cpuidle_state| objects held by the
- |struct cpuidle_driver| object pointed to by the ``drv`` argument (which
+ :c:member:`states` array of struct cpuidle_state objects held by the
+ struct cpuidle_driver object pointed to by the ``drv`` argument (which
represents the ``CPUIdle`` driver to be used with the CPU at hand). The
value returned by this callback is interpreted as an index into that
array (unless it is a negative error code).
@@ -137,7 +131,7 @@ callbacks:
asking the processor to enter the idle state).
This callback is mandatory (i.e. the :c:member:`select` callback pointer
- in |struct cpuidle_governor| must not be ``NULL`` for the registration
+ in struct cpuidle_governor must not be ``NULL`` for the registration
of the governor to succeed).
:c:member:`reflect`
@@ -168,21 +162,21 @@ CPU idle time management (``CPUIdle``) drivers provide an interface between the
other parts of ``CPUIdle`` and the hardware.
First of all, a ``CPUIdle`` driver has to populate the :c:member:`states` array
-of |struct cpuidle_state| objects included in the |struct cpuidle_driver| object
+of struct cpuidle_state objects included in the struct cpuidle_driver object
representing it. Going forward this array will represent the list of available
idle states that the processor hardware can be asked to enter shared by all of
the logical CPUs handled by the given driver.
The entries in the :c:member:`states` array are expected to be sorted by the
-value of the :c:member:`target_residency` field in |struct cpuidle_state| in
+value of the :c:member:`target_residency` field in struct cpuidle_state in
the ascending order (that is, index 0 should correspond to the idle state with
the minimum value of :c:member:`target_residency`). [Since the
:c:member:`target_residency` value is expected to reflect the "depth" of the
-idle state represented by the |struct cpuidle_state| object holding it, this
+idle state represented by the struct cpuidle_state object holding it, this
sorting order should be the same as the ascending sorting order by the idle
state "depth".]
-Three fields in |struct cpuidle_state| are used by the existing ``CPUIdle``
+Three fields in struct cpuidle_state are used by the existing ``CPUIdle``
governors for computations related to idle state selection:
:c:member:`target_residency`
@@ -204,7 +198,7 @@ governors for computations related to idle state selection:
any idle state at all. [There are other flags used by the ``CPUIdle``
core in special situations.]
-The :c:member:`enter` callback pointer in |struct cpuidle_state|, which must not
+The :c:member:`enter` callback pointer in struct cpuidle_state, which must not
be ``NULL``, points to the routine to execute in order to ask the processor to
enter this particular idle state:
@@ -213,14 +207,14 @@ enter this particular idle state:
void (*enter) (struct cpuidle_device *dev, struct cpuidle_driver *drv,
int index);
-The first two arguments of it point to the |struct cpuidle_device| object
+The first two arguments of it point to the struct cpuidle_device object
representing the logical CPU running this callback and the
-|struct cpuidle_driver| object representing the driver itself, respectively,
-and the last one is an index of the |struct cpuidle_state| entry in the driver's
+struct cpuidle_driver object representing the driver itself, respectively,
+and the last one is an index of the struct cpuidle_state entry in the driver's
:c:member:`states` array representing the idle state to ask the processor to
enter.
-The analogous ``->enter_s2idle()`` callback in |struct cpuidle_state| is used
+The analogous ``->enter_s2idle()`` callback in struct cpuidle_state is used
only for implementing the suspend-to-idle system-wide power management feature.
The difference between in and ``->enter()`` is that it must not re-enable
interrupts at any point (even temporarily) or attempt to change the states of
@@ -228,48 +222,48 @@ clock event devices, which the ``->enter()`` callback may do sometimes.
Once the :c:member:`states` array has been populated, the number of valid
entries in it has to be stored in the :c:member:`state_count` field of the
-|struct cpuidle_driver| object representing the driver. Moreover, if any
+struct cpuidle_driver object representing the driver. Moreover, if any
entries in the :c:member:`states` array represent "coupled" idle states (that
is, idle states that can only be asked for if multiple related logical CPUs are
-idle), the :c:member:`safe_state_index` field in |struct cpuidle_driver| needs
+idle), the :c:member:`safe_state_index` field in struct cpuidle_driver needs
to be the index of an idle state that is not "coupled" (that is, one that can be
asked for if only one logical CPU is idle).
In addition to that, if the given ``CPUIdle`` driver is only going to handle a
subset of logical CPUs in the system, the :c:member:`cpumask` field in its
-|struct cpuidle_driver| object must point to the set (mask) of CPUs that will be
+struct cpuidle_driver object must point to the set (mask) of CPUs that will be
handled by it.
A ``CPUIdle`` driver can only be used after it has been registered. If there
are no "coupled" idle state entries in the driver's :c:member:`states` array,
-that can be accomplished by passing the driver's |struct cpuidle_driver| object
+that can be accomplished by passing the driver's struct cpuidle_driver object
to :c:func:`cpuidle_register_driver()`. Otherwise, :c:func:`cpuidle_register()`
should be used for this purpose.
-However, it also is necessary to register |struct cpuidle_device| objects for
+However, it also is necessary to register struct cpuidle_device objects for
all of the logical CPUs to be handled by the given ``CPUIdle`` driver with the
help of :c:func:`cpuidle_register_device()` after the driver has been registered
and :c:func:`cpuidle_register_driver()`, unlike :c:func:`cpuidle_register()`,
does not do that automatically. For this reason, the drivers that use
:c:func:`cpuidle_register_driver()` to register themselves must also take care
-of registering the |struct cpuidle_device| objects as needed, so it is generally
+of registering the struct cpuidle_device objects as needed, so it is generally
recommended to use :c:func:`cpuidle_register()` for ``CPUIdle`` driver
registration in all cases.
-The registration of a |struct cpuidle_device| object causes the ``CPUIdle``
+The registration of a struct cpuidle_device object causes the ``CPUIdle``
``sysfs`` interface to be created and the governor's ``->enable()`` callback to
be invoked for the logical CPU represented by it, so it must take place after
registering the driver that will handle the CPU in question.
-``CPUIdle`` drivers and |struct cpuidle_device| objects can be unregistered
+``CPUIdle`` drivers and struct cpuidle_device objects can be unregistered
when they are not necessary any more which allows some resources associated with
them to be released. Due to dependencies between them, all of the
-|struct cpuidle_device| objects representing CPUs handled by the given
+struct cpuidle_device objects representing CPUs handled by the given
``CPUIdle`` driver must be unregistered, with the help of
:c:func:`cpuidle_unregister_device()`, before calling
:c:func:`cpuidle_unregister_driver()` to unregister the driver. Alternatively,
:c:func:`cpuidle_unregister()` can be called to unregister a ``CPUIdle`` driver
-along with all of the |struct cpuidle_device| objects representing CPUs handled
+along with all of the struct cpuidle_device objects representing CPUs handled
by it.
``CPUIdle`` drivers can respond to runtime system configuration changes that
@@ -278,8 +272,8 @@ happen, for example, when the system's power source is switched from AC to
battery or the other way around). Upon a notification of such a change,
a ``CPUIdle`` driver is expected to call :c:func:`cpuidle_pause_and_lock()` to
turn ``CPUIdle`` off temporarily and then :c:func:`cpuidle_disable_device()` for
-all of the |struct cpuidle_device| objects representing CPUs affected by that
+all of the struct cpuidle_device objects representing CPUs affected by that
change. Next, it can update its :c:member:`states` array in accordance with
the new configuration of the system, call :c:func:`cpuidle_enable_device()` for
-all of the relevant |struct cpuidle_device| objects and invoke
+all of the relevant struct cpuidle_device objects and invoke
:c:func:`cpuidle_resume_and_unlock()` to allow ``CPUIdle`` to be used again.
diff --git a/Documentation/driver-api/pm/devices.rst b/Documentation/driver-api/pm/devices.rst
index f66c7b9126ea..d448cb57df86 100644
--- a/Documentation/driver-api/pm/devices.rst
+++ b/Documentation/driver-api/pm/devices.rst
@@ -1,14 +1,6 @@
.. SPDX-License-Identifier: GPL-2.0
.. include:: <isonum.txt>
-.. |struct dev_pm_ops| replace:: :c:type:`struct dev_pm_ops <dev_pm_ops>`
-.. |struct dev_pm_domain| replace:: :c:type:`struct dev_pm_domain <dev_pm_domain>`
-.. |struct bus_type| replace:: :c:type:`struct bus_type <bus_type>`
-.. |struct device_type| replace:: :c:type:`struct device_type <device_type>`
-.. |struct class| replace:: :c:type:`struct class <class>`
-.. |struct wakeup_source| replace:: :c:type:`struct wakeup_source <wakeup_source>`
-.. |struct device| replace:: :c:type:`struct device <device>`
-
.. _driverapi_pm_devices:
==============================
@@ -107,7 +99,7 @@ Device Power Management Operations
Device power management operations, at the subsystem level as well as at the
device driver level, are implemented by defining and populating objects of type
-|struct dev_pm_ops| defined in :file:`include/linux/pm.h`. The roles of the
+struct dev_pm_ops defined in :file:`include/linux/pm.h`. The roles of the
methods included in it will be explained in what follows. For now, it should be
sufficient to remember that the last three methods are specific to runtime power
management while the remaining ones are used during system-wide power
@@ -115,7 +107,7 @@ transitions.
There also is a deprecated "old" or "legacy" interface for power management
operations available at least for some subsystems. This approach does not use
-|struct dev_pm_ops| objects and it is suitable only for implementing system
+struct dev_pm_ops objects and it is suitable only for implementing system
sleep power management methods in a limited way. Therefore it is not described
in this document, so please refer directly to the source code for more
information about it.
@@ -125,9 +117,9 @@ Subsystem-Level Methods
-----------------------
The core methods to suspend and resume devices reside in
-|struct dev_pm_ops| pointed to by the :c:member:`ops` member of
-|struct dev_pm_domain|, or by the :c:member:`pm` member of |struct bus_type|,
-|struct device_type| and |struct class|. They are mostly of interest to the
+struct dev_pm_ops pointed to by the :c:member:`ops` member of
+struct dev_pm_domain, or by the :c:member:`pm` member of struct bus_type,
+struct device_type and struct class. They are mostly of interest to the
people writing infrastructure for platforms and buses, like PCI or USB, or
device type and device class drivers. They also are relevant to the writers of
device drivers whose subsystems (PM domains, device types, device classes and
@@ -156,7 +148,7 @@ The :c:member:`power.can_wakeup` flag just records whether the device (and its
driver) can physically support wakeup events. The
:c:func:`device_set_wakeup_capable()` routine affects this flag. The
:c:member:`power.wakeup` field is a pointer to an object of type
-|struct wakeup_source| used for controlling whether or not the device should use
+struct wakeup_source used for controlling whether or not the device should use
its system wakeup mechanism and for notifying the PM core of system wakeup
events signaled by the device. This object is only present for wakeup-capable
devices (i.e. devices whose :c:member:`can_wakeup` flags are set) and is created
@@ -225,7 +217,7 @@ system-wide transition to a sleep state even though its :c:member:`runtime_auto`
flag is clear.
For more information about the runtime power management framework, refer to
-:file:`Documentation/power/runtime_pm.rst`.
+Documentation/power/runtime_pm.rst.
Calling Drivers to Enter and Leave System Sleep States
@@ -349,7 +341,7 @@ the phases are: ``prepare``, ``suspend``, ``suspend_late``, ``suspend_noirq``.
PM core will skip the ``suspend``, ``suspend_late`` and
``suspend_noirq`` phases as well as all of the corresponding phases of
the subsequent device resume for all of these devices. In that case,
- the ``->complete`` callback will be invoked directly after the
+ the ``->complete`` callback will be the next one invoked after the
``->prepare`` callback and is entirely responsible for putting the
device into a consistent state as appropriate.
@@ -361,9 +353,9 @@ the phases are: ``prepare``, ``suspend``, ``suspend_late``, ``suspend_noirq``.
runtime PM disabled.
This feature also can be controlled by device drivers by using the
- ``DPM_FLAG_NEVER_SKIP`` and ``DPM_FLAG_SMART_PREPARE`` driver power
- management flags. [Typically, they are set at the time the driver is
- probed against the device in question by passing them to the
+ ``DPM_FLAG_NO_DIRECT_COMPLETE`` and ``DPM_FLAG_SMART_PREPARE`` driver
+ power management flags. [Typically, they are set at the time the driver
+ is probed against the device in question by passing them to the
:c:func:`dev_pm_set_driver_flags` helper function.] If the first of
these flags is set, the PM core will not apply the direct-complete
procedure described above to the given device and, consequenty, to any
@@ -383,11 +375,15 @@ the phases are: ``prepare``, ``suspend``, ``suspend_late``, ``suspend_noirq``.
``->suspend`` methods provided by subsystems (bus types and PM domains
in particular) must follow an additional rule regarding what can be done
to the devices before their drivers' ``->suspend`` methods are called.
- Namely, they can only resume the devices from runtime suspend by
- calling :c:func:`pm_runtime_resume` for them, if that is necessary, and
+ Namely, they may resume the devices from runtime suspend by
+ calling :c:func:`pm_runtime_resume` for them, if that is necessary, but
they must not update the state of the devices in any other way at that
time (in case the drivers need to resume the devices from runtime
- suspend in their ``->suspend`` methods).
+ suspend in their ``->suspend`` methods). In fact, the PM core prevents
+ subsystems or drivers from putting devices into runtime suspend at
+ these times by calling :c:func:`pm_runtime_get_noresume` before issuing
+ the ``->prepare`` callback (and calling :c:func:`pm_runtime_put` after
+ issuing the ``->complete`` callback).
3. For a number of devices it is convenient to split suspend into the
"quiesce device" and "save device state" phases, in which cases
@@ -414,7 +410,7 @@ On many platforms they will gate off one or more clock sources; sometimes they
will also switch off power supplies or reduce voltages. [Drivers supporting
runtime PM may already have performed some or all of these steps.]
-If :c:func:`device_may_wakeup(dev)` returns ``true``, the device should be
+If :c:func:`device_may_wakeup()` returns ``true``, the device should be
prepared for generating hardware wakeup signals to trigger a system wakeup event
when the system is in the sleep state. For example, :c:func:`enable_irq_wake()`
might identify GPIO signals hooked up to a switch or other external hardware,
@@ -459,22 +455,22 @@ When resuming from freeze, standby or memory sleep, the phases are:
Note, however, that new children may be registered below the device as
soon as the ``->resume`` callbacks occur; it's not necessary to wait
- until the ``complete`` phase with that.
+ until the ``complete`` phase runs.
Moreover, if the preceding ``->prepare`` callback returned a positive
number, the device may have been left in runtime suspend throughout the
- whole system suspend and resume (the ``suspend``, ``suspend_late``,
- ``suspend_noirq`` phases of system suspend and the ``resume_noirq``,
- ``resume_early``, ``resume`` phases of system resume may have been
- skipped for it). In that case, the ``->complete`` callback is entirely
+ whole system suspend and resume (its ``->suspend``, ``->suspend_late``,
+ ``->suspend_noirq``, ``->resume_noirq``,
+ ``->resume_early``, and ``->resume`` callbacks may have been
+ skipped). In that case, the ``->complete`` callback is entirely
responsible for putting the device into a consistent state after system
suspend if necessary. [For example, it may need to queue up a runtime
resume request for the device for this purpose.] To check if that is
the case, the ``->complete`` callback can consult the device's
- ``power.direct_complete`` flag. Namely, if that flag is set when the
- ``->complete`` callback is being run, it has been called directly after
- the preceding ``->prepare`` and special actions may be required
- to make the device work correctly afterward.
+ ``power.direct_complete`` flag. If that flag is set when the
+ ``->complete`` callback is being run then the direct-complete mechanism
+ was used, and special actions may be required to make the device work
+ correctly afterward.
At the end of these phases, drivers should be as functional as they were before
suspending: I/O can be performed using DMA and IRQs, and the relevant clocks are
@@ -575,10 +571,12 @@ and the phases are similar.
The ``->poweroff``, ``->poweroff_late`` and ``->poweroff_noirq`` callbacks
should do essentially the same things as the ``->suspend``, ``->suspend_late``
-and ``->suspend_noirq`` callbacks, respectively. The only notable difference is
+and ``->suspend_noirq`` callbacks, respectively. A notable difference is
that they need not store the device register values, because the registers
should already have been stored during the ``freeze``, ``freeze_late`` or
-``freeze_noirq`` phases.
+``freeze_noirq`` phases. Also, on many machines the firmware will power-down
+the entire system, so it is not necessary for the callback to put the device in
+a low-power state.
Leaving Hibernation
@@ -657,7 +655,7 @@ been thawed. Generally speaking, the PM notifiers are suitable for performing
actions that either require user space to be available, or at least won't
interfere with user space.
-For details refer to :doc:`notifiers`.
+For details refer to Documentation/driver-api/pm/notifiers.rst.
Device Low-Power (suspend) States
@@ -707,8 +705,8 @@ nested inside another power domain. The nested domain is referred to as the
sub-domain of the parent domain.
Support for power domains is provided through the :c:member:`pm_domain` field of
-|struct device|. This field is a pointer to an object of type
-|struct dev_pm_domain|, defined in :file:`include/linux/pm.h`, providing a set
+struct device. This field is a pointer to an object of type
+struct dev_pm_domain, defined in :file:`include/linux/pm.h`, providing a set
of power management callbacks analogous to the subsystem-level and device driver
callbacks that are executed for the given device during all power transitions,
instead of the respective subsystem-level callbacks. Specifically, if a
@@ -728,7 +726,7 @@ it into account in any way.
Devices may be defined as IRQ-safe which indicates to the PM core that their
runtime PM callbacks may be invoked with disabled interrupts (see
-:file:`Documentation/power/runtime_pm.rst` for more information). If an
+Documentation/power/runtime_pm.rst for more information). If an
IRQ-safe device belongs to a PM domain, the runtime PM of the domain will be
disallowed, unless the domain itself is defined as IRQ-safe. However, it
makes sense to define a PM domain as IRQ-safe only if all the devices in it
@@ -764,70 +762,119 @@ device driver in question.
If it is necessary to resume a device from runtime suspend during a system-wide
transition into a sleep state, that can be done by calling
-:c:func:`pm_runtime_resume` for it from the ``->suspend`` callback (or its
-couterpart for transitions related to hibernation) of either the device's driver
-or a subsystem responsible for it (for example, a bus type or a PM domain).
-That is guaranteed to work by the requirement that subsystems must not change
-the state of devices (possibly except for resuming them from runtime suspend)
+:c:func:`pm_runtime_resume` from the ``->suspend`` callback (or the ``->freeze``
+or ``->poweroff`` callback for transitions related to hibernation) of either the
+device's driver or its subsystem (for example, a bus type or a PM domain).
+However, subsystems must not otherwise change the runtime status of devices
from their ``->prepare`` and ``->suspend`` callbacks (or equivalent) *before*
invoking device drivers' ``->suspend`` callbacks (or equivalent).
+.. _smart_suspend_flag:
+
+The ``DPM_FLAG_SMART_SUSPEND`` Driver Flag
+------------------------------------------
+
Some bus types and PM domains have a policy to resume all devices from runtime
suspend upfront in their ``->suspend`` callbacks, but that may not be really
-necessary if the driver of the device can cope with runtime-suspended devices.
-The driver can indicate that by setting ``DPM_FLAG_SMART_SUSPEND`` in
-:c:member:`power.driver_flags` at the probe time, by passing it to the
-:c:func:`dev_pm_set_driver_flags` helper. That also may cause middle-layer code
+necessary if the device's driver can cope with runtime-suspended devices.
+The driver can indicate this by setting ``DPM_FLAG_SMART_SUSPEND`` in
+:c:member:`power.driver_flags` at probe time, with the assistance of the
+:c:func:`dev_pm_set_driver_flags` helper routine.
+
+Setting that flag causes the PM core and middle-layer code
(bus types, PM domains etc.) to skip the ``->suspend_late`` and
``->suspend_noirq`` callbacks provided by the driver if the device remains in
-runtime suspend at the beginning of the ``suspend_late`` phase of system-wide
-suspend (or in the ``poweroff_late`` phase of hibernation), when runtime PM
-has been disabled for it, under the assumption that its state should not change
-after that point until the system-wide transition is over (the PM core itself
-does that for devices whose "noirq", "late" and "early" system-wide PM callbacks
-are executed directly by it). If that happens, the driver's system-wide resume
-callbacks, if present, may still be invoked during the subsequent system-wide
-resume transition and the device's runtime power management status may be set
-to "active" before enabling runtime PM for it, so the driver must be prepared to
-cope with the invocation of its system-wide resume callbacks back-to-back with
-its ``->runtime_suspend`` one (without the intervening ``->runtime_resume`` and
-so on) and the final state of the device must reflect the "active" runtime PM
-status in that case.
+runtime suspend throughout those phases of the system-wide suspend (and
+similarly for the "freeze" and "poweroff" parts of system hibernation).
+[Otherwise the same driver
+callback might be executed twice in a row for the same device, which would not
+be valid in general.] If the middle-layer system-wide PM callbacks are present
+for the device then they are responsible for skipping these driver callbacks;
+if not then the PM core skips them. The subsystem callback routines can
+determine whether they need to skip the driver callbacks by testing the return
+value from the :c:func:`dev_pm_skip_suspend` helper function.
+
+In addition, with ``DPM_FLAG_SMART_SUSPEND`` set, the driver's ``->thaw_noirq``
+and ``->thaw_early`` callbacks are skipped in hibernation if the device remained
+in runtime suspend throughout the preceding "freeze" transition. Again, if the
+middle-layer callbacks are present for the device, they are responsible for
+doing this, otherwise the PM core takes care of it.
+
+
+The ``DPM_FLAG_MAY_SKIP_RESUME`` Driver Flag
+--------------------------------------------
During system-wide resume from a sleep state it's easiest to put devices into
-the full-power state, as explained in :file:`Documentation/power/runtime_pm.rst`.
+the full-power state, as explained in Documentation/power/runtime_pm.rst.
[Refer to that document for more information regarding this particular issue as
well as for information on the device runtime power management framework in
-general.]
-
-However, it often is desirable to leave devices in suspend after system
-transitions to the working state, especially if those devices had been in
+general.] However, it often is desirable to leave devices in suspend after
+system transitions to the working state, especially if those devices had been in
runtime suspend before the preceding system-wide suspend (or analogous)
-transition. Device drivers can use the ``DPM_FLAG_LEAVE_SUSPENDED`` flag to
-indicate to the PM core (and middle-layer code) that they prefer the specific
-devices handled by them to be left suspended and they have no problems with
-skipping their system-wide resume callbacks for this reason. Whether or not the
-devices will actually be left in suspend may depend on their state before the
-given system suspend-resume cycle and on the type of the system transition under
-way. In particular, devices are not left suspended if that transition is a
-restore from hibernation, as device states are not guaranteed to be reflected
-by the information stored in the hibernation image in that case.
-
-The middle-layer code involved in the handling of the device is expected to
-indicate to the PM core if the device may be left in suspend by setting its
-:c:member:`power.may_skip_resume` status bit which is checked by the PM core
-during the "noirq" phase of the preceding system-wide suspend (or analogous)
-transition. The middle layer is then responsible for handling the device as
-appropriate in its "noirq" resume callback, which is executed regardless of
-whether or not the device is left suspended, but the other resume callbacks
-(except for ``->complete``) will be skipped automatically by the PM core if the
-device really can be left in suspend.
-
-For devices whose "noirq", "late" and "early" driver callbacks are invoked
-directly by the PM core, all of the system-wide resume callbacks are skipped if
-``DPM_FLAG_LEAVE_SUSPENDED`` is set and the device is in runtime suspend during
-the ``suspend_noirq`` (or analogous) phase or the transition under way is a
-proper system suspend (rather than anything related to hibernation) and the
-device's wakeup settings are suitable for runtime PM (that is, it cannot
-generate wakeup signals at all or it is allowed to wake up the system from
-sleep).
+transition.
+
+To that end, device drivers can use the ``DPM_FLAG_MAY_SKIP_RESUME`` flag to
+indicate to the PM core and middle-layer code that they allow their "noirq" and
+"early" resume callbacks to be skipped if the device can be left in suspend
+after system-wide PM transitions to the working state. Whether or not that is
+the case generally depends on the state of the device before the given system
+suspend-resume cycle and on the type of the system transition under way.
+In particular, the "thaw" and "restore" transitions related to hibernation are
+not affected by ``DPM_FLAG_MAY_SKIP_RESUME`` at all. [All callbacks are
+issued during the "restore" transition regardless of the flag settings,
+and whether or not any driver callbacks
+are skipped during the "thaw" transition depends whether or not the
+``DPM_FLAG_SMART_SUSPEND`` flag is set (see `above <smart_suspend_flag_>`_).
+In addition, a device is not allowed to remain in runtime suspend if any of its
+children will be returned to full power.]
+
+The ``DPM_FLAG_MAY_SKIP_RESUME`` flag is taken into account in combination with
+the :c:member:`power.may_skip_resume` status bit set by the PM core during the
+"suspend" phase of suspend-type transitions. If the driver or the middle layer
+has a reason to prevent the driver's "noirq" and "early" resume callbacks from
+being skipped during the subsequent system resume transition, it should
+clear :c:member:`power.may_skip_resume` in its ``->suspend``, ``->suspend_late``
+or ``->suspend_noirq`` callback. [Note that the drivers setting
+``DPM_FLAG_SMART_SUSPEND`` need to clear :c:member:`power.may_skip_resume` in
+their ``->suspend`` callback in case the other two are skipped.]
+
+Setting the :c:member:`power.may_skip_resume` status bit along with the
+``DPM_FLAG_MAY_SKIP_RESUME`` flag is necessary, but generally not sufficient,
+for the driver's "noirq" and "early" resume callbacks to be skipped. Whether or
+not they should be skipped can be determined by evaluating the
+:c:func:`dev_pm_skip_resume` helper function.
+
+If that function returns ``true``, the driver's "noirq" and "early" resume
+callbacks should be skipped and the device's runtime PM status will be set to
+"suspended" by the PM core. Otherwise, if the device was runtime-suspended
+during the preceding system-wide suspend transition and its
+``DPM_FLAG_SMART_SUSPEND`` is set, its runtime PM status will be set to
+"active" by the PM core. [Hence, the drivers that do not set
+``DPM_FLAG_SMART_SUSPEND`` should not expect the runtime PM status of their
+devices to be changed from "suspended" to "active" by the PM core during
+system-wide resume-type transitions.]
+
+If the ``DPM_FLAG_MAY_SKIP_RESUME`` flag is not set for a device, but
+``DPM_FLAG_SMART_SUSPEND`` is set and the driver's "late" and "noirq" suspend
+callbacks are skipped, its system-wide "noirq" and "early" resume callbacks, if
+present, are invoked as usual and the device's runtime PM status is set to
+"active" by the PM core before enabling runtime PM for it. In that case, the
+driver must be prepared to cope with the invocation of its system-wide resume
+callbacks back-to-back with its ``->runtime_suspend`` one (without the
+intervening ``->runtime_resume`` and system-wide suspend callbacks) and the
+final state of the device must reflect the "active" runtime PM status in that
+case. [Note that this is not a problem at all if the driver's
+``->suspend_late`` callback pointer points to the same function as its
+``->runtime_suspend`` one and its ``->resume_early`` callback pointer points to
+the same function as the ``->runtime_resume`` one, while none of the other
+system-wide suspend-resume callbacks of the driver are present, for example.]
+
+Likewise, if ``DPM_FLAG_MAY_SKIP_RESUME`` is set for a device, its driver's
+system-wide "noirq" and "early" resume callbacks may be skipped while its "late"
+and "noirq" suspend callbacks may have been executed (in principle, regardless
+of whether or not ``DPM_FLAG_SMART_SUSPEND`` is set). In that case, the driver
+needs to be able to cope with the invocation of its ``->runtime_resume``
+callback back-to-back with its "late" and "noirq" suspend ones. [For instance,
+that is not a concern if the driver sets both ``DPM_FLAG_SMART_SUSPEND`` and
+``DPM_FLAG_MAY_SKIP_RESUME`` and uses the same pair of suspend/resume callback
+functions for runtime PM and system-wide suspend/resume.]
diff --git a/Documentation/driver-api/pps.rst b/Documentation/driver-api/pps.rst
index 2d6b99766ee8..78dded03e5d8 100644
--- a/Documentation/driver-api/pps.rst
+++ b/Documentation/driver-api/pps.rst
@@ -200,11 +200,17 @@ Generators
Sometimes one needs to be able not only to catch PPS signals but to produce
them also. For example, running a distributed simulation, which requires
-computers' clock to be synchronized very tightly. One way to do this is to
-invent some complicated hardware solutions but it may be neither necessary
-nor affordable. The cheap way is to load a PPS generator on one of the
-computers (master) and PPS clients on others (slaves), and use very simple
-cables to deliver signals using parallel ports, for example.
+computers' clock to be synchronized very tightly.
+
+
+Parallel port generator
+------------------------
+
+One way to do this is to invent some complicated hardware solutions but it
+may be neither necessary nor affordable. The cheap way is to load a PPS
+generator on one of the computers (master) and PPS clients on others
+(slaves), and use very simple cables to deliver signals using parallel
+ports, for example.
Parallel port cable pinout::
diff --git a/Documentation/driver-api/pti_intel_mid.rst b/Documentation/driver-api/pti_intel_mid.rst
deleted file mode 100644
index bacc2a4ee89f..000000000000
--- a/Documentation/driver-api/pti_intel_mid.rst
+++ /dev/null
@@ -1,108 +0,0 @@
-.. SPDX-License-Identifier: GPL-2.0
-
-=============
-Intel MID PTI
-=============
-
-The Intel MID PTI project is HW implemented in Intel Atom
-system-on-a-chip designs based on the Parallel Trace
-Interface for MIPI P1149.7 cJTAG standard. The kernel solution
-for this platform involves the following files::
-
- ./include/linux/pti.h
- ./drivers/.../n_tracesink.h
- ./drivers/.../n_tracerouter.c
- ./drivers/.../n_tracesink.c
- ./drivers/.../pti.c
-
-pti.c is the driver that enables various debugging features
-popular on platforms from certain mobile manufacturers.
-n_tracerouter.c and n_tracesink.c allow extra system information to
-be collected and routed to the pti driver, such as trace
-debugging data from a modem. Although n_tracerouter
-and n_tracesink are a part of the complete PTI solution,
-these two line disciplines can work separately from
-pti.c and route any data stream from one /dev/tty node
-to another /dev/tty node via kernel-space. This provides
-a stable, reliable connection that will not break unless
-the user-space application shuts down (plus avoids
-kernel->user->kernel context switch overheads of routing
-data).
-
-An example debugging usage for this driver system:
-
- * Hook /dev/ttyPTI0 to syslogd. Opening this port will also start
- a console device to further capture debugging messages to PTI.
- * Hook /dev/ttyPTI1 to modem debugging data to write to PTI HW.
- This is where n_tracerouter and n_tracesink are used.
- * Hook /dev/pti to a user-level debugging application for writing
- to PTI HW.
- * `Use mipi_` Kernel Driver API in other device drivers for
- debugging to PTI by first requesting a PTI write address via
- mipi_request_masterchannel(1).
-
-Below is example pseudo-code on how a 'privileged' application
-can hook up n_tracerouter and n_tracesink to any tty on
-a system. 'Privileged' means the application has enough
-privileges to successfully manipulate the ldisc drivers
-but is not just blindly executing as 'root'. Keep in mind
-the use of ioctl(,TIOCSETD,) is not specific to the n_tracerouter
-and n_tracesink line discpline drivers but is a generic
-operation for a program to use a line discpline driver
-on a tty port other than the default n_tty:
-
-.. code-block:: c
-
- /////////// To hook up n_tracerouter and n_tracesink /////////
-
- // Note that n_tracerouter depends on n_tracesink.
- #include <errno.h>
- #define ONE_TTY "/dev/ttyOne"
- #define TWO_TTY "/dev/ttyTwo"
-
- // needed global to hand onto ldisc connection
- static int g_fd_source = -1;
- static int g_fd_sink = -1;
-
- // these two vars used to grab LDISC values from loaded ldisc drivers
- // in OS. Look at /proc/tty/ldiscs to get the right numbers from
- // the ldiscs loaded in the system.
- int source_ldisc_num, sink_ldisc_num = -1;
- int retval;
-
- g_fd_source = open(ONE_TTY, O_RDWR); // must be R/W
- g_fd_sink = open(TWO_TTY, O_RDWR); // must be R/W
-
- if (g_fd_source <= 0) || (g_fd_sink <= 0) {
- // doubt you'll want to use these exact error lines of code
- printf("Error on open(). errno: %d\n",errno);
- return errno;
- }
-
- retval = ioctl(g_fd_sink, TIOCSETD, &sink_ldisc_num);
- if (retval < 0) {
- printf("Error on ioctl(). errno: %d\n", errno);
- return errno;
- }
-
- retval = ioctl(g_fd_source, TIOCSETD, &source_ldisc_num);
- if (retval < 0) {
- printf("Error on ioctl(). errno: %d\n", errno);
- return errno;
- }
-
- /////////// To disconnect n_tracerouter and n_tracesink ////////
-
- // First make sure data through the ldiscs has stopped.
-
- // Second, disconnect ldiscs. This provides a
- // little cleaner shutdown on tty stack.
- sink_ldisc_num = 0;
- source_ldisc_num = 0;
- ioctl(g_fd_uart, TIOCSETD, &sink_ldisc_num);
- ioctl(g_fd_gadget, TIOCSETD, &source_ldisc_num);
-
- // Three, program closes connection, and cleanup:
- close(g_fd_uart);
- close(g_fd_gadget);
- g_fd_uart = g_fd_gadget = NULL;
diff --git a/Documentation/driver-api/ptp.rst b/Documentation/driver-api/ptp.rst
index a15192e32347..5e033c3b11b3 100644
--- a/Documentation/driver-api/ptp.rst
+++ b/Documentation/driver-api/ptp.rst
@@ -23,6 +23,7 @@ PTP hardware clock infrastructure for Linux
+ Ancillary clock features
- Time stamp external events
- Period output signals configurable from user space
+ - Low Pass Filter (LPF) access from user space
- Synchronization of the Linux system time via the PPS subsystem
PTP hardware clock kernel API
@@ -72,6 +73,22 @@ Writing clock drivers
class driver, since the lock may also be needed by the clock
driver's interrupt service routine.
+PTP hardware clock requirements for '.adjphase'
+-----------------------------------------------
+
+ The 'struct ptp_clock_info' interface has a '.adjphase' function.
+ This function has a set of requirements from the PHC in order to be
+ implemented.
+
+ * The PHC implements a servo algorithm internally that is used to
+ correct the offset passed in the '.adjphase' call.
+ * When other PTP adjustment functions are called, the PHC servo
+ algorithm is disabled.
+
+ **NOTE:** '.adjphase' is not a simple time adjustment functionality
+ that 'jumps' the PHC clock time based on the provided offset. It
+ should correct the offset provided using an internal algorithm.
+
Supported hardware
==================
@@ -94,3 +111,27 @@ Supported hardware
- Auxiliary Slave/Master Mode Snapshot (optional interrupt)
- Target Time (optional interrupt)
+
+ * Renesas (IDT) ClockMatrixâ„¢
+
+ - Up to 4 independent PHC channels
+ - Integrated low pass filter (LPF), access via .adjPhase (compliant to ITU-T G.8273.2)
+ - Programmable output periodic signals
+ - Programmable inputs can time stamp external triggers
+ - Driver and/or hardware configuration through firmware (idtcm.bin)
+ - LPF settings (bandwidth, phase limiting, automatic holdover, physical layer assist (per ITU-T G.8273.2))
+ - Programmable output PTP clocks, any frequency up to 1GHz (to other PHY/MAC time stampers, refclk to ASSPs/SoCs/FPGAs)
+ - Lock to GNSS input, automatic switching between GNSS and user-space PHC control (optional)
+
+ * NVIDIA Mellanox
+
+ - GPIO
+ - Certain variants of ConnectX-6 Dx and later products support one
+ GPIO which can time stamp external triggers and one GPIO to produce
+ periodic signals.
+ - Certain variants of ConnectX-5 and older products support one GPIO,
+ configured to either time stamp external triggers or produce
+ periodic signals.
+ - PHC instances
+ - All ConnectX devices have a free-running counter
+ - ConnectX-6 Dx and later devices have a UTC format counter
diff --git a/Documentation/driver-api/pwm.rst b/Documentation/driver-api/pwm.rst
index ab62f1bb0366..3c28ccc4b611 100644
--- a/Documentation/driver-api/pwm.rst
+++ b/Documentation/driver-api/pwm.rst
@@ -35,27 +35,47 @@ consumers to providers, as given in the following example::
Using PWMs
----------
-Legacy users can request a PWM device using pwm_request() and free it
-after usage with pwm_free().
-
-New users should use the pwm_get() function and pass to it the consumer
-device or a consumer name. pwm_put() is used to free the PWM device. Managed
-variants of these functions, devm_pwm_get() and devm_pwm_put(), also exist.
+Consumers use the pwm_get() function and pass to it the consumer device or a
+consumer name. pwm_put() is used to free the PWM device. Managed variants of
+the getter, devm_pwm_get() and devm_fwnode_pwm_get(), also exist.
After being requested, a PWM has to be configured using::
- int pwm_apply_state(struct pwm_device *pwm, struct pwm_state *state);
+ int pwm_apply_might_sleep(struct pwm_device *pwm, struct pwm_state *state);
This API controls both the PWM period/duty_cycle config and the
enable/disable state.
+PWM devices can be used from atomic context, if the PWM does not sleep. You
+can check if this the case with::
+
+ bool pwm_might_sleep(struct pwm_device *pwm);
+
+If false, the PWM can also be configured from atomic context with::
+
+ int pwm_apply_atomic(struct pwm_device *pwm, struct pwm_state *state);
+
+As a consumer, don't rely on the output's state for a disabled PWM. If it's
+easily possible, drivers are supposed to emit the inactive state, but some
+drivers cannot. If you rely on getting the inactive state, use .duty_cycle=0,
+.enabled=true.
+
+There is also a usage_power setting: If set, the PWM driver is only required to
+maintain the power output but has more freedom regarding signal form.
+If supported by the driver, the signal can be optimized, for example to improve
+EMI by phase shifting the individual channels of a chip.
+
The pwm_config(), pwm_enable() and pwm_disable() functions are just wrappers
-around pwm_apply_state() and should not be used if the user wants to change
+around pwm_apply_might_sleep() and should not be used if the user wants to change
several parameter at once. For example, if you see pwm_config() and
pwm_{enable,disable}() calls in the same function, this probably means you
-should switch to pwm_apply_state().
+should switch to pwm_apply_might_sleep().
-The PWM user API also allows one to query the PWM state with pwm_get_state().
+The PWM user API also allows one to query the PWM state that was passed to the
+last invocation of pwm_apply_might_sleep() using pwm_get_state(). Note this is
+different to what the driver has actually implemented if the request cannot be
+satisfied exactly with the hardware in use. There is currently no way for
+consumers to get the actually implemented settings.
In addition to the PWM state, the PWM API also exposes PWM arguments, which
are the reference PWM config one should use on this PWM.
@@ -100,13 +120,13 @@ channel that was exported. The following properties will then be available:
duty_cycle
The active time of the PWM signal (read/write).
- Value is in nanoseconds and must be less than the period.
+ Value is in nanoseconds and must be less than or equal to the period.
polarity
Changes the polarity of the PWM signal (read/write).
Writes to this property only work if the PWM chip supports changing
- the polarity. The polarity can only be changed if the PWM is not
- enabled. Value is the string "normal" or "inversed".
+ the polarity.
+ Value is the string "normal" or "inversed".
enable
Enable/disable the PWM signal (read/write).
@@ -151,8 +171,8 @@ consumers should implement it as described in the "Using PWMs" section.
Locking
-------
-The PWM core list manipulations are protected by a mutex, so pwm_request()
-and pwm_free() may not be called from an atomic context. Currently the
+The PWM core list manipulations are protected by a mutex, so pwm_get()
+and pwm_put() may not be called from an atomic context. Currently the
PWM core does not enforce any locking to pwm_enable(), pwm_disable() and
pwm_config(), so the calling context is currently driver specific. This
is an issue derived from the former barebone API and should be fixed soon.
diff --git a/Documentation/driver-api/rapidio/rapidio.rst b/Documentation/driver-api/rapidio/rapidio.rst
index fb8942d3ba85..74c552ad3eb8 100644
--- a/Documentation/driver-api/rapidio/rapidio.rst
+++ b/Documentation/driver-api/rapidio/rapidio.rst
@@ -356,7 +356,7 @@ NOTE:
http://www.rapidio.org/education/technology_comparisons/
[3] RapidIO support for Linux.
- http://lwn.net/Articles/139118/
+ https://lwn.net/Articles/139118/
[4] Matt Porter. RapidIO for Linux. Ottawa Linux Symposium, 2005
- http://www.kernel.org/doc/ols/2005/ols2005v2-pages-43-56.pdf
+ https://www.kernel.org/doc/ols/2005/ols2005v2-pages-43-56.pdf
diff --git a/Documentation/driver-api/regulator.rst b/Documentation/driver-api/regulator.rst
index 520da0a5251d..b43c78eb24d8 100644
--- a/Documentation/driver-api/regulator.rst
+++ b/Documentation/driver-api/regulator.rst
@@ -116,7 +116,7 @@ core, providing operations structures to the core. A notifier interface
allows error conditions to be reported to the core.
Registration should be triggered by explicit setup done by the platform,
-supplying a struct :c:type:`regulator_init_data` for the regulator
+supplying a struct regulator_init_data for the regulator
containing constraint and supply information.
Machine interface
@@ -144,7 +144,7 @@ a given system, for example supporting higher supply voltages than the
consumers are rated for.
This is done at driver registration time` by providing a
-struct :c:type:`regulation_constraints`.
+struct regulation_constraints.
The constraints may also specify an initial configuration for the
regulator in the constraints, which is particularly useful for use with
diff --git a/Documentation/driver-api/reset.rst b/Documentation/driver-api/reset.rst
new file mode 100644
index 000000000000..84e03d7039cc
--- /dev/null
+++ b/Documentation/driver-api/reset.rst
@@ -0,0 +1,221 @@
+.. SPDX-License-Identifier: GPL-2.0-only
+
+====================
+Reset controller API
+====================
+
+Introduction
+============
+
+Reset controllers are central units that control the reset signals to multiple
+peripherals.
+The reset controller API is split into two parts:
+the `consumer driver interface <#consumer-driver-interface>`__ (`API reference
+<#reset-consumer-api>`__), which allows peripheral drivers to request control
+over their reset input signals, and the `reset controller driver interface
+<#reset-controller-driver-interface>`__ (`API reference
+<#reset-controller-driver-api>`__), which is used by drivers for reset
+controller devices to register their reset controls to provide them to the
+consumers.
+
+While some reset controller hardware units also implement system restart
+functionality, restart handlers are out of scope for the reset controller API.
+
+Glossary
+--------
+
+The reset controller API uses these terms with a specific meaning:
+
+Reset line
+
+ Physical reset line carrying a reset signal from a reset controller
+ hardware unit to a peripheral module.
+
+Reset control
+
+ Control method that determines the state of one or multiple reset lines.
+ Most commonly this is a single bit in reset controller register space that
+ either allows direct control over the physical state of the reset line, or
+ is self-clearing and can be used to trigger a predetermined pulse on the
+ reset line.
+ In more complicated reset controls, a single trigger action can launch a
+ carefully timed sequence of pulses on multiple reset lines.
+
+Reset controller
+
+ A hardware module that provides a number of reset controls to control a
+ number of reset lines.
+
+Reset consumer
+
+ Peripheral module or external IC that is put into reset by the signal on a
+ reset line.
+
+Consumer driver interface
+=========================
+
+This interface provides an API that is similar to the kernel clock framework.
+Consumer drivers use get and put operations to acquire and release reset
+controls.
+Functions are provided to assert and deassert the controlled reset lines,
+trigger reset pulses, or to query reset line status.
+
+When requesting reset controls, consumers can use symbolic names for their
+reset inputs, which are mapped to an actual reset control on an existing reset
+controller device by the core.
+
+A stub version of this API is provided when the reset controller framework is
+not in use in order to minimize the need to use ifdefs.
+
+Shared and exclusive resets
+---------------------------
+
+The reset controller API provides either reference counted deassertion and
+assertion or direct, exclusive control.
+The distinction between shared and exclusive reset controls is made at the time
+the reset control is requested, either via devm_reset_control_get_shared() or
+via devm_reset_control_get_exclusive().
+This choice determines the behavior of the API calls made with the reset
+control.
+
+Shared resets behave similarly to clocks in the kernel clock framework.
+They provide reference counted deassertion, where only the first deassert,
+which increments the deassertion reference count to one, and the last assert
+which decrements the deassertion reference count back to zero, have a physical
+effect on the reset line.
+
+Exclusive resets on the other hand guarantee direct control.
+That is, an assert causes the reset line to be asserted immediately, and a
+deassert causes the reset line to be deasserted immediately.
+
+Assertion and deassertion
+-------------------------
+
+Consumer drivers use the reset_control_assert() and reset_control_deassert()
+functions to assert and deassert reset lines.
+For shared reset controls, calls to the two functions must be balanced.
+
+Note that since multiple consumers may be using a shared reset control, there
+is no guarantee that calling reset_control_assert() on a shared reset control
+will actually cause the reset line to be asserted.
+Consumer drivers using shared reset controls should assume that the reset line
+may be kept deasserted at all times.
+The API only guarantees that the reset line can not be asserted as long as any
+consumer has requested it to be deasserted.
+
+Triggering
+----------
+
+Consumer drivers use reset_control_reset() to trigger a reset pulse on a
+self-deasserting reset control.
+In general, these resets can not be shared between multiple consumers, since
+requesting a pulse from any consumer driver will reset all connected
+peripherals.
+
+The reset controller API allows requesting self-deasserting reset controls as
+shared, but for those only the first trigger request causes an actual pulse to
+be issued on the reset line.
+All further calls to this function have no effect until all consumers have
+called reset_control_rearm().
+For shared reset controls, calls to the two functions must be balanced.
+This allows devices that only require an initial reset at any point before the
+driver is probed or resumed to share a pulsed reset line.
+
+Querying
+--------
+
+Only some reset controllers support querying the current status of a reset
+line, via reset_control_status().
+If supported, this function returns a positive non-zero value if the given
+reset line is asserted.
+The reset_control_status() function does not accept a
+`reset control array <#reset-control-arrays>`__ handle as its input parameter.
+
+Optional resets
+---------------
+
+Often peripherals require a reset line on some platforms but not on others.
+For this, reset controls can be requested as optional using
+devm_reset_control_get_optional_exclusive() or
+devm_reset_control_get_optional_shared().
+These functions return a NULL pointer instead of an error when the requested
+reset control is not specified in the device tree.
+Passing a NULL pointer to the reset_control functions causes them to return
+quietly without an error.
+
+Reset control arrays
+--------------------
+
+Some drivers need to assert a bunch of reset lines in no particular order.
+devm_reset_control_array_get() returns an opaque reset control handle that can
+be used to assert, deassert, or trigger all specified reset controls at once.
+The reset control API does not guarantee the order in which the individual
+controls therein are handled.
+
+Reset controller driver interface
+=================================
+
+Drivers for reset controller modules provide the functionality necessary to
+assert or deassert reset signals, to trigger a reset pulse on a reset line, or
+to query its current state.
+All functions are optional.
+
+Initialization
+--------------
+
+Drivers fill a struct :c:type:`reset_controller_dev` and register it with
+reset_controller_register() in their probe function.
+The actual functionality is implemented in callback functions via a struct
+:c:type:`reset_control_ops`.
+
+API reference
+=============
+
+The reset controller API is documented here in two parts:
+the `reset consumer API <#reset-consumer-api>`__ and the `reset controller
+driver API <#reset-controller-driver-api>`__.
+
+Reset consumer API
+------------------
+
+Reset consumers can control a reset line using an opaque reset control handle,
+which can be obtained from devm_reset_control_get_exclusive() or
+devm_reset_control_get_shared().
+Given the reset control, consumers can call reset_control_assert() and
+reset_control_deassert(), trigger a reset pulse using reset_control_reset(), or
+query the reset line status using reset_control_status().
+
+.. kernel-doc:: include/linux/reset.h
+ :internal:
+
+.. kernel-doc:: drivers/reset/core.c
+ :functions: reset_control_reset
+ reset_control_assert
+ reset_control_deassert
+ reset_control_status
+ reset_control_acquire
+ reset_control_release
+ reset_control_rearm
+ reset_control_put
+ of_reset_control_get_count
+ of_reset_control_array_get
+ devm_reset_control_array_get
+ reset_control_get_count
+
+Reset controller driver API
+---------------------------
+
+Reset controller drivers are supposed to implement the necessary functions in
+a static constant structure :c:type:`reset_control_ops`, allocate and fill out
+a struct :c:type:`reset_controller_dev`, and register it using
+devm_reset_controller_register().
+
+.. kernel-doc:: include/linux/reset-controller.h
+ :internal:
+
+.. kernel-doc:: drivers/reset/core.c
+ :functions: of_reset_simple_xlate
+ reset_controller_register
+ reset_controller_unregister
+ devm_reset_controller_register
+ reset_controller_add_lookup
diff --git a/Documentation/driver-api/s390-drivers.rst b/Documentation/driver-api/s390-drivers.rst
index 5158577bc29b..8c0845c4eee7 100644
--- a/Documentation/driver-api/s390-drivers.rst
+++ b/Documentation/driver-api/s390-drivers.rst
@@ -27,7 +27,7 @@ not strictly considered I/O devices. They are considered here as well,
although they are not the focus of this document.
Some additional information can also be found in the kernel source under
-Documentation/s390/driver-model.rst.
+Documentation/arch/s390/driver-model.rst.
The css bus
===========
@@ -38,7 +38,7 @@ into several categories:
* Standard I/O subchannels, for use by the system. They have a child
device on the ccw bus and are described below.
* I/O subchannels bound to the vfio-ccw driver. See
- Documentation/s390/vfio-ccw.rst.
+ Documentation/arch/s390/vfio-ccw.rst.
* Message subchannels. No Linux driver currently exists.
* CHSC subchannels (at most one). The chsc subchannel driver can be used
to send asynchronous chsc commands.
diff --git a/Documentation/driver-api/serial/cyclades_z.rst b/Documentation/driver-api/serial/cyclades_z.rst
deleted file mode 100644
index 532ff67e2f1c..000000000000
--- a/Documentation/driver-api/serial/cyclades_z.rst
+++ /dev/null
@@ -1,11 +0,0 @@
-================
-Cyclades-Z notes
-================
-
-The Cyclades-Z must have firmware loaded onto the card before it will
-operate. This operation should be performed during system startup,
-
-The firmware, loader program and the latest device driver code are
-available from Cyclades at
-
- ftp://ftp.cyclades.com/pub/cyclades/cyclades-z/linux/
diff --git a/Documentation/driver-api/serial/driver.rst b/Documentation/driver-api/serial/driver.rst
index 31bd4e16fb1f..84b43061c11b 100644
--- a/Documentation/driver-api/serial/driver.rst
+++ b/Documentation/driver-api/serial/driver.rst
@@ -24,11 +24,11 @@ console support.
Console Support
---------------
-The serial core provides a few helper functions. This includes identifing
-the correct port structure (via uart_get_console) and decoding command line
-arguments (uart_parse_options).
+The serial core provides a few helper functions. This includes identifying
+the correct port structure (via uart_get_console()) and decoding command line
+arguments (uart_parse_options()).
-There is also a helper function (uart_console_write) which performs a
+There is also a helper function (uart_console_write()) which performs a
character by character write, translating newlines to CRLF sequences.
Driver writers are recommended to use this function rather than implementing
their own version.
@@ -39,7 +39,7 @@ Locking
It is the responsibility of the low level hardware driver to perform the
necessary locking using port->lock. There are some exceptions (which
-are described in the uart_ops listing below.)
+are described in the struct uart_ops listing below.)
There are two locks. A per-port spinlock, and an overall semaphore.
@@ -63,442 +63,23 @@ commonly referred to as the port mutex.
uart_ops
--------
-The uart_ops structure is the main interface between serial_core and the
-hardware specific driver. It contains all the methods to control the
-hardware.
-
- tx_empty(port)
- This function tests whether the transmitter fifo and shifter
- for the port described by 'port' is empty. If it is empty,
- this function should return TIOCSER_TEMT, otherwise return 0.
- If the port does not support this operation, then it should
- return TIOCSER_TEMT.
-
- Locking: none.
-
- Interrupts: caller dependent.
-
- This call must not sleep
-
- set_mctrl(port, mctrl)
- This function sets the modem control lines for port described
- by 'port' to the state described by mctrl. The relevant bits
- of mctrl are:
-
- - TIOCM_RTS RTS signal.
- - TIOCM_DTR DTR signal.
- - TIOCM_OUT1 OUT1 signal.
- - TIOCM_OUT2 OUT2 signal.
- - TIOCM_LOOP Set the port into loopback mode.
-
- If the appropriate bit is set, the signal should be driven
- active. If the bit is clear, the signal should be driven
- inactive.
-
- Locking: port->lock taken.
-
- Interrupts: locally disabled.
-
- This call must not sleep
-
- get_mctrl(port)
- Returns the current state of modem control inputs. The state
- of the outputs should not be returned, since the core keeps
- track of their state. The state information should include:
-
- - TIOCM_CAR state of DCD signal
- - TIOCM_CTS state of CTS signal
- - TIOCM_DSR state of DSR signal
- - TIOCM_RI state of RI signal
-
- The bit is set if the signal is currently driven active. If
- the port does not support CTS, DCD or DSR, the driver should
- indicate that the signal is permanently active. If RI is
- not available, the signal should not be indicated as active.
-
- Locking: port->lock taken.
-
- Interrupts: locally disabled.
-
- This call must not sleep
-
- stop_tx(port)
- Stop transmitting characters. This might be due to the CTS
- line becoming inactive or the tty layer indicating we want
- to stop transmission due to an XOFF character.
-
- The driver should stop transmitting characters as soon as
- possible.
-
- Locking: port->lock taken.
-
- Interrupts: locally disabled.
-
- This call must not sleep
-
- start_tx(port)
- Start transmitting characters.
-
- Locking: port->lock taken.
-
- Interrupts: locally disabled.
-
- This call must not sleep
-
- throttle(port)
- Notify the serial driver that input buffers for the line discipline are
- close to full, and it should somehow signal that no more characters
- should be sent to the serial port.
- This will be called only if hardware assisted flow control is enabled.
-
- Locking: serialized with .unthrottle() and termios modification by the
- tty layer.
-
- unthrottle(port)
- Notify the serial driver that characters can now be sent to the serial
- port without fear of overrunning the input buffers of the line
- disciplines.
-
- This will be called only if hardware assisted flow control is enabled.
-
- Locking: serialized with .throttle() and termios modification by the
- tty layer.
-
- send_xchar(port,ch)
- Transmit a high priority character, even if the port is stopped.
- This is used to implement XON/XOFF flow control and tcflow(). If
- the serial driver does not implement this function, the tty core
- will append the character to the circular buffer and then call
- start_tx() / stop_tx() to flush the data out.
-
- Do not transmit if ch == '\0' (__DISABLED_CHAR).
-
- Locking: none.
-
- Interrupts: caller dependent.
-
- stop_rx(port)
- Stop receiving characters; the port is in the process of
- being closed.
-
- Locking: port->lock taken.
-
- Interrupts: locally disabled.
-
- This call must not sleep
-
- enable_ms(port)
- Enable the modem status interrupts.
-
- This method may be called multiple times. Modem status
- interrupts should be disabled when the shutdown method is
- called.
-
- Locking: port->lock taken.
-
- Interrupts: locally disabled.
-
- This call must not sleep
-
- break_ctl(port,ctl)
- Control the transmission of a break signal. If ctl is
- nonzero, the break signal should be transmitted. The signal
- should be terminated when another call is made with a zero
- ctl.
-
- Locking: caller holds tty_port->mutex
-
- startup(port)
- Grab any interrupt resources and initialise any low level driver
- state. Enable the port for reception. It should not activate
- RTS nor DTR; this will be done via a separate call to set_mctrl.
-
- This method will only be called when the port is initially opened.
-
- Locking: port_sem taken.
-
- Interrupts: globally disabled.
-
- shutdown(port)
- Disable the port, disable any break condition that may be in
- effect, and free any interrupt resources. It should not disable
- RTS nor DTR; this will have already been done via a separate
- call to set_mctrl.
-
- Drivers must not access port->state once this call has completed.
-
- This method will only be called when there are no more users of
- this port.
-
- Locking: port_sem taken.
-
- Interrupts: caller dependent.
-
- flush_buffer(port)
- Flush any write buffers, reset any DMA state and stop any
- ongoing DMA transfers.
-
- This will be called whenever the port->state->xmit circular
- buffer is cleared.
-
- Locking: port->lock taken.
-
- Interrupts: locally disabled.
-
- This call must not sleep
-
- set_termios(port,termios,oldtermios)
- Change the port parameters, including word length, parity, stop
- bits. Update read_status_mask and ignore_status_mask to indicate
- the types of events we are interested in receiving. Relevant
- termios->c_cflag bits are:
-
- CSIZE
- - word size
- CSTOPB
- - 2 stop bits
- PARENB
- - parity enable
- PARODD
- - odd parity (when PARENB is in force)
- CREAD
- - enable reception of characters (if not set,
- still receive characters from the port, but
- throw them away.
- CRTSCTS
- - if set, enable CTS status change reporting
- CLOCAL
- - if not set, enable modem status change
- reporting.
-
- Relevant termios->c_iflag bits are:
-
- INPCK
- - enable frame and parity error events to be
- passed to the TTY layer.
- BRKINT / PARMRK
- - both of these enable break events to be
- passed to the TTY layer.
-
- IGNPAR
- - ignore parity and framing errors
- IGNBRK
- - ignore break errors, If IGNPAR is also
- set, ignore overrun errors as well.
-
- The interaction of the iflag bits is as follows (parity error
- given as an example):
-
- =============== ======= ====== =============================
- Parity error INPCK IGNPAR
- =============== ======= ====== =============================
- n/a 0 n/a character received, marked as
- TTY_NORMAL
- None 1 n/a character received, marked as
- TTY_NORMAL
- Yes 1 0 character received, marked as
- TTY_PARITY
- Yes 1 1 character discarded
- =============== ======= ====== =============================
-
- Other flags may be used (eg, xon/xoff characters) if your
- hardware supports hardware "soft" flow control.
-
- Locking: caller holds tty_port->mutex
-
- Interrupts: caller dependent.
-
- This call must not sleep
-
- set_ldisc(port,termios)
- Notifier for discipline change. See Documentation/driver-api/serial/tty.rst.
-
- Locking: caller holds tty_port->mutex
-
- pm(port,state,oldstate)
- Perform any power management related activities on the specified
- port. State indicates the new state (defined by
- enum uart_pm_state), oldstate indicates the previous state.
-
- This function should not be used to grab any resources.
-
- This will be called when the port is initially opened and finally
- closed, except when the port is also the system console. This
- will occur even if CONFIG_PM is not set.
-
- Locking: none.
-
- Interrupts: caller dependent.
-
- type(port)
- Return a pointer to a string constant describing the specified
- port, or return NULL, in which case the string 'unknown' is
- substituted.
-
- Locking: none.
-
- Interrupts: caller dependent.
-
- release_port(port)
- Release any memory and IO region resources currently in use by
- the port.
-
- Locking: none.
-
- Interrupts: caller dependent.
-
- request_port(port)
- Request any memory and IO region resources required by the port.
- If any fail, no resources should be registered when this function
- returns, and it should return -EBUSY on failure.
-
- Locking: none.
-
- Interrupts: caller dependent.
-
- config_port(port,type)
- Perform any autoconfiguration steps required for the port. `type`
- contains a bit mask of the required configuration. UART_CONFIG_TYPE
- indicates that the port requires detection and identification.
- port->type should be set to the type found, or PORT_UNKNOWN if
- no port was detected.
-
- UART_CONFIG_IRQ indicates autoconfiguration of the interrupt signal,
- which should be probed using standard kernel autoprobing techniques.
- This is not necessary on platforms where ports have interrupts
- internally hard wired (eg, system on a chip implementations).
-
- Locking: none.
-
- Interrupts: caller dependent.
-
- verify_port(port,serinfo)
- Verify the new serial port information contained within serinfo is
- suitable for this port type.
-
- Locking: none.
-
- Interrupts: caller dependent.
-
- ioctl(port,cmd,arg)
- Perform any port specific IOCTLs. IOCTL commands must be defined
- using the standard numbering system found in <asm/ioctl.h>
-
- Locking: none.
-
- Interrupts: caller dependent.
-
- poll_init(port)
- Called by kgdb to perform the minimal hardware initialization needed
- to support poll_put_char() and poll_get_char(). Unlike ->startup()
- this should not request interrupts.
-
- Locking: tty_mutex and tty_port->mutex taken.
-
- Interrupts: n/a.
-
- poll_put_char(port,ch)
- Called by kgdb to write a single character directly to the serial
- port. It can and should block until there is space in the TX FIFO.
-
- Locking: none.
-
- Interrupts: caller dependent.
-
- This call must not sleep
-
- poll_get_char(port)
- Called by kgdb to read a single character directly from the serial
- port. If data is available, it should be returned; otherwise
- the function should return NO_POLL_CHAR immediately.
-
- Locking: none.
-
- Interrupts: caller dependent.
-
- This call must not sleep
+.. kernel-doc:: include/linux/serial_core.h
+ :identifiers: uart_ops
Other functions
---------------
-uart_update_timeout(port,cflag,baud)
- Update the FIFO drain timeout, port->timeout, according to the
- number of bits, parity, stop bits and baud rate.
-
- Locking: caller is expected to take port->lock
-
- Interrupts: n/a
-
-uart_get_baud_rate(port,termios,old,min,max)
- Return the numeric baud rate for the specified termios, taking
- account of the special 38400 baud "kludge". The B0 baud rate
- is mapped to 9600 baud.
-
- If the baud rate is not within min..max, then if old is non-NULL,
- the original baud rate will be tried. If that exceeds the
- min..max constraint, 9600 baud will be returned. termios will
- be updated to the baud rate in use.
-
- Note: min..max must always allow 9600 baud to be selected.
-
- Locking: caller dependent.
-
- Interrupts: n/a
-
-uart_get_divisor(port,baud)
- Return the divisor (baud_base / baud) for the specified baud
- rate, appropriately rounded.
-
- If 38400 baud and custom divisor is selected, return the
- custom divisor instead.
-
- Locking: caller dependent.
-
- Interrupts: n/a
-
-uart_match_port(port1,port2)
- This utility function can be used to determine whether two
- uart_port structures describe the same port.
-
- Locking: n/a
-
- Interrupts: n/a
-
-uart_write_wakeup(port)
- A driver is expected to call this function when the number of
- characters in the transmit buffer have dropped below a threshold.
-
- Locking: port->lock should be held.
+.. kernel-doc:: drivers/tty/serial/serial_core.c
+ :identifiers: uart_update_timeout uart_get_baud_rate uart_get_divisor
+ uart_match_port uart_write_wakeup uart_register_driver
+ uart_unregister_driver uart_suspend_port uart_resume_port
+ uart_add_one_port uart_remove_one_port uart_console_write
+ uart_parse_earlycon uart_parse_options uart_set_options
+ uart_get_lsr_info uart_handle_dcd_change uart_handle_cts_change
+ uart_try_toggle_sysrq uart_get_console
- Interrupts: n/a
-
-uart_register_driver(drv)
- Register a uart driver with the core driver. We in turn register
- with the tty layer, and initialise the core driver per-port state.
-
- drv->port should be NULL, and the per-port structures should be
- registered using uart_add_one_port after this call has succeeded.
-
- Locking: none
-
- Interrupts: enabled
-
-uart_unregister_driver()
- Remove all references to a driver from the core driver. The low
- level driver must have removed all its ports via the
- uart_remove_one_port() if it registered them with uart_add_one_port().
-
- Locking: none
-
- Interrupts: enabled
-
-**uart_suspend_port()**
-
-**uart_resume_port()**
-
-**uart_add_one_port()**
-
-**uart_remove_one_port()**
+.. kernel-doc:: include/linux/serial_core.h
+ :identifiers: uart_port_tx_limited uart_port_tx
Other notes
-----------
@@ -519,31 +100,7 @@ Modem control lines via GPIO
Some helpers are provided in order to set/get modem control lines via GPIO.
-mctrl_gpio_init(port, idx):
- This will get the {cts,rts,...}-gpios from device tree if they are
- present and request them, set direction etc, and return an
- allocated structure. `devm_*` functions are used, so there's no need
- to call mctrl_gpio_free().
- As this sets up the irq handling make sure to not handle changes to the
- gpio input lines in your driver, too.
-
-mctrl_gpio_free(dev, gpios):
- This will free the requested gpios in mctrl_gpio_init().
- As `devm_*` functions are used, there's generally no need to call
- this function.
-
-mctrl_gpio_to_gpiod(gpios, gidx)
- This returns the gpio_desc structure associated to the modem line
- index.
-
-mctrl_gpio_set(gpios, mctrl):
- This will sets the gpios according to the mctrl state.
-
-mctrl_gpio_get(gpios, mctrl):
- This will update mctrl with the gpios values.
-
-mctrl_gpio_enable_ms(gpios):
- Enables irqs and handling of changes to the ms lines.
-
-mctrl_gpio_disable_ms(gpios):
- Disables irqs and handling of changes to the ms lines.
+.. kernel-doc:: drivers/tty/serial/serial_mctrl_gpio.c
+ :identifiers: mctrl_gpio_init mctrl_gpio_free mctrl_gpio_to_gpiod
+ mctrl_gpio_set mctrl_gpio_get mctrl_gpio_enable_ms
+ mctrl_gpio_disable_ms
diff --git a/Documentation/driver-api/serial/index.rst b/Documentation/driver-api/serial/index.rst
index 33ad10d05b26..03a55b987a1d 100644
--- a/Documentation/driver-api/serial/index.rst
+++ b/Documentation/driver-api/serial/index.rst
@@ -9,7 +9,6 @@ Support for Serial devices
driver
- tty
Serial drivers
==============
@@ -17,10 +16,6 @@ Serial drivers
.. toctree::
:maxdepth: 1
- cyclades_z
- moxa-smartio
- n_gsm
- rocket
serial-iso7816
serial-rs485
diff --git a/Documentation/driver-api/serial/moxa-smartio.rst b/Documentation/driver-api/serial/moxa-smartio.rst
deleted file mode 100644
index 156100f17c3f..000000000000
--- a/Documentation/driver-api/serial/moxa-smartio.rst
+++ /dev/null
@@ -1,615 +0,0 @@
-=============================================================
-MOXA Smartio/Industio Family Device Driver Installation Guide
-=============================================================
-
-.. note::
-
- This file is outdated. It needs some care in order to make it
- updated to Kernel 5.0 and upper
-
-Copyright (C) 2008, Moxa Inc.
-
-Date: 01/21/2008
-
-.. Content
-
- 1. Introduction
- 2. System Requirement
- 3. Installation
- 3.1 Hardware installation
- 3.2 Driver files
- 3.3 Device naming convention
- 3.4 Module driver configuration
- 3.5 Static driver configuration for Linux kernel 2.4.x and 2.6.x.
- 3.6 Custom configuration
- 3.7 Verify driver installation
- 4. Utilities
- 5. Setserial
- 6. Troubleshooting
-
-1. Introduction
-^^^^^^^^^^^^^^^
-
- The Smartio/Industio/UPCI family Linux driver supports following multiport
- boards.
-
- - 2 ports multiport board
- CP-102U, CP-102UL, CP-102UF
- CP-132U-I, CP-132UL,
- CP-132, CP-132I, CP132S, CP-132IS,
- CI-132, CI-132I, CI-132IS,
- (C102H, C102HI, C102HIS, C102P, CP-102, CP-102S)
-
- - 4 ports multiport board
- CP-104EL,
- CP-104UL, CP-104JU,
- CP-134U, CP-134U-I,
- C104H/PCI, C104HS/PCI,
- CP-114, CP-114I, CP-114S, CP-114IS, CP-114UL,
- C104H, C104HS,
- CI-104J, CI-104JS,
- CI-134, CI-134I, CI-134IS,
- (C114HI, CT-114I, C104P),
- POS-104UL,
- CB-114,
- CB-134I
-
- - 8 ports multiport board
- CP-118EL, CP-168EL,
- CP-118U, CP-168U,
- C168H/PCI,
- C168H, C168HS,
- (C168P),
- CB-108
-
- This driver and installation procedure have been developed upon Linux Kernel
- 2.4.x and 2.6.x. This driver supports Intel x86 hardware platform. In order
- to maintain compatibility, this version has also been properly tested with
- RedHat, Mandrake, Fedora and S.u.S.E Linux. However, if compatibility problem
- occurs, please contact Moxa at support@moxa.com.tw.
-
- In addition to device driver, useful utilities are also provided in this
- version. They are:
-
- - msdiag
- Diagnostic program for displaying installed Moxa
- Smartio/Industio boards.
- - msmon
- Monitor program to observe data count and line status signals.
- - msterm A simple terminal program which is useful in testing serial
- ports.
- - io-irq.exe
- Configuration program to setup ISA boards. Please note that
- this program can only be executed under DOS.
-
- All the drivers and utilities are published in form of source code under
- GNU General Public License in this version. Please refer to GNU General
- Public License announcement in each source code file for more detail.
-
- In Moxa's Web sites, you may always find latest driver at http://www.moxa.com/.
-
- This version of driver can be installed as Loadable Module (Module driver)
- or built-in into kernel (Static driver). You may refer to following
- installation procedure for suitable one. Before you install the driver,
- please refer to hardware installation procedure in the User's Manual.
-
- We assume the user should be familiar with following documents.
-
- - Serial-HOWTO
- - Kernel-HOWTO
-
-2. System Requirement
-^^^^^^^^^^^^^^^^^^^^^
-
- - Hardware platform: Intel x86 machine
- - Kernel version: 2.4.x or 2.6.x
- - gcc version 2.72 or later
- - Maximum 4 boards can be installed in combination
-
-3. Installation
-^^^^^^^^^^^^^^^
-
-3.1 Hardware installation
-=========================
-
- There are two types of buses, ISA and PCI, for Smartio/Industio
- family multiport board.
-
-ISA board
----------
-
- You'll have to configure CAP address, I/O address, Interrupt Vector
- as well as IRQ before installing this driver. Please refer to hardware
- installation procedure in User's Manual before proceed any further.
- Please make sure the JP1 is open after the ISA board is set properly.
-
-PCI/UPCI board
---------------
-
- You may need to adjust IRQ usage in BIOS to avoid from IRQ conflict
- with other ISA devices. Please refer to hardware installation
- procedure in User's Manual in advance.
-
-PCI IRQ Sharing
----------------
-
- Each port within the same multiport board shares the same IRQ. Up to
- 4 Moxa Smartio/Industio PCI Family multiport boards can be installed
- together on one system and they can share the same IRQ.
-
-
-3.2 Driver files
-================
-
- The driver file may be obtained from ftp, CD-ROM or floppy disk. The
- first step, anyway, is to copy driver file "mxser.tgz" into specified
- directory. e.g. /moxa. The execute commands as below::
-
- # cd /
- # mkdir moxa
- # cd /moxa
- # tar xvf /dev/fd0
-
-or::
-
- # cd /
- # mkdir moxa
- # cd /moxa
- # cp /mnt/cdrom/<driver directory>/mxser.tgz .
- # tar xvfz mxser.tgz
-
-
-3.3 Device naming convention
-============================
-
- You may find all the driver and utilities files in /moxa/mxser.
- Following installation procedure depends on the model you'd like to
- run the driver. If you prefer module driver, please refer to 3.4.
- If static driver is required, please refer to 3.5.
-
-Dialin and callout port
------------------------
-
- This driver remains traditional serial device properties. There are
- two special file name for each serial port. One is dial-in port
- which is named "ttyMxx". For callout port, the naming convention
- is "cumxx".
-
-Device naming when more than 2 boards installed
------------------------------------------------
-
- Naming convention for each Smartio/Industio multiport board is
- pre-defined as below.
-
- ============ =============== ==============
- Board Num. Dial-in Port Callout port
- 1st board ttyM0 - ttyM7 cum0 - cum7
- 2nd board ttyM8 - ttyM15 cum8 - cum15
- 3rd board ttyM16 - ttyM23 cum16 - cum23
- 4th board ttyM24 - ttym31 cum24 - cum31
- ============ =============== ==============
-
-.. note::
-
- Under Kernel 2.6 and upper, the cum Device is Obsolete. So use ttyM*
- device instead.
-
-Board sequence
---------------
-
- This driver will activate ISA boards according to the parameter set
- in the driver. After all specified ISA board activated, PCI board
- will be installed in the system automatically driven.
- Therefore the board number is sorted by the CAP address of ISA boards.
- For PCI boards, their sequence will be after ISA boards and C168H/PCI
- has higher priority than C104H/PCI boards.
-
-3.4 Module driver configuration
-===============================
-
- Module driver is easiest way to install. If you prefer static driver
- installation, please skip this paragraph.
-
-
- ------------- Prepare to use the MOXA driver --------------------
-
-3.4.1 Create tty device with correct major number
--------------------------------------------------
-
- Before using MOXA driver, your system must have the tty devices
- which are created with driver's major number. We offer one shell
- script "msmknod" to simplify the procedure.
- This step is only needed to be executed once. But you still
- need to do this procedure when:
-
- a. You change the driver's major number. Please refer the "3.7"
- section.
- b. Your total installed MOXA boards number is changed. Maybe you
- add/delete one MOXA board.
- c. You want to change the tty name. This needs to modify the
- shell script "msmknod"
-
- The procedure is::
-
- # cd /moxa/mxser/driver
- # ./msmknod
-
- This shell script will require the major number for dial-in
- device and callout device to create tty device. You also need
- to specify the total installed MOXA board number. Default major
- numbers for dial-in device and callout device are 30, 35. If
- you need to change to other number, please refer section "3.7"
- for more detailed procedure.
- Msmknod will delete any special files occupying the same device
- naming.
-
-3.4.2 Build the MOXA driver and utilities
------------------------------------------
-
- Before using the MOXA driver and utilities, you need compile the
- all the source code. This step is only need to be executed once.
- But you still re-compile the source code if you modify the source
- code. For example, if you change the driver's major number (see
- "3.7" section), then you need to do this step again.
-
- Find "Makefile" in /moxa/mxser, then run
-
- # make clean; make install
-
- ..note::
-
- For Red Hat 9, Red Hat Enterprise Linux AS3/ES3/WS3 & Fedora Core1:
- # make clean; make installsp1
-
- For Red Hat Enterprise Linux AS4/ES4/WS4:
- # make clean; make installsp2
-
- The driver files "mxser.o" and utilities will be properly compiled
- and copied to system directories respectively.
-
-------------- Load MOXA driver--------------------
-
-3.4.3 Load the MOXA driver
---------------------------
-
- ::
-
- # modprobe mxser <argument>
-
- will activate the module driver. You may run "lsmod" to check
- if "mxser" is activated. If the MOXA board is ISA board, the
- <argument> is needed. Please refer to section "3.4.5" for more
- information.
-
-------------- Load MOXA driver on boot --------------------
-
-3.4.4 Load the mxser driver
----------------------------
-
-
- For the above description, you may manually execute
- "modprobe mxser" to activate this driver and run
- "rmmod mxser" to remove it.
-
- However, it's better to have a boot time configuration to
- eliminate manual operation. Boot time configuration can be
- achieved by rc file. We offer one "rc.mxser" file to simplify
- the procedure under "moxa/mxser/driver".
-
- But if you use ISA board, please modify the "modprobe ..." command
- to add the argument (see "3.4.5" section). After modifying the
- rc.mxser, please try to execute "/moxa/mxser/driver/rc.mxser"
- manually to make sure the modification is ok. If any error
- encountered, please try to modify again. If the modification is
- completed, follow the below step.
-
- Run following command for setting rc files::
-
- # cd /moxa/mxser/driver
- # cp ./rc.mxser /etc/rc.d
- # cd /etc/rc.d
-
- Check "rc.serial" is existed or not. If "rc.serial" doesn't exist,
- create it by vi, run "chmod 755 rc.serial" to change the permission.
-
- Add "/etc/rc.d/rc.mxser" in last line.
-
- Reboot and check if moxa.o activated by "lsmod" command.
-
-3.4.5. specify CAP address
---------------------------
-
- If you'd like to drive Smartio/Industio ISA boards in the system,
- you'll have to add parameter to specify CAP address of given
- board while activating "mxser.o". The format for parameters are
- as follows.::
-
- modprobe mxser ioaddr=0x???,0x???,0x???,0x???
- | | | |
- | | | +- 4th ISA board
- | | +------ 3rd ISA board
- | +------------ 2nd ISA board
- +-------------------1st ISA board
-
-3.5 Static driver configuration for Linux kernel 2.4.x and 2.6.x
-================================================================
-
- Note:
- To use static driver, you must install the linux kernel
- source package.
-
-3.5.1 Backup the built-in driver in the kernel
-----------------------------------------------
-
- ::
-
- # cd /usr/src/linux/drivers/char
- # mv mxser.c mxser.c.old
-
- For Red Hat 7.x user, you need to create link:
- # cd /usr/src
- # ln -s linux-2.4 linux
-
-3.5.2 Create link
------------------
- ::
-
- # cd /usr/src/linux/drivers/char
- # ln -s /moxa/mxser/driver/mxser.c mxser.c
-
-3.5.3 Add CAP address list for ISA boards.
-------------------------------------------
-
- For PCI boards user, please skip this step.
-
- In module mode, the CAP address for ISA board is given by
- parameter. In static driver configuration, you'll have to
- assign it within driver's source code. If you will not
- install any ISA boards, you may skip to next portion.
- The instructions to modify driver source code are as
- below.
-
- a. run::
-
- # cd /moxa/mxser/driver
- # vi mxser.c
-
- b. Find the array mxserBoardCAP[] as below::
-
- static int mxserBoardCAP[] = {0x00, 0x00, 0x00, 0x00};
-
- c. Change the address within this array using vi. For
- example, to driver 2 ISA boards with CAP address
- 0x280 and 0x180 as 1st and 2nd board. Just to change
- the source code as follows::
-
- static int mxserBoardCAP[] = {0x280, 0x180, 0x00, 0x00};
-
-3.5.4 Setup kernel configuration
---------------------------------
-
- Configure the kernel::
-
- # cd /usr/src/linux
- # make menuconfig
-
- You will go into a menu-driven system. Please select [Character
- devices][Non-standard serial port support], enable the [Moxa
- SmartIO support] driver with "[*]" for built-in (not "[M]"), then
- select [Exit] to exit this program.
-
-3.5.5 Rebuild kernel
---------------------
-
- The following are for Linux kernel rebuilding, for your
- reference only.
-
- For appropriate details, please refer to the Linux document:
-
- a. Run the following commands::
-
- cd /usr/src/linux
- make clean # take a few minutes
- make dep # take a few minutes
- make bzImage # take probably 10-20 minutes
- make install # copy boot image to correct position
-
- f. Please make sure the boot kernel (vmlinuz) is in the
- correct position.
- g. If you use 'lilo' utility, you should check /etc/lilo.conf
- 'image' item specified the path which is the 'vmlinuz' path,
- or you will load wrong (or old) boot kernel image (vmlinuz).
- After checking /etc/lilo.conf, please run "lilo".
-
- Note that if the result of "make bzImage" is ERROR, then you have to
- go back to Linux configuration Setup. Type "make menuconfig" in
- directory /usr/src/linux.
-
-
-3.5.6 Make tty device and special file
---------------------------------------
-
- ::
- # cd /moxa/mxser/driver
- # ./msmknod
-
-3.5.7 Make utility
-------------------
-
- ::
-
- # cd /moxa/mxser/utility
- # make clean; make install
-
-3.5.8 Reboot
-------------
-
-
-
-3.6 Custom configuration
-========================
-
- Although this driver already provides you default configuration, you
- still can change the device name and major number. The instruction to
- change these parameters are shown as below.
-
-a. Change Device name
-
- If you'd like to use other device names instead of default naming
- convention, all you have to do is to modify the internal code
- within the shell script "msmknod". First, you have to open "msmknod"
- by vi. Locate each line contains "ttyM" and "cum" and change them
- to the device name you desired. "msmknod" creates the device names
- you need next time executed.
-
-b. Change Major number
-
- If major number 30 and 35 had been occupied, you may have to select
- 2 free major numbers for this driver. There are 3 steps to change
- major numbers.
-
-3.6.1 Find free major numbers
------------------------------
-
- In /proc/devices, you may find all the major numbers occupied
- in the system. Please select 2 major numbers that are available.
- e.g. 40, 45.
-
-3.6.2 Create special files
---------------------------
-
- Run /moxa/mxser/driver/msmknod to create special files with
- specified major numbers.
-
-3.6.3 Modify driver with new major number
------------------------------------------
-
- Run vi to open /moxa/mxser/driver/mxser.c. Locate the line
- contains "MXSERMAJOR". Change the content as below::
-
- #define MXSERMAJOR 40
- #define MXSERCUMAJOR 45
-
- 3.6.4 Run "make clean; make install" in /moxa/mxser/driver.
-
-3.7 Verify driver installation
-==============================
-
- You may refer to /var/log/messages to check the latest status
- log reported by this driver whenever it's activated.
-
-4. Utilities
-^^^^^^^^^^^^
-
- There are 3 utilities contained in this driver. They are msdiag, msmon and
- msterm. These 3 utilities are released in form of source code. They should
- be compiled into executable file and copied into /usr/bin.
-
- Before using these utilities, please load driver (refer 3.4 & 3.5) and
- make sure you had run the "msmknod" utility.
-
-msdiag - Diagnostic
-===================
-
- This utility provides the function to display what Moxa Smartio/Industio
- board found by driver in the system.
-
-msmon - Port Monitoring
-=======================
-
- This utility gives the user a quick view about all the MOXA ports'
- activities. One can easily learn each port's total received/transmitted
- (Rx/Tx) character count since the time when the monitoring is started.
-
- Rx/Tx throughputs per second are also reported in interval basis (e.g.
- the last 5 seconds) and in average basis (since the time the monitoring
- is started). You can reset all ports' count by <HOME> key. <+> <->
- (plus/minus) keys to change the displaying time interval. Press <ENTER>
- on the port, that cursor stay, to view the port's communication
- parameters, signal status, and input/output queue.
-
-msterm - Terminal Emulation
-===========================
-
- This utility provides data sending and receiving ability of all tty ports,
- especially for MOXA ports. It is quite useful for testing simple
- application, for example, sending AT command to a modem connected to the
- port or used as a terminal for login purpose. Note that this is only a
- dumb terminal emulation without handling full screen operation.
-
-5. Setserial
-^^^^^^^^^^^^
-
- Supported Setserial parameters are listed as below.
-
- ============== =========================================================
- uart set UART type(16450-->disable FIFO, 16550A-->enable FIFO)
- close_delay set the amount of time(in 1/100 of a second) that DTR
- should be kept low while being closed.
- closing_wait set the amount of time(in 1/100 of a second) that the
- serial port should wait for data to be drained while
- being closed, before the receiver is disable.
- spd_hi Use 57.6kb when the application requests 38.4kb.
- spd_vhi Use 115.2kb when the application requests 38.4kb.
- spd_shi Use 230.4kb when the application requests 38.4kb.
- spd_warp Use 460.8kb when the application requests 38.4kb.
- spd_normal Use 38.4kb when the application requests 38.4kb.
- spd_cust Use the custom divisor to set the speed when the
- application requests 38.4kb.
- divisor This option set the custom division.
- baud_base This option set the base baud rate.
- ============== =========================================================
-
-6. Troubleshooting
-^^^^^^^^^^^^^^^^^^
-
- The boot time error messages and solutions are stated as clearly as
- possible. If all the possible solutions fail, please contact our technical
- support team to get more help.
-
-
- Error msg:
- More than 4 Moxa Smartio/Industio family boards found. Fifth board
- and after are ignored.
-
- Solution:
- To avoid this problem, please unplug fifth and after board, because Moxa
- driver supports up to 4 boards.
-
- Error msg:
- Request_irq fail, IRQ(?) may be conflict with another device.
-
- Solution:
- Other PCI or ISA devices occupy the assigned IRQ. If you are not sure
- which device causes the situation, please check /proc/interrupts to find
- free IRQ and simply change another free IRQ for Moxa board.
-
- Error msg:
- Board #: C1xx Series(CAP=xxx) interrupt number invalid.
-
- Solution:
- Each port within the same multiport board shares the same IRQ. Please set
- one IRQ (IRQ doesn't equal to zero) for one Moxa board.
-
- Error msg:
- No interrupt vector be set for Moxa ISA board(CAP=xxx).
-
- Solution:
- Moxa ISA board needs an interrupt vector.Please refer to user's manual
- "Hardware Installation" chapter to set interrupt vector.
-
- Error msg:
- Couldn't install MOXA Smartio/Industio family driver!
-
- Solution:
- Load Moxa driver fail, the major number may conflict with other devices.
- Please refer to previous section 3.7 to change a free major number for
- Moxa driver.
-
- Error msg:
- Couldn't install MOXA Smartio/Industio family callout driver!
-
- Solution:
- Load Moxa callout driver fail, the callout device major number may
- conflict with other devices. Please refer to previous section 3.7 to
- change a free callout device major number for Moxa driver.
diff --git a/Documentation/driver-api/serial/n_gsm.rst b/Documentation/driver-api/serial/n_gsm.rst
deleted file mode 100644
index 286e7ff4d2d9..000000000000
--- a/Documentation/driver-api/serial/n_gsm.rst
+++ /dev/null
@@ -1,100 +0,0 @@
-==============================
-GSM 0710 tty multiplexor HOWTO
-==============================
-
-This line discipline implements the GSM 07.10 multiplexing protocol
-detailed in the following 3GPP document:
-
- http://www.3gpp.org/ftp/Specs/archive/07_series/07.10/0710-720.zip
-
-This document give some hints on how to use this driver with GPRS and 3G
-modems connected to a physical serial port.
-
-How to use it
--------------
-1. initialize the modem in 0710 mux mode (usually AT+CMUX= command) through
- its serial port. Depending on the modem used, you can pass more or less
- parameters to this command,
-2. switch the serial line to using the n_gsm line discipline by using
- TIOCSETD ioctl,
-3. configure the mux using GSMIOC_GETCONF / GSMIOC_SETCONF ioctl,
-4. obtain base gsmtty number for the used serial port,
-
-Major parts of the initialization program :
-(a good starting point is util-linux-ng/sys-utils/ldattach.c)::
-
- #include <stdio.h>
- #include <stdint.h>
- #include <linux/gsmmux.h>
- #include <linux/tty.h>
- #define DEFAULT_SPEED B115200
- #define SERIAL_PORT /dev/ttyS0
-
- int ldisc = N_GSM0710;
- struct gsm_config c;
- struct termios configuration;
- uint32_t first;
-
- /* open the serial port connected to the modem */
- fd = open(SERIAL_PORT, O_RDWR | O_NOCTTY | O_NDELAY);
-
- /* configure the serial port : speed, flow control ... */
-
- /* send the AT commands to switch the modem to CMUX mode
- and check that it's successful (should return OK) */
- write(fd, "AT+CMUX=0\r", 10);
-
- /* experience showed that some modems need some time before
- being able to answer to the first MUX packet so a delay
- may be needed here in some case */
- sleep(3);
-
- /* use n_gsm line discipline */
- ioctl(fd, TIOCSETD, &ldisc);
-
- /* get n_gsm configuration */
- ioctl(fd, GSMIOC_GETCONF, &c);
- /* we are initiator and need encoding 0 (basic) */
- c.initiator = 1;
- c.encapsulation = 0;
- /* our modem defaults to a maximum size of 127 bytes */
- c.mru = 127;
- c.mtu = 127;
- /* set the new configuration */
- ioctl(fd, GSMIOC_SETCONF, &c);
- /* get first gsmtty device node */
- ioctl(fd, GSMIOC_GETFIRST, &first);
- printf("first muxed line: /dev/gsmtty%i\n", first);
-
- /* and wait for ever to keep the line discipline enabled */
- daemon(0,0);
- pause();
-
-5. use these devices as plain serial ports.
-
- for example, it's possible:
-
- - and to use gnokii to send / receive SMS on ttygsm1
- - to use ppp to establish a datalink on ttygsm2
-
-6. first close all virtual ports before closing the physical port.
-
- Note that after closing the physical port the modem is still in multiplexing
- mode. This may prevent a successful re-opening of the port later. To avoid
- this situation either reset the modem if your hardware allows that or send
- a disconnect command frame manually before initializing the multiplexing mode
- for the second time. The byte sequence for the disconnect command frame is::
-
- 0xf9, 0x03, 0xef, 0x03, 0xc3, 0x16, 0xf9.
-
-Additional Documentation
-------------------------
-More practical details on the protocol and how it's supported by industrial
-modems can be found in the following documents :
-
-- http://www.telit.com/module/infopool/download.php?id=616
-- http://www.u-blox.com/images/downloads/Product_Docs/LEON-G100-G200-MuxImplementation_ApplicationNote_%28GSM%20G1-CS-10002%29.pdf
-- http://www.sierrawireless.com/Support/Downloads/AirPrime/WMP_Series/~/media/Support_Downloads/AirPrime/Application_notes/CMUX_Feature_Application_Note-Rev004.ashx
-- http://wm.sim.com/sim/News/photo/2010721161442.pdf
-
-11-03-08 - Eric Bénard - <eric@eukrea.com>
diff --git a/Documentation/driver-api/serial/rocket.rst b/Documentation/driver-api/serial/rocket.rst
deleted file mode 100644
index 23761eae4282..000000000000
--- a/Documentation/driver-api/serial/rocket.rst
+++ /dev/null
@@ -1,185 +0,0 @@
-================================================
-Comtrol(tm) RocketPort(R)/RocketModem(TM) Series
-================================================
-
-Device Driver for the Linux Operating System
-============================================
-
-Product overview
-----------------
-
-This driver provides a loadable kernel driver for the Comtrol RocketPort
-and RocketModem PCI boards. These boards provide, 2, 4, 8, 16, or 32
-high-speed serial ports or modems. This driver supports up to a combination
-of four RocketPort or RocketModems boards in one machine simultaneously.
-This file assumes that you are using the RocketPort driver which is
-integrated into the kernel sources.
-
-The driver can also be installed as an external module using the usual
-"make;make install" routine. This external module driver, obtainable
-from the Comtrol website listed below, is useful for updating the driver
-or installing it into kernels which do not have the driver configured
-into them. Installations instructions for the external module
-are in the included README and HW_INSTALL files.
-
-RocketPort ISA and RocketModem II PCI boards currently are only supported by
-this driver in module form.
-
-The RocketPort ISA board requires I/O ports to be configured by the DIP
-switches on the board. See the section "ISA Rocketport Boards" below for
-information on how to set the DIP switches.
-
-You pass the I/O port to the driver using the following module parameters:
-
-board1:
- I/O port for the first ISA board
-board2:
- I/O port for the second ISA board
-board3:
- I/O port for the third ISA board
-board4:
- I/O port for the fourth ISA board
-
-There is a set of utilities and scripts provided with the external driver
-(downloadable from http://www.comtrol.com) that ease the configuration and
-setup of the ISA cards.
-
-The RocketModem II PCI boards require firmware to be loaded into the card
-before it will function. The driver has only been tested as a module for this
-board.
-
-Installation Procedures
------------------------
-
-RocketPort/RocketModem PCI cards require no driver configuration, they are
-automatically detected and configured.
-
-The RocketPort driver can be installed as a module (recommended) or built
-into the kernel. This is selected, as for other drivers, through the `make config`
-command from the root of the Linux source tree during the kernel build process.
-
-The RocketPort/RocketModem serial ports installed by this driver are assigned
-device major number 46, and will be named /dev/ttyRx, where x is the port number
-starting at zero (ex. /dev/ttyR0, /devttyR1, ...). If you have multiple cards
-installed in the system, the mapping of port names to serial ports is displayed
-in the system log at /var/log/messages.
-
-If installed as a module, the module must be loaded. This can be done
-manually by entering "modprobe rocket". To have the module loaded automatically
-upon system boot, edit a `/etc/modprobe.d/*.conf` file and add the line
-"alias char-major-46 rocket".
-
-In order to use the ports, their device names (nodes) must be created with mknod.
-This is only required once, the system will retain the names once created. To
-create the RocketPort/RocketModem device names, use the command
-"mknod /dev/ttyRx c 46 x" where x is the port number starting at zero.
-
-For example::
-
- > mknod /dev/ttyR0 c 46 0
- > mknod /dev/ttyR1 c 46 1
- > mknod /dev/ttyR2 c 46 2
-
-The Linux script MAKEDEV will create the first 16 ttyRx device names (nodes)
-for you::
-
- >/dev/MAKEDEV ttyR
-
-ISA Rocketport Boards
----------------------
-
-You must assign and configure the I/O addresses used by the ISA Rocketport
-card before installing and using it. This is done by setting a set of DIP
-switches on the Rocketport board.
-
-
-Setting the I/O address
------------------------
-
-Before installing RocketPort(R) or RocketPort RA boards, you must find
-a range of I/O addresses for it to use. The first RocketPort card
-requires a 68-byte contiguous block of I/O addresses, starting at one
-of the following: 0x100h, 0x140h, 0x180h, 0x200h, 0x240h, 0x280h,
-0x300h, 0x340h, 0x380h. This I/O address must be reflected in the DIP
-switches of *all* of the Rocketport cards.
-
-The second, third, and fourth RocketPort cards require a 64-byte
-contiguous block of I/O addresses, starting at one of the following
-I/O addresses: 0x100h, 0x140h, 0x180h, 0x1C0h, 0x200h, 0x240h, 0x280h,
-0x2C0h, 0x300h, 0x340h, 0x380h, 0x3C0h. The I/O address used by the
-second, third, and fourth Rocketport cards (if present) are set via
-software control. The DIP switch settings for the I/O address must be
-set to the value of the first Rocketport cards.
-
-In order to distinguish each of the card from the others, each card
-must have a unique board ID set on the dip switches. The first
-Rocketport board must be set with the DIP switches corresponding to
-the first board, the second board must be set with the DIP switches
-corresponding to the second board, etc. IMPORTANT: The board ID is
-the only place where the DIP switch settings should differ between the
-various Rocketport boards in a system.
-
-The I/O address range used by any of the RocketPort cards must not
-conflict with any other cards in the system, including other
-RocketPort cards. Below, you will find a list of commonly used I/O
-address ranges which may be in use by other devices in your system.
-On a Linux system, "cat /proc/ioports" will also be helpful in
-identifying what I/O addresses are being used by devices on your
-system.
-
-Remember, the FIRST RocketPort uses 68 I/O addresses. So, if you set it
-for 0x100, it will occupy 0x100 to 0x143. This would mean that you
-CAN NOT set the second, third or fourth board for address 0x140 since
-the first 4 bytes of that range are used by the first board. You would
-need to set the second, third, or fourth board to one of the next available
-blocks such as 0x180.
-
-RocketPort and RocketPort RA SW1 Settings::
-
- +-------------------------------+
- | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 |
- +-------+-------+---------------+
- | Unused| Card | I/O Port Block|
- +-------------------------------+
-
- DIP Switches DIP Switches
- 7 8 6 5
- =================== ===================
- On On UNUSED, MUST BE ON. On On First Card <==== Default
- On Off Second Card
- Off On Third Card
- Off Off Fourth Card
-
- DIP Switches I/O Address Range
- 4 3 2 1 Used by the First Card
- =====================================
- On Off On Off 100-143
- On Off Off On 140-183
- On Off Off Off 180-1C3 <==== Default
- Off On On Off 200-243
- Off On Off On 240-283
- Off On Off Off 280-2C3
- Off Off On Off 300-343
- Off Off Off On 340-383
- Off Off Off Off 380-3C3
-
-Reporting Bugs
---------------
-
-For technical support, please provide the following
-information: Driver version, kernel release, distribution of
-kernel, and type of board you are using. Error messages and log
-printouts port configuration details are especially helpful.
-
-USA:
- :Phone: (612) 494-4100
- :FAX: (612) 494-4199
- :email: support@comtrol.com
-
-Comtrol Europe:
- :Phone: +44 (0) 1 869 323-220
- :FAX: +44 (0) 1 869 323-211
- :email: support@comtrol.co.uk
-
-Web: http://www.comtrol.com
-FTP: ftp.comtrol.com
diff --git a/Documentation/driver-api/serial/serial-rs485.rst b/Documentation/driver-api/serial/serial-rs485.rst
index 6bc824f948f9..dce061ef7647 100644
--- a/Documentation/driver-api/serial/serial-rs485.rst
+++ b/Documentation/driver-api/serial/serial-rs485.rst
@@ -29,19 +29,28 @@ RS485 Serial Communications
3. Data Structures Already Available in the Kernel
==================================================
- The Linux kernel provides the serial_rs485 structure (see [1]) to handle
- RS485 communications. This data structure is used to set and configure RS485
+ The Linux kernel provides the struct serial_rs485 to handle RS485
+ communications. This data structure is used to set and configure RS485
parameters in the platform data and in ioctls.
- The device tree can also provide RS485 boot time parameters (see [2]
- for bindings). The driver is in charge of filling this data structure from
- the values given by the device tree.
+ The device tree can also provide RS485 boot time parameters
+ [#DT-bindings]_. The serial core fills the struct serial_rs485 from the
+ values given by the device tree when the driver calls
+ uart_get_rs485_mode().
Any driver for devices capable of working both as RS232 and RS485 should
- implement the rs485_config callback in the uart_port structure. The
- serial_core calls rs485_config to do the device specific part in response
- to TIOCSRS485 and TIOCGRS485 ioctls (see below). The rs485_config callback
- receives a pointer to struct serial_rs485.
+ implement the ``rs485_config`` callback and provide ``rs485_supported``
+ in the ``struct uart_port``. The serial core calls ``rs485_config`` to do
+ the device specific part in response to TIOCSRS485 ioctl (see below). The
+ ``rs485_config`` callback receives a pointer to a sanitizated struct
+ serial_rs485. The struct serial_rs485 userspace provides is sanitized
+ before calling ``rs485_config`` using ``rs485_supported`` that indicates
+ what RS485 features the driver supports for the ``struct uart_port``.
+ TIOCGRS485 ioctl can be used to read back the struct serial_rs485
+ matching to the current configuration.
+
+.. kernel-doc:: include/uapi/linux/serial.h
+ :identifiers: serial_rs485 uart_get_rs485_mode
4. Usage from user-level
========================
@@ -95,9 +104,32 @@ RS485 Serial Communications
/* Error handling. See errno. */
}
-5. References
-=============
+5. Multipoint Addressing
+========================
+
+ The Linux kernel provides addressing mode for multipoint RS-485 serial
+ communications line. The addressing mode is enabled with
+ ``SER_RS485_ADDRB`` flag in struct serial_rs485. The struct serial_rs485
+ has two additional flags and fields for enabling receive and destination
+ addresses.
+
+ Address mode flags:
+ - ``SER_RS485_ADDRB``: Enabled addressing mode (sets also ADDRB in termios).
+ - ``SER_RS485_ADDR_RECV``: Receive (filter) address enabled.
+ - ``SER_RS485_ADDR_DEST``: Set destination address.
- [1] include/uapi/linux/serial.h
+ Address fields (enabled with corresponding ``SER_RS485_ADDR_*`` flag):
+ - ``addr_recv``: Receive address.
+ - ``addr_dest``: Destination address.
+
+ Once a receive address is set, the communication can occur only with the
+ particular device and other peers are filtered out. It is left up to the
+ receiver side to enforce the filtering. Receive address will be cleared
+ if ``SER_RS485_ADDR_RECV`` is not set.
+
+ Note: not all devices supporting RS485 support multipoint addressing.
+
+6. References
+=============
- [2] Documentation/devicetree/bindings/serial/rs485.txt
+.. [#DT-bindings] Documentation/devicetree/bindings/serial/rs485.txt
diff --git a/Documentation/driver-api/serial/tty.rst b/Documentation/driver-api/serial/tty.rst
deleted file mode 100644
index dd972caacf3e..000000000000
--- a/Documentation/driver-api/serial/tty.rst
+++ /dev/null
@@ -1,328 +0,0 @@
-=================
-The Lockronomicon
-=================
-
-Your guide to the ancient and twisted locking policies of the tty layer and
-the warped logic behind them. Beware all ye who read on.
-
-
-Line Discipline
----------------
-
-Line disciplines are registered with tty_register_ldisc() passing the
-discipline number and the ldisc structure. At the point of registration the
-discipline must be ready to use and it is possible it will get used before
-the call returns success. If the call returns an error then it won't get
-called. Do not re-use ldisc numbers as they are part of the userspace ABI
-and writing over an existing ldisc will cause demons to eat your computer.
-After the return the ldisc data has been copied so you may free your own
-copy of the structure. You must not re-register over the top of the line
-discipline even with the same data or your computer again will be eaten by
-demons.
-
-In order to remove a line discipline call tty_unregister_ldisc().
-In ancient times this always worked. In modern times the function will
-return -EBUSY if the ldisc is currently in use. Since the ldisc referencing
-code manages the module counts this should not usually be a concern.
-
-Heed this warning: the reference count field of the registered copies of the
-tty_ldisc structure in the ldisc table counts the number of lines using this
-discipline. The reference count of the tty_ldisc structure within a tty
-counts the number of active users of the ldisc at this instant. In effect it
-counts the number of threads of execution within an ldisc method (plus those
-about to enter and exit although this detail matters not).
-
-Line Discipline Methods
------------------------
-
-TTY side interfaces
-^^^^^^^^^^^^^^^^^^^
-
-======================= =======================================================
-open() Called when the line discipline is attached to
- the terminal. No other call into the line
- discipline for this tty will occur until it
- completes successfully. Should initialize any
- state needed by the ldisc, and set receive_room
- in the tty_struct to the maximum amount of data
- the line discipline is willing to accept from the
- driver with a single call to receive_buf().
- Returning an error will prevent the ldisc from
- being attached. Can sleep.
-
-close() This is called on a terminal when the line
- discipline is being unplugged. At the point of
- execution no further users will enter the
- ldisc code for this tty. Can sleep.
-
-hangup() Called when the tty line is hung up.
- The line discipline should cease I/O to the tty.
- No further calls into the ldisc code will occur.
- The return value is ignored. Can sleep.
-
-read() (optional) A process requests reading data from
- the line. Multiple read calls may occur in parallel
- and the ldisc must deal with serialization issues.
- If not defined, the process will receive an EIO
- error. May sleep.
-
-write() (optional) A process requests writing data to the
- line. Multiple write calls are serialized by the
- tty layer for the ldisc. If not defined, the
- process will receive an EIO error. May sleep.
-
-flush_buffer() (optional) May be called at any point between
- open and close, and instructs the line discipline
- to empty its input buffer.
-
-set_termios() (optional) Called on termios structure changes.
- The caller passes the old termios data and the
- current data is in the tty. Called under the
- termios semaphore so allowed to sleep. Serialized
- against itself only.
-
-poll() (optional) Check the status for the poll/select
- calls. Multiple poll calls may occur in parallel.
- May sleep.
-
-ioctl() (optional) Called when an ioctl is handed to the
- tty layer that might be for the ldisc. Multiple
- ioctl calls may occur in parallel. May sleep.
-
-compat_ioctl() (optional) Called when a 32 bit ioctl is handed
- to the tty layer that might be for the ldisc.
- Multiple ioctl calls may occur in parallel.
- May sleep.
-======================= =======================================================
-
-Driver Side Interfaces
-^^^^^^^^^^^^^^^^^^^^^^
-
-======================= =======================================================
-receive_buf() (optional) Called by the low-level driver to hand
- a buffer of received bytes to the ldisc for
- processing. The number of bytes is guaranteed not
- to exceed the current value of tty->receive_room.
- All bytes must be processed.
-
-receive_buf2() (optional) Called by the low-level driver to hand
- a buffer of received bytes to the ldisc for
- processing. Returns the number of bytes processed.
-
- If both receive_buf() and receive_buf2() are
- defined, receive_buf2() should be preferred.
-
-write_wakeup() May be called at any point between open and close.
- The TTY_DO_WRITE_WAKEUP flag indicates if a call
- is needed but always races versus calls. Thus the
- ldisc must be careful about setting order and to
- handle unexpected calls. Must not sleep.
-
- The driver is forbidden from calling this directly
- from the ->write call from the ldisc as the ldisc
- is permitted to call the driver write method from
- this function. In such a situation defer it.
-
-dcd_change() Report to the tty line the current DCD pin status
- changes and the relative timestamp. The timestamp
- cannot be NULL.
-======================= =======================================================
-
-
-Driver Access
-^^^^^^^^^^^^^
-
-Line discipline methods can call the following methods of the underlying
-hardware driver through the function pointers within the tty->driver
-structure:
-
-======================= =======================================================
-write() Write a block of characters to the tty device.
- Returns the number of characters accepted. The
- character buffer passed to this method is already
- in kernel space.
-
-put_char() Queues a character for writing to the tty device.
- If there is no room in the queue, the character is
- ignored.
-
-flush_chars() (Optional) If defined, must be called after
- queueing characters with put_char() in order to
- start transmission.
-
-write_room() Returns the numbers of characters the tty driver
- will accept for queueing to be written.
-
-ioctl() Invoke device specific ioctl.
- Expects data pointers to refer to userspace.
- Returns ENOIOCTLCMD for unrecognized ioctl numbers.
-
-set_termios() Notify the tty driver that the device's termios
- settings have changed. New settings are in
- tty->termios. Previous settings should be passed in
- the "old" argument.
-
- The API is defined such that the driver should return
- the actual modes selected. This means that the
- driver function is responsible for modifying any
- bits in the request it cannot fulfill to indicate
- the actual modes being used. A device with no
- hardware capability for change (e.g. a USB dongle or
- virtual port) can provide NULL for this method.
-
-throttle() Notify the tty driver that input buffers for the
- line discipline are close to full, and it should
- somehow signal that no more characters should be
- sent to the tty.
-
-unthrottle() Notify the tty driver that characters can now be
- sent to the tty without fear of overrunning the
- input buffers of the line disciplines.
-
-stop() Ask the tty driver to stop outputting characters
- to the tty device.
-
-start() Ask the tty driver to resume sending characters
- to the tty device.
-
-hangup() Ask the tty driver to hang up the tty device.
-
-break_ctl() (Optional) Ask the tty driver to turn on or off
- BREAK status on the RS-232 port. If state is -1,
- then the BREAK status should be turned on; if
- state is 0, then BREAK should be turned off.
- If this routine is not implemented, use ioctls
- TIOCSBRK / TIOCCBRK instead.
-
-wait_until_sent() Waits until the device has written out all of the
- characters in its transmitter FIFO.
-
-send_xchar() Send a high-priority XON/XOFF character to the device.
-======================= =======================================================
-
-
-Flags
-^^^^^
-
-Line discipline methods have access to tty->flags field containing the
-following interesting flags:
-
-======================= =======================================================
-TTY_THROTTLED Driver input is throttled. The ldisc should call
- tty->driver->unthrottle() in order to resume
- reception when it is ready to process more data.
-
-TTY_DO_WRITE_WAKEUP If set, causes the driver to call the ldisc's
- write_wakeup() method in order to resume
- transmission when it can accept more data
- to transmit.
-
-TTY_IO_ERROR If set, causes all subsequent userspace read/write
- calls on the tty to fail, returning -EIO.
-
-TTY_OTHER_CLOSED Device is a pty and the other side has closed.
-
-TTY_NO_WRITE_SPLIT Prevent driver from splitting up writes into
- smaller chunks.
-======================= =======================================================
-
-
-Locking
-^^^^^^^
-
-Callers to the line discipline functions from the tty layer are required to
-take line discipline locks. The same is true of calls from the driver side
-but not yet enforced.
-
-Three calls are now provided::
-
- ldisc = tty_ldisc_ref(tty);
-
-takes a handle to the line discipline in the tty and returns it. If no ldisc
-is currently attached or the ldisc is being closed and re-opened at this
-point then NULL is returned. While this handle is held the ldisc will not
-change or go away::
-
- tty_ldisc_deref(ldisc)
-
-Returns the ldisc reference and allows the ldisc to be closed. Returning the
-reference takes away your right to call the ldisc functions until you take
-a new reference::
-
- ldisc = tty_ldisc_ref_wait(tty);
-
-Performs the same function as tty_ldisc_ref except that it will wait for an
-ldisc change to complete and then return a reference to the new ldisc.
-
-While these functions are slightly slower than the old code they should have
-minimal impact as most receive logic uses the flip buffers and they only
-need to take a reference when they push bits up through the driver.
-
-A caution: The ldisc->open(), ldisc->close() and driver->set_ldisc
-functions are called with the ldisc unavailable. Thus tty_ldisc_ref will
-fail in this situation if used within these functions. Ldisc and driver
-code calling its own functions must be careful in this case.
-
-
-Driver Interface
-----------------
-
-======================= =======================================================
-open() Called when a device is opened. May sleep
-
-close() Called when a device is closed. At the point of
- return from this call the driver must make no
- further ldisc calls of any kind. May sleep
-
-write() Called to write bytes to the device. May not
- sleep. May occur in parallel in special cases.
- Because this includes panic paths drivers generally
- shouldn't try and do clever locking here.
-
-put_char() Stuff a single character onto the queue. The
- driver is guaranteed following up calls to
- flush_chars.
-
-flush_chars() Ask the kernel to write put_char queue
-
-write_room() Return the number of characters that can be stuffed
- into the port buffers without overflow (or less).
- The ldisc is responsible for being intelligent
- about multi-threading of write_room/write calls
-
-ioctl() Called when an ioctl may be for the driver
-
-set_termios() Called on termios change, serialized against
- itself by a semaphore. May sleep.
-
-set_ldisc() Notifier for discipline change. At the point this
- is done the discipline is not yet usable. Can now
- sleep (I think)
-
-throttle() Called by the ldisc to ask the driver to do flow
- control. Serialization including with unthrottle
- is the job of the ldisc layer.
-
-unthrottle() Called by the ldisc to ask the driver to stop flow
- control.
-
-stop() Ldisc notifier to the driver to stop output. As with
- throttle the serializations with start() are down
- to the ldisc layer.
-
-start() Ldisc notifier to the driver to start output.
-
-hangup() Ask the tty driver to cause a hangup initiated
- from the host side. [Can sleep ??]
-
-break_ctl() Send RS232 break. Can sleep. Can get called in
- parallel, driver must serialize (for now), and
- with write calls.
-
-wait_until_sent() Wait for characters to exit the hardware queue
- of the driver. Can sleep
-
-send_xchar() Send XON/XOFF and if possible jump the queue with
- it in order to get fast flow control responses.
- Cannot sleep ??
-======================= =======================================================
diff --git a/Documentation/driver-api/smsc_ece1099.rst b/Documentation/driver-api/smsc_ece1099.rst
deleted file mode 100644
index 079277421eaf..000000000000
--- a/Documentation/driver-api/smsc_ece1099.rst
+++ /dev/null
@@ -1,60 +0,0 @@
-=================================================
-Msc Keyboard Scan Expansion/GPIO Expansion device
-=================================================
-
-What is smsc-ece1099?
-----------------------
-
-The ECE1099 is a 40-Pin 3.3V Keyboard Scan Expansion
-or GPIO Expansion device. The device supports a keyboard
-scan matrix of 23x8. The device is connected to a Master
-via the SMSC BC-Link interface or via the SMBus.
-Keypad scan Input(KSI) and Keypad Scan Output(KSO) signals
-are multiplexed with GPIOs.
-
-Interrupt generation
---------------------
-
-Interrupts can be generated by an edge detection on a GPIO
-pin or an edge detection on one of the bus interface pins.
-Interrupts can also be detected on the keyboard scan interface.
-The bus interrupt pin (BC_INT# or SMBUS_INT#) is asserted if
-any bit in one of the Interrupt Status registers is 1 and
-the corresponding Interrupt Mask bit is also 1.
-
-In order for software to determine which device is the source
-of an interrupt, it should first read the Group Interrupt Status Register
-to determine which Status register group is a source for the interrupt.
-Software should read both the Status register and the associated Mask register,
-then AND the two values together. Bits that are 1 in the result of the AND
-are active interrupts. Software clears an interrupt by writing a 1 to the
-corresponding bit in the Status register.
-
-Communication Protocol
-----------------------
-
-- SMbus slave Interface
- The host processor communicates with the ECE1099 device
- through a series of read/write registers via the SMBus
- interface. SMBus is a serial communication protocol between
- a computer host and its peripheral devices. The SMBus data
- rate is 10KHz minimum to 400 KHz maximum
-
-- Slave Bus Interface
- The ECE1099 device SMBus implementation is a subset of the
- SMBus interface to the host. The device is a slave-only SMBus device.
- The implementation in the device is a subset of SMBus since it
- only supports four protocols.
-
- The Write Byte, Read Byte, Send Byte, and Receive Byte protocols are the
- only valid SMBus protocols for the device.
-
-- BC-LinkTM Interface
- The BC-Link is a proprietary bus that allows communication
- between a Master device and a Companion device. The Master
- device uses this serial bus to read and write registers
- located on the Companion device. The bus comprises three signals,
- BC_CLK, BC_DAT and BC_INT#. The Master device always provides the
- clock, BC_CLK, and the Companion device is the source for an
- independent asynchronous interrupt signal, BC_INT#. The ECE1099
- supports BC-Link speeds up to 24MHz.
diff --git a/Documentation/driver-api/sound.rst b/Documentation/driver-api/sound.rst
deleted file mode 100644
index afef6eabc073..000000000000
--- a/Documentation/driver-api/sound.rst
+++ /dev/null
@@ -1,54 +0,0 @@
-Sound Devices
-=============
-
-.. kernel-doc:: include/sound/core.h
- :internal:
-
-.. kernel-doc:: sound/sound_core.c
- :export:
-
-.. kernel-doc:: include/sound/pcm.h
- :internal:
-
-.. kernel-doc:: sound/core/pcm.c
- :export:
-
-.. kernel-doc:: sound/core/device.c
- :export:
-
-.. kernel-doc:: sound/core/info.c
- :export:
-
-.. kernel-doc:: sound/core/rawmidi.c
- :export:
-
-.. kernel-doc:: sound/core/sound.c
- :export:
-
-.. kernel-doc:: sound/core/memory.c
- :export:
-
-.. kernel-doc:: sound/core/pcm_memory.c
- :export:
-
-.. kernel-doc:: sound/core/init.c
- :export:
-
-.. kernel-doc:: sound/core/isadma.c
- :export:
-
-.. kernel-doc:: sound/core/control.c
- :export:
-
-.. kernel-doc:: sound/core/pcm_lib.c
- :export:
-
-.. kernel-doc:: sound/core/hwdep.c
- :export:
-
-.. kernel-doc:: sound/core/pcm_native.c
- :export:
-
-.. kernel-doc:: sound/core/memalloc.c
- :export:
-
diff --git a/Documentation/driver-api/soundwire/stream.rst b/Documentation/driver-api/soundwire/stream.rst
index 8bceece51554..b432a2de45d3 100644
--- a/Documentation/driver-api/soundwire/stream.rst
+++ b/Documentation/driver-api/soundwire/stream.rst
@@ -75,8 +75,33 @@ Slaves are using single port. ::
| (Data) |
+---------------+
+Example 4: Stereo Stream with L and R channels is rendered by
+Master. Both of the L and R channels are received by two different
+Slaves. Master and both Slaves are using single port handling
+L+R. Each Slave device processes the L + R data locally, typically
+based on static configuration or dynamic orientation, and may drive
+one or more speakers. ::
-Example 4: Stereo Stream with L and R channel is rendered by two different
+ +---------------+ Clock Signal +---------------+
+ | Master +---------+------------------------+ Slave |
+ | Interface | | | Interface |
+ | | | | 1 |
+ | | | Data Signal | |
+ | L + R +---+------------------------------+ L + R |
+ | (Data) | | | Data Direction | (Data) |
+ +---------------+ | | +-------------> +---------------+
+ | |
+ | |
+ | | +---------------+
+ | +----------------------> | Slave |
+ | | Interface |
+ | | 2 |
+ | | |
+ +----------------------------> | L + R |
+ | (Data) |
+ +---------------+
+
+Example 5: Stereo Stream with L and R channel is rendered by two different
Ports of the Master and is received by only single Port of the Slave
interface. ::
@@ -101,7 +126,7 @@ interface. ::
+--------------------+ | |
+----------------+
-Example 5: Stereo Stream with L and R channel is rendered by 2 Masters, each
+Example 6: Stereo Stream with L and R channel is rendered by 2 Masters, each
rendering one channel, and is received by two different Slaves, each
receiving one channel. Both Masters and both Slaves are using single port. ::
@@ -123,12 +148,70 @@ receiving one channel. Both Masters and both Slaves are using single port. ::
| (Data) | Data Direction | (Data) |
+---------------+ +-----------------------> +---------------+
-Note: In multi-link cases like above, to lock, one would acquire a global
+Example 7: Stereo Stream with L and R channel is rendered by 2
+Masters, each rendering both channels. Each Slave receives L + R. This
+is the same application as Example 4 but with Slaves placed on
+separate links. ::
+
+ +---------------+ Clock Signal +---------------+
+ | Master +----------------------------------+ Slave |
+ | Interface | | Interface |
+ | 1 | | 1 |
+ | | Data Signal | |
+ | L + R +----------------------------------+ L + R |
+ | (Data) | Data Direction | (Data) |
+ +---------------+ +-----------------------> +---------------+
+
+ +---------------+ Clock Signal +---------------+
+ | Master +----------------------------------+ Slave |
+ | Interface | | Interface |
+ | 2 | | 2 |
+ | | Data Signal | |
+ | L + R +----------------------------------+ L + R |
+ | (Data) | Data Direction | (Data) |
+ +---------------+ +-----------------------> +---------------+
+
+Example 8: 4-channel Stream is rendered by 2 Masters, each rendering a
+2 channels. Each Slave receives 2 channels. ::
+
+ +---------------+ Clock Signal +---------------+
+ | Master +----------------------------------+ Slave |
+ | Interface | | Interface |
+ | 1 | | 1 |
+ | | Data Signal | |
+ | L1 + R1 +----------------------------------+ L1 + R1 |
+ | (Data) | Data Direction | (Data) |
+ +---------------+ +-----------------------> +---------------+
+
+ +---------------+ Clock Signal +---------------+
+ | Master +----------------------------------+ Slave |
+ | Interface | | Interface |
+ | 2 | | 2 |
+ | | Data Signal | |
+ | L2 + R2 +----------------------------------+ L2 + R2 |
+ | (Data) | Data Direction | (Data) |
+ +---------------+ +-----------------------> +---------------+
+
+Note1: In multi-link cases like above, to lock, one would acquire a global
lock and then go on locking bus instances. But, in this case the caller
framework(ASoC DPCM) guarantees that stream operations on a card are
always serialized. So, there is no race condition and hence no need for
global lock.
+Note2: A Slave device may be configured to receive all channels
+transmitted on a link for a given Stream (Example 4) or just a subset
+of the data (Example 3). The configuration of the Slave device is not
+handled by a SoundWire subsystem API, but instead by the
+snd_soc_dai_set_tdm_slot() API. The platform or machine driver will
+typically configure which of the slots are used. For Example 4, the
+same slots would be used by all Devices, while for Example 3 the Slave
+Device1 would use e.g. Slot 0 and Slave device2 slot 1.
+
+Note3: Multiple Sink ports can extract the same information for the
+same bitSlots in the SoundWire frame, however multiple Source ports
+shall be configured with different bitSlot configurations. This is the
+same limitation as with I2S/PCM TDM usages.
+
SoundWire Stream Management flow
================================
@@ -210,6 +293,10 @@ per stream. From ASoC DPCM framework, this stream state maybe linked to
int sdw_alloc_stream(char * stream_name);
+The SoundWire core provides a sdw_startup_stream() helper function,
+typically called during a dailink .startup() callback, which performs
+stream allocation and sets the stream pointer for all DAIs
+connected to a stream.
SDW_STREAM_CONFIGURED
~~~~~~~~~~~~~~~~~~~~~
@@ -426,10 +513,15 @@ In .shutdown() the data structure maintaining stream state are freed up.
void sdw_release_stream(struct sdw_stream_runtime * stream);
+The SoundWire core provides a sdw_shutdown_stream() helper function,
+typically called during a dailink .shutdown() callback, which clears
+the stream pointer for all DAIS connected to a stream and releases the
+memory allocated for the stream.
+
Not Supported
=============
1. A single port with multiple channels supported cannot be used between two
-streams or across stream. For example a port with 4 channels cannot be used
-to handle 2 independent stereo streams even though it's possible in theory
-in SoundWire.
+ streams or across stream. For example a port with 4 channels cannot be used
+ to handle 2 independent stereo streams even though it's possible in theory
+ in SoundWire.
diff --git a/Documentation/driver-api/soundwire/summary.rst b/Documentation/driver-api/soundwire/summary.rst
index 8193125a2bfb..01dcb954f6d7 100644
--- a/Documentation/driver-api/soundwire/summary.rst
+++ b/Documentation/driver-api/soundwire/summary.rst
@@ -101,10 +101,11 @@ Following is the Bus API to register the SoundWire Bus:
.. code-block:: c
- int sdw_add_bus_master(struct sdw_bus *bus)
+ int sdw_bus_master_add(struct sdw_bus *bus,
+ struct device *parent,
+ struct fwnode_handle)
{
- if (!bus->dev)
- return -ENODEV;
+ sdw_master_device_add(bus, parent, fwnode);
mutex_init(&bus->lock);
INIT_LIST_HEAD(&bus->slaves);
diff --git a/Documentation/driver-api/spi.rst b/Documentation/driver-api/spi.rst
index f64cb666498a..f28887045049 100644
--- a/Documentation/driver-api/spi.rst
+++ b/Documentation/driver-api/spi.rst
@@ -25,8 +25,8 @@ hardware, which may be as simple as a set of GPIO pins or as complex as
a pair of FIFOs connected to dual DMA engines on the other side of the
SPI shift register (maximizing throughput). Such drivers bridge between
whatever bus they sit on (often the platform bus) and SPI, and expose
-the SPI side of their device as a :c:type:`struct spi_master
-<spi_master>`. SPI devices are children of that master,
+the SPI side of their device as a :c:type:`struct spi_controller
+<spi_controller>`. SPI devices are children of that master,
represented as a :c:type:`struct spi_device <spi_device>` and
manufactured from :c:type:`struct spi_board_info
<spi_board_info>` descriptors which are usually provided by
diff --git a/Documentation/driver-api/surface_aggregator/client-api.rst b/Documentation/driver-api/surface_aggregator/client-api.rst
new file mode 100644
index 000000000000..8e0b000d0e64
--- /dev/null
+++ b/Documentation/driver-api/surface_aggregator/client-api.rst
@@ -0,0 +1,38 @@
+.. SPDX-License-Identifier: GPL-2.0+
+
+===============================
+Client Driver API Documentation
+===============================
+
+.. contents::
+ :depth: 2
+
+
+Serial Hub Communication
+========================
+
+.. kernel-doc:: include/linux/surface_aggregator/serial_hub.h
+
+.. kernel-doc:: drivers/platform/surface/aggregator/ssh_packet_layer.c
+ :export:
+
+
+Controller and Core Interface
+=============================
+
+.. kernel-doc:: include/linux/surface_aggregator/controller.h
+
+.. kernel-doc:: drivers/platform/surface/aggregator/controller.c
+ :export:
+
+.. kernel-doc:: drivers/platform/surface/aggregator/core.c
+ :export:
+
+
+Client Bus and Client Device API
+================================
+
+.. kernel-doc:: include/linux/surface_aggregator/device.h
+
+.. kernel-doc:: drivers/platform/surface/aggregator/bus.c
+ :export:
diff --git a/Documentation/driver-api/surface_aggregator/client.rst b/Documentation/driver-api/surface_aggregator/client.rst
new file mode 100644
index 000000000000..e100ab0a24cc
--- /dev/null
+++ b/Documentation/driver-api/surface_aggregator/client.rst
@@ -0,0 +1,397 @@
+.. SPDX-License-Identifier: GPL-2.0+
+
+.. |ssam_controller| replace:: :c:type:`struct ssam_controller <ssam_controller>`
+.. |ssam_device| replace:: :c:type:`struct ssam_device <ssam_device>`
+.. |ssam_device_driver| replace:: :c:type:`struct ssam_device_driver <ssam_device_driver>`
+.. |ssam_client_bind| replace:: :c:func:`ssam_client_bind`
+.. |ssam_client_link| replace:: :c:func:`ssam_client_link`
+.. |ssam_get_controller| replace:: :c:func:`ssam_get_controller`
+.. |ssam_controller_get| replace:: :c:func:`ssam_controller_get`
+.. |ssam_controller_put| replace:: :c:func:`ssam_controller_put`
+.. |ssam_device_alloc| replace:: :c:func:`ssam_device_alloc`
+.. |ssam_device_add| replace:: :c:func:`ssam_device_add`
+.. |ssam_device_remove| replace:: :c:func:`ssam_device_remove`
+.. |ssam_device_driver_register| replace:: :c:func:`ssam_device_driver_register`
+.. |ssam_device_driver_unregister| replace:: :c:func:`ssam_device_driver_unregister`
+.. |module_ssam_device_driver| replace:: :c:func:`module_ssam_device_driver`
+.. |SSAM_DEVICE| replace:: :c:func:`SSAM_DEVICE`
+.. |ssam_notifier_register| replace:: :c:func:`ssam_notifier_register`
+.. |ssam_notifier_unregister| replace:: :c:func:`ssam_notifier_unregister`
+.. |ssam_device_notifier_register| replace:: :c:func:`ssam_device_notifier_register`
+.. |ssam_device_notifier_unregister| replace:: :c:func:`ssam_device_notifier_unregister`
+.. |ssam_request_do_sync| replace:: :c:func:`ssam_request_do_sync`
+.. |ssam_event_mask| replace:: :c:type:`enum ssam_event_mask <ssam_event_mask>`
+
+
+======================
+Writing Client Drivers
+======================
+
+For the API documentation, refer to:
+
+.. toctree::
+ :maxdepth: 2
+
+ client-api
+
+
+Overview
+========
+
+Client drivers can be set up in two main ways, depending on how the
+corresponding device is made available to the system. We specifically
+differentiate between devices that are presented to the system via one of
+the conventional ways, e.g. as platform devices via ACPI, and devices that
+are non-discoverable and instead need to be explicitly provided by some
+other mechanism, as discussed further below.
+
+
+Non-SSAM Client Drivers
+=======================
+
+All communication with the SAM EC is handled via the |ssam_controller|
+representing that EC to the kernel. Drivers targeting a non-SSAM device (and
+thus not being a |ssam_device_driver|) need to explicitly establish a
+connection/relation to that controller. This can be done via the
+|ssam_client_bind| function. Said function returns a reference to the SSAM
+controller, but, more importantly, also establishes a device link between
+client device and controller (this can also be done separate via
+|ssam_client_link|). It is important to do this, as it, first, guarantees
+that the returned controller is valid for use in the client driver for as
+long as this driver is bound to its device, i.e. that the driver gets
+unbound before the controller ever becomes invalid, and, second, as it
+ensures correct suspend/resume ordering. This setup should be done in the
+driver's probe function, and may be used to defer probing in case the SSAM
+subsystem is not ready yet, for example:
+
+.. code-block:: c
+
+ static int client_driver_probe(struct platform_device *pdev)
+ {
+ struct ssam_controller *ctrl;
+
+ ctrl = ssam_client_bind(&pdev->dev);
+ if (IS_ERR(ctrl))
+ return PTR_ERR(ctrl) == -ENODEV ? -EPROBE_DEFER : PTR_ERR(ctrl);
+
+ // ...
+
+ return 0;
+ }
+
+The controller may be separately obtained via |ssam_get_controller| and its
+lifetime be guaranteed via |ssam_controller_get| and |ssam_controller_put|.
+Note that none of these functions, however, guarantee that the controller
+will not be shut down or suspended. These functions essentially only operate
+on the reference, i.e. only guarantee a bare minimum of accessibility
+without any guarantees at all on practical operability.
+
+
+Adding SSAM Devices
+===================
+
+If a device does not already exist/is not already provided via conventional
+means, it should be provided as |ssam_device| via the SSAM client device
+hub. New devices can be added to this hub by entering their UID into the
+corresponding registry. SSAM devices can also be manually allocated via
+|ssam_device_alloc|, subsequently to which they have to be added via
+|ssam_device_add| and eventually removed via |ssam_device_remove|. By
+default, the parent of the device is set to the controller device provided
+for allocation, however this may be changed before the device is added. Note
+that, when changing the parent device, care must be taken to ensure that the
+controller lifetime and suspend/resume ordering guarantees, in the default
+setup provided through the parent-child relation, are preserved. If
+necessary, by use of |ssam_client_link| as is done for non-SSAM client
+drivers and described in more detail above.
+
+A client device must always be removed by the party which added the
+respective device before the controller shuts down. Such removal can be
+guaranteed by linking the driver providing the SSAM device to the controller
+via |ssam_client_link|, causing it to unbind before the controller driver
+unbinds. Client devices registered with the controller as parent are
+automatically removed when the controller shuts down, but this should not be
+relied upon, especially as this does not extend to client devices with a
+different parent.
+
+
+SSAM Client Drivers
+===================
+
+SSAM client device drivers are, in essence, no different than other device
+driver types. They are represented via |ssam_device_driver| and bind to a
+|ssam_device| via its UID (:c:type:`struct ssam_device.uid <ssam_device>`)
+member and the match table
+(:c:type:`struct ssam_device_driver.match_table <ssam_device_driver>`),
+which should be set when declaring the driver struct instance. Refer to the
+|SSAM_DEVICE| macro documentation for more details on how to define members
+of the driver's match table.
+
+The UID for SSAM client devices consists of a ``domain``, a ``category``,
+a ``target``, an ``instance``, and a ``function``. The ``domain`` is used
+differentiate between physical SAM devices
+(:c:type:`SSAM_DOMAIN_SERIALHUB <ssam_device_domain>`), i.e. devices that can
+be accessed via the Surface Serial Hub, and virtual ones
+(:c:type:`SSAM_DOMAIN_VIRTUAL <ssam_device_domain>`), such as client-device
+hubs, that have no real representation on the SAM EC and are solely used on
+the kernel/driver-side. For physical devices, ``category`` represents the
+target category, ``target`` the target ID, and ``instance`` the instance ID
+used to access the physical SAM device. In addition, ``function`` references
+a specific device functionality, but has no meaning to the SAM EC. The
+(default) name of a client device is generated based on its UID.
+
+A driver instance can be registered via |ssam_device_driver_register| and
+unregistered via |ssam_device_driver_unregister|. For convenience, the
+|module_ssam_device_driver| macro may be used to define module init- and
+exit-functions registering the driver.
+
+The controller associated with a SSAM client device can be found in its
+:c:type:`struct ssam_device.ctrl <ssam_device>` member. This reference is
+guaranteed to be valid for at least as long as the client driver is bound,
+but should also be valid for as long as the client device exists. Note,
+however, that access outside of the bound client driver must ensure that the
+controller device is not suspended while making any requests or
+(un-)registering event notifiers (and thus should generally be avoided). This
+is guaranteed when the controller is accessed from inside the bound client
+driver.
+
+
+Making Synchronous Requests
+===========================
+
+Synchronous requests are (currently) the main form of host-initiated
+communication with the EC. There are a couple of ways to define and execute
+such requests, however, most of them boil down to something similar as shown
+in the example below. This example defines a write-read request, meaning
+that the caller provides an argument to the SAM EC and receives a response.
+The caller needs to know the (maximum) length of the response payload and
+provide a buffer for it.
+
+Care must be taken to ensure that any command payload data passed to the SAM
+EC is provided in little-endian format and, similarly, any response payload
+data received from it is converted from little-endian to host endianness.
+
+.. code-block:: c
+
+ int perform_request(struct ssam_controller *ctrl, u32 arg, u32 *ret)
+ {
+ struct ssam_request rqst;
+ struct ssam_response resp;
+ int status;
+
+ /* Convert request argument to little-endian. */
+ __le32 arg_le = cpu_to_le32(arg);
+ __le32 ret_le = cpu_to_le32(0);
+
+ /*
+ * Initialize request specification. Replace this with your values.
+ * The rqst.payload field may be NULL if rqst.length is zero,
+ * indicating that the request does not have any argument.
+ *
+ * Note: The request parameters used here are not valid, i.e.
+ * they do not correspond to an actual SAM/EC request.
+ */
+ rqst.target_category = SSAM_SSH_TC_SAM;
+ rqst.target_id = SSAM_SSH_TID_SAM;
+ rqst.command_id = 0x02;
+ rqst.instance_id = 0x03;
+ rqst.flags = SSAM_REQUEST_HAS_RESPONSE;
+ rqst.length = sizeof(arg_le);
+ rqst.payload = (u8 *)&arg_le;
+
+ /* Initialize request response. */
+ resp.capacity = sizeof(ret_le);
+ resp.length = 0;
+ resp.pointer = (u8 *)&ret_le;
+
+ /*
+ * Perform actual request. The response pointer may be null in case
+ * the request does not have any response. This must be consistent
+ * with the SSAM_REQUEST_HAS_RESPONSE flag set in the specification
+ * above.
+ */
+ status = ssam_request_do_sync(ctrl, &rqst, &resp);
+
+ /*
+ * Alternatively use
+ *
+ * ssam_request_do_sync_onstack(ctrl, &rqst, &resp, sizeof(arg_le));
+ *
+ * to perform the request, allocating the message buffer directly
+ * on the stack as opposed to allocation via kzalloc().
+ */
+
+ /*
+ * Convert request response back to native format. Note that in the
+ * error case, this value is not touched by the SSAM core, i.e.
+ * 'ret_le' will be zero as specified in its initialization.
+ */
+ *ret = le32_to_cpu(ret_le);
+
+ return status;
+ }
+
+Note that |ssam_request_do_sync| in its essence is a wrapper over lower-level
+request primitives, which may also be used to perform requests. Refer to its
+implementation and documentation for more details.
+
+An arguably more user-friendly way of defining such functions is by using
+one of the generator macros, for example via:
+
+.. code-block:: c
+
+ SSAM_DEFINE_SYNC_REQUEST_W(__ssam_tmp_perf_mode_set, __le32, {
+ .target_category = SSAM_SSH_TC_TMP,
+ .target_id = SSAM_SSH_TID_SAM,
+ .command_id = 0x03,
+ .instance_id = 0x00,
+ });
+
+This example defines a function
+
+.. code-block:: c
+
+ static int __ssam_tmp_perf_mode_set(struct ssam_controller *ctrl, const __le32 *arg);
+
+executing the specified request, with the controller passed in when calling
+said function. In this example, the argument is provided via the ``arg``
+pointer. Note that the generated function allocates the message buffer on
+the stack. Thus, if the argument provided via the request is large, these
+kinds of macros should be avoided. Also note that, in contrast to the
+previous non-macro example, this function does not do any endianness
+conversion, which has to be handled by the caller. Apart from those
+differences the function generated by the macro is similar to the one
+provided in the non-macro example above.
+
+The full list of such function-generating macros is
+
+- :c:func:`SSAM_DEFINE_SYNC_REQUEST_N` for requests without return value and
+ without argument.
+- :c:func:`SSAM_DEFINE_SYNC_REQUEST_R` for requests with return value but no
+ argument.
+- :c:func:`SSAM_DEFINE_SYNC_REQUEST_W` for requests without return value but
+ with argument.
+
+Refer to their respective documentation for more details. For each one of
+these macros, a special variant is provided, which targets request types
+applicable to multiple instances of the same device type:
+
+- :c:func:`SSAM_DEFINE_SYNC_REQUEST_MD_N`
+- :c:func:`SSAM_DEFINE_SYNC_REQUEST_MD_R`
+- :c:func:`SSAM_DEFINE_SYNC_REQUEST_MD_W`
+
+The difference of those macros to the previously mentioned versions is, that
+the device target and instance IDs are not fixed for the generated function,
+but instead have to be provided by the caller of said function.
+
+Additionally, variants for direct use with client devices, i.e.
+|ssam_device|, are also provided. These can, for example, be used as
+follows:
+
+.. code-block:: c
+
+ SSAM_DEFINE_SYNC_REQUEST_CL_R(ssam_bat_get_sta, __le32, {
+ .target_category = SSAM_SSH_TC_BAT,
+ .command_id = 0x01,
+ });
+
+This invocation of the macro defines a function
+
+.. code-block:: c
+
+ static int ssam_bat_get_sta(struct ssam_device *sdev, __le32 *ret);
+
+executing the specified request, using the device IDs and controller given
+in the client device. The full list of such macros for client devices is:
+
+- :c:func:`SSAM_DEFINE_SYNC_REQUEST_CL_N`
+- :c:func:`SSAM_DEFINE_SYNC_REQUEST_CL_R`
+- :c:func:`SSAM_DEFINE_SYNC_REQUEST_CL_W`
+
+
+Handling Events
+===============
+
+To receive events from the SAM EC, an event notifier must be registered for
+the desired event via |ssam_notifier_register|. The notifier must be
+unregistered via |ssam_notifier_unregister| once it is not required any
+more. For |ssam_device| type clients, the |ssam_device_notifier_register| and
+|ssam_device_notifier_unregister| wrappers should be preferred as they properly
+handle hot-removal of client devices.
+
+Event notifiers are registered by providing (at minimum) a callback to call
+in case an event has been received, the registry specifying how the event
+should be enabled, an event ID specifying for which target category and,
+optionally and depending on the registry used, for which instance ID events
+should be enabled, and finally, flags describing how the EC will send these
+events. If the specific registry does not enable events by instance ID, the
+instance ID must be set to zero. Additionally, a priority for the respective
+notifier may be specified, which determines its order in relation to any
+other notifier registered for the same target category.
+
+By default, event notifiers will receive all events for the specific target
+category, regardless of the instance ID specified when registering the
+notifier. The core may be instructed to only call a notifier if the target
+ID or instance ID (or both) of the event match the ones implied by the
+notifier IDs (in case of target ID, the target ID of the registry), by
+providing an event mask (see |ssam_event_mask|).
+
+In general, the target ID of the registry is also the target ID of the
+enabled event (with the notable exception being keyboard input events on the
+Surface Laptop 1 and 2, which are enabled via a registry with target ID 1,
+but provide events with target ID 2).
+
+A full example for registering an event notifier and handling received
+events is provided below:
+
+.. code-block:: c
+
+ u32 notifier_callback(struct ssam_event_notifier *nf,
+ const struct ssam_event *event)
+ {
+ int status = ...
+
+ /* Handle the event here ... */
+
+ /* Convert return value and indicate that we handled the event. */
+ return ssam_notifier_from_errno(status) | SSAM_NOTIF_HANDLED;
+ }
+
+ int setup_notifier(struct ssam_device *sdev,
+ struct ssam_event_notifier *nf)
+ {
+ /* Set priority wrt. other handlers of same target category. */
+ nf->base.priority = 1;
+
+ /* Set event/notifier callback. */
+ nf->base.fn = notifier_callback;
+
+ /* Specify event registry, i.e. how events get enabled/disabled. */
+ nf->event.reg = SSAM_EVENT_REGISTRY_KIP;
+
+ /* Specify which event to enable/disable */
+ nf->event.id.target_category = sdev->uid.category;
+ nf->event.id.instance = sdev->uid.instance;
+
+ /*
+ * Specify for which events the notifier callback gets executed.
+ * This essentially tells the core if it can skip notifiers that
+ * don't have target or instance IDs matching those of the event.
+ */
+ nf->event.mask = SSAM_EVENT_MASK_STRICT;
+
+ /* Specify event flags. */
+ nf->event.flags = SSAM_EVENT_SEQUENCED;
+
+ return ssam_notifier_register(sdev->ctrl, nf);
+ }
+
+Multiple event notifiers can be registered for the same event. The event
+handler core takes care of enabling and disabling events when notifiers are
+registered and unregistered, by keeping track of how many notifiers for a
+specific event (combination of registry, event target category, and event
+instance ID) are currently registered. This means that a specific event will
+be enabled when the first notifier for it is being registered and disabled
+when the last notifier for it is being unregistered. Note that the event
+flags are therefore only used on the first registered notifier, however, one
+should take care that notifiers for a specific event are always registered
+with the same flag and it is considered a bug to do otherwise.
diff --git a/Documentation/driver-api/surface_aggregator/clients/cdev.rst b/Documentation/driver-api/surface_aggregator/clients/cdev.rst
new file mode 100644
index 000000000000..0134a841a079
--- /dev/null
+++ b/Documentation/driver-api/surface_aggregator/clients/cdev.rst
@@ -0,0 +1,204 @@
+.. SPDX-License-Identifier: GPL-2.0+
+
+.. |ssam_cdev_request| replace:: :c:type:`struct ssam_cdev_request <ssam_cdev_request>`
+.. |ssam_cdev_request_flags| replace:: :c:type:`enum ssam_cdev_request_flags <ssam_cdev_request_flags>`
+.. |ssam_cdev_event| replace:: :c:type:`struct ssam_cdev_event <ssam_cdev_event>`
+
+==============================
+User-Space EC Interface (cdev)
+==============================
+
+The ``surface_aggregator_cdev`` module provides a misc-device for the SSAM
+controller to allow for a (more or less) direct connection from user-space to
+the SAM EC. It is intended to be used for development and debugging, and
+therefore should not be used or relied upon in any other way. Note that this
+module is not loaded automatically, but instead must be loaded manually.
+
+The provided interface is accessible through the ``/dev/surface/aggregator``
+device-file. All functionality of this interface is provided via IOCTLs.
+These IOCTLs and their respective input/output parameter structs are defined in
+``include/uapi/linux/surface_aggregator/cdev.h``.
+
+A small python library and scripts for accessing this interface can be found
+at https://github.com/linux-surface/surface-aggregator-module/tree/master/scripts/ssam.
+
+.. contents::
+
+
+Receiving Events
+================
+
+Events can be received by reading from the device-file. The are represented by
+the |ssam_cdev_event| datatype.
+
+Before events are available to be read, however, the desired notifiers must be
+registered via the ``SSAM_CDEV_NOTIF_REGISTER`` IOCTL. Notifiers are, in
+essence, callbacks, called when the EC sends an event. They are, in this
+interface, associated with a specific target category and device-file-instance.
+They forward any event of this category to the buffer of the corresponding
+instance, from which it can then be read.
+
+Notifiers themselves do not enable events on the EC. Thus, it may additionally
+be necessary to enable events via the ``SSAM_CDEV_EVENT_ENABLE`` IOCTL. While
+notifiers work per-client (i.e. per-device-file-instance), events are enabled
+globally, for the EC and all of its clients (regardless of userspace or
+non-userspace). The ``SSAM_CDEV_EVENT_ENABLE`` and ``SSAM_CDEV_EVENT_DISABLE``
+IOCTLs take care of reference counting the events, such that an event is
+enabled as long as there is a client that has requested it.
+
+Note that enabled events are not automatically disabled once the client
+instance is closed. Therefore any client process (or group of processes) should
+balance their event enable calls with the corresponding event disable calls. It
+is, however, perfectly valid to enable and disable events on different client
+instances. For example, it is valid to set up notifiers and read events on
+client instance ``A``, enable those events on instance ``B`` (note that these
+will also be received by A since events are enabled/disabled globally), and
+after no more events are desired, disable the previously enabled events via
+instance ``C``.
+
+
+Controller IOCTLs
+=================
+
+The following IOCTLs are provided:
+
+.. flat-table:: Controller IOCTLs
+ :widths: 1 1 1 1 4
+ :header-rows: 1
+
+ * - Type
+ - Number
+ - Direction
+ - Name
+ - Description
+
+ * - ``0xA5``
+ - ``1``
+ - ``WR``
+ - ``REQUEST``
+ - Perform synchronous SAM request.
+
+ * - ``0xA5``
+ - ``2``
+ - ``W``
+ - ``NOTIF_REGISTER``
+ - Register event notifier.
+
+ * - ``0xA5``
+ - ``3``
+ - ``W``
+ - ``NOTIF_UNREGISTER``
+ - Unregister event notifier.
+
+ * - ``0xA5``
+ - ``4``
+ - ``W``
+ - ``EVENT_ENABLE``
+ - Enable event source.
+
+ * - ``0xA5``
+ - ``5``
+ - ``W``
+ - ``EVENT_DISABLE``
+ - Disable event source.
+
+
+``SSAM_CDEV_REQUEST``
+---------------------
+
+Defined as ``_IOWR(0xA5, 1, struct ssam_cdev_request)``.
+
+Executes a synchronous SAM request. The request specification is passed in
+as argument of type |ssam_cdev_request|, which is then written to/modified
+by the IOCTL to return status and result of the request.
+
+Request payload data must be allocated separately and is passed in via the
+``payload.data`` and ``payload.length`` members. If a response is required,
+the response buffer must be allocated by the caller and passed in via the
+``response.data`` member. The ``response.length`` member must be set to the
+capacity of this buffer, or if no response is required, zero. Upon
+completion of the request, the call will write the response to the response
+buffer (if its capacity allows it) and overwrite the length field with the
+actual size of the response, in bytes.
+
+Additionally, if the request has a response, this must be indicated via the
+request flags, as is done with in-kernel requests. Request flags can be set
+via the ``flags`` member and the values correspond to the values found in
+|ssam_cdev_request_flags|.
+
+Finally, the status of the request itself is returned in the ``status``
+member (a negative errno value indicating failure). Note that failure
+indication of the IOCTL is separated from failure indication of the request:
+The IOCTL returns a negative status code if anything failed during setup of
+the request (``-EFAULT``) or if the provided argument or any of its fields
+are invalid (``-EINVAL``). In this case, the status value of the request
+argument may be set, providing more detail on what went wrong (e.g.
+``-ENOMEM`` for out-of-memory), but this value may also be zero. The IOCTL
+will return with a zero status code in case the request has been set up,
+submitted, and completed (i.e. handed back to user-space) successfully from
+inside the IOCTL, but the request ``status`` member may still be negative in
+case the actual execution of the request failed after it has been submitted.
+
+A full definition of the argument struct is provided below.
+
+``SSAM_CDEV_NOTIF_REGISTER``
+----------------------------
+
+Defined as ``_IOW(0xA5, 2, struct ssam_cdev_notifier_desc)``.
+
+Register a notifier for the event target category specified in the given
+notifier description with the specified priority. Notifiers registration is
+required to receive events, but does not enable events themselves. After a
+notifier for a specific target category has been registered, all events of that
+category will be forwarded to the userspace client and can then be read from
+the device file instance. Note that events may have to be enabled, e.g. via the
+``SSAM_CDEV_EVENT_ENABLE`` IOCTL, before the EC will send them.
+
+Only one notifier can be registered per target category and client instance. If
+a notifier has already been registered, this IOCTL will fail with ``-EEXIST``.
+
+Notifiers will automatically be removed when the device file instance is
+closed.
+
+``SSAM_CDEV_NOTIF_UNREGISTER``
+------------------------------
+
+Defined as ``_IOW(0xA5, 3, struct ssam_cdev_notifier_desc)``.
+
+Unregisters the notifier associated with the specified target category. The
+priority field will be ignored by this IOCTL. If no notifier has been
+registered for this client instance and the given category, this IOCTL will
+fail with ``-ENOENT``.
+
+``SSAM_CDEV_EVENT_ENABLE``
+--------------------------
+
+Defined as ``_IOW(0xA5, 4, struct ssam_cdev_event_desc)``.
+
+Enable the event associated with the given event descriptor.
+
+Note that this call will not register a notifier itself, it will only enable
+events on the controller. If you want to receive events by reading from the
+device file, you will need to register the corresponding notifier(s) on that
+instance.
+
+Events are not automatically disabled when the device file is closed. This must
+be done manually, via a call to the ``SSAM_CDEV_EVENT_DISABLE`` IOCTL.
+
+``SSAM_CDEV_EVENT_DISABLE``
+---------------------------
+
+Defined as ``_IOW(0xA5, 5, struct ssam_cdev_event_desc)``.
+
+Disable the event associated with the given event descriptor.
+
+Note that this will not unregister any notifiers. Events may still be received
+and forwarded to user-space after this call. The only safe way of stopping
+events from being received is unregistering all previously registered
+notifiers.
+
+
+Structures and Enums
+====================
+
+.. kernel-doc:: include/uapi/linux/surface_aggregator/cdev.h
diff --git a/Documentation/driver-api/surface_aggregator/clients/dtx.rst b/Documentation/driver-api/surface_aggregator/clients/dtx.rst
new file mode 100644
index 000000000000..e7e7c20007f0
--- /dev/null
+++ b/Documentation/driver-api/surface_aggregator/clients/dtx.rst
@@ -0,0 +1,718 @@
+.. SPDX-License-Identifier: GPL-2.0+
+
+.. |__u16| replace:: :c:type:`__u16 <__u16>`
+.. |sdtx_event| replace:: :c:type:`struct sdtx_event <sdtx_event>`
+.. |sdtx_event_code| replace:: :c:type:`enum sdtx_event_code <sdtx_event_code>`
+.. |sdtx_base_info| replace:: :c:type:`struct sdtx_base_info <sdtx_base_info>`
+.. |sdtx_device_mode| replace:: :c:type:`struct sdtx_device_mode <sdtx_device_mode>`
+
+======================================================
+User-Space DTX (Clipboard Detachment System) Interface
+======================================================
+
+The ``surface_dtx`` driver is responsible for proper clipboard detachment
+and re-attachment handling. To this end, it provides the ``/dev/surface/dtx``
+device file, through which it can interface with a user-space daemon. This
+daemon is then ultimately responsible for determining and taking necessary
+actions, such as unmounting devices attached to the base,
+unloading/reloading the graphics-driver, user-notifications, etc.
+
+There are two basic communication principles used in this driver: Commands
+(in other parts of the documentation also referred to as requests) and
+events. Commands are sent to the EC and may have a different implications in
+different contexts. Events are sent by the EC upon some internal state
+change. Commands are always driver-initiated, whereas events are always
+initiated by the EC.
+
+.. contents::
+
+Nomenclature
+============
+
+* **Clipboard:**
+ The detachable upper part of the Surface Book, housing the screen and CPU.
+
+* **Base:**
+ The lower part of the Surface Book from which the clipboard can be
+ detached, optionally (model dependent) housing the discrete GPU (dGPU).
+
+* **Latch:**
+ The mechanism keeping the clipboard attached to the base in normal
+ operation and allowing it to be detached when requested.
+
+* **Silently ignored commands:**
+ The command is accepted by the EC as a valid command and acknowledged
+ (following the standard communication protocol), but the EC does not act
+ upon it, i.e. ignores it.e upper part of the
+
+
+Detachment Process
+==================
+
+Warning: This part of the documentation is based on reverse engineering and
+testing and thus may contain errors or be incomplete.
+
+Latch States
+------------
+
+The latch mechanism has two major states: *open* and *closed*. In the
+*closed* state (default), the clipboard is secured to the base, whereas in
+the *open* state, the clipboard can be removed by a user.
+
+The latch can additionally be locked and, correspondingly, unlocked, which
+can influence the detachment procedure. Specifically, this locking mechanism
+is intended to prevent the dGPU, positioned in the base of the device, from
+being hot-unplugged while in use. More details can be found in the
+documentation for the detachment procedure below. By default, the latch is
+unlocked.
+
+Detachment Procedure
+--------------------
+
+Note that the detachment process is governed fully by the EC. The
+``surface_dtx`` driver only relays events from the EC to user-space and
+commands from user-space to the EC, i.e. it does not influence this process.
+
+The detachment process is started with the user pressing the *detach* button
+on the base of the device or executing the ``SDTX_IOCTL_LATCH_REQUEST`` IOCTL.
+Following that:
+
+1. The EC turns on the indicator led on the detach-button, sends a
+ *detach-request* event (``SDTX_EVENT_REQUEST``), and awaits further
+ instructions/commands. In case the latch is unlocked, the led will flash
+ green. If the latch has been locked, the led will be solid red
+
+2. The event is, via the ``surface_dtx`` driver, relayed to user-space, where
+ an appropriate user-space daemon can handle it and send instructions back
+ to the EC via IOCTLs provided by this driver.
+
+3. The EC waits for instructions from user-space and acts according to them.
+ If the EC does not receive any instructions in a given period, it will
+ time out and continue as follows:
+
+ - If the latch is unlocked, the EC will open the latch and the clipboard
+ can be detached from the base. This is the exact behavior as without
+ this driver or any user-space daemon. See the ``SDTX_IOCTL_LATCH_CONFIRM``
+ description below for more details on the follow-up behavior of the EC.
+
+ - If the latch is locked, the EC will *not* open the latch, meaning the
+ clipboard cannot be detached from the base. Furthermore, the EC sends
+ an cancel event (``SDTX_EVENT_CANCEL``) detailing this with the cancel
+ reason ``SDTX_DETACH_TIMEDOUT`` (see :ref:`events` for details).
+
+Valid responses by a user-space daemon to a detachment request event are:
+
+- Execute ``SDTX_IOCTL_LATCH_REQUEST``. This will immediately abort the
+ detachment process. Furthermore, the EC will send a detach-request event,
+ similar to the user pressing the detach-button to cancel said process (see
+ below).
+
+- Execute ``SDTX_IOCTL_LATCH_CONFIRM``. This will cause the EC to open the
+ latch, after which the user can separate clipboard and base.
+
+ As this changes the latch state, a *latch-status* event
+ (``SDTX_EVENT_LATCH_STATUS``) will be sent once the latch has been opened
+ successfully. If the EC fails to open the latch, e.g. due to hardware
+ error or low battery, a latch-cancel event (``SDTX_EVENT_CANCEL``) will be
+ sent with the cancel reason indicating the specific failure.
+
+ If the latch is currently locked, the latch will automatically be
+ unlocked before it is opened.
+
+- Execute ``SDTX_IOCTL_LATCH_HEARTBEAT``. This will reset the internal timeout.
+ No other actions will be performed, i.e. the detachment process will neither
+ be completed nor canceled, and the EC will still be waiting for further
+ responses.
+
+- Execute ``SDTX_IOCTL_LATCH_CANCEL``. This will abort the detachment process,
+ similar to ``SDTX_IOCTL_LATCH_REQUEST``, described above, or the button
+ press, described below. A *generic request* event (``SDTX_EVENT_REQUEST``)
+ is send in response to this. In contrast to those, however, this command
+ does not trigger a new detachment process if none is currently in
+ progress.
+
+- Do nothing. The detachment process eventually times out as described in
+ point 3.
+
+See :ref:`ioctls` for more details on these responses.
+
+It is important to note that, if the user presses the detach button at any
+point when a detachment operation is in progress (i.e. after the EC has sent
+the initial *detach-request* event (``SDTX_EVENT_REQUEST``) and before it
+received the corresponding response concluding the process), the detachment
+process is canceled on the EC-level and an identical event is being sent.
+Thus a *detach-request* event, by itself, does not signal the start of the
+detachment process.
+
+The detachment process may further be canceled by the EC due to hardware
+failures or a low clipboard battery. This is done via a cancel event
+(``SDTX_EVENT_CANCEL``) with the corresponding cancel reason.
+
+
+User-Space Interface Documentation
+==================================
+
+Error Codes and Status Values
+-----------------------------
+
+Error and status codes are divided into different categories, which can be
+used to determine if the status code is an error, and, if it is, the
+severity and type of that error. The current categories are:
+
+.. flat-table:: Overview of Status/Error Categories.
+ :widths: 2 1 3
+ :header-rows: 1
+
+ * - Name
+ - Value
+ - Short Description
+
+ * - ``STATUS``
+ - ``0x0000``
+ - Non-error status codes.
+
+ * - ``RUNTIME_ERROR``
+ - ``0x1000``
+ - Non-critical runtime errors.
+
+ * - ``HARDWARE_ERROR``
+ - ``0x2000``
+ - Critical hardware failures.
+
+ * - ``UNKNOWN``
+ - ``0xF000``
+ - Unknown error codes.
+
+Other categories are reserved for future use. The ``SDTX_CATEGORY()`` macro
+can be used to determine the category of any status value. The
+``SDTX_SUCCESS()`` macro can be used to check if the status value is a
+success value (``SDTX_CATEGORY_STATUS``) or if it indicates a failure.
+
+Unknown status or error codes sent by the EC are assigned to the ``UNKNOWN``
+category by the driver and may be implemented via their own code in the
+future.
+
+Currently used error codes are:
+
+.. flat-table:: Overview of Error Codes.
+ :widths: 2 1 1 3
+ :header-rows: 1
+
+ * - Name
+ - Category
+ - Value
+ - Short Description
+
+ * - ``SDTX_DETACH_NOT_FEASIBLE``
+ - ``RUNTIME``
+ - ``0x1001``
+ - Detachment not feasible due to low clipboard battery.
+
+ * - ``SDTX_DETACH_TIMEDOUT``
+ - ``RUNTIME``
+ - ``0x1002``
+ - Detachment process timed out while the latch was locked.
+
+ * - ``SDTX_ERR_FAILED_TO_OPEN``
+ - ``HARDWARE``
+ - ``0x2001``
+ - Failed to open latch.
+
+ * - ``SDTX_ERR_FAILED_TO_REMAIN_OPEN``
+ - ``HARDWARE``
+ - ``0x2002``
+ - Failed to keep latch open.
+
+ * - ``SDTX_ERR_FAILED_TO_CLOSE``
+ - ``HARDWARE``
+ - ``0x2003``
+ - Failed to close latch.
+
+Other error codes are reserved for future use. Non-error status codes may
+overlap and are generally only unique within their use-case:
+
+.. flat-table:: Latch Status Codes.
+ :widths: 2 1 1 3
+ :header-rows: 1
+
+ * - Name
+ - Category
+ - Value
+ - Short Description
+
+ * - ``SDTX_LATCH_CLOSED``
+ - ``STATUS``
+ - ``0x0000``
+ - Latch is closed/has been closed.
+
+ * - ``SDTX_LATCH_OPENED``
+ - ``STATUS``
+ - ``0x0001``
+ - Latch is open/has been opened.
+
+.. flat-table:: Base State Codes.
+ :widths: 2 1 1 3
+ :header-rows: 1
+
+ * - Name
+ - Category
+ - Value
+ - Short Description
+
+ * - ``SDTX_BASE_DETACHED``
+ - ``STATUS``
+ - ``0x0000``
+ - Base has been detached/is not present.
+
+ * - ``SDTX_BASE_ATTACHED``
+ - ``STATUS``
+ - ``0x0001``
+ - Base has been attached/is present.
+
+Again, other codes are reserved for future use.
+
+.. _events:
+
+Events
+------
+
+Events can be received by reading from the device file. They are disabled by
+default and have to be enabled by executing ``SDTX_IOCTL_EVENTS_ENABLE``
+first. All events follow the layout prescribed by |sdtx_event|. Specific
+event types can be identified by their event code, described in
+|sdtx_event_code|. Note that other event codes are reserved for future use,
+thus an event parser must be able to handle any unknown/unsupported event
+types gracefully, by relying on the payload length given in the event header.
+
+Currently provided event types are:
+
+.. flat-table:: Overview of DTX events.
+ :widths: 2 1 1 3
+ :header-rows: 1
+
+ * - Name
+ - Code
+ - Payload
+ - Short Description
+
+ * - ``SDTX_EVENT_REQUEST``
+ - ``1``
+ - ``0`` bytes
+ - Detachment process initiated/aborted.
+
+ * - ``SDTX_EVENT_CANCEL``
+ - ``2``
+ - ``2`` bytes
+ - EC canceled detachment process.
+
+ * - ``SDTX_EVENT_BASE_CONNECTION``
+ - ``3``
+ - ``4`` bytes
+ - Base connection state changed.
+
+ * - ``SDTX_EVENT_LATCH_STATUS``
+ - ``4``
+ - ``2`` bytes
+ - Latch status changed.
+
+ * - ``SDTX_EVENT_DEVICE_MODE``
+ - ``5``
+ - ``2`` bytes
+ - Device mode changed.
+
+Individual events in more detail:
+
+``SDTX_EVENT_REQUEST``
+^^^^^^^^^^^^^^^^^^^^^^
+
+Sent when a detachment process is started or, if in progress, aborted by the
+user, either via a detach button press or a detach request
+(``SDTX_IOCTL_LATCH_REQUEST``) being sent from user-space.
+
+Does not have any payload.
+
+``SDTX_EVENT_CANCEL``
+^^^^^^^^^^^^^^^^^^^^^
+
+Sent when a detachment process is canceled by the EC due to unfulfilled
+preconditions (e.g. clipboard battery too low to detach) or hardware
+failure. The reason for cancellation is given in the event payload detailed
+below and can be one of
+
+* ``SDTX_DETACH_TIMEDOUT``: Detachment timed out while the latch was locked.
+ The latch has neither been opened nor unlocked.
+
+* ``SDTX_DETACH_NOT_FEASIBLE``: Detachment not feasible due to low clipboard
+ battery.
+
+* ``SDTX_ERR_FAILED_TO_OPEN``: Could not open the latch (hardware failure).
+
+* ``SDTX_ERR_FAILED_TO_REMAIN_OPEN``: Could not keep the latch open (hardware
+ failure).
+
+* ``SDTX_ERR_FAILED_TO_CLOSE``: Could not close the latch (hardware failure).
+
+Other error codes in this context are reserved for future use.
+
+These codes can be classified via the ``SDTX_CATEGORY()`` macro to discern
+between critical hardware errors (``SDTX_CATEGORY_HARDWARE_ERROR``) or
+runtime errors (``SDTX_CATEGORY_RUNTIME_ERROR``), the latter of which may
+happen during normal operation if certain preconditions for detachment are
+not given.
+
+.. flat-table:: Detachment Cancel Event Payload
+ :widths: 1 1 4
+ :header-rows: 1
+
+ * - Field
+ - Type
+ - Description
+
+ * - ``reason``
+ - |__u16|
+ - Reason for cancellation.
+
+``SDTX_EVENT_BASE_CONNECTION``
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Sent when the base connection state has changed, i.e. when the base has been
+attached, detached, or detachment has become infeasible due to low clipboard
+battery. The new state and, if a base is connected, ID of the base is
+provided as payload of type |sdtx_base_info| with its layout presented
+below:
+
+.. flat-table:: Base-Connection-Change Event Payload
+ :widths: 1 1 4
+ :header-rows: 1
+
+ * - Field
+ - Type
+ - Description
+
+ * - ``state``
+ - |__u16|
+ - Base connection state.
+
+ * - ``base_id``
+ - |__u16|
+ - Type of base connected (zero if none).
+
+Possible values for ``state`` are:
+
+* ``SDTX_BASE_DETACHED``,
+* ``SDTX_BASE_ATTACHED``, and
+* ``SDTX_DETACH_NOT_FEASIBLE``.
+
+Other values are reserved for future use.
+
+``SDTX_EVENT_LATCH_STATUS``
+^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Sent when the latch status has changed, i.e. when the latch has been opened,
+closed, or an error occurred. The current status is provided as payload:
+
+.. flat-table:: Latch-Status-Change Event Payload
+ :widths: 1 1 4
+ :header-rows: 1
+
+ * - Field
+ - Type
+ - Description
+
+ * - ``status``
+ - |__u16|
+ - Latch status.
+
+Possible values for ``status`` are:
+
+* ``SDTX_LATCH_CLOSED``,
+* ``SDTX_LATCH_OPENED``,
+* ``SDTX_ERR_FAILED_TO_OPEN``,
+* ``SDTX_ERR_FAILED_TO_REMAIN_OPEN``, and
+* ``SDTX_ERR_FAILED_TO_CLOSE``.
+
+Other values are reserved for future use.
+
+``SDTX_EVENT_DEVICE_MODE``
+^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Sent when the device mode has changed. The new device mode is provided as
+payload:
+
+.. flat-table:: Device-Mode-Change Event Payload
+ :widths: 1 1 4
+ :header-rows: 1
+
+ * - Field
+ - Type
+ - Description
+
+ * - ``mode``
+ - |__u16|
+ - Device operation mode.
+
+Possible values for ``mode`` are:
+
+* ``SDTX_DEVICE_MODE_TABLET``,
+* ``SDTX_DEVICE_MODE_LAPTOP``, and
+* ``SDTX_DEVICE_MODE_STUDIO``.
+
+Other values are reserved for future use.
+
+.. _ioctls:
+
+IOCTLs
+------
+
+The following IOCTLs are provided:
+
+.. flat-table:: Overview of DTX IOCTLs
+ :widths: 1 1 1 1 4
+ :header-rows: 1
+
+ * - Type
+ - Number
+ - Direction
+ - Name
+ - Description
+
+ * - ``0xA5``
+ - ``0x21``
+ - ``-``
+ - ``EVENTS_ENABLE``
+ - Enable events for the current file descriptor.
+
+ * - ``0xA5``
+ - ``0x22``
+ - ``-``
+ - ``EVENTS_DISABLE``
+ - Disable events for the current file descriptor.
+
+ * - ``0xA5``
+ - ``0x23``
+ - ``-``
+ - ``LATCH_LOCK``
+ - Lock the latch.
+
+ * - ``0xA5``
+ - ``0x24``
+ - ``-``
+ - ``LATCH_UNLOCK``
+ - Unlock the latch.
+
+ * - ``0xA5``
+ - ``0x25``
+ - ``-``
+ - ``LATCH_REQUEST``
+ - Request clipboard detachment.
+
+ * - ``0xA5``
+ - ``0x26``
+ - ``-``
+ - ``LATCH_CONFIRM``
+ - Confirm clipboard detachment request.
+
+ * - ``0xA5``
+ - ``0x27``
+ - ``-``
+ - ``LATCH_HEARTBEAT``
+ - Send heartbeat signal to EC.
+
+ * - ``0xA5``
+ - ``0x28``
+ - ``-``
+ - ``LATCH_CANCEL``
+ - Cancel detachment process.
+
+ * - ``0xA5``
+ - ``0x29``
+ - ``R``
+ - ``GET_BASE_INFO``
+ - Get current base/connection information.
+
+ * - ``0xA5``
+ - ``0x2A``
+ - ``R``
+ - ``GET_DEVICE_MODE``
+ - Get current device operation mode.
+
+ * - ``0xA5``
+ - ``0x2B``
+ - ``R``
+ - ``GET_LATCH_STATUS``
+ - Get current device latch status.
+
+``SDTX_IOCTL_EVENTS_ENABLE``
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Defined as ``_IO(0xA5, 0x22)``.
+
+Enable events for the current file descriptor. Events can be obtained by
+reading from the device, if enabled. Events are disabled by default.
+
+``SDTX_IOCTL_EVENTS_DISABLE``
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Defined as ``_IO(0xA5, 0x22)``.
+
+Disable events for the current file descriptor. Events can be obtained by
+reading from the device, if enabled. Events are disabled by default.
+
+``SDTX_IOCTL_LATCH_LOCK``
+^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Defined as ``_IO(0xA5, 0x23)``.
+
+Locks the latch, causing the detachment procedure to abort without opening
+the latch on timeout. The latch is unlocked by default. This command will be
+silently ignored if the latch is already locked.
+
+``SDTX_IOCTL_LATCH_UNLOCK``
+^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Defined as ``_IO(0xA5, 0x24)``.
+
+Unlocks the latch, causing the detachment procedure to open the latch on
+timeout. The latch is unlocked by default. This command will not open the
+latch when sent during an ongoing detachment process. It will be silently
+ignored if the latch is already unlocked.
+
+``SDTX_IOCTL_LATCH_REQUEST``
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Defined as ``_IO(0xA5, 0x25)``.
+
+Generic latch request. Behavior depends on the context: If no
+detachment-process is active, detachment is requested. Otherwise the
+currently active detachment-process will be aborted.
+
+If a detachment process is canceled by this operation, a generic detachment
+request event (``SDTX_EVENT_REQUEST``) will be sent.
+
+This essentially behaves the same as a detachment button press.
+
+``SDTX_IOCTL_LATCH_CONFIRM``
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Defined as ``_IO(0xA5, 0x26)``.
+
+Acknowledges and confirms a latch request. If sent during an ongoing
+detachment process, this command causes the latch to be opened immediately.
+The latch will also be opened if it has been locked. In this case, the latch
+lock is reset to the unlocked state.
+
+This command will be silently ignored if there is currently no detachment
+procedure in progress.
+
+``SDTX_IOCTL_LATCH_HEARTBEAT``
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Defined as ``_IO(0xA5, 0x27)``.
+
+Sends a heartbeat, essentially resetting the detachment timeout. This
+command can be used to keep the detachment process alive while work required
+for the detachment to succeed is still in progress.
+
+This command will be silently ignored if there is currently no detachment
+procedure in progress.
+
+``SDTX_IOCTL_LATCH_CANCEL``
+^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Defined as ``_IO(0xA5, 0x28)``.
+
+Cancels detachment in progress (if any). If a detachment process is canceled
+by this operation, a generic detachment request event
+(``SDTX_EVENT_REQUEST``) will be sent.
+
+This command will be silently ignored if there is currently no detachment
+procedure in progress.
+
+``SDTX_IOCTL_GET_BASE_INFO``
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Defined as ``_IOR(0xA5, 0x29, struct sdtx_base_info)``.
+
+Get the current base connection state (i.e. attached/detached) and the type
+of the base connected to the clipboard. This is command essentially provides
+a way to query the information provided by the base connection change event
+(``SDTX_EVENT_BASE_CONNECTION``).
+
+Possible values for ``struct sdtx_base_info.state`` are:
+
+* ``SDTX_BASE_DETACHED``,
+* ``SDTX_BASE_ATTACHED``, and
+* ``SDTX_DETACH_NOT_FEASIBLE``.
+
+Other values are reserved for future use.
+
+``SDTX_IOCTL_GET_DEVICE_MODE``
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Defined as ``_IOR(0xA5, 0x2A, __u16)``.
+
+Returns the device operation mode, indicating if and how the base is
+attached to the clipboard. This is command essentially provides a way to
+query the information provided by the device mode change event
+(``SDTX_EVENT_DEVICE_MODE``).
+
+Returned values are:
+
+* ``SDTX_DEVICE_MODE_LAPTOP``
+* ``SDTX_DEVICE_MODE_TABLET``
+* ``SDTX_DEVICE_MODE_STUDIO``
+
+See |sdtx_device_mode| for details. Other values are reserved for future
+use.
+
+
+``SDTX_IOCTL_GET_LATCH_STATUS``
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Defined as ``_IOR(0xA5, 0x2B, __u16)``.
+
+Get the current latch status or (presumably) the last error encountered when
+trying to open/close the latch. This is command essentially provides a way
+to query the information provided by the latch status change event
+(``SDTX_EVENT_LATCH_STATUS``).
+
+Returned values are:
+
+* ``SDTX_LATCH_CLOSED``,
+* ``SDTX_LATCH_OPENED``,
+* ``SDTX_ERR_FAILED_TO_OPEN``,
+* ``SDTX_ERR_FAILED_TO_REMAIN_OPEN``, and
+* ``SDTX_ERR_FAILED_TO_CLOSE``.
+
+Other values are reserved for future use.
+
+A Note on Base IDs
+------------------
+
+Base types/IDs provided via ``SDTX_EVENT_BASE_CONNECTION`` or
+``SDTX_IOCTL_GET_BASE_INFO`` are directly forwarded from the EC in the lower
+byte of the combined |__u16| value, with the driver storing the EC type from
+which this ID comes in the high byte (without this, base IDs over different
+types of ECs may be overlapping).
+
+The ``SDTX_DEVICE_TYPE()`` macro can be used to determine the EC device
+type. This can be one of
+
+* ``SDTX_DEVICE_TYPE_HID``, for Surface Aggregator Module over HID, and
+
+* ``SDTX_DEVICE_TYPE_SSH``, for Surface Aggregator Module over Surface Serial
+ Hub.
+
+Note that currently only the ``SSH`` type EC is supported, however ``HID``
+type is reserved for future use.
+
+Structures and Enums
+--------------------
+
+.. kernel-doc:: include/uapi/linux/surface_aggregator/dtx.h
+
+API Users
+=========
+
+A user-space daemon utilizing this API can be found at
+https://github.com/linux-surface/surface-dtx-daemon.
diff --git a/Documentation/driver-api/surface_aggregator/clients/index.rst b/Documentation/driver-api/surface_aggregator/clients/index.rst
new file mode 100644
index 000000000000..30160513afa5
--- /dev/null
+++ b/Documentation/driver-api/surface_aggregator/clients/index.rst
@@ -0,0 +1,23 @@
+.. SPDX-License-Identifier: GPL-2.0+
+
+===========================
+Client Driver Documentation
+===========================
+
+This is the documentation for client drivers themselves. Refer to
+Documentation/driver-api/surface_aggregator/client.rst for documentation
+on how to write client drivers.
+
+.. toctree::
+ :maxdepth: 1
+
+ cdev
+ dtx
+ san
+
+.. only:: subproject and html
+
+ Indices
+ =======
+
+ * :ref:`genindex`
diff --git a/Documentation/driver-api/surface_aggregator/clients/san.rst b/Documentation/driver-api/surface_aggregator/clients/san.rst
new file mode 100644
index 000000000000..38c2580e7758
--- /dev/null
+++ b/Documentation/driver-api/surface_aggregator/clients/san.rst
@@ -0,0 +1,44 @@
+.. SPDX-License-Identifier: GPL-2.0+
+
+.. |san_client_link| replace:: :c:func:`san_client_link`
+.. |san_dgpu_notifier_register| replace:: :c:func:`san_dgpu_notifier_register`
+.. |san_dgpu_notifier_unregister| replace:: :c:func:`san_dgpu_notifier_unregister`
+
+===================
+Surface ACPI Notify
+===================
+
+The Surface ACPI Notify (SAN) device provides the bridge between ACPI and
+SAM controller. Specifically, ACPI code can execute requests and handle
+battery and thermal events via this interface. In addition to this, events
+relating to the discrete GPU (dGPU) of the Surface Book 2 can be sent from
+ACPI code (note: the Surface Book 3 uses a different method for this). The
+only currently known event sent via this interface is a dGPU power-on
+notification. While this driver handles the former part internally, it only
+relays the dGPU events to any other driver interested via its public API and
+does not handle them.
+
+The public interface of this driver is split into two parts: Client
+registration and notifier-block registration.
+
+A client to the SAN interface can be linked as consumer to the SAN device
+via |san_client_link|. This can be used to ensure that the a client
+receiving dGPU events does not miss any events due to the SAN interface not
+being set up as this forces the client driver to unbind once the SAN driver
+is unbound.
+
+Notifier-blocks can be registered by any device for as long as the module is
+loaded, regardless of being linked as client or not. Registration is done
+with |san_dgpu_notifier_register|. If the notifier is not needed any more, it
+should be unregistered via |san_dgpu_notifier_unregister|.
+
+Consult the API documentation below for more details.
+
+
+API Documentation
+=================
+
+.. kernel-doc:: include/linux/surface_acpi_notify.h
+
+.. kernel-doc:: drivers/platform/surface/surface_acpi_notify.c
+ :export:
diff --git a/Documentation/driver-api/surface_aggregator/index.rst b/Documentation/driver-api/surface_aggregator/index.rst
new file mode 100644
index 000000000000..6f3e1094904d
--- /dev/null
+++ b/Documentation/driver-api/surface_aggregator/index.rst
@@ -0,0 +1,21 @@
+.. SPDX-License-Identifier: GPL-2.0+
+
+=======================================
+Surface System Aggregator Module (SSAM)
+=======================================
+
+.. toctree::
+ :maxdepth: 2
+
+ overview
+ client
+ clients/index
+ ssh
+ internal
+
+.. only:: subproject and html
+
+ Indices
+ =======
+
+ * :ref:`genindex`
diff --git a/Documentation/driver-api/surface_aggregator/internal-api.rst b/Documentation/driver-api/surface_aggregator/internal-api.rst
new file mode 100644
index 000000000000..639a67b5a392
--- /dev/null
+++ b/Documentation/driver-api/surface_aggregator/internal-api.rst
@@ -0,0 +1,67 @@
+.. SPDX-License-Identifier: GPL-2.0+
+
+==========================
+Internal API Documentation
+==========================
+
+.. contents::
+ :depth: 2
+
+
+Packet Transport Layer
+======================
+
+.. kernel-doc:: drivers/platform/surface/aggregator/ssh_parser.h
+ :internal:
+
+.. kernel-doc:: drivers/platform/surface/aggregator/ssh_parser.c
+ :internal:
+
+.. kernel-doc:: drivers/platform/surface/aggregator/ssh_msgb.h
+ :internal:
+
+.. kernel-doc:: drivers/platform/surface/aggregator/ssh_packet_layer.h
+ :internal:
+
+.. kernel-doc:: drivers/platform/surface/aggregator/ssh_packet_layer.c
+ :internal:
+
+
+Request Transport Layer
+=======================
+
+.. kernel-doc:: drivers/platform/surface/aggregator/ssh_request_layer.h
+ :internal:
+
+.. kernel-doc:: drivers/platform/surface/aggregator/ssh_request_layer.c
+ :internal:
+
+
+Controller
+==========
+
+.. kernel-doc:: drivers/platform/surface/aggregator/controller.h
+ :internal:
+
+.. kernel-doc:: drivers/platform/surface/aggregator/controller.c
+ :internal:
+
+
+Client Device Bus
+=================
+
+.. kernel-doc:: drivers/platform/surface/aggregator/bus.c
+ :internal:
+
+
+Core
+====
+
+.. kernel-doc:: drivers/platform/surface/aggregator/core.c
+ :internal:
+
+
+Trace Helpers
+=============
+
+.. kernel-doc:: drivers/platform/surface/aggregator/trace.h
diff --git a/Documentation/driver-api/surface_aggregator/internal.rst b/Documentation/driver-api/surface_aggregator/internal.rst
new file mode 100644
index 000000000000..8c7c80c9f418
--- /dev/null
+++ b/Documentation/driver-api/surface_aggregator/internal.rst
@@ -0,0 +1,578 @@
+.. SPDX-License-Identifier: GPL-2.0+
+
+.. |ssh_ptl| replace:: :c:type:`struct ssh_ptl <ssh_ptl>`
+.. |ssh_ptl_submit| replace:: :c:func:`ssh_ptl_submit`
+.. |ssh_ptl_cancel| replace:: :c:func:`ssh_ptl_cancel`
+.. |ssh_ptl_shutdown| replace:: :c:func:`ssh_ptl_shutdown`
+.. |ssh_ptl_rx_rcvbuf| replace:: :c:func:`ssh_ptl_rx_rcvbuf`
+.. |ssh_rtl| replace:: :c:type:`struct ssh_rtl <ssh_rtl>`
+.. |ssh_rtl_submit| replace:: :c:func:`ssh_rtl_submit`
+.. |ssh_rtl_cancel| replace:: :c:func:`ssh_rtl_cancel`
+.. |ssh_rtl_shutdown| replace:: :c:func:`ssh_rtl_shutdown`
+.. |ssh_packet| replace:: :c:type:`struct ssh_packet <ssh_packet>`
+.. |ssh_packet_get| replace:: :c:func:`ssh_packet_get`
+.. |ssh_packet_put| replace:: :c:func:`ssh_packet_put`
+.. |ssh_packet_ops| replace:: :c:type:`struct ssh_packet_ops <ssh_packet_ops>`
+.. |ssh_packet_base_priority| replace:: :c:type:`enum ssh_packet_base_priority <ssh_packet_base_priority>`
+.. |ssh_packet_flags| replace:: :c:type:`enum ssh_packet_flags <ssh_packet_flags>`
+.. |SSH_PACKET_PRIORITY| replace:: :c:func:`SSH_PACKET_PRIORITY`
+.. |ssh_frame| replace:: :c:type:`struct ssh_frame <ssh_frame>`
+.. |ssh_command| replace:: :c:type:`struct ssh_command <ssh_command>`
+.. |ssh_request| replace:: :c:type:`struct ssh_request <ssh_request>`
+.. |ssh_request_get| replace:: :c:func:`ssh_request_get`
+.. |ssh_request_put| replace:: :c:func:`ssh_request_put`
+.. |ssh_request_ops| replace:: :c:type:`struct ssh_request_ops <ssh_request_ops>`
+.. |ssh_request_init| replace:: :c:func:`ssh_request_init`
+.. |ssh_request_flags| replace:: :c:type:`enum ssh_request_flags <ssh_request_flags>`
+.. |ssam_controller| replace:: :c:type:`struct ssam_controller <ssam_controller>`
+.. |ssam_device| replace:: :c:type:`struct ssam_device <ssam_device>`
+.. |ssam_device_driver| replace:: :c:type:`struct ssam_device_driver <ssam_device_driver>`
+.. |ssam_client_bind| replace:: :c:func:`ssam_client_bind`
+.. |ssam_client_link| replace:: :c:func:`ssam_client_link`
+.. |ssam_request_sync| replace:: :c:type:`struct ssam_request_sync <ssam_request_sync>`
+.. |ssam_event_registry| replace:: :c:type:`struct ssam_event_registry <ssam_event_registry>`
+.. |ssam_event_id| replace:: :c:type:`struct ssam_event_id <ssam_event_id>`
+.. |ssam_nf| replace:: :c:type:`struct ssam_nf <ssam_nf>`
+.. |ssam_nf_refcount_inc| replace:: :c:func:`ssam_nf_refcount_inc`
+.. |ssam_nf_refcount_dec| replace:: :c:func:`ssam_nf_refcount_dec`
+.. |ssam_notifier_register| replace:: :c:func:`ssam_notifier_register`
+.. |ssam_notifier_unregister| replace:: :c:func:`ssam_notifier_unregister`
+.. |ssam_cplt| replace:: :c:type:`struct ssam_cplt <ssam_cplt>`
+.. |ssam_event_queue| replace:: :c:type:`struct ssam_event_queue <ssam_event_queue>`
+.. |ssam_request_sync_submit| replace:: :c:func:`ssam_request_sync_submit`
+
+=====================
+Core Driver Internals
+=====================
+
+Architectural overview of the Surface System Aggregator Module (SSAM) core
+and Surface Serial Hub (SSH) driver. For the API documentation, refer to:
+
+.. toctree::
+ :maxdepth: 2
+
+ internal-api
+
+
+Overview
+========
+
+The SSAM core implementation is structured in layers, somewhat following the
+SSH protocol structure:
+
+Lower-level packet transport is implemented in the *packet transport layer
+(PTL)*, directly building on top of the serial device (serdev)
+infrastructure of the kernel. As the name indicates, this layer deals with
+the packet transport logic and handles things like packet validation, packet
+acknowledgment (ACKing), packet (retransmission) timeouts, and relaying
+packet payloads to higher-level layers.
+
+Above this sits the *request transport layer (RTL)*. This layer is centered
+around command-type packet payloads, i.e. requests (sent from host to EC),
+responses of the EC to those requests, and events (sent from EC to host).
+It, specifically, distinguishes events from request responses, matches
+responses to their corresponding requests, and implements request timeouts.
+
+The *controller* layer is building on top of this and essentially decides
+how request responses and, especially, events are dealt with. It provides an
+event notifier system, handles event activation/deactivation, provides a
+workqueue for event and asynchronous request completion, and also manages
+the message counters required for building command messages (``SEQ``,
+``RQID``). This layer basically provides a fundamental interface to the SAM
+EC for use in other kernel drivers.
+
+While the controller layer already provides an interface for other kernel
+drivers, the client *bus* extends this interface to provide support for
+native SSAM devices, i.e. devices that are not defined in ACPI and not
+implemented as platform devices, via |ssam_device| and |ssam_device_driver|
+simplify management of client devices and client drivers.
+
+Refer to Documentation/driver-api/surface_aggregator/client.rst for
+documentation regarding the client device/driver API and interface options
+for other kernel drivers. It is recommended to familiarize oneself with
+that chapter and the Documentation/driver-api/surface_aggregator/ssh.rst
+before continuing with the architectural overview below.
+
+
+Packet Transport Layer
+======================
+
+The packet transport layer is represented via |ssh_ptl| and is structured
+around the following key concepts:
+
+Packets
+-------
+
+Packets are the fundamental transmission unit of the SSH protocol. They are
+managed by the packet transport layer, which is essentially the lowest layer
+of the driver and is built upon by other components of the SSAM core.
+Packets to be transmitted by the SSAM core are represented via |ssh_packet|
+(in contrast, packets received by the core do not have any specific
+structure and are managed entirely via the raw |ssh_frame|).
+
+This structure contains the required fields to manage the packet inside the
+transport layer, as well as a reference to the buffer containing the data to
+be transmitted (i.e. the message wrapped in |ssh_frame|). Most notably, it
+contains an internal reference count, which is used for managing its
+lifetime (accessible via |ssh_packet_get| and |ssh_packet_put|). When this
+counter reaches zero, the ``release()`` callback provided to the packet via
+its |ssh_packet_ops| reference is executed, which may then deallocate the
+packet or its enclosing structure (e.g. |ssh_request|).
+
+In addition to the ``release`` callback, the |ssh_packet_ops| reference also
+provides a ``complete()`` callback, which is run once the packet has been
+completed and provides the status of this completion, i.e. zero on success
+or a negative errno value in case of an error. Once the packet has been
+submitted to the packet transport layer, the ``complete()`` callback is
+always guaranteed to be executed before the ``release()`` callback, i.e. the
+packet will always be completed, either successfully, with an error, or due
+to cancellation, before it will be released.
+
+The state of a packet is managed via its ``state`` flags
+(|ssh_packet_flags|), which also contains the packet type. In particular,
+the following bits are noteworthy:
+
+* ``SSH_PACKET_SF_LOCKED_BIT``: This bit is set when completion, either
+ through error or success, is imminent. It indicates that no further
+ references of the packet should be taken and any existing references
+ should be dropped as soon as possible. The process setting this bit is
+ responsible for removing any references to this packet from the packet
+ queue and pending set.
+
+* ``SSH_PACKET_SF_COMPLETED_BIT``: This bit is set by the process running the
+ ``complete()`` callback and is used to ensure that this callback only runs
+ once.
+
+* ``SSH_PACKET_SF_QUEUED_BIT``: This bit is set when the packet is queued on
+ the packet queue and cleared when it is dequeued.
+
+* ``SSH_PACKET_SF_PENDING_BIT``: This bit is set when the packet is added to
+ the pending set and cleared when it is removed from it.
+
+Packet Queue
+------------
+
+The packet queue is the first of the two fundamental collections in the
+packet transport layer. It is a priority queue, with priority of the
+respective packets based on the packet type (major) and number of tries
+(minor). See |SSH_PACKET_PRIORITY| for more details on the priority value.
+
+All packets to be transmitted by the transport layer must be submitted to
+this queue via |ssh_ptl_submit|. Note that this includes control packets
+sent by the transport layer itself. Internally, data packets can be
+re-submitted to this queue due to timeouts or NAK packets sent by the EC.
+
+Pending Set
+-----------
+
+The pending set is the second of the two fundamental collections in the
+packet transport layer. It stores references to packets that have already
+been transmitted, but wait for acknowledgment (e.g. the corresponding ACK
+packet) by the EC.
+
+Note that a packet may both be pending and queued if it has been
+re-submitted due to a packet acknowledgment timeout or NAK. On such a
+re-submission, packets are not removed from the pending set.
+
+Transmitter Thread
+------------------
+
+The transmitter thread is responsible for most of the actual work regarding
+packet transmission. In each iteration, it (waits for and) checks if the
+next packet on the queue (if any) can be transmitted and, if so, removes it
+from the queue and increments its counter for the number of transmission
+attempts, i.e. tries. If the packet is sequenced, i.e. requires an ACK by
+the EC, the packet is added to the pending set. Next, the packet's data is
+submitted to the serdev subsystem. In case of an error or timeout during
+this submission, the packet is completed by the transmitter thread with the
+status value of the callback set accordingly. In case the packet is
+unsequenced, i.e. does not require an ACK by the EC, the packet is completed
+with success on the transmitter thread.
+
+Transmission of sequenced packets is limited by the number of concurrently
+pending packets, i.e. a limit on how many packets may be waiting for an ACK
+from the EC in parallel. This limit is currently set to one (see
+Documentation/driver-api/surface_aggregator/ssh.rst for the reasoning behind
+this). Control packets (i.e. ACK and NAK) can always be transmitted.
+
+Receiver Thread
+---------------
+
+Any data received from the EC is put into a FIFO buffer for further
+processing. This processing happens on the receiver thread. The receiver
+thread parses and validates the received message into its |ssh_frame| and
+corresponding payload. It prepares and submits the necessary ACK (and on
+validation error or invalid data NAK) packets for the received messages.
+
+This thread also handles further processing, such as matching ACK messages
+to the corresponding pending packet (via sequence ID) and completing it, as
+well as initiating re-submission of all currently pending packets on
+receival of a NAK message (re-submission in case of a NAK is similar to
+re-submission due to timeout, see below for more details on that). Note that
+the successful completion of a sequenced packet will always run on the
+receiver thread (whereas any failure-indicating completion will run on the
+process where the failure occurred).
+
+Any payload data is forwarded via a callback to the next upper layer, i.e.
+the request transport layer.
+
+Timeout Reaper
+--------------
+
+The packet acknowledgment timeout is a per-packet timeout for sequenced
+packets, started when the respective packet begins (re-)transmission (i.e.
+this timeout is armed once per transmission attempt on the transmitter
+thread). It is used to trigger re-submission or, when the number of tries
+has been exceeded, cancellation of the packet in question.
+
+This timeout is handled via a dedicated reaper task, which is essentially a
+work item (re-)scheduled to run when the next packet is set to time out. The
+work item then checks the set of pending packets for any packets that have
+exceeded the timeout and, if there are any remaining packets, re-schedules
+itself to the next appropriate point in time.
+
+If a timeout has been detected by the reaper, the packet will either be
+re-submitted if it still has some remaining tries left, or completed with
+``-ETIMEDOUT`` as status if not. Note that re-submission, in this case and
+triggered by receival of a NAK, means that the packet is added to the queue
+with a now incremented number of tries, yielding a higher priority. The
+timeout for the packet will be disabled until the next transmission attempt
+and the packet remains on the pending set.
+
+Note that due to transmission and packet acknowledgment timeouts, the packet
+transport layer is always guaranteed to make progress, if only through
+timing out packets, and will never fully block.
+
+Concurrency and Locking
+-----------------------
+
+There are two main locks in the packet transport layer: One guarding access
+to the packet queue and one guarding access to the pending set. These
+collections may only be accessed and modified under the respective lock. If
+access to both collections is needed, the pending lock must be acquired
+before the queue lock to avoid deadlocks.
+
+In addition to guarding the collections, after initial packet submission
+certain packet fields may only be accessed under one of the locks.
+Specifically, the packet priority must only be accessed while holding the
+queue lock and the packet timestamp must only be accessed while holding the
+pending lock.
+
+Other parts of the packet transport layer are guarded independently. State
+flags are managed by atomic bit operations and, if necessary, memory
+barriers. Modifications to the timeout reaper work item and expiration date
+are guarded by their own lock.
+
+The reference of the packet to the packet transport layer (``ptl``) is
+somewhat special. It is either set when the upper layer request is submitted
+or, if there is none, when the packet is first submitted. After it is set,
+it will not change its value. Functions that may run concurrently with
+submission, i.e. cancellation, can not rely on the ``ptl`` reference to be
+set. Access to it in these functions is guarded by ``READ_ONCE()``, whereas
+setting ``ptl`` is equally guarded with ``WRITE_ONCE()`` for symmetry.
+
+Some packet fields may be read outside of the respective locks guarding
+them, specifically priority and state for tracing. In those cases, proper
+access is ensured by employing ``WRITE_ONCE()`` and ``READ_ONCE()``. Such
+read-only access is only allowed when stale values are not critical.
+
+With respect to the interface for higher layers, packet submission
+(|ssh_ptl_submit|), packet cancellation (|ssh_ptl_cancel|), data receival
+(|ssh_ptl_rx_rcvbuf|), and layer shutdown (|ssh_ptl_shutdown|) may always be
+executed concurrently with respect to each other. Note that packet
+submission may not run concurrently with itself for the same packet.
+Equally, shutdown and data receival may also not run concurrently with
+themselves (but may run concurrently with each other).
+
+
+Request Transport Layer
+=======================
+
+The request transport layer is represented via |ssh_rtl| and builds on top
+of the packet transport layer. It deals with requests, i.e. SSH packets sent
+by the host containing a |ssh_command| as frame payload. This layer
+separates responses to requests from events, which are also sent by the EC
+via a |ssh_command| payload. While responses are handled in this layer,
+events are relayed to the next upper layer, i.e. the controller layer, via
+the corresponding callback. The request transport layer is structured around
+the following key concepts:
+
+Request
+-------
+
+Requests are packets with a command-type payload, sent from host to EC to
+query data from or trigger an action on it (or both simultaneously). They
+are represented by |ssh_request|, wrapping the underlying |ssh_packet|
+storing its message data (i.e. SSH frame with command payload). Note that
+all top-level representations, e.g. |ssam_request_sync| are built upon this
+struct.
+
+As |ssh_request| extends |ssh_packet|, its lifetime is also managed by the
+reference counter inside the packet struct (which can be accessed via
+|ssh_request_get| and |ssh_request_put|). Once the counter reaches zero, the
+``release()`` callback of the |ssh_request_ops| reference of the request is
+called.
+
+Requests can have an optional response that is equally sent via a SSH
+message with command-type payload (from EC to host). The party constructing
+the request must know if a response is expected and mark this in the request
+flags provided to |ssh_request_init|, so that the request transport layer
+can wait for this response.
+
+Similar to |ssh_packet|, |ssh_request| also has a ``complete()`` callback
+provided via its request ops reference and is guaranteed to be completed
+before it is released once it has been submitted to the request transport
+layer via |ssh_rtl_submit|. For a request without a response, successful
+completion will occur once the underlying packet has been successfully
+transmitted by the packet transport layer (i.e. from within the packet
+completion callback). For a request with response, successful completion
+will occur once the response has been received and matched to the request
+via its request ID (which happens on the packet layer's data-received
+callback running on the receiver thread). If the request is completed with
+an error, the status value will be set to the corresponding (negative) errno
+value.
+
+The state of a request is again managed via its ``state`` flags
+(|ssh_request_flags|), which also encode the request type. In particular,
+the following bits are noteworthy:
+
+* ``SSH_REQUEST_SF_LOCKED_BIT``: This bit is set when completion, either
+ through error or success, is imminent. It indicates that no further
+ references of the request should be taken and any existing references
+ should be dropped as soon as possible. The process setting this bit is
+ responsible for removing any references to this request from the request
+ queue and pending set.
+
+* ``SSH_REQUEST_SF_COMPLETED_BIT``: This bit is set by the process running the
+ ``complete()`` callback and is used to ensure that this callback only runs
+ once.
+
+* ``SSH_REQUEST_SF_QUEUED_BIT``: This bit is set when the request is queued on
+ the request queue and cleared when it is dequeued.
+
+* ``SSH_REQUEST_SF_PENDING_BIT``: This bit is set when the request is added to
+ the pending set and cleared when it is removed from it.
+
+Request Queue
+-------------
+
+The request queue is the first of the two fundamental collections in the
+request transport layer. In contrast to the packet queue of the packet
+transport layer, it is not a priority queue and the simple first come first
+serve principle applies.
+
+All requests to be transmitted by the request transport layer must be
+submitted to this queue via |ssh_rtl_submit|. Once submitted, requests may
+not be re-submitted, and will not be re-submitted automatically on timeout.
+Instead, the request is completed with a timeout error. If desired, the
+caller can create and submit a new request for another try, but it must not
+submit the same request again.
+
+Pending Set
+-----------
+
+The pending set is the second of the two fundamental collections in the
+request transport layer. This collection stores references to all pending
+requests, i.e. requests awaiting a response from the EC (similar to what the
+pending set of the packet transport layer does for packets).
+
+Transmitter Task
+----------------
+
+The transmitter task is scheduled when a new request is available for
+transmission. It checks if the next request on the request queue can be
+transmitted and, if so, submits its underlying packet to the packet
+transport layer. This check ensures that only a limited number of
+requests can be pending, i.e. waiting for a response, at the same time. If
+the request requires a response, the request is added to the pending set
+before its packet is submitted.
+
+Packet Completion Callback
+--------------------------
+
+The packet completion callback is executed once the underlying packet of a
+request has been completed. In case of an error completion, the
+corresponding request is completed with the error value provided in this
+callback.
+
+On successful packet completion, further processing depends on the request.
+If the request expects a response, it is marked as transmitted and the
+request timeout is started. If the request does not expect a response, it is
+completed with success.
+
+Data-Received Callback
+----------------------
+
+The data received callback notifies the request transport layer of data
+being received by the underlying packet transport layer via a data-type
+frame. In general, this is expected to be a command-type payload.
+
+If the request ID of the command is one of the request IDs reserved for
+events (one to ``SSH_NUM_EVENTS``, inclusively), it is forwarded to the
+event callback registered in the request transport layer. If the request ID
+indicates a response to a request, the respective request is looked up in
+the pending set and, if found and marked as transmitted, completed with
+success.
+
+Timeout Reaper
+--------------
+
+The request-response-timeout is a per-request timeout for requests expecting
+a response. It is used to ensure that a request does not wait indefinitely
+on a response from the EC and is started after the underlying packet has
+been successfully completed.
+
+This timeout is, similar to the packet acknowledgment timeout on the packet
+transport layer, handled via a dedicated reaper task. This task is
+essentially a work-item (re-)scheduled to run when the next request is set
+to time out. The work item then scans the set of pending requests for any
+requests that have timed out and completes them with ``-ETIMEDOUT`` as
+status. Requests will not be re-submitted automatically. Instead, the issuer
+of the request must construct and submit a new request, if so desired.
+
+Note that this timeout, in combination with packet transmission and
+acknowledgment timeouts, guarantees that the request layer will always make
+progress, even if only through timing out packets, and never fully block.
+
+Concurrency and Locking
+-----------------------
+
+Similar to the packet transport layer, there are two main locks in the
+request transport layer: One guarding access to the request queue and one
+guarding access to the pending set. These collections may only be accessed
+and modified under the respective lock.
+
+Other parts of the request transport layer are guarded independently. State
+flags are (again) managed by atomic bit operations and, if necessary, memory
+barriers. Modifications to the timeout reaper work item and expiration date
+are guarded by their own lock.
+
+Some request fields may be read outside of the respective locks guarding
+them, specifically the state for tracing. In those cases, proper access is
+ensured by employing ``WRITE_ONCE()`` and ``READ_ONCE()``. Such read-only
+access is only allowed when stale values are not critical.
+
+With respect to the interface for higher layers, request submission
+(|ssh_rtl_submit|), request cancellation (|ssh_rtl_cancel|), and layer
+shutdown (|ssh_rtl_shutdown|) may always be executed concurrently with
+respect to each other. Note that request submission may not run concurrently
+with itself for the same request (and also may only be called once per
+request). Equally, shutdown may also not run concurrently with itself.
+
+
+Controller Layer
+================
+
+The controller layer extends on the request transport layer to provide an
+easy-to-use interface for client drivers. It is represented by
+|ssam_controller| and the SSH driver. While the lower level transport layers
+take care of transmitting and handling packets and requests, the controller
+layer takes on more of a management role. Specifically, it handles device
+initialization, power management, and event handling, including event
+delivery and registration via the (event) completion system (|ssam_cplt|).
+
+Event Registration
+------------------
+
+In general, an event (or rather a class of events) has to be explicitly
+requested by the host before the EC will send it (HID input events seem to
+be the exception). This is done via an event-enable request (similarly,
+events should be disabled via an event-disable request once no longer
+desired).
+
+The specific request used to enable (or disable) an event is given via an
+event registry, i.e. the governing authority of this event (so to speak),
+represented by |ssam_event_registry|. As parameters to this request, the
+target category and, depending on the event registry, instance ID of the
+event to be enabled must be provided. This (optional) instance ID must be
+zero if the registry does not use it. Together, target category and instance
+ID form the event ID, represented by |ssam_event_id|. In short, both, event
+registry and event ID, are required to uniquely identify a respective class
+of events.
+
+Note that a further *request ID* parameter must be provided for the
+enable-event request. This parameter does not influence the class of events
+being enabled, but instead is set as the request ID (RQID) on each event of
+this class sent by the EC. It is used to identify events (as a limited
+number of request IDs is reserved for use in events only, specifically one
+to ``SSH_NUM_EVENTS`` inclusively) and also map events to their specific
+class. Currently, the controller always sets this parameter to the target
+category specified in |ssam_event_id|.
+
+As multiple client drivers may rely on the same (or overlapping) classes of
+events and enable/disable calls are strictly binary (i.e. on/off), the
+controller has to manage access to these events. It does so via reference
+counting, storing the counter inside an RB-tree based mapping with event
+registry and ID as key (there is no known list of valid event registry and
+event ID combinations). See |ssam_nf|, |ssam_nf_refcount_inc|, and
+|ssam_nf_refcount_dec| for details.
+
+This management is done together with notifier registration (described in
+the next section) via the top-level |ssam_notifier_register| and
+|ssam_notifier_unregister| functions.
+
+Event Delivery
+--------------
+
+To receive events, a client driver has to register an event notifier via
+|ssam_notifier_register|. This increments the reference counter for that
+specific class of events (as detailed in the previous section), enables the
+class on the EC (if it has not been enabled already), and installs the
+provided notifier callback.
+
+Notifier callbacks are stored in lists, with one (RCU) list per target
+category (provided via the event ID; NB: there is a fixed known number of
+target categories). There is no known association from the combination of
+event registry and event ID to the command data (target ID, target category,
+command ID, and instance ID) that can be provided by an event class, apart
+from target category and instance ID given via the event ID.
+
+Note that due to the way notifiers are (or rather have to be) stored, client
+drivers may receive events that they have not requested and need to account
+for them. Specifically, they will, by default, receive all events from the
+same target category. To simplify dealing with this, filtering of events by
+target ID (provided via the event registry) and instance ID (provided via
+the event ID) can be requested when registering a notifier. This filtering
+is applied when iterating over the notifiers at the time they are executed.
+
+All notifier callbacks are executed on a dedicated workqueue, the so-called
+completion workqueue. After an event has been received via the callback
+installed in the request layer (running on the receiver thread of the packet
+transport layer), it will be put on its respective event queue
+(|ssam_event_queue|). From this event queue the completion work item of that
+queue (running on the completion workqueue) will pick up the event and
+execute the notifier callback. This is done to avoid blocking on the
+receiver thread.
+
+There is one event queue per combination of target ID and target category.
+This is done to ensure that notifier callbacks are executed in sequence for
+events of the same target ID and target category. Callbacks can be executed
+in parallel for events with a different combination of target ID and target
+category.
+
+Concurrency and Locking
+-----------------------
+
+Most of the concurrency related safety guarantees of the controller are
+provided by the lower-level request transport layer. In addition to this,
+event (un-)registration is guarded by its own lock.
+
+Access to the controller state is guarded by the state lock. This lock is a
+read/write semaphore. The reader part can be used to ensure that the state
+does not change while functions depending on the state to stay the same
+(e.g. |ssam_notifier_register|, |ssam_notifier_unregister|,
+|ssam_request_sync_submit|, and derivatives) are executed and this guarantee
+is not already provided otherwise (e.g. through |ssam_client_bind| or
+|ssam_client_link|). The writer part guards any transitions that will change
+the state, i.e. initialization, destruction, suspension, and resumption.
+
+The controller state may be accessed (read-only) outside the state lock for
+smoke-testing against invalid API usage (e.g. in |ssam_request_sync_submit|).
+Note that such checks are not supposed to (and will not) protect against all
+invalid usages, but rather aim to help catch them. In those cases, proper
+variable access is ensured by employing ``WRITE_ONCE()`` and ``READ_ONCE()``.
+
+Assuming any preconditions on the state not changing have been satisfied,
+all non-initialization and non-shutdown functions may run concurrently with
+each other. This includes |ssam_notifier_register|, |ssam_notifier_unregister|,
+|ssam_request_sync_submit|, as well as all functions building on top of those.
diff --git a/Documentation/driver-api/surface_aggregator/overview.rst b/Documentation/driver-api/surface_aggregator/overview.rst
new file mode 100644
index 000000000000..26415e1ab7da
--- /dev/null
+++ b/Documentation/driver-api/surface_aggregator/overview.rst
@@ -0,0 +1,79 @@
+.. SPDX-License-Identifier: GPL-2.0+
+
+========
+Overview
+========
+
+The Surface/System Aggregator Module (SAM, SSAM) is an (arguably *the*)
+embedded controller (EC) on Microsoft Surface devices. It has been originally
+introduced on 4th generation devices (Surface Pro 4, Surface Book 1), but
+its responsibilities and feature-set have since been expanded significantly
+with the following generations.
+
+
+Features and Integration
+========================
+
+Not much is currently known about SAM on 4th generation devices (Surface Pro
+4, Surface Book 1), due to the use of a different communication interface
+between host and EC (as detailed below). On 5th (Surface Pro 2017, Surface
+Book 2, Surface Laptop 1) and later generation devices, SAM is responsible
+for providing battery information (both current status and static values,
+such as maximum capacity etc.), as well as an assortment of temperature
+sensors (e.g. skin temperature) and cooling/performance-mode setting to the
+host. On the Surface Book 2, specifically, it additionally provides an
+interface for properly handling clipboard detachment (i.e. separating the
+display part from the keyboard part of the device), on the Surface Laptop 1
+and 2 it is required for keyboard HID input. This HID subsystem has been
+restructured for 7th generation devices and on those, specifically Surface
+Laptop 3 and Surface Book 3, is responsible for all major HID input (i.e.
+keyboard and touchpad).
+
+While features have not changed much on a coarse level since the 5th
+generation, internal interfaces have undergone some rather large changes. On
+5th and 6th generation devices, both battery and temperature information is
+exposed to ACPI via a shim driver (referred to as Surface ACPI Notify, or
+SAN), translating ACPI generic serial bus write-/read-accesses to SAM
+requests. On 7th generation devices, this additional layer is gone and these
+devices require a driver hooking directly into the SAM interface. Equally,
+on newer generations, less devices are declared in ACPI, making them a bit
+harder to discover and requiring us to hard-code a sort of device registry.
+Due to this, a SSAM bus and subsystem with client devices
+(:c:type:`struct ssam_device <ssam_device>`) has been implemented.
+
+
+Communication
+=============
+
+The type of communication interface between host and EC depends on the
+generation of the Surface device. On 4th generation devices, host and EC
+communicate via HID, specifically using a HID-over-I2C device, whereas on
+5th and later generations, communication takes place via a USART serial
+device. In accordance to the drivers found on other operating systems, we
+refer to the serial device and its driver as Surface Serial Hub (SSH). When
+needed, we differentiate between both types of SAM by referring to them as
+SAM-over-SSH and SAM-over-HID.
+
+Currently, this subsystem only supports SAM-over-SSH. The SSH communication
+interface is described in more detail below. The HID interface has not been
+reverse engineered yet and it is, at the moment, unclear how many (and
+which) concepts of the SSH interface detailed below can be transferred to
+it.
+
+Surface Serial Hub
+------------------
+
+As already elaborated above, the Surface Serial Hub (SSH) is the
+communication interface for SAM on 5th- and all later-generation Surface
+devices. On the highest level, communication can be separated into two main
+types: Requests, messages sent from host to EC that may trigger a direct
+response from the EC (explicitly associated with the request), and events
+(sometimes also referred to as notifications), sent from EC to host without
+being a direct response to a previous request. We may also refer to requests
+without response as commands. In general, events need to be enabled via one
+of multiple dedicated requests before they are sent by the EC.
+
+See Documentation/driver-api/surface_aggregator/ssh.rst for a
+more technical protocol documentation and
+Documentation/driver-api/surface_aggregator/internal.rst for an
+overview of the internal driver architecture.
diff --git a/Documentation/driver-api/surface_aggregator/ssh.rst b/Documentation/driver-api/surface_aggregator/ssh.rst
new file mode 100644
index 000000000000..58a757319931
--- /dev/null
+++ b/Documentation/driver-api/surface_aggregator/ssh.rst
@@ -0,0 +1,346 @@
+.. SPDX-License-Identifier: GPL-2.0+
+
+.. |u8| replace:: :c:type:`u8 <u8>`
+.. |u16| replace:: :c:type:`u16 <u16>`
+.. |TYPE| replace:: ``TYPE``
+.. |LEN| replace:: ``LEN``
+.. |SEQ| replace:: ``SEQ``
+.. |SYN| replace:: ``SYN``
+.. |NAK| replace:: ``NAK``
+.. |ACK| replace:: ``ACK``
+.. |DATA| replace:: ``DATA``
+.. |DATA_SEQ| replace:: ``DATA_SEQ``
+.. |DATA_NSQ| replace:: ``DATA_NSQ``
+.. |TC| replace:: ``TC``
+.. |TID| replace:: ``TID``
+.. |SID| replace:: ``SID``
+.. |IID| replace:: ``IID``
+.. |RQID| replace:: ``RQID``
+.. |CID| replace:: ``CID``
+
+===========================
+Surface Serial Hub Protocol
+===========================
+
+The Surface Serial Hub (SSH) is the central communication interface for the
+embedded Surface Aggregator Module controller (SAM or EC), found on newer
+Surface generations. We will refer to this protocol and interface as
+SAM-over-SSH, as opposed to SAM-over-HID for the older generations.
+
+On Surface devices with SAM-over-SSH, SAM is connected to the host via UART
+and defined in ACPI as device with ID ``MSHW0084``. On these devices,
+significant functionality is provided via SAM, including access to battery
+and power information and events, thermal read-outs and events, and many
+more. For Surface Laptops, keyboard input is handled via HID directed
+through SAM, on the Surface Laptop 3 and Surface Book 3 this also includes
+touchpad input.
+
+Note that the standard disclaimer for this subsystem also applies to this
+document: All of this has been reverse-engineered and may thus be erroneous
+and/or incomplete.
+
+All CRCs used in the following are two-byte ``crc_itu_t(0xffff, ...)``.
+All multi-byte values are little-endian, there is no implicit padding between
+values.
+
+
+SSH Packet Protocol: Definitions
+================================
+
+The fundamental communication unit of the SSH protocol is a frame
+(:c:type:`struct ssh_frame <ssh_frame>`). A frame consists of the following
+fields, packed together and in order:
+
+.. flat-table:: SSH Frame
+ :widths: 1 1 4
+ :header-rows: 1
+
+ * - Field
+ - Type
+ - Description
+
+ * - |TYPE|
+ - |u8|
+ - Type identifier of the frame.
+
+ * - |LEN|
+ - |u16|
+ - Length of the payload associated with the frame.
+
+ * - |SEQ|
+ - |u8|
+ - Sequence ID (see explanation below).
+
+Each frame structure is followed by a CRC over this structure. The CRC over
+the frame structure (|TYPE|, |LEN|, and |SEQ| fields) is placed directly
+after the frame structure and before the payload. The payload is followed by
+its own CRC (over all payload bytes). If the payload is not present (i.e.
+the frame has ``LEN=0``), the CRC of the payload is still present and will
+evaluate to ``0xffff``. The |LEN| field does not include any of the CRCs, it
+equals the number of bytes between the CRC of the frame and the CRC of the
+payload.
+
+Additionally, the following fixed two-byte sequences are used:
+
+.. flat-table:: SSH Byte Sequences
+ :widths: 1 1 4
+ :header-rows: 1
+
+ * - Name
+ - Value
+ - Description
+
+ * - |SYN|
+ - ``[0xAA, 0x55]``
+ - Synchronization bytes.
+
+A message consists of |SYN|, followed by the frame (|TYPE|, |LEN|, |SEQ| and
+CRC) and, if specified in the frame (i.e. ``LEN > 0``), payload bytes,
+followed finally, regardless if the payload is present, the payload CRC. The
+messages corresponding to an exchange are, in part, identified by having the
+same sequence ID (|SEQ|), stored inside the frame (more on this in the next
+section). The sequence ID is a wrapping counter.
+
+A frame can have the following types
+(:c:type:`enum ssh_frame_type <ssh_frame_type>`):
+
+.. flat-table:: SSH Frame Types
+ :widths: 1 1 4
+ :header-rows: 1
+
+ * - Name
+ - Value
+ - Short Description
+
+ * - |NAK|
+ - ``0x04``
+ - Sent on error in previously received message.
+
+ * - |ACK|
+ - ``0x40``
+ - Sent to acknowledge receival of |DATA| frame.
+
+ * - |DATA_SEQ|
+ - ``0x80``
+ - Sent to transfer data. Sequenced.
+
+ * - |DATA_NSQ|
+ - ``0x00``
+ - Same as |DATA_SEQ|, but does not need to be ACKed.
+
+Both |NAK|- and |ACK|-type frames are used to control flow of messages and
+thus do not carry a payload. |DATA_SEQ|- and |DATA_NSQ|-type frames on the
+other hand must carry a payload. The flow sequence and interaction of
+different frame types will be described in more depth in the next section.
+
+
+SSH Packet Protocol: Flow Sequence
+==================================
+
+Each exchange begins with |SYN|, followed by a |DATA_SEQ|- or
+|DATA_NSQ|-type frame, followed by its CRC, payload, and payload CRC. In
+case of a |DATA_NSQ|-type frame, the exchange is then finished. In case of a
+|DATA_SEQ|-type frame, the receiving party has to acknowledge receival of
+the frame by responding with a message containing an |ACK|-type frame with
+the same sequence ID of the |DATA| frame. In other words, the sequence ID of
+the |ACK| frame specifies the |DATA| frame to be acknowledged. In case of an
+error, e.g. an invalid CRC, the receiving party responds with a message
+containing an |NAK|-type frame. As the sequence ID of the previous data
+frame, for which an error is indicated via the |NAK| frame, cannot be relied
+upon, the sequence ID of the |NAK| frame should not be used and is set to
+zero. After receival of an |NAK| frame, the sending party should re-send all
+outstanding (non-ACKed) messages.
+
+Sequence IDs are not synchronized between the two parties, meaning that they
+are managed independently for each party. Identifying the messages
+corresponding to a single exchange thus relies on the sequence ID as well as
+the type of the message, and the context. Specifically, the sequence ID is
+used to associate an ``ACK`` with its ``DATA_SEQ``-type frame, but not
+``DATA_SEQ``- or ``DATA_NSQ``-type frames with other ``DATA``- type frames.
+
+An example exchange might look like this:
+
+::
+
+ tx: -- SYN FRAME(D) CRC(F) PAYLOAD CRC(P) -----------------------------
+ rx: ------------------------------------- SYN FRAME(A) CRC(F) CRC(P) --
+
+where both frames have the same sequence ID (``SEQ``). Here, ``FRAME(D)``
+indicates a |DATA_SEQ|-type frame, ``FRAME(A)`` an ``ACK``-type frame,
+``CRC(F)`` the CRC over the previous frame, ``CRC(P)`` the CRC over the
+previous payload. In case of an error, the exchange would look like this:
+
+::
+
+ tx: -- SYN FRAME(D) CRC(F) PAYLOAD CRC(P) -----------------------------
+ rx: ------------------------------------- SYN FRAME(N) CRC(F) CRC(P) --
+
+upon which the sender should re-send the message. ``FRAME(N)`` indicates an
+|NAK|-type frame. Note that the sequence ID of the |NAK|-type frame is fixed
+to zero. For |DATA_NSQ|-type frames, both exchanges are the same:
+
+::
+
+ tx: -- SYN FRAME(DATA_NSQ) CRC(F) PAYLOAD CRC(P) ----------------------
+ rx: -------------------------------------------------------------------
+
+Here, an error can be detected, but not corrected or indicated to the
+sending party. These exchanges are symmetric, i.e. switching ``rx`` and
+``tx`` results again in a valid exchange. Currently, no longer exchanges are
+known.
+
+
+Commands: Requests, Responses, and Events
+=========================================
+
+Commands are sent as payload inside a data frame. Currently, this is the
+only known payload type of |DATA| frames, with a payload-type value of
+``0x80`` (:c:type:`SSH_PLD_TYPE_CMD <ssh_payload_type>`).
+
+The command-type payload (:c:type:`struct ssh_command <ssh_command>`)
+consists of an eight-byte command structure, followed by optional and
+variable length command data. The length of this optional data is derived
+from the frame payload length given in the corresponding frame, i.e. it is
+``frame.len - sizeof(struct ssh_command)``. The command struct contains the
+following fields, packed together and in order:
+
+.. flat-table:: SSH Command
+ :widths: 1 1 4
+ :header-rows: 1
+
+ * - Field
+ - Type
+ - Description
+
+ * - |TYPE|
+ - |u8|
+ - Type of the payload. For commands always ``0x80``.
+
+ * - |TC|
+ - |u8|
+ - Target category.
+
+ * - |TID|
+ - |u8|
+ - Target ID for commands/messages.
+
+ * - |SID|
+ - |u8|
+ - Source ID for commands/messages.
+
+ * - |IID|
+ - |u8|
+ - Instance ID.
+
+ * - |RQID|
+ - |u16|
+ - Request ID.
+
+ * - |CID|
+ - |u8|
+ - Command ID.
+
+The command struct and data, in general, does not contain any failure
+detection mechanism (e.g. CRCs), this is solely done on the frame level.
+
+Command-type payloads are used by the host to send commands and requests to
+the EC as well as by the EC to send responses and events back to the host.
+We differentiate between requests (sent by the host), responses (sent by the
+EC in response to a request), and events (sent by the EC without a preceding
+request).
+
+Commands and events are uniquely identified by their target category
+(``TC``) and command ID (``CID``). The target category specifies a general
+category for the command (e.g. system in general, vs. battery and AC, vs.
+temperature, and so on), while the command ID specifies the command inside
+that category. Only the combination of |TC| + |CID| is unique. Additionally,
+commands have an instance ID (``IID``), which is used to differentiate
+between different sub-devices. For example ``TC=3`` ``CID=1`` is a
+request to get the temperature on a thermal sensor, where |IID| specifies
+the respective sensor. If the instance ID is not used, it should be set to
+zero. If instance IDs are used, they, in general, start with a value of one,
+whereas zero may be used for instance independent queries, if applicable. A
+response to a request should have the same target category, command ID, and
+instance ID as the corresponding request.
+
+Responses are matched to their corresponding request via the request ID
+(``RQID``) field. This is a 16 bit wrapping counter similar to the sequence
+ID on the frames. Note that the sequence ID of the frames for a
+request-response pair does not match. Only the request ID has to match.
+Frame-protocol wise these are two separate exchanges, and may even be
+separated, e.g. by an event being sent after the request but before the
+response. Not all commands produce a response, and this is not detectable by
+|TC| + |CID|. It is the responsibility of the issuing party to wait for a
+response (or signal this to the communication framework, as is done in
+SAN/ACPI via the ``SNC`` flag).
+
+Events are identified by unique and reserved request IDs. These IDs should
+not be used by the host when sending a new request. They are used on the
+host to, first, detect events and, second, match them with a registered
+event handler. Request IDs for events are chosen by the host and directed to
+the EC when setting up and enabling an event source (via the
+enable-event-source request). The EC then uses the specified request ID for
+events sent from the respective source. Note that an event should still be
+identified by its target category, command ID, and, if applicable, instance
+ID, as a single event source can send multiple different event types. In
+general, however, a single target category should map to a single reserved
+event request ID.
+
+Furthermore, requests, responses, and events have an associated target ID
+(``TID``) and source ID (``SID``). These two fields indicate where a message
+originates from (``SID``) and what the intended target of the message is
+(``TID``). Note that a response to a specific request therefore has the source
+and target IDs swapped when compared to the original request (i.e. the request
+target is the response source and the request source is the response target).
+See (:c:type:`enum ssh_request_id <ssh_request_id>`) for possible values of
+both.
+
+Note that, even though requests and events should be uniquely identifiable by
+target category and command ID alone, the EC may require specific target ID and
+instance ID values to accept a command. A command that is accepted for
+``TID=1``, for example, may not be accepted for ``TID=2`` and vice versa. While
+this may not always hold in reality, you can think of different target/source
+IDs indicating different physical ECs with potentially different feature sets.
+
+
+Limitations and Observations
+============================
+
+The protocol can, in theory, handle up to ``U8_MAX`` frames in parallel,
+with up to ``U16_MAX`` pending requests (neglecting request IDs reserved for
+events). In practice, however, this is more limited. From our testing
+(although via a python and thus a user-space program), it seems that the EC
+can handle up to four requests (mostly) reliably in parallel at a certain
+time. With five or more requests in parallel, consistent discarding of
+commands (ACKed frame but no command response) has been observed. For five
+simultaneous commands, this reproducibly resulted in one command being
+dropped and four commands being handled.
+
+However, it has also been noted that, even with three requests in parallel,
+occasional frame drops happen. Apart from this, with a limit of three
+pending requests, no dropped commands (i.e. command being dropped but frame
+carrying command being ACKed) have been observed. In any case, frames (and
+possibly also commands) should be re-sent by the host if a certain timeout
+is exceeded. This is done by the EC for frames with a timeout of one second,
+up to two re-tries (i.e. three transmissions in total). The limit of
+re-tries also applies to received NAKs, and, in a worst case scenario, can
+lead to entire messages being dropped.
+
+While this also seems to work fine for pending data frames as long as no
+transmission failures occur, implementation and handling of these seems to
+depend on the assumption that there is only one non-acknowledged data frame.
+In particular, the detection of repeated frames relies on the last sequence
+number. This means that, if a frame that has been successfully received by
+the EC is sent again, e.g. due to the host not receiving an |ACK|, the EC
+will only detect this if it has the sequence ID of the last frame received
+by the EC. As an example: Sending two frames with ``SEQ=0`` and ``SEQ=1``
+followed by a repetition of ``SEQ=0`` will not detect the second ``SEQ=0``
+frame as such, and thus execute the command in this frame each time it has
+been received, i.e. twice in this example. Sending ``SEQ=0``, ``SEQ=1`` and
+then repeating ``SEQ=1`` will detect the second ``SEQ=1`` as repetition of
+the first one and ignore it, thus executing the contained command only once.
+
+In conclusion, this suggests a limit of at most one pending un-ACKed frame
+(per party, effectively leading to synchronous communication regarding
+frames) and at most three pending commands. The limit to synchronous frame
+transfers seems to be consistent with behavior observed on Windows.
diff --git a/Documentation/driver-api/target.rst b/Documentation/driver-api/target.rst
index 620ec6173a93..c70ca25171c0 100644
--- a/Documentation/driver-api/target.rst
+++ b/Documentation/driver-api/target.rst
@@ -41,18 +41,6 @@ iSCSI boot information
.. kernel-doc:: drivers/scsi/iscsi_boot_sysfs.c
:export:
-
-iSCSI transport class
-=====================
-
-The file drivers/scsi/scsi_transport_iscsi.c defines transport
-attributes for the iSCSI class, which sends SCSI packets over TCP/IP
-connections.
-
-.. kernel-doc:: drivers/scsi/scsi_transport_iscsi.c
- :export:
-
-
iSCSI TCP interfaces
====================
diff --git a/Documentation/driver-api/tee.rst b/Documentation/driver-api/tee.rst
new file mode 100644
index 000000000000..5eaeb8103988
--- /dev/null
+++ b/Documentation/driver-api/tee.rst
@@ -0,0 +1,66 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+===============================================
+TEE (Trusted Execution Environment) driver API
+===============================================
+
+Kernel provides a TEE bus infrastructure where a Trusted Application is
+represented as a device identified via Universally Unique Identifier (UUID) and
+client drivers register a table of supported device UUIDs.
+
+TEE bus infrastructure registers following APIs:
+
+match():
+ iterates over the client driver UUID table to find a corresponding
+ match for device UUID. If a match is found, then this particular device is
+ probed via corresponding probe API registered by the client driver. This
+ process happens whenever a device or a client driver is registered with TEE
+ bus.
+
+uevent():
+ notifies user-space (udev) whenever a new device is registered on
+ TEE bus for auto-loading of modularized client drivers.
+
+TEE bus device enumeration is specific to underlying TEE implementation, so it
+is left open for TEE drivers to provide corresponding implementation.
+
+Then TEE client driver can talk to a matched Trusted Application using APIs
+listed in include/linux/tee_drv.h.
+
+TEE client driver example
+-------------------------
+
+Suppose a TEE client driver needs to communicate with a Trusted Application
+having UUID: ``ac6a4085-0e82-4c33-bf98-8eb8e118b6c2``, so driver registration
+snippet would look like::
+
+ static const struct tee_client_device_id client_id_table[] = {
+ {UUID_INIT(0xac6a4085, 0x0e82, 0x4c33,
+ 0xbf, 0x98, 0x8e, 0xb8, 0xe1, 0x18, 0xb6, 0xc2)},
+ {}
+ };
+
+ MODULE_DEVICE_TABLE(tee, client_id_table);
+
+ static struct tee_client_driver client_driver = {
+ .id_table = client_id_table,
+ .driver = {
+ .name = DRIVER_NAME,
+ .bus = &tee_bus_type,
+ .probe = client_probe,
+ .remove = client_remove,
+ },
+ };
+
+ static int __init client_init(void)
+ {
+ return driver_register(&client_driver.driver);
+ }
+
+ static void __exit client_exit(void)
+ {
+ driver_unregister(&client_driver.driver);
+ }
+
+ module_init(client_init);
+ module_exit(client_exit);
diff --git a/Documentation/driver-api/thermal/cpu-idle-cooling.rst b/Documentation/driver-api/thermal/cpu-idle-cooling.rst
index a1c3edecae00..c2a7ca676853 100644
--- a/Documentation/driver-api/thermal/cpu-idle-cooling.rst
+++ b/Documentation/driver-api/thermal/cpu-idle-cooling.rst
@@ -1,3 +1,8 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+================
+CPU Idle Cooling
+================
Situation:
----------
@@ -45,7 +50,7 @@ idle state target residency, we lead to dropping the static and the
dynamic leakage for this period (modulo the energy needed to enter
this state). So the sustainable power with idle cycles has a linear
relation with the OPP’s sustainable power and can be computed with a
-coefficient similar to:
+coefficient similar to::
Power(IdleCycle) = Coef x Power(OPP)
@@ -136,7 +141,7 @@ Power considerations
--------------------
When we reach the thermal trip point, we have to sustain a specified
-power for a specific temperature but at this time we consume:
+power for a specific temperature but at this time we consume::
Power = Capacitance x Voltage^2 x Frequency x Utilisation
@@ -145,7 +150,7 @@ wrong in the system setup). The ‘Capacitance’ and ‘Utilisation’ are a
fixed value, ‘Voltage’ and the ‘Frequency’ are fixed artificially
because we don’t want to change the OPP. We can group the
‘Capacitance’ and the ‘Utilisation’ into a single term which is the
-‘Dynamic Power Coefficient (Cdyn)’ Simplifying the above, we have:
+‘Dynamic Power Coefficient (Cdyn)’ Simplifying the above, we have::
Pdyn = Cdyn x Voltage^2 x Frequency
@@ -154,7 +159,7 @@ in order to target the sustainable power defined in the device
tree. So with the idle injection mechanism, we want an average power
(Ptarget) resulting in an amount of time running at full power on a
specific OPP and idle another amount of time. That could be put in a
-equation:
+equation::
P(opp)target = ((Trunning x (P(opp)running) + (Tidle x P(opp)idle)) /
(Trunning + Tidle)
@@ -165,7 +170,7 @@ equation:
At this point if we know the running period for the CPU, that gives us
the idle injection we need. Alternatively if we have the idle
-injection duration, we can compute the running duration with:
+injection duration, we can compute the running duration with::
Trunning = Tidle / ((P(opp)running / P(opp)target) - 1)
@@ -188,7 +193,7 @@ However, in this demonstration we ignore three aspects:
target residency, otherwise we end up consuming more energy and
potentially invert the mitigation effect
-So the final equation is:
+So the final equation is::
Trunning = (Tidle - Twakeup ) x
(((P(opp)dyn + P(opp)static ) - P(opp)target) / P(opp)target )
diff --git a/Documentation/driver-api/thermal/index.rst b/Documentation/driver-api/thermal/index.rst
index 5ba61d19c6ae..a886028014ab 100644
--- a/Documentation/driver-api/thermal/index.rst
+++ b/Documentation/driver-api/thermal/index.rst
@@ -8,11 +8,12 @@ Thermal
:maxdepth: 1
cpu-cooling-api
+ cpu-idle-cooling
sysfs-api
power_allocator
exynos_thermal
exynos_thermal_emulation
- intel_powerclamp
nouveau_thermal
x86_pkg_temperature_thermal
+ intel_dptf
diff --git a/Documentation/driver-api/thermal/intel_dptf.rst b/Documentation/driver-api/thermal/intel_dptf.rst
new file mode 100644
index 000000000000..8fb8c5b2d685
--- /dev/null
+++ b/Documentation/driver-api/thermal/intel_dptf.rst
@@ -0,0 +1,381 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+===============================================================
+Intel(R) Dynamic Platform and Thermal Framework Sysfs Interface
+===============================================================
+
+:Copyright: © 2022 Intel Corporation
+
+:Author: Srinivas Pandruvada <srinivas.pandruvada@linux.intel.com>
+
+Introduction
+------------
+
+Intel(R) Dynamic Platform and Thermal Framework (DPTF) is a platform
+level hardware/software solution for power and thermal management.
+
+As a container for multiple power/thermal technologies, DPTF provides
+a coordinated approach for different policies to effect the hardware
+state of a system.
+
+Since it is a platform level framework, this has several components.
+Some parts of the technology is implemented in the firmware and uses
+ACPI and PCI devices to expose various features for monitoring and
+control. Linux has a set of kernel drivers exposing hardware interface
+to user space. This allows user space thermal solutions like
+"Linux Thermal Daemon" to read platform specific thermal and power
+tables to deliver adequate performance while keeping the system under
+thermal limits.
+
+DPTF ACPI Drivers interface
+----------------------------
+
+:file:`/sys/bus/platform/devices/<N>/uuids`, where <N>
+=INT3400|INTC1040|INTC1041|INTC10A0
+
+``available_uuids`` (RO)
+ A set of UUIDs strings presenting available policies
+ which should be notified to the firmware when the
+ user space can support those policies.
+
+ UUID strings:
+
+ "42A441D6-AE6A-462b-A84B-4A8CE79027D3" : Passive 1
+
+ "3A95C389-E4B8-4629-A526-C52C88626BAE" : Active
+
+ "97C68AE7-15FA-499c-B8C9-5DA81D606E0A" : Critical
+
+ "63BE270F-1C11-48FD-A6F7-3AF253FF3E2D" : Adaptive performance
+
+ "5349962F-71E6-431D-9AE8-0A635B710AEE" : Emergency call
+
+ "9E04115A-AE87-4D1C-9500-0F3E340BFE75" : Passive 2
+
+ "F5A35014-C209-46A4-993A-EB56DE7530A1" : Power Boss
+
+ "6ED722A7-9240-48A5-B479-31EEF723D7CF" : Virtual Sensor
+
+ "16CAF1B7-DD38-40ED-B1C1-1B8A1913D531" : Cooling mode
+
+ "BE84BABF-C4D4-403D-B495-3128FD44dAC1" : HDC
+
+``current_uuid`` (RW)
+ User space can write strings from available UUIDs, one at a
+ time.
+
+:file:`/sys/bus/platform/devices/<N>/`, where <N>
+=INT3400|INTC1040|INTC1041|INTC10A0
+
+``imok`` (WO)
+ User space daemon write 1 to respond to firmware event
+ for sending keep alive notification. User space receives
+ THERMAL_EVENT_KEEP_ALIVE kobject uevent notification when
+ firmware calls for user space to respond with imok ACPI
+ method.
+
+``odvp*`` (RO)
+ Firmware thermal status variable values. Thermal tables
+ calls for different processing based on these variable
+ values.
+
+``data_vault`` (RO)
+ Binary thermal table. Refer to
+ https:/github.com/intel/thermal_daemon for decoding
+ thermal table.
+
+``production_mode`` (RO)
+ When different from zero, manufacturer locked thermal configuration
+ from further changes.
+
+ACPI Thermal Relationship table interface
+------------------------------------------
+
+:file:`/dev/acpi_thermal_rel`
+
+ This device provides IOCTL interface to read standard ACPI
+ thermal relationship tables via ACPI methods _TRT and _ART.
+ These IOCTLs are defined in
+ drivers/thermal/intel/int340x_thermal/acpi_thermal_rel.h
+
+ IOCTLs:
+
+ ACPI_THERMAL_GET_TRT_LEN: Get length of TRT table
+
+ ACPI_THERMAL_GET_ART_LEN: Get length of ART table
+
+ ACPI_THERMAL_GET_TRT_COUNT: Number of records in TRT table
+
+ ACPI_THERMAL_GET_ART_COUNT: Number of records in ART table
+
+ ACPI_THERMAL_GET_TRT: Read binary TRT table, length to read is
+ provided via argument to ioctl().
+
+ ACPI_THERMAL_GET_ART: Read binary ART table, length to read is
+ provided via argument to ioctl().
+
+DPTF ACPI Sensor drivers
+-------------------------
+
+DPTF Sensor drivers are presented as standard thermal sysfs thermal_zone.
+
+
+DPTF ACPI Cooling drivers
+--------------------------
+
+DPTF cooling drivers are presented as standard thermal sysfs cooling_device.
+
+
+DPTF Processor thermal PCI Driver interface
+--------------------------------------------
+
+:file:`/sys/bus/pci/devices/0000\:00\:04.0/power_limits/`
+
+Refer to Documentation/power/powercap/powercap.rst for powercap
+ABI.
+
+``power_limit_0_max_uw`` (RO)
+ Maximum powercap sysfs constraint_0_power_limit_uw for Intel RAPL
+
+``power_limit_0_step_uw`` (RO)
+ Power limit increment/decrements for Intel RAPL constraint 0 power limit
+
+``power_limit_0_min_uw`` (RO)
+ Minimum powercap sysfs constraint_0_power_limit_uw for Intel RAPL
+
+``power_limit_0_tmin_us`` (RO)
+ Minimum powercap sysfs constraint_0_time_window_us for Intel RAPL
+
+``power_limit_0_tmax_us`` (RO)
+ Maximum powercap sysfs constraint_0_time_window_us for Intel RAPL
+
+``power_limit_1_max_uw`` (RO)
+ Maximum powercap sysfs constraint_1_power_limit_uw for Intel RAPL
+
+``power_limit_1_step_uw`` (RO)
+ Power limit increment/decrements for Intel RAPL constraint 1 power limit
+
+``power_limit_1_min_uw`` (RO)
+ Minimum powercap sysfs constraint_1_power_limit_uw for Intel RAPL
+
+``power_limit_1_tmin_us`` (RO)
+ Minimum powercap sysfs constraint_1_time_window_us for Intel RAPL
+
+``power_limit_1_tmax_us`` (RO)
+ Maximum powercap sysfs constraint_1_time_window_us for Intel RAPL
+
+``power_floor_status`` (RO)
+ When set to 1, the power floor of the system in the current
+ configuration has been reached. It needs to be reconfigured to allow
+ power to be reduced any further.
+
+``power_floor_enable`` (RW)
+ When set to 1, enable reading and notification of the power floor
+ status. Notifications are triggered for the power_floor_status
+ attribute value changes.
+
+:file:`/sys/bus/pci/devices/0000\:00\:04.0/`
+
+``tcc_offset_degree_celsius`` (RW)
+ TCC offset from the critical temperature where hardware will throttle
+ CPU.
+
+:file:`/sys/bus/pci/devices/0000\:00\:04.0/workload_request`
+
+``workload_available_types`` (RO)
+ Available workload types. User space can specify one of the workload type
+ it is currently executing via workload_type. For example: idle, bursty,
+ sustained etc.
+
+``workload_type`` (RW)
+ User space can specify any one of the available workload type using
+ this interface.
+
+DPTF Processor thermal RFIM interface
+--------------------------------------------
+
+RFIM interface allows adjustment of FIVR (Fully Integrated Voltage Regulator),
+DDR (Double Data Rate) and DLVR (Digital Linear Voltage Regulator)
+frequencies to avoid RF interference with WiFi and 5G.
+
+Switching voltage regulators (VR) generate radiated EMI or RFI at the
+fundamental frequency and its harmonics. Some harmonics may interfere
+with very sensitive wireless receivers such as Wi-Fi and cellular that
+are integrated into host systems like notebook PCs. One of mitigation
+methods is requesting SOC integrated VR (IVR) switching frequency to a
+small % and shift away the switching noise harmonic interference from
+radio channels. OEM or ODMs can use the driver to control SOC IVR
+operation within the range where it does not impact IVR performance.
+
+Some products use DLVR instead of FIVR as switching voltage regulator.
+In this case attributes of DLVR must be adjusted instead of FIVR.
+
+While shifting the frequencies additional clock noise can be introduced,
+which is compensated by adjusting Spread spectrum percent. This helps
+to reduce the clock noise to meet regulatory compliance. This spreading
+% increases bandwidth of signal transmission and hence reduces the
+effects of interference, noise and signal fading.
+
+DRAM devices of DDR IO interface and their power plane can generate EMI
+at the data rates. Similar to IVR control mechanism, Intel offers a
+mechanism by which DDR data rates can be changed if several conditions
+are met: there is strong RFI interference because of DDR; CPU power
+management has no other restriction in changing DDR data rates;
+PC ODMs enable this feature (real time DDR RFI Mitigation referred to as
+DDR-RFIM) for Wi-Fi from BIOS.
+
+
+FIVR attributes
+
+:file:`/sys/bus/pci/devices/0000\:00\:04.0/fivr/`
+
+``vco_ref_code_lo`` (RW)
+ The VCO reference code is an 11-bit field and controls the FIVR
+ switching frequency. This is the 3-bit LSB field.
+
+``vco_ref_code_hi`` (RW)
+ The VCO reference code is an 11-bit field and controls the FIVR
+ switching frequency. This is the 8-bit MSB field.
+
+``spread_spectrum_pct`` (RW)
+ Set the FIVR spread spectrum clocking percentage
+
+``spread_spectrum_clk_enable`` (RW)
+ Enable/disable of the FIVR spread spectrum clocking feature
+
+``rfi_vco_ref_code`` (RW)
+ This field is a read only status register which reflects the
+ current FIVR switching frequency
+
+``fivr_fffc_rev`` (RW)
+ This field indicated the revision of the FIVR HW.
+
+
+DVFS attributes
+
+:file:`/sys/bus/pci/devices/0000\:00\:04.0/dvfs/`
+
+``rfi_restriction_run_busy`` (RW)
+ Request the restriction of specific DDR data rate and set this
+ value 1. Self reset to 0 after operation.
+
+``rfi_restriction_err_code`` (RW)
+ 0 :Request is accepted, 1:Feature disabled,
+ 2: the request restricts more points than it is allowed
+
+``rfi_restriction_data_rate_Delta`` (RW)
+ Restricted DDR data rate for RFI protection: Lower Limit
+
+``rfi_restriction_data_rate_Base`` (RW)
+ Restricted DDR data rate for RFI protection: Upper Limit
+
+``ddr_data_rate_point_0`` (RO)
+ DDR data rate selection 1st point
+
+``ddr_data_rate_point_1`` (RO)
+ DDR data rate selection 2nd point
+
+``ddr_data_rate_point_2`` (RO)
+ DDR data rate selection 3rd point
+
+``ddr_data_rate_point_3`` (RO)
+ DDR data rate selection 4th point
+
+``rfi_disable (RW)``
+ Disable DDR rate change feature
+
+DLVR attributes
+
+:file:`/sys/bus/pci/devices/0000\:00\:04.0/dlvr/`
+
+``dlvr_hardware_rev`` (RO)
+ DLVR hardware revision.
+
+``dlvr_freq_mhz`` (RO)
+ Current DLVR PLL frequency in MHz.
+
+``dlvr_freq_select`` (RW)
+ Sets DLVR PLL clock frequency. Once set, and enabled via
+ dlvr_rfim_enable, the dlvr_freq_mhz will show the current
+ DLVR PLL frequency.
+
+``dlvr_pll_busy`` (RO)
+ PLL can't accept frequency change when set.
+
+``dlvr_rfim_enable`` (RW)
+ 0: Disable RF frequency hopping, 1: Enable RF frequency hopping.
+
+``dlvr_spread_spectrum_pct`` (RW)
+ Sets DLVR spread spectrum percent value.
+
+``dlvr_control_mode`` (RW)
+ Specifies how frequencies are spread using spread spectrum.
+ 0: Down spread,
+ 1: Spread in the Center.
+
+``dlvr_control_lock`` (RW)
+ 1: future writes are ignored.
+
+DPTF Power supply and Battery Interface
+----------------------------------------
+
+Refer to Documentation/ABI/testing/sysfs-platform-dptf
+
+DPTF Fan Control
+----------------------------------------
+
+Refer to Documentation/admin-guide/acpi/fan_performance_states.rst
+
+Workload Type Hints
+----------------------------------------
+
+The firmware in Meteor Lake processor generation is capable of identifying
+workload type and passing hints regarding it to the OS. A special sysfs
+interface is provided to allow user space to obtain workload type hints from
+the firmware and control the rate at which they are provided.
+
+User space can poll attribute "workload_type_index" for the current hint or
+can receive a notification whenever the value of this attribute is updated.
+
+file:`/sys/bus/pci/devices/0000:00:04.0/workload_hint/`
+Segment 0, bus 0, device 4, function 0 is reserved for the processor thermal
+device on all Intel client processors. So, the above path doesn't change
+based on the processor generation.
+
+``workload_hint_enable`` (RW)
+ Enable firmware to send workload type hints to user space.
+
+``notification_delay_ms`` (RW)
+ Minimum delay in milliseconds before firmware will notify OS. This is
+ for the rate control of notifications. This delay is between changing
+ the workload type prediction in the firmware and notifying the OS about
+ the change. The default delay is 1024 ms. The delay of 0 is invalid.
+ The delay is rounded up to the nearest power of 2 to simplify firmware
+ programming of the delay value. The read of notification_delay_ms
+ attribute shows the effective value used.
+
+``workload_type_index`` (RO)
+ Predicted workload type index. User space can get notification of
+ change via existing sysfs attribute change notification mechanism.
+
+ The supported index values and their meaning for the Meteor Lake
+ processor generation are as follows:
+
+ 0 - Idle: System performs no tasks, power and idle residency are
+ consistently low for long periods of time.
+
+ 1 – Battery Life: Power is relatively low, but the processor may
+ still be actively performing a task, such as video playback for
+ a long period of time.
+
+ 2 – Sustained: Power level that is relatively high for a long period
+ of time, with very few to no periods of idleness, which will
+ eventually exhaust RAPL Power Limit 1 and 2.
+
+ 3 – Bursty: Consumes a relatively constant average amount of power, but
+ periods of relative idleness are interrupted by bursts of
+ activity. The bursts are relatively short and the periods of
+ relative idleness between them typically prevent RAPL Power
+ Limit 1 from being exhausted.
+
+ 4 – Unknown: Can't classify.
diff --git a/Documentation/driver-api/thermal/intel_powerclamp.rst b/Documentation/driver-api/thermal/intel_powerclamp.rst
deleted file mode 100644
index 3f6dfb0b3ea6..000000000000
--- a/Documentation/driver-api/thermal/intel_powerclamp.rst
+++ /dev/null
@@ -1,320 +0,0 @@
-=======================
-Intel Powerclamp Driver
-=======================
-
-By:
- - Arjan van de Ven <arjan@linux.intel.com>
- - Jacob Pan <jacob.jun.pan@linux.intel.com>
-
-.. Contents:
-
- (*) Introduction
- - Goals and Objectives
-
- (*) Theory of Operation
- - Idle Injection
- - Calibration
-
- (*) Performance Analysis
- - Effectiveness and Limitations
- - Power vs Performance
- - Scalability
- - Calibration
- - Comparison with Alternative Techniques
-
- (*) Usage and Interfaces
- - Generic Thermal Layer (sysfs)
- - Kernel APIs (TBD)
-
-INTRODUCTION
-============
-
-Consider the situation where a system’s power consumption must be
-reduced at runtime, due to power budget, thermal constraint, or noise
-level, and where active cooling is not preferred. Software managed
-passive power reduction must be performed to prevent the hardware
-actions that are designed for catastrophic scenarios.
-
-Currently, P-states, T-states (clock modulation), and CPU offlining
-are used for CPU throttling.
-
-On Intel CPUs, C-states provide effective power reduction, but so far
-they’re only used opportunistically, based on workload. With the
-development of intel_powerclamp driver, the method of synchronizing
-idle injection across all online CPU threads was introduced. The goal
-is to achieve forced and controllable C-state residency.
-
-Test/Analysis has been made in the areas of power, performance,
-scalability, and user experience. In many cases, clear advantage is
-shown over taking the CPU offline or modulating the CPU clock.
-
-
-THEORY OF OPERATION
-===================
-
-Idle Injection
---------------
-
-On modern Intel processors (Nehalem or later), package level C-state
-residency is available in MSRs, thus also available to the kernel.
-
-These MSRs are::
-
- #define MSR_PKG_C2_RESIDENCY 0x60D
- #define MSR_PKG_C3_RESIDENCY 0x3F8
- #define MSR_PKG_C6_RESIDENCY 0x3F9
- #define MSR_PKG_C7_RESIDENCY 0x3FA
-
-If the kernel can also inject idle time to the system, then a
-closed-loop control system can be established that manages package
-level C-state. The intel_powerclamp driver is conceived as such a
-control system, where the target set point is a user-selected idle
-ratio (based on power reduction), and the error is the difference
-between the actual package level C-state residency ratio and the target idle
-ratio.
-
-Injection is controlled by high priority kernel threads, spawned for
-each online CPU.
-
-These kernel threads, with SCHED_FIFO class, are created to perform
-clamping actions of controlled duty ratio and duration. Each per-CPU
-thread synchronizes its idle time and duration, based on the rounding
-of jiffies, so accumulated errors can be prevented to avoid a jittery
-effect. Threads are also bound to the CPU such that they cannot be
-migrated, unless the CPU is taken offline. In this case, threads
-belong to the offlined CPUs will be terminated immediately.
-
-Running as SCHED_FIFO and relatively high priority, also allows such
-scheme to work for both preemptable and non-preemptable kernels.
-Alignment of idle time around jiffies ensures scalability for HZ
-values. This effect can be better visualized using a Perf timechart.
-The following diagram shows the behavior of kernel thread
-kidle_inject/cpu. During idle injection, it runs monitor/mwait idle
-for a given "duration", then relinquishes the CPU to other tasks,
-until the next time interval.
-
-The NOHZ schedule tick is disabled during idle time, but interrupts
-are not masked. Tests show that the extra wakeups from scheduler tick
-have a dramatic impact on the effectiveness of the powerclamp driver
-on large scale systems (Westmere system with 80 processors).
-
-::
-
- CPU0
- ____________ ____________
- kidle_inject/0 | sleep | mwait | sleep |
- _________| |________| |_______
- duration
- CPU1
- ____________ ____________
- kidle_inject/1 | sleep | mwait | sleep |
- _________| |________| |_______
- ^
- |
- |
- roundup(jiffies, interval)
-
-Only one CPU is allowed to collect statistics and update global
-control parameters. This CPU is referred to as the controlling CPU in
-this document. The controlling CPU is elected at runtime, with a
-policy that favors BSP, taking into account the possibility of a CPU
-hot-plug.
-
-In terms of dynamics of the idle control system, package level idle
-time is considered largely as a non-causal system where its behavior
-cannot be based on the past or current input. Therefore, the
-intel_powerclamp driver attempts to enforce the desired idle time
-instantly as given input (target idle ratio). After injection,
-powerclamp monitors the actual idle for a given time window and adjust
-the next injection accordingly to avoid over/under correction.
-
-When used in a causal control system, such as a temperature control,
-it is up to the user of this driver to implement algorithms where
-past samples and outputs are included in the feedback. For example, a
-PID-based thermal controller can use the powerclamp driver to
-maintain a desired target temperature, based on integral and
-derivative gains of the past samples.
-
-
-
-Calibration
------------
-During scalability testing, it is observed that synchronized actions
-among CPUs become challenging as the number of cores grows. This is
-also true for the ability of a system to enter package level C-states.
-
-To make sure the intel_powerclamp driver scales well, online
-calibration is implemented. The goals for doing such a calibration
-are:
-
-a) determine the effective range of idle injection ratio
-b) determine the amount of compensation needed at each target ratio
-
-Compensation to each target ratio consists of two parts:
-
- a) steady state error compensation
- This is to offset the error occurring when the system can
- enter idle without extra wakeups (such as external interrupts).
-
- b) dynamic error compensation
- When an excessive amount of wakeups occurs during idle, an
- additional idle ratio can be added to quiet interrupts, by
- slowing down CPU activities.
-
-A debugfs file is provided for the user to examine compensation
-progress and results, such as on a Westmere system::
-
- [jacob@nex01 ~]$ cat
- /sys/kernel/debug/intel_powerclamp/powerclamp_calib
- controlling cpu: 0
- pct confidence steady dynamic (compensation)
- 0 0 0 0
- 1 1 0 0
- 2 1 1 0
- 3 3 1 0
- 4 3 1 0
- 5 3 1 0
- 6 3 1 0
- 7 3 1 0
- 8 3 1 0
- ...
- 30 3 2 0
- 31 3 2 0
- 32 3 1 0
- 33 3 2 0
- 34 3 1 0
- 35 3 2 0
- 36 3 1 0
- 37 3 2 0
- 38 3 1 0
- 39 3 2 0
- 40 3 3 0
- 41 3 1 0
- 42 3 2 0
- 43 3 1 0
- 44 3 1 0
- 45 3 2 0
- 46 3 3 0
- 47 3 0 0
- 48 3 2 0
- 49 3 3 0
-
-Calibration occurs during runtime. No offline method is available.
-Steady state compensation is used only when confidence levels of all
-adjacent ratios have reached satisfactory level. A confidence level
-is accumulated based on clean data collected at runtime. Data
-collected during a period without extra interrupts is considered
-clean.
-
-To compensate for excessive amounts of wakeup during idle, additional
-idle time is injected when such a condition is detected. Currently,
-we have a simple algorithm to double the injection ratio. A possible
-enhancement might be to throttle the offending IRQ, such as delaying
-EOI for level triggered interrupts. But it is a challenge to be
-non-intrusive to the scheduler or the IRQ core code.
-
-
-CPU Online/Offline
-------------------
-Per-CPU kernel threads are started/stopped upon receiving
-notifications of CPU hotplug activities. The intel_powerclamp driver
-keeps track of clamping kernel threads, even after they are migrated
-to other CPUs, after a CPU offline event.
-
-
-Performance Analysis
-====================
-This section describes the general performance data collected on
-multiple systems, including Westmere (80P) and Ivy Bridge (4P, 8P).
-
-Effectiveness and Limitations
------------------------------
-The maximum range that idle injection is allowed is capped at 50
-percent. As mentioned earlier, since interrupts are allowed during
-forced idle time, excessive interrupts could result in less
-effectiveness. The extreme case would be doing a ping -f to generated
-flooded network interrupts without much CPU acknowledgement. In this
-case, little can be done from the idle injection threads. In most
-normal cases, such as scp a large file, applications can be throttled
-by the powerclamp driver, since slowing down the CPU also slows down
-network protocol processing, which in turn reduces interrupts.
-
-When control parameters change at runtime by the controlling CPU, it
-may take an additional period for the rest of the CPUs to catch up
-with the changes. During this time, idle injection is out of sync,
-thus not able to enter package C- states at the expected ratio. But
-this effect is minor, in that in most cases change to the target
-ratio is updated much less frequently than the idle injection
-frequency.
-
-Scalability
------------
-Tests also show a minor, but measurable, difference between the 4P/8P
-Ivy Bridge system and the 80P Westmere server under 50% idle ratio.
-More compensation is needed on Westmere for the same amount of
-target idle ratio. The compensation also increases as the idle ratio
-gets larger. The above reason constitutes the need for the
-calibration code.
-
-On the IVB 8P system, compared to an offline CPU, powerclamp can
-achieve up to 40% better performance per watt. (measured by a spin
-counter summed over per CPU counting threads spawned for all running
-CPUs).
-
-Usage and Interfaces
-====================
-The powerclamp driver is registered to the generic thermal layer as a
-cooling device. Currently, it’s not bound to any thermal zones::
-
- jacob@chromoly:/sys/class/thermal/cooling_device14$ grep . *
- cur_state:0
- max_state:50
- type:intel_powerclamp
-
-cur_state allows user to set the desired idle percentage. Writing 0 to
-cur_state will stop idle injection. Writing a value between 1 and
-max_state will start the idle injection. Reading cur_state returns the
-actual and current idle percentage. This may not be the same value
-set by the user in that current idle percentage depends on workload
-and includes natural idle. When idle injection is disabled, reading
-cur_state returns value -1 instead of 0 which is to avoid confusing
-100% busy state with the disabled state.
-
-Example usage:
-- To inject 25% idle time::
-
- $ sudo sh -c "echo 25 > /sys/class/thermal/cooling_device80/cur_state
-
-If the system is not busy and has more than 25% idle time already,
-then the powerclamp driver will not start idle injection. Using Top
-will not show idle injection kernel threads.
-
-If the system is busy (spin test below) and has less than 25% natural
-idle time, powerclamp kernel threads will do idle injection. Forced
-idle time is accounted as normal idle in that common code path is
-taken as the idle task.
-
-In this example, 24.1% idle is shown. This helps the system admin or
-user determine the cause of slowdown, when a powerclamp driver is in action::
-
-
- Tasks: 197 total, 1 running, 196 sleeping, 0 stopped, 0 zombie
- Cpu(s): 71.2%us, 4.7%sy, 0.0%ni, 24.1%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
- Mem: 3943228k total, 1689632k used, 2253596k free, 74960k buffers
- Swap: 4087804k total, 0k used, 4087804k free, 945336k cached
-
- PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
- 3352 jacob 20 0 262m 644 428 S 286 0.0 0:17.16 spin
- 3341 root -51 0 0 0 0 D 25 0.0 0:01.62 kidle_inject/0
- 3344 root -51 0 0 0 0 D 25 0.0 0:01.60 kidle_inject/3
- 3342 root -51 0 0 0 0 D 25 0.0 0:01.61 kidle_inject/1
- 3343 root -51 0 0 0 0 D 25 0.0 0:01.60 kidle_inject/2
- 2935 jacob 20 0 696m 125m 35m S 5 3.3 0:31.11 firefox
- 1546 root 20 0 158m 20m 6640 S 3 0.5 0:26.97 Xorg
- 2100 jacob 20 0 1223m 88m 30m S 3 2.3 0:23.68 compiz
-
-Tests have shown that by using the powerclamp driver as a cooling
-device, a PID based userspace thermal controller can manage to
-control CPU temperature effectively, when no other thermal influence
-is added. For example, a UltraBook user can compile the kernel under
-certain temperature (below most active trip points).
diff --git a/Documentation/driver-api/thermal/nouveau_thermal.rst b/Documentation/driver-api/thermal/nouveau_thermal.rst
index 37255fd6735d..aa10db6df309 100644
--- a/Documentation/driver-api/thermal/nouveau_thermal.rst
+++ b/Documentation/driver-api/thermal/nouveau_thermal.rst
@@ -90,7 +90,7 @@ Bug reports
-----------
Thermal management on Nouveau is new and may not work on all cards. If you have
-inquiries, please ping mupuf on IRC (#nouveau, freenode).
+inquiries, please ping mupuf on IRC (#nouveau, OFTC).
Bug reports should be filled on Freedesktop's bug tracker. Please follow
-http://nouveau.freedesktop.org/wiki/Bugs
+https://nouveau.freedesktop.org/wiki/Bugs
diff --git a/Documentation/driver-api/thermal/power_allocator.rst b/Documentation/driver-api/thermal/power_allocator.rst
index 67b6a3297238..aa5f66552d6f 100644
--- a/Documentation/driver-api/thermal/power_allocator.rst
+++ b/Documentation/driver-api/thermal/power_allocator.rst
@@ -71,7 +71,9 @@ to the speed-grade of the silicon. `sustainable_power` is therefore
simply an estimate, and may be tuned to affect the aggressiveness of
the thermal ramp. For reference, the sustainable power of a 4" phone
is typically 2000mW, while on a 10" tablet is around 4500mW (may vary
-depending on screen size).
+depending on screen size). It is possible to have the power value
+expressed in an abstract scale. The sustained power should be aligned
+to the scale used by the related cooling devices.
If you are using device tree, do add it as a property of the
thermal-zone. For example::
@@ -269,3 +271,11 @@ won't be very good. Note that this is not particular to this
governor, step-wise will also misbehave if you call its throttle()
faster than the normal thermal framework tick (due to interrupts for
example) as it will overreact.
+
+Energy Model requirements
+=========================
+
+Another important thing is the consistent scale of the power values
+provided by the cooling devices. All of the cooling devices in a single
+thermal zone should have power values reported either in milli-Watts
+or scaled to the same 'abstract scale'.
diff --git a/Documentation/driver-api/thermal/sysfs-api.rst b/Documentation/driver-api/thermal/sysfs-api.rst
index b40b1f839148..6c1175c6afba 100644
--- a/Documentation/driver-api/thermal/sysfs-api.rst
+++ b/Documentation/driver-api/thermal/sysfs-api.rst
@@ -54,7 +54,7 @@ temperature) and throttle appropriate devices.
trips:
the total number of trip points this thermal zone supports.
mask:
- Bit string: If 'n'th bit is set, then trip point 'n' is writeable.
+ Bit string: If 'n'th bit is set, then trip point 'n' is writable.
devdata:
device private data
ops:
@@ -306,42 +306,6 @@ temperature) and throttle appropriate devices.
::
- struct thermal_bind_params
-
- This structure defines the following parameters that are used to bind
- a zone with a cooling device for a particular trip point.
-
- .cdev:
- The cooling device pointer
- .weight:
- The 'influence' of a particular cooling device on this
- zone. This is relative to the rest of the cooling
- devices. For example, if all cooling devices have a
- weight of 1, then they all contribute the same. You can
- use percentages if you want, but it's not mandatory. A
- weight of 0 means that this cooling device doesn't
- contribute to the cooling of this zone unless all cooling
- devices have a weight of 0. If all weights are 0, then
- they all contribute the same.
- .trip_mask:
- This is a bit mask that gives the binding relation between
- this thermal zone and cdev, for a particular trip point.
- If nth bit is set, then the cdev and thermal zone are bound
- for trip point n.
- .binding_limits:
- This is an array of cooling state limits. Must have
- exactly 2 * thermal_zone.number_of_trip_points. It is an
- array consisting of tuples <lower-state upper-state> of
- state limits. Each trip will be associated with one state
- limit tuple when binding. A NULL pointer means
- <THERMAL_NO_LIMITS THERMAL_NO_LIMITS> on all trips.
- These limits are used when binding a cdev to a trip point.
- .match:
- This call back returns success(0) if the 'tz and cdev' need to
- be bound, as per platform data.
-
- ::
-
struct thermal_zone_params
This structure defines the platform level parameters for a thermal zone.
@@ -357,10 +321,6 @@ temperature) and throttle appropriate devices.
will be created. when no_hwmon == true, nothing will be done.
In case the thermal_zone_params is NULL, the hwmon interface
will be created (for backward compatibility).
- .num_tbps:
- Number of thermal_bind_params entries for this zone
- .tbp:
- thermal_bind_params entries
2. sysfs attributes structure
=============================
@@ -406,7 +366,7 @@ Thermal cooling device sys I/F, created once it's registered::
|---stats/reset: Writing any value resets the statistics
|---stats/time_in_state_ms: Time (msec) spent in various cooling states
|---stats/total_trans: Total number of times cooling state is changed
- |---stats/trans_table: Cooing state transition table
+ |---stats/trans_table: Cooling state transition table
Then next two dynamic attributes are created/removed in pairs. They represent
@@ -428,6 +388,9 @@ of thermal zone device. E.g. the generic thermal driver registers one hwmon
class device and build the associated hwmon sysfs I/F for all the registered
ACPI thermal zones.
+Please read Documentation/ABI/testing/sysfs-class-thermal for thermal
+zone and cooling device attribute details.
+
::
/sys/class/hwmon/hwmon[0-*]:
@@ -437,242 +400,6 @@ ACPI thermal zones.
Please read Documentation/hwmon/sysfs-interface.rst for additional information.
-Thermal zone attributes
------------------------
-
-type
- Strings which represent the thermal zone type.
- This is given by thermal zone driver as part of registration.
- E.g: "acpitz" indicates it's an ACPI thermal device.
- In order to keep it consistent with hwmon sys attribute; this should
- be a short, lowercase string, not containing spaces nor dashes.
- RO, Required
-
-temp
- Current temperature as reported by thermal zone (sensor).
- Unit: millidegree Celsius
- RO, Required
-
-mode
- One of the predefined values in [enabled, disabled].
- This file gives information about the algorithm that is currently
- managing the thermal zone. It can be either default kernel based
- algorithm or user space application.
-
- enabled
- enable Kernel Thermal management.
- disabled
- Preventing kernel thermal zone driver actions upon
- trip points so that user application can take full
- charge of the thermal management.
-
- RW, Optional
-
-policy
- One of the various thermal governors used for a particular zone.
-
- RW, Required
-
-available_policies
- Available thermal governors which can be used for a particular zone.
-
- RO, Required
-
-`trip_point_[0-*]_temp`
- The temperature above which trip point will be fired.
-
- Unit: millidegree Celsius
-
- RO, Optional
-
-`trip_point_[0-*]_type`
- Strings which indicate the type of the trip point.
-
- E.g. it can be one of critical, hot, passive, `active[0-*]` for ACPI
- thermal zone.
-
- RO, Optional
-
-`trip_point_[0-*]_hyst`
- The hysteresis value for a trip point, represented as an integer
- Unit: Celsius
- RW, Optional
-
-`cdev[0-*]`
- Sysfs link to the thermal cooling device node where the sys I/F
- for cooling device throttling control represents.
-
- RO, Optional
-
-`cdev[0-*]_trip_point`
- The trip point in this thermal zone which `cdev[0-*]` is associated
- with; -1 means the cooling device is not associated with any trip
- point.
-
- RO, Optional
-
-`cdev[0-*]_weight`
- The influence of `cdev[0-*]` in this thermal zone. This value
- is relative to the rest of cooling devices in the thermal
- zone. For example, if a cooling device has a weight double
- than that of other, it's twice as effective in cooling the
- thermal zone.
-
- RW, Optional
-
-passive
- Attribute is only present for zones in which the passive cooling
- policy is not supported by native thermal driver. Default is zero
- and can be set to a temperature (in millidegrees) to enable a
- passive trip point for the zone. Activation is done by polling with
- an interval of 1 second.
-
- Unit: millidegrees Celsius
-
- Valid values: 0 (disabled) or greater than 1000
-
- RW, Optional
-
-emul_temp
- Interface to set the emulated temperature method in thermal zone
- (sensor). After setting this temperature, the thermal zone may pass
- this temperature to platform emulation function if registered or
- cache it locally. This is useful in debugging different temperature
- threshold and its associated cooling action. This is write only node
- and writing 0 on this node should disable emulation.
- Unit: millidegree Celsius
-
- WO, Optional
-
- WARNING:
- Be careful while enabling this option on production systems,
- because userland can easily disable the thermal policy by simply
- flooding this sysfs node with low temperature values.
-
-sustainable_power
- An estimate of the sustained power that can be dissipated by
- the thermal zone. Used by the power allocator governor. For
- more information see Documentation/driver-api/thermal/power_allocator.rst
-
- Unit: milliwatts
-
- RW, Optional
-
-k_po
- The proportional term of the power allocator governor's PID
- controller during temperature overshoot. Temperature overshoot
- is when the current temperature is above the "desired
- temperature" trip point. For more information see
- Documentation/driver-api/thermal/power_allocator.rst
-
- RW, Optional
-
-k_pu
- The proportional term of the power allocator governor's PID
- controller during temperature undershoot. Temperature undershoot
- is when the current temperature is below the "desired
- temperature" trip point. For more information see
- Documentation/driver-api/thermal/power_allocator.rst
-
- RW, Optional
-
-k_i
- The integral term of the power allocator governor's PID
- controller. This term allows the PID controller to compensate
- for long term drift. For more information see
- Documentation/driver-api/thermal/power_allocator.rst
-
- RW, Optional
-
-k_d
- The derivative term of the power allocator governor's PID
- controller. For more information see
- Documentation/driver-api/thermal/power_allocator.rst
-
- RW, Optional
-
-integral_cutoff
- Temperature offset from the desired temperature trip point
- above which the integral term of the power allocator
- governor's PID controller starts accumulating errors. For
- example, if integral_cutoff is 0, then the integral term only
- accumulates error when temperature is above the desired
- temperature trip point. For more information see
- Documentation/driver-api/thermal/power_allocator.rst
-
- Unit: millidegree Celsius
-
- RW, Optional
-
-slope
- The slope constant used in a linear extrapolation model
- to determine a hotspot temperature based off the sensor's
- raw readings. It is up to the device driver to determine
- the usage of these values.
-
- RW, Optional
-
-offset
- The offset constant used in a linear extrapolation model
- to determine a hotspot temperature based off the sensor's
- raw readings. It is up to the device driver to determine
- the usage of these values.
-
- RW, Optional
-
-Cooling device attributes
--------------------------
-
-type
- String which represents the type of device, e.g:
-
- - for generic ACPI: should be "Fan", "Processor" or "LCD"
- - for memory controller device on intel_menlow platform:
- should be "Memory controller".
-
- RO, Required
-
-max_state
- The maximum permissible cooling state of this cooling device.
-
- RO, Required
-
-cur_state
- The current cooling state of this cooling device.
- The value can any integer numbers between 0 and max_state:
-
- - cur_state == 0 means no cooling
- - cur_state == max_state means the maximum cooling.
-
- RW, Required
-
-stats/reset
- Writing any value resets the cooling device's statistics.
- WO, Required
-
-stats/time_in_state_ms:
- The amount of time spent by the cooling device in various cooling
- states. The output will have "<state> <time>" pair in each line, which
- will mean this cooling device spent <time> msec of time at <state>.
- Output will have one line for each of the supported states. usertime
- units here is 10mS (similar to other time exported in /proc).
- RO, Required
-
-
-stats/total_trans:
- A single positive value showing the total number of times the state of a
- cooling device is changed.
-
- RO, Required
-
-stats/trans_table:
- This gives fine grained information about all the cooling state
- transitions. The cat output here is a two dimensional matrix, where an
- entry <i,j> (row i, column j) represents the number of transitions from
- State_i to State_j. If the transition table is bigger than PAGE_SIZE,
- reading this will return an -EFBIG error.
- RO, Required
-
3. A simple implementation
==========================
@@ -744,17 +471,7 @@ This function returns the thermal_instance corresponding to a given
{thermal_zone, cooling_device, trip_point} combination. Returns NULL
if such an instance does not exist.
-4.3. thermal_notify_framework
------------------------------
-
-This function handles the trip events from sensor drivers. It starts
-throttling the cooling devices according to the policy configured.
-For CRITICAL and HOT trip points, this notifies the respective drivers,
-and does actual throttling for other trip points i.e ACTIVE and PASSIVE.
-The throttling policy is based on the configured platform data; if no
-platform data is provided, this uses the step_wise throttling policy.
-
-4.4. thermal_cdev_update
+4.3. thermal_cdev_update
------------------------
This function serves as an arbitrator to set the state of a cooling
@@ -764,21 +481,15 @@ possible.
5. thermal_emergency_poweroff
=============================
-On an event of critical trip temperature crossing. Thermal framework
-allows the system to shutdown gracefully by calling orderly_poweroff().
-In the event of a failure of orderly_poweroff() to shut down the system
-we are in danger of keeping the system alive at undesirably high
-temperatures. To mitigate this high risk scenario we program a work
-queue to fire after a pre-determined number of seconds to start
-an emergency shutdown of the device using the kernel_power_off()
-function. In case kernel_power_off() fails then finally
-emergency_restart() is called in the worst case.
+On an event of critical trip temperature crossing the thermal framework
+shuts down the system by calling hw_protection_shutdown(). The
+hw_protection_shutdown() first attempts to perform an orderly shutdown
+but accepts a delay after which it proceeds doing a forced power-off
+or as last resort an emergency_restart.
The delay should be carefully profiled so as to give adequate time for
-orderly_poweroff(). In case of failure of an orderly_poweroff() the
-emergency poweroff kicks in after the delay has elapsed and shuts down
-the system.
+orderly poweroff.
-If set to 0 emergency poweroff will not be supported. So a carefully
-profiled non-zero positive value is a must for emergerncy poweroff to be
-triggered.
+If the delay is set to 0 emergency poweroff will not be supported. So a
+carefully profiled non-zero positive value is a must for emergency
+poweroff to be triggered.
diff --git a/Documentation/driver-api/tty/index.rst b/Documentation/driver-api/tty/index.rst
new file mode 100644
index 000000000000..b490da11f257
--- /dev/null
+++ b/Documentation/driver-api/tty/index.rst
@@ -0,0 +1,74 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+===
+TTY
+===
+
+Teletypewriter (TTY) layer takes care of all those serial devices. Including
+the virtual ones like pseudoterminal (PTY).
+
+TTY structures
+==============
+
+There are several major TTY structures. Every TTY device in a system has a
+corresponding struct tty_port. These devices are maintained by a TTY driver
+which is struct tty_driver. This structure describes the driver but also
+contains a reference to operations which could be performed on the TTYs. It is
+struct tty_operations. Then, upon open, a struct tty_struct is allocated and
+lives until the final close. During this time, several callbacks from struct
+tty_operations are invoked by the TTY layer.
+
+Every character received by the kernel (both from devices and users) is passed
+through a preselected :doc:`tty_ldisc` (in
+short ldisc; in C, struct tty_ldisc_ops). Its task is to transform characters
+as defined by a particular ldisc or by user too. The default one is n_tty,
+implementing echoes, signal handling, jobs control, special characters
+processing, and more. The transformed characters are passed further to
+user/device, depending on the source.
+
+In-detail description of the named TTY structures is in separate documents:
+
+.. toctree::
+ :maxdepth: 2
+
+ tty_driver
+ tty_port
+ tty_struct
+ tty_ldisc
+ tty_buffer
+ tty_ioctl
+ tty_internals
+
+Writing TTY Driver
+==================
+
+Before one starts writing a TTY driver, they must consider
+:doc:`Serial <../serial/driver>` and :doc:`USB Serial <../../usb/usb-serial>`
+layers first. Drivers for serial devices can often use one of these specific
+layers to implement a serial driver. Only special devices should be handled
+directly by the TTY Layer. If you are about to write such a driver, read on.
+
+A *typical* sequence a TTY driver performs is as follows:
+
+#. Allocate and register a TTY driver (module init)
+#. Create and register TTY devices as they are probed (probe function)
+#. Handle TTY operations and events like interrupts (TTY core invokes the
+ former, the device the latter)
+#. Remove devices as they are going away (remove function)
+#. Unregister and free the TTY driver (module exit)
+
+Steps regarding driver, i.e. 1., 3., and 5. are described in detail in
+:doc:`tty_driver`. For the other two (devices handling), look into
+:doc:`tty_port`.
+
+Other Documentation
+===================
+
+Miscellaneous documentation can be further found in these documents:
+
+.. toctree::
+ :maxdepth: 2
+
+ moxa-smartio
+ n_gsm
+ n_tty
diff --git a/Documentation/driver-api/tty/moxa-smartio.rst b/Documentation/driver-api/tty/moxa-smartio.rst
new file mode 100644
index 000000000000..af25bc5cc3e6
--- /dev/null
+++ b/Documentation/driver-api/tty/moxa-smartio.rst
@@ -0,0 +1,197 @@
+=============================================================
+MOXA Smartio/Industio Family Device Driver Installation Guide
+=============================================================
+
+Copyright (C) 2008, Moxa Inc.
+Copyright (C) 2021, Jiri Slaby
+
+.. Content
+
+ 1. Introduction
+ 2. System Requirement
+ 3. Installation
+ 3.1 Hardware installation
+ 3.2 Device naming convention
+ 4. Utilities
+ 5. Setserial
+ 6. Troubleshooting
+
+1. Introduction
+^^^^^^^^^^^^^^^
+
+ The Smartio/Industio/UPCI family Linux driver supports following multiport
+ boards:
+
+ - 2 ports multiport board
+ CP-102U, CP-102UL, CP-102UF
+ CP-132U-I, CP-132UL,
+ CP-132, CP-132I, CP132S, CP-132IS,
+ (CP-102, CP-102S)
+
+ - 4 ports multiport board
+ CP-104EL,
+ CP-104UL, CP-104JU,
+ CP-134U, CP-134U-I,
+ C104H/PCI, C104HS/PCI,
+ CP-114, CP-114I, CP-114S, CP-114IS, CP-114UL,
+ (C114HI, CT-114I),
+ POS-104UL,
+ CB-114,
+ CB-134I
+
+ - 8 ports multiport board
+ CP-118EL, CP-168EL,
+ CP-118U, CP-168U,
+ C168H/PCI,
+ CB-108
+
+ If a compatibility problem occurs, please contact Moxa at
+ support@moxa.com.tw.
+
+ In addition to device driver, useful utilities are also provided in this
+ version. They are:
+
+ - msdiag
+ Diagnostic program for displaying installed Moxa
+ Smartio/Industio boards.
+ - msmon
+ Monitor program to observe data count and line status signals.
+ - msterm A simple terminal program which is useful in testing serial
+ ports.
+
+ All the drivers and utilities are published in form of source code under
+ GNU General Public License in this version. Please refer to GNU General
+ Public License announcement in each source code file for more detail.
+
+ In Moxa's Web sites, you may always find the latest driver at
+ https://www.moxa.com/.
+
+ This version of driver can be installed as a Loadable Module (Module driver)
+ or built-in into kernel (Static driver). Before you install the driver,
+ please refer to hardware installation procedure in the User's Manual.
+
+ We assume the user should be familiar with following documents:
+
+ - Serial-HOWTO
+ - Kernel-HOWTO
+
+2. System Requirement
+^^^^^^^^^^^^^^^^^^^^^
+
+ - Maximum 4 boards can be installed in combination
+
+3. Installation
+^^^^^^^^^^^^^^^
+
+3.1 Hardware installation
+=========================
+
+PCI/UPCI board
+--------------
+
+ You may need to adjust IRQ usage in BIOS to avoid IRQ conflict with other
+ ISA devices. Please refer to hardware installation procedure in User's
+ Manual in advance.
+
+PCI IRQ Sharing
+---------------
+
+ Each port within the same multiport board shares the same IRQ. Up to
+ 4 Moxa Smartio/Industio PCI Family multiport boards can be installed
+ together on one system and they can share the same IRQ.
+
+
+
+3.2 Device naming convention
+============================
+
+ The device node is named "ttyMxx".
+
+Device naming when more than 2 boards installed
+-----------------------------------------------
+
+ Naming convention for each Smartio/Industio multiport board is
+ pre-defined as below.
+
+ ============ ===============
+ Board Num. Device node
+ 1st board ttyM0 - ttyM7
+ 2nd board ttyM8 - ttyM15
+ 3rd board ttyM16 - ttyM23
+ 4th board ttyM24 - ttyM31
+ ============ ===============
+
+4. Utilities
+^^^^^^^^^^^^
+
+ There are 3 utilities contained in this driver. They are msdiag, msmon and
+ msterm. These 3 utilities are released in form of source code. They should
+ be compiled into executable file and copied into /usr/bin.
+
+msdiag - Diagnostic
+===================
+
+ This utility provides the function to display what Moxa Smartio/Industio
+ board was found by the driver in the system.
+
+msmon - Port Monitoring
+=======================
+
+ This utility gives the user a quick view about all the MOXA ports'
+ activities. One can easily learn each port's total received/transmitted
+ (Rx/Tx) character count since the time when the monitoring is started.
+
+ Rx/Tx throughputs per second are also reported in interval basis (e.g.
+ the last 5 seconds) and in average basis (since the time the monitoring
+ is started). You can reset all ports' count by <HOME> key. <+> <->
+ (plus/minus) keys to change the displaying time interval. Press <ENTER>
+ on the port, that cursor stay, to view the port's communication
+ parameters, signal status, and input/output queue.
+
+msterm - Terminal Emulation
+===========================
+
+ This utility provides data sending and receiving ability of all tty ports,
+ especially for MOXA ports. It is quite useful for testing simple
+ application, for example, sending AT command to a modem connected to the
+ port or used as a terminal for login purpose. Note that this is only a
+ dumb terminal emulation without handling full screen operation.
+
+5. Setserial
+^^^^^^^^^^^^
+
+ Supported Setserial parameters are listed as below.
+
+ ============== =============================================================
+ uart set UART type(16450 --> disable FIFO, 16550A --> enable FIFO)
+ close_delay set the amount of time (in 1/100 of a second) that DTR
+ should be kept low while being closed.
+ closing_wait set the amount of time (in 1/100 of a second) that the
+ serial port should wait for data to be drained while
+ being closed, before the receiver is disabled.
+ spd_hi Use 57.6kb when the application requests 38.4kb.
+ spd_vhi Use 115.2kb when the application requests 38.4kb.
+ spd_shi Use 230.4kb when the application requests 38.4kb.
+ spd_warp Use 460.8kb when the application requests 38.4kb.
+ spd_normal Use 38.4kb when the application requests 38.4kb.
+ spd_cust Use the custom divisor to set the speed when the
+ application requests 38.4kb.
+ divisor This option sets the custom division.
+ baud_base This option sets the base baud rate.
+ ============== =============================================================
+
+6. Troubleshooting
+^^^^^^^^^^^^^^^^^^
+
+ The boot time error messages and solutions are stated as clearly as
+ possible. If all the possible solutions fail, please contact our technical
+ support team to get more help.
+
+
+ Error msg:
+ More than 4 Moxa Smartio/Industio family boards found. Fifth board
+ and after are ignored.
+
+ Solution:
+ To avoid this problem, please unplug fifth and after board, because Moxa
+ driver supports up to 4 boards.
diff --git a/Documentation/driver-api/tty/n_gsm.rst b/Documentation/driver-api/tty/n_gsm.rst
new file mode 100644
index 000000000000..120317ec990f
--- /dev/null
+++ b/Documentation/driver-api/tty/n_gsm.rst
@@ -0,0 +1,192 @@
+==============================
+GSM 0710 tty multiplexor HOWTO
+==============================
+
+.. contents:: :local:
+
+This line discipline implements the GSM 07.10 multiplexing protocol
+detailed in the following 3GPP document:
+
+ https://www.3gpp.org/ftp/Specs/archive/07_series/07.10/0710-720.zip
+
+This document give some hints on how to use this driver with GPRS and 3G
+modems connected to a physical serial port.
+
+How to use it
+=============
+
+Config Initiator
+----------------
+
+#. Initialize the modem in 0710 mux mode (usually ``AT+CMUX=`` command) through
+ its serial port. Depending on the modem used, you can pass more or less
+ parameters to this command.
+
+#. Switch the serial line to using the n_gsm line discipline by using
+ ``TIOCSETD`` ioctl.
+
+#. Configure the mux using ``GSMIOC_GETCONF_EXT``/``GSMIOC_SETCONF_EXT`` ioctl if needed.
+
+#. Configure the mux using ``GSMIOC_GETCONF``/``GSMIOC_SETCONF`` ioctl.
+
+#. Configure DLCs using ``GSMIOC_GETCONF_DLCI``/``GSMIOC_SETCONF_DLCI`` ioctl for non-defaults.
+
+#. Obtain base gsmtty number for the used serial port.
+
+ Major parts of the initialization program
+ (a good starting point is util-linux-ng/sys-utils/ldattach.c)::
+
+ #include <stdio.h>
+ #include <stdint.h>
+ #include <linux/gsmmux.h>
+ #include <linux/tty.h>
+
+ #define DEFAULT_SPEED B115200
+ #define SERIAL_PORT /dev/ttyS0
+
+ int ldisc = N_GSM0710;
+ struct gsm_config c;
+ struct gsm_config_ext ce;
+ struct gsm_dlci_config dc;
+ struct termios configuration;
+ uint32_t first;
+
+ /* open the serial port connected to the modem */
+ fd = open(SERIAL_PORT, O_RDWR | O_NOCTTY | O_NDELAY);
+
+ /* configure the serial port : speed, flow control ... */
+
+ /* send the AT commands to switch the modem to CMUX mode
+ and check that it's successful (should return OK) */
+ write(fd, "AT+CMUX=0\r", 10);
+
+ /* experience showed that some modems need some time before
+ being able to answer to the first MUX packet so a delay
+ may be needed here in some case */
+ sleep(3);
+
+ /* use n_gsm line discipline */
+ ioctl(fd, TIOCSETD, &ldisc);
+
+ /* get n_gsm extended configuration */
+ ioctl(fd, GSMIOC_GETCONF_EXT, &ce);
+ /* use keep-alive once every 5s for modem connection supervision */
+ ce.keep_alive = 500;
+ /* set the new extended configuration */
+ ioctl(fd, GSMIOC_SETCONF_EXT, &ce);
+ /* get n_gsm configuration */
+ ioctl(fd, GSMIOC_GETCONF, &c);
+ /* we are initiator and need encoding 0 (basic) */
+ c.initiator = 1;
+ c.encapsulation = 0;
+ /* our modem defaults to a maximum size of 127 bytes */
+ c.mru = 127;
+ c.mtu = 127;
+ /* set the new configuration */
+ ioctl(fd, GSMIOC_SETCONF, &c);
+ /* get DLC 1 configuration */
+ dc.channel = 1;
+ ioctl(fd, GSMIOC_GETCONF_DLCI, &dc);
+ /* the first user channel gets a higher priority */
+ dc.priority = 1;
+ /* set the new DLC 1 specific configuration */
+ ioctl(fd, GSMIOC_SETCONF_DLCI, &dc);
+ /* get first gsmtty device node */
+ ioctl(fd, GSMIOC_GETFIRST, &first);
+ printf("first muxed line: /dev/gsmtty%i\n", first);
+
+ /* and wait for ever to keep the line discipline enabled */
+ daemon(0,0);
+ pause();
+
+#. Use these devices as plain serial ports.
+
+ For example, it's possible:
+
+ - to use *gnokii* to send / receive SMS on ``ttygsm1``
+ - to use *ppp* to establish a datalink on ``ttygsm2``
+
+#. First close all virtual ports before closing the physical port.
+
+ Note that after closing the physical port the modem is still in multiplexing
+ mode. This may prevent a successful re-opening of the port later. To avoid
+ this situation either reset the modem if your hardware allows that or send
+ a disconnect command frame manually before initializing the multiplexing mode
+ for the second time. The byte sequence for the disconnect command frame is::
+
+ 0xf9, 0x03, 0xef, 0x03, 0xc3, 0x16, 0xf9
+
+Config Requester
+----------------
+
+#. Receive ``AT+CMUX=`` command through its serial port, initialize mux mode
+ config.
+
+#. Switch the serial line to using the *n_gsm* line discipline by using
+ ``TIOCSETD`` ioctl.
+
+#. Configure the mux using ``GSMIOC_GETCONF_EXT``/``GSMIOC_SETCONF_EXT``
+ ioctl if needed.
+
+#. Configure the mux using ``GSMIOC_GETCONF``/``GSMIOC_SETCONF`` ioctl.
+
+#. Configure DLCs using ``GSMIOC_GETCONF_DLCI``/``GSMIOC_SETCONF_DLCI`` ioctl for non-defaults.
+
+#. Obtain base gsmtty number for the used serial port::
+
+ #include <stdio.h>
+ #include <stdint.h>
+ #include <linux/gsmmux.h>
+ #include <linux/tty.h>
+ #define DEFAULT_SPEED B115200
+ #define SERIAL_PORT /dev/ttyS0
+
+ int ldisc = N_GSM0710;
+ struct gsm_config c;
+ struct gsm_config_ext ce;
+ struct gsm_dlci_config dc;
+ struct termios configuration;
+ uint32_t first;
+
+ /* open the serial port */
+ fd = open(SERIAL_PORT, O_RDWR | O_NOCTTY | O_NDELAY);
+
+ /* configure the serial port : speed, flow control ... */
+
+ /* get serial data and check "AT+CMUX=command" parameter ... */
+
+ /* use n_gsm line discipline */
+ ioctl(fd, TIOCSETD, &ldisc);
+
+ /* get n_gsm extended configuration */
+ ioctl(fd, GSMIOC_GETCONF_EXT, &ce);
+ /* use keep-alive once every 5s for peer connection supervision */
+ ce.keep_alive = 500;
+ /* set the new extended configuration */
+ ioctl(fd, GSMIOC_SETCONF_EXT, &ce);
+ /* get n_gsm configuration */
+ ioctl(fd, GSMIOC_GETCONF, &c);
+ /* we are requester and need encoding 0 (basic) */
+ c.initiator = 0;
+ c.encapsulation = 0;
+ /* our modem defaults to a maximum size of 127 bytes */
+ c.mru = 127;
+ c.mtu = 127;
+ /* set the new configuration */
+ ioctl(fd, GSMIOC_SETCONF, &c);
+ /* get DLC 1 configuration */
+ dc.channel = 1;
+ ioctl(fd, GSMIOC_GETCONF_DLCI, &dc);
+ /* the first user channel gets a higher priority */
+ dc.priority = 1;
+ /* set the new DLC 1 specific configuration */
+ ioctl(fd, GSMIOC_SETCONF_DLCI, &dc);
+ /* get first gsmtty device node */
+ ioctl(fd, GSMIOC_GETFIRST, &first);
+ printf("first muxed line: /dev/gsmtty%i\n", first);
+
+ /* and wait for ever to keep the line discipline enabled */
+ daemon(0,0);
+ pause();
+
+11-03-08 - Eric Bénard - <eric@eukrea.com>
diff --git a/Documentation/driver-api/tty/n_tty.rst b/Documentation/driver-api/tty/n_tty.rst
new file mode 100644
index 000000000000..15b70faee72d
--- /dev/null
+++ b/Documentation/driver-api/tty/n_tty.rst
@@ -0,0 +1,22 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+=====
+N_TTY
+=====
+
+.. contents:: :local:
+
+The default (and fallback) :doc:`TTY line discipline <tty_ldisc>`. It tries to
+handle characters as per POSIX.
+
+External Functions
+==================
+
+.. kernel-doc:: drivers/tty/n_tty.c
+ :export:
+
+Internal Functions
+==================
+
+.. kernel-doc:: drivers/tty/n_tty.c
+ :internal:
diff --git a/Documentation/driver-api/tty/tty_buffer.rst b/Documentation/driver-api/tty/tty_buffer.rst
new file mode 100644
index 000000000000..4b5ca1776d4f
--- /dev/null
+++ b/Documentation/driver-api/tty/tty_buffer.rst
@@ -0,0 +1,49 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+==========
+TTY Buffer
+==========
+
+.. contents:: :local:
+
+Here, we document functions for taking care of tty buffer and their flipping.
+Drivers are supposed to fill the buffer by one of those functions below and
+then flip the buffer, so that the data are passed to :doc:`line discipline
+<tty_ldisc>` for further processing.
+
+Flip Buffer Management
+======================
+
+.. kernel-doc:: drivers/tty/tty_buffer.c
+ :identifiers: tty_prepare_flip_string
+ tty_flip_buffer_push tty_ldisc_receive_buf
+
+.. kernel-doc:: include/linux/tty_flip.h
+ :identifiers: tty_insert_flip_string_fixed_flag tty_insert_flip_string_flags
+ tty_insert_flip_char
+
+----
+
+Other Functions
+===============
+
+.. kernel-doc:: drivers/tty/tty_buffer.c
+ :identifiers: tty_buffer_space_avail tty_buffer_set_limit
+
+----
+
+Buffer Locking
+==============
+
+These are used only in special circumstances. Avoid them.
+
+.. kernel-doc:: drivers/tty/tty_buffer.c
+ :identifiers: tty_buffer_lock_exclusive tty_buffer_unlock_exclusive
+
+----
+
+Internal Functions
+==================
+
+.. kernel-doc:: drivers/tty/tty_buffer.c
+ :internal:
diff --git a/Documentation/driver-api/tty/tty_driver.rst b/Documentation/driver-api/tty/tty_driver.rst
new file mode 100644
index 000000000000..cc529f863406
--- /dev/null
+++ b/Documentation/driver-api/tty/tty_driver.rst
@@ -0,0 +1,128 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+=============================
+TTY Driver and TTY Operations
+=============================
+
+.. contents:: :local:
+
+Allocation
+==========
+
+The first thing a driver needs to do is to allocate a struct tty_driver. This
+is done by tty_alloc_driver() (or __tty_alloc_driver()). Next, the newly
+allocated structure is filled with information. See `TTY Driver Reference`_ at
+the end of this document on what actually shall be filled in.
+
+The allocation routines expect a number of devices the driver can handle at
+most and flags. Flags are those starting ``TTY_DRIVER_`` listed and described
+in `TTY Driver Flags`_ below.
+
+When the driver is about to be freed, tty_driver_kref_put() is called on that.
+It will decrements the reference count and if it reaches zero, the driver is
+freed.
+
+For reference, both allocation and deallocation functions are explained here in
+detail:
+
+.. kernel-doc:: drivers/tty/tty_io.c
+ :identifiers: __tty_alloc_driver tty_driver_kref_put
+
+TTY Driver Flags
+----------------
+
+Here comes the documentation of flags accepted by tty_alloc_driver() (or
+__tty_alloc_driver()):
+
+.. kernel-doc:: include/linux/tty_driver.h
+ :doc: TTY Driver Flags
+
+----
+
+Registration
+============
+
+When a struct tty_driver is allocated and filled in, it can be registered using
+tty_register_driver(). It is recommended to pass ``TTY_DRIVER_DYNAMIC_DEV`` in
+flags of tty_alloc_driver(). If it is not passed, *all* devices are also
+registered during tty_register_driver() and the following paragraph of
+registering devices can be skipped for such drivers. However, the struct
+tty_port part in `Registering Devices`_ is still relevant there.
+
+.. kernel-doc:: drivers/tty/tty_io.c
+ :identifiers: tty_register_driver tty_unregister_driver
+
+Registering Devices
+-------------------
+
+Every TTY device shall be backed by a struct tty_port. Usually, TTY drivers
+embed tty_port into device's private structures. Further details about handling
+tty_port can be found in :doc:`tty_port`. The driver is also recommended to use
+tty_port's reference counting by tty_port_get() and tty_port_put(). The final
+put is supposed to free the tty_port including the device's private struct.
+
+Unless ``TTY_DRIVER_DYNAMIC_DEV`` was passed as flags to tty_alloc_driver(),
+TTY driver is supposed to register every device discovered in the system
+(the latter is preferred). This is performed by tty_register_device(). Or by
+tty_register_device_attr() if the driver wants to expose some information
+through struct attribute_group. Both of them register ``index``'th device and
+upon return, the device can be opened. There are also preferred tty_port
+variants described in `Linking Devices to Ports`_ later. It is up to driver to
+manage free indices and choosing the right one. The TTY layer only refuses to
+register more devices than passed to tty_alloc_driver().
+
+When the device is opened, the TTY layer allocates struct tty_struct and starts
+calling operations from :c:member:`tty_driver.ops`, see `TTY Operations
+Reference`_.
+
+The registration routines are documented as follows:
+
+.. kernel-doc:: drivers/tty/tty_io.c
+ :identifiers: tty_register_device tty_register_device_attr
+ tty_unregister_device
+
+----
+
+Linking Devices to Ports
+------------------------
+As stated earlier, every TTY device shall have a struct tty_port assigned to
+it. It must be known to the TTY layer at :c:member:`tty_driver.ops.install()`
+at latest. There are few helpers to *link* the two. Ideally, the driver uses
+tty_port_register_device() or tty_port_register_device_attr() instead of
+tty_register_device() and tty_register_device_attr() at the registration time.
+This way, the driver needs not care about linking later on.
+
+If that is not possible, the driver still can link the tty_port to a specific
+index *before* the actual registration by tty_port_link_device(). If it still
+does not fit, tty_port_install() can be used from the
+:c:member:`tty_driver.ops.install` hook as a last resort. The last one is
+dedicated mostly for in-memory devices like PTY where tty_ports are allocated
+on demand.
+
+The linking routines are documented here:
+
+.. kernel-doc:: drivers/tty/tty_port.c
+ :identifiers: tty_port_link_device tty_port_register_device
+ tty_port_register_device_attr
+
+----
+
+TTY Driver Reference
+====================
+
+All members of struct tty_driver are documented here. The required members are
+noted at the end. struct tty_operations are documented next.
+
+.. kernel-doc:: include/linux/tty_driver.h
+ :identifiers: tty_driver
+
+----
+
+TTY Operations Reference
+========================
+
+When a TTY is registered, these driver hooks can be invoked by the TTY layer:
+
+.. kernel-doc:: include/linux/tty_driver.h
+ :identifiers: tty_operations
+
diff --git a/Documentation/driver-api/tty/tty_internals.rst b/Documentation/driver-api/tty/tty_internals.rst
new file mode 100644
index 000000000000..d0d415820300
--- /dev/null
+++ b/Documentation/driver-api/tty/tty_internals.rst
@@ -0,0 +1,31 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+=============
+TTY Internals
+=============
+
+.. contents:: :local:
+
+Kopen
+=====
+
+These functions serve for opening a TTY from the kernelspace:
+
+.. kernel-doc:: drivers/tty/tty_io.c
+ :identifiers: tty_kopen_exclusive tty_kopen_shared tty_kclose
+
+----
+
+Exported Internal Functions
+===========================
+
+.. kernel-doc:: drivers/tty/tty_io.c
+ :identifiers: tty_release_struct tty_dev_name_to_number tty_get_icount
+
+----
+
+Internal Functions
+==================
+
+.. kernel-doc:: drivers/tty/tty_io.c
+ :internal:
diff --git a/Documentation/driver-api/tty/tty_ioctl.rst b/Documentation/driver-api/tty/tty_ioctl.rst
new file mode 100644
index 000000000000..3ff1ac5e07f1
--- /dev/null
+++ b/Documentation/driver-api/tty/tty_ioctl.rst
@@ -0,0 +1,10 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+=================
+TTY IOCTL Helpers
+=================
+
+.. kernel-doc:: drivers/tty/tty_ioctl.c
+
+.. kernel-doc:: include/linux/tty.h
+ :identifiers: tty_get_baud_rate
diff --git a/Documentation/driver-api/tty/tty_ldisc.rst b/Documentation/driver-api/tty/tty_ldisc.rst
new file mode 100644
index 000000000000..5144751be804
--- /dev/null
+++ b/Documentation/driver-api/tty/tty_ldisc.rst
@@ -0,0 +1,85 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+===================
+TTY Line Discipline
+===================
+
+.. contents:: :local:
+
+TTY line discipline process all incoming and outgoing character from/to a tty
+device. The default line discipline is :doc:`N_TTY <n_tty>`. It is also a
+fallback if establishing any other discipline for a tty fails. If even N_TTY
+fails, N_NULL takes over. That never fails, but also does not process any
+characters -- it throws them away.
+
+Registration
+============
+
+Line disciplines are registered with tty_register_ldisc() passing the ldisc
+structure. At the point of registration the discipline must be ready to use and
+it is possible it will get used before the call returns success. If the call
+returns an error then it won’t get called. Do not re-use ldisc numbers as they
+are part of the userspace ABI and writing over an existing ldisc will cause
+demons to eat your computer. You must not re-register over the top of the line
+discipline even with the same data or your computer again will be eaten by
+demons. In order to remove a line discipline call tty_unregister_ldisc().
+
+Heed this warning: the reference count field of the registered copies of the
+tty_ldisc structure in the ldisc table counts the number of lines using this
+discipline. The reference count of the tty_ldisc structure within a tty counts
+the number of active users of the ldisc at this instant. In effect it counts
+the number of threads of execution within an ldisc method (plus those about to
+enter and exit although this detail matters not).
+
+.. kernel-doc:: drivers/tty/tty_ldisc.c
+ :identifiers: tty_register_ldisc tty_unregister_ldisc
+
+Other Functions
+===============
+
+.. kernel-doc:: drivers/tty/tty_ldisc.c
+ :identifiers: tty_set_ldisc tty_ldisc_flush
+
+Line Discipline Operations Reference
+====================================
+
+.. kernel-doc:: include/linux/tty_ldisc.h
+ :identifiers: tty_ldisc_ops
+
+Driver Access
+=============
+
+Line discipline methods can call the methods of the underlying hardware driver.
+These are documented as a part of struct tty_operations.
+
+TTY Flags
+=========
+
+Line discipline methods have access to :c:member:`tty_struct.flags` field. See
+:doc:`tty_struct`.
+
+Locking
+=======
+
+Callers to the line discipline functions from the tty layer are required to
+take line discipline locks. The same is true of calls from the driver side
+but not yet enforced.
+
+.. kernel-doc:: drivers/tty/tty_ldisc.c
+ :identifiers: tty_ldisc_ref_wait tty_ldisc_ref tty_ldisc_deref
+
+While these functions are slightly slower than the old code they should have
+minimal impact as most receive logic uses the flip buffers and they only
+need to take a reference when they push bits up through the driver.
+
+A caution: The :c:member:`tty_ldisc_ops.open()`,
+:c:member:`tty_ldisc_ops.close()` and :c:member:`tty_driver.set_ldisc()`
+functions are called with the ldisc unavailable. Thus tty_ldisc_ref() will fail
+in this situation if used within these functions. Ldisc and driver code
+calling its own functions must be careful in this case.
+
+Internal Functions
+==================
+
+.. kernel-doc:: drivers/tty/tty_ldisc.c
+ :internal:
diff --git a/Documentation/driver-api/tty/tty_port.rst b/Documentation/driver-api/tty/tty_port.rst
new file mode 100644
index 000000000000..5cb90e954fcf
--- /dev/null
+++ b/Documentation/driver-api/tty/tty_port.rst
@@ -0,0 +1,70 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+========
+TTY Port
+========
+
+.. contents:: :local:
+
+The TTY drivers are advised to use struct tty_port helpers as much as possible.
+If the drivers implement :c:member:`tty_port.ops.activate()` and
+:c:member:`tty_port.ops.shutdown()`, they can use tty_port_open(),
+tty_port_close(), and tty_port_hangup() in respective
+:c:member:`tty_struct.ops` hooks.
+
+The reference and details are contained in the `TTY Port Reference`_ and `TTY
+Port Operations Reference`_ sections at the bottom.
+
+TTY Port Functions
+==================
+
+Init & Destroy
+--------------
+
+.. kernel-doc:: drivers/tty/tty_port.c
+ :identifiers: tty_port_init tty_port_destroy
+ tty_port_get tty_port_put
+
+Open/Close/Hangup Helpers
+-------------------------
+
+.. kernel-doc:: drivers/tty/tty_port.c
+ :identifiers: tty_port_install tty_port_open tty_port_block_til_ready
+ tty_port_close tty_port_close_start tty_port_close_end tty_port_hangup
+ tty_port_shutdown
+
+TTY Refcounting
+---------------
+
+.. kernel-doc:: drivers/tty/tty_port.c
+ :identifiers: tty_port_tty_get tty_port_tty_set
+
+TTY Helpers
+-----------
+
+.. kernel-doc:: drivers/tty/tty_port.c
+ :identifiers: tty_port_tty_hangup tty_port_tty_wakeup
+
+
+Modem Signals
+-------------
+
+.. kernel-doc:: drivers/tty/tty_port.c
+ :identifiers: tty_port_carrier_raised tty_port_raise_dtr_rts
+ tty_port_lower_dtr_rts
+
+----
+
+TTY Port Reference
+==================
+
+.. kernel-doc:: include/linux/tty_port.h
+ :identifiers: tty_port
+
+----
+
+TTY Port Operations Reference
+=============================
+
+.. kernel-doc:: include/linux/tty_port.h
+ :identifiers: tty_port_operations
diff --git a/Documentation/driver-api/tty/tty_struct.rst b/Documentation/driver-api/tty/tty_struct.rst
new file mode 100644
index 000000000000..c72f5a4293b2
--- /dev/null
+++ b/Documentation/driver-api/tty/tty_struct.rst
@@ -0,0 +1,81 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+==========
+TTY Struct
+==========
+
+.. contents:: :local:
+
+struct tty_struct is allocated by the TTY layer upon the first open of the TTY
+device and released after the last close. The TTY layer passes this structure
+to most of struct tty_operation's hooks. Members of tty_struct are documented
+in `TTY Struct Reference`_ at the bottom.
+
+Initialization
+==============
+
+.. kernel-doc:: drivers/tty/tty_io.c
+ :identifiers: tty_init_termios
+
+Name
+====
+
+.. kernel-doc:: drivers/tty/tty_io.c
+ :identifiers: tty_name
+
+Reference counting
+==================
+
+.. kernel-doc:: include/linux/tty.h
+ :identifiers: tty_kref_get
+
+.. kernel-doc:: drivers/tty/tty_io.c
+ :identifiers: tty_kref_put
+
+Install
+=======
+
+.. kernel-doc:: drivers/tty/tty_io.c
+ :identifiers: tty_standard_install
+
+Read & Write
+============
+
+.. kernel-doc:: drivers/tty/tty_io.c
+ :identifiers: tty_put_char
+
+Start & Stop
+============
+
+.. kernel-doc:: drivers/tty/tty_io.c
+ :identifiers: start_tty stop_tty
+
+Wakeup
+======
+
+.. kernel-doc:: drivers/tty/tty_io.c
+ :identifiers: tty_wakeup
+
+Hangup
+======
+
+.. kernel-doc:: drivers/tty/tty_io.c
+ :identifiers: tty_hangup tty_vhangup tty_hung_up_p
+
+Misc
+====
+
+.. kernel-doc:: drivers/tty/tty_io.c
+ :identifiers: tty_do_resize
+
+TTY Struct Flags
+================
+
+.. kernel-doc:: include/linux/tty.h
+ :doc: TTY Struct Flags
+
+TTY Struct Reference
+====================
+
+.. kernel-doc:: include/linux/tty.h
+ :identifiers: tty_struct
diff --git a/Documentation/driver-api/uio-howto.rst b/Documentation/driver-api/uio-howto.rst
index 84091cd25dc4..907ffa3b38f5 100644
--- a/Documentation/driver-api/uio-howto.rst
+++ b/Documentation/driver-api/uio-howto.rst
@@ -274,7 +274,7 @@ fields of ``struct uio_mem``:
region, it will show up in the corresponding sysfs node.
- ``int memtype``: Required if the mapping is used. Set this to
- ``UIO_MEM_PHYS`` if you you have physical memory on your card to be
+ ``UIO_MEM_PHYS`` if you have physical memory on your card to be
mapped. Use ``UIO_MEM_LOGICAL`` for logical memory (e.g. allocated
with :c:func:`__get_free_pages()` but not kmalloc()). There's also
``UIO_MEM_VIRTUAL`` for virtual memory.
diff --git a/Documentation/driver-api/usb/URB.rst b/Documentation/driver-api/usb/URB.rst
index 61a54da9fce9..a182c0f5e38a 100644
--- a/Documentation/driver-api/usb/URB.rst
+++ b/Documentation/driver-api/usb/URB.rst
@@ -47,7 +47,7 @@ called USB Request Block, or URB for short.
The URB structure
=================
-Some of the fields in struct :c:type:`urb` are::
+Some of the fields in struct urb are::
struct urb
{
@@ -240,7 +240,7 @@ How to do isochronous (ISO) transfers?
======================================
Besides the fields present on a bulk transfer, for ISO, you also
-also have to set ``urb->interval`` to say how often to make transfers; it's
+have to set ``urb->interval`` to say how often to make transfers; it's
often one per frame (which is once every microframe for highspeed devices).
The actual interval used will be a power of two that's no bigger than what
you specify. You can use the :c:func:`usb_fill_int_urb` macro to fill
diff --git a/Documentation/driver-api/usb/bulk-streams.rst b/Documentation/driver-api/usb/bulk-streams.rst
index 99b515babdeb..eeefe582f8ff 100644
--- a/Documentation/driver-api/usb/bulk-streams.rst
+++ b/Documentation/driver-api/usb/bulk-streams.rst
@@ -9,9 +9,9 @@ device driver to overload a bulk endpoint so that multiple transfers can be
queued at once.
Streams are defined in sections 4.4.6.4 and 8.12.1.4 of the Universal Serial Bus
-3.0 specification at http://www.usb.org/developers/docs/ The USB Attached SCSI
+3.0 specification at https://www.usb.org/developers/docs/ The USB Attached SCSI
Protocol, which uses streams to queue multiple SCSI commands, can be found on
-the T10 website (http://t10.org/).
+the T10 website (https://t10.org/).
Device-side implications
diff --git a/Documentation/driver-api/usb/dma.rst b/Documentation/driver-api/usb/dma.rst
index 59d5aee89e37..02f6825ff830 100644
--- a/Documentation/driver-api/usb/dma.rst
+++ b/Documentation/driver-api/usb/dma.rst
@@ -10,7 +10,7 @@ API overview
The big picture is that USB drivers can continue to ignore most DMA issues,
though they still must provide DMA-ready buffers (see
-``Documentation/DMA-API-HOWTO.txt``). That's how they've worked through
+Documentation/core-api/dma-api-howto.rst). That's how they've worked through
the 2.4 (and earlier) kernels, or they can now be DMA-aware.
DMA-aware usb drivers:
@@ -60,7 +60,7 @@ and effects like cache-trashing can impose subtle penalties.
force a consistent memory access ordering by using memory barriers. It's
not using a streaming DMA mapping, so it's good for small transfers on
systems where the I/O would otherwise thrash an IOMMU mapping. (See
- ``Documentation/DMA-API-HOWTO.txt`` for definitions of "coherent" and
+ Documentation/core-api/dma-api-howto.rst for definitions of "coherent" and
"streaming" DMA mappings.)
Asking for 1/Nth of a page (as well as asking for N pages) is reasonably
@@ -91,46 +91,20 @@ Working with existing buffers
Existing buffers aren't usable for DMA without first being mapped into the
DMA address space of the device. However, most buffers passed to your
driver can safely be used with such DMA mapping. (See the first section
-of Documentation/DMA-API-HOWTO.txt, titled "What memory is DMA-able?")
+of Documentation/core-api/dma-api-howto.rst, titled "What memory is DMA-able?")
-- When you're using scatterlists, you can map everything at once. On some
- systems, this kicks in an IOMMU and turns the scatterlists into single
- DMA transactions::
+- When you have the scatterlists which have been mapped for the USB controller,
+ you could use the new ``usb_sg_*()`` calls, which would turn scatterlist
+ into URBs::
- int usb_buffer_map_sg (struct usb_device *dev, unsigned pipe,
- struct scatterlist *sg, int nents);
+ int usb_sg_init(struct usb_sg_request *io, struct usb_device *dev,
+ unsigned pipe, unsigned period, struct scatterlist *sg,
+ int nents, size_t length, gfp_t mem_flags);
- void usb_buffer_dmasync_sg (struct usb_device *dev, unsigned pipe,
- struct scatterlist *sg, int n_hw_ents);
+ void usb_sg_wait(struct usb_sg_request *io);
- void usb_buffer_unmap_sg (struct usb_device *dev, unsigned pipe,
- struct scatterlist *sg, int n_hw_ents);
+ void usb_sg_cancel(struct usb_sg_request *io);
- It's probably easier to use the new ``usb_sg_*()`` calls, which do the DMA
- mapping and apply other tweaks to make scatterlist i/o be fast.
-
-- Some drivers may prefer to work with the model that they're mapping large
- buffers, synchronizing their safe re-use. (If there's no re-use, then let
- usbcore do the map/unmap.) Large periodic transfers make good examples
- here, since it's cheaper to just synchronize the buffer than to unmap it
- each time an urb completes and then re-map it on during resubmission.
-
- These calls all work with initialized urbs: ``urb->dev``, ``urb->pipe``,
- ``urb->transfer_buffer``, and ``urb->transfer_buffer_length`` must all be
- valid when these calls are used (``urb->setup_packet`` must be valid too
- if urb is a control request)::
-
- struct urb *usb_buffer_map (struct urb *urb);
-
- void usb_buffer_dmasync (struct urb *urb);
-
- void usb_buffer_unmap (struct urb *urb);
-
- The calls manage ``urb->transfer_dma`` for you, and set
- ``URB_NO_TRANSFER_DMA_MAP`` so that usbcore won't map or unmap the buffer.
- They cannot be used for setup_packet buffers in control requests.
-
-Note that several of those interfaces are currently commented out, since
-they don't have current users. See the source code. Other than the dmasync
-calls (where the underlying DMA primitives have changed), most of them can
-easily be commented back in if you want to use them.
+ When the USB controller doesn't support DMA, the ``usb_sg_init()`` would try
+ to submit URBs in PIO way as long as the page in scatterlists is not in the
+ Highmem, which could be very rare in modern architectures.
diff --git a/Documentation/driver-api/usb/dwc3.rst b/Documentation/driver-api/usb/dwc3.rst
index 8b36ff11cef9..e3d6a620997f 100644
--- a/Documentation/driver-api/usb/dwc3.rst
+++ b/Documentation/driver-api/usb/dwc3.rst
@@ -18,7 +18,7 @@ controller which can be configured in one of 4 ways:
4. Hub configuration
Linux currently supports several versions of this controller. In all
-likelyhood, the version in your SoC is already supported. At the time
+likelihood, the version in your SoC is already supported. At the time
of this writing, known tested versions range from 2.02a to 3.10a. As a
rule of thumb, anything above 2.02a should work reliably well.
diff --git a/Documentation/driver-api/usb/error-codes.rst b/Documentation/driver-api/usb/error-codes.rst
index a3e84bfac776..8f9790c2d6f8 100644
--- a/Documentation/driver-api/usb/error-codes.rst
+++ b/Documentation/driver-api/usb/error-codes.rst
@@ -61,6 +61,9 @@ USB-specific:
(c) requested data transfer length is invalid: negative
or too large for the host controller.
+``-EBADR`` The wLength value in a control URB's setup packet does
+ not match the URB's transfer_buffer_length.
+
``-ENOSPC`` This request would overcommit the usb bandwidth reserved
for periodic transfers (interrupt, isochronous).
diff --git a/Documentation/driver-api/usb/gadget.rst b/Documentation/driver-api/usb/gadget.rst
index 3e8a3809c0b8..09396edd6131 100644
--- a/Documentation/driver-api/usb/gadget.rst
+++ b/Documentation/driver-api/usb/gadget.rst
@@ -176,9 +176,9 @@ Kernel Mode Gadget API
Gadget drivers declare themselves through a struct
:c:type:`usb_gadget_driver`, which is responsible for most parts of enumeration
-for a struct :c:type:`usb_gadget`. The response to a set_configuration usually
-involves enabling one or more of the struct :c:type:`usb_ep` objects exposed by
-the gadget, and submitting one or more struct :c:type:`usb_request` buffers to
+for a struct usb_gadget. The response to a set_configuration usually
+involves enabling one or more of the struct usb_ep objects exposed by
+the gadget, and submitting one or more struct usb_request buffers to
transfer data. Understand those four data types, and their operations,
and you will understand how this API works.
@@ -339,8 +339,8 @@ multi-configuration devices (also more than one function, but not
necessarily sharing a given configuration). There is however an optional
framework which makes it easier to reuse and combine functions.
-Devices using this framework provide a struct :c:type:`usb_composite_driver`,
-which in turn provides one or more struct :c:type:`usb_configuration`
+Devices using this framework provide a struct usb_composite_driver,
+which in turn provides one or more struct usb_configuration
instances. Each such configuration includes at least one struct
:c:type:`usb_function`, which packages a user visible role such as "network
link" or "mass storage device". Management functions may also exist,
diff --git a/Documentation/driver-api/usb/hotplug.rst b/Documentation/driver-api/usb/hotplug.rst
index 79663e653ca1..c1e13107c50e 100644
--- a/Documentation/driver-api/usb/hotplug.rst
+++ b/Documentation/driver-api/usb/hotplug.rst
@@ -122,7 +122,7 @@ and their quirks, might have a MODULE_DEVICE_TABLE like this::
Most USB device drivers should pass these tables to the USB subsystem as
well as to the module management subsystem. Not all, though: some driver
frameworks connect using interfaces layered over USB, and so they won't
-need such a struct :c:type:`usb_driver`.
+need such a struct usb_driver.
Drivers that connect directly to the USB subsystem should be declared
something like this::
diff --git a/Documentation/driver-api/usb/typec_bus.rst b/Documentation/driver-api/usb/typec_bus.rst
index 03dfa9c018b7..21c890ae17e5 100644
--- a/Documentation/driver-api/usb/typec_bus.rst
+++ b/Documentation/driver-api/usb/typec_bus.rst
@@ -91,10 +91,16 @@ their control.
Driver API
----------
+Alternate mode structs
+~~~~~~~~~~~~~~~~~~~~~~
+
+.. kernel-doc:: include/linux/usb/typec_altmode.h
+ :functions: typec_altmode_driver typec_altmode_ops
+
Alternate mode driver registering/unregistering
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-.. kernel-doc:: drivers/usb/typec/bus.c
+.. kernel-doc:: include/linux/usb/typec_altmode.h
:functions: typec_altmode_register_driver typec_altmode_unregister_driver
Alternate mode driver operations
diff --git a/Documentation/driver-api/usb/usb.rst b/Documentation/driver-api/usb/usb.rst
index 078e981e2b16..fb41768696ec 100644
--- a/Documentation/driver-api/usb/usb.rst
+++ b/Documentation/driver-api/usb/usb.rst
@@ -109,13 +109,19 @@ well as to make sure they aren't relying on some HCD-specific behavior.
USB-Standard Types
==================
-In ``<linux/usb/ch9.h>`` you will find the USB data types defined in
-chapter 9 of the USB specification. These data types are used throughout
+In ``include/uapi/linux/usb/ch9.h`` you will find the USB data types defined
+in chapter 9 of the USB specification. These data types are used throughout
USB, and in APIs including this host side API, gadget APIs, usb character
-devices and debugfs interfaces.
+devices and debugfs interfaces. That file is itself included by
+``include/linux/usb/ch9.h``, which also contains declarations of a few
+utility routines for manipulating these data types; the implementations
+are in ``drivers/usb/common/common.c``.
-.. kernel-doc:: include/linux/usb/ch9.h
- :internal:
+.. kernel-doc:: drivers/usb/common/common.c
+ :export:
+
+In addition, some functions useful for creating debugging output are
+defined in ``drivers/usb/common/debug.c``.
.. _usb_header:
@@ -414,6 +420,12 @@ USBDEVFS_CONNECTINFO
know the devnum value already, it's the DDD value of the device file
name.
+USBDEVFS_GET_SPEED
+ Returns the speed of the device. The speed is returned as a
+ nummerical value in accordance with enum usb_device_speed
+
+ File modification time is not updated by this request.
+
USBDEVFS_GETDRIVER
Returns the name of the kernel driver bound to a given interface (a
string). Parameter is a pointer to this structure, which is
@@ -765,8 +777,7 @@ Speed may be:
======= ======================================================
1.5 Mbit/s for low speed USB
12 Mbit/s for full speed USB
- 480 Mbit/s for high speed USB (added for USB 2.0);
- also used for Wireless USB, which has no fixed speed
+ 480 Mbit/s for high speed USB (added for USB 2.0)
5000 Mbit/s for SuperSpeed USB (added for USB 3.0)
======= ======================================================
diff --git a/Documentation/driver-api/usb/usb3-debug-port.rst b/Documentation/driver-api/usb/usb3-debug-port.rst
index b9fd131f4723..d4610457b052 100644
--- a/Documentation/driver-api/usb/usb3-debug-port.rst
+++ b/Documentation/driver-api/usb/usb3-debug-port.rst
@@ -48,7 +48,7 @@ kernel boot parameter::
"earlyprintk=xdbc"
If there are multiple xHCI controllers in your system, you can
-append a host contoller index to this kernel parameter. This
+append a host controller index to this kernel parameter. This
index starts from 0.
Current design doesn't support DbC runtime suspend/resume. As
diff --git a/Documentation/driver-api/usb/writing_musb_glue_layer.rst b/Documentation/driver-api/usb/writing_musb_glue_layer.rst
index 5bf7152fd76f..10416cc11cd5 100644
--- a/Documentation/driver-api/usb/writing_musb_glue_layer.rst
+++ b/Documentation/driver-api/usb/writing_musb_glue_layer.rst
@@ -707,12 +707,12 @@ cheerful guidance and support.
Resources
=========
-USB Home Page: http://www.usb.org
+USB Home Page: https://www.usb.org
-linux-usb Mailing List Archives: http://marc.info/?l=linux-usb
+linux-usb Mailing List Archives: https://marc.info/?l=linux-usb
USB On-the-Go Basics:
-http://www.maximintegrated.com/app-notes/index.mvp/id/1822
+https://www.maximintegrated.com/app-notes/index.mvp/id/1822
:ref:`Writing USB Device Drivers <writing-usb-driver>`
diff --git a/Documentation/driver-api/usb/writing_usb_driver.rst b/Documentation/driver-api/usb/writing_usb_driver.rst
index 0b3d9ff221bb..95c4f5d14052 100644
--- a/Documentation/driver-api/usb/writing_usb_driver.rst
+++ b/Documentation/driver-api/usb/writing_usb_driver.rst
@@ -57,9 +57,12 @@ structure. The skeleton driver declares a :c:type:`usb_driver` as::
.name = "skeleton",
.probe = skel_probe,
.disconnect = skel_disconnect,
- .fops = &skel_fops,
- .minor = USB_SKEL_MINOR_BASE,
+ .suspend = skel_suspend,
+ .resume = skel_resume,
+ .pre_reset = skel_pre_reset,
+ .post_reset = skel_post_reset,
.id_table = skel_table,
+ .supports_autosuspend = 1,
};
@@ -81,7 +84,7 @@ this user-space interaction. The skeleton driver needs this kind of
interface, so it provides a minor starting number and a pointer to its
:c:type:`file_operations` functions.
-The USB driver is then registered with a call to :c:func:`usb_register`,
+The USB driver is then registered with a call to usb_register(),
usually in the driver's init function, as shown here::
static int __init usb_skel_init(void)
@@ -91,8 +94,8 @@ usually in the driver's init function, as shown here::
/* register this driver with the USB subsystem */
result = usb_register(&skel_driver);
if (result < 0) {
- err("usb_register failed for the "__FILE__ "driver."
- "Error number %d", result);
+ pr_err("usb_register failed for the %s driver. Error number %d\n",
+ skel_driver.name, result);
return -1;
}
@@ -102,7 +105,7 @@ usually in the driver's init function, as shown here::
When the driver is unloaded from the system, it needs to deregister
-itself with the USB subsystem. This is done with the :c:func:`usb_deregister`
+itself with the USB subsystem. This is done with usb_deregister()
function::
static void __exit usb_skel_exit(void)
@@ -167,8 +170,8 @@ structure. This is done so that future calls to file operations will
enable the driver to determine which device the user is addressing. All
of this is done with the following code::
- /* increment our usage count for the module */
- ++skel->open_count;
+ /* increment our usage count for the device */
+ kref_get(&dev->kref);
/* save our object in the file's private structure */
file->private_data = dev;
@@ -185,24 +188,26 @@ space, points the urb to the data and submits the urb to the USB
subsystem. This can be seen in the following code::
/* we can only write as much as 1 urb will hold */
- bytes_written = (count > skel->bulk_out_size) ? skel->bulk_out_size : count;
+ size_t writesize = min_t(size_t, count, MAX_TRANSFER);
/* copy the data from user space into our urb */
- copy_from_user(skel->write_urb->transfer_buffer, buffer, bytes_written);
+ copy_from_user(buf, user_buffer, writesize);
/* set up our urb */
- usb_fill_bulk_urb(skel->write_urb,
- skel->dev,
- usb_sndbulkpipe(skel->dev, skel->bulk_out_endpointAddr),
- skel->write_urb->transfer_buffer,
- bytes_written,
+ usb_fill_bulk_urb(urb,
+ dev->udev,
+ usb_sndbulkpipe(dev->udev, dev->bulk_out_endpointAddr),
+ buf,
+ writesize,
skel_write_bulk_callback,
- skel);
+ dev);
/* send the data out the bulk port */
- result = usb_submit_urb(skel->write_urb);
- if (result) {
- err("Failed submitting write urb, error %d", result);
+ retval = usb_submit_urb(urb, GFP_KERNEL);
+ if (retval) {
+ dev_err(&dev->interface->dev,
+ "%s - failed submitting write urb, error %d\n",
+ __func__, retval);
}
@@ -231,7 +236,7 @@ error message. This can be shown with the following code::
skel->bulk_in_endpointAddr),
skel->bulk_in_buffer,
skel->bulk_in_size,
- &count, HZ*10);
+ &count, 5000);
/* if the read was successful, copy the data to user space */
if (!retval) {
if (copy_to_user (buffer, skel->bulk_in_buffer, count))
@@ -318,6 +323,6 @@ linux-usb Mailing List Archives:
https://lore.kernel.org/linux-usb/
Programming Guide for Linux USB Device Drivers:
-http://lmu.web.psi.ch/docu/manuals/software_manuals/linux_sl/usb_linux_programming_guide.pdf
+https://lmu.web.psi.ch/docu/manuals/software_manuals/linux_sl/usb_linux_programming_guide.pdf
-USB Home Page: http://www.usb.org
+USB Home Page: https://www.usb.org
diff --git a/Documentation/driver-api/vfio-mediated-device.rst b/Documentation/driver-api/vfio-mediated-device.rst
index 25eb7d5b834b..bbd548b66b42 100644
--- a/Documentation/driver-api/vfio-mediated-device.rst
+++ b/Documentation/driver-api/vfio-mediated-device.rst
@@ -1,3 +1,4 @@
+.. SPDX-License-Identifier: GPL-2.0-only
.. include:: <isonum.txt>
=====================
@@ -8,9 +9,6 @@ VFIO Mediated devices
:Author: Neo Jia <cjia@nvidia.com>
:Author: Kirti Wankhede <kwankhede@nvidia.com>
-This program is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License version 2 as
-published by the Free Software Foundation.
Virtual Function I/O (VFIO) Mediated devices[1]
@@ -60,23 +58,17 @@ devices as examples, as these devices are the first devices to use this module::
| MDEV CORE |
| MODULE |
| mdev.ko |
- | +-----------+ | mdev_register_device() +--------------+
+ | +-----------+ | mdev_register_parent() +--------------+
| | | +<------------------------+ |
- | | | | | nvidia.ko |<-> physical
+ | | | | | ccw_device.ko|<-> physical
| | | +------------------------>+ | device
| | | | callbacks +--------------+
| | Physical | |
- | | device | | mdev_register_device() +--------------+
+ | | device | | mdev_register_parent() +--------------+
| | interface | |<------------------------+ |
| | | | | i915.ko |<-> physical
| | | +------------------------>+ | device
| | | | callbacks +--------------+
- | | | |
- | | | | mdev_register_device() +--------------+
- | | | +<------------------------+ |
- | | | | | ccw_device.ko|<-> physical
- | | | +------------------------>+ | device
- | | | | callbacks +--------------+
| +-----------+ |
+---------------+
@@ -93,20 +85,20 @@ interfaces:
Registration Interface for a Mediated Bus Driver
------------------------------------------------
-The registration interface for a mediated bus driver provides the following
+The registration interface for a mediated device driver provides the following
structure to represent a mediated device's driver::
/*
* struct mdev_driver [2] - Mediated device's driver
- * @name: driver name
* @probe: called when new device created
* @remove: called when device removed
* @driver: device driver structure
*/
struct mdev_driver {
- const char *name;
- int (*probe) (struct device *dev);
- void (*remove) (struct device *dev);
+ int (*probe) (struct mdev_device *dev);
+ void (*remove) (struct mdev_device *dev);
+ unsigned int (*get_available)(struct mdev_type *mtype);
+ ssize_t (*show_description)(struct mdev_type *mtype, char *buf);
struct device_driver driver;
};
@@ -115,61 +107,31 @@ to register and unregister itself with the core driver:
* Register::
- extern int mdev_register_driver(struct mdev_driver *drv,
- struct module *owner);
+ int mdev_register_driver(struct mdev_driver *drv);
* Unregister::
- extern void mdev_unregister_driver(struct mdev_driver *drv);
-
-The mediated bus driver is responsible for adding mediated devices to the VFIO
-group when devices are bound to the driver and removing mediated devices from
-the VFIO when devices are unbound from the driver.
-
-
-Physical Device Driver Interface
---------------------------------
-
-The physical device driver interface provides the mdev_parent_ops[3] structure
-to define the APIs to manage work in the mediated core driver that is related
-to the physical device.
+ void mdev_unregister_driver(struct mdev_driver *drv);
-The structures in the mdev_parent_ops structure are as follows:
+The mediated bus driver's probe function should create a vfio_device on top of
+the mdev_device and connect it to an appropriate implementation of
+vfio_device_ops.
-* dev_attr_groups: attributes of the parent device
-* mdev_attr_groups: attributes of the mediated device
-* supported_config: attributes to define supported configurations
+When a driver wants to add the GUID creation sysfs to an existing device it has
+probe'd to then it should call::
-The functions in the mdev_parent_ops structure are as follows:
+ int mdev_register_parent(struct mdev_parent *parent, struct device *dev,
+ struct mdev_driver *mdev_driver);
-* create: allocate basic resources in a driver for a mediated device
-* remove: free resources in a driver when a mediated device is destroyed
+This will provide the 'mdev_supported_types/XX/create' files which can then be
+used to trigger the creation of a mdev_device. The created mdev_device will be
+attached to the specified driver.
-(Note that mdev-core provides no implicit serialization of create/remove
-callbacks per mdev parent device, per mdev type, or any other categorization.
-Vendor drivers are expected to be fully asynchronous in this respect or
-provide their own internal resource protection.)
+When the driver needs to remove itself it calls::
-The callbacks in the mdev_parent_ops structure are as follows:
-
-* open: open callback of mediated device
-* close: close callback of mediated device
-* ioctl: ioctl callback of mediated device
-* read : read emulation callback
-* write: write emulation callback
-* mmap: mmap emulation callback
-
-A driver should use the mdev_parent_ops structure in the function call to
-register itself with the mdev core driver::
-
- extern int mdev_register_device(struct device *dev,
- const struct mdev_parent_ops *ops);
-
-However, the mdev_parent_ops structure is not required in the function call
-that a driver should use to unregister itself with the mdev core driver::
-
- extern void mdev_unregister_device(struct device *dev);
+ void mdev_unregister_parent(struct mdev_parent *parent);
+Which will unbind and destroy all the created mdevs and remove the sysfs files.
Mediated Device Management Interface Through sysfs
==================================================
@@ -233,17 +195,14 @@ Directories and files under the sysfs for Each Physical Device
sprintf(buf, "%s-%s", dev_driver_string(parent->dev), group->name);
- (or using mdev_parent_dev(mdev) to arrive at the parent device outside
- of the core mdev code)
-
* device_api
- This attribute should show which device API is being created, for example,
+ This attribute shows which device API is being created, for example,
"vfio-pci" for a PCI device.
* available_instances
- This attribute should show the number of devices of type <type-id> that can be
+ This attribute shows the number of devices of type <type-id> that can be
created.
* [device]
@@ -253,11 +212,11 @@ Directories and files under the sysfs for Each Physical Device
* name
- This attribute should show human readable name. This is optional attribute.
+ This attribute shows a human readable name.
* description
- This attribute should show brief features/description of the type. This is
+ This attribute can show brief features/description of the type. This is an
optional attribute.
Directories and Files Under the sysfs for Each mdev Device
@@ -293,10 +252,10 @@ Translation APIs for Mediated Devices
The following APIs are provided for translating user pfn to host pfn in a VFIO
driver::
- extern int vfio_pin_pages(struct device *dev, unsigned long *user_pfn,
- int npage, int prot, unsigned long *phys_pfn);
+ int vfio_pin_pages(struct vfio_device *device, dma_addr_t iova,
+ int npage, int prot, struct page **pages);
- extern int vfio_unpin_pages(struct device *dev, unsigned long *user_pfn,
+ void vfio_unpin_pages(struct vfio_device *device, dma_addr_t iova,
int npage);
These functions call back into the back-end IOMMU module by using the pin_pages
@@ -305,106 +264,6 @@ these callbacks are supported in the TYPE1 IOMMU module. To enable them for
other IOMMU backend modules, such as PPC64 sPAPR module, they need to provide
these two callback functions.
-Using the Sample Code
-=====================
-
-mtty.c in samples/vfio-mdev/ directory is a sample driver program to
-demonstrate how to use the mediated device framework.
-
-The sample driver creates an mdev device that simulates a serial port over a PCI
-card.
-
-1. Build and load the mtty.ko module.
-
- This step creates a dummy device, /sys/devices/virtual/mtty/mtty/
-
- Files in this device directory in sysfs are similar to the following::
-
- # tree /sys/devices/virtual/mtty/mtty/
- /sys/devices/virtual/mtty/mtty/
- |-- mdev_supported_types
- | |-- mtty-1
- | | |-- available_instances
- | | |-- create
- | | |-- device_api
- | | |-- devices
- | | `-- name
- | `-- mtty-2
- | |-- available_instances
- | |-- create
- | |-- device_api
- | |-- devices
- | `-- name
- |-- mtty_dev
- | `-- sample_mtty_dev
- |-- power
- | |-- autosuspend_delay_ms
- | |-- control
- | |-- runtime_active_time
- | |-- runtime_status
- | `-- runtime_suspended_time
- |-- subsystem -> ../../../../class/mtty
- `-- uevent
-
-2. Create a mediated device by using the dummy device that you created in the
- previous step::
-
- # echo "83b8f4f2-509f-382f-3c1e-e6bfe0fa1001" > \
- /sys/devices/virtual/mtty/mtty/mdev_supported_types/mtty-2/create
-
-3. Add parameters to qemu-kvm::
-
- -device vfio-pci,\
- sysfsdev=/sys/bus/mdev/devices/83b8f4f2-509f-382f-3c1e-e6bfe0fa1001
-
-4. Boot the VM.
-
- In the Linux guest VM, with no hardware on the host, the device appears
- as follows::
-
- # lspci -s 00:05.0 -xxvv
- 00:05.0 Serial controller: Device 4348:3253 (rev 10) (prog-if 02 [16550])
- Subsystem: Device 4348:3253
- Physical Slot: 5
- Control: I/O+ Mem- BusMaster- SpecCycle- MemWINV- VGASnoop- ParErr-
- Stepping- SERR- FastB2B- DisINTx-
- Status: Cap- 66MHz- UDF- FastB2B- ParErr- DEVSEL=medium >TAbort-
- <TAbort- <MAbort- >SERR- <PERR- INTx-
- Interrupt: pin A routed to IRQ 10
- Region 0: I/O ports at c150 [size=8]
- Region 1: I/O ports at c158 [size=8]
- Kernel driver in use: serial
- 00: 48 43 53 32 01 00 00 02 10 02 00 07 00 00 00 00
- 10: 51 c1 00 00 59 c1 00 00 00 00 00 00 00 00 00 00
- 20: 00 00 00 00 00 00 00 00 00 00 00 00 48 43 53 32
- 30: 00 00 00 00 00 00 00 00 00 00 00 00 0a 01 00 00
-
- In the Linux guest VM, dmesg output for the device is as follows:
-
- serial 0000:00:05.0: PCI INT A -> Link[LNKA] -> GSI 10 (level, high) -> IRQ 10
- 0000:00:05.0: ttyS1 at I/O 0xc150 (irq = 10) is a 16550A
- 0000:00:05.0: ttyS2 at I/O 0xc158 (irq = 10) is a 16550A
-
-
-5. In the Linux guest VM, check the serial ports::
-
- # setserial -g /dev/ttyS*
- /dev/ttyS0, UART: 16550A, Port: 0x03f8, IRQ: 4
- /dev/ttyS1, UART: 16550A, Port: 0xc150, IRQ: 10
- /dev/ttyS2, UART: 16550A, Port: 0xc158, IRQ: 10
-
-6. Using minicom or any terminal emulation program, open port /dev/ttyS1 or
- /dev/ttyS2 with hardware flow control disabled.
-
-7. Type data on the minicom terminal or send data to the terminal emulation
- program and read the data.
-
- Data is loop backed from hosts mtty driver.
-
-8. Destroy the mediated device that you created::
-
- # echo 1 > /sys/bus/mdev/devices/83b8f4f2-509f-382f-3c1e-e6bfe0fa1001/remove
-
References
==========
diff --git a/Documentation/driver-api/vfio-pci-device-specific-driver-acceptance.rst b/Documentation/driver-api/vfio-pci-device-specific-driver-acceptance.rst
new file mode 100644
index 000000000000..b7b99b876b50
--- /dev/null
+++ b/Documentation/driver-api/vfio-pci-device-specific-driver-acceptance.rst
@@ -0,0 +1,35 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+Acceptance criteria for vfio-pci device specific driver variants
+================================================================
+
+Overview
+--------
+The vfio-pci driver exists as a device agnostic driver using the
+system IOMMU and relying on the robustness of platform fault
+handling to provide isolated device access to userspace. While the
+vfio-pci driver does include some device specific support, further
+extensions for yet more advanced device specific features are not
+sustainable. The vfio-pci driver has therefore split out
+vfio-pci-core as a library that may be reused to implement features
+requiring device specific knowledge, ex. saving and loading device
+state for the purposes of supporting migration.
+
+In support of such features, it's expected that some device specific
+variants may interact with parent devices (ex. SR-IOV PF in support of
+a user assigned VF) or other extensions that may not be otherwise
+accessible via the vfio-pci base driver. Authors of such drivers
+should be diligent not to create exploitable interfaces via these
+interactions or allow unchecked userspace data to have an effect
+beyond the scope of the assigned device.
+
+New driver submissions are therefore requested to have approval via
+sign-off/ack/review/etc for any interactions with parent drivers.
+Additionally, drivers should make an attempt to provide sufficient
+documentation for reviewers to understand the device specific
+extensions, for example in the case of migration data, how is the
+device state composed and consumed, which portions are not otherwise
+available to the user via vfio-pci, what safeguards exist to validate
+the data, etc. To that extent, authors should additionally expect to
+require reviews from at least one of the listed reviewers, in addition
+to the overall vfio maintainer.
diff --git a/Documentation/driver-api/vfio.rst b/Documentation/driver-api/vfio.rst
index f1a4d3c3ba0b..633d11c7fa71 100644
--- a/Documentation/driver-api/vfio.rst
+++ b/Documentation/driver-api/vfio.rst
@@ -2,7 +2,7 @@
VFIO - "Virtual Function I/O" [1]_
==================================
-Many modern system now provide DMA and interrupt remapping facilities
+Many modern systems now provide DMA and interrupt remapping facilities
to help ensure I/O devices behave within the boundaries they've been
allotted. This includes x86 hardware with AMD-Vi and Intel VT-d,
POWER systems with Partitionable Endpoints (PEs) and embedded PowerPC
@@ -239,51 +239,230 @@ group and can access them as follows::
/* Gratuitous device reset and go... */
ioctl(device, VFIO_DEVICE_RESET);
+IOMMUFD and vfio_iommu_type1
+----------------------------
+
+IOMMUFD is the new user API to manage I/O page tables from userspace.
+It intends to be the portal of delivering advanced userspace DMA
+features (nested translation [5]_, PASID [6]_, etc.) while also providing
+a backwards compatibility interface for existing VFIO_TYPE1v2_IOMMU use
+cases. Eventually the vfio_iommu_type1 driver, as well as the legacy
+vfio container and group model is intended to be deprecated.
+
+The IOMMUFD backwards compatibility interface can be enabled two ways.
+In the first method, the kernel can be configured with
+CONFIG_IOMMUFD_VFIO_CONTAINER, in which case the IOMMUFD subsystem
+transparently provides the entire infrastructure for the VFIO
+container and IOMMU backend interfaces. The compatibility mode can
+also be accessed if the VFIO container interface, ie. /dev/vfio/vfio is
+simply symlink'd to /dev/iommu. Note that at the time of writing, the
+compatibility mode is not entirely feature complete relative to
+VFIO_TYPE1v2_IOMMU (ex. DMA mapping MMIO) and does not attempt to
+provide compatibility to the VFIO_SPAPR_TCE_IOMMU interface. Therefore
+it is not generally advisable at this time to switch from native VFIO
+implementations to the IOMMUFD compatibility interfaces.
+
+Long term, VFIO users should migrate to device access through the cdev
+interface described below, and native access through the IOMMUFD
+provided interfaces.
+
+VFIO Device cdev
+----------------
+
+Traditionally user acquires a device fd via VFIO_GROUP_GET_DEVICE_FD
+in a VFIO group.
+
+With CONFIG_VFIO_DEVICE_CDEV=y the user can now acquire a device fd
+by directly opening a character device /dev/vfio/devices/vfioX where
+"X" is the number allocated uniquely by VFIO for registered devices.
+cdev interface does not support noiommu devices, so user should use
+the legacy group interface if noiommu is wanted.
+
+The cdev only works with IOMMUFD. Both VFIO drivers and applications
+must adapt to the new cdev security model which requires using
+VFIO_DEVICE_BIND_IOMMUFD to claim DMA ownership before starting to
+actually use the device. Once BIND succeeds then a VFIO device can
+be fully accessed by the user.
+
+VFIO device cdev doesn't rely on VFIO group/container/iommu drivers.
+Hence those modules can be fully compiled out in an environment
+where no legacy VFIO application exists.
+
+So far SPAPR does not support IOMMUFD yet. So it cannot support device
+cdev either.
+
+vfio device cdev access is still bound by IOMMU group semantics, ie. there
+can be only one DMA owner for the group. Devices belonging to the same
+group can not be bound to multiple iommufd_ctx or shared between native
+kernel and vfio bus driver or other driver supporting the driver_managed_dma
+flag. A violation of this ownership requirement will fail at the
+VFIO_DEVICE_BIND_IOMMUFD ioctl, which gates full device access.
+
+Device cdev Example
+-------------------
+
+Assume user wants to access PCI device 0000:6a:01.0::
+
+ $ ls /sys/bus/pci/devices/0000:6a:01.0/vfio-dev/
+ vfio0
+
+This device is therefore represented as vfio0. The user can verify
+its existence::
+
+ $ ls -l /dev/vfio/devices/vfio0
+ crw------- 1 root root 511, 0 Feb 16 01:22 /dev/vfio/devices/vfio0
+ $ cat /sys/bus/pci/devices/0000:6a:01.0/vfio-dev/vfio0/dev
+ 511:0
+ $ ls -l /dev/char/511\:0
+ lrwxrwxrwx 1 root root 21 Feb 16 01:22 /dev/char/511:0 -> ../vfio/devices/vfio0
+
+Then provide the user with access to the device if unprivileged
+operation is desired::
+
+ $ chown user:user /dev/vfio/devices/vfio0
+
+Finally the user could get cdev fd by::
+
+ cdev_fd = open("/dev/vfio/devices/vfio0", O_RDWR);
+
+An opened cdev_fd doesn't give the user any permission of accessing
+the device except binding the cdev_fd to an iommufd. After that point
+then the device is fully accessible including attaching it to an
+IOMMUFD IOAS/HWPT to enable userspace DMA::
+
+ struct vfio_device_bind_iommufd bind = {
+ .argsz = sizeof(bind),
+ .flags = 0,
+ };
+ struct iommu_ioas_alloc alloc_data = {
+ .size = sizeof(alloc_data),
+ .flags = 0,
+ };
+ struct vfio_device_attach_iommufd_pt attach_data = {
+ .argsz = sizeof(attach_data),
+ .flags = 0,
+ };
+ struct iommu_ioas_map map = {
+ .size = sizeof(map),
+ .flags = IOMMU_IOAS_MAP_READABLE |
+ IOMMU_IOAS_MAP_WRITEABLE |
+ IOMMU_IOAS_MAP_FIXED_IOVA,
+ .__reserved = 0,
+ };
+
+ iommufd = open("/dev/iommu", O_RDWR);
+
+ bind.iommufd = iommufd;
+ ioctl(cdev_fd, VFIO_DEVICE_BIND_IOMMUFD, &bind);
+
+ ioctl(iommufd, IOMMU_IOAS_ALLOC, &alloc_data);
+ attach_data.pt_id = alloc_data.out_ioas_id;
+ ioctl(cdev_fd, VFIO_DEVICE_ATTACH_IOMMUFD_PT, &attach_data);
+
+ /* Allocate some space and setup a DMA mapping */
+ map.user_va = (int64_t)mmap(0, 1024 * 1024, PROT_READ | PROT_WRITE,
+ MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
+ map.iova = 0; /* 1MB starting at 0x0 from device view */
+ map.length = 1024 * 1024;
+ map.ioas_id = alloc_data.out_ioas_id;;
+
+ ioctl(iommufd, IOMMU_IOAS_MAP, &map);
+
+ /* Other device operations as stated in "VFIO Usage Example" */
+
VFIO User API
-------------------------------------------------------------------------------
-Please see include/linux/vfio.h for complete API documentation.
+Please see include/uapi/linux/vfio.h for complete API documentation.
VFIO bus driver API
-------------------------------------------------------------------------------
VFIO bus drivers, such as vfio-pci make use of only a few interfaces
into VFIO core. When devices are bound and unbound to the driver,
-the driver should call vfio_add_group_dev() and vfio_del_group_dev()
-respectively::
-
- extern int vfio_add_group_dev(struct device *dev,
- const struct vfio_device_ops *ops,
- void *device_data);
-
- extern void *vfio_del_group_dev(struct device *dev);
-
-vfio_add_group_dev() indicates to the core to begin tracking the
-iommu_group of the specified dev and register the dev as owned by
-a VFIO bus driver. The driver provides an ops structure for callbacks
+Following interfaces are called when devices are bound to and
+unbound from the driver::
+
+ int vfio_register_group_dev(struct vfio_device *device);
+ int vfio_register_emulated_iommu_dev(struct vfio_device *device);
+ void vfio_unregister_group_dev(struct vfio_device *device);
+
+The driver should embed the vfio_device in its own structure and use
+vfio_alloc_device() to allocate the structure, and can register
+@init/@release callbacks to manage any private state wrapping the
+vfio_device::
+
+ vfio_alloc_device(dev_struct, member, dev, ops);
+ void vfio_put_device(struct vfio_device *device);
+
+vfio_register_group_dev() indicates to the core to begin tracking the
+iommu_group of the specified dev and register the dev as owned by a VFIO bus
+driver. Once vfio_register_group_dev() returns it is possible for userspace to
+start accessing the driver, thus the driver should ensure it is completely
+ready before calling it. The driver provides an ops structure for callbacks
similar to a file operations structure::
struct vfio_device_ops {
- int (*open)(void *device_data);
- void (*release)(void *device_data);
- ssize_t (*read)(void *device_data, char __user *buf,
+ char *name;
+ int (*init)(struct vfio_device *vdev);
+ void (*release)(struct vfio_device *vdev);
+ int (*bind_iommufd)(struct vfio_device *vdev,
+ struct iommufd_ctx *ictx, u32 *out_device_id);
+ void (*unbind_iommufd)(struct vfio_device *vdev);
+ int (*attach_ioas)(struct vfio_device *vdev, u32 *pt_id);
+ void (*detach_ioas)(struct vfio_device *vdev);
+ int (*open_device)(struct vfio_device *vdev);
+ void (*close_device)(struct vfio_device *vdev);
+ ssize_t (*read)(struct vfio_device *vdev, char __user *buf,
size_t count, loff_t *ppos);
- ssize_t (*write)(void *device_data, const char __user *buf,
- size_t size, loff_t *ppos);
- long (*ioctl)(void *device_data, unsigned int cmd,
+ ssize_t (*write)(struct vfio_device *vdev, const char __user *buf,
+ size_t count, loff_t *size);
+ long (*ioctl)(struct vfio_device *vdev, unsigned int cmd,
unsigned long arg);
- int (*mmap)(void *device_data, struct vm_area_struct *vma);
+ int (*mmap)(struct vfio_device *vdev, struct vm_area_struct *vma);
+ void (*request)(struct vfio_device *vdev, unsigned int count);
+ int (*match)(struct vfio_device *vdev, char *buf);
+ void (*dma_unmap)(struct vfio_device *vdev, u64 iova, u64 length);
+ int (*device_feature)(struct vfio_device *device, u32 flags,
+ void __user *arg, size_t argsz);
};
-Each function is passed the device_data that was originally registered
-in the vfio_add_group_dev() call above. This allows the bus driver
-an easy place to store its opaque, private data. The open/release
-callbacks are issued when a new file descriptor is created for a
-device (via VFIO_GROUP_GET_DEVICE_FD). The ioctl interface provides
-a direct pass through for VFIO_DEVICE_* ioctls. The read/write/mmap
-interfaces implement the device region access defined by the device's
-own VFIO_DEVICE_GET_REGION_INFO ioctl.
+Each function is passed the vdev that was originally registered
+in the vfio_register_group_dev() or vfio_register_emulated_iommu_dev()
+call above. This allows the bus driver to obtain its private data using
+container_of().
+
+::
+
+ - The init/release callbacks are issued when vfio_device is initialized
+ and released.
+
+ - The open/close device callbacks are issued when the first
+ instance of a file descriptor for the device is created (eg.
+ via VFIO_GROUP_GET_DEVICE_FD) for a user session.
+
+ - The ioctl callback provides a direct pass through for some VFIO_DEVICE_*
+ ioctls.
+ - The [un]bind_iommufd callbacks are issued when the device is bound to
+ and unbound from iommufd.
+
+ - The [de]attach_ioas callback is issued when the device is attached to
+ and detached from an IOAS managed by the bound iommufd. However, the
+ attached IOAS can also be automatically detached when the device is
+ unbound from iommufd.
+
+ - The read/write/mmap callbacks implement the device region access defined
+ by the device's own VFIO_DEVICE_GET_REGION_INFO ioctl.
+
+ - The request callback is issued when device is going to be unregistered,
+ such as when trying to unbind the device from the vfio bus driver.
+
+ - The dma_unmap callback is issued when a range of iovas are unmapped
+ in the container or IOAS attached by the device. Drivers which make
+ use of the vfio page pinning interface must implement this callback in
+ order to unpin pages within the dma_unmap range. Drivers must tolerate
+ this callback even before calls to open_device().
PPC64 sPAPR implementation note
-------------------------------
@@ -518,3 +697,11 @@ This implementation has some specifics:
\-0d.1
00:1e.0 PCI bridge: Intel Corporation 82801 PCI Bridge (rev 90)
+
+.. [5] Nested translation is an IOMMU feature which supports two stage
+ address translations. This improves the address translation efficiency
+ in IOMMU virtualization.
+
+.. [6] PASID stands for Process Address Space ID, introduced by PCI
+ Express. It is a prerequisite for Shared Virtual Addressing (SVA)
+ and Scalable I/O Virtualization (Scalable IOV).
diff --git a/Documentation/driver-api/virtio/index.rst b/Documentation/driver-api/virtio/index.rst
new file mode 100644
index 000000000000..528b14b291e3
--- /dev/null
+++ b/Documentation/driver-api/virtio/index.rst
@@ -0,0 +1,11 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+======
+Virtio
+======
+
+.. toctree::
+ :maxdepth: 1
+
+ virtio
+ writing_virtio_drivers
diff --git a/Documentation/driver-api/virtio/virtio.rst b/Documentation/driver-api/virtio/virtio.rst
new file mode 100644
index 000000000000..7947b4ca690e
--- /dev/null
+++ b/Documentation/driver-api/virtio/virtio.rst
@@ -0,0 +1,145 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+.. _virtio:
+
+===============
+Virtio on Linux
+===============
+
+Introduction
+============
+
+Virtio is an open standard that defines a protocol for communication
+between drivers and devices of different types, see Chapter 5 ("Device
+Types") of the virtio spec (`[1]`_). Originally developed as a standard
+for paravirtualized devices implemented by a hypervisor, it can be used
+to interface any compliant device (real or emulated) with a driver.
+
+For illustrative purposes, this document will focus on the common case
+of a Linux kernel running in a virtual machine and using paravirtualized
+devices provided by the hypervisor, which exposes them as virtio devices
+via standard mechanisms such as PCI.
+
+
+Device - Driver communication: virtqueues
+=========================================
+
+Although the virtio devices are really an abstraction layer in the
+hypervisor, they're exposed to the guest as if they are physical devices
+using a specific transport method -- PCI, MMIO or CCW -- that is
+orthogonal to the device itself. The virtio spec defines these transport
+methods in detail, including device discovery, capabilities and
+interrupt handling.
+
+The communication between the driver in the guest OS and the device in
+the hypervisor is done through shared memory (that's what makes virtio
+devices so efficient) using specialized data structures called
+virtqueues, which are actually ring buffers [#f1]_ of buffer descriptors
+similar to the ones used in a network device:
+
+.. kernel-doc:: include/uapi/linux/virtio_ring.h
+ :identifiers: struct vring_desc
+
+All the buffers the descriptors point to are allocated by the guest and
+used by the host either for reading or for writing but not for both.
+
+Refer to Chapter 2.5 ("Virtqueues") of the virtio spec (`[1]`_) for the
+reference definitions of virtqueues and "Virtqueues and virtio ring: How
+the data travels" blog post (`[2]`_) for an illustrated overview of how
+the host device and the guest driver communicate.
+
+The :c:type:`vring_virtqueue` struct models a virtqueue, including the
+ring buffers and management data. Embedded in this struct is the
+:c:type:`virtqueue` struct, which is the data structure that's
+ultimately used by virtio drivers:
+
+.. kernel-doc:: include/linux/virtio.h
+ :identifiers: struct virtqueue
+
+The callback function pointed by this struct is triggered when the
+device has consumed the buffers provided by the driver. More
+specifically, the trigger will be an interrupt issued by the hypervisor
+(see vring_interrupt()). Interrupt request handlers are registered for
+a virtqueue during the virtqueue setup process (transport-specific).
+
+.. kernel-doc:: drivers/virtio/virtio_ring.c
+ :identifiers: vring_interrupt
+
+
+Device discovery and probing
+============================
+
+In the kernel, the virtio core contains the virtio bus driver and
+transport-specific drivers like `virtio-pci` and `virtio-mmio`. Then
+there are individual virtio drivers for specific device types that are
+registered to the virtio bus driver.
+
+How a virtio device is found and configured by the kernel depends on how
+the hypervisor defines it. Taking the `QEMU virtio-console
+<https://gitlab.com/qemu-project/qemu/-/blob/master/hw/char/virtio-console.c>`__
+device as an example. When using PCI as a transport method, the device
+will present itself on the PCI bus with vendor 0x1af4 (Red Hat, Inc.)
+and device id 0x1003 (virtio console), as defined in the spec, so the
+kernel will detect it as it would do with any other PCI device.
+
+During the PCI enumeration process, if a device is found to match the
+virtio-pci driver (according to the virtio-pci device table, any PCI
+device with vendor id = 0x1af4)::
+
+ /* Qumranet donated their vendor ID for devices 0x1000 thru 0x10FF. */
+ static const struct pci_device_id virtio_pci_id_table[] = {
+ { PCI_DEVICE(PCI_VENDOR_ID_REDHAT_QUMRANET, PCI_ANY_ID) },
+ { 0 }
+ };
+
+then the virtio-pci driver is probed and, if the probing goes well, the
+device is registered to the virtio bus::
+
+ static int virtio_pci_probe(struct pci_dev *pci_dev,
+ const struct pci_device_id *id)
+ {
+ ...
+
+ if (force_legacy) {
+ rc = virtio_pci_legacy_probe(vp_dev);
+ /* Also try modern mode if we can't map BAR0 (no IO space). */
+ if (rc == -ENODEV || rc == -ENOMEM)
+ rc = virtio_pci_modern_probe(vp_dev);
+ if (rc)
+ goto err_probe;
+ } else {
+ rc = virtio_pci_modern_probe(vp_dev);
+ if (rc == -ENODEV)
+ rc = virtio_pci_legacy_probe(vp_dev);
+ if (rc)
+ goto err_probe;
+ }
+
+ ...
+
+ rc = register_virtio_device(&vp_dev->vdev);
+
+When the device is registered to the virtio bus the kernel will look
+for a driver in the bus that can handle the device and call that
+driver's ``probe`` method.
+
+At this point, the virtqueues will be allocated and configured by
+calling the appropriate ``virtio_find`` helper function, such as
+virtio_find_single_vq() or virtio_find_vqs(), which will end up calling
+a transport-specific ``find_vqs`` method.
+
+
+References
+==========
+
+_`[1]` Virtio Spec v1.2:
+https://docs.oasis-open.org/virtio/virtio/v1.2/virtio-v1.2.html
+
+.. Check for later versions of the spec as well.
+
+_`[2]` Virtqueues and virtio ring: How the data travels
+https://www.redhat.com/en/blog/virtqueues-and-virtio-ring-how-data-travels
+
+.. rubric:: Footnotes
+
+.. [#f1] that's why they may be also referred to as virtrings.
diff --git a/Documentation/driver-api/virtio/writing_virtio_drivers.rst b/Documentation/driver-api/virtio/writing_virtio_drivers.rst
new file mode 100644
index 000000000000..e14c58796d25
--- /dev/null
+++ b/Documentation/driver-api/virtio/writing_virtio_drivers.rst
@@ -0,0 +1,197 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+.. _writing_virtio_drivers:
+
+======================
+Writing Virtio Drivers
+======================
+
+Introduction
+============
+
+This document serves as a basic guideline for driver programmers that
+need to hack a new virtio driver or understand the essentials of the
+existing ones. See :ref:`Virtio on Linux <virtio>` for a general
+overview of virtio.
+
+
+Driver boilerplate
+==================
+
+As a bare minimum, a virtio driver needs to register in the virtio bus
+and configure the virtqueues for the device according to its spec, the
+configuration of the virtqueues in the driver side must match the
+virtqueue definitions in the device. A basic driver skeleton could look
+like this::
+
+ #include <linux/virtio.h>
+ #include <linux/virtio_ids.h>
+ #include <linux/virtio_config.h>
+ #include <linux/module.h>
+
+ /* device private data (one per device) */
+ struct virtio_dummy_dev {
+ struct virtqueue *vq;
+ };
+
+ static void virtio_dummy_recv_cb(struct virtqueue *vq)
+ {
+ struct virtio_dummy_dev *dev = vq->vdev->priv;
+ char *buf;
+ unsigned int len;
+
+ while ((buf = virtqueue_get_buf(dev->vq, &len)) != NULL) {
+ /* process the received data */
+ }
+ }
+
+ static int virtio_dummy_probe(struct virtio_device *vdev)
+ {
+ struct virtio_dummy_dev *dev = NULL;
+
+ /* initialize device data */
+ dev = kzalloc(sizeof(struct virtio_dummy_dev), GFP_KERNEL);
+ if (!dev)
+ return -ENOMEM;
+
+ /* the device has a single virtqueue */
+ dev->vq = virtio_find_single_vq(vdev, virtio_dummy_recv_cb, "input");
+ if (IS_ERR(dev->vq)) {
+ kfree(dev);
+ return PTR_ERR(dev->vq);
+
+ }
+ vdev->priv = dev;
+
+ /* from this point on, the device can notify and get callbacks */
+ virtio_device_ready(vdev);
+
+ return 0;
+ }
+
+ static void virtio_dummy_remove(struct virtio_device *vdev)
+ {
+ struct virtio_dummy_dev *dev = vdev->priv;
+
+ /*
+ * disable vq interrupts: equivalent to
+ * vdev->config->reset(vdev)
+ */
+ virtio_reset_device(vdev);
+
+ /* detach unused buffers */
+ while ((buf = virtqueue_detach_unused_buf(dev->vq)) != NULL) {
+ kfree(buf);
+ }
+
+ /* remove virtqueues */
+ vdev->config->del_vqs(vdev);
+
+ kfree(dev);
+ }
+
+ static const struct virtio_device_id id_table[] = {
+ { VIRTIO_ID_DUMMY, VIRTIO_DEV_ANY_ID },
+ { 0 },
+ };
+
+ static struct virtio_driver virtio_dummy_driver = {
+ .driver.name = KBUILD_MODNAME,
+ .driver.owner = THIS_MODULE,
+ .id_table = id_table,
+ .probe = virtio_dummy_probe,
+ .remove = virtio_dummy_remove,
+ };
+
+ module_virtio_driver(virtio_dummy_driver);
+ MODULE_DEVICE_TABLE(virtio, id_table);
+ MODULE_DESCRIPTION("Dummy virtio driver");
+ MODULE_LICENSE("GPL");
+
+The device id ``VIRTIO_ID_DUMMY`` here is a placeholder, virtio drivers
+should be added only for devices that are defined in the spec, see
+include/uapi/linux/virtio_ids.h. Device ids need to be at least reserved
+in the virtio spec before being added to that file.
+
+If your driver doesn't have to do anything special in its ``init`` and
+``exit`` methods, you can use the module_virtio_driver() helper to
+reduce the amount of boilerplate code.
+
+The ``probe`` method does the minimum driver setup in this case
+(memory allocation for the device data) and initializes the
+virtqueue. virtio_device_ready() is used to enable the virtqueue and to
+notify the device that the driver is ready to manage the device
+("DRIVER_OK"). The virtqueues are anyway enabled automatically by the
+core after ``probe`` returns.
+
+.. kernel-doc:: include/linux/virtio_config.h
+ :identifiers: virtio_device_ready
+
+In any case, the virtqueues need to be enabled before adding buffers to
+them.
+
+Sending and receiving data
+==========================
+
+The virtio_dummy_recv_cb() callback in the code above will be triggered
+when the device notifies the driver after it finishes processing a
+descriptor or descriptor chain, either for reading or writing. However,
+that's only the second half of the virtio device-driver communication
+process, as the communication is always started by the driver regardless
+of the direction of the data transfer.
+
+To configure a buffer transfer from the driver to the device, first you
+have to add the buffers -- packed as `scatterlists` -- to the
+appropriate virtqueue using any of the virtqueue_add_inbuf(),
+virtqueue_add_outbuf() or virtqueue_add_sgs(), depending on whether you
+need to add one input `scatterlist` (for the device to fill in), one
+output `scatterlist` (for the device to consume) or multiple
+`scatterlists`, respectively. Then, once the virtqueue is set up, a call
+to virtqueue_kick() sends a notification that will be serviced by the
+hypervisor that implements the device::
+
+ struct scatterlist sg[1];
+ sg_init_one(sg, buffer, BUFLEN);
+ virtqueue_add_inbuf(dev->vq, sg, 1, buffer, GFP_ATOMIC);
+ virtqueue_kick(dev->vq);
+
+.. kernel-doc:: drivers/virtio/virtio_ring.c
+ :identifiers: virtqueue_add_inbuf
+
+.. kernel-doc:: drivers/virtio/virtio_ring.c
+ :identifiers: virtqueue_add_outbuf
+
+.. kernel-doc:: drivers/virtio/virtio_ring.c
+ :identifiers: virtqueue_add_sgs
+
+Then, after the device has read or written the buffers prepared by the
+driver and notifies it back, the driver can call virtqueue_get_buf() to
+read the data produced by the device (if the virtqueue was set up with
+input buffers) or simply to reclaim the buffers if they were already
+consumed by the device:
+
+.. kernel-doc:: drivers/virtio/virtio_ring.c
+ :identifiers: virtqueue_get_buf_ctx
+
+The virtqueue callbacks can be disabled and re-enabled using the
+virtqueue_disable_cb() and the family of virtqueue_enable_cb() functions
+respectively. See drivers/virtio/virtio_ring.c for more details:
+
+.. kernel-doc:: drivers/virtio/virtio_ring.c
+ :identifiers: virtqueue_disable_cb
+
+.. kernel-doc:: drivers/virtio/virtio_ring.c
+ :identifiers: virtqueue_enable_cb
+
+But note that some spurious callbacks can still be triggered under
+certain scenarios. The way to disable callbacks reliably is to reset the
+device or the virtqueue (virtio_reset_device()).
+
+
+References
+==========
+
+_`[1]` Virtio Spec v1.2:
+https://docs.oasis-open.org/virtio/virtio/v1.2/virtio-v1.2.html
+
+Check for later versions of the spec as well.
diff --git a/Documentation/driver-api/vme.rst b/Documentation/driver-api/vme.rst
index def139c13410..c0b475369de0 100644
--- a/Documentation/driver-api/vme.rst
+++ b/Documentation/driver-api/vme.rst
@@ -290,8 +290,8 @@ The function :c:func:`vme_bus_num` returns the bus ID of the provided bridge.
VME API
-------
-.. kernel-doc:: include/linux/vme.h
+.. kernel-doc:: drivers/staging/vme_user/vme.h
:internal:
-.. kernel-doc:: drivers/vme/vme.c
+.. kernel-doc:: drivers/staging/vme_user/vme.c
:export:
diff --git a/Documentation/driver-api/wbrf.rst b/Documentation/driver-api/wbrf.rst
new file mode 100644
index 000000000000..f48bfa029813
--- /dev/null
+++ b/Documentation/driver-api/wbrf.rst
@@ -0,0 +1,78 @@
+.. SPDX-License-Identifier: GPL-2.0-or-later
+
+=================================
+WBRF - Wifi Band RFI Mitigations
+=================================
+
+Due to electrical and mechanical constraints in certain platform designs
+there may be likely interference of relatively high-powered harmonics of
+the GPU memory clocks with local radio module frequency bands used by
+certain Wifi bands.
+
+To mitigate possible RFI interference producers can advertise the
+frequencies in use and consumers can use this information to avoid using
+these frequencies for sensitive features.
+
+When a platform is known to have this issue with any contained devices,
+the platform designer will advertise the availability of this feature via
+ACPI devices with a device specific method (_DSM).
+* Producers with this _DSM will be able to advertise the frequencies in use.
+* Consumers with this _DSM will be able to register for notifications of
+frequencies in use.
+
+Some general terms
+==================
+
+Producer: such component who can produce high-powered radio frequency
+Consumer: such component who can adjust its in-use frequency in
+response to the radio frequencies of other components to mitigate the
+possible RFI.
+
+To make the mechanism function, those producers should notify active use
+of their particular frequencies so that other consumers can make relative
+internal adjustments as necessary to avoid this resonance.
+
+ACPI interface
+==============
+
+Although initially used by for wifi + dGPU use cases, the ACPI interface
+can be scaled to any type of device that a platform designer discovers
+can cause interference.
+
+The GUID used for the _DSM is 7B7656CF-DC3D-4C1C-83E9-66E721DE3070.
+
+3 functions are available in this _DSM:
+
+* 0: discover # of functions available
+* 1: record RF bands in use
+* 2: retrieve RF bands in use
+
+Driver programming interface
+============================
+
+.. kernel-doc:: drivers/platform/x86/amd/wbrf.c
+
+Sample Usage
+=============
+
+The expected flow for the producers:
+1. During probe, call `acpi_amd_wbrf_supported_producer` to check if WBRF
+can be enabled for the device.
+2. On using some frequency band, call `acpi_amd_wbrf_add_remove` with 'add'
+param to get other consumers properly notified.
+3. Or on stopping using some frequency band, call
+`acpi_amd_wbrf_add_remove` with 'remove' param to get other consumers notified.
+
+The expected flow for the consumers:
+1. During probe, call `acpi_amd_wbrf_supported_consumer` to check if WBRF
+can be enabled for the device.
+2. Call `amd_wbrf_register_notifier` to register for notification
+of frequency band change(add or remove) from other producers.
+3. Call the `amd_wbrf_retrieve_freq_band` initally to retrieve
+current active frequency bands considering some producers may broadcast
+such information before the consumer is up.
+4. On receiving a notification for frequency band change, run
+`amd_wbrf_retrieve_freq_band` again to retrieve the latest
+active frequency bands.
+5. During driver cleanup, call `amd_wbrf_unregister_notifier` to
+unregister the notifier.
diff --git a/Documentation/driver-api/wmi.rst b/Documentation/driver-api/wmi.rst
new file mode 100644
index 000000000000..6ca58c8249e5
--- /dev/null
+++ b/Documentation/driver-api/wmi.rst
@@ -0,0 +1,21 @@
+.. SPDX-License-Identifier: GPL-2.0-or-later
+
+==============
+WMI Driver API
+==============
+
+The WMI driver core supports a more modern bus-based interface for interacting
+with WMI devices, and an older GUID-based interface. The latter interface is
+considered to be deprecated, so new WMI drivers should generally avoid it since
+it has some issues with multiple WMI devices and events sharing the same GUIDs
+and/or notification IDs. The modern bus-based interface instead maps each
+WMI device to a :c:type:`struct wmi_device <wmi_device>`, so it supports
+WMI devices sharing GUIDs and/or notification IDs. Drivers can then register
+a :c:type:`struct wmi_driver <wmi_driver>`, which will be bound to compatible
+WMI devices by the driver core.
+
+.. kernel-doc:: include/linux/wmi.h
+ :internal:
+
+.. kernel-doc:: drivers/platform/x86/wmi.c
+ :export:
diff --git a/Documentation/driver-api/xilinx/eemi.rst b/Documentation/driver-api/xilinx/eemi.rst
index 9dcbc6f18d75..c1bc47b9000d 100644
--- a/Documentation/driver-api/xilinx/eemi.rst
+++ b/Documentation/driver-api/xilinx/eemi.rst
@@ -16,35 +16,8 @@ components running across different processing clusters on a chip or
device to communicate with a power management controller (PMC) on a
device to issue or respond to power management requests.
-EEMI ops is a structure containing all eemi APIs supported by Zynq MPSoC.
-The zynqmp-firmware driver maintain all EEMI APIs in zynqmp_eemi_ops
-structure. Any driver who want to communicate with PMC using EEMI APIs
-can call zynqmp_pm_get_eemi_ops().
-
-Example of EEMI ops::
-
- /* zynqmp-firmware driver maintain all EEMI APIs */
- struct zynqmp_eemi_ops {
- int (*get_api_version)(u32 *version);
- int (*query_data)(struct zynqmp_pm_query_data qdata, u32 *out);
- };
-
- static const struct zynqmp_eemi_ops eemi_ops = {
- .get_api_version = zynqmp_pm_get_api_version,
- .query_data = zynqmp_pm_query_data,
- };
-
-Example of EEMI ops usage::
-
- static const struct zynqmp_eemi_ops *eemi_ops;
- u32 ret_payload[PAYLOAD_ARG_CNT];
- int ret;
-
- eemi_ops = zynqmp_pm_get_eemi_ops();
- if (IS_ERR(eemi_ops))
- return PTR_ERR(eemi_ops);
-
- ret = eemi_ops->query_data(qdata, ret_payload);
+Any driver who wants to communicate with PMC using EEMI APIs use the
+functions provided for each function.
IOCTL
------
diff --git a/Documentation/driver-api/xillybus.rst b/Documentation/driver-api/xillybus.rst
index 2446ee303c09..a3ab832cb22b 100644
--- a/Documentation/driver-api/xillybus.rst
+++ b/Documentation/driver-api/xillybus.rst
@@ -273,7 +273,7 @@ buffer is full, the FPGA informs the host about that (appending a
XILLYMSG_OPCODE_RELEASEBUF message channel 0 and sending an interrupt if
necessary). The host responds by making the data available for reading through
the character device. When all data has been read, the host writes on the
-the FPGA's buffer control register, allowing the buffer's overwriting. Flow
+FPGA's buffer control register, allowing the buffer's overwriting. Flow
control mechanisms exist on both sides to prevent underflows and overflows.
This is not good enough for creating a TCP/IP-like stream: If the data flow