xref: /linux/drivers/gpu/drm/i915/gem/i915_gem_shrinker.c (revision 05f0431bb90f2ee3657e7fc2678f11a1f9b778b7)
1 /*
2  * SPDX-License-Identifier: MIT
3  *
4  * Copyright © 2008-2015 Intel Corporation
5  */
6 
7 #include <linux/oom.h>
8 #include <linux/sched/mm.h>
9 #include <linux/shmem_fs.h>
10 #include <linux/slab.h>
11 #include <linux/swap.h>
12 #include <linux/pci.h>
13 #include <linux/dma-buf.h>
14 #include <linux/vmalloc.h>
15 
16 #include "gt/intel_gt_requests.h"
17 #include "gt/intel_gt.h"
18 
19 #include "i915_trace.h"
20 
21 static bool swap_available(void)
22 {
23 	return get_nr_swap_pages() > 0;
24 }
25 
26 static bool can_release_pages(struct drm_i915_gem_object *obj)
27 {
28 	/* Consider only shrinkable ojects. */
29 	if (!i915_gem_object_is_shrinkable(obj))
30 		return false;
31 
32 	/*
33 	 * We can only return physical pages to the system if we can either
34 	 * discard the contents (because the user has marked them as being
35 	 * purgeable) or if we can move their contents out to swap.
36 	 */
37 	return swap_available() || obj->mm.madv == I915_MADV_DONTNEED;
38 }
39 
40 static bool drop_pages(struct drm_i915_gem_object *obj,
41 		       unsigned long shrink, bool trylock_vm)
42 {
43 	unsigned long flags;
44 
45 	flags = 0;
46 	if (shrink & I915_SHRINK_ACTIVE)
47 		flags |= I915_GEM_OBJECT_UNBIND_ACTIVE;
48 	if (!(shrink & I915_SHRINK_BOUND))
49 		flags |= I915_GEM_OBJECT_UNBIND_TEST;
50 	if (trylock_vm)
51 		flags |= I915_GEM_OBJECT_UNBIND_VM_TRYLOCK;
52 
53 	if (i915_gem_object_unbind(obj, flags) == 0)
54 		return true;
55 
56 	return false;
57 }
58 
59 static int try_to_writeback(struct drm_i915_gem_object *obj, unsigned int flags)
60 {
61 	if (obj->ops->shrink) {
62 		unsigned int shrink_flags = 0;
63 
64 		if (!(flags & I915_SHRINK_ACTIVE))
65 			shrink_flags |= I915_GEM_OBJECT_SHRINK_NO_GPU_WAIT;
66 
67 		if (flags & I915_SHRINK_WRITEBACK)
68 			shrink_flags |= I915_GEM_OBJECT_SHRINK_WRITEBACK;
69 
70 		return obj->ops->shrink(obj, shrink_flags);
71 	}
72 
73 	return 0;
74 }
75 
76 /**
77  * i915_gem_shrink - Shrink buffer object caches
78  * @ww: i915 gem ww acquire ctx, or NULL
79  * @i915: i915 device
80  * @target: amount of memory to make available, in pages
81  * @nr_scanned: optional output for number of pages scanned (incremental)
82  * @shrink: control flags for selecting cache types
83  *
84  * This function is the main interface to the shrinker. It will try to release
85  * up to @target pages of main memory backing storage from buffer objects.
86  * Selection of the specific caches can be done with @flags. This is e.g. useful
87  * when purgeable objects should be removed from caches preferentially.
88  *
89  * Note that it's not guaranteed that released amount is actually available as
90  * free system memory - the pages might still be in-used to due to other reasons
91  * (like cpu mmaps) or the mm core has reused them before we could grab them.
92  * Therefore code that needs to explicitly shrink buffer objects caches (e.g. to
93  * avoid deadlocks in memory reclaim) must fall back to i915_gem_shrink_all().
94  *
95  * Also note that any kind of pinning (both per-vma address space pins and
96  * backing storage pins at the buffer object level) result in the shrinker code
97  * having to skip the object.
98  *
99  * Returns:
100  * The number of pages of backing storage actually released.
101  */
102 unsigned long
103 i915_gem_shrink(struct i915_gem_ww_ctx *ww,
104 		struct drm_i915_private *i915,
105 		unsigned long target,
106 		unsigned long *nr_scanned,
107 		unsigned int shrink)
108 {
109 	const struct {
110 		struct list_head *list;
111 		unsigned int bit;
112 	} phases[] = {
113 		{ &i915->mm.purge_list, ~0u },
114 		{
115 			&i915->mm.shrink_list,
116 			I915_SHRINK_BOUND | I915_SHRINK_UNBOUND
117 		},
118 		{ NULL, 0 },
119 	}, *phase;
120 	intel_wakeref_t wakeref = 0;
121 	unsigned long count = 0;
122 	unsigned long scanned = 0;
123 	int err = 0, i = 0;
124 	struct intel_gt *gt;
125 
126 	/* CHV + VTD workaround use stop_machine(); need to trylock vm->mutex */
127 	bool trylock_vm = !ww && intel_vm_no_concurrent_access_wa(i915);
128 
129 	trace_i915_gem_shrink(i915, target, shrink);
130 
131 	/*
132 	 * Unbinding of objects will require HW access; Let us not wake the
133 	 * device just to recover a little memory. If absolutely necessary,
134 	 * we will force the wake during oom-notifier.
135 	 */
136 	if (shrink & I915_SHRINK_BOUND) {
137 		wakeref = intel_runtime_pm_get_if_in_use(&i915->runtime_pm);
138 		if (!wakeref)
139 			shrink &= ~I915_SHRINK_BOUND;
140 	}
141 
142 	/*
143 	 * When shrinking the active list, we should also consider active
144 	 * contexts. Active contexts are pinned until they are retired, and
145 	 * so can not be simply unbound to retire and unpin their pages. To
146 	 * shrink the contexts, we must wait until the gpu is idle and
147 	 * completed its switch to the kernel context. In short, we do
148 	 * not have a good mechanism for idling a specific context, but
149 	 * what we can do is give them a kick so that we do not keep idle
150 	 * contexts around longer than is necessary.
151 	 */
152 	if (shrink & I915_SHRINK_ACTIVE) {
153 		for_each_gt(gt, i915, i)
154 			/* Retire requests to unpin all idle contexts */
155 			intel_gt_retire_requests(gt);
156 	}
157 
158 	/*
159 	 * As we may completely rewrite the (un)bound list whilst unbinding
160 	 * (due to retiring requests) we have to strictly process only
161 	 * one element of the list at the time, and recheck the list
162 	 * on every iteration.
163 	 *
164 	 * In particular, we must hold a reference whilst removing the
165 	 * object as we may end up waiting for and/or retiring the objects.
166 	 * This might release the final reference (held by the active list)
167 	 * and result in the object being freed from under us. This is
168 	 * similar to the precautions the eviction code must take whilst
169 	 * removing objects.
170 	 *
171 	 * Also note that although these lists do not hold a reference to
172 	 * the object we can safely grab one here: The final object
173 	 * unreferencing and the bound_list are both protected by the
174 	 * dev->struct_mutex and so we won't ever be able to observe an
175 	 * object on the bound_list with a reference count equals 0.
176 	 */
177 	for (phase = phases; phase->list; phase++) {
178 		struct list_head still_in_list;
179 		struct drm_i915_gem_object *obj;
180 		unsigned long flags;
181 
182 		if ((shrink & phase->bit) == 0)
183 			continue;
184 
185 		INIT_LIST_HEAD(&still_in_list);
186 
187 		/*
188 		 * We serialize our access to unreferenced objects through
189 		 * the use of the struct_mutex. While the objects are not
190 		 * yet freed (due to RCU then a workqueue) we still want
191 		 * to be able to shrink their pages, so they remain on
192 		 * the unbound/bound list until actually freed.
193 		 */
194 		spin_lock_irqsave(&i915->mm.obj_lock, flags);
195 		while (count < target &&
196 		       (obj = list_first_entry_or_null(phase->list,
197 						       typeof(*obj),
198 						       mm.link))) {
199 			list_move_tail(&obj->mm.link, &still_in_list);
200 
201 			if (shrink & I915_SHRINK_VMAPS &&
202 			    !is_vmalloc_addr(obj->mm.mapping))
203 				continue;
204 
205 			if (!(shrink & I915_SHRINK_ACTIVE) &&
206 			    i915_gem_object_is_framebuffer(obj))
207 				continue;
208 
209 			if (!can_release_pages(obj))
210 				continue;
211 
212 			if (!kref_get_unless_zero(&obj->base.refcount))
213 				continue;
214 
215 			spin_unlock_irqrestore(&i915->mm.obj_lock, flags);
216 
217 			/* May arrive from get_pages on another bo */
218 			if (!ww) {
219 				if (!i915_gem_object_trylock(obj, NULL))
220 					goto skip;
221 			} else {
222 				err = i915_gem_object_lock(obj, ww);
223 				if (err)
224 					goto skip;
225 			}
226 
227 			if (drop_pages(obj, shrink, trylock_vm) &&
228 			    !__i915_gem_object_put_pages(obj) &&
229 			    !try_to_writeback(obj, shrink))
230 				count += obj->base.size >> PAGE_SHIFT;
231 
232 			if (!ww)
233 				i915_gem_object_unlock(obj);
234 
235 			scanned += obj->base.size >> PAGE_SHIFT;
236 skip:
237 			i915_gem_object_put(obj);
238 
239 			spin_lock_irqsave(&i915->mm.obj_lock, flags);
240 			if (err)
241 				break;
242 		}
243 		list_splice_tail(&still_in_list, phase->list);
244 		spin_unlock_irqrestore(&i915->mm.obj_lock, flags);
245 		if (err)
246 			break;
247 	}
248 
249 	if (shrink & I915_SHRINK_BOUND)
250 		intel_runtime_pm_put(&i915->runtime_pm, wakeref);
251 
252 	if (err)
253 		return err;
254 
255 	if (nr_scanned)
256 		*nr_scanned += scanned;
257 	return count;
258 }
259 
260 /**
261  * i915_gem_shrink_all - Shrink buffer object caches completely
262  * @i915: i915 device
263  *
264  * This is a simple wraper around i915_gem_shrink() to aggressively shrink all
265  * caches completely. It also first waits for and retires all outstanding
266  * requests to also be able to release backing storage for active objects.
267  *
268  * This should only be used in code to intentionally quiescent the gpu or as a
269  * last-ditch effort when memory seems to have run out.
270  *
271  * Returns:
272  * The number of pages of backing storage actually released.
273  */
274 unsigned long i915_gem_shrink_all(struct drm_i915_private *i915)
275 {
276 	intel_wakeref_t wakeref;
277 	unsigned long freed = 0;
278 
279 	with_intel_runtime_pm(&i915->runtime_pm, wakeref) {
280 		freed = i915_gem_shrink(NULL, i915, -1UL, NULL,
281 					I915_SHRINK_BOUND |
282 					I915_SHRINK_UNBOUND);
283 	}
284 
285 	return freed;
286 }
287 
288 static unsigned long
289 i915_gem_shrinker_count(struct shrinker *shrinker, struct shrink_control *sc)
290 {
291 	struct drm_i915_private *i915 =
292 		container_of(shrinker, struct drm_i915_private, mm.shrinker);
293 	unsigned long num_objects;
294 	unsigned long count;
295 
296 	count = READ_ONCE(i915->mm.shrink_memory) >> PAGE_SHIFT;
297 	num_objects = READ_ONCE(i915->mm.shrink_count);
298 
299 	/*
300 	 * Update our preferred vmscan batch size for the next pass.
301 	 * Our rough guess for an effective batch size is roughly 2
302 	 * available GEM objects worth of pages. That is we don't want
303 	 * the shrinker to fire, until it is worth the cost of freeing an
304 	 * entire GEM object.
305 	 */
306 	if (num_objects) {
307 		unsigned long avg = 2 * count / num_objects;
308 
309 		i915->mm.shrinker.batch =
310 			max((i915->mm.shrinker.batch + avg) >> 1,
311 			    128ul /* default SHRINK_BATCH */);
312 	}
313 
314 	return count;
315 }
316 
317 static unsigned long
318 i915_gem_shrinker_scan(struct shrinker *shrinker, struct shrink_control *sc)
319 {
320 	struct drm_i915_private *i915 =
321 		container_of(shrinker, struct drm_i915_private, mm.shrinker);
322 	unsigned long freed;
323 
324 	sc->nr_scanned = 0;
325 
326 	freed = i915_gem_shrink(NULL, i915,
327 				sc->nr_to_scan,
328 				&sc->nr_scanned,
329 				I915_SHRINK_BOUND |
330 				I915_SHRINK_UNBOUND);
331 	if (sc->nr_scanned < sc->nr_to_scan && current_is_kswapd()) {
332 		intel_wakeref_t wakeref;
333 
334 		with_intel_runtime_pm(&i915->runtime_pm, wakeref) {
335 			freed += i915_gem_shrink(NULL, i915,
336 						 sc->nr_to_scan - sc->nr_scanned,
337 						 &sc->nr_scanned,
338 						 I915_SHRINK_ACTIVE |
339 						 I915_SHRINK_BOUND |
340 						 I915_SHRINK_UNBOUND |
341 						 I915_SHRINK_WRITEBACK);
342 		}
343 	}
344 
345 	return sc->nr_scanned ? freed : SHRINK_STOP;
346 }
347 
348 static int
349 i915_gem_shrinker_oom(struct notifier_block *nb, unsigned long event, void *ptr)
350 {
351 	struct drm_i915_private *i915 =
352 		container_of(nb, struct drm_i915_private, mm.oom_notifier);
353 	struct drm_i915_gem_object *obj;
354 	unsigned long unevictable, available, freed_pages;
355 	intel_wakeref_t wakeref;
356 	unsigned long flags;
357 
358 	freed_pages = 0;
359 	with_intel_runtime_pm(&i915->runtime_pm, wakeref)
360 		freed_pages += i915_gem_shrink(NULL, i915, -1UL, NULL,
361 					       I915_SHRINK_BOUND |
362 					       I915_SHRINK_UNBOUND |
363 					       I915_SHRINK_WRITEBACK);
364 
365 	/* Because we may be allocating inside our own driver, we cannot
366 	 * assert that there are no objects with pinned pages that are not
367 	 * being pointed to by hardware.
368 	 */
369 	available = unevictable = 0;
370 	spin_lock_irqsave(&i915->mm.obj_lock, flags);
371 	list_for_each_entry(obj, &i915->mm.shrink_list, mm.link) {
372 		if (!can_release_pages(obj))
373 			unevictable += obj->base.size >> PAGE_SHIFT;
374 		else
375 			available += obj->base.size >> PAGE_SHIFT;
376 	}
377 	spin_unlock_irqrestore(&i915->mm.obj_lock, flags);
378 
379 	if (freed_pages || available)
380 		pr_info("Purging GPU memory, %lu pages freed, "
381 			"%lu pages still pinned, %lu pages left available.\n",
382 			freed_pages, unevictable, available);
383 
384 	*(unsigned long *)ptr += freed_pages;
385 	return NOTIFY_DONE;
386 }
387 
388 static int
389 i915_gem_shrinker_vmap(struct notifier_block *nb, unsigned long event, void *ptr)
390 {
391 	struct drm_i915_private *i915 =
392 		container_of(nb, struct drm_i915_private, mm.vmap_notifier);
393 	struct i915_vma *vma, *next;
394 	unsigned long freed_pages = 0;
395 	intel_wakeref_t wakeref;
396 	struct intel_gt *gt;
397 	int i;
398 
399 	with_intel_runtime_pm(&i915->runtime_pm, wakeref)
400 		freed_pages += i915_gem_shrink(NULL, i915, -1UL, NULL,
401 					       I915_SHRINK_BOUND |
402 					       I915_SHRINK_UNBOUND |
403 					       I915_SHRINK_VMAPS);
404 
405 	/* We also want to clear any cached iomaps as they wrap vmap */
406 	for_each_gt(gt, i915, i) {
407 		mutex_lock(&gt->ggtt->vm.mutex);
408 		list_for_each_entry_safe(vma, next,
409 					 &gt->ggtt->vm.bound_list, vm_link) {
410 			unsigned long count = i915_vma_size(vma) >> PAGE_SHIFT;
411 			struct drm_i915_gem_object *obj = vma->obj;
412 
413 			if (!vma->iomap || i915_vma_is_active(vma))
414 				continue;
415 
416 			if (!i915_gem_object_trylock(obj, NULL))
417 				continue;
418 
419 			if (__i915_vma_unbind(vma) == 0)
420 				freed_pages += count;
421 
422 			i915_gem_object_unlock(obj);
423 		}
424 		mutex_unlock(&gt->ggtt->vm.mutex);
425 	}
426 
427 	*(unsigned long *)ptr += freed_pages;
428 	return NOTIFY_DONE;
429 }
430 
431 void i915_gem_driver_register__shrinker(struct drm_i915_private *i915)
432 {
433 	i915->mm.shrinker.scan_objects = i915_gem_shrinker_scan;
434 	i915->mm.shrinker.count_objects = i915_gem_shrinker_count;
435 	i915->mm.shrinker.seeks = DEFAULT_SEEKS;
436 	i915->mm.shrinker.batch = 4096;
437 	drm_WARN_ON(&i915->drm, register_shrinker(&i915->mm.shrinker,
438 						  "drm-i915_gem"));
439 
440 	i915->mm.oom_notifier.notifier_call = i915_gem_shrinker_oom;
441 	drm_WARN_ON(&i915->drm, register_oom_notifier(&i915->mm.oom_notifier));
442 
443 	i915->mm.vmap_notifier.notifier_call = i915_gem_shrinker_vmap;
444 	drm_WARN_ON(&i915->drm,
445 		    register_vmap_purge_notifier(&i915->mm.vmap_notifier));
446 }
447 
448 void i915_gem_driver_unregister__shrinker(struct drm_i915_private *i915)
449 {
450 	drm_WARN_ON(&i915->drm,
451 		    unregister_vmap_purge_notifier(&i915->mm.vmap_notifier));
452 	drm_WARN_ON(&i915->drm,
453 		    unregister_oom_notifier(&i915->mm.oom_notifier));
454 	unregister_shrinker(&i915->mm.shrinker);
455 }
456 
457 void i915_gem_shrinker_taints_mutex(struct drm_i915_private *i915,
458 				    struct mutex *mutex)
459 {
460 	if (!IS_ENABLED(CONFIG_LOCKDEP))
461 		return;
462 
463 	fs_reclaim_acquire(GFP_KERNEL);
464 
465 	mutex_acquire(&mutex->dep_map, 0, 0, _RET_IP_);
466 	mutex_release(&mutex->dep_map, _RET_IP_);
467 
468 	fs_reclaim_release(GFP_KERNEL);
469 }
470 
471 /**
472  * i915_gem_object_make_unshrinkable - Hide the object from the shrinker. By
473  * default all object types that support shrinking(see IS_SHRINKABLE), will also
474  * make the object visible to the shrinker after allocating the system memory
475  * pages.
476  * @obj: The GEM object.
477  *
478  * This is typically used for special kernel internal objects that can't be
479  * easily processed by the shrinker, like if they are perma-pinned.
480  */
481 void i915_gem_object_make_unshrinkable(struct drm_i915_gem_object *obj)
482 {
483 	struct drm_i915_private *i915 = obj_to_i915(obj);
484 	unsigned long flags;
485 
486 	/*
487 	 * We can only be called while the pages are pinned or when
488 	 * the pages are released. If pinned, we should only be called
489 	 * from a single caller under controlled conditions; and on release
490 	 * only one caller may release us. Neither the two may cross.
491 	 */
492 	if (atomic_add_unless(&obj->mm.shrink_pin, 1, 0))
493 		return;
494 
495 	spin_lock_irqsave(&i915->mm.obj_lock, flags);
496 	if (!atomic_fetch_inc(&obj->mm.shrink_pin) &&
497 	    !list_empty(&obj->mm.link)) {
498 		list_del_init(&obj->mm.link);
499 		i915->mm.shrink_count--;
500 		i915->mm.shrink_memory -= obj->base.size;
501 	}
502 	spin_unlock_irqrestore(&i915->mm.obj_lock, flags);
503 }
504 
505 static void ___i915_gem_object_make_shrinkable(struct drm_i915_gem_object *obj,
506 					       struct list_head *head)
507 {
508 	struct drm_i915_private *i915 = obj_to_i915(obj);
509 	unsigned long flags;
510 
511 	if (!i915_gem_object_is_shrinkable(obj))
512 		return;
513 
514 	if (atomic_add_unless(&obj->mm.shrink_pin, -1, 1))
515 		return;
516 
517 	spin_lock_irqsave(&i915->mm.obj_lock, flags);
518 	GEM_BUG_ON(!kref_read(&obj->base.refcount));
519 	if (atomic_dec_and_test(&obj->mm.shrink_pin)) {
520 		GEM_BUG_ON(!list_empty(&obj->mm.link));
521 
522 		list_add_tail(&obj->mm.link, head);
523 		i915->mm.shrink_count++;
524 		i915->mm.shrink_memory += obj->base.size;
525 
526 	}
527 	spin_unlock_irqrestore(&i915->mm.obj_lock, flags);
528 }
529 
530 /**
531  * __i915_gem_object_make_shrinkable - Move the object to the tail of the
532  * shrinkable list. Objects on this list might be swapped out. Used with
533  * WILLNEED objects.
534  * @obj: The GEM object.
535  *
536  * DO NOT USE. This is intended to be called on very special objects that don't
537  * yet have mm.pages, but are guaranteed to have potentially reclaimable pages
538  * underneath.
539  */
540 void __i915_gem_object_make_shrinkable(struct drm_i915_gem_object *obj)
541 {
542 	___i915_gem_object_make_shrinkable(obj,
543 					   &obj_to_i915(obj)->mm.shrink_list);
544 }
545 
546 /**
547  * __i915_gem_object_make_purgeable - Move the object to the tail of the
548  * purgeable list. Objects on this list might be swapped out. Used with
549  * DONTNEED objects.
550  * @obj: The GEM object.
551  *
552  * DO NOT USE. This is intended to be called on very special objects that don't
553  * yet have mm.pages, but are guaranteed to have potentially reclaimable pages
554  * underneath.
555  */
556 void __i915_gem_object_make_purgeable(struct drm_i915_gem_object *obj)
557 {
558 	___i915_gem_object_make_shrinkable(obj,
559 					   &obj_to_i915(obj)->mm.purge_list);
560 }
561 
562 /**
563  * i915_gem_object_make_shrinkable - Move the object to the tail of the
564  * shrinkable list. Objects on this list might be swapped out. Used with
565  * WILLNEED objects.
566  * @obj: The GEM object.
567  *
568  * MUST only be called on objects which have backing pages.
569  *
570  * MUST be balanced with previous call to i915_gem_object_make_unshrinkable().
571  */
572 void i915_gem_object_make_shrinkable(struct drm_i915_gem_object *obj)
573 {
574 	GEM_BUG_ON(!i915_gem_object_has_pages(obj));
575 	__i915_gem_object_make_shrinkable(obj);
576 }
577 
578 /**
579  * i915_gem_object_make_purgeable - Move the object to the tail of the purgeable
580  * list. Used with DONTNEED objects. Unlike with shrinkable objects, the
581  * shrinker will attempt to discard the backing pages, instead of trying to swap
582  * them out.
583  * @obj: The GEM object.
584  *
585  * MUST only be called on objects which have backing pages.
586  *
587  * MUST be balanced with previous call to i915_gem_object_make_unshrinkable().
588  */
589 void i915_gem_object_make_purgeable(struct drm_i915_gem_object *obj)
590 {
591 	GEM_BUG_ON(!i915_gem_object_has_pages(obj));
592 	__i915_gem_object_make_purgeable(obj);
593 }
594