xref: /linux/drivers/gpu/drm/ttm/ttm_pool.c (revision d53adc244fbf965d7efeefb278ff8f2664bbe20e)
1 // SPDX-License-Identifier: GPL-2.0 OR MIT
2 /*
3  * Copyright 2020 Advanced Micro Devices, Inc.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions 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 NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
19  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
20  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
21  * OTHER DEALINGS IN THE SOFTWARE.
22  *
23  * Authors: Christian König
24  */
25 
26 /* Pooling of allocated pages is necessary because changing the caching
27  * attributes on x86 of the linear mapping requires a costly cross CPU TLB
28  * invalidate for those addresses.
29  *
30  * Additional to that allocations from the DMA coherent API are pooled as well
31  * cause they are rather slow compared to alloc_pages+map.
32  */
33 
34 #include <linux/export.h>
35 #include <linux/module.h>
36 #include <linux/dma-mapping.h>
37 #include <linux/debugfs.h>
38 #include <linux/highmem.h>
39 #include <linux/sched/mm.h>
40 
41 #ifdef CONFIG_X86
42 #include <asm/set_memory.h>
43 #endif
44 
45 #include <drm/ttm/ttm_backup.h>
46 #include <drm/ttm/ttm_pool.h>
47 #include <drm/ttm/ttm_tt.h>
48 #include <drm/ttm/ttm_bo.h>
49 
50 #include "ttm_module.h"
51 #include "ttm_pool_internal.h"
52 
53 #ifdef CONFIG_FAULT_INJECTION
54 #include <linux/fault-inject.h>
55 static DECLARE_FAULT_ATTR(backup_fault_inject);
56 #else
57 #define should_fail(...) false
58 #endif
59 
60 /**
61  * struct ttm_pool_dma - Helper object for coherent DMA mappings
62  *
63  * @addr: original DMA address returned for the mapping
64  * @vaddr: original vaddr return for the mapping and order in the lower bits
65  */
66 struct ttm_pool_dma {
67 	dma_addr_t addr;
68 	unsigned long vaddr;
69 };
70 
71 /**
72  * struct ttm_pool_alloc_state - Current state of the tt page allocation process
73  * @pages: Pointer to the next tt page pointer to populate.
74  * @caching_divide: Pointer to the first page pointer whose page has a staged but
75  * not committed caching transition from write-back to @tt_caching.
76  * @dma_addr: Pointer to the next tt dma_address entry to populate if any.
77  * @remaining_pages: Remaining pages to populate.
78  * @tt_caching: The requested cpu-caching for the pages allocated.
79  */
80 struct ttm_pool_alloc_state {
81 	struct page **pages;
82 	struct page **caching_divide;
83 	dma_addr_t *dma_addr;
84 	pgoff_t remaining_pages;
85 	enum ttm_caching tt_caching;
86 };
87 
88 /**
89  * struct ttm_pool_tt_restore - State representing restore from backup
90  * @pool: The pool used for page allocation while restoring.
91  * @snapshot_alloc: A snapshot of the most recent struct ttm_pool_alloc_state.
92  * @alloced_page: Pointer to the page most recently allocated from a pool or system.
93  * @first_dma: The dma address corresponding to @alloced_page if dma_mapping
94  * is requested.
95  * @alloced_pages: The number of allocated pages present in the struct ttm_tt
96  * page vector from this restore session.
97  * @restored_pages: The number of 4K pages restored for @alloced_page (which
98  * is typically a multi-order page).
99  * @page_caching: The struct ttm_tt requested caching
100  * @order: The order of @alloced_page.
101  *
102  * Recovery from backup might fail when we've recovered less than the
103  * full ttm_tt. In order not to loose any data (yet), keep information
104  * around that allows us to restart a failed ttm backup recovery.
105  */
106 struct ttm_pool_tt_restore {
107 	struct ttm_pool *pool;
108 	struct ttm_pool_alloc_state snapshot_alloc;
109 	struct page *alloced_page;
110 	dma_addr_t first_dma;
111 	pgoff_t alloced_pages;
112 	pgoff_t restored_pages;
113 	enum ttm_caching page_caching;
114 	unsigned int order;
115 };
116 
117 static unsigned long page_pool_size;
118 
119 MODULE_PARM_DESC(page_pool_size, "Number of pages in the WC/UC/DMA pool");
120 module_param(page_pool_size, ulong, 0644);
121 
122 static atomic_long_t allocated_pages;
123 
124 static struct ttm_pool_type global_write_combined[NR_PAGE_ORDERS];
125 static struct ttm_pool_type global_uncached[NR_PAGE_ORDERS];
126 
127 static struct ttm_pool_type global_dma32_write_combined[NR_PAGE_ORDERS];
128 static struct ttm_pool_type global_dma32_uncached[NR_PAGE_ORDERS];
129 
130 static spinlock_t shrinker_lock;
131 static struct list_head shrinker_list;
132 static struct shrinker *mm_shrinker;
133 static DECLARE_RWSEM(pool_shrink_rwsem);
134 
135 /* Allocate pages of size 1 << order with the given gfp_flags */
136 static struct page *ttm_pool_alloc_page(struct ttm_pool *pool, gfp_t gfp_flags,
137 					unsigned int order)
138 {
139 	unsigned long attr = DMA_ATTR_FORCE_CONTIGUOUS;
140 	struct ttm_pool_dma *dma;
141 	struct page *p;
142 	void *vaddr;
143 
144 	/* Don't set the __GFP_COMP flag for higher order allocations.
145 	 * Mapping pages directly into an userspace process and calling
146 	 * put_page() on a TTM allocated page is illegal.
147 	 */
148 	if (order)
149 		gfp_flags |= __GFP_NOMEMALLOC | __GFP_NORETRY | __GFP_NOWARN |
150 			__GFP_THISNODE;
151 
152 	if (!ttm_pool_uses_dma_alloc(pool)) {
153 		p = alloc_pages_node(pool->nid, gfp_flags, order);
154 		if (p)
155 			p->private = order;
156 		return p;
157 	}
158 
159 	dma = kmalloc(sizeof(*dma), GFP_KERNEL);
160 	if (!dma)
161 		return NULL;
162 
163 	if (order)
164 		attr |= DMA_ATTR_NO_WARN;
165 
166 	vaddr = dma_alloc_attrs(pool->dev, (1ULL << order) * PAGE_SIZE,
167 				&dma->addr, gfp_flags, attr);
168 	if (!vaddr)
169 		goto error_free;
170 
171 	/* TODO: This is an illegal abuse of the DMA API, but we need to rework
172 	 * TTM page fault handling and extend the DMA API to clean this up.
173 	 */
174 	if (is_vmalloc_addr(vaddr))
175 		p = vmalloc_to_page(vaddr);
176 	else
177 		p = virt_to_page(vaddr);
178 
179 	dma->vaddr = (unsigned long)vaddr | order;
180 	p->private = (unsigned long)dma;
181 	return p;
182 
183 error_free:
184 	kfree(dma);
185 	return NULL;
186 }
187 
188 /* Reset the caching and pages of size 1 << order */
189 static void ttm_pool_free_page(struct ttm_pool *pool, enum ttm_caching caching,
190 			       unsigned int order, struct page *p)
191 {
192 	unsigned long attr = DMA_ATTR_FORCE_CONTIGUOUS;
193 	struct ttm_pool_dma *dma;
194 	void *vaddr;
195 
196 #ifdef CONFIG_X86
197 	/* We don't care that set_pages_wb is inefficient here. This is only
198 	 * used when we have to shrink and CPU overhead is irrelevant then.
199 	 */
200 	if (caching != ttm_cached && !PageHighMem(p))
201 		set_pages_wb(p, 1 << order);
202 #endif
203 
204 	if (!pool || !ttm_pool_uses_dma_alloc(pool)) {
205 		__free_pages(p, order);
206 		return;
207 	}
208 
209 	if (order)
210 		attr |= DMA_ATTR_NO_WARN;
211 
212 	dma = (void *)p->private;
213 	vaddr = (void *)(dma->vaddr & PAGE_MASK);
214 	dma_free_attrs(pool->dev, (1UL << order) * PAGE_SIZE, vaddr, dma->addr,
215 		       attr);
216 	kfree(dma);
217 }
218 
219 /* Apply any cpu-caching deferred during page allocation */
220 static int ttm_pool_apply_caching(struct ttm_pool_alloc_state *alloc)
221 {
222 #ifdef CONFIG_X86
223 	unsigned int num_pages = alloc->pages - alloc->caching_divide;
224 
225 	if (!num_pages)
226 		return 0;
227 
228 	switch (alloc->tt_caching) {
229 	case ttm_cached:
230 		break;
231 	case ttm_write_combined:
232 		return set_pages_array_wc(alloc->caching_divide, num_pages);
233 	case ttm_uncached:
234 		return set_pages_array_uc(alloc->caching_divide, num_pages);
235 	}
236 #endif
237 	alloc->caching_divide = alloc->pages;
238 	return 0;
239 }
240 
241 /* DMA Map pages of 1 << order size and return the resulting dma_address. */
242 static int ttm_pool_map(struct ttm_pool *pool, unsigned int order,
243 			struct page *p, dma_addr_t *dma_addr)
244 {
245 	dma_addr_t addr;
246 
247 	if (ttm_pool_uses_dma_alloc(pool)) {
248 		struct ttm_pool_dma *dma = (void *)p->private;
249 
250 		addr = dma->addr;
251 	} else {
252 		size_t size = (1ULL << order) * PAGE_SIZE;
253 
254 		addr = dma_map_page(pool->dev, p, 0, size, DMA_BIDIRECTIONAL);
255 		if (dma_mapping_error(pool->dev, addr))
256 			return -EFAULT;
257 	}
258 
259 	*dma_addr = addr;
260 
261 	return 0;
262 }
263 
264 /* Unmap pages of 1 << order size */
265 static void ttm_pool_unmap(struct ttm_pool *pool, dma_addr_t dma_addr,
266 			   unsigned int num_pages)
267 {
268 	/* Unmapped while freeing the page */
269 	if (ttm_pool_uses_dma_alloc(pool))
270 		return;
271 
272 	dma_unmap_page(pool->dev, dma_addr, (long)num_pages << PAGE_SHIFT,
273 		       DMA_BIDIRECTIONAL);
274 }
275 
276 /* Give pages into a specific pool_type */
277 static void ttm_pool_type_give(struct ttm_pool_type *pt, struct page *p)
278 {
279 	unsigned int i, num_pages = 1 << pt->order;
280 
281 	for (i = 0; i < num_pages; ++i) {
282 		if (PageHighMem(p))
283 			clear_highpage(p + i);
284 		else
285 			clear_page(page_address(p + i));
286 	}
287 
288 	spin_lock(&pt->lock);
289 	list_add(&p->lru, &pt->pages);
290 	spin_unlock(&pt->lock);
291 	atomic_long_add(1 << pt->order, &allocated_pages);
292 }
293 
294 /* Take pages from a specific pool_type, return NULL when nothing available */
295 static struct page *ttm_pool_type_take(struct ttm_pool_type *pt)
296 {
297 	struct page *p;
298 
299 	spin_lock(&pt->lock);
300 	p = list_first_entry_or_null(&pt->pages, typeof(*p), lru);
301 	if (p) {
302 		atomic_long_sub(1 << pt->order, &allocated_pages);
303 		list_del(&p->lru);
304 	}
305 	spin_unlock(&pt->lock);
306 
307 	return p;
308 }
309 
310 /* Initialize and add a pool type to the global shrinker list */
311 static void ttm_pool_type_init(struct ttm_pool_type *pt, struct ttm_pool *pool,
312 			       enum ttm_caching caching, unsigned int order)
313 {
314 	pt->pool = pool;
315 	pt->caching = caching;
316 	pt->order = order;
317 	spin_lock_init(&pt->lock);
318 	INIT_LIST_HEAD(&pt->pages);
319 
320 	spin_lock(&shrinker_lock);
321 	list_add_tail(&pt->shrinker_list, &shrinker_list);
322 	spin_unlock(&shrinker_lock);
323 }
324 
325 /* Remove a pool_type from the global shrinker list and free all pages */
326 static void ttm_pool_type_fini(struct ttm_pool_type *pt)
327 {
328 	struct page *p;
329 
330 	spin_lock(&shrinker_lock);
331 	list_del(&pt->shrinker_list);
332 	spin_unlock(&shrinker_lock);
333 
334 	while ((p = ttm_pool_type_take(pt)))
335 		ttm_pool_free_page(pt->pool, pt->caching, pt->order, p);
336 }
337 
338 /* Return the pool_type to use for the given caching and order */
339 static struct ttm_pool_type *ttm_pool_select_type(struct ttm_pool *pool,
340 						  enum ttm_caching caching,
341 						  unsigned int order)
342 {
343 	if (ttm_pool_uses_dma_alloc(pool))
344 		return &pool->caching[caching].orders[order];
345 
346 #ifdef CONFIG_X86
347 	switch (caching) {
348 	case ttm_write_combined:
349 		if (pool->nid != NUMA_NO_NODE)
350 			return &pool->caching[caching].orders[order];
351 
352 		if (ttm_pool_uses_dma32(pool))
353 			return &global_dma32_write_combined[order];
354 
355 		return &global_write_combined[order];
356 	case ttm_uncached:
357 		if (pool->nid != NUMA_NO_NODE)
358 			return &pool->caching[caching].orders[order];
359 
360 		if (ttm_pool_uses_dma32(pool))
361 			return &global_dma32_uncached[order];
362 
363 		return &global_uncached[order];
364 	default:
365 		break;
366 	}
367 #endif
368 
369 	return NULL;
370 }
371 
372 /* Free pages using the global shrinker list */
373 static unsigned int ttm_pool_shrink(void)
374 {
375 	struct ttm_pool_type *pt;
376 	unsigned int num_pages;
377 	struct page *p;
378 
379 	down_read(&pool_shrink_rwsem);
380 	spin_lock(&shrinker_lock);
381 	pt = list_first_entry(&shrinker_list, typeof(*pt), shrinker_list);
382 	list_move_tail(&pt->shrinker_list, &shrinker_list);
383 	spin_unlock(&shrinker_lock);
384 
385 	p = ttm_pool_type_take(pt);
386 	if (p) {
387 		ttm_pool_free_page(pt->pool, pt->caching, pt->order, p);
388 		num_pages = 1 << pt->order;
389 	} else {
390 		num_pages = 0;
391 	}
392 	up_read(&pool_shrink_rwsem);
393 
394 	return num_pages;
395 }
396 
397 /* Return the allocation order based for a page */
398 static unsigned int ttm_pool_page_order(struct ttm_pool *pool, struct page *p)
399 {
400 	if (ttm_pool_uses_dma_alloc(pool)) {
401 		struct ttm_pool_dma *dma = (void *)p->private;
402 
403 		return dma->vaddr & ~PAGE_MASK;
404 	}
405 
406 	return p->private;
407 }
408 
409 /*
410  * Split larger pages so that we can free each PAGE_SIZE page as soon
411  * as it has been backed up, in order to avoid memory pressure during
412  * reclaim.
413  */
414 static void ttm_pool_split_for_swap(struct ttm_pool *pool, struct page *p)
415 {
416 	unsigned int order = ttm_pool_page_order(pool, p);
417 	pgoff_t nr;
418 
419 	if (!order)
420 		return;
421 
422 	split_page(p, order);
423 	nr = 1UL << order;
424 	while (nr--)
425 		(p++)->private = 0;
426 }
427 
428 /**
429  * DOC: Partial backup and restoration of a struct ttm_tt.
430  *
431  * Swapout using ttm_backup_backup_page() and swapin using
432  * ttm_backup_copy_page() may fail.
433  * The former most likely due to lack of swap-space or memory, the latter due
434  * to lack of memory or because of signal interruption during waits.
435  *
436  * Backup failure is easily handled by using a ttm_tt pages vector that holds
437  * both backup handles and page pointers. This has to be taken into account when
438  * restoring such a ttm_tt from backup, and when freeing it while backed up.
439  * When restoring, for simplicity, new pages are actually allocated from the
440  * pool and the contents of any old pages are copied in and then the old pages
441  * are released.
442  *
443  * For restoration failures, the struct ttm_pool_tt_restore holds sufficient state
444  * to be able to resume an interrupted restore, and that structure is freed once
445  * the restoration is complete. If the struct ttm_tt is destroyed while there
446  * is a valid struct ttm_pool_tt_restore attached, that is also properly taken
447  * care of.
448  */
449 
450 /* Is restore ongoing for the currently allocated page? */
451 static bool ttm_pool_restore_valid(const struct ttm_pool_tt_restore *restore)
452 {
453 	return restore && restore->restored_pages < (1 << restore->order);
454 }
455 
456 /* DMA unmap and free a multi-order page, either to the relevant pool or to system. */
457 static pgoff_t ttm_pool_unmap_and_free(struct ttm_pool *pool, struct page *page,
458 				       const dma_addr_t *dma_addr, enum ttm_caching caching)
459 {
460 	struct ttm_pool_type *pt = NULL;
461 	unsigned int order;
462 	pgoff_t nr;
463 
464 	if (pool) {
465 		order = ttm_pool_page_order(pool, page);
466 		nr = (1UL << order);
467 		if (dma_addr)
468 			ttm_pool_unmap(pool, *dma_addr, nr);
469 
470 		pt = ttm_pool_select_type(pool, caching, order);
471 	} else {
472 		order = page->private;
473 		nr = (1UL << order);
474 	}
475 
476 	if (pt)
477 		ttm_pool_type_give(pt, page);
478 	else
479 		ttm_pool_free_page(pool, caching, order, page);
480 
481 	return nr;
482 }
483 
484 /* Populate the page-array using the most recent allocated multi-order page. */
485 static void ttm_pool_allocated_page_commit(struct page *allocated,
486 					   dma_addr_t first_dma,
487 					   struct ttm_pool_alloc_state *alloc,
488 					   pgoff_t nr)
489 {
490 	pgoff_t i;
491 
492 	for (i = 0; i < nr; ++i)
493 		*alloc->pages++ = allocated++;
494 
495 	alloc->remaining_pages -= nr;
496 
497 	if (!alloc->dma_addr)
498 		return;
499 
500 	for (i = 0; i < nr; ++i) {
501 		*alloc->dma_addr++ = first_dma;
502 		first_dma += PAGE_SIZE;
503 	}
504 }
505 
506 /*
507  * When restoring, restore backed-up content to the newly allocated page and
508  * if successful, populate the page-table and dma-address arrays.
509  */
510 static int ttm_pool_restore_commit(struct ttm_pool_tt_restore *restore,
511 				   struct file *backup,
512 				   const struct ttm_operation_ctx *ctx,
513 				   struct ttm_pool_alloc_state *alloc)
514 
515 {
516 	pgoff_t i, nr = 1UL << restore->order;
517 	struct page **first_page = alloc->pages;
518 	struct page *p;
519 	int ret = 0;
520 
521 	for (i = restore->restored_pages; i < nr; ++i) {
522 		p = first_page[i];
523 		if (ttm_backup_page_ptr_is_handle(p)) {
524 			unsigned long handle = ttm_backup_page_ptr_to_handle(p);
525 
526 			if (IS_ENABLED(CONFIG_FAULT_INJECTION) && ctx->interruptible &&
527 			    should_fail(&backup_fault_inject, 1)) {
528 				ret = -EINTR;
529 				break;
530 			}
531 
532 			if (handle == 0) {
533 				restore->restored_pages++;
534 				continue;
535 			}
536 
537 			ret = ttm_backup_copy_page(backup, restore->alloced_page + i,
538 						   handle, ctx->interruptible);
539 			if (ret)
540 				break;
541 
542 			ttm_backup_drop(backup, handle);
543 		} else if (p) {
544 			/*
545 			 * We could probably avoid splitting the old page
546 			 * using clever logic, but ATM we don't care, as
547 			 * we prioritize releasing memory ASAP. Note that
548 			 * here, the old retained page is always write-back
549 			 * cached.
550 			 */
551 			ttm_pool_split_for_swap(restore->pool, p);
552 			copy_highpage(restore->alloced_page + i, p);
553 			__free_pages(p, 0);
554 		}
555 
556 		restore->restored_pages++;
557 		first_page[i] = ttm_backup_handle_to_page_ptr(0);
558 	}
559 
560 	if (ret) {
561 		if (!restore->restored_pages) {
562 			dma_addr_t *dma_addr = alloc->dma_addr ? &restore->first_dma : NULL;
563 
564 			ttm_pool_unmap_and_free(restore->pool, restore->alloced_page,
565 						dma_addr, restore->page_caching);
566 			restore->restored_pages = nr;
567 		}
568 		return ret;
569 	}
570 
571 	ttm_pool_allocated_page_commit(restore->alloced_page, restore->first_dma,
572 				       alloc, nr);
573 	if (restore->page_caching == alloc->tt_caching || PageHighMem(restore->alloced_page))
574 		alloc->caching_divide = alloc->pages;
575 	restore->snapshot_alloc = *alloc;
576 	restore->alloced_pages += nr;
577 
578 	return 0;
579 }
580 
581 /* If restoring, save information needed for ttm_pool_restore_commit(). */
582 static void
583 ttm_pool_page_allocated_restore(struct ttm_pool *pool, unsigned int order,
584 				struct page *p,
585 				enum ttm_caching page_caching,
586 				dma_addr_t first_dma,
587 				struct ttm_pool_tt_restore *restore,
588 				const struct ttm_pool_alloc_state *alloc)
589 {
590 	restore->pool = pool;
591 	restore->order = order;
592 	restore->restored_pages = 0;
593 	restore->page_caching = page_caching;
594 	restore->first_dma = first_dma;
595 	restore->alloced_page = p;
596 	restore->snapshot_alloc = *alloc;
597 }
598 
599 /*
600  * Called when we got a page, either from a pool or newly allocated.
601  * if needed, dma map the page and populate the dma address array.
602  * Populate the page address array.
603  * If the caching is consistent, update any deferred caching. Otherwise
604  * stage this page for an upcoming deferred caching update.
605  */
606 static int ttm_pool_page_allocated(struct ttm_pool *pool, unsigned int order,
607 				   struct page *p, enum ttm_caching page_caching,
608 				   struct ttm_pool_alloc_state *alloc,
609 				   struct ttm_pool_tt_restore *restore)
610 {
611 	bool caching_consistent;
612 	dma_addr_t first_dma;
613 	int r = 0;
614 
615 	caching_consistent = (page_caching == alloc->tt_caching) || PageHighMem(p);
616 
617 	if (caching_consistent) {
618 		r = ttm_pool_apply_caching(alloc);
619 		if (r)
620 			return r;
621 	}
622 
623 	if (alloc->dma_addr) {
624 		r = ttm_pool_map(pool, order, p, &first_dma);
625 		if (r)
626 			return r;
627 	}
628 
629 	if (restore) {
630 		ttm_pool_page_allocated_restore(pool, order, p, page_caching,
631 						first_dma, restore, alloc);
632 	} else {
633 		ttm_pool_allocated_page_commit(p, first_dma, alloc, 1UL << order);
634 
635 		if (caching_consistent)
636 			alloc->caching_divide = alloc->pages;
637 	}
638 
639 	return 0;
640 }
641 
642 /**
643  * ttm_pool_free_range() - Free a range of TTM pages
644  * @pool: The pool used for allocating.
645  * @tt: The struct ttm_tt holding the page pointers.
646  * @caching: The page caching mode used by the range.
647  * @start_page: index for first page to free.
648  * @end_page: index for last page to free + 1.
649  *
650  * During allocation the ttm_tt page-vector may be populated with ranges of
651  * pages with different attributes if allocation hit an error without being
652  * able to completely fulfill the allocation. This function can be used
653  * to free these individual ranges.
654  */
655 static void ttm_pool_free_range(struct ttm_pool *pool, struct ttm_tt *tt,
656 				enum ttm_caching caching,
657 				pgoff_t start_page, pgoff_t end_page)
658 {
659 	struct page **pages = &tt->pages[start_page];
660 	struct file *backup = tt->backup;
661 	pgoff_t i, nr;
662 
663 	for (i = start_page; i < end_page; i += nr, pages += nr) {
664 		struct page *p = *pages;
665 
666 		nr = 1;
667 		if (ttm_backup_page_ptr_is_handle(p)) {
668 			unsigned long handle = ttm_backup_page_ptr_to_handle(p);
669 
670 			if (handle != 0)
671 				ttm_backup_drop(backup, handle);
672 		} else if (p) {
673 			dma_addr_t *dma_addr = tt->dma_address ?
674 				tt->dma_address + i : NULL;
675 
676 			nr = ttm_pool_unmap_and_free(pool, p, dma_addr, caching);
677 		}
678 	}
679 }
680 
681 static void ttm_pool_alloc_state_init(const struct ttm_tt *tt,
682 				      struct ttm_pool_alloc_state *alloc)
683 {
684 	alloc->pages = tt->pages;
685 	alloc->caching_divide = tt->pages;
686 	alloc->dma_addr = tt->dma_address;
687 	alloc->remaining_pages = tt->num_pages;
688 	alloc->tt_caching = tt->caching;
689 }
690 
691 /*
692  * Find a suitable allocation order based on highest desired order
693  * and number of remaining pages
694  */
695 static unsigned int ttm_pool_alloc_find_order(unsigned int highest,
696 					      const struct ttm_pool_alloc_state *alloc)
697 {
698 	return min_t(unsigned int, highest, __fls(alloc->remaining_pages));
699 }
700 
701 static int __ttm_pool_alloc(struct ttm_pool *pool, struct ttm_tt *tt,
702 			    const struct ttm_operation_ctx *ctx,
703 			    struct ttm_pool_alloc_state *alloc,
704 			    struct ttm_pool_tt_restore *restore)
705 {
706 	enum ttm_caching page_caching;
707 	gfp_t gfp_flags = GFP_USER;
708 	pgoff_t caching_divide;
709 	unsigned int order;
710 	bool allow_pools;
711 	struct page *p;
712 	int r;
713 
714 	WARN_ON(!alloc->remaining_pages || ttm_tt_is_populated(tt));
715 	WARN_ON(alloc->dma_addr && !pool->dev);
716 
717 	if (tt->page_flags & TTM_TT_FLAG_ZERO_ALLOC)
718 		gfp_flags |= __GFP_ZERO;
719 
720 	if (ctx->gfp_retry_mayfail)
721 		gfp_flags |= __GFP_RETRY_MAYFAIL;
722 
723 	if (ttm_pool_uses_dma32(pool))
724 		gfp_flags |= GFP_DMA32;
725 	else
726 		gfp_flags |= GFP_HIGHUSER;
727 
728 	page_caching = tt->caching;
729 	allow_pools = true;
730 	for (order = ttm_pool_alloc_find_order(MAX_PAGE_ORDER, alloc);
731 	     alloc->remaining_pages;
732 	     order = ttm_pool_alloc_find_order(order, alloc)) {
733 		struct ttm_pool_type *pt;
734 
735 		/* First, try to allocate a page from a pool if one exists. */
736 		p = NULL;
737 		pt = ttm_pool_select_type(pool, page_caching, order);
738 		if (pt && allow_pools)
739 			p = ttm_pool_type_take(pt);
740 		/*
741 		 * If that fails or previously failed, allocate from system.
742 		 * Note that this also disallows additional pool allocations using
743 		 * write-back cached pools of the same order. Consider removing
744 		 * that behaviour.
745 		 */
746 		if (!p) {
747 			page_caching = ttm_cached;
748 			allow_pools = false;
749 			p = ttm_pool_alloc_page(pool, gfp_flags, order);
750 		}
751 		/* If that fails, lower the order if possible and retry. */
752 		if (!p) {
753 			if (order) {
754 				--order;
755 				page_caching = tt->caching;
756 				allow_pools = true;
757 				continue;
758 			}
759 			r = -ENOMEM;
760 			goto error_free_all;
761 		}
762 		r = ttm_pool_page_allocated(pool, order, p, page_caching, alloc,
763 					    restore);
764 		if (r)
765 			goto error_free_page;
766 
767 		if (ttm_pool_restore_valid(restore)) {
768 			r = ttm_pool_restore_commit(restore, tt->backup, ctx, alloc);
769 			if (r)
770 				goto error_free_all;
771 		}
772 	}
773 
774 	r = ttm_pool_apply_caching(alloc);
775 	if (r)
776 		goto error_free_all;
777 
778 	kfree(tt->restore);
779 	tt->restore = NULL;
780 
781 	return 0;
782 
783 error_free_page:
784 	ttm_pool_free_page(pool, page_caching, order, p);
785 
786 error_free_all:
787 	if (tt->restore)
788 		return r;
789 
790 	caching_divide = alloc->caching_divide - tt->pages;
791 	ttm_pool_free_range(pool, tt, tt->caching, 0, caching_divide);
792 	ttm_pool_free_range(pool, tt, ttm_cached, caching_divide,
793 			    tt->num_pages - alloc->remaining_pages);
794 
795 	return r;
796 }
797 
798 /**
799  * ttm_pool_alloc - Fill a ttm_tt object
800  *
801  * @pool: ttm_pool to use
802  * @tt: ttm_tt object to fill
803  * @ctx: operation context
804  *
805  * Fill the ttm_tt object with pages and also make sure to DMA map them when
806  * necessary.
807  *
808  * Returns: 0 on successe, negative error code otherwise.
809  */
810 int ttm_pool_alloc(struct ttm_pool *pool, struct ttm_tt *tt,
811 		   struct ttm_operation_ctx *ctx)
812 {
813 	struct ttm_pool_alloc_state alloc;
814 
815 	if (WARN_ON(ttm_tt_is_backed_up(tt)))
816 		return -EINVAL;
817 
818 	ttm_pool_alloc_state_init(tt, &alloc);
819 
820 	return __ttm_pool_alloc(pool, tt, ctx, &alloc, NULL);
821 }
822 EXPORT_SYMBOL(ttm_pool_alloc);
823 
824 /**
825  * ttm_pool_restore_and_alloc - Fill a ttm_tt, restoring previously backed-up
826  * content.
827  *
828  * @pool: ttm_pool to use
829  * @tt: ttm_tt object to fill
830  * @ctx: operation context
831  *
832  * Fill the ttm_tt object with pages and also make sure to DMA map them when
833  * necessary. Read in backed-up content.
834  *
835  * Returns: 0 on successe, negative error code otherwise.
836  */
837 int ttm_pool_restore_and_alloc(struct ttm_pool *pool, struct ttm_tt *tt,
838 			       const struct ttm_operation_ctx *ctx)
839 {
840 	struct ttm_pool_alloc_state alloc;
841 
842 	if (WARN_ON(!ttm_tt_is_backed_up(tt)))
843 		return -EINVAL;
844 
845 	if (!tt->restore) {
846 		gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
847 
848 		ttm_pool_alloc_state_init(tt, &alloc);
849 		if (ctx->gfp_retry_mayfail)
850 			gfp |= __GFP_RETRY_MAYFAIL;
851 
852 		tt->restore = kzalloc(sizeof(*tt->restore), gfp);
853 		if (!tt->restore)
854 			return -ENOMEM;
855 
856 		tt->restore->snapshot_alloc = alloc;
857 		tt->restore->pool = pool;
858 		tt->restore->restored_pages = 1;
859 	} else {
860 		struct ttm_pool_tt_restore *restore = tt->restore;
861 		int ret;
862 
863 		alloc = restore->snapshot_alloc;
864 		if (ttm_pool_restore_valid(tt->restore)) {
865 			ret = ttm_pool_restore_commit(restore, tt->backup, ctx, &alloc);
866 			if (ret)
867 				return ret;
868 		}
869 		if (!alloc.remaining_pages)
870 			return 0;
871 	}
872 
873 	return __ttm_pool_alloc(pool, tt, ctx, &alloc, tt->restore);
874 }
875 
876 /**
877  * ttm_pool_free - Free the backing pages from a ttm_tt object
878  *
879  * @pool: Pool to give pages back to.
880  * @tt: ttm_tt object to unpopulate
881  *
882  * Give the packing pages back to a pool or free them
883  */
884 void ttm_pool_free(struct ttm_pool *pool, struct ttm_tt *tt)
885 {
886 	ttm_pool_free_range(pool, tt, tt->caching, 0, tt->num_pages);
887 
888 	while (atomic_long_read(&allocated_pages) > page_pool_size)
889 		ttm_pool_shrink();
890 }
891 EXPORT_SYMBOL(ttm_pool_free);
892 
893 /**
894  * ttm_pool_drop_backed_up() - Release content of a swapped-out struct ttm_tt
895  * @tt: The struct ttm_tt.
896  *
897  * Release handles with associated content or any remaining pages of
898  * a backed-up struct ttm_tt.
899  */
900 void ttm_pool_drop_backed_up(struct ttm_tt *tt)
901 {
902 	struct ttm_pool_tt_restore *restore;
903 	pgoff_t start_page = 0;
904 
905 	WARN_ON(!ttm_tt_is_backed_up(tt));
906 
907 	restore = tt->restore;
908 
909 	/*
910 	 * Unmap and free any uncommitted restore page.
911 	 * any tt page-array backup entries already read back has
912 	 * been cleared already
913 	 */
914 	if (ttm_pool_restore_valid(restore)) {
915 		dma_addr_t *dma_addr = tt->dma_address ? &restore->first_dma : NULL;
916 
917 		ttm_pool_unmap_and_free(restore->pool, restore->alloced_page,
918 					dma_addr, restore->page_caching);
919 		restore->restored_pages = 1UL << restore->order;
920 	}
921 
922 	/*
923 	 * If a restore is ongoing, part of the tt pages may have a
924 	 * caching different than writeback.
925 	 */
926 	if (restore) {
927 		pgoff_t mid = restore->snapshot_alloc.caching_divide - tt->pages;
928 
929 		start_page = restore->alloced_pages;
930 		WARN_ON(mid > start_page);
931 		/* Pages that might be dma-mapped and non-cached */
932 		ttm_pool_free_range(restore->pool, tt, tt->caching,
933 				    0, mid);
934 		/* Pages that might be dma-mapped but cached */
935 		ttm_pool_free_range(restore->pool, tt, ttm_cached,
936 				    mid, restore->alloced_pages);
937 		kfree(restore);
938 		tt->restore = NULL;
939 	}
940 
941 	ttm_pool_free_range(NULL, tt, ttm_cached, start_page, tt->num_pages);
942 }
943 
944 /**
945  * ttm_pool_backup() - Back up or purge a struct ttm_tt
946  * @pool: The pool used when allocating the struct ttm_tt.
947  * @tt: The struct ttm_tt.
948  * @flags: Flags to govern the backup behaviour.
949  *
950  * Back up or purge a struct ttm_tt. If @purge is true, then
951  * all pages will be freed directly to the system rather than to the pool
952  * they were allocated from, making the function behave similarly to
953  * ttm_pool_free(). If @purge is false the pages will be backed up instead,
954  * exchanged for handles.
955  * A subsequent call to ttm_pool_restore_and_alloc() will then read back the content and
956  * a subsequent call to ttm_pool_drop_backed_up() will drop it.
957  * If backup of a page fails for whatever reason, @ttm will still be
958  * partially backed up, retaining those pages for which backup fails.
959  * In that case, this function can be retried, possibly after freeing up
960  * memory resources.
961  *
962  * Return: Number of pages actually backed up or freed, or negative
963  * error code on error.
964  */
965 long ttm_pool_backup(struct ttm_pool *pool, struct ttm_tt *tt,
966 		     const struct ttm_backup_flags *flags)
967 {
968 	struct file *backup = tt->backup;
969 	struct page *page;
970 	unsigned long handle;
971 	gfp_t alloc_gfp;
972 	gfp_t gfp;
973 	int ret = 0;
974 	pgoff_t shrunken = 0;
975 	pgoff_t i, num_pages;
976 
977 	if (WARN_ON(ttm_tt_is_backed_up(tt)))
978 		return -EINVAL;
979 
980 	if ((!ttm_backup_bytes_avail() && !flags->purge) ||
981 	    ttm_pool_uses_dma_alloc(pool) || ttm_tt_is_backed_up(tt))
982 		return -EBUSY;
983 
984 #ifdef CONFIG_X86
985 	/* Anything returned to the system needs to be cached. */
986 	if (tt->caching != ttm_cached)
987 		set_pages_array_wb(tt->pages, tt->num_pages);
988 #endif
989 
990 	if (tt->dma_address || flags->purge) {
991 		for (i = 0; i < tt->num_pages; i += num_pages) {
992 			unsigned int order;
993 
994 			page = tt->pages[i];
995 			if (unlikely(!page)) {
996 				num_pages = 1;
997 				continue;
998 			}
999 
1000 			order = ttm_pool_page_order(pool, page);
1001 			num_pages = 1UL << order;
1002 			if (tt->dma_address)
1003 				ttm_pool_unmap(pool, tt->dma_address[i],
1004 					       num_pages);
1005 			if (flags->purge) {
1006 				shrunken += num_pages;
1007 				page->private = 0;
1008 				__free_pages(page, order);
1009 				memset(tt->pages + i, 0,
1010 				       num_pages * sizeof(*tt->pages));
1011 			}
1012 		}
1013 	}
1014 
1015 	if (flags->purge)
1016 		return shrunken;
1017 
1018 	if (ttm_pool_uses_dma32(pool))
1019 		gfp = GFP_DMA32;
1020 	else
1021 		gfp = GFP_HIGHUSER;
1022 
1023 	alloc_gfp = GFP_KERNEL | __GFP_HIGH | __GFP_NOWARN | __GFP_RETRY_MAYFAIL;
1024 
1025 	num_pages = tt->num_pages;
1026 
1027 	/* Pretend doing fault injection by shrinking only half of the pages. */
1028 	if (IS_ENABLED(CONFIG_FAULT_INJECTION) && should_fail(&backup_fault_inject, 1))
1029 		num_pages = DIV_ROUND_UP(num_pages, 2);
1030 
1031 	for (i = 0; i < num_pages; ++i) {
1032 		s64 shandle;
1033 
1034 		page = tt->pages[i];
1035 		if (unlikely(!page))
1036 			continue;
1037 
1038 		ttm_pool_split_for_swap(pool, page);
1039 
1040 		shandle = ttm_backup_backup_page(backup, page, flags->writeback, i,
1041 						 gfp, alloc_gfp);
1042 		if (shandle < 0) {
1043 			/* We allow partially shrunken tts */
1044 			ret = shandle;
1045 			break;
1046 		}
1047 		handle = shandle;
1048 		tt->pages[i] = ttm_backup_handle_to_page_ptr(handle);
1049 		put_page(page);
1050 		shrunken++;
1051 	}
1052 
1053 	return shrunken ? shrunken : ret;
1054 }
1055 
1056 /**
1057  * ttm_pool_init - Initialize a pool
1058  *
1059  * @pool: the pool to initialize
1060  * @dev: device for DMA allocations and mappings
1061  * @nid: NUMA node to use for allocations
1062  * @use_dma_alloc: true if coherent DMA alloc should be used
1063  * @use_dma32: true if GFP_DMA32 should be used
1064  *
1065  * Initialize the pool and its pool types.
1066  */
1067 void ttm_pool_init(struct ttm_pool *pool, struct device *dev,
1068 		   int nid, bool use_dma_alloc, bool use_dma32)
1069 {
1070 	unsigned int i, j;
1071 
1072 	WARN_ON(!dev && ttm_pool_uses_dma_alloc(pool));
1073 
1074 	pool->dev = dev;
1075 	pool->nid = nid;
1076 	pool->use_dma_alloc = use_dma_alloc;
1077 	pool->use_dma32 = use_dma32;
1078 
1079 	for (i = 0; i < TTM_NUM_CACHING_TYPES; ++i) {
1080 		for (j = 0; j < NR_PAGE_ORDERS; ++j) {
1081 			struct ttm_pool_type *pt;
1082 
1083 			/* Initialize only pool types which are actually used */
1084 			pt = ttm_pool_select_type(pool, i, j);
1085 			if (pt != &pool->caching[i].orders[j])
1086 				continue;
1087 
1088 			ttm_pool_type_init(pt, pool, i, j);
1089 		}
1090 	}
1091 }
1092 EXPORT_SYMBOL(ttm_pool_init);
1093 
1094 /**
1095  * ttm_pool_synchronize_shrinkers - Wait for all running shrinkers to complete.
1096  *
1097  * This is useful to guarantee that all shrinker invocations have seen an
1098  * update, before freeing memory, similar to rcu.
1099  */
1100 static void ttm_pool_synchronize_shrinkers(void)
1101 {
1102 	down_write(&pool_shrink_rwsem);
1103 	up_write(&pool_shrink_rwsem);
1104 }
1105 
1106 /**
1107  * ttm_pool_fini - Cleanup a pool
1108  *
1109  * @pool: the pool to clean up
1110  *
1111  * Free all pages in the pool and unregister the types from the global
1112  * shrinker.
1113  */
1114 void ttm_pool_fini(struct ttm_pool *pool)
1115 {
1116 	unsigned int i, j;
1117 
1118 	for (i = 0; i < TTM_NUM_CACHING_TYPES; ++i) {
1119 		for (j = 0; j < NR_PAGE_ORDERS; ++j) {
1120 			struct ttm_pool_type *pt;
1121 
1122 			pt = ttm_pool_select_type(pool, i, j);
1123 			if (pt != &pool->caching[i].orders[j])
1124 				continue;
1125 
1126 			ttm_pool_type_fini(pt);
1127 		}
1128 	}
1129 
1130 	/* We removed the pool types from the LRU, but we need to also make sure
1131 	 * that no shrinker is concurrently freeing pages from the pool.
1132 	 */
1133 	ttm_pool_synchronize_shrinkers();
1134 }
1135 EXPORT_SYMBOL(ttm_pool_fini);
1136 
1137 /* Free average pool number of pages.  */
1138 #define TTM_SHRINKER_BATCH ((1 << (MAX_PAGE_ORDER / 2)) * NR_PAGE_ORDERS)
1139 
1140 static unsigned long ttm_pool_shrinker_scan(struct shrinker *shrink,
1141 					    struct shrink_control *sc)
1142 {
1143 	unsigned long num_freed = 0;
1144 
1145 	do
1146 		num_freed += ttm_pool_shrink();
1147 	while (num_freed < sc->nr_to_scan &&
1148 	       atomic_long_read(&allocated_pages));
1149 
1150 	sc->nr_scanned = num_freed;
1151 
1152 	return num_freed ?: SHRINK_STOP;
1153 }
1154 
1155 /* Return the number of pages available or SHRINK_EMPTY if we have none */
1156 static unsigned long ttm_pool_shrinker_count(struct shrinker *shrink,
1157 					     struct shrink_control *sc)
1158 {
1159 	unsigned long num_pages = atomic_long_read(&allocated_pages);
1160 
1161 	return num_pages ? num_pages : SHRINK_EMPTY;
1162 }
1163 
1164 #ifdef CONFIG_DEBUG_FS
1165 /* Count the number of pages available in a pool_type */
1166 static unsigned int ttm_pool_type_count(struct ttm_pool_type *pt)
1167 {
1168 	unsigned int count = 0;
1169 	struct page *p;
1170 
1171 	spin_lock(&pt->lock);
1172 	/* Only used for debugfs, the overhead doesn't matter */
1173 	list_for_each_entry(p, &pt->pages, lru)
1174 		++count;
1175 	spin_unlock(&pt->lock);
1176 
1177 	return count;
1178 }
1179 
1180 /* Print a nice header for the order */
1181 static void ttm_pool_debugfs_header(struct seq_file *m)
1182 {
1183 	unsigned int i;
1184 
1185 	seq_puts(m, "\t ");
1186 	for (i = 0; i < NR_PAGE_ORDERS; ++i)
1187 		seq_printf(m, " ---%2u---", i);
1188 	seq_puts(m, "\n");
1189 }
1190 
1191 /* Dump information about the different pool types */
1192 static void ttm_pool_debugfs_orders(struct ttm_pool_type *pt,
1193 				    struct seq_file *m)
1194 {
1195 	unsigned int i;
1196 
1197 	for (i = 0; i < NR_PAGE_ORDERS; ++i)
1198 		seq_printf(m, " %8u", ttm_pool_type_count(&pt[i]));
1199 	seq_puts(m, "\n");
1200 }
1201 
1202 /* Dump the total amount of allocated pages */
1203 static void ttm_pool_debugfs_footer(struct seq_file *m)
1204 {
1205 	seq_printf(m, "\ntotal\t: %8lu of %8lu\n",
1206 		   atomic_long_read(&allocated_pages), page_pool_size);
1207 }
1208 
1209 /* Dump the information for the global pools */
1210 static int ttm_pool_debugfs_globals_show(struct seq_file *m, void *data)
1211 {
1212 	ttm_pool_debugfs_header(m);
1213 
1214 	spin_lock(&shrinker_lock);
1215 	seq_puts(m, "wc\t:");
1216 	ttm_pool_debugfs_orders(global_write_combined, m);
1217 	seq_puts(m, "uc\t:");
1218 	ttm_pool_debugfs_orders(global_uncached, m);
1219 	seq_puts(m, "wc 32\t:");
1220 	ttm_pool_debugfs_orders(global_dma32_write_combined, m);
1221 	seq_puts(m, "uc 32\t:");
1222 	ttm_pool_debugfs_orders(global_dma32_uncached, m);
1223 	spin_unlock(&shrinker_lock);
1224 
1225 	ttm_pool_debugfs_footer(m);
1226 
1227 	return 0;
1228 }
1229 DEFINE_SHOW_ATTRIBUTE(ttm_pool_debugfs_globals);
1230 
1231 /**
1232  * ttm_pool_debugfs - Debugfs dump function for a pool
1233  *
1234  * @pool: the pool to dump the information for
1235  * @m: seq_file to dump to
1236  *
1237  * Make a debugfs dump with the per pool and global information.
1238  */
1239 int ttm_pool_debugfs(struct ttm_pool *pool, struct seq_file *m)
1240 {
1241 	unsigned int i;
1242 
1243 	if (!ttm_pool_uses_dma_alloc(pool) && pool->nid == NUMA_NO_NODE) {
1244 		seq_puts(m, "unused\n");
1245 		return 0;
1246 	}
1247 
1248 	ttm_pool_debugfs_header(m);
1249 
1250 	spin_lock(&shrinker_lock);
1251 	for (i = 0; i < TTM_NUM_CACHING_TYPES; ++i) {
1252 		if (!ttm_pool_select_type(pool, i, 0))
1253 			continue;
1254 		if (ttm_pool_uses_dma_alloc(pool))
1255 			seq_puts(m, "DMA ");
1256 		else
1257 			seq_printf(m, "N%d ", pool->nid);
1258 		switch (i) {
1259 		case ttm_cached:
1260 			seq_puts(m, "\t:");
1261 			break;
1262 		case ttm_write_combined:
1263 			seq_puts(m, "wc\t:");
1264 			break;
1265 		case ttm_uncached:
1266 			seq_puts(m, "uc\t:");
1267 			break;
1268 		}
1269 		ttm_pool_debugfs_orders(pool->caching[i].orders, m);
1270 	}
1271 	spin_unlock(&shrinker_lock);
1272 
1273 	ttm_pool_debugfs_footer(m);
1274 	return 0;
1275 }
1276 EXPORT_SYMBOL(ttm_pool_debugfs);
1277 
1278 /* Test the shrinker functions and dump the result */
1279 static int ttm_pool_debugfs_shrink_show(struct seq_file *m, void *data)
1280 {
1281 	struct shrink_control sc = {
1282 		.gfp_mask = GFP_NOFS,
1283 		.nr_to_scan = TTM_SHRINKER_BATCH,
1284 	};
1285 	unsigned long count;
1286 
1287 	fs_reclaim_acquire(GFP_KERNEL);
1288 	count = ttm_pool_shrinker_count(mm_shrinker, &sc);
1289 	seq_printf(m, "%lu/%lu\n", count,
1290 		   ttm_pool_shrinker_scan(mm_shrinker, &sc));
1291 	fs_reclaim_release(GFP_KERNEL);
1292 
1293 	return 0;
1294 }
1295 DEFINE_SHOW_ATTRIBUTE(ttm_pool_debugfs_shrink);
1296 
1297 #endif
1298 
1299 /**
1300  * ttm_pool_mgr_init - Initialize globals
1301  *
1302  * @num_pages: default number of pages
1303  *
1304  * Initialize the global locks and lists for the MM shrinker.
1305  */
1306 int ttm_pool_mgr_init(unsigned long num_pages)
1307 {
1308 	unsigned int i;
1309 
1310 	if (!page_pool_size)
1311 		page_pool_size = num_pages;
1312 
1313 	spin_lock_init(&shrinker_lock);
1314 	INIT_LIST_HEAD(&shrinker_list);
1315 
1316 	for (i = 0; i < NR_PAGE_ORDERS; ++i) {
1317 		ttm_pool_type_init(&global_write_combined[i], NULL,
1318 				   ttm_write_combined, i);
1319 		ttm_pool_type_init(&global_uncached[i], NULL, ttm_uncached, i);
1320 
1321 		ttm_pool_type_init(&global_dma32_write_combined[i], NULL,
1322 				   ttm_write_combined, i);
1323 		ttm_pool_type_init(&global_dma32_uncached[i], NULL,
1324 				   ttm_uncached, i);
1325 	}
1326 
1327 #ifdef CONFIG_DEBUG_FS
1328 	debugfs_create_file("page_pool", 0444, ttm_debugfs_root, NULL,
1329 			    &ttm_pool_debugfs_globals_fops);
1330 	debugfs_create_file("page_pool_shrink", 0400, ttm_debugfs_root, NULL,
1331 			    &ttm_pool_debugfs_shrink_fops);
1332 #ifdef CONFIG_FAULT_INJECTION
1333 	fault_create_debugfs_attr("backup_fault_inject", ttm_debugfs_root,
1334 				  &backup_fault_inject);
1335 #endif
1336 #endif
1337 
1338 	mm_shrinker = shrinker_alloc(0, "drm-ttm_pool");
1339 	if (!mm_shrinker)
1340 		return -ENOMEM;
1341 
1342 	mm_shrinker->count_objects = ttm_pool_shrinker_count;
1343 	mm_shrinker->scan_objects = ttm_pool_shrinker_scan;
1344 	mm_shrinker->batch = TTM_SHRINKER_BATCH;
1345 	mm_shrinker->seeks = 1;
1346 
1347 	shrinker_register(mm_shrinker);
1348 
1349 	return 0;
1350 }
1351 
1352 /**
1353  * ttm_pool_mgr_fini - Finalize globals
1354  *
1355  * Cleanup the global pools and unregister the MM shrinker.
1356  */
1357 void ttm_pool_mgr_fini(void)
1358 {
1359 	unsigned int i;
1360 
1361 	for (i = 0; i < NR_PAGE_ORDERS; ++i) {
1362 		ttm_pool_type_fini(&global_write_combined[i]);
1363 		ttm_pool_type_fini(&global_uncached[i]);
1364 
1365 		ttm_pool_type_fini(&global_dma32_write_combined[i]);
1366 		ttm_pool_type_fini(&global_dma32_uncached[i]);
1367 	}
1368 
1369 	shrinker_free(mm_shrinker);
1370 	WARN_ON(!list_empty(&shrinker_list));
1371 }
1372