xref: /linux/net/core/page_pool.c (revision 031fba65fc202abf1f193e321be7a2c274fd88ba)
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/types.h>
9 #include <linux/kernel.h>
10 #include <linux/slab.h>
11 #include <linux/device.h>
12 
13 #include <net/page_pool/helpers.h>
14 #include <net/xdp.h>
15 
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>
21 #include <linux/ethtool.h>
22 #include <linux/netdevice.h>
23 
24 #include <trace/events/page_pool.h>
25 
26 #define DEFER_TIME (msecs_to_jiffies(1000))
27 #define DEFER_WARN_INTERVAL (60 * HZ)
28 
29 #define BIAS_MAX	LONG_MAX
30 
31 #ifdef CONFIG_PAGE_POOL_STATS
32 /* alloc_stat_inc is intended to be used in softirq context */
33 #define alloc_stat_inc(pool, __stat)	(pool->alloc_stats.__stat++)
34 /* recycle_stat_inc is safe to use when preemption is possible. */
35 #define recycle_stat_inc(pool, __stat)							\
36 	do {										\
37 		struct page_pool_recycle_stats __percpu *s = pool->recycle_stats;	\
38 		this_cpu_inc(s->__stat);						\
39 	} while (0)
40 
41 #define recycle_stat_add(pool, __stat, val)						\
42 	do {										\
43 		struct page_pool_recycle_stats __percpu *s = pool->recycle_stats;	\
44 		this_cpu_add(s->__stat, val);						\
45 	} while (0)
46 
47 static const char pp_stats[][ETH_GSTRING_LEN] = {
48 	"rx_pp_alloc_fast",
49 	"rx_pp_alloc_slow",
50 	"rx_pp_alloc_slow_ho",
51 	"rx_pp_alloc_empty",
52 	"rx_pp_alloc_refill",
53 	"rx_pp_alloc_waive",
54 	"rx_pp_recycle_cached",
55 	"rx_pp_recycle_cache_full",
56 	"rx_pp_recycle_ring",
57 	"rx_pp_recycle_ring_full",
58 	"rx_pp_recycle_released_ref",
59 };
60 
61 /**
62  * page_pool_get_stats() - fetch page pool stats
63  * @pool:	pool from which page was allocated
64  * @stats:	struct page_pool_stats to fill in
65  *
66  * Retrieve statistics about the page_pool. This API is only available
67  * if the kernel has been configured with ``CONFIG_PAGE_POOL_STATS=y``.
68  * A pointer to a caller allocated struct page_pool_stats structure
69  * is passed to this API which is filled in. The caller can then report
70  * those stats to the user (perhaps via ethtool, debugfs, etc.).
71  */
72 bool page_pool_get_stats(struct page_pool *pool,
73 			 struct page_pool_stats *stats)
74 {
75 	int cpu = 0;
76 
77 	if (!stats)
78 		return false;
79 
80 	/* The caller is responsible to initialize stats. */
81 	stats->alloc_stats.fast += pool->alloc_stats.fast;
82 	stats->alloc_stats.slow += pool->alloc_stats.slow;
83 	stats->alloc_stats.slow_high_order += pool->alloc_stats.slow_high_order;
84 	stats->alloc_stats.empty += pool->alloc_stats.empty;
85 	stats->alloc_stats.refill += pool->alloc_stats.refill;
86 	stats->alloc_stats.waive += pool->alloc_stats.waive;
87 
88 	for_each_possible_cpu(cpu) {
89 		const struct page_pool_recycle_stats *pcpu =
90 			per_cpu_ptr(pool->recycle_stats, cpu);
91 
92 		stats->recycle_stats.cached += pcpu->cached;
93 		stats->recycle_stats.cache_full += pcpu->cache_full;
94 		stats->recycle_stats.ring += pcpu->ring;
95 		stats->recycle_stats.ring_full += pcpu->ring_full;
96 		stats->recycle_stats.released_refcnt += pcpu->released_refcnt;
97 	}
98 
99 	return true;
100 }
101 EXPORT_SYMBOL(page_pool_get_stats);
102 
103 u8 *page_pool_ethtool_stats_get_strings(u8 *data)
104 {
105 	int i;
106 
107 	for (i = 0; i < ARRAY_SIZE(pp_stats); i++) {
108 		memcpy(data, pp_stats[i], ETH_GSTRING_LEN);
109 		data += ETH_GSTRING_LEN;
110 	}
111 
112 	return data;
113 }
114 EXPORT_SYMBOL(page_pool_ethtool_stats_get_strings);
115 
116 int page_pool_ethtool_stats_get_count(void)
117 {
118 	return ARRAY_SIZE(pp_stats);
119 }
120 EXPORT_SYMBOL(page_pool_ethtool_stats_get_count);
121 
122 u64 *page_pool_ethtool_stats_get(u64 *data, void *stats)
123 {
124 	struct page_pool_stats *pool_stats = stats;
125 
126 	*data++ = pool_stats->alloc_stats.fast;
127 	*data++ = pool_stats->alloc_stats.slow;
128 	*data++ = pool_stats->alloc_stats.slow_high_order;
129 	*data++ = pool_stats->alloc_stats.empty;
130 	*data++ = pool_stats->alloc_stats.refill;
131 	*data++ = pool_stats->alloc_stats.waive;
132 	*data++ = pool_stats->recycle_stats.cached;
133 	*data++ = pool_stats->recycle_stats.cache_full;
134 	*data++ = pool_stats->recycle_stats.ring;
135 	*data++ = pool_stats->recycle_stats.ring_full;
136 	*data++ = pool_stats->recycle_stats.released_refcnt;
137 
138 	return data;
139 }
140 EXPORT_SYMBOL(page_pool_ethtool_stats_get);
141 
142 #else
143 #define alloc_stat_inc(pool, __stat)
144 #define recycle_stat_inc(pool, __stat)
145 #define recycle_stat_add(pool, __stat, val)
146 #endif
147 
148 static bool page_pool_producer_lock(struct page_pool *pool)
149 	__acquires(&pool->ring.producer_lock)
150 {
151 	bool in_softirq = in_softirq();
152 
153 	if (in_softirq)
154 		spin_lock(&pool->ring.producer_lock);
155 	else
156 		spin_lock_bh(&pool->ring.producer_lock);
157 
158 	return in_softirq;
159 }
160 
161 static void page_pool_producer_unlock(struct page_pool *pool,
162 				      bool in_softirq)
163 	__releases(&pool->ring.producer_lock)
164 {
165 	if (in_softirq)
166 		spin_unlock(&pool->ring.producer_lock);
167 	else
168 		spin_unlock_bh(&pool->ring.producer_lock);
169 }
170 
171 static int page_pool_init(struct page_pool *pool,
172 			  const struct page_pool_params *params)
173 {
174 	unsigned int ring_qsize = 1024; /* Default */
175 
176 	memcpy(&pool->p, params, sizeof(pool->p));
177 
178 	/* Validate only known flags were used */
179 	if (pool->p.flags & ~(PP_FLAG_ALL))
180 		return -EINVAL;
181 
182 	if (pool->p.pool_size)
183 		ring_qsize = pool->p.pool_size;
184 
185 	/* Sanity limit mem that can be pinned down */
186 	if (ring_qsize > 32768)
187 		return -E2BIG;
188 
189 	/* DMA direction is either DMA_FROM_DEVICE or DMA_BIDIRECTIONAL.
190 	 * DMA_BIDIRECTIONAL is for allowing page used for DMA sending,
191 	 * which is the XDP_TX use-case.
192 	 */
193 	if (pool->p.flags & PP_FLAG_DMA_MAP) {
194 		if ((pool->p.dma_dir != DMA_FROM_DEVICE) &&
195 		    (pool->p.dma_dir != DMA_BIDIRECTIONAL))
196 			return -EINVAL;
197 	}
198 
199 	if (pool->p.flags & PP_FLAG_DMA_SYNC_DEV) {
200 		/* In order to request DMA-sync-for-device the page
201 		 * needs to be mapped
202 		 */
203 		if (!(pool->p.flags & PP_FLAG_DMA_MAP))
204 			return -EINVAL;
205 
206 		if (!pool->p.max_len)
207 			return -EINVAL;
208 
209 		/* pool->p.offset has to be set according to the address
210 		 * offset used by the DMA engine to start copying rx data
211 		 */
212 	}
213 
214 #ifdef CONFIG_PAGE_POOL_STATS
215 	pool->recycle_stats = alloc_percpu(struct page_pool_recycle_stats);
216 	if (!pool->recycle_stats)
217 		return -ENOMEM;
218 #endif
219 
220 	if (ptr_ring_init(&pool->ring, ring_qsize, GFP_KERNEL) < 0)
221 		return -ENOMEM;
222 
223 	atomic_set(&pool->pages_state_release_cnt, 0);
224 
225 	/* Driver calling page_pool_create() also call page_pool_destroy() */
226 	refcount_set(&pool->user_cnt, 1);
227 
228 	if (pool->p.flags & PP_FLAG_DMA_MAP)
229 		get_device(pool->p.dev);
230 
231 	return 0;
232 }
233 
234 /**
235  * page_pool_create() - create a page pool.
236  * @params: parameters, see struct page_pool_params
237  */
238 struct page_pool *page_pool_create(const struct page_pool_params *params)
239 {
240 	struct page_pool *pool;
241 	int err;
242 
243 	pool = kzalloc_node(sizeof(*pool), GFP_KERNEL, params->nid);
244 	if (!pool)
245 		return ERR_PTR(-ENOMEM);
246 
247 	err = page_pool_init(pool, params);
248 	if (err < 0) {
249 		pr_warn("%s() gave up with errno %d\n", __func__, err);
250 		kfree(pool);
251 		return ERR_PTR(err);
252 	}
253 
254 	return pool;
255 }
256 EXPORT_SYMBOL(page_pool_create);
257 
258 static void page_pool_return_page(struct page_pool *pool, struct page *page);
259 
260 noinline
261 static struct page *page_pool_refill_alloc_cache(struct page_pool *pool)
262 {
263 	struct ptr_ring *r = &pool->ring;
264 	struct page *page;
265 	int pref_nid; /* preferred NUMA node */
266 
267 	/* Quicker fallback, avoid locks when ring is empty */
268 	if (__ptr_ring_empty(r)) {
269 		alloc_stat_inc(pool, empty);
270 		return NULL;
271 	}
272 
273 	/* Softirq guarantee CPU and thus NUMA node is stable. This,
274 	 * assumes CPU refilling driver RX-ring will also run RX-NAPI.
275 	 */
276 #ifdef CONFIG_NUMA
277 	pref_nid = (pool->p.nid == NUMA_NO_NODE) ? numa_mem_id() : pool->p.nid;
278 #else
279 	/* Ignore pool->p.nid setting if !CONFIG_NUMA, helps compiler */
280 	pref_nid = numa_mem_id(); /* will be zero like page_to_nid() */
281 #endif
282 
283 	/* Refill alloc array, but only if NUMA match */
284 	do {
285 		page = __ptr_ring_consume(r);
286 		if (unlikely(!page))
287 			break;
288 
289 		if (likely(page_to_nid(page) == pref_nid)) {
290 			pool->alloc.cache[pool->alloc.count++] = page;
291 		} else {
292 			/* NUMA mismatch;
293 			 * (1) release 1 page to page-allocator and
294 			 * (2) break out to fallthrough to alloc_pages_node.
295 			 * This limit stress on page buddy alloactor.
296 			 */
297 			page_pool_return_page(pool, page);
298 			alloc_stat_inc(pool, waive);
299 			page = NULL;
300 			break;
301 		}
302 	} while (pool->alloc.count < PP_ALLOC_CACHE_REFILL);
303 
304 	/* Return last page */
305 	if (likely(pool->alloc.count > 0)) {
306 		page = pool->alloc.cache[--pool->alloc.count];
307 		alloc_stat_inc(pool, refill);
308 	}
309 
310 	return page;
311 }
312 
313 /* fast path */
314 static struct page *__page_pool_get_cached(struct page_pool *pool)
315 {
316 	struct page *page;
317 
318 	/* Caller MUST guarantee safe non-concurrent access, e.g. softirq */
319 	if (likely(pool->alloc.count)) {
320 		/* Fast-path */
321 		page = pool->alloc.cache[--pool->alloc.count];
322 		alloc_stat_inc(pool, fast);
323 	} else {
324 		page = page_pool_refill_alloc_cache(pool);
325 	}
326 
327 	return page;
328 }
329 
330 static void page_pool_dma_sync_for_device(struct page_pool *pool,
331 					  struct page *page,
332 					  unsigned int dma_sync_size)
333 {
334 	dma_addr_t dma_addr = page_pool_get_dma_addr(page);
335 
336 	dma_sync_size = min(dma_sync_size, pool->p.max_len);
337 	dma_sync_single_range_for_device(pool->p.dev, dma_addr,
338 					 pool->p.offset, dma_sync_size,
339 					 pool->p.dma_dir);
340 }
341 
342 static bool page_pool_dma_map(struct page_pool *pool, struct page *page)
343 {
344 	dma_addr_t dma;
345 
346 	/* Setup DMA mapping: use 'struct page' area for storing DMA-addr
347 	 * since dma_addr_t can be either 32 or 64 bits and does not always fit
348 	 * into page private data (i.e 32bit cpu with 64bit DMA caps)
349 	 * This mapping is kept for lifetime of page, until leaving pool.
350 	 */
351 	dma = dma_map_page_attrs(pool->p.dev, page, 0,
352 				 (PAGE_SIZE << pool->p.order),
353 				 pool->p.dma_dir, DMA_ATTR_SKIP_CPU_SYNC |
354 						  DMA_ATTR_WEAK_ORDERING);
355 	if (dma_mapping_error(pool->p.dev, dma))
356 		return false;
357 
358 	if (page_pool_set_dma_addr(page, dma))
359 		goto unmap_failed;
360 
361 	if (pool->p.flags & PP_FLAG_DMA_SYNC_DEV)
362 		page_pool_dma_sync_for_device(pool, page, pool->p.max_len);
363 
364 	return true;
365 
366 unmap_failed:
367 	WARN_ON_ONCE("unexpected DMA address, please report to netdev@");
368 	dma_unmap_page_attrs(pool->p.dev, dma,
369 			     PAGE_SIZE << pool->p.order, pool->p.dma_dir,
370 			     DMA_ATTR_SKIP_CPU_SYNC | DMA_ATTR_WEAK_ORDERING);
371 	return false;
372 }
373 
374 static void page_pool_set_pp_info(struct page_pool *pool,
375 				  struct page *page)
376 {
377 	page->pp = pool;
378 	page->pp_magic |= PP_SIGNATURE;
379 
380 	/* Ensuring all pages have been split into one fragment initially:
381 	 * page_pool_set_pp_info() is only called once for every page when it
382 	 * is allocated from the page allocator and page_pool_fragment_page()
383 	 * is dirtying the same cache line as the page->pp_magic above, so
384 	 * the overhead is negligible.
385 	 */
386 	page_pool_fragment_page(page, 1);
387 	if (pool->p.init_callback)
388 		pool->p.init_callback(page, pool->p.init_arg);
389 }
390 
391 static void page_pool_clear_pp_info(struct page *page)
392 {
393 	page->pp_magic = 0;
394 	page->pp = NULL;
395 }
396 
397 static struct page *__page_pool_alloc_page_order(struct page_pool *pool,
398 						 gfp_t gfp)
399 {
400 	struct page *page;
401 
402 	gfp |= __GFP_COMP;
403 	page = alloc_pages_node(pool->p.nid, gfp, pool->p.order);
404 	if (unlikely(!page))
405 		return NULL;
406 
407 	if ((pool->p.flags & PP_FLAG_DMA_MAP) &&
408 	    unlikely(!page_pool_dma_map(pool, page))) {
409 		put_page(page);
410 		return NULL;
411 	}
412 
413 	alloc_stat_inc(pool, slow_high_order);
414 	page_pool_set_pp_info(pool, page);
415 
416 	/* Track how many pages are held 'in-flight' */
417 	pool->pages_state_hold_cnt++;
418 	trace_page_pool_state_hold(pool, page, pool->pages_state_hold_cnt);
419 	return page;
420 }
421 
422 /* slow path */
423 noinline
424 static struct page *__page_pool_alloc_pages_slow(struct page_pool *pool,
425 						 gfp_t gfp)
426 {
427 	const int bulk = PP_ALLOC_CACHE_REFILL;
428 	unsigned int pp_flags = pool->p.flags;
429 	unsigned int pp_order = pool->p.order;
430 	struct page *page;
431 	int i, nr_pages;
432 
433 	/* Don't support bulk alloc for high-order pages */
434 	if (unlikely(pp_order))
435 		return __page_pool_alloc_page_order(pool, gfp);
436 
437 	/* Unnecessary as alloc cache is empty, but guarantees zero count */
438 	if (unlikely(pool->alloc.count > 0))
439 		return pool->alloc.cache[--pool->alloc.count];
440 
441 	/* Mark empty alloc.cache slots "empty" for alloc_pages_bulk_array */
442 	memset(&pool->alloc.cache, 0, sizeof(void *) * bulk);
443 
444 	nr_pages = alloc_pages_bulk_array_node(gfp, pool->p.nid, bulk,
445 					       pool->alloc.cache);
446 	if (unlikely(!nr_pages))
447 		return NULL;
448 
449 	/* Pages have been filled into alloc.cache array, but count is zero and
450 	 * page element have not been (possibly) DMA mapped.
451 	 */
452 	for (i = 0; i < nr_pages; i++) {
453 		page = pool->alloc.cache[i];
454 		if ((pp_flags & PP_FLAG_DMA_MAP) &&
455 		    unlikely(!page_pool_dma_map(pool, page))) {
456 			put_page(page);
457 			continue;
458 		}
459 
460 		page_pool_set_pp_info(pool, page);
461 		pool->alloc.cache[pool->alloc.count++] = page;
462 		/* Track how many pages are held 'in-flight' */
463 		pool->pages_state_hold_cnt++;
464 		trace_page_pool_state_hold(pool, page,
465 					   pool->pages_state_hold_cnt);
466 	}
467 
468 	/* Return last page */
469 	if (likely(pool->alloc.count > 0)) {
470 		page = pool->alloc.cache[--pool->alloc.count];
471 		alloc_stat_inc(pool, slow);
472 	} else {
473 		page = NULL;
474 	}
475 
476 	/* When page just alloc'ed is should/must have refcnt 1. */
477 	return page;
478 }
479 
480 /* For using page_pool replace: alloc_pages() API calls, but provide
481  * synchronization guarantee for allocation side.
482  */
483 struct page *page_pool_alloc_pages(struct page_pool *pool, gfp_t gfp)
484 {
485 	struct page *page;
486 
487 	/* Fast-path: Get a page from cache */
488 	page = __page_pool_get_cached(pool);
489 	if (page)
490 		return page;
491 
492 	/* Slow-path: cache empty, do real allocation */
493 	page = __page_pool_alloc_pages_slow(pool, gfp);
494 	return page;
495 }
496 EXPORT_SYMBOL(page_pool_alloc_pages);
497 
498 /* Calculate distance between two u32 values, valid if distance is below 2^(31)
499  *  https://en.wikipedia.org/wiki/Serial_number_arithmetic#General_Solution
500  */
501 #define _distance(a, b)	(s32)((a) - (b))
502 
503 static s32 page_pool_inflight(struct page_pool *pool)
504 {
505 	u32 release_cnt = atomic_read(&pool->pages_state_release_cnt);
506 	u32 hold_cnt = READ_ONCE(pool->pages_state_hold_cnt);
507 	s32 inflight;
508 
509 	inflight = _distance(hold_cnt, release_cnt);
510 
511 	trace_page_pool_release(pool, inflight, hold_cnt, release_cnt);
512 	WARN(inflight < 0, "Negative(%d) inflight packet-pages", inflight);
513 
514 	return inflight;
515 }
516 
517 /* Disconnects a page (from a page_pool).  API users can have a need
518  * to disconnect a page (from a page_pool), to allow it to be used as
519  * a regular page (that will eventually be returned to the normal
520  * page-allocator via put_page).
521  */
522 static void page_pool_return_page(struct page_pool *pool, struct page *page)
523 {
524 	dma_addr_t dma;
525 	int count;
526 
527 	if (!(pool->p.flags & PP_FLAG_DMA_MAP))
528 		/* Always account for inflight pages, even if we didn't
529 		 * map them
530 		 */
531 		goto skip_dma_unmap;
532 
533 	dma = page_pool_get_dma_addr(page);
534 
535 	/* When page is unmapped, it cannot be returned to our pool */
536 	dma_unmap_page_attrs(pool->p.dev, dma,
537 			     PAGE_SIZE << pool->p.order, pool->p.dma_dir,
538 			     DMA_ATTR_SKIP_CPU_SYNC | DMA_ATTR_WEAK_ORDERING);
539 	page_pool_set_dma_addr(page, 0);
540 skip_dma_unmap:
541 	page_pool_clear_pp_info(page);
542 
543 	/* This may be the last page returned, releasing the pool, so
544 	 * it is not safe to reference pool afterwards.
545 	 */
546 	count = atomic_inc_return_relaxed(&pool->pages_state_release_cnt);
547 	trace_page_pool_state_release(pool, page, count);
548 
549 	put_page(page);
550 	/* An optimization would be to call __free_pages(page, pool->p.order)
551 	 * knowing page is not part of page-cache (thus avoiding a
552 	 * __page_cache_release() call).
553 	 */
554 }
555 
556 static bool page_pool_recycle_in_ring(struct page_pool *pool, struct page *page)
557 {
558 	int ret;
559 	/* BH protection not needed if current is softirq */
560 	if (in_softirq())
561 		ret = ptr_ring_produce(&pool->ring, page);
562 	else
563 		ret = ptr_ring_produce_bh(&pool->ring, page);
564 
565 	if (!ret) {
566 		recycle_stat_inc(pool, ring);
567 		return true;
568 	}
569 
570 	return false;
571 }
572 
573 /* Only allow direct recycling in special circumstances, into the
574  * alloc side cache.  E.g. during RX-NAPI processing for XDP_DROP use-case.
575  *
576  * Caller must provide appropriate safe context.
577  */
578 static bool page_pool_recycle_in_cache(struct page *page,
579 				       struct page_pool *pool)
580 {
581 	if (unlikely(pool->alloc.count == PP_ALLOC_CACHE_SIZE)) {
582 		recycle_stat_inc(pool, cache_full);
583 		return false;
584 	}
585 
586 	/* Caller MUST have verified/know (page_ref_count(page) == 1) */
587 	pool->alloc.cache[pool->alloc.count++] = page;
588 	recycle_stat_inc(pool, cached);
589 	return true;
590 }
591 
592 /* If the page refcnt == 1, this will try to recycle the page.
593  * if PP_FLAG_DMA_SYNC_DEV is set, we'll try to sync the DMA area for
594  * the configured size min(dma_sync_size, pool->max_len).
595  * If the page refcnt != 1, then the page will be returned to memory
596  * subsystem.
597  */
598 static __always_inline struct page *
599 __page_pool_put_page(struct page_pool *pool, struct page *page,
600 		     unsigned int dma_sync_size, bool allow_direct)
601 {
602 	lockdep_assert_no_hardirq();
603 
604 	/* This allocator is optimized for the XDP mode that uses
605 	 * one-frame-per-page, but have fallbacks that act like the
606 	 * regular page allocator APIs.
607 	 *
608 	 * refcnt == 1 means page_pool owns page, and can recycle it.
609 	 *
610 	 * page is NOT reusable when allocated when system is under
611 	 * some pressure. (page_is_pfmemalloc)
612 	 */
613 	if (likely(page_ref_count(page) == 1 && !page_is_pfmemalloc(page))) {
614 		/* Read barrier done in page_ref_count / READ_ONCE */
615 
616 		if (pool->p.flags & PP_FLAG_DMA_SYNC_DEV)
617 			page_pool_dma_sync_for_device(pool, page,
618 						      dma_sync_size);
619 
620 		if (allow_direct && in_softirq() &&
621 		    page_pool_recycle_in_cache(page, pool))
622 			return NULL;
623 
624 		/* Page found as candidate for recycling */
625 		return page;
626 	}
627 	/* Fallback/non-XDP mode: API user have elevated refcnt.
628 	 *
629 	 * Many drivers split up the page into fragments, and some
630 	 * want to keep doing this to save memory and do refcnt based
631 	 * recycling. Support this use case too, to ease drivers
632 	 * switching between XDP/non-XDP.
633 	 *
634 	 * In-case page_pool maintains the DMA mapping, API user must
635 	 * call page_pool_put_page once.  In this elevated refcnt
636 	 * case, the DMA is unmapped/released, as driver is likely
637 	 * doing refcnt based recycle tricks, meaning another process
638 	 * will be invoking put_page.
639 	 */
640 	recycle_stat_inc(pool, released_refcnt);
641 	page_pool_return_page(pool, page);
642 
643 	return NULL;
644 }
645 
646 void page_pool_put_defragged_page(struct page_pool *pool, struct page *page,
647 				  unsigned int dma_sync_size, bool allow_direct)
648 {
649 	page = __page_pool_put_page(pool, page, dma_sync_size, allow_direct);
650 	if (page && !page_pool_recycle_in_ring(pool, page)) {
651 		/* Cache full, fallback to free pages */
652 		recycle_stat_inc(pool, ring_full);
653 		page_pool_return_page(pool, page);
654 	}
655 }
656 EXPORT_SYMBOL(page_pool_put_defragged_page);
657 
658 /**
659  * page_pool_put_page_bulk() - release references on multiple pages
660  * @pool:	pool from which pages were allocated
661  * @data:	array holding page pointers
662  * @count:	number of pages in @data
663  *
664  * Tries to refill a number of pages into the ptr_ring cache holding ptr_ring
665  * producer lock. If the ptr_ring is full, page_pool_put_page_bulk()
666  * will release leftover pages to the page allocator.
667  * page_pool_put_page_bulk() is suitable to be run inside the driver NAPI tx
668  * completion loop for the XDP_REDIRECT use case.
669  *
670  * Please note the caller must not use data area after running
671  * page_pool_put_page_bulk(), as this function overwrites it.
672  */
673 void page_pool_put_page_bulk(struct page_pool *pool, void **data,
674 			     int count)
675 {
676 	int i, bulk_len = 0;
677 	bool in_softirq;
678 
679 	for (i = 0; i < count; i++) {
680 		struct page *page = virt_to_head_page(data[i]);
681 
682 		/* It is not the last user for the page frag case */
683 		if (!page_pool_is_last_frag(page))
684 			continue;
685 
686 		page = __page_pool_put_page(pool, page, -1, false);
687 		/* Approved for bulk recycling in ptr_ring cache */
688 		if (page)
689 			data[bulk_len++] = page;
690 	}
691 
692 	if (unlikely(!bulk_len))
693 		return;
694 
695 	/* Bulk producer into ptr_ring page_pool cache */
696 	in_softirq = page_pool_producer_lock(pool);
697 	for (i = 0; i < bulk_len; i++) {
698 		if (__ptr_ring_produce(&pool->ring, data[i])) {
699 			/* ring full */
700 			recycle_stat_inc(pool, ring_full);
701 			break;
702 		}
703 	}
704 	recycle_stat_add(pool, ring, i);
705 	page_pool_producer_unlock(pool, in_softirq);
706 
707 	/* Hopefully all pages was return into ptr_ring */
708 	if (likely(i == bulk_len))
709 		return;
710 
711 	/* ptr_ring cache full, free remaining pages outside producer lock
712 	 * since put_page() with refcnt == 1 can be an expensive operation
713 	 */
714 	for (; i < bulk_len; i++)
715 		page_pool_return_page(pool, data[i]);
716 }
717 EXPORT_SYMBOL(page_pool_put_page_bulk);
718 
719 static struct page *page_pool_drain_frag(struct page_pool *pool,
720 					 struct page *page)
721 {
722 	long drain_count = BIAS_MAX - pool->frag_users;
723 
724 	/* Some user is still using the page frag */
725 	if (likely(page_pool_defrag_page(page, drain_count)))
726 		return NULL;
727 
728 	if (page_ref_count(page) == 1 && !page_is_pfmemalloc(page)) {
729 		if (pool->p.flags & PP_FLAG_DMA_SYNC_DEV)
730 			page_pool_dma_sync_for_device(pool, page, -1);
731 
732 		return page;
733 	}
734 
735 	page_pool_return_page(pool, page);
736 	return NULL;
737 }
738 
739 static void page_pool_free_frag(struct page_pool *pool)
740 {
741 	long drain_count = BIAS_MAX - pool->frag_users;
742 	struct page *page = pool->frag_page;
743 
744 	pool->frag_page = NULL;
745 
746 	if (!page || page_pool_defrag_page(page, drain_count))
747 		return;
748 
749 	page_pool_return_page(pool, page);
750 }
751 
752 struct page *page_pool_alloc_frag(struct page_pool *pool,
753 				  unsigned int *offset,
754 				  unsigned int size, gfp_t gfp)
755 {
756 	unsigned int max_size = PAGE_SIZE << pool->p.order;
757 	struct page *page = pool->frag_page;
758 
759 	if (WARN_ON(size > max_size))
760 		return NULL;
761 
762 	size = ALIGN(size, dma_get_cache_alignment());
763 	*offset = pool->frag_offset;
764 
765 	if (page && *offset + size > max_size) {
766 		page = page_pool_drain_frag(pool, page);
767 		if (page) {
768 			alloc_stat_inc(pool, fast);
769 			goto frag_reset;
770 		}
771 	}
772 
773 	if (!page) {
774 		page = page_pool_alloc_pages(pool, gfp);
775 		if (unlikely(!page)) {
776 			pool->frag_page = NULL;
777 			return NULL;
778 		}
779 
780 		pool->frag_page = page;
781 
782 frag_reset:
783 		pool->frag_users = 1;
784 		*offset = 0;
785 		pool->frag_offset = size;
786 		page_pool_fragment_page(page, BIAS_MAX);
787 		return page;
788 	}
789 
790 	pool->frag_users++;
791 	pool->frag_offset = *offset + size;
792 	alloc_stat_inc(pool, fast);
793 	return page;
794 }
795 EXPORT_SYMBOL(page_pool_alloc_frag);
796 
797 static void page_pool_empty_ring(struct page_pool *pool)
798 {
799 	struct page *page;
800 
801 	/* Empty recycle ring */
802 	while ((page = ptr_ring_consume_bh(&pool->ring))) {
803 		/* Verify the refcnt invariant of cached pages */
804 		if (!(page_ref_count(page) == 1))
805 			pr_crit("%s() page_pool refcnt %d violation\n",
806 				__func__, page_ref_count(page));
807 
808 		page_pool_return_page(pool, page);
809 	}
810 }
811 
812 static void __page_pool_destroy(struct page_pool *pool)
813 {
814 	if (pool->disconnect)
815 		pool->disconnect(pool);
816 
817 	ptr_ring_cleanup(&pool->ring, NULL);
818 
819 	if (pool->p.flags & PP_FLAG_DMA_MAP)
820 		put_device(pool->p.dev);
821 
822 #ifdef CONFIG_PAGE_POOL_STATS
823 	free_percpu(pool->recycle_stats);
824 #endif
825 	kfree(pool);
826 }
827 
828 static void page_pool_empty_alloc_cache_once(struct page_pool *pool)
829 {
830 	struct page *page;
831 
832 	if (pool->destroy_cnt)
833 		return;
834 
835 	/* Empty alloc cache, assume caller made sure this is
836 	 * no-longer in use, and page_pool_alloc_pages() cannot be
837 	 * call concurrently.
838 	 */
839 	while (pool->alloc.count) {
840 		page = pool->alloc.cache[--pool->alloc.count];
841 		page_pool_return_page(pool, page);
842 	}
843 }
844 
845 static void page_pool_scrub(struct page_pool *pool)
846 {
847 	page_pool_empty_alloc_cache_once(pool);
848 	pool->destroy_cnt++;
849 
850 	/* No more consumers should exist, but producers could still
851 	 * be in-flight.
852 	 */
853 	page_pool_empty_ring(pool);
854 }
855 
856 static int page_pool_release(struct page_pool *pool)
857 {
858 	int inflight;
859 
860 	page_pool_scrub(pool);
861 	inflight = page_pool_inflight(pool);
862 	if (!inflight)
863 		__page_pool_destroy(pool);
864 
865 	return inflight;
866 }
867 
868 static void page_pool_release_retry(struct work_struct *wq)
869 {
870 	struct delayed_work *dwq = to_delayed_work(wq);
871 	struct page_pool *pool = container_of(dwq, typeof(*pool), release_dw);
872 	int inflight;
873 
874 	inflight = page_pool_release(pool);
875 	if (!inflight)
876 		return;
877 
878 	/* Periodic warning */
879 	if (time_after_eq(jiffies, pool->defer_warn)) {
880 		int sec = (s32)((u32)jiffies - (u32)pool->defer_start) / HZ;
881 
882 		pr_warn("%s() stalled pool shutdown %d inflight %d sec\n",
883 			__func__, inflight, sec);
884 		pool->defer_warn = jiffies + DEFER_WARN_INTERVAL;
885 	}
886 
887 	/* Still not ready to be disconnected, retry later */
888 	schedule_delayed_work(&pool->release_dw, DEFER_TIME);
889 }
890 
891 void page_pool_use_xdp_mem(struct page_pool *pool, void (*disconnect)(void *),
892 			   struct xdp_mem_info *mem)
893 {
894 	refcount_inc(&pool->user_cnt);
895 	pool->disconnect = disconnect;
896 	pool->xdp_mem_id = mem->id;
897 }
898 
899 void page_pool_unlink_napi(struct page_pool *pool)
900 {
901 	if (!pool->p.napi)
902 		return;
903 
904 	/* To avoid races with recycling and additional barriers make sure
905 	 * pool and NAPI are unlinked when NAPI is disabled.
906 	 */
907 	WARN_ON(!test_bit(NAPI_STATE_SCHED, &pool->p.napi->state) ||
908 		READ_ONCE(pool->p.napi->list_owner) != -1);
909 
910 	WRITE_ONCE(pool->p.napi, NULL);
911 }
912 EXPORT_SYMBOL(page_pool_unlink_napi);
913 
914 void page_pool_destroy(struct page_pool *pool)
915 {
916 	if (!pool)
917 		return;
918 
919 	if (!page_pool_put(pool))
920 		return;
921 
922 	page_pool_unlink_napi(pool);
923 	page_pool_free_frag(pool);
924 
925 	if (!page_pool_release(pool))
926 		return;
927 
928 	pool->defer_start = jiffies;
929 	pool->defer_warn  = jiffies + DEFER_WARN_INTERVAL;
930 
931 	INIT_DELAYED_WORK(&pool->release_dw, page_pool_release_retry);
932 	schedule_delayed_work(&pool->release_dw, DEFER_TIME);
933 }
934 EXPORT_SYMBOL(page_pool_destroy);
935 
936 /* Caller must provide appropriate safe context, e.g. NAPI. */
937 void page_pool_update_nid(struct page_pool *pool, int new_nid)
938 {
939 	struct page *page;
940 
941 	trace_page_pool_update_nid(pool, new_nid);
942 	pool->p.nid = new_nid;
943 
944 	/* Flush pool alloc cache, as refill will check NUMA node */
945 	while (pool->alloc.count) {
946 		page = pool->alloc.cache[--pool->alloc.count];
947 		page_pool_return_page(pool, page);
948 	}
949 }
950 EXPORT_SYMBOL(page_pool_update_nid);
951