device-io.rst 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. .. Copyright 2001 Matthew Wilcox
  2. ..
  3. .. This documentation is free software; you can redistribute
  4. .. it and/or modify it under the terms of the GNU General Public
  5. .. License as published by the Free Software Foundation; either
  6. .. version 2 of the License, or (at your option) any later
  7. .. version.
  8. ===============================
  9. Bus-Independent Device Accesses
  10. ===============================
  11. :Author: Matthew Wilcox
  12. :Author: Alan Cox
  13. Introduction
  14. ============
  15. Linux provides an API which abstracts performing IO across all busses
  16. and devices, allowing device drivers to be written independently of bus
  17. type.
  18. Memory Mapped IO
  19. ================
  20. Getting Access to the Device
  21. ----------------------------
  22. The most widely supported form of IO is memory mapped IO. That is, a
  23. part of the CPU's address space is interpreted not as accesses to
  24. memory, but as accesses to a device. Some architectures define devices
  25. to be at a fixed address, but most have some method of discovering
  26. devices. The PCI bus walk is a good example of such a scheme. This
  27. document does not cover how to receive such an address, but assumes you
  28. are starting with one. Physical addresses are of type unsigned long.
  29. This address should not be used directly. Instead, to get an address
  30. suitable for passing to the accessor functions described below, you
  31. should call ioremap(). An address suitable for accessing
  32. the device will be returned to you.
  33. After you've finished using the device (say, in your module's exit
  34. routine), call iounmap() in order to return the address
  35. space to the kernel. Most architectures allocate new address space each
  36. time you call ioremap(), and they can run out unless you
  37. call iounmap().
  38. Accessing the device
  39. --------------------
  40. The part of the interface most used by drivers is reading and writing
  41. memory-mapped registers on the device. Linux provides interfaces to read
  42. and write 8-bit, 16-bit, 32-bit and 64-bit quantities. Due to a
  43. historical accident, these are named byte, word, long and quad accesses.
  44. Both read and write accesses are supported; there is no prefetch support
  45. at this time.
  46. The functions are named readb(), readw(), readl(), readq(),
  47. readb_relaxed(), readw_relaxed(), readl_relaxed(), readq_relaxed(),
  48. writeb(), writew(), writel() and writeq().
  49. Some devices (such as framebuffers) would like to use larger transfers than
  50. 8 bytes at a time. For these devices, the memcpy_toio(),
  51. memcpy_fromio() and memset_io() functions are
  52. provided. Do not use memset or memcpy on IO addresses; they are not
  53. guaranteed to copy data in order.
  54. The read and write functions are defined to be ordered. That is the
  55. compiler is not permitted to reorder the I/O sequence. When the ordering
  56. can be compiler optimised, you can use __readb() and friends to
  57. indicate the relaxed ordering. Use this with care.
  58. While the basic functions are defined to be synchronous with respect to
  59. each other and ordered with respect to each other the busses the devices
  60. sit on may themselves have asynchronicity. In particular many authors
  61. are burned by the fact that PCI bus writes are posted asynchronously. A
  62. driver author must issue a read from the same device to ensure that
  63. writes have occurred in the specific cases the author cares. This kind
  64. of property cannot be hidden from driver writers in the API. In some
  65. cases, the read used to flush the device may be expected to fail (if the
  66. card is resetting, for example). In that case, the read should be done
  67. from config space, which is guaranteed to soft-fail if the card doesn't
  68. respond.
  69. The following is an example of flushing a write to a device when the
  70. driver would like to ensure the write's effects are visible prior to
  71. continuing execution::
  72. static inline void
  73. qla1280_disable_intrs(struct scsi_qla_host *ha)
  74. {
  75. struct device_reg *reg;
  76. reg = ha->iobase;
  77. /* disable risc and host interrupts */
  78. WRT_REG_WORD(&reg->ictrl, 0);
  79. /*
  80. * The following read will ensure that the above write
  81. * has been received by the device before we return from this
  82. * function.
  83. */
  84. RD_REG_WORD(&reg->ictrl);
  85. ha->flags.ints_enabled = 0;
  86. }
  87. PCI ordering rules also guarantee that PIO read responses arrive after any
  88. outstanding DMA writes from that bus, since for some devices the result of
  89. a readb() call may signal to the driver that a DMA transaction is
  90. complete. In many cases, however, the driver may want to indicate that the
  91. next readb() call has no relation to any previous DMA writes
  92. performed by the device. The driver can use readb_relaxed() for
  93. these cases, although only some platforms will honor the relaxed
  94. semantics. Using the relaxed read functions will provide significant
  95. performance benefits on platforms that support it. The qla2xxx driver
  96. provides examples of how to use readX_relaxed(). In many cases, a majority
  97. of the driver's readX() calls can safely be converted to readX_relaxed()
  98. calls, since only a few will indicate or depend on DMA completion.
  99. Port Space Accesses
  100. ===================
  101. Port Space Explained
  102. --------------------
  103. Another form of IO commonly supported is Port Space. This is a range of
  104. addresses separate to the normal memory address space. Access to these
  105. addresses is generally not as fast as accesses to the memory mapped
  106. addresses, and it also has a potentially smaller address space.
  107. Unlike memory mapped IO, no preparation is required to access port
  108. space.
  109. Accessing Port Space
  110. --------------------
  111. Accesses to this space are provided through a set of functions which
  112. allow 8-bit, 16-bit and 32-bit accesses; also known as byte, word and
  113. long. These functions are inb(), inw(),
  114. inl(), outb(), outw() and
  115. outl().
  116. Some variants are provided for these functions. Some devices require
  117. that accesses to their ports are slowed down. This functionality is
  118. provided by appending a ``_p`` to the end of the function.
  119. There are also equivalents to memcpy. The ins() and
  120. outs() functions copy bytes, words or longs to the given
  121. port.
  122. __iomem pointer tokens
  123. ======================
  124. The data type for an MMIO address is an ``__iomem`` qualified pointer, such as
  125. ``void __iomem *reg``. On most architectures it is a regular pointer that
  126. points to a virtual memory address and can be offset or dereferenced, but in
  127. portable code, it must only be passed from and to functions that explicitly
  128. operated on an ``__iomem`` token, in particular the ioremap() and
  129. readl()/writel() functions. The 'sparse' semantic code checker can be used to
  130. verify that this is done correctly.
  131. While on most architectures, ioremap() creates a page table entry for an
  132. uncached virtual address pointing to the physical MMIO address, some
  133. architectures require special instructions for MMIO, and the ``__iomem`` pointer
  134. just encodes the physical address or an offsettable cookie that is interpreted
  135. by readl()/writel().
  136. Differences between I/O access functions
  137. ========================================
  138. readq(), readl(), readw(), readb(), writeq(), writel(), writew(), writeb()
  139. These are the most generic accessors, providing serialization against other
  140. MMIO accesses and DMA accesses as well as fixed endianness for accessing
  141. little-endian PCI devices and on-chip peripherals. Portable device drivers
  142. should generally use these for any access to ``__iomem`` pointers.
  143. Note that posted writes are not strictly ordered against a spinlock, see
  144. Documentation/driver-api/io_ordering.rst.
  145. readq_relaxed(), readl_relaxed(), readw_relaxed(), readb_relaxed(),
  146. writeq_relaxed(), writel_relaxed(), writew_relaxed(), writeb_relaxed()
  147. On architectures that require an expensive barrier for serializing against
  148. DMA, these "relaxed" versions of the MMIO accessors only serialize against
  149. each other, but contain a less expensive barrier operation. A device driver
  150. might use these in a particularly performance sensitive fast path, with a
  151. comment that explains why the usage in a specific location is safe without
  152. the extra barriers.
  153. See memory-barriers.txt for a more detailed discussion on the precise ordering
  154. guarantees of the non-relaxed and relaxed versions.
  155. ioread64(), ioread32(), ioread16(), ioread8(),
  156. iowrite64(), iowrite32(), iowrite16(), iowrite8()
  157. These are an alternative to the normal readl()/writel() functions, with almost
  158. identical behavior, but they can also operate on ``__iomem`` tokens returned
  159. for mapping PCI I/O space with pci_iomap() or ioport_map(). On architectures
  160. that require special instructions for I/O port access, this adds a small
  161. overhead for an indirect function call implemented in lib/iomap.c, while on
  162. other architectures, these are simply aliases.
  163. ioread64be(), ioread32be(), ioread16be()
  164. iowrite64be(), iowrite32be(), iowrite16be()
  165. These behave in the same way as the ioread32()/iowrite32() family, but with
  166. reversed byte order, for accessing devices with big-endian MMIO registers.
  167. Device drivers that can operate on either big-endian or little-endian
  168. registers may have to implement a custom wrapper function that picks one or
  169. the other depending on which device was found.
  170. Note: On some architectures, the normal readl()/writel() functions
  171. traditionally assume that devices are the same endianness as the CPU, while
  172. using a hardware byte-reverse on the PCI bus when running a big-endian kernel.
  173. Drivers that use readl()/writel() this way are generally not portable, but
  174. tend to be limited to a particular SoC.
  175. hi_lo_readq(), lo_hi_readq(), hi_lo_readq_relaxed(), lo_hi_readq_relaxed(),
  176. ioread64_lo_hi(), ioread64_hi_lo(), ioread64be_lo_hi(), ioread64be_hi_lo(),
  177. hi_lo_writeq(), lo_hi_writeq(), hi_lo_writeq_relaxed(), lo_hi_writeq_relaxed(),
  178. iowrite64_lo_hi(), iowrite64_hi_lo(), iowrite64be_lo_hi(), iowrite64be_hi_lo()
  179. Some device drivers have 64-bit registers that cannot be accessed atomically
  180. on 32-bit architectures but allow two consecutive 32-bit accesses instead.
  181. Since it depends on the particular device which of the two halves has to be
  182. accessed first, a helper is provided for each combination of 64-bit accessors
  183. with either low/high or high/low word ordering. A device driver must include
  184. either <linux/io-64-nonatomic-lo-hi.h> or <linux/io-64-nonatomic-hi-lo.h> to
  185. get the function definitions along with helpers that redirect the normal
  186. readq()/writeq() to them on architectures that do not provide 64-bit access
  187. natively.
  188. __raw_readq(), __raw_readl(), __raw_readw(), __raw_readb(),
  189. __raw_writeq(), __raw_writel(), __raw_writew(), __raw_writeb()
  190. These are low-level MMIO accessors without barriers or byteorder changes and
  191. architecture specific behavior. Accesses are usually atomic in the sense that
  192. a four-byte __raw_readl() does not get split into individual byte loads, but
  193. multiple consecutive accesses can be combined on the bus. In portable code, it
  194. is only safe to use these to access memory behind a device bus but not MMIO
  195. registers, as there are no ordering guarantees with regard to other MMIO
  196. accesses or even spinlocks. The byte order is generally the same as for normal
  197. memory, so unlike the other functions, these can be used to copy data between
  198. kernel memory and device memory.
  199. inl(), inw(), inb(), outl(), outw(), outb()
  200. PCI I/O port resources traditionally require separate helpers as they are
  201. implemented using special instructions on the x86 architecture. On most other
  202. architectures, these are mapped to readl()/writel() style accessors
  203. internally, usually pointing to a fixed area in virtual memory. Instead of an
  204. ``__iomem`` pointer, the address is a 32-bit integer token to identify a port
  205. number. PCI requires I/O port access to be non-posted, meaning that an outb()
  206. must complete before the following code executes, while a normal writeb() may
  207. still be in progress. On architectures that correctly implement this, I/O port
  208. access is therefore ordered against spinlocks. Many non-x86 PCI host bridge
  209. implementations and CPU architectures however fail to implement non-posted I/O
  210. space on PCI, so they can end up being posted on such hardware.
  211. In some architectures, the I/O port number space has a 1:1 mapping to
  212. ``__iomem`` pointers, but this is not recommended and device drivers should
  213. not rely on that for portability. Similarly, an I/O port number as described
  214. in a PCI base address register may not correspond to the port number as seen
  215. by a device driver. Portable drivers need to read the port number for the
  216. resource provided by the kernel.
  217. There are no direct 64-bit I/O port accessors, but pci_iomap() in combination
  218. with ioread64/iowrite64 can be used instead.
  219. inl_p(), inw_p(), inb_p(), outl_p(), outw_p(), outb_p()
  220. On ISA devices that require specific timing, the _p versions of the I/O
  221. accessors add a small delay. On architectures that do not have ISA buses,
  222. these are aliases to the normal inb/outb helpers.
  223. readsq, readsl, readsw, readsb
  224. writesq, writesl, writesw, writesb
  225. ioread64_rep, ioread32_rep, ioread16_rep, ioread8_rep
  226. iowrite64_rep, iowrite32_rep, iowrite16_rep, iowrite8_rep
  227. insl, insw, insb, outsl, outsw, outsb
  228. These are helpers that access the same address multiple times, usually to copy
  229. data between kernel memory byte stream and a FIFO buffer. Unlike the normal
  230. MMIO accessors, these do not perform a byteswap on big-endian kernels, so the
  231. first byte in the FIFO register corresponds to the first byte in the memory
  232. buffer regardless of the architecture.
  233. Device memory mapping modes
  234. ===========================
  235. Some architectures support multiple modes for mapping device memory.
  236. ioremap_*() variants provide a common abstraction around these
  237. architecture-specific modes, with a shared set of semantics.
  238. ioremap() is the most common mapping type, and is applicable to typical device
  239. memory (e.g. I/O registers). Other modes can offer weaker or stronger
  240. guarantees, if supported by the architecture. From most to least common, they
  241. are as follows:
  242. ioremap()
  243. ---------
  244. The default mode, suitable for most memory-mapped devices, e.g. control
  245. registers. Memory mapped using ioremap() has the following characteristics:
  246. * Uncached - CPU-side caches are bypassed, and all reads and writes are handled
  247. directly by the device
  248. * No speculative operations - the CPU may not issue a read or write to this
  249. memory, unless the instruction that does so has been reached in committed
  250. program flow.
  251. * No reordering - The CPU may not reorder accesses to this memory mapping with
  252. respect to each other. On some architectures, this relies on barriers in
  253. readl_relaxed()/writel_relaxed().
  254. * No repetition - The CPU may not issue multiple reads or writes for a single
  255. program instruction.
  256. * No write-combining - Each I/O operation results in one discrete read or write
  257. being issued to the device, and multiple writes are not combined into larger
  258. writes. This may or may not be enforced when using __raw I/O accessors or
  259. pointer dereferences.
  260. * Non-executable - The CPU is not allowed to speculate instruction execution
  261. from this memory (it probably goes without saying, but you're also not
  262. allowed to jump into device memory).
  263. On many platforms and buses (e.g. PCI), writes issued through ioremap()
  264. mappings are posted, which means that the CPU does not wait for the write to
  265. actually reach the target device before retiring the write instruction.
  266. On many platforms, I/O accesses must be aligned with respect to the access
  267. size; failure to do so will result in an exception or unpredictable results.
  268. ioremap_wc()
  269. ------------
  270. Maps I/O memory as normal memory with write combining. Unlike ioremap(),
  271. * The CPU may speculatively issue reads from the device that the program
  272. didn't actually execute, and may choose to basically read whatever it wants.
  273. * The CPU may reorder operations as long as the result is consistent from the
  274. program's point of view.
  275. * The CPU may write to the same location multiple times, even when the program
  276. issued a single write.
  277. * The CPU may combine several writes into a single larger write.
  278. This mode is typically used for video framebuffers, where it can increase
  279. performance of writes. It can also be used for other blocks of memory in
  280. devices (e.g. buffers or shared memory), but care must be taken as accesses are
  281. not guaranteed to be ordered with respect to normal ioremap() MMIO register
  282. accesses without explicit barriers.
  283. On a PCI bus, it is usually safe to use ioremap_wc() on MMIO areas marked as
  284. ``IORESOURCE_PREFETCH``, but it may not be used on those without the flag.
  285. For on-chip devices, there is no corresponding flag, but a driver can use
  286. ioremap_wc() on a device that is known to be safe.
  287. ioremap_wt()
  288. ------------
  289. Maps I/O memory as normal memory with write-through caching. Like ioremap_wc(),
  290. but also,
  291. * The CPU may cache writes issued to and reads from the device, and serve reads
  292. from that cache.
  293. This mode is sometimes used for video framebuffers, where drivers still expect
  294. writes to reach the device in a timely manner (and not be stuck in the CPU
  295. cache), but reads may be served from the cache for efficiency. However, it is
  296. rarely useful these days, as framebuffer drivers usually perform writes only,
  297. for which ioremap_wc() is more efficient (as it doesn't needlessly trash the
  298. cache). Most drivers should not use this.
  299. ioremap_np()
  300. ------------
  301. Like ioremap(), but explicitly requests non-posted write semantics. On some
  302. architectures and buses, ioremap() mappings have posted write semantics, which
  303. means that writes can appear to "complete" from the point of view of the
  304. CPU before the written data actually arrives at the target device. Writes are
  305. still ordered with respect to other writes and reads from the same device, but
  306. due to the posted write semantics, this is not the case with respect to other
  307. devices. ioremap_np() explicitly requests non-posted semantics, which means
  308. that the write instruction will not appear to complete until the device has
  309. received (and to some platform-specific extent acknowledged) the written data.
  310. This mapping mode primarily exists to cater for platforms with bus fabrics that
  311. require this particular mapping mode to work correctly. These platforms set the
  312. ``IORESOURCE_MEM_NONPOSTED`` flag for a resource that requires ioremap_np()
  313. semantics and portable drivers should use an abstraction that automatically
  314. selects it where appropriate (see the `Higher-level ioremap abstractions`_
  315. section below).
  316. The bare ioremap_np() is only available on some architectures; on others, it
  317. always returns NULL. Drivers should not normally use it, unless they are
  318. platform-specific or they derive benefit from non-posted writes where
  319. supported, and can fall back to ioremap() otherwise. The normal approach to
  320. ensure posted write completion is to do a dummy read after a write as
  321. explained in `Accessing the device`_, which works with ioremap() on all
  322. platforms.
  323. ioremap_np() should never be used for PCI drivers. PCI memory space writes are
  324. always posted, even on architectures that otherwise implement ioremap_np().
  325. Using ioremap_np() for PCI BARs will at best result in posted write semantics,
  326. and at worst result in complete breakage.
  327. Note that non-posted write semantics are orthogonal to CPU-side ordering
  328. guarantees. A CPU may still choose to issue other reads or writes before a
  329. non-posted write instruction retires. See the previous section on MMIO access
  330. functions for details on the CPU side of things.
  331. ioremap_uc()
  332. ------------
  333. ioremap_uc() behaves like ioremap() except that on the x86 architecture without
  334. 'PAT' mode, it marks memory as uncached even when the MTRR has designated
  335. it as cacheable, see Documentation/x86/pat.rst.
  336. Portable drivers should avoid the use of ioremap_uc().
  337. ioremap_cache()
  338. ---------------
  339. ioremap_cache() effectively maps I/O memory as normal RAM. CPU write-back
  340. caches can be used, and the CPU is free to treat the device as if it were a
  341. block of RAM. This should never be used for device memory which has side
  342. effects of any kind, or which does not return the data previously written on
  343. read.
  344. It should also not be used for actual RAM, as the returned pointer is an
  345. ``__iomem`` token. memremap() can be used for mapping normal RAM that is outside
  346. of the linear kernel memory area to a regular pointer.
  347. Portable drivers should avoid the use of ioremap_cache().
  348. Architecture example
  349. --------------------
  350. Here is how the above modes map to memory attribute settings on the ARM64
  351. architecture:
  352. +------------------------+--------------------------------------------+
  353. | API | Memory region type and cacheability |
  354. +------------------------+--------------------------------------------+
  355. | ioremap_np() | Device-nGnRnE |
  356. +------------------------+--------------------------------------------+
  357. | ioremap() | Device-nGnRE |
  358. +------------------------+--------------------------------------------+
  359. | ioremap_uc() | (not implemented) |
  360. +------------------------+--------------------------------------------+
  361. | ioremap_wc() | Normal-Non Cacheable |
  362. +------------------------+--------------------------------------------+
  363. | ioremap_wt() | (not implemented; fallback to ioremap) |
  364. +------------------------+--------------------------------------------+
  365. | ioremap_cache() | Normal-Write-Back Cacheable |
  366. +------------------------+--------------------------------------------+
  367. Higher-level ioremap abstractions
  368. =================================
  369. Instead of using the above raw ioremap() modes, drivers are encouraged to use
  370. higher-level APIs. These APIs may implement platform-specific logic to
  371. automatically choose an appropriate ioremap mode on any given bus, allowing for
  372. a platform-agnostic driver to work on those platforms without any special
  373. cases. At the time of this writing, the following ioremap() wrappers have such
  374. logic:
  375. devm_ioremap_resource()
  376. Can automatically select ioremap_np() over ioremap() according to platform
  377. requirements, if the ``IORESOURCE_MEM_NONPOSTED`` flag is set on the struct
  378. resource. Uses devres to automatically unmap the resource when the driver
  379. probe() function fails or a device in unbound from its driver.
  380. Documented in Documentation/driver-api/driver-model/devres.rst.
  381. of_address_to_resource()
  382. Automatically sets the ``IORESOURCE_MEM_NONPOSTED`` flag for platforms that
  383. require non-posted writes for certain buses (see the nonposted-mmio and
  384. posted-mmio device tree properties).
  385. of_iomap()
  386. Maps the resource described in a ``reg`` property in the device tree, doing
  387. all required translations. Automatically selects ioremap_np() according to
  388. platform requirements, as above.
  389. pci_ioremap_bar(), pci_ioremap_wc_bar()
  390. Maps the resource described in a PCI base address without having to extract
  391. the physical address first.
  392. pci_iomap(), pci_iomap_wc()
  393. Like pci_ioremap_bar()/pci_ioremap_bar(), but also works on I/O space when
  394. used together with ioread32()/iowrite32() and similar accessors
  395. pcim_iomap()
  396. Like pci_iomap(), but uses devres to automatically unmap the resource when
  397. the driver probe() function fails or a device in unbound from its driver
  398. Documented in Documentation/driver-api/driver-model/devres.rst.
  399. Not using these wrappers may make drivers unusable on certain platforms with
  400. stricter rules for mapping I/O memory.
  401. Generalizing Access to System and I/O Memory
  402. ============================================
  403. .. kernel-doc:: include/linux/iosys-map.h
  404. :doc: overview
  405. .. kernel-doc:: include/linux/iosys-map.h
  406. :internal:
  407. Public Functions Provided
  408. =========================
  409. .. kernel-doc:: arch/x86/include/asm/io.h
  410. :internal:
  411. .. kernel-doc:: lib/pci_iomap.c
  412. :export: