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