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