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