intel_breadcrumbs.c 26.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/*
 * Copyright © 2015 Intel Corporation
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 *
 */

25
#include <linux/kthread.h>
26
#include <uapi/linux/sched/types.h>
27

28 29
#include "i915_drv.h"

30
static unsigned int __intel_breadcrumbs_wakeup(struct intel_breadcrumbs *b)
31
{
32
	struct intel_wait *wait;
33 34
	unsigned int result = 0;

35 36 37
	lockdep_assert_held(&b->irq_lock);

	wait = b->irq_wait;
38
	if (wait) {
39
		result = ENGINE_WAKEUP_WAITER;
40 41
		if (wake_up_process(wait->tsk))
			result |= ENGINE_WAKEUP_ASLEEP;
42
	}
43 44 45 46 47 48 49

	return result;
}

unsigned int intel_engine_wakeup(struct intel_engine_cs *engine)
{
	struct intel_breadcrumbs *b = &engine->breadcrumbs;
50
	unsigned long flags;
51 52
	unsigned int result;

53
	spin_lock_irqsave(&b->irq_lock, flags);
54
	result = __intel_breadcrumbs_wakeup(b);
55
	spin_unlock_irqrestore(&b->irq_lock, flags);
56 57 58 59

	return result;
}

60 61 62 63 64
static unsigned long wait_timeout(void)
{
	return round_jiffies_up(jiffies + DRM_I915_HANGCHECK_JIFFIES);
}

65 66
static noinline void missed_breadcrumb(struct intel_engine_cs *engine)
{
67
	DRM_DEBUG_DRIVER("%s missed breadcrumb at %pS, irq posted? %s, current seqno=%x, last=%x\n",
68 69
			 engine->name, __builtin_return_address(0),
			 yesno(test_bit(ENGINE_IRQ_BREADCRUMB,
70 71 72
					&engine->irq_posted)),
			 intel_engine_get_seqno(engine),
			 intel_engine_last_submit(engine));
73 74 75 76

	set_bit(engine->id, &engine->i915->gpu_error.missed_irq_rings);
}

77
static void intel_breadcrumbs_hangcheck(struct timer_list *t)
78
{
79 80
	struct intel_engine_cs *engine = from_timer(engine, t,
						    breadcrumbs.hangcheck);
81 82
	struct intel_breadcrumbs *b = &engine->breadcrumbs;

83
	if (!b->irq_armed)
84 85
		return;

86 87 88
	if (b->hangcheck_interrupts != atomic_read(&engine->irq_count)) {
		b->hangcheck_interrupts = atomic_read(&engine->irq_count);
		mod_timer(&b->hangcheck, wait_timeout());
89 90 91
		return;
	}

92
	/* We keep the hangcheck timer alive until we disarm the irq, even
93 94 95
	 * if there are no waiters at present.
	 *
	 * If the waiter was currently running, assume it hasn't had a chance
96 97
	 * to process the pending interrupt (e.g, low priority task on a loaded
	 * system) and wait until it sleeps before declaring a missed interrupt.
98 99 100 101 102
	 *
	 * If the waiter was asleep (and not even pending a wakeup), then we
	 * must have missed an interrupt as the GPU has stopped advancing
	 * but we still have a waiter. Assuming all batches complete within
	 * DRM_I915_HANGCHECK_JIFFIES [1.5s]!
103
	 */
104
	if (intel_engine_wakeup(engine) & ENGINE_WAKEUP_ASLEEP) {
105
		missed_breadcrumb(engine);
106 107
		mod_timer(&engine->breadcrumbs.fake_irq, jiffies + 1);
	} else {
108 109
		mod_timer(&b->hangcheck, wait_timeout());
	}
110 111
}

