drm/ttm: don't attempt to use hugepages if dma32 requested (v2)
[sfrench/cifs-2.6.git] / drivers / gpu / drm / ttm / ttm_page_alloc.c
1 /*
2  * Copyright (c) Red Hat Inc.
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  * Authors: Dave Airlie <airlied@redhat.com>
24  *          Jerome Glisse <jglisse@redhat.com>
25  *          Pauli Nieminen <suokkos@gmail.com>
26  */
27
28 /* simple list based uncached page pool
29  * - Pool collects resently freed pages for reuse
30  * - Use page->lru to keep a free list
31  * - doesn't track currently in use pages
32  */
33
34 #define pr_fmt(fmt) "[TTM] " fmt
35
36 #include <linux/list.h>
37 #include <linux/spinlock.h>
38 #include <linux/highmem.h>
39 #include <linux/mm_types.h>
40 #include <linux/module.h>
41 #include <linux/mm.h>
42 #include <linux/seq_file.h> /* for seq_printf */
43 #include <linux/slab.h>
44 #include <linux/dma-mapping.h>
45
46 #include <linux/atomic.h>
47
48 #include <drm/ttm/ttm_bo_driver.h>
49 #include <drm/ttm/ttm_page_alloc.h>
50
51 #if IS_ENABLED(CONFIG_AGP)
52 #include <asm/agp.h>
53 #endif
54 #ifdef CONFIG_X86
55 #include <asm/set_memory.h>
56 #endif
57
58 #define NUM_PAGES_TO_ALLOC              (PAGE_SIZE/sizeof(struct page *))
59 #define SMALL_ALLOCATION                16
60 #define FREE_ALL_PAGES                  (~0U)
61 /* times are in msecs */
62 #define PAGE_FREE_INTERVAL              1000
63
64 /**
65  * struct ttm_page_pool - Pool to reuse recently allocated uc/wc pages.
66  *
67  * @lock: Protects the shared pool from concurrnet access. Must be used with
68  * irqsave/irqrestore variants because pool allocator maybe called from
69  * delayed work.
70  * @fill_lock: Prevent concurrent calls to fill.
71  * @list: Pool of free uc/wc pages for fast reuse.
72  * @gfp_flags: Flags to pass for alloc_page.
73  * @npages: Number of pages in pool.
74  */
75 struct ttm_page_pool {
76         spinlock_t              lock;
77         bool                    fill_lock;
78         struct list_head        list;
79         gfp_t                   gfp_flags;
80         unsigned                npages;
81         char                    *name;
82         unsigned long           nfrees;
83         unsigned long           nrefills;
84 };
85
86 /**
87  * Limits for the pool. They are handled without locks because only place where
88  * they may change is in sysfs store. They won't have immediate effect anyway
89  * so forcing serialization to access them is pointless.
90  */
91
92 struct ttm_pool_opts {
93         unsigned        alloc_size;
94         unsigned        max_size;
95         unsigned        small;
96 };
97
98 #define NUM_POOLS 6
99
100 /**
101  * struct ttm_pool_manager - Holds memory pools for fst allocation
102  *
103  * Manager is read only object for pool code so it doesn't need locking.
104  *
105  * @free_interval: minimum number of jiffies between freeing pages from pool.
106  * @page_alloc_inited: reference counting for pool allocation.
107  * @work: Work that is used to shrink the pool. Work is only run when there is
108  * some pages to free.
109  * @small_allocation: Limit in number of pages what is small allocation.
110  *
111  * @pools: All pool objects in use.
112  **/
113 struct ttm_pool_manager {
114         struct kobject          kobj;
115         struct shrinker         mm_shrink;
116         struct ttm_pool_opts    options;
117
118         union {
119                 struct ttm_page_pool    pools[NUM_POOLS];
120                 struct {
121                         struct ttm_page_pool    wc_pool;
122                         struct ttm_page_pool    uc_pool;
123                         struct ttm_page_pool    wc_pool_dma32;
124                         struct ttm_page_pool    uc_pool_dma32;
125                         struct ttm_page_pool    wc_pool_huge;
126                         struct ttm_page_pool    uc_pool_huge;
127                 } ;
128         };
129 };
130
131 static struct attribute ttm_page_pool_max = {
132         .name = "pool_max_size",
133         .mode = S_IRUGO | S_IWUSR
134 };
135 static struct attribute ttm_page_pool_small = {
136         .name = "pool_small_allocation",
137         .mode = S_IRUGO | S_IWUSR
138 };
139 static struct attribute ttm_page_pool_alloc_size = {
140         .name = "pool_allocation_size",
141         .mode = S_IRUGO | S_IWUSR
142 };
143
144 static struct attribute *ttm_pool_attrs[] = {
145         &ttm_page_pool_max,
146         &ttm_page_pool_small,
147         &ttm_page_pool_alloc_size,
148         NULL
149 };
150
151 static void ttm_pool_kobj_release(struct kobject *kobj)
152 {
153         struct ttm_pool_manager *m =
154                 container_of(kobj, struct ttm_pool_manager, kobj);
155         kfree(m);
156 }
157
158 static ssize_t ttm_pool_store(struct kobject *kobj,
159                 struct attribute *attr, const char *buffer, size_t size)
160 {
161         struct ttm_pool_manager *m =
162                 container_of(kobj, struct ttm_pool_manager, kobj);
163         int chars;
164         unsigned val;
165         chars = sscanf(buffer, "%u", &val);
166         if (chars == 0)
167                 return size;
168
169         /* Convert kb to number of pages */
170         val = val / (PAGE_SIZE >> 10);
171
172         if (attr == &ttm_page_pool_max)
173                 m->options.max_size = val;
174         else if (attr == &ttm_page_pool_small)
175                 m->options.small = val;
176         else if (attr == &ttm_page_pool_alloc_size) {
177                 if (val > NUM_PAGES_TO_ALLOC*8) {
178                         pr_err("Setting allocation size to %lu is not allowed. Recommended size is %lu\n",
179                                NUM_PAGES_TO_ALLOC*(PAGE_SIZE >> 7),
180                                NUM_PAGES_TO_ALLOC*(PAGE_SIZE >> 10));
181                         return size;
182                 } else if (val > NUM_PAGES_TO_ALLOC) {
183                         pr_warn("Setting allocation size to larger than %lu is not recommended\n",
184                                 NUM_PAGES_TO_ALLOC*(PAGE_SIZE >> 10));
185                 }
186                 m->options.alloc_size = val;
187         }
188
189         return size;
190 }
191
192 static ssize_t ttm_pool_show(struct kobject *kobj,
193                 struct attribute *attr, char *buffer)
194 {
195         struct ttm_pool_manager *m =
196                 container_of(kobj, struct ttm_pool_manager, kobj);
197         unsigned val = 0;
198
199         if (attr == &ttm_page_pool_max)
200                 val = m->options.max_size;
201         else if (attr == &ttm_page_pool_small)
202                 val = m->options.small;
203         else if (attr == &ttm_page_pool_alloc_size)
204                 val = m->options.alloc_size;
205
206         val = val * (PAGE_SIZE >> 10);
207
208         return snprintf(buffer, PAGE_SIZE, "%u\n", val);
209 }
210
211 static const struct sysfs_ops ttm_pool_sysfs_ops = {
212         .show = &ttm_pool_show,
213         .store = &ttm_pool_store,
214 };
215
216 static struct kobj_type ttm_pool_kobj_type = {
217         .release = &ttm_pool_kobj_release,
218         .sysfs_ops = &ttm_pool_sysfs_ops,
219         .default_attrs = ttm_pool_attrs,
220 };
221
222 static struct ttm_pool_manager *_manager;
223
224 #ifndef CONFIG_X86
225 static int set_pages_array_wb(struct page **pages, int addrinarray)
226 {
227 #if IS_ENABLED(CONFIG_AGP)
228         int i;
229
230         for (i = 0; i < addrinarray; i++)
231                 unmap_page_from_agp(pages[i]);
232 #endif
233         return 0;
234 }
235
236 static int set_pages_array_wc(struct page **pages, int addrinarray)
237 {
238 #if IS_ENABLED(CONFIG_AGP)
239         int i;
240
241         for (i = 0; i < addrinarray; i++)
242                 map_page_into_agp(pages[i]);
243 #endif
244         return 0;
245 }
246
247 static int set_pages_array_uc(struct page **pages, int addrinarray)
248 {
249 #if IS_ENABLED(CONFIG_AGP)
250         int i;
251
252         for (i = 0; i < addrinarray; i++)
253                 map_page_into_agp(pages[i]);
254 #endif
255         return 0;
256 }
257 #endif
258
259 /**
260  * Select the right pool or requested caching state and ttm flags. */
261 static struct ttm_page_pool *ttm_get_pool(int flags, bool huge,
262                                           enum ttm_caching_state cstate)
263 {
264         int pool_index;
265
266         if (cstate == tt_cached)
267                 return NULL;
268
269         if (cstate == tt_wc)
270                 pool_index = 0x0;
271         else
272                 pool_index = 0x1;
273
274         if (flags & TTM_PAGE_FLAG_DMA32) {
275                 if (huge)
276                         return NULL;
277                 pool_index |= 0x2;
278
279         } else if (huge) {
280                 pool_index |= 0x4;
281         }
282
283         return &_manager->pools[pool_index];
284 }
285
286 /* set memory back to wb and free the pages. */
287 static void ttm_pages_put(struct page *pages[], unsigned npages)
288 {
289         unsigned i;
290         if (set_pages_array_wb(pages, npages))
291                 pr_err("Failed to set %d pages to wb!\n", npages);
292         for (i = 0; i < npages; ++i)
293                 __free_page(pages[i]);
294 }
295
296 static void ttm_pool_update_free_locked(struct ttm_page_pool *pool,
297                 unsigned freed_pages)
298 {
299         pool->npages -= freed_pages;
300         pool->nfrees += freed_pages;
301 }
302
303 /**
304  * Free pages from pool.
305  *
306  * To prevent hogging the ttm_swap process we only free NUM_PAGES_TO_ALLOC
307  * number of pages in one go.
308  *
309  * @pool: to free the pages from
310  * @free_all: If set to true will free all pages in pool
311  * @use_static: Safe to use static buffer
312  **/
313 static int ttm_page_pool_free(struct ttm_page_pool *pool, unsigned nr_free,
314                               bool use_static)
315 {
316         static struct page *static_buf[NUM_PAGES_TO_ALLOC];
317         unsigned long irq_flags;
318         struct page *p;
319         struct page **pages_to_free;
320         unsigned freed_pages = 0,
321                  npages_to_free = nr_free;
322
323         if (NUM_PAGES_TO_ALLOC < nr_free)
324                 npages_to_free = NUM_PAGES_TO_ALLOC;
325
326         if (use_static)
327                 pages_to_free = static_buf;
328         else
329                 pages_to_free = kmalloc(npages_to_free * sizeof(struct page *),
330                                         GFP_KERNEL);
331         if (!pages_to_free) {
332                 pr_debug("Failed to allocate memory for pool free operation\n");
333                 return 0;
334         }
335
336 restart:
337         spin_lock_irqsave(&pool->lock, irq_flags);
338
339         list_for_each_entry_reverse(p, &pool->list, lru) {
340                 if (freed_pages >= npages_to_free)
341                         break;
342
343                 pages_to_free[freed_pages++] = p;
344                 /* We can only remove NUM_PAGES_TO_ALLOC at a time. */
345                 if (freed_pages >= NUM_PAGES_TO_ALLOC) {
346                         /* remove range of pages from the pool */
347                         __list_del(p->lru.prev, &pool->list);
348
349                         ttm_pool_update_free_locked(pool, freed_pages);
350                         /**
351                          * Because changing page caching is costly
352                          * we unlock the pool to prevent stalling.
353                          */
354                         spin_unlock_irqrestore(&pool->lock, irq_flags);
355
356                         ttm_pages_put(pages_to_free, freed_pages);
357                         if (likely(nr_free != FREE_ALL_PAGES))
358                                 nr_free -= freed_pages;
359
360                         if (NUM_PAGES_TO_ALLOC >= nr_free)
361                                 npages_to_free = nr_free;
362                         else
363                                 npages_to_free = NUM_PAGES_TO_ALLOC;
364
365                         freed_pages = 0;
366
367                         /* free all so restart the processing */
368                         if (nr_free)
369                                 goto restart;
370
371                         /* Not allowed to fall through or break because
372                          * following context is inside spinlock while we are
373                          * outside here.
374                          */
375                         goto out;
376
377                 }
378         }
379
380         /* remove range of pages from the pool */
381         if (freed_pages) {
382                 __list_del(&p->lru, &pool->list);
383
384                 ttm_pool_update_free_locked(pool, freed_pages);
385                 nr_free -= freed_pages;
386         }
387
388         spin_unlock_irqrestore(&pool->lock, irq_flags);
389
390         if (freed_pages)
391                 ttm_pages_put(pages_to_free, freed_pages);
392 out:
393         if (pages_to_free != static_buf)
394                 kfree(pages_to_free);
395         return nr_free;
396 }
397
398 /**
399  * Callback for mm to request pool to reduce number of page held.
400  *
401  * XXX: (dchinner) Deadlock warning!
402  *
403  * This code is crying out for a shrinker per pool....
404  */
405 static unsigned long
406 ttm_pool_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
407 {
408         static DEFINE_MUTEX(lock);
409         static unsigned start_pool;
410         unsigned i;
411         unsigned pool_offset;
412         struct ttm_page_pool *pool;
413         int shrink_pages = sc->nr_to_scan;
414         unsigned long freed = 0;
415
416         if (!mutex_trylock(&lock))
417                 return SHRINK_STOP;
418         pool_offset = ++start_pool % NUM_POOLS;
419         /* select start pool in round robin fashion */
420         for (i = 0; i < NUM_POOLS; ++i) {
421                 unsigned nr_free = shrink_pages;
422                 if (shrink_pages == 0)
423                         break;
424                 pool = &_manager->pools[(i + pool_offset)%NUM_POOLS];
425                 /* OK to use static buffer since global mutex is held. */
426                 shrink_pages = ttm_page_pool_free(pool, nr_free, true);
427                 freed += nr_free - shrink_pages;
428         }
429         mutex_unlock(&lock);
430         return freed;
431 }
432
433
434 static unsigned long
435 ttm_pool_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
436 {
437         unsigned i;
438         unsigned long count = 0;
439
440         for (i = 0; i < NUM_POOLS; ++i)
441                 count += _manager->pools[i].npages;
442
443         return count;
444 }
445
446 static void ttm_pool_mm_shrink_init(struct ttm_pool_manager *manager)
447 {
448         manager->mm_shrink.count_objects = ttm_pool_shrink_count;
449         manager->mm_shrink.scan_objects = ttm_pool_shrink_scan;
450         manager->mm_shrink.seeks = 1;
451         register_shrinker(&manager->mm_shrink);
452 }
453
454 static void ttm_pool_mm_shrink_fini(struct ttm_pool_manager *manager)
455 {
456         unregister_shrinker(&manager->mm_shrink);
457 }
458
459 static int ttm_set_pages_caching(struct page **pages,
460                 enum ttm_caching_state cstate, unsigned cpages)
461 {
462         int r = 0;
463         /* Set page caching */
464         switch (cstate) {
465         case tt_uncached:
466                 r = set_pages_array_uc(pages, cpages);
467                 if (r)
468                         pr_err("Failed to set %d pages to uc!\n", cpages);
469                 break;
470         case tt_wc:
471                 r = set_pages_array_wc(pages, cpages);
472                 if (r)
473                         pr_err("Failed to set %d pages to wc!\n", cpages);
474                 break;
475         default:
476                 break;
477         }
478         return r;
479 }
480
481 /**
482  * Free pages the pages that failed to change the caching state. If there is
483  * any pages that have changed their caching state already put them to the
484  * pool.
485  */
486 static void ttm_handle_caching_state_failure(struct list_head *pages,
487                 int ttm_flags, enum ttm_caching_state cstate,
488                 struct page **failed_pages, unsigned cpages)
489 {
490         unsigned i;
491         /* Failed pages have to be freed */
492         for (i = 0; i < cpages; ++i) {
493                 list_del(&failed_pages[i]->lru);
494                 __free_page(failed_pages[i]);
495         }
496 }
497
498 /**
499  * Allocate new pages with correct caching.
500  *
501  * This function is reentrant if caller updates count depending on number of
502  * pages returned in pages array.
503  */
504 static int ttm_alloc_new_pages(struct list_head *pages, gfp_t gfp_flags,
505                                int ttm_flags, enum ttm_caching_state cstate,
506                                unsigned count, unsigned order)
507 {
508         struct page **caching_array;
509         struct page *p;
510         int r = 0;
511         unsigned i, j, cpages;
512         unsigned npages = 1 << order;
513         unsigned max_cpages = min(count,
514                         (unsigned)(PAGE_SIZE/sizeof(struct page *)));
515
516         /* allocate array for page caching change */
517         caching_array = kmalloc(max_cpages*sizeof(struct page *), GFP_KERNEL);
518
519         if (!caching_array) {
520                 pr_debug("Unable to allocate table for new pages\n");
521                 return -ENOMEM;
522         }
523
524         for (i = 0, cpages = 0; i < count; ++i) {
525                 p = alloc_pages(gfp_flags, order);
526
527                 if (!p) {
528                         pr_debug("Unable to get page %u\n", i);
529
530                         /* store already allocated pages in the pool after
531                          * setting the caching state */
532                         if (cpages) {
533                                 r = ttm_set_pages_caching(caching_array,
534                                                           cstate, cpages);
535                                 if (r)
536                                         ttm_handle_caching_state_failure(pages,
537                                                 ttm_flags, cstate,
538                                                 caching_array, cpages);
539                         }
540                         r = -ENOMEM;
541                         goto out;
542                 }
543
544                 list_add(&p->lru, pages);
545
546 #ifdef CONFIG_HIGHMEM
547                 /* gfp flags of highmem page should never be dma32 so we
548                  * we should be fine in such case
549                  */
550                 if (PageHighMem(p))
551                         continue;
552
553 #endif
554                 for (j = 0; j < npages; ++j) {
555                         caching_array[cpages++] = p++;
556                         if (cpages == max_cpages) {
557
558                                 r = ttm_set_pages_caching(caching_array,
559                                                 cstate, cpages);
560                                 if (r) {
561                                         ttm_handle_caching_state_failure(pages,
562                                                 ttm_flags, cstate,
563                                                 caching_array, cpages);
564                                         goto out;
565                                 }
566                                 cpages = 0;
567                         }
568                 }
569         }
570
571         if (cpages) {
572                 r = ttm_set_pages_caching(caching_array, cstate, cpages);
573                 if (r)
574                         ttm_handle_caching_state_failure(pages,
575                                         ttm_flags, cstate,
576                                         caching_array, cpages);
577         }
578 out:
579         kfree(caching_array);
580
581         return r;
582 }
583
584 /**
585  * Fill the given pool if there aren't enough pages and the requested number of
586  * pages is small.
587  */
588 static void ttm_page_pool_fill_locked(struct ttm_page_pool *pool, int ttm_flags,
589                                       enum ttm_caching_state cstate,
590                                       unsigned count, unsigned long *irq_flags)
591 {
592         struct page *p;
593         int r;
594         unsigned cpages = 0;
595         /**
596          * Only allow one pool fill operation at a time.
597          * If pool doesn't have enough pages for the allocation new pages are
598          * allocated from outside of pool.
599          */
600         if (pool->fill_lock)
601                 return;
602
603         pool->fill_lock = true;
604
605         /* If allocation request is small and there are not enough
606          * pages in a pool we fill the pool up first. */
607         if (count < _manager->options.small
608                 && count > pool->npages) {
609                 struct list_head new_pages;
610                 unsigned alloc_size = _manager->options.alloc_size;
611
612                 /**
613                  * Can't change page caching if in irqsave context. We have to
614                  * drop the pool->lock.
615                  */
616                 spin_unlock_irqrestore(&pool->lock, *irq_flags);
617
618                 INIT_LIST_HEAD(&new_pages);
619                 r = ttm_alloc_new_pages(&new_pages, pool->gfp_flags, ttm_flags,
620                                         cstate, alloc_size, 0);
621                 spin_lock_irqsave(&pool->lock, *irq_flags);
622
623                 if (!r) {
624                         list_splice(&new_pages, &pool->list);
625                         ++pool->nrefills;
626                         pool->npages += alloc_size;
627                 } else {
628                         pr_debug("Failed to fill pool (%p)\n", pool);
629                         /* If we have any pages left put them to the pool. */
630                         list_for_each_entry(p, &new_pages, lru) {
631                                 ++cpages;
632                         }
633                         list_splice(&new_pages, &pool->list);
634                         pool->npages += cpages;
635                 }
636
637         }
638         pool->fill_lock = false;
639 }
640
641 /**
642  * Allocate pages from the pool and put them on the return list.
643  *
644  * @return zero for success or negative error code.
645  */
646 static int ttm_page_pool_get_pages(struct ttm_page_pool *pool,
647                                    struct list_head *pages,
648                                    int ttm_flags,
649                                    enum ttm_caching_state cstate,
650                                    unsigned count, unsigned order)
651 {
652         unsigned long irq_flags;
653         struct list_head *p;
654         unsigned i;
655         int r = 0;
656
657         spin_lock_irqsave(&pool->lock, irq_flags);
658         if (!order)
659                 ttm_page_pool_fill_locked(pool, ttm_flags, cstate, count,
660                                           &irq_flags);
661
662         if (count >= pool->npages) {
663                 /* take all pages from the pool */
664                 list_splice_init(&pool->list, pages);
665                 count -= pool->npages;
666                 pool->npages = 0;
667                 goto out;
668         }
669         /* find the last pages to include for requested number of pages. Split
670          * pool to begin and halve it to reduce search space. */
671         if (count <= pool->npages/2) {
672                 i = 0;
673                 list_for_each(p, &pool->list) {
674                         if (++i == count)
675                                 break;
676                 }
677         } else {
678                 i = pool->npages + 1;
679                 list_for_each_prev(p, &pool->list) {
680                         if (--i == count)
681                                 break;
682                 }
683         }
684         /* Cut 'count' number of pages from the pool */
685         list_cut_position(pages, &pool->list, p);
686         pool->npages -= count;
687         count = 0;
688 out:
689         spin_unlock_irqrestore(&pool->lock, irq_flags);
690
691         /* clear the pages coming from the pool if requested */
692         if (ttm_flags & TTM_PAGE_FLAG_ZERO_ALLOC) {
693                 struct page *page;
694
695                 list_for_each_entry(page, pages, lru) {
696                         if (PageHighMem(page))
697                                 clear_highpage(page);
698                         else
699                                 clear_page(page_address(page));
700                 }
701         }
702
703         /* If pool didn't have enough pages allocate new one. */
704         if (count) {
705                 gfp_t gfp_flags = pool->gfp_flags;
706
707                 /* set zero flag for page allocation if required */
708                 if (ttm_flags & TTM_PAGE_FLAG_ZERO_ALLOC)
709                         gfp_flags |= __GFP_ZERO;
710
711                 /* ttm_alloc_new_pages doesn't reference pool so we can run
712                  * multiple requests in parallel.
713                  **/
714                 r = ttm_alloc_new_pages(pages, gfp_flags, ttm_flags, cstate,
715                                         count, order);
716         }
717
718         return r;
719 }
720
721 /* Put all pages in pages list to correct pool to wait for reuse */
722 static void ttm_put_pages(struct page **pages, unsigned npages, int flags,
723                           enum ttm_caching_state cstate)
724 {
725         struct ttm_page_pool *pool = ttm_get_pool(flags, false, cstate);
726 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
727         struct ttm_page_pool *huge = ttm_get_pool(flags, true, cstate);
728 #endif
729         unsigned long irq_flags;
730         unsigned i;
731
732         if (pool == NULL) {
733                 /* No pool for this memory type so free the pages */
734                 i = 0;
735                 while (i < npages) {
736 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
737                         struct page *p = pages[i];
738 #endif
739                         unsigned order = 0, j;
740
741                         if (!pages[i]) {
742                                 ++i;
743                                 continue;
744                         }
745
746 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
747                         if (!(flags & TTM_PAGE_FLAG_DMA32)) {
748                                 for (j = 0; j < HPAGE_PMD_NR; ++j)
749                                         if (p++ != pages[i + j])
750                                             break;
751
752                                 if (j == HPAGE_PMD_NR)
753                                         order = HPAGE_PMD_ORDER;
754                         }
755 #endif
756
757                         if (page_count(pages[i]) != 1)
758                                 pr_err("Erroneous page count. Leaking pages.\n");
759                         __free_pages(pages[i], order);
760
761                         j = 1 << order;
762                         while (j) {
763                                 pages[i++] = NULL;
764                                 --j;
765                         }
766                 }
767                 return;
768         }
769
770         i = 0;
771 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
772         if (huge) {
773                 unsigned max_size, n2free;
774
775                 spin_lock_irqsave(&huge->lock, irq_flags);
776                 while (i < npages) {
777                         struct page *p = pages[i];
778                         unsigned j;
779
780                         if (!p)
781                                 break;
782
783                         for (j = 0; j < HPAGE_PMD_NR; ++j)
784                                 if (p++ != pages[i + j])
785                                     break;
786
787                         if (j != HPAGE_PMD_NR)
788                                 break;
789
790                         list_add_tail(&pages[i]->lru, &huge->list);
791
792                         for (j = 0; j < HPAGE_PMD_NR; ++j)
793                                 pages[i++] = NULL;
794                         huge->npages++;
795                 }
796
797                 /* Check that we don't go over the pool limit */
798                 max_size = _manager->options.max_size;
799                 max_size /= HPAGE_PMD_NR;
800                 if (huge->npages > max_size)
801                         n2free = huge->npages - max_size;
802                 else
803                         n2free = 0;
804                 spin_unlock_irqrestore(&huge->lock, irq_flags);
805                 if (n2free)
806                         ttm_page_pool_free(huge, n2free, false);
807         }
808 #endif
809
810         spin_lock_irqsave(&pool->lock, irq_flags);
811         while (i < npages) {
812                 if (pages[i]) {
813                         if (page_count(pages[i]) != 1)
814                                 pr_err("Erroneous page count. Leaking pages.\n");
815                         list_add_tail(&pages[i]->lru, &pool->list);
816                         pages[i] = NULL;
817                         pool->npages++;
818                 }
819                 ++i;
820         }
821         /* Check that we don't go over the pool limit */
822         npages = 0;
823         if (pool->npages > _manager->options.max_size) {
824                 npages = pool->npages - _manager->options.max_size;
825                 /* free at least NUM_PAGES_TO_ALLOC number of pages
826                  * to reduce calls to set_memory_wb */
827                 if (npages < NUM_PAGES_TO_ALLOC)
828                         npages = NUM_PAGES_TO_ALLOC;
829         }
830         spin_unlock_irqrestore(&pool->lock, irq_flags);
831         if (npages)
832                 ttm_page_pool_free(pool, npages, false);
833 }
834
835 /*
836  * On success pages list will hold count number of correctly
837  * cached pages.
838  */
839 static int ttm_get_pages(struct page **pages, unsigned npages, int flags,
840                          enum ttm_caching_state cstate)
841 {
842         struct ttm_page_pool *pool = ttm_get_pool(flags, false, cstate);
843 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
844         struct ttm_page_pool *huge = ttm_get_pool(flags, true, cstate);
845 #endif
846         struct list_head plist;
847         struct page *p = NULL;
848         unsigned count;
849         int r;
850
851         /* No pool for cached pages */
852         if (pool == NULL) {
853                 gfp_t gfp_flags = GFP_USER;
854                 unsigned i;
855 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
856                 unsigned j;
857 #endif
858
859                 /* set zero flag for page allocation if required */
860                 if (flags & TTM_PAGE_FLAG_ZERO_ALLOC)
861                         gfp_flags |= __GFP_ZERO;
862
863                 if (flags & TTM_PAGE_FLAG_DMA32)
864                         gfp_flags |= GFP_DMA32;
865                 else
866                         gfp_flags |= GFP_HIGHUSER;
867
868                 i = 0;
869 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
870                 if (!(gfp_flags & GFP_DMA32)) {
871                         while (npages >= HPAGE_PMD_NR) {
872                                 gfp_t huge_flags = gfp_flags;
873
874                                 huge_flags |= GFP_TRANSHUGE;
875                                 huge_flags &= ~__GFP_MOVABLE;
876                                 huge_flags &= ~__GFP_COMP;
877                                 p = alloc_pages(huge_flags, HPAGE_PMD_ORDER);
878                                 if (!p)
879                                         break;
880
881                                 for (j = 0; j < HPAGE_PMD_NR; ++j)
882                                         pages[i++] = p++;
883
884                                 npages -= HPAGE_PMD_NR;
885                         }
886                 }
887 #endif
888
889                 while (npages) {
890                         p = alloc_page(gfp_flags);
891                         if (!p) {
892                                 pr_debug("Unable to allocate page\n");
893                                 return -ENOMEM;
894                         }
895
896                         pages[i++] = p;
897                         --npages;
898                 }
899                 return 0;
900         }
901
902         count = 0;
903
904 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
905         if (huge && npages >= HPAGE_PMD_NR) {
906                 INIT_LIST_HEAD(&plist);
907                 ttm_page_pool_get_pages(huge, &plist, flags, cstate,
908                                         npages / HPAGE_PMD_NR,
909                                         HPAGE_PMD_ORDER);
910
911                 list_for_each_entry(p, &plist, lru) {
912                         unsigned j;
913
914                         for (j = 0; j < HPAGE_PMD_NR; ++j)
915                                 pages[count++] = &p[j];
916                 }
917         }
918 #endif
919
920         INIT_LIST_HEAD(&plist);
921         r = ttm_page_pool_get_pages(pool, &plist, flags, cstate,
922                                     npages - count, 0);
923
924         list_for_each_entry(p, &plist, lru)
925                 pages[count++] = p;
926
927         if (r) {
928                 /* If there is any pages in the list put them back to
929                  * the pool.
930                  */
931                 pr_debug("Failed to allocate extra pages for large request\n");
932                 ttm_put_pages(pages, count, flags, cstate);
933                 return r;
934         }
935
936         return 0;
937 }
938
939 static void ttm_page_pool_init_locked(struct ttm_page_pool *pool, gfp_t flags,
940                 char *name)
941 {
942         spin_lock_init(&pool->lock);
943         pool->fill_lock = false;
944         INIT_LIST_HEAD(&pool->list);
945         pool->npages = pool->nfrees = 0;
946         pool->gfp_flags = flags;
947         pool->name = name;
948 }
949
950 int ttm_page_alloc_init(struct ttm_mem_global *glob, unsigned max_pages)
951 {
952         int ret;
953
954         WARN_ON(_manager);
955
956         pr_info("Initializing pool allocator\n");
957
958         _manager = kzalloc(sizeof(*_manager), GFP_KERNEL);
959
960         ttm_page_pool_init_locked(&_manager->wc_pool, GFP_HIGHUSER, "wc");
961
962         ttm_page_pool_init_locked(&_manager->uc_pool, GFP_HIGHUSER, "uc");
963
964         ttm_page_pool_init_locked(&_manager->wc_pool_dma32,
965                                   GFP_USER | GFP_DMA32, "wc dma");
966
967         ttm_page_pool_init_locked(&_manager->uc_pool_dma32,
968                                   GFP_USER | GFP_DMA32, "uc dma");
969
970         ttm_page_pool_init_locked(&_manager->wc_pool_huge,
971                                   GFP_TRANSHUGE & ~(__GFP_MOVABLE | __GFP_COMP),
972                                   "wc huge");
973
974         ttm_page_pool_init_locked(&_manager->uc_pool_huge,
975                                   GFP_TRANSHUGE & ~(__GFP_MOVABLE | __GFP_COMP)
976                                   , "uc huge");
977
978         _manager->options.max_size = max_pages;
979         _manager->options.small = SMALL_ALLOCATION;
980         _manager->options.alloc_size = NUM_PAGES_TO_ALLOC;
981
982         ret = kobject_init_and_add(&_manager->kobj, &ttm_pool_kobj_type,
983                                    &glob->kobj, "pool");
984         if (unlikely(ret != 0)) {
985                 kobject_put(&_manager->kobj);
986                 _manager = NULL;
987                 return ret;
988         }
989
990         ttm_pool_mm_shrink_init(_manager);
991
992         return 0;
993 }
994
995 void ttm_page_alloc_fini(void)
996 {
997         int i;
998
999         pr_info("Finalizing pool allocator\n");
1000         ttm_pool_mm_shrink_fini(_manager);
1001
1002         /* OK to use static buffer since global mutex is no longer used. */
1003         for (i = 0; i < NUM_POOLS; ++i)
1004                 ttm_page_pool_free(&_manager->pools[i], FREE_ALL_PAGES, true);
1005
1006         kobject_put(&_manager->kobj);
1007         _manager = NULL;
1008 }
1009
1010 int ttm_pool_populate(struct ttm_tt *ttm)
1011 {
1012         struct ttm_mem_global *mem_glob = ttm->glob->mem_glob;
1013         unsigned i;
1014         int ret;
1015
1016         if (ttm->state != tt_unpopulated)
1017                 return 0;
1018
1019         ret = ttm_get_pages(ttm->pages, ttm->num_pages, ttm->page_flags,
1020                             ttm->caching_state);
1021         if (unlikely(ret != 0)) {
1022                 ttm_pool_unpopulate(ttm);
1023                 return ret;
1024         }
1025
1026         for (i = 0; i < ttm->num_pages; ++i) {
1027                 ret = ttm_mem_global_alloc_page(mem_glob, ttm->pages[i],
1028                                                 PAGE_SIZE);
1029                 if (unlikely(ret != 0)) {
1030                         ttm_pool_unpopulate(ttm);
1031                         return -ENOMEM;
1032                 }
1033         }
1034
1035         if (unlikely(ttm->page_flags & TTM_PAGE_FLAG_SWAPPED)) {
1036                 ret = ttm_tt_swapin(ttm);
1037                 if (unlikely(ret != 0)) {
1038                         ttm_pool_unpopulate(ttm);
1039                         return ret;
1040                 }
1041         }
1042
1043         ttm->state = tt_unbound;
1044         return 0;
1045 }
1046 EXPORT_SYMBOL(ttm_pool_populate);
1047
1048 void ttm_pool_unpopulate(struct ttm_tt *ttm)
1049 {
1050         unsigned i;
1051
1052         for (i = 0; i < ttm->num_pages; ++i) {
1053                 if (!ttm->pages[i])
1054                         continue;
1055
1056                 ttm_mem_global_free_page(ttm->glob->mem_glob, ttm->pages[i],
1057                                          PAGE_SIZE);
1058         }
1059         ttm_put_pages(ttm->pages, ttm->num_pages, ttm->page_flags,
1060                       ttm->caching_state);
1061         ttm->state = tt_unpopulated;
1062 }
1063 EXPORT_SYMBOL(ttm_pool_unpopulate);
1064
1065 #if defined(CONFIG_SWIOTLB) || defined(CONFIG_INTEL_IOMMU)
1066 int ttm_populate_and_map_pages(struct device *dev, struct ttm_dma_tt *tt)
1067 {
1068         unsigned i, j;
1069         int r;
1070
1071         r = ttm_pool_populate(&tt->ttm);
1072         if (r)
1073                 return r;
1074
1075         for (i = 0; i < tt->ttm.num_pages; ++i) {
1076                 struct page *p = tt->ttm.pages[i];
1077                 size_t num_pages = 1;
1078
1079                 for (j = i + 1; j < tt->ttm.num_pages; ++j) {
1080                         if (++p != tt->ttm.pages[j])
1081                                 break;
1082
1083                         ++num_pages;
1084                 }
1085
1086                 tt->dma_address[i] = dma_map_page(dev, tt->ttm.pages[i],
1087                                                   0, num_pages * PAGE_SIZE,
1088                                                   DMA_BIDIRECTIONAL);
1089                 if (dma_mapping_error(dev, tt->dma_address[i])) {
1090                         while (i--) {
1091                                 dma_unmap_page(dev, tt->dma_address[i],
1092                                                PAGE_SIZE, DMA_BIDIRECTIONAL);
1093                                 tt->dma_address[i] = 0;
1094                         }
1095                         ttm_pool_unpopulate(&tt->ttm);
1096                         return -EFAULT;
1097                 }
1098
1099                 for (j = 1; j < num_pages; ++j) {
1100                         tt->dma_address[i + 1] = tt->dma_address[i] + PAGE_SIZE;
1101                         ++i;
1102                 }
1103         }
1104         return 0;
1105 }
1106 EXPORT_SYMBOL(ttm_populate_and_map_pages);
1107
1108 void ttm_unmap_and_unpopulate_pages(struct device *dev, struct ttm_dma_tt *tt)
1109 {
1110         unsigned i, j;
1111
1112         for (i = 0; i < tt->ttm.num_pages;) {
1113                 struct page *p = tt->ttm.pages[i];
1114                 size_t num_pages = 1;
1115
1116                 if (!tt->dma_address[i] || !tt->ttm.pages[i]) {
1117                         ++i;
1118                         continue;
1119                 }
1120
1121                 for (j = i + 1; j < tt->ttm.num_pages; ++j) {
1122                         if (++p != tt->ttm.pages[j])
1123                                 break;
1124
1125                         ++num_pages;
1126                 }
1127
1128                 dma_unmap_page(dev, tt->dma_address[i], num_pages * PAGE_SIZE,
1129                                DMA_BIDIRECTIONAL);
1130
1131                 i += num_pages;
1132         }
1133         ttm_pool_unpopulate(&tt->ttm);
1134 }
1135 EXPORT_SYMBOL(ttm_unmap_and_unpopulate_pages);
1136 #endif
1137
1138 int ttm_page_alloc_debugfs(struct seq_file *m, void *data)
1139 {
1140         struct ttm_page_pool *p;
1141         unsigned i;
1142         char *h[] = {"pool", "refills", "pages freed", "size"};
1143         if (!_manager) {
1144                 seq_printf(m, "No pool allocator running.\n");
1145                 return 0;
1146         }
1147         seq_printf(m, "%7s %12s %13s %8s\n",
1148                         h[0], h[1], h[2], h[3]);
1149         for (i = 0; i < NUM_POOLS; ++i) {
1150                 p = &_manager->pools[i];
1151
1152                 seq_printf(m, "%7s %12ld %13ld %8d\n",
1153                                 p->name, p->nrefills,
1154                                 p->nfrees, p->npages);
1155         }
1156         return 0;
1157 }
1158 EXPORT_SYMBOL(ttm_page_alloc_debugfs);