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