112
static void intel_breadcrumbs_fake_irq(struct timer_list *t)
113
{
114 115
	struct intel_engine_cs *engine = from_timer(engine, t,
						    breadcrumbs.fake_irq);
116
	struct intel_breadcrumbs *b = &engine->breadcrumbs;
117

118
	/* The timer persists in case we cannot enable interrupts,
119
	 * or if we have previously seen seqno/interrupt incoherency
120 121 122
	 * ("missed interrupt" syndrome, better known as a "missed breadcrumb").
	 * Here the worker will wake up every jiffie in order to kick the
	 * oldest waiter to do the coherent seqno check.
123
	 */
124

125
	spin_lock_irq(&b->irq_lock);
126
	if (b->irq_armed && !__intel_breadcrumbs_wakeup(b))
127
		__intel_engine_disarm_breadcrumbs(engine);
128
	spin_unlock_irq(&b->irq_lock);
129
	if (!b->irq_armed)
130 131
		return;

132
	mod_timer(&b->fake_irq, jiffies + 1);
133 134 135 136 137 138 139 140 141 142 143

	/* Ensure that even if the GPU hangs, we get woken up.
	 *
	 * However, note that if no one is waiting, we never notice
	 * a gpu hang. Eventually, we will have to wait for a resource
	 * held by the GPU and so trigger a hangcheck. In the most
	 * pathological case, this will be upon memory starvation! To
	 * prevent this, we also queue the hangcheck from the retire
	 * worker.
	 */
	i915_queue_hangcheck(engine->i915);
144 145 146 147
}

static void irq_enable(struct intel_engine_cs *engine)
{
148 149 150 151 152 153 154 155
	/*
	 * FIXME: Ideally we want this on the API boundary, but for the
	 * sake of testing with mock breadcrumbs (no HW so unable to
	 * enable irqs) we place it deep within the bowels, at the point
	 * of no return.
	 */
	GEM_BUG_ON(!intel_irqs_enabled(engine->i915));

156 157 158 159
	/* Enabling the IRQ may miss the generation of the interrupt, but
	 * we still need to force the barrier before reading the seqno,
	 * just in case.
	 */
160
	set_bit(ENGINE_IRQ_BREADCRUMB, &engine->irq_posted);
161

162 163
	/* Caller disables interrupts */
	spin_lock(&engine->i915->irq_lock);
164
	engine->irq_enable(engine);
165
	spin_unlock(&engine->i915->irq_lock);
166 167 168 169
}

static void irq_disable(struct intel_engine_cs *engine)
{
170 171
	/* Caller disables interrupts */
	spin_lock(&engine->i915->irq_lock);
172
	engine->irq_disable(engine);
173
	spin_unlock(&engine->i915->irq_lock);
174 175
}

176 177 178 179
void __intel_engine_disarm_breadcrumbs(struct intel_engine_cs *engine)
{
	struct intel_breadcrumbs *b = &engine->breadcrumbs;

180
	lockdep_assert_held(&b->irq_lock);
181
	GEM_BUG_ON(b->irq_wait);
182
	GEM_BUG_ON(!b->irq_armed);
183

184 185
	GEM_BUG_ON(!b->irq_enabled);
	if (!--b->irq_enabled)
186 187 188 189 190
		irq_disable(engine);

	b->irq_armed = false;
}

191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
void intel_engine_pin_breadcrumbs_irq(struct intel_engine_cs *engine)
{
	struct intel_breadcrumbs *b = &engine->breadcrumbs;

	spin_lock_irq(&b->irq_lock);
	if (!b->irq_enabled++)
		irq_enable(engine);
	GEM_BUG_ON(!b->irq_enabled); /* no overflow! */
	spin_unlock_irq(&b->irq_lock);
}

void intel_engine_unpin_breadcrumbs_irq(struct intel_engine_cs *engine)
{
	struct intel_breadcrumbs *b = &engine->breadcrumbs;

	spin_lock_irq(&b->irq_lock);
	GEM_BUG_ON(!b->irq_enabled); /* no underflow! */
	if (!--b->irq_enabled)
		irq_disable(engine);
	spin_unlock_irq(&b->irq_lock);
}

213 214 215
void intel_engine_disarm_breadcrumbs(struct intel_engine_cs *engine)
{
	struct intel_breadcrumbs *b = &engine->breadcrumbs;
216
	struct intel_wait *wait, *n, *first;
217 218 219 220 221

	if (!b->irq_armed)
		return;

	/* We only disarm the irq when we are idle (all requests completed),
222
	 * so if the bottom-half remains asleep, it missed the request
223 224 225
	 * completion.
	 */

226
	spin_lock_irq(&b->rb_lock);
227 228 229

	spin_lock(&b->irq_lock);
	first = fetch_and_zero(&b->irq_wait);
230 231
	if (b->irq_armed)
		__intel_engine_disarm_breadcrumbs(engine);
232 233
	spin_unlock(&b->irq_lock);

234 235
	rbtree_postorder_for_each_entry_safe(wait, n, &b->waiters, node) {
		RB_CLEAR_NODE(&wait->node);
236
		if (wake_up_process(wait->tsk) && wait == first)
237 238 239 240 241
			missed_breadcrumb(engine);
	}
	b->waiters = RB_ROOT;

	spin_unlock_irq(&b->rb_lock);
242 243
}

