xref: /linux/drivers/gpu/drm/i915/i915_active.c (revision 889600e21e3be388a6817c2a0dac0411df860751)
1 /*
2  * SPDX-License-Identifier: MIT
3  *
4  * Copyright © 2019 Intel Corporation
5  */
6 
7 #include <linux/debugobjects.h>
8 
9 #include "gt/intel_context.h"
10 #include "gt/intel_engine_heartbeat.h"
11 #include "gt/intel_engine_pm.h"
12 #include "gt/intel_ring.h"
13 
14 #include "i915_drv.h"
15 #include "i915_active.h"
16 
17 /*
18  * Active refs memory management
19  *
20  * To be more economical with memory, we reap all the i915_active trees as
21  * they idle (when we know the active requests are inactive) and allocate the
22  * nodes from a local slab cache to hopefully reduce the fragmentation.
23  */
24 static struct kmem_cache *slab_cache;
25 
26 struct active_node {
27 	struct rb_node node;
28 	struct i915_active_fence base;
29 	struct i915_active *ref;
30 	u64 timeline;
31 };
32 
33 #define fetch_node(x) rb_entry(READ_ONCE(x), typeof(struct active_node), node)
34 
35 static inline struct active_node *
node_from_active(struct i915_active_fence * active)36 node_from_active(struct i915_active_fence *active)
37 {
38 	return container_of(active, struct active_node, base);
39 }
40 
41 #define take_preallocated_barriers(x) llist_del_all(&(x)->preallocated_barriers)
42 
is_barrier(const struct i915_active_fence * active)43 static inline bool is_barrier(const struct i915_active_fence *active)
44 {
45 	return IS_ERR(rcu_access_pointer(active->fence));
46 }
47 
barrier_to_ll(struct active_node * node)48 static inline struct llist_node *barrier_to_ll(struct active_node *node)
49 {
50 	GEM_BUG_ON(!is_barrier(&node->base));
51 	return (struct llist_node *)&node->base.cb.node;
52 }
53 
54 static inline struct intel_engine_cs *
__barrier_to_engine(struct active_node * node)55 __barrier_to_engine(struct active_node *node)
56 {
57 	return (struct intel_engine_cs *)READ_ONCE(node->base.cb.node.prev);
58 }
59 
60 static inline struct intel_engine_cs *
barrier_to_engine(struct active_node * node)61 barrier_to_engine(struct active_node *node)
62 {
63 	GEM_BUG_ON(!is_barrier(&node->base));
64 	return __barrier_to_engine(node);
65 }
66 
barrier_from_ll(struct llist_node * x)67 static inline struct active_node *barrier_from_ll(struct llist_node *x)
68 {
69 	return container_of((struct list_head *)x,
70 			    struct active_node, base.cb.node);
71 }
72 
73 #if IS_ENABLED(CONFIG_DRM_I915_DEBUG_GEM) && IS_ENABLED(CONFIG_DEBUG_OBJECTS)
74 
active_debug_hint(void * addr)75 static void *active_debug_hint(void *addr)
76 {
77 	struct i915_active *ref = addr;
78 
79 	return (void *)ref->active ?: (void *)ref->retire ?: (void *)ref;
80 }
81 
82 static const struct debug_obj_descr active_debug_desc = {
83 	.name = "i915_active",
84 	.debug_hint = active_debug_hint,
85 };
86 
debug_active_init(struct i915_active * ref)87 static void debug_active_init(struct i915_active *ref)
88 {
89 	debug_object_init(ref, &active_debug_desc);
90 }
91 
debug_active_activate(struct i915_active * ref)92 static void debug_active_activate(struct i915_active *ref)
93 {
94 	lockdep_assert_held(&ref->tree_lock);
95 	debug_object_activate(ref, &active_debug_desc);
96 }
97 
debug_active_deactivate(struct i915_active * ref)98 static void debug_active_deactivate(struct i915_active *ref)
99 {
100 	lockdep_assert_held(&ref->tree_lock);
101 	if (!atomic_read(&ref->count)) /* after the last dec */
102 		debug_object_deactivate(ref, &active_debug_desc);
103 }
104 
debug_active_fini(struct i915_active * ref)105 static void debug_active_fini(struct i915_active *ref)
106 {
107 	debug_object_free(ref, &active_debug_desc);
108 }
109 
debug_active_assert(struct i915_active * ref)110 static void debug_active_assert(struct i915_active *ref)
111 {
112 	debug_object_assert_init(ref, &active_debug_desc);
113 }
114 
115 #else
116 
debug_active_init(struct i915_active * ref)117 static inline void debug_active_init(struct i915_active *ref) { }
debug_active_activate(struct i915_active * ref)118 static inline void debug_active_activate(struct i915_active *ref) { }
debug_active_deactivate(struct i915_active * ref)119 static inline void debug_active_deactivate(struct i915_active *ref) { }
debug_active_fini(struct i915_active * ref)120 static inline void debug_active_fini(struct i915_active *ref) { }
debug_active_assert(struct i915_active * ref)121 static inline void debug_active_assert(struct i915_active *ref) { }
122 
123 #endif
124 
125 static void
__active_retire(struct i915_active * ref)126 __active_retire(struct i915_active *ref)
127 {
128 	struct rb_root root = RB_ROOT;
129 	struct active_node *it, *n;
130 	unsigned long flags;
131 
132 	GEM_BUG_ON(i915_active_is_idle(ref));
133 
134 	/* return the unused nodes to our slabcache -- flushing the allocator */
135 	if (!atomic_dec_and_lock_irqsave(&ref->count, &ref->tree_lock, flags))
136 		return;
137 
138 	GEM_BUG_ON(rcu_access_pointer(ref->excl.fence));
139 	debug_active_deactivate(ref);
140 
141 	/* Even if we have not used the cache, we may still have a barrier */
142 	if (!ref->cache)
143 		ref->cache = fetch_node(ref->tree.rb_node);
144 
145 	/* Keep the MRU cached node for reuse */
146 	if (ref->cache) {
147 		/* Discard all other nodes in the tree */
148 		rb_erase(&ref->cache->node, &ref->tree);
149 		root = ref->tree;
150 
151 		/* Rebuild the tree with only the cached node */
152 		rb_link_node(&ref->cache->node, NULL, &ref->tree.rb_node);
153 		rb_insert_color(&ref->cache->node, &ref->tree);
154 		GEM_BUG_ON(ref->tree.rb_node != &ref->cache->node);
155 
156 		/* Make the cached node available for reuse with any timeline */
157 		ref->cache->timeline = 0; /* needs cmpxchg(u64) */
158 	}
159 
160 	spin_unlock_irqrestore(&ref->tree_lock, flags);
161 
162 	/* After the final retire, the entire struct may be freed */
163 	if (ref->retire)
164 		ref->retire(ref);
165 
166 	/* ... except if you wait on it, you must manage your own references! */
167 	wake_up_var(ref);
168 
169 	/* Finally free the discarded timeline tree  */
170 	rbtree_postorder_for_each_entry_safe(it, n, &root, node) {
171 		GEM_BUG_ON(i915_active_fence_isset(&it->base));
172 		kmem_cache_free(slab_cache, it);
173 	}
174 }
175 
176 static void
active_work(struct work_struct * wrk)177 active_work(struct work_struct *wrk)
178 {
179 	struct i915_active *ref = container_of(wrk, typeof(*ref), work);
180 
181 	GEM_BUG_ON(!atomic_read(&ref->count));
182 	if (atomic_add_unless(&ref->count, -1, 1))
183 		return;
184 
185 	__active_retire(ref);
186 }
187 
188 static void
active_retire(struct i915_active * ref)189 active_retire(struct i915_active *ref)
190 {
191 	GEM_BUG_ON(!atomic_read(&ref->count));
192 	if (atomic_add_unless(&ref->count, -1, 1))
193 		return;
194 
195 	if (ref->flags & I915_ACTIVE_RETIRE_SLEEPS) {
196 		queue_work(system_dfl_wq, &ref->work);
197 		return;
198 	}
199 
200 	__active_retire(ref);
201 }
202 
203 static inline struct dma_fence **
__active_fence_slot(struct i915_active_fence * active)204 __active_fence_slot(struct i915_active_fence *active)
205 {
206 	return (struct dma_fence ** __force)&active->fence;
207 }
208 
209 static inline bool
active_fence_cb(struct dma_fence * fence,struct dma_fence_cb * cb)210 active_fence_cb(struct dma_fence *fence, struct dma_fence_cb *cb)
211 {
212 	struct i915_active_fence *active =
213 		container_of(cb, typeof(*active), cb);
214 
215 	return try_cmpxchg(__active_fence_slot(active), &fence, NULL);
216 }
217 
218 static void
node_retire(struct dma_fence * fence,struct dma_fence_cb * cb)219 node_retire(struct dma_fence *fence, struct dma_fence_cb *cb)
220 {
221 	if (active_fence_cb(fence, cb))
222 		active_retire(container_of(cb, struct active_node, base.cb)->ref);
223 }
224 
225 static void
excl_retire(struct dma_fence * fence,struct dma_fence_cb * cb)226 excl_retire(struct dma_fence *fence, struct dma_fence_cb *cb)
227 {
228 	if (active_fence_cb(fence, cb))
229 		active_retire(container_of(cb, struct i915_active, excl.cb));
230 }
231 
__active_lookup(struct i915_active * ref,u64 idx)232 static struct active_node *__active_lookup(struct i915_active *ref, u64 idx)
233 {
234 	struct active_node *it;
235 
236 	GEM_BUG_ON(idx == 0); /* 0 is the unordered timeline, rsvd for cache */
237 
238 	/*
239 	 * We track the most recently used timeline to skip a rbtree search
240 	 * for the common case, under typical loads we never need the rbtree
241 	 * at all. We can reuse the last slot if it is empty, that is
242 	 * after the previous activity has been retired, or if it matches the
243 	 * current timeline.
244 	 */
245 	it = READ_ONCE(ref->cache);
246 	if (it) {
247 		u64 cached = READ_ONCE(it->timeline);
248 
249 		/* Once claimed, this slot will only belong to this idx */
250 		if (cached == idx)
251 			return it;
252 
253 		/*
254 		 * An unclaimed cache [.timeline=0] can only be claimed once.
255 		 *
256 		 * If the value is already non-zero, some other thread has
257 		 * claimed the cache and we know that is does not match our
258 		 * idx. If, and only if, the timeline is currently zero is it
259 		 * worth competing to claim it atomically for ourselves (for
260 		 * only the winner of that race will cmpxchg succeed).
261 		 */
262 		if (!cached && try_cmpxchg64(&it->timeline, &cached, idx))
263 			return it;
264 	}
265 
266 	BUILD_BUG_ON(offsetof(typeof(*it), node));
267 
268 	/* While active, the tree can only be built; not destroyed */
269 	GEM_BUG_ON(i915_active_is_idle(ref));
270 
271 	it = fetch_node(ref->tree.rb_node);
272 	while (it) {
273 		if (it->timeline < idx) {
274 			it = fetch_node(it->node.rb_right);
275 		} else if (it->timeline > idx) {
276 			it = fetch_node(it->node.rb_left);
277 		} else {
278 			WRITE_ONCE(ref->cache, it);
279 			break;
280 		}
281 	}
282 
283 	/* NB: If the tree rotated beneath us, we may miss our target. */
284 	return it;
285 }
286 
287 static struct i915_active_fence *
active_instance(struct i915_active * ref,u64 idx)288 active_instance(struct i915_active *ref, u64 idx)
289 {
290 	struct active_node *node;
291 	struct rb_node **p, *parent;
292 
293 	node = __active_lookup(ref, idx);
294 	if (likely(node))
295 		return &node->base;
296 
297 	spin_lock_irq(&ref->tree_lock);
298 	GEM_BUG_ON(i915_active_is_idle(ref));
299 
300 	parent = NULL;
301 	p = &ref->tree.rb_node;
302 	while (*p) {
303 		parent = *p;
304 
305 		node = rb_entry(parent, struct active_node, node);
306 		if (node->timeline == idx)
307 			goto out;
308 
309 		if (node->timeline < idx)
310 			p = &parent->rb_right;
311 		else
312 			p = &parent->rb_left;
313 	}
314 
315 	/*
316 	 * XXX: We should preallocate this before i915_active_ref() is ever
317 	 *  called, but we cannot call into fs_reclaim() anyway, so use GFP_ATOMIC.
318 	 */
319 	node = kmem_cache_alloc(slab_cache, GFP_ATOMIC);
320 	if (!node)
321 		goto err;
322 
323 	__i915_active_fence_init(&node->base, NULL, node_retire);
324 	node->ref = ref;
325 	node->timeline = idx;
326 
327 	rb_link_node(&node->node, parent, p);
328 	rb_insert_color(&node->node, &ref->tree);
329 
330 out:
331 	WRITE_ONCE(ref->cache, node);
332 	spin_unlock_irq(&ref->tree_lock);
333 
334 	return &node->base;
335 
336 err:
337 	spin_unlock_irq(&ref->tree_lock);
338 
339 	return NULL;
340 }
341 
__i915_active_init(struct i915_active * ref,int (* active)(struct i915_active * ref),void (* retire)(struct i915_active * ref),unsigned long flags,struct lock_class_key * mkey,struct lock_class_key * wkey)342 void __i915_active_init(struct i915_active *ref,
343 			int (*active)(struct i915_active *ref),
344 			void (*retire)(struct i915_active *ref),
345 			unsigned long flags,
346 			struct lock_class_key *mkey,
347 			struct lock_class_key *wkey)
348 {
349 	debug_active_init(ref);
350 
351 	ref->flags = flags;
352 	ref->active = active;
353 	ref->retire = retire;
354 
355 	spin_lock_init(&ref->tree_lock);
356 	ref->tree = RB_ROOT;
357 	ref->cache = NULL;
358 
359 	init_llist_head(&ref->preallocated_barriers);
360 	atomic_set(&ref->count, 0);
361 	__mutex_init(&ref->mutex, "i915_active", mkey);
362 	__i915_active_fence_init(&ref->excl, NULL, excl_retire);
363 	INIT_WORK(&ref->work, active_work);
364 #if IS_ENABLED(CONFIG_LOCKDEP)
365 	lockdep_init_map(&ref->work.lockdep_map, "i915_active.work", wkey, 0);
366 #endif
367 }
368 
____active_del_barrier(struct i915_active * ref,struct active_node * node,struct intel_engine_cs * engine)369 static bool ____active_del_barrier(struct i915_active *ref,
370 				   struct active_node *node,
371 				   struct intel_engine_cs *engine)
372 
373 {
374 	struct llist_node *head = NULL, *tail = NULL;
375 	struct llist_node *pos, *next;
376 
377 	GEM_BUG_ON(node->timeline != engine->kernel_context->timeline->fence_context);
378 
379 	/*
380 	 * Rebuild the llist excluding our node. We may perform this
381 	 * outside of the kernel_context timeline mutex and so someone
382 	 * else may be manipulating the engine->barrier_tasks, in
383 	 * which case either we or they will be upset :)
384 	 *
385 	 * A second __active_del_barrier() will report failure to claim
386 	 * the active_node and the caller will just shrug and know not to
387 	 * claim ownership of its node.
388 	 *
389 	 * A concurrent i915_request_add_active_barriers() will miss adding
390 	 * any of the tasks, but we will try again on the next -- and since
391 	 * we are actively using the barrier, we know that there will be
392 	 * at least another opportunity when we idle.
393 	 */
394 	llist_for_each_safe(pos, next, llist_del_all(&engine->barrier_tasks)) {
395 		if (node == barrier_from_ll(pos)) {
396 			node = NULL;
397 			continue;
398 		}
399 
400 		pos->next = head;
401 		head = pos;
402 		if (!tail)
403 			tail = pos;
404 	}
405 	if (head)
406 		llist_add_batch(head, tail, &engine->barrier_tasks);
407 
408 	return !node;
409 }
410 
411 static bool
__active_del_barrier(struct i915_active * ref,struct active_node * node)412 __active_del_barrier(struct i915_active *ref, struct active_node *node)
413 {
414 	return ____active_del_barrier(ref, node, barrier_to_engine(node));
415 }
416 
417 static bool
replace_barrier(struct i915_active * ref,struct i915_active_fence * active)418 replace_barrier(struct i915_active *ref, struct i915_active_fence *active)
419 {
420 	if (!is_barrier(active)) /* proto-node used by our idle barrier? */
421 		return false;
422 
423 	/*
424 	 * This request is on the kernel_context timeline, and so
425 	 * we can use it to substitute for the pending idle-barrer
426 	 * request that we want to emit on the kernel_context.
427 	 */
428 	return __active_del_barrier(ref, node_from_active(active));
429 }
430 
i915_active_add_request(struct i915_active * ref,struct i915_request * rq)431 int i915_active_add_request(struct i915_active *ref, struct i915_request *rq)
432 {
433 	u64 idx = i915_request_timeline(rq)->fence_context;
434 	struct dma_fence *fence = &rq->fence;
435 	struct i915_active_fence *active;
436 	int err;
437 
438 	/* Prevent reaping in case we malloc/wait while building the tree */
439 	err = i915_active_acquire(ref);
440 	if (err)
441 		return err;
442 
443 	do {
444 		active = active_instance(ref, idx);
445 		if (!active) {
446 			err = -ENOMEM;
447 			goto out;
448 		}
449 
450 		if (replace_barrier(ref, active)) {
451 			RCU_INIT_POINTER(active->fence, NULL);
452 			atomic_dec(&ref->count);
453 		}
454 	} while (unlikely(is_barrier(active)));
455 
456 	fence = __i915_active_fence_set(active, fence);
457 	if (!fence)
458 		__i915_active_acquire(ref);
459 	else
460 		dma_fence_put(fence);
461 
462 out:
463 	i915_active_release(ref);
464 	return err;
465 }
466 
467 static struct dma_fence *
__i915_active_set_fence(struct i915_active * ref,struct i915_active_fence * active,struct dma_fence * fence)468 __i915_active_set_fence(struct i915_active *ref,
469 			struct i915_active_fence *active,
470 			struct dma_fence *fence)
471 {
472 	struct dma_fence *prev;
473 
474 	if (replace_barrier(ref, active)) {
475 		RCU_INIT_POINTER(active->fence, fence);
476 		return NULL;
477 	}
478 
479 	prev = __i915_active_fence_set(active, fence);
480 	if (!prev)
481 		__i915_active_acquire(ref);
482 
483 	return prev;
484 }
485 
486 struct dma_fence *
i915_active_set_exclusive(struct i915_active * ref,struct dma_fence * f)487 i915_active_set_exclusive(struct i915_active *ref, struct dma_fence *f)
488 {
489 	/* We expect the caller to manage the exclusive timeline ordering */
490 	return __i915_active_set_fence(ref, &ref->excl, f);
491 }
492 
i915_active_acquire_if_busy(struct i915_active * ref)493 bool i915_active_acquire_if_busy(struct i915_active *ref)
494 {
495 	debug_active_assert(ref);
496 	return atomic_add_unless(&ref->count, 1, 0);
497 }
498 
__i915_active_activate(struct i915_active * ref)499 static void __i915_active_activate(struct i915_active *ref)
500 {
501 	spin_lock_irq(&ref->tree_lock); /* __active_retire() */
502 	if (!atomic_fetch_inc(&ref->count))
503 		debug_active_activate(ref);
504 	spin_unlock_irq(&ref->tree_lock);
505 }
506 
i915_active_acquire(struct i915_active * ref)507 int i915_active_acquire(struct i915_active *ref)
508 {
509 	int err;
510 
511 	if (i915_active_acquire_if_busy(ref))
512 		return 0;
513 
514 	if (!ref->active) {
515 		__i915_active_activate(ref);
516 		return 0;
517 	}
518 
519 	err = mutex_lock_interruptible(&ref->mutex);
520 	if (err)
521 		return err;
522 
523 	if (likely(!i915_active_acquire_if_busy(ref))) {
524 		err = ref->active(ref);
525 		if (!err)
526 			__i915_active_activate(ref);
527 	}
528 
529 	mutex_unlock(&ref->mutex);
530 
531 	return err;
532 }
533 
i915_active_release(struct i915_active * ref)534 void i915_active_release(struct i915_active *ref)
535 {
536 	debug_active_assert(ref);
537 	active_retire(ref);
538 }
539 
enable_signaling(struct i915_active_fence * active)540 static void enable_signaling(struct i915_active_fence *active)
541 {
542 	struct dma_fence *fence;
543 
544 	if (unlikely(is_barrier(active)))
545 		return;
546 
547 	fence = i915_active_fence_get(active);
548 	if (!fence)
549 		return;
550 
551 	dma_fence_enable_signaling(fence);
552 	dma_fence_put(fence);
553 }
554 
flush_barrier(struct active_node * it)555 static int flush_barrier(struct active_node *it)
556 {
557 	struct intel_engine_cs *engine;
558 
559 	if (likely(!is_barrier(&it->base)))
560 		return 0;
561 
562 	engine = __barrier_to_engine(it);
563 	smp_rmb(); /* serialise with add_active_barriers */
564 	if (!is_barrier(&it->base))
565 		return 0;
566 
567 	return intel_engine_flush_barriers(engine);
568 }
569 
flush_lazy_signals(struct i915_active * ref)570 static int flush_lazy_signals(struct i915_active *ref)
571 {
572 	struct active_node *it, *n;
573 	int err = 0;
574 
575 	enable_signaling(&ref->excl);
576 	rbtree_postorder_for_each_entry_safe(it, n, &ref->tree, node) {
577 		err = flush_barrier(it); /* unconnected idle barrier? */
578 		if (err)
579 			break;
580 
581 		enable_signaling(&it->base);
582 	}
583 
584 	return err;
585 }
586 
__i915_active_wait(struct i915_active * ref,int state)587 int __i915_active_wait(struct i915_active *ref, int state)
588 {
589 	might_sleep();
590 
591 	/* Any fence added after the wait begins will not be auto-signaled */
592 	if (i915_active_acquire_if_busy(ref)) {
593 		int err;
594 
595 		err = flush_lazy_signals(ref);
596 		i915_active_release(ref);
597 		if (err)
598 			return err;
599 
600 		if (___wait_var_event(ref, i915_active_is_idle(ref),
601 				      state, 0, 0, schedule()))
602 			return -EINTR;
603 	}
604 
605 	/*
606 	 * After the wait is complete, the caller may free the active.
607 	 * We have to flush any concurrent retirement before returning.
608 	 */
609 	flush_work(&ref->work);
610 	return 0;
611 }
612 
__await_active(struct i915_active_fence * active,int (* fn)(void * arg,struct dma_fence * fence),void * arg)613 static int __await_active(struct i915_active_fence *active,
614 			  int (*fn)(void *arg, struct dma_fence *fence),
615 			  void *arg)
616 {
617 	struct dma_fence *fence;
618 
619 	if (is_barrier(active)) /* XXX flush the barrier? */
620 		return 0;
621 
622 	fence = i915_active_fence_get(active);
623 	if (fence) {
624 		int err;
625 
626 		err = fn(arg, fence);
627 		dma_fence_put(fence);
628 		if (err < 0)
629 			return err;
630 	}
631 
632 	return 0;
633 }
634 
635 struct wait_barrier {
636 	struct wait_queue_entry base;
637 	struct i915_active *ref;
638 };
639 
640 static int
barrier_wake(wait_queue_entry_t * wq,unsigned int mode,int flags,void * key)641 barrier_wake(wait_queue_entry_t *wq, unsigned int mode, int flags, void *key)
642 {
643 	struct wait_barrier *wb = container_of(wq, typeof(*wb), base);
644 
645 	if (i915_active_is_idle(wb->ref)) {
646 		list_del(&wq->entry);
647 		i915_sw_fence_complete(wq->private);
648 		kfree(wq);
649 	}
650 
651 	return 0;
652 }
653 
__await_barrier(struct i915_active * ref,struct i915_sw_fence * fence)654 static int __await_barrier(struct i915_active *ref, struct i915_sw_fence *fence)
655 {
656 	struct wait_barrier *wb;
657 
658 	wb = kmalloc_obj(*wb);
659 	if (unlikely(!wb))
660 		return -ENOMEM;
661 
662 	GEM_BUG_ON(i915_active_is_idle(ref));
663 	if (!i915_sw_fence_await(fence)) {
664 		kfree(wb);
665 		return -EINVAL;
666 	}
667 
668 	wb->base.flags = 0;
669 	wb->base.func = barrier_wake;
670 	wb->base.private = fence;
671 	wb->ref = ref;
672 
673 	add_wait_queue(__var_waitqueue(ref), &wb->base);
674 	return 0;
675 }
676 
await_active(struct i915_active * ref,unsigned int flags,int (* fn)(void * arg,struct dma_fence * fence),void * arg,struct i915_sw_fence * barrier)677 static int await_active(struct i915_active *ref,
678 			unsigned int flags,
679 			int (*fn)(void *arg, struct dma_fence *fence),
680 			void *arg, struct i915_sw_fence *barrier)
681 {
682 	int err = 0;
683 
684 	if (!i915_active_acquire_if_busy(ref))
685 		return 0;
686 
687 	if (flags & I915_ACTIVE_AWAIT_EXCL &&
688 	    rcu_access_pointer(ref->excl.fence)) {
689 		err = __await_active(&ref->excl, fn, arg);
690 		if (err)
691 			goto out;
692 	}
693 
694 	if (flags & I915_ACTIVE_AWAIT_ACTIVE) {
695 		struct active_node *it, *n;
696 
697 		rbtree_postorder_for_each_entry_safe(it, n, &ref->tree, node) {
698 			err = __await_active(&it->base, fn, arg);
699 			if (err)
700 				goto out;
701 		}
702 	}
703 
704 	if (flags & I915_ACTIVE_AWAIT_BARRIER) {
705 		err = flush_lazy_signals(ref);
706 		if (err)
707 			goto out;
708 
709 		err = __await_barrier(ref, barrier);
710 		if (err)
711 			goto out;
712 	}
713 
714 out:
715 	i915_active_release(ref);
716 	return err;
717 }
718 
rq_await_fence(void * arg,struct dma_fence * fence)719 static int rq_await_fence(void *arg, struct dma_fence *fence)
720 {
721 	return i915_request_await_dma_fence(arg, fence);
722 }
723 
i915_request_await_active(struct i915_request * rq,struct i915_active * ref,unsigned int flags)724 int i915_request_await_active(struct i915_request *rq,
725 			      struct i915_active *ref,
726 			      unsigned int flags)
727 {
728 	return await_active(ref, flags, rq_await_fence, rq, &rq->submit);
729 }
730 
sw_await_fence(void * arg,struct dma_fence * fence)731 static int sw_await_fence(void *arg, struct dma_fence *fence)
732 {
733 	return i915_sw_fence_await_dma_fence(arg, fence, 0,
734 					     GFP_NOWAIT | __GFP_NOWARN);
735 }
736 
i915_sw_fence_await_active(struct i915_sw_fence * fence,struct i915_active * ref,unsigned int flags)737 int i915_sw_fence_await_active(struct i915_sw_fence *fence,
738 			       struct i915_active *ref,
739 			       unsigned int flags)
740 {
741 	return await_active(ref, flags, sw_await_fence, fence, fence);
742 }
743 
i915_active_fini(struct i915_active * ref)744 void i915_active_fini(struct i915_active *ref)
745 {
746 	debug_active_fini(ref);
747 	GEM_BUG_ON(atomic_read(&ref->count));
748 	GEM_BUG_ON(work_pending(&ref->work));
749 	mutex_destroy(&ref->mutex);
750 
751 	if (ref->cache)
752 		kmem_cache_free(slab_cache, ref->cache);
753 }
754 
is_idle_barrier(struct active_node * node,u64 idx)755 static inline bool is_idle_barrier(struct active_node *node, u64 idx)
756 {
757 	return node->timeline == idx && !i915_active_fence_isset(&node->base);
758 }
759 
reuse_idle_barrier(struct i915_active * ref,u64 idx)760 static struct active_node *reuse_idle_barrier(struct i915_active *ref, u64 idx)
761 {
762 	struct rb_node *prev, *p;
763 
764 	if (RB_EMPTY_ROOT(&ref->tree))
765 		return NULL;
766 
767 	GEM_BUG_ON(i915_active_is_idle(ref));
768 
769 	/*
770 	 * Try to reuse any existing barrier nodes already allocated for this
771 	 * i915_active, due to overlapping active phases there is likely a
772 	 * node kept alive (as we reuse before parking). We prefer to reuse
773 	 * completely idle barriers (less hassle in manipulating the llists),
774 	 * but otherwise any will do.
775 	 */
776 	if (ref->cache && is_idle_barrier(ref->cache, idx)) {
777 		p = &ref->cache->node;
778 		goto match;
779 	}
780 
781 	prev = NULL;
782 	p = ref->tree.rb_node;
783 	while (p) {
784 		struct active_node *node =
785 			rb_entry(p, struct active_node, node);
786 
787 		if (is_idle_barrier(node, idx))
788 			goto match;
789 
790 		prev = p;
791 		if (node->timeline < idx)
792 			p = READ_ONCE(p->rb_right);
793 		else
794 			p = READ_ONCE(p->rb_left);
795 	}
796 
797 	/*
798 	 * No quick match, but we did find the leftmost rb_node for the
799 	 * kernel_context. Walk the rb_tree in-order to see if there were
800 	 * any idle-barriers on this timeline that we missed, or just use
801 	 * the first pending barrier.
802 	 */
803 	for (p = prev; p; p = rb_next(p)) {
804 		struct active_node *node =
805 			rb_entry(p, struct active_node, node);
806 		struct intel_engine_cs *engine;
807 
808 		if (node->timeline > idx)
809 			break;
810 
811 		if (node->timeline < idx)
812 			continue;
813 
814 		if (is_idle_barrier(node, idx))
815 			goto match;
816 
817 		/*
818 		 * The list of pending barriers is protected by the
819 		 * kernel_context timeline, which notably we do not hold
820 		 * here. i915_request_add_active_barriers() may consume
821 		 * the barrier before we claim it, so we have to check
822 		 * for success.
823 		 */
824 		engine = __barrier_to_engine(node);
825 		smp_rmb(); /* serialise with add_active_barriers */
826 		if (is_barrier(&node->base) &&
827 		    ____active_del_barrier(ref, node, engine))
828 			goto match;
829 	}
830 
831 	return NULL;
832 
833 match:
834 	spin_lock_irq(&ref->tree_lock);
835 	rb_erase(p, &ref->tree); /* Hide from waits and sibling allocations */
836 	if (p == &ref->cache->node)
837 		WRITE_ONCE(ref->cache, NULL);
838 	spin_unlock_irq(&ref->tree_lock);
839 
840 	return rb_entry(p, struct active_node, node);
841 }
842 
i915_active_acquire_preallocate_barrier(struct i915_active * ref,struct intel_engine_cs * engine)843 int i915_active_acquire_preallocate_barrier(struct i915_active *ref,
844 					    struct intel_engine_cs *engine)
845 {
846 	intel_engine_mask_t tmp, mask = engine->mask;
847 	struct llist_node *first = NULL, *last = NULL;
848 	struct intel_gt *gt = engine->gt;
849 
850 	GEM_BUG_ON(i915_active_is_idle(ref));
851 
852 	/* Wait until the previous preallocation is completed */
853 	while (!llist_empty(&ref->preallocated_barriers))
854 		cond_resched();
855 
856 	/*
857 	 * Preallocate a node for each physical engine supporting the target
858 	 * engine (remember virtual engines have more than one sibling).
859 	 * We can then use the preallocated nodes in
860 	 * i915_active_acquire_barrier()
861 	 */
862 	GEM_BUG_ON(!mask);
863 	for_each_engine_masked(engine, gt, mask, tmp) {
864 		u64 idx = engine->kernel_context->timeline->fence_context;
865 		struct llist_node *prev = first;
866 		struct active_node *node;
867 
868 		rcu_read_lock();
869 		node = reuse_idle_barrier(ref, idx);
870 		rcu_read_unlock();
871 		if (!node) {
872 			node = kmem_cache_alloc(slab_cache, GFP_KERNEL);
873 			if (!node)
874 				goto unwind;
875 
876 			RCU_INIT_POINTER(node->base.fence, NULL);
877 			node->base.cb.func = node_retire;
878 			node->timeline = idx;
879 			node->ref = ref;
880 		}
881 
882 		if (!i915_active_fence_isset(&node->base)) {
883 			/*
884 			 * Mark this as being *our* unconnected proto-node.
885 			 *
886 			 * Since this node is not in any list, and we have
887 			 * decoupled it from the rbtree, we can reuse the
888 			 * request to indicate this is an idle-barrier node
889 			 * and then we can use the rb_node and list pointers
890 			 * for our tracking of the pending barrier.
891 			 */
892 			RCU_INIT_POINTER(node->base.fence, ERR_PTR(-EAGAIN));
893 			node->base.cb.node.prev = (void *)engine;
894 			__i915_active_acquire(ref);
895 		}
896 		GEM_BUG_ON(rcu_access_pointer(node->base.fence) != ERR_PTR(-EAGAIN));
897 
898 		GEM_BUG_ON(barrier_to_engine(node) != engine);
899 		first = barrier_to_ll(node);
900 		first->next = prev;
901 		if (!last)
902 			last = first;
903 		intel_engine_pm_get(engine);
904 	}
905 
906 	GEM_BUG_ON(!llist_empty(&ref->preallocated_barriers));
907 	llist_add_batch(first, last, &ref->preallocated_barriers);
908 
909 	return 0;
910 
911 unwind:
912 	while (first) {
913 		struct active_node *node = barrier_from_ll(first);
914 
915 		first = first->next;
916 
917 		atomic_dec(&ref->count);
918 		intel_engine_pm_put(barrier_to_engine(node));
919 
920 		kmem_cache_free(slab_cache, node);
921 	}
922 	return -ENOMEM;
923 }
924 
i915_active_acquire_barrier(struct i915_active * ref)925 void i915_active_acquire_barrier(struct i915_active *ref)
926 {
927 	struct llist_node *pos, *next;
928 	unsigned long flags;
929 
930 	GEM_BUG_ON(i915_active_is_idle(ref));
931 
932 	/*
933 	 * Transfer the list of preallocated barriers into the
934 	 * i915_active rbtree, but only as proto-nodes. They will be
935 	 * populated by i915_request_add_active_barriers() to point to the
936 	 * request that will eventually release them.
937 	 */
938 	llist_for_each_safe(pos, next, take_preallocated_barriers(ref)) {
939 		struct active_node *node = barrier_from_ll(pos);
940 		struct intel_engine_cs *engine = barrier_to_engine(node);
941 		struct rb_node **p, *parent;
942 
943 		spin_lock_irqsave_nested(&ref->tree_lock, flags,
944 					 SINGLE_DEPTH_NESTING);
945 		parent = NULL;
946 		p = &ref->tree.rb_node;
947 		while (*p) {
948 			struct active_node *it;
949 
950 			parent = *p;
951 
952 			it = rb_entry(parent, struct active_node, node);
953 			if (it->timeline < node->timeline)
954 				p = &parent->rb_right;
955 			else
956 				p = &parent->rb_left;
957 		}
958 		rb_link_node(&node->node, parent, p);
959 		rb_insert_color(&node->node, &ref->tree);
960 		spin_unlock_irqrestore(&ref->tree_lock, flags);
961 
962 		GEM_BUG_ON(!intel_engine_pm_is_awake(engine));
963 		llist_add(barrier_to_ll(node), &engine->barrier_tasks);
964 		intel_engine_pm_put_delay(engine, 2);
965 	}
966 }
967 
ll_to_fence_slot(struct llist_node * node)968 static struct dma_fence **ll_to_fence_slot(struct llist_node *node)
969 {
970 	return __active_fence_slot(&barrier_from_ll(node)->base);
971 }
972 
i915_request_add_active_barriers(struct i915_request * rq)973 void i915_request_add_active_barriers(struct i915_request *rq)
974 {
975 	struct intel_engine_cs *engine = rq->engine;
976 	struct llist_node *node, *next;
977 	unsigned long flags;
978 
979 	GEM_BUG_ON(!intel_context_is_barrier(rq->context));
980 	GEM_BUG_ON(intel_engine_is_virtual(engine));
981 	GEM_BUG_ON(i915_request_timeline(rq) != engine->kernel_context->timeline);
982 
983 	node = llist_del_all(&engine->barrier_tasks);
984 	if (!node)
985 		return;
986 	/*
987 	 * Attach the list of proto-fences to the in-flight request such
988 	 * that the parent i915_active will be released when this request
989 	 * is retired.
990 	 */
991 	spin_lock_irqsave(&rq->lock, flags);
992 	llist_for_each_safe(node, next, node) {
993 		/* serialise with reuse_idle_barrier */
994 		smp_store_mb(*ll_to_fence_slot(node), &rq->fence);
995 		list_add_tail((struct list_head *)node, &rq->fence.cb_list);
996 	}
997 	spin_unlock_irqrestore(&rq->lock, flags);
998 }
999 
1000 /*
1001  * __i915_active_fence_set: Update the last active fence along its timeline
1002  * @active: the active tracker
1003  * @fence: the new fence (under construction)
1004  *
1005  * Records the new @fence as the last active fence along its timeline in
1006  * this active tracker, moving the tracking callbacks from the previous
1007  * fence onto this one. Gets and returns a reference to the previous fence
1008  * (if not already completed), which the caller must put after making sure
1009  * that it is executed before the new fence. To ensure that the order of
1010  * fences within the timeline of the i915_active_fence is understood, it
1011  * should be locked by the caller.
1012  */
1013 struct dma_fence *
__i915_active_fence_set(struct i915_active_fence * active,struct dma_fence * fence)1014 __i915_active_fence_set(struct i915_active_fence *active,
1015 			struct dma_fence *fence)
1016 {
1017 	struct dma_fence *prev;
1018 	unsigned long flags;
1019 
1020 	/*
1021 	 * In case of fences embedded in i915_requests, their memory is
1022 	 * SLAB_FAILSAFE_BY_RCU, then it can be reused right after release
1023 	 * by new requests.  Then, there is a risk of passing back a pointer
1024 	 * to a new, completely unrelated fence that reuses the same memory
1025 	 * while tracked under a different active tracker.  Combined with i915
1026 	 * perf open/close operations that build await dependencies between
1027 	 * engine kernel context requests and user requests from different
1028 	 * timelines, this can lead to dependency loops and infinite waits.
1029 	 *
1030 	 * As a countermeasure, we try to get a reference to the active->fence
1031 	 * first, so if we succeed and pass it back to our user then it is not
1032 	 * released and potentially reused by an unrelated request before the
1033 	 * user has a chance to set up an await dependency on it.
1034 	 */
1035 	prev = i915_active_fence_get(active);
1036 	if (fence == prev)
1037 		return fence;
1038 
1039 	GEM_BUG_ON(test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags));
1040 
1041 	/*
1042 	 * Consider that we have two threads arriving (A and B), with
1043 	 * C already resident as the active->fence.
1044 	 *
1045 	 * Both A and B have got a reference to C or NULL, depending on the
1046 	 * timing of the interrupt handler.  Let's assume that if A has got C
1047 	 * then it has locked C first (before B).
1048 	 *
1049 	 * Note the strong ordering of the timeline also provides consistent
1050 	 * nesting rules for the fence->lock; the inner lock is always the
1051 	 * older lock.
1052 	 */
1053 	dma_fence_lock_irqsave(fence, flags);
1054 	if (prev)
1055 		spin_lock_nested(dma_fence_spinlock(prev),
1056 				 SINGLE_DEPTH_NESTING);
1057 
1058 	/*
1059 	 * A does the cmpxchg first, and so it sees C or NULL, as before, or
1060 	 * something else, depending on the timing of other threads and/or
1061 	 * interrupt handler.  If not the same as before then A unlocks C if
1062 	 * applicable and retries, starting from an attempt to get a new
1063 	 * active->fence.  Meanwhile, B follows the same path as A.
1064 	 * Once A succeeds with cmpxch, B fails again, retires, gets A from
1065 	 * active->fence, locks it as soon as A completes, and possibly
1066 	 * succeeds with cmpxchg.
1067 	 */
1068 	while (cmpxchg(__active_fence_slot(active), prev, fence) != prev) {
1069 		if (prev) {
1070 			spin_unlock(dma_fence_spinlock(prev));
1071 			dma_fence_put(prev);
1072 		}
1073 		dma_fence_unlock_irqrestore(fence, flags);
1074 
1075 		prev = i915_active_fence_get(active);
1076 		GEM_BUG_ON(prev == fence);
1077 
1078 		dma_fence_lock_irqsave(fence, flags);
1079 		if (prev)
1080 			spin_lock_nested(dma_fence_spinlock(prev),
1081 					 SINGLE_DEPTH_NESTING);
1082 	}
1083 
1084 	/*
1085 	 * If prev is NULL then the previous fence must have been signaled
1086 	 * and we know that we are first on the timeline.  If it is still
1087 	 * present then, having the lock on that fence already acquired, we
1088 	 * serialise with the interrupt handler, in the process of removing it
1089 	 * from any future interrupt callback.  A will then wait on C before
1090 	 * executing (if present).
1091 	 *
1092 	 * As B is second, it sees A as the previous fence and so waits for
1093 	 * it to complete its transition and takes over the occupancy for
1094 	 * itself -- remembering that it needs to wait on A before executing.
1095 	 */
1096 	if (prev) {
1097 		__list_del_entry(&active->cb.node);
1098 		/* serialise with prev->cb_list */
1099 		spin_unlock(dma_fence_spinlock(prev));
1100 	}
1101 	list_add_tail(&active->cb.node, &fence->cb_list);
1102 	dma_fence_unlock_irqrestore(fence, flags);
1103 
1104 	return prev;
1105 }
1106 
i915_active_fence_set(struct i915_active_fence * active,struct i915_request * rq)1107 int i915_active_fence_set(struct i915_active_fence *active,
1108 			  struct i915_request *rq)
1109 {
1110 	struct dma_fence *fence;
1111 	int err = 0;
1112 
1113 	/* Must maintain timeline ordering wrt previous active requests */
1114 	fence = __i915_active_fence_set(active, &rq->fence);
1115 	if (fence) {
1116 		err = i915_request_await_dma_fence(rq, fence);
1117 		dma_fence_put(fence);
1118 	}
1119 
1120 	return err;
1121 }
1122 
i915_active_noop(struct dma_fence * fence,struct dma_fence_cb * cb)1123 void i915_active_noop(struct dma_fence *fence, struct dma_fence_cb *cb)
1124 {
1125 	active_fence_cb(fence, cb);
1126 }
1127 
1128 struct auto_active {
1129 	struct i915_active base;
1130 	struct kref ref;
1131 };
1132 
i915_active_get(struct i915_active * ref)1133 struct i915_active *i915_active_get(struct i915_active *ref)
1134 {
1135 	struct auto_active *aa = container_of(ref, typeof(*aa), base);
1136 
1137 	kref_get(&aa->ref);
1138 	return &aa->base;
1139 }
1140 
auto_release(struct kref * ref)1141 static void auto_release(struct kref *ref)
1142 {
1143 	struct auto_active *aa = container_of(ref, typeof(*aa), ref);
1144 
1145 	i915_active_fini(&aa->base);
1146 	kfree(aa);
1147 }
1148 
i915_active_put(struct i915_active * ref)1149 void i915_active_put(struct i915_active *ref)
1150 {
1151 	struct auto_active *aa = container_of(ref, typeof(*aa), base);
1152 
1153 	kref_put(&aa->ref, auto_release);
1154 }
1155 
auto_active(struct i915_active * ref)1156 static int auto_active(struct i915_active *ref)
1157 {
1158 	i915_active_get(ref);
1159 	return 0;
1160 }
1161 
auto_retire(struct i915_active * ref)1162 static void auto_retire(struct i915_active *ref)
1163 {
1164 	i915_active_put(ref);
1165 }
1166 
i915_active_create(void)1167 struct i915_active *i915_active_create(void)
1168 {
1169 	struct auto_active *aa;
1170 
1171 	aa = kmalloc_obj(*aa);
1172 	if (!aa)
1173 		return NULL;
1174 
1175 	kref_init(&aa->ref);
1176 	i915_active_init(&aa->base, auto_active, auto_retire, 0);
1177 
1178 	return &aa->base;
1179 }
1180 
1181 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
1182 #include "selftests/i915_active.c"
1183 #endif
1184 
i915_active_module_exit(void)1185 void i915_active_module_exit(void)
1186 {
1187 	kmem_cache_destroy(slab_cache);
1188 }
1189 
i915_active_module_init(void)1190 int __init i915_active_module_init(void)
1191 {
1192 	slab_cache = KMEM_CACHE(active_node, SLAB_HWCACHE_ALIGN);
1193 	if (!slab_cache)
1194 		return -ENOMEM;
1195 
1196 	return 0;
1197 }
1198