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