Skip to contentSkip to conversation

DMA_PMD: PMD_SIZE-backed IO buffer pools

RFC Superseded Luigi Rizzo 19 participants 162 messages Oct 3 – Nov 27 Page 1 of 2

Subsystems (37)
lore
Share & tools
lore
#0 lore raw

cover DMA_PMD: PMD_SIZE-backed IO buffer pools

Here is a subsystem called DMA_PMD on which I would like feedback on architecture, possible enhancements, or kernel components that could be reused to avoid duplication.

I think it can be extremely useful for those affected by the HW/SW overhead of IOMMU (especially IOTLB thrashing, see [1]), or confidential computing, or preemptable VMs.

The (not too exaggerated) pitch line is

DMA_PMD has the performance of identity, guarantees that only IO buffers can ever have active IOMMU or IOTLB mappings, removes the bounce buffer overhead in confidential computing and preemptable VMs, and integrates smoothly with existing kernel APIs.

=== ARCHITECTURE

DMA_PMD was initially designed to address IOTLB thrashing (details in [1]), but turned out to also resolve nicely the strict IOMMU overhead, and avoid the bounce buffer overhead in preemptible VMs and Confidential Computing.

It works by combining several known techniques:

- transparently feed allocators of device memory (skb_page_frag_refill(), dma_alloc_attrs(), pagepool, ...) with DMA_PMD pages, i.e. physically contiguous PMD_SIZE (2MB) pages mapped via PDE_SIZE IOMMU entries

- heavy recycling of DMA_PMD pages (like pagepool) and lazy IOMMU unmapping (like DMA-FQ), BUT:

- like strict IOMMU (DMA), safely release memory back to the kernel only after destroying all of its IOMMU mappings and a synchronous IOTLB flush

- on allocation, DMA_PMD pages can be configured to be pinned in the host (hence suitable for preemptible VMs) and/or unencrypted (hence suitable for Confidential Computing), removing the need for bounce buffers

- there are global and per-device optin /sys/device/.../dma_pmd_* and /proc/sys/net/core/tx_enable_dma_pmd

NIC drivers can typically use dma_pmd with no modifications for rings, tx buffers, rx buffers (if they use pagepool), and rx headers. For tx headers, almost all drivers need changes (see later patches in the series) to implement cheap bounce buffers and avoid individual 4K mappings.

The series has the following main components:

- a sparse array (similar to pageblock_flags) to quickly attach metadata to a 2MB page without fiddling with the struct page. Cost is 128B per 2MB page used as an IO buffer, totally negligible.

- dma_pmd_pool, a replacement for alloc_pages() that can be instantiated per-CPU or per receive queue. It handles the split of PMD_SIZE pages into order-N blocks, handles dma_map and unmap, and aggressively recycles entries. It is used to feed skb_page_frag_refill(), pagepool, and receive buffers for drivers that do not use pagepool.
See [2] for "WHY NOT PAGEPOOL FOR TX AND EVERYTHING"

- dma_pmd_arena, is another allocator backed by DMA_PMD pages and is used exclusively as the backend for dma_alloc_attrs(). Used for longer-lived allocations (descriptor/completion rings, rx and tx header buffers)

- glue code to hook DMA_PMD into pagepool [2], skb_page_frag_refill(), dma_alloc_attrs(), dma_map/unmap...

- per-driver patches, where necessary (e.g. tx header buffers [3])

=== PERFORMANCE BENEFITS

Your mileage may vary. Enabling the IOMMU may have no throughput impact, until it does when some system components (bus, IOTLB, CPU) become overloaded. Aside from throughput reduction, one interesting parameter is the effectiveness of the IOTLB. Here is a sample of SMMU performance counters for a large ARM system with 2x200G NICs doing bidirectional traffic:

    === DMA-FQ MODE (total throughput ~440Gbps)
    25,757,488      smmuv3_pmcg_*/event=0x80/   IOTLB lookups
    16,634,941      smmuv3_pmcg_*/event=0x81/   IOTLB  misses

    === DMA_PMD on top of strict DMA (total throughput ~745Gbps)
    22,693,218      smmuv3_pmcg_*/event=0x80/   IOTLB lookups
        30,536      smmuv3_pmcg_*/event=0x81/   IOTLB  misses
    (not a mistake, also lookups went down despite the higher rate
    because the tx side can use larger segments)

The 2MB mappings made IOTLB misses almost non existent, because the working set is reduced by a factor of ~512.

Note, the code has more verbose comments than I would like. Several of them are there to avoid Sashiko getting confused and flagging false positives.

=== NOTES

[1] IOMMU IMPACT AND IOTLB THRASHING
This is documented in more detail in Documentation/core-api/dma-pmd.rst but the compact version is below.

There are three main costs involved with using the IOMMU:
- CPU cost for dma map/unmap
- CPU cost and latency for synchronous IOTLB flush (required for strong security)
- IOTLB thrashing, shows up dramatically when the IO access pattern exceeds the IOTLB size, and IOMMU page walks slow down bus activity up to a point where we see over 30..60% throughput reduction just for this reason. Some relevant references

https://lore.kernel.org/all/[email protected]/
https://www.ncbi.nlm.nih.gov/pmc/articles/PMC10280580/

Specifically, NICs access 4 or more pages per packet (descriptor queue, completion queue, rx or tx header, one or more buffers), with very little locality especially for data buffers and tx headers. Each queue has 1-4K entries, a fast NIC uses 16 or more queues per direction, so just the data buffers cover 32..128K pages. Using 4KB mappings makes the IOTLB ineffective, as shown by the performance counters shown earlier.

[2] WHY NOT PAGEPOOL FOR TX AND EVERYTHING
There is some overlap between pagepool and dma_pmd_pool in that both implement a cache, but pagepool is missing some important features:

- pagepool does not handle splitting 2M pages in smaller chunks, or the mappings. That would need to be implemented (and is what dma_pmd_pool does)

- pagepool's provided pages cannot be cleanly managed by get_page()/put_page(), which is what all the consumers of skb_page_frag_refill(). Fixing that would require dozen of changes with high risk of missing some paths.

- even for the receive path, a provider for pagepool has more restrictions than alloc_pages-supplied memory, so if I wanted to wrap dma_pmd_pool as a provider I would have needed changes to the provider interface.

- pagepool requires a device at allocation time, which is not known when skb_page_frag_refill() runs, hence the IOMMU mappings cannot be handled at allocation time.

- page_pool_alloc_pages assumes a single NAPI consumer with BH disabled, whereas skb_page_frag_refill() runs from a preemptive context.

- and last not least, we need to handle the dma_alloc_attrs() allocations which don't match pagepool API

Of course all of the above could be modified, but the complexity would be similar to that of implementing dma_pmd_pool, and with a huge risk of breaking existing functionality or missing some path.

[3] DRIVER CHANGES

Most drivers need no change for rings, transmit buffers, or receive buffers (if they use pagepool). Tx headers are generally mapped on the fly and that is enough to trigger IOTLB thrashing, so most drivers need a small change to implement very cheap tx bounce buffers backed by DMA_PMD pages.

We could avoid the bounce buffers using DMA_PMD for the skb->head region, but that memory is contiguous to skb_shinfo so it would be exposed to IO device access, which may be undesirable for security.

Luigi Rizzo (22):
iommu/dma: introduce CONFIG_DMA_PMD and metadata table iommu/dma: add DMA_PMD pool lifecycle and page recycle hook
mm: Add split_page_compound()
iommu/dma: add DMA_PMD pool block allocation iommu/dma: Global cap and shrinker for DMA_PMD pool memory iommu/dma: reserve a per-domain IOVA window for DMA_PMD pages iommu/dma: release DMA_PMD domain mappings on domain teardown iommu/dma: use per-domain IOVA window to map DMA_PMD memory iommu/dma: Add DMA_PMD arena allocator
driver core: Add per-device dma_pmd_* sysfs attributes
dma-mapping: Use DMA_PMD arena for dma_alloc_attrs() net/core: Use per-CPU DMA_PMD pools for skb_page_frag_refill() net/core: Use DMA_PMD for page_pool memory iommu/dma: Support decrypted and pinned DMA_PMD pages iommu/dma: Add background page scrubber for DMA_PMD pools iommu/dma: Add per-NUMA-node PMD page reservoir net/gve: Use DMA_PMD memory for RX buffers
net/gve: Use DMA_PMD memory for tx header bounce buffers net/mlx5e: Use DMA_PMD memory for tx header bounce buffers net/idpf: Use DMA_PMD memory for tx header bounce buffers net/bnxt: Use DMA_PMD memory for tx header bounce buffers iommu/dma: Add DMA_PMD statistics and debugfs

 Documentation/core-api/dma-pmd.rst            |  320 ++++
 Documentation/core-api/index.rst              |    1 +
 drivers/base/core.c                           |   51 +
 drivers/iommu/Kconfig                         |   33 +
 drivers/iommu/Makefile                        |    3 +
 drivers/iommu/dma-iommu.c                     |   72 +-
 drivers/iommu/dma-iommu.h                     |    8 +
 drivers/iommu/dma-pmd-arena.c                 |  412 +++++
 drivers/iommu/dma-pmd-kunit.c                 |  225 +++
 drivers/iommu/dma-pmd-map.c                   |  531 ++++++
 drivers/iommu/dma-pmd-meta.c                  |  403 +++++
 drivers/iommu/dma-pmd-pool.c                  | 1538 +++++++++++++++++
 drivers/iommu/dma-pmd-priv.h                  |  385 +++++
 drivers/iommu/iommu.c                         |    2 +-
 drivers/net/ethernet/broadcom/bnxt/bnxt.c     |   45 +-
 drivers/net/ethernet/broadcom/bnxt/bnxt.h     |    2 +
 drivers/net/ethernet/google/gve/gve.h         |    5 +
 drivers/net/ethernet/google/gve/gve_main.c    |    5 +
 drivers/net/ethernet/google/gve/gve_rx.c      |   61 +-
 drivers/net/ethernet/google/gve/gve_tx.c      |   38 +-
 drivers/net/ethernet/google/gve/gve_tx_dqo.c  |   45 +-
 .../ethernet/intel/idpf/idpf_singleq_txrx.c   |    6 +-
 drivers/net/ethernet/intel/idpf/idpf_txrx.c   |   21 +-
 drivers/net/ethernet/intel/idpf/idpf_txrx.h   |   27 +-
 drivers/net/ethernet/mellanox/mlx5/core/en.h  |    2 +
 .../net/ethernet/mellanox/mlx5/core/en/txrx.h |    4 +-
 .../net/ethernet/mellanox/mlx5/core/en_main.c |   14 +
 .../net/ethernet/mellanox/mlx5/core/en_tx.c   |   28 +-
 include/linux/device.h                        |    5 +
 include/linux/dma-pmd.h                       |  198 +++
 include/linux/mm.h                            |    2 +
 include/net/libeth/tx.h                       |    5 +-
 include/net/page_pool/types.h                 |    3 +
 include/net/sock.h                            |    3 +
 kernel/dma/direct.c                           |    6 +-
 kernel/dma/mapping.c                          |   39 +-
 mm/Kconfig.debug                              |   11 +
 mm/Makefile                                   |    1 +
 mm/page_alloc.c                               |   89 +
 mm/split_page_compound_kunit.c                |  113 ++
 net/core/page_pool.c                          |   61 +-
 net/core/sock.c                               |   86 +-
 net/core/sysctl_net_core.c                    |    7 +
 43 files changed, 4835 insertions(+), 81 deletions(-)
 create mode 100644 Documentation/core-api/dma-pmd.rst
 create mode 100644 drivers/iommu/dma-pmd-arena.c
 create mode 100644 drivers/iommu/dma-pmd-kunit.c
 create mode 100644 drivers/iommu/dma-pmd-map.c
 create mode 100644 drivers/iommu/dma-pmd-meta.c
 create mode 100644 drivers/iommu/dma-pmd-pool.c
 create mode 100644 drivers/iommu/dma-pmd-priv.h
 create mode 100644 include/linux/dma-pmd.h
 create mode 100644 mm/split_page_compound_kunit.c
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#1 lore raw

RFC 1/22 iommu/dma: introduce CONFIG_DMA_PMD and metadata table

DMA_PMD is a new subsystem to back IO buffers with physically contiguous PMD_SIZE pages, allowing the use of larger leaves in the IOMMU. This significantly reduces IOTLB pressure, with great performance benefits. It support very common cases (2MB PMD, !PREEMPT_RT). The 2MB backing pages are dynamically allocated and released. DMA_PMD overhead is 128B of metadata per physical page (64KB per 1GB, or 0.01% of physical RAM).

Add a CONFIG_DMA_PMD option to enable it only when applicable, and introduce a sparse per-PMD metadata table to store the necessary side information efficiently (similar in principle to pageblock_flags). The table is initialized on first use, reserving KVA across the physical address space up to iomem_resource.end (capped at MAX_PHYSMEM_BITS, 64KB of KVA per 1GB of address space) along with a chunk-populated bitmap (1 bit per 64MB chunk) for fast lockless lookups. Only chunks covering online RAM are backed by physical pages at init; memory hotplugged later within the reserved range is populated on demand when allocated by a DMA_PMD pool, and safely declined otherwise.

Also add a built-in KUnit test suite (CONFIG_DMA_PMD_META_KUNIT_TEST) exercising initialization idempotency, PFN/physical round-trip lookups, out-of-bounds physical address handling, and DMA_PMD membership toggling.

---
 Documentation/core-api/dma-pmd.rst | 320 +++++++++++++++++++++++++
 Documentation/core-api/index.rst   |   1 +
 drivers/iommu/Kconfig              |  32 +++
 drivers/iommu/Makefile             |   2 +
 drivers/iommu/dma-pmd-kunit.c      | 102 ++++++++
 drivers/iommu/dma-pmd-meta.c       | 365 +++++++++++++++++++++++++++++
 drivers/iommu/dma-pmd-priv.h       |  56 +++++
 include/linux/dma-pmd.h            |  36 +++
 8 files changed, 914 insertions(+)
 create mode 100644 Documentation/core-api/dma-pmd.rst
 create mode 100644 drivers/iommu/dma-pmd-kunit.c
 create mode 100644 drivers/iommu/dma-pmd-meta.c
 create mode 100644 drivers/iommu/dma-pmd-priv.h
 create mode 100644 include/linux/dma-pmd.h
Documentation/core-api/dma-pmd.rst new file +320 -0
new file mode 100644
index 0000000000000..1d113b8c15876
@@ -0,0 +1,320 @@
+.. SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
+
+=========================================================
+DMA_PMD: PMD_SIZE IOMMU mappings for DMA-coherent devices
+=========================================================
+
+Overview
+========
+
+DMA_PMD is a transparent enhancement of the current IOMMU modes, that
+gives the performance of identity mode, and like strict IOMMU mode
+(DMA), guarantees that memory will go back to the buddy allocator only
+when all IOMMU mappings have been removed and IOTLB flushed.
+
+The original design aimed at removing IOTLB thrashing, but its mechanism
+also give security guarantees comparable to strict IOMMU, and remove the
+bounce buffer overhead from Confidential Computing and preemptible VMs.
+
+Background and motivations
+==========================
+
+I/O devices typically access at least 3-4 different memory regions on
+each transaction (network packet or disk request):
+
+- command, completion and buffer queues
+- optionally, header or metadata buffers (e.g., NIC packet headers, NVMe SGL...)
+- data buffers (TX socket buffers, NIC RX buffers, disk I/O buffers)
+
+Enabling the IOMMU impacts performance for the following reasons:
+
+- CPU cost to install/remove IOMMU Page Table Entries (PTEs)
+  (``dma_map_*()``, ``dma_unmap_*()``)
+- CPU/system overhead to flush the IOTLB, ie remove stale PTEs that could give
+  access to sensitive data or code when memory is recycled for other purposes.
+- Higher DMA read/write latency from IOMMU page walks when the working set
+  exceeds the IOTLB size, backpressuring the bus via flow control.
+  This is one of the biggest bottleneck for high speed devices:
+  typical network devices have very little IOVA locality, and that makes the IOTLB
+  almost completely ineffective.
+
+There are known methods to mitigate these problems:
+
+1. Recycling I/O buffers and their IOMMU mappings removes most of the DMA map/unmap
+   costs. This is common practice for command, completion and buffer
+   queues, as well as disk I/O and network receive buffers.  Network
+   TX buffers are a noticeable exception. They normally come from
+   ``alloc_pages()`` calls unaware of the leaf device, and require
+   mapping/unmapping on each use.
+
+2. Lazily flushing the IOTLB (as implemented by DMA-FQ) amortizes a
+   very expensive operation (up to several microseconds to wait for
+   completion, necessary for security), but the way it is implemented
+   in DMA-FQ compromises on security: IOTLB flush requests are run
+   periodically in batches, but the underlying memory is recycled without
+   waiting. During that window, the physical memory is still accessible,
+   opening the door to exfiltration or corruption of sensitive data/code.
+
+3. The set of PTEs in active use can be significantly reduced by mapping larger
+   blocks, e.g. 2MB (called PMD) instead of the usual 4KB (PTE). This is not
+   currently pursued by the kernel.
+
+DMA_PMD addresses all the above with a combination of simple, known concepts,
+implemented in a way that integrates smoothly with the kernel and drivers:
+
+- intercept calls to the small set of functions used to allocate, map, unmap, and free
+  device-accessible memory (rings and buffers)
+- return memory backed by physically contiguous 2MB pages (PMD) and 2MB IOMMU
+  mappings
+- heavily recycle memory and mappings
+- wait until the IOTLB has been flushed before returning unused DMA_PMD memory
+  to the system pool
+
+Execution is what makes DMA_PMD practical: the implementation intercepts
+a small set of kernel APIs so that device will inherit the benefits with
+little if any changes, and the design is such that these intercepts have
+minimal impact on the original functions.
+
+Furthermore, since DMA_PMD intercepts allocations of device-accessible
+memory, it gives two important benefits:
+- transparent pinning/unpining, required for preemptible VMs
+- transparent configuration of unencrypted mode, required for confidential computing
+
+Limitations
+===========
+
+DMA_PMD is currently limited to systems with ``PMD_SIZE`` equal to 2MB, which
+is the vast majority of existing platforms. It could be extended to larger
+pages without much effort. This is enforced at compile time.
+
+The implementation assumes non-preemptible spinlocks, so DMA_PMD is not
+compatible with ``PREEMPT_RT``. This is enforced at compile time.
+
+DMA_PMD can only be used by DMA-coherent devices. This is enforced at runtime.
+
+IOMMU mappings for data buffers are always ``DMA_BIDIRECTIONAL``. This
+simplifies the handling of e.g. forwarding between different network
+interfaces.
+
+IOMMU mappings for queues are also ``DMA_BIDIRECTIONAL``, though stricter modes
+can be implemented trivially.
+
+Implementation details
+======================
+
+Most of the code size and design complexity relates to the handling
+of exceptional events (device teardown, memory hotplug) and to
+the safe release of pages through deferred tasks, RCU and grace
+periods.
+
+The implementation lives in ``drivers/iommu/dma-pmd-*.c`` and
+``include/linux/dma-pmd.h``, and relies on the components described below.
+We use the name "DMA_PMD" to refer to the second-level physically contiguous
+pages (typically 2MB) used for I/O memory.
+
+The set of functions that need to be intercepted is relatively small:
+
+- ``page_pool_dev_alloc*()``, ``skb_page_frag_refill()``, ``__free_pages()``
+- ``dma_alloc_attrs()``, ``dma_map_*()``, ``dma_unmap_*()``
+
+and most devices will automatically inherit the benefits.
+
+Requirements (for performance and functionality)
+================================================
+
+- efficient identification of DMA_PMD pages, based on either their Physical
+  Address (PA) or their I/O Virtual Address (IOVA)
+- fast access to DMA_PMD page metadata
+- fast allocation under highly concurrent usage
+- efficient DMA map/unmap
+- comprehensive lifetime management
+- support for confidential computing (decrypted DMA buffers)
+- support for preemptible VMs (pinned DMA buffers)
+
+Internal mechanisms
+===================
+
+We use the following components:
+
+- **DMA_PMD metadata** (``struct dma_pmd_meta``):
+
+  Identification of DMA_PMD pages could be done in principle with a flag in
+  ``struct page``, but that would not solve the management of per-page
+  metadata.
+
+  DMA_PMD addresses both requirements without depending on ``struct page``
+  using an idea similar to ``pageblock_flags``. Each 2MB page used as a
+  buffer requires only 256B of metadata, or 0.01% overhead. For metadata,
+  we reserve a sparse virtual memory region covering of approximate
+  size ``max_pfn * 256 / PMD_SIZE``, so the metadata can be accessed
+  directly using the 2MB page index.  Metadata pages are populated on
+  demand, with a compact bitmap (1 bit per 32MB chunk, or 4KB per 1TB
+  of address space) tracking which metadata pages are backed, allowing
+  fast lockless validation and direct array indexing. Memory hotplugged
+  later is also supported.
+
+  ``struct dma_pmd_meta`` has flags to mark the page status (used as
+  DMA_PMD buffer, decrypted for confidential computing, or pinned against
+  memory compaction), and tracks which subpages are free, which domains
+  have an active IOMMU mapping for the page, and holds list/RCU linkage
+  to manage its lifetime.
+
+- **Per-domain reserved DMA_PMD IOVA ranges**:
+
+  Another key requirement is to quickly resolve the PA-IOVA mapping for a given domain. Since
+  a DMA_PMD page can be mapped in multiple domains (e.g. a network buffer used
+  to route packets between different NICs), it would be too expensive to manage random
+  PA-IOVA mappings created on the fly.
+  DMA_PMD reserves on each domain an IOVA range
+  covering the physical memory range plus an extra region, allowing a
+  fixed PA-IOVA offset, possibly different for each domain.
+  The IOVA allocation happens the first time a domain is used, hence a
+  IOVA within the reserved range will uniquely identify a DMA_PMD page.
+
+- **alloc_pages() compatible dma_pmd_pool allocator for I/O buffers**:
+
+  DMA_PMD implements a dma_pmd_pool object for fixed-order page allocations
+  that is a natural fit for the allocation of NIC receive buffers and tx
+  socket buffers. The API is similar to ``alloc_pages()`` (in fact, it is an
+  almost direct replacement) and dma_pmd_pools are instantiated as follow:
+  - per NIC-receive-queue (or page_pool) to provide order-0 pages to each queue
+  - per-CPU to provide order-0 and order-3 pages to refill tx socket buffers.
+
+- **dma_pmd_arena allocator to back dma_alloc_attrs()**
+
+  Devices use ``dma_alloc_attrs()`` or variants for long-lived, variable size
+  allocations to back device queues and header buffers. dma_pmd_arena
+  has the same functions: it both allocates and maps memory in the
+  reserved IOVA, and is used exclusively within dma_alloc_attrs() to
+  handle suitable requests (4K or larger, GFP_KERNEL, for devices that
+  specifically enable DMA_PMD)
+
+
+- **Fine grained control**
+
+  Both for experimentation and production use, it is useful to have
+  some form of control on which devices want to use DMA_PMD and for
+  what. DMA_PMD exposes the following controls. Keep in mind that full
+  performance can only be achieved if all regions are mapped using DMA_PMD.
+
+  - /sys/devices/*/*/dma_pmd_{rings,rxbuf,tx_hdrs} per-device entries
+    that can be used within device drivers to decide whether to use DMA_PMD for each of its regions
+
+  - /proc/sys/net/core/tx_enable_dma_pmd controls whether tx socket buffers should use DMA_PMD
+
+- **Safe release of memory to the system**
+
+  A key feature of DMA_PMD is that memory is not released to the system
+  while there are active IOMMU mappings. Release of buffers is managed
+  as follows
+
+  1. on ``__free_pages()`` or ``dma_free_attrs()``, blocks are returned to DMA_PMD,
+     IOMMU mappings are still active, and they can be recycled
+
+  2. when all blocks in a DMA_PMD page are unused, the page is moved to an
+     "idle" list, still with active mappings and available for reuse
+
+  3. upon memory pressure or when above some global threshold, a shrinker
+     thread collects idle pages from all pools and starts removing the iommu
+     mappings and issues a synchronous IOTLB flush. The pages are not usable for allocations
+     but not returned to the pool yet
+
+  4. once the previous step is complete, the system schedules ``call_rcu()``
+     and waits for an RCU grace period (and re-encrypts the page if it was
+     decrypted) before returning the 2MB page to the buddy allocator.
+
+- **Handling domain destruction**
+
+  When a device/domain is destroyed, all I/O issued by the device must have
+  been quiesced and memory released via ``__free_pages()`` or ``dma_free*()``.
+  DMA_PMD hooks into the domain destructor and removes all existing mappings
+  for the disappearing domain and synchronously flushes the IOTLB, similarly
+  to steps #3 and #4 shown before.
+
+- **Allocation and compound splitting**:
+
+  A pool that needs memory calls ``dma_pmd_add_page()`` to allocate a
+  physically contiguous 2MB page on the calling CPU's NUMA node, and
+  ``split_page_compound()`` to split it into independent blocks of
+  ``pool->order``. These blocks can be independently passed through the
+  networking stack.
+
+Modified kernel APIs and runtime controls
+=========================================
+
+DMA_PMD integrates transparently into existing kernel memory, DMA, and
+networking APIs. Allocation of DMA_PMD memory is opt-in via per-device sysfs
+attributes or sysctls, while mapping, unmapping, and freeing automatically
+detect whether a buffer or IOVA belongs to DMA_PMD:
+
+1. **Streaming DMA map and unmap** (``dma_map_page_attrs()``,
+   ``dma_map_single_attrs()``, ``dma_map_sg_attrs()`` and
+   ``dma_unmap_page_attrs()``, ``dma_unmap_single_attrs()``,
+   ``dma_unmap_sg_attrs()`` via ``drivers/iommu/dma-iommu.c`` and
+   ``kernel/dma/direct.c``):
+
+   - On map, any buffer belonging to a DMA_PMD page (``dma_is_pmd_phys(phys)``)
+     is mapped via the domain's reserved ``DMA_PMD`` IOVA window with a simple
+     addition, typically reusing existing mappings.
+     Under ``dma-direct``, decrypted or pinned ``DMA_PMD`` pages
+     (``dma_is_pmd_direct(phys)``) can be mapped directly without ``swiotlb`` bounce.
+
+     On unmap, IOVAs can be identified as DMA_PMD buffers with a simple range check
+     and that results in a no-operation.
+
+2. **Coherent DMA allocation and free** (``dma_alloc_attrs()`` /
+   ``dma_alloc_coherent()`` and ``dma_free_attrs()`` / ``dma_free_coherent()``
+   in ``kernel/dma/mapping.c``):
+
+   - DMA_PMD is enabled per device via ``/sys/devices/.../dma_pmd_rings``
+     (``dev->dma_pmd_rings``). When set, sleepable ``GFP_KERNEL`` coherent
+     allocations are rounded up to 4KB and carved out of DMA_PMD buffers
+     ``dma_pmd_arena`` and mapped accordingly.
+     ``dma_free_attrs()`` automatically detects arena IOVAs via
+     ``dma_pmd_free()`` and returns the sub-blocks to the arena.
+
+3. **Page allocator release** (``__free_pages()`` / ``put_page()`` via
+   ``__free_pages_prepare()`` in ``mm/page_alloc.c``):
+
+   - ``dma_pmd_free_page()`` checks
+     ``dma_is_pmd_page(page_to_pfn(page))`` and recycles DMA_PMD subpages back to
+     their owning ``dma_pmd_pool`` instead of releasing them to the buddy
+     allocator while their 2MB IOMMU mappings remain active.
+
+4. **IOMMU domain teardown** (``iommu_put_dma_cookie()`` in
+   ``drivers/iommu/dma-iommu.c``):
+
+   - A call to ``dma_pmd_domain_release()`` before freeing a
+     domain's IOVA cookie and page tables clears cached domain state across
+     all pools. Existing IOMMU mappings and IOTLB flush has already happened.
+
+5. **Networking ``page_pool``**
+
+   - DMA_PMD is enabled per device via ``/sys/devices/.../dma_pmd_rxbuf``
+     (``dev->dma_pmd_rxbuf``). Any NIC driver using ``page_pool`` with this
+     flag set will back its RX buffers with a per-``page_pool``
+     ``dma_pmd_pool``, and opportunistically replaces plain 4KB pages when pooled 2MB
+     blocks are available.
+
+6. **Socket TX page fragments** (``skb_page_frag_refill()`` in
+   ``net/core/sock.c``):
+
+   - When enabled globally via the ``net.core.tx_enable_dma_pmd`` sysctl
+     socket TX fragments are allocated from per-CPU ``dma_pmd_pool`` instances.
+
+7. **NIC driver RX pools and TX header bounce buffers**
+
+   - **RX buffers:** Controlled per device by ``/sys/devices/.../dma_pmd_rxbuf``
+     (``dev->dma_pmd_rxbuf``) for queue modes managing their own page rings
+     (``idpf``, ``gve`` GQI-RDA, ``gq``).
+   - **TX headers:** Controlled per device by
+     ``/sys/devices/.../dma_pmd_tx_hdrs`` (``dev->dma_pmd_tx_hdrs``),
+     copying linear packet headers into pre-allocated coherent bounce buffers
+     (backed by ``dma_pmd_arena`` when ``dma_pmd_rings`` is also enabled).
+
+8. **Global pool limit and observability:**
+
+   - ``/sys/module/kernel/parameters/dma_pmd_max_pages``: Global cap on 2MB
+     pages held across all pools (defaults to 1/8th of physical RAM).
+   - ``/sys/kernel/debug/dma_pmd/pools``: Debugfs summary of global and per-pool
+     allocation, mapping, and fallback counters.
Documentation/core-api/index.rst +1 -0
index 92f91c6a0d79d..49608d2b7509b 100644
@@ -113,6 +113,7 @@ more memory-management documentation in Documentation/mm/index.rst.
    dma-attributes
    dma-isa-lpc
    swiotlb
+   dma-pmd
    mm-api
    cgroup
    genalloc
drivers/iommu/Kconfig +32 -0
index 6e07bd69467a3..1bb347fd9da4a 100644
@@ -158,6 +158,38 @@ config IOMMU_DMA
 	select NEED_SG_DMA_LENGTH
 	select NEED_SG_DMA_FLAGS if SWIOTLB
 
+# PMD_SIZE IOMMU backing for DMA-coherent devices
+config DMA_PMD
+	bool "PMD_SIZE IOMMU backing for DMA-coherent devices"
+	depends on IOMMU_DMA
+	depends on X86_64 || (ARM64 && ARM64_4K_PAGES)
+	depends on !PREEMPT_RT
+	default y
+	help
+	  Hand out DMA buffers carved out of PMD_SIZE physically contiguous
+	  blocks that the IOMMU maps with a single leaf PTE. Mapping,
+	  unmapping and IOTLB flushing are done lazily to reduce CPU overhead.
+	  The large mappings greatly reduce IOTLB usage. As in strict iommu
+	  mode, pages are returned to the buddy allocator only when any existing
+	  mappings have been removed and IOTLB flushed.
+	  Costs 128KB of metadata per GB of DMA_PMD buffers, allocated on demand.
+
+	  The config option enforces requirements (2MB PMD and !PREEMPT_RT) at compile
+	  time. Other constraints (e.g. dma-coherent devices) are verified at runtime.
+
+	  If unsure, say Y.
+
+config DMA_PMD_META_KUNIT_TEST
+	bool "KUnit test for DMA_PMD metadata table (built-in)" if !KUNIT_ALL_TESTS
+	depends on DMA_PMD && KUNIT=y
+	default KUNIT_ALL_TESTS
+	help
+	  Builds KUnit unit tests for the sparse, per-PMD-frame metadata table,
+	  PMD page pools, and coherent DMA arenas in drivers/iommu/dma-pmd*.c,
+	  verifying metadata lookup, pool recycling, and arena block allocation.
+
+	  If unsure, say N.
+
 # Shared Virtual Addressing
 config IOMMU_SVA
 	select IOMMU_MM_DATA
drivers/iommu/Makefile +2 -0
index 2f05725eaab18..2ad9b2eefd741 100644
@@ -11,6 +11,8 @@ obj-$(CONFIG_IOMMU_API) += iommu-traces.o
 obj-$(CONFIG_IOMMU_API) += iommu-sysfs.o
 obj-$(CONFIG_IOMMU_DEBUGFS) += iommu-debugfs.o
 obj-$(CONFIG_IOMMU_DMA) += dma-iommu.o
+obj-$(CONFIG_DMA_PMD) += dma-pmd-meta.o
+obj-$(CONFIG_DMA_PMD_META_KUNIT_TEST) += dma-pmd-kunit.o
 obj-$(CONFIG_IOMMU_IO_PGTABLE) += io-pgtable.o
 obj-$(CONFIG_IOMMU_IO_PGTABLE_ARMV7S) += io-pgtable-arm-v7s.o
 obj-$(CONFIG_IOMMU_IO_PGTABLE_LPAE) += io-pgtable-arm.o
drivers/iommu/dma-pmd-kunit.c new file +102 -0

102 lines not on this page · raw message

drivers/iommu/dma-pmd-meta.c new file +365 -0

365 lines not on this page · raw message

drivers/iommu/dma-pmd-priv.h new file +56 -0

56 lines not on this page · raw message

include/linux/dma-pmd.h new file +36 -0
new file mode 100644
index 0000000000000..07df815945257
@@ -0,0 +1,36 @@
+/* SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause */
+/* See Documentation/core-api/dma-pmd.rst for the architecture overview. */
+#ifndef _LINUX_DMA_PMD_H
+#define _LINUX_DMA_PMD_H
+
+#include <linux/compiler.h>
+#include <linux/mm_types.h>
+#include <linux/types.h>
+
+#ifdef CONFIG_DMA_PMD
+
+extern void *dma_pmd_meta_array;
+
+bool __dma_is_pmd_page(unsigned long pfn);
+
+static inline bool dma_is_pmd_page(unsigned long pfn)
+{
+	/*
+	 * Acquire pairs with smp_store_release() in dma_pmd_meta_init():
+	 * orders both @dma_pmd_meta_nframes and the populated backing pages.
+	 */
+	if (likely(!smp_load_acquire(&dma_pmd_meta_array)))
+		return false;
+
+	return __dma_is_pmd_page(pfn);
+}
+
+#else /* !CONFIG_DMA_PMD */
+
+static inline bool dma_is_pmd_page(unsigned long pfn)
+{
+	return false;
+}
+
+#endif /* CONFIG_DMA_PMD */
+#endif /* _LINUX_DMA_PMD_H */
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
reviewer
#2 lore raw

Re: [RFC: DMA_PMD 01/22] iommu/dma: introduce CONFIG_DMA_PMD and metadata table

Quoted 13 lines · Luigi Rizzo
drivers/iommu/Kconfig +5 -0
index 6e07bd69467a3..1bb347fd9da4a 100644
@@ -158,6 +158,38 @@ config IOMMU_DMA
 	select NEED_SG_DMA_LENGTH
 	select NEED_SG_DMA_FLAGS if SWIOTLB
 
+# PMD_SIZE IOMMU backing for DMA-coherent devices
+config DMA_PMD
+	bool "PMD_SIZE IOMMU backing for DMA-coherent devices"
+	depends on IOMMU_DMA
+	depends on X86_64 || (ARM64 && ARM64_4K_PAGES)

drivers/iommu/Kconfig config IOMMU_DMA · line 175

Quoted 10 lines
drivers/iommu/Kconfig +10 -0
+	depends on !PREEMPT_RT
+	default y
+	help
+	  Hand out DMA buffers carved out of PMD_SIZE physically contiguous
+	  blocks that the IOMMU maps with a single leaf PTE. Mapping,
+	  unmapping and IOTLB flushing are done lazily to reduce CPU overhead.
+	  The large mappings greatly reduce IOTLB usage. As in strict iommu
+	  mode, pages are returned to the buddy allocator only when any existing
+	  mappings have been removed and IOTLB flushed.
+	  Costs 128KB of metadata per GB of DMA_PMD buffers, allocated on demand.

Paragraph 1 of the patch description says 64KB per 1GB, not 128KB. Or am I mixing things up?

Signature · 1 line
~Randy
#3 lore raw

Re: [RFC: DMA_PMD 01/22] iommu/dma: introduce CONFIG_DMA_PMD and metadata table

Quoted 14 lines · Randy Dunlap
Quoted 10 lines · Luigi Rizzo
drivers/iommu/Kconfig +2 -0
index 6e07bd69467a3..1bb347fd9da4a 100644
@@ -158,6 +158,38 @@ config IOMMU_DMA
      select NEED_SG_DMA_LENGTH
      select NEED_SG_DMA_FLAGS if SWIOTLB
 
+# PMD_SIZE IOMMU backing for DMA-coherent devices
+config DMA_PMD

...

Quoted 4 lines
Quoted 1 line

+ Costs 128KB of metadata per GB of DMA_PMD buffers, allocated on demand.

Paragraph 1 of the patch description says 64KB per 1GB, not 128KB. Or am I mixing things up?

256B per 2MB page, 128KB per 1GB is the correct version. The number in the patch description is a leftover from an earlier version, I will update.

cheers
luigi

#4 lore raw

RFC 2/22 iommu/dma: add DMA_PMD pool lifecycle and page recycle hook

In reply to Luigi Rizzo

DMA_PMD manages pools of PMD_SIZE physically contiguous memory from which IO buffers can be allocated. Recycling memory to the pool amortizes the cost of mapping, unmapping and IOTLB flush, but must be handled so that memory with active IOMMU mappings cannot be used for other data or code.

Add the pool lifecycle (struct dma_pmd_pool, dma_pmd_pool_create(), dma_pmd_pool_destroy()) and the page release side. In particular, __dma_pmd_free_page() is hooked into __free_pages_prepare() so that DMA_PMD pages are returned to the pool.

Also implement asynchronous DMA_PMD page retirement and release to the buddy allocator via a WQ_MEM_RECLAIM worker. Retirement removes DMA_PMD pages from pools and destroys the mappings flushing the IOTLB, but defers the buddy release by an RCU grace period, so a reader that already passed dma_is_pmd_page() can safely finish reading p2m.

---
 drivers/iommu/Makefile       |   2 +-
 drivers/iommu/dma-pmd-meta.c |   4 +-
 drivers/iommu/dma-pmd-pool.c | 379 +++++++++++++++++++++++++++++++++++
 drivers/iommu/dma-pmd-priv.h | 129 +++++++++++-
 include/linux/dma-pmd.h      |  73 ++++++-
 mm/page_alloc.c              |   4 +
 6 files changed, 579 insertions(+), 12 deletions(-)
 create mode 100644 drivers/iommu/dma-pmd-pool.c
drivers/iommu/Makefile +1 -1
index 2ad9b2eefd741..de2c3bad9aa3e 100644
@@ -11,7 +11,7 @@ obj-$(CONFIG_IOMMU_API) += iommu-traces.o
 obj-$(CONFIG_IOMMU_API) += iommu-sysfs.o
 obj-$(CONFIG_IOMMU_DEBUGFS) += iommu-debugfs.o
 obj-$(CONFIG_IOMMU_DMA) += dma-iommu.o
-obj-$(CONFIG_DMA_PMD) += dma-pmd-meta.o
+obj-$(CONFIG_DMA_PMD) += dma-pmd-meta.o dma-pmd-pool.o
 obj-$(CONFIG_DMA_PMD_META_KUNIT_TEST) += dma-pmd-kunit.o
 obj-$(CONFIG_IOMMU_IO_PGTABLE) += io-pgtable.o
 obj-$(CONFIG_IOMMU_IO_PGTABLE_ARMV7S) += io-pgtable-arm-v7s.o
drivers/iommu/dma-pmd-meta.c +3 -1
index fcaf5b121e66a..27b8c2568c749 100644
@@ -43,7 +43,9 @@ EXPORT_SYMBOL(dma_pmd_meta_array);
 unsigned long dma_pmd_meta_nframes __read_mostly;
 static unsigned long *dma_pmd_chunk_bitmap __read_mostly;
 
-static struct dma_pmd_meta dma_pmd_meta_nil;
+static struct dma_pmd_meta dma_pmd_meta_nil = {
+	.map_lock = __SPIN_LOCK_UNLOCKED(dma_pmd_meta_nil.map_lock),
+};
 
 static unsigned long dma_pmd_meta_pages;
 static DEFINE_MUTEX(dma_pmd_meta_mutex);
drivers/iommu/dma-pmd-pool.c new file +379 -0

379 lines not on this page · raw message

drivers/iommu/dma-pmd-priv.h +121 -8

158 lines not on this page · raw message

include/linux/dma-pmd.h +71 -2

91 lines not on this page · raw message

mm/page_alloc.c +4 -0
index 12fac9084c483..e8e9905cdea5b 100644
@@ -17,6 +17,7 @@
 #include <linux/stddef.h>
 #include <linux/mm.h>
 #include <linux/highmem.h>
+#include <linux/dma-pmd.h>
 #include <linux/interrupt.h>
 #include <linux/jiffies.h>
 #include <linux/compiler.h>
@@ -1327,6 +1328,9 @@ static __always_inline bool __free_pages_prepare(struct page *page,
 
 	VM_BUG_ON_PAGE(PageTail(page), page);
 
+	if (unlikely(dma_pmd_free_page(page)))
+		return false;
+
 	trace_mm_page_free(page, order);
 	kmsan_free_page(page, order);
 
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#5 lore raw

Re: [RFC: DMA_PMD 02/22] iommu/dma: add DMA_PMD pool lifecycle and page recycle hook

kernel test robot noticed "WARNING:at_kernel/workqueue.c:#alloc_workqueue_va" on:

Hello,

kernel test robot noticed "WARNING:at_kernel/workqueue.c:#alloc_workqueue_va" on:

commit: 3311715530328ddf9249e312fa817c89b767fde9 ("[RFC: DMA_PMD 02/22] iommu/dma: add DMA_PMD pool lifecycle and page recycle hook")
url: https://github.com/intel-lab-lkp/linux/commits/Luigi-Rizzo/iommu-dma-introduce-CONFIG_DMA_PMD-and-metadata-table/20261003-212220
base: https://git.kernel.org/cgit/linux/kernel/git/akpm/mm.git mm-everything patch link: https://lore.kernel.org/all/[email protected]/
patch subject: [RFC: DMA_PMD 02/22] iommu/dma: add DMA_PMD pool lifecycle and page recycle hook

in testcase: boot

config: x86_64-rhel-9.4-rust
compiler: clang-22
test machine: qemu-system-x86_64 -enable-kvm -cpu SandyBridge -smp 4 -m 16G

(please refer to attached dmesg/kmsg for entire log/backtrace)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags | Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-lkp/[email protected]

[    0.966875][    T1] ------------[ cut here ]------------
[    0.972831][    T1] workqueue: dma_pmd is using neither WQ_PERCPU or WQ_UNBOUND. Setting WQ_PERCPU.
[    0.978823][    T1] WARNING: kernel/workqueue.c:5939 at alloc_workqueue_va+0x75a/0x7c0, CPU#3: swapper/0/1
[    0.983827][    T1] Modules linked in:
[    0.985221][    T1] CPU: 3 UID: 0 PID: 1 Comm: swapper/0 Not tainted 7.3.0-rc5+ #1 PREEMPT(lazy)
[    0.988734][    T1] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.16.3-debian-1.16.3-2 04/01/2014
[    0.991819][    T1] RIP: 0010:alloc_workqueue_va (workqueue.c:5938)
[    0.993522][    T1] Code: 00 08 00 00 e8 40 08 f0 ff e9 cb f9 ff ff 0f 0b e9 cd fe ff ff 0f 0b e9 c6 fe ff ff 48 8d 3d 66 07 18 02 49 8d b6 b8 00 00 00 <67> 48 0f b9 3a 41 81 cc 00 01 00 00 e9 75 f9 ff ff 48 8d 3d 57 07
All code
========
   0:	00 08                	add    %cl,(%rax)
   2:	00 00                	add    %al,(%rax)
   4:	e8 40 08 f0 ff       	call   0xfffffffffff00849
   9:	e9 cb f9 ff ff       	jmp    0xfffffffffffff9d9
   e:	0f 0b                	ud2
  10:	e9 cd fe ff ff       	jmp    0xfffffffffffffee2
  15:	0f 0b                	ud2
  17:	e9 c6 fe ff ff       	jmp    0xfffffffffffffee2
  1c:	48 8d 3d 66 07 18 02 	lea    0x2180766(%rip),%rdi        # 0x2180789
  23:	49 8d b6 b8 00 00 00 	lea    0xb8(%r14),%rsi
  2a:*	67 48 0f b9 3a       	ud1    (%edx),%rdi		<-- trapping instruction
  2f:	41 81 cc 00 01 00 00 	or     $0x100,%r12d
  36:	e9 75 f9 ff ff       	jmp    0xfffffffffffff9b0
  3b:	48                   	rex.W
  3c:	8d                   	.byte 0x8d
  3d:	3d                   	.byte 0x3d
  3e:	57                   	push   %rdi
  3f:	07                   	(bad)

Code starting with the faulting instruction ===========================================

   0:	67 48 0f b9 3a       	ud1    (%edx),%rdi
   5:	41 81 cc 00 01 00 00 	or     $0x100,%r12d
   c:	e9 75 f9 ff ff       	jmp    0xfffffffffffff986
  11:	48                   	rex.W
  12:	8d                   	.byte 0x8d
  13:	3d                   	.byte 0x3d
  14:	57                   	push   %rdi
  15:	07                   	(bad)
[    0.999820][    T1] RSP: 0000:ffffcb9d00013a90 EFLAGS: 00010246
[    1.001542][    T1] RAX: 0000000000000000 RBX: ffff8b7380b46400 RCX: 33ebeeb162fc7d00
[    1.004550][    T1] RDX: 0000000000000007 RSI: ffff8b7380b464b8 RDI: ffffffff8e484980
[    1.006818][    T1] RBP: 0000000000000000 R08: 00000000646d705f R09: 000000000000000f
[    1.008790][    T1] R10: ffff8b7381cec680 R11: ffffffff8ea6ca80 R12: 0000000000000008
[    1.011630][    T1] R13: ffffffff8da42c29 R14: ffff8b7380b46400 R15: ffffcb9d00013b10
[    1.013818][    T1] FS:  0000000000000000(0000) GS:ffff8b7721089000(0000) knlGS:0000000000000000
[    1.016639][    T1] CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
[    1.018818][    T1] CR2: 0000000000000000 CR3: 00000003e4e20000 CR4: 00000000000406f0
[    1.021819][    T1] Call Trace:
[    1.022829][    T1]  <TASK>
[    1.023829][    T1]  ? iommu_dma_forcedac_setup (dma-iommu.c:?)
[    1.025515][    T1]  alloc_workqueue_noprof (workqueue.c:6049)
[    1.026818][    T1]  ? blake2s_update (crypto/blake2s.c:131)
[    1.028234][    T1]  ? intel_cleanup_irq_remapping (irq_remapping.c:?)
[    1.029818][    T1]  dma_pmd_init (iommu/dma-pmd-pool.c:373)
[    1.031195][    T1]  do_one_initcall (main.c:1358)
[    1.032833][    T1]  ? get_random_u32 (char/random.c:396 char/random.c:541)
[    1.033826][    T1]  ? __get_random_u32_below (char/random.c:555)
[    1.036270][    T1]  ? alloc_from_new_slab (linux/spinlock.h:425 slub.c:4519)
[    1.037829][    T1]  ? refill_objects (slub.c:7424)
[    1.038818][    T1]  ? irqentry_exit (linux/irq-entry-common.h:539)
[    1.040264][    T1]  ? asm_sysvec_apic_timer_interrupt (x86/include/asm/idtentry.h:674)
[    1.045448][    T1]  ? parameq (params.c:91 params.c:99)
[    1.046722][    T1]  ? parameq (linux/fortify-string.h:218 params.c:99)
[    1.051786][    T1]  ? do_initcall_level (linux/srcutree.h:?)
[    1.054571][    T1]  ? parse_args (params.c:153)
[    1.056827][    T1]  do_initcall_level (main.c:1420)
[    1.058834][    T1]  do_initcalls (main.c:1436)
[    1.060827][    T1]  kernel_init_freeable (main.c:1671)
[    1.063560][    T1]  ? rest_init (main.c:?)
[    1.065827][    T1]  kernel_init (main.c:1561)
[    1.067786][    T1]  ret_from_fork (x86/kernel/process.c:158)
[    1.069828][    T1]  ? rest_init (main.c:?)
[    1.072821][    T1]  ret_from_fork_asm (x86/entry/entry_64.S:245)
[    1.074826][    T1]  </TASK>
[    1.076251][    T1] ---[ end trace 0000000000000000 ]---

The kernel config and materials to reproduce are available at:
https://download.01.org/0day-ci/archive/20261010/[email protected]

--
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki

#6 lore raw

RFC 3/22 mm: Add split_page_compound()

In reply to Luigi Rizzo

Add split_page_compound(), which splits an order-@old_order page into independently refcounted order-@new_order compound pages (or order-0 pages when @new_order == 0). This is the high-order counterpart of split_page(), used by DMA_PMD pools to carve PMD pages into smaller compound blocks.

All resulting pieces are returned frozen (refcount 0) so the caller can park them in a pool and publish each piece with page_ref_unfreeze(piece, 1) when handed out.

Also add a KUnit test suite (CONFIG_SPLIT_PAGE_COMPOUND_KUNIT_TEST) in mm/split_page_compound_kunit.c.

---
 include/linux/mm.h             |   2 +
 mm/Kconfig.debug               |  11 ++++
 mm/Makefile                    |   1 +
 mm/page_alloc.c                |  85 +++++++++++++++++++++++++
 mm/split_page_compound_kunit.c | 113 +++++++++++++++++++++++++++++++++
 5 files changed, 212 insertions(+)
 create mode 100644 mm/split_page_compound_kunit.c
include/linux/mm.h +2 -0
index dd09c438fa23e..799a42005627f 100644
@@ -1985,6 +1985,8 @@ static inline struct folio *virt_to_folio(const void *x)
 void __folio_put(struct folio *folio);
 
 void split_page(struct page *page, unsigned int order);
+int split_page_compound(struct page *page, unsigned int old_order,
+			unsigned int new_order);
 void folio_copy(struct folio *dst, struct folio *src);
 int folio_mc_copy(struct folio *dst, struct folio *src);
 
mm/Kconfig.debug +11 -0
index 15dca19dd07da..e1a04671c3b0d 100644
@@ -347,3 +347,14 @@ config MEM_ALLOC_PROFILING_DEBUG
 	help
 	  Adds warnings with helpful error messages for memory allocation
 	  profiling.
+
+config SPLIT_PAGE_COMPOUND_KUNIT_TEST
+	bool "KUnit test for split_page_compound() (built-in)" if !KUNIT_ALL_TESTS
+	depends on KUNIT=y
+	default KUNIT_ALL_TESTS
+	help
+	  Builds KUnit unit tests for split_page_compound() in mm/page_alloc.c,
+	  verifying compound splitting, sub-block freezing, and speculative
+	  reference handling.
+
+	  If unsure, say N.
mm/Makefile +1 -0
index e7245cb88c665..448c0f5f783f3 100644
@@ -148,3 +148,4 @@ obj-$(CONFIG_EXECMEM) += execmem.o
 obj-$(CONFIG_TMPFS_QUOTA) += shmem_quota.o
 obj-$(CONFIG_LAZY_MMU_MODE_KUNIT_TEST) += tests/lazy_mmu_mode_kunit.o
 obj-$(CONFIG_MEM_ALLOC_PROFILING) += alloc_tag.o
+obj-$(CONFIG_SPLIT_PAGE_COMPOUND_KUNIT_TEST) += split_page_compound_kunit.o
mm/page_alloc.c +85 -0

91 lines not on this page · raw message

mm/split_page_compound_kunit.c new file +113 -0

113 lines not on this page · raw message

Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#7 lore raw

RFC 4/22 iommu/dma: add DMA_PMD pool block allocation

In reply to Luigi Rizzo

Add dma_pmd_add_page(), dma_pmd_pool_alloc_bulk_node() (with single-page inline wrappers dma_pmd_pool_alloc_node() and dma_pmd_pool_alloc()), and dma_pmd_pool_has_free() to carve PMD_SIZE physical blocks into subpages of a pool's order with split_page_compound() and hand them out to callers.

A parked subpage is kept frozen (refcount 0) and published with page_ref_unfreeze() when it is handed out, mirroring the way the page allocator shapes a page before publishing it, so a stray put_page() on a parked subpage trips a refcount check instead of freeing it twice. GFP flags asking for a placement a pool cannot choose - __GFP_THISNODE, __GFP_DMA, __GFP_DMA32 - are ignored, as documented at dma_pmd_pool_alloc_bulk_node(); __GFP_ZERO is honoured by zeroing at dispense.

Also add a KUnit test case (test_pool_alloc_and_recycle) exercising pool allocation, recycling via __free_page(), and deferred teardown with in-flight blocks.

---
 drivers/iommu/dma-pmd-kunit.c |  41 ++++-
 drivers/iommu/dma-pmd-pool.c  | 279 ++++++++++++++++++++++++++++++++++
 include/linux/dma-pmd.h       |  40 +++++
 3 files changed, 359 insertions(+), 1 deletion(-)
drivers/iommu/dma-pmd-kunit.c +40 -1
index f80527eaf2e84..24978a5123f54 100644
@@ -70,6 +70,7 @@ static void test_meta_pooled_toggle(struct kunit *test)
 	base_pfn = ALIGN_DOWN(pfn, 1UL << PMD_ORDER);
 	/* The buddy allocator returns naturally aligned blocks. */
 	KUNIT_EXPECT_EQ(test, pfn, base_pfn);
+	KUNIT_ASSERT_TRUE(test, dma_pmd_meta_ensure_pfn(pfn, true));
 	m = dma_pmd_meta_of_pfn(pfn);
 
 	KUNIT_EXPECT_FALSE(test, dma_is_pmd_page(pfn));
@@ -85,10 +86,48 @@ static void test_meta_pooled_toggle(struct kunit *test)
 	__free_pages(page, PMD_ORDER);
 }
 
+static void test_pool_alloc_and_recycle(struct kunit *test)
+{
+	struct dma_pmd_pool *pool;
+	struct page *p1, *p2;
+	unsigned int order;
+
+	KUNIT_EXPECT_NULL(test, dma_pmd_pool_destroy(NULL));
+
+	for (order = 0; order <= PMD_ORDER + 1; order++) {
+		pool = dma_pmd_pool_create(order, 2);
+		if (order > PMD_ORDER) {
+			KUNIT_EXPECT_NULL(test, pool);
+			continue;
+		}
+		KUNIT_ASSERT_NOT_NULL(test, pool);
+		KUNIT_EXPECT_FALSE(test, dma_pmd_pool_has_free(pool));
+
+		p1 = dma_pmd_pool_alloc(pool, GFP_KERNEL | __GFP_ZERO);
+		if (!p1)
+			dma_pmd_pool_destroy(pool);
+		KUNIT_ASSERT_NOT_NULL(test, p1);
+		KUNIT_EXPECT_TRUE(test, dma_is_pmd_page(page_to_pfn(p1)));
+		KUNIT_EXPECT_EQ(test, dma_pmd_pool_has_free(pool), order < PMD_ORDER);
+
+		/* Freeing p1 returns it to the pool; next allocation reuses index 0. */
+		__free_pages(p1, order);
+		KUNIT_EXPECT_TRUE(test, dma_pmd_pool_has_free(pool));
+		p2 = dma_pmd_pool_alloc(pool, GFP_KERNEL);
+		KUNIT_EXPECT_PTR_EQ(test, p1, p2);
+
+		/* Destroy with p2 still in flight; freeing p2 releases the 2M page. */
+		dma_pmd_pool_destroy(pool);
+		if (p2)
+			__free_pages(p2, order);
+	}
+}
+
 static struct kunit_case dma_pmd_meta_test_cases[] = {
 	KUNIT_CASE(test_meta_init_and_roundtrip),
 	KUNIT_CASE(test_meta_invalid_phys),
 	KUNIT_CASE(test_meta_pooled_toggle),
+	KUNIT_CASE(test_pool_alloc_and_recycle),
 	{}
 };
 
@@ -98,5 +137,5 @@ static struct kunit_suite dma_pmd_meta_test_suite = {
 };
 
 kunit_test_suite(dma_pmd_meta_test_suite);
-MODULE_DESCRIPTION("KUnit tests for struct dma_pmd_meta table");
+MODULE_DESCRIPTION("KUnit tests for struct dma_pmd_meta table and DMA_PMD pool");
 MODULE_LICENSE("Dual BSD/GPL");
drivers/iommu/dma-pmd-pool.c +279 -0

285 lines not on this page · raw message

include/linux/dma-pmd.h +40 -0
index 236be50b7349f..085d9a730c278 100644
@@ -5,6 +5,7 @@
 
 #include <linux/types.h>
 #include <linux/mm.h>
+#include <linux/numa.h>
 #include <linux/rcupdate.h>
 
 struct device;
@@ -77,6 +78,22 @@ static inline bool dma_pmd_free_page(struct page *page)
  */
 struct dma_pmd_pool *dma_pmd_pool_create(unsigned int order, unsigned int max_idle_pages);
 struct dma_pmd_pool *dma_pmd_pool_destroy(struct dma_pmd_pool *pool);
+unsigned long dma_pmd_pool_alloc_bulk_node(struct dma_pmd_pool *pool, gfp_t gfp,
+					   int nid, unsigned long nr_pages,
+					   struct page **page_array);
+static inline struct page *dma_pmd_pool_alloc_node(struct dma_pmd_pool *pool,
+						   gfp_t gfp, int nid)
+{
+	struct page *page = NULL;
+
+	dma_pmd_pool_alloc_bulk_node(pool, gfp, nid, 1, &page);
+	return page;
+}
+static inline struct page *dma_pmd_pool_alloc(struct dma_pmd_pool *pool, gfp_t gfp)
+{
+	return dma_pmd_pool_alloc_node(pool, gfp, NUMA_NO_NODE);
+}
+bool dma_pmd_pool_has_free(struct dma_pmd_pool *pool);
 
 #else /* !CONFIG_DMA_PMD */
 
@@ -101,5 +118,28 @@ static inline struct dma_pmd_pool *dma_pmd_pool_destroy(struct dma_pmd_pool *poo
 	return NULL;
 }
 
+static inline unsigned long
+dma_pmd_pool_alloc_bulk_node(struct dma_pmd_pool *pool, gfp_t gfp, int nid,
+			     unsigned long nr_pages, struct page **page_array)
+{
+	return 0;
+}
+
+static inline struct page *
+dma_pmd_pool_alloc_node(struct dma_pmd_pool *pool, gfp_t gfp, int nid)
+{
+	return NULL;
+}
+
+static inline struct page *dma_pmd_pool_alloc(struct dma_pmd_pool *pool, gfp_t gfp)
+{
+	return NULL;
+}
+
+static inline bool dma_pmd_pool_has_free(struct dma_pmd_pool *pool)
+{
+	return false;
+}
+
 #endif /* CONFIG_DMA_PMD */
 #endif /* _LINUX_DMA_PMD_H */
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#8 lore raw

RFC 5/22 iommu/dma: Global cap and shrinker for DMA_PMD pool memory

In reply to Luigi Rizzo

Each pool holds some idle pages, for faster future allocations, but on large systems there is one pool per CPU and the number may become large.

Add two mechanism to bound the number of unused DMA_PMD pages:

- a global ceiling on the number of DMA_PMD pages pinned across all pools, defaulting to one eighth of RAM with a floor for small machines if not configured via /sys/module/kernel/parameters/dma_pmd_max_pages It is checked before each DMA_PMD page allocation and is meant to bound a pathological configuration, not to be reached in normal operation.

- a shrinker that, under reclaim, offers every completely idle page in every pool and retires as many as the reclaim path asks for, stopping there. Idle pages are detached under the pool lock and retired outside it, since retiring one unmaps it from the IOMMU.

---
 drivers/iommu/dma-pmd-kunit.c |  21 ++++-
 drivers/iommu/dma-pmd-pool.c  | 146 +++++++++++++++++++++++++++++++++-
 drivers/iommu/dma-pmd-priv.h  |   2 +
 3 files changed, 165 insertions(+), 4 deletions(-)
drivers/iommu/dma-pmd-kunit.c +19 -2
index 24978a5123f54..4e38cc5970433 100644
@@ -88,8 +88,8 @@ static void test_meta_pooled_toggle(struct kunit *test)
 
 static void test_pool_alloc_and_recycle(struct kunit *test)
 {
-	struct dma_pmd_pool *pool;
-	struct page *p1, *p2;
+	struct dma_pmd_pool *pool, *pool_wm;
+	struct page *p1, *p2, *b1, *b2, *b3;
 	unsigned int order;
 
 	KUNIT_EXPECT_NULL(test, dma_pmd_pool_destroy(NULL));
@@ -121,6 +121,23 @@ static void test_pool_alloc_and_recycle(struct kunit *test)
 		if (p2)
 			__free_pages(p2, order);
 	}
+
+	/*
+	 * Exercise max_idle_2m = 1 watermark release: an order-(PMD_ORDER - 1)
+	 * pool has 2 blocks per 2M page, so 3 allocations span two 2M pages.
+	 */
+	pool_wm = dma_pmd_pool_create(PMD_ORDER - 1, 1);
+	KUNIT_ASSERT_NOT_NULL(test, pool_wm);
+	b1 = dma_pmd_pool_alloc(pool_wm, GFP_KERNEL);
+	b2 = dma_pmd_pool_alloc(pool_wm, GFP_KERNEL);
+	b3 = dma_pmd_pool_alloc(pool_wm, GFP_KERNEL);
+	if (b1)
+		__free_pages(b1, PMD_ORDER - 1);
+	if (b2)
+		__free_pages(b2, PMD_ORDER - 1);
+	if (b3)
+		__free_pages(b3, PMD_ORDER - 1);
+	dma_pmd_pool_destroy(pool_wm);
 }
 
 static struct kunit_case dma_pmd_meta_test_cases[] = {
drivers/iommu/dma-pmd-pool.c +144 -2

208 lines not on this page · raw message

drivers/iommu/dma-pmd-priv.h +2 -0
index 99bd7d77fd4ef..39295d0add51d 100644
@@ -21,6 +21,8 @@
  *			when can_block is true. It is not nested with pool->lock
  *			or meta->map_lock, and sits inside dma_pmd_pools_lock
  *			when dma_pmd_pool_create() calls dma_pmd_meta_init().
+ *			The only reverse edge on dma_pmd_pools_lock is the
+ *			shrinker's mutex_trylock(), which cannot block.
  *
  * dma_pmd_pools_lock	Mutex over the list of live pools. Outermost of the
  *			three, and it must not be taken from a context that
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#9 lore raw

RFC 6/22 iommu/dma: reserve a per-domain IOVA window for DMA_PMD pages

In reply to Luigi Rizzo

Embed struct dma_pmd_window in struct iommu_dma_cookie to record the per-domain IOVA range reserved for DMA_PMD mappings, and expose the cookie accessors (dma_pmd_dma_window(), dma_pmd_dma_iovad(), dma_pmd_window_owns()) and dma_info_to_prot() needed by the DMA_PMD mapping layer in subsequent patches.

No functional change.

---
 drivers/iommu/dma-iommu.c     | 39 ++++++++++++++++++-
 drivers/iommu/dma-iommu.h     |  8 ++++
 drivers/iommu/dma-pmd-kunit.c | 19 +++++++++
 drivers/iommu/dma-pmd-priv.h  | 72 +++++++++++++++++++++++++++++++++++
 4 files changed, 137 insertions(+), 1 deletion(-)
drivers/iommu/dma-iommu.c +38 -1
index 58c624513cd43..70aee7a3020c8 100644
@@ -18,6 +18,7 @@
 #include <linux/gfp.h>
 #include <linux/huge_mm.h>
 #include <linux/iommu.h>
+#include <linux/dma-pmd.h>
 #include <linux/iommu-dma.h>
 #include <linux/iova.h>
 #include <linux/irq.h>
@@ -36,6 +37,7 @@
 #include <trace/events/swiotlb.h>
 
 #include "dma-iommu.h"
+#include "dma-pmd-priv.h"
 #include "iommu-pages.h"
 
 struct iommu_dma_msi_page {
@@ -75,6 +77,8 @@ struct iommu_dma_cookie {
 	struct iommu_domain *fq_domain;
 	/* Options for dma-iommu use */
 	struct iommu_dma_options options;
+	/* IOVA window reserved for DMA_PMD pages. Nothing else can go here. */
+	struct dma_pmd_window win_dma_pmd;
 };
 
 struct iommu_dma_msi_cookie {
@@ -732,7 +736,7 @@ static int iommu_dma_init_domain(struct iommu_domain *domain, struct device *dev
  *
  * Return: corresponding IOMMU API page protection flags
  */
-static int dma_info_to_prot(enum dma_data_direction dir, bool coherent,
+int dma_info_to_prot(enum dma_data_direction dir, bool coherent,
 		     unsigned long attrs)
 {
 	int prot;
@@ -1214,6 +1218,39 @@ static inline size_t iova_unaligned(struct iova_domain *iovad, phys_addr_t phys,
 	return iova_offset(iovad, phys | size);
 }
 
+/**
+ * dma_pmd_dma_window - This domain's IOVA window for DMA_PMD
+ * @domain: Domain to look at
+ *
+ * For the DMA_PMD code's slow paths, which need a window but do not have the
+ * cookie layout. The DMA map path is handed the pointer by its caller instead,
+ * so this is never called at map frequency.
+ *
+ * Return: the window, or NULL if @domain is NULL or does not carry a DMA-IOVA
+ * cookie. The cookie shares a union with the MSI, iommufd and fault-handler
+ * ones, so the type has to be tested rather than the pointer. An identity,
+ * passthrough, or MSI-only domain has no window, and a device can be moved to
+ * one after its pool was created (e.g. via sysfs domain type changes or VFIO
+ * attachment).
+ */
+struct dma_pmd_window *dma_pmd_dma_window(struct iommu_domain *domain)
+{
+	/*
+	 * Also decline in kdump kernels (iommu_deferred_attach_enabled);
+	 * dma_pmd_dma_iovad() uses this check so win->size stays 0.
+	 */
+	if (static_branch_unlikely(&iommu_deferred_attach_enabled) ||
+	    !domain || domain->cookie_type != IOMMU_COOKIE_DMA_IOVA)
+		return NULL;
+
+	return &domain->iova_cookie->win_dma_pmd;
+}
+
+struct iova_domain *dma_pmd_dma_iovad(struct iommu_domain *domain)
+{
+	return dma_pmd_dma_window(domain) ? &domain->iova_cookie->iovad : NULL;
+}
+
 dma_addr_t iommu_dma_map_phys(struct device *dev, phys_addr_t phys, size_t size,
 		enum dma_data_direction dir, unsigned long attrs)
 {
drivers/iommu/dma-iommu.h +8 -0
index 040d002525632..241f8de002e50 100644
@@ -7,6 +7,9 @@
 
 #include <linux/iommu.h>
 
+struct dma_pmd_window;
+struct iova_domain;
+
 #ifdef CONFIG_IOMMU_DMA
 
 void iommu_setup_dma_ops(struct device *dev, struct iommu_domain *domain);
@@ -22,6 +25,11 @@ void iommu_dma_get_resv_regions(struct device *dev, struct list_head *list);
 int iommu_dma_sw_msi(struct iommu_domain *domain, struct msi_desc *desc,
 		     phys_addr_t msi_addr);
 
+int dma_info_to_prot(enum dma_data_direction dir, bool coherent, unsigned long attrs);
+
+struct iova_domain *dma_pmd_dma_iovad(struct iommu_domain *domain);
+struct dma_pmd_window *dma_pmd_dma_window(struct iommu_domain *domain);
+
 extern bool iommu_dma_forcedac;
 
 #else /* CONFIG_IOMMU_DMA */
drivers/iommu/dma-pmd-kunit.c +19 -0
index 4e38cc5970433..16312014b8976 100644
@@ -140,11 +140,30 @@ static void test_pool_alloc_and_recycle(struct kunit *test)
 	dma_pmd_pool_destroy(pool_wm);
 }
 
+static void test_window_helpers(struct kunit *test)
+{
+	struct dma_pmd_window win = {};
+
+	KUNIT_ASSERT_EQ(test, dma_pmd_meta_init(), 0);
+
+	/* Empty window (size == 0) never owns any IOVA. */
+	KUNIT_EXPECT_FALSE(test, dma_pmd_window_owns(&win, 0));
+	KUNIT_EXPECT_FALSE(test, dma_pmd_window_owns(&win, SZ_4G));
+
+	win.base = SZ_4G;
+	win.size = SZ_2G;
+	KUNIT_EXPECT_FALSE(test, dma_pmd_window_owns(&win, SZ_4G - 1));
+	KUNIT_EXPECT_TRUE(test, dma_pmd_window_owns(&win, SZ_4G));
+	KUNIT_EXPECT_TRUE(test, dma_pmd_window_owns(&win, SZ_4G + SZ_2G - 1));
+	KUNIT_EXPECT_FALSE(test, dma_pmd_window_owns(&win, SZ_4G + SZ_2G));
+}
+
 static struct kunit_case dma_pmd_meta_test_cases[] = {
 	KUNIT_CASE(test_meta_init_and_roundtrip),
 	KUNIT_CASE(test_meta_invalid_phys),
 	KUNIT_CASE(test_meta_pooled_toggle),
 	KUNIT_CASE(test_pool_alloc_and_recycle),
+	KUNIT_CASE(test_window_helpers),
 	{}
 };
 
drivers/iommu/dma-pmd-priv.h +72 -0

87 lines not on this page · raw message

Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#10 lore raw

RFC 7/22 iommu/dma: release DMA_PMD domain mappings on domain teardown

In reply to Luigi Rizzo

Track per-domain PMD_SIZE leaf PTE presence in a 64-entry domain registry (dma_pmd_domains[]) and a per-PMD-page bitmask (p2m->domains_mapped), unmapping active domains in dma_pmd_unmap_all() when a DMA_PMD page is retired.

When an IOMMU DMA domain is torn down at runtime (for example across VFIO bind/unbind or Dynamic Memory Security domain switches), its page tables and IOVA domain are freed by the caller, but DMA_PMD pages that were mapped into it may outlive the domain in per-queue or per-CPU pools.

Add dma_pmd_domain_release() and call it from iommu_put_dma_cookie() before freeing the cookie:
- Clear the domain's slot in dma_pmd_domains[] and mark it draining so a racing dma_pmd_unmap_all() skips the dying domain instead of calling iommu_unmap() on freed page tables.
- Walk all live pools (including destroyed pools that still hold in-flight DMA_PMD pages via pool->refcount) and clear the domain's bit in every p2m->domains_mapped bitmap via dma_pmd_forget_domain().
- Flush dma_pmd_reclaim_work and wait on dma_pmd_srcu so any in-flight unmapper finishes before the domain index is released for reuse.

---
 drivers/iommu/Makefile        |   2 +-
 drivers/iommu/dma-iommu.c     |   6 +
 drivers/iommu/dma-pmd-kunit.c |   8 ++
 drivers/iommu/dma-pmd-map.c   | 220 ++++++++++++++++++++++++++++++++++
 drivers/iommu/dma-pmd-pool.c  |  59 ++++++---
 drivers/iommu/dma-pmd-priv.h  |  34 ++++++
 6 files changed, 314 insertions(+), 15 deletions(-)
 create mode 100644 drivers/iommu/dma-pmd-map.c
drivers/iommu/Makefile +1 -1
index de2c3bad9aa3e..e701b36b9b605 100644
@@ -11,7 +11,7 @@ obj-$(CONFIG_IOMMU_API) += iommu-traces.o
 obj-$(CONFIG_IOMMU_API) += iommu-sysfs.o
 obj-$(CONFIG_IOMMU_DEBUGFS) += iommu-debugfs.o
 obj-$(CONFIG_IOMMU_DMA) += dma-iommu.o
-obj-$(CONFIG_DMA_PMD) += dma-pmd-meta.o dma-pmd-pool.o
+obj-$(CONFIG_DMA_PMD) += dma-pmd-meta.o dma-pmd-pool.o dma-pmd-map.o
 obj-$(CONFIG_DMA_PMD_META_KUNIT_TEST) += dma-pmd-kunit.o
 obj-$(CONFIG_IOMMU_IO_PGTABLE) += io-pgtable.o
 obj-$(CONFIG_IOMMU_IO_PGTABLE_ARMV7S) += io-pgtable-arm-v7s.o
drivers/iommu/dma-iommu.c +6 -0
index 70aee7a3020c8..ee14175b79bc2 100644
@@ -430,6 +430,12 @@ void iommu_put_dma_cookie(struct iommu_domain *domain)
 	struct iommu_dma_cookie *cookie = domain->iova_cookie;
 	struct iommu_dma_msi_page *msi, *tmp;
 
+	/*
+	 * Drop any DMA_PMD mappings cached against this domain before its
+	 * page tables and IOVA domain go away.
+	 */
+	dma_pmd_domain_release(domain);
+
 	if (cookie->iovad.granule) {
 		iommu_dma_free_fq(cookie);
 		put_iova_domain(&cookie->iovad);
drivers/iommu/dma-pmd-kunit.c +8 -0
index 16312014b8976..7f4251845ba49 100644
@@ -5,6 +5,7 @@
 #include <kunit/test.h>
 #include <linux/gfp.h>
 #include <linux/dma-pmd.h>
+#include <linux/iommu.h>
 #include <linux/mm.h>
 
 #include "dma-pmd-priv.h"
@@ -142,7 +143,9 @@ static void test_pool_alloc_and_recycle(struct kunit *test)
 
 static void test_window_helpers(struct kunit *test)
 {
+	struct iommu_domain dummy_domain = {};
 	struct dma_pmd_window win = {};
+	struct dma_pmd_pool *pool;
 
 	KUNIT_ASSERT_EQ(test, dma_pmd_meta_init(), 0);
 
@@ -156,6 +159,11 @@ static void test_window_helpers(struct kunit *test)
 	KUNIT_EXPECT_TRUE(test, dma_pmd_window_owns(&win, SZ_4G));
 	KUNIT_EXPECT_TRUE(test, dma_pmd_window_owns(&win, SZ_4G + SZ_2G - 1));
 	KUNIT_EXPECT_FALSE(test, dma_pmd_window_owns(&win, SZ_4G + SZ_2G));
+	/* Releasing an unregistered domain with an active pool is a safe no-op. */
+	pool = dma_pmd_pool_create(0, 1);
+	KUNIT_ASSERT_NOT_NULL(test, pool);
+	dma_pmd_domain_release(&dummy_domain);
+	dma_pmd_pool_destroy(pool);
 }
 
 static struct kunit_case dma_pmd_meta_test_cases[] = {
drivers/iommu/dma-pmd-map.c new file +220 -0

220 lines not on this page · raw message

drivers/iommu/dma-pmd-pool.c +45 -14

123 lines not on this page · raw message

drivers/iommu/dma-pmd-priv.h +34 -0
index 8104897572921..8477a8edfac63 100644
@@ -7,8 +7,11 @@
 #include <linux/list.h>
 #include <linux/llist.h>
 #include <linux/spinlock.h>
+#include <linux/srcu.h>
 #include <linux/types.h>
 
+struct iommu_domain;
+
 /**
  * struct dma_pmd_window - A domain's IOVA window reserved for DMA_PMD pages
  * @base: First IOVA of the window. A page at @phys is mapped, in every domain
@@ -36,6 +39,15 @@ struct dma_pmd_window {
 
 #define DMA_PMD_BLOCKS(order)		(1U << (PMD_ORDER - (order)))
 
+/*
+ * Number of IOMMU domains that may use DMA_PMD at once.
+ *
+ * Each such domain is given a dense index, which is the bit position it uses
+ * in dma_pmd_meta.domains_mapped. One word per PMD page records every domain
+ * that has mapped this PMD page. Used to speed up map and unmap.
+ */
+#define DMA_PMD_MAX_DOMAINS		BITS_PER_LONG
+
 /*
  * Sentinel values of dma_pmd_window.domain_idx below DMA_PMD_IDX_FIRST:
  * never attempted (0, matching kzalloc), or permanently declined. A real
@@ -71,6 +83,17 @@ enum {
  * meta->map_lock	IRQ-safe spinlock over one PMD frame's domains_mapped
  *			bitmap. Innermost, and never held across anything that
  *			sleeps.
+ *
+ * The full order is dma_pmd_pools_lock -> pool->lock -> meta->map_lock, as
+ * taken by dma_pmd_domain_release().
+ *
+ * dma_pmd_domains_lock IRQ-safe spinlock over the domain index table and the
+ *			per-domain windows. Taken on its own; it is never
+ *			nested with dma_pmd_pools_lock in either direction.
+ *
+ * dma_pmd_srcu	Read side lets the unmap path dereference a domain out
+ *			of dma_pmd_domains[] without blocking a concurrent
+ *			dma_pmd_domain_release().
  */
 
 /*
@@ -186,6 +209,7 @@ struct dma_pmd_pool {
 } ____cacheline_aligned;
 
 extern unsigned long dma_pmd_meta_nframes;
+extern struct srcu_struct dma_pmd_srcu;
 
 static inline struct dma_pmd_meta *dma_pmd_meta_base(void)
 {
@@ -203,6 +227,10 @@ struct dma_pmd_meta *dma_pmd_meta_from_phys(phys_addr_t pa);
 unsigned long dma_pmd_meta_to_pfn(const struct dma_pmd_meta *m);
 phys_addr_t dma_pmd_meta_to_phys(const struct dma_pmd_meta *m);
 
+unsigned int dma_pmd_pools_forget_domain(int idx);
+void dma_pmd_unmap_all(struct dma_pmd_meta *meta);
+unsigned int dma_pmd_forget_domain(struct dma_pmd_meta *meta, int idx);
+
 static inline bool dma_is_pmd_phys(phys_addr_t phys)
 {
 	return dma_is_pmd_page(phys >> PAGE_SHIFT);
@@ -227,6 +255,8 @@ static inline bool dma_pmd_window_owns(const struct dma_pmd_window *win, dma_add
 	return size && dma - win->base < size;
 }
 
+void dma_pmd_domain_release(struct iommu_domain *domain);
+
 #else /* !CONFIG_DMA_PMD */
 
 static inline bool dma_is_pmd_phys(phys_addr_t phys)
@@ -239,5 +269,9 @@ static inline bool dma_pmd_window_owns(const struct dma_pmd_window *win, dma_add
 	return false;
 }
 
+static inline void dma_pmd_domain_release(struct iommu_domain *domain)
+{
+}
+
 #endif /* CONFIG_DMA_PMD */
 #endif /* _DRIVERS_IOMMU_DMA_PMD_PRIV_H */
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#11 lore raw

RFC 8/22 iommu/dma: use per-domain IOVA window to map DMA_PMD memory

In reply to Luigi Rizzo

Map each DMA_PMD page at win->base + phys inside the domain's reserved IOVA window and track per-domain leaf PDE residency in p2m->domains_mapped:

- dma_pmd_window_assign() assigns a dense domain index in dma_pmd_domains[] and allocates the per-domain IOVA window via dma_pmd_dma_window_alloc() on first use.
- dma_pmd_dma_window_alloc() reserves a PMD_SIZE-aligned range via alloc_iova() from the domain's iova_domain so no ordinary IOVA can land inside it, allowing unmap to identify pooled IOVAs by range check.
- dma_pmd_dma_map_phys() returns win->base + phys in O(1) when the domain's bit is set in p2m->domains_mapped, installing the PDE_ORDER leaf PTE on the first map in a domain.
- iommu_dma_map_phys() and iommu_dma_unmap_phys() route DMA_PMD buffers through the per-domain window, making dma_unmap_*() an O(1) range check with no page-table walk or IOTLB flush.

---
 drivers/iommu/Kconfig        |   1 +
 drivers/iommu/dma-iommu.c    |  27 +++-
 drivers/iommu/dma-pmd-map.c  | 275 +++++++++++++++++++++++++++++++++++
 drivers/iommu/dma-pmd-priv.h |  33 +++++
 drivers/iommu/iommu.c        |   2 +-
 5 files changed, 336 insertions(+), 2 deletions(-)
drivers/iommu/Kconfig +1 -0
index 1bb347fd9da4a..7cb5b036e0f3b 100644
@@ -164,6 +164,7 @@ config DMA_PMD
 	depends on IOMMU_DMA
 	depends on X86_64 || (ARM64 && ARM64_4K_PAGES)
 	depends on !PREEMPT_RT
+	select NEED_SG_DMA_FLAGS
 	default y
 	help
 	  Hand out DMA buffers carved out of PMD_SIZE physically contiguous
drivers/iommu/dma-iommu.c +26 -1
index ee14175b79bc2..6d33e245530ec 100644
@@ -1286,6 +1286,14 @@ dma_addr_t iommu_dma_map_phys(struct device *dev, phys_addr_t phys, size_t size,
 		arch_sync_dma_flush();
 	}
 
+	if (dma_is_pmd_phys(phys)) {
+		iova = dma_pmd_dma_map_phys(dev, domain,
+					    &domain->iova_cookie->win_dma_pmd,
+					    phys, size, prot, dma_mask);
+		if (likely(iova != DMA_MAPPING_ERROR))
+			return iova;
+	}
+
 	iova = __iommu_dma_map(dev, phys, size, prot, dma_mask);
 	if (iova == DMA_MAPPING_ERROR &&
 	    !(attrs & (DMA_ATTR_MMIO | DMA_ATTR_REQUIRE_COHERENT)))
@@ -1296,14 +1304,19 @@ dma_addr_t iommu_dma_map_phys(struct device *dev, phys_addr_t phys, size_t size,
 void iommu_dma_unmap_phys(struct device *dev, dma_addr_t dma_handle,
 		size_t size, enum dma_data_direction dir, unsigned long attrs)
 {
+	struct iommu_domain *domain = iommu_get_dma_domain(dev);
 	phys_addr_t phys;
 
+	/* DMA_PMD mapped buffer: nothing to unmap or release. */
+	if (dma_pmd_window_owns(&domain->iova_cookie->win_dma_pmd, dma_handle))
+		return;
+
 	if (attrs & (DMA_ATTR_MMIO | DMA_ATTR_REQUIRE_COHERENT)) {
 		__iommu_dma_unmap(dev, dma_handle, size);
 		return;
 	}
 
-	phys = iommu_iova_to_phys(iommu_get_dma_domain(dev), dma_handle);
+	phys = iommu_iova_to_phys(domain, dma_handle);
 	if (WARN_ON(!phys))
 		return;
 
@@ -1499,6 +1512,18 @@ int iommu_dma_map_sg(struct device *dev, struct scatterlist *sg, int nents,
 			 */
 			break;
 		case PCI_P2PDMA_MAP_NONE:
+			if (dma_is_pmd_phys(sg_phys(s))) {
+				iova = dma_pmd_dma_map_phys(dev, domain,
+							    &cookie->win_dma_pmd,
+							    sg_phys(s), s_length,
+							    prot, dma_get_mask(dev));
+				if (likely(iova != DMA_MAPPING_ERROR)) {
+					s->dma_address = iova;
+					sg_dma_len(s) = s_length;
+					sg_dma_mark_bus_address(s);
+					continue;
+				}
+			}
 			break;
 		case PCI_P2PDMA_MAP_BUS_ADDR:
 			/*
drivers/iommu/dma-pmd-map.c +275 -0

284 lines not on this page · raw message

drivers/iommu/dma-pmd-priv.h +33 -0
index 8477a8edfac63..355f865f44057 100644
@@ -2,6 +2,7 @@
 #ifndef _DRIVERS_IOMMU_DMA_PMD_PRIV_H
 #define _DRIVERS_IOMMU_DMA_PMD_PRIV_H
 
+#include <linux/dma-mapping.h>
 #include <linux/dma-pmd.h>
 #include <linux/kref.h>
 #include <linux/list.h>
@@ -10,6 +11,7 @@
 #include <linux/srcu.h>
 #include <linux/types.h>
 
+struct device;
 struct iommu_domain;
 
 /**
@@ -220,6 +222,22 @@ static inline struct dma_pmd_meta *dma_pmd_meta_base(void)
 	return smp_load_acquire(&dma_pmd_meta_array);
 }
 
+/*
+ * Highest PFN covered by the allocated @dma_pmd_meta_array reservation.
+ * Every domain's IOVA window is sized to match this bound.
+ */
+static inline unsigned long dma_pmd_top_pfn(void)
+{
+	return dma_pmd_meta_nframes << PMD_ORDER;
+}
+
+/* IOVA of @phys in @win. Only valid once the PMD page's PTE is installed. */
+static inline dma_addr_t dma_pmd_window_iova(const struct dma_pmd_window *win,
+					     phys_addr_t phys)
+{
+	return win->base + phys;
+}
+
 int dma_pmd_meta_init(void);
 bool dma_pmd_meta_ensure_pfn(unsigned long pfn, bool can_block);
 struct dma_pmd_meta *dma_pmd_meta_of_pfn(unsigned long pfn);
@@ -230,6 +248,8 @@ phys_addr_t dma_pmd_meta_to_phys(const struct dma_pmd_meta *m);
 unsigned int dma_pmd_pools_forget_domain(int idx);
 void dma_pmd_unmap_all(struct dma_pmd_meta *meta);
 unsigned int dma_pmd_forget_domain(struct dma_pmd_meta *meta, int idx);
+int dma_pmd_window_assign(struct device *dev, struct iommu_domain *domain,
+			  struct dma_pmd_window *win);
 
 static inline bool dma_is_pmd_phys(phys_addr_t phys)
 {
@@ -255,6 +275,10 @@ static inline bool dma_pmd_window_owns(const struct dma_pmd_window *win, dma_add
 	return size && dma - win->base < size;
 }
 
+dma_addr_t dma_pmd_dma_map_phys(struct device *dev, struct iommu_domain *domain,
+				struct dma_pmd_window *win, phys_addr_t phys,
+				size_t size, int prot, u64 dma_mask);
+
 void dma_pmd_domain_release(struct iommu_domain *domain);
 
 #else /* !CONFIG_DMA_PMD */
@@ -269,6 +293,15 @@ static inline bool dma_pmd_window_owns(const struct dma_pmd_window *win, dma_add
 	return false;
 }
 
+static inline dma_addr_t dma_pmd_dma_map_phys(struct device *dev,
+					      struct iommu_domain *domain,
+					      struct dma_pmd_window *win,
+					      phys_addr_t phys, size_t size,
+					      int prot, u64 dma_mask)
+{
+	return DMA_MAPPING_ERROR;
+}
+
 static inline void dma_pmd_domain_release(struct iommu_domain *domain)
 {
 }
drivers/iommu/iommu.c +1 -1
index cd1bca7ede9af..d918d1294eb0d 100644
@@ -2867,7 +2867,7 @@ ssize_t iommu_map_sg(struct iommu_domain *domain, unsigned long iova,
 	while (i <= nents) {
 		phys_addr_t s_phys = sg_phys(sg);
 
-		if (len && s_phys != start + len) {
+		if (len && (sg_dma_is_bus_address(sg) || s_phys != start + len)) {
 			ret = iommu_map_nosync(domain, iova + mapped, start,
 					len, prot, gfp);
 			if (ret)
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#12 lore raw

RFC 9/22 iommu/dma: Add DMA_PMD arena allocator

In reply to Luigi Rizzo

Device driver use dma_alloc_attrs() for several long lived device-accessible regions, such as queues and header buffers.

Add a compatible dma_pmd_arena allocator for DMA_PMD pages, which will be later used by dma_alloc_attrs() for eligible allocations. Reserve a IOVA region right after the one used to map physical ram, used specifically for dma_pmd_arena allocations so they can be easily identifyed from their IOVA.

---
 drivers/iommu/Makefile        |   3 +-
 drivers/iommu/dma-pmd-arena.c | 385 ++++++++++++++++++++++++++++++++++
 drivers/iommu/dma-pmd-kunit.c |  35 ++++
 drivers/iommu/dma-pmd-map.c   |  19 +-
 drivers/iommu/dma-pmd-meta.c  |  61 ++++--
 drivers/iommu/dma-pmd-priv.h  |  41 +++-
 include/linux/dma-pmd.h       |   9 +
 7 files changed, 519 insertions(+), 34 deletions(-)
 create mode 100644 drivers/iommu/dma-pmd-arena.c
drivers/iommu/Makefile +2 -1
index e701b36b9b605..e96fcf309a0b2 100644
@@ -11,7 +11,8 @@ obj-$(CONFIG_IOMMU_API) += iommu-traces.o
 obj-$(CONFIG_IOMMU_API) += iommu-sysfs.o
 obj-$(CONFIG_IOMMU_DEBUGFS) += iommu-debugfs.o
 obj-$(CONFIG_IOMMU_DMA) += dma-iommu.o
-obj-$(CONFIG_DMA_PMD) += dma-pmd-meta.o dma-pmd-pool.o dma-pmd-map.o
+obj-$(CONFIG_DMA_PMD) += dma-pmd-meta.o dma-pmd-pool.o dma-pmd-map.o \
+			 dma-pmd-arena.o
 obj-$(CONFIG_DMA_PMD_META_KUNIT_TEST) += dma-pmd-kunit.o
 obj-$(CONFIG_IOMMU_IO_PGTABLE) += io-pgtable.o
 obj-$(CONFIG_IOMMU_IO_PGTABLE_ARMV7S) += io-pgtable-arm-v7s.o
drivers/iommu/dma-pmd-arena.c new file +385 -0

385 lines not on this page · raw message

drivers/iommu/dma-pmd-kunit.c +35 -0
index 7f4251845ba49..b91dbcb468879 100644
@@ -166,12 +166,47 @@ static void test_window_helpers(struct kunit *test)
 	dma_pmd_pool_destroy(pool);
 }
 
+static void test_arena_alloc_and_free(struct kunit *test)
+{
+	struct device dev = { .numa_node = NUMA_NO_NODE };
+	void *v1, *v2, *v3, *vl1;
+	dma_addr_t d1, d2, d3, dl1;
+
+	KUNIT_EXPECT_NULL(test,
+			  dma_pmd_arena_alloc(NULL, SZ_4K, &d1, NUMA_NO_NODE));
+
+	v1 = dma_pmd_arena_alloc(&dev, SZ_64K, &d1, NUMA_NO_NODE);
+	KUNIT_ASSERT_NOT_NULL(test, v1);
+	v2 = dma_pmd_arena_alloc(&dev, SZ_64K, &d2, NUMA_NO_NODE);
+	KUNIT_ASSERT_NOT_NULL(test, v2);
+	KUNIT_EXPECT_PTR_EQ(test, v2, v1 + SZ_64K);
+	KUNIT_EXPECT_EQ(test, d2, d1 + SZ_64K);
+
+	/* Freeing v1 unreserves [0, 64K); next 64K alloc reuses it. */
+	KUNIT_EXPECT_TRUE(test, dma_pmd_arena_free(&dev, SZ_64K, v1, d1));
+	v3 = dma_pmd_arena_alloc(&dev, SZ_64K, &d3, NUMA_NO_NODE);
+	KUNIT_EXPECT_PTR_EQ(test, v3, v1);
+	KUNIT_EXPECT_EQ(test, d3, d1);
+
+	/*
+	 * Allocate 3MB (spans 2 contiguous fully_empty slots in ARENA_REGION);
+	 * the trailing 1MB in the second slot is marked partial_empty and can
+	 * satisfy a <= 1MB allocation before both are freed.
+	 */
+	vl1 = dma_pmd_arena_alloc(&dev, SZ_2M + SZ_1M, &dl1, NUMA_NO_NODE);
+	KUNIT_ASSERT_NOT_NULL(test, vl1);
+	KUNIT_EXPECT_TRUE(test, dma_pmd_arena_free(&dev, SZ_2M + SZ_1M, vl1, dl1));
+	KUNIT_EXPECT_TRUE(test, dma_pmd_arena_free(&dev, SZ_64K, v2, d2));
+	KUNIT_EXPECT_TRUE(test, dma_pmd_arena_free(&dev, SZ_64K, v3, d3));
+}
+
 static struct kunit_case dma_pmd_meta_test_cases[] = {
 	KUNIT_CASE(test_meta_init_and_roundtrip),
 	KUNIT_CASE(test_meta_invalid_phys),
 	KUNIT_CASE(test_meta_pooled_toggle),
 	KUNIT_CASE(test_pool_alloc_and_recycle),
 	KUNIT_CASE(test_window_helpers),
+	KUNIT_CASE(test_arena_alloc_and_free),
 	{}
 };
 
drivers/iommu/dma-pmd-map.c +14 -5
index 565e10dd1a2e8..1147874ac8068 100644
@@ -51,6 +51,11 @@ static DEFINE_SPINLOCK(dma_pmd_domains_lock);
  */
 DEFINE_SRCU(dma_pmd_srcu);
 
+bool dma_pmd_domain_active(unsigned int idx, const struct iommu_domain *domain)
+{
+	return READ_ONCE(dma_pmd_domains[idx].domain) == domain;
+}
+
 /**
  * dma_pmd_unmap_all - Remove a PMD page's PTE from every domain holding it
  * @meta: PMD page metadata structure
@@ -77,7 +82,7 @@ DEFINE_SRCU(dma_pmd_srcu);
  */
 void dma_pmd_unmap_all(struct dma_pmd_meta *meta)
 {
-	phys_addr_t phys = dma_pmd_meta_to_phys(meta);
+	dma_addr_t offset = dma_pmd_meta_win_offset(meta);
 	unsigned long mapped, flags;
 	int idx, srcu_idx;
 
@@ -104,7 +109,7 @@ void dma_pmd_unmap_all(struct dma_pmd_meta *meta)
 		if (!domain)
 			continue;
 
-		iommu_unmap(domain, base + phys, PMD_SIZE);
+		iommu_unmap(domain, base + offset, PMD_SIZE);
 	}
 	srcu_read_unlock(&dma_pmd_srcu, srcu_idx);
 }
@@ -170,6 +175,7 @@ void dma_pmd_domain_release(struct iommu_domain *domain)
 {
 	unsigned int dropped = 0;
 	unsigned long flags;
+	unsigned int i;
 	int idx;
 
 	/* Nothing has ever been pooled, so nothing can reference @domain. */
@@ -199,6 +205,9 @@ void dma_pmd_domain_release(struct iommu_domain *domain)
 
 	dropped += dma_pmd_pools_forget_domain(idx);
 
+	for (i = 0; i < DMA_PMD_ARENA_PAGES; i++)
+		dropped += dma_pmd_forget_domain(dma_pmd_arena_meta(i), idx);
+
 	/*
 	 * Any PMD page removed from a pool list before the walk above is either
 	 * already on @dma_pmd_free_list (placed there under @pool->lock in
@@ -225,7 +234,7 @@ void dma_pmd_domain_release(struct iommu_domain *domain)
  * dma_pmd_dma_window_alloc - Allocate an IOVA window for DMA_PMD mappings
  * @dev: Device whose addressing limits the window must respect
  * @domain: Domain to take the window from
- * @size: Window size in bytes
+ * @sizep: In/out window size in bytes
  *
  * Allocates a contiguous IOVA range out of @domain's iova_domain on first use,
  * aligned to PMD_SIZE matching the mapping. Callers on the map path still
@@ -237,9 +246,9 @@ void dma_pmd_domain_release(struct iommu_domain *domain)
 static dma_addr_t dma_pmd_dma_window_alloc(struct device *dev,
 					   struct iommu_domain *domain, u64 *sizep)
 {
+	u64 min_size = ARENA_REGION_SIZE + ALIGN(PFN_PHYS(max_pfn), PMD_SIZE);
 	u64 limit = min_not_zero(dma_get_mask(dev), dev->bus_dma_limit);
 	struct iova_domain *iovad = dma_pmd_dma_iovad(domain);
-	u64 min_size = ALIGN(PFN_PHYS(max_pfn), PMD_SIZE);
 	unsigned long shift, iova_len;
 	struct iova *new_iova;
 
@@ -295,7 +304,7 @@ static dma_addr_t dma_pmd_dma_window_alloc(struct device *dev,
 int dma_pmd_window_assign(struct device *dev, struct iommu_domain *domain,
 			  struct dma_pmd_window *win)
 {
-	u64 size = ALIGN(PFN_PHYS(dma_pmd_top_pfn()), PMD_SIZE);
+	u64 size = ALIGN(PFN_PHYS(dma_pmd_top_pfn()), PMD_SIZE) + ARENA_REGION_SIZE;
 	unsigned long flags;
 	int idx, ret = 0;
 	dma_addr_t base;
drivers/iommu/dma-pmd-meta.c +42 -19

125 lines not on this page · raw message

drivers/iommu/dma-pmd-priv.h +32 -9

102 lines not on this page · raw message

include/linux/dma-pmd.h +9 -0
index 085d9a730c278..55c770fe232b0 100644
@@ -95,6 +95,9 @@ static inline struct page *dma_pmd_pool_alloc(struct dma_pmd_pool *pool, gfp_t g
 }
 bool dma_pmd_pool_has_free(struct dma_pmd_pool *pool);
 
+/* Hooks for kernel/dma/mapping.c */
+bool dma_pmd_arena_free(struct device *dev, size_t size, void *cpu_addr, dma_addr_t dma);
+
 #else /* !CONFIG_DMA_PMD */
 
 static inline bool dma_is_pmd_page(unsigned long pfn)
@@ -141,5 +144,11 @@ static inline bool dma_pmd_pool_has_free(struct dma_pmd_pool *pool)
 	return false;
 }
 
+static inline bool dma_pmd_arena_free(struct device *dev, size_t size,
+				      void *cpu_addr, dma_addr_t dma)
+{
+	return false;
+}
+
 #endif /* CONFIG_DMA_PMD */
 #endif /* _LINUX_DMA_PMD_H */
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#13 lore raw

Re: [RFC: DMA_PMD 09/22] iommu/dma: Add DMA_PMD arena allocator

kernel test robot noticed the following build warnings:

Hi Luigi,

[This is a private test report for your RFC patch.] kernel test robot noticed the following build warnings:

[auto build test WARNING on akpm-mm/mm-everything]
[also build test WARNING on tnguy-next-queue/dev-queue tnguy-net-queue/dev-queue linus/master v7.3-rc6 next-20261006] [If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]

url:    https://github.com/intel-lab-lkp/linux/commits/Luigi-Rizzo/iommu-dma-introduce-CONFIG_DMA_PMD-and-metadata-table/20261003-212220
base:   https://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm.git mm-everything
patch link:    https://lore.kernel.org/r/20261003212241.3432303-10-lrizzo%40google.com
patch subject: [RFC: DMA_PMD 09/22] iommu/dma: Add DMA_PMD arena allocator
config: x86_64-randconfig-1007-20261008 (https://download.01.org/0day-ci/archive/20261008/[email protected]/config)
compiler: gcc-14 (Debian 14.2.0-19) 14.2.0
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20261008/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All warnings (new ones prefixed by >>):

drivers/iommu/dma-pmd-kunit.c: In function 'test_arena_alloc_and_free':
drivers/iommu/dma-pmd-kunit.c:171:32: error: 'struct device' has no member named 'numa_node'

     171 |         struct device dev = { .numa_node = NUMA_NO_NODE };
         |                                ^~~~~~~~~
   In file included from include/linux/nodemask.h:93,
                    from include/linux/numa.h:6,
                    from include/linux/cpumask.h:15,
                    from arch/x86/include/asm/paravirt.h:19,
                    from arch/x86/include/asm/irqflags.h:100,
                    from include/linux/irqflags.h:18,
                    from include/linux/spinlock.h:59,
                    from include/linux/kref.h:16,
                    from include/kunit/test.h:22,
                    from drivers/iommu/dma-pmd-kunit.c:5:
   include/linux/nodemask_types.h:15:25: error: initialization of 'const char *' from 'int' makes pointer from integer without a cast [-Wint-conversion]
      15 | #define NUMA_NO_NODE    (-1)
         |                         ^
   drivers/iommu/dma-pmd-kunit.c:171:44: note: in expansion of macro 'NUMA_NO_NODE'
     171 |         struct device dev = { .numa_node = NUMA_NO_NODE };
         |                                            ^~~~~~~~~~~~
   include/linux/nodemask_types.h:15:25: note: (near initialization for 'dev.kobj.name')
      15 | #define NUMA_NO_NODE    (-1)
         |                         ^
   drivers/iommu/dma-pmd-kunit.c:171:44: note: in expansion of macro 'NUMA_NO_NODE'
     171 |         struct device dev = { .numa_node = NUMA_NO_NODE };
         |                                            ^~~~~~~~~~~~
>> drivers/iommu/dma-pmd-kunit.c:171:29: warning: missing braces around initializer [-Wmissing-braces]
     171 |         struct device dev = { .numa_node = NUMA_NO_NODE };
         |                             ^

vim +171 drivers/iommu/dma-pmd-kunit.c

168
169 static void test_arena_alloc_and_free(struct kunit *test)
170 {

 > 171		struct device dev = { .numa_node = NUMA_NO_NODE };

172 void *v1, *v2, *v3, *vl1;
173 dma_addr_t d1, d2, d3, dl1;
174
175 KUNIT_EXPECT_NULL(test,
176 dma_pmd_arena_alloc(NULL, SZ_4K, &d1, NUMA_NO_NODE));
177
178 v1 = dma_pmd_arena_alloc(&dev, SZ_64K, &d1, NUMA_NO_NODE);
179 KUNIT_ASSERT_NOT_NULL(test, v1);
180 v2 = dma_pmd_arena_alloc(&dev, SZ_64K, &d2, NUMA_NO_NODE);
181 KUNIT_ASSERT_NOT_NULL(test, v2);
182 KUNIT_EXPECT_PTR_EQ(test, v2, v1 + SZ_64K);
183 KUNIT_EXPECT_EQ(test, d2, d1 + SZ_64K);
184
185 /* Freeing v1 unreserves [0, 64K); next 64K alloc reuses it. */
186 KUNIT_EXPECT_TRUE(test, dma_pmd_arena_free(&dev, SZ_64K, v1, d1));
187 v3 = dma_pmd_arena_alloc(&dev, SZ_64K, &d3, NUMA_NO_NODE);
188 KUNIT_EXPECT_PTR_EQ(test, v3, v1);
189 KUNIT_EXPECT_EQ(test, d3, d1);
190
191 /*
192 * Allocate 3MB (spans 2 contiguous fully_empty slots in ARENA_REGION);
193 * the trailing 1MB in the second slot is marked partial_empty and can
194 * satisfy a <= 1MB allocation before both are freed.
195 */
196 vl1 = dma_pmd_arena_alloc(&dev, SZ_2M + SZ_1M, &dl1, NUMA_NO_NODE);
197 KUNIT_ASSERT_NOT_NULL(test, vl1);
198 KUNIT_EXPECT_TRUE(test, dma_pmd_arena_free(&dev, SZ_2M + SZ_1M, vl1, dl1));
199 KUNIT_EXPECT_TRUE(test, dma_pmd_arena_free(&dev, SZ_64K, v2, d2));
200 KUNIT_EXPECT_TRUE(test, dma_pmd_arena_free(&dev, SZ_64K, v3, d3));
201 }
202

--
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki

#14 lore raw

RFC 10/22 driver core: Add per-device dma_pmd_* sysfs attributes

In reply to Luigi Rizzo

Add four boolean attributes to struct device exposed under /sys/devices/*/*/dma_pmd_*:
- dma_pmd_rxbuf: enable DMA_PMD pools for RX buffers / page_pool
- dma_pmd_tx_hdrs: enable DMA_PMD pools for TX header bounce buffers
- dma_pmd_rings: enable DMA_PMD arena for coherent rings
- dma_pmd_debug: log coherent DMA alloc timing and arena usage

These can be used by device drivers to selectively enable DMA_PMD for their allocations.

---
 drivers/base/core.c    | 51 ++++++++++++++++++++++++++++++++++++++++++
 include/linux/device.h |  5 +++++
 2 files changed, 56 insertions(+)
drivers/base/core.c +51 -0
index 4c0c373998a19..f8c3c42d84b8d 100644
@@ -2905,6 +2905,43 @@ static ssize_t removable_show(struct device *dev, const struct device_attribute
 }
 static const DEVICE_ATTR_RO(removable);
 
+/* Per-device configuration to selectively enable DMA_PMD */
+#define DMA_PMD_BOOL_ATTR(name)						\
+static ssize_t name##_show(struct device *dev,				\
+			   struct device_attribute *attr, char *buf)	\
+{									\
+	return sysfs_emit(buf, "%u\n", READ_ONCE(dev->name));		\
+}									\
+static ssize_t name##_store(struct device *dev,				\
+			    struct device_attribute *attr,		\
+			    const char *buf, size_t count)		\
+{									\
+	bool val;							\
+	int ret = kstrtobool(buf, &val);				\
+	if (ret < 0)							\
+		return ret;						\
+	WRITE_ONCE(dev->name, val);					\
+	return count;							\
+}									\
+static DEVICE_ATTR_RW(name)
+
+DMA_PMD_BOOL_ATTR(dma_pmd_rxbuf);
+DMA_PMD_BOOL_ATTR(dma_pmd_tx_hdrs);
+DMA_PMD_BOOL_ATTR(dma_pmd_rings);
+DMA_PMD_BOOL_ATTR(dma_pmd_debug);
+
+static struct attribute *dev_attr_dma_pmd[] = {
+	&dev_attr_dma_pmd_rxbuf.attr,
+	&dev_attr_dma_pmd_tx_hdrs.attr,
+	&dev_attr_dma_pmd_rings.attr,
+	&dev_attr_dma_pmd_debug.attr,
+	NULL,
+};
+
+static const struct attribute_group dev_attr_dma_pmd_group = {
+	.attrs = dev_attr_dma_pmd,
+};
+
 int device_add_groups(struct device *dev,
 		      const struct attribute_group *const *groups)
 {
@@ -3012,8 +3049,20 @@ static int device_add_attrs(struct device *dev)
 			goto err_remove_dev_removable;
 	}
 
+	if (dev->dma_mask) {
+		error = device_add_group(dev, &dev_attr_dma_pmd_group);
+		if (error)
+			goto err_remove_dev_physical_location;
+	}
+
 	return 0;
 
+ err_remove_dev_physical_location:
+	if (dev->physical_location) {
+		device_remove_group(dev, &dev_attr_physical_location_group);
+		kfree(dev->physical_location);
+		dev->physical_location = NULL;
+	}
  err_remove_dev_removable:
 	device_remove_file(dev, &dev_attr_removable);
  err_remove_dev_waiting_for_supplier:
@@ -3037,6 +3086,8 @@ static void device_remove_attrs(struct device *dev)
 	const struct class *class = dev->class;
 	const struct device_type *type = dev->type;
 
+	device_remove_group(dev, &dev_attr_dma_pmd_group);
+
 	if (dev->physical_location) {
 		device_remove_group(dev, &dev_attr_physical_location_group);
 		kfree(dev->physical_location);
include/linux/device.h +5 -0
index aee79fd6b32b4..52aa4a7e1cc45 100644
@@ -794,6 +794,11 @@ struct device {
 
 	enum device_removable	removable;
 
+	bool			dma_pmd_rxbuf;
+	bool			dma_pmd_tx_hdrs;
+	bool			dma_pmd_rings;
+	bool			dma_pmd_debug;
+
 	DECLARE_BITMAP(flags, DEV_FLAG_COUNT);
 };
 
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#15 lore raw

RFC 11/22 dma-mapping: Use DMA_PMD arena for dma_alloc_attrs()

In reply to Luigi Rizzo

Wire dma_alloc_attrs() and dma_free_attrs() into the DMA_PMD arena when dev->dma_pmd_rings is enabled on a device:
- Add dma_pmd_dma_alloc() and dma_is_pmd_dma() backed by dma_pmd_arena.
- Route GFP_KERNEL dma_alloc_attrs() requests through dma_pmd_dma_alloc()

    when dev->dma_pmd_rings is set, logging latency when
    dev->dma_pmd_debug is enabled.

- Reclaim sub-allocations back to the arena in dma_free_attrs() via dma_pmd_arena_free() while keeping the PMD_SIZE IOMMU mapping active.

---
 drivers/iommu/dma-pmd-arena.c | 27 ++++++++++++++++++++++++
 drivers/iommu/dma-pmd-kunit.c | 11 +++++++---
 drivers/iommu/dma-pmd-map.c   | 17 +++++++++++++++
 include/linux/dma-pmd.h       | 29 ++++++++++++++++++++++++++
 kernel/dma/mapping.c          | 39 +++++++++++++++++++++++++++++------
 5 files changed, 114 insertions(+), 9 deletions(-)
drivers/iommu/dma-pmd-arena.c +27 -0
index 578df5be86a86..e1a7d9d6f0f60 100644
@@ -383,3 +383,30 @@ void *dma_pmd_arena_alloc(struct device *dev, size_t size, dma_addr_t *dma, int
 	return NULL;
 }
 EXPORT_SYMBOL(dma_pmd_arena_alloc);
+
+void *dma_pmd_dma_alloc(struct device *dev, size_t size, dma_addr_t *dma,
+			gfp_t gfp, unsigned long attrs)
+{
+	void *va;
+
+	if (!dev || !dev->iommu_group || !dev_is_dma_coherent(dev))
+		return NULL;
+	/*
+	 * The arena allocates PMD pages, IOMMU page tables, and vmap() areas
+	 * with GFP_KERNEL, and shares PMD pages across allocations on the same
+	 * device. Decline non-GFP_KERNEL requests (including GFP_NOFS/GFP_NOIO
+	 * or scoped memalloc_nofs/noio contexts) and per-allocation modifiers
+	 * such as __GFP_ACCOUNT or __GFP_NORETRY so the caller falls back to
+	 * the standard DMA allocator.
+	 */
+	if ((current_gfp_context(gfp) & ~(__GFP_ZERO | __GFP_NOWARN)) != GFP_KERNEL ||
+	    (attrs & ~DMA_ATTR_NO_WARN))
+		return NULL;
+
+	va = dma_pmd_arena_alloc(dev, size, dma, dev_to_node(dev));
+	if (!va && !(gfp & __GFP_NOWARN) && !(attrs & DMA_ATTR_NO_WARN))
+		dev_warn_ratelimited(dev, "DMA_PMD arena alloc failed (size %zu)\n",
+				     size);
+	return va;
+}
+EXPORT_SYMBOL(dma_pmd_dma_alloc);
drivers/iommu/dma-pmd-kunit.c +8 -3
index b91dbcb468879..c2363277e2ecd 100644
@@ -169,11 +169,16 @@ static void test_window_helpers(struct kunit *test)
 static void test_arena_alloc_and_free(struct kunit *test)
 {
 	struct device dev = { .numa_node = NUMA_NO_NODE };
-	void *v1, *v2, *v3, *vl1;
 	dma_addr_t d1, d2, d3, dl1;
+	void *v1, *v2, *v3, *vl1;
 
-	KUNIT_EXPECT_NULL(test,
-			  dma_pmd_arena_alloc(NULL, SZ_4K, &d1, NUMA_NO_NODE));
+	KUNIT_EXPECT_NULL(test, dma_pmd_arena_alloc(NULL, SZ_4K, &d1, NUMA_NO_NODE));
+	KUNIT_EXPECT_NULL(test, dma_pmd_dma_alloc(NULL, SZ_4K, &d1, GFP_KERNEL, 0));
+	KUNIT_EXPECT_NULL(test, dma_pmd_dma_alloc(&dev, SZ_4K, &d1, GFP_KERNEL, 0));
+	KUNIT_EXPECT_NULL(test, dma_pmd_dma_alloc(&dev, SZ_4K, &d1,
+						  GFP_KERNEL | __GFP_ACCOUNT, 0));
+	KUNIT_EXPECT_FALSE(test, dma_pmd_free(&dev, SZ_4K, NULL, 0));
+	KUNIT_EXPECT_FALSE(test, dma_is_pmd_dma(&dev, 0));
 
 	v1 = dma_pmd_arena_alloc(&dev, SZ_64K, &d1, NUMA_NO_NODE);
 	KUNIT_ASSERT_NOT_NULL(test, v1);
drivers/iommu/dma-pmd-map.c +17 -0
index 1147874ac8068..76cb5d01cb1e8 100644
@@ -380,6 +380,23 @@ int dma_pmd_window_assign(struct device *dev, struct iommu_domain *domain,
 	return ret;
 }
 
+/**
+ * dma_is_pmd_dma - Test whether @dma lies in @dev's DMA_PMD IOVA window
+ * @dev: Device performing DMA
+ * @dma: DMA address to test
+ */
+bool dma_is_pmd_dma(struct device *dev, dma_addr_t dma)
+{
+	struct dma_pmd_window *win;
+
+	if (!dev || !dev->iommu_group)
+		return false;
+
+	win = dma_pmd_dma_window(iommu_get_dma_domain(dev));
+	return win && dma_pmd_window_owns(win, dma);
+}
+EXPORT_SYMBOL(dma_is_pmd_dma);
+
 /**
  * dma_pmd_dma_map_phys - Derive the IOVA of a pool address, mapping if needed
  * @dev: Device performing DMA
include/linux/dma-pmd.h +29 -0
index 55c770fe232b0..7b7e9477d44e1 100644
@@ -96,7 +96,19 @@ static inline struct page *dma_pmd_pool_alloc(struct dma_pmd_pool *pool, gfp_t g
 bool dma_pmd_pool_has_free(struct dma_pmd_pool *pool);
 
 /* Hooks for kernel/dma/mapping.c */
+void *dma_pmd_dma_alloc(struct device *dev, size_t size, dma_addr_t *dma,
+			gfp_t gfp, unsigned long attrs);
 bool dma_pmd_arena_free(struct device *dev, size_t size, void *cpu_addr, dma_addr_t dma);
+bool dma_is_pmd_dma(struct device *dev, dma_addr_t dma);
+
+static inline bool dma_pmd_free(struct device *dev, size_t size,
+				void *cpu_addr, dma_addr_t dma_handle)
+{
+	/* Pairs with smp_store_release() in dma_pmd_meta_init(). */
+	if (likely(!smp_load_acquire(&dma_pmd_meta_array)))
+		return false;
+	return dma_pmd_arena_free(dev, size, cpu_addr, dma_handle);
+}
 
 #else /* !CONFIG_DMA_PMD */
 
@@ -144,11 +156,28 @@ static inline bool dma_pmd_pool_has_free(struct dma_pmd_pool *pool)
 	return false;
 }
 
+static inline void *dma_pmd_dma_alloc(struct device *dev, size_t size, dma_addr_t *dma,
+				      gfp_t gfp, unsigned long attrs)
+{
+	return NULL;
+}
+
 static inline bool dma_pmd_arena_free(struct device *dev, size_t size,
 				      void *cpu_addr, dma_addr_t dma)
 {
 	return false;
 }
 
+static inline bool dma_is_pmd_dma(struct device *dev, dma_addr_t dma)
+{
+	return false;
+}
+
+static inline bool dma_pmd_free(struct device *dev, size_t size,
+				void *cpu_addr, dma_addr_t dma_handle)
+{
+	return false;
+}
+
 #endif /* CONFIG_DMA_PMD */
 #endif /* _LINUX_DMA_PMD_H */
kernel/dma/mapping.c +33 -6
index bf2651a70b7c2..cc18896017e35 100644
@@ -10,6 +10,8 @@
 #include <linux/dma-map-ops.h>
 #include <linux/export.h>
 #include <linux/gfp.h>
+#include <linux/ktime.h>
+#include <linux/dma-pmd.h>
 #include <linux/iommu-dma.h>
 #include <linux/kmsan.h>
 #include <linux/of_device.h>
@@ -180,7 +182,8 @@ dma_addr_t dma_map_phys(struct device *dev, phys_addr_t phys, size_t size,
 	if (!is_mmio)
 		kmsan_handle_dma(phys, size, dir);
 	trace_dma_map_phys(dev, phys, addr, size, dir, attrs);
-	debug_dma_map_phys(dev, phys, size, dir, addr, attrs);
+	if (IS_ENABLED(CONFIG_DMA_API_DEBUG) && !dma_is_pmd_dma(dev, addr))
+		debug_dma_map_phys(dev, phys, size, dir, addr, attrs);
 
 	return addr;
 }
@@ -223,7 +226,8 @@ void dma_unmap_phys(struct device *dev, dma_addr_t addr, size_t size,
 	else if (ops->unmap_phys)
 		ops->unmap_phys(dev, addr, size, dir, attrs);
 	trace_dma_unmap_phys(dev, addr, size, dir, attrs);
-	debug_dma_unmap_phys(dev, addr, size, dir, attrs);
+	if (IS_ENABLED(CONFIG_DMA_API_DEBUG) && !dma_is_pmd_dma(dev, addr))
+		debug_dma_unmap_phys(dev, addr, size, dir, attrs);
 }
 EXPORT_SYMBOL_GPL(dma_unmap_phys);
 
@@ -633,7 +637,11 @@ EXPORT_SYMBOL_GPL(dma_get_required_mask);
 void *dma_alloc_attrs(struct device *dev, size_t size, dma_addr_t *dma_handle,
 		gfp_t flag, unsigned long attrs)
 {
+	bool debug = unlikely(READ_ONCE(dev->dma_pmd_debug)) && gfpflags_allow_blocking(flag);
 	const struct dma_map_ops *ops = get_dma_ops(dev);
+	bool can_block = gfpflags_allow_blocking(flag);
+	bool from_arena = false;
+	u64 start_ns = 0;
 	void *cpu_addr;
 
 	WARN_ON_ONCE(!dev->coherent_dma_mask);
@@ -655,10 +663,14 @@ void *dma_alloc_attrs(struct device *dev, size_t size, dma_addr_t *dma_handle,
 	if (force_dma_unencrypted(dev))
 		attrs |= __DMA_ATTR_ALLOC_CC_SHARED;
 
+	if (debug) {
+		start_ns = ktime_get_ns();
+		*dma_handle = 0;
+	}
 	if (dma_alloc_from_dev_coherent(dev, size, dma_handle, &cpu_addr)) {
 		trace_dma_alloc(dev, cpu_addr, *dma_handle, size,
 				DMA_BIDIRECTIONAL, flag, attrs);
-		return cpu_addr;
+		goto out_debug;
 	}
 
 	/* let the implementation decide on the zone to allocate from: */
@@ -667,18 +679,31 @@ void *dma_alloc_attrs(struct device *dev, size_t size, dma_addr_t *dma_handle,
 	if (dma_alloc_direct(dev, ops) || arch_dma_alloc_direct(dev)) {
 		cpu_addr = dma_direct_alloc(dev, size, dma_handle, flag, attrs);
 	} else if (use_dma_iommu(dev)) {
-		cpu_addr = iommu_dma_alloc(dev, size, dma_handle, flag, attrs);
+		if (READ_ONCE(dev->dma_pmd_rings) && can_block) {
+			cpu_addr = dma_pmd_dma_alloc(dev, size, dma_handle, flag, attrs);
+			from_arena = !!cpu_addr;
+		}
+		if (!from_arena)
+			cpu_addr = iommu_dma_alloc(dev, size, dma_handle, flag, attrs);
 	} else if (ops->alloc) {
 		cpu_addr = ops->alloc(dev, size, dma_handle, flag, attrs);
 	} else {
+		cpu_addr = NULL;
 		trace_dma_alloc(dev, NULL, 0, size, DMA_BIDIRECTIONAL, flag,
 				attrs);
-		return NULL;
+		goto out_debug;
 	}
 
 	trace_dma_alloc(dev, cpu_addr, *dma_handle, size, DMA_BIDIRECTIONAL,
 			flag, attrs);
-	debug_dma_alloc_coherent(dev, size, *dma_handle, cpu_addr, attrs);
+	if (!from_arena)
+		debug_dma_alloc_coherent(dev, size, *dma_handle, cpu_addr, attrs);
+out_debug:
+	if (debug)
+		dev_info(dev,
+			 "dma_alloc_coherent(size=%zu, gfp=%pGg, attrs=%#lx) -> va=%p, dma=%pad, arena=%d in %llu ns\n",
+			 size, &flag, attrs, cpu_addr, dma_handle, from_arena,
+			 ktime_get_ns() - start_ns);
 	return cpu_addr;
 }
 EXPORT_SYMBOL(dma_alloc_attrs);
@@ -703,6 +728,8 @@ void dma_free_attrs(struct device *dev, size_t size, void *cpu_addr,
 		       attrs);
 	if (!cpu_addr)
 		return;
+	if (use_dma_iommu(dev) && dma_pmd_free(dev, size, cpu_addr, dma_handle))
+		return;
 
 	debug_dma_free_coherent(dev, size, cpu_addr, dma_handle, attrs);
 	if (dma_alloc_direct(dev, ops) || arch_dma_free_direct(dev, dma_handle))
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#16 lore raw

RFC 12/22 net/core: Use per-CPU DMA_PMD pools for skb_page_frag_refill()

In reply to Luigi Rizzo

Add sysctl net.core.tx_enable_dma_pmd to back skb_page_frag_refill() with per-CPU order-3 (32KB block) and order-0 (4KB block) DMA_PMD page pools.

When enabled, TX socket buffer page fragment allocations draw fragments from DMA_PMD physical pages registered with per-CPU dma_pmd_pool. The first allocation maps the entire DMA_PMD page, subsequent allocations reuse the cached PMD_SIZE IOVA mapping locklessly without per-packet unmap or IOTLB flush.

---
 include/net/sock.h         |  3 ++
 net/core/sock.c            | 86 +++++++++++++++++++++++++++++++++++++-
 net/core/sysctl_net_core.c |  7 ++++
 3 files changed, 94 insertions(+), 2 deletions(-)
include/net/sock.h +3 -0
index 60ea55dc18854..a06b53e9ff225 100644
@@ -3092,6 +3092,9 @@ extern __u32 sysctl_rmem_default;
 
 #define SKB_FRAG_PAGE_ORDER	get_order(32768)
 DECLARE_STATIC_KEY_FALSE(net_high_order_alloc_disable_key);
+DECLARE_STATIC_KEY_FALSE(net_tx_enable_dma_pmd_key);
+int net_tx_dma_pmd_sysctl(const struct ctl_table *table, int write,
+			  void *buffer, size_t *lenp, loff_t *ppos);
 
 static inline int sk_get_wmem0(const struct sock *sk, const struct proto *proto)
 {
net/core/sock.c +84 -2

110 lines not on this page · raw message

net/core/sysctl_net_core.c +7 -0
index eb35da3556f4a..d9a7d9cb349e0 100644
@@ -651,6 +651,13 @@ static struct ctl_table net_core_table[] = {
 		.mode		= 0644,
 		.proc_handler	= proc_do_static_key,
 	},
+	{
+		.procname	= "tx_enable_dma_pmd",
+		.data		= &net_tx_enable_dma_pmd_key.key,
+		.maxlen		= sizeof(net_tx_enable_dma_pmd_key),
+		.mode		= 0644,
+		.proc_handler	= net_tx_dma_pmd_sysctl,
+	},
 	{
 		.procname	= "gro_normal_batch",
 		.data		= &net_hotdata.gro_normal_batch,
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#17 lore raw

RFC 13/22 net/core: Use DMA_PMD for page_pool memory

In reply to Luigi Rizzo

When dev->dma_pmd_rxbuf is enabled on the pool device,
use a per-page_pool DMA_PMD pool for page_pool allocations (__page_pool_alloc_netmems_slow() and __page_pool_alloc_page_order()).

When enabled, pages leaving the page_pool cache (e.g. held by socket buffers beyond NAPI) return to the DMA_PMD pool on final put_page(), retaining their cached IOVA mapping, avoiding per-page 4KB IOMMU PTE updates and IOTLB flushes on replenishment. Plain 4KB pages are opportunistically replaced in __page_pool_page_can_be_recycled() when free pooled blocks are available.

Also skip inserting and erasing DMA_PMD pages in the pool->dma_mapped XArray (used for DMA_ATTR_SKIP_CPU_SYNC tracking), as dma_unmap_page_attrs() is a no-op for DMA_PMD pages and skipping the XArray avoids xa_lock contention on refill and release.

---
 include/net/page_pool/types.h |  3 ++
 net/core/page_pool.c          | 61 ++++++++++++++++++++++++++++-------
 2 files changed, 52 insertions(+), 12 deletions(-)
include/net/page_pool/types.h +3 -0
index 03da138722f58..62a5c50dda43f 100644
@@ -34,6 +34,8 @@
 #define PP_FLAG_ALL		(PP_FLAG_DMA_MAP | PP_FLAG_DMA_SYNC_DEV | \
 				 PP_FLAG_SYSTEM_POOL | PP_FLAG_ALLOW_UNREADABLE_NETMEM)
 
+struct dma_pmd_pool;
+
 /* Index limit to stay within PP_DMA_INDEX_BITS for DMA indices */
 #define PP_DMA_INDEX_LIMIT XA_LIMIT(1, BIT(PP_DMA_INDEX_BITS) - 1)
 
@@ -234,6 +236,7 @@ struct page_pool {
 
 	void *mp_priv;
 	const struct memory_provider_ops *mp_ops;
+	struct dma_pmd_pool *dma_pmd_pool;
 
 	struct xarray dma_mapped;
 
net/core/page_pool.c +49 -12

117 lines not on this page · raw message

Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#18 lore raw

RFC 14/22 iommu/dma: Support decrypted and pinned DMA_PMD pages

In reply to Luigi Rizzo

In Confidential Computing (CoCo) guests (AMD SEV-SNP, Intel TDX, ARM CCA), guest memory is private/encrypted by default and DMA buffers must be converted to shared/decrypted in the host page tables before a device can access them. Similarly, in preemptible VMs, IO-accessible memory may need to be pinned in the host on allocation and unpinned on release.

Doing these conversions on a per-packet 4K basis is prohibitive. With DMA_PMD pools, a 2MB page is allocated once from the buddy allocator, handed out in sub-blocks, and only returned when completely idle.

Add two module parameters (dma_pmd.decrypt and dma_pmd.pin, with dma_pmd.decrypt auto-enabled when CC_ATTR_GUEST_MEM_ENCRYPT is active) and per-PMD-page state flags in meta->flags (DMA_PMD_DECRYPTED, DMA_PMD_PINNED):

- On 2MB page allocation (dma_pmd_add_page), call dma_pmd_page_prepare() before splitting the compound page to invoke set_memory_decrypted() and/or the host pin hook. Skip conversion if the caller cannot sleep (!gfpflags_allow_blocking), since set_memory_decrypted() acquires cpa_lock and allocates PTE pages.
- On 2MB page release (dma_pmd_release_page / dma_pmd_release_page_rcu), call dma_pmd_page_unprepare() before RCU free to restore set_memory_encrypted() and/or unpin before returning the 2MB page to the buddy allocator. If restoration fails, leak the 2MB page rather than returning a page with inconsistent encryption/pin state to buddy.
- In dma_pmd_shrink_scan(), defer decrypted/pinned pages to the async reclaim workqueue (dma_pmd_free_list) instead of calling dma_pmd_release_page() inline under fs_reclaim.
- Add dma_is_pmd_direct(phys) and use it in dma_direct_map_phys() to bypass swiotlb_map() bounce buffering for decrypted/pinned DMA_PMD pages, using phys_to_dma_direct() so force_dma_unencrypted() devices receive unencrypted DMA addresses.

---
 drivers/iommu/dma-pmd-kunit.c |   2 +-
 drivers/iommu/dma-pmd-meta.c  |  15 +++-
 drivers/iommu/dma-pmd-pool.c  | 147 ++++++++++++++++++++++++++++------
 drivers/iommu/dma-pmd-priv.h  |  14 +++-
 include/linux/dma-pmd.h       |  15 ++++
 kernel/dma/direct.c           |   6 +-
 6 files changed, 168 insertions(+), 31 deletions(-)
drivers/iommu/dma-pmd-kunit.c +1 -1
index c2363277e2ecd..7fcc2bcb315bc 100644
@@ -53,7 +53,7 @@ static void test_meta_invalid_phys(struct kunit *test)
 
 static void dma_pmd_meta_set_pooled(struct dma_pmd_meta *m, bool pooled)
 {
-	WRITE_ONCE(m->pooled, pooled);
+	WRITE_ONCE(m->flags, pooled ? DMA_PMD_POOLED : 0);
 }
 
 static void test_meta_pooled_toggle(struct kunit *test)
drivers/iommu/dma-pmd-meta.c +14 -1
index 8f2bc7d77e5bd..744964d2c7974 100644
@@ -8,6 +8,7 @@
 #include <linux/bitmap.h>
 #include <linux/cache.h>
 #include <linux/cacheflush.h>
+#include <linux/cc_platform.h>
 #include <linux/dma-pmd.h>
 #include <linux/export.h>
 #include <linux/gfp.h>
@@ -64,10 +65,22 @@ static __always_inline struct dma_pmd_meta *__dma_pmd_meta_of_pfn(unsigned long
 
 bool __dma_is_pmd_page(unsigned long pfn)
 {
-	return READ_ONCE(__dma_pmd_meta_of_pfn(pfn)->pooled);
+	return READ_ONCE(__dma_pmd_meta_of_pfn(pfn)->flags) & DMA_PMD_POOLED;
 }
 EXPORT_SYMBOL(__dma_is_pmd_page);
 
+bool __dma_is_pmd_direct(unsigned long pfn)
+{
+	u8 flags = READ_ONCE(__dma_pmd_meta_of_pfn(pfn)->flags);
+
+	if (cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT) &&
+	    !(flags & DMA_PMD_DECRYPTED))
+		return false;
+	return (flags & DMA_PMD_POOLED) &&
+	       (flags & (DMA_PMD_DECRYPTED | DMA_PMD_PINNED));
+}
+EXPORT_SYMBOL(__dma_is_pmd_direct);
+
 /**
  * dma_pmd_meta_of_pfn - Metadata for a PFN known to be used by DMA_PMD.
  * @pfn: PFN the caller already holds a struct page for
drivers/iommu/dma-pmd-pool.c +123 -24

226 lines not on this page · raw message

drivers/iommu/dma-pmd-priv.h +10 -4
index b411ecb1fdafc..8c7a50d5b7220 100644
@@ -107,10 +107,16 @@ enum {
 #define DMA_PMD_META_SHIFT		8
 #define DMA_PMD_META_SIZE		BIT(DMA_PMD_META_SHIFT)
 
+enum {
+	DMA_PMD_POOLED		= BIT(0),
+	DMA_PMD_DECRYPTED	= BIT(1),
+	DMA_PMD_PINNED		= BIT(2),
+};
+
 /**
  * struct dma_pmd_meta - Metadata for a single DMA_PMD page
- * @pooled:	True while this page is owned by an dma_pmd_pool (offset 0)
- *		read locklessly by dma_is_pmd_page().
+ * @flags:	Bitmask of DMA_PMD_POOLED, DMA_PMD_DECRYPTED, DMA_PMD_PINNED
+ *		(offset 0), read locklessly by dma_is_pmd_page() and dma_is_pmd_direct().
  * @nr_free:	Number of zeroed available blocks in @free_bitmap
  * @nr_dirty:	Number of dirty available blocks in @dirty_bitmap
  * @map_lock:	Spinlock protecting slow-path updates to @domains_mapped
@@ -138,7 +144,7 @@ enum {
  * physical pages (128 KB per GB of RAM).
  */
 struct dma_pmd_meta {
-	bool pooled;
+	u8 flags;
 	u16 nr_free;
 	u16 nr_dirty;
 	spinlock_t map_lock;
@@ -160,7 +166,7 @@ struct dma_pmd_meta {
 	DECLARE_BITMAP(dirty_bitmap, 1U << PMD_ORDER) ____cacheline_aligned;
 } __aligned(DMA_PMD_META_SIZE);
 
-static_assert(offsetof(struct dma_pmd_meta, pooled) == 0);
+static_assert(offsetof(struct dma_pmd_meta, flags) == 0);
 static_assert(sizeof(struct dma_pmd_meta) == DMA_PMD_META_SIZE);
 
 static inline unsigned int dma_pmd_meta_avail(const struct dma_pmd_meta *m)
include/linux/dma-pmd.h +15 -0
index 7b7e9477d44e1..c9775e86979f9 100644
@@ -16,6 +16,7 @@ struct dma_pmd_pool;
 extern void *dma_pmd_meta_array;
 
 bool __dma_is_pmd_page(unsigned long pfn);
+bool __dma_is_pmd_direct(unsigned long pfn);
 
 static inline bool dma_is_pmd_page(unsigned long pfn)
 {
@@ -29,6 +30,15 @@ static inline bool dma_is_pmd_page(unsigned long pfn)
 	return __dma_is_pmd_page(pfn);
 }
 
+static inline bool dma_is_pmd_direct(phys_addr_t phys)
+{
+	/* Pairs with smp_store_release() in dma_pmd_meta_init(). */
+	if (likely(!smp_load_acquire(&dma_pmd_meta_array)))
+		return false;
+
+	return __dma_is_pmd_direct(phys >> PAGE_SHIFT);
+}
+
 bool __dma_pmd_free_page(struct page *page);
 
 static inline bool dma_pmd_free_page(struct page *page)
@@ -117,6 +127,11 @@ static inline bool dma_is_pmd_page(unsigned long pfn)
 	return false;
 }
 
+static inline bool dma_is_pmd_direct(phys_addr_t phys)
+{
+	return false;
+}
+
 static inline bool dma_pmd_free_page(struct page *page)
 {
 	return false;
kernel/dma/direct.c +5 -1
index da665ca22d5c0..a786c2869b869 100644
@@ -7,6 +7,7 @@
 #include <linux/memblock.h> /* for max_pfn */
 #include <linux/export.h>
 #include <linux/mm.h>
+#include <linux/dma-pmd.h>
 #include <linux/dma-map-ops.h>
 #include <linux/scatterlist.h>
 #include <linux/pfn.h>
@@ -679,7 +680,10 @@ dma_addr_t dma_direct_map_phys(struct device *dev, phys_addr_t phys,
 			attrs |= DMA_ATTR_CC_SHARED;
 	}
 
-	if (is_swiotlb_force_bounce(dev)) {
+	if (dma_is_pmd_direct(phys)) {
+		if (force_dma_unencrypted(dev))
+			attrs |= DMA_ATTR_CC_SHARED;
+	} else if (is_swiotlb_force_bounce(dev)) {
 		if (attrs & (DMA_ATTR_MMIO | DMA_ATTR_REQUIRE_COHERENT))
 			return DMA_MAPPING_ERROR;
 
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#19 lore raw

RFC 15/22 iommu/dma: Add background page scrubber for DMA_PMD pools

In reply to Luigi Rizzo

Add a background scrubber worker (dma_pmd_scrub_work) that zeroes dirty blocks in meta->dirty_bitmap[] and moves them to meta->free_bitmap[], and change __GFP_ZERO (want_init_on_alloc) allocations to take blocks exclusively from free_bitmap[]:

- Remove the per-block memset() and out_prep: loop from dma_pmd_pool_alloc_bulk_node(). When dma_pmd_add_page() allocates a new PMD page for a zeroed request, zero the 2MB page once and place all blocks in free_bitmap[].
- Maintain pool->partial (nr_free > 0, with clean-only pages at head and mixed pages at tail), pool->partial_dirty (nr_free == 0, nr_dirty > 0), and pool->idle (clean pages at head, dirty pages at tail) so both allocation and scrubbing find candidate PMD pages in O(1) time.
- Trigger dma_pmd_scrub_work only when meta->nr_dirty transitions from 0 to 1 on block free (or when a non-zeroed PMD page is added).
- Detach up to DMA_PMD_SCRUB_BATCH (64) dirty blocks under pool->lock, zero them outside the lock, and re-insert them into free_bitmap[].

---
 drivers/iommu/dma-pmd-pool.c | 336 ++++++++++++++++++++++++++++++-----
 drivers/iommu/dma-pmd-priv.h |   9 +-
 2 files changed, 296 insertions(+), 49 deletions(-)
drivers/iommu/dma-pmd-pool.c +289 -47
index deacb6f7d3610..d774cd05347b8 100644
@@ -32,6 +32,8 @@
 
 #include "dma-pmd-priv.h"
 
+#define DMA_PMD_SCRUB_BATCH	64U
+
 /*
  * DMA_PMD pages whose last block has just been freed and which are over the
  * pool's idle watermark are pushed here locklessly for later release.
@@ -66,6 +68,7 @@ static DEFINE_MUTEX(dma_pmd_pools_lock);
 static LLIST_HEAD(dma_pmd_dead_pools);
 
 static void dma_pmd_schedule_reclaim(void);
+static void dma_pmd_schedule_scrub(void);
 
 static void dma_pmd_pool_free_kref(struct kref *kref)
 {
@@ -250,6 +253,216 @@ static void dma_pmd_schedule_reclaim(void)
 		schedule_work(&dma_pmd_reclaim_work);
 }
 
+/*
+ * Background page scrubber
+ * ------------------------
+ * Freed blocks are returned to @meta->dirty_bitmap so __dma_pmd_free_page()
+ * never pays a memset() on the free hot path. Callers that do not require
+ * zeroed memory take dirty blocks first, while callers with __GFP_ZERO (or
+ * init_on_alloc) take pre-zeroed blocks from @meta->free_bitmap.
+ *
+ * The scrubber runs on system_wq to asynchronously convert dirty blocks into
+ * zeroed blocks in @meta->free_bitmap. To avoid holding @pool->lock across
+ * memset(), it detaches up to DMA_PMD_SCRUB_BATCH (64) dirty bits under
+ * @pool->lock, zeroes the pages unlocked (while their bits are clear in both
+ * bitmaps so no allocator or double-free check can race on them), and
+ * republishes them in @meta->free_bitmap under @pool->lock.
+ *
+ * Triggered lazily (without touching any list on every __dma_pmd_free_page()):
+ * when a PMD page transitions from 0 to 1 dirty block, when a page with dirty
+ * blocks becomes completely idle, or when a __GFP_ZERO allocation misses on
+ * clean pages while dirty pages are present.
+ */
+
+/*
+ * Place @meta on the appropriate pool list according to its available clean
+ * (@nr_free) and dirty (@nr_dirty) block counts. Caller must hold @pool->lock
+ * and update @pool->num_idle_pages when moving into or out of @pool->idle.
+ *
+ * List invariants:
+ * - @pool->full:          avail == 0
+ * - @pool->partial:       0 < avail < nr, nr_free > 0
+ *                         (nr_dirty == 0 at head, nr_dirty > 0 at tail)
+ * - @pool->partial_dirty: 0 < avail < nr, nr_free == 0, nr_dirty > 0
+ * - @pool->idle:          avail == nr
+ *                         (nr_dirty == 0 at head, nr_dirty > 0 at tail)
+ */
+static void dma_pmd_place_meta(struct dma_pmd_pool *pool,
+			       struct dma_pmd_meta *meta)
+{
+	unsigned int avail = dma_pmd_meta_avail(meta);
+	unsigned int nr = DMA_PMD_BLOCKS(pool->order);
+
+	if (!avail) {
+		list_move(&meta->list, &pool->full);
+	} else if (avail == nr) {
+		if (!meta->nr_dirty)
+			list_move(&meta->list, &pool->idle);
+		else
+			list_move_tail(&meta->list, &pool->idle);
+	} else if (!meta->nr_free) {
+		list_move_tail(&meta->list, &pool->partial_dirty);
+	} else if (!meta->nr_dirty) {
+		list_move(&meta->list, &pool->partial);
+	} else {
+		list_move_tail(&meta->list, &pool->partial);
+	}
+}
+
+static struct dma_pmd_meta *dma_pmd_pick_dirty_meta(struct dma_pmd_pool *pool)
+{
+	struct dma_pmd_meta *meta;
+
+	meta = list_first_entry_or_null(&pool->partial_dirty,
+					struct dma_pmd_meta, list);
+	if (meta)
+		return meta;
+
+	if (!list_empty(&pool->partial)) {
+		meta = list_last_entry(&pool->partial, struct dma_pmd_meta, list);
+		if (meta->nr_dirty)
+			return meta;
+	}
+
+	if (!list_empty(&pool->idle)) {
+		meta = list_last_entry(&pool->idle, struct dma_pmd_meta, list);
+		if (meta->nr_dirty) {
+			pool->num_idle_pages--;
+			return meta;
+		}
+	}
+
+	return NULL;
+}
+
+/**
+ * dma_pmd_scrub_pool - Scrub one batch of dirty blocks in @pool
+ * @pool: Pool to scrub
+ *
+ * Cost: Zeroes up to DMA_PMD_SCRUB_BATCH blocks (e.g. up to 256 KB for
+ *       order-0) outside @pool->lock; two brief O(batch) bitmap passes under
+ *       @pool->lock.
+ * Locking: Process context. Acquires @pool->lock (irqsave) to detach and
+ *          republish block bits; drops lock during memset().
+ * Frequency: Background worker only (on system_wq).
+ *
+ * Return: true if a batch was scrubbed (more dirty blocks may remain),
+ *         false if @pool has no dirty blocks left or is destroyed.
+ */
+static bool dma_pmd_scrub_pool(struct dma_pmd_pool *pool)
+{
+	unsigned int nr, order, idx, count = 0, used = 0;
+	u16 idxs[DMA_PMD_SCRUB_BATCH];
+	struct dma_pmd_meta *meta;
+	bool should_release = false;
+	unsigned long base_pfn;
+	unsigned long flags;
+
+	spin_lock_irqsave(&pool->lock, flags);
+	if (pool->destroyed) {
+		spin_unlock_irqrestore(&pool->lock, flags);
+		return false;
+	}
+
+	meta = dma_pmd_pick_dirty_meta(pool);
+	if (!meta) {
+		spin_unlock_irqrestore(&pool->lock, flags);
+		return false;
+	}
+
+	order = pool->order;
+	nr = DMA_PMD_BLOCKS(order);
+	base_pfn = dma_pmd_meta_to_pfn(meta);
+
+	for_each_set_bit(idx, meta->dirty_bitmap, nr) {
+		struct page *block = pfn_to_page(base_pfn + (idx << order));
+
+		__clear_bit(idx, meta->dirty_bitmap);
+		used++;
+		if (unlikely(folio_contain_hwpoisoned_page(page_folio(block)))) {
+			pr_err_once("dma_pmd: poisoned block at pfn %lu, leaking it to keep pool %p intact\n",
+				    page_to_pfn(block), pool);
+		} else {
+			idxs[count++] = idx;
+		}
+		if (used == meta->nr_dirty || count == DMA_PMD_SCRUB_BATCH)
+			break;
+	}
+	meta->nr_dirty -= used;
+	dma_pmd_place_meta(pool, meta);
+	spin_unlock_irqrestore(&pool->lock, flags);
+
+	if (unlikely(!count))
+		return used > 0;
+
+	for (idx = 0; idx < count; idx++) {
+		struct page *block = pfn_to_page(base_pfn + (idxs[idx] << order));
+
+		memset(page_address(block), 0, PAGE_SIZE << order);
+	}
+
+	spin_lock_irqsave(&pool->lock, flags);
+	for (idx = 0; idx < count; idx++)
+		__set_bit(idxs[idx], meta->free_bitmap);
+	meta->nr_free += count;
+	pool->block_scrub_cnt += count;
+
+	if (dma_pmd_meta_avail(meta) == nr) {
+		if (pool->destroyed || pool->num_idle_pages >= pool->max_idle_pages) {
+			list_del_init(&meta->list);
+			llist_add(&meta->llnode, &dma_pmd_free_list);
+			should_release = true;
+		} else {
+			pool->num_idle_pages++;
+			dma_pmd_place_meta(pool, meta);
+		}
+	} else if (!pool->destroyed) {
+		dma_pmd_place_meta(pool, meta);
+	}
+	spin_unlock_irqrestore(&pool->lock, flags);
+
+	if (should_release)
+		dma_pmd_schedule_reclaim();
+
+	return true;
+}
+
+/*
+ * Walk all live pools and scrub dirty blocks until every pool is clean.
+ *
+ * Cost: Proportional to total dirty blocks across all pools; yields via
+ *       cond_resched() between batches of DMA_PMD_SCRUB_BATCH blocks.
+ * Locking: Process context (system_wq). Holds @dma_pmd_pools_lock across the
+ *          pool walk.
+ * Frequency: Scheduled on demand via dma_pmd_schedule_scrub(); coalesced by
+ *            work_pending().
+ */
+static void dma_pmd_scrub_work_fn(struct work_struct *work)
+{
+	struct dma_pmd_pool *pool;
+	bool progress;
+
+	do {
+		progress = false;
+		mutex_lock(&dma_pmd_pools_lock);
+		list_for_each_entry(pool, &dma_pmd_pools, node) {
+			while (dma_pmd_scrub_pool(pool)) {
+				progress = true;
+				cond_resched();
+			}
+		}
+		mutex_unlock(&dma_pmd_pools_lock);
+	} while (progress);
+}
+
+static DECLARE_WORK(dma_pmd_scrub_work, dma_pmd_scrub_work_fn);
+
+static void dma_pmd_schedule_scrub(void)
+{
+	if (!work_pending(&dma_pmd_scrub_work))
+		schedule_work(&dma_pmd_scrub_work);
+}
+
 unsigned int dma_pmd_pools_forget_domain(int idx)
 {
 	struct dma_pmd_pool *pool;
@@ -262,6 +475,8 @@ unsigned int dma_pmd_pools_forget_domain(int idx)
 		spin_lock_irqsave(&pool->lock, flags);
 		list_for_each_entry(meta, &pool->partial, list)
 			dropped += dma_pmd_forget_domain(meta, idx);
+		list_for_each_entry(meta, &pool->partial_dirty, list)
+			dropped += dma_pmd_forget_domain(meta, idx);
 		list_for_each_entry(meta, &pool->idle, list)
 			dropped += dma_pmd_forget_domain(meta, idx);
 		list_for_each_entry(meta, &pool->full, list)
@@ -311,6 +526,7 @@ struct dma_pmd_pool *dma_pmd_pool_create(unsigned int order, unsigned int max_id
 	pool->max_idle_pages = max_idle_pages ? : 16;
 	pool->next_alloc_attempt = jiffies;
 	INIT_LIST_HEAD(&pool->partial);
+	INIT_LIST_HEAD(&pool->partial_dirty);
 	INIT_LIST_HEAD(&pool->idle);
 	INIT_LIST_HEAD(&pool->full);
 
@@ -368,6 +584,7 @@ struct dma_pmd_pool *dma_pmd_pool_destroy(struct dma_pmd_pool *pool)
 	}
 	srcu_read_unlock(&dma_pmd_srcu, srcu_idx);
 
+	flush_work(&dma_pmd_scrub_work);
 	kref_put(&pool->refcount, dma_pmd_pool_free_kref);
 	flush_work(&dma_pmd_reclaim_work);
 	return NULL;
@@ -379,6 +596,7 @@ EXPORT_SYMBOL(dma_pmd_pool_destroy);
  * @pool: Owning pool
  * @gfp: GFP allocation flags
  * @nid: Target NUMA node (or NUMA_NO_NODE for local node)
+ * @zero: True if caller requires zeroed blocks in @meta->free_bitmap
  *
  * Cost: Slow path (pool miss); allocates PMD page from buddy on @nid,
  *       splits into compound blocks, and sets the PMD page's membership bit.
@@ -390,7 +608,7 @@ EXPORT_SYMBOL(dma_pmd_pool_destroy);
  *         on failure.
  */
 static struct dma_pmd_meta *dma_pmd_add_page(struct dma_pmd_pool *pool,
-					     gfp_t gfp, int nid)
+					     gfp_t gfp, int nid, bool zero)
 {
 	/*
 	 * Require full GFP_KERNEL (not just gfpflags_allow_blocking()):
@@ -431,7 +649,7 @@ static struct dma_pmd_meta *dma_pmd_add_page(struct dma_pmd_pool *pool,
 	 * is shaped into compound pieces by hand. What is left is also free
 	 * of everything slab treats as a bug in GFP_SLAB_BUG_MASK, so the
 	 * metadata allocation below can use it as it stands.
-	 * __GFP_ZERO is handled per-block in dma_pmd_pool_alloc_bulk_node().
+	 * __GFP_ZERO is handled explicitly below after dma_pmd_page_prepare().
 	 */
 	base_gfp = gfp & ~(__GFP_COMP | __GFP_HIGHMEM | __GFP_MOVABLE | __GFP_ZERO);
 
@@ -487,7 +705,9 @@ static struct dma_pmd_meta *dma_pmd_add_page(struct dma_pmd_pool *pool,
 		return NULL;
 	}
 
-	if (meta->flags & DMA_PMD_DECRYPTED) {
+	if (zero || (meta->flags & DMA_PMD_DECRYPTED)) {
+		if (!(meta->flags & DMA_PMD_DECRYPTED))
+			memset(page_address(page), 0, PMD_SIZE);
 		bitmap_set(meta->free_bitmap, 0, nr);
 		meta->nr_free = nr;
 	} else {
@@ -514,8 +734,7 @@ static struct dma_pmd_meta *dma_pmd_add_page(struct dma_pmd_pool *pool,
 static unsigned int dma_pmd_scan_bitmap(struct dma_pmd_pool *pool,
 					unsigned long *bitmap, u16 *countp,
 					unsigned long base_pfn, unsigned int nr,
-					unsigned long want, struct page **out,
-					bool unfreeze)
+					unsigned long want, struct page **out)
 {
 	unsigned int idx, got = 0, used = 0;
 
@@ -531,8 +750,7 @@ static unsigned int dma_pmd_scan_bitmap(struct dma_pmd_pool *pool,
 			pr_err_once("dma_pmd: poisoned block at pfn %lu, leaking it to keep pool %p intact\n",
 				    page_to_pfn(block), pool);
 		} else {
-			if (unfreeze)
-				page_ref_unfreeze(block, 1);
+			page_ref_unfreeze(block, 1);
 			out[got++] = block;
 		}
 
@@ -544,6 +762,41 @@ static unsigned int dma_pmd_scan_bitmap(struct dma_pmd_pool *pool,
 	return got;
 }
 
+static struct dma_pmd_meta *dma_pmd_pick_meta(struct dma_pmd_pool *pool, bool zero)
+{
+	struct dma_pmd_meta *meta;
+
+	if (!zero) {
+		meta = list_first_entry_or_null(&pool->partial_dirty,
+						struct dma_pmd_meta, list);
+		if (meta)
+			return meta;
+		if (!list_empty(&pool->partial))
+			return list_last_entry(&pool->partial,
+					       struct dma_pmd_meta, list);
+		if (!list_empty(&pool->idle)) {
+			meta = list_last_entry(&pool->idle,
+					       struct dma_pmd_meta, list);
+			pool->num_idle_pages--;
+			return meta;
+		}
+		return NULL;
+	}
+
+	meta = list_first_entry_or_null(&pool->partial, struct dma_pmd_meta, list);
+	if (meta)
+		return meta;
+
+	list_for_each_entry(meta, &pool->idle, list) {
+		if (meta->nr_free) {
+			pool->num_idle_pages--;
+			return meta;
+		}
+	}
+
+	return NULL;
+}
+
 /* Extract up to @want available blocks from @meta under @pool->lock. */
 static unsigned long dma_pmd_take_blocks(struct dma_pmd_pool *pool,
 					 struct dma_pmd_meta *meta,
@@ -555,23 +808,18 @@ static unsigned long dma_pmd_take_blocks(struct dma_pmd_pool *pool,
 	unsigned int nr = DMA_PMD_BLOCKS(pool->order);
 	unsigned int got = 0, used;
 
-	if (zero) {
-		got += dma_pmd_scan_bitmap(pool, meta->free_bitmap, &meta->nr_free,
-					   base_pfn, nr, want, out, true);
+	if (!zero)
 		got += dma_pmd_scan_bitmap(pool, meta->dirty_bitmap, &meta->nr_dirty,
-					   base_pfn, nr, want - got, out + got, false);
-	} else {
-		got += dma_pmd_scan_bitmap(pool, meta->dirty_bitmap, &meta->nr_dirty,
-					   base_pfn, nr, want, out, false);
-		got += dma_pmd_scan_bitmap(pool, meta->free_bitmap, &meta->nr_free,
-					   base_pfn, nr, want - got, out + got, true);
-	}
+					   base_pfn, nr, want, out);
+	got += dma_pmd_scan_bitmap(pool, meta->free_bitmap, &meta->nr_free,
+				   base_pfn, nr, want - got, out + got);
+
 	used = avail_before - dma_pmd_meta_avail(meta);
-	if (!dma_pmd_meta_avail(meta) || WARN_ON_ONCE(!used)) {
+	if (WARN_ON_ONCE(!used)) {
 		meta->nr_free = 0;
 		meta->nr_dirty = 0;
-		list_move(&meta->list, &pool->full);
 	}
+	dma_pmd_place_meta(pool, meta);
 
 	return got;
 }
@@ -588,7 +836,7 @@ static unsigned long dma_pmd_take_blocks(struct dma_pmd_pool *pool,
  *       under a single lock acquisition. Slow path (both empty) calls
  *       dma_pmd_add_page().
  * Locking: Acquires @pool->lock (irqsave) for the bitmap scan. Drops lock
- *          during slow-path PMD buddy allocation and per-block initialization.
+ *          during slow-path PMD buddy allocation.
  * Frequency: High (called per RX buffer refill or per SKB TX page frag refill).
  *
  * A pool hands out a block of a PMD page it already owns, on the node that
@@ -605,7 +853,8 @@ unsigned long dma_pmd_pool_alloc_bulk_node(struct dma_pmd_pool *pool, gfp_t gfp,
 					   int nid, unsigned long nr_pages,
 					   struct page **page_array)
 {
-	unsigned long allocated = 0, flags, i;
+	unsigned long allocated = 0, flags;
+	bool should_scrub = false;
 	bool zero;
 
 	if (unlikely(!pool || pool->destroyed || !nr_pages ||
@@ -619,22 +868,18 @@ unsigned long dma_pmd_pool_alloc_bulk_node(struct dma_pmd_pool *pool, gfp_t gfp,
 	while (allocated < nr_pages) {
 		struct dma_pmd_meta *meta;
 
-		/* Partially used pages first, idle ones next. */
-		meta = list_first_entry_or_null(&pool->partial, struct dma_pmd_meta, list);
-		if (!meta && !list_empty(&pool->idle)) {
-			meta = list_first_entry(&pool->idle, struct dma_pmd_meta, list);
-			list_move(&meta->list, &pool->partial);
-			pool->num_idle_pages--;
-		}
+		meta = dma_pmd_pick_meta(pool, zero);
 		if (!meta) {
 			/* Fallback to a new allocation */
 			spin_unlock_irqrestore(&pool->lock, flags);
-			meta = dma_pmd_add_page(pool, gfp, nid);
+			meta = dma_pmd_add_page(pool, gfp, nid, zero);
 			if (!meta)
-				goto out_prep;
+				goto out;
 			spin_lock_irqsave(&pool->lock, flags);
 			pool->pmd_alloc_cnt++;
 			list_add(&meta->list, &pool->partial);
+			if (meta->nr_dirty)
+				should_scrub = true;
 		}
 
 		allocated += dma_pmd_take_blocks(pool, meta,
@@ -643,14 +888,9 @@ unsigned long dma_pmd_pool_alloc_bulk_node(struct dma_pmd_pool *pool, gfp_t gfp,
 	}
 	spin_unlock_irqrestore(&pool->lock, flags);
 
-out_prep:
-	for (i = 0; i < allocated; i++) {
-		if (!page_count(page_array[i])) {
-			page_ref_unfreeze(page_array[i], 1);
-			if (zero)
-				memset(page_address(page_array[i]), 0, PAGE_SIZE << pool->order);
-		}
-	}
+out:
+	if (should_scrub)
+		dma_pmd_schedule_scrub();
 	return allocated;
 }
 EXPORT_SYMBOL(dma_pmd_pool_alloc_bulk_node);
@@ -674,7 +914,9 @@ EXPORT_SYMBOL(dma_pmd_pool_alloc_bulk_node);
 bool dma_pmd_pool_has_free(struct dma_pmd_pool *pool)
 {
 	return pool && !READ_ONCE(pool->destroyed) &&
-	       (!list_empty_careful(&pool->partial) || !list_empty_careful(&pool->idle));
+	       (!list_empty_careful(&pool->partial) ||
+		!list_empty_careful(&pool->partial_dirty) ||
+		!list_empty_careful(&pool->idle));
 }
 EXPORT_SYMBOL(dma_pmd_pool_has_free);
 
@@ -706,8 +948,8 @@ bool __dma_pmd_free_page(struct page *page)
 	struct dma_pmd_pool *pool = meta->pool;
 	unsigned long pfn = page_to_pfn(page);
 	bool should_release = false;
+	bool should_scrub = false;
 	bool zeroed_on_free = false;
-	unsigned int avail;
 	unsigned long flags;
 
 	idx = (pfn - dma_pmd_meta_to_pfn(meta)) >> pool->order;
@@ -755,28 +997,28 @@ bool __dma_pmd_free_page(struct page *page)
 		meta->nr_free++;
 	} else {
 		__set_bit(idx, meta->dirty_bitmap);
-		meta->nr_dirty++;
+		should_scrub = !meta->nr_dirty++;
 	}
-	avail = dma_pmd_meta_avail(meta);
 	pool->block_free_cnt++;
 
-	if (avail == 1 && !pool->destroyed)
-		list_move(&meta->list, &pool->partial);
-
-	if (avail == nr) {
+	if (dma_pmd_meta_avail(meta) == nr) {
 		if (pool->destroyed || pool->num_idle_pages >= pool->max_idle_pages) {
 			list_del_init(&meta->list);
 			llist_add(&meta->llnode, &dma_pmd_free_list);
 			should_release = true;
 		} else {
-			list_move(&meta->list, &pool->idle);
 			pool->num_idle_pages++;
+			dma_pmd_place_meta(pool, meta);
 		}
+	} else if (!pool->destroyed) {
+		dma_pmd_place_meta(pool, meta);
 	}
 	spin_unlock_irqrestore(&pool->lock, flags);
 
 	if (should_release)
 		dma_pmd_schedule_reclaim();
+	else if (should_scrub)
+		dma_pmd_schedule_scrub();
 
 	return true;
 }
drivers/iommu/dma-pmd-priv.h +7 -2
index 8c7a50d5b7220..82a5c869aa216 100644
@@ -181,8 +181,10 @@ static inline unsigned int dma_pmd_meta_avail(const struct dma_pmd_meta *m)
  *		block bitmaps and the statistics counters
  * @order:	Block order managed by this pool (<= PMD_ORDER)
  * @destroyed:	Set when dma_pmd_pool_destroy() has been called
- * @partial:	List of PMD pages with at least 1 free block, but not all
- *		of them (MRU ordered). Candidates for allocation.
+ * @partial:	List of partially used PMD pages with @nr_free > 0 (clean-only
+ *		at head, mixed clean/dirty at tail)
+ * @partial_dirty: List of partially used PMD pages with @nr_free == 0 and
+ *		@nr_dirty > 0
  * @idle:	List of PMD pages whose every usable block is free. Held
  *		separately because they can be released under pressure.
  * @full:	List of PMD pages with 0 free blocks
@@ -193,6 +195,7 @@ static inline unsigned int dma_pmd_meta_avail(const struct dma_pmd_meta *m)
  * @pmd_free_cnt: Statistics counter of PMD pages released back to buddy
  * @block_alloc_cnt: Statistics counter of block allocations satisfied
  * @block_free_cnt: Statistics counter of block frees recycled into pool
+ * @block_scrub_cnt: Statistics counter of dirty blocks zeroed by scrubber
  * @next_alloc_attempt: Do not attempt a new order-9 allocation before this time.
  *		Damps repeated high-order GFP_ATOMIC failures under
  *		fragmentation, which would otherwise be retried on every
@@ -207,6 +210,7 @@ struct dma_pmd_pool {
 	u8			order;
 	bool			destroyed;
 	struct list_head	partial;
+	struct list_head	partial_dirty;
 	struct list_head	idle;
 	struct list_head	full;
 	unsigned int		num_idle_pages;
@@ -217,6 +221,7 @@ struct dma_pmd_pool {
 	u64			pmd_free_cnt;
 	u64			block_alloc_cnt;
 	u64			block_free_cnt;
+	u64			block_scrub_cnt;
 
 	/* Cold. */
 	unsigned long		next_alloc_attempt;
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#20 lore raw

RFC 16/22 iommu/dma: Add per-NUMA-node PMD page reservoir

In reply to Luigi Rizzo

Add a per-NUMA-node reservoir of pre-allocated, pre-zeroed, and pre-prepared 2MB pages (dma_pmd_reservoirs[MAX_NUMNODES]) refilled in process context by a background worker (dma_pmd_reservoir_work):

- Controlled by dma_pmd.reservoir_max (default 16 PMD pages = 32 MB per N_MEMORY node, subject to the global dma_pmd_max_pages ceiling).
- dma_pmd_add_page() first tries dma_pmd_reservoir_get(nid) (preferring the target NUMA node and falling back to other N_MEMORY nodes), avoiding blocking or failing order-9 buddy allocations on pool misses.
- When a node's reservoir drops to <= reservoir_max / 2 (or on pool creation), dma_pmd_reservoir_work is scheduled to refill in the background.
- Integrate the reservoir with dma_pmd_shrink_count() and dma_pmd_shrink_scan() so reservoir pages are reclaimed first under memory pressure.

---
 drivers/iommu/dma-pmd-pool.c | 307 +++++++++++++++++++++++++++++++----
 1 file changed, 277 insertions(+), 30 deletions(-)
drivers/iommu/dma-pmd-pool.c +277 -30
index d774cd05347b8..d48c8e19741ab 100644
@@ -21,6 +21,7 @@
 #include <linux/mm.h>
 #include <linux/moduleparam.h>
 #include <linux/mutex.h>
+#include <linux/nodemask.h>
 #include <linux/rcupdate.h>
 #include <linux/seq_file.h>
 #include <linux/set_memory.h>
@@ -62,6 +63,18 @@ static atomic_long_t dma_pmd_nr_pages __cacheline_aligned_in_smp;
 static unsigned long dma_pmd_max_pages __read_mostly;
 core_param(dma_pmd_max_pages, dma_pmd_max_pages, ulong, 0644);
 
+/* Target number of pre-allocated PMD pages per NUMA node in reservoir. */
+static unsigned int dma_pmd_reservoir_max __read_mostly = 16;
+module_param_named(reservoir_max, dma_pmd_reservoir_max, uint, 0644);
+
+struct dma_pmd_reservoir {
+	spinlock_t		lock;	/* protects @pages and @nr_pages */
+	struct list_head	pages;
+	unsigned int		nr_pages;
+};
+
+static struct dma_pmd_reservoir dma_pmd_reservoirs[MAX_NUMNODES];
+
 /* All live pools. */
 static LIST_HEAD(dma_pmd_pools);
 static DEFINE_MUTEX(dma_pmd_pools_lock);
@@ -69,6 +82,7 @@ static LLIST_HEAD(dma_pmd_dead_pools);
 
 static void dma_pmd_schedule_reclaim(void);
 static void dma_pmd_schedule_scrub(void);
+static void dma_pmd_schedule_reservoir(void);
 
 static void dma_pmd_pool_free_kref(struct kref *kref)
 {
@@ -81,8 +95,10 @@ static void dma_pmd_pool_free_kref(struct kref *kref)
 static int dma_pmd_page_prepare(struct page *page, struct dma_pmd_meta *meta,
 				bool can_block)
 {
-	bool want_decrypt = READ_ONCE(dma_pmd_decrypt);
-	bool want_pin = READ_ONCE(dma_pmd_pin);
+	bool want_decrypt = READ_ONCE(dma_pmd_decrypt) &&
+			    !(meta->flags & DMA_PMD_DECRYPTED);
+	bool want_pin = READ_ONCE(dma_pmd_pin) &&
+			!(meta->flags & DMA_PMD_PINNED);
 	void *vaddr = page_address(page);
 	int ret;
 
@@ -142,6 +158,16 @@ static int dma_pmd_page_unprepare(struct dma_pmd_meta *meta)
 	return 0;
 }
 
+static void dma_pmd_free_reservoir_page(struct dma_pmd_meta *meta)
+{
+	struct page *page = pfn_to_page(dma_pmd_meta_to_pfn(meta));
+
+	if (!dma_pmd_page_unprepare(meta)) {
+		__free_pages(page, PMD_ORDER);
+		atomic_long_dec(&dma_pmd_nr_pages);
+	}
+}
+
 /*
  * Releasing an idle PMD page proceeds in three stages:
  *
@@ -226,8 +252,12 @@ static void dma_pmd_reclaim_work_fn(struct work_struct *work)
 	struct dma_pmd_pool *pool, *ptmp;
 	struct dma_pmd_meta *meta, *tmp;
 
-	llist_for_each_entry_safe(meta, tmp, node, llnode)
-		dma_pmd_release_page(meta);
+	llist_for_each_entry_safe(meta, tmp, node, llnode) {
+		if (meta->pool)
+			dma_pmd_release_page(meta);
+		else
+			dma_pmd_free_reservoir_page(meta);
+	}
 
 	node = llist_del_all(&dma_pmd_dead_pools);
 	if (node) {
@@ -463,6 +493,186 @@ static void dma_pmd_schedule_scrub(void)
 		schedule_work(&dma_pmd_scrub_work);
 }
 
+/*
+ * Per-NUMA-node PMD page reservoir
+ * --------------------------------
+ * Order-9 (2MB) buddy allocations can compact/reclaim and fail or stall in
+ * atomic context (such as NAPI RX refill or softirq TX), and CoCo decryption /
+ * hypervisor pinning cannot run in atomic context at all.
+ *
+ * Each NUMA node maintains a small reservoir of up to @dma_pmd_reservoir_max
+ * (default 8 = 16 MB/node) pre-allocated, pre-zeroed, and pre-decrypted/pinned
+ * PMD pages. On a pool miss, dma_pmd_add_page() pops a ready PMD page from the
+ * target node's reservoir in O(1) under a spinlock (falling back to other
+ * nodes before calling alloc_pages_node() directly).
+ *
+ * A background worker on system_wq refills nodes whenever a node's count drops
+ * to or below half of @dma_pmd_reservoir_max, on a reservoir miss, or when a
+ * new pool is created. Pages held in the reservoir count toward the global
+ * @dma_pmd_nr_pages budget and are reclaimable by the shrinker under memory
+ * pressure.
+ */
+
+/**
+ * dma_pmd_reservoir_refill_node - Refill node @nid's reservoir up to @max
+ * @nid: NUMA node ID
+ * @max: Target number of PMD pages to hold in @nid's reservoir
+ *
+ * Cost: Slow path; allocates order-9 pages with GFP_KERNEL | __GFP_RETRY_MAYFAIL,
+ *       populates metadata, decrypts/pins if configured, and zeroes 2MB per page.
+ * Locking: Process context (system_wq); sleeps during buddy allocation, CPA
+ *          decryption, and cond_resched(). Takes @res->lock briefly to enqueue.
+ * Frequency: Rare (when reservoir drops to <= @max / 2 or on pool creation).
+ */
+static void dma_pmd_reservoir_refill_node(int nid, unsigned int max)
+{
+	gfp_t gfp = GFP_KERNEL | __GFP_THISNODE | __GFP_NOWARN | __GFP_RETRY_MAYFAIL;
+	struct dma_pmd_reservoir *res = &dma_pmd_reservoirs[nid];
+
+	while (READ_ONCE(res->nr_pages) < max) {
+		struct dma_pmd_meta *meta;
+		unsigned long flags;
+		struct page *page;
+
+		if (atomic_long_inc_return(&dma_pmd_nr_pages) >
+		    READ_ONCE(dma_pmd_max_pages)) {
+			atomic_long_dec(&dma_pmd_nr_pages);
+			break;
+		}
+
+		page = alloc_pages_node(nid, gfp, PMD_ORDER);
+		if (!page) {
+			atomic_long_dec(&dma_pmd_nr_pages);
+			break;
+		}
+
+		if (unlikely(!dma_pmd_meta_ensure_pfn(page_to_pfn(page), true))) {
+			__free_pages(page, PMD_ORDER);
+			atomic_long_dec(&dma_pmd_nr_pages);
+			break;
+		}
+
+		meta = dma_pmd_meta_of_pfn(page_to_pfn(page));
+		memset(meta, 0, sizeof(*meta));
+		spin_lock_init(&meta->map_lock);
+
+		if (dma_pmd_page_prepare(page, meta, true)) {
+			__free_pages(page, PMD_ORDER);
+			atomic_long_dec(&dma_pmd_nr_pages);
+			break;
+		}
+
+		if (!(meta->flags & DMA_PMD_DECRYPTED))
+			memset(page_address(page), 0, PMD_SIZE);
+
+		spin_lock_irqsave(&res->lock, flags);
+		list_add(&meta->list, &res->pages);
+		res->nr_pages++;
+		spin_unlock_irqrestore(&res->lock, flags);
+
+		cond_resched();
+	}
+}
+
+static void dma_pmd_reservoir_work_fn(struct work_struct *work)
+{
+	unsigned int max = READ_ONCE(dma_pmd_reservoir_max);
+	int nid;
+
+	if (!max || !dma_pmd_meta_base())
+		return;
+
+	for_each_node_state(nid, N_MEMORY)
+		dma_pmd_reservoir_refill_node(nid, max);
+}
+
+static DECLARE_WORK(dma_pmd_reservoir_work, dma_pmd_reservoir_work_fn);
+
+static void dma_pmd_schedule_reservoir(void)
+{
+	if (READ_ONCE(dma_pmd_reservoir_max) &&
+	    !work_pending(&dma_pmd_reservoir_work))
+		schedule_work(&dma_pmd_reservoir_work);
+}
+
+/*
+ * Pop one pre-prepared PMD page from node @nid's reservoir.
+ *
+ * Cost: O(1) list pop under @res->lock.
+ * Locking: Acquires @res->lock (irqsave). Safe from any context (IRQ, softirq,
+ *          process). Never sleeps.
+ * Frequency: Only on pool miss (dma_pmd_add_page()).
+ */
+static struct dma_pmd_meta *dma_pmd_reservoir_pop_node(int nid, unsigned int max)
+{
+	struct dma_pmd_reservoir *res = &dma_pmd_reservoirs[nid];
+	struct dma_pmd_meta *meta;
+	unsigned long flags;
+	bool refill = false;
+
+	if (!READ_ONCE(res->nr_pages))
+		return NULL;
+
+	spin_lock_irqsave(&res->lock, flags);
+	meta = list_first_entry_or_null(&res->pages, struct dma_pmd_meta, list);
+	if (meta) {
+		list_del_init(&meta->list);
+		res->nr_pages--;
+		refill = res->nr_pages <= max / 2;
+	}
+	spin_unlock_irqrestore(&res->lock, flags);
+
+	if (refill)
+		dma_pmd_schedule_reservoir();
+
+	return meta;
+}
+
+/**
+ * dma_pmd_reservoir_get - Obtain a pre-prepared PMD page, preferring @nid
+ * @nid: Preferred NUMA node (or NUMA_NO_NODE for local node)
+ *
+ * Tries @nid's reservoir first, then falls back to other memory nodes and
+ * schedules an async refill if a fallback or empty reservoir is encountered.
+ *
+ * Cost: O(1) on local node hit; O(MAX_NUMNODES) lockless checks on miss.
+ * Locking: Acquires @res->lock (irqsave) on non-empty node. Safe from any
+ *          context. Never sleeps.
+ * Frequency: Only on pool miss (dma_pmd_add_page()).
+ *
+ * Return: Metadata pointer of a ready PMD page (not yet compound-split or
+ *         bound to a pool), or NULL if all reservoirs are empty.
+ */
+static struct dma_pmd_meta *dma_pmd_reservoir_get(int nid)
+{
+	unsigned int max = READ_ONCE(dma_pmd_reservoir_max);
+	struct dma_pmd_meta *meta;
+	int target_nid, n;
+
+	if (!max)
+		return NULL;
+
+	target_nid = (nid == NUMA_NO_NODE) ? numa_mem_id() : nid;
+	if (target_nid >= 0 && target_nid < MAX_NUMNODES) {
+		meta = dma_pmd_reservoir_pop_node(target_nid, max);
+		if (meta)
+			return meta;
+	}
+
+	for_each_node_state(n, N_MEMORY) {
+		if (n == target_nid)
+			continue;
+		meta = dma_pmd_reservoir_pop_node(n, max);
+		if (meta) {
+			dma_pmd_schedule_reservoir();
+			return meta;
+		}
+	}
+
+	dma_pmd_schedule_reservoir();
+	return NULL;
+}
+
 unsigned int dma_pmd_pools_forget_domain(int idx)
 {
 	struct dma_pmd_pool *pool;
@@ -538,6 +748,7 @@ struct dma_pmd_pool *dma_pmd_pool_create(unsigned int order, unsigned int max_id
 	}
 	list_add(&pool->node, &dma_pmd_pools);
 	mutex_unlock(&dma_pmd_pools_lock);
+	dma_pmd_schedule_reservoir();
 
 	return pool;
 }
@@ -616,10 +827,18 @@ static struct dma_pmd_meta *dma_pmd_add_page(struct dma_pmd_pool *pool,
 	 */
 	bool can_block = (gfp & GFP_KERNEL) == GFP_KERNEL;
 	unsigned int nr = DMA_PMD_BLOCKS(pool->order);
+	bool from_reservoir = false;
 	struct dma_pmd_meta *meta;
 	gfp_t alloc_gfp, base_gfp;
 	struct page *page;
 
+	meta = dma_pmd_reservoir_get(nid);
+	if (meta) {
+		page = pfn_to_page(dma_pmd_meta_to_pfn(meta));
+		from_reservoir = true;
+		goto prepare;
+	}
+
 	/*
 	 * A high-order allocation is expensive when it fails, and under fragmentation
 	 * it fails on every pool miss. For GFP_ATOMIC, back off briefly.
@@ -687,9 +906,10 @@ static struct dma_pmd_meta *dma_pmd_add_page(struct dma_pmd_pool *pool,
 
 	meta = dma_pmd_meta_of_pfn(page_to_pfn(page));
 	memset(meta, 0, sizeof(*meta));
-	meta->pool = pool;
 	spin_lock_init(&meta->map_lock);
 
+prepare:
+	meta->pool = pool;
 	if (dma_pmd_page_prepare(page, meta, can_block)) {
 		__free_pages(page, PMD_ORDER);
 		atomic_long_dec(&dma_pmd_nr_pages);
@@ -705,8 +925,8 @@ static struct dma_pmd_meta *dma_pmd_add_page(struct dma_pmd_pool *pool,
 		return NULL;
 	}
 
-	if (zero || (meta->flags & DMA_PMD_DECRYPTED)) {
-		if (!(meta->flags & DMA_PMD_DECRYPTED))
+	if (from_reservoir || zero || (meta->flags & DMA_PMD_DECRYPTED)) {
+		if (!from_reservoir && !(meta->flags & DMA_PMD_DECRYPTED))
 			memset(page_address(page), 0, PMD_SIZE);
 		bitmap_set(meta->free_bitmap, 0, nr);
 		meta->nr_free = nr;
@@ -1042,14 +1262,17 @@ static unsigned long dma_pmd_shrink_count(struct shrinker *shrink,
 {
 	struct dma_pmd_pool *pool;
 	unsigned long nr = 0;
+	int nid;
 
-	if (!mutex_trylock(&dma_pmd_pools_lock))
-		return 0;
+	for_each_node_state(nid, N_MEMORY)
+		nr += READ_ONCE(dma_pmd_reservoirs[nid].nr_pages);
 
-	list_for_each_entry(pool, &dma_pmd_pools, node)
-		nr += READ_ONCE(pool->num_idle_pages);
+	if (mutex_trylock(&dma_pmd_pools_lock)) {
+		list_for_each_entry(pool, &dma_pmd_pools, node)
+			nr += READ_ONCE(pool->num_idle_pages);
 
-	mutex_unlock(&dma_pmd_pools_lock);
+		mutex_unlock(&dma_pmd_pools_lock);
+	}
 
 	return nr << PMD_ORDER;
 }
@@ -1062,34 +1285,50 @@ static unsigned long dma_pmd_shrink_scan(struct shrinker *shrink,
 	unsigned long freed = 0;
 	LIST_HEAD(release_list);
 	unsigned long flags;
-	int srcu_idx;
+	int srcu_idx, nid;
 
-	if (!mutex_trylock(&dma_pmd_pools_lock))
-		return SHRINK_STOP;
+	for_each_node_state(nid, N_MEMORY) {
+		struct dma_pmd_reservoir *res = &dma_pmd_reservoirs[nid];
 
-	srcu_idx = srcu_read_lock(&dma_pmd_srcu);
-	list_for_each_entry(pool, &dma_pmd_pools, node) {
-		/*
-		 * Every PMD page on @idle is a candidate, so this detaches one
-		 * per iteration and stops as soon as the reclaim path has
-		 * what it asked for: the IRQs-off section is bounded by the
-		 * work done, not by how many PMD pages the pool holds.
-		 */
-		spin_lock_irqsave(&pool->lock, flags);
-		list_for_each_entry_safe(meta, tmp, &pool->idle, list) {
+		if (!READ_ONCE(res->nr_pages))
+			continue;
+		spin_lock_irqsave(&res->lock, flags);
+		list_for_each_entry_safe(meta, tmp, &res->pages, list) {
 			if (freed >= sc->nr_to_scan)
 				break;
 			list_move(&meta->list, &release_list);
-			pool->num_idle_pages--;
+			res->nr_pages--;
 			freed += 1UL << PMD_ORDER;
 		}
-		spin_unlock_irqrestore(&pool->lock, flags);
-
+		spin_unlock_irqrestore(&res->lock, flags);
 		if (freed >= sc->nr_to_scan)
 			break;
 	}
 
-	mutex_unlock(&dma_pmd_pools_lock);
+	srcu_idx = srcu_read_lock(&dma_pmd_srcu);
+	if (freed < sc->nr_to_scan && mutex_trylock(&dma_pmd_pools_lock)) {
+		list_for_each_entry(pool, &dma_pmd_pools, node) {
+			/*
+			 * Every PMD page on @idle is a candidate, so this detaches one
+			 * per iteration and stops as soon as the reclaim path has
+			 * what it asked for: the IRQs-off section is bounded by the
+			 * work done, not by how many PMD pages the pool holds.
+			 */
+			spin_lock_irqsave(&pool->lock, flags);
+			list_for_each_entry_safe(meta, tmp, &pool->idle, list) {
+				if (freed >= sc->nr_to_scan)
+					break;
+				list_move(&meta->list, &release_list);
+				pool->num_idle_pages--;
+				freed += 1UL << PMD_ORDER;
+			}
+			spin_unlock_irqrestore(&pool->lock, flags);
+
+			if (freed >= sc->nr_to_scan)
+				break;
+		}
+		mutex_unlock(&dma_pmd_pools_lock);
+	}
 
 	/*
 	 * Retiring is done outside both locks: dma_pmd_release_page() unmaps
@@ -1103,8 +1342,10 @@ static unsigned long dma_pmd_shrink_scan(struct shrinker *shrink,
 		if (meta->flags & (DMA_PMD_DECRYPTED | DMA_PMD_PINNED)) {
 			llist_add(&meta->llnode, &dma_pmd_free_list);
 			dma_pmd_schedule_reclaim();
-		} else {
+		} else if (meta->pool) {
 			dma_pmd_release_page(meta);
+		} else {
+			dma_pmd_free_reservoir_page(meta);
 		}
 	}
 	srcu_read_unlock(&dma_pmd_srcu, srcu_idx);
@@ -1128,6 +1369,12 @@ static unsigned long dma_pmd_shrink_scan(struct shrinker *shrink,
 static int __init dma_pmd_init(void)
 {
 	struct shrinker *shrink;
+	int nid;
+
+	for (nid = 0; nid < MAX_NUMNODES; nid++) {
+		spin_lock_init(&dma_pmd_reservoirs[nid].lock);
+		INIT_LIST_HEAD(&dma_pmd_reservoirs[nid].pages);
+	}
 
 	/*
 	 * Hard ceiling on memory diverted from the buddy allocator into 2MB
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#21 lore raw

RFC 17/22 net/gve: Use DMA_PMD memory for RX buffers

In reply to Luigi Rizzo

When dev->dma_pmd_rxbuf is enabled, back GQI-RDA RX packet buffers with a per-queue DMA_PMD page pool (rx->dma_pmd_pool); DQO-RDA uses page_pool, which checks dev->dma_pmd_rxbuf directly.

---
 drivers/net/ethernet/google/gve/gve.h      |  2 +
 drivers/net/ethernet/google/gve/gve_main.c |  5 ++
 drivers/net/ethernet/google/gve/gve_rx.c   | 61 ++++++++++++++++------
 3 files changed, 53 insertions(+), 15 deletions(-)
drivers/net/ethernet/google/gve/gve.h +2 -0
index c280ff35ee771..11330404f681b 100644
@@ -10,6 +10,7 @@
 #include <linux/dma-mapping.h>
 #include <linux/dmapool.h>
 #include <linux/ethtool_netlink.h>
+#include <linux/dma-pmd.h>
 #include <linux/netdevice.h>
 #include <linux/net_tstamp.h>
 #include <linux/pci.h>
@@ -258,6 +259,7 @@ struct gve_rx_ring {
 			u32 qpl_copy_pool_mask;
 			u32 qpl_copy_pool_head;
 			struct gve_rx_slot_page_info *qpl_copy_pool;
+			struct dma_pmd_pool *dma_pmd_pool;
 		};
 
 		/* DQO fields. */
drivers/net/ethernet/google/gve/gve_main.c +5 -0
index 9cc343a162712..e5631987b050f 100644
@@ -1055,6 +1055,11 @@ static int gve_queues_mem_alloc(struct gve_priv *priv,
 	if (err)
 		goto free_tx;
 
+	if (rx_alloc_cfg->raw_addressing && priv->pdev->dev.dma_pmd_rxbuf)
+		dev_info(&priv->pdev->dev,
+			 "DMA_PMD rx_bufs pool: enabled on %u RX queue(s)\n",
+			 rx_alloc_cfg->qcfg_rx->num_queues);
+
 	return 0;
 
 free_tx:
drivers/net/ethernet/google/gve/gve_rx.c +46 -15

130 lines not on this page · raw message

Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#22 lore raw

RFC 18/22 net/gve: Use DMA_PMD memory for tx header bounce buffers

In reply to Luigi Rizzo

When dev->dma_pmd_tx_hdrs is enabled, allocate a MAX_TCP_HEADER bounce buffer per TX slot/packet out of the DMA_PMD arena in raw-addressing mode (both GQI and DQO). When skb_headlen(skb) <= MAX_TCP_HEADER, the linear portion is copied into the pre-mapped bounce buffer instead of calling dma_map_single()/dma_unmap_single() on every packet.

---
 drivers/net/ethernet/google/gve/gve.h        |  3 ++
 drivers/net/ethernet/google/gve/gve_tx.c     | 38 ++++++++++++++---
 drivers/net/ethernet/google/gve/gve_tx_dqo.c | 45 +++++++++++++++-----
 3 files changed, 69 insertions(+), 17 deletions(-)
drivers/net/ethernet/google/gve/gve.h +3 -0
index 11330404f681b..00e438fe05a50 100644
@@ -18,6 +18,7 @@
 #include <linux/ptp_clock_kernel.h>
 #include <linux/u64_stats_sync.h>
 #include <net/page_pool/helpers.h>
+#include <net/tcp.h>
 #include <net/xdp.h>
 
 #include "gve_desc.h"
@@ -642,6 +643,8 @@ struct gve_tx_ring {
 			};
 		} dqo;
 	} ____cacheline_aligned;
+	void *tx_hdr_bufs;
+	dma_addr_t tx_hdr_bufs_dma;
 	struct netdev_queue *netdev_txq;
 	struct gve_queue_resources *q_resources; /* head and tail pointer idx */
 	struct device *dev;
drivers/net/ethernet/google/gve/gve_tx.c +32 -6
index 79338fd9bf66e..9610b54ef4792 100644
@@ -224,6 +224,11 @@ static void gve_tx_free_ring_gqi(struct gve_priv *priv, struct gve_tx_ring *tx,
 	u32 slots;
 
 	slots = tx->mask + 1;
+	if (tx->tx_hdr_bufs) {
+		dma_free_coherent(hdev, slots * MAX_TCP_HEADER,
+				  tx->tx_hdr_bufs, tx->tx_hdr_bufs_dma);
+		tx->tx_hdr_bufs = NULL;
+	}
 	dma_free_coherent(hdev, sizeof(*tx->q_resources),
 			  tx->q_resources, tx->q_resources_bus);
 	tx->q_resources = NULL;
@@ -298,6 +303,11 @@ static int gve_tx_alloc_ring_gqi(struct gve_priv *priv,
 		/* map Tx FIFO */
 		if (gve_tx_fifo_init(priv, &tx->tx_fifo))
 			goto abort_with_qpl;
+	} else if (hdev->dma_pmd_tx_hdrs) {
+		tx->tx_hdr_bufs = dma_alloc_coherent(hdev,
+						     cfg->ring_size * MAX_TCP_HEADER,
+						     &tx->tx_hdr_bufs_dma,
+						     GFP_KERNEL);
 	}
 
 	tx->q_resources =
@@ -311,6 +321,12 @@ static int gve_tx_alloc_ring_gqi(struct gve_priv *priv,
 	return 0;
 
 abort_with_fifo:
+	if (tx->tx_hdr_bufs) {
+		dma_free_coherent(hdev,
+				  cfg->ring_size * MAX_TCP_HEADER,
+				  tx->tx_hdr_bufs, tx->tx_hdr_bufs_dma);
+		tx->tx_hdr_bufs = NULL;
+	}
 	if (!tx->raw_addressing)
 		gve_tx_fifo_release(priv, &tx->tx_fifo);
 abort_with_qpl:
@@ -423,6 +439,8 @@ static inline int gve_skb_fifo_bytes_required(struct gve_tx_ring *tx,
 #define MAX_TX_DESC_NEEDED	(MAX_SKB_FRAGS + 4)
 static void gve_tx_unmap_buf(struct device *dev, struct gve_tx_buffer_state *info)
 {
+	if (!dma_unmap_len(info, len))
+		return;
 	if (info->skb) {
 		dma_unmap_single(dev, dma_unmap_addr(info, dma),
 				 dma_unmap_len(info, len),
@@ -657,13 +675,21 @@ static int gve_tx_add_skb_no_copy(struct gve_priv *priv, struct gve_tx_ring *tx,
 
 	info->skb =  skb;
 
-	addr = dma_map_single(tx->dev, skb->data, len, DMA_TO_DEVICE);
-	if (unlikely(dma_mapping_error(tx->dev, addr))) {
-		tx->dma_mapping_error++;
-		goto drop;
+	if (tx->tx_hdr_bufs && len <= MAX_TCP_HEADER) {
+		u32 hdr_off = idx * MAX_TCP_HEADER;
+
+		memcpy(tx->tx_hdr_bufs + hdr_off, skb->data, len);
+		addr = tx->tx_hdr_bufs_dma + hdr_off;
+		dma_unmap_len_set(info, len, 0);
+	} else {
+		addr = dma_map_single(tx->dev, skb->data, len, DMA_TO_DEVICE);
+		if (unlikely(dma_mapping_error(tx->dev, addr))) {
+			tx->dma_mapping_error++;
+			goto drop;
+		}
+		dma_unmap_len_set(info, len, len);
+		dma_unmap_addr_set(info, dma, addr);
 	}
-	dma_unmap_len_set(info, len, len);
-	dma_unmap_addr_set(info, dma, addr);
 
 	num_descriptors = 1 + shinfo->nr_frags;
 	if (hlen < len)
drivers/net/ethernet/google/gve/gve_tx_dqo.c +34 -11

76 lines not on this page · raw message

Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#23 lore raw

RFC 19/22 net/mlx5e: Use DMA_PMD memory for tx header bounce buffers

In reply to Luigi Rizzo

When dev->dma_pmd_tx_hdrs is enabled, allocate a MAX_TCP_HEADER bounce buffer per TX DMA FIFO slot out of the DMA_PMD arena. When the linear portion of a transmitted packet is at most MAX_TCP_HEADER bytes, copy it into the pre-mapped bounce buffer instead of calling dma_map_single()/dma_unmap_single() on every packet.

---
 drivers/net/ethernet/mellanox/mlx5/core/en.h  |  2 ++
 .../net/ethernet/mellanox/mlx5/core/en/txrx.h |  4 ++-
 .../net/ethernet/mellanox/mlx5/core/en_main.c | 14 ++++++++++
 .../net/ethernet/mellanox/mlx5/core/en_tx.c   | 28 +++++++++++++++----
 4 files changed, 42 insertions(+), 6 deletions(-)
drivers/net/ethernet/mellanox/mlx5/core/en.h +2 -0
index a3945195f454e..d762ad1c1ffaf 100644
@@ -442,6 +442,8 @@ struct mlx5e_txqsq {
 		struct mlx5e_sq_dma       *dma_fifo;
 		struct mlx5e_skb_fifo      skb_fifo;
 		struct mlx5e_tx_wqe_info  *wqe_info;
+		void                      *tx_hdr_bufs;
+		dma_addr_t                 tx_hdr_bufs_dma;
 	} db;
 	void __iomem              *uar_map;
 	struct netdev_queue       *txq;
drivers/net/ethernet/mellanox/mlx5/core/en/txrx.h +3 -1
index f2a8453d8dce0..6de7a2a430d72 100644
@@ -365,7 +365,9 @@ mlx5e_tx_dma_unmap(struct device *pdev, struct mlx5e_sq_dma *dma)
 {
 	switch (dma->type) {
 	case MLX5E_DMA_MAP_SINGLE:
-		dma_unmap_single(pdev, dma->addr, dma->size, DMA_TO_DEVICE);
+		if (dma->size)
+			dma_unmap_single(pdev, dma->addr, dma->size,
+					 DMA_TO_DEVICE);
 		break;
 	case MLX5E_DMA_MAP_PAGE:
 		netmem_dma_unmap_page_attrs(pdev, dma->addr, dma->size,
drivers/net/ethernet/mellanox/mlx5/core/en_main.c +14 -0
index 4c6060d54fbed..efd766aa43a02 100644
@@ -1666,6 +1666,13 @@ static void mlx5e_free_icosq(struct mlx5e_icosq *sq)
 
 void mlx5e_free_txqsq_db(struct mlx5e_txqsq *sq)
 {
+	if (sq->db.tx_hdr_bufs) {
+		int wq_sz = mlx5_wq_cyc_get_size(&sq->wq);
+		int df_sz = wq_sz * MLX5_SEND_WQEBB_NUM_DS;
+
+		dma_free_coherent(sq->pdev, df_sz * MAX_TCP_HEADER,
+				  sq->db.tx_hdr_bufs, sq->db.tx_hdr_bufs_dma);
+	}
 	kvfree(sq->db.wqe_info);
 	kvfree(sq->db.skb_fifo.fifo);
 	kvfree(sq->db.dma_fifo);
@@ -1690,6 +1697,13 @@ int mlx5e_alloc_txqsq_db(struct mlx5e_txqsq *sq, int numa)
 		return -ENOMEM;
 	}
 
+	if (sq->pdev->dma_pmd_tx_hdrs)
+		sq->db.tx_hdr_bufs =
+			dma_alloc_coherent(sq->pdev,
+					   df_sz * MAX_TCP_HEADER,
+					   &sq->db.tx_hdr_bufs_dma,
+					   GFP_KERNEL | __GFP_NOWARN);
+
 	sq->dma_fifo_mask = df_sz - 1;
 
 	sq->db.skb_fifo.pc   = &sq->skb_fifo_pc;
drivers/net/ethernet/mellanox/mlx5/core/en_tx.c +23 -5
index 0b5e600e4a6a9..3b6a7a8b0128e 100644
@@ -177,6 +177,27 @@ mlx5e_tx_get_gso_ihs(struct mlx5e_txqsq *sq, struct sk_buff *skb)
 	return ihs;
 }
 
+static inline dma_addr_t
+mlx5e_tx_map_hdr(struct mlx5e_txqsq *sq, unsigned char *data, u32 len)
+{
+	dma_addr_t dma_addr;
+
+	if (sq->db.tx_hdr_bufs && len <= MAX_TCP_HEADER) {
+		u32 off = (sq->dma_fifo_pc & sq->dma_fifo_mask) *
+			  MAX_TCP_HEADER;
+
+		memcpy(sq->db.tx_hdr_bufs + off, data, len);
+		dma_addr = sq->db.tx_hdr_bufs_dma + off;
+		mlx5e_dma_push_single(sq, dma_addr, 0);
+		return dma_addr;
+	}
+
+	dma_addr = dma_map_single(sq->pdev, data, len, DMA_TO_DEVICE);
+	if (likely(!dma_mapping_error(sq->pdev, dma_addr)))
+		mlx5e_dma_push_single(sq, dma_addr, len);
+	return dma_addr;
+}
+
 static inline int
 mlx5e_txwqe_build_dsegs(struct mlx5e_txqsq *sq, struct sk_buff *skb,
 			unsigned char *skb_data, u16 headlen,
@@ -187,8 +208,7 @@ mlx5e_txwqe_build_dsegs(struct mlx5e_txqsq *sq, struct sk_buff *skb,
 	int i;
 
 	if (headlen) {
-		dma_addr = dma_map_single(sq->pdev, skb_data, headlen,
-					  DMA_TO_DEVICE);
+		dma_addr = mlx5e_tx_map_hdr(sq, skb_data, headlen);
 		if (unlikely(dma_mapping_error(sq->pdev, dma_addr)))
 			goto dma_unmap_wqe_err;
 
@@ -196,7 +216,6 @@ mlx5e_txwqe_build_dsegs(struct mlx5e_txqsq *sq, struct sk_buff *skb,
 		dseg->lkey       = sq->mkey_be;
 		dseg->byte_count = cpu_to_be32(headlen);
 
-		mlx5e_dma_push_single(sq, dma_addr, headlen);
 		num_dma++;
 		dseg++;
 	}
@@ -578,7 +597,7 @@ mlx5e_sq_xmit_mpwqe(struct mlx5e_txqsq *sq, struct sk_buff *skb,
 	txd.data = skb->data;
 	txd.len = skb->len;
 
-	txd.dma_addr = dma_map_single(sq->pdev, txd.data, txd.len, DMA_TO_DEVICE);
+	txd.dma_addr = mlx5e_tx_map_hdr(sq, txd.data, txd.len);
 	if (unlikely(dma_mapping_error(sq->pdev, txd.dma_addr)))
 		goto err_unmap;
 
@@ -591,7 +610,6 @@ mlx5e_sq_xmit_mpwqe(struct mlx5e_txqsq *sq, struct sk_buff *skb,
 
 	sq->stats->xmit_more += xmit_more;
 
-	mlx5e_dma_push_single(sq, txd.dma_addr, txd.len);
 	mlx5e_skb_fifo_push(&sq->db.skb_fifo, skb);
 	mlx5e_tx_mpwqe_add_dseg(sq, &txd);
 	mlx5e_tx_skb_update_ts_flags(skb);
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#24 lore raw

Re: [RFC: DMA_PMD 19/22] net/mlx5e: Use DMA_PMD memory for tx header bounce buffers

Quoted 6 lines · Luigi Rizzo

When dev->dma_pmd_tx_hdrs is enabled, allocate a MAX_TCP_HEADER bounce buffer per TX DMA FIFO slot out of the DMA_PMD arena. When the linear portion of a transmitted packet is at most MAX_TCP_HEADER bytes, copy it into the pre-mapped bounce buffer instead of calling dma_map_single()/dma_unmap_single() on every packet.

What is the difference between using the DMA_PMD pool or one (or a few) coherent DMA (2MB) buffers allocated by the driver?

Quoted 13 lines
---
 drivers/net/ethernet/mellanox/mlx5/core/en.h  |  2 ++
 .../net/ethernet/mellanox/mlx5/core/en/txrx.h |  4 ++-
 .../net/ethernet/mellanox/mlx5/core/en_main.c | 14 ++++++++++
 .../net/ethernet/mellanox/mlx5/core/en_tx.c   | 28 +++++++++++++++----
 4 files changed, 42 insertions(+), 6 deletions(-)
drivers/net/ethernet/mellanox/mlx5/core/en.h +0 -0
index a3945195f454e..d762ad1c1ffaf 100644

drivers/net/ethernet/mellanox/mlx5/core/en.h struct mlx5e_txqsq { · line 446

Quoted 5 lines
drivers/net/ethernet/mellanox/mlx5/core/en.h +2 -0
@@ -442,6 +442,8 @@ struct mlx5e_txqsq {
 		struct mlx5e_sq_dma       *dma_fifo;
 		struct mlx5e_skb_fifo      skb_fifo;
 		struct mlx5e_tx_wqe_info  *wqe_info;
+		void                      *tx_hdr_bufs;
+		dma_addr_t                 tx_hdr_bufs_dma;

Why are only headers considered for bouncing? Because they have the highest mapping overhead?

Note that TSO/GSO packets will copy the header inline in the WQE already. But not for small packets.

Quoted 69 lines
drivers/net/ethernet/mellanox/mlx5/core/en.h +0 -0
 	} db;
 	void __iomem              *uar_map;
 	struct netdev_queue       *txq;
drivers/net/ethernet/mellanox/mlx5/core/en/txrx.h +3 -1
index f2a8453d8dce0..6de7a2a430d72 100644
@@ -365,7 +365,9 @@ mlx5e_tx_dma_unmap(struct device *pdev, struct mlx5e_sq_dma *dma)
 {
 	switch (dma->type) {
 	case MLX5E_DMA_MAP_SINGLE:
-		dma_unmap_single(pdev, dma->addr, dma->size, DMA_TO_DEVICE);
+		if (dma->size)
+			dma_unmap_single(pdev, dma->addr, dma->size,
+					 DMA_TO_DEVICE);
 		break;
 	case MLX5E_DMA_MAP_PAGE:
 		netmem_dma_unmap_page_attrs(pdev, dma->addr, dma->size,
drivers/net/ethernet/mellanox/mlx5/core/en_main.c +14 -0
index 4c6060d54fbed..efd766aa43a02 100644
@@ -1666,6 +1666,13 @@ static void mlx5e_free_icosq(struct mlx5e_icosq *sq)
 
 void mlx5e_free_txqsq_db(struct mlx5e_txqsq *sq)
 {
+	if (sq->db.tx_hdr_bufs) {
+		int wq_sz = mlx5_wq_cyc_get_size(&sq->wq);
+		int df_sz = wq_sz * MLX5_SEND_WQEBB_NUM_DS;
+
+		dma_free_coherent(sq->pdev, df_sz * MAX_TCP_HEADER,
+				  sq->db.tx_hdr_bufs, sq->db.tx_hdr_bufs_dma);
+	}
 	kvfree(sq->db.wqe_info);
 	kvfree(sq->db.skb_fifo.fifo);
 	kvfree(sq->db.dma_fifo);
@@ -1690,6 +1697,13 @@ int mlx5e_alloc_txqsq_db(struct mlx5e_txqsq *sq, int numa)
 		return -ENOMEM;
 	}
 
+	if (sq->pdev->dma_pmd_tx_hdrs)
+		sq->db.tx_hdr_bufs =
+			dma_alloc_coherent(sq->pdev,
+					   df_sz * MAX_TCP_HEADER,
+					   &sq->db.tx_hdr_bufs_dma,
+					   GFP_KERNEL | __GFP_NOWARN);
+
 	sq->dma_fifo_mask = df_sz - 1;
 
 	sq->db.skb_fifo.pc   = &sq->skb_fifo_pc;
drivers/net/ethernet/mellanox/mlx5/core/en_tx.c +11 -0
index 0b5e600e4a6a9..3b6a7a8b0128e 100644
@@ -177,6 +177,27 @@ mlx5e_tx_get_gso_ihs(struct mlx5e_txqsq *sq, struct sk_buff *skb)
 	return ihs;
 }
 
+static inline dma_addr_t
+mlx5e_tx_map_hdr(struct mlx5e_txqsq *sq, unsigned char *data, u32 len)
+{
+	dma_addr_t dma_addr;
+
+	if (sq->db.tx_hdr_bufs && len <= MAX_TCP_HEADER) {
+		u32 off = (sq->dma_fifo_pc & sq->dma_fifo_mask) *
+			  MAX_TCP_HEADER;
+
+		memcpy(sq->db.tx_hdr_bufs + off, data, len);
+		dma_addr = sq->db.tx_hdr_bufs_dma + off;

drivers/net/ethernet/mellanox/mlx5/core/en_tx.c mlx5e_tx_get_gso_ihs(struct mlx5e_txqsq *sq, struct sk_buff *skb) · line 200

Quoted 10 lines
drivers/net/ethernet/mellanox/mlx5/core/en_tx.c +10 -0
+		mlx5e_dma_push_single(sq, dma_addr, 0);
+		return dma_addr;
+	}
+
+	dma_addr = dma_map_single(sq->pdev, data, len, DMA_TO_DEVICE);
+	if (likely(!dma_mapping_error(sq->pdev, dma_addr)))
+		mlx5e_dma_push_single(sq, dma_addr, len);
+	return dma_addr;
+}
+

This looks like a form of tx-copybreak.

Thanks,
Dragos

#25 lore raw

Re: [RFC: DMA_PMD 19/22] net/mlx5e: Use DMA_PMD memory for tx header bounce buffers

Quoted 12 lines · Dragos Tatulea
Quoted 6 lines · Luigi Rizzo

When dev->dma_pmd_tx_hdrs is enabled, allocate a MAX_TCP_HEADER bounce buffer per TX DMA FIFO slot out of the DMA_PMD arena. When the linear portion of a transmitted packet is at most MAX_TCP_HEADER bytes, copy it into the pre-mapped bounce buffer instead of calling dma_map_single()/dma_unmap_single() on every packet.

What is the difference between using the DMA_PMD pool or one (or a few) coherent DMA (2MB) buffers allocated by the driver?

The patch was actually using the coherent buffer. My bad, sorry.

Quoted 8 lines
Quoted 8 lines
---
 drivers/net/ethernet/mellanox/mlx5/core/en.h  |  2 ++
 .../net/ethernet/mellanox/mlx5/core/en/txrx.h |  4 ++-
 .../net/ethernet/mellanox/mlx5/core/en_main.c | 14 ++++++++++
 .../net/ethernet/mellanox/mlx5/core/en_tx.c   | 28 +++++++++++++++----
 4 files changed, 42 insertions(+), 6 deletions(-)
Quoted 12 lines

drivers/net/ethernet/mellanox/mlx5/core/en.h struct mlx5e_txqsq { · line 446

Quoted 10 lines
drivers/net/ethernet/mellanox/mlx5/core/en.h +2 -0
index a3945195f454e..d762ad1c1ffaf 100644
@@ -442,6 +442,8 @@ struct mlx5e_txqsq {
 		struct mlx5e_sq_dma       *dma_fifo;
 		struct mlx5e_skb_fifo      skb_fifo;
 		struct mlx5e_tx_wqe_info  *wqe_info;
+		void                      *tx_hdr_bufs;
+		dma_addr_t                 tx_hdr_bufs_dma;

Why are only headers considered for bouncing? Because they have the highest mapping overhead?

I meant to say headers and small packets.

Quoted 87 lines

Note that TSO/GSO packets will copy the header inline in the WQE already. But not for small packets.

Quoted 69 lines
drivers/net/ethernet/mellanox/mlx5/core/en.h +0 -0
 	} db;
 	void __iomem              *uar_map;
 	struct netdev_queue       *txq;
drivers/net/ethernet/mellanox/mlx5/core/en/txrx.h +3 -1
index f2a8453d8dce0..6de7a2a430d72 100644
@@ -365,7 +365,9 @@ mlx5e_tx_dma_unmap(struct device *pdev, struct mlx5e_sq_dma *dma)
 {
 	switch (dma->type) {
 	case MLX5E_DMA_MAP_SINGLE:
-		dma_unmap_single(pdev, dma->addr, dma->size, DMA_TO_DEVICE);
+		if (dma->size)
+			dma_unmap_single(pdev, dma->addr, dma->size,
+					 DMA_TO_DEVICE);
 		break;
 	case MLX5E_DMA_MAP_PAGE:
 		netmem_dma_unmap_page_attrs(pdev, dma->addr, dma->size,
drivers/net/ethernet/mellanox/mlx5/core/en_main.c +14 -0
index 4c6060d54fbed..efd766aa43a02 100644
@@ -1666,6 +1666,13 @@ static void mlx5e_free_icosq(struct mlx5e_icosq *sq)
 
 void mlx5e_free_txqsq_db(struct mlx5e_txqsq *sq)
 {
+	if (sq->db.tx_hdr_bufs) {
+		int wq_sz = mlx5_wq_cyc_get_size(&sq->wq);
+		int df_sz = wq_sz * MLX5_SEND_WQEBB_NUM_DS;
+
+		dma_free_coherent(sq->pdev, df_sz * MAX_TCP_HEADER,
+				  sq->db.tx_hdr_bufs, sq->db.tx_hdr_bufs_dma);
+	}
 	kvfree(sq->db.wqe_info);
 	kvfree(sq->db.skb_fifo.fifo);
 	kvfree(sq->db.dma_fifo);
@@ -1690,6 +1697,13 @@ int mlx5e_alloc_txqsq_db(struct mlx5e_txqsq *sq, int numa)
 		return -ENOMEM;
 	}
 
+	if (sq->pdev->dma_pmd_tx_hdrs)
+		sq->db.tx_hdr_bufs =
+			dma_alloc_coherent(sq->pdev,
+					   df_sz * MAX_TCP_HEADER,
+					   &sq->db.tx_hdr_bufs_dma,
+					   GFP_KERNEL | __GFP_NOWARN);
+
 	sq->dma_fifo_mask = df_sz - 1;
 
 	sq->db.skb_fifo.pc   = &sq->skb_fifo_pc;
drivers/net/ethernet/mellanox/mlx5/core/en_tx.c +11 -0
index 0b5e600e4a6a9..3b6a7a8b0128e 100644
@@ -177,6 +177,27 @@ mlx5e_tx_get_gso_ihs(struct mlx5e_txqsq *sq, struct sk_buff *skb)
 	return ihs;
 }
 
+static inline dma_addr_t
+mlx5e_tx_map_hdr(struct mlx5e_txqsq *sq, unsigned char *data, u32 len)
+{
+	dma_addr_t dma_addr;
+
+	if (sq->db.tx_hdr_bufs && len <= MAX_TCP_HEADER) {
+		u32 off = (sq->dma_fifo_pc & sq->dma_fifo_mask) *
+			  MAX_TCP_HEADER;
+
+		memcpy(sq->db.tx_hdr_bufs + off, data, len);
+		dma_addr = sq->db.tx_hdr_bufs_dma + off;

drivers/net/ethernet/mellanox/mlx5/core/en_tx.c mlx5e_tx_get_gso_ihs(struct mlx5e_txqsq *sq, struct sk_buff *skb) · line 200

Quoted 10 lines
drivers/net/ethernet/mellanox/mlx5/core/en_tx.c +10 -0
+		mlx5e_dma_push_single(sq, dma_addr, 0);
+		return dma_addr;
+	}
+
+	dma_addr = dma_map_single(sq->pdev, data, len, DMA_TO_DEVICE);
+	if (likely(!dma_mapping_error(sq->pdev, dma_addr)))
+		mlx5e_dma_push_single(sq, dma_addr, len);
+	return dma_addr;
+}
+

This looks like a form of tx-copybreak.

Thanks,
Dragos

#26 lore raw

Re: [RFC: DMA_PMD 19/22] net/mlx5e: Use DMA_PMD memory for tx header bounce buffers

Quoted 8 lines · Dragos Tatulea
Quoted 6 lines · Luigi Rizzo

Why are only headers considered for bouncing? Because they have the highest mapping overhead?

I meant to say headers and small packets.

Headers have a high cost for the map/unmap (especially in strict iommu mode), and also cause significant IOTLB thrashing, because they come from skb_head that is not pre-mapped. The impact of IOTLB thrashing depends on the hardware and load but they consume one IOTLB entry per packet with almost non-existent recycling.

In the following version I have modified the slub and skb allocator to feed skb head from DMA_PMD memory, which removes the need for header bounce buffers. It is a compromise (the skb head includes skb_shinfo, which we may not always want to expose to the device), but gives an option to those who want it, and in that case drivers that use pagepool can get all the benefits of DMA_PMD with zero modifications.

Quoted 2 lines
Quoted 2 lines

Note that TSO/GSO packets will copy the header inline in the WQE already. But not for small packets.

Yes additional bounce buffers are not needed on hardware that are essentially using the WQE as a bounce buffer. I'll double check the patch (mechanically generated).

Small packets should not be too problematic, as long as they come from fragments allocated during the copy_from_user.

cheers
luigi

#27 lore raw

RFC 20/22 net/idpf: Use DMA_PMD memory for tx header bounce buffers

In reply to Luigi Rizzo

When dev->dma_pmd_tx_hdrs is enabled, allocate a MAX_TCP_HEADER bounce buffer per TX buffer slot out of the DMA_PMD arena. When the linear portion of a transmitted packet is at most MAX_TCP_HEADER bytes, copy it into the pre-mapped bounce buffer and set the SQE unmap length to 0 instead of calling dma_map_single()/dma_unmap_page() on every packet.

---
 .../ethernet/intel/idpf/idpf_singleq_txrx.c   |  6 ++---
 drivers/net/ethernet/intel/idpf/idpf_txrx.c   | 21 ++++++++++++---
 drivers/net/ethernet/intel/idpf/idpf_txrx.h   | 27 ++++++++++++++++++-
 include/net/libeth/tx.h                       |  5 ++--
 4 files changed, 50 insertions(+), 9 deletions(-)
drivers/net/ethernet/intel/idpf/idpf_singleq_txrx.c +3 -3
index e3ddf18dcbf51..24a2dfec6212d 100644
@@ -261,7 +261,7 @@ static void idpf_tx_singleq_map(struct idpf_tx_queue *tx_q,
 
 	tx_desc = &tx_q->base_tx[i];
 
-	dma = dma_map_single(tx_q->dev, skb->data, size, DMA_TO_DEVICE);
+	dma = idpf_tx_map_hdr(tx_q, skb, first, size);
 
 	/* write each descriptor with CRC bit */
 	if (idpf_queue_has(CRC_EN, tx_q))
@@ -274,8 +274,7 @@ static void idpf_tx_singleq_map(struct idpf_tx_queue *tx_q,
 			return idpf_tx_singleq_dma_map_error(tx_q, skb,
 							     first, i);
 
-		/* record length, and DMA address */
-		dma_unmap_len_set(tx_buf, len, size);
+		/* record DMA address */
 		dma_unmap_addr_set(tx_buf, dma, dma);
 		tx_buf->type = LIBETH_SQE_FRAG;
 
@@ -326,6 +325,7 @@ static void idpf_tx_singleq_map(struct idpf_tx_queue *tx_q,
 
 		size = skb_frag_size(frag);
 		data_len -= size;
+		dma_unmap_len_set(tx_buf, len, size);
 
 		dma = skb_frag_dma_map(tx_q->dev, frag, 0, size,
 				       DMA_TO_DEVICE);
drivers/net/ethernet/intel/idpf/idpf_txrx.c +18 -3
index 4311ffa30bb18..4bdec468ea2ce 100644
@@ -90,6 +90,14 @@ static void idpf_tx_buf_rel_all(struct idpf_tx_queue *txq)
 	else
 		idpf_tx_buf_clean(txq);
 
+	if (txq->hdr_buf_va) {
+		dma_free_coherent(txq->dev,
+				  txq->buf_pool_size * MAX_TCP_HEADER,
+				  txq->hdr_buf_va, txq->hdr_buf_dma);
+		txq->hdr_buf_va = NULL;
+		txq->hdr_buf_dma = 0;
+	}
+
 	kfree(txq->tx_buf);
 	txq->tx_buf = NULL;
 }
@@ -187,6 +195,13 @@ static int idpf_tx_buf_alloc_all(struct idpf_tx_queue *tx_q)
 	if (!tx_q->tx_buf)
 		return -ENOMEM;
 
+	if (tx_q->dev->dma_pmd_tx_hdrs)
+		tx_q->hdr_buf_va =
+			dma_alloc_coherent(tx_q->dev,
+					   tx_q->buf_pool_size * MAX_TCP_HEADER,
+					   &tx_q->hdr_buf_dma,
+					   GFP_KERNEL | __GFP_NOWARN);
+
 	return 0;
 }
 
@@ -2663,7 +2678,7 @@ static void idpf_tx_splitq_map(struct idpf_tx_queue *tx_q,
 
 	tx_desc = &tx_q->flex_tx[i];
 
-	dma = dma_map_single(tx_q->dev, skb->data, size, DMA_TO_DEVICE);
+	dma = idpf_tx_map_hdr(tx_q, skb, first, size);
 
 	tx_buf = first;
 	first->nr_frags = 0;
@@ -2680,8 +2695,7 @@ static void idpf_tx_splitq_map(struct idpf_tx_queue *tx_q,
 		first->nr_frags++;
 		tx_buf->type = LIBETH_SQE_FRAG;
 
-		/* record length, and DMA address */
-		dma_unmap_len_set(tx_buf, len, size);
+		/* record DMA address */
 		dma_unmap_addr_set(tx_buf, dma, dma);
 
 		/* buf_addr is in same location for both desc types */
@@ -2784,6 +2798,7 @@ static void idpf_tx_splitq_map(struct idpf_tx_queue *tx_q,
 
 		size = skb_frag_size(frag);
 		data_len -= size;
+		dma_unmap_len_set(tx_buf, len, size);
 
 		dma = skb_frag_dma_map(tx_q->dev, frag, 0, size,
 				       DMA_TO_DEVICE);
drivers/net/ethernet/intel/idpf/idpf_txrx.h +26 -1
index 93547597efd2a..39458a8e5baa0 100644
@@ -8,6 +8,7 @@
 #include <linux/net/intel/virtchnl2_lan_desc.h>
 
 #include <net/libeth/cache.h>
+#include <net/libeth/tx.h>
 #include <net/libeth/types.h>
 #include <net/netdev_queues.h>
 #include <net/tcp.h>
@@ -639,6 +640,8 @@ libeth_cacheline_set_assert(struct idpf_rx_queue,
  * @q_vector: Backreference to associated vector
  * @buf_pool_size: Total number of idpf_tx_buf
  * @rel_q_id: relative virtchnl queue index
+ * @hdr_buf_va: Base of the TX header bounce buffer array, or NULL
+ * @hdr_buf_dma: DMA address matching @hdr_buf_va
  */
 struct idpf_tx_queue {
 	__cacheline_group_begin_aligned(read_mostly);
@@ -715,6 +718,8 @@ struct idpf_tx_queue {
 
 	u32 buf_pool_size;
 	u32 rel_q_id;
+	void *hdr_buf_va;
+	dma_addr_t hdr_buf_dma;
 	__cacheline_group_end_aligned(cold);
 };
 libeth_cacheline_set_assert(struct idpf_tx_queue, 64,
@@ -723,7 +728,7 @@ libeth_cacheline_set_assert(struct idpf_tx_queue, 64,
 			    offsetofend(struct idpf_tx_queue, timer) +
 			    offsetof(struct idpf_tx_queue, q_stats) -
 			    offsetofend(struct idpf_tx_queue, tstamp_task),
-			    32);
+			    48);
 
 /**
  * struct idpf_buf_queue - software structure representing a buffer queue
@@ -1131,4 +1136,24 @@ int idpf_tso(struct sk_buff *skb, struct idpf_tx_offload_params *off);
 
 void idpf_wait_for_sw_marker_completion(const struct idpf_tx_queue *txq);
 
+static inline dma_addr_t idpf_tx_map_hdr(struct idpf_tx_queue *tx_q,
+					 const struct sk_buff *skb,
+					 struct libeth_sqe *first,
+					 unsigned int size)
+{
+	u32 buf_idx = first - tx_q->tx_buf;
+
+	if (tx_q->hdr_buf_va && buf_idx < tx_q->buf_pool_size &&
+	    size <= MAX_TCP_HEADER) {
+		u32 offset = buf_idx * MAX_TCP_HEADER;
+
+		memcpy(tx_q->hdr_buf_va + offset, skb->data, size);
+		dma_unmap_len_set(first, len, 0);
+		return tx_q->hdr_buf_dma + offset;
+	}
+
+	dma_unmap_len_set(first, len, size);
+	return dma_map_single(tx_q->dev, skb->data, size, DMA_TO_DEVICE);
+}
+
 #endif /* !_IDPF_TXRX_H_ */
include/net/libeth/tx.h +3 -2
index c3db5c6f16410..2720ab9393e90 100644
@@ -130,8 +130,9 @@ static inline void libeth_tx_complete(struct libeth_sqe *sqe,
 	case LIBETH_SQE_SKB:
 	case LIBETH_SQE_FRAG:
 	case LIBETH_SQE_SLAB:
-		dma_unmap_page(cp->dev, dma_unmap_addr(sqe, dma),
-			       dma_unmap_len(sqe, len), DMA_TO_DEVICE);
+		if (dma_unmap_len(sqe, len))
+			dma_unmap_page(cp->dev, dma_unmap_addr(sqe, dma),
+				       dma_unmap_len(sqe, len), DMA_TO_DEVICE);
 		break;
 	default:
 		break;
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#28 lore raw

RFC 21/22 net/bnxt: Use DMA_PMD memory for tx header bounce buffers

In reply to Luigi Rizzo

When dev->dma_pmd_tx_hdrs is enabled, allocate a MAX_TCP_HEADER bounce buffer per TX ring slot out of the DMA_PMD arena. When the linear portion of a transmitted packet is at most MAX_TCP_HEADER bytes, copy it into the pre-mapped bounce buffer instead of calling dma_map_single()/dma_unmap_single() on every packet.

---
 drivers/net/ethernet/broadcom/bnxt/bnxt.c | 45 ++++++++++++++++++-----
 drivers/net/ethernet/broadcom/bnxt/bnxt.h |  2 +
 2 files changed, 37 insertions(+), 10 deletions(-)
drivers/net/ethernet/broadcom/bnxt/bnxt.c +35 -10
index d7728d0c5b6e6..b9c91eb3aaddd 100644
@@ -680,13 +680,22 @@ static netdev_tx_t bnxt_start_xmit(struct sk_buff *skb, struct net_device *dev)
 		length = BNXT_MIN_PKT_SIZE;
 	}
 
-	mapping = dma_map_single(&pdev->dev, skb->data, len, DMA_TO_DEVICE);
-
-	if (unlikely(dma_mapping_error(&pdev->dev, mapping)))
-		goto tx_free;
-
-	dma_unmap_addr_set(tx_buf, mapping, mapping);
-	dma_unmap_len_set(tx_buf, len, len);
+	if (txr->tx_hdr_bufs && len + pad <= MAX_TCP_HEADER) {
+		u32 off = RING_TX(bp, prod) * MAX_TCP_HEADER;
+
+		memcpy(txr->tx_hdr_bufs + off, skb->data, len);
+		if (pad && !last_frag)
+			memset(txr->tx_hdr_bufs + off + len, 0, pad);
+		mapping = txr->tx_hdr_bufs_dma + off;
+		dma_unmap_len_set(tx_buf, len, 0);
+	} else {
+		mapping = dma_map_single(&pdev->dev, skb->data, len,
+					 DMA_TO_DEVICE);
+		if (unlikely(dma_mapping_error(&pdev->dev, mapping)))
+			goto tx_free;
+		dma_unmap_addr_set(tx_buf, mapping, mapping);
+		dma_unmap_len_set(tx_buf, len, len);
+	}
 	flags = (len << TX_BD_LEN_SHIFT) | TX_BD_TYPE_LONG_TX_BD |
 		TX_BD_CNT(last_frag + 2);
 
@@ -800,8 +809,9 @@ static netdev_tx_t bnxt_start_xmit(struct sk_buff *skb, struct net_device *dev)
 	/* start back at beginning and unmap skb */
 	prod = txr->tx_prod;
 	tx_buf = &txr->tx_buf_ring[RING_TX(bp, prod)];
-	dma_unmap_single(&pdev->dev, dma_unmap_addr(tx_buf, mapping),
-			 skb_headlen(skb), DMA_TO_DEVICE);
+	if (dma_unmap_len(tx_buf, len))
+		dma_unmap_single(&pdev->dev, dma_unmap_addr(tx_buf, mapping),
+				 skb_headlen(skb), DMA_TO_DEVICE);
 	prod = NEXT_TX(prod);
 
 	/* unmap remaining mapped pages */
@@ -885,7 +895,6 @@ static bool __bnxt_tx_int(struct bnxt *bp, struct bnxt_tx_ring_info *txr,
 			dma_unmap_single(&pdev->dev, dma_addr, dma_len,
 					 DMA_TO_DEVICE);
 		}
-
 		last = tx_buf->nr_frags;
 
 		for (j = 0; j < last; j++) {
@@ -4111,6 +4120,15 @@ static void bnxt_free_tx_rings(struct bnxt *bp)
 
 		ring = &txr->tx_ring_struct;
 
+		if (txr->tx_hdr_bufs) {
+			dma_free_coherent(&pdev->dev,
+					  ring->ring_mem.nr_pages *
+					  TX_DESC_CNT * MAX_TCP_HEADER,
+					  txr->tx_hdr_bufs,
+					  txr->tx_hdr_bufs_dma);
+			txr->tx_hdr_bufs = NULL;
+		}
+
 		bnxt_free_ring(bp, &ring->ring_mem);
 	}
 }
@@ -4181,6 +4199,13 @@ static int bnxt_alloc_tx_rings(struct bnxt *bp)
 			if (rc)
 				return rc;
 		}
+		if (pdev->dev.dma_pmd_tx_hdrs && i >= bp->tx_nr_rings_xdp)
+			txr->tx_hdr_bufs =
+				dma_alloc_coherent(&pdev->dev,
+						   ring->ring_mem.nr_pages *
+						   TX_DESC_CNT * MAX_TCP_HEADER,
+						   &txr->tx_hdr_bufs_dma,
+						   GFP_KERNEL | __GFP_NOWARN);
 		qidx = bp->tc_to_qidx[j];
 		ring->queue_id = bp->q_info[qidx].queue_id;
 		spin_lock_init(&txr->xdp_tx_lock);
drivers/net/ethernet/broadcom/bnxt/bnxt.h +2 -0
index c673b2ce4a0d2..b42bbabc0eb98 100644
@@ -1003,6 +1003,8 @@ struct bnxt_tx_ring_info {
 	struct tx_push_buffer	*tx_push;
 	dma_addr_t		tx_push_mapping;
 	__le64			data_mapping;
+	void			*tx_hdr_bufs;
+	dma_addr_t		tx_hdr_bufs_dma;
 
 	void			*tx_inline_buf;
 	dma_addr_t		tx_inline_dma;
Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#29 lore raw

RFC 22/22 iommu/dma: Add DMA_PMD statistics and debugfs

In reply to Luigi Rizzo

DMA_PMD pools fail silently. dma_pmd_pool_alloc() returns NULL for four distinct reasons - allocation backoff, the global DMA_PMD page ceiling, an PMD_ORDER allocation failure, and a split_page_compound() rejection - and every caller quietly falls back to a plain page, so a pool that has stopped pooling looks exactly like one that is working. The map path is no
better: a buffer can be mapped individually because the domain has no usable IOVA window, because the domain has no 2MB page size, or because the PMD_ORDER page mapping itself failed, and none of that was observable either. The only symptom is a throughput loss with no counter to point at.

Add a counter for each of those cases plus the number of 2M page mappings established and dropped, and export them, along with the existing per-pool statistics, through /sys/kernel/debug/dma_pmd/pools.

The new counters are atomic64_t rather than being folded into the existing lock-protected statistics because their update sites cannot take pool->lock: dma_pmd_add_page() runs outside it, and the map slow path holds p2m->map_lock, so taking pool->lock there would invert the order against dma_pmd_domain_release().

Also emit a one-shot warning on the first PMD_ORDER allocation failure. That request carries __GFP_NOWARN, so the page allocator says nothing, and this is the one failure mode that is worth a line in dmesg rather than a counter somebody has to know to look at.

---
 drivers/iommu/dma-pmd-map.c  |  16 +++-
 drivers/iommu/dma-pmd-pool.c | 143 ++++++++++++++++++++++++++++++++---
 drivers/iommu/dma-pmd-priv.h |  43 ++++++++++-
 3 files changed, 186 insertions(+), 16 deletions(-)
drivers/iommu/dma-pmd-map.c +13 -3
index 76cb5d01cb1e8..46c6ab5c1b7de 100644
@@ -468,8 +468,13 @@ dma_addr_t dma_pmd_dma_map_phys(struct device *dev, struct iommu_domain *domain,
 		else
 			ret = dma_pmd_window_assign(dev, domain, win);
 
-		if (ret)
+		if (ret) {
+			if (ret == -EOPNOTSUPP)
+				atomic64_inc(&meta->pool->fallback_nopool);
+			else
+				atomic64_inc(&meta->pool->fallback_nowindow);
 			return DMA_MAPPING_ERROR;
+		}
 		win_size = READ_ONCE(win->size);
 	}
 
@@ -482,8 +487,10 @@ dma_addr_t dma_pmd_dma_map_phys(struct device *dev, struct iommu_domain *domain,
 	 * device mask.
 	 */
 	if (unlikely(iova - win->base + size > win_size ||
-		     iova + size - 1 > min_not_zero(dma_mask, dev->bus_dma_limit)))
+		     iova + size - 1 > min_not_zero(dma_mask, dev->bus_dma_limit))) {
+		atomic64_inc(&meta->pool->fallback_nowindow);
 		return DMA_MAPPING_ERROR;
+	}
 
 	domain_idx = win->domain_idx - DMA_PMD_IDX_FIRST;
 	if (likely(test_bit(domain_idx, &meta->domains_mapped)))
@@ -510,12 +517,15 @@ dma_addr_t dma_pmd_dma_map_phys(struct device *dev, struct iommu_domain *domain,
 			 */
 			smp_mb__before_atomic();
 			set_bit(domain_idx, &meta->domains_mapped);
+			atomic64_inc(&meta->pool->pmd_map_cnt);
 		}
 	}
 	spin_unlock_irqrestore(&meta->map_lock, flags);
 
-	if (unlikely(ret))
+	if (unlikely(ret)) {
+		atomic64_inc(&meta->pool->fallback_maperr);
 		return DMA_MAPPING_ERROR;
+	}
 
 	return iova;
 }
drivers/iommu/dma-pmd-pool.c +131 -12

233 lines not on this page · raw message

drivers/iommu/dma-pmd-priv.h +42 -1

73 lines not on this page · raw message

Signature · 1 line
2.56.0.rc1.315.gc6ed9934b7-goog
#30 lore raw
In reply to Luigi Rizzo

On Sat, Oct 03, 2026 at 09:22:19PM +0000, Luigi Rizzo wrote:

Hi Luigi,

Quoted 4 lines

Here is a subsystem called DMA_PMD on which I would like feedback on architecture, possible enhancements, or kernel components that could be reused to avoid duplication.

Thanks for posting this series, it solves more than one problems. I went through the whole series and the following is my take on the overall design (I might wait before replying to individual patches hence this might be verbose).

Quoted 11 lines

I think it can be extremely useful for those affected by the HW/SW overhead of IOMMU (especially IOTLB thrashing, see [1]), or confidential computing, or preemptable VMs.

The (not too exaggerated) pitch line is

DMA_PMD has the performance of identity, guarantees that only IO buffers can ever have active IOMMU or IOTLB mappings, removes the bounce buffer overhead in confidential computing and preemptable VMs, and integrates smoothly with existing kernel APIs.

Quoted 6 lines

=== ARCHITECTURE

DMA_PMD was initially designed to address IOTLB thrashing (details in [1]), but turned out to also resolve nicely the strict IOMMU overhead, and avoid the bounce buffer overhead in preemptible VMs and Confidential Computing.

I'm thinking if we can re-work the dma pools here to fit the needs of DMA PMD. Apart from that my main concern is the isolation model. As implemented:

- dma_unmap_*() of a pooled buffer is a no-op, i.e. unmap doesn't happen till the page is retired.
- the whole 2M page is mapped IOMMU_READ | IOMMU_WRITE, regardless of the direction of the buffer that triggered the mapping
- the mapping stays in every domain that ever mapped any block of the page until the page is retired, which under steady traffic may be never
- the TX pools are per-CPU and shared by all sockets and devices.

So, a NIC ends up with long-lived RW access to other sockets' data in the same 2M pages, including loopback payloads and kTLS SW plaintext (both come from sk_page_frag), and a DMA after unmap no longer faults but silently hits whoever owns the block next. For pooled memory this is identity-like isolation and weaker than DMA-FQ, whose exposure is bounded by the flush timeout. Thus, I'm not fully sure of the claim:
"security guarantees comparable to strict IOMMU".

It also isn't opt-in: dma_is_pmd_phys() is checked for every device in iommu_dma_map_phys(), thus, any device that is handed a pooled page gets a window, including in domains where the admin asked for strict mode. I think DMA_PMD has to be an explicit per-group default-domain policy, like DMA-FQ: selectable through iommu_groups/N/type and/or a boot option, off by default, decided when the default domain is set up and recorded in the cookie and the map path can check it before doing any pool lookup.

That is also the natural place to refuse untrusted devices. Today the window path runs after the swiotlb decision in iommu_dma_map_phys(), which for untrusted devices only bounces buffers that aren't granule-aligned, so a page-aligned pooled block gives an external-facing device a permanent RW 2M window over unrelated data. iommu_get_default_domain_type() already forces strict DMA for such groups DMA_PMD must not undo that.

I'm thinking If pooled memory is going to be shared across opt-in devices anyway, would an explicit shared domain for opted-in devices be cleaner?

It removes the per-domain machinery, but those devices then lose isolation from each other for all DMA, and the core would need to support a default domain shared across groups

Additionally, we should handle edge cases where the dma unmap (or it's TLB flush) fails for some reason but the page is freed to buddy..

Quoted 6 lines

It works by combining several known techniques:

- transparently feed allocators of device memory (skb_page_frag_refill(), dma_alloc_attrs(), pagepool, ...) with DMA_PMD pages, i.e. physically contiguous PMD_SIZE (2MB) pages mapped via PDE_SIZE IOMMU entries

Quoted 6 lines

- heavy recycling of DMA_PMD pages (like pagepool) and lazy IOMMU unmapping (like DMA-FQ), BUT:

- like strict IOMMU (DMA), safely release memory back to the kernel only after destroying all of its IOMMU mappings and a synchronous IOTLB flush

That's one of the strict-mode properties that this series keeps and two things undermine it today, dma_pmd_unmap_all() ignores the iommu_unmap() retval after it has already cleared the per-domain bits (for fellow reviewers this is in patch 7). And window PTEs outlive driver unbind and DMA ownership trasnfer because dma_pmd_domain_release() only runs when the cookie is freed, if a device is handed back from VFIO, it'll regain access to live host pages and patch 13 additionally gives up page_pool's destroy unmap of in-flight pafes.. The mappings need to go when the last DMA API user of the domain goes away not only at domain free..

Quoted 4 lines

- on allocation, DMA_PMD pages can be configured to be pinned in the host (hence suitable for preemptible VMs) and/or unencrypted (hence suitable for Confidential Computing), removing the need for bounce buffers

In CoCo guests, dma_pmd.decrypt is swtiched on silently and applied to every pool. inclusing the per-CPU skb_page_frag_refill pools that serve every socket. Enabling tx_enable_dma_pmd thenmakes loopback payloads and kTLS plaintext host readable & writable before encyrption. Similarly decrypted Rx pages lose the private copythat swiotlb had making it possible for the host to change packets after the stack has looked at them.. Can we make it much more explicit to the Guest/ Guest user that they're opting in to sharing their data with host for performance?

Quoted 3 lines

- there are global and per-device optin /sys/device/.../dma_pmd_* and /proc/sys/net/core/tx_enable_dma_pmd

Bools with sysfs files on every device having a dma_mask doesn't seem too nice.. the iommu policy belongs to the group's default domain..

Quoted 11 lines

NIC drivers can typically use dma_pmd with no modifications for rings, tx buffers, rx buffers (if they use pagepool), and rx headers. For tx headers, almost all drivers need changes (see later patches in the series) to implement cheap bounce buffers and avoid individual 4K mappings.

The series has the following main components:

- a sparse array (similar to pageblock_flags) to quickly attach metadata to a 2MB page without fiddling with the struct page. Cost is 128B per 2MB page used as an IO buffer, totally negligible.

IIUC, the entries are 256B and the array is sized from theoretical phys_addr space rather that from memory: up to 8G of KVA on x86 4-level, 32G on arm64 with 48-bit PA and 512G 52-bit PA, where the chunk bitmap no longer fits in kmalloc, failing the init. Init also populates metadata for the entire RAM.. it'd be nice to size it from real memory ranges or use an xarray or per-section array with lazy population..

Quoted 7 lines

- dma_pmd_pool, a replacement for alloc_pages() that can be instantiated per-CPU or per receive queue. It handles the split of PMD_SIZE pages into order-N blocks, handles dma_map and unmap, and aggressively recycles entries. It is used to feed skb_page_frag_refill(), pagepool, and receive buffers for drivers that do not use pagepool.
See [2] for "WHY NOT PAGEPOOL FOR TX AND EVERYTHING"

I am seeing that the recycles page blocks bypass KASAN/KMSAN poisoning, page owner, alloc tagging and bad_page checks.. which might make a UAF go undetected. We might have to use it or a similar technique to ensure the UAF of a polled buffer remains safe in such a case.. IIRC, kasan_mempool_(un)poison_pages are used for such cache (I'd let the mm folks chime in on this).

Quoted 8 lines

- dma_pmd_arena, is another allocator backed by DMA_PMD pages and is used exclusively as the backend for dma_alloc_attrs(). Used for longer-lived allocations (descriptor/completion rings, rx and tx header buffers)

- glue code to hook DMA_PMD into pagepool [2], skb_page_frag_refill(), dma_alloc_attrs(), dma_map/unmap...

On the IOMMU side there are also a few structural limits:

- the domain registry has BITS_PER_LONG entries, and a decline is cached in the cookie forever. Default domains are per IOMMU group, often one per function (VFs included) on ACS-capable machines, and TX pages reach every NIC, so a limit of 64 is reachable, and which devices get to pool would depend on probe order.
- the per-domain window is a multi-TB alloc_iova() carved on the first map, under a global IRQ-off lock, sized from iomem_resource.end and from whichever device in the group maps firstF
- I'm wondering it iova - base == PA (plus a fixed 16G offset), is safe? As devices learn host physical addresses.

Can we consider giving each PMD page a dense slot number when it enters a pool, and using iova = base + slot * 2M? That keeps the O(1) map and the range-check unmap, shrinks the window to cap * 2M, works with narrower masks and stops exposing PAs, and per-domain tracking of mapped slots would lift the 64-domain limit as well. The window could then be reserved in iommu_dma_init_domain() through a dma-iommu helper, instead of handing the iova_domain to dma-pmd-map.c.

Thanks,
Praan

#31 lore raw
In reply to Luigi Rizzo
Quoted 3 lines · Luigi Rizzo

Here is a subsystem called DMA_PMD on which I would like feedback on architecture, possible enhancements, or kernel components that could be reused to avoid duplication.

Here is a feedback to a subsystem called DMA_PMD ;)

Why is basing this on PMDs (and embedding it in the name) the right approach?

On architctures with large PMDs (512 MiB on arm64 with 64k), would we really want to use 512 MiB pages, or rather something smaller (e.g., 2 MiB) that might possibly also have TLB benefits (cont-pte)?

Signature · 3 lines
Cheers,

David
#32 lore raw
Quoted 6 lines · David Hildenbrand (Arm)
Quoted 3 lines · Luigi Rizzo

Here is a subsystem called DMA_PMD on which I would like feedback on architecture, possible enhancements, or kernel components that could be reused to avoid duplication.

Quoted 7 lines

Here is a feedback to a subsystem called DMA_PMD ;)

Why is basing this on PMDs (and embedding it in the name) the right approach?

On architctures with large PMDs (512 MiB on arm64 with 64k), would we really want to use 512 MiB pages, or rather something smaller (e.g., 2 MiB) that might possibly also have TLB benefits (cont-pte)?

I had to call it something... an earlier prototype used the name IOMMU_2M, but I didn't want to suggest that the design was limited to 2M (it is not).

Aside from the name, the _current_ prototype restricts to 2M allocations, exactly because too large units are expensive and wasteful.

In the code, decoupling the allocation size from the PMD size is trivial.

To enjoy the reduced IOTLB pressure the architecture needs to support IOMMU leaves with the correct size. Looks like ARM supports a "Contiguous" hint, but I am not sure how to tell if the hint is honored (ie the IOTLB actually uses one entry for the full contiguous range) other than measuring.

cheers
luigi

#33 lore raw
Quoted 16 lines · Luigi Rizzo
Quoted 6 lines · David Hildenbrand (Arm)
Quoted 3 lines · Luigi Rizzo

Here is a subsystem called DMA_PMD on which I would like feedback on architecture, possible enhancements, or kernel components that could be reused to avoid duplication.

Quoted 7 lines

Here is a feedback to a subsystem called DMA_PMD ;)

Why is basing this on PMDs (and embedding it in the name) the right approach?

On architctures with large PMDs (512 MiB on arm64 with 64k), would we really want to use 512 MiB pages, or rather something smaller (e.g., 2 MiB) that might possibly also have TLB benefits (cont-pte)?

Quoted 7 lines

I had to call it something... an earlier prototype used the name IOMMU_2M, but I didn't want to suggest that the design was limited to 2M (it is not).

Aside from the name, the _current_ prototype restricts to 2M allocations, exactly because too large units are expensive and wasteful.

In the code, decoupling the allocation size from the PMD size is trivial.

Yeah, we should do that.

We should probably just find a way to describe that this is a POOL that focuses on physical contiguity in some configured granularity.

Signature · 3 lines
Cheers,

David
maintainer
#34 lore raw
Quoted 23 lines · David Hildenbrand (Arm)
Quoted 22 lines · Luigi Rizzo
Quoted 6 lines · David Hildenbrand (Arm)
Quoted 3 lines · Luigi Rizzo

Here is a subsystem called DMA_PMD on which I would like feedback on architecture, possible enhancements, or kernel components that could be reused to avoid duplication.

Quoted 7 lines

Here is a feedback to a subsystem called DMA_PMD ;)

Why is basing this on PMDs (and embedding it in the name) the right approach?

On architctures with large PMDs (512 MiB on arm64 with 64k), would we really want to use 512 MiB pages, or rather something smaller (e.g., 2 MiB) that might possibly also have TLB benefits (cont-pte)?

I had to call it something... an earlier prototype used the name IOMMU_2M, but I didn't want to suggest that the design was limited to 2M (it is not).

Aside from the name, the _current_ prototype restricts to 2M allocations, exactly because too large units are expensive and wasteful.

Quoted 6 lines
Quoted 1 line

In the code, decoupling the allocation size from the PMD size is trivial.

Yeah, we should do that.

We should probably just find a way to describe that this is a POOL that focuses on physical contiguity in some configured granularity.

And since it's intended for DMA we could call it dma_pool and oh look it already exists...

Sure the current implementation is capped at PAGE_SIZE for allocation (and thus mapping too), but I don't see why that couldn't just be made more flexible.

Thanks,
Robin.

#35 lore raw
Quoted 11 lines · Robin Murphy
Quoted 10 lines · David Hildenbrand (Arm)
Quoted 9 lines · Luigi Rizzo

On Mon, Oct 12, 2026 at 3:51 PM David Hildenbrand (Arm) <[email protected]> wrote:

I had to call it something... an earlier prototype used the name IOMMU_2M, but I didn't want to suggest that the design was limited to 2M (it is not).

Aside from the name, the _current_ prototype restricts to 2M allocations, exactly because too large units are expensive and wasteful.

Quoted 8 lines
Quoted 6 lines
Quoted 1 line

In the code, decoupling the allocation size from the PMD size is trivial.

Yeah, we should do that.

We should probably just find a way to describe that this is a POOL that focuses on physical contiguity in some configured granularity.

And since it's intended for DMA we could call it dma_pool and oh look it already exists...

Heh, I did have "DMA_POOL" in mind when writing my reply.

Quoted 3 lines

Sure the current implementation is capped at PAGE_SIZE for allocation (and thus mapping too), but I don't see why that couldn't just be made more flexible.

That intuitively sounds like the right direction.

Signature · 3 lines
Cheers,

David
#36 lore raw
Quoted 15 lines · David Hildenbrand (Arm)
Quoted 13 lines · Robin Murphy
Quoted 12 lines · David Hildenbrand (Arm)
Quoted 10 lines · Luigi Rizzo

On Mon, Oct 12, 2026 at 3:51 PM David Hildenbrand (Arm) <[email protected]> wrote:

I had to call it something... an earlier prototype used the name IOMMU_2M, but I didn't want to suggest that the design was limited to 2M (it is not).

Aside from the name, the _current_ prototype restricts to 2M allocations, exactly because too large units are expensive and wasteful.

In the code, decoupling the allocation size from the PMD size is trivial.

Quoted 8 lines
Quoted 6 lines
Quoted 4 lines

Yeah, we should do that.

We should probably just find a way to describe that this is a POOL that focuses on physical contiguity in some configured granularity.

And since it's intended for DMA we could call it dma_pool and oh look it already exists...

Heh, I did have "DMA_POOL" in mind when writing my reply.

which confirms that naming is one of the hardest problems in CS... Let's try to figure out a good name before renaming everything.

Quoted 4 lines
Quoted 2 lines

Sure the current implementation is capped at PAGE_SIZE for allocation (and thus mapping too), but I don't see why that couldn't just be made more flexible.

That intuitively sounds like the right direction.

Point taken, I will decouple the allocaiton size from PMD_SIZE this in the next iteration.

I have also followed up on most of Pranjal's feedback (stricter error checking, compact IOVA ranges, opt-in per destination on the tx path...) .

I am also looking at reducing some inefficiencies (e.g. pagepool already caches, and allocations of new pages are relatively rare, so there is not much of a point
of having a dma_pmd_pool per queue; and on the tx side, something similar to the percpu page cache to reduce locking costs when a page is allocated on one CPU and freed on a different one)

cheers
luigi

#37 lore raw
In reply to David Hildenbrand (Arm)
Quoted 24 lines · David Hildenbrand (Arm)
Quoted 22 lines · Luigi Rizzo
Quoted 6 lines · David Hildenbrand (Arm)
Quoted 3 lines · Luigi Rizzo

Here is a subsystem called DMA_PMD on which I would like feedback on architecture, possible enhancements, or kernel components that could be reused to avoid duplication.

Quoted 7 lines

Here is a feedback to a subsystem called DMA_PMD ;)

Why is basing this on PMDs (and embedding it in the name) the right approach?

On architctures with large PMDs (512 MiB on arm64 with 64k), would we really want to use 512 MiB pages, or rather something smaller (e.g., 2 MiB) that might possibly also have TLB benefits (cont-pte)?

I had to call it something... an earlier prototype used the name IOMMU_2M, but I didn't want to suggest that the design was limited to 2M (it is not).

Aside from the name, the _current_ prototype restricts to 2M allocations, exactly because too large units are expensive and wasteful.

Quoted 6 lines
Quoted 1 line

In the code, decoupling the allocation size from the PMD size is trivial.

Yeah, we should do that.

We should probably just find a way to describe that this is a POOL that focuses on physical contiguity in some configured granularity.

Before embarking in a global renaming, I would like to get opinions on acceptable alternative names (possibly with a short prefix usable for identifiers in the code). I could think of the following

DMA_PMAP (for PreMapped or Persistent Mapped)
or, ahemm...
DMA_PISA (Pooled IOMMU Superpage Allocator)
both using dmap_ for internal name prefixes

Other suggestions ?

cheers
luigi

#38 lore raw
Quoted 11 lines · Luigi Rizzo
Quoted 2 lines

We should probably just find a way to describe that this is a POOL that focuses on physical contiguity in some configured granularity.

Before embarking in a global renaming, I would like to get opinions on acceptable alternative names (possibly with a short prefix usable for identifiers in the code). I could think of the following

DMA_PMAP (for PreMapped or Persistent Mapped)
or, ahemm...
DMA_PISA (Pooled IOMMU Superpage Allocator)
both using dmap_ for internal name prefixes

Can someone explain what outside netdev would use this? And why you couldn't do this in the netdev page pool?

It is not a common workload to have the DMA allocator be the one that allocates the memory. Usually we are DMA'ing from memory that was allocated someplace else.

I think Robin is right, this is just a special case of the dma pool, and it certainly shouldn't be something as grandiose as a subsystem..

Jason

#39 lore raw
Quoted 9 lines · Jason Gunthorpe
Quoted 7 lines · Luigi Rizzo
Quoted 2 lines

We should probably just find a way to describe that this is a POOL that focuses on physical contiguity in some configured granularity.

Before embarking in a global renaming, I would like to get opinions on acceptable alternative names (possibly with a short prefix usable for identifiers in the code). I could think of the following

Quoted 7 lines
Quoted 4 lines

DMA_PMAP (for PreMapped or Persistent Mapped)
or, ahemm...
DMA_PISA (Pooled IOMMU Superpage Allocator)
both using dmap_ for internal name prefixes

Can someone explain what outside netdev would use this? And why you couldn't do this in the netdev page pool?

I can try.

Regarding users, the next target is disks (not included in this series)

Regarding why not just pagepool, see below.

FWIW when I started this (after the previous work on swiotlb copy elision
https://lore.kernel.org/all/[email protected]/ ) I thought this would take only some simple tweaks to pagepool and skb_page_frag_refill, a couple of days with some agents tops. But the agents did point out that there were a ton of corner cases to handle (device detach, reconfiguration, memory reclaiming, reducing locking contention...).

As a reminder my goals are the following:
- reduce DMA map/unmap costs in strict iommu mode without the DMA-FQ compromise on security
- address the IOTLB thrashing problem when using 4K mappings (very serious even with DMA-FQ)
- help reduce bounce buffer usage in confidential computing and overcommitted VMs.

With that in mind:

Quoted 3 lines

It is not a common workload to have the DMA allocator be the one that allocates the memory. Usually we are DMA'ing from memory that was allocated someplace else.

Aside from the fact that dma_alloc_attr()/dma_alloc_coherent() does memory allocation + iova allocation/mapping, this is not what happens here.
Maybe the confusion comes from one function name (dma_map_alloc_pages()), but it doesn't map any thing.

My code (in this version, and more in the upcoming release) mainly implements a specialized memory allocator with an
API equivalent to alloc_pages() and variants, but ensures that the order-N blocks come from contiguous 2MB blocks reserved on the fly.

The physical addresses of these blocks are recognized by the
"dma allocator" (I suppose you meant the entity that allocates the IOVA range) so that it can apply specialized IOMMU mappings backed by 2MB IOMMU leaves.

And finally, it hooks into existing kernel subsystem (pagepool, the skb transmit buffer allocation, dma_alloc_*(), dma_map_*() so that devices can opt-in to use it without any driver code change.

Regarding pagepool:
For the receive path, I do use my allocator to feed pagepool (in the next version I have wrapped it into a proper memory provider interface. Non-pagepool NICs can either use a few trivial changes to call dma_map_alloc_pages() when filling their rings, or convert to pagepool (slightly bigger change; anyways there are options).

Note that just feeding the pagepool with 2MB pages is not efficient because the fragmentation in pagepool is done with a bump
allocator, so recycling blocks from a 2MB page is difficult
(it has to wait until all 512 blocks to become idle). My code has a bitmap to track usage, so it naturally recycles at the block level.

Then there is the transmit path.

For skb heads, one simple solution is to use tx head bounce buffers some of the patches in the series show that option (the next version implements a proper tx-copybreak).

Otherwise we need to populate skb heads with pre-mapped memory. In the next version I have a simple modification to the slub code to accept an opt-in alternative to alloc_pages(). I considered using the pagepool, but the changes would be similar and the layering seemed really odd, with a cache on top of a cache.

For transmit, there is a bit of impedance mismatch as well:
skb_page_frag_refill() does not know which device
we want to use (in fact, it is a per-task so there may be many netdevs used by a task). We could tweak the pagepool
to be device-agnostic, but that would be a bit more intrusive (more architecturally than in terms of code);
also we need to make sure dma_map() on those pages does the right thing without trying to map/unmap the individual 4K fragments,
and we need to make sure the skb_free() etc does
not leak those pages into free_pages().

Quoted 4 lines

I think Robin is right, this is just a special case of the dma pool, and it certainly shouldn't be something as grandiose as a subsystem..

dma_pool() could be tweaked to allocate 2MB and return order-N fragments, so maybe that could be a provider for pagepool, but it has some caveats:
- when fragmenting, the freelist is constructed in-band, ie using memory exposed to the IO device. That is really a no-go if we use the IOMMU because we don't trust the device, so we would also need to allocate extra memory for the freelist (no big deal, but
that is basically what my dma_pmd_meta supports)
- memory is never released until the pool is destroyed,
so there is a problem of stranded idle memory.

Trying to use dma_pool for the transmit path has all the problems listed above: lack of device, inefficient release of memory, coarse grained locking...

In summary: of course we could tweak existing subsystems, trying to reuse them in ways that were probably not anticipated (see the above partial list of missing features).

I think that once one addresses the functional and performance problems, the changes would become quite intrusive and the risk of penalizing the currently supported code path might become significant.

cheers
luigi

#40 lore raw
Quoted 15 lines · Luigi Rizzo
Quoted 14 lines · Jason Gunthorpe
Quoted 11 lines · Luigi Rizzo
Quoted 2 lines

We should probably just find a way to describe that this is a POOL that focuses on physical contiguity in some configured granularity.

Before embarking in a global renaming, I would like to get opinions on acceptable alternative names (possibly with a short prefix usable for identifiers in the code). I could think of the following

DMA_PMAP (for PreMapped or Persistent Mapped)
or, ahemm...
DMA_PISA (Pooled IOMMU Superpage Allocator)
both using dmap_ for internal name prefixes

Quoted 6 lines
Quoted 2 lines

Can someone explain what outside netdev would use this? And why you couldn't do this in the netdev page pool?

I can try.

Regarding users, the next target is disks (not included in this series)

Disks don't use a memory pool, they do IO to folios allocated by the page cache.

The only other candiates I know of besides page pool would be the existing dma pool users. I don't think they are so performance sensitive as netdev.

IOW I think this entire series is only useful to netdev.

Quoted 10 lines
Quoted 3 lines

It is not a common workload to have the DMA allocator be the one that allocates the memory. Usually we are DMA'ing from memory that was allocated someplace else.

Aside from the fact that dma_alloc_attr()/dma_alloc_coherent() does memory allocation + iova allocation/mapping, this is not what happens here.
Maybe the confusion comes from one function name (dma_map_alloc_pages()), but it doesn't map any thing.

Quoted 8 lines

My code (in this version, and more in the upcoming release) mainly implements a specialized memory allocator with an
API equivalent to alloc_pages() and variants, but ensures that the order-N blocks come from contiguous 2MB blocks reserved on the fly.

The physical addresses of these blocks are recognized by the
"dma allocator" (I suppose you meant the entity that allocates the IOVA range) so that it can apply specialized IOMMU mappings backed by 2MB IOMMU leaves.

Why? This seems completely divergent from how anything else works in DMA mapping, and I don't see a reason for it to be anything like this. Other than it makes page pool work a bit easier

Frankly this looks like you had AI to transpose a bunch netdev page pool into iommu.

Quoted 5 lines

Note that just feeding the pagepool with 2MB pages is not efficient because the fragmentation in pagepool is done with a bump
allocator, so recycling blocks from a 2MB page is difficult
(it has to wait until all 512 blocks to become idle). My code has a bitmap to track usage, so it naturally recycles at the block level.

It doesn't seem like this little issue should motivate all this

Quoted 6 lines

Then there is the transmit path.

For skb heads, one simple solution is to use tx head bounce buffers some of the patches in the series show that option (the next version implements a proper tx-copybreak).

Quoted 6 lines

Otherwise we need to populate skb heads with pre-mapped memory. In the next version I have a simple modification to the slub code to accept an opt-in alternative to alloc_pages(). I considered using the pagepool, but the changes would be similar and the layering seemed really odd, with a cache on top of a cache.

With AI there is no limit to the layering violations one can make :(

Quoted 10 lines

For transmit, there is a bit of impedance mismatch as well:
skb_page_frag_refill() does not know which device
we want to use (in fact, it is a per-task so there may be many netdevs used by a task). We could tweak the pagepool
to be device-agnostic, but that would be a bit more intrusive (more architecturally than in terms of code);
also we need to make sure dma_map() on those pages does the right thing without trying to map/unmap the individual 4K fragments,
and we need to make sure the skb_free() etc does
not leak those pages into free_pages().

This is all a page pool problem, has nothing to do with iommu or the common dma layer.

You can already get optimally mapped 2M IOVA and memory out of the APIs we have. I can see no justification for the intrustive mess under this beyond it makes netdev page pool easier to hack on top.

Every thing you listed boils down to 'netdev page pool work the way I want'

Jason

#41 lore raw
Quoted 3 lines · Jason Gunthorpe
Quoted 1 line · Luigi Rizzo

On Thu, Oct 22, 2026 at 10:12 PM Jason Gunthorpe <[email protected]> wrote:

...

Quoted 9 lines
Quoted 6 lines
Quoted 2 lines

Can someone explain what outside netdev would use this? And why you couldn't do this in the netdev page pool?

I can try.

Regarding users, the next target is disks (not included in this series)

Disks don't use a memory pool, they do IO to folios allocated by the page cache.

I know. As I said I have a separate patch to cover those IO buffers

 block/bio.c                  |  21 +++++
 block/blk-mq-dma.c           |   4 +-
 drivers/iommu/dma-pmd-node.c |   3 +-
 drivers/iommu/dma-pmd-pool.c |  14 ++-
 drivers/iommu/dma-pmd-priv.h |   7 +-
 drivers/iommu/dma-pmd-user.c | 390
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
 include/linux/dma-pmd.h      |  53 +++++++++++
 mm/filemap.c                 |  27 +++++-
 mm/page-writeback.c          |  13 +++
 mm/readahead.c               |   9 +-

Disk I/O is still potentially affected by the same problems (cost if io mapping/unmapping, iotlb thrashing, bounce buffers in confidential computing...)

Quoted 6 lines

The only other candiates I know of besides page pool would be the existing dma pool users. I don't think they are so performance sensitive as netdev.

IOW I think this entire series is only useful to netdev.

Well, the series provide mechanisms to address disk I/O as well.

Quoted 20 lines
Quoted 11 lines
Quoted 4 lines

It is not a common workload to have the DMA allocator be the one that allocates the memory. Usually we are DMA'ing from memory that was allocated someplace else.

Aside from the fact that dma_alloc_attr()/dma_alloc_coherent() does memory allocation + iova allocation/mapping, this is not what happens here.
Maybe the confusion comes from one function name (dma_map_alloc_pages()), but it doesn't map any thing.

Quoted 8 lines

My code (in this version, and more in the upcoming release) mainly implements a specialized memory allocator with an
API equivalent to alloc_pages() and variants, but ensures that the order-N blocks come from contiguous 2MB blocks reserved on the fly.

The physical addresses of these blocks are recognized by the
"dma allocator" (I suppose you meant the entity that allocates the IOVA range) so that it can apply specialized IOMMU mappings backed by 2MB IOMMU leaves.

Quoted 6 lines

Why? This seems completely divergent from how anything else works in DMA mapping, and I don't see a reason for it to be anything like this. Other than it makes page pool work a bit easier

Frankly this looks like you had AI to transpose a bunch netdev page pool into iommu.

(yes, AI assisted, heavily human-guided).
Frankly, it's very orthogonal to pagepool, given that it uses pagepool for what it does well, and it provides functionality that pagepool does not have.

Anyways, reading your next comments, are you suggesting that all these functionalities should be implemented as pagepool extensions? (2MB mappings and iommu backing, proper allocator of fragments out of larger pages, device-less pagepools, multi-domain mappings, pagepool
as memory provider for skb heads, pagepool as memory provider for descriptor rings ?)

cheers
luigi

#42 lore raw
Quoted 30 lines · Luigi Rizzo
Quoted 3 lines · Jason Gunthorpe
Quoted 1 line · Luigi Rizzo

On Thu, Oct 22, 2026 at 10:12 PM Jason Gunthorpe <[email protected]> wrote:

...

Quoted 9 lines
Quoted 6 lines
Quoted 2 lines

Can someone explain what outside netdev would use this? And why you couldn't do this in the netdev page pool?

I can try.

Regarding users, the next target is disks (not included in this series)

Disks don't use a memory pool, they do IO to folios allocated by the page cache.

I know. As I said I have a separate patch to cover those IO buffers

 block/bio.c                  |  21 +++++
 block/blk-mq-dma.c           |   4 +-
 drivers/iommu/dma-pmd-node.c |   3 +-
 drivers/iommu/dma-pmd-pool.c |  14 ++-
 drivers/iommu/dma-pmd-priv.h |   7 +-
 drivers/iommu/dma-pmd-user.c | 390
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
 include/linux/dma-pmd.h      |  53 +++++++++++
 mm/filemap.c                 |  27 +++++-
 mm/page-writeback.c          |  13 +++
 mm/readahead.c               |   9 +-
Quoted 3 lines

Disk I/O is still potentially affected by the same problems (cost if io mapping/unmapping, iotlb thrashing, bounce buffers in confidential computing...)

The disk folks already have a proposal to address all of this using io_uring and preallocated buffers. I really doubt yet another version is going to be interesting there.

Quoted 6 lines

Anyways, reading your next comments, are you suggesting that all these functionalities should be implemented as pagepool extensions? (2MB mappings and iommu backing, proper allocator of fragments out of larger pages, device-less pagepools, multi-domain mappings, pagepool
as memory provider for skb heads, pagepool as memory provider for descriptor rings ?)

netdev shouldn't be touching iommu, it can get a 2M page and map it using the normal DMA API. AFAIK there is not such a big reason to need any of these layering violations. They just make it easier on page pool..

"multi-domain mappings" is that just for page pool because it can't easially keep track of IOVAs for all the devices mapping the same PMD? I admit hacking in a special IOVA range so every netdev has the same IOVA is certainly a creative way to ignore all layering and solve it. :\

But you could just figure out a way to keep track of the per-device per-PMD iova mapping..

That said, if you came with some much narrower series to request some kind of 'globally shared iova' during dma allocation that might be something dma-api folks could agree with.. It seems like the only actual DMA API request here anyhow?

That's a bit tricky since it is impossible as a general concept, but maybe you can come up with some way to narrow it..

I'm still not convinced this is even right for netdev, especially compared to what Dragos has been working on. The CC stuff seems actively dangerous. Unconditionally always using CC shared memory for skbs is completely security wrong. What I have traffic flowing inside my VM between containers or something? Does this end up putting those skbs in shared memory even if they never hit a physical NIC? Same with a TDISP capable NIC, does this unconditionally degrade its security?

Jason

#43 lore raw
Quoted 2 lines · Jason Gunthorpe

On Fri, Oct 23, 2026 at 04:30:25PM +0200, Luigi Rizzo wrote:

Just addressing the last part:

Quoted 7 lines

...The CC stuff seems
actively dangerous. Unconditionally always using CC shared memory for skbs is completely security wrong. What I have traffic flowing inside my VM between containers or something? Does this end up putting those skbs in shared memory even if they never hit a physical NIC? Same with a TDISP capable NIC, does this unconditionally degrade its security?

the current series was RFC and "unconditional" just to show the concept.

My next version (a trivial change, really) is fully opt-in on a per-device and per direction basis.

The unencrypted (or pre-mapped) buffers will only be used for traffic that hits a device that opted in, and only for the directions that were opted in. So we can finely tune the configuration based on hw capabilities, threat model and performance requirements.

cheers
luigi

maintainer
#44 lore raw
In reply to Jason Gunthorpe
Quoted 11 lines · On Fri, 23 Oct 2026 11:50:23 -0300 Jason Gunthorpe wrote:
Quoted 6 lines

Anyways, reading your next comments, are you suggesting that all these functionalities should be implemented as pagepool extensions? (2MB mappings and iommu backing, proper allocator of fragments out of larger pages, device-less pagepools, multi-domain mappings, pagepool
as memory provider for skb heads, pagepool as memory provider for descriptor rings ?)

netdev shouldn't be touching iommu, it can get a 2M page and map it using the normal DMA API. AFAIK there is not such a big reason to need any of these layering violations. They just make it easier on page pool..

FWIW we're entirely happy on the netdev side to add this to page pool. In fact the initial RFC I posted for "page pool memory providers" was addressing this exact use case. I didn't push it forward due to low time and suspicion that IOMMU folks would prefer a more generic solution. Since then memory providers were pushed forward and merged for dmabuf, and we have netlink APIs to configure things. So adding large mappings should be SMOC.

#45 lore raw
Quoted 14 lines · Jakub Kicinski
Quoted 11 lines · On Fri, 23 Oct 2026 11:50:23 -0300 Jason Gunthorpe wrote:
Quoted 6 lines

Anyways, reading your next comments, are you suggesting that all these functionalities should be implemented as pagepool extensions? (2MB mappings and iommu backing, proper allocator of fragments out of larger pages, device-less pagepools, multi-domain mappings, pagepool
as memory provider for skb heads, pagepool as memory provider for descriptor rings ?)

netdev shouldn't be touching iommu, it can get a 2M page and map it using the normal DMA API. AFAIK there is not such a big reason to need any of these layering violations. They just make it easier on page pool..

Quoted 7 lines

FWIW we're entirely happy on the netdev side to add this to page pool. In fact the initial RFC I posted for "page pool memory providers" was addressing this exact use case. I didn't push it forward due to low time and suspicion that IOMMU folks would prefer a more generic solution. Since then memory providers were pushed forward and merged for dmabuf, and we have netlink APIs to configure things. So adding large mappings should be SMOC.

Maybe technicalities, maybe not...

Getting a 2MB contiguous and aligned page is only the first step, and the easy one.

Next we need to split it into 4K fragments that can be recycled without waiting for the entire 512 of them to be returned. This is not rocket science, but requires much more state that what fits in the struct page, so that's another layer that needs to be added to quickly access the state from the pfn. Essentially my dma_pmd_meta (because I could not/did not want to/ use fields in struct page to access ).
Doing it in pagepool could reuse some fields in
struct page to point to the metadata and simplify the implementation, but maybe leave people unhappy because now something may require an extra indirection.

Then there is a question of resource management: when 512 fragments come out of a much larger page, deciding which one to recycle matters a lot. Without a strategy, there is a significant risk of stranding a lot of lightly used 2M pages that cannot be returned because some fragments are in use.
Again no rocket science but that takes some compromises (sorting based on usage ? periodically drain old pages ? etc) between effectiveness, code complexity and runtime cost.

And then of course adapting to zero or many devices...

cheers
luigi

#46 lore raw
In reply to Jason Gunthorpe
Quoted 7 lines · Jason Gunthorpe
Quoted 3 lines

Disk I/O is still potentially affected by the same problems (cost if io mapping/unmapping, iotlb thrashing, bounce buffers in confidential computing...)

The disk folks already have a proposal to address all of this using io_uring and preallocated buffers. I really doubt yet another version is going to be interesting there.

Huh? If you mean the dma-buf I/O it doesn't really have anything to do with disks, except that this is the first user. The dma-buf iovec can work for every ->read_iter/->write_iter consumer, and should be adopted more broadly. Including by networking instead of their own totally weird different world.

#47 lore raw
Quoted 10 lines · Christoph Hellwig
Quoted 7 lines · Jason Gunthorpe
Quoted 3 lines

Disk I/O is still potentially affected by the same problems (cost if io mapping/unmapping, iotlb thrashing, bounce buffers in confidential computing...)

The disk folks already have a proposal to address all of this using io_uring and preallocated buffers. I really doubt yet another version is going to be interesting there.

Quoted 5 lines

Huh? If you mean the dma-buf I/O it doesn't really have anything to do with disks, except that this is the first user. The dma-buf iovec can work for every ->read_iter/->write_iter consumer, and should be adopted more broadly. Including by networking instead of their own totally weird different world.

Christoph, is this the dma-buf series you are referring to ?
https://lore.kernel.org/all/[email protected]/

I am not claiming that my proposal is a good fit for disk or accelerator I/O, but every subsystem has different constraints, so it is not unreasonable that a proposal for (N)etwork and a proposal for (D)isk focus on the different bottlenecks (still there can be learning from looking at the other solution).

As an example, in networking we have to deal with the following:
- typically at least two buffers per packet (header+payload)
- often, very small fragments (1400-ish MTU plus crumbles from data in different buffers
- extremely high I/O rate with almost no spatial locality, which is an IOTLB killer and the main reason behind my proposal and some of its complexity.
- on tx no good way for the application to pre-reserve buffers (buffers are sliced from a 32K per-task block,
going to possibly different destinations)

cheers
luigi

#48 lore raw
In reply to Christoph Hellwig
Quoted 11 lines · Christoph Hellwig
Quoted 7 lines · Jason Gunthorpe
Quoted 3 lines

Disk I/O is still potentially affected by the same problems (cost if io mapping/unmapping, iotlb thrashing, bounce buffers in confidential computing...)

The disk folks already have a proposal to address all of this using io_uring and preallocated buffers. I really doubt yet another version is going to be interesting there.

Huh? If you mean the dma-buf I/O it doesn't really have anything to do with disks, except that this is the first user.

Yeah

Quoted 3 lines

The dma-buf iovec can work for every ->read_iter/->write_iter consumer, and should be adopted more broadly. Including by networking instead of their own totally weird different world.

I'm not holding my breath on that one..

Jason

#49 lore raw

I drafted an implementation [1] for premapped TX and RX buffers on top of the existing networking page_pool. It is implemented entirely in the networking layer and extends page_pool as the default RX allocator, to the TX path. There are no hooks in the IOMMU, DMA or page allocator code. I wanted to understand if this implementation correctly captured the feedback on this thread. Key components of this design:

- Chunks: as in Luigi's series, memory comes in 2 MiB chunks, but each chunk is mapped once per opted-in device through the DMA API and records its IOVA for each device, rather than using a shared IOVA window.

- TX: page_pool accepts a memory provider for pools that are not bound to an RX queue. Per-CPU page_pools take 32 KiB pages from the chunks of their NUMA node; TCP copies sendmsg() data into them through the task page_frag and allocates its skb heads from them.

- RX: an instance of the same memory provider, sharing the chunk code, backs RX queue page_pools. RX chunks of order-0 pages belong to one device and NUMA node, and are shared by that device's queues on the node.

[1] https://github.com/torvalds/linux/compare/master...NamanGulati:linux:netdev_dma_pool

Quoted 24 lines · Jason Gunthorpe
Quoted 11 lines · Christoph Hellwig
Quoted 7 lines · Jason Gunthorpe
Quoted 3 lines

Disk I/O is still potentially affected by the same problems (cost if io mapping/unmapping, iotlb thrashing, bounce buffers in confidential computing...)

The disk folks already have a proposal to address all of this using io_uring and preallocated buffers. I really doubt yet another version is going to be interesting there.

Huh? If you mean the dma-buf I/O it doesn't really have anything to do with disks, except that this is the first user.

Yeah

Quoted 3 lines

The dma-buf iovec can work for every ->read_iter/->write_iter consumer, and should be adopted more broadly. Including by networking instead of their own totally weird different world.

I'm not holding my breath on that one..

Jason

#50 lore raw
Quoted 18 lines · Naman Gulati

I drafted an implementation [1] for premapped TX and RX buffers on top of the existing networking page_pool. It is implemented entirely in the networking layer and extends page_pool as the default RX allocator, to the TX path. There are no hooks in the IOMMU, DMA or page allocator code. I wanted to understand if this implementation correctly captured the feedback on this thread. Key components of this design:

- Chunks: as in Luigi's series, memory comes in 2 MiB chunks, but each chunk is mapped once per opted-in device through the DMA API and records its IOVA for each device, rather than using a shared IOVA window.

- TX: page_pool accepts a memory provider for pools that are not bound to an RX queue. Per-CPU page_pools take 32 KiB pages from the chunks of their NUMA node; TCP copies sendmsg() data into them through the task page_frag and allocates its skb heads from them.

Quoted 6 lines

- RX: an instance of the same memory provider, sharing the chunk code, backs RX queue page_pools. RX chunks of order-0 pages belong to one device and NUMA node, and are shared by that device's queues on the node.

[1] https://github.com/torvalds/linux/compare/master...NamanGulati:linux:netdev_dma_pool

IMHO the netstack should never read from shared/decrypted memory. If you put it in a SKB you have to be sure the only touch after that point will be a DMA read from an untrusted device on the TX side (sending it to a trusted device would be a fail) and the final copy to userspace on the RX side.

Everything else is very security questionable.

It is unclear to me how any of these page pool proposals meet that requirement since page pool typically provides memory that ends up widely used in the netstack.

Jason

#51 lore raw
Quoted 25 lines · Jason Gunthorpe
Quoted 23 lines · Naman Gulati

I drafted an implementation [1] for premapped TX and RX buffers on top of the existing networking page_pool. It is implemented entirely in the networking layer and extends page_pool as the default RX allocator, to the TX path. There are no hooks in the IOMMU, DMA or page allocator code. I wanted to understand if this implementation correctly captured the feedback on this thread. Key components of this design:

- Chunks: as in Luigi's series, memory comes in 2 MiB chunks, but each chunk is mapped once per opted-in device through the DMA API and records its IOVA for each device, rather than using a shared IOVA window.

- TX: page_pool accepts a memory provider for pools that are not bound to an RX queue. Per-CPU page_pools take 32 KiB pages from the chunks of their NUMA node; TCP copies sendmsg() data into them through the task page_frag and allocates its skb heads from them.

- RX: an instance of the same memory provider, sharing the chunk code, backs RX queue page_pools. RX chunks of order-0 pages belong to one device and NUMA node, and are shared by that device's queues on the node.

Quoted 7 lines
Quoted 1 line

[1] https://github.com/torvalds/linux/compare/master...NamanGulati:linux:netdev_dma_pool

IMHO the netstack should never read from shared/decrypted memory. If you put it in a SKB you have to be sure the only touch after that point will be a DMA read from an untrusted device on the TX side (sending it to a trusted device would be a fail) and the final copy to userspace on the RX side.

That's likely a fair callout. TBH I'm not very familiar with CoCo and will spend some time understanding the constraints. I kept CoCo out of my implementation as I approached this solution from the overcommitted VM problem where we are trying to overcommit memory in VMs and use these pre-mapped pages to avoid using bounce buffers.

Quoted 8 lines

Everything else is very security questionable.

It is unclear to me how any of these page pool proposals meet that requirement since page pool typically provides memory that ends up widely used in the netstack.

Jason

#52 lore raw
Quoted 34 lines · Naman Gulati
Quoted 25 lines · Jason Gunthorpe
Quoted 23 lines · Naman Gulati

I drafted an implementation [1] for premapped TX and RX buffers on top of the existing networking page_pool. It is implemented entirely in the networking layer and extends page_pool as the default RX allocator, to the TX path. There are no hooks in the IOMMU, DMA or page allocator code. I wanted to understand if this implementation correctly captured the feedback on this thread. Key components of this design:

- Chunks: as in Luigi's series, memory comes in 2 MiB chunks, but each chunk is mapped once per opted-in device through the DMA API and records its IOVA for each device, rather than using a shared IOVA window.

- TX: page_pool accepts a memory provider for pools that are not bound to an RX queue. Per-CPU page_pools take 32 KiB pages from the chunks of their NUMA node; TCP copies sendmsg() data into them through the task page_frag and allocates its skb heads from them.

- RX: an instance of the same memory provider, sharing the chunk code, backs RX queue page_pools. RX chunks of order-0 pages belong to one device and NUMA node, and are shared by that device's queues on the node.

Quoted 7 lines
Quoted 1 line

[1] https://github.com/torvalds/linux/compare/master...NamanGulati:linux:netdev_dma_pool

IMHO the netstack should never read from shared/decrypted memory. If you put it in a SKB you have to be sure the only touch after that point will be a DMA read from an untrusted device on the TX side (sending it to a trusted device would be a fail) and the final copy to userspace on the RX side.

Quoted 5 lines

That's likely a fair callout. TBH I'm not very familiar with CoCo and will spend some time understanding the constraints. I kept CoCo out of my implementation as I approached this solution from the overcommitted VM problem where we are trying to overcommit memory in VMs and use these pre-mapped pages to avoid using bounce buffers.

Why does overcomitted VM use bounce buffers? Do you mean this is about getting better memory clustering in page pool since the VM paging granule is 2M?

Jason

#53 lore raw
Quoted 42 lines · Jason Gunthorpe
Quoted 34 lines · Naman Gulati
Quoted 25 lines · Jason Gunthorpe
Quoted 23 lines · Naman Gulati

I drafted an implementation [1] for premapped TX and RX buffers on top of the existing networking page_pool. It is implemented entirely in the networking layer and extends page_pool as the default RX allocator, to the TX path. There are no hooks in the IOMMU, DMA or page allocator code. I wanted to understand if this implementation correctly captured the feedback on this thread. Key components of this design:

- Chunks: as in Luigi's series, memory comes in 2 MiB chunks, but each chunk is mapped once per opted-in device through the DMA API and records its IOVA for each device, rather than using a shared IOVA window.

- TX: page_pool accepts a memory provider for pools that are not bound to an RX queue. Per-CPU page_pools take 32 KiB pages from the chunks of their NUMA node; TCP copies sendmsg() data into them through the task page_frag and allocates its skb heads from them.

- RX: an instance of the same memory provider, sharing the chunk code, backs RX queue page_pools. RX chunks of order-0 pages belong to one device and NUMA node, and are shared by that device's queues on the node.

Quoted 7 lines
Quoted 1 line

[1] https://github.com/torvalds/linux/compare/master...NamanGulati:linux:netdev_dma_pool

IMHO the netstack should never read from shared/decrypted memory. If you put it in a SKB you have to be sure the only touch after that point will be a DMA read from an untrusted device on the TX side (sending it to a trusted device would be a fail) and the final copy to userspace on the RX side.

Quoted 5 lines

That's likely a fair callout. TBH I'm not very familiar with CoCo and will spend some time understanding the constraints. I kept CoCo out of my implementation as I approached this solution from the overcommitted VM problem where we are trying to overcommit memory in VMs and use these pre-mapped pages to avoid using bounce buffers.

Quoted 3 lines

Why does overcomitted VM use bounce buffers? Do you mean this is about getting better memory clustering in page pool since the VM paging granule is 2M?

Not exactly, we are trying to use VFIO passthrough NICs in overcommitted VMs. Since the guest memory is overcommitted we can't dma-map the entire guest address space (as non-overcommitted VMs do). So overcommitted VMs can use bounce buffers to have a set of pre-mapped buffers to bounce traffic in and out. We're trying to use this solution to map pages dynamically with virtio-iommu and recycle them via page-pool to avoid traps on each TX/RX and avoid the copy cost of bounce buffers.

This problem extends to generally reducing IOMMU overhead in networking - taking the dma map/unmap cost out of the hot-path and avoiding IOTLB thrashing.

Quoted 2 lines

Jason

#54 lore raw
Quoted 43 lines · Naman Gulati
Quoted 42 lines · Jason Gunthorpe
Quoted 39 lines · Naman Gulati
Quoted 25 lines · Jason Gunthorpe
Quoted 23 lines · Naman Gulati

I drafted an implementation [1] for premapped TX and RX buffers on top of the existing networking page_pool. It is implemented entirely in the networking layer and extends page_pool as the default RX allocator, to the TX path. There are no hooks in the IOMMU, DMA or page allocator code. I wanted to understand if this implementation correctly captured the feedback on this thread. Key components of this design:

- Chunks: as in Luigi's series, memory comes in 2 MiB chunks, but each chunk is mapped once per opted-in device through the DMA API and records its IOVA for each device, rather than using a shared IOVA window.

- TX: page_pool accepts a memory provider for pools that are not bound to an RX queue. Per-CPU page_pools take 32 KiB pages from the chunks of their NUMA node; TCP copies sendmsg() data into them through the task page_frag and allocates its skb heads from them.

- RX: an instance of the same memory provider, sharing the chunk code, backs RX queue page_pools. RX chunks of order-0 pages belong to one device and NUMA node, and are shared by that device's queues on the node.

Quoted 7 lines
Quoted 1 line

[1] https://github.com/torvalds/linux/compare/master...NamanGulati:linux:netdev_dma_pool

IMHO the netstack should never read from shared/decrypted memory. If you put it in a SKB you have to be sure the only touch after that point will be a DMA read from an untrusted device on the TX side (sending it to a trusted device would be a fail) and the final copy to userspace on the RX side.

That's likely a fair callout. TBH I'm not very familiar with CoCo and will spend some time understanding the constraints. I kept CoCo out of my implementation as I approached this solution from the overcommitted VM problem where we are trying to overcommit memory in VMs and use these pre-mapped pages to avoid using bounce buffers.

Quoted 7 lines
Quoted 3 lines

Why does overcomitted VM use bounce buffers? Do you mean this is about getting better memory clustering in page pool since the VM paging granule is 2M?

Not exactly, we are trying to use VFIO passthrough NICs in overcommitted VMs. Since the guest memory is overcommitted we can't dma-map the entire guest address space (as non-overcommitted VMs do).

?? I understood you could and this was implemented under the virtio-iommu by pinning the memory under active DMA?

Where in upstream does the DMA API force bounce buffering for this case?

Quoted 9 lines

So overcommitted VMs can use bounce buffers to have a set of pre-mapped buffers to bounce traffic in and out. We're trying to use this solution to map pages dynamically with virtio-iommu and recycle them via page-pool to avoid traps on each TX/RX and avoid the copy cost of bounce buffers.

This problem extends to generally reducing IOMMU overhead in networking - taking the dma map/unmap cost out of the hot-path and avoiding IOTLB thrashing.

Sure, that makes sense, but just having a pool of entirely normal pre-dma-mapped memory is quite a different problem from what launched this thread...

Jason

#55 lore raw
Quoted 2 lines · Jason Gunthorpe

On Fri, Nov 06, 2026 at 10:17:38AM -0800, Naman Gulati wrote:

...

Quoted 7 lines
Quoted 3 lines

This problem extends to generally reducing IOMMU overhead in networking - taking the dma map/unmap cost out of the hot-path and avoiding IOTLB thrashing.

Sure, that makes sense, but just having a pool of entirely normal pre-dma-mapped memory is quite a different problem from what launched this thread...

Since I launched the thread, I guess I should comment...

I wanted to address multiple problems, in random order:
- IOTLB thrashing
- better security than DMA-FQ
- reduce dma map/unmap costs (both on the host and guest)
- reduce/avoid bounce buffer overhead in Confidential Computing and overcommitted VMs
- not just for networking, also for disks and accelerators etc.

Now it turns out that one way to address all of them was to
- create a special memory allocator, which distributed ordinary memory but with additional metadata that make it easier to implement large
iommu mappings,
track lifetime etc.
- hook this allocator into relevant kernel subsystems so that consumers could use it with little or no changes.

As it happens, the first version I posted last month was not terribly clean, and possibly not terribly well presented, and had some redundancy that was unnecessary.

The next version (hopefully next week) is hopefully a lot cleaner, and i think the best witness is how small is the change to pagepool, basically "if the device has opted in, ask for that special memory"

net/core/page_pool.c +1 -0
index b775b6305fb78..e12ba47a20e43 100644
@@ -16,6 +16,7 @@
 #include <net/page_pool/helpers.h>
 #include <net/page_pool/memory_provider.h>
 #include <net/xdp.h>
+#include <linux/pisa.h>
 
 #include <linux/dma-direction.h>
 #include <linux/dma-mapping.h>
@@ -602,6 +603,8 @@ static noinline netmem_ref

__page_pool_alloc_netmems_slow(struct page_pool *pool

         */
        if ((gfp & GFP_ATOMIC) == GFP_ATOMIC)
                gfp |= __GFP_NOWARN;

+ if (dma_map)
+ gfp |= pisa_rx_gfp(pool->p.dev);

        /* Don't support bulk alloc for high-order pages */
        if (unlikely(pp_order))

The network tx side is more complicated because, as discussed earlier, we need to be sure that the leaf device is one that needs those special dma-able buffers, and there isn't (or I have not found) one central place to hook into for tcp, udp, zerocopy, security things etc., leading to a plethora of small hooks

 net/core/skbuff.c                                            |   42 +++-
 net/core/sock.c                                              |   62 +++++-
 net/ipv4/esp4.c                                              |    4 +-
 net/ipv4/ip_output.c                                         |   19 +-
 net/ipv4/tcp.c                                               |   23 ++-
 net/ipv4/tcp_output.c                                        |   12 +-
 net/ipv6/esp6.c                                              |    4 +-
 net/ipv6/ip6_output.c                                        |   19 +-
 net/tls/tls_device.c                                         |    4 +-

cheers
luigi

#56 lore raw
In reply to Jason Gunthorpe
Quoted 53 lines · Jason Gunthorpe
Quoted 43 lines · Naman Gulati
Quoted 42 lines · Jason Gunthorpe
Quoted 39 lines · Naman Gulati
Quoted 25 lines · Jason Gunthorpe
Quoted 23 lines · Naman Gulati

I drafted an implementation [1] for premapped TX and RX buffers on top of the existing networking page_pool. It is implemented entirely in the networking layer and extends page_pool as the default RX allocator, to the TX path. There are no hooks in the IOMMU, DMA or page allocator code. I wanted to understand if this implementation correctly captured the feedback on this thread. Key components of this design:

- Chunks: as in Luigi's series, memory comes in 2 MiB chunks, but each chunk is mapped once per opted-in device through the DMA API and records its IOVA for each device, rather than using a shared IOVA window.

- TX: page_pool accepts a memory provider for pools that are not bound to an RX queue. Per-CPU page_pools take 32 KiB pages from the chunks of their NUMA node; TCP copies sendmsg() data into them through the task page_frag and allocates its skb heads from them.

- RX: an instance of the same memory provider, sharing the chunk code, backs RX queue page_pools. RX chunks of order-0 pages belong to one device and NUMA node, and are shared by that device's queues on the node.

Quoted 7 lines
Quoted 1 line

[1] https://github.com/torvalds/linux/compare/master...NamanGulati:linux:netdev_dma_pool

IMHO the netstack should never read from shared/decrypted memory. If you put it in a SKB you have to be sure the only touch after that point will be a DMA read from an untrusted device on the TX side (sending it to a trusted device would be a fail) and the final copy to userspace on the RX side.

That's likely a fair callout. TBH I'm not very familiar with CoCo and will spend some time understanding the constraints. I kept CoCo out of my implementation as I approached this solution from the overcommitted VM problem where we are trying to overcommit memory in VMs and use these pre-mapped pages to avoid using bounce buffers.

Quoted 7 lines
Quoted 3 lines

Why does overcomitted VM use bounce buffers? Do you mean this is about getting better memory clustering in page pool since the VM paging granule is 2M?

Not exactly, we are trying to use VFIO passthrough NICs in overcommitted VMs. Since the guest memory is overcommitted we can't dma-map the entire guest address space (as non-overcommitted VMs do).

Quoted 5 lines

?? I understood you could and this was implemented under the virtio-iommu by pinning the memory under active DMA?

Where in upstream does the DMA API force bounce buffering for this case?

Sorry, should have been clearer: the DMA API does not enforce this, bounce buffering is typically implemented by the drivers in this case. Such as QPL mode in the GVE driver.

Quoted 16 lines
Quoted 10 lines

So overcommitted VMs can use bounce buffers to have a set of pre-mapped buffers to bounce traffic in and out. We're trying to use this solution to map pages dynamically with virtio-iommu and recycle them via page-pool to avoid traps on each TX/RX and avoid the copy cost of bounce buffers.

This problem extends to generally reducing IOMMU overhead in networking - taking the dma map/unmap cost out of the hot-path and avoiding IOTLB thrashing.

Sure, that makes sense, but just having a pool of entirely normal pre-dma-mapped memory is quite a different problem from what launched this thread...

Jason

#57 lore raw
In reply to David Hildenbrand (Arm)
Quoted 5 lines · David Hildenbrand (Arm)
Quoted 3 lines · Luigi Rizzo

Here is a subsystem called DMA_PMD on which I would like feedback on architecture, possible enhancements, or kernel components that could be reused to avoid duplication.

Quoted 7 lines

Here is a feedback to a subsystem called DMA_PMD ;)

Why is basing this on PMDs (and embedding it in the name) the right approach?

On architctures with large PMDs (512 MiB on arm64 with 64k), would we really want to use 512 MiB pages, or rather something smaller (e.g., 2 MiB) that might possibly also have TLB benefits (cont-pte)?

+1 I raised the same point in the LPC talk.
AFAIK, this series tries to solve both IOTLB pressure and CoCo bouncing at the same time which might be too strict; as for CoCo there is no actual IOMMU, so there is no sizing constraint.

Also to reduce bouncing, I think it is sufficient to use the SWIOTLB instead of having a new pool + recycling, the tricky part is how to abstract that to client drivers as this would be needed beyond SKB.

Thanks,
Mostafa

Quoted 6 lines
Signature · 4 lines
-- 
Cheers,

David
#58 lore raw
Quoted 9 lines · Mostafa Saleh
Quoted 7 lines · David Hildenbrand (Arm)
Quoted 3 lines · Luigi Rizzo

Here is a subsystem called DMA_PMD on which I would like feedback on architecture, possible enhancements, or kernel components that could be reused to avoid duplication.

Here is a feedback to a subsystem called DMA_PMD ;)

Quoted 7 lines
Quoted 5 lines

Why is basing this on PMDs (and embedding it in the name) the right approach?

On architctures with large PMDs (512 MiB on arm64 with 64k), would we really want to use 512 MiB pages, or rather something smaller (e.g., 2 MiB) that might possibly also have TLB benefits (cont-pte)?

+1 I raised the same point in the LPC talk.

See my other reply, he code makes it clear that the target is reasonably-sized chunks (2M being the obvious choice with 4K PTE/2M PMD, for other cases we need hw support, and it is relatively simple to decouple page size and chunk size.

Quoted 7 lines

AFAIK, this series tries to solve both IOTLB pressure and CoCo bouncing at the same time which might be too strict; as for CoCo there is no actual IOMMU, so there is no sizing constraint.

Also to reduce bouncing, I think it is sufficient to use the SWIOTLB instead of having a new pool + recycling, the tricky part is how to abstract that to client drivers as this would be needed beyond SKB.

I did have another series to build buffers out of the swiotlb pool
https://lore.kernel.org/all/[email protected]/
but I found it does not scale well under pressure: the existing swiotlb pools use linear search to find an empty region of suitable size, linear scanning when one pool is full, which quickly degrades to O(N) on each allocation.
I had some other (not posted) changes to build a buddy allocator on top of the pool (so searching for a slot becomes O(1)) and to spread the search order when a pool is full (avoiding O(N) locking conflicts), but there is a bit of extra overhead in the light-load case. Also it felt like reimplementing the wheel.

Overall I think DMA_[NOT_JUST_]PMD is cleaner and superior.

cheers
luigi

Quoted 9 lines

Thanks,
Mostafa

Quoted 6 lines

--
Cheers,

David

Signature · 5 lines
-----------------------------------------
Luigi RIZZO, [email protected]
 http://www.iet.unipi.it/~luigi/
 Mobile   +39-338-6809875
-----------------------------------------
#59 lore raw
In reply to Luigi Rizzo

Hi Luigi,

Quoted 150 lines · Luigi Rizzo

Here is a subsystem called DMA_PMD on which I would like feedback on architecture, possible enhancements, or kernel components that could be reused to avoid duplication.

I think it can be extremely useful for those affected by the HW/SW overhead of IOMMU (especially IOTLB thrashing, see [1]), or confidential computing, or preemptable VMs.

The (not too exaggerated) pitch line is

DMA_PMD has the performance of identity, guarantees that only IO buffers can ever have active IOMMU or IOTLB mappings, removes the bounce buffer overhead in confidential computing and preemptable VMs, and integrates smoothly with existing kernel APIs.

=== ARCHITECTURE

DMA_PMD was initially designed to address IOTLB thrashing (details in [1]), but turned out to also resolve nicely the strict IOMMU overhead, and avoid the bounce buffer overhead in preemptible VMs and Confidential Computing.

It works by combining several known techniques:

- transparently feed allocators of device memory (skb_page_frag_refill(), dma_alloc_attrs(), pagepool, ...) with DMA_PMD pages, i.e. physically contiguous PMD_SIZE (2MB) pages mapped via PDE_SIZE IOMMU entries

- heavy recycling of DMA_PMD pages (like pagepool) and lazy IOMMU unmapping (like DMA-FQ), BUT:

- like strict IOMMU (DMA), safely release memory back to the kernel only after destroying all of its IOMMU mappings and a synchronous IOTLB flush

- on allocation, DMA_PMD pages can be configured to be pinned in the host (hence suitable for preemptible VMs) and/or unencrypted (hence suitable for Confidential Computing), removing the need for bounce buffers

- there are global and per-device optin /sys/device/.../dma_pmd_* and /proc/sys/net/core/tx_enable_dma_pmd

NIC drivers can typically use dma_pmd with no modifications for rings, tx buffers, rx buffers (if they use pagepool), and rx headers. For tx headers, almost all drivers need changes (see later patches in the series) to implement cheap bounce buffers and avoid individual 4K mappings.

The series has the following main components:

- a sparse array (similar to pageblock_flags) to quickly attach metadata to a 2MB page without fiddling with the struct page. Cost is 128B per 2MB page used as an IO buffer, totally negligible.

- dma_pmd_pool, a replacement for alloc_pages() that can be instantiated per-CPU or per receive queue. It handles the split of PMD_SIZE pages into order-N blocks, handles dma_map and unmap, and aggressively recycles entries. It is used to feed skb_page_frag_refill(), pagepool, and receive buffers for drivers that do not use pagepool.
See [2] for "WHY NOT PAGEPOOL FOR TX AND EVERYTHING"

- dma_pmd_arena, is another allocator backed by DMA_PMD pages and is used exclusively as the backend for dma_alloc_attrs(). Used for longer-lived allocations (descriptor/completion rings, rx and tx header buffers)

- glue code to hook DMA_PMD into pagepool [2], skb_page_frag_refill(), dma_alloc_attrs(), dma_map/unmap...

- per-driver patches, where necessary (e.g. tx header buffers [3])

=== PERFORMANCE BENEFITS

Your mileage may vary. Enabling the IOMMU may have no throughput impact, until it does when some system components (bus, IOTLB, CPU) become overloaded. Aside from throughput reduction, one interesting parameter is the effectiveness of the IOTLB. Here is a sample of SMMU performance counters for a large ARM system with 2x200G NICs doing bidirectional traffic:

    === DMA-FQ MODE (total throughput ~440Gbps)
    25,757,488      smmuv3_pmcg_*/event=0x80/   IOTLB lookups
    16,634,941      smmuv3_pmcg_*/event=0x81/   IOTLB  misses

    === DMA_PMD on top of strict DMA (total throughput ~745Gbps)
    22,693,218      smmuv3_pmcg_*/event=0x80/   IOTLB lookups
        30,536      smmuv3_pmcg_*/event=0x81/   IOTLB  misses
    (not a mistake, also lookups went down despite the higher rate
    because the tx side can use larger segments)

The 2MB mappings made IOTLB misses almost non existent, because the working set is reduced by a factor of ~512.

Note, the code has more verbose comments than I would like. Several of them are there to avoid Sashiko getting confused and flagging false positives.

=== NOTES

[1] IOMMU IMPACT AND IOTLB THRASHING
This is documented in more detail in Documentation/core-api/dma-pmd.rst but the compact version is below.

There are three main costs involved with using the IOMMU:
- CPU cost for dma map/unmap
- CPU cost and latency for synchronous IOTLB flush (required for strong security)
- IOTLB thrashing, shows up dramatically when the IO access pattern exceeds the IOTLB size, and IOMMU page walks slow down bus activity up to a point where we see over 30..60% throughput reduction just for this reason. Some relevant references

https://lore.kernel.org/all/[email protected]/
https://www.ncbi.nlm.nih.gov/pmc/articles/PMC10280580/

Specifically, NICs access 4 or more pages per packet (descriptor queue, completion queue, rx or tx header, one or more buffers), with very little locality especially for data buffers and tx headers. Each queue has 1-4K entries, a fast NIC uses 16 or more queues per direction, so just the data buffers cover 32..128K pages. Using 4KB mappings makes the IOTLB ineffective, as shown by the performance counters shown earlier.

[2] WHY NOT PAGEPOOL FOR TX AND EVERYTHING
There is some overlap between pagepool and dma_pmd_pool in that both implement a cache, but pagepool is missing some important features:

- pagepool does not handle splitting 2M pages in smaller chunks, or the mappings. That would need to be implemented (and is what dma_pmd_pool does)

- pagepool's provided pages cannot be cleanly managed by get_page()/put_page(), which is what all the consumers of skb_page_frag_refill(). Fixing that would require dozen of changes with high risk of missing some paths.

- even for the receive path, a provider for pagepool has more restrictions than alloc_pages-supplied memory, so if I wanted to wrap dma_pmd_pool as a provider I would have needed changes to the provider interface.

- pagepool requires a device at allocation time, which is not known when skb_page_frag_refill() runs, hence the IOMMU mappings cannot be handled at allocation time.

- page_pool_alloc_pages assumes a single NAPI consumer with BH disabled, whereas skb_page_frag_refill() runs from a preemptive context.

- and last not least, we need to handle the dma_alloc_attrs() allocations which don't match pagepool API

Of course all of the above could be modified, but the complexity would be similar to that of implementing dma_pmd_pool, and with a huge risk of breaking existing functionality or missing some path.

[3] DRIVER CHANGES

Quoted 9 lines

Most drivers need no change for rings, transmit buffers, or receive buffers (if they use pagepool). Tx headers are generally mapped on the fly and that is enough to trigger IOTLB thrashing, so most drivers need a small change to implement very cheap tx bounce buffers backed by DMA_PMD pages.

We could avoid the bounce buffers using DMA_PMD for the skb->head region, but that memory is contiguous to skb_shinfo so it would be exposed to IO device access, which may be undesirable for security.

Thanks for the RFC. Here are my notes (some points rephrase what was already said):

- On CoCo VMs it seems that the only way to opt in the IOMMU optimization is to also opt in the copy avoidance which is not always desirable.

- Having the pool generic opens up more visibility from the untrusted host side. Having device based pools at least isolates one device's memory from the rest of the system.

- Also, device driver could help with provisioning just the right amount of memory that is needed. And per device control also means that probably you don't need to map everything RW to the IOMMU.

Thanks,
Dragos

#60 lore raw
Quoted 5 lines · Dragos Tatulea

Hi Luigi,

Quoted 1 line · Luigi Rizzo

Here is a subsystem called DMA_PMD on which I would like feedback on

...

Quoted 7 lines

Thanks for the RFC. Here are my notes (some points rephrase what was already said):

- On CoCo VMs it seems that the only way to opt in the IOMMU optimization is to also opt in the copy avoidance which is not always desirable.

Quoted 7 lines

- Having the pool generic opens up more visibility from the untrusted host side. Having device based pools at least isolates one device's memory from the rest of the system.

- Also, device driver could help with provisioning just the right amount of memory that is needed. And per device control also means that probably you don't need to map everything RW to the IOMMU.

Yes on all three. I am looking into providing more knobs for different levels of opt-in and isolation, so users may adjust them according to the threat models and performance goals.

I am not especially worried about provisioning because the system is already reasonably adaptive, and leveraging existing caches, the waste the waste due to allocating 2MB units can be kept relatively small.

As an example, the update I am working on has the following:
- a lean per-cpu cache that can be attached on top of a dma_pmd_pool, similar to the one used by the buddy allocator. The dma_pmd_pool will hold the 2MB pages, and the caches can buffer smaller sets, reducing the waste. Useful on the tx side.
- on the receive side, one dma_pmd_pool per device will feed all pagepools for that device (typically one per queue).
The pagepool is already a pretty good cache that does not access the allocator often, so once again the waste due to partially used pages is minimized.

cheers
luigi

#61 lore raw

v2 cover PISA: Pre-mapped IOVA Superpage Allocator for DMA and CoCo

In reply to Luigi Rizzo

This is v2 of the RFC previously posted as DMA_PMD [0] (renamed to avoid confusion with CPU page table PMD levels).

PISA stands for "Pre-mapped IOVA Superpage Allocator" and as the name says, it is a specialized memory allocator. Invoked via __GFP_PISA* flag to alloc_pages(), it returns pages ("PISA memory") that make DMA-related operations on that memory a lot more efficient, both in software and in hardware.

Specifically, PISA memory has the following properties:

- it is backed by 2MB contiguous physical pages, so the IOMMU can use large leaf mappings and significantly reduce IOTLB pressure see [1]

- IOMMU mappings are recycled while PISA memory is used for IO buffers, thus greatly reducing IOVA allocation and dma map/unmap costs. This includes cases (e.g. overcommitted VMs or Confidential Compute) where they would trigger expensive VM exits or bounce buffer copies.

- PISA memory is returned to the buddy allocator in background, and only after all existing IOMMU and IOTLB mappings have been flushed. This removes a significant security problem in DMA-FQ, which instead returns pages before flushing the IOTLB, without the performance penalty of strict iommu (DMA) where the flushes are synchronous.

The pitch line remains:

PISA has the performance of identity mapping, guarantees that only active I/O buffers have IOMMU/IOTLB mappings (unlike DMA-FQ), removes bounce-buffer copies in Confidential Computing VMs, and integrates transparently with existing kernel subsystems and drivers.

=== KEY IDEA: A SPECIALIZED MEMORY ALLOCATOR

For avoidance of doubt, PISA is NOT a new buffer cache, page_pool replacement, slab allocator, or custom netdev feature. The kernel already has plenty of specialized caches and pools (page_pool, socket page_frags, SLUB, page cache) built on top of the buddy allocator.

Instead, PISA sits *below* those existing subsystems as a specialized memory provider modeled after alloc_pages() and __free_pages_prepare(). It enforces a few properties on the memory it dispenses so that IOMMU mapping, unmapping, and CoCo page decryption become nearly free:

1. PISA allocates order-N blocks out of physically contiguous 2MB pages that are mapped once per IOMMU domain using 2MB IOMMU leaf entries in a reserved per-domain IOVA window (and decrypted once upfront in CoCo guests). Subsequent dma_map_*() calls resolve the IOVA with a simple window offset calculation, and dma_unmap_*() is a no-op.

2. Freed blocks are intercepted in __free_pages_prepare() and recycled back into their PISA allocator while their 2MB IOMMU mappings remain active. A 2MB page is returned to the buddy allocator only when all of its blocks are idle, its IOMMU mappings have been removed from all domains, a synchronous IOTLB flush has completed, and an RCU grace period has elapsed.

3. Callers allocate from per-NUMA-node PISA allocators using standard page allocator calls with __GFP_PISA_RW (DMA_BIDIRECTIONAL) or __GFP_PISA_RO (DMA_TO_DEVICE, mapped IOMMU_READ-only so devices cannot overwrite shared/adjacent data), falling back to the buddy allocator on failure.

Because PISA operates at the page allocator and DMA mapping boundary, existing clients require minimal changes. For example, the entire patch integrating page_pool with PISA (patch 13/25) is just 3 lines:

  --- a/net/core/page_pool.c
  +++ b/net/core/page_pool.c
  @@ -16,6 +16,7 @@
   #include <net/page_pool/helpers.h>
   #include <net/page_pool/memory_provider.h>
   #include <net/xdp.h>
  +#include <linux/pisa.h>
  @@ -622,6 +623,8 @@ static noinline netmem_ref __page_pool_alloc_netmems_slow(...)
   	if ((gfp & GFP_ATOMIC) == GFP_ATOMIC)
   		gfp |= __GFP_NOWARN;
  +	if (dma_map)
  +		gfp |= pisa_rx_gfp(pool->p.dev);

Similarly:
- Coherent rings/queues (dma_alloc_attrs()) are served from the per-node order-0 PISA allocator when dev->pisa_coherent is enabled; no driver changes needed.
- Socket TX page fragments (skb_page_frag_refill()) use a per-task page_frag fed by __GFP_PISA_RO when the egress device has pisa_tx_bufs enabled; no driver changes needed.
- Small TX skb heads (kmalloc_reserve()) use a parallel skbuff_small_head_pisa SLUB cache backed by zeroed, read-only PISA folios (SLAB_CACHE_PISA_RO) when pisa_tx_skb_heads is enabled. This eliminates the per-driver TX header bounce-buffer patches from v1.
- TX MSG_ZEROCOPY, O_DIRECT, and buffered disk I/O migrates or allocates order-0 user and page-cache folios from per-node PISA allocators so zero-copy network sends and storage I/O also use 2MB IOMMU mappings.

All features are strictly opt-in per device via /sys/devices/.../pisa_{coherent,rx_bufs,tx_bufs,tx_skb_heads} (and pisa.user_max_4K_pages for user/page-cache folios). Until a device opts in, PISA is gated off by a static key and allocates no metadata.

=== CHANGES SINCE v1 [0]

I have make use and applied several comments and suggestions received on the previous version. The changes are massive so perhaps it makes sense to look at the new code in isolation, unless you have already revised in detail the previous version.

A high level summary is the following:

- Renamed DMA_PMD to PISA (CONFIG_PISA, include/linux/pisa.h, drivers/iommu/pisa-*.c, /sys/devices/.../pisa_*).

- Hooked __GFP_PISA_RO and __GFP_PISA_RW into __alloc_frozen_pages_noprof() and alloc_pages_bulk_noprof(), replacing custom pool calls in page_pool and socket TX refill.

- Added lockless per-CPU block caches (pisa_enable_pcp()) in front of the per-node order-0 RW and SKB_FRAG_PAGE_ORDER RO allocators.

- Added SLAB_CACHE_PISA_RO in SLUB and skbuff_small_head_pisa for small TX skb heads, dropping the per-driver TX header bounce-buffer patches.

- Added PISA support for MSG_ZEROCOPY user pages (madvise(MADV_PISA) and automatic upgrade on send) and block/page-cache I/O (O_DIRECT and buffered reads/writes), plus age/waste-based compaction and scrub migration (pisa.wasted_pct, pisa.old_ms, pisa.scrub_migrate).

- Made metadata table initialization and static key activation lazy on first device opt-in.

=== PERFORMANCE BENEFITS

Your mileage may vary. Enabling the IOMMU may have no throughput impact until system components (bus, IOTLB, CPU) become overloaded. Aside from throughput reduction, one key metric is IOTLB effectiveness. Below are SMMU performance counters on a large ARM64 system with 2x200G NICs running bidirectional traffic:

    === DMA-FQ MODE (total throughput ~440Gbps)
    25,757,488      smmuv3_pmcg_*/event=0x80/   IOTLB lookups
    16,634,941      smmuv3_pmcg_*/event=0x81/   IOTLB misses

    === PISA on top of strict DMA (total throughput ~745Gbps)
    22,693,218      smmuv3_pmcg_*/event=0x80/   IOTLB lookups
        30,536      smmuv3_pmcg_*/event=0x81/   IOTLB misses

The 2MB mappings make IOTLB misses almost non-existent because the working set of IOTLB entries is reduced by a factor of ~512.

=== NOTES

[0] v1 (DMA_PMD):

    https://lore.kernel.org/all/[email protected]/

[1] IOMMU IMPACT AND IOTLB THRASHING
Documented in detail in Documentation/core-api/pisa.rst. In short, there are three main costs with the IOMMU:
- CPU cost for dma_map/unmap
- CPU cost and latency for synchronous IOTLB flush (required for security)
- IOTLB thrashing when the working set of 4KB pages exceeds IOTLB capacity, causing IOMMU page walks that backpressure PCIe/bus traffic (30..60% throughput drop on high-speed NICs). See also:
https://lore.kernel.org/all/[email protected]/
https://www.ncbi.nlm.nih.gov/pmc/articles/PMC10280580/

[2] WHY NOT USE PAGE_POOL FOR EVERYTHING
page_pool is a consumer of PISA (via __GFP_PISA_RW), not a replacement:
- page_pool does not split 2MB pages into order-N blocks or manage shared 2MB IOMMU mappings across domains;
- page_pool pages cannot be managed by arbitrary get_page()/put_page() callers (socket TX fragments, SLUB slabs, user/page-cache folios);
- page_pool requires a single NAPI consumer with BH disabled and a known device at allocation time, whereas socket TX, SLUB, and dma_alloc_attrs() run in process/preemptible context across arbitrary devices.

Luigi Rizzo (25):
iommu/dma: Introduce CONFIG_PISA and metadata table iommu/dma: Add PISA allocator lifecycle and page recycle hook iommu/dma: Add per-NUMA-node PISA page reservoir iommu/dma: Add PISA block allocation
iommu/dma: Add global cap and shrinker for PISA pages iommu/dma: Reserve a per-domain IOVA window for PISA pages iommu/dma: Release PISA domain mappings on domain teardown iommu/dma: Use per-domain IOVA window to map PISA memory driver core: Add per-device pisa_* sysfs attributes for PISA optin iommu/dma: Use PISA for coherent DMA allocations iommu/dma: Add per-CPU block caches to PISA allocators net/core: Use per-node PISA allocators for skb_page_frag_refill() net/core: Use PISA for page_pool memory
iommu/dma: Support decrypted PISA pages
iommu/dma: Add background page scrubber for PISA allocators mm/slub: Add SLAB_CACHE_PISA_RO for PISA-backed slab caches
net: Allocate small skb heads from PISA
iommu/dma: Migrate user pages into PISA for TX zerocopy iommu/dma: Stop recycling old PISA pages when allocator waste is high net/libeth: Use GFP_KERNEL when pre-filling RX rings net/gve: Use GFP_KERNEL when pre-filling RX rings
net/gve: Use PISA memory for RX buffers
block, mm, iommu/dma: Support PISA for disk I/O and scrub migration
Documentation: Add PISA architecture documentation iommu/dma: Add PISA statistics and debugfs

 .../admin-guide/kernel-parameters.txt         |    6 +
 Documentation/core-api/index.rst              |    1 +
 Documentation/core-api/pisa.rst               |  426 ++++
 block/bio.c                                   |   46 +
 drivers/base/core.c                           |   78 +
 drivers/iommu/Kconfig                         |   34 +
 drivers/iommu/Makefile                        |    5 +
 drivers/iommu/dma-iommu.c                     |   48 +-
 drivers/iommu/dma-iommu.h                     |   16 +
 drivers/iommu/iommu.c                         |   10 +-
 drivers/iommu/pisa-alloc.c                    | 2063 +++++++++++++++++
 drivers/iommu/pisa-kunit.c                    |  669 ++++++
 drivers/iommu/pisa-map.c                      |  553 +++++
 drivers/iommu/pisa-meta.c                     |  300 +++
 drivers/iommu/pisa-node.c                     |  378 +++
 drivers/iommu/pisa-priv.h                     |  511 ++++
 drivers/iommu/pisa-user.c                     |  662 ++++++
 .../ethernet/google/gve/gve_buffer_mgmt_dqo.c |    7 +-
 drivers/net/ethernet/google/gve/gve_rx.c      |   40 +-
 include/linux/device.h                        |   27 +
 include/linux/gfp_types.h                     |   17 +-
 include/linux/netdevice.h                     |    4 +
 include/linux/pisa.h                          |  367 +++
 include/linux/sched.h                         |    4 +
 include/linux/skbuff.h                        |    2 +
 include/linux/slab.h                          |   10 +
 include/linux/swap.h                          |    1 +
 include/net/libeth/rx.h                       |   11 +-
 include/net/sock.h                            |  143 ++
 include/trace/events/mmflags.h                |   11 +-
 include/uapi/asm-generic/mman-common.h        |    2 +
 kernel/dma/direct.c                           |   14 +-
 kernel/exit.c                                 |    2 +
 kernel/fork.c                                 |    2 +
 mm/filemap.c                                  |   15 +-
 mm/madvise.c                                  |   11 +
 mm/page-writeback.c                           |    8 +
 mm/page_alloc.c                               |   59 +
 mm/readahead.c                                |    5 +-
 mm/slab.h                                     |    3 +-
 mm/slab_common.c                              |    5 +-
 mm/slub.c                                     |   14 +-
 net/core/datagram.c                           |   85 +-
 net/core/page_pool.c                          |    3 +
 net/core/skbuff.c                             |   42 +-
 net/core/sock.c                               |   62 +-
 net/ipv4/esp4.c                               |    4 +-
 net/ipv4/ip_output.c                          |   19 +-
 net/ipv4/tcp.c                                |   17 +-
 net/ipv4/tcp_output.c                         |   12 +-
 net/ipv6/esp6.c                               |    4 +-
 net/ipv6/ip6_output.c                         |   19 +-
 52 files changed, 6784 insertions(+), 73 deletions(-)
 create mode 100644 Documentation/core-api/pisa.rst
 create mode 100644 drivers/iommu/pisa-alloc.c
 create mode 100644 drivers/iommu/pisa-kunit.c
 create mode 100644 drivers/iommu/pisa-map.c
 create mode 100644 drivers/iommu/pisa-meta.c
 create mode 100644 drivers/iommu/pisa-node.c
 create mode 100644 drivers/iommu/pisa-priv.h
 create mode 100644 drivers/iommu/pisa-user.c
 create mode 100644 include/linux/pisa.h
Signature · 1 line
2.56.0.542.g3ef89b7020-goog
#62 lore raw

v3 cover PISA: Pre-mapped IOVA Superpage Allocator for DMA and CoCo

This is v3 of the RFC previously posted as DMA_PMD [0], now renamed PISA ("Pre-mapped IOVA Superpage Allocator"). The text below follows Documentation/core-api/pisa.rst (patch 25/25), which has the details.

=== OVERVIEW

PISA is an extension to the page allocator: requests with __GFP_PISA return memory that makes I/O-related operations cheaper when using DMA-FQ, DMA, or Confidential Computing swiotlb. I/O devices can individually opt in to use PISA for specific buffer classes (e.g. read or write data, headers, zerocopy, ...). Relevant kernel subsystems (mm, iommu, dma, disk I/O, page cache, the network stack) are modified to make use of PISA memory for opt-in devices.

The design and implementation have the following main goals:

- no changes to individual device drivers (or minimal changes for NIC drivers that use custom RX page allocators)
- minimize changes to base code: in most cases one or a few lines of code
- safety: PISA memory is only used for devices that opt in, and it is returned to the buddy allocator only after IOMMU mappings and IOTLB entries have been flushed
- no dependency on struct page or struct folio
- compile-time option to disable or enable PISA
- zero runtime overhead when no devices opt in (static keys and inline hooks)
- minimal overhead when in use (direct PFN lookup in a flat metadata table)
- keep memory overhead as low as possible (adaptive shrinking and compaction of memory)

=== MECHANISMS

PISA returns order-N blocks backed by 2MB physically contiguous pages, so it can use 2MB IOMMU leaves and reduce the IOTLB pressure by up to 512x. PISA maps memory in pre-allocated per-domain IOVA ranges, and recycles blocks and mappings until the 2MB page is returned to the buddy allocator. This makes most of dma map/unmap a no-op, also avoiding related VM exits in overcommitted VMs. In Confidential Computing VMs, PISA pages are also decrypted, removing the need for bounce buffers.

The kernel identifies devices and sockets that use an IOMMU or Confidential Computing and have opted into PISA, and allocates (or migrates) I/O buffers using PISA memory so that DMA mapping and unmapping are mostly no-ops. All the above makes performance comparable to identity mode, with isolation better than DMA-FQ and comparable to DMA.

Devices that do not opt in continue to use their native DMA/DMA-FQ mode.

=== PERFORMANCE

Your mileage may vary. Enabling the IOMMU will increase load on various system components (CPU, IOTLB, bus latency, increased locking serialization) but the impact on throughput will only show up when one or more of these resources become fully congested.

Some anecdotal data:

NVMe: fio throughput in IOPS, 4KB random reads, O_DIRECT, on an x86 system with 8 NVMe disks capable of 1.7M IOPS each

    drives      DMA     PISA    identity
    1           380K    1.7M    1.7M
    8           1.3M    13.5M   13.5M

Network: throughput in Gbps on a Confidential Computing VM, 200G NIC

    flows/mtu   swiotlb PISA
    1/1460      36      65
    1/4148      45      65
    16/1460     130     170
    16/4148     130     182
    256/1460    140     170
    256/4148    140     182

Network: throughput and SMMU performance counters on a large ARM64 system with 2x200G NICs running bidirectional traffic (this shows the effect of IOTLB thrashing)

    === DMA-FQ (total throughput ~440Gbps)
    25,757,488      smmuv3_pmcg_*/event=0x80/   IOTLB lookups
    16,634,941      smmuv3_pmcg_*/event=0x81/   IOTLB misses

    === PISA on top of strict DMA (total throughput ~745Gbps)
    22,693,218      smmuv3_pmcg_*/event=0x80/   IOTLB lookups
        30,536      smmuv3_pmcg_*/event=0x81/   IOTLB misses

=== COMPARISON WITH STANDARD DMA MODES

PISA layered on top of strict DMA, compared with identity, DMA-FQ and strict DMA ( > means PISA is better ):

identity DMA-FQ DMA

  dma_map cost                          ~=         >>       >>
  dma_unmap cost                        ==         >>       >>
  IOTLB friendliness                    na         >>       >>
  Buffer shared across domains          na         <=       <=
  Memory remains accessible to device   >>         >>       <=
  Needs bounce buffers                  >>         >>       >>
  Page alloc/free cost                  >=         >=       >=

- dma_map/dma_unmap cost: once a 2MB PISA page is mapped in a domain's reserved IOVA window, dma_map_*() is an offset lookup and dma_unmap_*() is a no-op, avoiding IOVA tree allocation, page-table walks, and synchronous IOTLB shootdowns.
- IOTLB friendliness: 2MB IOMMU leaves reduce IOTLB pressure by up to 512x
- Buffer shared across domains: even in DMA-FQ and DMA, sub-page buffers from task_frag or skb head slabs can cause the underlying page to be mapped across multiple domains. PISA exhibits the same behavior, just at 2MB granularity.
- Memory remains accessible to device: in identity mode all of RAM is always accessible. In DMA-FQ, pages returned to the buddy allocator remain accessible until the flush queue drains. PISA and DMA both unmap the page and perform a synchronous IOTLB flush before returning memory to the buddy allocator. In all modes, pagepool keeps receive buffers mapped and accessible to the device while queued in the rx socket buffer. PISA expands this visibility also to page cache and O_DIRECT pages.
- Needs bounce buffers: in Confidential Computing VMs, PISA allocators pre-decrypt 2MB pages in place, avoiding swiotlb bounce-buffer copies.

=== BACKGROUND

Enabling the IOMMU costs CPU to install and remove PTEs on dma_map/unmap, CPU and latency to flush the IOTLB, and higher DMA latency from IOMMU page walks when the working set exceeds the IOTLB size. The last one is among the biggest bottlenecks for high speed devices: network devices have very little IOVA locality, which makes the IOTLB almost completely ineffective.

The known mitigations are recycling buffers and mappings (common for queues and RX buffers, but not for network TX buffers), lazy IOTLB flush (DMA-FQ, which recycles memory without waiting for the flush), and larger mappings (not currently pursued by the kernel). PISA combines them:

- intercept the small set of functions used to allocate, map, unmap, and free device-accessible memory (rings and buffers)
- return memory backed by physically contiguous 2MB pages and 2MB IOMMU mappings
- heavily recycle memory and mappings
- wait until the IOTLB has been flushed before returning unused PISA pages to the system

=== IMPLEMENTATION AND CODE LAYOUT

PISA is implemented by a few groups of commits:

- mm: infrastructure for per-page metadata (no dependency on struct page), hook into alloc_pages(), PISA optimizations (per-cpu caches, shrinker, background zeroing)
- driver core: per-device sysfs entries to opt in
- iommu/dma: manage PISA IOVA ranges and intercept map/unmap
- block, mm, net: transparently upgrade pages to PISA for disk I/O and network tx zerocopy
- net: identify sockets that need PISA pages, hook PISA into page frags, skb heads, page_pool

The code layout now matches the "allocator" nature of PISA: most of the code is in mm/, and iommu and net only carry subsystem-specific changes.

mm/pisa-*.c metadata, allocators, per-node
reservoir, user and page-cache pages (~5100 lines)
drivers/iommu/pisa-map.c IOVA ranges, map/unmap

                                         (~500 lines)

net/core/pisa-net.c, include/net/pisa.h
socket and skb glue (~450 lines)
include/linux/pisa*.h public API and inline hooks

The functions that need to be intercepted are few:

- page_pool_dev_alloc*(), socket TX page frags, __free_pages()
- dma_alloc_attrs(), dma_map_*(), dma_unmap_*()
- __filemap_get_folio_mpol(), ractl_alloc_folio(), writeback_get_folio(), __bio_iov_iter_get_pages(), madvise()

and most devices automatically inherit the benefits. Fast-path hooks are guarded by static keys: pisa_key remains disabled (a single NOP) until the first device opts in via sysfs. NIC drivers that do not use page_pool need a few lines to pass __GFP_PISA_RW when allocating RX buffers; gve is converted as an example.

=== INTERNAL MECHANISMS

- PISA metadata: each 2MB page used for PISA memory is identified by a compact index (slot). Two flat arrays in virtual address space, with holes mapped read-only to a zero page:

1. pisa_pfn2slot[pfn >> PISA_ORDER] (4 bytes per 2MB physical frame) packs the status flags and the slot. It is populated for system RAM at boot or on hotplug, and grows by 4KB for each 2GB of physical RAM regardless of RAM layout.

2. pisa_meta_array[slot] (256 bytes per 2MB PISA page) holds struct
pisa_meta: base PFN, flags, free/clean/dirty subpage bitmaps, the bitmap of IOMMU domains with an active 2MB mapping, and list/RCU linkage. Backing pages are allocated on demand up to pisa.max_pages (default 1/8th of RAM).

- Per-domain reserved IOVA ranges: PISA reserves on each domain an IOVA range covering the slot table, and a page is mapped on demand at offset slot * PISA_SIZE in each domain that requires it. This makes PA-IOVA translation just an addition, uniquely identifies PISA IOVAs, and does not expose physical addresses.

- alloc_pages() compatible allocator: a pisa_alloc object serves fixed-order allocations, returning objects fully compatible with those of the page allocator. alloc_pages() and related requests are routed to PISA via __GFP_PISA, which makes it easy to select PISA pages where needed (two lines in page_pool, similar small changes in page frag refill and disk I/O buffers).

- Safe release of memory: freed blocks return to PISA with mappings still active. When all blocks of a 2MB page are unused the page becomes idle; idle pages above pisa.max_idle are released after pisa.idle_ms, or by the shrinker: mappings are removed, a synchronous IOTLB flush is issued, and after an RCU grace period (and re-encryption if needed) the page is returned to the buddy allocator.

- Memory compaction: partially allocated 2MB pages are classified as dense (preferred for new allocations) or sparse (left to drain). For user pages, pisa.scrub_migrate also migrates live 4KB pages out of old sparse 2MB pages in the background.

=== MODIFIED KERNEL APIS AND CONTROLS

Opt-in is per device, through /sys/devices/.../pisa_{coherent,rx_bufs,tx_bufs,tx_skb_heads,tx_zerocopy}.

- Streaming DMA map and unmap: a buffer belonging to a PISA page is mapped via the domain's reserved window with a simple addition, typically reusing existing mappings; unmap is a range check and a no-op. Under dma-direct, decrypted PISA pages are mapped without swiotlb bounce.
- Coherent DMA (pisa_coherent): sleepable allocations up to 2MB are carved out of the per-node order-0 allocator.
- Network receive buffers (pisa_rx_bufs): a two-line change in page_pool adds __GFP_PISA_RW, falling back to the buddy allocator on exhaustion.
- Socket TX page fragments (pisa_tx_bufs): fragments come from PISA pages mapped DMA_TO_DEVICE, only for data routed to an opt-in device with a DMA parent. Loopback, virtual devices, kTLS, sockmap, KCM and MPTCP use ordinary pages.
- Small skb heads (pisa_tx_skb_heads): served by an skbuff_small_head_pisa slab cache backed by PISA memory mapped DMA_TO_DEVICE. Never used in Confidential Computing, where it would expose kernel pointers; tx-copybreak avoids the swiotlb cost there.
- Zerocopy receive: RX buffers from PISA pages can be mapped into user space by TCP_ZEROCOPY_RECEIVE.
- Zerocopy transmit (pisa_tx_zerocopy): MSG_ZEROCOPY sends migrate eligible user pages into DMA_TO_DEVICE PISA blocks on a best-effort basis. With pisa_tx_bufs also set, TCP copies the pages that could not be migrated.
- User and disk I/O pages: madvise(MADV_PISA) migrates private anonymous pages into PISA and MADV_NOPISA migrates them back. For block devices with pisa_rx_bufs (reads) or pisa_tx_bufs (writes) on a parent device, new order-0 page-cache folios are allocated from PISA, and writeback and direct-I/O bio preparation migrate eligible folios.

Global controls are pisa.* parameters: max_pages, reservoir_max, max_idle, idle_ms, pcp_batch, compact, target_usage_percent, old_ms, scrub_max, scrub_migrate, user_max_pages. Counters are in /sys/kernel/debug/pisa/allocs.

=== LIMITATIONS

- Not compatible with PREEMPT_RT (enforced at compile time).
- Only DMA-coherent devices can use PISA (enforced at runtime).
- IOMMU mappings follow the direction the allocator was created with:
descriptor queues and receive buffers are DMA_BIDIRECTIONAL, disk and network write buffers and socket TX fragments are DMA_TO_DEVICE.

=== CHANGES SINCE v2 [1]

The changes are too many to list in detail; at a high level:

- Code layout: the allocator moved from drivers/iommu/pisa-*.c to mm/pisa-*.c (and CONFIG_PISA to mm/Kconfig). Only the IOVA window and map/unmap code is left in drivers/iommu/pisa-map.c, and the network hooks moved from include/net/sock.h to include/net/pisa.h and net/core/pisa-net.c. See CODE LAYOUT.
- Flags renamed to __GFP_PISA and __GFP_PISA_RW
- Reworked metadata: a flat pfn-indexed table plus compact per-page slots, with the per-domain IOVA window indexed by slot. Saves one load access in the hot paths, and
removes several tuning knobs while allowing 57bit address space with negligible memory overhead
- Net: the opt-in flags of the leaf devices are cached on struct net_device, and MSG_ZEROCOPY migration has its own per-device knob, pisa_tx_zerocopy.
- Confidential Computing: added arm64 Realms support.
- Compaction is driven by a target usage (pisa.target_usage_percent) instead of pisa.wasted_pct.
- Series reorganized (mm first, then iommu/dma, block, net, drivers), with the three IOVA window patches merged into one.
- Fixes for the issues reported on v2 by the automated review.
- Added NVMe and Confidential Computing results.

=== CHANGES SINCE v1 [0]

v1 presented DMA_PMD as a set of pools and an arena under drivers/iommu, called explicitly by page_pool, the socket code and four NIC drivers.

- Renamed DMA_PMD to PISA.
- Restructured as an extension to the page allocator: callers pass __GFP_PISA / __GFP_PISA_RW to alloc_pages() instead of calling a dma_pmd_pool, and the code moved from drivers/iommu/ to mm/ (see CODE LAYOUT).
- Per-NUMA-node allocators with per-CPU caches replace the per-CPU and per-queue pools; the dma_pmd_arena for dma_alloc_attrs() is merged into the per-node order-0 allocator.
- The per-driver TX header bounce buffers (gve, mlx5, idpf, bnxt) are gone, replaced by a PISA-backed slab cache for small skb heads.
- New: user pages (MADV_PISA, MSG_ZEROCOPY) and disk I/O (O_DIRECT and page cache), with compaction and background migration.
- Opt-in is through per-device pisa_* attributes and pisa.* parameters; metadata and static keys are activated on the first opt-in.

[1] v2 (PISA)

    https://lore.kernel.org/all/[email protected]/
[0] v1 (DMA_PMD):
    https://lore.kernel.org/all/[email protected]/

Luigi Rizzo (25):
mm: Introduce CONFIG_PISA and metadata table
mm: Add PISA allocator lifecycle and page recycle hook
mm: Add per-NUMA-node PISA page reservoir mm/page_alloc: Extend alloc_pages() to __GFP_PISA and PISA block
allocation
mm: Add global cap and shrinker for PISA pages iommu/dma: Map PISA memory in a per-domain IOVA window driver core: Add per-device pisa_* sysfs attributes for PISA optin iommu/dma: Use PISA for coherent DMA allocations
mm: Add per-CPU block caches to PISA allocators
mm: Add background page scrubber for PISA allocators
mm: Migrate user pages into PISA
block, mm: Support PISA for disk I/O and scrub migration
net: Cache leaf PISA TX flags on struct net_device
net: Use per-node PISA allocators for skb_page_frag_refill()
net: Use PISA for page_pool memory
mm/slub: Add SLAB_CACHE_PISA_RO for PISA-backed slab caches
net: Allocate small skb heads from PISA
net: Migrate user pages into PISA for MSG_ZEROCOPY
mm, iommu/dma: Support decrypted PISA pages
arm64/mm, mm: Support decrypted PISA pages in Realms
mm: Add PISA statistics and debugfs
net/libeth: Use GFP_KERNEL when pre-filling RX rings net/gve: Use GFP_KERNEL when pre-filling RX rings net/gve: Use PISA memory for RX buffers
Documentation: Add PISA architecture documentation

 .../admin-guide/kernel-parameters.txt         |    7 +
 Documentation/core-api/index.rst              |    1 +
 Documentation/core-api/pisa.rst               |  485 +++++
 arch/arm64/include/asm/pgtable.h              |   28 +-
 block/bio.c                                   |    9 +
 drivers/base/core.c                           |   78 +
 drivers/iommu/Makefile                        |    3 +
 drivers/iommu/dma-iommu.c                     |   49 +-
 drivers/iommu/iommu.c                         |    7 +-
 drivers/iommu/pisa-map.c                      |  488 +++++
 .../ethernet/google/gve/gve_buffer_mgmt_dqo.c |    8 +-
 drivers/net/ethernet/google/gve/gve_rx.c      |   40 +-
 include/linux/device.h                        |   32 +
 include/linux/gfp_types.h                     |   14 +-
 include/linux/huge_mm.h                       |    7 +
 include/linux/netdevice.h                     |    4 +
 include/linux/pisa-iommu.h                    |  141 ++
 include/linux/pisa-mm.h                       |  205 ++
 include/linux/pisa.h                          |  356 ++++
 include/linux/sched.h                         |    4 +
 include/linux/slab.h                          |   10 +
 include/linux/swap.h                          |    1 +
 include/net/libeth/rx.h                       |   11 +-
 include/net/pisa.h                            |  204 ++
 include/trace/events/mmflags.h                |   11 +-
 include/uapi/asm-generic/mman-common.h        |    2 +
 kernel/dma/direct.c                           |   11 +
 kernel/exit.c                                 |    2 +
 kernel/fork.c                                 |    2 +
 mm/Kconfig                                    |   35 +
 mm/Makefile                                   |    3 +
 mm/filemap.c                                  |   12 +-
 mm/huge_memory.c                              |   36 +-
 mm/ksm.c                                      |    3 +-
 mm/madvise.c                                  |   19 +
 mm/memory.c                                   |    8 +-
 mm/migrate.c                                  |    3 +-
 mm/page-writeback.c                           |    9 +
 mm/page_alloc.c                               |   10 +
 mm/pisa-alloc.c                               | 1758 +++++++++++++++++
 mm/pisa-kunit.c                               |  778 ++++++++
 mm/pisa-meta.c                                |  834 ++++++++
 mm/pisa-node.c                                |  567 ++++++
 mm/pisa-priv.h                                |  319 +++
 mm/pisa-user.c                                |  898 +++++++++
 mm/readahead.c                                |    3 +-
 mm/slab.h                                     |    3 +-
 mm/slab_common.c                              |    2 +-
 mm/slub.c                                     |   23 +-
 mm/swapfile.c                                 |    3 +-
 mm/userfaultfd.c                              |    7 +-
 net/core/Makefile                             |    1 +
 net/core/datagram.c                           |   17 +-
 net/core/page_pool.c                          |    3 +
 net/core/pisa-net.c                           |  264 +++
 net/core/skbuff.c                             |   33 +-
 net/core/sock.c                               |   31 +-
 net/ipv4/esp4.c                               |    7 +-
 net/ipv4/ip_output.c                          |   20 +-
 net/ipv4/raw.c                                |    6 +-
 net/ipv4/tcp.c                                |   17 +-
 net/ipv4/tcp_output.c                         |   14 +-
 net/ipv6/esp6.c                               |    7 +-
 net/ipv6/ip6_output.c                         |   20 +-
 net/ipv6/raw.c                                |    6 +-
 65 files changed, 7907 insertions(+), 92 deletions(-)
 create mode 100644 Documentation/core-api/pisa.rst
 create mode 100644 drivers/iommu/pisa-map.c
 create mode 100644 include/linux/pisa-iommu.h
 create mode 100644 include/linux/pisa-mm.h
 create mode 100644 include/linux/pisa.h
 create mode 100644 include/net/pisa.h
 create mode 100644 mm/pisa-alloc.c
 create mode 100644 mm/pisa-kunit.c
 create mode 100644 mm/pisa-meta.c
 create mode 100644 mm/pisa-node.c
 create mode 100644 mm/pisa-priv.h
 create mode 100644 mm/pisa-user.c
 create mode 100644 net/core/pisa-net.c

base-commit: 20eef29b7c8465ac98d7dd6d6f2ac07a8d8056ca

Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#63 lore raw

RFC PATCH v3 1/25 mm: Introduce CONFIG_PISA and metadata table

PISA ("Pre-mapped IOVA Superpage Allocator") is an extension to the page
allocator: requests with __GFP_PISA return memory that makes I/O-related operations cheaper when using DMA-FQ, DMA, or Confidential Computing swiotlb. I/O devices can individually opt in to use PISA for specific buffer classes (e.g. read or write data, headers, zerocopy). The relevant kernel subsystems (mm, iommu, dma, disk I/O, page cache, the network stack) are modified to use PISA memory for devices that opt in.

PISA returns order-N blocks backed by 2MB physically contiguous pages, so it can use 2MB IOMMU leaves and reduce IOTLB pressure by up to 512x. It maps memory in pre-allocated per-domain IOVA ranges, and recycles blocks and mappings until the 2MB page is returned to the buddy allocator. This makes most of dma map/unmap a no-op, also avoiding the related VM exits in overcommitted VMs. In Confidential Computing VMs, PISA pages are also decrypted, removing the need for bounce buffers. Performance is comparable to identity mode, with isolation better than DMA-FQ and comparable to DMA.

The design has the following main goals:
- no changes to individual device drivers (or minimal changes for NIC drivers that use custom RX page allocators)
- minimal changes to base code: in most cases one or a few lines
- safety: PISA memory is only used for devices that opt in, and it is returned to the buddy allocator only after IOMMU mappings and IOTLB entries have been flushed
- no dependency on struct page or struct folio
- a compile-time option to disable or enable PISA
- zero runtime overhead when no devices opt in (static keys and inline hooks), minimal overhead when in use (direct PFN lookup in a flat metadata table)
- memory overhead as low as possible (adaptive shrinking and compaction)

Devices that do not opt in keep using their native DMA/DMA-FQ mode. See Documentation/core-api/pisa.rst, added at the end of the series.

Add a CONFIG_PISA option, enabled only on supported kernels (64bit, !PREEMPT_RT) and introduce two metadata tables, populated on demand, to hold per-2MB buffer state:

- pisa_pfn2slot[pfn >> PISA_ORDER] to quickly access flags and a compact page index (slot). Covers 57 bit address space with only 12KB of page tables (unbacked holes are mapped to the shared read-only zero page), plus 4KB for each 2GB of RAM.

- pisa_meta_array[slot] (256B per slot, 4KB of RAM per 32MB of active PISA buffers)

Also add a built-in KUnit test suite (CONFIG_PISA_META_KUNIT_TEST) exercising initialization idempotency, PFN/physical round-trip lookups, out-of-bounds physical address handling, and PISA membership toggling.

---
 include/linux/pisa-iommu.h |  40 +++
 include/linux/pisa.h       | 114 +++++++
 mm/Kconfig                 |  34 +++
 mm/Makefile                |   3 +
 mm/pisa-kunit.c            | 112 +++++++
 mm/pisa-meta.c             | 603 +++++++++++++++++++++++++++++++++++++
 mm/pisa-priv.h             |  61 ++++
 7 files changed, 967 insertions(+)
 create mode 100644 include/linux/pisa-iommu.h
 create mode 100644 include/linux/pisa.h
 create mode 100644 mm/pisa-kunit.c
 create mode 100644 mm/pisa-meta.c
 create mode 100644 mm/pisa-priv.h
include/linux/pisa-iommu.h new file +40 -0
new file mode 100644
index 0000000000000..7a04523b28b4c
@@ -0,0 +1,40 @@
+/* SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause */
+/* PISA page metadata, shared by mm/pisa-*.c and drivers/iommu/pisa-map.c. */
+#ifndef _LINUX_PISA_IOMMU_H
+#define _LINUX_PISA_IOMMU_H
+
+#include <linux/bitmap.h>
+#include <linux/dma-direct.h>
+#include <linux/list.h>
+#include <linux/llist.h>
+#include <linux/pisa.h>
+
+struct pisa_alloc;
+
+#ifdef CONFIG_PISA
+
+/* PISA page byte size and alignment mask. */
+#define PISA_SIZE		(1UL << PISA_SHIFT)
+#define PISA_MASK		(~(PISA_SIZE - 1))
+
+/* size of struct pisa_meta (256B, power of 2) and max blocks per PISA page. */
+#define _PISA_META_SHIFT	8
+#define _PISA_META_SIZE		(1U << _PISA_META_SHIFT)
+#define _PISA_MAX_BLOCKS	512U
+
+/* Metadata for a single PISA page in @pisa_meta_array (indexed by @slot). */
+struct pisa_meta {
+	unsigned long flags;	/* PISA_ACTIVE / PISA_QUARANTINED / PISA_DECRYPTED */
+	unsigned long base_pfn;	/* base PFN of this PISA page */
+	u32 slot;		/* dense index in @pisa_meta_array and IOVA windows */
+	struct list_head list;	/* node in @pa lists or pisa_node.pages */
+} __aligned(_PISA_META_SIZE);
+
+static_assert(sizeof(struct pisa_meta) == _PISA_META_SIZE);
+
+extern struct pisa_meta *pisa_meta_array;
+
+struct pisa_meta *pisa_meta_of_pfn(unsigned long pfn);
+
+#endif /* CONFIG_PISA */
+#endif /* _LINUX_PISA_IOMMU_H */
include/linux/pisa.h new file +114 -0

114 lines not on this page · raw message

mm/Kconfig +34 -0
index afff1b25b5438..6e7811569d33a 100644
@@ -1431,6 +1431,40 @@ config IOMMU_MM_DATA
 config EXECMEM
 	bool
 
+# Pre-mapped IOVA Superpage Allocator
+config PISA
+	bool "Pre-mapped IOVA Superpage Allocator"
+	depends on (X86_64 && !UML) || (ARM64 && ARM64_4K_PAGES && PGTABLE_LEVELS >= 4)
+	depends on SPARSEMEM && !PREEMPT_RT
+	default y
+	help
+	  PISA is a specialized memory allocator with an API similar to
+	  alloc_pages(). For devices that opt-in, it provides DMA-able
+	  pages backed by 2MB physically contiguous pages, and mapped in
+	  the IOMMU maps with a single leaf PTE of the same size (or with
+	  smaller ones if the IOMMU has no such page size). Mapping, unmapping
+	  and IOTLB flushing are done lazily to reduce CPU overhead.
+	  The large mappings greatly reduce IOTLB usage. As in strict iommu
+	  mode, pages are returned to the buddy allocator only when any existing
+	  mappings have been removed and IOTLB flushed.
+	  Uses 4KB of metadata for each 32MB of PISA buffers, allocated on demand.
+
+	  The config option enforces requirements (2MB large pages and !PREEMPT_RT) at compile
+	  time. Other constraints (e.g. dma-coherent devices) are verified at runtime.
+
+	  If unsure, say Y.
+
+config PISA_META_KUNIT_TEST
+	bool "KUnit test for PISA metadata table (built-in)" if !KUNIT_ALL_TESTS
+	depends on PISA && KUNIT=y
+	default KUNIT_ALL_TESTS
+	help
+	  Builds KUnit unit tests for the sparse, per-PISA-frame metadata table,
+	  and PISA page allocators in mm/pisa-*.c, verifying metadata
+	  lookup, allocator recycling, and coherent block allocation.
+
+	  If unsure, say N.
+
 config NUMA_MEMBLKS
 	bool
 
mm/Makefile +3 -0
index 2a3ec53d62eef..55dff84df1555 100644
@@ -146,6 +146,9 @@ obj-$(CONFIG_PAGE_REPORTING) += page_reporting.o
 obj-$(CONFIG_GENERIC_IOREMAP) += ioremap.o
 obj-$(CONFIG_SHRINKER_DEBUG) += shrinker_debug.o
 obj-$(CONFIG_EXECMEM) += execmem.o
+obj-$(CONFIG_PISA) += pisa.o
+pisa-y := pisa-meta.o
+obj-$(CONFIG_PISA_META_KUNIT_TEST) += pisa-kunit.o
 obj-$(CONFIG_TMPFS_QUOTA) += shmem_quota.o
 obj-$(CONFIG_LAZY_MMU_MODE_KUNIT_TEST) += tests/lazy_mmu_mode_kunit.o
 obj-$(CONFIG_MEM_ALLOC_PROFILING) += alloc_tag.o
mm/pisa-kunit.c new file +112 -0

112 lines not on this page · raw message

mm/pisa-meta.c new file +603 -0

603 lines not on this page · raw message

mm/pisa-priv.h new file +61 -0

61 lines not on this page · raw message

Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#64 lore raw

Re: [RFC PATCH v3 01/25] mm: Introduce CONFIG_PISA and metadata table

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [Medium] mm: unmapped KMSAN vmalloc shadow in pisa_pfn2slot and pisa_meta_array - [Medium] mm: freeing…

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [Medium] mm: unmapped KMSAN vmalloc shadow in pisa_pfn2slot and pisa_meta_array
- [Medium] mm: freeing init_mm page tables in pisa_meta_init() without init_mm.mmap_lock
- [Low] mm: early pisa_enabled() return in pisa_meta_init() during jump_label_update()
--

commit e2c1da1898da520bb5d1c1e05212fb580b78c49f
Author: Luigi Rizzo <[email protected]>

mm: Introduce CONFIG_PISA and metadata table

This commit adds CONFIG_PISA, the two-level metadata tables (pisa_pfn2slot and pisa_meta_array) with on-demand page table management and memory hotplug support, and a built-in KUnit test suite.

Quoted 6 lines
mm/pisa-meta.c new file +0 -0
new file mode 100644
index 0000000000000..734f49320047a
@@ -0,0 +1,603 @@

[ ... ]

Quoted 20 lines
mm/pisa-meta.c new file +20 -0
+static int pisa_pfn2slot_init_zero(unsigned long start)
+{
+	unsigned long end = start + PISA_PFN2SLOT_SIZE, addr;
+	int ret = -ENOMEM;
+
+	for (addr = start; addr < end; addr += PUD_SIZE) {
+		pgd_t *pgd = pgd_offset_k(addr);
+		p4d_t *p4d = p4d_alloc(&init_mm, pgd, addr);
+		pud_t *pud = p4d ? pud_alloc(&init_mm, p4d, addr) : NULL;
+
+		if (!pud)
+			goto undo;
+		/* An earlier user of this vmalloc range may have left page tables. */
+		if (!pud_none(pudp_get(pud)) && !pud_free_pmd_page(pud, addr)) {
+			ret = -EBUSY;
+			goto undo;
+		}
+		pud_populate(&init_mm, pud, pisa_zero_pmds);
+	}
+	return 0;

[ ... ]

Quoted 25 lines
mm/pisa-meta.c new file +25 -0
+static void pisa_pfn2slot_free(struct vm_struct *vm)
+{
+	unsigned long start = ALIGN((unsigned long)vm->addr, PUD_SIZE);
+	unsigned long end = start + PISA_PFN2SLOT_SIZE;
+
+	for (unsigned long addr = start; addr < end; addr += PUD_SIZE) {
+		pgd_t *pgd = pgd_offset_k(addr);
+		p4d_t *p4d = pgd_none(pgdp_get(pgd)) ? NULL : p4d_offset(pgd, addr);
+		pud_t *pud = (!p4d || p4d_none(p4dp_get(p4d))) ? NULL : pud_offset(p4d, addr);
+		pmd_t *pmds;
+
+		if (!pud || pud_none(pudp_get(pud)))
+			continue;
+		pmds = pud_pgtable(pudp_get(pud));
+		pud_clear(pud);
+		if (pmds == pisa_zero_pmds)
+			continue;
+
+		for (unsigned int i = 0; i < PTRS_PER_PMD; i++) {
+			pte_t *ptes = (pte_t *)pmd_page_vaddr(pmdp_get(&pmds[i]));
+
+			if (ptes == pisa_zero_ptes)
+				continue;
+			for (unsigned int j = 0; j < PTRS_PER_PTE; j++) {
+				pte_t pte = ptep_get(&ptes[j]);

mm/pisa-meta.c line 380

Quoted 10 lines
mm/pisa-meta.c new file +10 -0
+
+				if (pte_write(pte))
+					__free_page(pte_page(pte));
+			}
+			pte_free_kernel(&init_mm, ptes);
+		}
+		pmd_free(&init_mm, pmds);
+	}
+	free_vm_area(vm);
+}

[Severity: Medium]
Can freeing lower-level init_mm page tables in pisa_pfn2slot_init_zero() and pisa_pfn2slot_free() without holding init_mm.mmap_lock cause a use-after-free during a concurrent ptdump walk?

ptdump_walk_pgd() walks init_mm page tables under mmap_write_lock(&init_mm), and vmalloc paths such as vmap_try_huge_pud() take mmap_read_lock(&init_mm) around pud_free_pmd_page(). Because pisa_meta_init() runs at runtime without init_mm.mmap_lock, a concurrent /sys/kernel/debug/page_tables/kernel read can race with table teardown:

CPU0 CPU1
ptdump_walk_pgd(&init_mm) pisa_meta_init()
mmap_write_lock(&init_mm) pisa_pfn2slot_init_zero()
walk_pud_level() pud_free_pmd_page(pud, addr)
walk_pmd_level() pud_clear(pud)
free_pte_table() pmd_free(&init_mm, pmd_table)
walk_pte_level() <-- use-after-free

The same race applies if pisa_meta_init() fails and pisa_pfn2slot_free() frees private PMD and PTE tables via pte_free_kernel() and pmd_free().

[ ... ]

Quoted 10 lines
mm/pisa-meta.c new file +10 -0
+	/* Lazily back the PTE page covering this 16-slot chunk of @pisa_meta_array. */
+	meta = &pisa_meta_array[slot];
+	ptep = pisa_meta_pte((unsigned long)meta);
+	if (pte_none(ptep_get(ptep))) {
+		unsigned long addr = (unsigned long)meta & PAGE_MASK;
+
+		if (!new_page) {
+			/* Allocate outside the lock, this opens a race so retry. */
+			spin_unlock_irqrestore(&pisa_slot_lock, flags);
+			new_page = alloc_pages_node(pfn_to_nid(pfn), gfp, 0);

mm/pisa-meta.c line 468

Quoted 10 lines
mm/pisa-meta.c new file +10 -0
+			if (new_page)
+				goto retry;
+			return -ENOMEM;
+		}
+		set_pte_at(&init_mm, addr, ptep, pfn_pte(page_to_pfn(new_page), PAGE_KERNEL));
+		flush_cache_vmap(addr, addr + PAGE_SIZE);
+		new_page = NULL;
+	}
+
+	memset(meta, 0, sizeof(*meta));

[Severity: Medium]
Does accessing pisa_meta_array or pisa_pfn2slot fault on unmapped KMSAN vmalloc shadow memory when CONFIG_KMSAN=y?

pisa_meta_init() reserves pfn2slot_vm and meta_vm from the vmalloc range via get_vm_area(), and pisa_pfn2slot_init_zero(), pisa_pfn2slot_populate(), and pisa_meta_ensure_pfn() install page table entries directly with pud_populate() and set_pte_at() instead of going through vmap_pages_range_noflush() -> kmsan_vmap_pages_range_noflush(). Because CONFIG_PISA is enabled by default on x86_64 without depending on !KMSAN, KMSAN-instrumented accesses such as memset(meta, 0, sizeof(*meta)) or reads from pisa_pfn2slot translate the vmalloc address into KMSAN_VMALLOC_SHADOW_START / KMSAN_VMALLOC_ORIGIN_START, where no shadow or origin pages are mapped, causing an unhandled page fault during the built-in KUnit test at boot.

[ ... ]

Quoted 25 lines
mm/pisa-meta.c new file +25 -0
+/* Reserve @pisa_pfn2slot and @pisa_meta_array and populate page tables. */
+int pisa_meta_init(void)
+{
+	struct vm_struct *pfn2slot_vm, *meta_vm;
+	unsigned long meta_size;
+	unsigned long *bitmap;
+	struct pisa_meta *meta;
+	u32 *pfn2slot;
+	static int pisa_init_err;
+	int ret = 0;
+
+	if (pisa_enabled())
+		return 0;
+
+	mutex_lock(&pisa_meta_mutex);
+	if (pisa_init_err) {
+		/* A previous init attempt failed. */
+		mutex_unlock(&pisa_meta_mutex);
+		return pisa_init_err;
+	}
+	if (pisa_pfn2slot) {
+		/* The previous caller completed init while we waited on the mutex. */
+		mutex_unlock(&pisa_meta_mutex);
+		goto out_enable;
+	}

[ ... ]

mm/pisa-meta.c line 589

Quoted 6 lines
mm/pisa-meta.c new file +6 -0
+	pr_info("pisa: %lu GB pfn2slot KVA, %u slots (%lu KB meta KVA)\n",
+		PISA_PFN2SLOT_SIZE >> 30, pisa_nr_slots, meta_size >> 10);
+	mutex_unlock(&pisa_meta_mutex);
+out_enable:
+	static_branch_enable(&pisa_key);
+	return 0;

[Severity: Low]
Can a concurrent caller of pisa_meta_init() return 0 from the early pisa_enabled() check while static_branch_enable(&pisa_key) is still patching other jump sites?

jump_label_update() patches jump entries one by one before setting key->enabled to 1:

CPU0 CPU1
pisa_meta_init()
...
mutex_unlock(&pisa_meta_mutex)
static_branch_enable(&pisa_key)

    jump_label_update()
      /* patches pisa_meta_init() site */
                                      pisa_meta_init()
                                        if (pisa_enabled())
                                          return 0;
                                      pisa_meta_ensure_pfn()
                                        if (!pisa_enabled())
                                          return -ERANGE;  <-- unpatched site
      /* patches pisa_meta_ensure_pfn() site */

Testing static_key_enabled(&pisa_key) for the fast path in pisa_meta_init() would wait until jump_label_update() finishes patching all call sites before returning early.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
#65 lore raw

RFC PATCH v3 2/25 mm: Add PISA allocator lifecycle and page recycle hook

In reply to Luigi Rizzo

PISA allocators use 2MB physically contiguous memory pages from which IO buffers are allocated. Recycling memory to the PISA allocator amortizes the cost of mapping, unmapping and IOTLB flush. Memory is returned to the buddy allocator only when all active IOMMU/IOTLB mappings have been flushed, so sensitive data or code will not ever be accessible to IO devices.

Add the allocator creation (struct pisa_alloc, pisa_alloc_create()) and the page release side, hooking into __free_pages_prepare() so that PISA pages are returned to the allocator.

Also implement asynchronous PISA page retirement and release to the buddy allocator via a WQ_MEM_RECLAIM worker. Retirement removes PISA pages from allocators and destroys the mappings flushing the IOTLB, but defers the buddy release by an RCU grace period.

---
 include/linux/pisa-iommu.h |  24 +++
 include/linux/pisa-mm.h    |  35 ++++
 include/linux/pisa.h       |   2 +
 mm/Makefile                |   2 +-
 mm/page_alloc.c            |   4 +
 mm/pisa-alloc.c            | 338 +++++++++++++++++++++++++++++++++++++
 mm/pisa-kunit.c            | 101 ++++++++++-
 mm/pisa-meta.c             |  71 ++++++++
 mm/pisa-node.c             |  61 +++++++
 mm/pisa-priv.h             |  88 ++++++++++
 10 files changed, 724 insertions(+), 2 deletions(-)
 create mode 100644 include/linux/pisa-mm.h
 create mode 100644 mm/pisa-alloc.c
 create mode 100644 mm/pisa-node.c
include/linux/pisa-iommu.h +24 -0
index 7a04523b28b4c..098430c5f864a 100644
@@ -26,8 +26,20 @@ struct pisa_alloc;
 struct pisa_meta {
 	unsigned long flags;	/* PISA_ACTIVE / PISA_QUARANTINED / PISA_DECRYPTED */
 	unsigned long base_pfn;	/* base PFN of this PISA page */
+	u16 nr_clean;		/* zeroed available blocks in @clean_bitmap */
+	u16 nr_dirty;		/* dirty available blocks in @dirty_bitmap */
+	u8 on_list;		/* current placement in @pa (PISA_LIST_*) */
 	u32 slot;		/* dense index in @pisa_meta_array and IOVA windows */
+	struct pisa_alloc *pa;	/* NULL for reservoir pages */
 	struct list_head list;	/* node in @pa lists or pisa_node.pages */
+
+	union {
+		struct llist_node llnode; /* node in lockless pisa_free_list */
+		struct rcu_head rcu;
+	};
+
+	DECLARE_BITMAP(clean_bitmap, _PISA_MAX_BLOCKS) ____cacheline_aligned;
+	DECLARE_BITMAP(dirty_bitmap, _PISA_MAX_BLOCKS) ____cacheline_aligned;
 } __aligned(_PISA_META_SIZE);
 
 static_assert(sizeof(struct pisa_meta) == _PISA_META_SIZE);
@@ -35,6 +47,18 @@ static_assert(sizeof(struct pisa_meta) == _PISA_META_SIZE);
 extern struct pisa_meta *pisa_meta_array;
 
 struct pisa_meta *pisa_meta_of_pfn(unsigned long pfn);
+bool pisa_quarantine_page(struct pisa_meta *meta);
+void pisa_schedule_reclaim(void);
 
 #endif /* CONFIG_PISA */
+
+#if defined(CONFIG_PISA) && defined(CONFIG_IOMMU_DMA)
+
+void pisa_unmap_all_domains(struct pisa_meta *meta);
+
+#else /* !CONFIG_PISA || !CONFIG_IOMMU_DMA */
+
+static inline void pisa_unmap_all_domains(struct pisa_meta *meta) {}
+
+#endif /* CONFIG_PISA && CONFIG_IOMMU_DMA */
 #endif /* _LINUX_PISA_IOMMU_H */
include/linux/pisa-mm.h new file +35 -0
new file mode 100644
index 0000000000000..60dae9ab6116d
@@ -0,0 +1,35 @@
+/* SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause */
+/* PISA hooks for mm and the block layer. */
+#ifndef _LINUX_PISA_MM_H
+#define _LINUX_PISA_MM_H
+
+#include <linux/pisa.h>
+
+#ifdef CONFIG_PISA
+
+bool __pisa_free_page(struct page *page, unsigned int order);
+
+/*
+ * ============================================================================
+ * MM hooks (every hook starts inline with a static-key check)
+ * ============================================================================
+ */
+
+/* Hook for __free_pages_prepare() (guarded by @pisa_key). */
+static inline bool pisa_free_page(struct page *page, unsigned int order)
+{
+	if (!pisa_enabled())
+		return false;
+	guard(rcu)();
+	return is_pisa_page(page) && __pisa_free_page(page, order);
+}
+
+#else /* !CONFIG_PISA */
+
+static inline bool pisa_free_page(struct page *page, unsigned int order)
+{
+	return false;
+}
+
+#endif /* CONFIG_PISA */
+#endif /* _LINUX_PISA_MM_H */
include/linux/pisa.h +2 -0
index 660329fd448fe..f07432d2e6809 100644
@@ -5,9 +5,11 @@
 
 #include <linux/types.h>
 #include <linux/bitops.h>
+#include <linux/dma-mapping.h>
 #include <linux/jump_label.h>
 #include <linux/mm.h>
 #include <linux/uaccess.h>
+#include <linux/rcupdate.h>
 
 #ifdef CONFIG_PISA
 
mm/Makefile +1 -1
index 55dff84df1555..7d624e4bad456 100644
@@ -147,7 +147,7 @@ obj-$(CONFIG_GENERIC_IOREMAP) += ioremap.o
 obj-$(CONFIG_SHRINKER_DEBUG) += shrinker_debug.o
 obj-$(CONFIG_EXECMEM) += execmem.o
 obj-$(CONFIG_PISA) += pisa.o
-pisa-y := pisa-meta.o
+pisa-y := pisa-meta.o pisa-alloc.o pisa-node.o
 obj-$(CONFIG_PISA_META_KUNIT_TEST) += pisa-kunit.o
 obj-$(CONFIG_TMPFS_QUOTA) += shmem_quota.o
 obj-$(CONFIG_LAZY_MMU_MODE_KUNIT_TEST) += tests/lazy_mmu_mode_kunit.o
mm/page_alloc.c +4 -0
index 2fef4092c913c..e053cc7298eab 100644
@@ -17,6 +17,7 @@
 #include <linux/stddef.h>
 #include <linux/mm.h>
 #include <linux/highmem.h>
+#include <linux/pisa-mm.h>
 #include <linux/interrupt.h>
 #include <linux/jiffies.h>
 #include <linux/compiler.h>
@@ -1324,6 +1325,9 @@ static __always_inline bool __free_pages_prepare(struct page *page,
 
 	VM_BUG_ON_PAGE(PageTail(page), page);
 
+	if (unlikely(pisa_free_page(page, order)))
+		return false;
+
 	trace_mm_page_free(page, order);
 	kmsan_free_page(page, order);
 
mm/pisa-alloc.c new file +338 -0

338 lines not on this page · raw message

mm/pisa-kunit.c +100 -1

121 lines not on this page · raw message

mm/pisa-meta.c +71 -0

83 lines not on this page · raw message

mm/pisa-node.c new file +61 -0

61 lines not on this page · raw message

mm/pisa-priv.h +88 -0

115 lines not on this page · raw message

Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#66 lore raw

RFC PATCH v3 3/25 mm: Add per-NUMA-node PISA page reservoir

In reply to Luigi Rizzo

Allocating a large page may involve compacting and blocking, so it cannot be issued in GFP_ATOMIC context.

Add a per-NUMA-node reservoir of pre-allocated and set up PISA pages, that can serve allocations without blocking. The reservoir is refilled in process context by a per-node work item, queued with queue_work_node() on system_dfl_wq so each node is refilled from its own CPUs, not bound to the CPU that caused the miss.

pisa.reservoir_max, writable at runtime, sets the number of PISA pages per node (default 16 = 32 MB per node; 0 = disabled).

---
 mm/pisa-alloc.c |   2 +
 mm/pisa-kunit.c |   7 ++
 mm/pisa-meta.c  |   1 +
 mm/pisa-node.c  | 273 +++++++++++++++++++++++++++++++++++++++++++++++-
 mm/pisa-priv.h  |  22 ++++
 5 files changed, 304 insertions(+), 1 deletion(-)
mm/pisa-alloc.c +2 -0
index 557ec1ba88c78..7ba93746f6a89 100644
@@ -328,6 +328,8 @@ bool __pisa_free_page(struct page *page, unsigned int order)
 
 static int __init pisa_init(void)
 {
+	pisa_node_init();
+
 	/* Dedicated WQ_MEM_RECLAIM workqueue so reclaim never blocks behind system_wq. */
 	pisa_wq = alloc_workqueue("pisa", WQ_MEM_RECLAIM, 0);
 	if (!pisa_wq)
mm/pisa-kunit.c +7 -0
index 7436d1c9b86a6..bdf5184bbd52a 100644
@@ -192,12 +192,19 @@ static void test_quarantine(struct kunit *test)
 	__free_pages(page, PISA_ORDER);
 }
 
+static void test_reservoir_and_scrubber(struct kunit *test)
+{
+	KUNIT_ASSERT_EQ(test, pisa_meta_init(), 0);
+	KUNIT_EXPECT_EQ(test, READ_ONCE(pisa_reservoir_max), 16U);
+}
+
 static struct kunit_case pisa_meta_test_cases[] = {
 	KUNIT_CASE(test_meta_init_and_roundtrip),
 	KUNIT_CASE(test_meta_invalid_phys),
 	KUNIT_CASE(test_meta_active_toggle),
 	KUNIT_CASE(test_alloc_and_recycle),
 	KUNIT_CASE(test_quarantine),
+	KUNIT_CASE(test_reservoir_and_scrubber),
 	{}
 };
 
mm/pisa-meta.c +1 -0
index 41ea277c60f00..7cdb1c45d65c8 100644
@@ -657,6 +657,7 @@ int pisa_meta_init(void)
 	mutex_unlock(&pisa_meta_mutex);
 out_enable:
 	static_branch_enable(&pisa_key);
+	pisa_schedule_reservoir();
 	return 0;
 
 out_free_vms:
mm/pisa-node.c +272 -1

295 lines not on this page · raw message

mm/pisa-priv.h +22 -0
index 776462a2f1ee2..bca35f463c3b7 100644
@@ -9,9 +9,11 @@
 
 #undef MODULE_PARAM_PREFIX
 #define MODULE_PARAM_PREFIX "pisa."
+#include <linux/jiffies.h>
 #include <linux/nodemask.h>
 #include <linux/spinlock.h>
 #include <linux/topology.h>
+#include <linux/workqueue.h>
 
 
 #ifdef CONFIG_PISA
@@ -24,6 +26,7 @@
  *
  * 1. Allocators (mm/pisa-alloc.c, mm/pisa-node.c):
  *    pisa_allocs_lock (rwlock) -> pa->lock (spinlock)
+ *    pisa_nodes[].lock (spinlock): leaf lock over a node's reservoir.
  *
  * 2. Metadata tables (mm/pisa-meta.c):
  *    pisa_meta_mutex (mutex): init and hotplug page-table population.
@@ -99,7 +102,13 @@ struct pisa_alloc {
 
 /* Per-NUMA-node PISA state. */
 struct pisa_node {
+	unsigned long		next_alloc;	/* atomic alloc backoff jiffies */
 	struct pisa_alloc	*pa[2][PISA_MAX_ALLOC_ORDER + 1]; /* [0]=RW, [1]=RO */
+
+	spinlock_t		lock;		/* protects @pages and @nr_pages */
+	unsigned int		nr_pages;	/* entries in @pages */
+	struct list_head	pages;		/* reservoir */
+	struct work_struct	work;		/* refill/trim, on this node */
 } ____cacheline_aligned_in_smp;
 
 /* Per-NUMA-node PISA state (ring/TX/user allocators, reservoir). */
@@ -136,6 +145,12 @@ static inline struct pisa_alloc *pisa_node_pa(int nid, unsigned int order, bool
 	       pisa_nodes[pisa_sanitize_nid(nid)].pa[read_only][order];
 }
 
+static inline void pisa_alloc_backoff(struct pisa_node *node, bool can_block)
+{
+	if (!can_block)
+		WRITE_ONCE(node->next_alloc, jiffies + DIV_ROUND_UP(HZ, 100));
+}
+
 /* pisa-alloc.c, also used by the per-node code in pisa-node.c */
 struct pisa_alloc *pisa_alloc_create(int nid, unsigned int order, enum dma_data_direction dir);
 __printf(2, 3)
@@ -145,5 +160,12 @@ extern struct llist_head pisa_free_list;
 extern unsigned int pisa_idle_ms;
 void pisa_release_page(struct pisa_meta *meta);
 
+/* pisa-node.c: per-NUMA-node PISA page reservoir and work item */
+extern unsigned int pisa_reservoir_max;
+void pisa_node_init(void);
+void pisa_schedule_reservoir(void);
+struct pisa_meta *pisa_reservoir_pop(int nid, gfp_t gfp, bool *clean);
+unsigned long pisa_reservoir_count(void);
+
 #endif /* CONFIG_PISA */
 #endif /* _MM_PISA_PRIV_H */
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#67 lore raw

Re: [RFC PATCH v3 03/25] mm: Add per-NUMA-node PISA page reservoir

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] mm: race in pisa_schedule_reservoir_node() skips reservoir trim work --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] mm: race in pisa_schedule_reservoir_node() skips reservoir trim work
--

commit 540432e01d5fdd397e42906780e4e3354270a3d7
Author: Luigi Rizzo <[email protected]>

mm: Add per-NUMA-node PISA page reservoir

This commit adds a per-NUMA-node reservoir of pre-allocated and zeroed PISA pages to satisfy non-blocking allocations, managed by a per-node work item and controlled by the pisa.reservoir_max parameter.

Quoted 4 lines
mm/pisa-node.c +0 -0
index fe9f37deac755..5b9b44186b967 100644

[ ... ]

Quoted 69 lines
mm/pisa-node.c +68 -0
@@ -53,9 +153,180 @@ static void pisa_release_page_rcu(struct rcu_head *head)
+/* Refill node @nid's reservoir up to pisa_reservoir_max pre-zeroed PISA pages. */
+static void pisa_reservoir_refill_node(struct pisa_node *node, int nid)
+{
+	while (READ_ONCE(node->nr_pages) < READ_ONCE(pisa_reservoir_max)) {
+		struct pisa_meta *meta;
+		unsigned long flags;
+		bool clean, added;
+
+		meta = __pisa_page_alloc(GFP_KERNEL | __GFP_THISNODE, nid, true, &clean);
+		if (IS_ERR(meta)) {
+			pisa_alloc_backoff(node, false);
+			break;
+		}
+
+		/* init_on_alloc/init_on_free pages are already zeroed. */
+		if (!clean)
+			memset(page_address(pisa_meta_to_page(meta)), 0, PISA_SIZE);
+
+		spin_lock_irqsave(&node->lock, flags);
+		/* pisa_reservoir_max may have been lowered while allocating and zeroing. */
+		added = node->nr_pages < READ_ONCE(pisa_reservoir_max);
+		if (added) {
+			list_add(&meta->list, &node->pages);
+			WRITE_ONCE(node->nr_pages, node->nr_pages + 1);
+		}
+		spin_unlock_irqrestore(&node->lock, flags);
+		if (!added) {
+			pisa_release_page(meta);
+			break;
+		}
+
+		cond_resched();
+	}
+}
+
+/* Release PISA pages in @node's reservoir above @max. */
+static void pisa_reservoir_trim_node(struct pisa_node *node, unsigned int max)
+{
+	while (READ_ONCE(node->nr_pages) > max &&
+	       READ_ONCE(node->nr_pages) > READ_ONCE(pisa_reservoir_max)) {
+		struct pisa_meta *meta;
+		unsigned long flags;
+
+		spin_lock_irqsave(&node->lock, flags);
+		meta = list_first_entry_or_null(&node->pages, struct pisa_meta, list);
+		if (meta) {
+			list_del_init(&meta->list);
+			WRITE_ONCE(node->nr_pages, node->nr_pages - 1);
+		}
+		spin_unlock_irqrestore(&node->lock, flags);
+		if (!meta)
+			break;
+
+		pisa_release_page(meta);
+		cond_resched();
+	}
+}
+
+/* Per-node worker: trim/refill the reservoir, then scrub allocators homed on @nid. */
+static void pisa_node_work_fn(struct work_struct *work)
+{
+	struct pisa_node *node = container_of(work, struct pisa_node, work);
+	int nid = node - pisa_nodes;
+
+	pisa_reservoir_trim_node(node, READ_ONCE(pisa_reservoir_max));
+	if (pisa_enabled() && READ_ONCE(pisa_reservoir_max))
+		pisa_reservoir_refill_node(node, nid);
+}

mm/pisa-node.c static void pisa_release_page_rcu(struct rcu_head *head) · line 230

Quoted 10 lines
mm/pisa-node.c +10 -0
+
+/* Queue node @nid's work if its reservoir is below or above the target. */
+static void pisa_schedule_reservoir_node(int nid)
+{
+	struct pisa_node *node = &pisa_nodes[nid];
+
+	if (READ_ONCE(node->nr_pages) != READ_ONCE(pisa_reservoir_max) &&
+	    !work_pending(&node->work))
+		queue_work_node(nid, system_dfl_wq, &node->work);
+}

[Severity: Medium]
Can lowering pisa_reservoir_max race with pisa_reservoir_refill_node() and skip queueing the trim work?

CPU0 (kworker) CPU1
pisa_node_work_fn()
pisa_reservoir_refill_node()

    /* nr_pages == 0, max == 16 */
    spin_lock_irqsave(&node->lock)
    added = node->nr_pages <
            READ_ONCE(pisa_reservoir_max);
                                      pisa_reservoir_max_set()
                                        /* sets pisa_reservoir_max = 0 */
                                        pisa_schedule_reservoir()
                                          pisa_schedule_reservoir_node()
                                            READ_ONCE(node->nr_pages) !=
                                            READ_ONCE(pisa_reservoir_max)
                                            /* 0 != 0 is false: skipped */
    list_add(&meta->list, &node->pages)
    WRITE_ONCE(node->nr_pages, 1)
    spin_unlock_irqrestore(&node->lock)

Because pisa_node_work_fn() only calls pisa_reservoir_trim_node() before pisa_reservoir_refill_node(), the worker exits with an extra PISA page left in node->pages above pisa_reservoir_max. When pisa_reservoir_max is set to 0, pisa_reservoir_pop() bypasses the reservoir altogether, leaving that page stranded in node->pages.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
#68 lore raw

RFC PATCH v3 4/25 mm/page_alloc: Extend alloc_pages() to __GFP_PISA and PISA block allocation

In reply to Luigi Rizzo

Add block allocation (pisa_alloc_bulk(), pisa_alloc())
and split_page_compound(), which splits a newly acquired 2MB PISA page into blocks of the allocator's order, frozen at refcount 0.

Introduce __GFP_PISA and __GFP_PISA_RW GFP flags and hook __alloc_frozen_pages_noprof() and alloc_pages_bulk_noprof() so callers can allocate from per-node PISA allocators (pisa_nodes[nid].pa[ro][order]) using standard page allocation APIs.

---
 include/linux/gfp_types.h      |  14 +-
 include/linux/pisa-mm.h        |  46 +++++
 include/trace/events/mmflags.h |  11 +-
 mm/page_alloc.c                |   6 +
 mm/pisa-alloc.c                | 342 +++++++++++++++++++++++++++++++++
 mm/pisa-kunit.c                |  69 +++++++
 mm/pisa-priv.h                 |  15 ++
 7 files changed, 499 insertions(+), 4 deletions(-)
include/linux/gfp_types.h +12 -2
index c1331bf0b2398..80d1371212375 100644
@@ -33,7 +33,7 @@ enum {
 	___GFP_IO_BIT,
 	___GFP_FS_BIT,
 	___GFP_ZERO_BIT,
-	___GFP_UNUSED_BIT,	/* 0x200u unused */
+	___GFP_PISA_BIT,
 	___GFP_DIRECT_RECLAIM_BIT,
 	___GFP_KSWAPD_RECLAIM_BIT,
 	___GFP_WRITE_BIT,
@@ -68,7 +68,13 @@ enum {
 #define ___GFP_IO		BIT(___GFP_IO_BIT)
 #define ___GFP_FS		BIT(___GFP_FS_BIT)
 #define ___GFP_ZERO		BIT(___GFP_ZERO_BIT)
-/* 0x200u unused */
+#ifdef CONFIG_PISA
+#define ___GFP_PISA		BIT(___GFP_PISA_BIT)
+#define ___GFP_PISA_RW		(___GFP_PISA | ___GFP_WRITE)
+#else
+#define ___GFP_PISA		0
+#define ___GFP_PISA_RW		0
+#endif
 #define ___GFP_DIRECT_RECLAIM	BIT(___GFP_DIRECT_RECLAIM_BIT)
 #define ___GFP_KSWAPD_RECLAIM	BIT(___GFP_KSWAPD_RECLAIM_BIT)
 #define ___GFP_WRITE		BIT(___GFP_WRITE_BIT)
@@ -289,6 +295,10 @@ enum {
 /* Disable lockdep for GFP context tracking */
 #define __GFP_NOLOCKDEP ((__force gfp_t)___GFP_NOLOCKDEP)
 
+/* Allocate from per-node PISA allocators (fall back to buddy on failure) */
+#define __GFP_PISA			((__force gfp_t)___GFP_PISA)
+#define __GFP_PISA_RW			((__force gfp_t)___GFP_PISA_RW)
+
 /* Room for N __GFP_FOO bits */
 #define __GFP_BITS_SHIFT ___GFP_LAST_BIT
 #define __GFP_BITS_MASK ((__force gfp_t)((1 << __GFP_BITS_SHIFT) - 1))
include/linux/pisa-mm.h +46 -0

64 lines not on this page · raw message

include/trace/events/mmflags.h +9 -2
index 3c153b3ad8450..c2b2ec99ab63c 100644
@@ -54,10 +54,18 @@
 # define TRACE_GFP_FLAGS_LOCKDEP
 #endif
 
+#ifdef CONFIG_PISA
+# define TRACE_GFP_FLAGS_PISA			\
+	TRACE_GFP_EM(PISA)
+#else
+# define TRACE_GFP_FLAGS_PISA
+#endif
+
 #define TRACE_GFP_FLAGS				\
 	TRACE_GFP_FLAGS_GENERAL			\
 	TRACE_GFP_FLAGS_KASAN			\
-	TRACE_GFP_FLAGS_LOCKDEP
+	TRACE_GFP_FLAGS_LOCKDEP			\
+	TRACE_GFP_FLAGS_PISA
 
 #undef TRACE_GFP_EM
 #define TRACE_GFP_EM(a) TRACE_DEFINE_ENUM(___GFP_##a##_BIT);
@@ -65,7 +73,6 @@
 TRACE_GFP_FLAGS
 
 /* Just in case these are ever used */
-TRACE_DEFINE_ENUM(___GFP_UNUSED_BIT);
 TRACE_DEFINE_ENUM(___GFP_LAST_BIT);
 
 #define gfpflag_string(flag) {(__force unsigned long)flag, #flag}
mm/page_alloc.c +6 -0
index e053cc7298eab..af1399659a163 100644
@@ -5228,6 +5228,8 @@ unsigned long alloc_pages_bulk_noprof(gfp_t gfp, int preferred_nid,
 	unsigned int zonelist_iter_cookie;
 	int nr_populated = 0, nr_account = 0;
 
+	nr_populated = pisa_alloc_pages_bulk(&gfp, 0, preferred_nid, nodemask,
+					     nr_pages, page_array, false);
 	/*
 	 * Skip populated array elements to determine if any pages need
 	 * to be allocated before disabling IRQs.
@@ -5480,6 +5482,10 @@ struct page *__alloc_frozen_pages_noprof(gfp_t gfp, unsigned int order,
 		fastpath_alloc_flags |= ALLOC_WMARK_LOW;
 	}
 
+	page = pisa_alloc_pages(&gfp, order, preferred_nid, nodemask);
+	if (page)
+		return page;
+
 	gfp &= gfp_allowed_mask;
 	/*
 	 * Apply scoped allocation constraints. This is mainly about GFP_NOFS
mm/pisa-alloc.c +342 -0

371 lines not on this page · raw message

mm/pisa-kunit.c +69 -0

91 lines not on this page · raw message

mm/pisa-priv.h +15 -0
index bca35f463c3b7..46170da8a0f0d 100644
@@ -155,10 +155,25 @@ static inline void pisa_alloc_backoff(struct pisa_node *node, bool can_block)
 struct pisa_alloc *pisa_alloc_create(int nid, unsigned int order, enum dma_data_direction dir);
 __printf(2, 3)
 void pisa_alloc_set_name(struct pisa_alloc *pa, const char *fmt, ...);
+__printf(5, 6)
+struct pisa_alloc *pisa_alloc_ensure(struct pisa_alloc **pap, int nid,
+				     unsigned int order, enum dma_data_direction dir,
+				     const char *fmt, ...);
 bool pisa_place_meta(struct pisa_meta *meta);
 extern struct llist_head pisa_free_list;
 extern unsigned int pisa_idle_ms;
 void pisa_release_page(struct pisa_meta *meta);
+unsigned long pisa_alloc_bulk(struct pisa_alloc *pa, gfp_t gfp,
+			      unsigned long nr_pages, struct page **page_array, bool frozen);
+
+static inline struct page *pisa_alloc(struct pisa_alloc *pa, gfp_t gfp)
+{
+	struct page *page = NULL;
+
+	if (pa)
+		pisa_alloc_bulk(pa, gfp, 1, &page, false);
+	return page;
+}
 
 /* pisa-node.c: per-NUMA-node PISA page reservoir and work item */
 extern unsigned int pisa_reservoir_max;
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#69 lore raw

Re: [RFC PATCH v3 04/25] mm/page_alloc: Extend alloc_pages() to __GFP_PISA and PISA block allocation

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [High] mm/pisa: __pisa_page_alloc() propagates __GFP_NOFAIL and __GFP_HIGH to order-9 --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [High] mm/pisa: __pisa_page_alloc() propagates __GFP_NOFAIL and __GFP_HIGH to order-9
--

commit a900e3d8d2cb1db57e93b7cd711921f0fe72bca4
Author: Luigi Rizzo <[email protected]>

mm/page_alloc: Extend alloc_pages() to __GFP_PISA and PISA block allocation

This commit adds PISA block allocation helpers (pisa_alloc_bulk() and pisa_alloc()), introduces the __GFP_PISA and __GFP_PISA_RW flags, and hooks __alloc_frozen_pages_noprof() and alloc_pages_bulk_noprof() to allocate from per-node PISA allocators.

Quoted 4 lines
mm/pisa-alloc.c +0 -0
index 7ba93746f6a89..e7f7ed5dca067 100644

[ ... ]

Quoted 13 lines
mm/pisa-alloc.c +13 -0
+/* Obtain and split a new PISA page on @nid into blocks of @order. */
+static struct pisa_meta *pisa_alloc_split_page(unsigned int order, gfp_t gfp, int nid)
+{
+	bool can_block = gfpflags_allow_blocking(gfp), clean;
+	unsigned int bpp = PISA_BLOCKS(order);
+	struct pisa_meta *meta;
+	struct page *page;
+	int err;
+
+	/* __GFP_DMA/__GFP_DMA32 were already declined by pisa_alloc_bulk(). */
+	meta = pisa_reservoir_pop(nid, gfp & ~__GFP_ZERO, &clean);
+	if (IS_ERR(meta))
+		return meta;

[ ... ]

mm/pisa-alloc.c static bool pisa_return_block_locked(struct pisa_alloc *pa, struct page *block) · line 598

Quoted 12 lines
mm/pisa-alloc.c +12 -0
+unsigned long pisa_alloc_bulk(struct pisa_alloc *pa, gfp_t gfp,
+			      unsigned long nr_pages, struct page **page_array, bool frozen)
+{
+	unsigned long i = 0, n, got;
+
+	/* Skip any already populated prefix, as alloc_pages_bulk_node() does. */
+	while (i < nr_pages && page_array[i])
+		i++;
+	if (unlikely(!pa || i == nr_pages ||
+		     (gfp & (__GFP_DMA | __GFP_DMA32 | __GFP_THISNODE | __GFP_ACCOUNT))))
+		return i;
+	gfp = current_gfp_context(gfp);

[Severity: High]
Can pisa_alloc_bulk() forward __GFP_NOFAIL and __GFP_HIGH into the order-9 PISA page allocation when the allocator and per-node reservoir are empty?

When pisa_alloc_split_page() calls pisa_reservoir_pop(nid, gfp & ~__GFP_ZERO, &clean) and the reservoir misses, __pisa_page_alloc() strips only __GFP_COMP, __GFP_HIGHMEM, and __GFP_MOVABLE before requesting an order-9 (PISA_ORDER) page:

mm/pisa-node.c:__pisa_page_alloc() {
    ...
	/*
	 * Long-lived active pages must be unmovable, lowmem, non-compound, and
	 * must not dip into emergency reserves or trigger OOM/warnings.
	 */
	gfp &= ~(__GFP_COMP | __GFP_HIGHMEM | __GFP_MOVABLE);
	gfp |= __GFP_NOWARN | __GFP_NOMEMALLOC | (can_block ? __GFP_RETRY_MAYFAIL : __GFP_NORETRY);

	if (can_block)
		memflags = pisa_memalloc_save(gfp);
	page = alloc_pages_node(nid, gfp, PISA_ORDER);
    ...
}

If an order-0 caller passes __GFP_NOFAIL, __alloc_pages_slowpath() will loop indefinitely trying to compact a 2MB unmovable block instead of failing so the caller can fall back to an order-0 buddy page. Similarly, if a caller passes GFP_ATOMIC (__GFP_HIGH), alloc_flags_slowpath() grants ALLOC_MIN_RESERVE even with __GFP_NOMEMALLOC set, allowing an opportunistic 2MB PISA allocation to deplete emergency reserves.

Stripping __GFP_NOFAIL and __GFP_HIGH in __pisa_page_alloc() (or declining __GFP_NOFAIL in pisa_alloc_bulk()) would avoid both issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
#70 lore raw

RFC PATCH v3 5/25 mm: Add global cap and shrinker for PISA pages

In reply to Luigi Rizzo

Add mechanisms to bound the number of unused PISA pages:

- a global ceiling, pisa.max_pages, on the number of PISA pages pinned across all allocators and reservoirs, defaulting to one eighth of RAM, with a floor for small machines.

- a shrinker that, under reclaim, drains the per-node reservoirs first and then completely idle pages across all allocators.
Idle pages are detached under the allocator lock but retired outside it, to avoid holding the lock during the expensive unmaps/iotlb flush.

- recycle gating for caller pools (pisa_page_can_recycle()): blocks that belong to old, sparse partial pages are returned to their allocator instead of being recycled in place, so those pages can drain to idle. Tuned by pisa.compact, pisa.target_usage_percent and pisa.old_ms.

---
 include/linux/pisa-iommu.h |   3 +
 include/linux/pisa.h       |  20 +++++-
 mm/pisa-alloc.c            | 116 ++++++++++++++++++++++++++++++++++
 mm/pisa-kunit.c            |  16 +++++
 mm/pisa-meta.c             | 123 ++++++++++++++++++++++++++++++++++++-
 mm/pisa-node.c             |  33 +++++++++-
 mm/pisa-priv.h             |  38 ++++++++++++
 7 files changed, 344 insertions(+), 5 deletions(-)
include/linux/pisa-iommu.h +3 -0
index 098430c5f864a..b29b405804193 100644
@@ -29,6 +29,7 @@ struct pisa_meta {
 	u16 nr_clean;		/* zeroed available blocks in @clean_bitmap */
 	u16 nr_dirty;		/* dirty available blocks in @dirty_bitmap */
 	u8 on_list;		/* current placement in @pa (PISA_LIST_*) */
+	bool drain;		/* sparse old page draining back to @idle */
 	u32 slot;		/* dense index in @pisa_meta_array and IOVA windows */
 	struct pisa_alloc *pa;	/* NULL for reservoir pages */
 	struct list_head list;	/* node in @pa lists or pisa_node.pages */
@@ -37,6 +38,7 @@ struct pisa_meta {
 		struct llist_node llnode; /* node in lockless pisa_free_list */
 		struct rcu_head rcu;
 	};
+	unsigned long alloc_jiffies;	/* jiffies when page entered/re-entered use */
 
 	DECLARE_BITMAP(clean_bitmap, _PISA_MAX_BLOCKS) ____cacheline_aligned;
 	DECLARE_BITMAP(dirty_bitmap, _PISA_MAX_BLOCKS) ____cacheline_aligned;
@@ -45,6 +47,7 @@ struct pisa_meta {
 static_assert(sizeof(struct pisa_meta) == _PISA_META_SIZE);
 
 extern struct pisa_meta *pisa_meta_array;
+extern unsigned int pisa_nr_slots;
 
 struct pisa_meta *pisa_meta_of_pfn(unsigned long pfn);
 bool pisa_quarantine_page(struct pisa_meta *meta);
include/linux/pisa.h +19 -1
index f07432d2e6809..3307fae1dbd66 100644
@@ -40,12 +40,18 @@ enum {
 #define PISA_ACTIVE		BIT(_PISA_ACTIVE)	/* set up as a PISA page, not retired yet */
 #define PISA_QUARANTINED	BIT(_PISA_QUARANTINED)	/* IOMMU unmap failed: never reuse */
 
-/* Enabled on first pisa_meta_init() to activate fast-path hooks. */
+/*
+ * Static keys guarding all kernel hooks:
+ * - @pisa_key: enabled on first device opt-in (pisa_meta_init()).
+ * - @pisa_recycle_check_key: enabled when pisa.compact or pisa.target_usage_percent > 0.
+ */
 DECLARE_STATIC_KEY_FALSE(pisa_key);
+DECLARE_STATIC_KEY_FALSE(pisa_recycle_check_key);
 
 extern u32 *pisa_pfn2slot;
 
 int pisa_meta_init(void);
+bool __pisa_page_can_recycle(const struct page *page);
 
 static inline bool pisa_enabled(void)
 {
@@ -103,6 +109,13 @@ static inline struct page *pisa_virt_to_page(const void *addr)
 	return is_pisa_page(page) ? page : NULL;
 }
 
+/* Hook for skb_page_frag_refill() and __pisa_free_page() (@pisa_recycle_check_key). */
+static inline bool pisa_page_can_recycle(const struct page *page)
+{
+	return !static_branch_unlikely(&pisa_recycle_check_key) ||
+	       __pisa_page_can_recycle(page);
+}
+
 #else /* !CONFIG_PISA */
 
 static inline int pisa_meta_init(void) { return -EOPNOTSUPP; }
@@ -112,5 +125,10 @@ static inline bool is_pisa_page(const struct page *page) { return false; }
 static inline bool is_pisa_phys(phys_addr_t phys) { return false; }
 static inline struct page *pisa_virt_to_page(const void *addr) { return NULL; }
 
+static inline bool pisa_page_can_recycle(const struct page *page)
+{
+	return true;
+}
+
 #endif /* CONFIG_PISA */
 #endif /* _LINUX_PISA_H */
mm/pisa-alloc.c +116 -0

190 lines not on this page · raw message

mm/pisa-kunit.c +16 -0
index ea605cb6afe5b..cd2bfbfb0f1a7 100644
@@ -7,6 +7,7 @@
 #include <linux/gfp.h>
 #include <linux/pisa.h>
 #include <linux/mm.h>
+#include <linux/shrinker.h>
 #include <linux/skbuff.h>
 #include <net/sock.h>
 
@@ -108,8 +109,10 @@ static void test_alloc_and_recycle(struct kunit *test)
 		{ 0, false },
 		{ SKB_FRAG_PAGE_ORDER, true },
 	};
+	struct shrink_control sc = { .nr_to_scan = ULONG_MAX };
 	struct page *p1, *p2, *bulk[3];
 	struct pisa_alloc *pa;
+	unsigned long old_max;
 
 	KUNIT_EXPECT_NULL(test, pisa_alloc_create(first_memory_node, 0, DMA_NONE));
 	KUNIT_EXPECT_NULL(test, pisa_alloc_create(first_memory_node, PISA_ORDER + 1,
@@ -124,6 +127,7 @@ static void test_alloc_and_recycle(struct kunit *test)
 
 		pa = pisa_node_pa(first_memory_node, order, cases[i].ro);
 		KUNIT_ASSERT_NOT_NULL(test, pa);
+		pisa_shrink_scan(NULL, &sc);
 		KUNIT_EXPECT_NULL(test, pisa_alloc(pa, GFP_KERNEL | __GFP_ACCOUNT));
 		KUNIT_EXPECT_NULL(test, pisa_alloc(pa, GFP_KERNEL | __GFP_DMA32));
 		KUNIT_EXPECT_NULL(test, pisa_alloc(pa, GFP_KERNEL | __GFP_THISNODE));
@@ -164,6 +168,7 @@ static void test_alloc_and_recycle(struct kunit *test)
 
 		if (p2)
 			__free_pages(p2, order);
+		pisa_shrink_scan(NULL, &sc);
 	}
 
 	/* Plain alloc_page() without __GFP_PISA_* comes from the buddy allocator. */
@@ -171,6 +176,16 @@ static void test_alloc_and_recycle(struct kunit *test)
 	KUNIT_ASSERT_NOT_NULL(test, p1);
 	KUNIT_EXPECT_FALSE(test, is_pisa_page(p1));
 	__free_pages(p1, 0);
+
+	/* Global budget cap (pisa_max_pages = 0) refuses new PISA pages. */
+	pa = pisa_node_pa(first_memory_node, SKB_FRAG_PAGE_ORDER, true);
+	KUNIT_ASSERT_NOT_NULL(test, pa);
+	old_max = READ_ONCE(pisa_max_pages);
+	WRITE_ONCE(pisa_max_pages, 0);
+	WRITE_ONCE(pisa_reservoir_max, 0);
+	KUNIT_EXPECT_NULL(test, pisa_alloc(pa, GFP_KERNEL));
+	WRITE_ONCE(pisa_reservoir_max, 16);
+	WRITE_ONCE(pisa_max_pages, old_max);
 }
 
 /* Wait for the reclaim worker and its RCU callback to retire @meta. */
@@ -221,6 +236,7 @@ static void test_quarantine(struct kunit *test)
 	/* Give the page to @pa with half of its blocks in use. */
 	spin_lock_irqsave(&pa->lock, flags);
 	meta->pa = pa;
+	pa->stats.page_alloc++;	/* balanced by page_free when the page is retired */
 	meta->nr_clean = bpp / 2;
 	pisa_meta_set_flags(meta, PISA_ACTIVE);
 	pisa_place_meta(meta);
mm/pisa-meta.c +121 -2

147 lines not on this page · raw message

mm/pisa-node.c +31 -2
index 5b9b44186b967..29f6ba866b633 100644
@@ -82,6 +82,10 @@ static struct pisa_meta *__pisa_page_alloc(gfp_t gfp, int nid, bool can_block,
 			return ERR_PTR(-EAGAIN);
 	}
 
+	/* Racy check against global ceiling across allocators and reservoirs. */
+	if (atomic_long_read(&pisa_nr_pages) >= READ_ONCE(pisa_max_pages))
+		return ERR_PTR(-ENOSPC);
+
 	/*
 	 * Long-lived active pages must be unmovable, lowmem, non-compound, and
 	 * must not dip into emergency reserves or trigger OOM/warnings.
@@ -110,6 +114,8 @@ static struct pisa_meta *__pisa_page_alloc(gfp_t gfp, int nid, bool can_block,
 		memalloc_flags_restore(memflags);
 
 	meta = pisa_meta_of_pfn(page_to_pfn(page));
+
+	atomic_long_inc(&pisa_nr_pages);
 	*clean = (gfp & __GFP_ZERO) || want_init_on_alloc(0) || want_init_on_free();
 
 	return meta;
@@ -138,10 +144,10 @@ static void pisa_release_page_rcu(struct rcu_head *head)
 	/* The page has been unmapped from every domain by pisa_release_page() */
 	pisa_slot_free(meta);
 
-	/* Possibly still mapped by a device: leak it. */
+	/* Possibly still mapped by a device: leak it, still charged. */
 	if (flags & PISA_QUARANTINED)
 		return;
-
+	atomic_long_dec(&pisa_nr_pages);
 	for (unsigned int i = 0; i < PISA_BLOCKS(order); i++) {
 		struct page *block = page + (i << order);
 
@@ -158,9 +164,13 @@ void pisa_release_page(struct pisa_meta *meta)
 
 		pisa_slot_free(meta);
 		__free_pages(page, PISA_ORDER);
+		atomic_long_dec(&pisa_nr_pages);
 		return;
 	}
 
+	/* Count it now: pisa_alloc_held_pages() must not see a retiring page as held. */
+	atomic64_inc(&meta->pa->stats.page_free);
+
 	/* pisa_unmap_all_domains(meta) will be called here once IOMMU mappings are added. */
 
 	/* Clear PISA_ACTIVE before the RCU grace period so new readers stop entering. */
@@ -322,6 +332,25 @@ unsigned long pisa_reservoir_count(void)
 	return nr;
 }
 
+/* Detach up to @nr_to_scan base pages from reservoirs onto @release_list. */
+unsigned long pisa_reservoir_shrink(struct list_head *release_list, unsigned long nr_to_scan)
+{
+	unsigned long freed = 0;
+	int nid;
+
+	for_each_node_state(nid, N_MEMORY) {
+		struct pisa_node *node = &pisa_nodes[nid];
+
+		if (!READ_ONCE(node->nr_pages))
+			continue;
+		freed += pisa_shrink_list(&node->lock, &node->pages, &node->nr_pages,
+					  release_list, nr_to_scan - freed);
+		if (freed >= nr_to_scan)
+			break;
+	}
+	return freed;
+}
+
 void __init pisa_node_init(void)
 {
 	for (int nid = 0; nid < MAX_NUMNODES; nid++) {
mm/pisa-priv.h +38 -0
index 46170da8a0f0d..a191ede9bf3ce 100644
@@ -79,6 +79,12 @@ static inline unsigned int pisa_meta_avail(const struct pisa_meta *meta)
 	return meta->nr_clean + meta->nr_dirty;
 }
 
+/* Per-allocator statistics, see pisa_allocs_show(). */
+struct pisa_alloc_stats {
+	u64		page_alloc;
+	atomic64_t	page_free;
+};
+
 /* Allocator managing blocks of a fixed order, carved from PISA pages. */
 struct pisa_alloc {
 	/* First cacheline: hot fields touched on block alloc and free. */
@@ -91,12 +97,22 @@ struct pisa_alloc {
 	unsigned int		num_idle_pages;
 	unsigned int		max_idle_pages;
 	unsigned long		idle_jiffies;	/* last change of @idle at/above @max_idle_pages */
+	unsigned long		blocks_in_use;	/* blocks handed out and not yet freed */
 	/* Cold. */
 	int			nid;		/* home NUMA node */
 	struct list_head	node;		/* node in pisa_allocs */
 	char			name[48];
+	struct pisa_alloc_stats	stats;
 } ____cacheline_aligned;
 
+/* Active non-idle PISA pages held by @pa, for soft compaction checks. */
+static inline long pisa_alloc_held_pages(const struct pisa_alloc *pa)
+{
+	return (long)(READ_ONCE(pa->stats.page_alloc) -
+		      atomic64_read(&pa->stats.page_free)) -
+	       READ_ONCE(pa->num_idle_pages);
+}
+
 /* Max block order for predefined per-node allocators in pisa_node.pa[][]. */
 #define PISA_MAX_ALLOC_ORDER	3U
 
@@ -117,6 +133,12 @@ extern struct pisa_node pisa_nodes[MAX_NUMNODES];
 int pisa_meta_ensure_pfn(unsigned long pfn, bool can_block);
 void pisa_slots_configure(void);
 
+/* Default global cap: 1/8 of RAM, at least 16 PISA pages. */
+static inline unsigned long pisa_default_max_pages(void)
+{
+	return max(totalram_pages() >> (PISA_ORDER + 3), 16UL);
+}
+
 static inline unsigned long pisa_meta_to_pfn(const struct pisa_meta *meta)
 {
 	return meta->base_pfn;
@@ -129,6 +151,16 @@ static inline struct page *pisa_meta_to_page(const struct pisa_meta *meta)
 
 void pisa_slot_free(struct pisa_meta *meta);
 
+struct shrink_control;
+struct shrinker;
+#if IS_ENABLED(CONFIG_KUNIT)
+unsigned long pisa_shrink_scan(struct shrinker *shrink, struct shrink_control *sc);
+#endif
+
+/* Global PISA page budget across all allocators and per-node reservoirs. */
+extern atomic_long_t pisa_nr_pages;
+extern unsigned long pisa_max_pages;
+
 static inline int pisa_sanitize_nid(int nid)
 {
 	if ((unsigned int)nid >= MAX_NUMNODES || !node_state(nid, N_MEMORY))
@@ -175,12 +207,18 @@ static inline struct page *pisa_alloc(struct pisa_alloc *pa, gfp_t gfp)
 	return page;
 }
 
+#define PISA_OLD_MS_MAX		100000U
+unsigned long pisa_shrink_list(spinlock_t *lock, struct list_head *list,
+			       unsigned int *nr, struct list_head *release_list,
+			       unsigned long nr_to_scan);
+
 /* pisa-node.c: per-NUMA-node PISA page reservoir and work item */
 extern unsigned int pisa_reservoir_max;
 void pisa_node_init(void);
 void pisa_schedule_reservoir(void);
 struct pisa_meta *pisa_reservoir_pop(int nid, gfp_t gfp, bool *clean);
 unsigned long pisa_reservoir_count(void);
+unsigned long pisa_reservoir_shrink(struct list_head *release_list, unsigned long nr_to_scan);
 
 #endif /* CONFIG_PISA */
 #endif /* _MM_PISA_PRIV_H */
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#71 lore raw

RFC PATCH v3 6/25 iommu/dma: Map PISA memory in a per-domain IOVA window

In reply to Luigi Rizzo

Each PISA page may have to be mapped in multiple IOMMU domains, and PISA buffers must be recognized quickly from their IOVA. Both problems are solved by reserving, in each domain, an IOVA window that only holds PISA pages. With this:
- a PISA page is mapped at offset "slot * 2MB" in each domain, so there is no need to track individual offsets and one bit per domain suffices to tell whether the page is mapped.
- since the reserved IOVA window is only used for PISA memory, a simple address comparison suffices to identify a PISA-backed buffer.

Reserve an IOVA window in each domain, and use it to map PISA pages as described above. Unmapping becomes a no-op, after a quick identification of the address. The actual unmapping happens when the backing PISA page is retired, or when the domain has no more users.

---
 drivers/iommu/Makefile     |   3 +
 drivers/iommu/dma-iommu.c  |  39 +++-
 drivers/iommu/iommu.c      |   7 +-
 drivers/iommu/pisa-map.c   | 385 +++++++++++++++++++++++++++++++++++++
 include/linux/pisa-iommu.h |  42 +++-
 include/linux/pisa.h       |  95 +++++++++
 mm/Kconfig                 |   1 +
 mm/pisa-alloc.c            |   4 +
 mm/pisa-kunit.c            | 170 ++++++++++++++++
 mm/pisa-node.c             |   3 +-
 mm/pisa-priv.h             |  10 +
 11 files changed, 755 insertions(+), 4 deletions(-)
 create mode 100644 drivers/iommu/pisa-map.c
drivers/iommu/Makefile +3 -0
index 29a26d2a3af12..a04b4458efaaa 100644
@@ -11,6 +11,9 @@ obj-$(CONFIG_IOMMU_API) += iommu-traces.o
 obj-$(CONFIG_IOMMU_API) += iommu-sysfs.o
 obj-$(CONFIG_IOMMU_DEBUGFS) += iommu-debugfs.o
 obj-$(CONFIG_IOMMU_DMA) += dma-iommu.o
+ifdef CONFIG_IOMMU_DMA
+obj-$(CONFIG_PISA) += pisa-map.o
+endif
 obj-$(CONFIG_IOMMU_IO_PGTABLE) += io-pgtable.o
 obj-$(CONFIG_IOMMU_IO_PGTABLE_ARMV7S) += io-pgtable-arm-v7s.o
 obj-$(CONFIG_IOMMU_IO_PGTABLE_LPAE) += io-pgtable-arm.o
drivers/iommu/dma-iommu.c +38 -1
index 78742aeba932d..9b26d0aee9a97 100644
@@ -36,6 +36,7 @@
 #include <trace/events/swiotlb.h>
 
 #include "dma-iommu.h"
+#include <linux/pisa.h>
 #include "iommu-pages.h"
 #include "iommu-priv.h"
 
@@ -76,6 +77,8 @@ struct iommu_dma_cookie {
 	struct iommu_domain *fq_domain;
 	/* Options for dma-iommu use */
 	struct iommu_dma_options options;
+	/* IOVA window reserved for PISA pages. Nothing else can go here. */
+	struct pisa_iova pisa_iova;
 };
 
 struct iommu_dma_msi_cookie {
@@ -379,6 +382,7 @@ int iommu_get_dma_cookie(struct iommu_domain *domain)
 		return -ENOMEM;
 
 	INIT_LIST_HEAD(&cookie->msi_page_list);
+	cookie->pisa_iova.iovad = &cookie->iovad;
 	domain->cookie_type = IOMMU_COOKIE_DMA_IOVA;
 	domain->iova_cookie = cookie;
 	return 0;
@@ -427,6 +431,9 @@ void iommu_put_dma_cookie(struct iommu_domain *domain)
 	struct iommu_dma_cookie *cookie = domain->iova_cookie;
 	struct iommu_dma_msi_page *msi, *tmp;
 
+	/* Drop cached PISA mappings before the IOVA domain goes away. */
+	pisa_domain_release(domain);
+
 	if (cookie->iovad.granule) {
 		iommu_dma_free_fq(cookie);
 		put_iova_domain(&cookie->iovad);
@@ -831,6 +838,8 @@ static void __iommu_dma_unmap(struct device *dev, dma_addr_t dma_addr,
 	struct iommu_iotlb_gather iotlb_gather;
 	size_t unmapped;
 
+	if (is_pisa_iova(&cookie->pisa_iova, dma_addr))
+		return;
 	dma_addr -= iova_off;
 	size = iova_align(iovad, size + iova_off);
 	iommu_iotlb_gather_init(&iotlb_gather);
@@ -857,6 +866,8 @@ static dma_addr_t __iommu_dma_map(struct device *dev, phys_addr_t phys,
 	    iommu_deferred_attach(dev, domain))
 		return DMA_MAPPING_ERROR;
 
+	if (pisa_map_phys(&iova, dev, domain, phys, size, prot))
+		return iova;
 	/* If anyone ever wants this we'd need support in the IOVA allocator */
 	if (dev_WARN_ONCE(dev, dma_get_min_align_mask(dev) > iova_mask(iovad),
 	    "Unsupported alignment constraint\n"))
@@ -1215,6 +1226,16 @@ static inline size_t iova_unaligned(struct iova_domain *iovad, phys_addr_t phys,
 	return iova_offset(iovad, phys | size);
 }
 
+/* Return @domain's PISA window, or NULL if @domain cannot use PISA. */
+struct pisa_iova *pisa_dma_iova(struct iommu_domain *domain)
+{
+	if (static_branch_unlikely(&iommu_deferred_attach_enabled) || !domain ||
+	    domain->cookie_type != IOMMU_COOKIE_DMA_IOVA)
+		return NULL;
+
+	return &domain->iova_cookie->pisa_iova;
+}
+
 dma_addr_t iommu_dma_map_phys(struct device *dev, phys_addr_t phys, size_t size,
 		enum dma_data_direction dir, unsigned long attrs)
 {
@@ -1256,6 +1277,10 @@ void iommu_dma_unmap_phys(struct device *dev, dma_addr_t dma_handle,
 {
 	phys_addr_t phys;
 
+	/* PISA mapped buffer: nothing to unmap or release. */
+	if (is_pisa_iova(&iommu_get_dma_domain(dev)->iova_cookie->pisa_iova, dma_handle))
+		return;
+
 	if (attrs & (DMA_ATTR_MMIO | DMA_ATTR_REQUIRE_COHERENT)) {
 		__iommu_dma_unmap(dev, dma_handle, size);
 		return;
@@ -1457,6 +1482,13 @@ int iommu_dma_map_sg(struct device *dev, struct scatterlist *sg, int nents,
 			 */
 			break;
 		case PCI_P2PDMA_MAP_NONE:
+			/* Map PISA pages and mark as bus addresses to skip IOVA alloc and map. */
+			if (pisa_map_phys(&s->dma_address, dev, domain,
+					  sg_phys(s), s_length, prot)) {
+				sg_dma_len(s) = s_length;
+				sg_dma_mark_bus_address(s);
+				continue;
+			}
 			break;
 		case PCI_P2PDMA_MAP_BUS_ADDR:
 			/*
@@ -1822,7 +1854,12 @@ bool dma_iova_try_alloc(struct device *dev, struct dma_iova_state *state,
 	dma_addr_t addr;
 
 	memset(state, 0, sizeof(*state));
-	if (!use_dma_iommu(dev))
+	/*
+	 * PISA memory is mapped in its own IOVA window. A PISA page whose
+	 * protection does not cover the request is declined here too, and
+	 * __iommu_dma_map() then maps it as ordinary memory, page by page.
+	 */
+	if (!use_dma_iommu(dev) || is_pisa_phys(phys))
 		return false;
 
 	domain = iommu_get_dma_domain(dev);
drivers/iommu/iommu.c +6 -1
index b486b8bbd1fcd..ac49b3b33ced6 100644
@@ -37,6 +37,7 @@
 #include <linux/generic_pt/iommu.h>
 
 #include "dma-iommu.h"
+#include <linux/pisa.h>
 #include "iommu-priv.h"
 
 static struct kset *iommu_group_kset;
@@ -2867,7 +2868,7 @@ ssize_t iommu_map_sg(struct iommu_domain *domain, unsigned long iova,
 	while (i <= nents) {
 		phys_addr_t s_phys = sg_phys(sg);
 
-		if (len && s_phys != start + len) {
+		if (len && (sg_dma_is_bus_address(sg) || s_phys != start + len)) {
 			ret = iommu_map_nosync(domain, iova + mapped, start,
 					len, prot, gfp);
 			if (ret)
@@ -3363,6 +3364,10 @@ void iommu_device_unuse_default_domain(struct device *dev)
 	if (!WARN_ON(!group->owner_cnt || !xa_empty(&group->pasid_array)))
 		group->owner_cnt--;
 
+	/* Unmap persistent PISA windows when the last driver detaches. */
+	if (!group->owner_cnt)
+		pisa_domain_quiesce(group->default_domain);
+
 	mutex_unlock(&group->mutex);
 }
 
drivers/iommu/pisa-map.c new file +385 -0

385 lines not on this page · raw message

include/linux/pisa-iommu.h +41 -1

88 lines not on this page · raw message

include/linux/pisa.h +95 -0

115 lines not on this page · raw message

mm/Kconfig +1 -0
index 6e7811569d33a..f96c4017519ee 100644
@@ -1436,6 +1436,7 @@ config PISA
 	bool "Pre-mapped IOVA Superpage Allocator"
 	depends on (X86_64 && !UML) || (ARM64 && ARM64_4K_PAGES && PGTABLE_LEVELS >= 4)
 	depends on SPARSEMEM && !PREEMPT_RT
+	select NEED_SG_DMA_FLAGS
 	default y
 	help
 	  PISA is a specialized memory allocator with an API similar to
mm/pisa-alloc.c +4 -0
index c09f321b07eeb..01d8bbc8d72ff 100644
@@ -13,6 +13,7 @@
 #include <linux/pisa.h>
 #include <linux/export.h>
 #include <linux/gfp.h>
+#include <linux/iommu.h>
 #include <linux/kasan.h>
 #include <linux/list.h>
 #include <linux/llist.h>
@@ -261,6 +262,8 @@ struct pisa_alloc *pisa_alloc_create(int nid, unsigned int order, enum dma_data_
 	spin_lock_init(&pa->lock);
 	pa->order = order;
 	pa->nid = nid;
+	pa->prot = (dir != DMA_FROM_DEVICE ? IOMMU_READ : 0) |
+		     (dir != DMA_TO_DEVICE ? IOMMU_WRITE : 0);
 	pisa_alloc_set_name(pa, "%ps", (void *)_RET_IP_);
 	INIT_LIST_HEAD(&pa->partial);
 	INIT_LIST_HEAD(&pa->partial_dirty);
@@ -585,6 +588,7 @@ static unsigned long __pisa_alloc_bulk(struct pisa_alloc *pa, gfp_t gfp, unsigne
 			goto out;
 		spin_lock_irqsave(&pa->lock, flags);
 		meta->pa = pa;
+		meta->prot = pa->prot;
 		WRITE_ONCE(meta->alloc_jiffies, jiffies);
 		/* Set PISA_ACTIVE after @meta is fully set up. */
 		pisa_meta_set_flags(meta, PISA_ACTIVE);
mm/pisa-kunit.c +170 -0

188 lines not on this page · raw message

mm/pisa-node.c +2 -1
index 29f6ba866b633..a39251b952263 100644
@@ -171,7 +171,8 @@ void pisa_release_page(struct pisa_meta *meta)
 	/* Count it now: pisa_alloc_held_pages() must not see a retiring page as held. */
 	atomic64_inc(&meta->pa->stats.page_free);
 
-	/* pisa_unmap_all_domains(meta) will be called here once IOMMU mappings are added. */
+	/* Quarantined on unmap failure and leaked in pisa_release_page_rcu(). */
+	pisa_unmap_all_domains(meta);
 
 	/* Clear PISA_ACTIVE before the RCU grace period so new readers stop entering. */
 	pisa_meta_clear_flags(meta, PISA_ACTIVE);
mm/pisa-priv.h +10 -0
index a191ede9bf3ce..8736b8d168727 100644
@@ -16,6 +16,11 @@
 #include <linux/workqueue.h>
 
 
+#ifdef CONFIG_IOMMU_DMA
+int iommu_get_dma_cookie(struct iommu_domain *domain);
+void iommu_put_dma_cookie(struct iommu_domain *domain);
+#endif
+
 #ifdef CONFIG_PISA
 
 /* Number of order-@order blocks in one PISA page. */
@@ -31,6 +36,10 @@
  * 2. Metadata tables (mm/pisa-meta.c):
  *    pisa_meta_mutex (mutex): init and hotplug page-table population.
  *    pisa_slot_lock (spinlock): slot allocation and @pisa_meta_array PTE install.
+ *
+ * 3. IOMMU domains (drivers/iommu/pisa-map.c):
+ *    pisa_srcu -> pisa_domains_lock (spinlock, leaf over pisa_domains[]).
+ *    pisa_domains[].map_lock (spinlock): standalone per-domain iommu_map() lock.
  */
 
 /*
@@ -90,6 +99,7 @@ struct pisa_alloc {
 	/* First cacheline: hot fields touched on block alloc and free. */
 	spinlock_t		lock;
 	u8			order;		/* block order (<= PISA_ORDER) */
+	u8			prot;		/* IOMMU_READ and/or IOMMU_WRITE */
 	struct list_head	partial;	/* partial pages with nr_clean > 0 */
 	struct list_head	partial_dirty;	/* partial pages with nr_clean == 0 */
 	struct list_head	idle;		/* completely free PISA pages */
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#72 lore raw

RFC PATCH v3 7/25 driver core: Add per-device pisa_* sysfs attributes for PISA optin

In reply to Luigi Rizzo

Because of the performance and security implications, the use of PISA features is opt-in and configurable per device with a fine granularity.

Add boolean attributes to struct device exposed under /sys/devices/*/*/pisa_*:

  - pisa_coherent:     enable PISA for coherent allocations
  - pisa_rx_bufs:      enable PISA for RX buffers / page_pool
  - pisa_tx_bufs:      enable PISA for TX socket page frags

- pisa_tx_skb_heads: enable PISA slab cache for small TX skb heads
- pisa_tx_zerocopy: migrate MSG_ZEROCOPY user pages into PISA

---
 drivers/base/core.c    | 75 ++++++++++++++++++++++++++++++++++++++++++
 include/linux/device.h | 15 +++++++++
 include/linux/pisa.h   | 27 +++++++++++++++
 mm/pisa-alloc.c        | 21 ++++++++++++
 mm/pisa-kunit.c        | 71 +++++++++++++++++++++++++++++++++++++++
 5 files changed, 209 insertions(+)
drivers/base/core.c +75 -0
index cbe05197d4a0b..df93b6b6e125e 100644
@@ -25,6 +25,7 @@
 #include <linux/notifier.h>
 #include <linux/of.h>
 #include <linux/of_device.h>
+#include <linux/pisa.h>
 #include <linux/pm_runtime.h>
 #include <linux/sched/mm.h>
 #include <linux/sched/signal.h>
@@ -2907,6 +2908,65 @@ static ssize_t removable_show(struct device *dev, const struct device_attribute
 }
 static const DEVICE_ATTR_RO(removable);
 
+/* Per-device configuration to selectively enable PISA */
+static ssize_t pisa_attr_store(struct device *dev, const char *buf, size_t count,
+			       bool *field, int (*setter)(struct device *, bool))
+{
+	bool val;
+	int ret = kstrtobool(buf, &val);
+
+	if (ret < 0)
+		return ret;
+	if (val) {
+		ret = pisa_meta_init();
+		if (ret < 0)
+			return ret;
+	}
+	if (setter) {
+		ret = setter(dev, val);
+		if (ret < 0)
+			return ret;
+	} else {
+		WRITE_ONCE(*field, val);
+	}
+	return count;
+}
+
+#define PISA_SET_ATTR(name, setter)					\
+static ssize_t name##_show(struct device *dev,				\
+			   struct device_attribute *attr, char *buf)	\
+{									\
+	return sysfs_emit(buf, "%u\n", READ_ONCE(dev->name));		\
+}									\
+static ssize_t name##_store(struct device *dev,				\
+			    struct device_attribute *attr,		\
+			    const char *buf, size_t count)		\
+{									\
+	return pisa_attr_store(dev, buf, count, &dev->name, setter);	\
+}									\
+static DEVICE_ATTR_RW(name)
+
+#define PISA_BOOL_ATTR(name)	PISA_SET_ATTR(name, NULL)
+
+PISA_BOOL_ATTR(pisa_coherent);
+PISA_BOOL_ATTR(pisa_rx_bufs);
+PISA_BOOL_ATTR(pisa_tx_bufs);
+PISA_BOOL_ATTR(pisa_tx_skb_heads);
+PISA_BOOL_ATTR(pisa_tx_zerocopy);
+
+static struct attribute *dev_attr_pisa[] = {
+	&dev_attr_pisa_coherent.attr,
+	&dev_attr_pisa_rx_bufs.attr,
+	&dev_attr_pisa_tx_bufs.attr,
+	&dev_attr_pisa_tx_skb_heads.attr,
+	&dev_attr_pisa_tx_zerocopy.attr,
+	NULL,
+};
+
+static const struct attribute_group dev_attr_pisa_group = {
+	.attrs = dev_attr_pisa,
+};
+
 int device_add_groups(struct device *dev,
 		      const struct attribute_group *const *groups)
 {
@@ -3014,6 +3074,18 @@ static int device_add_attrs(struct device *dev)
 			goto err_remove_dev_removable;
 	}
 
+	if (IS_ENABLED(CONFIG_PISA) && dev->dma_mask) {
+		error = device_add_group(dev, &dev_attr_pisa_group);
+		if (error) {
+			if (dev->physical_location) {
+				device_remove_group(dev, &dev_attr_physical_location_group);
+				kfree(dev->physical_location);
+				dev->physical_location = NULL;
+			}
+			goto err_remove_dev_removable;
+		}
+	}
+
 	return 0;
 
  err_remove_dev_removable:
@@ -3039,6 +3111,9 @@ static void device_remove_attrs(struct device *dev)
 	const struct class *class = dev->class;
 	const struct device_type *type = dev->type;
 
+	if (IS_ENABLED(CONFIG_PISA) && dev->dma_mask)
+		device_remove_group(dev, &dev_attr_pisa_group);
+
 	if (dev->physical_location) {
 		device_remove_group(dev, &dev_attr_physical_location_group);
 		kfree(dev->physical_location);
include/linux/device.h +15 -0
index 429e39f647cf9..e705df38e49af 100644
@@ -695,6 +695,15 @@ enum struct_device_flags {
  * @removable:  Whether the device can be removed from the system. This
  *              should be set by the subsystem / bus driver that discovered
  *              the device.
+ * @pisa_coherent: Back coherent dma_alloc_attrs() with PISA
+ *		(sysfs pisa_coherent).
+ * @pisa_rx_bufs: Use PISA allocators for RX buffers (sysfs pisa_rx_bufs).
+ * @pisa_tx_bufs: Use PISA allocators for socket TX page fragments
+ *		(sysfs pisa_tx_bufs).
+ * @pisa_tx_skb_heads: Use PISA slab cache for small TX skb heads
+ *		(sysfs pisa_tx_skb_heads).
+ * @pisa_tx_zerocopy: Migrate MSG_ZEROCOPY user pages into PISA
+ *		(sysfs pisa_tx_zerocopy).
  * @flags:	DEV_FLAG_XXX flags. Use atomic bitfield operations to modify.
  *
  * At the lowest level, every device in a Linux system is represented by an
@@ -799,6 +808,12 @@ struct device {
 
 	enum device_removable	removable;
 
+	bool			pisa_coherent;
+	bool			pisa_rx_bufs;
+	bool			pisa_tx_bufs;
+	bool			pisa_tx_skb_heads;
+	bool			pisa_tx_zerocopy;
+
 	DECLARE_BITMAP(flags, DEV_FLAG_COUNT);
 };
 
include/linux/pisa.h +27 -0
index cc33e181df097..5222cb207257f 100644
@@ -84,6 +84,7 @@ static inline u64 pisa_iova_size(void)
 }
 
 int pisa_meta_init(void);
+bool __pisa_has_free_blocks_rx(unsigned int order, int nid);
 bool __pisa_page_can_recycle(const struct page *page);
 
 static inline bool pisa_enabled(void)
@@ -142,6 +143,21 @@ static inline struct page *pisa_virt_to_page(const void *addr)
 	return is_pisa_page(page) ? page : NULL;
 }
 
+/* Hook for __page_pool_alloc_netmems_slow() (guarded by @pisa_key). */
+static inline gfp_t pisa_rx_gfp(const struct device *dev)
+{
+	return pisa_enabled() && dev && READ_ONCE(dev->pisa_rx_bufs) ?
+	       __GFP_PISA_RW : 0;
+}
+
+/* Hook for NIC driver RX buffer allocation (guarded by @pisa_key). */
+static inline bool pisa_has_free_blocks_rx(const struct device *dev,
+					   unsigned int order, int nid)
+{
+	return pisa_enabled() && dev && READ_ONCE(dev->pisa_rx_bufs) &&
+	       __pisa_has_free_blocks_rx(order, nid);
+}
+
 /* Hook for skb_page_frag_refill() and __pisa_free_page() (@pisa_recycle_check_key). */
 static inline bool pisa_page_can_recycle(const struct page *page)
 {
@@ -158,6 +174,17 @@ static inline bool is_pisa_page(const struct page *page) { return false; }
 static inline bool is_pisa_phys(phys_addr_t phys) { return false; }
 static inline struct page *pisa_virt_to_page(const void *addr) { return NULL; }
 
+static inline gfp_t pisa_rx_gfp(const struct device *dev)
+{
+	return 0;
+}
+
+static inline bool pisa_has_free_blocks_rx(const struct device *dev,
+					   unsigned int order, int nid)
+{
+	return false;
+}
+
 static inline bool pisa_page_can_recycle(const struct page *page)
 {
 	return true;
mm/pisa-alloc.c +21 -0
index 01d8bbc8d72ff..ff8565c3206ad 100644
@@ -9,6 +9,7 @@
 #include <linux/bitmap.h>
 #include <linux/bitops.h>
 #include <linux/cache.h>
+#include <linux/device.h>
 #include <linux/dma-mapping.h>
 #include <linux/pisa.h>
 #include <linux/export.h>
@@ -374,6 +375,26 @@ unsigned long __pisa_alloc_pages_bulk(gfp_t gfp, unsigned int order,
 	return pisa_alloc_bulk(pa, gfp & ~__GFP_PISA_RW, nr_pages, page_array, frozen);
 }
 
+/**
+ * __pisa_has_free_blocks_rx - Check if per-node RX allocator of @order on @nid has free blocks
+ * @order: Block order
+ * @nid: Target NUMA node (or NUMA_NO_NODE)
+ *
+ * Return: true if the per-node RX allocator has a free block available, or
+ * the node's reservoir has a PISA page to give it.
+ */
+bool __pisa_has_free_blocks_rx(unsigned int order, int nid)
+{
+	struct pisa_alloc *pa = pisa_node_pa(nid, order, false);
+
+	return pa &&
+	       (!list_empty_careful(&pa->partial) ||
+		!list_empty_careful(&pa->partial_dirty) ||
+		!list_empty_careful(&pa->idle) ||
+		READ_ONCE(pisa_nodes[pa->nid].nr_pages));
+}
+EXPORT_SYMBOL(__pisa_has_free_blocks_rx);
+
 /*
  * Split a non-compound page of @old_order into 1 << (@old_order - @new_order)
  * pages of @new_order (compound if @new_order > 0), all frozen at refcount 0.
mm/pisa-kunit.c +71 -0

89 lines not on this page · raw message

Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#73 lore raw

RFC PATCH v3 8/25 iommu/dma: Use PISA for coherent DMA allocations

In reply to Luigi Rizzo

Coherent DMA allocations (e.g. TX/RX descriptor rings allocated via dma_alloc_attrs() / dma_alloc_coherent()) are long-lived and accessed on every packet or I/O operation, so they benefit from sharing 2MB IOMMU leaf mappings.

When dev->pisa_coherent is enabled, serve coherent DMA allocations (dma_alloc_attrs()) up to 2MB with contiguous memory from PISA pages.

---
 drivers/iommu/dma-iommu.c  |   6 ++
 drivers/iommu/pisa-map.c   |  16 +++
 include/linux/pisa-iommu.h |   7 ++
 include/linux/pisa.h       |  38 +++++++
 kernel/dma/direct.c        |   7 ++
 mm/pisa-alloc.c            | 205 +++++++++++++++++++++++++++++++++++++
 mm/pisa-kunit.c            |  71 +++++++++++++
 mm/pisa-priv.h             |   3 +
 8 files changed, 353 insertions(+)
drivers/iommu/dma-iommu.c +6 -0
index 9b26d0aee9a97..45e9432d2a020 100644
@@ -1653,6 +1653,8 @@ static void __iommu_dma_free(struct device *dev, size_t size, void *cpu_addr)
 		dma_common_free_remap(cpu_addr, alloc_size);
 	} else {
 		/* Lowmem means a coherent atomic or CMA allocation */
+		if (pisa_free_coherent(cpu_addr, alloc_size))
+			return;
 		page = virt_to_page(cpu_addr);
 	}
 
@@ -1723,6 +1725,10 @@ void *iommu_dma_alloc(struct device *dev, size_t size, dma_addr_t *handle,
 
 	gfp |= __GFP_ZERO;
 
+	cpu_addr = pisa_alloc_map_coherent(dev, size, handle, gfp, attrs);
+	if (cpu_addr)
+		return cpu_addr;
+
 	if (gfpflags_allow_blocking(gfp) &&
 	    !(attrs & DMA_ATTR_FORCE_CONTIGUOUS)) {
 		return iommu_dma_alloc_remap(dev, size, handle, gfp, attrs);
drivers/iommu/pisa-map.c +16 -0
index 3ff9f1a6c5b85..bbf330877f824 100644
@@ -10,6 +10,7 @@
 #include <linux/dma-map-ops.h>
 #include <linux/dma-mapping.h>
 #include <linux/iommu.h>
+#include <linux/iommu-dma.h>
 #include <linux/iova.h>
 #include <linux/log2.h>
 #include <linux/mm.h>
@@ -18,6 +19,8 @@
 #include <linux/spinlock.h>
 #include <linux/srcu.h>
 
+#include "iommu-priv.h"
+
 
 /*
  * Registry of PISA IOMMU domains. Each slot is FREE (!domain && !base),
@@ -191,6 +194,19 @@ void __pisa_domain_quiesce(struct iommu_domain *domain)
 			 done, domain, idx);
 }
 
+/*
+ * Set *@domain to the DMA domain of @dev, or to NULL if @dev does not use
+ * dma-iommu. Returns an error if a deferred attach of @dev fails.
+ */
+int pisa_dev_dma_domain(struct device *dev, struct iommu_domain **domain)
+{
+	*domain = NULL;
+	if (!use_dma_iommu(dev))
+		return 0;
+	*domain = iommu_get_dma_domain(dev);
+	return iommu_deferred_attach(dev, *domain);
+}
+
 /* Return negative errno if @pi's domain was permanently/currently declined, or 0. */
 int pisa_iova_declined(const struct pisa_iova *pi)
 {
include/linux/pisa-iommu.h +7 -0
index d4c01207dca72..568108747f575 100644
@@ -96,6 +96,7 @@ static inline dma_addr_t pisa_phys_to_iova(const struct pisa_iova *pi,
 extern unsigned int pisa_domains_generation;
 
 void pisa_unmap_all_domains(struct pisa_meta *meta);
+int pisa_dev_dma_domain(struct device *dev, struct iommu_domain **domain);
 int pisa_iova_declined(const struct pisa_iova *pi);
 
 #else /* !CONFIG_PISA || !CONFIG_IOMMU_DMA */
@@ -103,5 +104,11 @@ int pisa_iova_declined(const struct pisa_iova *pi);
 static inline void pisa_unmap_all_domains(struct pisa_meta *meta) {}
 static inline int pisa_iova_declined(const struct pisa_iova *pi) { return -EOPNOTSUPP; }
 
+static inline int pisa_dev_dma_domain(struct device *dev, struct iommu_domain **domain)
+{
+	*domain = NULL;
+	return 0;
+}
+
 #endif /* CONFIG_PISA && CONFIG_IOMMU_DMA */
 #endif /* _LINUX_PISA_IOMMU_H */
include/linux/pisa.h +38 -0
index 5222cb207257f..edd34771ad1c4 100644
@@ -84,6 +84,9 @@ static inline u64 pisa_iova_size(void)
 }
 
 int pisa_meta_init(void);
+void *__pisa_alloc_map_coherent_dev(struct device *dev, size_t size,
+				    dma_addr_t *dma_handle, gfp_t gfp,
+				    unsigned long attrs);
 bool __pisa_has_free_blocks_rx(unsigned int order, int nid);
 bool __pisa_page_can_recycle(const struct page *page);
 
@@ -143,6 +146,29 @@ static inline struct page *pisa_virt_to_page(const void *addr)
 	return is_pisa_page(page) ? page : NULL;
 }
 
+/* Hook for iommu_dma_alloc() and dma_direct_alloc() (guarded by @pisa_key). */
+static inline void *pisa_alloc_map_coherent(struct device *dev, size_t size,
+					    dma_addr_t *dma_handle, gfp_t gfp,
+					    unsigned long attrs)
+{
+	if (!pisa_enabled() || !READ_ONCE(dev->pisa_coherent))
+		return NULL;
+	return __pisa_alloc_map_coherent_dev(dev, size, dma_handle, gfp, attrs);
+}
+
+/* Hook for __iommu_dma_free() and dma_direct_free() (guarded by @pisa_key). */
+static inline bool pisa_free_coherent(const void *cpu_addr, size_t size)
+{
+	unsigned long count = PAGE_ALIGN(size) >> PAGE_SHIFT;
+	struct page *page = pisa_virt_to_page(cpu_addr);
+
+	if (!page)
+		return false;
+	while (count--)
+		__free_page(page++);
+	return true;
+}
+
 /* Hook for __page_pool_alloc_netmems_slow() (guarded by @pisa_key). */
 static inline gfp_t pisa_rx_gfp(const struct device *dev)
 {
@@ -174,6 +200,18 @@ static inline bool is_pisa_page(const struct page *page) { return false; }
 static inline bool is_pisa_phys(phys_addr_t phys) { return false; }
 static inline struct page *pisa_virt_to_page(const void *addr) { return NULL; }
 
+static inline void *pisa_alloc_map_coherent(struct device *dev, size_t size,
+					    dma_addr_t *dma_handle, gfp_t gfp,
+					    unsigned long attrs)
+{
+	return NULL;
+}
+
+static inline bool pisa_free_coherent(const void *cpu_addr, size_t size)
+{
+	return false;
+}
+
 static inline gfp_t pisa_rx_gfp(const struct device *dev)
 {
 	return 0;
kernel/dma/direct.c +7 -0
index 25e9a86835fd3..9ac4912e4a0a1 100644
@@ -15,6 +15,7 @@
 #include <linux/slab.h>
 #include <linux/pci-p2pdma.h>
 #include <linux/cc_platform.h>
+#include <linux/pisa.h>
 
 #include "direct.h"
 
@@ -244,6 +245,10 @@ void *dma_direct_alloc(struct device *dev, size_t size,
 	if (attrs & DMA_ATTR_NO_WARN)
 		gfp |= __GFP_NOWARN;
 
+	cpu_addr = pisa_alloc_map_coherent(dev, size, dma_handle, gfp, attrs);
+	if (cpu_addr)
+		return cpu_addr;
+
 	if (dma_direct_use_no_mapping(dev, attrs))
 		return dma_direct_alloc_no_mapping(dev, size, dma_handle, gfp);
 
@@ -424,6 +429,8 @@ void dma_direct_free(struct device *dev, size_t size,
 
 	if (is_vmalloc_addr(cpu_addr)) {
 		vunmap(cpu_addr);
+	} else if (pisa_free_coherent(cpu_addr, size)) {
+		return;
 	} else {
 		if (IS_ENABLED(CONFIG_ARCH_HAS_DMA_CLEAR_UNCACHED))
 			arch_dma_clear_uncached(cpu_addr, size);
mm/pisa-alloc.c +205 -0

228 lines not on this page · raw message

mm/pisa-kunit.c +71 -0

89 lines not on this page · raw message

mm/pisa-priv.h +3 -0
index 8736b8d168727..fb26eb3aa9b37 100644
@@ -165,6 +165,9 @@ struct shrink_control;
 struct shrinker;
 #if IS_ENABLED(CONFIG_KUNIT)
 unsigned long pisa_shrink_scan(struct shrinker *shrink, struct shrink_control *sc);
+void *__pisa_alloc_map_coherent(struct device *dev, struct iommu_domain *domain,
+				size_t size, dma_addr_t *dma_handle, gfp_t gfp,
+				unsigned long attrs);
 #endif
 
 /* Global PISA page budget across all allocators and per-node reservoirs. */
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#74 lore raw

RFC PATCH v3 9/25 mm: Add per-CPU block caches to PISA allocators

In reply to Luigi Rizzo

Every block allocation and free takes the allocator's lock. Highly concurrent users e.g. socket tx fragments, can cause significant lock contention.

Add pisa_enable_pcp(), an opt-in per-CPU front cache, similar to the page allocator's per-CPU lists:

- Each per-CPU cache keeps up to 64 free blocks, and refills it from the main allocator in batches of 32.
- returned blocks belonging to the local NUMA node are kept in the local cache.
- returned blocks belonging to a remote NUMA node are returned to the proper per-node allocator.
The cache is fully integrated with the shrinker and CPU offlining to drain the cache.

Enable per-CPU caches for the per-node order-0 RW and SKB_FRAG_PAGE_ORDER RO allocators.

---
 mm/pisa-alloc.c | 272 ++++++++++++++++++++++++++++++++++++++++++++++--
 mm/pisa-kunit.c |  79 ++++++++++++++
 mm/pisa-priv.h  |  11 +-
 3 files changed, 348 insertions(+), 14 deletions(-)
mm/pisa-alloc.c +261 -11
index eda12d475c9a7..896709303f258 100644
@@ -9,6 +9,7 @@
 #include <linux/bitmap.h>
 #include <linux/bitops.h>
 #include <linux/cache.h>
+#include <linux/cpuhotplug.h>
 #include <linux/device.h>
 #include <linux/dma-direct.h>
 #include <linux/dma-map-ops.h>
@@ -26,6 +27,7 @@
 #include <linux/moduleparam.h>
 #include <linux/mutex.h>
 #include <linux/page_owner.h>
+#include <linux/percpu.h>
 #include <linux/pgalloc_tag.h>
 #include <linux/page_table_check.h>
 #include <linux/pci.h>
@@ -324,13 +326,168 @@ static bool pisa_return_block_locked(struct pisa_alloc *pa, struct page *block)
 	return pisa_place_meta(meta);
 }
 
+/* Return @n freed blocks to @pa under a single acquisition of @pa->lock. */
+static void pisa_free_bulk(struct pisa_alloc *pa, unsigned int n, struct page **blocks)
+{
+	bool released = false;
+	unsigned long flags;
+
+	spin_lock_irqsave(&pa->lock, flags);
+	for (unsigned int i = 0; i < n; i++) {
+		if (likely(!is_pisa_block_poisoned(pa, blocks[i])))
+			released |= pisa_return_block_locked(pa, blocks[i]);
+	}
+	spin_unlock_irqrestore(&pa->lock, flags);
+
+	if (released)
+		pisa_schedule_reclaim();
+}
+
+/*
+ * Per-CPU block cache: each CPU caches up to PISA_PCP_HIGH free blocks
+ * (refcount 0, not in bitmaps), refilling and flushing in PISA_PCP_BATCH
+ * batches. Drained by the shrinker and CPU hotplug.
+ */
+#define PISA_PCP_BATCH	32U	/* blocks moved per refill or flush */
+
+struct pisa_pcp {
+	spinlock_t	lock;	/* by this CPU, or by a drain from any CPU */
+	unsigned int	count;
+	struct page	*blocks[PISA_PCP_HIGH];
+};
+
+/* Max blocks moved per per-CPU cache refill or flush (1..PISA_PCP_BATCH). */
+static unsigned int pisa_pcp_batch __read_mostly = PISA_PCP_BATCH;
+
+static int pisa_pcp_batch_set(const char *val, const struct kernel_param *kp)
+{
+	return param_set_uint_minmax(val, kp, 1, PISA_PCP_BATCH);
+}
+
+static const struct kernel_param_ops pisa_pcp_batch_ops = {
+	.set = pisa_pcp_batch_set,
+	.get = param_get_uint,
+};
+module_param_cb(pcp_batch, &pisa_pcp_batch_ops, &pisa_pcp_batch, 0644);
+
+static inline unsigned int pisa_pcp_batch_order(const struct pisa_alloc *pa)
+{
+	return max(1U, READ_ONCE(pisa_pcp_batch) >> pa->order);
+}
+
+/* Cache @n blocks at refcount 0 on this CPU, @n <= PISA_PCP_BATCH. */
+static void pisa_pcp_push(struct pisa_alloc *pa, unsigned int n, struct page **blocks)
+{
+	unsigned int batch = pisa_pcp_batch_order(pa);
+	unsigned int high = max(2U, PISA_PCP_HIGH >> pa->order);
+	struct pisa_pcp *pcp;
+	unsigned long flags;
+
+	/* @pcp->lock protects the cache: migrating to another CPU here is harmless. */
+	pcp = raw_cpu_ptr(pa->pcp);
+	spin_lock_irqsave(&pcp->lock, flags);
+	for (unsigned int i = 0; i < n; i++) {
+		if (pcp->count >= high) {
+			/* Keep the most recently freed, likely still in cache. */
+			pisa_free_bulk(pa, batch, pcp->blocks);
+			pcp->count -= batch;
+			memmove(pcp->blocks, pcp->blocks + batch,
+				pcp->count * sizeof(*pcp->blocks));
+		}
+		pcp->blocks[pcp->count++] = blocks[i];
+	}
+	spin_unlock_irqrestore(&pcp->lock, flags);
+}
+
+/* Take up to @nr blocks, at refcount 0, from this CPU's cache. */
+static unsigned int pisa_pcp_pop(struct pisa_alloc *pa, unsigned int nr, struct page **out)
+{
+	struct pisa_pcp *pcp;
+	unsigned int got = 0;
+	unsigned long flags;
+
+	/* @pcp->lock protects the cache: migrating to another CPU here is harmless. */
+	pcp = raw_cpu_ptr(pa->pcp);
+	spin_lock_irqsave(&pcp->lock, flags);
+	while (got < nr && pcp->count)
+		out[got++] = pcp->blocks[--pcp->count];
+	spin_unlock_irqrestore(&pcp->lock, flags);
+
+	return got;
+}
+
+/* Return the blocks @cpu caches for @pa. */
+static void pisa_pcp_drain_cpu(struct pisa_alloc *pa, int cpu)
+{
+	struct pisa_pcp *pcp = per_cpu_ptr(pa->pcp, cpu);
+
+	if (!READ_ONCE(pcp->count))
+		return;
+	guard(spinlock_irqsave)(&pcp->lock);
+	if (pcp->count) {
+		pisa_free_bulk(pa, pcp->count, pcp->blocks);
+		pcp->count = 0;
+	}
+}
+
+/* Drain every non-empty CPU cache of @pa. */
+void pisa_pcp_drain(struct pisa_alloc *pa)
+{
+	int cpu;
+
+	/* Pairs with smp_store_release() in pisa_enable_pcp(). */
+	if (!smp_load_acquire(&pa->pcp))
+		return;
+	for_each_possible_cpu(cpu)
+		pisa_pcp_drain_cpu(pa, cpu);
+}
+
+/* Blocks in @pa's caches, for shrinker and debugfs. */
+static unsigned long pisa_pcp_count(struct pisa_alloc *pa)
+{
+	unsigned long n = 0;
+	int cpu;
+
+	if (!pa->pcp)
+		return 0;
+	for_each_possible_cpu(cpu) {
+		/* A racy sum is good enough for reclaim and statistics. */
+		n += data_race(per_cpu_ptr(pa->pcp, cpu)->count);
+	}
+	return n;
+}
+
+/**
+ * pisa_enable_pcp - Put per-CPU block caches in front of an allocator
+ * @pa: Allocator to cache
+ *
+ * Return: 0, or -ENOMEM; @pa works without the cache.
+ */
+int pisa_enable_pcp(struct pisa_alloc *pa)
+{
+	struct pisa_pcp __percpu *pcp;
+	int cpu;
+
+	if (!pa || pa->pcp)
+		return 0;
+	pcp = alloc_percpu(struct pisa_pcp);
+	if (!pcp)
+		return -ENOMEM;
+	for_each_possible_cpu(cpu)
+		spin_lock_init(&per_cpu_ptr(pcp, cpu)->lock);
+	/* Publish initialized locks; readers depend on the pointer. */
+	if (cmpxchg_release(&pa->pcp, NULL, pcp))
+		free_percpu(pcp);
+	return 0;
+}
+
 static DEFINE_MUTEX(pisa_init_mutex);
 
 /* Return *@pap, creating and publishing it under @pisa_init_mutex if NULL. */
-__printf(5, 6)
+__printf(6, 7)
 struct pisa_alloc *pisa_alloc_ensure(struct pisa_alloc **pap, int nid,
 				     unsigned int order, enum dma_data_direction dir,
-				     const char *fmt, ...)
+				     bool pcp, const char *fmt, ...)
 {
 	/* Pairs with smp_store_release() below. */
 	struct pisa_alloc *pa = smp_load_acquire(pap);
@@ -349,6 +506,8 @@ struct pisa_alloc *pisa_alloc_ensure(struct pisa_alloc **pap, int nid,
 		va_start(args, fmt);
 		vsnprintf(pa->name, sizeof(pa->name), fmt, args);
 		va_end(args);
+		if (pcp)
+			pisa_enable_pcp(pa);
 		/* Pairs with smp_load_acquire() in lockless readers. */
 		smp_store_release(pap, pa);
 	}
@@ -392,7 +551,9 @@ bool __pisa_has_free_blocks_rx(unsigned int order, int nid)
 	struct pisa_alloc *pa = pisa_node_pa(nid, order, false);
 
 	return pa &&
-	       (!list_empty_careful(&pa->partial) ||
+	       /* Pairs with cmpxchg_release() in pisa_enable_pcp(). */
+	       ((smp_load_acquire(&pa->pcp) && raw_cpu_read(pa->pcp->count)) ||
+		!list_empty_careful(&pa->partial) ||
 		!list_empty_careful(&pa->partial_dirty) ||
 		!list_empty_careful(&pa->idle) ||
 		READ_ONCE(pisa_nodes[pa->nid].nr_pages));
@@ -636,6 +797,58 @@ static unsigned long __pisa_alloc_bulk(struct pisa_alloc *pa, gfp_t gfp, unsigne
 	return n;
 }
 
+/* Allocate @nr_pages blocks through this CPU's cache, refilling in batches on miss. */
+static unsigned long pisa_pcp_alloc(struct pisa_alloc *pa, gfp_t gfp, unsigned long nr_pages,
+				    struct page **page_array, bool frozen)
+{
+	unsigned int pcp_batch = pisa_pcp_batch_order(pa);
+	unsigned long got, j = 0;
+
+	got = pisa_pcp_pop(pa, nr_pages, page_array);
+	if (got < nr_pages) {
+		if (nr_pages - got >= pcp_batch) {
+			got += __pisa_alloc_bulk(pa, gfp, nr_pages - got,
+						 page_array + got, false, true);
+		} else {
+			struct page *batch[PISA_PCP_BATCH];
+			unsigned long n, i;
+
+			n = __pisa_alloc_bulk(pa, gfp, pcp_batch, batch, false, true);
+			for (i = 0; i < n && got < nr_pages; i++)
+				page_array[got++] = batch[i];
+			if (i < n) {
+				if (pa->nid == numa_mem_id())
+					pisa_pcp_push(pa, n - i, batch + i);
+				else
+					pisa_free_bulk(pa, n - i, batch + i);
+			}
+		}
+	}
+
+	for (unsigned long i = 0; i < got; i++) {
+		struct page *block = page_array[i];
+
+		page_array[i] = NULL;
+		/* Poisoned while cached: leak it, as pisa_scan_bitmap() does. */
+		if (is_pisa_block_poisoned(pa, block))
+			continue;
+		pisa_block_prep(block);
+		if (want_init_on_alloc(gfp)) {
+			memset(page_address(block), 0, PAGE_SIZE << pa->order);
+			if (frozen) /* Order zeroing before caller publishes the page. */
+				smp_wmb();
+		}
+		if (!frozen)
+			page_ref_unfreeze(block, 1);
+		page_array[j++] = block;
+	}
+	/* Replace blocks dropped as poisoned, so that callers do not see a short allocation. */
+	if (unlikely(j < got))
+		j += __pisa_alloc_bulk(pa, gfp, nr_pages - j, page_array + j,
+				       want_init_on_alloc(gfp), frozen);
+	return j;
+}
+
 /**
  * pisa_alloc_bulk - Allocate up to @nr_pages blocks from @pa
  * @pa: Allocator to allocate from
@@ -665,11 +878,16 @@ unsigned long pisa_alloc_bulk(struct pisa_alloc *pa, gfp_t gfp,
 			i++;
 			continue;
 		}
+
 		/* Fill the run of @n NULL entries at @i. */
 		for (n = 1; i + n < nr_pages && !page_array[i + n]; n++)
 			;
-		got = __pisa_alloc_bulk(pa, gfp, n, page_array + i,
-					want_init_on_alloc(gfp), frozen);
+		/* Pairs with smp_store_release() in pisa_enable_pcp(). */
+		if (smp_load_acquire(&pa->pcp) && pa->nid == numa_mem_id())
+			got = pisa_pcp_alloc(pa, gfp, n, page_array + i, frozen);
+		else
+			got = __pisa_alloc_bulk(pa, gfp, n, page_array + i,
+						want_init_on_alloc(gfp), frozen);
 		i += got;
 		if (got < n)
 			break;
@@ -812,6 +1030,7 @@ __pisa_alloc_map_coherent(struct device *dev, struct iommu_domain *domain,
 	pa = pisa_node_pa(dev_to_node(dev), 0, false);
 	if (!pa)
 		return NULL;
+	pisa_pcp_drain(pa);
 
 	nblocks = size >> PAGE_SHIFT;
 	align_mask = (1UL << get_order(size)) - 1;
@@ -911,6 +1130,16 @@ bool __pisa_free_page(struct page *page, unsigned int order)
 	if (want_init_on_free())
 		memset(page_address(page), 0, PAGE_SIZE << pa->order);
 
+	/* Pairs with cmpxchg_release() in pisa_enable_pcp(). */
+	if (smp_load_acquire(&pa->pcp) && pa->nid == numa_mem_id() &&
+	    page_to_nid(page) == numa_mem_id()) {
+		if (pisa_page_can_recycle(page)) {
+			pisa_pcp_push(pa, 1, &page);
+			return true;
+		}
+		pisa_pcp_drain_cpu(pa, raw_smp_processor_id());
+	}
+
 	spin_lock_irqsave(&pa->lock, flags);
 	should_release = pisa_return_block_locked(pa, page);
 	spin_unlock_irqrestore(&pa->lock, flags);
@@ -924,14 +1153,16 @@ bool __pisa_free_page(struct page *page, unsigned int order)
 /* Shrinker: releases reservoir pages first, then idle allocator pages. */
 static unsigned long pisa_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
 {
-	unsigned long nr = pisa_reservoir_count();
+	unsigned long nr = pisa_reservoir_count() << PISA_ORDER;
 	struct pisa_alloc *pa;
 
 	guard(read_lock)(&pisa_allocs_lock);
-	list_for_each_entry(pa, &pisa_allocs, node)
-		nr += READ_ONCE(pa->num_idle_pages);
+	list_for_each_entry(pa, &pisa_allocs, node) {
+		nr += (unsigned long)READ_ONCE(pa->num_idle_pages) << PISA_ORDER;
+		nr += pisa_pcp_count(pa) << pa->order;
+	}
 
-	return nr << PISA_ORDER;
+	return nr;
 }
 
 /* Detach PISA pages from @list onto @release_list up to @nr_to_scan base pages. */
@@ -967,6 +1198,8 @@ VISIBLE_IF_KUNIT unsigned long pisa_shrink_scan(struct shrinker *shrink, struct
 	if (freed < sc->nr_to_scan) {
 		read_lock(&pisa_allocs_lock);
 		list_for_each_entry(pa, &pisa_allocs, node) {
+			/* Cached blocks keep PISA pages from going idle. */
+			pisa_pcp_drain(pa);
 			freed += pisa_shrink_list(&pa->lock, &pa->idle,
 						  &pa->num_idle_pages, &release_list,
 						  sc->nr_to_scan - freed);
@@ -989,6 +1222,19 @@ VISIBLE_IF_KUNIT unsigned long pisa_shrink_scan(struct shrinker *shrink, struct
 	return freed ?: SHRINK_STOP;
 }
 
+/* Return the blocks a dead CPU cached, which nothing else would. */
+static int pisa_cpu_dead(unsigned int cpu)
+{
+	struct pisa_alloc *pa;
+
+	guard(read_lock)(&pisa_allocs_lock);
+	list_for_each_entry(pa, &pisa_allocs, node)
+		/* Pairs with smp_store_release() in pisa_enable_pcp(). */
+		if (smp_load_acquire(&pa->pcp))
+			pisa_pcp_drain_cpu(pa, cpu);
+	return 0;
+}
+
 static int __init pisa_init(void)
 {
 	struct shrinker *shrink;
@@ -1001,9 +1247,9 @@ static int __init pisa_init(void)
 	/* Preallocate the supported per-node allocators. */
 	for_each_node_state(nid, N_MEMORY) {
 		pisa_alloc_ensure(&pisa_nodes[nid].pa[0][0], nid, 0,
-				  DMA_BIDIRECTIONAL, "pisa_o0_n%d", nid);
+				  DMA_BIDIRECTIONAL, true, "pisa_o0_n%d", nid);
 		pisa_alloc_ensure(&pisa_nodes[nid].pa[1][SKB_FRAG_PAGE_ORDER],
-				  nid, SKB_FRAG_PAGE_ORDER, DMA_TO_DEVICE,
+				  nid, SKB_FRAG_PAGE_ORDER, DMA_TO_DEVICE, true,
 				  "pisa_ro_o%u_n%d", SKB_FRAG_PAGE_ORDER, nid);
 	}
 
@@ -1012,6 +1258,10 @@ static int __init pisa_init(void)
 	if (!pisa_wq)
 		pr_warn("pisa: no reclaim workqueue, falling back to system_wq\n");
 
+	if (cpuhp_setup_state_nocalls(CPUHP_BP_PREPARE_DYN, "iommu/pisa:dead", NULL,
+				      pisa_cpu_dead) < 0)
+		pr_warn("pisa: no CPU hotplug callback, offline CPUs keep cached blocks\n");
+
 	shrink = shrinker_alloc(0, "pisa");
 	if (!shrink) {
 		pr_warn("pisa: shrinker registration failed\n");
mm/pisa-kunit.c +79 -0

91 lines not on this page · raw message

mm/pisa-priv.h +8 -3
index fb26eb3aa9b37..60120a05082a9 100644
@@ -15,6 +15,7 @@
 #include <linux/topology.h>
 #include <linux/workqueue.h>
 
+struct pisa_pcp;
 
 #ifdef CONFIG_IOMMU_DMA
 int iommu_get_dma_cookie(struct iommu_domain *domain);
@@ -30,7 +31,7 @@ void iommu_put_dma_cookie(struct iommu_domain *domain);
  * Locking (disjoint groups; locks in different groups do not nest):
  *
  * 1. Allocators (mm/pisa-alloc.c, mm/pisa-node.c):
- *    pisa_allocs_lock (rwlock) -> pa->lock (spinlock)
+ *    pisa_allocs_lock (rwlock) -> pcp->lock (spinlock) -> pa->lock (spinlock)
  *    pisa_nodes[].lock (spinlock): leaf lock over a node's reservoir.
  *
  * 2. Metadata tables (mm/pisa-meta.c):
@@ -100,6 +101,7 @@ struct pisa_alloc {
 	spinlock_t		lock;
 	u8			order;		/* block order (<= PISA_ORDER) */
 	u8			prot;		/* IOMMU_READ and/or IOMMU_WRITE */
+	struct pisa_pcp __percpu *pcp;
 	struct list_head	partial;	/* partial pages with nr_clean > 0 */
 	struct list_head	partial_dirty;	/* partial pages with nr_clean == 0 */
 	struct list_head	idle;		/* completely free PISA pages */
@@ -200,10 +202,13 @@ static inline void pisa_alloc_backoff(struct pisa_node *node, bool can_block)
 struct pisa_alloc *pisa_alloc_create(int nid, unsigned int order, enum dma_data_direction dir);
 __printf(2, 3)
 void pisa_alloc_set_name(struct pisa_alloc *pa, const char *fmt, ...);
-__printf(5, 6)
+__printf(6, 7)
 struct pisa_alloc *pisa_alloc_ensure(struct pisa_alloc **pap, int nid,
 				     unsigned int order, enum dma_data_direction dir,
-				     const char *fmt, ...);
+				     bool pcp, const char *fmt, ...);
+#define PISA_PCP_HIGH		64U	/* blocks cached per CPU at most */
+int pisa_enable_pcp(struct pisa_alloc *pa);
+void pisa_pcp_drain(struct pisa_alloc *pa);
 bool pisa_place_meta(struct pisa_meta *meta);
 extern struct llist_head pisa_free_list;
 extern unsigned int pisa_idle_ms;
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#75 lore raw

Re: [RFC PATCH v3 09/25] mm: Add per-CPU block caches to PISA allocators

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] mm: quarantined PISA blocks cached and reused via per-CPU cache - [Low] mm: migration race in…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] mm: quarantined PISA blocks cached and reused via per-CPU cache
- [Low] mm: migration race in pisa_pcp_push() strands blocks on remote or dead CPUs
--

commit 9051b3f49c794994e5d00217ac93ea632ab60aeb
Author: Luigi Rizzo <[email protected]>

mm: Add per-CPU block caches to PISA allocators

This commit adds an opt-in per-CPU block cache to PISA allocators, integrated with the shrinker and CPU hotplug teardown, and enables it for per-node order-0 RW and SKB_FRAG_PAGE_ORDER RO allocators.

Quoted 4 lines
mm/pisa-alloc.c +0 -0
index eda12d475c9a7..896709303f258 100644

[ ... ]

Quoted 3 lines
mm/pisa-alloc.c +0 -0
@@ -324,13 +326,168 @@ static bool pisa_return_block_locked(struct pisa_alloc *pa, struct page *block)
 	return pisa_place_meta(meta);
 }

[ ... ]

Quoted 13 lines
mm/pisa-alloc.c +13 -0
+/* Cache @n blocks at refcount 0 on this CPU, @n <= PISA_PCP_BATCH. */
+static void pisa_pcp_push(struct pisa_alloc *pa, unsigned int n, struct page **blocks)
+{
+	unsigned int batch = pisa_pcp_batch_order(pa);
+	unsigned int high = max(2U, PISA_PCP_HIGH >> pa->order);
+	struct pisa_pcp *pcp;
+	unsigned long flags;
+
+	/* @pcp->lock protects the cache: migrating to another CPU here is harmless. */
+	pcp = raw_cpu_ptr(pa->pcp);
+	spin_lock_irqsave(&pcp->lock, flags);
+	for (unsigned int i = 0; i < n; i++) {
+		if (pcp->count >= high) {

mm/pisa-alloc.c static bool pisa_return_block_locked(struct pisa_alloc *pa, struct page *block) · line 400

Quoted 10 lines
mm/pisa-alloc.c +10 -0
+			/* Keep the most recently freed, likely still in cache. */
+			pisa_free_bulk(pa, batch, pcp->blocks);
+			pcp->count -= batch;
+			memmove(pcp->blocks, pcp->blocks + batch,
+				pcp->count * sizeof(*pcp->blocks));
+		}
+		pcp->blocks[pcp->count++] = blocks[i];
+	}
+	spin_unlock_irqrestore(&pcp->lock, flags);
+}

[Severity: Low]
Can preemption before spin_lock_irqsave() in pisa_pcp_push() strand freed blocks on a remote-node or offlined CPU's cache?

Both pisa_pcp_alloc() and __pisa_free_page() check pa->nid == numa_mem_id() with preemption enabled before calling pisa_pcp_push(), and raw_cpu_ptr() is evaluated before spin_lock_irqsave() disables preemption:

CPU0 (node 0) CPU1 (node 1)
__pisa_free_page()
pa->nid == numa_mem_id()
<migrated to CPU1>

                                  pisa_pcp_push()
                                    pcp = raw_cpu_ptr(pa->pcp)
                                    spin_lock_irqsave(&pcp->lock, ...)
                                    pcp->blocks[pcp->count++] = ...
                                    spin_unlock_irqrestore(&pcp->lock, ...)

Similarly, if the task is preempted between raw_cpu_ptr(pa->pcp) and spin_lock_irqsave() while CPU0 goes offline and runs pisa_cpu_dead(0), the task will repopulate CPU0's cache after it has already been drained.

Because pisa_alloc_bulk() and __pisa_free_page() only access pa->pcp on online CPUs where pa->nid == numa_mem_id(), blocks pushed onto a remote-node or dead CPU's cache will not be popped or flushed by normal allocations and frees, keeping pa->blocks_in_use elevated and preventing the containing PISA page from becoming idle until a shrinker scan or coherent DMA allocation drains all CPUs.

[ ... ]

mm/pisa-alloc.c bool __pisa_free_page(struct page *page, unsigned int order) · line 1141

Quoted 13 lines
mm/pisa-alloc.c +9 -0
@@ -911,6 +1130,16 @@ bool __pisa_free_page(struct page *page, unsigned int order)
 	if (want_init_on_free())
 		memset(page_address(page), 0, PAGE_SIZE << pa->order);
 
+	/* Pairs with cmpxchg_release() in pisa_enable_pcp(). */
+	if (smp_load_acquire(&pa->pcp) && pa->nid == numa_mem_id() &&
+	    page_to_nid(page) == numa_mem_id()) {
+		if (pisa_page_can_recycle(page)) {
+			pisa_pcp_push(pa, 1, &page);
+			return true;
+		}
+		pisa_pcp_drain_cpu(pa, raw_smp_processor_id());
+	}

[Severity: Medium]
Can blocks belonging to a quarantined PISA page be cached in pa->pcp and reallocated instead of draining to retirement?

When an IOMMU unmap fails, pisa_quarantine_page() sets _PISA_QUARANTINED in meta->flags so that no further blocks are handed out from that PISA page and the page is retired once all in-use blocks return. Here __pisa_free_page() relies on pisa_page_can_recycle(page) to avoid pushing quarantined blocks into pa->pcp:

include/linux/pisa.h:pisa_page_can_recycle() {
	return !static_branch_unlikely(&pisa_recycle_check_key) ||
	       __pisa_page_can_recycle(page);
}

pisa_recycle_check_key is only enabled when pisa.compact or pisa.target_usage_percent is non-zero, and pisa_quarantine_page() does not enable it. Under default settings, pisa_page_can_recycle() returns true without calling __pisa_page_can_recycle() -> pisa_meta_can_recycle() where PISA_QUARANTINED is checked, so freed blocks of a quarantined page are pushed into pa->pcp and reallocated to new callers.

Even when pisa_recycle_check_key is enabled, pisa_quarantine_page() does not drain per-CPU caches across CPUs, __pisa_free_page() only drains the current CPU, and pisa_pcp_alloc() only checks popped blocks for PageHWPoison() without checking whether their PISA page was quarantined while cached.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
#76 lore raw

RFC PATCH v3 10/25 mm: Add background page scrubber for PISA allocators

In reply to Luigi Rizzo

Blocks returned to a pisa_alloc are marked dirty and need to be zeroed before they can serve __GFP_ZERO requests. Zeroing blocks inline at allocation time adds CPU cost and latency.

Add an optional background scrubber (enabled via pisa.scrub_max) that runs on the allocator's home NUMA node work item, zeroes dirty blocks outside pa->lock in batches, and moves them to meta->clean_bitmap[]. Scrubbing is demand-driven by the number of dirty blocks that __GFP_ZERO allocations had to zero inline.

---
 include/linux/pisa-iommu.h |   1 +
 mm/pisa-alloc.c            | 187 ++++++++++++++++++++++++++++++++++++-
 mm/pisa-kunit.c            |  51 +++++++++-
 mm/pisa-meta.c             |   7 +-
 mm/pisa-node.c             |  33 +++++++
 mm/pisa-priv.h             |  10 +-
 6 files changed, 281 insertions(+), 8 deletions(-)
include/linux/pisa-iommu.h +1 -0
index 568108747f575..7dd91ff47288a 100644
@@ -55,6 +55,7 @@ struct pisa_meta {
 	u8 on_list;		/* current placement in @pa (PISA_LIST_*) */
 	bool drain;		/* sparse old page draining back to @idle */
 	u32 slot;		/* dense index in @pisa_meta_array and IOVA windows */
+	u16 nr_scrub;		/* blocks being zeroed by the scrubber, in neither bitmap */
 
 	DECLARE_BITMAP(domains_mapped, PISA_MAX_DOMAINS);
 
mm/pisa-alloc.c +183 -4

278 lines not on this page · raw message

mm/pisa-kunit.c +50 -1

58 lines not on this page · raw message

mm/pisa-meta.c +5 -2
index 30f0f2f6ef628..49fa5271a392f 100644
@@ -213,10 +213,13 @@ bool pisa_place_meta(struct pisa_meta *meta)
 		 * (head of partial list, preferred for allocation). In between,
 		 * keep the current dense/sparse state.
 		 */
+		/* Blocks that the scrubber is zeroing are free: count them here. */
+		unsigned int nfree = avail + meta->nr_scrub;
+
 		to_list = meta->nr_clean ? PISA_LIST_CLEAN : PISA_LIST_DIRTY;
-		if (avail >= bpp - (bpp >> 2))
+		if (nfree >= bpp - (bpp >> 2))
 			to_list |= PISA_LIST_SPARSE;
-		else if (avail > (bpp >> 1))
+		else if (nfree > (bpp >> 1))
 			to_list |= meta->on_list & PISA_LIST_SPARSE;
 	}
 
mm/pisa-node.c +33 -0
index a39251b952263..c013e384b1c7e 100644
@@ -5,6 +5,9 @@
  */
 
 #include <linux/atomic.h>
+#include <linux/bitops.h>
+#include <linux/device.h>
+#include <linux/export.h>
 #include <linux/pisa.h>
 #include <linux/err.h>
 #include <linux/gfp.h>
@@ -37,6 +40,9 @@ struct pisa_node pisa_nodes[MAX_NUMNODES] = {
 	},
 };
 
+/* Bit number in pisa_node.flags: background scrub requested on this node. */
+#define PISA_NODE_SCRUB	0
+
 static int pisa_reservoir_max_set(const char *val, const struct kernel_param *kp)
 {
 	int ret = param_set_uint(val, kp);
@@ -237,6 +243,30 @@ static void pisa_reservoir_trim_node(struct pisa_node *node, unsigned int max)
 	}
 }
 
+/* Schedule node @nid's work item to scrub allocators homed on @nid. */
+void pisa_schedule_scrub(int nid)
+{
+	struct pisa_node *node;
+
+	if (!READ_ONCE(pisa_scrub_max))
+		return;
+
+	node = &pisa_nodes[nid];
+	set_bit(PISA_NODE_SCRUB, &node->flags);
+	/* Pairs with the clearing of PENDING before the work runs. */
+	smp_mb__after_atomic();
+	if (!work_pending(&node->work))
+		queue_work_node(nid, system_dfl_wq, &node->work);
+}
+
+void pisa_schedule_scrub_all(void)
+{
+	int nid;
+
+	for_each_node_state(nid, N_MEMORY)
+		pisa_schedule_scrub(nid);
+}
+
 /* Per-node worker: trim/refill the reservoir, then scrub allocators homed on @nid. */
 static void pisa_node_work_fn(struct work_struct *work)
 {
@@ -246,6 +276,9 @@ static void pisa_node_work_fn(struct work_struct *work)
 	pisa_reservoir_trim_node(node, READ_ONCE(pisa_reservoir_max));
 	if (pisa_enabled() && READ_ONCE(pisa_reservoir_max))
 		pisa_reservoir_refill_node(node, nid);
+
+	if (test_and_clear_bit(PISA_NODE_SCRUB, &node->flags) && pisa_scrub_node(nid))
+		pisa_schedule_scrub(nid);
 }
 
 /* Queue node @nid's work if its reservoir is below or above the target. */
mm/pisa-priv.h +9 -1
index 60120a05082a9..9f01173d30f5f 100644
@@ -108,6 +108,7 @@ struct pisa_alloc {
 	struct list_head	full;		/* PISA pages with 0 free blocks */
 	unsigned int		num_idle_pages;
 	unsigned int		max_idle_pages;
+	unsigned int		scrub_demand;	/* dirty blocks zeroed inline */
 	unsigned long		idle_jiffies;	/* last change of @idle at/above @max_idle_pages */
 	unsigned long		blocks_in_use;	/* blocks handed out and not yet freed */
 	/* Cold. */
@@ -136,7 +137,8 @@ struct pisa_node {
 	spinlock_t		lock;		/* protects @pages and @nr_pages */
 	unsigned int		nr_pages;	/* entries in @pages */
 	struct list_head	pages;		/* reservoir */
-	struct work_struct	work;		/* refill/trim, on this node */
+	unsigned long		flags;		/* PISA_NODE_* requests */
+	struct work_struct	work;		/* refill/trim/scrub, on this node */
 } ____cacheline_aligned_in_smp;
 
 /* Per-NUMA-node PISA state (ring/TX/user allocators, reservoir). */
@@ -229,11 +231,17 @@ static inline struct page *pisa_alloc(struct pisa_alloc *pa, gfp_t gfp)
 unsigned long pisa_shrink_list(spinlock_t *lock, struct list_head *list,
 			       unsigned int *nr, struct list_head *release_list,
 			       unsigned long nr_to_scan);
+/* Time after which a scrubber run stops and requeues. */
+#define PISA_SCRUB_RUN_NS	(50 * NSEC_PER_USEC)
+extern unsigned int pisa_scrub_max;
+bool pisa_scrub_node(int nid);
 
 /* pisa-node.c: per-NUMA-node PISA page reservoir and work item */
 extern unsigned int pisa_reservoir_max;
 void pisa_node_init(void);
 void pisa_schedule_reservoir(void);
+void pisa_schedule_scrub(int nid);
+void pisa_schedule_scrub_all(void);
 struct pisa_meta *pisa_reservoir_pop(int nid, gfp_t gfp, bool *clean);
 unsigned long pisa_reservoir_count(void);
 unsigned long pisa_reservoir_shrink(struct list_head *release_list, unsigned long nr_to_scan);
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#77 lore raw

Re: [RFC PATCH v3 10/25] mm: Add background page scrubber for PISA allocators

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] mm: test_reservoir_and_scrubber() moves dirty page to idle before scrub --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] mm: test_reservoir_and_scrubber() moves dirty page to idle before scrub
--

commit 70c7c1222c1db62795294daab0b4e4be086b26aa
Author: Luigi Rizzo <[email protected]>

mm: Add background page scrubber for PISA allocators

This commit adds an optional demand-driven background page scrubber for PISA allocators that zeroes dirty blocks on the home NUMA node's work item outside pa->lock and moves them to meta->clean_bitmap.

Quoted 36 lines
mm/pisa-kunit.c +26 -1
index 0f8cc9baf5d28..4effbc8610079 100644
@@ -662,8 +662,57 @@ static void test_gfp_pisa(struct kunit *test)
 
 static void test_reservoir_and_scrubber(struct kunit *test)
 {
+	unsigned int old_res = READ_ONCE(pisa_reservoir_max);
+	unsigned int old_scrub = READ_ONCE(pisa_scrub_max);
+	struct shrink_control sc = { .nr_to_scan = ULONG_MAX };
+	struct pisa_meta *meta;
+	struct pisa_alloc *pa;
+	struct page *p;
+	int nid;
+
 	KUNIT_ASSERT_EQ(test, pisa_meta_init(), 0);
-	KUNIT_EXPECT_EQ(test, READ_ONCE(pisa_reservoir_max), 16U);
+	pisa_shrink_scan(NULL, &sc);
+
+	/* Refill reservoir to 1 PISA page per memory node, then consume one. */
+	WRITE_ONCE(pisa_reservoir_max, 1);
+	pisa_schedule_reservoir();
+	for_each_node_state(nid, N_MEMORY)
+		flush_work(&pisa_nodes[nid].work);
+	KUNIT_EXPECT_GE(test, pisa_reservoir_count(), 1UL);
+
+	pa = pisa_node_pa(first_memory_node, SKB_FRAG_PAGE_ORDER, true);
+	KUNIT_ASSERT_NOT_NULL(test, pa);
+	p = pisa_alloc(pa, GFP_KERNEL);
+	if (p) {
+		meta = pisa_meta_of_pfn(page_to_pfn(p));
+		/* Reservoir pages come pre-zeroed (all remaining blocks clean). */
+		KUNIT_EXPECT_EQ(test, meta->nr_dirty, 0U);
+		__free_pages(p, SKB_FRAG_PAGE_ORDER);
+		pisa_pcp_drain(pa);

mm/pisa-kunit.c static void test_gfp_pisa(struct kunit *test) · line 701

Quoted 10 lines
mm/pisa-kunit.c +10 -0
+		if (!want_init_on_free()) {
+			KUNIT_EXPECT_GE(test, meta->nr_dirty, 1U);
+
+			/* Scrub the freed block and its PCP batch back into clean_bitmap. */
+			pa->scrub_demand = meta->nr_dirty;
+			WRITE_ONCE(pisa_scrub_max, 512);
+			pisa_scrub_node(pa->nid);
+			KUNIT_EXPECT_EQ(test, meta->nr_dirty, 0U);
+		}
+	}

[Severity: Medium]
Does freeing p and calling pisa_pcp_drain(pa) move meta onto pa->idle before pisa_scrub_node() runs?

Because p was the only allocated block from meta, returning p and draining the remaining PCP refill batch brings pisa_meta_avail(meta) back to PISA_BLOCKS(pa->order), so pisa_place_meta() moves meta to pa->idle (or pisa_free_list if pisa_idle_ms == 0). pisa_pick_dirty_meta() only scans pa->partial_dirty and pa->partial and skips pa->idle, so pisa_alloc_scrub_blocks() resets pa->scrub_demand to 0 without scrubbing meta, and KUNIT_EXPECT_EQ(test, meta->nr_dirty, 0U) fails whenever init_on_free is disabled. Holding a second block from meta across pisa_pcp_drain() and pisa_scrub_node() would keep meta on pa->partial so the scrubber can pick it up.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=10
#78 lore raw

RFC PATCH v3 11/25 mm: Migrate user pages into PISA

In reply to Luigi Rizzo

Zero-copy DMA paths (such as O_DIRECT disk I/O and MSG_ZEROCOPY sockets) map each user page with a per-buffer IOMMU mapping and IOTLB flush. Moving user buffers into PISA blocks once allows subsequent DMA operations to reuse pre-mapped 2MB IOMMU entries.

Add mm/pisa-user.c to migrate private anonymous order-0 user pages into per-node DMA_TO_DEVICE PISA allocators, controlled by pisa.user_max_pages (0 = disabled), via madvise(MADV_PISA) / MADV_NOPISA (also supported via process_madvise()) and pisa_upgrade_user_pages().

Large anonymous folios are split to order 0 first, while budget remains, with split_folio_to_list_keep_zero(): a variant of split_folio_to_list() that leaves zero-filled subpages mapped instead of remapping them to the shared zeropage, so that pages the caller is about to write to (e.g. the target of an O_DIRECT read) are still there to migrate.

---
 include/linux/huge_mm.h                |   7 +
 include/linux/pisa-mm.h                |   8 +
 include/linux/pisa.h                   |  18 ++
 include/linux/swap.h                   |   1 +
 include/uapi/asm-generic/mman-common.h |   2 +
 mm/Makefile                            |   2 +-
 mm/huge_memory.c                       |  36 ++-
 mm/madvise.c                           |  19 ++
 mm/pisa-alloc.c                        |   2 +
 mm/pisa-priv.h                         |   2 +
 mm/pisa-user.c                         | 394 +++++++++++++++++++++++++
 11 files changed, 483 insertions(+), 8 deletions(-)
 create mode 100644 mm/pisa-user.c
include/linux/huge_mm.h +7 -0
index fac05120ab774..d679de8cf261d 100644
@@ -404,6 +404,7 @@ int __split_huge_page_to_list_to_order(struct page *page, struct list_head *list
 int folio_split_unmapped(struct folio *folio, unsigned int new_order);
 unsigned int min_order_for_split(struct folio *folio);
 int split_folio_to_list(struct folio *folio, struct list_head *list);
+int split_folio_to_list_keep_zero(struct folio *folio, struct list_head *list);
 int folio_check_splittable(struct folio *folio, unsigned int new_order,
 			   enum split_type split_type);
 int folio_split(struct folio *folio, unsigned int new_order, struct page *page,
@@ -671,6 +672,12 @@ static inline int split_folio_to_list(struct folio *folio, struct list_head *lis
 	return -EINVAL;
 }
 
+static inline int split_folio_to_list_keep_zero(struct folio *folio, struct list_head *list)
+{
+	VM_WARN_ON_ONCE_FOLIO(1, folio);
+	return -EINVAL;
+}
+
 static inline int folio_split(struct folio *folio, unsigned int new_order,
 		struct page *page, struct list_head *list)
 {
include/linux/pisa-mm.h +8 -0
index d55a42397c4b3..1e82e081b4004 100644
@@ -11,6 +11,8 @@ unsigned long __pisa_alloc_pages_bulk(gfp_t gfp, unsigned int order,
 				      int preferred_nid, int nr_pages,
 				      struct page **page_array, bool frozen);
 bool __pisa_free_page(struct page *page, unsigned int order);
+int pisa_madvise(struct vm_area_struct *vma, unsigned long start,
+		 unsigned long end, bool to_pisa);
 
 /*
  * ============================================================================
@@ -77,5 +79,11 @@ static inline bool pisa_free_page(struct page *page, unsigned int order)
 	return false;
 }
 
+static inline int pisa_madvise(struct vm_area_struct *vma, unsigned long start,
+			       unsigned long end, bool to_pisa)
+{
+	return -EINVAL;
+}
+
 #endif /* CONFIG_PISA */
 #endif /* _LINUX_PISA_MM_H */
include/linux/pisa.h +18 -0
index edd34771ad1c4..9321e7ff00042 100644
@@ -14,6 +14,7 @@
 
 struct iommu_domain;
 struct iova_domain;
+struct iov_iter;
 
 /**
  * struct pisa_iova - A domain's IOVA window reserved for PISA pages
@@ -70,9 +71,11 @@ enum {
  * Static keys guarding all kernel hooks:
  * - @pisa_key: enabled on first device opt-in (pisa_meta_init()).
  * - @pisa_recycle_check_key: enabled when pisa.compact or pisa.target_usage_percent > 0.
+ * - @pisa_user_key: enabled when pisa.user_max_pages > 0.
  */
 DECLARE_STATIC_KEY_FALSE(pisa_key);
 DECLARE_STATIC_KEY_FALSE(pisa_recycle_check_key);
+DECLARE_STATIC_KEY_FALSE(pisa_user_key);
 
 extern u32 *pisa_pfn2slot;
 extern unsigned int pisa_nr_slots;
@@ -89,12 +92,19 @@ void *__pisa_alloc_map_coherent_dev(struct device *dev, size_t size,
 				    unsigned long attrs);
 bool __pisa_has_free_blocks_rx(unsigned int order, int nid);
 bool __pisa_page_can_recycle(const struct page *page);
+bool pisa_upgrade_user_pages(struct iov_iter *iter, struct page **pages,
+			     size_t size, size_t offset);
 
 static inline bool pisa_enabled(void)
 {
 	return static_branch_unlikely(&pisa_key);
 }
 
+static inline bool pisa_user_enabled(void)
+{
+	return static_branch_unlikely(&pisa_user_key);
+}
+
 static inline u32 pisa_pfn_flags(unsigned long pfn)
 {
 	unsigned long frame = pfn >> PISA_ORDER;
@@ -195,6 +205,7 @@ static inline bool pisa_page_can_recycle(const struct page *page)
 
 static inline int pisa_meta_init(void) { return -EOPNOTSUPP; }
 static inline bool pisa_enabled(void) { return false; }
+static inline bool pisa_user_enabled(void) { return false; }
 static inline bool is_pisa_pfn(unsigned long pfn) { return false; }
 static inline bool is_pisa_page(const struct page *page) { return false; }
 static inline bool is_pisa_phys(phys_addr_t phys) { return false; }
@@ -228,6 +239,13 @@ static inline bool pisa_page_can_recycle(const struct page *page)
 	return true;
 }
 
+static inline bool pisa_upgrade_user_pages(struct iov_iter *iter,
+					   struct page **pages, size_t size,
+					   size_t offset)
+{
+	return false;
+}
+
 #endif /* CONFIG_PISA */
 
 #if defined(CONFIG_PISA) && defined(CONFIG_IOMMU_DMA)
include/linux/swap.h +1 -0
index 4f686709d71f0..3736786ccc5a3 100644
@@ -314,6 +314,7 @@ extern unsigned long totalreserve_pages;
 /* linux/mm/folio.c */
 void folio_add_lru(struct folio *folio);
 void folio_mark_accessed(struct folio *folio);
+void lru_add_drain(void);
 void lru_add_drain_all(void);
 
 enum lru_cache_drained {
include/uapi/asm-generic/mman-common.h +2 -0
index ef1c27fa3c570..c4332db8e56ff 100644
@@ -81,6 +81,8 @@
 
 #define MADV_GUARD_INSTALL 102		/* fatal signal on access to range */
 #define MADV_GUARD_REMOVE 103		/* unguard range */
+#define MADV_PISA		210	/* move pages into PISA memory */
+#define MADV_NOPISA		211	/* move pages out of PISA memory */
 
 /* compatibility flags */
 #define MAP_FILE	0
mm/Makefile +1 -1
index 7d624e4bad456..d6b54a6eb3dc0 100644
@@ -147,7 +147,7 @@ obj-$(CONFIG_GENERIC_IOREMAP) += ioremap.o
 obj-$(CONFIG_SHRINKER_DEBUG) += shrinker_debug.o
 obj-$(CONFIG_EXECMEM) += execmem.o
 obj-$(CONFIG_PISA) += pisa.o
-pisa-y := pisa-meta.o pisa-alloc.o pisa-node.o
+pisa-y := pisa-meta.o pisa-alloc.o pisa-node.o pisa-user.o
 obj-$(CONFIG_PISA_META_KUNIT_TEST) += pisa-kunit.o
 obj-$(CONFIG_TMPFS_QUOTA) += shmem_quota.o
 obj-$(CONFIG_LAZY_MMU_MODE_KUNIT_TEST) += tests/lazy_mmu_mode_kunit.o
mm/huge_memory.c +29 -7
index 7791872f14af7..ffa3912f2418b 100644
@@ -4113,7 +4113,8 @@ static void folio_reset_partially_mapped(struct folio *folio)
 
 static int __folio_freeze_split_anon(struct folio *folio,
 		unsigned int new_order, struct page *split_at, bool do_lru,
-		struct list_head *list, enum split_type split_type)
+		struct list_head *list, enum split_type split_type,
+		bool keep_zero)
 {
 	struct folio *end_folio = folio_next(folio);
 	struct swap_cluster_info *ci = NULL;
@@ -4207,7 +4208,13 @@ static int __folio_freeze_split_anon(struct folio *folio,
 out_no_split:
 	local_irq_enable();
 	if (anon_vma) {
-		if (!ret && !folio_is_device_private(folio))
+		/*
+		 * Zero-filled anon subpages are normally unmapped, freed and
+		 * replaced by the shared zeropage. A @keep_zero caller needs
+		 * the subpages themselves, e.g. to migrate them before a
+		 * device writes to them.
+		 */
+		if (!ret && !folio_is_device_private(folio) && !keep_zero)
 			ttu_flags = TTU_USE_SHARED_ZEROPAGE;
 		remap_anon_folio(folio, 1 << old_order, ttu_flags);
 	}
@@ -4387,6 +4394,7 @@ static int __folio_freeze_split_file(struct folio *folio,
  * @lock_at: a page within @folio to be left locked to caller
  * @list: after-split folios will be put on it if non NULL
  * @split_type: perform uniform split or not (non-uniform split)
+ * @keep_zero: do not remap zero-filled anon subpages to the shared zeropage
  *
  * It calls __split_frozen_folio() to perform uniform and non-uniform split.
  * It is in charge of checking whether the split is supported or not and
@@ -4402,7 +4410,8 @@ static int __folio_freeze_split_file(struct folio *folio,
  */
 static int __folio_split(struct folio *folio, unsigned int new_order,
 		struct page *split_at, struct page *lock_at,
-		struct list_head *list, enum split_type split_type)
+		struct list_head *list, enum split_type split_type,
+		bool keep_zero)
 {
 	struct folio *end_folio = folio_next(folio);
 	const bool is_anon = folio_test_anon(folio);
@@ -4432,7 +4441,8 @@ static int __folio_split(struct folio *folio, unsigned int new_order,
 
 	if (is_anon)
 		ret = __folio_freeze_split_anon(folio, new_order, split_at,
-						true, list, split_type);
+						true, list, split_type,
+						keep_zero);
 	else
 		ret = __folio_freeze_split_file(folio, new_order, split_at,
 						list, split_type);
@@ -4495,7 +4505,7 @@ int folio_split_unmapped(struct folio *folio, unsigned int new_order)
 	VM_WARN_ON_ONCE_FOLIO(!folio_test_anon(folio), folio);
 
 	return __folio_freeze_split_anon(folio, new_order, &folio->page,
-					 false, NULL, SPLIT_TYPE_UNIFORM);
+					 false, NULL, SPLIT_TYPE_UNIFORM, false);
 }
 
 /*
@@ -4551,7 +4561,7 @@ int __split_huge_page_to_list_to_order(struct page *page, struct list_head *list
 	struct folio *folio = page_folio(page);
 
 	return __folio_split(folio, new_order, &folio->page, page, list,
-			     SPLIT_TYPE_UNIFORM);
+			     SPLIT_TYPE_UNIFORM, false);
 }
 
 /**
@@ -4582,7 +4592,7 @@ int folio_split(struct folio *folio, unsigned int new_order,
 		struct page *split_at, struct list_head *list)
 {
 	return __folio_split(folio, new_order, split_at, &folio->page, list,
-			     SPLIT_TYPE_NON_UNIFORM);
+			     SPLIT_TYPE_NON_UNIFORM, false);
 }
 
 /**
@@ -4617,6 +4627,18 @@ int split_folio_to_list(struct folio *folio, struct list_head *list)
 	return split_huge_page_to_list_to_order(&folio->page, list, 0);
 }
 
+/*
+ * As split_folio_to_list(), but zero-filled subpages of an anon folio stay
+ * mapped instead of being remapped to the shared zeropage. For callers that
+ * are about to take write references on the subpages: PISA uses it to migrate
+ * the pages of an I/O buffer, e.g. the target of an O_DIRECT read.
+ */
+int split_folio_to_list_keep_zero(struct folio *folio, struct list_head *list)
+{
+	return __folio_split(folio, 0, &folio->page, &folio->page, list,
+			     SPLIT_TYPE_UNIFORM, true);
+}
+
 /*
  * __folio_unqueue_deferred_split() is not to be called directly:
  * the folio_unqueue_deferred_split() inline wrapper in mm/internal.h
mm/madvise.c +19 -0
index 0214efd2a014f..46981ad295aa5 100644
@@ -6,6 +6,7 @@
  * Copyright (C) 2002  Christoph Hellwig
  */
 
+#include <linux/pisa-mm.h>
 #include <linux/mman.h>
 #include <linux/pagemap.h>
 #include <linux/syscalls.h>
@@ -1393,6 +1394,11 @@ static int madvise_vma_behavior(struct madvise_behavior *madv_behavior)
 		return madvise_guard_install(madv_behavior);
 	case MADV_GUARD_REMOVE:
 		return madvise_guard_remove(madv_behavior);
+#ifdef MADV_PISA
+	case MADV_PISA:
+	case MADV_NOPISA:
+		return pisa_madvise(vma, range->start, range->end, behavior == MADV_PISA);
+#endif
 
 	/* The below behaviours update VMAs via madvise_update_vma(). */
 
@@ -1582,6 +1588,11 @@ madvise_behavior_valid(int behavior)
 	case MADV_HWPOISON:
 #endif
 		return true;
+#ifdef MADV_PISA
+	case MADV_PISA:
+	case MADV_NOPISA:
+		return IS_ENABLED(CONFIG_PISA);
+#endif
 
 	default:
 		return false;
@@ -1596,6 +1607,10 @@ static bool process_madvise_remote_valid(int behavior)
 	case MADV_PAGEOUT:
 	case MADV_WILLNEED:
 	case MADV_COLLAPSE:
+#ifdef MADV_PISA
+	case MADV_PISA:
+	case MADV_NOPISA:
+#endif
 		return true;
 	default:
 		return false;
@@ -1782,6 +1797,10 @@ static enum madvise_lock_mode get_lock_mode(struct madvise_behavior *madv_behavi
 	case MADV_POPULATE_READ:
 	case MADV_POPULATE_WRITE:
 	case MADV_COLLAPSE:
+#ifdef MADV_PISA
+	case MADV_PISA:
+	case MADV_NOPISA:
+#endif
 		return MADVISE_MMAP_READ_LOCK;
 	case MADV_GUARD_INSTALL:
 	case MADV_GUARD_REMOVE:
mm/pisa-alloc.c +2 -0
index ccba2bf01bd59..2213a56de1242 100644
@@ -1432,6 +1432,8 @@ static int __init pisa_init(void)
 				  "pisa_ro_o%u_n%d", SKB_FRAG_PAGE_ORDER, nid);
 	}
 
+	pisa_user_boot_enable();
+
 	/* Dedicated WQ_MEM_RECLAIM workqueue so reclaim never blocks behind system_wq. */
 	pisa_wq = alloc_workqueue("pisa", WQ_MEM_RECLAIM, 0);
 	if (!pisa_wq)
mm/pisa-priv.h +2 -0
index 9f01173d30f5f..b18d461198ac5 100644
@@ -133,6 +133,7 @@ static inline long pisa_alloc_held_pages(const struct pisa_alloc *pa)
 struct pisa_node {
 	unsigned long		next_alloc;	/* atomic alloc backoff jiffies */
 	struct pisa_alloc	*pa[2][PISA_MAX_ALLOC_ORDER + 1]; /* [0]=RW, [1]=RO */
+	struct pisa_alloc	*user_pa;	/* user page migration pa */
 
 	spinlock_t		lock;		/* protects @pages and @nr_pages */
 	unsigned int		nr_pages;	/* entries in @pages */
@@ -245,6 +246,7 @@ void pisa_schedule_scrub_all(void);
 struct pisa_meta *pisa_reservoir_pop(int nid, gfp_t gfp, bool *clean);
 unsigned long pisa_reservoir_count(void);
 unsigned long pisa_reservoir_shrink(struct list_head *release_list, unsigned long nr_to_scan);
+void pisa_user_boot_enable(void);
 
 #endif /* CONFIG_PISA */
 #endif /* _MM_PISA_PRIV_H */
mm/pisa-user.c new file +394 -0

394 lines not on this page · raw message

Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#79 lore raw

Re: [RFC PATCH v3 11/25] mm: Migrate user pages into PISA

Quoted 10 lines · Luigi Rizzo

Zero-copy DMA paths (such as O_DIRECT disk I/O and MSG_ZEROCOPY sockets) map each user page with a per-buffer IOMMU mapping and IOTLB flush. Moving user buffers into PISA blocks once allows subsequent DMA operations to reuse pre-mapped 2MB IOMMU entries.

Add mm/pisa-user.c to migrate private anonymous order-0 user pages into per-node DMA_TO_DEVICE PISA allocators, controlled by pisa.user_max_pages (0 = disabled), via madvise(MADV_PISA) / MADV_NOPISA (also supported via process_madvise()) and pisa_upgrade_user_pages().

No, this isn't how madvise works. It's not a place to stuff custom hooks for a feature you want.

Quoted 8 lines

Large anonymous folios are split to order 0 first, while budget remains, with split_folio_to_list_keep_zero(): a variant of split_folio_to_list() that leaves zero-filled subpages mapped instead of remapping them to the shared zeropage, so that pages the caller is about to write to (e.g. the target of an O_DIRECT read) are still there to migrate.

No thanks. This whole approach seems completely wrong.

Quoted 764 lines
---
 include/linux/huge_mm.h                |   7 +
 include/linux/pisa-mm.h                |   8 +
 include/linux/pisa.h                   |  18 ++
 include/linux/swap.h                   |   1 +
 include/uapi/asm-generic/mman-common.h |   2 +
 mm/Makefile                            |   2 +-
 mm/huge_memory.c                       |  36 ++-
 mm/madvise.c                           |  19 ++
 mm/pisa-alloc.c                        |   2 +
 mm/pisa-priv.h                         |   2 +
 mm/pisa-user.c                         | 394 +++++++++++++++++++++++++
 11 files changed, 483 insertions(+), 8 deletions(-)
 create mode 100644 mm/pisa-user.c
include/linux/huge_mm.h +7 -0
index fac05120ab774..d679de8cf261d 100644
@@ -404,6 +404,7 @@ int __split_huge_page_to_list_to_order(struct page *page, struct list_head *list
 int folio_split_unmapped(struct folio *folio, unsigned int new_order);
 unsigned int min_order_for_split(struct folio *folio);
 int split_folio_to_list(struct folio *folio, struct list_head *list);
+int split_folio_to_list_keep_zero(struct folio *folio, struct list_head *list);
 int folio_check_splittable(struct folio *folio, unsigned int new_order,
 			   enum split_type split_type);
 int folio_split(struct folio *folio, unsigned int new_order, struct page *page,
@@ -671,6 +672,12 @@ static inline int split_folio_to_list(struct folio *folio, struct list_head *lis
 	return -EINVAL;
 }
 
+static inline int split_folio_to_list_keep_zero(struct folio *folio, struct list_head *list)
+{
+	VM_WARN_ON_ONCE_FOLIO(1, folio);
+	return -EINVAL;
+}
+
 static inline int folio_split(struct folio *folio, unsigned int new_order,
 		struct page *page, struct list_head *list)
 {
include/linux/pisa-mm.h +8 -0
index d55a42397c4b3..1e82e081b4004 100644
@@ -11,6 +11,8 @@ unsigned long __pisa_alloc_pages_bulk(gfp_t gfp, unsigned int order,
 				      int preferred_nid, int nr_pages,
 				      struct page **page_array, bool frozen);
 bool __pisa_free_page(struct page *page, unsigned int order);
+int pisa_madvise(struct vm_area_struct *vma, unsigned long start,
+		 unsigned long end, bool to_pisa);
 
 /*
  * ============================================================================
@@ -77,5 +79,11 @@ static inline bool pisa_free_page(struct page *page, unsigned int order)
 	return false;
 }
 
+static inline int pisa_madvise(struct vm_area_struct *vma, unsigned long start,
+			       unsigned long end, bool to_pisa)
+{
+	return -EINVAL;
+}
+
 #endif /* CONFIG_PISA */
 #endif /* _LINUX_PISA_MM_H */
include/linux/pisa.h +18 -0
index edd34771ad1c4..9321e7ff00042 100644
@@ -14,6 +14,7 @@
 
 struct iommu_domain;
 struct iova_domain;
+struct iov_iter;
 
 /**
  * struct pisa_iova - A domain's IOVA window reserved for PISA pages
@@ -70,9 +71,11 @@ enum {
  * Static keys guarding all kernel hooks:
  * - @pisa_key: enabled on first device opt-in (pisa_meta_init()).
  * - @pisa_recycle_check_key: enabled when pisa.compact or pisa.target_usage_percent > 0.
+ * - @pisa_user_key: enabled when pisa.user_max_pages > 0.
  */
 DECLARE_STATIC_KEY_FALSE(pisa_key);
 DECLARE_STATIC_KEY_FALSE(pisa_recycle_check_key);
+DECLARE_STATIC_KEY_FALSE(pisa_user_key);
 
 extern u32 *pisa_pfn2slot;
 extern unsigned int pisa_nr_slots;
@@ -89,12 +92,19 @@ void *__pisa_alloc_map_coherent_dev(struct device *dev, size_t size,
 				    unsigned long attrs);
 bool __pisa_has_free_blocks_rx(unsigned int order, int nid);
 bool __pisa_page_can_recycle(const struct page *page);
+bool pisa_upgrade_user_pages(struct iov_iter *iter, struct page **pages,
+			     size_t size, size_t offset);
 
 static inline bool pisa_enabled(void)
 {
 	return static_branch_unlikely(&pisa_key);
 }
 
+static inline bool pisa_user_enabled(void)
+{
+	return static_branch_unlikely(&pisa_user_key);
+}
+
 static inline u32 pisa_pfn_flags(unsigned long pfn)
 {
 	unsigned long frame = pfn >> PISA_ORDER;
@@ -195,6 +205,7 @@ static inline bool pisa_page_can_recycle(const struct page *page)
 
 static inline int pisa_meta_init(void) { return -EOPNOTSUPP; }
 static inline bool pisa_enabled(void) { return false; }
+static inline bool pisa_user_enabled(void) { return false; }
 static inline bool is_pisa_pfn(unsigned long pfn) { return false; }
 static inline bool is_pisa_page(const struct page *page) { return false; }
 static inline bool is_pisa_phys(phys_addr_t phys) { return false; }
@@ -228,6 +239,13 @@ static inline bool pisa_page_can_recycle(const struct page *page)
 	return true;
 }
 
+static inline bool pisa_upgrade_user_pages(struct iov_iter *iter,
+					   struct page **pages, size_t size,
+					   size_t offset)
+{
+	return false;
+}
+
 #endif /* CONFIG_PISA */
 
 #if defined(CONFIG_PISA) && defined(CONFIG_IOMMU_DMA)
include/linux/swap.h +1 -0
index 4f686709d71f0..3736786ccc5a3 100644
@@ -314,6 +314,7 @@ extern unsigned long totalreserve_pages;
 /* linux/mm/folio.c */
 void folio_add_lru(struct folio *folio);
 void folio_mark_accessed(struct folio *folio);
+void lru_add_drain(void);
 void lru_add_drain_all(void);
 
 enum lru_cache_drained {
include/uapi/asm-generic/mman-common.h +2 -0
index ef1c27fa3c570..c4332db8e56ff 100644
@@ -81,6 +81,8 @@
 
 #define MADV_GUARD_INSTALL 102		/* fatal signal on access to range */
 #define MADV_GUARD_REMOVE 103		/* unguard range */
+#define MADV_PISA		210	/* move pages into PISA memory */
+#define MADV_NOPISA		211	/* move pages out of PISA memory */
 
 /* compatibility flags */
 #define MAP_FILE	0
mm/Makefile +1 -1
index 7d624e4bad456..d6b54a6eb3dc0 100644
@@ -147,7 +147,7 @@ obj-$(CONFIG_GENERIC_IOREMAP) += ioremap.o
 obj-$(CONFIG_SHRINKER_DEBUG) += shrinker_debug.o
 obj-$(CONFIG_EXECMEM) += execmem.o
 obj-$(CONFIG_PISA) += pisa.o
-pisa-y := pisa-meta.o pisa-alloc.o pisa-node.o
+pisa-y := pisa-meta.o pisa-alloc.o pisa-node.o pisa-user.o
 obj-$(CONFIG_PISA_META_KUNIT_TEST) += pisa-kunit.o
 obj-$(CONFIG_TMPFS_QUOTA) += shmem_quota.o
 obj-$(CONFIG_LAZY_MMU_MODE_KUNIT_TEST) += tests/lazy_mmu_mode_kunit.o
mm/huge_memory.c +29 -7
index 7791872f14af7..ffa3912f2418b 100644
@@ -4113,7 +4113,8 @@ static void folio_reset_partially_mapped(struct folio *folio)
 
 static int __folio_freeze_split_anon(struct folio *folio,
 		unsigned int new_order, struct page *split_at, bool do_lru,
-		struct list_head *list, enum split_type split_type)
+		struct list_head *list, enum split_type split_type,
+		bool keep_zero)
 {
 	struct folio *end_folio = folio_next(folio);
 	struct swap_cluster_info *ci = NULL;
@@ -4207,7 +4208,13 @@ static int __folio_freeze_split_anon(struct folio *folio,
 out_no_split:
 	local_irq_enable();
 	if (anon_vma) {
-		if (!ret && !folio_is_device_private(folio))
+		/*
+		 * Zero-filled anon subpages are normally unmapped, freed and
+		 * replaced by the shared zeropage. A @keep_zero caller needs
+		 * the subpages themselves, e.g. to migrate them before a
+		 * device writes to them.
+		 */
+		if (!ret && !folio_is_device_private(folio) && !keep_zero)
 			ttu_flags = TTU_USE_SHARED_ZEROPAGE;
 		remap_anon_folio(folio, 1 << old_order, ttu_flags);
 	}
@@ -4387,6 +4394,7 @@ static int __folio_freeze_split_file(struct folio *folio,
  * @lock_at: a page within @folio to be left locked to caller
  * @list: after-split folios will be put on it if non NULL
  * @split_type: perform uniform split or not (non-uniform split)
+ * @keep_zero: do not remap zero-filled anon subpages to the shared zeropage
  *
  * It calls __split_frozen_folio() to perform uniform and non-uniform split.
  * It is in charge of checking whether the split is supported or not and
@@ -4402,7 +4410,8 @@ static int __folio_freeze_split_file(struct folio *folio,
  */
 static int __folio_split(struct folio *folio, unsigned int new_order,
 		struct page *split_at, struct page *lock_at,
-		struct list_head *list, enum split_type split_type)
+		struct list_head *list, enum split_type split_type,
+		bool keep_zero)
 {
 	struct folio *end_folio = folio_next(folio);
 	const bool is_anon = folio_test_anon(folio);
@@ -4432,7 +4441,8 @@ static int __folio_split(struct folio *folio, unsigned int new_order,
 
 	if (is_anon)
 		ret = __folio_freeze_split_anon(folio, new_order, split_at,
-						true, list, split_type);
+						true, list, split_type,
+						keep_zero);
 	else
 		ret = __folio_freeze_split_file(folio, new_order, split_at,
 						list, split_type);
@@ -4495,7 +4505,7 @@ int folio_split_unmapped(struct folio *folio, unsigned int new_order)
 	VM_WARN_ON_ONCE_FOLIO(!folio_test_anon(folio), folio);
 
 	return __folio_freeze_split_anon(folio, new_order, &folio->page,
-					 false, NULL, SPLIT_TYPE_UNIFORM);
+					 false, NULL, SPLIT_TYPE_UNIFORM, false);
 }
 
 /*
@@ -4551,7 +4561,7 @@ int __split_huge_page_to_list_to_order(struct page *page, struct list_head *list
 	struct folio *folio = page_folio(page);
 
 	return __folio_split(folio, new_order, &folio->page, page, list,
-			     SPLIT_TYPE_UNIFORM);
+			     SPLIT_TYPE_UNIFORM, false);
 }
 
 /**
@@ -4582,7 +4592,7 @@ int folio_split(struct folio *folio, unsigned int new_order,
 		struct page *split_at, struct list_head *list)
 {
 	return __folio_split(folio, new_order, split_at, &folio->page, list,
-			     SPLIT_TYPE_NON_UNIFORM);
+			     SPLIT_TYPE_NON_UNIFORM, false);
 }
 
 /**
@@ -4617,6 +4627,18 @@ int split_folio_to_list(struct folio *folio, struct list_head *list)
 	return split_huge_page_to_list_to_order(&folio->page, list, 0);
 }
 
+/*
+ * As split_folio_to_list(), but zero-filled subpages of an anon folio stay
+ * mapped instead of being remapped to the shared zeropage. For callers that
+ * are about to take write references on the subpages: PISA uses it to migrate
+ * the pages of an I/O buffer, e.g. the target of an O_DIRECT read.
+ */
+int split_folio_to_list_keep_zero(struct folio *folio, struct list_head *list)
+{
+	return __folio_split(folio, 0, &folio->page, &folio->page, list,
+			     SPLIT_TYPE_UNIFORM, true);
+}
+
 /*
  * __folio_unqueue_deferred_split() is not to be called directly:
  * the folio_unqueue_deferred_split() inline wrapper in mm/internal.h
mm/madvise.c +19 -0
index 0214efd2a014f..46981ad295aa5 100644
@@ -6,6 +6,7 @@
  * Copyright (C) 2002  Christoph Hellwig
  */
 
+#include <linux/pisa-mm.h>
 #include <linux/mman.h>
 #include <linux/pagemap.h>
 #include <linux/syscalls.h>
@@ -1393,6 +1394,11 @@ static int madvise_vma_behavior(struct madvise_behavior *madv_behavior)
 		return madvise_guard_install(madv_behavior);
 	case MADV_GUARD_REMOVE:
 		return madvise_guard_remove(madv_behavior);
+#ifdef MADV_PISA
+	case MADV_PISA:
+	case MADV_NOPISA:
+		return pisa_madvise(vma, range->start, range->end, behavior == MADV_PISA);
+#endif
 
 	/* The below behaviours update VMAs via madvise_update_vma(). */
 
@@ -1582,6 +1588,11 @@ madvise_behavior_valid(int behavior)
 	case MADV_HWPOISON:
 #endif
 		return true;
+#ifdef MADV_PISA
+	case MADV_PISA:
+	case MADV_NOPISA:
+		return IS_ENABLED(CONFIG_PISA);
+#endif
 
 	default:
 		return false;
@@ -1596,6 +1607,10 @@ static bool process_madvise_remote_valid(int behavior)
 	case MADV_PAGEOUT:
 	case MADV_WILLNEED:
 	case MADV_COLLAPSE:
+#ifdef MADV_PISA
+	case MADV_PISA:
+	case MADV_NOPISA:
+#endif
 		return true;
 	default:
 		return false;
@@ -1782,6 +1797,10 @@ static enum madvise_lock_mode get_lock_mode(struct madvise_behavior *madv_behavi
 	case MADV_POPULATE_READ:
 	case MADV_POPULATE_WRITE:
 	case MADV_COLLAPSE:
+#ifdef MADV_PISA
+	case MADV_PISA:
+	case MADV_NOPISA:
+#endif
 		return MADVISE_MMAP_READ_LOCK;
 	case MADV_GUARD_INSTALL:
 	case MADV_GUARD_REMOVE:
mm/pisa-alloc.c +2 -0
index ccba2bf01bd59..2213a56de1242 100644
@@ -1432,6 +1432,8 @@ static int __init pisa_init(void)
 				  "pisa_ro_o%u_n%d", SKB_FRAG_PAGE_ORDER, nid);
 	}
 
+	pisa_user_boot_enable();
+
 	/* Dedicated WQ_MEM_RECLAIM workqueue so reclaim never blocks behind system_wq. */
 	pisa_wq = alloc_workqueue("pisa", WQ_MEM_RECLAIM, 0);
 	if (!pisa_wq)
mm/pisa-priv.h +2 -0
index 9f01173d30f5f..b18d461198ac5 100644
@@ -133,6 +133,7 @@ static inline long pisa_alloc_held_pages(const struct pisa_alloc *pa)
 struct pisa_node {
 	unsigned long		next_alloc;	/* atomic alloc backoff jiffies */
 	struct pisa_alloc	*pa[2][PISA_MAX_ALLOC_ORDER + 1]; /* [0]=RW, [1]=RO */
+	struct pisa_alloc	*user_pa;	/* user page migration pa */
 
 	spinlock_t		lock;		/* protects @pages and @nr_pages */
 	unsigned int		nr_pages;	/* entries in @pages */
@@ -245,6 +246,7 @@ void pisa_schedule_scrub_all(void);
 struct pisa_meta *pisa_reservoir_pop(int nid, gfp_t gfp, bool *clean);
 unsigned long pisa_reservoir_count(void);
 unsigned long pisa_reservoir_shrink(struct list_head *release_list, unsigned long nr_to_scan);
+void pisa_user_boot_enable(void);
 
 #endif /* CONFIG_PISA */
 #endif /* _MM_PISA_PRIV_H */
mm/pisa-user.c new file +394 -1
new file mode 100644
index 0000000000000..6c3efaee4ecda
@@ -0,0 +1,394 @@
+// SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
+/*
+ * PISA user and page-cache folios: allocate or migrate order-0 folios into
+ * per-node PISA allocators so zero-copy TX and block I/O use the PISA IOMMU mappings.
+ */
+#include <linux/pisa.h>
+#include <linux/gfp.h>
+#include <linux/huge_mm.h>
+#include <linux/migrate.h>
+#include <linux/mm.h>
+#include <linux/moduleparam.h>
+#include <linux/nodemask.h>
+#include <linux/pagewalk.h>
+#include <linux/swap.h>
+#include <linux/uio.h>
+
+#include "pisa-priv.h"
+
+/* Soft cap on user (PTE) pages held in PISA blocks, in PISA pages (0 = disabled). */
+static unsigned long pisa_user_max_pages __read_mostly;
+DEFINE_STATIC_KEY_FALSE(pisa_user_key);
+
+/* Create per-node user allocators and enable pisa_user_key (serialized by param_lock/init). */
+static int pisa_user_init(void)
+{
+	int nid;
+
+	if (pisa_user_enabled())
+		return 0;
+	if (pisa_meta_init())
+		return -ENOMEM;
+	for_each_node_state(nid, N_MEMORY) {
+		if (!pisa_alloc_ensure(&pisa_nodes[nid].user_pa, nid, 0,
+				       DMA_TO_DEVICE, false, "user_tx_n%d", nid))
+			return -ENOMEM;
+	}
+	static_branch_enable(&pisa_user_key);
+	return 0;
+}
+
+static int pisa_user_max_set(const char *val, const struct kernel_param *kp)
+{
+	unsigned long max_pages;
+	int ret;
+
+	ret = kstrtoul(val, 0, &max_pages);
+	if (ret)
+		return ret;
+	WRITE_ONCE(pisa_user_max_pages, max_pages);
+	if (!max_pages) {
+		static_branch_disable(&pisa_user_key);
+	} else if (pisa_nodes[first_memory_node].pa[0][0] && pisa_user_init()) {
+		WRITE_ONCE(pisa_user_max_pages, 0);
+		return -ENOMEM;
+	}
+	return 0;
+}
+
+static const struct kernel_param_ops pisa_user_max_ops = {
+	.set = pisa_user_max_set,
+	.get = param_get_ulong,
+};
+module_param_cb(user_max_pages, &pisa_user_max_ops, &pisa_user_max_pages, 0644);
+
+/*
+ * Initialize per-node user allocators if pisa.user_max_pages was set on
+ * the kernel command line before pisa_init() ran.
+ */
+void __init pisa_user_boot_enable(void)
+{
+	if (READ_ONCE(pisa_user_max_pages))
+		pisa_user_init();
+}
+
+/* User pages currently held in PISA blocks. */
+static unsigned long pisa_user_in_use(void)
+{
+	unsigned long used = 0;
+	int nid;
+
+	for_each_node_state(nid, N_MEMORY) {
+		/* Pairs with smp_store_release() in pisa_user_init(). */
+		const struct pisa_alloc *pa = smp_load_acquire(&pisa_nodes[nid].user_pa);
+
+		used += pa ? READ_ONCE(pa->blocks_in_use) : 0;
+	}
+	return used;
+}
+
+/* Pages that can still be moved in before reaching pisa.user_max_pages. */
+static long pisa_user_budget(void)
+{
+	return (long)((READ_ONCE(pisa_user_max_pages) << PISA_ORDER) - pisa_user_in_use());
+}
+
+/* Is @folio worth moving into (@to_pisa) or out of PISA memory? */
+static bool pisa_user_want(struct folio *folio, bool to_pisa)
+{
+	if (!folio_test_anon(folio) || folio_is_zone_device(folio) ||
+	    folio_test_ksm(folio) || is_huge_zero_folio(folio) ||
+	    (folio_test_large(folio) && !to_pisa) ||
+	    folio_maybe_mapped_shared(folio))
+		return false;
+	return is_pisa_pfn(folio_pfn(folio)) != to_pisa;
+}
+
+/* Return true if @folio has references beyond its mappings, swap cache, and @extra. */
+static bool pisa_user_busy(struct folio *folio, int extra)
+{
+	return folio_ref_count(folio) > folio_expected_ref_count(folio) + extra;
+}
+
+struct pisa_user_mtc {
+	gfp_t	gfp;
+	long	budget;
+};
+
+/* new_folio_t for migration into PISA memory. */
+static struct folio *pisa_user_new_folio(struct folio *src, unsigned long private)
+{
+	struct pisa_user_mtc *mtc = (void *)private;
+	int nid = folio_nid(src);
+	struct page *page;
+
+	/* Callers split large folios first (see pisa_user_split()); none is expected here. */
+	if (mtc->budget <= 0 || folio_test_large(src))
+		return NULL;
+	page = pisa_alloc(pisa_nodes[nid].user_pa, mtc->gfp);
+	if (!page)
+		return NULL;
+	mtc->budget--;
+	return page_folio(page);
+}
+
+/* free_folio_t: give back an unused destination block and the budget it was charged. */
+static void pisa_user_put_folio(struct folio *dst, unsigned long private)
+{
+	struct pisa_user_mtc *mtc = (void *)private;
+
+	mtc->budget++;
+	folio_put(dst);
+}
+
+/* new_folio_t for migration out of PISA memory: allocators never serve these. */
+static struct folio *pisa_user_old_folio(struct folio *src, unsigned long private)
+{
+	return __folio_alloc_node(GFP_HIGHUSER_MOVABLE | __GFP_NOWARN, 0, folio_nid(src));
+}
+
+/* Migrate the isolated folios on @list; failures are put back. */
+static void pisa_user_migrate(struct list_head *list, bool to_pisa, gfp_t gfp)
+{
+	struct pisa_user_mtc mtc = { .gfp = gfp, .budget = LONG_MAX };
+	enum migrate_mode mode = MIGRATE_SYNC;
+
+	if (list_empty(list))
+		return;
+	if (to_pisa) {
+		mtc.budget = pisa_user_budget();
+		if (!gfpflags_allow_blocking(gfp))
+			mode = MIGRATE_ASYNC;
+	}
+	if (migrate_pages(list, to_pisa ? pisa_user_new_folio : pisa_user_old_folio,
+			  to_pisa ? pisa_user_put_folio : NULL, (unsigned long)&mtc,
+			  mode, MR_SYSCALL, NULL))
+		putback_movable_pages(list);
+}
+
+/*
+ * Split large anon @folio to order 0, with the caller holding the only extra
+ * reference. Zero-filled subpages stay mapped instead of being replaced by the
+ * shared zeropage, so that a GUP for write that follows (e.g. an O_DIRECT
+ * read) finds them. After-split folios go to @list, or to the LRU if NULL.
+ */
+static bool pisa_user_split(struct folio *folio, struct list_head *list, bool can_wait)
+{
+	int ret;
+
+	if (can_wait)
+		folio_lock(folio);
+	else if (!folio_trylock(folio))
+		return false;
+	ret = split_folio_to_list_keep_zero(folio, list);
+	folio_unlock(folio);
+	return !ret;
+}
+
+/*
+ * Split isolated large @folio and move to @out the subpages found in @pages.
+ * The others, or all of @folio if @split is false or the split fails, go back
+ * to the LRU. Returns the number of subpages moved to @out.
+ */
+static unsigned int pisa_user_split_isolated(struct folio *folio, struct list_head *out,
+					     struct page **pages, unsigned int nr, bool split)
+{
+	const struct page *lo = NULL, *hi = NULL;
+	unsigned int kept = 0;
+	struct folio *f, *next;
+	LIST_HEAD(pieces);
+
+	/* @folio is held isolated, so page_folio() of its subpages is stable. */
+	for (unsigned int i = 0; i < nr; i++) {
+		if (page_folio(pages[i]) != folio)
+			continue;
+		if (!lo || pages[i] < lo)
+			lo = pages[i];
+		if (!hi || pages[i] > hi)
+			hi = pages[i];
+	}
+	list_move(&folio->lru, &pieces);
+	if (split && pisa_user_split(folio, &pieces, false)) {
+		list_for_each_entry_safe(f, next, &pieces, lru) {
+			if (!folio_test_large(f) && &f->page >= lo && &f->page <= hi) {
+				list_move_tail(&f->lru, out);
+				kept++;
+			}
+		}
+	}
+	putback_movable_pages(&pieces);
+	return kept;
+}
+
+/**
+ * pisa_upgrade_user_pages - Migrate extracted user @pages into PISA
+ * @iter: Iterator from which @pages were just extracted
+ * @pages: Extracted page array, one reference each
+ * @size: Number of bytes extracted from @iter
+ * @offset: Byte offset within @pages[0]
+ *
+ * Return: false if no pages were isolated (@pages and @iter are untouched);
+ * true otherwise, so the caller must re-extract @pages from the reverted @iter.
+ */
+bool pisa_upgrade_user_pages(struct iov_iter *iter, struct page **pages,
+			     size_t size, size_t offset)
+{
+	unsigned int nr = DIV_ROUND_UP(offset + size, PAGE_SIZE);
+	unsigned int want = 0;
+	struct folio *f, *next;
+	bool drained = false;
+	LIST_HEAD(small);
+	LIST_HEAD(list);
+	long budget;
+
+	if (!pisa_user_enabled())
+		return false;
+	/*
+	 * First pass: check if any page needs migration and whether budget is
+	 * available before draining per-CPU LRU caches or isolating folios.
+	 */
+	for (unsigned int i = 0; i < nr; i++)
+		want += pisa_user_want(page_folio(pages[i]), true);
+	if (!want || pisa_user_budget() <= 0)
+		return false;
+	for (unsigned int i = 0; i < nr; i++) {
+		struct folio *folio = page_folio(pages[i]);
+		unsigned int refs = 0;
+
+		if (!pisa_user_want(folio, true))
+			continue;
+		/* Drain per-CPU LRU batches once so freshly faulted folios can be isolated. */
+		if (!drained && !folio_test_lru(folio)) {
+			lru_add_drain();
+			drained = true;
+		}
+		if (!folio_test_lru(folio))
+			continue;
+		for (unsigned int j = 0; j < nr; j++)
+			refs += page_folio(pages[j]) == folio;
+		/* The references from iov_iter_get_pages2() are expected. */
+		if (folio_maybe_dma_pinned(folio) || pisa_user_busy(folio, refs))
+			continue;
+		if (isolate_folio_to_list(folio, &list))
+			list_move_tail(&folio->lru, &list);
+	}
+	if (list_empty(&list))
+		return false;
+	/*
+	 * Release the caller's references on @pages before migrating
+	 * (migrate_pages() rejects folios with extra references).
+	 */
+	for (unsigned int i = 0; i < nr; i++)
+		put_page(pages[i]);
+	/*
+	 * Split large folios while budget remains and keep only their subpages
+	 * that are in @pages: migrate_pages() would split them regardless of
+	 * the budget, migrate every subpage and drop the zero-filled ones.
+	 */
+	budget = pisa_user_budget();
+	list_for_each_entry_safe(f, next, &list, lru) {
+		if (folio_test_large(f))
+			budget -= pisa_user_split_isolated(f, &small, pages, nr, budget > 0);
+		else
+			budget -= !is_pisa_pfn(folio_pfn(f));
+	}
+	list_splice_tail(&small, &list);
+	pisa_user_migrate(&list, true,
+			  GFP_NOWAIT | __GFP_HARDWALL | __GFP_NOWARN);
+	/* Rewind @iter so the caller re-extracts the updated page pointers. */
+	iov_iter_revert(iter, size);
+	return true;
+}
+
+#define PISA_USER_BATCH	512
+
+struct pisa_madvise_walk {
+	struct list_head	list;	/* isolated folios waiting to be migrated */
+	unsigned int		n;	/* pages on @list */
+	bool			to_pisa;
+};
+
+#define PISA_MADVISE_GFP	(GFP_USER | __GFP_NOWARN)
+
+/* Isolate the wanted folios mapped in one PMD's range, splitting the large ones first. */
+static int pisa_madvise_pmd_entry(pmd_t *pmd, unsigned long addr, unsigned long end,
+				  struct mm_walk *walk)
+{
+	struct pisa_madvise_walk *w = walk->private;
+	bool to_pisa = w->to_pisa;
+	struct folio_walk fw;
+	struct folio *folio;
+
+	while (addr < end) {
+		unsigned long nr = 1;
+
+		if (fatal_signal_pending(current))
+			return -EINTR;
+		/* Stop the walk, without an error, once the cap is reached. */
+		if (to_pisa && pisa_user_budget() <= (long)w->n)
+			return 1;
+		folio = folio_walk_start(&fw, walk->vma, addr, 0);
+		if (folio) {
+			bool want = pisa_user_want(folio, to_pisa) && folio_test_lru(folio);
+			bool busy = want && pisa_user_busy(folio, 0);
+			bool split = want && !busy && folio_test_large(folio);
+
+			/* A PMD mapping covers the rest of the range, a PTE maps one page. */
+			if (fw.level != FW_LEVEL_PTE)
+				nr = (end - addr) >> PAGE_SHIFT;
+			if (split) {
+				folio_get(folio);
+			} else if (want && !busy && isolate_folio_to_list(folio, &w->list)) {
+				list_move_tail(&folio->lru, &w->list);
+				w->n++;
+			}
+			folio_walk_end(&fw, walk->vma);
+			if (split) {
+				split = pisa_user_split(folio, NULL, true);
+				folio_put(folio);
+				/* Look at @addr again: it now maps an order-0 folio. */
+				if (split)
+					continue;
+			}
+		}
+		if (w->n >= PISA_USER_BATCH) {
+			pisa_user_migrate(&w->list, to_pisa, PISA_MADVISE_GFP);
+			w->n = 0;
+		}
+		addr += nr << PAGE_SHIFT;
+		cond_resched();
+	}
+	return 0;
+}
+
+static const struct mm_walk_ops pisa_madvise_walk_ops = {
+	.pmd_entry	= pisa_madvise_pmd_entry,
+	.walk_lock	= PGWALK_RDLOCK,
+};
+
+/**
+ * pisa_madvise - MADV_PISA / MADV_NOPISA on [@start, @end) of @vma
+ * @vma: VMA, with the mmap lock held for reading
+ * @start: Start address
+ * @end: End address
+ * @to_pisa: true to move present pages into PISA, false to move them out
+ *
+ * Return: 0, -EINVAL for unsupported mappings, or -EOPNOTSUPP if disabled.
+ */
+int pisa_madvise(struct vm_area_struct *vma, unsigned long start, unsigned long end, bool to_pisa)
+{
+	struct pisa_madvise_walk w = { .list = LIST_HEAD_INIT(w.list), .to_pisa = to_pisa };
+	int ret;
+
+	if (vma->vm_flags & (VM_SHARED | VM_IO | VM_PFNMAP | VM_HUGETLB))
+		return -EINVAL;
+	if (to_pisa && !pisa_user_enabled())
+		return -EOPNOTSUPP;
+	if (!pisa_enabled() && !to_pisa)
+		return 0;
+	lru_add_drain();
+	/* The page walker skips the unpopulated page-table levels of sparse mappings. */
+	ret = walk_page_range_vma(vma, start, end, &pisa_madvise_walk_ops, &w);
+	pisa_user_migrate(&w.list, to_pisa, PISA_MADVISE_GFP);
+	return ret < 0 ? ret : 0;
+}
--
Quoted 2 lines

2.56.1.809.ga0b61035b5-goog

--
Cheers, Lorenzo

#80 lore raw

Re: [RFC PATCH v3 11/25] mm: Migrate user pages into PISA

In reply to Luigi Rizzo
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Low] mm: shift overflow on unclamped pisa_user_max_pages in pisa_user_budget() - [Low] mm: redundant…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Low] mm: shift overflow on unclamped pisa_user_max_pages in pisa_user_budget()
- [Low] mm: redundant lru_add_drain() on large folios in pisa_upgrade_user_pages()
--

commit 0013c02c237d37de8c598b2b6ae3c55e334c3521
Author: Luigi Rizzo <[email protected]>

mm: Migrate user pages into PISA

This commit adds mm/pisa-user.c to migrate private anonymous user pages into per-node PISA allocators via madvise(MADV_PISA) / MADV_NOPISA and pisa_upgrade_user_pages(), splitting large anonymous folios to order 0 without remapping zero-filled subpages to the shared zeropage.

Quoted 6 lines
mm/pisa-user.c new file +0 -0
new file mode 100644
index 0000000000000..6c3efaee4ecda
@@ -0,0 +1,394 @@

[ ... ]

Quoted 17 lines
mm/pisa-user.c new file +17 -0
+static int pisa_user_max_set(const char *val, const struct kernel_param *kp)
+{
+	unsigned long max_pages;
+	int ret;
+
+	ret = kstrtoul(val, 0, &max_pages);
+	if (ret)
+		return ret;
+	WRITE_ONCE(pisa_user_max_pages, max_pages);
+	if (!max_pages) {
+		static_branch_disable(&pisa_user_key);
+	} else if (pisa_nodes[first_memory_node].pa[0][0] && pisa_user_init()) {
+		WRITE_ONCE(pisa_user_max_pages, 0);
+		return -ENOMEM;
+	}
+	return 0;
+}

[ ... ]

mm/pisa-user.c line 94

Quoted 5 lines
mm/pisa-user.c new file +5 -0
+/* Pages that can still be moved in before reaching pisa.user_max_pages. */
+static long pisa_user_budget(void)
+{
+	return (long)((READ_ONCE(pisa_user_max_pages) << PISA_ORDER) - pisa_user_in_use());
+}

[Severity: Low]
Can READ_ONCE(pisa_user_max_pages) << PISA_ORDER overflow in pisa_user_budget()?

pisa_user_max_set() stores max_pages without clamping it. If an administrator writes a large value such as ULONG_MAX to pisa.user_max_pages, left-shifting by PISA_ORDER wraps or overflows the signed long cast, producing a non-positive budget that causes pisa_madvise() and pisa_upgrade_user_pages() to skip all user page migrations into PISA.

[ ... ]

Quoted 3 lines
mm/pisa-user.c new file +3 -0
+bool pisa_upgrade_user_pages(struct iov_iter *iter, struct page **pages,
+			     size_t size, size_t offset)
+{

[ ... ]

Quoted 11 lines
mm/pisa-user.c new file +11 -0
+	for (unsigned int i = 0; i < nr; i++) {
+		struct folio *folio = page_folio(pages[i]);
+		unsigned int refs = 0;
+
+		if (!pisa_user_want(folio, true))
+			continue;
+		/* Drain per-CPU LRU batches once so freshly faulted folios can be isolated. */
+		if (!drained && !folio_test_lru(folio)) {
+			lru_add_drain();
+			drained = true;
+		}

mm/pisa-user.c line 274

Quoted 10 lines
mm/pisa-user.c new file +10 -0
+		if (!folio_test_lru(folio))
+			continue;
+		for (unsigned int j = 0; j < nr; j++)
+			refs += page_folio(pages[j]) == folio;
+		/* The references from iov_iter_get_pages2() are expected. */
+		if (folio_maybe_dma_pinned(folio) || pisa_user_busy(folio, refs))
+			continue;
+		if (isolate_folio_to_list(folio, &list))
+			list_move_tail(&folio->lru, &list);
+	}

[Severity: Low]
Does isolating a large folio on its first subpage trigger an unnecessary lru_add_drain() on its second subpage?

When pages[] contains multiple subpages of the same large folio, isolate_folio_to_list() clears PG_lru on the first subpage. On the next subpage of that folio, !folio_test_lru(folio) is true and calls lru_add_drain() even though the folio was already on the LRU and has just been isolated.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=11
#81 lore raw

RFC PATCH v3 12/25 block, mm: Support PISA for disk I/O and scrub migration

In reply to Luigi Rizzo

Extend PISA user/page-cache allocators to support O_DIRECT and buffered disk I/O, gated per block/controller device through pisa_rx_bufs (read) and pisa_tx_bufs (write):

- Split per-node user_pa into DMA_BIDIRECTIONAL, DMA_TO_DEVICE, and DMA_FROM_DEVICE allocators, promoting pages to DMA_BIDIRECTIONAL if later accessed in the opposite direction.
- Upgrade pinned O_DIRECT user pages in bio_iov_iter_get_pages(), and allocate/promote order-0 page-cache folios for buffered I/O when PISA is enabled on the target block device.
- Add pisa.scrub_migrate to compact or demote lingering folios off old, sparse user_pa 2MB pages.

Assisted-by gemini:2.5-pro
---
 block/bio.c             |   9 +
 include/linux/pisa-mm.h |  76 ++++++
 include/linux/pisa.h    |   7 +-
 mm/filemap.c            |  12 +-
 mm/page-writeback.c     |   9 +
 mm/pisa-alloc.c         |  18 +-
 mm/pisa-meta.c          |  15 +-
 mm/pisa-node.c          |  10 +-
 mm/pisa-priv.h          |   9 +-
 mm/pisa-user.c          | 523 ++++++++++++++++++++++++++++++++++++----
 mm/readahead.c          |   3 +-
 11 files changed, 635 insertions(+), 56 deletions(-)
block/bio.c +9 -0
index b0fcc69de6535..ad8632661dddf 100644
@@ -6,6 +6,7 @@
 #include <linux/swap.h>
 #include <linux/bio-integrity.h>
 #include <linux/blkdev.h>
+#include <linux/pisa-mm.h>
 #include <linux/uio.h>
 #include <linux/iocontext.h>
 #include <linux/slab.h>
@@ -1346,6 +1347,7 @@ int bio_iov_iter_get_pages(struct bio *bio, struct iov_iter *iter,
 {
 	iov_iter_extraction_t flags = 0;
 	struct iov_iter saved_iter;
+	bool migrated = false;
 	int ret;
 
 	if (WARN_ON_ONCE(bio_flagged(bio, BIO_CLONED)))
@@ -1368,6 +1370,7 @@ int bio_iov_iter_get_pages(struct bio *bio, struct iov_iter *iter,
 		flags |= ITER_ALLOW_P2PDMA;
 
 	saved_iter = *iter;
+retry:
 	do {
 		ssize_t size;
 
@@ -1386,6 +1389,12 @@ int bio_iov_iter_get_pages(struct bio *bio, struct iov_iter *iter,
 		bio->bi_iter.bi_size += size;
 	} while (iov_iter_count(iter) && !bio_full(bio, 0));
 
+	/* Migrate suitable pages to PISA, re-extract if so. */
+	if (!migrated && pisa_bio_migrate_pages(bio, iter)) {
+		migrated = true;
+		goto retry;
+	}
+
 	if (is_pci_p2pdma_page(bio->bi_io_vec->bv_page))
 		bio->bi_opf |= REQ_NOMERGE;
 	ret = bio_iov_iter_align_down(bio, iter, len_align_mask);
include/linux/pisa-mm.h +76 -0

102 lines not on this page · raw message

include/linux/pisa.h +5 -2
index 9321e7ff00042..6d184e393e297 100644
@@ -93,7 +93,8 @@ void *__pisa_alloc_map_coherent_dev(struct device *dev, size_t size,
 bool __pisa_has_free_blocks_rx(unsigned int order, int nid);
 bool __pisa_page_can_recycle(const struct page *page);
 bool pisa_upgrade_user_pages(struct iov_iter *iter, struct page **pages,
-			     size_t size, size_t offset);
+			     size_t size, size_t offset,
+			     enum dma_data_direction dir, bool pinned);
 
 static inline bool pisa_enabled(void)
 {
@@ -241,7 +242,9 @@ static inline bool pisa_page_can_recycle(const struct page *page)
 
 static inline bool pisa_upgrade_user_pages(struct iov_iter *iter,
 					   struct page **pages, size_t size,
-					   size_t offset)
+					   size_t offset,
+					   enum dma_data_direction dir,
+					   bool pinned)
 {
 	return false;
 }
mm/filemap.c +11 -1
index f9e34144c53c7..7d870c22abe53 100644
@@ -15,6 +15,7 @@
 #include <linux/dax.h>
 #include <linux/fs.h>
 #include <linux/sched/signal.h>
+#include <linux/pisa-mm.h>
 #include <linux/uaccess.h>
 #include <linux/capability.h>
 #include <linux/kernel_stat.h>
@@ -1976,6 +1977,7 @@ void *filemap_get_entry(struct address_space *mapping, pgoff_t index)
 struct folio *__filemap_get_folio_mpol(struct address_space *mapping,
 		pgoff_t index, fgf_t fgp_flags, gfp_t gfp, struct mempolicy *policy)
 {
+	bool tried_pisa = false;
 	struct folio *folio;
 
 repeat:
@@ -1985,6 +1987,13 @@ struct folio *__filemap_get_folio_mpol(struct address_space *mapping,
 	if (!folio)
 		goto no_page;
 
+	if (!tried_pisa) {
+		tried_pisa = true;
+		if (pisa_filemap_upgrade(mapping, folio,
+					 (fgp_flags & (FGP_WRITE | FGP_NOWAIT)) == FGP_WRITE))
+			goto repeat;
+	}
+
 	if (fgp_flags & FGP_LOCK) {
 		if (fgp_flags & FGP_NOWAIT) {
 			if (!folio_trylock(folio)) {
@@ -2044,7 +2053,8 @@ struct folio *__filemap_get_folio_mpol(struct address_space *mapping,
 			err = -ENOMEM;
 			if (order > min_order)
 				alloc_gfp |= __GFP_NORETRY | __GFP_NOWARN;
-			folio = filemap_alloc_folio(alloc_gfp, order, policy);
+			folio = pisa_filemap_alloc_folio(alloc_gfp, order,
+							 policy, mapping);
 			if (!folio)
 				continue;
 
mm/page-writeback.c +9 -0
index 0694ec4098f6d..5f1327c22c0e4 100644
@@ -37,6 +37,7 @@
 #include <linux/sched/rt.h>
 #include <linux/sched/signal.h>
 #include <linux/mm_inline.h>
+#include <linux/pisa-mm.h>
 #include <linux/shmem_fs.h>
 #include <trace/events/writeback.h>
 
@@ -2409,6 +2410,7 @@ static pgoff_t wbc_end(struct writeback_control *wbc)
 static struct folio *writeback_get_folio(struct address_space *mapping,
 		struct writeback_control *wbc)
 {
+	bool tried_pisa = false;
 	struct folio *folio;
 
 retry:
@@ -2423,6 +2425,13 @@ static struct folio *writeback_get_folio(struct address_space *mapping,
 			return NULL;
 	}
 
+	if (!tried_pisa &&
+	    pisa_writeback_upgrade(mapping, folio, &wbc->index, &wbc->fbatch)) {
+		tried_pisa = true;
+		goto retry;
+	}
+	tried_pisa = false;
+
 	folio_lock(folio);
 	if (unlikely(!folio_prepare_writeback(mapping, wbc, folio))) {
 		folio_unlock(folio);
mm/pisa-alloc.c +17 -1
index 2213a56de1242..8c4c0f1f1cf50 100644
@@ -574,6 +574,20 @@ static unsigned int pisa_pcp_pop(struct pisa_alloc *pa, unsigned int nr, struct
 	return got;
 }
 
+/* Free blocks in the per-CPU caches of @pa, which @pa->blocks_in_use counts as in use. */
+unsigned long pisa_pcp_cached(struct pisa_alloc *pa)
+{
+	unsigned long n = 0;
+	int cpu;
+
+	/* Pairs with smp_store_release() in pisa_enable_pcp(). */
+	if (!smp_load_acquire(&pa->pcp))
+		return 0;
+	for_each_possible_cpu(cpu)
+		n += READ_ONCE(per_cpu_ptr(pa->pcp, cpu)->count);
+	return n;
+}
+
 /* Return the blocks @cpu caches for @pa. */
 static void pisa_pcp_drain_cpu(struct pisa_alloc *pa, int cpu)
 {
@@ -1316,7 +1330,9 @@ bool __pisa_free_page(struct page *page, unsigned int order)
 			pisa_pcp_push(pa, 1, &page);
 			return true;
 		}
-		pisa_pcp_drain_cpu(pa, raw_smp_processor_id());
+		/* A compaction target drains the caches once, when it is done. */
+		if (!(READ_ONCE(meta->on_list) & PISA_LIST_HOLD))
+			pisa_pcp_drain_cpu(pa, raw_smp_processor_id());
 	}
 
 	spin_lock_irqsave(&pa->lock, flags);
mm/pisa-meta.c +13 -2
index 49fa5271a392f..25d3add7a4891 100644
@@ -85,8 +85,8 @@ DEFINE_STATIC_KEY_FALSE(pisa_key);
 EXPORT_SYMBOL(pisa_key);
 
 static unsigned int pisa_compact __read_mostly;
-static unsigned int pisa_target_usage_percent __read_mostly;
-static unsigned int pisa_old_ms __read_mostly;
+unsigned int pisa_target_usage_percent __read_mostly;
+unsigned int pisa_old_ms __read_mostly;
 
 /* Enabled when pisa.compact > 0 or pisa.target_usage_percent > 0. */
 DEFINE_STATIC_KEY_FALSE(pisa_recycle_check_key);
@@ -189,6 +189,10 @@ bool pisa_place_meta(struct pisa_meta *meta)
 
 	lockdep_assert_held(&pa->lock);
 
+	/* A compaction target stays parked until pisa_user_scrub_alloc() is done. */
+	if (meta->on_list & PISA_LIST_HOLD)
+		return false;
+
 	if (avail == bpp) {
 		/* All blocks free: retire immediately if quarantined or over idle cap with idle_ms == 0. */
 		if (pa->num_idle_pages >= pa->max_idle_pages)
@@ -283,6 +287,10 @@ static bool pisa_meta_can_recycle(struct pisa_meta *meta)
 	if (unlikely(READ_ONCE(meta->flags) & PISA_QUARANTINED))
 		return false;
 
+	/* Blocks freed from a compaction target go back to it, not to a cache. */
+	if (READ_ONCE(meta->on_list) & PISA_LIST_HOLD)
+		return false;
+
 	if (!(READ_ONCE(meta->on_list) & PISA_LIST_SPARSE))
 		return true;
 
@@ -317,6 +325,9 @@ static bool pisa_meta_can_recycle(struct pisa_meta *meta)
 	}
 
 	WRITE_ONCE(meta->drain, true);
+	/* Let scrub migration move out what the callers still hold on @meta. */
+	if (READ_ONCE(pisa_scrub_migrate))
+		pisa_schedule_scrub(pa->nid);
 	return false;
 }
 
mm/pisa-node.c +7 -3
index c013e384b1c7e..8d6fa9f36bdcf 100644
@@ -248,7 +248,7 @@ void pisa_schedule_scrub(int nid)
 {
 	struct pisa_node *node;
 
-	if (!READ_ONCE(pisa_scrub_max))
+	if (!READ_ONCE(pisa_scrub_max) && !READ_ONCE(pisa_scrub_migrate))
 		return;
 
 	node = &pisa_nodes[nid];
@@ -277,8 +277,12 @@ static void pisa_node_work_fn(struct work_struct *work)
 	if (pisa_enabled() && READ_ONCE(pisa_reservoir_max))
 		pisa_reservoir_refill_node(node, nid);
 
-	if (test_and_clear_bit(PISA_NODE_SCRUB, &node->flags) && pisa_scrub_node(nid))
-		pisa_schedule_scrub(nid);
+	if (test_and_clear_bit(PISA_NODE_SCRUB, &node->flags)) {
+		bool more = pisa_scrub_node(nid);
+
+		if (pisa_user_scrub_node(nid) || more)
+			pisa_schedule_scrub(nid);
+	}
 }
 
 /* Queue node @nid's work if its reservoir is below or above the target. */
mm/pisa-priv.h +8 -1
index b18d461198ac5..c7f4e30579070 100644
@@ -55,6 +55,7 @@ enum {
 	PISA_LIST_DIRTY		= BIT(3),	/* on @pa->partial_dirty */
 	PISA_LIST_MASK		= 0xf,
 	PISA_LIST_SPARSE	= BIT(4),	/* tail: list_move_tail() */
+	PISA_LIST_HOLD		= BIT(5),	/* parked on @pa->full by compaction */
 };
 
 /* Publish meta->flags into the pfn2slot array. */
@@ -133,10 +134,11 @@ static inline long pisa_alloc_held_pages(const struct pisa_alloc *pa)
 struct pisa_node {
 	unsigned long		next_alloc;	/* atomic alloc backoff jiffies */
 	struct pisa_alloc	*pa[2][PISA_MAX_ALLOC_ORDER + 1]; /* [0]=RW, [1]=RO */
-	struct pisa_alloc	*user_pa;	/* user page migration pa */
+	struct pisa_alloc	*user_pa[3];	/* user/page-cache allocators by dir */
 
 	spinlock_t		lock;		/* protects @pages and @nr_pages */
 	unsigned int		nr_pages;	/* entries in @pages */
+	unsigned int		scrub_dir;	/* round-robin user_pa scrub index */
 	struct list_head	pages;		/* reservoir */
 	unsigned long		flags;		/* PISA_NODE_* requests */
 	struct work_struct	work;		/* refill/trim/scrub, on this node */
@@ -212,6 +214,7 @@ struct pisa_alloc *pisa_alloc_ensure(struct pisa_alloc **pap, int nid,
 #define PISA_PCP_HIGH		64U	/* blocks cached per CPU at most */
 int pisa_enable_pcp(struct pisa_alloc *pa);
 void pisa_pcp_drain(struct pisa_alloc *pa);
+unsigned long pisa_pcp_cached(struct pisa_alloc *pa);
 bool pisa_place_meta(struct pisa_meta *meta);
 extern struct llist_head pisa_free_list;
 extern unsigned int pisa_idle_ms;
@@ -229,6 +232,9 @@ static inline struct page *pisa_alloc(struct pisa_alloc *pa, gfp_t gfp)
 }
 
 #define PISA_OLD_MS_MAX		100000U
+extern unsigned int pisa_target_usage_percent;
+extern unsigned int pisa_old_ms;
+extern unsigned int pisa_scrub_migrate;
 unsigned long pisa_shrink_list(spinlock_t *lock, struct list_head *list,
 			       unsigned int *nr, struct list_head *release_list,
 			       unsigned long nr_to_scan);
@@ -236,6 +242,7 @@ unsigned long pisa_shrink_list(spinlock_t *lock, struct list_head *list,
 #define PISA_SCRUB_RUN_NS	(50 * NSEC_PER_USEC)
 extern unsigned int pisa_scrub_max;
 bool pisa_scrub_node(int nid);
+bool pisa_user_scrub_node(int nid);
 
 /* pisa-node.c: per-NUMA-node PISA page reservoir and work item */
 extern unsigned int pisa_reservoir_max;
mm/pisa-user.c +478 -45

684 lines not on this page · raw message

mm/readahead.c +2 -1
index 6e5563290287e..82b03ac1161dd 100644
@@ -114,6 +114,7 @@
  */
 
 #include <linux/blk_plug.h>
+#include <linux/pisa-mm.h>
 #include <linux/kernel.h>
 #include <linux/dax.h>
 #include <linux/gfp.h>
@@ -197,7 +198,7 @@ static struct folio *ractl_alloc_folio(struct readahead_control *ractl,
 {
 	struct folio *folio;
 
-	folio = filemap_alloc_folio(gfp_mask, order, NULL);
+	folio = pisa_filemap_alloc_folio(gfp_mask, order, NULL, ractl->mapping);
 	if (folio && ractl->dropbehind)
 		__folio_set_dropbehind(folio);
 
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#82 lore raw

Re: [RFC PATCH v3 12/25] block, mm: Support PISA for disk I/O and scrub migration

Quoted 4 lines · Luigi Rizzo

Extend PISA user/page-cache allocators to support O_DIRECT and buffered disk I/O, gated per block/controller device through pisa_rx_bufs (read) and pisa_tx_bufs (write):

Quoted 8 lines

- Split per-node user_pa into DMA_BIDIRECTIONAL, DMA_TO_DEVICE, and DMA_FROM_DEVICE allocators, promoting pages to DMA_BIDIRECTIONAL if later accessed in the opposite direction.
- Upgrade pinned O_DIRECT user pages in bio_iov_iter_get_pages(), and allocate/promote order-0 page-cache folios for buffered I/O when PISA is enabled on the target block device.
- Add pisa.scrub_migrate to compact or demote lingering folios off old, sparse user_pa 2MB pages.

No, doing MM migrations in an (any) I/O path makes no sense at all.

Can we all please go back to actually thinking about problems instead of generating giants amounts of shit code without the slightest reflection.

Than you very much for your attention.

#83 lore raw

Re: [RFC PATCH v3 12/25] block, mm: Support PISA for disk I/O and scrub migration

In reply to Luigi Rizzo
Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [Medium] mm: unlocked folio_mapping() dereference without RCU in pisa_user_old_folio() - [Medium] mm…

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [Medium] mm: unlocked folio_mapping() dereference without RCU in pisa_user_old_folio()
- [Medium] mm: pisa_user_scrub_alloc() uses list_is_first() in reverse partial-list scan
- [Medium] mm: pisa_user_scrub_alloc() drops PISA_LIST_SPARSE when unparking target
--

commit 3b57a0418e67606042f9e55005bdffc210273bea
Author: Luigi Rizzo <[email protected]>

block, mm: Support PISA for disk I/O and scrub migration

This commit extends PISA user and page-cache allocators to support direct and buffered disk I/O by splitting per-node user allocators by DMA direction, adding page-cache and bio migration hooks, and adding background scrub migration for sparse PISA pages.

Quoted 4 lines
mm/pisa-user.c +0 -0
index 6c3efaee4ecda..5fb1ec7c45204 100644

[ ... ]

mm/pisa-user.c static void pisa_user_put_folio(struct folio *dst, unsigned long private) · line 258

Quoted 13 lines
mm/pisa-user.c +7 -1
@@ -144,17 +248,31 @@ static void pisa_user_put_folio(struct folio *dst, unsigned long private)
 /* new_folio_t for migration out of PISA memory: allocators never serve these. */
 static struct folio *pisa_user_old_folio(struct folio *src, unsigned long private)
 {
-	return __folio_alloc_node(GFP_HIGHUSER_MOVABLE | __GFP_NOWARN, 0, folio_nid(src));
+	struct address_space *mapping = folio_mapping(src);
+	gfp_t gfp = GFP_HIGHUSER_MOVABLE;
+
+	/* A file folio goes back to memory that its mapping allows. */
+	if (!folio_test_anon(src) && mapping)
+		gfp = mapping_gfp_constraint(mapping, gfp);
+	return __folio_alloc_node(gfp | __GFP_NOWARN, 0, folio_nid(src));
 }

[Severity: Medium]
Can mapping_gfp_constraint() read a freed struct address_space here?

migrate_folio_unmap() invokes get_new_folio() before locking src, and the scrub demotion path isolates file-backed folios without pinning their inode:

CPU0 (scrub work) CPU1
pisa_user_scrub_alloc()
...
migrate_folio_unmap()
pisa_user_old_folio(src)
mapping = folio_mapping(src)
truncate / evict()
filemap_remove_folio(src) /* RCU grace period frees inode */
mapping_gfp_constraint(mapping, gfp)
<-- use-after-free

Wrapping the folio_mapping(src) lookup and mapping_gfp_constraint() call in rcu_read_lock() / rcu_read_unlock(), as pisa_user_want_dir() does, would keep the inode alive across the read.

[ ... ]

Quoted 1 line
mm/pisa-user.c +0 -0
@@ -293,15 +432,307 @@ bool pisa_upgrade_user_pages(struct iov_iter *iter, struct page **pages,

[ ... ]

Quoted 6 lines
mm/pisa-user.c +6 -0
+	spin_lock_irqsave(&pa->lock, flags);
+	for (unsigned int i = 0; i < ARRAY_SIZE(lists) && !target; i++) {
+		list_for_each_entry_reverse(meta, lists[i], list) {
+			if (pisa_meta_avail(meta) < (bpp >> 1))
+				break;
+			/* Compaction needs a sparse page and another partial page to fill. */

mm/pisa-user.c bool pisa_upgrade_user_pages(struct iov_iter *iter, struct page **pages, · line 627

Quoted 10 lines
mm/pisa-user.c +10 -0
+			if (mode == 1 && (!(meta->on_list & PISA_LIST_SPARSE) ||
+					  (list_is_first(&meta->list, lists[i]) &&
+					   list_empty(lists[!i]))))
+				break;
+			if (time_after(jiffies, meta->alloc_jiffies + max_age)) {
+				target = meta;
+				break;
+			}
+		}
+	}

[Severity: Medium]
Should this check list_is_singular(lists[i]) instead of list_is_first(&meta->list, lists[i])?

When the reverse walk skips younger sparse entries near the tail of lists[i] (or entries whose alloc_jiffies was refreshed after an unmovable pass) and reaches the oldest entry at the head while lists[!i] is empty, list_is_first() triggers and aborts the scan even though the skipped tail entries in lists[i] are available to receive compacted folios.

Quoted 10 lines
mm/pisa-user.c +10 -0
+	if (target) {
+		/*
+		 * Compaction: park @target on @pa->full, so that the blocks
+		 * freed from it are neither cached nor handed out again while
+		 * its folios move to other pages of @pa.
+		 */
+		if (mode == 1) {
+			WRITE_ONCE(target->on_list, PISA_LIST_FULL | PISA_LIST_HOLD);
+			list_move(&target->list, &pa->full);
+		}

[ ... ]

mm/pisa-user.c bool pisa_upgrade_user_pages(struct iov_iter *iter, struct page **pages, · line 696

Quoted 11 lines
mm/pisa-user.c +11 -0
+	if (mode == 1) {
+		bool should_release;
+
+		/* Put @target back on the list that its free blocks call for. */
+		spin_lock_irqsave(&pa->lock, flags);
+		WRITE_ONCE(target->on_list, PISA_LIST_FULL);
+		should_release = pisa_place_meta(target);
+		spin_unlock_irqrestore(&pa->lock, flags);
+		if (should_release)
+			pisa_schedule_reclaim();
+	}

[Severity: Medium]
Does writing PISA_LIST_FULL to target->on_list drop PISA_LIST_SPARSE when target remains in the 50%-75% free hysteresis band?

In pisa_place_meta(), pages with nfree between 50% and 75% of bpp retain their sparse classification via meta->on_list & PISA_LIST_SPARSE. Because parking and unparking target overwrites target->on_list with PISA_LIST_FULL, a sparse page that finishes a compaction pass with fewer than 75% free blocks (for example, when some folios were busy or budget capped the batch) loses PISA_LIST_SPARSE and target->drain, and is moved to the dense head of the partial list where new allocations immediately refill it.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=12
#84 lore raw

RFC PATCH v3 13/25 net: Cache leaf PISA TX flags on struct net_device

In reply to Luigi Rizzo

The sysfs attributes pisa_tx_bufs and pisa_tx_skb_heads live on the physical DMA parent (dev->dev.parent), whereas a socket route (dst->dev) or skb->dev may point to an upper virtual net_device (bond, VLAN, ipvlan, etc.). Walking lower devices via netdev_walk_all_lower_dev_rcu() on every TX allocation would be too expensive.

Add dev->pisa_tx_flags_tstamp on struct net_device to cache the leaf device PISA TX flags and refresh them at most once every 256 jiffies via pisa_tx_flags_refresh(). Also add the net_pisa_tx_bufs_key static key and helpers (use_pisa_tx_bufs(), pisa_tx_bufs_gfp()) for subsequent TX buffer patches.

---
 drivers/base/core.c       |   6 ++-
 include/linux/device.h    |  11 ++++
 include/linux/netdevice.h |   4 ++
 include/net/pisa.h        |  81 +++++++++++++++++++++++++++++
 mm/pisa-kunit.c           |   3 +-
 net/core/Makefile         |   1 +
 net/core/pisa-net.c       | 104 ++++++++++++++++++++++++++++++++++++++
 7 files changed, 207 insertions(+), 3 deletions(-)
 create mode 100644 include/net/pisa.h
 create mode 100644 net/core/pisa-net.c
drivers/base/core.c +4 -2
index df93b6b6e125e..5f1291e644c5e 100644
@@ -2950,7 +2950,7 @@ static DEVICE_ATTR_RW(name)
 
 PISA_BOOL_ATTR(pisa_coherent);
 PISA_BOOL_ATTR(pisa_rx_bufs);
-PISA_BOOL_ATTR(pisa_tx_bufs);
+PISA_SET_ATTR(pisa_tx_bufs, net_pisa_tx_bufs_set);
 PISA_BOOL_ATTR(pisa_tx_skb_heads);
 PISA_BOOL_ATTR(pisa_tx_zerocopy);
 
@@ -3111,8 +3111,10 @@ static void device_remove_attrs(struct device *dev)
 	const struct class *class = dev->class;
 	const struct device_type *type = dev->type;
 
-	if (IS_ENABLED(CONFIG_PISA) && dev->dma_mask)
+	if (IS_ENABLED(CONFIG_PISA) && dev->dma_mask) {
 		device_remove_group(dev, &dev_attr_pisa_group);
+		net_pisa_tx_bufs_set(dev, false);
+	}
 
 	if (dev->physical_location) {
 		device_remove_group(dev, &dev_attr_physical_location_group);
include/linux/device.h +11 -0
index e705df38e49af..0d867d8255ba5 100644
@@ -817,6 +817,17 @@ struct device {
 	DECLARE_BITMAP(flags, DEV_FLAG_COUNT);
 };
 
+#if defined(CONFIG_NET) && defined(CONFIG_PISA)
+int net_pisa_tx_bufs_set(struct device *dev, bool val);
+#else
+/* Without CONFIG_NET the flag still gates block-device writes (see pisa_bdev_enabled()). */
+static inline int net_pisa_tx_bufs_set(struct device *dev, bool val)
+{
+	WRITE_ONCE(dev->pisa_tx_bufs, val);
+	return 0;
+}
+#endif
+
 #define __create_dev_flag_accessors(accessor_name, flag_name) \
 static inline bool dev_##accessor_name(const struct device *dev) \
 { \
include/linux/netdevice.h +4 -0
index 435be7880d7e5..f973faba4402c 100644
@@ -2161,6 +2161,7 @@ enum netdev_reg_state {
  *	@neighbours:	List heads pointing to this device's neighbours'
  *			dev_list, one per address-family.
  *	@hwprov: Tracks which PTP performs hardware packet time stamping.
+ *	@pisa_tx_flags_tstamp: Cached leaf pisa flags and timestamp.
  *
  *	FIXME: cleanup struct net_device such that network protocol info
  *	moves out.
@@ -2276,6 +2277,9 @@ struct net_device {
 	} adj_list;
 
 	/* Read-mostly cache-line for fast-path access */
+#ifdef CONFIG_PISA
+	u32			pisa_tx_flags_tstamp;
+#endif
 	xdp_features_t		xdp_features;
 	const struct xdp_metadata_ops *xdp_metadata_ops;
 	const struct xsk_tx_metadata_ops *xsk_tx_metadata_ops;
include/net/pisa.h new file +81 -0

81 lines not on this page · raw message

mm/pisa-kunit.c +2 -1
index 4effbc8610079..d7670c76e98c5 100644
@@ -578,7 +578,8 @@ static void test_dev_pisa_attrs(struct kunit *test)
 	kunit_check_pisa_attr(test, dev, "pisa_coherent", &dev->pisa_coherent);
 	kunit_check_pisa_attr(test, dev, "pisa_rx_bufs", &dev->pisa_rx_bufs);
 	kunit_check_pisa_attr(test, dev, "pisa_tx_zerocopy", &dev->pisa_tx_zerocopy);
-	kunit_check_pisa_attr(test, dev, "pisa_tx_bufs", &dev->pisa_tx_bufs);
+	if (IS_ENABLED(CONFIG_NET))
+		kunit_check_pisa_attr(test, dev, "pisa_tx_bufs", &dev->pisa_tx_bufs);
 	kunit_check_pisa_attr(test, dev, "pisa_tx_skb_heads", &dev->pisa_tx_skb_heads);
 	device_unregister(dev);
 }
net/core/Makefile +1 -0
index c20e520358b8e..3c84358d6b0c0 100644
@@ -52,3 +52,4 @@ obj-$(CONFIG_NET_TEST) += net_test.o
 obj-$(CONFIG_NET_DEVMEM) += devmem.o
 obj-$(CONFIG_DEBUG_NET) += lock_debug.o
 obj-$(CONFIG_FAIL_SKB_REALLOC) += skb_fault_injection.o
+obj-$(CONFIG_PISA) += pisa-net.o
net/core/pisa-net.c new file +104 -0

104 lines not on this page · raw message

Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#85 lore raw

RFC PATCH v3 14/25 net: Use per-node PISA allocators for skb_page_frag_refill()

In reply to Luigi Rizzo

Transmit socket buffers use memory coming from skb_page_frag_refill(). Sockets whose leaf device has enabled pisa_tx_bufs should use PISA memory.

Add a dedicated per-task page_frag, current->task_frag_pisa, populated with read-only PISA blocks via __GFP_PISA, and select it on TX when the socket's (or cork's) route goes out in the clear through a PISA-enabled device.

Special paths that hold plaintext before encryption (IPsec, kTLS) or do not use a DMA device keep using regular pages; ESP output uses pisa_tx_bufs_gfp() to opt in when the egress device has pisa_tx_bufs enabled.

---
 include/linux/pisa.h  | 15 +++++++++++++++
 include/linux/sched.h |  4 ++++
 include/net/pisa.h    | 33 +++++++++++++++++++++++++++++++++
 kernel/exit.c         |  2 ++
 kernel/fork.c         |  2 ++
 net/core/sock.c       | 10 ++++++++++
 net/ipv4/esp4.c       |  7 +++++--
 net/ipv4/ip_output.c  | 12 ++++++++----
 net/ipv4/tcp.c        |  3 ++-
 net/ipv6/esp6.c       |  7 +++++--
 net/ipv6/ip6_output.c | 12 ++++++++----
 11 files changed, 94 insertions(+), 13 deletions(-)
include/linux/pisa.h +15 -0
index 6d184e393e297..84692852299f1 100644
@@ -202,6 +202,18 @@ static inline bool pisa_page_can_recycle(const struct page *page)
 	       __pisa_page_can_recycle(page);
 }
 
+/* Hooks for dup_task_struct() and do_exit() (guarded by @pisa_key on release). */
+static inline void pisa_task_frag_init(struct task_struct *tsk)
+{
+	tsk->task_frag_pisa.page = NULL;
+}
+
+static inline void pisa_task_frag_release(struct task_struct *tsk)
+{
+	if (pisa_enabled() && tsk->task_frag_pisa.page)
+		put_page(tsk->task_frag_pisa.page);
+}
+
 #else /* !CONFIG_PISA */
 
 static inline int pisa_meta_init(void) { return -EOPNOTSUPP; }
@@ -240,6 +252,9 @@ static inline bool pisa_page_can_recycle(const struct page *page)
 	return true;
 }
 
+static inline void pisa_task_frag_init(struct task_struct *tsk) {}
+static inline void pisa_task_frag_release(struct task_struct *tsk) {}
+
 static inline bool pisa_upgrade_user_pages(struct iov_iter *iter,
 					   struct page **pages, size_t size,
 					   size_t offset,
include/linux/sched.h +4 -0
index e4f6323d78555..a8edeeb2661f4 100644
@@ -1455,6 +1455,10 @@ struct task_struct {
 	struct pipe_inode_info		*splice_pipe;
 
 	struct page_frag		task_frag;
+#ifdef CONFIG_PISA
+	/* TX frag that may hold PISA pages, see sk_page_frag_dst(). */
+	struct page_frag		task_frag_pisa;
+#endif
 
 #ifdef CONFIG_ARCH_HAS_LAZY_MMU_MODE
 	struct lazy_mmu_state		lazy_mmu_state;
include/net/pisa.h +33 -0
index 1f95e67e99bf8..8e23d8b01e73d 100644
@@ -4,6 +4,7 @@
 #define _NET_PISA_H
 
 #include <linux/pisa.h>
+#include <linux/tcp.h>
 #include <net/sock.h>
 
 /*
@@ -72,10 +73,42 @@ static inline gfp_t pisa_tx_bufs_gfp(const struct sk_buff *skb)
 	       __pisa_tx_gfp(skb_dst(skb), PISA_TX_FLAG_BUFS | PISA_TX_XFRM_OK) : 0;
 }
 
+/* Hook for skb_page_frag_refill() and __ip*_append_data() (@net_pisa_tx_bufs_key). */
+static inline bool is_pisa_pfrag(const struct page_frag *pfrag)
+{
+	return static_branch_unlikely(&net_pisa_tx_bufs_key) &&
+	       pfrag == &current->task_frag_pisa;
+}
+
+/* Hook for task/socket TX page_frag selection (@net_pisa_tx_bufs_key). */
+static inline struct page_frag *task_page_frag(const struct dst_entry *dst)
+{
+	return use_pisa_tx_bufs(dst) ? &current->task_frag_pisa : &current->task_frag;
+}
+
+static inline struct page_frag *sk_page_frag_dst(struct sock *sk,
+						 const struct dst_entry *dst)
+{
+	return static_branch_unlikely(&net_pisa_tx_bufs_key) &&
+	       sk->sk_use_task_frag ? task_page_frag(dst) : sk_page_frag(sk);
+}
+
 #else /* !CONFIG_PISA */
 
 static inline bool use_pisa_tx_bufs(const struct dst_entry *dst) { return false; }
 static inline gfp_t pisa_tx_bufs_gfp(const struct sk_buff *skb) { return 0; }
+static inline bool is_pisa_pfrag(const struct page_frag *pfrag) { return false; }
+
+static inline struct page_frag *task_page_frag(const struct dst_entry *dst)
+{
+	return &current->task_frag;
+}
+
+static inline struct page_frag *sk_page_frag_dst(struct sock *sk,
+						 const struct dst_entry *dst)
+{
+	return sk_page_frag(sk);
+}
 
 #endif /* CONFIG_PISA */
 #endif /* _NET_PISA_H */
kernel/exit.c +2 -0
index d5e7bc2af804a..ac7ca1fb180c3 100644
@@ -6,6 +6,7 @@
  */
 
 #include <linux/mm.h>
+#include <linux/pisa.h>
 #include <linux/slab.h>
 #include <linux/sched/autogroup.h>
 #include <linux/sched/mm.h>
@@ -1009,6 +1010,7 @@ void __noreturn do_exit(long code)
 
 	if (tsk->task_frag.page)
 		put_page(tsk->task_frag.page);
+	pisa_task_frag_release(tsk);
 
 	exit_task_stack_account(tsk);
 
kernel/fork.c +2 -0
index 5efceb8d58a78..d235d7ab04687 100644
@@ -44,6 +44,7 @@
 #include <linux/mmu_notifier.h>
 #include <linux/fs.h>
 #include <linux/mm.h>
+#include <linux/pisa.h>
 #include <linux/mm_inline.h>
 #include <linux/memblock.h>
 #include <linux/nsproxy.h>
@@ -982,6 +983,7 @@ static struct task_struct *dup_task_struct(struct task_struct *orig, int node)
 #endif
 	tsk->splice_pipe = NULL;
 	tsk->task_frag.page = NULL;
+	pisa_task_frag_init(tsk);
 	tsk->wake_q.next = NULL;
 	tsk->worker_private = NULL;
 
net/core/sock.c +10 -0
index ad414878dc5ba..56dea49baaec2 100644
@@ -115,6 +115,7 @@
 #include <linux/memcontrol.h>
 #include <linux/prefetch.h>
 #include <linux/compat.h>
+#include <linux/pisa.h>
 #include <linux/mroute.h>
 #include <linux/mroute6.h>
 #include <linux/icmpv6.h>
@@ -147,6 +148,7 @@
 #include <net/tcp.h>
 #include <net/busy_poll.h>
 #include <net/phonet/phonet.h>
+#include <net/pisa.h>
 
 #include <linux/ethtool.h>
 
@@ -3257,13 +3259,21 @@ DEFINE_STATIC_KEY_FALSE(net_high_order_alloc_disable_key);
  */
 bool skb_page_frag_refill(unsigned int sz, struct page_frag *pfrag, gfp_t gfp)
 {
+	/* PISA pages only go into current->task_frag_pisa, see sk_page_frag_dst(). */
+	if (is_pisa_pfrag(pfrag))
+		gfp |= __GFP_PISA;
+
 	if (pfrag->page) {
 		if (page_ref_count(pfrag->page) == 1) {
+			if (!!(gfp & __GFP_PISA) != is_pisa_page(pfrag->page) ||
+			    ((gfp & __GFP_PISA) && !pisa_page_can_recycle(pfrag->page)))
+				goto drop_page;
 			pfrag->offset = 0;
 			return true;
 		}
 		if (pfrag->offset + sz <= pfrag->size)
 			return true;
+drop_page:
 		put_page(pfrag->page);
 	}
 
net/ipv4/esp4.c +5 -2
index ae701561d9f12..8ed713772e4ee 100644
@@ -20,6 +20,7 @@
 #include <net/udp.h>
 #include <net/tcp.h>
 #include <net/espintcp.h>
+#include <net/pisa.h>
 #include <linux/skbuff_ref.h>
 
 #include <linux/highmem.h>
@@ -451,7 +452,8 @@ int esp_output_head(struct xfrm_state *x, struct sk_buff *skb, struct esp_info *
 
 			spin_lock_bh(&x->lock);
 
-			if (unlikely(!skb_page_frag_refill(allocsize, pfrag, GFP_ATOMIC))) {
+			if (unlikely(!skb_page_frag_refill(allocsize, pfrag,
+							   GFP_ATOMIC | pisa_tx_bufs_gfp(skb)))) {
 				spin_unlock_bh(&x->lock);
 				goto cow;
 			}
@@ -560,7 +562,8 @@ int esp_output_tail(struct xfrm_state *x, struct sk_buff *skb, struct esp_info *
 		allocsize = ALIGN(skb->data_len, L1_CACHE_BYTES);
 
 		spin_lock_bh(&x->lock);
-		if (unlikely(!skb_page_frag_refill(allocsize, pfrag, GFP_ATOMIC))) {
+		if (unlikely(!skb_page_frag_refill(allocsize, pfrag,
+						   GFP_ATOMIC | pisa_tx_bufs_gfp(skb)))) {
 			spin_unlock_bh(&x->lock);
 			goto error_free;
 		}
net/ipv4/ip_output.c +8 -4
index d42d776af273e..50b8c92c3cd5e 100644
@@ -71,6 +71,7 @@
 #include <net/xfrm.h>
 #include <linux/skbuff.h>
 #include <net/sock.h>
+#include <net/pisa.h>
 #include <net/arp.h>
 #include <net/icmp.h>
 #include <net/checksum.h>
@@ -986,7 +987,10 @@ static int __ip_append_data(struct sock *sk,
 
 	exthdrlen = !skb ? rt->dst.header_len : 0;
 	mtu = cork->gso_size ? IP_MAX_MTU : cork->fragsize;
-	paged = !!cork->gso_size;
+	paged = !!cork->gso_size ||
+		(getfrag == ip_generic_getfrag &&
+		 (rt->dst.dev->features & NETIF_F_SG) &&
+		 is_pisa_pfrag(pfrag));
 
 	hh_len = LL_RESERVED_SPACE(rt->dst.dev);
 
@@ -1383,8 +1387,8 @@ int ip_append_data(struct sock *sk, struct flowi4 *fl4,
 	}
 
 	return __ip_append_data(sk, fl4, &sk->sk_write_queue, &inet->cork.base,
-				sk_page_frag(sk), getfrag,
-				from, length, transhdrlen, flags);
+				sk_page_frag_dst(sk, inet->cork.base.dst),
+				getfrag, from, length, transhdrlen, flags);
 }
 
 static void ip_cork_release(struct inet_cork *cork)
@@ -1592,7 +1596,7 @@ struct sk_buff *ip_make_skb(struct sock *sk,
 		return ERR_PTR(err);
 
 	err = __ip_append_data(sk, fl4, &queue, cork,
-			       &current->task_frag, getfrag,
+			       sk_page_frag_dst(sk, cork->dst), getfrag,
 			       from, length, transhdrlen, flags);
 	if (err) {
 		__ip_flush_pending_frames(sk, &queue, cork);
net/ipv4/tcp.c +2 -1
index 832b25ddd3c2e..3c3edc48705d7 100644
@@ -273,6 +273,7 @@
 #include <net/inet_common.h>
 #include <net/inet_ecn.h>
 #include <net/tcp.h>
+#include <net/pisa.h>
 #include <net/tcp_ecn.h>
 #include <net/mptcp.h>
 #include <net/proto_memory.h>
@@ -1295,7 +1296,7 @@ int tcp_sendmsg_locked(struct sock *sk, struct msghdr *msg, size_t size)
 		if (zc == 0) {
 			bool merge = true;
 			int i = skb_shinfo(skb)->nr_frags;
-			struct page_frag *pfrag = sk_page_frag(sk);
+			struct page_frag *pfrag = sk_page_frag_dst(sk, __sk_dst_get(sk));
 
 			if (!sk_page_frag_refill(sk, pfrag))
 				goto wait_for_space;
net/ipv6/esp6.c +5 -2
index d654f0f442388..98ed9120ae7b4 100644
@@ -36,6 +36,7 @@
 #include <net/tcp.h>
 #include <net/espintcp.h>
 #include <net/inet6_hashtables.h>
+#include <net/pisa.h>
 #include <linux/skbuff_ref.h>
 
 #include <linux/highmem.h>
@@ -481,7 +482,8 @@ int esp6_output_head(struct xfrm_state *x, struct sk_buff *skb, struct esp_info
 
 			spin_lock_bh(&x->lock);
 
-			if (unlikely(!skb_page_frag_refill(allocsize, pfrag, GFP_ATOMIC))) {
+			if (unlikely(!skb_page_frag_refill(allocsize, pfrag,
+							   GFP_ATOMIC | pisa_tx_bufs_gfp(skb)))) {
 				spin_unlock_bh(&x->lock);
 				goto cow;
 			}
@@ -592,7 +594,8 @@ int esp6_output_tail(struct xfrm_state *x, struct sk_buff *skb, struct esp_info
 		allocsize = ALIGN(skb->data_len, L1_CACHE_BYTES);
 
 		spin_lock_bh(&x->lock);
-		if (unlikely(!skb_page_frag_refill(allocsize, pfrag, GFP_ATOMIC))) {
+		if (unlikely(!skb_page_frag_refill(allocsize, pfrag,
+						   GFP_ATOMIC | pisa_tx_bufs_gfp(skb)))) {
 			spin_unlock_bh(&x->lock);
 			goto error_free;
 		}
net/ipv6/ip6_output.c +8 -4
index cb648c8394310..8f6f0bed15499 100644
@@ -40,6 +40,7 @@
 #include <linux/netfilter_ipv6.h>
 
 #include <net/sock.h>
+#include <net/pisa.h>
 #include <net/snmp.h>
 
 #include <net/gso.h>
@@ -1489,7 +1490,10 @@ static int __ip6_append_data(struct sock *sk,
 		dst_exthdrlen = rt->dst.header_len - rt->rt6i_nfheader_len;
 	}
 
-	paged = !!cork->gso_size;
+	paged = !!cork->gso_size ||
+		(getfrag == ip_generic_getfrag &&
+		 (rt->dst.dev->features & NETIF_F_SG) &&
+		 is_pisa_pfrag(pfrag));
 	mtu = cork->gso_size ? IP6_MAX_MTU : cork->fragsize;
 	orig_mtu = mtu;
 
@@ -1892,8 +1896,8 @@ int ip6_append_data(struct sock *sk,
 	}
 
 	return __ip6_append_data(sk, &sk->sk_write_queue, &inet->cork,
-				 sk_page_frag(sk), getfrag,
-				 from, length, transhdrlen, flags);
+				 sk_page_frag_dst(sk, inet->cork.base.dst),
+				 getfrag, from, length, transhdrlen, flags);
 }
 EXPORT_SYMBOL_GPL(ip6_append_data);
 
@@ -2095,7 +2099,7 @@ struct sk_buff *ip6_make_skb(struct sock *sk,
 	}
 
 	err = __ip6_append_data(sk, &queue, cork,
-				&current->task_frag, getfrag, from,
+				sk_page_frag_dst(sk, cork->base.dst), getfrag, from,
 				length + exthdrlen, transhdrlen + exthdrlen,
 				flags);
 	if (err) {
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#86 lore raw

RFC PATCH v3 15/25 net: Use PISA for page_pool memory

In reply to Luigi Rizzo

When a page_pool performs DMA mapping (PP_FLAG_DMA_MAP) on a device with pisa_rx_bufs enabled, pass __GFP_PISA_RW to use PISA memory.

---
 net/core/page_pool.c | 3 +++
 1 file changed, 3 insertions(+)
net/core/page_pool.c +3 -0
index d7c88c0b67e53..91cae5ba78373 100644
@@ -16,6 +16,7 @@
 #include <net/page_pool/helpers.h>
 #include <net/page_pool/memory_provider.h>
 #include <net/xdp.h>
+#include <linux/pisa.h>
 
 #include <linux/dma-direction.h>
 #include <linux/dma-mapping.h>
@@ -622,6 +623,8 @@ static noinline netmem_ref __page_pool_alloc_netmems_slow(struct page_pool *pool
 	 */
 	if ((gfp & GFP_ATOMIC) == GFP_ATOMIC)
 		gfp |= __GFP_NOWARN;
+	if (dma_map)
+		gfp |= pisa_rx_gfp(pool->p.dev);
 
 	/* Don't support bulk alloc for high-order pages */
 	if (unlikely(pp_order))
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#87 lore raw

RFC PATCH v3 16/25 mm/slub: Add SLAB_CACHE_PISA_RO for PISA-backed slab caches

In reply to Luigi Rizzo

skb heads are provided by a slab allocator that is fed by alloc_pages().

Add SLAB_CACHE_PISA_RO so that a slab cache can back its slabs with zeroed, read-only PISA folios (__GFP_PISA | __GFP_ZERO) via pisa_alloc_folio().
Slabs are still released with free_frozen_pages(), so pages from PISA return to their allocator via __free_pages_prepare(). Caches with SLAB_CACHE_PISA_RO skip KFENCE and are never merged.

Existing caches are unaffected.

---
 include/linux/pisa-mm.h | 20 ++++++++++++++
 include/linux/slab.h    | 10 +++++++
 mm/pisa-alloc.c         | 60 +++++++++++++++++++++++++++++++++++++++++
 mm/pisa-kunit.c         | 22 +++++++++++++++
 mm/pisa-priv.h          |  1 +
 mm/slab.h               |  3 ++-
 mm/slab_common.c        |  2 +-
 mm/slub.c               | 23 ++++++++++++++--
 8 files changed, 137 insertions(+), 4 deletions(-)
include/linux/pisa-mm.h +20 -0
index 8caa2afded6ff..fd5e7234e9423 100644
@@ -14,6 +14,8 @@ struct folio_batch;
 unsigned long __pisa_alloc_pages_bulk(gfp_t gfp, unsigned int order,
 				      int preferred_nid, int nr_pages,
 				      struct page **page_array, bool frozen);
+struct folio *__pisa_alloc_folio(gfp_t gfp, unsigned int order, int nid);
+int pisa_slab_cache_init(unsigned int order);
 bool __pisa_free_page(struct page *page, unsigned int order);
 bool __pisa_bio_migrate_pages(struct bio *bio, struct iov_iter *iter,
 			      enum dma_data_direction dir);
@@ -63,6 +65,13 @@ pisa_alloc_pages(gfp_t *gfp, unsigned int order, int preferred_nid,
 	return page;
 }
 
+/* Hook for SLAB_CACHE_PISA_RO in alloc_slab_page() (guarded by @pisa_key). */
+static inline struct folio *
+pisa_alloc_folio(gfp_t gfp, unsigned int order, int nid)
+{
+	return pisa_enabled() ? __pisa_alloc_folio(gfp, order, nid) : NULL;
+}
+
 /* Hook for __free_pages_prepare() (guarded by @pisa_key). */
 static inline bool pisa_free_page(struct page *page, unsigned int order)
 {
@@ -129,6 +138,17 @@ pisa_alloc_pages(gfp_t *gfp, unsigned int order, int preferred_nid,
 	return NULL;
 }
 
+static inline struct folio *
+pisa_alloc_folio(gfp_t gfp, unsigned int order, int nid)
+{
+	return NULL;
+}
+
+static inline int pisa_slab_cache_init(unsigned int order)
+{
+	return 0;
+}
+
 static inline bool pisa_free_page(struct page *page, unsigned int order)
 {
 	return false;
include/linux/slab.h +10 -0
index cda126def67af..4b6205540279d 100644
@@ -66,6 +66,9 @@ enum _slab_flag_bits {
 #endif
 #endif
 	_SLAB_NO_SHEAVES,
+#ifdef CONFIG_PISA
+	_SLAB_CACHE_PISA_RO,
+#endif
 	_SLAB_FLAGS_LAST_BIT
 };
 
@@ -260,6 +263,13 @@ enum _slab_flag_bits {
 #define SLAB_OBJ_EXT_IN_OBJ	__SLAB_FLAG_UNUSED
 #endif
 
+/* Back slabs with zeroed read-only PISA folios (__GFP_PISA | __GFP_ZERO) */
+#ifdef CONFIG_PISA
+#define SLAB_CACHE_PISA_RO	__SLAB_FLAG_BIT(_SLAB_CACHE_PISA_RO)
+#else
+#define SLAB_CACHE_PISA_RO	__SLAB_FLAG_UNUSED
+#endif
+
 /*
  * ZERO_SIZE_PTR will be returned for zero sized kmalloc requests.
  *
mm/pisa-alloc.c +60 -0

72 lines not on this page · raw message

mm/pisa-kunit.c +22 -0
index d7670c76e98c5..ec7af4313915a 100644
@@ -13,6 +13,7 @@
 #include <linux/mm.h>
 #include <linux/shrinker.h>
 #include <linux/skbuff.h>
+#include <linux/slab.h>
 #include <linux/swiotlb.h>
 #include <net/sock.h>
 
@@ -716,6 +717,26 @@ static void test_reservoir_and_scrubber(struct kunit *test)
 	WRITE_ONCE(pisa_scrub_max, old_scrub);
 }
 
+static void test_slub_page_alloc(struct kunit *test)
+{
+	struct kmem_cache *s;
+	void *obj;
+
+	KUNIT_ASSERT_EQ(test, pisa_meta_init(), 0);
+	s = kmem_cache_create("pisa_kunit_slab", 1024, NULL,
+			      SLAB_NO_MERGE | SLAB_CACHE_PISA_RO);
+	KUNIT_ASSERT_NOT_NULL(test, s);
+
+	obj = kmem_cache_alloc(s, GFP_KERNEL);
+	KUNIT_EXPECT_NOT_NULL(test, obj);
+	if (obj) {
+		KUNIT_EXPECT_NOT_NULL(test, pisa_virt_to_page(obj));
+		kmem_cache_free(s, obj);
+	}
+
+	kmem_cache_destroy(s);
+}
+
 static struct kunit_case pisa_meta_test_cases[] = {
 	KUNIT_CASE(test_meta_init_and_roundtrip),
 	KUNIT_CASE(test_meta_invalid_phys),
@@ -731,6 +752,7 @@ static struct kunit_case pisa_meta_test_cases[] = {
 	KUNIT_CASE(test_pcp_cache),
 	KUNIT_CASE(test_gfp_pisa),
 	KUNIT_CASE(test_reservoir_and_scrubber),
+	KUNIT_CASE(test_slub_page_alloc),
 	{}
 };
 
mm/pisa-priv.h +1 -0
index c7f4e30579070..08bf1b64bcf2c 100644
@@ -134,6 +134,7 @@ static inline long pisa_alloc_held_pages(const struct pisa_alloc *pa)
 struct pisa_node {
 	unsigned long		next_alloc;	/* atomic alloc backoff jiffies */
 	struct pisa_alloc	*pa[2][PISA_MAX_ALLOC_ORDER + 1]; /* [0]=RW, [1]=RO */
+	struct pisa_alloc	*slab_pa[PISA_MAX_ALLOC_ORDER + 1]; /* SLAB_CACHE_PISA_RO */
 	struct pisa_alloc	*user_pa[3];	/* user/page-cache allocators by dir */
 
 	spinlock_t		lock;		/* protects @pages and @nr_pages */
mm/slab.h +2 -1
index e94ac63d10dc0..53620e40b216b 100644
@@ -473,7 +473,8 @@ void flush_rcu_sheaves_on_cache(struct kmem_cache *s);
 			 SLAB_TYPESAFE_BY_RCU | SLAB_DEBUG_OBJECTS | \
 			 SLAB_NOLEAKTRACE | SLAB_RECLAIM_ACCOUNT | \
 			 SLAB_TEMPORARY | SLAB_ACCOUNT | \
-			 SLAB_NO_USER_FLAGS | SLAB_KMALLOC | SLAB_NO_MERGE)
+			 SLAB_NO_USER_FLAGS | SLAB_KMALLOC | SLAB_NO_MERGE | \
+			 SLAB_CACHE_PISA_RO)
 
 #define SLAB_DEBUG_FLAGS (SLAB_RED_ZONE | SLAB_POISON | SLAB_STORE_USER | \
 			  SLAB_TRACE | SLAB_CONSISTENCY_CHECKS)
mm/slab_common.c +1 -1
index 2befd24b4d099..5dae3aa524221 100644
@@ -49,7 +49,7 @@ struct kmem_cache *kmem_cache;
  */
 #define SLAB_NEVER_MERGE (SLAB_DEBUG_FLAGS | SLAB_TYPESAFE_BY_RCU | \
 		SLAB_NOLEAKTRACE | SLAB_FAILSLAB | SLAB_NO_MERGE | \
-		SLAB_OBJ_EXT_IN_OBJ)
+		SLAB_OBJ_EXT_IN_OBJ | SLAB_CACHE_PISA_RO)
 
 #define SLAB_MERGE_SAME (SLAB_RECLAIM_ACCOUNT | SLAB_CACHE_DMA | \
 			 SLAB_CACHE_DMA32 | SLAB_ACCOUNT | SLAB_MAY_ACCOUNT)
mm/slub.c +21 -2
index cd671b9347191..0380869fb3301 100644
@@ -46,6 +46,7 @@
 #include <linux/prandom.h>
 #include <kunit/test.h>
 #include <kunit/test-bug.h>
+#include <linux/pisa-mm.h>
 #include <linux/sort.h>
 #include <linux/irq_work.h>
 #include <linux/kprobes.h>
@@ -2112,7 +2113,8 @@ static inline void dec_slabs_node(struct kmem_cache *s, int node,
  */
 #define OBJCGS_CLEAR_MASK	(__GFP_DMA | __GFP_RECLAIMABLE | \
 				__GFP_ACCOUNT | __GFP_NOFAIL | \
-				__GFP_THISNODE | __GFP_COMP)
+				__GFP_THISNODE | __GFP_COMP | \
+				__GFP_PISA_RW)
 
 #ifdef CONFIG_SLAB_OBJ_EXT
 
@@ -3378,6 +3380,8 @@ static inline struct slab *alloc_slab_page(gfp_t flags, int node,
 	if (unlikely(!allow_spin))
 		page = alloc_frozen_pages_nolock(0/* __GFP_COMP is implied */,
 								  node, order);
+	else if (unlikely(flags & __GFP_PISA))
+		page = (struct page *)pisa_alloc_folio(flags, order, node);
 	else if (node == NUMA_NO_NODE)
 		page = alloc_frozen_pages(flags, order);
 	else
@@ -3484,7 +3488,7 @@ static struct slab *allocate_slab(struct kmem_cache *s, gfp_t flags,
 	gfp_t alloc_gfp;
 	void *start;
 
-	flags &= gfp_allowed_mask;
+	flags &= gfp_allowed_mask & ~__GFP_PISA_RW;
 
 	flags |= s->allocflags;
 
@@ -3495,9 +3499,13 @@ static struct slab *allocate_slab(struct kmem_cache *s, gfp_t flags,
 	alloc_gfp = (flags | __GFP_NOWARN | __GFP_NORETRY) & ~__GFP_NOFAIL;
 	if ((alloc_gfp & __GFP_DIRECT_RECLAIM) && oo_order(oo) > oo_order(s->min))
 		alloc_gfp = (alloc_gfp | __GFP_NOMEMALLOC) & ~__GFP_RECLAIM;
+	if (unlikely(s->flags & SLAB_CACHE_PISA_RO))
+		alloc_gfp = (flags | __GFP_NOWARN) & ~__GFP_NOFAIL;
 
 	slab = alloc_slab_page(alloc_gfp, node, oo, allow_spin);
 	if (unlikely(!slab)) {
+		if (s->flags & SLAB_CACHE_PISA_RO)
+			return NULL;
 		oo = s->min;
 		alloc_gfp = flags;
 		/*
@@ -8182,6 +8190,11 @@ static int calculate_sizes(struct kmem_cache_args *args, struct kmem_cache *s)
 	if (s->flags & SLAB_RECLAIM_ACCOUNT)
 		s->allocflags |= __GFP_RECLAIMABLE;
 
+	if (s->flags & SLAB_CACHE_PISA_RO) {
+		s->flags |= SLAB_SKIP_KFENCE;
+		s->allocflags |= __GFP_PISA | __GFP_ZERO;
+	}
+
 	/*
 	 * For kmalloc caches we enable sheaves later by
 	 * bootstrap_kmalloc_sheaves() to avoid recursion.
@@ -8914,6 +8927,12 @@ int do_kmem_cache_create(struct kmem_cache *s, const char *name,
 	if (err)
 		goto out;
 
+	if (s->flags & SLAB_CACHE_PISA_RO) {
+		err = pisa_slab_cache_init(oo_order(s->oo));
+		if (err)
+			goto out;
+	}
+
 	err = 0;
 
 	/* Mutex is not taken during early boot */
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#88 lore raw

Re: [RFC PATCH v3 16/25] mm/slub: Add SLAB_CACHE_PISA_RO for PISA-backed slab caches

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] mm/pisa: __pisa_alloc_folio() pollutes slab_pa on __GFP_THISNODE --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] mm/pisa: __pisa_alloc_folio() pollutes slab_pa on __GFP_THISNODE
--

commit 1f383ac0c30c2d9cdbc7439034c54bc1d3d3fce6
Author: Luigi Rizzo <[email protected]>

mm/slub: Add SLAB_CACHE_PISA_RO for PISA-backed slab caches

This commit introduces the SLAB_CACHE_PISA_RO slab flag to back slab caches with zeroed, read-only PISA folios via pisa_alloc_folio().

Quoted 4 lines
mm/pisa-alloc.c +0 -0
index 8c4c0f1f1cf50..4fc3b4d29de67 100644

[ ... ]

Quoted 1 line
mm/pisa-alloc.c +0 -0
@@ -710,6 +712,64 @@ unsigned long __pisa_alloc_pages_bulk(gfp_t gfp, unsigned int order,

[ ... ]

Quoted 19 lines
mm/pisa-alloc.c +19 -0
+/* Allocate a zeroed read-only PISA folio for SLAB_CACHE_PISA_RO. */
+struct folio *__pisa_alloc_folio(gfp_t gfp, unsigned int order, int nid)
+{
+	int target_nid = pisa_sanitize_nid(nid);
+	struct page *page = NULL;
+	struct pisa_alloc *pa;
+
+	if (order > PISA_MAX_ALLOC_ORDER)
+		return NULL;
+	/* Pairs with smp_store_release() in pisa_alloc_ensure(). */
+	pa = smp_load_acquire(&pisa_nodes[target_nid].slab_pa[order]);
+	if (unlikely(!pa)) {
+		gfp_t ctx = current_gfp_context(gfp);
+
+		/* Only for a node that got memory after pisa_slab_cache_init(). */
+		if (!gfpflags_allow_blocking(ctx) ||
+		    (ctx & (__GFP_FS | __GFP_IO)) != (__GFP_FS | __GFP_IO))
+			return NULL;
+		pa = pisa_slab_pa_ensure(target_nid, order);

mm/pisa-alloc.c unsigned long __pisa_alloc_pages_bulk(gfp_t gfp, unsigned int order, · line 771

Quoted 10 lines
mm/pisa-alloc.c +10 -0
+	}
+	pisa_alloc_bulk(pa, gfp & ~__GFP_THISNODE, 1, &page, true);
+	if (page && (gfp & __GFP_THISNODE) && nid != NUMA_NO_NODE &&
+	    page_to_nid(page) != nid) {
+		/* @page is frozen (refcount 0): __free_pages() would underflow it. */
+		free_frozen_pages(page, order);
+		return NULL;
+	}
+	return page ? page_folio(page) : NULL;
+}

[Severity: Medium]
Can stripping __GFP_THISNODE here attach a remote-node PISA page to pisa_nodes[target_nid].slab_pa[order]?

In ___slab_alloc(), SLUB passes GFP_NOWAIT | __GFP_NOWARN | __GFP_THISNODE on its first try_thisnode pass when node != NUMA_NO_NODE. When slab_pa and target_nid's reservoir are empty (or when nid is a memoryless node redirected by pisa_sanitize_nid()), __pisa_page_alloc() calls alloc_pages_node(nid, gfp, PISA_ORDER) without __GFP_THISNODE, which can fall back to a remote node and bind that remote PISA page's pisa_meta to pisa_nodes[target_nid].slab_pa[order].

When page_to_nid(page) != nid then rejects the block, free_frozen_pages() routes through pisa_free_page() -> __pisa_free_page() and recycles the remote block back into pisa_nodes[target_nid].slab_pa[order] rather than freeing the underlying page. Later __GFP_THISNODE allocations on that node will then repeatedly pop blocks from the remote PISA page on slab_pa, dirty them on free, and return NULL even after local PISA pages become available in the reservoir.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=16
#89 lore raw

RFC PATCH v3 17/25 net: Allocate small skb heads from PISA

In reply to Luigi Rizzo

The linear part of most transmitted skbs is a small head from the skbuff_small_head cache. To avoid per-packet IOMMU map/unmap operations or bounce-buffer copies for headers, allow backing small TX skb heads with PISA memory.

When per-device pisa_tx_skb_heads is enabled, create a parallel skbuff_small_head_pisa slab cache backed by zeroed, read-only PISA folios (SLAB_CACHE_PISA_RO). Eligible TX paths passing __GFP_PISA allocate small heads from this cache and fall back to skbuff_small_head on failure.

---
 drivers/base/core.c    |  3 +-
 include/linux/device.h |  6 +++
 include/net/pisa.h     | 64 +++++++++++++++++++++++++++++
 mm/pisa-kunit.c        |  5 ++-
 net/core/pisa-net.c    | 93 +++++++++++++++++++++++++++++++++++++-----
 net/core/skbuff.c      | 30 +++++++++++---
 net/core/sock.c        | 21 ++++++++--
 net/ipv4/ip_output.c   |  8 ++--
 net/ipv4/raw.c         |  6 +--
 net/ipv4/tcp.c         |  2 +-
 net/ipv4/tcp_output.c  | 14 ++++---
 net/ipv6/ip6_output.c  |  8 ++--
 net/ipv6/raw.c         |  6 +--
 13 files changed, 224 insertions(+), 42 deletions(-)
drivers/base/core.c +2 -1
index 5f1291e644c5e..92eec7d3d4cf1 100644
@@ -2951,7 +2951,7 @@ static DEVICE_ATTR_RW(name)
 PISA_BOOL_ATTR(pisa_coherent);
 PISA_BOOL_ATTR(pisa_rx_bufs);
 PISA_SET_ATTR(pisa_tx_bufs, net_pisa_tx_bufs_set);
-PISA_BOOL_ATTR(pisa_tx_skb_heads);
+PISA_SET_ATTR(pisa_tx_skb_heads, net_pisa_tx_skb_heads_set);
 PISA_BOOL_ATTR(pisa_tx_zerocopy);
 
 static struct attribute *dev_attr_pisa[] = {
@@ -3114,6 +3114,7 @@ static void device_remove_attrs(struct device *dev)
 	if (IS_ENABLED(CONFIG_PISA) && dev->dma_mask) {
 		device_remove_group(dev, &dev_attr_pisa_group);
 		net_pisa_tx_bufs_set(dev, false);
+		net_pisa_tx_skb_heads_set(dev, false);
 	}
 
 	if (dev->physical_location) {
include/linux/device.h +6 -0
index 0d867d8255ba5..6776048d05ca8 100644
@@ -819,6 +819,7 @@ struct device {
 
 #if defined(CONFIG_NET) && defined(CONFIG_PISA)
 int net_pisa_tx_bufs_set(struct device *dev, bool val);
+int net_pisa_tx_skb_heads_set(struct device *dev, bool val);
 #else
 /* Without CONFIG_NET the flag still gates block-device writes (see pisa_bdev_enabled()). */
 static inline int net_pisa_tx_bufs_set(struct device *dev, bool val)
@@ -826,6 +827,11 @@ static inline int net_pisa_tx_bufs_set(struct device *dev, bool val)
 	WRITE_ONCE(dev->pisa_tx_bufs, val);
 	return 0;
 }
+
+static inline int net_pisa_tx_skb_heads_set(struct device *dev, bool val)
+{
+	return -EOPNOTSUPP;
+}
 #endif
 
 #define __create_dev_flag_accessors(accessor_name, flag_name) \
include/net/pisa.h +64 -0

98 lines not on this page · raw message

mm/pisa-kunit.c +3 -2
index ec7af4313915a..0dbc3ecf44465 100644
@@ -579,9 +579,10 @@ static void test_dev_pisa_attrs(struct kunit *test)
 	kunit_check_pisa_attr(test, dev, "pisa_coherent", &dev->pisa_coherent);
 	kunit_check_pisa_attr(test, dev, "pisa_rx_bufs", &dev->pisa_rx_bufs);
 	kunit_check_pisa_attr(test, dev, "pisa_tx_zerocopy", &dev->pisa_tx_zerocopy);
-	if (IS_ENABLED(CONFIG_NET))
+	if (IS_ENABLED(CONFIG_NET)) {
 		kunit_check_pisa_attr(test, dev, "pisa_tx_bufs", &dev->pisa_tx_bufs);
-	kunit_check_pisa_attr(test, dev, "pisa_tx_skb_heads", &dev->pisa_tx_skb_heads);
+		kunit_check_pisa_attr(test, dev, "pisa_tx_skb_heads", &dev->pisa_tx_skb_heads);
+	}
 	device_unregister(dev);
 }
 
net/core/pisa-net.c +82 -11

118 lines not on this page · raw message

net/core/skbuff.c +24 -6
index 1ac1e327ac4c6..4f487e0450d4b 100644
@@ -70,6 +70,7 @@
 #include <net/protocol.h>
 #include <net/dst.h>
 #include <net/sock.h>
+#include <net/pisa.h>
 #include <net/checksum.h>
 #include <net/gro.h>
 #include <net/gso.h>
@@ -93,6 +94,7 @@
 #include <linux/user_namespace.h>
 #include <linux/indirect_call_wrapper.h>
 #include <linux/textsearch.h>
+#include <linux/pisa.h>
 
 #include "dev.h"
 #include "devmem.h"
@@ -607,16 +609,23 @@ static void *kmalloc_pfmemalloc(size_t obj_size, gfp_t flags, int node)
 static void *kmalloc_reserve(unsigned int *size, gfp_t flags, int node,
 			     struct sk_buff *skb)
 {
+	bool pisa = flags & __GFP_PISA;
 	size_t obj_size;
 	void *obj;
 
+	flags &= ~__GFP_PISA_RW;
 	obj_size = SKB_HEAD_ALIGN(*size);
 	if (obj_size <= SKB_SMALL_HEAD_CACHE_SIZE &&
 	    !(flags & KMALLOC_NOT_NORMAL_BITS)) {
+		*size = SKB_SMALL_HEAD_CACHE_SIZE;
+		if (unlikely(pisa)) {
+			obj = pisa_skb_head_alloc_node(flags, node);
+			if (likely(obj))
+				goto out;
+		}
 		obj = kmem_cache_alloc_node(net_hotdata.skb_small_head_cache,
 				flags | __GFP_NOMEMALLOC | __GFP_NOWARN,
 				node);
-		*size = SKB_SMALL_HEAD_CACHE_SIZE;
 		if (likely(obj))
 			goto out;
 		/* Try again but now we are using pfmemalloc reserves */
@@ -2194,6 +2203,7 @@ struct sk_buff *skb_copy(const struct sk_buff *skb, gfp_t gfp_mask)
 
 	headerlen = skb_headroom(skb);
 	size = skb_end_offset(skb) + skb->data_len;
+	gfp_mask |= skb_head_pisa_gfp(skb);
 	n = __alloc_skb(size, gfp_mask,
 			skb_alloc_rx_flag(skb), NUMA_NO_NODE);
 	if (!n)
@@ -2238,7 +2248,10 @@ struct sk_buff *__pskb_copy_fclone(struct sk_buff *skb, int headroom,
 {
 	unsigned int size = skb_headlen(skb) + headroom;
 	int flags = skb_alloc_rx_flag(skb) | (fclone ? SKB_ALLOC_FCLONE : 0);
-	struct sk_buff *n = __alloc_skb(size, gfp_mask, flags, NUMA_NO_NODE);
+	struct sk_buff *n;
+
+	/* For the head only: @gfp_mask is also used to orphan frags below. */
+	n = __alloc_skb(size, gfp_mask | skb_head_pisa_gfp(skb), flags, NUMA_NO_NODE);
 
 	if (!n)
 		goto out;
@@ -2327,7 +2340,8 @@ int pskb_expand_head(struct sk_buff *skb, int nhead, int ntail,
 	if (skb_pfmemalloc(skb))
 		gfp_mask |= __GFP_MEMALLOC;
 
-	data = kmalloc_reserve(&size, gfp_mask, NUMA_NO_NODE, NULL);
+	/* For the head only: @gfp_mask is also used to orphan frags below. */
+	data = kmalloc_reserve(&size, gfp_mask | skb_head_pisa_gfp(skb), NUMA_NO_NODE, NULL);
 	if (!data)
 		goto nodata;
 	size = SKB_WITH_OVERHEAD(size);
@@ -2535,6 +2549,7 @@ struct sk_buff *skb_copy_expand(const struct sk_buff *skb,
 		return NULL;
 
 	oldheadroom = skb_headroom(skb);
+	gfp_mask |= skb_head_pisa_gfp(skb);
 	n = __alloc_skb(newheadroom + skb->len + newtailroom,
 			gfp_mask, skb_alloc_rx_flag(skb),
 			NUMA_NO_NODE);
@@ -5037,7 +5052,8 @@ struct sk_buff *skb_segment(struct sk_buff *head_skb,
 				hsize = len;
 
 			nskb = __alloc_skb(hsize + doffset + headroom,
-					   GFP_ATOMIC, skb_alloc_rx_flag(head_skb),
+					   GFP_ATOMIC | skb_head_pisa_gfp(head_skb),
+					   skb_alloc_rx_flag(head_skb),
 					   NUMA_NO_NODE);
 
 			if (unlikely(!nskb))
@@ -7012,7 +7028,8 @@ static int pskb_carve_inside_header(struct sk_buff *skb, const u32 off,
 	if (skb_pfmemalloc(skb))
 		gfp_mask |= __GFP_MEMALLOC;
 
-	data = kmalloc_reserve(&size, gfp_mask, NUMA_NO_NODE, NULL);
+	/* For the head only: @gfp_mask is also used to orphan frags below. */
+	data = kmalloc_reserve(&size, gfp_mask | skb_head_pisa_gfp(skb), NUMA_NO_NODE, NULL);
 	if (!data)
 		return -ENOMEM;
 	size = SKB_WITH_OVERHEAD(size);
@@ -7134,7 +7151,8 @@ static int pskb_carve_inside_nonlinear(struct sk_buff *skb, const u32 off,
 	if (skb_pfmemalloc(skb))
 		gfp_mask |= __GFP_MEMALLOC;
 
-	data = kmalloc_reserve(&size, gfp_mask, NUMA_NO_NODE, NULL);
+	/* For the head only: @gfp_mask is also used to orphan frags below. */
+	data = kmalloc_reserve(&size, gfp_mask | skb_head_pisa_gfp(skb), NUMA_NO_NODE, NULL);
 	if (!data)
 		return -ENOMEM;
 	size = SKB_WITH_OVERHEAD(size);
net/core/sock.c +17 -4
index 56dea49baaec2..0599c7d1aa6d0 100644
@@ -3062,9 +3062,10 @@ static long sock_wait_for_wmem(struct sock *sk, long timeo)
  *	Generic send/receive buffer handlers
  */
 
-struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len,
-				     unsigned long data_len, int noblock,
-				     int *errcode, int max_page_order)
+struct sk_buff *__sock_alloc_send_pskb(struct sock *sk, unsigned long header_len,
+				       unsigned long data_len, int noblock,
+				       int *errcode, int max_page_order,
+				       gfp_t gfp)
 {
 	struct sk_buff *skb;
 	long timeo;
@@ -3093,7 +3094,8 @@ struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len,
 		timeo = sock_wait_for_wmem(sk, timeo);
 	}
 	skb = alloc_skb_with_frags(header_len, data_len, max_page_order,
-				   errcode, sk->sk_allocation);
+				   errcode,
+				   sk->sk_allocation | gfp);
 	if (skb)
 		skb_set_owner_w(skb, sk);
 	return skb;
@@ -3104,6 +3106,17 @@ struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len,
 	*errcode = err;
 	return NULL;
 }
+EXPORT_SYMBOL(__sock_alloc_send_pskb);
+
+struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len,
+				     unsigned long data_len, int noblock,
+				     int *errcode, int max_page_order)
+{
+	/* Callers with data_len != 0 (unix, packet, tun/tap) have no sk_dst_cache, so gfp is 0. */
+	return __sock_alloc_send_pskb(sk, header_len, data_len, noblock,
+				      errcode, max_page_order,
+				      pisa_tx_head_sk_gfp(sk));
+}
 EXPORT_SYMBOL(sock_alloc_send_pskb);
 
 int __sock_cmsg_send(struct sock *sk, struct cmsghdr *cmsg,
net/ipv4/ip_output.c +5 -3
index 50b8c92c3cd5e..f710cf959124f 100644
@@ -1135,14 +1135,16 @@ static int __ip_append_data(struct sock *sk,
 			alloclen += alloc_extra;
 
 			if (transhdrlen) {
-				skb = sock_alloc_send_skb(sk, alloclen,
-						(flags & MSG_DONTWAIT), &err);
+				skb = sock_alloc_send_skb_dst(sk, alloclen,
+							      flags & MSG_DONTWAIT,
+							      &err, &rt->dst);
 			} else {
 				skb = NULL;
 				if (refcount_read(&sk->sk_wmem_alloc) + wmem_alloc_delta <=
 				    2 * sk->sk_sndbuf)
 					skb = alloc_skb(alloclen,
-							sk->sk_allocation);
+							sk->sk_allocation |
+							pisa_tx_head_gfp(&rt->dst));
 				if (unlikely(!skb))
 					err = -ENOBUFS;
 			}
net/ipv4/raw.c +3 -3
index f33a9dfc53099..87622fc1e2849 100644
@@ -60,6 +60,7 @@
 #include <linux/ip.h>
 #include <linux/net.h>
 #include <net/ip.h>
+#include <net/pisa.h>
 #include <net/icmp.h>
 #include <net/udp.h>
 #include <net/raw.h>
@@ -358,9 +359,8 @@ static int raw_send_hdrinc(struct sock *sk, struct flowi4 *fl4,
 
 	hlen = LL_RESERVED_SPACE(rt->dst.dev);
 	tlen = rt->dst.dev->needed_tailroom;
-	skb = sock_alloc_send_skb(sk,
-				  length + hlen + tlen + 15,
-				  flags & MSG_DONTWAIT, &err);
+	skb = sock_alloc_send_skb_dst(sk, length + hlen + tlen + 15,
+				      flags & MSG_DONTWAIT, &err, &rt->dst);
 	if (!skb)
 		goto error;
 	skb_reserve(skb, hlen);
net/ipv4/tcp.c +1 -1
index 3c3edc48705d7..83f8ed2aa9a7e 100644
@@ -932,7 +932,7 @@ struct sk_buff *tcp_stream_alloc_skb(struct sock *sk, gfp_t gfp,
 {
 	struct sk_buff *skb;
 
-	skb = alloc_skb_fclone(MAX_TCP_HEADER, gfp);
+	skb = alloc_skb_fclone(MAX_TCP_HEADER, gfp | pisa_tx_head_sk_gfp(sk));
 	if (likely(skb)) {
 		bool mem_scheduled;
 
net/ipv4/tcp_output.c +9 -5
index cf3ddc055d48d..24629788295b6 100644
@@ -43,6 +43,7 @@
 #include <net/smc.h>
 #include <net/proto_memory.h>
 #include <net/psp.h>
+#include <net/pisa.h>
 
 #include <linux/compiler.h>
 #include <linux/gfp.h>
@@ -3893,7 +3894,8 @@ void tcp_send_fin(struct sock *sk)
 	} else {
 		skb = alloc_skb_fclone(MAX_TCP_HEADER,
 				       sk_gfp_mask(sk, GFP_ATOMIC |
-						       __GFP_NOWARN));
+						       __GFP_NOWARN) |
+				       pisa_tx_head_sk_gfp(sk));
 		if (unlikely(!skb))
 			return;
 
@@ -3921,7 +3923,7 @@ void tcp_send_active_reset(struct sock *sk, enum sk_rst_reason reason)
 	TCP_INC_STATS(sock_net(sk), TCP_MIB_OUTRSTS);
 
 	/* NOTE: No TCP options attached and we never retransmit this. */
-	skb = alloc_skb(MAX_TCP_HEADER, priority);
+	skb = alloc_skb(MAX_TCP_HEADER, priority | pisa_tx_head_sk_gfp(sk));
 	if (!skb) {
 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTFAILED);
 		return;
@@ -4011,7 +4013,7 @@ struct sk_buff *tcp_make_synack(const struct sock *sk, struct dst_entry *dst,
 	int mss;
 	u64 now;
 
-	skb = alloc_skb(MAX_TCP_HEADER, GFP_ATOMIC);
+	skb = alloc_skb(MAX_TCP_HEADER, GFP_ATOMIC | pisa_tx_head_gfp(dst));
 	if (unlikely(!skb)) {
 		dst_release(dst);
 		return NULL;
@@ -4548,7 +4550,8 @@ void __tcp_send_ack(struct sock *sk, u32 rcv_nxt, u16 flags)
 	 * sock.
 	 */
 	buff = alloc_skb(MAX_TCP_HEADER,
-			 sk_gfp_mask(sk, GFP_ATOMIC | __GFP_NOWARN));
+			 sk_gfp_mask(sk, GFP_ATOMIC | __GFP_NOWARN) |
+			 pisa_tx_head_sk_gfp(sk));
 	if (unlikely(!buff)) {
 		struct inet_connection_sock *icsk = inet_csk(sk);
 		unsigned long delay;
@@ -4601,7 +4604,8 @@ static int tcp_xmit_probe_skb(struct sock *sk, int urgent, int mib)
 
 	/* We don't queue it, tcp_transmit_skb() sets ownership. */
 	skb = alloc_skb(MAX_TCP_HEADER,
-			sk_gfp_mask(sk, GFP_ATOMIC | __GFP_NOWARN));
+			sk_gfp_mask(sk, GFP_ATOMIC | __GFP_NOWARN) |
+			pisa_tx_head_sk_gfp(sk));
 	if (!skb)
 		return -1;
 
net/ipv6/ip6_output.c +5 -3
index 8f6f0bed15499..9a853655f8558 100644
@@ -1699,14 +1699,16 @@ static int __ip6_append_data(struct sock *sk,
 				goto error;
 			}
 			if (transhdrlen) {
-				skb = sock_alloc_send_skb(sk, alloclen,
-						(flags & MSG_DONTWAIT), &err);
+				skb = sock_alloc_send_skb_dst(sk, alloclen,
+							      flags & MSG_DONTWAIT,
+							      &err, &rt->dst);
 			} else {
 				skb = NULL;
 				if (refcount_read(&sk->sk_wmem_alloc) + wmem_alloc_delta <=
 				    2 * sk->sk_sndbuf)
 					skb = alloc_skb(alloclen,
-							sk->sk_allocation);
+							sk->sk_allocation |
+							pisa_tx_head_gfp(&rt->dst));
 				if (unlikely(!skb))
 					err = -ENOBUFS;
 			}
net/ipv6/raw.c +3 -3
index 00d832c7cdae9..aa10e74d0db3f 100644
@@ -33,6 +33,7 @@
 
 #include <net/net_namespace.h>
 #include <net/ip.h>
+#include <net/pisa.h>
 #include <net/sock.h>
 #include <net/snmp.h>
 
@@ -614,9 +615,8 @@ static int rawv6_send_hdrinc(struct sock *sk, struct msghdr *msg, int length,
 	if (flags&MSG_PROBE)
 		goto out;
 
-	skb = sock_alloc_send_skb(sk,
-				  length + hlen + tlen + 15,
-				  flags & MSG_DONTWAIT, &err);
+	skb = sock_alloc_send_skb_dst(sk, length + hlen + tlen + 15,
+				      flags & MSG_DONTWAIT, &err, &rt->dst);
 	if (!skb)
 		goto error;
 	skb_reserve(skb, hlen);
Signature · 1 line
2.56.1.809.ga0b61035b5-goog