244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
static bool use_fake_irq(const struct intel_breadcrumbs *b)
{
	const struct intel_engine_cs *engine =
		container_of(b, struct intel_engine_cs, breadcrumbs);

	if (!test_bit(engine->id, &engine->i915->gpu_error.missed_irq_rings))
		return false;

	/* Only start with the heavy weight fake irq timer if we have not
	 * seen any interrupts since enabling it the first time. If the
	 * interrupts are still arriving, it means we made a mistake in our
	 * engine->seqno_barrier(), a timing error that should be transient
	 * and unlikely to reoccur.
	 */
	return atomic_read(&engine->irq_count) == b->hangcheck_interrupts;
}

261 262 263 264 265 266 267 268 269
static void enable_fake_irq(struct intel_breadcrumbs *b)
{
	/* Ensure we never sleep indefinitely */
	if (!b->irq_enabled || use_fake_irq(b))
		mod_timer(&b->fake_irq, jiffies + 1);
	else
		mod_timer(&b->hangcheck, wait_timeout());
}

270
static bool __intel_breadcrumbs_enable_irq(struct intel_breadcrumbs *b)
271 272 273 274
{
	struct intel_engine_cs *engine =
		container_of(b, struct intel_engine_cs, breadcrumbs);
	struct drm_i915_private *i915 = engine->i915;
275 276
	bool enabled;

277
	lockdep_assert_held(&b->irq_lock);
278
	if (b->irq_armed)
279
		return false;
280

281 282 283 284 285 286 287
	/* The breadcrumb irq will be disarmed on the interrupt after the
	 * waiters are signaled. This gives us a single interrupt window in
	 * which we can add a new waiter and avoid the cost of re-enabling
	 * the irq.
	 */
	b->irq_armed = true;

288 289 290 291 292 293 294 295
	if (I915_SELFTEST_ONLY(b->mock)) {
		/* For our mock objects we want to avoid interaction
		 * with the real hardware (which is not set up). So
		 * we simply pretend we have enabled the powerwell
		 * and the irq, and leave it up to the mock
		 * implementation to call intel_engine_wakeup()
		 * itself when it wants to simulate a user interrupt,
		 */
296
		return true;
297 298
	}

299
	/* Since we are waiting on a request, the GPU should be busy
300 301 302 303
	 * and should have its own rpm reference. This is tracked
	 * by i915->gt.awake, we can forgo holding our own wakref
	 * for the interrupt as before i915->gt.awake is released (when
	 * the driver is idle) we disarm the breadcrumbs.
304 305 306
	 */

	/* No interrupts? Kick the waiter every jiffie! */
307 308 309 310 311
	enabled = false;
	if (!b->irq_enabled++ &&
	    !test_bit(engine->id, &i915->gpu_error.test_irq_rings)) {
		irq_enable(engine);
		enabled = true;
312 313
	}

314
	enable_fake_irq(b);
315
	return enabled;
316 317 318 319
}

static inline struct intel_wait *to_wait(struct rb_node *node)
{
320
	return rb_entry(node, struct intel_wait, node);
321 322 323 324 325
}

static inline void __intel_breadcrumbs_finish(struct intel_breadcrumbs *b,
					      struct intel_wait *wait)
{
326
	lockdep_assert_held(&b->rb_lock);
327
	GEM_BUG_ON(b->irq_wait == wait);
328 329

	/* This request is completed, so remove it from the tree, mark it as
330 331 332 333 334 335
	 * complete, and *then* wake up the associated task. N.B. when the
	 * task wakes up, it will find the empty rb_node, discern that it
	 * has already been removed from the tree and skip the serialisation
	 * of the b->rb_lock and b->irq_lock. This means that the destruction
	 * of the intel_wait is not serialised with the interrupt handler
	 * by the waiter - it must instead be serialised by the caller.
336 337 338 339 340 341 342
	 */
	rb_erase(&wait->node, &b->waiters);
	RB_CLEAR_NODE(&wait->node);

