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 "i915_trace.h"
17 
18 static bool swap_available(void)
19 {
20 	return get_nr_swap_pages() > 0;
21 }
22 
23 static bool can_release_pages(struct drm_i915_gem_object *obj)
24 {
25 	/* Consider only shrinkable ojects. */
26 	if (!i915_gem_object_is_shrinkable(obj))
27 		return false;
28 
29 	/*
30 	 * Only report true if by unbinding the object and putting its pages
31 	 * we can actually make forward progress towards freeing physical
32 	 * pages.
33 	 *
34 	 * If the pages are pinned for any other reason than being bound
35 	 * to the GPU, simply unbinding from the GPU is not going to succeed
36 	 * in releasing our pin count on the pages themselves.
37 	 */
38 	if (atomic_read(&obj->mm.pages_pin_count) > atomic_read(&obj->bind_count))
39 		return false;
40 
41 	/*
42 	 * We can only return physical pages to the system if we can either
43 	 * discard the contents (because the user has marked them as being
44 	 * purgeable) or if we can move their contents out to swap.
45 	 */
46 	return swap_available() || obj->mm.madv == I915_MADV_DONTNEED;
47 }
48 
49 static bool unsafe_drop_pages(struct drm_i915_gem_object *obj,
50 			      unsigned long shrink)
51 {
52 	unsigned long flags;
53 
54 	flags = 0;
55 	if (shrink & I915_SHRINK_ACTIVE)
56 		flags = I915_GEM_OBJECT_UNBIND_ACTIVE;
57 
58 	if (i915_gem_object_unbind(obj, flags) == 0)
59 		__i915_gem_object_put_pages(obj);
60 
61 	return !i915_gem_object_has_pages(obj);
62 }
63 
64 static void try_to_writeback(struct drm_i915_gem_object *obj,
65 			     unsigned int flags)
66 {
67 	switch (obj->mm.madv) {
68 	case I915_MADV_DONTNEED:
69 		i915_gem_object_truncate(obj);
70 	case __I915_MADV_PURGED:
71 		return;
72 	}
73 
74 	if (flags & I915_SHRINK_WRITEBACK)
75 		i915_gem_object_writeback(obj);
76 }
77 
78 /**
79  * i915_gem_shrink - Shrink buffer object caches
80  * @i915: i915 device
81  * @target: amount of memory to make available, in pages
82  * @nr_scanned: optional output for number of pages scanned (incremental)
83  * @shrink: control flags for selecting cache types
84  *
85  * This function is the main interface to the shrinker. It will try to release
86  * up to @target pages of main memory backing storage from buffer objects.
87  * Selection of the specific caches can be done with @flags. This is e.g. useful
88  * when purgeable objects should be removed from caches preferentially.
89  *
90  * Note that it's not guaranteed that released amount is actually available as
91  * free system memory - the pages might still be in-used to due to other reasons
92  * (like cpu mmaps) or the mm core has reused them before we could grab them.
93  * Therefore code that needs to explicitly shrink buffer objects caches (e.g. to
94  * avoid deadlocks in memory reclaim) must fall back to i915_gem_shrink_all().
95  *
96  * Also note that any kind of pinning (both per-vma address space pins and
97  * backing storage pins at the buffer object level) result in the shrinker code
98  * having to skip the object.
99  *
100  * Returns:
101  * The number of pages of backing storage actually released.
102  */
103 unsigned long
104 i915_gem_shrink(struct drm_i915_private *i915,
105 		unsigned long target,
106 		unsigned long *nr_scanned,
107 		unsigned int shrink)
108 {
109 	const struct {
110 		struct list_head *list;
111 		unsigned int bit;
112 	} phases[] = {
113 		{ &i915->mm.purge_list, ~0u },
114 		{
115 			&i915->mm.shrink_list,
116 			I915_SHRINK_BOUND | I915_SHRINK_UNBOUND
117 		},
118 		{ NULL, 0 },
119 	}, *phase;
120 	intel_wakeref_t wakeref = 0;
121 	unsigned long count = 0;
122 	unsigned long scanned = 0;
123 
124 	/*
125 	 * When shrinking the active list, we should also consider active
126 	 * contexts. Active contexts are pinned until they are retired, and
127 	 * so can not be simply unbound to retire and unpin their pages. To
128 	 * shrink the contexts, we must wait until the gpu is idle and
129 	 * completed its switch to the kernel context. In short, we do
130 	 * not have a good mechanism for idling a specific context.
131 	 */
132 
133 	trace_i915_gem_shrink(i915, target, shrink);
134 
135 	/*
136 	 * Unbinding of objects will require HW access; Let us not wake the
137 	 * device just to recover a little memory. If absolutely necessary,
138 	 * we will force the wake during oom-notifier.
139 	 */
140 	if (shrink & I915_SHRINK_BOUND) {
141 		wakeref = intel_runtime_pm_get_if_in_use(&i915->runtime_pm);
142 		if (!wakeref)
143 			shrink &= ~I915_SHRINK_BOUND;
144 	}
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 (!(shrink & I915_SHRINK_BOUND) &&
198 			    atomic_read(&obj->bind_count))
199 				continue;
200 
201 			if (!can_release_pages(obj))
202 				continue;
203 
204 			if (!kref_get_unless_zero(&obj->base.refcount))
205 				continue;
206 
207 			spin_unlock_irqrestore(&i915->mm.obj_lock, flags);
208 
209 			if (unsafe_drop_pages(obj, shrink)) {
210 				/* May arrive from get_pages on another bo */
211 				mutex_lock(&obj->mm.lock);
212 				if (!i915_gem_object_has_pages(obj)) {
213 					try_to_writeback(obj, shrink);
214 					count += obj->base.size >> PAGE_SHIFT;
215 				}
216 				mutex_unlock(&obj->mm.lock);
217 			}
218 
219 			scanned += obj->base.size >> PAGE_SHIFT;
220 			i915_gem_object_put(obj);
221 
222 			spin_lock_irqsave(&i915->mm.obj_lock, flags);
223 		}
224 		list_splice_tail(&still_in_list, phase->list);
225 		spin_unlock_irqrestore(&i915->mm.obj_lock, flags);
226 	}
227 
228 	if (shrink & I915_SHRINK_BOUND)
229 		intel_runtime_pm_put(&i915->runtime_pm, wakeref);
230 
231 	if (nr_scanned)
232 		*nr_scanned += scanned;
233 	return count;
234 }
235 
236 /**
237  * i915_gem_shrink_all - Shrink buffer object caches completely
238  * @i915: i915 device
239  *
240  * This is a simple wraper around i915_gem_shrink() to aggressively shrink all
241  * caches completely. It also first waits for and retires all outstanding
242  * requests to also be able to release backing storage for active objects.
243  *
244  * This should only be used in code to intentionally quiescent the gpu or as a
245  * last-ditch effort when memory seems to have run out.
246  *
247  * Returns:
248  * The number of pages of backing storage actually released.
249  */
250 unsigned long i915_gem_shrink_all(struct drm_i915_private *i915)
251 {
252 	intel_wakeref_t wakeref;
253 	unsigned long freed = 0;
254 
255 	with_intel_runtime_pm(&i915->runtime_pm, wakeref) {
256 		freed = i915_gem_shrink(i915, -1UL, NULL,
257 					I915_SHRINK_BOUND |
258 					I915_SHRINK_UNBOUND);
259 	}
260 
261 	return freed;
262 }
263 
264 static unsigned long
265 i915_gem_shrinker_count(struct shrinker *shrinker, struct shrink_control *sc)
266 {
267 	struct drm_i915_private *i915 =
268 		container_of(shrinker, struct drm_i915_private, mm.shrinker);
269 	unsigned long num_objects;
270 	unsigned long count;
271 
272 	count = READ_ONCE(i915->mm.shrink_memory) >> PAGE_SHIFT;
273 	num_objects = READ_ONCE(i915->mm.shrink_count);
274 
275 	/*
276 	 * Update our preferred vmscan batch size for the next pass.
277 	 * Our rough guess for an effective batch size is roughly 2
278 	 * available GEM objects worth of pages. That is we don't want
279 	 * the shrinker to fire, until it is worth the cost of freeing an
280 	 * entire GEM object.
281 	 */
282 	if (num_objects) {
283 		unsigned long avg = 2 * count / num_objects;
284 
285 		i915->mm.shrinker.batch =
286 			max((i915->mm.shrinker.batch + avg) >> 1,
287 			    128ul /* default SHRINK_BATCH */);
288 	}
289 
290 	return count;
291 }
292 
293 static unsigned long
294 i915_gem_shrinker_scan(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 freed;
299 
300 	sc->nr_scanned = 0;
301 
302 	freed = i915_gem_shrink(i915,
303 				sc->nr_to_scan,
304 				&sc->nr_scanned,
305 				I915_SHRINK_BOUND |
306 				I915_SHRINK_UNBOUND);
307 	if (sc->nr_scanned < sc->nr_to_scan && current_is_kswapd()) {
308 		intel_wakeref_t wakeref;
309 
310 		with_intel_runtime_pm(&i915->runtime_pm, wakeref) {
311 			freed += i915_gem_shrink(i915,
312 						 sc->nr_to_scan - sc->nr_scanned,
313 						 &sc->nr_scanned,
314 						 I915_SHRINK_ACTIVE |
315 						 I915_SHRINK_BOUND |
316 						 I915_SHRINK_UNBOUND |
317 						 I915_SHRINK_WRITEBACK);
318 		}
319 	}
320 
321 	return sc->nr_scanned ? freed : SHRINK_STOP;
322 }
323 
324 static int
325 i915_gem_shrinker_oom(struct notifier_block *nb, unsigned long event, void *ptr)
326 {
327 	struct drm_i915_private *i915 =
328 		container_of(nb, struct drm_i915_private, mm.oom_notifier);
329 	struct drm_i915_gem_object *obj;
330 	unsigned long unevictable, available, freed_pages;
331 	intel_wakeref_t wakeref;
332 	unsigned long flags;
333 
334 	freed_pages = 0;
335 	with_intel_runtime_pm(&i915->runtime_pm, wakeref)
336 		freed_pages += i915_gem_shrink(i915, -1UL, NULL,
337 					       I915_SHRINK_BOUND |
338 					       I915_SHRINK_UNBOUND |
339 					       I915_SHRINK_WRITEBACK);
340 
341 	/* Because we may be allocating inside our own driver, we cannot
342 	 * assert that there are no objects with pinned pages that are not
343 	 * being pointed to by hardware.
344 	 */
345 	available = unevictable = 0;
346 	spin_lock_irqsave(&i915->mm.obj_lock, flags);
347 	list_for_each_entry(obj, &i915->mm.shrink_list, mm.link) {
348 		if (!can_release_pages(obj))
349 			unevictable += obj->base.size >> PAGE_SHIFT;
350 		else
351 			available += obj->base.size >> PAGE_SHIFT;
352 	}
353 	spin_unlock_irqrestore(&i915->mm.obj_lock, flags);
354 
355 	if (freed_pages || available)
356 		pr_info("Purging GPU memory, %lu pages freed, "
357 			"%lu pages still pinned, %lu pages left available.\n",
358 			freed_pages, unevictable, available);
359 
360 	*(unsigned long *)ptr += freed_pages;
361 	return NOTIFY_DONE;
362 }
363 
364 static int
365 i915_gem_shrinker_vmap(struct notifier_block *nb, unsigned long event, void *ptr)
366 {
367 	struct drm_i915_private *i915 =
368 		container_of(nb, struct drm_i915_private, mm.vmap_notifier);
369 	struct i915_vma *vma, *next;
370 	unsigned long freed_pages = 0;
371 	intel_wakeref_t wakeref;
372 
373 	with_intel_runtime_pm(&i915->runtime_pm, wakeref)
374 		freed_pages += i915_gem_shrink(i915, -1UL, NULL,
375 					       I915_SHRINK_BOUND |
376 					       I915_SHRINK_UNBOUND |
377 					       I915_SHRINK_VMAPS);
378 
379 	/* We also want to clear any cached iomaps as they wrap vmap */
380 	mutex_lock(&i915->ggtt.vm.mutex);
381 	list_for_each_entry_safe(vma, next,
382 				 &i915->ggtt.vm.bound_list, vm_link) {
383 		unsigned long count = vma->node.size >> PAGE_SHIFT;
384 
385 		if (!vma->iomap || i915_vma_is_active(vma))
386 			continue;
387 
388 		if (__i915_vma_unbind(vma) == 0)
389 			freed_pages += count;
390 	}
391 	mutex_unlock(&i915->ggtt.vm.mutex);
392 
393 	*(unsigned long *)ptr += freed_pages;
394 	return NOTIFY_DONE;
395 }
396 
397 void i915_gem_driver_register__shrinker(struct drm_i915_private *i915)
398 {
399 	i915->mm.shrinker.scan_objects = i915_gem_shrinker_scan;
400 	i915->mm.shrinker.count_objects = i915_gem_shrinker_count;
401 	i915->mm.shrinker.seeks = DEFAULT_SEEKS;
402 	i915->mm.shrinker.batch = 4096;
403 	drm_WARN_ON(&i915->drm, register_shrinker(&i915->mm.shrinker));
404 
405 	i915->mm.oom_notifier.notifier_call = i915_gem_shrinker_oom;
406 	drm_WARN_ON(&i915->drm, register_oom_notifier(&i915->mm.oom_notifier));
407 
408 	i915->mm.vmap_notifier.notifier_call = i915_gem_shrinker_vmap;
409 	drm_WARN_ON(&i915->drm,
410 		    register_vmap_purge_notifier(&i915->mm.vmap_notifier));
411 }
412 
413 void i915_gem_driver_unregister__shrinker(struct drm_i915_private *i915)
414 {
415 	drm_WARN_ON(&i915->drm,
416 		    unregister_vmap_purge_notifier(&i915->mm.vmap_notifier));
417 	drm_WARN_ON(&i915->drm,
418 		    unregister_oom_notifier(&i915->mm.oom_notifier));
419 	unregister_shrinker(&i915->mm.shrinker);
420 }
421 
422 void i915_gem_shrinker_taints_mutex(struct drm_i915_private *i915,
423 				    struct mutex *mutex)
424 {
425 	bool unlock = false;
426 
427 	if (!IS_ENABLED(CONFIG_LOCKDEP))
428 		return;
429 
430 	if (!lockdep_is_held_type(&i915->drm.struct_mutex, -1)) {
431 		mutex_acquire(&i915->drm.struct_mutex.dep_map,
432 			      I915_MM_NORMAL, 0, _RET_IP_);
433 		unlock = true;
434 	}
435 
436 	fs_reclaim_acquire(GFP_KERNEL);
437 
438 	mutex_acquire(&mutex->dep_map, 0, 0, _RET_IP_);
439 	mutex_release(&mutex->dep_map, _RET_IP_);
440 
441 	fs_reclaim_release(GFP_KERNEL);
442 
443 	if (unlock)
444 		mutex_release(&i915->drm.struct_mutex.dep_map, _RET_IP_);
445 }
446 
447 #define obj_to_i915(obj__) to_i915((obj__)->base.dev)
448 
449 void i915_gem_object_make_unshrinkable(struct drm_i915_gem_object *obj)
450 {
451 	struct drm_i915_private *i915 = obj_to_i915(obj);
452 	unsigned long flags;
453 
454 	/*
455 	 * We can only be called while the pages are pinned or when
456 	 * the pages are released. If pinned, we should only be called
457 	 * from a single caller under controlled conditions; and on release
458 	 * only one caller may release us. Neither the two may cross.
459 	 */
460 	if (atomic_add_unless(&obj->mm.shrink_pin, 1, 0))
461 		return;
462 
463 	spin_lock_irqsave(&i915->mm.obj_lock, flags);
464 	if (!atomic_fetch_inc(&obj->mm.shrink_pin) &&
465 	    !list_empty(&obj->mm.link)) {
466 		list_del_init(&obj->mm.link);
467 		i915->mm.shrink_count--;
468 		i915->mm.shrink_memory -= obj->base.size;
469 	}
470 	spin_unlock_irqrestore(&i915->mm.obj_lock, flags);
471 }
472 
473 static void __i915_gem_object_make_shrinkable(struct drm_i915_gem_object *obj,
474 					      struct list_head *head)
475 {
476 	struct drm_i915_private *i915 = obj_to_i915(obj);
477 	unsigned long flags;
478 
479 	GEM_BUG_ON(!i915_gem_object_has_pages(obj));
480 	if (!i915_gem_object_is_shrinkable(obj))
481 		return;
482 
483 	if (atomic_add_unless(&obj->mm.shrink_pin, -1, 1))
484 		return;
485 
486 	spin_lock_irqsave(&i915->mm.obj_lock, flags);
487 	GEM_BUG_ON(!kref_read(&obj->base.refcount));
488 	if (atomic_dec_and_test(&obj->mm.shrink_pin)) {
489 		GEM_BUG_ON(!list_empty(&obj->mm.link));
490 
491 		list_add_tail(&obj->mm.link, head);
492 		i915->mm.shrink_count++;
493 		i915->mm.shrink_memory += obj->base.size;
494 
495 	}
496 	spin_unlock_irqrestore(&i915->mm.obj_lock, flags);
497 }
498 
499 void i915_gem_object_make_shrinkable(struct drm_i915_gem_object *obj)
500 {
501 	__i915_gem_object_make_shrinkable(obj,
502 					  &obj_to_i915(obj)->mm.shrink_list);
503 }
504 
505 void i915_gem_object_make_purgeable(struct drm_i915_gem_object *obj)
506 {
507 	__i915_gem_object_make_shrinkable(obj,
508 					  &obj_to_i915(obj)->mm.purge_list);
509 }
510