Merge tag 'exfat-for-5.11-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/linki...
[linux-2.6-microblaze.git] / drivers / gpu / drm / ttm / ttm_pool.c
1 // SPDX-License-Identifier: GPL-2.0 OR MIT
2 /*
3  * Copyright 2020 Advanced Micro Devices, Inc.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
19  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
20  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
21  * OTHER DEALINGS IN THE SOFTWARE.
22  *
23  * Authors: Christian König
24  */
25
26 /* Pooling of allocated pages is necessary because changing the caching
27  * attributes on x86 of the linear mapping requires a costly cross CPU TLB
28  * invalidate for those addresses.
29  *
30  * Additional to that allocations from the DMA coherent API are pooled as well
31  * cause they are rather slow compared to alloc_pages+map.
32  */
33
34 #include <linux/module.h>
35 #include <linux/dma-mapping.h>
36
37 #ifdef CONFIG_X86
38 #include <asm/set_memory.h>
39 #endif
40
41 #include <drm/ttm/ttm_pool.h>
42 #include <drm/ttm/ttm_bo_driver.h>
43 #include <drm/ttm/ttm_tt.h>
44
45 /**
46  * struct ttm_pool_dma - Helper object for coherent DMA mappings
47  *
48  * @addr: original DMA address returned for the mapping
49  * @vaddr: original vaddr return for the mapping and order in the lower bits
50  */
51 struct ttm_pool_dma {
52         dma_addr_t addr;
53         unsigned long vaddr;
54 };
55
56 static unsigned long page_pool_size;
57
58 MODULE_PARM_DESC(page_pool_size, "Number of pages in the WC/UC/DMA pool");
59 module_param(page_pool_size, ulong, 0644);
60
61 static atomic_long_t allocated_pages;
62
63 static struct ttm_pool_type global_write_combined[MAX_ORDER];
64 static struct ttm_pool_type global_uncached[MAX_ORDER];
65
66 static struct ttm_pool_type global_dma32_write_combined[MAX_ORDER];
67 static struct ttm_pool_type global_dma32_uncached[MAX_ORDER];
68
69 static spinlock_t shrinker_lock;
70 static struct list_head shrinker_list;
71 static struct shrinker mm_shrinker;
72
73 /* Allocate pages of size 1 << order with the given gfp_flags */
74 static struct page *ttm_pool_alloc_page(struct ttm_pool *pool, gfp_t gfp_flags,
75                                         unsigned int order)
76 {
77         unsigned long attr = DMA_ATTR_FORCE_CONTIGUOUS;
78         struct ttm_pool_dma *dma;
79         struct page *p;
80         void *vaddr;
81
82         if (order) {
83                 gfp_flags |= GFP_TRANSHUGE_LIGHT | __GFP_NORETRY |
84                         __GFP_KSWAPD_RECLAIM;
85                 gfp_flags &= ~__GFP_MOVABLE;
86                 gfp_flags &= ~__GFP_COMP;
87         }
88
89         if (!pool->use_dma_alloc) {
90                 p = alloc_pages(gfp_flags, order);
91                 if (p)
92                         p->private = order;
93                 return p;
94         }
95
96         dma = kmalloc(sizeof(*dma), GFP_KERNEL);
97         if (!dma)
98                 return NULL;
99
100         if (order)
101                 attr |= DMA_ATTR_NO_WARN;
102
103         vaddr = dma_alloc_attrs(pool->dev, (1ULL << order) * PAGE_SIZE,
104                                 &dma->addr, gfp_flags, attr);
105         if (!vaddr)
106                 goto error_free;
107
108         /* TODO: This is an illegal abuse of the DMA API, but we need to rework
109          * TTM page fault handling and extend the DMA API to clean this up.
110          */
111         if (is_vmalloc_addr(vaddr))
112                 p = vmalloc_to_page(vaddr);
113         else
114                 p = virt_to_page(vaddr);
115
116         dma->vaddr = (unsigned long)vaddr | order;
117         p->private = (unsigned long)dma;
118         return p;
119
120 error_free:
121         kfree(dma);
122         return NULL;
123 }
124
125 /* Reset the caching and pages of size 1 << order */
126 static void ttm_pool_free_page(struct ttm_pool *pool, enum ttm_caching caching,
127                                unsigned int order, struct page *p)
128 {
129         unsigned long attr = DMA_ATTR_FORCE_CONTIGUOUS;
130         struct ttm_pool_dma *dma;
131         void *vaddr;
132
133 #ifdef CONFIG_X86
134         /* We don't care that set_pages_wb is inefficient here. This is only
135          * used when we have to shrink and CPU overhead is irrelevant then.
136          */
137         if (caching != ttm_cached && !PageHighMem(p))
138                 set_pages_wb(p, 1 << order);
139 #endif
140
141         if (!pool || !pool->use_dma_alloc) {
142                 __free_pages(p, order);
143                 return;
144         }
145
146         if (order)
147                 attr |= DMA_ATTR_NO_WARN;
148
149         dma = (void *)p->private;
150         vaddr = (void *)(dma->vaddr & PAGE_MASK);
151         dma_free_attrs(pool->dev, (1UL << order) * PAGE_SIZE, vaddr, dma->addr,
152                        attr);
153         kfree(dma);
154 }
155
156 /* Apply a new caching to an array of pages */
157 static int ttm_pool_apply_caching(struct page **first, struct page **last,
158                                   enum ttm_caching caching)
159 {
160 #ifdef CONFIG_X86
161         unsigned int num_pages = last - first;
162
163         if (!num_pages)
164                 return 0;
165
166         switch (caching) {
167         case ttm_cached:
168                 break;
169         case ttm_write_combined:
170                 return set_pages_array_wc(first, num_pages);
171         case ttm_uncached:
172                 return set_pages_array_uc(first, num_pages);
173         }
174 #endif
175         return 0;
176 }
177
178 /* Map pages of 1 << order size and fill the DMA address array  */
179 static int ttm_pool_map(struct ttm_pool *pool, unsigned int order,
180                         struct page *p, dma_addr_t **dma_addr)
181 {
182         dma_addr_t addr;
183         unsigned int i;
184
185         if (pool->use_dma_alloc) {
186                 struct ttm_pool_dma *dma = (void *)p->private;
187
188                 addr = dma->addr;
189         } else {
190                 size_t size = (1ULL << order) * PAGE_SIZE;
191
192                 addr = dma_map_page(pool->dev, p, 0, size, DMA_BIDIRECTIONAL);
193                 if (dma_mapping_error(pool->dev, **dma_addr))
194                         return -EFAULT;
195         }
196
197         for (i = 1 << order; i ; --i) {
198                 *(*dma_addr)++ = addr;
199                 addr += PAGE_SIZE;
200         }
201
202         return 0;
203 }
204
205 /* Unmap pages of 1 << order size */
206 static void ttm_pool_unmap(struct ttm_pool *pool, dma_addr_t dma_addr,
207                            unsigned int num_pages)
208 {
209         /* Unmapped while freeing the page */
210         if (pool->use_dma_alloc)
211                 return;
212
213         dma_unmap_page(pool->dev, dma_addr, (long)num_pages << PAGE_SHIFT,
214                        DMA_BIDIRECTIONAL);
215 }
216
217 /* Give pages into a specific pool_type */
218 static void ttm_pool_type_give(struct ttm_pool_type *pt, struct page *p)
219 {
220         spin_lock(&pt->lock);
221         list_add(&p->lru, &pt->pages);
222         spin_unlock(&pt->lock);
223         atomic_long_add(1 << pt->order, &allocated_pages);
224 }
225
226 /* Take pages from a specific pool_type, return NULL when nothing available */
227 static struct page *ttm_pool_type_take(struct ttm_pool_type *pt)
228 {
229         struct page *p;
230
231         spin_lock(&pt->lock);
232         p = list_first_entry_or_null(&pt->pages, typeof(*p), lru);
233         if (p) {
234                 atomic_long_sub(1 << pt->order, &allocated_pages);
235                 list_del(&p->lru);
236         }
237         spin_unlock(&pt->lock);
238
239         return p;
240 }
241
242 /* Count the number of pages available in a pool_type */
243 static unsigned int ttm_pool_type_count(struct ttm_pool_type *pt)
244 {
245         unsigned int count = 0;
246         struct page *p;
247
248         spin_lock(&pt->lock);
249         /* Only used for debugfs, the overhead doesn't matter */
250         list_for_each_entry(p, &pt->pages, lru)
251                 ++count;
252         spin_unlock(&pt->lock);
253
254         return count;
255 }
256
257 /* Initialize and add a pool type to the global shrinker list */
258 static void ttm_pool_type_init(struct ttm_pool_type *pt, struct ttm_pool *pool,
259                                enum ttm_caching caching, unsigned int order)
260 {
261         pt->pool = pool;
262         pt->caching = caching;
263         pt->order = order;
264         spin_lock_init(&pt->lock);
265         INIT_LIST_HEAD(&pt->pages);
266
267         spin_lock(&shrinker_lock);
268         list_add_tail(&pt->shrinker_list, &shrinker_list);
269         spin_unlock(&shrinker_lock);
270 }
271
272 /* Remove a pool_type from the global shrinker list and free all pages */
273 static void ttm_pool_type_fini(struct ttm_pool_type *pt)
274 {
275         struct page *p, *tmp;
276
277         spin_lock(&shrinker_lock);
278         list_del(&pt->shrinker_list);
279         spin_unlock(&shrinker_lock);
280
281         list_for_each_entry_safe(p, tmp, &pt->pages, lru)
282                 ttm_pool_free_page(pt->pool, pt->caching, pt->order, p);
283 }
284
285 /* Return the pool_type to use for the given caching and order */
286 static struct ttm_pool_type *ttm_pool_select_type(struct ttm_pool *pool,
287                                                   enum ttm_caching caching,
288                                                   unsigned int order)
289 {
290         if (pool->use_dma_alloc)
291                 return &pool->caching[caching].orders[order];
292
293 #ifdef CONFIG_X86
294         switch (caching) {
295         case ttm_write_combined:
296                 if (pool->use_dma32)
297                         return &global_dma32_write_combined[order];
298
299                 return &global_write_combined[order];
300         case ttm_uncached:
301                 if (pool->use_dma32)
302                         return &global_dma32_uncached[order];
303
304                 return &global_uncached[order];
305         default:
306                 break;
307         }
308 #endif
309
310         return NULL;
311 }
312
313 /* Free pages using the global shrinker list */
314 static unsigned int ttm_pool_shrink(void)
315 {
316         struct ttm_pool_type *pt;
317         unsigned int num_freed;
318         struct page *p;
319
320         spin_lock(&shrinker_lock);
321         pt = list_first_entry(&shrinker_list, typeof(*pt), shrinker_list);
322
323         p = ttm_pool_type_take(pt);
324         if (p) {
325                 ttm_pool_free_page(pt->pool, pt->caching, pt->order, p);
326                 num_freed = 1 << pt->order;
327         } else {
328                 num_freed = 0;
329         }
330
331         list_move_tail(&pt->shrinker_list, &shrinker_list);
332         spin_unlock(&shrinker_lock);
333
334         return num_freed;
335 }
336
337 /* Return the allocation order based for a page */
338 static unsigned int ttm_pool_page_order(struct ttm_pool *pool, struct page *p)
339 {
340         if (pool->use_dma_alloc) {
341                 struct ttm_pool_dma *dma = (void *)p->private;
342
343                 return dma->vaddr & ~PAGE_MASK;
344         }
345
346         return p->private;
347 }
348
349 /**
350  * ttm_pool_alloc - Fill a ttm_tt object
351  *
352  * @pool: ttm_pool to use
353  * @tt: ttm_tt object to fill
354  * @ctx: operation context
355  *
356  * Fill the ttm_tt object with pages and also make sure to DMA map them when
357  * necessary.
358  *
359  * Returns: 0 on successe, negative error code otherwise.
360  */
361 int ttm_pool_alloc(struct ttm_pool *pool, struct ttm_tt *tt,
362                    struct ttm_operation_ctx *ctx)
363 {
364         unsigned long num_pages = tt->num_pages;
365         dma_addr_t *dma_addr = tt->dma_address;
366         struct page **caching = tt->pages;
367         struct page **pages = tt->pages;
368         gfp_t gfp_flags = GFP_USER;
369         unsigned int i, order;
370         struct page *p;
371         int r;
372
373         WARN_ON(!num_pages || ttm_tt_is_populated(tt));
374         WARN_ON(dma_addr && !pool->dev);
375
376         if (tt->page_flags & TTM_PAGE_FLAG_ZERO_ALLOC)
377                 gfp_flags |= __GFP_ZERO;
378
379         if (ctx->gfp_retry_mayfail)
380                 gfp_flags |= __GFP_RETRY_MAYFAIL;
381
382         if (pool->use_dma32)
383                 gfp_flags |= GFP_DMA32;
384         else
385                 gfp_flags |= GFP_HIGHUSER;
386
387         for (order = min(MAX_ORDER - 1UL, __fls(num_pages)); num_pages;
388              order = min_t(unsigned int, order, __fls(num_pages))) {
389                 bool apply_caching = false;
390                 struct ttm_pool_type *pt;
391
392                 pt = ttm_pool_select_type(pool, tt->caching, order);
393                 p = pt ? ttm_pool_type_take(pt) : NULL;
394                 if (p) {
395                         apply_caching = true;
396                 } else {
397                         p = ttm_pool_alloc_page(pool, gfp_flags, order);
398                         if (p && PageHighMem(p))
399                                 apply_caching = true;
400                 }
401
402                 if (!p) {
403                         if (order) {
404                                 --order;
405                                 continue;
406                         }
407                         r = -ENOMEM;
408                         goto error_free_all;
409                 }
410
411                 if (apply_caching) {
412                         r = ttm_pool_apply_caching(caching, pages,
413                                                    tt->caching);
414                         if (r)
415                                 goto error_free_page;
416                         caching = pages + (1 << order);
417                 }
418
419                 r = ttm_mem_global_alloc_page(&ttm_mem_glob, p,
420                                               (1 << order) * PAGE_SIZE,
421                                               ctx);
422                 if (r)
423                         goto error_free_page;
424
425                 if (dma_addr) {
426                         r = ttm_pool_map(pool, order, p, &dma_addr);
427                         if (r)
428                                 goto error_global_free;
429                 }
430
431                 num_pages -= 1 << order;
432                 for (i = 1 << order; i; --i)
433                         *(pages++) = p++;
434         }
435
436         r = ttm_pool_apply_caching(caching, pages, tt->caching);
437         if (r)
438                 goto error_free_all;
439
440         return 0;
441
442 error_global_free:
443         ttm_mem_global_free_page(&ttm_mem_glob, p, (1 << order) * PAGE_SIZE);
444
445 error_free_page:
446         ttm_pool_free_page(pool, tt->caching, order, p);
447
448 error_free_all:
449         num_pages = tt->num_pages - num_pages;
450         for (i = 0; i < num_pages; ) {
451                 order = ttm_pool_page_order(pool, tt->pages[i]);
452                 ttm_pool_free_page(pool, tt->caching, order, tt->pages[i]);
453                 i += 1 << order;
454         }
455
456         return r;
457 }
458 EXPORT_SYMBOL(ttm_pool_alloc);
459
460 /**
461  * ttm_pool_free - Free the backing pages from a ttm_tt object
462  *
463  * @pool: Pool to give pages back to.
464  * @tt: ttm_tt object to unpopulate
465  *
466  * Give the packing pages back to a pool or free them
467  */
468 void ttm_pool_free(struct ttm_pool *pool, struct ttm_tt *tt)
469 {
470         unsigned int i;
471
472         for (i = 0; i < tt->num_pages; ) {
473                 struct page *p = tt->pages[i];
474                 unsigned int order, num_pages;
475                 struct ttm_pool_type *pt;
476
477                 order = ttm_pool_page_order(pool, p);
478                 num_pages = 1ULL << order;
479                 ttm_mem_global_free_page(&ttm_mem_glob, p,
480                                          num_pages * PAGE_SIZE);
481                 if (tt->dma_address)
482                         ttm_pool_unmap(pool, tt->dma_address[i], num_pages);
483
484                 pt = ttm_pool_select_type(pool, tt->caching, order);
485                 if (pt)
486                         ttm_pool_type_give(pt, tt->pages[i]);
487                 else
488                         ttm_pool_free_page(pool, tt->caching, order,
489                                            tt->pages[i]);
490
491                 i += num_pages;
492         }
493
494         while (atomic_long_read(&allocated_pages) > page_pool_size)
495                 ttm_pool_shrink();
496 }
497 EXPORT_SYMBOL(ttm_pool_free);
498
499 /**
500  * ttm_pool_init - Initialize a pool
501  *
502  * @pool: the pool to initialize
503  * @dev: device for DMA allocations and mappings
504  * @use_dma_alloc: true if coherent DMA alloc should be used
505  * @use_dma32: true if GFP_DMA32 should be used
506  *
507  * Initialize the pool and its pool types.
508  */
509 void ttm_pool_init(struct ttm_pool *pool, struct device *dev,
510                    bool use_dma_alloc, bool use_dma32)
511 {
512         unsigned int i, j;
513
514         WARN_ON(!dev && use_dma_alloc);
515
516         pool->dev = dev;
517         pool->use_dma_alloc = use_dma_alloc;
518         pool->use_dma32 = use_dma32;
519
520         for (i = 0; i < TTM_NUM_CACHING_TYPES; ++i)
521                 for (j = 0; j < MAX_ORDER; ++j)
522                         ttm_pool_type_init(&pool->caching[i].orders[j],
523                                            pool, i, j);
524 }
525 EXPORT_SYMBOL(ttm_pool_init);
526
527 /**
528  * ttm_pool_fini - Cleanup a pool
529  *
530  * @pool: the pool to clean up
531  *
532  * Free all pages in the pool and unregister the types from the global
533  * shrinker.
534  */
535 void ttm_pool_fini(struct ttm_pool *pool)
536 {
537         unsigned int i, j;
538
539         for (i = 0; i < TTM_NUM_CACHING_TYPES; ++i)
540                 for (j = 0; j < MAX_ORDER; ++j)
541                         ttm_pool_type_fini(&pool->caching[i].orders[j]);
542 }
543 EXPORT_SYMBOL(ttm_pool_fini);
544
545 #ifdef CONFIG_DEBUG_FS
546
547 /* Dump information about the different pool types */
548 static void ttm_pool_debugfs_orders(struct ttm_pool_type *pt,
549                                     struct seq_file *m)
550 {
551         unsigned int i;
552
553         for (i = 0; i < MAX_ORDER; ++i)
554                 seq_printf(m, " %8u", ttm_pool_type_count(&pt[i]));
555         seq_puts(m, "\n");
556 }
557
558 /**
559  * ttm_pool_debugfs - Debugfs dump function for a pool
560  *
561  * @pool: the pool to dump the information for
562  * @m: seq_file to dump to
563  *
564  * Make a debugfs dump with the per pool and global information.
565  */
566 int ttm_pool_debugfs(struct ttm_pool *pool, struct seq_file *m)
567 {
568         unsigned int i;
569
570         spin_lock(&shrinker_lock);
571
572         seq_puts(m, "\t ");
573         for (i = 0; i < MAX_ORDER; ++i)
574                 seq_printf(m, " ---%2u---", i);
575         seq_puts(m, "\n");
576
577         seq_puts(m, "wc\t:");
578         ttm_pool_debugfs_orders(global_write_combined, m);
579         seq_puts(m, "uc\t:");
580         ttm_pool_debugfs_orders(global_uncached, m);
581
582         seq_puts(m, "wc 32\t:");
583         ttm_pool_debugfs_orders(global_dma32_write_combined, m);
584         seq_puts(m, "uc 32\t:");
585         ttm_pool_debugfs_orders(global_dma32_uncached, m);
586
587         for (i = 0; i < TTM_NUM_CACHING_TYPES; ++i) {
588                 seq_puts(m, "DMA ");
589                 switch (i) {
590                 case ttm_cached:
591                         seq_puts(m, "\t:");
592                         break;
593                 case ttm_write_combined:
594                         seq_puts(m, "wc\t:");
595                         break;
596                 case ttm_uncached:
597                         seq_puts(m, "uc\t:");
598                         break;
599                 }
600                 ttm_pool_debugfs_orders(pool->caching[i].orders, m);
601         }
602
603         seq_printf(m, "\ntotal\t: %8lu of %8lu\n",
604                    atomic_long_read(&allocated_pages), page_pool_size);
605
606         spin_unlock(&shrinker_lock);
607
608         return 0;
609 }
610 EXPORT_SYMBOL(ttm_pool_debugfs);
611
612 #endif
613
614 /* As long as pages are available make sure to release at least one */
615 static unsigned long ttm_pool_shrinker_scan(struct shrinker *shrink,
616                                             struct shrink_control *sc)
617 {
618         unsigned long num_freed = 0;
619
620         do
621                 num_freed += ttm_pool_shrink();
622         while (!num_freed && atomic_long_read(&allocated_pages));
623
624         return num_freed;
625 }
626
627 /* Return the number of pages available or SHRINK_EMPTY if we have none */
628 static unsigned long ttm_pool_shrinker_count(struct shrinker *shrink,
629                                              struct shrink_control *sc)
630 {
631         unsigned long num_pages = atomic_long_read(&allocated_pages);
632
633         return num_pages ? num_pages : SHRINK_EMPTY;
634 }
635
636 /**
637  * ttm_pool_mgr_init - Initialize globals
638  *
639  * @num_pages: default number of pages
640  *
641  * Initialize the global locks and lists for the MM shrinker.
642  */
643 int ttm_pool_mgr_init(unsigned long num_pages)
644 {
645         unsigned int i;
646
647         if (!page_pool_size)
648                 page_pool_size = num_pages;
649
650         spin_lock_init(&shrinker_lock);
651         INIT_LIST_HEAD(&shrinker_list);
652
653         for (i = 0; i < MAX_ORDER; ++i) {
654                 ttm_pool_type_init(&global_write_combined[i], NULL,
655                                    ttm_write_combined, i);
656                 ttm_pool_type_init(&global_uncached[i], NULL, ttm_uncached, i);
657
658                 ttm_pool_type_init(&global_dma32_write_combined[i], NULL,
659                                    ttm_write_combined, i);
660                 ttm_pool_type_init(&global_dma32_uncached[i], NULL,
661                                    ttm_uncached, i);
662         }
663
664         mm_shrinker.count_objects = ttm_pool_shrinker_count;
665         mm_shrinker.scan_objects = ttm_pool_shrinker_scan;
666         mm_shrinker.seeks = 1;
667         return register_shrinker(&mm_shrinker);
668 }
669
670 /**
671  * ttm_pool_mgr_fini - Finalize globals
672  *
673  * Cleanup the global pools and unregister the MM shrinker.
674  */
675 void ttm_pool_mgr_fini(void)
676 {
677         unsigned int i;
678
679         for (i = 0; i < MAX_ORDER; ++i) {
680                 ttm_pool_type_fini(&global_write_combined[i]);
681                 ttm_pool_type_fini(&global_uncached[i]);
682
683                 ttm_pool_type_fini(&global_dma32_write_combined[i]);
684                 ttm_pool_type_fini(&global_dma32_uncached[i]);
685         }
686
687         unregister_shrinker(&mm_shrinker);
688         WARN_ON(!list_empty(&shrinker_list));
689 }