1 /* SPDX-License-Identifier: GPL-2.0
4 * Author: Jesper Dangaard Brouer <netoptimizer@brouer.com>
5 * Copyright (C) 2016 Red Hat, Inc.
8 #include <linux/types.h>
9 #include <linux/kernel.h>
10 #include <linux/slab.h>
11 #include <linux/device.h>
13 #include <net/page_pool.h>
16 #include <linux/dma-direction.h>
17 #include <linux/dma-mapping.h>
18 #include <linux/page-flags.h>
19 #include <linux/mm.h> /* for __put_page() */
20 #include <linux/poison.h>
22 #include <trace/events/page_pool.h>
24 #define DEFER_TIME (msecs_to_jiffies(1000))
25 #define DEFER_WARN_INTERVAL (60 * HZ)
27 #define BIAS_MAX LONG_MAX
29 static bool page_pool_producer_lock(struct page_pool *pool)
30 __acquires(&pool->ring.producer_lock)
32 bool in_softirq = in_softirq();
35 spin_lock(&pool->ring.producer_lock);
37 spin_lock_bh(&pool->ring.producer_lock);
42 static void page_pool_producer_unlock(struct page_pool *pool,
44 __releases(&pool->ring.producer_lock)
47 spin_unlock(&pool->ring.producer_lock);
49 spin_unlock_bh(&pool->ring.producer_lock);
52 static int page_pool_init(struct page_pool *pool,
53 const struct page_pool_params *params)
55 unsigned int ring_qsize = 1024; /* Default */
57 memcpy(&pool->p, params, sizeof(pool->p));
59 /* Validate only known flags were used */
60 if (pool->p.flags & ~(PP_FLAG_ALL))
63 if (pool->p.pool_size)
64 ring_qsize = pool->p.pool_size;
66 /* Sanity limit mem that can be pinned down */
67 if (ring_qsize > 32768)
70 /* DMA direction is either DMA_FROM_DEVICE or DMA_BIDIRECTIONAL.
71 * DMA_BIDIRECTIONAL is for allowing page used for DMA sending,
72 * which is the XDP_TX use-case.
74 if (pool->p.flags & PP_FLAG_DMA_MAP) {
75 if ((pool->p.dma_dir != DMA_FROM_DEVICE) &&
76 (pool->p.dma_dir != DMA_BIDIRECTIONAL))
80 if (pool->p.flags & PP_FLAG_DMA_SYNC_DEV) {
81 /* In order to request DMA-sync-for-device the page
84 if (!(pool->p.flags & PP_FLAG_DMA_MAP))
90 /* pool->p.offset has to be set according to the address
91 * offset used by the DMA engine to start copying rx data
95 if (PAGE_POOL_DMA_USE_PP_FRAG_COUNT &&
96 pool->p.flags & PP_FLAG_PAGE_FRAG)
99 if (ptr_ring_init(&pool->ring, ring_qsize, GFP_KERNEL) < 0)
102 atomic_set(&pool->pages_state_release_cnt, 0);
104 /* Driver calling page_pool_create() also call page_pool_destroy() */
105 refcount_set(&pool->user_cnt, 1);
107 if (pool->p.flags & PP_FLAG_DMA_MAP)
108 get_device(pool->p.dev);
113 struct page_pool *page_pool_create(const struct page_pool_params *params)
115 struct page_pool *pool;
118 pool = kzalloc_node(sizeof(*pool), GFP_KERNEL, params->nid);
120 return ERR_PTR(-ENOMEM);
122 err = page_pool_init(pool, params);
124 pr_warn("%s() gave up with errno %d\n", __func__, err);
131 EXPORT_SYMBOL(page_pool_create);
133 static void page_pool_return_page(struct page_pool *pool, struct page *page);
136 static struct page *page_pool_refill_alloc_cache(struct page_pool *pool)
138 struct ptr_ring *r = &pool->ring;
140 int pref_nid; /* preferred NUMA node */
142 /* Quicker fallback, avoid locks when ring is empty */
143 if (__ptr_ring_empty(r))
146 /* Softirq guarantee CPU and thus NUMA node is stable. This,
147 * assumes CPU refilling driver RX-ring will also run RX-NAPI.
150 pref_nid = (pool->p.nid == NUMA_NO_NODE) ? numa_mem_id() : pool->p.nid;
152 /* Ignore pool->p.nid setting if !CONFIG_NUMA, helps compiler */
153 pref_nid = numa_mem_id(); /* will be zero like page_to_nid() */
156 /* Slower-path: Get pages from locked ring queue */
157 spin_lock(&r->consumer_lock);
159 /* Refill alloc array, but only if NUMA match */
161 page = __ptr_ring_consume(r);
165 if (likely(page_to_nid(page) == pref_nid)) {
166 pool->alloc.cache[pool->alloc.count++] = page;
169 * (1) release 1 page to page-allocator and
170 * (2) break out to fallthrough to alloc_pages_node.
171 * This limit stress on page buddy alloactor.
173 page_pool_return_page(pool, page);
177 } while (pool->alloc.count < PP_ALLOC_CACHE_REFILL);
179 /* Return last page */
180 if (likely(pool->alloc.count > 0))
181 page = pool->alloc.cache[--pool->alloc.count];
183 spin_unlock(&r->consumer_lock);
188 static struct page *__page_pool_get_cached(struct page_pool *pool)
192 /* Caller MUST guarantee safe non-concurrent access, e.g. softirq */
193 if (likely(pool->alloc.count)) {
195 page = pool->alloc.cache[--pool->alloc.count];
197 page = page_pool_refill_alloc_cache(pool);
203 static void page_pool_dma_sync_for_device(struct page_pool *pool,
205 unsigned int dma_sync_size)
207 dma_addr_t dma_addr = page_pool_get_dma_addr(page);
209 dma_sync_size = min(dma_sync_size, pool->p.max_len);
210 dma_sync_single_range_for_device(pool->p.dev, dma_addr,
211 pool->p.offset, dma_sync_size,
215 static bool page_pool_dma_map(struct page_pool *pool, struct page *page)
219 /* Setup DMA mapping: use 'struct page' area for storing DMA-addr
220 * since dma_addr_t can be either 32 or 64 bits and does not always fit
221 * into page private data (i.e 32bit cpu with 64bit DMA caps)
222 * This mapping is kept for lifetime of page, until leaving pool.
224 dma = dma_map_page_attrs(pool->p.dev, page, 0,
225 (PAGE_SIZE << pool->p.order),
226 pool->p.dma_dir, DMA_ATTR_SKIP_CPU_SYNC);
227 if (dma_mapping_error(pool->p.dev, dma))
230 page_pool_set_dma_addr(page, dma);
232 if (pool->p.flags & PP_FLAG_DMA_SYNC_DEV)
233 page_pool_dma_sync_for_device(pool, page, pool->p.max_len);
238 static void page_pool_set_pp_info(struct page_pool *pool,
242 page->pp_magic |= PP_SIGNATURE;
245 static void page_pool_clear_pp_info(struct page *page)
251 static struct page *__page_pool_alloc_page_order(struct page_pool *pool,
257 page = alloc_pages_node(pool->p.nid, gfp, pool->p.order);
261 if ((pool->p.flags & PP_FLAG_DMA_MAP) &&
262 unlikely(!page_pool_dma_map(pool, page))) {
267 page_pool_set_pp_info(pool, page);
269 /* Track how many pages are held 'in-flight' */
270 pool->pages_state_hold_cnt++;
271 trace_page_pool_state_hold(pool, page, pool->pages_state_hold_cnt);
277 static struct page *__page_pool_alloc_pages_slow(struct page_pool *pool,
280 const int bulk = PP_ALLOC_CACHE_REFILL;
281 unsigned int pp_flags = pool->p.flags;
282 unsigned int pp_order = pool->p.order;
286 /* Don't support bulk alloc for high-order pages */
287 if (unlikely(pp_order))
288 return __page_pool_alloc_page_order(pool, gfp);
290 /* Unnecessary as alloc cache is empty, but guarantees zero count */
291 if (unlikely(pool->alloc.count > 0))
292 return pool->alloc.cache[--pool->alloc.count];
294 /* Mark empty alloc.cache slots "empty" for alloc_pages_bulk_array */
295 memset(&pool->alloc.cache, 0, sizeof(void *) * bulk);
297 nr_pages = alloc_pages_bulk_array(gfp, bulk, pool->alloc.cache);
298 if (unlikely(!nr_pages))
301 /* Pages have been filled into alloc.cache array, but count is zero and
302 * page element have not been (possibly) DMA mapped.
304 for (i = 0; i < nr_pages; i++) {
305 page = pool->alloc.cache[i];
306 if ((pp_flags & PP_FLAG_DMA_MAP) &&
307 unlikely(!page_pool_dma_map(pool, page))) {
312 page_pool_set_pp_info(pool, page);
313 pool->alloc.cache[pool->alloc.count++] = page;
314 /* Track how many pages are held 'in-flight' */
315 pool->pages_state_hold_cnt++;
316 trace_page_pool_state_hold(pool, page,
317 pool->pages_state_hold_cnt);
320 /* Return last page */
321 if (likely(pool->alloc.count > 0))
322 page = pool->alloc.cache[--pool->alloc.count];
326 /* When page just alloc'ed is should/must have refcnt 1. */
330 /* For using page_pool replace: alloc_pages() API calls, but provide
331 * synchronization guarantee for allocation side.
333 struct page *page_pool_alloc_pages(struct page_pool *pool, gfp_t gfp)
337 /* Fast-path: Get a page from cache */
338 page = __page_pool_get_cached(pool);
342 /* Slow-path: cache empty, do real allocation */
343 page = __page_pool_alloc_pages_slow(pool, gfp);
346 EXPORT_SYMBOL(page_pool_alloc_pages);
348 /* Calculate distance between two u32 values, valid if distance is below 2^(31)
349 * https://en.wikipedia.org/wiki/Serial_number_arithmetic#General_Solution
351 #define _distance(a, b) (s32)((a) - (b))
353 static s32 page_pool_inflight(struct page_pool *pool)
355 u32 release_cnt = atomic_read(&pool->pages_state_release_cnt);
356 u32 hold_cnt = READ_ONCE(pool->pages_state_hold_cnt);
359 inflight = _distance(hold_cnt, release_cnt);
361 trace_page_pool_release(pool, inflight, hold_cnt, release_cnt);
362 WARN(inflight < 0, "Negative(%d) inflight packet-pages", inflight);
367 /* Disconnects a page (from a page_pool). API users can have a need
368 * to disconnect a page (from a page_pool), to allow it to be used as
369 * a regular page (that will eventually be returned to the normal
370 * page-allocator via put_page).
372 void page_pool_release_page(struct page_pool *pool, struct page *page)
377 if (!(pool->p.flags & PP_FLAG_DMA_MAP))
378 /* Always account for inflight pages, even if we didn't
383 dma = page_pool_get_dma_addr(page);
385 /* When page is unmapped, it cannot be returned to our pool */
386 dma_unmap_page_attrs(pool->p.dev, dma,
387 PAGE_SIZE << pool->p.order, pool->p.dma_dir,
388 DMA_ATTR_SKIP_CPU_SYNC);
389 page_pool_set_dma_addr(page, 0);
391 page_pool_clear_pp_info(page);
393 /* This may be the last page returned, releasing the pool, so
394 * it is not safe to reference pool afterwards.
396 count = atomic_inc_return_relaxed(&pool->pages_state_release_cnt);
397 trace_page_pool_state_release(pool, page, count);
399 EXPORT_SYMBOL(page_pool_release_page);
401 /* Return a page to the page allocator, cleaning up our state */
402 static void page_pool_return_page(struct page_pool *pool, struct page *page)
404 page_pool_release_page(pool, page);
407 /* An optimization would be to call __free_pages(page, pool->p.order)
408 * knowing page is not part of page-cache (thus avoiding a
409 * __page_cache_release() call).
413 static bool page_pool_recycle_in_ring(struct page_pool *pool, struct page *page)
416 /* BH protection not needed if current is softirq */
418 ret = ptr_ring_produce(&pool->ring, page);
420 ret = ptr_ring_produce_bh(&pool->ring, page);
422 return (ret == 0) ? true : false;
425 /* Only allow direct recycling in special circumstances, into the
426 * alloc side cache. E.g. during RX-NAPI processing for XDP_DROP use-case.
428 * Caller must provide appropriate safe context.
430 static bool page_pool_recycle_in_cache(struct page *page,
431 struct page_pool *pool)
433 if (unlikely(pool->alloc.count == PP_ALLOC_CACHE_SIZE))
436 /* Caller MUST have verified/know (page_ref_count(page) == 1) */
437 pool->alloc.cache[pool->alloc.count++] = page;
441 /* If the page refcnt == 1, this will try to recycle the page.
442 * if PP_FLAG_DMA_SYNC_DEV is set, we'll try to sync the DMA area for
443 * the configured size min(dma_sync_size, pool->max_len).
444 * If the page refcnt != 1, then the page will be returned to memory
447 static __always_inline struct page *
448 __page_pool_put_page(struct page_pool *pool, struct page *page,
449 unsigned int dma_sync_size, bool allow_direct)
451 /* It is not the last user for the page frag case */
452 if (pool->p.flags & PP_FLAG_PAGE_FRAG &&
453 page_pool_atomic_sub_frag_count_return(page, 1))
456 /* This allocator is optimized for the XDP mode that uses
457 * one-frame-per-page, but have fallbacks that act like the
458 * regular page allocator APIs.
460 * refcnt == 1 means page_pool owns page, and can recycle it.
462 * page is NOT reusable when allocated when system is under
463 * some pressure. (page_is_pfmemalloc)
465 if (likely(page_ref_count(page) == 1 && !page_is_pfmemalloc(page))) {
466 /* Read barrier done in page_ref_count / READ_ONCE */
468 if (pool->p.flags & PP_FLAG_DMA_SYNC_DEV)
469 page_pool_dma_sync_for_device(pool, page,
472 if (allow_direct && in_softirq() &&
473 page_pool_recycle_in_cache(page, pool))
476 /* Page found as candidate for recycling */
479 /* Fallback/non-XDP mode: API user have elevated refcnt.
481 * Many drivers split up the page into fragments, and some
482 * want to keep doing this to save memory and do refcnt based
483 * recycling. Support this use case too, to ease drivers
484 * switching between XDP/non-XDP.
486 * In-case page_pool maintains the DMA mapping, API user must
487 * call page_pool_put_page once. In this elevated refcnt
488 * case, the DMA is unmapped/released, as driver is likely
489 * doing refcnt based recycle tricks, meaning another process
490 * will be invoking put_page.
492 /* Do not replace this with page_pool_return_page() */
493 page_pool_release_page(pool, page);
499 void page_pool_put_page(struct page_pool *pool, struct page *page,
500 unsigned int dma_sync_size, bool allow_direct)
502 page = __page_pool_put_page(pool, page, dma_sync_size, allow_direct);
503 if (page && !page_pool_recycle_in_ring(pool, page)) {
504 /* Cache full, fallback to free pages */
505 page_pool_return_page(pool, page);
508 EXPORT_SYMBOL(page_pool_put_page);
510 /* Caller must not use data area after call, as this function overwrites it */
511 void page_pool_put_page_bulk(struct page_pool *pool, void **data,
517 for (i = 0; i < count; i++) {
518 struct page *page = virt_to_head_page(data[i]);
520 page = __page_pool_put_page(pool, page, -1, false);
521 /* Approved for bulk recycling in ptr_ring cache */
523 data[bulk_len++] = page;
526 if (unlikely(!bulk_len))
529 /* Bulk producer into ptr_ring page_pool cache */
530 in_softirq = page_pool_producer_lock(pool);
531 for (i = 0; i < bulk_len; i++) {
532 if (__ptr_ring_produce(&pool->ring, data[i]))
533 break; /* ring full */
535 page_pool_producer_unlock(pool, in_softirq);
537 /* Hopefully all pages was return into ptr_ring */
538 if (likely(i == bulk_len))
541 /* ptr_ring cache full, free remaining pages outside producer lock
542 * since put_page() with refcnt == 1 can be an expensive operation
544 for (; i < bulk_len; i++)
545 page_pool_return_page(pool, data[i]);
547 EXPORT_SYMBOL(page_pool_put_page_bulk);
549 static struct page *page_pool_drain_frag(struct page_pool *pool,
552 long drain_count = BIAS_MAX - pool->frag_users;
554 /* Some user is still using the page frag */
555 if (likely(page_pool_atomic_sub_frag_count_return(page,
559 if (page_ref_count(page) == 1 && !page_is_pfmemalloc(page)) {
560 if (pool->p.flags & PP_FLAG_DMA_SYNC_DEV)
561 page_pool_dma_sync_for_device(pool, page, -1);
566 page_pool_return_page(pool, page);
570 static void page_pool_free_frag(struct page_pool *pool)
572 long drain_count = BIAS_MAX - pool->frag_users;
573 struct page *page = pool->frag_page;
575 pool->frag_page = NULL;
578 page_pool_atomic_sub_frag_count_return(page, drain_count))
581 page_pool_return_page(pool, page);
584 struct page *page_pool_alloc_frag(struct page_pool *pool,
585 unsigned int *offset,
586 unsigned int size, gfp_t gfp)
588 unsigned int max_size = PAGE_SIZE << pool->p.order;
589 struct page *page = pool->frag_page;
591 if (WARN_ON(!(pool->p.flags & PP_FLAG_PAGE_FRAG) ||
595 size = ALIGN(size, dma_get_cache_alignment());
596 *offset = pool->frag_offset;
598 if (page && *offset + size > max_size) {
599 page = page_pool_drain_frag(pool, page);
605 page = page_pool_alloc_pages(pool, gfp);
606 if (unlikely(!page)) {
607 pool->frag_page = NULL;
611 pool->frag_page = page;
614 pool->frag_users = 1;
616 pool->frag_offset = size;
617 page_pool_set_frag_count(page, BIAS_MAX);
622 pool->frag_offset = *offset + size;
625 EXPORT_SYMBOL(page_pool_alloc_frag);
627 static void page_pool_empty_ring(struct page_pool *pool)
631 /* Empty recycle ring */
632 while ((page = ptr_ring_consume_bh(&pool->ring))) {
633 /* Verify the refcnt invariant of cached pages */
634 if (!(page_ref_count(page) == 1))
635 pr_crit("%s() page_pool refcnt %d violation\n",
636 __func__, page_ref_count(page));
638 page_pool_return_page(pool, page);
642 static void page_pool_free(struct page_pool *pool)
644 if (pool->disconnect)
645 pool->disconnect(pool);
647 ptr_ring_cleanup(&pool->ring, NULL);
649 if (pool->p.flags & PP_FLAG_DMA_MAP)
650 put_device(pool->p.dev);
655 static void page_pool_empty_alloc_cache_once(struct page_pool *pool)
659 if (pool->destroy_cnt)
662 /* Empty alloc cache, assume caller made sure this is
663 * no-longer in use, and page_pool_alloc_pages() cannot be
666 while (pool->alloc.count) {
667 page = pool->alloc.cache[--pool->alloc.count];
668 page_pool_return_page(pool, page);
672 static void page_pool_scrub(struct page_pool *pool)
674 page_pool_empty_alloc_cache_once(pool);
677 /* No more consumers should exist, but producers could still
680 page_pool_empty_ring(pool);
683 static int page_pool_release(struct page_pool *pool)
687 page_pool_scrub(pool);
688 inflight = page_pool_inflight(pool);
690 page_pool_free(pool);
695 static void page_pool_release_retry(struct work_struct *wq)
697 struct delayed_work *dwq = to_delayed_work(wq);
698 struct page_pool *pool = container_of(dwq, typeof(*pool), release_dw);
701 inflight = page_pool_release(pool);
705 /* Periodic warning */
706 if (time_after_eq(jiffies, pool->defer_warn)) {
707 int sec = (s32)((u32)jiffies - (u32)pool->defer_start) / HZ;
709 pr_warn("%s() stalled pool shutdown %d inflight %d sec\n",
710 __func__, inflight, sec);
711 pool->defer_warn = jiffies + DEFER_WARN_INTERVAL;
714 /* Still not ready to be disconnected, retry later */
715 schedule_delayed_work(&pool->release_dw, DEFER_TIME);
718 void page_pool_use_xdp_mem(struct page_pool *pool, void (*disconnect)(void *))
720 refcount_inc(&pool->user_cnt);
721 pool->disconnect = disconnect;
724 void page_pool_destroy(struct page_pool *pool)
729 if (!page_pool_put(pool))
732 page_pool_free_frag(pool);
734 if (!page_pool_release(pool))
737 pool->defer_start = jiffies;
738 pool->defer_warn = jiffies + DEFER_WARN_INTERVAL;
740 INIT_DELAYED_WORK(&pool->release_dw, page_pool_release_retry);
741 schedule_delayed_work(&pool->release_dw, DEFER_TIME);
743 EXPORT_SYMBOL(page_pool_destroy);
745 /* Caller must provide appropriate safe context, e.g. NAPI. */
746 void page_pool_update_nid(struct page_pool *pool, int new_nid)
750 trace_page_pool_update_nid(pool, new_nid);
751 pool->p.nid = new_nid;
753 /* Flush pool alloc cache, as refill will check NUMA node */
754 while (pool->alloc.count) {
755 page = pool->alloc.cache[--pool->alloc.count];
756 page_pool_return_page(pool, page);
759 EXPORT_SYMBOL(page_pool_update_nid);
761 bool page_pool_return_skb_page(struct page *page)
763 struct page_pool *pp;
765 page = compound_head(page);
767 /* page->pp_magic is OR'ed with PP_SIGNATURE after the allocation
768 * in order to preserve any existing bits, such as bit 0 for the
769 * head page of compound page and bit 1 for pfmemalloc page, so
770 * mask those bits for freeing side when doing below checking,
771 * and page_is_pfmemalloc() is checked in __page_pool_put_page()
772 * to avoid recycling the pfmemalloc page.
774 if (unlikely((page->pp_magic & ~0x3UL) != PP_SIGNATURE))
779 /* Driver set this to memory recycling info. Reset it on recycle.
780 * This will *not* work for NIC using a split-page memory model.
781 * The page will be returned to the pool here regardless of the
782 * 'flipped' fragment being in use or not.
784 page_pool_put_full_page(pp, page, false);
788 EXPORT_SYMBOL(page_pool_return_skb_page);