drm: Sync with FreeBSD
[dragonfly.git] / sys / dev / 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  * Copyright (c) 2013 The FreeBSD Foundation
29  * All rights reserved.
30  *
31  * Portions of this software were developed by Konstantin Belousov
32  * <kib@FreeBSD.org> under sponsorship from the FreeBSD Foundation.
33  *
34  * $FreeBSD: head/sys/dev/drm2/ttm/ttm_page_alloc.c 247849 2013-03-05 16:15:34Z kib $
35  */
36
37 /* simple list based uncached page pool
38  * - Pool collects resently freed pages for reuse
39  * - Use page->lru to keep a free list
40  * - doesn't track currently in use pages
41  */
42
43 #include <sys/eventhandler.h>
44
45 #include <dev/drm/drmP.h>
46 #include <dev/drm/ttm/ttm_bo_driver.h>
47 #include <dev/drm/ttm/ttm_page_alloc.h>
48
49 #ifdef TTM_HAS_AGP
50 #include <asm/agp.h>
51 #endif
52
53 #define NUM_PAGES_TO_ALLOC              (PAGE_SIZE/sizeof(vm_page_t))
54 #define SMALL_ALLOCATION                16
55 #define FREE_ALL_PAGES                  (~0U)
56 /* times are in msecs */
57 #define PAGE_FREE_INTERVAL              1000
58
59 /**
60  * struct ttm_page_pool - Pool to reuse recently allocated uc/wc pages.
61  *
62  * @lock: Protects the shared pool from concurrnet access. Must be used with
63  * irqsave/irqrestore variants because pool allocator maybe called from
64  * delayed work.
65  * @fill_lock: Prevent concurrent calls to fill.
66  * @list: Pool of free uc/wc pages for fast reuse.
67  * @gfp_flags: Flags to pass for alloc_page.
68  * @npages: Number of pages in pool.
69  */
70 struct ttm_page_pool {
71         struct lock             lock;
72         bool                    fill_lock;
73         bool                    dma32;
74         struct pglist           list;
75         int                     ttm_page_alloc_flags;
76         unsigned                npages;
77         char                    *name;
78         unsigned long           nfrees;
79         unsigned long           nrefills;
80 };
81
82 /**
83  * Limits for the pool. They are handled without locks because only place where
84  * they may change is in sysfs store. They won't have immediate effect anyway
85  * so forcing serialization to access them is pointless.
86  */
87
88 struct ttm_pool_opts {
89         unsigned        alloc_size;
90         unsigned        max_size;
91         unsigned        small;
92 };
93
94 #define NUM_POOLS 4
95
96 /**
97  * struct ttm_pool_manager - Holds memory pools for fst allocation
98  *
99  * Manager is read only object for pool code so it doesn't need locking.
100  *
101  * @free_interval: minimum number of jiffies between freeing pages from pool.
102  * @page_alloc_inited: reference counting for pool allocation.
103  * @work: Work that is used to shrink the pool. Work is only run when there is
104  * some pages to free.
105  * @small_allocation: Limit in number of pages what is small allocation.
106  *
107  * @pools: All pool objects in use.
108  **/
109 struct ttm_pool_manager {
110         unsigned int kobj_ref;
111         eventhandler_tag lowmem_handler;
112         struct ttm_pool_opts    options;
113
114         union {
115                 struct ttm_page_pool    u_pools[NUM_POOLS];
116                 struct _utag {
117                         struct ttm_page_pool    u_wc_pool;
118                         struct ttm_page_pool    u_uc_pool;
119                         struct ttm_page_pool    u_wc_pool_dma32;
120                         struct ttm_page_pool    u_uc_pool_dma32;
121                 } _ut;
122         } _u;
123 };
124
125 #define pools _u.u_pools
126 #define wc_pool _u._ut.u_wc_pool
127 #define uc_pool _u._ut.u_uc_pool
128 #define wc_pool_dma32 _u._ut.u_wc_pool_dma32
129 #define uc_pool_dma32 _u._ut.u_uc_pool_dma32
130
131 MALLOC_DEFINE(M_TTM_POOLMGR, "ttm_poolmgr", "TTM Pool Manager");
132
133 static void
134 ttm_vm_page_free(vm_page_t m)
135 {
136
137         KASSERT(m->object == NULL, ("ttm page %p is owned", m));
138         KASSERT(m->wire_count == 1, ("ttm lost wire %p", m));
139         KASSERT((m->flags & PG_FICTITIOUS) != 0, ("ttm lost fictitious %p", m));
140 #if 0
141         KASSERT((m->oflags & VPO_UNMANAGED) == 0, ("ttm got unmanaged %p", m));
142         m->oflags |= VPO_UNMANAGED;
143 #endif
144         m->flags &= ~PG_FICTITIOUS;
145         vm_page_unwire(m, 0);
146         vm_page_free(m);
147 }
148
149 static vm_memattr_t
150 ttm_caching_state_to_vm(enum ttm_caching_state cstate)
151 {
152
153         switch (cstate) {
154         case tt_uncached:
155                 return (VM_MEMATTR_UNCACHEABLE);
156         case tt_wc:
157                 return (VM_MEMATTR_WRITE_COMBINING);
158         case tt_cached:
159                 return (VM_MEMATTR_WRITE_BACK);
160         }
161         panic("caching state %d\n", cstate);
162 }
163
164 static void ttm_pool_kobj_release(struct ttm_pool_manager *m)
165 {
166
167         drm_free(m, M_TTM_POOLMGR);
168 }
169
170 #if 0
171 /* XXXKIB sysctl */
172 static ssize_t ttm_pool_store(struct ttm_pool_manager *m,
173                 struct attribute *attr, const char *buffer, size_t size)
174 {
175         int chars;
176         unsigned val;
177         chars = sscanf(buffer, "%u", &val);
178         if (chars == 0)
179                 return size;
180
181         /* Convert kb to number of pages */
182         val = val / (PAGE_SIZE >> 10);
183
184         if (attr == &ttm_page_pool_max)
185                 m->options.max_size = val;
186         else if (attr == &ttm_page_pool_small)
187                 m->options.small = val;
188         else if (attr == &ttm_page_pool_alloc_size) {
189                 if (val > NUM_PAGES_TO_ALLOC*8) {
190                         pr_err("Setting allocation size to %lu is not allowed. Recommended size is %lu\n",
191                                NUM_PAGES_TO_ALLOC*(PAGE_SIZE >> 7),
192                                NUM_PAGES_TO_ALLOC*(PAGE_SIZE >> 10));
193                         return size;
194                 } else if (val > NUM_PAGES_TO_ALLOC) {
195                         pr_warn("Setting allocation size to larger than %lu is not recommended\n",
196                                 NUM_PAGES_TO_ALLOC*(PAGE_SIZE >> 10));
197                 }
198                 m->options.alloc_size = val;
199         }
200
201         return size;
202 }
203
204 static ssize_t ttm_pool_show(struct ttm_pool_manager *m,
205                 struct attribute *attr, char *buffer)
206 {
207         unsigned val = 0;
208
209         if (attr == &ttm_page_pool_max)
210                 val = m->options.max_size;
211         else if (attr == &ttm_page_pool_small)
212                 val = m->options.small;
213         else if (attr == &ttm_page_pool_alloc_size)
214                 val = m->options.alloc_size;
215
216         val = val * (PAGE_SIZE >> 10);
217
218         return snprintf(buffer, PAGE_SIZE, "%u\n", val);
219 }
220 #endif
221
222 static struct ttm_pool_manager *_manager;
223
224 static int set_pages_array_wb(vm_page_t *pages, int addrinarray)
225 {
226         vm_page_t m;
227         int i;
228
229         for (i = 0; i < addrinarray; i++) {
230                 m = pages[i];
231 #ifdef TTM_HAS_AGP
232                 unmap_page_from_agp(m);
233 #endif
234                 pmap_page_set_memattr(m, VM_MEMATTR_WRITE_BACK);
235         }
236         return 0;
237 }
238
239 static int set_pages_array_wc(vm_page_t *pages, int addrinarray)
240 {
241         vm_page_t m;
242         int i;
243
244         for (i = 0; i < addrinarray; i++) {
245                 m = pages[i];
246 #ifdef TTM_HAS_AGP
247                 map_page_into_agp(pages[i]);
248 #endif
249                 pmap_page_set_memattr(m, VM_MEMATTR_WRITE_COMBINING);
250         }
251         return 0;
252 }
253
254 static int set_pages_array_uc(vm_page_t *pages, int addrinarray)
255 {
256         vm_page_t m;
257         int i;
258
259         for (i = 0; i < addrinarray; i++) {
260                 m = pages[i];
261 #ifdef TTM_HAS_AGP
262                 map_page_into_agp(pages[i]);
263 #endif
264                 pmap_page_set_memattr(m, VM_MEMATTR_UNCACHEABLE);
265         }
266         return 0;
267 }
268
269 /**
270  * Select the right pool or requested caching state and ttm flags. */
271 static struct ttm_page_pool *ttm_get_pool(int flags,
272                 enum ttm_caching_state cstate)
273 {
274         int pool_index;
275
276         if (cstate == tt_cached)
277                 return NULL;
278
279         if (cstate == tt_wc)
280                 pool_index = 0x0;
281         else
282                 pool_index = 0x1;
283
284         if (flags & TTM_PAGE_FLAG_DMA32)
285                 pool_index |= 0x2;
286
287         return &_manager->pools[pool_index];
288 }
289
290 /* set memory back to wb and free the pages. */
291 static void ttm_pages_put(vm_page_t *pages, unsigned npages)
292 {
293         unsigned i;
294
295         /* Our VM handles vm memattr automatically on the page free. */
296         if (set_pages_array_wb(pages, npages))
297                 kprintf("[TTM] Failed to set %d pages to wb!\n", npages);
298         for (i = 0; i < npages; ++i)
299                 ttm_vm_page_free(pages[i]);
300 }
301
302 static void ttm_pool_update_free_locked(struct ttm_page_pool *pool,
303                 unsigned freed_pages)
304 {
305         pool->npages -= freed_pages;
306         pool->nfrees += freed_pages;
307 }
308
309 /**
310  * Free pages from pool.
311  *
312  * To prevent hogging the ttm_swap process we only free NUM_PAGES_TO_ALLOC
313  * number of pages in one go.
314  *
315  * @pool: to free the pages from
316  * @free_all: If set to true will free all pages in pool
317  **/
318 static int ttm_page_pool_free(struct ttm_page_pool *pool, unsigned nr_free)
319 {
320         vm_page_t p, p1;
321         vm_page_t *pages_to_free;
322         unsigned freed_pages = 0,
323                  npages_to_free = nr_free;
324         unsigned i;
325
326         if (NUM_PAGES_TO_ALLOC < nr_free)
327                 npages_to_free = NUM_PAGES_TO_ALLOC;
328
329         pages_to_free = kmalloc(npages_to_free * sizeof(vm_page_t),
330             M_TEMP, M_WAITOK | M_ZERO);
331
332 restart:
333         lockmgr(&pool->lock, LK_EXCLUSIVE);
334
335         TAILQ_FOREACH_REVERSE_MUTABLE(p, &pool->list, pglist, pageq, p1) {
336                 if (freed_pages >= npages_to_free)
337                         break;
338
339                 pages_to_free[freed_pages++] = p;
340                 /* We can only remove NUM_PAGES_TO_ALLOC at a time. */
341                 if (freed_pages >= NUM_PAGES_TO_ALLOC) {
342                         /* remove range of pages from the pool */
343                         for (i = 0; i < freed_pages; i++)
344                                 TAILQ_REMOVE(&pool->list, pages_to_free[i], pageq);
345
346                         ttm_pool_update_free_locked(pool, freed_pages);
347                         /**
348                          * Because changing page caching is costly
349                          * we unlock the pool to prevent stalling.
350                          */
351                         lockmgr(&pool->lock, LK_RELEASE);
352
353                         ttm_pages_put(pages_to_free, freed_pages);
354                         if (likely(nr_free != FREE_ALL_PAGES))
355                                 nr_free -= freed_pages;
356
357                         if (NUM_PAGES_TO_ALLOC >= nr_free)
358                                 npages_to_free = nr_free;
359                         else
360                                 npages_to_free = NUM_PAGES_TO_ALLOC;
361
362                         freed_pages = 0;
363
364                         /* free all so restart the processing */
365                         if (nr_free)
366                                 goto restart;
367
368                         /* Not allowed to fall through or break because
369                          * following context is inside spinlock while we are
370                          * outside here.
371                          */
372                         goto out;
373
374                 }
375         }
376
377         /* remove range of pages from the pool */
378         if (freed_pages) {
379                 for (i = 0; i < freed_pages; i++)
380                         TAILQ_REMOVE(&pool->list, pages_to_free[i], pageq);
381
382                 ttm_pool_update_free_locked(pool, freed_pages);
383                 nr_free -= freed_pages;
384         }
385
386         lockmgr(&pool->lock, LK_RELEASE);
387
388         if (freed_pages)
389                 ttm_pages_put(pages_to_free, freed_pages);
390 out:
391         drm_free(pages_to_free, M_TEMP);
392         return nr_free;
393 }
394
395 /* Get good estimation how many pages are free in pools */
396 static int ttm_pool_get_num_unused_pages(void)
397 {
398         unsigned i;
399         int total = 0;
400         for (i = 0; i < NUM_POOLS; ++i)
401                 total += _manager->pools[i].npages;
402
403         return total;
404 }
405
406 /**
407  * Callback for mm to request pool to reduce number of page held.
408  */
409 static int ttm_pool_mm_shrink(void *arg)
410 {
411         static unsigned int start_pool = 0;
412         unsigned i;
413         unsigned pool_offset = atomic_fetchadd_int(&start_pool, 1);
414         struct ttm_page_pool *pool;
415         int shrink_pages = 100; /* XXXKIB */
416
417         pool_offset = pool_offset % NUM_POOLS;
418         /* select start pool in round robin fashion */
419         for (i = 0; i < NUM_POOLS; ++i) {
420                 unsigned nr_free = shrink_pages;
421                 if (shrink_pages == 0)
422                         break;
423                 pool = &_manager->pools[(i + pool_offset)%NUM_POOLS];
424                 shrink_pages = ttm_page_pool_free(pool, nr_free);
425         }
426         /* return estimated number of unused pages in pool */
427         return ttm_pool_get_num_unused_pages();
428 }
429
430 static void ttm_pool_mm_shrink_init(struct ttm_pool_manager *manager)
431 {
432
433         manager->lowmem_handler = EVENTHANDLER_REGISTER(vm_lowmem,
434             ttm_pool_mm_shrink, manager, EVENTHANDLER_PRI_ANY);
435 }
436
437 static void ttm_pool_mm_shrink_fini(struct ttm_pool_manager *manager)
438 {
439
440         EVENTHANDLER_DEREGISTER(vm_lowmem, manager->lowmem_handler);
441 }
442
443 static int ttm_set_pages_caching(vm_page_t *pages,
444                 enum ttm_caching_state cstate, unsigned cpages)
445 {
446         int r = 0;
447         /* Set page caching */
448         switch (cstate) {
449         case tt_uncached:
450                 r = set_pages_array_uc(pages, cpages);
451                 if (r)
452                         kprintf("[TTM] Failed to set %d pages to uc!\n", cpages);
453                 break;
454         case tt_wc:
455                 r = set_pages_array_wc(pages, cpages);
456                 if (r)
457                         kprintf("[TTM] Failed to set %d pages to wc!\n", cpages);
458                 break;
459         default:
460                 break;
461         }
462         return r;
463 }
464
465 /**
466  * Free pages the pages that failed to change the caching state. If there is
467  * any pages that have changed their caching state already put them to the
468  * pool.
469  */
470 static void ttm_handle_caching_state_failure(struct pglist *pages,
471                 int ttm_flags, enum ttm_caching_state cstate,
472                 vm_page_t *failed_pages, unsigned cpages)
473 {
474         unsigned i;
475         /* Failed pages have to be freed */
476         for (i = 0; i < cpages; ++i) {
477                 TAILQ_REMOVE(pages, failed_pages[i], pageq);
478                 ttm_vm_page_free(failed_pages[i]);
479         }
480 }
481
482 /**
483  * Allocate new pages with correct caching.
484  *
485  * This function is reentrant if caller updates count depending on number of
486  * pages returned in pages array.
487  */
488 static int ttm_alloc_new_pages(struct pglist *pages, int ttm_alloc_flags,
489                 int ttm_flags, enum ttm_caching_state cstate, unsigned count)
490 {
491         vm_page_t *caching_array;
492         vm_page_t p;
493         int r = 0;
494         unsigned i, cpages, aflags;
495         unsigned max_cpages = min(count,
496                         (unsigned)(PAGE_SIZE/sizeof(vm_page_t)));
497
498         aflags = VM_ALLOC_NORMAL |
499             ((ttm_alloc_flags & TTM_PAGE_FLAG_ZERO_ALLOC) != 0 ?
500             VM_ALLOC_ZERO : 0);
501         
502         /* allocate array for page caching change */
503         caching_array = kmalloc(max_cpages * sizeof(vm_page_t), M_TEMP,
504             M_WAITOK | M_ZERO);
505
506         for (i = 0, cpages = 0; i < count; ++i) {
507                 p = vm_page_alloc_contig(0,
508                     (ttm_alloc_flags & TTM_PAGE_FLAG_DMA32) ? 0xffffffff :
509                     VM_MAX_ADDRESS, PAGE_SIZE, 0,
510                     1*PAGE_SIZE, ttm_caching_state_to_vm(cstate));
511                 if (!p) {
512                         kprintf("[TTM] Unable to get page %u\n", i);
513
514                         /* store already allocated pages in the pool after
515                          * setting the caching state */
516                         if (cpages) {
517                                 r = ttm_set_pages_caching(caching_array,
518                                                           cstate, cpages);
519                                 if (r)
520                                         ttm_handle_caching_state_failure(pages,
521                                                 ttm_flags, cstate,
522                                                 caching_array, cpages);
523                         }
524                         r = -ENOMEM;
525                         goto out;
526                 }
527 #if 0
528                 p->oflags &= ~VPO_UNMANAGED;
529 #endif
530                 p->flags |= PG_FICTITIOUS;
531
532 #ifdef CONFIG_HIGHMEM /* KIB: nop */
533                 /* gfp flags of highmem page should never be dma32 so we
534                  * we should be fine in such case
535                  */
536                 if (!PageHighMem(p))
537 #endif
538                 {
539                         caching_array[cpages++] = p;
540                         if (cpages == max_cpages) {
541
542                                 r = ttm_set_pages_caching(caching_array,
543                                                 cstate, cpages);
544                                 if (r) {
545                                         ttm_handle_caching_state_failure(pages,
546                                                 ttm_flags, cstate,
547                                                 caching_array, cpages);
548                                         goto out;
549                                 }
550                                 cpages = 0;
551                         }
552                 }
553
554                 TAILQ_INSERT_HEAD(pages, p, pageq);
555         }
556
557         if (cpages) {
558                 r = ttm_set_pages_caching(caching_array, cstate, cpages);
559                 if (r)
560                         ttm_handle_caching_state_failure(pages,
561                                         ttm_flags, cstate,
562                                         caching_array, cpages);
563         }
564 out:
565         drm_free(caching_array, M_TEMP);
566
567         return r;
568 }
569
570 /**
571  * Fill the given pool if there aren't enough pages and the requested number of
572  * pages is small.
573  */
574 static void ttm_page_pool_fill_locked(struct ttm_page_pool *pool,
575     int ttm_flags, enum ttm_caching_state cstate, unsigned count)
576 {
577         vm_page_t p;
578         int r;
579         unsigned cpages = 0;
580         /**
581          * Only allow one pool fill operation at a time.
582          * If pool doesn't have enough pages for the allocation new pages are
583          * allocated from outside of pool.
584          */
585         if (pool->fill_lock)
586                 return;
587
588         pool->fill_lock = true;
589
590         /* If allocation request is small and there are not enough
591          * pages in a pool we fill the pool up first. */
592         if (count < _manager->options.small
593                 && count > pool->npages) {
594                 struct pglist new_pages;
595                 unsigned alloc_size = _manager->options.alloc_size;
596
597                 /**
598                  * Can't change page caching if in irqsave context. We have to
599                  * drop the pool->lock.
600                  */
601                 lockmgr(&pool->lock, LK_RELEASE);
602
603                 TAILQ_INIT(&new_pages);
604                 r = ttm_alloc_new_pages(&new_pages, pool->ttm_page_alloc_flags,
605                     ttm_flags, cstate, alloc_size);
606                 lockmgr(&pool->lock, LK_EXCLUSIVE);
607
608                 if (!r) {
609                         TAILQ_CONCAT(&pool->list, &new_pages, pageq);
610                         ++pool->nrefills;
611                         pool->npages += alloc_size;
612                 } else {
613                         kprintf("[TTM] Failed to fill pool (%p)\n", pool);
614                         /* If we have any pages left put them to the pool. */
615                         TAILQ_FOREACH(p, &pool->list, pageq) {
616                                 ++cpages;
617                         }
618                         TAILQ_CONCAT(&pool->list, &new_pages, pageq);
619                         pool->npages += cpages;
620                 }
621
622         }
623         pool->fill_lock = false;
624 }
625
626 /**
627  * Cut 'count' number of pages from the pool and put them on the return list.
628  *
629  * @return count of pages still required to fulfill the request.
630  */
631 static unsigned ttm_page_pool_get_pages(struct ttm_page_pool *pool,
632                                         struct pglist *pages,
633                                         int ttm_flags,
634                                         enum ttm_caching_state cstate,
635                                         unsigned count)
636 {
637         vm_page_t p;
638         unsigned i;
639
640         lockmgr(&pool->lock, LK_EXCLUSIVE);
641         ttm_page_pool_fill_locked(pool, ttm_flags, cstate, count);
642
643         if (count >= pool->npages) {
644                 /* take all pages from the pool */
645                 TAILQ_CONCAT(pages, &pool->list, pageq);
646                 count -= pool->npages;
647                 pool->npages = 0;
648                 goto out;
649         }
650         for (i = 0; i < count; i++) {
651                 p = TAILQ_FIRST(&pool->list);
652                 TAILQ_REMOVE(&pool->list, p, pageq);
653                 TAILQ_INSERT_TAIL(pages, p, pageq);
654         }
655         pool->npages -= count;
656         count = 0;
657 out:
658         lockmgr(&pool->lock, LK_RELEASE);
659         return count;
660 }
661
662 /* Put all pages in pages list to correct pool to wait for reuse */
663 static void ttm_put_pages(vm_page_t *pages, unsigned npages, int flags,
664                           enum ttm_caching_state cstate)
665 {
666         struct ttm_page_pool *pool = ttm_get_pool(flags, cstate);
667         unsigned i;
668
669         if (pool == NULL) {
670                 /* No pool for this memory type so free the pages */
671                 for (i = 0; i < npages; i++) {
672                         if (pages[i]) {
673                                 ttm_vm_page_free(pages[i]);
674                                 pages[i] = NULL;
675                         }
676                 }
677                 return;
678         }
679
680         lockmgr(&pool->lock, LK_EXCLUSIVE);
681         for (i = 0; i < npages; i++) {
682                 if (pages[i]) {
683                         TAILQ_INSERT_TAIL(&pool->list, pages[i], pageq);
684                         pages[i] = NULL;
685                         pool->npages++;
686                 }
687         }
688         /* Check that we don't go over the pool limit */
689         npages = 0;
690         if (pool->npages > _manager->options.max_size) {
691                 npages = pool->npages - _manager->options.max_size;
692                 /* free at least NUM_PAGES_TO_ALLOC number of pages
693                  * to reduce calls to set_memory_wb */
694                 if (npages < NUM_PAGES_TO_ALLOC)
695                         npages = NUM_PAGES_TO_ALLOC;
696         }
697         lockmgr(&pool->lock, LK_RELEASE);
698         if (npages)
699                 ttm_page_pool_free(pool, npages);
700 }
701
702 /*
703  * On success pages list will hold count number of correctly
704  * cached pages.
705  */
706 static int ttm_get_pages(vm_page_t *pages, unsigned npages, int flags,
707                          enum ttm_caching_state cstate)
708 {
709         struct ttm_page_pool *pool = ttm_get_pool(flags, cstate);
710         struct pglist plist;
711         vm_page_t p = NULL;
712         int gfp_flags, aflags;
713         unsigned count;
714         int r;
715
716         aflags = VM_ALLOC_NORMAL |
717             ((flags & TTM_PAGE_FLAG_ZERO_ALLOC) != 0 ? VM_ALLOC_ZERO : 0);
718
719         /* No pool for cached pages */
720         if (pool == NULL) {
721                 for (r = 0; r < npages; ++r) {
722                         p = vm_page_alloc_contig(0,
723                             (flags & TTM_PAGE_FLAG_DMA32) ? 0xffffffff :
724                             VM_MAX_ADDRESS, PAGE_SIZE,
725                             0, 1*PAGE_SIZE, ttm_caching_state_to_vm(cstate));
726                         if (!p) {
727                                 kprintf("[TTM] Unable to allocate page\n");
728                                 return -ENOMEM;
729                         }
730 #if 0
731                         p->oflags &= ~VPO_UNMANAGED;
732 #endif
733                         p->flags |= PG_FICTITIOUS;
734                         pages[r] = p;
735                 }
736                 return 0;
737         }
738
739         /* combine zero flag to pool flags */
740         gfp_flags = flags | pool->ttm_page_alloc_flags;
741
742         /* First we take pages from the pool */
743         TAILQ_INIT(&plist);
744         npages = ttm_page_pool_get_pages(pool, &plist, flags, cstate, npages);
745         count = 0;
746         TAILQ_FOREACH(p, &plist, pageq) {
747                 pages[count++] = p;
748         }
749
750         /* clear the pages coming from the pool if requested */
751         if (flags & TTM_PAGE_FLAG_ZERO_ALLOC) {
752                 TAILQ_FOREACH(p, &plist, pageq) {
753                         pmap_zero_page(VM_PAGE_TO_PHYS(p));
754                 }
755         }
756
757         /* If pool didn't have enough pages allocate new one. */
758         if (npages > 0) {
759                 /* ttm_alloc_new_pages doesn't reference pool so we can run
760                  * multiple requests in parallel.
761                  **/
762                 TAILQ_INIT(&plist);
763                 r = ttm_alloc_new_pages(&plist, gfp_flags, flags, cstate,
764                     npages);
765                 TAILQ_FOREACH(p, &plist, pageq) {
766                         pages[count++] = p;
767                 }
768                 if (r) {
769                         /* If there is any pages in the list put them back to
770                          * the pool. */
771                         kprintf("[TTM] Failed to allocate extra pages for large request\n");
772                         ttm_put_pages(pages, count, flags, cstate);
773                         return r;
774                 }
775         }
776
777         return 0;
778 }
779
780 static void ttm_page_pool_init_locked(struct ttm_page_pool *pool, int flags,
781                                       char *name)
782 {
783         lockinit(&pool->lock, "ttmpool", 0, LK_CANRECURSE);
784         pool->fill_lock = false;
785         TAILQ_INIT(&pool->list);
786         pool->npages = pool->nfrees = 0;
787         pool->ttm_page_alloc_flags = flags;
788         pool->name = name;
789 }
790
791 int ttm_page_alloc_init(struct ttm_mem_global *glob, unsigned max_pages)
792 {
793
794         if (_manager != NULL)
795                 kprintf("[TTM] manager != NULL\n");
796         kprintf("[TTM] Initializing pool allocator\n");
797
798         _manager = kmalloc(sizeof(*_manager), M_TTM_POOLMGR, M_WAITOK | M_ZERO);
799
800         ttm_page_pool_init_locked(&_manager->wc_pool, 0, "wc");
801         ttm_page_pool_init_locked(&_manager->uc_pool, 0, "uc");
802         ttm_page_pool_init_locked(&_manager->wc_pool_dma32,
803             TTM_PAGE_FLAG_DMA32, "wc dma");
804         ttm_page_pool_init_locked(&_manager->uc_pool_dma32,
805             TTM_PAGE_FLAG_DMA32, "uc dma");
806
807         _manager->options.max_size = max_pages;
808         _manager->options.small = SMALL_ALLOCATION;
809         _manager->options.alloc_size = NUM_PAGES_TO_ALLOC;
810
811         refcount_init(&_manager->kobj_ref, 1);
812         ttm_pool_mm_shrink_init(_manager);
813
814         return 0;
815 }
816
817 void ttm_page_alloc_fini(void)
818 {
819         int i;
820
821         kprintf("[TTM] Finalizing pool allocator\n");
822         ttm_pool_mm_shrink_fini(_manager);
823
824         for (i = 0; i < NUM_POOLS; ++i)
825                 ttm_page_pool_free(&_manager->pools[i], FREE_ALL_PAGES);
826
827         if (refcount_release(&_manager->kobj_ref))
828                 ttm_pool_kobj_release(_manager);
829         _manager = NULL;
830 }
831
832 int ttm_pool_populate(struct ttm_tt *ttm)
833 {
834         struct ttm_mem_global *mem_glob = ttm->glob->mem_glob;
835         unsigned i;
836         int ret;
837
838         if (ttm->state != tt_unpopulated)
839                 return 0;
840
841         for (i = 0; i < ttm->num_pages; ++i) {
842                 ret = ttm_get_pages(&ttm->pages[i], 1,
843                                     ttm->page_flags,
844                                     ttm->caching_state);
845                 if (ret != 0) {
846                         ttm_pool_unpopulate(ttm);
847                         return -ENOMEM;
848                 }
849
850                 ret = ttm_mem_global_alloc_page(mem_glob, ttm->pages[i],
851                                                 false, false);
852                 if (unlikely(ret != 0)) {
853                         ttm_pool_unpopulate(ttm);
854                         return -ENOMEM;
855                 }
856         }
857
858         if (unlikely(ttm->page_flags & TTM_PAGE_FLAG_SWAPPED)) {
859                 ret = ttm_tt_swapin(ttm);
860                 if (unlikely(ret != 0)) {
861                         ttm_pool_unpopulate(ttm);
862                         return ret;
863                 }
864         }
865
866         ttm->state = tt_unbound;
867         return 0;
868 }
869
870 void ttm_pool_unpopulate(struct ttm_tt *ttm)
871 {
872         unsigned i;
873
874         for (i = 0; i < ttm->num_pages; ++i) {
875                 if (ttm->pages[i]) {
876                         ttm_mem_global_free_page(ttm->glob->mem_glob,
877                                                  ttm->pages[i]);
878                         ttm_put_pages(&ttm->pages[i], 1,
879                                       ttm->page_flags,
880                                       ttm->caching_state);
881                 }
882         }
883         ttm->state = tt_unpopulated;
884 }
885
886 #if 0
887 /* XXXKIB sysctl */
888 int ttm_page_alloc_debugfs(struct seq_file *m, void *data)
889 {
890         struct ttm_page_pool *p;
891         unsigned i;
892         char *h[] = {"pool", "refills", "pages freed", "size"};
893         if (!_manager) {
894                 seq_printf(m, "No pool allocator running.\n");
895                 return 0;
896         }
897         seq_printf(m, "%6s %12s %13s %8s\n",
898                         h[0], h[1], h[2], h[3]);
899         for (i = 0; i < NUM_POOLS; ++i) {
900                 p = &_manager->pools[i];
901
902                 seq_printf(m, "%6s %12ld %13ld %8d\n",
903                                 p->name, p->nrefills,
904                                 p->nfrees, p->npages);
905         }
906         return 0;
907 }
908 #endif