xref: /linux/net/core/page_pool.c (revision 33f016b23a219fe034213849b51436b8e79df251)
1 /* SPDX-License-Identifier: GPL-2.0
2  *
3  * page_pool.c
4  *	Author:	Jesper Dangaard Brouer <netoptimizer@brouer.com>
5  *	Copyright (C) 2016 Red Hat, Inc.
6  */
7 
8 #include <linux/error-injection.h>
9 #include <linux/types.h>
10 #include <linux/kernel.h>
11 #include <linux/slab.h>
12 #include <linux/device.h>
13 
14 #include <net/netdev_lock.h>
15 #include <net/netdev_rx_queue.h>
16 #include <net/page_pool/helpers.h>
17 #include <net/page_pool/memory_provider.h>
18 #include <net/xdp.h>
19 
20 #include <linux/dma-direction.h>
21 #include <linux/dma-mapping.h>
22 #include <linux/page-flags.h>
23 #include <linux/mm.h> /* for put_page() */
24 #include <linux/poison.h>
25 #include <linux/ethtool.h>
26 #include <linux/netdevice.h>
27 
28 #include <trace/events/page_pool.h>
29 
30 #include "dev.h"
31 #include "mp_dmabuf_devmem.h"
32 #include "netmem_priv.h"
33 #include "page_pool_priv.h"
34 
35 DEFINE_STATIC_KEY_FALSE(page_pool_mem_providers);
36 
37 #define DEFER_TIME (msecs_to_jiffies(1000))
38 #define DEFER_WARN_INTERVAL (60 * HZ)
39 
40 #define BIAS_MAX	(LONG_MAX >> 1)
41 
42 #ifdef CONFIG_PAGE_POOL_STATS
43 static DEFINE_PER_CPU(struct page_pool_recycle_stats, pp_system_recycle_stats);
44 
45 /* alloc_stat_inc is intended to be used in softirq context */
46 #define alloc_stat_inc(pool, __stat)	(pool->alloc_stats.__stat++)
47 /* recycle_stat_inc is safe to use when preemption is possible. */
48 #define recycle_stat_inc(pool, __stat)							\
49 	do {										\
50 		struct page_pool_recycle_stats __percpu *s = pool->recycle_stats;	\
51 		this_cpu_inc(s->__stat);						\
52 	} while (0)
53 
54 #define recycle_stat_add(pool, __stat, val)						\
55 	do {										\
56 		struct page_pool_recycle_stats __percpu *s = pool->recycle_stats;	\
57 		this_cpu_add(s->__stat, val);						\
58 	} while (0)
59 
60 static const char pp_stats[][ETH_GSTRING_LEN] = {
61 	"rx_pp_alloc_fast",
62 	"rx_pp_alloc_slow",
63 	"rx_pp_alloc_slow_ho",
64 	"rx_pp_alloc_empty",
65 	"rx_pp_alloc_refill",
66 	"rx_pp_alloc_waive",
67 	"rx_pp_recycle_cached",
68 	"rx_pp_recycle_cache_full",
69 	"rx_pp_recycle_ring",
70 	"rx_pp_recycle_ring_full",
71 	"rx_pp_recycle_released_ref",
72 };
73 
74 /**
75  * page_pool_get_stats() - fetch page pool stats
76  * @pool:	pool from which page was allocated
77  * @stats:	struct page_pool_stats to fill in
78  *
79  * Deprecated driver API for querying stats. Page pool stats can be queried
80  * via netdev Netlink.
81  *
82  * Retrieve statistics about the page_pool. This API is only available
83  * if the kernel has been configured with ``CONFIG_PAGE_POOL_STATS=y``.
84  * A pointer to a caller allocated struct page_pool_stats structure
85  * is passed to this API which is filled in. The caller can then report
86  * those stats to the user (perhaps via ethtool, debugfs, etc.).
87  */
88 void page_pool_get_stats(const struct page_pool *pool,
89 			 struct page_pool_stats *stats)
90 {
91 	int cpu = 0;
92 
93 	/* The caller is responsible to initialize stats. */
94 	stats->alloc_stats.fast += pool->alloc_stats.fast;
95 	stats->alloc_stats.slow += pool->alloc_stats.slow;
96 	stats->alloc_stats.slow_high_order += pool->alloc_stats.slow_high_order;
97 	stats->alloc_stats.empty += pool->alloc_stats.empty;
98 	stats->alloc_stats.refill += pool->alloc_stats.refill;
99 	stats->alloc_stats.waive += pool->alloc_stats.waive;
100 
101 	for_each_possible_cpu(cpu) {
102 		const struct page_pool_recycle_stats *pcpu =
103 			per_cpu_ptr(pool->recycle_stats, cpu);
104 
105 		stats->recycle_stats.cached += pcpu->cached;
106 		stats->recycle_stats.cache_full += pcpu->cache_full;
107 		stats->recycle_stats.ring += pcpu->ring;
108 		stats->recycle_stats.ring_full += pcpu->ring_full;
109 		stats->recycle_stats.released_refcnt += pcpu->released_refcnt;
110 	}
111 }
112 EXPORT_SYMBOL(page_pool_get_stats);
113 
114 u8 *page_pool_ethtool_stats_get_strings(u8 *data)
115 {
116 	int i;
117 
118 	for (i = 0; i < ARRAY_SIZE(pp_stats); i++) {
119 		memcpy(data, pp_stats[i], ETH_GSTRING_LEN);
120 		data += ETH_GSTRING_LEN;
121 	}
122 
123 	return data;
124 }
125 EXPORT_SYMBOL(page_pool_ethtool_stats_get_strings);
126 
127 int page_pool_ethtool_stats_get_count(void)
128 {
129 	return ARRAY_SIZE(pp_stats);
130 }
131 EXPORT_SYMBOL(page_pool_ethtool_stats_get_count);
132 
133 u64 *page_pool_ethtool_stats_get(u64 *data, const void *stats)
134 {
135 	const struct page_pool_stats *pool_stats = stats;
136 
137 	*data++ = pool_stats->alloc_stats.fast;
138 	*data++ = pool_stats->alloc_stats.slow;
139 	*data++ = pool_stats->alloc_stats.slow_high_order;
140 	*data++ = pool_stats->alloc_stats.empty;
141 	*data++ = pool_stats->alloc_stats.refill;
142 	*data++ = pool_stats->alloc_stats.waive;
143 	*data++ = pool_stats->recycle_stats.cached;
144 	*data++ = pool_stats->recycle_stats.cache_full;
145 	*data++ = pool_stats->recycle_stats.ring;
146 	*data++ = pool_stats->recycle_stats.ring_full;
147 	*data++ = pool_stats->recycle_stats.released_refcnt;
148 
149 	return data;
150 }
151 EXPORT_SYMBOL(page_pool_ethtool_stats_get);
152 
153 #else
154 #define alloc_stat_inc(...)	do { } while (0)
155 #define recycle_stat_inc(...)	do { } while (0)
156 #define recycle_stat_add(...)	do { } while (0)
157 #endif
158 
159 static bool page_pool_producer_lock(struct page_pool *pool)
160 	__acquires(&pool->ring.producer_lock)
161 {
162 	bool in_softirq = in_softirq();
163 
164 	if (in_softirq)
165 		spin_lock(&pool->ring.producer_lock);
166 	else
167 		spin_lock_bh(&pool->ring.producer_lock);
168 
169 	return in_softirq;
170 }
171 
172 static void page_pool_producer_unlock(struct page_pool *pool,
173 				      bool in_softirq)
174 	__releases(&pool->ring.producer_lock)
175 {
176 	if (in_softirq)
177 		spin_unlock(&pool->ring.producer_lock);
178 	else
179 		spin_unlock_bh(&pool->ring.producer_lock);
180 }
181 
182 static void page_pool_struct_check(void)
183 {
184 	CACHELINE_ASSERT_GROUP_MEMBER(struct page_pool, frag, frag_users);
185 	CACHELINE_ASSERT_GROUP_MEMBER(struct page_pool, frag, frag_page);
186 	CACHELINE_ASSERT_GROUP_MEMBER(struct page_pool, frag, frag_offset);
187 	CACHELINE_ASSERT_GROUP_SIZE(struct page_pool, frag,
188 				    PAGE_POOL_FRAG_GROUP_ALIGN);
189 }
190 
191 static int page_pool_init(struct page_pool *pool,
192 			  const struct page_pool_params *params,
193 			  int cpuid)
194 {
195 	unsigned int ring_qsize = 1024; /* Default */
196 	struct netdev_rx_queue *rxq;
197 	int err;
198 
199 	page_pool_struct_check();
200 
201 	memcpy(&pool->p, &params->fast, sizeof(pool->p));
202 	memcpy(&pool->slow, &params->slow, sizeof(pool->slow));
203 
204 	pool->cpuid = cpuid;
205 	pool->dma_sync_for_cpu = true;
206 
207 	/* Validate only known flags were used */
208 	if (pool->slow.flags & ~PP_FLAG_ALL)
209 		return -EINVAL;
210 
211 	if (pool->p.pool_size)
212 		ring_qsize = min(pool->p.pool_size, 16384);
213 
214 	/* DMA direction is either DMA_FROM_DEVICE or DMA_BIDIRECTIONAL.
215 	 * DMA_BIDIRECTIONAL is for allowing page used for DMA sending,
216 	 * which is the XDP_TX use-case.
217 	 */
218 	if (pool->slow.flags & PP_FLAG_DMA_MAP) {
219 		if ((pool->p.dma_dir != DMA_FROM_DEVICE) &&
220 		    (pool->p.dma_dir != DMA_BIDIRECTIONAL))
221 			return -EINVAL;
222 
223 		pool->dma_map = true;
224 	}
225 
226 	if (pool->slow.flags & PP_FLAG_DMA_SYNC_DEV) {
227 		/* In order to request DMA-sync-for-device the page
228 		 * needs to be mapped
229 		 */
230 		if (!(pool->slow.flags & PP_FLAG_DMA_MAP))
231 			return -EINVAL;
232 
233 		if (!pool->p.max_len)
234 			return -EINVAL;
235 
236 		pool->dma_sync = true;
237 
238 		/* pool->p.offset has to be set according to the address
239 		 * offset used by the DMA engine to start copying rx data
240 		 */
241 	}
242 
243 	pool->has_init_callback = !!pool->slow.init_callback;
244 
245 #ifdef CONFIG_PAGE_POOL_STATS
246 	if (!(pool->slow.flags & PP_FLAG_SYSTEM_POOL)) {
247 		pool->recycle_stats = alloc_percpu(struct page_pool_recycle_stats);
248 		if (!pool->recycle_stats)
249 			return -ENOMEM;
250 	} else {
251 		/* For system page pool instance we use a singular stats object
252 		 * instead of allocating a separate percpu variable for each
253 		 * (also percpu) page pool instance.
254 		 */
255 		pool->recycle_stats = &pp_system_recycle_stats;
256 		pool->system = true;
257 	}
258 #endif
259 
260 	if (ptr_ring_init(&pool->ring, ring_qsize, GFP_KERNEL) < 0) {
261 #ifdef CONFIG_PAGE_POOL_STATS
262 		if (!pool->system)
263 			free_percpu(pool->recycle_stats);
264 #endif
265 		return -ENOMEM;
266 	}
267 
268 	atomic_set(&pool->pages_state_release_cnt, 0);
269 
270 	/* Driver calling page_pool_create() also call page_pool_destroy() */
271 	refcount_set(&pool->user_cnt, 1);
272 
273 	xa_init_flags(&pool->dma_mapped, XA_FLAGS_ALLOC1);
274 
275 	if (pool->slow.flags & PP_FLAG_ALLOW_UNREADABLE_NETMEM) {
276 		netdev_assert_locked(pool->slow.netdev);
277 		rxq = __netif_get_rx_queue(pool->slow.netdev,
278 					   pool->slow.queue_idx);
279 		pool->mp_priv = rxq->mp_params.mp_priv;
280 		pool->mp_ops = rxq->mp_params.mp_ops;
281 	}
282 
283 	if (pool->mp_ops) {
284 		if (!pool->dma_map || !pool->dma_sync) {
285 			err = -EOPNOTSUPP;
286 			goto free_ptr_ring;
287 		}
288 
289 		if (WARN_ON(!is_kernel_rodata((unsigned long)pool->mp_ops))) {
290 			err = -EFAULT;
291 			goto free_ptr_ring;
292 		}
293 
294 		err = pool->mp_ops->init(pool);
295 		if (err) {
296 			pr_warn("%s() mem-provider init failed %d\n", __func__,
297 				err);
298 			goto free_ptr_ring;
299 		}
300 
301 		static_branch_inc(&page_pool_mem_providers);
302 	} else if (pool->p.order > MAX_PAGE_ORDER) {
303 		err = -EINVAL;
304 		goto free_ptr_ring;
305 	}
306 
307 	return 0;
308 
309 free_ptr_ring:
310 	ptr_ring_cleanup(&pool->ring, NULL);
311 	xa_destroy(&pool->dma_mapped);
312 #ifdef CONFIG_PAGE_POOL_STATS
313 	if (!pool->system)
314 		free_percpu(pool->recycle_stats);
315 #endif
316 	return err;
317 }
318 
319 static void page_pool_uninit(struct page_pool *pool)
320 {
321 	ptr_ring_cleanup(&pool->ring, NULL);
322 	xa_destroy(&pool->dma_mapped);
323 
324 #ifdef CONFIG_PAGE_POOL_STATS
325 	if (!pool->system)
326 		free_percpu(pool->recycle_stats);
327 #endif
328 
329 	if (pool->mp_ops) {
330 		pool->mp_ops->destroy(pool);
331 		static_branch_dec(&page_pool_mem_providers);
332 	}
333 }
334 
335 /**
336  * page_pool_create_percpu() - create a page pool for a given cpu.
337  * @params: parameters, see struct page_pool_params
338  * @cpuid: cpu identifier
339  */
340 struct page_pool *
341 page_pool_create_percpu(const struct page_pool_params *params, int cpuid)
342 {
343 	struct page_pool *pool;
344 	int err;
345 
346 	pool = kzalloc_node(sizeof(*pool), GFP_KERNEL, params->nid);
347 	if (!pool)
348 		return ERR_PTR(-ENOMEM);
349 
350 	err = page_pool_init(pool, params, cpuid);
351 	if (err < 0)
352 		goto err_free;
353 
354 	err = page_pool_list(pool);
355 	if (err)
356 		goto err_uninit;
357 
358 	return pool;
359 
360 err_uninit:
361 	page_pool_uninit(pool);
362 err_free:
363 	pr_warn("%s() gave up with errno %d\n", __func__, err);
364 	kfree(pool);
365 	return ERR_PTR(err);
366 }
367 EXPORT_SYMBOL(page_pool_create_percpu);
368 
369 /**
370  * page_pool_create() - create a page pool
371  * @params: parameters, see struct page_pool_params
372  */
373 struct page_pool *page_pool_create(const struct page_pool_params *params)
374 {
375 	return page_pool_create_percpu(params, -1);
376 }
377 EXPORT_SYMBOL(page_pool_create);
378 
379 static void page_pool_return_netmem(struct page_pool *pool, netmem_ref netmem);
380 
381 static noinline netmem_ref page_pool_refill_alloc_cache(struct page_pool *pool)
382 {
383 	struct ptr_ring *r = &pool->ring;
384 	netmem_ref netmem;
385 	int pref_nid; /* preferred NUMA node */
386 
387 	/* Quicker fallback, avoid locks when ring is empty */
388 	if (__ptr_ring_empty(r)) {
389 		alloc_stat_inc(pool, empty);
390 		return 0;
391 	}
392 
393 	/* Softirq guarantee CPU and thus NUMA node is stable. This,
394 	 * assumes CPU refilling driver RX-ring will also run RX-NAPI.
395 	 */
396 #ifdef CONFIG_NUMA
397 	pref_nid = (pool->p.nid == NUMA_NO_NODE) ? numa_mem_id() : pool->p.nid;
398 #else
399 	/* Ignore pool->p.nid setting if !CONFIG_NUMA, helps compiler */
400 	pref_nid = numa_mem_id(); /* will be zero like page_to_nid() */
401 #endif
402 
403 	/* Refill alloc array, but only if NUMA match */
404 	do {
405 		netmem = (__force netmem_ref)__ptr_ring_consume(r);
406 		if (unlikely(!netmem))
407 			break;
408 
409 		if (likely(netmem_is_pref_nid(netmem, pref_nid))) {
410 			pool->alloc.cache[pool->alloc.count++] = netmem;
411 		} else {
412 			/* NUMA mismatch;
413 			 * (1) release 1 page to page-allocator and
414 			 * (2) break out to fallthrough to alloc_pages_node.
415 			 * This limit stress on page buddy alloactor.
416 			 */
417 			page_pool_return_netmem(pool, netmem);
418 			alloc_stat_inc(pool, waive);
419 			netmem = 0;
420 			break;
421 		}
422 	} while (pool->alloc.count < PP_ALLOC_CACHE_REFILL);
423 
424 	/* Return last page */
425 	if (likely(pool->alloc.count > 0)) {
426 		netmem = pool->alloc.cache[--pool->alloc.count];
427 		alloc_stat_inc(pool, refill);
428 	}
429 
430 	return netmem;
431 }
432 
433 /* fast path */
434 static netmem_ref __page_pool_get_cached(struct page_pool *pool)
435 {
436 	netmem_ref netmem;
437 
438 	/* Caller MUST guarantee safe non-concurrent access, e.g. softirq */
439 	if (likely(pool->alloc.count)) {
440 		/* Fast-path */
441 		netmem = pool->alloc.cache[--pool->alloc.count];
442 		alloc_stat_inc(pool, fast);
443 	} else {
444 		netmem = page_pool_refill_alloc_cache(pool);
445 	}
446 
447 	return netmem;
448 }
449 
450 static void __page_pool_dma_sync_for_device(const struct page_pool *pool,
451 					    netmem_ref netmem,
452 					    u32 dma_sync_size)
453 {
454 #if defined(CONFIG_HAS_DMA) && defined(CONFIG_DMA_NEED_SYNC)
455 	dma_addr_t dma_addr = page_pool_get_dma_addr_netmem(netmem);
456 
457 	dma_sync_size = min(dma_sync_size, pool->p.max_len);
458 	__dma_sync_single_for_device(pool->p.dev, dma_addr + pool->p.offset,
459 				     dma_sync_size, pool->p.dma_dir);
460 #endif
461 }
462 
463 static __always_inline void
464 page_pool_dma_sync_for_device(const struct page_pool *pool,
465 			      netmem_ref netmem,
466 			      u32 dma_sync_size)
467 {
468 	if (pool->dma_sync && dma_dev_need_sync(pool->p.dev)) {
469 		rcu_read_lock();
470 		/* re-check under rcu_read_lock() to sync with page_pool_scrub() */
471 		if (pool->dma_sync)
472 			__page_pool_dma_sync_for_device(pool, netmem,
473 							dma_sync_size);
474 		rcu_read_unlock();
475 	}
476 }
477 
478 static int page_pool_register_dma_index(struct page_pool *pool,
479 					netmem_ref netmem, gfp_t gfp)
480 {
481 	int err = 0;
482 	u32 id;
483 
484 	if (unlikely(!PP_DMA_INDEX_BITS))
485 		goto out;
486 
487 	if (in_softirq())
488 		err = xa_alloc(&pool->dma_mapped, &id, netmem_to_page(netmem),
489 			       PP_DMA_INDEX_LIMIT, gfp);
490 	else
491 		err = xa_alloc_bh(&pool->dma_mapped, &id, netmem_to_page(netmem),
492 				  PP_DMA_INDEX_LIMIT, gfp);
493 	if (err) {
494 		WARN_ONCE(err != -ENOMEM, "couldn't track DMA mapping, please report to netdev@");
495 		goto out;
496 	}
497 
498 	netmem_set_dma_index(netmem, id);
499 out:
500 	return err;
501 }
502 
503 static void __page_pool_unmap_netmem_dma(struct page_pool *pool,
504 					 netmem_ref netmem)
505 {
506 	struct page *old, *page = netmem_to_page(netmem);
507 	unsigned long id;
508 	dma_addr_t dma;
509 
510 	if (!pool->dma_map)
511 		return;
512 
513 	/* Cache dma_addr before xa_cmpxchg. The scrub path holds no page ref;
514 	 * the unref path calls put_page() regardless of cmpxchg outcome, so
515 	 * after the cmpxchg we cannot safely touch netmem fields.
516 	 */
517 	dma = page_pool_get_dma_addr_netmem(netmem);
518 
519 	if (likely(PP_DMA_INDEX_BITS)) {
520 		id = netmem_get_dma_index(netmem);
521 		if (!id)
522 			return;
523 
524 		if (in_softirq())
525 			old = xa_cmpxchg(&pool->dma_mapped,
526 					 id, page, NULL, 0);
527 		else
528 			old = xa_cmpxchg_bh(&pool->dma_mapped,
529 					    id, page, NULL, 0);
530 		if (old != page)
531 			return;
532 	}
533 
534 	dma_unmap_page_attrs(pool->p.dev, dma,
535 			     PAGE_SIZE << pool->p.order, pool->p.dma_dir,
536 			     DMA_ATTR_SKIP_CPU_SYNC | DMA_ATTR_WEAK_ORDERING);
537 }
538 
539 static bool page_pool_dma_map(struct page_pool *pool, netmem_ref netmem, gfp_t gfp)
540 {
541 	dma_addr_t dma;
542 	int err;
543 
544 	/* Setup DMA mapping: use 'struct page' area for storing DMA-addr
545 	 * since dma_addr_t can be either 32 or 64 bits and does not always fit
546 	 * into page private data (i.e 32bit cpu with 64bit DMA caps)
547 	 * This mapping is kept for lifetime of page, until leaving pool.
548 	 */
549 	dma = dma_map_page_attrs(pool->p.dev, netmem_to_page(netmem), 0,
550 				 (PAGE_SIZE << pool->p.order), pool->p.dma_dir,
551 				 DMA_ATTR_SKIP_CPU_SYNC |
552 					 DMA_ATTR_WEAK_ORDERING);
553 	if (dma_mapping_error(pool->p.dev, dma))
554 		return false;
555 
556 	if (page_pool_set_dma_addr_netmem(netmem, dma)) {
557 		WARN_ONCE(1, "unexpected DMA address, please report to netdev@");
558 		goto unmap_failed;
559 	}
560 
561 	err = page_pool_register_dma_index(pool, netmem, gfp);
562 	if (err)
563 		goto unset_failed;
564 
565 	page_pool_dma_sync_for_device(pool, netmem, pool->p.max_len);
566 
567 	return true;
568 
569 unset_failed:
570 	page_pool_set_dma_addr_netmem(netmem, 0);
571 unmap_failed:
572 	dma_unmap_page_attrs(pool->p.dev, dma,
573 			     PAGE_SIZE << pool->p.order, pool->p.dma_dir,
574 			     DMA_ATTR_SKIP_CPU_SYNC | DMA_ATTR_WEAK_ORDERING);
575 	return false;
576 }
577 
578 static struct page *__page_pool_alloc_page_order(struct page_pool *pool,
579 						 gfp_t gfp)
580 {
581 	struct page *page;
582 
583 	gfp |= __GFP_COMP;
584 	page = alloc_pages_node(pool->p.nid, gfp, pool->p.order);
585 	if (unlikely(!page))
586 		return NULL;
587 
588 	if (pool->dma_map && unlikely(!page_pool_dma_map(pool, page_to_netmem(page), gfp))) {
589 		put_page(page);
590 		return NULL;
591 	}
592 
593 	alloc_stat_inc(pool, slow_high_order);
594 	page_pool_set_pp_info(pool, page_to_netmem(page));
595 
596 	/* Track how many pages are held 'in-flight' */
597 	pool->pages_state_hold_cnt++;
598 	trace_page_pool_state_hold(pool, page_to_netmem(page),
599 				   pool->pages_state_hold_cnt);
600 	return page;
601 }
602 
603 /* slow path */
604 static noinline netmem_ref __page_pool_alloc_netmems_slow(struct page_pool *pool,
605 							  gfp_t gfp)
606 {
607 	const int bulk = PP_ALLOC_CACHE_REFILL;
608 	unsigned int pp_order = pool->p.order;
609 	bool dma_map = pool->dma_map;
610 	netmem_ref netmem;
611 	int i, nr_pages;
612 
613 	/* Unconditionally set NOWARN if allocating from NAPI.
614 	 * Drivers forget to set it, and OOM reports on packet Rx are useless.
615 	 */
616 	if ((gfp & GFP_ATOMIC) == GFP_ATOMIC)
617 		gfp |= __GFP_NOWARN;
618 
619 	/* Don't support bulk alloc for high-order pages */
620 	if (unlikely(pp_order))
621 		return page_to_netmem(__page_pool_alloc_page_order(pool, gfp));
622 
623 	/* Unnecessary as alloc cache is empty, but guarantees zero count */
624 	if (unlikely(pool->alloc.count > 0))
625 		return pool->alloc.cache[--pool->alloc.count];
626 
627 	/* Mark empty alloc.cache slots "empty" for alloc_pages_bulk */
628 	memset(&pool->alloc.cache, 0, sizeof(void *) * bulk);
629 
630 	nr_pages = alloc_pages_bulk_node(gfp, pool->p.nid, bulk,
631 					 (struct page **)pool->alloc.cache);
632 	if (unlikely(!nr_pages))
633 		return 0;
634 
635 	/* Pages have been filled into alloc.cache array, but count is zero and
636 	 * page element have not been (possibly) DMA mapped.
637 	 */
638 	for (i = 0; i < nr_pages; i++) {
639 		netmem = pool->alloc.cache[i];
640 		if (dma_map && unlikely(!page_pool_dma_map(pool, netmem, gfp))) {
641 			put_page(netmem_to_page(netmem));
642 			continue;
643 		}
644 
645 		page_pool_set_pp_info(pool, netmem);
646 		pool->alloc.cache[pool->alloc.count++] = netmem;
647 		/* Track how many pages are held 'in-flight' */
648 		pool->pages_state_hold_cnt++;
649 		trace_page_pool_state_hold(pool, netmem,
650 					   pool->pages_state_hold_cnt);
651 	}
652 
653 	/* Return last page */
654 	if (likely(pool->alloc.count > 0)) {
655 		netmem = pool->alloc.cache[--pool->alloc.count];
656 		alloc_stat_inc(pool, slow);
657 	} else {
658 		netmem = 0;
659 	}
660 
661 	/* When page just alloc'ed is should/must have refcnt 1. */
662 	return netmem;
663 }
664 
665 /* For using page_pool replace: alloc_pages() API calls, but provide
666  * synchronization guarantee for allocation side.
667  */
668 netmem_ref page_pool_alloc_netmems(struct page_pool *pool, gfp_t gfp)
669 {
670 	netmem_ref netmem;
671 
672 	/* Fast-path: Get a page from cache */
673 	netmem = __page_pool_get_cached(pool);
674 	if (netmem)
675 		return netmem;
676 
677 	/* Slow-path: cache empty, do real allocation */
678 	if (static_branch_unlikely(&page_pool_mem_providers) && pool->mp_ops)
679 		netmem = pool->mp_ops->alloc_netmems(pool, gfp);
680 	else
681 		netmem = __page_pool_alloc_netmems_slow(pool, gfp);
682 	return netmem;
683 }
684 EXPORT_SYMBOL(page_pool_alloc_netmems);
685 ALLOW_ERROR_INJECTION(page_pool_alloc_netmems, NULL);
686 
687 struct page *page_pool_alloc_pages(struct page_pool *pool, gfp_t gfp)
688 {
689 	return netmem_to_page(page_pool_alloc_netmems(pool, gfp));
690 }
691 EXPORT_SYMBOL(page_pool_alloc_pages);
692 
693 /* Calculate distance between two u32 values, valid if distance is below 2^(31)
694  *  https://en.wikipedia.org/wiki/Serial_number_arithmetic#General_Solution
695  */
696 #define _distance(a, b)	(s32)((a) - (b))
697 
698 s32 page_pool_inflight(const struct page_pool *pool, bool strict)
699 {
700 	u32 release_cnt = atomic_read(&pool->pages_state_release_cnt);
701 	u32 hold_cnt = READ_ONCE(pool->pages_state_hold_cnt);
702 	s32 inflight;
703 
704 	inflight = _distance(hold_cnt, release_cnt);
705 
706 	if (strict) {
707 		trace_page_pool_release(pool, inflight, hold_cnt, release_cnt);
708 		WARN(inflight < 0, "Negative(%d) inflight packet-pages",
709 		     inflight);
710 	} else {
711 		inflight = max(0, inflight);
712 	}
713 
714 	return inflight;
715 }
716 
717 void page_pool_set_pp_info(struct page_pool *pool, netmem_ref netmem)
718 {
719 	netmem_set_pp(netmem, pool);
720 	netmem_or_pp_magic(netmem, PP_SIGNATURE);
721 
722 	/* Ensuring all pages have been split into one fragment initially:
723 	 * page_pool_set_pp_info() is only called once for every page when it
724 	 * is allocated from the page allocator and page_pool_fragment_page()
725 	 * is dirtying the same cache line as the page->pp_magic above, so
726 	 * the overhead is negligible.
727 	 */
728 	page_pool_fragment_netmem(netmem, 1);
729 	if (pool->has_init_callback)
730 		pool->slow.init_callback(netmem, pool->slow.init_arg);
731 }
732 
733 void page_pool_clear_pp_info(netmem_ref netmem)
734 {
735 	netmem_clear_pp_magic(netmem);
736 	netmem_set_pp(netmem, NULL);
737 }
738 
739 static __always_inline void __page_pool_release_netmem_dma(struct page_pool *pool,
740 							   netmem_ref netmem)
741 {
742 	/* Caller must hold a page ref: __page_pool_unmap_netmem_dma() is
743 	 * safe without a ref, but the field clears below require it.
744 	 */
745 	if (!pool->dma_map)
746 		return;
747 
748 	__page_pool_unmap_netmem_dma(pool, netmem);
749 	page_pool_set_dma_addr_netmem(netmem, 0);
750 	if (likely(PP_DMA_INDEX_BITS))
751 		netmem_set_dma_index(netmem, 0);
752 }
753 
754 /* Disconnects a page (from a page_pool).  API users can have a need
755  * to disconnect a page (from a page_pool), to allow it to be used as
756  * a regular page (that will eventually be returned to the normal
757  * page-allocator via put_page).
758  */
759 static void page_pool_return_netmem(struct page_pool *pool, netmem_ref netmem)
760 {
761 	int count;
762 	bool put;
763 
764 	put = true;
765 	if (static_branch_unlikely(&page_pool_mem_providers) && pool->mp_ops)
766 		put = pool->mp_ops->release_netmem(pool, netmem);
767 	else
768 		__page_pool_release_netmem_dma(pool, netmem);
769 
770 	/* This may be the last page returned, releasing the pool, so
771 	 * it is not safe to reference pool afterwards.
772 	 */
773 	count = atomic_inc_return_relaxed(&pool->pages_state_release_cnt);
774 	trace_page_pool_state_release(pool, netmem, count);
775 
776 	if (put) {
777 		page_pool_clear_pp_info(netmem);
778 		put_page(netmem_to_page(netmem));
779 	}
780 	/* An optimization would be to call __free_pages(page, pool->p.order)
781 	 * knowing page is not part of page-cache (thus avoiding a
782 	 * __page_cache_release() call).
783 	 */
784 }
785 
786 static bool page_pool_recycle_in_ring(struct page_pool *pool, netmem_ref netmem)
787 {
788 	bool in_softirq, ret;
789 
790 	/* BH protection not needed if current is softirq */
791 	in_softirq = page_pool_producer_lock(pool);
792 	ret = !__ptr_ring_produce(&pool->ring, (__force void *)netmem);
793 	if (ret)
794 		recycle_stat_inc(pool, ring);
795 	page_pool_producer_unlock(pool, in_softirq);
796 
797 	return ret;
798 }
799 
800 /* Only allow direct recycling in special circumstances, into the
801  * alloc side cache.  E.g. during RX-NAPI processing for XDP_DROP use-case.
802  *
803  * Caller must provide appropriate safe context.
804  */
805 static bool page_pool_recycle_in_cache(netmem_ref netmem,
806 				       struct page_pool *pool)
807 {
808 	if (unlikely(pool->alloc.count == PP_ALLOC_CACHE_SIZE)) {
809 		recycle_stat_inc(pool, cache_full);
810 		return false;
811 	}
812 
813 	/* Caller MUST have verified/know (page_ref_count(page) == 1) */
814 	pool->alloc.cache[pool->alloc.count++] = netmem;
815 	recycle_stat_inc(pool, cached);
816 	return true;
817 }
818 
819 static bool __page_pool_page_can_be_recycled(netmem_ref netmem)
820 {
821 	return netmem_is_net_iov(netmem) ||
822 	       (page_ref_count(netmem_to_page(netmem)) == 1 &&
823 		!page_is_pfmemalloc(netmem_to_page(netmem)));
824 }
825 
826 /* If the page refcnt == 1, this will try to recycle the page.
827  * If pool->dma_sync is set, we'll try to sync the DMA area for
828  * the configured size min(dma_sync_size, pool->max_len).
829  * If the page refcnt != 1, then the page will be returned to memory
830  * subsystem.
831  */
832 static __always_inline netmem_ref
833 __page_pool_put_page(struct page_pool *pool, netmem_ref netmem,
834 		     unsigned int dma_sync_size, bool allow_direct)
835 {
836 	lockdep_assert_no_hardirq();
837 
838 	/* This allocator is optimized for the XDP mode that uses
839 	 * one-frame-per-page, but have fallbacks that act like the
840 	 * regular page allocator APIs.
841 	 *
842 	 * refcnt == 1 means page_pool owns page, and can recycle it.
843 	 *
844 	 * page is NOT reusable when allocated when system is under
845 	 * some pressure. (page_is_pfmemalloc)
846 	 */
847 	if (likely(__page_pool_page_can_be_recycled(netmem))) {
848 		/* Read barrier done in page_ref_count / READ_ONCE */
849 
850 		page_pool_dma_sync_for_device(pool, netmem, dma_sync_size);
851 
852 		if (allow_direct && page_pool_recycle_in_cache(netmem, pool))
853 			return 0;
854 
855 		/* Page found as candidate for recycling */
856 		return netmem;
857 	}
858 
859 	/* Fallback/non-XDP mode: API user have elevated refcnt.
860 	 *
861 	 * Many drivers split up the page into fragments, and some
862 	 * want to keep doing this to save memory and do refcnt based
863 	 * recycling. Support this use case too, to ease drivers
864 	 * switching between XDP/non-XDP.
865 	 *
866 	 * In-case page_pool maintains the DMA mapping, API user must
867 	 * call page_pool_put_page once.  In this elevated refcnt
868 	 * case, the DMA is unmapped/released, as driver is likely
869 	 * doing refcnt based recycle tricks, meaning another process
870 	 * will be invoking put_page.
871 	 */
872 	recycle_stat_inc(pool, released_refcnt);
873 	page_pool_return_netmem(pool, netmem);
874 
875 	return 0;
876 }
877 
878 static bool page_pool_napi_local(const struct page_pool *pool)
879 {
880 	const struct napi_struct *napi;
881 	u32 cpuid;
882 
883 	/* On PREEMPT_RT the softirq can be preempted by the consumer */
884 	if (IS_ENABLED(CONFIG_PREEMPT_RT))
885 		return false;
886 
887 	if (unlikely(!in_softirq()))
888 		return false;
889 
890 	/* Allow direct recycle if we have reasons to believe that we are
891 	 * in the same context as the consumer would run, so there's
892 	 * no possible race.
893 	 * __page_pool_put_page() makes sure we're not in hardirq context
894 	 * and interrupts are enabled prior to accessing the cache.
895 	 */
896 	cpuid = smp_processor_id();
897 	if (READ_ONCE(pool->cpuid) == cpuid)
898 		return true;
899 
900 	napi = READ_ONCE(pool->p.napi);
901 
902 	return napi && READ_ONCE(napi->list_owner) == cpuid;
903 }
904 
905 void page_pool_put_unrefed_netmem(struct page_pool *pool, netmem_ref netmem,
906 				  unsigned int dma_sync_size, bool allow_direct)
907 {
908 	if (!allow_direct)
909 		allow_direct = page_pool_napi_local(pool);
910 
911 	netmem = __page_pool_put_page(pool, netmem, dma_sync_size,
912 				      allow_direct);
913 	if (netmem && !page_pool_recycle_in_ring(pool, netmem)) {
914 		/* Cache full, fallback to free pages */
915 		recycle_stat_inc(pool, ring_full);
916 		page_pool_return_netmem(pool, netmem);
917 	}
918 }
919 EXPORT_SYMBOL(page_pool_put_unrefed_netmem);
920 
921 void page_pool_put_unrefed_page(struct page_pool *pool, struct page *page,
922 				unsigned int dma_sync_size, bool allow_direct)
923 {
924 	page_pool_put_unrefed_netmem(pool, page_to_netmem(page), dma_sync_size,
925 				     allow_direct);
926 }
927 EXPORT_SYMBOL(page_pool_put_unrefed_page);
928 
929 static void page_pool_recycle_ring_bulk(struct page_pool *pool,
930 					netmem_ref *bulk,
931 					u32 bulk_len)
932 {
933 	bool in_softirq;
934 	u32 i;
935 
936 	/* Bulk produce into ptr_ring page_pool cache */
937 	in_softirq = page_pool_producer_lock(pool);
938 
939 	for (i = 0; i < bulk_len; i++) {
940 		if (__ptr_ring_produce(&pool->ring, (__force void *)bulk[i])) {
941 			/* ring full */
942 			recycle_stat_inc(pool, ring_full);
943 			break;
944 		}
945 	}
946 
947 	page_pool_producer_unlock(pool, in_softirq);
948 	recycle_stat_add(pool, ring, i);
949 
950 	/* Hopefully all pages were returned into ptr_ring */
951 	if (likely(i == bulk_len))
952 		return;
953 
954 	/*
955 	 * ptr_ring cache is full, free remaining pages outside producer lock
956 	 * since put_page() with refcnt == 1 can be an expensive operation.
957 	 */
958 	for (; i < bulk_len; i++)
959 		page_pool_return_netmem(pool, bulk[i]);
960 }
961 
962 /**
963  * page_pool_put_netmem_bulk() - release references on multiple netmems
964  * @data:	array holding netmem references
965  * @count:	number of entries in @data
966  *
967  * Tries to refill a number of netmems into the ptr_ring cache holding ptr_ring
968  * producer lock. If the ptr_ring is full, page_pool_put_netmem_bulk()
969  * will release leftover netmems to the memory provider.
970  * page_pool_put_netmem_bulk() is suitable to be run inside the driver NAPI tx
971  * completion loop for the XDP_REDIRECT use case.
972  *
973  * Please note the caller must not use data area after running
974  * page_pool_put_netmem_bulk(), as this function overwrites it.
975  */
976 void page_pool_put_netmem_bulk(netmem_ref *data, u32 count)
977 {
978 	u32 bulk_len = 0;
979 
980 	for (u32 i = 0; i < count; i++) {
981 		netmem_ref netmem = netmem_compound_head(data[i]);
982 
983 		if (page_pool_unref_and_test(netmem))
984 			data[bulk_len++] = netmem;
985 	}
986 
987 	count = bulk_len;
988 	while (count) {
989 		netmem_ref bulk[XDP_BULK_QUEUE_SIZE];
990 		struct page_pool *pool = NULL;
991 		bool allow_direct;
992 		u32 foreign = 0;
993 
994 		bulk_len = 0;
995 
996 		for (u32 i = 0; i < count; i++) {
997 			struct page_pool *netmem_pp;
998 			netmem_ref netmem = data[i];
999 
1000 			netmem_pp = netmem_get_pp(netmem);
1001 			if (unlikely(!pool)) {
1002 				pool = netmem_pp;
1003 				allow_direct = page_pool_napi_local(pool);
1004 			} else if (netmem_pp != pool) {
1005 				/*
1006 				 * If the netmem belongs to a different
1007 				 * page_pool, save it for another round.
1008 				 */
1009 				data[foreign++] = netmem;
1010 				continue;
1011 			}
1012 
1013 			netmem = __page_pool_put_page(pool, netmem, -1,
1014 						      allow_direct);
1015 			/* Approved for bulk recycling in ptr_ring cache */
1016 			if (netmem)
1017 				bulk[bulk_len++] = netmem;
1018 		}
1019 
1020 		if (bulk_len)
1021 			page_pool_recycle_ring_bulk(pool, bulk, bulk_len);
1022 
1023 		count = foreign;
1024 	}
1025 }
1026 EXPORT_SYMBOL(page_pool_put_netmem_bulk);
1027 
1028 static netmem_ref page_pool_drain_frag(struct page_pool *pool,
1029 				       netmem_ref netmem)
1030 {
1031 	long drain_count = BIAS_MAX - pool->frag_users;
1032 
1033 	/* Some user is still using the page frag */
1034 	if (likely(page_pool_unref_netmem(netmem, drain_count)))
1035 		return 0;
1036 
1037 	if (__page_pool_page_can_be_recycled(netmem)) {
1038 		page_pool_dma_sync_for_device(pool, netmem, -1);
1039 		return netmem;
1040 	}
1041 
1042 	page_pool_return_netmem(pool, netmem);
1043 	return 0;
1044 }
1045 
1046 static void page_pool_free_frag(struct page_pool *pool)
1047 {
1048 	long drain_count = BIAS_MAX - pool->frag_users;
1049 	netmem_ref netmem = pool->frag_page;
1050 
1051 	pool->frag_page = 0;
1052 
1053 	if (!netmem || page_pool_unref_netmem(netmem, drain_count))
1054 		return;
1055 
1056 	page_pool_return_netmem(pool, netmem);
1057 }
1058 
1059 netmem_ref page_pool_alloc_frag_netmem(struct page_pool *pool,
1060 				       unsigned int *offset, unsigned int size,
1061 				       gfp_t gfp)
1062 {
1063 	unsigned int max_size = PAGE_SIZE << pool->p.order;
1064 	netmem_ref netmem = pool->frag_page;
1065 
1066 	if (WARN_ON(size > max_size))
1067 		return 0;
1068 
1069 	size = ALIGN(size, dma_get_cache_alignment());
1070 	*offset = pool->frag_offset;
1071 
1072 	if (netmem && *offset + size > max_size) {
1073 		netmem = page_pool_drain_frag(pool, netmem);
1074 		if (netmem) {
1075 			recycle_stat_inc(pool, cached);
1076 			alloc_stat_inc(pool, fast);
1077 			goto frag_reset;
1078 		}
1079 	}
1080 
1081 	if (!netmem) {
1082 		netmem = page_pool_alloc_netmems(pool, gfp);
1083 		if (unlikely(!netmem)) {
1084 			pool->frag_page = 0;
1085 			return 0;
1086 		}
1087 
1088 		pool->frag_page = netmem;
1089 
1090 frag_reset:
1091 		pool->frag_users = 1;
1092 		*offset = 0;
1093 		pool->frag_offset = size;
1094 		page_pool_fragment_netmem(netmem, BIAS_MAX);
1095 		return netmem;
1096 	}
1097 
1098 	pool->frag_users++;
1099 	pool->frag_offset = *offset + size;
1100 	return netmem;
1101 }
1102 EXPORT_SYMBOL(page_pool_alloc_frag_netmem);
1103 
1104 struct page *page_pool_alloc_frag(struct page_pool *pool, unsigned int *offset,
1105 				  unsigned int size, gfp_t gfp)
1106 {
1107 	return netmem_to_page(page_pool_alloc_frag_netmem(pool, offset, size,
1108 							  gfp));
1109 }
1110 EXPORT_SYMBOL(page_pool_alloc_frag);
1111 
1112 static void page_pool_empty_ring(struct page_pool *pool)
1113 {
1114 	netmem_ref netmem;
1115 
1116 	/* Empty recycle ring */
1117 	while ((netmem = (__force netmem_ref)ptr_ring_consume_bh(&pool->ring))) {
1118 		/* Verify the refcnt invariant of cached pages */
1119 		if (!(netmem_ref_count(netmem) == 1))
1120 			pr_crit("%s() page_pool refcnt %d violation\n",
1121 				__func__, netmem_ref_count(netmem));
1122 
1123 		page_pool_return_netmem(pool, netmem);
1124 	}
1125 }
1126 
1127 static void __page_pool_destroy(struct page_pool *pool)
1128 {
1129 	if (pool->disconnect)
1130 		pool->disconnect(pool);
1131 
1132 	page_pool_unlist(pool);
1133 	page_pool_uninit(pool);
1134 
1135 	kfree(pool);
1136 }
1137 
1138 static void page_pool_empty_alloc_cache_once(struct page_pool *pool)
1139 {
1140 	netmem_ref netmem;
1141 
1142 	if (pool->destroy_cnt)
1143 		return;
1144 
1145 	/* Empty alloc cache, assume caller made sure this is
1146 	 * no-longer in use, and page_pool_alloc_pages() cannot be
1147 	 * call concurrently.
1148 	 */
1149 	while (pool->alloc.count) {
1150 		netmem = pool->alloc.cache[--pool->alloc.count];
1151 		page_pool_return_netmem(pool, netmem);
1152 	}
1153 }
1154 
1155 static void page_pool_scrub(struct page_pool *pool)
1156 {
1157 	unsigned long id;
1158 	void *ptr;
1159 
1160 	page_pool_empty_alloc_cache_once(pool);
1161 	if (!pool->destroy_cnt++ && pool->dma_map) {
1162 		if (pool->dma_sync) {
1163 			/* Disable page_pool_dma_sync_for_device() */
1164 			pool->dma_sync = false;
1165 
1166 			/* Make sure all concurrent returns that may see the old
1167 			 * value of dma_sync (and thus perform a sync) have
1168 			 * finished before doing the unmapping below. Skip the
1169 			 * wait if the device doesn't actually need syncing, or
1170 			 * if there are no outstanding mapped pages.
1171 			 */
1172 			if (dma_dev_need_sync(pool->p.dev) &&
1173 			    !xa_empty(&pool->dma_mapped))
1174 				synchronize_net();
1175 		}
1176 
1177 		/* No page ref, dma-unmap only. */
1178 		xa_for_each(&pool->dma_mapped, id, ptr)
1179 			__page_pool_unmap_netmem_dma(pool, page_to_netmem((struct page *)ptr));
1180 	}
1181 
1182 	/* No more consumers should exist, but producers could still
1183 	 * be in-flight.
1184 	 */
1185 	page_pool_empty_ring(pool);
1186 }
1187 
1188 static int page_pool_release(struct page_pool *pool)
1189 {
1190 	bool in_softirq;
1191 	int inflight;
1192 
1193 	page_pool_scrub(pool);
1194 	inflight = page_pool_inflight(pool, true);
1195 	/* Acquire producer lock to make sure producers have exited. */
1196 	in_softirq = page_pool_producer_lock(pool);
1197 	page_pool_producer_unlock(pool, in_softirq);
1198 	if (!inflight)
1199 		__page_pool_destroy(pool);
1200 
1201 	return inflight;
1202 }
1203 
1204 static void page_pool_release_retry(struct work_struct *wq)
1205 {
1206 	struct delayed_work *dwq = to_delayed_work(wq);
1207 	struct page_pool *pool = container_of(dwq, typeof(*pool), release_dw);
1208 	void *netdev;
1209 	int inflight;
1210 
1211 	inflight = page_pool_release(pool);
1212 	/* In rare cases, a driver bug may cause inflight to go negative.
1213 	 * Don't reschedule release if inflight is 0 or negative.
1214 	 * - If 0, the page_pool has been destroyed
1215 	 * - if negative, we will never recover
1216 	 * in both cases no reschedule is necessary.
1217 	 */
1218 	if (inflight <= 0)
1219 		return;
1220 
1221 	/* Periodic warning for page pools the user can't see */
1222 	netdev = READ_ONCE(pool->slow.netdev);
1223 	if (time_after_eq(jiffies, pool->defer_warn) &&
1224 	    (!netdev || netdev == NET_PTR_POISON)) {
1225 		int sec = (s32)((u32)jiffies - (u32)pool->defer_start) / HZ;
1226 
1227 		pr_warn("%s() stalled pool shutdown: id %u, %d inflight %d sec\n",
1228 			__func__, pool->user.id, inflight, sec);
1229 		pool->defer_warn = jiffies + DEFER_WARN_INTERVAL;
1230 	}
1231 
1232 	/* Still not ready to be disconnected, retry later */
1233 	schedule_delayed_work(&pool->release_dw, DEFER_TIME);
1234 }
1235 
1236 void page_pool_use_xdp_mem(struct page_pool *pool, void (*disconnect)(void *),
1237 			   const struct xdp_mem_info *mem)
1238 {
1239 	refcount_inc(&pool->user_cnt);
1240 	pool->disconnect = disconnect;
1241 	pool->xdp_mem_id = mem->id;
1242 }
1243 
1244 /**
1245  * page_pool_enable_direct_recycling() - mark page pool as owned by NAPI
1246  * @pool: page pool to modify
1247  * @napi: NAPI instance to associate the page pool with
1248  *
1249  * Associate a page pool with a NAPI instance for lockless page recycling.
1250  * This is useful when a new page pool has to be added to a NAPI instance
1251  * without disabling that NAPI instance, to mark the point at which control
1252  * path "hands over" the page pool to the NAPI instance. In most cases driver
1253  * can simply set the @napi field in struct page_pool_params, and does not
1254  * have to call this helper.
1255  *
1256  * The function is idempotent, but does not implement any refcounting.
1257  * Single page_pool_disable_direct_recycling() will disable recycling,
1258  * no matter how many times enable was called.
1259  */
1260 void page_pool_enable_direct_recycling(struct page_pool *pool,
1261 				       struct napi_struct *napi)
1262 {
1263 	if (READ_ONCE(pool->p.napi) == napi)
1264 		return;
1265 	WARN_ON(!napi || pool->p.napi);
1266 
1267 	mutex_lock(&page_pools_lock);
1268 	WRITE_ONCE(pool->p.napi, napi);
1269 	mutex_unlock(&page_pools_lock);
1270 }
1271 EXPORT_SYMBOL(page_pool_enable_direct_recycling);
1272 
1273 void page_pool_disable_direct_recycling(struct page_pool *pool)
1274 {
1275 	/* Disable direct recycling based on pool->cpuid.
1276 	 * Paired with READ_ONCE() in page_pool_napi_local().
1277 	 */
1278 	WRITE_ONCE(pool->cpuid, -1);
1279 
1280 	if (!pool->p.napi)
1281 		return;
1282 
1283 	napi_assert_will_not_race(pool->p.napi);
1284 
1285 	mutex_lock(&page_pools_lock);
1286 	WRITE_ONCE(pool->p.napi, NULL);
1287 	mutex_unlock(&page_pools_lock);
1288 }
1289 EXPORT_SYMBOL(page_pool_disable_direct_recycling);
1290 
1291 void page_pool_destroy(struct page_pool *pool)
1292 {
1293 	if (!pool)
1294 		return;
1295 
1296 	if (!page_pool_put(pool))
1297 		return;
1298 
1299 	page_pool_disable_direct_recycling(pool);
1300 	page_pool_free_frag(pool);
1301 
1302 	if (!page_pool_release(pool))
1303 		return;
1304 
1305 	page_pool_detached(pool);
1306 	pool->defer_start = jiffies;
1307 	pool->defer_warn  = jiffies + DEFER_WARN_INTERVAL;
1308 
1309 	INIT_DELAYED_WORK(&pool->release_dw, page_pool_release_retry);
1310 	schedule_delayed_work(&pool->release_dw, DEFER_TIME);
1311 }
1312 EXPORT_SYMBOL(page_pool_destroy);
1313 
1314 /* Caller must provide appropriate safe context, e.g. NAPI. */
1315 void page_pool_update_nid(struct page_pool *pool, int new_nid)
1316 {
1317 	netmem_ref netmem;
1318 
1319 	trace_page_pool_update_nid(pool, new_nid);
1320 	pool->p.nid = new_nid;
1321 
1322 	/* Flush pool alloc cache, as refill will check NUMA node */
1323 	while (pool->alloc.count) {
1324 		netmem = pool->alloc.cache[--pool->alloc.count];
1325 		page_pool_return_netmem(pool, netmem);
1326 	}
1327 }
1328 EXPORT_SYMBOL(page_pool_update_nid);
1329 
1330 bool net_mp_niov_set_dma_addr(struct net_iov *niov, dma_addr_t addr)
1331 {
1332 	return page_pool_set_dma_addr_netmem(net_iov_to_netmem(niov), addr);
1333 }
1334 
1335 /* Associate a niov with a page pool. Should follow with a matching
1336  * net_mp_niov_clear_page_pool()
1337  */
1338 void net_mp_niov_set_page_pool(struct page_pool *pool, struct net_iov *niov)
1339 {
1340 	netmem_ref netmem = net_iov_to_netmem(niov);
1341 
1342 	page_pool_set_pp_info(pool, netmem);
1343 
1344 	pool->pages_state_hold_cnt++;
1345 	trace_page_pool_state_hold(pool, netmem, pool->pages_state_hold_cnt);
1346 }
1347 
1348 /* Disassociate a niov from a page pool. Should only be used in the
1349  * ->release_netmem() path.
1350  */
1351 void net_mp_niov_clear_page_pool(struct net_iov *niov)
1352 {
1353 	netmem_ref netmem = net_iov_to_netmem(niov);
1354 
1355 	page_pool_clear_pp_info(netmem);
1356 }
1357