xref: /linux/kernel/futex/waitwake.c (revision 3f63e2545978abda58f2cf7ff0d7a2942965e8cb)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 
3 #include <linux/plist.h>
4 #include <linux/sched/task.h>
5 #include <linux/sched/signal.h>
6 #include <linux/freezer.h>
7 
8 #include "futex.h"
9 
10 /*
11  * READ this before attempting to hack on futexes!
12  *
13  * Basic futex operation and ordering guarantees
14  * =============================================
15  *
16  * The waiter reads the futex value in user space and calls
17  * futex_wait(). This function computes the hash bucket and acquires
18  * the hash bucket lock. After that it reads the futex user space value
19  * again and verifies that the data has not changed. If it has not changed
20  * it enqueues itself into the hash bucket, releases the hash bucket lock
21  * and schedules.
22  *
23  * The waker side modifies the user space value of the futex and calls
24  * futex_wake(). This function computes the hash bucket and acquires the
25  * hash bucket lock. Then it looks for waiters on that futex in the hash
26  * bucket and wakes them.
27  *
28  * In futex wake up scenarios where no tasks are blocked on a futex, taking
29  * the hb spinlock can be avoided and simply return. In order for this
30  * optimization to work, ordering guarantees must exist so that the waiter
31  * being added to the list is acknowledged when the list is concurrently being
32  * checked by the waker, avoiding scenarios like the following:
33  *
34  * CPU 0                               CPU 1
35  * val = *futex;
36  * sys_futex(WAIT, futex, val);
37  *   futex_wait(futex, val);
38  *   uval = *futex;
39  *                                     *futex = newval;
40  *                                     sys_futex(WAKE, futex);
41  *                                       futex_wake(futex);
42  *                                       if (queue_empty())
43  *                                         return;
44  *   if (uval == val)
45  *      lock(hash_bucket(futex));
46  *      queue();
47  *     unlock(hash_bucket(futex));
48  *     schedule();
49  *
50  * This would cause the waiter on CPU 0 to wait forever because it
51  * missed the transition of the user space value from val to newval
52  * and the waker did not find the waiter in the hash bucket queue.
53  *
54  * The correct serialization ensures that a waiter either observes
55  * the changed user space value before blocking or is woken by a
56  * concurrent waker:
57  *
58  * CPU 0                                 CPU 1
59  * val = *futex;
60  * sys_futex(WAIT, futex, val);
61  *   futex_wait(futex, val);
62  *
63  *   waiters++; (a)
64  *   smp_mb(); (A) <-- paired with -.
65  *                                  |
66  *   lock(hash_bucket(futex));      |
67  *                                  |
68  *   uval = *futex;                 |
69  *                                  |        *futex = newval;
70  *                                  |        sys_futex(WAKE, futex);
71  *                                  |          futex_wake(futex);
72  *                                  |
73  *                                  `--------> smp_mb(); (B)
74  *   if (uval == val)
75  *     queue();
76  *     unlock(hash_bucket(futex));
77  *     schedule();                         if (waiters)
78  *                                           lock(hash_bucket(futex));
79  *   else                                    wake_waiters(futex);
80  *     waiters--; (b)                        unlock(hash_bucket(futex));
81  *
82  * Where (A) orders the waiters increment and the futex value read through
83  * atomic operations (see futex_hb_waiters_inc) and where (B) orders the write
84  * to futex and the waiters read (see futex_hb_waiters_pending()).
85  *
86  * This yields the following case (where X:=waiters, Y:=futex):
87  *
88  *	X = Y = 0
89  *
90  *	w[X]=1		w[Y]=1
91  *	MB		MB
92  *	r[Y]=y		r[X]=x
93  *
94  * Which guarantees that x==0 && y==0 is impossible; which translates back into
95  * the guarantee that we cannot both miss the futex variable change and the
96  * enqueue.
97  *
98  * Note that a new waiter is accounted for in (a) even when it is possible that
99  * the wait call can return error, in which case we backtrack from it in (b).
100  * Refer to the comment in futex_q_lock().
101  *
102  * Similarly, in order to account for waiters being requeued on another
103  * address we always increment the waiters for the destination bucket before
104  * acquiring the lock. It then decrements them again  after releasing it -
105  * the code that actually moves the futex(es) between hash buckets (requeue_futex)
106  * will do the additional required waiter count housekeeping. This is done for
107  * double_lock_hb() and double_unlock_hb(), respectively.
108  */
109 
110 bool __futex_wake_mark(struct futex_q *q)
111 {
112 	if (WARN(q->pi_state || q->rt_waiter, "refusing to wake PI futex\n"))
113 		return false;
114 
115 	__futex_unqueue(q);
116 	/*
117 	 * The waiting task can free the futex_q as soon as q->lock_ptr = NULL
118 	 * is written, without taking any locks. This is possible in the event
119 	 * of a spurious wakeup, for example. A memory barrier is required here
120 	 * to prevent the following store to lock_ptr from getting ahead of the
121 	 * plist_del in __futex_unqueue().
122 	 */
123 	smp_store_release(&q->lock_ptr, NULL);
124 
125 	return true;
126 }
127 
128 /*
129  * The hash bucket lock must be held when this is called.
130  * Afterwards, the futex_q must not be accessed. Callers
131  * must ensure to later call wake_up_q() for the actual
132  * wakeups to occur.
133  */
134 void futex_wake_mark(struct wake_q_head *wake_q, struct futex_q *q)
135 {
136 	struct task_struct *p = q->task;
137 
138 	get_task_struct(p);
139 
140 	if (!__futex_wake_mark(q)) {
141 		put_task_struct(p);
142 		return;
143 	}
144 
145 	/*
146 	 * Queue the task for later wakeup for after we've released
147 	 * the hb->lock.
148 	 */
149 	wake_q_add_safe(wake_q, p);
150 }
151 
152 /*
153  * If requested, clear the robust list pending op and unlock the futex
154  */
155 static bool futex_robust_unlock(u32 __user *uaddr, unsigned int flags, void __user *pop)
156 {
157 	if (!(flags & FLAGS_ROBUST_UNLOCK))
158 		return true;
159 
160 	/* First unlock the futex, which requires release semantics. */
161 	scoped_user_write_access(uaddr, efault)
162 		unsafe_atomic_store_release_user(0, uaddr, efault);
163 
164 	/*
165 	 * Clear the pending list op now. If that fails, then the task is in
166 	 * deeper trouble as the robust list head is usually part of the TLS.
167 	 * The chance of survival is close to zero.
168 	 */
169 	return futex_robust_list_clear_pending(pop, flags);
170 
171 efault:
172 	return false;
173 }
174 
175 /*
176  * Wake up waiters matching bitset queued on this futex (uaddr).
177  */
178 int futex_wake(u32 __user *uaddr, unsigned int flags, void __user *pop, int nr_wake, u32 bitset)
179 {
180 	union futex_key key = FUTEX_KEY_INIT;
181 	struct futex_q *this, *next;
182 	DEFINE_WAKE_Q(wake_q);
183 	int ret;
184 
185 	if (!bitset)
186 		return -EINVAL;
187 
188 	ret = get_futex_key(uaddr, flags, &key, FUTEX_READ);
189 	if (unlikely(ret != 0))
190 		return ret;
191 
192 	if (!futex_robust_unlock(uaddr, flags, pop))
193 		return -EFAULT;
194 
195 	if ((flags & FLAGS_STRICT) && !nr_wake)
196 		return 0;
197 
198 	CLASS(hb, hb)(&key);
199 
200 	/* Make sure we really have tasks to wakeup */
201 	if (!futex_hb_waiters_pending(hb))
202 		return ret;
203 
204 	spin_lock(&hb->lock);
205 
206 	plist_for_each_entry_safe(this, next, &hb->chain, list) {
207 		if (futex_match (&this->key, &key)) {
208 			if (this->pi_state || this->rt_waiter) {
209 				ret = -EINVAL;
210 				break;
211 			}
212 
213 			/* Check if one of the bits is set in both bitsets */
214 			if (!(this->bitset & bitset))
215 				continue;
216 
217 			this->wake(&wake_q, this);
218 			if (++ret >= nr_wake)
219 				break;
220 		}
221 	}
222 
223 	spin_unlock(&hb->lock);
224 	wake_up_q(&wake_q);
225 	return ret;
226 }
227 
228 static int futex_atomic_op_inuser(unsigned int encoded_op, u32 __user *uaddr)
229 {
230 	unsigned int op =	  (encoded_op & 0x70000000) >> 28;
231 	unsigned int cmp =	  (encoded_op & 0x0f000000) >> 24;
232 	int oparg = sign_extend32((encoded_op & 0x00fff000) >> 12, 11);
233 	int cmparg = sign_extend32(encoded_op & 0x00000fff, 11);
234 	int oldval, ret;
235 
236 	if (encoded_op & (FUTEX_OP_OPARG_SHIFT << 28)) {
237 		if (oparg < 0 || oparg > 31) {
238 			/*
239 			 * kill this print and return -EINVAL when userspace
240 			 * is sane again
241 			 */
242 			pr_info_ratelimited("futex_wake_op: %s tries to shift op by %d; fix this program\n",
243 					    current->comm, oparg);
244 			oparg &= 31;
245 		}
246 		oparg = 1 << oparg;
247 	}
248 
249 	pagefault_disable();
250 	ret = arch_futex_atomic_op_inuser(op, oparg, &oldval, uaddr);
251 	pagefault_enable();
252 	if (ret)
253 		return ret;
254 
255 	switch (cmp) {
256 	case FUTEX_OP_CMP_EQ:
257 		return oldval == cmparg;
258 	case FUTEX_OP_CMP_NE:
259 		return oldval != cmparg;
260 	case FUTEX_OP_CMP_LT:
261 		return oldval < cmparg;
262 	case FUTEX_OP_CMP_GE:
263 		return oldval >= cmparg;
264 	case FUTEX_OP_CMP_LE:
265 		return oldval <= cmparg;
266 	case FUTEX_OP_CMP_GT:
267 		return oldval > cmparg;
268 	default:
269 		return -ENOSYS;
270 	}
271 }
272 
273 /*
274  * Wake up all waiters hashed on the physical page that is mapped
275  * to this virtual address:
276  */
277 int futex_wake_op(u32 __user *uaddr1, unsigned int flags, u32 __user *uaddr2,
278 		  int nr_wake, int nr_wake2, int op)
279 {
280 	union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT;
281 	struct futex_q *this, *next;
282 	int ret, op_ret;
283 	DEFINE_WAKE_Q(wake_q);
284 
285 retry:
286 	ret = get_futex_key(uaddr1, flags, &key1, FUTEX_READ);
287 	if (unlikely(ret != 0))
288 		return ret;
289 	ret = get_futex_key(uaddr2, flags, &key2, FUTEX_WRITE);
290 	if (unlikely(ret != 0))
291 		return ret;
292 
293 retry_private:
294 	if (1) {
295 		CLASS(hb, hb1)(&key1);
296 		CLASS(hb, hb2)(&key2);
297 
298 		double_lock_hb(hb1, hb2);
299 		op_ret = futex_atomic_op_inuser(op, uaddr2);
300 		if (unlikely(op_ret < 0)) {
301 			double_unlock_hb(hb1, hb2);
302 
303 			if (!IS_ENABLED(CONFIG_MMU) ||
304 			    unlikely(op_ret != -EFAULT && op_ret != -EAGAIN)) {
305 				/*
306 				 * we don't get EFAULT from MMU faults if we don't have
307 				 * an MMU, but we might get them from range checking
308 				 */
309 				ret = op_ret;
310 				return ret;
311 			}
312 
313 			if (op_ret == -EFAULT) {
314 				ret = fault_in_user_writeable(uaddr2);
315 				if (ret)
316 					return ret;
317 			}
318 
319 			cond_resched();
320 			if (!(flags & FLAGS_SHARED))
321 				goto retry_private;
322 			goto retry;
323 		}
324 
325 		plist_for_each_entry_safe(this, next, &hb1->chain, list) {
326 			if (futex_match(&this->key, &key1)) {
327 				if (this->pi_state || this->rt_waiter) {
328 					ret = -EINVAL;
329 					goto out_unlock;
330 				}
331 				this->wake(&wake_q, this);
332 				if (++ret >= nr_wake)
333 					break;
334 			}
335 		}
336 
337 		if (op_ret > 0) {
338 			op_ret = 0;
339 			plist_for_each_entry_safe(this, next, &hb2->chain, list) {
340 				if (futex_match(&this->key, &key2)) {
341 					if (this->pi_state || this->rt_waiter) {
342 						ret = -EINVAL;
343 						goto out_unlock;
344 					}
345 					this->wake(&wake_q, this);
346 					if (++op_ret >= nr_wake2)
347 						break;
348 				}
349 			}
350 			ret += op_ret;
351 		}
352 
353 out_unlock:
354 		double_unlock_hb(hb1, hb2);
355 	}
356 	wake_up_q(&wake_q);
357 	return ret;
358 }
359 
360 static long futex_wait_restart(struct restart_block *restart);
361 
362 /**
363  * futex_do_wait() - wait for wakeup, timeout, or signal
364  * @q:		the futex_q to queue up on
365  * @timeout:	the prepared hrtimer_sleeper, or null for no timeout
366  */
367 void futex_do_wait(struct futex_q *q, struct hrtimer_sleeper *timeout)
368 {
369 	/* Arm the timer */
370 	if (timeout)
371 		hrtimer_sleeper_start_expires(timeout, HRTIMER_MODE_ABS);
372 
373 	/*
374 	 * If we have been removed from the hash list, then another task
375 	 * has tried to wake us, and we can skip the call to schedule().
376 	 */
377 	if (likely(!plist_node_empty(&q->list))) {
378 		/*
379 		 * If the timer has already expired, current will already be
380 		 * flagged for rescheduling. Only call schedule if there
381 		 * is no timeout, or if it has yet to expire.
382 		 */
383 		if (!timeout || timeout->task)
384 			schedule();
385 	}
386 	__set_current_state(TASK_RUNNING);
387 }
388 
389 /**
390  * futex_unqueue_multiple - Remove various futexes from their hash bucket
391  * @v:	   The list of futexes to unqueue
392  * @count: Number of futexes in the list
393  *
394  * Helper to unqueue a list of futexes. This can't fail.
395  *
396  * Return:
397  *  - >=0 - Index of the last futex that was awoken;
398  *  - -1  - No futex was awoken
399  */
400 int futex_unqueue_multiple(struct futex_vector *v, int count)
401 {
402 	int ret = -1, i;
403 
404 	for (i = 0; i < count; i++) {
405 		if (!futex_unqueue(&v[i].q))
406 			ret = i;
407 	}
408 
409 	return ret;
410 }
411 
412 /**
413  * futex_wait_multiple_setup - Prepare to wait and enqueue multiple futexes
414  * @vs:		The futex list to wait on
415  * @count:	The size of the list
416  * @woken:	Index of the last woken futex, if any. Used to notify the
417  *		caller that it can return this index to userspace (return parameter)
418  *
419  * Prepare multiple futexes in a single step and enqueue them. This may fail if
420  * the futex list is invalid or if any futex was already awoken. On success the
421  * task is ready to interruptible sleep.
422  *
423  * Return:
424  *  -  1 - One of the futexes was woken by another thread
425  *  -  0 - Success
426  *  - <0 - -EFAULT, -EWOULDBLOCK or -EINVAL
427  */
428 int futex_wait_multiple_setup(struct futex_vector *vs, int count, int *woken)
429 {
430 	bool retry = false;
431 	int ret, i;
432 	u32 uval;
433 
434 	/*
435 	 * Make sure to have a reference on the private_hash such that we
436 	 * don't block on rehash after changing the task state below.
437 	 */
438 	guard(private_hash)();
439 
440 	/*
441 	 * Enqueuing multiple futexes is tricky, because we need to enqueue
442 	 * each futex on the list before dealing with the next one to avoid
443 	 * deadlocking on the hash bucket. But, before enqueuing, we need to
444 	 * make sure that current->state is TASK_INTERRUPTIBLE, so we don't
445 	 * lose any wake events, which cannot be done before the get_futex_key
446 	 * of the next key, because it calls get_user_pages, which can sleep.
447 	 * Thus, we fetch the list of futexes keys in two steps, by first
448 	 * pinning all the memory keys in the futex key, and only then we read
449 	 * each key and queue the corresponding futex.
450 	 *
451 	 * Private futexes doesn't need to recalculate hash in retry, so skip
452 	 * get_futex_key() when retrying.
453 	 */
454 retry:
455 	for (i = 0; i < count; i++) {
456 		if (!(vs[i].w.flags & FLAGS_SHARED) && retry)
457 			continue;
458 
459 		ret = get_futex_key(u64_to_user_ptr(vs[i].w.uaddr),
460 				    vs[i].w.flags,
461 				    &vs[i].q.key, FUTEX_READ);
462 
463 		if (unlikely(ret))
464 			return ret;
465 	}
466 
467 	set_current_state(TASK_INTERRUPTIBLE|TASK_FREEZABLE);
468 
469 	for (i = 0; i < count; i++) {
470 		u32 __user *uaddr = (u32 __user *)(unsigned long)vs[i].w.uaddr;
471 		struct futex_q *q = &vs[i].q;
472 		u32 val = vs[i].w.val;
473 
474 		if (1) {
475 			CLASS(hb, hb)(&q->key);
476 
477 			futex_q_lock(q, hb);
478 			ret = futex_get_value_locked(&uval, uaddr);
479 
480 			if (!ret && uval == val) {
481 				/*
482 				 * The bucket lock can't be held while dealing with the
483 				 * next futex. Queue each futex at this moment so hb can
484 				 * be unlocked.
485 				 */
486 				futex_queue(q, hb, current);
487 				continue;
488 			}
489 
490 			futex_q_unlock(hb);
491 			__release(q->lock_ptr);
492 		}
493 		__set_current_state(TASK_RUNNING);
494 
495 		/*
496 		 * Even if something went wrong, if we find out that a futex
497 		 * was woken, we don't return error and return this index to
498 		 * userspace
499 		 */
500 		*woken = futex_unqueue_multiple(vs, i);
501 		if (*woken >= 0)
502 			return 1;
503 
504 		if (ret) {
505 			/*
506 			 * If we need to handle a page fault, we need to do so
507 			 * without any lock and any enqueued futex (otherwise
508 			 * we could lose some wakeup). So we do it here, after
509 			 * undoing all the work done so far. In success, we
510 			 * retry all the work.
511 			 */
512 			if (get_user(uval, uaddr))
513 				return -EFAULT;
514 
515 			retry = true;
516 			goto retry;
517 		}
518 
519 		if (uval != val)
520 			return -EWOULDBLOCK;
521 	}
522 
523 	return 0;
524 }
525 
526 /**
527  * futex_sleep_multiple - Check sleeping conditions and sleep
528  * @vs:    List of futexes to wait for
529  * @count: Length of vs
530  * @to:    Timeout
531  *
532  * Sleep if and only if the timeout hasn't expired and no futex on the list has
533  * been woken up.
534  */
535 static void futex_sleep_multiple(struct futex_vector *vs, unsigned int count,
536 				 struct hrtimer_sleeper *to)
537 {
538 	if (to && !to->task)
539 		return;
540 
541 	for (; count; count--, vs++) {
542 		if (!READ_ONCE(vs->q.lock_ptr))
543 			return;
544 	}
545 
546 	schedule();
547 }
548 
549 /**
550  * futex_wait_multiple - Prepare to wait on and enqueue several futexes
551  * @vs:		The list of futexes to wait on
552  * @count:	The number of objects
553  * @to:		Timeout before giving up and returning to userspace
554  *
555  * Entry point for the FUTEX_WAIT_MULTIPLE futex operation, this function
556  * sleeps on a group of futexes and returns on the first futex that is
557  * wake, or after the timeout has elapsed.
558  *
559  * Return:
560  *  - >=0 - Hint to the futex that was awoken
561  *  - <0  - On error
562  */
563 int futex_wait_multiple(struct futex_vector *vs, unsigned int count,
564 			struct hrtimer_sleeper *to)
565 {
566 	int ret, hint = 0;
567 
568 	if (to)
569 		hrtimer_sleeper_start_expires(to, HRTIMER_MODE_ABS);
570 
571 	while (1) {
572 		ret = futex_wait_multiple_setup(vs, count, &hint);
573 		if (ret) {
574 			if (ret > 0) {
575 				/* A futex was woken during setup */
576 				ret = hint;
577 			}
578 			return ret;
579 		}
580 
581 		futex_sleep_multiple(vs, count, to);
582 
583 		__set_current_state(TASK_RUNNING);
584 
585 		ret = futex_unqueue_multiple(vs, count);
586 		if (ret >= 0)
587 			return ret;
588 
589 		if (to && !to->task)
590 			return -ETIMEDOUT;
591 		else if (signal_pending(current))
592 			return -ERESTARTSYS;
593 		/*
594 		 * The final case is a spurious wakeup, for
595 		 * which just retry.
596 		 */
597 	}
598 }
599 
600 /**
601  * futex_wait_setup() - Prepare to wait on a futex
602  * @uaddr:	the futex userspace address
603  * @val:	the expected value
604  * @flags:	futex flags (FLAGS_SHARED, etc.)
605  * @q:		the associated futex_q
606  * @key2:	the second futex_key if used for requeue PI
607  * @task:	Task queueing this futex
608  *
609  * Setup the futex_q and locate the hash_bucket.  Get the futex value and
610  * compare it with the expected value.  Handle atomic faults internally.
611  * Return with the hb lock held on success, and unlocked on failure.
612  *
613  * Return:
614  *  -  0 - uaddr contains val and hb has been locked;
615  *  - <0 - On error and the hb is unlocked. A possible reason: the uaddr can not
616  *	   be read, does not contain the expected value or is not properly aligned.
617  */
618 int futex_wait_setup(u32 __user *uaddr, u32 val, unsigned int flags,
619 		     struct futex_q *q, union futex_key *key2,
620 		     struct task_struct *task)
621 {
622 	u32 uval;
623 	int ret;
624 
625 	/*
626 	 * Access the page AFTER the hash-bucket is locked.
627 	 * Order is important:
628 	 *
629 	 *   Userspace waiter: val = var; if (cond(val)) futex_wait(&var, val);
630 	 *   Userspace waker:  if (cond(var)) { var = new; futex_wake(&var); }
631 	 *
632 	 * The basic logical guarantee of a futex is that it blocks ONLY
633 	 * if cond(var) is known to be true at the time of blocking, for
634 	 * any cond.  If we locked the hash-bucket after testing *uaddr, that
635 	 * would open a race condition where we could block indefinitely with
636 	 * cond(var) false, which would violate the guarantee.
637 	 *
638 	 * On the other hand, we insert q and release the hash-bucket only
639 	 * after testing *uaddr.  This guarantees that futex_wait() will NOT
640 	 * absorb a wakeup if *uaddr does not match the desired values
641 	 * while the syscall executes.
642 	 */
643 retry:
644 	ret = get_futex_key(uaddr, flags, &q->key, FUTEX_READ);
645 	if (unlikely(ret != 0))
646 		return ret;
647 
648 retry_private:
649 	if (1) {
650 		CLASS(hb, hb)(&q->key);
651 
652 		futex_q_lock(q, hb);
653 
654 		ret = futex_get_value_locked(&uval, uaddr);
655 
656 		if (ret) {
657 			futex_q_unlock(hb);
658 			__release(q->lock_ptr);
659 
660 			ret = get_user(uval, uaddr);
661 			if (ret)
662 				return ret;
663 
664 			if (!(flags & FLAGS_SHARED))
665 				goto retry_private;
666 
667 			goto retry;
668 		}
669 
670 		if (uval != val) {
671 			futex_q_unlock(hb);
672 			__release(q->lock_ptr);
673 			return -EWOULDBLOCK;
674 		}
675 
676 		if (key2 && futex_match(&q->key, key2)) {
677 			futex_q_unlock(hb);
678 			__release(q->lock_ptr);
679 			return -EINVAL;
680 		}
681 
682 		/*
683 		 * The task state is guaranteed to be set before another task can
684 		 * wake it. set_current_state() is implemented using smp_store_mb() and
685 		 * futex_queue() calls spin_unlock() upon completion, both serializing
686 		 * access to the hash list and forcing another memory barrier.
687 		 */
688 		if (task == current)
689 			set_current_state(TASK_INTERRUPTIBLE|TASK_FREEZABLE);
690 		futex_queue(q, hb, task);
691 	}
692 
693 	return ret;
694 }
695 
696 int __futex_wait(u32 __user *uaddr, unsigned int flags, u32 val,
697 		 struct hrtimer_sleeper *to, u32 bitset)
698 {
699 	struct futex_q q = futex_q_init;
700 	int ret;
701 
702 	if (!bitset)
703 		return -EINVAL;
704 
705 	q.bitset = bitset;
706 
707 retry:
708 	/*
709 	 * Prepare to wait on uaddr. On success, it holds hb->lock and q
710 	 * is initialized.
711 	 */
712 	ret = futex_wait_setup(uaddr, val, flags, &q, NULL, current);
713 	if (ret)
714 		return ret;
715 
716 	/* futex_queue and wait for wakeup, timeout, or a signal. */
717 	futex_do_wait(&q, to);
718 
719 	/* If we were woken (and unqueued), we succeeded, whatever. */
720 	if (!futex_unqueue(&q))
721 		return 0;
722 
723 	if (to && !to->task)
724 		return -ETIMEDOUT;
725 
726 	/*
727 	 * We expect signal_pending(current), but we might be the
728 	 * victim of a spurious wakeup as well.
729 	 */
730 	if (!signal_pending(current))
731 		goto retry;
732 
733 	return -ERESTARTSYS;
734 }
735 
736 int futex_wait(u32 __user *uaddr, unsigned int flags, u32 val, ktime_t *abs_time, u32 bitset)
737 {
738 	struct hrtimer_sleeper timeout, *to;
739 	struct restart_block *restart;
740 	int ret;
741 
742 	to = futex_setup_timer(abs_time, &timeout, flags,
743 			       current->timer_slack_ns);
744 
745 	ret = __futex_wait(uaddr, flags, val, to, bitset);
746 
747 	/* No timeout, nothing to clean up. */
748 	if (!to)
749 		return ret;
750 
751 	hrtimer_cancel(&to->timer);
752 	destroy_hrtimer_on_stack(&to->timer);
753 
754 	if (ret == -ERESTARTSYS) {
755 		restart = &current->restart_block;
756 		restart->futex.uaddr = uaddr;
757 		restart->futex.val = val;
758 		restart->futex.time = *abs_time;
759 		restart->futex.bitset = bitset;
760 		restart->futex.flags = flags | FLAGS_HAS_TIMEOUT;
761 
762 		return set_restart_fn(restart, futex_wait_restart);
763 	}
764 
765 	return ret;
766 }
767 
768 static long futex_wait_restart(struct restart_block *restart)
769 {
770 	u32 __user *uaddr = restart->futex.uaddr;
771 	ktime_t *tp = NULL;
772 
773 	if (restart->futex.flags & FLAGS_HAS_TIMEOUT)
774 		tp = &restart->futex.time;
775 
776 	restart->fn = do_no_restart_syscall;
777 
778 	return (long)futex_wait(uaddr, restart->futex.flags,
779 				restart->futex.val, tp, restart->futex.bitset);
780 }
781 
782