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