1 /*
2  * Copyright © 2008-2010 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  *
23  * Authors:
24  *    Eric Anholt <eric@anholt.net>
25  *    Chris Wilson <chris@chris-wilson.co.uuk>
26  *
27  */
28 
29 #include <drm/drmP.h>
30 #include <drm/i915_drm.h>
31 
32 #include "i915_drv.h"
33 #include "intel_drv.h"
34 #include "i915_trace.h"
35 
36 I915_SELFTEST_DECLARE(static struct igt_evict_ctl {
37 	bool fail_if_busy:1;
38 } igt_evict_ctl;)
39 
40 static bool ggtt_is_idle(struct drm_i915_private *i915)
41 {
42        struct intel_engine_cs *engine;
43        enum intel_engine_id id;
44 
45        if (i915->gt.active_requests)
46 	       return false;
47 
48        for_each_engine(engine, i915, id) {
49 	       if (!intel_engine_has_kernel_context(engine))
50 		       return false;
51        }
52 
53        return true;
54 }
55 
56 static int ggtt_flush(struct drm_i915_private *i915)
57 {
58 	int err;
59 
60 	/* Not everything in the GGTT is tracked via vma (otherwise we
61 	 * could evict as required with minimal stalling) so we are forced
62 	 * to idle the GPU and explicitly retire outstanding requests in
63 	 * the hopes that we can then remove contexts and the like only
64 	 * bound by their active reference.
65 	 */
66 	err = i915_gem_switch_to_kernel_context(i915);
67 	if (err)
68 		return err;
69 
70 	err = i915_gem_wait_for_idle(i915,
71 				     I915_WAIT_INTERRUPTIBLE |
72 				     I915_WAIT_LOCKED,
73 				     MAX_SCHEDULE_TIMEOUT);
74 	if (err)
75 		return err;
76 
77 	GEM_BUG_ON(!ggtt_is_idle(i915));
78 	return 0;
79 }
80 
81 static bool
82 mark_free(struct drm_mm_scan *scan,
83 	  struct i915_vma *vma,
84 	  unsigned int flags,
85 	  struct list_head *unwind)
86 {
87 	if (i915_vma_is_pinned(vma))
88 		return false;
89 
90 	if (flags & PIN_NONFAULT && i915_vma_has_userfault(vma))
91 		return false;
92 
93 	list_add(&vma->evict_link, unwind);
94 	return drm_mm_scan_add_block(scan, &vma->node);
95 }
96 
97 /**
98  * i915_gem_evict_something - Evict vmas to make room for binding a new one
99  * @vm: address space to evict from
100  * @min_size: size of the desired free space
101  * @alignment: alignment constraint of the desired free space
102  * @cache_level: cache_level for the desired space
103  * @start: start (inclusive) of the range from which to evict objects
104  * @end: end (exclusive) of the range from which to evict objects
105  * @flags: additional flags to control the eviction algorithm
106  *
107  * This function will try to evict vmas until a free space satisfying the
108  * requirements is found. Callers must check first whether any such hole exists
109  * already before calling this function.
110  *
111  * This function is used by the object/vma binding code.
112  *
113  * Since this function is only used to free up virtual address space it only
114  * ignores pinned vmas, and not object where the backing storage itself is
115  * pinned. Hence obj->pages_pin_count does not protect against eviction.
116  *
117  * To clarify: This is for freeing up virtual address space, not for freeing
118  * memory in e.g. the shrinker.
119  */
120 int
121 i915_gem_evict_something(struct i915_address_space *vm,
122 			 u64 min_size, u64 alignment,
123 			 unsigned cache_level,
124 			 u64 start, u64 end,
125 			 unsigned flags)
126 {
127 	struct drm_i915_private *dev_priv = vm->i915;
128 	struct drm_mm_scan scan;
129 	struct list_head eviction_list;
130 	struct list_head *phases[] = {
131 		&vm->inactive_list,
132 		&vm->active_list,
133 		NULL,
134 	}, **phase;
135 	struct i915_vma *vma, *next;
136 	struct drm_mm_node *node;
137 	enum drm_mm_insert_mode mode;
138 	int ret;
139 
140 	lockdep_assert_held(&vm->i915->drm.struct_mutex);
141 	trace_i915_gem_evict(vm, min_size, alignment, flags);
142 
143 	/*
144 	 * The goal is to evict objects and amalgamate space in LRU order.
145 	 * The oldest idle objects reside on the inactive list, which is in
146 	 * retirement order. The next objects to retire are those in flight,
147 	 * on the active list, again in retirement order.
148 	 *
149 	 * The retirement sequence is thus:
150 	 *   1. Inactive objects (already retired)
151 	 *   2. Active objects (will stall on unbinding)
152 	 *
153 	 * On each list, the oldest objects lie at the HEAD with the freshest
154 	 * object on the TAIL.
155 	 */
156 	mode = DRM_MM_INSERT_BEST;
157 	if (flags & PIN_HIGH)
158 		mode = DRM_MM_INSERT_HIGH;
159 	if (flags & PIN_MAPPABLE)
160 		mode = DRM_MM_INSERT_LOW;
161 	drm_mm_scan_init_with_range(&scan, &vm->mm,
162 				    min_size, alignment, cache_level,
163 				    start, end, mode);
164 
165 	/*
166 	 * Retire before we search the active list. Although we have
167 	 * reasonable accuracy in our retirement lists, we may have
168 	 * a stray pin (preventing eviction) that can only be resolved by
169 	 * retiring.
170 	 */
171 	if (!(flags & PIN_NONBLOCK))
172 		i915_retire_requests(dev_priv);
173 	else
174 		phases[1] = NULL;
175 
176 search_again:
177 	INIT_LIST_HEAD(&eviction_list);
178 	phase = phases;
179 	do {
180 		list_for_each_entry(vma, *phase, vm_link)
181 			if (mark_free(&scan, vma, flags, &eviction_list))
182 				goto found;
183 	} while (*++phase);
184 
185 	/* Nothing found, clean up and bail out! */
186 	list_for_each_entry_safe(vma, next, &eviction_list, evict_link) {
187 		ret = drm_mm_scan_remove_block(&scan, &vma->node);
188 		BUG_ON(ret);
189 	}
190 
191 	/*
192 	 * Can we unpin some objects such as idle hw contents,
193 	 * or pending flips? But since only the GGTT has global entries
194 	 * such as scanouts, rinbuffers and contexts, we can skip the
195 	 * purge when inspecting per-process local address spaces.
196 	 */
197 	if (!i915_is_ggtt(vm) || flags & PIN_NONBLOCK)
198 		return -ENOSPC;
199 
200 	/*
201 	 * Not everything in the GGTT is tracked via VMA using
202 	 * i915_vma_move_to_active(), otherwise we could evict as required
203 	 * with minimal stalling. Instead we are forced to idle the GPU and
204 	 * explicitly retire outstanding requests which will then remove
205 	 * the pinning for active objects such as contexts and ring,
206 	 * enabling us to evict them on the next iteration.
207 	 *
208 	 * To ensure that all user contexts are evictable, we perform
209 	 * a switch to the perma-pinned kernel context. This all also gives
210 	 * us a termination condition, when the last retired context is
211 	 * the kernel's there is no more we can evict.
212 	 */
213 	if (!ggtt_is_idle(dev_priv)) {
214 		if (I915_SELFTEST_ONLY(igt_evict_ctl.fail_if_busy))
215 			return -EBUSY;
216 
217 		ret = ggtt_flush(dev_priv);
218 		if (ret)
219 			return ret;
220 
221 		cond_resched();
222 		goto search_again;
223 	}
224 
225 	/*
226 	 * If we still have pending pageflip completions, drop
227 	 * back to userspace to give our workqueues time to
228 	 * acquire our locks and unpin the old scanouts.
229 	 */
230 	return intel_has_pending_fb_unpin(dev_priv) ? -EAGAIN : -ENOSPC;
231 
232 found:
233 	/* drm_mm doesn't allow any other other operations while
234 	 * scanning, therefore store to-be-evicted objects on a
235 	 * temporary list and take a reference for all before
236 	 * calling unbind (which may remove the active reference
237 	 * of any of our objects, thus corrupting the list).
238 	 */
239 	list_for_each_entry_safe(vma, next, &eviction_list, evict_link) {
240 		if (drm_mm_scan_remove_block(&scan, &vma->node))
241 			__i915_vma_pin(vma);
242 		else
243 			list_del(&vma->evict_link);
244 	}
245 
246 	/* Unbinding will emit any required flushes */
247 	ret = 0;
248 	list_for_each_entry_safe(vma, next, &eviction_list, evict_link) {
249 		__i915_vma_unpin(vma);
250 		if (ret == 0)
251 			ret = i915_vma_unbind(vma);
252 	}
253 
254 	while (ret == 0 && (node = drm_mm_scan_color_evict(&scan))) {
255 		vma = container_of(node, struct i915_vma, node);
256 		ret = i915_vma_unbind(vma);
257 	}
258 
259 	return ret;
260 }
261 
262 /**
263  * i915_gem_evict_for_vma - Evict vmas to make room for binding a new one
264  * @vm: address space to evict from
265  * @target: range (and color) to evict for
266  * @flags: additional flags to control the eviction algorithm
267  *
268  * This function will try to evict vmas that overlap the target node.
269  *
270  * To clarify: This is for freeing up virtual address space, not for freeing
271  * memory in e.g. the shrinker.
272  */
273 int i915_gem_evict_for_node(struct i915_address_space *vm,
274 			    struct drm_mm_node *target,
275 			    unsigned int flags)
276 {
277 	LIST_HEAD(eviction_list);
278 	struct drm_mm_node *node;
279 	u64 start = target->start;
280 	u64 end = start + target->size;
281 	struct i915_vma *vma, *next;
282 	bool check_color;
283 	int ret = 0;
284 
285 	lockdep_assert_held(&vm->i915->drm.struct_mutex);
286 	GEM_BUG_ON(!IS_ALIGNED(start, I915_GTT_PAGE_SIZE));
287 	GEM_BUG_ON(!IS_ALIGNED(end, I915_GTT_PAGE_SIZE));
288 
289 	trace_i915_gem_evict_node(vm, target, flags);
290 
291 	/* Retire before we search the active list. Although we have
292 	 * reasonable accuracy in our retirement lists, we may have
293 	 * a stray pin (preventing eviction) that can only be resolved by
294 	 * retiring.
295 	 */
296 	if (!(flags & PIN_NONBLOCK))
297 		i915_retire_requests(vm->i915);
298 
299 	check_color = vm->mm.color_adjust;
300 	if (check_color) {
301 		/* Expand search to cover neighbouring guard pages (or lack!) */
302 		if (start)
303 			start -= I915_GTT_PAGE_SIZE;
304 
305 		/* Always look at the page afterwards to avoid the end-of-GTT */
306 		end += I915_GTT_PAGE_SIZE;
307 	}
308 	GEM_BUG_ON(start >= end);
309 
310 	drm_mm_for_each_node_in_range(node, &vm->mm, start, end) {
311 		/* If we find any non-objects (!vma), we cannot evict them */
312 		if (node->color == I915_COLOR_UNEVICTABLE) {
313 			ret = -ENOSPC;
314 			break;
315 		}
316 
317 		GEM_BUG_ON(!node->allocated);
318 		vma = container_of(node, typeof(*vma), node);
319 
320 		/* If we are using coloring to insert guard pages between
321 		 * different cache domains within the address space, we have
322 		 * to check whether the objects on either side of our range
323 		 * abutt and conflict. If they are in conflict, then we evict
324 		 * those as well to make room for our guard pages.
325 		 */
326 		if (check_color) {
327 			if (node->start + node->size == target->start) {
328 				if (node->color == target->color)
329 					continue;
330 			}
331 			if (node->start == target->start + target->size) {
332 				if (node->color == target->color)
333 					continue;
334 			}
335 		}
336 
337 		if (flags & PIN_NONBLOCK &&
338 		    (i915_vma_is_pinned(vma) || i915_vma_is_active(vma))) {
339 			ret = -ENOSPC;
340 			break;
341 		}
342 
343 		if (flags & PIN_NONFAULT && i915_vma_has_userfault(vma)) {
344 			ret = -ENOSPC;
345 			break;
346 		}
347 
348 		/* Overlap of objects in the same batch? */
349 		if (i915_vma_is_pinned(vma)) {
350 			ret = -ENOSPC;
351 			if (vma->exec_flags &&
352 			    *vma->exec_flags & EXEC_OBJECT_PINNED)
353 				ret = -EINVAL;
354 			break;
355 		}
356 
357 		/* Never show fear in the face of dragons!
358 		 *
359 		 * We cannot directly remove this node from within this
360 		 * iterator and as with i915_gem_evict_something() we employ
361 		 * the vma pin_count in order to prevent the action of
362 		 * unbinding one vma from freeing (by dropping its active
363 		 * reference) another in our eviction list.
364 		 */
365 		__i915_vma_pin(vma);
366 		list_add(&vma->evict_link, &eviction_list);
367 	}
368 
369 	list_for_each_entry_safe(vma, next, &eviction_list, evict_link) {
370 		__i915_vma_unpin(vma);
371 		if (ret == 0)
372 			ret = i915_vma_unbind(vma);
373 	}
374 
375 	return ret;
376 }
377 
378 /**
379  * i915_gem_evict_vm - Evict all idle vmas from a vm
380  * @vm: Address space to cleanse
381  *
382  * This function evicts all vmas from a vm.
383  *
384  * This is used by the execbuf code as a last-ditch effort to defragment the
385  * address space.
386  *
387  * To clarify: This is for freeing up virtual address space, not for freeing
388  * memory in e.g. the shrinker.
389  */
390 int i915_gem_evict_vm(struct i915_address_space *vm)
391 {
392 	struct list_head *phases[] = {
393 		&vm->inactive_list,
394 		&vm->active_list,
395 		NULL
396 	}, **phase;
397 	struct list_head eviction_list;
398 	struct i915_vma *vma, *next;
399 	int ret;
400 
401 	lockdep_assert_held(&vm->i915->drm.struct_mutex);
402 	trace_i915_gem_evict_vm(vm);
403 
404 	/* Switch back to the default context in order to unpin
405 	 * the existing context objects. However, such objects only
406 	 * pin themselves inside the global GTT and performing the
407 	 * switch otherwise is ineffective.
408 	 */
409 	if (i915_is_ggtt(vm)) {
410 		ret = ggtt_flush(vm->i915);
411 		if (ret)
412 			return ret;
413 	}
414 
415 	INIT_LIST_HEAD(&eviction_list);
416 	phase = phases;
417 	do {
418 		list_for_each_entry(vma, *phase, vm_link) {
419 			if (i915_vma_is_pinned(vma))
420 				continue;
421 
422 			__i915_vma_pin(vma);
423 			list_add(&vma->evict_link, &eviction_list);
424 		}
425 	} while (*++phase);
426 
427 	ret = 0;
428 	list_for_each_entry_safe(vma, next, &eviction_list, evict_link) {
429 		__i915_vma_unpin(vma);
430 		if (ret == 0)
431 			ret = i915_vma_unbind(vma);
432 	}
433 	return ret;
434 }
435 
436 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
437 #include "selftests/i915_gem_evict.c"
438 #endif
439