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 "i915_trace.h"
19 
20 static bool swap_available(void)
21 {
22 	return get_nr_swap_pages() > 0;
23 }
24 
25 static bool can_release_pages(struct drm_i915_gem_object *obj)
26 {
27 	/* Consider only shrinkable ojects. */
28 	if (!i915_gem_object_is_shrinkable(obj))
29 		return false;
30 
31 	/*
32 	 * We can only return physical pages to the system if we can either
33 	 * discard the contents (because the user has marked them as being
34 	 * purgeable) or if we can move their contents out to swap.
35 	 */
36 	return swap_available() || obj->mm.madv == I915_MADV_DONTNEED;
37 }
38 
39 static int drop_pages(struct drm_i915_gem_object *obj,
40 		       unsigned long shrink, bool trylock_vm)
41 {
42 	unsigned long flags;
43 
44 	flags = 0;
45 	if (shrink & I915_SHRINK_ACTIVE)
46 		flags |= I915_GEM_OBJECT_UNBIND_ACTIVE;
47 	if (!(shrink & I915_SHRINK_BOUND))
48 		flags |= I915_GEM_OBJECT_UNBIND_TEST;
49 	if (trylock_vm)
50 		flags |= I915_GEM_OBJECT_UNBIND_VM_TRYLOCK;
51 
52 	if (i915_gem_object_unbind(obj, flags) == 0)
53 		return true;
54 
55 	return false;
56 }
57 
58 static int try_to_writeback(struct drm_i915_gem_object *obj, unsigned int flags)
59 {
60 	if (obj->ops->shrinker_release_pages)
61 		return obj->ops->shrinker_release_pages(obj,
62 							!(flags & I915_SHRINK_ACTIVE),
63 							flags & I915_SHRINK_WRITEBACK);
64 
65 	switch (obj->mm.madv) {
66 	case I915_MADV_DONTNEED:
67 		i915_gem_object_truncate(obj);
68 		return 0;
69 	case __I915_MADV_PURGED:
70 		return 0;
71 	}
72 
73 	if (flags & I915_SHRINK_WRITEBACK)
74 		i915_gem_object_writeback(obj);
75 
76 	return 0;
77 }
78 
79 /**
80  * i915_gem_shrink - Shrink buffer object caches
81  * @ww: i915 gem ww acquire ctx, or NULL
82  * @i915: i915 device
83  * @target: amount of memory to make available, in pages
84  * @nr_scanned: optional output for number of pages scanned (incremental)
85  * @shrink: control flags for selecting cache types
86  *
87  * This function is the main interface to the shrinker. It will try to release
88  * up to @target pages of main memory backing storage from buffer objects.
89  * Selection of the specific caches can be done with @flags. This is e.g. useful
90  * when purgeable objects should be removed from caches preferentially.
91  *
92  * Note that it's not guaranteed that released amount is actually available as
93  * free system memory - the pages might still be in-used to due to other reasons
94  * (like cpu mmaps) or the mm core has reused them before we could grab them.
95  * Therefore code that needs to explicitly shrink buffer objects caches (e.g. to
96  * avoid deadlocks in memory reclaim) must fall back to i915_gem_shrink_all().
97  *
98  * Also note that any kind of pinning (both per-vma address space pins and
99  * backing storage pins at the buffer object level) result in the shrinker code
100  * having to skip the object.
101  *
102  * Returns:
103  * The number of pages of backing storage actually released.
104  */
105 unsigned long
106 i915_gem_shrink(struct i915_gem_ww_ctx *ww,
107 		struct drm_i915_private *i915,
108 		unsigned long target,
109 		unsigned long *nr_scanned,
110 		unsigned int shrink)
111 {
112 	const struct {
113 		struct list_head *list;
114 		unsigned int bit;
115 	} phases[] = {
116 		{ &i915->mm.purge_list, ~0u },
117 		{
118 			&i915->mm.shrink_list,
119 			I915_SHRINK_BOUND | I915_SHRINK_UNBOUND
120 		},
121 		{ NULL, 0 },
122 	}, *phase;
123 	intel_wakeref_t wakeref = 0;
124 	unsigned long count = 0;
125 	unsigned long scanned = 0;
126 	int err = 0;
127 
128 	/* CHV + VTD workaround use stop_machine(); need to trylock vm->mutex */
129 	bool trylock_vm = !ww && intel_vm_no_concurrent_access_wa(i915);
130 
131 	trace_i915_gem_shrink(i915, target, shrink);
132 
133 	/*
134 	 * Unbinding of objects will require HW access; Let us not wake the
135 	 * device just to recover a little memory. If absolutely necessary,
136 	 * we will force the wake during oom-notifier.
137 	 */
138 	if (shrink & I915_SHRINK_BOUND) {
139 		wakeref = intel_runtime_pm_get_if_in_use(&i915->runtime_pm);
140 		if (!wakeref)
141 			shrink &= ~I915_SHRINK_BOUND;
142 	}
143 
144 	/*
145 	 * When shrinking the active list, we should also consider active
146 	 * contexts. Active contexts are pinned until they are retired, and
147 	 * so can not be simply unbound to retire and unpin their pages. To
148 	 * shrink the contexts, we must wait until the gpu is idle and
149 	 * completed its switch to the kernel context. In short, we do
150 	 * not have a good mechanism for idling a specific context, but
151 	 * what we can do is give them a kick so that we do not keep idle
152 	 * contexts around longer than is necessary.
153 	 */
154 	if (shrink & I915_SHRINK_ACTIVE)
155 		/* Retire requests to unpin all idle contexts */
156 		intel_gt_retire_requests(to_gt(i915));
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 
397 	with_intel_runtime_pm(&i915->runtime_pm, wakeref)
398 		freed_pages += i915_gem_shrink(NULL, i915, -1UL, NULL,
399 					       I915_SHRINK_BOUND |
400 					       I915_SHRINK_UNBOUND |
401 					       I915_SHRINK_VMAPS);
402 
403 	/* We also want to clear any cached iomaps as they wrap vmap */
404 	mutex_lock(&i915->ggtt.vm.mutex);
405 	list_for_each_entry_safe(vma, next,
406 				 &i915->ggtt.vm.bound_list, vm_link) {
407 		unsigned long count = vma->node.size >> PAGE_SHIFT;
408 		struct drm_i915_gem_object *obj = vma->obj;
409 
410 		if (!vma->iomap || i915_vma_is_active(vma))
411 			continue;
412 
413 		if (!i915_gem_object_trylock(obj, NULL))
414 			continue;
415 
416 		if (__i915_vma_unbind(vma) == 0)
417 			freed_pages += count;
418 
419 		i915_gem_object_unlock(obj);
420 	}
421 	mutex_unlock(&i915->ggtt.vm.mutex);
422 
423 	*(unsigned long *)ptr += freed_pages;
424 	return NOTIFY_DONE;
425 }
426 
427 void i915_gem_driver_register__shrinker(struct drm_i915_private *i915)
428 {
429 	i915->mm.shrinker.scan_objects = i915_gem_shrinker_scan;
430 	i915->mm.shrinker.count_objects = i915_gem_shrinker_count;
431 	i915->mm.shrinker.seeks = DEFAULT_SEEKS;
432 	i915->mm.shrinker.batch = 4096;
433 	drm_WARN_ON(&i915->drm, register_shrinker(&i915->mm.shrinker));
434 
435 	i915->mm.oom_notifier.notifier_call = i915_gem_shrinker_oom;
436 	drm_WARN_ON(&i915->drm, register_oom_notifier(&i915->mm.oom_notifier));
437 
438 	i915->mm.vmap_notifier.notifier_call = i915_gem_shrinker_vmap;
439 	drm_WARN_ON(&i915->drm,
440 		    register_vmap_purge_notifier(&i915->mm.vmap_notifier));
441 }
442 
443 void i915_gem_driver_unregister__shrinker(struct drm_i915_private *i915)
444 {
445 	drm_WARN_ON(&i915->drm,
446 		    unregister_vmap_purge_notifier(&i915->mm.vmap_notifier));
447 	drm_WARN_ON(&i915->drm,
448 		    unregister_oom_notifier(&i915->mm.oom_notifier));
449 	unregister_shrinker(&i915->mm.shrinker);
450 }
451 
452 void i915_gem_shrinker_taints_mutex(struct drm_i915_private *i915,
453 				    struct mutex *mutex)
454 {
455 	if (!IS_ENABLED(CONFIG_LOCKDEP))
456 		return;
457 
458 	fs_reclaim_acquire(GFP_KERNEL);
459 
460 	mutex_acquire(&mutex->dep_map, 0, 0, _RET_IP_);
461 	mutex_release(&mutex->dep_map, _RET_IP_);
462 
463 	fs_reclaim_release(GFP_KERNEL);
464 }
465 
466 #define obj_to_i915(obj__) to_i915((obj__)->base.dev)
467 
468 /**
469  * i915_gem_object_make_unshrinkable - Hide the object from the shrinker. By
470  * default all object types that support shrinking(see IS_SHRINKABLE), will also
471  * make the object visible to the shrinker after allocating the system memory
472  * pages.
473  * @obj: The GEM object.
474  *
475  * This is typically used for special kernel internal objects that can't be
476  * easily processed by the shrinker, like if they are perma-pinned.
477  */
478 void i915_gem_object_make_unshrinkable(struct drm_i915_gem_object *obj)
479 {
480 	struct drm_i915_private *i915 = obj_to_i915(obj);
481 	unsigned long flags;
482 
483 	/*
484 	 * We can only be called while the pages are pinned or when
485 	 * the pages are released. If pinned, we should only be called
486 	 * from a single caller under controlled conditions; and on release
487 	 * only one caller may release us. Neither the two may cross.
488 	 */
489 	if (atomic_add_unless(&obj->mm.shrink_pin, 1, 0))
490 		return;
491 
492 	spin_lock_irqsave(&i915->mm.obj_lock, flags);
493 	if (!atomic_fetch_inc(&obj->mm.shrink_pin) &&
494 	    !list_empty(&obj->mm.link)) {
495 		list_del_init(&obj->mm.link);
496 		i915->mm.shrink_count--;
497 		i915->mm.shrink_memory -= obj->base.size;
498 	}
499 	spin_unlock_irqrestore(&i915->mm.obj_lock, flags);
500 }
501 
502 static void ___i915_gem_object_make_shrinkable(struct drm_i915_gem_object *obj,
503 					       struct list_head *head)
504 {
505 	struct drm_i915_private *i915 = obj_to_i915(obj);
506 	unsigned long flags;
507 
508 	if (!i915_gem_object_is_shrinkable(obj))
509 		return;
510 
511 	if (atomic_add_unless(&obj->mm.shrink_pin, -1, 1))
512 		return;
513 
514 	spin_lock_irqsave(&i915->mm.obj_lock, flags);
515 	GEM_BUG_ON(!kref_read(&obj->base.refcount));
516 	if (atomic_dec_and_test(&obj->mm.shrink_pin)) {
517 		GEM_BUG_ON(!list_empty(&obj->mm.link));
518 
519 		list_add_tail(&obj->mm.link, head);
520 		i915->mm.shrink_count++;
521 		i915->mm.shrink_memory += obj->base.size;
522 
523 	}
524 	spin_unlock_irqrestore(&i915->mm.obj_lock, flags);
525 }
526 
527 /**
528  * __i915_gem_object_make_shrinkable - Move the object to the tail of the
529  * shrinkable list. Objects on this list might be swapped out. Used with
530  * WILLNEED objects.
531  * @obj: The GEM object.
532  *
533  * DO NOT USE. This is intended to be called on very special objects that don't
534  * yet have mm.pages, but are guaranteed to have potentially reclaimable pages
535  * underneath.
536  */
537 void __i915_gem_object_make_shrinkable(struct drm_i915_gem_object *obj)
538 {
539 	___i915_gem_object_make_shrinkable(obj,
540 					   &obj_to_i915(obj)->mm.shrink_list);
541 }
542 
543 /**
544  * __i915_gem_object_make_purgeable - Move the object to the tail of the
545  * purgeable list. Objects on this list might be swapped out. Used with
546  * DONTNEED objects.
547  * @obj: The GEM object.
548  *
549  * DO NOT USE. This is intended to be called on very special objects that don't
550  * yet have mm.pages, but are guaranteed to have potentially reclaimable pages
551  * underneath.
552  */
553 void __i915_gem_object_make_purgeable(struct drm_i915_gem_object *obj)
554 {
555 	___i915_gem_object_make_shrinkable(obj,
556 					   &obj_to_i915(obj)->mm.purge_list);
557 }
558 
559 /**
560  * i915_gem_object_make_shrinkable - Move the object to the tail of the
561  * shrinkable list. Objects on this list might be swapped out. Used with
562  * WILLNEED objects.
563  * @obj: The GEM object.
564  *
565  * MUST only be called on objects which have backing pages.
566  *
567  * MUST be balanced with previous call to i915_gem_object_make_unshrinkable().
568  */
569 void i915_gem_object_make_shrinkable(struct drm_i915_gem_object *obj)
570 {
571 	GEM_BUG_ON(!i915_gem_object_has_pages(obj));
572 	__i915_gem_object_make_shrinkable(obj);
573 }
574 
575 /**
576  * i915_gem_object_make_purgeable - Move the object to the tail of the purgeable
577  * list. Used with DONTNEED objects. Unlike with shrinkable objects, the
578  * shrinker will attempt to discard the backing pages, instead of trying to swap
579  * them out.
580  * @obj: The GEM object.
581  *
582  * MUST only be called on objects which have backing pages.
583  *
584  * MUST be balanced with previous call to i915_gem_object_make_unshrinkable().
585  */
586 void i915_gem_object_make_purgeable(struct drm_i915_gem_object *obj)
587 {
588 	GEM_BUG_ON(!i915_gem_object_has_pages(obj));
589 	__i915_gem_object_make_purgeable(obj);
590 }
591