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