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