	wake_up_process(wait->tsk); /* implicit smp_wmb() */
}

343 344 345 346 347
static inline void __intel_breadcrumbs_next(struct intel_engine_cs *engine,
					    struct rb_node *next)
{
	struct intel_breadcrumbs *b = &engine->breadcrumbs;

348
	spin_lock(&b->irq_lock);
349
	GEM_BUG_ON(!b->irq_armed);
350
	GEM_BUG_ON(!b->irq_wait);
351 352
	b->irq_wait = to_wait(next);
	spin_unlock(&b->irq_lock);
353 354 355 356 357 358 359 360 361

	/* We always wake up the next waiter that takes over as the bottom-half
	 * as we may delegate not only the irq-seqno barrier to the next waiter
	 * but also the task of waking up concurrent waiters.
	 */
	if (next)
		wake_up_process(to_wait(next)->tsk);
}

362 363 364 365 366
static bool __intel_engine_add_wait(struct intel_engine_cs *engine,
				    struct intel_wait *wait)
{
	struct intel_breadcrumbs *b = &engine->breadcrumbs;
	struct rb_node **p, *parent, *completed;
367
	bool first, armed;
368 369 370 371 372 373 374 375 376 377 378 379 380 381
	u32 seqno;

	/* Insert the request into the retirement ordered list
	 * of waiters by walking the rbtree. If we are the oldest
	 * seqno in the tree (the first to be retired), then
	 * set ourselves as the bottom-half.
	 *
	 * As we descend the tree, prune completed branches since we hold the
	 * spinlock we know that the first_waiter must be delayed and can
	 * reduce some of the sequential wake up latency if we take action
	 * ourselves and wake up the completed tasks in parallel. Also, by
	 * removing stale elements in the tree, we may be able to reduce the
	 * ping-pong between the old bottom-half and ourselves as first-waiter.
	 */
382
	armed = false;
383 384 385
	first = true;
	parent = NULL;
	completed = NULL;
386
	seqno = intel_engine_get_seqno(engine);
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427

	 /* If the request completed before we managed to grab the spinlock,
	  * return now before adding ourselves to the rbtree. We let the
	  * current bottom-half handle any pending wakeups and instead
	  * try and get out of the way quickly.
	  */
	if (i915_seqno_passed(seqno, wait->seqno)) {
		RB_CLEAR_NODE(&wait->node);
		return first;
	}

	p = &b->waiters.rb_node;
	while (*p) {
		parent = *p;
		if (wait->seqno == to_wait(parent)->seqno) {
			/* We have multiple waiters on the same seqno, select
			 * the highest priority task (that with the smallest
			 * task->prio) to serve as the bottom-half for this
			 * group.
			 */
			if (wait->tsk->prio > to_wait(parent)->tsk->prio) {
				p = &parent->rb_right;
				first = false;
			} else {
				p = &parent->rb_left;
			}
		} else if (i915_seqno_passed(wait->seqno,
					     to_wait(parent)->seqno)) {
			p = &parent->rb_right;
			if (i915_seqno_passed(seqno, to_wait(parent)->seqno))
				completed = parent;
			else
				first = false;
		} else {
			p = &parent->rb_left;
		}
	}
	rb_link_node(&wait->node, parent, p);
	rb_insert_color(&wait->node, &b->waiters);

	if (first) {
428 429
		spin_lock(&b->irq_lock);
		b->irq_wait = wait;
430 431 432 433 434
		/* After assigning ourselves as the new bottom-half, we must
		 * perform a cursory check to prevent a missed interrupt.
		 * Either we miss the interrupt whilst programming the hardware,
		 * or if there was a previous waiter (for a later seqno) they
		 * may be woken instead of us (due to the inherent race
435 436
		 * in the unlocked read of b->irq_seqno_bh in the irq handler)
		 * and so we miss the wake up.
437
		 */
438
		armed = __intel_breadcrumbs_enable_irq(b);
439
		spin_unlock(&b->irq_lock);
440
	}
441 442

