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