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