tzfile.5, tzselect.8: sync from tzdb upstream
[man-pages.git] / man2 / futex.2
blobcd52254bad1d175f03d2cd6e17b2b8f786757ae5
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 (date) "Linux man-pages (unreleased)"
23 .SH NAME
24 futex \- fast user-space locking
25 .SH LIBRARY
26 Standard C library
27 .RI ( libc ", " \-lc )
28 .SH SYNOPSIS
29 .nf
30 .PP
31 .BR "#include <linux/futex.h>" "      /* Definition of " FUTEX_* " constants */"
32 .BR "#include <sys/syscall.h>" "      /* Definition of " SYS_* " constants */"
33 .B #include <unistd.h>
34 .PP
35 .BI "long syscall(SYS_futex, uint32_t *" uaddr ", int " futex_op \
36 ", uint32_t " val ,
37 .BI "             const struct timespec *" timeout , \
38 " \fR  /* or: \fBuint32_t \fIval2\fP */"
39 .BI "             uint32_t *" uaddr2 ", uint32_t " val3 );
40 .fi
41 .PP
42 .IR Note :
43 glibc provides no wrapper for
44 .BR futex (),
45 necessitating the use of
46 .BR syscall (2).
47 .SH DESCRIPTION
48 The
49 .BR futex ()
50 system call provides a method for waiting until a certain condition becomes
51 true.
52 It is typically used as a blocking construct in the context of
53 shared-memory synchronization.
54 When using futexes, the majority of
55 the synchronization operations are performed in user space.
56 A user-space program employs the
57 .BR futex ()
58 system call only when it is likely that the program has to block for
59 a longer time until the condition becomes true.
60 Other
61 .BR futex ()
62 operations can be used to wake any processes or threads waiting
63 for a particular condition.
64 .PP
65 A futex is a 32-bit value\[em]referred to below as a
66 .IR "futex word" \[em]whose
67 address is supplied to the
68 .BR futex ()
69 system call.
70 (Futexes are 32 bits in size on all platforms, including 64-bit systems.)
71 All futex operations are governed by this value.
72 In order to share a futex between processes,
73 the futex is placed in a region of shared memory,
74 created using (for example)
75 .BR mmap (2)
77 .BR shmat (2).
78 (Thus, the futex word may have different
79 virtual addresses in different processes,
80 but these addresses all refer to the same location in physical memory.)
81 In a multithreaded program, it is sufficient to place the futex word
82 in a global variable shared by all threads.
83 .PP
84 When executing a futex operation that requests to block a thread,
85 the kernel will block only if the futex word has the value that the
86 calling thread supplied (as one of the arguments of the
87 .BR futex ()
88 call) as the expected value of the futex word.
89 The loading of the futex word's value,
90 the comparison of that value with the expected value,
91 and the actual blocking will happen atomically and will be totally ordered
92 with respect to concurrent operations performed by other threads
93 on the same futex word.
94 .\" Notes from Darren Hart (Dec 2015):
95 .\"     Totally ordered with respect futex operations refers to semantics
96 .\"     of the ACQUIRE/RELEASE operations and how they impact ordering of
97 .\"     memory reads and writes. The kernel futex operations are protected
98 .\"     by spinlocks, which ensure that all operations are serialized
99 .\"     with respect to one another.
101 .\"     This is a lot to attempt to define in this document. Perhaps a
102 .\"     reference to linux/Documentation/memory-barriers.txt as a footnote
103 .\"     would be sufficient? Or perhaps for this manual, "serialized" would
104 .\"     be sufficient, with a footnote regarding "totally ordered" and a
105 .\"     pointer to the memory-barrier documentation?
106 Thus, the futex word is used to connect the synchronization in user space
107 with the implementation of blocking by the kernel.
108 Analogously to an atomic
109 compare-and-exchange operation that potentially changes shared memory,
110 blocking via a futex is an atomic compare-and-block operation.
111 .\" FIXME(Torvald Riegel):
112 .\" Eventually we want to have some text in NOTES to satisfy
113 .\" the reference in the following sentence
114 .\"     See NOTES for a detailed specification of
115 .\"     the synchronization semantics.
117 One use of futexes is for implementing locks.
118 The state of the lock (i.e., acquired or not acquired)
119 can be represented as an atomically accessed flag in shared memory.
120 In the uncontended case,
121 a thread can access or modify the lock state with atomic instructions,
122 for example atomically changing it from not acquired to acquired
123 using an atomic compare-and-exchange instruction.
124 (Such instructions are performed entirely in user mode,
125 and the kernel maintains no information about the lock state.)
126 On the other hand, a thread may be unable to acquire a lock because
127 it is already acquired by another thread.
128 It then may pass the lock's flag as a futex word and the value
129 representing the acquired state as the expected value to a
130 .BR futex ()
131 wait operation.
132 This
133 .BR futex ()
134 operation will block if and only if the lock is still acquired
135 (i.e., the value in the futex word still matches the "acquired state").
136 When releasing the lock, a thread has to first reset the
137 lock state to not acquired and then execute a futex
138 operation that wakes threads blocked on the lock flag used as a futex word
139 (this can be further optimized to avoid unnecessary wake-ups).
141 .BR futex (7)
142 for more detail on how to use futexes.
144 Besides the basic wait and wake-up futex functionality, there are further
145 futex operations aimed at supporting more complex use cases.
147 Note that
148 no explicit initialization or destruction is necessary to use futexes;
149 the kernel maintains a futex
150 (i.e., the kernel-internal implementation artifact)
151 only while operations such as
152 .BR FUTEX_WAIT ,
153 described below, are being performed on a particular futex word.
155 .SS Arguments
157 .I uaddr
158 argument points to the futex word.
159 On all platforms, futexes are four-byte
160 integers that must be aligned on a four-byte boundary.
161 The operation to perform on the futex is specified in the
162 .I futex_op
163 argument;
164 .I val
165 is a value whose meaning and purpose depends on
166 .IR futex_op .
168 The remaining arguments
169 .RI ( timeout ,
170 .IR uaddr2 ,
172 .IR val3 )
173 are required only for certain of the futex operations described below.
174 Where one of these arguments is not required, it is ignored.
176 For several blocking operations, the
177 .I timeout
178 argument is a pointer to a
179 .I timespec
180 structure that specifies a timeout for the operation.
181 However,  notwithstanding the prototype shown above, for some operations,
182 the least significant four bytes of this argument are instead
183 used as an integer whose meaning is determined by the operation.
184 For these operations, the kernel casts the
185 .I timeout
186 value first to
187 .IR "unsigned long",
188 then to
189 .IR uint32_t ,
190 and in the remainder of this page, this argument is referred to as
191 .I val2
192 when interpreted in this fashion.
194 Where it is required, the
195 .I uaddr2
196 argument is a pointer to a second futex word that is employed
197 by the operation.
199 The interpretation of the final integer argument,
200 .IR val3 ,
201 depends on the operation.
203 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
205 .SS Futex operations
207 .I futex_op
208 argument consists of two parts:
209 a command that specifies the operation to be performed,
210 bitwise ORed with zero or more options that
211 modify the behaviour of the operation.
212 The options that may be included in
213 .I futex_op
214 are as follows:
216 .BR FUTEX_PRIVATE_FLAG " (since Linux 2.6.22)"
217 .\" commit 34f01cc1f512fa783302982776895c73714ebbc2
218 This option bit can be employed with all futex operations.
219 It tells the kernel that the futex is process-private and not shared
220 with another process (i.e., it is being used for synchronization
221 only between threads of the same process).
222 This allows the kernel to make some additional performance optimizations.
223 .\" I.e., It allows the kernel choose the fast path for validating
224 .\" the user-space address and avoids expensive VMA lookups,
225 .\" taking reference counts on file backing store, and so on.
227 As a convenience,
228 .I <linux/futex.h>
229 defines a set of constants with the suffix
230 .B _PRIVATE
231 that are equivalents of all of the operations listed below,
232 .\" except the obsolete FUTEX_FD, for which the "private" flag was
233 .\" meaningless
234 but with the
235 .B FUTEX_PRIVATE_FLAG
236 ORed into the constant value.
237 Thus, there are
238 .BR FUTEX_WAIT_PRIVATE ,
239 .BR FUTEX_WAKE_PRIVATE ,
240 and so on.
242 .BR FUTEX_CLOCK_REALTIME " (since Linux 2.6.28)"
243 .\" commit 1acdac104668a0834cfa267de9946fac7764d486
244 This option bit can be employed only with the
245 .BR FUTEX_WAIT_BITSET ,
246 .BR FUTEX_WAIT_REQUEUE_PI ,
247 (since Linux 4.5)
248 .\" commit 337f13046ff03717a9e99675284a817527440a49
249 .BR FUTEX_WAIT ,
251 (since Linux 5.14)
252 .\" commit bf22a6976897977b0a3f1aeba6823c959fc4fdae
253 .B FUTEX_LOCK_PI2
254 operations.
256 If this option is set, the kernel measures the
257 .I timeout
258 against the
259 .B CLOCK_REALTIME
260 clock.
262 If this option is not set, the kernel measures the
263 .I timeout
264 against the
265 .B CLOCK_MONOTONIC
266 clock.
268 The operation specified in
269 .I futex_op
270 is one of the following:
272 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
275 .BR FUTEX_WAIT " (since Linux 2.6.0)"
276 .\" Strictly speaking, since some time in Linux 2.5.x
277 This operation tests that the value at the
278 futex word pointed to by the address
279 .I uaddr
280 still contains the expected value
281 .IR val ,
282 and if so, then sleeps waiting for a
283 .B FUTEX_WAKE
284 operation on the futex word.
285 The load of the value of the futex word is an atomic memory
286 access (i.e., using atomic machine instructions of the respective
287 architecture).
288 This load, the comparison with the expected value, and
289 starting to sleep are performed atomically
290 .\" FIXME: Torvald, I think we may need to add some explanation of
291 .\" "totally ordered" here.
292 and totally ordered
293 with respect to other futex operations on the same futex word.
294 If the thread starts to sleep,
295 it is considered a waiter on this futex word.
296 If the futex value does not match
297 .IR val ,
298 then the call fails immediately with the error
299 .BR EAGAIN .
301 The purpose of the comparison with the expected value is to prevent lost
302 wake-ups.
303 If another thread changed the value of the futex word after the
304 calling thread decided to block based on the prior value,
305 and if the other thread executed a
306 .B FUTEX_WAKE
307 operation (or similar wake-up) after the value change and before this
308 .B FUTEX_WAIT
309 operation, then the calling thread will observe the
310 value change and will not start to sleep.
312 If the
313 .I timeout
314 is not NULL, the structure it points to specifies a
315 timeout for the wait.
316 (This interval will be rounded up to the system clock granularity,
317 and is guaranteed not to expire early.)
318 The timeout is by default measured according to the
319 .B CLOCK_MONOTONIC
320 clock, but, since Linux 4.5, the
321 .B CLOCK_REALTIME
322 clock can be selected by specifying
323 .B FUTEX_CLOCK_REALTIME
325 .IR futex_op .
327 .I timeout
328 is NULL, the call blocks indefinitely.
330 .IR Note :
332 .BR FUTEX_WAIT ,
333 .I timeout
334 is interpreted as a
335 .I relative
336 value.
337 This differs from other futex operations, where
338 .I timeout
339 is interpreted as an absolute value.
340 To obtain the equivalent of
341 .B FUTEX_WAIT
342 with an absolute timeout, employ
343 .B FUTEX_WAIT_BITSET
344 with
345 .I val3
346 specified as
347 .BR FUTEX_BITSET_MATCH_ANY .
349 The arguments
350 .I uaddr2
352 .I val3
353 are ignored.
354 .\" FIXME . (Torvald) I think we should remove this.  Or maybe adapt to a
355 .\" different example.
357 .\"     For
358 .\"     .BR futex (7),
359 .\"     this call is executed if decrementing the count gave a negative value
360 .\"     (indicating contention),
361 .\"     and will sleep until another process or thread releases
362 .\"     the futex and executes the
363 .\"     .B FUTEX_WAKE
364 .\"     operation.
366 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
369 .BR FUTEX_WAKE " (since Linux 2.6.0)"
370 .\" Strictly speaking, since Linux 2.5.x
371 This operation wakes at most
372 .I val
373 of the waiters that are waiting (e.g., inside
374 .BR FUTEX_WAIT )
375 on the futex word at the address
376 .IR uaddr .
377 Most commonly,
378 .I val
379 is specified as either 1 (wake up a single waiter) or
380 .B INT_MAX
381 (wake up all waiters).
382 No guarantee is provided about which waiters are awoken
383 (e.g., a waiter with a higher scheduling priority is not guaranteed
384 to be awoken in preference to a waiter with a lower priority).
386 The arguments
387 .IR timeout ,
388 .IR uaddr2 ,
390 .I val3
391 are ignored.
392 .\" FIXME . (Torvald) I think we should remove this.  Or maybe adapt to
393 .\" a different example.
395 .\"     For
396 .\"     .BR futex (7),
397 .\"     this is executed if incrementing the count showed that
398 .\"     there were waiters,
399 .\"     once the futex value has been set to 1
400 .\"     (indicating that it is available).
402 .\" How does "incrementing the count show that there were waiters"?
404 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
407 .BR FUTEX_FD " (from Linux 2.6.0 up to and including Linux 2.6.25)"
408 .\" Strictly speaking, from Linux 2.5.x to Linux 2.6.25
409 This operation creates a file descriptor that is associated with
410 the futex at
411 .IR uaddr .
412 The caller must close the returned file descriptor after use.
413 When another process or thread performs a
414 .B FUTEX_WAKE
415 on the futex word, the file descriptor indicates as being readable with
416 .BR select (2),
417 .BR poll (2),
419 .BR epoll (7)
421 The file descriptor can be used to obtain asynchronous notifications: if
422 .I val
423 is nonzero, then, when another process or thread executes a
424 .BR FUTEX_WAKE ,
425 the caller will receive the signal number that was passed in
426 .IR val .
428 The arguments
429 .IR timeout ,
430 .IR uaddr2 ,
432 .I val3
433 are ignored.
435 Because it was inherently racy,
436 .B FUTEX_FD
437 has been removed
438 .\" commit 82af7aca56c67061420d618cc5a30f0fd4106b80
439 from Linux 2.6.26 onward.
441 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
444 .BR FUTEX_REQUEUE " (since Linux 2.6.0)"
445 This operation performs the same task as
446 .B FUTEX_CMP_REQUEUE
447 (see below), except that no check is made using the value in
448 .IR  val3 .
449 (The argument
450 .I val3
451 is ignored.)
453 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
456 .BR FUTEX_CMP_REQUEUE " (since Linux 2.6.7)"
457 This operation first checks whether the location
458 .I uaddr
459 still contains the value
460 .IR val3 .
461 If not, the operation fails with the error
462 .BR EAGAIN .
463 Otherwise, the operation wakes up a maximum of
464 .I val
465 waiters that are waiting on the futex at
466 .IR uaddr .
467 If there are more than
468 .I val
469 waiters, then the remaining waiters are removed
470 from the wait queue of the source futex at
471 .I uaddr
472 and added to the wait queue of the target futex at
473 .IR uaddr2 .
475 .I val2
476 argument specifies an upper limit on the number of waiters
477 that are requeued to the futex at
478 .IR uaddr2 .
480 .\" FIXME(Torvald) Is the following correct?  Or is just the decision
481 .\" which threads to wake or requeue part of the atomic operation?
482 The load from
483 .I uaddr
484 is an atomic memory access (i.e., using atomic machine instructions of
485 the respective architecture).
486 This load, the comparison with
487 .IR val3 ,
488 and the requeueing of any waiters are performed atomically and totally
489 ordered with respect to other operations on the same futex word.
490 .\" Notes from a f2f conversation with Thomas Gleixner (Aug 2015): ###
491 .\"     The operation is serialized with respect to operations on both
492 .\"     source and target futex. No other waiter can enqueue itself
493 .\"     for waiting and no other waiter can dequeue itself because of
494 .\"     a timeout or signal.
496 Typical values to specify for
497 .I val
498 are 0 or 1.
499 (Specifying
500 .B INT_MAX
501 is not useful, because it would make the
502 .B FUTEX_CMP_REQUEUE
503 operation equivalent to
504 .BR FUTEX_WAKE .)
505 The limit value specified via
506 .I val2
507 is typically either 1 or
508 .BR INT_MAX .
509 (Specifying the argument as 0 is not useful, because it would make the
510 .B FUTEX_CMP_REQUEUE
511 operation equivalent to
512 .BR FUTEX_WAIT .)
515 .B FUTEX_CMP_REQUEUE
516 operation was added as a replacement for the earlier
517 .BR FUTEX_REQUEUE .
518 The difference is that the check of the value at
519 .I uaddr
520 can be used to ensure that requeueing happens only under certain
521 conditions, which allows race conditions to be avoided in certain use cases.
522 .\" But, as Rich Felker points out, there remain valid use cases for
523 .\" FUTEX_REQUEUE, for example, when the calling thread is requeuing
524 .\" the target(s) to a lock that the calling thread owns
525 .\"     From: Rich Felker <dalias@libc.org>
526 .\"     Date: Wed, 29 Oct 2014 22:43:17 -0400
527 .\"     To: Darren Hart <dvhart@infradead.org>
528 .\"     CC: libc-alpha@sourceware.org, ...
529 .\"     Subject: Re: Add futex wrapper to glibc?
531 Both
532 .B FUTEX_REQUEUE
534 .B FUTEX_CMP_REQUEUE
535 can be used to avoid "thundering herd" wake-ups that could occur when using
536 .B FUTEX_WAKE
537 in cases where all of the waiters that are woken need to acquire
538 another futex.
539 Consider the following scenario,
540 where multiple waiter threads are waiting on B,
541 a wait queue implemented using a futex:
543 .in +4n
545 lock(A)
546 while (!check_value(V)) {
547     unlock(A);
548     block_on(B);
549     lock(A);
551 unlock(A);
555 If a waker thread used
556 .BR FUTEX_WAKE ,
557 then all waiters waiting on B would be woken up,
558 and they would all try to acquire lock A.
559 However, waking all of the threads in this manner would be pointless because
560 all except one of the threads would immediately block on lock A again.
561 By contrast, a requeue operation wakes just one waiter and moves
562 the other waiters to lock A,
563 and when the woken waiter unlocks A then the next waiter can proceed.
565 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
568 .BR FUTEX_WAKE_OP " (since Linux 2.6.14)"
569 .\" commit 4732efbeb997189d9f9b04708dc26bf8613ed721
570 .\"     Author: Jakub Jelinek <jakub@redhat.com>
571 .\"     Date:   Tue Sep 6 15:16:25 2005 -0700
572 .\" FIXME. (Torvald) The glibc condvar implementation is currently being
573 .\"     revised (e.g., to not use an internal lock anymore).
574 .\"     It is probably more future-proof to remove this paragraph.
575 .\" [Torvald, do you have an update here?]
576 This operation was added to support some user-space use cases
577 where more than one futex must be handled at the same time.
578 The most notable example is the implementation of
579 .BR pthread_cond_signal (3),
580 which requires operations on two futexes,
581 the one used to implement the mutex and the one used in the implementation
582 of the wait queue associated with the condition variable.
583 .B FUTEX_WAKE_OP
584 allows such cases to be implemented without leading to
585 high rates of contention and context switching.
588 .B FUTEX_WAKE_OP
589 operation is equivalent to executing the following code atomically
590 and totally ordered with respect to other futex operations on
591 any of the two supplied futex words:
593 .in +4n
595 uint32_t oldval = *(uint32_t *) uaddr2;
596 *(uint32_t *) uaddr2 = oldval \fIop\fP \fIoparg\fP;
597 futex(uaddr, FUTEX_WAKE, val, 0, 0, 0);
598 if (oldval \fIcmp\fP \fIcmparg\fP)
599     futex(uaddr2, FUTEX_WAKE, val2, 0, 0, 0);
603 In other words,
604 .B FUTEX_WAKE_OP
605 does the following:
607 .IP \[bu] 3
608 saves the original value of the futex word at
609 .I uaddr2
610 and performs an operation to modify the value of the futex at
611 .IR uaddr2 ;
612 this is an atomic read-modify-write memory access (i.e., using atomic
613 machine instructions of the respective architecture)
614 .IP \[bu]
615 wakes up a maximum of
616 .I val
617 waiters on the futex for the futex word at
618 .IR uaddr ;
620 .IP \[bu]
621 dependent on the results of a test of the original value of the
622 futex word at
623 .IR uaddr2 ,
624 wakes up a maximum of
625 .I val2
626 waiters on the futex for the futex word at
627 .IR uaddr2 .
630 The operation and comparison that are to be performed are encoded
631 in the bits of the argument
632 .IR val3 .
633 Pictorially, the encoding is:
635 .in +4n
637 +---+---+-----------+-----------+
638 |op |cmp|   oparg   |  cmparg   |
639 +---+---+-----------+-----------+
640   4   4       12          12    <== # of bits
644 Expressed in code, the encoding is:
646 .in +4n
648 #define FUTEX_OP(op, oparg, cmp, cmparg) \e
649                 (((op & 0xf) << 28) | \e
650                 ((cmp & 0xf) << 24) | \e
651                 ((oparg & 0xfff) << 12) | \e
652                 (cmparg & 0xfff))
656 In the above,
657 .I op
659 .I cmp
660 are each one of the codes listed below.
662 .I oparg
664 .I cmparg
665 components are literal numeric values, except as noted below.
668 .I op
669 component has one of the following values:
671 .in +4n
673 FUTEX_OP_SET        0  /* uaddr2 = oparg; */
674 FUTEX_OP_ADD        1  /* uaddr2 += oparg; */
675 FUTEX_OP_OR         2  /* uaddr2 |= oparg; */
676 FUTEX_OP_ANDN       3  /* uaddr2 &= \[ti]oparg; */
677 FUTEX_OP_XOR        4  /* uaddr2 \[ha]= oparg; */
681 In addition, bitwise ORing the following value into
682 .I op
683 causes
684 .I (1\~<<\~oparg)
685 to be used as the operand:
687 .in +4n
689 FUTEX_OP_ARG_SHIFT  8  /* Use (1 << oparg) as operand */
694 .I cmp
695 field is one of the following:
697 .in +4n
699 FUTEX_OP_CMP_EQ     0  /* if (oldval == cmparg) wake */
700 FUTEX_OP_CMP_NE     1  /* if (oldval != cmparg) wake */
701 FUTEX_OP_CMP_LT     2  /* if (oldval < cmparg) wake */
702 FUTEX_OP_CMP_LE     3  /* if (oldval <= cmparg) wake */
703 FUTEX_OP_CMP_GT     4  /* if (oldval > cmparg) wake */
704 FUTEX_OP_CMP_GE     5  /* if (oldval >= cmparg) wake */
708 The return value of
709 .B FUTEX_WAKE_OP
710 is the sum of the number of waiters woken on the futex
711 .I uaddr
712 plus the number of waiters woken on the futex
713 .IR uaddr2 .
715 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
718 .BR FUTEX_WAIT_BITSET " (since Linux 2.6.25)"
719 .\" commit cd689985cf49f6ff5c8eddc48d98b9d581d9475d
720 This operation is like
721 .B FUTEX_WAIT
722 except that
723 .I val3
724 is used to provide a 32-bit bit mask to the kernel.
725 This bit mask, in which at least one bit must be set,
726 is stored in the kernel-internal state of the waiter.
727 See the description of
728 .B FUTEX_WAKE_BITSET
729 for further details.
732 .I timeout
733 is not NULL, the structure it points to specifies
734 an absolute timeout for the wait operation.
736 .I timeout
737 is NULL, the operation can block indefinitely.
740 .I uaddr2
741 argument is ignored.
743 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
746 .BR FUTEX_WAKE_BITSET " (since Linux 2.6.25)"
747 .\" commit cd689985cf49f6ff5c8eddc48d98b9d581d9475d
748 This operation is the same as
749 .B FUTEX_WAKE
750 except that the
751 .I val3
752 argument is used to provide a 32-bit bit mask to the kernel.
753 This bit mask, in which at least one bit must be set,
754 is used to select which waiters should be woken up.
755 The selection is done by a bitwise AND of the "wake" bit mask
756 (i.e., the value in
757 .IR val3 )
758 and the bit mask which is stored in the kernel-internal
759 state of the waiter (the "wait" bit mask that is set using
760 .BR FUTEX_WAIT_BITSET ).
761 All of the waiters for which the result of the AND is nonzero are woken up;
762 the remaining waiters are left sleeping.
764 The effect of
765 .B FUTEX_WAIT_BITSET
767 .B FUTEX_WAKE_BITSET
768 is to allow selective wake-ups among multiple waiters that are blocked
769 on the same futex.
770 However, note that, depending on the use case,
771 employing this bit-mask multiplexing feature on a
772 futex can be less efficient than simply using multiple futexes,
773 because employing bit-mask multiplexing requires the kernel
774 to check all waiters on a futex,
775 including those that are not interested in being woken up
776 (i.e., they do not have the relevant bit set in their "wait" bit mask).
777 .\" According to http://locklessinc.com/articles/futex_cheat_sheet/:
779 .\"    "The original reason for the addition of these extensions
780 .\"     was to improve the performance of pthread read-write locks
781 .\"     in glibc. However, the pthreads library no longer uses the
782 .\"     same locking algorithm, and these extensions are not used
783 .\"     without the bitset parameter being all ones.
785 .\" The page goes on to note that the FUTEX_WAIT_BITSET operation
786 .\" is nevertheless used (with a bit mask of all ones) in order to
787 .\" obtain the absolute timeout functionality that is useful
788 .\" for efficiently implementing Pthreads APIs (which use absolute
789 .\" timeouts); FUTEX_WAIT provides only relative timeouts.
791 The constant
792 .BR FUTEX_BITSET_MATCH_ANY ,
793 which corresponds to all 32 bits set in the bit mask, can be used as the
794 .I val3
795 argument for
796 .B FUTEX_WAIT_BITSET
798 .BR FUTEX_WAKE_BITSET .
799 Other than differences in the handling of the
800 .I timeout
801 argument, the
802 .B FUTEX_WAIT
803 operation is equivalent to
804 .B FUTEX_WAIT_BITSET
805 with
806 .I val3
807 specified as
808 .BR FUTEX_BITSET_MATCH_ANY ;
809 that is, allow a wake-up by any waker.
811 .B FUTEX_WAKE
812 operation is equivalent to
813 .B FUTEX_WAKE_BITSET
814 with
815 .I val3
816 specified as
817 .BR FUTEX_BITSET_MATCH_ANY ;
818 that is, wake up any waiter(s).
821 .I uaddr2
823 .I timeout
824 arguments are ignored.
826 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
828 .SS Priority-inheritance futexes
829 Linux supports priority-inheritance (PI) futexes in order to handle
830 priority-inversion problems that can be encountered with
831 normal futex locks.
832 Priority inversion is the problem that occurs when a high-priority
833 task is blocked waiting to acquire a lock held by a low-priority task,
834 while tasks at an intermediate priority continuously preempt
835 the low-priority task from the CPU.
836 Consequently, the low-priority task makes no progress toward
837 releasing the lock, and the high-priority task remains blocked.
839 Priority inheritance is a mechanism for dealing with
840 the priority-inversion problem.
841 With this mechanism, when a high-priority task becomes blocked
842 by a lock held by a low-priority task,
843 the priority of the low-priority task is temporarily raised
844 to that of the high-priority task,
845 so that it is not preempted by any intermediate level tasks,
846 and can thus make progress toward releasing the lock.
847 To be effective, priority inheritance must be transitive,
848 meaning that if a high-priority task blocks on a lock
849 held by a lower-priority task that is itself blocked by a lock
850 held by another intermediate-priority task
851 (and so on, for chains of arbitrary length),
852 then both of those tasks
853 (or more generally, all of the tasks in a lock chain)
854 have their priorities raised to be the same as the high-priority task.
856 From a user-space perspective,
857 what makes a futex PI-aware is a policy agreement (described below)
858 between user space and the kernel about the value of the futex word,
859 coupled with the use of the PI-futex operations described below.
860 (Unlike the other futex operations described above,
861 the PI-futex operations are designed
862 for the implementation of very specific IPC mechanisms.)
864 .\" Quoting Darren Hart:
865 .\"     These opcodes paired with the PI futex value policy (described below)
866 .\"     defines a "futex" as PI aware. These were created very specifically
867 .\"     in support of PI pthread_mutexes, so it makes a lot more sense to
868 .\"     talk about a PI aware pthread_mutex, than a PI aware futex, since
869 .\"     there is a lot of policy and scaffolding that has to be built up
870 .\"     around it to use it properly (this is what a PI pthread_mutex is).
872 .\"       mtk: The following text is drawn from the Hart/Guniguntala paper
873 .\"       (listed in SEE ALSO), but I have reworded some pieces
874 .\"       significantly.
876 The PI-futex operations described below differ from the other
877 futex operations in that they impose policy on the use of the value of the
878 futex word:
879 .IP \[bu] 3
880 If the lock is not acquired, the futex word's value shall be 0.
881 .IP \[bu]
882 If the lock is acquired, the futex word's value shall
883 be the thread ID (TID;
885 .BR gettid (2))
886 of the owning thread.
887 .IP \[bu]
888 If the lock is owned and there are threads contending for the lock,
889 then the
890 .B FUTEX_WAITERS
891 bit shall be set in the futex word's value; in other words, this value is:
893 .in +4n
895 FUTEX_WAITERS | TID
899 (Note that is invalid for a PI futex word to have no owner and
900 .B FUTEX_WAITERS
901 set.)
903 With this policy in place,
904 a user-space application can acquire an unacquired
905 lock or release a lock using atomic instructions executed in user mode
906 (e.g., a compare-and-swap operation such as
907 .I cmpxchg
908 on the x86 architecture).
909 Acquiring a lock simply consists of using compare-and-swap to atomically
910 set the futex word's value to the caller's TID if its previous value was 0.
911 Releasing a lock requires using compare-and-swap to set the futex word's
912 value to 0 if the previous value was the expected TID.
914 If a futex is already acquired (i.e., has a nonzero value),
915 waiters must employ the
916 .B FUTEX_LOCK_PI
918 .B FUTEX_LOCK_PI2
919 operations to acquire the lock.
920 If other threads are waiting for the lock, then the
921 .B FUTEX_WAITERS
922 bit is set in the futex value;
923 in this case, the lock owner must employ the
924 .B FUTEX_UNLOCK_PI
925 operation to release the lock.
927 In the cases where callers are forced into the kernel
928 (i.e., required to perform a
929 .BR futex ()
930 call),
931 they then deal directly with a so-called RT-mutex,
932 a kernel locking mechanism which implements the required
933 priority-inheritance semantics.
934 After the RT-mutex is acquired, the futex value is updated accordingly,
935 before the calling thread returns to user space.
937 It is important to note
938 .\" tglx (July 2015):
939 .\"     If there are multiple waiters on a pi futex then a wake pi operation
940 .\"     will wake the first waiter and hand over the lock to this waiter. This
941 .\"     includes handing over the rtmutex which represents the futex in the
942 .\"     kernel. The strict requirement is that the futex owner and the rtmutex
943 .\"     owner must be the same, except for the update period which is
944 .\"     serialized by the futex internal locking. That means the kernel must
945 .\"     update the user-space value prior to returning to user space
946 that the kernel will update the futex word's value prior
947 to returning to user space.
948 (This prevents the possibility of the futex word's value ending
949 up in an invalid state, such as having an owner but the value being 0,
950 or having waiters but not having the
951 .B FUTEX_WAITERS
952 bit set.)
954 If a futex has an associated RT-mutex in the kernel
955 (i.e., there are blocked waiters)
956 and the owner of the futex/RT-mutex dies unexpectedly,
957 then the kernel cleans up the RT-mutex and hands it over to the next waiter.
958 This in turn requires that the user-space value is updated accordingly.
959 To indicate that this is required, the kernel sets the
960 .B FUTEX_OWNER_DIED
961 bit in the futex word along with the thread ID of the new owner.
962 User space can detect this situation via the presence of the
963 .B FUTEX_OWNER_DIED
964 bit and is then responsible for cleaning up the stale state left over by
965 the dead owner.
966 .\" tglx (July 2015):
967 .\"     The FUTEX_OWNER_DIED bit can also be set on uncontended futexes, where
968 .\"     the kernel has no state associated. This happens via the robust futex
969 .\"     mechanism. In that case the futex value will be set to
970 .\"     FUTEX_OWNER_DIED. The robust futex mechanism is also available for non
971 .\"     PI futexes.
973 PI futexes are operated on by specifying one of the values listed below in
974 .IR futex_op .
975 Note that the PI futex operations must be used as paired operations
976 and are subject to some additional requirements:
977 .IP \[bu] 3
978 .BR FUTEX_LOCK_PI ,
979 .BR FUTEX_LOCK_PI2 ,
981 .B FUTEX_TRYLOCK_PI
982 pair with
983 .BR FUTEX_UNLOCK_PI .
984 .B FUTEX_UNLOCK_PI
985 must be called only on a futex owned by the calling thread,
986 as defined by the value policy, otherwise the error
987 .B EPERM
988 results.
989 .IP \[bu]
990 .B FUTEX_WAIT_REQUEUE_PI
991 pairs with
992 .BR FUTEX_CMP_REQUEUE_PI .
993 This must be performed from a non-PI futex to a distinct PI futex
994 (or the error
995 .B EINVAL
996 results).
997 Additionally,
998 .I val
999 (the number of waiters to be woken) must be 1
1000 (or the error
1001 .B EINVAL
1002 results).
1004 The PI futex operations are as follows:
1006 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
1009 .BR FUTEX_LOCK_PI " (since Linux 2.6.18)"
1010 .\" commit c87e2837be82df479a6bae9f155c43516d2feebc
1011 This operation is used after an attempt to acquire
1012 the lock via an atomic user-mode instruction failed
1013 because the futex word has a nonzero value\[em]specifically,
1014 because it contained the (PID-namespace-specific) TID of the lock owner.
1016 The operation checks the value of the futex word at the address
1017 .IR uaddr .
1018 If the value is 0, then the kernel tries to atomically set
1019 the futex value to the caller's TID.
1020 If the futex word's value is nonzero,
1021 the kernel atomically sets the
1022 .B FUTEX_WAITERS
1023 bit, which signals the futex owner that it cannot unlock the futex in
1024 user space atomically by setting the futex value to 0.
1025 .\" tglx (July 2015):
1026 .\"     The operation here is similar to the FUTEX_WAIT logic. When the user
1027 .\"     space atomic acquire does not succeed because the futex value was non
1028 .\"     zero, then the waiter goes into the kernel, takes the kernel internal
1029 .\"     lock and retries the acquisition under the lock. If the acquisition
1030 .\"     does not succeed either, then it sets the FUTEX_WAITERS bit, to signal
1031 .\"     the lock owner that it needs to go into the kernel. Here is the pseudo
1032 .\"     code:
1034 .\"             lock(kernel_lock);
1035 .\"     retry:
1037 .\"             /*
1038 .\"              * Owner might have unlocked in user space before we
1039 .\"              * were able to set the waiter bit.
1040 .\"              */
1041 .\"             if (atomic_acquire(futex) == SUCCESS) {
1042 .\"                unlock(kernel_lock());
1043 .\"                return 0;
1044 .\"             }
1046 .\"             /*
1047 .\"              * Owner might have unlocked after the above atomic_acquire()
1048 .\"              * attempt.
1049 .\"              */
1050 .\"             if (atomic_set_waiters_bit(futex) != SUCCESS)
1051 .\"                goto retry;
1053 .\"             queue_waiter();
1054 .\"             unlock(kernel_lock);
1055 .\"             block();
1057 After that, the kernel:
1059 .IP (1) 5
1060 Tries to find the thread which is associated with the owner TID.
1061 .IP (2)
1062 Creates or reuses kernel state on behalf of the owner.
1063 (If this is the first waiter, there is no kernel state for this
1064 futex, so kernel state is created by locking the RT-mutex
1065 and the futex owner is made the owner of the RT-mutex.
1066 If there are existing waiters, then the existing state is reused.)
1067 .IP (3)
1068 Attaches the waiter to the futex
1069 (i.e., the waiter is enqueued on the RT-mutex waiter list).
1072 If more than one waiter exists,
1073 the enqueueing of the waiter is in descending priority order.
1074 (For information on priority ordering, see the discussion of the
1075 .BR SCHED_DEADLINE ,
1076 .BR SCHED_FIFO ,
1078 .B SCHED_RR
1079 scheduling policies in
1080 .BR sched (7).)
1081 The owner inherits either the waiter's CPU bandwidth
1082 (if the waiter is scheduled under the
1083 .B SCHED_DEADLINE
1084 policy) or the waiter's priority (if the waiter is scheduled under the
1085 .B SCHED_RR
1087 .B SCHED_FIFO
1088 policy).
1089 .\" August 2015:
1090 .\"     mtk: If the realm is restricted purely to SCHED_OTHER (SCHED_NORMAL)
1091 .\"          processes, does the nice value come into play also?
1093 .\"     tglx: No. SCHED_OTHER/NORMAL tasks are handled in FIFO order
1094 This inheritance follows the lock chain in the case of nested locking
1095 .\" (i.e., task 1 blocks on lock A, held by task 2,
1096 .\" while task 2 blocks on lock B, held by task 3)
1097 and performs deadlock detection.
1100 .I timeout
1101 argument provides a timeout for the lock attempt.
1103 .I timeout
1104 is not NULL, the structure it points to specifies
1105 an absolute timeout, measured against the
1106 .B CLOCK_REALTIME
1107 clock.
1108 .\" 2016-07-07 response from Thomas Gleixner on LKML:
1109 .\" From: Thomas Gleixner <tglx@linutronix.de>
1110 .\" Date: 6 July 2016 at 20:57
1111 .\" Subject: Re: futex: Allow FUTEX_CLOCK_REALTIME with FUTEX_WAIT op
1113 .\" On Thu, 23 Jun 2016, Michael Kerrisk (man-pages) wrote:
1114 .\" > On 06/23/2016 08:28 PM, Darren Hart wrote:
1115 .\" > > And as a follow-on, what is the reason for FUTEX_LOCK_PI only using
1116 .\" > > CLOCK_REALTIME? It seems reasonable to me that a user may want to wait a
1117 .\" > > specific amount of time, regardless of wall time.
1118 .\" >
1119 .\" > Yes, that's another weird inconsistency.
1121 .\" The reason is that phtread_mutex_timedlock() uses absolute timeouts based on
1122 .\" CLOCK_REALTIME. glibc folks asked to make that the default behaviour back
1123 .\" then when we added LOCK_PI.
1125 .I timeout
1126 is NULL, the operation will block indefinitely.
1129 .IR uaddr2 ,
1130 .IR val ,
1132 .I val3
1133 arguments are ignored.
1135 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
1138 .BR FUTEX_LOCK_PI2 " (since Linux 5.14)"
1139 .\" commit bf22a6976897977b0a3f1aeba6823c959fc4fdae
1140 This operation is the same as
1141 .BR FUTEX_LOCK_PI ,
1142 except that the clock against which
1143 .I timeout
1144 is measured is selectable.
1145 By default, the (absolute) timeout specified in
1146 .I timeout
1147 is measured against the
1148 .B CLOCK_MONOTONIC
1149 clock, but if the
1150 .B FUTEX_CLOCK_REALTIME
1151 flag is specified in
1152 .IR futex_op ,
1153 then the timeout is measured against the
1154 .B CLOCK_REALTIME
1155 clock.
1157 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
1160 .BR FUTEX_TRYLOCK_PI " (since Linux 2.6.18)"
1161 .\" commit c87e2837be82df479a6bae9f155c43516d2feebc
1162 This operation tries to acquire the lock at
1163 .IR uaddr .
1164 It is invoked when a user-space atomic acquire did not
1165 succeed because the futex word was not 0.
1167 Because the kernel has access to more state information than user space,
1168 acquisition of the lock might succeed if performed by the
1169 kernel in cases where the futex word
1170 (i.e., the state information accessible to use-space) contains stale state
1171 .RB ( FUTEX_WAITERS
1172 and/or
1173 .BR FUTEX_OWNER_DIED ).
1174 This can happen when the owner of the futex died.
1175 User space cannot handle this condition in a race-free manner,
1176 but the kernel can fix this up and acquire the futex.
1177 .\" Paraphrasing a f2f conversation with Thomas Gleixner about the
1178 .\" above point (Aug 2015): ###
1179 .\"     There is a rare possibility of a race condition involving an
1180 .\"     uncontended futex with no owner, but with waiters.  The
1181 .\"     kernel-user-space contract is that if a futex is nonzero, you must
1182 .\"     go into kernel.  The futex was owned by a task, and that task dies
1183 .\"     but there are no waiters, so the futex value is non zero.
1184 .\"     Therefore, the next locker has to go into the kernel,
1185 .\"     so that the kernel has a chance to clean up. (CMXCH on zero
1186 .\"     in user space would fail, so kernel has to clean up.)
1187 .\" Darren Hart (Oct 2015):
1188 .\"     The trylock in the kernel has more state, so it can independently
1189 .\"     verify the flags that user space must trust implicitly.
1192 .IR uaddr2 ,
1193 .IR val ,
1194 .IR timeout ,
1196 .I val3
1197 arguments are ignored.
1199 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
1202 .BR FUTEX_UNLOCK_PI " (since Linux 2.6.18)"
1203 .\" commit c87e2837be82df479a6bae9f155c43516d2feebc
1204 This operation wakes the top priority waiter that is waiting in
1205 .B FUTEX_LOCK_PI
1207 .B FUTEX_LOCK_PI2
1208 on the futex address provided by the
1209 .I uaddr
1210 argument.
1212 This is called when the user-space value at
1213 .I uaddr
1214 cannot be changed atomically from a TID (of the owner) to 0.
1217 .IR uaddr2 ,
1218 .IR val ,
1219 .IR timeout ,
1221 .I val3
1222 arguments are ignored.
1224 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
1227 .BR FUTEX_CMP_REQUEUE_PI " (since Linux 2.6.31)"
1228 .\" commit 52400ba946759af28442dee6265c5c0180ac7122
1229 This operation is a PI-aware variant of
1230 .BR FUTEX_CMP_REQUEUE .
1231 It requeues waiters that are blocked via
1232 .B FUTEX_WAIT_REQUEUE_PI
1234 .I uaddr
1235 from a non-PI source futex
1236 .RI ( uaddr )
1237 to a PI target futex
1238 .RI ( uaddr2 ).
1240 As with
1241 .BR FUTEX_CMP_REQUEUE ,
1242 this operation wakes up a maximum of
1243 .I val
1244 waiters that are waiting on the futex at
1245 .IR uaddr .
1246 However, for
1247 .BR FUTEX_CMP_REQUEUE_PI ,
1248 .I val
1249 is required to be 1
1250 (since the main point is to avoid a thundering herd).
1251 The remaining waiters are removed from the wait queue of the source futex at
1252 .I uaddr
1253 and added to the wait queue of the target futex at
1254 .IR uaddr2 .
1257 .I val2
1258 .\" val2 is the cap on the number of requeued waiters.
1259 .\" In the glibc pthread_cond_broadcast() implementation, this argument
1260 .\" is specified as INT_MAX, and for pthread_cond_signal() it is 0.
1262 .I val3
1263 arguments serve the same purposes as for
1264 .BR FUTEX_CMP_REQUEUE .
1266 .\"       The page at http://locklessinc.com/articles/futex_cheat_sheet/
1267 .\"       notes that "priority-inheritance Futex to priority-inheritance
1268 .\"       Futex requeues are currently unsupported". However, probably
1269 .\"       the page does not need to say nothing about this, since
1270 .\"       Thomas Gleixner commented (July 2015): "they never will be
1271 .\"       supported because they make no sense at all"
1273 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
1276 .BR FUTEX_WAIT_REQUEUE_PI " (since Linux 2.6.31)"
1277 .\" commit 52400ba946759af28442dee6265c5c0180ac7122
1279 Wait on a non-PI futex at
1280 .I uaddr
1281 and potentially be requeued (via a
1282 .B FUTEX_CMP_REQUEUE_PI
1283 operation in another task) onto a PI futex at
1284 .IR uaddr2 .
1285 The wait operation on
1286 .I uaddr
1287 is the same as for
1288 .BR FUTEX_WAIT .
1290 The waiter can be removed from the wait on
1291 .I uaddr
1292 without requeueing on
1293 .I uaddr2
1294 via a
1295 .B FUTEX_WAKE
1296 operation in another task.
1297 In this case, the
1298 .B FUTEX_WAIT_REQUEUE_PI
1299 operation fails with the error
1300 .BR EAGAIN .
1303 .I timeout
1304 is not NULL, the structure it points to specifies
1305 an absolute timeout for the wait operation.
1307 .I timeout
1308 is NULL, the operation can block indefinitely.
1311 .I val3
1312 argument is ignored.
1315 .B FUTEX_WAIT_REQUEUE_PI
1317 .B FUTEX_CMP_REQUEUE_PI
1318 were added to support a fairly specific use case:
1319 support for priority-inheritance-aware POSIX threads condition variables.
1320 The idea is that these operations should always be paired,
1321 in order to ensure that user space and the kernel remain in sync.
1322 Thus, in the
1323 .B FUTEX_WAIT_REQUEUE_PI
1324 operation, the user-space application pre-specifies the target
1325 of the requeue that takes place in the
1326 .B FUTEX_CMP_REQUEUE_PI
1327 operation.
1329 .\" Darren Hart notes that a patch to allow glibc to fully support
1330 .\" PI-aware pthreads condition variables has not yet been accepted into
1331 .\" glibc. The story is complex, and can be found at
1332 .\" https://sourceware.org/bugzilla/show_bug.cgi?id=11588
1333 .\" Darren notes that in the meantime, the patch is shipped with various
1334 .\" PREEMPT_RT-enabled Linux systems.
1336 .\" Related to the preceding, Darren proposed that somewhere, man-pages
1337 .\" should document the following point:
1339 .\"     While the Linux kernel, since Linux 2.6.31, supports requeueing of
1340 .\"     priority-inheritance (PI) aware mutexes via the
1341 .\"     FUTEX_WAIT_REQUEUE_PI and FUTEX_CMP_REQUEUE_PI futex operations,
1342 .\"     the glibc implementation does not yet take full advantage of this.
1343 .\"     Specifically, the condvar internal data lock remains a non-PI aware
1344 .\"     mutex, regardless of the type of the pthread_mutex associated with
1345 .\"     the condvar. This can lead to an unbounded priority inversion on
1346 .\"     the internal data lock even when associating a PI aware
1347 .\"     pthread_mutex with a condvar during a pthread_cond*_wait
1348 .\"     operation. For this reason, it is not recommended to rely on
1349 .\"     priority inheritance when using pthread condition variables.
1351 .\" The problem is that the obvious location for this text is
1352 .\" the pthread_cond*wait(3) man page. However, such a man page
1353 .\" does not currently exist.
1355 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
1357 .SH RETURN VALUE
1358 In the event of an error (and assuming that
1359 .BR futex ()
1360 was invoked via
1361 .BR syscall (2)),
1362 all operations return \-1 and set
1363 .I errno
1364 to indicate the error.
1366 The return value on success depends on the operation,
1367 as described in the following list:
1369 .B FUTEX_WAIT
1370 Returns 0 if the caller was woken up.
1371 Note that a wake-up can also be caused by common futex usage patterns
1372 in unrelated code that happened to have previously used the futex word's
1373 memory location (e.g., typical futex-based implementations of
1374 Pthreads mutexes can cause this under some conditions).
1375 Therefore, callers should always conservatively assume that a return
1376 value of 0 can mean a spurious wake-up, and use the futex word's value
1377 (i.e., the user-space synchronization scheme)
1378 to decide whether to continue to block or not.
1380 .B FUTEX_WAKE
1381 Returns the number of waiters that were woken up.
1383 .B FUTEX_FD
1384 Returns the new file descriptor associated with the futex.
1386 .B FUTEX_REQUEUE
1387 Returns the number of waiters that were woken up.
1389 .B FUTEX_CMP_REQUEUE
1390 Returns the total number of waiters that were woken up or
1391 requeued to the futex for the futex word at
1392 .IR uaddr2 .
1393 If this value is greater than
1394 .IR val ,
1395 then the difference is the number of waiters requeued to the futex for the
1396 futex word at
1397 .IR uaddr2 .
1399 .B FUTEX_WAKE_OP
1400 Returns the total number of waiters that were woken up.
1401 This is the sum of the woken waiters on the two futexes for
1402 the futex words at
1403 .I uaddr
1405 .IR uaddr2 .
1407 .B FUTEX_WAIT_BITSET
1408 Returns 0 if the caller was woken up.
1410 .B FUTEX_WAIT
1411 for how to interpret this correctly in practice.
1413 .B FUTEX_WAKE_BITSET
1414 Returns the number of waiters that were woken up.
1416 .B FUTEX_LOCK_PI
1417 Returns 0 if the futex was successfully locked.
1419 .B FUTEX_LOCK_PI2
1420 Returns 0 if the futex was successfully locked.
1422 .B FUTEX_TRYLOCK_PI
1423 Returns 0 if the futex was successfully locked.
1425 .B FUTEX_UNLOCK_PI
1426 Returns 0 if the futex was successfully unlocked.
1428 .B FUTEX_CMP_REQUEUE_PI
1429 Returns the total number of waiters that were woken up or
1430 requeued to the futex for the futex word at
1431 .IR uaddr2 .
1432 If this value is greater than
1433 .IR val ,
1434 then difference is the number of waiters requeued to the futex for
1435 the futex word at
1436 .IR uaddr2 .
1438 .B FUTEX_WAIT_REQUEUE_PI
1439 Returns 0 if the caller was successfully requeued to the futex for
1440 the futex word at
1441 .IR uaddr2 .
1443 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
1445 .SH ERRORS
1447 .B EACCES
1448 No read access to the memory of a futex word.
1450 .B EAGAIN
1451 .RB ( FUTEX_WAIT ,
1452 .BR FUTEX_WAIT_BITSET ,
1453 .BR FUTEX_WAIT_REQUEUE_PI )
1454 The value pointed to by
1455 .I uaddr
1456 was not equal to the expected value
1457 .I val
1458 at the time of the call.
1460 .BR Note :
1461 on Linux, the symbolic names
1462 .B EAGAIN
1464 .B EWOULDBLOCK
1465 (both of which appear in different parts of the kernel futex code)
1466 have the same value.
1468 .B EAGAIN
1469 .RB ( FUTEX_CMP_REQUEUE ,
1470 .BR FUTEX_CMP_REQUEUE_PI )
1471 The value pointed to by
1472 .I uaddr
1473 is not equal to the expected value
1474 .IR val3 .
1476 .B EAGAIN
1477 .RB ( FUTEX_LOCK_PI ,
1478 .BR FUTEX_LOCK_PI2 ,
1479 .BR FUTEX_TRYLOCK_PI ,
1480 .BR FUTEX_CMP_REQUEUE_PI )
1481 The futex owner thread ID of
1482 .I uaddr
1483 (for
1484 .BR FUTEX_CMP_REQUEUE_PI :
1485 .IR uaddr2 )
1486 is about to exit,
1487 but has not yet handled the internal state cleanup.
1488 Try again.
1490 .B EDEADLK
1491 .RB ( FUTEX_LOCK_PI ,
1492 .BR FUTEX_LOCK_PI2 ,
1493 .BR FUTEX_TRYLOCK_PI ,
1494 .BR FUTEX_CMP_REQUEUE_PI )
1495 The futex word at
1496 .I uaddr
1497 is already locked by the caller.
1499 .B EDEADLK
1500 .\" FIXME . I see that kernel/locking/rtmutex.c uses EDEADLK in some
1501 .\"       places, and EDEADLOCK in others. On almost all architectures
1502 .\"       these constants are synonymous. Is there a reason that both
1503 .\"       names are used?
1505 .\"       tglx (July 2015): "No. We should probably fix that."
1507 .RB ( FUTEX_CMP_REQUEUE_PI )
1508 While requeueing a waiter to the PI futex for the futex word at
1509 .IR uaddr2 ,
1510 the kernel detected a deadlock.
1512 .B EFAULT
1513 A required pointer argument (i.e.,
1514 .IR uaddr ,
1515 .IR uaddr2 ,
1517 .IR timeout )
1518 did not point to a valid user-space address.
1520 .B EINTR
1522 .B FUTEX_WAIT
1524 .B FUTEX_WAIT_BITSET
1525 operation was interrupted by a signal (see
1526 .BR signal (7)).
1527 Before Linux 2.6.22, this error could also be returned for
1528 a spurious wakeup; since Linux 2.6.22, this no longer happens.
1530 .B EINVAL
1531 The operation in
1532 .I futex_op
1533 is one of those that employs a timeout, but the supplied
1534 .I timeout
1535 argument was invalid
1536 .RI ( tv_sec
1537 was less than zero, or
1538 .I tv_nsec
1539 was not less than 1,000,000,000).
1541 .B EINVAL
1542 The operation specified in
1543 .I futex_op
1544 employs one or both of the pointers
1545 .I uaddr
1547 .IR uaddr2 ,
1548 but one of these does not point to a valid object\[em]that is,
1549 the address is not four-byte-aligned.
1551 .B EINVAL
1552 .RB ( FUTEX_WAIT_BITSET ,
1553 .BR FUTEX_WAKE_BITSET )
1554 The bit mask supplied in
1555 .I val3
1556 is zero.
1558 .B EINVAL
1559 .RB ( FUTEX_CMP_REQUEUE_PI )
1560 .I uaddr
1561 equals
1562 .I uaddr2
1563 (i.e., an attempt was made to requeue to the same futex).
1565 .B EINVAL
1566 .RB ( FUTEX_FD )
1567 The signal number supplied in
1568 .I val
1569 is invalid.
1571 .B EINVAL
1572 .RB ( FUTEX_WAKE ,
1573 .BR FUTEX_WAKE_OP ,
1574 .BR FUTEX_WAKE_BITSET ,
1575 .BR FUTEX_REQUEUE ,
1576 .BR FUTEX_CMP_REQUEUE )
1577 The kernel detected an inconsistency between the user-space state at
1578 .I uaddr
1579 and the kernel state\[em]that is, it detected a waiter which waits in
1580 .B FUTEX_LOCK_PI
1582 .B FUTEX_LOCK_PI2
1584 .IR uaddr .
1586 .B EINVAL
1587 .RB ( FUTEX_LOCK_PI ,
1588 .BR FUTEX_LOCK_PI2 ,
1589 .BR FUTEX_TRYLOCK_PI ,
1590 .BR FUTEX_UNLOCK_PI )
1591 The kernel detected an inconsistency between the user-space state at
1592 .I uaddr
1593 and the kernel state.
1594 This indicates either state corruption
1595 or that the kernel found a waiter on
1596 .I uaddr
1597 which is waiting via
1598 .B FUTEX_WAIT
1600 .BR FUTEX_WAIT_BITSET .
1602 .B EINVAL
1603 .RB ( FUTEX_CMP_REQUEUE_PI )
1604 The kernel detected an inconsistency between the user-space state at
1605 .I uaddr2
1606 and the kernel state;
1607 .\" From a conversation with Thomas Gleixner (Aug 2015): ###
1608 .\"     The kernel sees: I have non PI state for a futex you tried to
1609 .\"     tell me was PI
1610 that is, the kernel detected a waiter which waits via
1611 .B FUTEX_WAIT
1613 .B FUTEX_WAIT_BITSET
1615 .IR uaddr2 .
1617 .B EINVAL
1618 .RB ( FUTEX_CMP_REQUEUE_PI )
1619 The kernel detected an inconsistency between the user-space state at
1620 .I uaddr
1621 and the kernel state;
1622 that is, the kernel detected a waiter which waits via
1623 .B FUTEX_WAIT
1625 .B FUTEX_WAIT_BITSET
1627 .IR uaddr .
1629 .B EINVAL
1630 .RB ( FUTEX_CMP_REQUEUE_PI )
1631 The kernel detected an inconsistency between the user-space state at
1632 .I uaddr
1633 and the kernel state;
1634 that is, the kernel detected a waiter which waits on
1635 .I uaddr
1637 .B FUTEX_LOCK_PI
1639 .B FUTEX_LOCK_PI2
1640 (instead of
1641 .BR FUTEX_WAIT_REQUEUE_PI ).
1643 .B EINVAL
1644 .RB ( FUTEX_CMP_REQUEUE_PI )
1645 .\" This deals with the case:
1646 .\"     wait_requeue_pi(A, B);
1647 .\"     requeue_pi(A, C);
1648 An attempt was made to requeue a waiter to a futex other than that
1649 specified by the matching
1650 .B FUTEX_WAIT_REQUEUE_PI
1651 call for that waiter.
1653 .B EINVAL
1654 .RB ( FUTEX_CMP_REQUEUE_PI )
1656 .I val
1657 argument is not 1.
1659 .B EINVAL
1660 Invalid argument.
1662 .B ENFILE
1663 .RB ( FUTEX_FD )
1664 The system-wide limit on the total number of open files has been reached.
1666 .B ENOMEM
1667 .RB ( FUTEX_LOCK_PI ,
1668 .BR FUTEX_LOCK_PI2 ,
1669 .BR FUTEX_TRYLOCK_PI ,
1670 .BR FUTEX_CMP_REQUEUE_PI )
1671 The kernel could not allocate memory to hold state information.
1673 .B ENOSYS
1674 Invalid operation specified in
1675 .IR futex_op .
1677 .B ENOSYS
1679 .B FUTEX_CLOCK_REALTIME
1680 option was specified in
1681 .IR futex_op ,
1682 but the accompanying operation was neither
1683 .BR FUTEX_WAIT ,
1684 .BR FUTEX_WAIT_BITSET ,
1685 .BR FUTEX_WAIT_REQUEUE_PI ,
1687 .BR FUTEX_LOCK_PI2 .
1689 .B ENOSYS
1690 .RB ( FUTEX_LOCK_PI ,
1691 .BR FUTEX_LOCK_PI2 ,
1692 .BR FUTEX_TRYLOCK_PI ,
1693 .BR FUTEX_UNLOCK_PI ,
1694 .BR FUTEX_CMP_REQUEUE_PI ,
1695 .BR FUTEX_WAIT_REQUEUE_PI )
1696 A run-time check determined that the operation is not available.
1697 The PI-futex operations are not implemented on all architectures and
1698 are not supported on some CPU variants.
1700 .B EPERM
1701 .RB ( FUTEX_LOCK_PI ,
1702 .BR FUTEX_LOCK_PI2 ,
1703 .BR FUTEX_TRYLOCK_PI ,
1704 .BR FUTEX_CMP_REQUEUE_PI )
1705 The caller is not allowed to attach itself to the futex at
1706 .I uaddr
1707 (for
1708 .BR FUTEX_CMP_REQUEUE_PI :
1709 the futex at
1710 .IR uaddr2 ).
1711 (This may be caused by a state corruption in user space.)
1713 .B EPERM
1714 .RB ( FUTEX_UNLOCK_PI )
1715 The caller does not own the lock represented by the futex word.
1717 .B ESRCH
1718 .RB ( FUTEX_LOCK_PI ,
1719 .BR FUTEX_LOCK_PI2 ,
1720 .BR FUTEX_TRYLOCK_PI ,
1721 .BR FUTEX_CMP_REQUEUE_PI )
1722 The thread ID in the futex word at
1723 .I uaddr
1724 does not exist.
1726 .B ESRCH
1727 .RB ( FUTEX_CMP_REQUEUE_PI )
1728 The thread ID in the futex word at
1729 .I uaddr2
1730 does not exist.
1732 .B ETIMEDOUT
1733 The operation in
1734 .I futex_op
1735 employed the timeout specified in
1736 .IR timeout ,
1737 and the timeout expired before the operation completed.
1739 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
1741 .SH VERSIONS
1742 Futexes were first made available in a stable kernel release
1743 with Linux 2.6.0.
1745 Initial futex support was merged in Linux 2.5.7 but with different
1746 semantics from what was described above.
1747 A four-argument system call with the semantics
1748 described in this page was introduced in Linux 2.5.40.
1749 A fifth argument was added in Linux 2.5.70,
1750 and a sixth argument was added in Linux 2.6.7.
1751 .SH STANDARDS
1752 This system call is Linux-specific.
1753 .SH NOTES
1754 Several higher-level programming abstractions are implemented via futexes,
1755 including POSIX semaphores and
1756 various POSIX threads synchronization mechanisms
1757 (mutexes, condition variables, read-write locks, and barriers).
1758 .\" TODO FIXME(Torvald) Above, we cite this section and claim it contains
1759 .\" details on the synchronization semantics; add the C11 equivalents
1760 .\" here (or whatever we find consensus for).
1762 .\""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
1764 .SH EXAMPLES
1765 The program below demonstrates use of futexes in a program where a parent
1766 process and a child process use a pair of futexes located inside a
1767 shared anonymous mapping to synchronize access to a shared resource:
1768 the terminal.
1769 The two processes each write
1770 .I nloops
1771 (a command-line argument that defaults to 5 if omitted)
1772 messages to the terminal and employ a synchronization protocol
1773 that ensures that they alternate in writing messages.
1774 Upon running this program we see output such as the following:
1776 .in +4n
1778 $ \fB./futex_demo\fP
1779 Parent (18534) 0
1780 Child  (18535) 0
1781 Parent (18534) 1
1782 Child  (18535) 1
1783 Parent (18534) 2
1784 Child  (18535) 2
1785 Parent (18534) 3
1786 Child  (18535) 3
1787 Parent (18534) 4
1788 Child  (18535) 4
1791 .SS Program source
1793 .\" SRC BEGIN (futex.c)
1795 /* futex_demo.c
1797    Usage: futex_demo [nloops]
1798                     (Default: 5)
1800    Demonstrate the use of futexes in a program where parent and child
1801    use a pair of futexes located inside a shared anonymous mapping to
1802    synchronize access to a shared resource: the terminal. The two
1803    processes each write \[aq]num\-loops\[aq] messages to the terminal and employ
1804    a synchronization protocol that ensures that they alternate in
1805    writing messages.
1807 #define _GNU_SOURCE
1808 #include <err.h>
1809 #include <errno.h>
1810 #include <linux/futex.h>
1811 #include <stdatomic.h>
1812 #include <stdint.h>
1813 #include <stdio.h>
1814 #include <stdlib.h>
1815 #include <sys/mman.h>
1816 #include <sys/syscall.h>
1817 #include <sys/time.h>
1818 #include <sys/wait.h>
1819 #include <unistd.h>
1821 static uint32_t *futex1, *futex2, *iaddr;
1823 static int
1824 futex(uint32_t *uaddr, int futex_op, uint32_t val,
1825       const struct timespec *timeout, uint32_t *uaddr2, uint32_t val3)
1827     return syscall(SYS_futex, uaddr, futex_op, val,
1828                    timeout, uaddr2, val3);
1831 /* Acquire the futex pointed to by \[aq]futexp\[aq]: wait for its value to
1832    become 1, and then set the value to 0. */
1834 static void
1835 fwait(uint32_t *futexp)
1837     long            s;
1838     const uint32_t  one = 1;
1840     /* atomic_compare_exchange_strong(ptr, oldval, newval)
1841        atomically performs the equivalent of:
1843            if (*ptr == *oldval)
1844                *ptr = newval;
1846        It returns true if the test yielded true and *ptr was updated. */
1848     while (1) {
1850         /* Is the futex available? */
1851         if (atomic_compare_exchange_strong(futexp, &one, 0))
1852             break;      /* Yes */
1854         /* Futex is not available; wait. */
1856         s = futex(futexp, FUTEX_WAIT, 0, NULL, NULL, 0);
1857         if (s == \-1 && errno != EAGAIN)
1858             err(EXIT_FAILURE, "futex\-FUTEX_WAIT");
1859     }
1862 /* Release the futex pointed to by \[aq]futexp\[aq]: if the futex currently
1863    has the value 0, set its value to 1 and then wake any futex waiters,
1864    so that if the peer is blocked in fwait(), it can proceed. */
1866 static void
1867 fpost(uint32_t *futexp)
1869     long            s;
1870     const uint32_t  zero = 0;
1872     /* atomic_compare_exchange_strong() was described
1873        in comments above. */
1875     if (atomic_compare_exchange_strong(futexp, &zero, 1)) {
1876         s = futex(futexp, FUTEX_WAKE, 1, NULL, NULL, 0);
1877         if (s  == \-1)
1878             err(EXIT_FAILURE, "futex\-FUTEX_WAKE");
1879     }
1883 main(int argc, char *argv[])
1885     pid_t         childPid;
1886     unsigned int  nloops;
1888     setbuf(stdout, NULL);
1890     nloops = (argc > 1) ? atoi(argv[1]) : 5;
1892     /* Create a shared anonymous mapping that will hold the futexes.
1893        Since the futexes are being shared between processes, we
1894        subsequently use the "shared" futex operations (i.e., not the
1895        ones suffixed "_PRIVATE"). */
1897     iaddr = mmap(NULL, sizeof(*iaddr) * 2, PROT_READ | PROT_WRITE,
1898                  MAP_ANONYMOUS | MAP_SHARED, \-1, 0);
1899     if (iaddr == MAP_FAILED)
1900         err(EXIT_FAILURE, "mmap");
1902     futex1 = &iaddr[0];
1903     futex2 = &iaddr[1];
1905     *futex1 = 0;        /* State: unavailable */
1906     *futex2 = 1;        /* State: available */
1908     /* Create a child process that inherits the shared anonymous
1909        mapping. */
1911     childPid = fork();
1912     if (childPid == \-1)
1913         err(EXIT_FAILURE, "fork");
1915     if (childPid == 0) {        /* Child */
1916         for (unsigned int j = 0; j < nloops; j++) {
1917             fwait(futex1);
1918             printf("Child  (%jd) %u\en", (intmax_t) getpid(), j);
1919             fpost(futex2);
1920         }
1922         exit(EXIT_SUCCESS);
1923     }
1925     /* Parent falls through to here. */
1927     for (unsigned int j = 0; j < nloops; j++) {
1928         fwait(futex2);
1929         printf("Parent (%jd) %u\en", (intmax_t) getpid(), j);
1930         fpost(futex1);
1931     }
1933     wait(NULL);
1935     exit(EXIT_SUCCESS);
1938 .\" SRC END
1939 .SH SEE ALSO
1940 .ad l
1941 .BR get_robust_list (2),
1942 .BR restart_syscall (2),
1943 .BR pthread_mutexattr_getprotocol (3),
1944 .BR futex (7),
1945 .BR sched (7)
1947 The following kernel source files:
1948 .IP \[bu] 3
1949 .I Documentation/pi\-futex.txt
1950 .IP \[bu]
1951 .I Documentation/futex\-requeue\-pi.txt
1952 .IP \[bu]
1953 .I Documentation/locking/rt\-mutex.txt
1954 .IP \[bu]
1955 .I Documentation/locking/rt\-mutex\-design.txt
1956 .IP \[bu]
1957 .I Documentation/robust\-futex\-ABI.txt
1959 Franke, H., Russell, R., and Kirwood, M., 2002.
1960 \fIFuss, Futexes and Furwocks: Fast Userlevel Locking in Linux\fP
1961 (from proceedings of the Ottawa Linux Symposium 2002),
1963 .UR http://kernel.org\:/doc\:/ols\:/2002\:/ols2002\-pages\-479\-495.pdf
1966 Hart, D., 2009. \fIA futex overview and update\fP,
1967 .UR http://lwn.net/Articles/360699/
1970 Hart, D.\& and Guniguntala, D., 2009.
1971 \fIRequeue-PI: Making glibc Condvars PI-Aware\fP
1972 (from proceedings of the 2009 Real-Time Linux Workshop),
1973 .UR http://lwn.net/images/conf/rtlws11/papers/proc/p10.pdf
1976 Drepper, U., 2011. \fIFutexes Are Tricky\fP,
1977 .UR http://www.akkadia.org/drepper/futex.pdf
1980 Futex example library, futex-*.tar.bz2 at
1982 .UR https://mirrors.kernel.org\:/pub\:/linux\:/kernel\:/people\:/rusty/
1985 .\" FIXME(Torvald) We should probably refer to the glibc code here, in
1986 .\" particular the glibc-internal futex wrapper functions that are
1987 .\" WIP, and the generic pthread_mutex_t and perhaps condvar
1988 .\" implementations.