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