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