• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 
3 #include <linux/plist.h>
4 #include <linux/sched/signal.h>
5 
6 #include "futex.h"
7 #include "../locking/rtmutex_common.h"
8 
9 /*
10  * On PREEMPT_RT, the hash bucket lock is a 'sleeping' spinlock with an
11  * underlying rtmutex. The task which is about to be requeued could have
12  * just woken up (timeout, signal). After the wake up the task has to
13  * acquire hash bucket lock, which is held by the requeue code.  As a task
14  * can only be blocked on _ONE_ rtmutex at a time, the proxy lock blocking
15  * and the hash bucket lock blocking would collide and corrupt state.
16  *
17  * On !PREEMPT_RT this is not a problem and everything could be serialized
18  * on hash bucket lock, but aside of having the benefit of common code,
19  * this allows to avoid doing the requeue when the task is already on the
20  * way out and taking the hash bucket lock of the original uaddr1 when the
21  * requeue has been completed.
22  *
23  * The following state transitions are valid:
24  *
25  * On the waiter side:
26  *   Q_REQUEUE_PI_NONE		-> Q_REQUEUE_PI_IGNORE
27  *   Q_REQUEUE_PI_IN_PROGRESS	-> Q_REQUEUE_PI_WAIT
28  *
29  * On the requeue side:
30  *   Q_REQUEUE_PI_NONE		-> Q_REQUEUE_PI_INPROGRESS
31  *   Q_REQUEUE_PI_IN_PROGRESS	-> Q_REQUEUE_PI_DONE/LOCKED
32  *   Q_REQUEUE_PI_IN_PROGRESS	-> Q_REQUEUE_PI_NONE (requeue failed)
33  *   Q_REQUEUE_PI_WAIT		-> Q_REQUEUE_PI_DONE/LOCKED
34  *   Q_REQUEUE_PI_WAIT		-> Q_REQUEUE_PI_IGNORE (requeue failed)
35  *
36  * The requeue side ignores a waiter with state Q_REQUEUE_PI_IGNORE as this
37  * signals that the waiter is already on the way out. It also means that
38  * the waiter is still on the 'wait' futex, i.e. uaddr1.
39  *
40  * The waiter side signals early wakeup to the requeue side either through
41  * setting state to Q_REQUEUE_PI_IGNORE or to Q_REQUEUE_PI_WAIT depending
42  * on the current state. In case of Q_REQUEUE_PI_IGNORE it can immediately
43  * proceed to take the hash bucket lock of uaddr1. If it set state to WAIT,
44  * which means the wakeup is interleaving with a requeue in progress it has
45  * to wait for the requeue side to change the state. Either to DONE/LOCKED
46  * or to IGNORE. DONE/LOCKED means the waiter q is now on the uaddr2 futex
47  * and either blocked (DONE) or has acquired it (LOCKED). IGNORE is set by
48  * the requeue side when the requeue attempt failed via deadlock detection
49  * and therefore the waiter q is still on the uaddr1 futex.
50  */
51 enum {
52 	Q_REQUEUE_PI_NONE		=  0,
53 	Q_REQUEUE_PI_IGNORE,
54 	Q_REQUEUE_PI_IN_PROGRESS,
55 	Q_REQUEUE_PI_WAIT,
56 	Q_REQUEUE_PI_DONE,
57 	Q_REQUEUE_PI_LOCKED,
58 };
59 
60 const struct futex_q futex_q_init = {
61 	/* list gets initialized in futex_queue()*/
62 	.wake		= futex_wake_mark,
63 	.key		= FUTEX_KEY_INIT,
64 	.bitset		= FUTEX_BITSET_MATCH_ANY,
65 	.requeue_state	= ATOMIC_INIT(Q_REQUEUE_PI_NONE),
66 };
67 
68 /**
69  * requeue_futex() - Requeue a futex_q from one hb to another
70  * @q:		the futex_q to requeue
71  * @hb1:	the source hash_bucket
72  * @hb2:	the target hash_bucket
73  * @key2:	the new key for the requeued futex_q
74  */
75 static inline
requeue_futex(struct futex_q * q,struct futex_hash_bucket * hb1,struct futex_hash_bucket * hb2,union futex_key * key2)76 void requeue_futex(struct futex_q *q, struct futex_hash_bucket *hb1,
77 		   struct futex_hash_bucket *hb2, union futex_key *key2)
78 {
79 
80 	/*
81 	 * If key1 and key2 hash to the same bucket, no need to
82 	 * requeue.
83 	 */
84 	if (likely(&hb1->chain != &hb2->chain)) {
85 		plist_del(&q->list, &hb1->chain);
86 		futex_hb_waiters_dec(hb1);
87 		futex_hb_waiters_inc(hb2);
88 		plist_add(&q->list, &hb2->chain);
89 		q->lock_ptr = &hb2->lock;
90 	}
91 	q->key = *key2;
92 }
93 
futex_requeue_pi_prepare(struct futex_q * q,struct futex_pi_state * pi_state)94 static inline bool futex_requeue_pi_prepare(struct futex_q *q,
95 					    struct futex_pi_state *pi_state)
96 {
97 	int old, new;
98 
99 	/*
100 	 * Set state to Q_REQUEUE_PI_IN_PROGRESS unless an early wakeup has
101 	 * already set Q_REQUEUE_PI_IGNORE to signal that requeue should
102 	 * ignore the waiter.
103 	 */
104 	old = atomic_read_acquire(&q->requeue_state);
105 	do {
106 		if (old == Q_REQUEUE_PI_IGNORE)
107 			return false;
108 
109 		/*
110 		 * futex_proxy_trylock_atomic() might have set it to
111 		 * IN_PROGRESS and a interleaved early wake to WAIT.
112 		 *
113 		 * It was considered to have an extra state for that
114 		 * trylock, but that would just add more conditionals
115 		 * all over the place for a dubious value.
116 		 */
117 		if (old != Q_REQUEUE_PI_NONE)
118 			break;
119 
120 		new = Q_REQUEUE_PI_IN_PROGRESS;
121 	} while (!atomic_try_cmpxchg(&q->requeue_state, &old, new));
122 
123 	q->pi_state = pi_state;
124 	return true;
125 }
126 
futex_requeue_pi_complete(struct futex_q * q,int locked)127 static inline void futex_requeue_pi_complete(struct futex_q *q, int locked)
128 {
129 	int old, new;
130 
131 	old = atomic_read_acquire(&q->requeue_state);
132 	do {
133 		if (old == Q_REQUEUE_PI_IGNORE)
134 			return;
135 
136 		if (locked >= 0) {
137 			/* Requeue succeeded. Set DONE or LOCKED */
138 			WARN_ON_ONCE(old != Q_REQUEUE_PI_IN_PROGRESS &&
139 				     old != Q_REQUEUE_PI_WAIT);
140 			new = Q_REQUEUE_PI_DONE + locked;
141 		} else if (old == Q_REQUEUE_PI_IN_PROGRESS) {
142 			/* Deadlock, no early wakeup interleave */
143 			new = Q_REQUEUE_PI_NONE;
144 		} else {
145 			/* Deadlock, early wakeup interleave. */
146 			WARN_ON_ONCE(old != Q_REQUEUE_PI_WAIT);
147 			new = Q_REQUEUE_PI_IGNORE;
148 		}
149 	} while (!atomic_try_cmpxchg(&q->requeue_state, &old, new));
150 
151 #ifdef CONFIG_PREEMPT_RT
152 	/* If the waiter interleaved with the requeue let it know */
153 	if (unlikely(old == Q_REQUEUE_PI_WAIT))
154 		rcuwait_wake_up(&q->requeue_wait);
155 #endif
156 }
157 
futex_requeue_pi_wakeup_sync(struct futex_q * q)158 static inline int futex_requeue_pi_wakeup_sync(struct futex_q *q)
159 {
160 	int old, new;
161 
162 	old = atomic_read_acquire(&q->requeue_state);
163 	do {
164 		/* Is requeue done already? */
165 		if (old >= Q_REQUEUE_PI_DONE)
166 			return old;
167 
168 		/*
169 		 * If not done, then tell the requeue code to either ignore
170 		 * the waiter or to wake it up once the requeue is done.
171 		 */
172 		new = Q_REQUEUE_PI_WAIT;
173 		if (old == Q_REQUEUE_PI_NONE)
174 			new = Q_REQUEUE_PI_IGNORE;
175 	} while (!atomic_try_cmpxchg(&q->requeue_state, &old, new));
176 
177 	/* If the requeue was in progress, wait for it to complete */
178 	if (old == Q_REQUEUE_PI_IN_PROGRESS) {
179 #ifdef CONFIG_PREEMPT_RT
180 		rcuwait_wait_event(&q->requeue_wait,
181 				   atomic_read(&q->requeue_state) != Q_REQUEUE_PI_WAIT,
182 				   TASK_UNINTERRUPTIBLE);
183 #else
184 		(void)atomic_cond_read_relaxed(&q->requeue_state, VAL != Q_REQUEUE_PI_WAIT);
185 #endif
186 	}
187 
188 	/*
189 	 * Requeue is now either prohibited or complete. Reread state
190 	 * because during the wait above it might have changed. Nothing
191 	 * will modify q->requeue_state after this point.
192 	 */
193 	return atomic_read(&q->requeue_state);
194 }
195 
196 /**
197  * requeue_pi_wake_futex() - Wake a task that acquired the lock during requeue
198  * @q:		the futex_q
199  * @key:	the key of the requeue target futex
200  * @hb:		the hash_bucket of the requeue target futex
201  *
202  * During futex_requeue, with requeue_pi=1, it is possible to acquire the
203  * target futex if it is uncontended or via a lock steal.
204  *
205  * 1) Set @q::key to the requeue target futex key so the waiter can detect
206  *    the wakeup on the right futex.
207  *
208  * 2) Dequeue @q from the hash bucket.
209  *
210  * 3) Set @q::rt_waiter to NULL so the woken up task can detect atomic lock
211  *    acquisition.
212  *
213  * 4) Set the q->lock_ptr to the requeue target hb->lock for the case that
214  *    the waiter has to fixup the pi state.
215  *
216  * 5) Complete the requeue state so the waiter can make progress. After
217  *    this point the waiter task can return from the syscall immediately in
218  *    case that the pi state does not have to be fixed up.
219  *
220  * 6) Wake the waiter task.
221  *
222  * Must be called with both q->lock_ptr and hb->lock held.
223  */
224 static inline
requeue_pi_wake_futex(struct futex_q * q,union futex_key * key,struct futex_hash_bucket * hb)225 void requeue_pi_wake_futex(struct futex_q *q, union futex_key *key,
226 			   struct futex_hash_bucket *hb)
227 {
228 	struct task_struct *task;
229 
230 	q->key = *key;
231 	__futex_unqueue(q);
232 
233 	WARN_ON(!q->rt_waiter);
234 	q->rt_waiter = NULL;
235 
236 	q->lock_ptr = &hb->lock;
237 	task = READ_ONCE(q->task);
238 
239 	/* Signal locked state to the waiter */
240 	futex_requeue_pi_complete(q, 1);
241 	wake_up_state(task, TASK_NORMAL);
242 }
243 
244 /**
245  * futex_proxy_trylock_atomic() - Attempt an atomic lock for the top waiter
246  * @pifutex:		the user address of the to futex
247  * @hb1:		the from futex hash bucket, must be locked by the caller
248  * @hb2:		the to futex hash bucket, must be locked by the caller
249  * @key1:		the from futex key
250  * @key2:		the to futex key
251  * @ps:			address to store the pi_state pointer
252  * @exiting:		Pointer to store the task pointer of the owner task
253  *			which is in the middle of exiting
254  * @set_waiters:	force setting the FUTEX_WAITERS bit (1) or not (0)
255  *
256  * Try and get the lock on behalf of the top waiter if we can do it atomically.
257  * Wake the top waiter if we succeed.  If the caller specified set_waiters,
258  * then direct futex_lock_pi_atomic() to force setting the FUTEX_WAITERS bit.
259  * hb1 and hb2 must be held by the caller.
260  *
261  * @exiting is only set when the return value is -EBUSY. If so, this holds
262  * a refcount on the exiting task on return and the caller needs to drop it
263  * after waiting for the exit to complete.
264  *
265  * Return:
266  *  -  0 - failed to acquire the lock atomically;
267  *  - >0 - acquired the lock, return value is vpid of the top_waiter
268  *  - <0 - error
269  */
270 static int
futex_proxy_trylock_atomic(u32 __user * pifutex,struct futex_hash_bucket * hb1,struct futex_hash_bucket * hb2,union futex_key * key1,union futex_key * key2,struct futex_pi_state ** ps,struct task_struct ** exiting,int set_waiters)271 futex_proxy_trylock_atomic(u32 __user *pifutex, struct futex_hash_bucket *hb1,
272 			   struct futex_hash_bucket *hb2, union futex_key *key1,
273 			   union futex_key *key2, struct futex_pi_state **ps,
274 			   struct task_struct **exiting, int set_waiters)
275 {
276 	struct futex_q *top_waiter;
277 	u32 curval;
278 	int ret;
279 
280 	if (futex_get_value_locked(&curval, pifutex))
281 		return -EFAULT;
282 
283 	if (unlikely(should_fail_futex(true)))
284 		return -EFAULT;
285 
286 	/*
287 	 * Find the top_waiter and determine if there are additional waiters.
288 	 * If the caller intends to requeue more than 1 waiter to pifutex,
289 	 * force futex_lock_pi_atomic() to set the FUTEX_WAITERS bit now,
290 	 * as we have means to handle the possible fault.  If not, don't set
291 	 * the bit unnecessarily as it will force the subsequent unlock to enter
292 	 * the kernel.
293 	 */
294 	top_waiter = futex_top_waiter(hb1, key1);
295 
296 	/* There are no waiters, nothing for us to do. */
297 	if (!top_waiter)
298 		return 0;
299 
300 	/*
301 	 * Ensure that this is a waiter sitting in futex_wait_requeue_pi()
302 	 * and waiting on the 'waitqueue' futex which is always !PI.
303 	 */
304 	if (!top_waiter->rt_waiter || top_waiter->pi_state)
305 		return -EINVAL;
306 
307 	/* Ensure we requeue to the expected futex. */
308 	if (!futex_match(top_waiter->requeue_pi_key, key2))
309 		return -EINVAL;
310 
311 	/* Ensure that this does not race against an early wakeup */
312 	if (!futex_requeue_pi_prepare(top_waiter, NULL))
313 		return -EAGAIN;
314 
315 	/*
316 	 * Try to take the lock for top_waiter and set the FUTEX_WAITERS bit
317 	 * in the contended case or if @set_waiters is true.
318 	 *
319 	 * In the contended case PI state is attached to the lock owner. If
320 	 * the user space lock can be acquired then PI state is attached to
321 	 * the new owner (@top_waiter->task) when @set_waiters is true.
322 	 */
323 	ret = futex_lock_pi_atomic(pifutex, hb2, key2, ps, top_waiter->task,
324 				   exiting, set_waiters);
325 	if (ret == 1) {
326 		/*
327 		 * Lock was acquired in user space and PI state was
328 		 * attached to @top_waiter->task. That means state is fully
329 		 * consistent and the waiter can return to user space
330 		 * immediately after the wakeup.
331 		 */
332 		requeue_pi_wake_futex(top_waiter, key2, hb2);
333 	} else if (ret < 0) {
334 		/* Rewind top_waiter::requeue_state */
335 		futex_requeue_pi_complete(top_waiter, ret);
336 	} else {
337 		/*
338 		 * futex_lock_pi_atomic() did not acquire the user space
339 		 * futex, but managed to establish the proxy lock and pi
340 		 * state. top_waiter::requeue_state cannot be fixed up here
341 		 * because the waiter is not enqueued on the rtmutex
342 		 * yet. This is handled at the callsite depending on the
343 		 * result of rt_mutex_start_proxy_lock() which is
344 		 * guaranteed to be reached with this function returning 0.
345 		 */
346 	}
347 	return ret;
348 }
349 
350 /**
351  * futex_requeue() - Requeue waiters from uaddr1 to uaddr2
352  * @uaddr1:	source futex user address
353  * @flags1:	futex flags (FLAGS_SHARED, etc.)
354  * @uaddr2:	target futex user address
355  * @flags2:	futex flags (FLAGS_SHARED, etc.)
356  * @nr_wake:	number of waiters to wake (must be 1 for requeue_pi)
357  * @nr_requeue:	number of waiters to requeue (0-INT_MAX)
358  * @cmpval:	@uaddr1 expected value (or %NULL)
359  * @requeue_pi:	if we are attempting to requeue from a non-pi futex to a
360  *		pi futex (pi to pi requeue is not supported)
361  *
362  * Requeue waiters on uaddr1 to uaddr2. In the requeue_pi case, try to acquire
363  * uaddr2 atomically on behalf of the top waiter.
364  *
365  * Return:
366  *  - >=0 - on success, the number of tasks requeued or woken;
367  *  -  <0 - on error
368  */
futex_requeue(u32 __user * uaddr1,unsigned int flags1,u32 __user * uaddr2,unsigned int flags2,int nr_wake,int nr_requeue,u32 * cmpval,int requeue_pi)369 int futex_requeue(u32 __user *uaddr1, unsigned int flags1,
370 		  u32 __user *uaddr2, unsigned int flags2,
371 		  int nr_wake, int nr_requeue, u32 *cmpval, int requeue_pi)
372 {
373 	union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT;
374 	int task_count = 0, ret;
375 	struct futex_pi_state *pi_state = NULL;
376 	struct futex_hash_bucket *hb1, *hb2;
377 	struct futex_q *this, *next;
378 	DEFINE_WAKE_Q(wake_q);
379 
380 	if (nr_wake < 0 || nr_requeue < 0)
381 		return -EINVAL;
382 
383 	/*
384 	 * When PI not supported: return -ENOSYS if requeue_pi is true,
385 	 * consequently the compiler knows requeue_pi is always false past
386 	 * this point which will optimize away all the conditional code
387 	 * further down.
388 	 */
389 	if (!IS_ENABLED(CONFIG_FUTEX_PI) && requeue_pi)
390 		return -ENOSYS;
391 
392 	if (requeue_pi) {
393 		/*
394 		 * Requeue PI only works on two distinct uaddrs. This
395 		 * check is only valid for private futexes. See below.
396 		 */
397 		if (uaddr1 == uaddr2)
398 			return -EINVAL;
399 
400 		/*
401 		 * futex_requeue() allows the caller to define the number
402 		 * of waiters to wake up via the @nr_wake argument. With
403 		 * REQUEUE_PI, waking up more than one waiter is creating
404 		 * more problems than it solves. Waking up a waiter makes
405 		 * only sense if the PI futex @uaddr2 is uncontended as
406 		 * this allows the requeue code to acquire the futex
407 		 * @uaddr2 before waking the waiter. The waiter can then
408 		 * return to user space without further action. A secondary
409 		 * wakeup would just make the futex_wait_requeue_pi()
410 		 * handling more complex, because that code would have to
411 		 * look up pi_state and do more or less all the handling
412 		 * which the requeue code has to do for the to be requeued
413 		 * waiters. So restrict the number of waiters to wake to
414 		 * one, and only wake it up when the PI futex is
415 		 * uncontended. Otherwise requeue it and let the unlock of
416 		 * the PI futex handle the wakeup.
417 		 *
418 		 * All REQUEUE_PI users, e.g. pthread_cond_signal() and
419 		 * pthread_cond_broadcast() must use nr_wake=1.
420 		 */
421 		if (nr_wake != 1)
422 			return -EINVAL;
423 
424 		/*
425 		 * requeue_pi requires a pi_state, try to allocate it now
426 		 * without any locks in case it fails.
427 		 */
428 		if (refill_pi_state_cache())
429 			return -ENOMEM;
430 	}
431 
432 retry:
433 	ret = get_futex_key(uaddr1, flags1, &key1, FUTEX_READ);
434 	if (unlikely(ret != 0))
435 		return ret;
436 	ret = get_futex_key(uaddr2, flags2, &key2,
437 			    requeue_pi ? FUTEX_WRITE : FUTEX_READ);
438 	if (unlikely(ret != 0))
439 		return ret;
440 
441 	/*
442 	 * The check above which compares uaddrs is not sufficient for
443 	 * shared futexes. We need to compare the keys:
444 	 */
445 	if (requeue_pi && futex_match(&key1, &key2))
446 		return -EINVAL;
447 
448 	hb1 = futex_hash(&key1);
449 	hb2 = futex_hash(&key2);
450 
451 retry_private:
452 	futex_hb_waiters_inc(hb2);
453 	double_lock_hb(hb1, hb2);
454 
455 	if (likely(cmpval != NULL)) {
456 		u32 curval;
457 
458 		ret = futex_get_value_locked(&curval, uaddr1);
459 
460 		if (unlikely(ret)) {
461 			double_unlock_hb(hb1, hb2);
462 			futex_hb_waiters_dec(hb2);
463 
464 			ret = get_user(curval, uaddr1);
465 			if (ret)
466 				return ret;
467 
468 			if (!(flags1 & FLAGS_SHARED))
469 				goto retry_private;
470 
471 			goto retry;
472 		}
473 		if (curval != *cmpval) {
474 			ret = -EAGAIN;
475 			goto out_unlock;
476 		}
477 	}
478 
479 	if (requeue_pi) {
480 		struct task_struct *exiting = NULL;
481 
482 		/*
483 		 * Attempt to acquire uaddr2 and wake the top waiter. If we
484 		 * intend to requeue waiters, force setting the FUTEX_WAITERS
485 		 * bit.  We force this here where we are able to easily handle
486 		 * faults rather in the requeue loop below.
487 		 *
488 		 * Updates topwaiter::requeue_state if a top waiter exists.
489 		 */
490 		ret = futex_proxy_trylock_atomic(uaddr2, hb1, hb2, &key1,
491 						 &key2, &pi_state,
492 						 &exiting, nr_requeue);
493 
494 		/*
495 		 * At this point the top_waiter has either taken uaddr2 or
496 		 * is waiting on it. In both cases pi_state has been
497 		 * established and an initial refcount on it. In case of an
498 		 * error there's nothing.
499 		 *
500 		 * The top waiter's requeue_state is up to date:
501 		 *
502 		 *  - If the lock was acquired atomically (ret == 1), then
503 		 *    the state is Q_REQUEUE_PI_LOCKED.
504 		 *
505 		 *    The top waiter has been dequeued and woken up and can
506 		 *    return to user space immediately. The kernel/user
507 		 *    space state is consistent. In case that there must be
508 		 *    more waiters requeued the WAITERS bit in the user
509 		 *    space futex is set so the top waiter task has to go
510 		 *    into the syscall slowpath to unlock the futex. This
511 		 *    will block until this requeue operation has been
512 		 *    completed and the hash bucket locks have been
513 		 *    dropped.
514 		 *
515 		 *  - If the trylock failed with an error (ret < 0) then
516 		 *    the state is either Q_REQUEUE_PI_NONE, i.e. "nothing
517 		 *    happened", or Q_REQUEUE_PI_IGNORE when there was an
518 		 *    interleaved early wakeup.
519 		 *
520 		 *  - If the trylock did not succeed (ret == 0) then the
521 		 *    state is either Q_REQUEUE_PI_IN_PROGRESS or
522 		 *    Q_REQUEUE_PI_WAIT if an early wakeup interleaved.
523 		 *    This will be cleaned up in the loop below, which
524 		 *    cannot fail because futex_proxy_trylock_atomic() did
525 		 *    the same sanity checks for requeue_pi as the loop
526 		 *    below does.
527 		 */
528 		switch (ret) {
529 		case 0:
530 			/* We hold a reference on the pi state. */
531 			break;
532 
533 		case 1:
534 			/*
535 			 * futex_proxy_trylock_atomic() acquired the user space
536 			 * futex. Adjust task_count.
537 			 */
538 			task_count++;
539 			ret = 0;
540 			break;
541 
542 		/*
543 		 * If the above failed, then pi_state is NULL and
544 		 * waiter::requeue_state is correct.
545 		 */
546 		case -EFAULT:
547 			double_unlock_hb(hb1, hb2);
548 			futex_hb_waiters_dec(hb2);
549 			ret = fault_in_user_writeable(uaddr2);
550 			if (!ret)
551 				goto retry;
552 			return ret;
553 		case -EBUSY:
554 		case -EAGAIN:
555 			/*
556 			 * Two reasons for this:
557 			 * - EBUSY: Owner is exiting and we just wait for the
558 			 *   exit to complete.
559 			 * - EAGAIN: The user space value changed.
560 			 */
561 			double_unlock_hb(hb1, hb2);
562 			futex_hb_waiters_dec(hb2);
563 			/*
564 			 * Handle the case where the owner is in the middle of
565 			 * exiting. Wait for the exit to complete otherwise
566 			 * this task might loop forever, aka. live lock.
567 			 */
568 			wait_for_owner_exiting(ret, exiting);
569 			cond_resched();
570 			goto retry;
571 		default:
572 			goto out_unlock;
573 		}
574 	}
575 
576 	plist_for_each_entry_safe(this, next, &hb1->chain, list) {
577 		if (task_count - nr_wake >= nr_requeue)
578 			break;
579 
580 		if (!futex_match(&this->key, &key1))
581 			continue;
582 
583 		/*
584 		 * FUTEX_WAIT_REQUEUE_PI and FUTEX_CMP_REQUEUE_PI should always
585 		 * be paired with each other and no other futex ops.
586 		 *
587 		 * We should never be requeueing a futex_q with a pi_state,
588 		 * which is awaiting a futex_unlock_pi().
589 		 */
590 		if ((requeue_pi && !this->rt_waiter) ||
591 		    (!requeue_pi && this->rt_waiter) ||
592 		    this->pi_state) {
593 			ret = -EINVAL;
594 			break;
595 		}
596 
597 		/* Plain futexes just wake or requeue and are done */
598 		if (!requeue_pi) {
599 			if (++task_count <= nr_wake)
600 				this->wake(&wake_q, this);
601 			else
602 				requeue_futex(this, hb1, hb2, &key2);
603 			continue;
604 		}
605 
606 		/* Ensure we requeue to the expected futex for requeue_pi. */
607 		if (!futex_match(this->requeue_pi_key, &key2)) {
608 			ret = -EINVAL;
609 			break;
610 		}
611 
612 		/*
613 		 * Requeue nr_requeue waiters and possibly one more in the case
614 		 * of requeue_pi if we couldn't acquire the lock atomically.
615 		 *
616 		 * Prepare the waiter to take the rt_mutex. Take a refcount
617 		 * on the pi_state and store the pointer in the futex_q
618 		 * object of the waiter.
619 		 */
620 		get_pi_state(pi_state);
621 
622 		/* Don't requeue when the waiter is already on the way out. */
623 		if (!futex_requeue_pi_prepare(this, pi_state)) {
624 			/*
625 			 * Early woken waiter signaled that it is on the
626 			 * way out. Drop the pi_state reference and try the
627 			 * next waiter. @this->pi_state is still NULL.
628 			 */
629 			put_pi_state(pi_state);
630 			continue;
631 		}
632 
633 		ret = rt_mutex_start_proxy_lock(&pi_state->pi_mutex,
634 						this->rt_waiter,
635 						this->task);
636 
637 		if (ret == 1) {
638 			/*
639 			 * We got the lock. We do neither drop the refcount
640 			 * on pi_state nor clear this->pi_state because the
641 			 * waiter needs the pi_state for cleaning up the
642 			 * user space value. It will drop the refcount
643 			 * after doing so. this::requeue_state is updated
644 			 * in the wakeup as well.
645 			 */
646 			requeue_pi_wake_futex(this, &key2, hb2);
647 			task_count++;
648 		} else if (!ret) {
649 			/* Waiter is queued, move it to hb2 */
650 			requeue_futex(this, hb1, hb2, &key2);
651 			futex_requeue_pi_complete(this, 0);
652 			task_count++;
653 		} else {
654 			/*
655 			 * rt_mutex_start_proxy_lock() detected a potential
656 			 * deadlock when we tried to queue that waiter.
657 			 * Drop the pi_state reference which we took above
658 			 * and remove the pointer to the state from the
659 			 * waiters futex_q object.
660 			 */
661 			this->pi_state = NULL;
662 			put_pi_state(pi_state);
663 			futex_requeue_pi_complete(this, ret);
664 			/*
665 			 * We stop queueing more waiters and let user space
666 			 * deal with the mess.
667 			 */
668 			break;
669 		}
670 	}
671 
672 	/*
673 	 * We took an extra initial reference to the pi_state in
674 	 * futex_proxy_trylock_atomic(). We need to drop it here again.
675 	 */
676 	put_pi_state(pi_state);
677 
678 out_unlock:
679 	double_unlock_hb(hb1, hb2);
680 	wake_up_q(&wake_q);
681 	futex_hb_waiters_dec(hb2);
682 	return ret ? ret : task_count;
683 }
684 
685 /**
686  * handle_early_requeue_pi_wakeup() - Handle early wakeup on the initial futex
687  * @hb:		the hash_bucket futex_q was original enqueued on
688  * @q:		the futex_q woken while waiting to be requeued
689  * @timeout:	the timeout associated with the wait (NULL if none)
690  *
691  * Determine the cause for the early wakeup.
692  *
693  * Return:
694  *  -EWOULDBLOCK or -ETIMEDOUT or -ERESTARTNOINTR
695  */
696 static inline
handle_early_requeue_pi_wakeup(struct futex_hash_bucket * hb,struct futex_q * q,struct hrtimer_sleeper * timeout)697 int handle_early_requeue_pi_wakeup(struct futex_hash_bucket *hb,
698 				   struct futex_q *q,
699 				   struct hrtimer_sleeper *timeout)
700 {
701 	int ret;
702 
703 	/*
704 	 * With the hb lock held, we avoid races while we process the wakeup.
705 	 * We only need to hold hb (and not hb2) to ensure atomicity as the
706 	 * wakeup code can't change q.key from uaddr to uaddr2 if we hold hb.
707 	 * It can't be requeued from uaddr2 to something else since we don't
708 	 * support a PI aware source futex for requeue.
709 	 */
710 	WARN_ON_ONCE(&hb->lock != q->lock_ptr);
711 
712 	/*
713 	 * We were woken prior to requeue by a timeout or a signal.
714 	 * Unqueue the futex_q and determine which it was.
715 	 */
716 	plist_del(&q->list, &hb->chain);
717 	futex_hb_waiters_dec(hb);
718 
719 	/* Handle spurious wakeups gracefully */
720 	ret = -EWOULDBLOCK;
721 	if (timeout && !timeout->task)
722 		ret = -ETIMEDOUT;
723 	else if (signal_pending(current))
724 		ret = -ERESTARTNOINTR;
725 	return ret;
726 }
727 
728 /**
729  * futex_wait_requeue_pi() - Wait on uaddr and take uaddr2
730  * @uaddr:	the futex we initially wait on (non-pi)
731  * @flags:	futex flags (FLAGS_SHARED, FLAGS_CLOCKRT, etc.), they must be
732  *		the same type, no requeueing from private to shared, etc.
733  * @val:	the expected value of uaddr
734  * @abs_time:	absolute timeout
735  * @bitset:	32 bit wakeup bitset set by userspace, defaults to all
736  * @uaddr2:	the pi futex we will take prior to returning to user-space
737  *
738  * The caller will wait on uaddr and will be requeued by futex_requeue() to
739  * uaddr2 which must be PI aware and unique from uaddr.  Normal wakeup will wake
740  * on uaddr2 and complete the acquisition of the rt_mutex prior to returning to
741  * userspace.  This ensures the rt_mutex maintains an owner when it has waiters;
742  * without one, the pi logic would not know which task to boost/deboost, if
743  * there was a need to.
744  *
745  * We call schedule in futex_wait_queue() when we enqueue and return there
746  * via the following--
747  * 1) wakeup on uaddr2 after an atomic lock acquisition by futex_requeue()
748  * 2) wakeup on uaddr2 after a requeue
749  * 3) signal
750  * 4) timeout
751  *
752  * If 3, cleanup and return -ERESTARTNOINTR.
753  *
754  * If 2, we may then block on trying to take the rt_mutex and return via:
755  * 5) successful lock
756  * 6) signal
757  * 7) timeout
758  * 8) other lock acquisition failure
759  *
760  * If 6, return -EWOULDBLOCK (restarting the syscall would do the same).
761  *
762  * If 4 or 7, we cleanup and return with -ETIMEDOUT.
763  *
764  * Return:
765  *  -  0 - On success;
766  *  - <0 - On error
767  */
futex_wait_requeue_pi(u32 __user * uaddr,unsigned int flags,u32 val,ktime_t * abs_time,u32 bitset,u32 __user * uaddr2)768 int futex_wait_requeue_pi(u32 __user *uaddr, unsigned int flags,
769 			  u32 val, ktime_t *abs_time, u32 bitset,
770 			  u32 __user *uaddr2)
771 {
772 	struct hrtimer_sleeper timeout, *to;
773 	struct rt_mutex_waiter rt_waiter;
774 	struct futex_hash_bucket *hb;
775 	union futex_key key2 = FUTEX_KEY_INIT;
776 	struct futex_q q = futex_q_init;
777 	struct rt_mutex_base *pi_mutex;
778 	int res, ret;
779 
780 	if (!IS_ENABLED(CONFIG_FUTEX_PI))
781 		return -ENOSYS;
782 
783 	if (uaddr == uaddr2)
784 		return -EINVAL;
785 
786 	if (!bitset)
787 		return -EINVAL;
788 
789 	to = futex_setup_timer(abs_time, &timeout, flags,
790 			       current->timer_slack_ns);
791 
792 	/*
793 	 * The waiter is allocated on our stack, manipulated by the requeue
794 	 * code while we sleep on uaddr.
795 	 */
796 	rt_mutex_init_waiter(&rt_waiter);
797 
798 	ret = get_futex_key(uaddr2, flags, &key2, FUTEX_WRITE);
799 	if (unlikely(ret != 0))
800 		goto out;
801 
802 	q.bitset = bitset;
803 	q.rt_waiter = &rt_waiter;
804 	q.requeue_pi_key = &key2;
805 
806 	/*
807 	 * Prepare to wait on uaddr. On success, it holds hb->lock and q
808 	 * is initialized.
809 	 */
810 	ret = futex_wait_setup(uaddr, val, flags, &q, &hb);
811 	if (ret)
812 		goto out;
813 
814 	/*
815 	 * The check above which compares uaddrs is not sufficient for
816 	 * shared futexes. We need to compare the keys:
817 	 */
818 	if (futex_match(&q.key, &key2)) {
819 		futex_q_unlock(hb);
820 		ret = -EINVAL;
821 		goto out;
822 	}
823 
824 	/* Queue the futex_q, drop the hb lock, wait for wakeup. */
825 	futex_wait_queue(hb, &q, to);
826 
827 	switch (futex_requeue_pi_wakeup_sync(&q)) {
828 	case Q_REQUEUE_PI_IGNORE:
829 		/* The waiter is still on uaddr1 */
830 		spin_lock(&hb->lock);
831 		ret = handle_early_requeue_pi_wakeup(hb, &q, to);
832 		spin_unlock(&hb->lock);
833 		break;
834 
835 	case Q_REQUEUE_PI_LOCKED:
836 		/* The requeue acquired the lock */
837 		if (q.pi_state && (q.pi_state->owner != current)) {
838 			spin_lock(q.lock_ptr);
839 			ret = fixup_pi_owner(uaddr2, &q, true);
840 			/*
841 			 * Drop the reference to the pi state which the
842 			 * requeue_pi() code acquired for us.
843 			 */
844 			put_pi_state(q.pi_state);
845 			spin_unlock(q.lock_ptr);
846 			/*
847 			 * Adjust the return value. It's either -EFAULT or
848 			 * success (1) but the caller expects 0 for success.
849 			 */
850 			ret = ret < 0 ? ret : 0;
851 		}
852 		break;
853 
854 	case Q_REQUEUE_PI_DONE:
855 		/* Requeue completed. Current is 'pi_blocked_on' the rtmutex */
856 		pi_mutex = &q.pi_state->pi_mutex;
857 		ret = rt_mutex_wait_proxy_lock(pi_mutex, to, &rt_waiter);
858 
859 		/*
860 		 * See futex_unlock_pi()'s cleanup: comment.
861 		 */
862 		if (ret && !rt_mutex_cleanup_proxy_lock(pi_mutex, &rt_waiter))
863 			ret = 0;
864 
865 		spin_lock(q.lock_ptr);
866 		debug_rt_mutex_free_waiter(&rt_waiter);
867 		/*
868 		 * Fixup the pi_state owner and possibly acquire the lock if we
869 		 * haven't already.
870 		 */
871 		res = fixup_pi_owner(uaddr2, &q, !ret);
872 		/*
873 		 * If fixup_pi_owner() returned an error, propagate that.  If it
874 		 * acquired the lock, clear -ETIMEDOUT or -EINTR.
875 		 */
876 		if (res)
877 			ret = (res < 0) ? res : 0;
878 
879 		futex_unqueue_pi(&q);
880 		spin_unlock(q.lock_ptr);
881 
882 		if (ret == -EINTR) {
883 			/*
884 			 * We've already been requeued, but cannot restart
885 			 * by calling futex_lock_pi() directly. We could
886 			 * restart this syscall, but it would detect that
887 			 * the user space "val" changed and return
888 			 * -EWOULDBLOCK.  Save the overhead of the restart
889 			 * and return -EWOULDBLOCK directly.
890 			 */
891 			ret = -EWOULDBLOCK;
892 		}
893 		break;
894 	default:
895 		BUG();
896 	}
897 
898 out:
899 	if (to) {
900 		hrtimer_cancel(&to->timer);
901 		destroy_hrtimer_on_stack(&to->timer);
902 	}
903 	return ret;
904 }
905 
906