]> Git Repo - linux.git/blob - drivers/gpu/drm/ttm/ttm_page_alloc_dma.c
Merge tag 'modules-for-v4.16' of git://git.kernel.org/pub/scm/linux/kernel/git/jeyu...
[linux.git] / drivers / gpu / drm / ttm / ttm_page_alloc_dma.c
1 /*
2  * Copyright 2011 (c) Oracle Corp.
3
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sub license,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the
12  * next paragraph) shall be included in all copies or substantial portions
13  * 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 NON-INFRINGEMENT. IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Author: Konrad Rzeszutek Wilk <[email protected]>
24  */
25
26 /*
27  * A simple DMA pool losely based on dmapool.c. It has certain advantages
28  * over the DMA pools:
29  * - Pool collects resently freed pages for reuse (and hooks up to
30  *   the shrinker).
31  * - Tracks currently in use pages
32  * - Tracks whether the page is UC, WB or cached (and reverts to WB
33  *   when freed).
34  */
35
36 #if defined(CONFIG_SWIOTLB) || defined(CONFIG_INTEL_IOMMU)
37 #define pr_fmt(fmt) "[TTM] " fmt
38
39 #include <linux/dma-mapping.h>
40 #include <linux/list.h>
41 #include <linux/seq_file.h> /* for seq_printf */
42 #include <linux/slab.h>
43 #include <linux/spinlock.h>
44 #include <linux/highmem.h>
45 #include <linux/mm_types.h>
46 #include <linux/module.h>
47 #include <linux/mm.h>
48 #include <linux/atomic.h>
49 #include <linux/device.h>
50 #include <linux/kthread.h>
51 #include <drm/ttm/ttm_bo_driver.h>
52 #include <drm/ttm/ttm_page_alloc.h>
53 #if IS_ENABLED(CONFIG_AGP)
54 #include <asm/agp.h>
55 #endif
56 #ifdef CONFIG_X86
57 #include <asm/set_memory.h>
58 #endif
59
60 #define NUM_PAGES_TO_ALLOC              (PAGE_SIZE/sizeof(struct page *))
61 #define SMALL_ALLOCATION                4
62 #define FREE_ALL_PAGES                  (~0U)
63 #define VADDR_FLAG_HUGE_POOL            1UL
64 #define VADDR_FLAG_UPDATED_COUNT        2UL
65
66 enum pool_type {
67         IS_UNDEFINED    = 0,
68         IS_WC           = 1 << 1,
69         IS_UC           = 1 << 2,
70         IS_CACHED       = 1 << 3,
71         IS_DMA32        = 1 << 4,
72         IS_HUGE         = 1 << 5
73 };
74
75 /*
76  * The pool structure. There are up to nine pools:
77  *  - generic (not restricted to DMA32):
78  *      - write combined, uncached, cached.
79  *  - dma32 (up to 2^32 - so up 4GB):
80  *      - write combined, uncached, cached.
81  *  - huge (not restricted to DMA32):
82  *      - write combined, uncached, cached.
83  * for each 'struct device'. The 'cached' is for pages that are actively used.
84  * The other ones can be shrunk by the shrinker API if neccessary.
85  * @pools: The 'struct device->dma_pools' link.
86  * @type: Type of the pool
87  * @lock: Protects the free_list from concurrnet access. Must be
88  * used with irqsave/irqrestore variants because pool allocator maybe called
89  * from delayed work.
90  * @free_list: Pool of pages that are free to be used. No order requirements.
91  * @dev: The device that is associated with these pools.
92  * @size: Size used during DMA allocation.
93  * @npages_free: Count of available pages for re-use.
94  * @npages_in_use: Count of pages that are in use.
95  * @nfrees: Stats when pool is shrinking.
96  * @nrefills: Stats when the pool is grown.
97  * @gfp_flags: Flags to pass for alloc_page.
98  * @name: Name of the pool.
99  * @dev_name: Name derieved from dev - similar to how dev_info works.
100  *   Used during shutdown as the dev_info during release is unavailable.
101  */
102 struct dma_pool {
103         struct list_head pools; /* The 'struct device->dma_pools link */
104         enum pool_type type;
105         spinlock_t lock;
106         struct list_head free_list;
107         struct device *dev;
108         unsigned size;
109         unsigned npages_free;
110         unsigned npages_in_use;
111         unsigned long nfrees; /* Stats when shrunk. */
112         unsigned long nrefills; /* Stats when grown. */
113         gfp_t gfp_flags;
114         char name[13]; /* "cached dma32" */
115         char dev_name[64]; /* Constructed from dev */
116 };
117
118 /*
119  * The accounting page keeping track of the allocated page along with
120  * the DMA address.
121  * @page_list: The link to the 'page_list' in 'struct dma_pool'.
122  * @vaddr: The virtual address of the page and a flag if the page belongs to a
123  * huge pool
124  * @dma: The bus address of the page. If the page is not allocated
125  *   via the DMA API, it will be -1.
126  */
127 struct dma_page {
128         struct list_head page_list;
129         unsigned long vaddr;
130         struct page *p;
131         dma_addr_t dma;
132 };
133
134 /*
135  * Limits for the pool. They are handled without locks because only place where
136  * they may change is in sysfs store. They won't have immediate effect anyway
137  * so forcing serialization to access them is pointless.
138  */
139
140 struct ttm_pool_opts {
141         unsigned        alloc_size;
142         unsigned        max_size;
143         unsigned        small;
144 };
145
146 /*
147  * Contains the list of all of the 'struct device' and their corresponding
148  * DMA pools. Guarded by _mutex->lock.
149  * @pools: The link to 'struct ttm_pool_manager->pools'
150  * @dev: The 'struct device' associated with the 'pool'
151  * @pool: The 'struct dma_pool' associated with the 'dev'
152  */
153 struct device_pools {
154         struct list_head pools;
155         struct device *dev;
156         struct dma_pool *pool;
157 };
158
159 /*
160  * struct ttm_pool_manager - Holds memory pools for fast allocation
161  *
162  * @lock: Lock used when adding/removing from pools
163  * @pools: List of 'struct device' and 'struct dma_pool' tuples.
164  * @options: Limits for the pool.
165  * @npools: Total amount of pools in existence.
166  * @shrinker: The structure used by [un|]register_shrinker
167  */
168 struct ttm_pool_manager {
169         struct mutex            lock;
170         struct list_head        pools;
171         struct ttm_pool_opts    options;
172         unsigned                npools;
173         struct shrinker         mm_shrink;
174         struct kobject          kobj;
175 };
176
177 static struct ttm_pool_manager *_manager;
178
179 static struct attribute ttm_page_pool_max = {
180         .name = "pool_max_size",
181         .mode = S_IRUGO | S_IWUSR
182 };
183 static struct attribute ttm_page_pool_small = {
184         .name = "pool_small_allocation",
185         .mode = S_IRUGO | S_IWUSR
186 };
187 static struct attribute ttm_page_pool_alloc_size = {
188         .name = "pool_allocation_size",
189         .mode = S_IRUGO | S_IWUSR
190 };
191
192 static struct attribute *ttm_pool_attrs[] = {
193         &ttm_page_pool_max,
194         &ttm_page_pool_small,
195         &ttm_page_pool_alloc_size,
196         NULL
197 };
198
199 static void ttm_pool_kobj_release(struct kobject *kobj)
200 {
201         struct ttm_pool_manager *m =
202                 container_of(kobj, struct ttm_pool_manager, kobj);
203         kfree(m);
204 }
205
206 static ssize_t ttm_pool_store(struct kobject *kobj, struct attribute *attr,
207                               const char *buffer, size_t size)
208 {
209         struct ttm_pool_manager *m =
210                 container_of(kobj, struct ttm_pool_manager, kobj);
211         int chars;
212         unsigned val;
213         chars = sscanf(buffer, "%u", &val);
214         if (chars == 0)
215                 return size;
216
217         /* Convert kb to number of pages */
218         val = val / (PAGE_SIZE >> 10);
219
220         if (attr == &ttm_page_pool_max)
221                 m->options.max_size = val;
222         else if (attr == &ttm_page_pool_small)
223                 m->options.small = val;
224         else if (attr == &ttm_page_pool_alloc_size) {
225                 if (val > NUM_PAGES_TO_ALLOC*8) {
226                         pr_err("Setting allocation size to %lu is not allowed. Recommended size is %lu\n",
227                                NUM_PAGES_TO_ALLOC*(PAGE_SIZE >> 7),
228                                NUM_PAGES_TO_ALLOC*(PAGE_SIZE >> 10));
229                         return size;
230                 } else if (val > NUM_PAGES_TO_ALLOC) {
231                         pr_warn("Setting allocation size to larger than %lu is not recommended\n",
232                                 NUM_PAGES_TO_ALLOC*(PAGE_SIZE >> 10));
233                 }
234                 m->options.alloc_size = val;
235         }
236
237         return size;
238 }
239
240 static ssize_t ttm_pool_show(struct kobject *kobj, struct attribute *attr,
241                              char *buffer)
242 {
243         struct ttm_pool_manager *m =
244                 container_of(kobj, struct ttm_pool_manager, kobj);
245         unsigned val = 0;
246
247         if (attr == &ttm_page_pool_max)
248                 val = m->options.max_size;
249         else if (attr == &ttm_page_pool_small)
250                 val = m->options.small;
251         else if (attr == &ttm_page_pool_alloc_size)
252                 val = m->options.alloc_size;
253
254         val = val * (PAGE_SIZE >> 10);
255
256         return snprintf(buffer, PAGE_SIZE, "%u\n", val);
257 }
258
259 static const struct sysfs_ops ttm_pool_sysfs_ops = {
260         .show = &ttm_pool_show,
261         .store = &ttm_pool_store,
262 };
263
264 static struct kobj_type ttm_pool_kobj_type = {
265         .release = &ttm_pool_kobj_release,
266         .sysfs_ops = &ttm_pool_sysfs_ops,
267         .default_attrs = ttm_pool_attrs,
268 };
269
270 #ifndef CONFIG_X86
271 static int set_pages_array_wb(struct page **pages, int addrinarray)
272 {
273 #if IS_ENABLED(CONFIG_AGP)
274         int i;
275
276         for (i = 0; i < addrinarray; i++)
277                 unmap_page_from_agp(pages[i]);
278 #endif
279         return 0;
280 }
281
282 static int set_pages_array_wc(struct page **pages, int addrinarray)
283 {
284 #if IS_ENABLED(CONFIG_AGP)
285         int i;
286
287         for (i = 0; i < addrinarray; i++)
288                 map_page_into_agp(pages[i]);
289 #endif
290         return 0;
291 }
292
293 static int set_pages_array_uc(struct page **pages, int addrinarray)
294 {
295 #if IS_ENABLED(CONFIG_AGP)
296         int i;
297
298         for (i = 0; i < addrinarray; i++)
299                 map_page_into_agp(pages[i]);
300 #endif
301         return 0;
302 }
303 #endif /* for !CONFIG_X86 */
304
305 static int ttm_set_pages_caching(struct dma_pool *pool,
306                                  struct page **pages, unsigned cpages)
307 {
308         int r = 0;
309         /* Set page caching */
310         if (pool->type & IS_UC) {
311                 r = set_pages_array_uc(pages, cpages);
312                 if (r)
313                         pr_err("%s: Failed to set %d pages to uc!\n",
314                                pool->dev_name, cpages);
315         }
316         if (pool->type & IS_WC) {
317                 r = set_pages_array_wc(pages, cpages);
318                 if (r)
319                         pr_err("%s: Failed to set %d pages to wc!\n",
320                                pool->dev_name, cpages);
321         }
322         return r;
323 }
324
325 static void __ttm_dma_free_page(struct dma_pool *pool, struct dma_page *d_page)
326 {
327         dma_addr_t dma = d_page->dma;
328         d_page->vaddr &= ~VADDR_FLAG_HUGE_POOL;
329         dma_free_coherent(pool->dev, pool->size, (void *)d_page->vaddr, dma);
330
331         kfree(d_page);
332         d_page = NULL;
333 }
334 static struct dma_page *__ttm_dma_alloc_page(struct dma_pool *pool)
335 {
336         struct dma_page *d_page;
337         unsigned long attrs = 0;
338         void *vaddr;
339
340         d_page = kmalloc(sizeof(struct dma_page), GFP_KERNEL);
341         if (!d_page)
342                 return NULL;
343
344         if (pool->type & IS_HUGE)
345                 attrs = DMA_ATTR_NO_WARN;
346
347         vaddr = dma_alloc_attrs(pool->dev, pool->size, &d_page->dma,
348                                 pool->gfp_flags, attrs);
349         if (vaddr) {
350                 if (is_vmalloc_addr(vaddr))
351                         d_page->p = vmalloc_to_page(vaddr);
352                 else
353                         d_page->p = virt_to_page(vaddr);
354                 d_page->vaddr = (unsigned long)vaddr;
355                 if (pool->type & IS_HUGE)
356                         d_page->vaddr |= VADDR_FLAG_HUGE_POOL;
357         } else {
358                 kfree(d_page);
359                 d_page = NULL;
360         }
361         return d_page;
362 }
363 static enum pool_type ttm_to_type(int flags, enum ttm_caching_state cstate)
364 {
365         enum pool_type type = IS_UNDEFINED;
366
367         if (flags & TTM_PAGE_FLAG_DMA32)
368                 type |= IS_DMA32;
369         if (cstate == tt_cached)
370                 type |= IS_CACHED;
371         else if (cstate == tt_uncached)
372                 type |= IS_UC;
373         else
374                 type |= IS_WC;
375
376         return type;
377 }
378
379 static void ttm_pool_update_free_locked(struct dma_pool *pool,
380                                         unsigned freed_pages)
381 {
382         pool->npages_free -= freed_pages;
383         pool->nfrees += freed_pages;
384
385 }
386
387 /* set memory back to wb and free the pages. */
388 static void ttm_dma_page_put(struct dma_pool *pool, struct dma_page *d_page)
389 {
390         struct page *page = d_page->p;
391         unsigned i, num_pages;
392         int ret;
393
394         /* Don't set WB on WB page pool. */
395         if (!(pool->type & IS_CACHED)) {
396                 num_pages = pool->size / PAGE_SIZE;
397                 for (i = 0; i < num_pages; ++i, ++page) {
398                         ret = set_pages_array_wb(&page, 1);
399                         if (ret) {
400                                 pr_err("%s: Failed to set %d pages to wb!\n",
401                                        pool->dev_name, 1);
402                         }
403                 }
404         }
405
406         list_del(&d_page->page_list);
407         __ttm_dma_free_page(pool, d_page);
408 }
409
410 static void ttm_dma_pages_put(struct dma_pool *pool, struct list_head *d_pages,
411                               struct page *pages[], unsigned npages)
412 {
413         struct dma_page *d_page, *tmp;
414
415         if (pool->type & IS_HUGE) {
416                 list_for_each_entry_safe(d_page, tmp, d_pages, page_list)
417                         ttm_dma_page_put(pool, d_page);
418
419                 return;
420         }
421
422         /* Don't set WB on WB page pool. */
423         if (npages && !(pool->type & IS_CACHED) &&
424             set_pages_array_wb(pages, npages))
425                 pr_err("%s: Failed to set %d pages to wb!\n",
426                        pool->dev_name, npages);
427
428         list_for_each_entry_safe(d_page, tmp, d_pages, page_list) {
429                 list_del(&d_page->page_list);
430                 __ttm_dma_free_page(pool, d_page);
431         }
432 }
433
434 /*
435  * Free pages from pool.
436  *
437  * To prevent hogging the ttm_swap process we only free NUM_PAGES_TO_ALLOC
438  * number of pages in one go.
439  *
440  * @pool: to free the pages from
441  * @nr_free: If set to true will free all pages in pool
442  * @use_static: Safe to use static buffer
443  **/
444 static unsigned ttm_dma_page_pool_free(struct dma_pool *pool, unsigned nr_free,
445                                        bool use_static)
446 {
447         static struct page *static_buf[NUM_PAGES_TO_ALLOC];
448         unsigned long irq_flags;
449         struct dma_page *dma_p, *tmp;
450         struct page **pages_to_free;
451         struct list_head d_pages;
452         unsigned freed_pages = 0,
453                  npages_to_free = nr_free;
454
455         if (NUM_PAGES_TO_ALLOC < nr_free)
456                 npages_to_free = NUM_PAGES_TO_ALLOC;
457 #if 0
458         if (nr_free > 1) {
459                 pr_debug("%s: (%s:%d) Attempting to free %d (%d) pages\n",
460                          pool->dev_name, pool->name, current->pid,
461                          npages_to_free, nr_free);
462         }
463 #endif
464         if (use_static)
465                 pages_to_free = static_buf;
466         else
467                 pages_to_free = kmalloc(npages_to_free * sizeof(struct page *),
468                                         GFP_KERNEL);
469
470         if (!pages_to_free) {
471                 pr_debug("%s: Failed to allocate memory for pool free operation\n",
472                        pool->dev_name);
473                 return 0;
474         }
475         INIT_LIST_HEAD(&d_pages);
476 restart:
477         spin_lock_irqsave(&pool->lock, irq_flags);
478
479         /* We picking the oldest ones off the list */
480         list_for_each_entry_safe_reverse(dma_p, tmp, &pool->free_list,
481                                          page_list) {
482                 if (freed_pages >= npages_to_free)
483                         break;
484
485                 /* Move the dma_page from one list to another. */
486                 list_move(&dma_p->page_list, &d_pages);
487
488                 pages_to_free[freed_pages++] = dma_p->p;
489                 /* We can only remove NUM_PAGES_TO_ALLOC at a time. */
490                 if (freed_pages >= NUM_PAGES_TO_ALLOC) {
491
492                         ttm_pool_update_free_locked(pool, freed_pages);
493                         /**
494                          * Because changing page caching is costly
495                          * we unlock the pool to prevent stalling.
496                          */
497                         spin_unlock_irqrestore(&pool->lock, irq_flags);
498
499                         ttm_dma_pages_put(pool, &d_pages, pages_to_free,
500                                           freed_pages);
501
502                         INIT_LIST_HEAD(&d_pages);
503
504                         if (likely(nr_free != FREE_ALL_PAGES))
505                                 nr_free -= freed_pages;
506
507                         if (NUM_PAGES_TO_ALLOC >= nr_free)
508                                 npages_to_free = nr_free;
509                         else
510                                 npages_to_free = NUM_PAGES_TO_ALLOC;
511
512                         freed_pages = 0;
513
514                         /* free all so restart the processing */
515                         if (nr_free)
516                                 goto restart;
517
518                         /* Not allowed to fall through or break because
519                          * following context is inside spinlock while we are
520                          * outside here.
521                          */
522                         goto out;
523
524                 }
525         }
526
527         /* remove range of pages from the pool */
528         if (freed_pages) {
529                 ttm_pool_update_free_locked(pool, freed_pages);
530                 nr_free -= freed_pages;
531         }
532
533         spin_unlock_irqrestore(&pool->lock, irq_flags);
534
535         if (freed_pages)
536                 ttm_dma_pages_put(pool, &d_pages, pages_to_free, freed_pages);
537 out:
538         if (pages_to_free != static_buf)
539                 kfree(pages_to_free);
540         return nr_free;
541 }
542
543 static void ttm_dma_free_pool(struct device *dev, enum pool_type type)
544 {
545         struct device_pools *p;
546         struct dma_pool *pool;
547
548         if (!dev)
549                 return;
550
551         mutex_lock(&_manager->lock);
552         list_for_each_entry_reverse(p, &_manager->pools, pools) {
553                 if (p->dev != dev)
554                         continue;
555                 pool = p->pool;
556                 if (pool->type != type)
557                         continue;
558
559                 list_del(&p->pools);
560                 kfree(p);
561                 _manager->npools--;
562                 break;
563         }
564         list_for_each_entry_reverse(pool, &dev->dma_pools, pools) {
565                 if (pool->type != type)
566                         continue;
567                 /* Takes a spinlock.. */
568                 /* OK to use static buffer since global mutex is held. */
569                 ttm_dma_page_pool_free(pool, FREE_ALL_PAGES, true);
570                 WARN_ON(((pool->npages_in_use + pool->npages_free) != 0));
571                 /* This code path is called after _all_ references to the
572                  * struct device has been dropped - so nobody should be
573                  * touching it. In case somebody is trying to _add_ we are
574                  * guarded by the mutex. */
575                 list_del(&pool->pools);
576                 kfree(pool);
577                 break;
578         }
579         mutex_unlock(&_manager->lock);
580 }
581
582 /*
583  * On free-ing of the 'struct device' this deconstructor is run.
584  * Albeit the pool might have already been freed earlier.
585  */
586 static void ttm_dma_pool_release(struct device *dev, void *res)
587 {
588         struct dma_pool *pool = *(struct dma_pool **)res;
589
590         if (pool)
591                 ttm_dma_free_pool(dev, pool->type);
592 }
593
594 static int ttm_dma_pool_match(struct device *dev, void *res, void *match_data)
595 {
596         return *(struct dma_pool **)res == match_data;
597 }
598
599 static struct dma_pool *ttm_dma_pool_init(struct device *dev, gfp_t flags,
600                                           enum pool_type type)
601 {
602         const char *n[] = {"wc", "uc", "cached", " dma32", "huge"};
603         enum pool_type t[] = {IS_WC, IS_UC, IS_CACHED, IS_DMA32, IS_HUGE};
604         struct device_pools *sec_pool = NULL;
605         struct dma_pool *pool = NULL, **ptr;
606         unsigned i;
607         int ret = -ENODEV;
608         char *p;
609
610         if (!dev)
611                 return NULL;
612
613         ptr = devres_alloc(ttm_dma_pool_release, sizeof(*ptr), GFP_KERNEL);
614         if (!ptr)
615                 return NULL;
616
617         ret = -ENOMEM;
618
619         pool = kmalloc_node(sizeof(struct dma_pool), GFP_KERNEL,
620                             dev_to_node(dev));
621         if (!pool)
622                 goto err_mem;
623
624         sec_pool = kmalloc_node(sizeof(struct device_pools), GFP_KERNEL,
625                                 dev_to_node(dev));
626         if (!sec_pool)
627                 goto err_mem;
628
629         INIT_LIST_HEAD(&sec_pool->pools);
630         sec_pool->dev = dev;
631         sec_pool->pool =  pool;
632
633         INIT_LIST_HEAD(&pool->free_list);
634         INIT_LIST_HEAD(&pool->pools);
635         spin_lock_init(&pool->lock);
636         pool->dev = dev;
637         pool->npages_free = pool->npages_in_use = 0;
638         pool->nfrees = 0;
639         pool->gfp_flags = flags;
640         if (type & IS_HUGE)
641 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
642                 pool->size = HPAGE_PMD_SIZE;
643 #else
644                 BUG();
645 #endif
646         else
647                 pool->size = PAGE_SIZE;
648         pool->type = type;
649         pool->nrefills = 0;
650         p = pool->name;
651         for (i = 0; i < ARRAY_SIZE(t); i++) {
652                 if (type & t[i]) {
653                         p += snprintf(p, sizeof(pool->name) - (p - pool->name),
654                                       "%s", n[i]);
655                 }
656         }
657         *p = 0;
658         /* We copy the name for pr_ calls b/c when dma_pool_destroy is called
659          * - the kobj->name has already been deallocated.*/
660         snprintf(pool->dev_name, sizeof(pool->dev_name), "%s %s",
661                  dev_driver_string(dev), dev_name(dev));
662         mutex_lock(&_manager->lock);
663         /* You can get the dma_pool from either the global: */
664         list_add(&sec_pool->pools, &_manager->pools);
665         _manager->npools++;
666         /* or from 'struct device': */
667         list_add(&pool->pools, &dev->dma_pools);
668         mutex_unlock(&_manager->lock);
669
670         *ptr = pool;
671         devres_add(dev, ptr);
672
673         return pool;
674 err_mem:
675         devres_free(ptr);
676         kfree(sec_pool);
677         kfree(pool);
678         return ERR_PTR(ret);
679 }
680
681 static struct dma_pool *ttm_dma_find_pool(struct device *dev,
682                                           enum pool_type type)
683 {
684         struct dma_pool *pool, *tmp, *found = NULL;
685
686         if (type == IS_UNDEFINED)
687                 return found;
688
689         /* NB: We iterate on the 'struct dev' which has no spinlock, but
690          * it does have a kref which we have taken. The kref is taken during
691          * graphic driver loading - in the drm_pci_init it calls either
692          * pci_dev_get or pci_register_driver which both end up taking a kref
693          * on 'struct device'.
694          *
695          * On teardown, the graphic drivers end up quiescing the TTM (put_pages)
696          * and calls the dev_res deconstructors: ttm_dma_pool_release. The nice
697          * thing is at that point of time there are no pages associated with the
698          * driver so this function will not be called.
699          */
700         list_for_each_entry_safe(pool, tmp, &dev->dma_pools, pools) {
701                 if (pool->type != type)
702                         continue;
703                 found = pool;
704                 break;
705         }
706         return found;
707 }
708
709 /*
710  * Free pages the pages that failed to change the caching state. If there
711  * are pages that have changed their caching state already put them to the
712  * pool.
713  */
714 static void ttm_dma_handle_caching_state_failure(struct dma_pool *pool,
715                                                  struct list_head *d_pages,
716                                                  struct page **failed_pages,
717                                                  unsigned cpages)
718 {
719         struct dma_page *d_page, *tmp;
720         struct page *p;
721         unsigned i = 0;
722
723         p = failed_pages[0];
724         if (!p)
725                 return;
726         /* Find the failed page. */
727         list_for_each_entry_safe(d_page, tmp, d_pages, page_list) {
728                 if (d_page->p != p)
729                         continue;
730                 /* .. and then progress over the full list. */
731                 list_del(&d_page->page_list);
732                 __ttm_dma_free_page(pool, d_page);
733                 if (++i < cpages)
734                         p = failed_pages[i];
735                 else
736                         break;
737         }
738
739 }
740
741 /*
742  * Allocate 'count' pages, and put 'need' number of them on the
743  * 'pages' and as well on the 'dma_address' starting at 'dma_offset' offset.
744  * The full list of pages should also be on 'd_pages'.
745  * We return zero for success, and negative numbers as errors.
746  */
747 static int ttm_dma_pool_alloc_new_pages(struct dma_pool *pool,
748                                         struct list_head *d_pages,
749                                         unsigned count)
750 {
751         struct page **caching_array;
752         struct dma_page *dma_p;
753         struct page *p;
754         int r = 0;
755         unsigned i, j, npages, cpages;
756         unsigned max_cpages = min(count,
757                         (unsigned)(PAGE_SIZE/sizeof(struct page *)));
758
759         /* allocate array for page caching change */
760         caching_array = kmalloc(max_cpages*sizeof(struct page *), GFP_KERNEL);
761
762         if (!caching_array) {
763                 pr_debug("%s: Unable to allocate table for new pages\n",
764                        pool->dev_name);
765                 return -ENOMEM;
766         }
767
768         if (count > 1) {
769                 pr_debug("%s: (%s:%d) Getting %d pages\n",
770                          pool->dev_name, pool->name, current->pid, count);
771         }
772
773         for (i = 0, cpages = 0; i < count; ++i) {
774                 dma_p = __ttm_dma_alloc_page(pool);
775                 if (!dma_p) {
776                         pr_debug("%s: Unable to get page %u\n",
777                                  pool->dev_name, i);
778
779                         /* store already allocated pages in the pool after
780                          * setting the caching state */
781                         if (cpages) {
782                                 r = ttm_set_pages_caching(pool, caching_array,
783                                                           cpages);
784                                 if (r)
785                                         ttm_dma_handle_caching_state_failure(
786                                                 pool, d_pages, caching_array,
787                                                 cpages);
788                         }
789                         r = -ENOMEM;
790                         goto out;
791                 }
792                 p = dma_p->p;
793                 list_add(&dma_p->page_list, d_pages);
794
795 #ifdef CONFIG_HIGHMEM
796                 /* gfp flags of highmem page should never be dma32 so we
797                  * we should be fine in such case
798                  */
799                 if (PageHighMem(p))
800                         continue;
801 #endif
802
803                 npages = pool->size / PAGE_SIZE;
804                 for (j = 0; j < npages; ++j) {
805                         caching_array[cpages++] = p + j;
806                         if (cpages == max_cpages) {
807                                 /* Note: Cannot hold the spinlock */
808                                 r = ttm_set_pages_caching(pool, caching_array,
809                                                           cpages);
810                                 if (r) {
811                                         ttm_dma_handle_caching_state_failure(
812                                              pool, d_pages, caching_array,
813                                              cpages);
814                                         goto out;
815                                 }
816                                 cpages = 0;
817                         }
818                 }
819         }
820
821         if (cpages) {
822                 r = ttm_set_pages_caching(pool, caching_array, cpages);
823                 if (r)
824                         ttm_dma_handle_caching_state_failure(pool, d_pages,
825                                         caching_array, cpages);
826         }
827 out:
828         kfree(caching_array);
829         return r;
830 }
831
832 /*
833  * @return count of pages still required to fulfill the request.
834  */
835 static int ttm_dma_page_pool_fill_locked(struct dma_pool *pool,
836                                          unsigned long *irq_flags)
837 {
838         unsigned count = _manager->options.small;
839         int r = pool->npages_free;
840
841         if (count > pool->npages_free) {
842                 struct list_head d_pages;
843
844                 INIT_LIST_HEAD(&d_pages);
845
846                 spin_unlock_irqrestore(&pool->lock, *irq_flags);
847
848                 /* Returns how many more are neccessary to fulfill the
849                  * request. */
850                 r = ttm_dma_pool_alloc_new_pages(pool, &d_pages, count);
851
852                 spin_lock_irqsave(&pool->lock, *irq_flags);
853                 if (!r) {
854                         /* Add the fresh to the end.. */
855                         list_splice(&d_pages, &pool->free_list);
856                         ++pool->nrefills;
857                         pool->npages_free += count;
858                         r = count;
859                 } else {
860                         struct dma_page *d_page;
861                         unsigned cpages = 0;
862
863                         pr_debug("%s: Failed to fill %s pool (r:%d)!\n",
864                                  pool->dev_name, pool->name, r);
865
866                         list_for_each_entry(d_page, &d_pages, page_list) {
867                                 cpages++;
868                         }
869                         list_splice_tail(&d_pages, &pool->free_list);
870                         pool->npages_free += cpages;
871                         r = cpages;
872                 }
873         }
874         return r;
875 }
876
877 /*
878  * The populate list is actually a stack (not that is matters as TTM
879  * allocates one page at a time.
880  * return dma_page pointer if success, otherwise NULL.
881  */
882 static struct dma_page *ttm_dma_pool_get_pages(struct dma_pool *pool,
883                                   struct ttm_dma_tt *ttm_dma,
884                                   unsigned index)
885 {
886         struct dma_page *d_page = NULL;
887         struct ttm_tt *ttm = &ttm_dma->ttm;
888         unsigned long irq_flags;
889         int count;
890
891         spin_lock_irqsave(&pool->lock, irq_flags);
892         count = ttm_dma_page_pool_fill_locked(pool, &irq_flags);
893         if (count) {
894                 d_page = list_first_entry(&pool->free_list, struct dma_page, page_list);
895                 ttm->pages[index] = d_page->p;
896                 ttm_dma->dma_address[index] = d_page->dma;
897                 list_move_tail(&d_page->page_list, &ttm_dma->pages_list);
898                 pool->npages_in_use += 1;
899                 pool->npages_free -= 1;
900         }
901         spin_unlock_irqrestore(&pool->lock, irq_flags);
902         return d_page;
903 }
904
905 static gfp_t ttm_dma_pool_gfp_flags(struct ttm_dma_tt *ttm_dma, bool huge)
906 {
907         struct ttm_tt *ttm = &ttm_dma->ttm;
908         gfp_t gfp_flags;
909
910         if (ttm->page_flags & TTM_PAGE_FLAG_DMA32)
911                 gfp_flags = GFP_USER | GFP_DMA32;
912         else
913                 gfp_flags = GFP_HIGHUSER;
914         if (ttm->page_flags & TTM_PAGE_FLAG_ZERO_ALLOC)
915                 gfp_flags |= __GFP_ZERO;
916
917         if (huge) {
918                 gfp_flags |= GFP_TRANSHUGE;
919                 gfp_flags &= ~__GFP_MOVABLE;
920                 gfp_flags &= ~__GFP_COMP;
921         }
922
923         return gfp_flags;
924 }
925
926 /*
927  * On success pages list will hold count number of correctly
928  * cached pages. On failure will hold the negative return value (-ENOMEM, etc).
929  */
930 int ttm_dma_populate(struct ttm_dma_tt *ttm_dma, struct device *dev,
931                         struct ttm_operation_ctx *ctx)
932 {
933         struct ttm_tt *ttm = &ttm_dma->ttm;
934         struct ttm_mem_global *mem_glob = ttm->glob->mem_glob;
935         unsigned long num_pages = ttm->num_pages;
936         struct dma_pool *pool;
937         struct dma_page *d_page;
938         enum pool_type type;
939         unsigned i;
940         int ret;
941
942         if (ttm->state != tt_unpopulated)
943                 return 0;
944
945         INIT_LIST_HEAD(&ttm_dma->pages_list);
946         i = 0;
947
948         type = ttm_to_type(ttm->page_flags, ttm->caching_state);
949
950 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
951         if (ttm->page_flags & TTM_PAGE_FLAG_DMA32)
952                 goto skip_huge;
953
954         pool = ttm_dma_find_pool(dev, type | IS_HUGE);
955         if (!pool) {
956                 gfp_t gfp_flags = ttm_dma_pool_gfp_flags(ttm_dma, true);
957
958                 pool = ttm_dma_pool_init(dev, gfp_flags, type | IS_HUGE);
959                 if (IS_ERR_OR_NULL(pool))
960                         goto skip_huge;
961         }
962
963         while (num_pages >= HPAGE_PMD_NR) {
964                 unsigned j;
965
966                 d_page = ttm_dma_pool_get_pages(pool, ttm_dma, i);
967                 if (!d_page)
968                         break;
969
970                 ret = ttm_mem_global_alloc_page(mem_glob, ttm->pages[i],
971                                                 pool->size, ctx);
972                 if (unlikely(ret != 0)) {
973                         ttm_dma_unpopulate(ttm_dma, dev);
974                         return -ENOMEM;
975                 }
976
977                 d_page->vaddr |= VADDR_FLAG_UPDATED_COUNT;
978                 for (j = i + 1; j < (i + HPAGE_PMD_NR); ++j) {
979                         ttm->pages[j] = ttm->pages[j - 1] + 1;
980                         ttm_dma->dma_address[j] = ttm_dma->dma_address[j - 1] +
981                                 PAGE_SIZE;
982                 }
983
984                 i += HPAGE_PMD_NR;
985                 num_pages -= HPAGE_PMD_NR;
986         }
987
988 skip_huge:
989 #endif
990
991         pool = ttm_dma_find_pool(dev, type);
992         if (!pool) {
993                 gfp_t gfp_flags = ttm_dma_pool_gfp_flags(ttm_dma, false);
994
995                 pool = ttm_dma_pool_init(dev, gfp_flags, type);
996                 if (IS_ERR_OR_NULL(pool))
997                         return -ENOMEM;
998         }
999
1000         while (num_pages) {
1001                 d_page = ttm_dma_pool_get_pages(pool, ttm_dma, i);
1002                 if (!d_page) {
1003                         ttm_dma_unpopulate(ttm_dma, dev);
1004                         return -ENOMEM;
1005                 }
1006
1007                 ret = ttm_mem_global_alloc_page(mem_glob, ttm->pages[i],
1008                                                 pool->size, ctx);
1009                 if (unlikely(ret != 0)) {
1010                         ttm_dma_unpopulate(ttm_dma, dev);
1011                         return -ENOMEM;
1012                 }
1013
1014                 d_page->vaddr |= VADDR_FLAG_UPDATED_COUNT;
1015                 ++i;
1016                 --num_pages;
1017         }
1018
1019         if (unlikely(ttm->page_flags & TTM_PAGE_FLAG_SWAPPED)) {
1020                 ret = ttm_tt_swapin(ttm);
1021                 if (unlikely(ret != 0)) {
1022                         ttm_dma_unpopulate(ttm_dma, dev);
1023                         return ret;
1024                 }
1025         }
1026
1027         ttm->state = tt_unbound;
1028         return 0;
1029 }
1030 EXPORT_SYMBOL_GPL(ttm_dma_populate);
1031
1032 /* Put all pages in pages list to correct pool to wait for reuse */
1033 void ttm_dma_unpopulate(struct ttm_dma_tt *ttm_dma, struct device *dev)
1034 {
1035         struct ttm_tt *ttm = &ttm_dma->ttm;
1036         struct dma_pool *pool;
1037         struct dma_page *d_page, *next;
1038         enum pool_type type;
1039         bool is_cached = false;
1040         unsigned count, i, npages = 0;
1041         unsigned long irq_flags;
1042
1043         type = ttm_to_type(ttm->page_flags, ttm->caching_state);
1044
1045 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1046         pool = ttm_dma_find_pool(dev, type | IS_HUGE);
1047         if (pool) {
1048                 count = 0;
1049                 list_for_each_entry_safe(d_page, next, &ttm_dma->pages_list,
1050                                          page_list) {
1051                         if (!(d_page->vaddr & VADDR_FLAG_HUGE_POOL))
1052                                 continue;
1053
1054                         count++;
1055                         if (d_page->vaddr & VADDR_FLAG_UPDATED_COUNT) {
1056                                 ttm_mem_global_free_page(ttm->glob->mem_glob,
1057                                                          d_page->p, pool->size);
1058                                 d_page->vaddr &= ~VADDR_FLAG_UPDATED_COUNT;
1059                         }
1060                         ttm_dma_page_put(pool, d_page);
1061                 }
1062
1063                 spin_lock_irqsave(&pool->lock, irq_flags);
1064                 pool->npages_in_use -= count;
1065                 pool->nfrees += count;
1066                 spin_unlock_irqrestore(&pool->lock, irq_flags);
1067         }
1068 #endif
1069
1070         pool = ttm_dma_find_pool(dev, type);
1071         if (!pool)
1072                 return;
1073
1074         is_cached = (ttm_dma_find_pool(pool->dev,
1075                      ttm_to_type(ttm->page_flags, tt_cached)) == pool);
1076
1077         /* make sure pages array match list and count number of pages */
1078         count = 0;
1079         list_for_each_entry_safe(d_page, next, &ttm_dma->pages_list,
1080                                  page_list) {
1081                 ttm->pages[count] = d_page->p;
1082                 count++;
1083
1084                 if (d_page->vaddr & VADDR_FLAG_UPDATED_COUNT) {
1085                         ttm_mem_global_free_page(ttm->glob->mem_glob,
1086                                                  d_page->p, pool->size);
1087                         d_page->vaddr &= ~VADDR_FLAG_UPDATED_COUNT;
1088                 }
1089
1090                 if (is_cached)
1091                         ttm_dma_page_put(pool, d_page);
1092         }
1093
1094         spin_lock_irqsave(&pool->lock, irq_flags);
1095         pool->npages_in_use -= count;
1096         if (is_cached) {
1097                 pool->nfrees += count;
1098         } else {
1099                 pool->npages_free += count;
1100                 list_splice(&ttm_dma->pages_list, &pool->free_list);
1101                 /*
1102                  * Wait to have at at least NUM_PAGES_TO_ALLOC number of pages
1103                  * to free in order to minimize calls to set_memory_wb().
1104                  */
1105                 if (pool->npages_free >= (_manager->options.max_size +
1106                                           NUM_PAGES_TO_ALLOC))
1107                         npages = pool->npages_free - _manager->options.max_size;
1108         }
1109         spin_unlock_irqrestore(&pool->lock, irq_flags);
1110
1111         INIT_LIST_HEAD(&ttm_dma->pages_list);
1112         for (i = 0; i < ttm->num_pages; i++) {
1113                 ttm->pages[i] = NULL;
1114                 ttm_dma->dma_address[i] = 0;
1115         }
1116
1117         /* shrink pool if necessary (only on !is_cached pools)*/
1118         if (npages)
1119                 ttm_dma_page_pool_free(pool, npages, false);
1120         ttm->state = tt_unpopulated;
1121 }
1122 EXPORT_SYMBOL_GPL(ttm_dma_unpopulate);
1123
1124 /**
1125  * Callback for mm to request pool to reduce number of page held.
1126  *
1127  * XXX: (dchinner) Deadlock warning!
1128  *
1129  * I'm getting sadder as I hear more pathetical whimpers about needing per-pool
1130  * shrinkers
1131  */
1132 static unsigned long
1133 ttm_dma_pool_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
1134 {
1135         static unsigned start_pool;
1136         unsigned idx = 0;
1137         unsigned pool_offset;
1138         unsigned shrink_pages = sc->nr_to_scan;
1139         struct device_pools *p;
1140         unsigned long freed = 0;
1141
1142         if (list_empty(&_manager->pools))
1143                 return SHRINK_STOP;
1144
1145         if (!mutex_trylock(&_manager->lock))
1146                 return SHRINK_STOP;
1147         if (!_manager->npools)
1148                 goto out;
1149         pool_offset = ++start_pool % _manager->npools;
1150         list_for_each_entry(p, &_manager->pools, pools) {
1151                 unsigned nr_free;
1152
1153                 if (!p->dev)
1154                         continue;
1155                 if (shrink_pages == 0)
1156                         break;
1157                 /* Do it in round-robin fashion. */
1158                 if (++idx < pool_offset)
1159                         continue;
1160                 nr_free = shrink_pages;
1161                 /* OK to use static buffer since global mutex is held. */
1162                 shrink_pages = ttm_dma_page_pool_free(p->pool, nr_free, true);
1163                 freed += nr_free - shrink_pages;
1164
1165                 pr_debug("%s: (%s:%d) Asked to shrink %d, have %d more to go\n",
1166                          p->pool->dev_name, p->pool->name, current->pid,
1167                          nr_free, shrink_pages);
1168         }
1169 out:
1170         mutex_unlock(&_manager->lock);
1171         return freed;
1172 }
1173
1174 static unsigned long
1175 ttm_dma_pool_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
1176 {
1177         struct device_pools *p;
1178         unsigned long count = 0;
1179
1180         if (!mutex_trylock(&_manager->lock))
1181                 return 0;
1182         list_for_each_entry(p, &_manager->pools, pools)
1183                 count += p->pool->npages_free;
1184         mutex_unlock(&_manager->lock);
1185         return count;
1186 }
1187
1188 static int ttm_dma_pool_mm_shrink_init(struct ttm_pool_manager *manager)
1189 {
1190         manager->mm_shrink.count_objects = ttm_dma_pool_shrink_count;
1191         manager->mm_shrink.scan_objects = &ttm_dma_pool_shrink_scan;
1192         manager->mm_shrink.seeks = 1;
1193         return register_shrinker(&manager->mm_shrink);
1194 }
1195
1196 static void ttm_dma_pool_mm_shrink_fini(struct ttm_pool_manager *manager)
1197 {
1198         unregister_shrinker(&manager->mm_shrink);
1199 }
1200
1201 int ttm_dma_page_alloc_init(struct ttm_mem_global *glob, unsigned max_pages)
1202 {
1203         int ret;
1204
1205         WARN_ON(_manager);
1206
1207         pr_info("Initializing DMA pool allocator\n");
1208
1209         _manager = kzalloc(sizeof(*_manager), GFP_KERNEL);
1210         if (!_manager)
1211                 return -ENOMEM;
1212
1213         mutex_init(&_manager->lock);
1214         INIT_LIST_HEAD(&_manager->pools);
1215
1216         _manager->options.max_size = max_pages;
1217         _manager->options.small = SMALL_ALLOCATION;
1218         _manager->options.alloc_size = NUM_PAGES_TO_ALLOC;
1219
1220         /* This takes care of auto-freeing the _manager */
1221         ret = kobject_init_and_add(&_manager->kobj, &ttm_pool_kobj_type,
1222                                    &glob->kobj, "dma_pool");
1223         if (unlikely(ret != 0))
1224                 goto error;
1225
1226         ret = ttm_dma_pool_mm_shrink_init(_manager);
1227         if (unlikely(ret != 0))
1228                 goto error;
1229         return 0;
1230
1231 error:
1232         kobject_put(&_manager->kobj);
1233         _manager = NULL;
1234         return ret;
1235 }
1236
1237 void ttm_dma_page_alloc_fini(void)
1238 {
1239         struct device_pools *p, *t;
1240
1241         pr_info("Finalizing DMA pool allocator\n");
1242         ttm_dma_pool_mm_shrink_fini(_manager);
1243
1244         list_for_each_entry_safe_reverse(p, t, &_manager->pools, pools) {
1245                 dev_dbg(p->dev, "(%s:%d) Freeing.\n", p->pool->name,
1246                         current->pid);
1247                 WARN_ON(devres_destroy(p->dev, ttm_dma_pool_release,
1248                         ttm_dma_pool_match, p->pool));
1249                 ttm_dma_free_pool(p->dev, p->pool->type);
1250         }
1251         kobject_put(&_manager->kobj);
1252         _manager = NULL;
1253 }
1254
1255 int ttm_dma_page_alloc_debugfs(struct seq_file *m, void *data)
1256 {
1257         struct device_pools *p;
1258         struct dma_pool *pool = NULL;
1259
1260         if (!_manager) {
1261                 seq_printf(m, "No pool allocator running.\n");
1262                 return 0;
1263         }
1264         seq_printf(m, "         pool      refills   pages freed    inuse available     name\n");
1265         mutex_lock(&_manager->lock);
1266         list_for_each_entry(p, &_manager->pools, pools) {
1267                 struct device *dev = p->dev;
1268                 if (!dev)
1269                         continue;
1270                 pool = p->pool;
1271                 seq_printf(m, "%13s %12ld %13ld %8d %8d %8s\n",
1272                                 pool->name, pool->nrefills,
1273                                 pool->nfrees, pool->npages_in_use,
1274                                 pool->npages_free,
1275                                 pool->dev_name);
1276         }
1277         mutex_unlock(&_manager->lock);
1278         return 0;
1279 }
1280 EXPORT_SYMBOL_GPL(ttm_dma_page_alloc_debugfs);
1281
1282 #endif
This page took 0.119781 seconds and 4 git commands to generate.