	if (completed) {
443 444 445 446 447
		/* Advance the bottom-half (b->irq_wait) before we wake up
		 * the waiters who may scribble over their intel_wait
		 * just as the interrupt handler is dereferencing it via
		 * b->irq_wait.
		 */
448 449 450 451 452 453 454 455 456 457 458 459 460
		if (!first) {
			struct rb_node *next = rb_next(completed);
			GEM_BUG_ON(next == &wait->node);
			__intel_breadcrumbs_next(engine, next);
		}

		do {
			struct intel_wait *crumb = to_wait(completed);
			completed = rb_prev(completed);
			__intel_breadcrumbs_finish(b, crumb);
		} while (completed);
	}

461
	GEM_BUG_ON(!b->irq_wait);
462
	GEM_BUG_ON(!b->irq_armed);
463
	GEM_BUG_ON(rb_first(&b->waiters) != &b->irq_wait->node);
464

465
	return armed;
466 467 468 469 470 471
}

bool intel_engine_add_wait(struct intel_engine_cs *engine,
			   struct intel_wait *wait)
{
	struct intel_breadcrumbs *b = &engine->breadcrumbs;
472
	bool armed;
473

474
	spin_lock_irq(&b->rb_lock);
475
	armed = __intel_engine_add_wait(engine, wait);
476
	spin_unlock_irq(&b->rb_lock);
477 478
	if (armed)
		return armed;
479

480 481 482
	/* Make the caller recheck if its request has already started. */
	return i915_seqno_passed(intel_engine_get_seqno(engine),
				 wait->seqno - 1);
483 484 485 486 487 488 489
}

static inline bool chain_wakeup(struct rb_node *rb, int priority)
{
	return rb && to_wait(rb)->tsk->prio <= priority;
}

490 491 492 493 494 495 496 497 498
static inline int wakeup_priority(struct intel_breadcrumbs *b,
				  struct task_struct *tsk)
{
	if (tsk == b->signaler)
		return INT_MIN;
	else
		return tsk->prio;
}

499 500
static void __intel_engine_remove_wait(struct intel_engine_cs *engine,
				       struct intel_wait *wait)
501 502 503
{
	struct intel_breadcrumbs *b = &engine->breadcrumbs;

504
	lockdep_assert_held(&b->rb_lock);
505 506

	if (RB_EMPTY_NODE(&wait->node))
507
		goto out;
508

509
	if (b->irq_wait == wait) {
510
		const int priority = wakeup_priority(b, wait->tsk);
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
		struct rb_node *next;

		/* We are the current bottom-half. Find the next candidate,
		 * the first waiter in the queue on the remaining oldest
		 * request. As multiple seqnos may complete in the time it
		 * takes us to wake up and find the next waiter, we have to
		 * wake up that waiter for it to perform its own coherent
		 * completion check.
		 */
		next = rb_next(&wait->node);
		if (chain_wakeup(next, priority)) {
			/* If the next waiter is already complete,
			 * wake it up and continue onto the next waiter. So
			 * if have a small herd, they will wake up in parallel
			 * rather than sequentially, which should reduce
			 * the overall latency in waking all the completed
			 * clients.
			 *
			 * However, waking up a chain adds extra latency to
			 * the first_waiter. This is undesirable if that
			 * waiter is a high priority task.
			 */
533
			u32 seqno = intel_engine_get_seqno(engine);
534 535 536 537 538 539 540 541 542 543 544

			while (i915_seqno_passed(seqno, to_wait(next)->seqno)) {
				struct rb_node *n = rb_next(next);

				__intel_breadcrumbs_finish(b, to_wait(next));
				next = n;
				if (!chain_wakeup(next, priority))
					break;
			}
		}

545
		__intel_breadcrumbs_next(engine, next);
546 547 548 549 550 551
	} else {
		GEM_BUG_ON(rb_first(&b->waiters) == &wait->node);
	}

	GEM_BUG_ON(RB_EMPTY_NODE(&wait->node));
	rb_erase(&wait->node, &b->waiters);
552
	RB_CLEAR_NODE(&wait->node);
553

554
out:
555
	GEM_BUG_ON(b->irq_wait == wait);
556
	GEM_BUG_ON(rb_first(&b->waiters) !=
557
		   (b->irq_wait ? &b->irq_wait->node : NULL));
558 559 560 561 562 563 564 565 566 567 568
}

void intel_engine_remove_wait(struct intel_engine_cs *engine,
			      struct intel_wait *wait)
{
	struct intel_breadcrumbs *b = &engine->breadcrumbs;

