execve.2: SEE ALSO: getauxval(3)
[man-pages.git] / man2 / futex.2
blobada96c517ddb4b766f57edbf5f0435c9cb15b402
1 .\" Page by b.hubert
2 .\" and Copyright (C) 2015, Thomas Gleixner <tglx@linutronix.de>
3 .\" and Copyright (C) 2015, Michael Kerrisk <mtk.manpages@gmail.com>
4 .\"
5 .\" %%%LICENSE_START(FREELY_REDISTRIBUTABLE)
6 .\" may be freely modified and distributed
7 .\" %%%LICENSE_END
8 .\"
9 .\" Niki A. Rahimi (LTC Security Development, narahimi@us.ibm.com)
10 .\" added ERRORS section.
11 .\"
12 .\" Modified 2004-06-17 mtk
13 .\" Modified 2004-10-07 aeb, added FUTEX_REQUEUE, FUTEX_CMP_REQUEUE
14 .\"
15 .\" FIXME Still to integrate are some points from Torvald Riegel's mail of
16 .\" 2015-01-23:
17 .\"       http://thread.gmane.org/gmane.linux.kernel/1703405/focus=7977
18 .\"
19 .\" FIXME Do we need to add some text regarding Torvald Riegel's 2015-01-24 mail
20 .\"       http://thread.gmane.org/gmane.linux.kernel/1703405/focus=1873242
21 .\"
22 .TH FUTEX 2 2021-03-22 "Linux" "Linux Programmer's Manual"
23 .SH NAME
24 futex \- fast user-space locking
25 .SH SYNOPSIS
26 .nf
27 .PP
28 .BR "#include <linux/futex.h>" "      /* Definition of " FUTEX_* " constants */"
29 .BR "#include <sys/syscall.h>" "      /* Definition of " SYS_* " constants */"
30 .B #include <unistd.h>
31 .PP
32 .BI "long syscall(SYS_futex, uint32_t *" uaddr ", int " futex_op \
33 ", uint32_t " val ,
34 .BI "             const struct timespec *" timeout , \
35 " \fR  /* or: \fBuint32_t \fIval2\fP */"
36 .BI "             uint32_t *" uaddr2 ", uint32_t " val3 );
37 .fi
38 .PP
39 .IR Note :
40 glibc provides no wrapper for
41 .BR futex (),
42 necessitating the use of
43 .BR syscall (2).
44 .SH DESCRIPTION
45 The
46 .BR futex ()
47 system call provides a method for waiting until a certain condition becomes
48 true.
49 It is typically used as a blocking construct in the context of
50 shared-memory synchronization.
51 When using futexes, the majority of
52 the synchronization operations are performed in user space.
53 A user-space program employs the
54 .BR futex ()
55 system call only when it is likely that the program has to block for
56 a longer time until the condition becomes true.
57 Other
58 .BR futex ()
59 operations can be used to wake any processes or threads waiting
60 for a particular condition.
61 .PP
62 A futex is a 32-bit value\(emreferred to below as a
63 .IR "futex word" \(emwhose
64 address is supplied to the
65 .BR futex ()
66 system call.
67 (Futexes are 32 bits in size on all platforms, including 64-bit systems.)
68 All futex operations are governed by this value.
69 In order to share a futex between processes,
70 the futex is placed in a region of shared memory,
71 created using (for example)
72 .BR mmap (2)
74 .BR shmat (2).
75 (Thus, the futex word may have different
76 virtual addresses in different processes,
77 but these addresses all refer to the same location in physical memory.)
78 In a multithreaded program, it is sufficient to place the futex word
79 in a global variable shared by all threads.
80 .PP
81 When executing a futex operation that requests to block a thread,
82 the kernel will block only if the futex word has the value that the
83 calling thread supplied (as one of the arguments of the
84 .BR futex ()
85 call) as the expected value of the futex word.
86 The loading of the futex word's value,
87 the comparison of that value with the expected value,
88 and the actual blocking will happen atomically and will be totally ordered
89 with respect to concurrent operations performed by other threads
90 on the same futex word.
91 .\" Notes from Darren Hart (Dec 2015):
92 .\"     Totally ordered with respect futex operations refers to semantics
93 .\"     of the ACQUIRE/RELEASE operations and how they impact ordering of
94 .\"     memory reads and writes. The kernel futex operations are protected
95 .\"     by spinlocks, which ensure that all operations are serialized
96 .\"     with respect to one another.
97 .\"
98 .\"     This is a lot to attempt to define in this document. Perhaps a
99 .\"     reference to linux/Documentation/memory-barriers.txt as a footnote
100 .\"     would be sufficient? Or perhaps for this manual, "serialized" would
101 .\"     be sufficient, with a footnote regarding "totally ordered" and a
102 .\"     pointer to the memory-barrier documentation?
103 Thus, the futex word is used to connect the synchronization in user space
104 with the implementation of blocking by the kernel.
105 Analogously to an atomic
106 compare-and-exchange operation that potentially changes shared memory,
107 blocking via a futex is an atomic compare-and-block operation.
108 .\" FIXME(Torvald Riegel):
109 .\" Eventually we want to have some text in NOTES to satisfy
110 .\" the reference in the following sentence
111 .\"     See NOTES for a detailed specification of
112 .\"     the synchronization semantics.
114 One use of futexes is for implementing locks.
115 The state of the lock (i.e., acquired or not acquired)
116 can be represented as an atomically accessed flag in shared memory.
117 In the uncontended case,
118 a thread can access or modify the lock state with atomic instructions,
119 for example atomically changing it from not acquired to acquired
120 using an atomic compare-and-exchange instruction.
121 (Such instructions are performed entirely in user mode,
122 and the kernel maintains no information about the lock state.)
123 On the other hand, a thread may be unable to acquire a lock because
124 it is already acquired by another thread.
125 It then may pass the lock's flag as a futex word and the value
126 representing the acquired state as the expected value to a
127 .BR futex ()
128 wait operation.
129 This
130 .BR futex ()
131 operation will block if and only if the lock is still acquired
132 (i.e., the value in the futex word still matches the "acquired state").
133 When releasing the lock, a thread has to first reset the
134 lock state to not acquired and then execute a futex
135 operation that wakes threads blocked on the lock flag used as a futex word
136 (this can be further optimized to avoid unnecessary wake-ups).
138 .BR futex (7)
139 for more detail on how to use futexes.
141 Besides the basic wait and wake-up futex functionality, there are further
142 futex operations aimed at supporting more complex use cases.
144 Note that
145 no explicit initialization or destruction is necessary to use futexes;
146 the kernel maintains a futex
147 (i.e., the kernel-internal implementation artifact)
148 only while operations such as
149 .BR FUTEX_WAIT ,
150 described below, are being performed on a particular futex word.
152 .SS Arguments
154 .I uaddr
155 argument points to the futex word.
156 On all platforms, futexes are four-byte
157 integers that must be aligned on a four-byte boundary.
158 The operation to perform on the futex is specified in the
159 .I futex_op
160 argument;
161 .IR val
162 is a value whose meaning and purpose depends on
163 .IR futex_op .
165 The remaining arguments
166 .RI ( timeout ,
167 .IR uaddr2 ,
169 .IR val3 )
170 are required only for certain of the futex operations described below.
171 Where one of these arguments is not required, it is ignored.
173 For several blocking operations, the
174 .I timeout
175 argument is a pointer to a
176 .IR timespec
177 structure that specifies a timeout for the operation.
178 However,  notwithstanding the prototype shown above, for some operations,
179 the least significant four bytes of this argument are instead
180 used as an integer whose meaning is determined by the operation.
181 For these operations, the kernel casts the
182 .I timeout
183 value first to
184 .IR "unsigned long",
185 then to
186 .IR uint32_t ,
187 and in the remainder of this page, this argument is referred to as
188 .I val2
189 when interpreted in this fashion.
191 Where it is required, the
192 .IR uaddr2
193 argument is a pointer to a second futex word that is employed
194 by the operation.
196 The interpretation of the final integer argument,
197 .IR val3 ,
198 depends on the operation.
200 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
202 .SS Futex operations
204 .I futex_op
205 argument consists of two parts:
206 a command that specifies the operation to be performed,
207 bitwise ORed with zero or more options that
208 modify the behaviour of the operation.
209 The options that may be included in
210 .I futex_op
211 are as follows:
213 .BR FUTEX_PRIVATE_FLAG " (since Linux 2.6.22)"
214 .\" commit 34f01cc1f512fa783302982776895c73714ebbc2
215 This option bit can be employed with all futex operations.
216 It tells the kernel that the futex is process-private and not shared
217 with another process (i.e., it is being used for synchronization
218 only between threads of the same process).
219 This allows the kernel to make some additional performance optimizations.
220 .\" I.e., It allows the kernel choose the fast path for validating
221 .\" the user-space address and avoids expensive VMA lookups,
222 .\" taking reference counts on file backing store, and so on.
224 As a convenience,
225 .IR <linux/futex.h>
226 defines a set of constants with the suffix
227 .BR _PRIVATE
228 that are equivalents of all of the operations listed below,
229 .\" except the obsolete FUTEX_FD, for which the "private" flag was
230 .\" meaningless
231 but with the
232 .BR FUTEX_PRIVATE_FLAG
233 ORed into the constant value.
234 Thus, there are
235 .BR FUTEX_WAIT_PRIVATE ,
236 .BR FUTEX_WAKE_PRIVATE ,
237 and so on.
239 .BR FUTEX_CLOCK_REALTIME " (since Linux 2.6.28)"
240 .\" commit 1acdac104668a0834cfa267de9946fac7764d486
241 This option bit can be employed only with the
242 .BR FUTEX_WAIT_BITSET ,
243 .BR FUTEX_WAIT_REQUEUE_PI ,
245 (since Linux 4.5)
246 .\" commit 337f13046ff03717a9e99675284a817527440a49
247 .BR FUTEX_WAIT
248 operations.
250 If this option is set, the kernel measures the
251 .I timeout
252 against the
253 .BR CLOCK_REALTIME
254 clock.
256 If this option is not set, the kernel measures the
257 .I timeout
258 against the
259 .BR CLOCK_MONOTONIC
260 clock.
262 The operation specified in
263 .I futex_op
264 is one of the following:
266 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
269 .BR FUTEX_WAIT " (since Linux 2.6.0)"
270 .\" Strictly speaking, since some time in 2.5.x
271 This operation tests that the value at the
272 futex word pointed to by the address
273 .I uaddr
274 still contains the expected value
275 .IR val ,
276 and if so, then sleeps waiting for a
277 .B FUTEX_WAKE
278 operation on the futex word.
279 The load of the value of the futex word is an atomic memory
280 access (i.e., using atomic machine instructions of the respective
281 architecture).
282 This load, the comparison with the expected value, and
283 starting to sleep are performed atomically
284 .\" FIXME: Torvald, I think we may need to add some explanation of
285 .\" "totally ordered" here.
286 and totally ordered
287 with respect to other futex operations on the same futex word.
288 If the thread starts to sleep,
289 it is considered a waiter on this futex word.
290 If the futex value does not match
291 .IR val ,
292 then the call fails immediately with the error
293 .BR EAGAIN .
295 The purpose of the comparison with the expected value is to prevent lost
296 wake-ups.
297 If another thread changed the value of the futex word after the
298 calling thread decided to block based on the prior value,
299 and if the other thread executed a
300 .BR FUTEX_WAKE
301 operation (or similar wake-up) after the value change and before this
302 .BR FUTEX_WAIT
303 operation, then the calling thread will observe the
304 value change and will not start to sleep.
306 If the
307 .I timeout
308 is not NULL, the structure it points to specifies a
309 timeout for the wait.
310 (This interval will be rounded up to the system clock granularity,
311 and is guaranteed not to expire early.)
312 The timeout is by default measured according to the
313 .BR CLOCK_MONOTONIC
314 clock, but, since Linux 4.5, the
315 .BR CLOCK_REALTIME
316 clock can be selected by specifying
317 .BR FUTEX_CLOCK_REALTIME
319 .IR futex_op .
321 .I timeout
322 is NULL, the call blocks indefinitely.
324 .IR Note :
326 .BR FUTEX_WAIT ,
327 .IR timeout
328 is interpreted as a
329 .IR relative
330 value.
331 This differs from other futex operations, where
332 .I timeout
333 is interpreted as an absolute value.
334 To obtain the equivalent of
335 .BR FUTEX_WAIT
336 with an absolute timeout, employ
337 .BR FUTEX_WAIT_BITSET
338 with
339 .IR val3
340 specified as
341 .BR FUTEX_BITSET_MATCH_ANY .
343 The arguments
344 .I uaddr2
346 .I val3
347 are ignored.
348 .\" FIXME . (Torvald) I think we should remove this.  Or maybe adapt to a
349 .\" different example.
351 .\"     For
352 .\"     .BR futex (7),
353 .\"     this call is executed if decrementing the count gave a negative value
354 .\"     (indicating contention),
355 .\"     and will sleep until another process or thread releases
356 .\"     the futex and executes the
357 .\"     .B FUTEX_WAKE
358 .\"     operation.
360 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
363 .BR FUTEX_WAKE " (since Linux 2.6.0)"
364 .\" Strictly speaking, since Linux 2.5.x
365 This operation wakes at most
366 .I val
367 of the waiters that are waiting (e.g., inside
368 .BR FUTEX_WAIT )
369 on the futex word at the address
370 .IR uaddr .
371 Most commonly,
372 .I val
373 is specified as either 1 (wake up a single waiter) or
374 .BR INT_MAX
375 (wake up all waiters).
376 No guarantee is provided about which waiters are awoken
377 (e.g., a waiter with a higher scheduling priority is not guaranteed
378 to be awoken in preference to a waiter with a lower priority).
380 The arguments
381 .IR timeout ,
382 .IR uaddr2 ,
384 .I val3
385 are ignored.
386 .\" FIXME . (Torvald) I think we should remove this.  Or maybe adapt to
387 .\" a different example.
389 .\"     For
390 .\"     .BR futex (7),
391 .\"     this is executed if incrementing the count showed that
392 .\"     there were waiters,
393 .\"     once the futex value has been set to 1
394 .\"     (indicating that it is available).
396 .\" How does "incrementing the count show that there were waiters"?
398 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
401 .BR FUTEX_FD " (from Linux 2.6.0 up to and including Linux 2.6.25)"
402 .\" Strictly speaking, from Linux 2.5.x to 2.6.25
403 This operation creates a file descriptor that is associated with
404 the futex at
405 .IR uaddr .
406 The caller must close the returned file descriptor after use.
407 When another process or thread performs a
408 .BR FUTEX_WAKE
409 on the futex word, the file descriptor indicates as being readable with
410 .BR select (2),
411 .BR poll (2),
413 .BR epoll (7)
415 The file descriptor can be used to obtain asynchronous notifications: if
416 .I val
417 is nonzero, then, when another process or thread executes a
418 .BR FUTEX_WAKE ,
419 the caller will receive the signal number that was passed in
420 .IR val .
422 The arguments
423 .IR timeout ,
424 .IR uaddr2 ,
426 .I val3
427 are ignored.
429 Because it was inherently racy,
430 .B FUTEX_FD
431 has been removed
432 .\" commit 82af7aca56c67061420d618cc5a30f0fd4106b80
433 from Linux 2.6.26 onward.
435 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
438 .BR FUTEX_REQUEUE " (since Linux 2.6.0)"
439 This operation performs the same task as
440 .BR FUTEX_CMP_REQUEUE
441 (see below), except that no check is made using the value in
442 .IR  val3 .
443 (The argument
444 .I val3
445 is ignored.)
447 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
450 .BR FUTEX_CMP_REQUEUE " (since Linux 2.6.7)"
451 This operation first checks whether the location
452 .I uaddr
453 still contains the value
454 .IR val3 .
455 If not, the operation fails with the error
456 .BR EAGAIN .
457 Otherwise, the operation wakes up a maximum of
458 .I val
459 waiters that are waiting on the futex at
460 .IR uaddr .
461 If there are more than
462 .I val
463 waiters, then the remaining waiters are removed
464 from the wait queue of the source futex at
465 .I uaddr
466 and added to the wait queue of the target futex at
467 .IR uaddr2 .
469 .I val2
470 argument specifies an upper limit on the number of waiters
471 that are requeued to the futex at
472 .IR uaddr2 .
474 .\" FIXME(Torvald) Is the following correct?  Or is just the decision
475 .\" which threads to wake or requeue part of the atomic operation?
476 The load from
477 .I uaddr
478 is an atomic memory access (i.e., using atomic machine instructions of
479 the respective architecture).
480 This load, the comparison with
481 .IR val3 ,
482 and the requeueing of any waiters are performed atomically and totally
483 ordered with respect to other operations on the same futex word.
484 .\" Notes from a f2f conversation with Thomas Gleixner (Aug 2015): ###
485 .\"     The operation is serialized with respect to operations on both
486 .\"     source and target futex. No other waiter can enqueue itself
487 .\"     for waiting and no other waiter can dequeue itself because of
488 .\"     a timeout or signal.
490 Typical values to specify for
491 .I val
492 are 0 or 1.
493 (Specifying
494 .BR INT_MAX
495 is not useful, because it would make the
496 .BR FUTEX_CMP_REQUEUE
497 operation equivalent to
498 .BR FUTEX_WAKE .)
499 The limit value specified via
500 .I val2
501 is typically either 1 or
502 .BR INT_MAX .
503 (Specifying the argument as 0 is not useful, because it would make the
504 .BR FUTEX_CMP_REQUEUE
505 operation equivalent to
506 .BR FUTEX_WAIT .)
509 .B FUTEX_CMP_REQUEUE
510 operation was added as a replacement for the earlier
511 .BR FUTEX_REQUEUE .
512 The difference is that the check of the value at
513 .I uaddr
514 can be used to ensure that requeueing happens only under certain
515 conditions, which allows race conditions to be avoided in certain use cases.
516 .\" But, as Rich Felker points out, there remain valid use cases for
517 .\" FUTEX_REQUEUE, for example, when the calling thread is requeuing
518 .\" the target(s) to a lock that the calling thread owns
519 .\"     From: Rich Felker <dalias@libc.org>
520 .\"     Date: Wed, 29 Oct 2014 22:43:17 -0400
521 .\"     To: Darren Hart <dvhart@infradead.org>
522 .\"     CC: libc-alpha@sourceware.org, ...
523 .\"     Subject: Re: Add futex wrapper to glibc?
525 Both
526 .BR FUTEX_REQUEUE
528 .BR FUTEX_CMP_REQUEUE
529 can be used to avoid "thundering herd" wake-ups that could occur when using
530 .B FUTEX_WAKE
531 in cases where all of the waiters that are woken need to acquire
532 another futex.
533 Consider the following scenario,
534 where multiple waiter threads are waiting on B,
535 a wait queue implemented using a futex:
537 .in +4n
539 lock(A)
540 while (!check_value(V)) {
541     unlock(A);
542     block_on(B);
543     lock(A);
545 unlock(A);
549 If a waker thread used
550 .BR FUTEX_WAKE ,
551 then all waiters waiting on B would be woken up,
552 and they would all try to acquire lock A.
553 However, waking all of the threads in this manner would be pointless because
554 all except one of the threads would immediately block on lock A again.
555 By contrast, a requeue operation wakes just one waiter and moves
556 the other waiters to lock A,
557 and when the woken waiter unlocks A then the next waiter can proceed.
559 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
562 .BR FUTEX_WAKE_OP " (since Linux 2.6.14)"
563 .\" commit 4732efbeb997189d9f9b04708dc26bf8613ed721
564 .\"     Author: Jakub Jelinek <jakub@redhat.com>
565 .\"     Date:   Tue Sep 6 15:16:25 2005 -0700
566 .\" FIXME. (Torvald) The glibc condvar implementation is currently being
567 .\"     revised (e.g., to not use an internal lock anymore).
568 .\"     It is probably more future-proof to remove this paragraph.
569 .\" [Torvald, do you have an update here?]
570 This operation was added to support some user-space use cases
571 where more than one futex must be handled at the same time.
572 The most notable example is the implementation of
573 .BR pthread_cond_signal (3),
574 which requires operations on two futexes,
575 the one used to implement the mutex and the one used in the implementation
576 of the wait queue associated with the condition variable.
577 .BR FUTEX_WAKE_OP
578 allows such cases to be implemented without leading to
579 high rates of contention and context switching.
582 .BR FUTEX_WAKE_OP
583 operation is equivalent to executing the following code atomically
584 and totally ordered with respect to other futex operations on
585 any of the two supplied futex words:
587 .in +4n
589 uint32_t oldval = *(uint32_t *) uaddr2;
590 *(uint32_t *) uaddr2 = oldval \fIop\fP \fIoparg\fP;
591 futex(uaddr, FUTEX_WAKE, val, 0, 0, 0);
592 if (oldval \fIcmp\fP \fIcmparg\fP)
593     futex(uaddr2, FUTEX_WAKE, val2, 0, 0, 0);
597 In other words,
598 .BR FUTEX_WAKE_OP
599 does the following:
601 .IP * 3
602 saves the original value of the futex word at
603 .IR uaddr2
604 and performs an operation to modify the value of the futex at
605 .IR uaddr2 ;
606 this is an atomic read-modify-write memory access (i.e., using atomic
607 machine instructions of the respective architecture)
608 .IP *
609 wakes up a maximum of
610 .I val
611 waiters on the futex for the futex word at
612 .IR uaddr ;
614 .IP *
615 dependent on the results of a test of the original value of the
616 futex word at
617 .IR uaddr2 ,
618 wakes up a maximum of
619 .I val2
620 waiters on the futex for the futex word at
621 .IR uaddr2 .
624 The operation and comparison that are to be performed are encoded
625 in the bits of the argument
626 .IR val3 .
627 Pictorially, the encoding is:
629 .in +4n
631 +---+---+-----------+-----------+
632 |op |cmp|   oparg   |  cmparg   |
633 +---+---+-----------+-----------+
634   4   4       12          12    <== # of bits
638 Expressed in code, the encoding is:
640 .in +4n
642 #define FUTEX_OP(op, oparg, cmp, cmparg) \e
643                 (((op & 0xf) << 28) | \e
644                 ((cmp & 0xf) << 24) | \e
645                 ((oparg & 0xfff) << 12) | \e
646                 (cmparg & 0xfff))
650 In the above,
651 .I op
653 .I cmp
654 are each one of the codes listed below.
656 .I oparg
658 .I cmparg
659 components are literal numeric values, except as noted below.
662 .I op
663 component has one of the following values:
665 .in +4n
667 FUTEX_OP_SET        0  /* uaddr2 = oparg; */
668 FUTEX_OP_ADD        1  /* uaddr2 += oparg; */
669 FUTEX_OP_OR         2  /* uaddr2 |= oparg; */
670 FUTEX_OP_ANDN       3  /* uaddr2 &= \(tioparg; */
671 FUTEX_OP_XOR        4  /* uaddr2 \(ha= oparg; */
675 In addition, bitwise ORing the following value into
676 .I op
677 causes
678 .IR "(1\ <<\ oparg)"
679 to be used as the operand:
681 .in +4n
683 FUTEX_OP_ARG_SHIFT  8  /* Use (1 << oparg) as operand */
688 .I cmp
689 field is one of the following:
691 .in +4n
693 FUTEX_OP_CMP_EQ     0  /* if (oldval == cmparg) wake */
694 FUTEX_OP_CMP_NE     1  /* if (oldval != cmparg) wake */
695 FUTEX_OP_CMP_LT     2  /* if (oldval < cmparg) wake */
696 FUTEX_OP_CMP_LE     3  /* if (oldval <= cmparg) wake */
697 FUTEX_OP_CMP_GT     4  /* if (oldval > cmparg) wake */
698 FUTEX_OP_CMP_GE     5  /* if (oldval >= cmparg) wake */
702 The return value of
703 .BR FUTEX_WAKE_OP
704 is the sum of the number of waiters woken on the futex
705 .IR uaddr
706 plus the number of waiters woken on the futex
707 .IR uaddr2 .
709 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
712 .BR FUTEX_WAIT_BITSET " (since Linux 2.6.25)"
713 .\" commit cd689985cf49f6ff5c8eddc48d98b9d581d9475d
714 This operation is like
715 .BR FUTEX_WAIT
716 except that
717 .I val3
718 is used to provide a 32-bit bit mask to the kernel.
719 This bit mask, in which at least one bit must be set,
720 is stored in the kernel-internal state of the waiter.
721 See the description of
722 .BR FUTEX_WAKE_BITSET
723 for further details.
726 .I timeout
727 is not NULL, the structure it points to specifies
728 an absolute timeout for the wait operation.
730 .I timeout
731 is NULL, the operation can block indefinitely.
734 .I uaddr2
735 argument is ignored.
737 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
740 .BR FUTEX_WAKE_BITSET " (since Linux 2.6.25)"
741 .\" commit cd689985cf49f6ff5c8eddc48d98b9d581d9475d
742 This operation is the same as
743 .BR FUTEX_WAKE
744 except that the
745 .I val3
746 argument is used to provide a 32-bit bit mask to the kernel.
747 This bit mask, in which at least one bit must be set,
748 is used to select which waiters should be woken up.
749 The selection is done by a bitwise AND of the "wake" bit mask
750 (i.e., the value in
751 .IR val3 )
752 and the bit mask which is stored in the kernel-internal
753 state of the waiter (the "wait" bit mask that is set using
754 .BR FUTEX_WAIT_BITSET ).
755 All of the waiters for which the result of the AND is nonzero are woken up;
756 the remaining waiters are left sleeping.
758 The effect of
759 .BR FUTEX_WAIT_BITSET
761 .BR FUTEX_WAKE_BITSET
762 is to allow selective wake-ups among multiple waiters that are blocked
763 on the same futex.
764 However, note that, depending on the use case,
765 employing this bit-mask multiplexing feature on a
766 futex can be less efficient than simply using multiple futexes,
767 because employing bit-mask multiplexing requires the kernel
768 to check all waiters on a futex,
769 including those that are not interested in being woken up
770 (i.e., they do not have the relevant bit set in their "wait" bit mask).
771 .\" According to http://locklessinc.com/articles/futex_cheat_sheet/:
773 .\"    "The original reason for the addition of these extensions
774 .\"     was to improve the performance of pthread read-write locks
775 .\"     in glibc. However, the pthreads library no longer uses the
776 .\"     same locking algorithm, and these extensions are not used
777 .\"     without the bitset parameter being all ones.
779 .\" The page goes on to note that the FUTEX_WAIT_BITSET operation
780 .\" is nevertheless used (with a bit mask of all ones) in order to
781 .\" obtain the absolute timeout functionality that is useful
782 .\" for efficiently implementing Pthreads APIs (which use absolute
783 .\" timeouts); FUTEX_WAIT provides only relative timeouts.
785 The constant
786 .BR FUTEX_BITSET_MATCH_ANY ,
787 which corresponds to all 32 bits set in the bit mask, can be used as the
788 .I val3
789 argument for
790 .BR FUTEX_WAIT_BITSET
792 .BR FUTEX_WAKE_BITSET .
793 Other than differences in the handling of the
794 .I timeout
795 argument, the
796 .BR FUTEX_WAIT
797 operation is equivalent to
798 .BR FUTEX_WAIT_BITSET
799 with
800 .IR val3
801 specified as
802 .BR FUTEX_BITSET_MATCH_ANY ;
803 that is, allow a wake-up by any waker.
805 .BR FUTEX_WAKE
806 operation is equivalent to
807 .BR FUTEX_WAKE_BITSET
808 with
809 .IR val3
810 specified as
811 .BR FUTEX_BITSET_MATCH_ANY ;
812 that is, wake up any waiter(s).
815 .I uaddr2
817 .I timeout
818 arguments are ignored.
820 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
822 .SS Priority-inheritance futexes
823 Linux supports priority-inheritance (PI) futexes in order to handle
824 priority-inversion problems that can be encountered with
825 normal futex locks.
826 Priority inversion is the problem that occurs when a high-priority
827 task is blocked waiting to acquire a lock held by a low-priority task,
828 while tasks at an intermediate priority continuously preempt
829 the low-priority task from the CPU.
830 Consequently, the low-priority task makes no progress toward
831 releasing the lock, and the high-priority task remains blocked.
833 Priority inheritance is a mechanism for dealing with
834 the priority-inversion problem.
835 With this mechanism, when a high-priority task becomes blocked
836 by a lock held by a low-priority task,
837 the priority of the low-priority task is temporarily raised
838 to that of the high-priority task,
839 so that it is not preempted by any intermediate level tasks,
840 and can thus make progress toward releasing the lock.
841 To be effective, priority inheritance must be transitive,
842 meaning that if a high-priority task blocks on a lock
843 held by a lower-priority task that is itself blocked by a lock
844 held by another intermediate-priority task
845 (and so on, for chains of arbitrary length),
846 then both of those tasks
847 (or more generally, all of the tasks in a lock chain)
848 have their priorities raised to be the same as the high-priority task.
850 From a user-space perspective,
851 what makes a futex PI-aware is a policy agreement (described below)
852 between user space and the kernel about the value of the futex word,
853 coupled with the use of the PI-futex operations described below.
854 (Unlike the other futex operations described above,
855 the PI-futex operations are designed
856 for the implementation of very specific IPC mechanisms.)
858 .\" Quoting Darren Hart:
859 .\"     These opcodes paired with the PI futex value policy (described below)
860 .\"     defines a "futex" as PI aware. These were created very specifically
861 .\"     in support of PI pthread_mutexes, so it makes a lot more sense to
862 .\"     talk about a PI aware pthread_mutex, than a PI aware futex, since
863 .\"     there is a lot of policy and scaffolding that has to be built up
864 .\"     around it to use it properly (this is what a PI pthread_mutex is).
866 .\"       mtk: The following text is drawn from the Hart/Guniguntala paper
867 .\"       (listed in SEE ALSO), but I have reworded some pieces
868 .\"       significantly.
870 The PI-futex operations described below differ from the other
871 futex operations in that they impose policy on the use of the value of the
872 futex word:
873 .IP * 3
874 If the lock is not acquired, the futex word's value shall be 0.
875 .IP *
876 If the lock is acquired, the futex word's value shall
877 be the thread ID (TID;
879 .BR gettid (2))
880 of the owning thread.
881 .IP *
882 If the lock is owned and there are threads contending for the lock,
883 then the
884 .B FUTEX_WAITERS
885 bit shall be set in the futex word's value; in other words, this value is:
887     FUTEX_WAITERS | TID
889 (Note that is invalid for a PI futex word to have no owner and
890 .BR FUTEX_WAITERS
891 set.)
893 With this policy in place,
894 a user-space application can acquire an unacquired
895 lock or release a lock using atomic instructions executed in user mode
896 (e.g., a compare-and-swap operation such as
897 .I cmpxchg
898 on the x86 architecture).
899 Acquiring a lock simply consists of using compare-and-swap to atomically
900 set the futex word's value to the caller's TID if its previous value was 0.
901 Releasing a lock requires using compare-and-swap to set the futex word's
902 value to 0 if the previous value was the expected TID.
904 If a futex is already acquired (i.e., has a nonzero value),
905 waiters must employ the
906 .B FUTEX_LOCK_PI
907 operation to acquire the lock.
908 If other threads are waiting for the lock, then the
909 .B FUTEX_WAITERS
910 bit is set in the futex value;
911 in this case, the lock owner must employ the
912 .B FUTEX_UNLOCK_PI
913 operation to release the lock.
915 In the cases where callers are forced into the kernel
916 (i.e., required to perform a
917 .BR futex ()
918 call),
919 they then deal directly with a so-called RT-mutex,
920 a kernel locking mechanism which implements the required
921 priority-inheritance semantics.
922 After the RT-mutex is acquired, the futex value is updated accordingly,
923 before the calling thread returns to user space.
925 It is important to note
926 .\" tglx (July 2015):
927 .\"     If there are multiple waiters on a pi futex then a wake pi operation
928 .\"     will wake the first waiter and hand over the lock to this waiter. This
929 .\"     includes handing over the rtmutex which represents the futex in the
930 .\"     kernel. The strict requirement is that the futex owner and the rtmutex
931 .\"     owner must be the same, except for the update period which is
932 .\"     serialized by the futex internal locking. That means the kernel must
933 .\"     update the user-space value prior to returning to user space
934 that the kernel will update the futex word's value prior
935 to returning to user space.
936 (This prevents the possibility of the futex word's value ending
937 up in an invalid state, such as having an owner but the value being 0,
938 or having waiters but not having the
939 .B FUTEX_WAITERS
940 bit set.)
942 If a futex has an associated RT-mutex in the kernel
943 (i.e., there are blocked waiters)
944 and the owner of the futex/RT-mutex dies unexpectedly,
945 then the kernel cleans up the RT-mutex and hands it over to the next waiter.
946 This in turn requires that the user-space value is updated accordingly.
947 To indicate that this is required, the kernel sets the
948 .B FUTEX_OWNER_DIED
949 bit in the futex word along with the thread ID of the new owner.
950 User space can detect this situation via the presence of the
951 .B FUTEX_OWNER_DIED
952 bit and is then responsible for cleaning up the stale state left over by
953 the dead owner.
954 .\" tglx (July 2015):
955 .\"     The FUTEX_OWNER_DIED bit can also be set on uncontended futexes, where
956 .\"     the kernel has no state associated. This happens via the robust futex
957 .\"     mechanism. In that case the futex value will be set to
958 .\"     FUTEX_OWNER_DIED. The robust futex mechanism is also available for non
959 .\"     PI futexes.
961 PI futexes are operated on by specifying one of the values listed below in
962 .IR futex_op .
963 Note that the PI futex operations must be used as paired operations
964 and are subject to some additional requirements:
965 .IP * 3
966 .B FUTEX_LOCK_PI
968 .B FUTEX_TRYLOCK_PI
969 pair with
970 .BR FUTEX_UNLOCK_PI .
971 .B FUTEX_UNLOCK_PI
972 must be called only on a futex owned by the calling thread,
973 as defined by the value policy, otherwise the error
974 .B EPERM
975 results.
976 .IP *
977 .B FUTEX_WAIT_REQUEUE_PI
978 pairs with
979 .BR FUTEX_CMP_REQUEUE_PI .
980 This must be performed from a non-PI futex to a distinct PI futex
981 (or the error
982 .B EINVAL
983 results).
984 Additionally,
985 .I val
986 (the number of waiters to be woken) must be 1
987 (or the error
988 .B EINVAL
989 results).
991 The PI futex operations are as follows:
993 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
996 .BR FUTEX_LOCK_PI " (since Linux 2.6.18)"
997 .\" commit c87e2837be82df479a6bae9f155c43516d2feebc
998 This operation is used after an attempt to acquire
999 the lock via an atomic user-mode instruction failed
1000 because the futex word has a nonzero value\(emspecifically,
1001 because it contained the (PID-namespace-specific) TID of the lock owner.
1003 The operation checks the value of the futex word at the address
1004 .IR uaddr .
1005 If the value is 0, then the kernel tries to atomically set
1006 the futex value to the caller's TID.
1007 If the futex word's value is nonzero,
1008 the kernel atomically sets the
1009 .B FUTEX_WAITERS
1010 bit, which signals the futex owner that it cannot unlock the futex in
1011 user space atomically by setting the futex value to 0.
1012 .\" tglx (July 2015):
1013 .\"     The operation here is similar to the FUTEX_WAIT logic. When the user
1014 .\"     space atomic acquire does not succeed because the futex value was non
1015 .\"     zero, then the waiter goes into the kernel, takes the kernel internal
1016 .\"     lock and retries the acquisition under the lock. If the acquisition
1017 .\"     does not succeed either, then it sets the FUTEX_WAITERS bit, to signal
1018 .\"     the lock owner that it needs to go into the kernel. Here is the pseudo
1019 .\"     code:
1021 .\"             lock(kernel_lock);
1022 .\"     retry:
1024 .\"             /*
1025 .\"              * Owner might have unlocked in user space before we
1026 .\"              * were able to set the waiter bit.
1027 .\"              */
1028 .\"             if (atomic_acquire(futex) == SUCCESS) {
1029 .\"                unlock(kernel_lock());
1030 .\"                return 0;
1031 .\"             }
1033 .\"             /*
1034 .\"              * Owner might have unlocked after the above atomic_acquire()
1035 .\"              * attempt.
1036 .\"              */
1037 .\"             if (atomic_set_waiters_bit(futex) != SUCCESS)
1038 .\"                goto retry;
1040 .\"             queue_waiter();
1041 .\"             unlock(kernel_lock);
1042 .\"             block();
1044 After that, the kernel:
1046 .IP 1. 3
1047 Tries to find the thread which is associated with the owner TID.
1048 .IP 2.
1049 Creates or reuses kernel state on behalf of the owner.
1050 (If this is the first waiter, there is no kernel state for this
1051 futex, so kernel state is created by locking the RT-mutex
1052 and the futex owner is made the owner of the RT-mutex.
1053 If there are existing waiters, then the existing state is reused.)
1054 .IP 3.
1055 Attaches the waiter to the futex
1056 (i.e., the waiter is enqueued on the RT-mutex waiter list).
1059 If more than one waiter exists,
1060 the enqueueing of the waiter is in descending priority order.
1061 (For information on priority ordering, see the discussion of the
1062 .BR SCHED_DEADLINE ,
1063 .BR SCHED_FIFO ,
1065 .BR SCHED_RR
1066 scheduling policies in
1067 .BR sched (7).)
1068 The owner inherits either the waiter's CPU bandwidth
1069 (if the waiter is scheduled under the
1070 .BR SCHED_DEADLINE
1071 policy) or the waiter's priority (if the waiter is scheduled under the
1072 .BR SCHED_RR
1074 .BR SCHED_FIFO
1075 policy).
1076 .\" August 2015:
1077 .\"     mtk: If the realm is restricted purely to SCHED_OTHER (SCHED_NORMAL)
1078 .\"          processes, does the nice value come into play also?
1080 .\"     tglx: No. SCHED_OTHER/NORMAL tasks are handled in FIFO order
1081 This inheritance follows the lock chain in the case of nested locking
1082 .\" (i.e., task 1 blocks on lock A, held by task 2,
1083 .\" while task 2 blocks on lock B, held by task 3)
1084 and performs deadlock detection.
1087 .I timeout
1088 argument provides a timeout for the lock attempt.
1090 .I timeout
1091 is not NULL, the structure it points to specifies
1092 an absolute timeout, measured against the
1093 .BR CLOCK_REALTIME
1094 clock.
1095 .\" 2016-07-07 response from Thomas Gleixner on LKML:
1096 .\" From: Thomas Gleixner <tglx@linutronix.de>
1097 .\" Date: 6 July 2016 at 20:57
1098 .\" Subject: Re: futex: Allow FUTEX_CLOCK_REALTIME with FUTEX_WAIT op
1100 .\" On Thu, 23 Jun 2016, Michael Kerrisk (man-pages) wrote:
1101 .\" > On 06/23/2016 08:28 PM, Darren Hart wrote:
1102 .\" > > And as a follow-on, what is the reason for FUTEX_LOCK_PI only using
1103 .\" > > CLOCK_REALTIME? It seems reasonable to me that a user may want to wait a
1104 .\" > > specific amount of time, regardless of wall time.
1105 .\" >
1106 .\" > Yes, that's another weird inconsistency.
1108 .\" The reason is that phtread_mutex_timedlock() uses absolute timeouts based on
1109 .\" CLOCK_REALTIME. glibc folks asked to make that the default behaviour back
1110 .\" then when we added LOCK_PI.
1112 .I timeout
1113 is NULL, the operation will block indefinitely.
1116 .IR uaddr2 ,
1117 .IR val ,
1119 .IR val3
1120 arguments are ignored.
1122 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
1125 .BR FUTEX_TRYLOCK_PI " (since Linux 2.6.18)"
1126 .\" commit c87e2837be82df479a6bae9f155c43516d2feebc
1127 This operation tries to acquire the lock at
1128 .IR uaddr .
1129 It is invoked when a user-space atomic acquire did not
1130 succeed because the futex word was not 0.
1132 Because the kernel has access to more state information than user space,
1133 acquisition of the lock might succeed if performed by the
1134 kernel in cases where the futex word
1135 (i.e., the state information accessible to use-space) contains stale state
1136 .RB ( FUTEX_WAITERS
1137 and/or
1138 .BR FUTEX_OWNER_DIED ).
1139 This can happen when the owner of the futex died.
1140 User space cannot handle this condition in a race-free manner,
1141 but the kernel can fix this up and acquire the futex.
1142 .\" Paraphrasing a f2f conversation with Thomas Gleixner about the
1143 .\" above point (Aug 2015): ###
1144 .\"     There is a rare possibility of a race condition involving an
1145 .\"     uncontended futex with no owner, but with waiters.  The
1146 .\"     kernel-user-space contract is that if a futex is nonzero, you must
1147 .\"     go into kernel.  The futex was owned by a task, and that task dies
1148 .\"     but there are no waiters, so the futex value is non zero.
1149 .\"     Therefore, the next locker has to go into the kernel,
1150 .\"     so that the kernel has a chance to clean up. (CMXCH on zero
1151 .\"     in user space would fail, so kernel has to clean up.)
1152 .\" Darren Hart (Oct 2015):
1153 .\"     The trylock in the kernel has more state, so it can independently
1154 .\"     verify the flags that user space must trust implicitly.
1157 .IR uaddr2 ,
1158 .IR val ,
1159 .IR timeout ,
1161 .IR val3
1162 arguments are ignored.
1164 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
1167 .BR FUTEX_UNLOCK_PI " (since Linux 2.6.18)"
1168 .\" commit c87e2837be82df479a6bae9f155c43516d2feebc
1169 This operation wakes the top priority waiter that is waiting in
1170 .B FUTEX_LOCK_PI
1171 on the futex address provided by the
1172 .I uaddr
1173 argument.
1175 This is called when the user-space value at
1176 .I uaddr
1177 cannot be changed atomically from a TID (of the owner) to 0.
1180 .IR uaddr2 ,
1181 .IR val ,
1182 .IR timeout ,
1184 .IR val3
1185 arguments are ignored.
1187 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
1190 .BR FUTEX_CMP_REQUEUE_PI " (since Linux 2.6.31)"
1191 .\" commit 52400ba946759af28442dee6265c5c0180ac7122
1192 This operation is a PI-aware variant of
1193 .BR FUTEX_CMP_REQUEUE .
1194 It requeues waiters that are blocked via
1195 .B FUTEX_WAIT_REQUEUE_PI
1197 .I uaddr
1198 from a non-PI source futex
1199 .RI ( uaddr )
1200 to a PI target futex
1201 .RI ( uaddr2 ).
1203 As with
1204 .BR FUTEX_CMP_REQUEUE ,
1205 this operation wakes up a maximum of
1206 .I val
1207 waiters that are waiting on the futex at
1208 .IR uaddr .
1209 However, for
1210 .BR FUTEX_CMP_REQUEUE_PI ,
1211 .I val
1212 is required to be 1
1213 (since the main point is to avoid a thundering herd).
1214 The remaining waiters are removed from the wait queue of the source futex at
1215 .I uaddr
1216 and added to the wait queue of the target futex at
1217 .IR uaddr2 .
1220 .I val2
1221 .\" val2 is the cap on the number of requeued waiters.
1222 .\" In the glibc pthread_cond_broadcast() implementation, this argument
1223 .\" is specified as INT_MAX, and for pthread_cond_signal() it is 0.
1225 .I val3
1226 arguments serve the same purposes as for
1227 .BR FUTEX_CMP_REQUEUE .
1229 .\"       The page at http://locklessinc.com/articles/futex_cheat_sheet/
1230 .\"       notes that "priority-inheritance Futex to priority-inheritance
1231 .\"       Futex requeues are currently unsupported". However, probably
1232 .\"       the page does not need to say nothing about this, since
1233 .\"       Thomas Gleixner commented (July 2015): "they never will be
1234 .\"       supported because they make no sense at all"
1236 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
1239 .BR FUTEX_WAIT_REQUEUE_PI " (since Linux 2.6.31)"
1240 .\" commit 52400ba946759af28442dee6265c5c0180ac7122
1242 Wait on a non-PI futex at
1243 .I uaddr
1244 and potentially be requeued (via a
1245 .BR FUTEX_CMP_REQUEUE_PI
1246 operation in another task) onto a PI futex at
1247 .IR uaddr2 .
1248 The wait operation on
1249 .I uaddr
1250 is the same as for
1251 .BR FUTEX_WAIT .
1253 The waiter can be removed from the wait on
1254 .I uaddr
1255 without requeueing on
1256 .IR uaddr2
1257 via a
1258 .BR FUTEX_WAKE
1259 operation in another task.
1260 In this case, the
1261 .BR FUTEX_WAIT_REQUEUE_PI
1262 operation fails with the error
1263 .BR EAGAIN .
1266 .I timeout
1267 is not NULL, the structure it points to specifies
1268 an absolute timeout for the wait operation.
1270 .I timeout
1271 is NULL, the operation can block indefinitely.
1274 .I val3
1275 argument is ignored.
1278 .BR FUTEX_WAIT_REQUEUE_PI
1280 .BR FUTEX_CMP_REQUEUE_PI
1281 were added to support a fairly specific use case:
1282 support for priority-inheritance-aware POSIX threads condition variables.
1283 The idea is that these operations should always be paired,
1284 in order to ensure that user space and the kernel remain in sync.
1285 Thus, in the
1286 .BR FUTEX_WAIT_REQUEUE_PI
1287 operation, the user-space application pre-specifies the target
1288 of the requeue that takes place in the
1289 .BR FUTEX_CMP_REQUEUE_PI
1290 operation.
1292 .\" Darren Hart notes that a patch to allow glibc to fully support
1293 .\" PI-aware pthreads condition variables has not yet been accepted into
1294 .\" glibc. The story is complex, and can be found at
1295 .\" https://sourceware.org/bugzilla/show_bug.cgi?id=11588
1296 .\" Darren notes that in the meantime, the patch is shipped with various
1297 .\" PREEMPT_RT-enabled Linux systems.
1299 .\" Related to the preceding, Darren proposed that somewhere, man-pages
1300 .\" should document the following point:
1302 .\"     While the Linux kernel, since 2.6.31, supports requeueing of
1303 .\"     priority-inheritance (PI) aware mutexes via the
1304 .\"     FUTEX_WAIT_REQUEUE_PI and FUTEX_CMP_REQUEUE_PI futex operations,
1305 .\"     the glibc implementation does not yet take full advantage of this.
1306 .\"     Specifically, the condvar internal data lock remains a non-PI aware
1307 .\"     mutex, regardless of the type of the pthread_mutex associated with
1308 .\"     the condvar. This can lead to an unbounded priority inversion on
1309 .\"     the internal data lock even when associating a PI aware
1310 .\"     pthread_mutex with a condvar during a pthread_cond*_wait
1311 .\"     operation. For this reason, it is not recommended to rely on
1312 .\"     priority inheritance when using pthread condition variables.
1314 .\" The problem is that the obvious location for this text is
1315 .\" the pthread_cond*wait(3) man page. However, such a man page
1316 .\" does not currently exist.
1318 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
1320 .SH RETURN VALUE
1321 In the event of an error (and assuming that
1322 .BR futex ()
1323 was invoked via
1324 .BR syscall (2)),
1325 all operations return \-1 and set
1326 .I errno
1327 to indicate the error.
1329 The return value on success depends on the operation,
1330 as described in the following list:
1332 .B FUTEX_WAIT
1333 Returns 0 if the caller was woken up.
1334 Note that a wake-up can also be caused by common futex usage patterns
1335 in unrelated code that happened to have previously used the futex word's
1336 memory location (e.g., typical futex-based implementations of
1337 Pthreads mutexes can cause this under some conditions).
1338 Therefore, callers should always conservatively assume that a return
1339 value of 0 can mean a spurious wake-up, and use the futex word's value
1340 (i.e., the user-space synchronization scheme)
1341 to decide whether to continue to block or not.
1343 .B FUTEX_WAKE
1344 Returns the number of waiters that were woken up.
1346 .B FUTEX_FD
1347 Returns the new file descriptor associated with the futex.
1349 .B FUTEX_REQUEUE
1350 Returns the number of waiters that were woken up.
1352 .B FUTEX_CMP_REQUEUE
1353 Returns the total number of waiters that were woken up or
1354 requeued to the futex for the futex word at
1355 .IR uaddr2 .
1356 If this value is greater than
1357 .IR val ,
1358 then the difference is the number of waiters requeued to the futex for the
1359 futex word at
1360 .IR uaddr2 .
1362 .B FUTEX_WAKE_OP
1363 Returns the total number of waiters that were woken up.
1364 This is the sum of the woken waiters on the two futexes for
1365 the futex words at
1366 .I uaddr
1368 .IR uaddr2 .
1370 .B FUTEX_WAIT_BITSET
1371 Returns 0 if the caller was woken up.
1373 .B FUTEX_WAIT
1374 for how to interpret this correctly in practice.
1376 .B FUTEX_WAKE_BITSET
1377 Returns the number of waiters that were woken up.
1379 .B FUTEX_LOCK_PI
1380 Returns 0 if the futex was successfully locked.
1382 .B FUTEX_TRYLOCK_PI
1383 Returns 0 if the futex was successfully locked.
1385 .B FUTEX_UNLOCK_PI
1386 Returns 0 if the futex was successfully unlocked.
1388 .B FUTEX_CMP_REQUEUE_PI
1389 Returns the total number of waiters that were woken up or
1390 requeued to the futex for the futex word at
1391 .IR uaddr2 .
1392 If this value is greater than
1393 .IR val ,
1394 then difference is the number of waiters requeued to the futex for
1395 the futex word at
1396 .IR uaddr2 .
1398 .B FUTEX_WAIT_REQUEUE_PI
1399 Returns 0 if the caller was successfully requeued to the futex for
1400 the futex word at
1401 .IR uaddr2 .
1403 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
1405 .SH ERRORS
1407 .B EACCES
1408 No read access to the memory of a futex word.
1410 .B EAGAIN
1411 .RB ( FUTEX_WAIT ,
1412 .BR FUTEX_WAIT_BITSET ,
1413 .BR FUTEX_WAIT_REQUEUE_PI )
1414 The value pointed to by
1415 .I uaddr
1416 was not equal to the expected value
1417 .I val
1418 at the time of the call.
1420 .BR Note :
1421 on Linux, the symbolic names
1422 .B EAGAIN
1424 .B EWOULDBLOCK
1425 (both of which appear in different parts of the kernel futex code)
1426 have the same value.
1428 .B EAGAIN
1429 .RB ( FUTEX_CMP_REQUEUE ,
1430 .BR FUTEX_CMP_REQUEUE_PI )
1431 The value pointed to by
1432 .I uaddr
1433 is not equal to the expected value
1434 .IR val3 .
1436 .BR EAGAIN
1437 .RB ( FUTEX_LOCK_PI ,
1438 .BR FUTEX_TRYLOCK_PI ,
1439 .BR FUTEX_CMP_REQUEUE_PI )
1440 The futex owner thread ID of
1441 .I uaddr
1442 (for
1443 .BR FUTEX_CMP_REQUEUE_PI :
1444 .IR uaddr2 )
1445 is about to exit,
1446 but has not yet handled the internal state cleanup.
1447 Try again.
1449 .BR EDEADLK
1450 .RB ( FUTEX_LOCK_PI ,
1451 .BR FUTEX_TRYLOCK_PI ,
1452 .BR FUTEX_CMP_REQUEUE_PI )
1453 The futex word at
1454 .I uaddr
1455 is already locked by the caller.
1457 .BR EDEADLK
1458 .\" FIXME . I see that kernel/locking/rtmutex.c uses EDEADLK in some
1459 .\"       places, and EDEADLOCK in others. On almost all architectures
1460 .\"       these constants are synonymous. Is there a reason that both
1461 .\"       names are used?
1463 .\"       tglx (July 2015): "No. We should probably fix that."
1465 .RB ( FUTEX_CMP_REQUEUE_PI )
1466 While requeueing a waiter to the PI futex for the futex word at
1467 .IR uaddr2 ,
1468 the kernel detected a deadlock.
1470 .B EFAULT
1471 A required pointer argument (i.e.,
1472 .IR uaddr ,
1473 .IR uaddr2 ,
1475 .IR timeout )
1476 did not point to a valid user-space address.
1478 .B EINTR
1480 .B FUTEX_WAIT
1482 .B FUTEX_WAIT_BITSET
1483 operation was interrupted by a signal (see
1484 .BR signal (7)).
1485 In kernels before Linux 2.6.22, this error could also be returned for
1486 a spurious wakeup; since Linux 2.6.22, this no longer happens.
1488 .B EINVAL
1489 The operation in
1490 .IR futex_op
1491 is one of those that employs a timeout, but the supplied
1492 .I timeout
1493 argument was invalid
1494 .RI ( tv_sec
1495 was less than zero, or
1496 .IR tv_nsec
1497 was not less than 1,000,000,000).
1499 .B EINVAL
1500 The operation specified in
1501 .IR futex_op
1502 employs one or both of the pointers
1503 .I uaddr
1505 .IR uaddr2 ,
1506 but one of these does not point to a valid object\(emthat is,
1507 the address is not four-byte-aligned.
1509 .B EINVAL
1510 .RB ( FUTEX_WAIT_BITSET ,
1511 .BR FUTEX_WAKE_BITSET )
1512 The bit mask supplied in
1513 .IR val3
1514 is zero.
1516 .B EINVAL
1517 .RB ( FUTEX_CMP_REQUEUE_PI )
1518 .I uaddr
1519 equals
1520 .IR uaddr2
1521 (i.e., an attempt was made to requeue to the same futex).
1523 .BR EINVAL
1524 .RB ( FUTEX_FD )
1525 The signal number supplied in
1526 .I val
1527 is invalid.
1529 .B EINVAL
1530 .RB ( FUTEX_WAKE ,
1531 .BR FUTEX_WAKE_OP ,
1532 .BR FUTEX_WAKE_BITSET ,
1533 .BR FUTEX_REQUEUE ,
1534 .BR FUTEX_CMP_REQUEUE )
1535 The kernel detected an inconsistency between the user-space state at
1536 .I uaddr
1537 and the kernel state\(emthat is, it detected a waiter which waits in
1538 .BR FUTEX_LOCK_PI
1540 .IR uaddr .
1542 .B EINVAL
1543 .RB ( FUTEX_LOCK_PI ,
1544 .BR FUTEX_TRYLOCK_PI ,
1545 .BR FUTEX_UNLOCK_PI )
1546 The kernel detected an inconsistency between the user-space state at
1547 .I uaddr
1548 and the kernel state.
1549 This indicates either state corruption
1550 or that the kernel found a waiter on
1551 .I uaddr
1552 which is waiting via
1553 .BR FUTEX_WAIT
1555 .BR FUTEX_WAIT_BITSET .
1557 .B EINVAL
1558 .RB ( FUTEX_CMP_REQUEUE_PI )
1559 The kernel detected an inconsistency between the user-space state at
1560 .I uaddr2
1561 and the kernel state;
1562 .\" From a conversation with Thomas Gleixner (Aug 2015): ###
1563 .\"     The kernel sees: I have non PI state for a futex you tried to
1564 .\"     tell me was PI
1565 that is, the kernel detected a waiter which waits via
1566 .BR FUTEX_WAIT
1568 .BR FUTEX_WAIT_BITSET
1570 .IR uaddr2 .
1572 .B EINVAL
1573 .RB ( FUTEX_CMP_REQUEUE_PI )
1574 The kernel detected an inconsistency between the user-space state at
1575 .I uaddr
1576 and the kernel state;
1577 that is, the kernel detected a waiter which waits via
1578 .BR FUTEX_WAIT
1580 .BR FUTEX_WAIT_BITSET
1582 .IR uaddr .
1584 .B EINVAL
1585 .RB ( FUTEX_CMP_REQUEUE_PI )
1586 The kernel detected an inconsistency between the user-space state at
1587 .I uaddr
1588 and the kernel state;
1589 that is, the kernel detected a waiter which waits on
1590 .I uaddr
1592 .BR FUTEX_LOCK_PI
1593 (instead of
1594 .BR FUTEX_WAIT_REQUEUE_PI ).
1596 .B EINVAL
1597 .RB ( FUTEX_CMP_REQUEUE_PI )
1598 .\" This deals with the case:
1599 .\"     wait_requeue_pi(A, B);
1600 .\"     requeue_pi(A, C);
1601 An attempt was made to requeue a waiter to a futex other than that
1602 specified by the matching
1603 .B FUTEX_WAIT_REQUEUE_PI
1604 call for that waiter.
1606 .B EINVAL
1607 .RB ( FUTEX_CMP_REQUEUE_PI )
1609 .I val
1610 argument is not 1.
1612 .B EINVAL
1613 Invalid argument.
1615 .B ENFILE
1616 .RB ( FUTEX_FD )
1617 The system-wide limit on the total number of open files has been reached.
1619 .BR ENOMEM
1620 .RB ( FUTEX_LOCK_PI ,
1621 .BR FUTEX_TRYLOCK_PI ,
1622 .BR FUTEX_CMP_REQUEUE_PI )
1623 The kernel could not allocate memory to hold state information.
1625 .B ENOSYS
1626 Invalid operation specified in
1627 .IR futex_op .
1629 .B ENOSYS
1631 .BR FUTEX_CLOCK_REALTIME
1632 option was specified in
1633 .IR futex_op ,
1634 but the accompanying operation was neither
1635 .BR FUTEX_WAIT ,
1636 .BR FUTEX_WAIT_BITSET ,
1638 .BR FUTEX_WAIT_REQUEUE_PI .
1640 .BR ENOSYS
1641 .RB ( FUTEX_LOCK_PI ,
1642 .BR FUTEX_TRYLOCK_PI ,
1643 .BR FUTEX_UNLOCK_PI ,
1644 .BR FUTEX_CMP_REQUEUE_PI ,
1645 .BR FUTEX_WAIT_REQUEUE_PI )
1646 A run-time check determined that the operation is not available.
1647 The PI-futex operations are not implemented on all architectures and
1648 are not supported on some CPU variants.
1650 .BR EPERM
1651 .RB ( FUTEX_LOCK_PI ,
1652 .BR FUTEX_TRYLOCK_PI ,
1653 .BR FUTEX_CMP_REQUEUE_PI )
1654 The caller is not allowed to attach itself to the futex at
1655 .I uaddr
1656 (for
1657 .BR FUTEX_CMP_REQUEUE_PI :
1658 the futex at
1659 .IR uaddr2 ).
1660 (This may be caused by a state corruption in user space.)
1662 .BR EPERM
1663 .RB ( FUTEX_UNLOCK_PI )
1664 The caller does not own the lock represented by the futex word.
1666 .BR ESRCH
1667 .RB ( FUTEX_LOCK_PI ,
1668 .BR FUTEX_TRYLOCK_PI ,
1669 .BR FUTEX_CMP_REQUEUE_PI )
1670 The thread ID in the futex word at
1671 .I uaddr
1672 does not exist.
1674 .BR ESRCH
1675 .RB ( FUTEX_CMP_REQUEUE_PI )
1676 The thread ID in the futex word at
1677 .I uaddr2
1678 does not exist.
1680 .B ETIMEDOUT
1681 The operation in
1682 .IR futex_op
1683 employed the timeout specified in
1684 .IR timeout ,
1685 and the timeout expired before the operation completed.
1687 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
1689 .SH VERSIONS
1690 Futexes were first made available in a stable kernel release
1691 with Linux 2.6.0.
1693 Initial futex support was merged in Linux 2.5.7 but with different
1694 semantics from what was described above.
1695 A four-argument system call with the semantics
1696 described in this page was introduced in Linux 2.5.40.
1697 A fifth argument was added in Linux 2.5.70,
1698 and a sixth argument was added in Linux 2.6.7.
1699 .SH CONFORMING TO
1700 This system call is Linux-specific.
1701 .SH NOTES
1702 Several higher-level programming abstractions are implemented via futexes,
1703 including POSIX semaphores and
1704 various POSIX threads synchronization mechanisms
1705 (mutexes, condition variables, read-write locks, and barriers).
1706 .\" TODO FIXME(Torvald) Above, we cite this section and claim it contains
1707 .\" details on the synchronization semantics; add the C11 equivalents
1708 .\" here (or whatever we find consensus for).
1710 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
1712 .SH EXAMPLES
1713 The program below demonstrates use of futexes in a program where a parent
1714 process and a child process use a pair of futexes located inside a
1715 shared anonymous mapping to synchronize access to a shared resource:
1716 the terminal.
1717 The two processes each write
1718 .IR nloops
1719 (a command-line argument that defaults to 5 if omitted)
1720 messages to the terminal and employ a synchronization protocol
1721 that ensures that they alternate in writing messages.
1722 Upon running this program we see output such as the following:
1724 .in +4n
1726 $ \fB./futex_demo\fP
1727 Parent (18534) 0
1728 Child  (18535) 0
1729 Parent (18534) 1
1730 Child  (18535) 1
1731 Parent (18534) 2
1732 Child  (18535) 2
1733 Parent (18534) 3
1734 Child  (18535) 3
1735 Parent (18534) 4
1736 Child  (18535) 4
1739 .SS Program source
1742 /* futex_demo.c
1744    Usage: futex_demo [nloops]
1745                     (Default: 5)
1747    Demonstrate the use of futexes in a program where parent and child
1748    use a pair of futexes located inside a shared anonymous mapping to
1749    synchronize access to a shared resource: the terminal. The two
1750    processes each write \(aqnum\-loops\(aq messages to the terminal and employ
1751    a synchronization protocol that ensures that they alternate in
1752    writing messages.
1754 #define _GNU_SOURCE
1755 #include <stdio.h>
1756 #include <errno.h>
1757 #include <stdatomic.h>
1758 #include <stdint.h>
1759 #include <stdlib.h>
1760 #include <unistd.h>
1761 #include <sys/wait.h>
1762 #include <sys/mman.h>
1763 #include <sys/syscall.h>
1764 #include <linux/futex.h>
1765 #include <sys/time.h>
1767 #define errExit(msg)    do { perror(msg); exit(EXIT_FAILURE); \e
1768                         } while (0)
1770 static uint32_t *futex1, *futex2, *iaddr;
1772 static int
1773 futex(uint32_t *uaddr, int futex_op, uint32_t val,
1774       const struct timespec *timeout, uint32_t *uaddr2, uint32_t val3)
1776     return syscall(SYS_futex, uaddr, futex_op, val,
1777                    timeout, uaddr2, val3);
1780 /* Acquire the futex pointed to by \(aqfutexp\(aq: wait for its value to
1781    become 1, and then set the value to 0. */
1783 static void
1784 fwait(uint32_t *futexp)
1786     long s;
1788     /* atomic_compare_exchange_strong(ptr, oldval, newval)
1789        atomically performs the equivalent of:
1791            if (*ptr == *oldval)
1792                *ptr = newval;
1794        It returns true if the test yielded true and *ptr was updated. */
1796     while (1) {
1798         /* Is the futex available? */
1799         const uint32_t one = 1;
1800         if (atomic_compare_exchange_strong(futexp, &one, 0))
1801             break;      /* Yes */
1803         /* Futex is not available; wait. */
1805         s = futex(futexp, FUTEX_WAIT, 0, NULL, NULL, 0);
1806         if (s == \-1 && errno != EAGAIN)
1807             errExit("futex\-FUTEX_WAIT");
1808     }
1811 /* Release the futex pointed to by \(aqfutexp\(aq: if the futex currently
1812    has the value 0, set its value to 1 and the wake any futex waiters,
1813    so that if the peer is blocked in fwait(), it can proceed. */
1815 static void
1816 fpost(uint32_t *futexp)
1818     long s;
1820     /* atomic_compare_exchange_strong() was described
1821        in comments above. */
1823     const uint32_t zero = 0;
1824     if (atomic_compare_exchange_strong(futexp, &zero, 1)) {
1825         s = futex(futexp, FUTEX_WAKE, 1, NULL, NULL, 0);
1826         if (s  == \-1)
1827             errExit("futex\-FUTEX_WAKE");
1828     }
1832 main(int argc, char *argv[])
1834     pid_t childPid;
1835     int nloops;
1837     setbuf(stdout, NULL);
1839     nloops = (argc > 1) ? atoi(argv[1]) : 5;
1841     /* Create a shared anonymous mapping that will hold the futexes.
1842        Since the futexes are being shared between processes, we
1843        subsequently use the "shared" futex operations (i.e., not the
1844        ones suffixed "_PRIVATE"). */
1846     iaddr = mmap(NULL, sizeof(*iaddr) * 2, PROT_READ | PROT_WRITE,
1847                 MAP_ANONYMOUS | MAP_SHARED, \-1, 0);
1848     if (iaddr == MAP_FAILED)
1849         errExit("mmap");
1851     futex1 = &iaddr[0];
1852     futex2 = &iaddr[1];
1854     *futex1 = 0;        /* State: unavailable */
1855     *futex2 = 1;        /* State: available */
1857     /* Create a child process that inherits the shared anonymous
1858        mapping. */
1860     childPid = fork();
1861     if (childPid == \-1)
1862         errExit("fork");
1864     if (childPid == 0) {        /* Child */
1865         for (int j = 0; j < nloops; j++) {
1866             fwait(futex1);
1867             printf("Child  (%jd) %d\en", (intmax_t) getpid(), j);
1868             fpost(futex2);
1869         }
1871         exit(EXIT_SUCCESS);
1872     }
1874     /* Parent falls through to here. */
1876     for (int j = 0; j < nloops; j++) {
1877         fwait(futex2);
1878         printf("Parent (%jd) %d\en", (intmax_t) getpid(), j);
1879         fpost(futex1);
1880     }
1882     wait(NULL);
1884     exit(EXIT_SUCCESS);
1887 .SH SEE ALSO
1888 .ad l
1889 .BR get_robust_list (2),
1890 .BR restart_syscall (2),
1891 .BR pthread_mutexattr_getprotocol (3),
1892 .BR futex (7),
1893 .BR sched (7)
1895 The following kernel source files:
1896 .IP * 2
1897 .I Documentation/pi\-futex.txt
1898 .IP *
1899 .I Documentation/futex\-requeue\-pi.txt
1900 .IP *
1901 .I Documentation/locking/rt\-mutex.txt
1902 .IP *
1903 .I Documentation/locking/rt\-mutex\-design.txt
1904 .IP *
1905 .I Documentation/robust\-futex\-ABI.txt
1907 Franke, H., Russell, R., and Kirwood, M., 2002.
1908 \fIFuss, Futexes and Furwocks: Fast Userlevel Locking in Linux\fP
1909 (from proceedings of the Ottawa Linux Symposium 2002),
1911 .UR http://kernel.org\:/doc\:/ols\:/2002\:/ols2002\-pages\-479\-495.pdf
1914 Hart, D., 2009. \fIA futex overview and update\fP,
1915 .UR http://lwn.net/Articles/360699/
1918 Hart, D.\& and Guniguntala, D., 2009.
1919 \fIRequeue-PI: Making Glibc Condvars PI-Aware\fP
1920 (from proceedings of the 2009 Real-Time Linux Workshop),
1921 .UR http://lwn.net/images/conf/rtlws11/papers/proc/p10.pdf
1924 Drepper, U., 2011. \fIFutexes Are Tricky\fP,
1925 .UR http://www.akkadia.org/drepper/futex.pdf
1928 Futex example library, futex-*.tar.bz2 at
1930 .UR ftp://ftp.kernel.org\:/pub\:/linux\:/kernel\:/people\:/rusty/
1933 .\" FIXME(Torvald) We should probably refer to the glibc code here, in
1934 .\" particular the glibc-internal futex wrapper functions that are
1935 .\" WIP, and the generic pthread_mutex_t and perhaps condvar
1936 .\" implementations.