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