	/* Quick check to see if this waiter was already decoupled from
	 * the tree by the bottom-half to avoid contention on the spinlock
	 * by the herd.
	 */
569 570
	if (RB_EMPTY_NODE(&wait->node)) {
		GEM_BUG_ON(READ_ONCE(b->irq_wait) == wait);
571
		return;
572
	}
573

574
	spin_lock_irq(&b->rb_lock);
575
	__intel_engine_remove_wait(engine, wait);
576
	spin_unlock_irq(&b->rb_lock);
577 578
}

579 580 581 582 583 584
static bool signal_valid(const struct drm_i915_gem_request *request)
{
	return intel_wait_check_request(&request->signaling.wait, request);
}

static bool signal_complete(const struct drm_i915_gem_request *request)
585
{
586
	if (!request)
587 588 589 590 591
		return false;

	/* If another process served as the bottom-half it may have already
	 * signalled that this wait is already completed.
	 */
592
	if (intel_wait_complete(&request->signaling.wait))
593
		return signal_valid(request);
594 595 596 597

	/* Carefully check if the request is complete, giving time for the
	 * seqno to be visible or if the GPU hung.
	 */
598
	if (__i915_request_irq_complete(request))
599 600 601 602 603
		return true;

	return false;
}

604
static struct drm_i915_gem_request *to_signaler(struct rb_node *rb)
605
{
606
	return rb_entry(rb, struct drm_i915_gem_request, signaling.node);
607 608 609 610 611 612 613 614 615 616 617 618 619
}

static void signaler_set_rtpriority(void)
{
	 struct sched_param param = { .sched_priority = 1 };

	 sched_setscheduler_nocheck(current, SCHED_FIFO, &param);
}

static int intel_breadcrumbs_signaler(void *arg)
{
	struct intel_engine_cs *engine = arg;
	struct intel_breadcrumbs *b = &engine->breadcrumbs;
620
	struct drm_i915_gem_request *request;
621 622 623 624 625

	/* Install ourselves with high priority to reduce signalling latency */
	signaler_set_rtpriority();

	do {
626 627
		bool do_schedule = true;

628 629 630 631 632 633 634 635 636 637
		set_current_state(TASK_INTERRUPTIBLE);

		/* We are either woken up by the interrupt bottom-half,
		 * or by a client adding a new signaller. In both cases,
		 * the GPU seqno may have advanced beyond our oldest signal.
		 * If it has, propagate the signal, remove the waiter and
		 * check again with the next oldest signal. Otherwise we
		 * need to wait for a new interrupt from the GPU or for
		 * a new client.
		 */
638 639 640 641 642
		rcu_read_lock();
		request = rcu_dereference(b->first_signal);
		if (request)
			request = i915_gem_request_get_rcu(request);
		rcu_read_unlock();
643
		if (signal_complete(request)) {
644 645 646 647
			local_bh_disable();
			dma_fence_signal(&request->fence);
			local_bh_enable(); /* kick start the tasklets */

648
			spin_lock_irq(&b->rb_lock);
649

650 651 652
			/* Wake up all other completed waiters and select the
			 * next bottom-half for the next user interrupt.
			 */
653 654
			__intel_engine_remove_wait(engine,
						   &request->signaling.wait);
655

656 657 658 659 660 661
			/* Find the next oldest signal. Note that as we have
			 * not been holding the lock, another client may
			 * have installed an even older signal than the one
			 * we just completed - so double check we are still
			 * the oldest before picking the next one.
			 */
662
			if (request == rcu_access_pointer(b->first_signal)) {
663 664
				struct rb_node *rb =
					rb_next(&request->signaling.node);
665 666
				rcu_assign_pointer(b->first_signal,
						   rb ? to_signaler(rb) : NULL);
667 668
			}
			rb_erase(&request->signaling.node, &b->signals);
669 670
			RB_CLEAR_NODE(&request->signaling.node);

671
			spin_unlock_irq(&b->rb_lock);
672

673
			i915_gem_request_put(request);
674 675 676 677 678 679 680 681 682 683 684 685

			/* If the engine is saturated we may be continually
			 * processing completed requests. This angers the
			 * NMI watchdog if we never let anything else
			 * have access to the CPU. Let's pretend to be nice
			 * and relinquish the CPU if we burn through the
			 * entire RT timeslice!
			 */
			do_schedule = need_resched();
		}

		if (unlikely(do_schedule)) {
686 687
			DEFINE_WAIT(exec);

688 689 690
			if (kthread_should_park())
				kthread_parkme();

691 692
			if (kthread_should_stop()) {
				GEM_BUG_ON(request);
693
				break;
694
			}
695

696 697 698
			if (request)
				add_wait_queue(&request->execute, &exec);

699
			schedule();
700

701 702
			if (request)
				remove_wait_queue(&request->execute, &exec);
703
		}
704
		i915_gem_request_put(request);
705 706 707 708 709 710
	} while (1);
	__set_current_state(TASK_RUNNING);

	return 0;
}

