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