711 712
void intel_engine_enable_signaling(struct drm_i915_gem_request *request,
				   bool wakeup)
713 714 715
{
	struct intel_engine_cs *engine = request->engine;
	struct intel_breadcrumbs *b = &engine->breadcrumbs;
716
	u32 seqno;
717

718 719 720
	/* Note that we may be called from an interrupt handler on another
	 * device (e.g. nouveau signaling a fence completion causing us
	 * to submit a request, and so enable signaling). As such,
721
	 * we need to make sure that all other users of b->rb_lock protect
722 723 724 725
	 * against interrupts, i.e. use spin_lock_irqsave.
	 */

	/* locked by dma_fence_enable_sw_signaling() (irqsafe fence->lock) */
726
	GEM_BUG_ON(!irqs_disabled());
727
	lockdep_assert_held(&request->lock);
728 729 730

	seqno = i915_gem_request_global_seqno(request);
	if (!seqno)
731
		return;
732

733
	request->signaling.wait.tsk = b->signaler;
734
	request->signaling.wait.request = request;
735
	request->signaling.wait.seqno = seqno;
736
	i915_gem_request_get(request);
737

738
	spin_lock(&b->rb_lock);
739

740 741 742 743 744 745 746 747
	/* First add ourselves into the list of waiters, but register our
	 * bottom-half as the signaller thread. As per usual, only the oldest
	 * waiter (not just signaller) is tasked as the bottom-half waking
	 * up all completed waiters after the user interrupt.
	 *
	 * If we are the oldest waiter, enable the irq (after which we
	 * must double check that the seqno did not complete).
	 */
748
	wakeup &= __intel_engine_add_wait(engine, &request->signaling.wait);
749

750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
	if (!__i915_gem_request_completed(request, seqno)) {
		struct rb_node *parent, **p;
		bool first;

		/* Now insert ourselves into the retirement ordered list of
		 * signals on this engine. We track the oldest seqno as that
		 * will be the first signal to complete.
		 */
		parent = NULL;
		first = true;
		p = &b->signals.rb_node;
		while (*p) {
			parent = *p;
			if (i915_seqno_passed(seqno,
					      to_signaler(parent)->signaling.wait.seqno)) {
				p = &parent->rb_right;
				first = false;
			} else {
				p = &parent->rb_left;
			}
770
		}
771 772 773 774 775 776 777 778
		rb_link_node(&request->signaling.node, parent, p);
		rb_insert_color(&request->signaling.node, &b->signals);
		if (first)
			rcu_assign_pointer(b->first_signal, request);
	} else {
		__intel_engine_remove_wait(engine, &request->signaling.wait);
		i915_gem_request_put(request);
		wakeup = false;
779
	}
780

781
	spin_unlock(&b->rb_lock);
782 783 784 785 786

	if (wakeup)
		wake_up_process(b->signaler);
}

787 788 789 790 791
void intel_engine_cancel_signaling(struct drm_i915_gem_request *request)
{
	struct intel_engine_cs *engine = request->engine;
	struct intel_breadcrumbs *b = &engine->breadcrumbs;

792
	GEM_BUG_ON(!irqs_disabled());
793
	lockdep_assert_held(&request->lock);
794 795
	GEM_BUG_ON(!request->signaling.wait.seqno);

796
	spin_lock(&b->rb_lock);
797 798 799 800 801 802 803 804 805 806 807 808 809 810 811

	if (!RB_EMPTY_NODE(&request->signaling.node)) {
		if (request == rcu_access_pointer(b->first_signal)) {
			struct rb_node *rb =
				rb_next(&request->signaling.node);
			rcu_assign_pointer(b->first_signal,
					   rb ? to_signaler(rb) : NULL);
		}
		rb_erase(&request->signaling.node, &b->signals);
		RB_CLEAR_NODE(&request->signaling.node);
		i915_gem_request_put(request);
	}

	__intel_engine_remove_wait(engine, &request->signaling.wait);

812
	spin_unlock(&b->rb_lock);
813 814 815 816

	request->signaling.wait.seqno = 0;
}

817 818 819
int intel_engine_init_breadcrumbs(struct intel_engine_cs *engine)
{
	struct intel_breadcrumbs *b = &engine->breadcrumbs;
820
	struct task_struct *tsk;
821

822 823 824
	spin_lock_init(&b->rb_lock);
	spin_lock_init(&b->irq_lock);

825 826
	timer_setup(&b->fake_irq, intel_breadcrumbs_fake_irq, 0);
	timer_setup(&b->hangcheck, intel_breadcrumbs_hangcheck, 0);
827

828 829 830 831 832 833 834 835 836 837 838 839 840
	/* Spawn a thread to provide a common bottom-half for all signals.
	 * As this is an asynchronous interface we cannot steal the current
	 * task for handling the bottom-half to the user interrupt, therefore
	 * we create a thread to do the coherent seqno dance after the
	 * interrupt and then signal the waitqueue (via the dma-buf/fence).
	 */
	tsk = kthread_run(intel_breadcrumbs_signaler, engine,
			  "i915/signal:%d", engine->id);
	if (IS_ERR(tsk))
		return PTR_ERR(tsk);

	b->signaler = tsk;

841 842 843
	return 0;
}

844 845 846 847 848 849 850 851 852 853 854 855 856 857
static void cancel_fake_irq(struct intel_engine_cs *engine)
{
	struct intel_breadcrumbs *b = &engine->breadcrumbs;

	del_timer_sync(&b->hangcheck);
	del_timer_sync(&b->fake_irq);
	clear_bit(engine->id, &engine->i915->gpu_error.missed_irq_rings);
}

void intel_engine_reset_breadcrumbs(struct intel_engine_cs *engine)
{
	struct intel_breadcrumbs *b = &engine->breadcrumbs;

	cancel_fake_irq(engine);
858
	spin_lock_irq(&b->irq_lock);
859

860 861 862
	if (b->irq_enabled)
		irq_enable(engine);
	else
863
		irq_disable(engine);
864 865 866 867 868 869 870 871 872 873 874 875

	/* We set the IRQ_BREADCRUMB bit when we enable the irq presuming the
	 * GPU is active and may have already executed the MI_USER_INTERRUPT
	 * before the CPU is ready to receive. However, the engine is currently
	 * idle (we haven't started it yet), there is no possibility for a
	 * missed interrupt as we enabled the irq and so we can clear the
	 * immediate wakeup (until a real interrupt arrives for the waiter).
	 */
	clear_bit(ENGINE_IRQ_BREADCRUMB, &engine->irq_posted);

	if (b->irq_armed)
		enable_fake_irq(b);
876

877
	spin_unlock_irq(&b->irq_lock);
878 879
}

880 881 882 883
void intel_engine_fini_breadcrumbs(struct intel_engine_cs *engine)
{
	struct intel_breadcrumbs *b = &engine->breadcrumbs;

884
	/* The engines should be idle and all requests accounted for! */
885
	WARN_ON(READ_ONCE(b->irq_wait));
886
	WARN_ON(!RB_EMPTY_ROOT(&b->waiters));
887
	WARN_ON(rcu_access_pointer(b->first_signal));
888 889
	WARN_ON(!RB_EMPTY_ROOT(&b->signals));

890 891 892
	if (!IS_ERR_OR_NULL(b->signaler))
		kthread_stop(b->signaler);

893
	cancel_fake_irq(engine);
894 895
}

896
bool intel_breadcrumbs_busy(struct intel_engine_cs *engine)
897
{
898 899
	struct intel_breadcrumbs *b = &engine->breadcrumbs;
	bool busy = false;
900

901
	spin_lock_irq(&b->rb_lock);
902

903 904
	if (b->irq_wait) {
		wake_up_process(b->irq_wait->tsk);
905
		busy = true;
906
	}
907

908
	if (rcu_access_pointer(b->first_signal)) {
909
		wake_up_process(b->signaler);
910
		busy = true;
911 912
	}

913
	spin_unlock_irq(&b->rb_lock);
914 915

	return busy;
916
}
917 918 919 920

#if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
#include "selftests/intel_breadcrumbs.c"
#endif